summaryrefslogtreecommitdiffstats
path: root/drivers/usb/gadget/function/f_midi2.c
blob: ee3d9e3578f791bd14393da3b9074b11ecd9023d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
// SPDX-License-Identifier: GPL-2.0+
/*
 * f_midi2.c -- USB MIDI 2.0 class function driver
 */

#include <linux/device.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>

#include <sound/core.h>
#include <sound/control.h>
#include <sound/ump.h>
#include <sound/ump_msg.h>
#include <sound/ump_convert.h>

#include <linux/usb/ch9.h>
#include <linux/usb/func_utils.h>
#include <linux/usb/gadget.h>
#include <linux/usb/audio.h>
#include <linux/usb/midi-v2.h>

#include "u_midi2.h"

struct f_midi2;
struct f_midi2_ep;
struct f_midi2_usb_ep;

/* Context for each USB request */
struct f_midi2_req_ctx {
	struct f_midi2_usb_ep *usb_ep;	/* belonging USB EP */
	unsigned int index;		/* array index: 0-31 */
	struct usb_request *req;	/* assigned request */
};

/* Resources for a USB Endpoint */
struct f_midi2_usb_ep {
	struct f_midi2 *card;		/* belonging card */
	struct f_midi2_ep *ep;		/* belonging UMP EP (optional) */
	struct usb_ep *usb_ep;		/* assigned USB EP */
	void (*complete)(struct usb_ep *usb_ep, struct usb_request *req);
	unsigned long free_reqs;	/* bitmap for unused requests */
	unsigned int num_reqs;		/* number of allocated requests */
	struct f_midi2_req_ctx *reqs;	/* request context array */
};

/* Resources for UMP Function Block (and USB Group Terminal Block) */
struct f_midi2_block {
	struct f_midi2_block_info info;	/* FB info, copied from configfs */
	struct snd_ump_block *fb;	/* assigned FB */
	unsigned int gtb_id;		/* assigned GTB id */
	unsigned int string_id;		/* assigned string id */
};

/* Temporary buffer for altset 0 MIDI 1.0 handling */
struct f_midi2_midi1_port {
	unsigned int pending; /* pending bytes on the input buffer */
	u8 buf[32];	/* raw MIDI 1.0 byte input */
	u8 state;	/* running status */
	u8 data[2];	/* rendered USB MIDI 1.0 packet data */
};

/* MIDI 1.0 message states */
enum {
	STATE_INITIAL = 0,	/* pseudo state */
	STATE_1PARAM,
	STATE_2PARAM_1,
	STATE_2PARAM_2,
	STATE_SYSEX_0,
	STATE_SYSEX_1,
	STATE_SYSEX_2,
	STATE_REAL_TIME,
	STATE_FINISHED,		/* pseudo state */
};

/* Resources for UMP Endpoint */
struct f_midi2_ep {
	struct snd_ump_endpoint *ump;	/* assigned UMP EP */
	struct f_midi2 *card;		/* belonging MIDI 2.0 device */

	struct f_midi2_ep_info info;	/* UMP EP info, copied from configfs */
	unsigned int num_blks;		/* number of FBs */
	struct f_midi2_block blks[SNDRV_UMP_MAX_BLOCKS];	/* UMP FBs */

	struct f_midi2_usb_ep ep_in;	/* USB MIDI EP-in */
	struct f_midi2_usb_ep ep_out;	/* USB MIDI EP-out */

	u8 in_group_to_cable[SNDRV_UMP_MAX_GROUPS]; /* map to cable; 1-based! */
};

/* indices for USB strings */
enum {
	STR_IFACE = 0,
	STR_GTB1 = 1,
};

/* 1-based GTB id to string id */
#define gtb_to_str_id(id)	(STR_GTB1 + (id) - 1)

/* mapping from MIDI 1.0 cable to UMP group */
struct midi1_cable_mapping {
	struct f_midi2_ep *ep;
	unsigned char block;
	unsigned char group;
};

/* operation mode */
enum {
	MIDI_OP_MODE_UNSET,	/* no altset set yet */
	MIDI_OP_MODE_MIDI1,	/* MIDI 1.0 (altset 0) is used */
	MIDI_OP_MODE_MIDI2,	/* MIDI 2.0 (altset 1) is used */
};

/* Resources for MIDI 2.0 Device */
struct f_midi2 {
	struct usb_function func;
	struct usb_gadget *gadget;
	struct snd_card *card;

	/* MIDI 1.0 in/out USB EPs */
	struct f_midi2_usb_ep midi1_ep_in;
	struct f_midi2_usb_ep midi1_ep_out;

	/* number of MIDI 1.0 I/O cables */
	unsigned int num_midi1_in;
	unsigned int num_midi1_out;

	/* conversion for MIDI 1.0 EP-in */
	struct f_midi2_midi1_port midi1_port[MAX_CABLES];
	/* conversion for MIDI 1.0 EP-out */
	struct ump_cvt_to_ump midi1_ump_cvt;
	/* mapping between cables and UMP groups */
	struct midi1_cable_mapping in_cable_mapping[MAX_CABLES];
	struct midi1_cable_mapping out_cable_mapping[MAX_CABLES];

	int midi_if;			/* USB MIDI interface number */
	int operation_mode;		/* current operation mode */

	spinlock_t queue_lock;

	struct f_midi2_card_info info;	/* card info, copied from configfs */

	unsigned int num_eps;
	struct f_midi2_ep midi2_eps[MAX_UMP_EPS];

	unsigned int total_blocks;	/* total number of blocks of all EPs */
	struct usb_string *string_defs;
	struct usb_string *strings;
};

#define func_to_midi2(f)	container_of(f, struct f_midi2, func)

/* convert from MIDI protocol number (1 or 2) to SNDRV_UMP_EP_INFO_PROTO_* */
#define to_ump_protocol(v)	(((v) & 3) << 8)

/* get EP name string */
static const char *ump_ep_name(const struct f_midi2_ep *ep)
{
	return ep->info.ep_name ? ep->info.ep_name : "MIDI 2.0 Gadget";
}

/* get EP product ID string */
static const char *ump_product_id(const struct f_midi2_ep *ep)
{
	return ep->info.product_id ? ep->info.product_id : "Unique Product ID";
}

/* get FB name string */
static const char *ump_fb_name(const struct f_midi2_block_info *info)
{
	return info->name ? info->name : "MIDI 2.0 Gadget I/O";
}

/*
 * USB Descriptor Definitions
 */
/* GTB header descriptor */
static struct usb_ms20_gr_trm_block_header_descriptor gtb_header_desc = {
	.bLength =		sizeof(gtb_header_desc),
	.bDescriptorType =	USB_DT_CS_GR_TRM_BLOCK,
	.bDescriptorSubtype =	USB_MS_GR_TRM_BLOCK_HEADER,
	.wTotalLength =		__cpu_to_le16(0x12), // to be filled
};

/* GTB descriptor template: most items are replaced dynamically */
static struct usb_ms20_gr_trm_block_descriptor gtb_desc = {
	.bLength =		sizeof(gtb_desc),
	.bDescriptorType =	USB_DT_CS_GR_TRM_BLOCK,
	.bDescriptorSubtype =	USB_MS_GR_TRM_BLOCK,
	.bGrpTrmBlkID =		0x01,
	.bGrpTrmBlkType =	USB_MS_GR_TRM_BLOCK_TYPE_BIDIRECTIONAL,
	.nGroupTrm =		0x00,
	.nNumGroupTrm =		1,
	.iBlockItem =		0,
	.bMIDIProtocol =	USB_MS_MIDI_PROTO_1_0_64,
	.wMaxInputBandwidth =	0,
	.wMaxOutputBandwidth =	0,
};

DECLARE_USB_MIDI_OUT_JACK_DESCRIPTOR(1);
DECLARE_USB_MS_ENDPOINT_DESCRIPTOR(16);
DECLARE_UAC_AC_HEADER_DESCRIPTOR(1);
DECLARE_USB_MS20_ENDPOINT_DESCRIPTOR(32);

#define EP_MAX_PACKET_INT	8

/* Audio Control Interface */
static struct usb_interface_descriptor midi2_audio_if_desc = {
	.bLength =		USB_DT_INTERFACE_SIZE,
	.bDescriptorType =	USB_DT_INTERFACE,
	.bInterfaceNumber =	0, // to be filled
	.bNumEndpoints =	0,
	.bInterfaceClass =	USB_CLASS_AUDIO,
	.bInterfaceSubClass =	USB_SUBCLASS_AUDIOCONTROL,
	.bInterfaceProtocol =	0,
	.iInterface =		0,
};

static struct uac1_ac_header_descriptor_1 midi2_audio_class_desc = {
	.bLength =		0x09,
	.bDescriptorType =	USB_DT_CS_INTERFACE,
	.bDescriptorSubtype =	0x01,
	.bcdADC =		__cpu_to_le16(0x0100),
	.wTotalLength =		__cpu_to_le16(0x0009),
	.bInCollection =	0x01,
	.baInterfaceNr =	{ 0x01 }, // to be filled
};

/* MIDI 1.0 Streaming Interface (altset 0) */
static struct usb_interface_descriptor midi2_midi1_if_desc = {
	.bLength =		USB_DT_INTERFACE_SIZE,
	.bDescriptorType =	USB_DT_INTERFACE,
	.bInterfaceNumber =	0, // to be filled
	.bAlternateSetting =	0,
	.bNumEndpoints =	2, // to be filled
	.bInterfaceClass =	USB_CLASS_AUDIO,
	.bInterfaceSubClass =	USB_SUBCLASS_MIDISTREAMING,
	.bInterfaceProtocol =	0,
	.iInterface =		0, // to be filled
};

static struct usb_ms_header_descriptor midi2_midi1_class_desc = {
	.bLength =		0x07,
	.bDescriptorType =	USB_DT_CS_INTERFACE,
	.bDescriptorSubtype =	USB_MS_HEADER,
	.bcdMSC =		__cpu_to_le16(0x0100),
	.wTotalLength =		__cpu_to_le16(0x41), // to be calculated
};

/* MIDI 1.0 EP OUT */
static struct usb_endpoint_descriptor midi2_midi1_ep_out_desc = {
	.bLength =		USB_DT_ENDPOINT_AUDIO_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,
	.bEndpointAddress =	USB_DIR_OUT | 0, // set up dynamically
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
};

static struct usb_ss_ep_comp_descriptor midi2_midi1_ep_out_ss_comp_desc = {
	.bLength                = sizeof(midi2_midi1_ep_out_ss_comp_desc),
	.bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,
};

static struct usb_ms_endpoint_descriptor_16 midi2_midi1_ep_out_class_desc = {
	.bLength =		0x05, // to be filled
	.bDescriptorType =	USB_DT_CS_ENDPOINT,
	.bDescriptorSubtype =	USB_MS_GENERAL,
	.bNumEmbMIDIJack =	1,
	.baAssocJackID =	{ 0x01 },
};

/* MIDI 1.0 EP IN */
static struct usb_endpoint_descriptor midi2_midi1_ep_in_desc = {
	.bLength =		USB_DT_ENDPOINT_AUDIO_SIZE,
	.bDescriptorType =	USB_DT_ENDPOINT,
	.bEndpointAddress =	USB_DIR_IN | 0, // set up dynamically
	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
};

static struct usb_ss_ep_comp_descriptor midi2_midi1_ep_in_ss_comp_desc = {
	.bLength                = sizeof(midi2_midi1_ep_in_ss_comp_desc),
	.bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,
};

static struct usb_ms_endpoint_descriptor_16 midi2_midi1_ep_in_class_desc = {
	.bLength =		0x05, // to be filled
	.bDescriptorType =	USB_DT_CS_ENDPOINT,
	.bDescriptorSubtype =	USB_MS_GENERAL,
	.bNumEmbMIDIJack =	1,
	.baAssocJackID =	{ 0x03 },
};

/* MIDI 2.0 Streaming Interface (altset 1) */
static struct usb_interface_descriptor midi2_midi2_if_desc = {
	.bLength =		USB_DT_INTERFACE_SIZE,
	.bDescriptorType =	USB_DT_INTERFACE,
	.bInterfaceNumber =	0, // to be filled
	.bAlternateSetting =	1,
	.bNumEndpoints =	2, // to be filled
	.bInterfaceClass =	USB_CLASS_AUDIO,
	.bInterfaceSubClass =	USB_SUBCLASS_MIDISTREAMING,
	.bInterfaceProtocol =	0,
	.iInterface =		0, // to be filled
};

