summaryrefslogtreecommitdiff
path: root/drivers/hid/hid-nintendo.c
blob: 4d40f67f3e640155296351e51b736d9f6cf6b414 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
// SPDX-License-Identifier: GPL-2.0+
/*
 * HID driver for Nintendo Switch Joy-Cons and Pro Controllers, as well as
 * Nintendo Switch 2 Joy-Cons, Pro Controller, and GameCube Controller
 *
 * Copyright (c) 2019-2021 Daniel J. Ogorchock <djogorchock@gmail.com>
 * Portions Copyright (c) 2020 Nadia Holmquist Pedersen <nadia@nhp.sh>
 * Copyright (c) 2022 Emily Strickland <linux@emily.st>
 * Copyright (c) 2023 Ryan McClelland <rymcclel@gmail.com>
 * Copyright (c) 2026 Valve Software
 *
 * The following resources/projects were referenced for this driver:
 *   https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering
 *   https://gitlab.com/pjranki/joycon-linux-kernel (Peter Rankin)
 *   https://github.com/FrotBot/SwitchProConLinuxUSB
 *   https://github.com/MTCKC/ProconXInput
 *   https://github.com/Davidobot/BetterJoyForCemu
 *   https://gist.github.com/shinyquagsire23/66f006b46c56216acbaac6c1e2279b64
 *   https://github.com/ndeadly/switch2_controller_research
 *   hid-wiimote kernel hid driver
 *   hid-logitech-hidpp driver
 *   hid-sony driver
 *
 * This driver supports the Nintendo Switch Joy-Cons and Pro Controllers. The
 * Pro Controllers can either be used over USB or Bluetooth.
 *
 * This driver also incorporates support for Nintendo Switch Online controllers
 * for the NES, SNES, Sega Genesis, and N64.
 *
 * The driver will retrieve the factory calibration info from the controllers,
 * so little to no user calibration should be required.
 *
 */

#include "hid-ids.h"
#include "hid-nintendo.h"
#include <linux/unaligned.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/devm-helpers.h>
#include <linux/kernel.h>
#include <linux/hid.h>
#include <linux/idr.h>
#include <linux/input.h>
#include <linux/jiffies.h>
#include <linux/leds.h>
#include <linux/module.h>
#include <linux/power_supply.h>
#include <linux/spinlock.h>
#include <linux/usb.h>
#include "usbhid/usbhid.h"

/*
 * Reference the url below for the following HID report defines:
 * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering
 */

/* Output Reports */
#define JC_OUTPUT_RUMBLE_AND_SUBCMD	 0x01
#define JC_OUTPUT_FW_UPDATE_PKT		 0x03
#define JC_OUTPUT_RUMBLE_ONLY		 0x10
#define JC_OUTPUT_MCU_DATA		 0x11
#define JC_OUTPUT_USB_CMD		 0x80

/* Subcommand IDs */
#define JC_SUBCMD_STATE			 0x00
#define JC_SUBCMD_MANUAL_BT_PAIRING	 0x01
#define JC_SUBCMD_REQ_DEV_INFO		 0x02
#define JC_SUBCMD_SET_REPORT_MODE	 0x03
#define JC_SUBCMD_TRIGGERS_ELAPSED	 0x04
#define JC_SUBCMD_GET_PAGE_LIST_STATE	 0x05
#define JC_SUBCMD_SET_HCI_STATE		 0x06
#define JC_SUBCMD_RESET_PAIRING_INFO	 0x07
#define JC_SUBCMD_LOW_POWER_MODE	 0x08
#define JC_SUBCMD_SPI_FLASH_READ	 0x10
#define JC_SUBCMD_SPI_FLASH_WRITE	 0x11
#define JC_SUBCMD_RESET_MCU		 0x20
#define JC_SUBCMD_SET_MCU_CONFIG	 0x21
#define JC_SUBCMD_SET_MCU_STATE		 0x22
#define JC_SUBCMD_SET_PLAYER_LIGHTS	 0x30
#define JC_SUBCMD_GET_PLAYER_LIGHTS	 0x31
#define JC_SUBCMD_SET_HOME_LIGHT	 0x38
#define JC_SUBCMD_ENABLE_IMU		 0x40
#define JC_SUBCMD_SET_IMU_SENSITIVITY	 0x41
#define JC_SUBCMD_WRITE_IMU_REG		 0x42
#define JC_SUBCMD_READ_IMU_REG		 0x43
#define JC_SUBCMD_ENABLE_VIBRATION	 0x48
#define JC_SUBCMD_GET_REGULATED_VOLTAGE	 0x50

/* Input Reports */
#define JC_INPUT_BUTTON_EVENT		 0x3F
#define JC_INPUT_SUBCMD_REPLY		 0x21
#define JC_INPUT_IMU_DATA		 0x30
#define JC_INPUT_MCU_DATA		 0x31
#define JC_INPUT_USB_RESPONSE		 0x81

/* Feature Reports */
#define JC_FEATURE_LAST_SUBCMD		 0x02
#define JC_FEATURE_OTA_FW_UPGRADE	 0x70
#define JC_FEATURE_SETUP_MEM_READ	 0x71
#define JC_FEATURE_MEM_READ		 0x72
#define JC_FEATURE_ERASE_MEM_SECTOR	 0x73
#define JC_FEATURE_MEM_WRITE		 0x74
#define JC_FEATURE_LAUNCH		 0x75

/* USB Commands */
#define JC_USB_CMD_CONN_STATUS		 0x01
#define JC_USB_CMD_HANDSHAKE		 0x02
#define JC_USB_CMD_BAUDRATE_3M		 0x03
#define JC_USB_CMD_NO_TIMEOUT		 0x04
#define JC_USB_CMD_EN_TIMEOUT		 0x05
#define JC_USB_RESET			 0x06
#define JC_USB_PRE_HANDSHAKE		 0x91
#define JC_USB_SEND_UART		 0x92

/* Magic value denoting presence of user calibration */
#define JC_CAL_USR_MAGIC_0		 0xB2
#define JC_CAL_USR_MAGIC_1		 0xA1
#define JC_CAL_USR_MAGIC_SIZE		 2

/* SPI storage addresses of user calibration data */
#define JC_CAL_USR_LEFT_MAGIC_ADDR	 0x8010
#define JC_CAL_USR_LEFT_DATA_ADDR	 0x8012
#define JC_CAL_USR_LEFT_DATA_END	 0x801A
#define JC_CAL_USR_RIGHT_MAGIC_ADDR	 0x801B
#define JC_CAL_USR_RIGHT_DATA_ADDR	 0x801D
#define JC_CAL_STICK_DATA_SIZE \
	(JC_CAL_USR_LEFT_DATA_END - JC_CAL_USR_LEFT_DATA_ADDR + 1)

/* SPI storage addresses of factory calibration data */
#define JC_CAL_FCT_DATA_LEFT_ADDR	 0x603d
#define JC_CAL_FCT_DATA_RIGHT_ADDR	 0x6046

/* SPI storage addresses of IMU factory calibration data */
#define JC_IMU_CAL_FCT_DATA_ADDR	 0x6020
#define JC_IMU_CAL_FCT_DATA_END	 0x6037
#define JC_IMU_CAL_DATA_SIZE \
	(JC_IMU_CAL_FCT_DATA_END - JC_IMU_CAL_FCT_DATA_ADDR + 1)
/* SPI storage addresses of IMU user calibration data */
#define JC_IMU_CAL_USR_MAGIC_ADDR	 0x8026
#define JC_IMU_CAL_USR_DATA_ADDR	 0x8028

/* The raw analog joystick values will be mapped in terms of this magnitude */
#define JC_MAX_STICK_MAG		 32767
#define JC_STICK_FUZZ			 250
#define JC_STICK_FLAT			 500

/* Hat values for pro controller's d-pad */
#define JC_MAX_DPAD_MAG		1
#define JC_DPAD_FUZZ		0
#define JC_DPAD_FLAT		0

/* Under most circumstances IMU reports are pushed every 15ms; use as default */
#define JC_IMU_DFLT_AVG_DELTA_MS	15
/* How many samples to sum before calculating average IMU report delta */
#define JC_IMU_SAMPLES_PER_DELTA_AVG	300
/* Controls how many dropped IMU packets at once trigger a warning message */
#define JC_IMU_DROPPED_PKT_WARNING	3

/*
 * The controller's accelerometer has a sensor resolution of 16bits and is
 * configured with a range of +-8000 milliGs. Therefore, the resolution can be
 * calculated thus: (2^16-1)/(8000 * 2) = 4.096 digits per milliG
 * Resolution per G (rather than per millliG): 4.096 * 1000 = 4096 digits per G
 * Alternatively: 1/4096 = .0002441 Gs per digit
 */
#define JC_IMU_MAX_ACCEL_MAG		32767
#define JC_IMU_ACCEL_RES_PER_G		4096
#define JC_IMU_ACCEL_FUZZ		10
#define JC_IMU_ACCEL_FLAT		0

/*
 * The controller's gyroscope has a sensor resolution of 16bits and is
 * configured with a range of +-2000 degrees/second.
 * Digits per dps: (2^16 -1)/(2000*2) = 16.38375
 * dps per digit: 16.38375E-1 = .0610
 *
 * STMicro recommends in the datasheet to add 15% to the dps/digit. This allows
 * the full sensitivity range to be saturated without clipping. This yields more
 * accurate results, so it's the technique this driver uses.
 * dps per digit (corrected): .0610 * 1.15 = .0702
 * digits per dps (corrected): .0702E-1 = 14.247
 *
 * Now, 14.247 truncating to 14 loses a lot of precision, so we rescale the
 * min/max range by 1000.
 */
#define JC_IMU_PREC_RANGE_SCALE	1000
/* Note: change mag and res_per_dps if prec_range_scale is ever altered */
#define JC_IMU_MAX_GYRO_MAG		32767000 /* (2^16-1)*1000 */
#define JC_IMU_GYRO_RES_PER_DPS		14247 /* (14.247*1000) */
#define JC_IMU_GYRO_FUZZ		10
#define JC_IMU_GYRO_FLAT		0

/* frequency/amplitude tables for rumble */
struct joycon_rumble_freq_data {
	u16 high;
	u8 low;
	u16 freq; /* Hz*/
};

struct joycon_rumble_amp_data {
	u8 high;
	u16 low;
	u16 amp;
};

#if IS_ENABLED(CONFIG_NINTENDO_FF)
/*
 * These tables are from
 * https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering/blob/master/rumble_data_table.md
 */
static const struct joycon_rumble_freq_data joycon_rumble_frequencies[] = {
	/* high, low, freq */
	{ 0x0000, 0x01,   41 }, { 0x0000, 0x02,   42 }, { 0x0000, 0x03,   43 },
	{ 0x0000, 0x04,   44 }, { 0x0000, 0x05,   45 }, { 0x0000, 0x06,   46 },
	{ 0x0000, 0x07,   47 }, { 0x0000, 0x08,   48 }, { 0x0000, 0x09,   49 },
	{ 0x0000, 0x0A,   50 }, { 0x0000, 0x0B,   51 }, { 0x0000, 0x0C,   52 },
	{ 0x0000, 0x0D,   53 }, { 0x0000, 0x0E,   54 }, { 0x0000, 0x0F,   55 },
	{ 0x0000, 0x10,   57 }, { 0x0000, 0x11,   58 }, { 0x0000, 0x12,   59 },
	{ 0x0000, 0x13,   60 }, { 0x0000, 0x14,   62 }, { 0x0000, 0x15,   63 },
	{ 0x0000, 0x16,   64 }, { 0x0000, 0x17,   66 }, { 0x0000, 0x18,   67 },
	{ 0x0000, 0x19,   69 }, { 0x0000, 0x1A,   70 }, { 0x0000, 0x1B,   72 },
	{ 0x0000, 0x1C,   73 }, { 0x0000, 0x1D,   75 }, { 0x0000, 0x1e,   77 },
	{ 0x0000, 0x1f,   78 }, { 0x0000, 0x20,   80 }, { 0x0400, 0x21,   82 },
	{ 0x0800, 0x22,   84 }, { 0x0c00, 0x23,   85 }, { 0x1000, 0x24,   87 },
	{ 0x1400, 0x25,   89 }, { 0x1800, 0x26,   91 }, { 0x1c00, 0x27,   93 },
	{ 0x2000, 0x28,   95 }, { 0x2400, 0x29,   97 }, { 0x2800, 0x2a,   99 },
	{ 0x2c00, 0x2b,  102 }, { 0x3000, 0x2c,  104 }, { 0x3400, 0x2d,  106 },
	{ 0x3800, 0x2e,  108 }, { 0x3c00, 0x2f,  111 }, { 0x4000, 0x30,  113 },
	{ 0x4400, 0x31,  116 }, { 0x4800, 0x32,  118 }, { 0x4c00, 0x33,  121 },
	{ 0x5000, 0x34,  123 }, { 0x5400, 0x35,  126 }, { 0x5800, 0x36,  129 },
	{ 0x5c00, 0x37,  132 }, { 0x6000, 0x38,  135 }, { 0x6400, 0x39,  137 },
	{ 0x6800, 0x3a,  141 }, { 0x6c00, 0x3b,  144 }, { 0x7000, 0x3c,  147 },
	{ 0x7400, 0x3d,  150 }, { 0x7800, 0x3e,  153 }, { 0x7c00, 0x3f,  157 },
	{ 0x8000, 0x40,  160 }, { 0x8400, 0x41,  164 }, { 0x8800, 0x42,  167 },
	{ 0x8c00, 0x43,  171 }, { 0x9000, 0x44,  174 }, { 0x9400, 0x45,  178 },
	{ 0x9800, 0x46,  182 }, { 0x9c00, 0x47,  186 }, { 0xa000, 0x48,  190 },
	{ 0xa400, 0x49,  194 }, { 0xa800, 0x4a,  199 }, { 0xac00, 0x4b,  203 },
	{ 0xb000, 0x4c,  207 }, { 0xb400, 0x4d,  212 }, { 0xb800, 0x4e,  217 },
	{ 0xbc00, 0x4f,  221 }, { 0xc000, 0x50,  226 }, { 0xc400, 0x51,  231 },
	{ 0xc800, 0x52,  236 }, { 0xcc00, 0x53,  241 }, { 0xd000, 0x54,  247 },
	{ 0xd400, 0x55,  252 }, { 0xd800, 0x56,  258 }, { 0xdc00, 0x57,  263 },
	{ 0xe000, 0x58,  269 }, { 0xe400, 0x59,  275 }, { 0xe800, 0x5a,  281 },
	{ 0xec00, 0x5b,  287 }, { 0xf000, 0x5c,  293 }, { 0xf400, 0x5d,  300 },
	{ 0xf800, 0x5e,  306 }, { 0xfc00, 0x5f,  313 }, { 0x0001, 0x60,  320 },
	{ 0x0401, 0x61,  327 }, { 0x0801, 0x62,  334 }, { 0x0c01, 0x63,  341 },
	{ 0x1001, 0x64,  349 }, { 0x1401, 0x65,  357 }, { 0x1801, 0x66,  364 },
	{ 0x1c01, 0x67,  372 }, { 0x2001, 0x68,  381 }, { 0x2401, 0x69,  389 },
	{ 0x2801, 0x6a,  397 }, { 0x2c01, 0x6b,  406 }, { 0x3001, 0x6c,  415 },
	{ 0x3401, 0x6d,  424 }, { 0x3801, 0x6e,  433 }, { 0x3c01, 0x6f,  443 },
	{ 0x4001, 0x70,  453 }, { 0x4401, 0x71,  462 }, { 0x4801, 0x72,  473 },
	{ 0x4c01, 0x73,  483 }, { 0x5001, 0x74,  494 }, { 0x5401, 0x75,  504 },
	{ 0x5801, 0x76,  515 }, { 0x5c01, 0x77,  527 }, { 0x6001, 0x78,  538 },
	{ 0x6401, 0x79,  550 }, { 0x6801, 0x7a,  562 }, { 0x6c01, 0x7b,  574 },
	{ 0x7001, 0x7c,  587 }, { 0x7401, 0x7d,  600 }, { 0x7801, 0x7e,  613 },
	{ 0x7c01, 0x7f,  626 }, { 0x8001, 0x00,  640 }, { 0x8401, 0x00,  654 },
	{ 0x8801, 0x00,  668 }, { 0x8c01, 0x00,  683 }, { 0x9001, 0x00,  698 },
	{ 0x9401, 0x00,  713 }, { 0x9801, 0x00,  729 }, { 0x9c01, 0x00,  745 },
	{ 0xa001, 0x00,  761 }, { 0xa401, 0x00,  778 }, { 0xa801, 0x00,  795 },
	{ 0xac01, 0x00,  812 }, { 0xb001, 0x00,  830 }, { 0xb401, 0x00,  848 },
	{ 0xb801, 0x00,  867 }, { 0xbc01, 0x00,  886 }, { 0xc001, 0x00,  905 },
	{ 0xc401, 0x00,  925 }, { 0xc801, 0x00,  945 }, { 0xcc01, 0x00,  966 },
	{ 0xd001, 0x00,  987 }, { 0xd401, 0x00, 1009 }, { 0xd801, 0x00, 1031 },
	{ 0xdc01, 0x00, 1053 }, { 0xe001, 0x00, 1076 }, { 0xe401, 0x00, 1100 },
	{ 0xe801, 0x00, 1124 }, { 0xec01, 0x00, 1149 }, { 0xf001, 0x00, 1174 },
	{ 0xf401, 0x00, 1199 }, { 0xf801, 0x00, 1226 }, { 0xfc01, 0x00, 1253 }
};

#define joycon_max_rumble_amp	(1003)
static const struct joycon_rumble_amp_data joycon_rumble_amplitudes[] = {
	/* high, low, amp */
	{ 0x00, 0x0040,    0 },
	{ 0x02, 0x8040,   10 }, { 0x04, 0x0041,   12 }, { 0x06, 0x8041,   14 },
	{ 0x08, 0x0042,   17 }, { 0x0a, 0x8042,   20 }, { 0x0c, 0x0043,   24 },
	{ 0x0e, 0x8043,   28 }, { 0x10, 0x0044,   33 }, { 0x12, 0x8044,   40 },
	{ 0x14, 0x0045,   47 }, { 0x16, 0x8045,   56 }, { 0x18, 0x0046,   67 },
	{ 0x1a, 0x8046,   80 }, { 0x1c, 0x0047,   95 }, { 0x1e, 0x8047,  112 },
	{ 0x20, 0x0048,  117 }, { 0x22, 0x8048,  123 }, { 0x24, 0x0049,  128 },
	{ 0x26, 0x8049,  134 }, { 0x28, 0x004a,  140 }, { 0x2a, 0x804a,  146 },
	{ 0x2c, 0x004b,  152 }, { 0x2e, 0x804b,  159 }, { 0x30, 0x004c,  166 },
	{ 0x32, 0x804c,  173 }, { 0x34, 0x004d,  181 }, { 0x36, 0x804d,  189 },
	{ 0x38, 0x004e,  198 }, { 0x3a, 0x804e,  206 }, { 0x3c, 0x004f,  215 },
	{ 0x3e, 0x804f,  225 }, { 0x40, 0x0050,  230 }, { 0x42, 0x8050,  235 },
	{ 0x44, 0x0051,  240 }, { 0x46, 0x8051,  245 }, { 0x48, 0x0052,  251 },
	{ 0x4a, 0x8052,  256 }, { 0x4c, 0x0053,  262 }, { 0x4e, 0x8053,  268 },
	{ 0x50, 0x0054,  273 }, { 0x52, 0x8054,  279 }, { 0x54, 0x0055,  286 },
	{ 0x56, 0x8055,  292 }, { 0x58, 0x0056,  298 }, { 0x5a, 0x8056,  305 },
	{ 0x5c, 0x0057,  311 }, { 0x5e, 0x8057,  318 }, { 0x60, 0x0058,  325 },
	{ 0x62, 0x8058,  332 }, { 0x64, 0x0059,  340 }, { 0x66, 0x8059,  347 },
	{ 0x68, 0x005a,  355 }, { 0x6a, 0x805a,  362 }, { 0x6c, 0x005b,  370 },
	{ 0x6e, 0x805b,  378 }, { 0x70, 0x005c,  387 }, { 0x72, 0x805c,  395 },
	{ 0x74, 0x005d,  404 }, { 0x76, 0x805d,  413 }, { 0x78, 0x005e,  422 },
	{ 0x7a, 0x805e,  431 }, { 0x7c, 0x005f,  440 }, { 0x7e, 0x805f,  450 },
	{ 0x80, 0x0060,  460 }, { 0x82, 0x8060,  470 }, { 0x84, 0x0061,  480 },
	{ 0x86, 0x8061,  491 }, { 0x88, 0x0062,  501 }, { 0x8a, 0x8062,  512 },
	{ 0x8c, 0x0063,  524 }, { 0x8e, 0x8063,  535 }, { 0x90, 0x0064,  547 },
	{ 0x92, 0x8064,  559 }, { 0x94, 0x0065,  571 }, { 0x96, 0x8065,  584 },
	{ 0x98, 0x0066,  596 }, { 0x9a, 0x8066,  609 }, { 0x9c, 0x0067,  623 },
	{ 0x9e, 0x8067,  636 }, { 0xa0, 0x0068,  650 }, { 0xa2, 0x8068,  665 },
	{ 0xa4, 0x0069,  679 }, { 0xa6, 0x8069,  694 }, { 0xa8, 0x006a,  709 },
	{ 0xaa, 0x806a,  725 }, { 0xac, 0x006b,  741 }, { 0xae, 0x806b,  757 },
	{ 0xb0, 0x006c,  773 }, { 0xb2, 0x806c,  790 }, { 0xb4, 0x006d,  808 },
	{ 0xb6, 0x806d,  825 }, { 0xb8, 0x006e,  843 }, { 0xba, 0x806e,  862 },
	{ 0xbc, 0x006f,  881 }, { 0xbe, 0x806f,  900 }, { 0xc0, 0x0070,  920 },
	{ 0xc2, 0x8070,  940 }, { 0xc4, 0x0071,  960 }, { 0xc6, 0x8071,  981 },
	{ 0xc8, 0x0072, joycon_max_rumble_amp }
};
static const u16 JC_RUMBLE_DFLT_LOW_FREQ = 160;
static const u16 JC_RUMBLE_DFLT_HIGH_FREQ = 320;
static const unsigned short JC_RUMBLE_ZERO_AMP_PKT_CNT = 5;
#endif /* IS_ENABLED(CONFIG_NINTENDO_FF) */
static const u16 JC_RUMBLE_PERIOD_MS = 50;

/* States for controller state machine */
enum joycon_ctlr_state {
	JOYCON_CTLR_STATE_INIT,
	JOYCON_CTLR_STATE_READ,
	JOYCON_CTLR_STATE_REMOVED,
	JOYCON_CTLR_STATE_SUSPENDED,
};

/* Controller type received as part of device info */
enum joycon_ctlr_type {
	JOYCON_CTLR_TYPE_JCL  = 0x01,
	JOYCON_CTLR_TYPE_JCR  = 0x02,
	JOYCON_CTLR_TYPE_PRO  = 0x03,
	JOYCON_CTLR_TYPE_LIC_PRO = 0x06,
	JOYCON_CTLR_TYPE_NESL = 0x09,
	JOYCON_CTLR_TYPE_NESR = 0x0A,
	JOYCON_CTLR_TYPE_SNES = 0x0B,
	JOYCON_CTLR_TYPE_GEN  = 0x0D,
	JOYCON_CTLR_TYPE_N64  = 0x0C,
};

struct joycon_stick_cal {
	s32 max;
	s32 min;
	s32 center;
};

struct joycon_imu_cal {
	s16 offset[3];
	s16 scale[3];
};

/*
 * All the controller's button values are stored in a u32.
 * They can be accessed with bitwise ANDs.
 */
