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
|
/*++
Copyright (c) Microsoft Corporation All Rights Reserved
Module Name:
common.cpp
Abstract:
Implementation of the AdapterCommon class.
--*/
#pragma warning (disable : 4127)
#include <initguid.h>
#include <sysvad.h>
#include "hw.h"
#include "savedata.h"
#include "IHVPrivatePropertySet.h"
#include "simple.h"
#ifdef SYSVAD_BTH_BYPASS
#include <limits.h>
#include <bthhfpddi.h>
#include <wdmguid.h> // guild-arrival/removal
#include <devpkey.h>
#include "bthhfpminipairs.h"
#include "BthhfpDevice.h"
#endif // SYSVAD_BTH_BYPASS
#ifdef SYSVAD_USB_SIDEBAND
#include <usbspec.h>
#include <usb.h>
#include <SidebandAudio.h>
#include <USBSidebandAudio.h>
#include "UsbHsMinipairs.h"
#include "UsbHsDevice.h"
#endif // SYSVAD_USB_SIDEBAND
//-----------------------------------------------------------------------------
// CSaveData statics
//-----------------------------------------------------------------------------
PSAVEWORKER_PARAM CSaveData::m_pWorkItems = NULL;
PDEVICE_OBJECT CSaveData::m_pDeviceObject = NULL;
//=============================================================================
// Classes
//=============================================================================
#ifdef SYSVAD_BTH_BYPASS
class BthHfpDevice; // Forward declaration.
#endif // SYSVAD_BTH_BYPASS
#ifdef SYSVAD_USB_SIDEBAND
class UsbHsDevice; // Forward declaration.
#endif // SYSVAD_USB_SIDEBAND
///////////////////////////////////////////////////////////////////////////////
// CAdapterCommon
//
class CAdapterCommon :
public IAdapterCommon,
public IAdapterPowerManagement,
public CUnknown
{
private:
PSERVICEGROUP m_pServiceGroupWave;
PDEVICE_OBJECT m_pDeviceObject;
PDEVICE_OBJECT m_pPhysicalDeviceObject;
WDFDEVICE m_WdfDevice; // Wdf device.
DEVICE_POWER_STATE m_PowerState;
PCSYSVADHW m_pHW; // Virtual SYSVAD HW object
PPORTCLSETWHELPER m_pPortClsEtwHelper;
static LONG m_AdapterInstances; // # of adapter objects.
DWORD m_dwIdleRequests;
#ifdef SYSVAD_USB_SIDEBAND
typedef struct _SysvadPowerRelationsDo
{
LIST_ENTRY ListEntry;
PDEVICE_OBJECT Pdo;
}SysVadPowerRelationsDo, *PSysVadPowerRelationsDo;
LIST_ENTRY m_PowerRelations;
FAST_MUTEX m_PowerRelationsLock;
#endif//SYSVAD_USB_SIDEBAND
public:
//=====================================================================
// Default CUnknown
DECLARE_STD_UNKNOWN();
DEFINE_STD_CONSTRUCTOR(CAdapterCommon);
~CAdapterCommon();
//=====================================================================
// Default IAdapterPowerManagement
IMP_IAdapterPowerManagement;
//=====================================================================
// IAdapterCommon methods
STDMETHODIMP_(NTSTATUS) Init
(
_In_ PDEVICE_OBJECT DeviceObject
);
STDMETHODIMP_(PDEVICE_OBJECT) GetDeviceObject(void);
STDMETHODIMP_(PDEVICE_OBJECT) GetPhysicalDeviceObject(void);
STDMETHODIMP_(WDFDEVICE) GetWdfDevice(void);
STDMETHODIMP_(void) SetWaveServiceGroup
(
_In_ PSERVICEGROUP ServiceGroup
);
STDMETHODIMP_(BOOL) bDevSpecificRead();
STDMETHODIMP_(void) bDevSpecificWrite
(
_In_ BOOL bDevSpecific
);
STDMETHODIMP_(INT) iDevSpecificRead();
STDMETHODIMP_(void) iDevSpecificWrite
(
_In_ INT iDevSpecific
);
STDMETHODIMP_(UINT) uiDevSpecificRead();
STDMETHODIMP_(void) uiDevSpecificWrite
(
_In_ UINT uiDevSpecific
);
STDMETHODIMP_(BOOL) MixerMuteRead
(
_In_ ULONG Index,
_In_ ULONG Channel
);
STDMETHODIMP_(void) MixerMuteWrite
(
_In_ ULONG Index,
_In_ ULONG Channel,
_In_ BOOL Value
);
STDMETHODIMP_(ULONG) MixerMuxRead(void);
STDMETHODIMP_(void) MixerMuxWrite
(
_In_ ULONG Index
);
STDMETHODIMP_(void) MixerReset(void);
STDMETHODIMP_(LONG) MixerVolumeRead
(
_In_ ULONG Index,
_In_ ULONG Channel
);
STDMETHODIMP_(void) MixerVolumeWrite
(
_In_ ULONG Index,
_In_ ULONG Channel,
_In_ LONG Value
);
STDMETHODIMP_(LONG) MixerPeakMeterRead
(
_In_ ULONG Index,
_In_ ULONG Channel
);
STDMETHODIMP_(NTSTATUS) WriteEtwEvent
(
_In_ EPcMiniportEngineEvent miniportEventType,
_In_ ULONGLONG ullData1,
_In_ ULONGLONG ullData2,
_In_ ULONGLONG ullData3,
_In_ ULONGLONG ullData4
);
STDMETHODIMP_(VOID) SetEtwHelper
(
PPORTCLSETWHELPER _pPortClsEtwHelper
);
STDMETHODIMP_(NTSTATUS) InstallSubdevice
(
_In_opt_ PIRP Irp,
_In_ PWSTR Name,
_In_opt_ PWSTR TemplateName,
_In_ REFGUID PortClassId,
_In_ REFGUID MiniportClassId,
_In_opt_ PFNCREATEMINIPORT MiniportCreate,
_In_ ULONG cPropertyCount,
_In_reads_opt_(cPropertyCount) const SYSVAD_DEVPROPERTY * pProperties,
_In_opt_ PVOID DeviceContext,
_In_ PENDPOINT_MINIPAIR MiniportPair,
_In_opt_ PRESOURCELIST ResourceList,
_In_ REFGUID PortInterfaceId,
_Out_opt_ PUNKNOWN * OutPortInterface,
_Out_opt_ PUNKNOWN * OutPortUnknown,
_Out_opt_ PUNKNOWN * OutMiniportUnknown
);
STDMETHODIMP_(NTSTATUS) UnregisterSubdevice
(
_In_opt_ PUNKNOWN UnknownPort
);
STDMETHODIMP_(NTSTATUS) ConnectTopologies
(
_In_ PUNKNOWN UnknownTopology,
_In_ PUNKNOWN UnknownWave,
_In_ PHYSICALCONNECTIONTABLE* PhysicalConnections,
_In_ ULONG PhysicalConnectionCount
);
STDMETHODIMP_(NTSTATUS) DisconnectTopologies
(
_In_ PUNKNOWN UnknownTopology,
_In_ PUNKNOWN UnknownWave,
_In_ PHYSICALCONNECTIONTABLE* PhysicalConnections,
_In_ ULONG PhysicalConnectionCount
);
STDMETHODIMP_(NTSTATUS) InstallEndpointFilters
(
_In_opt_ PIRP Irp,
_In_ PENDPOINT_MINIPAIR MiniportPair,
_In_opt_ PVOID DeviceContext,
_Out_opt_ PUNKNOWN * UnknownTopology,
_Out_opt_ PUNKNOWN * UnknownWave,
_Out_opt_ PUNKNOWN * UnknownMiniportTopology,
_Out_opt_ PUNKNOWN * UnknownMiniportWave
);
STDMETHODIMP_(NTSTATUS) RemoveEndpointFilters
(
_In_ PENDPOINT_MINIPAIR MiniportPair,
_In_opt_ PUNKNOWN UnknownTopology,
_In_opt_ PUNKNOWN UnknownWave
);
STDMETHODIMP_(NTSTATUS) GetFilters
(
_In_ PENDPOINT_MINIPAIR MiniportPair,
_Out_opt_ PUNKNOWN *UnknownTopologyPort,
_Out_opt_ PUNKNOWN *UnknownTopologyMiniport,
_Out_opt_ PUNKNOWN *UnknownWavePort,
_Out_opt_ PUNKNOWN *UnknownWaveMiniport
);
STDMETHODIMP_(NTSTATUS) SetIdlePowerManagement
(
_In_ PENDPOINT_MINIPAIR MiniportPair,
_In_ BOOL bEnabled
);
STDMETHODIMP_(NTSTATUS) NotifyEndpointPair
(
_In_ WCHAR *RenderEndpointTopoName,
_In_ ULONG RenderEndpointNameLen,
_In_ ULONG RenderPinId,
_In_ WCHAR *CaptureEndpointTopoName,
_In_ ULONG CaptureEndpointNameLen,
_In_ ULONG CapturePinId
);
#ifdef SYSVAD_BTH_BYPASS
STDMETHODIMP_(NTSTATUS) InitBthScoBypass();
STDMETHODIMP_(VOID) CleanupBthScoBypass();
#endif // SYSVAD_BTH_BYPASS
#ifdef SYSVAD_USB_SIDEBAND
STDMETHODIMP_(NTSTATUS) InitUsbSideband();
STDMETHODIMP_(VOID) CleanupUsbSideband();
STDMETHODIMP_(NTSTATUS) AddDeviceAsPowerDependency
(
_In_ PDEVICE_OBJECT pdo
);
STDMETHODIMP_(NTSTATUS) RemoveDeviceAsPowerDependency
(
_In_ PDEVICE_OBJECT pdo
);
#endif // SYSVAD_USB_SIDEBAND
STDMETHODIMP_(VOID) Cleanup();
#ifdef SYSVAD_USB_SIDEBAND
STDMETHODIMP_(NTSTATUS) UpdatePowerRelations(_In_ PIRP Irp);
#endif // SYSVAD_USB_SIDEBAND
//=====================================================================
// friends
friend NTSTATUS NewAdapterCommon
(
_Out_ PUNKNOWN * Unknown,
_In_ REFCLSID,
_In_opt_ PUNKNOWN UnknownOuter,
_When_((PoolType & NonPagedPoolMustSucceed) != 0,
__drv_reportError("Must succeed pool allocations are forbidden. "
"Allocation failures cause a system crash"))
_In_ POOL_TYPE PoolType
);
#ifdef SYSVAD_BTH_BYPASS
//=====================================================================
// Bluetooth Hands-free Profile SCO Bypass support.
private:
PVOID m_BthHfpScoNotificationHandle;
FAST_MUTEX m_BthHfpFastMutex; // To serialize access.
WDFWORKITEM m_BthHfpWorkItem; // Async work-item.
LIST_ENTRY m_BthHfpWorkTasks; // Work-item's tasks.
LIST_ENTRY m_BthHfpDevices; // Bth HFP devices.
NPAGED_LOOKASIDE_LIST m_BthHfpWorkTaskPool; // LookasideList
size_t m_BthHfpWorkTaskPoolElementSize;
BOOL m_BthHfpEnableCleanup; // Do cleanup if true.
private:
static
DRIVER_NOTIFICATION_CALLBACK_ROUTINE EvtBthHfpScoBypassInterfaceChange;
static
EVT_WDF_WORKITEM EvtBthHfpScoBypassInterfaceWorkItem;
protected:
BthHfpDevice * BthHfpDeviceFind
(
_In_ PUNICODE_STRING SymbolicLinkName
);
NTSTATUS BthHfpScoInterfaceArrival
(
_In_ PUNICODE_STRING SymbolicLinkName
);
NTSTATUS BthHfpScoInterfaceRemoval
(
_In_ PUNICODE_STRING SymbolicLinkName
);
#endif // SYSVAD_BTH_BYPASS
#ifdef SYSVAD_USB_SIDEBAND
//=====================================================================
// USB Sideband Audio support.
private:
PVOID m_UsbSidebandNotificationHandle;
FAST_MUTEX m_UsbSidebandFastMutex; // To serialize access.
WDFWORKITEM m_UsbSidebandWorkItem; // Async work-item.
LIST_ENTRY m_UsbSidebandWorkTasks; // Work-item's tasks.
LIST_ENTRY m_UsbSidebandDevices; // USB Sideband devices.
NPAGED_LOOKASIDE_LIST m_UsbSidebandWorkTaskPool; // LookasideList
size_t m_UsbSidebandWorkTaskPoolElementSize;
BOOL m_UsbSidebandEnableCleanup; // Do cleanup if true.
private:
static
DRIVER_NOTIFICATION_CALLBACK_ROUTINE EvtUsbSidebandInterfaceChange;
static
EVT_WDF_WORKITEM EvtUsbSidebandInterfaceWorkItem;
protected:
UsbHsDevice * UsbSidebandDeviceFind
(
_In_ PUNICODE_STRING SymbolicLinkName
);
NTSTATUS UsbSidebandInterfaceArrival
(
_In_ PUNICODE_STRING SymbolicLinkName
);
NTSTATUS UsbSidebandInterfaceRemoval
(
_In_ PUNICODE_STRING SymbolicLinkName
);
#endif // SYSVAD_USB_SIDEBAND
private:
LIST_ENTRY m_SubdeviceCache;
NTSTATUS GetCachedSubdevice
(
_In_ PWSTR Name,
_Out_opt_ PUNKNOWN *OutUnknownPort,
_Out_opt_ PUNKNOWN *OutUnknownMiniport
);
NTSTATUS CacheSubdevice
(
_In_ PWSTR Name,
_In_ PUNKNOWN UnknownPort,
_In_ PUNKNOWN UnknownMiniport
);
NTSTATUS RemoveCachedSubdevice
(
_In_ PWSTR Name
);
VOID EmptySubdeviceCache();
NTSTATUS CreateAudioInterfaceWithProperties
(
_In_ PCWSTR ReferenceString,
_In_opt_ PCWSTR TemplateReferenceString,
_In_ ULONG cPropertyCount,
_In_reads_opt_(cPropertyCount) const SYSVAD_DEVPROPERTY *pProperties,
_Out_ _At_(AudioSymbolicLinkName->Buffer, __drv_allocatesMem(Mem)) PUNICODE_STRING AudioSymbolicLinkName
);
NTSTATUS MigrateDeviceInterfaceTemplateParameters
(
_In_ PUNICODE_STRING SymbolicLinkName,
_In_opt_ PCWSTR TemplateReferenceString
);
};
typedef struct _MINIPAIR_UNKNOWN
{
LIST_ENTRY ListEntry;
WCHAR Name[MAX_PATH];
PUNKNOWN PortInterface;
PUNKNOWN MiniportInterface;
PADAPTERPOWERMANAGEMENT PowerInterface;
PMINIPORTCHANGE MiniportChange;
} MINIPAIR_UNKNOWN;
#define MAX_DEVICE_REG_KEY_LENGTH 0x100
//
// Used to implement the singleton pattern.
//
LONG CAdapterCommon::m_AdapterInstances = 0;
//-----------------------------------------------------------------------------
// Functions
//-----------------------------------------------------------------------------
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS SysvadIoSetDeviceInterfacePropertyDataMultiple
(
_In_ PUNICODE_STRING SymbolicLinkName,
_In_ ULONG cPropertyCount,
_In_reads_opt_(cPropertyCount) const SYSVAD_DEVPROPERTY *pProperties
)
{
NTSTATUS ntStatus;
PAGED_CODE();
if (pProperties)
{
for (ULONG i = 0; i < cPropertyCount; i++)
{
ntStatus = IoSetDeviceInterfacePropertyData(
SymbolicLinkName,
pProperties[i].PropertyKey,
LOCALE_NEUTRAL,
PLUGPLAY_PROPERTY_PERSISTENT,
pProperties[i].Type,
pProperties[i].BufferSize,
pProperties[i].Buffer);
if (!NT_SUCCESS(ntStatus))
{
return ntStatus;
}
}
}
return STATUS_SUCCESS;
}
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS
NewAdapterCommon
(
_Out_ PUNKNOWN * Unknown,
_In_ REFCLSID,
_In_opt_ PUNKNOWN UnknownOuter,
_When_((PoolType & NonPagedPoolMustSucceed) != 0,
__drv_reportError("Must succeed pool allocations are forbidden. "
"Allocation failures cause a system crash"))
_In_ POOL_TYPE PoolType
)
/*++
Routine Description:
Creates a new CAdapterCommon
Arguments:
Unknown -
UnknownOuter -
PoolType
Return Value:
NT status code.
--*/
{
PAGED_CODE();
ASSERT(Unknown);
NTSTATUS ntStatus;
//
// This sample supports only one instance of this object.
// (b/c of CSaveData's static members and Bluetooth HFP logic).
//
if (InterlockedCompareExchange(&CAdapterCommon::m_AdapterInstances, 1, 0) != 0)
{
ntStatus = STATUS_DEVICE_BUSY;
DPF(D_ERROR, ("NewAdapterCommon failed, only one instance is allowed"));
goto Done;
}
//
// Allocate an adapter object.
//
CAdapterCommon *p = new(PoolType, MINADAPTER_POOLTAG) CAdapterCommon(UnknownOuter);
if (p == NULL)
{
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
DPF(D_ERROR, ("NewAdapterCommon failed, 0x%x", ntStatus));
goto Done;
}
//
// Success.
//
*Unknown = PUNKNOWN((PADAPTERCOMMON)(p));
(*Unknown)->AddRef();
ntStatus = STATUS_SUCCESS;
Done:
return ntStatus;
} // NewAdapterCommon
//=============================================================================
#pragma code_seg("PAGE")
CAdapterCommon::~CAdapterCommon
(
void
)
/*++
Routine Description:
Destructor for CAdapterCommon.
Arguments:
Return Value:
void
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::~CAdapterCommon]"));
if (m_pHW)
{
delete m_pHW;
m_pHW = NULL;
}
CSaveData::DestroyWorkItems();
SAFE_RELEASE(m_pPortClsEtwHelper);
SAFE_RELEASE(m_pServiceGroupWave);
if (m_WdfDevice)
{
WdfObjectDelete(m_WdfDevice);
m_WdfDevice = NULL;
}
InterlockedDecrement(&CAdapterCommon::m_AdapterInstances);
ASSERT(CAdapterCommon::m_AdapterInstances == 0);
#ifdef SYSVAD_USB_SIDEBAND
ASSERT(IsListEmpty(&m_PowerRelations));
#endif // SYSVAD_USB_SIDEBAND
} // ~CAdapterCommon
//=============================================================================
#pragma code_seg("PAGE")
STDMETHODIMP_(PDEVICE_OBJECT)
CAdapterCommon::GetDeviceObject
(
void
)
/*++
Routine Description:
Returns the deviceobject
Arguments:
Return Value:
PDEVICE_OBJECT
--*/
{
PAGED_CODE();
return m_pDeviceObject;
} // GetDeviceObject
//=============================================================================
#pragma code_seg("PAGE")
STDMETHODIMP_(PDEVICE_OBJECT)
CAdapterCommon::GetPhysicalDeviceObject
(
void
)
/*++
Routine Description:
Returns the PDO.
Arguments:
Return Value:
PDEVICE_OBJECT
--*/
{
PAGED_CODE();
return m_pPhysicalDeviceObject;
} // GetPhysicalDeviceObject
//=============================================================================
#pragma code_seg("PAGE")
STDMETHODIMP_(WDFDEVICE)
CAdapterCommon::GetWdfDevice
(
void
)
/*++
Routine Description:
Returns the associated WDF miniport device. Note that this is NOT an audio
miniport. The WDF miniport device is the WDF device associated with the
adapter.
Arguments:
Return Value:
WDFDEVICE
--*/
{
PAGED_CODE();
return m_WdfDevice;
} // GetWdfDevice
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS
CAdapterCommon::Init
(
_In_ PDEVICE_OBJECT DeviceObject
)
/*++
Routine Description:
Initialize adapter common object.
Arguments:
DeviceObject - pointer to the device object
Return Value:
NT status code.
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::Init]"));
ASSERT(DeviceObject);
NTSTATUS ntStatus = STATUS_SUCCESS;
#ifdef SYSVAD_BTH_BYPASS
m_BthHfpEnableCleanup = FALSE;
#endif // SYSVAD_BTH_BYPASS
#ifdef SYSVAD_USB_SIDEBAND
m_UsbSidebandEnableCleanup = FALSE;
#endif // SYSVAD_USB_SIDEBAND
m_pServiceGroupWave = NULL;
m_pDeviceObject = DeviceObject;
m_pPhysicalDeviceObject = NULL;
m_WdfDevice = NULL;
m_PowerState = PowerDeviceD0;
m_pHW = NULL;
m_pPortClsEtwHelper = NULL;
InitializeListHead(&m_SubdeviceCache);
#ifdef SYSVAD_USB_SIDEBAND
InitializeListHead(&m_PowerRelations);
ExInitializeFastMutex(&m_PowerRelationsLock);
#endif//SYSVAD_USB_SIDEBAND
//
// Get the PDO.
//
ntStatus = PcGetPhysicalDeviceObject(DeviceObject, &m_pPhysicalDeviceObject);
IF_FAILED_ACTION_JUMP(
ntStatus,
DPF(D_ERROR, ("PcGetPhysicalDeviceObject failed, 0x%x", ntStatus)),
Done);
//
// Create a WDF miniport to represent the adapter. Note that WDF miniports
// are NOT audio miniports. An audio adapter is associated with a single WDF
// miniport. This driver uses WDF to simplify the handling of the Bluetooth
// SCO HFP Bypass interface.
//
ntStatus = WdfDeviceMiniportCreate( WdfGetDriver(),
WDF_NO_OBJECT_ATTRIBUTES,
DeviceObject, // FDO
NULL, // Next device.
NULL, // PDO
&m_WdfDevice);
IF_FAILED_ACTION_JUMP(
ntStatus,
DPF(D_ERROR, ("WdfDeviceMiniportCreate failed, 0x%x", ntStatus)),
Done);
// Initialize HW.
//
m_pHW = new (NonPagedPoolNx, SYSVAD_POOLTAG) CSYSVADHW;
if (!m_pHW)
{
DPF(D_TERSE, ("Insufficient memory for SYSVAD HW"));
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
}
IF_FAILED_JUMP(ntStatus, Done);
m_pHW->MixerReset();
//
// Initialize SaveData class.
//
CSaveData::SetDeviceObject(DeviceObject); //device object is needed by CSaveData
ntStatus = CSaveData::InitializeWorkItems(DeviceObject);
IF_FAILED_JUMP(ntStatus, Done);
Done:
return ntStatus;
} // Init
//=============================================================================
#pragma code_seg("PAGE")
STDMETHODIMP_(void)
CAdapterCommon::MixerReset
(
void
)
/*++
Routine Description:
Reset mixer registers from registry.
Arguments:
Return Value:
void
--*/
{
PAGED_CODE();
if (m_pHW)
{
m_pHW->MixerReset();
}
} // MixerReset
//=============================================================================
/* Here are the definitions of the standard miniport events.
Event type : eMINIPORT_IHV_DEFINED
Parameter 1 : Defined and used by IHVs
Parameter 2 : Defined and used by IHVs
Parameter 3 : Defined and used by IHVs
Parameter 4 :Defined and used by IHVs
Event type: eMINIPORT_BUFFER_COMPLETE
Parameter 1: Current linear buffer position
Parameter 2: the previous WaveRtBufferWritePosition that the drive received
Parameter 3: Data length completed
Parameter 4:0
Event type: eMINIPORT_PIN_STATE
Parameter 1: Current linear buffer position
Parameter 2: the previous WaveRtBufferWritePosition that the drive received
Parameter 3: Pin State 0->KS_STOP, 1->KS_ACQUIRE, 2->KS_PAUSE, 3->KS_RUN
Parameter 4:0
Event type: eMINIPORT_GET_STREAM_POS
Parameter 1: Current linear buffer position
Parameter 2: the previous WaveRtBufferWritePosition that the drive received
Parameter 3: 0
Parameter 4:0
Event type: eMINIPORT_SET_WAVERT_BUFFER_WRITE_POS
Parameter 1: Current linear buffer position
Parameter 2: the previous WaveRtBufferWritePosition that the drive received
Parameter 3: the arget WaveRtBufferWritePosition received from portcls
Parameter 4:0
Event type: eMINIPORT_GET_PRESENTATION_POS
Parameter 1: Current linear buffer position
Parameter 2: the previous WaveRtBufferWritePosition that the drive received
Parameter 3: Presentation position
Parameter 4:0
Event type: eMINIPORT_PROGRAM_DMA
Parameter 1: Current linear buffer position
Parameter 2: the previous WaveRtBufferWritePosition that the drive received
Parameter 3: Starting WaveRt buffer offset
Parameter 4: Data length
Event type: eMINIPORT_GLITCH_REPORT
Parameter 1: Current linear buffer position
Parameter 2: the previous WaveRtBufferWritePosition that the drive received
Parameter 3: major glitch code: 1:WaveRT buffer is underrun,
2:decoder errors,
3:receive the same wavert buffer two in a row in event driven mode
Parameter 4: minor code for the glitch cause
Event type: eMINIPORT_LAST_BUFFER_RENDERED
Parameter 1: Current linear buffer position
Parameter 2: the very last WaveRtBufferWritePosition that the driver received
Parameter 3: 0
Parameter 4: 0
*/
#pragma code_seg()
STDMETHODIMP
CAdapterCommon::WriteEtwEvent
(
_In_ EPcMiniportEngineEvent miniportEventType,
_In_ ULONGLONG ullData1,
_In_ ULONGLONG ullData2,
_In_ ULONGLONG ullData3,
_In_ ULONGLONG ullData4
)
{
NTSTATUS ntStatus = STATUS_SUCCESS;
if (m_pPortClsEtwHelper)
{
ntStatus = m_pPortClsEtwHelper->MiniportWriteEtwEvent( miniportEventType, ullData1, ullData2, ullData3, ullData4) ;
}
return ntStatus;
} // WriteEtwEvent
//=============================================================================
#pragma code_seg("PAGE")
STDMETHODIMP_(void)
CAdapterCommon::SetEtwHelper
(
PPORTCLSETWHELPER _pPortClsEtwHelper
)
{
PAGED_CODE();
SAFE_RELEASE(m_pPortClsEtwHelper);
m_pPortClsEtwHelper = _pPortClsEtwHelper;
if (m_pPortClsEtwHelper)
{
m_pPortClsEtwHelper->AddRef();
}
} // SetEtwHelper
//=============================================================================
#pragma code_seg("PAGE")
STDMETHODIMP
CAdapterCommon::NonDelegatingQueryInterface
(
_In_ REFIID Interface,
_COM_Outptr_ PVOID * Object
)
/*++
Routine Description:
QueryInterface routine for AdapterCommon
Arguments:
Interface -
Object -
Return Value:
NT status code.
--*/
{
PAGED_CODE();
ASSERT(Object);
if (IsEqualGUIDAligned(Interface, IID_IUnknown))
{
*Object = PVOID(PUNKNOWN(PADAPTERCOMMON(this)));
}
else if (IsEqualGUIDAligned(Interface, IID_IAdapterCommon))
{
*Object = PVOID(PADAPTERCOMMON(this));
}
else if (IsEqualGUIDAligned(Interface, IID_IAdapterPowerManagement))
{
*Object = PVOID(PADAPTERPOWERMANAGEMENT(this));
}
else
{
*Object = NULL;
}
if (*Object)
{
PUNKNOWN(*Object)->AddRef();
return STATUS_SUCCESS;
}
return STATUS_INVALID_PARAMETER;
} // NonDelegatingQueryInterface
//=============================================================================
#pragma code_seg("PAGE")
STDMETHODIMP_(void)
CAdapterCommon::SetWaveServiceGroup
(
_In_ PSERVICEGROUP ServiceGroup
)
/*++
Routine Description:
Arguments:
Return Value:
NT status code.
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::SetWaveServiceGroup]"));
SAFE_RELEASE(m_pServiceGroupWave);
m_pServiceGroupWave = ServiceGroup;
if (m_pServiceGroupWave)
{
m_pServiceGroupWave->AddRef();
}
} // SetWaveServiceGroup
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(BOOL)
CAdapterCommon::bDevSpecificRead()
/*++
Routine Description:
Fetch Device Specific information.
Arguments:
N/A
Return Value:
BOOL - Device Specific info
--*/
{
if (m_pHW)
{
return m_pHW->bGetDevSpecific();
}
return FALSE;
} // bDevSpecificRead
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(void)
CAdapterCommon::bDevSpecificWrite
(
_In_ BOOL bDevSpecific
)
/*++
Routine Description:
Store the new value in the Device Specific location.
Arguments:
bDevSpecific - Value to store
Return Value:
N/A.
--*/
{
if (m_pHW)
{
m_pHW->bSetDevSpecific(bDevSpecific);
}
} // DevSpecificWrite
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(INT)
CAdapterCommon::iDevSpecificRead()
/*++
Routine Description:
Fetch Device Specific information.
Arguments:
N/A
Return Value:
INT - Device Specific info
--*/
{
if (m_pHW)
{
return m_pHW->iGetDevSpecific();
}
return 0;
} // iDevSpecificRead
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(void)
CAdapterCommon::iDevSpecificWrite
(
_In_ INT iDevSpecific
)
/*++
Routine Description:
Store the new value in the Device Specific location.
Arguments:
iDevSpecific - Value to store
Return Value:
N/A.
--*/
{
if (m_pHW)
{
m_pHW->iSetDevSpecific(iDevSpecific);
}
} // iDevSpecificWrite
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(UINT)
CAdapterCommon::uiDevSpecificRead()
/*++
Routine Description:
Fetch Device Specific information.
Arguments:
N/A
Return Value:
UINT - Device Specific info
--*/
{
if (m_pHW)
{
return m_pHW->uiGetDevSpecific();
}
return 0;
} // uiDevSpecificRead
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(void)
CAdapterCommon::uiDevSpecificWrite
(
_In_ UINT uiDevSpecific
)
/*++
Routine Description:
Store the new value in the Device Specific location.
Arguments:
uiDevSpecific - Value to store
Return Value:
N/A.
--*/
{
if (m_pHW)
{
m_pHW->uiSetDevSpecific(uiDevSpecific);
}
} // uiDevSpecificWrite
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(BOOL)
CAdapterCommon::MixerMuteRead
(
_In_ ULONG Index,
_In_ ULONG Channel
)
/*++
Routine Description:
Store the new value in mixer register array.
Arguments:
Index - node id
Return Value:
BOOL - mixer mute setting for this node
--*/
{
if (m_pHW)
{
return m_pHW->GetMixerMute(Index, Channel);
}
return 0;
} // MixerMuteRead
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(void)
CAdapterCommon::MixerMuteWrite
(
_In_ ULONG Index,
_In_ ULONG Channel,
_In_ BOOL Value
)
/*++
Routine Description:
Store the new value in mixer register array.
Arguments:
Index - node id
Value - new mute settings
Return Value:
NT status code.
--*/
{
if (m_pHW)
{
m_pHW->SetMixerMute(Index, Channel, Value);
}
} // MixerMuteWrite
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(ULONG)
CAdapterCommon::MixerMuxRead()
/*++
Routine Description:
Return the mux selection
Arguments:
Index - node id
Value - new mute settings
Return Value:
NT status code.
--*/
{
if (m_pHW)
{
return m_pHW->GetMixerMux();
}
return 0;
} // MixerMuxRead
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(void)
CAdapterCommon::MixerMuxWrite
(
_In_ ULONG Index
)
/*++
Routine Description:
Store the new mux selection
Arguments:
Index - node id
Value - new mute settings
Return Value:
NT status code.
--*/
{
if (m_pHW)
{
m_pHW->SetMixerMux(Index);
}
} // MixerMuxWrite
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(LONG)
CAdapterCommon::MixerVolumeRead
(
_In_ ULONG Index,
_In_ ULONG Channel
)
/*++
Routine Description:
Return the value in mixer register array.
Arguments:
Index - node id
Channel = which channel
Return Value:
Byte - mixer volume settings for this line
--*/
{
if (m_pHW)
{
return m_pHW->GetMixerVolume(Index, Channel);
}
return 0;
} // MixerVolumeRead
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(void)
CAdapterCommon::MixerVolumeWrite
(
_In_ ULONG Index,
_In_ ULONG Channel,
_In_ LONG Value
)
/*++
Routine Description:
Store the new value in mixer register array.
Arguments:
Index - node id
Channel - which channel
Value - new volume level
Return Value:
void
--*/
{
if (m_pHW)
{
m_pHW->SetMixerVolume(Index, Channel, Value);
}
} // MixerVolumeWrite
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(LONG)
CAdapterCommon::MixerPeakMeterRead
(
_In_ ULONG Index,
_In_ ULONG Channel
)
/*++
Routine Description:
Return the value in mixer register array.
Arguments:
Index - node id
Channel = which channel
Return Value:
Byte - mixer sample peak meter settings for this line
--*/
{
if (m_pHW)
{
return m_pHW->GetMixerPeakMeter(Index, Channel);
}
return 0;
} // MixerVolumeRead
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(void)
CAdapterCommon::PowerChangeState
(
_In_ POWER_STATE NewState
)
/*++
Routine Description:
Arguments:
NewState - The requested, new power state for the device.
Return Value:
void
Note:
From MSDN:
To assist the driver, PortCls will pause any active audio streams prior to calling
this method to place the device in a sleep state. After calling this method, PortCls
will unpause active audio streams, to wake the device up. Miniports can opt for
additional notification by utilizing the IPowerNotify interface.
The miniport driver must perform the requested change to the device's power state
before it returns from the PowerChangeState call. If the miniport driver needs to
save or restore any device state before a power-state change, the miniport driver
should support the IPowerNotify interface, which allows it to receive advance warning
of any such change. Before returning from a successful PowerChangeState call, the
miniport driver should cache the new power state.
While the miniport driver is in one of the sleep states (any state other than
PowerDeviceD0), it must avoid writing to the hardware. The miniport driver must cache
any hardware accesses that need to be deferred until the device powers up again. If
the power state is changing from one of the sleep states to PowerDeviceD0, the
miniport driver should perform any deferred hardware accesses after it has powered up
the device. If the power state is changing from PowerDeviceD0 to a sleep state, the
miniport driver can perform any necessary hardware accesses during the PowerChangeState
call before it powers down the device.
While powered down, a miniport driver is never asked to create a miniport driver object
or stream object. PortCls always places the device in the PowerDeviceD0 state before
calling the miniport driver's NewStream method.
--*/
{
DPF_ENTER(("[CAdapterCommon::PowerChangeState]"));
// Notify all registered miniports of a power state change
PLIST_ENTRY le = NULL;
for (le = m_SubdeviceCache.Flink; le != &m_SubdeviceCache; le = le->Flink)
{
MINIPAIR_UNKNOWN *pRecord = CONTAINING_RECORD(le, MINIPAIR_UNKNOWN, ListEntry);
if (pRecord->PowerInterface)
{
pRecord->PowerInterface->PowerChangeState(NewState);
}
}
// is this actually a state change??
//
if (NewState.DeviceState != m_PowerState)
{
// switch on new state
//
switch (NewState.DeviceState)
{
case PowerDeviceD0:
case PowerDeviceD1:
case PowerDeviceD2:
case PowerDeviceD3:
m_PowerState = NewState.DeviceState;
DPF
(
D_VERBOSE,
("Entering D%u", ULONG(m_PowerState) - ULONG(PowerDeviceD0))
);
break;
default:
DPF(D_VERBOSE, ("Unknown Device Power State"));
break;
}
}
} // PowerStateChange
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(NTSTATUS)
CAdapterCommon::QueryDeviceCapabilities
(
_Inout_updates_bytes_(sizeof(DEVICE_CAPABILITIES)) PDEVICE_CAPABILITIES PowerDeviceCaps
)
/*++
Routine Description:
Called at startup to get the caps for the device. This structure provides
the system with the mappings between system power state and device power
state. This typically will not need modification by the driver.
Arguments:
PowerDeviceCaps - The device's capabilities.
Return Value:
NT status code.
--*/
{
UNREFERENCED_PARAMETER(PowerDeviceCaps);
DPF_ENTER(("[CAdapterCommon::QueryDeviceCapabilities]"));
return (STATUS_SUCCESS);
} // QueryDeviceCapabilities
//=============================================================================
#pragma code_seg()
STDMETHODIMP_(NTSTATUS)
CAdapterCommon::QueryPowerChangeState
(
_In_ POWER_STATE NewStateQuery
)
/*++
Routine Description:
Query to see if the device can change to this power state
Arguments:
NewStateQuery - The requested, new power state for the device
Return Value:
NT status code.
--*/
{
NTSTATUS status = STATUS_SUCCESS;
DPF_ENTER(("[CAdapterCommon::QueryPowerChangeState]"));
// query each miniport for it's power state, we're finished if even one indicates
// it cannot go to this power state.
PLIST_ENTRY le = NULL;
for (le = m_SubdeviceCache.Flink; le != &m_SubdeviceCache && NT_SUCCESS(status); le = le->Flink)
{
MINIPAIR_UNKNOWN *pRecord = CONTAINING_RECORD(le, MINIPAIR_UNKNOWN, ListEntry);
if (pRecord->PowerInterface)
{
status = pRecord->PowerInterface->QueryPowerChangeState(NewStateQuery);
}
}
return status;
} // QueryPowerChangeState
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS
CAdapterCommon::CreateAudioInterfaceWithProperties
(
_In_ PCWSTR ReferenceString,
_In_opt_ PCWSTR TemplateReferenceString,
_In_ ULONG cPropertyCount,
_In_reads_opt_(cPropertyCount) const SYSVAD_DEVPROPERTY *pProperties,
_Out_ _At_(AudioSymbolicLinkName->Buffer, __drv_allocatesMem(Mem)) PUNICODE_STRING AudioSymbolicLinkName
)
/*++
Routine Description:
Create the audio interface (in disabled mode).
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::CreateAudioInterfaceWithProperties]"));
NTSTATUS ntStatus;
UNICODE_STRING referenceString;
RtlInitUnicodeString(&referenceString, ReferenceString);
//
// Reset output value.
//
RtlZeroMemory(AudioSymbolicLinkName, sizeof(UNICODE_STRING));
//
// Register an audio interface if not already present.
//
ntStatus = IoRegisterDeviceInterface(
GetPhysicalDeviceObject(),
&KSCATEGORY_AUDIO,
&referenceString,
AudioSymbolicLinkName);
IF_FAILED_ACTION_JUMP(
ntStatus,
DPF(D_ERROR, ("CreateAudioInterfaceWithProperties: IoRegisterDeviceInterface(KSCATEGORY_AUDIO): failed, 0x%x", ntStatus)),
Done);
//
// Migrate optional device interface parameters from the template if it exists
// This is done first, so that any additional parameters in pProperties will override the defaults.
//
if (NULL != TemplateReferenceString)
{
ntStatus = MigrateDeviceInterfaceTemplateParameters(AudioSymbolicLinkName, TemplateReferenceString);
IF_FAILED_ACTION_JUMP(
ntStatus,
DPF(D_ERROR, ("MigrateDeviceInterfaceTempalteParameters: MigrateDeviceInterfaceTemplateParameters(...): failed, 0x%x", ntStatus)),
Done);
}
//
// Set properties on the interface
//
ntStatus = SysvadIoSetDeviceInterfacePropertyDataMultiple(AudioSymbolicLinkName, cPropertyCount, pProperties);
IF_FAILED_ACTION_JUMP(
ntStatus,
DPF(D_ERROR, ("CreateAudioInterfaceWithProperties: SysvadIoSetDeviceInterfacePropertyDataMultiple(...): failed, 0x%x", ntStatus)),
Done);
//
// All done.
//
ntStatus = STATUS_SUCCESS;
Done:
if (!NT_SUCCESS(ntStatus))
{
RtlFreeUnicodeString(AudioSymbolicLinkName);
RtlZeroMemory(AudioSymbolicLinkName, sizeof(UNICODE_STRING));
}
return ntStatus;
}
//=============================================================================
#pragma code_seg("PAGE")
STDMETHODIMP_(NTSTATUS)
CAdapterCommon::InstallSubdevice
(
_In_opt_ PIRP Irp,
_In_ PWSTR Name,
_In_opt_ PWSTR TemplateName,
_In_ REFGUID PortClassId,
_In_ REFGUID MiniportClassId,
_In_opt_ PFNCREATEMINIPORT MiniportCreate,
_In_ ULONG cPropertyCount,
_In_reads_opt_(cPropertyCount) const SYSVAD_DEVPROPERTY * pProperties,
_In_opt_ PVOID DeviceContext,
_In_ PENDPOINT_MINIPAIR MiniportPair,
_In_opt_ PRESOURCELIST ResourceList,
_In_ REFGUID PortInterfaceId,
_Out_opt_ PUNKNOWN * OutPortInterface,
_Out_opt_ PUNKNOWN * OutPortUnknown,
_Out_opt_ PUNKNOWN * OutMiniportUnknown
)
{
/*++
Routine Description:
This function creates and registers a subdevice consisting of a port
driver, a minport driver and a set of resources bound together. It will
also optionally place a pointer to an interface on the port driver in a
specified location before initializing the port driver. This is done so
that a common ISR can have access to the port driver during
initialization, when the ISR might fire.
Arguments:
Irp - pointer to the irp object.
Name - name of the miniport. Passes to PcRegisterSubDevice
PortClassId - port class id. Passed to PcNewPort.
MiniportClassId - miniport class id. Passed to PcNewMiniport.
MiniportCreate - pointer to a miniport creation function. If NULL,
PcNewMiniport is used.
DeviceContext - deviceType specific.
MiniportPair - endpoint configuration info.
ResourceList - pointer to the resource list.
PortInterfaceId - GUID that represents the port interface.
OutPortInterface - pointer to store the port interface
OutPortUnknown - pointer to store the unknown port interface.
OutMiniportUnknown - pointer to store the unknown miniport interface
Return Value:
NT status code.
--*/
PAGED_CODE();
DPF_ENTER(("[InstallSubDevice %S]", Name));
ASSERT(Name != NULL);
ASSERT(m_pDeviceObject != NULL);
NTSTATUS ntStatus;
PPORT port = NULL;
PUNKNOWN miniport = NULL;
PADAPTERCOMMON adapterCommon = NULL;
UNICODE_STRING symbolicLink = { 0 };
adapterCommon = PADAPTERCOMMON(this);
ntStatus = CreateAudioInterfaceWithProperties(Name, TemplateName, cPropertyCount, pProperties, &symbolicLink);
if (NT_SUCCESS(ntStatus))
{
// Currently have no use for the symbolic link
RtlFreeUnicodeString(&symbolicLink);
// Create the port driver object
//
ntStatus = PcNewPort(&port, PortClassId);
}
// Create the miniport object
//
if (NT_SUCCESS(ntStatus))
{
if (MiniportCreate)
{
ntStatus =
MiniportCreate
(
&miniport,
MiniportClassId,
NULL,
NonPagedPoolNx,
adapterCommon,
DeviceContext,
MiniportPair
);
}
else
{
ntStatus =
PcNewMiniport
(
(PMINIPORT *) &miniport,
MiniportClassId
);
}
}
// Init the port driver and miniport in one go.
//
if (NT_SUCCESS(ntStatus))
{
#pragma warning(push)
// IPort::Init's annotation on ResourceList requires it to be non-NULL. However,
// for dynamic devices, we may no longer have the resource list and this should
// still succeed.
//
#pragma warning(disable:6387)
ntStatus =
port->Init
(
m_pDeviceObject,
Irp,
miniport,
adapterCommon,
ResourceList
);
#pragma warning (pop)
if (NT_SUCCESS(ntStatus))
{
// Register the subdevice (port/miniport combination).
//
ntStatus =
PcRegisterSubdevice
(
m_pDeviceObject,
Name,
port
);
}
}
// Deposit the port interfaces if it's needed.
//
if (NT_SUCCESS(ntStatus))
{
if (OutPortUnknown)
{
ntStatus =
port->QueryInterface
(
IID_IUnknown,
(PVOID *)OutPortUnknown
);
}
if (OutPortInterface)
{
ntStatus =
port->QueryInterface
(
PortInterfaceId,
(PVOID *) OutPortInterface
);
}
if (OutMiniportUnknown)
{
ntStatus =
miniport->QueryInterface
(
IID_IUnknown,
(PVOID *)OutMiniportUnknown
);
}
}
if (port)
{
port->Release();
}
if (miniport)
{
miniport->Release();
}
return ntStatus;
} // InstallSubDevice
//=============================================================================
#pragma code_seg("PAGE")
STDMETHODIMP_(NTSTATUS)
CAdapterCommon::UnregisterSubdevice
(
_In_opt_ PUNKNOWN UnknownPort
)
/*++
Routine Description:
Unregisters and releases the specified subdevice.
Arguments:
UnknownPort - Wave or topology port interface.
Return Value:
NTSTATUS
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::UnregisterSubdevice]"));
ASSERT(m_pDeviceObject != NULL);
NTSTATUS ntStatus = STATUS_SUCCESS;
PUNREGISTERSUBDEVICE unregisterSubdevice = NULL;
if (NULL == UnknownPort)
{
return ntStatus;
}
//
// Get the IUnregisterSubdevice interface.
//
ntStatus = UnknownPort->QueryInterface(
IID_IUnregisterSubdevice,
(PVOID *)&unregisterSubdevice);
//
// Unregister the port object.
//
if (NT_SUCCESS(ntStatus))
{
ntStatus = unregisterSubdevice->UnregisterSubdevice(
m_pDeviceObject,
UnknownPort);
//
// Release the IUnregisterSubdevice interface.
//
unregisterSubdevice->Release();
}
return ntStatus;
}
//=============================================================================
#pragma code_seg("PAGE")
STDMETHODIMP_(NTSTATUS)
CAdapterCommon::ConnectTopologies
(
_In_ PUNKNOWN UnknownTopology,
_In_ PUNKNOWN UnknownWave,
_In_ PHYSICALCONNECTIONTABLE* PhysicalConnections,
_In_ ULONG PhysicalConnectionCount
)
/*++
Routine Description:
Connects the bridge pins between the wave and mixer topologies.
Arguments:
Return Value:
NTSTATUS
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::ConnectTopologies]"));
ASSERT(m_pDeviceObject != NULL);
NTSTATUS ntStatus = STATUS_SUCCESS;
//
// register wave <=> topology connections
// This will connect bridge pins of wave and topology
// miniports.
//
for (ULONG i = 0; i < PhysicalConnectionCount && NT_SUCCESS(ntStatus); i++)
{
switch(PhysicalConnections[i].eType)
{
case CONNECTIONTYPE_TOPOLOGY_OUTPUT:
ntStatus =
PcRegisterPhysicalConnection
(
m_pDeviceObject,
UnknownTopology,
PhysicalConnections[i].ulTopology,
UnknownWave,
PhysicalConnections[i].ulWave
);
if (!NT_SUCCESS(ntStatus))
{
DPF(D_TERSE, ("ConnectTopologies: PcRegisterPhysicalConnection(render) failed, 0x%x", ntStatus));
}
break;
case CONNECTIONTYPE_WAVE_OUTPUT:
ntStatus =
PcRegisterPhysicalConnection
(
m_pDeviceObject,
UnknownWave,
PhysicalConnections[i].ulWave,
UnknownTopology,
PhysicalConnections[i].ulTopology
);
if (!NT_SUCCESS(ntStatus))
{
DPF(D_TERSE, ("ConnectTopologies: PcRegisterPhysicalConnection(capture) failed, 0x%x", ntStatus));
}
break;
}
}
//
// Cleanup in case of error.
//
if (!NT_SUCCESS(ntStatus))
{
// disconnect all connections on error, ignore error code because not all
// connections may have been made
DisconnectTopologies(UnknownTopology, UnknownWave, PhysicalConnections, PhysicalConnectionCount);
}
return ntStatus;
}
//=============================================================================
#pragma code_seg("PAGE")
STDMETHODIMP_(NTSTATUS)
CAdapterCommon::DisconnectTopologies
(
_In_ PUNKNOWN UnknownTopology,
_In_ PUNKNOWN UnknownWave,
_In_ PHYSICALCONNECTIONTABLE* PhysicalConnections,
_In_ ULONG PhysicalConnectionCount
)
/*++
Routine Description:
Disconnects the bridge pins between the wave and mixer topologies.
Arguments:
Return Value:
NTSTATUS
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::DisconnectTopologies]"));
ASSERT(m_pDeviceObject != NULL);
NTSTATUS ntStatus = STATUS_SUCCESS;
NTSTATUS ntStatus2 = STATUS_SUCCESS;
PUNREGISTERPHYSICALCONNECTION unregisterPhysicalConnection = NULL;
//
// Get the IUnregisterPhysicalConnection interface
//
ntStatus = UnknownTopology->QueryInterface(
IID_IUnregisterPhysicalConnection,
(PVOID *)&unregisterPhysicalConnection);
if (NT_SUCCESS(ntStatus))
{
for (ULONG i = 0; i < PhysicalConnectionCount; i++)
{
switch(PhysicalConnections[i].eType)
{
case CONNECTIONTYPE_TOPOLOGY_OUTPUT:
ntStatus =
unregisterPhysicalConnection->UnregisterPhysicalConnection(
m_pDeviceObject,
UnknownTopology,
PhysicalConnections[i].ulTopology,
UnknownWave,
PhysicalConnections[i].ulWave
);
if (!NT_SUCCESS(ntStatus))
{
DPF(D_TERSE, ("DisconnectTopologies: UnregisterPhysicalConnection(render) failed, 0x%x", ntStatus));
}
break;
case CONNECTIONTYPE_WAVE_OUTPUT:
ntStatus =
unregisterPhysicalConnection->UnregisterPhysicalConnection(
m_pDeviceObject,
UnknownWave,
PhysicalConnections[i].ulWave,
UnknownTopology,
PhysicalConnections[i].ulTopology
);
if (!NT_SUCCESS(ntStatus2))
{
DPF(D_TERSE, ("DisconnectTopologies: UnregisterPhysicalConnection(capture) failed, 0x%x", ntStatus2));
}
break;
}
// cache and return the first error encountered, as it's likely the most relevent
if (NT_SUCCESS(ntStatus))
{
ntStatus = ntStatus2;
}
}
}
//
// Release the IUnregisterPhysicalConnection interface.
//
SAFE_RELEASE(unregisterPhysicalConnection);
return ntStatus;
}
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS
CAdapterCommon::GetCachedSubdevice
(
_In_ PWSTR Name,
_Out_opt_ PUNKNOWN *OutUnknownPort,
_Out_opt_ PUNKNOWN *OutUnknownMiniport
)
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::GetCachedSubdevice]"));
// search list, return interface to device if found, fail if not found
PLIST_ENTRY le = NULL;
BOOL bFound = FALSE;
for (le = m_SubdeviceCache.Flink; le != &m_SubdeviceCache && !bFound; le = le->Flink)
{
MINIPAIR_UNKNOWN *pRecord = CONTAINING_RECORD(le, MINIPAIR_UNKNOWN, ListEntry);
if (0 == wcscmp(Name, pRecord->Name))
{
if (OutUnknownPort)
{
*OutUnknownPort = pRecord->PortInterface;
(*OutUnknownPort)->AddRef();
}
if (OutUnknownMiniport)
{
*OutUnknownMiniport = pRecord->MiniportInterface;
(*OutUnknownMiniport)->AddRef();
}
bFound = TRUE;
}
}
return bFound?STATUS_SUCCESS:STATUS_OBJECT_NAME_NOT_FOUND;
}
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS
CAdapterCommon::CacheSubdevice
(
_In_ PWSTR Name,
_In_ PUNKNOWN UnknownPort,
_In_ PUNKNOWN UnknownMiniport
)
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::CacheSubdevice]"));
// add the item with this name/interface to the list
NTSTATUS ntStatus = STATUS_SUCCESS;
MINIPAIR_UNKNOWN *pNewSubdevice = NULL;
pNewSubdevice = new(NonPagedPoolNx, MINADAPTER_POOLTAG) MINIPAIR_UNKNOWN;
if (!pNewSubdevice)
{
DPF(D_TERSE, ("Insufficient memory to cache subdevice"));
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
}
if (NT_SUCCESS(ntStatus))
{
memset(pNewSubdevice, 0, sizeof(MINIPAIR_UNKNOWN));
ntStatus = RtlStringCchCopyW(pNewSubdevice->Name, SIZEOF_ARRAY(pNewSubdevice->Name), Name);
}
if (NT_SUCCESS(ntStatus))
{
pNewSubdevice->PortInterface = UnknownPort;
pNewSubdevice->PortInterface->AddRef();
pNewSubdevice->MiniportInterface = UnknownMiniport;
pNewSubdevice->MiniportInterface->AddRef();
// cache the IAdapterPowerManagement interface (if available) from the filter. Some endpoints,
// like FM and cellular, have their own power requirements that we must track. If this fails,
// it just means this filter doesn't do power management.
UnknownMiniport->QueryInterface(IID_IAdapterPowerManagement, (PVOID *)&(pNewSubdevice->PowerInterface));
UnknownMiniport->QueryInterface(IID_IMiniportChange, (PVOID *)&(pNewSubdevice->MiniportChange));
InsertTailList(&m_SubdeviceCache, &pNewSubdevice->ListEntry);
}
if (!NT_SUCCESS(ntStatus))
{
if (pNewSubdevice)
{
delete pNewSubdevice;
}
}
return ntStatus;
}
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS
CAdapterCommon::RemoveCachedSubdevice
(
_In_ PWSTR Name
)
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::RemoveCachedSubdevice]"));
// search list, remove the entry from the list
PLIST_ENTRY le = NULL;
BOOL bRemoved = FALSE;
for (le = m_SubdeviceCache.Flink; le != &m_SubdeviceCache && !bRemoved; le = le->Flink)
{
MINIPAIR_UNKNOWN *pRecord = CONTAINING_RECORD(le, MINIPAIR_UNKNOWN, ListEntry);
if (0 == wcscmp(Name, pRecord->Name))
{
SAFE_RELEASE(pRecord->PortInterface);
SAFE_RELEASE(pRecord->MiniportInterface);
SAFE_RELEASE(pRecord->PowerInterface);
SAFE_RELEASE(pRecord->MiniportChange);
memset(pRecord->Name, 0, sizeof(pRecord->Name));
RemoveEntryList(le);
bRemoved = TRUE;
delete pRecord;
break;
}
}
return bRemoved?STATUS_SUCCESS:STATUS_OBJECT_NAME_NOT_FOUND;
}
#pragma code_seg("PAGE")
VOID
CAdapterCommon::EmptySubdeviceCache()
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::EmptySubdeviceCache]"));
while (!IsListEmpty(&m_SubdeviceCache))
{
PLIST_ENTRY le = RemoveHeadList(&m_SubdeviceCache);
MINIPAIR_UNKNOWN *pRecord = CONTAINING_RECORD(le, MINIPAIR_UNKNOWN, ListEntry);
SAFE_RELEASE(pRecord->PortInterface);
SAFE_RELEASE(pRecord->MiniportInterface);
SAFE_RELEASE(pRecord->MiniportChange);
SAFE_RELEASE(pRecord->PowerInterface);
memset(pRecord->Name, 0, sizeof(pRecord->Name));
delete pRecord;
}
}
#pragma code_seg("PAGE")
VOID
CAdapterCommon::Cleanup()
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::Cleanup]"));
#ifdef SYSVAD_BTH_BYPASS
//
// This ensures Bluetooth HFP notifications are turned off when port class
// cleanups and unregisters the static subdevices.
//
CleanupBthScoBypass();
#endif // SYSVAD_BTH_BYPASS
#ifdef SYSVAD_USB_SIDEBAND
//
// This ensures USB Sideband notifications are turned off when port class
// cleanups and unregisters the static subdevices.
//
CleanupUsbSideband();
#endif // SYSVAD_USB_SIDEBAND
EmptySubdeviceCache();
}
#ifdef SYSVAD_USB_SIDEBAND
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS
CAdapterCommon::UpdatePowerRelations(_In_ PIRP Irp)
{
PDEVICE_RELATIONS priorRelations = NULL;
PDEVICE_RELATIONS newRelations = NULL;
ULONG qprPdosCount = 0;
ULONG count = 0;
size_t size;
NTSTATUS status = STATUS_SUCCESS;
ULONG i = 0;
PLIST_ENTRY pe = NULL;
ExAcquireFastMutex(&m_PowerRelationsLock);
pe = m_PowerRelations.Flink;
while (pe != &m_PowerRelations)
{
pe = pe->Flink;
qprPdosCount++;
}
if (0 == qprPdosCount)
{
DPF(D_ERROR, ("CAdapterCommon::UpdatePowerRelations: No PDOs in power relations"));
// Not an error. Just nothing to do.
newRelations = (PDEVICE_RELATIONS)(Irp->IoStatus.Information);
goto Exit;
}
count = qprPdosCount;
priorRelations = (PDEVICE_RELATIONS)Irp->IoStatus.Information;
if (priorRelations != NULL)
{
//
// Another driver in the stack may have added some entries.
// Make sure we allocate space for these additional entries.
//
count = priorRelations->Count + count;
}
//
// Allocate space for the DEVICE_RELATIONS structure (which includes
// space for one PDEVICE_OBJECT, and then allocate enough additional
// space for the extra PDEVICE_OBJECTs we need.
//
size = sizeof(DEVICE_RELATIONS) + (count - 1) * sizeof(PDEVICE_OBJECT);
newRelations = (PDEVICE_RELATIONS)ExAllocatePoolWithTag(PagedPool, size, USBSIDEBANDTEST_POOLTAG015);
ASSERT(newRelations);
if (NULL == newRelations)
{
status = STATUS_INSUFFICIENT_RESOURCES;
DPF(D_ERROR, ("CAdapterCommon::UpdatePowerRelations: could not allocate memory"));
goto Exit;
}
//
// If there was an existing device relations structure, copy
// the entries to the new structure.
//
RtlZeroMemory(newRelations, size);
if (priorRelations != NULL && priorRelations->Count > 0)
{
size = sizeof(DEVICE_RELATIONS) + (priorRelations->Count - 1) * sizeof(PDEVICE_OBJECT);
RtlCopyMemory(newRelations, priorRelations, size);
}
//
// Add new relations to the DEVICE_RELATIONS structure. Pnp dictates that
// each PDO in the list be referenced. Pnp manager will deref the PDO.
//
pe = m_PowerRelations.Flink;
while (pe != &m_PowerRelations)
{
PSysVadPowerRelationsDo powerDepDo = CONTAINING_RECORD(pe, SysVadPowerRelationsDo, ListEntry);
pe = pe->Flink;
#pragma prefast(suppress: __WARNING_BUFFER_OVERFLOW, "the access to newRelation->Objects is in-range")
newRelations->Objects[newRelations->Count] = powerDepDo->Pdo;
// Add a reference on the PDO before returning it as a dependency.
// PnP will remove the reference when appropriate as per msdn.
// https://docs.microsoft.com/en-us/windows-hardware/drivers/kernel/irp-mn-query-device-relations#operation
ObReferenceObject(powerDepDo->Pdo);
//
// update the count
//
newRelations->Count++;
}
Exit:
ExReleaseFastMutex(&m_PowerRelationsLock);
if (!NT_SUCCESS(status))
{
//
// Dereference any previously reported relations before exiting. They
// are dereferenced here because the PNP manager will see error and not
// do anything while the driver which added these objects expects the
// pnp manager to do the dereference. Since this device is changing the
// status, it must act like the pnp manager.
//
if (priorRelations != NULL)
{
for (i = 0; i < priorRelations->Count; ++i)
{
ObDereferenceObject(priorRelations->Objects[i]);
}
}
ASSERT(newRelations == NULL);
}
if (priorRelations != NULL)
{
ExFreePool(priorRelations);
}
Irp->IoStatus.Status = status;
Irp->IoStatus.Information = (ULONG_PTR)newRelations;
return status;
}
#endif // SYSVAD_USB_SIDEBAND
//=============================================================================
#pragma code_seg("PAGE")
STDMETHODIMP_(NTSTATUS)
CAdapterCommon::InstallEndpointFilters
(
_In_opt_ PIRP Irp,
_In_ PENDPOINT_MINIPAIR MiniportPair,
_In_opt_ PVOID DeviceContext,
_Out_opt_ PUNKNOWN * UnknownTopology,
_Out_opt_ PUNKNOWN * UnknownWave,
_Out_opt_ PUNKNOWN * UnknownMiniportTopology,
_Out_opt_ PUNKNOWN * UnknownMiniportWave
)
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::InstallEndpointFilters]"));
NTSTATUS ntStatus = STATUS_SUCCESS;
PUNKNOWN unknownTopology = NULL;
PUNKNOWN unknownWave = NULL;
BOOL bTopologyCreated = FALSE;
BOOL bWaveCreated = FALSE;
PUNKNOWN unknownMiniTopo = NULL;
PUNKNOWN unknownMiniWave = NULL;
// Initialize output optional parameters if needed
if (UnknownTopology)
{
*UnknownTopology = NULL;
}
if (UnknownWave)
{
*UnknownWave = NULL;
}
if (UnknownMiniportTopology)
{
*UnknownMiniportTopology = NULL;
}
if (UnknownMiniportWave)
{
*UnknownMiniportWave = NULL;
}
ntStatus = GetCachedSubdevice(MiniportPair->TopoName, &unknownTopology, &unknownMiniTopo);
if (!NT_SUCCESS(ntStatus) || NULL == unknownTopology || NULL == unknownMiniTopo)
{
bTopologyCreated = TRUE;
// Install SYSVAD topology miniport for the render endpoint.
//
ntStatus = InstallSubdevice(Irp,
MiniportPair->TopoName, // make sure this name matches with SYSVAD.<TopoName>.szPname in the inf's [Strings] section
MiniportPair->TemplateTopoName,
CLSID_PortTopology,
CLSID_PortTopology,
MiniportPair->TopoCreateCallback,
MiniportPair->TopoInterfacePropertyCount,
MiniportPair->TopoInterfaceProperties,
DeviceContext,
MiniportPair,
NULL,
IID_IPortTopology,
NULL,
&unknownTopology,
&unknownMiniTopo
);
if (NT_SUCCESS(ntStatus))
{
ntStatus = CacheSubdevice(MiniportPair->TopoName, unknownTopology, unknownMiniTopo);
}
}
ntStatus = GetCachedSubdevice(MiniportPair->WaveName, &unknownWave, &unknownMiniWave);
if (!NT_SUCCESS(ntStatus) || NULL == unknownWave || NULL == unknownMiniWave)
{
bWaveCreated = TRUE;
// Install SYSVAD wave miniport for the render endpoint.
//
ntStatus = InstallSubdevice(Irp,
MiniportPair->WaveName, // make sure this name matches with SYSVAD.<WaveName>.szPname in the inf's [Strings] section
MiniportPair->TemplateWaveName,
CLSID_PortWaveRT,
CLSID_PortWaveRT,
MiniportPair->WaveCreateCallback,
MiniportPair->WaveInterfacePropertyCount,
MiniportPair->WaveInterfaceProperties,
DeviceContext,
MiniportPair,
NULL,
IID_IPortWaveRT,
NULL,
&unknownWave,
&unknownMiniWave
);
if (NT_SUCCESS(ntStatus))
{
ntStatus = CacheSubdevice(MiniportPair->WaveName, unknownWave, unknownMiniWave);
}
}
if (unknownTopology && unknownWave)
{
//
// register wave <=> topology connections
// This will connect bridge pins of wave and topology
// miniports.
//
ntStatus = ConnectTopologies(
unknownTopology,
unknownWave,
MiniportPair->PhysicalConnections,
MiniportPair->PhysicalConnectionCount);
}
if (NT_SUCCESS(ntStatus))
{
//
// Set output parameters.
//
if (UnknownTopology != NULL && unknownTopology != NULL)
{
unknownTopology->AddRef();
*UnknownTopology = unknownTopology;
}
if (UnknownWave != NULL && unknownWave != NULL)
{
unknownWave->AddRef();
*UnknownWave = unknownWave;
}
if (UnknownMiniportTopology != NULL && unknownMiniTopo != NULL)
{
unknownMiniTopo->AddRef();
*UnknownMiniportTopology = unknownMiniTopo;
}
if (UnknownMiniportWave != NULL && unknownMiniWave != NULL)
{
unknownMiniWave->AddRef();
*UnknownMiniportWave = unknownMiniWave;
}
}
else
{
if (bTopologyCreated && unknownTopology != NULL)
{
UnregisterSubdevice(unknownTopology);
RemoveCachedSubdevice(MiniportPair->TopoName);
}
if (bWaveCreated && unknownWave != NULL)
{
UnregisterSubdevice(unknownWave);
RemoveCachedSubdevice(MiniportPair->WaveName);
}
}
SAFE_RELEASE(unknownMiniTopo);
SAFE_RELEASE(unknownTopology);
SAFE_RELEASE(unknownMiniWave);
SAFE_RELEASE(unknownWave);
return ntStatus;
}
//=============================================================================
#pragma code_seg("PAGE")
STDMETHODIMP_(NTSTATUS)
CAdapterCommon::RemoveEndpointFilters
(
_In_ PENDPOINT_MINIPAIR MiniportPair,
_In_opt_ PUNKNOWN UnknownTopology,
_In_opt_ PUNKNOWN UnknownWave
)
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::RemoveEndpointFilters]"));
NTSTATUS ntStatus = STATUS_SUCCESS;
if (UnknownTopology != NULL && UnknownWave != NULL)
{
ntStatus = DisconnectTopologies(
UnknownTopology,
UnknownWave,
MiniportPair->PhysicalConnections,
MiniportPair->PhysicalConnectionCount);
if (!NT_SUCCESS(ntStatus))
{
DPF(D_VERBOSE, ("RemoveEndpointFilters: DisconnectTopologies failed: 0x%x", ntStatus));
}
}
RemoveCachedSubdevice(MiniportPair->WaveName);
ntStatus = UnregisterSubdevice(UnknownWave);
if (!NT_SUCCESS(ntStatus))
{
DPF(D_VERBOSE, ("RemoveEndpointFilters: UnregisterSubdevice(wave) failed: 0x%x", ntStatus));
}
RemoveCachedSubdevice(MiniportPair->TopoName);
ntStatus = UnregisterSubdevice(UnknownTopology);
if (!NT_SUCCESS(ntStatus))
{
DPF(D_VERBOSE, ("RemoveEndpointFilters: UnregisterSubdevice(topology) failed: 0x%x", ntStatus));
}
//
// All Done.
//
ntStatus = STATUS_SUCCESS;
return ntStatus;
}
//=============================================================================
#pragma code_seg("PAGE")
STDMETHODIMP_(NTSTATUS)
CAdapterCommon::GetFilters
(
_In_ PENDPOINT_MINIPAIR MiniportPair,
_Out_opt_ PUNKNOWN * UnknownTopologyPort,
_Out_opt_ PUNKNOWN * UnknownTopologyMiniport,
_Out_opt_ PUNKNOWN * UnknownWavePort,
_Out_opt_ PUNKNOWN * UnknownWaveMiniport
)
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::GetFilters]"));
NTSTATUS ntStatus = STATUS_SUCCESS;
PUNKNOWN unknownTopologyPort = NULL;
PUNKNOWN unknownTopologyMiniport = NULL;
PUNKNOWN unknownWavePort = NULL;
PUNKNOWN unknownWaveMiniport = NULL;
// if the client requested the topology filter, find it and return it
if (UnknownTopologyPort != NULL || UnknownTopologyMiniport != NULL)
{
ntStatus = GetCachedSubdevice(MiniportPair->TopoName, &unknownTopologyPort, &unknownTopologyMiniport);
if (NT_SUCCESS(ntStatus))
{
if (UnknownTopologyPort)
{
*UnknownTopologyPort = unknownTopologyPort;
}
if (UnknownTopologyMiniport)
{
*UnknownTopologyMiniport = unknownTopologyMiniport;
}
}
}
// if the client requested the wave filter, find it and return it
if (NT_SUCCESS(ntStatus) && (UnknownWavePort != NULL || UnknownWaveMiniport != NULL))
{
ntStatus = GetCachedSubdevice(MiniportPair->WaveName, &unknownWavePort, &unknownWaveMiniport);
if (NT_SUCCESS(ntStatus))
{
if (UnknownWavePort)
{
*UnknownWavePort = unknownWavePort;
}
if (UnknownWaveMiniport)
{
*UnknownWaveMiniport = unknownWaveMiniport;
}
}
}
return ntStatus;
}
//=============================================================================
#pragma code_seg("PAGE")
STDMETHODIMP_(NTSTATUS)
CAdapterCommon::SetIdlePowerManagement
(
_In_ PENDPOINT_MINIPAIR MiniportPair,
_In_ BOOL bEnabled
)
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::SetIdlePowerManagement]"));
NTSTATUS ntStatus = STATUS_SUCCESS;
IUnknown *pUnknown = NULL;
PPORTCLSPOWER pPortClsPower = NULL;
// refcounting disable requests. Each miniport is responsible for calling this in pairs,
// disable on the first request to disable, enable on the last request to enable.
// make sure that we always call SetIdlePowerManagment using the IPortClsPower
// from the requesting port, so we don't cache a reference to a port
// indefinitely, preventing it from ever unloading.
ntStatus = GetFilters(MiniportPair, NULL, NULL, &pUnknown, NULL);
if (NT_SUCCESS(ntStatus))
{
ntStatus =
pUnknown->QueryInterface
(
IID_IPortClsPower,
(PVOID*) &pPortClsPower
);
}
if (NT_SUCCESS(ntStatus))
{
if (bEnabled)
{
m_dwIdleRequests--;
if (0 == m_dwIdleRequests)
{
pPortClsPower->SetIdlePowerManagement(m_pDeviceObject, TRUE);
}
}
else
{
if (0 == m_dwIdleRequests)
{
pPortClsPower->SetIdlePowerManagement(m_pDeviceObject, FALSE);
}
m_dwIdleRequests++;
}
}
SAFE_RELEASE(pUnknown);
SAFE_RELEASE(pPortClsPower);
return ntStatus;
}
#ifdef SYSVAD_BTH_BYPASS
//
// CAdapterCommon Bluetooth Hands-Free Profile function implementation.
//
//=============================================================================
#pragma code_seg("PAGE")
VOID
CAdapterCommon::EvtBthHfpScoBypassInterfaceWorkItem
(
_In_ WDFWORKITEM WorkItem
)
/*++
Routine Description:
The function handles the arrival or removal of a HFP SCO Bypass interface.
Arguments:
WorkItem - WDF work-item object.
--*/
{
PAGED_CODE();
DPF_ENTER(("[EvtBthHfpScoBypassInterfaceWorkItem]"));
CAdapterCommon * This;
if (WorkItem == NULL)
{
return;
}
This = GetBthHfpWorkItemContext(WorkItem)->Adapter;
ASSERT(This != NULL);
for (;;)
{
PLIST_ENTRY le = NULL;
BthHfpWorkTask * task = NULL;
//
// Retrieve a taask.
//
ExAcquireFastMutex(&This->m_BthHfpFastMutex);
if (!IsListEmpty(&This->m_BthHfpWorkTasks))
{
le = RemoveHeadList(&This->m_BthHfpWorkTasks);
task = CONTAINING_RECORD(le, BthHfpWorkTask, ListEntry);
InitializeListHead(le);
}
ExReleaseFastMutex(&This->m_BthHfpFastMutex);
if (task == NULL)
{
break;
}
ASSERT(task->Device != NULL);
_Analysis_assume_(task->Device != NULL);
//
// Process the task.
//
switch(task->Action)
{
case eBthHfpTaskStart:
task->Device->Start();
break;
case eBthHfpTaskStop:
task->Device->Stop();
break;
default:
DPF(D_ERROR, ("EvtBthHfpScoBypassInterfaceWorkItem: invalid action %d", task->Action));
break;
}
//
// Release the ref we took on the device when we inserted the task in the queue.
// For a stop operation this may be the last reference.
//
SAFE_RELEASE(task->Device);
//
// Free the task.
//
ExFreeToNPagedLookasideList(&This->m_BthHfpWorkTaskPool, task);
}
}
//=============================================================================
#pragma code_seg("PAGE")
BthHfpDevice *
CAdapterCommon::BthHfpDeviceFind
(
_In_ PUNICODE_STRING SymbolicLinkName
)
/*++
Routine Description:
The function looks for the specified device in the adapter's list.
Arguments:
SymbolicLinkName - interface's symbolic link.
Return Value:
BthHfpDevice pointer or NULL.
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::BthHfpDeviceFind]"));
PLIST_ENTRY le = NULL;
BthHfpDevice * bthDevice = NULL;
ExAcquireFastMutex(&m_BthHfpFastMutex);
for (le = m_BthHfpDevices.Flink; le != &m_BthHfpDevices; le = le->Flink)
{
BthHfpDevice * tmpBthDevice = BthHfpDevice::GetBthHfpDevice(le);
ASSERT(tmpBthDevice != NULL);
PUNICODE_STRING unicodeStr = tmpBthDevice->GetSymbolicLinkName();
ASSERT(unicodeStr != NULL);
if (unicodeStr->Length == SymbolicLinkName->Length &&
0 == wcsncmp(unicodeStr->Buffer, SymbolicLinkName->Buffer, unicodeStr->Length/sizeof(WCHAR)))
{
// Found it!
bthDevice = tmpBthDevice;
bthDevice->AddRef();
break;
}
}
ExReleaseFastMutex(&m_BthHfpFastMutex);
return bthDevice;
}
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS
CAdapterCommon::BthHfpScoInterfaceArrival
(
_In_ PUNICODE_STRING SymbolicLinkName
)
/*++
Routine Description:
The function handles the arrival of a new HFP SCO Bypass interface.
Arguments:
SymbolicLinkName - new interface's symbolic link.
Return Value:
NT status code.
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::BthHfpScoInterfaceArrival]"));
NTSTATUS ntStatus = STATUS_SUCCESS;
BthHfpDevice * bthDevice = NULL;
BthHfpWorkTask * bthWorkTask = NULL;
DPF(D_VERBOSE, ("BthHfpScoInterfaceArrival: SymbolicLinkName %wZ", SymbolicLinkName));
//
// Check if the Bluetooth device is already present.
// According to the docs it is possible to receive two notifications for the same
// interface.
//
bthDevice = BthHfpDeviceFind(SymbolicLinkName);
if (bthDevice != NULL)
{
DPF(D_VERBOSE, ("BthHfpScoInterfaceArrival: Bluetooth HFP device already present"));
SAFE_RELEASE(bthDevice);
ntStatus = STATUS_SUCCESS;
goto Done;
}
//
// Alloc a new structure for this Bluetooth hands-free device.
//
bthDevice = new (NonPagedPoolNx, MINADAPTER_POOLTAG) BthHfpDevice(NULL); // NULL -> OuterUnknown
if (NULL == bthDevice)
{
DPF(D_ERROR, ("BthHfpScoInterfaceArrival: unable to allocate BthHfpDevice, out of memory"));
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
goto Done;
}
DPF(D_VERBOSE, ("BthHfpScoInterfaceArrival: created BthHfpDevice 0x%p ", bthDevice));
//
// Basic initialization of the Bluetooth Hands-Free Profile interface.
// The audio miniport creation is done later by the BthHfpDevice.Start()
// which is invoked asynchronously by a worker thread.
// BthHfpDevice->Init() must be invoked just after the creation of the object.
//
ntStatus = bthDevice->Init(this, SymbolicLinkName);
IF_FAILED_JUMP(ntStatus, Done);
//
// Get and init a work task.
//
bthWorkTask = (BthHfpWorkTask*)ExAllocateFromNPagedLookasideList(&m_BthHfpWorkTaskPool);
if (NULL == bthWorkTask)
{
DPF(D_ERROR, ("BthHfpScoInterfaceArrival: unable to allocate BthHfpWorkTask, out of memory"));
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
goto Done;
}
// bthWorkTask->L.Size is set to sizeof(BthHfpWorkTask) in the Look Aside List configuration
#pragma warning(suppress: 6386)
RtlZeroMemory(bthWorkTask, sizeof(*bthWorkTask));
bthWorkTask->Action = eBthHfpTaskStart;
InitializeListHead(&bthWorkTask->ListEntry);
// Note that bthDevice has one reference at this point.
bthWorkTask->Device = bthDevice;
ExAcquireFastMutex(&m_BthHfpFastMutex);
//
// Insert this new Bluetooth HFP device in our list.
//
InsertTailList(&m_BthHfpDevices, bthDevice->GetListEntry());
//
// Add a new task for the worker thread.
//
InsertTailList(&m_BthHfpWorkTasks, &bthWorkTask->ListEntry);
bthDevice->AddRef(); // released when task runs.
//
// Schedule a work-item if not already running.
//
WdfWorkItemEnqueue(m_BthHfpWorkItem);
ExReleaseFastMutex(&m_BthHfpFastMutex);
Done:
if (!NT_SUCCESS(ntStatus))
{
// Release the last ref, this will delete the BthHfpDevice
SAFE_RELEASE(bthDevice);
if (bthWorkTask != NULL)
{
ExFreeToNPagedLookasideList(&m_BthHfpWorkTaskPool, bthWorkTask);
bthWorkTask = NULL;
}
}
return ntStatus;
}
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS
CAdapterCommon::BthHfpScoInterfaceRemoval
(
_In_ PUNICODE_STRING SymbolicLinkName
)
/*++
Routine Description:
The function handles the removal of a HFP SCO Bypass interface.
Arguments:
SymbolicLinkName - interface's symbolic link to remove.
Return Value:
NT status code.
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::BthHfpScoInterfaceRemoval]"));
NTSTATUS ntStatus = STATUS_SUCCESS;
BthHfpDevice * bthDevice = NULL;
BthHfpWorkTask * bthWorkTask = NULL;
DPF(D_VERBOSE, ("BthHfpScoInterfaceRemoval: SymbolicLinkName %wZ", SymbolicLinkName));
//
// Check if the Bluetooth device is present.
//
bthDevice = BthHfpDeviceFind(SymbolicLinkName);
if (bthDevice == NULL)
{
// This can happen if the init/start of the BthHfpDevice failed.
DPF(D_VERBOSE, ("BthHfpScoInterfaceRemoval: Bluetooth HFP device not found"));
ntStatus = STATUS_SUCCESS;
goto Done;
}
//
// Init a work task.
//
bthWorkTask = (BthHfpWorkTask*)ExAllocateFromNPagedLookasideList(&m_BthHfpWorkTaskPool);
if (NULL == bthWorkTask)
{
DPF(D_ERROR, ("BthHfpScoInterfaceRemoval: unable to allocate BthHfpWorkTask, out of memory"));
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
goto Done;
}
// bthWorkTask->L.Size is set to sizeof(BthHfpWorkTask) in the Look Aside List configuration
#pragma warning(suppress: 6386)
RtlZeroMemory(bthWorkTask, sizeof(*bthWorkTask));
bthWorkTask->Action = eBthHfpTaskStop;
InitializeListHead(&bthWorkTask->ListEntry);
// Work-item callback will release the reference we got above from BthHfpDeviceFind.
bthWorkTask->Device = bthDevice;
ExAcquireFastMutex(&m_BthHfpFastMutex);
//
// Remove this Bluetooth device from our list and release the associated reference.
//
RemoveEntryList(bthDevice->GetListEntry());
InitializeListHead(bthDevice->GetListEntry());
bthDevice->Release(); // This is not the last ref.
//
// Add a new task for the worker thread.
//
InsertTailList(&m_BthHfpWorkTasks, &bthWorkTask->ListEntry);
//
// Schedule a work-item if not already running.
//
WdfWorkItemEnqueue(m_BthHfpWorkItem);
ExReleaseFastMutex(&m_BthHfpFastMutex);
//
// All done.
//
ntStatus = STATUS_SUCCESS;
Done:
if (!NT_SUCCESS(ntStatus))
{
// Release the ref we got in find.
SAFE_RELEASE(bthDevice);
}
return ntStatus;
}
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS
CAdapterCommon::EvtBthHfpScoBypassInterfaceChange(
_In_ PVOID NotificationPointer,
_Inout_opt_ PVOID Context
)
/*++
Routine Description:
This callback is invoked when a new HFP SCO Bypass interface is added or removed.
Arguments:
NotificationPointer - Interface change notification
Context - CAdapterCommon ptr.
Return Value:
NT status code.
--*/
{
PAGED_CODE();
DPF_ENTER(("[EvtBthHfpScoBypassInterfaceChange]"));
NTSTATUS ntStatus = STATUS_SUCCESS;
CAdapterCommon * This = NULL;
PDEVICE_INTERFACE_CHANGE_NOTIFICATION Notification = (PDEVICE_INTERFACE_CHANGE_NOTIFICATION) NotificationPointer;
//
// Make sure this is the interface class we extect. Any other class guid
// is an error, but let it go since it is not fatal to the machine.
//
if (!IsEqualGUID(Notification->InterfaceClassGuid, GUID_DEVINTERFACE_BLUETOOTH_HFP_SCO_HCIBYPASS))
{
DPF(D_VERBOSE, ("EvtBthHfpScoBypassInterfaceChange: bad interface ClassGuid"));
ASSERTMSG("EvtBthHfpScoBypassInterfaceChange: bad interface ClassGuid ", FALSE);
goto Done;
}
This = (CAdapterCommon *)Context;
ASSERT(This != NULL);
_Analysis_assume_(This != NULL);
//
// Take action based on the event. Any other event type is an error,
// but let it go since it is not fatal to the machine.
//
if (IsEqualGUID(Notification->Event, GUID_DEVICE_INTERFACE_ARRIVAL))
{
ntStatus = This->BthHfpScoInterfaceArrival(Notification->SymbolicLinkName);
}
else if (IsEqualGUID(Notification->Event, GUID_DEVICE_INTERFACE_REMOVAL))
{
ntStatus = This->BthHfpScoInterfaceRemoval(Notification->SymbolicLinkName);
}
else
{
DPF(D_VERBOSE, ("EvtBthHfpScoBypassInterfaceChange: bad "
"GUID_DEVINTERFACE_BLUETOOTH_HFP_SCO_HCIBYPASS event"));
ASSERTMSG("EvtBthHfpScoBypassInterfaceChange: bad "
"GUID_DEVINTERFACE_BLUETOOTH_HFP_SCO_HCIBYPASS event ", FALSE);
goto Done;
}
Done:
return ntStatus;
}
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS
CAdapterCommon::InitBthScoBypass()
/*++
Routine Description:
Initialize the bluetooth bypass environment.
Return Value:
NT status code.
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::InitBluetoothBypass]"));
NTSTATUS ntStatus = STATUS_SUCCESS;
WDF_WORKITEM_CONFIG wiConfig;
WDF_OBJECT_ATTRIBUTES attributes;
BthHfpWorkItemContext * wiContext;
//
// Init spin-lock, linked lists, work-item, event, etc.
// Init all members to default values. This basic init should not fail.
//
m_BthHfpWorkItem = NULL;
m_BthHfpScoNotificationHandle = NULL;
ExInitializeFastMutex(&m_BthHfpFastMutex);
InitializeListHead(&m_BthHfpWorkTasks);
InitializeListHead(&m_BthHfpDevices);
m_BthHfpWorkTaskPoolElementSize = sizeof(BthHfpWorkTask);
ExInitializeNPagedLookasideList(&m_BthHfpWorkTaskPool,
NULL,
NULL,
POOL_NX_ALLOCATION,
m_BthHfpWorkTaskPoolElementSize,
MINADAPTER_POOLTAG,
0);
//
// Enable Bluetooth HFP SCO-Bypass Cleanup.
// Do any allocation/initialization that can fail after this point.
//
m_BthHfpEnableCleanup = TRUE;
//
// Allocate a WDF work-item.
//
WDF_WORKITEM_CONFIG_INIT(&wiConfig, EvtBthHfpScoBypassInterfaceWorkItem);
wiConfig.AutomaticSerialization = FALSE;
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, BthHfpWorkItemContext);
attributes.ParentObject = GetWdfDevice();
ntStatus = WdfWorkItemCreate( &wiConfig,
&attributes,
&m_BthHfpWorkItem);
IF_FAILED_ACTION_JUMP(
ntStatus,
DPF(D_ERROR, ("InitBthScoBypass: WdfWorkItemCreate failed: 0x%x", ntStatus)),
Done);
wiContext = GetBthHfpWorkItemContext(m_BthHfpWorkItem);
wiContext->Adapter = this; // weak ref.
//
// Register for bluetooth heandsfree profile interface changes.
//
ntStatus = IoRegisterPlugPlayNotification (
EventCategoryDeviceInterfaceChange,
PNPNOTIFY_DEVICE_INTERFACE_INCLUDE_EXISTING_INTERFACES,
(PVOID)&GUID_DEVINTERFACE_BLUETOOTH_HFP_SCO_HCIBYPASS,
m_pDeviceObject->DriverObject,
EvtBthHfpScoBypassInterfaceChange,
(PVOID)this,
&m_BthHfpScoNotificationHandle);
IF_FAILED_ACTION_JUMP(
ntStatus,
DPF(D_ERROR, ("InitBthScoBypass: IoRegisterPlugPlayNotification(GUID_DEVINTERFACE_BLUETOOTH_HFP_SCO_HCIBYPASS) failed: 0x%x", ntStatus)),
Done);
//
// Initialization completed.
//
ntStatus = STATUS_SUCCESS;
Done:
return ntStatus;
}
//=============================================================================
#pragma code_seg("PAGE")
VOID
CAdapterCommon::CleanupBthScoBypass()
/*++
Routine Description:
Cleanup the bluetooth bypass environment.
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::CleanupBthScoBypass]"));
//
// Do nothing if Bluetooth HFP environment was not correctly initialized.
//
if (m_BthHfpEnableCleanup == FALSE)
{
return;
}
//
// Unregister for bluetooth heandsfree profile interface changes.
//
if (m_BthHfpScoNotificationHandle != NULL)
{
(void)IoUnregisterPlugPlayNotificationEx(m_BthHfpScoNotificationHandle);
m_BthHfpScoNotificationHandle = NULL;
}
//
// Wait for the Bluetooth hands-free profile worker thread to be done.
//
if (m_BthHfpWorkItem != NULL)
{
WdfWorkItemFlush(m_BthHfpWorkItem);
WdfObjectDelete(m_BthHfpWorkItem);
m_BthHfpWorkItem = NULL;
}
ASSERT(IsListEmpty(&m_BthHfpWorkTasks));
//
// Stop and delete all BthHfpDevices. We are the only thread accessing this list,
// so there is no need to acquire the mutex.
//
while (!IsListEmpty(&m_BthHfpDevices))
{
BthHfpDevice * bthDevice = NULL;
PLIST_ENTRY le = NULL;
le = RemoveHeadList(&m_BthHfpDevices);
bthDevice = BthHfpDevice::GetBthHfpDevice(le);
InitializeListHead(le);
// bthDevice is invalid after this call.
bthDevice->Stop();
// This should be the last reference.
bthDevice->Release();
}
ASSERT(IsListEmpty(&m_BthHfpDevices));
//
// General cleanup.
//
ExDeleteNPagedLookasideList(&m_BthHfpWorkTaskPool);
}
#endif // SYSVAD_BTH_BYPASS
#ifdef SYSVAD_USB_SIDEBAND
//
// CAdapterCommon USB Sideband function implementation.
//
//=============================================================================
#pragma code_seg("PAGE")
VOID
CAdapterCommon::EvtUsbSidebandInterfaceWorkItem
(
_In_ WDFWORKITEM WorkItem
)
/*++
Routine Description:
The function handles the arrival or removal of a USB Sideband interface.
Arguments:
WorkItem - WDF work-item object.
--*/
{
PAGED_CODE();
DPF_ENTER(("[EvtUsbSidebandInterfaceWorkItem]"));
CAdapterCommon * This;
if (WorkItem == NULL)
{
return;
}
This = GetUsbHsWorkItemContext(WorkItem)->Adapter;
ASSERT(This != NULL);
for (;;)
{
PLIST_ENTRY le = NULL;
UsbHsWorkTask * task = NULL;
//
// Retrieve a taask.
//
ExAcquireFastMutex(&This->m_UsbSidebandFastMutex);
if (!IsListEmpty(&This->m_UsbSidebandWorkTasks))
{
le = RemoveHeadList(&This->m_UsbSidebandWorkTasks);
task = CONTAINING_RECORD(le, UsbHsWorkTask, ListEntry);
InitializeListHead(le);
}
ExReleaseFastMutex(&This->m_UsbSidebandFastMutex);
if (task == NULL)
{
break;
}
ASSERT(task->Device != NULL);
_Analysis_assume_(task->Device != NULL);
//
// Process the task.
//
switch (task->Action)
{
case eUsbHsTaskStart:
task->Device->Start();
break;
case eUsbHsTaskStop:
task->Device->Stop();
break;
default:
DPF(D_ERROR, ("EvtUsbSidebandInterfaceWorkItem: invalid action %d", task->Action));
break;
}
//
// Release the ref we took on the device when we inserted the task in the queue.
// For a stop operation this may be the last reference.
//
SAFE_RELEASE(task->Device);
//
// Free the task.
//
ExFreeToNPagedLookasideList(&This->m_UsbSidebandWorkTaskPool, task);
}
}
//=============================================================================
#pragma code_seg("PAGE")
UsbHsDevice *
CAdapterCommon::UsbSidebandDeviceFind
(
_In_ PUNICODE_STRING SymbolicLinkName
)
/*++
Routine Description:
The function looks for the specified device in the adapter's list.
Arguments:
SymbolicLinkName - interface's symbolic link.
Return Value:
UsbSidebandDevice pointer or NULL.
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::UsbSidebandDeviceFind]"));
PLIST_ENTRY le = NULL;
UsbHsDevice * usbDevice = NULL;
ExAcquireFastMutex(&m_UsbSidebandFastMutex);
for (le = m_UsbSidebandDevices.Flink; le != &m_UsbSidebandDevices; le = le->Flink)
{
UsbHsDevice * tmpUsbHsDevice = UsbHsDevice::GetUsbHsDevice(le);
ASSERT(tmpUsbHsDevice != NULL);
PUNICODE_STRING unicodeStr = tmpUsbHsDevice->GetSymbolicLinkName();
ASSERT(unicodeStr != NULL);
if (unicodeStr->Length == SymbolicLinkName->Length &&
0 == wcsncmp(unicodeStr->Buffer, SymbolicLinkName->Buffer, unicodeStr->Length / sizeof(WCHAR)))
{
// Found it!
usbDevice = tmpUsbHsDevice;
usbDevice->AddRef();
break;
}
}
ExReleaseFastMutex(&m_UsbSidebandFastMutex);
return usbDevice;
}
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS
CAdapterCommon::UsbSidebandInterfaceArrival
(
_In_ PUNICODE_STRING SymbolicLinkName
)
/*++
Routine Description:
The function handles the arrival of a new USB Sideband interface.
Arguments:
SymbolicLinkName - new interface's symbolic link.
Return Value:
NT status code.
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::UsbSidebandInterfaceArrival]"));
NTSTATUS ntStatus = STATUS_SUCCESS;
UsbHsDevice *usbHsDevice = NULL;
UsbHsWorkTask *usbHsWorkTask = NULL;
DPF(D_VERBOSE, ("UsbSidebandInterfaceArrival: SymbolicLinkName %wZ", SymbolicLinkName));
//
// Check if the USB device is already present.
// According to the docs it is possible to receive two notifications for the same
// interface.
//
usbHsDevice = UsbSidebandDeviceFind(SymbolicLinkName);
if (usbHsDevice != NULL)
{
DPF(D_VERBOSE, ("UsbSidebandInterfaceArrival: USB device already present"));
SAFE_RELEASE(usbHsDevice);
ntStatus = STATUS_SUCCESS;
goto Done;
}
//
// Alloc a new structure for this USB device.
//
usbHsDevice = new (NonPagedPoolNx, MINADAPTER_POOLTAG) UsbHsDevice(NULL); // NULL -> OuterUnknown
if (NULL == usbHsDevice)
{
DPF(D_ERROR, ("UsbSidebandInterfaceArrival: unable to allocate UsbSidebandDevice, out of memory"));
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
goto Done;
}
DPF(D_VERBOSE, ("UsbSidebandInterfaceArrival: created UsbSidebandDevice 0x%p ", usbHsDevice));
//
// Basic initialization of the USB Sideband interface.
// The audio miniport creation is done later by the UsbSidebandDevice.Start()
// which is invoked asynchronously by a worker thread.
// UsbSidebandDevice->Init() must be invoked just after the creation of the object.
//
ntStatus = usbHsDevice->Init(this, SymbolicLinkName);
IF_FAILED_JUMP(ntStatus, Done);
//
// Get and init a work task.
//
usbHsWorkTask = (UsbHsWorkTask*)ExAllocateFromNPagedLookasideList(&m_UsbSidebandWorkTaskPool);
if (NULL == usbHsWorkTask)
{
DPF(D_ERROR, ("UsbSidebandInterfaceArrival: unable to allocate UsbSidebandWorkTask, out of memory"));
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
goto Done;
}
// usbWorkTask->L.Size is set to sizeof(UsbSidebandWorkTask) in the Look Aside List configuration
#pragma warning(suppress: 6386)
RtlZeroMemory(usbHsWorkTask, sizeof(*usbHsWorkTask));
usbHsWorkTask->Action = eUsbHsTaskStart;
InitializeListHead(&usbHsWorkTask->ListEntry);
// Note that usbDevice has one reference at this point.
usbHsWorkTask->Device = usbHsDevice;
ExAcquireFastMutex(&m_UsbSidebandFastMutex);
//
// Insert this new USB Sideband device in our list.
//
InsertTailList(&m_UsbSidebandDevices, usbHsDevice->GetListEntry());
//
// Add a new task for the worker thread.
//
InsertTailList(&m_UsbSidebandWorkTasks, &usbHsWorkTask->ListEntry);
usbHsDevice->AddRef(); // released when task runs.
//
// Schedule a work-item if not already running.
//
WdfWorkItemEnqueue(m_UsbSidebandWorkItem);
ExReleaseFastMutex(&m_UsbSidebandFastMutex);
Done:
if (!NT_SUCCESS(ntStatus))
{
// Release the last ref, this will delete the UsbSidebandDevice
SAFE_RELEASE(usbHsDevice);
if (usbHsWorkTask != NULL)
{
ExFreeToNPagedLookasideList(&m_UsbSidebandWorkTaskPool, usbHsWorkTask);
usbHsWorkTask = NULL;
}
}
return ntStatus;
}
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS
CAdapterCommon::UsbSidebandInterfaceRemoval
(
_In_ PUNICODE_STRING SymbolicLinkName
)
/*++
Routine Description:
The function handles the removal of a USB Sideband interface.
Arguments:
SymbolicLinkName - interface's symbolic link to remove.
Return Value:
NT status code.
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::UsbSidebandInterfaceRemoval]"));
NTSTATUS ntStatus = STATUS_SUCCESS;
UsbHsDevice *usbHsDevice = NULL;
UsbHsWorkTask *usbHsWorkTask = NULL;
DPF(D_VERBOSE, ("UsbSidebandInterfaceRemoval: SymbolicLinkName %wZ", SymbolicLinkName));
//
// Check if the USB device is present.
//
usbHsDevice = UsbSidebandDeviceFind(SymbolicLinkName);
if (usbHsDevice == NULL)
{
// This can happen if the init/start of the UsbSidebandDevice failed.
DPF(D_VERBOSE, ("UsbSidebandInterfaceRemoval: USB device not found"));
ntStatus = STATUS_SUCCESS;
goto Done;
}
//
// Init a work task.
//
usbHsWorkTask = (UsbHsWorkTask*)ExAllocateFromNPagedLookasideList(&m_UsbSidebandWorkTaskPool);
if (NULL == usbHsWorkTask)
{
DPF(D_ERROR, ("UsbSidebandInterfaceRemoval: unable to allocate UsbSidebandWorkTask, out of memory"));
ntStatus = STATUS_INSUFFICIENT_RESOURCES;
goto Done;
}
// usbWorkTask->L.Size is set to sizeof(UsbSidebandWorkTask) in the Look Aside List configuration
#pragma warning(suppress: 6386)
RtlZeroMemory(usbHsWorkTask, sizeof(*usbHsWorkTask));
usbHsWorkTask->Action = eUsbHsTaskStop;
InitializeListHead(&usbHsWorkTask->ListEntry);
// Work-item callback will release the reference we got above from UsbSidebandDeviceFind.
usbHsWorkTask->Device = usbHsDevice;
ExAcquireFastMutex(&m_UsbSidebandFastMutex);
//
// Remove this USB device from our list and release the associated reference.
//
RemoveEntryList(usbHsDevice->GetListEntry());
InitializeListHead(usbHsDevice->GetListEntry());
usbHsDevice->Release(); // This is not the last ref.
//
// Add a new task for the worker thread.
//
InsertTailList(&m_UsbSidebandWorkTasks, &usbHsWorkTask->ListEntry);
//
// Schedule a work-item if not already running.
//
WdfWorkItemEnqueue(m_UsbSidebandWorkItem);
ExReleaseFastMutex(&m_UsbSidebandFastMutex);
//
// All done.
//
ntStatus = STATUS_SUCCESS;
Done:
if (!NT_SUCCESS(ntStatus))
{
// Release the ref we got in find.
SAFE_RELEASE(usbHsDevice);
}
return ntStatus;
}
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS
CAdapterCommon::EvtUsbSidebandInterfaceChange(
_In_ PVOID NotificationPointer,
_Inout_opt_ PVOID Context
)
/*++
Routine Description:
This callback is invoked when a new USB Sideband interface is added or removed.
Arguments:
NotificationPointer - Interface change notification
Context - CAdapterCommon ptr.
Return Value:
NT status code.
--*/
{
PAGED_CODE();
DPF_ENTER(("[EvtUsbSidebandInterfaceChange]"));
NTSTATUS ntStatus = STATUS_SUCCESS;
CAdapterCommon * This = NULL;
PDEVICE_INTERFACE_CHANGE_NOTIFICATION Notification = (PDEVICE_INTERFACE_CHANGE_NOTIFICATION)NotificationPointer;
//
// Make sure this is the interface class we extect. Any other class guid
// is an error, but let it go since it is not fatal to the machine.
//
if (!IsEqualGUID(Notification->InterfaceClassGuid, GUID_DEVINTERFACE_USB_SIDEBAND_AUDIO_HS_HCIBYPASS))
{
DPF(D_VERBOSE, ("EvtUsbSidebandInterfaceChange: bad interface ClassGuid"));
ASSERTMSG("EvtUsbSidebandInterfaceChange: bad interface ClassGuid ", FALSE);
goto Done;
}
This = (CAdapterCommon *)Context;
ASSERT(This != NULL);
_Analysis_assume_(This != NULL);
//
// Take action based on the event. Any other event type is an error,
// but let it go since it is not fatal to the machine.
//
if (IsEqualGUID(Notification->Event, GUID_DEVICE_INTERFACE_ARRIVAL))
{
ntStatus = This->UsbSidebandInterfaceArrival(Notification->SymbolicLinkName);
}
else if (IsEqualGUID(Notification->Event, GUID_DEVICE_INTERFACE_REMOVAL))
{
ntStatus = This->UsbSidebandInterfaceRemoval(Notification->SymbolicLinkName);
}
else
{
DPF(D_VERBOSE, ("EvtUsbSidebandInterfaceChange: bad "
"GUID_DEVINTERFACE_USB_SIDEBAND_AUDIO_HCIBYPASS event"));
ASSERTMSG("EvtUsbSidebandInterfaceChange: bad "
"GUID_DEVINTERFACE_USB_SIDEBAND_AUDIO_HCIBYPASS event ", FALSE);
goto Done;
}
Done:
return ntStatus;
}
//=============================================================================
#pragma code_seg("PAGE")
NTSTATUS
CAdapterCommon::InitUsbSideband()
/*++
Routine Description:
Initialize the USB Sideband environment.
Return Value:
NT status code.
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::InitUsbSideband]"));
NTSTATUS ntStatus = STATUS_SUCCESS;
WDF_WORKITEM_CONFIG wiConfig;
WDF_OBJECT_ATTRIBUTES attributes;
UsbHsWorkItemContext * wiContext;
//
// Init spin-lock, linked lists, work-item, event, etc.
// Init all members to default values. This basic init should not fail.
//
m_UsbSidebandWorkItem = NULL;
m_UsbSidebandNotificationHandle = NULL;
ExInitializeFastMutex(&m_UsbSidebandFastMutex);
InitializeListHead(&m_UsbSidebandWorkTasks);
InitializeListHead(&m_UsbSidebandDevices);
m_UsbSidebandWorkTaskPoolElementSize = sizeof(UsbHsWorkTask);
ExInitializeNPagedLookasideList(&m_UsbSidebandWorkTaskPool,
NULL,
NULL,
POOL_NX_ALLOCATION,
m_UsbSidebandWorkTaskPoolElementSize,
MINADAPTER_POOLTAG,
0);
//
// Enable USB Sideband Cleanup.
// Do any allocation/initialization that can fail after this point.
//
m_UsbSidebandEnableCleanup = TRUE;
//
// Allocate a WDF work-item.
//
WDF_WORKITEM_CONFIG_INIT(&wiConfig, EvtUsbSidebandInterfaceWorkItem);
wiConfig.AutomaticSerialization = FALSE;
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes, UsbHsWorkItemContext);
attributes.ParentObject = GetWdfDevice();
ntStatus = WdfWorkItemCreate(&wiConfig,
&attributes,
&m_UsbSidebandWorkItem);
IF_FAILED_ACTION_JUMP(
ntStatus,
DPF(D_ERROR, ("InitUsbSideband: WdfWorkItemCreate failed: 0x%x", ntStatus)),
Done);
wiContext = GetUsbHsWorkItemContext(m_UsbSidebandWorkItem);
wiContext->Adapter = this; // weak ref.
//
// Register for USB Sideband interface changes.
//
ntStatus = IoRegisterPlugPlayNotification(
EventCategoryDeviceInterfaceChange,
PNPNOTIFY_DEVICE_INTERFACE_INCLUDE_EXISTING_INTERFACES,
(PVOID)&GUID_DEVINTERFACE_USB_SIDEBAND_AUDIO_HS_HCIBYPASS,
m_pDeviceObject->DriverObject,
EvtUsbSidebandInterfaceChange,
(PVOID)this,
&m_UsbSidebandNotificationHandle);
IF_FAILED_ACTION_JUMP(
ntStatus,
DPF(D_ERROR, ("InitUsbSideband: IoRegisterPlugPlayNotification(GUID_DEVINTERFACE_USB_SIDEBAND_AUDIO_HCIBYPASS) failed: 0x%x", ntStatus)),
Done);
//
// Initialization completed.
//
ntStatus = STATUS_SUCCESS;
Done:
return ntStatus;
}
//=============================================================================
#pragma code_seg()
NTSTATUS
CAdapterCommon::AddDeviceAsPowerDependency
(
_In_ PDEVICE_OBJECT pdo
)
{
NTSTATUS status = STATUS_SUCCESS;
// allocate SysVadPowerRelationsDo
PSysVadPowerRelationsDo powerDepDo = (PSysVadPowerRelationsDo)ExAllocatePoolWithTag(NonPagedPoolNx, sizeof(SysVadPowerRelationsDo), USBSIDEBANDTEST_POOLTAG014);
if (NULL == powerDepDo)
{
status = STATUS_INSUFFICIENT_RESOURCES;
DPF(D_ERROR, ("CAdapterCommon::AddDeviceAsPowerDependency could not allocate memory for list entry"));
goto exit;
}
InitializeListHead(&powerDepDo->ListEntry);
powerDepDo->Pdo = pdo;
ObReferenceObject(pdo);
// Add to list
ExAcquireFastMutex(&m_PowerRelationsLock);
InsertTailList(&m_PowerRelations, &powerDepDo->ListEntry);
ExReleaseFastMutex(&m_PowerRelationsLock);
IoInvalidateDeviceRelations(m_pPhysicalDeviceObject, PowerRelations);
exit:
return status;
}
//=============================================================================
#pragma code_seg()
NTSTATUS
CAdapterCommon::RemoveDeviceAsPowerDependency
(
_In_ PDEVICE_OBJECT pdo
)
{
NTSTATUS status = STATUS_SUCCESS;
// Find in list
ExAcquireFastMutex(&m_PowerRelationsLock);
PLIST_ENTRY pe = m_PowerRelations.Flink;
while (pe != &m_PowerRelations)
{
PSysVadPowerRelationsDo powerDepDo = CONTAINING_RECORD(pe, SysVadPowerRelationsDo, ListEntry);
pe = pe->Flink;
if (powerDepDo->Pdo == pdo)
{
ObDereferenceObject(powerDepDo->Pdo);
RemoveEntryList(&powerDepDo->ListEntry);
ExFreePoolWithTag(powerDepDo, USBSIDEBANDTEST_POOLTAG014);
}
}
ExReleaseFastMutex(&m_PowerRelationsLock);
IoInvalidateDeviceRelations(m_pPhysicalDeviceObject, PowerRelations);
return status;
}
//=============================================================================
#pragma code_seg("PAGE")
VOID
CAdapterCommon::CleanupUsbSideband()
/*++
Routine Description:
Cleanup the USB Sideband environment.
--*/
{
PAGED_CODE();
DPF_ENTER(("[CAdapterCommon::CleanupUsbSideband]"));
//
// Do nothing if USB Sideband environment was not correctly initialized.
//
if (m_UsbSidebandEnableCleanup == FALSE)
{
return;
}
//
// Unregister for USB Sideband interface changes.
//
if (m_UsbSidebandNotificationHandle != NULL)
{
(void)IoUnregisterPlugPlayNotificationEx(m_UsbSidebandNotificationHandle);
m_UsbSidebandNotificationHandle = NULL;
}
//
// Wait for the USB Sideband worker thread to be done.
//
if (m_UsbSidebandWorkItem != NULL)
{
WdfWorkItemFlush(m_UsbSidebandWorkItem);
WdfObjectDelete(m_UsbSidebandWorkItem);
m_UsbSidebandWorkItem = NULL;
}
ASSERT(IsListEmpty(&m_UsbSidebandWorkTasks));
//
// Stop and delete all UsbSidebandDevices. We are the only thread accessing this list,
// so there is no need to acquire the mutex.
//
while (!IsListEmpty(&m_UsbSidebandDevices))
{
UsbHsDevice * usbHsDevice = NULL;
PLIST_ENTRY le = NULL;
le = RemoveHeadList(&m_UsbSidebandDevices);
usbHsDevice = UsbHsDevice::GetUsbHsDevice(le);
InitializeListHead(le);
// usbDevice is invalid after this call.
usbHsDevice->Stop();
// This should be the last reference.
usbHsDevice->Release();
}
ASSERT(IsListEmpty(&m_UsbSidebandDevices));
//
// General cleanup.
//
ExDeleteNPagedLookasideList(&m_UsbSidebandWorkTaskPool);
}
#endif // SYSVAD_USB_SIDEBAND
#pragma code_seg("PAGE")
NTSTATUS
CopyRegistryValues(HANDLE _hSourceKey, HANDLE _hDestinationKey)
/*++
Routine Description:
This method copies the registry values in _hSourceKey to _hDestinationKey.
Return Value:
NT status code.
--*/
{
NTSTATUS ntStatus = STATUS_SUCCESS;
PKEY_VALUE_FULL_INFORMATION kvFullInfo = NULL;
ULONG ulFullInfoLength = 0;
ULONG ulFullInfoResultLength = 0;
PWSTR pwstrKeyValueName = NULL;
UNICODE_STRING strKeyValueName;
PAGED_CODE();
// Allocate the KEY_VALUE_FULL_INFORMATION structure
ulFullInfoLength = sizeof(KEY_VALUE_FULL_INFORMATION) + MAX_DEVICE_REG_KEY_LENGTH;
kvFullInfo = (PKEY_VALUE_FULL_INFORMATION)ExAllocatePoolWithTag(NonPagedPoolNx, ulFullInfoLength, MINADAPTER_POOLTAG);
IF_TRUE_ACTION_JUMP(kvFullInfo == NULL, ntStatus = STATUS_INSUFFICIENT_RESOURCES, Exit);
// Iterate over each value and copy it to the destination
for (UINT i = 0; NT_SUCCESS(ntStatus); i++)
{
// Enumerate the next value
ntStatus = ZwEnumerateValueKey(_hSourceKey, i, KeyValueFullInformation, kvFullInfo, ulFullInfoLength, &ulFullInfoResultLength);
// Jump out of this loop if there are no more values
IF_TRUE_ACTION_JUMP(ntStatus == STATUS_NO_MORE_ENTRIES, ntStatus = STATUS_SUCCESS, Exit);
// Handle incorrect buffer size
if (ntStatus == STATUS_BUFFER_TOO_SMALL || ntStatus == STATUS_BUFFER_OVERFLOW)
{
// Free and re-allocate the KEY_VALUE_FULL_INFORMATION structure with the correct size
ExFreePoolWithTag(kvFullInfo, MINADAPTER_POOLTAG);
ulFullInfoLength = ulFullInfoResultLength;
kvFullInfo = (PKEY_VALUE_FULL_INFORMATION)ExAllocatePoolWithTag(NonPagedPoolNx, ulFullInfoLength, MINADAPTER_POOLTAG);
IF_TRUE_ACTION_JUMP(kvFullInfo == NULL, ntStatus = STATUS_INSUFFICIENT_RESOURCES, loop_exit);
// Try to enumerate the current value again
ntStatus = ZwEnumerateValueKey(_hSourceKey, i, KeyValueFullInformation, kvFullInfo, ulFullInfoLength, &ulFullInfoResultLength);
// Jump out of this loop if there are no more values
IF_TRUE_ACTION_JUMP(ntStatus == STATUS_NO_MORE_ENTRIES, ntStatus = STATUS_SUCCESS, Exit);
IF_FAILED_JUMP(ntStatus, loop_exit);
}
else
{
IF_FAILED_JUMP(ntStatus, loop_exit);
}
// Allocate the key value name string
pwstrKeyValueName = (PWSTR)ExAllocatePoolWithTag(NonPagedPoolNx, kvFullInfo->NameLength + sizeof(WCHAR)*2, MINADAPTER_POOLTAG);
IF_TRUE_ACTION_JUMP(kvFullInfo == NULL, ntStatus = STATUS_INSUFFICIENT_RESOURCES, loop_exit);
// Copy the key value name from the full information struct
RtlStringCbCopyNW(pwstrKeyValueName, kvFullInfo->NameLength + sizeof(WCHAR)*2, kvFullInfo->Name, kvFullInfo->NameLength);
// Make sure the string is null terminated
pwstrKeyValueName[(kvFullInfo->NameLength) / sizeof(WCHAR)] = 0;
// Copy the key value name string to a UNICODE string
RtlInitUnicodeString(&strKeyValueName, pwstrKeyValueName);
// Write the key value from the source into the destination
ntStatus = ZwSetValueKey(_hDestinationKey, &strKeyValueName, 0, kvFullInfo->Type, (PVOID)((PUCHAR)kvFullInfo + kvFullInfo->DataOffset), kvFullInfo->DataLength);
IF_FAILED_JUMP(ntStatus, loop_exit);
loop_exit:
// Free the key value name string
if (pwstrKeyValueName)
{
ExFreePoolWithTag(pwstrKeyValueName, MINADAPTER_POOLTAG);
}
// Bail if anything failed
IF_FAILED_JUMP(ntStatus, Exit);
}
Exit:
// Free the KEY_VALUE_FULL_INFORMATION structure
if (kvFullInfo)
{
ExFreePoolWithTag(kvFullInfo, MINADAPTER_POOLTAG);
}
return ntStatus;
}
NTSTATUS
CopyRegistryKey(HANDLE _hSourceKey, HANDLE _hDestinationKey, BOOL _bOverwrite = FALSE)
/*++
Routine Description:
This method recursively copies the registry values in _hSourceKey to _hDestinationKey.
Set _bOverwrite to indicate whether the first level values are copied or not.
Normal use is to set false for the initial call, and then all sub paths will be copied.
Return Value:
NT status code.
--*/
{
NTSTATUS ntStatus = STATUS_UNSUCCESSFUL;
PKEY_BASIC_INFORMATION kBasicInfo = NULL;
ULONG ulBasicInfoLength = 0;
ULONG ulBasicInfoResultLength = 0;
ULONG ulDisposition = 0;
PWSTR pwstrKeyName = NULL;
UNICODE_STRING strKeyName;
OBJECT_ATTRIBUTES hCurrentSourceKeyAttributes;
OBJECT_ATTRIBUTES hNewDestinationKeyAttributes;
HANDLE hCurrentSourceKey = NULL;
HANDLE hNewDestinationKey = NULL;
PAGED_CODE();
// Validate parameters
IF_TRUE_ACTION_JUMP(_hSourceKey == nullptr, ntStatus = STATUS_INVALID_PARAMETER, Exit);
IF_TRUE_ACTION_JUMP(_hDestinationKey == nullptr, ntStatus = STATUS_INVALID_PARAMETER, Exit);
// Allocate the KEY_BASIC_INFORMATION structure
ulBasicInfoLength = sizeof(KEY_BASIC_INFORMATION) + MAX_DEVICE_REG_KEY_LENGTH;
kBasicInfo = (PKEY_BASIC_INFORMATION)ExAllocatePoolWithTag(NonPagedPoolNx, ulBasicInfoLength, MINADAPTER_POOLTAG);
IF_TRUE_ACTION_JUMP(kBasicInfo == NULL, ntStatus = STATUS_INSUFFICIENT_RESOURCES, Exit);
ntStatus = STATUS_SUCCESS;
// Iterate over each key and copy it
for (UINT i = 0; NT_SUCCESS(ntStatus); i++)
{
// Enumerate the next key
ntStatus = ZwEnumerateKey(_hSourceKey, i, KeyBasicInformation, kBasicInfo, ulBasicInfoLength, &ulBasicInfoResultLength);
// Jump out of this loop if there are no more keys
IF_TRUE_ACTION_JUMP(ntStatus == STATUS_NO_MORE_ENTRIES, ntStatus = STATUS_SUCCESS, copy_values);
// Handle incorrect buffer size
if (ntStatus == STATUS_BUFFER_TOO_SMALL || ntStatus == STATUS_BUFFER_OVERFLOW)
{
// Free and re-allocate the KEY_BASIC_INFORMATION structure with the correct size.
ExFreePoolWithTag(kBasicInfo, MINADAPTER_POOLTAG);
ulBasicInfoLength = ulBasicInfoResultLength;
kBasicInfo = (PKEY_BASIC_INFORMATION)ExAllocatePoolWithTag(NonPagedPoolNx, ulBasicInfoLength, MINADAPTER_POOLTAG);
IF_TRUE_ACTION_JUMP(kBasicInfo == NULL, ntStatus = STATUS_INSUFFICIENT_RESOURCES, loop_exit);
// Try to enumerate the current key again.
ntStatus = ZwEnumerateKey(_hSourceKey, i, KeyBasicInformation, kBasicInfo, ulBasicInfoLength, &ulBasicInfoResultLength);
// Jump out of this loop if there are no more keys
IF_TRUE_ACTION_JUMP(ntStatus == STATUS_NO_MORE_ENTRIES, ntStatus = STATUS_SUCCESS, copy_values);
IF_FAILED_JUMP(ntStatus, loop_exit);
}
else
{
IF_FAILED_JUMP(ntStatus, loop_exit);
}
// Allocate the key name string
pwstrKeyName = (PWSTR)ExAllocatePoolWithTag(NonPagedPoolNx, kBasicInfo->NameLength + sizeof(WCHAR), MINADAPTER_POOLTAG);
IF_TRUE_ACTION_JUMP(kBasicInfo == NULL, ntStatus = STATUS_INSUFFICIENT_RESOURCES, loop_exit);
// Copy the key name from the basic information struct
RtlStringCbCopyNW(pwstrKeyName, kBasicInfo->NameLength + sizeof(WCHAR), kBasicInfo->Name, kBasicInfo->NameLength);
// Make sure the string is null terminated
pwstrKeyName[(kBasicInfo->NameLength) / sizeof(WCHAR)] = 0;
// Copy the key name string to a UNICODE string
RtlInitUnicodeString(&strKeyName, pwstrKeyName);
// Initialize attributes to open the currently enumerated source key
InitializeObjectAttributes(&hCurrentSourceKeyAttributes, &strKeyName, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, _hSourceKey, NULL);
// Open the currently enumerated source key
ntStatus = ZwOpenKey(&hCurrentSourceKey, KEY_READ, &hCurrentSourceKeyAttributes);
IF_FAILED_ACTION_JUMP(ntStatus, ZwClose(hCurrentSourceKey), loop_exit);
// Initialize attributes to create the new destination key
InitializeObjectAttributes(&hNewDestinationKeyAttributes, &strKeyName, OBJ_KERNEL_HANDLE, _hDestinationKey, NULL);
// Create the key at the destination
ntStatus = ZwCreateKey(&hNewDestinationKey, KEY_WRITE, &hNewDestinationKeyAttributes, 0, NULL, REG_OPTION_NON_VOLATILE, &ulDisposition);
IF_FAILED_ACTION_JUMP(ntStatus, ZwClose(hCurrentSourceKey), loop_exit);
// Now copy the contents of the currently enumerated key to the destination
ntStatus = CopyRegistryKey(hCurrentSourceKey, hNewDestinationKey, TRUE);
IF_FAILED_JUMP(ntStatus, loop_exit);
loop_exit:
// Free the key name string
if (pwstrKeyName)
{
ExFreePoolWithTag(pwstrKeyName, MINADAPTER_POOLTAG);
}
// Close the current source key
if (hCurrentSourceKey)
{
ZwClose(hCurrentSourceKey);
}
// Close the new destination key
if (hNewDestinationKey)
{
ZwClose(hNewDestinationKey);
}
// Bail if anything failed
IF_FAILED_JUMP(ntStatus, Exit);
}
copy_values:
// Copy the values
if (_bOverwrite)
{
ntStatus = CopyRegistryValues(_hSourceKey, _hDestinationKey);
IF_FAILED_JUMP(ntStatus, Exit);
}
Exit:
// Free the basic information structure
if (kBasicInfo)
{
ExFreePoolWithTag(kBasicInfo, MINADAPTER_POOLTAG);
}
return ntStatus;
}
NTSTATUS CAdapterCommon::MigrateDeviceInterfaceTemplateParameters
(
_In_ PUNICODE_STRING SymbolicLinkName,
_In_opt_ PCWSTR TemplateReferenceString
)
/*++
Routine Description:
This method copies all of the properties from the template interface,
which is specified in the inf, to the actual interface being used which
may be dynamically generated at run time. This allows for a driver
to reuse a single inf entry for multiple audio endpoints. The primary
purpose for this is to allow for sideband audio endpoints to dynamically
generate the reference string at run time, tied to the peripheral connected,
while still having a simple static inf entry for setting up apo's or other
parameters.
For example, if you have an interface in your inf defined with reference string
"SpeakerWave". At runtime you could generate "SpeakerWave-1234ABCDE", and specify
"SpeakerWave" as the template name. When "SpeakerWave-1234ABCDE" is installed
we will copy all of the parameters that were specified in the inf for "SpeakerWave"
over to "SpeakerWave-1234ABCDE". You simply need to specify "SpeakerWave" as the
"TemplateName" in the ENDPOINT_MINIPAIRS.
By default, the first level of registry keys are not copied. Only the 2nd level and
deeper are copied. This way the friendly name and other PNP properties will not
be modified, but the EP and FX properties will be copied.
Return Value:
NT status code.
--*/
{
NTSTATUS ntStatus = STATUS_SUCCESS;
HANDLE hDeviceInterfaceParametersKey(NULL);
HANDLE hTemplateDeviceInterfaceParametersKey(NULL);
UNICODE_STRING TemplateSymbolicLinkName;
UNICODE_STRING referenceString;
RtlInitUnicodeString(&TemplateSymbolicLinkName, NULL);
RtlInitUnicodeString(&referenceString, TemplateReferenceString);
//
// Register an audio interface if not already present for the template interface, so we can access
// the registry path. If it's already registered, this simply returns the symbolic link name.
// No need to unregister it (there is no mechanism to), and we'll never make it active.
//
ntStatus = IoRegisterDeviceInterface(
GetPhysicalDeviceObject(),
&KSCATEGORY_AUDIO,
&referenceString,
&TemplateSymbolicLinkName);
// Open the template device interface's registry key path
ntStatus = IoOpenDeviceInterfaceRegistryKey(&TemplateSymbolicLinkName, GENERIC_READ, &hTemplateDeviceInterfaceParametersKey);
IF_FAILED_JUMP(ntStatus, Exit);
// Open the new device interface's registry key path that we plan to activate
ntStatus = IoOpenDeviceInterfaceRegistryKey(SymbolicLinkName, GENERIC_WRITE, &hDeviceInterfaceParametersKey);
IF_FAILED_JUMP(ntStatus, Exit);
// Copy the template device parameters key to the device interface key
ntStatus = CopyRegistryKey(hTemplateDeviceInterfaceParametersKey, hDeviceInterfaceParametersKey);
IF_FAILED_JUMP(ntStatus, Exit);
Exit:
RtlFreeUnicodeString(&TemplateSymbolicLinkName);
if (hTemplateDeviceInterfaceParametersKey)
{
ZwClose(hTemplateDeviceInterfaceParametersKey);
}
if (hDeviceInterfaceParametersKey)
{
ZwClose(hDeviceInterfaceParametersKey);
}
return ntStatus;
}
#pragma code_seg("PAGE")
STDMETHODIMP_(NTSTATUS)
CAdapterCommon::NotifyEndpointPair
(
_In_ WCHAR *RenderEndpointTopoName,
_In_ ULONG RenderEndpointNameLen,
_In_ ULONG RenderPinId,
_In_ WCHAR *CaptureEndpointTopoName,
_In_ ULONG CaptureEndpointNameLen,
_In_ ULONG CapturePinId
)
{
NTSTATUS ntStatus = STATUS_SUCCESS;
PAGED_CODE ();
PLIST_ENTRY le = NULL;
BOOL bRemoved = FALSE;
// notify each subdevice which implements IMiniportChange
for (le = m_SubdeviceCache.Flink; le != &m_SubdeviceCache && !bRemoved; le = le->Flink)
{
MINIPAIR_UNKNOWN *pRecord = CONTAINING_RECORD(le, MINIPAIR_UNKNOWN, ListEntry);
if(pRecord->MiniportChange)
{
pRecord->MiniportChange->NotifyEndpointPair(
RenderEndpointTopoName,
RenderEndpointNameLen,
RenderPinId,
CaptureEndpointTopoName,
CaptureEndpointNameLen,
CapturePinId
);
}
}
return ntStatus;
}
|