static struct usb_ms_header_descriptor midi2_midi2_class_desc = {
	.bLength =		0x07,
	.bDescriptorType =	USB_DT_CS_INTERFACE,
	.bDescriptorSubtype =	USB_MS_HEADER,
	.bcdMSC =		__cpu_to_le16(0x0200),
	.wTotalLength =		__cpu_to_le16(0x07),
};

/* MIDI 2.0 EP OUT */
static struct usb_endpoint_descriptor midi2_midi2_ep_out_desc[MAX_UMP_EPS];

static struct usb_ss_ep_comp_descriptor midi2_midi2_ep_out_ss_comp_desc = {
	.bLength                = sizeof(midi2_midi1_ep_out_ss_comp_desc),
	.bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,
};

static struct usb_ms20_endpoint_descriptor_32 midi2_midi2_ep_out_class_desc[MAX_UMP_EPS];

/* MIDI 2.0 EP IN */
static struct usb_endpoint_descriptor midi2_midi2_ep_in_desc[MAX_UMP_EPS];

static struct usb_ss_ep_comp_descriptor midi2_midi2_ep_in_ss_comp_desc = {
	.bLength                = sizeof(midi2_midi2_ep_in_ss_comp_desc),
	.bDescriptorType        = USB_DT_SS_ENDPOINT_COMP,
};

static struct usb_ms20_endpoint_descriptor_32 midi2_midi2_ep_in_class_desc[MAX_UMP_EPS];

/* Arrays of descriptors to be created */
static void *midi2_audio_descs[] = {
	&midi2_audio_if_desc,
	&midi2_audio_class_desc,
	NULL
};

static void *midi2_midi1_descs[] = {
	&midi2_midi1_if_desc,
	&midi2_midi1_class_desc,
	NULL
};

static void *midi2_midi1_ep_out_descs[] = {
	&midi2_midi1_ep_out_desc,
	&midi2_midi1_ep_out_class_desc,
	NULL
};

static void *midi2_midi1_ep_in_descs[] = {
	&midi2_midi1_ep_in_desc,
	&midi2_midi1_ep_in_class_desc,
	NULL
};

static void *midi2_midi1_ep_out_ss_descs[] = {
	&midi2_midi1_ep_out_desc,
	&midi2_midi1_ep_out_ss_comp_desc,
	&midi2_midi1_ep_out_class_desc,
	NULL
};

static void *midi2_midi1_ep_in_ss_descs[] = {
	&midi2_midi1_ep_in_desc,
	&midi2_midi1_ep_in_ss_comp_desc,
	&midi2_midi1_ep_in_class_desc,
	NULL
};

static void *midi2_midi2_descs[] = {
	&midi2_midi2_if_desc,
	&midi2_midi2_class_desc,
	NULL
};

/*
 * USB request handling
 */

/* get an empty request for the given EP */
static struct usb_request *get_empty_request(struct f_midi2_usb_ep *usb_ep)
{
	struct usb_request *req = NULL;
	unsigned long flags;
	int index;

	spin_lock_irqsave(&usb_ep->card->queue_lock, flags);
	if (!usb_ep->free_reqs)
		goto unlock;
	index = find_first_bit(&usb_ep->free_reqs, usb_ep->num_reqs);
	if (index >= usb_ep->num_reqs)
		goto unlock;
	req = usb_ep->reqs[index].req;
	if (!req)
		goto unlock;
	clear_bit(index, &usb_ep->free_reqs);
	req->length = 0;
 unlock:
	spin_unlock_irqrestore(&usb_ep->card->queue_lock, flags);
	return req;
}

/* put the empty request back */
static void put_empty_request(struct usb_request *req)
{
	struct f_midi2_req_ctx *ctx = req->context;
	unsigned long flags;

	spin_lock_irqsave(&ctx->usb_ep->card->queue_lock, flags);
	set_bit(ctx->index, &ctx->usb_ep->free_reqs);
	spin_unlock_irqrestore(&ctx->usb_ep->card->queue_lock, flags);
}

/*
 * UMP v1.1 Stream message handling
 */

/* queue a request to UMP EP; request is either queued or freed after this */
static int queue_request_ep_raw(struct usb_request *req)
{
	struct f_midi2_req_ctx *ctx = req->context;
	int err;

	req->complete = ctx->usb_ep->complete;
	err = usb_ep_queue(ctx->usb_ep->usb_ep, req, GFP_ATOMIC);
	if (err) {
		put_empty_request(req);
		return err;
	}
	return 0;
}

/* queue a request with endianness conversion */
static int queue_request_ep_in(struct usb_request *req)
{
	/* UMP packets have to be converted to little-endian */
	cpu_to_le32_array((u32 *)req->buf, req->length >> 2);
	return queue_request_ep_raw(req);
}

/* reply a UMP packet via EP-in */
static int reply_ep_in(struct f_midi2_ep *ep, const void *buf, int len)
{
	struct f_midi2_usb_ep *usb_ep = &ep->ep_in;
	struct usb_request *req;

	req = get_empty_request(usb_ep);
	if (!req)
		return -ENOSPC;

	req->length = len;
	memcpy(req->buf, buf, len);
	return queue_request_ep_in(req);
}

/* reply a UMP stream EP info */
static void reply_ump_stream_ep_info(struct f_midi2_ep *ep)
{
	struct snd_ump_stream_msg_ep_info rep = {
		.type = UMP_MSG_TYPE_STREAM,
		.status = UMP_STREAM_MSG_STATUS_EP_INFO,
		.ump_version_major = 0x01,
		.ump_version_minor = 0x01,
		.num_function_blocks = ep->num_blks,
		.static_function_block = !!ep->card->info.static_block,
		.protocol = (UMP_STREAM_MSG_EP_INFO_CAP_MIDI1 |
			     UMP_STREAM_MSG_EP_INFO_CAP_MIDI2) >> 8,
	};

	reply_ep_in(ep, &rep, sizeof(rep));
}

/* reply a UMP EP device info */
static void reply_ump_stream_ep_device(struct f_midi2_ep *ep)
{
	struct snd_ump_stream_msg_devince_info rep = {
		.type = UMP_MSG_TYPE_STREAM,
		.status = UMP_STREAM_MSG_STATUS_DEVICE_INFO,
		.manufacture_id = ep->info.manufacturer,
		.family_lsb = ep->info.family & 0xff,
		.family_msb = (ep->info.family >> 8) & 0xff,
		.model_lsb = ep->info.model & 0xff,
		.model_msb = (ep->info.model >> 8) & 0xff,
		.sw_revision = ep->info.sw_revision,
	};

	reply_ep_in(ep, &rep, sizeof(rep));
}

#define UMP_STREAM_PKT_BYTES	16	/* UMP stream packet size = 16 bytes*/
#define UMP_STREAM_EP_STR_OFF	2	/* offset of name string for EP info */
#define UMP_STREAM_FB_STR_OFF	3	/* offset of name string for FB info */

/* Helper to replay a string */
static void reply_ump_stream_string(struct f_midi2_ep *ep, const u8 *name,
				    unsigned int type, unsigned int extra,
				    unsigned int start_ofs)
{
	struct f_midi2_usb_ep *usb_ep = &ep->ep_in;
	struct f_midi2 *midi2 = ep->card;
	struct usb_request *req;
	unsigned int pos;
	u32 *buf;

	if (!*name)
		return;
	req = get_empty_request(usb_ep);
	if (!req)
		return;

	buf = (u32 *)req->buf;
	pos = start_ofs;
	for (;;) {
		if (pos == start_ofs) {
			memset(buf, 0, UMP_STREAM_PKT_BYTES);
			buf[0] = ump_stream_compose(type, 0) | extra;
		}
		buf[pos / 4] |= *name++ << ((3 - (pos % 4)) * 8);
		if (!*name) {
			if (req->length)
				buf[0] |= UMP_STREAM_MSG_FORMAT_END << 26;
			req->length += UMP_STREAM_PKT_BYTES;
			break;
		}
		if (++pos == UMP_STREAM_PKT_BYTES) {
			if (!req->length)
				buf[0] |= UMP_STREAM_MSG_FORMAT_START << 26;
			else
				buf[0] |= UMP_STREAM_MSG_FORMAT_CONTINUE << 26;
			req->length += UMP_STREAM_PKT_BYTES;
			if (midi2->info.req_buf_size - req->length < UMP_STREAM_PKT_BYTES)
				break;
			buf += 4;
			pos = start_ofs;
		}
	}

	if (req->length)
		queue_request_ep_in(req);
	else
		put_empty_request(req);
}

/* Reply a UMP EP name string */
static void reply_ump_stream_ep_name(struct f_midi2_ep *ep)
{
	reply_ump_stream_string(ep, ump_ep_name(ep),
				UMP_STREAM_MSG_STATUS_EP_NAME, 0,
				UMP_STREAM_EP_STR_OFF);
}

/* Reply a UMP EP product ID string */
static void reply_ump_stream_ep_pid(struct f_midi2_ep *ep)
{
	reply_ump_stream_string(ep, ump_product_id(ep),
				UMP_STREAM_MSG_STATUS_PRODUCT_ID, 0,
				UMP_STREAM_EP_STR_OFF);
}

/* Reply a UMP EP stream config */
static void reply_ump_stream_ep_config(struct f_midi2_ep *ep)
{
	struct snd_ump_stream_msg_stream_cfg rep = {
		.type = UMP_MSG_TYPE_STREAM,
		.status = UMP_STREAM_MSG_STATUS_STREAM_CFG,
	};

	if (ep->info.protocol == 2)
		rep.protocol = UMP_STREAM_MSG_EP_INFO_CAP_MIDI2 >> 8;
	else
		rep.protocol = UMP_STREAM_MSG_EP_INFO_CAP_MIDI1 >> 8;

	reply_ep_in(ep, &rep, sizeof(rep));
}

/* Reply a UMP FB info */
static void reply_ump_stream_fb_info(struct f_midi2_ep *ep, int blk)
{
	struct f_midi2_block_info *b = &ep->blks[blk].info;
	struct snd_ump_stream_msg_fb_info rep = {
		.type = UMP_MSG_TYPE_STREAM,
		.status = UMP_STREAM_MSG_STATUS_FB_INFO,
		.active = !!b->active,
		.function_block_id = blk,
		.ui_hint = b->ui_hint,
		.midi_10 = b->is_midi1,
		.direction = b->direction,
		.first_group = b->first_group,
		.num_groups = b->num_groups,
		.midi_ci_version = b->midi_ci_version,
		.sysex8_streams = b->sysex8_streams,
	};

	reply_ep_in(ep, &rep, sizeof(rep));
}

/* Reply a FB name string */
static void reply_ump_stream_fb_name(struct f_midi2_ep *ep, unsigned int blk)
{
	reply_ump_stream_string(ep, ump_fb_name(&ep->blks[blk].info),
				UMP_STREAM_MSG_STATUS_FB_NAME, blk << 8,
				UMP_STREAM_FB_STR_OFF);
}

/* Process a UMP Stream message */
static void process_ump_stream_msg(struct f_midi2_ep *ep, const u32 *data)
{
	struct f_midi2 *midi2 = ep->card;
	unsigned int format, status, blk;

	format = ump_stream_message_format(*data);
	status = ump_stream_message_status(*data);
	switch (status) {
	case UMP_STREAM_MSG_STATUS_EP_DISCOVERY:
		if (format)
			return; // invalid
		if (data[1] & UMP_STREAM_MSG_REQUEST_EP_INFO)
			reply_ump_stream_ep_info(ep);
		if (data[1] & UMP_STREAM_MSG_REQUEST_DEVICE_INFO)
			reply_ump_stream_ep_device(ep);
		if (data[1] & UMP_STREAM_MSG_REQUEST_EP_NAME)
			reply_ump_stream_ep_name(ep);
		if (data[1] & UMP_STREAM_MSG_REQUEST_PRODUCT_ID)
			reply_ump_stream_ep_pid(ep);
		if (data[1] & UMP_STREAM_MSG_REQUEST_STREAM_CFG)
			reply_ump_stream_ep_config(ep);
		return;
	case UMP_STREAM_MSG_STATUS_STREAM_CFG_REQUEST:
		if (*data & UMP_STREAM_MSG_EP_INFO_CAP_MIDI2) {
			ep->info.protocol = 2;
			DBG(midi2, "Switching Protocol to MIDI2\n");
		} else {
			ep->info.protocol = 1;
			DBG(midi2, "Switching Protocol to MIDI1\n");
		}
		snd_ump_switch_protocol(ep->ump, to_ump_protocol(ep->info.protocol));
		reply_ump_stream_ep_config(ep);
		return;
	case UMP_STREAM_MSG_STATUS_FB_DISCOVERY:
		if (format)
			return; // invalid
		blk = (*data >> 8) & 0xff;
		if (blk == 0xff) {
			/* inquiry for all blocks */
			for (blk = 0; blk < ep->num_blks; blk++) {
				if (*data & UMP_STREAM_MSG_REQUEST_FB_INFO)
					reply_ump_stream_fb_info(ep, blk);
				if (*data & UMP_STREAM_MSG_REQUEST_FB_NAME)
					reply_ump_stream_fb_name(ep, blk);
			}
		} else if (blk < ep->num_blks) {
			/* only the specified block */
			if (*data & UMP_STREAM_MSG_REQUEST_FB_INFO)
				reply_ump_stream_fb_info(ep, blk);
			if (*data & UMP_STREAM_MSG_REQUEST_FB_NAME)
				reply_ump_stream_fb_name(ep, blk);
		}
		return;
	}
}