#define JC_BTN_Y	 BIT(0)
#define JC_BTN_X	 BIT(1)
#define JC_BTN_B	 BIT(2)
#define JC_BTN_A	 BIT(3)
#define JC_BTN_SR_R	 BIT(4)
#define JC_BTN_SL_R	 BIT(5)
#define JC_BTN_R	 BIT(6)
#define JC_BTN_ZR	 BIT(7)
#define JC_BTN_MINUS	 BIT(8)
#define JC_BTN_PLUS	 BIT(9)
#define JC_BTN_RSTICK	 BIT(10)
#define JC_BTN_LSTICK	 BIT(11)
#define JC_BTN_HOME	 BIT(12)
#define JC_BTN_CAP	 BIT(13) /* capture button */
#define JC_BTN_DOWN	 BIT(16)
#define JC_BTN_UP	 BIT(17)
#define JC_BTN_RIGHT	 BIT(18)
#define JC_BTN_LEFT	 BIT(19)
#define JC_BTN_SR_L	 BIT(20)
#define JC_BTN_SL_L	 BIT(21)
#define JC_BTN_L	 BIT(22)
#define JC_BTN_ZL	 BIT(23)

struct joycon_ctlr_button_mapping {
	u32 code;
	u32 bit;
};

/*
 * D-pad is configured as buttons for the left Joy-Con only!
 */
static const struct joycon_ctlr_button_mapping left_joycon_button_mappings[] = {
	{ BTN_TL,		JC_BTN_L,	},
	{ BTN_TL2,		JC_BTN_ZL,	},
	{ BTN_SELECT,		JC_BTN_MINUS,	},
	{ BTN_THUMBL,		JC_BTN_LSTICK,	},
	{ BTN_DPAD_UP,		JC_BTN_UP,	},
	{ BTN_DPAD_DOWN,	JC_BTN_DOWN,	},
	{ BTN_DPAD_LEFT,	JC_BTN_LEFT,	},
	{ BTN_DPAD_RIGHT,	JC_BTN_RIGHT,	},
	{ BTN_Z,		JC_BTN_CAP,	},
	{ /* sentinel */ },
};

/*
 * The unused *right*-side triggers become the SL/SR triggers for the *left*
 * Joy-Con, if and only if we're not using a charging grip.
 */
static const struct joycon_ctlr_button_mapping left_joycon_s_button_mappings[] = {
	{ BTN_TR,	JC_BTN_SL_L,	},
	{ BTN_TR2,	JC_BTN_SR_L,	},
	{ /* sentinel */ },
};

static const struct joycon_ctlr_button_mapping right_joycon_button_mappings[] = {
	{ BTN_EAST,	JC_BTN_A,	},
	{ BTN_SOUTH,	JC_BTN_B,	},
	{ BTN_NORTH,	JC_BTN_X,	},
	{ BTN_WEST,	JC_BTN_Y,	},
	{ BTN_TR,	JC_BTN_R,	},
	{ BTN_TR2,	JC_BTN_ZR,	},
	{ BTN_START,	JC_BTN_PLUS,	},
	{ BTN_THUMBR,	JC_BTN_RSTICK,	},
	{ BTN_MODE,	JC_BTN_HOME,	},
	{ /* sentinel */ },
};

/*
 * The unused *left*-side triggers become the SL/SR triggers for the *right*
 * Joy-Con, if and only if we're not using a charging grip.
 */
static const struct joycon_ctlr_button_mapping right_joycon_s_button_mappings[] = {
	{ BTN_TL,	JC_BTN_SL_R,	},
	{ BTN_TL2,	JC_BTN_SR_R,	},
	{ /* sentinel */ },
};

static const struct joycon_ctlr_button_mapping procon_button_mappings[] = {
	{ BTN_EAST,	JC_BTN_A,	},
	{ BTN_SOUTH,	JC_BTN_B,	},
	{ BTN_NORTH,	JC_BTN_X,	},
	{ BTN_WEST,	JC_BTN_Y,	},
	{ BTN_TL,	JC_BTN_L,	},
	{ BTN_TR,	JC_BTN_R,	},
	{ BTN_TL2,	JC_BTN_ZL,	},
	{ BTN_TR2,	JC_BTN_ZR,	},
	{ BTN_SELECT,	JC_BTN_MINUS,	},
	{ BTN_START,	JC_BTN_PLUS,	},
	{ BTN_THUMBL,	JC_BTN_LSTICK,	},
	{ BTN_THUMBR,	JC_BTN_RSTICK,	},
	{ BTN_MODE,	JC_BTN_HOME,	},
	{ BTN_Z,	JC_BTN_CAP,	},
	{ /* sentinel */ },
};

/* HORI Licensed Pro Controllers swap X/Y bits in the report */
static const struct joycon_ctlr_button_mapping lic_hori_procon_button_mappings[] = {
	{ BTN_EAST,	JC_BTN_A,	},
	{ BTN_SOUTH,	JC_BTN_B,	},
	{ BTN_NORTH,	JC_BTN_Y,	},
	{ BTN_WEST,	JC_BTN_X,	},
	{ BTN_TL,	JC_BTN_L,	},
	{ BTN_TR,	JC_BTN_R,	},
	{ BTN_TL2,	JC_BTN_ZL,	},
	{ BTN_TR2,	JC_BTN_ZR,	},
	{ BTN_SELECT,	JC_BTN_MINUS,	},
	{ BTN_START,	JC_BTN_PLUS,	},
	{ BTN_THUMBL,	JC_BTN_LSTICK,	},
	{ BTN_THUMBR,	JC_BTN_RSTICK,	},
	{ BTN_MODE,	JC_BTN_HOME,	},
	{ BTN_Z,	JC_BTN_CAP,	},
	{ /* sentinel */ },
};

static const struct joycon_ctlr_button_mapping nescon_button_mappings[] = {
	{ BTN_SOUTH,	JC_BTN_A,	},
	{ BTN_EAST,	JC_BTN_B,	},
	{ BTN_TL,	JC_BTN_L,	},
	{ BTN_TR,	JC_BTN_R,	},
	{ BTN_SELECT,	JC_BTN_MINUS,	},
	{ BTN_START,	JC_BTN_PLUS,	},
	{ /* sentinel */ },
};

static const struct joycon_ctlr_button_mapping snescon_button_mappings[] = {
	{ BTN_EAST,	JC_BTN_A,	},
	{ BTN_SOUTH,	JC_BTN_B,	},
	{ BTN_NORTH,	JC_BTN_X,	},
	{ BTN_WEST,	JC_BTN_Y,	},
	{ BTN_TL,	JC_BTN_L,	},
	{ BTN_TR,	JC_BTN_R,	},
	{ BTN_TL2,	JC_BTN_ZL,	},
	{ BTN_TR2,	JC_BTN_ZR,	},
	{ BTN_SELECT,	JC_BTN_MINUS,	},
	{ BTN_START,	JC_BTN_PLUS,	},
	{ /* sentinel */ },
};

static const struct joycon_ctlr_button_mapping gencon_button_mappings[] = {
	{ BTN_WEST,	JC_BTN_A,	}, /* A */
	{ BTN_SOUTH,	JC_BTN_B,	}, /* B */
	{ BTN_EAST,	JC_BTN_R,	}, /* C */
	{ BTN_TL,	JC_BTN_X,	}, /* X MD/GEN 6B Only */
	{ BTN_NORTH,	JC_BTN_Y,	}, /* Y MD/GEN 6B Only */
	{ BTN_TR,	JC_BTN_L,	}, /* Z MD/GEN 6B Only */
	{ BTN_SELECT,	JC_BTN_ZR,	}, /* Mode */
	{ BTN_START,	JC_BTN_PLUS,	},
	{ BTN_MODE,	JC_BTN_HOME,	},
	{ BTN_Z,	JC_BTN_CAP,	},
	{ /* sentinel */ },
};

static const struct joycon_ctlr_button_mapping n64con_button_mappings[] = {
	{ BTN_A,		JC_BTN_A,	},
	{ BTN_B,		JC_BTN_B,	},
	{ BTN_TL2,		JC_BTN_ZL,	}, /* Z */
	{ BTN_TL,		JC_BTN_L,	},
	{ BTN_TR,		JC_BTN_R,	},
	{ BTN_TR2,		JC_BTN_LSTICK,	}, /* ZR */
	{ BTN_START,		JC_BTN_PLUS,	},
	{ BTN_SELECT,		JC_BTN_Y,	}, /* C UP */
	{ BTN_X,		JC_BTN_ZR,	}, /* C DOWN */
	{ BTN_Y,		JC_BTN_X,	}, /* C LEFT */
	{ BTN_C,		JC_BTN_MINUS,	}, /* C RIGHT */
	{ BTN_MODE,		JC_BTN_HOME,	},
	{ BTN_Z,		JC_BTN_CAP,	},
	{ /* sentinel */ },
};

enum joycon_msg_type {
	JOYCON_MSG_TYPE_NONE,
	JOYCON_MSG_TYPE_USB,
	JOYCON_MSG_TYPE_SUBCMD,
};

struct joycon_rumble_output {
	u8 output_id;
	u8 packet_num;
	u8 rumble_data[8];
} __packed;

struct joycon_subcmd_request {
	u8 output_id; /* must be 0x01 for subcommand, 0x10 for rumble only */
	u8 packet_num; /* incremented every send */
	u8 rumble_data[8];
	u8 subcmd_id;
	u8 data[]; /* length depends on the subcommand */
} __packed;

struct joycon_subcmd_reply {
	u8 ack; /* MSB 1 for ACK, 0 for NACK */
	u8 id; /* id of requested subcmd */
	u8 data[]; /* will be at most 35 bytes */
} __packed;

struct joycon_imu_data {
	s16 accel_x;
	s16 accel_y;
	s16 accel_z;
	s16 gyro_x;
	s16 gyro_y;
	s16 gyro_z;
} __packed;

struct joycon_input_report {
	u8 id;
	u8 timer;
	u8 bat_con; /* battery and connection info */
	u8 button_status[3];
	u8 left_stick[3];
	u8 right_stick[3];
	u8 vibrator_report;

	union {
		struct joycon_subcmd_reply subcmd_reply;
		/* IMU input reports contain 3 samples */
		u8 imu_raw_bytes[sizeof(struct joycon_imu_data) * 3];
	};
} __packed;

#define JC_MAX_RESP_SIZE	(sizeof(struct joycon_input_report) + 35)
#define JC_RUMBLE_DATA_SIZE	8
#define JC_RUMBLE_QUEUE_SIZE	8

static const char * const joycon_player_led_names[] = {
	LED_FUNCTION_PLAYER1,
	LED_FUNCTION_PLAYER2,
	LED_FUNCTION_PLAYER3,
	LED_FUNCTION_PLAYER4,
};
#define JC_NUM_LEDS		ARRAY_SIZE(joycon_player_led_names)
#define JC_NUM_LED_PATTERNS 8
/* Taken from https://www.nintendo.com/my/support/qa/detail/33822 */
static const enum led_brightness joycon_player_led_patterns[JC_NUM_LED_PATTERNS][JC_NUM_LEDS] = {
	{ 1, 0, 0, 0 },
	{ 1, 1, 0, 0 },
	{ 1, 1, 1, 0 },
	{ 1, 1, 1, 1 },
	{ 1, 0, 0, 1 },
	{ 1, 0, 1, 0 },
	{ 1, 0, 1, 1 },
	{ 0, 1, 1, 0 },
};

/* Each physical controller is associated with a joycon_ctlr struct */
struct joycon_ctlr {
	struct hid_device *hdev;
	struct input_dev *input;
	u32 player_id;
	struct led_classdev leds[JC_NUM_LEDS]; /* player leds */
	struct led_classdev home_led;
	enum joycon_ctlr_state ctlr_state;
	spinlock_t lock;
	u8 mac_addr[6];
	char *mac_addr_str;
	enum joycon_ctlr_type ctlr_type;

	/* The following members are used for synchronous sends/receives */
	enum joycon_msg_type msg_type;
	u8 subcmd_num;
	struct mutex output_mutex;
	u8 input_buf[JC_MAX_RESP_SIZE];
	wait_queue_head_t wait;
	bool received_resp;
	u8 usb_ack_match;
	u8 subcmd_ack_match;
	bool received_input_report;
	unsigned int last_input_report_msecs;
	unsigned int last_subcmd_sent_msecs;
	unsigned int consecutive_valid_report_deltas;
	unsigned int subcmd_rate_exhaustions;
	bool subcmd_rate_relaxed;

	/* factory calibration data */
	struct joycon_stick_cal left_stick_cal_x;
	struct joycon_stick_cal left_stick_cal_y;
	struct joycon_stick_cal right_stick_cal_x;
	struct joycon_stick_cal right_stick_cal_y;

	struct joycon_imu_cal accel_cal;
	struct joycon_imu_cal gyro_cal;

	/* prevents needlessly recalculating these divisors every sample */
	s32 imu_cal_accel_divisor[3];
	s32 imu_cal_gyro_divisor[3];

	/* power supply data */
	struct power_supply *battery;
	struct power_supply_desc battery_desc;
	u8 battery_capacity;
	bool battery_charging;
	bool host_powered;

	/* rumble */
	u8 rumble_data[JC_RUMBLE_QUEUE_SIZE][JC_RUMBLE_DATA_SIZE];
	int rumble_queue_head;
	int rumble_queue_tail;
	struct workqueue_struct *rumble_queue;
	struct work_struct rumble_worker;
	unsigned int rumble_msecs;
	u16 rumble_ll_freq;
	u16 rumble_lh_freq;
	u16 rumble_rl_freq;
	u16 rumble_rh_freq;
	unsigned short rumble_zero_countdown;

	/* imu */
	struct input_dev *imu_input;
	bool imu_first_packet_received; /* helps in initiating timestamp */
	unsigned int imu_timestamp_us; /* timestamp we report to userspace */
	unsigned int imu_last_pkt_ms; /* used to calc imu report delta */
	/* the following are used to track the average imu report time delta */
	unsigned int imu_delta_samples_count;
	unsigned int imu_delta_samples_sum;
	unsigned int imu_avg_delta_ms;
};

/* Helper macros for checking controller type */
#define jc_type_is_joycon(ctlr) \
	(ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONL || \
	 ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_JOYCONR || \
	 ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP)
#define jc_type_is_procon(ctlr) \
	(ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_PROCON)
#define jc_type_is_chrggrip(ctlr) \
	(ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP)

/* Does this controller have inputs associated with left joycon? */
#define jc_type_has_left(ctlr) \
	(ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCL || \
	 ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO || \
	 ctlr->ctlr_type == JOYCON_CTLR_TYPE_N64)

/* Does this controller have inputs associated with right joycon? */
#define jc_type_has_right(ctlr) \
	(ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCR || \
	 ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO)

/*
 * Controller device helpers
 *
 * These look at the device ID known to the HID subsystem to identify a device,
 * but take caution: some NSO devices lie about themselves (NES Joy-Cons and
 * Sega Genesis controller). See type helpers below.
 *
 * These helpers are most useful early during the HID probe or in conjunction
 * with the capability helpers below.
 */
static inline bool joycon_device_is_chrggrip(struct joycon_ctlr *ctlr)
{
	return ctlr->hdev->product == USB_DEVICE_ID_NINTENDO_CHRGGRIP;
}

/*
 * Controller type helpers
 *
 * These are slightly different than the device-ID-based helpers above. They are
 * generally more reliable, since they can distinguish between, e.g., Genesis
 * versus SNES, or NES Joy-Cons versus regular Switch Joy-Cons. They're most
 * useful for reporting available inputs. For other kinds of distinctions, see
 * the capability helpers below.
 *
 * They have two major drawbacks: (1) they're not available until after we set
 * the reporting method and then request the device info; (2) they can't
 * distinguish all controllers (like the Charging Grip from the Pro controller.)
 */
static inline bool joycon_type_is_left_joycon(struct joycon_ctlr *ctlr)
{
	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCL;
}

static inline bool joycon_type_is_right_joycon(struct joycon_ctlr *ctlr)
{
	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_JCR;
}

static inline bool joycon_type_is_procon(struct joycon_ctlr *ctlr)
{
	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_PRO ||
	       ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO;
}

static inline bool joycon_type_is_snescon(struct joycon_ctlr *ctlr)
{
	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_SNES;
}

static inline bool joycon_type_is_gencon(struct joycon_ctlr *ctlr)
{
	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_GEN;
}

static inline bool joycon_type_is_n64con(struct joycon_ctlr *ctlr)
{
	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_N64;
}

static inline bool joycon_type_is_left_nescon(struct joycon_ctlr *ctlr)
{
	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_NESL;
}

static inline bool joycon_type_is_right_nescon(struct joycon_ctlr *ctlr)
{
	return ctlr->ctlr_type == JOYCON_CTLR_TYPE_NESR;
}

static inline bool joycon_type_is_any_joycon(struct joycon_ctlr *ctlr)
{
	return joycon_type_is_left_joycon(ctlr) ||
	       joycon_type_is_right_joycon(ctlr) ||
	       joycon_device_is_chrggrip(ctlr);
}

static inline bool joycon_type_is_any_nescon(struct joycon_ctlr *ctlr)
{
	return joycon_type_is_left_nescon(ctlr) ||
	       joycon_type_is_right_nescon(ctlr);
}

/*
 * Controller capability helpers
 *
 * These helpers combine the use of the helpers above to detect certain
 * capabilities during initialization. They are always accurate but (since they
 * use type helpers) cannot be used early in the HID probe.
 */
static inline bool joycon_has_imu(struct joycon_ctlr *ctlr)
{
	return joycon_device_is_chrggrip(ctlr) ||
	       joycon_type_is_any_joycon(ctlr) ||
	       joycon_type_is_procon(ctlr);
}

static inline bool joycon_has_joysticks(struct joycon_ctlr *ctlr)
{
	return joycon_device_is_chrggrip(ctlr) ||
	       joycon_type_is_any_joycon(ctlr) ||
	       joycon_type_is_procon(ctlr) ||
	       joycon_type_is_n64con(ctlr);
}

static inline bool joycon_has_rumble(struct joycon_ctlr *ctlr)
{
	return joycon_device_is_chrggrip(ctlr) ||
	       joycon_type_is_any_joycon(ctlr) ||
	       joycon_type_is_procon(ctlr) ||
	       joycon_type_is_n64con(ctlr);
}

static inline bool joycon_using_usb(struct joycon_ctlr *ctlr)
{
	return ctlr->hdev->bus == BUS_USB;
}

static int __joycon_hid_send(struct hid_device *hdev, u8 *data, size_t len)
{
	u8 *buf;
	int ret;

	buf = kmemdup(data, len, GFP_KERNEL);
	if (!buf)
		return -ENOMEM;
	ret = hid_hw_output_report(hdev, buf, len);
	kfree(buf);
	if (ret < 0)
		hid_dbg(hdev, "Failed to send output report ret=%d\n", ret);
	return ret;
}

static void joycon_wait_for_input_report(struct joycon_ctlr *ctlr)
{
	int ret;

	/*
	 * If we are in the proper reporting mode, wait for an input
	 * report prior to sending the subcommand. This improves
	 * reliability considerably.
	 */
	if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ) {
		unsigned long flags;

		spin_lock_irqsave(&ctlr->lock, flags);
		ctlr->received_input_report = false;
		spin_unlock_irqrestore(&ctlr->lock, flags);
		ret = wait_event_timeout(ctlr->wait,
					 ctlr->received_input_report,
					 HZ / 4);
		/* We will still proceed, even with a timeout here */
		if (!ret)
			hid_warn(ctlr->hdev,
				 "timeout waiting for input report\n");
	}
}

/*
 * Sending subcommands and/or rumble data at too high a rate can cause bluetooth
 * controller disconnections.
 */
#define JC_INPUT_REPORT_MIN_DELTA	8
#define JC_INPUT_REPORT_MAX_DELTA	17
#define JC_SUBCMD_TX_OFFSET_MS		4
#define JC_SUBCMD_VALID_DELTA_REQ	3
#define JC_SUBCMD_RATE_MAX_ATTEMPTS	25
#define JC_SUBCMD_RATE_MAX_FAILURES	4
#define JC_SUBCMD_RATE_LIMITER_USB_MS	20
#define JC_SUBCMD_RATE_LIMITER_BT_MS	60
#define JC_SUBCMD_RATE_LIMITER_MS(ctlr)	((ctlr)->hdev->bus == BUS_USB ? JC_SUBCMD_RATE_LIMITER_USB_MS : JC_SUBCMD_RATE_LIMITER_BT_MS)
static void joycon_enforce_subcmd_rate_strict(struct joycon_ctlr *ctlr)
{
	unsigned int current_ms;
	unsigned long subcmd_delta;
	int consecutive_valid_deltas = 0;
	int attempts = 0;
	unsigned long flags;

	if (unlikely(ctlr->ctlr_state != JOYCON_CTLR_STATE_READ))
		return;

	do {
		joycon_wait_for_input_report(ctlr);
		current_ms = jiffies_to_msecs(jiffies);
		subcmd_delta = current_ms - ctlr->last_subcmd_sent_msecs;

		spin_lock_irqsave(&ctlr->lock, flags);
		consecutive_valid_deltas = ctlr->consecutive_valid_report_deltas;
		spin_unlock_irqrestore(&ctlr->lock, flags);

		attempts++;
	} while ((consecutive_valid_deltas < JC_SUBCMD_VALID_DELTA_REQ ||
		  subcmd_delta < JC_SUBCMD_RATE_LIMITER_MS(ctlr)) &&
		 ctlr->ctlr_state == JOYCON_CTLR_STATE_READ &&
		 attempts < JC_SUBCMD_RATE_MAX_ATTEMPTS);

	if (attempts >= JC_SUBCMD_RATE_MAX_ATTEMPTS) {
		hid_warn(ctlr->hdev, "%s: exceeded max attempts", __func__);

		if (++ctlr->subcmd_rate_exhaustions == JC_SUBCMD_RATE_MAX_FAILURES) {
			ctlr->subcmd_rate_relaxed = true;
			hid_info(ctlr->hdev,
				 "input report cadence does not fit the %d-%dms window; using the legacy subcommand throttle\n",
				 JC_INPUT_REPORT_MIN_DELTA,
				 JC_INPUT_REPORT_MAX_DELTA);
		}
		return;
	}

	ctlr->last_subcmd_sent_msecs = current_ms;

	/*
	 * Wait a short time after receiving an input report before
	 * transmitting. This should reduce odds of a TX coinciding with an RX.
	 * Minimizing concurrent BT traffic with the controller seems to lower
	 * the rate of disconnections.
	 */
	msleep(JC_SUBCMD_TX_OFFSET_MS);
}

/* The rate limiter as it was before commit d750d1480362, without the report
 * cadence requirement.
 */
static void joycon_enforce_subcmd_rate_legacy(struct joycon_ctlr *ctlr)
{
	static const unsigned int max_subcmd_rate_ms = 25;
	unsigned int current_ms = jiffies_to_msecs(jiffies);
	unsigned int delta_ms = current_ms - ctlr->last_subcmd_sent_msecs;

	while (delta_ms < max_subcmd_rate_ms &&
	       ctlr->ctlr_state == JOYCON_CTLR_STATE_READ) {
		joycon_wait_for_input_report(ctlr);
		current_ms = jiffies_to_msecs(jiffies);
		delta_ms = current_ms - ctlr->last_subcmd_sent_msecs;
	}
	ctlr->last_subcmd_sent_msecs = current_ms;
}

static void joycon_enforce_subcmd_rate(struct joycon_ctlr *ctlr)
{
	if (ctlr->subcmd_rate_relaxed)
		joycon_enforce_subcmd_rate_legacy(ctlr);
	else
		joycon_enforce_subcmd_rate_strict(ctlr);
}

static int joycon_hid_send_sync(struct joycon_ctlr *ctlr, u8 *data, size_t len,
				u32 timeout)
{
	int ret;
	int tries = 2;

	/*
	 * The controller occasionally seems to drop subcommands. In testing,
	 * doing one retry after a timeout appears to always work.
	 */
	while (tries--) {
		joycon_enforce_subcmd_rate(ctlr);

		ret = __joycon_hid_send(ctlr->hdev, data, len);
		if (ret < 0) {
			memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
			return ret;
		}

		ret = wait_event_timeout(ctlr->wait, ctlr->received_resp,
					 timeout);
		if (!ret) {
			hid_dbg(ctlr->hdev,
				"synchronous send/receive timed out\n");
			if (tries) {
				hid_dbg(ctlr->hdev,
					"retrying sync send after timeout\n");
			}
			memset(ctlr->input_buf, 0, JC_MAX_RESP_SIZE);
			ret = -ETIMEDOUT;
		} else {
			ret = 0;
			break;
		}
	}

	ctlr->received_resp = false;
	return ret;
}

