summaryrefslogtreecommitdiff
path: root/src/devices/nm-device.c
blob: 8105ae20f2a56351c0c6ddee586969a757f1efd8 (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
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
// SPDX-License-Identifier: GPL-2.0+
/*
 * Copyright (C) 2005 - 2018 Red Hat, Inc.
 * Copyright (C) 2006 - 2008 Novell, Inc.
 */

#include "nm-default.h"

#include "nm-device.h"

#include <netinet/in.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <linux/if_addr.h>
#include <linux/if_arp.h>
#include <linux/rtnetlink.h>

#include "nm-std-aux/unaligned.h"
#include "nm-glib-aux/nm-dedup-multi.h"
#include "nm-glib-aux/nm-random-utils.h"
#include "systemd/nm-sd-utils-shared.h"

#include "nm-libnm-core-intern/nm-ethtool-utils.h"
#include "nm-libnm-core-intern/nm-common-macros.h"
#include "nm-device-private.h"
#include "nm-l3cfg.h"
#include "nm-l3-config-data.h"
#include "NetworkManagerUtils.h"
#include "nm-manager.h"
#include "platform/nm-platform.h"
#include "platform/nm-platform-utils.h"
#include "platform/nmp-object.h"
#include "platform/nmp-rules-manager.h"
#include "ndisc/nm-ndisc.h"
#include "ndisc/nm-lndp-ndisc.h"
#include "dhcp/nm-dhcp-manager.h"
#include "dhcp/nm-dhcp-utils.h"
#include "nm-act-request.h"
#include "nm-proxy-config.h"
#include "nm-ip4-config.h"
#include "nm-ip6-config.h"
#include "nm-pacrunner-manager.h"
#include "dnsmasq/nm-dnsmasq-manager.h"
#include "nm-dhcp-config.h"
#include "nm-rfkill-manager.h"
#include "nm-firewall-manager.h"
#include "settings/nm-settings-connection.h"
#include "settings/nm-settings.h"
#include "nm-setting-ethtool.h"
#include "nm-setting-user.h"
#include "nm-auth-utils.h"
#include "nm-keep-alive.h"
#include "nm-netns.h"
#include "nm-dispatcher.h"
#include "nm-config.h"
#include "c-list/src/c-list.h"
#include "dns/nm-dns-manager.h"
#include "nm-acd-manager.h"
#include "nm-core-internal.h"
#include "systemd/nm-sd.h"
#include "nm-lldp-listener.h"
#include "nm-audit-manager.h"
#include "nm-connectivity.h"
#include "nm-dbus-interface.h"

#include "nm-device-generic.h"
#include "nm-device-vlan.h"
#include "nm-device-vrf.h"
#include "nm-device-wireguard.h"

#include "nm-device-logging.h"
_LOG_DECLARE_SELF (NMDevice);

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

#define DEFAULT_AUTOCONNECT    TRUE

static guint32
dhcp_grace_period_from_timeout (guint32 timeout)
{
#define DHCP_GRACE_PERIOD_MULTIPLIER 2U

	nm_assert (timeout > 0);
	nm_assert (timeout < G_MAXINT32);

	if (timeout < G_MAXUINT32 / DHCP_GRACE_PERIOD_MULTIPLIER)
		return timeout * DHCP_GRACE_PERIOD_MULTIPLIER;

	return G_MAXUINT32;
}

#define CARRIER_WAIT_TIME_MS 6000
#define CARRIER_WAIT_TIME_AFTER_MTU_MS 10000

#define NM_DEVICE_AUTH_RETRIES_UNSET    -1
#define NM_DEVICE_AUTH_RETRIES_INFINITY -2
#define NM_DEVICE_AUTH_RETRIES_DEFAULT  3

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

typedef void (*ActivationHandleFunc) (NMDevice *self);

typedef enum {
	CLEANUP_TYPE_KEEP,
	CLEANUP_TYPE_REMOVED,
	CLEANUP_TYPE_DECONFIGURE,
} CleanupType;

typedef struct {
	CList lst_slave;
	NMDevice *slave;
	gulong watch_id;
	bool slave_is_enslaved;
	bool configure;
} SlaveInfo;

typedef struct {
	NMDevice *device;
	guint idle_add_id;
	int ifindex;
} DeleteOnDeactivateData;

typedef struct {
	NMDevice *device;
	GCancellable *cancellable;
	NMPlatformAsyncCallback callback;
	gpointer callback_data;
	guint num_vfs;
	NMTernary autoprobe;
} SriovOp;

typedef void (*AcdCallback) (NMDevice *, NMIP4Config **, gboolean);

typedef enum {
	/* The various NML3ConfigData types that we track explicitly. Note that
	 * their relative order matters: higher numbers in this enum means more
	 * important (and during merge overwrites other settings). */
	L3_CONFIG_DATA_TYPE_LL_4,
	L3_CONFIG_DATA_TYPE_AC_6,
	L3_CONFIG_DATA_TYPE_DHCP_4,
	L3_CONFIG_DATA_TYPE_DHCP_6,
	L3_CONFIG_DATA_TYPE_DEV_4,
	L3_CONFIG_DATA_TYPE_DEV_6,
	L3_CONFIG_DATA_TYPE_SETTING,
	_L3_CONFIG_DATA_TYPE_NUM,
	_L3_CONFIG_DATA_TYPE_NONE,
} L3ConfigDataType;

typedef struct {
	AcdCallback callback;
	NMDevice *device;
	NMIP4Config **configs;
} AcdData;

typedef enum {
	HW_ADDR_TYPE_UNSET = 0,
	HW_ADDR_TYPE_PERMANENT,
	HW_ADDR_TYPE_EXPLICIT,
	HW_ADDR_TYPE_GENERATED,
} HwAddrType;

typedef enum {
	FIREWALL_STATE_UNMANAGED = 0,
	FIREWALL_STATE_INITIALIZED,
	FIREWALL_STATE_WAIT_STAGE_3,
	FIREWALL_STATE_WAIT_IP_CONFIG,
} FirewallState;

typedef struct {
	NMIPConfig *orig;      /* the original configuration applied to the device */
	NMIPConfig *current;   /* configuration after external changes.  NULL means
	                          that the original configuration didn't change. */
} AppliedConfig;

typedef struct {
	NMDhcpClient *client;
	NMDhcpConfig *config;
	gulong state_sigid;
	guint grace_id;
	bool grace_pending:1;
	bool was_active:1;
} DhcpData;

struct _NMDeviceConnectivityHandle {
	CList concheck_lst;
	NMDevice *self;
	NMDeviceConnectivityCallback callback;
	gpointer user_data;
	NMConnectivityCheckHandle *c_handle;
	guint64 seq;
	bool is_periodic:1;
	bool is_periodic_bump:1;
	bool is_periodic_bump_on_complete:1;
	int addr_family;
};

typedef struct {
	int ifindex;
	NMEthtoolFeatureStates *features;
	NMTernary requested[_NM_ETHTOOL_ID_FEATURE_NUM];
	NMEthtoolCoalesceState *coalesce;
	NMEthtoolRingState *ring;
} EthtoolState;

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

enum {
	STATE_CHANGED,
	AUTOCONNECT_ALLOWED,
	IP4_CONFIG_CHANGED,
	IP6_CONFIG_CHANGED,
	IP6_PREFIX_DELEGATED,
	IP6_SUBNET_NEEDED,
	REMOVED,
	RECHECK_AUTO_ACTIVATE,
	RECHECK_ASSUME,
	LAST_SIGNAL,
};
static guint signals[LAST_SIGNAL] = { 0 };

NM_GOBJECT_PROPERTIES_DEFINE (NMDevice,
	PROP_UDI,
	PROP_PATH,
	PROP_IFACE,
	PROP_IP_IFACE,
	PROP_DRIVER,
	PROP_DRIVER_VERSION,
	PROP_FIRMWARE_VERSION,
	PROP_CAPABILITIES,
	PROP_CARRIER,
	PROP_MTU,
	PROP_IP4_ADDRESS,
	PROP_IP4_CONFIG,
	PROP_DHCP4_CONFIG,
	PROP_IP6_CONFIG,
	PROP_DHCP6_CONFIG,
	PROP_STATE,
	PROP_STATE_REASON,
	PROP_ACTIVE_CONNECTION,
	PROP_DEVICE_TYPE,
	PROP_LINK_TYPE,
	PROP_MANAGED,
	PROP_AUTOCONNECT,
	PROP_FIRMWARE_MISSING,
	PROP_NM_PLUGIN_MISSING,
	PROP_TYPE_DESC,
	PROP_RFKILL_TYPE,
	PROP_IFINDEX,
	PROP_AVAILABLE_CONNECTIONS,
	PROP_PHYSICAL_PORT_ID,
	PROP_MASTER,
	PROP_PARENT,
	PROP_HW_ADDRESS,
	PROP_PERM_HW_ADDRESS,
	PROP_HAS_PENDING_ACTION,
	PROP_METERED,
	PROP_LLDP_NEIGHBORS,
	PROP_REAL,
	PROP_SLAVES,
	PROP_STATISTICS_REFRESH_RATE_MS,
	PROP_STATISTICS_TX_BYTES,
	PROP_STATISTICS_RX_BYTES,
	PROP_IP4_CONNECTIVITY,
	PROP_IP6_CONNECTIVITY,
	PROP_INTERFACE_FLAGS,
);

typedef struct _NMDevicePrivate {
	bool in_state_changed;

	guint device_link_changed_id;
	guint device_ip_link_changed_id;

	NMDeviceState state;
	NMDeviceStateReason state_reason;
	struct {
		guint id;

		/* The @state/@reason is only valid, when @id is set. */
		NMDeviceState state;
		NMDeviceStateReason reason;
	} queued_state;

	union {
		struct {
			guint queued_ip_config_id_6;
			guint queued_ip_config_id_4;
		};
		guint queued_ip_config_id_x[2];
	};

	GSList *pending_actions;
	GSList *dad6_failed_addrs;

	NMDBusTrackObjPath parent_device;

	char *        udi;
	char *        path;

	union {
		const char *const iface;
		char *            iface_;
	};
	union {
		const char *const ip_iface;
		char *            ip_iface_;
	};

	union {
		NML3Cfg *const l3cfg;
		NML3Cfg *l3cfg_;
	};

	union {
		const int ifindex;
		int       ifindex_;
	};
	union {
		const int ip_ifindex;
		int       ip_ifindex_;
	};

	const NML3ConfigData *l3cds[_L3_CONFIG_DATA_TYPE_NUM];

	int parent_ifindex;

	int auth_retries;

	union {
		const guint8 hw_addr_len; /* read-only */
		guint8 hw_addr_len_;
	};

	HwAddrType hw_addr_type:5;

	bool          real:1;

	bool update_ip_config_completed_v4:1;
	bool update_ip_config_completed_v6:1;

	NMDeviceType  type;
	char *        type_desc;
	NMLinkType    link_type;
	NMDeviceCapabilities capabilities;
	char *        driver;
	char *        driver_version;
	char *        firmware_version;
	RfKillType    rfkill_type;
	bool          firmware_missing:1;
	bool          nm_plugin_missing:1;
	bool          hw_addr_perm_fake:1; /* whether the permanent HW address could not be read and is a fake */

	NMUtilsStableType current_stable_id_type:3;

	bool          nm_owned:1; /* whether the device is a device owned and created by NM */

	bool          assume_state_guess_assume:1;
	char *        assume_state_connection_uuid;

	GHashTable *  available_connections;
	char *        hw_addr;
	char *        hw_addr_perm;
	char *        hw_addr_initial;
	char *        physical_port_id;
	guint         dev_id;

	NMUnmanagedFlags        unmanaged_mask;
	NMUnmanagedFlags        unmanaged_flags;
	DeleteOnDeactivateData *delete_on_deactivate_data; /* data for scheduled cleanup when deleting link (g_idle_add) */

	GCancellable *deactivating_cancellable;

	guint32         ip4_address;

	NMActRequest *  queued_act_request;
	bool            queued_act_request_is_waiting_for_carrier:1;
	NMDBusTrackObjPath act_request;

	union {
		struct {
			guint activation_source_id_6;
			guint activation_source_id_4; /* for layer2 and IPv4. */
		};
		guint activation_source_id_x[2];
	};

	union {
		struct {
			ActivationHandleFunc activation_source_func_6;
			ActivationHandleFunc activation_source_func_4; /* for layer2 and IPv4. */
		};
		ActivationHandleFunc activation_source_func_x[2];
	};

	guint           recheck_assume_id;

	struct {
		guint               call_id;
		NMDeviceStateReason available_reason;
		NMDeviceStateReason unavailable_reason;
	} recheck_available;

	struct {
		NMDispatcherCallId *call_id;
		NMDeviceState       post_state;
		NMDeviceStateReason post_state_reason;
	} dispatcher;

	/* Link stuff */
	guint           link_connected_id;
	guint           link_disconnected_id;
	guint           carrier_defer_id;
	guint           carrier_wait_id;
	gulong          config_changed_id;
	guint32         mtu;
	guint32         ip6_mtu;
	guint32         mtu_initial;
	guint32         ip6_mtu_initial;
	NMDeviceMtuSource mtu_source;

	guint32         v4_route_table;
	guint32         v6_route_table;

	/* when carrier goes away, we give a grace period of _get_carrier_wait_ms()
	 * until taking action.
	 *
	 * When changing MTU, the device might take longer then that. So, whenever
	 * NM changes the MTU it sets @carrier_wait_until_ms to CARRIER_WAIT_TIME_AFTER_MTU_MS
	 * in the future. This is used to extend the grace period in this particular case. */
	gint64          carrier_wait_until_ms;

	union {
		struct {
			NML3ConfigMergeFlags l3config_merge_flags_6;
			NML3ConfigMergeFlags l3config_merge_flags_4;
		};
		NML3ConfigMergeFlags l3config_merge_flags_x[2];
	};

	bool            carrier:1;
	bool            ignore_carrier:1;

	bool            up:1;   /* IFF_UP */

	bool            v4_commit_first_time:1;
	bool            v6_commit_first_time:1;

	bool            default_route_metric_penalty_ip4_has:1;
	bool            default_route_metric_penalty_ip6_has:1;

	NMDeviceSysIfaceState sys_iface_state:2;

	bool            v4_route_table_initialized:1;
	bool            v6_route_table_initialized:1;

	bool            l3config_merge_flags_has:1;

	bool            v4_route_table_all_sync_before:1;
	bool            v6_route_table_all_sync_before:1;

	NMDeviceAutoconnectBlockedFlags autoconnect_blocked_flags:5;

	bool            is_enslaved:1;

	bool            ipv6ll_handle:1; /* TRUE if NM handles the device's IPv6LL address */
	bool            ipv6ll_has:1;
	bool            ndisc_started:1;
	bool            device_link_changed_down:1;

	bool            concheck_rp_filter_checked:1;

	NMDeviceStageState stage1_sriov_state:3;

	/* Generic DHCP stuff */
	char *          dhcp_anycast_address;

	char *          current_stable_id;

	/* Proxy Configuration */
	NMProxyConfig *proxy_config;
	NMPacrunnerConfId *pacrunner_conf_id;

	/* IP configuration info. Combined config from VPN, settings, and device */
	union {
		struct {
			NMIP6Config *ip_config_6;
			NMIP4Config *ip_config_4;
		};
		NMIPConfig *ip_config_x[2];
	};

	/* Config from DHCP, PPP, LLv4, etc */
	AppliedConfig  dev_ip_config_4;

	/* config from the setting */
	union {
		struct {
			NMIP6Config *con_ip_config_6;
			NMIP4Config *con_ip_config_4;
		};
		NMIPConfig *con_ip_config_x[2];
	};

	/* Stuff added outside NM */
	union {
		struct {
			NMIP6Config *ext_ip_config_6;
			NMIP4Config *ext_ip_config_4;
		};
		NMIPConfig *ext_ip_config_x[2];
	};

	/* VPNs which use this device */
	union {
		struct {
			GSList *vpn_configs_6;
			GSList *vpn_configs_4;
		};
		GSList *vpn_configs_x[2];
	};

	/* Extra device configuration, injected by the subclass of NMDevice.
	 * This is used for example by NMDeviceModem for WWAN configuration. */
	union {
		struct {
			AppliedConfig dev2_ip_config_6;
			AppliedConfig dev2_ip_config_4;
		};
		AppliedConfig dev2_ip_config_x[2];
	};

	/* DHCPv4 tracking */
	struct {
		char *          pac_url;
	} dhcp4;

	struct {
		/* IP6 config from DHCP */
		AppliedConfig    ip6_config;
		/* Event ID of the current IP6 config from DHCP */
		char *           event_id;
		gulong           prefix_sigid;
		NMNDiscDHCPLevel mode;
		guint            needed_prefixes;
	} dhcp6;

	union {
		struct {
			DhcpData dhcp_data_6;
			DhcpData dhcp_data_4;
		};
		DhcpData dhcp_data_x[2];
	};

	struct {
		NMLogDomain log_domain;
		guint timeout;
		guint watch;
		GPid pid;
		char *binary;
		char *address;
		guint deadline;
	} gw_ping;

	/* dnsmasq stuff for shared connections */
	NMDnsMasqManager *dnsmasq_manager;
	gulong            dnsmasq_state_id;

	/* Firewall */
	FirewallState fw_state:4;
	NMFirewallManager *fw_mgr;
	NMFirewallManagerCallId *fw_call;

	/* IPv4LL stuff */
	sd_ipv4ll *    ipv4ll;
	guint          ipv4ll_timeout;
	guint          rt6_temporary_not_available_id;

	/* IPv4 DAD stuff */
	struct {
		GSList *          dad_list;
		NMAcdManager * announcing;
	} acd;

	union {
		struct {
			const NMDeviceIPState   ip_state_6;
			const NMDeviceIPState   ip_state_4;
		};
		union {
			const NMDeviceIPState   ip_state_x[2];
			NMDeviceIPState         ip_state_x_[2];
		};
	};

	AppliedConfig  ac_ip6_config;  /* config from IPv6 autoconfiguration */
	NMIP6Config *  ext_ip6_config_captured; /* Configuration captured from platform. */
	NMIP6Config *  dad6_ip6_config;
	struct in6_addr ipv6ll_addr;

	GHashTable *   rt6_temporary_not_available;

	NMNDisc *      ndisc;
	gulong         ndisc_changed_id;
	gulong         ndisc_timeout_id;
	NMSettingIP6ConfigPrivacy ndisc_use_tempaddr;

	guint          linklocal6_timeout_id;
	guint8         linklocal6_dad_counter;

	GHashTable *   ip6_saved_properties;

	EthtoolState  *ethtool_state;

	gboolean needs_ip6_subnet;

	/* master interface for bridge/bond/team slave */
	NMDevice *      master;
	gulong          master_ready_id;

	/* slave management */
	CList           slaves;    /* list of SlaveInfo */

	NMMetered       metered;

	NMSettings *settings;
	NMManager *manager;

	NMNetns *netns;

	NMLldpListener *lldp_listener;

	NMConnectivity *concheck_mgr;
	CList concheck_lst_head;
	struct {
		/* if periodic checks are enabled, this is the source id for the next check. */
		guint p_cur_id;

		/* the currently configured max periodic interval. */
		guint p_max_interval;

		/* the current interval. If we are probing, the interval might be lower
		 * then the configured max interval. */
		guint p_cur_interval;

		/* the timestamp, when we last scheduled the timer p_cur_id with current interval
		 * p_cur_interval. */
		gint64 p_cur_basetime_ns;

		NMConnectivityState state;
	} concheck_x[2];

	guint check_delete_unrealized_id;
	guint32 interface_flags;

	struct {
		SriovOp *pending;    /* SR-IOV operation currently running */
		SriovOp *next;       /* next SR-IOV operation scheduled */
	} sriov;
	guint sriov_reset_pending;

	struct {
		guint timeout_id;
		guint refresh_rate_ms;
		guint64 tx_bytes;
		guint64 rx_bytes;
	} stats;
} NMDevicePrivate;

G_DEFINE_ABSTRACT_TYPE (NMDevice, nm_device, NM_TYPE_DBUS_OBJECT)

#define NM_DEVICE_GET_PRIVATE(self) _NM_GET_PRIVATE_PTR(self, NMDevice, NM_IS_DEVICE)

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

static const NMDBusInterfaceInfoExtended interface_info_device;
static const GDBusSignalInfo signal_info_state_changed;

static void nm_device_set_proxy_config (NMDevice *self, const char *pac_url);

static gboolean update_ext_ip_config (NMDevice *self, int addr_family, gboolean intersect_configs);

static gboolean nm_device_set_ip_config (NMDevice *self,
                                         int addr_family,
                                         NMIPConfig *config,
                                         gboolean commit,
                                         GPtrArray *ip4_dev_route_blacklist);

static gboolean ip_config_merge_and_apply (NMDevice *self,
                                           int addr_family,
                                           gboolean commit);

static gboolean nm_device_master_add_slave (NMDevice *self, NMDevice *slave, gboolean configure);
static void nm_device_slave_notify_enslave (NMDevice *self, gboolean success);
static void nm_device_slave_notify_release (NMDevice *self, NMDeviceStateReason reason);

static void addrconf6_start_with_link_ready (NMDevice *self);
static gboolean linklocal6_start (NMDevice *self);

static guint32 default_route_metric_penalty_get (NMDevice *self, int addr_family);

static guint get_ipv4_dad_timeout (NMDevice *self);

static void _carrier_wait_check_queued_act_request (NMDevice *self);
static gint64 _get_carrier_wait_ms (NMDevice *self);

static const char *_activation_func_to_string (ActivationHandleFunc func);

static void _set_state_full (NMDevice *self,
                             NMDeviceState state,
                             NMDeviceStateReason reason,
                             gboolean quitting);
static void queued_state_clear (NMDevice *device);
static gboolean queued_ip4_config_change (gpointer user_data);
static gboolean queued_ip6_config_change (gpointer user_data);
static void ip_check_ping_watch_cb (GPid pid, int status, gpointer user_data);
static gboolean ip_config_valid (NMDeviceState state);
static NMActStageReturn dhcp4_start (NMDevice *self);
static gboolean dhcp6_start (NMDevice *self, gboolean wait_for_ll);
static void nm_device_start_ip_check (NMDevice *self);
static void realize_start_setup (NMDevice *self,
                                 const NMPlatformLink *plink,
                                 gboolean assume_state_guess_assume,
                                 const char *assume_state_connection_uuid,
                                 gboolean set_nm_owned,
                                 NMUnmanFlagOp unmanaged_user_explicit,
                                 gboolean force_platform_init);
static void _set_mtu (NMDevice *self, guint32 mtu);
static void _commit_mtu (NMDevice *self, const NMIP4Config *config);
static void _cancel_activation (NMDevice *self);

static void concheck_update_state (NMDevice *self,
                                   int addr_family,
                                   NMConnectivityState state,
                                   gboolean is_periodic);

static void activate_stage4_ip_config_timeout_4 (NMDevice *self);
static void activate_stage4_ip_config_timeout_6 (NMDevice *self);

static void (*const activate_stage4_ip_config_timeout_x[2]) (NMDevice *self) = {
	activate_stage4_ip_config_timeout_6,
	activate_stage4_ip_config_timeout_4,
};

static void sriov_op_cb (GError *error, gpointer user_data);

static void activate_stage5_ip_config_result_4 (NMDevice *self);
static void activate_stage5_ip_config_result_6 (NMDevice *self);

static void (*const activate_stage5_ip_config_result_x[2]) (NMDevice *self) = {
	activate_stage5_ip_config_result_6,
	activate_stage5_ip_config_result_4,
};

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

static
NM_UTILS_LOOKUP_STR_DEFINE (queued_state_to_string, NMDeviceState,
	NM_UTILS_LOOKUP_DEFAULT  (                              NM_PENDING_ACTIONPREFIX_QUEUED_STATE_CHANGE "???"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_UNKNOWN,      NM_PENDING_ACTIONPREFIX_QUEUED_STATE_CHANGE "unknown"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_UNMANAGED,    NM_PENDING_ACTIONPREFIX_QUEUED_STATE_CHANGE "unmanaged"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_UNAVAILABLE,  NM_PENDING_ACTIONPREFIX_QUEUED_STATE_CHANGE "unavailable"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_DISCONNECTED, NM_PENDING_ACTIONPREFIX_QUEUED_STATE_CHANGE "disconnected"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_PREPARE,      NM_PENDING_ACTIONPREFIX_QUEUED_STATE_CHANGE "prepare"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_CONFIG,       NM_PENDING_ACTIONPREFIX_QUEUED_STATE_CHANGE "config"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_NEED_AUTH,    NM_PENDING_ACTIONPREFIX_QUEUED_STATE_CHANGE "need-auth"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_IP_CONFIG,    NM_PENDING_ACTIONPREFIX_QUEUED_STATE_CHANGE "ip-config"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_IP_CHECK,     NM_PENDING_ACTIONPREFIX_QUEUED_STATE_CHANGE "ip-check"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_SECONDARIES,  NM_PENDING_ACTIONPREFIX_QUEUED_STATE_CHANGE "secondaries"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_ACTIVATED,    NM_PENDING_ACTIONPREFIX_QUEUED_STATE_CHANGE "activated"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_DEACTIVATING, NM_PENDING_ACTIONPREFIX_QUEUED_STATE_CHANGE "deactivating"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_FAILED,       NM_PENDING_ACTIONPREFIX_QUEUED_STATE_CHANGE "failed"),
);

const char *
nm_device_state_to_str (NMDeviceState state)
{
	return queued_state_to_string (state) + NM_STRLEN (NM_PENDING_ACTIONPREFIX_QUEUED_STATE_CHANGE);
}

NM_UTILS_LOOKUP_STR_DEFINE (nm_device_state_reason_to_str, NMDeviceStateReason,
	NM_UTILS_LOOKUP_DEFAULT (NULL),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_UNKNOWN,                        "unknown"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_NONE,                           "none"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_NOW_MANAGED,                    "managed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_NOW_UNMANAGED,                  "unmanaged"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_CONFIG_FAILED,                  "config-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE,          "ip-config-unavailable"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED,              "ip-config-expired"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_NO_SECRETS,                     "no-secrets"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SUPPLICANT_DISCONNECT,          "supplicant-disconnect"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SUPPLICANT_CONFIG_FAILED,       "supplicant-config-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SUPPLICANT_FAILED,              "supplicant-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SUPPLICANT_TIMEOUT,             "supplicant-timeout"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_PPP_START_FAILED,               "ppp-start-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_PPP_DISCONNECT,                 "ppp-disconnect"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_PPP_FAILED,                     "ppp-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_DHCP_START_FAILED,              "dhcp-start-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_DHCP_ERROR,                     "dhcp-error"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_DHCP_FAILED,                    "dhcp-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SHARED_START_FAILED,            "sharing-start-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SHARED_FAILED,                  "sharing-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_AUTOIP_START_FAILED,            "autoip-start-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_AUTOIP_ERROR,                   "autoip-error"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_AUTOIP_FAILED,                  "autoip-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_BUSY,                     "modem-busy"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_NO_DIAL_TONE,             "modem-no-dialtone"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_NO_CARRIER,               "modem-no-carrier"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_DIAL_TIMEOUT,             "modem-dial-timeout"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_DIAL_FAILED,              "modem-dial-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_INIT_FAILED,              "modem-init-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_APN_FAILED,                 "gsm-apn-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_REGISTRATION_NOT_SEARCHING, "gsm-registration-idle"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_REGISTRATION_DENIED,        "gsm-registration-denied"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_REGISTRATION_TIMEOUT,       "gsm-registration-timeout"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_REGISTRATION_FAILED,        "gsm-registration-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_PIN_CHECK_FAILED,           "gsm-pin-check-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_FIRMWARE_MISSING,               "firmware-missing"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_REMOVED,                        "removed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SLEEPING,                       "sleeping"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_CONNECTION_REMOVED,             "connection-removed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_USER_REQUESTED,                 "user-requested"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_CARRIER,                        "carrier-changed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED,             "connection-assumed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SUPPLICANT_AVAILABLE,           "supplicant-available"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_NOT_FOUND,                "modem-not-found"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_BT_FAILED,                      "bluetooth-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_SIM_NOT_INSERTED,           "gsm-sim-not-inserted"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_SIM_PIN_REQUIRED,           "gsm-sim-pin-required"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_SIM_PUK_REQUIRED,           "gsm-sim-puk-required"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_GSM_SIM_WRONG,                  "gsm-sim-wrong"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_INFINIBAND_MODE,                "infiniband-mode"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED,              "dependency-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_BR2684_FAILED,                  "br2684-bridge-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_MANAGER_UNAVAILABLE,      "modem-manager-unavailable"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SSID_NOT_FOUND,                 "ssid-not-found"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SECONDARY_CONNECTION_FAILED,    "secondary-connection-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_DCB_FCOE_FAILED,                "dcb-fcoe-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_TEAMD_CONTROL_FAILED,           "teamd-control-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_FAILED,                   "modem-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_MODEM_AVAILABLE,                "modem-available"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SIM_PIN_INCORRECT,              "sim-pin-incorrect"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_NEW_ACTIVATION,                 "new-activation"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_PARENT_CHANGED,                 "parent-changed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_PARENT_MANAGED_CHANGED,         "parent-managed-changed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_OVSDB_FAILED,                   "ovsdb-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_IP_ADDRESS_DUPLICATE,           "ip-address-duplicate"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_IP_METHOD_UNSUPPORTED,          "ip-method-unsupported"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_SRIOV_CONFIGURATION_FAILED,     "sriov-configuration-failed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_STATE_REASON_PEER_NOT_FOUND,                 "peer-not-found"),
);

#define reason_to_string_a(reason) NM_UTILS_LOOKUP_STR_A (nm_device_state_reason_to_str, reason)

static
NM_UTILS_LOOKUP_STR_DEFINE (mtu_source_to_str, NMDeviceMtuSource,
	NM_UTILS_LOOKUP_DEFAULT_NM_ASSERT ("unknown"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_MTU_SOURCE_NONE,       "none"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_MTU_SOURCE_PARENT,     "parent"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_MTU_SOURCE_IP_CONFIG,  "ip-config"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_MTU_SOURCE_CONNECTION, "connection"),
);

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

static void
_ethtool_features_reset (NMDevice *self,
                         NMPlatform *platform,
                         EthtoolState *ethtool_state)
{
	gs_free NMEthtoolFeatureStates *features;

	features = g_steal_pointer (&ethtool_state->features);

	if (!nm_platform_ethtool_set_features (platform,
	                                       ethtool_state->ifindex,
	                                       features,
	                                       ethtool_state->requested,
	                                       FALSE))
		_LOGW (LOGD_DEVICE, "ethtool: failure resetting one or more offload features");
	else
		_LOGD (LOGD_DEVICE, "ethtool: offload features successfully reset");
}

static void
_ethtool_features_set (NMDevice *self,
                       NMPlatform *platform,
                       EthtoolState *ethtool_state,
                       NMSettingEthtool *s_ethtool)
{
	gs_free NMEthtoolFeatureStates *features = NULL;

	if (ethtool_state->features)
		_ethtool_features_reset (self, platform, ethtool_state);

	if (nm_setting_ethtool_init_features (s_ethtool, ethtool_state->requested) == 0)
		return;

	features = nm_platform_ethtool_get_link_features (platform,
	                                                  ethtool_state->ifindex);
	if (!features) {
		_LOGW (LOGD_DEVICE, "ethtool: failure setting offload features (cannot read features)");
		return;
	}

	if (!nm_platform_ethtool_set_features (platform,
	                                       ethtool_state->ifindex,
	                                       features,
	                                       ethtool_state->requested,
	                                       TRUE))
		_LOGW (LOGD_DEVICE, "ethtool: failure setting one or more offload features");
	else
		_LOGD (LOGD_DEVICE, "ethtool: offload features successfully set");

	ethtool_state->features = g_steal_pointer (&features);
}

static void
_ethtool_coalesce_reset (NMDevice *self,
                         NMPlatform *platform,
                         EthtoolState *ethtool_state)
{
	gs_free NMEthtoolCoalesceState *coalesce = NULL;

	nm_assert (NM_IS_DEVICE (self));
	nm_assert (NM_IS_PLATFORM (platform));
	nm_assert (ethtool_state);

	coalesce = g_steal_pointer (&ethtool_state->coalesce);
	if (!coalesce)
		return;

	if (!nm_platform_ethtool_set_coalesce (platform,
	                                       ethtool_state->ifindex,
	                                       coalesce))
		_LOGW (LOGD_DEVICE, "ethtool: failure resetting one or more coalesce settings");
	else
		_LOGD (LOGD_DEVICE, "ethtool: coalesce settings successfully reset");
}

static void
_ethtool_coalesce_set (NMDevice *self,
                       NMPlatform *platform,
                       EthtoolState *ethtool_state,
                       NMSettingEthtool *s_ethtool)
{
	NMEthtoolCoalesceState coalesce_old;
	NMEthtoolCoalesceState coalesce_new;
	gboolean has_old = FALSE;
	GHashTable *hash;
	GHashTableIter iter;
	const char *name;
	GVariant *variant;

	nm_assert (NM_IS_DEVICE (self));
	nm_assert (NM_IS_PLATFORM (platform));
	nm_assert (NM_IS_SETTING_ETHTOOL (s_ethtool));
	nm_assert (ethtool_state);
	nm_assert (!ethtool_state->coalesce);

	hash = _nm_setting_option_hash (NM_SETTING (s_ethtool), FALSE);
	if (!hash)
		return;

	g_hash_table_iter_init (&iter, hash);
	while (g_hash_table_iter_next (&iter, (gpointer *) &name, (gpointer *) &variant)) {
		NMEthtoolID ethtool_id = nm_ethtool_id_get_by_name (name);

		if (!nm_ethtool_id_is_coalesce (ethtool_id))
			continue;

		if (!has_old) {
			if (!nm_platform_ethtool_get_link_coalesce (platform,
			                                            ethtool_state->ifindex,
			                                            &coalesce_old)) {
				_LOGW (LOGD_DEVICE, "ethtool: failure getting coalesce settings (cannot read)");
				return;
			}
			has_old = TRUE;
			coalesce_new = coalesce_old;
		}

		nm_assert (g_variant_is_of_type (variant, G_VARIANT_TYPE_UINT32));
		coalesce_new.s[_NM_ETHTOOL_ID_COALESCE_AS_IDX (ethtool_id)] = g_variant_get_uint32 (variant);
	}

	if (!has_old)
		return;

	ethtool_state->coalesce = nm_memdup (&coalesce_old, sizeof (coalesce_old));

	if (!nm_platform_ethtool_set_coalesce (platform,
	                                       ethtool_state->ifindex,
	                                       &coalesce_new)) {
		_LOGW (LOGD_DEVICE, "ethtool: failure setting coalesce settings");
		return;
	}

	_LOGD (LOGD_DEVICE, "ethtool: coalesce settings successfully set");
}

static void
_ethtool_ring_reset (NMDevice *self,
                     NMPlatform *platform,
                     EthtoolState *ethtool_state)
{
	gs_free NMEthtoolRingState *ring = NULL;

	nm_assert (NM_IS_DEVICE (self));
	nm_assert (NM_IS_PLATFORM (platform));
	nm_assert (ethtool_state);

	ring = g_steal_pointer (&ethtool_state->ring);
	if (!ring)
		return;

	if (!nm_platform_ethtool_set_ring (platform,
	                                   ethtool_state->ifindex,
	                                   ring))
		_LOGW (LOGD_DEVICE, "ethtool: failure resetting one or more ring settings");
	else
		_LOGD (LOGD_DEVICE, "ethtool: ring settings successfully reset");
}

static void
_ethtool_ring_set (NMDevice *self,
                   NMPlatform *platform,
                   EthtoolState *ethtool_state,
                   NMSettingEthtool *s_ethtool)
{
	NMEthtoolRingState ring_old;
	NMEthtoolRingState ring_new;
	GHashTable *hash;
	GHashTableIter iter;
	const char *name;
	GVariant *variant;
	gboolean has_old = FALSE;

	nm_assert (NM_IS_DEVICE (self));
	nm_assert (NM_IS_PLATFORM (platform));
	nm_assert (NM_IS_SETTING_ETHTOOL (s_ethtool));
	nm_assert (ethtool_state);
	nm_assert (!ethtool_state->ring);

	hash = _nm_setting_option_hash (NM_SETTING (s_ethtool), FALSE);
	if (!hash)
		return;

	g_hash_table_iter_init (&iter, hash);
	while (g_hash_table_iter_next (&iter, (gpointer *) &name, (gpointer *) &variant)) {
		NMEthtoolID ethtool_id = nm_ethtool_id_get_by_name (name);
		guint32 u32;

		if (!nm_ethtool_id_is_ring (ethtool_id))
			continue;

		nm_assert (g_variant_is_of_type (variant, G_VARIANT_TYPE_UINT32));

		if (!has_old) {
			if (!nm_platform_ethtool_get_link_ring (platform,
			                                        ethtool_state->ifindex,
			                                        &ring_old)) {
				_LOGW (LOGD_DEVICE, "ethtool: failure setting ring options (cannot read existing setting)");
				return;
			}
			has_old = TRUE;
			ring_new = ring_old;
		}

		u32 = g_variant_get_uint32 (variant);

		switch (ethtool_id) {
		case NM_ETHTOOL_ID_RING_RX:
			ring_new.rx_pending = u32;
			break;
		case NM_ETHTOOL_ID_RING_RX_JUMBO:
			ring_new.rx_jumbo_pending = u32;
			break;
		case NM_ETHTOOL_ID_RING_RX_MINI:
			ring_new.rx_mini_pending = u32;
			break;
		case NM_ETHTOOL_ID_RING_TX:
			ring_new.tx_pending = u32;
			break;
		default:
			nm_assert_not_reached ();
		}
	}

	if (!has_old)
		return;

	ethtool_state->ring = nm_memdup (&ring_old, sizeof (ring_old));

	if (!nm_platform_ethtool_set_ring (platform,
	                                   ethtool_state->ifindex,
	                                   &ring_new)) {
		_LOGW (LOGD_DEVICE, "ethtool: failure setting ring settings");
		return;
	}

	_LOGD (LOGD_DEVICE, "ethtool: ring settings successfully set");
}

static void
_ethtool_state_reset (NMDevice *self)
{
	NMPlatform *platform = nm_device_get_platform (self);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gs_free EthtoolState *ethtool_state = g_steal_pointer (&priv->ethtool_state);

	if (!ethtool_state)
		return;

	if (ethtool_state->features)
		_ethtool_features_reset (self, platform, ethtool_state);
	if (ethtool_state->coalesce)
		_ethtool_coalesce_reset (self, platform, ethtool_state);
	if (ethtool_state->ring)
		_ethtool_ring_reset (self, platform, ethtool_state);
}

static void
_ethtool_state_set (NMDevice *self)
{
	int ifindex;
	NMPlatform *platform;
	NMConnection *connection;
	NMSettingEthtool *s_ethtool;
	gs_free EthtoolState *ethtool_state = NULL;
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	ifindex = nm_device_get_ip_ifindex (self);
	if (ifindex <= 0)
		return;

	platform = nm_device_get_platform (self);
	nm_assert (platform);

	connection = nm_device_get_applied_connection (self);
	if (!connection)
		return;

	s_ethtool = NM_SETTING_ETHTOOL (nm_connection_get_setting (connection, NM_TYPE_SETTING_ETHTOOL));
	if (!s_ethtool)
		return;

	ethtool_state = g_new0 (EthtoolState, 1);
	ethtool_state->ifindex = ifindex;

	_ethtool_features_set (self,
	                       platform,
	                       ethtool_state,
	                       s_ethtool);
	_ethtool_coalesce_set (self,
	                       platform,
	                       ethtool_state,
	                       s_ethtool);
	_ethtool_ring_set (self,
	                   platform,
	                   ethtool_state,
	                   s_ethtool);

	if (   ethtool_state->features
	    || ethtool_state->coalesce
	    || ethtool_state->ring)
		priv->ethtool_state = g_steal_pointer (&ethtool_state);
}

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

static gboolean
is_loopback (NMDevice *self)
{
	return    NM_IS_DEVICE_GENERIC (self)
	       && NM_DEVICE_GET_PRIVATE (self)->ifindex == 1;
}

gboolean
nm_device_is_vpn (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	/* NetworkManager currently treats VPN connections (loaded from NetworkManager VPN plugins)
	 * differently. Those are considered VPNs.
	 * However, some native device types may also be considered VPNs...
	 *
	 * We should avoid distinguishing between is-vpn and "regular" devices. Is an (unencrypted)
	 * IP tunnel a VPN? Is MACSec on top of an IP tunnel a VPN?
	 * Sometimes we differentiate, but avoid unless reasonable. */

	return NM_IS_DEVICE_WIREGUARD (self);
}

NMSettings *
nm_device_get_settings (NMDevice *self)
{
	return NM_DEVICE_GET_PRIVATE (self)->settings;
}

NMManager *
nm_device_get_manager (NMDevice *self)
{
	return NM_DEVICE_GET_PRIVATE (self)->manager;
}

NMNetns *
nm_device_get_netns (NMDevice *self)
{
	return NM_DEVICE_GET_PRIVATE (self)->netns;
}

NMDedupMultiIndex *
nm_device_get_multi_index (NMDevice *self)
{
	return nm_netns_get_multi_idx (nm_device_get_netns (self));
}

NMPlatform *
nm_device_get_platform (NMDevice *self)
{
	return nm_netns_get_platform (nm_device_get_netns (self));
}

static NMConnectivity *
concheck_get_mgr (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (G_UNLIKELY (!priv->concheck_mgr))
		priv->concheck_mgr = g_object_ref (nm_connectivity_get ());
	return priv->concheck_mgr;
}

NMIP4Config *
nm_device_ip4_config_new (NMDevice *self)
{
	return nm_ip4_config_new (nm_device_get_multi_index (self),
	                          nm_device_get_ip_ifindex (self));
}

NMIP6Config *
nm_device_ip6_config_new (NMDevice *self)
{
	return nm_ip6_config_new (nm_device_get_multi_index (self),
	                          nm_device_get_ip_ifindex (self));
}

NMIPConfig *
nm_device_ip_config_new (NMDevice *self, int addr_family)
{
	nm_assert_addr_family (addr_family);

	return addr_family == AF_INET
	       ? (gpointer) nm_device_ip4_config_new (self)
	       : (gpointer) nm_device_ip6_config_new (self);
}

NML3ConfigData *
nm_device_create_l3_config_data (NMDevice *self)
{
	int ifindex;

	nm_assert (NM_IS_DEVICE (self));

	ifindex = nm_device_get_ip_ifindex (self);
	if (ifindex <= 0)
		g_return_val_if_reached (NULL);

	return nm_l3_config_data_new (nm_device_get_multi_index (self),
	                              ifindex);
}

static void
applied_config_clear (AppliedConfig *config)
{
	g_clear_object (&config->current);
	g_clear_object (&config->orig);
}

static void
applied_config_init (AppliedConfig *config, gpointer ip_config)
{
	nm_assert (   !ip_config
	           || (!config->orig && !config->current)
	           || nm_ip_config_get_addr_family (ip_config) == nm_ip_config_get_addr_family (config->orig ?: config->current));
	nm_assert (   !ip_config
	           || NM_IS_IP_CONFIG (ip_config));

	nm_g_object_ref (ip_config);
	applied_config_clear (config);
	config->orig = ip_config;
}

static void
applied_config_init_new (AppliedConfig *config, NMDevice *self, int addr_family)
{
	gs_unref_object NMIPConfig *c = nm_device_ip_config_new (self, addr_family);

	applied_config_init (config, c);
}

static NMIPConfig *
applied_config_get_current (AppliedConfig *config)
{
	return config->current ?: config->orig;
}

static void
applied_config_add_address (AppliedConfig *config, const NMPlatformIPAddress *address)
{
	if (config->orig)
		nm_ip_config_add_address (config->orig, address);
	else
		nm_assert (!config->current);

	if (config->current)
		nm_ip_config_add_address (config->current, address);
}

static void
applied_config_add_nameserver (AppliedConfig *config, const NMIPAddr *ns)
{
	if (config->orig)
		nm_ip_config_add_nameserver (config->orig, ns);
	else
		nm_assert (!config->current);

	if (config->current)
		nm_ip_config_add_nameserver (config->current, ns);
}

static void
applied_config_add_search (AppliedConfig *config, const char *new)
{
	if (config->orig)
		nm_ip_config_add_search (config->orig, new);
	else
		nm_assert (!config->current);

	if (config->current)
		nm_ip_config_add_search (config->current, new);
}

static void
applied_config_reset_searches (AppliedConfig *config)
{
	if (config->orig)
		nm_ip_config_reset_searches (config->orig);
	else
		nm_assert (!config->current);

	if (config->current)
		nm_ip_config_reset_searches (config->current);
}

static void
applied_config_reset_nameservers (AppliedConfig *config)
{
	if (config->orig)
		nm_ip_config_reset_nameservers (config->orig);
	else
		nm_assert (!config->current);

	if (config->current)
		nm_ip_config_reset_nameservers (config->current);
}

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

static
NM_UTILS_LOOKUP_STR_DEFINE (_sys_iface_state_to_str, NMDeviceSysIfaceState,
	NM_UTILS_LOOKUP_DEFAULT_NM_ASSERT ("unknown"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_SYS_IFACE_STATE_EXTERNAL, "external"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_SYS_IFACE_STATE_ASSUME,   "assume"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_SYS_IFACE_STATE_MANAGED,  "managed"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_SYS_IFACE_STATE_REMOVED,  "removed"),
);

NMDeviceSysIfaceState
nm_device_sys_iface_state_get (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), NM_DEVICE_SYS_IFACE_STATE_EXTERNAL);

	return NM_DEVICE_GET_PRIVATE (self)->sys_iface_state;
}

gboolean
nm_device_sys_iface_state_is_external (NMDevice *self)
{
	return NM_IN_SET (nm_device_sys_iface_state_get (self),
	                  NM_DEVICE_SYS_IFACE_STATE_EXTERNAL);
}

gboolean
nm_device_sys_iface_state_is_external_or_assume (NMDevice *self)
{
	return NM_IN_SET (nm_device_sys_iface_state_get (self),
	                  NM_DEVICE_SYS_IFACE_STATE_EXTERNAL,
	                  NM_DEVICE_SYS_IFACE_STATE_ASSUME);
}

void
nm_device_sys_iface_state_set (NMDevice *self,
                               NMDeviceSysIfaceState sys_iface_state)
{
	NMDevicePrivate *priv;

	g_return_if_fail (NM_IS_DEVICE (self));
	g_return_if_fail (NM_IN_SET (sys_iface_state,
	                             NM_DEVICE_SYS_IFACE_STATE_EXTERNAL,
	                             NM_DEVICE_SYS_IFACE_STATE_ASSUME,
	                             NM_DEVICE_SYS_IFACE_STATE_MANAGED,
	                             NM_DEVICE_SYS_IFACE_STATE_REMOVED));

	priv = NM_DEVICE_GET_PRIVATE (self);
	if (priv->sys_iface_state != sys_iface_state) {
		_LOGT (LOGD_DEVICE, "sys-iface-state: %s -> %s",
		       _sys_iface_state_to_str (priv->sys_iface_state),
		       _sys_iface_state_to_str (sys_iface_state));
		priv->sys_iface_state = sys_iface_state;
	}

	/* this function only sets a flag, no immediate actions are initiated.
	 *
	 * If you change this, make sure that all callers are fine with such actions. */

	nm_assert (priv->sys_iface_state == sys_iface_state);
}

static void
_active_connection_set_state_flags_full (NMDevice *self,
                                         NMActivationStateFlags flags,
                                         NMActivationStateFlags mask)
{
	NMActiveConnection *ac;

	ac = NM_ACTIVE_CONNECTION (nm_device_get_act_request (self));
	if (ac)
		nm_active_connection_set_state_flags_full (ac, flags, mask);
}

static void
_active_connection_set_state_flags (NMDevice *self,
                                    NMActivationStateFlags flags)
{
	_active_connection_set_state_flags_full (self, flags, flags);
}

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

void
nm_device_assume_state_get (NMDevice *self,
                            gboolean *out_assume_state_guess_assume,
                            const char **out_assume_state_connection_uuid)
{
	NMDevicePrivate *priv;

	g_return_if_fail (NM_IS_DEVICE (self));

	priv = NM_DEVICE_GET_PRIVATE (self);
	NM_SET_OUT (out_assume_state_guess_assume, priv->assume_state_guess_assume);
	NM_SET_OUT (out_assume_state_connection_uuid, priv->assume_state_connection_uuid);
}

static void
_assume_state_set (NMDevice *self,
                   gboolean assume_state_guess_assume,
                   const char *assume_state_connection_uuid)
{
	NMDevicePrivate *priv;

	nm_assert (NM_IS_DEVICE (self));

	priv = NM_DEVICE_GET_PRIVATE (self);
	if (   priv->assume_state_guess_assume == !!assume_state_guess_assume
	    && nm_streq0 (priv->assume_state_connection_uuid, assume_state_connection_uuid))
		return;

	_LOGD (LOGD_DEVICE, "assume-state: set guess-assume=%c, connection=%s%s%s",
	       assume_state_guess_assume ? '1' : '0',
	       NM_PRINT_FMT_QUOTE_STRING (assume_state_connection_uuid));
	priv->assume_state_guess_assume = assume_state_guess_assume;
	g_free (priv->assume_state_connection_uuid);
	priv->assume_state_connection_uuid = g_strdup (assume_state_connection_uuid);
}

void
nm_device_assume_state_reset (NMDevice *self)
{
	g_return_if_fail (NM_IS_DEVICE (self));

	_assume_state_set (self, FALSE, NULL);
}

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

static void
init_ip_config_dns_priority (NMDevice *self, NMIPConfig *config)
{
	const char *property;
	int priority;

	property = (nm_ip_config_get_addr_family (config) == AF_INET)
	             ? NM_CON_DEFAULT ("ipv4.dns-priority")
	             : NM_CON_DEFAULT ("ipv6.dns-priority");

	priority = nm_config_data_get_connection_default_int64 (NM_CONFIG_GET_DATA,
	                                                        property,
	                                                        self,
	                                                        G_MININT,
	                                                        G_MAXINT,
	                                                        0);

	if (priority == 0) {
		priority =   nm_device_is_vpn (self)
		           ? NM_DNS_PRIORITY_DEFAULT_VPN
		           : NM_DNS_PRIORITY_DEFAULT_NORMAL;
	}

	nm_ip_config_set_dns_priority (config, priority);
}

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

static char *
nm_device_sysctl_ip_conf_get (NMDevice *self,
                              int addr_family,
                              const char *property)
{
	const char *ifname;

	nm_assert_addr_family (addr_family);

	ifname = nm_device_get_ip_iface_from_platform (self);
	if (!ifname)
		return NULL;
	return nm_platform_sysctl_ip_conf_get (nm_device_get_platform (self), addr_family, ifname, property);
}

static gint64
nm_device_sysctl_ip_conf_get_int_checked (NMDevice *self,
                                          int addr_family,
                                          const char *property,
                                          guint base,
                                          gint64 min,
                                          gint64 max,
                                          gint64 fallback)
{
	const char *ifname;

	nm_assert_addr_family (addr_family);

	ifname = nm_device_get_ip_iface_from_platform (self);
	if (!ifname) {
		errno = EINVAL;
		return fallback;
	}
	return nm_platform_sysctl_ip_conf_get_int_checked (nm_device_get_platform (self),
	                                                   addr_family,
	                                                   ifname,
	                                                   property,
	                                                   base,
	                                                   min,
	                                                   max,
	                                                   fallback);
}

static void
set_ipv6_token (NMDevice *self, NMUtilsIPv6IfaceId iid, const char *token_str)
{
	NMPlatform *platform;
	int ifindex;
	const NMPlatformLink *link;
	char buf[32];
	gint64 val;

	/* Setting the kernel token is not strictly necessary as the
	 * IPv6 address is generated in userspace. However it is
	 * convenient so that users can see the token with iproute
	 * ('ip token'). */
	platform = nm_device_get_platform (self);
	ifindex = nm_device_get_ip_ifindex (self);
	link = nm_platform_link_get (platform, ifindex);

	if (link && link->inet6_token.id == iid.id) {
		_LOGT (LOGD_DEVICE | LOGD_IP6, "token %s already set", token_str);
		return;
	}

	/* The kernel allows setting a token only when 'accept_ra'
	 * is 1: temporarily flip it if necessary; unfortunately
	 * this will also generate an additional Router Solicitation
	 * from kernel. */
	val = nm_device_sysctl_ip_conf_get_int_checked (self,
	                                                AF_INET6,
	                                                "accept_ra",
	                                                10,
	                                                G_MININT32,
	                                                G_MAXINT32,
	                                                1);
	if (val != 1)
		nm_device_sysctl_ip_conf_set (self, AF_INET6, "accept_ra", "1");

	nm_platform_link_set_ipv6_token (platform, ifindex, iid);

	if (val != 1) {
		nm_sprintf_buf (buf, "%d", (int) val);
		nm_device_sysctl_ip_conf_set (self, AF_INET6, "accept_ra", buf);
	}
}

gboolean
nm_device_sysctl_ip_conf_set (NMDevice *self,
                              int addr_family,
                              const char *property,
                              const char *value)
{
	NMPlatform *platform = nm_device_get_platform (self);
	gs_free char *value_to_free = NULL;
	const char *ifname;

	nm_assert_addr_family (addr_family);

	ifname = nm_device_get_ip_iface_from_platform (self);
	if (!ifname)
		return FALSE;

	if (!value) {
		/* Set to a default value when we've got a NULL @value. */
		value_to_free = nm_platform_sysctl_ip_conf_get (platform,
		                                                addr_family,
		                                                "default",
		                                                property);
		value = value_to_free;
		if (!value)
			return FALSE;
	}

	return nm_platform_sysctl_ip_conf_set (platform,
	                                       addr_family,
	                                       ifname,
	                                       property,
	                                       value);
}

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

gboolean
nm_device_has_capability (NMDevice *self, NMDeviceCapabilities caps)
{
	return NM_FLAGS_ANY (NM_DEVICE_GET_PRIVATE (self)->capabilities, caps);
}

static void
_add_capabilities (NMDevice *self, NMDeviceCapabilities capabilities)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (!NM_FLAGS_ALL (priv->capabilities, capabilities)) {
		priv->capabilities |= capabilities;
		_notify (self, PROP_CAPABILITIES);
	}
}

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

static const char *
_get_stable_id (NMDevice *self,
                NMConnection *connection,
                NMUtilsStableType *out_stable_type)
{
	NMDevicePrivate *priv;

	nm_assert (NM_IS_DEVICE (self));
	nm_assert (NM_IS_CONNECTION (connection));
	nm_assert (out_stable_type);

	priv = NM_DEVICE_GET_PRIVATE (self);

	/* we cache the generated stable ID for the time of an activation.
	 *
	 * The reason is, that we don't want the stable-id to change as long
	 * as the device is active.
	 *
	 * Especially with ${RANDOM} stable-id we want to generate *one* configuration
	 * for each activation. */
	if (G_UNLIKELY (!priv->current_stable_id)) {
		gs_free char *default_id = NULL;
		gs_free char *generated = NULL;
		NMUtilsStableType stable_type;
		NMSettingConnection *s_con;
		gboolean hwaddr_is_fake;
		const char *hwaddr;
		const char *stable_id;
		const char *uuid;

		s_con = nm_connection_get_setting_connection (connection);

		stable_id = nm_setting_connection_get_stable_id (s_con);

		if (!stable_id) {
			default_id = nm_config_data_get_connection_default (NM_CONFIG_GET_DATA,
			                                                    NM_CON_DEFAULT ("connection.stable-id"),
			                                                    self);
			stable_id = default_id;
		}

		uuid = nm_connection_get_uuid (connection);

		/* the cloned-mac-address may be generated based on the stable-id.
		 * Thus, at this point, we can only use the permanent MAC address
		 * as seed. */
		hwaddr = nm_device_get_permanent_hw_address_full (self, TRUE, &hwaddr_is_fake);

		stable_type = nm_utils_stable_id_parse (stable_id,
		                                        nm_device_get_ip_iface (self),
		                                        !hwaddr_is_fake ? hwaddr : NULL,
		                                        nm_utils_boot_id_str (),
		                                        uuid,
		                                        &generated);

		/* current_stable_id_type is a bitfield! */
		priv->current_stable_id_type = stable_type;
		nm_assert (stable_type <= (NMUtilsStableType) 0x3);
		nm_assert (stable_type + (NMUtilsStableType) 1 > (NMUtilsStableType) 0);
		nm_assert (priv->current_stable_id_type == stable_type);

		if (stable_type == NM_UTILS_STABLE_TYPE_UUID)
			priv->current_stable_id = g_strdup (uuid);
		else if (stable_type == NM_UTILS_STABLE_TYPE_STABLE_ID)
			priv->current_stable_id = g_strdup (stable_id);
		else if (stable_type == NM_UTILS_STABLE_TYPE_GENERATED)
			priv->current_stable_id = nm_str_realloc (nm_utils_stable_id_generated_complete (generated));
		else {
			nm_assert (stable_type == NM_UTILS_STABLE_TYPE_RANDOM);
			priv->current_stable_id = nm_str_realloc (nm_utils_stable_id_random ());
		}
		_LOGT (LOGD_DEVICE,
		       "stable-id: type=%d, \"%s\""
		       "%s%s%s",
		       (int) priv->current_stable_id_type,
		       priv->current_stable_id,
		       NM_PRINT_FMT_QUOTED (stable_type == NM_UTILS_STABLE_TYPE_GENERATED, " from \"", generated, "\"", ""));
	}

	nm_assert (priv->current_stable_id);
	*out_stable_type = priv->current_stable_id_type;
	return priv->current_stable_id;
}

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

static
NM_UTILS_LOOKUP_STR_DEFINE (_ip_state_to_string, NMDeviceIPState,
	NM_UTILS_LOOKUP_DEFAULT_WARN ("unknown"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_IP_STATE_NONE, "none"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_IP_STATE_WAIT, "wait"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_IP_STATE_CONF, "conf"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_IP_STATE_DONE, "done"),
	NM_UTILS_LOOKUP_STR_ITEM (NM_DEVICE_IP_STATE_FAIL, "fail"),
);

static void
_set_ip_state (NMDevice *self, int addr_family, NMDeviceIPState new_state)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	nm_assert_addr_family (addr_family);

	if (priv->ip_state_x[IS_IPv4] == new_state)
		return;

	_LOGT (LOGD_DEVICE, "ip%c-state: set to %d (%s)",
	       nm_utils_addr_family_to_char (addr_family),
	       (int) new_state,
	       _ip_state_to_string (new_state));

	priv->ip_state_x_[IS_IPv4] = new_state;

	if (new_state == NM_DEVICE_IP_STATE_DONE) {
		/* we only set the IPx_READY flag once we reach NM_DEVICE_IP_STATE_DONE state. We don't
		 * ever clear it, even if we later enter NM_DEVICE_IP_STATE_FAIL state.
		 *
		 * This is not documented/guaranteed behavior, but seems to make sense for now. */
		_active_connection_set_state_flags (self,
		                                    addr_family == AF_INET
		                                      ? NM_ACTIVATION_STATE_FLAG_IP4_READY
		                                      : NM_ACTIVATION_STATE_FLAG_IP6_READY);
	}
}

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

static L3ConfigDataType
_dev_l3_config_data_tag_to_type (NMDevice *self,
                                 gconstpointer tag)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	int d;

	if (   tag < ((gpointer) &priv->l3cds[0])
	    || tag >= ((gpointer) &priv->l3cds[G_N_ELEMENTS (priv->l3cds)]))
		return _L3_CONFIG_DATA_TYPE_NONE;

	d = ((const NML3ConfigData **) tag) - (&priv->l3cds[0]);

	nm_assert (d >= 0);
	nm_assert (d < _L3_CONFIG_DATA_TYPE_NUM);
	nm_assert (tag == &priv->l3cds[d]);
	return d;
}

static NML3ConfigMergeFlags
_dev_l3_get_merge_flags (NMDevice *self,
                         L3ConfigDataType type)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NML3ConfigMergeFlags flags;
	NMConnection *connection;
	NMSettingIPConfig *s_ip;

	if (G_UNLIKELY (!priv->l3config_merge_flags_has)) {
		int IS_IPv4;

		connection = nm_device_get_applied_connection (self);

		for (IS_IPv4 = 0; IS_IPv4 < 2; IS_IPv4++) {
			flags = NM_L3_CONFIG_MERGE_FLAGS_NONE;

			if (   connection
			    && (s_ip = nm_connection_get_setting_ip_config (connection, IS_IPv4 ? AF_INET : AF_INET6))) {

				if (nm_setting_ip_config_get_ignore_auto_routes (s_ip))
					flags |= NM_L3_CONFIG_MERGE_FLAGS_NO_ROUTES;

				if (nm_setting_ip_config_get_ignore_auto_dns (s_ip))
					flags |= NM_L3_CONFIG_MERGE_FLAGS_NO_DNS;

				if (   nm_setting_ip_config_get_never_default (s_ip)
				    || nm_setting_ip_config_get_gateway (s_ip)) {
					/* if the connection has an explicit gateway, we also ignore
					 * the default routes from other sources. */
					flags |= NM_L3_CONFIG_MERGE_FLAGS_NO_DEFAULT_ROUTES;
				}
			}

			priv->l3config_merge_flags_x[IS_IPv4] = flags;
		}
		priv->l3config_merge_flags_has = TRUE;
	}

	switch (type) {

	case L3_CONFIG_DATA_TYPE_SETTING:
	case L3_CONFIG_DATA_TYPE_LL_4:
		return NM_L3_CONFIG_MERGE_FLAGS_NONE;

	case L3_CONFIG_DATA_TYPE_DHCP_4:
	case L3_CONFIG_DATA_TYPE_DEV_4:
		return priv->l3config_merge_flags_4;

	case L3_CONFIG_DATA_TYPE_AC_6:
	case L3_CONFIG_DATA_TYPE_DHCP_6:
	case L3_CONFIG_DATA_TYPE_DEV_6:
		return priv->l3config_merge_flags_6;

	case _L3_CONFIG_DATA_TYPE_NUM:
	case _L3_CONFIG_DATA_TYPE_NONE:
		break;
	}
	return nm_assert_unreachable_val (NM_L3_CONFIG_MERGE_FLAGS_NONE);
}

_nm_unused /* FIXME(l3cfg) */
static gboolean
_dev_l3_register_l3cds_set_one (NMDevice *self,
                                L3ConfigDataType l3cd_type,
                                const NML3ConfigData *l3cd)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	nm_auto_unref_l3cd const NML3ConfigData *l3cd_old_free = NULL;
	const NML3ConfigData *l3cd_old;
	gboolean changed = FALSE;

	l3cd_old = priv->l3cds[l3cd_type];
	if (l3cd != priv->l3cds[l3cd_type]) {
		l3cd_old_free = g_steal_pointer (&priv->l3cds[l3cd_type]);
		if (l3cd)
			priv->l3cds[l3cd_type] = nm_l3_config_data_ref_and_seal (l3cd);
	}

	if (priv->l3cfg) {
		if (nm_l3cfg_add_config (priv->l3cfg,
		                         &priv->l3cds[l3cd_type],
		                         FALSE,
		                         priv->l3cds[l3cd_type],
		                         l3cd_type,
		                         default_route_metric_penalty_get (self, AF_INET),
		                         default_route_metric_penalty_get (self, AF_INET6),
		                         get_ipv4_dad_timeout (self),
		                         _dev_l3_get_merge_flags (self, l3cd_type)))
			changed = TRUE;

		if (   l3cd_old
		    && l3cd_old != l3cd) {
			if (nm_l3cfg_remove_config (priv->l3cfg, &priv->l3cds[l3cd_type], l3cd_old))
				changed = TRUE;
		}
	}

	return changed;
}

static gboolean
_dev_l3_register_l3cds (NMDevice *self,
                        NML3Cfg *l3cfg,
                        gboolean do_add /* else remove */)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	guint32 default_route_penalty_4 = 0;
	guint32 default_route_penalty_6 = 0;
	guint32 acd_timeout_msec = 0;
	gboolean is_external;
	gboolean changed;
	int i;

	if (!l3cfg)
		return FALSE;

	is_external = nm_device_sys_iface_state_is_external (self);
	if (!is_external) {
		default_route_penalty_4 = default_route_metric_penalty_get (self, AF_INET);
		default_route_penalty_6 = default_route_metric_penalty_get (self, AF_INET6);
		acd_timeout_msec = get_ipv4_dad_timeout (self);
	}

	changed = FALSE;
	for (i = 0; i < G_N_ELEMENTS (priv->l3cds); i++) {
		if (!priv->l3cds[i])
			continue;
		if (!do_add) {
			if (nm_l3cfg_remove_config (l3cfg, &priv->l3cds[i], priv->l3cds[i]))
				changed = TRUE;
			continue;
		}
		if (is_external)
			continue;
		if (nm_l3cfg_add_config (l3cfg,
		                         &priv->l3cds[i],
		                         FALSE,
		                         priv->l3cds[i],
		                         i,
		                         default_route_penalty_4,
		                         default_route_penalty_6,
		                         acd_timeout_msec,
		                         _dev_l3_get_merge_flags (self, i)))
			changed = TRUE;
	}

	return changed;
}

_nm_unused /* FIXME(l3cfg) */
static gboolean
_dev_l3_platform_commit (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gboolean success;

	if (!priv->l3cfg)
		return FALSE;

	if (nm_device_sys_iface_state_is_external (self))
		return TRUE;

	success = nm_l3cfg_platform_commit (priv->l3cfg,
	                                      nm_device_sys_iface_state_is_external_or_assume (self)
	                                    ? NM_L3_CFG_COMMIT_TYPE_ASSUME
	                                    : NM_L3_CFG_COMMIT_TYPE_UPDATE,
	                                    AF_UNSPEC,
	                                    NULL);
	return success;
}

static void
_dev_l3_cfg_acd_maybe_comlete (NMDevice *self)
{
	/* FIXME(l3cfg) */
}

static void
_dev_l3_cfg_notify_cb (NML3Cfg *l3cfg,
                       int notify_type_i,
                       const NML3ConfigNotifyPayload *payload,
                       NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	nm_assert (l3cfg == priv->l3cfg);

	switch ((NML3ConfigNotifyType) notify_type_i) {
	case NM_L3_CONFIG_NOTIFY_TYPE_ACD_FAILED: {
		const NML3ConfigNotifyPayloadAcdFailedSource *sources = payload->acd_failed.sources;
		guint sources_len = payload->acd_failed.sources_len;
		guint i;

		for (i = 0; i < sources_len; i++) {
			L3ConfigDataType l3cd_type = _dev_l3_config_data_tag_to_type (self, sources[i].tag);

			if (NM_IN_SET (l3cd_type, L3_CONFIG_DATA_TYPE_DHCP_4)) {
				nm_dhcp_client_decline (priv->dhcp_data_4.client, "Address conflict detected", NULL);
				nm_device_ip_method_failed (self, AF_INET,
				                            NM_DEVICE_STATE_REASON_IP_ADDRESS_DUPLICATE);
				return;
			}
		}
		_dev_l3_cfg_acd_maybe_comlete (self);
		return;
	}
	case NM_L3_CONFIG_NOTIFY_TYPE_ACD_COMPLETED:
		_dev_l3_cfg_acd_maybe_comlete (self);
		return;
	case NM_L3_CONFIG_NOTIFY_TYPE_ROUTES_TEMPORARY_NOT_AVAILABLE_EXPIRED:
		/* FIXME(l3cfg) */
		return;
	case _NM_L3_CONFIG_NOTIFY_TYPE_NUM:
		break;
	}
	nm_assert_not_reached ();
}

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

const char *
nm_device_get_udi (NMDevice *self)
{
	g_return_val_if_fail (self != NULL, NULL);

	return NM_DEVICE_GET_PRIVATE (self)->udi;
}

const char *
nm_device_get_iface (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), NULL);

	return NM_DEVICE_GET_PRIVATE (self)->iface;
}

static gboolean
_set_ifindex (NMDevice *self, int ifindex, gboolean is_ip_ifindex)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gs_unref_object NML3Cfg *l3cfg_old = NULL;
	gboolean l3_changed;
	int ip_ifindex_new;
	int *p_ifindex;

	if (ifindex < 0)
		ifindex = 0;

	p_ifindex =   is_ip_ifindex
	            ? &priv->ip_ifindex_
	            : &priv->ifindex_;

	if (*p_ifindex == ifindex)
		return FALSE;

	*p_ifindex = ifindex;

	ip_ifindex_new = nm_device_get_ip_ifindex (self);

	if (priv->l3cfg) {
		if (   ip_ifindex_new <= 0
		    || ip_ifindex_new != nm_l3cfg_get_ifindex (priv->l3cfg)) {
			g_signal_handlers_disconnect_by_func (priv->l3cfg,
			                                      G_CALLBACK (_dev_l3_cfg_notify_cb),
			                                      self);
			l3cfg_old = g_steal_pointer (&priv->l3cfg_);
		}
	}
	if (   !priv->l3cfg
	    && ip_ifindex_new > 0) {
		priv->l3cfg_ = nm_netns_access_l3cfg (priv->netns, ip_ifindex_new);

		g_signal_connect (priv->l3cfg,
		                  NM_L3CFG_SIGNAL_NOTIFY,
		                  G_CALLBACK (_dev_l3_cfg_notify_cb),
		                  self);
	}

	_LOGD (LOGD_DEVICE,
	       "ifindex: set %sifindex %d%s%s%s%s%s%s",
	       is_ip_ifindex ? "ip-" : "",
	       ifindex,
	       NM_PRINT_FMT_QUOTED (l3cfg_old   && l3cfg_old != priv->l3cfg, " (old-l3cfg: ", nm_hash_obfuscated_ptr_str_a (l3cfg_old),   ")", ""),
	       NM_PRINT_FMT_QUOTED (priv->l3cfg && l3cfg_old != priv->l3cfg, " (l3cfg: ",     nm_hash_obfuscated_ptr_str_a (priv->l3cfg), ")", ""));

	if (!is_ip_ifindex)
		_notify (self, PROP_IFINDEX);

	l3_changed = FALSE;
	if (_dev_l3_register_l3cds (self, priv->l3cfg, TRUE))
		l3_changed = TRUE;
	if (_dev_l3_register_l3cds (self, l3cfg_old, FALSE))
		l3_changed = TRUE;

	if (l3_changed) {
		/* FIXME(l3cfg) */
	}

	return TRUE;
}

/**
 * nm_device_take_over_link:
 * @self: the #NMDevice
 * @ifindex: a ifindex
 * @old_name: (transfer full): on return, the name of the old link, if
 *   the link was renamed
 * @error: location to store error, or %NULL
 *
 * Given an existing link, move it under the control of a device. In
 * particular, the link will be renamed to match the device name. If the
 * link was renamed, the old name is returned in @old_name.
 *
 * Returns: %TRUE if the device took control of the link, %FALSE otherwise
 */
gboolean
nm_device_take_over_link (NMDevice *self, int ifindex, char **old_name, GError **error)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const NMPlatformLink *plink;
	NMPlatform *platform;

	nm_assert (ifindex > 0);
	NM_SET_OUT (old_name, NULL);

	if (   priv->ifindex > 0
	    && priv->ifindex != ifindex) {
		nm_utils_error_set (error, NM_UTILS_ERROR_UNKNOWN,
		                    "the device already has ifindex %d",
		                    priv->ifindex);
		return FALSE;
	}

	platform = nm_device_get_platform (self);
	plink = nm_platform_link_get (platform, ifindex);
	if (!plink) {
		nm_utils_error_set (error, NM_UTILS_ERROR_UNKNOWN,
		                    "link %d not found", ifindex);
		return FALSE;
	}

	if (!nm_streq (plink->name, nm_device_get_iface (self))) {
		gboolean up;
		gboolean success;
		gs_free char *name = NULL;

		up = NM_FLAGS_HAS (plink->n_ifi_flags, IFF_UP);
		name = g_strdup (plink->name);

		/* Rename the link to the device ifname */
		if (up)
			nm_platform_link_set_down (platform, ifindex);
		success = nm_platform_link_set_name (platform, ifindex, nm_device_get_iface (self));
		if (up)
			nm_platform_link_set_up (platform, ifindex, NULL);

		if (!success) {
			nm_utils_error_set (error, NM_UTILS_ERROR_UNKNOWN,
			                    "failure renaming link %d", ifindex);
			return FALSE;
		}

		NM_SET_OUT (old_name, g_steal_pointer (&name));
	}

	_set_ifindex (self, ifindex, FALSE);

	return TRUE;
}

int
nm_device_get_ifindex (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), 0);

	return NM_DEVICE_GET_PRIVATE (self)->ifindex;
}

/**
 * nm_device_is_software:
 * @self: the #NMDevice
 *
 * Indicates if the device is a software-based virtual device without
 * backing hardware, which can be added and removed programmatically.
 *
 * Returns: %TRUE if the device is a software-based device
 */
gboolean
nm_device_is_software (NMDevice *self)
{
	return NM_FLAGS_HAS (NM_DEVICE_GET_PRIVATE (self)->capabilities, NM_DEVICE_CAP_IS_SOFTWARE);
}

/**
 * nm_device_is_real:
 * @self: the #NMDevice
 *
 * Returns: %TRUE if the device exists, %FALSE if the device is a placeholder
 */
gboolean
nm_device_is_real (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	return NM_DEVICE_GET_PRIVATE (self)->real;
}

const char *
nm_device_get_ip_iface (NMDevice *self)
{
	NMDevicePrivate *priv;

	g_return_val_if_fail (self != NULL, NULL);

	priv = NM_DEVICE_GET_PRIVATE (self);
	/* If it's not set, default to iface */
	return priv->ip_iface ?: priv->iface;
}

const char *
nm_device_get_ip_iface_from_platform (NMDevice *self)
{
	int ifindex;

	ifindex = nm_device_get_ip_ifindex (self);
	if (ifindex <= 0)
		return NULL;

	return nm_platform_link_get_name (nm_device_get_platform (self), ifindex);
}

int
nm_device_get_ip_ifindex (const NMDevice *self)
{
	const NMDevicePrivate *priv;

	g_return_val_if_fail (self != NULL, 0);

	priv = NM_DEVICE_GET_PRIVATE (self);
	/* If it's not set, default to ifindex */
	return priv->ip_iface ? priv->ip_ifindex : priv->ifindex;
}

static void
_set_ip_ifindex (NMDevice *self,
                 int ifindex,
                 const char *ifname)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMPlatform *platform;
	gboolean eq_name;

	/* normalize arguments */
	if (ifindex <= 0) {
		ifindex = 0;
		ifname = NULL;
	}

	eq_name = nm_streq0 (priv->ip_iface, ifname);

	if (   eq_name
	    && priv->ip_ifindex == ifindex)
		return;

	_LOGD (LOGD_DEVICE, "ip-ifindex: update ip-interface to %s%s%s, ifindex %d",
	       NM_PRINT_FMT_QUOTE_STRING (ifname),
	       ifindex);

	_set_ifindex (self, ifindex, TRUE);

	if (!eq_name) {
		g_free (priv->ip_iface_);
		priv->ip_iface_ = g_strdup (ifname);
		_notify (self, PROP_IP_IFACE);
	}

	if (priv->ip_ifindex > 0) {
		platform = nm_device_get_platform (self);

		nm_platform_process_events_ensure_link (platform,
		                                        priv->ip_ifindex,
		                                        priv->ip_iface);

		if (nm_platform_kernel_support_get (NM_PLATFORM_KERNEL_SUPPORT_TYPE_USER_IPV6LL))
			nm_platform_link_set_user_ipv6ll_enabled (platform, priv->ip_ifindex, TRUE);

		if (!nm_platform_link_is_up (platform, priv->ip_ifindex))
			nm_platform_link_set_up (platform, priv->ip_ifindex, NULL);
	}

	/* We don't care about any saved values from the old iface */
	g_hash_table_remove_all (priv->ip6_saved_properties);
}

gboolean
nm_device_set_ip_ifindex (NMDevice *self, int ifindex)
{
	char ifname_buf[IFNAMSIZ];
	const char *ifname = NULL;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
	g_return_val_if_fail (nm_device_is_activating (self), FALSE);

	if (ifindex > 0) {
		ifname = nm_platform_if_indextoname (nm_device_get_platform (self), ifindex, ifname_buf);
		if (!ifname)
			_LOGW (LOGD_DEVICE, "ip-ifindex: ifindex %d not found", ifindex);
	}

	_set_ip_ifindex (self, ifindex, ifname);
	return ifindex > 0;
}

/**
 * nm_device_set_ip_iface:
 * @self: the #NMDevice
 * @ifname: the new IP interface name
 *
 * Updates the IP interface name and possibly the ifindex.
 *
 * Returns: %TRUE if an interface with name @ifname exists,
 *   and %FALSE, if @ifname is %NULL or no such interface exists.
 */
gboolean
nm_device_set_ip_iface (NMDevice *self, const char *ifname)
{
	int ifindex = 0;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
	g_return_val_if_fail (nm_device_is_activating (self), FALSE);

	if (ifname) {
		ifindex = nm_platform_if_nametoindex (nm_device_get_platform (self), ifname);
		if (ifindex <= 0)
			_LOGW (LOGD_DEVICE, "ip-ifindex: ifname %s not found", ifname);
	}

	_set_ip_ifindex (self, ifindex, ifname);
	return ifindex > 0;
}

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

int
nm_device_parent_get_ifindex (NMDevice *self)
{
	NMDevicePrivate *priv;

	g_return_val_if_fail (NM_IS_DEVICE (self), 0);

	priv = NM_DEVICE_GET_PRIVATE (self);
	return priv->parent_ifindex;
}

NMDevice *
nm_device_parent_get_device (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), NULL);

	return NM_DEVICE_GET_PRIVATE (self)->parent_device.obj;
}

static void
parent_changed_notify (NMDevice *self,
                       int old_ifindex,
                       NMDevice *old_parent,
                       int new_ifindex,
                       NMDevice *new_parent)
{
	/* empty handler to allow subclasses to always chain up the virtual function. */
}

static gboolean
_parent_set_ifindex (NMDevice *self,
                     int parent_ifindex,
                     gboolean force_check)
{
	NMDevicePrivate *priv;
	NMDevice *parent_device;
	gboolean changed = FALSE;
	int old_ifindex;
	gs_unref_object NMDevice *old_device = NULL;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (parent_ifindex <= 0)
		parent_ifindex = 0;

	old_ifindex = priv->parent_ifindex;

	if (priv->parent_ifindex == parent_ifindex) {
		if (parent_ifindex > 0) {
			if (   !force_check
			    && priv->parent_device.obj
			    && nm_device_get_ifindex (priv->parent_device.obj) == parent_ifindex)
				return FALSE;
		} else {
			if (!priv->parent_device.obj)
				return FALSE;
		}
	} else {
		priv->parent_ifindex = parent_ifindex;
		changed = TRUE;
	}

	if (parent_ifindex > 0) {
		parent_device = nm_manager_get_device_by_ifindex (NM_MANAGER_GET, parent_ifindex);
		if (parent_device == self)
			parent_device = NULL;
	} else
		parent_device = NULL;

	if (parent_device != priv->parent_device.obj) {
		old_device = nm_g_object_ref (priv->parent_device.obj);
		nm_dbus_track_obj_path_set (&priv->parent_device, parent_device, TRUE);
		changed = TRUE;
	}

	if (changed) {
		if (priv->parent_ifindex <= 0)
			_LOGD (LOGD_DEVICE, "parent: clear");
		else if (!priv->parent_device.obj)
			_LOGD (LOGD_DEVICE, "parent: ifindex %d, no device", priv->parent_ifindex);
		else {
			_LOGD (LOGD_DEVICE, "parent: ifindex %d, device %p, %s", priv->parent_ifindex,
			       priv->parent_device.obj, nm_device_get_iface (priv->parent_device.obj));
		}

		NM_DEVICE_GET_CLASS (self)->parent_changed_notify (self, old_ifindex, old_device, priv->parent_ifindex, priv->parent_device.obj);
	}
	return changed;
}

void
nm_device_parent_set_ifindex (NMDevice *self,
                              int parent_ifindex)
{
	_parent_set_ifindex (self, parent_ifindex, FALSE);
}

gboolean
nm_device_parent_notify_changed (NMDevice *self,
                                 NMDevice *change_candidate,
                                 gboolean device_removed)
{
	NMDevicePrivate *priv;

	nm_assert (NM_IS_DEVICE (self));
	nm_assert (NM_IS_DEVICE (change_candidate));

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->parent_ifindex > 0) {
		if (   priv->parent_device.obj == change_candidate
		    || priv->parent_ifindex == nm_device_get_ifindex (change_candidate))
			return _parent_set_ifindex (self, priv->parent_ifindex, device_removed);
	}
	return FALSE;
}

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

const char *
nm_device_parent_find_for_connection (NMDevice *self,
                                      const char *current_setting_parent)
{
	const char *new_parent;
	NMDevice *parent_device;

	parent_device = nm_device_parent_get_device (self);
	if (!parent_device)
		return NULL;

	new_parent = nm_device_get_iface (parent_device);
	if (!new_parent)
		return NULL;

	if (   current_setting_parent
	    && !nm_streq (current_setting_parent, new_parent)
	    && nm_utils_is_uuid (current_setting_parent)) {
		NMSettingsConnection *parent_connection;

		/* Don't change a parent specified by UUID if it's still valid */
		parent_connection = nm_settings_get_connection_by_uuid (nm_device_get_settings (self),
		                                                        current_setting_parent);
		if (   parent_connection
		    && nm_device_check_connection_compatible (parent_device,
		                                              nm_settings_connection_get_connection (parent_connection),
		                                              NULL))
			return current_setting_parent;
	}

	return new_parent;
}

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

static void
_stats_update_counters (NMDevice *self,
                        guint64 tx_bytes,
                        guint64 rx_bytes)
{
	NMDevicePrivate *priv;
	gboolean tx_changed = FALSE;
	gboolean rx_changed = FALSE;

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->stats.tx_bytes != tx_bytes) {
		priv->stats.tx_bytes = tx_bytes;
		tx_changed = TRUE;
	}
	if (priv->stats.rx_bytes != rx_bytes) {
		priv->stats.rx_bytes = rx_bytes;
		rx_changed = TRUE;
	}

	nm_gobject_notify_together (self,
	                            tx_changed ? PROP_STATISTICS_TX_BYTES : PROP_0,
	                            rx_changed ? PROP_STATISTICS_RX_BYTES : PROP_0);
}

static void
_stats_update_counters_from_pllink (NMDevice *self, const NMPlatformLink *pllink)
{
	_stats_update_counters (self, pllink->tx_bytes, pllink->rx_bytes);
}

static gboolean
_stats_timeout_cb (gpointer user_data)
{
	NMDevice *self = user_data;
	int ifindex;

	ifindex = nm_device_get_ip_ifindex (self);

	_LOGT (LOGD_DEVICE, "stats: refresh %d", ifindex);

	if (ifindex > 0)
		nm_platform_link_refresh (nm_device_get_platform (self), ifindex);

	return G_SOURCE_CONTINUE;
}

static guint
_stats_refresh_rate_real (guint refresh_rate_ms)
{
	const guint STATS_REFRESH_RATE_MS_MIN = 200;

	if (refresh_rate_ms == 0)
		return 0;

	if (refresh_rate_ms < STATS_REFRESH_RATE_MS_MIN) {
		/* you cannot set the refresh-rate arbitrarily small. E.g.
		 * setting to 1ms is just killing. Have a lowest number. */
		return STATS_REFRESH_RATE_MS_MIN;
	}

	return refresh_rate_ms;
}

static void
_stats_set_refresh_rate (NMDevice *self, guint refresh_rate_ms)
{
	NMDevicePrivate *priv;
	int ifindex;
	guint old_rate;

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->stats.refresh_rate_ms == refresh_rate_ms)
		return;

	old_rate = priv->stats.refresh_rate_ms;
	priv->stats.refresh_rate_ms = refresh_rate_ms;
	_notify (self, PROP_STATISTICS_REFRESH_RATE_MS);

	_LOGD (LOGD_DEVICE, "stats: set refresh to %u ms", priv->stats.refresh_rate_ms);

	if (!nm_device_is_real (self))
		return;

	refresh_rate_ms = _stats_refresh_rate_real (refresh_rate_ms);
	if (_stats_refresh_rate_real (old_rate) == refresh_rate_ms)
		return;

	nm_clear_g_source (&priv->stats.timeout_id);

	if (!refresh_rate_ms)
		return;

	/* trigger an initial refresh of the data whenever the refresh-rate changes.
	 * As we process the result in an idle handler with device_link_changed(),
	 * we don't get the result right away. */
	ifindex = nm_device_get_ip_ifindex (self);
	if (ifindex > 0)
		nm_platform_link_refresh (nm_device_get_platform (self), ifindex);

	priv->stats.timeout_id = g_timeout_add (refresh_rate_ms, _stats_timeout_cb, self);
}

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

static gboolean
get_ip_iface_identifier (NMDevice *self, NMUtilsIPv6IfaceId *out_iid)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMPlatform *platform = nm_device_get_platform (self);
	const NMPlatformLink *pllink;
	const guint8 *hwaddr;
	guint8 pseudo_hwaddr[ETH_ALEN];
	gsize hwaddr_len;
	int ifindex;
	gboolean success;

	/* If we get here, we *must* have a kernel netdev, which implies an ifindex */
	ifindex = nm_device_get_ip_ifindex (self);
	g_return_val_if_fail (ifindex > 0, FALSE);

	pllink = nm_platform_link_get (platform, ifindex);
	if (   !pllink
	    || NM_IN_SET (pllink->type, NM_LINK_TYPE_NONE, NM_LINK_TYPE_UNKNOWN))
		return FALSE;

	hwaddr = nmp_link_address_get (&pllink->l_address, &hwaddr_len);
	if (hwaddr_len <= 0)
		return FALSE;

	if (pllink->type == NM_LINK_TYPE_6LOWPAN) {
		/* If the underlying IEEE 802.15.4 device has a short address we generate
		 * a "pseudo 48-bit address" that's to be used in the same fashion as a
		 * wired Ethernet address. The mechanism is specified in Section 6. of
		 * RFC 4944 */
		guint16 pan_id;
		guint16 short_addr;

		short_addr = nm_platform_wpan_get_short_addr (platform, pllink->parent);
		if (short_addr != G_MAXUINT16) {
			pan_id = nm_platform_wpan_get_pan_id (platform, pllink->parent);
			pseudo_hwaddr[0] = short_addr & 0xff;
			pseudo_hwaddr[1] = (short_addr >> 8) & 0xff;
			pseudo_hwaddr[2] = 0;
			pseudo_hwaddr[3] = 0;
			pseudo_hwaddr[4] = pan_id & 0xff;
			pseudo_hwaddr[5] = (pan_id >> 8) & 0xff;

			hwaddr = pseudo_hwaddr;
			hwaddr_len = G_N_ELEMENTS (pseudo_hwaddr);
		}
	}

	success = nm_utils_get_ipv6_interface_identifier (pllink->type,
	                                                  hwaddr,
	                                                  hwaddr_len,
	                                                  priv->dev_id,
	                                                  out_iid);
	if (!success) {
		_LOGW (LOGD_PLATFORM, "failed to generate interface identifier "
		       "for link type %u hwaddr_len %zu", pllink->type, hwaddr_len);
	}
	return success;
}

/**
 * nm_device_get_ip_iface_identifier:
 * @self: an #NMDevice
 * @iid: where to place the interface identifier
 * @ignore_token: force creation of a non-tokenized address
 *
 * Return the interface's identifier for the EUI64 address generation mode.
 * It's either a manually set token or and identifier generated in a
 * hardware-specific way.
 *
 * Unless @ignore_token is set the token is preferred. That is the case
 * for link-local addresses (to mimic kernel behavior).
 *
 * Returns: #TRUE if the @iid could be set
 */
static gboolean
nm_device_get_ip_iface_identifier (NMDevice *self, NMUtilsIPv6IfaceId *iid, gboolean ignore_token)
{
	NMSettingIP6Config *s_ip6;
	const char *token = NULL;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	if (!ignore_token) {
		s_ip6 = nm_device_get_applied_setting (self, NM_TYPE_SETTING_IP6_CONFIG);

		g_return_val_if_fail (s_ip6, FALSE);

		token = nm_setting_ip6_config_get_token (s_ip6);
	}
	if (token)
		return nm_utils_ipv6_interface_identifier_get_from_token (iid, token);
	else
		return NM_DEVICE_GET_CLASS (self)->get_ip_iface_identifier (self, iid);
}

const char *
nm_device_get_driver (NMDevice *self)
{
	g_return_val_if_fail (self != NULL, NULL);

	return NM_DEVICE_GET_PRIVATE (self)->driver;
}

const char *
nm_device_get_driver_version (NMDevice *self)
{
	g_return_val_if_fail (self != NULL, NULL);

	return NM_DEVICE_GET_PRIVATE (self)->driver_version;
}

NMDeviceType
nm_device_get_device_type (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), NM_DEVICE_TYPE_UNKNOWN);

	return NM_DEVICE_GET_PRIVATE (self)->type;
}

NMLinkType
nm_device_get_link_type (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), NM_LINK_TYPE_UNKNOWN);

	return NM_DEVICE_GET_PRIVATE (self)->link_type;
}

/**
 * nm_device_get_metered:
 * @setting: the #NMDevice
 *
 * Returns: the #NMDevice:metered property of the device.
 *
 * Since: 1.2
 **/
NMMetered
nm_device_get_metered (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), NM_METERED_UNKNOWN);

	return NM_DEVICE_GET_PRIVATE (self)->metered;
}

guint32
nm_device_get_route_metric_default (NMDeviceType device_type)
{
	/* Device 'priority' is used for the default route-metric and is based on
	 * the device type. The settings ipv4.route-metric and ipv6.route-metric
	 * can overwrite this default.
	 *
	 * For both IPv4 and IPv6 we use the same default values.
	 *
	 * The route-metric is used for the metric of the routes of device.
	 * This also applies to the default route. Therefore it affects also
	 * which device is the "best".
	 *
	 * For comparison, note that iproute2 by default adds IPv4 routes with
	 * metric 0, and IPv6 routes with metric 1024. The latter is the IPv6
	 * "user default" in the kernel (NM_PLATFORM_ROUTE_METRIC_DEFAULT_IP6).
	 * In kernel, the full uint32_t range is available for route
	 * metrics (except for IPv6, where 0 means 1024).
	 */

	switch (device_type) {

	/* 50 is also used for VPN plugins (NM_VPN_ROUTE_METRIC_DEFAULT).
	 *
	 * Note that returning 50 from this function means that this device-type is
	 * in some aspects a VPN. */
	case NM_DEVICE_TYPE_WIREGUARD:
		return NM_VPN_ROUTE_METRIC_DEFAULT;

	case NM_DEVICE_TYPE_ETHERNET:
	case NM_DEVICE_TYPE_VETH:
		return 100;
	case NM_DEVICE_TYPE_MACSEC:
		return 125;
	case NM_DEVICE_TYPE_INFINIBAND:
		return 150;
	case NM_DEVICE_TYPE_ADSL:
		return 200;
	case NM_DEVICE_TYPE_WIMAX:
		return 250;
	case NM_DEVICE_TYPE_BOND:
		return 300;
	case NM_DEVICE_TYPE_TEAM:
		return 350;
	case NM_DEVICE_TYPE_VLAN:
		return 400;
	case NM_DEVICE_TYPE_MACVLAN:
		return 410;
	case NM_DEVICE_TYPE_BRIDGE:
		return 425;
	case NM_DEVICE_TYPE_TUN:
		return 450;
	case NM_DEVICE_TYPE_PPP:
		return 460;
	case NM_DEVICE_TYPE_VRF:
		return 470;
	case NM_DEVICE_TYPE_VXLAN:
		return 500;
	case NM_DEVICE_TYPE_DUMMY:
		return 550;
	case NM_DEVICE_TYPE_WIFI:
		return 600;
	case NM_DEVICE_TYPE_OLPC_MESH:
		return 650;
	case NM_DEVICE_TYPE_IP_TUNNEL:
		return 675;
	case NM_DEVICE_TYPE_MODEM:
		return 700;
	case NM_DEVICE_TYPE_BT:
		return 750;
	case NM_DEVICE_TYPE_6LOWPAN:
		return 775;
	case NM_DEVICE_TYPE_OVS_BRIDGE:
	case NM_DEVICE_TYPE_OVS_INTERFACE:
	case NM_DEVICE_TYPE_OVS_PORT:
		return 800;
	case NM_DEVICE_TYPE_WPAN:
		return 850;
	case NM_DEVICE_TYPE_WIFI_P2P:
	case NM_DEVICE_TYPE_GENERIC:
		return 950;
	case NM_DEVICE_TYPE_UNKNOWN:
		return 10000;
	case NM_DEVICE_TYPE_UNUSED1:
	case NM_DEVICE_TYPE_UNUSED2:
		/* omit default: to get compiler warning about missing switch cases */
		break;
	}
	return 11000;
}

static gboolean
default_route_metric_penalty_detect (NMDevice *self, int addr_family)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	/* currently we don't differentiate between IPv4 and IPv6 when detecting
	 * connectivity. */
	if (   priv->concheck_x[IS_IPv4].state != NM_CONNECTIVITY_FULL
	    && nm_connectivity_check_enabled (concheck_get_mgr (self)))
		return TRUE;

	return FALSE;
}

static guint32
default_route_metric_penalty_get (NMDevice *self, int addr_family)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	nm_assert_addr_family (addr_family);

	if (  addr_family == AF_INET
	    ? priv->default_route_metric_penalty_ip4_has
	    : priv->default_route_metric_penalty_ip6_has)
		return 20000;
	return 0;
}

guint32
nm_device_get_route_metric (NMDevice *self,
                            int addr_family)
{
	gint64 route_metric;
	NMSettingIPConfig *s_ip;
	NMConnection *connection;
	const char *property;

	g_return_val_if_fail (NM_IS_DEVICE (self), G_MAXUINT32);
	g_return_val_if_fail (NM_IN_SET (addr_family, AF_INET, AF_INET6), G_MAXUINT32);

	connection = nm_device_get_applied_connection (self);
	if (connection) {
		s_ip = nm_connection_get_setting_ip_config (connection, addr_family);

		/* Slave interfaces don't have IP settings, but we may get here when
		 * external changes are made or when noticing IP changes when starting
		 * the slave connection.
		 */
		if (s_ip) {
			route_metric = nm_setting_ip_config_get_route_metric (s_ip);
			if (route_metric >= 0)
				goto out;
		}
	}

	/* use the current NMConfigData, which makes this configuration reloadable.
	 * Note that that means that the route-metric might change between SIGHUP.
	 * You must cache the returned value if that is a problem. */
	property = addr_family == AF_INET
	    ? NM_CON_DEFAULT ("ipv4.route-metric")
	    : NM_CON_DEFAULT ("ipv6.route-metric");
	route_metric = nm_config_data_get_connection_default_int64 (NM_CONFIG_GET_DATA,
	                                                            property,
	                                                            self,
	                                                            0, G_MAXUINT32, -1);
	if (route_metric >= 0)
		goto out;

	route_metric = nm_manager_device_route_metric_reserve (NM_MANAGER_GET,
	                                                       nm_device_get_ip_ifindex (self),
	                                                       nm_device_get_device_type (self));
out:
	return nm_utils_ip_route_metric_normalize (addr_family, route_metric);
}

static NMSettingConnectionMdns
_get_mdns (NMDevice *self)
{
	NMConnection *connection;
	NMSettingConnectionMdns mdns = NM_SETTING_CONNECTION_MDNS_DEFAULT;

	g_return_val_if_fail (NM_IS_DEVICE (self), NM_SETTING_CONNECTION_MDNS_DEFAULT);

	connection = nm_device_get_applied_connection (self);
	if (connection)
		mdns = nm_setting_connection_get_mdns (nm_connection_get_setting_connection (connection));
	if (mdns != NM_SETTING_CONNECTION_MDNS_DEFAULT)
		return mdns;

	return nm_config_data_get_connection_default_int64 (NM_CONFIG_GET_DATA,
	                                                    NM_CON_DEFAULT ("connection.mdns"),
	                                                    self,
	                                                    NM_SETTING_CONNECTION_MDNS_NO,
	                                                    NM_SETTING_CONNECTION_MDNS_YES,
	                                                    NM_SETTING_CONNECTION_MDNS_DEFAULT);
}

static NMSettingConnectionLlmnr
_get_llmnr (NMDevice *self)
{
	NMConnection *connection;
	NMSettingConnectionLlmnr llmnr = NM_SETTING_CONNECTION_LLMNR_DEFAULT;

	g_return_val_if_fail (NM_IS_DEVICE (self), NM_SETTING_CONNECTION_LLMNR_DEFAULT);

	connection = nm_device_get_applied_connection (self);
	if (connection)
		llmnr = nm_setting_connection_get_llmnr (nm_connection_get_setting_connection (connection));
	if (llmnr != NM_SETTING_CONNECTION_LLMNR_DEFAULT)
		return llmnr;

	return nm_config_data_get_connection_default_int64 (NM_CONFIG_GET_DATA,
	                                                    NM_CON_DEFAULT ("connection.llmnr"),
	                                                    self,
	                                                    NM_SETTING_CONNECTION_LLMNR_NO,
	                                                    NM_SETTING_CONNECTION_LLMNR_YES,
	                                                    NM_SETTING_CONNECTION_LLMNR_DEFAULT);
}

static guint32
_get_route_table (NMDevice *self,
                  int addr_family)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMDeviceClass *klass;
	NMConnection *connection;
	NMSettingIPConfig *s_ip;
	guint32 route_table = 0;
	gboolean is_user_config = TRUE;
	NMSettingConnection *s_con;
	NMSettingVrf *s_vrf;

	nm_assert_addr_family (addr_family);

	/* the route table setting affects how we sync routes. We shall
	 * not change it while the device is active, hence, cache it. */
	if (addr_family == AF_INET) {
		if (priv->v4_route_table_initialized)
			return priv->v4_route_table;
	} else {
		if (priv->v6_route_table_initialized)
			return priv->v6_route_table;
	}

	connection = nm_device_get_applied_connection (self);
	if (connection) {
		s_ip = nm_connection_get_setting_ip_config (connection, addr_family);
		if (s_ip)
			route_table = nm_setting_ip_config_get_route_table (s_ip);
	}
	if (route_table == 0u) {
		gint64 v;

		v = nm_config_data_get_connection_default_int64 (NM_CONFIG_GET_DATA,
		                                                   addr_family == AF_INET
		                                                 ? NM_CON_DEFAULT ("ipv4.route-table")
		                                                 : NM_CON_DEFAULT ("ipv6.route-table"),
		                                                 self,
		                                                 0,
		                                                 G_MAXUINT32,
		                                                 -1);
		if (v != -1) {
			route_table = v;
			is_user_config = FALSE;
		}
	}

	if (   route_table == 0u
	    && connection
	    && (s_con = nm_connection_get_setting_connection (connection))
	    && (nm_streq0 (nm_setting_connection_get_slave_type (s_con), NM_SETTING_VRF_SETTING_NAME)
	    && priv->master
	    && nm_device_get_device_type (priv->master) == NM_DEVICE_TYPE_VRF)) {
		const NMPlatformLnkVrf *lnk;

		lnk = nm_platform_link_get_lnk_vrf (nm_device_get_platform (self),
		                                    nm_device_get_ifindex (priv->master),
		                                    NULL);

		if (lnk)
			route_table = lnk->table;
	}

	if (   route_table == 0u
	    && connection
	    && (s_vrf = (NMSettingVrf *) nm_connection_get_setting (connection, NM_TYPE_SETTING_VRF))) {
		route_table = nm_setting_vrf_get_table (s_vrf);
	}

	klass = NM_DEVICE_GET_CLASS (self);
	if (klass->coerce_route_table)
		route_table = klass->coerce_route_table (self, addr_family, route_table, is_user_config);

	if (addr_family == AF_INET) {
		priv->v4_route_table_initialized = TRUE;
		priv->v4_route_table = route_table;
	} else {
		priv->v6_route_table_initialized = TRUE;
		priv->v6_route_table = route_table;
	}

	_LOGT (LOGD_DEVICE,
	       "ipv%c.route-table = %u%s",
	       addr_family == AF_INET ? '4' : '6',
	       (guint) (route_table ?: RT_TABLE_MAIN),
	       route_table != 0u ? "" : " (policy routing not enabled)");

	return route_table;
}

guint32
nm_device_get_route_table (NMDevice *self,
                           int addr_family)
{
	guint32 route_table;

	g_return_val_if_fail (NM_IS_DEVICE (self), RT_TABLE_MAIN);

	route_table = _get_route_table (self, addr_family);
	return route_table ?: (guint32) RT_TABLE_MAIN;
}

static NMIPRouteTableSyncMode
_get_route_table_sync_mode_stateful (NMDevice *self,
                                     int addr_family)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMDedupMultiIter ipconf_iter;
	gboolean all_sync_now;
	gboolean all_sync_eff;

	all_sync_now = _get_route_table (self, addr_family) != 0u;

	if (!all_sync_now) {
		/* If there's a local route switch to all-sync in order
		 * to properly manage the local table */
		if (addr_family == AF_INET) {
			const NMPlatformIP4Route *route;

			nm_ip_config_iter_ip4_route_for_each (&ipconf_iter, priv->con_ip_config_4, &route) {
				if (nm_platform_route_type_uncoerce (route->type_coerced) == RTN_LOCAL) {
					all_sync_now = TRUE;
					break;
				}
			}
		} else {
			const NMPlatformIP6Route *route;

			nm_ip_config_iter_ip6_route_for_each (&ipconf_iter, priv->con_ip_config_6, &route) {
				if (nm_platform_route_type_uncoerce (route->type_coerced) == RTN_LOCAL) {
					all_sync_now = TRUE;
					break;
				}
			}
		}
	}

	if (all_sync_now)
		all_sync_eff = TRUE;
	else {
		/* When we change from all-sync to no all-sync, we do a last all-sync one
		 * more time. For that, we determine the effective all-state based on the
		 * cached/previous all-sync flag.
		 *
		 * The purpose of this is to support reapply of route-table (and thus the
		 * all-sync mode). If reapply toggles from all-sync to no-all-sync, we must
		 * sync one last time. */
		if (addr_family == AF_INET)
			all_sync_eff = priv->v4_route_table_all_sync_before;
		else
			all_sync_eff = priv->v6_route_table_all_sync_before;
	}

	if (addr_family == AF_INET)
		priv->v4_route_table_all_sync_before = all_sync_now;
	else
		priv->v6_route_table_all_sync_before = all_sync_now;

	return   all_sync_eff
	       ? NM_IP_ROUTE_TABLE_SYNC_MODE_ALL
	       : NM_IP_ROUTE_TABLE_SYNC_MODE_MAIN;
}

const NMPObject *
nm_device_get_best_default_route (NMDevice *self,
                                  int addr_family)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	switch (addr_family) {
	case AF_INET:
		return priv->ip_config_4 ? nm_ip4_config_best_default_route_get (priv->ip_config_4) : NULL;
	case AF_INET6:
		return priv->ip_config_6 ? nm_ip6_config_best_default_route_get (priv->ip_config_6) : NULL;
	case AF_UNSPEC:
		return    (priv->ip_config_4 ? nm_ip4_config_best_default_route_get (priv->ip_config_4) : NULL)
		       ?: (priv->ip_config_6 ? nm_ip6_config_best_default_route_get (priv->ip_config_6) : NULL);
	default:
		g_return_val_if_reached (NULL);
	}
}

const char *
nm_device_get_type_desc (NMDevice *self)
{
	g_return_val_if_fail (self != NULL, NULL);

	return NM_DEVICE_GET_PRIVATE (self)->type_desc;
}

const char *
nm_device_get_type_description (NMDevice *self)
{
	g_return_val_if_fail (self != NULL, NULL);

	/* Beware: this function should return the same
	 * value as nm_device_get_type_description() in libnm. */

	return NM_DEVICE_GET_CLASS (self)->get_type_description (self);
}

static const char *
get_type_description (NMDevice *self)
{
	NMDeviceClass *klass;

	nm_assert (NM_IS_DEVICE (self));

	/* the default implementation for the description just returns the (modified)
	 * class name and depends entirely on the type of self. Note that we cache the
	 * description in the klass itself.
	 *
	 * Also note, that as the GObject class gets inited, it inherrits the fields
	 * of the parent class. That means, if NMDeviceVethClass was initialized after
	 * NMDeviceEthernetClass already has the description cached in the class
	 * (because we already fetched the description for an ethernet device),
	 * then default_type_description will wrongly contain "ethernet".
	 * To avoid that, and catch the situation, also cache the klass for
	 * which the description was cached. If that doesn't match, it was
	 * inherited and we need to reset it. */
	klass = NM_DEVICE_GET_CLASS (self);
	if (G_UNLIKELY (klass->default_type_description_klass != klass)) {
		const char *typename;
		gs_free char *s = NULL;

		typename = G_OBJECT_TYPE_NAME (self);
		if (g_str_has_prefix (typename, "NMDevice"))
			typename += 8;
		s = g_ascii_strdown (typename, -1);
		klass->default_type_description = g_intern_string (s);
		klass->default_type_description_klass = klass;
	}

	nm_assert (klass->default_type_description);
	return klass->default_type_description;
}

gboolean
nm_device_has_carrier (NMDevice *self)
{
	return NM_DEVICE_GET_PRIVATE (self)->carrier;
}

NMActRequest *
nm_device_get_act_request (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), NULL);

	return NM_DEVICE_GET_PRIVATE (self)->act_request.obj;
}

NMActivationStateFlags
nm_device_get_activation_state_flags (NMDevice *self)
{
	NMActRequest *ac;

	g_return_val_if_fail (NM_IS_DEVICE (self), NM_ACTIVATION_STATE_FLAG_NONE);

	ac = NM_DEVICE_GET_PRIVATE (self)->act_request.obj;
	if (!ac)
		return NM_ACTIVATION_STATE_FLAG_NONE;
	return nm_active_connection_get_state_flags (NM_ACTIVE_CONNECTION (ac));
}

NMSettingsConnection *
nm_device_get_settings_connection (NMDevice *self)
{
	NMDevicePrivate *priv;

	g_return_val_if_fail (NM_IS_DEVICE (self), NULL);

	priv = NM_DEVICE_GET_PRIVATE (self);

	return priv->act_request.obj ? nm_act_request_get_settings_connection (priv->act_request.obj) : NULL;
}

NMConnection *
nm_device_get_settings_connection_get_connection (NMDevice *self)
{
	NMSettingsConnection *sett_con;
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (!priv->act_request.obj)
		return NULL;

	sett_con = nm_act_request_get_settings_connection (priv->act_request.obj);
	if (!sett_con)
		return NULL;

	return nm_settings_connection_get_connection (sett_con);
}

NMConnection *
nm_device_get_applied_connection (NMDevice *self)
{
	NMDevicePrivate *priv;

	g_return_val_if_fail (NM_IS_DEVICE (self), NULL);

	priv = NM_DEVICE_GET_PRIVATE (self);

	return priv->act_request.obj ? nm_act_request_get_applied_connection (priv->act_request.obj) : NULL;
}

gboolean
nm_device_has_unmodified_applied_connection (NMDevice *self, NMSettingCompareFlags compare_flags)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (!priv->act_request.obj)
		return FALSE;

	return nm_active_connection_has_unmodified_applied_connection ((NMActiveConnection *) priv->act_request.obj, compare_flags);
}

gpointer
nm_device_get_applied_setting (NMDevice *self, GType setting_type)
{
	NMConnection *connection;

	connection = nm_device_get_applied_connection (self);
	return connection ? nm_connection_get_setting (connection, setting_type) : NULL;
}

RfKillType
nm_device_get_rfkill_type (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	return NM_DEVICE_GET_PRIVATE (self)->rfkill_type;
}

static const char *
nm_device_get_physical_port_id (NMDevice *self)
{
	return NM_DEVICE_GET_PRIVATE (self)->physical_port_id;
}

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

typedef enum {
	CONCHECK_SCHEDULE_UPDATE_INTERVAL,
	CONCHECK_SCHEDULE_UPDATE_INTERVAL_RESTART,
	CONCHECK_SCHEDULE_CHECK_EXTERNAL,
	CONCHECK_SCHEDULE_CHECK_PERIODIC,
	CONCHECK_SCHEDULE_RETURNED_MIN,
	CONCHECK_SCHEDULE_RETURNED_BUMP,
	CONCHECK_SCHEDULE_RETURNED_MAX,
} ConcheckScheduleMode;

static NMDeviceConnectivityHandle *concheck_start (NMDevice *self,
                                                   int addr_family,
                                                   NMDeviceConnectivityCallback callback,
                                                   gpointer user_data,
                                                   gboolean is_periodic);

static void concheck_periodic_schedule_set (NMDevice *self,
                                            int addr_family,
                                            ConcheckScheduleMode mode);

static gboolean
_concheck_periodic_timeout_cb (NMDevice *self, int addr_family)
{
	_LOGt (LOGD_CONCHECK, "connectivity: [IPv%c] periodic timeout",
	       nm_utils_addr_family_to_char (addr_family));
	concheck_periodic_schedule_set (self, addr_family, CONCHECK_SCHEDULE_CHECK_PERIODIC);
	return G_SOURCE_REMOVE;
}

static gboolean
concheck_ip4_periodic_timeout_cb (gpointer user_data)
{
	return _concheck_periodic_timeout_cb (user_data, AF_INET);
}

static gboolean
concheck_ip6_periodic_timeout_cb (gpointer user_data)
{
	return _concheck_periodic_timeout_cb (user_data, AF_INET6);
}

static gboolean
concheck_is_possible (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (   !nm_device_is_real (self)
	    || is_loopback (self))
		return FALSE;

	/* we enable periodic checks for every device state (except UNKNOWN). Especially with
	 * unmanaged devices, it is interesting to know whether we have connectivity on that device. */
	if (priv->state == NM_DEVICE_STATE_UNKNOWN)
		return FALSE;

	return TRUE;
}

static gboolean
concheck_periodic_schedule_do (NMDevice *self, int addr_family, gint64 now_ns)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gboolean periodic_check_disabled = FALSE;
	gint64 expiry, tdiff;
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	/* we always cancel whatever was pending. */
	if (nm_clear_g_source (&priv->concheck_x[IS_IPv4].p_cur_id))
		periodic_check_disabled = TRUE;

	if (priv->concheck_x[IS_IPv4].p_max_interval == 0) {
		/* periodic checks are disabled */
		goto out;
	}

	if (!concheck_is_possible (self))
		goto out;

	nm_assert (now_ns > 0);
	nm_assert (priv->concheck_x[IS_IPv4].p_cur_interval > 0);

	/* we schedule the timeout based on our current settings cur-interval and cur-basetime.
	 * Before calling concheck_periodic_schedule_do(), make sure that these properties are
	 * correct. */

	expiry = priv->concheck_x[IS_IPv4].p_cur_basetime_ns + (priv->concheck_x[IS_IPv4].p_cur_interval * NM_UTILS_NSEC_PER_SEC);
	tdiff = expiry - now_ns;

	_LOGT (LOGD_CONCHECK, "connectivity: [IPv%c] periodic-check: %sscheduled in %lld milliseconds (%u seconds interval)",
	       nm_utils_addr_family_to_char (addr_family),
	       periodic_check_disabled ? "re-" : "",
	       (long long) (tdiff / NM_UTILS_NSEC_PER_MSEC),
	       priv->concheck_x[IS_IPv4].p_cur_interval);

	priv->concheck_x[IS_IPv4].p_cur_id =
		g_timeout_add (NM_MAX ((gint64) 0, tdiff) / NM_UTILS_NSEC_PER_MSEC,
	                       IS_IPv4 ? concheck_ip4_periodic_timeout_cb : concheck_ip6_periodic_timeout_cb,
	                       self);
	return TRUE;
out:
	if (periodic_check_disabled) {
		_LOGT (LOGD_CONCHECK, "connectivity: [IPv%c] periodic-check: unscheduled",
		       nm_utils_addr_family_to_char (addr_family));
	}
	return FALSE;
}

#define CONCHECK_P_PROBE_INTERVAL 1

static void
concheck_periodic_schedule_set (NMDevice *self, int addr_family, ConcheckScheduleMode mode)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gint64 new_expiry, exp_expiry, cur_expiry, tdiff;
	gint64 now_ns = 0;
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	if (priv->concheck_x[IS_IPv4].p_max_interval == 0) {
		/* periodic check is disabled. Nothing to do. */
		return;
	}

	if (!priv->concheck_x[IS_IPv4].p_cur_id) {
		/* we currently don't have a timeout scheduled. No need to reschedule
		 * another one... */
		if (NM_IN_SET (mode, CONCHECK_SCHEDULE_UPDATE_INTERVAL,
		                     CONCHECK_SCHEDULE_UPDATE_INTERVAL_RESTART)) {
			/* ... unless, we are about to start periodic checks after update-interval.
			 * In this case, fall through and restart the periodic checks below. */
			mode = CONCHECK_SCHEDULE_UPDATE_INTERVAL_RESTART;
		} else
			return;
	}

	switch (mode) {
	case CONCHECK_SCHEDULE_UPDATE_INTERVAL_RESTART:
		priv->concheck_x[IS_IPv4].p_cur_interval = NM_MIN (priv->concheck_x[IS_IPv4].p_max_interval, CONCHECK_P_PROBE_INTERVAL);
		priv->concheck_x[IS_IPv4].p_cur_basetime_ns = nm_utils_get_monotonic_timestamp_nsec_cached (&now_ns);
		if (concheck_periodic_schedule_do (self, addr_family, now_ns))
			concheck_start (self, addr_family, NULL, NULL, TRUE);
		return;

	case CONCHECK_SCHEDULE_UPDATE_INTERVAL:
		/* called with "UPDATE_INTERVAL" and already have a p_cur_id scheduled. */

		nm_assert (priv->concheck_x[IS_IPv4].p_max_interval > 0);
		nm_assert (priv->concheck_x[IS_IPv4].p_cur_interval > 0);

		if (priv->concheck_x[IS_IPv4].p_cur_interval <= priv->concheck_x[IS_IPv4].p_max_interval) {
			/* we currently have a shorter interval set, than what we now have. Either,
			 * because we are probing, or because the previous max interval was shorter.
			 *
			 * Either way, the current timer is set just fine. Nothing to do, we will
			 * probe our way up. */
			return;
		}

		cur_expiry = priv->concheck_x[IS_IPv4].p_cur_basetime_ns + (priv->concheck_x[IS_IPv4].p_max_interval * NM_UTILS_NSEC_PER_SEC);
		nm_utils_get_monotonic_timestamp_nsec_cached (&now_ns);

		priv->concheck_x[IS_IPv4].p_cur_interval = priv->concheck_x[IS_IPv4].p_max_interval;
		if (cur_expiry <= now_ns) {
			/* Since the last time we scheduled a periodic check, already more than the
			 * new max_interval passed. We need to start a check right away (and
			 * schedule a timeout in cur-interval in the future). */
			priv->concheck_x[IS_IPv4].p_cur_basetime_ns = now_ns;
			if (concheck_periodic_schedule_do (self, addr_family, now_ns))
				concheck_start (self, addr_family, NULL, NULL, TRUE);
		} else {
			/* we are reducing the max-interval to a shorter interval that we have currently
			 * scheduled (with cur_interval).
			 *
			 * However, since the last time we scheduled the check, not even the new max-interval
			 * expired. All we need to do, is reschedule the timer to expire sooner. The cur_basetime
			 * is unchanged. */
			concheck_periodic_schedule_do (self, addr_family, now_ns);
		}
		return;

	case CONCHECK_SCHEDULE_CHECK_EXTERNAL:
		/* a external connectivity check delays our periodic check. We reset the counter. */
		priv->concheck_x[IS_IPv4].p_cur_basetime_ns = nm_utils_get_monotonic_timestamp_nsec_cached (&now_ns);
		concheck_periodic_schedule_do (self, addr_family, now_ns);
		return;

	case CONCHECK_SCHEDULE_CHECK_PERIODIC:
	{
		gboolean any_periodic_pending;
		NMDeviceConnectivityHandle *handle;
		guint old_interval = priv->concheck_x[IS_IPv4].p_cur_interval;

		any_periodic_pending = FALSE;
		c_list_for_each_entry (handle, &priv->concheck_lst_head, concheck_lst) {
			if (handle->addr_family != addr_family)
				continue;
			if (handle->is_periodic_bump) {
				handle->is_periodic_bump = FALSE;
				handle->is_periodic_bump_on_complete = FALSE;
				any_periodic_pending = TRUE;
			}
		}
		if (any_periodic_pending) {
			/* we reached a timeout to schedule a new periodic request, however we still
			 * have period requests pending that didn't complete yet. We need to bump the
			 * interval already. */
			priv->concheck_x[IS_IPv4].p_cur_interval = NM_MIN (old_interval * 2, priv->concheck_x[IS_IPv4].p_max_interval);
		}

		/* we just reached a timeout. The expected expiry (exp_expiry) should be
		 * pretty close to now_ns.
		 *
		 * We want to reschedule the timeout at exp_expiry (aka now) + cur_interval. */
		nm_utils_get_monotonic_timestamp_nsec_cached (&now_ns);
		exp_expiry = priv->concheck_x[IS_IPv4].p_cur_basetime_ns + (old_interval * NM_UTILS_NSEC_PER_SEC);
		new_expiry = exp_expiry + (priv->concheck_x[IS_IPv4].p_cur_interval * NM_UTILS_NSEC_PER_SEC);
		tdiff = NM_MAX (new_expiry - now_ns, 0);
		priv->concheck_x[IS_IPv4].p_cur_basetime_ns = (now_ns + tdiff) - (priv->concheck_x[IS_IPv4].p_cur_interval * NM_UTILS_NSEC_PER_SEC);
		if (concheck_periodic_schedule_do (self, addr_family, now_ns)) {
			handle = concheck_start (self, addr_family, NULL, NULL, TRUE);
			if (old_interval != priv->concheck_x[IS_IPv4].p_cur_interval) {
				/* we just bumped the interval already when scheduling this check.
				 * When the handle returns, don't bump a second time.
				 *
				 * But if we reach the timeout again before the handle returns (this
				 * code here) we will still bump the interval. */
				handle->is_periodic_bump_on_complete = FALSE;
			}
		}
		return;
	}

	/* we just got an event that we lost connectivity (that is, concheck returned). We reset
	 * the interval to min/max or increase the probe interval (bump). */
	case CONCHECK_SCHEDULE_RETURNED_MIN:
		priv->concheck_x[IS_IPv4].p_cur_interval = NM_MIN (priv->concheck_x[IS_IPv4].p_max_interval, CONCHECK_P_PROBE_INTERVAL);
		break;
	case CONCHECK_SCHEDULE_RETURNED_MAX:
		priv->concheck_x[IS_IPv4].p_cur_interval = priv->concheck_x[IS_IPv4].p_max_interval;
		break;
	case CONCHECK_SCHEDULE_RETURNED_BUMP:
		priv->concheck_x[IS_IPv4].p_cur_interval = NM_MIN (priv->concheck_x[IS_IPv4].p_cur_interval * 2, priv->concheck_x[IS_IPv4].p_max_interval);
		break;
	}

	/* we are here, because we returned from a connectivity check and adjust the current interval.
	 *
	 * But note that we calculate the new timeout based on the time when we scheduled the
	 * last check, instead of counting from now. The reason is that we want that the times
	 * when we schedule checks be at precise intervals, without including the time it took for
	 * the connectivity check. */
	new_expiry = priv->concheck_x[IS_IPv4].p_cur_basetime_ns + (priv->concheck_x[IS_IPv4].p_cur_interval * NM_UTILS_NSEC_PER_SEC);
	tdiff = NM_MAX (new_expiry - nm_utils_get_monotonic_timestamp_nsec_cached (&now_ns), 0);
	priv->concheck_x[IS_IPv4].p_cur_basetime_ns = now_ns + tdiff - (priv->concheck_x[IS_IPv4].p_cur_interval * NM_UTILS_NSEC_PER_SEC);
	concheck_periodic_schedule_do (self, addr_family, now_ns);
}

static void
concheck_update_interval (NMDevice *self, int addr_family, gboolean check_now)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	guint new_interval;
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	new_interval = nm_connectivity_get_interval (concheck_get_mgr (self));

	new_interval = NM_MIN (new_interval, 7 *24 * 3600);

	if (new_interval != priv->concheck_x[IS_IPv4].p_max_interval) {
		_LOGT (LOGD_CONCHECK, "connectivity: [IPv%c] periodic-check: set interval to %u seconds",
		       nm_utils_addr_family_to_char (addr_family), new_interval);
		priv->concheck_x[IS_IPv4].p_max_interval = new_interval;
	}

	if (!new_interval) {
		/* this will cancel any potentially pending timeout because max-interval is zero.
		 * But it logs a nice message... */
		concheck_periodic_schedule_do (self, addr_family, 0);

		/* also update the fake connectivity state. */
		concheck_update_state (self, addr_family, NM_CONNECTIVITY_FAKE, TRUE);
		return;
	}

	concheck_periodic_schedule_set (self,
	                                addr_family,
	                                check_now
	                                  ? CONCHECK_SCHEDULE_UPDATE_INTERVAL_RESTART
	                                  : CONCHECK_SCHEDULE_UPDATE_INTERVAL);
}

void
nm_device_check_connectivity_update_interval (NMDevice *self)
{
	concheck_update_interval (self, AF_INET, TRUE);
	concheck_update_interval (self, AF_INET6, TRUE);
}

static void
concheck_update_state (NMDevice *self,
                       int addr_family,
                       NMConnectivityState state,
                       gboolean allow_periodic_bump)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	/* @state is a result of the connectivity check. We only expect a precise
	 * number of possible values. */
	nm_assert (NM_IN_SET (state, NM_CONNECTIVITY_LIMITED,
	                             NM_CONNECTIVITY_PORTAL,
	                             NM_CONNECTIVITY_FULL,
	                             NM_CONNECTIVITY_FAKE,
	                             NM_CONNECTIVITY_NONE,
	                             NM_CONNECTIVITY_ERROR));

	if (state == NM_CONNECTIVITY_ERROR) {
		/* on error, we don't change the current connectivity state,
		 * except making UNKNOWN to NONE. */
		state = priv->concheck_x[IS_IPv4].state;
		if (state == NM_CONNECTIVITY_UNKNOWN)
			state = NM_CONNECTIVITY_NONE;
	} else if (state == NM_CONNECTIVITY_FAKE) {
		/* If the connectivity check is disabled and we obtain a fake
		 * result, make an optimistic guess. */
		if (priv->state == NM_DEVICE_STATE_ACTIVATED) {
			/* FIXME: the fake connectivity state depends on the availability of
			 * a default route. However, we have no mechanism that rechecks the
			 * value if a device route appears/disappears after the device
			 * was activated. */
			if (nm_device_get_best_default_route (self, AF_UNSPEC))
				state = NM_CONNECTIVITY_FULL;
			else
				state = NM_CONNECTIVITY_LIMITED;
		} else
			state = NM_CONNECTIVITY_NONE;
	}

	if (priv->concheck_x[IS_IPv4].state == state) {
		/* we got a connectivity update, but the state didn't change. If we were probing,
		 * we bump the probe frequency. */
		if (allow_periodic_bump)
			concheck_periodic_schedule_set (self, addr_family, CONCHECK_SCHEDULE_RETURNED_BUMP);
		return;
	}
	/* we need to update the probe interval before emitting signals. Emitting
	 * a signal might call back into NMDevice and change the probe settings.
	 * So, do that first. */
	if (state == NM_CONNECTIVITY_FULL) {
		/* we reached full connectivity state. Stop probing by setting the
		 * interval to the max. */
		concheck_periodic_schedule_set (self, addr_family, CONCHECK_SCHEDULE_RETURNED_MAX);
	} else if (priv->concheck_x[IS_IPv4].state == NM_CONNECTIVITY_FULL) {
		/* we are about to loose connectivity. (re)start probing by setting
		 * the timeout interval to the min. */
		concheck_periodic_schedule_set (self, addr_family, CONCHECK_SCHEDULE_RETURNED_MIN);
	} else {
		if (allow_periodic_bump)
			concheck_periodic_schedule_set (self, addr_family, CONCHECK_SCHEDULE_RETURNED_BUMP);
	}

	_LOGD (LOGD_CONCHECK, "connectivity state changed from %s to %s",
	       nm_connectivity_state_to_string (priv->concheck_x[IS_IPv4].state),
	       nm_connectivity_state_to_string (state));
	priv->concheck_x[IS_IPv4].state = state;

	_notify (self, IS_IPv4 ? PROP_IP4_CONNECTIVITY : PROP_IP6_CONNECTIVITY);

	if (   priv->state == NM_DEVICE_STATE_ACTIVATED
	    && !nm_device_sys_iface_state_is_external (self)) {
		if (   nm_device_get_best_default_route (self, AF_INET)
		    && !ip_config_merge_and_apply (self, AF_INET, TRUE))
			_LOGW (LOGD_IP4, "Failed to update IPv4 route metric");
		if (   nm_device_get_best_default_route (self, AF_INET6)
		    && !ip_config_merge_and_apply (self, AF_INET6, TRUE))
			_LOGW (LOGD_IP6, "Failed to update IPv6 route metric");
	}
}

static const char *
nm_device_get_effective_ip_config_method (NMDevice *self,
                                          int addr_family)
{
	NMDeviceClass *klass;
	NMConnection *connection = nm_device_get_applied_connection (self);
	const char *method;

	g_return_val_if_fail (NM_IS_CONNECTION (connection), "" /* bogus */);
	nm_assert_addr_family (addr_family);

	method = nm_utils_get_ip_config_method (connection, addr_family);

	if (   (addr_family == AF_INET  && nm_streq (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO))
	    || (addr_family == AF_INET6 && nm_streq (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO))) {
		klass = NM_DEVICE_GET_CLASS (self);
		if (klass->get_auto_ip_config_method) {
			const char *auto_method;

			auto_method = klass->get_auto_ip_config_method (self, addr_family);
			if (auto_method)
				return auto_method;
		}
	}

	return method;
}

static void
concheck_handle_complete (NMDeviceConnectivityHandle *handle, GError *error)
{
	const gboolean IS_IPv4 = (handle->addr_family == AF_INET);

	/* The moment we invoke the callback, we unlink it. It signals
	 * that @handle is handled -- as far as the callee of callback
	 * is concerned. */
	c_list_unlink (&handle->concheck_lst);

	if (handle->c_handle)
		nm_connectivity_check_cancel (handle->c_handle);

	if (handle->callback) {
		handle->callback (handle->self,
		                  handle,
		                  NM_DEVICE_GET_PRIVATE (handle->self)->concheck_x[IS_IPv4].state,
		                  error,
		                  handle->user_data);
	}

	g_slice_free (NMDeviceConnectivityHandle, handle);
}

static void
concheck_cb (NMConnectivity *connectivity,
             NMConnectivityCheckHandle *c_handle,
             NMConnectivityState state,
             gpointer user_data)
{
	_nm_unused gs_unref_object NMDevice *self_keep_alive = NULL;
	NMDevice *self;
	NMDevicePrivate *priv;
	NMDeviceConnectivityHandle *handle;
	NMDeviceConnectivityHandle *other_handle;
	gboolean handle_is_alive;
	gboolean allow_periodic_bump;
	gboolean any_periodic_before;
	gboolean any_periodic_after;
	guint64 seq;

	handle = user_data;
	nm_assert (handle->c_handle == c_handle);
	nm_assert (NM_IS_DEVICE (handle->self));

	handle->c_handle = NULL;
	self = handle->self;

	if (state == NM_CONNECTIVITY_CANCELLED) {
		/* the only place where we nm_connectivity_check_cancel(@c_handle), is
		 * from inside concheck_handle_complete(). This is a recursive call,
		 * nothing to do. */
		_LOGT (LOGD_CONCHECK, "connectivity: [IPv%c] complete check (seq:%llu, cancelled)",
		       nm_utils_addr_family_to_char (handle->addr_family),
		       (long long unsigned) handle->seq);
		return;
	}

	/* we keep NMConnectivity instance alive. It cannot be disposing. */
	nm_assert (state != NM_CONNECTIVITY_DISPOSING);

	self_keep_alive = g_object_ref (self);

	/* keep @self alive, while we invoke callbacks. */
	priv = NM_DEVICE_GET_PRIVATE (self);

	nm_assert (handle && c_list_contains (&priv->concheck_lst_head, &handle->concheck_lst));

	seq = handle->seq;

	_LOGT (LOGD_CONCHECK, "connectivity: [Ipv%c] complete check (seq:%llu, state:%s)",
	       nm_utils_addr_family_to_char (handle->addr_family),
	       (long long unsigned) handle->seq,
	       nm_connectivity_state_to_string (state));

	/* find out, if there are any periodic checks pending (either whether they
	 * were scheduled before or after @handle. */
	any_periodic_before = FALSE;
	any_periodic_after = FALSE;
	c_list_for_each_entry (other_handle, &priv->concheck_lst_head, concheck_lst) {
		if (other_handle->addr_family != handle->addr_family)
			continue;
		if (other_handle->is_periodic_bump_on_complete) {
			if (other_handle->seq < seq)
				any_periodic_before = TRUE;
			else if (other_handle->seq > seq)
				any_periodic_after = TRUE;
		}
	}
	if (NM_IN_SET (state, NM_CONNECTIVITY_ERROR)) {
		/* the request failed. We consider this periodic check only as completed if
		 * this was a periodic check, and there are not checks pending (either
		 * before or after this one).
		 *
		 * We allow_periodic_bump, if the request failed and there are
		 * still other requests periodic pending. */
		allow_periodic_bump =    handle->is_periodic_bump_on_complete
		                      && !any_periodic_before
		                      && !any_periodic_after;
	} else {
		/* the request succeeded. This marks the completion of a periodic check,
		 * if this handle was periodic, or any previously scheduled one (that
		 * we are going to complete below). */
		allow_periodic_bump =    handle->is_periodic_bump_on_complete
		                      || any_periodic_before;
	}

	/* first update the new state, and emit signals. */
	concheck_update_state (self, handle->addr_family, state, allow_periodic_bump);

	handle_is_alive = FALSE;

	/* we might have invoked callbacks during concheck_update_state(). The caller might have
	 * cancelled and thus destroyed @handle. We have to check whether handle is still alive,
	 * by searching it in the list of alive handles.
	 *
	 * Also, we might want to complete all pending callbacks that were started before
	 * @handle, as they are automatically obsoleted. */
check_handles:
	c_list_for_each_entry (other_handle, &priv->concheck_lst_head, concheck_lst) {
		if (other_handle->addr_family != handle->addr_family)
			continue;
		if (other_handle->seq >= seq) {
			/* it's not guaranteed that @handle is still in the list. It might already
			 * be canceled while invoking callbacks for a previous other_handle.
			 * If it is already cancelled, @handle is a dangling pointer.
			 *
			 * Since @seq is assigned uniquely and increasing, either @other_handle is
			 * @handle (and thus, handle is alive), or it isn't. */
			if (other_handle == handle)
				handle_is_alive = TRUE;
			break;
		}

		nm_assert (other_handle != handle);

		if (!NM_IN_SET (state, NM_CONNECTIVITY_ERROR)) {
			/* we also want to complete handles that were started before the current
			 * @handle. Their response is out-dated. */
			concheck_handle_complete (other_handle, NULL);

			/* we invoked callbacks, other handles might be cancelled and removed from the list.
			 * Need to iterate the list from the start. */
			goto check_handles;
		}
	}

	if (!handle_is_alive) {
		/* We didn't find @handle in the list of alive handles. Thus, the handles
		 * was cancelled while we were invoking events. Nothing to do, and don't
		 * touch the dangling pointer. */
		return;
	}

	concheck_handle_complete (handle, NULL);
}

static NMDeviceConnectivityHandle *
concheck_start (NMDevice *self,
                int addr_family,
                NMDeviceConnectivityCallback callback,
                gpointer user_data,
                gboolean is_periodic)
{
	static guint64 seq_counter = 0;
	NMDevicePrivate *priv;
	NMDeviceConnectivityHandle *handle;
	const char *ifname;

	g_return_val_if_fail (NM_IS_DEVICE (self), NULL);

	priv = NM_DEVICE_GET_PRIVATE (self);

	handle = g_slice_new0 (NMDeviceConnectivityHandle);
	handle->seq = ++seq_counter;
	handle->self = self;
	handle->callback = callback;
	handle->user_data = user_data;
	handle->is_periodic = is_periodic;
	handle->is_periodic_bump = is_periodic;
	handle->is_periodic_bump_on_complete = is_periodic;
	handle->addr_family = addr_family;

	c_list_link_tail (&priv->concheck_lst_head, &handle->concheck_lst);

	_LOGT (LOGD_CONCHECK, "connectivity: [IPv%c] start check (seq:%llu%s)",
	       nm_utils_addr_family_to_char (addr_family),
	       (long long unsigned) handle->seq,
	       is_periodic ? ", periodic-check" : "");

	if (   addr_family == AF_INET
	    && !priv->concheck_rp_filter_checked) {

		if ((ifname = nm_device_get_ip_iface_from_platform (self))) {
			gboolean due_to_all;
			int val;

			val = nm_platform_sysctl_ip_conf_get_rp_filter_ipv4 (nm_device_get_platform (self),
			                                                     ifname,
			                                                     TRUE,
			                                                     &due_to_all);
			if (val == 1) {
				_LOGW (LOGD_CONCHECK, "connectivity: \"/proc/sys/net/ipv4/conf/%s/rp_filter\" is set to \"1\". "
				       "This might break connectivity checking for IPv4 on this device",
				       due_to_all ? "all" : ifname);
			}
		}

		/* we only check once per device. It's a warning after all.  */
		priv->concheck_rp_filter_checked = TRUE;
	}

	handle->c_handle = nm_connectivity_check_start (concheck_get_mgr (self),
	                                                handle->addr_family,
	                                                nm_device_get_platform (self),
	                                                nm_device_get_ip_ifindex (self),
	                                                nm_device_get_ip_iface (self),
	                                                concheck_cb,
	                                                handle);
	return handle;
}

NMDeviceConnectivityHandle *
nm_device_check_connectivity (NMDevice *self,
                              int addr_family,
                              NMDeviceConnectivityCallback callback,
                              gpointer user_data)
{
	if (!concheck_is_possible (self))
		return NULL;

	concheck_periodic_schedule_set (self, addr_family, CONCHECK_SCHEDULE_CHECK_EXTERNAL);
	return concheck_start (self, addr_family, callback, user_data, FALSE);
}

void
nm_device_check_connectivity_cancel (NMDeviceConnectivityHandle *handle)
{
	gs_free_error GError *cancelled_error = NULL;

	g_return_if_fail (handle);
	g_return_if_fail (NM_IS_DEVICE (handle->self));
	g_return_if_fail (!c_list_is_empty (&handle->concheck_lst));

	/* nobody has access to periodic handles, and cannot cancel
	 * them externally. */
	nm_assert (!handle->is_periodic);

	nm_utils_error_set_cancelled (&cancelled_error, FALSE, "NMDevice");
	concheck_handle_complete (handle, cancelled_error);
}

NMConnectivityState
nm_device_get_connectivity_state (NMDevice *self, int addr_family)
{
	NMDevicePrivate *priv;
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	g_return_val_if_fail (NM_IS_DEVICE (self), NM_CONNECTIVITY_UNKNOWN);
	nm_assert_addr_family (addr_family);

	priv = NM_DEVICE_GET_PRIVATE (self);

	switch (addr_family) {
	case AF_INET:
	case AF_INET6:
		return priv->concheck_x[IS_IPv4].state;
	default:
		nm_assert (addr_family == AF_UNSPEC);
		return NM_MAX_WITH_CMP (nm_connectivity_state_cmp,
		                        priv->concheck_x[0].state,
		                        priv->concheck_x[1].state);
	}
}

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

static SlaveInfo *
find_slave_info (NMDevice *self, NMDevice *slave)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	CList *iter;
	SlaveInfo *info;

	c_list_for_each (iter, &priv->slaves) {
		info = c_list_entry (iter, SlaveInfo, lst_slave);
		if (info->slave == slave)
			return info;
	}
	return NULL;
}

/**
 * nm_device_master_enslave_slave:
 * @self: the master device
 * @slave: the slave device to enslave
 * @connection: (allow-none): the slave device's connection
 *
 * If @self is capable of enslaving other devices (ie it's a bridge, bond, team,
 * etc) then this function enslaves @slave.
 *
 * Returns: %TRUE on success, %FALSE on failure or if this device cannot enslave
 *  other devices.
 */
static gboolean
nm_device_master_enslave_slave (NMDevice *self, NMDevice *slave, NMConnection *connection)
{
	NMDevicePrivate *priv;
	SlaveInfo *info;
	gboolean success = FALSE;
	gboolean configure;

	g_return_val_if_fail (self != NULL, FALSE);
	g_return_val_if_fail (slave != NULL, FALSE);
	g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->enslave_slave != NULL, FALSE);

	priv = NM_DEVICE_GET_PRIVATE (self);
	info = find_slave_info (self, slave);
	if (!info)
		return FALSE;

	if (info->slave_is_enslaved)
		success = TRUE;
	else {
		configure = (info->configure && connection != NULL);
		if (configure)
			g_return_val_if_fail (nm_device_get_state (slave) >= NM_DEVICE_STATE_DISCONNECTED, FALSE);

		success = NM_DEVICE_GET_CLASS (self)->enslave_slave (self, slave, connection, configure);
		info->slave_is_enslaved = success;
	}

	nm_device_slave_notify_enslave (info->slave, success);

	/* Ensure the device's hardware address is up-to-date; it often changes
	 * when slaves change.
	 */
	nm_device_update_hw_address (self);

	/* Send ARP announcements if did not yet and have addresses. */
	if (   priv->ip_state_4 == NM_DEVICE_IP_STATE_DONE
	    && !priv->acd.announcing)
		nm_device_arp_announce (self);

	/* Restart IP configuration if we're waiting for slaves.  Do this
	 * after updating the hardware address as IP config may need the
	 * new address.
	 */
	if (success) {
		if (priv->ip_state_4 == NM_DEVICE_IP_STATE_WAIT)
			nm_device_activate_stage3_ip4_start (self);

		if (priv->ip_state_6 == NM_DEVICE_IP_STATE_WAIT)
			nm_device_activate_stage3_ip6_start (self);
	}

	/* Since slave devices don't have their own IP configuration,
	 * set the MTU here.
	 */
	_commit_mtu (slave, NM_DEVICE_GET_PRIVATE (slave)->ip_config_4);

	return success;
}

/**
 * nm_device_master_release_one_slave:
 * @self: the master device
 * @slave: the slave device to release
 * @configure: whether @self needs to actually release @slave
 * @force: force the release of @slave even if it wasn't added
 *         to @master by NetworkManager
 * @reason: the state change reason for the @slave
 *
 * If @self is capable of enslaving other devices (ie it's a bridge, bond, team,
 * etc) then this function releases the previously enslaved @slave and/or
 * updates the state of @self and @slave to reflect its release.
 */
static void
nm_device_master_release_one_slave (NMDevice *self,
                                    NMDevice *slave,
                                    gboolean configure,
                                    gboolean force,
                                    NMDeviceStateReason reason)
{
	NMDevicePrivate *priv;
	NMDevicePrivate *slave_priv;
	SlaveInfo *info;
	gs_unref_object NMDevice *self_free = NULL;

	g_return_if_fail (NM_DEVICE (self));
	g_return_if_fail (NM_DEVICE (slave));
	g_return_if_fail (!force || configure);
	g_return_if_fail (NM_DEVICE_GET_CLASS (self)->release_slave != NULL);

	info = find_slave_info (self, slave);

	_LOGT (LOGD_CORE, "master: release one slave %p/%s %s%s",
	       slave, nm_device_get_iface (slave),
	       !info ? "(not registered)" : (info->slave_is_enslaved ? "(enslaved)" : "(not enslaved)"),
	       force ? " (force-configure)" : (configure ? " (configure)" : ""));

	if (!info)
		g_return_if_reached ();

	priv = NM_DEVICE_GET_PRIVATE (self);
	slave_priv = NM_DEVICE_GET_PRIVATE (slave);

	g_return_if_fail (self == slave_priv->master);
	nm_assert (slave == info->slave);

	/* first, let subclasses handle the release ... */
	if (info->slave_is_enslaved || force)
		NM_DEVICE_GET_CLASS (self)->release_slave (self, slave, configure);

	/* raise notifications about the release, including clearing is_enslaved. */
	nm_device_slave_notify_release (slave, reason);

	/* keep both alive until the end of the function.
	 * Transfers ownership from slave_priv->master.  */
	self_free = self;

	c_list_unlink (&info->lst_slave);
	slave_priv->master = NULL;

	g_signal_handler_disconnect (slave, info->watch_id);
	g_object_unref (slave);
	g_slice_free (SlaveInfo, info);

	if (c_list_is_empty (&priv->slaves)) {
		_active_connection_set_state_flags_full (self,
		                                         0,
		                                         NM_ACTIVATION_STATE_FLAG_MASTER_HAS_SLAVES);
	}

	/* Ensure the device's hardware address is up-to-date; it often changes
	 * when slaves change.
	 */
	nm_device_update_hw_address (self);
	nm_device_set_unmanaged_by_flags (slave, NM_UNMANAGED_IS_SLAVE, NM_UNMAN_FLAG_OP_FORGET, NM_DEVICE_STATE_REASON_REMOVED);
}

/**
 * can_unmanaged_external_down:
 * @self: the device
 *
 * Check whether the device should stay NM_UNMANAGED_EXTERNAL_DOWN unless
 * IFF_UP-ed externally.
 */
static gboolean
can_unmanaged_external_down (NMDevice *self)
{
	return    !NM_DEVICE_GET_PRIVATE (self)->nm_owned
	       && nm_device_is_software (self);
}

static NMUnmanFlagOp
is_unmanaged_external_down (NMDevice *self, gboolean consider_can)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (   consider_can
	    && !NM_DEVICE_GET_CLASS (self)->can_unmanaged_external_down (self))
		return NM_UNMAN_FLAG_OP_FORGET;

	/* Manage externally-created software interfaces only when they are IFF_UP */
	if (   priv->ifindex <= 0
	    || !priv->up
	    || !(   !c_list_is_empty (&priv->slaves)
	         || nm_platform_link_can_assume (nm_device_get_platform (self), priv->ifindex)))
		return NM_UNMAN_FLAG_OP_SET_UNMANAGED;

	return NM_UNMAN_FLAG_OP_SET_MANAGED;
}

static void
set_unmanaged_external_down (NMDevice *self, gboolean only_if_unmanaged)
{
	NMUnmanFlagOp ext_flags;

	if (!nm_device_get_unmanaged_mask (self, NM_UNMANAGED_EXTERNAL_DOWN))
		return;

	if (only_if_unmanaged) {
		if (!nm_device_get_unmanaged_flags (self, NM_UNMANAGED_EXTERNAL_DOWN))
			return;
	}

	ext_flags = is_unmanaged_external_down (self, FALSE);
	if (ext_flags != NM_UNMAN_FLAG_OP_SET_UNMANAGED) {
		/* Ensure the assume check is queued before any queued state changes
		 * from the transition to UNAVAILABLE.
		 */
		nm_device_queue_recheck_assume (self);
	}

	nm_device_set_unmanaged_by_flags (self,
	                                  NM_UNMANAGED_EXTERNAL_DOWN,
	                                  ext_flags,
	                                  NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);
}

void
nm_device_update_dynamic_ip_setup (NMDevice *self)
{
	NMDevicePrivate *priv;
	GError *error = NULL;

	g_return_if_fail (NM_IS_DEVICE (self));

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (   priv->state < NM_DEVICE_STATE_IP_CONFIG
	    || priv->state > NM_DEVICE_STATE_ACTIVATED)
		return;

	g_hash_table_remove_all (priv->ip6_saved_properties);

	if (priv->dhcp_data_4.client) {
		if (!nm_device_dhcp4_renew (self, FALSE)) {
			nm_device_state_changed (self,
			                         NM_DEVICE_STATE_FAILED,
			                         NM_DEVICE_STATE_REASON_DHCP_FAILED);
			return;
		}
	}
	if (priv->dhcp_data_6.client) {
		if (!nm_device_dhcp6_renew (self, FALSE)) {
			nm_device_state_changed (self,
			                         NM_DEVICE_STATE_FAILED,
			                         NM_DEVICE_STATE_REASON_DHCP_FAILED);
			return;
		}
	}
	if (priv->ndisc) {
		/* FIXME: todo */
	}
	if (priv->dnsmasq_manager) {
		/* FIXME: todo */
	}

	if (   priv->lldp_listener
	    && nm_lldp_listener_is_running (priv->lldp_listener)) {
		nm_lldp_listener_stop (priv->lldp_listener);
		if (!nm_lldp_listener_start (priv->lldp_listener, nm_device_get_ifindex (self), &error)) {
			_LOGD (LOGD_DEVICE, "LLDP listener %p could not be restarted: %s",
			       priv->lldp_listener, error->message);
			g_clear_error (&error);
		}
	}
}

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

static void
carrier_changed_notify (NMDevice *self, gboolean carrier)
{
	/* stub */
}

static void
carrier_changed (NMDevice *self, gboolean carrier)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->state <= NM_DEVICE_STATE_UNMANAGED)
		return;

	nm_device_recheck_available_connections (self);

	/* ignore-carrier devices ignore all carrier-down events */
	if (priv->ignore_carrier && !carrier)
		return;

	if (nm_device_is_master (self)) {
		if (carrier) {
			/* Force master to retry getting ip addresses when carrier
			* is restored. */
			if (priv->state == NM_DEVICE_STATE_ACTIVATED)
				nm_device_update_dynamic_ip_setup (self);
			/* If needed, also resume IP configuration that is
			 * waiting for carrier. */
			if (nm_device_activate_ip4_state_in_wait (self))
				nm_device_activate_stage3_ip4_start (self);
			if (nm_device_activate_ip6_state_in_wait (self))
				nm_device_activate_stage3_ip6_start (self);
			return;
		}
		/* fall-through and change state of device */
	} else if (priv->is_enslaved && !carrier) {
		/* Slaves don't deactivate when they lose carrier; for
		 * bonds/teams in particular that would be actively
		 * counterproductive.
		 */
		return;
	}

	if (carrier) {
		if (priv->state == NM_DEVICE_STATE_UNAVAILABLE) {
			nm_device_queue_state (self, NM_DEVICE_STATE_DISCONNECTED,
			                       NM_DEVICE_STATE_REASON_CARRIER);
		} else if (priv->state == NM_DEVICE_STATE_DISCONNECTED) {
			/* If the device is already in DISCONNECTED state without a carrier
			 * (probably because it is tagged for carrier ignore) ensure that
			 * when the carrier appears, auto connections are rechecked for
			 * the device.
			 */
			nm_device_emit_recheck_auto_activate (self);
		} else if (priv->state == NM_DEVICE_STATE_ACTIVATED) {
			/* If the device is active without a carrier (probably because it is
			 * tagged for carrier ignore) ensure that when the carrier appears we
			 * renew DHCP leases and such.
			 */
			nm_device_update_dynamic_ip_setup (self);
		}
	} else {
		if (priv->state == NM_DEVICE_STATE_UNAVAILABLE) {
			if (   priv->queued_state.id
			    && priv->queued_state.state >= NM_DEVICE_STATE_DISCONNECTED)
				queued_state_clear (self);
		} else {
			nm_device_queue_state (self, NM_DEVICE_STATE_UNAVAILABLE,
			                       NM_DEVICE_STATE_REASON_CARRIER);
		}
	}
}

static gboolean
carrier_disconnected_action_cb (gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	_LOGD (LOGD_DEVICE, "carrier: link disconnected (calling deferred action) (id=%u)", priv->carrier_defer_id);

	priv->carrier_defer_id = 0;
	carrier_changed (self, FALSE);
	return FALSE;
}

static void
carrier_disconnected_action_cancel (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	guint id = priv->carrier_defer_id;

	if (nm_clear_g_source (&priv->carrier_defer_id)) {
		_LOGD (LOGD_DEVICE, "carrier: link disconnected (canceling deferred action) (id=%u)",
		       id);
	}
}

void
nm_device_set_carrier (NMDevice *self, gboolean carrier)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMDeviceState state = nm_device_get_state (self);
	gboolean notify_flags = FALSE;

	if (priv->carrier == carrier)
		return;

	if (NM_FLAGS_ALL (priv->capabilities,
	                    NM_DEVICE_CAP_CARRIER_DETECT
	                  | NM_DEVICE_CAP_NONSTANDARD_CARRIER)) {
		if (carrier)
			priv->interface_flags |= NM_DEVICE_INTERFACE_FLAG_CARRIER;
		else
			priv->interface_flags &= ~NM_DEVICE_INTERFACE_FLAG_CARRIER;
		notify_flags = TRUE;
	}

	priv->carrier = carrier;
	if (notify_flags)
		nm_gobject_notify_together (self, PROP_CARRIER, PROP_INTERFACE_FLAGS);
	else
		_notify (self, PROP_CARRIER);

	if (priv->carrier) {
		_LOGI (LOGD_DEVICE, "carrier: link connected");
		carrier_disconnected_action_cancel (self);
		NM_DEVICE_GET_CLASS (self)->carrier_changed_notify (self, carrier);
		carrier_changed (self, TRUE);

		if (priv->carrier_wait_id) {
			nm_device_remove_pending_action (self, NM_PENDING_ACTION_CARRIER_WAIT, FALSE);
			_carrier_wait_check_queued_act_request (self);
		}
	} else {
		if (priv->carrier_wait_id)
			nm_device_add_pending_action (self, NM_PENDING_ACTION_CARRIER_WAIT, FALSE);
		NM_DEVICE_GET_CLASS (self)->carrier_changed_notify (self, carrier);
		if (   state <= NM_DEVICE_STATE_DISCONNECTED
		    && !priv->queued_act_request) {
			_LOGD (LOGD_DEVICE, "carrier: link disconnected");
			carrier_changed (self, FALSE);
		} else {
			gint64 now_ms, until_ms;

			now_ms = nm_utils_get_monotonic_timestamp_msec ();
			until_ms = NM_MAX (now_ms + _get_carrier_wait_ms (self), priv->carrier_wait_until_ms);
			priv->carrier_defer_id = g_timeout_add (until_ms - now_ms, carrier_disconnected_action_cb, self);
			_LOGD (LOGD_DEVICE, "carrier: link disconnected (deferring action for %ld milliseconds) (id=%u)",
			       (long) (until_ms - now_ms), priv->carrier_defer_id);
		}
	}
}

static void
nm_device_set_carrier_from_platform (NMDevice *self)
{
	int ifindex;

	if (nm_device_has_capability (self, NM_DEVICE_CAP_CARRIER_DETECT)) {
		if (   !nm_device_has_capability (self, NM_DEVICE_CAP_NONSTANDARD_CARRIER)
		    && (ifindex = nm_device_get_ip_ifindex (self)) > 0) {
			nm_device_set_carrier (self,
			                       nm_platform_link_is_connected (nm_device_get_platform (self),
			                                                      ifindex));
		}
	} else {
		NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

		/* Fake online link when carrier detection is not available. */
		if (!priv->carrier) {
			priv->carrier = TRUE;
			_notify (self, PROP_CARRIER);
		}
	}
}

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

static void
device_recheck_slave_status (NMDevice *self, const NMPlatformLink *plink)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMDevice *master;
	nm_auto_nmpobj const NMPObject *plink_master_keep_alive = NULL;
	const NMPlatformLink *plink_master;

	g_return_if_fail (plink);

	if (plink->master <= 0)
		return;

	master = nm_manager_get_device_by_ifindex (NM_MANAGER_GET, plink->master);
	plink_master = nm_platform_link_get (nm_device_get_platform (self), plink->master);
	plink_master_keep_alive = nmp_object_ref (NMP_OBJECT_UP_CAST (plink_master));

	if (   master == NULL
	    && plink_master
	    && nm_streq0 (plink_master->name, "ovs-system")
	    && plink_master->type == NM_LINK_TYPE_OPENVSWITCH) {
		_LOGD (LOGD_DEVICE, "the device claimed by openvswitch");
		return;
	}

	if (priv->master) {
		if (   plink->master > 0
		    && plink->master == nm_device_get_ifindex (priv->master)) {
			/* call add-slave again. We expect @self already to be added to
			 * the master, but this also triggers a recheck-assume. */
			nm_device_master_add_slave (priv->master, self, FALSE);
			return;
		}

		nm_device_master_release_one_slave (priv->master, self, FALSE, FALSE, NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);
	}

	if (master && NM_DEVICE_GET_CLASS (master)->enslave_slave)
		nm_device_master_add_slave (master, self, FALSE);
	else if (master) {
		_LOGI (LOGD_DEVICE, "enslaved to non-master-type device %s; ignoring",
		       nm_device_get_iface (master));
	} else {
		_LOGW (LOGD_DEVICE, "enslaved to unknown device %d (%s%s%s)",
		       plink->master,
		       NM_PRINT_FMT_QUOTED (plink_master, "\"", plink_master->name, "\"", "??"));
	}
}

static void
ndisc_set_router_config (NMNDisc *ndisc, NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gint32 now;
	GArray *addresses, *dns_servers, *dns_domains;
	guint len, i;
	const NMDedupMultiHeadEntry *head_entry;
	NMDedupMultiIter ipconf_iter;

	if (nm_ndisc_get_node_type (ndisc) != NM_NDISC_NODE_TYPE_ROUTER)
		return;

	now = nm_utils_get_monotonic_timestamp_sec ();

	head_entry = nm_ip6_config_lookup_addresses (priv->ip_config_6);
	addresses = g_array_sized_new (FALSE, TRUE, sizeof (NMNDiscAddress),
	                               head_entry ? head_entry->len : 0);
	nm_dedup_multi_iter_for_each (&ipconf_iter, head_entry) {
		const NMPlatformIP6Address *addr = NMP_OBJECT_CAST_IP6_ADDRESS (ipconf_iter.current->obj);
		NMNDiscAddress *ndisc_addr;
		guint32 lifetime, preferred;
		gint32 base;

		if (   IN6_IS_ADDR_UNSPECIFIED (&addr->address)
		    || IN6_IS_ADDR_LINKLOCAL (&addr->address))
			continue;

		if (   addr->n_ifa_flags & IFA_F_TENTATIVE
		    || addr->n_ifa_flags & IFA_F_DADFAILED)
			continue;

		if (addr->plen != 64)
			continue;

		/* resolve the timestamps relative to a new base.
		 *
		 * Note that for convenience, platform @addr might have timestamp and/or
		 * lifetime unset. We don't allow that flexibility for ndisc and require
		 * well defined timestamps. */
		if (addr->timestamp) {
			nm_assert (addr->timestamp < G_MAXINT32);
			base = addr->timestamp;
		} else
			base = now;

		lifetime = nm_utils_lifetime_get (addr->timestamp, addr->lifetime, addr->preferred,
		                                  base, &preferred);
		if (!lifetime)
			continue;

		g_array_set_size (addresses, addresses->len+1);
		ndisc_addr = &g_array_index (addresses, NMNDiscAddress, addresses->len-1);
		ndisc_addr->address = addr->address;
		ndisc_addr->timestamp = base;
		ndisc_addr->lifetime = lifetime;
		ndisc_addr->preferred = preferred;
	}

	len = nm_ip6_config_get_num_nameservers (priv->ip_config_6);
	dns_servers = g_array_sized_new (FALSE, TRUE, sizeof (NMNDiscDNSServer), len);
	g_array_set_size (dns_servers, len);
	for (i = 0; i < len; i++) {
		const struct in6_addr *nameserver = nm_ip6_config_get_nameserver (priv->ip_config_6, i);
		NMNDiscDNSServer *ndisc_nameserver;

		ndisc_nameserver = &g_array_index (dns_servers, NMNDiscDNSServer, i);
		ndisc_nameserver->address = *nameserver;
		ndisc_nameserver->timestamp = now;
		ndisc_nameserver->lifetime = NM_NDISC_ROUTER_LIFETIME;
	}

	len = nm_ip6_config_get_num_searches (priv->ip_config_6);
	dns_domains = g_array_sized_new (FALSE, TRUE, sizeof (NMNDiscDNSDomain), len);
	g_array_set_size (dns_domains, len);
	for (i = 0; i < len; i++) {
		const char *search = nm_ip6_config_get_search (priv->ip_config_6, i);
		NMNDiscDNSDomain *ndisc_search;

		ndisc_search = &g_array_index (dns_domains, NMNDiscDNSDomain, i);
		ndisc_search->domain = (char *) search;
		ndisc_search->timestamp = now;
		ndisc_search->lifetime = NM_NDISC_ROUTER_LIFETIME;
	}

	nm_ndisc_set_config (ndisc, addresses, dns_servers, dns_domains);
	g_array_unref (addresses);
	g_array_unref (dns_servers);
	g_array_unref (dns_domains);
}

static void
device_update_interface_flags (NMDevice *self, const NMPlatformLink *plink)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMDeviceInterfaceFlags flags = NM_DEVICE_INTERFACE_FLAG_NONE;

	if (plink && NM_FLAGS_HAS (plink->n_ifi_flags, IFF_UP))
		flags |= NM_DEVICE_INTERFACE_FLAG_UP;
	if (plink && NM_FLAGS_HAS (plink->n_ifi_flags, IFF_LOWER_UP))
		flags |= NM_DEVICE_INTERFACE_FLAG_LOWER_UP;

	if (NM_FLAGS_ALL (priv->capabilities,
	                    NM_DEVICE_CAP_CARRIER_DETECT
	                  | NM_DEVICE_CAP_NONSTANDARD_CARRIER)) {
		if (priv->carrier)
			flags |= NM_DEVICE_INTERFACE_FLAG_CARRIER;
	} else {
		if (plink && NM_FLAGS_HAS (plink->n_ifi_flags, IFF_LOWER_UP))
			flags |= NM_DEVICE_INTERFACE_FLAG_CARRIER;
	}

	if (flags != priv->interface_flags) {
		priv->interface_flags = flags;
		_notify (self, PROP_INTERFACE_FLAGS);
	}
}

static gboolean
device_link_changed (NMDevice *self)
{
	NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gboolean ip_ifname_changed = FALSE;
	nm_auto_nmpobj const NMPObject *pllink_keep_alive = NULL;
	const NMPlatformLink *pllink;
	const char *str;
	int ifindex;
	gboolean was_up;
	gboolean update_unmanaged_specs = FALSE;
	gboolean got_hw_addr = FALSE, had_hw_addr;
	gboolean seen_down = priv->device_link_changed_down;

	priv->device_link_changed_id = 0;
	priv->device_link_changed_down = FALSE;

	ifindex = nm_device_get_ifindex (self);
	if (ifindex <= 0)
		return G_SOURCE_REMOVE;
	pllink = nm_platform_link_get (nm_device_get_platform (self), ifindex);
	if (!pllink)
		return G_SOURCE_REMOVE;

	pllink_keep_alive = nmp_object_ref (NMP_OBJECT_UP_CAST (pllink));

	str = nm_platform_link_get_udi (nm_device_get_platform (self), pllink->ifindex);
	if (!nm_streq0 (str, priv->udi)) {
		g_free (priv->udi);
		priv->udi = g_strdup (str);
		_notify (self, PROP_UDI);
	}

	str = nm_platform_link_get_path (nm_device_get_platform (self), pllink->ifindex);
	if (!nm_streq0 (str, priv->path)) {
		g_free (priv->path);
		priv->path = g_strdup (str);
		_notify (self, PROP_PATH);
	}

	if (!nm_streq0 (pllink->driver, priv->driver)) {
		g_free (priv->driver);
		priv->driver = g_strdup (pllink->driver);
		_notify (self, PROP_DRIVER);
	}

	_set_mtu (self, pllink->mtu);

	if (ifindex == nm_device_get_ip_ifindex (self))
		_stats_update_counters_from_pllink (self, pllink);

	had_hw_addr = (priv->hw_addr != NULL);
	nm_device_update_hw_address (self);
	got_hw_addr = (!had_hw_addr && priv->hw_addr);
	nm_device_update_permanent_hw_address (self, FALSE);

	if (   pllink->name[0]
	    && !nm_streq (priv->iface, pllink->name)) {
		_LOGI (LOGD_DEVICE, "interface index %d renamed iface from '%s' to '%s'",
		       priv->ifindex, priv->iface, pllink->name);
		g_free (priv->iface_);
		priv->iface_ = g_strdup (pllink->name);

		/* If the device has no explicit ip_iface, then changing iface changes ip_iface too. */
		ip_ifname_changed = !priv->ip_iface;

		if (nm_device_get_unmanaged_flags (self, NM_UNMANAGED_PLATFORM_INIT))
			nm_device_set_unmanaged_by_user_settings (self);
		else
			update_unmanaged_specs = TRUE;

		_notify (self, PROP_IFACE);
		if (ip_ifname_changed)
			_notify (self, PROP_IP_IFACE);

		/* Re-match available connections against the new interface name */
		nm_device_recheck_available_connections (self);

		/* Let any connections that use the new interface name have a chance
		 * to auto-activate on the device.
		 */
		nm_device_emit_recheck_auto_activate (self);
	}

	if (priv->ndisc && pllink->inet6_token.id) {
		if (nm_ndisc_set_iid (priv->ndisc, pllink->inet6_token))
			_LOGD (LOGD_DEVICE, "IPv6 tokenized identifier present on device %s", priv->iface);
	}

	/* Update carrier from link event if applicable. */
	if (   nm_device_has_capability (self, NM_DEVICE_CAP_CARRIER_DETECT)
	    && !nm_device_has_capability (self, NM_DEVICE_CAP_NONSTANDARD_CARRIER))
		nm_device_set_carrier (self, pllink->connected);

	device_update_interface_flags (self, pllink);

	klass->link_changed (self, pllink);

	/* Update DHCP, etc, if needed */
	if (ip_ifname_changed)
		nm_device_update_dynamic_ip_setup (self);

	was_up = priv->up;
	priv->up = NM_FLAGS_HAS (pllink->n_ifi_flags, IFF_UP);

	if (   pllink->initialized
	    && nm_device_get_unmanaged_flags (self, NM_UNMANAGED_PLATFORM_INIT)) {
		NMDeviceStateReason reason;

		nm_device_set_unmanaged_by_user_udev (self);
		nm_device_set_unmanaged_by_user_conf (self);

		reason = NM_DEVICE_STATE_REASON_NOW_MANAGED;

		/* If the device is a external-down candidated but no longer has external
		 * down set, we must clear the platform-unmanaged flag with reason
		 * "assumed". */
		if (    nm_device_get_unmanaged_mask (self, NM_UNMANAGED_EXTERNAL_DOWN)
		    && !nm_device_get_unmanaged_flags (self, NM_UNMANAGED_EXTERNAL_DOWN)) {
			/* actually, user-udev overwrites external-down. So we only assume the device,
			 * when it is a external-down candidate, which is not managed via udev. */
			if (!nm_device_get_unmanaged_mask (self, NM_UNMANAGED_USER_UDEV)) {
				/* Ensure the assume check is queued before any queued state changes
				 * from the transition to UNAVAILABLE.
				 */
				nm_device_queue_recheck_assume (self);
				reason = NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED;
			}
		}

		nm_device_set_unmanaged_by_flags (self, NM_UNMANAGED_PLATFORM_INIT, FALSE, reason);
	}

	set_unmanaged_external_down (self, FALSE);

	device_recheck_slave_status (self, pllink);

	if (priv->up && (!was_up || seen_down)) {
		/* the link was down and just came up. That happens for example, while changing MTU.
		 * We must restore IP configuration. */
		if (NM_IN_SET (priv->ip_state_4, NM_DEVICE_IP_STATE_CONF,
		                                 NM_DEVICE_IP_STATE_DONE)) {
			if (!ip_config_merge_and_apply (self, AF_INET, TRUE))
				_LOGW (LOGD_IP4, "failed applying IP4 config after link comes up again");
		}

		priv->linklocal6_dad_counter = 0;
		if (NM_IN_SET (priv->ip_state_6, NM_DEVICE_IP_STATE_CONF,
		                                 NM_DEVICE_IP_STATE_DONE)) {
			if (!ip_config_merge_and_apply (self, AF_INET6, TRUE))
				_LOGW (LOGD_IP6, "failed applying IP6 config after link comes up again");
		}
	}

	if (update_unmanaged_specs)
		nm_device_set_unmanaged_by_user_settings (self);

	if (   got_hw_addr
	    && !priv->up
	    && nm_device_get_state (self) == NM_DEVICE_STATE_UNAVAILABLE) {
		/*
		 * If the device is UNAVAILABLE, any previous try to
		 * bring it up probably has failed because of the
		 * invalid hardware address; try again.
		 */
		nm_device_bring_up (self, TRUE, NULL);
		nm_device_queue_recheck_available (self,
		                                   NM_DEVICE_STATE_REASON_NONE,
		                                   NM_DEVICE_STATE_REASON_NONE);
	}

	return G_SOURCE_REMOVE;
}

static gboolean
device_ip_link_changed (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const NMPlatformLink *pllink;
	const char *ip_iface;

	priv->device_ip_link_changed_id = 0;

	if (priv->ip_ifindex <= 0)
		return G_SOURCE_REMOVE;

	nm_assert (priv->ip_iface);

	pllink = nm_platform_link_get (nm_device_get_platform (self), priv->ip_ifindex);
	if (!pllink)
		return G_SOURCE_REMOVE;

	if (   priv->ifindex <= 0
	    && pllink->mtu)
		_set_mtu (self, pllink->mtu);

	_stats_update_counters_from_pllink (self, pllink);

	ip_iface = pllink->name;

	if (!ip_iface[0])
		return FALSE;

	if (!nm_streq (priv->ip_iface, ip_iface)) {
		_LOGI (LOGD_DEVICE, "ip-ifname: interface index %d renamed ip_iface (%d) from '%s' to '%s'",
		       priv->ifindex,
		       priv->ip_ifindex,
		       priv->ip_iface,
		       ip_iface);
		g_free (priv->ip_iface_);
		priv->ip_iface_ = g_strdup (ip_iface);
		_notify (self, PROP_IP_IFACE);

		nm_device_update_dynamic_ip_setup (self);
	}

	return G_SOURCE_REMOVE;
}

static void
link_changed_cb (NMPlatform *platform,
                 int obj_type_i,
                 int ifindex,
                 NMPlatformLink *info,
                 int change_type_i,
                 NMDevice *self)
{
	const NMPlatformSignalChangeType change_type = change_type_i;
	NMDevicePrivate *priv;

	if (change_type != NM_PLATFORM_SIGNAL_CHANGED)
		return;

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (ifindex == nm_device_get_ifindex (self)) {
		if (!(info->n_ifi_flags & IFF_UP))
			priv->device_link_changed_down = TRUE;
		if (!priv->device_link_changed_id) {
			priv->device_link_changed_id = g_idle_add ((GSourceFunc) device_link_changed, self);
			_LOGD (LOGD_DEVICE, "queued link change for ifindex %d", ifindex);
		}
	} else if (ifindex == nm_device_get_ip_ifindex (self)) {
		if (!priv->device_ip_link_changed_id) {
			priv->device_ip_link_changed_id = g_idle_add ((GSourceFunc) device_ip_link_changed, self);
			_LOGD (LOGD_DEVICE, "queued link change for ip-ifindex %d", ifindex);
		}
	}
}

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

static void
link_changed (NMDevice *self, const NMPlatformLink *pllink)
{
	/* stub implementation of virtual function to allow subclasses to chain up. */
}

static gboolean
link_type_compatible (NMDevice *self,
                      NMLinkType link_type,
                      gboolean *out_compatible,
                      GError **error)
{
	NMDeviceClass *klass;
	NMLinkType device_type;
	guint i = 0;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	klass = NM_DEVICE_GET_CLASS (self);

	if (!klass->link_types) {
		NM_SET_OUT (out_compatible, FALSE);
		g_set_error_literal (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED,
		                     "Device does not support platform links");
		return FALSE;
	}

	device_type = self->_priv->link_type;
	if (device_type > NM_LINK_TYPE_UNKNOWN && device_type != link_type) {
		g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED,
		             "Needed link type 0x%x does not match the platform link type 0x%X",
		             device_type, link_type);
		return FALSE;
	}

	for (i = 0; klass->link_types[i] > NM_LINK_TYPE_UNKNOWN; i++) {
		if (klass->link_types[i] == link_type)
			return TRUE;
		if (klass->link_types[i] == NM_LINK_TYPE_ANY)
			return TRUE;
	}

	NM_SET_OUT (out_compatible, FALSE);
	g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED,
	             "Device does not support platform link type 0x%X",
	             link_type);
	return FALSE;
}

/**
 * nm_device_realize_start():
 * @self: the #NMDevice
 * @plink: an existing platform link or %NULL
 * @assume_state_guess_assume: set the guess_assume state.
 * @assume_state_connection_uuid: set the connection uuid to assume.
 * @set_nm_owned: for software device, if TRUE set nm-owned.
 * @unmanaged_user_explicit: the user-explicit unmanaged flag to apply
 *   on the device initially.
 * @out_compatible: %TRUE on return if @self is compatible with @plink
 * @error: location to store error, or %NULL
 *
 * Initializes and sets up the device using existing backing resources. Before
 * the device is ready for use nm_device_realize_finish() must be called.
 * @out_compatible will only be set if @plink is not %NULL, and
 *
 * Important: if nm_device_realize_start() returns %TRUE, the caller MUST
 * also call nm_device_realize_finish() to balance g_object_freeze_notify().
 *
 * Returns: %TRUE on success, %FALSE on error
 */
gboolean
nm_device_realize_start (NMDevice *self,
                         const NMPlatformLink *plink,
                         gboolean assume_state_guess_assume,
                         const char *assume_state_connection_uuid,
                         gboolean set_nm_owned,
                         NMUnmanFlagOp unmanaged_user_explicit,
                         gboolean *out_compatible,
                         GError **error)
{
	nm_auto_nmpobj const NMPObject *plink_keep_alive = NULL;

	nm_assert (!plink || NMP_OBJECT_GET_TYPE (NMP_OBJECT_UP_CAST (plink)) == NMP_OBJECT_TYPE_LINK);

	NM_SET_OUT (out_compatible, TRUE);

	if (plink) {
		if (!nm_streq0 (nm_device_get_iface (self), plink->name)) {
			NM_SET_OUT (out_compatible, FALSE);
			g_set_error_literal (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED,
			                     "Device interface name does not match platform link");
			return FALSE;
		}

		if (!link_type_compatible (self, plink->type, out_compatible, error))
			return FALSE;

		plink_keep_alive = nmp_object_ref (NMP_OBJECT_UP_CAST (plink));
	}

	realize_start_setup (self,
	                     plink,
	                     assume_state_guess_assume,
	                     assume_state_connection_uuid,
	                     set_nm_owned,
	                     unmanaged_user_explicit,
	                     FALSE);
	return TRUE;
}

/**
 * nm_device_create_and_realize():
 * @self: the #NMDevice
 * @connection: the #NMConnection being activated
 * @parent: the parent #NMDevice if any
 * @error: location to store error, or %NULL
 *
 * Creates any backing resources needed to realize the device to proceed
 * with activating @connection.
 *
 * Returns: %TRUE on success, %FALSE on error
 */
gboolean
nm_device_create_and_realize (NMDevice *self,
                              NMConnection *connection,
                              NMDevice *parent,
                              GError **error)
{
	nm_auto_nmpobj const NMPObject *plink_keep_alive = NULL;
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const NMPlatformLink *plink;
	gboolean nm_owned;

	/* Must be set before device is realized */
	plink = nm_platform_link_get_by_ifname (nm_device_get_platform (self), priv->iface);
	nm_owned = !plink || !link_type_compatible (self, plink->type, NULL, NULL);
	_LOGD (LOGD_DEVICE, "create (is %snm-owned)", nm_owned ? "" : "not ");

	plink = NULL;
	/* Create any resources the device needs */
	if (NM_DEVICE_GET_CLASS (self)->create_and_realize) {
		if (!NM_DEVICE_GET_CLASS (self)->create_and_realize (self, connection, parent, &plink, error))
			return FALSE;
		if (plink) {
			nm_assert (NMP_OBJECT_GET_TYPE (NMP_OBJECT_UP_CAST (plink)) == NMP_OBJECT_TYPE_LINK);
			plink_keep_alive = nmp_object_ref (NMP_OBJECT_UP_CAST (plink));
		}
	}

	priv->nm_owned = nm_owned;

	realize_start_setup (self,
	                     plink,
	                     FALSE, /* assume_state_guess_assume */
	                     NULL,  /* assume_state_connection_uuid */
	                     FALSE, NM_UNMAN_FLAG_OP_FORGET,
	                     TRUE);
	nm_device_realize_finish (self, plink);

	if (nm_device_get_managed (self, FALSE)) {
		nm_device_state_changed (self,
		                         NM_DEVICE_STATE_UNAVAILABLE,
		                         NM_DEVICE_STATE_REASON_NOW_MANAGED);
	}
	return TRUE;
}

static gboolean
can_update_from_platform_link (NMDevice *self, const NMPlatformLink *plink)
{
	return TRUE;
}

void
nm_device_update_from_platform_link (NMDevice *self, const NMPlatformLink *plink)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const char *str;
	gboolean ifindex_changed;
	guint32 mtu;

	if (!NM_DEVICE_GET_CLASS (self)->can_update_from_platform_link (self, plink))
		return;

	g_return_if_fail (plink == NULL || link_type_compatible (self, plink->type, NULL, NULL));

	str = plink ? nm_platform_link_get_udi (nm_device_get_platform (self), plink->ifindex) : NULL;
	if (!nm_streq0 (str, priv->udi)) {
		g_free (priv->udi);
		priv->udi = g_strdup (str);
		_notify (self, PROP_UDI);
	}

	str = plink ? nm_platform_link_get_path (nm_device_get_platform (self), plink->ifindex) : NULL;
	if (!nm_streq0 (str, priv->path)) {
		g_free (priv->path);
		priv->path = g_strdup (str);
		_notify (self, PROP_PATH);
	}

	if (   plink
	    && !nm_str_is_empty (plink->name)
	    && nm_utils_strdup_reset (&priv->iface_, plink->name))
		_notify (self, PROP_IFACE);

	str = plink ? plink->driver : NULL;
	if (!nm_streq0 (str, priv->driver)) {
		g_free (priv->driver);
		priv->driver = g_strdup (str);
		_notify (self, PROP_DRIVER);
	}

	if (plink) {
		priv->up = NM_FLAGS_HAS (plink->n_ifi_flags, IFF_UP);
		if (plink->ifindex == nm_device_get_ip_ifindex (self))
			_stats_update_counters_from_pllink (self, plink);
	} else {
		priv->up = FALSE;
	}

	mtu = plink ? plink->mtu : 0;
	_set_mtu (self, mtu);

	ifindex_changed = _set_ifindex (self,
	                                plink ? plink->ifindex : 0,
	                                FALSE);

	if (ifindex_changed)
		NM_DEVICE_GET_CLASS (self)->link_changed (self, plink);

	device_update_interface_flags (self, plink);
}

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

static void
sriov_op_start (NMDevice *self, SriovOp *op)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	nm_assert (!priv->sriov.pending);

	op->cancellable = g_cancellable_new ();
	op->device = g_object_ref (self);
	priv->sriov.pending = op;

	nm_platform_link_set_sriov_params_async (nm_device_get_platform (self),
	                                         priv->ifindex,
	                                         op->num_vfs,
	                                         op->autoprobe,
	                                         sriov_op_cb,
	                                         op,
	                                         op->cancellable);
}

static void
sriov_op_cb (GError *error, gpointer user_data)
{
	SriovOp *op = user_data;
	gs_unref_object NMDevice *self = op->device;
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	nm_assert (op == priv->sriov.pending);

	g_clear_object (&op->cancellable);

	if (op->callback)
		op->callback (error, op->callback_data);

	priv->sriov.pending = NULL;
	nm_g_slice_free (op);

	if (priv->sriov.next) {
		sriov_op_start (self,
		                g_steal_pointer (&priv->sriov.next));
	}
}

static void
sriov_op_queue_op (NMDevice *self,
                   SriovOp *op)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->sriov.next) {
		SriovOp *op_next = g_steal_pointer (&priv->sriov.next);

		priv->sriov.next = op;

		/* Cancel the next operation immediately */
		if (op_next->callback) {
			gs_free_error GError *error = NULL;

			nm_utils_error_set_cancelled (&error, FALSE, NULL);
			op_next->callback (error, op_next->callback_data);
		}

		nm_g_slice_free (op_next);
		return;
	}

	if (priv->sriov.pending) {
		priv->sriov.next = op;
		g_cancellable_cancel (priv->sriov.pending->cancellable);
		return;
	}

	if (op)
		sriov_op_start (self, op);
}

static void
sriov_op_queue (NMDevice *self,
                guint num_vfs,
                NMTernary autoprobe,
                NMPlatformAsyncCallback callback,
                gpointer callback_data)
{
	SriovOp *op;

	/* We usually never want to cancel an async write operation, unless it's superseded
	 * by a newer operation (that resets the state). That is, because we need to ensure
	 * that we never end up doing two concurrent writes (since we write on a background
	 * thread, that would be unordered/racy).
	 * Of course, since we queue requests only per-device, when devices get renamed we
	 * might end up writing the same sysctl concurrently still. But that's really
	 * unlikely, and don't rename after udev completes!
	 *
	 * The "next" operation is not yet even started. It can be replaced/canceled right away
	 * when a newer request comes.
	 * The "pending" operation is currently ongoing, and we may cancel it if
	 * we have a follow-up operation (queued in "next"). Unless we have a such
	 * a newer request, we cannot cancel it!
	 *
	 * FIXME(shutdown): However, during shutdown we don't have a follow-up write request to cancel
	 * this operation and we have to give it at least some time to complete. The solution is that
	 * we register a way to abort the last call during shutdown, and after NM_SHUTDOWN_TIMEOUT_MS
	 * grace period we pull the plug and cancel it. */

	op = g_slice_new (SriovOp);
	*op = (SriovOp) {
		.num_vfs       = num_vfs,
		.autoprobe     = autoprobe,
		.callback      = callback,
		.callback_data = callback_data,
	};
	sriov_op_queue_op (self, op);
}

static void
device_init_static_sriov_num_vfs (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gs_free char *value = NULL;
	int num_vfs;

	if (   priv->ifindex > 0
	    && nm_device_has_capability (self, NM_DEVICE_CAP_SRIOV)) {
		value = nm_config_data_get_device_config (NM_CONFIG_GET_DATA,
		                                          NM_CONFIG_KEYFILE_KEY_DEVICE_SRIOV_NUM_VFS,
		                                          self,
		                                          NULL);
		num_vfs = _nm_utils_ascii_str_to_int64 (value, 10, 0, G_MAXINT32, -1);
		if (num_vfs >= 0)
			sriov_op_queue (self, num_vfs, NM_TERNARY_DEFAULT, NULL, NULL);
	}
}

static void
config_changed (NMConfig *config,
                NMConfigData *config_data,
                NMConfigChangeFlags changes,
                NMConfigData *old_data,
                NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (   priv->state <= NM_DEVICE_STATE_DISCONNECTED
	    || priv->state > NM_DEVICE_STATE_ACTIVATED) {
		priv->ignore_carrier = nm_config_data_get_ignore_carrier (config_data, self);
		if (NM_FLAGS_HAS (changes, NM_CONFIG_CHANGE_VALUES))
			device_init_static_sriov_num_vfs (self);
	}
}

static void
realize_start_notify (NMDevice *self,
                      const NMPlatformLink *pllink)
{
	/* the default implementation of realize_start_notify() just calls
	 * link_changed() -- which by default does nothing. */
	NM_DEVICE_GET_CLASS (self)->link_changed (self, pllink);
}

/**
 * realize_start_setup():
 * @self: the #NMDevice
 * @plink: the #NMPlatformLink if backed by a kernel netdevice
 * @assume_state_guess_assume: set the guess_assume state.
 * @assume_state_connection_uuid: set the connection uuid to assume.
 * @set_nm_owned: if TRUE and device is a software-device, set nm-owned.
 *    TRUE.
 * @unmanaged_user_explicit: the user-explict unmanaged flag to set.
 * @force_platform_init: if TRUE the platform-init unmanaged flag is
 *    forcefully cleared.
 *
 * Update the device from backing resource properties (like hardware
 * addresses, carrier states, driver/firmware info, etc).  This function
 * should only change properties for this device, and should not perform
 * any tasks that affect other interfaces (like master/slave or parent/child
 * stuff).
 */
static void
realize_start_setup (NMDevice *self,
                     const NMPlatformLink *plink,
                     gboolean assume_state_guess_assume,
                     const char *assume_state_connection_uuid,
                     gboolean set_nm_owned,
                     NMUnmanFlagOp unmanaged_user_explicit,
                     gboolean force_platform_init)
{
	NMDevicePrivate *priv;
	NMDeviceClass *klass;
	NMPlatform *platform;
	static guint32 id = 0;
	NMDeviceCapabilities capabilities = 0;
	NMConfig *config;
	guint real_rate;
	gboolean unmanaged;

	/* plink is a NMPlatformLink type, however, we require it to come from the platform
	 * cache (where else would it come from?). */
	nm_assert (!plink || NMP_OBJECT_GET_TYPE (NMP_OBJECT_UP_CAST (plink)) == NMP_OBJECT_TYPE_LINK);

	g_return_if_fail (NM_IS_DEVICE (self));

	priv = NM_DEVICE_GET_PRIVATE (self);

	/* The device should not be realized */
	g_return_if_fail (!priv->real);
	g_return_if_fail (nm_device_get_unmanaged_flags (self, NM_UNMANAGED_PLATFORM_INIT));
	g_return_if_fail (priv->ip_ifindex <= 0);
	g_return_if_fail (priv->ip_iface == NULL);
	g_return_if_fail (!priv->queued_ip_config_id_4);
	g_return_if_fail (!priv->queued_ip_config_id_6);

	_LOGD (LOGD_DEVICE, "start setup of %s, kernel ifindex %d", G_OBJECT_TYPE_NAME (self), plink ? plink->ifindex : 0);

	klass = NM_DEVICE_GET_CLASS (self);
	platform = nm_device_get_platform (self);

	/* Balanced by a thaw in nm_device_realize_finish() */
	g_object_freeze_notify (G_OBJECT (self));

	priv->mtu_source = NM_DEVICE_MTU_SOURCE_NONE;
	priv->mtu_initial = 0;
	priv->ip6_mtu_initial = 0;
	priv->ip6_mtu = 0;
	_set_mtu (self, 0);

	_assume_state_set (self, assume_state_guess_assume, assume_state_connection_uuid);

	nm_device_sys_iface_state_set (self, NM_DEVICE_SYS_IFACE_STATE_EXTERNAL);

	if (plink)
		nm_device_update_from_platform_link (self, plink);

	if (priv->ifindex > 0) {
		priv->physical_port_id = nm_platform_link_get_physical_port_id (platform, priv->ifindex);
		_notify (self, PROP_PHYSICAL_PORT_ID);

		priv->dev_id = nm_platform_link_get_dev_id (platform, priv->ifindex);

		if (nm_platform_link_is_software (platform, priv->ifindex))
			capabilities |= NM_DEVICE_CAP_IS_SOFTWARE;

		_set_mtu (self,
		          nm_platform_link_get_mtu (platform,
		                                    priv->ifindex));

		nm_platform_link_get_driver_info (platform,
		                                  priv->ifindex,
		                                  NULL,
		                                  &priv->driver_version,
		                                  &priv->firmware_version);
		if (priv->driver_version)
			_notify (self, PROP_DRIVER_VERSION);
		if (priv->firmware_version)
			_notify (self, PROP_FIRMWARE_VERSION);

		if (nm_platform_kernel_support_get (NM_PLATFORM_KERNEL_SUPPORT_TYPE_USER_IPV6LL))
			priv->ipv6ll_handle = nm_platform_link_get_user_ipv6ll_enabled (platform, priv->ifindex);

		if (nm_platform_link_supports_sriov (platform, priv->ifindex))
			capabilities |= NM_DEVICE_CAP_SRIOV;
	}

	if (klass->get_generic_capabilities)
		capabilities |= klass->get_generic_capabilities (self);

	_add_capabilities (self, capabilities);

	if (   !priv->nm_owned
	    && set_nm_owned
	    && nm_device_is_software (self)) {
		priv->nm_owned = TRUE;
		_LOGD (LOGD_DEVICE, "set nm-owned from state file");
	}

	if (!priv->udi) {
		/* Use a placeholder UDI until we get a real one */
		priv->udi = g_strdup_printf ("/virtual/device/placeholder/%d", id++);
		_notify (self, PROP_UDI);
	}

	nm_device_update_hw_address (self);
	nm_device_update_initial_hw_address (self);
	nm_device_update_permanent_hw_address (self, FALSE);

	/* Note: initial hardware address must be read before calling get_ignore_carrier() */
	config = nm_config_get ();
	priv->ignore_carrier = nm_config_data_get_ignore_carrier (nm_config_get_data (config), self);
	if (!priv->config_changed_id) {
		priv->config_changed_id = g_signal_connect (config,
		                                            NM_CONFIG_SIGNAL_CONFIG_CHANGED,
		                                            G_CALLBACK (config_changed),
		                                            self);
	}

	nm_device_set_carrier_from_platform (self);

	nm_assert (!priv->stats.timeout_id);
	real_rate = _stats_refresh_rate_real (priv->stats.refresh_rate_ms);
	if (real_rate)
		priv->stats.timeout_id = g_timeout_add (real_rate, _stats_timeout_cb, self);

	klass->realize_start_notify (self, plink);

	nm_assert (!nm_device_get_unmanaged_mask (self, NM_UNMANAGED_USER_EXPLICIT));
	nm_device_set_unmanaged_flags (self,
	                               NM_UNMANAGED_USER_EXPLICIT,
	                               unmanaged_user_explicit);

	/* Do not manage externally created software devices until they are IFF_UP
	 * or have IP addressing */
	nm_device_set_unmanaged_flags (self,
	                               NM_UNMANAGED_EXTERNAL_DOWN,
	                               is_unmanaged_external_down (self, TRUE));

	/* Unmanaged the loopback device with an explicit NM_UNMANAGED_BY_TYPE flag.
	 * Later we might want to manage 'lo' too. Currently, that doesn't work because
	 * NetworkManager might down the interface or remove the 127.0.0.1 address. */
	nm_device_set_unmanaged_flags (self,
	                               NM_UNMANAGED_BY_TYPE,
	                               is_loopback (self));

	nm_device_set_unmanaged_by_user_udev (self);
	nm_device_set_unmanaged_by_user_conf (self);

	unmanaged =    plink
	            && !plink->initialized
	            && !force_platform_init;

	nm_device_set_unmanaged_flags (self, NM_UNMANAGED_PLATFORM_INIT,
	                               unmanaged);
}

/**
 * nm_device_realize_finish():
 * @self: the #NMDevice
 * @plink: the #NMPlatformLink if backed by a kernel netdevice
 *
 * Update the device's master/slave or parent/child relationships from
 * backing resource properties.  After this function finishes, the device
 * is ready for network connectivity.
 */
void
nm_device_realize_finish (NMDevice *self, const NMPlatformLink *plink)
{
	NMDevicePrivate *priv;

	g_return_if_fail (NM_IS_DEVICE (self));
	g_return_if_fail (!plink || link_type_compatible (self, plink->type, NULL, NULL));

	priv = NM_DEVICE_GET_PRIVATE (self);

	g_return_if_fail (!priv->real);

	if (plink)
		device_recheck_slave_status (self, plink);

	priv->update_ip_config_completed_v4 = FALSE;
	priv->update_ip_config_completed_v6 = FALSE;

	priv->real = TRUE;
	_notify (self, PROP_REAL);

	nm_device_recheck_available_connections (self);

	/* Balanced by a freeze in realize_start_setup(). */
	g_object_thaw_notify (G_OBJECT (self));
}

static void
unrealize_notify (NMDevice *self)
{
	/* Stub implementation for unrealize_notify(). It does nothing,
	 * but allows derived classes to uniformly invoke the parent
	 * implementation. */
}

static gboolean
available_connections_check_delete_unrealized_on_idle (gpointer user_data)
{
	NMDevice *self = user_data;
	NMDevicePrivate *priv;

	g_return_val_if_fail (NM_IS_DEVICE (self), G_SOURCE_REMOVE);

	priv = NM_DEVICE_GET_PRIVATE (self);

	priv->check_delete_unrealized_id = 0;

	if (   g_hash_table_size (priv->available_connections) == 0
	    && !nm_device_is_real (self))
		g_signal_emit (self, signals[REMOVED], 0);

	return G_SOURCE_REMOVE;
}

static void
available_connections_check_delete_unrealized (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	/* always rescheadule the remove signal. */
	nm_clear_g_source (&priv->check_delete_unrealized_id);

	if (   g_hash_table_size (priv->available_connections) == 0
	    && !nm_device_is_real (self))
		priv->check_delete_unrealized_id = g_idle_add (available_connections_check_delete_unrealized_on_idle, self);
}

/**
 * nm_device_unrealize():
 * @self: the #NMDevice
 * @remove_resources: if %TRUE, remove backing resources
 * @error: location to store error, or %NULL
 *
 * Clears any properties that depend on backing resources (kernel devices,
 * etc) and removes those resources if @remove_resources is %TRUE.
 *
 * Returns: %TRUE on success, %FALSE on error
 */
gboolean
nm_device_unrealize (NMDevice *self, gboolean remove_resources, GError **error)
{
	NMDevicePrivate *priv;
	int ifindex;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	if (!nm_device_is_software (self) || !nm_device_is_real (self)) {
		g_set_error_literal (error,
		                     NM_DEVICE_ERROR,
		                     NM_DEVICE_ERROR_NOT_SOFTWARE,
		                     "This device is not a software device or is not realized");
		return FALSE;
	}

	priv = NM_DEVICE_GET_PRIVATE (self);

	g_return_val_if_fail (priv->iface != NULL, FALSE);
	g_return_val_if_fail (priv->real, FALSE);

	ifindex = nm_device_get_ifindex (self);

	_LOGD (LOGD_DEVICE, "unrealize (ifindex %d)", ifindex > 0 ? ifindex : 0);

	nm_device_assume_state_reset (self);

	if (remove_resources) {
		if (NM_DEVICE_GET_CLASS (self)->unrealize) {
			if (!NM_DEVICE_GET_CLASS (self)->unrealize (self, error))
				return FALSE;
		} else if (ifindex > 0) {
			nm_platform_link_delete (nm_device_get_platform (self), ifindex);
		}
	}

	nm_clear_g_source (&priv->queued_ip_config_id_4);
	nm_clear_g_source (&priv->queued_ip_config_id_6);

	g_object_freeze_notify (G_OBJECT (self));
	NM_DEVICE_GET_CLASS (self)->unrealize_notify (self);

	_parent_set_ifindex (self, 0, FALSE);

	_set_ifindex (self, 0, FALSE);
	_set_ifindex (self, 0, TRUE);
	if (nm_clear_g_free (&priv->ip_iface_))
		_notify (self, PROP_IP_IFACE);

	_set_mtu (self, 0);

	if (priv->driver_version) {
		nm_clear_g_free (&priv->driver_version);
		_notify (self, PROP_DRIVER_VERSION);
	}
	if (priv->firmware_version) {
		nm_clear_g_free (&priv->firmware_version);
		_notify (self, PROP_FIRMWARE_VERSION);
	}
	if (priv->udi) {
		nm_clear_g_free (&priv->udi);
		_notify (self, PROP_UDI);
	}
	if (priv->path) {
		nm_clear_g_free (&priv->path);
		_notify (self, PROP_PATH);
	}
	if (priv->physical_port_id) {
		nm_clear_g_free (&priv->physical_port_id);
		_notify (self, PROP_PHYSICAL_PORT_ID);
	}

	nm_clear_g_source (&priv->stats.timeout_id);
	_stats_update_counters (self, 0, 0);

	priv->hw_addr_len_ = 0;
	if (nm_clear_g_free (&priv->hw_addr))
		_notify (self, PROP_HW_ADDRESS);
	priv->hw_addr_type = HW_ADDR_TYPE_UNSET;
	if (nm_clear_g_free (&priv->hw_addr_perm))
		_notify (self, PROP_PERM_HW_ADDRESS);
	nm_clear_g_free (&priv->hw_addr_initial);

	priv->capabilities = NM_DEVICE_CAP_NM_SUPPORTED;
	if (NM_DEVICE_GET_CLASS (self)->get_generic_capabilities)
		priv->capabilities |= NM_DEVICE_GET_CLASS (self)->get_generic_capabilities (self);
	_notify (self, PROP_CAPABILITIES);

	nm_clear_g_signal_handler (nm_config_get (), &priv->config_changed_id);

	priv->real = FALSE;
	_notify (self, PROP_REAL);

	g_object_thaw_notify (G_OBJECT (self));

	nm_device_set_unmanaged_flags (self,
	                               NM_UNMANAGED_PLATFORM_INIT,
	                               TRUE);

	nm_device_set_unmanaged_flags (self,
	                               NM_UNMANAGED_PARENT |
	                               NM_UNMANAGED_BY_TYPE |
	                               NM_UNMANAGED_USER_UDEV |
	                               NM_UNMANAGED_USER_EXPLICIT |
	                               NM_UNMANAGED_EXTERNAL_DOWN |
	                               NM_UNMANAGED_IS_SLAVE,
	                               NM_UNMAN_FLAG_OP_FORGET);

	nm_device_state_changed (self,
	                         NM_DEVICE_STATE_UNMANAGED,
	                         remove_resources ?
	                             NM_DEVICE_STATE_REASON_USER_REQUESTED : NM_DEVICE_STATE_REASON_NOW_UNMANAGED);

	/* Garbage-collect unneeded unrealized devices. */
	nm_device_recheck_available_connections (self);

	return TRUE;
}

void
nm_device_notify_availability_maybe_changed (NMDevice *self)
{
	NMDevicePrivate *priv;

	g_return_if_fail (NM_IS_DEVICE (self));

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->state != NM_DEVICE_STATE_DISCONNECTED)
		return;

	/* A device could have stayed disconnected because it would
	 * want to register with a network server that now become
	 * available. */
	nm_device_recheck_available_connections (self);
	if (g_hash_table_size (priv->available_connections) > 0)
		nm_device_emit_recheck_auto_activate (self);
}

/**
 * nm_device_owns_iface():
 * @self: the #NMDevice
 * @iface: an interface name
 *
 * Called by the manager to ask if the device or any of its components owns
 * @iface.  For example, a WWAN implementation would return %TRUE for an
 * ethernet interface name that was owned by the WWAN device's modem component,
 * because that ethernet interface is controlled by the WWAN device and cannot
 * be used independently of the WWAN device.
 *
 * Returns: %TRUE if @self or its components own the interface name,
 * %FALSE if not
 */
gboolean
nm_device_owns_iface (NMDevice *self, const char *iface)
{
	if (NM_DEVICE_GET_CLASS (self)->owns_iface)
		return NM_DEVICE_GET_CLASS (self)->owns_iface (self, iface);
	return FALSE;
}

NMConnection *
nm_device_new_default_connection (NMDevice *self)
{
	NMConnection *connection;
	GError *error = NULL;

	if (!NM_DEVICE_GET_CLASS (self)->new_default_connection)
		return NULL;

	connection = NM_DEVICE_GET_CLASS (self)->new_default_connection (self);
	if (!connection)
		return NULL;

	if (!nm_connection_normalize (connection, NULL, NULL, &error)) {
		_LOGD (LOGD_DEVICE, "device generated an invalid default connection: %s", error->message);
		g_error_free (error);
		g_return_val_if_reached (NULL);
	}

	return connection;
}

static void
slave_state_changed (NMDevice *slave,
                     NMDeviceState slave_new_state,
                     NMDeviceState slave_old_state,
                     NMDeviceStateReason reason,
                     NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gboolean release = FALSE;
	gboolean configure;

	_LOGD (LOGD_DEVICE, "slave %s state change %d (%s) -> %d (%s)",
	       nm_device_get_iface (slave),
	       slave_old_state,
	       nm_device_state_to_str (slave_old_state),
	       slave_new_state,
	       nm_device_state_to_str (slave_new_state));

	/* Don't try to enslave slaves until the master is ready */
	if (priv->state < NM_DEVICE_STATE_CONFIG)
		return;

	if (slave_new_state == NM_DEVICE_STATE_IP_CONFIG)
		nm_device_master_enslave_slave (self, slave, nm_device_get_applied_connection (slave));
	else if (slave_new_state > NM_DEVICE_STATE_ACTIVATED)
		release = TRUE;
	else if (   slave_new_state <= NM_DEVICE_STATE_DISCONNECTED
	         && slave_old_state > NM_DEVICE_STATE_DISCONNECTED) {
		/* Catch failures due to unavailable or unmanaged */
		release = TRUE;
	}

	if (release) {
		configure =    priv->sys_iface_state == NM_DEVICE_SYS_IFACE_STATE_MANAGED
		            && nm_device_sys_iface_state_get (slave) != NM_DEVICE_SYS_IFACE_STATE_EXTERNAL;

		nm_device_master_release_one_slave (self, slave,
		                                    configure,
		                                    FALSE,
		                                    reason);
		/* Bridge/bond/team interfaces are left up until manually deactivated */
		if (   c_list_is_empty (&priv->slaves)
		    && priv->state == NM_DEVICE_STATE_ACTIVATED)
			_LOGD (LOGD_DEVICE, "last slave removed; remaining activated");
	}
}

/**
 * nm_device_master_add_slave:
 * @self: the master device
 * @slave: the slave device to enslave
 * @configure: pass %TRUE if the slave should be configured by the master, or
 * %FALSE if it is already configured outside NetworkManager
 *
 * If @self is capable of enslaving other devices (ie it's a bridge, bond, team,
 * etc) then this function adds @slave to the slave list for later enslavement.
 *
 * Returns: %TRUE if the slave was enslaved. %FALSE means, the slave was already
 *   enslaved and nothing was done.
 */
static gboolean
nm_device_master_add_slave (NMDevice *self, NMDevice *slave, gboolean configure)
{
	NMDevicePrivate *priv;
	NMDevicePrivate *slave_priv;
	SlaveInfo *info;
	gboolean changed = FALSE;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
	g_return_val_if_fail (NM_IS_DEVICE (slave), FALSE);
	g_return_val_if_fail (NM_DEVICE_GET_CLASS (self)->enslave_slave != NULL, FALSE);

	priv = NM_DEVICE_GET_PRIVATE (self);
	slave_priv = NM_DEVICE_GET_PRIVATE (slave);

	info = find_slave_info (self, slave);

	_LOGT (LOGD_CORE, "master: add one slave %p/%s%s", slave, nm_device_get_iface (slave),
	       info ? " (already registered)" : "");

	if (configure)
		g_return_val_if_fail (nm_device_get_state (slave) >= NM_DEVICE_STATE_DISCONNECTED, FALSE);

	if (!info) {
		g_return_val_if_fail (!slave_priv->master, FALSE);
		g_return_val_if_fail (!slave_priv->is_enslaved, FALSE);

		info = g_slice_new0 (SlaveInfo);
		info->slave = g_object_ref (slave);
		info->configure = configure;
		info->watch_id = g_signal_connect (slave,
		                                   NM_DEVICE_STATE_CHANGED,
		                                   G_CALLBACK (slave_state_changed), self);
		c_list_link_tail (&priv->slaves, &info->lst_slave);
		slave_priv->master = g_object_ref (self);

		_active_connection_set_state_flags (self,
		                                    NM_ACTIVATION_STATE_FLAG_MASTER_HAS_SLAVES);

		/* no need to emit
		 *
		 *   _notify (slave, PROP_MASTER);
		 *
		 * because slave_priv->is_enslaved is not true, thus the value
		 * didn't change yet. */

		g_warn_if_fail (!NM_FLAGS_HAS (slave_priv->unmanaged_mask, NM_UNMANAGED_IS_SLAVE));
		nm_device_set_unmanaged_by_flags (slave, NM_UNMANAGED_IS_SLAVE, FALSE, NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);
		changed = TRUE;
	} else
		g_return_val_if_fail (slave_priv->master == self, FALSE);

	nm_device_queue_recheck_assume (self);
	nm_device_queue_recheck_assume (slave);

	return changed;
}

/**
 * nm_device_master_check_slave_physical_port:
 * @self: the master device
 * @slave: a slave device
 * @log_domain: domain to log a warning in
 *
 * Checks if @self already has a slave with the same #NMDevice:physical-port-id
 * as @slave, and logs a warning if so.
 */
void
nm_device_master_check_slave_physical_port (NMDevice *self, NMDevice *slave,
                                            NMLogDomain log_domain)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const char *slave_physical_port_id, *existing_physical_port_id;
	SlaveInfo *info;
	CList *iter;

	slave_physical_port_id = nm_device_get_physical_port_id (slave);
	if (!slave_physical_port_id)
		return;

	c_list_for_each (iter, &priv->slaves) {
		info = c_list_entry (iter, SlaveInfo, lst_slave);
		if (info->slave == slave)
			continue;

		existing_physical_port_id = nm_device_get_physical_port_id (info->slave);
		if (nm_streq0 (slave_physical_port_id, existing_physical_port_id)) {
			_LOGW (log_domain, "slave %s shares a physical port with existing slave %s",
			       nm_device_get_ip_iface (slave),
			       nm_device_get_ip_iface (info->slave));
			/* Since this function will get called for every slave, we only have
			 * to warn about the first match we find; if there are other matches
			 * later in the list, we will have already warned about them matching
			 * @existing earlier.
			 */
			return;
		}
	}
}

/* release all slaves */
static void
nm_device_master_release_slaves (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMDeviceStateReason reason;
	CList *iter, *safe;

	/* Don't release the slaves if this connection doesn't belong to NM. */
	if (nm_device_sys_iface_state_is_external (self))
		return;

	reason = priv->state_reason;
	if (priv->state == NM_DEVICE_STATE_FAILED)
		reason = NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED;

	c_list_for_each_safe (iter, safe, &priv->slaves) {
		SlaveInfo *info = c_list_entry (iter, SlaveInfo, lst_slave);

		nm_device_master_release_one_slave (self, info->slave, TRUE, FALSE, reason);
	}
}

/**
 * nm_device_is_master:
 * @self: the device
 *
 * Returns: %TRUE if the device can have slaves
 */
gboolean
nm_device_is_master (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	return NM_DEVICE_GET_CLASS (self)->is_master;
}

/**
 * nm_device_get_master:
 * @self: the device
 *
 * If @self has been enslaved by another device, this returns that
 * device. Otherwise, it returns %NULL. (In particular, note that if
 * @self is in the process of activating as a slave, but has not yet
 * been enslaved by its master, this will return %NULL.)
 *
 * Returns: (transfer none): @self's master, or %NULL
 */
NMDevice *
nm_device_get_master (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->is_enslaved) {
		g_return_val_if_fail (priv->master, NULL);
		return priv->master;
	}
	return NULL;
}

static gboolean
get_ip_config_may_fail (NMDevice *self, int addr_family)
{
	NMConnection *connection;
	NMSettingIPConfig *s_ip;

	connection = nm_device_get_applied_connection (self);

	s_ip = nm_connection_get_setting_ip_config (connection, addr_family);

	return !s_ip || nm_setting_ip_config_get_may_fail (s_ip);
}

/*
 * check_ip_state
 *
 * When @full_state_update is TRUE, transition the device from IP_CONFIG to the
 * next state according to the outcome of IPv4 and IPv6 configuration. @may_fail
 * indicates that we are called just after the initial configuration and thus
 * IPv4/IPv6 are allowed to fail if the ipvx.may-fail properties say so, because
 * the IP methods couldn't even be started.
 * If @full_state_update is FALSE, just check if the connection should be failed
 * due to the state of both ip families and the ipvx.may-fail settings.
 */
static void
check_ip_state (NMDevice *self, gboolean may_fail, gboolean full_state_update)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gboolean ip4_disabled = FALSE, ip6_disabled = FALSE;
	NMSettingIPConfig *s_ip4, *s_ip6;
	NMDeviceState state;

	if (   full_state_update
	    && nm_device_get_state (self) != NM_DEVICE_STATE_IP_CONFIG)
		return;

	/* Don't progress into IP_CHECK or SECONDARIES if we're waiting for the
	 * master to enslave us. */
	if (   nm_active_connection_get_master (NM_ACTIVE_CONNECTION (priv->act_request.obj))
	    && !priv->is_enslaved)
		return;

	s_ip4 = nm_device_get_applied_setting (self, NM_TYPE_SETTING_IP4_CONFIG);
	if (s_ip4 && nm_streq0 (nm_setting_ip_config_get_method (s_ip4),
	                        NM_SETTING_IP4_CONFIG_METHOD_DISABLED))
		ip4_disabled = TRUE;

	s_ip6 = nm_device_get_applied_setting (self, NM_TYPE_SETTING_IP6_CONFIG);
	if (s_ip6 && NM_IN_STRSET (nm_setting_ip_config_get_method (s_ip6),
	                           NM_SETTING_IP6_CONFIG_METHOD_IGNORE,
	                           NM_SETTING_IP6_CONFIG_METHOD_DISABLED))
		ip6_disabled = TRUE;

	if (   priv->ip_state_4 == NM_DEVICE_IP_STATE_DONE
	    && priv->ip_state_6 == NM_DEVICE_IP_STATE_DONE) {
		/* Both method completed (or disabled), proceed with activation */
		nm_device_state_changed (self, NM_DEVICE_STATE_IP_CHECK, NM_DEVICE_STATE_REASON_NONE);
		return;
	}

	if (   (priv->ip_state_4 == NM_DEVICE_IP_STATE_FAIL || (ip4_disabled && priv->ip_state_4 == NM_DEVICE_IP_STATE_DONE))
	    && (priv->ip_state_6 == NM_DEVICE_IP_STATE_FAIL || (ip6_disabled && priv->ip_state_6 == NM_DEVICE_IP_STATE_DONE))) {
		/* Either both methods failed, or only one failed and the other is
		 * disabled */
		if (nm_device_sys_iface_state_is_external_or_assume (self)) {
			/* We have assumed configuration, but couldn't redo it. No problem,
			 * move to check state. */
			_set_ip_state (self, AF_INET, NM_DEVICE_IP_STATE_DONE);
			_set_ip_state (self, AF_INET6, NM_DEVICE_IP_STATE_DONE);
			state = NM_DEVICE_STATE_IP_CHECK;
		} else if (   may_fail
		           && get_ip_config_may_fail (self, AF_INET)
		           && get_ip_config_may_fail (self, AF_INET6)) {
			/* Couldn't start either IPv6 and IPv4 autoconfiguration,
			 * but both are allowed to fail. */
			state = NM_DEVICE_STATE_SECONDARIES;
		} else {
			/* Autoconfiguration attempted without success. */
			state = NM_DEVICE_STATE_FAILED;
		}

		if (   full_state_update
		    || state == NM_DEVICE_STATE_FAILED) {
			nm_device_state_changed (self,
			                         state,
			                         NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE);
		}
		return;
	}

	/* If a method is still pending but required, wait */
	if (priv->ip_state_4 != NM_DEVICE_IP_STATE_DONE && !get_ip_config_may_fail (self, AF_INET))
		return;
	if (priv->ip_state_6 != NM_DEVICE_IP_STATE_DONE && !get_ip_config_may_fail (self, AF_INET6))
		return;

	/* If at least a method has completed, proceed with activation */
	if (   (priv->ip_state_4 == NM_DEVICE_IP_STATE_DONE && !ip4_disabled)
	    || (priv->ip_state_6 == NM_DEVICE_IP_STATE_DONE && !ip6_disabled)) {
		if (full_state_update)
			nm_device_state_changed (self, NM_DEVICE_STATE_IP_CHECK, NM_DEVICE_STATE_REASON_NONE);
		return;
	}
}

/**
 * nm_device_slave_notify_enslave:
 * @self: the slave device
 * @success: whether the enslaving operation succeeded
 *
 * Notifies a slave that either it has been enslaved, or else its master tried
 * to enslave it and failed.
 */
static void
nm_device_slave_notify_enslave (NMDevice *self, gboolean success)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMConnection *connection = nm_device_get_applied_connection (self);
	gboolean activating = (priv->state == NM_DEVICE_STATE_IP_CONFIG);

	g_return_if_fail (priv->master);

	if (!priv->is_enslaved) {
		if (success) {
			if (activating) {
				_LOGI (LOGD_DEVICE, "Activation: connection '%s' enslaved, continuing activation",
				       nm_connection_get_id (connection));
			} else
				_LOGI (LOGD_DEVICE, "enslaved to %s", nm_device_get_iface (priv->master));

			priv->is_enslaved = TRUE;

			_notify (self, PROP_MASTER);
			_notify (priv->master, PROP_SLAVES);
		} else if (activating) {
			_LOGW (LOGD_DEVICE, "Activation: connection '%s' could not be enslaved",
			       nm_connection_get_id (connection));
		}
	}

	if (activating) {
		if (success)
			check_ip_state (self, FALSE, TRUE);
		else
			nm_device_queue_state (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_UNKNOWN);
	} else
		nm_device_queue_recheck_assume (self);
}

/**
 * nm_device_slave_notify_release:
 * @self: the slave device
 * @reason: the reason associated with the state change
 *
 * Notifies a slave that it has been released, and why.
 */
static void
nm_device_slave_notify_release (NMDevice *self, NMDeviceStateReason reason)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMConnection *connection = nm_device_get_applied_connection (self);
	const char *master_status;

	g_return_if_fail (priv->master);

	if (   priv->state > NM_DEVICE_STATE_DISCONNECTED
	    && priv->state <= NM_DEVICE_STATE_ACTIVATED) {
		switch (nm_device_state_reason_check (reason)) {
		case NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED:
			master_status = "failed";
			break;
		case NM_DEVICE_STATE_REASON_USER_REQUESTED:
			reason = NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED;
			master_status = "deactivated by user request";
			break;
		case NM_DEVICE_STATE_REASON_CONNECTION_REMOVED:
			reason = NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED;
			master_status = "deactivated because master was removed";
			break;
		default:
			master_status = "deactivated";
			break;
		}

		_LOGD (LOGD_DEVICE, "Activation: connection '%s' master %s",
		       nm_connection_get_id (connection),
		       master_status);

		/* Cancel any pending activation sources */
		_cancel_activation (self);
		nm_device_queue_state (self, NM_DEVICE_STATE_DEACTIVATING, reason);
	} else
		_LOGI (LOGD_DEVICE, "released from master device %s", nm_device_get_iface (priv->master));

	if (priv->is_enslaved) {
		priv->is_enslaved = FALSE;
		_notify (self, PROP_MASTER);
		_notify (priv->master, PROP_SLAVES);
	}
}

/**
 * nm_device_removed:
 * @self: the #NMDevice
 * @unconfigure_ip_config: whether to clear the IP config objects
 *   of the device (provided, it is still not cleared at this point).
 *
 * Called by the manager when the device was removed. Releases the device from
 * the master in case it's enslaved.
 */
void
nm_device_removed (NMDevice *self, gboolean unconfigure_ip_config)
{
	NMDevicePrivate *priv;

	g_return_if_fail (NM_IS_DEVICE (self));

	priv = NM_DEVICE_GET_PRIVATE (self);
	if (priv->master) {
		/* this is called when something externally messes with the slave or during shut-down.
		 * Release the slave from master, but don't touch the device. */
		nm_device_master_release_one_slave (priv->master, self, FALSE, FALSE, NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);
	}

	if (unconfigure_ip_config) {
		nm_device_set_ip_config (self, AF_INET, NULL, FALSE, NULL);
		nm_device_set_ip_config (self, AF_INET6, NULL, FALSE, NULL);
	} else {
		if (priv->dhcp_data_4.client)
			nm_dhcp_client_stop (priv->dhcp_data_4.client, FALSE);
		if (priv->dhcp_data_6.client)
			nm_dhcp_client_stop (priv->dhcp_data_6.client, FALSE);
	}
}

static gboolean
is_available (NMDevice *self, NMDeviceCheckDevAvailableFlags flags)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (   priv->carrier
	    || priv->ignore_carrier)
		return TRUE;

	if (NM_FLAGS_HAS (flags, _NM_DEVICE_CHECK_DEV_AVAILABLE_IGNORE_CARRIER))
		return TRUE;

	/* master types are always available even without carrier. */
	if (nm_device_is_master (self))
		return TRUE;

	return FALSE;
}

/**
 * nm_device_is_available:
 * @self: the #NMDevice
 * @flags: additional flags to influence the check. Flags have the
 *   meaning to increase the availability of a device.
 *
 * Checks if @self would currently be capable of activating a
 * connection. In particular, it checks that the device is ready (eg,
 * is not missing firmware), that it has carrier (if necessary), and
 * that any necessary external software (eg, ModemManager,
 * wpa_supplicant) is available.
 *
 * @self can only be in a state higher than
 * %NM_DEVICE_STATE_UNAVAILABLE when nm_device_is_available() returns
 * %TRUE. (But note that it can still be %NM_DEVICE_STATE_UNMANAGED
 * when it is available.)
 *
 * Returns: %TRUE or %FALSE
 */
gboolean
nm_device_is_available (NMDevice *self, NMDeviceCheckDevAvailableFlags flags)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->firmware_missing)
		return FALSE;

	return NM_DEVICE_GET_CLASS (self)->is_available (self, flags);
}

gboolean
nm_device_ignore_carrier_by_default (NMDevice *self)
{
	/* master types ignore-carrier by default. */
	return nm_device_is_master (self);
}

gboolean
nm_device_get_enabled (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	if (NM_DEVICE_GET_CLASS (self)->get_enabled)
		return NM_DEVICE_GET_CLASS (self)->get_enabled (self);
	return TRUE;
}

void
nm_device_set_enabled (NMDevice *self, gboolean enabled)
{
	g_return_if_fail (NM_IS_DEVICE (self));

	if (NM_DEVICE_GET_CLASS (self)->set_enabled)
		NM_DEVICE_GET_CLASS (self)->set_enabled (self, enabled);
}

static
NM_UTILS_FLAGS2STR_DEFINE (_autoconnect_blocked_flags_to_string, NMDeviceAutoconnectBlockedFlags,
	NM_UTILS_FLAGS2STR (NM_DEVICE_AUTOCONNECT_BLOCKED_NONE,              "none"),
	NM_UTILS_FLAGS2STR (NM_DEVICE_AUTOCONNECT_BLOCKED_USER,              "user"),
	NM_UTILS_FLAGS2STR (NM_DEVICE_AUTOCONNECT_BLOCKED_WRONG_PIN,         "wrong-pin"),
	NM_UTILS_FLAGS2STR (NM_DEVICE_AUTOCONNECT_BLOCKED_MANUAL_DISCONNECT, "manual-disconnect"),
);

NMDeviceAutoconnectBlockedFlags
nm_device_autoconnect_blocked_get (NMDevice *self, NMDeviceAutoconnectBlockedFlags mask)
{
	NMDevicePrivate *priv;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	if (mask == 0)
		mask = NM_DEVICE_AUTOCONNECT_BLOCKED_ALL;

	priv = NM_DEVICE_GET_PRIVATE (self);
	return priv->autoconnect_blocked_flags & mask;
}

void
nm_device_autoconnect_blocked_set_full (NMDevice *self, NMDeviceAutoconnectBlockedFlags mask, NMDeviceAutoconnectBlockedFlags value)
{
	NMDevicePrivate *priv;
	gboolean changed;
	char buf1[128], buf2[128];

	g_return_if_fail (NM_IS_DEVICE (self));
	nm_assert (mask);
	nm_assert (!NM_FLAGS_ANY (mask, ~NM_DEVICE_AUTOCONNECT_BLOCKED_ALL));
	nm_assert (!NM_FLAGS_ANY (value, ~mask));

	priv = NM_DEVICE_GET_PRIVATE (self);

	value = (priv->autoconnect_blocked_flags & ~mask) | (mask & value);
	if (value == priv->autoconnect_blocked_flags)
		return;

	changed = ((!value) != (!priv->autoconnect_blocked_flags));

	_LOGT (LOGD_DEVICE, "autoconnect-blocked: set \"%s\" (was \"%s\")",
	       _autoconnect_blocked_flags_to_string (value, buf1, sizeof (buf1)),
	       _autoconnect_blocked_flags_to_string (priv->autoconnect_blocked_flags, buf2, sizeof (buf2)));

	priv->autoconnect_blocked_flags = value;
	nm_assert (priv->autoconnect_blocked_flags == value);
	if (changed)
		_notify (self, PROP_AUTOCONNECT);
}

static gboolean
autoconnect_allowed_accumulator (GSignalInvocationHint *ihint,
                                 GValue *return_accu,
                                 const GValue *handler_return, gpointer data)
{
	if (!g_value_get_boolean (handler_return))
		g_value_set_boolean (return_accu, FALSE);
	return TRUE;
}

/**
 * nm_device_autoconnect_allowed:
 * @self: the #NMDevice
 *
 * Returns: %TRUE if the device can be auto-connected immediately, taking
 * transient conditions into account (like companion devices that may wish to
 * block autoconnect for a time).
 */
gboolean
nm_device_autoconnect_allowed (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self);
	GValue instance = G_VALUE_INIT;
	GValue retval = G_VALUE_INIT;

	if (nm_device_autoconnect_blocked_get (self, NM_DEVICE_AUTOCONNECT_BLOCKED_ALL))
		return FALSE;

	if (   klass->get_autoconnect_allowed
	    && !klass->get_autoconnect_allowed (self))
		return FALSE;

	if (!nm_device_get_enabled (self))
		return FALSE;

	if (nm_device_is_real (self)) {
		if (priv->state < NM_DEVICE_STATE_DISCONNECTED)
			return FALSE;
	} else {
		if (!nm_device_check_unrealized_device_managed (self))
			return FALSE;
	}

	if (priv->delete_on_deactivate_data)
		return FALSE;

	/* The 'autoconnect-allowed' signal is emitted on a device to allow
	 * other listeners to block autoconnect on the device if they wish.
	 * This is mainly used by the OLPC Mesh devices to block autoconnect
	 * on their companion Wi-Fi device as they share radio resources and
	 * cannot be connected at the same time.
	 */

	g_value_init (&instance, G_TYPE_OBJECT);
	g_value_set_object (&instance, self);

	g_value_init (&retval, G_TYPE_BOOLEAN);
	g_value_set_boolean (&retval, TRUE);

	/* Use g_signal_emitv() rather than g_signal_emit() to avoid the return
	 * value being changed if no handlers are connected */
	g_signal_emitv (&instance, signals[AUTOCONNECT_ALLOWED], 0, &retval);
	g_value_unset (&instance);

	return g_value_get_boolean (&retval);
}

static gboolean
can_auto_connect (NMDevice *self,
                  NMSettingsConnection *sett_conn,
                  char **specific_object)
{
	nm_assert (!specific_object || !*specific_object);
	return TRUE;
}

/**
 * nm_device_can_auto_connect:
 * @self: an #NMDevice
 * @sett_conn: a #NMSettingsConnection
 * @specific_object: (out) (transfer full): on output, the path of an
 *   object associated with the returned connection, to be passed to
 *   nm_manager_activate_connection(), or %NULL.
 *
 * Checks if @sett_conn can be auto-activated on @self right now.
 * This requires, at a minimum, that the connection be compatible with
 * @self, and that it have the #NMSettingConnection:autoconnect property
 * set, and that the device allow auto connections. Some devices impose
 * additional requirements. (Eg, a Wi-Fi connection can only be activated
 * if its SSID was seen in the last scan.)
 *
 * Returns: %TRUE, if the @sett_conn can be auto-activated.
 **/
gboolean
nm_device_can_auto_connect (NMDevice *self,
                            NMSettingsConnection *sett_conn,
                            char **specific_object)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
	g_return_val_if_fail (NM_IS_SETTINGS_CONNECTION (sett_conn), FALSE);
	g_return_val_if_fail (!specific_object || !*specific_object, FALSE);

	/* the caller must ensure that nm_device_autoconnect_allowed() returns
	 * TRUE as well. This is done, because nm_device_can_auto_connect()
	 * has only one caller, and it iterates over a list of available
	 * connections.
	 *
	 * Hence, we don't need to re-check nm_device_autoconnect_allowed()
	 * over and over again. The caller is supposed to do that. */
	nm_assert (nm_device_autoconnect_allowed (self));

	if (!nm_device_check_connection_available (self,
	                                           nm_settings_connection_get_connection (sett_conn),
	                                           NM_DEVICE_CHECK_CON_AVAILABLE_NONE,
	                                           NULL,
	                                           NULL))
		return FALSE;

	if (!NM_DEVICE_GET_CLASS (self)->can_auto_connect (self, sett_conn, specific_object))
		return FALSE;

	return TRUE;
}

static gboolean
device_has_config (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	/* Check for IP configuration. */
	if (priv->ip_config_4 && nm_ip4_config_get_num_addresses (priv->ip_config_4))
		return TRUE;
	if (priv->ip_config_6 && nm_ip6_config_get_num_addresses (priv->ip_config_6))
		return TRUE;

	/* The existence of a software device is good enough. */
	if (nm_device_is_software (self) && nm_device_is_real (self))
		return TRUE;

	/* Master-slave relationship is also a configuration */
	if (   !c_list_is_empty (&priv->slaves)
	    || nm_platform_link_get_master (nm_device_get_platform (self), priv->ifindex) > 0)
		return TRUE;

	return FALSE;
}

/**
 * nm_device_master_update_slave_connection:
 * @self: the master #NMDevice
 * @slave: the slave #NMDevice
 * @connection: the #NMConnection to update with the slave settings
 * @GError: (out): error description
 *
 * Reads the slave configuration for @slave and updates @connection with those
 * properties. This invokes a virtual function on the master device @self.
 *
 * Returns: %TRUE if the configuration was read and @connection updated,
 * %FALSE on failure.
 */
gboolean
nm_device_master_update_slave_connection (NMDevice *self,
                                          NMDevice *slave,
                                          NMConnection *connection,
                                          GError **error)
{
	NMDeviceClass *klass;
	gboolean success;

	g_return_val_if_fail (self, FALSE);
	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
	g_return_val_if_fail (slave, FALSE);
	g_return_val_if_fail (connection, FALSE);
	g_return_val_if_fail (!error || !*error, FALSE);
	g_return_val_if_fail (nm_connection_get_setting_connection (connection), FALSE);

	g_return_val_if_fail (nm_device_get_iface (self), FALSE);

	klass = NM_DEVICE_GET_CLASS (self);
	if (klass->master_update_slave_connection) {
		success = klass->master_update_slave_connection (self, slave, connection, error);

		g_return_val_if_fail (!error || (success && !*error) || *error, success);
		return success;
	}

	g_set_error (error,
	             NM_DEVICE_ERROR,
	             NM_DEVICE_ERROR_FAILED,
	             "master device '%s' cannot update a slave connection for slave device '%s' (master type not supported?)",
	             nm_device_get_iface (self), nm_device_get_iface (slave));
	return FALSE;
}

static gboolean
_get_maybe_ipv6_disabled (NMDevice *self)
{
	NMPlatform *platform;
	int ifindex;
	const char *path;
	char ifname[IFNAMSIZ];

	ifindex = nm_device_get_ip_ifindex (self);
	if (ifindex <= 0)
		return FALSE;

	platform = nm_device_get_platform (self);
	if (!nm_platform_if_indextoname (platform, ifindex, ifname))
		return FALSE;

	path = nm_sprintf_bufa (128, "/proc/sys/net/ipv6/conf/%s/disable_ipv6", ifname);
	return (nm_platform_sysctl_get_int32 (platform, NMP_SYSCTL_PATHID_ABSOLUTE (path), 0) == 0);
}

NMConnection *
nm_device_generate_connection (NMDevice *self,
                               NMDevice *master,
                               gboolean *out_maybe_later,
                               GError **error)
{
	NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const char *ifname = nm_device_get_iface (self);
	gs_unref_object NMConnection *connection = NULL;
	NMSetting *s_con;
	NMSetting *s_ip4;
	NMSetting *s_ip6;
	char uuid[37];
	const char *ip4_method, *ip6_method;
	GError *local = NULL;
	const NMPlatformLink *pllink;

	NM_SET_OUT (out_maybe_later, FALSE);

	/* If update_connection() is not implemented, just fail. */
	if (!klass->update_connection) {
		g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED,
		             "device class %s does not support generating a connection",
		             G_OBJECT_TYPE_NAME (self));
		return NULL;
	}

	/* Return NULL if device is unconfigured. */
	if (!device_has_config (self)) {
		g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED,
		             "device has no existing configuration");
		return NULL;
	}

	connection = nm_simple_connection_new ();
	s_con = nm_setting_connection_new ();

	g_object_set (s_con,
	              NM_SETTING_CONNECTION_UUID, nm_utils_uuid_generate_buf (uuid),
	              NM_SETTING_CONNECTION_ID, ifname,
	              NM_SETTING_CONNECTION_AUTOCONNECT, FALSE,
	              NM_SETTING_CONNECTION_INTERFACE_NAME, ifname,
	              NM_SETTING_CONNECTION_TIMESTAMP, (guint64) time (NULL),
	              NULL);

	if (klass->connection_type_supported)
		g_object_set (s_con, NM_SETTING_CONNECTION_TYPE, klass->connection_type_supported, NULL);

	nm_connection_add_setting (connection, s_con);

	/* If the device is a slave, update various slave settings */
	if (master) {
		if (!nm_device_master_update_slave_connection (master,
		                                               self,
		                                               connection,
		                                               &local)) {
			g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED,
			             "master device '%s' failed to update slave connection: %s",
			             nm_device_get_iface (master), local->message);
			g_error_free (local);
			return NULL;
		}
	} else {
		/* Only regular and master devices get IP configuration; slaves do not */
		s_ip4 = nm_ip4_config_create_setting (priv->ip_config_4);
		nm_connection_add_setting (connection, s_ip4);

		s_ip6 = nm_ip6_config_create_setting (priv->ip_config_6, _get_maybe_ipv6_disabled (self));
		nm_connection_add_setting (connection, s_ip6);

		nm_connection_add_setting (connection, nm_setting_proxy_new ());

		pllink = nm_platform_link_get (nm_device_get_platform (self), priv->ifindex);
		if (   pllink
		    && pllink->inet6_token.id) {
			char sbuf[NM_UTILS_INET_ADDRSTRLEN];

			g_object_set (s_ip6,
			              NM_SETTING_IP6_CONFIG_ADDR_GEN_MODE, NM_IN6_ADDR_GEN_MODE_EUI64,
			              NM_SETTING_IP6_CONFIG_TOKEN, nm_utils_inet6_interface_identifier_to_token (pllink->inet6_token, sbuf),
			              NULL);
		}
	}

	klass->update_connection (self, connection);

	if (!nm_connection_normalize (connection, NULL, NULL, &local)) {
		g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED,
		             "generated connection does not verify: %s",
		             local->message);
		g_error_free (local);
		return NULL;
	}

	/* Ignore the connection if it has no IP configuration,
	 * no slave configuration, and is not a master interface.
	 */
	ip4_method = nm_utils_get_ip_config_method (connection, AF_INET);
	ip6_method = nm_utils_get_ip_config_method (connection, AF_INET6);
	if (   nm_streq0 (ip4_method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED)
	    && NM_IN_STRSET (ip6_method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE,
	                                 NM_SETTING_IP6_CONFIG_METHOD_DISABLED)
	    && !nm_setting_connection_get_master (NM_SETTING_CONNECTION (s_con))
	    && c_list_is_empty (&priv->slaves)) {
		NM_SET_OUT (out_maybe_later, TRUE);
		g_set_error_literal (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED,
		                     "ignoring generated connection (no IP and not in master-slave relationship)");
		return NULL;
	}

	/* Ignore any IPv6LL-only, not master connections without slaves,
	 * unless they are in the assume-ipv6ll-only list.
	 */
	if (   nm_streq0 (ip4_method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED)
	    && nm_streq0 (ip6_method, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL)
	    && !nm_setting_connection_get_master (NM_SETTING_CONNECTION (s_con))
	    && c_list_is_empty (&priv->slaves)
	    && !nm_config_data_get_assume_ipv6ll_only (NM_CONFIG_GET_DATA, self)) {
		_LOGD (LOGD_DEVICE, "ignoring generated connection (IPv6LL-only and not in master-slave relationship)");
		NM_SET_OUT (out_maybe_later, TRUE);
		g_set_error_literal (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_FAILED,
		                    "ignoring generated connection (IPv6LL-only and not in master-slave relationship)");
		return NULL;
	}

	return g_steal_pointer (&connection);
}

/**
 * nm_device_complete_connection:
 *
 * Complete the connection. This is solely used for AddAndActivate where the user
 * may pass in an incomplete connection and a device, and the device tries to
 * make sense of it and complete it for activation. Otherwise, this is not
 * used.
 *
 * Returns: success or failure.
 */
gboolean
nm_device_complete_connection (NMDevice *self,
                               NMConnection *connection,
                               const char *specific_object,
                               NMConnection *const*existing_connections,
                               GError **error)
{
	NMDeviceClass *klass;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
	g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE);

	klass = NM_DEVICE_GET_CLASS (self);

	if (!klass->complete_connection) {
		g_set_error (error, NM_DEVICE_ERROR, NM_DEVICE_ERROR_INVALID_CONNECTION,
		             "Device class %s had no complete_connection method",
		             G_OBJECT_TYPE_NAME (self));
		return FALSE;
	}

	if (!klass->complete_connection (self,
	                                 connection,
	                                 specific_object,
	                                 existing_connections,
	                                 error))
		return FALSE;

	if (!nm_connection_normalize (connection, NULL, NULL, error))
		return FALSE;

	return nm_device_check_connection_compatible (self, connection, error);
}

gboolean
nm_device_match_parent (NMDevice *self, const char *parent)
{
	NMDevice *parent_device;

	g_return_val_if_fail (parent, FALSE);

	parent_device = nm_device_parent_get_device (self);
	if (!parent_device)
		return FALSE;

	if (nm_utils_is_uuid (parent)) {
		NMConnection *connection;

		/* If the parent is a UUID, the connection matches when there is
		 * no connection active on the device or when a connection with
		 * that UUID is active.
		 */
		connection = nm_device_get_applied_connection (parent_device);
		if (   connection
		    && !nm_streq0 (parent, nm_connection_get_uuid (connection)))
			return FALSE;
	} else {
		/* Interface name */
		if (!nm_streq0 (parent, nm_device_get_ip_iface (parent_device)))
			return FALSE;
	}

	return TRUE;
}

gboolean
nm_device_match_parent_hwaddr (NMDevice *device,
                               NMConnection *connection,
                               gboolean fail_if_no_hwaddr)
{
	NMSettingWired *s_wired;
	NMDevice *parent_device;
	const char *setting_mac;
	const char *parent_mac;

	s_wired = nm_connection_get_setting_wired (connection);
	if (!s_wired)
		return !fail_if_no_hwaddr;

	setting_mac = nm_setting_wired_get_mac_address (s_wired);
	if (!setting_mac)
		return !fail_if_no_hwaddr;

	parent_device = nm_device_parent_get_device (device);
	if (!parent_device)
		return !fail_if_no_hwaddr;

	parent_mac = nm_device_get_permanent_hw_address (parent_device);
	return parent_mac && nm_utils_hwaddr_matches (setting_mac, -1, parent_mac, -1);
}

static gboolean
check_connection_compatible (NMDevice *self, NMConnection *connection, GError **error)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const char *device_iface = nm_device_get_iface (self);
	gs_free_error GError *local = NULL;
	gs_free char *conn_iface = NULL;
	NMDeviceClass *klass;
	NMSettingMatch *s_match;

	klass = NM_DEVICE_GET_CLASS (self);
	if (klass->connection_type_check_compatible) {
		if (!_nm_connection_check_main_setting (connection,
		                                        klass->connection_type_check_compatible,
		                                        error))
			return FALSE;
	} else if (klass->check_connection_compatible == check_connection_compatible) {
		/* the device class does not implement check_connection_compatible nor set
		 * connection_type_check_compatible. That means, it is by default not compatible
		 * with any connection type. */
		nm_utils_error_set_literal (error,
		                            NM_UTILS_ERROR_CONNECTION_AVAILABLE_INCOMPATIBLE,
		                            "device does not support any connections");
		return FALSE;
	}

	conn_iface = nm_manager_get_connection_iface (NM_MANAGER_GET,
	                                              connection,
	                                              NULL,
	                                              NULL,
	                                              &local);

	/* We always need a interface name for virtual devices, but for
	 * physical ones a connection without interface name is fine for
	 * any device. */
	if (!conn_iface) {
		if (nm_connection_is_virtual (connection)) {
			nm_utils_error_set (error, NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
			                    "cannot get interface name due to %s", local->message);
			return FALSE;
		}
	} else if (!nm_streq0 (conn_iface, device_iface)) {
		nm_utils_error_set_literal (error, NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
		                            "mismatching interface name");
		return FALSE;
	}

	s_match = (NMSettingMatch *) nm_connection_get_setting (connection,
	                                                        NM_TYPE_SETTING_MATCH);
	if (s_match) {
		const char *const *patterns;
		const char *device_driver;
		guint num_patterns = 0;

		patterns = nm_setting_match_get_interface_names (s_match, &num_patterns);
		if (!nm_wildcard_match_check (device_iface, patterns, num_patterns)) {
			nm_utils_error_set_literal (error, NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
			                            "device does not satisfy match.interface-name property");
			return FALSE;
		}

		patterns = nm_setting_match_get_kernel_command_lines (s_match, &num_patterns);
		if (   num_patterns > 0
		    && !nm_utils_kernel_cmdline_match_check (nm_utils_proc_cmdline_split (),
		                                             patterns,
		                                             num_patterns,
		                                             error))
			return FALSE;

		device_driver = nm_device_get_driver (self);
		patterns = nm_setting_match_get_drivers (s_match, &num_patterns);
		if (!nm_wildcard_match_check (device_driver, patterns, num_patterns)) {
			nm_utils_error_set_literal (error, NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
			                            "device does not satisfy match.driver property");
			return FALSE;
		}

		patterns = nm_setting_match_get_paths (s_match, &num_patterns);
		if (!nm_wildcard_match_check (priv->path, patterns, num_patterns)) {
			nm_utils_error_set_literal (error, NM_UTILS_ERROR_CONNECTION_AVAILABLE_INCOMPATIBLE,
			                            "device does not satisfy match.path property");
			return FALSE;
		}
	}

	return TRUE;
}

/**
 * nm_device_check_connection_compatible:
 * @self: an #NMDevice
 * @connection: an #NMConnection
 * @error: optional reason why it is incompatible. Note that the
 *   error code is set to %NM_UTILS_ERROR_CONNECTION_AVAILABLE_INCOMPATIBLE,
 *   if the profile is fundamentally incompatible with the device
 *   (most commonly, because the device-type does not support the
 *   connection-type).
 *
 * Checks if @connection could potentially be activated on @self.
 * This means only that @self has the proper capabilities, and that
 * @connection is not locked to some other device. It does not
 * necessarily mean that @connection could be activated on @self
 * right now. (Eg, it might refer to a Wi-Fi network that is not
 * currently available.)
 *
 * Returns: #TRUE if @connection could potentially be activated on
 *   @self.
 */
gboolean
nm_device_check_connection_compatible (NMDevice *self, NMConnection *connection, GError **error)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
	g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE);

	return NM_DEVICE_GET_CLASS (self)->check_connection_compatible (self, connection, error);
}

gboolean
nm_device_check_slave_connection_compatible (NMDevice *self, NMConnection *slave)
{
	NMSettingConnection *s_con;
	const char *connection_type, *slave_type;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
	g_return_val_if_fail (NM_IS_CONNECTION (slave), FALSE);

	if (!nm_device_is_master (self))
		return FALSE;

	/* All masters should have connection type set */
	connection_type = NM_DEVICE_GET_CLASS (self)->connection_type_supported;
	g_return_val_if_fail (connection_type, FALSE);

	s_con = nm_connection_get_setting_connection (slave);
	g_assert (s_con);
	slave_type = nm_setting_connection_get_slave_type (s_con);
	if (!slave_type)
		return FALSE;

	return nm_streq (connection_type, slave_type);
}

/**
 * nm_device_can_assume_connections:
 * @self: #NMDevice instance
 *
 * This is a convenience function to determine whether connection assumption
 * is available for this device.
 *
 * Returns: %TRUE if the device is capable of assuming connections, %FALSE if not
 */
static gboolean
nm_device_can_assume_connections (NMDevice *self)
{
	return !!NM_DEVICE_GET_CLASS (self)->update_connection;
}

static gboolean
unmanaged_on_quit (NMDevice *self)
{
	NMConnection *connection;

	/* NMDeviceWifi overwrites this function to always unmanage wifi devices.
	 *
	 * For all other types, if the device type can assume connections, we leave
	 * it up on quit.
	 *
	 * Originally, we would only keep devices up that can be assumed afterwards.
	 * However, that meant we unmanged layer-2 only devices. So, this was step
	 * by step refined to unmanage less (commit 25aaaab3, rh#1311988, rh#1333983).
	 * But there are more scenarios where we also want to keep the device up
	 * (rh#1378418, rh#1371126). */
	if (!nm_device_can_assume_connections (self))
		return TRUE;

	/* the only exception are IPv4 shared connections. We unmanage them on quit. */
	connection = nm_device_get_applied_connection (self);
	if (connection) {
		if (NM_IN_STRSET (nm_utils_get_ip_config_method (connection, AF_INET),
		                  NM_SETTING_IP4_CONFIG_METHOD_SHARED)) {
			/* shared connections are to be unmangaed. */
			return TRUE;
		}
	}

	return FALSE;
}

gboolean
nm_device_unmanage_on_quit (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	return NM_DEVICE_GET_CLASS (self)->unmanaged_on_quit (self);
}

static gboolean
nm_device_emit_recheck_assume (gpointer user_data)
{
	NMDevice *self = user_data;
	NMDevicePrivate *priv;

	g_return_val_if_fail (NM_IS_DEVICE (self), G_SOURCE_REMOVE);

	priv = NM_DEVICE_GET_PRIVATE (self);

	priv->recheck_assume_id = 0;
	if (!nm_device_get_act_request (self))
		g_signal_emit (self, signals[RECHECK_ASSUME], 0);

	return G_SOURCE_REMOVE;
}

void
nm_device_queue_recheck_assume (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (   !priv->recheck_assume_id
	    && nm_device_can_assume_connections (self))
		priv->recheck_assume_id = g_idle_add (nm_device_emit_recheck_assume, self);
}

static gboolean
recheck_available (gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gboolean now_available;
	NMDeviceState state = nm_device_get_state (self);
	NMDeviceState new_state = NM_DEVICE_STATE_UNKNOWN;

	priv->recheck_available.call_id = 0;

	now_available = nm_device_is_available (self, NM_DEVICE_CHECK_DEV_AVAILABLE_NONE);

	if (state == NM_DEVICE_STATE_UNAVAILABLE && now_available) {
		new_state = NM_DEVICE_STATE_DISCONNECTED;
		nm_device_queue_state (self, new_state, priv->recheck_available.available_reason);
	} else if (state >= NM_DEVICE_STATE_DISCONNECTED && !now_available) {
		new_state = NM_DEVICE_STATE_UNAVAILABLE;
		nm_device_queue_state (self, new_state, priv->recheck_available.unavailable_reason);
	}

	if (new_state > NM_DEVICE_STATE_UNKNOWN) {
		_LOGD (LOGD_DEVICE, "is %savailable, %s %s",
		       now_available ? "" : "not ",
		       new_state == NM_DEVICE_STATE_UNAVAILABLE ? "no change required for" : "will transition to",
		       nm_device_state_to_str (new_state == NM_DEVICE_STATE_UNAVAILABLE ? state : new_state));

		priv->recheck_available.available_reason = NM_DEVICE_STATE_REASON_NONE;
		priv->recheck_available.unavailable_reason = NM_DEVICE_STATE_REASON_NONE;
	}

	if (priv->recheck_available.call_id == 0)
		nm_device_remove_pending_action (self, NM_PENDING_ACTION_RECHECK_AVAILABLE, TRUE);

	return G_SOURCE_REMOVE;
}

void
nm_device_queue_recheck_available (NMDevice *self,
                                   NMDeviceStateReason available_reason,
                                   NMDeviceStateReason unavailable_reason)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	priv->recheck_available.available_reason = available_reason;
	priv->recheck_available.unavailable_reason = unavailable_reason;
	if (!priv->recheck_available.call_id) {
		priv->recheck_available.call_id = g_idle_add (recheck_available, self);
		nm_device_add_pending_action (self, NM_PENDING_ACTION_RECHECK_AVAILABLE,
		                              FALSE /* cannot assert, because of how recheck_available() first clears
		                                       the call-id and postpones removing the pending-action. */);
	}
}

void
nm_device_emit_recheck_auto_activate (NMDevice *self)
{
	g_signal_emit (self, signals[RECHECK_AUTO_ACTIVATE], 0);
}

static void
dnsmasq_state_changed_cb (NMDnsMasqManager *manager, guint32 status, gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);

	switch (status) {
	case NM_DNSMASQ_STATUS_DEAD:
		nm_device_ip_method_failed (self, AF_INET, NM_DEVICE_STATE_REASON_SHARED_START_FAILED);
		break;
	default:
		break;
	}
}

void
nm_device_auth_request (NMDevice *self,
                        GDBusMethodInvocation *context,
                        NMConnection *connection,
                        const char *permission,
                        gboolean allow_interaction,
                        GCancellable *cancellable,
                        NMManagerDeviceAuthRequestFunc callback,
                        gpointer user_data)
{
	nm_manager_device_auth_request (nm_device_get_manager (self),
	                                self,
	                                context,
	                                connection,
	                                permission,
	                                allow_interaction,
	                                cancellable,
	                                callback,
	                                user_data);
}

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

static void
activation_source_clear (NMDevice *self,
                         int addr_family)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	if (priv->activation_source_id_x[IS_IPv4] != 0) {
		_LOGD (LOGD_DEVICE, "activation-stage: clear %s,v%c (id %u)",
		       _activation_func_to_string (priv->activation_source_func_x[IS_IPv4]),
		       nm_utils_addr_family_to_char (addr_family),
		       priv->activation_source_id_x[IS_IPv4]);
		nm_clear_g_source (&priv->activation_source_id_x[IS_IPv4]);
		priv->activation_source_func_x[IS_IPv4] = NULL;
	}
}

static gboolean
activation_source_handle_cb (NMDevice *self,
                             int addr_family)
{
	NMDevicePrivate *priv;
	const gboolean IS_IPv4 = (addr_family == AF_INET);
	ActivationHandleFunc activation_source_func;
	guint activation_source_id;

	g_return_val_if_fail (NM_IS_DEVICE (self), G_SOURCE_REMOVE);

	priv = NM_DEVICE_GET_PRIVATE (self);

	activation_source_func = priv->activation_source_func_x[IS_IPv4];
	activation_source_id = priv->activation_source_id_x[IS_IPv4];

	g_return_val_if_fail (activation_source_id != 0, G_SOURCE_REMOVE);
	nm_assert (activation_source_func);

	priv->activation_source_func_x[IS_IPv4] = NULL;
	priv->activation_source_id_x[IS_IPv4] = 0;

	_LOGD (LOGD_DEVICE, "activation-stage: invoke %s,v%c (id %u)",
	       _activation_func_to_string (activation_source_func),
	       nm_utils_addr_family_to_char (addr_family),
	       activation_source_id);

	activation_source_func (self);

	_LOGT (LOGD_DEVICE, "activation-stage: complete %s,v%c (id %u)",
	       _activation_func_to_string (activation_source_func),
	       nm_utils_addr_family_to_char (addr_family),
	       activation_source_id);

	return G_SOURCE_REMOVE;
}

static gboolean
activation_source_handle_cb_4 (gpointer user_data)
{
	return activation_source_handle_cb (user_data, AF_INET);
}

static gboolean
activation_source_handle_cb_6 (gpointer user_data)
{
	return activation_source_handle_cb (user_data, AF_INET6);
}

static void
activation_source_schedule (NMDevice *self, ActivationHandleFunc func, int addr_family)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const gboolean IS_IPv4 = (addr_family == AF_INET);
	guint new_id = 0;

	if (   priv->activation_source_id_x[IS_IPv4] != 0
	    && priv->activation_source_func_x[IS_IPv4] == func) {
		/* Scheduling the same stage multiple times is fine. */
		_LOGT (LOGD_DEVICE, "activation-stage: already scheduled %s,v%c (id %u)",
		       _activation_func_to_string (func),
		       nm_utils_addr_family_to_char (addr_family),
		       priv->activation_source_id_x[IS_IPv4]);
		return;
	}

	new_id = g_idle_add (  IS_IPv4
	                     ? activation_source_handle_cb_4
	                     : activation_source_handle_cb_6,
	                     self);

	if (priv->activation_source_id_x[IS_IPv4] != 0) {
		_LOGD (LOGD_DEVICE, "activation-stage: schedule %s,v%c which replaces %s,v%c (id %u -> %u)",
		       _activation_func_to_string (func),
		       nm_utils_addr_family_to_char (addr_family),
		       _activation_func_to_string (priv->activation_source_func_x[IS_IPv4]),
		       nm_utils_addr_family_to_char (addr_family),
		       priv->activation_source_id_x[IS_IPv4], new_id);
		nm_clear_g_source (&priv->activation_source_id_x[IS_IPv4]);
	} else {
		_LOGD (LOGD_DEVICE, "activation-stage: schedule %s,v%c (id %u)",
		       _activation_func_to_string (func),
		       nm_utils_addr_family_to_char (addr_family),
		       new_id);
	}

	priv->activation_source_func_x[IS_IPv4] = func;
	priv->activation_source_id_x[IS_IPv4] = new_id;
}

static void
activation_source_invoke_sync (NMDevice *self, ActivationHandleFunc func, int addr_family)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	if (priv->activation_source_id_x[IS_IPv4] == 0) {
		_LOGD (LOGD_DEVICE, "activation-stage: synchronously invoke %s,v%c",
		       _activation_func_to_string (func),
		       nm_utils_addr_family_to_char (addr_family));
	} else if (priv->activation_source_func_x[IS_IPv4] == func) {
		_LOGD (LOGD_DEVICE, "activation-stage: synchronously invoke %s,v%c which was already scheduled (id %u)",
		       _activation_func_to_string (func),
		       nm_utils_addr_family_to_char (addr_family),
		       priv->activation_source_id_x[IS_IPv4]);
	} else {
		_LOGD (LOGD_DEVICE, "activation-stage: synchronously invoke %s,v%c which replaces %s,v%c (id %u)",
		       _activation_func_to_string (func),
		       nm_utils_addr_family_to_char (addr_family),
		       _activation_func_to_string (priv->activation_source_func_x[IS_IPv4]),
		       nm_utils_addr_family_to_char (addr_family),
		       priv->activation_source_id_x[IS_IPv4]);
	}

	nm_clear_g_source (&priv->activation_source_id_x[IS_IPv4]);
	priv->activation_source_func_x[IS_IPv4] = NULL;

	func (self);
}

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

static void
master_ready (NMDevice *self,
              NMActiveConnection *active)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMActiveConnection *master_connection;
	NMDevice *master;

	/* Notify a master device that it has a new slave */
	nm_assert (nm_active_connection_get_master_ready (active));

	master_connection = nm_active_connection_get_master (active);

	master = nm_active_connection_get_device (master_connection);

	_LOGD (LOGD_DEVICE, "master connection ready; master device %s",
	       nm_device_get_iface (master));

	if (   priv->master
	    && priv->master != master)
		nm_device_master_release_one_slave (priv->master, self, FALSE, FALSE, NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);

	/* If the master didn't change, add-slave only rechecks whether to assume a connection. */
	nm_device_master_add_slave (master,
	                            self,
	                            !nm_device_sys_iface_state_is_external_or_assume (self));
}

static void
master_ready_cb (NMActiveConnection *active,
                 GParamSpec *pspec,
                 NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	nm_assert (nm_active_connection_get_master_ready (active));

	if (priv->state == NM_DEVICE_STATE_PREPARE)
		nm_device_activate_schedule_stage1_device_prepare (self, FALSE);
}

static void
lldp_neighbors_changed (NMLldpListener *lldp_listener, GParamSpec *pspec,
                        gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);

	_notify (self, PROP_LLDP_NEIGHBORS);
}

static gboolean
lldp_rx_enabled (NMDevice *self)
{
	NMConnection *connection;
	NMSettingConnection *s_con;
	NMSettingConnectionLldp lldp = NM_SETTING_CONNECTION_LLDP_DEFAULT;

	connection = nm_device_get_applied_connection (self);
	g_return_val_if_fail (connection, FALSE);

	s_con = nm_connection_get_setting_connection (connection);
	g_return_val_if_fail (s_con, FALSE);

	lldp = nm_setting_connection_get_lldp (s_con);
	if (lldp == NM_SETTING_CONNECTION_LLDP_DEFAULT) {
		lldp = nm_config_data_get_connection_default_int64 (NM_CONFIG_GET_DATA,
		                                                    NM_CON_DEFAULT ("connection.lldp"),
		                                                    self,
		                                                    NM_SETTING_CONNECTION_LLDP_DEFAULT,
		                                                    NM_SETTING_CONNECTION_LLDP_ENABLE_RX,
		                                                    NM_SETTING_CONNECTION_LLDP_DEFAULT);
		if (lldp == NM_SETTING_CONNECTION_LLDP_DEFAULT)
			lldp = NM_SETTING_CONNECTION_LLDP_DISABLE;
	}
	return lldp == NM_SETTING_CONNECTION_LLDP_ENABLE_RX;
}

static NMPlatformVF *
sriov_vf_config_to_platform (NMDevice *self,
                             NMSriovVF *vf,
                             GError **error)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gs_free NMPlatformVF *plat_vf = NULL;
	const guint *vlan_ids;
	GVariant *variant;
	guint i, num_vlans;
	gsize length;

	g_return_val_if_fail (!error || !*error, FALSE);

	vlan_ids = nm_sriov_vf_get_vlan_ids (vf, &num_vlans);
	plat_vf = g_malloc0 (  sizeof (NMPlatformVF)
	                     + sizeof (NMPlatformVFVlan) * num_vlans);

	plat_vf->index = nm_sriov_vf_get_index (vf);

	variant = nm_sriov_vf_get_attribute (vf, NM_SRIOV_VF_ATTRIBUTE_SPOOF_CHECK);
	if (variant)
		plat_vf->spoofchk = g_variant_get_boolean (variant);
	else
		plat_vf->spoofchk = -1;

	variant = nm_sriov_vf_get_attribute (vf, NM_SRIOV_VF_ATTRIBUTE_TRUST);
	if (variant)
		plat_vf->trust = g_variant_get_boolean (variant);
	else
		plat_vf->trust = -1;

	variant = nm_sriov_vf_get_attribute (vf, NM_SRIOV_VF_ATTRIBUTE_MAC);
	if (variant) {
		if (!_nm_utils_hwaddr_aton (g_variant_get_string (variant, NULL),
		                            plat_vf->mac.data,
		                            sizeof (plat_vf->mac.data),
		                            &length)) {
			g_set_error (error,
			             NM_DEVICE_ERROR,
			             NM_DEVICE_ERROR_FAILED,
			             "invalid MAC %s",
			             g_variant_get_string (variant, NULL));
			return NULL;
		}
		if (length != priv->hw_addr_len) {
			g_set_error (error,
			             NM_DEVICE_ERROR,
			             NM_DEVICE_ERROR_FAILED,
			             "wrong MAC length %" G_GSIZE_FORMAT ", should be %u",
			             length, priv->hw_addr_len);
			return NULL;
		}
		plat_vf->mac.len = length;
	}

	variant = nm_sriov_vf_get_attribute (vf, NM_SRIOV_VF_ATTRIBUTE_MIN_TX_RATE);
	if (variant)
		plat_vf->min_tx_rate = g_variant_get_uint32 (variant);

	variant = nm_sriov_vf_get_attribute (vf, NM_SRIOV_VF_ATTRIBUTE_MAX_TX_RATE);
	if (variant)
		plat_vf->max_tx_rate = g_variant_get_uint32 (variant);

	plat_vf->num_vlans = num_vlans;
	plat_vf->vlans = (NMPlatformVFVlan *) (&plat_vf[1]);
	for (i = 0; i < num_vlans; i++) {
		plat_vf->vlans[i].id = vlan_ids[i];
		plat_vf->vlans[i].qos = nm_sriov_vf_get_vlan_qos (vf, vlan_ids[i]);
		plat_vf->vlans[i].proto_ad = nm_sriov_vf_get_vlan_protocol (vf, vlan_ids[i]) == NM_SRIOV_VF_VLAN_PROTOCOL_802_1AD;
	}

	return g_steal_pointer (&plat_vf);
}

static void
sriov_params_cb (GError *error, gpointer data)
{
	NMDevice *self;
	NMDevicePrivate *priv;
	nm_auto_freev NMPlatformVF **plat_vfs = NULL;

	nm_utils_user_data_unpack (data, &self, &plat_vfs);

	if (nm_utils_error_is_cancelled_or_disposing (error))
		return;

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (error) {
		_LOGE (LOGD_DEVICE, "failed to set SR-IOV parameters: %s", error->message);
		nm_device_state_changed (self,
		                         NM_DEVICE_STATE_FAILED,
		                         NM_DEVICE_STATE_REASON_SRIOV_CONFIGURATION_FAILED);
		return;
	}

	if (!nm_platform_link_set_sriov_vfs (nm_device_get_platform (self),
	                                     priv->ifindex,
	                                     (const NMPlatformVF *const *) plat_vfs)) {
		_LOGE (LOGD_DEVICE, "failed to apply SR-IOV VFs");
		nm_device_state_changed (self,
		                         NM_DEVICE_STATE_FAILED,
		                         NM_DEVICE_STATE_REASON_SRIOV_CONFIGURATION_FAILED);
		return;
	}

	priv->stage1_sriov_state = NM_DEVICE_STAGE_STATE_COMPLETED;

	nm_device_activate_schedule_stage1_device_prepare (self, FALSE);
}

/*
 * activate_stage1_device_prepare
 *
 * Prepare for device activation
 *
 */
static void
activate_stage1_device_prepare (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMActStageReturn ret = NM_ACT_STAGE_RETURN_SUCCESS;
	NMActiveConnection *active;
	NMActiveConnection *master;
	NMDeviceClass *klass;

	priv->v4_route_table_initialized = FALSE;
	priv->v6_route_table_initialized = FALSE;
	priv->l3config_merge_flags_has = FALSE;

	_set_ip_state (self, AF_INET, NM_DEVICE_IP_STATE_NONE);
	_set_ip_state (self, AF_INET6, NM_DEVICE_IP_STATE_NONE);

	/* Notify the new ActiveConnection along with the state change */
	nm_dbus_track_obj_path_set (&priv->act_request,
	                            priv->act_request.obj,
	                            TRUE);

	nm_device_state_changed (self, NM_DEVICE_STATE_PREPARE, NM_DEVICE_STATE_REASON_NONE);

	if (priv->stage1_sriov_state != NM_DEVICE_STAGE_STATE_COMPLETED) {
		NMSettingSriov *s_sriov;

		if (nm_device_sys_iface_state_is_external_or_assume (self)) {
			/* pass */
		} else if (priv->stage1_sriov_state == NM_DEVICE_STAGE_STATE_PENDING)
			return;
		else if (   priv->ifindex > 0
		         && nm_device_has_capability (self, NM_DEVICE_CAP_SRIOV)
		         && (s_sriov = nm_device_get_applied_setting (self, NM_TYPE_SETTING_SRIOV))) {
			nm_auto_freev NMPlatformVF **plat_vfs = NULL;
			gs_free_error GError *error = NULL;
			NMSriovVF *vf;
			NMTernary autoprobe;
			guint i, num;

			autoprobe = nm_setting_sriov_get_autoprobe_drivers (s_sriov);
			if (autoprobe == NM_TERNARY_DEFAULT) {
				autoprobe = nm_config_data_get_connection_default_int64 (NM_CONFIG_GET_DATA,
				                                                         NM_CON_DEFAULT ("sriov.autoprobe-drivers"),
				                                                         self,
				                                                         NM_TERNARY_FALSE,
				                                                         NM_TERNARY_TRUE,
				                                                         NM_TERNARY_TRUE);
			}

			num = nm_setting_sriov_get_num_vfs (s_sriov);
			plat_vfs = g_new0 (NMPlatformVF *, num + 1);
			for (i = 0; i < num; i++) {
				vf = nm_setting_sriov_get_vf (s_sriov, i);
				plat_vfs[i] = sriov_vf_config_to_platform (self, vf, &error);
				if (!plat_vfs[i]) {
					_LOGE (LOGD_DEVICE,
					       "failed to apply SR-IOV VF '%s': %s",
					       nm_utils_sriov_vf_to_str (vf, FALSE, NULL),
					       error->message);
					nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_SRIOV_CONFIGURATION_FAILED);
					return;
				}
			}

			/* When changing the number of VFs the kernel can block
			 * for very long time in the write to sysfs, especially
			 * if autoprobe-drivers is enabled. Do it asynchronously
			 * to avoid blocking the entire NM process.
			 */
			sriov_op_queue (self,
			                nm_setting_sriov_get_total_vfs (s_sriov),
			                autoprobe,
			                sriov_params_cb,
			                nm_utils_user_data_pack (self,
			                                         g_steal_pointer (&plat_vfs)));
			priv->stage1_sriov_state = NM_DEVICE_STAGE_STATE_PENDING;
			return;
		}
		priv->stage1_sriov_state = NM_DEVICE_STAGE_STATE_COMPLETED;
	}

	/* Assumed connections were already set up outside NetworkManager */
	klass = NM_DEVICE_GET_CLASS (self);

	if (   klass->act_stage1_prepare_set_hwaddr_ethernet
	    && !nm_device_sys_iface_state_is_external_or_assume (self)) {
		if (!nm_device_hw_addr_set_cloned (self,
		                                   nm_device_get_applied_connection (self),
		                                   FALSE)) {
			nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_CONFIG_FAILED);
			return;
		}
	}

	if (   klass->act_stage1_prepare_also_for_external_or_assume
	    || !nm_device_sys_iface_state_is_external_or_assume (self)) {
		nm_assert (!klass->act_stage1_prepare_also_for_external_or_assume || klass->act_stage1_prepare);
		if (klass->act_stage1_prepare) {
			NMDeviceStateReason failure_reason = NM_DEVICE_STATE_REASON_NONE;

			ret = klass->act_stage1_prepare (self, &failure_reason);
			if (ret == NM_ACT_STAGE_RETURN_FAILURE) {
				nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, failure_reason);
				return;
			}
			if (ret == NM_ACT_STAGE_RETURN_POSTPONE)
				return;

			nm_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS);
		}
	}

	active = NM_ACTIVE_CONNECTION (priv->act_request.obj);
	master = nm_active_connection_get_master (active);
	if (master) {
		if (nm_active_connection_get_state (master) >= NM_ACTIVE_CONNECTION_STATE_DEACTIVATING) {
			_LOGD (LOGD_DEVICE, "master connection is deactivating");
			nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_DEPENDENCY_FAILED);
			return;
		}
		/* If the master connection is ready for slaves, attach ourselves */
		if (!nm_active_connection_get_master_ready (active)) {
			if (priv->master_ready_id == 0) {
				_LOGD (LOGD_DEVICE, "waiting for master connection to become ready");
				priv->master_ready_id = g_signal_connect (active,
				                                          "notify::" NM_ACTIVE_CONNECTION_INT_MASTER_READY,
				                                          (GCallback) master_ready_cb,
				                                          self);
			}
			return;
		}
	}
	nm_clear_g_signal_handler (priv->act_request.obj, &priv->master_ready_id);
	if (master)
		master_ready (self, active);
	else if (priv->master) {
		nm_device_master_release_one_slave (priv->master,
		                                    self,
		                                    TRUE,
		                                    TRUE,
		                                    NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);
	}

	nm_device_activate_schedule_stage2_device_config (self, TRUE);
}

void
nm_device_activate_schedule_stage1_device_prepare (NMDevice *self,
                                                   gboolean do_sync)
{
	g_return_if_fail (NM_IS_DEVICE (self));
	g_return_if_fail (NM_DEVICE_GET_PRIVATE (self)->act_request.obj);

	if (!do_sync) {
		activation_source_schedule (self, activate_stage1_device_prepare, AF_INET);
		return;
	}

	activation_source_invoke_sync (self, activate_stage1_device_prepare, AF_INET);
}

static NMActStageReturn
act_stage2_config (NMDevice *self, NMDeviceStateReason *out_failure_reason)
{
	return NM_ACT_STAGE_RETURN_SUCCESS;
}

static void
lldp_init (NMDevice *self, gboolean restart)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->ifindex > 0 && lldp_rx_enabled (self)) {
		gs_free_error GError *error = NULL;

		if (priv->lldp_listener) {
			if (   restart
			    && nm_lldp_listener_is_running (priv->lldp_listener))
				nm_lldp_listener_stop (priv->lldp_listener);
		} else {
			priv->lldp_listener = nm_lldp_listener_new ();
			g_signal_connect (priv->lldp_listener,
			                  "notify::" NM_LLDP_LISTENER_NEIGHBORS,
			                  G_CALLBACK (lldp_neighbors_changed),
			                  self);
		}

		if (!nm_lldp_listener_is_running (priv->lldp_listener)) {
			if (nm_lldp_listener_start (priv->lldp_listener, nm_device_get_ifindex (self), &error))
				_LOGD (LOGD_DEVICE, "LLDP listener %p started", priv->lldp_listener);
			else {
				_LOGD (LOGD_DEVICE, "LLDP listener %p could not be started: %s",
				       priv->lldp_listener, error->message);
			}
		}
	} else {
		if (priv->lldp_listener)
			nm_lldp_listener_stop (priv->lldp_listener);
	}
}

/* set-mode can be:
 *  - TRUE: sync with new rules.
 *  - FALSE: sync, but remove all rules (== flush)
 *  - DEFAULT: forget about all the rules that we previously tracked,
 *       but don't actually remove them. This is when quitting NM
 *       we want to keep the rules.
 *       The problem is, after restart of NM, the rule manager will
 *       no longer remember that NM added these rules and treat them
 *       as externally added ones. Don't restart NetworkManager if
 *       you care about that.
 */
static void
_routing_rules_sync (NMDevice *self,
                     NMTernary set_mode)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMPRulesManager *rules_manager = nm_netns_get_rules_manager (nm_device_get_netns (self));
	NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self);
	gboolean untrack_only_dirty = FALSE;
	gboolean keep_deleted_rules;
	gpointer user_tag_1;
	gpointer user_tag_2;

	/* take two arbitrary user-tag pointers that belong to @self. */
	user_tag_1 = &priv->v4_route_table;
	user_tag_2 = &priv->v6_route_table;

	if (set_mode == NM_TERNARY_TRUE) {
		NMConnection *applied_connection;
		NMSettingIPConfig *s_ip;
		guint i, num;
		int is_ipv4;

		untrack_only_dirty = TRUE;
		nmp_rules_manager_set_dirty (rules_manager, user_tag_1);
		if (klass->get_extra_rules)
			nmp_rules_manager_set_dirty (rules_manager, user_tag_2);

		applied_connection = nm_device_get_applied_connection (self);

		for (is_ipv4 = 0; applied_connection && is_ipv4 < 2; is_ipv4++) {
			int addr_family = is_ipv4 ? AF_INET : AF_INET6;

			s_ip = nm_connection_get_setting_ip_config (applied_connection, addr_family);
			if (!s_ip)
				continue;

			num = nm_setting_ip_config_get_num_routing_rules (s_ip);
			for (i = 0; i < num; i++) {
				NMPlatformRoutingRule plrule;
				NMIPRoutingRule *rule;

				rule = nm_setting_ip_config_get_routing_rule (s_ip, i);
				nm_ip_routing_rule_to_platform (rule, &plrule);

				/* We track this rule, but we also make it explicitly not weakly-tracked
				 * (meaning to untrack NMP_RULES_MANAGER_EXTERN_WEAKLY_TRACKED_USER_TAG at
				 * the same time). */
				nmp_rules_manager_track (rules_manager,
				                         &plrule,
				                         10,
				                         user_tag_1,
				                         NMP_RULES_MANAGER_EXTERN_WEAKLY_TRACKED_USER_TAG);
			}
		}

		if (klass->get_extra_rules) {
			gs_unref_ptrarray GPtrArray *extra_rules = NULL;

			extra_rules = klass->get_extra_rules (self);
			if (extra_rules) {
				for (i = 0; i < extra_rules->len; i++) {
					nmp_rules_manager_track (rules_manager,
					                         NMP_OBJECT_CAST_ROUTING_RULE (extra_rules->pdata[i]),
					                         10,
					                         user_tag_2,
					                         NMP_RULES_MANAGER_EXTERN_WEAKLY_TRACKED_USER_TAG);
				}
			}
		}
	}

	nmp_rules_manager_untrack_all (rules_manager, user_tag_1, !untrack_only_dirty);
	if (klass->get_extra_rules)
		nmp_rules_manager_untrack_all (rules_manager, user_tag_2, !untrack_only_dirty);

	keep_deleted_rules = FALSE;
	if (set_mode == NM_TERNARY_DEFAULT) {
		/* when exiting NM, we leave the device up and the rules configured.
		 * We just all nmp_rules_manager_sync() to forget about the synced rules,
		 * but we don't actually delete them.
		 *
		 * FIXME: that is a problem after restart of NetworkManager, because these
		 * rules will look like externally added, and NM will no longer remove
		 * them.
		 * To fix that, we could during "assume" mark the rules of the profile
		 * as owned (and "added" by the device). The problem with that is that it
		 * wouldn't cover rules that devices add by internal decision (not because
		 * of a setting in the profile, e.g. WireGuard could setup policy routing).
		 * Maybe it would be better to remember these orphaned rules at exit in a
		 * file and track them after restart again. */
		keep_deleted_rules = TRUE;
	}
	nmp_rules_manager_sync (rules_manager, keep_deleted_rules);
}

static gboolean
tc_commit (NMDevice *self)
{
	NMConnection *connection = NULL;
	gs_unref_ptrarray GPtrArray *qdiscs = NULL;
	gs_unref_ptrarray GPtrArray *tfilters = NULL;
	NMSettingTCConfig *s_tc = NULL;
	NMPlatform *platform;
	int ip_ifindex;

	platform = nm_device_get_platform (self);
	connection = nm_device_get_applied_connection (self);
	if (connection)
		s_tc = nm_connection_get_setting_tc_config (connection);

	ip_ifindex = nm_device_get_ip_ifindex (self);
	if (!ip_ifindex)
		return s_tc == NULL;

	if (s_tc) {
		qdiscs = nm_utils_qdiscs_from_tc_setting (platform, s_tc, ip_ifindex);
		tfilters = nm_utils_tfilters_from_tc_setting (platform, s_tc, ip_ifindex);
	}

	if (!nm_platform_qdisc_sync (platform, ip_ifindex, qdiscs))
		return FALSE;

	if (!nm_platform_tfilter_sync (platform, ip_ifindex, tfilters))
		return FALSE;

	return TRUE;
}

/*
 * activate_stage2_device_config
 *
 * Determine device parameters and set those on the device, ie
 * for wireless devices, set SSID, keys, etc.
 *
 */
static void
activate_stage2_device_config (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMDeviceClass *klass;
	NMActStageReturn ret;
	gboolean no_firmware = FALSE;
	CList *iter;

	nm_device_state_changed (self, NM_DEVICE_STATE_CONFIG, NM_DEVICE_STATE_REASON_NONE);

	if (!nm_device_sys_iface_state_is_external_or_assume (self))
		_ethtool_state_set (self);

	if (!nm_device_sys_iface_state_is_external_or_assume (self)) {
		if (!tc_commit (self)) {
			_LOGW (LOGD_IP6, "failed applying traffic control rules");
			nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, NM_DEVICE_STATE_REASON_CONFIG_FAILED);
			return;
		}
	}

	_routing_rules_sync (self, NM_TERNARY_TRUE);

	if (!nm_device_sys_iface_state_is_external_or_assume (self)) {
		if (!nm_device_bring_up (self, FALSE, &no_firmware)) {
			nm_device_state_changed (self,
			                         NM_DEVICE_STATE_FAILED,
			                           no_firmware
			                         ? NM_DEVICE_STATE_REASON_FIRMWARE_MISSING
			                         : NM_DEVICE_STATE_REASON_CONFIG_FAILED);
			return;
		}
	}

	klass = NM_DEVICE_GET_CLASS (self);
	if (   klass->act_stage2_config_also_for_external_or_assume
	    || !nm_device_sys_iface_state_is_external_or_assume (self)) {
		NMDeviceStateReason failure_reason = NM_DEVICE_STATE_REASON_NONE;

		ret = klass->act_stage2_config (self, &failure_reason);
		if (ret == NM_ACT_STAGE_RETURN_POSTPONE)
			return;
		if (ret != NM_ACT_STAGE_RETURN_SUCCESS) {
			nm_assert (ret == NM_ACT_STAGE_RETURN_FAILURE);
			nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, failure_reason);
			return;
		}
	}

	/* If we have slaves that aren't yet enslaved, do that now */
	c_list_for_each (iter, &priv->slaves) {
		SlaveInfo *info = c_list_entry (iter, SlaveInfo, lst_slave);
		NMDeviceState slave_state = nm_device_get_state (info->slave);

		if (slave_state == NM_DEVICE_STATE_IP_CONFIG)
			nm_device_master_enslave_slave (self, info->slave, nm_device_get_applied_connection (info->slave));
		else if (   priv->act_request.obj
		         && nm_device_sys_iface_state_is_external (self)
		         && slave_state <= NM_DEVICE_STATE_DISCONNECTED)
			nm_device_queue_recheck_assume (info->slave);
	}

	lldp_init (self, TRUE);

	nm_device_activate_schedule_stage3_ip_config_start (self);
}

void
nm_device_activate_schedule_stage2_device_config (NMDevice *self,
                                                  gboolean do_sync)
{
	g_return_if_fail (NM_IS_DEVICE (self));

	if (!do_sync) {
		activation_source_schedule (self, activate_stage2_device_config, AF_INET);
		return;
	}

	activation_source_invoke_sync (self, activate_stage2_device_config, AF_INET);
}

void
nm_device_ip_method_failed (NMDevice *self,
                            int addr_family,
                            NMDeviceStateReason reason)
{
	g_return_if_fail (NM_IS_DEVICE (self));
	g_return_if_fail (NM_IN_SET (addr_family, AF_INET, AF_INET6));

	_set_ip_state (self, addr_family, NM_DEVICE_IP_STATE_FAIL);

	if (get_ip_config_may_fail (self, addr_family))
		check_ip_state (self, FALSE, (nm_device_get_state (self) == NM_DEVICE_STATE_IP_CONFIG));
	else
		nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, reason);
}

/*****************************************************************************/
/* IPv4 DAD stuff */

static guint
get_ipv4_dad_timeout (NMDevice *self)
{
	NMConnection *connection;
	NMSettingIPConfig *s_ip4 = NULL;
	int timeout = -1;

	connection = nm_device_get_applied_connection (self);
	if (connection)
		s_ip4 = nm_connection_get_setting_ip4_config (connection);
	if (s_ip4)
		timeout = nm_setting_ip_config_get_dad_timeout (s_ip4);
	if (timeout >= 0)
		return timeout;

	return nm_config_data_get_connection_default_int64 (NM_CONFIG_GET_DATA,
	                                                    NM_CON_DEFAULT ("ipv4.dad-timeout"),
	                                                    self,
	                                                    0,
	                                                    NM_SETTING_IP_CONFIG_DAD_TIMEOUT_MAX,
	                                                    0);
}

static void
acd_data_destroy (gpointer ptr)
{
	AcdData *data = ptr;
	int i;

	for (i = 0; data->configs && data->configs[i]; i++)
		g_object_unref (data->configs[i]);
	g_free (data->configs);
	g_slice_free (AcdData, data);
}

static void
ipv4_manual_method_apply (NMDevice *self, NMIP4Config **configs, gboolean success)
{
	NMConnection *connection;
	const char *method;

	connection = nm_device_get_applied_connection (self);
	nm_assert (connection);
	method = nm_utils_get_ip_config_method (connection, AF_INET);
	nm_assert (NM_IN_STRSET (method,
	                         NM_SETTING_IP4_CONFIG_METHOD_MANUAL,
	                         NM_SETTING_IP4_CONFIG_METHOD_AUTO));

	if (!success) {
		nm_device_ip_method_failed (self, AF_INET,
		                            NM_DEVICE_STATE_REASON_IP_ADDRESS_DUPLICATE);
		return;
	}

	if (nm_streq (method, NM_SETTING_IP4_CONFIG_METHOD_MANUAL))
		nm_device_activate_schedule_ip_config_result (self, AF_INET, NULL);
	else {
		if (NM_DEVICE_GET_PRIVATE (self)->ip_state_4 != NM_DEVICE_IP_STATE_DONE)
			ip_config_merge_and_apply (self, AF_INET, TRUE);
	}
}

static void
acd_manager_probe_terminated (NMAcdManager *acd_manager, gpointer user_data)
{
	AcdData *data = user_data;
	NMDevice *self;
	NMDevicePrivate *priv;
	NMDedupMultiIter ipconf_iter;
	const NMPlatformIP4Address *address;
	gboolean result, success = TRUE;
	int i;

	g_assert (data);
	self = data->device;
	priv = NM_DEVICE_GET_PRIVATE (self);

	for (i = 0; data->configs && data->configs[i]; i++) {
		nm_ip_config_iter_ip4_address_for_each (&ipconf_iter, data->configs[i], &address) {
			char sbuf[NM_UTILS_INET_ADDRSTRLEN];

			result = nm_acd_manager_check_address (acd_manager, address->address);
			success &= result;

			_NMLOG (result ? LOGL_DEBUG : LOGL_WARN,
			        LOGD_DEVICE,
			        "IPv4 DAD result: address %s is %s",
			        _nm_utils_inet4_ntop (address->address, sbuf),
			        result ? "unique" : "duplicate");
		}
	}

	data->callback (self, data->configs, success);

	priv->acd.dad_list = g_slist_remove (priv->acd.dad_list, acd_manager);
	nm_acd_manager_free (acd_manager);
}

/**
 * ipv4_dad_start:
 * @self: device instance
 * @configs: NULL-terminated array of IPv4 configurations
 * @cb: callback function
 *
 * Start IPv4 DAD on device @self, check addresses in @configs and call @cb
 * when the procedure ends. @cb will be called in any case, even if DAD can't
 * be started. @configs will be unreferenced after @cb has been called.
 */
static void
ipv4_dad_start (NMDevice *self, NMIP4Config **configs, AcdCallback cb)
{
	static const NMAcdCallbacks acd_callbacks = {
		.probe_terminated_callback = acd_manager_probe_terminated,
		.user_data_destroy         = acd_data_destroy,
	};
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMAcdManager *acd_manager;
	const NMPlatformIP4Address *address;
	NMDedupMultiIter ipconf_iter;
	AcdData *data;
	guint timeout;
	gboolean addr_found;
	int r;
	const guint8 *hwaddr_arr;
	size_t length;
	guint i;

	g_return_if_fail (NM_IS_DEVICE (self));
	g_return_if_fail (configs);
	g_return_if_fail (cb);

	for (i = 0, addr_found = FALSE; configs[i]; i++) {
		if (nm_ip4_config_get_num_addresses (configs[i]) > 0) {
			addr_found = TRUE;
			break;
		}
	}

	timeout = get_ipv4_dad_timeout (self);
	hwaddr_arr = nm_platform_link_get_address (nm_device_get_platform (self),
	                                           nm_device_get_ip_ifindex (self),
	                                           &length);

	if (   !timeout
	    || !hwaddr_arr
	    || !addr_found
	    || length != ETH_ALEN
	    || nm_device_sys_iface_state_is_external_or_assume (self)) {

		/* DAD not needed, signal success */
		cb (self, configs, TRUE);

		for (i = 0; configs[i]; i++)
			g_object_unref (configs[i]);
		g_free (configs);

		return;
	}

	data = g_slice_new0 (AcdData);
	data->configs = configs;
	data->callback = cb;
	data->device = self;

	acd_manager = nm_acd_manager_new (nm_device_get_ip_ifindex (self),
	                                  hwaddr_arr,
	                                  length,
	                                  &acd_callbacks,
	                                  data);
	priv->acd.dad_list = g_slist_append (priv->acd.dad_list, acd_manager);

	for (i = 0; configs[i]; i++) {
		nm_ip_config_iter_ip4_address_for_each (&ipconf_iter, configs[i], &address)
			nm_acd_manager_add_address (acd_manager, address->address);
	}

	r = nm_acd_manager_start_probe (acd_manager, timeout);
	if (r < 0) {
		_LOGW (LOGD_DEVICE, "acd probe failed");

		/* DAD could not be started, signal success */
		cb (self, configs, TRUE);

		priv->acd.dad_list = g_slist_remove (priv->acd.dad_list, acd_manager);
		nm_acd_manager_free (acd_manager);
	}
}

/*****************************************************************************/
/* IPv4LL stuff */

static void
ipv4ll_cleanup (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->ipv4ll) {
		sd_ipv4ll_set_callback (priv->ipv4ll, NULL, NULL);
		sd_ipv4ll_stop (priv->ipv4ll);
		priv->ipv4ll = sd_ipv4ll_unref (priv->ipv4ll);
	}

	nm_clear_g_source (&priv->ipv4ll_timeout);
}

static NMIP4Config *
ipv4ll_get_ip4_config (NMDevice *self, guint32 lla)
{
	NMIP4Config *config = NULL;
	NMPlatformIP4Address address;
	NMPlatformIP4Route route;

	config = nm_device_ip4_config_new (self);
	g_assert (config);

	memset (&address, 0, sizeof (address));
	nm_platform_ip4_address_set_addr (&address, lla, 16);
	address.addr_source = NM_IP_CONFIG_SOURCE_IP4LL;
	nm_ip4_config_add_address (config, &address);

	/* Add a multicast route for link-local connections: destination= 224.0.0.0, netmask=240.0.0.0 */
	memset (&route, 0, sizeof (route));
	route.network = htonl (0xE0000000L);
	route.plen = 4;
	route.rt_source = NM_IP_CONFIG_SOURCE_IP4LL;
	route.table_coerced = nm_platform_route_table_coerce (nm_device_get_route_table (self, AF_INET));
	route.metric = nm_device_get_route_metric (self, AF_INET);
	nm_ip4_config_add_route (config, &route, NULL);

	return config;
}

static void
nm_device_handle_ipv4ll_event (sd_ipv4ll *ll, int event, void *data)
{
	NMDevice *self = data;
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	struct in_addr address;
	NMIP4Config *config;
	int r;

	if (priv->act_request.obj == NULL)
		return;

	nm_assert (nm_streq (nm_device_get_effective_ip_config_method (self, AF_INET),
	                     NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL));

	switch (event) {
	case SD_IPV4LL_EVENT_BIND:
		r = sd_ipv4ll_get_address (ll, &address);
		if (r < 0) {
			_LOGE (LOGD_AUTOIP4, "invalid IPv4 link-local address received, error %d.", r);
			nm_device_ip_method_failed (self, AF_INET, NM_DEVICE_STATE_REASON_AUTOIP_START_FAILED);
			return;
		}

		if (!nm_utils_ip4_address_is_link_local (address.s_addr)) {
			_LOGE (LOGD_AUTOIP4, "invalid address %08x received (not link-local).", address.s_addr);
			nm_device_ip_method_failed (self, AF_INET, NM_DEVICE_STATE_REASON_AUTOIP_ERROR);
			return;
		}

		config = ipv4ll_get_ip4_config (self, address.s_addr);
		if (config == NULL) {
			_LOGE (LOGD_AUTOIP4, "failed to get IPv4LL config");
			nm_device_ip_method_failed (self, AF_INET, NM_DEVICE_STATE_REASON_AUTOIP_FAILED);
			return;
		}

		if (priv->ip_state_4 == NM_DEVICE_IP_STATE_CONF) {
			nm_clear_g_source (&priv->ipv4ll_timeout);
			nm_device_activate_schedule_ip_config_result (self, AF_INET, NM_IP_CONFIG_CAST (config));
		} else if (priv->ip_state_4 == NM_DEVICE_IP_STATE_DONE) {
			applied_config_init (&priv->dev_ip_config_4, config);
			if (!ip_config_merge_and_apply (self, AF_INET, TRUE)) {
				_LOGE (LOGD_AUTOIP4, "failed to update IP4 config for autoip change.");
				nm_device_ip_method_failed (self, AF_INET, NM_DEVICE_STATE_REASON_AUTOIP_FAILED);
			}
		} else
			g_assert_not_reached ();

		g_object_unref (config);
		break;
	default:
		_LOGW (LOGD_AUTOIP4, "IPv4LL address no longer valid after event %d.", event);
		nm_device_ip_method_failed (self, AF_INET, NM_DEVICE_STATE_REASON_AUTOIP_FAILED);
	}
}

static gboolean
ipv4ll_timeout_cb (gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->ipv4ll_timeout) {
		_LOGI (LOGD_AUTOIP4, "IPv4LL configuration timed out.");
		priv->ipv4ll_timeout = 0;
		ipv4ll_cleanup (self);

		if (priv->ip_state_4 == NM_DEVICE_IP_STATE_CONF)
			nm_device_activate_schedule_ip_config_timeout (self, AF_INET);
	}

	return FALSE;
}

static NMActStageReturn
ipv4ll_start (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const struct ether_addr *addr;
	int ifindex, r;
	size_t addr_len;

	ipv4ll_cleanup (self);

	r = sd_ipv4ll_new (&priv->ipv4ll);
	if (r < 0) {
		_LOGE (LOGD_AUTOIP4, "IPv4LL: new() failed with error %d", r);
		return NM_ACT_STAGE_RETURN_FAILURE;
	}

	r = sd_ipv4ll_attach_event (priv->ipv4ll, NULL, 0);
	if (r < 0) {
		_LOGE (LOGD_AUTOIP4, "IPv4LL: attach_event() failed with error %d", r);
		return NM_ACT_STAGE_RETURN_FAILURE;
	}

	ifindex = nm_device_get_ip_ifindex (self);
	addr = nm_platform_link_get_address (nm_device_get_platform (self), ifindex, &addr_len);
	if (!addr || addr_len != ETH_ALEN) {
		_LOGE (LOGD_AUTOIP4, "IPv4LL: can't retrieve hardware address");
		return NM_ACT_STAGE_RETURN_FAILURE;
	}

	r = sd_ipv4ll_set_mac (priv->ipv4ll, addr);
	if (r < 0) {
		_LOGE (LOGD_AUTOIP4, "IPv4LL: set_mac() failed with error %d", r);
		return NM_ACT_STAGE_RETURN_FAILURE;
	}

	r = sd_ipv4ll_set_ifindex (priv->ipv4ll, ifindex);
	if (r < 0) {
		_LOGE (LOGD_AUTOIP4, "IPv4LL: set_ifindex() failed with error %d", r);
		return NM_ACT_STAGE_RETURN_FAILURE;
	}

	r = sd_ipv4ll_set_callback (priv->ipv4ll, nm_device_handle_ipv4ll_event, self);
	if (r < 0) {
		_LOGE (LOGD_AUTOIP4, "IPv4LL: set_callback() failed with error %d", r);
		return NM_ACT_STAGE_RETURN_FAILURE;
	}

	r = sd_ipv4ll_start (priv->ipv4ll);
	if (r < 0) {
		_LOGE (LOGD_AUTOIP4, "IPv4LL: start() failed with error %d", r);
		return NM_ACT_STAGE_RETURN_FAILURE;
	}

	_LOGI (LOGD_DEVICE | LOGD_AUTOIP4, "IPv4LL: started");

	/* Start a timeout to bound the address attempt */
	priv->ipv4ll_timeout = g_timeout_add_seconds (20, ipv4ll_timeout_cb, self);
	return NM_ACT_STAGE_RETURN_POSTPONE;
}

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

static void
ensure_con_ip_config (NMDevice *self, int addr_family)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMConnection *connection;
	const gboolean IS_IPv4 = (addr_family == AF_INET);
	NMIPConfig *con_ip_config;

	if (priv->con_ip_config_x[IS_IPv4])
		return;

	connection = nm_device_get_applied_connection (self);
	if (!connection)
		return;

	con_ip_config = nm_device_ip_config_new (self, addr_family);

	if (IS_IPv4) {
		nm_ip4_config_merge_setting (NM_IP4_CONFIG (con_ip_config),
		                             nm_connection_get_setting_ip4_config (connection),
		                             _get_mdns (self),
		                             _get_llmnr (self),
		                             nm_device_get_route_table (self, addr_family),
		                             nm_device_get_route_metric (self, addr_family));
	} else {
		nm_ip6_config_merge_setting (NM_IP6_CONFIG (con_ip_config),
		                             nm_connection_get_setting_ip6_config (connection),
		                             nm_device_get_route_table (self, addr_family),
		                             nm_device_get_route_metric (self, addr_family));
	}

	if (nm_device_sys_iface_state_is_external_or_assume (self)) {
		/* For assumed connections ignore all addresses and routes. */
		nm_ip_config_reset_addresses (con_ip_config);
		nm_ip_config_reset_routes (con_ip_config);
	}

	priv->con_ip_config_x[IS_IPv4] = con_ip_config;
}

/*****************************************************************************/
/* DHCPv4 stuff */

static guint32
_prop_get_ipvx_dhcp_timeout (NMDevice *self, int addr_family)
{
	NMDeviceClass *klass;
	NMConnection *connection;
	int timeout_i;
	guint32 timeout;

	nm_assert (NM_IS_DEVICE (self));
	nm_assert_addr_family (addr_family);

	connection = nm_device_get_applied_connection (self);

	timeout_i  = nm_setting_ip_config_get_dhcp_timeout (nm_connection_get_setting_ip_config (connection, addr_family));
	nm_assert (timeout_i >= 0 && timeout_i <= G_MAXINT32);

	timeout = (guint32) timeout_i;
	if (timeout)
		goto out;

	timeout = nm_config_data_get_connection_default_int64 (NM_CONFIG_GET_DATA,
	                                                       addr_family == AF_INET
	                                                         ? NM_CON_DEFAULT ("ipv4.dhcp-timeout")
	                                                         : NM_CON_DEFAULT ("ipv6.dhcp-timeout"),
	                                                       self,
	                                                       0, G_MAXINT32, 0);
	if (timeout)
		goto out;

	klass = NM_DEVICE_GET_CLASS (self);
	if (klass->get_dhcp_timeout_for_device) {
		timeout = klass->get_dhcp_timeout_for_device (self, addr_family);
		if (timeout)
			goto out;
	}

	timeout = NM_DHCP_TIMEOUT_DEFAULT;

out:
	G_STATIC_ASSERT_EXPR (G_MAXINT32 == NM_DHCP_TIMEOUT_INFINITY);
	nm_assert (timeout > 0);
	nm_assert (timeout <= G_MAXINT32);
	return timeout;
}

static void
dhcp4_cleanup (NMDevice *self, CleanupType cleanup_type, gboolean release)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	priv->dhcp_data_4.was_active = FALSE;
	nm_clear_g_source (&priv->dhcp_data_4.grace_id);
	priv->dhcp_data_4.grace_pending = FALSE;
	nm_clear_g_free (&priv->dhcp4.pac_url);

	if (priv->dhcp_data_4.client) {
		/* Stop any ongoing DHCP transaction on this device */
		nm_clear_g_signal_handler (priv->dhcp_data_4.client, &priv->dhcp_data_4.state_sigid);

		if (   cleanup_type == CLEANUP_TYPE_DECONFIGURE
		    || cleanup_type == CLEANUP_TYPE_REMOVED)
			nm_dhcp_client_stop (priv->dhcp_data_4.client, release);

		g_clear_object (&priv->dhcp_data_4.client);
	}

	if (priv->dhcp_data_4.config) {
		nm_dbus_object_clear_and_unexport (&priv->dhcp_data_4.config);
		_notify (self, PROP_DHCP4_CONFIG);
	}
}

static gboolean
ip_config_merge_and_apply (NMDevice *self,
                           int addr_family,
                           gboolean commit)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gboolean success;
	gs_unref_object NMIPConfig *composite = NULL;
	NMIPConfig *config;
	gs_unref_ptrarray GPtrArray *ip4_dev_route_blacklist = NULL;
	NMConnection *connection;
	gboolean ignore_auto_routes = FALSE;
	gboolean ignore_auto_dns = FALSE;
	gboolean ignore_default_routes = FALSE;
	GSList *iter;
	const char *ip6_addr_gen_token = NULL;
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	if (nm_device_sys_iface_state_is_external (self))
		commit = FALSE;

	connection = nm_device_get_applied_connection (self);

	/* Apply ignore-auto-routes and ignore-auto-dns settings */
	if (connection) {
		NMSettingIPConfig *s_ip;

		s_ip = nm_connection_get_setting_ip_config (connection, addr_family);
		if (s_ip) {
			ignore_auto_routes = nm_setting_ip_config_get_ignore_auto_routes (s_ip);
			ignore_auto_dns = nm_setting_ip_config_get_ignore_auto_dns (s_ip);

			/* if the connection has an explicit gateway, we also ignore
			 * the default routes from other sources. */
			ignore_default_routes =    nm_setting_ip_config_get_never_default (s_ip)
			                        || nm_setting_ip_config_get_gateway (s_ip);

			if (!IS_IPv4) {
				NMSettingIP6Config *s_ip6 = NM_SETTING_IP6_CONFIG (s_ip);

				if (nm_setting_ip6_config_get_addr_gen_mode (s_ip6) == NM_SETTING_IP6_CONFIG_ADDR_GEN_MODE_EUI64)
					ip6_addr_gen_token = nm_setting_ip6_config_get_token (s_ip6);
			}
		}
	}

	composite = nm_device_ip_config_new (self, addr_family);

	if (!IS_IPv4) {
		nm_ip6_config_set_privacy (NM_IP6_CONFIG (composite),
		                           priv->ndisc
		                             ? priv->ndisc_use_tempaddr
		                             : NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN);
	}

	init_ip_config_dns_priority (self, composite);

	if (commit) {
		if (priv->queued_ip_config_id_x[IS_IPv4])
			update_ext_ip_config (self, addr_family, FALSE);
		ensure_con_ip_config (self, addr_family);
	}

	if (!IS_IPv4) {
		if (   commit
		    && priv->ipv6ll_has) {
			const NMPlatformIP6Address ll_a = {
				.address = priv->ipv6ll_addr,
				.plen = 64,
				.addr_source = NM_IP_CONFIG_SOURCE_IP6LL,
			};
			const NMPlatformIP6Route ll_r = {
				.network.s6_addr16[0] = htons (0xfe80u),
				.plen = 64,
				.metric = nm_device_get_route_metric (self, addr_family),
				.rt_source = NM_IP_CONFIG_SOURCE_IP6LL,
			};

			nm_assert (IN6_IS_ADDR_LINKLOCAL (&priv->ipv6ll_addr));

			nm_ip6_config_add_address (NM_IP6_CONFIG (composite), &ll_a);
			nm_ip6_config_add_route (NM_IP6_CONFIG (composite), &ll_r, NULL);
		}
	}

	if (commit) {
		gboolean v;

		v = default_route_metric_penalty_detect (self, addr_family);
		if (IS_IPv4)
			priv->default_route_metric_penalty_ip4_has = v;
		else
			priv->default_route_metric_penalty_ip6_has = v;
	}

	/* Merge all the IP configs into the composite config */

	if (IS_IPv4) {
		config = applied_config_get_current (&priv->dev_ip_config_4);
		if (config) {
			nm_ip4_config_merge (NM_IP4_CONFIG (composite), NM_IP4_CONFIG (config),
			                       (ignore_auto_routes ? NM_IP_CONFIG_MERGE_NO_ROUTES : 0)
			                     | (ignore_default_routes ? NM_IP_CONFIG_MERGE_NO_DEFAULT_ROUTES : 0)
			                     | (ignore_auto_dns ? NM_IP_CONFIG_MERGE_NO_DNS : 0),
			                     default_route_metric_penalty_get (self, addr_family));
		}
	}

	if (!IS_IPv4) {
		config = applied_config_get_current (&priv->ac_ip6_config);
		if (config) {
			nm_ip6_config_merge (NM_IP6_CONFIG (composite), NM_IP6_CONFIG (config),
			                       (ignore_auto_routes ? NM_IP_CONFIG_MERGE_NO_ROUTES : 0)
			                     | (ignore_default_routes ? NM_IP_CONFIG_MERGE_NO_DEFAULT_ROUTES : 0)
			                     | (ignore_auto_dns ? NM_IP_CONFIG_MERGE_NO_DNS : 0),
			                     default_route_metric_penalty_get (self, addr_family));
		}
	}

	if (!IS_IPv4) {
		config = applied_config_get_current (&priv->dhcp6.ip6_config);
		if (config) {
			nm_ip6_config_merge (NM_IP6_CONFIG (composite), NM_IP6_CONFIG (config),
			                       (ignore_auto_routes ? NM_IP_CONFIG_MERGE_NO_ROUTES : 0)
			                     | (ignore_default_routes ? NM_IP_CONFIG_MERGE_NO_DEFAULT_ROUTES : 0)
			                     | (ignore_auto_dns ? NM_IP_CONFIG_MERGE_NO_DNS : 0),
			                     default_route_metric_penalty_get (self, addr_family));
		}
	}

	for (iter = priv->vpn_configs_x[IS_IPv4]; iter; iter = iter->next)
		nm_ip_config_merge (composite, iter->data, NM_IP_CONFIG_MERGE_DEFAULT, 0);

	if (priv->ext_ip_config_x[IS_IPv4])
		nm_ip_config_merge (composite, priv->ext_ip_config_x[IS_IPv4], NM_IP_CONFIG_MERGE_EXTERNAL, 0);

	/* Merge WWAN config *last* to ensure modem-given settings overwrite
	 * any external stuff set by pppd or other scripts.
	 */
	config = applied_config_get_current (&priv->dev2_ip_config_x[IS_IPv4]);
	if (config) {
		nm_ip_config_merge (composite, config,
		                      (ignore_auto_routes ? NM_IP_CONFIG_MERGE_NO_ROUTES : 0)
		                    | (ignore_default_routes ? NM_IP_CONFIG_MERGE_NO_DEFAULT_ROUTES : 0)
		                    | (ignore_auto_dns ? NM_IP_CONFIG_MERGE_NO_DNS : 0),
		                    default_route_metric_penalty_get (self, addr_family));
	}

	if (!IS_IPv4) {
		if (priv->rt6_temporary_not_available) {
			const NMPObject *o;
			GHashTableIter hiter;

			g_hash_table_iter_init (&hiter, priv->rt6_temporary_not_available);
			while (g_hash_table_iter_next (&hiter, (gpointer *) &o, NULL)) {
				nm_ip6_config_add_route (NM_IP6_CONFIG (composite),
				                         NMP_OBJECT_CAST_IP6_ROUTE (o),
				                         NULL);
			}
		}
	}

	/* Merge user overrides into the composite config. For assumed connections,
	 * con_ip_config_x is empty. */
	if (priv->con_ip_config_x[IS_IPv4]) {
		nm_ip_config_merge (composite, priv->con_ip_config_x[IS_IPv4], NM_IP_CONFIG_MERGE_DEFAULT,
		                    default_route_metric_penalty_get (self, addr_family));
	}

	if (commit) {
		gboolean is_vrf;

		is_vrf = priv->master && nm_device_get_device_type (priv->master) == NM_DEVICE_TYPE_VRF;

		if (IS_IPv4) {
			nm_ip4_config_add_dependent_routes (NM_IP4_CONFIG (composite),
			                                    nm_device_get_route_table (self, addr_family),
			                                    nm_device_get_route_metric (self, addr_family),
			                                    is_vrf,
			                                    &ip4_dev_route_blacklist);
		} else {
			nm_ip6_config_add_dependent_routes (NM_IP6_CONFIG (composite),
			                                    nm_device_get_route_table (self, addr_family),
			                                    nm_device_get_route_metric (self, addr_family),
			                                    is_vrf);
		}
	}

	if (IS_IPv4) {
		if (commit) {
			if (NM_DEVICE_GET_CLASS (self)->ip4_config_pre_commit)
				NM_DEVICE_GET_CLASS (self)->ip4_config_pre_commit (self, NM_IP4_CONFIG (composite));
		}
	}

	if (!IS_IPv4) {
		NMUtilsIPv6IfaceId iid;

		if (   commit
		    && priv->ndisc_started
		    && ip6_addr_gen_token
		    && nm_utils_ipv6_interface_identifier_get_from_token (&iid, ip6_addr_gen_token)) {
			set_ipv6_token (self, iid, ip6_addr_gen_token);
		}
	}

	success = nm_device_set_ip_config (self, addr_family, composite, commit, ip4_dev_route_blacklist);
	if (commit) {
		if (IS_IPv4)
			priv->v4_commit_first_time = FALSE;
		else
			priv->v6_commit_first_time = FALSE;
	}

	return success;
}

static gboolean
dhcp4_lease_change (NMDevice *self, NMIP4Config *config, gboolean bound)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gs_free_error GError *error = NULL;

	g_return_val_if_fail (config, FALSE);

	applied_config_init (&priv->dev_ip_config_4, config);

	if (!ip_config_merge_and_apply (self, AF_INET, TRUE)) {
		_LOGW (LOGD_DHCP4, "failed to update IPv4 config for DHCP change.");
		return FALSE;
	}

	/* TODO: we should perform DAD again whenever we obtain a
	 * new lease after an expiry. But what should we do if
	 * a duplicate address is detected? Fail the connection;
	 * restart DHCP; continue without an address? */
	if (bound && !nm_dhcp_client_accept (priv->dhcp_data_4.client, &error)) {
		_LOGW (LOGD_DHCP4, "error accepting lease: %s", error->message);
		return FALSE;
	}

	nm_dispatcher_call_device (NM_DISPATCHER_ACTION_DHCP4_CHANGE,
	                           self,
	                           NULL,
	                           NULL, NULL, NULL);

	return TRUE;
}

static gboolean
dhcp_grace_period_expired (NMDevice *self, int addr_family)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	priv->dhcp_data_x[IS_IPv4].grace_id = 0;
	priv->dhcp_data_x[IS_IPv4].grace_pending = FALSE;

	_LOGI (LOGD_DHCP_from_addr_family (addr_family),
	       "DHCPv%c: grace period expired",
	       nm_utils_addr_family_to_char (addr_family));

	nm_device_ip_method_failed (self,
	                            addr_family,
	                            NM_DEVICE_STATE_REASON_IP_CONFIG_EXPIRED);
	/* If the device didn't fail, the DHCP client will continue */

	return G_SOURCE_REMOVE;
}

static gboolean
dhcp_grace_period_expired_4 (gpointer user_data)
{
	return dhcp_grace_period_expired (user_data, AF_INET);
}

static gboolean
dhcp_grace_period_expired_6 (gpointer user_data)
{
	return dhcp_grace_period_expired (user_data, AF_INET6);
}

static gboolean
dhcp_grace_period_start (NMDevice *self, int addr_family)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const gboolean IS_IPv4 = (addr_family == AF_INET);
	guint32 timeout;

	/* In any other case (expired lease, assumed connection, etc.),
	 * wait for some time before failing the IP method.
	 */
	if (priv->dhcp_data_x[IS_IPv4].grace_pending) {
		/* already pending. */
		return FALSE;
	}

	/* Start a grace period equal to the DHCP timeout multiplied
	 * by a constant factor. */
	timeout = _prop_get_ipvx_dhcp_timeout (self, addr_family);
	if (timeout == NM_DHCP_TIMEOUT_INFINITY)
		_LOGI (LOGD_DHCP_from_addr_family (addr_family),
		       "DHCPv%c: trying to acquire a new lease",
		       nm_utils_addr_family_to_char (addr_family));
	else {
		timeout = dhcp_grace_period_from_timeout (timeout);
		_LOGI (LOGD_DHCP_from_addr_family (addr_family),
		       "DHCPv%c: trying to acquire a new lease within %u seconds",
		       nm_utils_addr_family_to_char (addr_family),
		       timeout);
		nm_assert (!priv->dhcp_data_x[IS_IPv4].grace_id);
		priv->dhcp_data_x[IS_IPv4].grace_id = g_timeout_add_seconds (timeout,
		                                                               IS_IPv4
		                                                             ? dhcp_grace_period_expired_4
		                                                             : dhcp_grace_period_expired_6,
		                                                             self);
	}

	priv->dhcp_data_x[IS_IPv4].grace_pending = TRUE;

	return TRUE;
}
static void
dhcp4_fail (NMDevice *self, NMDhcpState dhcp_state)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	_LOGD (LOGD_DHCP4, "DHCPv4 failed (ip_state %s, was_active %d)",
	       _ip_state_to_string (priv->ip_state_4),
	       priv->dhcp_data_4.was_active);

	/* The client is always left running after a failure. */

	/* Nothing to do if we failed before... */
	if (priv->ip_state_4 == NM_DEVICE_IP_STATE_FAIL)
		goto clear_config;

	/* ... and also if there are static addresses configured
	 * on the interface.
	 */
	if (   priv->ip_state_4 == NM_DEVICE_IP_STATE_DONE
	    && priv->con_ip_config_4
	    && nm_ip4_config_get_num_addresses (priv->con_ip_config_4) > 0)
		goto clear_config;

	/* Fail the method when one of the following is true:
	 * 1) the DHCP client terminated: it does not make sense to start a grace
	 *    period without a client running;
	 * 2) we failed to get an initial lease AND the client was
	 *    not active before.
	 */
	if (   dhcp_state == NM_DHCP_STATE_TERMINATED
	    || (!priv->dhcp_data_4.was_active && priv->ip_state_4 == NM_DEVICE_IP_STATE_CONF)) {
		nm_device_activate_schedule_ip_config_timeout (self, AF_INET);
		return;
	}

	if (dhcp_grace_period_start (self, AF_INET))
		goto clear_config;

	return;

clear_config:
	/* The previous configuration is no longer valid */
	if (priv->dhcp_data_4.config) {
		nm_dbus_object_clear_and_unexport (&priv->dhcp_data_4.config);
		priv->dhcp_data_4.config = nm_dhcp_config_new (AF_INET);
		_notify (self, PROP_DHCP4_CONFIG);
	}
}

static void
dhcp4_dad_cb (NMDevice *self, NMIP4Config **configs, gboolean success)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (success) {
		nm_device_activate_schedule_ip_config_result (self, AF_INET,
		                                              NM_IP_CONFIG_CAST (configs[1]));
	} else {
		nm_dhcp_client_decline (priv->dhcp_data_4.client, "Address conflict detected", NULL);
		nm_device_ip_method_failed (self, AF_INET,
		                            NM_DEVICE_STATE_REASON_IP_ADDRESS_DUPLICATE);
	}
}

static void
dhcp4_state_changed (NMDhcpClient *client,
                     NMDhcpState state,
                     NMIP4Config *ip4_config,
                     GHashTable *options,
                     const char *event_id,
                     gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMIP4Config *manual, **configs;
	NMConnection *connection;

	g_return_if_fail (nm_dhcp_client_get_addr_family (client) == AF_INET);
	g_return_if_fail (!ip4_config || NM_IS_IP4_CONFIG (ip4_config));

	_LOGD (LOGD_DHCP4, "new DHCPv4 client state %d", state);

	switch (state) {
	case NM_DHCP_STATE_BOUND:
	case NM_DHCP_STATE_EXTENDED:
		if (!ip4_config) {
			_LOGW (LOGD_DHCP4, "failed to get IPv4 config in response to DHCP event.");
			dhcp4_fail (self, state);
			break;
		}

		nm_clear_g_source (&priv->dhcp_data_4.grace_id);
		priv->dhcp_data_4.grace_pending = FALSE;

		/* After some failures, we have been able to renew the lease:
		 * update the ip state
		 */
		if (priv->ip_state_4 == NM_DEVICE_IP_STATE_FAIL)
			_set_ip_state (self, AF_INET, NM_DEVICE_IP_STATE_CONF);

		g_free (priv->dhcp4.pac_url);
		priv->dhcp4.pac_url = g_strdup (g_hash_table_lookup (options, "wpad"));
		nm_device_set_proxy_config (self, priv->dhcp4.pac_url);

		nm_dhcp_config_set_options (priv->dhcp_data_4.config, options);
		_notify (self, PROP_DHCP4_CONFIG);

		if (priv->ip_state_4 == NM_DEVICE_IP_STATE_CONF) {
			connection = nm_device_get_applied_connection (self);
			g_assert (connection);

			manual = nm_device_ip4_config_new (self);
			nm_ip4_config_merge_setting (manual,
			                             nm_connection_get_setting_ip4_config (connection),
			                             NM_SETTING_CONNECTION_MDNS_DEFAULT,
			                             NM_SETTING_CONNECTION_LLMNR_DEFAULT,
			                             nm_device_get_route_table (self, AF_INET),
			                             nm_device_get_route_metric (self, AF_INET));

			configs = g_new0 (NMIP4Config *, 3);
			configs[0] = manual;
			configs[1] = g_object_ref (ip4_config);

			ipv4_dad_start (self, configs, dhcp4_dad_cb);
		} else if (priv->ip_state_4 == NM_DEVICE_IP_STATE_DONE) {
			if (dhcp4_lease_change (self, ip4_config,
			                        state == NM_DHCP_STATE_BOUND))
				nm_device_update_metered (self);
			else
				dhcp4_fail (self, state);
		}
		break;
	case NM_DHCP_STATE_TIMEOUT:
		dhcp4_fail (self, state);
		break;
	case NM_DHCP_STATE_EXPIRE:
		/* Ignore expiry before we even have a lease (NAK, old lease, etc) */
		if (priv->ip_state_4 == NM_DEVICE_IP_STATE_CONF)
			break;
		/* fall-through */
	case NM_DHCP_STATE_DONE:
	case NM_DHCP_STATE_FAIL:
	case NM_DHCP_STATE_TERMINATED:
		dhcp4_fail (self, state);
		break;
	default:
		break;
	}
}

/**
 * _prop_get_ipvx_dhcp_iaid:
 * @self: the #NMDevice
 * @addr_family: the address family
 * @connection: the connection
 * @out_is_explicit: on return, %TRUE if the user set a valid IAID in
 *   the connection or in global configuration; %FALSE if the connection
 *   property was empty and no valid global configuration was provided.
 *
 * Returns: a IAID value for this device and the given connection.
 */
static guint32
_prop_get_ipvx_dhcp_iaid (NMDevice *self,
                          int addr_family,
                          NMConnection *connection,
                          gboolean *out_is_explicit)
{
	NMSettingIPConfig *s_ip;
	const char *iaid_str;
	gs_free char *iaid_str_free = NULL;
	guint32 iaid;
	const char *iface;
	const char *fail_reason;
	gboolean is_explicit = TRUE;

	s_ip = nm_connection_get_setting_ip_config (connection, addr_family);
	iaid_str = nm_setting_ip_config_get_dhcp_iaid (s_ip);
	if (!iaid_str) {
		iaid_str_free = nm_config_data_get_connection_default (NM_CONFIG_GET_DATA,
		                                                         addr_family == AF_INET
		                                                       ? NM_CON_DEFAULT ("ipv4.dhcp-iaid")
		                                                       : NM_CON_DEFAULT ("ipv6.dhcp-iaid"),
		                                                       self);
		iaid_str = iaid_str_free;
		if (!iaid_str) {
			iaid_str = NM_IAID_IFNAME;
			is_explicit = FALSE;
		} else if (!_nm_utils_iaid_verify (iaid_str, NULL)) {
			_LOGW (LOGD_DEVICE, "invalid global default '%s' for ipv%c.dhcp-iaid",
			       iaid_str,
			       nm_utils_addr_family_to_char (addr_family));
			iaid_str = NM_IAID_IFNAME;
			is_explicit = FALSE;
		}
	}

	if (nm_streq0 (iaid_str, NM_IAID_MAC)) {
		const NMPlatformLink *pllink;

		pllink = nm_platform_link_get (nm_device_get_platform (self),
		                               nm_device_get_ip_ifindex (self));
		if (!pllink || pllink->l_address.len < 4) {
			fail_reason = "invalid link-layer address";
			goto out_fail;
		}

		/* @iaid is in native endianness. Use unaligned_read_be32()
		 * so that the IAID for a given MAC address is the same on
		 * BE and LE machines. */
		iaid = unaligned_read_be32 (&pllink->l_address.data[pllink->l_address.len - 4]);
		goto out_good;
	} else if (nm_streq0 (iaid_str, NM_IAID_PERM_MAC)) {
		guint8 hwaddr_buf[NM_UTILS_HWADDR_LEN_MAX];
		const char *hwaddr_str;
		gsize hwaddr_len;

		hwaddr_str = nm_device_get_permanent_hw_address (self);
		if (!hwaddr_str) {
			fail_reason = "no permanent link-layer address";
			goto out_fail;
		}

		if (!_nm_utils_hwaddr_aton (hwaddr_str, hwaddr_buf, sizeof (hwaddr_buf), &hwaddr_len))
			g_return_val_if_reached (0);

		if (hwaddr_len < 4) {
			fail_reason = "invalid link-layer address";
			goto out_fail;
		}

		iaid = unaligned_read_be32 (&hwaddr_buf[hwaddr_len - 4]);
		goto out_good;
	}  else if (nm_streq (iaid_str, "stable")) {
		nm_auto_free_checksum GChecksum *sum = NULL;
		guint8 digest[NM_UTILS_CHECKSUM_LENGTH_SHA1];
		NMUtilsStableType stable_type;
		const char *stable_id;
		guint32 salted_header;
		const guint8 *host_id;
		gsize host_id_len;

		stable_id = _get_stable_id (self, connection, &stable_type);
		salted_header = htonl (53390459 + stable_type);
		nm_utils_host_id_get (&host_id, &host_id_len);
		iface = nm_device_get_ip_iface (self);

		sum = g_checksum_new (G_CHECKSUM_SHA1);
		g_checksum_update (sum, (const guchar *) &salted_header, sizeof (salted_header));
		g_checksum_update (sum, (const guchar *) stable_id, strlen (stable_id) + 1);
		g_checksum_update (sum, (const guchar *) iface, strlen (iface) + 1);
		g_checksum_update (sum, (const guchar *) host_id, host_id_len);
		nm_utils_checksum_get_digest (sum, digest);

		iaid = unaligned_read_be32 (digest);
		goto out_good;
	} else if ((iaid = _nm_utils_ascii_str_to_int64 (iaid_str, 10, 0, G_MAXUINT32, -1)) != -1) {
		goto out_good;
	} else {
		iface = nm_device_get_ip_iface (self);
		iaid = nm_utils_create_dhcp_iaid (TRUE,
		                                  (const guint8 *) iface,
		                                  strlen (iface));
		goto out_good;
	}

out_fail:
	nm_assert (fail_reason);
	_LOGW (  addr_family == AF_INET
	       ? (LOGD_DEVICE | LOGD_DHCP4 | LOGD_IP4)
	       : (LOGD_DEVICE | LOGD_DHCP6 | LOGD_IP6),
	       "ipv%c.dhcp-iaid: failure to generate IAID: %s. Using interface-name based IAID",
	       nm_utils_addr_family_to_char (addr_family), fail_reason);
	is_explicit = FALSE;
	iface = nm_device_get_ip_iface (self);
	iaid = nm_utils_create_dhcp_iaid (TRUE,
	                                  (const guint8 *) iface,
	                                  strlen (iface));
out_good:
	_LOGD (  addr_family == AF_INET
	       ? (LOGD_DEVICE | LOGD_DHCP4 | LOGD_IP4)
	       : (LOGD_DEVICE | LOGD_DHCP6 | LOGD_IP6),
	       "ipv%c.dhcp-iaid: using %u (0x%08x) IAID (str: '%s', explicit %d)",
	       nm_utils_addr_family_to_char (addr_family), iaid, iaid,
	       iaid_str, is_explicit);
	NM_SET_OUT (out_is_explicit, is_explicit);
	return iaid;
}

static NMDhcpHostnameFlags
get_dhcp_hostname_flags (NMDevice *self, int addr_family)
{
	NMConnection *connection;
	NMSettingIPConfig *s_ip;
	NMDhcpHostnameFlags flags;
	gs_free_error GError *error = NULL;

	g_return_val_if_fail (NM_IS_DEVICE (self), NM_DHCP_HOSTNAME_FLAG_NONE);

	connection = nm_device_get_applied_connection (self);
	s_ip = nm_connection_get_setting_ip_config (connection, addr_family);
	g_return_val_if_fail (s_ip, NM_DHCP_HOSTNAME_FLAG_NONE);

	if (!nm_setting_ip_config_get_dhcp_send_hostname (s_ip))
		return NM_DHCP_HOSTNAME_FLAG_NONE;

	flags = nm_setting_ip_config_get_dhcp_hostname_flags (s_ip);
	if (flags != NM_DHCP_HOSTNAME_FLAG_NONE)
		return flags;

	flags = nm_config_data_get_connection_default_int64 (NM_CONFIG_GET_DATA,
	                                                     addr_family == AF_INET
	                                                       ? NM_CON_DEFAULT ("ipv4.dhcp-hostname-flags")
	                                                       : NM_CON_DEFAULT ("ipv6.dhcp-hostname-flags"),
	                                                     self,
	                                                     0, NM_DHCP_HOSTNAME_FLAG_FQDN_CLEAR_FLAGS,
	                                                     0);

	if (!_nm_utils_validate_dhcp_hostname_flags (flags, addr_family, &error)) {
		_LOGW (LOGD_DEVICE, "invalid global default value 0x%x for ipv%d.%s: %s",
		       (guint) flags,
		       addr_family == AF_INET ? 4 : 6,
		       NM_SETTING_IP_CONFIG_DHCP_HOSTNAME_FLAGS,
		       error->message);
		flags = NM_DHCP_HOSTNAME_FLAG_NONE;
	}

	if (flags != NM_DHCP_HOSTNAME_FLAG_NONE)
		return flags;

	if (addr_family == AF_INET)
		return NM_DHCP_HOSTNAME_FLAGS_FQDN_DEFAULT_IP4;
	else
		return NM_DHCP_HOSTNAME_FLAGS_FQDN_DEFAULT_IP6;
}

static const char *
_prop_get_connection_mud_url (NMDevice *self,
                              NMSettingConnection *s_con,
                              char **out_mud_url)
{
	const char *mud_url;
	gs_free char *s = NULL;

	nm_assert (out_mud_url && !*out_mud_url);

	mud_url = nm_setting_connection_get_mud_url (s_con);

	if (mud_url) {
		if (nm_streq (mud_url, NM_CONNECTION_MUD_URL_NONE))
			return NULL;
		return mud_url;
	}

	s = nm_config_data_get_connection_default (NM_CONFIG_GET_DATA,
	                                           NM_CON_DEFAULT ("connection.mud-url"),
	                                           self);
	if (s) {
		if (nm_streq (s, NM_CONNECTION_MUD_URL_NONE))
			return NULL;
		if (nm_sd_http_url_is_valid_https (s))
			return (*out_mud_url = g_steal_pointer (&s));
	}

	return NULL;
}

static GBytes *
_prop_get_ipv4_dhcp_client_id (NMDevice *self,
                               NMConnection *connection,
                               GBytes *hwaddr)
{
	NMSettingIPConfig *s_ip4;
	const char *client_id;
	gs_free char *client_id_default = NULL;
	guint8 *client_id_buf;
	const char *fail_reason;
	guint8 hwaddr_bin_buf[NM_UTILS_HWADDR_LEN_MAX];
	const guint8 *hwaddr_bin;
	int arp_type;
	gsize hwaddr_len;
	GBytes *result;
	gs_free char *logstr1 = NULL;

	s_ip4 = nm_connection_get_setting_ip4_config (connection);
	client_id = nm_setting_ip4_config_get_dhcp_client_id (NM_SETTING_IP4_CONFIG (s_ip4));

	if (!client_id) {
		client_id_default = nm_config_data_get_connection_default (NM_CONFIG_GET_DATA,
		                                                           NM_CON_DEFAULT ("ipv4.dhcp-client-id"),
		                                                           self);
		if (client_id_default && client_id_default[0]) {
			/* a non-empty client-id is always valid, see nm_dhcp_utils_client_id_string_to_bytes().  */
			client_id = client_id_default;
		}
	}

	if (!client_id) {
		_LOGD (LOGD_DEVICE | LOGD_DHCP4 | LOGD_IP4,
		       "ipv4.dhcp-client-id: no explicit client-id configured");
		return NULL;
	}

	if (nm_streq (client_id, "mac")) {
		if (!hwaddr) {
			fail_reason = "missing link-layer address";
			goto out_fail;
		}

		hwaddr_bin = g_bytes_get_data (hwaddr, &hwaddr_len);
		arp_type = nm_utils_arp_type_detect_from_hwaddrlen (hwaddr_len);
		if (arp_type < 0) {
			fail_reason = "unsupported link-layer address";
			goto out_fail;
		}

		result = nm_utils_dhcp_client_id_mac (arp_type, hwaddr_bin, hwaddr_len);
		goto out_good;
	}

	if (nm_streq (client_id, "perm-mac")) {
		const char *hwaddr_str;

		hwaddr_str = nm_device_get_permanent_hw_address (self);
		if (!hwaddr_str) {
			fail_reason = "missing permanent link-layer address";
			goto out_fail;
		}

		if (!_nm_utils_hwaddr_aton (hwaddr_str, hwaddr_bin_buf, sizeof (hwaddr_bin_buf), &hwaddr_len))
			g_return_val_if_reached (NULL);

		arp_type = nm_utils_arp_type_detect_from_hwaddrlen (hwaddr_len);
		if (arp_type < 0) {
			fail_reason = "unsupported permanent link-layer address";
			goto out_fail;
		}

		result = nm_utils_dhcp_client_id_mac (arp_type, hwaddr_bin_buf, hwaddr_len);
		goto out_good;
	}

	if (nm_streq (client_id, "duid")) {
		guint32 iaid = _prop_get_ipvx_dhcp_iaid (self, AF_INET, connection, NULL);

		result = nm_utils_dhcp_client_id_systemd_node_specific (iaid);
		goto out_good;
	}

	if (nm_streq (client_id, "stable")) {
		nm_auto_free_checksum GChecksum *sum = NULL;
		guint8 digest[NM_UTILS_CHECKSUM_LENGTH_SHA1];
		NMUtilsStableType stable_type;
		const char *stable_id;
		guint32 salted_header;
		const guint8 *host_id;
		gsize host_id_len;

		stable_id = _get_stable_id (self, connection, &stable_type);
		salted_header = htonl (2011610591 + stable_type);
		nm_utils_host_id_get (&host_id, &host_id_len);

		sum = g_checksum_new (G_CHECKSUM_SHA1);
		g_checksum_update (sum, (const guchar *) &salted_header, sizeof (salted_header));
		g_checksum_update (sum, (const guchar *) stable_id, strlen (stable_id) + 1);
		g_checksum_update (sum, (const guchar *) host_id, host_id_len);
		nm_utils_checksum_get_digest (sum, digest);

		client_id_buf = g_malloc (1 + 15);
		client_id_buf[0] = 0;
		memcpy (&client_id_buf[1], digest, 15);
		result = g_bytes_new_take (client_id_buf, 1 + 15);
		goto out_good;
	}

	result = nm_dhcp_utils_client_id_string_to_bytes (client_id);
	goto out_good;

out_fail:
	nm_assert (fail_reason);
	_LOGW (LOGD_DEVICE | LOGD_DHCP4 | LOGD_IP4,
	       "ipv4.dhcp-client-id: failure to generate client id (%s). Use random client id",
	       fail_reason);
	client_id_buf = g_malloc (1 + 15);
	client_id_buf[0] = 0;
	nm_utils_random_bytes (&client_id_buf[1], 15);
	result = g_bytes_new_take (client_id_buf, 1 + 15);

out_good:
	nm_assert (result);
	_LOGD (LOGD_DEVICE | LOGD_DHCP4 | LOGD_IP4,
	       "ipv4.dhcp-client-id: use \"%s\" client ID: %s",
	       client_id,
	       (logstr1 = nm_dhcp_utils_duid_to_string (result)));
	return result;
}

static GBytes *
_prop_get_ipv4_dhcp_vendor_class_identifier (NMDevice *self, NMSettingIP4Config *s_ip4)
{
	gs_free char *config_data_prop = NULL;
	gs_free char *to_free = NULL;
	const char *conn_prop;
	GBytes *bytes = NULL;
	const char *bin;
	gsize len;

	conn_prop = nm_setting_ip4_config_get_dhcp_vendor_class_identifier (s_ip4);

	if (!conn_prop) {
		/* set in NetworkManager.conf ? */
		config_data_prop = nm_config_data_get_connection_default (
		    NM_CONFIG_GET_DATA,
		    NM_CON_DEFAULT ("ipv4.dhcp-vendor-class-identifier"),
		    self);

		if (   config_data_prop
		    && nm_utils_validate_dhcp4_vendor_class_id (config_data_prop, NULL))
			conn_prop = config_data_prop;
	}

	if (conn_prop) {
		bin = nm_utils_buf_utf8safe_unescape (conn_prop,
		                                      NM_UTILS_STR_UTF8_SAFE_FLAG_NONE,
		                                      &len,
		                                      (gpointer *) &to_free);
		if (to_free)
			bytes = g_bytes_new_take (g_steal_pointer (&to_free), len);
		else
			bytes = g_bytes_new (bin, len);
	}

	return bytes;
}

static NMActStageReturn
dhcp4_start (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMSettingIPConfig *s_ip4;
	gs_unref_bytes GBytes *vendor_class_identifier = NULL;
	gs_unref_bytes GBytes *hwaddr = NULL;
	gs_unref_bytes GBytes *bcast_hwaddr = NULL;
	gs_unref_bytes GBytes *client_id = NULL;
	gs_free char *mud_url_free = NULL;
	NMConnection *connection;
	NMSettingConnection *s_con;
	GError *error = NULL;
	const NMPlatformLink *pllink;
	const char *const *reject_servers;

	connection = nm_device_get_applied_connection (self);
	g_return_val_if_fail (connection, FALSE);

	s_ip4 = nm_connection_get_setting_ip4_config (connection);

	s_con = nm_connection_get_setting_connection (connection);
	nm_assert (s_con);

	/* Clear old exported DHCP options */
	nm_dbus_object_clear_and_unexport (&priv->dhcp_data_4.config);
	priv->dhcp_data_4.config = nm_dhcp_config_new (AF_INET);

	pllink = nm_platform_link_get (nm_device_get_platform (self), nm_device_get_ip_ifindex (self));
	if (pllink) {
		hwaddr = nmp_link_address_get_as_bytes (&pllink->l_address);
		bcast_hwaddr = nmp_link_address_get_as_bytes (&pllink->l_broadcast);
	}

	client_id = _prop_get_ipv4_dhcp_client_id (self, connection, hwaddr);
	vendor_class_identifier = _prop_get_ipv4_dhcp_vendor_class_identifier (self, NM_SETTING_IP4_CONFIG (s_ip4));
	reject_servers = nm_setting_ip_config_get_dhcp_reject_servers (s_ip4, NULL);

	g_warn_if_fail (priv->dhcp_data_4.client == NULL);
	priv->dhcp_data_4.client = nm_dhcp_manager_start_ip4 (nm_dhcp_manager_get (),
	                                                      nm_netns_get_multi_idx (nm_device_get_netns (self)),
	                                                      nm_device_get_ip_iface (self),
	                                                      nm_device_get_ip_ifindex (self),
	                                                      hwaddr,
	                                                      bcast_hwaddr,
	                                                      nm_connection_get_uuid (connection),
	                                                      nm_device_get_route_table (self, AF_INET),
	                                                      nm_device_get_route_metric (self, AF_INET),
	                                                      nm_setting_ip_config_get_dhcp_send_hostname (s_ip4),
	                                                      nm_setting_ip_config_get_dhcp_hostname (s_ip4),
	                                                      nm_setting_ip4_config_get_dhcp_fqdn (NM_SETTING_IP4_CONFIG (s_ip4)),
	                                                      get_dhcp_hostname_flags (self, AF_INET),
	                                                      _prop_get_connection_mud_url (self, s_con, &mud_url_free),
	                                                      client_id,
	                                                      _prop_get_ipvx_dhcp_timeout (self, AF_INET),
	                                                      priv->dhcp_anycast_address,
	                                                      NULL,
	                                                      vendor_class_identifier,
	                                                      reject_servers,
	                                                      &error);
	if (!priv->dhcp_data_4.client) {
		_LOGW (LOGD_DHCP4, "failure to start DHCP: %s", error->message);
		g_clear_error (&error);
		return NM_ACT_STAGE_RETURN_FAILURE;
	}

	priv->dhcp_data_4.state_sigid = g_signal_connect (priv->dhcp_data_4.client,
	                                                  NM_DHCP_CLIENT_SIGNAL_STATE_CHANGED,
	                                                  G_CALLBACK (dhcp4_state_changed),
	                                                  self);

	if (nm_device_sys_iface_state_is_external_or_assume (self))
		priv->dhcp_data_4.was_active = TRUE;

	/* DHCP devices will be notified by the DHCP manager when stuff happens */
	return NM_ACT_STAGE_RETURN_POSTPONE;
}

gboolean
nm_device_dhcp4_renew (NMDevice *self, gboolean release)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	g_return_val_if_fail (priv->dhcp_data_4.client != NULL, FALSE);

	_LOGI (LOGD_DHCP4, "DHCPv4 lease renewal requested");

	/* Terminate old DHCP instance and release the old lease */
	dhcp4_cleanup (self, CLEANUP_TYPE_DECONFIGURE, release);

	/* Start DHCP again on the interface */
	return dhcp4_start (self) != NM_ACT_STAGE_RETURN_FAILURE;
}

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

static GHashTable *shared_ips = NULL;

static void
shared_ip_release (gpointer data)
{
	g_hash_table_remove (shared_ips, data);
	if (!g_hash_table_size (shared_ips))
		nm_clear_pointer (&shared_ips, g_hash_table_unref);
}

static NMIP4Config *
shared4_new_config (NMDevice *self, NMConnection *connection)
{
	NMIP4Config *config = NULL;
	gboolean is_generated = FALSE;
	NMSettingIPConfig *s_ip4;
	NMPlatformIP4Address address = {
		.addr_source = NM_IP_CONFIG_SOURCE_SHARED,
	};

	g_return_val_if_fail (self, NULL);
	g_return_val_if_fail (connection, NULL);

	s_ip4 = nm_connection_get_setting_ip4_config (connection);
	if (s_ip4 && nm_setting_ip_config_get_num_addresses (s_ip4)) {
		/* Use the first user-supplied address */
		NMIPAddress *user = nm_setting_ip_config_get_address (s_ip4, 0);
		in_addr_t a;

		nm_ip_address_get_address_binary (user, &a);
		nm_platform_ip4_address_set_addr (&address, a, nm_ip_address_get_prefix (user));
	} else {
		/* Find an unused address in the 10.42.x.x range */
		guint32 start = (guint32) ntohl (0x0a2a0001); /* 10.42.0.1 */
		guint32 count = 0;

		if (G_UNLIKELY (!shared_ips))
			shared_ips = g_hash_table_new (nm_direct_hash, NULL);
		else {
			while (g_hash_table_lookup (shared_ips, GUINT_TO_POINTER (start + count))) {
				count += ntohl (0x100);
				if (count > ntohl (0xFE00)) {
					_LOGE (LOGD_SHARING, "ran out of shared IP addresses!");
					return FALSE;
				}
			}
		}
		nm_platform_ip4_address_set_addr (&address, start + count, 24);
		g_hash_table_add (shared_ips, GUINT_TO_POINTER (address.address));
		is_generated = TRUE;
	}

	config = nm_device_ip4_config_new (self);
	nm_ip4_config_add_address (config, &address);
	if (is_generated) {
		/* Remove the address lock when the object gets disposed */
		g_object_set_qdata_full (G_OBJECT (config), NM_CACHED_QUARK ("shared-ip"),
		                         GUINT_TO_POINTER (address.address),
		                         shared_ip_release);
	}
	return config;
}

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

static gboolean
connection_ip_method_requires_carrier (NMConnection *connection,
                                       int addr_family,
                                       gboolean *out_ip_enabled)
{
	const char *method;

	method = nm_utils_get_ip_config_method (connection, addr_family);

	if (addr_family == AF_INET) {
		NM_SET_OUT (out_ip_enabled, !nm_streq (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED));
		return NM_IN_STRSET (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO,
		                             NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL);
	}

	NM_SET_OUT (out_ip_enabled,
	            !NM_IN_STRSET (method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE,
	                                   NM_SETTING_IP6_CONFIG_METHOD_DISABLED));
	return NM_IN_STRSET (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO,
	                             NM_SETTING_IP6_CONFIG_METHOD_DHCP,
	                             NM_SETTING_IP6_CONFIG_METHOD_SHARED,
	                             NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL);
}

static gboolean
connection_requires_carrier (NMConnection *connection)
{
	NMSettingIPConfig *s_ip4, *s_ip6;
	NMSettingConnection *s_con;
	gboolean ip4_carrier_wanted, ip6_carrier_wanted;
	gboolean ip4_used = FALSE, ip6_used = FALSE;

	/* We can progress to IP_CONFIG now, so that we're enslaved.
	 * That may actually cause carrier to go up and thus continue activation. */
	s_con = nm_connection_get_setting_connection (connection);
	if (nm_setting_connection_get_master (s_con))
		return FALSE;

	ip4_carrier_wanted = connection_ip_method_requires_carrier (connection, AF_INET, &ip4_used);
	if (ip4_carrier_wanted) {
		/* If IPv4 wants a carrier and cannot fail, the whole connection
		 * requires a carrier regardless of the IPv6 method.
		 */
		s_ip4 = nm_connection_get_setting_ip4_config (connection);
		if (s_ip4 && !nm_setting_ip_config_get_may_fail (s_ip4))
			return TRUE;
	}

	ip6_carrier_wanted = connection_ip_method_requires_carrier (connection, AF_INET6, &ip6_used);
	if (ip6_carrier_wanted) {
		/* If IPv6 wants a carrier and cannot fail, the whole connection
		 * requires a carrier regardless of the IPv4 method.
		 */
		s_ip6 = nm_connection_get_setting_ip6_config (connection);
		if (s_ip6 && !nm_setting_ip_config_get_may_fail (s_ip6))
			return TRUE;
	}

	/* If an IP version wants a carrier and the other IP version isn't
	 * used, the connection requires carrier since it will just fail without one.
	 */
	if (ip4_carrier_wanted && !ip6_used)
		return TRUE;
	if (ip6_carrier_wanted && !ip4_used)
		return TRUE;

	/* If both want a carrier, the whole connection wants a carrier */
	return ip4_carrier_wanted && ip6_carrier_wanted;
}

static gboolean
have_any_ready_slaves (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	SlaveInfo *info;
	CList *iter;

	/* Any enslaved slave is "ready" in the generic case as it's
	 * at least >= NM_DEVCIE_STATE_IP_CONFIG and has had Layer 2
	 * properties set up.
	 */
	c_list_for_each (iter, &priv->slaves) {
		info = c_list_entry (iter, SlaveInfo, lst_slave);
		if (NM_DEVICE_GET_PRIVATE (info->slave)->is_enslaved)
			return TRUE;
	}
	return FALSE;
}

/*****************************************************************************/
/* DHCPv6 stuff */

static void
dhcp6_cleanup (NMDevice *self, CleanupType cleanup_type, gboolean release)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	priv->dhcp_data_6.was_active = FALSE;
	priv->dhcp6.mode = NM_NDISC_DHCP_LEVEL_NONE;
	applied_config_clear (&priv->dhcp6.ip6_config);
	nm_clear_g_free (&priv->dhcp6.event_id);
	nm_clear_g_source (&priv->dhcp_data_6.grace_id);
	priv->dhcp_data_6.grace_pending = FALSE;

	if (priv->dhcp_data_6.client) {
		nm_clear_g_signal_handler (priv->dhcp_data_6.client, &priv->dhcp_data_6.state_sigid);
		nm_clear_g_signal_handler (priv->dhcp_data_6.client, &priv->dhcp6.prefix_sigid);

		if (   cleanup_type == CLEANUP_TYPE_DECONFIGURE
		    || cleanup_type == CLEANUP_TYPE_REMOVED)
			nm_dhcp_client_stop (priv->dhcp_data_6.client, release);

		g_clear_object (&priv->dhcp_data_6.client);
	}

	if (priv->dhcp_data_6.config) {
		nm_dbus_object_clear_and_unexport (&priv->dhcp_data_6.config);
		_notify (self, PROP_DHCP6_CONFIG);
	}
}

static gboolean
dhcp6_lease_change (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMSettingsConnection *settings_connection;

	if (!applied_config_get_current (&priv->dhcp6.ip6_config)) {
		_LOGW (LOGD_DHCP6, "failed to get DHCPv6 config for rebind");
		return FALSE;
	}

	g_assert (priv->dhcp_data_6.client);  /* sanity check */

	settings_connection = nm_device_get_settings_connection (self);
	g_assert (settings_connection);

	/* Apply the updated config */
	if (!ip_config_merge_and_apply (self, AF_INET6, TRUE)) {
		_LOGW (LOGD_DHCP6, "failed to update IPv6 config in response to DHCP event");
		return FALSE;
	}

	nm_dispatcher_call_device (NM_DISPATCHER_ACTION_DHCP6_CHANGE,
	                           self,
	                           NULL,
	                           NULL, NULL, NULL);

	return TRUE;
}

static void
dhcp6_fail (NMDevice *self, NMDhcpState dhcp_state)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gboolean is_dhcp_managed;

	_LOGD (LOGD_DHCP6, "DHCPv6 failed (ip_state %s, was_active %d)",
	       _ip_state_to_string (priv->ip_state_6),
	       priv->dhcp_data_6.was_active);

	/* The client is always left running after a failure. */

	/* Nothing to do if we failed before... */
	if (priv->ip_state_6 == NM_DEVICE_IP_STATE_FAIL)
		goto clear_config;

	is_dhcp_managed = (priv->dhcp6.mode == NM_NDISC_DHCP_LEVEL_MANAGED);

	if (is_dhcp_managed) {
		/* ... and also if there are static addresses configured
		 * on the interface.
		 */
		if (   priv->ip_state_6 == NM_DEVICE_IP_STATE_DONE
		    && priv->con_ip_config_6
		    && nm_ip6_config_get_num_addresses (priv->con_ip_config_6))
			goto clear_config;

		/* Fail the method when one of the following is true:
		 * 1) the DHCP client terminated: it does not make sense to start a grace
		 *    period without a client running;
		 * 2) we failed to get an initial lease AND the client was
		 *    not active before.
		 */
		if (   dhcp_state == NM_DHCP_STATE_TERMINATED
		    || (!priv->dhcp_data_6.was_active && priv->ip_state_6 == NM_DEVICE_IP_STATE_CONF)) {
			nm_device_activate_schedule_ip_config_timeout (self, AF_INET6);
			return;
		}

		if (dhcp_grace_period_start (self, AF_INET6))
			goto clear_config;
	} else {
		/* not a hard failure; just live with the RA info */
		dhcp6_cleanup (self, CLEANUP_TYPE_DECONFIGURE, FALSE);
		if (priv->ip_state_6 == NM_DEVICE_IP_STATE_CONF)
			nm_device_activate_schedule_ip_config_result (self, AF_INET6, NULL);
	}
	return;

clear_config:
	/* The previous configuration is no longer valid */
	if (priv->dhcp_data_6.config) {
		nm_dbus_object_clear_and_unexport (&priv->dhcp_data_6.config);
		priv->dhcp_data_6.config = nm_dhcp_config_new (AF_INET6);
		_notify (self, PROP_DHCP6_CONFIG);
	}
}

static void
dhcp6_state_changed (NMDhcpClient *client,
                     NMDhcpState state,
                     NMIP6Config *ip6_config,
                     GHashTable *options,
                     const char *event_id,
                     gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	g_return_if_fail (nm_dhcp_client_get_addr_family (client) == AF_INET6);
	g_return_if_fail (!ip6_config || NM_IS_IP6_CONFIG (ip6_config));

	_LOGD (LOGD_DHCP6, "new DHCPv6 client state %d", state);

	switch (state) {
	case NM_DHCP_STATE_BOUND:
	case NM_DHCP_STATE_EXTENDED:
		nm_clear_g_source (&priv->dhcp_data_6.grace_id);
		priv->dhcp_data_6.grace_pending = FALSE;
		/* If the server sends multiple IPv6 addresses, we receive a state
		 * changed event for each of them. Use the event ID to merge IPv6
		 * addresses from the same transaction into a single configuration.
		 */
		if (   ip6_config
		    && event_id
		    && priv->dhcp6.event_id
		    && nm_streq (event_id, priv->dhcp6.event_id)) {
			NMDedupMultiIter ipconf_iter;
			const NMPlatformIP6Address *a;

			nm_ip_config_iter_ip6_address_for_each (&ipconf_iter, ip6_config, &a)
				applied_config_add_address (&priv->dhcp6.ip6_config, NM_PLATFORM_IP_ADDRESS_CAST (a));
		} else {
			nm_clear_g_free (&priv->dhcp6.event_id);
			if (ip6_config) {
				applied_config_init (&priv->dhcp6.ip6_config, ip6_config);
				priv->dhcp6.event_id = g_strdup (event_id);
				nm_dhcp_config_set_options (priv->dhcp_data_6.config, options);
				_notify (self, PROP_DHCP6_CONFIG);
			} else
				applied_config_clear (&priv->dhcp6.ip6_config);
		}

		/* After long time we have been able to renew the lease:
		 * update the ip state
		 */
		if (priv->ip_state_6 == NM_DEVICE_IP_STATE_FAIL)
			_set_ip_state (self, AF_INET6, NM_DEVICE_IP_STATE_CONF);

		if (priv->ip_state_6 == NM_DEVICE_IP_STATE_CONF) {
			if (!applied_config_get_current (&priv->dhcp6.ip6_config)) {
				nm_device_ip_method_failed (self, AF_INET6, NM_DEVICE_STATE_REASON_DHCP_FAILED);
				break;
			}
			nm_device_activate_schedule_ip_config_result (self, AF_INET6, NULL);
		} else if (priv->ip_state_6 == NM_DEVICE_IP_STATE_DONE)
			if (!dhcp6_lease_change (self))
				dhcp6_fail (self, state);
		break;
	case NM_DHCP_STATE_TIMEOUT:
		if (priv->dhcp6.mode == NM_NDISC_DHCP_LEVEL_MANAGED)
			dhcp6_fail (self, state);
		else {
			/* not a hard failure; just live with the RA info */
			dhcp6_cleanup (self, CLEANUP_TYPE_DECONFIGURE, FALSE);
			if (priv->ip_state_6 == NM_DEVICE_IP_STATE_CONF)
				nm_device_activate_schedule_ip_config_result (self, AF_INET6, NULL);
		}
		break;
	case NM_DHCP_STATE_EXPIRE:
		/* Ignore expiry before we even have a lease (NAK, old lease, etc) */
		if (priv->ip_state_6 != NM_DEVICE_IP_STATE_CONF)
			dhcp6_fail (self, state);
		break;
	case NM_DHCP_STATE_TERMINATED:
		/* In IPv6 info-only mode, the client doesn't handle leases so it
		 * may exit right after getting a response from the server.  That's
		 * normal.  In that case we just ignore the exit.
		 */
		if (priv->dhcp6.mode == NM_NDISC_DHCP_LEVEL_OTHERCONF)
			break;
		/* fall-through */
	case NM_DHCP_STATE_DONE:
	case NM_DHCP_STATE_FAIL:
		dhcp6_fail (self, state);
		break;
	default:
		break;
	}
}

static void
dhcp6_prefix_delegated (NMDhcpClient *client,
                        NMPlatformIP6Address *prefix,
                        gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);

	/* Just re-emit. The device just contributes the prefix to the
	 * pool in NMPolicy, which decides about subnet allocation
	 * on the shared devices. */
	g_signal_emit (self, signals[IP6_PREFIX_DELEGATED], 0, prefix);
}

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

static GBytes *
_prop_get_ipv6_dhcp_duid (NMDevice *self, NMConnection *connection, GBytes *hwaddr, gboolean *out_enforce)
{
	NMSettingIPConfig *s_ip6;
	const char *duid;
	gs_free char *duid_default = NULL;
	const char *duid_error;
	GBytes *duid_out;
	gboolean duid_enforce = TRUE;
	gs_free char *logstr1 = NULL;
	const guint8 *hwaddr_bin;
	gsize hwaddr_len;
	int arp_type;

	s_ip6 = nm_connection_get_setting_ip6_config (connection);
	duid = nm_setting_ip6_config_get_dhcp_duid (NM_SETTING_IP6_CONFIG (s_ip6));

	if (!duid) {
		duid_default = nm_config_data_get_connection_default (NM_CONFIG_GET_DATA,
		                                                      NM_CON_DEFAULT ("ipv6.dhcp-duid"),
		                                                      self);
		duid = duid_default;
		if (!duid)
			duid = "lease";
	}

	if (nm_streq (duid, "lease")) {
		duid_enforce = FALSE;
		duid_out = nm_utils_generate_duid_from_machine_id ();
		goto out_good;
	}

	if (!_nm_utils_dhcp_duid_valid (duid, &duid_out)) {
		duid_error = "invalid duid";
		goto out_fail;
	}

	if (duid_out)
		goto out_good;

	if (NM_IN_STRSET (duid, "ll", "llt")) {
		if (!hwaddr) {
			duid_error = "missing link-layer address";
			goto out_fail;
		}

		hwaddr_bin = g_bytes_get_data (hwaddr, &hwaddr_len);
		arp_type = nm_utils_arp_type_detect_from_hwaddrlen (hwaddr_len);
		if (arp_type < 0) {
			duid_error = "unsupported link-layer address";
			goto out_fail;
		}

		if (nm_streq (duid, "ll"))
			duid_out = nm_utils_generate_duid_ll (arp_type, hwaddr_bin, hwaddr_len);
		else {
			duid_out = nm_utils_generate_duid_llt (arp_type, hwaddr_bin, hwaddr_len,
			                                       nm_utils_host_id_get_timestamp_ns () / NM_UTILS_NSEC_PER_SEC);
		}

		goto out_good;
	}

	if (NM_IN_STRSET (duid, "stable-ll", "stable-llt", "stable-uuid")) {
		/* preferably, we would salt the checksum differently for each @duid type. We missed
		 * to do that initially, so most types use the DEFAULT_SALT.
		 *
		 * Implementations that are added later, should use a distinct salt instead,
		 * like "stable-ll"/"stable-llt" with ARPHRD_INFINIBAND below. */
		const guint32 DEFAULT_SALT = 670531087u;
		nm_auto_free_checksum GChecksum *sum = NULL;
		NMUtilsStableType stable_type;
		const char *stable_id = NULL;
		guint32 salted_header;
		const guint8 *host_id;
		gsize host_id_len;
		union {
			guint8 sha256[NM_UTILS_CHECKSUM_LENGTH_SHA256];
			guint8 hwaddr_eth[ETH_ALEN];
			guint8 hwaddr_infiniband[INFINIBAND_ALEN];
			NMUuid uuid;
			struct _nm_packed {
				guint8 hwaddr[ETH_ALEN];
				guint32 timestamp;
			} llt_eth;
			struct _nm_packed {
				guint8 hwaddr[INFINIBAND_ALEN];
				guint32 timestamp;
			} llt_infiniband;
		} digest;

		stable_id = _get_stable_id (self, connection, &stable_type);

		if (NM_IN_STRSET (duid, "stable-ll", "stable-llt")) {
			/* for stable LL/LLT DUIDs, we still need a hardware address to detect
			 * the arp-type. Alternatively, we would be able to detect it based on
			 * other means (e.g. NMDevice type), but instead require the hardware
			 * address to be present. This is at least consistent with the "ll"/"llt"
			 * modes above. */
			if (!hwaddr) {
				duid_error = "missing link-layer address";
				goto out_fail;
			}
			if ((arp_type = nm_utils_arp_type_detect_from_hwaddrlen (g_bytes_get_size (hwaddr))) < 0) {
				duid_error = "unsupported link-layer address";
				goto out_fail;
			}

			if (arp_type == ARPHRD_ETHER)
				salted_header = DEFAULT_SALT;
			else {
				nm_assert (arp_type == ARPHRD_INFINIBAND);
				salted_header = 0x42492CEFu + ((guint32) arp_type);
			}
		} else {
			salted_header = DEFAULT_SALT;
			arp_type = -1;
		}

		salted_header = htonl (salted_header + ((guint32) stable_type));

		nm_utils_host_id_get (&host_id, &host_id_len);

		sum = g_checksum_new (G_CHECKSUM_SHA256);
		g_checksum_update (sum, (const guchar *) &salted_header, sizeof (salted_header));
		g_checksum_update (sum, (const guchar *) stable_id, -1);
		g_checksum_update (sum, (const guchar *) host_id, host_id_len);
		nm_utils_checksum_get_digest (sum, digest.sha256);

		G_STATIC_ASSERT_EXPR (sizeof (digest) == sizeof (digest.sha256));

		if (nm_streq (duid, "stable-ll")) {
			switch (arp_type) {
			case ARPHRD_ETHER:
				duid_out = nm_utils_generate_duid_ll (arp_type, digest.hwaddr_eth, sizeof (digest.hwaddr_eth));
				break;
			case ARPHRD_INFINIBAND:
				duid_out = nm_utils_generate_duid_ll (arp_type, digest.hwaddr_infiniband, sizeof (digest.hwaddr_infiniband));
				break;
			default:
				g_return_val_if_reached (NULL);
			}
		} else if (nm_streq (duid, "stable-llt")) {
			gint64 time;
			guint32 timestamp;

#define EPOCH_DATETIME_THREE_YEARS  (356 * 24 * 3600 * 3)

			/* We want a variable time between the host_id timestamp and three years
			 * before. Let's compute the time (in seconds) from 0 to 3 years; then we'll
			 * subtract it from the host_id timestamp.
			 */
			time = nm_utils_host_id_get_timestamp_ns () / NM_UTILS_NSEC_PER_SEC;

			/* don't use too old timestamps. They cannot be expressed in DUID-LLT and
			 * would all be truncated to zero. */
			time = NM_MAX (time, NM_UTILS_EPOCH_DATETIME_200001010000 + EPOCH_DATETIME_THREE_YEARS);

			switch (arp_type) {
			case ARPHRD_ETHER:
				timestamp = unaligned_read_be32 (&digest.llt_eth.timestamp);
				time -= timestamp % EPOCH_DATETIME_THREE_YEARS;
				duid_out = nm_utils_generate_duid_llt (arp_type, digest.llt_eth.hwaddr, sizeof (digest.llt_eth.hwaddr), time);
				break;
			case ARPHRD_INFINIBAND:
				timestamp = unaligned_read_be32 (&digest.llt_infiniband.timestamp);
				time -= timestamp % EPOCH_DATETIME_THREE_YEARS;
				duid_out = nm_utils_generate_duid_llt (arp_type, digest.llt_infiniband.hwaddr, sizeof (digest.llt_infiniband.hwaddr), time);
				break;
			default:
				g_return_val_if_reached (NULL);
			}
		} else {
			nm_assert (nm_streq (duid, "stable-uuid"));
			duid_out = nm_utils_generate_duid_uuid (&digest.uuid);
		}

		goto out_good;
	}

	g_return_val_if_reached (NULL);

out_fail:
	nm_assert (!duid_out && duid_error);
	{
		NMUuid uuid;

		_LOGW (LOGD_IP6 | LOGD_DHCP6,
		       "ipv6.dhcp-duid: failure to generate %s DUID: %s. Fallback to random DUID-UUID.",
		       duid, duid_error);

		nm_utils_random_bytes (&uuid, sizeof (uuid));
		duid_out = nm_utils_generate_duid_uuid (&uuid);
	}

out_good:
	nm_assert (duid_out);
	_LOGD (LOGD_IP6 | LOGD_DHCP6,
	       "ipv6.dhcp-duid: generate %s DUID '%s' (%s)",
	       duid,
	       (logstr1 = nm_dhcp_utils_duid_to_string (duid_out)),
	       duid_enforce ? "enforcing" : "prefer lease");

	NM_SET_OUT (out_enforce, duid_enforce);
	return duid_out;
}

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

static gboolean
dhcp6_start_with_link_ready (NMDevice *self, NMConnection *connection)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMSettingIPConfig *s_ip6;
	gs_unref_bytes GBytes *hwaddr = NULL;
	gs_unref_bytes GBytes *duid = NULL;
	gboolean enforce_duid = FALSE;
	const NMPlatformLink *pllink;
	gs_free char *mud_url_free = NULL;
	GError *error = NULL;
	guint32 iaid;
	gboolean iaid_explicit;
	NMSettingConnection *s_con;
	const NMPlatformIP6Address *ll_addr = NULL;

	g_return_val_if_fail (connection, FALSE);

	s_ip6 = nm_connection_get_setting_ip6_config (connection);
	nm_assert (s_ip6);
	s_con = nm_connection_get_setting_connection (connection);
	nm_assert (s_con);

	if (priv->ext_ip6_config_captured) {
		ll_addr = nm_ip6_config_find_first_address (priv->ext_ip6_config_captured,
		                                              NM_PLATFORM_MATCH_WITH_ADDRTYPE_LINKLOCAL
		                                            | NM_PLATFORM_MATCH_WITH_ADDRSTATE_NORMAL);
	}

	if (!ll_addr) {
		_LOGW (LOGD_DHCP6, "can't start DHCPv6: no link-local address");
		return FALSE;
	}

	pllink = nm_platform_link_get (nm_device_get_platform (self), nm_device_get_ip_ifindex (self));
	if (pllink)
		hwaddr = nmp_link_address_get_as_bytes (&pllink->l_address);

	iaid = _prop_get_ipvx_dhcp_iaid (self, AF_INET6, connection, &iaid_explicit);
	duid = _prop_get_ipv6_dhcp_duid (self, connection, hwaddr, &enforce_duid);

	priv->dhcp_data_6.client = nm_dhcp_manager_start_ip6 (nm_dhcp_manager_get (),
	                                                      nm_device_get_multi_index (self),
	                                                      nm_device_get_ip_iface (self),
	                                                      nm_device_get_ip_ifindex (self),
	                                                      &ll_addr->address,
	                                                      nm_connection_get_uuid (connection),
	                                                      nm_device_get_route_table (self, AF_INET6),
	                                                      nm_device_get_route_metric (self, AF_INET6),
	                                                      nm_setting_ip_config_get_dhcp_send_hostname (s_ip6),
	                                                      nm_setting_ip_config_get_dhcp_hostname (s_ip6),
	                                                      get_dhcp_hostname_flags (self, AF_INET6),
	                                                      _prop_get_connection_mud_url (self, s_con, &mud_url_free),
	                                                      duid,
	                                                      enforce_duid,
	                                                      iaid,
	                                                      iaid_explicit,
	                                                      _prop_get_ipvx_dhcp_timeout (self, AF_INET6),
	                                                      priv->dhcp_anycast_address,
	                                                      (priv->dhcp6.mode == NM_NDISC_DHCP_LEVEL_OTHERCONF) ? TRUE : FALSE,
	                                                      nm_setting_ip6_config_get_ip6_privacy (NM_SETTING_IP6_CONFIG (s_ip6)),
	                                                      priv->dhcp6.needed_prefixes,
	                                                      &error);
	if (!priv->dhcp_data_6.client) {
		_LOGW (LOGD_DHCP6, "failure to start DHCPv6: %s", error->message);
		g_clear_error (&error);
		if (nm_device_sys_iface_state_is_external_or_assume (self))
			priv->dhcp_data_6.was_active = TRUE;
		return FALSE;
	}

	priv->dhcp_data_6.state_sigid = g_signal_connect (priv->dhcp_data_6.client,
	                                                  NM_DHCP_CLIENT_SIGNAL_STATE_CHANGED,
	                                                  G_CALLBACK (dhcp6_state_changed),
	                                                  self);
	priv->dhcp6.prefix_sigid = g_signal_connect (priv->dhcp_data_6.client,
	                                             NM_DHCP_CLIENT_SIGNAL_PREFIX_DELEGATED,
	                                             G_CALLBACK (dhcp6_prefix_delegated),
	                                             self);

	if (nm_device_sys_iface_state_is_external_or_assume (self))
		priv->dhcp_data_6.was_active = TRUE;

	return TRUE;
}

static gboolean
dhcp6_start (NMDevice *self, gboolean wait_for_ll)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMConnection *connection;

	nm_dbus_object_clear_and_unexport (&priv->dhcp_data_6.config);
	priv->dhcp_data_6.config = nm_dhcp_config_new (AF_INET6);

	nm_assert (!applied_config_get_current (&priv->dhcp6.ip6_config));
	applied_config_clear (&priv->dhcp6.ip6_config);
	nm_clear_g_free (&priv->dhcp6.event_id);

	connection = nm_device_get_applied_connection (self);
	g_return_val_if_fail (connection, FALSE);

	if (wait_for_ll) {
		/* ensure link local is ready... */
		if (!linklocal6_start (self)) {
			/* wait for the LL address to show up */
			return TRUE;
		}
		/* already have the LL address; kick off DHCP */
	}

	if (!dhcp6_start_with_link_ready (self, connection))
		return FALSE;

	return TRUE;
}

gboolean
nm_device_dhcp6_renew (NMDevice *self, gboolean release)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	g_return_val_if_fail (priv->dhcp_data_6.client != NULL, FALSE);

	_LOGI (LOGD_DHCP6, "DHCPv6 lease renewal requested");

	/* Terminate old DHCP instance and release the old lease */
	dhcp6_cleanup (self, CLEANUP_TYPE_DECONFIGURE, release);

	/* Start DHCP again on the interface */
	return dhcp6_start (self, FALSE);
}

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

/*
 * Called on the requesting interface when a subnet can't be obtained
 * from known prefixes for a newly active shared connection.
 */
void
nm_device_request_ip6_prefixes (NMDevice *self, int needed_prefixes)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	priv->dhcp6.needed_prefixes = needed_prefixes;

	if (priv->dhcp_data_6.client) {
		_LOGD (LOGD_IP6, "ipv6-pd: asking DHCPv6 for %d prefixes", needed_prefixes);
		nm_device_dhcp6_renew (self, FALSE);
	} else {
		_LOGI (LOGD_IP6, "ipv6-pd: device doesn't use DHCPv6, can't request prefixes");
	}
}

gboolean
nm_device_needs_ip6_subnet (NMDevice *self)
{
	return NM_DEVICE_GET_PRIVATE (self)->needs_ip6_subnet;
}

/*
 * Called on the ipv6.method=shared interface when a new subnet is allocated
 * or the prefix from which it is allocated is renewed.
 */
void
nm_device_use_ip6_subnet (NMDevice *self, const NMPlatformIP6Address *subnet)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMPlatformIP6Address address = *subnet;
	char sbuf[NM_UTILS_INET_ADDRSTRLEN];

	if (!applied_config_get_current (&priv->ac_ip6_config))
		applied_config_init_new (&priv->ac_ip6_config, self, AF_INET6);

	/* Assign a ::1 address in the subnet for us. */
	address.address.s6_addr32[3] |= htonl (1);
	applied_config_add_address (&priv->ac_ip6_config, NM_PLATFORM_IP_ADDRESS_CAST (&address));

	_LOGD (LOGD_IP6, "ipv6-pd: using %s address (preferred for %u seconds)",
	       _nm_utils_inet6_ntop (&address.address, sbuf),
	       subnet->preferred);

	/* This also updates the ndisc if there are actual changes. */
	if (!ip_config_merge_and_apply (self, AF_INET6, TRUE))
		_LOGW (LOGD_IP6, "ipv6-pd: failed applying IP6 config for connection sharing");
}

/*
 * Called whenever the policy picks a default IPv6 device.
 * The ipv6.method=shared devices just reuse its DNS configuration.
 */
void
nm_device_copy_ip6_dns_config (NMDevice *self, NMDevice *from_device)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMIP6Config *from_config = NULL;
	guint i, len;

	if (applied_config_get_current (&priv->ac_ip6_config)) {
		applied_config_reset_nameservers (&priv->ac_ip6_config);
		applied_config_reset_searches (&priv->ac_ip6_config);
	} else
		applied_config_init_new (&priv->ac_ip6_config, self, AF_INET6);

	if (from_device)
		from_config = nm_device_get_ip6_config (from_device);
	if (!from_config)
		return;

	len = nm_ip6_config_get_num_nameservers (from_config);
	for (i = 0; i < len; i++) {
		applied_config_add_nameserver (&priv->ac_ip6_config,
		                               (const NMIPAddr *) nm_ip6_config_get_nameserver (from_config, i));
	}

	len = nm_ip6_config_get_num_searches (from_config);
	for (i = 0; i < len; i++) {
		applied_config_add_search (&priv->ac_ip6_config,
		                           nm_ip6_config_get_search (from_config, i));
	}

	if (!ip_config_merge_and_apply (self, AF_INET6, TRUE))
		_LOGW (LOGD_IP6, "ipv6-pd: failed applying DNS config for connection sharing");
}

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

static void
linklocal6_failed (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	nm_clear_g_source (&priv->linklocal6_timeout_id);
	nm_device_activate_schedule_ip_config_timeout (self, AF_INET6);
}

static gboolean
linklocal6_timeout_cb (gpointer user_data)
{
	NMDevice *self = user_data;

	_LOGD (LOGD_DEVICE, "linklocal6: waiting for link-local addresses failed due to timeout");
	linklocal6_failed (self);
	return G_SOURCE_REMOVE;
}

static void
linklocal6_check_complete (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMConnection *connection;
	const char *method;

	if (!priv->linklocal6_timeout_id) {
		/* we are not waiting for linklocal to complete. Nothing to do. */
		return;
	}

	if (   !priv->ext_ip6_config_captured
	    || !nm_ip6_config_find_first_address (priv->ext_ip6_config_captured,
	                                            NM_PLATFORM_MATCH_WITH_ADDRTYPE_LINKLOCAL
	                                          | NM_PLATFORM_MATCH_WITH_ADDRSTATE_NORMAL)) {
		/* we don't have a non-tentative link local address yet. Wait longer. */
		return;
	}

	nm_clear_g_source (&priv->linklocal6_timeout_id);

	connection = nm_device_get_applied_connection (self);
	g_assert (connection);

	method = nm_device_get_effective_ip_config_method (self, AF_INET6);

	_LOGD (LOGD_DEVICE, "linklocal6: waiting for link-local addresses successful, continue with method %s", method);

	if (NM_IN_STRSET (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO,
	                          NM_SETTING_IP6_CONFIG_METHOD_SHARED))
		addrconf6_start_with_link_ready (self);
	else if (nm_streq (method, NM_SETTING_IP6_CONFIG_METHOD_DHCP)) {
		if (!dhcp6_start_with_link_ready (self, connection)) {
			/* Time out IPv6 instead of failing the entire activation */
			nm_device_activate_schedule_ip_config_timeout (self, AF_INET6);
		}
	} else if (nm_streq (method, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL))
		nm_device_activate_schedule_ip_config_result (self, AF_INET6, NULL);
	else
		g_return_if_fail (FALSE);
}

static void
check_and_add_ipv6ll_addr (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	struct in6_addr lladdr;
	NMConnection *connection;
	NMSettingIP6Config *s_ip6 = NULL;
	GError *error = NULL;
	const char *addr_type;
	char sbuf[NM_UTILS_INET_ADDRSTRLEN];

	if (!priv->ipv6ll_handle)
		return;

	if (   priv->ext_ip6_config_captured
	    && nm_ip6_config_find_first_address (priv->ext_ip6_config_captured,
	                                           NM_PLATFORM_MATCH_WITH_ADDRTYPE_LINKLOCAL
	                                         | NM_PLATFORM_MATCH_WITH_ADDRSTATE_NORMAL
	                                         | NM_PLATFORM_MATCH_WITH_ADDRSTATE_TENTATIVE)) {
		/* Already have an LL address, nothing to do */
		return;
	}

	priv->ipv6ll_has = FALSE;
	memset (&priv->ipv6ll_addr, 0, sizeof (priv->ipv6ll_addr));

	memset (&lladdr, 0, sizeof (lladdr));
	lladdr.s6_addr16[0] = htons (0xfe80);

	connection = nm_device_get_applied_connection (self);
	if (connection)
		s_ip6 = NM_SETTING_IP6_CONFIG (nm_connection_get_setting_ip6_config (connection));

	if (s_ip6 && nm_setting_ip6_config_get_addr_gen_mode (s_ip6) == NM_SETTING_IP6_CONFIG_ADDR_GEN_MODE_STABLE_PRIVACY) {
		NMUtilsStableType stable_type;
		const char *stable_id;

		stable_id = _get_stable_id (self, connection, &stable_type);
		if (!nm_utils_ipv6_addr_set_stable_privacy (stable_type,
		                                            &lladdr,
		                                            nm_device_get_iface (self),
		                                            stable_id,
		                                            priv->linklocal6_dad_counter++,
		                                            &error)) {
			_LOGW (LOGD_IP6, "linklocal6: failed to generate an address: %s", error->message);
			g_clear_error (&error);
			linklocal6_failed (self);
			return;
		}
		addr_type = "stable-privacy";
	} else {
		NMUtilsIPv6IfaceId iid;

		if (priv->linklocal6_timeout_id) {
			/* We already started and attempt to add a LL address. For the EUI-64
			 * mode we can't pick a new one, we'll just fail. */
			_LOGW (LOGD_IP6, "linklocal6: DAD failed for an EUI-64 address");
			linklocal6_failed (self);
			return;
		}

		if (!nm_device_get_ip_iface_identifier (self, &iid, TRUE)) {
			_LOGW (LOGD_IP6, "linklocal6: failed to get interface identifier; IPv6 cannot continue");
			return;
		}
		nm_utils_ipv6_addr_set_interface_identifier (&lladdr, iid);
		addr_type = "EUI-64";
	}

	_LOGD (LOGD_IP6, "linklocal6: generated %s IPv6LL address %s",
	       addr_type, _nm_utils_inet6_ntop (&lladdr, sbuf));
	priv->ipv6ll_has = TRUE;
	priv->ipv6ll_addr = lladdr;
	ip_config_merge_and_apply (self, AF_INET6, TRUE);
}

static gboolean
linklocal6_start (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	nm_clear_g_source (&priv->linklocal6_timeout_id);

	if (   priv->ext_ip6_config_captured
	    && nm_ip6_config_find_first_address (priv->ext_ip6_config_captured,
	                                           NM_PLATFORM_MATCH_WITH_ADDRTYPE_LINKLOCAL
	                                         | NM_PLATFORM_MATCH_WITH_ADDRSTATE_NORMAL))
		return TRUE;

	_LOGD (LOGD_DEVICE, "linklocal6: starting IPv6 with method '%s', but the device has no link-local addresses configured. Wait.",
	       nm_device_get_effective_ip_config_method (self, AF_INET6));

	check_and_add_ipv6ll_addr (self);

	/* Depending on the network and what the 'dad_transmits' and 'retrans_time_ms'
	 * sysctl values are, DAD for the IPv6LL address may take quite a while.
	 * FIXME: use dad/retrans sysctl values if they are higher than a minimum time.
	 * (rh #1101809)
	 */
	priv->linklocal6_timeout_id = g_timeout_add_seconds (15, linklocal6_timeout_cb, self);
	return FALSE;
}

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

gint64
nm_device_get_configured_mtu_from_connection_default (NMDevice *self,
                                                      const char *property_name,
                                                      guint32 max_mtu)
{
	return nm_config_data_get_connection_default_int64 (NM_CONFIG_GET_DATA,
	                                                    property_name,
	                                                    self,
	                                                    0, max_mtu, -1);
}

guint32
nm_device_get_configured_mtu_from_connection (NMDevice *self,
                                              GType setting_type,
                                              NMDeviceMtuSource *out_source)
{
	const char *global_property_name;
	NMConnection *connection;
	NMSetting *setting;
	gint64 mtu_default;
	guint32 mtu = 0;
	guint32 max_mtu = G_MAXUINT32;

	nm_assert (NM_IS_DEVICE (self));
	nm_assert (out_source);

	connection = nm_device_get_applied_connection (self);
	if (!connection)
		g_return_val_if_reached (0);

	setting = nm_connection_get_setting (connection, setting_type);

	if (setting_type == NM_TYPE_SETTING_WIRED) {
		if (setting)
			mtu = nm_setting_wired_get_mtu (NM_SETTING_WIRED (setting));
		global_property_name = NM_CON_DEFAULT ("ethernet.mtu");
	} else if (setting_type == NM_TYPE_SETTING_WIRELESS) {
		if (setting)
			mtu = nm_setting_wireless_get_mtu (NM_SETTING_WIRELESS (setting));
		global_property_name = NM_CON_DEFAULT ("wifi.mtu");
	} else if (setting_type == NM_TYPE_SETTING_INFINIBAND) {
		if (setting)
			mtu = nm_setting_infiniband_get_mtu (NM_SETTING_INFINIBAND (setting));
		global_property_name = NM_CON_DEFAULT ("infiniband.mtu");
		max_mtu = NM_INFINIBAND_MAX_MTU;
	} else if (setting_type == NM_TYPE_SETTING_IP_TUNNEL) {
		if (setting)
			mtu = nm_setting_ip_tunnel_get_mtu (NM_SETTING_IP_TUNNEL (setting));
		global_property_name = NM_CON_DEFAULT ("ip-tunnel.mtu");
	} else if (setting_type == NM_TYPE_SETTING_WIREGUARD) {
		if (setting)
			mtu = nm_setting_wireguard_get_mtu (NM_SETTING_WIREGUARD (setting));
		global_property_name = NM_CON_DEFAULT ("wireguard.mtu");
	} else
		g_return_val_if_reached (0);

	if (mtu) {
		*out_source = NM_DEVICE_MTU_SOURCE_CONNECTION;
		return mtu;
	}

	mtu_default = nm_device_get_configured_mtu_from_connection_default (self, global_property_name, max_mtu);
	if (mtu_default >= 0) {
		*out_source = NM_DEVICE_MTU_SOURCE_CONNECTION;
		return (guint32) mtu_default;
	}

	*out_source = NM_DEVICE_MTU_SOURCE_NONE;
	return 0;
}

guint32
nm_device_get_configured_mtu_for_wired (NMDevice *self,
                                        NMDeviceMtuSource *out_source,
                                        gboolean *out_force)
{
	return nm_device_get_configured_mtu_from_connection (self,
	                                                     NM_TYPE_SETTING_WIRED,
	                                                     out_source);
}

guint32
nm_device_get_configured_mtu_wired_parent (NMDevice *self,
                                           NMDeviceMtuSource *out_source,
                                           gboolean *out_force)
{
	guint32 mtu = 0;
	guint32 parent_mtu = 0;
	int ifindex;

	ifindex = nm_device_parent_get_ifindex (self);
	if (ifindex > 0) {
		parent_mtu = nm_platform_link_get_mtu (nm_device_get_platform (self), ifindex);
		if (parent_mtu >= NM_DEVICE_GET_CLASS (self)->mtu_parent_delta)
			parent_mtu -= NM_DEVICE_GET_CLASS (self)->mtu_parent_delta;
		else
			parent_mtu = 0;
	}

	mtu = nm_device_get_configured_mtu_for_wired (self, out_source, NULL);

	if (parent_mtu && mtu > parent_mtu) {
		/* Trying to set a MTU that is out of range from configuration:
		 * fall back to the parent MTU and set force flag so that it
		 * overrides an MTU with higher priority already configured.
		 */
		 *out_source = NM_DEVICE_MTU_SOURCE_PARENT;
		 *out_force = TRUE;
		 return parent_mtu;
	}

	if (*out_source != NM_DEVICE_MTU_SOURCE_NONE) {
		nm_assert (mtu > 0);
		return mtu;
	}

	/* Inherit the MTU from parent device, if any */
	if (parent_mtu) {
		mtu = parent_mtu;
		*out_source = NM_DEVICE_MTU_SOURCE_PARENT;
	}

	return mtu;
}

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

static void
_set_mtu (NMDevice *self, guint32 mtu)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->mtu == mtu)
		return;

	priv->mtu = mtu;
	_notify (self, PROP_MTU);

	if (priv->master) {
		/* changing the MTU of a slave, might require the master to reset
		 * its MTU. Note that the master usually cannot set a MTU larger
		 * then the slave's. Hence, when the slave increases the MTU,
		 * master might want to retry setting the MTU. */
		nm_device_commit_mtu (priv->master);
	}
}

static gboolean
set_platform_mtu (NMDevice *self, guint32 mtu)
{
	int r;

	r = nm_platform_link_set_mtu (nm_device_get_platform (self),
	                              nm_device_get_ip_ifindex (self),
	                              mtu);
	return (r != -NME_PL_CANT_SET_MTU);
}

static void
_commit_mtu (NMDevice *self, const NMIP4Config *config)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMDeviceMtuSource source = NM_DEVICE_MTU_SOURCE_NONE;
	guint32 ip6_mtu, ip6_mtu_orig;
	guint32 mtu_desired, mtu_desired_orig;
	guint32 mtu_plat;
	struct {
		gboolean initialized;
		guint32 value;
	} ip6_mtu_sysctl = { 0, };
	int ifindex;
	char sbuf[64], sbuf1[64], sbuf2[64];
	gboolean success = TRUE;

	ifindex = nm_device_get_ip_ifindex (self);
	if (ifindex <= 0)
		return;

	if (   !nm_device_get_applied_connection (self)
	    || nm_device_sys_iface_state_is_external_or_assume (self)) {
		/* we don't tamper with the MTU of disconnected and
		 * external/assumed devices. */
		return;
	}

	{
		guint32 mtu = 0;
		gboolean force = FALSE;

		/* We take the MTU from various sources: (in order of increasing
		 * priority) parent link, IP configuration (which contains the
		 * MTU from DHCP/PPP), connection profile.
		 *
		 * We could just compare it with the platform MTU and apply it
		 * when different, but this would revert at random times manual
		 * changes done by the user with the MTU from the connection.
		 *
		 * Instead, we remember the source of the currently configured
		 * MTU and apply the new one only when the new source has a
		 * higher priority, so that we don't set a MTU from same source
		 * multiple times. An exception to this is for the PARENT
		 * source, since we need to keep tracking the parent MTU when it
		 * changes.
		 *
		 * The subclass can set the @force argument to TRUE to signal that the
		 * returned MTU should be applied even if it has a lower priority. This
		 * is useful when the value from a lower source should
		 * preempt the one from higher ones.
		 */

		if (NM_DEVICE_GET_CLASS (self)->get_configured_mtu)
			mtu = NM_DEVICE_GET_CLASS (self)->get_configured_mtu (self, &source, &force);

		if (   config
		    && !force
		    && source < NM_DEVICE_MTU_SOURCE_IP_CONFIG
		    && nm_ip4_config_get_mtu (config)) {
			mtu = nm_ip4_config_get_mtu (config);
			source = NM_DEVICE_MTU_SOURCE_IP_CONFIG;
		}

		if (mtu != 0) {
			_LOGT (LOGD_DEVICE,
			       "mtu: value %u from source '%s' (%u), current source '%s' (%u)%s",
			       (guint) mtu,
			       mtu_source_to_str (source), (guint) source,
			       mtu_source_to_str (priv->mtu_source), (guint) priv->mtu_source,
			       force ? " (forced)" : "");
		}

		if (   mtu != 0
		    && (   force
		        || source > priv->mtu_source
		        || (priv->mtu_source == NM_DEVICE_MTU_SOURCE_PARENT && source == priv->mtu_source)))
			mtu_desired = mtu;
		else {
			mtu_desired = 0;
			source = NM_DEVICE_MTU_SOURCE_NONE;
		}
	}

	if (mtu_desired && mtu_desired < 1280) {
		NMSettingIPConfig *s_ip6;

		s_ip6 = nm_device_get_applied_setting (self, NM_TYPE_SETTING_IP6_CONFIG);
		if (   s_ip6
		    && !NM_IN_STRSET (nm_setting_ip_config_get_method (s_ip6),
		                      NM_SETTING_IP6_CONFIG_METHOD_IGNORE,
		                      NM_SETTING_IP6_CONFIG_METHOD_DISABLED)) {
			/* the interface has IPv6 enabled. The MTU with IPv6 cannot be smaller
			 * then 1280.
			 *
			 * For slave-devices (that don't have @s_ip6 we) don't do this fixup because
			 * it's anyway an unsolved problem when the slave configures a conflicting
			 * MTU. */
			mtu_desired = 1280;
		}
	}

	ip6_mtu = priv->ip6_mtu;
	if (!ip6_mtu && priv->mtu_source == NM_DEVICE_MTU_SOURCE_NONE) {
		/* initially, if the IPv6 MTU is not specified, grow it as large as the
		 * link MTU @mtu_desired. Only exception is, if @mtu_desired is so small
		 * to disable IPv6. */
		if (mtu_desired >= 1280)
			ip6_mtu = mtu_desired;
	}

	if (!ip6_mtu && !mtu_desired)
		return;

	mtu_desired_orig = mtu_desired;
	ip6_mtu_orig = ip6_mtu;

	mtu_plat = nm_platform_link_get_mtu (nm_device_get_platform (self), ifindex);

	if (ip6_mtu) {
		ip6_mtu = NM_MAX (1280, ip6_mtu);

		if (!mtu_desired)
			mtu_desired = mtu_plat;

		if (mtu_desired) {
			mtu_desired = NM_MAX (1280, mtu_desired);

			if (mtu_desired < ip6_mtu)
				ip6_mtu = mtu_desired;
		}
	}

	_LOGT (LOGD_DEVICE, "mtu: device-mtu: %u%s, ipv6-mtu: %u%s, ifindex: %d",
	       (guint) mtu_desired,
	       mtu_desired == mtu_desired_orig ? "" : nm_sprintf_buf (sbuf1, " (was %u)", (guint) mtu_desired_orig),
	       (guint) ip6_mtu,
	       ip6_mtu == ip6_mtu_orig ? "" : nm_sprintf_buf (sbuf2, " (was %u)", (guint) ip6_mtu_orig),
	       ifindex);

#define _IP6_MTU_SYS() \
	({ \
		if (!ip6_mtu_sysctl.initialized) { \
			ip6_mtu_sysctl.value = nm_device_sysctl_ip_conf_get_int_checked (self, AF_INET6, "mtu", 10, 0, G_MAXUINT32, 0); \
			ip6_mtu_sysctl.initialized = TRUE; \
		} \
		ip6_mtu_sysctl.value; \
	})
	if (   (mtu_desired && mtu_desired != mtu_plat)
	    || (ip6_mtu && ip6_mtu != _IP6_MTU_SYS ())) {
		gboolean anticipated_failure = FALSE;

		if (!priv->mtu_initial && !priv->ip6_mtu_initial) {
			/* before touching any of the MTU parameters, record the
			 * original setting to restore on deactivation. */
			priv->mtu_initial = mtu_plat;
			priv->ip6_mtu_initial = _IP6_MTU_SYS ();
		}

		if (mtu_desired && mtu_desired != mtu_plat) {
			if (!NM_DEVICE_GET_CLASS (self)->set_platform_mtu (self, mtu_desired)) {
				anticipated_failure = TRUE;
				success = FALSE;
				_LOGW (LOGD_DEVICE, "mtu: failure to set MTU. %s",
				       NM_IS_DEVICE_VLAN (self)
				         ? "Is the parent's MTU size large enough?"
				         : (!c_list_is_empty (&priv->slaves)
				              ? "Are the MTU sizes of the slaves large enough?"
				              : "Did you configure the MTU correctly?"));
			}
			priv->carrier_wait_until_ms = nm_utils_get_monotonic_timestamp_msec () + CARRIER_WAIT_TIME_AFTER_MTU_MS;
		}

		if (ip6_mtu && ip6_mtu != _IP6_MTU_SYS ()) {
			if (!nm_device_sysctl_ip_conf_set (self, AF_INET6, "mtu",
			                                   nm_sprintf_buf (sbuf, "%u", (unsigned) ip6_mtu))) {
				int errsv = errno;
				NMLogLevel level = LOGL_WARN;
				const char *msg = NULL;

				success = FALSE;

				if (anticipated_failure && errsv == EINVAL) {
					level = LOGL_DEBUG;
					msg = "Is the underlying MTU value successfully set?";
				} else if (!g_file_test ("/proc/sys/net/ipv6", G_FILE_TEST_IS_DIR)) {
					level = LOGL_DEBUG;
					msg = "IPv6 is disabled";
					success = TRUE;
				}

				_NMLOG (level,
				        LOGD_DEVICE,
				        "mtu: failure to set IPv6 MTU%s%s",
				        msg ? ": " : "",
				        msg ?: "");
			}
			priv->carrier_wait_until_ms = nm_utils_get_monotonic_timestamp_msec () + CARRIER_WAIT_TIME_AFTER_MTU_MS;
		}
	}

	if (success && source != NM_DEVICE_MTU_SOURCE_NONE)
		priv->mtu_source = source;

#undef _IP6_MTU_SYS
}

void
nm_device_commit_mtu (NMDevice *self)
{
	NMDeviceState state;

	g_return_if_fail (NM_IS_DEVICE (self));

	state = nm_device_get_state (self);
	if (   state >= NM_DEVICE_STATE_CONFIG
	    && state < NM_DEVICE_STATE_DEACTIVATING) {
		_LOGT (LOGD_DEVICE, "mtu: commit-mtu...");
		_commit_mtu (self, NM_DEVICE_GET_PRIVATE (self)->ip_config_4);
	} else
		_LOGT (LOGD_DEVICE, "mtu: commit-mtu... skip due to state %s", nm_device_state_to_str (state));
}

static void
ndisc_config_changed (NMNDisc *ndisc, const NMNDiscData *rdata, guint changed_int, NMDevice *self)
{
	NMNDiscConfigMap changed = changed_int;
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	guint i;

	g_return_if_fail (priv->act_request.obj);

	if (!applied_config_get_current (&priv->ac_ip6_config))
		applied_config_init_new (&priv->ac_ip6_config, self, AF_INET6);

	if (changed & NM_NDISC_CONFIG_ADDRESSES) {
		guint8 plen;
		guint32 ifa_flags;

		/* Check, whether kernel is recent enough to help user space handling RA.
		 * If it's not supported, we have no ipv6-privacy and must add autoconf
		 * addresses as /128. The reason for the /128 is to prevent the kernel
		 * from adding a prefix route for this address. */
		ifa_flags = 0;
		if (nm_platform_kernel_support_get (NM_PLATFORM_KERNEL_SUPPORT_TYPE_EXTENDED_IFA_FLAGS)) {
			ifa_flags |= IFA_F_NOPREFIXROUTE;
			if (NM_IN_SET (priv->ndisc_use_tempaddr, NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR,
			                                         NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_PUBLIC_ADDR))
				ifa_flags |= IFA_F_MANAGETEMPADDR;
			plen = 64;
		} else
			plen = 128;

		nm_ip6_config_reset_addresses_ndisc ((NMIP6Config *) priv->ac_ip6_config.orig,
		                                     rdata->addresses,
		                                     rdata->addresses_n,
		                                     plen,
		                                     ifa_flags);
		if (priv->ac_ip6_config.current) {
			nm_ip6_config_reset_addresses_ndisc ((NMIP6Config *) priv->ac_ip6_config.current,
			                                     rdata->addresses,
			                                     rdata->addresses_n,
			                                     plen,
			                                     ifa_flags);
		}
	}

	if (NM_FLAGS_ANY (changed,   NM_NDISC_CONFIG_ROUTES
	                           | NM_NDISC_CONFIG_GATEWAYS)) {
		nm_ip6_config_reset_routes_ndisc ((NMIP6Config *) priv->ac_ip6_config.orig,
		                                  rdata->gateways,
		                                  rdata->gateways_n,
		                                  rdata->routes,
		                                  rdata->routes_n,
		                                  nm_device_get_route_table (self, AF_INET6),
		                                  nm_device_get_route_metric (self, AF_INET6),
		                                  nm_platform_kernel_support_get (NM_PLATFORM_KERNEL_SUPPORT_TYPE_RTA_PREF));
		if (priv->ac_ip6_config.current) {
			nm_ip6_config_reset_routes_ndisc ((NMIP6Config *) priv->ac_ip6_config.current,
			                                  rdata->gateways,
			                                  rdata->gateways_n,
			                                  rdata->routes,
			                                  rdata->routes_n,
			                                  nm_device_get_route_table (self, AF_INET6),
			                                  nm_device_get_route_metric (self, AF_INET6),
			                                  nm_platform_kernel_support_get (NM_PLATFORM_KERNEL_SUPPORT_TYPE_RTA_PREF));
		}

	}

	if (changed & NM_NDISC_CONFIG_DNS_SERVERS) {
		/* Rebuild DNS server list from neighbor discovery cache. */
		applied_config_reset_nameservers (&priv->ac_ip6_config);

		for (i = 0; i < rdata->dns_servers_n; i++)
			applied_config_add_nameserver (&priv->ac_ip6_config, (const NMIPAddr *) &rdata->dns_servers[i].address);
	}

	if (changed & NM_NDISC_CONFIG_DNS_DOMAINS) {
		/* Rebuild domain list from neighbor discovery cache. */
		applied_config_reset_searches (&priv->ac_ip6_config);

		for (i = 0; i < rdata->dns_domains_n; i++)
			applied_config_add_search (&priv->ac_ip6_config, rdata->dns_domains[i].domain);
	}

	if (changed & NM_NDISC_CONFIG_DHCP_LEVEL) {
		dhcp6_cleanup (self, CLEANUP_TYPE_DECONFIGURE, TRUE);

		priv->dhcp6.mode = rdata->dhcp_level;
		if (priv->dhcp6.mode != NM_NDISC_DHCP_LEVEL_NONE) {
			_LOGD (LOGD_DEVICE | LOGD_DHCP6,
			       "Activation: Stage 3 of 5 (IP Configure Start) starting DHCPv6"
			       " as requested by IPv6 router...");
			if (!dhcp6_start (self, FALSE)) {
				if (priv->dhcp6.mode == NM_NDISC_DHCP_LEVEL_MANAGED) {
					nm_device_state_changed (self, NM_DEVICE_STATE_FAILED,
					                         NM_DEVICE_STATE_REASON_DHCP_START_FAILED);
					return;
				}
			}
		}
	}

	if (changed & NM_NDISC_CONFIG_HOP_LIMIT)
		nm_platform_sysctl_ip_conf_set_ipv6_hop_limit_safe (nm_device_get_platform (self), nm_device_get_ip_iface (self), rdata->hop_limit);

	if (changed & NM_NDISC_CONFIG_REACHABLE_TIME) {
		nm_platform_sysctl_ip_neigh_set_ipv6_reachable_time (nm_device_get_platform (self),
		                                                     nm_device_get_ip_iface (self),
		                                                     rdata->reachable_time_ms);
	}

	if (changed & NM_NDISC_CONFIG_RETRANS_TIMER) {
		nm_platform_sysctl_ip_neigh_set_ipv6_retrans_time (nm_device_get_platform (self),
		                                                   nm_device_get_ip_iface (self),
		                                                   rdata->retrans_timer_ms);
	}

	if (changed & NM_NDISC_CONFIG_MTU) {
		if (priv->ip6_mtu != rdata->mtu) {
			_LOGD (LOGD_DEVICE, "mtu: set IPv6 MTU to %u", (guint) rdata->mtu);
			priv->ip6_mtu = rdata->mtu;
		}
	}

	nm_device_activate_schedule_ip_config_result (self, AF_INET6, NULL);
}

static void
ndisc_ra_timeout (NMNDisc *ndisc, NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	/* We don't want to stop listening for router advertisements completely,
	 * but instead let device activation continue activating.  If an RA
	 * shows up later, we'll use it as long as the device is not disconnected.
	 */

	_LOGD (LOGD_IP6, "timed out waiting for IPv6 router advertisement");
	if (priv->ip_state_6 == NM_DEVICE_IP_STATE_CONF) {
		/* If RA is our only source of addressing information and we don't
		 * ever receive one, then time out IPv6.  But if there is other
		 * IPv6 configuration, like manual IPv6 addresses or external IPv6
		 * config, consider that sufficient for IPv6 success.
		 *
		 * FIXME: it doesn't seem correct to determine this based on which
		 *        addresses we find inside priv->ip_config_6.
		 */
		if (   priv->ip_config_6
		    && nm_ip6_config_find_first_address (priv->ip_config_6,
		                                           NM_PLATFORM_MATCH_WITH_ADDRTYPE_NORMAL
		                                         | NM_PLATFORM_MATCH_WITH_ADDRSTATE__ANY))
			nm_device_activate_schedule_ip_config_result (self, AF_INET6, NULL);
		else
			nm_device_activate_schedule_ip_config_timeout (self, AF_INET6);
	}
}

static void
addrconf6_start_with_link_ready (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMUtilsIPv6IfaceId iid;

	g_assert (priv->ndisc);

	if (nm_device_get_ip_iface_identifier (self, &iid, FALSE)) {
		_LOGD (LOGD_IP6, "addrconf6: using the device EUI-64 identifier");
		nm_ndisc_set_iid (priv->ndisc, iid);
	} else {
		/* Don't abort the addrconf at this point -- if ndisc needs the iid
		 * it will notice this itself. */
		_LOGI (LOGD_IP6, "addrconf6: no interface identifier; IPv6 address creation may fail");
	}

	/* Apply any manual configuration before starting RA */
	if (!ip_config_merge_and_apply (self, AF_INET6, TRUE))
		_LOGW (LOGD_IP6, "failed to apply manual IPv6 configuration");

	if (nm_ndisc_get_node_type (priv->ndisc) == NM_NDISC_NODE_TYPE_ROUTER) {
		nm_device_sysctl_ip_conf_set (self, AF_INET6, "forwarding", "1");
		nm_device_activate_schedule_ip_config_result (self, AF_INET6, NULL);
		priv->needs_ip6_subnet = TRUE;
		g_signal_emit (self, signals[IP6_SUBNET_NEEDED], 0);
	}

	priv->ndisc_changed_id = g_signal_connect (priv->ndisc,
	                                           NM_NDISC_CONFIG_RECEIVED,
	                                           G_CALLBACK (ndisc_config_changed),
	                                           self);
	priv->ndisc_timeout_id = g_signal_connect (priv->ndisc,
	                                           NM_NDISC_RA_TIMEOUT_SIGNAL,
	                                           G_CALLBACK (ndisc_ra_timeout),
	                                           self);

	ndisc_set_router_config (priv->ndisc, self);
	nm_ndisc_start (priv->ndisc);
	priv->ndisc_started = TRUE;
	return;
}

static NMNDiscNodeType
ndisc_node_type (NMDevice *self)
{
	if (nm_streq (nm_device_get_effective_ip_config_method (self, AF_INET6),
	              NM_SETTING_IP4_CONFIG_METHOD_SHARED))
		return NM_NDISC_NODE_TYPE_ROUTER;
	return NM_NDISC_NODE_TYPE_HOST;
}

static gint32
get_ra_timeout (NMDevice *self)
{
	NMConnection *connection;
	gint32 timeout;

	G_STATIC_ASSERT_EXPR (NM_RA_TIMEOUT_DEFAULT == 0);
	G_STATIC_ASSERT_EXPR (NM_RA_TIMEOUT_INFINITY == G_MAXINT32);

	connection = nm_device_get_applied_connection (self);

	timeout = nm_setting_ip6_config_get_ra_timeout (NM_SETTING_IP6_CONFIG (nm_connection_get_setting_ip6_config (connection)));
	nm_assert (timeout >= 0);
	if (timeout)
		return timeout;

	return nm_config_data_get_connection_default_int64 (NM_CONFIG_GET_DATA,
	                                                    NM_CON_DEFAULT ("ipv6.ra-timeout"),
	                                                    self,
	                                                    0, G_MAXINT32, 0);
}

static gboolean
addrconf6_start (NMDevice *self, NMSettingIP6ConfigPrivacy use_tempaddr)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMConnection *connection;
	NMSettingIP6Config *s_ip6 = NULL;
	GError *error = NULL;
	NMUtilsStableType stable_type;
	const char *stable_id;

	connection = nm_device_get_applied_connection (self);
	g_assert (connection);

	nm_assert (!applied_config_get_current (&priv->ac_ip6_config));
	applied_config_clear (&priv->ac_ip6_config);

	nm_clear_pointer (&priv->rt6_temporary_not_available, g_hash_table_unref);
	nm_clear_g_source (&priv->rt6_temporary_not_available_id);

	s_ip6 = NM_SETTING_IP6_CONFIG (nm_connection_get_setting_ip6_config (connection));
	g_assert (s_ip6);

	stable_id = _get_stable_id (self, connection, &stable_type);
	priv->ndisc = nm_lndp_ndisc_new (nm_device_get_platform (self),
	                                 nm_device_get_ip_ifindex (self),
	                                 nm_device_get_ip_iface (self),
	                                 stable_type,
	                                 stable_id,
	                                 nm_setting_ip6_config_get_addr_gen_mode (s_ip6),
	                                 ndisc_node_type (self),
	                                 get_ra_timeout (self),
	                                 &error);
	if (!priv->ndisc) {
		_LOGE (LOGD_IP6, "addrconf6: failed to start neighbor discovery: %s", error->message);
		g_error_free (error);
		return FALSE;
	}

	priv->ndisc_use_tempaddr = use_tempaddr;

	if (   NM_IN_SET (use_tempaddr, NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR, NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_PUBLIC_ADDR)
	    && !nm_platform_kernel_support_get (NM_PLATFORM_KERNEL_SUPPORT_TYPE_EXTENDED_IFA_FLAGS)) {
		_LOGW (LOGD_IP6, "The kernel does not support extended IFA_FLAGS needed by NM for "
		                 "IPv6 private addresses. This feature is not available");
	}

	/* ensure link local is ready... */
	if (!linklocal6_start (self)) {
		/* wait for the LL address to show up */
		return TRUE;
	}

	/* already have the LL address; kick off neighbor discovery */
	addrconf6_start_with_link_ready (self);
	return TRUE;
}

static void
addrconf6_cleanup (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	priv->ndisc_started = FALSE;
	nm_clear_g_signal_handler (priv->ndisc, &priv->ndisc_changed_id);
	nm_clear_g_signal_handler (priv->ndisc, &priv->ndisc_timeout_id);

	applied_config_clear (&priv->ac_ip6_config);
	nm_clear_pointer (&priv->rt6_temporary_not_available, g_hash_table_unref);
	nm_clear_g_source (&priv->rt6_temporary_not_available_id);
	g_clear_object (&priv->ndisc);
}

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

static void
save_ip6_properties (NMDevice *self)
{
	static const char *const ip6_properties_to_save[] = {
		"accept_ra",
		"forwarding",
		"disable_ipv6",
		"hop_limit",
		"use_tempaddr",
	};
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMPlatform *platform = nm_device_get_platform (self);
	const char *ifname;
	char *value;
	int i;

	g_hash_table_remove_all (priv->ip6_saved_properties);

	ifname = nm_device_get_ip_iface_from_platform (self);
	if (!ifname)
		return;

	for (i = 0; i < G_N_ELEMENTS (ip6_properties_to_save); i++) {
		value = nm_platform_sysctl_ip_conf_get (platform,
		                                        AF_INET6,
		                                        ifname,
		                                        ip6_properties_to_save[i]);
		if (value) {
			g_hash_table_insert (priv->ip6_saved_properties,
			                     (char *) ip6_properties_to_save[i],
			                     value);
		}
	}
}

static void
restore_ip6_properties (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	GHashTableIter iter;
	gpointer key, value;

	g_hash_table_iter_init (&iter, priv->ip6_saved_properties);
	while (g_hash_table_iter_next (&iter, &key, &value)) {
		/* Don't touch "disable_ipv6" if we're doing userland IPv6LL */
		if (   priv->ipv6ll_handle
		    && nm_streq (key, "disable_ipv6"))
			continue;
		nm_device_sysctl_ip_conf_set (self, AF_INET6, key, value);
	}
}

static void
set_disable_ipv6 (NMDevice *self, const char *value)
{
	/* We only touch disable_ipv6 when NM is not managing the IPv6LL address */
	if (!NM_DEVICE_GET_PRIVATE (self)->ipv6ll_handle)
		nm_device_sysctl_ip_conf_set (self, AF_INET6, "disable_ipv6", value);
}

static void
set_nm_ipv6ll (NMDevice *self, gboolean enable)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	int ifindex = nm_device_get_ip_ifindex (self);

	if (!nm_platform_kernel_support_get (NM_PLATFORM_KERNEL_SUPPORT_TYPE_USER_IPV6LL))
		return;

	priv->ipv6ll_handle = enable;
	if (ifindex > 0) {
		const char *detail = enable ? "enable" : "disable";
		int r;

		_LOGD (LOGD_IP6, "will %s userland IPv6LL", detail);
		r = nm_platform_link_set_user_ipv6ll_enabled (nm_device_get_platform (self), ifindex, enable);
		if (r < 0) {
			_NMLOG (  NM_IN_SET (r, -NME_PL_NOT_FOUND,
			                        -NME_PL_OPNOTSUPP)
			        ? LOGL_DEBUG
			        : LOGL_WARN,
			        LOGD_IP6,
			        "failed to %s userspace IPv6LL address handling (%s)",
			        detail,
			        nm_strerror (r));
		}

		if (enable) {
			gs_free char *value = NULL;

			/* Bounce IPv6 to ensure the kernel stops IPv6LL address generation */
			value = nm_device_sysctl_ip_conf_get (self,
			                                      AF_INET6,
			                                      "disable_ipv6");
			if (nm_streq0 (value, "0"))
				nm_device_sysctl_ip_conf_set (self, AF_INET6, "disable_ipv6", "1");

			/* Ensure IPv6 is enabled */
			nm_device_sysctl_ip_conf_set (self, AF_INET6, "disable_ipv6", "0");
		}

	}
}

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

static NMSettingIP6ConfigPrivacy
_ip6_privacy_clamp (NMSettingIP6ConfigPrivacy use_tempaddr)
{
	switch (use_tempaddr) {
	case NM_SETTING_IP6_CONFIG_PRIVACY_DISABLED:
	case NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR:
	case NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_PUBLIC_ADDR:
		return use_tempaddr;
	default:
		return NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN;
	}
}

static NMSettingIP6ConfigPrivacy
_ip6_privacy_get (NMDevice *self)
{
	NMSettingIP6ConfigPrivacy ip6_privacy;
	NMConnection *connection;

	g_return_val_if_fail (self, NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN);

	/* 1.) First look at the per-connection setting. If it is not -1 (unknown),
	 * use it. */
	connection = nm_device_get_applied_connection (self);
	if (connection) {
		NMSettingIPConfig *s_ip6 = nm_connection_get_setting_ip6_config (connection);

		if (s_ip6) {
			ip6_privacy = nm_setting_ip6_config_get_ip6_privacy (NM_SETTING_IP6_CONFIG (s_ip6));
			ip6_privacy = _ip6_privacy_clamp (ip6_privacy);
			if (ip6_privacy != NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN)
				return ip6_privacy;
		}
	}

	/* 2.) use the default value from the configuration. */
	ip6_privacy = nm_config_data_get_connection_default_int64 (NM_CONFIG_GET_DATA,
	                                                           NM_CON_DEFAULT ("ipv6.ip6-privacy"),
	                                                           self,
	                                                           NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN,
	                                                           NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR,
	                                                           NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN);
	if (ip6_privacy != NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN)
		return ip6_privacy;

	if (!nm_device_get_ip_ifindex (self))
		return NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN;

	/* 3.) No valid default-value configured. Fallback to reading sysctl.
	 *
	 * Instead of reading static config files in /etc, just read the current sysctl value.
	 * This works as NM only writes to "/proc/sys/net/ipv6/conf/IFNAME/use_tempaddr", but leaves
	 * the "default" entry untouched. */
	ip6_privacy = nm_platform_sysctl_get_int32 (nm_device_get_platform (self),
	                                            NMP_SYSCTL_PATHID_ABSOLUTE ("/proc/sys/net/ipv6/conf/default/use_tempaddr"),
	                                            NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN);
	return _ip6_privacy_clamp (ip6_privacy);
}

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

static gboolean
ip_requires_slaves (NMDevice *self, int addr_family)
{
	const char *method;

	method = nm_device_get_effective_ip_config_method (self, addr_family);

	if (addr_family == AF_INET)
		return nm_streq (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO);

	/* SLAAC, DHCP, and Link-Local depend on connectivity (and thus slaves)
	 * to complete addressing.  SLAAC and DHCP need a peer to provide a prefix.
	 */
	return NM_IN_STRSET (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO,
	                             NM_SETTING_IP6_CONFIG_METHOD_DHCP);
}

static NMActStageReturn
act_stage3_ip_config_start (NMDevice *self,
                            int addr_family,
                            gpointer *out_config,
                            NMDeviceStateReason *out_failure_reason)
{
	const gboolean IS_IPv4 = (addr_family == AF_INET);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMConnection *connection;
	NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE;
	const char *method;

	nm_assert_addr_family (addr_family);

	connection = nm_device_get_applied_connection (self);

	g_return_val_if_fail (connection, NM_ACT_STAGE_RETURN_FAILURE);

	if (   connection_ip_method_requires_carrier (connection, addr_family, NULL)
	    && nm_device_is_master (self)
	    && !priv->carrier) {
		_LOGI (LOGD_IP | LOGD_DEVICE,
		       "IPv%c config waiting until carrier is on",
		       nm_utils_addr_family_to_char (addr_family));
		return NM_ACT_STAGE_RETURN_IP_WAIT;
	}

	if (   nm_device_is_master (self)
	    && ip_requires_slaves (self, addr_family)) {
		/* If the master has no ready slaves, and depends on slaves for
		 * a successful IP configuration attempt, then postpone IP addressing.
		 */
		if (!have_any_ready_slaves (self)) {
			_LOGI (LOGD_DEVICE | LOGD_IP,
			       "IPv%c config waiting until slaves are ready",
			       nm_utils_addr_family_to_char (addr_family));
			return NM_ACT_STAGE_RETURN_IP_WAIT;
		}
	}

	if (!IS_IPv4)
		priv->dhcp6.mode = NM_NDISC_DHCP_LEVEL_NONE;

	method = nm_device_get_effective_ip_config_method (self, addr_family);

	_LOGD (LOGD_IP | LOGD_DEVICE, "IPv%c config method is %s",
	       nm_utils_addr_family_to_char (addr_family), method);

	if (IS_IPv4) {
		if (NM_IN_STRSET (method,
		                  NM_SETTING_IP4_CONFIG_METHOD_AUTO,
		                  NM_SETTING_IP4_CONFIG_METHOD_MANUAL)) {
			NMSettingIPConfig *s_ip4;
			NMIP4Config **configs, *config;
			guint num_addresses;

			s_ip4 = nm_connection_get_setting_ip4_config (connection);
			g_return_val_if_fail (s_ip4, NM_ACT_STAGE_RETURN_FAILURE);
			num_addresses = nm_setting_ip_config_get_num_addresses (s_ip4);

			if (nm_streq (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO)) {
				ret = dhcp4_start (self);
				if (ret == NM_ACT_STAGE_RETURN_FAILURE) {
					NM_SET_OUT (out_failure_reason, NM_DEVICE_STATE_REASON_DHCP_START_FAILED);
					return ret;
				}
			} else {
				g_return_val_if_fail (num_addresses != 0, NM_ACT_STAGE_RETURN_FAILURE);
				ret = NM_ACT_STAGE_RETURN_POSTPONE;
			}

			if (num_addresses) {
				config = nm_device_ip4_config_new (self);
				nm_ip4_config_merge_setting (config,
				                             nm_connection_get_setting_ip4_config (connection),
				                             NM_SETTING_CONNECTION_MDNS_DEFAULT,
				                             NM_SETTING_CONNECTION_LLMNR_DEFAULT,
				                             nm_device_get_route_table (self, AF_INET),
				                             nm_device_get_route_metric (self, AF_INET));
				configs = g_new0 (NMIP4Config *, 2);
				configs[0] = config;
				ipv4_dad_start (self, configs, ipv4_manual_method_apply);
			}
		} else if (nm_streq (method, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL)) {
			ret = ipv4ll_start (self);
			if (ret == NM_ACT_STAGE_RETURN_FAILURE)
				NM_SET_OUT (out_failure_reason, NM_DEVICE_STATE_REASON_AUTOIP_START_FAILED);
		} else if (nm_streq (method, NM_SETTING_IP4_CONFIG_METHOD_SHARED)) {
			if (out_config) {
				*out_config = shared4_new_config (self, connection);
				if (*out_config) {
					priv->dnsmasq_manager = nm_dnsmasq_manager_new (nm_device_get_ip_iface (self));
					ret = NM_ACT_STAGE_RETURN_SUCCESS;
				} else {
					NM_SET_OUT (out_failure_reason, NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE);
					ret = NM_ACT_STAGE_RETURN_FAILURE;
				}
			} else
				g_return_val_if_reached (NM_ACT_STAGE_RETURN_FAILURE);
		} else if (nm_streq (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED))
			ret = NM_ACT_STAGE_RETURN_SUCCESS;
		else
			_LOGW (LOGD_IP4, "unhandled IPv4 config method '%s'; will fail", method);

		return ret;
	} else {
		NMSettingIP6ConfigPrivacy ip6_privacy = NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN;
		const char *ip6_privacy_str = "0";
		NMPlatform *platform;
		int ifindex;

		if (nm_streq (method, NM_SETTING_IP6_CONFIG_METHOD_DISABLED)) {
			nm_device_sysctl_ip_conf_set (self, AF_INET6, "disable_ipv6", "1");
			return NM_ACT_STAGE_RETURN_IP_DONE;
		}

		if (nm_streq (method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE)) {
			if (!nm_device_sys_iface_state_is_external (self)) {
				if (priv->master) {
					/* If a device only has an IPv6 link-local address,
					 * we don't generate an assumed connection. Therefore,
					 * when a new slave connection (without IP configuration)
					 * is activated on the device, the link-local address
					 * remains configured. The IP configuration of an activated
					 * slave should not depend on the previous state. Flush
					 * addresses and routes on activation.
					 */
					ifindex = nm_device_get_ip_ifindex (self);
					platform = nm_device_get_platform (self);

					if (ifindex > 0) {
						gs_unref_object NMIP6Config *config = nm_device_ip6_config_new (self);

						nm_platform_ip_route_flush (platform, AF_INET6, ifindex);
						nm_platform_ip_address_flush (platform, AF_INET6, ifindex);
						nm_device_set_ip_config (self, AF_INET6, (NMIPConfig *) config, FALSE, NULL);
					}
				} else {
					gboolean ipv6ll_handle_old = priv->ipv6ll_handle;

					/* When activating an IPv6 'ignore' connection we need to revert back
					 * to kernel IPv6LL, but the kernel won't actually assign an address
					 * to the interface until disable_ipv6 is bounced.
					 */
					set_nm_ipv6ll (self, FALSE);
					if (ipv6ll_handle_old)
						nm_device_sysctl_ip_conf_set (self, AF_INET6, "disable_ipv6", "1");
					restore_ip6_properties (self);
				}
			}
			return NM_ACT_STAGE_RETURN_IP_DONE;
		}

		/* Ensure the MTU makes sense. If it was below 1280 the kernel would not
		 * expose any ipv6 sysctls or allow presence of any addresses on the interface,
		 * including LL, which * would make it impossible to autoconfigure MTU to a
		 * correct value. */
		_commit_mtu (self, priv->ip_config_4);

		/* Any method past this point requires an IPv6LL address. Use NM-controlled
		 * IPv6LL if this is not an assumed connection, since assumed connections
		 * will already have IPv6 set up.
		 */
		if (!nm_device_sys_iface_state_is_external_or_assume (self))
			set_nm_ipv6ll (self, TRUE);

		/* Re-enable IPv6 on the interface */
		nm_device_sysctl_ip_conf_set (self, AF_INET6, "accept_ra", "0");
		set_disable_ipv6 (self, "0");

		/* Synchronize external IPv6 configuration with kernel, since
		 * linklocal6_start() uses the information there to determine if we can
		 * proceed with the selected method (SLAAC, DHCP, link-local).
		 */
		nm_platform_process_events (nm_device_get_platform (self));
		g_clear_object (&priv->ext_ip6_config_captured);
		priv->ext_ip6_config_captured = nm_ip6_config_capture (nm_device_get_multi_index (self),
		                                                       nm_device_get_platform (self),
		                                                       nm_device_get_ip_ifindex (self),
		                                                       NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN);

		ip6_privacy = _ip6_privacy_get (self);

		if (NM_IN_STRSET (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO,
		                          NM_SETTING_IP6_CONFIG_METHOD_SHARED)) {
			if (!addrconf6_start (self, ip6_privacy)) {
				/* IPv6 might be disabled; allow IPv4 to proceed */
				ret = NM_ACT_STAGE_RETURN_IP_FAIL;
			} else
				ret = NM_ACT_STAGE_RETURN_POSTPONE;
		} else if (nm_streq (method, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL)) {
			ret = linklocal6_start (self)
			      ? NM_ACT_STAGE_RETURN_SUCCESS
			      : NM_ACT_STAGE_RETURN_POSTPONE;
		} else if (nm_streq (method, NM_SETTING_IP6_CONFIG_METHOD_DHCP)) {
			priv->dhcp6.mode = NM_NDISC_DHCP_LEVEL_MANAGED;
			if (!dhcp6_start (self, TRUE)) {
				/* IPv6 might be disabled; allow IPv4 to proceed */
				ret = NM_ACT_STAGE_RETURN_IP_FAIL;
			} else
				ret = NM_ACT_STAGE_RETURN_POSTPONE;
		} else if (nm_streq (method, NM_SETTING_IP6_CONFIG_METHOD_MANUAL))
			ret = NM_ACT_STAGE_RETURN_SUCCESS;
		else
			_LOGW (LOGD_IP6, "unhandled IPv6 config method '%s'; will fail", method);

		if (   ret != NM_ACT_STAGE_RETURN_FAILURE
		    && !nm_device_sys_iface_state_is_external_or_assume (self)) {
			switch (ip6_privacy) {
			case NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN:
			case NM_SETTING_IP6_CONFIG_PRIVACY_DISABLED:
				ip6_privacy_str = "0";
				break;
			case NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_PUBLIC_ADDR:
				ip6_privacy_str = "1";
				break;
			case NM_SETTING_IP6_CONFIG_PRIVACY_PREFER_TEMP_ADDR:
				ip6_privacy_str = "2";
				break;
			}
			nm_device_sysctl_ip_conf_set (self, AF_INET6, "use_tempaddr", ip6_privacy_str);
		}

		return ret;
	}
}

/**
 * nm_device_activate_stage3_ip4_start:
 * @self: the device
 *
 * Try starting IPv4 configuration.
 */
gboolean
nm_device_activate_stage3_ip4_start (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMActStageReturn ret;
	NMDeviceStateReason failure_reason = NM_DEVICE_STATE_REASON_NONE;
	gs_unref_object NMIP4Config *ip4_config = NULL;

	g_assert (priv->ip_state_4 == NM_DEVICE_IP_STATE_WAIT);

	if (nm_device_sys_iface_state_is_external (self)) {
		_set_ip_state (self, AF_INET, NM_DEVICE_IP_STATE_DONE);
		check_ip_state (self, FALSE, TRUE);
		return TRUE;
	}

	_set_ip_state (self, AF_INET, NM_DEVICE_IP_STATE_CONF);
	ret = NM_DEVICE_GET_CLASS (self)->act_stage3_ip_config_start (self, AF_INET, (gpointer *) &ip4_config, &failure_reason);
	if (ret == NM_ACT_STAGE_RETURN_SUCCESS)
		nm_device_activate_schedule_ip_config_result (self, AF_INET, NM_IP_CONFIG_CAST (ip4_config));
	else if (ret == NM_ACT_STAGE_RETURN_IP_DONE) {
		_set_ip_state (self, AF_INET, NM_DEVICE_IP_STATE_DONE);
		check_ip_state (self, FALSE, TRUE);
	} else if (ret == NM_ACT_STAGE_RETURN_FAILURE) {
		nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, failure_reason);
		return FALSE;
	} else if (ret == NM_ACT_STAGE_RETURN_IP_FAIL) {
		/* Activation not wanted */
		_set_ip_state (self, AF_INET, NM_DEVICE_IP_STATE_FAIL);
	} else if (ret == NM_ACT_STAGE_RETURN_IP_WAIT) {
		/* Wait for something to try IP config again */
		_set_ip_state (self, AF_INET, NM_DEVICE_IP_STATE_WAIT);
	} else
		g_assert (ret == NM_ACT_STAGE_RETURN_POSTPONE);

	return TRUE;
}

/**
 * nm_device_activate_stage3_ip6_start:
 * @self: the device
 *
 * Try starting IPv6 configuration.
 */
gboolean
nm_device_activate_stage3_ip6_start (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMActStageReturn ret;
	NMDeviceStateReason failure_reason = NM_DEVICE_STATE_REASON_NONE;
	gs_unref_object NMIP6Config *ip6_config = NULL;

	g_assert (priv->ip_state_6 == NM_DEVICE_IP_STATE_WAIT);

	if (nm_device_sys_iface_state_is_external (self)) {
		_set_ip_state (self, AF_INET6, NM_DEVICE_IP_STATE_DONE);
		check_ip_state (self, FALSE, TRUE);
		return TRUE;
	}

	_set_ip_state (self, AF_INET6, NM_DEVICE_IP_STATE_CONF);
	ret = NM_DEVICE_GET_CLASS (self)->act_stage3_ip_config_start (self, AF_INET6, (gpointer *) &ip6_config, &failure_reason);
	if (ret == NM_ACT_STAGE_RETURN_SUCCESS) {
		if (!ip6_config)
			ip6_config = nm_device_ip6_config_new (self);
		/* Here we get a static IPv6 config, like for Shared where it's
		 * autogenerated or from modems where it comes from ModemManager.
		 */
		nm_assert (!applied_config_get_current (&priv->ac_ip6_config));
		applied_config_init (&priv->ac_ip6_config, ip6_config);
		nm_device_activate_schedule_ip_config_result (self, AF_INET6, NULL);
	} else if (ret == NM_ACT_STAGE_RETURN_IP_DONE) {
		_set_ip_state (self, AF_INET6, NM_DEVICE_IP_STATE_DONE);
		check_ip_state (self, FALSE, TRUE);
	} else if (ret == NM_ACT_STAGE_RETURN_FAILURE) {
		nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, failure_reason);
		return FALSE;
	} else if (ret == NM_ACT_STAGE_RETURN_IP_FAIL) {
		/* Activation not wanted */
		_set_ip_state (self, AF_INET6, NM_DEVICE_IP_STATE_FAIL);
	} else if (ret == NM_ACT_STAGE_RETURN_IP_WAIT) {
		/* Wait for something to try IP config again */
		_set_ip_state (self, AF_INET6, NM_DEVICE_IP_STATE_WAIT);
	} else
		g_assert (ret == NM_ACT_STAGE_RETURN_POSTPONE);

	return TRUE;
}

/*
 * activate_stage3_ip_config_start
 *
 * Begin automatic/manual IP configuration
 *
 */
static void
activate_stage3_ip_config_start (NMDevice *self)
{
	int ifindex;

	_set_ip_state (self, AF_INET, NM_DEVICE_IP_STATE_WAIT);
	_set_ip_state (self, AF_INET6, NM_DEVICE_IP_STATE_WAIT);

	_active_connection_set_state_flags (self,
	                                    NM_ACTIVATION_STATE_FLAG_LAYER2_READY);

	nm_device_state_changed (self, NM_DEVICE_STATE_IP_CONFIG, NM_DEVICE_STATE_REASON_NONE);

	/* Device should be up before we can do anything with it */
	if (   (ifindex = nm_device_get_ip_ifindex (self)) > 0
	    && !nm_platform_link_is_up (nm_device_get_platform (self), ifindex))
		_LOGW (LOGD_DEVICE, "interface %s not up for IP configuration", nm_device_get_ip_iface (self));

	/* IPv4 */
	if (   nm_device_activate_ip4_state_in_wait (self)
	    && !nm_device_activate_stage3_ip4_start (self))
		return;

	/* IPv6 */
	if (   nm_device_activate_ip6_state_in_wait (self)
	    && !nm_device_activate_stage3_ip6_start (self))
		return;

	/* Proxy */
	nm_device_set_proxy_config (self, NULL);

	check_ip_state (self, TRUE, TRUE);
}

static void
fw_change_zone_cb (NMFirewallManager *firewall_manager,
                   NMFirewallManagerCallId *call_id,
                   GError *error,
                   gpointer user_data)
{
	NMDevice *self = user_data;
	NMDevicePrivate *priv;

	g_return_if_fail (NM_IS_DEVICE (self));

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->fw_call != call_id)
		g_return_if_reached ();

	priv->fw_call = NULL;

	if (nm_utils_error_is_cancelled (error))
		return;

	switch (priv->fw_state) {
	case FIREWALL_STATE_WAIT_STAGE_3:
		priv->fw_state = FIREWALL_STATE_INITIALIZED;
		nm_device_activate_schedule_stage3_ip_config_start (self);
		break;
	case FIREWALL_STATE_WAIT_IP_CONFIG:
		priv->fw_state = FIREWALL_STATE_INITIALIZED;
		if (priv->ip_state_4 == NM_DEVICE_IP_STATE_DONE || priv->ip_state_6 == NM_DEVICE_IP_STATE_DONE)
			nm_device_start_ip_check (self);
		break;
	case FIREWALL_STATE_INITIALIZED:
		break;
	default:
		g_return_if_reached ();
	}
}

static void
fw_change_zone (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMConnection *applied_connection;
	NMSettingConnection *s_con;
	const char *zone;

	nm_assert (priv->fw_state >= FIREWALL_STATE_INITIALIZED);

	applied_connection = nm_device_get_applied_connection (self);
	nm_assert (applied_connection);

	s_con = nm_connection_get_setting_connection (applied_connection);
	nm_assert (s_con);

	if (priv->fw_call) {
		nm_firewall_manager_cancel_call (priv->fw_call);
		nm_assert (!priv->fw_call);
	}

	if (G_UNLIKELY (!priv->fw_mgr))
		priv->fw_mgr = g_object_ref (nm_firewall_manager_get ());

	zone = nm_setting_connection_get_zone (s_con);
#if WITH_FIREWALLD_ZONE
	if (!zone || zone[0] == '\0') {
		if (   nm_streq0 (nm_device_get_effective_ip_config_method (self, AF_INET),
		                  NM_SETTING_IP4_CONFIG_METHOD_SHARED)
		    || nm_streq0 (nm_device_get_effective_ip_config_method (self, AF_INET6),
		                  NM_SETTING_IP6_CONFIG_METHOD_SHARED))
			zone = "nm-shared";
	}
#endif
	priv->fw_call = nm_firewall_manager_add_or_change_zone (priv->fw_mgr,
	                                                        nm_device_get_ip_iface (self),
	                                                        zone,
	                                                        FALSE, /* change zone */
	                                                        fw_change_zone_cb,
	                                                        self);
}

/*
 * nm_device_activate_schedule_stage3_ip_config_start
 *
 * Schedule IP configuration start
 */
void
nm_device_activate_schedule_stage3_ip_config_start (NMDevice *self)
{
	NMDevicePrivate *priv;

	g_return_if_fail (NM_IS_DEVICE (self));

	priv = NM_DEVICE_GET_PRIVATE (self);
	g_return_if_fail (priv->act_request.obj);

	/* Add the interface to the specified firewall zone */
	if (priv->fw_state == FIREWALL_STATE_UNMANAGED) {
		if (!nm_device_sys_iface_state_is_external (self)) {
			priv->fw_state = FIREWALL_STATE_WAIT_STAGE_3;
			fw_change_zone (self);
			return;
		}

		/* fake success. */
		priv->fw_state = FIREWALL_STATE_INITIALIZED;
	} else if (priv->fw_state == FIREWALL_STATE_WAIT_STAGE_3) {
		/* a firewall call for stage3 is pending. Return and wait. */
		return;
	}

	nm_assert (priv->fw_state == FIREWALL_STATE_INITIALIZED);

	activation_source_schedule (self, activate_stage3_ip_config_start, AF_INET);
}

static NMActStageReturn
act_stage4_ip_config_timeout (NMDevice *self,
                              int addr_family,
                              NMDeviceStateReason *out_failure_reason)
{
	nm_assert_addr_family (addr_family);

	if (!get_ip_config_may_fail (self, addr_family)) {
		NM_SET_OUT (out_failure_reason, NM_DEVICE_STATE_REASON_IP_CONFIG_UNAVAILABLE);
		return NM_ACT_STAGE_RETURN_FAILURE;
	}

	return NM_ACT_STAGE_RETURN_SUCCESS;
}


/*
 * nm_device_activate_stage4_ip4_config_timeout
 *
 * Time out on retrieving the IPv4 config.
 *
 */
static void
activate_stage4_ip_config_timeout_4 (NMDevice *self)
{
	NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE;
	NMDeviceStateReason failure_reason = NM_DEVICE_STATE_REASON_NONE;

	ret = NM_DEVICE_GET_CLASS (self)->act_stage4_ip_config_timeout (self, AF_INET, &failure_reason);
	if (ret == NM_ACT_STAGE_RETURN_POSTPONE)
		return;
	else if (ret == NM_ACT_STAGE_RETURN_FAILURE) {
		nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, failure_reason);
		return;
	}
	g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS);

	_set_ip_state (self, AF_INET, NM_DEVICE_IP_STATE_FAIL);

	check_ip_state (self, FALSE, TRUE);
}

void
nm_device_activate_schedule_ip_config_timeout (NMDevice *self,
                                               int addr_family)
{
	NMDevicePrivate *priv;
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	g_return_if_fail (NM_IS_DEVICE (self));
	g_return_if_fail (NM_IN_SET (addr_family, AF_INET, AF_INET6));

	priv = NM_DEVICE_GET_PRIVATE (self);

	g_return_if_fail (priv->act_request.obj);

	activation_source_schedule (self, activate_stage4_ip_config_timeout_x[IS_IPv4], addr_family);
}

static void
activate_stage4_ip_config_timeout_6 (NMDevice *self)
{
	NMActStageReturn ret = NM_ACT_STAGE_RETURN_FAILURE;
	NMDeviceStateReason failure_reason = NM_DEVICE_STATE_REASON_NONE;

	ret = NM_DEVICE_GET_CLASS (self)->act_stage4_ip_config_timeout (self, AF_INET6, &failure_reason);
	if (ret == NM_ACT_STAGE_RETURN_POSTPONE)
		return;
	if (ret == NM_ACT_STAGE_RETURN_FAILURE) {
		nm_device_state_changed (self, NM_DEVICE_STATE_FAILED, failure_reason);
		return;
	}
	g_assert (ret == NM_ACT_STAGE_RETURN_SUCCESS);

	_set_ip_state (self, AF_INET6, NM_DEVICE_IP_STATE_FAIL);

	check_ip_state (self, FALSE, TRUE);
}

static gboolean
share_init (NMDevice *self, GError **error)
{
	char *modules[] = { "ip_tables", "iptable_nat", "nf_nat_ftp", "nf_nat_irc",
	                    "nf_nat_sip", "nf_nat_tftp", "nf_nat_pptp", "nf_nat_h323",
	                    NULL };
	char **iter;
	int errsv;

	if (nm_platform_sysctl_get_int32 (nm_device_get_platform (self), NMP_SYSCTL_PATHID_ABSOLUTE ("/proc/sys/net/ipv4/ip_forward"), -1) == 1) {
		/* nothing to do. */
	} else if (!nm_platform_sysctl_set (nm_device_get_platform (self), NMP_SYSCTL_PATHID_ABSOLUTE ("/proc/sys/net/ipv4/ip_forward"), "1")) {
		errsv = errno;
		_LOGD (LOGD_SHARING, "share: error enabling IPv4 forwarding: (%d) %s",
		       errsv, nm_strerror_native (errsv));
		g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_UNKNOWN,
		             "cannot set ipv4/ip_forward: %s", nm_strerror_native (errsv));
		return FALSE;
	}

	if (nm_platform_sysctl_get_int32 (nm_device_get_platform (self), NMP_SYSCTL_PATHID_ABSOLUTE ("/proc/sys/net/ipv4/ip_dynaddr"), -1) == 1) {
		/* nothing to do. */
	} else if (!nm_platform_sysctl_set (nm_device_get_platform (self), NMP_SYSCTL_PATHID_ABSOLUTE ("/proc/sys/net/ipv4/ip_dynaddr"), "1")) {
		errsv = errno;
		_LOGD (LOGD_SHARING, "share: error enabling dynamic addresses: (%d) %s",
		       errsv, nm_strerror_native (errsv));
	}

	for (iter = modules; *iter; iter++)
		nm_utils_modprobe (NULL, FALSE, *iter, NULL);

	return TRUE;
}

#define add_share_rule(req, table, ...) \
	G_STMT_START { \
		char *_cmd = g_strdup_printf (__VA_ARGS__); \
		nm_act_request_add_share_rule (req, table, _cmd); \
		g_free (_cmd); \
	} G_STMT_END

static gboolean
start_sharing (NMDevice *self, NMIP4Config *config, GError **error)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMActRequest *req;
	char str_addr[INET_ADDRSTRLEN];
	char str_mask[INET_ADDRSTRLEN];
	guint32 netmask, network;
	const NMPlatformIP4Address *ip4_addr = NULL;
	const char *ip_iface;
	GError *local = NULL;
	NMConnection *conn;
	NMSettingConnection *s_con;
	gboolean announce_android_metered;

	g_return_val_if_fail (config, FALSE);

	ip_iface = nm_device_get_ip_iface (self);
	if (!ip_iface) {
		g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_UNKNOWN,
		             "device has no ip interface");
		return FALSE;
	}

	ip4_addr = nm_ip4_config_get_first_address (config);
	if (!ip4_addr || !ip4_addr->address) {
		g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_UNKNOWN,
		             "could not determine IPv4 address");
		return FALSE;
	}

	if (!share_init (self, error))
		return FALSE;

	req = nm_device_get_act_request (self);
	g_return_val_if_fail (req, FALSE);

	netmask = _nm_utils_ip4_prefix_to_netmask (ip4_addr->plen);
	_nm_utils_inet4_ntop (netmask, str_mask);

	network = ip4_addr->address & netmask;
	_nm_utils_inet4_ntop (network, str_addr);

	add_share_rule (req, "nat", "POSTROUTING --source %s/%s ! --destination %s/%s --jump MASQUERADE", str_addr, str_mask, str_addr, str_mask);
	add_share_rule (req, "filter", "FORWARD --destination %s/%s --out-interface %s --match state --state ESTABLISHED,RELATED --jump ACCEPT", str_addr, str_mask, ip_iface);
	add_share_rule (req, "filter", "FORWARD --source %s/%s --in-interface %s --jump ACCEPT", str_addr, str_mask, ip_iface);
	add_share_rule (req, "filter", "FORWARD --in-interface %s --out-interface %s --jump ACCEPT", ip_iface, ip_iface);
	add_share_rule (req, "filter", "FORWARD --out-interface %s --jump REJECT", ip_iface);
	add_share_rule (req, "filter", "FORWARD --in-interface %s --jump REJECT", ip_iface);
	add_share_rule (req, "filter", "INPUT --in-interface %s --protocol udp --destination-port 67 --jump ACCEPT", ip_iface);
	add_share_rule (req, "filter", "INPUT --in-interface %s --protocol tcp --destination-port 67 --jump ACCEPT", ip_iface);
	add_share_rule (req, "filter", "INPUT --in-interface %s --protocol udp --destination-port 53 --jump ACCEPT", ip_iface);
	add_share_rule (req, "filter", "INPUT --in-interface %s --protocol tcp --destination-port 53 --jump ACCEPT", ip_iface);

	nm_act_request_set_shared (req, TRUE);

	conn = nm_act_request_get_applied_connection (req);
	s_con = nm_connection_get_setting_connection (conn);

	switch (nm_setting_connection_get_metered (s_con)) {
	case NM_METERED_YES:
		/* honor the metered flag. Note that reapply on the device does not affect
		 * the metered setting. This is different from other profiles, where the
		 * metered flag of an activated profile can be changed (reapplied). */
		announce_android_metered = TRUE;
		break;
	case NM_METERED_UNKNOWN:
		/* we pick up the current value and announce it. But again, we cannot update
		 * the announced setting without restarting dnsmasq. That means, if the default
		 * route changes w.r.t. being metered, then the shared connection does not get
		 * updated before reactivating. */
		announce_android_metered = NM_IN_SET (nm_manager_get_metered (NM_MANAGER_GET),
		                                      NM_METERED_YES,
		                                      NM_METERED_GUESS_YES);
		break;
	default:
		announce_android_metered = FALSE;
		break;
	}


	if (!nm_dnsmasq_manager_start (priv->dnsmasq_manager,
	                               config,
	                               announce_android_metered,
	                               &local)) {
		g_set_error (error, NM_UTILS_ERROR, NM_UTILS_ERROR_UNKNOWN,
		             "could not start dnsmasq due to %s", local->message);
		g_error_free (local);
		nm_act_request_set_shared (req, FALSE);
		return FALSE;
	}

	priv->dnsmasq_state_id = g_signal_connect (priv->dnsmasq_manager, NM_DNS_MASQ_MANAGER_STATE_CHANGED,
	                                           G_CALLBACK (dnsmasq_state_changed_cb),
	                                           self);
	return TRUE;
}

static void
arp_cleanup (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	nm_clear_pointer (&priv->acd.announcing, nm_acd_manager_free);
}

void
nm_device_arp_announce (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMConnection *connection;
	NMSettingIPConfig *s_ip4;
	guint num, i;
	const guint8 *hw_addr;
	size_t hw_addr_len = 0;

	arp_cleanup (self);

	hw_addr = nm_platform_link_get_address (nm_device_get_platform (self),
	                                        nm_device_get_ip_ifindex (self),
	                                        &hw_addr_len);

	if (!hw_addr || hw_addr_len != ETH_ALEN)
		return;

	/* We only care about manually-configured addresses; DHCP- and autoip-configured
	 * ones should already have been seen on the network at this point.
	 */
	connection = nm_device_get_applied_connection (self);
	if (!connection)
		return;
	s_ip4 = nm_connection_get_setting_ip4_config (connection);
	if (!s_ip4)
		return;
	num = nm_setting_ip_config_get_num_addresses (s_ip4);
	if (num == 0)
		return;

	priv->acd.announcing = nm_acd_manager_new (nm_device_get_ip_ifindex (self),
	                                           hw_addr,
	                                           hw_addr_len,
	                                           NULL,
	                                           NULL);

	for (i = 0; i < num; i++) {
		NMIPAddress *ip = nm_setting_ip_config_get_address (s_ip4, i);
		in_addr_t addr;

		if (inet_pton (AF_INET, nm_ip_address_get_address (ip), &addr) == 1)
			nm_acd_manager_add_address (priv->acd.announcing, addr);
		else
			g_warn_if_reached ();
	}

	nm_acd_manager_announce_addresses (priv->acd.announcing);
}

static void
activate_stage5_ip_config_result_4 (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMActRequest *req;
	const char *method;
	int ip_ifindex;
	gboolean do_announce = FALSE;

	req = nm_device_get_act_request (self);
	g_assert (req);

	/* Interface must be IFF_UP before IP config can be applied */
	ip_ifindex = nm_device_get_ip_ifindex (self);
	if (!nm_platform_link_is_up (nm_device_get_platform (self), ip_ifindex) && !nm_device_sys_iface_state_is_external_or_assume (self)) {
		nm_platform_link_set_up (nm_device_get_platform (self), ip_ifindex, NULL);
		if (!nm_platform_link_is_up (nm_device_get_platform (self), ip_ifindex))
			_LOGW (LOGD_DEVICE, "interface %s not up for IP configuration", nm_device_get_ip_iface (self));
	}

	if (!ip_config_merge_and_apply (self, AF_INET, TRUE)) {
		_LOGD (LOGD_DEVICE | LOGD_IP4, "Activation: Stage 5 of 5 (IPv4 Commit) failed");
		nm_device_ip_method_failed (self, AF_INET, NM_DEVICE_STATE_REASON_CONFIG_FAILED);
		return;
	}

	/* Start IPv4 sharing if we need it */
	method = nm_device_get_effective_ip_config_method (self, AF_INET);
	if (nm_streq (method, NM_SETTING_IP4_CONFIG_METHOD_SHARED)) {
		gs_free_error GError *error = NULL;

		if (!start_sharing (self, priv->ip_config_4, &error)) {
			_LOGW (LOGD_SHARING, "Activation: Stage 5 of 5 (IPv4 Commit) start sharing failed: %s", error->message);
			nm_device_ip_method_failed (self, AF_INET, NM_DEVICE_STATE_REASON_SHARED_START_FAILED);
			return;
		}
	}

	if (priv->dhcp_data_4.client) {
		gs_free_error GError *error = NULL;

		if (!nm_dhcp_client_accept (priv->dhcp_data_4.client, &error)) {
			_LOGW (LOGD_DHCP4,
			       "Activation: Stage 5 of 5 (IPv4 Commit) error accepting lease: %s",
			       error->message);
			nm_device_ip_method_failed (self, AF_INET, NM_DEVICE_STATE_REASON_DHCP_ERROR);
			return;
		}
	}

	/* If IPv4 wasn't the first to complete, and DHCP was used, then ensure
	 * dispatcher scripts get the DHCP lease information.
	 */
	if (   priv->dhcp_data_4.client
	    && nm_device_activate_ip4_state_in_conf (self)
	    && (nm_device_get_state (self) > NM_DEVICE_STATE_IP_CONFIG)) {
		nm_dispatcher_call_device (NM_DISPATCHER_ACTION_DHCP4_CHANGE,
		                           self,
		                           NULL,
		                           NULL, NULL, NULL);
	}

	/* Send ARP announcements */

	if (nm_device_is_master (self)) {
		CList *iter;
		SlaveInfo *info;

		/* Skip announcement if there are no device enslaved, for two reasons:
		 * 1) the master has a temporary MAC address until the first slave comes
		 * 2) announcements are going to be dropped anyway without slaves
		 */
		do_announce = FALSE;

		c_list_for_each (iter, &priv->slaves) {
			info = c_list_entry (iter, SlaveInfo, lst_slave);
			if (info->slave_is_enslaved) {
				do_announce = TRUE;
				break;
			}
		}
	} else
		do_announce = TRUE;

	if (do_announce)
		nm_device_arp_announce (self);

	/* Enter the IP_CHECK state if this is the first method to complete */
	_set_ip_state (self, AF_INET, NM_DEVICE_IP_STATE_DONE);
	check_ip_state (self, FALSE, TRUE);
}

void
nm_device_activate_schedule_ip_config_result (NMDevice *self,
                                              int addr_family,
                                              NMIPConfig *config)
{
	NMDevicePrivate *priv;
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	g_return_if_fail (NM_IS_DEVICE (self));
	g_return_if_fail (NM_IN_SET (addr_family, AF_INET, AF_INET6));
	g_return_if_fail (   !config
	                  || (   addr_family == AF_INET
	                      && nm_ip_config_get_addr_family (config) == AF_INET));

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (IS_IPv4) {
		applied_config_init (&priv->dev_ip_config_4, config);
	} else {
		/* If IP had previously failed, move it back to NM_DEVICE_IP_STATE_CONF since we
		 * clearly now have configuration.
		 */
		if (priv->ip_state_6 == NM_DEVICE_IP_STATE_FAIL)
			_set_ip_state (self, AF_INET6, NM_DEVICE_IP_STATE_CONF);
	}

	activation_source_schedule (self, activate_stage5_ip_config_result_x[IS_IPv4], addr_family);
}

NMDeviceIPState
nm_device_activate_get_ip_state (NMDevice *self,
                                 int addr_family)
{
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	g_return_val_if_fail (NM_IS_DEVICE (self), NM_DEVICE_IP_STATE_NONE);
	g_return_val_if_fail (NM_IN_SET (addr_family, AF_INET, AF_INET6), NM_DEVICE_IP_STATE_NONE);

	return NM_DEVICE_GET_PRIVATE (self)->ip_state_x[IS_IPv4];
}

static void
dad6_add_pending_address (NMDevice *self,
                          NMPlatform *platform,
                          int ifindex,
                          const struct in6_addr *address,
                          NMIP6Config **dad6_config)
{
	const NMPlatformIP6Address *pl_addr;

	pl_addr = nm_platform_ip6_address_get (platform,
	                                       ifindex,
	                                       *address);
	if (   pl_addr
	    && NM_FLAGS_HAS (pl_addr->n_ifa_flags, IFA_F_TENTATIVE)
	    && !NM_FLAGS_HAS (pl_addr->n_ifa_flags, IFA_F_DADFAILED)
	    && !NM_FLAGS_HAS (pl_addr->n_ifa_flags, IFA_F_OPTIMISTIC)) {
		_LOGt (LOGD_DEVICE, "IPv6 DAD: pending address %s",
		       nm_platform_ip6_address_to_string (pl_addr, NULL, 0));

		if (!*dad6_config)
			*dad6_config = nm_device_ip6_config_new (self);

		nm_ip6_config_add_address (*dad6_config, pl_addr);
	}
}

/*
 * Returns a NMIP6Config containing NM-configured addresses which
 * have the tentative flag, or NULL if none is present.
 */
static NMIP6Config *
dad6_get_pending_addresses (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMIP6Config *confs[] = { (NMIP6Config *) applied_config_get_current (&priv->ac_ip6_config),
	                         (NMIP6Config *) applied_config_get_current (&priv->dhcp6.ip6_config),
	                         priv->con_ip_config_6,
	                         (NMIP6Config *) applied_config_get_current (&priv->dev2_ip_config_6) };
	const NMPlatformIP6Address *addr;
	NMIP6Config *dad6_config = NULL;
	NMDedupMultiIter ipconf_iter;
	guint i;
	int ifindex;
	NMPlatform *platform;

	ifindex = nm_device_get_ip_ifindex (self);
	g_return_val_if_fail (ifindex > 0, NULL);

	platform = nm_device_get_platform (self);

	if (priv->ipv6ll_has) {
		dad6_add_pending_address (self,
		                          platform,
		                          ifindex,
		                          &priv->ipv6ll_addr,
		                          &dad6_config);
	}

	/* We are interested only in addresses that we have explicitly configured,
	 * not in externally added ones.
	 */
	for (i = 0; i < G_N_ELEMENTS (confs); i++) {
		if (!confs[i])
			continue;

		nm_ip_config_iter_ip6_address_for_each (&ipconf_iter, confs[i], &addr) {
			dad6_add_pending_address (self,
			                          platform,
			                          ifindex,
			                          &addr->address,
			                          &dad6_config);
		}
	}

	return dad6_config;
}

static void
activate_stage5_ip_config_result_6 (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMActRequest *req;
	const char *method;
	int ip_ifindex;
	int errsv;

	req = nm_device_get_act_request (self);
	g_assert (req);

	/* Interface must be IFF_UP before IP config can be applied */
	ip_ifindex = nm_device_get_ip_ifindex (self);
	g_return_if_fail (ip_ifindex);

	if (!nm_platform_link_is_up (nm_device_get_platform (self), ip_ifindex) && !nm_device_sys_iface_state_is_external_or_assume (self)) {
		nm_platform_link_set_up (nm_device_get_platform (self), ip_ifindex, NULL);
		if (!nm_platform_link_is_up (nm_device_get_platform (self), ip_ifindex))
			_LOGW (LOGD_DEVICE, "interface %s not up for IP configuration", nm_device_get_ip_iface (self));
	}

	if (ip_config_merge_and_apply (self, AF_INET6, TRUE)) {
		if (   priv->dhcp6.mode != NM_NDISC_DHCP_LEVEL_NONE
		    && priv->ip_state_6 == NM_DEVICE_IP_STATE_CONF) {
			if (applied_config_get_current (&priv->dhcp6.ip6_config)) {
				/* If IPv6 wasn't the first IP to complete, and DHCP was used,
				 * then ensure dispatcher scripts get the DHCP lease information.
				 */
				nm_dispatcher_call_device (NM_DISPATCHER_ACTION_DHCP6_CHANGE,
				                           self,
				                           NULL,
				                           NULL, NULL, NULL);
			} else {
				/* still waiting for first dhcp6 lease. */
				return;
			}
		}

		/* Start IPv6 forwarding if we need it */
		method = nm_device_get_effective_ip_config_method (self, AF_INET6);
		if (nm_streq (method, NM_SETTING_IP6_CONFIG_METHOD_SHARED)) {
			if (!nm_platform_sysctl_set (nm_device_get_platform (self), NMP_SYSCTL_PATHID_ABSOLUTE ("/proc/sys/net/ipv6/conf/all/forwarding"), "1")) {
				errsv = errno;
				_LOGE (LOGD_SHARING, "share: error enabling IPv6 forwarding: (%d) %s", errsv, nm_strerror_native (errsv));
				nm_device_ip_method_failed (self, AF_INET6, NM_DEVICE_STATE_REASON_SHARED_START_FAILED);
			}
		}

		/* Check if we have to wait for DAD */
		if (priv->ip_state_6 == NM_DEVICE_IP_STATE_CONF && !priv->dad6_ip6_config) {
			if (!priv->carrier && priv->ignore_carrier && get_ip_config_may_fail (self, AF_INET6))
				_LOGI (LOGD_DEVICE | LOGD_IP6, "IPv6 DAD: carrier missing and ignored, not delaying activation");
			else
				priv->dad6_ip6_config = dad6_get_pending_addresses (self);

			if (priv->dad6_ip6_config) {
				_LOGD (LOGD_DEVICE | LOGD_IP6, "IPv6 DAD: awaiting termination");
			} else {
				_set_ip_state (self, AF_INET6, NM_DEVICE_IP_STATE_DONE);
				check_ip_state (self, FALSE, TRUE);
			}
		}
	} else {
		_LOGW (LOGD_DEVICE | LOGD_IP6, "Activation: Stage 5 of 5 (IPv6 Commit) failed");
		nm_device_ip_method_failed (self, AF_INET6, NM_DEVICE_STATE_REASON_CONFIG_FAILED);
	}
}

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

static void
act_request_set (NMDevice *self, NMActRequest *act_request)
{
	NMDevicePrivate *priv;

	nm_assert (NM_IS_DEVICE (self));
	nm_assert (!act_request || NM_IS_ACT_REQUEST (act_request));

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (   !priv->act_request.visible
	    && priv->act_request.obj == act_request)
		return;

	/* always clear the public flag. The few callers that set a new @act_request
	 * don't want that the property is public yet.  */
	nm_dbus_track_obj_path_set (&priv->act_request,
	                            act_request,
	                            FALSE);

	if (act_request) {
		switch (nm_active_connection_get_activation_type (NM_ACTIVE_CONNECTION (act_request))) {
		case NM_ACTIVATION_TYPE_EXTERNAL:
			break;
		case NM_ACTIVATION_TYPE_ASSUME:
			if (priv->sys_iface_state == NM_DEVICE_SYS_IFACE_STATE_EXTERNAL)
				nm_device_sys_iface_state_set (self, NM_DEVICE_SYS_IFACE_STATE_ASSUME);
			break;
		case NM_ACTIVATION_TYPE_MANAGED:
			if (NM_IN_SET_TYPED (NMDeviceSysIfaceState,
			                     priv->sys_iface_state,
			                     NM_DEVICE_SYS_IFACE_STATE_EXTERNAL,
			                     NM_DEVICE_SYS_IFACE_STATE_ASSUME))
				nm_device_sys_iface_state_set (self, NM_DEVICE_SYS_IFACE_STATE_MANAGED);
			break;
		}
	}
}

static void
dnsmasq_cleanup (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (!priv->dnsmasq_manager)
		return;

	nm_clear_g_signal_handler (priv->dnsmasq_manager, &priv->dnsmasq_state_id);

	nm_dnsmasq_manager_stop (priv->dnsmasq_manager);
	g_object_unref (priv->dnsmasq_manager);
	priv->dnsmasq_manager = NULL;
}

static void
_update_ip4_address (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const NMPlatformIP4Address *address;

	g_return_if_fail (NM_IS_DEVICE (self));

	if (   priv->ip_config_4
	    && ip_config_valid (priv->state)
	    && (address = nm_ip4_config_get_first_address (priv->ip_config_4))) {
		if (address->address != priv->ip4_address) {
			priv->ip4_address = address->address;
			_notify (self, PROP_IP4_ADDRESS);
		}
	}
}

gboolean
nm_device_is_nm_owned (NMDevice *self)
{
	return NM_DEVICE_GET_PRIVATE (self)->nm_owned;
}

/*
 * delete_on_deactivate_link_delete
 *
 * Function will be queued with g_idle_add to call
 * nm_platform_link_delete for the underlying resources
 * of the device.
 */
static gboolean
delete_on_deactivate_link_delete (gpointer user_data)
{
	DeleteOnDeactivateData *data = user_data;
	NMDevice *self = data->device;

	_LOGD (LOGD_DEVICE, "delete_on_deactivate: cleanup and delete virtual link #%d (id=%u)",
	       data->ifindex, data->idle_add_id);

	if (data->device) {
		NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (data->device);
		gs_free_error GError *error = NULL;

		g_object_remove_weak_pointer (G_OBJECT (data->device), (void **) &data->device);
		priv->delete_on_deactivate_data = NULL;

		if (!nm_device_unrealize (data->device, TRUE, &error))
			_LOGD (LOGD_DEVICE, "delete_on_deactivate: unrealizing %d failed (%s)", data->ifindex, error->message);
	} else if (data->ifindex > 0)
		nm_platform_link_delete (nm_device_get_platform (self), data->ifindex);

	nm_device_emit_recheck_auto_activate (self);

	g_free (data);
	return FALSE;
}

static void
delete_on_deactivate_unschedule (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->delete_on_deactivate_data) {
		DeleteOnDeactivateData *data = priv->delete_on_deactivate_data;

		priv->delete_on_deactivate_data = NULL;

		g_source_remove (data->idle_add_id);
		g_object_remove_weak_pointer (G_OBJECT (self), (void **) &data->device);
		_LOGD (LOGD_DEVICE, "delete_on_deactivate: cancel cleanup and delete virtual link #%d (id=%u)",
		       data->ifindex, data->idle_add_id);
		g_free (data);
	}
}

static void
delete_on_deactivate_check_and_schedule (NMDevice *self, int ifindex)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	DeleteOnDeactivateData *data;

	if (!priv->nm_owned)
		return;
	if (priv->queued_act_request)
		return;
	if (!nm_device_is_software (self) || !nm_device_is_real (self))
		return;
	if (nm_device_get_state (self) == NM_DEVICE_STATE_UNMANAGED)
		return;
	if (nm_device_get_state (self) == NM_DEVICE_STATE_UNAVAILABLE)
		return;
	delete_on_deactivate_unschedule (self); /* always cancel and reschedule */

	data = g_new (DeleteOnDeactivateData, 1);
	g_object_add_weak_pointer (G_OBJECT (self), (void **) &data->device);
	data->device = self;
	data->ifindex = ifindex;
	data->idle_add_id = g_idle_add (delete_on_deactivate_link_delete, data);
	priv->delete_on_deactivate_data = data;

	_LOGD (LOGD_DEVICE, "delete_on_deactivate: schedule cleanup and delete virtual link #%d (id=%u)",
	       ifindex, data->idle_add_id);
}

static void
_cleanup_ip_pre (NMDevice *self, int addr_family, CleanupType cleanup_type)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	_set_ip_state (self, addr_family, NM_DEVICE_IP_STATE_NONE);

	if (nm_clear_g_source (&priv->queued_ip_config_id_x[IS_IPv4])) {
		_LOGD (LOGD_DEVICE, "clearing queued IP%c config change",
		       nm_utils_addr_family_to_char (addr_family));
	}

	if (IS_IPv4) {
		dhcp4_cleanup (self, cleanup_type, FALSE);
		arp_cleanup (self);
		dnsmasq_cleanup (self);
		ipv4ll_cleanup (self);
		g_slist_free_full (priv->acd.dad_list, (GDestroyNotify) nm_acd_manager_free);
		priv->acd.dad_list = NULL;
	} else {
		g_slist_free_full (priv->dad6_failed_addrs, (GDestroyNotify) nmp_object_unref);
		priv->dad6_failed_addrs = NULL;
		g_clear_object (&priv->dad6_ip6_config);
		dhcp6_cleanup (self, cleanup_type, FALSE);
		nm_clear_g_source (&priv->linklocal6_timeout_id);
		addrconf6_cleanup (self);
	}
}

gboolean
_nm_device_hash_check_invalid_keys (GHashTable *hash,
                                    const char *setting_name,
                                    GError **error,
                                    const char *const*whitelist)
{
	guint found_whitelisted_keys = 0;
	guint i;

	nm_assert (hash && g_hash_table_size (hash) > 0);
	nm_assert (whitelist && whitelist[0]);

#if NM_MORE_ASSERTS > 10
	/* Require whitelist to only contain unique keys. */
	{
		gs_unref_hashtable GHashTable *check_dups = g_hash_table_new_full (nm_str_hash, g_str_equal, NULL, NULL);

		for (i = 0; whitelist[i]; i++) {
			if (!g_hash_table_add (check_dups, (char *) whitelist[i]))
				nm_assert (FALSE);
		}
		nm_assert (g_hash_table_size (check_dups) > 0);
	}
#endif

	for (i = 0; whitelist[i]; i++) {
		if (g_hash_table_contains (hash, whitelist[i]))
			found_whitelisted_keys++;
	}

	if (found_whitelisted_keys == g_hash_table_size (hash)) {
		/* Good, there are only whitelisted keys in the hash. */
		return TRUE;
	}

	if (error) {
		GHashTableIter iter;
		const char *k = NULL;
		const char *first_invalid_key = NULL;

		g_hash_table_iter_init (&iter, hash);
		while (g_hash_table_iter_next (&iter, (gpointer *) &k, NULL)) {
			if (nm_utils_strv_find_first ((char **) whitelist, -1, k) < 0) {
				first_invalid_key = k;
				break;
			}
		}
		if (setting_name) {
			g_set_error (error,
			             NM_DEVICE_ERROR,
			             NM_DEVICE_ERROR_INCOMPATIBLE_CONNECTION,
			             "Can't reapply changes to '%s.%s' setting",
			             setting_name,
			             first_invalid_key);
		} else {
			g_set_error (error,
			             NM_DEVICE_ERROR,
			             NM_DEVICE_ERROR_INCOMPATIBLE_CONNECTION,
			             "Can't reapply any changes to '%s' setting",
			             first_invalid_key);
		}
		g_return_val_if_fail (first_invalid_key, FALSE);
	}

	return FALSE;
}

void
nm_device_reactivate_ip4_config (NMDevice *self,
                                 NMSettingIPConfig *s_ip4_old,
                                 NMSettingIPConfig *s_ip4_new)
{
	NMDevicePrivate *priv;
	const char *method_old, *method_new;

	g_return_if_fail (NM_IS_DEVICE (self));
	priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->ip_state_4 != NM_DEVICE_IP_STATE_NONE) {
		g_clear_object (&priv->con_ip_config_4);
		g_clear_object (&priv->ext_ip_config_4);
		g_clear_object (&priv->dev_ip_config_4.current);
		g_clear_object (&priv->dev2_ip_config_4.current);
		priv->con_ip_config_4 = nm_device_ip4_config_new (self);
		nm_ip4_config_merge_setting (priv->con_ip_config_4,
		                             s_ip4_new,
		                             _get_mdns (self),
		                             _get_llmnr (self),
		                             nm_device_get_route_table (self, AF_INET),
		                             nm_device_get_route_metric (self, AF_INET));

		method_old = s_ip4_old
		             ? nm_setting_ip_config_get_method (s_ip4_old)
		             : NM_SETTING_IP4_CONFIG_METHOD_DISABLED;
		method_new = s_ip4_new
		             ? nm_setting_ip_config_get_method (s_ip4_new)
		             : NM_SETTING_IP4_CONFIG_METHOD_DISABLED;

		if (!nm_streq0 (method_old, method_new)) {
			_cleanup_ip_pre (self, AF_INET, CLEANUP_TYPE_DECONFIGURE);
			_set_ip_state (self, AF_INET, NM_DEVICE_IP_STATE_WAIT);
			if (!nm_device_activate_stage3_ip4_start (self))
				_LOGW (LOGD_IP4, "Failed to apply IPv4 configuration");
			return;
		}

		if (s_ip4_old && s_ip4_new) {
			gint64 metric_old, metric_new;

			/* For dynamic IP methods (DHCP, IPv4LL, WWAN) the route metric is
			 * set at activation/renewal time using the value from static
			 * configuration. To support runtime change we need to update the
			 * dynamic configuration in place and tell the DHCP client the new
			 * value to use for future renewals.
			 */
			metric_old = nm_setting_ip_config_get_route_metric (s_ip4_old);
			metric_new = nm_setting_ip_config_get_route_metric (s_ip4_new);

			if (metric_old != metric_new) {
				if (priv->dev_ip_config_4.orig) {
					nm_ip4_config_update_routes_metric ((NMIP4Config *) priv->dev_ip_config_4.orig,
					                                    nm_device_get_route_metric (self, AF_INET));
				}
				if (priv->dev2_ip_config_4.orig) {
					nm_ip4_config_update_routes_metric ((NMIP4Config *) priv->dev2_ip_config_4.orig,
					                                    nm_device_get_route_metric (self, AF_INET));
				}
				if (priv->dhcp_data_4.client) {
					nm_dhcp_client_set_route_metric (priv->dhcp_data_4.client,
					                                 nm_device_get_route_metric (self, AF_INET));
				}
			}
		}

		if (   nm_device_get_ip_ifindex (self) > 0
		    && !ip_config_merge_and_apply (self, AF_INET, TRUE))
			_LOGW (LOGD_IP4, "Failed to reapply IPv4 configuration");
	}
}

void
nm_device_reactivate_ip6_config (NMDevice *self,
                                 NMSettingIPConfig *s_ip6_old,
                                 NMSettingIPConfig *s_ip6_new)
{
	NMDevicePrivate *priv;
	const char *method_old, *method_new;

	g_return_if_fail (NM_IS_DEVICE (self));
	priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->ip_state_6 != NM_DEVICE_IP_STATE_NONE) {
		g_clear_object (&priv->con_ip_config_6);
		g_clear_object (&priv->ext_ip_config_6);
		g_clear_object (&priv->ac_ip6_config.current);
		g_clear_object (&priv->dhcp6.ip6_config.current);
		g_clear_object (&priv->dev2_ip_config_6.current);
		if (   priv->ipv6ll_handle
		    && !IN6_IS_ADDR_UNSPECIFIED (&priv->ipv6ll_addr))
			priv->ipv6ll_has = TRUE;
		priv->con_ip_config_6 = nm_device_ip6_config_new (self);
		nm_ip6_config_merge_setting (priv->con_ip_config_6,
		                             s_ip6_new,
		                             nm_device_get_route_table (self, AF_INET6),
		                             nm_device_get_route_metric (self, AF_INET6));

		method_old = s_ip6_old
		             ? nm_setting_ip_config_get_method (s_ip6_old)
		             : NM_SETTING_IP6_CONFIG_METHOD_IGNORE;
		method_new = s_ip6_new
		             ? nm_setting_ip_config_get_method (s_ip6_new)
		             : NM_SETTING_IP6_CONFIG_METHOD_IGNORE;

		if (!nm_streq0 (method_old, method_new)) {
			_cleanup_ip_pre (self, AF_INET6, CLEANUP_TYPE_DECONFIGURE);
			_set_ip_state (self, AF_INET6, NM_DEVICE_IP_STATE_WAIT);
			if (!nm_device_activate_stage3_ip6_start (self))
				_LOGW (LOGD_IP6, "Failed to apply IPv6 configuration");
			return;
		}

		if (s_ip6_old && s_ip6_new) {
			gint64 metric_old, metric_new;

			/* See comment in nm_device_reactivate_ip4_config() */
			metric_old = nm_setting_ip_config_get_route_metric (s_ip6_old);
			metric_new = nm_setting_ip_config_get_route_metric (s_ip6_new);

			if (metric_old != metric_new) {
				if (priv->ac_ip6_config.orig) {
					nm_ip6_config_update_routes_metric ((NMIP6Config *) priv->ac_ip6_config.orig,
					                                    nm_device_get_route_metric (self, AF_INET6));
				}
				if (priv->dhcp6.ip6_config.orig) {
					nm_ip6_config_update_routes_metric ((NMIP6Config *) priv->dhcp6.ip6_config.orig,
					                                    nm_device_get_route_metric (self, AF_INET6));
				}
				if (priv->dev2_ip_config_6.orig) {
					nm_ip6_config_update_routes_metric ((NMIP6Config *) priv->dev2_ip_config_6.orig,
					                                    nm_device_get_route_metric (self, AF_INET6));
				}
				if (priv->dhcp_data_6.client) {
					nm_dhcp_client_set_route_metric (priv->dhcp_data_6.client,
					                                 nm_device_get_route_metric (self, AF_INET6));
				}
			}
		}

		if (   nm_device_get_ip_ifindex (self) > 0
		    && !ip_config_merge_and_apply (self, AF_INET6, TRUE))
			_LOGW (LOGD_IP4, "Failed to reapply IPv6 configuration");
	}
}

static void
_pacrunner_manager_add (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	nm_pacrunner_manager_remove_clear (&priv->pacrunner_conf_id);

	priv->pacrunner_conf_id = nm_pacrunner_manager_add (nm_pacrunner_manager_get (),
	                                                    priv->proxy_config,
	                                                    nm_device_get_ip_iface (self),
	                                                    NULL,
	                                                    NULL);
}

static void
reactivate_proxy_config (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (!priv->pacrunner_conf_id)
		return;
	nm_device_set_proxy_config (self, priv->dhcp4.pac_url);
	_pacrunner_manager_add (self);
}

static gboolean
can_reapply_change (NMDevice *self,
                    const char *setting_name,
                    NMSetting *s_old,
                    NMSetting *s_new,
                    GHashTable *diffs,
                    GError **error)
{
	if (nm_streq (setting_name, NM_SETTING_CONNECTION_SETTING_NAME)) {
		/* Whitelist allowed properties from "connection" setting which are
		 * allowed to differ.
		 *
		 * This includes UUID, there is no principal problem with reapplying a
		 * connection and changing its UUID. In fact, disallowing it makes it
		 * cumbersome for the user to reapply any connection but the original
		 * settings-connection. */
		return nm_device_hash_check_invalid_keys (diffs,
		                                          NM_SETTING_CONNECTION_SETTING_NAME,
		                                          error,
		                                          NM_SETTING_CONNECTION_ID,
		                                          NM_SETTING_CONNECTION_UUID,
		                                          NM_SETTING_CONNECTION_STABLE_ID,
		                                          NM_SETTING_CONNECTION_AUTOCONNECT,
		                                          NM_SETTING_CONNECTION_ZONE,
		                                          NM_SETTING_CONNECTION_METERED,
		                                          NM_SETTING_CONNECTION_LLDP,
		                                          NM_SETTING_CONNECTION_MDNS,
		                                          NM_SETTING_CONNECTION_LLMNR);
	} else if (NM_IN_STRSET (setting_name,
	                         NM_SETTING_USER_SETTING_NAME,
	                         NM_SETTING_PROXY_SETTING_NAME,
	                         NM_SETTING_IP4_CONFIG_SETTING_NAME,
	                         NM_SETTING_IP6_CONFIG_SETTING_NAME)) {
		return TRUE;
	} else if (   nm_streq (setting_name, NM_SETTING_WIRED_SETTING_NAME)
	           && NM_IN_SET (NM_DEVICE_GET_CLASS (self)->get_configured_mtu,
	                         nm_device_get_configured_mtu_wired_parent,
	                         nm_device_get_configured_mtu_for_wired)) {
		return nm_device_hash_check_invalid_keys (diffs,
		                                          NM_SETTING_WIRED_SETTING_NAME,
		                                          error,
		                                          NM_SETTING_WIRED_MTU);
	} else {
		g_set_error (error,
		             NM_DEVICE_ERROR,
		             NM_DEVICE_ERROR_INCOMPATIBLE_CONNECTION,
		             "Can't reapply any changes to '%s' setting",
		             setting_name);
		return FALSE;
	}
}

static void
reapply_connection (NMDevice *self, NMConnection *con_old, NMConnection *con_new)
{
}

/* check_and_reapply_connection:
 * @connection: the new connection settings to be applied or %NULL to reapply
 *   the current settings connection
 * @version_id: either zero, or the current version id for the applied
 *   connection.
 * @audit_args: on return, a string representing the changes
 * @error: the error if %FALSE is returned
 *
 * Change configuration of an already configured device if possible.
 * Updates the device's applied connection upon success.
 *
 * Return: %FALSE if the new configuration can not be reapplied.
 */
static gboolean
check_and_reapply_connection (NMDevice *self,
                              NMConnection *connection,
                              guint64 version_id,
                              char **audit_args,
                              GError **error)
{
	NMDeviceClass *klass = NM_DEVICE_GET_CLASS (self);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMConnection *applied = nm_device_get_applied_connection (self);
	gs_unref_object NMConnection *applied_clone = NULL;
	gs_unref_hashtable GHashTable *diffs = NULL;
	NMConnection *con_old, *con_new;
	NMSettingIPConfig *s_ip4_old, *s_ip4_new;
	NMSettingIPConfig *s_ip6_old, *s_ip6_new;
	GHashTableIter iter;

	if (   priv->state < NM_DEVICE_STATE_PREPARE
	    || priv->state > NM_DEVICE_STATE_ACTIVATED) {
		g_set_error_literal (error,
		                     NM_DEVICE_ERROR,
		                     NM_DEVICE_ERROR_NOT_ACTIVE,
		                     "Device is not activated");
		return FALSE;
	}

	nm_connection_diff (connection,
	                    applied,
	                    NM_SETTING_COMPARE_FLAG_IGNORE_TIMESTAMP |
	                    NM_SETTING_COMPARE_FLAG_IGNORE_SECRETS,
	                    &diffs);

	if (audit_args) {
		if (diffs && nm_audit_manager_audit_enabled (nm_audit_manager_get ()))
			*audit_args = nm_utils_format_con_diff_for_audit (diffs);
		else
			*audit_args = NULL;
	}

	/**************************************************************************
	 * check for unsupported changes and reject to reapply
	 *************************************************************************/
	if (diffs) {
		char *setting_name;
		GHashTable *setting_diff;

		g_hash_table_iter_init (&iter, diffs);
		while (g_hash_table_iter_next (&iter, (gpointer *) &setting_name, (gpointer *) &setting_diff)) {
			if (!klass->can_reapply_change (self,
			                                setting_name,
			                                nm_connection_get_setting_by_name (applied, setting_name),
			                                nm_connection_get_setting_by_name (connection, setting_name),
			                                setting_diff,
			                                error))
				return FALSE;
		}
	}

	if (   version_id != 0
	    && version_id != nm_active_connection_version_id_get ((NMActiveConnection *) priv->act_request.obj)) {
		g_set_error_literal (error,
		                     NM_DEVICE_ERROR,
		                     NM_DEVICE_ERROR_VERSION_ID_MISMATCH,
		                     "Reapply failed because device changed in the meantime and the version-id mismatches");
		return FALSE;
	}

	/**************************************************************************
	 * Update applied connection
	 *************************************************************************/

	if (diffs)
		nm_active_connection_version_id_bump ((NMActiveConnection *) priv->act_request.obj);

	_LOGD (LOGD_DEVICE, "reapply (version-id %llu%s)",
	       (unsigned long long) nm_active_connection_version_id_get (((NMActiveConnection *) priv->act_request.obj)),
	       diffs ? "" : " (unmodified)");

	if (diffs) {
		NMConnection *connection_clean = connection;
		gs_unref_object NMConnection *connection_clean_free = NULL;

		{
			NMSettingConnection *s_con_a, *s_con_n;

			/* we allow re-applying a connection with differing ID, UUID, STABLE_ID and AUTOCONNECT.
			 * This is for convenience but these values are not actually changeable. So, check
			 * if they changed, and if the did revert to the original values. */
			s_con_a = nm_connection_get_setting_connection (applied);
			s_con_n = nm_connection_get_setting_connection (connection);

			if (   !nm_streq (nm_setting_connection_get_id (s_con_a), nm_setting_connection_get_id (s_con_n))
			    || !nm_streq (nm_setting_connection_get_uuid (s_con_a), nm_setting_connection_get_uuid (s_con_n))
			    || nm_setting_connection_get_autoconnect (s_con_a) != nm_setting_connection_get_autoconnect (s_con_n)
			    || !nm_streq0 (nm_setting_connection_get_stable_id (s_con_a), nm_setting_connection_get_stable_id (s_con_n))) {
				connection_clean_free = nm_simple_connection_new_clone (connection);
				connection_clean = connection_clean_free;
				s_con_n = nm_connection_get_setting_connection (connection_clean);
				g_object_set (s_con_n,
				              NM_SETTING_CONNECTION_ID, nm_setting_connection_get_id (s_con_a),
				              NM_SETTING_CONNECTION_UUID, nm_setting_connection_get_uuid (s_con_a),
				              NM_SETTING_CONNECTION_AUTOCONNECT, nm_setting_connection_get_autoconnect (s_con_a),
				              NM_SETTING_CONNECTION_STABLE_ID, nm_setting_connection_get_stable_id (s_con_a),
				              NULL);
			}
		}

		con_old = applied_clone  = nm_simple_connection_new_clone (applied);
		con_new = applied;
		nm_connection_replace_settings_from_connection (applied, connection_clean);
		nm_connection_clear_secrets (applied);
	} else
		con_old = con_new = applied;

	priv->v4_commit_first_time = TRUE;
	priv->v6_commit_first_time = TRUE;

	priv->v4_route_table_initialized = FALSE;
	priv->v6_route_table_initialized = FALSE;
	priv->l3config_merge_flags_has = FALSE;

	/**************************************************************************
	 * Reapply changes
	 *
	 * Note that reapply_connection() is called as very first. This is for example
	 * important for NMDeviceWireGuard, which implements coerce_route_table()
	 * and get_extra_rules().
	 * That is because NMDeviceWireGuard caches settings, so during reapply that
	 * cache must be updated *first*.
	 *************************************************************************/
	klass->reapply_connection (self, con_old, con_new);

	if (priv->state >= NM_DEVICE_STATE_CONFIG)
		lldp_init (self, FALSE);

	if (priv->state >= NM_DEVICE_STATE_IP_CONFIG) {
		s_ip4_old = nm_connection_get_setting_ip4_config (con_old);
		s_ip4_new = nm_connection_get_setting_ip4_config (con_new);
		s_ip6_old = nm_connection_get_setting_ip6_config (con_old);
		s_ip6_new = nm_connection_get_setting_ip6_config (con_new);

		/* Allow reapply of MTU */
		priv->mtu_source = NM_DEVICE_MTU_SOURCE_NONE;

		nm_device_reactivate_ip4_config (self, s_ip4_old, s_ip4_new);
		nm_device_reactivate_ip6_config (self, s_ip6_old, s_ip6_new);

		_routing_rules_sync (self, NM_TERNARY_TRUE);

		reactivate_proxy_config (self);
	}

	if (priv->state >= NM_DEVICE_STATE_IP_CHECK)
		nm_device_update_firewall_zone (self);

	if (priv->state >= NM_DEVICE_STATE_ACTIVATED)
		nm_device_update_metered (self);

	return TRUE;
}

gboolean
nm_device_reapply (NMDevice *self,
                   NMConnection *connection,
                   GError **error)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	return check_and_reapply_connection (self,
	                                     connection,
	                                     0,
	                                     NULL,
	                                     error);
}

typedef struct {
	NMConnection *connection;
	guint64 version_id;
} ReapplyData;

static void
reapply_cb (NMDevice *self,
            GDBusMethodInvocation *context,
            NMAuthSubject *subject,
            GError *error,
            gpointer user_data)
{
	ReapplyData *reapply_data = user_data;
	guint64 version_id = 0;
	gs_unref_object NMConnection *connection = NULL;
	GError *local = NULL;
	gs_free char *audit_args = NULL;

	if (reapply_data) {
		connection = reapply_data->connection;
		version_id = reapply_data->version_id;
		g_slice_free (ReapplyData, reapply_data);
	}

	if (error) {
		nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_REAPPLY, self, FALSE, NULL, subject, error->message);
		g_dbus_method_invocation_return_gerror (context, error);
		return;
	}

	if (nm_device_sys_iface_state_is_external (self))
		nm_device_sys_iface_state_set (self, NM_DEVICE_SYS_IFACE_STATE_MANAGED);

	if (!check_and_reapply_connection (self,
	                                   connection ?: nm_device_get_settings_connection_get_connection (self),
	                                   version_id,
	                                   &audit_args,
	                                   &local)) {
		nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_REAPPLY, self, FALSE, audit_args, subject, local->message);
		g_dbus_method_invocation_take_error (context, local);
		local = NULL;
	} else {
		nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_REAPPLY, self, TRUE, audit_args, subject, NULL);
		g_dbus_method_invocation_return_value (context, NULL);
	}
}

static void
impl_device_reapply (NMDBusObject *obj,
                     const NMDBusInterfaceInfoExtended *interface_info,
                     const NMDBusMethodInfoExtended *method_info,
                     GDBusConnection *dbus_connection,
                     const char *sender,
                     GDBusMethodInvocation *invocation,
                     GVariant *parameters)
{
	NMDevice *self = NM_DEVICE (obj);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMSettingsConnection *settings_connection;
	NMConnection *connection = NULL;
	GError *error = NULL;
	ReapplyData *reapply_data;
	gs_unref_variant GVariant *settings = NULL;
	guint64 version_id;
	guint32 flags;

	g_variant_get (parameters, "(@a{sa{sv}}tu)", &settings, &version_id, &flags);

	/* No flags supported as of now. */
	if (flags != 0) {
		error = g_error_new_literal (NM_DEVICE_ERROR,
		                             NM_DEVICE_ERROR_FAILED,
		                             "Invalid flags specified");
		nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_REAPPLY, self, FALSE, NULL, invocation, error->message);
		g_dbus_method_invocation_take_error (invocation, error);
		return;
	}

	if (   priv->state < NM_DEVICE_STATE_PREPARE
	    || priv->state > NM_DEVICE_STATE_ACTIVATED) {
		error = g_error_new_literal (NM_DEVICE_ERROR,
		                             NM_DEVICE_ERROR_NOT_ACTIVE,
		                             "Device is not activated");
		nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_REAPPLY, self, FALSE, NULL, invocation, error->message);
		g_dbus_method_invocation_take_error (invocation, error);
		return;
	}

	settings_connection = nm_device_get_settings_connection (self);
	g_return_if_fail (settings_connection);

	if (settings && g_variant_n_children (settings)) {
		/* New settings specified inline. */
		connection = _nm_simple_connection_new_from_dbus (settings,
		                                                    NM_SETTING_PARSE_FLAGS_STRICT
		                                                  | NM_SETTING_PARSE_FLAGS_NORMALIZE,
		                                                  &error);
		if (!connection) {
			g_prefix_error (&error, "The settings specified are invalid: ");
			nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_REAPPLY, self, FALSE, NULL, invocation, error->message);
			g_dbus_method_invocation_take_error (invocation, error);
			return;
		}
		nm_connection_clear_secrets (connection);
	}

	if (connection || version_id) {
		reapply_data = g_slice_new (ReapplyData);
		reapply_data->connection = connection;
		reapply_data->version_id = version_id;
	} else
		reapply_data = NULL;

	nm_device_auth_request (self,
	                        invocation,
	                        nm_device_get_applied_connection (self),
	                        NM_AUTH_PERMISSION_NETWORK_CONTROL,
	                        TRUE,
	                        NULL,
	                        reapply_cb,
	                        reapply_data);
}

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

static void
get_applied_connection_cb (NMDevice *self,
                           GDBusMethodInvocation *context,
                           NMAuthSubject *subject,
                           GError *error,
                           gpointer user_data /* possibly dangling pointer */)
{
	NMDevicePrivate *priv;
	NMConnection *applied_connection;
	GVariant *settings;

	g_return_if_fail (NM_IS_DEVICE (self));

	if (error) {
		g_dbus_method_invocation_return_gerror (context, error);
		return;
	}

	priv = NM_DEVICE_GET_PRIVATE (self);

	applied_connection = nm_device_get_applied_connection (self);

	if (!applied_connection) {
		error = g_error_new_literal (NM_DEVICE_ERROR,
		                             NM_DEVICE_ERROR_NOT_ACTIVE,
		                             "Device is not activated");
		g_dbus_method_invocation_take_error (context, error);
		return;
	}

	if (applied_connection != user_data) {
		/* The applied connection changed due to a race. Reauthenticate. */
		nm_device_auth_request (self,
		                        context,
		                        applied_connection,
		                        NM_AUTH_PERMISSION_NETWORK_CONTROL,
		                        TRUE,
		                        NULL,
		                        get_applied_connection_cb,
		                        applied_connection /* no need take a ref. We will not dereference this pointer. */);
		return;
	}

	settings = nm_connection_to_dbus (applied_connection, NM_CONNECTION_SERIALIZE_NO_SECRETS);
	if (!settings)
		settings = g_variant_new_array (G_VARIANT_TYPE ("{sa{sv}}"), NULL, 0);

	g_dbus_method_invocation_return_value (context,
	                                       g_variant_new ("(@a{sa{sv}}t)",
	                                                      settings,
	                                                      nm_active_connection_version_id_get ((NMActiveConnection *) priv->act_request.obj)));
}

static void
impl_device_get_applied_connection (NMDBusObject *obj,
                                    const NMDBusInterfaceInfoExtended *interface_info,
                                    const NMDBusMethodInfoExtended *method_info,
                                    GDBusConnection *connection,
                                    const char *sender,
                                    GDBusMethodInvocation *invocation,
                                    GVariant *parameters)
{
	NMDevice *self = NM_DEVICE (obj);
	NMConnection *applied_connection;
	guint32 flags;

	g_variant_get (parameters, "(u)", &flags);

	/* No flags supported as of now. */
	if (flags != 0) {
		g_dbus_method_invocation_return_error_literal (invocation,
		                                               NM_DEVICE_ERROR,
		                                               NM_DEVICE_ERROR_FAILED,
		                                               "Invalid flags specified");
		return;
	}

	applied_connection = nm_device_get_applied_connection (self);
	if (!applied_connection) {
		g_dbus_method_invocation_return_error_literal (invocation,
		                                               NM_DEVICE_ERROR,
		                                               NM_DEVICE_ERROR_NOT_ACTIVE,
		                                               "Device is not activated");
		return;
	}

	nm_device_auth_request (self,
	                        invocation,
	                        applied_connection,
	                        NM_AUTH_PERMISSION_NETWORK_CONTROL,
	                        TRUE,
	                        NULL,
	                        get_applied_connection_cb,
	                        applied_connection /* no need take a ref. We will not dereference this pointer. */);
}

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

typedef struct {
	gint64 timestamp_ms;
	bool dirty;
} IP6RoutesTemporaryNotAvailableData;

static gboolean
_rt6_temporary_not_available_timeout (gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	priv->rt6_temporary_not_available_id = 0;
	nm_device_activate_schedule_ip_config_result (self, AF_INET6, NULL);

	return G_SOURCE_REMOVE;
}

static gboolean
_rt6_temporary_not_available_set (NMDevice *self,
                                  GPtrArray *temporary_not_available)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	IP6RoutesTemporaryNotAvailableData *data;
	GHashTableIter iter;
	gint64 now_ms, oldest_ms;
	const gint64 MAX_AGE_MS = 20000;
	guint i;
	gboolean success = TRUE;

	if (   !temporary_not_available
	    || !temporary_not_available->len) {
		/* nothing outstanding. Clear tracking the routes. */
		nm_clear_pointer (&priv->rt6_temporary_not_available, g_hash_table_unref);
		nm_clear_g_source (&priv->rt6_temporary_not_available_id);
		return success;
	}

	if (priv->rt6_temporary_not_available) {
		g_hash_table_iter_init (&iter, priv->rt6_temporary_not_available);
		while (g_hash_table_iter_next (&iter, NULL, (gpointer *) &data))
			data->dirty = TRUE;
	} else {
		priv->rt6_temporary_not_available = g_hash_table_new_full ((GHashFunc) nmp_object_id_hash,
		                                                           (GEqualFunc) nmp_object_id_equal,
		                                                           (GDestroyNotify) nmp_object_unref,
		                                                           nm_g_slice_free_fcn (IP6RoutesTemporaryNotAvailableData));
	}

	now_ms = nm_utils_get_monotonic_timestamp_msec ();
	oldest_ms = now_ms;

	for (i = 0; i < temporary_not_available->len; i++) {
		const NMPObject *o = temporary_not_available->pdata[i];

		data = g_hash_table_lookup (priv->rt6_temporary_not_available, o);
		if (data) {
			if (!data->dirty)
				continue;
			data->dirty = FALSE;
			nm_assert (data->timestamp_ms > 0 && data->timestamp_ms <= now_ms);
			if (now_ms > data->timestamp_ms + MAX_AGE_MS) {
				/* timeout. Could not add this address. */
				_LOGW (LOGD_DEVICE, "failure to add IPv6 route: %s",
				       nmp_object_to_string (o, NMP_OBJECT_TO_STRING_PUBLIC, NULL, 0));
				success = FALSE;
			} else
				oldest_ms = MIN (data->timestamp_ms, oldest_ms);
			continue;
		}

		data = g_slice_new0 (IP6RoutesTemporaryNotAvailableData);
		data->timestamp_ms = now_ms;
		g_hash_table_insert (priv->rt6_temporary_not_available, (gpointer) nmp_object_ref (o), data);
	}

	g_hash_table_iter_init (&iter, priv->rt6_temporary_not_available);
	while (g_hash_table_iter_next (&iter, NULL, (gpointer *) &data)) {
		if (data->dirty)
			g_hash_table_iter_remove (&iter);
	}

	nm_clear_g_source (&priv->rt6_temporary_not_available_id);
	priv->rt6_temporary_not_available_id = g_timeout_add (oldest_ms + MAX_AGE_MS - now_ms,
	                                                      _rt6_temporary_not_available_timeout,
	                                                      self);

	return success;
}

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

static void
disconnect_cb (NMDevice *self,
               GDBusMethodInvocation *context,
               NMAuthSubject *subject,
               GError *error,
               gpointer user_data)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	GError *local = NULL;

	if (error) {
		g_dbus_method_invocation_return_gerror (context, error);
		nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_DISCONNECT, self, FALSE, NULL, subject, error->message);
		return;
	}

	/* Authorized */
	if (priv->state <= NM_DEVICE_STATE_DISCONNECTED) {
		local = g_error_new_literal (NM_DEVICE_ERROR,
		                             NM_DEVICE_ERROR_NOT_ACTIVE,
		                             "Device is not active");
		nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_DISCONNECT, self, FALSE, NULL, subject, local->message);
		g_dbus_method_invocation_take_error (context, local);
	} else {
		nm_device_autoconnect_blocked_set (self, NM_DEVICE_AUTOCONNECT_BLOCKED_MANUAL_DISCONNECT);

		nm_device_state_changed (self,
		                         NM_DEVICE_STATE_DEACTIVATING,
		                         NM_DEVICE_STATE_REASON_USER_REQUESTED);
		g_dbus_method_invocation_return_value (context, NULL);
		nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_DISCONNECT, self, TRUE, NULL, subject, NULL);
	}
}

static void
_clear_queued_act_request (NMDevicePrivate *priv,
                           NMActiveConnectionStateReason active_reason)
{
	if (priv->queued_act_request) {
		gs_unref_object NMActRequest *ac = NULL;

		ac = g_steal_pointer (&priv->queued_act_request);
		nm_active_connection_set_state_fail ((NMActiveConnection *) ac,
		                                     active_reason,
		                                     NULL);
	}
}

static void
impl_device_disconnect (NMDBusObject *obj,
                        const NMDBusInterfaceInfoExtended *interface_info,
                        const NMDBusMethodInfoExtended *method_info,
                        GDBusConnection *dbus_connection,
                        const char *sender,
                        GDBusMethodInvocation *invocation,
                        GVariant *parameters)
{
	NMDevice *self = NM_DEVICE (obj);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMConnection *connection;

	if (!priv->act_request.obj) {
		g_dbus_method_invocation_return_error_literal (invocation,
		                                               NM_DEVICE_ERROR,
		                                               NM_DEVICE_ERROR_NOT_ACTIVE,
		                                               "This device is not active");
		return;
	}

	connection = nm_device_get_applied_connection (self);
	nm_assert (connection);

	nm_device_auth_request (self,
	                        invocation,
	                        connection,
	                        NM_AUTH_PERMISSION_NETWORK_CONTROL,
	                        TRUE,
	                        NULL,
	                        disconnect_cb,
	                        NULL);
}

static void
delete_cb (NMDevice *self,
           GDBusMethodInvocation *context,
           NMAuthSubject *subject,
           GError *error,
           gpointer user_data)
{
	GError *local = NULL;

	if (error) {
		g_dbus_method_invocation_return_gerror (context, error);
		nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_DELETE, self, FALSE, NULL, subject, error->message);
		return;
	}

	/* Authorized */
	nm_audit_log_device_op (NM_AUDIT_OP_DEVICE_DELETE, self, TRUE, NULL, subject, NULL);
	if (nm_device_unrealize (self, TRUE, &local))
		g_dbus_method_invocation_return_value (context, NULL);
	else
		g_dbus_method_invocation_take_error (context, local);
}

static void
impl_device_delete (NMDBusObject *obj,
                    const NMDBusInterfaceInfoExtended *interface_info,
                    const NMDBusMethodInfoExtended *method_info,
                    GDBusConnection *connection,
                    const char *sender,
                    GDBusMethodInvocation *invocation,
                    GVariant *parameters)
{
	NMDevice *self = NM_DEVICE (obj);

	if (   !nm_device_is_software (self)
	    || !nm_device_is_real (self)) {
		g_dbus_method_invocation_return_error_literal (invocation,
		                                               NM_DEVICE_ERROR,
		                                               NM_DEVICE_ERROR_NOT_SOFTWARE,
		                                               "This device is not a software device or is not realized");
		return;
	}

	nm_device_auth_request (self,
	                        invocation,
	                        NULL,
	                        NM_AUTH_PERMISSION_NETWORK_CONTROL,
	                        TRUE,
	                        NULL,
	                        delete_cb,
	                        NULL);
}

static void
_device_activate (NMDevice *self, NMActRequest *req)
{
	NMConnection *connection;

	g_return_if_fail (NM_IS_DEVICE (self));
	g_return_if_fail (NM_IS_ACT_REQUEST (req));
	nm_assert (nm_device_is_real (self));

	/* Ensure the activation request is still valid; the master may have
	 * already failed in which case activation of this device should not proceed.
	 */
	if (nm_active_connection_get_state (NM_ACTIVE_CONNECTION (req)) >= NM_ACTIVE_CONNECTION_STATE_DEACTIVATING)
		return;

	if (!nm_device_get_managed (self, FALSE)) {
		/* It's unclear why the device would be unmanaged at this point.
		 * Just to be sure, handle it and error out. */
		_LOGE (LOGD_DEVICE, "Activation: failed activating connection '%s' because device is still unmanaged",
		       nm_active_connection_get_settings_connection_id ((NMActiveConnection *) req));
		nm_active_connection_set_state_fail ((NMActiveConnection *) req,
		                                     NM_ACTIVE_CONNECTION_STATE_REASON_UNKNOWN,
		                                     NULL);
		return;
	}

	connection = nm_act_request_get_applied_connection (req);
	nm_assert (connection);

	_LOGI (LOGD_DEVICE, "Activation: starting connection '%s' (%s)",
	       nm_connection_get_id (connection),
	       nm_connection_get_uuid (connection));

	delete_on_deactivate_unschedule (self);

	act_request_set (self, req);

	nm_device_activate_schedule_stage1_device_prepare (self, FALSE);
}

static void
_carrier_wait_check_queued_act_request (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (   !priv->queued_act_request
	    || !priv->queued_act_request_is_waiting_for_carrier)
		return;

	priv->queued_act_request_is_waiting_for_carrier = FALSE;
	if (!priv->carrier) {
		_LOGD (LOGD_DEVICE, "Cancel queued activation request as we have no carrier after timeout");
		_clear_queued_act_request (priv,
		                           NM_ACTIVE_CONNECTION_STATE_REASON_DEVICE_DISCONNECTED);
	} else if (priv->state == NM_DEVICE_STATE_DISCONNECTED) {
		gs_unref_object NMActRequest *queued_req = NULL;

		_LOGD (LOGD_DEVICE, "Activate queued activation request as we now have carrier");
		queued_req = g_steal_pointer (&priv->queued_act_request);
		_device_activate (self, queued_req);
	}
}

static gboolean
_carrier_wait_check_act_request_must_queue (NMDevice *self, NMActRequest *req)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMConnection *connection;

	/* If we have carrier or if we are not waiting for it, the activation
	 * request is not blocked waiting for carrier. */
	if (priv->carrier)
		return FALSE;
	if (priv->carrier_wait_id == 0)
		return FALSE;

	connection = nm_act_request_get_applied_connection (req);
	if (!connection_requires_carrier (connection))
		return FALSE;

	if (!nm_device_check_connection_available (self, connection, NM_DEVICE_CHECK_CON_AVAILABLE_ALL, NULL, NULL)) {
		/* We passed all @flags we have, and no @specific_object.
		 * This equals maximal availability, if a connection is not available
		 * in this case, it is not waiting for carrier.
		 *
		 * Actually, why are we even trying to activate it? Strange, but whatever
		 * the reason, don't wait for carrier.
		 */
		return FALSE;
	}

	if (nm_device_check_connection_available (self, connection,
	                                          NM_DEVICE_CHECK_CON_AVAILABLE_ALL & ~_NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST_WAITING_CARRIER,
	                                          NULL, NULL)) {
		/* The connection was available with flags ALL, and it is still available
		 * if we pretend not to wait for carrier. That means that the
		 * connection is available now, and does not wait for carrier.
		 *
		 * Since the flags increase the availability of a connection, when checking
		 * ALL&~WAITING_CARRIER, it means that we certainly would wait for carrier. */
		return FALSE;
	}

	/* The activation request must wait for carrier. */
	return TRUE;
}

void
nm_device_disconnect_active_connection (NMActiveConnection *active,
                                        NMDeviceStateReason device_reason,
                                        NMActiveConnectionStateReason active_reason)
{
	NMDevice *self;
	NMDevicePrivate *priv;

	g_return_if_fail (NM_IS_ACTIVE_CONNECTION (active));

	self = nm_active_connection_get_device (active);
	if (!self) {
		/* hm, no device? Just fail the active connection. */
		goto do_fail;
	}

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (NM_ACTIVE_CONNECTION (priv->queued_act_request) == active) {
		_clear_queued_act_request (priv, active_reason);
		return;
	}

	if (NM_ACTIVE_CONNECTION (priv->act_request.obj) == active) {
		if (priv->state < NM_DEVICE_STATE_DEACTIVATING) {
			nm_device_state_changed (self,
			                         NM_DEVICE_STATE_DEACTIVATING,
			                         device_reason);
		} else {
			/* @active is the current ac of @self, but it's going down already.
			 * Nothing to do. */
		}
		return;
	}

	/* the active connection references this device, but it's neither the
	 * queued_act_request nor the current act_request. Just set it to fail... */
do_fail:
	nm_active_connection_set_state_fail (active,
	                                     active_reason,
	                                     NULL);
}

void
nm_device_queue_activation (NMDevice *self, NMActRequest *req)
{
	NMDevicePrivate *priv;
	gboolean must_queue;

	g_return_if_fail (NM_IS_DEVICE (self));
	g_return_if_fail (NM_IS_ACT_REQUEST (req));

	nm_keep_alive_arm (nm_active_connection_get_keep_alive (NM_ACTIVE_CONNECTION (req)));

	if (nm_active_connection_get_state (NM_ACTIVE_CONNECTION (req)) >= NM_ACTIVE_CONNECTION_STATE_DEACTIVATING) {
		/* it's already deactivating. Nothing to do. */
		nm_assert (NM_IN_SET (nm_active_connection_get_device (NM_ACTIVE_CONNECTION (req)), NULL, self));
		return;
	}

	nm_assert (self == nm_active_connection_get_device (NM_ACTIVE_CONNECTION (req)));

	priv = NM_DEVICE_GET_PRIVATE (self);

	must_queue = _carrier_wait_check_act_request_must_queue (self, req);

	if (   !priv->act_request.obj
	    && !must_queue
	    && nm_device_is_real (self)) {
		_device_activate (self, req);
		return;
	}

	/* supersede any already-queued request */
	_clear_queued_act_request (priv,
	                           NM_ACTIVE_CONNECTION_STATE_REASON_DEVICE_DISCONNECTED);
	priv->queued_act_request = g_object_ref (req);
	priv->queued_act_request_is_waiting_for_carrier = must_queue;

	_LOGD (LOGD_DEVICE, "queue activation request waiting for %s", must_queue ? "carrier" : "currently active connection to disconnect");

	/* Deactivate existing activation request first */
	if (priv->act_request.obj) {
		_LOGI (LOGD_DEVICE, "disconnecting for new activation request.");
		nm_device_state_changed (self,
		                         NM_DEVICE_STATE_DEACTIVATING,
		                         NM_DEVICE_STATE_REASON_NEW_ACTIVATION);
	}
}

/*
 * nm_device_is_activating
 *
 * Return whether or not the device is currently activating itself.
 *
 */
gboolean
nm_device_is_activating (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMDeviceState state;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	state = nm_device_get_state (self);
	if (state >= NM_DEVICE_STATE_PREPARE && state <= NM_DEVICE_STATE_SECONDARIES)
		return TRUE;

	/* There's a small race between the time when stage 1 is scheduled
	 * and when the device actually sets STATE_PREPARE when the activation
	 * handler is actually run.  If there's an activation handler scheduled
	 * we're activating anyway.
	 */
	return priv->activation_source_id_4 != 0;
}

NMProxyConfig *
nm_device_get_proxy_config (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), NULL);

	return NM_DEVICE_GET_PRIVATE (self)->proxy_config;
}

static void
nm_device_set_proxy_config (NMDevice *self, const char *pac_url)
{
	NMDevicePrivate *priv;
	NMConnection *connection;
	NMSettingProxy *s_proxy = NULL;

	g_return_if_fail (NM_IS_DEVICE (self));

	priv = NM_DEVICE_GET_PRIVATE (self);

	g_clear_object (&priv->proxy_config);
	priv->proxy_config = nm_proxy_config_new ();

	if (pac_url) {
		nm_proxy_config_set_method (priv->proxy_config, NM_PROXY_CONFIG_METHOD_AUTO);
		nm_proxy_config_set_pac_url (priv->proxy_config, pac_url);
		_LOGD (LOGD_PROXY, "proxy: PAC url \"%s\"", pac_url);
	} else
		nm_proxy_config_set_method (priv->proxy_config, NM_PROXY_CONFIG_METHOD_NONE);

	connection = nm_device_get_applied_connection (self);
	if (connection)
		s_proxy = nm_connection_get_setting_proxy (connection);

	if (s_proxy)
		nm_proxy_config_merge_setting (priv->proxy_config, s_proxy);
}

/* IP Configuration stuff */
NMDhcpConfig *
nm_device_get_dhcp_config (NMDevice *self, int addr_family)
{
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	g_return_val_if_fail (NM_IS_DEVICE (self), NULL);

	nm_assert_addr_family (addr_family);

	return NM_DEVICE_GET_PRIVATE (self)->dhcp_data_x[IS_IPv4].config;
}

NMIP4Config *
nm_device_get_ip4_config (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), NULL);

	return NM_DEVICE_GET_PRIVATE (self)->ip_config_4;
}

static gboolean
nm_device_set_ip_config (NMDevice *self,
                         int addr_family,
                         NMIPConfig *new_config,
                         gboolean commit,
                         GPtrArray *ip4_dev_route_blacklist)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const gboolean IS_IPv4 = (addr_family == AF_INET);
	NMIPConfig *old_config;
	gboolean has_changes = FALSE;
	gboolean success = TRUE;
	NMSettingsConnection *settings_connection;

	nm_assert_addr_family (addr_family);
	nm_assert (!new_config || nm_ip_config_get_addr_family (new_config) == addr_family);
	nm_assert (   !new_config
	           || (   new_config
	               && ({
	                    int ip_ifindex = nm_device_get_ip_ifindex (self);

	                    (   ip_ifindex > 0
	                     && ip_ifindex == nm_ip_config_get_ifindex (new_config));
	                  })));
	nm_assert (IS_IPv4 || !ip4_dev_route_blacklist);

	_LOGD (LOGD_IP_from_af (addr_family),
	       "ip%c-config: update (commit=%d, new-config=%p)",
	       nm_utils_addr_family_to_char (addr_family),
	       commit,
	       new_config);

	/* Always commit to nm-platform to update lifetimes */
	if (commit && new_config) {

		_commit_mtu (self,
		             IS_IPv4
		               ? NM_IP4_CONFIG (new_config)
		               : priv->ip_config_4);

		if (IS_IPv4) {
			success = nm_ip4_config_commit (NM_IP4_CONFIG (new_config),
			                                nm_device_get_platform (self),
			                                _get_route_table_sync_mode_stateful (self,
			                                                                     AF_INET));
			nm_platform_ip4_dev_route_blacklist_set (nm_device_get_platform (self),
			                                         nm_ip_config_get_ifindex (new_config),
			                                         ip4_dev_route_blacklist);
		} else {
			gs_unref_ptrarray GPtrArray *temporary_not_available = NULL;

			success = nm_ip6_config_commit (NM_IP6_CONFIG (new_config),
			                                nm_device_get_platform (self),
			                                _get_route_table_sync_mode_stateful (self,
			                                                                     AF_INET6),
			                                &temporary_not_available);

			if (!_rt6_temporary_not_available_set (self, temporary_not_available))
				success = FALSE;
		}
	}

	old_config = priv->ip_config_x[IS_IPv4];

	if (new_config && old_config) {
		/* has_changes is set only on relevant changes, because when the configuration changes,
		 * this causes a re-read and reset. This should only happen for relevant changes */
		nm_ip_config_replace (old_config, new_config, &has_changes);
		if (has_changes) {
			_LOGD (LOGD_IP_from_af (addr_family),
			       "ip%c-config: update IP Config instance (%s)",
			       nm_utils_addr_family_to_char (addr_family),
			       nm_dbus_object_get_path (NM_DBUS_OBJECT (old_config)));
		}
	} else if (new_config /*&& !old_config*/) {
		has_changes = TRUE;
		priv->ip_config_x[IS_IPv4] = g_object_ref (new_config);
		if (!nm_dbus_object_is_exported (NM_DBUS_OBJECT (new_config)))
			nm_dbus_object_export (NM_DBUS_OBJECT (new_config));

		_LOGD (LOGD_IP_from_af (addr_family),
		       "ip%c-config: set IP Config instance (%s)",
		       nm_utils_addr_family_to_char (addr_family),
		       nm_dbus_object_get_path (NM_DBUS_OBJECT (new_config)));
	} else if (old_config /*&& !new_config*/) {
		has_changes = TRUE;
		priv->ip_config_x[IS_IPv4] = NULL;
		_LOGD (LOGD_IP_from_af (addr_family),
		       "ip%c-config: clear IP Config instance (%s)",
		       nm_utils_addr_family_to_char (addr_family),
		       nm_dbus_object_get_path (NM_DBUS_OBJECT (old_config)));
		if (IS_IPv4) {
			/* Device config is invalid if combined config is invalid */
			applied_config_clear (&priv->dev_ip_config_4);
		} else
			priv->needs_ip6_subnet = FALSE;
	}

	if (has_changes) {

		if (IS_IPv4)
			_update_ip4_address (self);

		if (old_config != priv->ip_config_x[IS_IPv4])
			_notify (self, IS_IPv4 ? PROP_IP4_CONFIG : PROP_IP6_CONFIG);

		g_signal_emit (self,
		               signals[IS_IPv4 ? IP4_CONFIG_CHANGED : IP6_CONFIG_CHANGED],
		               0,
		               priv->ip_config_x[IS_IPv4],
		               old_config);

		if (old_config != priv->ip_config_x[IS_IPv4])
			nm_dbus_object_clear_and_unexport (&old_config);

		if (   nm_device_sys_iface_state_is_external (self)
		    && (settings_connection = nm_device_get_settings_connection (self))
		    && NM_FLAGS_HAS (nm_settings_connection_get_flags (settings_connection),
		                     NM_SETTINGS_CONNECTION_INT_FLAGS_EXTERNAL)
		    && nm_active_connection_get_activation_type (NM_ACTIVE_CONNECTION (priv->act_request.obj)) == NM_ACTIVATION_TYPE_EXTERNAL) {
			gs_unref_object NMConnection *new_connection = NULL;

			new_connection = nm_simple_connection_new_clone (nm_settings_connection_get_connection (settings_connection));

			nm_connection_add_setting (new_connection,
			                             IS_IPv4
			                           ? nm_ip4_config_create_setting (priv->ip_config_4)
			                           : nm_ip6_config_create_setting (priv->ip_config_6,
			                                                           _get_maybe_ipv6_disabled (self)));

			nm_settings_connection_update (settings_connection,
			                               new_connection,
			                               NM_SETTINGS_CONNECTION_PERSIST_MODE_IN_MEMORY,
			                               NM_SETTINGS_CONNECTION_INT_FLAGS_NONE,
			                               NM_SETTINGS_CONNECTION_INT_FLAGS_NONE,
			                               NM_SETTINGS_CONNECTION_UPDATE_REASON_NONE,
			                               "update-external",
			                               NULL);
		}

		nm_device_queue_recheck_assume (self);

		if (!IS_IPv4) {
			if (priv->ndisc)
				ndisc_set_router_config (priv->ndisc, self);
		}
	}

	nm_assert (!old_config || old_config == priv->ip_config_x[IS_IPv4]);

	return success;
}

static gboolean
_replace_vpn_config_in_list (GSList **plist, GObject *old, GObject *new)
{
	GSList *old_link;

	/* Below, assert that @new is not yet tracked, but still behave
	 * correctly in any case. Don't complain for missing @old since
	 * it could have been removed when the parent device became
	 * unmanaged. */

	if (   old
	    && (old_link = g_slist_find (*plist, old))) {
		if (old != new) {
			if (new)
				old_link->data = g_object_ref (new);
			else
				*plist = g_slist_delete_link (*plist, old_link);
			g_object_unref (old);
		}
		return TRUE;
	}

	if (new) {
		if (!g_slist_find (*plist, new))
			*plist = g_slist_append (*plist, g_object_ref (new));
		else
			g_return_val_if_reached (TRUE);
		return TRUE;
	}

	return FALSE;
}

void
nm_device_replace_vpn4_config (NMDevice *self, NMIP4Config *old, NMIP4Config *config)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	nm_assert (!old || NM_IS_IP4_CONFIG (old));
	nm_assert (!config || NM_IS_IP4_CONFIG (config));
	nm_assert (!old || nm_ip4_config_get_ifindex (old) == nm_device_get_ip_ifindex (self));
	nm_assert (!config || nm_ip4_config_get_ifindex (config) == nm_device_get_ip_ifindex (self));

	if (!_replace_vpn_config_in_list (&priv->vpn_configs_4, (GObject *) old, (GObject *) config))
		return;

	/* NULL to use existing configs */
	if (!ip_config_merge_and_apply (self, AF_INET, TRUE))
		_LOGW (LOGD_IP4, "failed to set VPN routes for device");
}

void
nm_device_set_dev2_ip_config (NMDevice *self,
                              int addr_family,
                              NMIPConfig *config)
{
	NMDevicePrivate *priv;
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	g_return_if_fail (NM_IS_DEVICE (self));
	g_return_if_fail (NM_IN_SET (addr_family, AF_INET, AF_INET6));
	g_return_if_fail (   !config
	                  || nm_ip_config_get_addr_family (config) == addr_family);

	priv = NM_DEVICE_GET_PRIVATE (self);

	applied_config_init (&priv->dev2_ip_config_x[IS_IPv4], config);
	if (!ip_config_merge_and_apply (self, addr_family, TRUE)) {
		_LOGW (LOGD_IP, "failed to set extra device IPv%c configuration",
		       nm_utils_addr_family_to_char (addr_family));
	}
}

void
nm_device_replace_vpn6_config (NMDevice *self, NMIP6Config *old, NMIP6Config *config)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	nm_assert (!old || NM_IS_IP6_CONFIG (old));
	nm_assert (!config || NM_IS_IP6_CONFIG (config));
	nm_assert (!old || nm_ip6_config_get_ifindex (old) == nm_device_get_ip_ifindex (self));
	nm_assert (!config || nm_ip6_config_get_ifindex (config) == nm_device_get_ip_ifindex (self));

	if (!_replace_vpn_config_in_list (&priv->vpn_configs_6, (GObject *) old, (GObject *) config))
		return;

	/* NULL to use existing configs */
	if (!ip_config_merge_and_apply (self, AF_INET6, TRUE))
		_LOGW (LOGD_IP6, "failed to set VPN routes for device");
}

NMIP6Config *
nm_device_get_ip6_config (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), NULL);

	return NM_DEVICE_GET_PRIVATE (self)->ip_config_6;
}

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

static gboolean
dispatcher_cleanup (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (!priv->dispatcher.call_id)
		return FALSE;

	nm_dispatcher_call_cancel (g_steal_pointer (&priv->dispatcher.call_id));
	priv->dispatcher.post_state = NM_DEVICE_STATE_UNKNOWN;
	priv->dispatcher.post_state_reason = NM_DEVICE_STATE_REASON_NONE;
	return TRUE;
}

static void
dispatcher_complete_proceed_state (NMDispatcherCallId *call_id, gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	g_return_if_fail (call_id == priv->dispatcher.call_id);

	priv->dispatcher.call_id = NULL;
	nm_device_queue_state (self,
	                       priv->dispatcher.post_state,
	                       priv->dispatcher.post_state_reason);
	priv->dispatcher.post_state = NM_DEVICE_STATE_UNKNOWN;
	priv->dispatcher.post_state_reason = NM_DEVICE_STATE_REASON_NONE;
}

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

static void
ip_check_pre_up (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (dispatcher_cleanup (self))
		nm_assert_not_reached ();

	priv->dispatcher.post_state = NM_DEVICE_STATE_SECONDARIES;
	priv->dispatcher.post_state_reason = NM_DEVICE_STATE_REASON_NONE;
	if (!nm_dispatcher_call_device (NM_DISPATCHER_ACTION_PRE_UP,
	                                self,
	                                NULL,
	                                dispatcher_complete_proceed_state,
	                                self,
	                                &priv->dispatcher.call_id)) {
		/* Just proceed on errors */
		dispatcher_complete_proceed_state (0, self);
	}
}

static void
ip_check_gw_ping_cleanup (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	nm_clear_g_source (&priv->gw_ping.watch);
	nm_clear_g_source (&priv->gw_ping.timeout);

	if (priv->gw_ping.pid) {
		nm_utils_kill_child_async (priv->gw_ping.pid, SIGTERM, priv->gw_ping.log_domain, "ping", 1000, NULL, NULL);
		priv->gw_ping.pid = 0;
	}

	nm_clear_g_free (&priv->gw_ping.binary);
	nm_clear_g_free (&priv->gw_ping.address);
}

static gboolean
spawn_ping (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gs_free char *str_timeout = NULL;
	gs_free char *tmp_str = NULL;
	const char *args[] = { priv->gw_ping.binary, "-I", nm_device_get_ip_iface (self),
	                       "-c", "1", "-w", NULL, priv->gw_ping.address, NULL };
	gs_free_error GError *error = NULL;
	gboolean ret;

	args[6] = str_timeout = g_strdup_printf ("%u", priv->gw_ping.deadline);
	tmp_str = g_strjoinv (" ", (char **) args);
	_LOGD (priv->gw_ping.log_domain, "ping: running '%s'", tmp_str);

	ret = g_spawn_async ("/",
	                     (char **) args,
	                      NULL,
	                      G_SPAWN_DO_NOT_REAP_CHILD,
	                      NULL,
	                      NULL,
	                      &priv->gw_ping.pid,
	                      &error);

	if (!ret) {
		_LOGW (priv->gw_ping.log_domain, "ping: could not spawn %s: %s",
		       priv->gw_ping.binary, error->message);
	}

	return ret;
}

static gboolean
respawn_ping_cb (gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	priv->gw_ping.watch = 0;

	if (spawn_ping (self)) {
		priv->gw_ping.watch = g_child_watch_add (priv->gw_ping.pid,
		                                         ip_check_ping_watch_cb, self);
	} else {
		ip_check_gw_ping_cleanup (self);
		ip_check_pre_up (self);
	}

	return FALSE;
}

static void
ip_check_ping_watch_cb (GPid pid, int status, gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMLogDomain log_domain = priv->gw_ping.log_domain;
	gboolean success = FALSE;

	if (!priv->gw_ping.watch)
		return;
	priv->gw_ping.watch = 0;
	priv->gw_ping.pid = 0;

	if (WIFEXITED (status)) {
		if (WEXITSTATUS (status) == 0) {
			_LOGD (log_domain, "ping: gateway ping succeeded");
			success = TRUE;
		} else {
			_LOGW (log_domain, "ping: gateway ping failed with error code %d",
			       WEXITSTATUS (status));
		}
	} else
		_LOGW (log_domain, "ping: stopped unexpectedly with status %d", status);

	if (success) {
		/* We've got connectivity, proceed to pre_up */
		ip_check_gw_ping_cleanup (self);
		ip_check_pre_up (self);
	} else {
		/* If ping exited with an error it may have returned early,
		 * wait 1 second and restart it */
		priv->gw_ping.watch = g_timeout_add_seconds (1, respawn_ping_cb, self);
	}
}

static gboolean
ip_check_ping_timeout_cb (gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	priv->gw_ping.timeout = 0;

	_LOGW (priv->gw_ping.log_domain, "ping: gateway ping timed out");

	ip_check_gw_ping_cleanup (self);
	ip_check_pre_up (self);
	return FALSE;
}

static gboolean
start_ping (NMDevice *self,
            NMLogDomain log_domain,
            const char *binary,
            const char *address,
            guint timeout)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	g_return_val_if_fail (priv->gw_ping.watch == 0, FALSE);
	g_return_val_if_fail (priv->gw_ping.timeout == 0, FALSE);

	priv->gw_ping.log_domain = log_domain;
	priv->gw_ping.address = g_strdup (address);
	priv->gw_ping.binary = g_strdup (binary);
	priv->gw_ping.deadline = timeout + 10; /* the proper termination is enforced by a timer */

	if (spawn_ping (self)) {
		priv->gw_ping.watch = g_child_watch_add (priv->gw_ping.pid, ip_check_ping_watch_cb, self);
		priv->gw_ping.timeout = g_timeout_add_seconds (timeout, ip_check_ping_timeout_cb, self);
		return TRUE;
	}

	ip_check_gw_ping_cleanup (self);
	return FALSE;
}

static void
nm_device_start_ip_check (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMConnection *connection;
	NMSettingConnection *s_con;
	guint timeout = 0;
	const char *ping_binary = NULL;
	char buf[NM_UTILS_INET_ADDRSTRLEN];
	NMLogDomain log_domain = LOGD_IP4;

	/* Shouldn't be any active ping here, since IP_CHECK happens after the
	 * first IP method completes.  Any subsequently completing IP method doesn't
	 * get checked.
	 */
	g_return_if_fail (!priv->gw_ping.watch);
	g_return_if_fail (!priv->gw_ping.timeout);
	g_return_if_fail (!priv->gw_ping.pid);
	g_return_if_fail (priv->ip_state_4 == NM_DEVICE_IP_STATE_DONE || priv->ip_state_6 == NM_DEVICE_IP_STATE_DONE);

	connection = nm_device_get_applied_connection (self);
	g_assert (connection);

	s_con = nm_connection_get_setting_connection (connection);
	g_assert (s_con);
	timeout = nm_setting_connection_get_gateway_ping_timeout (s_con);

	buf[0] = '\0';
	if (timeout) {
		const NMPObject *gw;

		if (priv->ip_config_4 && priv->ip_state_4 == NM_DEVICE_IP_STATE_DONE) {
			gw = nm_ip4_config_best_default_route_get (priv->ip_config_4);
			if (gw) {
				_nm_utils_inet4_ntop (NMP_OBJECT_CAST_IP4_ROUTE (gw)->gateway, buf);
				ping_binary = nm_utils_find_helper ("ping", "/usr/bin/ping", NULL);
				log_domain = LOGD_IP4;
			}
		} else if (priv->ip_config_6 && priv->ip_state_6 == NM_DEVICE_IP_STATE_DONE) {
			gw = nm_ip6_config_best_default_route_get (priv->ip_config_6);
			if (gw) {
				_nm_utils_inet6_ntop (&NMP_OBJECT_CAST_IP6_ROUTE (gw)->gateway, buf);
				ping_binary = nm_utils_find_helper ("ping6", "/usr/bin/ping6", NULL);
				log_domain = LOGD_IP6;
			}
		}
	}

	if (buf[0])
		start_ping (self, log_domain, ping_binary, buf, timeout);

	/* If no ping was started, just advance to pre_up */
	if (!priv->gw_ping.pid)
		ip_check_pre_up (self);
}

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

static gboolean
carrier_wait_timeout (gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	priv->carrier_wait_id = 0;
	nm_device_remove_pending_action (self, NM_PENDING_ACTION_CARRIER_WAIT, FALSE);
	if (!priv->carrier)
		_carrier_wait_check_queued_act_request (self);
	return G_SOURCE_REMOVE;
}

static gboolean
nm_device_is_up (NMDevice *self)
{
	int ifindex;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	ifindex = nm_device_get_ip_ifindex (self);
	return ifindex > 0 ? nm_platform_link_is_up (nm_device_get_platform (self), ifindex) : TRUE;
}

static gint64
_get_carrier_wait_ms (NMDevice *self)
{
	gs_free char *value = NULL;

	value = nm_config_data_get_device_config (NM_CONFIG_GET_DATA,
	                                          NM_CONFIG_KEYFILE_KEY_DEVICE_CARRIER_WAIT_TIMEOUT,
	                                          self,
	                                          NULL);
	return _nm_utils_ascii_str_to_int64 (value, 10, 0, G_MAXINT32, CARRIER_WAIT_TIME_MS);
}

gboolean
nm_device_bring_up (NMDevice *self, gboolean block, gboolean *no_firmware)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gboolean device_is_up = FALSE;
	NMDeviceCapabilities capabilities;
	int ifindex;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	NM_SET_OUT (no_firmware, FALSE);

	if (!nm_device_get_enabled (self)) {
		_LOGD (LOGD_PLATFORM, "bringing up device ignored due to disabled");
		return FALSE;
	}

	ifindex = nm_device_get_ip_ifindex (self);
	_LOGD (LOGD_PLATFORM, "bringing up device %d", ifindex);
	if (ifindex <= 0) {
		/* assume success. */
	} else {
		if (!nm_platform_link_set_up (nm_device_get_platform (self), ifindex, no_firmware))
			return FALSE;
	}

	/* Store carrier immediately. */
	nm_device_set_carrier_from_platform (self);

	device_is_up = nm_device_is_up (self);
	if (block && !device_is_up) {
		gint64 wait_until = nm_utils_get_monotonic_timestamp_usec () + 10000 /* microseconds */;

		do {
			g_usleep (200);
			if (!nm_platform_link_refresh (nm_device_get_platform (self), ifindex))
				return FALSE;
			device_is_up = nm_device_is_up (self);
		} while (!device_is_up && nm_utils_get_monotonic_timestamp_usec () < wait_until);
	}

	if (!device_is_up) {
		if (block)
			_LOGW (LOGD_PLATFORM, "device not up after timeout!");
		else
			_LOGD (LOGD_PLATFORM, "device not up immediately");
		return FALSE;
	}

	/* some ethernet devices fail to report capabilities unless the device
	 * is up. Re-read the capabilities. */
	capabilities = 0;
	if (NM_DEVICE_GET_CLASS (self)->get_generic_capabilities)
		capabilities |= NM_DEVICE_GET_CLASS (self)->get_generic_capabilities (self);
	_add_capabilities (self, capabilities);

	/* Devices that support carrier detect must be IFF_UP to report carrier
	 * changes; so after setting the device IFF_UP we must suppress startup
	 * complete (via a pending action) until either the carrier turns on, or
	 * a timeout is reached.
	 */
	if (nm_device_has_capability (self, NM_DEVICE_CAP_CARRIER_DETECT)) {
		gint64 now_ms, until_ms;

		/* we start a grace period of 5 seconds during which we will schedule
		 * a pending action whenever we have no carrier.
		 *
		 * If during that time carrier goes away, we declare the interface
		 * as not ready. */
		nm_clear_g_source (&priv->carrier_wait_id);
		if (!priv->carrier)
			nm_device_add_pending_action (self, NM_PENDING_ACTION_CARRIER_WAIT, FALSE);

		now_ms = nm_utils_get_monotonic_timestamp_msec ();
		until_ms = NM_MAX (now_ms + _get_carrier_wait_ms (self), priv->carrier_wait_until_ms);
		priv->carrier_wait_id = g_timeout_add (until_ms - now_ms, carrier_wait_timeout, self);
	}

	/* Can only get HW address of some devices when they are up */
	nm_device_update_hw_address (self);

	_update_ip4_address (self);

	/* when the link comes up, we must restore IP configuration if necessary. */
	if (priv->ip_state_4 == NM_DEVICE_IP_STATE_DONE) {
		if (!ip_config_merge_and_apply (self, AF_INET, TRUE))
			_LOGW (LOGD_IP4, "failed applying IP4 config after bringing link up");
	}
	if (priv->ip_state_6 == NM_DEVICE_IP_STATE_DONE) {
		if (!ip_config_merge_and_apply (self, AF_INET6, TRUE))
			_LOGW (LOGD_IP6, "failed applying IP6 config after bringing link up");
	}

	return TRUE;
}

void
nm_device_take_down (NMDevice *self, gboolean block)
{
	int ifindex;
	gboolean device_is_up;

	g_return_if_fail (NM_IS_DEVICE (self));

	ifindex = nm_device_get_ip_ifindex (self);
	_LOGD (LOGD_PLATFORM, "taking down device %d", ifindex);
	if (ifindex <= 0) {
		/* devices without ifindex are always up. */
		return;
	}

	if (!nm_platform_link_set_down (nm_device_get_platform (self), ifindex))
		return;

	device_is_up = nm_device_is_up (self);
	if (block && device_is_up) {
		gint64 wait_until = nm_utils_get_monotonic_timestamp_usec () + 10000 /* microseconds */;

		do {
			g_usleep (200);
			if (!nm_platform_link_refresh (nm_device_get_platform (self), ifindex))
				return;
			device_is_up = nm_device_is_up (self);
		} while (device_is_up && nm_utils_get_monotonic_timestamp_usec () < wait_until);
	}

	if (device_is_up) {
		if (block)
			_LOGW (LOGD_PLATFORM, "device not down after timeout!");
		else
			_LOGD (LOGD_PLATFORM, "device not down immediately");
	}
}

void
nm_device_set_firmware_missing (NMDevice *self, gboolean new_missing)
{
	NMDevicePrivate *priv;

	g_return_if_fail (NM_IS_DEVICE (self));

	priv = NM_DEVICE_GET_PRIVATE (self);
	if (priv->firmware_missing != new_missing) {
		priv->firmware_missing = new_missing;
		_notify (self, PROP_FIRMWARE_MISSING);
	}
}

gboolean
nm_device_get_firmware_missing (NMDevice *self)
{
	return NM_DEVICE_GET_PRIVATE (self)->firmware_missing;
}

static void
intersect_ext_config (NMDevice *self,
                      AppliedConfig *config,
                      gboolean intersect_addresses,
                      gboolean intersect_routes)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMIPConfig *ext;
	guint32 penalty;
	int family;

	if (!config->orig)
		return;

	family = nm_ip_config_get_addr_family (config->orig);
	penalty = default_route_metric_penalty_get (self, family);
	ext = family == AF_INET
	      ? (NMIPConfig *) priv->ext_ip_config_4
	      : (NMIPConfig *) priv->ext_ip_config_6;

	if (config->current) {
		nm_ip_config_intersect (config->current,
		                        ext,
		                        intersect_addresses,
		                        intersect_routes,
		                        penalty);
	} else {
		config->current = nm_ip_config_intersect_alloc (config->orig,
		                                                ext,
		                                                intersect_addresses,
		                                                intersect_routes,
		                                                penalty);
	}
}

static gboolean
update_ext_ip_config (NMDevice *self, int addr_family, gboolean intersect_configs)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	int ifindex;
	GSList *iter;
	gboolean is_up;

	nm_assert_addr_family (addr_family);

	ifindex = nm_device_get_ip_ifindex (self);
	if (!ifindex)
		return FALSE;

	is_up = nm_platform_link_is_up (nm_device_get_platform (self), ifindex);

	if (addr_family == AF_INET) {

		g_clear_object (&priv->ext_ip_config_4);
		priv->ext_ip_config_4 = nm_ip4_config_capture (nm_device_get_multi_index (self),
		                                              nm_device_get_platform (self),
		                                              ifindex);
		if (priv->ext_ip_config_4) {
			if (intersect_configs) {
				/* This function was called upon external changes. Remove the configuration
				 * (addresses,routes) that is no longer present externally from the internal
				 * config. This way, we don't re-add addresses that were manually removed
				 * by the user. */
				if (priv->con_ip_config_4) {
					nm_ip4_config_intersect (priv->con_ip_config_4, priv->ext_ip_config_4,
					                         TRUE,
					                         is_up,
					                         default_route_metric_penalty_get (self, AF_INET));
				}

				intersect_ext_config (self, &priv->dev_ip_config_4, TRUE, is_up);
				intersect_ext_config (self, &priv->dev2_ip_config_4, TRUE, is_up);

				for (iter = priv->vpn_configs_4; iter; iter = iter->next)
					nm_ip4_config_intersect (iter->data, priv->ext_ip_config_4, TRUE, is_up, 0);
			}

			/* Remove parts from ext_ip_config_4 to only contain the information that
			 * was configured externally -- we already have the same configuration from
			 * internal origins. */
			if (priv->con_ip_config_4) {
				nm_ip4_config_subtract (priv->ext_ip_config_4, priv->con_ip_config_4,
				                        default_route_metric_penalty_get (self, AF_INET));
			}
			if (applied_config_get_current (&priv->dev_ip_config_4)) {
				nm_ip_config_subtract ((NMIPConfig *) priv->ext_ip_config_4,
				                       applied_config_get_current (&priv->dev_ip_config_4),
				                       default_route_metric_penalty_get (self, AF_INET));
			}
			if (applied_config_get_current (&priv->dev2_ip_config_4)) {
				nm_ip_config_subtract ((NMIPConfig *) priv->ext_ip_config_4,
				                       applied_config_get_current (&priv->dev2_ip_config_4),
				                       default_route_metric_penalty_get (self, AF_INET));
			}
			for (iter = priv->vpn_configs_4; iter; iter = iter->next)
				nm_ip4_config_subtract (priv->ext_ip_config_4, iter->data, 0);
		}

	} else {
		nm_assert (addr_family == AF_INET6);

		g_clear_object (&priv->ext_ip_config_6);
		g_clear_object (&priv->ext_ip6_config_captured);
		priv->ext_ip6_config_captured = nm_ip6_config_capture (nm_device_get_multi_index (self),
		                                                       nm_device_get_platform (self),
		                                                       ifindex,
		                                                       NM_SETTING_IP6_CONFIG_PRIVACY_UNKNOWN);
		if (priv->ext_ip6_config_captured) {

			priv->ext_ip_config_6 = nm_ip6_config_new_cloned (priv->ext_ip6_config_captured);

			if (intersect_configs) {
				/* This function was called upon external changes. Remove the configuration
				 * (addresses,routes) that is no longer present externally from the internal
				 * config. This way, we don't re-add addresses that were manually removed
				 * by the user. */
				if (priv->con_ip_config_6) {
					nm_ip6_config_intersect (priv->con_ip_config_6, priv->ext_ip_config_6,
					                         is_up,
					                         is_up,
					                         default_route_metric_penalty_get (self, AF_INET6));
				}

				intersect_ext_config (self, &priv->ac_ip6_config, is_up, is_up);
				intersect_ext_config (self, &priv->dhcp6.ip6_config, is_up, is_up);
				intersect_ext_config (self, &priv->dev2_ip_config_6, is_up, is_up);

				for (iter = priv->vpn_configs_6; iter; iter = iter->next)
					nm_ip6_config_intersect (iter->data, priv->ext_ip_config_6, is_up, is_up, 0);

				if (   is_up
				    && priv->ipv6ll_has
				    && !nm_ip6_config_lookup_address (priv->ext_ip_config_6, &priv->ipv6ll_addr))
					priv->ipv6ll_has = FALSE;
			}

			/* Remove parts from ext_ip_config_6 to only contain the information that
			 * was configured externally -- we already have the same configuration from
			 * internal origins. */
			if (priv->con_ip_config_6) {
				nm_ip6_config_subtract (priv->ext_ip_config_6, priv->con_ip_config_6,
				                        default_route_metric_penalty_get (self, AF_INET6));
			}
			if (applied_config_get_current (&priv->ac_ip6_config)) {
				nm_ip_config_subtract ((NMIPConfig *) priv->ext_ip_config_6,
				                       applied_config_get_current (&priv->ac_ip6_config),
				                       default_route_metric_penalty_get (self, AF_INET6));
			}
			if (applied_config_get_current (&priv->dhcp6.ip6_config)) {
				nm_ip_config_subtract ((NMIPConfig *) priv->ext_ip_config_6,
				                       applied_config_get_current (&priv->dhcp6.ip6_config),
				                       default_route_metric_penalty_get (self, AF_INET6));
			}
			if (applied_config_get_current (&priv->dev2_ip_config_6)) {
				nm_ip_config_subtract ((NMIPConfig *) priv->ext_ip_config_6,
				                       applied_config_get_current (&priv->dev2_ip_config_6),
				                       default_route_metric_penalty_get (self, AF_INET6));
			}
			for (iter = priv->vpn_configs_6; iter; iter = iter->next)
				nm_ip6_config_subtract (priv->ext_ip_config_6, iter->data, 0);
		}
	}

	return TRUE;
}

static void
update_ip_config (NMDevice *self, int addr_family)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	nm_assert_addr_family (addr_family);

	if (addr_family == AF_INET)
		priv->update_ip_config_completed_v4 = TRUE;
	else
		priv->update_ip_config_completed_v6 = TRUE;

	if (update_ext_ip_config (self, addr_family, TRUE)) {
		if (addr_family == AF_INET) {
			if (priv->ext_ip_config_4)
				ip_config_merge_and_apply (self, AF_INET, FALSE);
		} else {
			if (priv->ext_ip6_config_captured)
				ip_config_merge_and_apply (self, AF_INET6, FALSE);
		}
	}
}

void
nm_device_capture_initial_config (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (!priv->update_ip_config_completed_v4)
		update_ip_config (self, AF_INET);
	if (!priv->update_ip_config_completed_v6)
		update_ip_config (self, AF_INET6);
}

static gboolean
queued_ip_config_change (NMDevice *self, int addr_family)
{
	NMDevicePrivate *priv;
	const gboolean IS_IPv4 = (addr_family == AF_INET);

	g_return_val_if_fail (NM_IS_DEVICE (self), G_SOURCE_REMOVE);

	priv = NM_DEVICE_GET_PRIVATE (self);

	/* Wait for any queued state changes */
	if (priv->queued_state.id)
		return G_SOURCE_CONTINUE;

	/* If a commit is scheduled, this function would potentially interfere with
	 * it changing IP configurations before they are applied. Postpone the
	 * update in such case.
	 */
	if (   priv->activation_source_id_x[IS_IPv4] != 0
	    && priv->activation_source_func_x[IS_IPv4] == activate_stage5_ip_config_result_x[IS_IPv4])
		return G_SOURCE_CONTINUE;

	priv->queued_ip_config_id_x[IS_IPv4] = 0;

	update_ip_config (self, addr_family);

	if (!IS_IPv4) {
		/* Check whether we need to complete waiting for link-local.
		 * We are also called from an idle handler, so no problem doing state transitions
		 * now. */
		linklocal6_check_complete (self);
	}

	if (!IS_IPv4) {
		NMPlatform *platform;
		GSList *dad6_failed_addrs, *iter;
		const NMPlatformLink *pllink;

		dad6_failed_addrs = g_steal_pointer (&priv->dad6_failed_addrs);

		if (   priv->state > NM_DEVICE_STATE_DISCONNECTED
		    && priv->state < NM_DEVICE_STATE_DEACTIVATING
		    && priv->ifindex > 0
		    && !nm_device_sys_iface_state_is_external (self)
		    && (platform = nm_device_get_platform (self))
		    && (pllink = nm_platform_link_get (platform, priv->ifindex))
		    && (pllink->n_ifi_flags & IFF_UP)) {
			gboolean need_ipv6ll = FALSE;
			NMNDiscConfigMap ndisc_config_changed = NM_NDISC_CONFIG_NONE;

			/* Handle DAD failures */
			for (iter = dad6_failed_addrs; iter; iter = iter->next) {
				const NMPObject *obj = iter->data;
				const NMPlatformIP6Address *addr;

				if (!nm_ndisc_dad_addr_is_fail_candidate (platform, obj))
					continue;

				addr = NMP_OBJECT_CAST_IP6_ADDRESS (obj);

				_LOGI (LOGD_IP6, "ipv6: duplicate address check failed for the %s address",
				       nm_platform_ip6_address_to_string (addr, NULL, 0));

				if (IN6_IS_ADDR_LINKLOCAL (&addr->address))
					need_ipv6ll = TRUE;
				else if (priv->ndisc)
					ndisc_config_changed |= nm_ndisc_dad_failed (priv->ndisc, &addr->address, FALSE);
			}

			if (ndisc_config_changed != NM_NDISC_CONFIG_NONE)
				nm_ndisc_emit_config_change (priv->ndisc, ndisc_config_changed);

			/* If no IPv6 link-local address exists but other addresses do then we
			 * must add the LL address to remain conformant with RFC 3513 chapter 2.1
			 * ("Addressing Model"): "All interfaces are required to have at least
			 * one link-local unicast address".
			 */
			if (   priv->ip_config_6
			    && nm_ip6_config_get_num_addresses (priv->ip_config_6))
				need_ipv6ll = TRUE;
			if (need_ipv6ll)
				check_and_add_ipv6ll_addr (self);
		}

		g_slist_free_full (dad6_failed_addrs, (GDestroyNotify) nmp_object_unref);
	}

	if (!IS_IPv4) {
		/* Check if DAD is still pending */
		if (   priv->ip_state_6 == NM_DEVICE_IP_STATE_CONF
		    && priv->dad6_ip6_config
		    && priv->ext_ip6_config_captured
		    && !nm_ip6_config_has_any_dad_pending (priv->ext_ip6_config_captured,
		                                           priv->dad6_ip6_config)) {
			_LOGD (LOGD_DEVICE | LOGD_IP6, "IPv6 DAD terminated");
			g_clear_object (&priv->dad6_ip6_config);
			_set_ip_state (self, addr_family, NM_DEVICE_IP_STATE_DONE);
			check_ip_state (self, FALSE, TRUE);
			if (priv->rt6_temporary_not_available)
				nm_device_activate_schedule_ip_config_result (self, AF_INET6, NULL);
		}
	}

	set_unmanaged_external_down (self, TRUE);

	return G_SOURCE_REMOVE;
}

static gboolean
queued_ip4_config_change (gpointer user_data)
{
	return queued_ip_config_change (user_data, AF_INET);
}

static gboolean
queued_ip6_config_change (gpointer user_data)
{
	return queued_ip_config_change (user_data, AF_INET6);
}

static void
device_ipx_changed (NMPlatform *platform,
                    int obj_type_i,
                    int ifindex,
                    gconstpointer platform_object,
                    int change_type_i,
                    NMDevice *self)
{
	const NMPObjectType obj_type = obj_type_i;
	const NMPlatformSignalChangeType change_type = change_type_i;
	NMDevicePrivate *priv;
	const NMPlatformIP6Address *addr;

	if (nm_device_get_ip_ifindex (self) != ifindex)
		return;

	if (!nm_device_is_real (self))
		return;

	if (nm_device_get_unmanaged_flags (self, NM_UNMANAGED_PLATFORM_INIT)) {
		/* ignore all platform signals until the link is initialized in platform. */
		return;
	}

	priv = NM_DEVICE_GET_PRIVATE (self);

	switch (obj_type) {
	case NMP_OBJECT_TYPE_IP4_ADDRESS:
	case NMP_OBJECT_TYPE_IP4_ROUTE:
		if (!priv->queued_ip_config_id_4) {
			priv->queued_ip_config_id_4 = g_idle_add (queued_ip4_config_change, self);
			_LOGD (LOGD_DEVICE, "queued IP4 config change");
		}
		break;
	case NMP_OBJECT_TYPE_IP6_ADDRESS:
		addr = platform_object;

		if (   priv->state > NM_DEVICE_STATE_DISCONNECTED
		    && priv->state < NM_DEVICE_STATE_DEACTIVATING
		    && nm_ndisc_dad_addr_is_fail_candidate_event (change_type, addr)) {
			priv->dad6_failed_addrs = g_slist_prepend (priv->dad6_failed_addrs,
			                                           (gpointer) nmp_object_ref (NMP_OBJECT_UP_CAST (addr)));
		}

		/* fall-through */
	case NMP_OBJECT_TYPE_IP6_ROUTE:
		if (!priv->queued_ip_config_id_6) {
			priv->queued_ip_config_id_6 = g_idle_add (queued_ip6_config_change, self);
			_LOGD (LOGD_DEVICE, "queued IP6 config change");
		}
		break;
	default:
		g_return_if_reached ();
	}
}

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

NM_UTILS_FLAGS2STR_DEFINE (nm_unmanaged_flags2str, NMUnmanagedFlags,
	NM_UTILS_FLAGS2STR (NM_UNMANAGED_SLEEPING, "sleeping"),
	NM_UTILS_FLAGS2STR (NM_UNMANAGED_QUITTING, "quitting"),
	NM_UTILS_FLAGS2STR (NM_UNMANAGED_PARENT, "parent"),
	NM_UTILS_FLAGS2STR (NM_UNMANAGED_BY_TYPE, "by-type"),
	NM_UTILS_FLAGS2STR (NM_UNMANAGED_PLATFORM_INIT, "platform-init"),
	NM_UTILS_FLAGS2STR (NM_UNMANAGED_USER_EXPLICIT, "user-explicit"),
	NM_UTILS_FLAGS2STR (NM_UNMANAGED_BY_DEFAULT, "by-default"),
	NM_UTILS_FLAGS2STR (NM_UNMANAGED_USER_SETTINGS, "user-settings"),
	NM_UTILS_FLAGS2STR (NM_UNMANAGED_USER_CONF, "user-conf"),
	NM_UTILS_FLAGS2STR (NM_UNMANAGED_USER_UDEV, "user-udev"),
	NM_UTILS_FLAGS2STR (NM_UNMANAGED_EXTERNAL_DOWN, "external-down"),
	NM_UTILS_FLAGS2STR (NM_UNMANAGED_IS_SLAVE, "is-slave"),
);

static const char *
_unmanaged_flags2str (NMUnmanagedFlags flags, NMUnmanagedFlags mask, char *buf, gsize len)
{
	char buf2[512];
	char *b;
	char *tmp, *tmp2;
	gsize l;

	nm_utils_to_string_buffer_init (&buf, &len);
	if (!len)
		return buf;

	b = buf;

	mask |= flags;

	nm_unmanaged_flags2str (flags, b, len);
	l = strlen (b);
	b += l;
	len -= l;

	nm_unmanaged_flags2str (mask & ~flags, buf2, sizeof (buf2));
	if (buf2[0]) {
		gboolean add_separator = l > 0;

		tmp = buf2;
		while (TRUE) {
			if (add_separator)
				nm_utils_strbuf_append_c (&b, &len, ',');
			add_separator = TRUE;

			tmp2 = strchr (tmp, ',');
			if (tmp2)
				tmp2[0] = '\0';

			nm_utils_strbuf_append_c (&b, &len, '!');
			nm_utils_strbuf_append_str (&b, &len, tmp);
			if (!tmp2)
				break;

			tmp = &tmp2[1];
		}
	}

	return buf;
}

static gboolean
_get_managed_by_flags(NMUnmanagedFlags flags, NMUnmanagedFlags mask, gboolean for_user_request)
{
	/* Evaluate the managed state based on the unmanaged flags.
	 *
	 * Some flags are authoritative, meaning they always cause
	 * the device to be unmanaged (e.g. @NM_UNMANAGED_PLATFORM_INIT).
	 *
	 * OTOH, some flags can be overwritten. For example NM_UNMANAGED_USER_UDEV
	 * is ignored once NM_UNMANAGED_USER_EXPLICIT is set. The idea is that
	 * the flag from the configuration has no effect once the user explicitly
	 * touches the unmanaged flags. */

	if (for_user_request) {

		/* @for_user_request can make the result only ~more~ managed.
		 * If the flags already indicate a managed state for a non-user-request,
		 * then it is also managed for an explicit user-request.
		 *
		 * Effectively, this check is redundant, as the code below already
		 * already ensures that. Still, express this invariant explicitly here. */
		if (_get_managed_by_flags (flags, mask, FALSE))
			return TRUE;

		/* A for-user-request, is effectively the same as pretending
		 * that user-explicit flag is cleared. */
		mask |= NM_UNMANAGED_USER_EXPLICIT;
		flags &= ~NM_UNMANAGED_USER_EXPLICIT;
	}

	if (   NM_FLAGS_ANY (mask, NM_UNMANAGED_USER_SETTINGS)
	    && !NM_FLAGS_ANY (flags, NM_UNMANAGED_USER_SETTINGS)) {
		/* NM_UNMANAGED_USER_SETTINGS can only explicitly unmanage a device. It cannot
		 * *manage* it. Having NM_UNMANAGED_USER_SETTINGS explicitly not set, is the
		 * same as having it not set at all. */
		mask &= ~NM_UNMANAGED_USER_SETTINGS;
	}

	if (NM_FLAGS_ANY (mask, NM_UNMANAGED_USER_UDEV)) {
		/* configuration from udev or nm-config overwrites the by-default flag
		 * which is based on the device type.
		 * configuration from udev overwrites external-down */
		flags &= ~(  NM_UNMANAGED_BY_DEFAULT
		           | NM_UNMANAGED_EXTERNAL_DOWN);
	}

	if (NM_FLAGS_ANY (mask, NM_UNMANAGED_USER_CONF)) {
		/* configuration from NetworkManager.conf overwrites the by-default flag
		 * which is based on the device type.
		 * It also overwrites the udev configuration and external-down */
		flags &= ~(   NM_UNMANAGED_BY_DEFAULT
		           | NM_UNMANAGED_USER_UDEV
		           | NM_UNMANAGED_EXTERNAL_DOWN);
	}

	if (   NM_FLAGS_HAS (mask, NM_UNMANAGED_IS_SLAVE)
	    && !NM_FLAGS_HAS (flags, NM_UNMANAGED_IS_SLAVE)) {
		/* for an enslaved device, by-default doesn't matter */
		flags &= ~NM_UNMANAGED_BY_DEFAULT;
	}

	if (NM_FLAGS_HAS (mask, NM_UNMANAGED_USER_EXPLICIT)) {
		/* if the device is managed by user-decision, certain other flags
		 * are ignored. */
		flags &= ~(  NM_UNMANAGED_BY_DEFAULT
		           | NM_UNMANAGED_USER_UDEV
		           | NM_UNMANAGED_USER_CONF
		           | NM_UNMANAGED_EXTERNAL_DOWN);
	}

	return flags == NM_UNMANAGED_NONE;
}

/**
 * nm_device_get_managed:
 * @self: the #NMDevice
 * @for_user_request: whether to check the flags for an explicit user-request
 *   Setting this to %TRUE has the same effect as if %NM_UNMANAGED_USER_EXPLICIT
 *   unmanaged flag would be unset (meaning: explicitly not-unmanaged).
 *   If this parameter is %TRUE, the device can only appear more managed.
 *
 * Whether the device is unmanaged according to the unmanaged flags.
 *
 * Returns: %TRUE if the device is unmanaged because of the flags.
 */
gboolean
nm_device_get_managed (NMDevice *self, gboolean for_user_request)
{
	NMDevicePrivate *priv;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	if (!nm_device_is_real (self)) {
		/* a unrealized device is always considered unmanaged. */
		return FALSE;
	}

	priv = NM_DEVICE_GET_PRIVATE (self);

	return _get_managed_by_flags (priv->unmanaged_flags, priv->unmanaged_mask, for_user_request);
}

/**
 * nm_device_get_unmanaged_mask:
 * @self: the #NMDevice
 * @flag: the unmanaged flags to check.
 *
 * Return the unmanaged flags mask set on this device.
 *
 * Returns: the flags of the device ( & @flag)
 */
NMUnmanagedFlags
nm_device_get_unmanaged_mask (NMDevice *self, NMUnmanagedFlags flag)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), NM_UNMANAGED_NONE);
	g_return_val_if_fail (flag != NM_UNMANAGED_NONE, NM_UNMANAGED_NONE);

	return NM_DEVICE_GET_PRIVATE (self)->unmanaged_mask & flag;
}

/**
 * nm_device_get_unmanaged_flags:
 * @self: the #NMDevice
 * @flag: the unmanaged flags to check.
 *
 * Return the unmanaged flags of the device.
 *
 * Returns: the flags of the device ( & @flag)
 */
NMUnmanagedFlags
nm_device_get_unmanaged_flags (NMDevice *self, NMUnmanagedFlags flag)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), NM_UNMANAGED_NONE);
	g_return_val_if_fail (flag != NM_UNMANAGED_NONE, NM_UNMANAGED_NONE);

	return NM_DEVICE_GET_PRIVATE (self)->unmanaged_flags & flag;
}

/**
 * _set_unmanaged_flags:
 * @self: the #NMDevice instance
 * @flags: which #NMUnmanagedFlags to set.
 * @set_op: whether to set/clear/forget the flags. You can also pass
 *   boolean values %TRUE and %FALSE, which mean %NM_UNMAN_FLAG_OP_SET_UNMANAGED
 *   and %NM_UNMAN_FLAG_OP_SET_MANAGED, respectively.
 * @allow_state_transition: if %FALSE, setting flags never triggers a device
 *   state change. If %TRUE, the device can change state, if it is real and
 *   switches from managed to unmanaged (or vice versa).
 * @now: whether the state change should be immediate or delayed
 * @reason: the device state reason passed to nm_device_state_changed() if
 *   the device becomes managed/unmanaged. This is only relevant if the
 *   device switches state and if @allow_state_transition is %TRUE.
 *
 * Set the unmanaged flags of the device.
 **/
static void
_set_unmanaged_flags (NMDevice *self,
                      NMUnmanagedFlags flags,
                      NMUnmanFlagOp set_op,
                      gboolean allow_state_transition,
                      gboolean now,
                      NMDeviceStateReason reason)
{
	NMDevicePrivate *priv;
	gboolean was_managed, transition_state;
	NMUnmanagedFlags old_flags, old_mask;
	NMDeviceState new_state;
	const char *operation = NULL;
	char str1[512];
	char str2[512];
	gboolean do_notify_has_pending_actions = FALSE;
	gboolean had_pending_actions = FALSE;

	g_return_if_fail (NM_IS_DEVICE (self));
	g_return_if_fail (flags);

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (!priv->real)
		allow_state_transition = FALSE;
	was_managed = allow_state_transition && nm_device_get_managed (self, FALSE);

	if (   NM_FLAGS_HAS (priv->unmanaged_flags, NM_UNMANAGED_PLATFORM_INIT)
	    && NM_FLAGS_HAS (flags, NM_UNMANAGED_PLATFORM_INIT)
	    && NM_IN_SET (set_op, NM_UNMAN_FLAG_OP_SET_MANAGED)) {
		/* we are clearing the platform-init flags. This triggers additional actions. */
		if (!NM_FLAGS_HAS (flags, NM_UNMANAGED_USER_SETTINGS)) {
			gboolean unmanaged;

			unmanaged = nm_device_spec_match_list (self,
			                                       nm_settings_get_unmanaged_specs (NM_DEVICE_GET_PRIVATE (self)->settings));
			nm_device_set_unmanaged_flags (self,
			                               NM_UNMANAGED_USER_SETTINGS,
			                               !!unmanaged);
		}

		/* trigger an initial update of IP configuration. */
		nm_assert_se (!nm_clear_g_source (&priv->queued_ip_config_id_4));
		nm_assert_se (!nm_clear_g_source (&priv->queued_ip_config_id_6));
		priv->queued_ip_config_id_4 = g_idle_add (queued_ip4_config_change, self);
		priv->queued_ip_config_id_6 = g_idle_add (queued_ip6_config_change, self);

		if (!priv->pending_actions) {
			do_notify_has_pending_actions = TRUE;
			had_pending_actions = nm_device_has_pending_action (self);
		}
	}

	old_flags = priv->unmanaged_flags;
	old_mask = priv->unmanaged_mask;

	switch (set_op) {
	case NM_UNMAN_FLAG_OP_FORGET:
		priv->unmanaged_mask &= ~flags;
		priv->unmanaged_flags &= ~flags;
		operation = "forget";
		break;
	case NM_UNMAN_FLAG_OP_SET_UNMANAGED:
		priv->unmanaged_mask |= flags;
		priv->unmanaged_flags |= flags;
		operation = "set-unmanaged";
		break;
	case NM_UNMAN_FLAG_OP_SET_MANAGED:
		priv->unmanaged_mask |= flags;
		priv->unmanaged_flags &= ~flags;
		operation = "set-managed";
		break;
	default:
		g_return_if_reached ();
	}

	if (   old_flags == priv->unmanaged_flags
	    && old_mask == priv->unmanaged_mask)
		return;

	transition_state =    allow_state_transition
	                   && was_managed != nm_device_get_managed (self, FALSE)
	                   && (   was_managed
	                       || (   !was_managed
	                           && nm_device_get_state (self) == NM_DEVICE_STATE_UNMANAGED));

	_LOGD (LOGD_DEVICE, "unmanaged: flags set to [%s%s0x%0x/0x%x/%s%s], %s [%s=0x%0x]%s%s%s)",
	       _unmanaged_flags2str (priv->unmanaged_flags, priv->unmanaged_mask, str1, sizeof (str1)), \
	       (priv->unmanaged_flags | priv->unmanaged_mask) ? "=" : "", \
	       (guint) priv->unmanaged_flags, \
	       (guint) priv->unmanaged_mask, \
	       (_get_managed_by_flags (priv->unmanaged_flags, priv->unmanaged_mask, FALSE) \
	            ? "managed" \
	            : (_get_managed_by_flags (priv->unmanaged_flags, priv->unmanaged_mask, TRUE) \
	                   ? "manageable" \
	                   : "unmanaged")),
	       priv->real ? "" : "/unrealized",
	       operation,
	       nm_unmanaged_flags2str (flags, str2, sizeof (str2)),
	       flags,
	       NM_PRINT_FMT_QUOTED (allow_state_transition,
	                            ", reason ",
	                            reason_to_string_a (reason),
	                            transition_state ? ", transition-state" : "",
	                            ""));

	if (   do_notify_has_pending_actions
	    && had_pending_actions != nm_device_has_pending_action (self))
		_notify (self, PROP_HAS_PENDING_ACTION);

	if (transition_state) {
		new_state = was_managed ? NM_DEVICE_STATE_UNMANAGED : NM_DEVICE_STATE_UNAVAILABLE;
		if (now)
			nm_device_state_changed (self, new_state, reason);
		else
			nm_device_queue_state (self, new_state, reason);
	}
}

/**
 * @self: the #NMDevice instance
 * @flags: which #NMUnmanagedFlags to set.
 * @set_op: whether to set/clear/forget the flags. You can also pass
 *   boolean values %TRUE and %FALSE, which mean %NM_UNMAN_FLAG_OP_SET_UNMANAGED
 *   and %NM_UNMAN_FLAG_OP_SET_MANAGED, respectively.
 *
 * Set the unmanaged flags of the device (does not trigger a state change).
 **/
void
nm_device_set_unmanaged_flags (NMDevice *self,
                               NMUnmanagedFlags flags,
                               NMUnmanFlagOp set_op)
{
	_set_unmanaged_flags (self, flags, set_op, FALSE, FALSE, NM_DEVICE_STATE_REASON_NONE);
}

/**
 * nm_device_set_unmanaged_by_flags:
 * @self: the #NMDevice instance
 * @flags: which #NMUnmanagedFlags to set.
 * @set_op: whether to set/clear/forget the flags. You can also pass
 *   boolean values %TRUE and %FALSE, which mean %NM_UNMAN_FLAG_OP_SET_UNMANAGED
 *   and %NM_UNMAN_FLAG_OP_SET_MANAGED, respectively.
 * @reason: the device state reason passed to nm_device_state_changed() if
 *   the device becomes managed/unmanaged.
 *
 * Set the unmanaged flags of the device and possibly trigger a state change.
 **/
void
nm_device_set_unmanaged_by_flags (NMDevice *self,
                                  NMUnmanagedFlags flags,
                                  NMUnmanFlagOp set_op,
                                  NMDeviceStateReason reason)
{
	_set_unmanaged_flags (self, flags, set_op, TRUE, TRUE, reason);
}

void
nm_device_set_unmanaged_by_flags_queue (NMDevice *self,
                                        NMUnmanagedFlags flags,
                                        NMUnmanFlagOp set_op,
                                        NMDeviceStateReason reason)
{
	_set_unmanaged_flags (self, flags, set_op, TRUE, FALSE, reason);
}

/**
 * nm_device_check_unrealized_device_managed:
 *
 * Checks if a unrealized device is managed from user settings
 * or user configuration.
 */
gboolean
nm_device_check_unrealized_device_managed (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	nm_assert (!nm_device_is_real (self));

	if (!nm_config_data_get_device_config_boolean (NM_CONFIG_GET_DATA,
	                                               NM_CONFIG_KEYFILE_KEY_DEVICE_MANAGED,
	                                               self,
	                                               TRUE,
	                                               TRUE))
		return FALSE;

	if (nm_device_spec_match_list (self, nm_settings_get_unmanaged_specs (priv->settings)))
		return FALSE;

	return TRUE;
}

void
nm_device_set_unmanaged_by_user_settings (NMDevice *self)
{
	gboolean unmanaged;

	g_return_if_fail (NM_IS_DEVICE (self));

	if (nm_device_get_unmanaged_flags (self, NM_UNMANAGED_PLATFORM_INIT)) {
		/* the device is already unmanaged due to platform-init.
		 *
		 * We want to delay evaluating the device spec, because it will freeze
		 * the permanent MAC address. That should not be done, before the platform
		 * link is fully initialized (via UDEV).
		 *
		 * Note that when clearing NM_UNMANAGED_PLATFORM_INIT, we will re-evaluate
		 * whether the device is unmanaged by user-settings. */
		return;
	}

	unmanaged = nm_device_spec_match_list (self,
	                                       nm_settings_get_unmanaged_specs (NM_DEVICE_GET_PRIVATE (self)->settings));

	nm_device_set_unmanaged_by_flags (self,
	                                  NM_UNMANAGED_USER_SETTINGS,
	                                  !!unmanaged,
	                                  unmanaged
	                                      ? NM_DEVICE_STATE_REASON_NOW_UNMANAGED
	                                      : NM_DEVICE_STATE_REASON_NOW_MANAGED);
}

void
nm_device_set_unmanaged_by_user_udev (NMDevice *self)
{
	int ifindex;
	gboolean platform_unmanaged = FALSE;

	ifindex = self->_priv->ifindex;

	if (   ifindex <= 0
	    || !nm_platform_link_get_unmanaged (nm_device_get_platform (self), ifindex, &platform_unmanaged))
		return;

	nm_device_set_unmanaged_by_flags (self,
	                                  NM_UNMANAGED_USER_UDEV,
	                                  platform_unmanaged,
	                                  NM_DEVICE_STATE_REASON_USER_REQUESTED);
}

void
nm_device_set_unmanaged_by_user_conf (NMDevice *self)
{
	gboolean value;
	NMUnmanFlagOp set_op;

	value = nm_config_data_get_device_config_boolean (NM_CONFIG_GET_DATA,
	                                                  NM_CONFIG_KEYFILE_KEY_DEVICE_MANAGED,
	                                                  self,
	                                                  -1,
	                                                  TRUE);
	switch (value) {
	case TRUE:
		set_op = NM_UNMAN_FLAG_OP_SET_MANAGED;
		break;
	case FALSE:
		set_op = NM_UNMAN_FLAG_OP_SET_UNMANAGED;
		break;
	default:
		set_op = NM_UNMAN_FLAG_OP_FORGET;
		break;
	}

	nm_device_set_unmanaged_by_flags (self,
	                                  NM_UNMANAGED_USER_CONF,
	                                  set_op,
	                                  NM_DEVICE_STATE_REASON_USER_REQUESTED);
}

void
nm_device_set_unmanaged_by_quitting (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gboolean need_deactivate = nm_device_is_activating (self) ||
	                           priv->state == NM_DEVICE_STATE_ACTIVATED;

	/* It's OK to block here because we're quitting */
	if (need_deactivate)
		_set_state_full (self, NM_DEVICE_STATE_DEACTIVATING, NM_DEVICE_STATE_REASON_NOW_UNMANAGED, TRUE);

	nm_device_set_unmanaged_by_flags (self,
	                                  NM_UNMANAGED_QUITTING,
	                                  TRUE,
	                                  need_deactivate ? NM_DEVICE_STATE_REASON_REMOVED
	                                                  : NM_DEVICE_STATE_REASON_NOW_UNMANAGED);
}

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

void
nm_device_set_dhcp_anycast_address (NMDevice *self, const char *addr)
{
	NMDevicePrivate *priv;

	g_return_if_fail (NM_IS_DEVICE (self));
	g_return_if_fail (!addr || nm_utils_hwaddr_valid (addr, ETH_ALEN));

	priv = NM_DEVICE_GET_PRIVATE (self);

	g_free (priv->dhcp_anycast_address);
	priv->dhcp_anycast_address = g_strdup (addr);
}

void
nm_device_reapply_settings_immediately (NMDevice *self)
{
	NMConnection *applied_connection;
	NMSettingsConnection *settings_connection;
	NMDeviceState state;
	NMSettingConnection *s_con_settings;
	NMSettingConnection *s_con_applied;
	const char *zone;
	NMMetered metered;
	guint64 version_id;

	g_return_if_fail (NM_IS_DEVICE (self));

	state = nm_device_get_state (self);
	if (   state <= NM_DEVICE_STATE_DISCONNECTED
	    || state > NM_DEVICE_STATE_ACTIVATED)
		return;

	applied_connection = nm_device_get_applied_connection (self);
	settings_connection = nm_device_get_settings_connection (self);

	if (!nm_settings_connection_has_unmodified_applied_connection (settings_connection,
	                                                               applied_connection,
	                                                               NM_SETTING_COMPARE_FLAG_IGNORE_REAPPLY_IMMEDIATELY))
		return;

	s_con_settings = nm_connection_get_setting_connection (nm_settings_connection_get_connection (settings_connection));
	s_con_applied = nm_connection_get_setting_connection (applied_connection);

	if (!nm_streq0 ((zone = nm_setting_connection_get_zone (s_con_settings)),
	                nm_setting_connection_get_zone (s_con_applied))) {

		version_id = nm_active_connection_version_id_bump ((NMActiveConnection *) self->_priv->act_request.obj);
		_LOGD (LOGD_DEVICE, "reapply setting: zone = %s%s%s (version-id %llu)", NM_PRINT_FMT_QUOTE_STRING (zone), (unsigned long long) version_id);

		g_object_set (G_OBJECT (s_con_applied),
		              NM_SETTING_CONNECTION_ZONE, zone,
		              NULL);

		nm_device_update_firewall_zone (self);
	}

	if ((metered = nm_setting_connection_get_metered (s_con_settings)) != nm_setting_connection_get_metered (s_con_applied)) {

		version_id = nm_active_connection_version_id_bump ((NMActiveConnection *) self->_priv->act_request.obj);
		_LOGD (LOGD_DEVICE, "reapply setting: metered = %d (version-id %llu)", (int) metered, (unsigned long long) version_id);

		g_object_set (G_OBJECT (s_con_applied),
		              NM_SETTING_CONNECTION_METERED, metered,
		              NULL);

		nm_device_update_metered (self);
	}
}

void
nm_device_update_firewall_zone (NMDevice *self)
{
	NMDevicePrivate *priv;

	g_return_if_fail (NM_IS_DEVICE (self));

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (   priv->fw_state >= FIREWALL_STATE_INITIALIZED
	    && !nm_device_sys_iface_state_is_external (self))
		fw_change_zone (self);
}

void
nm_device_update_metered (NMDevice *self)
{
#define NM_METERED_INVALID ((NMMetered) -1)
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMSettingConnection *setting;
	NMMetered conn_value, value = NM_METERED_INVALID;
	NMConnection *connection = NULL;
	NMDeviceState state;

	g_return_if_fail (NM_IS_DEVICE (self));

	state = nm_device_get_state (self);
	if (   state <= NM_DEVICE_STATE_DISCONNECTED
	    || state > NM_DEVICE_STATE_ACTIVATED)
		value = NM_METERED_UNKNOWN;

	if (value == NM_METERED_INVALID) {
		connection = nm_device_get_applied_connection (self);
		if (connection) {
			setting = nm_connection_get_setting_connection (connection);
			if (setting) {
				conn_value = nm_setting_connection_get_metered (setting);
				if (conn_value != NM_METERED_UNKNOWN)
					value = conn_value;
			}
		}
	}

	if (   value == NM_METERED_INVALID
	    && NM_DEVICE_GET_CLASS (self)->get_guessed_metered
	    && NM_DEVICE_GET_CLASS (self)->get_guessed_metered (self))
		value = NM_METERED_GUESS_YES;

	/* Try to guess a value using the metered flag in IP configuration */
	if (value == NM_METERED_INVALID) {
		if (   priv->ip_config_4
		    && priv->ip_state_4 == NM_DEVICE_IP_STATE_DONE
		    && nm_ip4_config_get_metered (priv->ip_config_4))
			value = NM_METERED_GUESS_YES;
	}

	/* Otherwise, look at connection type. For Bluetooth, we look at the type of
	 * Bluetooth sharing: for PANU/DUN (where we are receiving internet from
	 * another device) we set GUESS_YES; for NAP (where we are sharing internet
	 * to another device) we set GUESS_NO. We ignore WiMAX here as it’s no
	 * longer supported by NetworkManager. */
	if (   value == NM_METERED_INVALID
	    && nm_connection_is_type (connection, NM_SETTING_BLUETOOTH_SETTING_NAME)) {

		if (_nm_connection_get_setting_bluetooth_for_nap (connection)) {
			/* NAP types are not metered, but other types are. */
			value = NM_METERED_GUESS_NO;
		} else
			value = NM_METERED_GUESS_YES;
	}

	if (value == NM_METERED_INVALID) {
		if (   nm_connection_is_type (connection, NM_SETTING_GSM_SETTING_NAME)
		    || nm_connection_is_type (connection, NM_SETTING_CDMA_SETTING_NAME))
			value = NM_METERED_GUESS_YES;
		else
			value = NM_METERED_GUESS_NO;
	}

	if (value != priv->metered) {
		_LOGD (LOGD_DEVICE, "set metered value %d", value);
		priv->metered = value;
		_notify (self, PROP_METERED);
	}
}

static NMDeviceCheckDevAvailableFlags
_device_check_dev_available_flags_from_con (NMDeviceCheckConAvailableFlags con_flags)
{
	NMDeviceCheckDevAvailableFlags dev_flags;

	dev_flags = NM_DEVICE_CHECK_DEV_AVAILABLE_NONE;

	if (NM_FLAGS_HAS (con_flags, _NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST_WAITING_CARRIER))
		dev_flags |= _NM_DEVICE_CHECK_DEV_AVAILABLE_IGNORE_CARRIER;

	return dev_flags;
}

static gboolean
_nm_device_check_connection_available (NMDevice *self,
                                       NMConnection *connection,
                                       NMDeviceCheckConAvailableFlags flags,
                                       const char *specific_object,
                                       GError **error)
{
	NMDeviceState state;
	GError *local = NULL;

	/* an unrealized software device is always available, hardware devices never. */
	if (!nm_device_is_real (self)) {
		if (nm_device_is_software (self)) {
			if (!nm_device_check_connection_compatible (self, connection,
			                                            error ? &local : NULL)) {
				if (error) {
					g_return_val_if_fail (local, FALSE);
					nm_utils_error_set (error,
					                    local->domain == NM_UTILS_ERROR
					                      ? local->code
					                      : NM_UTILS_ERROR_UNKNOWN,
					                    "profile is not compatible with software device (%s)",
					                    local->message);
					g_error_free (local);
				}
				return FALSE;
			}
			return TRUE;
		}
		nm_utils_error_set_literal (error, NM_UTILS_ERROR_CONNECTION_AVAILABLE_UNMANAGED_DEVICE,
		                            "hardware device is not realized");
		return FALSE;
	}

	state = nm_device_get_state (self);
	if (state < NM_DEVICE_STATE_UNMANAGED) {
		nm_utils_error_set_literal (error, NM_UTILS_ERROR_CONNECTION_AVAILABLE_UNMANAGED_DEVICE,
		                            "device is in unknown state");
		return FALSE;
	}
	if (state < NM_DEVICE_STATE_UNAVAILABLE) {
		if (nm_device_get_managed (self, FALSE)) {
			/* device is managed, both for user-requests and non-user-requests alike. */
		} else {
			if (!nm_device_get_managed (self, TRUE)) {
				/* device is strictly unmanaged by authoritative unmanaged reasons. */
				nm_utils_error_set_literal (error, NM_UTILS_ERROR_CONNECTION_AVAILABLE_UNMANAGED_DEVICE,
				                            "device is strictly unmanaged");
				return FALSE;
			}
			if (!NM_FLAGS_HAS (flags, _NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST_OVERRULE_UNMANAGED)) {
				/* device could be managed for an explict user-request, but this is not such a request. */
				nm_utils_error_set_literal (error, NM_UTILS_ERROR_CONNECTION_AVAILABLE_UNMANAGED_DEVICE,
				                            "device is currently unmanaged");
				return FALSE;
			}
		}
	}
	if (   state < NM_DEVICE_STATE_DISCONNECTED
	    && !nm_device_is_software (self)) {
		if (!nm_device_is_available (self, _device_check_dev_available_flags_from_con (flags))) {
			if (NM_FLAGS_HAS (flags, _NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST)) {
				nm_utils_error_set_literal (error, NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
				                            "device is not available");
			} else {
				nm_utils_error_set_literal (error, NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
				                            "device is not available for internal request");
			}
			return FALSE;
		}
	}

	if (!nm_device_check_connection_compatible (self, connection,
	                                            error ? &local : NULL)) {
		if (error) {
			nm_utils_error_set (error,
			                    local->domain == NM_UTILS_ERROR
			                      ? local->code
			                      : NM_UTILS_ERROR_UNKNOWN,
			                    "profile is not compatible with device (%s)",
			                    local->message);
			g_error_free (local);
		}
		return FALSE;
	}

	return NM_DEVICE_GET_CLASS (self)->check_connection_available (self, connection, flags, specific_object, error);
}

/**
 * nm_device_check_connection_available():
 * @self: the #NMDevice
 * @connection: the #NMConnection to check for availability
 * @flags: flags to affect the decision making of whether a connection
 *   is available. Adding a flag can only make a connection more available,
 *   not less.
 * @specific_object: a device type dependent argument to further
 *   filter the result. Passing a non %NULL specific object can only reduce
 *   the availability of a connection.
 * @error: optionally give reason why not available.
 *
 * Check if @connection is available to be activated on @self.
 *
 * Returns: %TRUE if @connection can be activated on @self
 */
gboolean
nm_device_check_connection_available (NMDevice *self,
                                      NMConnection *connection,
                                      NMDeviceCheckConAvailableFlags flags,
                                      const char *specific_object,
                                      GError **error)
{
	gboolean available;

	available = _nm_device_check_connection_available (self, connection, flags, specific_object, error);

#if NM_MORE_ASSERTS >= 2
	{
		/* The meaning of the flags is so that *adding* a flag relaxes a condition, thus making
		 * the device *more* available. Assert against that requirement by testing all the flags. */
		NMDeviceCheckConAvailableFlags i, j, k;
		gboolean available_all[NM_DEVICE_CHECK_CON_AVAILABLE_ALL + 1] = { FALSE };

		for (i = 0; i <= NM_DEVICE_CHECK_CON_AVAILABLE_ALL; i++)
			available_all[i] = _nm_device_check_connection_available (self, connection, i, specific_object, NULL);

		for (i = 0; i <= NM_DEVICE_CHECK_CON_AVAILABLE_ALL; i++) {
			for (j = 1; j <= NM_DEVICE_CHECK_CON_AVAILABLE_ALL; j <<= 1) {
				if (NM_FLAGS_ANY (i, j)) {
					k = i & ~j;
					nm_assert (   available_all[i] == available_all[k]
					           || available_all[i]);
				}
			}
		}
	}
#endif

	return available;
}

static gboolean
available_connections_del_all (NMDevice *self)
{
	if (g_hash_table_size (self->_priv->available_connections) == 0)
		return FALSE;
	g_hash_table_remove_all (self->_priv->available_connections);
	return TRUE;
}

static gboolean
available_connections_add (NMDevice *self, NMSettingsConnection *sett_conn)
{
	return g_hash_table_add (self->_priv->available_connections, g_object_ref (sett_conn));
}

static gboolean
available_connections_del (NMDevice *self, NMSettingsConnection *sett_conn)
{
	return g_hash_table_remove (self->_priv->available_connections, sett_conn);
}

static gboolean
check_connection_available (NMDevice *self,
                            NMConnection *connection,
                            NMDeviceCheckConAvailableFlags flags,
                            const char *specific_object,
                            GError **error)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE(self);

	/* Connections which require a network connection are not available when
	 * the device has no carrier, even with ignore-carrer=TRUE.
	 */
	if (   priv->carrier
	    || !connection_requires_carrier (connection))
		return TRUE;

	if (   NM_FLAGS_HAS (flags, _NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST_WAITING_CARRIER)
	    && priv->carrier_wait_id != 0) {
		/* The device has no carrier though the connection requires it.
		 *
		 * If we are still waiting for carrier, the connection is available
		 * for an explicit user-request. */
		return TRUE;
	}

	/* master types are always available even without carrier.
	 * Making connection non-available would un-enslave slaves which
	 * is not desired. */
	if (nm_device_is_master (self))
		return TRUE;

	nm_utils_error_set_literal (error, NM_UTILS_ERROR_CONNECTION_AVAILABLE_TEMPORARY,
	                            "device has no carrier");
	return FALSE;
}

void
nm_device_recheck_available_connections (NMDevice *self)
{
	NMDevicePrivate *priv;
	NMSettingsConnection *const*connections;
	gboolean changed = FALSE;
	GHashTableIter h_iter;
	NMSettingsConnection *sett_conn;
	guint i;
	gs_unref_hashtable GHashTable *prune_list = NULL;

	g_return_if_fail (NM_IS_DEVICE (self));

	priv = NM_DEVICE_GET_PRIVATE(self);

	if (g_hash_table_size (priv->available_connections) > 0) {
		prune_list = g_hash_table_new (nm_direct_hash, NULL);
		g_hash_table_iter_init (&h_iter, priv->available_connections);
		while (g_hash_table_iter_next (&h_iter, (gpointer *) &sett_conn, NULL))
			g_hash_table_add (prune_list, sett_conn);
	}

	connections = nm_settings_get_connections (priv->settings, NULL);
	for (i = 0; connections[i]; i++) {
		sett_conn = connections[i];

		if (nm_device_check_connection_available (self,
		                                          nm_settings_connection_get_connection (sett_conn),
		                                          NM_DEVICE_CHECK_CON_AVAILABLE_NONE,
		                                          NULL,
		                                          NULL)) {
			if (available_connections_add (self, sett_conn))
				changed = TRUE;
			if (prune_list)
				g_hash_table_remove (prune_list, sett_conn);
		}
	}

	if (prune_list) {
		g_hash_table_iter_init (&h_iter, prune_list);
		while (g_hash_table_iter_next (&h_iter, (gpointer *) &sett_conn, NULL)) {
			if (available_connections_del (self, sett_conn))
				changed = TRUE;
		}
	}

	if (changed)
		_notify (self, PROP_AVAILABLE_CONNECTIONS);
	available_connections_check_delete_unrealized (self);
}

/**
 * nm_device_get_best_connection:
 * @self: the #NMDevice
 * @specific_object: a specific object path if any
 * @error: reason why no connection was returned
 *
 * Returns a connection that's most suitable for user-initiated activation
 * of a device, optionally with a given specific object.
 *
 * Returns: the #NMSettingsConnection or %NULL (setting an @error)
 */
NMSettingsConnection *
nm_device_get_best_connection (NMDevice *self,
                               const char *specific_object,
                               GError **error)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMSettingsConnection *sett_conn = NULL;
	NMSettingsConnection *candidate;
	guint64 best_timestamp = 0;
	GHashTableIter iter;

	g_hash_table_iter_init (&iter, priv->available_connections);
	while (g_hash_table_iter_next (&iter, (gpointer) &candidate, NULL)) {
		guint64 candidate_timestamp = 0;

		/* If a specific object is given, only include connections that are
		 * compatible with it.
		 */
		if (    specific_object /* << Optimization: we know that the connection is available without @specific_object.  */
		    && !nm_device_check_connection_available (self,
		                                              nm_settings_connection_get_connection (candidate),
		                                              _NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST,
		                                              specific_object,
		                                              NULL))
			continue;

		nm_settings_connection_get_timestamp (candidate, &candidate_timestamp);
		if (!sett_conn || (candidate_timestamp > best_timestamp)) {
			sett_conn = candidate;
			best_timestamp = candidate_timestamp;
		}
	}

	if (!sett_conn) {
		g_set_error (error, NM_MANAGER_ERROR, NM_MANAGER_ERROR_UNKNOWN_CONNECTION,
		             "The device '%s' has no connections available for activation.",
		              nm_device_get_iface (self));
	}

	return sett_conn;
}

static void
cp_connection_added_or_updated (NMDevice *self, NMSettingsConnection *sett_conn)
{
	gboolean changed;

	g_return_if_fail (NM_IS_DEVICE (self));
	g_return_if_fail (NM_IS_SETTINGS_CONNECTION (sett_conn));

	if (nm_device_check_connection_available (self,
	                                          nm_settings_connection_get_connection (sett_conn),
	                                          _NM_DEVICE_CHECK_CON_AVAILABLE_FOR_USER_REQUEST,
	                                          NULL,
	                                          NULL))
		changed = available_connections_add (self, sett_conn);
	else
		changed = available_connections_del (self, sett_conn);

	if (changed) {
		_notify (self, PROP_AVAILABLE_CONNECTIONS);
		available_connections_check_delete_unrealized (self);
	}
}

static void
cp_connection_added (NMSettings *settings, NMSettingsConnection *sett_conn, gpointer user_data)
{
	cp_connection_added_or_updated (user_data, sett_conn);
}

static void
cp_connection_updated (NMSettings *settings, NMSettingsConnection *sett_conn, guint update_reason_u, gpointer user_data)
{
	cp_connection_added_or_updated (user_data, sett_conn);
}

static void
cp_connection_removed (NMSettings *settings, NMSettingsConnection *sett_conn, gpointer user_data)
{
	NMDevice *self = user_data;

	g_return_if_fail (NM_IS_DEVICE (self));

	if (available_connections_del (self, sett_conn)) {
		_notify (self, PROP_AVAILABLE_CONNECTIONS);
		available_connections_check_delete_unrealized (self);
	}
}

gboolean
nm_device_supports_vlans (NMDevice *self)
{
	return nm_platform_link_supports_vlans (nm_device_get_platform (self), nm_device_get_ifindex (self));
}

/**
 * nm_device_add_pending_action():
 * @self: the #NMDevice to add the pending action to
 * @action: a static string that identifies the action. The string instance must
 *   stay valid until the pending action is removed (that is, the string is
 *   not cloned, but ownership stays with the caller).
 * @assert_not_yet_pending: if %TRUE, assert that the @action is currently not yet pending.
 * Otherwise, ignore duplicate scheduling of the same action silently.
 *
 * Adds a pending action to the device.
 *
 * Returns: %TRUE if the action was added (and not already added before). %FALSE
 * if the same action is already scheduled. In the latter case, the action was not scheduled
 * a second time.
 */
gboolean
nm_device_add_pending_action (NMDevice *self, const char *action, gboolean assert_not_yet_pending)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	GSList *iter;
	guint count = 0;

	g_return_val_if_fail (action, FALSE);

	/* Check if the action is already pending. Cannot add duplicate actions */
	for (iter = priv->pending_actions; iter; iter = iter->next) {
		if (nm_streq (action, iter->data)) {
			if (assert_not_yet_pending) {
				_LOGW (LOGD_DEVICE, "add_pending_action (%d): '%s' already pending",
				       count + g_slist_length (iter), action);
				g_return_val_if_reached (FALSE);
			} else {
				_LOGT (LOGD_DEVICE, "add_pending_action (%d): '%s' already pending (expected)",
				       count + g_slist_length (iter), action);
			}
			return FALSE;
		}
		count++;
	}

	priv->pending_actions = g_slist_prepend (priv->pending_actions, (char *) action);
	count++;

	_LOGD (LOGD_DEVICE, "add_pending_action (%d): '%s'", count, action);

	if (count == 1)
		_notify (self, PROP_HAS_PENDING_ACTION);

	return TRUE;
}

/**
 * nm_device_remove_pending_action():
 * @self: the #NMDevice to remove the pending action from
 * @action: a string that identifies the action.
 * @assert_is_pending: if %TRUE, assert that the @action is pending.
 * If %FALSE, don't do anything if the current action is not pending and
 * return %FALSE.
 *
 * Removes a pending action previously added by nm_device_add_pending_action().
 *
 * Returns: whether the @action was pending and is now removed.
 */
gboolean
nm_device_remove_pending_action (NMDevice *self, const char *action, gboolean assert_is_pending)
{
	NMDevicePrivate *priv;
	GSList *iter, *next;
	guint count = 0;

	g_return_val_if_fail (self, FALSE);
	g_return_val_if_fail (action, FALSE);

	priv = NM_DEVICE_GET_PRIVATE (self);

	for (iter = priv->pending_actions; iter; iter = next) {
		next = iter->next;
		if (nm_streq (action, iter->data)) {
			_LOGD (LOGD_DEVICE, "remove_pending_action (%d): '%s'",
			       count + g_slist_length (iter->next), /* length excluding 'iter' */
			       action);
			priv->pending_actions = g_slist_delete_link (priv->pending_actions, iter);
			if (priv->pending_actions == NULL)
				_notify (self, PROP_HAS_PENDING_ACTION);
			return TRUE;
		}
		count++;
	}

	if (assert_is_pending) {
		_LOGW (LOGD_DEVICE, "remove_pending_action (%d): '%s' not pending", count, action);
		g_return_val_if_reached (FALSE);
	} else
		_LOGT (LOGD_DEVICE, "remove_pending_action (%d): '%s' not pending (expected)", count, action);

	return FALSE;
}

const char *
nm_device_has_pending_action_reason (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->pending_actions) {

		if (   !priv->pending_actions->next
		    && nm_device_get_state (self) == NM_DEVICE_STATE_ACTIVATED
		    && nm_streq (priv->pending_actions->data, NM_PENDING_ACTION_CARRIER_WAIT)) {
			/* if the device is already in activated state, and the only reason
			 * why it appears still busy is "carrier-wait", then we are already complete. */
			return NULL;
		}

		return priv->pending_actions->data;
	}

	if (   nm_device_is_real (self)
	    && nm_device_get_unmanaged_flags (self, NM_UNMANAGED_PLATFORM_INIT)) {
		/* as long as the platform link is not yet initialized, we have a pending
		 * action. */
		return NM_PENDING_ACTION_LINK_INIT;
	}

	return NULL;
}

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

static void
_cancel_activation (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->fw_call) {
		nm_firewall_manager_cancel_call (priv->fw_call);
		nm_assert (!priv->fw_call);
		priv->fw_call = NULL;
		priv->fw_state = FIREWALL_STATE_INITIALIZED;
	}

	ip_check_gw_ping_cleanup (self);

	/* Break the activation chain */
	activation_source_clear (self, AF_INET);
	activation_source_clear (self, AF_INET6);
}

static void
_cleanup_generic_pre (NMDevice *self, CleanupType cleanup_type)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	_cancel_activation (self);

	priv->stage1_sriov_state = NM_DEVICE_STAGE_STATE_INIT;

	if (cleanup_type != CLEANUP_TYPE_KEEP) {
		nm_manager_device_route_metric_clear (NM_MANAGER_GET,
		                                      nm_device_get_ip_ifindex (self));
	}

	if (   cleanup_type == CLEANUP_TYPE_DECONFIGURE
	    && priv->fw_state >= FIREWALL_STATE_INITIALIZED
	    && priv->fw_mgr
	    && !nm_device_sys_iface_state_is_external (self)) {
		nm_firewall_manager_remove_from_zone (priv->fw_mgr,
		                                      nm_device_get_ip_iface (self),
		                                      NULL,
		                                      NULL,
		                                      NULL);
	}
	priv->fw_state = FIREWALL_STATE_UNMANAGED;
	g_clear_object (&priv->fw_mgr);

	queued_state_clear (self);

	_cleanup_ip_pre (self, AF_INET, cleanup_type);
	_cleanup_ip_pre (self, AF_INET6, cleanup_type);
}

static void
_cleanup_generic_post (NMDevice *self, CleanupType cleanup_type)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	priv->v4_commit_first_time = TRUE;
	priv->v6_commit_first_time = TRUE;

	priv->v4_route_table_initialized = FALSE;
	priv->v6_route_table_initialized = FALSE;
	priv->l3config_merge_flags_has = FALSE;

	priv->v4_route_table_all_sync_before = FALSE;
	priv->v6_route_table_all_sync_before = FALSE;

	priv->default_route_metric_penalty_ip4_has = FALSE;
	priv->default_route_metric_penalty_ip6_has = FALSE;

	priv->linklocal6_dad_counter = 0;

	/* Clean up IP configs; this does not actually deconfigure the
	 * interface; the caller must flush routes and addresses explicitly.
	 */
	nm_device_set_ip_config (self, AF_INET, NULL, TRUE, NULL);
	nm_device_set_ip_config (self, AF_INET6, NULL, TRUE, NULL);
	g_clear_object (&priv->proxy_config);
	g_clear_object (&priv->con_ip_config_4);
	applied_config_clear (&priv->dev_ip_config_4);
	applied_config_clear (&priv->dev2_ip_config_4);
	g_clear_object (&priv->ext_ip_config_4);
	g_clear_object (&priv->ip_config_4);
	g_clear_object (&priv->con_ip_config_6);
	applied_config_clear (&priv->ac_ip6_config);
	g_clear_object (&priv->ext_ip_config_6);
	g_clear_object (&priv->ext_ip6_config_captured);
	applied_config_clear (&priv->dev2_ip_config_6);
	g_clear_object (&priv->ip_config_6);
	g_clear_object (&priv->dad6_ip6_config);
	priv->ipv6ll_has = FALSE;
	memset (&priv->ipv6ll_addr, 0, sizeof (priv->ipv6ll_addr));

	nm_clear_pointer (&priv->rt6_temporary_not_available, g_hash_table_unref);
	nm_clear_g_source (&priv->rt6_temporary_not_available_id);

	g_slist_free_full (priv->vpn_configs_4, g_object_unref);
	priv->vpn_configs_4 = NULL;
	g_slist_free_full (priv->vpn_configs_6, g_object_unref);
	priv->vpn_configs_6 = NULL;

	/* We no longer accept the delegations. nm_device_set_ip_config(NULL)
	 * above disables them. */
	nm_assert (priv->needs_ip6_subnet == FALSE);

	if (priv->act_request.obj) {
		nm_active_connection_set_default (NM_ACTIVE_CONNECTION (priv->act_request.obj), AF_INET, FALSE);
		nm_clear_g_signal_handler (priv->act_request.obj, &priv->master_ready_id);
		act_request_set (self, NULL);
	}

	/* Clear legacy IPv4 address property */
	if (priv->ip4_address) {
		priv->ip4_address = 0;
		_notify (self, PROP_IP4_ADDRESS);
	}

	if (cleanup_type == CLEANUP_TYPE_DECONFIGURE) {
		/* Check if the device was deactivated, and if so, delete_link.
		 * Don't call delete_link synchronously because we are currently
		 * handling a state change -- which is not reentrant. */
		delete_on_deactivate_check_and_schedule (self, nm_device_get_ip_ifindex (self));
	}

	/* ip_iface should be cleared after flushing all routes and addresses, since
	 * those are identified by ip_iface, not by iface (which might be a tty
	 * or ATM device).
	 */
	_set_ip_ifindex (self, 0, NULL);
}

/*
 * nm_device_cleanup
 *
 * Remove a device's routing table entries and IP addresses.
 *
 */
static void
nm_device_cleanup (NMDevice *self, NMDeviceStateReason reason, CleanupType cleanup_type)
{
	NMDevicePrivate *priv;
	int ifindex;

	g_return_if_fail (NM_IS_DEVICE (self));

	if (reason == NM_DEVICE_STATE_REASON_NOW_MANAGED)
		_LOGD (LOGD_DEVICE, "preparing device");
	else
		_LOGD (LOGD_DEVICE, "deactivating device (reason '%s') [%d]", reason_to_string_a (reason), reason);

	/* Save whether or not we tried IPv6 for later */
	priv = NM_DEVICE_GET_PRIVATE (self);

	_cleanup_generic_pre (self, cleanup_type);

	/* Turn off kernel IPv6 */
	if (cleanup_type == CLEANUP_TYPE_DECONFIGURE) {
		set_disable_ipv6 (self, "1");
		nm_device_sysctl_ip_conf_set (self, AF_INET6, "use_tempaddr", "0");
	}

	/* Call device type-specific deactivation */
	if (NM_DEVICE_GET_CLASS (self)->deactivate)
		NM_DEVICE_GET_CLASS (self)->deactivate (self);

	ifindex = nm_device_get_ip_ifindex (self);

	if (cleanup_type == CLEANUP_TYPE_DECONFIGURE) {
		/* master: release slaves */
		nm_device_master_release_slaves (self);

		/* Take out any entries in the routing table and any IP address the device had. */
		if (ifindex > 0) {
			NMPlatform *platform = nm_device_get_platform (self);
			NMUtilsIPv6IfaceId iid = { };

			nm_platform_ip_route_flush (platform, AF_UNSPEC, ifindex);
			nm_platform_ip_address_flush (platform, AF_UNSPEC, ifindex);
			nm_platform_tfilter_sync (platform, ifindex, NULL);
			nm_platform_qdisc_sync (platform, ifindex, NULL);
			set_ipv6_token (self, iid, "::");
		}
	}

	_routing_rules_sync (self,
	                       cleanup_type == CLEANUP_TYPE_KEEP
	                     ? NM_TERNARY_DEFAULT
	                     : NM_TERNARY_FALSE);

	if (ifindex > 0)
		nm_platform_ip4_dev_route_blacklist_set (nm_device_get_platform (self), ifindex, NULL);

	/* slave: mark no longer enslaved */
	if (   priv->master
	    && priv->ifindex > 0
	    && nm_platform_link_get_master (nm_device_get_platform (self), priv->ifindex) <= 0)
		nm_device_master_release_one_slave (priv->master, self, FALSE, FALSE, NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED);

	if (priv->lldp_listener)
		nm_lldp_listener_stop (priv->lldp_listener);

	nm_device_update_metered (self);

	if (ifindex > 0) {
		/* during device cleanup, we want to reset the MAC address of the device
		 * to the initial state.
		 *
		 * We certainly want to do that when reaching the UNMANAGED state... */
		if (nm_device_get_state (self) <= NM_DEVICE_STATE_UNMANAGED)
			nm_device_hw_addr_reset (self, "unmanage");
		else {
			/* for other device states (UNAVAILABLE, DISCONNECTED), allow the
			 * device to overwrite the reset behavior, so that Wi-Fi can set
			 * a randomized MAC address used during scanning. */
			NM_DEVICE_GET_CLASS (self)->deactivate_reset_hw_addr (self);
		}
	}

	priv->mtu_source = NM_DEVICE_MTU_SOURCE_NONE;
	priv->ip6_mtu = 0;
	if (priv->mtu_initial || priv->ip6_mtu_initial) {
		ifindex = nm_device_get_ip_ifindex (self);

		if (   ifindex > 0
		    && cleanup_type == CLEANUP_TYPE_DECONFIGURE) {
			_LOGT (LOGD_DEVICE, "mtu: reset device-mtu: %u, ipv6-mtu: %u, ifindex: %d",
			       (guint) priv->mtu_initial, (guint) priv->ip6_mtu_initial, ifindex);
			if (priv->mtu_initial) {
				nm_platform_link_set_mtu (nm_device_get_platform (self), ifindex, priv->mtu_initial);
				priv->carrier_wait_until_ms = nm_utils_get_monotonic_timestamp_msec () + CARRIER_WAIT_TIME_AFTER_MTU_MS;
			}
			if (priv->ip6_mtu_initial) {
				char sbuf[64];

				nm_device_sysctl_ip_conf_set (self, AF_INET6, "mtu",
				                              nm_sprintf_buf (sbuf, "%u", (unsigned) priv->ip6_mtu_initial));
			}
		}
		priv->mtu_initial = 0;
		priv->ip6_mtu_initial = 0;
	}

	_ethtool_state_reset (self);

	_cleanup_generic_post (self, cleanup_type);
}

static void
deactivate_reset_hw_addr (NMDevice *self)
{
	nm_device_hw_addr_reset (self, "deactivate");
}

static char *
find_dhcp4_address (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	const NMPlatformIP4Address *a;
	NMDedupMultiIter ipconf_iter;

	if (!priv->ip_config_4)
		return NULL;

	nm_ip_config_iter_ip4_address_for_each (&ipconf_iter, priv->ip_config_4, &a) {
		if (a->addr_source == NM_IP_CONFIG_SOURCE_DHCP)
			return nm_utils_inet4_ntop_dup (a->address);
	}
	return NULL;
}

void
nm_device_spawn_iface_helper (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	gboolean configured = FALSE;
	NMConnection *connection;
	GError *error = NULL;
	const char *method;
	GPtrArray *argv;
	gs_free char *dhcp4_address = NULL;
	char *logging_backend;
	NMUtilsStableType stable_type;
	const char *stable_id;

	if (priv->state != NM_DEVICE_STATE_ACTIVATED)
		return;
	if (!nm_device_can_assume_connections (self))
		return;

	connection = nm_device_get_applied_connection (self);

	g_return_if_fail (connection);

	argv = g_ptr_array_sized_new (10);
	g_ptr_array_set_free_func (argv, g_free);

	g_ptr_array_add (argv, g_strdup (LIBEXECDIR "/nm-iface-helper"));
	g_ptr_array_add (argv, g_strdup ("--ifname"));
	g_ptr_array_add (argv, g_strdup (nm_device_get_ip_iface (self)));
	g_ptr_array_add (argv, g_strdup ("--uuid"));
	g_ptr_array_add (argv, g_strdup (nm_connection_get_uuid (connection)));

	stable_id = _get_stable_id (self, connection, &stable_type);
	if (stable_type != NM_UTILS_STABLE_TYPE_UUID) {
		g_ptr_array_add (argv, g_strdup ("--stable-id"));
		g_ptr_array_add (argv, g_strdup_printf ("%d %s", (int) stable_type, stable_id));
	}

	logging_backend = nm_config_data_get_value (NM_CONFIG_GET_DATA_ORIG,
	                                            NM_CONFIG_KEYFILE_GROUP_LOGGING,
	                                            NM_CONFIG_KEYFILE_KEY_LOGGING_BACKEND,
	                                            NM_CONFIG_GET_VALUE_STRIP | NM_CONFIG_GET_VALUE_NO_EMPTY);
	if (logging_backend) {
		g_ptr_array_add (argv, g_strdup ("--logging-backend"));
		g_ptr_array_add (argv, logging_backend);
	}

	g_ptr_array_add (argv, g_strdup ("--log-level"));
	g_ptr_array_add (argv, g_strdup (nm_logging_level_to_string ()));

	g_ptr_array_add (argv, g_strdup ("--log-domains"));
	g_ptr_array_add (argv, g_strdup (nm_logging_domains_to_string ()));

	dhcp4_address = find_dhcp4_address (self);

	method = nm_device_get_effective_ip_config_method (self, AF_INET);
	if (nm_streq (method, NM_SETTING_IP4_CONFIG_METHOD_AUTO)) {
		NMSettingIPConfig *s_ip4;

		s_ip4 = nm_connection_get_setting_ip4_config (connection);
		nm_assert (s_ip4);

		g_ptr_array_add (argv, g_strdup ("--priority4"));
		g_ptr_array_add (argv, g_strdup_printf ("%u", nm_device_get_route_metric (self, AF_INET)));

		g_ptr_array_add (argv, g_strdup ("--dhcp4"));
		g_ptr_array_add (argv, g_strdup (dhcp4_address));
		if (nm_setting_ip_config_get_may_fail (s_ip4) == FALSE)
			g_ptr_array_add (argv, g_strdup ("--dhcp4-required"));

		if (priv->dhcp_data_4.client) {
			const char *hostname;
			GBytes *client_id;

			client_id = nm_dhcp_client_get_client_id (priv->dhcp_data_4.client);
			if (client_id) {
				g_ptr_array_add (argv, g_strdup ("--dhcp4-clientid"));
				g_ptr_array_add (argv,
				                 nm_utils_bin2hexstr_full (g_bytes_get_data (client_id, NULL),
				                                           g_bytes_get_size (client_id),
				                                           ':',
				                                           FALSE,
				                                           NULL));
			}

			hostname = nm_dhcp_client_get_hostname (priv->dhcp_data_4.client);
			if (hostname) {
				if (nm_dhcp_client_get_use_fqdn (priv->dhcp_data_4.client))
					g_ptr_array_add (argv, g_strdup ("--dhcp4-fqdn"));
				else
					g_ptr_array_add (argv, g_strdup ("--dhcp4-hostname"));
				g_ptr_array_add (argv, g_strdup (hostname));
			}
		}

		configured = TRUE;
	}

	method = nm_utils_get_ip_config_method (connection, AF_INET6);
	if (nm_streq (method, NM_SETTING_IP6_CONFIG_METHOD_AUTO)) {
		NMSettingIPConfig *s_ip6;
		NMUtilsIPv6IfaceId iid = NM_UTILS_IPV6_IFACE_ID_INIT;

		s_ip6 = nm_connection_get_setting_ip6_config (connection);
		g_assert (s_ip6);

		g_ptr_array_add (argv, g_strdup ("--priority6"));
		g_ptr_array_add (argv, g_strdup_printf ("%u", nm_device_get_route_metric (self, AF_INET6)));

		g_ptr_array_add (argv, g_strdup ("--slaac"));

		if (nm_setting_ip_config_get_may_fail (s_ip6) == FALSE)
			g_ptr_array_add (argv, g_strdup ("--slaac-required"));

		g_ptr_array_add (argv, g_strdup ("--slaac-tempaddr"));
		g_ptr_array_add (argv, g_strdup_printf ("%d", priv->ndisc_use_tempaddr));

		if (nm_device_get_ip_iface_identifier (self, &iid, FALSE)) {
			g_ptr_array_add (argv, g_strdup ("--iid"));
			g_ptr_array_add (argv,
			                 nm_utils_bin2hexstr_full (iid.id_u8,
			                                           sizeof (NMUtilsIPv6IfaceId),
			                                           ':',
			                                           FALSE,
			                                           NULL));
		}

		g_ptr_array_add (argv, g_strdup ("--addr-gen-mode"));
		g_ptr_array_add (argv, g_strdup_printf ("%d", nm_setting_ip6_config_get_addr_gen_mode (NM_SETTING_IP6_CONFIG (s_ip6))));

		configured = TRUE;
	}

	if (configured) {
		GPid pid;

		g_ptr_array_add (argv, NULL);

		if (nm_logging_enabled (LOGL_DEBUG, LOGD_DEVICE)) {
			char *tmp;

			tmp = g_strjoinv (" ", (char **) argv->pdata);
			_LOGD (LOGD_DEVICE, "running '%s'", tmp);
			g_free (tmp);
		}

		if (g_spawn_async (NULL, (char **) argv->pdata, NULL,
		                   G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &pid, &error)) {
			_LOGI (LOGD_DEVICE, "spawned helper PID %u", (guint) pid);
		} else {
			_LOGW (LOGD_DEVICE, "failed to spawn helper: %s", error->message);
			g_error_free (error);
		}
	}

	g_ptr_array_unref (argv);
}

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

static gboolean
ip_config_valid (NMDeviceState state)
{
	return (state == NM_DEVICE_STATE_UNMANAGED) ||
	        (state >= NM_DEVICE_STATE_IP_CHECK &&
	         state <= NM_DEVICE_STATE_DEACTIVATING);
}

static void
notify_ip_properties (NMDevice *self)
{
	_notify (self, PROP_IP_IFACE);
	_notify (self, PROP_IP4_CONFIG);
	_notify (self, PROP_DHCP4_CONFIG);
	_notify (self, PROP_IP6_CONFIG);
	_notify (self, PROP_DHCP6_CONFIG);
}

static void
ip6_managed_setup (NMDevice *self)
{
	set_nm_ipv6ll (self, TRUE);
	set_disable_ipv6 (self, "1");
	nm_device_sysctl_ip_conf_set (self, AF_INET6, "accept_ra", "0");
	nm_device_sysctl_ip_conf_set (self, AF_INET6, "use_tempaddr", "0");
	nm_device_sysctl_ip_conf_set (self, AF_INET6, "forwarding", "0");
}

static void
deactivate_ready (NMDevice *self, NMDeviceStateReason reason)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->dispatcher.call_id)
		return;

	if (priv->sriov_reset_pending > 0)
		return;

	if (priv->state == NM_DEVICE_STATE_DEACTIVATING)
		nm_device_queue_state (self, NM_DEVICE_STATE_DISCONNECTED, reason);
}

static void
sriov_reset_on_deactivate_cb (GError *error, gpointer user_data)
{
	NMDevice *self;
	NMDevicePrivate *priv;
	gpointer reason;

	nm_utils_user_data_unpack (user_data, &self, &reason);
	priv = NM_DEVICE_GET_PRIVATE (self);
	nm_assert (priv->sriov_reset_pending > 0);
	priv->sriov_reset_pending--;

	if (nm_utils_error_is_cancelled (error))
		return;

	deactivate_ready (self, GPOINTER_TO_INT (reason));
}

static void
sriov_reset_on_failure_cb (GError *error, gpointer user_data)
{
	NMDevice *self = user_data;
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	nm_assert (priv->sriov_reset_pending > 0);
	priv->sriov_reset_pending--;

	if (nm_utils_error_is_cancelled (error))
		return;

	if (priv->state == NM_DEVICE_STATE_FAILED) {
		nm_device_queue_state (self,
		                       NM_DEVICE_STATE_DISCONNECTED,
		                       NM_DEVICE_STATE_REASON_NONE);
	}
}

static void
deactivate_async_ready (NMDevice *self,
                        GError *error,
                        gpointer user_data)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMDeviceStateReason reason = GPOINTER_TO_UINT (user_data);

	if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
		_LOGD (LOGD_DEVICE, "Deactivation cancelled");
		return;
	}

	g_clear_object (&priv->deactivating_cancellable);

	/* In every other case, transition to the DISCONNECTED state */
	if (error) {
		_LOGW (LOGD_DEVICE, "Deactivation failed: %s",
		       error->message);
	}

	deactivate_ready (self, reason);
}

static void
deactivate_dispatcher_complete (NMDispatcherCallId *call_id, gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMDeviceStateReason reason;

	g_return_if_fail (call_id == priv->dispatcher.call_id);
	g_return_if_fail (priv->dispatcher.post_state == NM_DEVICE_STATE_DISCONNECTED);

	reason = priv->state_reason;

	priv->dispatcher.call_id = NULL;
	priv->dispatcher.post_state = NM_DEVICE_STATE_UNKNOWN;
	priv->dispatcher.post_state_reason = NM_DEVICE_STATE_REASON_NONE;

	if (nm_clear_g_cancellable (&priv->deactivating_cancellable))
		nm_assert_not_reached ();

	if (NM_DEVICE_GET_CLASS (self)->deactivate_async) {
		/* FIXME: the virtual function deactivate_async() has only this caller here.
		 * And the NMDevice subtypes are well aware of the circumstances when they
		 * are called. We shall make the function less generic and thus (as the scope
		 * is narrower) more convenient.
		 *
		 * - Drop the callback argument. Instead, when deactivate_async() completes, the
		 *   subtype shall call a method _nm_device_deactivate_async_done(). Because as
		 *   it is currently, subtypes need to pretend this callback and the user-data
		 *   would be opaque, and carry it around. When it's in fact very clear what this
		 *   is.
		 *
		 * - Also drop the GCancellable argument. Upon cancellation, NMDevice shall
		 *   call another virtual function deactivate_async_abort(). As it is currently,
		 *   callers need to register to the cancelled signal of the cancellable. It
		 *   seems simpler to just implement the deactivate_async_abort() function.
		 *   On the other hand, some implementations actually use the GCancellable.
		 *   So, NMDevice shall do both: it shall both pass a cancellable, but also
		 *   invoke deactivate_async_abort(). It allow the implementation to honor
		 *   whatever is simpler for their purpose.
		 *
		 * - sometimes, the subclass can complete right away. Scheduling the completion
		 *   in an idle handler is cumbersome. Allow the function to return FALSE to
		 *   indicate that the device is already deactivated and the callback (or
		 *   _nm_device_deactivate_async_done()) won't be invoked.
		 */
		priv->deactivating_cancellable = g_cancellable_new ();
		NM_DEVICE_GET_CLASS (self)->deactivate_async (self,
		                                              priv->deactivating_cancellable,
		                                              deactivate_async_ready,
		                                              GUINT_TO_POINTER (reason));
	} else
		deactivate_ready (self, reason);
}

static void
_set_state_full (NMDevice *self,
                 NMDeviceState state,
                 NMDeviceStateReason reason,
                 gboolean quitting)
{
	NMDevicePrivate *priv;
	NMDeviceState old_state;
	gs_unref_object NMActRequest *req = NULL;
	gboolean no_firmware = FALSE;
	NMSettingsConnection *sett_conn;
	NMSettingSriov *s_sriov;
	gboolean concheck_now;

	g_return_if_fail (NM_IS_DEVICE (self));

	priv = NM_DEVICE_GET_PRIVATE (self);

	/* Track re-entry */
	g_warn_if_fail (priv->in_state_changed == FALSE);

	old_state = priv->state;

	if (   state == NM_DEVICE_STATE_FAILED
	    && nm_device_sys_iface_state_is_external_or_assume (self)) {
		/* Avoid tearing down assumed connection, assume it's connected */
		state = NM_DEVICE_STATE_ACTIVATED;
		reason = NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED;
	}

	/* Do nothing if state isn't changing, but as a special case allow
	 * re-setting UNAVAILABLE if the device is missing firmware so that we
	 * can retry device initialization.
	 */
	if (   (priv->state == state)
	    && (   state != NM_DEVICE_STATE_UNAVAILABLE
	        || !priv->firmware_missing)) {
		_LOGD (LOGD_DEVICE, "state change: %s -> %s (reason '%s', sys-iface-state: '%s'%s)",
		       nm_device_state_to_str (old_state),
		       nm_device_state_to_str (state),
		       reason_to_string_a (reason),
		       _sys_iface_state_to_str (priv->sys_iface_state),
		       priv->firmware_missing ? ", missing firmware" : "");
		return;
	}

	_LOGI (LOGD_DEVICE, "state change: %s -> %s (reason '%s', sys-iface-state: '%s')",
	       nm_device_state_to_str (old_state),
	       nm_device_state_to_str (state),
	       reason_to_string_a (reason),
	       _sys_iface_state_to_str (priv->sys_iface_state));

	/* in order to prevent triggering any callback caused
	 * by the device not having any pending action anymore
	 * we add one here that gets removed at the end of the function */
	nm_device_add_pending_action (self,
	                              NM_PENDING_ACTION_IN_STATE_CHANGE,
	                              TRUE);
	priv->in_state_changed = TRUE;

	priv->state = state;
	priv->state_reason = reason;

	queued_state_clear (self);

	dispatcher_cleanup (self);

	nm_clear_g_cancellable (&priv->deactivating_cancellable);

	/* Cache the activation request for the dispatcher */
	req = nm_g_object_ref (priv->act_request.obj);

	if (   state >  NM_DEVICE_STATE_UNMANAGED
	    && state <= NM_DEVICE_STATE_ACTIVATED
	    && nm_device_state_reason_check (reason) == NM_DEVICE_STATE_REASON_NOW_MANAGED
	    && NM_IN_SET_TYPED (NMDeviceSysIfaceState,
	                        priv->sys_iface_state,
	                        NM_DEVICE_SYS_IFACE_STATE_EXTERNAL,
	                        NM_DEVICE_SYS_IFACE_STATE_ASSUME))
		nm_device_sys_iface_state_set (self, NM_DEVICE_SYS_IFACE_STATE_MANAGED);

	if (   state <= NM_DEVICE_STATE_DISCONNECTED
	    || state >= NM_DEVICE_STATE_ACTIVATED)
		priv->auth_retries = NM_DEVICE_AUTH_RETRIES_UNSET;

	if (state > NM_DEVICE_STATE_DISCONNECTED)
		nm_device_assume_state_reset (self);

	if (state <= NM_DEVICE_STATE_UNAVAILABLE) {
		if (available_connections_del_all (self))
			_notify (self, PROP_AVAILABLE_CONNECTIONS);
		if (old_state > NM_DEVICE_STATE_UNAVAILABLE) {
			_clear_queued_act_request (priv,
			                           NM_ACTIVE_CONNECTION_STATE_REASON_DEVICE_DISCONNECTED);
		}
	}

	/* Update the available connections list when a device first becomes available */
	if (state >= NM_DEVICE_STATE_DISCONNECTED && old_state < NM_DEVICE_STATE_DISCONNECTED)
		nm_device_recheck_available_connections (self);

	if (state <= NM_DEVICE_STATE_DISCONNECTED || state > NM_DEVICE_STATE_DEACTIVATING) {
		if (nm_clear_g_free (&priv->current_stable_id))
			_LOGT (LOGD_DEVICE, "stable-id: clear");
	}

	/* Handle the new state here; but anything that could trigger
	 * another state change should be done below.
	 */
	switch (state) {
	case NM_DEVICE_STATE_UNMANAGED:
		nm_device_set_firmware_missing (self, FALSE);
		if (old_state > NM_DEVICE_STATE_UNMANAGED) {
			if (priv->sys_iface_state != NM_DEVICE_SYS_IFACE_STATE_MANAGED) {
				nm_device_cleanup (self, reason,
				                   priv->sys_iface_state == NM_DEVICE_SYS_IFACE_STATE_REMOVED
				                       ? CLEANUP_TYPE_REMOVED
				                       : CLEANUP_TYPE_KEEP);
			} else {
				/* Clean up if the device is now unmanaged but was activated */
				if (nm_device_get_act_request (self))
					nm_device_cleanup (self, reason, CLEANUP_TYPE_DECONFIGURE);
				nm_device_take_down (self, TRUE);
				nm_device_hw_addr_reset (self, "unmanage");
				set_nm_ipv6ll (self, FALSE);
				restore_ip6_properties (self);
				break;
			}
		}
		break;
	case NM_DEVICE_STATE_UNAVAILABLE:
		if (old_state == NM_DEVICE_STATE_UNMANAGED) {
			save_ip6_properties (self);
			if (priv->sys_iface_state == NM_DEVICE_SYS_IFACE_STATE_MANAGED)
				ip6_managed_setup (self);
			device_init_static_sriov_num_vfs (self);
		}

		if (priv->sys_iface_state == NM_DEVICE_SYS_IFACE_STATE_MANAGED) {
			if (old_state == NM_DEVICE_STATE_UNMANAGED || priv->firmware_missing) {
				if (!nm_device_bring_up (self, TRUE, &no_firmware) && no_firmware)
					_LOGW (LOGD_PLATFORM, "firmware may be missing.");
				nm_device_set_firmware_missing (self, no_firmware ? TRUE : FALSE);
			}

			/* Ensure the device gets deactivated in response to stuff like
			 * carrier changes or rfkill.  But don't deactivate devices that are
			 * about to assume a connection since that defeats the purpose of
			 * assuming the device's existing connection.
			 *
			 * Note that we "deactivate" the device even when coming from
			 * UNMANAGED, to ensure that it's in a clean state.
			 */
			nm_device_cleanup (self, reason, CLEANUP_TYPE_DECONFIGURE);
		}
		break;
	case NM_DEVICE_STATE_DISCONNECTED:
		if (old_state > NM_DEVICE_STATE_DISCONNECTED) {
			/* Ensure devices that previously assumed a connection now have
			 * userspace IPv6LL enabled.
			 */
			set_nm_ipv6ll (self, TRUE);

			nm_device_cleanup (self, reason, CLEANUP_TYPE_DECONFIGURE);
		} else if (old_state < NM_DEVICE_STATE_DISCONNECTED) {
			if (priv->sys_iface_state == NM_DEVICE_SYS_IFACE_STATE_MANAGED) {
				/* Ensure IPv6 is set up as it may not have been done when
				 * entering the UNAVAILABLE state depending on the reason.
				 */
				ip6_managed_setup (self);
			}
		}
		break;
	case NM_DEVICE_STATE_PREPARE:
		nm_device_update_initial_hw_address (self);
		break;
	case NM_DEVICE_STATE_NEED_AUTH:
		if (old_state > NM_DEVICE_STATE_NEED_AUTH) {
			/* Clean up any half-done IP operations if the device's layer2
			 * finds out it needs authentication during IP config.
			 */
			_cleanup_ip_pre (self, AF_INET, CLEANUP_TYPE_DECONFIGURE);
			_cleanup_ip_pre (self, AF_INET6, CLEANUP_TYPE_DECONFIGURE);
		}
		break;
	default:
		break;
	}

	/* Reset intern autoconnect flags when the device is activating or connected. */
	if (   state >= NM_DEVICE_STATE_PREPARE
	    && state <= NM_DEVICE_STATE_ACTIVATED)
		nm_device_autoconnect_blocked_unset (self, NM_DEVICE_AUTOCONNECT_BLOCKED_INTERNAL);

	_notify (self, PROP_STATE);
	_notify (self, PROP_STATE_REASON);
	nm_dbus_object_emit_signal (NM_DBUS_OBJECT (self),
	                            &interface_info_device,
	                            &signal_info_state_changed,
	                            "(uuu)",
	                            (guint32) state,
	                            (guint32) old_state,
	                            (guint32) reason);
	g_signal_emit (self, signals[STATE_CHANGED], 0, (guint) state, (guint) old_state, (guint) reason);

	/* Post-process the event after internal notification */

	switch (state) {
	case NM_DEVICE_STATE_UNAVAILABLE:
		/* If the device can activate now (ie, it's got a carrier, the supplicant
		 * is active, or whatever) schedule a delayed transition to DISCONNECTED
		 * to get things rolling.  The device can't transition immediately because
		 * we can't change states again from the state handler for a variety of
		 * reasons.
		 */
		if (nm_device_is_available (self, NM_DEVICE_CHECK_DEV_AVAILABLE_NONE)) {
			nm_device_queue_recheck_available (self,
			                                   NM_DEVICE_STATE_REASON_NONE,
			                                   NM_DEVICE_STATE_REASON_NONE);
		} else {
			_LOGD (LOGD_DEVICE, "device not yet available for transition to DISCONNECTED");
		}
		break;
	case NM_DEVICE_STATE_DEACTIVATING:
		_cancel_activation (self);

		/* We cache the ignore_carrier state to not react on config-reloads while the connection
		 * is active. But on deactivating, reset the ignore-carrier flag to the current state. */
		priv->ignore_carrier = nm_config_data_get_ignore_carrier (NM_CONFIG_GET_DATA, self);

		if (quitting) {
			nm_dispatcher_call_device_sync (NM_DISPATCHER_ACTION_PRE_DOWN,
			                                self, req);
		} else {
			priv->dispatcher.post_state = NM_DEVICE_STATE_DISCONNECTED;
			priv->dispatcher.post_state_reason = reason;
			if (!nm_dispatcher_call_device (NM_DISPATCHER_ACTION_PRE_DOWN,
			                                self,
			                                req,
			                                deactivate_dispatcher_complete,
			                                self,
			                                &priv->dispatcher.call_id)) {
				/* Just proceed on errors */
				deactivate_dispatcher_complete (0, self);
			}

			if (   priv->ifindex > 0
			    && (s_sriov = nm_device_get_applied_setting (self, NM_TYPE_SETTING_SRIOV))) {
				priv->sriov_reset_pending++;
				sriov_op_queue (self,
				                0,
				                NM_TERNARY_TRUE,
				                sriov_reset_on_deactivate_cb,
				                nm_utils_user_data_pack (self, GINT_TO_POINTER (reason)));
			}
		}

		nm_pacrunner_manager_remove_clear (&priv->pacrunner_conf_id);
		break;
	case NM_DEVICE_STATE_DISCONNECTED:
		if (   priv->queued_act_request
		    && !priv->queued_act_request_is_waiting_for_carrier) {
			gs_unref_object NMActRequest *queued_req = NULL;

			queued_req = g_steal_pointer (&priv->queued_act_request);
			_device_activate (self, queued_req);
		}
		break;
	case NM_DEVICE_STATE_ACTIVATED:
		_LOGI (LOGD_DEVICE, "Activation: successful, device activated.");
		nm_device_update_metered (self);
		nm_dispatcher_call_device (NM_DISPATCHER_ACTION_UP,
		                           self,
		                           req,
		                           NULL, NULL, NULL);

		if (priv->proxy_config)
			_pacrunner_manager_add (self);
		break;
	case NM_DEVICE_STATE_FAILED:
		/* Usually upon failure the activation chain is interrupted in
		 * one of the stages; but in some cases the device fails for
		 * external events (as a failure of master connection) while
		 * the activation sequence is running and so we need to ensure
		 * that the chain is terminated here.
		 */
		_cancel_activation (self);

		sett_conn = nm_device_get_settings_connection (self);
		_LOGW (LOGD_DEVICE | LOGD_WIFI,
		       "Activation: failed for connection '%s'",
		       sett_conn ? nm_settings_connection_get_id (sett_conn) : "<unknown>");

		/* Notify any slaves of the unexpected failure */
		nm_device_master_release_slaves (self);

		/* If the connection doesn't yet have a timestamp, set it to zero so that
		 * we can distinguish between connections we've tried to activate and have
		 * failed (zero timestamp), connections that succeeded (non-zero timestamp),
		 * and those we haven't tried yet (no timestamp).
		 */
		if (sett_conn && !nm_settings_connection_get_timestamp (sett_conn, NULL))
			nm_settings_connection_update_timestamp (sett_conn, (guint64) 0);

		if (   priv->ifindex > 0
		    && (s_sriov = nm_device_get_applied_setting (self, NM_TYPE_SETTING_SRIOV))) {
			priv->sriov_reset_pending++;
			sriov_op_queue (self,
			                0,
			                NM_TERNARY_TRUE,
			                sriov_reset_on_failure_cb,
			                self);
			break;
		}
		/* Schedule the transition to DISCONNECTED.  The device can't transition
		 * immediately because we can't change states again from the state
		 * handler for a variety of reasons.
		 */
		nm_device_queue_state (self, NM_DEVICE_STATE_DISCONNECTED, NM_DEVICE_STATE_REASON_NONE);
		break;
	case NM_DEVICE_STATE_IP_CHECK:
		if (   priv->fw_state >= FIREWALL_STATE_INITIALIZED
		    && priv->ip_iface
		    && !nm_device_sys_iface_state_is_external (self)) {
			priv->fw_state = FIREWALL_STATE_WAIT_IP_CONFIG;
			fw_change_zone (self);
		} else
			nm_device_start_ip_check (self);

		/* IP-related properties are only valid when the device has IP configuration;
		 * now that it does, ensure their change notifications are emitted.
		 */
		notify_ip_properties (self);
		break;
	case NM_DEVICE_STATE_SECONDARIES:
		ip_check_gw_ping_cleanup (self);
		_LOGD (LOGD_DEVICE, "device entered SECONDARIES state");
		break;
	default:
		break;
	}

	if (state > NM_DEVICE_STATE_DISCONNECTED)
		delete_on_deactivate_unschedule (self);

	if (   (old_state == NM_DEVICE_STATE_ACTIVATED || old_state == NM_DEVICE_STATE_DEACTIVATING)
	    && (state != NM_DEVICE_STATE_DEACTIVATING)) {
		if (quitting) {
			nm_dispatcher_call_device_sync (NM_DISPATCHER_ACTION_DOWN,
			                                self, req);
		} else {
			nm_dispatcher_call_device (NM_DISPATCHER_ACTION_DOWN,
			                           self,
			                           req,
			                           NULL, NULL, NULL);
		}
	}

	/* IP-related properties are only valid when the device has IP configuration.
	 * If it no longer does, ensure their change notifications are emitted.
	 */
	if (   ip_config_valid (old_state)
	    && !ip_config_valid (state))
		notify_ip_properties (self);

	concheck_now =    NM_IN_SET (state, NM_DEVICE_STATE_ACTIVATED,
	                                    NM_DEVICE_STATE_DISCONNECTED)
	               || old_state >= NM_DEVICE_STATE_ACTIVATED;
	concheck_update_interval (self, AF_INET, concheck_now);
	concheck_update_interval (self, AF_INET6, concheck_now);

	priv->in_state_changed = FALSE;
	nm_device_remove_pending_action (self,
	                                 NM_PENDING_ACTION_IN_STATE_CHANGE,
	                                 TRUE);

	if ((old_state > NM_DEVICE_STATE_UNMANAGED) != (state > NM_DEVICE_STATE_UNMANAGED))
		_notify (self, PROP_MANAGED);
}

void
nm_device_state_changed (NMDevice *self,
                         NMDeviceState state,
                         NMDeviceStateReason reason)
{
	_set_state_full (self, state, reason, FALSE);
}

static gboolean
queued_state_set (gpointer user_data)
{
	NMDevice *self = NM_DEVICE (user_data);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMDeviceState new_state;
	NMDeviceStateReason new_reason;

	nm_assert (priv->queued_state.id);

	_LOGD (LOGD_DEVICE, "queue-state[%s, reason:%s, id:%u]: %s",
	       nm_device_state_to_str (priv->queued_state.state),
	       reason_to_string_a (priv->queued_state.reason),
	       priv->queued_state.id,
	       "change state");

	/* Clear queued state struct before triggering state change, since
	 * the state change may queue another state.
	 */
	priv->queued_state.id = 0;
	new_state = priv->queued_state.state;
	new_reason = priv->queued_state.reason;

	nm_device_state_changed (self, new_state, new_reason);
	nm_device_remove_pending_action (self, queued_state_to_string (new_state), TRUE);

	return G_SOURCE_REMOVE;
}

void
nm_device_queue_state (NMDevice *self,
                       NMDeviceState state,
                       NMDeviceStateReason reason)
{
	NMDevicePrivate *priv;

	g_return_if_fail (NM_IS_DEVICE (self));

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->queued_state.id && priv->queued_state.state == state) {
		_LOGD (LOGD_DEVICE, "queue-state[%s, reason:%s, id:%u]: %s%s%s%s",
		       nm_device_state_to_str (priv->queued_state.state),
		       reason_to_string_a (priv->queued_state.reason),
		       priv->queued_state.id,
		       "ignore queuing same state change",
		       NM_PRINT_FMT_QUOTED (priv->queued_state.reason != reason,
		                            " (reason differs: ", reason_to_string_a (reason), ")", ""));
		return;
	}

	/* Add pending action for the new state before clearing the queued states, so
	 * that we don't accidentally pop all pending states and reach 'startup complete'  */
	nm_device_add_pending_action (self, queued_state_to_string (state), TRUE);

	/* We should only ever have one delayed state transition at a time */
	if (priv->queued_state.id) {
		_LOGW (LOGD_DEVICE, "queue-state[%s, reason:%s, id:%u]: %s",
		       nm_device_state_to_str (priv->queued_state.state),
		       reason_to_string_a (priv->queued_state.reason),
		       priv->queued_state.id,
		       "replace previously queued state change");
		nm_clear_g_source (&priv->queued_state.id);
		nm_device_remove_pending_action (self, queued_state_to_string (priv->queued_state.state), TRUE);
	}

	priv->queued_state.state = state;
	priv->queued_state.reason = reason;
	priv->queued_state.id = g_idle_add (queued_state_set, self);

	_LOGD (LOGD_DEVICE, "queue-state[%s, reason:%s, id:%u]: %s",
	       nm_device_state_to_str (state),
	       reason_to_string_a (reason),
	       priv->queued_state.id,
	       "queue state change");
}

static void
queued_state_clear (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (!priv->queued_state.id)
		return;

	_LOGD (LOGD_DEVICE, "queue-state[%s, reason:%s, id:%u]: %s",
	       nm_device_state_to_str (priv->queued_state.state),
	       reason_to_string_a (priv->queued_state.reason),
	       priv->queued_state.id,
	       "clear queued state change");
	nm_clear_g_source (&priv->queued_state.id);
	nm_device_remove_pending_action (self, queued_state_to_string (priv->queued_state.state), TRUE);
}

NMDeviceState
nm_device_get_state (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), NM_DEVICE_STATE_UNKNOWN);

	return NM_DEVICE_GET_PRIVATE (self)->state;
}

/*****************************************************************************/
/* NMConfigDevice interface related stuff */

const char *
nm_device_get_hw_address (NMDevice *self)
{
	NMDevicePrivate *priv;
	char buf[NM_UTILS_HWADDR_LEN_MAX];
	gsize l;

	g_return_val_if_fail (NM_IS_DEVICE (self), NULL);

	priv = NM_DEVICE_GET_PRIVATE (self);

	nm_assert (   (!priv->hw_addr && priv->hw_addr_len == 0)
	           || (   priv->hw_addr
	               && _nm_utils_hwaddr_aton (priv->hw_addr, buf, sizeof (buf), &l)
	               && l == priv->hw_addr_len));

	return priv->hw_addr;
}

gboolean
nm_device_update_hw_address (NMDevice *self)
{
	NMDevicePrivate *priv;
	const guint8 *hwaddr;
	gsize hwaddrlen = 0;

	priv = NM_DEVICE_GET_PRIVATE (self);
	if (priv->ifindex <= 0)
		return FALSE;

	hwaddr = nm_platform_link_get_address (nm_device_get_platform (self), priv->ifindex, &hwaddrlen);

	if (   priv->type == NM_DEVICE_TYPE_ETHERNET
	    && hwaddr
	    && nm_utils_hwaddr_matches (hwaddr, hwaddrlen, nm_ip_addr_zero.addr_eth, sizeof (nm_ip_addr_zero.addr_eth)))
		hwaddrlen = 0;

	if (!hwaddrlen)
		return FALSE;

	if (   priv->hw_addr_len
	    && priv->hw_addr_len != hwaddrlen) {
		char s_buf[NM_UTILS_HWADDR_LEN_MAX_STR];

		/* we cannot change the address length of a device once it is set (except
		 * unrealizing the device).
		 *
		 * The reason is that the permanent and initial MAC addresses also must have the
		 * same address length, so it's unclear what it would mean that the length changes. */
		_LOGD (LOGD_PLATFORM | LOGD_DEVICE,
		       "hw-addr: read a MAC address with differing length (%s vs. %s)",
		       priv->hw_addr,
		       nm_utils_hwaddr_ntoa_buf (hwaddr, hwaddrlen, TRUE, s_buf, sizeof (s_buf)));
		return FALSE;
	}

	if (   priv->hw_addr
	    && nm_utils_hwaddr_matches (priv->hw_addr, -1, hwaddr, hwaddrlen))
		return FALSE;

	g_free (priv->hw_addr);
	priv->hw_addr_len_ = hwaddrlen;
	priv->hw_addr = nm_utils_hwaddr_ntoa (hwaddr, hwaddrlen);

	_LOGD (LOGD_PLATFORM | LOGD_DEVICE, "hw-addr: hardware address now %s", priv->hw_addr);
	_notify (self, PROP_HW_ADDRESS);

	if (   !priv->hw_addr_initial
	    || (   priv->hw_addr_type == HW_ADDR_TYPE_UNSET
	        && priv->state < NM_DEVICE_STATE_PREPARE
	        && !nm_device_is_activating (self))) {
		/* when we get a hw_addr the first time or while the device
		 * is not activated (with no explicit hw address set), always
		 * update our initial hw-address as well. */
		nm_device_update_initial_hw_address (self);
	}
	return TRUE;
}

void
nm_device_update_initial_hw_address (NMDevice *self)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	if (   priv->hw_addr
	    && !nm_streq0 (priv->hw_addr_initial, priv->hw_addr)) {
		if (   priv->hw_addr_initial
		    && priv->hw_addr_type != HW_ADDR_TYPE_UNSET) {
			/* once we have the initial hw address set, we only allow
			 * update if the currently type is "unset". */
			return;
		}
		g_free (priv->hw_addr_initial);
		priv->hw_addr_initial = g_strdup (priv->hw_addr);
		_LOGD (LOGD_DEVICE, "hw-addr: update initial MAC address %s",
		       priv->hw_addr_initial);
	}
}

void
nm_device_update_permanent_hw_address (NMDevice *self, gboolean force_freeze)
{
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	guint8 buf[NM_UTILS_HWADDR_LEN_MAX];
	size_t len = 0;
	gboolean success_read;
	int ifindex;
	const NMPlatformLink *pllink;
	const NMConfigDeviceStateData *dev_state;

	if (priv->hw_addr_perm) {
		/* the permanent hardware address is only read once and not
		 * re-read later.
		 *
		 * Except during unrealize/realize cycles, where we clear the permanent
		 * hardware address during unrealization. */
		return;
	}

	ifindex = priv->ifindex;
	if (ifindex <= 0)
		return;

	/* the user is advised to configure stable MAC addresses for software devices via
	 * UDEV. Thus, check whether the link is fully initialized. */
	pllink = nm_platform_link_get (nm_device_get_platform (self), ifindex);
	if (   !pllink
	    || !pllink->initialized) {
		if (!force_freeze) {
			/* we can afford to wait. Back off and leave the permanent MAC address
			 * undecided for now. */
			return;
		}
		/* try to refresh the link just to give UDEV a bit more time... */
		nm_platform_link_refresh (nm_device_get_platform (self), ifindex);
		/* maybe the MAC address changed... */
		nm_device_update_hw_address (self);
	} else if (!priv->hw_addr_len)
		nm_device_update_hw_address (self);

	if (!priv->hw_addr_len) {
		/* we need the current MAC address because we require the permanent MAC address
		 * to have the same length as the current address.
		 *
		 * Abort if there is no current MAC address. */
		return;
	}

	success_read = nm_platform_link_get_permanent_address (nm_device_get_platform (self), ifindex, buf, &len);
	if (success_read && priv->hw_addr_len == len) {
		priv->hw_addr_perm_fake = FALSE;
		priv->hw_addr_perm = nm_utils_hwaddr_ntoa (buf, len);
		_LOGD (LOGD_DEVICE, "hw-addr: read permanent MAC address '%s'",
		       priv->hw_addr_perm);
		goto notify_and_out;
	}

	/* we failed to read a permanent MAC address, thus we use a fake address,
	 * that is the current MAC address of the device.
	 *
	 * Note that the permanet MAC address of a NMDevice instance does not change
	 * after being set once. Thus, we use now a fake address and stick to that
	 * (until we unrealize the device). */
	priv->hw_addr_perm_fake = TRUE;

	/* We also persist our choice of the fake address to the device state
	 * file to use the same address on restart of NetworkManager.
	 * First, try to reload the address from the state file. */
	dev_state = nm_config_device_state_get (nm_config_get (), ifindex);
	if (   dev_state
	    && dev_state->perm_hw_addr_fake
	    && nm_utils_hwaddr_aton (dev_state->perm_hw_addr_fake, buf, priv->hw_addr_len)
	    && !nm_utils_hwaddr_matches (buf, priv->hw_addr_len, priv->hw_addr, -1)) {
		_LOGD (LOGD_PLATFORM | LOGD_ETHER, "hw-addr: %s (use from statefile: %s, current: %s)",
		       success_read
		           ? "read HW addr length of permanent MAC address differs"
		           : "unable to read permanent MAC address",
		       dev_state->perm_hw_addr_fake,
		       priv->hw_addr);
		priv->hw_addr_perm = nm_utils_hwaddr_ntoa (buf, priv->hw_addr_len);
		goto notify_and_out;
	}

	_LOGD (LOGD_PLATFORM | LOGD_ETHER, "hw-addr: %s (use current: %s)",
	       success_read
	           ? "read HW addr length of permanent MAC address differs"
	           : "unable to read permanent MAC address",
	       priv->hw_addr);
	priv->hw_addr_perm = g_strdup (priv->hw_addr);

notify_and_out:
	_notify (self, PROP_PERM_HW_ADDRESS);
}

static const char *
_get_cloned_mac_address_setting (NMDevice *self, NMConnection *connection, gboolean is_wifi, char **out_addr)
{
	NMSetting *setting;
	const char *addr = NULL;

	nm_assert (out_addr && !*out_addr);

	setting = nm_connection_get_setting (connection,
	                                     is_wifi ? NM_TYPE_SETTING_WIRELESS : NM_TYPE_SETTING_WIRED);
	if (setting) {
		addr = is_wifi
		       ? nm_setting_wireless_get_cloned_mac_address ((NMSettingWireless *) setting)
		       : nm_setting_wired_get_cloned_mac_address ((NMSettingWired *) setting);
	}

	if (!addr) {
		gs_free char *a = NULL;

		a = nm_config_data_get_connection_default (NM_CONFIG_GET_DATA,
		                                           is_wifi
		                                               ? NM_CON_DEFAULT ("wifi.cloned-mac-address")
		                                               : NM_CON_DEFAULT ("ethernet.cloned-mac-address"),
		                                           self);

		addr = NM_CLONED_MAC_PRESERVE;

		if (!a) {
			if (is_wifi) {
				NMSettingMacRandomization v;

				/* for backward compatibility, read the deprecated wifi.mac-address-randomization setting. */
				a = nm_config_data_get_connection_default (NM_CONFIG_GET_DATA,
				                                           NM_CON_DEFAULT ("wifi.mac-address-randomization"),
				                                           self);
				v = _nm_utils_ascii_str_to_int64 (a, 10,
				                                  NM_SETTING_MAC_RANDOMIZATION_DEFAULT,
				                                  NM_SETTING_MAC_RANDOMIZATION_ALWAYS,
				                                  NM_SETTING_MAC_RANDOMIZATION_DEFAULT);
				if (v == NM_SETTING_MAC_RANDOMIZATION_ALWAYS)
					addr = NM_CLONED_MAC_RANDOM;
			}
		} else if (   NM_CLONED_MAC_IS_SPECIAL (a)
		           || nm_utils_hwaddr_valid (a, ETH_ALEN))
			addr = *out_addr = g_steal_pointer (&a);
	}

	return addr;
}

static const char *
_get_generate_mac_address_mask_setting (NMDevice *self, NMConnection *connection, gboolean is_wifi, char **out_value)
{
	NMSetting *setting;
	const char *value = NULL;
	char *a;

	nm_assert (out_value && !*out_value);

	setting = nm_connection_get_setting (connection,
	                                     is_wifi ? NM_TYPE_SETTING_WIRELESS : NM_TYPE_SETTING_WIRED);
	if (setting) {
		value = is_wifi
		        ? nm_setting_wireless_get_generate_mac_address_mask ((NMSettingWireless *) setting)
		        : nm_setting_wired_get_generate_mac_address_mask ((NMSettingWired *) setting);
		if (value)
			return value;
	}

	a = nm_config_data_get_connection_default (NM_CONFIG_GET_DATA,
	                                           is_wifi
	                                               ? NM_CON_DEFAULT ("wifi.generate-mac-address-mask")
	                                               : NM_CON_DEFAULT ("ethernet.generate-mac-address-mask"),
	                                           self);
	if (!a)
		return NULL;
	*out_value = a;
	return a;
}

gboolean
nm_device_hw_addr_is_explict (NMDevice *self)
{
	NMDevicePrivate *priv;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	priv = NM_DEVICE_GET_PRIVATE (self);
	return !NM_IN_SET ((HwAddrType) priv->hw_addr_type,
	                   HW_ADDR_TYPE_PERMANENT,
	                   HW_ADDR_TYPE_UNSET);
}

static gboolean
_hw_addr_matches (NMDevice *self, const guint8 *addr, gsize addr_len)
{
	const char *cur_addr;

	cur_addr = nm_device_get_hw_address (self);
	return cur_addr && nm_utils_hwaddr_matches (addr, addr_len, cur_addr, -1);
}

static gboolean
_hw_addr_set (NMDevice *self,
              const char *const addr,
              const char *const operation,
              const char *const detail)
{
	NMDevicePrivate *priv;
	gboolean success = FALSE;
	int r;
	guint8 addr_bytes[NM_UTILS_HWADDR_LEN_MAX];
	gsize addr_len;
	gboolean was_taken_down = FALSE;
	gboolean retry_down;

	nm_assert (NM_IS_DEVICE (self));
	nm_assert (addr);
	nm_assert (operation);

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (!_nm_utils_hwaddr_aton (addr, addr_bytes, sizeof (addr_bytes), &addr_len))
		g_return_val_if_reached (FALSE);

	/* Do nothing if current MAC is same */
	if (_hw_addr_matches (self, addr_bytes, addr_len)) {
		_LOGT (LOGD_DEVICE, "set-hw-addr: no MAC address change needed (%s)", addr);
		return TRUE;
	}

	if (   priv->hw_addr_len
	    && priv->hw_addr_len != addr_len) {
		_LOGT (LOGD_DEVICE, "set-hw-addr: setting MAC address to '%s' (%s, %s) failed because of wrong address length (should be %u bytes)", addr, operation, detail, priv->hw_addr_len);
		return FALSE;
	}

	_LOGT (LOGD_DEVICE, "set-hw-addr: setting MAC address to '%s' (%s, %s)...", addr, operation, detail);

	if (nm_device_get_device_type (self) == NM_DEVICE_TYPE_WIFI) {
		/* Always take the device down for Wi-Fi because
		 * wpa_supplicant needs it to properly detect the MAC
		 * change. */
		retry_down = FALSE;
		was_taken_down = TRUE;
		nm_device_take_down (self, FALSE);
	}

again:
	r = nm_platform_link_set_address (nm_device_get_platform (self), nm_device_get_ip_ifindex (self), addr_bytes, addr_len);
	success = (r >= 0);
	if (!success) {
		retry_down =    !was_taken_down
		             && r != -NME_PL_NOT_FOUND
		             && nm_platform_link_is_up (nm_device_get_platform (self),
		                                        nm_device_get_ip_ifindex (self));
		_NMLOG (  (   retry_down
		           || r == -NME_PL_NOT_FOUND)
		        ? LOGL_DEBUG
		        : LOGL_WARN,
		        LOGD_DEVICE,
		        "set-hw-addr: failed to %s MAC address to %s (%s) (%s)%s",
		        operation, addr, detail,
		        nm_strerror (r),
		        retry_down ? " (retry with taking down)" : "");
	} else {
		/* MAC address successfully changed; update the current MAC to match */
		nm_device_update_hw_address (self);

		if (!_hw_addr_matches (self, addr_bytes, addr_len)) {
			gint64 poll_end, now;

			_LOGD (LOGD_DEVICE,
			       "set-hw-addr: new MAC address %s not successfully %s (%s) (refresh link)",
			       addr, operation, detail);

			/* The platform call indicated success, however the address is not
			 * as expected. That is either due to a driver issue (brcmfmac, bgo#770456,
			 * rh#1374023) or a race where externally the MAC address was reset.
			 * The race is rather unlikely.
			 *
			 * The alternative would be to postpone the activation in case the
			 * MAC address is not yet ready and poll without blocking. However,
			 * that is rather complicated and it is not expected that this case
			 * happens for regular drivers.
			 * Note that brcmfmac can block NetworkManager for 500 msec while
			 * taking down the device. Let's add another 100 msec to that.
			 *
			 * wait/poll up to 100 msec until it changes. */

			poll_end = nm_utils_get_monotonic_timestamp_usec () + (100 * 1000);
			for (;;) {
				if (!nm_platform_link_refresh (nm_device_get_platform (self), nm_device_get_ip_ifindex (self)))
					goto handle_fail;
				if (!nm_device_update_hw_address (self))
					goto handle_wait;
				if (!_hw_addr_matches (self, addr_bytes, addr_len))
					goto handle_fail;

				break;
handle_wait:
				now = nm_utils_get_monotonic_timestamp_usec ();
				if (now < poll_end) {
					g_usleep (NM_MIN (poll_end - now, 500));
					continue;
				}
handle_fail:
				success = FALSE;
				break;
			}
		}

		if (success) {
			retry_down = FALSE;
			_LOGI (LOGD_DEVICE, "set-hw-addr: %s MAC address to %s (%s)",
			       operation, addr, detail);
		} else {
			retry_down =    !was_taken_down
			             && nm_platform_link_is_up (nm_device_get_platform (self),
			                                        nm_device_get_ip_ifindex (self));

			_NMLOG (  retry_down
			        ? LOGL_DEBUG
			        : LOGL_WARN,
			        LOGD_DEVICE,
			        "set-hw-addr: new MAC address %s not successfully %s (%s)%s",
			        addr,
			        operation,
			        detail,
			        retry_down ? " (retry with taking down)" : "");
		}
	}

	if (retry_down) {
		/* changing the MAC address failed, but also the device was up (and we did not yet try to take
		 * it down). Optimally, we change the MAC address without taking the device down, but some
		 * devices don't like that. So, retry with taking the device down. */
		retry_down = FALSE;
		was_taken_down = TRUE;
		nm_device_take_down (self, FALSE);
		goto again;
	}

	if (was_taken_down) {
		if (!nm_device_bring_up (self, TRUE, NULL))
			return FALSE;
	}

	return success;
}

gboolean
nm_device_hw_addr_set (NMDevice *self,
                       const char *addr,
                       const char *detail,
                       gboolean set_permanent)
{
	NMDevicePrivate *priv;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (!addr)
		g_return_val_if_reached (FALSE);

	if (set_permanent) {
		/* The type is set to PERMANENT by NMDeviceVlan when taking the MAC
		 * address from the parent and by NMDeviceWifi when setting a random MAC
		 * address during scanning.
		 */
		priv->hw_addr_type = HW_ADDR_TYPE_PERMANENT;
	}

	return _hw_addr_set (self, addr, "set", detail);
}

/*
 * _hw_addr_get_cloned:
 * @self: a #NMDevice
 * @connection: a #NMConnection
 * @is_wifi: whether the device is Wi-Fi
 * @preserve: (out): whether the address must be reset to initial one
 * @hwaddr: (out): the cloned MAC address to set on interface
 * @hwaddr_type: (out): the type of address to set
 * @hwaddr_detail: (out): the detail (origin) of address to set
 * @error: (out): on return, an error or %NULL
 *
 * Computes the MAC to be set on a interface. On success, one of the
 * following exclusive conditions are verified:
 *
 *  - @preserve is %TRUE: the address must be reset to the initial one
 *  - @hwaddr is not %NULL: the given address must be set on the device
 *  - @hwaddr is %NULL and @preserve is %FALSE: no action needed
 *
 * Returns: %FALSE in case of error in determining the cloned MAC address,
 * %TRUE otherwise
 */
static gboolean
_hw_addr_get_cloned (NMDevice *self, NMConnection *connection, gboolean is_wifi,
                     gboolean *preserve, char **hwaddr, HwAddrType *hwaddr_type,
                     char **hwaddr_detail, GError **error)
{
	NMDevicePrivate *priv;
	gs_free char *addr_setting_free = NULL;
	gs_free char *hw_addr_generated = NULL;
	gs_free char *generate_mac_address_mask_tmp = NULL;
	const char *addr, *addr_setting;
	char *addr_out;
	HwAddrType type_out;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
	g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE);
	g_return_val_if_fail (!error || !*error, FALSE);

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (!connection)
		g_return_val_if_reached (FALSE);

	addr = addr_setting = _get_cloned_mac_address_setting (self, connection, is_wifi, &addr_setting_free);

	if (nm_streq (addr, NM_CLONED_MAC_PRESERVE)) {
		/* "preserve" means to reset the initial MAC address. */
		NM_SET_OUT (preserve, TRUE);
		NM_SET_OUT (hwaddr, NULL);
		NM_SET_OUT (hwaddr_type, HW_ADDR_TYPE_UNSET);
		NM_SET_OUT (hwaddr_detail, g_steal_pointer (&addr_setting_free) ?: g_strdup (addr_setting));
		return TRUE;
	}

	if (nm_streq (addr, NM_CLONED_MAC_PERMANENT)) {
		gboolean is_fake;

		addr = nm_device_get_permanent_hw_address_full (self, TRUE, &is_fake);
		if (is_fake) {
			/* Preserve the current address if the permanent address if fake */
			NM_SET_OUT (preserve, TRUE);
			NM_SET_OUT (hwaddr, NULL);
			NM_SET_OUT (hwaddr_type, HW_ADDR_TYPE_UNSET);
			NM_SET_OUT (hwaddr_detail, g_steal_pointer (&addr_setting_free) ?: g_strdup (addr_setting));
			return TRUE;
		} else if (!addr) {
			g_set_error_literal (error,
			                     NM_DEVICE_ERROR,
			                     NM_DEVICE_ERROR_FAILED,
			                     "failed to retrieve permanent address");
			return FALSE;
		}
		addr_out = g_strdup (addr);
		type_out = HW_ADDR_TYPE_PERMANENT;
	} else if (NM_IN_STRSET (addr, NM_CLONED_MAC_RANDOM)) {
		if (priv->hw_addr_type == HW_ADDR_TYPE_GENERATED) {
			/* hm, we already use a generate MAC address. Most certainly, that is from the same
			 * activation request, so we should not create a new random address, instead keep
			 * the current. */
			goto out_no_action;
		}
		hw_addr_generated = nm_utils_hw_addr_gen_random_eth (nm_device_get_initial_hw_address (self),
		                                                     _get_generate_mac_address_mask_setting (self, connection,
		                                                                                             is_wifi,
		                                                                                             &generate_mac_address_mask_tmp));
		if (!hw_addr_generated) {
			g_set_error (error,
			             NM_DEVICE_ERROR,
			             NM_DEVICE_ERROR_FAILED,
			             "failed to generate %s MAC address", "random");
			return FALSE;
		}

		addr_out = g_steal_pointer (&hw_addr_generated);
		type_out = HW_ADDR_TYPE_GENERATED;
	} else if (NM_IN_STRSET (addr, NM_CLONED_MAC_STABLE)) {
		NMUtilsStableType stable_type;
		const char *stable_id;

		if (priv->hw_addr_type == HW_ADDR_TYPE_GENERATED) {
			/* hm, we already use a generate MAC address. Most certainly, that is from the same
			 * activation request, so let's skip creating the stable address anew. */
			goto out_no_action;
		}

		stable_id = _get_stable_id (self, connection, &stable_type);
		hw_addr_generated = nm_utils_hw_addr_gen_stable_eth (stable_type, stable_id,
		                                                     nm_device_get_ip_iface (self),
		                                                     nm_device_get_initial_hw_address (self),
		                                                     _get_generate_mac_address_mask_setting (self, connection, is_wifi, &generate_mac_address_mask_tmp));
		if (!hw_addr_generated) {
			g_set_error (error,
			             NM_DEVICE_ERROR,
			             NM_DEVICE_ERROR_FAILED,
			             "failed to generate %s MAC address", "stable");
			return FALSE;
		}

		addr_out = g_steal_pointer (&hw_addr_generated);
		type_out = HW_ADDR_TYPE_GENERATED;
	} else {
		/* this must be a valid address. Otherwise, we shouldn't come here. */
		if (!nm_utils_hwaddr_valid (addr, -1))
			g_return_val_if_reached (FALSE);

		addr_out = g_strdup (addr);
		type_out = HW_ADDR_TYPE_EXPLICIT;
	}

	NM_SET_OUT (preserve, FALSE);
	NM_SET_OUT (hwaddr, addr_out);
	NM_SET_OUT (hwaddr_type, type_out);
	NM_SET_OUT (hwaddr_detail, g_steal_pointer (&addr_setting_free) ?: g_strdup (addr_setting));
	return TRUE;
out_no_action:
	NM_SET_OUT (preserve, FALSE);
	NM_SET_OUT (hwaddr, NULL);
	NM_SET_OUT (hwaddr_type, HW_ADDR_TYPE_UNSET);
	NM_SET_OUT (hwaddr_detail, NULL);
	return TRUE;
}

gboolean
nm_device_hw_addr_get_cloned (NMDevice *self, NMConnection *connection, gboolean is_wifi,
                              char **hwaddr, gboolean *preserve, GError **error)
{
	if (!_hw_addr_get_cloned (self, connection, is_wifi, preserve, hwaddr, NULL, NULL, error))
		return FALSE;

	return TRUE;
}

gboolean
nm_device_hw_addr_set_cloned (NMDevice *self, NMConnection *connection, gboolean is_wifi)
{
	NMDevicePrivate *priv;
	gboolean preserve = FALSE;
	gs_free char *hwaddr = NULL;
	gs_free char *detail = NULL;
	HwAddrType type = HW_ADDR_TYPE_UNSET;
	gs_free_error GError *error = NULL;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);
	priv = NM_DEVICE_GET_PRIVATE (self);

	if (!_hw_addr_get_cloned (self, connection, is_wifi, &preserve, &hwaddr, &type, &detail, &error)) {
		_LOGW (LOGD_DEVICE, "set-hw-addr: %s", error->message);
		return FALSE;
	}

	if (preserve)
		return nm_device_hw_addr_reset (self, detail);

	if (hwaddr) {
		priv->hw_addr_type = type;
		return _hw_addr_set (self, hwaddr, "set-cloned", detail);
	}

	return TRUE;
}

gboolean
nm_device_hw_addr_reset (NMDevice *self, const char *detail)
{
	NMDevicePrivate *priv;
	const char *addr;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (priv->hw_addr_type == HW_ADDR_TYPE_UNSET)
		return TRUE;

	priv->hw_addr_type = HW_ADDR_TYPE_UNSET;
	addr = nm_device_get_initial_hw_address (self);
	if (!addr) {
		/* as hw_addr_type is not UNSET, we expect that we can get an
		 * initial address to which to reset. */
		g_return_val_if_reached (FALSE);
	}

	return _hw_addr_set (self, addr, "reset", detail);
}

const char *
nm_device_get_permanent_hw_address_full (NMDevice *self, gboolean force_freeze, gboolean *out_is_fake)
{
	NMDevicePrivate *priv;

	g_return_val_if_fail (NM_IS_DEVICE (self), NULL);

	priv = NM_DEVICE_GET_PRIVATE (self);

	if (   !priv->hw_addr_perm
	    && force_freeze) {
		/* somebody requests a permanent MAC address, but we don't have it set
		 * yet. We cannot delay it any longer and try to get it without waiting
		 * for UDEV. */
		nm_device_update_permanent_hw_address (self, TRUE);
	}

	NM_SET_OUT (out_is_fake, priv->hw_addr_perm && priv->hw_addr_perm_fake);
	return priv->hw_addr_perm;
}

const char *
nm_device_get_permanent_hw_address (NMDevice *self)
{
	return nm_device_get_permanent_hw_address_full (self, TRUE, NULL);
}

const char *
nm_device_get_initial_hw_address (NMDevice *self)
{
	g_return_val_if_fail (NM_IS_DEVICE (self), NULL);

	return NM_DEVICE_GET_PRIVATE (self)->hw_addr_initial;
}

/**
 * nm_device_spec_match_list:
 * @self: an #NMDevice
 * @specs: (element-type utf8): a list of device specs
 *
 * Checks if @self matches any of the specifications in @specs. The
 * currently-supported spec types are:
 *
 *     "mac:00:11:22:33:44:55" - matches a device with the given
 *     hardware address
 *
 *     "interface-name:foo0" - matches a device with the given
 *     interface name
 *
 *     "s390-subchannels:00.11.22" - matches a device with the given
 *     z/VM / s390 subchannels.
 *
 *     "*" - matches any device
 *
 * Returns: #TRUE if @self matches one of the specs in @specs
 */
gboolean
nm_device_spec_match_list (NMDevice *self, const GSList *specs)
{
	return nm_device_spec_match_list_full (self, specs, FALSE);
}

int
nm_device_spec_match_list_full (NMDevice *self, const GSList *specs, int no_match_value)
{
	NMDeviceClass *klass;
	NMMatchSpecMatchType m;
	const char *hw_address = NULL;
	gboolean is_fake;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	klass = NM_DEVICE_GET_CLASS (self);
	hw_address = nm_device_get_permanent_hw_address_full (self,
	                                                      !nm_device_get_unmanaged_flags (self, NM_UNMANAGED_PLATFORM_INIT),
	                                                      &is_fake);

	m = nm_match_spec_device (specs,
	                          nm_device_get_iface (self),
	                          nm_device_get_type_description (self),
	                          nm_device_get_driver (self),
	                          nm_device_get_driver_version (self),
	                          is_fake ? NULL : hw_address,
	                          klass->get_s390_subchannels ? klass->get_s390_subchannels (self) : NULL,
	                          nm_dhcp_manager_get_config (nm_dhcp_manager_get ()));

	switch (m) {
	case NM_MATCH_SPEC_MATCH:
		return TRUE;
	case NM_MATCH_SPEC_NEG_MATCH:
		return FALSE;
	case NM_MATCH_SPEC_NO_MATCH:
		return no_match_value;
	}
	nm_assert_not_reached ();
	return no_match_value;
}

guint
nm_device_get_supplicant_timeout (NMDevice *self)
{
	NMConnection *connection;
	NMSetting8021x *s_8021x;
	int timeout;
#define SUPPLICANT_DEFAULT_TIMEOUT 25

	g_return_val_if_fail (NM_IS_DEVICE (self), SUPPLICANT_DEFAULT_TIMEOUT);

	connection = nm_device_get_applied_connection (self);

	g_return_val_if_fail (connection, SUPPLICANT_DEFAULT_TIMEOUT);

	s_8021x = nm_connection_get_setting_802_1x (connection);
	if (s_8021x) {
		timeout = nm_setting_802_1x_get_auth_timeout (s_8021x);
		if (timeout > 0)
			return timeout;
	}

	return nm_config_data_get_connection_default_int64 (NM_CONFIG_GET_DATA,
	                                                    NM_CON_DEFAULT ("802-1x.auth-timeout"),
	                                                    self,
	                                                    1,
	                                                    G_MAXINT32,
	                                                    SUPPLICANT_DEFAULT_TIMEOUT);
}

gboolean
nm_device_auth_retries_try_next (NMDevice *self)
{
	NMDevicePrivate *priv;
	NMSettingConnection *s_con;
	int auth_retries;

	g_return_val_if_fail (NM_IS_DEVICE (self), FALSE);

	priv = NM_DEVICE_GET_PRIVATE (self);
	auth_retries = priv->auth_retries;

	if (G_UNLIKELY (auth_retries == NM_DEVICE_AUTH_RETRIES_UNSET)) {
		auth_retries = -1;

		s_con = nm_device_get_applied_setting (self, NM_TYPE_SETTING_CONNECTION);
		if (s_con)
			auth_retries = nm_setting_connection_get_auth_retries (s_con);

		if (auth_retries == -1) {
			auth_retries = nm_config_data_get_connection_default_int64 (NM_CONFIG_GET_DATA,
			                                                            NM_CON_DEFAULT ("connection.auth-retries"),
			                                                            self,
			                                                            -1, G_MAXINT32, -1);
		}

		if (auth_retries == 0)
			auth_retries = NM_DEVICE_AUTH_RETRIES_INFINITY;
		else if (auth_retries == -1)
			auth_retries = NM_DEVICE_AUTH_RETRIES_DEFAULT;
		else
			nm_assert (auth_retries > 0);

		priv->auth_retries = auth_retries;
	}

	if (auth_retries == NM_DEVICE_AUTH_RETRIES_INFINITY)
		return TRUE;
	if (auth_retries <= 0) {
		nm_assert (auth_retries == 0);
		return FALSE;
	}
	priv->auth_retries--;
	return TRUE;
}

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

static const char *
_activation_func_to_string (ActivationHandleFunc func)
{
#define FUNC_TO_STRING_CHECK_AND_RETURN(func, f) \
	G_STMT_START { \
		if ((func) == (f)) \
			return #f; \
	} G_STMT_END
	FUNC_TO_STRING_CHECK_AND_RETURN (func, activate_stage1_device_prepare);
	FUNC_TO_STRING_CHECK_AND_RETURN (func, activate_stage2_device_config);
	FUNC_TO_STRING_CHECK_AND_RETURN (func, activate_stage3_ip_config_start);
	FUNC_TO_STRING_CHECK_AND_RETURN (func, activate_stage4_ip_config_timeout_4);
	FUNC_TO_STRING_CHECK_AND_RETURN (func, activate_stage4_ip_config_timeout_6);
	FUNC_TO_STRING_CHECK_AND_RETURN (func, activate_stage5_ip_config_result_4);
	FUNC_TO_STRING_CHECK_AND_RETURN (func, activate_stage5_ip_config_result_6);
	g_return_val_if_reached ("unknown");
}

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

static void
get_property (GObject *object, guint prop_id,
              GValue *value, GParamSpec *pspec)
{
	NMDevice *self = NM_DEVICE (object);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	GVariantBuilder array_builder;

	switch (prop_id) {
	case PROP_UDI:
		/* UDI is (depending on the device type) a path to sysfs and can contain
		 * non-UTF-8.
		 *   ip link add name $'d\xccf\\c' type dummy  */
		g_value_take_string (value,
		                     nm_utils_str_utf8safe_escape_cp (priv->udi,
		                                                      NM_UTILS_STR_UTF8_SAFE_FLAG_NONE));
		break;
	case PROP_PATH:
		g_value_take_string (value,
		                     nm_utils_str_utf8safe_escape_cp (priv->path,
		                                                      NM_UTILS_STR_UTF8_SAFE_FLAG_NONE));
		break;
	case PROP_IFACE:
		g_value_take_string (value,
		                     nm_utils_str_utf8safe_escape_cp (priv->iface,
		                                                      NM_UTILS_STR_UTF8_SAFE_FLAG_ESCAPE_CTRL));
		break;
	case PROP_IP_IFACE:
		if (ip_config_valid (priv->state)) {
			g_value_take_string (value,
			                     nm_utils_str_utf8safe_escape_cp (nm_device_get_ip_iface (self),
			                                                      NM_UTILS_STR_UTF8_SAFE_FLAG_ESCAPE_CTRL));
		} else
			g_value_set_string (value, NULL);
		break;
	case PROP_IFINDEX:
		g_value_set_int (value, priv->ifindex);
		break;
	case PROP_DRIVER:
		g_value_take_string (value,
		                     nm_utils_str_utf8safe_escape_cp (priv->driver,
		                                                      NM_UTILS_STR_UTF8_SAFE_FLAG_ESCAPE_CTRL));
		break;
	case PROP_DRIVER_VERSION:
		g_value_take_string (value,
		                     nm_utils_str_utf8safe_escape_cp (priv->driver_version,
		                                                      NM_UTILS_STR_UTF8_SAFE_FLAG_ESCAPE_CTRL));
		break;
	case PROP_FIRMWARE_VERSION:
		g_value_take_string (value,
		                     nm_utils_str_utf8safe_escape_cp (priv->firmware_version,
		                                                      NM_UTILS_STR_UTF8_SAFE_FLAG_ESCAPE_CTRL));
		break;
	case PROP_CAPABILITIES:
		g_value_set_uint (value, (priv->capabilities & ~NM_DEVICE_CAP_INTERNAL_MASK));
		break;
	case PROP_IP4_ADDRESS:
		g_value_set_uint (value, priv->ip4_address);
		break;
	case PROP_CARRIER:
		g_value_set_boolean (value, priv->carrier);
		break;
	case PROP_MTU:
		g_value_set_uint (value, priv->mtu);
		break;
	case PROP_IP4_CONFIG:
		nm_dbus_utils_g_value_set_object_path (value, ip_config_valid (priv->state) ? priv->ip_config_4 : NULL);
		break;
	case PROP_DHCP4_CONFIG:
		nm_dbus_utils_g_value_set_object_path (value, ip_config_valid (priv->state) ? priv->dhcp_data_4.config : NULL);
		break;
	case PROP_IP6_CONFIG:
		nm_dbus_utils_g_value_set_object_path (value, ip_config_valid (priv->state) ? priv->ip_config_6 : NULL);
		break;
	case PROP_DHCP6_CONFIG:
		nm_dbus_utils_g_value_set_object_path (value, ip_config_valid (priv->state) ? priv->dhcp_data_6.config : NULL);
		break;
	case PROP_STATE:
		g_value_set_uint (value, priv->state);
		break;
	case PROP_STATE_REASON:
		g_value_take_variant (value,
		                      g_variant_new ("(uu)", priv->state, priv->state_reason));
		break;
	case PROP_ACTIVE_CONNECTION:
		g_value_set_string (value, nm_dbus_track_obj_path_get (&priv->act_request));
		break;
	case PROP_DEVICE_TYPE:
		g_value_set_uint (value, priv->type);
		break;
	case PROP_LINK_TYPE:
		g_value_set_uint (value, priv->link_type);
		break;
	case PROP_MANAGED:
		/* The managed state exposed on D-Bus only depends on the current device state alone. */
		g_value_set_boolean (value, nm_device_get_state (self) > NM_DEVICE_STATE_UNMANAGED);
		break;
	case PROP_AUTOCONNECT:
		g_value_set_boolean (value,
		                     nm_device_autoconnect_blocked_get (self, NM_DEVICE_AUTOCONNECT_BLOCKED_ALL)
		                       ? FALSE
		                       : TRUE);
		break;
	case PROP_FIRMWARE_MISSING:
		g_value_set_boolean (value, priv->firmware_missing);
		break;
	case PROP_NM_PLUGIN_MISSING:
		g_value_set_boolean (value, priv->nm_plugin_missing);
		break;
	case PROP_TYPE_DESC:
		g_value_set_string (value, priv->type_desc);
		break;
	case PROP_RFKILL_TYPE:
		g_value_set_uint (value, priv->rfkill_type);
		break;
	case PROP_AVAILABLE_CONNECTIONS:
		nm_dbus_utils_g_value_set_object_path_from_hash (value,
		                                                 priv->available_connections,
		                                                 TRUE);
		break;
	case PROP_PHYSICAL_PORT_ID:
		g_value_set_string (value, priv->physical_port_id);
		break;
	case PROP_MASTER:
		g_value_set_object (value, nm_device_get_master (self));
		break;
	case PROP_PARENT:
		g_value_set_string (value, nm_dbus_track_obj_path_get (&priv->parent_device));
		break;
	case PROP_HW_ADDRESS:
		g_value_set_string (value, priv->hw_addr);
		break;
	case PROP_PERM_HW_ADDRESS: {
		const char *perm_hw_addr;
		gboolean perm_hw_addr_is_fake;

		perm_hw_addr = nm_device_get_permanent_hw_address_full (self, FALSE, &perm_hw_addr_is_fake);
		/* this property is exposed on D-Bus for NMDeviceEthernet and NMDeviceWifi. */
		g_value_set_string (value, perm_hw_addr && !perm_hw_addr_is_fake ? perm_hw_addr : NULL);
		break;
	}
	case PROP_HAS_PENDING_ACTION:
		g_value_set_boolean (value, nm_device_has_pending_action (self));
		break;
	case PROP_METERED:
		g_value_set_uint (value, priv->metered);
		break;
	case PROP_LLDP_NEIGHBORS:
		if (priv->lldp_listener)
			g_value_set_variant (value, nm_lldp_listener_get_neighbors (priv->lldp_listener));
		else {
			g_variant_builder_init (&array_builder, G_VARIANT_TYPE ("aa{sv}"));
			g_value_take_variant (value, g_variant_builder_end (&array_builder));
		}
		break;
	case PROP_REAL:
		g_value_set_boolean (value, nm_device_is_real (self));
		break;
	case PROP_SLAVES: {
		CList *slave_iter;
		char **slave_list;
		gsize i, n;

		n = c_list_length (&priv->slaves);
		slave_list = g_new (char *, n + 1);
		i = 0;
		c_list_for_each (slave_iter, &priv->slaves) {
			SlaveInfo *info = c_list_entry (slave_iter, SlaveInfo, lst_slave);
			const char *path;

			if (!NM_DEVICE_GET_PRIVATE (info->slave)->is_enslaved)
				continue;
			path = nm_dbus_object_get_path (NM_DBUS_OBJECT (info->slave));
			if (path)
				slave_list[i++] = g_strdup (path);
		}
		nm_assert (i <= n);
		slave_list[i] = NULL;
		g_value_take_boxed (value, slave_list);
		break;
	}
	case PROP_STATISTICS_REFRESH_RATE_MS:
		g_value_set_uint (value, priv->stats.refresh_rate_ms);
		break;
	case PROP_STATISTICS_TX_BYTES:
		g_value_set_uint64 (value, priv->stats.tx_bytes);
		break;
	case PROP_STATISTICS_RX_BYTES:
		g_value_set_uint64 (value, priv->stats.rx_bytes);
		break;
	case PROP_IP4_CONNECTIVITY:
		g_value_set_uint (value, priv->concheck_x[1].state);
		break;
	case PROP_IP6_CONNECTIVITY:
		g_value_set_uint (value, priv->concheck_x[0].state);
		break;
	case PROP_INTERFACE_FLAGS:
		g_value_set_uint (value, priv->interface_flags);
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		break;
	}
}

static void
set_property (GObject *object, guint prop_id,
              const GValue *value, GParamSpec *pspec)
{
	NMDevice *self = (NMDevice *) object;
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	switch (prop_id) {
	case PROP_UDI:
		/* construct-only */
		priv->udi = g_value_dup_string (value);
		break;
	case PROP_IFACE:
		/* construct-only */
		priv->iface_ = g_value_dup_string (value);
		break;
	case PROP_DRIVER:
		/* construct-only */
		priv->driver = g_value_dup_string (value);
		break;
	case PROP_MANAGED:
		/* via D-Bus */
		if (nm_device_is_real (self)) {
			gboolean managed;
			NMDeviceStateReason reason;

			managed = g_value_get_boolean (value);
			if (managed) {
				reason = NM_DEVICE_STATE_REASON_CONNECTION_ASSUMED;
				if (NM_IN_SET_TYPED (NMDeviceSysIfaceState,
				                     priv->sys_iface_state,
				                     NM_DEVICE_SYS_IFACE_STATE_EXTERNAL,
				                     NM_DEVICE_SYS_IFACE_STATE_REMOVED))
					nm_device_sys_iface_state_set (self, NM_DEVICE_SYS_IFACE_STATE_ASSUME);
			} else {
				reason = NM_DEVICE_STATE_REASON_REMOVED;
				nm_device_sys_iface_state_set (self, NM_DEVICE_SYS_IFACE_STATE_REMOVED);
			}
			nm_device_set_unmanaged_by_flags (self,
			                                  NM_UNMANAGED_USER_EXPLICIT,
			                                  !managed,
			                                  reason);
		}
		break;
	case PROP_AUTOCONNECT:
		/* via D-Bus */
		if (g_value_get_boolean (value))
			nm_device_autoconnect_blocked_unset (self, NM_DEVICE_AUTOCONNECT_BLOCKED_ALL);
		else
			nm_device_autoconnect_blocked_set (self, NM_DEVICE_AUTOCONNECT_BLOCKED_USER);
		break;
	case PROP_NM_PLUGIN_MISSING:
		/* construct-only */
		priv->nm_plugin_missing = g_value_get_boolean (value);
		break;
	case PROP_DEVICE_TYPE:
		/* construct-only */
		nm_assert (priv->type == NM_DEVICE_TYPE_UNKNOWN);
		priv->type = g_value_get_uint (value);
		nm_assert (priv->type > NM_DEVICE_TYPE_UNKNOWN);
		nm_assert (priv->type <= NM_DEVICE_TYPE_VRF);
		break;
	case PROP_LINK_TYPE:
		/* construct-only */
		nm_assert (priv->link_type == NM_LINK_TYPE_NONE);
		priv->link_type = g_value_get_uint (value);
		break;
	case PROP_TYPE_DESC:
		/* construct-only */
		priv->type_desc = g_value_dup_string (value);
		break;
	case PROP_RFKILL_TYPE:
		/* construct-only */
		priv->rfkill_type = g_value_get_uint (value);
		break;
	case PROP_PERM_HW_ADDRESS:
		/* construct-only */
		priv->hw_addr_perm = g_value_dup_string (value);
		break;
	case PROP_STATISTICS_REFRESH_RATE_MS:
		/* via D-Bus */
		_stats_set_refresh_rate (self, g_value_get_uint (value));
		break;
	default:
		G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
		break;
	}
}

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

static void
nm_device_init (NMDevice *self)
{
	NMDevicePrivate *priv;

	priv = G_TYPE_INSTANCE_GET_PRIVATE (self, NM_TYPE_DEVICE, NMDevicePrivate);

	self->_priv = priv;

	c_list_init (&priv->concheck_lst_head);
	c_list_init (&self->devices_lst);
	c_list_init (&priv->slaves);

	priv->concheck_x[0].state = NM_CONNECTIVITY_UNKNOWN;
	priv->concheck_x[1].state = NM_CONNECTIVITY_UNKNOWN;

	nm_dbus_track_obj_path_init (&priv->parent_device, G_OBJECT (self), obj_properties[PROP_PARENT]);
	nm_dbus_track_obj_path_init (&priv->act_request, G_OBJECT (self), obj_properties[PROP_ACTIVE_CONNECTION]);

	priv->netns = g_object_ref (NM_NETNS_GET);

	priv->autoconnect_blocked_flags = DEFAULT_AUTOCONNECT
	                                  ? NM_DEVICE_AUTOCONNECT_BLOCKED_NONE
	                                  : NM_DEVICE_AUTOCONNECT_BLOCKED_USER;

	priv->auth_retries = NM_DEVICE_AUTH_RETRIES_UNSET;
	priv->type = NM_DEVICE_TYPE_UNKNOWN;
	priv->capabilities = NM_DEVICE_CAP_NM_SUPPORTED;
	priv->state = NM_DEVICE_STATE_UNMANAGED;
	priv->state_reason = NM_DEVICE_STATE_REASON_NONE;
	priv->rfkill_type = RFKILL_TYPE_UNKNOWN;
	priv->unmanaged_flags = NM_UNMANAGED_PLATFORM_INIT;
	priv->unmanaged_mask = priv->unmanaged_flags;
	priv->available_connections = g_hash_table_new_full (nm_direct_hash, NULL, g_object_unref, NULL);
	priv->ip6_saved_properties = g_hash_table_new_full (nm_str_hash, g_str_equal, NULL, g_free);
	priv->sys_iface_state = NM_DEVICE_SYS_IFACE_STATE_EXTERNAL;

	priv->v4_commit_first_time = TRUE;
	priv->v6_commit_first_time = TRUE;
}

static GObject*
constructor (GType type,
             guint n_construct_params,
             GObjectConstructParam *construct_params)
{
	GObject *object;
	GObjectClass *klass;
	NMDevice *self;
	NMDevicePrivate *priv;
	const NMPlatformLink *pllink;

	klass = G_OBJECT_CLASS (nm_device_parent_class);
	object = klass->constructor (type, n_construct_params, construct_params);
	if (!object)
		return NULL;

	self = NM_DEVICE (object);
	priv = NM_DEVICE_GET_PRIVATE (self);

	if (   priv->iface
	    && G_LIKELY (!nm_utils_get_testing ())) {
		pllink = nm_platform_link_get_by_ifname (nm_device_get_platform (self), priv->iface);

		if (pllink && link_type_compatible (self, pllink->type, NULL, NULL)) {
			_set_ifindex (self, pllink->ifindex, FALSE);
			priv->up = NM_FLAGS_HAS (pllink->n_ifi_flags, IFF_UP);
		}
	}

	if (priv->hw_addr_perm) {
		guint8 buf[NM_UTILS_HWADDR_LEN_MAX];
		gsize l;

		if (!_nm_utils_hwaddr_aton (priv->hw_addr_perm, buf, sizeof (buf), &l)) {
			nm_clear_g_free (&priv->hw_addr_perm);
			g_return_val_if_reached (object);
		}

		priv->hw_addr_len_ = l;
		priv->hw_addr = nm_utils_hwaddr_ntoa (buf, l);
		_LOGT (LOGD_DEVICE, "hw-addr: has permanent hw-address '%s'", priv->hw_addr_perm);
	}

	return object;
}

static void
constructed (GObject *object)
{
	NMDevice *self = NM_DEVICE (object);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMPlatform *platform;

	if (NM_DEVICE_GET_CLASS (self)->get_generic_capabilities)
		priv->capabilities |= NM_DEVICE_GET_CLASS (self)->get_generic_capabilities (self);

	/* Watch for external IP config changes */
	platform = nm_device_get_platform (self);
	g_signal_connect (platform, NM_PLATFORM_SIGNAL_IP4_ADDRESS_CHANGED, G_CALLBACK (device_ipx_changed), self);
	g_signal_connect (platform, NM_PLATFORM_SIGNAL_IP6_ADDRESS_CHANGED, G_CALLBACK (device_ipx_changed), self);
	g_signal_connect (platform, NM_PLATFORM_SIGNAL_IP4_ROUTE_CHANGED, G_CALLBACK (device_ipx_changed), self);
	g_signal_connect (platform, NM_PLATFORM_SIGNAL_IP6_ROUTE_CHANGED, G_CALLBACK (device_ipx_changed), self);
	g_signal_connect (platform, NM_PLATFORM_SIGNAL_LINK_CHANGED, G_CALLBACK (link_changed_cb), self);

	priv->manager = g_object_ref (NM_MANAGER_GET);
	priv->settings = g_object_ref (NM_SETTINGS_GET);

	g_signal_connect (priv->settings,
	                  NM_SETTINGS_SIGNAL_CONNECTION_ADDED,
	                  G_CALLBACK (cp_connection_added),
	                  self);
	g_signal_connect (priv->settings,
	                  NM_SETTINGS_SIGNAL_CONNECTION_UPDATED,
	                  G_CALLBACK (cp_connection_updated),
	                  self);
	g_signal_connect (priv->settings,
	                  NM_SETTINGS_SIGNAL_CONNECTION_REMOVED,
	                  G_CALLBACK (cp_connection_removed),
	                  self);

	G_OBJECT_CLASS (nm_device_parent_class)->constructed (object);

	_LOGD (LOGD_DEVICE, "constructed (%s)", G_OBJECT_TYPE_NAME (self));
}

static void
dispose (GObject *object)
{
	NMDevice *self = NM_DEVICE (object);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);
	NMPlatform *platform;
	NMDeviceConnectivityHandle *con_handle;
	gs_free_error GError *cancelled_error = NULL;

	_LOGD (LOGD_DEVICE, "disposing");

	nm_assert (c_list_is_empty (&self->devices_lst));

	while ((con_handle = c_list_first_entry (&priv->concheck_lst_head, NMDeviceConnectivityHandle, concheck_lst))) {
		if (!cancelled_error)
			nm_utils_error_set_cancelled (&cancelled_error, FALSE, "NMDevice");
		concheck_handle_complete (con_handle, cancelled_error);
	}

	nm_clear_g_cancellable (&priv->deactivating_cancellable);

	nm_device_assume_state_reset (self);

	_parent_set_ifindex (self, 0, FALSE);

	platform = nm_device_get_platform (self);
	g_signal_handlers_disconnect_by_func (platform, G_CALLBACK (device_ipx_changed), self);
	g_signal_handlers_disconnect_by_func (platform, G_CALLBACK (link_changed_cb), self);

	arp_cleanup (self);

	nm_clear_g_signal_handler (nm_config_get (), &priv->config_changed_id);

	dispatcher_cleanup (self);

	nm_pacrunner_manager_remove_clear (&priv->pacrunner_conf_id);

	_cleanup_generic_pre (self, CLEANUP_TYPE_KEEP);

	nm_assert (c_list_is_empty (&priv->slaves));

	/* Let the kernel manage IPv6LL again */
	set_nm_ipv6ll (self, FALSE);

	_cleanup_generic_post (self, CLEANUP_TYPE_KEEP);

	nm_assert (priv->master_ready_id == 0);

	g_hash_table_remove_all (priv->ip6_saved_properties);

	nm_clear_g_source (&priv->recheck_assume_id);
	nm_clear_g_source (&priv->recheck_available.call_id);

	nm_clear_g_source (&priv->check_delete_unrealized_id);

	nm_clear_g_source (&priv->stats.timeout_id);

	carrier_disconnected_action_cancel (self);

	_set_ifindex (self, 0, FALSE);
	_set_ifindex (self, 0, TRUE);

	if (priv->settings) {
		g_signal_handlers_disconnect_by_func (priv->settings, cp_connection_added, self);
		g_signal_handlers_disconnect_by_func (priv->settings, cp_connection_updated, self);
		g_signal_handlers_disconnect_by_func (priv->settings, cp_connection_removed, self);
	}

	available_connections_del_all (self);

	if (nm_clear_g_source (&priv->carrier_wait_id))
		nm_device_remove_pending_action (self, NM_PENDING_ACTION_CARRIER_WAIT, FALSE);

	_clear_queued_act_request (priv,
	                           NM_ACTIVE_CONNECTION_STATE_REASON_DEVICE_DISCONNECTED);

	nm_clear_g_source (&priv->device_link_changed_id);
	nm_clear_g_source (&priv->device_ip_link_changed_id);

	if (priv->lldp_listener) {
		g_signal_handlers_disconnect_by_func (priv->lldp_listener,
		                                      G_CALLBACK (lldp_neighbors_changed),
		                                      self);
		nm_lldp_listener_stop (priv->lldp_listener);
		g_clear_object (&priv->lldp_listener);
	}

	nm_clear_g_source (&priv->concheck_x[0].p_cur_id);
	nm_clear_g_source (&priv->concheck_x[1].p_cur_id);

	nm_assert (!priv->sriov.pending);
	if (priv->sriov.next) {
		nm_g_slice_free (priv->sriov.next);
		priv->sriov.next = NULL;
	}

	G_OBJECT_CLASS (nm_device_parent_class)->dispose (object);

	if (nm_clear_g_source (&priv->queued_state.id)) {
		/* FIXME: we'd expect the queud_state to be already cleared and this statement
		 * not being necessary. Add this check here to hopefully investigate crash
		 * rh#1270247. */
		g_return_if_reached ();
	}
}

static void
finalize (GObject *object)
{
	NMDevice *self = NM_DEVICE (object);
	NMDevicePrivate *priv = NM_DEVICE_GET_PRIVATE (self);

	_LOGD (LOGD_DEVICE, "finalize(): %s", G_OBJECT_TYPE_NAME (self));

	g_free (priv->hw_addr);
	g_free (priv->hw_addr_perm);
	g_free (priv->hw_addr_initial);
	g_slist_free (priv->pending_actions);
	g_slist_free_full (priv->dad6_failed_addrs, (GDestroyNotify) nmp_object_unref);
	nm_clear_g_free (&priv->physical_port_id);
	g_free (priv->udi);
	g_free (priv->path);
	g_free (priv->iface_);
	g_free (priv->ip_iface_);
	g_free (priv->driver);
	g_free (priv->driver_version);
	g_free (priv->firmware_version);
	g_free (priv->type_desc);
	g_free (priv->dhcp_anycast_address);
	g_free (priv->current_stable_id);

	g_hash_table_unref (priv->ip6_saved_properties);
	g_hash_table_unref (priv->available_connections);

	nm_dbus_track_obj_path_deinit (&priv->parent_device);
	nm_dbus_track_obj_path_deinit (&priv->act_request);

	G_OBJECT_CLASS (nm_device_parent_class)->finalize (object);

	/* for testing, NMDeviceTest does not invoke NMDevice::constructed,
	 * and thus @settings might be unset. */
	nm_g_object_unref (priv->settings);
	nm_g_object_unref (priv->manager);

	nm_g_object_unref (priv->concheck_mgr);

	g_object_unref (priv->netns);
}

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

static const GDBusSignalInfo signal_info_state_changed = NM_DEFINE_GDBUS_SIGNAL_INFO_INIT (
	"StateChanged",
	.args = NM_DEFINE_GDBUS_ARG_INFOS (
		NM_DEFINE_GDBUS_ARG_INFO ("new_state", "u"),
		NM_DEFINE_GDBUS_ARG_INFO ("old_state", "u"),
		NM_DEFINE_GDBUS_ARG_INFO ("reason",    "u"),
	),
);

static const NMDBusInterfaceInfoExtended interface_info_device = {
	.parent = NM_DEFINE_GDBUS_INTERFACE_INFO_INIT (
		NM_DBUS_INTERFACE_DEVICE,
		.methods = NM_DEFINE_GDBUS_METHOD_INFOS (
			NM_DEFINE_DBUS_METHOD_INFO_EXTENDED (
				NM_DEFINE_GDBUS_METHOD_INFO_INIT (
					"Reapply",
					.in_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("connection", "a{sa{sv}}"),
						NM_DEFINE_GDBUS_ARG_INFO ("version_id", "t"),
						NM_DEFINE_GDBUS_ARG_INFO ("flags",      "u"),
					),
				),
				.handle = impl_device_reapply,
			),
			NM_DEFINE_DBUS_METHOD_INFO_EXTENDED (
				NM_DEFINE_GDBUS_METHOD_INFO_INIT (
					"GetAppliedConnection",
					.in_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("flags", "u"),
					),
					.out_args = NM_DEFINE_GDBUS_ARG_INFOS (
						NM_DEFINE_GDBUS_ARG_INFO ("connection", "a{sa{sv}}"),
						NM_DEFINE_GDBUS_ARG_INFO ("version_id", "t"),
					),
				),
				.handle = impl_device_get_applied_connection,
			),
			NM_DEFINE_DBUS_METHOD_INFO_EXTENDED (
				NM_DEFINE_GDBUS_METHOD_INFO_INIT (
					"Disconnect",
				),
				.handle = impl_device_disconnect,
			),
			NM_DEFINE_DBUS_METHOD_INFO_EXTENDED (
				NM_DEFINE_GDBUS_METHOD_INFO_INIT (
					"Delete",
				),
				.handle = impl_device_delete,
			),
		),
		.signals = NM_DEFINE_GDBUS_SIGNAL_INFOS (
			&signal_info_state_changed,
		),
		.properties = NM_DEFINE_GDBUS_PROPERTY_INFOS (
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("Udi",                  "s",      NM_DEVICE_UDI),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("Path",                 "s",      NM_DEVICE_PATH),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("Interface",            "s",      NM_DEVICE_IFACE),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("IpInterface",          "s",      NM_DEVICE_IP_IFACE),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("Driver",               "s",      NM_DEVICE_DRIVER),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("DriverVersion",        "s",      NM_DEVICE_DRIVER_VERSION),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("FirmwareVersion",      "s",      NM_DEVICE_FIRMWARE_VERSION),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("Capabilities",         "u",      NM_DEVICE_CAPABILITIES),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("Ip4Address",           "u",      NM_DEVICE_IP4_ADDRESS),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("State",                "u",      NM_DEVICE_STATE),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("StateReason",          "(uu)",   NM_DEVICE_STATE_REASON),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("ActiveConnection",     "o",      NM_DEVICE_ACTIVE_CONNECTION),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("Ip4Config",            "o",      NM_DEVICE_IP4_CONFIG),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("Dhcp4Config",          "o",      NM_DEVICE_DHCP4_CONFIG),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("Ip6Config",            "o",      NM_DEVICE_IP6_CONFIG),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("Dhcp6Config",          "o",      NM_DEVICE_DHCP6_CONFIG),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READWRITABLE_L ("Managed",              "b",      NM_DEVICE_MANAGED,               NM_AUTH_PERMISSION_NETWORK_CONTROL, NM_AUDIT_OP_DEVICE_MANAGED),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READWRITABLE_L ("Autoconnect",          "b",      NM_DEVICE_AUTOCONNECT,           NM_AUTH_PERMISSION_NETWORK_CONTROL, NM_AUDIT_OP_DEVICE_AUTOCONNECT),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("FirmwareMissing",      "b",      NM_DEVICE_FIRMWARE_MISSING),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("NmPluginMissing",      "b",      NM_DEVICE_NM_PLUGIN_MISSING),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("DeviceType",           "u",      NM_DEVICE_DEVICE_TYPE),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("AvailableConnections", "ao",     NM_DEVICE_AVAILABLE_CONNECTIONS),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("PhysicalPortId",       "s",      NM_DEVICE_PHYSICAL_PORT_ID),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("Mtu",                  "u",      NM_DEVICE_MTU),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("Metered",              "u",      NM_DEVICE_METERED),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("LldpNeighbors",        "aa{sv}", NM_DEVICE_LLDP_NEIGHBORS),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE_L     ("Real",                 "b",      NM_DEVICE_REAL),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE       ("Ip4Connectivity",      "u",      NM_DEVICE_IP4_CONNECTIVITY),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE       ("Ip6Connectivity",      "u",      NM_DEVICE_IP6_CONNECTIVITY),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE       ("InterfaceFlags",       "u",      NM_DEVICE_INTERFACE_FLAGS),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE       ("HwAddress",            "s",      NM_DEVICE_HW_ADDRESS),
		),
	),
};

const NMDBusInterfaceInfoExtended nm_interface_info_device_statistics = {
	.parent = NM_DEFINE_GDBUS_INTERFACE_INFO_INIT (
		NM_DBUS_INTERFACE_DEVICE_STATISTICS,
		.signals = NM_DEFINE_GDBUS_SIGNAL_INFOS (
			&nm_signal_info_property_changed_legacy,
		),
		.properties = NM_DEFINE_GDBUS_PROPERTY_INFOS (
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READWRITABLE ("RefreshRateMs", "u", NM_DEVICE_STATISTICS_REFRESH_RATE_MS, NM_AUTH_PERMISSION_ENABLE_DISABLE_STATISTICS, NM_AUDIT_OP_STATISTICS),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE     ("TxBytes",       "t", NM_DEVICE_STATISTICS_TX_BYTES),
			NM_DEFINE_DBUS_PROPERTY_INFO_EXTENDED_READABLE     ("RxBytes",       "t", NM_DEVICE_STATISTICS_RX_BYTES),
		),
	),
};

static void
nm_device_class_init (NMDeviceClass *klass)
{
	GObjectClass *object_class = G_OBJECT_CLASS (klass);
	NMDBusObjectClass *dbus_object_class = NM_DBUS_OBJECT_CLASS (klass);

	g_type_class_add_private (object_class, sizeof (NMDevicePrivate));

	dbus_object_class->export_path = NM_DBUS_EXPORT_PATH_NUMBERED (NM_DBUS_PATH"/Devices");
	dbus_object_class->interface_infos = NM_DBUS_INTERFACE_INFOS (&interface_info_device,
	                                                              &nm_interface_info_device_statistics);

	object_class->dispose = dispose;
	object_class->finalize = finalize;
	object_class->set_property = set_property;
	object_class->get_property = get_property;
	object_class->constructor = constructor;
	object_class->constructed = constructed;

	klass->link_changed = link_changed;

	klass->is_available = is_available;
	klass->act_stage2_config = act_stage2_config;
	klass->act_stage3_ip_config_start = act_stage3_ip_config_start;
	klass->act_stage4_ip_config_timeout = act_stage4_ip_config_timeout;

	klass->get_type_description = get_type_description;
	klass->can_auto_connect = can_auto_connect;
	klass->can_update_from_platform_link = can_update_from_platform_link;
	klass->check_connection_compatible = check_connection_compatible;
	klass->check_connection_available = check_connection_available;
	klass->can_unmanaged_external_down = can_unmanaged_external_down;
	klass->realize_start_notify = realize_start_notify;
	klass->unrealize_notify = unrealize_notify;
	klass->carrier_changed_notify = carrier_changed_notify;
	klass->get_ip_iface_identifier = get_ip_iface_identifier;
	klass->unmanaged_on_quit = unmanaged_on_quit;
	klass->deactivate_reset_hw_addr = deactivate_reset_hw_addr;
	klass->parent_changed_notify = parent_changed_notify;
	klass->can_reapply_change = can_reapply_change;
	klass->reapply_connection = reapply_connection;
	klass->set_platform_mtu = set_platform_mtu;

	obj_properties[PROP_UDI] =
	    g_param_spec_string (NM_DEVICE_UDI, "", "",
	                         NULL,
	                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_PATH] =
	    g_param_spec_string (NM_DEVICE_PATH, "", "",
	                         NULL,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_IFACE] =
	    g_param_spec_string (NM_DEVICE_IFACE, "", "",
	                         NULL,
	                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_IP_IFACE] =
	    g_param_spec_string (NM_DEVICE_IP_IFACE, "", "",
	                         NULL,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_DRIVER] =
	    g_param_spec_string (NM_DEVICE_DRIVER, "", "",
	                         NULL,
	                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_DRIVER_VERSION] =
	    g_param_spec_string (NM_DEVICE_DRIVER_VERSION, "", "",
	                         NULL,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_FIRMWARE_VERSION] =
	    g_param_spec_string (NM_DEVICE_FIRMWARE_VERSION, "", "",
	                         NULL,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_CAPABILITIES] =
	    g_param_spec_uint (NM_DEVICE_CAPABILITIES, "", "",
	                       0, G_MAXUINT32, NM_DEVICE_CAP_NONE,
	                       G_PARAM_READABLE |
	                       G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_CARRIER] =
	    g_param_spec_boolean (NM_DEVICE_CARRIER, "", "",
	                          FALSE,
	                          G_PARAM_READABLE |
	                          G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_MTU] =
	    g_param_spec_uint (NM_DEVICE_MTU, "", "",
	                       0, G_MAXUINT32, 1500,
	                       G_PARAM_READABLE |
	                       G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_IP4_ADDRESS] =
	    g_param_spec_uint (NM_DEVICE_IP4_ADDRESS, "", "",
	                       0, G_MAXUINT32, 0, /* FIXME */
	                       G_PARAM_READABLE |
	                       G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_IP4_CONFIG] =
	    g_param_spec_string (NM_DEVICE_IP4_CONFIG, "", "",
	                         NULL,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_DHCP4_CONFIG] =
	    g_param_spec_string (NM_DEVICE_DHCP4_CONFIG, "", "",
	                         NULL,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_IP6_CONFIG] =
	    g_param_spec_string (NM_DEVICE_IP6_CONFIG, "", "",
	                         NULL,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_DHCP6_CONFIG] =
	    g_param_spec_string (NM_DEVICE_DHCP6_CONFIG, "", "",
	                         NULL,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_STATE] =
	    g_param_spec_uint (NM_DEVICE_STATE, "", "",
	                       0, G_MAXUINT32, NM_DEVICE_STATE_UNKNOWN,
	                       G_PARAM_READABLE |
	                       G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_STATE_REASON] =
	    g_param_spec_variant (NM_DEVICE_STATE_REASON, "", "",
	                          G_VARIANT_TYPE ("(uu)"),
	                          NULL,
	                          G_PARAM_READABLE |
	                          G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_ACTIVE_CONNECTION] =
	    g_param_spec_string (NM_DEVICE_ACTIVE_CONNECTION, "", "",
	                         NULL,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_DEVICE_TYPE] =
	    g_param_spec_uint (NM_DEVICE_DEVICE_TYPE, "", "",
	                       0, G_MAXUINT32, NM_DEVICE_TYPE_UNKNOWN,
	                       G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
	                       G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_LINK_TYPE] =
	    g_param_spec_uint (NM_DEVICE_LINK_TYPE, "", "",
	                       0, G_MAXUINT32, NM_LINK_TYPE_NONE,
	                       G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
	                       G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_MANAGED] =
	    g_param_spec_boolean (NM_DEVICE_MANAGED, "", "",
	                          FALSE,
	                          G_PARAM_READWRITE | /* via D-Bus */
	                          G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_AUTOCONNECT] =
	    g_param_spec_boolean (NM_DEVICE_AUTOCONNECT, "", "",
	                          DEFAULT_AUTOCONNECT,
	                          G_PARAM_READWRITE | /* via D-Bus */
	                          G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_FIRMWARE_MISSING] =
	    g_param_spec_boolean (NM_DEVICE_FIRMWARE_MISSING, "", "",
	                          FALSE,
	                          G_PARAM_READABLE |
	                          G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_NM_PLUGIN_MISSING] =
	    g_param_spec_boolean (NM_DEVICE_NM_PLUGIN_MISSING, "", "",
	                          FALSE,
	                          G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
	                          G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_TYPE_DESC] =
	    g_param_spec_string (NM_DEVICE_TYPE_DESC, "", "",
	                         NULL,
	                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_RFKILL_TYPE] =
	    g_param_spec_uint (NM_DEVICE_RFKILL_TYPE, "", "",
	                       RFKILL_TYPE_WLAN,
	                       RFKILL_TYPE_MAX,
	                       RFKILL_TYPE_UNKNOWN,
	                       G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
	                       G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_IFINDEX] =
	    g_param_spec_int (NM_DEVICE_IFINDEX, "", "",
	                      0, G_MAXINT, 0,
	                      G_PARAM_READABLE |
	                      G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_AVAILABLE_CONNECTIONS] =
	    g_param_spec_boxed (NM_DEVICE_AVAILABLE_CONNECTIONS, "", "",
	                        G_TYPE_STRV,
	                        G_PARAM_READABLE |
	                        G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_PHYSICAL_PORT_ID] =
	    g_param_spec_string (NM_DEVICE_PHYSICAL_PORT_ID, "", "",
	                         NULL,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_MASTER] =
	    g_param_spec_object (NM_DEVICE_MASTER, "", "",
	                         NM_TYPE_DEVICE,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_PARENT] =
	    g_param_spec_string (NM_DEVICE_PARENT, "", "",
	                         NULL,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_HW_ADDRESS] =
	    g_param_spec_string (NM_DEVICE_HW_ADDRESS, "", "",
	                         NULL,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_PERM_HW_ADDRESS] =
	    g_param_spec_string (NM_DEVICE_PERM_HW_ADDRESS, "", "",
	                         NULL,
	                         G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_HAS_PENDING_ACTION] =
	    g_param_spec_boolean (NM_DEVICE_HAS_PENDING_ACTION, "", "",
	                          FALSE,
	                          G_PARAM_READABLE |
	                          G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_METERED] =
	    g_param_spec_uint (NM_DEVICE_METERED, "", "",
	                       0, G_MAXUINT32, NM_METERED_UNKNOWN,
	                       G_PARAM_READABLE |
	                       G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_LLDP_NEIGHBORS] =
	    g_param_spec_variant (NM_DEVICE_LLDP_NEIGHBORS, "", "",
	                          G_VARIANT_TYPE ("aa{sv}"),
	                          NULL,
	                          G_PARAM_READABLE |
	                          G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_REAL] =
	    g_param_spec_boolean (NM_DEVICE_REAL, "", "",
	                          FALSE,
	                          G_PARAM_READABLE |
	                          G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_SLAVES] =
	    g_param_spec_boxed (NM_DEVICE_SLAVES, "", "",
	                        G_TYPE_STRV,
	                        G_PARAM_READABLE |
	                        G_PARAM_STATIC_STRINGS);

	obj_properties[PROP_STATISTICS_REFRESH_RATE_MS] =
	    g_param_spec_uint (NM_DEVICE_STATISTICS_REFRESH_RATE_MS, "", "",
	                       0, UINT32_MAX, 0,
	                       G_PARAM_READWRITE | /* via D-Bus */
	                       G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_STATISTICS_TX_BYTES] =
	    g_param_spec_uint64 (NM_DEVICE_STATISTICS_TX_BYTES, "", "",
	                         0, UINT64_MAX, 0,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_STATISTICS_RX_BYTES] =
	    g_param_spec_uint64 (NM_DEVICE_STATISTICS_RX_BYTES, "", "",
	                         0, UINT64_MAX, 0,
	                         G_PARAM_READABLE |
	                         G_PARAM_STATIC_STRINGS);

	obj_properties[PROP_IP4_CONNECTIVITY] =
	     g_param_spec_uint (NM_DEVICE_IP4_CONNECTIVITY, "", "",
	                        NM_CONNECTIVITY_UNKNOWN, NM_CONNECTIVITY_FULL, NM_CONNECTIVITY_UNKNOWN,
	                        G_PARAM_READABLE |
	                        G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_IP6_CONNECTIVITY] =
	     g_param_spec_uint (NM_DEVICE_IP6_CONNECTIVITY, "", "",
	                        NM_CONNECTIVITY_UNKNOWN, NM_CONNECTIVITY_FULL, NM_CONNECTIVITY_UNKNOWN,
	                        G_PARAM_READABLE |
	                        G_PARAM_STATIC_STRINGS);
	obj_properties[PROP_INTERFACE_FLAGS] =
	    g_param_spec_uint (NM_DEVICE_INTERFACE_FLAGS, "", "",
	                       0,
	                       G_MAXUINT32,
	                       0,
	                       G_PARAM_READABLE |
	                       G_PARAM_STATIC_STRINGS);

	g_object_class_install_properties (object_class, _PROPERTY_ENUMS_LAST, obj_properties);

	signals[STATE_CHANGED] =
	    g_signal_new (NM_DEVICE_STATE_CHANGED,
	                  G_OBJECT_CLASS_TYPE (object_class),
	                  G_SIGNAL_RUN_LAST,
	                  G_STRUCT_OFFSET (NMDeviceClass, state_changed),
	                  NULL, NULL, NULL,
	                  G_TYPE_NONE, 3,
	                  G_TYPE_UINT, G_TYPE_UINT, G_TYPE_UINT);

	signals[AUTOCONNECT_ALLOWED] =
	    g_signal_new (NM_DEVICE_AUTOCONNECT_ALLOWED,
	                  G_OBJECT_CLASS_TYPE (object_class),
	                  G_SIGNAL_RUN_LAST,
	                  0,
	                  autoconnect_allowed_accumulator, NULL, NULL,
	                  G_TYPE_BOOLEAN, 0);

	signals[IP4_CONFIG_CHANGED] =
	    g_signal_new (NM_DEVICE_IP4_CONFIG_CHANGED,
	                  G_OBJECT_CLASS_TYPE (object_class),
	                  G_SIGNAL_RUN_FIRST,
	                  0, NULL, NULL, NULL,
	                  G_TYPE_NONE, 2, G_TYPE_OBJECT, G_TYPE_OBJECT);

	signals[IP6_CONFIG_CHANGED] =
	    g_signal_new (NM_DEVICE_IP6_CONFIG_CHANGED,
	                  G_OBJECT_CLASS_TYPE (object_class),
	                  G_SIGNAL_RUN_FIRST,
	                  0, NULL, NULL, NULL,
	                  G_TYPE_NONE, 2, G_TYPE_OBJECT, G_TYPE_OBJECT);

	signals[IP6_PREFIX_DELEGATED] =
	    g_signal_new (NM_DEVICE_IP6_PREFIX_DELEGATED,
	                  G_OBJECT_CLASS_TYPE (object_class),
	                  G_SIGNAL_RUN_FIRST,
	                  0, NULL, NULL, NULL,
	                  G_TYPE_NONE, 1, G_TYPE_POINTER);

	signals[IP6_SUBNET_NEEDED] =
	    g_signal_new (NM_DEVICE_IP6_SUBNET_NEEDED,
	                  G_OBJECT_CLASS_TYPE (object_class),
	                  G_SIGNAL_RUN_FIRST,
	                  0, NULL, NULL, NULL,
	                  G_TYPE_NONE, 0);

	signals[REMOVED] =
	    g_signal_new (NM_DEVICE_REMOVED,
	                  G_OBJECT_CLASS_TYPE (object_class),
	                  G_SIGNAL_RUN_FIRST,
	                  0, NULL, NULL, NULL,
	                  G_TYPE_NONE, 0);

	signals[RECHECK_AUTO_ACTIVATE] =
	    g_signal_new (NM_DEVICE_RECHECK_AUTO_ACTIVATE,
	                  G_OBJECT_CLASS_TYPE (object_class),
	                  G_SIGNAL_RUN_FIRST,
	                  0, NULL, NULL, NULL,
	                  G_TYPE_NONE, 0);

	signals[RECHECK_ASSUME] =
	    g_signal_new (NM_DEVICE_RECHECK_ASSUME,
	                  G_OBJECT_CLASS_TYPE (object_class),
	                  G_SIGNAL_RUN_FIRST,
	                  0, NULL, NULL, NULL,
	                  G_TYPE_NONE, 0);
}

/* Connection defaults from plugins */
NM_CON_DEFAULT_NOP ("cdma.mtu");
NM_CON_DEFAULT_NOP ("gsm.mtu");
NM_CON_DEFAULT_NOP ("wifi.ap-isolation");
NM_CON_DEFAULT_NOP ("wifi.powersave");
NM_CON_DEFAULT_NOP ("wifi.wake-on-wlan");
NM_CON_DEFAULT_NOP ("wifi-sec.pmf");
NM_CON_DEFAULT_NOP ("wifi-sec.fils");