/* Process UMP messages included in a USB request */
static void process_ump(struct f_midi2_ep *ep, const struct usb_request *req)
{
	const u32 *data = (u32 *)req->buf;
	int len = req->actual >> 2;
	const u32 *in_buf = ep->ump->input_buf;

	for (; len > 0; len--, data++) {
		if (snd_ump_receive_ump_val(ep->ump, *data) <= 0)
			continue;
		if (ump_message_type(*in_buf) == UMP_MSG_TYPE_STREAM)
			process_ump_stream_msg(ep, in_buf);
	}
}

/*
 * MIDI 2.0 UMP USB request handling
 */

/* complete handler for UMP EP-out requests */
static void f_midi2_ep_out_complete(struct usb_ep *usb_ep,
				    struct usb_request *req)
{
	struct f_midi2_req_ctx *ctx = req->context;
	struct f_midi2_ep *ep = ctx->usb_ep->ep;
	struct f_midi2 *midi2 = ep->card;
	int status = req->status;

	if (status) {
		DBG(midi2, "%s complete error %d: %d/%d\n",
		    usb_ep->name, status, req->actual, req->length);
		goto error;
	}

	/* convert to UMP packet in native endianness */
	le32_to_cpu_array((u32 *)req->buf, req->actual >> 2);

	if (midi2->info.process_ump)
		process_ump(ep, req);

	snd_ump_receive(ep->ump, req->buf, req->actual & ~3);

	if (midi2->operation_mode != MIDI_OP_MODE_MIDI2)
		goto error;

	if (queue_request_ep_raw(req))
		goto error;
	return;

 error:
	put_empty_request(req);
}

/* Transmit UMP packets received from user-space to the gadget */
static void process_ump_transmit(struct f_midi2_ep *ep)
{
	struct f_midi2_usb_ep *usb_ep = &ep->ep_in;
	struct f_midi2 *midi2 = ep->card;
	struct usb_request *req;
	int len;

	if (!usb_ep->usb_ep->enabled)
		return;

	for (;;) {
		req = get_empty_request(usb_ep);
		if (!req)
			break;
		len = snd_ump_transmit(ep->ump, (u32 *)req->buf,
				       midi2->info.req_buf_size);
		if (len <= 0) {
			put_empty_request(req);
			break;
		}

		req->length = len;
		if (queue_request_ep_in(req) < 0)
			break;
	}
}

/* Complete handler for UMP EP-in requests */
static void f_midi2_ep_in_complete(struct usb_ep *usb_ep,
				   struct usb_request *req)
{
	struct f_midi2_req_ctx *ctx = req->context;
	struct f_midi2_ep *ep = ctx->usb_ep->ep;
	struct f_midi2 *midi2 = ep->card;
	int status = req->status;

	put_empty_request(req);

	if (status) {
		DBG(midi2, "%s complete error %d: %d/%d\n",
		    usb_ep->name, status, req->actual, req->length);
		return;
	}

	process_ump_transmit(ep);
}

/*
 * MIDI1 (altset 0) USB request handling
 */

/* process one MIDI byte -- copied from f_midi.c
 *
 * fill the packet or request if needed
 * returns true if the request became empty (queued)
 */
static bool process_midi1_byte(struct f_midi2 *midi2, u8 cable, u8 b,
			       struct usb_request **req_p)
{
	struct f_midi2_midi1_port *port = &midi2->midi1_port[cable];
	u8 p[4] = { cable << 4, 0, 0, 0 };
	int next_state = STATE_INITIAL;
	struct usb_request *req = *req_p;

	switch (b) {
	case 0xf8 ... 0xff:
		/* System Real-Time Messages */
		p[0] |= 0x0f;
		p[1] = b;
		next_state = port->state;
		port->state = STATE_REAL_TIME;
		break;

	case 0xf7:
		/* End of SysEx */
		switch (port->state) {
		case STATE_SYSEX_0:
			p[0] |= 0x05;
			p[1] = 0xf7;
			next_state = STATE_FINISHED;
			break;
		case STATE_SYSEX_1:
			p[0] |= 0x06;
			p[1] = port->data[0];
			p[2] = 0xf7;
			next_state = STATE_FINISHED;
			break;
		case STATE_SYSEX_2:
			p[0] |= 0x07;
			p[1] = port->data[0];
			p[2] = port->data[1];
			p[3] = 0xf7;
			next_state = STATE_FINISHED;
			break;
		default:
			/* Ignore byte */
			next_state = port->state;
			port->state = STATE_INITIAL;
		}
		break;

	case 0xf0 ... 0xf6:
		/* System Common Messages */
		port->data[0] = port->data[1] = 0;
		port->state = STATE_INITIAL;
		switch (b) {
		case 0xf0:
			port->data[0] = b;
			port->data[1] = 0;
			next_state = STATE_SYSEX_1;
			break;
		case 0xf1:
		case 0xf3:
			port->data[0] = b;
			next_state = STATE_1PARAM;
			break;
		case 0xf2:
			port->data[0] = b;
			next_state = STATE_2PARAM_1;
			break;
		case 0xf4:
		case 0xf5:
			next_state = STATE_INITIAL;
			break;
		case 0xf6:
			p[0] |= 0x05;
			p[1] = 0xf6;
			next_state = STATE_FINISHED;
			break;
		}
		break;

	case 0x80 ... 0xef:
		/*
		 * Channel Voice Messages, Channel Mode Messages
		 * and Control Change Messages.
		 */
		port->data[0] = b;
		port->data[1] = 0;
		port->state = STATE_INITIAL;
		if (b >= 0xc0 && b <= 0xdf)
			next_state = STATE_1PARAM;
		else
			next_state = STATE_2PARAM_1;
		break;

	case 0x00 ... 0x7f:
		/* Message parameters */
		switch (port->state) {
		case STATE_1PARAM:
			if (port->data[0] < 0xf0)
				p[0] |= port->data[0] >> 4;
			else
				p[0] |= 0x02;

			p[1] = port->data[0];
			p[2] = b;
			/* This is to allow Running State Messages */
			next_state = STATE_1PARAM;
			break;
		case STATE_2PARAM_1:
			port->data[1] = b;
			next_state = STATE_2PARAM_2;
			break;
		case STATE_2PARAM_2:
			if (port->data[0] < 0xf0)
				p[0] |= port->data[0] >> 4;
			else
				p[0] |= 0x03;

			p[1] = port->data[0];
			p[2] = port->data[1];
			p[3] = b;
			/* This is to allow Running State Messages */
			next_state = STATE_2PARAM_1;
			break;
		case STATE_SYSEX_0:
			port->data[0] = b;
			next_state = STATE_SYSEX_1;
			break;
		case STATE_SYSEX_1:
			port->data[1] = b;
			next_state = STATE_SYSEX_2;
			break;
		case STATE_SYSEX_2:
			p[0] |= 0x04;
			p[1] = port->data[0];
			p[2] = port->data[1];
			p[3] = b;
			next_state = STATE_SYSEX_0;
			break;
		}
		break;
	}

	/* States where we have to write into the USB request */
	if (next_state == STATE_FINISHED ||
	    port->state == STATE_SYSEX_2 ||
	    port->state == STATE_1PARAM ||
	    port->state == STATE_2PARAM_2 ||
	    port->state == STATE_REAL_TIME) {
		memcpy(req->buf + req->length, p, sizeof(p));
		req->length += sizeof(p);

		if (next_state == STATE_FINISHED) {
			next_state = STATE_INITIAL;
			port->data[0] = port->data[1] = 0;
		}

		if (midi2->info.req_buf_size - req->length <= 4) {
			queue_request_ep_raw(req);
			*req_p = NULL;
			return true;
		}
	}

	port->state = next_state;
	return false;
}

/* process all pending MIDI bytes in the internal buffer;
 * returns true if the request gets empty
 * returns false if all have been processed
 */
static bool process_midi1_pending_buf(struct f_midi2 *midi2,
				      struct usb_request **req_p)
{
	unsigned int cable, c;

	for (cable = 0; cable < midi2->num_midi1_in; cable++) {
		struct f_midi2_midi1_port *port = &midi2->midi1_port[cable];

		if (!port->pending)
			continue;
		for (c = 0; c < port->pending; c++) {
			if (process_midi1_byte(midi2, cable, port->buf[c],
					       req_p)) {
				port->pending -= c;
				if (port->pending)
					memmove(port->buf, port->buf + c,
						port->pending);
				return true;
			}
		}
		port->pending = 0;
	}

	return false;
}

/* fill the MIDI bytes onto the temporary buffer
 */
static void fill_midi1_pending_buf(struct f_midi2 *midi2, u8 cable, u8 *buf,
				   unsigned int size)
{
	struct f_midi2_midi1_port *port = &midi2->midi1_port[cable];

	if (port->pending + size > sizeof(port->buf))
		return;
	memcpy(port->buf + port->pending, buf, size);
	port->pending += size;
}

/* try to process data given from the associated UMP stream */
static void process_midi1_transmit(struct f_midi2 *midi2)
{
	struct f_midi2_usb_ep *usb_ep = &midi2->midi1_ep_in;
	struct f_midi2_ep *ep = &midi2->midi2_eps[0];
	struct usb_request *req = NULL;
	/* 12 is the largest outcome (4 MIDI1 cmds) for a single UMP packet */
	unsigned char outbuf[12];
	unsigned char group, cable;
	int len, size;
	u32 ump;

	if (!usb_ep->usb_ep || !usb_ep->usb_ep->enabled)
		return;

	for (;;) {
		if (!req) {
			req = get_empty_request(usb_ep);
			if (!req)
				break;
		}

		if (process_midi1_pending_buf(midi2, &req))
			continue;

		len = snd_ump_transmit(ep->ump, &ump, 4);
		if (len <= 0)
			break;
		if (snd_ump_receive_ump_val(ep->ump, ump) <= 0)
			continue;
		size = snd_ump_convert_from_ump(ep->ump->input_buf, outbuf,
						&group);
		if (size <= 0)
			continue;
		cable = ep->in_group_to_cable[group];
		if (!cable)
			continue;
		cable--; /* to 0-base */
		fill_midi1_pending_buf(midi2, cable, outbuf, size);
	}

	if (req) {
		if (req->length)
			queue_request_ep_raw(req);
		else
			put_empty_request(req);
	}
}

/* complete handler for MIDI1 EP-in requests */
static void f_midi2_midi1_ep_in_complete(struct usb_ep *usb_ep,
					 struct usb_request *req)
{
	struct f_midi2_req_ctx *ctx = req->context;
	struct f_midi2 *midi2 = ctx->usb_ep->card;
	int status = req->status;

	put_empty_request(req);

	if (status) {
		DBG(midi2, "%s complete error %d: %d/%d\n",
		    usb_ep->name, status, req->actual, req->length);
		return;
	}

	process_midi1_transmit(midi2);
}

/* complete handler for MIDI1 EP-out requests */
static void f_midi2_midi1_ep_out_complete(struct usb_ep *usb_ep,
					  struct usb_request *req)
{
	struct f_midi2_req_ctx *ctx = req->context;
	struct f_midi2 *midi2 = ctx->usb_ep->card;
	struct f_midi2_ep *ep;
	struct ump_cvt_to_ump *cvt = &midi2->midi1_ump_cvt;
	static const u8 midi1_packet_bytes[16] = {
		0, 0, 2, 3, 3, 1, 2, 3, 3, 3, 3, 3, 2, 2, 3, 1
	};
	unsigned int group, cable, bytes, c, len;
	int status = req->status;
	const u8 *buf = req->buf;