static int joycon_send_usb(struct joycon_ctlr *ctlr, u8 cmd, u32 timeout)
{
	int ret;
	u8 buf[2] = {JC_OUTPUT_USB_CMD};

	buf[1] = cmd;
	ctlr->usb_ack_match = cmd;
	ctlr->msg_type = JOYCON_MSG_TYPE_USB;
	ret = joycon_hid_send_sync(ctlr, buf, sizeof(buf), timeout);
	if (ret)
		hid_dbg(ctlr->hdev, "send usb command failed; ret=%d\n", ret);
	return ret;
}

static int joycon_send_subcmd(struct joycon_ctlr *ctlr,
			      struct joycon_subcmd_request *subcmd,
			      size_t data_len, u32 timeout)
{
	int ret;
	unsigned long flags;

	spin_lock_irqsave(&ctlr->lock, flags);
	/*
	 * If the controller has been removed, just return ENODEV so the LED
	 * subsystem doesn't print invalid errors on removal.
	 */
	if (ctlr->ctlr_state == JOYCON_CTLR_STATE_REMOVED) {
		spin_unlock_irqrestore(&ctlr->lock, flags);
		return -ENODEV;
	}
	memcpy(subcmd->rumble_data, ctlr->rumble_data[ctlr->rumble_queue_tail],
	       JC_RUMBLE_DATA_SIZE);
	spin_unlock_irqrestore(&ctlr->lock, flags);

	subcmd->output_id = JC_OUTPUT_RUMBLE_AND_SUBCMD;
	subcmd->packet_num = ctlr->subcmd_num;
	if (++ctlr->subcmd_num > 0xF)
		ctlr->subcmd_num = 0;
	ctlr->subcmd_ack_match = subcmd->subcmd_id;
	ctlr->msg_type = JOYCON_MSG_TYPE_SUBCMD;

	ret = joycon_hid_send_sync(ctlr, (u8 *)subcmd,
				   sizeof(*subcmd) + data_len, timeout);
	if (ret < 0)
		hid_dbg(ctlr->hdev, "send subcommand failed; ret=%d\n", ret);
	else
		ret = 0;
	return ret;
}

/* Supply nibbles for flash and on. Ones correspond to active */
static int joycon_set_player_leds(struct joycon_ctlr *ctlr, u8 flash, u8 on)
{
	struct joycon_subcmd_request *req;
	u8 buffer[sizeof(*req) + 1] = { 0 };

	req = (struct joycon_subcmd_request *)buffer;
	req->subcmd_id = JC_SUBCMD_SET_PLAYER_LIGHTS;
	req->data[0] = (flash << 4) | on;

	hid_dbg(ctlr->hdev, "setting player leds\n");
	return joycon_send_subcmd(ctlr, req, 1, HZ/4);
}

static int joycon_set_home_led(struct joycon_ctlr *ctlr, enum led_brightness brightness)
{
	struct joycon_subcmd_request *req;
	u8 buffer[sizeof(*req) + 5] = { 0 };
	u8 *data;

	req = (struct joycon_subcmd_request *)buffer;
	req->subcmd_id = JC_SUBCMD_SET_HOME_LIGHT;
	data = req->data;
	data[0] = 0x01;
	data[1] = brightness << 4;
	data[2] = brightness | (brightness << 4);
	data[3] = 0x11;
	data[4] = 0x11;

	hid_dbg(ctlr->hdev, "setting home led brightness\n");
	return joycon_send_subcmd(ctlr, req, 5, HZ/4);
}

static int joycon_request_spi_flash_read(struct joycon_ctlr *ctlr,
					 u32 start_addr, u8 size, u8 **reply)
{
	struct joycon_subcmd_request *req;
	struct joycon_input_report *report;
	u8 buffer[sizeof(*req) + 5] = { 0 };
	u8 *data;
	int ret;

	if (!reply)
		return -EINVAL;

	req = (struct joycon_subcmd_request *)buffer;
	req->subcmd_id = JC_SUBCMD_SPI_FLASH_READ;
	data = req->data;
	put_unaligned_le32(start_addr, data);
	data[4] = size;

	hid_dbg(ctlr->hdev, "requesting SPI flash data\n");
	ret = joycon_send_subcmd(ctlr, req, 5, HZ);
	if (ret) {
		hid_err(ctlr->hdev, "failed reading SPI flash; ret=%d\n", ret);
	} else {
		report = (struct joycon_input_report *)ctlr->input_buf;
		/* The read data starts at the 6th byte */
		*reply = &report->subcmd_reply.data[5];
	}
	return ret;
}

/*
 * User calibration's presence is denoted with a magic byte preceding it.
 * returns 0 if magic val is present, 1 if not present, < 0 on error
 */
static int joycon_check_for_cal_magic(struct joycon_ctlr *ctlr, u32 flash_addr)
{
	int ret;
	u8 *reply;

	ret = joycon_request_spi_flash_read(ctlr, flash_addr,
					    JC_CAL_USR_MAGIC_SIZE, &reply);
	if (ret)
		return ret;

	return reply[0] != JC_CAL_USR_MAGIC_0 || reply[1] != JC_CAL_USR_MAGIC_1;
}

static int joycon_read_stick_calibration(struct joycon_ctlr *ctlr, u16 cal_addr,
					 struct joycon_stick_cal *cal_x,
					 struct joycon_stick_cal *cal_y,
					 bool left_stick)
{
	s32 x_max_above;
	s32 x_min_below;
	s32 y_max_above;
	s32 y_min_below;
	u8 *raw_cal;
	int ret;

	ret = joycon_request_spi_flash_read(ctlr, cal_addr,
					    JC_CAL_STICK_DATA_SIZE, &raw_cal);
	if (ret)
		return ret;

	/* stick calibration parsing: note the order differs based on stick */
	if (left_stick) {
		x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0,
						12);
		y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4,
						12);
		cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0,
						  12);
		cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4,
						  12);
		x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0,
						12);
		y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4,
						12);
	} else {
		cal_x->center = hid_field_extract(ctlr->hdev, (raw_cal + 0), 0,
						  12);
		cal_y->center = hid_field_extract(ctlr->hdev, (raw_cal + 1), 4,
						  12);
		x_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 3), 0,
						12);
		y_min_below = hid_field_extract(ctlr->hdev, (raw_cal + 4), 4,
						12);
		x_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 6), 0,
						12);
		y_max_above = hid_field_extract(ctlr->hdev, (raw_cal + 7), 4,
						12);
	}

	cal_x->max = cal_x->center + x_max_above;
	cal_x->min = cal_x->center - x_min_below;
	cal_y->max = cal_y->center + y_max_above;
	cal_y->min = cal_y->center - y_min_below;

	/* check if calibration values are plausible */
	if (cal_x->min >= cal_x->center || cal_x->center >= cal_x->max ||
	    cal_y->min >= cal_y->center || cal_y->center >= cal_y->max)
		ret = -EINVAL;

	return ret;
}

static const u16 DFLT_STICK_CAL_CEN = 2000;
static const u16 DFLT_STICK_CAL_MAX = 3500;
static const u16 DFLT_STICK_CAL_MIN = 500;
static void joycon_use_default_calibration(struct hid_device *hdev,
					   struct joycon_stick_cal *cal_x,
					   struct joycon_stick_cal *cal_y,
					   const char *stick, int ret)
{
	hid_warn(hdev,
		 "Failed to read %s stick cal, using defaults; e=%d\n",
		 stick, ret);

	cal_x->center = cal_y->center = DFLT_STICK_CAL_CEN;
	cal_x->max = cal_y->max = DFLT_STICK_CAL_MAX;
	cal_x->min = cal_y->min = DFLT_STICK_CAL_MIN;
}

static int joycon_request_calibration(struct joycon_ctlr *ctlr)
{
	u16 left_stick_addr = JC_CAL_FCT_DATA_LEFT_ADDR;
	u16 right_stick_addr = JC_CAL_FCT_DATA_RIGHT_ADDR;
	int ret;

	hid_dbg(ctlr->hdev, "requesting cal data\n");

	/* check if user stick calibrations are present */
	if (!joycon_check_for_cal_magic(ctlr, JC_CAL_USR_LEFT_MAGIC_ADDR)) {
		left_stick_addr = JC_CAL_USR_LEFT_DATA_ADDR;
		hid_info(ctlr->hdev, "using user cal for left stick\n");
	} else {
		hid_info(ctlr->hdev, "using factory cal for left stick\n");
	}
	if (!joycon_check_for_cal_magic(ctlr, JC_CAL_USR_RIGHT_MAGIC_ADDR)) {
		right_stick_addr = JC_CAL_USR_RIGHT_DATA_ADDR;
		hid_info(ctlr->hdev, "using user cal for right stick\n");
	} else {
		hid_info(ctlr->hdev, "using factory cal for right stick\n");
	}

	/* read the left stick calibration data */
	ret = joycon_read_stick_calibration(ctlr, left_stick_addr,
					    &ctlr->left_stick_cal_x,
					    &ctlr->left_stick_cal_y,
					    true);

	if (ret)
		joycon_use_default_calibration(ctlr->hdev,
					       &ctlr->left_stick_cal_x,
					       &ctlr->left_stick_cal_y,
					       "left", ret);

	/* read the right stick calibration data */
	ret = joycon_read_stick_calibration(ctlr, right_stick_addr,
					    &ctlr->right_stick_cal_x,
					    &ctlr->right_stick_cal_y,
					    false);

	if (ret)
		joycon_use_default_calibration(ctlr->hdev,
					       &ctlr->right_stick_cal_x,
					       &ctlr->right_stick_cal_y,
					       "right", ret);

	hid_dbg(ctlr->hdev, "calibration:\n"
			    "l_x_c=%d l_x_max=%d l_x_min=%d\n"
			    "l_y_c=%d l_y_max=%d l_y_min=%d\n"
			    "r_x_c=%d r_x_max=%d r_x_min=%d\n"
			    "r_y_c=%d r_y_max=%d r_y_min=%d\n",
			    ctlr->left_stick_cal_x.center,
			    ctlr->left_stick_cal_x.max,
			    ctlr->left_stick_cal_x.min,
			    ctlr->left_stick_cal_y.center,
			    ctlr->left_stick_cal_y.max,
			    ctlr->left_stick_cal_y.min,
			    ctlr->right_stick_cal_x.center,
			    ctlr->right_stick_cal_x.max,
			    ctlr->right_stick_cal_x.min,
			    ctlr->right_stick_cal_y.center,
			    ctlr->right_stick_cal_y.max,
			    ctlr->right_stick_cal_y.min);

	return 0;
}

/*
 * These divisors are calculated once rather than for each sample. They are only
 * dependent on the IMU calibration values. They are used when processing the
 * IMU input reports.
 */
static void joycon_calc_imu_cal_divisors(struct joycon_ctlr *ctlr)
{
	int i, divz = 0;

	for (i = 0; i < 3; i++) {
		ctlr->imu_cal_accel_divisor[i] = ctlr->accel_cal.scale[i] -
						ctlr->accel_cal.offset[i];
		ctlr->imu_cal_gyro_divisor[i] = ctlr->gyro_cal.scale[i] -
						ctlr->gyro_cal.offset[i];

		if (ctlr->imu_cal_accel_divisor[i] == 0) {
			ctlr->imu_cal_accel_divisor[i] = 1;
			divz++;
		}

		if (ctlr->imu_cal_gyro_divisor[i] == 0) {
			ctlr->imu_cal_gyro_divisor[i] = 1;
			divz++;
		}
	}

	if (divz)
		hid_warn(ctlr->hdev, "inaccurate IMU divisors (%d)\n", divz);
}

static const s16 DFLT_ACCEL_OFFSET /*= 0*/;
static const s16 DFLT_ACCEL_SCALE = 16384;
static const s16 DFLT_GYRO_OFFSET /*= 0*/;
static const s16 DFLT_GYRO_SCALE  = 13371;
static int joycon_request_imu_calibration(struct joycon_ctlr *ctlr)
{
	u16 imu_cal_addr = JC_IMU_CAL_FCT_DATA_ADDR;
	u8 *raw_cal;
	int ret;
	int i;

	/* check if user calibration exists */
	if (!joycon_check_for_cal_magic(ctlr, JC_IMU_CAL_USR_MAGIC_ADDR)) {
		imu_cal_addr = JC_IMU_CAL_USR_DATA_ADDR;
		hid_info(ctlr->hdev, "using user cal for IMU\n");
	} else {
		hid_info(ctlr->hdev, "using factory cal for IMU\n");
	}

	/* request IMU calibration data */
	hid_dbg(ctlr->hdev, "requesting IMU cal data\n");
	ret = joycon_request_spi_flash_read(ctlr, imu_cal_addr,
					    JC_IMU_CAL_DATA_SIZE, &raw_cal);
	if (ret) {
		hid_warn(ctlr->hdev,
			 "Failed to read IMU cal, using defaults; ret=%d\n",
			 ret);

		for (i = 0; i < 3; i++) {
			ctlr->accel_cal.offset[i] = DFLT_ACCEL_OFFSET;
			ctlr->accel_cal.scale[i] = DFLT_ACCEL_SCALE;
			ctlr->gyro_cal.offset[i] = DFLT_GYRO_OFFSET;
			ctlr->gyro_cal.scale[i] = DFLT_GYRO_SCALE;
		}
		joycon_calc_imu_cal_divisors(ctlr);
		return ret;
	}

	/* IMU calibration parsing */
	for (i = 0; i < 3; i++) {
		int j = i * 2;

		ctlr->accel_cal.offset[i] = get_unaligned_le16(raw_cal + j);
		ctlr->accel_cal.scale[i] = get_unaligned_le16(raw_cal + j + 6);
		ctlr->gyro_cal.offset[i] = get_unaligned_le16(raw_cal + j + 12);
		ctlr->gyro_cal.scale[i] = get_unaligned_le16(raw_cal + j + 18);
	}

	joycon_calc_imu_cal_divisors(ctlr);

	hid_dbg(ctlr->hdev, "IMU calibration:\n"
			    "a_o[0]=%d a_o[1]=%d a_o[2]=%d\n"
			    "a_s[0]=%d a_s[1]=%d a_s[2]=%d\n"
			    "g_o[0]=%d g_o[1]=%d g_o[2]=%d\n"
			    "g_s[0]=%d g_s[1]=%d g_s[2]=%d\n",
			    ctlr->accel_cal.offset[0],
			    ctlr->accel_cal.offset[1],
			    ctlr->accel_cal.offset[2],
			    ctlr->accel_cal.scale[0],
			    ctlr->accel_cal.scale[1],
			    ctlr->accel_cal.scale[2],
			    ctlr->gyro_cal.offset[0],
			    ctlr->gyro_cal.offset[1],
			    ctlr->gyro_cal.offset[2],
			    ctlr->gyro_cal.scale[0],
			    ctlr->gyro_cal.scale[1],
			    ctlr->gyro_cal.scale[2]);

	return 0;
}

static int joycon_set_report_mode(struct joycon_ctlr *ctlr)
{
	struct joycon_subcmd_request *req;
	u8 buffer[sizeof(*req) + 1] = { 0 };

	req = (struct joycon_subcmd_request *)buffer;
	req->subcmd_id = JC_SUBCMD_SET_REPORT_MODE;
	req->data[0] = 0x30; /* standard, full report mode */

	hid_dbg(ctlr->hdev, "setting controller report mode\n");
	return joycon_send_subcmd(ctlr, req, 1, HZ);
}

static int joycon_enable_rumble(struct joycon_ctlr *ctlr)
{
	struct joycon_subcmd_request *req;
	u8 buffer[sizeof(*req) + 1] = { 0 };

	req = (struct joycon_subcmd_request *)buffer;
	req->subcmd_id = JC_SUBCMD_ENABLE_VIBRATION;
	req->data[0] = 0x01; /* note: 0x00 would disable */

	hid_dbg(ctlr->hdev, "enabling rumble\n");
	return joycon_send_subcmd(ctlr, req, 1, HZ/4);
}

static int joycon_enable_imu(struct joycon_ctlr *ctlr)
{
	struct joycon_subcmd_request *req;
	u8 buffer[sizeof(*req) + 1] = { 0 };

	req = (struct joycon_subcmd_request *)buffer;
	req->subcmd_id = JC_SUBCMD_ENABLE_IMU;
	req->data[0] = 0x01; /* note: 0x00 would disable */

	hid_dbg(ctlr->hdev, "enabling IMU\n");
	return joycon_send_subcmd(ctlr, req, 1, HZ);
}

static s32 joycon_map_stick_val(struct joycon_stick_cal *cal, s32 val)
{
	s32 center = cal->center;
	s32 min = cal->min;
	s32 max = cal->max;
	s32 new_val;

	if (val > center) {
		new_val = (val - center) * JC_MAX_STICK_MAG;
		new_val /= (max - center);
	} else {
		new_val = (center - val) * -JC_MAX_STICK_MAG;
		new_val /= (center - min);
	}
	new_val = clamp(new_val, (s32)-JC_MAX_STICK_MAG, (s32)JC_MAX_STICK_MAG);
	return new_val;
}

static void joycon_input_report_parse_imu_data(struct joycon_ctlr *ctlr,
					       struct joycon_input_report *rep,
					       struct joycon_imu_data *imu_data)
{
	u8 *raw = rep->imu_raw_bytes;
	int i;

	for (i = 0; i < 3; i++) {
		struct joycon_imu_data *data = &imu_data[i];

		data->accel_x = get_unaligned_le16(raw + 0);
		data->accel_y = get_unaligned_le16(raw + 2);
		data->accel_z = get_unaligned_le16(raw + 4);
		data->gyro_x = get_unaligned_le16(raw + 6);
		data->gyro_y = get_unaligned_le16(raw + 8);
		data->gyro_z = get_unaligned_le16(raw + 10);
		/* point to next imu sample */
		raw += sizeof(struct joycon_imu_data);
	}
}

static void joycon_parse_imu_report(struct joycon_ctlr *ctlr,
				    struct joycon_input_report *rep)
{
	struct joycon_imu_data imu_data[3] = {0}; /* 3 reports per packet */
	struct input_dev *idev = ctlr->imu_input;
	unsigned int msecs = jiffies_to_msecs(jiffies);
	unsigned int last_msecs = ctlr->imu_last_pkt_ms;
	int i;
	int value[6];

	joycon_input_report_parse_imu_data(ctlr, rep, imu_data);

	/*
	 * There are complexities surrounding how we determine the timestamps we
	 * associate with the samples we pass to userspace. The IMU input
	 * reports do not provide us with a good timestamp. There's a quickly
	 * incrementing 8-bit counter per input report, but it is not very
	 * useful for this purpose (it is not entirely clear what rate it
	 * increments at or if it varies based on packet push rate - more on
	 * the push rate below...).
	 *
	 * The reverse engineering work done on the joy-cons and pro controllers
	 * by the community seems to indicate the following:
	 * - The controller samples the IMU every 1.35ms. It then does some of
	 *   its own processing, probably averaging the samples out.
	 * - Each imu input report contains 3 IMU samples, (usually 5ms apart).
	 * - In the standard reporting mode (which this driver uses exclusively)
	 *   input reports are pushed from the controller as follows:
	 *      * joy-con (bluetooth): every 15 ms
	 *      * joy-cons (in charging grip via USB): every 15 ms
	 *      * pro controller (USB): every 15 ms
	 *      * pro controller (bluetooth): every 8 ms (this is the wildcard)
	 *
	 * Further complicating matters is that some bluetooth stacks are known
	 * to alter the controller's packet rate by hardcoding the bluetooth
	 * SSR for the switch controllers (android's stack currently sets the
	 * SSR to 11ms for both the joy-cons and pro controllers).
	 *
	 * In my own testing, I've discovered that my pro controller either
	 * reports IMU sample batches every 11ms or every 15ms. This rate is
	 * stable after connecting. It isn't 100% clear what determines this
	 * rate. Importantly, even when sending every 11ms, none of the samples
	 * are duplicates. This seems to indicate that the time deltas between
	 * reported samples can vary based on the input report rate.
	 *
	 * The solution employed in this driver is to keep track of the average
	 * time delta between IMU input reports. In testing, this value has
	 * proven to be stable, staying at 15ms or 11ms, though other hardware
	 * configurations and bluetooth stacks could potentially see other rates
	 * (hopefully this will become more clear as more people use the
	 * driver).
	 *
	 * Keeping track of the average report delta allows us to submit our
	 * timestamps to userspace based on that. Each report contains 3
	 * samples, so the IMU sampling rate should be avg_time_delta/3. We can
	 * also use this average to detect events where we have dropped a
	 * packet. The userspace timestamp for the samples will be adjusted
	 * accordingly to prevent unwanted behvaior.
	 */
	if (!ctlr->imu_first_packet_received) {
		ctlr->imu_timestamp_us = 0;
		ctlr->imu_delta_samples_count = 0;
		ctlr->imu_delta_samples_sum = 0;
		ctlr->imu_avg_delta_ms = JC_IMU_DFLT_AVG_DELTA_MS;
		ctlr->imu_first_packet_received = true;
	} else {
		unsigned int delta = msecs - last_msecs;
		unsigned int dropped_pkts;
		unsigned int dropped_threshold;

		/* avg imu report delta housekeeping */
		ctlr->imu_delta_samples_sum += delta;
		ctlr->imu_delta_samples_count++;
		if (ctlr->imu_delta_samples_count >=
		    JC_IMU_SAMPLES_PER_DELTA_AVG) {
			ctlr->imu_avg_delta_ms = ctlr->imu_delta_samples_sum /
						 ctlr->imu_delta_samples_count;
			ctlr->imu_delta_samples_count = 0;
			ctlr->imu_delta_samples_sum = 0;
		}

		/* don't ever want divide by zero shenanigans */
		if (ctlr->imu_avg_delta_ms == 0) {
			ctlr->imu_avg_delta_ms = 1;
			hid_warn(ctlr->hdev, "calculated avg imu delta of 0\n");
		}

		/* useful for debugging IMU sample rate */
		hid_dbg(ctlr->hdev,
			"imu_report: ms=%u last_ms=%u delta=%u avg_delta=%u\n",
			msecs, last_msecs, delta, ctlr->imu_avg_delta_ms);

		/* check if any packets have been dropped */
		dropped_threshold = ctlr->imu_avg_delta_ms * 3 / 2;
		dropped_pkts = (delta - min(delta, dropped_threshold)) /
				ctlr->imu_avg_delta_ms;
		if (dropped_pkts > JC_IMU_DROPPED_PKT_WARNING) {
			hid_warn_ratelimited(ctlr->hdev,
				 "compensating for %u dropped IMU reports\n",
				 dropped_pkts);
			hid_warn_ratelimited(ctlr->hdev,
				 "delta=%u avg_delta=%u\n",
				 delta, ctlr->imu_avg_delta_ms);
		}
	}
	ctlr->imu_last_pkt_ms = msecs;