	if (status) {
		DBG(midi2, "%s complete error %d: %d/%d\n",
		    usb_ep->name, status, req->actual, req->length);
		goto error;
	}

	len = req->actual >> 2;
	for (; len; len--, buf += 4) {
		cable = *buf >> 4;
		ep = midi2->out_cable_mapping[cable].ep;
		if (!ep)
			continue;
		group = midi2->out_cable_mapping[cable].group;
		bytes = midi1_packet_bytes[*buf & 0x0f];
		for (c = 0; c < bytes; c++) {
			snd_ump_convert_to_ump(cvt, group,
					       to_ump_protocol(ep->info.protocol),
					       buf[c + 1]);
			if (cvt->ump_bytes) {
				snd_ump_receive(ep->ump, cvt->ump,
						cvt->ump_bytes);
				cvt->ump_bytes = 0;
			}
		}
	}

	if (midi2->operation_mode != MIDI_OP_MODE_MIDI1)
		goto error;

	if (queue_request_ep_raw(req))
		goto error;
	return;

 error:
	put_empty_request(req);
}

/*
 * Common EP handling helpers
 */

/* Start MIDI EP */
static int f_midi2_start_ep(struct f_midi2_usb_ep *usb_ep,
			    struct usb_function *fn)
{
	int err;

	if (!usb_ep->usb_ep)
		return 0;

	usb_ep_disable(usb_ep->usb_ep);
	err = config_ep_by_speed(usb_ep->card->gadget, fn, usb_ep->usb_ep);
	if (err)
		return err;
	return usb_ep_enable(usb_ep->usb_ep);
}

/* Drop pending requests */
static void f_midi2_drop_reqs(struct f_midi2_usb_ep *usb_ep)
{
	int i;

	if (!usb_ep->usb_ep || !usb_ep->num_reqs)
		return;

	for (i = 0; i < usb_ep->num_reqs; i++) {
		if (!test_bit(i, &usb_ep->free_reqs) && usb_ep->reqs[i].req) {
			usb_ep_dequeue(usb_ep->usb_ep, usb_ep->reqs[i].req);
			set_bit(i, &usb_ep->free_reqs);
		}
	}
}

/* Allocate requests for the given EP */
static int f_midi2_alloc_ep_reqs(struct f_midi2_usb_ep *usb_ep)
{
	struct f_midi2 *midi2 = usb_ep->card;
	int i;

	if (!usb_ep->usb_ep)
		return 0;
	if (!usb_ep->reqs)
		return -EINVAL;

	for (i = 0; i < midi2->info.num_reqs; i++) {
		if (usb_ep->reqs[i].req)
			continue;
		usb_ep->reqs[i].req = alloc_ep_req(usb_ep->usb_ep,
						   midi2->info.req_buf_size);
		if (!usb_ep->reqs[i].req)
			return -ENOMEM;
		usb_ep->reqs[i].req->context = &usb_ep->reqs[i];
	}
	return 0;
}

/* Free allocated requests */
static void f_midi2_free_ep_reqs(struct f_midi2_usb_ep *usb_ep)
{
	struct f_midi2 *midi2 = usb_ep->card;
	int i;

	for (i = 0; i < midi2->info.num_reqs; i++) {
		if (!usb_ep->reqs[i].req)
			continue;
		free_ep_req(usb_ep->usb_ep, usb_ep->reqs[i].req);
		usb_ep->reqs[i].req = NULL;
	}
}

/* Initialize EP */
static int f_midi2_init_ep(struct f_midi2 *midi2, struct f_midi2_ep *ep,
			   struct f_midi2_usb_ep *usb_ep,
			   void *desc,
			   void (*complete)(struct usb_ep *usb_ep,
					    struct usb_request *req))
{
	int i;

	usb_ep->card = midi2;
	usb_ep->ep = ep;
	usb_ep->usb_ep = usb_ep_autoconfig(midi2->gadget, desc);
	if (!usb_ep->usb_ep)
		return -ENODEV;
	usb_ep->complete = complete;

	usb_ep->reqs = kcalloc(midi2->info.num_reqs, sizeof(*usb_ep->reqs),
			       GFP_KERNEL);
	if (!usb_ep->reqs)
		return -ENOMEM;
	for (i = 0; i < midi2->info.num_reqs; i++) {
		usb_ep->reqs[i].index = i;
		usb_ep->reqs[i].usb_ep = usb_ep;
		set_bit(i, &usb_ep->free_reqs);
		usb_ep->num_reqs++;
	}

	return 0;
}

/* Free EP */
static void f_midi2_free_ep(struct f_midi2_usb_ep *usb_ep)
{
	f_midi2_drop_reqs(usb_ep);

	f_midi2_free_ep_reqs(usb_ep);

	kfree(usb_ep->reqs);
	usb_ep->num_reqs = 0;
	usb_ep->free_reqs = 0;
	usb_ep->reqs = NULL;
}

/* Queue requests for EP-out at start */
static void f_midi2_queue_out_reqs(struct f_midi2_usb_ep *usb_ep)
{
	int i, err;

	if (!usb_ep->usb_ep)
		return;

	for (i = 0; i < usb_ep->num_reqs; i++) {
		if (!test_bit(i, &usb_ep->free_reqs) || !usb_ep->reqs[i].req)
			continue;
		usb_ep->reqs[i].req->complete = usb_ep->complete;
		err = usb_ep_queue(usb_ep->usb_ep, usb_ep->reqs[i].req,
				   GFP_ATOMIC);
		if (!err)
			clear_bit(i, &usb_ep->free_reqs);
	}
}

/*
 * Gadget Function callbacks
 */

/* stop both IN and OUT EPs */
static void f_midi2_stop_eps(struct f_midi2_usb_ep *ep_in,
			     struct f_midi2_usb_ep *ep_out)
{
	f_midi2_drop_reqs(ep_in);
	f_midi2_drop_reqs(ep_out);
	f_midi2_free_ep_reqs(ep_in);
	f_midi2_free_ep_reqs(ep_out);
}

/* start/queue both IN and OUT EPs */
static int f_midi2_start_eps(struct f_midi2_usb_ep *ep_in,
			     struct f_midi2_usb_ep *ep_out,
			     struct usb_function *fn)
{
	int err;

	err = f_midi2_start_ep(ep_in, fn);
	if (err)
		return err;
	err = f_midi2_start_ep(ep_out, fn);
	if (err)
		return err;

	err = f_midi2_alloc_ep_reqs(ep_in);
	if (err)
		return err;
	err = f_midi2_alloc_ep_reqs(ep_out);
	if (err)
		return err;

	f_midi2_queue_out_reqs(ep_out);
	return 0;
}

/* gadget function set_alt callback */
static int f_midi2_set_alt(struct usb_function *fn, unsigned int intf,
			   unsigned int alt)
{
	struct f_midi2 *midi2 = func_to_midi2(fn);
	struct f_midi2_ep *ep;
	int i, op_mode, err;

	if (intf != midi2->midi_if || alt > 1)
		return 0;

	if (alt == 0)
		op_mode = MIDI_OP_MODE_MIDI1;
	else
		op_mode = MIDI_OP_MODE_MIDI2;

	if (midi2->operation_mode == op_mode)
		return 0;

	midi2->operation_mode = op_mode;

	if (op_mode != MIDI_OP_MODE_MIDI1)
		f_midi2_stop_eps(&midi2->midi1_ep_in, &midi2->midi1_ep_out);

	if (op_mode != MIDI_OP_MODE_MIDI2) {
		for (i = 0; i < midi2->num_eps; i++) {
			ep = &midi2->midi2_eps[i];
			f_midi2_stop_eps(&ep->ep_in, &ep->ep_out);
		}
	}

	if (op_mode == MIDI_OP_MODE_MIDI1)
		return f_midi2_start_eps(&midi2->midi1_ep_in,
					 &midi2->midi1_ep_out, fn);

	if (op_mode == MIDI_OP_MODE_MIDI2) {
		for (i = 0; i < midi2->num_eps; i++) {
			ep = &midi2->midi2_eps[i];

			err = f_midi2_start_eps(&ep->ep_in, &ep->ep_out, fn);
			if (err)
				return err;
		}
	}

	return 0;
}

/* gadget function get_alt callback */
static int f_midi2_get_alt(struct usb_function *fn, unsigned int intf)
{
	struct f_midi2 *midi2 = func_to_midi2(fn);

	if (intf == midi2->midi_if &&
	    midi2->operation_mode == MIDI_OP_MODE_MIDI2)
		return 1;
	return 0;
}

/* convert UMP direction to USB MIDI 2.0 direction */
static unsigned int ump_to_usb_dir(unsigned int ump_dir)
{
	switch (ump_dir) {
	case SNDRV_UMP_DIR_INPUT:
		return USB_MS_GR_TRM_BLOCK_TYPE_INPUT_ONLY;
	case SNDRV_UMP_DIR_OUTPUT:
		return USB_MS_GR_TRM_BLOCK_TYPE_OUTPUT_ONLY;
	default:
		return USB_MS_GR_TRM_BLOCK_TYPE_BIDIRECTIONAL;
	}
}

/* assign GTB descriptors (for the given request) */
static void assign_block_descriptors(struct f_midi2 *midi2,
				     struct usb_request *req,
				     int max_len)
{
	struct usb_ms20_gr_trm_block_header_descriptor header;
	struct usb_ms20_gr_trm_block_descriptor *desc;
	struct f_midi2_block_info *b;
	struct f_midi2_ep *ep;
	int i, blk, len;
	char *data;

	len = sizeof(gtb_header_desc) + sizeof(gtb_desc) * midi2->total_blocks;
	if (WARN_ON(len > midi2->info.req_buf_size))
		return;

	header = gtb_header_desc;
	header.wTotalLength = cpu_to_le16(len);
	if (max_len < len) {
		len = min_t(int, len, sizeof(header));
		memcpy(req->buf, &header, len);
		req->length = len;
		req->zero = len < max_len;
		return;
	}

	memcpy(req->buf, &header, sizeof(header));
	data = req->buf + sizeof(header);
	for (i = 0; i < midi2->num_eps; i++) {
		ep = &midi2->midi2_eps[i];
		for (blk = 0; blk < ep->num_blks; blk++) {
			b = &ep->blks[blk].info;
			desc = (struct usb_ms20_gr_trm_block_descriptor *)data;

			*desc = gtb_desc;
			desc->bGrpTrmBlkID = ep->blks[blk].gtb_id;
			desc->bGrpTrmBlkType = ump_to_usb_dir(b->direction);
			desc->nGroupTrm = b->first_group;
			desc->nNumGroupTrm = b->num_groups;
			desc->iBlockItem = ep->blks[blk].string_id;

			if (ep->info.protocol == 2)
				desc->bMIDIProtocol = USB_MS_MIDI_PROTO_2_0;
			else
				desc->bMIDIProtocol = USB_MS_MIDI_PROTO_1_0_128;

			if (b->is_midi1 == 2) {
				desc->wMaxInputBandwidth = cpu_to_le16(1);
				desc->wMaxOutputBandwidth = cpu_to_le16(1);
			}

			data += sizeof(*desc);
		}
	}

	req->length = len;
	req->zero = len < max_len;
}

/* gadget function setup callback: handle GTB requests */
static int f_midi2_setup(struct usb_function *fn,
			 const struct usb_ctrlrequest *ctrl)
{
	struct f_midi2 *midi2 = func_to_midi2(fn);
	struct usb_composite_dev *cdev = fn->config->cdev;
	struct usb_request *req = cdev->req;
	u16 value, length;

	if ((ctrl->bRequestType & USB_TYPE_MASK) != USB_TYPE_STANDARD ||
	    ctrl->bRequest != USB_REQ_GET_DESCRIPTOR)
		return -EOPNOTSUPP;

	value = le16_to_cpu(ctrl->wValue);
	length = le16_to_cpu(ctrl->wLength);

	if ((value >> 8) != USB_DT_CS_GR_TRM_BLOCK)
		return -EOPNOTSUPP;

	/* handle only altset 1 */
	if ((value & 0xff) != 1)
		return -EOPNOTSUPP;

	assign_block_descriptors(midi2, req, length);
	return usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
}