	/* Each IMU input report contains three samples */
	for (i = 0; i < 3; i++) {
		input_event(idev, EV_MSC, MSC_TIMESTAMP,
			    ctlr->imu_timestamp_us);

		/*
		 * These calculations (which use the controller's calibration
		 * settings to improve the final values) are based on those
		 * found in the community's reverse-engineering repo (linked at
		 * top of driver). For hid-nintendo, we make sure that the final
		 * value given to userspace is always in terms of the axis
		 * resolution we provided.
		 *
		 * Currently only the gyro calculations subtract the calibration
		 * offsets from the raw value itself. In testing, doing the same
		 * for the accelerometer raw values decreased accuracy.
		 *
		 * Note that the gyro values are multiplied by the
		 * precision-saving scaling factor to prevent large inaccuracies
		 * due to truncation of the resolution value which would
		 * otherwise occur. To prevent overflow (without resorting to 64
		 * bit integer math), the mult_frac macro is used.
		 */
		value[0] = mult_frac((JC_IMU_PREC_RANGE_SCALE *
				      (imu_data[i].gyro_x -
				       ctlr->gyro_cal.offset[0])),
				     ctlr->gyro_cal.scale[0],
				     ctlr->imu_cal_gyro_divisor[0]);
		value[1] = mult_frac((JC_IMU_PREC_RANGE_SCALE *
				      (imu_data[i].gyro_y -
				       ctlr->gyro_cal.offset[1])),
				     ctlr->gyro_cal.scale[1],
				     ctlr->imu_cal_gyro_divisor[1]);
		value[2] = mult_frac((JC_IMU_PREC_RANGE_SCALE *
				      (imu_data[i].gyro_z -
				       ctlr->gyro_cal.offset[2])),
				     ctlr->gyro_cal.scale[2],
				     ctlr->imu_cal_gyro_divisor[2]);

		value[3] = ((s32)imu_data[i].accel_x *
			    ctlr->accel_cal.scale[0]) /
			    ctlr->imu_cal_accel_divisor[0];
		value[4] = ((s32)imu_data[i].accel_y *
			    ctlr->accel_cal.scale[1]) /
			    ctlr->imu_cal_accel_divisor[1];
		value[5] = ((s32)imu_data[i].accel_z *
			    ctlr->accel_cal.scale[2]) /
			    ctlr->imu_cal_accel_divisor[2];

		hid_dbg(ctlr->hdev, "raw_gyro: g_x=%d g_y=%d g_z=%d\n",
			imu_data[i].gyro_x, imu_data[i].gyro_y,
			imu_data[i].gyro_z);
		hid_dbg(ctlr->hdev, "raw_accel: a_x=%d a_y=%d a_z=%d\n",
			imu_data[i].accel_x, imu_data[i].accel_y,
			imu_data[i].accel_z);

		/*
		 * The right joy-con has 2 axes negated, Y and Z. This is due to
		 * the orientation of the IMU in the controller. We negate those
		 * axes' values in order to be consistent with the left joy-con
		 * and the pro controller:
		 *   X: positive is pointing toward the triggers
		 *   Y: positive is pointing to the left
		 *   Z: positive is pointing up (out of the buttons/sticks)
		 * The axes follow the right-hand rule.
		 */
		if (jc_type_is_joycon(ctlr) && jc_type_has_right(ctlr)) {
			int j;

			/* negate all but x axis */
			for (j = 1; j < 6; ++j) {
				if (j == 3)
					continue;
				value[j] *= -1;
			}
		}

		input_report_abs(idev, ABS_RX, value[0]);
		input_report_abs(idev, ABS_RY, value[1]);
		input_report_abs(idev, ABS_RZ, value[2]);
		input_report_abs(idev, ABS_X, value[3]);
		input_report_abs(idev, ABS_Y, value[4]);
		input_report_abs(idev, ABS_Z, value[5]);
		input_sync(idev);
		/* convert to micros and divide by 3 (3 samples per report). */
		ctlr->imu_timestamp_us += ctlr->imu_avg_delta_ms * 1000 / 3;
	}
}

static void joycon_handle_rumble_report(struct joycon_ctlr *ctlr, struct joycon_input_report *rep)
{
	unsigned long flags;
	unsigned long msecs = jiffies_to_msecs(jiffies);

	spin_lock_irqsave(&ctlr->lock, flags);
	if (IS_ENABLED(CONFIG_NINTENDO_FF) && rep->vibrator_report &&
	    ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED &&
	    (msecs - ctlr->rumble_msecs) >= JC_RUMBLE_PERIOD_MS &&
	    (ctlr->rumble_queue_head != ctlr->rumble_queue_tail ||
	     ctlr->rumble_zero_countdown > 0)) {
		/*
		 * When this value reaches 0, we know we've sent multiple
		 * packets to the controller instructing it to disable rumble.
		 * We can safely stop sending periodic rumble packets until the
		 * next ff effect.
		 */
		if (ctlr->rumble_zero_countdown > 0)
			ctlr->rumble_zero_countdown--;
		queue_work(ctlr->rumble_queue, &ctlr->rumble_worker);
	}

	spin_unlock_irqrestore(&ctlr->lock, flags);
}

static void joycon_parse_battery_status(struct joycon_ctlr *ctlr, struct joycon_input_report *rep)
{
	u8 tmp;
	unsigned long flags;

	spin_lock_irqsave(&ctlr->lock, flags);

	tmp = rep->bat_con;
	ctlr->host_powered = tmp & BIT(0);
	ctlr->battery_charging = tmp & BIT(4);
	tmp = tmp >> 5;

	switch (tmp) {
	case 0: /* empty */
		ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
		break;
	case 1: /* low */
		ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_LOW;
		break;
	case 2: /* medium */
		ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
		break;
	case 3: /* high */
		ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_HIGH;
		break;
	case 4: /* full */
		ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_FULL;
		break;
	default:
		ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;
		hid_warn(ctlr->hdev, "Invalid battery status\n");
		break;
	}

	spin_unlock_irqrestore(&ctlr->lock, flags);
}

static void joycon_report_left_stick(struct joycon_ctlr *ctlr,
				     struct joycon_input_report *rep)
{
	u16 raw_x;
	u16 raw_y;
	s32 x;
	s32 y;

	raw_x = hid_field_extract(ctlr->hdev, rep->left_stick, 0, 12);
	raw_y = hid_field_extract(ctlr->hdev, rep->left_stick + 1, 4, 12);

	x = joycon_map_stick_val(&ctlr->left_stick_cal_x, raw_x);
	y = -joycon_map_stick_val(&ctlr->left_stick_cal_y, raw_y);

	input_report_abs(ctlr->input, ABS_X, x);
	input_report_abs(ctlr->input, ABS_Y, y);
}

static void joycon_report_right_stick(struct joycon_ctlr *ctlr,
				      struct joycon_input_report *rep)
{
	u16 raw_x;
	u16 raw_y;
	s32 x;
	s32 y;

	raw_x = hid_field_extract(ctlr->hdev, rep->right_stick, 0, 12);
	raw_y = hid_field_extract(ctlr->hdev, rep->right_stick + 1, 4, 12);

	x = joycon_map_stick_val(&ctlr->right_stick_cal_x, raw_x);
	y = -joycon_map_stick_val(&ctlr->right_stick_cal_y, raw_y);

	input_report_abs(ctlr->input, ABS_RX, x);
	input_report_abs(ctlr->input, ABS_RY, y);
}

static void joycon_report_dpad(struct joycon_ctlr *ctlr,
			       struct joycon_input_report *rep)
{
	int hatx = 0;
	int haty = 0;
	u32 btns = hid_field_extract(ctlr->hdev, rep->button_status, 0, 24);

	if (btns & JC_BTN_LEFT)
		hatx = -1;
	else if (btns & JC_BTN_RIGHT)
		hatx = 1;

	if (btns & JC_BTN_UP)
		haty = -1;
	else if (btns & JC_BTN_DOWN)
		haty = 1;

	input_report_abs(ctlr->input, ABS_HAT0X, hatx);
	input_report_abs(ctlr->input, ABS_HAT0Y, haty);
}

static void joycon_report_buttons(struct joycon_ctlr *ctlr,
				  struct joycon_input_report *rep,
				  const struct joycon_ctlr_button_mapping button_mappings[])
{
	const struct joycon_ctlr_button_mapping *button;
	u32 status = hid_field_extract(ctlr->hdev, rep->button_status, 0, 24);

	for (button = button_mappings; button->code; button++)
		input_report_key(ctlr->input, button->code, status & button->bit);
}

static void joycon_parse_report(struct joycon_ctlr *ctlr,
				struct joycon_input_report *rep)
{
	unsigned long flags;
	unsigned long msecs = jiffies_to_msecs(jiffies);
	unsigned long report_delta_ms = msecs - ctlr->last_input_report_msecs;

	if (joycon_has_rumble(ctlr))
		joycon_handle_rumble_report(ctlr, rep);

	joycon_parse_battery_status(ctlr, rep);

	if (joycon_type_is_left_joycon(ctlr)) {
		joycon_report_left_stick(ctlr, rep);
		joycon_report_buttons(ctlr, rep, left_joycon_button_mappings);
		if (!joycon_device_is_chrggrip(ctlr))
			joycon_report_buttons(ctlr, rep, left_joycon_s_button_mappings);
	} else if (joycon_type_is_right_joycon(ctlr)) {
		joycon_report_right_stick(ctlr, rep);
		joycon_report_buttons(ctlr, rep, right_joycon_button_mappings);
		if (!joycon_device_is_chrggrip(ctlr))
			joycon_report_buttons(ctlr, rep, right_joycon_s_button_mappings);
	} else if (joycon_type_is_procon(ctlr)) {
		joycon_report_left_stick(ctlr, rep);
		joycon_report_right_stick(ctlr, rep);
		joycon_report_dpad(ctlr, rep);
		if (ctlr->hdev->vendor == USB_VENDOR_ID_HORI)
			joycon_report_buttons(ctlr, rep, lic_hori_procon_button_mappings);
		else
			joycon_report_buttons(ctlr, rep, procon_button_mappings);
	} else if (joycon_type_is_any_nescon(ctlr)) {
		joycon_report_dpad(ctlr, rep);
		joycon_report_buttons(ctlr, rep, nescon_button_mappings);
	} else if (joycon_type_is_snescon(ctlr)) {
		joycon_report_dpad(ctlr, rep);
		joycon_report_buttons(ctlr, rep, snescon_button_mappings);
	} else if (joycon_type_is_gencon(ctlr)) {
		joycon_report_dpad(ctlr, rep);
		joycon_report_buttons(ctlr, rep, gencon_button_mappings);
	} else if (joycon_type_is_n64con(ctlr)) {
		joycon_report_left_stick(ctlr, rep);
		joycon_report_dpad(ctlr, rep);
		joycon_report_buttons(ctlr, rep, n64con_button_mappings);
	}

	input_sync(ctlr->input);

	spin_lock_irqsave(&ctlr->lock, flags);
	ctlr->last_input_report_msecs = msecs;
	/*
	 * Was this input report a reasonable time delta compared to the prior
	 * report? We use this information to decide when a safe time is to send
	 * rumble packets or subcommand packets.
	 */
	if (report_delta_ms >= JC_INPUT_REPORT_MIN_DELTA &&
	    report_delta_ms <= JC_INPUT_REPORT_MAX_DELTA) {
		if (ctlr->consecutive_valid_report_deltas < JC_SUBCMD_VALID_DELTA_REQ)
			ctlr->consecutive_valid_report_deltas++;
	} else {
		ctlr->consecutive_valid_report_deltas = 0;
	}
	/*
	 * Our consecutive valid report tracking is only relevant for
	 * bluetooth-connected controllers. For USB devices, we're beholden to
	 * USB's underlying polling rate anyway. Always set to the consecutive
	 * delta requirement.
	 */
	if (ctlr->hdev->bus == BUS_USB)
		ctlr->consecutive_valid_report_deltas = JC_SUBCMD_VALID_DELTA_REQ;

	spin_unlock_irqrestore(&ctlr->lock, flags);

	/*
	 * Immediately after receiving a report is the most reliable time to
	 * send a subcommand to the controller. Wake any subcommand senders
	 * waiting for a report.
	 */
	if (unlikely(mutex_is_locked(&ctlr->output_mutex))) {
		spin_lock_irqsave(&ctlr->lock, flags);
		ctlr->received_input_report = true;
		spin_unlock_irqrestore(&ctlr->lock, flags);
		wake_up(&ctlr->wait);
	}

	/* parse IMU data if present */
	if ((rep->id == JC_INPUT_IMU_DATA) && joycon_has_imu(ctlr))
		joycon_parse_imu_report(ctlr, rep);
}

static int joycon_send_rumble_data(struct joycon_ctlr *ctlr)
{
	int ret;
	unsigned long flags;
	struct joycon_rumble_output rumble_output = { 0 };

	spin_lock_irqsave(&ctlr->lock, flags);
	/*
	 * If the controller has been removed, just return ENODEV so the LED
	 * subsystem doesn't print invalid errors on removal.
	 */
	if (ctlr->ctlr_state == JOYCON_CTLR_STATE_REMOVED) {
		spin_unlock_irqrestore(&ctlr->lock, flags);
		return -ENODEV;
	}
	memcpy(rumble_output.rumble_data,
	       ctlr->rumble_data[ctlr->rumble_queue_tail],
	       JC_RUMBLE_DATA_SIZE);
	spin_unlock_irqrestore(&ctlr->lock, flags);

	rumble_output.output_id = JC_OUTPUT_RUMBLE_ONLY;
	rumble_output.packet_num = ctlr->subcmd_num;
	if (++ctlr->subcmd_num > 0xF)
		ctlr->subcmd_num = 0;

	joycon_enforce_subcmd_rate(ctlr);

	ret = __joycon_hid_send(ctlr->hdev, (u8 *)&rumble_output,
				sizeof(rumble_output));
	return ret;
}

static void joycon_rumble_worker(struct work_struct *work)
{
	struct joycon_ctlr *ctlr = container_of(work, struct joycon_ctlr,
							rumble_worker);
	unsigned long flags;
	bool again = true;
	int ret;

	while (again) {
		mutex_lock(&ctlr->output_mutex);
		ret = joycon_send_rumble_data(ctlr);
		mutex_unlock(&ctlr->output_mutex);

		/* -ENODEV means the controller was just unplugged */
		spin_lock_irqsave(&ctlr->lock, flags);
		if (ret < 0 && ret != -ENODEV &&
		    ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED)
			hid_warn(ctlr->hdev, "Failed to set rumble; e=%d", ret);

		ctlr->rumble_msecs = jiffies_to_msecs(jiffies);
		if (ctlr->rumble_queue_tail != ctlr->rumble_queue_head) {
			if (++ctlr->rumble_queue_tail >= JC_RUMBLE_QUEUE_SIZE)
				ctlr->rumble_queue_tail = 0;
		} else {
			again = false;
		}
		spin_unlock_irqrestore(&ctlr->lock, flags);
	}
}

#if IS_ENABLED(CONFIG_NINTENDO_FF)
static struct joycon_rumble_freq_data joycon_find_rumble_freq(u16 freq)
{
	const size_t length = ARRAY_SIZE(joycon_rumble_frequencies);
	const struct joycon_rumble_freq_data *data = joycon_rumble_frequencies;
	int i = 0;

	if (freq > data[0].freq) {
		for (i = 1; i < length - 1; i++) {
			if (freq > data[i - 1].freq && freq <= data[i].freq)
				break;
		}
	}

	return data[i];
}

static struct joycon_rumble_amp_data joycon_find_rumble_amp(u16 amp)
{
	const size_t length = ARRAY_SIZE(joycon_rumble_amplitudes);
	const struct joycon_rumble_amp_data *data = joycon_rumble_amplitudes;
	int i = 0;

	if (amp > data[0].amp) {
		for (i = 1; i < length - 1; i++) {
			if (amp > data[i - 1].amp && amp <= data[i].amp)
				break;
		}
	}

	return data[i];
}

static void joycon_encode_rumble(u8 *data, u16 freq_low, u16 freq_high, u16 amp)
{
	struct joycon_rumble_freq_data freq_data_low;
	struct joycon_rumble_freq_data freq_data_high;
	struct joycon_rumble_amp_data amp_data;

	freq_data_low = joycon_find_rumble_freq(freq_low);
	freq_data_high = joycon_find_rumble_freq(freq_high);
	amp_data = joycon_find_rumble_amp(amp);

	data[0] = (freq_data_high.high >> 8) & 0xFF;
	data[1] = (freq_data_high.high & 0xFF) + amp_data.high;
	data[2] = freq_data_low.low + ((amp_data.low >> 8) & 0xFF);
	data[3] = amp_data.low & 0xFF;
}

static const u16 JOYCON_MAX_RUMBLE_HIGH_FREQ	= 1253;
static const u16 JOYCON_MIN_RUMBLE_HIGH_FREQ	= 82;
static const u16 JOYCON_MAX_RUMBLE_LOW_FREQ	= 626;
static const u16 JOYCON_MIN_RUMBLE_LOW_FREQ	= 41;

static void joycon_clamp_rumble_freqs(struct joycon_ctlr *ctlr)
{
	unsigned long flags;

	spin_lock_irqsave(&ctlr->lock, flags);
	ctlr->rumble_ll_freq = clamp(ctlr->rumble_ll_freq,
				     JOYCON_MIN_RUMBLE_LOW_FREQ,
				     JOYCON_MAX_RUMBLE_LOW_FREQ);
	ctlr->rumble_lh_freq = clamp(ctlr->rumble_lh_freq,
				     JOYCON_MIN_RUMBLE_HIGH_FREQ,
				     JOYCON_MAX_RUMBLE_HIGH_FREQ);
	ctlr->rumble_rl_freq = clamp(ctlr->rumble_rl_freq,
				     JOYCON_MIN_RUMBLE_LOW_FREQ,
				     JOYCON_MAX_RUMBLE_LOW_FREQ);
	ctlr->rumble_rh_freq = clamp(ctlr->rumble_rh_freq,
				     JOYCON_MIN_RUMBLE_HIGH_FREQ,
				     JOYCON_MAX_RUMBLE_HIGH_FREQ);
	spin_unlock_irqrestore(&ctlr->lock, flags);
}

static int joycon_set_rumble(struct joycon_ctlr *ctlr, u16 amp_r, u16 amp_l,
			     bool schedule_now)
{
	u8 data[JC_RUMBLE_DATA_SIZE];
	u16 amp;
	u16 freq_r_low;
	u16 freq_r_high;
	u16 freq_l_low;
	u16 freq_l_high;
	unsigned long flags;
	int next_rq_head;

	spin_lock_irqsave(&ctlr->lock, flags);
	freq_r_low = ctlr->rumble_rl_freq;
	freq_r_high = ctlr->rumble_rh_freq;
	freq_l_low = ctlr->rumble_ll_freq;
	freq_l_high = ctlr->rumble_lh_freq;
	/* limit number of silent rumble packets to reduce traffic */
	if (amp_l != 0 || amp_r != 0)
		ctlr->rumble_zero_countdown = JC_RUMBLE_ZERO_AMP_PKT_CNT;
	spin_unlock_irqrestore(&ctlr->lock, flags);

	/* right joy-con */
	amp = amp_r * (u32)joycon_max_rumble_amp / 65535;
	joycon_encode_rumble(data + 4, freq_r_low, freq_r_high, amp);

	/* left joy-con */
	amp = amp_l * (u32)joycon_max_rumble_amp / 65535;
	joycon_encode_rumble(data, freq_l_low, freq_l_high, amp);

	spin_lock_irqsave(&ctlr->lock, flags);

	next_rq_head = ctlr->rumble_queue_head + 1;
	if (next_rq_head >= JC_RUMBLE_QUEUE_SIZE)
		next_rq_head = 0;

	/* Did we overrun the circular buffer?
	 * If so, be sure we keep the latest intended rumble state.
	 */
	if (next_rq_head == ctlr->rumble_queue_tail) {
		hid_dbg(ctlr->hdev, "rumble queue is full");
		/* overwrite the prior value at the end of the circular buf */
		next_rq_head = ctlr->rumble_queue_head;
	}

	ctlr->rumble_queue_head = next_rq_head;
	memcpy(ctlr->rumble_data[ctlr->rumble_queue_head], data,
	       JC_RUMBLE_DATA_SIZE);

	/* don't wait for the periodic send (reduces latency) */
	if (schedule_now && ctlr->ctlr_state != JOYCON_CTLR_STATE_REMOVED)
		queue_work(ctlr->rumble_queue, &ctlr->rumble_worker);

	spin_unlock_irqrestore(&ctlr->lock, flags);

	return 0;
}

static int joycon_play_effect(struct input_dev *dev, void *data,
						     struct ff_effect *effect)
{
	struct joycon_ctlr *ctlr = input_get_drvdata(dev);

	if (effect->type != FF_RUMBLE)
		return 0;

	return joycon_set_rumble(ctlr,
				 effect->u.rumble.weak_magnitude,
				 effect->u.rumble.strong_magnitude,
				 true);
}
#endif /* IS_ENABLED(CONFIG_NINTENDO_FF) */

static void joycon_config_left_stick(struct input_dev *idev)
{
	input_set_abs_params(idev,
			     ABS_X,
			     -JC_MAX_STICK_MAG,
			     JC_MAX_STICK_MAG,
			     JC_STICK_FUZZ,
			     JC_STICK_FLAT);
	input_set_abs_params(idev,
			     ABS_Y,
			     -JC_MAX_STICK_MAG,
			     JC_MAX_STICK_MAG,
			     JC_STICK_FUZZ,
			     JC_STICK_FLAT);
}

static void joycon_config_right_stick(struct input_dev *idev)
{
	input_set_abs_params(idev,
			     ABS_RX,
			     -JC_MAX_STICK_MAG,
			     JC_MAX_STICK_MAG,
			     JC_STICK_FUZZ,
			     JC_STICK_FLAT);
	input_set_abs_params(idev,
			     ABS_RY,
			     -JC_MAX_STICK_MAG,
			     JC_MAX_STICK_MAG,
			     JC_STICK_FUZZ,
			     JC_STICK_FLAT);
}

static void joycon_config_dpad(struct input_dev *idev)
{
	input_set_abs_params(idev,
			     ABS_HAT0X,
			     -JC_MAX_DPAD_MAG,
			     JC_MAX_DPAD_MAG,
			     JC_DPAD_FUZZ,
			     JC_DPAD_FLAT);
	input_set_abs_params(idev,
			     ABS_HAT0Y,
			     -JC_MAX_DPAD_MAG,
			     JC_MAX_DPAD_MAG,
			     JC_DPAD_FUZZ,
			     JC_DPAD_FLAT);
}

static void joycon_config_buttons(struct input_dev *idev,
		 const struct joycon_ctlr_button_mapping button_mappings[])
{
	const struct joycon_ctlr_button_mapping *button;

	for (button = button_mappings; button->code; button++)
		input_set_capability(idev, EV_KEY, button->code);
}

static void joycon_config_rumble(struct joycon_ctlr *ctlr)
{
#if IS_ENABLED(CONFIG_NINTENDO_FF)
	/* set up rumble */
	input_set_capability(ctlr->input, EV_FF, FF_RUMBLE);
	input_ff_create_memless(ctlr->input, NULL, joycon_play_effect);
	ctlr->rumble_ll_freq = JC_RUMBLE_DFLT_LOW_FREQ;
	ctlr->rumble_lh_freq = JC_RUMBLE_DFLT_HIGH_FREQ;
	ctlr->rumble_rl_freq = JC_RUMBLE_DFLT_LOW_FREQ;
	ctlr->rumble_rh_freq = JC_RUMBLE_DFLT_HIGH_FREQ;
	joycon_clamp_rumble_freqs(ctlr);
	joycon_set_rumble(ctlr, 0, 0, false);
	ctlr->rumble_msecs = jiffies_to_msecs(jiffies);
#endif
}