/* gadget function disable callback */
static void f_midi2_disable(struct usb_function *fn)
{
	struct f_midi2 *midi2 = func_to_midi2(fn);

	midi2->operation_mode = MIDI_OP_MODE_UNSET;
}

/*
 * ALSA UMP ops: most of them are NOPs, only trigger for write is needed
 */
static int f_midi2_ump_open(struct snd_ump_endpoint *ump, int dir)
{
	return 0;
}

static void f_midi2_ump_close(struct snd_ump_endpoint *ump, int dir)
{
}

static void f_midi2_ump_trigger(struct snd_ump_endpoint *ump, int dir, int up)
{
	struct f_midi2_ep *ep = ump->private_data;
	struct f_midi2 *midi2 = ep->card;

	if (up && dir == SNDRV_RAWMIDI_STREAM_OUTPUT) {
		switch (midi2->operation_mode) {
		case MIDI_OP_MODE_MIDI1:
			process_midi1_transmit(midi2);
			break;
		case MIDI_OP_MODE_MIDI2:
			process_ump_transmit(ep);
			break;
		}
	}
}

static void f_midi2_ump_drain(struct snd_ump_endpoint *ump, int dir)
{
}

static const struct snd_ump_ops f_midi2_ump_ops = {
	.open = f_midi2_ump_open,
	.close = f_midi2_ump_close,
	.trigger = f_midi2_ump_trigger,
	.drain = f_midi2_ump_drain,
};

/*
 * "Operation Mode" control element
 */
static int f_midi2_operation_mode_info(struct snd_kcontrol *kcontrol,
				       struct snd_ctl_elem_info *uinfo)
{
	uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER;
	uinfo->count = 1;
	uinfo->value.integer.min = MIDI_OP_MODE_UNSET;
	uinfo->value.integer.max = MIDI_OP_MODE_MIDI2;
	return 0;
}

static int f_midi2_operation_mode_get(struct snd_kcontrol *kcontrol,
				      struct snd_ctl_elem_value *ucontrol)
{
	struct f_midi2 *midi2 = snd_kcontrol_chip(kcontrol);

	ucontrol->value.integer.value[0] = midi2->operation_mode;
	return 0;
}

static const struct snd_kcontrol_new operation_mode_ctl = {
	.iface = SNDRV_CTL_ELEM_IFACE_RAWMIDI,
	.name = "Operation Mode",
	.access = SNDRV_CTL_ELEM_ACCESS_READ | SNDRV_CTL_ELEM_ACCESS_VOLATILE,
	.info = f_midi2_operation_mode_info,
	.get = f_midi2_operation_mode_get,
};

/*
 * ALSA UMP instance creation / deletion
 */
static void f_midi2_free_card(struct f_midi2 *midi2)
{
	if (midi2->card) {
		snd_card_free_when_closed(midi2->card);
		midi2->card = NULL;
	}
}

/* use a reverse direction for the gadget host */
static int reverse_dir(int dir)
{
	if (!dir || dir == SNDRV_UMP_DIR_BIDIRECTION)
		return dir;
	return (dir == SNDRV_UMP_DIR_OUTPUT) ?
		SNDRV_UMP_DIR_INPUT : SNDRV_UMP_DIR_OUTPUT;
}

static int f_midi2_create_card(struct f_midi2 *midi2)
{
	struct snd_card *card;
	struct snd_ump_endpoint *ump;
	struct f_midi2_ep *ep;
	int i, id, blk, err;
	__be32 sw;

	err = snd_card_new(&midi2->gadget->dev, -1, NULL, THIS_MODULE, 0,
			   &card);
	if (err < 0)
		return err;
	midi2->card = card;

	strcpy(card->driver, "f_midi2");
	strcpy(card->shortname, "MIDI 2.0 Gadget");
	strcpy(card->longname, "MIDI 2.0 Gadget");

	id = 0;
	for (i = 0; i < midi2->num_eps; i++) {
		ep = &midi2->midi2_eps[i];
		err = snd_ump_endpoint_new(card, "MIDI 2.0 Gadget", id,
					   1, 1, &ump);
		if (err < 0)
			goto error;
		id++;

		ep->ump = ump;
		ump->no_process_stream = true;
		ump->private_data = ep;
		ump->ops = &f_midi2_ump_ops;
		if (midi2->info.static_block)
			ump->info.flags |= SNDRV_UMP_EP_INFO_STATIC_BLOCKS;
		ump->info.protocol_caps = (ep->info.protocol_caps & 3) << 8;
		ump->info.protocol = to_ump_protocol(ep->info.protocol);
		ump->info.version = 0x0101;
		ump->info.family_id = ep->info.family;
		ump->info.model_id = ep->info.model;
		ump->info.manufacturer_id = ep->info.manufacturer & 0xffffff;
		sw = cpu_to_be32(ep->info.sw_revision);
		memcpy(ump->info.sw_revision, &sw, 4);

		strscpy(ump->info.name, ump_ep_name(ep),
			sizeof(ump->info.name));
		strscpy(ump->info.product_id, ump_product_id(ep),
			sizeof(ump->info.product_id));
		strscpy(ump->core.name, ump->info.name, sizeof(ump->core.name));

		for (blk = 0; blk < ep->num_blks; blk++) {
			const struct f_midi2_block_info *b = &ep->blks[blk].info;
			struct snd_ump_block *fb;

			err = snd_ump_block_new(ump, blk,
						reverse_dir(b->direction),
						b->first_group, b->num_groups,
						&ep->blks[blk].fb);
			if (err < 0)
				goto error;
			fb = ep->blks[blk].fb;
			fb->info.active = !!b->active;
			fb->info.midi_ci_version = b->midi_ci_version;
			fb->info.ui_hint = reverse_dir(b->ui_hint);
			fb->info.sysex8_streams = b->sysex8_streams;
			fb->info.flags |= b->is_midi1;
			strscpy(fb->info.name, ump_fb_name(b),
				sizeof(fb->info.name));
		}
	}

	for (i = 0; i < midi2->num_eps; i++) {
		err = snd_ump_attach_legacy_rawmidi(midi2->midi2_eps[i].ump,
						    "Legacy MIDI", id);
		if (err < 0)
			goto error;
		id++;
	}

	err = snd_ctl_add(card, snd_ctl_new1(&operation_mode_ctl, midi2));
	if (err < 0)
		goto error;

	err = snd_card_register(card);
	if (err < 0)
		goto error;

	return 0;

 error:
	f_midi2_free_card(midi2);
	return err;
}

/*
 * Creation of USB descriptors
 */
struct f_midi2_usb_config {
	struct usb_descriptor_header **list;
	unsigned int size;
	unsigned int alloc;

	/* MIDI 1.0 jacks */
	unsigned char jack_in, jack_out, jack_id;
	struct usb_midi_in_jack_descriptor jack_ins[MAX_CABLES];
	struct usb_midi_out_jack_descriptor_1 jack_outs[MAX_CABLES];
};

static int append_config(struct f_midi2_usb_config *config, void *d)
{
	unsigned int size;
	void *buf;

	if (config->size + 2 >= config->alloc) {
		size = config->size + 16;
		buf = krealloc(config->list, size * sizeof(void *), GFP_KERNEL);
		if (!buf)
			return -ENOMEM;
		config->list = buf;
		config->alloc = size;
	}

	config->list[config->size] = d;
	config->size++;
	config->list[config->size] = NULL;
	return 0;
}

static int append_configs(struct f_midi2_usb_config *config, void **d)
{
	int err;

	for (; *d; d++) {
		err = append_config(config, *d);
		if (err)
			return err;
	}
	return 0;
}

static int append_midi1_in_jack(struct f_midi2 *midi2,
				struct f_midi2_usb_config *config,
				struct midi1_cable_mapping *map,
				unsigned int type)
{
	struct usb_midi_in_jack_descriptor *jack =
		&config->jack_ins[config->jack_in++];
	int id = ++config->jack_id;
	int err;

	jack->bLength = 0x06;
	jack->bDescriptorType = USB_DT_CS_INTERFACE;
	jack->bDescriptorSubtype = USB_MS_MIDI_IN_JACK;
	jack->bJackType = type;
	jack->bJackID = id;
	/* use the corresponding block name as jack name */
	if (map->ep)
		jack->iJack = map->ep->blks[map->block].string_id;

	err = append_config(config, jack);
	if (err < 0)
		return err;
	return id;
}

static int append_midi1_out_jack(struct f_midi2 *midi2,
				 struct f_midi2_usb_config *config,
				 struct midi1_cable_mapping *map,
				 unsigned int type, unsigned int source)
{
	struct usb_midi_out_jack_descriptor_1 *jack =
		&config->jack_outs[config->jack_out++];
	int id = ++config->jack_id;
	int err;

	jack->bLength = 0x09;
	jack->bDescriptorType = USB_DT_CS_INTERFACE;
	jack->bDescriptorSubtype = USB_MS_MIDI_OUT_JACK;
	jack->bJackType = type;
	jack->bJackID = id;
	jack->bNrInputPins = 1;
	jack->pins[0].baSourceID = source;
	jack->pins[0].baSourcePin = 0x01;
	/* use the corresponding block name as jack name */
	if (map->ep)
		jack->iJack = map->ep->blks[map->block].string_id;

	err = append_config(config, jack);
	if (err < 0)
		return err;
	return id;
}

static int f_midi2_create_usb_configs(struct f_midi2 *midi2,
				      struct f_midi2_usb_config *config,
				      int speed)
{
	void **midi1_in_eps, **midi1_out_eps;
	int i, jack, total;
	int err;

	switch (speed) {
	default:
	case USB_SPEED_HIGH:
		midi2_midi1_ep_out_desc.wMaxPacketSize = cpu_to_le16(512);
		midi2_midi1_ep_in_desc.wMaxPacketSize = cpu_to_le16(512);
		for (i = 0; i < midi2->num_eps; i++)
			midi2_midi2_ep_out_desc[i].wMaxPacketSize =
				cpu_to_le16(512);
		fallthrough;
	case USB_SPEED_FULL:
		midi1_in_eps = midi2_midi1_ep_in_descs;
		midi1_out_eps = midi2_midi1_ep_out_descs;
		break;
	case USB_SPEED_SUPER:
		midi2_midi1_ep_out_desc.wMaxPacketSize = cpu_to_le16(1024);
		midi2_midi1_ep_in_desc.wMaxPacketSize = cpu_to_le16(1024);
		for (i = 0; i < midi2->num_eps; i++)
			midi2_midi2_ep_out_desc[i].wMaxPacketSize =
				cpu_to_le16(1024);
		midi1_in_eps = midi2_midi1_ep_in_ss_descs;
		midi1_out_eps = midi2_midi1_ep_out_ss_descs;
		break;
	}

	err = append_configs(config, midi2_audio_descs);
	if (err < 0)
		return err;

	if (midi2->num_midi1_in && midi2->num_midi1_out)
		midi2_midi1_if_desc.bNumEndpoints = 2;
	else
		midi2_midi1_if_desc.bNumEndpoints = 1;

	err = append_configs(config, midi2_midi1_descs);
	if (err < 0)
		return err;

	total = USB_DT_MS_HEADER_SIZE;
	if (midi2->num_midi1_out) {
		midi2_midi1_ep_out_class_desc.bLength =
			USB_DT_MS_ENDPOINT_SIZE(midi2->num_midi1_out);
		total += midi2_midi1_ep_out_class_desc.bLength;
		midi2_midi1_ep_out_class_desc.bNumEmbMIDIJack =
			midi2->num_midi1_out;
		total += midi2->num_midi1_out *
			(USB_DT_MIDI_IN_SIZE + USB_DT_MIDI_OUT_SIZE(1));
		for (i = 0; i < midi2->num_midi1_out; i++) {
			jack = append_midi1_in_jack(midi2, config,
						    &midi2->in_cable_mapping[i],
						    USB_MS_EMBEDDED);
			if (jack < 0)
				return jack;
			midi2_midi1_ep_out_class_desc.baAssocJackID[i] = jack;
			jack = append_midi1_out_jack(midi2, config,
						     &midi2->in_cable_mapping[i],
						     USB_MS_EXTERNAL, jack);
			if (jack < 0)
				return jack;
		}
	}

	if (midi2->num_midi1_in) {
		midi2_midi1_ep_in_class_desc.bLength =
			USB_DT_MS_ENDPOINT_SIZE(midi2->num_midi1_in);
		total += midi2_midi1_ep_in_class_desc.bLength;
		midi2_midi1_ep_in_class_desc.bNumEmbMIDIJack =
			midi2->num_midi1_in;
		total += midi2->num_midi1_in *
			(USB_DT_MIDI_IN_SIZE + USB_DT_MIDI_OUT_SIZE(1));
		for (i = 0; i < midi2->num_midi1_in; i++) {
			jack = append_midi1_in_jack(midi2, config,
						    &midi2->out_cable_mapping[i],
						    USB_MS_EXTERNAL);
			if (jack < 0)
				return jack;
			jack = append_midi1_out_jack(midi2, config,
						     &midi2->out_cable_mapping[i],
						     USB_MS_EMBEDDED, jack);
			if (jack < 0)
				return jack;
			midi2_midi1_ep_in_class_desc.baAssocJackID[i] = jack;
		}
	}

	midi2_midi1_class_desc.wTotalLength = cpu_to_le16(total);

	if (midi2->num_midi1_out) {
		err = append_configs(config, midi1_out_eps);
		if (err < 0)
			return err;
	}
	if (midi2->num_midi1_in) {
		err = append_configs(config, midi1_in_eps);
		if (err < 0)
			return err;
	}

	err = append_configs(config, midi2_midi2_descs);
	if (err < 0)
		return err;

	for (i = 0; i < midi2->num_eps; i++) {
		err = append_config(config, &midi2_midi2_ep_out_desc[i]);
		if (err < 0)
			return err;
		if (speed == USB_SPEED_SUPER || speed == USB_SPEED_SUPER_PLUS) {
			err = append_config(config, &midi2_midi2_ep_out_ss_comp_desc);
			if (err < 0)
				return err;
		}
		err = append_config(config, &midi2_midi2_ep_out_class_desc[i]);
		if (err < 0)
			return err;
		err = append_config(config, &midi2_midi2_ep_in_desc[i]);
		if (err < 0)
			return err;
		if (speed == USB_SPEED_SUPER || speed == USB_SPEED_SUPER_PLUS) {
			err = append_config(config, &midi2_midi2_ep_in_ss_comp_desc);
			if (err < 0)
				return err;
		}
		err = append_config(config, &midi2_midi2_ep_in_class_desc[i]);
		if (err < 0)
			return err;
	}

	return 0;
}