static int joycon_imu_input_create(struct joycon_ctlr *ctlr)
{
	struct hid_device *hdev;
	const char *imu_name;
	int ret;

	hdev = ctlr->hdev;

	/* configure the imu input device */
	ctlr->imu_input = devm_input_allocate_device(&hdev->dev);
	if (!ctlr->imu_input)
		return -ENOMEM;

	ctlr->imu_input->id.bustype = hdev->bus;
	ctlr->imu_input->id.vendor = hdev->vendor;
	ctlr->imu_input->id.product = hdev->product;
	ctlr->imu_input->id.version = hdev->version;
	ctlr->imu_input->uniq = ctlr->mac_addr_str;
	ctlr->imu_input->phys = hdev->phys;

	imu_name = devm_kasprintf(&hdev->dev, GFP_KERNEL, "%s (IMU)", ctlr->input->name);
	if (!imu_name)
		return -ENOMEM;

	ctlr->imu_input->name = imu_name;

	input_set_drvdata(ctlr->imu_input, ctlr);

	/* configure imu axes */
	input_set_abs_params(ctlr->imu_input, ABS_X,
			     -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG,
			     JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT);
	input_set_abs_params(ctlr->imu_input, ABS_Y,
			     -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG,
			     JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT);
	input_set_abs_params(ctlr->imu_input, ABS_Z,
			     -JC_IMU_MAX_ACCEL_MAG, JC_IMU_MAX_ACCEL_MAG,
			     JC_IMU_ACCEL_FUZZ, JC_IMU_ACCEL_FLAT);
	input_abs_set_res(ctlr->imu_input, ABS_X, JC_IMU_ACCEL_RES_PER_G);
	input_abs_set_res(ctlr->imu_input, ABS_Y, JC_IMU_ACCEL_RES_PER_G);
	input_abs_set_res(ctlr->imu_input, ABS_Z, JC_IMU_ACCEL_RES_PER_G);

	input_set_abs_params(ctlr->imu_input, ABS_RX,
			     -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG,
			     JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT);
	input_set_abs_params(ctlr->imu_input, ABS_RY,
			     -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG,
			     JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT);
	input_set_abs_params(ctlr->imu_input, ABS_RZ,
			     -JC_IMU_MAX_GYRO_MAG, JC_IMU_MAX_GYRO_MAG,
			     JC_IMU_GYRO_FUZZ, JC_IMU_GYRO_FLAT);

	input_abs_set_res(ctlr->imu_input, ABS_RX, JC_IMU_GYRO_RES_PER_DPS);
	input_abs_set_res(ctlr->imu_input, ABS_RY, JC_IMU_GYRO_RES_PER_DPS);
	input_abs_set_res(ctlr->imu_input, ABS_RZ, JC_IMU_GYRO_RES_PER_DPS);

	__set_bit(EV_MSC, ctlr->imu_input->evbit);
	__set_bit(MSC_TIMESTAMP, ctlr->imu_input->mscbit);
	__set_bit(INPUT_PROP_ACCELEROMETER, ctlr->imu_input->propbit);

	ret = input_register_device(ctlr->imu_input);
	if (ret)
		return ret;

	return 0;
}

static int joycon_input_create(struct joycon_ctlr *ctlr)
{
	struct hid_device *hdev;
	int ret;

	hdev = ctlr->hdev;

	ctlr->input = devm_input_allocate_device(&hdev->dev);
	if (!ctlr->input)
		return -ENOMEM;
	ctlr->input->id.bustype = hdev->bus;
	ctlr->input->id.vendor = hdev->vendor;
	ctlr->input->id.product = hdev->product;
	ctlr->input->id.version = hdev->version;
	ctlr->input->uniq = ctlr->mac_addr_str;
	ctlr->input->name = hdev->name;
	ctlr->input->phys = hdev->phys;
	input_set_drvdata(ctlr->input, ctlr);

	if (joycon_type_is_right_joycon(ctlr)) {
		joycon_config_right_stick(ctlr->input);
		joycon_config_buttons(ctlr->input, right_joycon_button_mappings);
		if (!joycon_device_is_chrggrip(ctlr))
			joycon_config_buttons(ctlr->input, right_joycon_s_button_mappings);
	} else if (joycon_type_is_left_joycon(ctlr)) {
		joycon_config_left_stick(ctlr->input);
		joycon_config_buttons(ctlr->input, left_joycon_button_mappings);
		if (!joycon_device_is_chrggrip(ctlr))
			joycon_config_buttons(ctlr->input, left_joycon_s_button_mappings);
	} else if (joycon_type_is_procon(ctlr)) {
		joycon_config_left_stick(ctlr->input);
		joycon_config_right_stick(ctlr->input);
		joycon_config_dpad(ctlr->input);
		if (ctlr->hdev->vendor == USB_VENDOR_ID_HORI)
			joycon_config_buttons(ctlr->input, lic_hori_procon_button_mappings);
		else
			joycon_config_buttons(ctlr->input, procon_button_mappings);
	} else if (joycon_type_is_any_nescon(ctlr)) {
		joycon_config_dpad(ctlr->input);
		joycon_config_buttons(ctlr->input, nescon_button_mappings);
	} else if (joycon_type_is_snescon(ctlr)) {
		joycon_config_dpad(ctlr->input);
		joycon_config_buttons(ctlr->input, snescon_button_mappings);
	} else if (joycon_type_is_gencon(ctlr)) {
		joycon_config_dpad(ctlr->input);
		joycon_config_buttons(ctlr->input, gencon_button_mappings);
	} else if (joycon_type_is_n64con(ctlr)) {
		joycon_config_dpad(ctlr->input);
		joycon_config_left_stick(ctlr->input);
		joycon_config_buttons(ctlr->input, n64con_button_mappings);
	}

	if (joycon_has_imu(ctlr)) {
		ret = joycon_imu_input_create(ctlr);
		if (ret)
			return ret;
	}

	if (joycon_has_rumble(ctlr))
		joycon_config_rumble(ctlr);

	ret = input_register_device(ctlr->input);
	if (ret)
		return ret;

	return 0;
}

/* Because the subcommand sets all the leds at once, the brightness argument is ignored */
static int joycon_player_led_brightness_set(struct led_classdev *led,
					    enum led_brightness brightness)
{
	struct device *dev = led->dev->parent;
	struct hid_device *hdev = to_hid_device(dev);
	struct joycon_ctlr *ctlr;
	int val = 0;
	int i;
	int ret;

	ctlr = hid_get_drvdata(hdev);
	if (!ctlr) {
		hid_err(hdev, "No controller data\n");
		return -ENODEV;
	}

	for (i = 0; i < JC_NUM_LEDS; i++)
		val |= ctlr->leds[i].brightness << i;

	mutex_lock(&ctlr->output_mutex);
	ret = joycon_set_player_leds(ctlr, 0, val);
	mutex_unlock(&ctlr->output_mutex);

	return ret;
}

static int joycon_home_led_brightness_set(struct led_classdev *led,
					  enum led_brightness brightness)
{
	struct device *dev = led->dev->parent;
	struct hid_device *hdev = to_hid_device(dev);
	struct joycon_ctlr *ctlr;
	int ret;

	ctlr = hid_get_drvdata(hdev);
	if (!ctlr) {
		hid_err(hdev, "No controller data\n");
		return -ENODEV;
	}
	mutex_lock(&ctlr->output_mutex);
	ret = joycon_set_home_led(ctlr, brightness);
	mutex_unlock(&ctlr->output_mutex);
	return ret;
}

static DEFINE_IDA(nintendo_player_id_allocator);

static int joycon_leds_create(struct joycon_ctlr *ctlr)
{
	struct hid_device *hdev = ctlr->hdev;
	struct device *dev = &hdev->dev;
	const char *d_name = dev_name(dev);
	struct led_classdev *led;
	int led_val = 0;
	char *name;
	int ret;
	int i;
	int player_led_pattern;

	/* configure the player LEDs */
	ctlr->player_id = U32_MAX;
	ret = ida_alloc(&nintendo_player_id_allocator, GFP_KERNEL);
	if (ret < 0) {
		hid_warn(hdev, "Failed to allocate player ID, skipping; ret=%d\n", ret);
		goto home_led;
	}
	ctlr->player_id = ret;
	player_led_pattern = ret % JC_NUM_LED_PATTERNS;
	hid_info(ctlr->hdev, "assigned player %d led pattern", player_led_pattern + 1);

	for (i = 0; i < JC_NUM_LEDS; i++) {
		name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s",
				      d_name,
				      "green",
				      joycon_player_led_names[i]);
		if (!name)
			return -ENOMEM;

		led = &ctlr->leds[i];
		led->name = name;
		led->brightness = joycon_player_led_patterns[player_led_pattern][i];
		led->max_brightness = 1;
		led->brightness_set_blocking =
					joycon_player_led_brightness_set;
		led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE;

		led_val |= joycon_player_led_patterns[player_led_pattern][i] << i;
	}
	mutex_lock(&ctlr->output_mutex);
	ret = joycon_set_player_leds(ctlr, 0, led_val);
	mutex_unlock(&ctlr->output_mutex);
	if (ret) {
		hid_warn(hdev, "Failed to set players LEDs, skipping registration; ret=%d\n", ret);
		goto home_led;
	}

	for (i = 0; i < JC_NUM_LEDS; i++) {
		led = &ctlr->leds[i];
		ret = devm_led_classdev_register(&hdev->dev, led);
		if (ret) {
			hid_err(hdev, "Failed to register player %d LED; ret=%d\n", i + 1, ret);
			return ret;
		}
	}

home_led:
	/* configure the home LED */
	if (jc_type_has_right(ctlr)) {
		name = devm_kasprintf(dev, GFP_KERNEL, "%s:%s:%s",
				      d_name,
				      "blue",
				      LED_FUNCTION_PLAYER5);
		if (!name)
			return -ENOMEM;

		led = &ctlr->home_led;
		led->name = name;
		led->brightness = 0;
		led->max_brightness = 0xF;
		led->brightness_set_blocking = joycon_home_led_brightness_set;
		led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE;

		/* Set the home LED to 0 as default state */
		mutex_lock(&ctlr->output_mutex);
		ret = joycon_set_home_led(ctlr, 0);
		mutex_unlock(&ctlr->output_mutex);
		if (ret) {
			hid_warn(hdev, "Failed to set home LED, skipping registration; ret=%d\n", ret);
			return 0;
		}

		ret = devm_led_classdev_register(&hdev->dev, led);
		if (ret) {
			hid_err(hdev, "Failed to register home LED; ret=%d\n", ret);
			return ret;
		}
	}

	return 0;
}

static int joycon_battery_get_property(struct power_supply *supply,
				       enum power_supply_property prop,
				       union power_supply_propval *val)
{
	struct joycon_ctlr *ctlr = power_supply_get_drvdata(supply);
	unsigned long flags;
	int ret = 0;
	u8 capacity;
	bool charging;
	bool powered;

	spin_lock_irqsave(&ctlr->lock, flags);
	capacity = ctlr->battery_capacity;
	charging = ctlr->battery_charging;
	powered = ctlr->host_powered;
	spin_unlock_irqrestore(&ctlr->lock, flags);

	switch (prop) {
	case POWER_SUPPLY_PROP_PRESENT:
		val->intval = 1;
		break;
	case POWER_SUPPLY_PROP_SCOPE:
		val->intval = POWER_SUPPLY_SCOPE_DEVICE;
		break;
	case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
		val->intval = capacity;
		break;
	case POWER_SUPPLY_PROP_STATUS:
		if (charging)
			val->intval = POWER_SUPPLY_STATUS_CHARGING;
		else if (capacity == POWER_SUPPLY_CAPACITY_LEVEL_FULL &&
			 powered)
			val->intval = POWER_SUPPLY_STATUS_FULL;
		else
			val->intval = POWER_SUPPLY_STATUS_DISCHARGING;
		break;
	default:
		ret = -EINVAL;
		break;
	}
	return ret;
}

static enum power_supply_property joycon_battery_props[] = {
	POWER_SUPPLY_PROP_PRESENT,
	POWER_SUPPLY_PROP_CAPACITY_LEVEL,
	POWER_SUPPLY_PROP_SCOPE,
	POWER_SUPPLY_PROP_STATUS,
};

static int joycon_power_supply_create(struct joycon_ctlr *ctlr)
{
	struct hid_device *hdev = ctlr->hdev;
	struct power_supply_config supply_config = { .drv_data = ctlr, };
	const char * const name_fmt = "nintendo_switch_controller_battery_%s";
	int ret = 0;

	/* Set initially to unknown before receiving first input report */
	ctlr->battery_capacity = POWER_SUPPLY_CAPACITY_LEVEL_UNKNOWN;

	/* Configure the battery's description */
	ctlr->battery_desc.properties = joycon_battery_props;
	ctlr->battery_desc.num_properties =
					ARRAY_SIZE(joycon_battery_props);
	ctlr->battery_desc.get_property = joycon_battery_get_property;
	ctlr->battery_desc.type = POWER_SUPPLY_TYPE_BATTERY;
	ctlr->battery_desc.use_for_apm = 0;
	ctlr->battery_desc.name = devm_kasprintf(&hdev->dev, GFP_KERNEL,
						 name_fmt,
						 dev_name(&hdev->dev));
	if (!ctlr->battery_desc.name)
		return -ENOMEM;

	ctlr->battery = devm_power_supply_register(&hdev->dev,
						   &ctlr->battery_desc,
						   &supply_config);
	if (IS_ERR(ctlr->battery)) {
		ret = PTR_ERR(ctlr->battery);
		hid_err(hdev, "Failed to register battery; ret=%d\n", ret);
		return ret;
	}

	return power_supply_powers(ctlr->battery, &hdev->dev);
}

static int joycon_read_info(struct joycon_ctlr *ctlr)
{
	int ret;
	int i;
	int j;
	struct joycon_subcmd_request req = { 0 };
	struct joycon_input_report *report;

	req.subcmd_id = JC_SUBCMD_REQ_DEV_INFO;
	ret = joycon_send_subcmd(ctlr, &req, 0, 2 * HZ);
	if (ret) {
		hid_err(ctlr->hdev, "Failed to get joycon info; ret=%d\n", ret);
		return ret;
	}

	report = (struct joycon_input_report *)ctlr->input_buf;

	for (i = 4, j = 0; j < 6; i++, j++)
		ctlr->mac_addr[j] = report->subcmd_reply.data[i];

	ctlr->mac_addr_str = devm_kasprintf(&ctlr->hdev->dev, GFP_KERNEL, "%pMU",
					    ctlr->mac_addr);
	if (!ctlr->mac_addr_str)
		return -ENOMEM;
	hid_info(ctlr->hdev, "controller MAC = %s\n", ctlr->mac_addr_str);

	/*
	 * Retrieve the type so we can distinguish the controller type
	 * Unfortantly the hdev->product can't always be used due to a ?bug?
	 * with the NSO Genesis controller. Over USB, it will report the
	 * PID as 0x201E, but over bluetooth it will report the PID as 0x2017
	 * which is the same as the NSO SNES controller. This is different from
	 * the rest of the controllers which will report the same PID over USB
	 * and bluetooth.
	 */
	ctlr->ctlr_type = report->subcmd_reply.data[2];
	hid_dbg(ctlr->hdev, "controller type = 0x%02X\n", ctlr->ctlr_type);

	return 0;
}

static int joycon_init(struct hid_device *hdev)
{
	struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
	int ret = 0;

	mutex_lock(&ctlr->output_mutex);
	/* if handshake command fails, assume ble pro controller */
	if (joycon_using_usb(ctlr) && !joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ)) {
		hid_dbg(hdev, "detected USB controller\n");
		/* set baudrate for improved latency */
		ret = joycon_send_usb(ctlr, JC_USB_CMD_BAUDRATE_3M, HZ);
		if (ret) {
			/*
			 * We can function with the default baudrate.
			 * Provide a warning, and continue on.
			 */
			hid_warn(hdev, "Failed to set baudrate (ret=%d), continuing anyway\n", ret);
		}
		/* handshake */
		ret = joycon_send_usb(ctlr, JC_USB_CMD_HANDSHAKE, HZ);
		if (ret) {
			hid_err(hdev, "Failed handshake; ret=%d\n", ret);
			goto out_unlock;
		}
		/*
		 * Set no timeout (to keep controller in USB mode).
		 * This doesn't send a response, so ignore the timeout.
		 */
		joycon_send_usb(ctlr, JC_USB_CMD_NO_TIMEOUT, HZ/10);
	} else if (jc_type_is_chrggrip(ctlr)) {
		hid_err(hdev, "Failed charging grip handshake\n");
		ret = -ETIMEDOUT;
		goto out_unlock;
	}

	/* needed to retrieve the controller type */
	ret = joycon_read_info(ctlr);
	if (ret) {
		hid_err(hdev, "Failed to retrieve controller info; ret=%d\n",
			ret);
		goto out_unlock;
	}

	if (joycon_has_joysticks(ctlr)) {
		/* get controller calibration data, and parse it */
		if (ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO) {
			/*
			 * Licensed controllers may have incompatible SPI flash
			 * layouts. Use default calibration values.
			 */
			hid_info(hdev, "using default cal for licensed controller\n");
			joycon_use_default_calibration(hdev,
						       &ctlr->left_stick_cal_x,
						       &ctlr->left_stick_cal_y,
						       "left", 0);
			joycon_use_default_calibration(hdev,
						       &ctlr->right_stick_cal_x,
						       &ctlr->right_stick_cal_y,
						       "right", 0);
		} else {
			ret = joycon_request_calibration(ctlr);
			if (ret) {
				/*
				 * We can function with default calibration, but
				 * it may be inaccurate. Provide a warning, and
				 * continue on.
				 */
				hid_warn(hdev, "Analog stick positions may be inaccurate\n");
			}
		}
	}

	if (joycon_has_imu(ctlr)) {
		/* get IMU calibration data, and parse it */
		ret = joycon_request_imu_calibration(ctlr);
		if (ret) {
			/*
			 * We can function with default calibration, but it may be
			 * inaccurate. Provide a warning, and continue on.
			 */
			hid_warn(hdev, "Unable to read IMU calibration data\n");
		}

		/* Enable the IMU */
		ret = joycon_enable_imu(ctlr);
		if (ret) {
			if (ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO) {
				hid_dbg(hdev, "IMU enable failed for licensed controller, continuing\n");
				ret = 0;
			} else {
				hid_err(hdev, "Failed to enable the IMU; ret=%d\n", ret);
				goto out_unlock;
			}
		}
	}

	/* Set the reporting mode to 0x30, which is the full report mode */
	ret = joycon_set_report_mode(ctlr);
	if (ret) {
		hid_err(hdev, "Failed to set report mode; ret=%d\n", ret);
		goto out_unlock;
	}

	if (joycon_has_rumble(ctlr)) {
		/* Enable rumble */
		ret = joycon_enable_rumble(ctlr);
		if (ret) {
			if (ctlr->ctlr_type == JOYCON_CTLR_TYPE_LIC_PRO) {
				hid_dbg(hdev, "rumble enable failed for licensed controller, continuing\n");
				ret = 0;
			} else {
				hid_err(hdev, "Failed to enable rumble; ret=%d\n", ret);
				goto out_unlock;
			}
		}
	}

out_unlock:
	mutex_unlock(&ctlr->output_mutex);
	return ret;
}

/* Common handler for parsing inputs */
static int joycon_ctlr_read_handler(struct joycon_ctlr *ctlr, u8 *data,
							      int size)
{
	if (data[0] == JC_INPUT_SUBCMD_REPLY || data[0] == JC_INPUT_IMU_DATA ||
	    data[0] == JC_INPUT_MCU_DATA) {
		/*
		 * The whole struct is cast and parsed below, including the
		 * IMU/subcmd union, not just the 12-byte partial header this
		 * used to check for.
		 */
		if (size >= sizeof(struct joycon_input_report))
			joycon_parse_report(ctlr,
					    (struct joycon_input_report *)data);
	}

	return 0;
}

static int joycon_ctlr_handle_event(struct joycon_ctlr *ctlr, u8 *data,
							      int size)
{
	int ret = 0;
	bool match = false;
	struct joycon_input_report *report;

	if (unlikely(mutex_is_locked(&ctlr->output_mutex)) &&
	    ctlr->msg_type != JOYCON_MSG_TYPE_NONE) {
		switch (ctlr->msg_type) {
		case JOYCON_MSG_TYPE_USB:
			if (size < 2)
				break;
			if (data[0] == JC_INPUT_USB_RESPONSE &&
			    data[1] == ctlr->usb_ack_match)
				match = true;
			break;
		case JOYCON_MSG_TYPE_SUBCMD:
			if (size < sizeof(struct joycon_input_report) ||
			    data[0] != JC_INPUT_SUBCMD_REPLY)
				break;
			report = (struct joycon_input_report *)data;
			if (report->subcmd_reply.id == ctlr->subcmd_ack_match)
				match = true;
			break;
		default:
			break;
		}

		if (match) {
			memcpy(ctlr->input_buf, data,
			       min(size, (int)JC_MAX_RESP_SIZE));
			ctlr->msg_type = JOYCON_MSG_TYPE_NONE;
			ctlr->received_resp = true;
			wake_up(&ctlr->wait);

			/* This message has been handled */
			return 1;
		}
	}

	if (ctlr->ctlr_state == JOYCON_CTLR_STATE_READ)
		ret = joycon_ctlr_read_handler(ctlr, data, size);

	return ret;
}

static int joycon_event(struct hid_device *hdev,
			      struct hid_report *report, u8 *raw_data, int size)
{
	struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);

	if (size < 1)
		return -EINVAL;

	return joycon_ctlr_handle_event(ctlr, raw_data, size);
}

static int joycon_probe(struct hid_device *hdev,
			    const struct hid_device_id *id)
{
	int ret;
	struct joycon_ctlr *ctlr;

	hid_dbg(hdev, "probe - start\n");

	ctlr = devm_kzalloc(&hdev->dev, sizeof(*ctlr), GFP_KERNEL);
	if (!ctlr) {
		ret = -ENOMEM;
		goto err;
	}

	ctlr->hdev = hdev;
	ctlr->ctlr_state = JOYCON_CTLR_STATE_INIT;
	ctlr->rumble_queue_head = 0;
	ctlr->rumble_queue_tail = 0;
	hid_set_drvdata(hdev, ctlr);
	mutex_init(&ctlr->output_mutex);
	init_waitqueue_head(&ctlr->wait);
	spin_lock_init(&ctlr->lock);
	ctlr->rumble_queue = alloc_workqueue("hid-nintendo-rumble_wq",
					     WQ_FREEZABLE | WQ_MEM_RECLAIM | WQ_PERCPU,
					     0);
	if (!ctlr->rumble_queue) {
		ret = -ENOMEM;
		goto err;
	}
	INIT_WORK(&ctlr->rumble_worker, joycon_rumble_worker);

	ret = hid_parse(hdev);
	if (ret) {
		hid_err(hdev, "HID parse failed\n");
		goto err_wq;
	}

	/*
	 * Patch the hw version of pro controller/joycons, so applications can
	 * distinguish between the default HID mappings and the mappings defined
	 * by the Linux game controller spec. This is important for the SDL2
	 * library, which has a game controller database, which uses device ids
	 * in combination with version as a key.
	 */
	hdev->version |= 0x8000;

	ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
	if (ret) {
		hid_err(hdev, "HW start failed\n");
		goto err_wq;
	}

	ret = hid_hw_open(hdev);
	if (ret) {
		hid_err(hdev, "cannot start hardware I/O\n");
		goto err_stop;
	}

	hid_device_io_start(hdev);

	ret = joycon_init(hdev);
	if (ret) {
		hid_err(hdev, "Failed to initialize controller; ret=%d\n", ret);
		goto err_io_stop;
	}

	/* Initialize the leds */
	ret = joycon_leds_create(ctlr);
	if (ret) {
		hid_err(hdev, "Failed to create leds; ret=%d\n", ret);
		goto err_io_stop;
	}

	/* Initialize the battery power supply */
	ret = joycon_power_supply_create(ctlr);
	if (ret) {
		hid_err(hdev, "Failed to create power_supply; ret=%d\n", ret);
		goto err_ida;
	}

	ret = joycon_input_create(ctlr);
	if (ret) {
		hid_err(hdev, "Failed to create input device; ret=%d\n", ret);
		goto err_ida;
	}

	ctlr->ctlr_state = JOYCON_CTLR_STATE_READ;

	hid_dbg(hdev, "probe - success\n");
	return 0;

err_ida:
	ida_free(&nintendo_player_id_allocator, ctlr->player_id);
err_io_stop:
	hid_device_io_stop(hdev);
	hid_hw_close(hdev);
err_stop:
	hid_hw_stop(hdev);
err_wq:
	destroy_workqueue(ctlr->rumble_queue);
err:
	hid_err(hdev, "probe - fail = %d\n", ret);
	return ret;
}

static void joycon_remove(struct hid_device *hdev)
{
	struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
	unsigned long flags;

	hid_dbg(hdev, "remove\n");

	/* Prevent further attempts at sending subcommands. */
	spin_lock_irqsave(&ctlr->lock, flags);
	ctlr->ctlr_state = JOYCON_CTLR_STATE_REMOVED;
	spin_unlock_irqrestore(&ctlr->lock, flags);

	destroy_workqueue(ctlr->rumble_queue);
	ida_free(&nintendo_player_id_allocator, ctlr->player_id);

	hid_hw_close(hdev);
	hid_hw_stop(hdev);
}