static void f_midi2_free_usb_configs(struct f_midi2_usb_config *config)
{
	kfree(config->list);
	memset(config, 0, sizeof(*config));
}

/* as we use the static descriptors for simplicity, serialize bind call */
static DEFINE_MUTEX(f_midi2_desc_mutex);

/* fill MIDI2 EP class-specific descriptor */
static void fill_midi2_class_desc(struct f_midi2_ep *ep,
				  struct usb_ms20_endpoint_descriptor_32 *cdesc)
{
	int blk;

	cdesc->bLength = USB_DT_MS20_ENDPOINT_SIZE(ep->num_blks);
	cdesc->bDescriptorType = USB_DT_CS_ENDPOINT;
	cdesc->bDescriptorSubtype = USB_MS_GENERAL_2_0;
	cdesc->bNumGrpTrmBlock = ep->num_blks;
	for (blk = 0; blk < ep->num_blks; blk++)
		cdesc->baAssoGrpTrmBlkID[blk] = ep->blks[blk].gtb_id;
}

/* initialize MIDI2 EP-in */
static int f_midi2_init_midi2_ep_in(struct f_midi2 *midi2, int index)
{
	struct f_midi2_ep *ep = &midi2->midi2_eps[index];
	struct usb_endpoint_descriptor *desc = &midi2_midi2_ep_in_desc[index];

	desc->bLength = USB_DT_ENDPOINT_SIZE;
	desc->bDescriptorType = USB_DT_ENDPOINT;
	desc->bEndpointAddress = USB_DIR_IN;
	desc->bmAttributes = USB_ENDPOINT_XFER_INT;
	desc->wMaxPacketSize = cpu_to_le16(EP_MAX_PACKET_INT);
	desc->bInterval = 1;

	fill_midi2_class_desc(ep, &midi2_midi2_ep_in_class_desc[index]);

	return f_midi2_init_ep(midi2, ep, &ep->ep_in, desc,
			       f_midi2_ep_in_complete);
}

/* initialize MIDI2 EP-out */
static int f_midi2_init_midi2_ep_out(struct f_midi2 *midi2, int index)
{
	struct f_midi2_ep *ep = &midi2->midi2_eps[index];
	struct usb_endpoint_descriptor *desc = &midi2_midi2_ep_out_desc[index];

	desc->bLength = USB_DT_ENDPOINT_SIZE;
	desc->bDescriptorType = USB_DT_ENDPOINT;
	desc->bEndpointAddress = USB_DIR_OUT;
	desc->bmAttributes = USB_ENDPOINT_XFER_BULK;

	fill_midi2_class_desc(ep, &midi2_midi2_ep_out_class_desc[index]);

	return f_midi2_init_ep(midi2, ep, &ep->ep_out, desc,
			       f_midi2_ep_out_complete);
}

/* gadget function bind callback */
static int f_midi2_bind(struct usb_configuration *c, struct usb_function *f)
{
	struct usb_composite_dev *cdev = c->cdev;
	struct f_midi2 *midi2 = func_to_midi2(f);
	struct f_midi2_ep *ep;
	struct f_midi2_usb_config config = {};
	struct usb_gadget_strings string_fn = {
		.language = 0x0409,	/* en-us */
		.strings = midi2->string_defs,
	};
	struct usb_gadget_strings *strings[] = {
		&string_fn,
		NULL,
	};
	int i, blk, status;

	midi2->gadget = cdev->gadget;
	midi2->operation_mode = MIDI_OP_MODE_UNSET;

	status = f_midi2_create_card(midi2);
	if (status < 0)
		goto fail_register;

	/* maybe allocate device-global string ID */
	midi2->strings = usb_gstrings_attach(c->cdev, strings,
					     midi2->total_blocks + 1);
	if (IS_ERR(midi2->strings)) {
		status = PTR_ERR(midi2->strings);
		goto fail_string;
	}

	mutex_lock(&f_midi2_desc_mutex);
	midi2_midi1_if_desc.iInterface = midi2->strings[STR_IFACE].id;
	midi2_midi2_if_desc.iInterface = midi2->strings[STR_IFACE].id;
	for (i = 0; i < midi2->num_eps; i++) {
		ep = &midi2->midi2_eps[i];
		for (blk = 0; blk < ep->num_blks; blk++)
			ep->blks[blk].string_id =
				midi2->strings[gtb_to_str_id(ep->blks[blk].gtb_id)].id;
	}

	midi2_midi2_if_desc.bNumEndpoints = midi2->num_eps * 2;

	/* audio interface */
	status = usb_interface_id(c, f);
	if (status < 0)
		goto fail;
	midi2_audio_if_desc.bInterfaceNumber = status;

	/* MIDI streaming */
	status = usb_interface_id(c, f);
	if (status < 0)
		goto fail;
	midi2->midi_if = status;
	midi2_midi1_if_desc.bInterfaceNumber = status;
	midi2_midi2_if_desc.bInterfaceNumber = status;
	midi2_audio_class_desc.baInterfaceNr[0] = status;

	/* allocate instance-specific endpoints */
	if (midi2->midi2_eps[0].blks[0].info.direction != SNDRV_UMP_DIR_OUTPUT) {
		status = f_midi2_init_ep(midi2, NULL, &midi2->midi1_ep_in,
					 &midi2_midi1_ep_in_desc,
					 f_midi2_midi1_ep_in_complete);
		if (status)
			goto fail;
	}

	if (midi2->midi2_eps[0].blks[0].info.direction != SNDRV_UMP_DIR_INPUT) {
		status = f_midi2_init_ep(midi2, NULL, &midi2->midi1_ep_out,
					 &midi2_midi1_ep_out_desc,
					 f_midi2_midi1_ep_out_complete);
		if (status)
			goto fail;
	}

	for (i = 0; i < midi2->num_eps; i++) {
		status = f_midi2_init_midi2_ep_in(midi2, i);
		if (status)
			goto fail;
		status = f_midi2_init_midi2_ep_out(midi2, i);
		if (status)
			goto fail;
	}

	status = f_midi2_create_usb_configs(midi2, &config, USB_SPEED_FULL);
	if (status < 0)
		goto fail;
	f->fs_descriptors = usb_copy_descriptors(config.list);
	if (!f->fs_descriptors) {
		status = -ENOMEM;
		goto fail;
	}
	f_midi2_free_usb_configs(&config);

	status = f_midi2_create_usb_configs(midi2, &config, USB_SPEED_HIGH);
	if (status < 0)
		goto fail;
	f->hs_descriptors = usb_copy_descriptors(config.list);
	if (!f->hs_descriptors) {
		status = -ENOMEM;
		goto fail;
	}
	f_midi2_free_usb_configs(&config);

	status = f_midi2_create_usb_configs(midi2, &config, USB_SPEED_SUPER);
	if (status < 0)
		goto fail;
	f->ss_descriptors = usb_copy_descriptors(config.list);
	if (!f->ss_descriptors) {
		status = -ENOMEM;
		goto fail;
	}
	f_midi2_free_usb_configs(&config);

	mutex_unlock(&f_midi2_desc_mutex);
	return 0;

fail:
	f_midi2_free_usb_configs(&config);
	mutex_unlock(&f_midi2_desc_mutex);
	usb_free_all_descriptors(f);
fail_string:
	f_midi2_free_card(midi2);
fail_register:
	ERROR(midi2, "%s: can't bind, err %d\n", f->name, status);
	return status;
}

/* gadget function unbind callback */
static void f_midi2_unbind(struct usb_configuration *c, struct usb_function *f)
{
	struct f_midi2 *midi2 = func_to_midi2(f);
	int i;

	f_midi2_free_card(midi2);

	f_midi2_free_ep(&midi2->midi1_ep_in);
	f_midi2_free_ep(&midi2->midi1_ep_out);
	for (i = 0; i < midi2->num_eps; i++) {
		f_midi2_free_ep(&midi2->midi2_eps[i].ep_in);
		f_midi2_free_ep(&midi2->midi2_eps[i].ep_out);
	}

	usb_free_all_descriptors(f);
}

/*
 * ConfigFS interface
 */

/* type conversion helpers */
static inline struct f_midi2_opts *to_f_midi2_opts(struct config_item *item)
{
	return container_of(to_config_group(item), struct f_midi2_opts,
			    func_inst.group);
}

static inline struct f_midi2_ep_opts *
to_f_midi2_ep_opts(struct config_item *item)
{
	return container_of(to_config_group(item), struct f_midi2_ep_opts,
			    group);
}

static inline struct f_midi2_block_opts *
to_f_midi2_block_opts(struct config_item *item)
{
	return container_of(to_config_group(item), struct f_midi2_block_opts,
			    group);
}

/* trim the string to be usable for EP and FB name strings */
static void make_name_string(char *s)
{
	char *p;

	p = strchr(s, '\n');
	if (p)
		*p = 0;

	p = s + strlen(s);
	for (; p > s && isspace(*p); p--)
		*p = 0;
}

/* configfs helpers: generic show/store for unisnged int */
static ssize_t f_midi2_opts_uint_show(struct f_midi2_opts *opts,
				      u32 val, const char *format, char *page)
{
	int result;

	mutex_lock(&opts->lock);
	result = sprintf(page, format, val);
	mutex_unlock(&opts->lock);
	return result;
}

static ssize_t f_midi2_opts_uint_store(struct f_midi2_opts *opts,
				       u32 *valp, u32 minval, u32 maxval,
				       const char *page, size_t len)
{
	int ret;
	u32 val;

	mutex_lock(&opts->lock);
	if (opts->refcnt) {
		ret = -EBUSY;
		goto end;
	}

	ret = kstrtou32(page, 0, &val);
	if (ret)
		goto end;
	if (val < minval || val > maxval) {
		ret = -EINVAL;
		goto end;
	}

	*valp = val;
	ret = len;

end:
	mutex_unlock(&opts->lock);
	return ret;
}

/* generic store for bool */
static ssize_t f_midi2_opts_bool_store(struct f_midi2_opts *opts,
				       bool *valp, const char *page, size_t len)
{
	int ret;
	bool val;

	mutex_lock(&opts->lock);
	if (opts->refcnt) {
		ret = -EBUSY;
		goto end;
	}

	ret = kstrtobool(page, &val);
	if (ret)
		goto end;
	*valp = val;
	ret = len;

end:
	mutex_unlock(&opts->lock);
	return ret;
}