static int joycon_resume(struct hid_device *hdev)
{
	struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);
	int ret;

	hid_dbg(hdev, "resume\n");
	if (!joycon_using_usb(ctlr)) {
		hid_dbg(hdev, "no-op resume for bt ctlr\n");
		ctlr->ctlr_state = JOYCON_CTLR_STATE_READ;
		return 0;
	}

	ret = joycon_init(hdev);
	if (ret)
		hid_err(hdev,
			"Failed to restore controller after resume: %d\n",
			ret);
	else
		ctlr->ctlr_state = JOYCON_CTLR_STATE_READ;

	return ret;
}

static int joycon_suspend(struct hid_device *hdev, pm_message_t message)
{
	struct joycon_ctlr *ctlr = hid_get_drvdata(hdev);

	hid_dbg(hdev, "suspend: %d\n", message.event);
	/*
	 * Avoid any blocking loops in suspend/resume transitions.
	 *
	 * joycon_enforce_subcmd_rate() can result in repeated retries if for
	 * whatever reason the controller stops providing input reports.
	 *
	 * This has been observed with bluetooth controllers which lose
	 * connectivity prior to suspend (but not long enough to result in
	 * complete disconnection).
	 */
	ctlr->ctlr_state = JOYCON_CTLR_STATE_SUSPENDED;
	return 0;
}

/*
 * =============================================================================
 * Switch 2 support
 * =============================================================================
 */
#define NS2_BTNR_B	BIT(0)
#define NS2_BTNR_A	BIT(1)
#define NS2_BTNR_Y	BIT(2)
#define NS2_BTNR_X	BIT(3)
#define NS2_BTNR_R	BIT(4)
#define NS2_BTNR_ZR	BIT(5)
#define NS2_BTNR_PLUS	BIT(6)
#define NS2_BTNR_RS	BIT(7)

#define NS2_BTNL_DOWN	BIT(0)
#define NS2_BTNL_RIGHT	BIT(1)
#define NS2_BTNL_LEFT	BIT(2)
#define NS2_BTNL_UP	BIT(3)
#define NS2_BTNL_L	BIT(4)
#define NS2_BTNL_ZL	BIT(5)
#define NS2_BTNL_MINUS	BIT(6)
#define NS2_BTNL_LS	BIT(7)

#define NS2_BTN3_C	BIT(4)
#define NS2_BTN3_SR	BIT(6)
#define NS2_BTN3_SL	BIT(7)

#define NS2_BTN_U1_Y	BIT(0)
#define NS2_BTN_U1_X	BIT(1)
#define NS2_BTN_U1_B	BIT(2)
#define NS2_BTN_U1_A	BIT(3)
#define NS2_BTN_U1_SR	BIT(4)
#define NS2_BTN_U1_SL	BIT(5)
#define NS2_BTN_U1_R	BIT(6)
#define NS2_BTN_U1_ZR	BIT(7)

#define NS2_BTN_U2_MINUS	BIT(0)
#define NS2_BTN_U2_PLUS		BIT(1)
#define NS2_BTN_U2_RS		BIT(2)
#define NS2_BTN_U2_LS		BIT(3)
#define NS2_BTN_U2_HOME		BIT(4)
#define NS2_BTN_U2_CAPTURE	BIT(5)
#define NS2_BTN_U2_C		BIT(6)

#define NS2_BTN_U3_DOWN		BIT(0)
#define NS2_BTN_U3_UP		BIT(1)
#define NS2_BTN_U3_RIGHT	BIT(2)
#define NS2_BTN_U3_LEFT		BIT(3)
#define NS2_BTN_U3_SR		BIT(4)
#define NS2_BTN_U3_SL		BIT(5)
#define NS2_BTN_U3_L		BIT(6)
#define NS2_BTN_U3_ZL		BIT(7)

#define NS2_BTN_U4_GR		BIT(0)
#define NS2_BTN_U4_GL		BIT(1)
#define NS2_BTN_U4_HEADSET	BIT(5)

#define NS2_BTN_JCR_HOME	BIT(0)
#define NS2_BTN_JCR_GR		BIT(2)
#define NS2_BTN_JCR_C		NS2_BTN3_C
#define NS2_BTN_JCR_SR		NS2_BTN3_SR
#define NS2_BTN_JCR_SL		NS2_BTN3_SL

#define NS2_BTN_JCL_CAPTURE	BIT(0)
#define NS2_BTN_JCL_GL		BIT(2)
#define NS2_BTN_JCL_SR		NS2_BTN3_SR
#define NS2_BTN_JCL_SL		NS2_BTN3_SL

#define NS2_BTN_PRO_HOME	BIT(0)
#define NS2_BTN_PRO_CAPTURE	BIT(1)
#define NS2_BTN_PRO_GR		BIT(2)
#define NS2_BTN_PRO_GL		BIT(3)
#define NS2_BTN_PRO_C		NS2_BTN3_C

#define NS2_BTN_GC_HOME		BIT(0)
#define NS2_BTN_GC_CAPTURE	BIT(1)
#define NS2_BTN_GC_C		NS2_BTN3_C

#define NS2_TRIGGER_RANGE	4095
#define NS2_AXIS_MIN		-32768
#define NS2_AXIS_MAX		32767

#define NS2_MAX_PLAYER_ID	8

#define NS2_MAX_INIT_RETRIES	4

#define NS2_FLASH_ADDR_SERIAL			0x13002
#define NS2_FLASH_ADDR_FACTORY_PRIMARY_CALIB	0x130a8
#define NS2_FLASH_ADDR_FACTORY_SECONDARY_CALIB	0x130e8
#define NS2_FLASH_ADDR_FACTORY_TRIGGER_CALIB	0x13140
#define NS2_FLASH_ADDR_USER_PRIMARY_CALIB	0x1fc040
#define NS2_FLASH_ADDR_USER_SECONDARY_CALIB	0x1fc080

#define NS2_FLASH_SIZE_SERIAL 0x10
#define NS2_FLASH_SIZE_FACTORY_AXIS_CALIB 9
#define NS2_FLASH_SIZE_FACTORY_TRIGGER_CALIB 2
#define NS2_FLASH_SIZE_USER_AXIS_CALIB 11

#define NS2_USER_CALIB_MAGIC 0xa1b2

#define NS2_FEATURE_BUTTONS	BIT(0)
#define NS2_FEATURE_ANALOG	BIT(1)
#define NS2_FEATURE_IMU		BIT(2)
#define NS2_FEATURE_MOUSE	BIT(4)
#define NS2_FEATURE_RUMBLE	BIT(5)
#define NS2_FEATURE_MAGNETO	BIT(7)

enum switch2_subcmd_flash {
	NS2_SUBCMD_FLASH_READ_BLOCK = 0x01,
	NS2_SUBCMD_FLASH_WRITE_BLOCK = 0x02,
	NS2_SUBCMD_FLASH_ERASE_BLOCK = 0x03,
	NS2_SUBCMD_FLASH_READ = 0x04,
	NS2_SUBCMD_FLASH_WRITE = 0x05,
};

enum switch2_subcmd_init {
	NS2_SUBCMD_INIT_SELECT_REPORT = 0xa,
	NS2_SUBCMD_INIT_USB = 0xd,
};

enum switch2_subcmd_feature_select {
	NS2_SUBCMD_FEATSEL_GET_INFO = 0x1,
	NS2_SUBCMD_FEATSEL_SET_MASK = 0x2,
	NS2_SUBCMD_FEATSEL_CLEAR_MASK = 0x3,
	NS2_SUBCMD_FEATSEL_ENABLE = 0x4,
	NS2_SUBCMD_FEATSEL_DISABLE = 0x5,
};

enum switch2_subcmd_grip {
	NS2_SUBCMD_GRIP_GET_INFO = 0x1,
	NS2_SUBCMD_GRIP_ENABLE_BUTTONS = 0x2,
	NS2_SUBCMD_GRIP_GET_INFO_EXT = 0x3,
};

enum switch2_subcmd_led {
	NS2_SUBCMD_LED_P1 = 0x1,
	NS2_SUBCMD_LED_P2 = 0x2,
	NS2_SUBCMD_LED_P3 = 0x3,
	NS2_SUBCMD_LED_P4 = 0x4,
	NS2_SUBCMD_LED_ALL_ON = 0x5,
	NS2_SUBCMD_LED_ALL_OFF = 0x6,
	NS2_SUBCMD_LED_PATTERN = 0x7,
	NS2_SUBCMD_LED_BLINK = 0x8,
};

enum switch2_subcmd_fw_info {
	NS2_SUBCMD_FW_INFO_GET = 0x1,
};

enum switch2_ctlr_type {
	NS2_CTLR_TYPE_JCL = 0x00,
	NS2_CTLR_TYPE_JCR = 0x01,
	NS2_CTLR_TYPE_PRO = 0x02,
	NS2_CTLR_TYPE_GC = 0x03,
};

enum switch2_report_id {
	NS2_REPORT_UNIFIED = 0x05,
	NS2_REPORT_JCL = 0x07,
	NS2_REPORT_JCR = 0x08,
	NS2_REPORT_PRO = 0x09,
	NS2_REPORT_GC = 0x0a,
};

enum switch2_init_step {
	NS2_INIT_READ_SERIAL,
	NS2_INIT_GET_FIRMWARE_INFO,
	NS2_INIT_READ_FACTORY_PRIMARY_CALIB,
	NS2_INIT_READ_FACTORY_SECONDARY_CALIB,
	NS2_INIT_READ_FACTORY_TRIGGER_CALIB,
	NS2_INIT_READ_USER_PRIMARY_CALIB,
	NS2_INIT_READ_USER_SECONDARY_CALIB,
	NS2_INIT_SET_FEATURE_MASK,
	NS2_INIT_ENABLE_FEATURES,
	NS2_INIT_ENABLE_RUMBLE,
	NS2_INIT_GRIP_BUTTONS,
	NS2_INIT_REPORT_FORMAT,
	NS2_INIT_INPUT,
	NS2_INIT_SET_PLAYER_LEDS,
	NS2_INIT_FINISH,
	NS2_INIT_DONE,
};

struct switch2_version_info {
	uint8_t major;
	uint8_t minor;
	uint8_t patch;
	uint8_t ctlr_type;
	__le32 unk;
	int8_t dsp_major;
	int8_t dsp_minor;
	int8_t dsp_patch;
	int8_t dsp_type;
};

struct switch2_axis_calibration {
	uint16_t neutral;
	uint16_t negative;
	uint16_t positive;
};

struct switch2_stick_calibration {
	struct switch2_axis_calibration x;
	struct switch2_axis_calibration y;
};

struct switch2_hd_rumble {
	uint16_t hi_freq : 10;
	uint16_t hi_amp : 10;
	uint16_t lo_freq : 10;
	uint16_t lo_amp : 10;
} __packed;

struct switch2_erm_rumble {
	uint16_t error;
	uint16_t amplitude;
};

struct switch2_controller {
	struct hid_device *hdev;
	struct switch2_cfg_intf *cfg;
	struct kref refcount;

	char name[64];
	char phys[64];
	struct list_head entry;
	struct mutex lock;

	enum switch2_ctlr_type ctlr_type;
	enum switch2_init_step init_step;
	int init_retries;
	struct input_dev __rcu *input;
	char serial[NS2_FLASH_SIZE_SERIAL + 1];
	struct switch2_version_info version;

	struct switch2_stick_calibration stick_calib[2];
	uint8_t lt_zero;
	uint8_t rt_zero;

	uint32_t player_id;
	struct led_classdev *leds;

#if IS_ENABLED(CONFIG_NINTENDO_FF)
	spinlock_t rumble_lock;
	uint8_t rumble_seq;
	union {
		struct switch2_hd_rumble hd;
		struct switch2_erm_rumble sd;
	} rumble;
	uint64_t last_rumble_work;
	struct delayed_work rumble_work;
	uint8_t *rumble_buffer;
#endif
};

enum gc_rumble {
	GC_RUMBLE_OFF = 0,
	GC_RUMBLE_ON = 1,
	GC_RUMBLE_STOP = 2,
};

/*
 * The highest rumble level for "HD Rumble" is strong enough to potentially damage the controller,
 * and also leaves your hands feeling like melted jelly, so we set a semi-arbitrary scaling factor
 * to artificially limit the maximum for safety and comfort. It is currently unknown if the Switch
 * 2 itself does something similar, but it's quite likely.
 *
 * This value must be between 0 and 1024, otherwise the math below will overflow.
 */
#define RUMBLE_MAX 450u

/*
 * Semi-arbitrary values used to simulate the "rumble" sensation of an eccentric rotating
 * mass type haptic motor on the Switch 2 controllers' linear resonant actuator type haptics.
 *
 * The units used are unknown, but the values must be between 0 and 1023.
 */
#define RUMBLE_HI_FREQ 0x187
#define RUMBLE_LO_FREQ 0x112

static DEFINE_MUTEX(switch2_controllers_lock);
static LIST_HEAD(switch2_controllers);

struct switch2_ctlr_button_mapping {
	uint32_t code;
	int byte;
	uint32_t bit;
};

static const struct switch2_ctlr_button_mapping ns2_left_joycon_button_mappings[] = {
	{ BTN_DPAD_LEFT,	0, NS2_BTNL_LEFT,	},
	{ BTN_DPAD_UP,		0, NS2_BTNL_UP,		},
	{ BTN_DPAD_DOWN,	0, NS2_BTNL_DOWN,	},
	{ BTN_DPAD_RIGHT,	0, NS2_BTNL_RIGHT,	},
	{ BTN_TL,		0, NS2_BTNL_L,		},
	{ BTN_TL2,		0, NS2_BTNL_ZL,		},
	{ BTN_SELECT,		0, NS2_BTNL_MINUS,	},
	{ BTN_THUMBL,		0, NS2_BTNL_LS,		},
	{ KEY_RECORD,		1, NS2_BTN_JCL_CAPTURE,	},
	{ BTN_GRIPR,		1, NS2_BTN_JCL_SL,	},
	{ BTN_GRIPR2,		1, NS2_BTN_JCL_SR,	},
	{ BTN_GRIPL,		1, NS2_BTN_JCL_GL,	},
	{ /* sentinel */ },
};

static const struct switch2_ctlr_button_mapping ns2_left_joycon_button_unified_mappings[] = {
	{ BTN_DPAD_LEFT,	2, NS2_BTN_U3_LEFT,	},
	{ BTN_DPAD_UP,		2, NS2_BTN_U3_UP,	},
	{ BTN_DPAD_DOWN,	2, NS2_BTN_U3_DOWN,	},
	{ BTN_DPAD_RIGHT,	2, NS2_BTN_U3_RIGHT,	},
	{ BTN_TL,		2, NS2_BTN_U3_L,	},
	{ BTN_TL2,		2, NS2_BTN_U3_ZL,	},
	{ BTN_SELECT,		1, NS2_BTN_U2_MINUS,	},
	{ BTN_THUMBL,		1, NS2_BTN_U2_LS,	},
	{ KEY_RECORD,		1, NS2_BTN_U2_CAPTURE,	},
	{ BTN_GRIPR,		2, NS2_BTN_U3_SL,	},
	{ BTN_GRIPR2,		2, NS2_BTN_U3_SR,	},
	{ BTN_GRIPL,		3, NS2_BTN_U4_GL,	},
	{ /* sentinel */ },
};

static const struct switch2_ctlr_button_mapping ns2_right_joycon_button_mappings[] = {
	{ BTN_SOUTH,	0, NS2_BTNR_A,		},
	{ BTN_EAST,	0, NS2_BTNR_B,		},
	{ BTN_NORTH,	0, NS2_BTNR_X,		},
	{ BTN_WEST,	0, NS2_BTNR_Y,		},
	{ BTN_TR,	0, NS2_BTNR_R,		},
	{ BTN_TR2,	0, NS2_BTNR_ZR,		},
	{ BTN_START,	0, NS2_BTNR_PLUS,	},
	{ BTN_THUMBR,	0, NS2_BTNR_RS,		},
	{ BTN_C,	1, NS2_BTN_JCR_C,	},
	{ BTN_MODE,	1, NS2_BTN_JCR_HOME,	},
	{ BTN_GRIPL2,	1, NS2_BTN_JCR_SL,	},
	{ BTN_GRIPL,	1, NS2_BTN_JCR_SR,	},
	{ BTN_GRIPR,	1, NS2_BTN_JCR_GR,	},
	{ /* sentinel */ },
};

static const struct switch2_ctlr_button_mapping ns2_right_joycon_button_unified_mappings[] = {
	{ BTN_SOUTH,	0, NS2_BTN_U1_A,	},
	{ BTN_EAST,	0, NS2_BTN_U1_B,	},
	{ BTN_NORTH,	0, NS2_BTN_U1_X,	},
	{ BTN_WEST,	0, NS2_BTN_U1_Y,	},
	{ BTN_TR,	0, NS2_BTN_U1_R,	},
	{ BTN_TR2,	0, NS2_BTN_U1_ZR	},
	{ BTN_START,	1, NS2_BTN_U2_PLUS,	},
	{ BTN_THUMBR,	1, NS2_BTN_U2_RS,	},
	{ BTN_C,	1, NS2_BTN_U2_C,	},
	{ BTN_MODE,	1, NS2_BTN_U2_HOME,	},
	{ BTN_GRIPL2,	0, NS2_BTN_U1_SL,	},
	{ BTN_GRIPL,	0, NS2_BTN_U1_SR,	},
	{ BTN_GRIPR,	3, NS2_BTN_U4_GR,	},
	{ /* sentinel */ },
};

static const struct switch2_ctlr_button_mapping ns2_procon_mappings[] = {
	{ BTN_SOUTH,	0, NS2_BTNR_A,		},
	{ BTN_EAST,	0, NS2_BTNR_B,		},
	{ BTN_NORTH,	0, NS2_BTNR_X,		},
	{ BTN_WEST,	0, NS2_BTNR_Y,		},
	{ BTN_TL,	1, NS2_BTNL_L,		},
	{ BTN_TR,	0, NS2_BTNR_R,		},
	{ BTN_TL2,	1, NS2_BTNL_ZL,		},
	{ BTN_TR2,	0, NS2_BTNR_ZR,		},
	{ BTN_SELECT,	1, NS2_BTNL_MINUS,	},
	{ BTN_START,	0, NS2_BTNR_PLUS,	},
	{ BTN_THUMBL,	1, NS2_BTNL_LS,		},
	{ BTN_THUMBR,	0, NS2_BTNR_RS,		},
	{ BTN_MODE,	2, NS2_BTN_PRO_HOME	},
	{ KEY_RECORD,	2, NS2_BTN_PRO_CAPTURE	},
	{ BTN_GRIPR,	2, NS2_BTN_PRO_GR	},
	{ BTN_GRIPL,	2, NS2_BTN_PRO_GL	},
	{ BTN_C,	2, NS2_BTN_PRO_C	},
	{ /* sentinel */ },
};

static const struct switch2_ctlr_button_mapping ns2_procon_unified_mappings[] = {
	{ BTN_SOUTH,	0, NS2_BTN_U1_A,	},
	{ BTN_EAST,	0, NS2_BTN_U1_B,	},
	{ BTN_NORTH,	0, NS2_BTN_U1_X,	},
	{ BTN_WEST,	0, NS2_BTN_U1_Y,	},
	{ BTN_TL,	2, NS2_BTN_U3_L,	},
	{ BTN_TR,	0, NS2_BTN_U1_R,	},
	{ BTN_TL2,	2, NS2_BTN_U3_ZL,	},
	{ BTN_TR2,	0, NS2_BTN_U1_ZR,	},
	{ BTN_SELECT,	1, NS2_BTN_U2_MINUS,	},
	{ BTN_START,	1, NS2_BTN_U2_PLUS,	},
	{ BTN_THUMBL,	1, NS2_BTN_U2_LS,	},
	{ BTN_THUMBR,	1, NS2_BTN_U2_RS,	},
	{ BTN_MODE,	1, NS2_BTN_U2_HOME	},
	{ KEY_RECORD,	1, NS2_BTN_U2_CAPTURE	},
	{ BTN_GRIPR,	3, NS2_BTN_U4_GR	},
	{ BTN_GRIPL,	3, NS2_BTN_U4_GL	},
	{ BTN_C,	1, NS2_BTN_U2_C		},
	{ /* sentinel */ },
};

static const struct switch2_ctlr_button_mapping ns2_gccon_mappings[] = {
	{ BTN_SOUTH,	0, NS2_BTNR_A,		},
	{ BTN_EAST,	0, NS2_BTNR_B,		},
	{ BTN_NORTH,	0, NS2_BTNR_X,		},
	{ BTN_WEST,	0, NS2_BTNR_Y,		},
	{ BTN_TL2,	1, NS2_BTNL_L,		},
	{ BTN_TR2,	0, NS2_BTNR_R,		},
	{ BTN_TL,	1, NS2_BTNL_ZL,		},
	{ BTN_TR,	0, NS2_BTNR_ZR,		},
	{ BTN_SELECT,	1, NS2_BTNL_MINUS,	},
	{ BTN_START,	0, NS2_BTNR_PLUS,	},
	{ BTN_MODE,	2, NS2_BTN_GC_HOME	},
	{ KEY_RECORD,	2, NS2_BTN_GC_CAPTURE	},
	{ BTN_C,	2, NS2_BTN_GC_C		},
	{ /* sentinel */ },
};

static const struct switch2_ctlr_button_mapping ns2_gccon_unified_mappings[] = {
	{ BTN_SOUTH,	0, NS2_BTN_U1_A,	},
	{ BTN_EAST,	0, NS2_BTN_U1_B,	},
	{ BTN_NORTH,	0, NS2_BTN_U1_X,	},
	{ BTN_WEST,	0, NS2_BTN_U1_Y,	},
	{ BTN_TL2,	2, NS2_BTN_U3_L,	},
	{ BTN_TR2,	0, NS2_BTN_U1_R,	},
	{ BTN_TL,	2, NS2_BTN_U3_ZL	},
	{ BTN_TR,	0, NS2_BTN_U1_ZR	},
	{ BTN_SELECT,	1, NS2_BTN_U2_MINUS,	},
	{ BTN_START,	1, NS2_BTN_U2_PLUS,	},
	{ BTN_MODE,	1, NS2_BTN_U2_HOME	},
	{ KEY_RECORD,	1, NS2_BTN_U2_CAPTURE	},
	{ BTN_C,	1, NS2_BTN_U2_C		},
	{ /* sentinel */ },
};

static const uint8_t switch2_init_cmd_data[] = {
	/*
	 * The last 6 bytes of this packet are the MAC address of
	 * the console, but we don't need that for USB
	 */
	0x01, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};

static const uint8_t switch2_one_data[] = { 0x01, 0x00, 0x00, 0x00 };

static const uint8_t switch2_feature_mask[] = {
	NS2_FEATURE_BUTTONS | NS2_FEATURE_ANALOG | NS2_FEATURE_IMU | NS2_FEATURE_RUMBLE,
	0x00, 0x00, 0x00
};

static int switch2_init_controller(struct switch2_controller *ns2);

static void switch2_init_step_done(struct switch2_controller *ns2, enum switch2_init_step step)
{
	if (ns2->init_step != step)
		return;

	ns2->init_retries = 0;
	ns2->init_step++;
}

static inline bool switch2_ctlr_is_joycon(enum switch2_ctlr_type type)
{
	return type == NS2_CTLR_TYPE_JCL || type == NS2_CTLR_TYPE_JCR;
}

static struct switch2_controller *switch2_get_controller(const char *phys)
{
	struct switch2_controller *ns2;

	guard(mutex)(&switch2_controllers_lock);
	list_for_each_entry(ns2, &switch2_controllers, entry) {
		if (strncmp(ns2->phys, phys, sizeof(ns2->phys)) == 0) {
			if (kref_get_unless_zero(&ns2->refcount))
				return ns2;
		}
	}
	ns2 = kzalloc_obj(*ns2);
	if (!ns2)
		return ERR_PTR(-ENOMEM);