/* generic show/store for string */
static ssize_t f_midi2_opts_str_show(struct f_midi2_opts *opts,
				     const char *str, char *page)
{
	int result = 0;

	mutex_lock(&opts->lock);
	if (str)
		result = scnprintf(page, PAGE_SIZE, "%s\n", str);
	mutex_unlock(&opts->lock);
	return result;
}

static ssize_t f_midi2_opts_str_store(struct f_midi2_opts *opts,
				      const char **strp, size_t maxlen,
				      const char *page, size_t len)
{
	char *c;
	int ret;

	mutex_lock(&opts->lock);
	if (opts->refcnt) {
		ret = -EBUSY;
		goto end;
	}

	c = kstrndup(page, min(len, maxlen), GFP_KERNEL);
	if (!c) {
		ret = -ENOMEM;
		goto end;
	}

	kfree(*strp);
	make_name_string(c);
	*strp = c;
	ret = len;

end:
	mutex_unlock(&opts->lock);
	return ret;
}

/*
 * Definitions for UMP Block config
 */

/* define an uint option for block */
#define F_MIDI2_BLOCK_OPT(name, format, minval, maxval)			\
static ssize_t f_midi2_block_opts_##name##_show(struct config_item *item,\
					  char *page)			\
{									\
	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);	\
	return f_midi2_opts_uint_show(opts->ep->opts, opts->info.name,	\
				      format "\n", page);		\
}									\
									\
static ssize_t f_midi2_block_opts_##name##_store(struct config_item *item,\
					 const char *page, size_t len)	\
{									\
	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);	\
	return f_midi2_opts_uint_store(opts->ep->opts, &opts->info.name,\
				       minval, maxval, page, len);	\
}									\
									\
CONFIGFS_ATTR(f_midi2_block_opts_, name)

/* define a boolean option for block */
#define F_MIDI2_BLOCK_BOOL_OPT(name)					\
static ssize_t f_midi2_block_opts_##name##_show(struct config_item *item,\
					  char *page)			\
{									\
	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);	\
	return f_midi2_opts_uint_show(opts->ep->opts, opts->info.name,	\
				      "%u\n", page);			\
}									\
									\
static ssize_t f_midi2_block_opts_##name##_store(struct config_item *item,\
					 const char *page, size_t len)	\
{									\
	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);	\
	return f_midi2_opts_bool_store(opts->ep->opts, &opts->info.name,\
				       page, len);			\
}									\
									\
CONFIGFS_ATTR(f_midi2_block_opts_, name)

F_MIDI2_BLOCK_OPT(direction, "0x%x", 1, 3);
F_MIDI2_BLOCK_OPT(first_group, "0x%x", 0, 15);
F_MIDI2_BLOCK_OPT(num_groups, "0x%x", 1, 16);
F_MIDI2_BLOCK_OPT(midi1_first_group, "0x%x", 0, 15);
F_MIDI2_BLOCK_OPT(midi1_num_groups, "0x%x", 0, 16);
F_MIDI2_BLOCK_OPT(ui_hint, "0x%x", 0, 3);
F_MIDI2_BLOCK_OPT(midi_ci_version, "%u", 0, 1);
F_MIDI2_BLOCK_OPT(sysex8_streams, "%u", 0, 255);
F_MIDI2_BLOCK_OPT(is_midi1, "%u", 0, 2);
F_MIDI2_BLOCK_BOOL_OPT(active);

static ssize_t f_midi2_block_opts_name_show(struct config_item *item,
					    char *page)
{
	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);

	return f_midi2_opts_str_show(opts->ep->opts, opts->info.name, page);
}

static ssize_t f_midi2_block_opts_name_store(struct config_item *item,
					     const char *page, size_t len)
{
	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);

	return f_midi2_opts_str_store(opts->ep->opts, &opts->info.name, 128,
				      page, len);
}

CONFIGFS_ATTR(f_midi2_block_opts_, name);

static struct configfs_attribute *f_midi2_block_attrs[] = {
	&f_midi2_block_opts_attr_direction,
	&f_midi2_block_opts_attr_first_group,
	&f_midi2_block_opts_attr_num_groups,
	&f_midi2_block_opts_attr_midi1_first_group,
	&f_midi2_block_opts_attr_midi1_num_groups,
	&f_midi2_block_opts_attr_ui_hint,
	&f_midi2_block_opts_attr_midi_ci_version,
	&f_midi2_block_opts_attr_sysex8_streams,
	&f_midi2_block_opts_attr_is_midi1,
	&f_midi2_block_opts_attr_active,
	&f_midi2_block_opts_attr_name,
	NULL,
};

static void f_midi2_block_opts_release(struct config_item *item)
{
	struct f_midi2_block_opts *opts = to_f_midi2_block_opts(item);

	kfree(opts->info.name);
	kfree(opts);
}

static struct configfs_item_operations f_midi2_block_item_ops = {
	.release	= f_midi2_block_opts_release,
};

static const struct config_item_type f_midi2_block_type = {
	.ct_item_ops	= &f_midi2_block_item_ops,
	.ct_attrs	= f_midi2_block_attrs,
	.ct_owner	= THIS_MODULE,
};

/* create a f_midi2_block_opts instance for the given block number */
static int f_midi2_block_opts_create(struct f_midi2_ep_opts *ep_opts,
				     unsigned int blk,
				     struct f_midi2_block_opts **block_p)
{
	struct f_midi2_block_opts *block_opts;
	int ret = 0;

	mutex_lock(&ep_opts->opts->lock);
	if (ep_opts->opts->refcnt || ep_opts->blks[blk]) {
		ret = -EBUSY;
		goto out;
	}

	block_opts = kzalloc(sizeof(*block_opts), GFP_KERNEL);
	if (!block_opts) {
		ret = -ENOMEM;
		goto out;
	}

	block_opts->ep = ep_opts;
	block_opts->id = blk;

	/* set up the default values */
	block_opts->info.direction = SNDRV_UMP_DIR_BIDIRECTION;
	block_opts->info.first_group = 0;
	block_opts->info.num_groups = 1;
	block_opts->info.ui_hint = SNDRV_UMP_BLOCK_UI_HINT_BOTH;
	block_opts->info.active = 1;

	ep_opts->blks[blk] = block_opts;
	*block_p = block_opts;

 out:
	mutex_unlock(&ep_opts->opts->lock);
	return ret;
}

/* make_group callback for a block */
static struct config_group *
f_midi2_opts_block_make(struct config_group *group, const char *name)
{
	struct f_midi2_ep_opts *ep_opts;
	struct f_midi2_block_opts *block_opts;
	unsigned int blk;
	int ret;

	if (strncmp(name, "block.", 6))
		return ERR_PTR(-EINVAL);
	ret = kstrtouint(name + 6, 10, &blk);
	if (ret)
		return ERR_PTR(ret);

	ep_opts = to_f_midi2_ep_opts(&group->cg_item);

	if (blk >= SNDRV_UMP_MAX_BLOCKS)
		return ERR_PTR(-EINVAL);
	if (ep_opts->blks[blk])
		return ERR_PTR(-EBUSY);
	ret = f_midi2_block_opts_create(ep_opts, blk, &block_opts);
	if (ret)
		return ERR_PTR(ret);

	config_group_init_type_name(&block_opts->group, name,
				    &f_midi2_block_type);
	return &block_opts->group;
}

/* drop_item callback for a block */
static void
f_midi2_opts_block_drop(struct config_group *group, struct config_item *item)
{
	struct f_midi2_block_opts *block_opts = to_f_midi2_block_opts(item);

	mutex_lock(&block_opts->ep->opts->lock);
	block_opts->ep->blks[block_opts->id] = NULL;
	mutex_unlock(&block_opts->ep->opts->lock);
	config_item_put(item);
}

/*
 * Definitions for UMP Endpoint config
 */

/* define an uint option for EP */
#define F_MIDI2_EP_OPT(name, format, minval, maxval)			\
static ssize_t f_midi2_ep_opts_##name##_show(struct config_item *item,	\
					     char *page)		\
{									\
	struct f_midi2_ep_opts *opts = to_f_midi2_ep_opts(item);	\
	return f_midi2_opts_uint_show(opts->opts, opts->info.name,	\
				      format "\n", page);		\
}									\
									\
static ssize_t f_midi2_ep_opts_##name##_store(struct config_item *item,	\
					   const char *page, size_t len)\
{									\
	struct f_midi2_ep_opts *opts = to_f_midi2_ep_opts(item);	\
	return f_midi2_opts_uint_store(opts->opts, &opts->info.name,	\
				       minval, maxval, page, len);	\
}									\
									\
CONFIGFS_ATTR(f_midi2_ep_opts_, name)

/* define a string option for EP */
#define F_MIDI2_EP_STR_OPT(name, maxlen)				\
static ssize_t f_midi2_ep_opts_##name##_show(struct config_item *item,	\
					     char *page)		\
{									\
	struct f_midi2_ep_opts *opts = to_f_midi2_ep_opts(item);	\
	return f_midi2_opts_str_show(opts->opts, opts->info.name, page);\
}									\
									\
static ssize_t f_midi2_ep_opts_##name##_store(struct config_item *item,	\
					 const char *page, size_t len)	\
{									\
	struct f_midi2_ep_opts *opts = to_f_midi2_ep_opts(item);	\
	return f_midi2_opts_str_store(opts->opts, &opts->info.name, maxlen,\
				      page, len);			\
}									\
									\
CONFIGFS_ATTR(f_midi2_ep_opts_, name)

F_MIDI2_EP_OPT(protocol, "0x%x", 1, 2);
F_MIDI2_EP_OPT(protocol_caps, "0x%x", 1, 3);
F_MIDI2_EP_OPT(manufacturer, "0x%x", 0, 0xffffff);
F_MIDI2_EP_OPT(family, "0x%x", 0, 0xffff);
F_MIDI2_EP_OPT(model, "0x%x", 0, 0xffff);
F_MIDI2_EP_OPT(sw_revision, "0x%x", 0, 0xffffffff);
F_MIDI2_EP_STR_OPT(ep_name, 128);
F_MIDI2_EP_STR_OPT(product_id, 128);

static struct configfs_attribute *f_midi2_ep_attrs[] = {
	&f_midi2_ep_opts_attr_protocol,
	&f_midi2_ep_opts_attr_protocol_caps,
	&f_midi2_ep_opts_attr_ep_name,
	&f_midi2_ep_opts_attr_product_id,
	&f_midi2_ep_opts_attr_manufacturer,
	&f_midi2_ep_opts_attr_family,
	&f_midi2_ep_opts_attr_model,
	&f_midi2_ep_opts_attr_sw_revision,
	NULL,
};

static void f_midi2_ep_opts_release(struct config_item *item)
{
	struct f_midi2_ep_opts *opts = to_f_midi2_ep_opts(item);

	kfree(opts->info.ep_name);
	kfree(opts->info.product_id);
	kfree(opts);
}

static struct configfs_item_operations f_midi2_ep_item_ops = {
	.release	= f_midi2_ep_opts_release,
};

static struct configfs_group_operations f_midi2_ep_group_ops = {
	.make_group	= f_midi2_opts_block_make,
	.drop_item	= f_midi2_opts_block_drop,
};

static const struct config_item_type f_midi2_ep_type = {
	.ct_item_ops	= &f_midi2_ep_item_ops,
	.ct_group_ops	= &f_midi2_ep_group_ops,
	.ct_attrs	= f_midi2_ep_attrs,
	.ct_owner	= THIS_MODULE,
};

/* create a f_midi2_ep_opts instance */
static int f_midi2_ep_opts_create(struct f_midi2_opts *opts,
				  unsigned int index,
				  struct f_midi2_ep_opts **ep_p)
{
	struct f_midi2_ep_opts *ep_opts;

	ep_opts = kzalloc(sizeof(*ep_opts), GFP_KERNEL);
	if (!ep_opts)
		return -ENOMEM;

	ep_opts->opts = opts;
	ep_opts->index = index;

	/* set up the default values */
	ep_opts->info.protocol = 2;
	ep_opts->info.protocol_caps = 3;

	opts->eps[index] = ep_opts;
	*ep_p = ep_opts;
	return 0;
}