	kref_init(&ns2->refcount);
	mutex_init(&ns2->lock);
	INIT_LIST_HEAD(&ns2->entry);
	list_add(&ns2->entry, &switch2_controllers);
	strscpy(ns2->phys, phys, sizeof(ns2->phys));
#if IS_ENABLED(CONFIG_NINTENDO_FF)
	spin_lock_init(&ns2->rumble_lock);
#endif
	return ns2;
}

static void switch2_controller_put(struct switch2_controller *ns2)
{
	struct input_dev *input;

	mutex_lock(&ns2->lock);
	rcu_read_lock();
	input = rcu_dereference(ns2->input);
	rcu_read_unlock();

	rcu_assign_pointer(ns2->input, NULL);
	synchronize_rcu();

	ns2->init_step = 0;
	mutex_unlock(&ns2->lock);

	if (input)
		input_unregister_device(input);
}

static void switch2_kref_put(struct kref *refcount)
{
	struct switch2_controller *ns2 = container_of(refcount,
					struct switch2_controller, refcount);

	guard(mutex)(&switch2_controllers_lock);
	list_del_init(&ns2->entry);
	mutex_destroy(&ns2->lock);
	kfree(ns2);
}

#if IS_ENABLED(CONFIG_NINTENDO_FF)
static void switch2_encode_rumble(struct switch2_hd_rumble *rumble, uint8_t buffer[5])
{
	buffer[0] = rumble->hi_freq;
	buffer[1] = (rumble->hi_freq >> 8) | (rumble->hi_amp << 2);
	buffer[2] = (rumble->hi_amp >> 6) | (rumble->lo_freq << 4);
	buffer[3] = (rumble->lo_freq >> 4) | (rumble->lo_amp << 6);
	buffer[4] = rumble->lo_amp >> 2;
}

static int switch2_play_effect(struct input_dev *dev, void *data, struct ff_effect *effect)
{
	struct switch2_controller *ns2 = input_get_drvdata(dev);
	unsigned long flags;

	if (effect->type != FF_RUMBLE)
		return 0;

	if (!ns2)
		return -ENODEV;

	spin_lock_irqsave(&ns2->rumble_lock, flags);
	if (ns2->ctlr_type == NS2_CTLR_TYPE_GC) {
		ns2->rumble.sd.amplitude = max(effect->u.rumble.strong_magnitude,
			(uint16_t) (effect->u.rumble.weak_magnitude >> 1));
	} else {
		ns2->rumble.hd.hi_freq = RUMBLE_HI_FREQ;
		ns2->rumble.hd.lo_freq = RUMBLE_LO_FREQ;
		ns2->rumble.hd.hi_amp = effect->u.rumble.weak_magnitude * RUMBLE_MAX >> 16;
		ns2->rumble.hd.lo_amp = effect->u.rumble.strong_magnitude * RUMBLE_MAX >> 16;
	}
	spin_unlock_irqrestore(&ns2->rumble_lock, flags);

	schedule_delayed_work(&ns2->rumble_work, 0);

	return 0;
}

static void switch2_rumble_work(struct work_struct *work)
{
	struct switch2_controller *ns2 = container_of(to_delayed_work(work),
						      struct switch2_controller, rumble_work);
	unsigned long flags;
	bool active;
	int ret = 0;

	spin_lock_irqsave(&ns2->rumble_lock, flags);
	ns2->rumble_buffer[0x1] = 0x50 | ns2->rumble_seq;
	if (ns2->ctlr_type == NS2_CTLR_TYPE_GC) {
		ns2->rumble_buffer[0] = 3;
		if (ns2->rumble.sd.amplitude == 0) {
			ns2->rumble_buffer[2] = GC_RUMBLE_STOP;
			ns2->rumble.sd.error = 0;
			active = false;
		} else {
			if (ns2->rumble.sd.error < ns2->rumble.sd.amplitude) {
				ns2->rumble_buffer[2] = GC_RUMBLE_ON;
				ns2->rumble.sd.error += U16_MAX - ns2->rumble.sd.amplitude;
			} else {
				ns2->rumble_buffer[2] = GC_RUMBLE_OFF;
				ns2->rumble.sd.error -= ns2->rumble.sd.amplitude;
			}
			active = true;
		}
	} else {
		ns2->rumble_buffer[0] = 1;
		switch2_encode_rumble(&ns2->rumble.hd, &ns2->rumble_buffer[0x2]);
		active = ns2->rumble.hd.hi_amp || ns2->rumble.hd.lo_amp;
		if (ns2->ctlr_type == NS2_CTLR_TYPE_PRO) {
			/*
			 * The Pro Controller contains separate LRAs on each
			 * side that can be controlled individually.
			 */
			ns2->rumble_buffer[0] = 2;
			ns2->rumble_buffer[0x11] = 0x50 | ns2->rumble_seq;
			switch2_encode_rumble(&ns2->rumble.hd, &ns2->rumble_buffer[0x12]);
		}
	}
	ns2->rumble_seq = (ns2->rumble_seq + 1) & 0xF;
	spin_unlock_irqrestore(&ns2->rumble_lock, flags);

	if (active) {
		unsigned long interval = msecs_to_jiffies(4);
		uint64_t current_jiffies = get_jiffies_64();

		if (!ns2->last_rumble_work)
			ns2->last_rumble_work = current_jiffies;
		else
			ns2->last_rumble_work += interval;

		/* Reschedule a little early to make sure the buffer never underruns */
		interval -= msecs_to_jiffies(2);
		if (ns2->last_rumble_work + interval >= current_jiffies)
			schedule_delayed_work(&ns2->rumble_work,
				ns2->last_rumble_work + interval - current_jiffies);
		else
			schedule_delayed_work(&ns2->rumble_work, 0);
	} else {
		ns2->last_rumble_work = 0;
	}

	mutex_lock(&ns2->lock);
	if (!ns2->hdev) {
		cancel_delayed_work(&ns2->rumble_work);
	} else {
		ret = hid_hw_output_report(ns2->hdev, ns2->rumble_buffer, 64);
		/*
		 * Don't log on ENODEV, ESHUTDOWN, or EPROTO, which can happen
		 * mid-hotplug. Also cancel any further work on ENODEV or
		 * ESHUTDOWN as they're clear indications that the endpoint
		 * is dead.
		 */
		if (ret == -ENODEV || ret == -ESHUTDOWN)
			cancel_delayed_work(&ns2->rumble_work);
		else if (ret < 0 && ret != -EPROTO)
			hid_warn_ratelimited(ns2->hdev,
				"Failed to send output report ret=%d\n", ret);
	}
	mutex_unlock(&ns2->lock);
}
#endif

static int switch2_set_leds(struct switch2_controller *ns2)
{
	int i;
	uint8_t message[8] = { 0 };

	for (i = 0; i < JC_NUM_LEDS; i++)
		message[0] |= (!!ns2->leds[i].brightness) << i;

	if (!ns2->cfg)
		return -ENOTCONN;
	return ns2->cfg->send_command(NS2_CMD_LED, NS2_SUBCMD_LED_PATTERN,
		&message, sizeof(message),
		ns2->cfg);
}

static int switch2_player_led_brightness_set(struct led_classdev *led,
					    enum led_brightness brightness)
{
	struct device *dev = led->dev->parent;
	struct input_dev *input = to_input_dev(dev);
	struct switch2_controller *ns2 = input_get_drvdata(input);

	if (!ns2)
		return -ENODEV;

	guard(mutex)(&ns2->lock);
	return switch2_set_leds(ns2);
}

static void switch2_config_buttons(struct input_dev *idev,
	const struct switch2_ctlr_button_mapping button_mappings[])
{
	const struct switch2_ctlr_button_mapping *button;

	for (button = button_mappings; button->code; button++)
		input_set_capability(idev, EV_KEY, button->code);
}

static int switch2_input_ref(struct input_dev *input)
{
	struct switch2_controller *ns2 = input_get_drvdata(input);

	kref_get(&ns2->refcount);

	return 0;
}

static void switch2_input_deref(struct input_dev *input)
{
	struct switch2_controller *ns2 = input_get_drvdata(input);

	kref_put(&ns2->refcount, switch2_kref_put);
}

static int switch2_init_input(struct switch2_controller *ns2)
{
	struct input_dev *input;
	struct hid_device *hdev = ns2->hdev;
	int player_led_pattern;
	int i;
	int ret;

	rcu_read_lock();
	input = rcu_dereference(ns2->input);
	rcu_read_unlock();

	if (input) {
		switch2_init_step_done(ns2, NS2_INIT_INPUT);
		return 0;
	}

	input = input_allocate_device();
	if (!input)
		return -ENOMEM;

	input_set_drvdata(input, ns2);
	input->open = switch2_input_ref;
	input->close = switch2_input_deref;
	input->dev.parent = &hdev->dev;
	input->id.bustype = hdev->bus;
	input->id.vendor = hdev->vendor;
	input->id.product = hdev->product;
	input->id.version = hdev->version;
	input->uniq = ns2->serial;
	input->name = ns2->name;
	input->phys = hdev->phys;

	switch (ns2->ctlr_type) {
	case NS2_CTLR_TYPE_JCL:
		input_set_abs_params(input, ABS_X, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
		input_set_abs_params(input, ABS_Y, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
		switch2_config_buttons(input, ns2_left_joycon_button_mappings);
		break;
	case NS2_CTLR_TYPE_JCR:
		input_set_abs_params(input, ABS_X, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
		input_set_abs_params(input, ABS_Y, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
		switch2_config_buttons(input, ns2_right_joycon_button_mappings);
		break;
	case NS2_CTLR_TYPE_GC:
		input_set_abs_params(input, ABS_X, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
		input_set_abs_params(input, ABS_Y, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
		input_set_abs_params(input, ABS_RX, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
		input_set_abs_params(input, ABS_RY, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
		input_set_abs_params(input, ABS_Z, 0, NS2_TRIGGER_RANGE, 32, 128);
		input_set_abs_params(input, ABS_RZ, 0, NS2_TRIGGER_RANGE, 32, 128);
		input_set_abs_params(input, ABS_HAT0X, -1, 1, 0, 0);
		input_set_abs_params(input, ABS_HAT0Y, -1, 1, 0, 0);
		switch2_config_buttons(input, ns2_gccon_mappings);
		break;
	case NS2_CTLR_TYPE_PRO:
		input_set_abs_params(input, ABS_X, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
		input_set_abs_params(input, ABS_Y, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
		input_set_abs_params(input, ABS_RX, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
		input_set_abs_params(input, ABS_RY, NS2_AXIS_MIN, NS2_AXIS_MAX, 32, 128);
		input_set_abs_params(input, ABS_HAT0X, -1, 1, 0, 0);
		input_set_abs_params(input, ABS_HAT0Y, -1, 1, 0, 0);
		switch2_config_buttons(input, ns2_procon_mappings);
		break;
	default:
		input_free_device(input);
		return -EINVAL;
	}

#if IS_ENABLED(CONFIG_NINTENDO_FF)
	ns2->rumble_buffer = devm_kzalloc(&input->dev, 64, GFP_KERNEL);
	if (!ns2->rumble_buffer) {
		input_free_device(input);
		return -ENOMEM;
	}
	ret = devm_delayed_work_autocancel(&input->dev, &ns2->rumble_work, switch2_rumble_work);
	if (ret < 0) {
		input_free_device(input);
		return ret;
	}

	input_set_capability(input, EV_FF, FF_RUMBLE);
	ret = input_ff_create_memless(input, NULL, switch2_play_effect);
	if (ret) {
		input_free_device(input);
		return ret;
	}
#endif

	hid_info(ns2->hdev, "Firmware version %u.%u.%u (type %i)\n", ns2->version.major,
		ns2->version.minor, ns2->version.patch, ns2->version.ctlr_type);
	if (ns2->version.dsp_type >= 0)
		hid_info(ns2->hdev, "DSP version %u.%u.%u\n", ns2->version.dsp_major,
			ns2->version.dsp_minor, ns2->version.dsp_patch);

	ret = input_register_device(input);
	if (ret < 0) {
		hid_err(ns2->hdev, "Failed to register input; ret=%d\n", ret);
		input_free_device(input);
		return ret;
	}

	player_led_pattern = ns2->player_id % JC_NUM_LED_PATTERNS;
	hid_dbg(hdev, "assigned player %d led pattern", player_led_pattern + 1);

	ns2->leds = devm_kcalloc(&input->dev, JC_NUM_LEDS, sizeof(*ns2->leds), GFP_KERNEL);
	if (!ns2->leds) {
		input_unregister_device(input);
		return -ENOMEM;
	}

	for (i = 0; i < JC_NUM_LEDS; i++) {
		struct led_classdev *led = &ns2->leds[i];

		led->brightness = joycon_player_led_patterns[player_led_pattern][i];
		led->max_brightness = 1;
		led->brightness_set_blocking = switch2_player_led_brightness_set;
		led->flags = LED_CORE_SUSPENDRESUME | LED_HW_PLUGGABLE | LED_RETAIN_AT_SHUTDOWN;
		char *name = devm_kasprintf(&input->dev, GFP_KERNEL, "%s:%s:%s",
				      dev_name(&input->dev),
				      "green",
				      joycon_player_led_names[i]);

		if (!name) {
			dev_err(&input->dev, "Failed to allocate name for player %d LED; ret=%d\n",
				i + 1, ret);
			break;
		}

		led->name = name;
		ret = devm_led_classdev_register(&input->dev, led);
		if (ret < 0) {
			dev_err(&input->dev, "Failed to register player %d LED; ret=%d\n",
				i + 1, ret);
			break;
		}
	}

	rcu_assign_pointer(ns2->input, input);
	synchronize_rcu();

	switch2_init_step_done(ns2, NS2_INIT_INPUT);
	return switch2_init_controller(ns2);
}

static bool switch2_parse_stick_calibration(struct switch2_stick_calibration *calib,
	const uint8_t *data)
{
	static const uint8_t UNCALIBRATED[9] = {
		0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
	};
	if (memcmp(UNCALIBRATED, data, sizeof(UNCALIBRATED)) == 0)
		return false;

	calib->x.neutral = data[0];
	calib->x.neutral |= (data[1] & 0x0F) << 8;

	calib->y.neutral = data[1] >> 4;
	calib->y.neutral |= data[2] << 4;

	calib->x.positive = data[3];
	calib->x.positive |= (data[4] & 0x0F) << 8;

	calib->y.positive = data[4] >> 4;
	calib->y.positive |= data[5] << 4;

	calib->x.negative = data[6];
	calib->x.negative |= (data[7] & 0x0F) << 8;

	calib->y.negative = data[7] >> 4;
	calib->y.negative |= data[8] << 4;

	return true;
}

static void switch2_handle_flash_read(struct switch2_controller *ns2, uint8_t size,
	uint32_t address, const uint8_t *data)
{
	bool ok;

	switch (address) {
	case NS2_FLASH_ADDR_SERIAL:
		if (size != NS2_FLASH_SIZE_SERIAL)
			return;
		memcpy(ns2->serial, data, size);
		switch2_init_step_done(ns2, NS2_INIT_READ_SERIAL);
		break;
	case NS2_FLASH_ADDR_FACTORY_PRIMARY_CALIB:
		if (size != NS2_FLASH_SIZE_FACTORY_AXIS_CALIB)
			return;
		switch2_init_step_done(ns2, NS2_INIT_READ_FACTORY_PRIMARY_CALIB);
		ok = switch2_parse_stick_calibration(&ns2->stick_calib[0], data);
		if (ns2->hdev) {
			if (ok) {
				hid_dbg(ns2->hdev, "Got factory primary stick calibration:\n");
				hid_dbg(ns2->hdev, "Left max: %i, neutral: %i, right max: %i\n",
					ns2->stick_calib[0].x.negative,
					ns2->stick_calib[0].x.neutral,
					ns2->stick_calib[0].x.positive);
				hid_dbg(ns2->hdev, "Down max: %i, neutral: %i, up max: %i\n",
					ns2->stick_calib[0].y.negative,
					ns2->stick_calib[0].y.neutral,
					ns2->stick_calib[0].y.positive);
			} else {
				hid_dbg(ns2->hdev, "Factory primary stick calibration not present\n");
			}
		}
		break;
	case NS2_FLASH_ADDR_FACTORY_SECONDARY_CALIB:
		if (size != NS2_FLASH_SIZE_FACTORY_AXIS_CALIB)
			return;
		switch2_init_step_done(ns2, NS2_INIT_READ_FACTORY_SECONDARY_CALIB);
		ok = switch2_parse_stick_calibration(&ns2->stick_calib[1], data);
		if (ns2->hdev) {
			if (ok) {
				hid_dbg(ns2->hdev, "Got factory secondary stick calibration:\n");
				hid_dbg(ns2->hdev, "Left max: %i, neutral: %i, right max: %i\n",
					ns2->stick_calib[1].x.negative,
					ns2->stick_calib[1].x.neutral,
					ns2->stick_calib[1].x.positive);
				hid_dbg(ns2->hdev, "Down max: %i, neutral: %i, up max: %i\n",
					ns2->stick_calib[1].y.negative,
					ns2->stick_calib[1].y.neutral,
					ns2->stick_calib[1].y.positive);
			} else {
				hid_dbg(ns2->hdev, "Factory secondary stick calibration not present\n");
			}
		}
		break;
	case NS2_FLASH_ADDR_FACTORY_TRIGGER_CALIB:
		if (size != NS2_FLASH_SIZE_FACTORY_TRIGGER_CALIB)
			return;
		switch2_init_step_done(ns2, NS2_INIT_READ_FACTORY_TRIGGER_CALIB);
		if (data[0] != 0xFF && data[1] != 0xFF) {
			ns2->lt_zero = data[0];
			ns2->rt_zero = data[1];

			if (ns2->hdev) {
				hid_dbg(ns2->hdev, "Got factory trigger calibration:\n");
				hid_dbg(ns2->hdev, "Left zero point: %i\n", ns2->lt_zero);
				hid_dbg(ns2->hdev, "Right zero point: %i\n", ns2->rt_zero);
			}
		} else if (ns2->hdev) {
			hid_dbg(ns2->hdev, "Factory trigger calibration not present\n");
		}
		break;
	case NS2_FLASH_ADDR_USER_PRIMARY_CALIB:
		if (size != NS2_FLASH_SIZE_USER_AXIS_CALIB)
			return;
		switch2_init_step_done(ns2, NS2_INIT_READ_USER_PRIMARY_CALIB);
		if (get_unaligned_le16((__le16 *)data) != NS2_USER_CALIB_MAGIC) {
			if (ns2->hdev)
				hid_dbg(ns2->hdev, "No user primary stick calibration present\n");
			break;
		}

		ok = switch2_parse_stick_calibration(&ns2->stick_calib[0], &data[2]);
		if (ns2->hdev) {
			if (ok) {
				hid_dbg(ns2->hdev, "Got user primary stick calibration:\n");
				hid_dbg(ns2->hdev, "Left max: %i, neutral: %i, right max: %i\n",
					ns2->stick_calib[0].x.negative,
					ns2->stick_calib[0].x.neutral,
					ns2->stick_calib[0].x.positive);
				hid_dbg(ns2->hdev, "Down max: %i, neutral: %i, up max: %i\n",
					ns2->stick_calib[0].y.negative,
					ns2->stick_calib[0].y.neutral,
					ns2->stick_calib[0].y.positive);
			} else {
				hid_dbg(ns2->hdev, "No user primary stick calibration present\n");
			}
		}
		break;
	case NS2_FLASH_ADDR_USER_SECONDARY_CALIB:
		if (size != NS2_FLASH_SIZE_USER_AXIS_CALIB)
			return;
		switch2_init_step_done(ns2, NS2_INIT_READ_USER_SECONDARY_CALIB);
		if (get_unaligned_le16((__le16 *)data) != NS2_USER_CALIB_MAGIC) {
			if (ns2->hdev)
				hid_dbg(ns2->hdev, "No user secondary stick calibration present\n");
			break;
		}

		ok = switch2_parse_stick_calibration(&ns2->stick_calib[1], &data[2]);
		if (ns2->hdev) {
			if (ok) {
				hid_dbg(ns2->hdev, "Got user secondary stick calibration:\n");
				hid_dbg(ns2->hdev, "Left max: %i, neutral: %i, right max: %i\n",
					ns2->stick_calib[1].x.negative,
					ns2->stick_calib[1].x.neutral,
					ns2->stick_calib[1].x.positive);
				hid_dbg(ns2->hdev, "Down max: %i, neutral: %i, up max: %i\n",
					ns2->stick_calib[1].y.negative,
					ns2->stick_calib[1].y.neutral,
					ns2->stick_calib[1].y.positive);
			} else {
				hid_dbg(ns2->hdev, "No user secondary stick calibration present\n");
			}
		}
		break;
	}
}

static void switch2_report_buttons(struct input_dev *input, const uint8_t *bytes,
	const struct switch2_ctlr_button_mapping button_mappings[])
{
	const struct switch2_ctlr_button_mapping *button;

	for (button = button_mappings; button->code; button++)
		input_report_key(input, button->code, bytes[button->byte] & button->bit);
}

static void switch2_report_axis(struct input_dev *input, struct switch2_axis_calibration *calib,
	int axis, bool invert, int value)
{
	if (calib && calib->neutral && calib->negative && calib->positive) {
		value -= calib->neutral;
		value *= NS2_AXIS_MAX + 1;
		if (value < 0)
			value /= calib->negative;
		else
			value /= calib->positive;
	} else {
		value = (value - 2048) * 16;
	}

	if (invert)
		value = -value;
	input_report_abs(input, axis,
		clamp(value, NS2_AXIS_MIN, NS2_AXIS_MAX));
}

static void switch2_report_stick(struct input_dev *input, struct switch2_stick_calibration *calib,
	int x, bool invert_x, int y, bool invert_y, const uint8_t *data)
{
	switch2_report_axis(input, &calib->x, x, invert_x, data[0] | ((data[1] & 0x0F) << 8));
	switch2_report_axis(input, &calib->y, y, invert_y, (data[1] >> 4) | (data[2] << 4));
}

static void switch2_report_trigger(struct input_dev *input, uint8_t zero, int abs, uint8_t data)
{
	int value = (NS2_TRIGGER_RANGE + 1) * (data - zero);

	if (zero != 232)
		value /= (232 - zero);
	input_report_abs(input, abs, clamp(value, 0, NS2_TRIGGER_RANGE));
}

static int switch2_event(struct hid_device *hdev, struct hid_report *report, uint8_t *raw_data,
	int size)
{
	struct switch2_controller *ns2 = hid_get_drvdata(hdev);
	struct input_dev *input;

	if (report->type != HID_INPUT_REPORT)
		return 0;

	if (size < 15)
		return -EINVAL;

	guard(rcu)();
	input = rcu_dereference(ns2->input);

	if (!input)
		return 0;

	switch (report->id) {
	case NS2_REPORT_UNIFIED:
		if (size < 0x3f)
			return -EINVAL;

		switch (ns2->ctlr_type) {
		case NS2_CTLR_TYPE_JCL:
			switch2_report_stick(input, &ns2->stick_calib[0],
				ABS_X, false, ABS_Y, true, &raw_data[11]);
			switch2_report_buttons(input, &raw_data[5],
				ns2_left_joycon_button_unified_mappings);
			break;
		case NS2_CTLR_TYPE_JCR:
			switch2_report_stick(input, &ns2->stick_calib[0],
				ABS_X, false, ABS_Y, true, &raw_data[14]);
			switch2_report_buttons(input, &raw_data[5],
				ns2_right_joycon_button_unified_mappings);
			break;
		case NS2_CTLR_TYPE_GC:
			input_report_abs(input, ABS_HAT0X,
				!!(raw_data[7] & NS2_BTN_U3_RIGHT) -
				!!(raw_data[7] & NS2_BTN_U3_LEFT));
			input_report_abs(input, ABS_HAT0Y,
				!!(raw_data[7] & NS2_BTN_U3_DOWN) -
				!!(raw_data[7] & NS2_BTN_U3_UP));
			switch2_report_buttons(input, &raw_data[5], ns2_gccon_unified_mappings);
			switch2_report_stick(input, &ns2->stick_calib[0],
				ABS_X, false, ABS_Y, true, &raw_data[11]);
			switch2_report_stick(input, &ns2->stick_calib[1],
				ABS_RX, false, ABS_RY, true, &raw_data[14]);
			switch2_report_trigger(input, ns2->lt_zero, ABS_Z, raw_data[0x3d]);
			switch2_report_trigger(input, ns2->rt_zero, ABS_RZ, raw_data[0x3e]);
			break;
		case NS2_CTLR_TYPE_PRO:
			input_report_abs(input, ABS_HAT0X,
				!!(raw_data[7] & NS2_BTN_U3_RIGHT) -
				!!(raw_data[7] & NS2_BTN_U3_LEFT));
			input_report_abs(input, ABS_HAT0Y,
				!!(raw_data[7] & NS2_BTN_U3_DOWN) -
				!!(raw_data[7] & NS2_BTN_U3_UP));
			switch2_report_buttons(input, &raw_data[5], ns2_procon_unified_mappings);
			switch2_report_stick(input, &ns2->stick_calib[0],
				ABS_X, false, ABS_Y, true, &raw_data[11]);
			switch2_report_stick(input, &ns2->stick_calib[1],
				ABS_RX, false, ABS_RY, true, &raw_data[14]);
			break;
		}
		break;
	case NS2_REPORT_JCL:
		switch2_report_stick(input, &ns2->stick_calib[0], ABS_X, false,
			ABS_Y, true, &raw_data[6]);
		switch2_report_buttons(input, &raw_data[3], ns2_left_joycon_button_mappings);
		break;
	case NS2_REPORT_JCR:
		switch2_report_stick(input, &ns2->stick_calib[0], ABS_X, false,
			ABS_Y, true, &raw_data[6]);
		switch2_report_buttons(input, &raw_data[3], ns2_right_joycon_button_mappings);
		break;
	case NS2_REPORT_GC:
		input_report_abs(input, ABS_HAT0X,
			!!(raw_data[4] & NS2_BTNL_RIGHT) -
			!!(raw_data[4] & NS2_BTNL_LEFT));
		input_report_abs(input, ABS_HAT0Y,
			!!(raw_data[4] & NS2_BTNL_DOWN) -
			!!(raw_data[4] & NS2_BTNL_UP));
		switch2_report_buttons(input, &raw_data[3], ns2_gccon_mappings);
		switch2_report_stick(input, &ns2->stick_calib[0], ABS_X, false,
			ABS_Y, true, &raw_data[6]);
		switch2_report_stick(input, &ns2->stick_calib[1], ABS_RX, false,
			ABS_RY, true, &raw_data[9]);
		switch2_report_trigger(input, ns2->lt_zero, ABS_Z, raw_data[13]);
		switch2_report_trigger(input, ns2->rt_zero, ABS_RZ, raw_data[14]);
		break;
	case NS2_REPORT_PRO:
		input_report_abs(input, ABS_HAT0X,
			!!(raw_data[4] & NS2_BTNL_RIGHT) -
			!!(raw_data[4] & NS2_BTNL_LEFT));
		input_report_abs(input, ABS_HAT0Y,
			!!(raw_data[4] & NS2_BTNL_DOWN) -
			!!(raw_data[4] & NS2_BTNL_UP));
		switch2_report_buttons(input, &raw_data[3], ns2_procon_mappings);
		switch2_report_stick(input, &ns2->stick_calib[0], ABS_X, false,
			ABS_Y, true, &raw_data[6]);
		switch2_report_stick(input, &ns2->stick_calib[1], ABS_RX, false,
			ABS_RY, true, &raw_data[9]);
		break;
	default:
		return -EINVAL;
	}

	input_sync(input);
	return 0;
}

static int switch2_features_enable(struct switch2_controller *ns2, int features)
{
	__le32 feature_bits = __cpu_to_le32(features);

	if (!ns2->cfg)
		return -ENOTCONN;
	return ns2->cfg->send_command(NS2_CMD_FEATSEL, NS2_SUBCMD_FEATSEL_ENABLE,
		&feature_bits, sizeof(feature_bits),
		ns2->cfg);
}

static int switch2_read_flash(struct switch2_controller *ns2, uint32_t address,
	uint8_t size)
{
	uint8_t message[8] = { size, 0x7e };

	if (!ns2->cfg)
		return -ENOTCONN;
	put_unaligned_le32(address, &message[4]);
	return ns2->cfg->send_command(NS2_CMD_FLASH, NS2_SUBCMD_FLASH_READ, message,
		sizeof(message), ns2->cfg);
}

static int switch2_set_player_id(struct switch2_controller *ns2, uint32_t player_id)
{
	int i;
	int player_led_pattern = player_id % JC_NUM_LED_PATTERNS;

	for (i = 0; i < JC_NUM_LEDS; i++)
		ns2->leds[i].brightness = joycon_player_led_patterns[player_led_pattern][i];

	return switch2_set_leds(ns2);
}

static int switch2_set_report_format(struct switch2_controller *ns2, enum switch2_report_id fmt)
{
	__le32 format_id = __cpu_to_le32(fmt);

	if (!ns2->cfg)
		return -ENOTCONN;
	return ns2->cfg->send_command(NS2_CMD_INIT, NS2_SUBCMD_INIT_SELECT_REPORT,
		&format_id, sizeof(format_id),
		ns2->cfg);
}

int switch2_init_controller(struct switch2_controller *ns2)
{
	if (ns2->init_step == NS2_INIT_DONE)
		return 0;

	if (!ns2->cfg)
		return -ENOTCONN;

	if (ns2->init_retries > NS2_MAX_INIT_RETRIES) {
		if (ns2->init_retries == NS2_MAX_INIT_RETRIES + 1) {
			dev_err(ns2->cfg->dev, "Failed to configure controller\n");
			ns2->init_retries++;
		}
		return -EIO;
	}

	ns2->init_retries++;
	switch (ns2->init_step) {
	case NS2_INIT_READ_SERIAL:
		return switch2_read_flash(ns2, NS2_FLASH_ADDR_SERIAL,
			NS2_FLASH_SIZE_SERIAL);
	case NS2_INIT_GET_FIRMWARE_INFO:
		return ns2->cfg->send_command(NS2_CMD_FW_INFO, NS2_SUBCMD_FW_INFO_GET,
			NULL, 0, ns2->cfg);
	case NS2_INIT_READ_FACTORY_PRIMARY_CALIB:
		return switch2_read_flash(ns2, NS2_FLASH_ADDR_FACTORY_PRIMARY_CALIB,
			NS2_FLASH_SIZE_FACTORY_AXIS_CALIB);
	case NS2_INIT_READ_FACTORY_SECONDARY_CALIB:
		if (switch2_ctlr_is_joycon(ns2->ctlr_type)) {
			switch2_init_step_done(ns2, ns2->init_step);
			return switch2_init_controller(ns2);
		}
		return switch2_read_flash(ns2, NS2_FLASH_ADDR_FACTORY_SECONDARY_CALIB,
			NS2_FLASH_SIZE_FACTORY_AXIS_CALIB);
	case NS2_INIT_READ_FACTORY_TRIGGER_CALIB:
		if (ns2->ctlr_type != NS2_CTLR_TYPE_GC) {
			switch2_init_step_done(ns2, ns2->init_step);
			return switch2_init_controller(ns2);
		}
		return switch2_read_flash(ns2, NS2_FLASH_ADDR_FACTORY_TRIGGER_CALIB,
			NS2_FLASH_SIZE_FACTORY_TRIGGER_CALIB);
	case NS2_INIT_READ_USER_PRIMARY_CALIB:
		return switch2_read_flash(ns2, NS2_FLASH_ADDR_USER_PRIMARY_CALIB,
			NS2_FLASH_SIZE_USER_AXIS_CALIB);
	case NS2_INIT_READ_USER_SECONDARY_CALIB:
		if (switch2_ctlr_is_joycon(ns2->ctlr_type)) {
			switch2_init_step_done(ns2, ns2->init_step);
			return switch2_init_controller(ns2);
		}
		return switch2_read_flash(ns2, NS2_FLASH_ADDR_USER_SECONDARY_CALIB,
			NS2_FLASH_SIZE_USER_AXIS_CALIB);
	case NS2_INIT_SET_FEATURE_MASK:
		return ns2->cfg->send_command(NS2_CMD_FEATSEL, NS2_SUBCMD_FEATSEL_SET_MASK,
			switch2_feature_mask, sizeof(switch2_feature_mask), ns2->cfg);
	case NS2_INIT_ENABLE_FEATURES:
		return switch2_features_enable(ns2, NS2_FEATURE_BUTTONS |
			NS2_FEATURE_ANALOG | NS2_FEATURE_RUMBLE);
	case NS2_INIT_ENABLE_RUMBLE:
		/*
		 * It is unclear what this packet is supposed to be for, but it
		 * appears to be needed for rumble to work reliably. The reply
		 * data indicates it might be a query of some sort, but we
		 * ignore the reply so long as it doesn't return an error.
		 */
		return ns2->cfg->send_command(0x11, 1, NULL, 0, ns2->cfg);
	case NS2_INIT_GRIP_BUTTONS:
		if (!switch2_ctlr_is_joycon(ns2->ctlr_type)) {
			switch2_init_step_done(ns2, ns2->init_step);
			return switch2_init_controller(ns2);
		}
		return ns2->cfg->send_command(NS2_CMD_GRIP, NS2_SUBCMD_GRIP_ENABLE_BUTTONS,
			switch2_one_data, sizeof(switch2_one_data),
			ns2->cfg);
	case NS2_INIT_REPORT_FORMAT:
		switch (ns2->ctlr_type) {
		case NS2_CTLR_TYPE_JCL:
			return switch2_set_report_format(ns2, NS2_REPORT_JCL);
		case NS2_CTLR_TYPE_JCR:
			return switch2_set_report_format(ns2, NS2_REPORT_JCR);
		case NS2_CTLR_TYPE_PRO:
			return switch2_set_report_format(ns2, NS2_REPORT_PRO);
		case NS2_CTLR_TYPE_GC:
			return switch2_set_report_format(ns2, NS2_REPORT_GC);
		default:
			switch2_init_step_done(ns2, ns2->init_step);
			return switch2_init_controller(ns2);
		}
	case NS2_INIT_INPUT:
		if (ns2->hdev)
			return switch2_init_input(ns2);
		break;
	case NS2_INIT_SET_PLAYER_LEDS:
		return switch2_set_player_id(ns2, ns2->player_id);
	case NS2_INIT_FINISH:
		return ns2->cfg->send_command(NS2_CMD_INIT, NS2_SUBCMD_INIT_USB,
			switch2_init_cmd_data, sizeof(switch2_init_cmd_data), ns2->cfg);
	default:
		WARN_ON_ONCE(1);
		break;
	}
	return 0;
}

int switch2_receive_command(struct switch2_controller *ns2,
	const uint8_t *message, size_t length)
{
	const struct switch2_cmd_header *header;
	int ret = 0;

	if (length < 8)
		return -EINVAL;

	print_hex_dump_debug("got cmd: ", DUMP_PREFIX_OFFSET, 16, 1, message, length, false);

	mutex_lock(&ns2->lock);

	header = (const struct switch2_cmd_header *)message;
	if (!(header->flags & NS2_FLAG_OK)) {
		if (ns2->cfg)
			dev_warn(ns2->cfg->dev, "Packet error %02x replying to command %x:%x",
				header->flags, header->command, header->subcommand);
		ret = -EIO;
		goto exit;
	}
	message = &message[8];
	length -= 8;

	switch (header->command) {
	case NS2_CMD_FLASH:
		if (header->subcommand == NS2_SUBCMD_FLASH_READ) {
			uint8_t read_size;
			uint32_t read_address;

			if (length < 8) {
				ret = -EINVAL;
				goto exit;
			}
			read_size = message[0];
			read_address = get_unaligned_le32(&message[4]);
			if (length < read_size + 8) {
				ret = -EINVAL;
				goto exit;
			}
			switch2_handle_flash_read(ns2, read_size, read_address, &message[8]);
		}
		break;
	case NS2_CMD_INIT:
		if (header->subcommand == NS2_SUBCMD_INIT_USB)
			switch2_init_step_done(ns2, NS2_INIT_FINISH);
		else if (header->subcommand == NS2_SUBCMD_INIT_SELECT_REPORT)
			switch2_init_step_done(ns2, NS2_INIT_REPORT_FORMAT);
		break;
	case NS2_CMD_GRIP:
		if (header->subcommand == NS2_SUBCMD_GRIP_ENABLE_BUTTONS)
			switch2_init_step_done(ns2, NS2_INIT_GRIP_BUTTONS);
		break;
	case NS2_CMD_LED:
		if (header->subcommand == NS2_SUBCMD_LED_PATTERN)
			switch2_init_step_done(ns2, NS2_INIT_SET_PLAYER_LEDS);
		break;
	case NS2_CMD_FEATSEL:
		if (header->subcommand == NS2_SUBCMD_FEATSEL_SET_MASK)
			switch2_init_step_done(ns2, NS2_INIT_SET_FEATURE_MASK);
		else if (header->subcommand == NS2_SUBCMD_FEATSEL_ENABLE)
			switch2_init_step_done(ns2, NS2_INIT_ENABLE_FEATURES);
		break;
	case NS2_CMD_FW_INFO:
		if (header->subcommand == NS2_SUBCMD_FW_INFO_GET) {
			if (length < sizeof(ns2->version)) {
				ret = -EINVAL;
				goto exit;
			}
			memcpy(&ns2->version, message, sizeof(ns2->version));
			ns2->ctlr_type = ns2->version.ctlr_type;
			switch2_init_step_done(ns2, NS2_INIT_GET_FIRMWARE_INFO);
		}
		break;
	case 0x11:
		if (header->subcommand == 1)
			switch2_init_step_done(ns2, NS2_INIT_ENABLE_RUMBLE);
		break;
	default:
		break;
	}

exit:
	if (ns2->init_step < NS2_INIT_DONE)
		switch2_init_controller(ns2);

	mutex_unlock(&ns2->lock);
	return ret;
}
EXPORT_SYMBOL_GPL(switch2_receive_command);

int switch2_controller_attach_cfg(const char *phys, struct switch2_cfg_intf *cfg)
{
	struct switch2_controller *ns2 = switch2_get_controller(phys);
	int ret = 0;

	if (IS_ERR(ns2))
		return PTR_ERR(ns2);

	mutex_lock(&ns2->lock);
	if (ns2->cfg) {
		ret = -EBUSY;
		goto out;
	}
	cfg->parent = ns2;
	ns2->cfg = cfg;

	if (ns2->hdev)
		ret = switch2_init_controller(ns2);

	if (ret < 0) {
		if (cfg->shutdown)
			cfg->shutdown(cfg);
		cfg->parent = NULL;
		ns2->cfg = NULL;
	}

out:
	mutex_unlock(&ns2->lock);

	if (ret < 0)
		kref_put(&ns2->refcount, switch2_kref_put);
	return ret;
}
EXPORT_SYMBOL_GPL(switch2_controller_attach_cfg);

void switch2_controller_detach_cfg(struct switch2_controller *ns2)
{
	mutex_lock(&ns2->lock);
	if (!ns2->cfg || WARN_ON(ns2 != ns2->cfg->parent)) {
		mutex_unlock(&ns2->lock);
		return;
	}
	if (ns2->cfg->shutdown)
		ns2->cfg->shutdown(ns2->cfg);
	ns2->cfg->parent = NULL;
	ns2->cfg = NULL;
	mutex_unlock(&ns2->lock);
	switch2_controller_put(ns2);
	kref_put(&ns2->refcount, switch2_kref_put);
}
EXPORT_SYMBOL_GPL(switch2_controller_detach_cfg);

static int switch2_probe(struct hid_device *hdev, const struct hid_device_id *id)
{
	struct switch2_controller *ns2;
	struct usb_device *udev;
	char phys[64];
	int ret;

	if (!hid_is_usb(hdev))
		return -ENODEV;

	udev = hid_to_usb_dev(hdev);
	if (usb_make_path(udev, phys, sizeof(phys)) < 0)
		return -EINVAL;

	ret = hid_parse(hdev);
	if (ret) {
		hid_err(hdev, "parse failed %d\n", ret);
		return ret;
	}

	ns2 = switch2_get_controller(phys);
	if (IS_ERR(ns2))
		return PTR_ERR(ns2);

	mutex_lock(&ns2->lock);
	if (ns2->hdev) {
		mutex_unlock(&ns2->lock);
		hid_err(hdev,
			"Second hdev tried to claim same controller, first=%p vs second=%p\n",
			ns2->hdev, hdev);
		kref_put(&ns2->refcount, switch2_kref_put);
		return -EBUSY;
	}
	ns2->hdev = hdev;
	hid_set_drvdata(hdev, ns2);

	switch (hdev->product | (hdev->vendor << 16)) {
	default:
		strscpy(ns2->name, hdev->name, sizeof(ns2->name));
		break;
	/* Some controllers have slightly wrong names so we override them */
	case USB_DEVICE_ID_NINTENDO_NS2_JOYCONR | (USB_VENDOR_ID_NINTENDO << 16):
		/* Missing the "2" in the name */
		strscpy(ns2->name, "Nintendo Joy-Con 2 (R)", sizeof(ns2->name));
		break;
	case USB_DEVICE_ID_NINTENDO_NS2_GCCON | (USB_VENDOR_ID_NINTENDO << 16):
		/* Has "Nintendo" in the name twice */
		strscpy(ns2->name, "Nintendo GameCube Controller", sizeof(ns2->name));
		break;
	}

	ns2->player_id = U32_MAX;
	ret = ida_alloc(&nintendo_player_id_allocator, GFP_KERNEL);
	if (ret < 0)
		hid_warn(hdev, "Failed to allocate player ID, skipping; ret=%d\n", ret);
	else
		ns2->player_id = ret;

	ret = hid_hw_start(hdev, HID_CONNECT_HIDRAW);
	if (ret) {
		hid_err(hdev, "hw_start failed %d\n", ret);
		goto err_cleanup;
	}

	ret = hid_hw_open(hdev);
	if (ret) {
		hid_err(hdev, "hw_open failed %d\n", ret);
		goto err_stop;
	}

	ret = 0;
	if (ns2->cfg)
		ret = switch2_init_controller(ns2);

	if (!ret) {
		mutex_unlock(&ns2->lock);
		return 0;
	}

	hid_hw_close(hdev);
err_stop:
	hid_hw_stop(hdev);
err_cleanup:
	ida_free(&nintendo_player_id_allocator, ns2->player_id);
	ns2->hdev = NULL;
	mutex_unlock(&ns2->lock);
	switch2_controller_put(ns2);
	kref_put(&ns2->refcount, switch2_kref_put);

	return ret;
}

static void switch2_remove(struct hid_device *hdev)
{
	struct switch2_controller *ns2 = hid_get_drvdata(hdev);

	switch2_controller_put(ns2);
	mutex_lock(&ns2->lock);
	ns2->hdev = NULL;
	ida_free(&nintendo_player_id_allocator, ns2->player_id);
	mutex_unlock(&ns2->lock);
	kref_put(&ns2->refcount, switch2_kref_put);
	hid_hw_close(hdev);
	hid_hw_stop(hdev);
}

static const struct hid_device_id nintendo_hid_devices[] = {
	/* Switch devices */
	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
			 USB_DEVICE_ID_NINTENDO_PROCON) },
	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
			 USB_DEVICE_ID_NINTENDO_SNESCON) },
	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
			 USB_DEVICE_ID_NINTENDO_GENCON) },
	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
			 USB_DEVICE_ID_NINTENDO_N64CON) },
	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
			 USB_DEVICE_ID_NINTENDO_PROCON) },
	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
			 USB_DEVICE_ID_NINTENDO_CHRGGRIP) },
	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
			 USB_DEVICE_ID_NINTENDO_JOYCONL) },
	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
			 USB_DEVICE_ID_NINTENDO_JOYCONR) },
	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
			 USB_DEVICE_ID_NINTENDO_SNESCON) },
	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
			 USB_DEVICE_ID_NINTENDO_GENCON) },
	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_NINTENDO,
			 USB_DEVICE_ID_NINTENDO_N64CON) },
	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_HORI,
			 USB_DEVICE_ID_HORI_WIRELESS_SWITCH_PAD) },
	{ HID_BLUETOOTH_DEVICE(USB_VENDOR_ID_PDP,
			 USB_DEVICE_ID_PDP_SWITCH_AFTERGLOW) },
	/* Switch 2 devices */
	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
			 USB_DEVICE_ID_NINTENDO_NS2_JOYCONL) },
	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
			 USB_DEVICE_ID_NINTENDO_NS2_JOYCONR) },
	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
			 USB_DEVICE_ID_NINTENDO_NS2_PROCON) },
	{ HID_USB_DEVICE(USB_VENDOR_ID_NINTENDO,
			 USB_DEVICE_ID_NINTENDO_NS2_GCCON) },
	{ }
};
MODULE_DEVICE_TABLE(hid, nintendo_hid_devices);

static bool nintendo_is_switch2(struct hid_device *hdev)
{
	return hdev->vendor == USB_VENDOR_ID_NINTENDO &&
		hdev->product >= USB_DEVICE_ID_NINTENDO_NS2_JOYCONR;
}

static void nintendo_hid_remove(struct hid_device *hdev)
{
	if (nintendo_is_switch2(hdev))
		switch2_remove(hdev);
	else
		joycon_remove(hdev);
}

static int nintendo_hid_event(struct hid_device *hdev,
			      struct hid_report *report, u8 *raw_data, int size)
{
	if (nintendo_is_switch2(hdev))
		return switch2_event(hdev, report, raw_data, size);
	else
		return joycon_event(hdev, report, raw_data, size);
}

static const __u8 *nintendo_hid_report_fixup(struct hid_device *hdev,
			    __u8 *rdesc, unsigned int *rsize)
{
	if (hdev->vendor == USB_VENDOR_ID_NINTENDO &&
		hdev->product == USB_DEVICE_ID_NINTENDO_NS2_JOYCONR &&
		*rsize == 100 && rdesc[24] == NS2_REPORT_JCL)
		/*
		 * The NYXI Hyperion 3 right Joy-Con accidentally reports as the
		 * left one. Since the HID subsystem rejects report IDs that
		 * aren't listed in the descriptor, we need to patch it.
		 */
		rdesc[24] = NS2_REPORT_JCR;
	return rdesc;
}

static int nintendo_hid_probe(struct hid_device *hdev,
			    const struct hid_device_id *id)
{
	if (nintendo_is_switch2(hdev))
		return switch2_probe(hdev, id);
	else
		return joycon_probe(hdev, id);
}

static int nintendo_hid_resume(struct hid_device *hdev)
{
	if (nintendo_is_switch2(hdev))
		return 0;
	else
		return joycon_resume(hdev);
}

static int nintendo_hid_suspend(struct hid_device *hdev, pm_message_t message)
{
	if (nintendo_is_switch2(hdev))
		return 0;
	else
		return joycon_suspend(hdev, message);
}

static struct hid_driver nintendo_hid_driver = {
	.name		= "nintendo",
	.id_table	= nintendo_hid_devices,
	.report_fixup	= nintendo_hid_report_fixup,
	.probe		= nintendo_hid_probe,
	.remove		= nintendo_hid_remove,
	.raw_event	= nintendo_hid_event,
	.resume		= pm_ptr(nintendo_hid_resume),
	.suspend	= pm_ptr(nintendo_hid_suspend),
};
static int __init nintendo_init(void)
{
	return hid_register_driver(&nintendo_hid_driver);
}

static void __exit nintendo_exit(void)
{
	hid_unregister_driver(&nintendo_hid_driver);
	ida_destroy(&nintendo_player_id_allocator);
}

module_init(nintendo_init);
module_exit(nintendo_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Ryan McClelland <rymcclel@gmail.com>");
MODULE_AUTHOR("Emily Strickland <linux@emily.st>");
MODULE_AUTHOR("Daniel J. Ogorchock <djogorchock@gmail.com>");
MODULE_AUTHOR("Vicki Pfau <vi@endrift.com>");
MODULE_DESCRIPTION("Driver for Nintendo Switch Controllers");