/* make_group callback for an EP */
static struct config_group *
f_midi2_opts_ep_make(struct config_group *group, const char *name)
{
	struct f_midi2_opts *opts;
	struct f_midi2_ep_opts *ep_opts;
	unsigned int index;
	int ret;

	if (strncmp(name, "ep.", 3))
		return ERR_PTR(-EINVAL);
	ret = kstrtouint(name + 3, 10, &index);
	if (ret)
		return ERR_PTR(ret);

	opts = to_f_midi2_opts(&group->cg_item);
	if (index >= MAX_UMP_EPS)
		return ERR_PTR(-EINVAL);
	if (opts->eps[index])
		return ERR_PTR(-EBUSY);
	ret = f_midi2_ep_opts_create(opts, index, &ep_opts);
	if (ret)
		return ERR_PTR(ret);

	config_group_init_type_name(&ep_opts->group, name, &f_midi2_ep_type);
	return &ep_opts->group;
}

/* drop_item callback for an EP */
static void
f_midi2_opts_ep_drop(struct config_group *group, struct config_item *item)
{
	struct f_midi2_ep_opts *ep_opts = to_f_midi2_ep_opts(item);

	mutex_lock(&ep_opts->opts->lock);
	ep_opts->opts->eps[ep_opts->index] = NULL;
	mutex_unlock(&ep_opts->opts->lock);
	config_item_put(item);
}

/*
 * Definitions for card config
 */

/* define a bool option for card */
#define F_MIDI2_BOOL_OPT(name)						\
static ssize_t f_midi2_opts_##name##_show(struct config_item *item,	\
					  char *page)			\
{									\
	struct f_midi2_opts *opts = to_f_midi2_opts(item);		\
	return f_midi2_opts_uint_show(opts, opts->info.name,		\
				      "%u\n", page);			\
}									\
									\
static ssize_t f_midi2_opts_##name##_store(struct config_item *item,	\
					 const char *page, size_t len)	\
{									\
	struct f_midi2_opts *opts = to_f_midi2_opts(item);		\
	return f_midi2_opts_bool_store(opts, &opts->info.name,		\
				       page, len);			\
}									\
									\
CONFIGFS_ATTR(f_midi2_opts_, name)

F_MIDI2_BOOL_OPT(process_ump);
F_MIDI2_BOOL_OPT(static_block);

static ssize_t f_midi2_opts_iface_name_show(struct config_item *item,
					    char *page)
{
	struct f_midi2_opts *opts = to_f_midi2_opts(item);

	return f_midi2_opts_str_show(opts, opts->info.iface_name, page);
}

static ssize_t f_midi2_opts_iface_name_store(struct config_item *item,
					     const char *page, size_t len)
{
	struct f_midi2_opts *opts = to_f_midi2_opts(item);

	return f_midi2_opts_str_store(opts, &opts->info.iface_name, 128,
				      page, len);
}

CONFIGFS_ATTR(f_midi2_opts_, iface_name);

static struct configfs_attribute *f_midi2_attrs[] = {
	&f_midi2_opts_attr_process_ump,
	&f_midi2_opts_attr_static_block,
	&f_midi2_opts_attr_iface_name,
	NULL
};

static void f_midi2_opts_release(struct config_item *item)
{
	struct f_midi2_opts *opts = to_f_midi2_opts(item);

	usb_put_function_instance(&opts->func_inst);
}

static struct configfs_item_operations f_midi2_item_ops = {
	.release	= f_midi2_opts_release,
};

static struct configfs_group_operations f_midi2_group_ops = {
	.make_group	= f_midi2_opts_ep_make,
	.drop_item	= f_midi2_opts_ep_drop,
};

static const struct config_item_type f_midi2_func_type = {
	.ct_item_ops	= &f_midi2_item_ops,
	.ct_group_ops	= &f_midi2_group_ops,
	.ct_attrs	= f_midi2_attrs,
	.ct_owner	= THIS_MODULE,
};

static void f_midi2_free_inst(struct usb_function_instance *f)
{
	struct f_midi2_opts *opts;

	opts = container_of(f, struct f_midi2_opts, func_inst);

	kfree(opts->info.iface_name);
	kfree(opts);
}

/* gadget alloc_inst */
static struct usb_function_instance *f_midi2_alloc_inst(void)
{
	struct f_midi2_opts *opts;
	struct f_midi2_ep_opts *ep_opts;
	struct f_midi2_block_opts *block_opts;
	int ret;

	opts = kzalloc(sizeof(*opts), GFP_KERNEL);
	if (!opts)
		return ERR_PTR(-ENOMEM);

	mutex_init(&opts->lock);
	opts->func_inst.free_func_inst = f_midi2_free_inst;
	opts->info.process_ump = true;
	opts->info.static_block = true;
	opts->info.num_reqs = 32;
	opts->info.req_buf_size = 512;

	/* create the default ep */
	ret = f_midi2_ep_opts_create(opts, 0, &ep_opts);
	if (ret) {
		kfree(opts);
		return ERR_PTR(ret);
	}

	/* create the default block */
	ret = f_midi2_block_opts_create(ep_opts, 0, &block_opts);
	if (ret) {
		kfree(ep_opts);
		kfree(opts);
		return ERR_PTR(ret);
	}

	/* set up the default MIDI1 (that is mandatory) */
	block_opts->info.midi1_num_groups = 1;

	config_group_init_type_name(&opts->func_inst.group, "",
				    &f_midi2_func_type);

	config_group_init_type_name(&ep_opts->group, "ep.0",
				    &f_midi2_ep_type);
	configfs_add_default_group(&ep_opts->group, &opts->func_inst.group);

	config_group_init_type_name(&block_opts->group, "block.0",
				    &f_midi2_block_type);
	configfs_add_default_group(&block_opts->group, &ep_opts->group);

	return &opts->func_inst;
}

static void do_f_midi2_free(struct f_midi2 *midi2, struct f_midi2_opts *opts)
{
	mutex_lock(&opts->lock);
	--opts->refcnt;
	mutex_unlock(&opts->lock);
	kfree(midi2->string_defs);
	kfree(midi2);
}

static void f_midi2_free(struct usb_function *f)
{
	do_f_midi2_free(func_to_midi2(f),
			container_of(f->fi, struct f_midi2_opts, func_inst));
}

/* verify the parameters set up via configfs;
 * return the number of EPs or a negative error
 */
static int verify_parameters(struct f_midi2_opts *opts)
{
	int i, j, num_eps, num_blks;
	struct f_midi2_ep_info *ep;
	struct f_midi2_block_info *bp;

	for (num_eps = 0; num_eps < MAX_UMP_EPS && opts->eps[num_eps];
	     num_eps++)
		;
	if (!num_eps) {
		pr_err("f_midi2: No EP is defined\n");
		return -EINVAL;
	}

	num_blks = 0;
	for (i = 0; i < num_eps; i++) {
		ep = &opts->eps[i]->info;
		if (!(ep->protocol_caps & ep->protocol)) {
			pr_err("f_midi2: Invalid protocol 0x%x (caps 0x%x) for EP %d\n",
			       ep->protocol, ep->protocol_caps, i);
			return -EINVAL;
		}

		for (j = 0; j < SNDRV_UMP_MAX_BLOCKS && opts->eps[i]->blks[j];
		     j++, num_blks++) {
			bp = &opts->eps[i]->blks[j]->info;
			if (bp->first_group + bp->num_groups > SNDRV_UMP_MAX_GROUPS) {
				pr_err("f_midi2: Invalid group definitions for block %d:%d\n",
				       i, j);
				return -EINVAL;
			}

			if (bp->midi1_num_groups) {
				if (bp->midi1_first_group < bp->first_group ||
				    bp->midi1_first_group + bp->midi1_num_groups >
				    bp->first_group + bp->num_groups) {
					pr_err("f_midi2: Invalid MIDI1 group definitions for block %d:%d\n",
					       i, j);
					return -EINVAL;
				}
			}
		}
	}
	if (!num_blks) {
		pr_err("f_midi2: No block is defined\n");
		return -EINVAL;
	}

	return num_eps;
}

/* fill mapping between MIDI 1.0 cable and UMP EP/group */
static void fill_midi1_cable_mapping(struct f_midi2 *midi2,
				     struct f_midi2_ep *ep,
				     int blk)
{
	const struct f_midi2_block_info *binfo = &ep->blks[blk].info;
	struct midi1_cable_mapping *map;
	int i, group;

	if (!binfo->midi1_num_groups)
		return;
	if (binfo->direction != SNDRV_UMP_DIR_OUTPUT) {
		group = binfo->midi1_first_group;
		map = midi2->in_cable_mapping + midi2->num_midi1_in;
		for (i = 0; i < binfo->midi1_num_groups; i++, group++, map++) {
			if (midi2->num_midi1_in >= MAX_CABLES)
				break;
			map->ep = ep;
			map->block = blk;
			map->group = group;
			midi2->num_midi1_in++;
			/* store 1-based cable number */
			ep->in_group_to_cable[group] = midi2->num_midi1_in;
		}
	}

	if (binfo->direction != SNDRV_UMP_DIR_INPUT) {
		group = binfo->midi1_first_group;
		map = midi2->out_cable_mapping + midi2->num_midi1_out;
		for (i = 0; i < binfo->midi1_num_groups; i++, group++, map++) {
			if (midi2->num_midi1_out >= MAX_CABLES)
				break;
			map->ep = ep;
			map->block = blk;
			map->group = group;
			midi2->num_midi1_out++;
		}
	}
}

/* gadget alloc callback */
static struct usb_function *f_midi2_alloc(struct usb_function_instance *fi)
{
	struct f_midi2 *midi2;
	struct f_midi2_opts *opts;
	struct f_midi2_ep *ep;
	struct f_midi2_block *bp;
	int i, num_eps, blk;

	midi2 = kzalloc(sizeof(*midi2), GFP_KERNEL);
	if (!midi2)
		return ERR_PTR(-ENOMEM);

	opts = container_of(fi, struct f_midi2_opts, func_inst);
	mutex_lock(&opts->lock);
	num_eps = verify_parameters(opts);
	if (num_eps < 0) {
		mutex_unlock(&opts->lock);
		kfree(midi2);
		return ERR_PTR(num_eps);
	}
	++opts->refcnt;
	mutex_unlock(&opts->lock);

	spin_lock_init(&midi2->queue_lock);

	midi2->func.name = "midi2_func";
	midi2->func.bind = f_midi2_bind;
	midi2->func.unbind = f_midi2_unbind;
	midi2->func.get_alt = f_midi2_get_alt;
	midi2->func.set_alt = f_midi2_set_alt;
	midi2->func.setup = f_midi2_setup;
	midi2->func.disable = f_midi2_disable;
	midi2->func.free_func = f_midi2_free;

	midi2->info = opts->info;
	midi2->num_eps = num_eps;

	for (i = 0; i < num_eps; i++) {
		ep = &midi2->midi2_eps[i];
		ep->info = opts->eps[i]->info;
		ep->card = midi2;
		for (blk = 0; blk < SNDRV_UMP_MAX_BLOCKS &&
			     opts->eps[i]->blks[blk]; blk++) {
			bp = &ep->blks[blk];
			ep->num_blks++;
			bp->info = opts->eps[i]->blks[blk]->info;
			bp->gtb_id = ++midi2->total_blocks;
		}
	}

	midi2->string_defs = kcalloc(midi2->total_blocks + 1,
				     sizeof(*midi2->string_defs), GFP_KERNEL);
	if (!midi2->string_defs) {
		do_f_midi2_free(midi2, opts);
		return ERR_PTR(-ENOMEM);
	}

	if (opts->info.iface_name && *opts->info.iface_name)
		midi2->string_defs[STR_IFACE].s = opts->info.iface_name;
	else
		midi2->string_defs[STR_IFACE].s = ump_ep_name(&midi2->midi2_eps[0]);

	for (i = 0; i < midi2->num_eps; i++) {
		ep = &midi2->midi2_eps[i];
		for (blk = 0; blk < ep->num_blks; blk++) {
			bp = &ep->blks[blk];
			midi2->string_defs[gtb_to_str_id(bp->gtb_id)].s =
				ump_fb_name(&bp->info);

			fill_midi1_cable_mapping(midi2, ep, blk);
		}
	}

	if (!midi2->num_midi1_in && !midi2->num_midi1_out) {
		pr_err("f_midi2: MIDI1 definition is missing\n");
		do_f_midi2_free(midi2, opts);
		return ERR_PTR(-EINVAL);
	}

	return &midi2->func;
}

DECLARE_USB_FUNCTION_INIT(midi2, f_midi2_alloc_inst, f_midi2_alloc);

MODULE_DESCRIPTION("USB MIDI 2.0 class function driver");
MODULE_LICENSE("GPL");