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

#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/list.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/platform_device.h>
#include <linux/poll.h>
#include <linux/sched.h>
#include <linux/skbuff.h>
#include <linux/types.h>
#include <net/bluetooth/bluetooth.h>
#include <net/bluetooth/hci.h>

#include "cg2900.h"
#include "cg2900_audio.h"
#include "cg2900_chip.h"

#define MAX_NBR_OF_USERS			10
#define FIRST_USER				1

#define DEFAULT_SCO_HANDLE			0x0008

/* Use a timeout of 5 seconds when waiting for a command response */
#define RESP_TIMEOUT				5000

#define BT_DEV					(info->dev_bt)
#define FM_DEV					(info->dev_fm)

/* Bluetooth error codes */
#define HCI_BT_ERROR_NO_ERROR			0x00

/* Used to select proper API, ignoring subrevisions etc */
enum chip_revision {
	CHIP_REV_PG1,
	CHIP_REV_PG2
};

/**
 * enum chip_resp_state - State when communicating with the CG2900 controller.
 * @IDLE:		No outstanding packets to the controller.
 * @WAITING:		Packet has been sent to the controller. Waiting for
 *			response.
 * @RESP_RECEIVED:	Response from controller has been received but not yet
 *			handled.
 */
enum chip_resp_state {
	IDLE,
	WAITING,
	RESP_RECEIVED
};

/**
 * enum main_state - Main state for the CG2900 Audio driver.
 * @OPENED:	Audio driver has registered to CG2900 Core.
 * @CLOSED:	Audio driver is not registered to CG2900 Core.
 * @RESET:	A reset of CG2900 Core has occurred and no user has re-opened
 *		the audio driver.
 */
enum main_state {
	OPENED,
	CLOSED,
	RESET
};

/**
 * struct endpoint_list - List for storing endpoint configuration nodes.
 * @ep_list:		Pointer to first node in list.
 * @management_mutex:	Mutex for handling access to list.
 */
struct endpoint_list {
	struct list_head	ep_list;
	struct mutex		management_mutex;
};

/**
 * struct endpoint_config_node - Node for storing endpoint configuration.
 * @list:		list_head struct.
 * @endpoint_id:	Endpoint ID.
 * @config:		Stored configuration for this endpoint.
 */
struct endpoint_config_node {
	struct list_head			list;
	enum cg2900_audio_endpoint_id		endpoint_id;
	union cg2900_endpoint_config_union	config;
};

/**
 * struct audio_info - Main CG2900 Audio driver info structure.
 * @list:			list_head struct.
 * @state:			Current state of the CG2900 Audio driver.
 * @revision:			Chip revision, used to select API.
 * @misc_dev:			The misc device created by this driver.
 * @misc_registered:		True if misc device is registered.
 * @parent:			Parent device.
 * @dev_bt:			Device registered by this driver for the BT
 *				audio channel.
 * @dev_fm:			Device registered by this driver for the FM
 *				audio channel.
 * @management_mutex:		Mutex for handling access to CG2900 Audio driver
 *				management.
 * @bt_mutex:			Mutex for handling access to BT audio channel.
 * @fm_mutex:			Mutex for handling access to FM audio channel.
 * @nbr_of_users_active:	Number of sessions open in the CG2900 Audio
 *				driver.
 * @i2s_config:			DAI I2S configuration.
 * @i2s_pcm_config:		DAI PCM_I2S configuration.
 * @i2s_config_known:		@true if @i2s_config has been set,
 *				@false otherwise.
 * @i2s_pcm_config_known:	@true if @i2s_pcm_config has been set,
 *				@false otherwise.
 * @endpoints:			List containing the endpoint configurations.
 * @stream_ids:			Bitmask for in-use stream ids (only used with
 *				PG2 chip API).
 */
struct audio_info {
	struct list_head		list;
	enum main_state			state;
	enum chip_revision		revision;
	struct miscdevice		misc_dev;
	bool				misc_registered;
	struct device			*parent;
	struct device			*dev_bt;
	struct device			*dev_fm;
	struct mutex			management_mutex;
	struct mutex			bt_mutex;
	struct mutex			fm_mutex;
	int				nbr_of_users_active;
	struct cg2900_dai_conf_i2s	i2s_config;
	struct cg2900_dai_conf_i2s_pcm	i2s_pcm_config;
	bool				i2s_config_known;
	bool				i2s_pcm_config_known;
	struct endpoint_list		endpoints;
	u8				stream_ids[16];
};

/**
 * struct audio_user - CG2900 audio user info structure.
 * @session:	Stored session for the char device.
 * @resp_state:	State for controller communications.
 * @info:	CG2900 audio info structure.
 */
struct audio_user {
	int			session;
	enum chip_resp_state	resp_state;
	struct audio_info	*info;
};

/**
 * struct audio_cb_info - Callback info structure registered in @user_data.
 * @user:	Audio user currently awaiting data on the channel.
 * @wq:		Wait queue for this channel.
 * @skb_queue:	Sk buffer queue.
 */
struct audio_cb_info {
	struct audio_user	*user;
	wait_queue_head_t	wq;
	struct sk_buff_head	skb_queue;
};

/**
 * struct char_dev_info - CG2900 character device info structure.
 * @session:		Stored session for the char device.
 * @stored_data:	Data returned when executing last command, if any.
 * @stored_data_len:	Length of @stored_data in bytes.
 * @management_mutex:	Mutex for handling access to char dev management.
 * @rw_mutex:		Mutex for handling access to char dev writes and reads.
 * @info:		CG2900 audio info struct.
 * @rx_queue:		Data queue.
 */
struct char_dev_info {
	int			session;
	u8			*stored_data;
	int			stored_data_len;
	struct mutex		management_mutex;
	struct mutex		rw_mutex;
	struct audio_info	*info;
	struct sk_buff_head	rx_queue;
};

/*
 * cg2900_audio_devices - List of active CG2900 audio devices.
 */
LIST_HEAD(cg2900_audio_devices);

/*
 * cg2900_audio_sessions - Pointers to currently opened sessions (maps
 *			   session ID to user info).
 */
static struct audio_user *cg2900_audio_sessions[MAX_NBR_OF_USERS];

/*
 *	Internal conversion functions
 *
 *	Since the CG2900 APIs uses several different ways to encode the
 *	same parameter in different cases, we have to use translator
 *	functions.
 */

/**
 * session_config_sample_rate() - Convert sample rate to format used in VS_Set_SessionConfiguration.
 * @rate: Sample rate in API encoding.
 */
static u8 session_config_sample_rate(enum cg2900_endpoint_sample_rate rate)
{
	static const u8 codes[] = {
		[ENDPOINT_SAMPLE_RATE_8_KHZ]    = CG2900_BT_SESSION_RATE_8K,
		[ENDPOINT_SAMPLE_RATE_16_KHZ]   = CG2900_BT_SESSION_RATE_16K,
		[ENDPOINT_SAMPLE_RATE_44_1_KHZ] = CG2900_BT_SESSION_RATE_44_1K,
		[ENDPOINT_SAMPLE_RATE_48_KHZ]   = CG2900_BT_SESSION_RATE_48K
	};

	return codes[rate];
}

/**
 * mc_i2s_sample_rate() - Convert sample rate to format used in VS_Port_Config for I2S.
 * @rate: Sample rate in API encoding.
 */
static u8 mc_i2s_sample_rate(enum cg2900_dai_sample_rate rate)
{
	static const u8 codes[] = {
		[SAMPLE_RATE_8]    = CG2900_MC_I2S_SAMPLE_RATE_8,
		[SAMPLE_RATE_16]   = CG2900_MC_I2S_SAMPLE_RATE_16,
		[SAMPLE_RATE_44_1] = CG2900_MC_I2S_SAMPLE_RATE_44_1,
		[SAMPLE_RATE_48]   = CG2900_MC_I2S_SAMPLE_RATE_48
	};

	return codes[rate];
}

/**
 * mc_pcm_sample_rate() - Convert sample rate to format used in VS_Port_Config for PCM/I2S.
 * @rate: Sample rate in API encoding.
 */
static u8 mc_pcm_sample_rate(enum cg2900_dai_sample_rate rate)
{
	static const u8 codes[] = {
		[SAMPLE_RATE_8]    = CG2900_MC_PCM_SAMPLE_RATE_8,
		[SAMPLE_RATE_16]   = CG2900_MC_PCM_SAMPLE_RATE_16,
		[SAMPLE_RATE_44_1] = CG2900_MC_PCM_SAMPLE_RATE_44_1,
		[SAMPLE_RATE_48]   = CG2900_MC_PCM_SAMPLE_RATE_48
	};

	return codes[rate];
}

/**
 * mc_i2s_channel_select() - Convert channel selection to format used in VS_Port_Config.
 * @sel: Channel selection in API encoding.
 */
static u8 mc_i2s_channel_select(enum cg2900_dai_channel_sel sel)
{
	static const u8 codes[] = {
		[CHANNEL_SELECTION_RIGHT] = CG2900_MC_I2S_RIGHT_CHANNEL,
		[CHANNEL_SELECTION_LEFT]  = CG2900_MC_I2S_LEFT_CHANNEL,
		[CHANNEL_SELECTION_BOTH]  = CG2900_MC_I2S_BOTH_CHANNELS
	};
	return codes[sel];
}

/**
 * get_fs_duration() - Convert framesync-enumeration to real value.
 * @duration: Framsync duration (API encoding).
 *
 * Returns:
 * Duration in bits.
 */
static u16 get_fs_duration(enum cg2900_dai_fs_duration duration)
{
	static const u16 values[] = {
		[SYNC_DURATION_8] = 8,
		[SYNC_DURATION_16] = 16,
		[SYNC_DURATION_24] = 24,
		[SYNC_DURATION_32] = 32,
		[SYNC_DURATION_48] = 48,
		[SYNC_DURATION_50] = 50,
		[SYNC_DURATION_64] = 64,
		[SYNC_DURATION_75] = 75,
		[SYNC_DURATION_96] = 96,
		[SYNC_DURATION_125] = 125,
		[SYNC_DURATION_128] = 128,
		[SYNC_DURATION_150] = 150,
		[SYNC_DURATION_192] = 192,
		[SYNC_DURATION_250] = 250,
		[SYNC_DURATION_256] = 256,
		[SYNC_DURATION_300] = 300,
		[SYNC_DURATION_384] = 384,
		[SYNC_DURATION_500] = 500,
		[SYNC_DURATION_512] = 512,
		[SYNC_DURATION_600] = 600,
		[SYNC_DURATION_768] = 768
	};
	return values[duration];
}

/**
 * mc_i2s_role() - Convert master/slave encoding to format for I2S-ports.
 * @mode: Master/slave in API encoding.
 */
static u8 mc_i2s_role(enum cg2900_dai_mode mode)
{
	if (mode == DAI_MODE_SLAVE)
		return CG2900_I2S_MODE_SLAVE;
	else
		return CG2900_I2S_MODE_MASTER;
}

/**
 * mc_pcm_role() - Convert master/slave encoding to format for PCM/I2S-port.
 * @mode: Master/slave in API encoding.
 */
static u8 mc_pcm_role(enum cg2900_dai_mode mode)
{
	if (mode == DAI_MODE_SLAVE)
		return CG2900_PCM_MODE_SLAVE;
	else
		return CG2900_PCM_MODE_MASTER;
}

/**
 * fm_get_conversion() - Convert sample rate to convert up/down used in X_Set_Control FM commands.
 * @srate: Sample rate.
 */
static u16 fm_get_conversion(enum cg2900_endpoint_sample_rate srate)
{
	if (srate >= ENDPOINT_SAMPLE_RATE_44_1_KHZ)
		return CG2900_FM_CMD_SET_CTRL_CONV_UP;
	else
		return CG2900_FM_CMD_SET_CTRL_CONV_DOWN;
}

/**
 * get_info() - Return info structure for this device.
 * @dev:	Current device.
 *
 * This function returns the info structure on the following basis:
 *	* If dev is NULL return first info struct found. If none is found return
 *	  NULL.
 *	* If dev is valid we will return corresponding info struct if dev is the
 *	  parent of the info struct or if dev's parent is the parent of the info
 *	  struct.
 *	* If dev is valid and no info structure is found, a new info struct is
 *	  allocated, initialized, and returned.
 *
 * Returns:
 *   Pointer to info struct if there is no error.
 *   NULL if NULL was supplied and no info structure exist.
 *   ERR_PTR(-ENOMEM) if allocation fails.
 */
static struct audio_info *get_info(struct device *dev)
{
	struct list_head *cursor;
	struct audio_info *tmp;
	struct audio_info *info = NULL;

	/*
	 * Find the info structure for dev. If NULL is supplied for dev
	 * just return first device found.
	 */
	list_for_each(cursor, &cg2900_audio_devices) {
		tmp = list_entry(cursor, struct audio_info, list);
		if (!dev || tmp->parent == dev->parent || tmp->parent == dev) {
			info = tmp;
			break;
		}
	}

	if (!dev || info)
		return info;

	info = kzalloc(sizeof(*info), GFP_KERNEL);
	if (!info) {
		dev_err(dev, "Could not allocate info struct\n");
		return ERR_PTR(-ENOMEM);
	}
	info->parent = dev->parent;

	/* Initiate the mutexes */
	mutex_init(&(info->management_mutex));
	mutex_init(&(info->bt_mutex));
	mutex_init(&(info->fm_mutex));
	mutex_init(&(info->endpoints.management_mutex));

	/* Initiate the endpoint list */
	INIT_LIST_HEAD(&info->endpoints.ep_list);

	list_add_tail(&info->list, &cg2900_audio_devices);

	dev_info(dev, "CG2900 device added\n");
	return info;
}

/**
 * flush_endpoint_list() - Deletes all stored endpoints in @list.
 * @list:	List of endpoints.
 */
static void flush_endpoint_list(struct endpoint_list *list)
{
	struct list_head *cursor, *next;
	struct endpoint_config_node *tmp;

	mutex_lock(&list->management_mutex);
	list_for_each_safe(cursor, next, &(list->ep_list)) {
		tmp = list_entry(cursor, struct endpoint_config_node, list);
		list_del(cursor);
		kfree(tmp);
	}
	mutex_unlock(&list->management_mutex);
}

/**
 * device_removed() - Remove device from list if there are no channels left.
 * @info:	CG2900 audio info structure.
 */
static void device_removed(struct audio_info *info)
{
	struct list_head *cursor;
	struct audio_info *tmp;

	if (info->dev_bt || info->dev_fm)
		/* There are still devices active */
		return;

	/* Find the stored info structure */
	list_for_each(cursor, &cg2900_audio_devices) {
		tmp = list_entry(cursor, struct audio_info, list);
		if (tmp == info) {
			list_del(cursor);
			break;
		}
	}

	flush_endpoint_list(&info->endpoints);

	mutex_destroy(&info->management_mutex);
	mutex_destroy(&info->bt_mutex);
	mutex_destroy(&info->fm_mutex);
	mutex_destroy(&info->endpoints.management_mutex);

	kfree(info);
	pr_info("CG2900 Audio device removed");
}

/**
 * read_cb() - Handle data received from STE connectivity driver.
 * @dev:	Device receiving data.
 * @skb:	Buffer with data coming form device.
 */
static void read_cb(struct cg2900_user_data *dev, struct sk_buff *skb)
{
	struct audio_cb_info *cb_info;

	cb_info = cg2900_get_usr(dev);

	if (!(cb_info->user)) {
		dev_err(dev->dev, "NULL supplied as cb_info->user\n");
		return;
	}

	/* Mark that packet has been received */
	dev_dbg(dev->dev, "New resp_state: RESP_RECEIVED");
	cb_info->user->resp_state = RESP_RECEIVED;
	skb_queue_tail(&cb_info->skb_queue, skb);
	wake_up_all(&cb_info->wq);
}

/**
 * reset_cb() - Reset callback function.
 * @dev:	CG2900_Core device resetting.
 */
static void reset_cb(struct cg2900_user_data *dev)
{
	struct audio_info *info;

	dev_dbg(dev->dev, "reset_cb\n");

	info = dev_get_drvdata(dev->dev);
	mutex_lock(&info->management_mutex);
	info->nbr_of_users_active = 0;
	info->state = RESET;
	mutex_unlock(&info->management_mutex);
}

/**
 * get_session_user() - Check that supplied session is within valid range.
 * @session:	Session ID.
 *
 * Returns:
 *   Audio_user if there is no error.
 *   NULL for bad session ID.
 */
static struct audio_user *get_session_user(int session)
{
	struct audio_user *audio_user;

	if (session < FIRST_USER || session >= MAX_NBR_OF_USERS) {
		pr_err("Calling with invalid session %d", session);
		return NULL;
	}

	audio_user = cg2900_audio_sessions[session];
	if (!audio_user)
		pr_err("Calling with non-opened session %d", session);
	return audio_user;
}

/**
 * del_endpoint_private() - Deletes an endpoint from @list.
 * @endpoint_id:	Endpoint ID.
 * @list:		List of endpoints.
 *
 * Deletes an endpoint from the supplied endpoint list.
 * This function is not protected by any semaphore.
 */
static void del_endpoint_private(enum cg2900_audio_endpoint_id endpoint_id,
				 struct endpoint_list *list)
{
	struct list_head *cursor, *next;
	struct endpoint_config_node *tmp;

	list_for_each_safe(cursor, next, &(list->ep_list)) {
		tmp = list_entry(cursor, struct endpoint_config_node, list);
		if (tmp->endpoint_id == endpoint_id) {
			list_del(cursor);
			kfree(tmp);
		}
	}
}

/**
 * add_endpoint() - Add endpoint node to @list.
 * @ep_config:	Endpoint configuration.
 * @list:	List of endpoints.
 *
 * Add endpoint node to the supplied list and copies supplied config to node.
 * If a node already exists for the supplied endpoint, the old node is removed
 * and replaced by the new node.
 */
static void add_endpoint(struct cg2900_endpoint_config *ep_config,
			 struct endpoint_list *list)
{
	struct endpoint_config_node *item;

	item = kzalloc(sizeof(*item), GFP_KERNEL);
	if (!item) {
		pr_err("add_endpoint: Failed to alloc memory");
		return;
	}

	/* Store values */
	item->endpoint_id = ep_config->endpoint_id;
	memcpy(&(item->config), &(ep_config->config), sizeof(item->config));

	mutex_lock(&(list->management_mutex));

	/*
	 * Check if endpoint ID already exist in list.
	 * If that is the case, remove it.
	 */
	if (!list_empty(&(list->ep_list)))
		del_endpoint_private(ep_config->endpoint_id, list);

	list_add_tail(&(item->list), &(list->ep_list));

	mutex_unlock(&(list->management_mutex));
}

/**
 * find_endpoint() - Finds endpoint identified by @endpoint_id in @list.
 * @endpoint_id:	Endpoint ID.
 * @list:		List of endpoints.
 *
 * Returns:
 *   Endpoint configuration if there is no error.
 *   NULL if no configuration can be found for @endpoint_id.
 */
static union cg2900_endpoint_config_union *
find_endpoint(enum cg2900_audio_endpoint_id endpoint_id,
	      struct endpoint_list *list)
{
	struct list_head *cursor, *next;
	struct endpoint_config_node *tmp;
	struct endpoint_config_node *ret_ep = NULL;

	mutex_lock(&list->management_mutex);
	list_for_each_safe(cursor, next, &(list->ep_list)) {
		tmp = list_entry(cursor, struct endpoint_config_node, list);
		if (tmp->endpoint_id == endpoint_id) {
			ret_ep = tmp;
			break;
		}
	}
	mutex_unlock(&list->management_mutex);

	if (ret_ep)
		return &(ret_ep->config);
	else
		return NULL;
}

/**
 * new_stream_id() - Allocate a new stream id.
 * @info:	Current audio info struct.
 *
 * Returns:
 *  0-127 new valid id.
 *  -ENOMEM if no id is available.
 */
static s8 new_stream_id(struct audio_info *info)
{
	int r;

	mutex_lock(&info->management_mutex);

	r = find_first_zero_bit(info->stream_ids,
				8 * sizeof(info->stream_ids));

	if (r >= 8 * sizeof(info->stream_ids)) {
		r = -ENOMEM;
		goto out;
	}

	set_bit(r, (unsigned long int *)info->stream_ids);

out:
	mutex_unlock(&info->management_mutex);
	return r;
}

/**
 * release_stream_id() - Release a stream id.
 * @info:	Current audio info struct.
 * @id:		Stream to release.
 */
static void release_stream_id(struct audio_info *info, u8 id)
{
	if (id >= 8 * sizeof(info->stream_ids))
		return;

	mutex_lock(&info->management_mutex);
	clear_bit(id, (unsigned long int *)info->stream_ids);
	mutex_unlock(&info->management_mutex);
}

/**
 * receive_fm_write_response() - Wait for and handle the response to an FM Legacy WriteCommand request.
 * @audio_user:	Audio user to check for.
 * @command:	FM command to wait for.
 *
 * This function first waits (up to 5 seconds) for a response to an FM
 * write command and when one arrives, it checks that it is the one we
 * are waiting for and also that no error has occurred.
 *
 * Returns:
 *   0 if there is no error.
 *   -ECOMM if no response was received.
 *   -EIO for other errors.
 */
static int receive_fm_write_response(struct audio_user *audio_user,
				     u16 command)
{
	int err = 0;
	int res;
	struct sk_buff *skb;
	struct fm_leg_cmd_cmpl *pkt;
	u16 rsp_cmd;
	struct audio_cb_info *cb_info;
	struct audio_info *info;
	struct cg2900_user_data *pf_data;

	info = audio_user->info;
	pf_data = dev_get_platdata(info->dev_fm);
	cb_info = cg2900_get_usr(pf_data);

	/*
	 * Wait for callback to receive command complete and then wake us up
	 * again.
	 */
	res = wait_event_timeout(cb_info->wq,
				 audio_user->resp_state == RESP_RECEIVED,
				 msecs_to_jiffies(RESP_TIMEOUT));
	if (!res) {
		dev_err(FM_DEV, "Timeout while waiting for return packet\n");
		return -ECOMM;
	} else if (res < 0) {
		dev_err(FM_DEV,
			"Error %d occurred while waiting for return packet\n",
			res);
		return -ECOMM;
	}

	/* OK, now we should have received answer. Let's check it. */
	skb = skb_dequeue_tail(&cb_info->skb_queue);
	if (!skb) {
		dev_err(FM_DEV, "No skb in queue when it should be there\n");
		return -EIO;
	}

	pkt = (struct fm_leg_cmd_cmpl *)skb->data;

	/* Check if we received the correct event */
	if (pkt->opcode != CG2900_FM_GEN_ID_LEGACY) {
		dev_err(FM_DEV,
			"Received unknown FM packet. 0x%X %X %X %X %X\n",
			skb->data[0], skb->data[1], skb->data[2],
			skb->data[3], skb->data[4]);
		err = -EIO;
		goto error_handling_free_skb;
	}

	/* FM Legacy Command complete event */
	rsp_cmd = cg2900_get_fm_cmd_id(le16_to_cpu(pkt->response_head));

	if (pkt->fm_function != CG2900_FM_CMD_PARAM_WRITECOMMAND ||
	    rsp_cmd != command) {
		dev_err(FM_DEV,
			"Received unexpected packet func 0x%X cmd 0x%04X\n",
			pkt->fm_function, rsp_cmd);
		err = -EIO;
		goto error_handling_free_skb;
	}

	if (pkt->cmd_status != CG2900_FM_CMD_STATUS_COMMAND_SUCCEEDED) {
		dev_err(FM_DEV, "FM Command failed (%d)\n", pkt->cmd_status);
		err = -EIO;
		goto error_handling_free_skb;
	}
	/* Operation succeeded. We are now done */

error_handling_free_skb:
	kfree_skb(skb);
	return err;
}

/**
 * receive_bt_cmd_complete() - Wait for and handle an BT Command Complete event.
 * @audio_user:	Audio user to check for.
 * @rsp:	Opcode of BT command to wait for.
 * @data:	Pointer to buffer if any received data should be stored (except
 *		status).
 * @data_len:	Length of @data in bytes.
 *
 * This function first waits for BT Command Complete event (up to 5 seconds)
 * and when one arrives, it checks that it is the one we are waiting for and
 * also that no error has occurred.
 * If @data is supplied it also copies received data into @data.
 *
 * Returns:
 *   0 if there is no error.
 *   -ECOMM if no response was received.
 *   -EIO for other errors.
 */
static int receive_bt_cmd_complete(struct audio_user *audio_user, u16 rsp,
				   void *data, int data_len)
{
	int err = 0;
	int res;
	struct sk_buff *skb;
	struct bt_cmd_cmpl_event *evt;
	u16 opcode;
	struct audio_cb_info *cb_info;
	struct audio_info *info;
	struct cg2900_user_data *pf_data;

	info = audio_user->info;
	pf_data = dev_get_platdata(info->dev_bt);
	cb_info = cg2900_get_usr(pf_data);

	/*
	 * Wait for callback to receive command complete and then wake us up
	 * again.
	 */
	res = wait_event_timeout(cb_info->wq,
				 audio_user->resp_state == RESP_RECEIVED,
				 msecs_to_jiffies(RESP_TIMEOUT));
	if (!res) {
		dev_err(BT_DEV, "Timeout while waiting for return packet\n");
		return -ECOMM;
	} else if (res < 0) {
		/* We timed out or an error occurred */
		dev_err(BT_DEV,
			"Error %d occurred while waiting for return packet\n",
			res);
		return -ECOMM;
	}

	/* OK, now we should have received answer. Let's check it. */
	skb = skb_dequeue_tail(&cb_info->skb_queue);
	if (!skb) {
		dev_err(BT_DEV, "No skb in queue when it should be there\n");
		return -EIO;
	}

	evt = (struct bt_cmd_cmpl_event *)skb->data;
	if (evt->eventcode != HCI_EV_CMD_COMPLETE) {
		dev_err(BT_DEV,
			"We did not receive the event we expected (0x%X)\n",
			evt->eventcode);
		err = -EIO;
		goto error_handling_free_skb;
	}

	opcode = le16_to_cpu(evt->opcode);
	if (opcode != rsp) {
		dev_err(BT_DEV,
			"Received cmd complete for unexpected command: "
			"0x%04X\n", opcode);
		err = -EIO;
		goto error_handling_free_skb;
	}

	if (evt->status != HCI_BT_ERROR_NO_ERROR) {
		dev_err(BT_DEV, "Received command complete with err %d\n",
			evt->status);
		err = -EIO;
		/*
		* In data there might be more detailed error code.
		* Let's copy it.
		*/
	}

	/*
	 * Copy the rest of the parameters if a buffer has been supplied.
	 * The caller must have set the length correctly.
	 */
	if (data)
		memcpy(data, evt->data, data_len);

	/* Operation succeeded. We are now done */

error_handling_free_skb:
	kfree_skb(skb);
	return err;
}

/**
 * send_vs_delete_stream() - Delete an audio stream defined by @stream_handle.
 * @audio_user:		Audio user to check for.
 * @stream_handle:	Handle of the audio stream.
 *
 * This function is used to delete an audio stream defined by a stream
 * handle.
 *
 * Returns:
 *   0 if there is no error.
 *   -ECOMM if no response was received.
 *   -ENOMEM upon allocation errors.
 *   Errors from @cg2900_write.
 *   -EIO for other errors.
 */
static int send_vs_delete_stream(struct audio_user *audio_user,
			    unsigned int stream_handle)
{
	int err = 0;
	struct sk_buff *skb;
	u16 opcode;
	struct audio_info *info = audio_user->info;
	struct cg2900_user_data *pf_data = dev_get_platdata(info->dev_bt);
	struct audio_cb_info *cb_info = cg2900_get_usr(pf_data);

	/* Now delete the stream - format command... */
	if (info->revision == CHIP_REV_PG1) {
		struct bt_vs_reset_session_cfg_cmd *cmd;

		dev_dbg(BT_DEV, "BT: HCI_VS_Reset_Session_Configuration\n");

		skb = pf_data->alloc_skb(sizeof(*cmd), GFP_KERNEL);
		if (!skb) {
			dev_err(BT_DEV, "Could not allocate skb\n");
			err = -ENOMEM;
			return err;
		}

		cmd = (struct bt_vs_reset_session_cfg_cmd *)
			skb_put(skb, sizeof(*cmd));

		opcode = CG2900_BT_VS_RESET_SESSION_CONFIG;
		cmd->opcode = cpu_to_le16(opcode);
		cmd->plen   = BT_PARAM_LEN(sizeof(*cmd));
		cmd->id     = (u8)stream_handle;
	} else {
		struct mc_vs_delete_stream_cmd *cmd;

		dev_dbg(BT_DEV, "BT: HCI_VS_Delete_Stream\n");

		skb = pf_data->alloc_skb(sizeof(*cmd), GFP_KERNEL);
		if (!skb) {
			dev_err(BT_DEV, "Could not allocate skb\n");
			err = -ENOMEM;
			return err;
		}

		cmd = (struct mc_vs_delete_stream_cmd *)
			skb_put(skb, sizeof(*cmd));

		opcode = CG2900_MC_VS_DELETE_STREAM;
		cmd->opcode = cpu_to_le16(opcode);
		cmd->plen   = BT_PARAM_LEN(sizeof(*cmd));
		cmd->stream = (u8)stream_handle;
	}

	/* ...and send it */
	cb_info->user = audio_user;
	dev_dbg(BT_DEV, "New resp_state: WAITING\n");
	audio_user->resp_state = WAITING;

	err = pf_data->write(pf_data, skb);
	if (err) {
		dev_err(BT_DEV, "Error %d occurred while transmitting skb\n",
			err);
		goto error_handling_free_skb;
	}

	/* wait for response */
	if (info->revision == CHIP_REV_PG1) {
		err = receive_bt_cmd_complete(audio_user, opcode, NULL, 0);
	} else {
		u8 vs_err;

		/* All commands in PG2 API returns one byte extra status */
		err = receive_bt_cmd_complete(audio_user, opcode,
					      &vs_err, sizeof(vs_err));

	if (err)
		dev_err(BT_DEV,
			"VS_DELETE_STREAM - failed with error 0x%02X\n",
			vs_err);
		else
			release_stream_id(info, stream_handle);
	}

	return err;

error_handling_free_skb:
	kfree_skb(skb);
	return err;
}

/**
 * send_vs_session_ctrl() - Formats an sends a CG2900_BT_VS_SESSION_CTRL command.
 * @user:		Audio user this command belongs to.
 * @stream_handle:	Handle to stream.
 * @command:		Command to execute on stream, should be one of
 *			CG2900_BT_SESSION_START, CG2900_BT_SESSION_STOP,
 *			CG2900_BT_SESSION_PAUSE, CG2900_BT_SESSION_RESUME.
 *
 * Packs and sends a command packet and waits for the response. Must
 * be called with the bt_mutex held.
 *
 * Returns:
 *  0 if there is no error.
 *  -ENOMEM if not possible to allocate packet.
 *  -ECOMM if no response was received.
 *  -EIO for other errors.
 */
static int send_vs_session_ctrl(struct audio_user *user,
				u8 stream_handle, u8 command)
{
	int err = 0;
	struct bt_vs_session_ctrl_cmd *pkt;
	struct sk_buff *skb;
	struct audio_cb_info *cb_info;
	struct audio_info *info;
	struct cg2900_user_data *pf_data;

	info = user->info;
	pf_data = dev_get_platdata(info->dev_bt);
	cb_info = cg2900_get_usr(pf_data);

	dev_dbg(BT_DEV, "BT: HCI_VS_Session_Control handle: %d cmd: %d\n",
		stream_handle, command);

	skb = pf_data->alloc_skb(sizeof(*pkt), GFP_KERNEL);
	if (!skb) {
		dev_err(BT_DEV,
			"send_vs_session_ctrl: Could not allocate skb\n");
		return -ENOMEM;
	}

	/* Enter data into the skb */
	pkt = (struct bt_vs_session_ctrl_cmd *) skb_put(skb, sizeof(*pkt));

	pkt->opcode  = cpu_to_le16(CG2900_BT_VS_SESSION_CTRL);
	pkt->plen    = BT_PARAM_LEN(sizeof(*pkt));
	pkt->id      = stream_handle;
	pkt->control = command; /* Start/stop etc */

	cb_info->user = user;
	dev_dbg(BT_DEV, "New resp_state: WAITING\n");
	user->resp_state = WAITING;

	/* Send packet to controller */
	err = pf_data->write(pf_data, skb);
	if (err) {
		dev_err(BT_DEV, "Error %d occurred while transmitting skb\n",
			err);
		kfree_skb(skb);
		goto finished;
	}

	err = receive_bt_cmd_complete(user, CG2900_BT_VS_SESSION_CTRL,
				      NULL, 0);
finished:
	dev_dbg(BT_DEV, "New resp_state: IDLE\n");
	user->resp_state = IDLE;
	return err;
}

/**
 * send_vs_session_config() - Formats an sends a CG2900_BT_VS_SESSION_CONFIG command.
 * @user:		Audio user this command belongs to.
 * @config_stream:	Custom function for configuring the stream.
 * @priv_data:		Private data passed to @config_stream untouched.
 *
 * Packs and sends a command packet and waits for the response. Must
 * be called with the bt_mutex held.
 *
 * Space is allocated for one stream and a custom function is used to
 * fill in the stream configuration.
 *
 * Returns:
 *  0-255 stream handle if no error.
 *  -ENOMEM if not possible to allocate packet.
 *  -ECOMM if no response was received.
 *  -EIO for other errors.
 */
static int send_vs_session_config(struct audio_user *user,
	void(*config_stream)(struct audio_info *, void *,
			     struct session_config_stream *),
	void *priv_data)
{
	int err = 0;
	struct sk_buff *skb;
	struct bt_vs_session_config_cmd *pkt;
	u8 session_id;
	struct audio_cb_info *cb_info;
	struct audio_info *info;
	struct cg2900_user_data *pf_data;

	info = user->info;
	pf_data = dev_get_platdata(info->dev_bt);
	cb_info = cg2900_get_usr(pf_data);

	dev_dbg(BT_DEV, "BT: HCI_VS_Set_Session_Configuration\n");

	skb = pf_data->alloc_skb(sizeof(*pkt), GFP_KERNEL);
	if (!skb) {
		dev_err(BT_DEV,
			"send_vs_session_config: Could not allocate skb\n");
		return -ENOMEM;
	}

	pkt = (struct bt_vs_session_config_cmd *)skb_put(skb, sizeof(*pkt));
	/* zero the packet so we don't have to set all reserved fields */
	memset(pkt, 0, sizeof(*pkt));

	/* Common parameters */
	pkt->opcode    = cpu_to_le16(CG2900_BT_VS_SET_SESSION_CONFIG);
	pkt->plen      = BT_PARAM_LEN(sizeof(*pkt));
	pkt->n_streams = 1; /* 1 stream configuration supplied */

	/* Let the custom-function fill in the rest */
	config_stream(info, priv_data, &pkt->stream);

	cb_info->user = user;
	dev_dbg(BT_DEV, "New resp_state: WAITING\n");
	user->resp_state = WAITING;

	/* Send packet to controller */
	err = pf_data->write(pf_data, skb);
	if (err) {
		dev_err(BT_DEV, "Error %d occurred while transmitting skb\n",
			err);
		kfree_skb(skb);
		goto finished;
	}

	err = receive_bt_cmd_complete(user,
				      CG2900_BT_VS_SET_SESSION_CONFIG,
				      &session_id, sizeof(session_id));
	/* Return session id/stream handle if success */
	if (!err)
		err = session_id;

finished:
	dev_dbg(BT_DEV, "New resp_state: IDLE\n");
	user->resp_state = IDLE;
	return err;
}

/**
 * send_fm_write_1_param() - Formats and sends an FM legacy write command with one parameter.
 * @user:	Audio user this command belongs to.
 * @command:	Command.
 * @param:	Parameter for command.
 *
 * Packs and sends a command packet and waits for the response. Must
 * be called with the fm_mutex held.
 *
 * Returns:
 *  0 if there is no error.
 *  -ENOMEM if not possible to allocate packet.
 *  -ECOMM if no response was received.
 *  -EIO for other errors.
 */
static int send_fm_write_1_param(struct audio_user *user,
				 u16 command, u16 param)
{
	int err = 0;
	struct sk_buff *skb;
	struct fm_leg_cmd *cmd;
	size_t len;
	struct audio_cb_info *cb_info;
	struct audio_info *info;
	struct cg2900_user_data *pf_data;

	info = user->info;
	pf_data = dev_get_platdata(info->dev_fm);
	cb_info = cg2900_get_usr(pf_data);

	dev_dbg(FM_DEV, "send_fm_write_1_param cmd 0x%X param 0x%X\n",
		command, param);

	/* base package + one parameter */
	len = sizeof(*cmd) + sizeof(cmd->fm_cmd.data[0]);

	skb = pf_data->alloc_skb(len, GFP_KERNEL);
	if (!skb) {
		dev_err(FM_DEV,
			"send_fm_write_1_param: Could not allocate skb\n");
		return -ENOMEM;
	}

	cmd = (struct fm_leg_cmd *)skb_put(skb, len);

	cmd->length      = CG2900_FM_CMD_PARAM_LEN(len);
	cmd->opcode      = CG2900_FM_GEN_ID_LEGACY;
	cmd->read_write  = CG2900_FM_CMD_LEG_PARAM_WRITE;
	cmd->fm_function = CG2900_FM_CMD_PARAM_WRITECOMMAND;
	/* one parameter - builtin assumption for this function */
	cmd->fm_cmd.head    = cpu_to_le16(cg2900_make_fm_cmd_id(command, 1));
	cmd->fm_cmd.data[0] = cpu_to_le16(param);

	cb_info->user = user;
	dev_dbg(FM_DEV, "New resp_state: WAITING\n");
	user->resp_state = WAITING;

	/* Send packet to controller */
	err = pf_data->write(pf_data, skb);
	if (err) {
		dev_err(FM_DEV, "Error %d occurred while transmitting skb\n",
			err);
		kfree_skb(skb);
		goto finished;
	}

	err = receive_fm_write_response(user, command);
finished:
	dev_dbg(FM_DEV, "New resp_state: IDLE\n");
	user->resp_state = IDLE;
	return err;
}

/**
 * send_vs_stream_ctrl() - Formats an sends a CG2900_MC_VS_STREAM_CONTROL command.
 * @user:	Audio user this command belongs to.
 * @stream:	Stream id.
 * @command:	Start/stop etc.
 *
 * Packs and sends a command packet and waits for the response. Must
 * be called with the bt_mutex held.
 *
 * While the HCI command allows for multiple streams in one command,
 * this function only handles one.
 *
 * Returns:
 *  0 if there is no error.
 *  -ENOMEM if not possible to allocate packet.
 *  -ECOMM if no response was received.
 *  -EIO for other errors.
 */
static int send_vs_stream_ctrl(struct audio_user *user, u8 stream, u8 command)
{
	int err = 0;
	struct sk_buff *skb;
	struct mc_vs_stream_ctrl_cmd *cmd;
	size_t len;
	u8 vs_err;
	struct audio_cb_info *cb_info;
	struct audio_info *info;
	struct cg2900_user_data *pf_data;

	info = user->info;
	pf_data = dev_get_platdata(info->dev_bt);
	cb_info = cg2900_get_usr(pf_data);

	dev_dbg(BT_DEV, "send_vs_stream_ctrl stream %d command %d\n", stream,
		command);

	/* basic length + one stream */
	len = sizeof(*cmd) + sizeof(cmd->stream[0]);

	skb = pf_data->alloc_skb(len, GFP_KERNEL);
	if (!skb) {
		dev_err(BT_DEV, "send_vs_stream_ctrl:Could not allocate skb\n");
		return -ENOMEM;
	}

	cmd = (struct mc_vs_stream_ctrl_cmd *)skb_put(skb, len);

	cmd->opcode  = cpu_to_le16(CG2900_MC_VS_STREAM_CONTROL);
	cmd->plen    = BT_PARAM_LEN(len);
	cmd->command = command;

	/* one stream */
	cmd->n_streams  = 1;
	cmd->stream[0] = stream;

	cb_info->user = user;
	dev_dbg(BT_DEV, "New resp_state: WAITING\n");
	user->resp_state = WAITING;

	/* Send packet to controller */
	err = pf_data->write(pf_data, skb);
	if (err) {
		dev_err(BT_DEV, "Error %d occurred while transmitting skb\n",
			err);
		kfree_skb(skb);
		goto finished;
	}

	/* All commands in PG2 API returns one byte with extra status */
	err = receive_bt_cmd_complete(user,
				      CG2900_MC_VS_STREAM_CONTROL,
				      &vs_err, sizeof(vs_err));
	if (err)
		dev_err(BT_DEV,
			"VS_STREAM_CONTROL - failed with error 0x%02x\n",
			vs_err);

finished:
	dev_dbg(BT_DEV, "New resp_state: IDLE\n");
	user->resp_state = IDLE;
	return err;
}

/**
 * send_vs_create_stream() - Formats an sends a CG2900_MC_VS_CREATE_STREAM command.
 * @user:	Audio user this command belongs to.
 * @inport:	Stream id.
 * @outport:	Start/stop etc.
 * @order:	Activation order.
 *
 * Packs and sends a command packet and waits for the response. Must
 * be called with the bt_mutex held.
 *
 * Returns:
 *  0 if there is no error.
 *  -ENOMEM if not possible to allocate packet.
 *  -ECOMM if no response was received.
 *  -EIO for other errors.
 */
static int send_vs_create_stream(struct audio_user *user, u8 inport,
				 u8 outport, u8 order)
{
	int err = 0;
	struct sk_buff *skb;
	struct mc_vs_create_stream_cmd *cmd;
	s8 id;
	u8 vs_err;
	struct audio_cb_info *cb_info;
	struct audio_info *info;
	struct cg2900_user_data *pf_data;

	info = user->info;
	pf_data = dev_get_platdata(info->dev_bt);
	cb_info = cg2900_get_usr(pf_data);

	dev_dbg(BT_DEV,
		"send_vs_create_stream inport %d outport %d order %d\n",
		inport, outport, order);

	id = new_stream_id(info);
	if (id < 0) {
		dev_err(BT_DEV, "No free stream id\n");
		err = -EIO;
		goto finished;
	}

	skb = pf_data->alloc_skb(sizeof(*cmd), GFP_KERNEL);
	if (!skb) {
		dev_err(BT_DEV,
			"send_vs_create_stream: Could not allocate skb\n");
		err = -ENOMEM;
		goto finished_release_id;
	}

	cmd = (struct mc_vs_create_stream_cmd *)skb_put(skb, sizeof(*cmd));

	cmd->opcode  = cpu_to_le16(CG2900_MC_VS_CREATE_STREAM);
	cmd->plen    = BT_PARAM_LEN(sizeof(*cmd));
	cmd->id      = (u8)id;
	cmd->inport  = inport;
	cmd->outport = outport;
	cmd->order   = order;

	cb_info->user = user;
	dev_dbg(BT_DEV, "New resp_state: WAITING\n");
	user->resp_state = WAITING;

	/* Send packet to controller */
	err = pf_data->write(pf_data, skb);
	if (err) {
		dev_err(BT_DEV, "Error %d occurred while transmitting skb\n",
			err);
		kfree_skb(skb);
		goto finished_release_id;
	}

	/* All commands in PG2 API returns one byte with extra status */
	err = receive_bt_cmd_complete(user,
				      CG2900_MC_VS_CREATE_STREAM,
				      &vs_err, sizeof(vs_err));
	if (err) {
		dev_err(BT_DEV,
			"VS_CREATE_STREAM - failed with error 0x%02x\n",
			vs_err);
		goto finished_release_id;
	}

	err = id;
	goto finished;

finished_release_id:
	release_stream_id(info, id);
finished:
	dev_dbg(BT_DEV, "New resp_state: IDLE\n");
	user->resp_state = IDLE;
	return err;
}

/**
 * send_vs_port_cfg() - Formats an sends a CG2900_MC_VS_PORT_CONFIG command.
 * @user:	Audio user this command belongs to.
 * @port:	Port id to configure.
 * @cfg:	Pointer to specific configuration.
 * @cfglen:	Length of configuration.
 *
 * Packs and sends a command packet and waits for the response. Must
 * be called with the bt_mutex held.
 *
 * Returns:
 *  0 if there is no error.
 *  -ENOMEM if not possible to allocate packet.
 *  -ECOMM if no response was received.
 *  -EIO for other errors.
 */
static int send_vs_port_cfg(struct audio_user *user, u8 port,
			    const void *cfg, size_t cfglen)
{
	int err = 0;
	struct sk_buff *skb;
	struct mc_vs_port_cfg_cmd *cmd;
	void *ptr;
	u8 vs_err;
	struct audio_cb_info *cb_info;
	struct audio_info *info;
	struct cg2900_user_data *pf_data;

	info = user->info;
	pf_data = dev_get_platdata(info->dev_bt);
	cb_info = cg2900_get_usr(pf_data);

	dev_dbg(BT_DEV, "send_vs_port_cfg len %d\n", cfglen);

	skb = pf_data->alloc_skb(sizeof(*cmd) + cfglen, GFP_KERNEL);
	if (!skb) {
		dev_err(BT_DEV, "send_vs_port_cfg: Could not allocate skb\n");
		return -ENOMEM;
	}

	/* Fill in common part */
	cmd = (struct mc_vs_port_cfg_cmd *) skb_put(skb, sizeof(*cmd));
	cmd->opcode = cpu_to_le16(CG2900_MC_VS_PORT_CONFIG);
	cmd->plen = BT_PARAM_LEN(sizeof(*cmd) + cfglen);
	cmd->type = port;

	/* Copy specific configuration */
	ptr = skb_put(skb, cfglen);
	memcpy(ptr, cfg, cfglen);

	/* Send */
	cb_info->user = user;
	dev_dbg(BT_DEV, "New resp_state: WAITING\n");
	user->resp_state = WAITING;

	err = pf_data->write(pf_data, skb);
	if (err) {
		dev_err(BT_DEV, "Error %d occurred while transmitting skb\n",
			err);
		kfree_skb(skb);
		goto finished;
	}

	/* All commands in PG2 API returns one byte with extra status */
	err = receive_bt_cmd_complete(user, CG2900_MC_VS_PORT_CONFIG,
				      &vs_err, sizeof(vs_err));
	if (err)
		dev_err(BT_DEV, "VS_PORT_CONFIG - failed with error 0x%02x\n",
			vs_err);

finished:
	dev_dbg(BT_DEV, "New resp_state: IDLE\n");
	user->resp_state = IDLE;
	return err;
}

/**
 * set_dai_config_pg1() - Internal implementation of @cg2900_audio_set_dai_config for PG1 hardware.
 * @audio_user:	Pointer to audio user struct.
 * @config:	Pointer to the configuration to set.
 *
 * Sets the Digital Audio Interface (DAI) configuration for PG1
 * hardware. This is and internal function and basic
 * argument-verification should have been done by the caller.
 *
 * Returns:
 *  0 if there is no error.
 *  -EACCESS if port is not supported.
 *  -ENOMEM if not possible to allocate packet.
 *  -ECOMM if no response was received.
 *  -EIO for other errors.
 */
static int set_dai_config_pg1(struct audio_user *audio_user,
			      struct cg2900_dai_config *config)
{
	int err = 0;
	struct cg2900_dai_conf_i2s_pcm *i2s_pcm;
	struct sk_buff *skb = NULL;
	struct bt_vs_set_hw_cfg_cmd_i2s *i2s_cmd;
	struct bt_vs_set_hw_cfg_cmd_pcm *pcm_cmd;
	struct audio_info *info = audio_user->info;
	struct cg2900_user_data *pf_data = dev_get_platdata(info->dev_bt);
	struct audio_cb_info *cb_info = cg2900_get_usr(pf_data);

	dev_dbg(BT_DEV, "set_dai_config_pg1 port %d\n", config->port);

	/*
	 * Use mutex to assure that only ONE command is sent at any time on
	 * each channel.
	 */
	mutex_lock(&info->bt_mutex);

	/* Allocate the sk_buffer. The length is actually a max length since
	 * length varies depending on logical transport.
	 */
	skb = pf_data->alloc_skb(CG2900_BT_LEN_VS_SET_HARDWARE_CONFIG,
				 GFP_KERNEL);
	if (!skb) {
		dev_err(BT_DEV, "set_dai_config_pg1: Could not allocate skb\n");
		err = -ENOMEM;
		goto finished_unlock_mutex;
	}

	/* Fill in hci-command according to received configuration */
	switch (config->port) {
	case PORT_0_I2S:
		i2s_cmd = (struct bt_vs_set_hw_cfg_cmd_i2s *)
			skb_put(skb, sizeof(*i2s_cmd));

		i2s_cmd->opcode = cpu_to_le16(CG2900_BT_VS_SET_HARDWARE_CONFIG);
		i2s_cmd->plen   = BT_PARAM_LEN(sizeof(*i2s_cmd));

		i2s_cmd->vp_type = PORT_PROTOCOL_I2S;
		i2s_cmd->port_id = 0x00; /* First/only I2S port */
		i2s_cmd->half_period = config->conf.i2s.half_period;

		i2s_cmd->master_slave = mc_i2s_role(config->conf.i2s.mode);

		/* Store the new configuration */
		mutex_lock(&info->management_mutex);
		memcpy(&info->i2s_config, &config->conf.i2s,
		       sizeof(config->conf.i2s));
		info->i2s_config_known = true;
		mutex_unlock(&info->management_mutex);
		break;

	case PORT_1_I2S_PCM:
		pcm_cmd = (struct bt_vs_set_hw_cfg_cmd_pcm *)
			skb_put(skb, sizeof(*pcm_cmd));

		pcm_cmd->opcode = cpu_to_le16(CG2900_BT_VS_SET_HARDWARE_CONFIG);
		pcm_cmd->plen   = BT_PARAM_LEN(sizeof(*pcm_cmd));

		i2s_pcm = &config->conf.i2s_pcm;

		/*
		 * PG1 chips don't support I2S over the PCM/I2S bus,
		 * and PG2 chips don't use this command
		 */
		if (i2s_pcm->protocol != PORT_PROTOCOL_PCM) {
			dev_err(BT_DEV,
				"I2S not supported over the PCM/I2S bus\n");
			err = -EACCES;
			goto error_handling_free_skb;
		}

		pcm_cmd->vp_type = PORT_PROTOCOL_PCM;
		pcm_cmd->port_id = 0x00; /* First/only PCM port */

		HWCONFIG_PCM_SET_MODE(pcm_cmd, mc_pcm_role(i2s_pcm->mode));

		HWCONFIG_PCM_SET_DIR(pcm_cmd, 0, i2s_pcm->slot_0_dir);
		HWCONFIG_PCM_SET_DIR(pcm_cmd, 1, i2s_pcm->slot_1_dir);
		HWCONFIG_PCM_SET_DIR(pcm_cmd, 2, i2s_pcm->slot_2_dir);
		HWCONFIG_PCM_SET_DIR(pcm_cmd, 3, i2s_pcm->slot_3_dir);

		pcm_cmd->bit_clock = i2s_pcm->clk;
		pcm_cmd->frame_len =
			cpu_to_le16(get_fs_duration(i2s_pcm->duration));

		/* Store the new configuration */
		mutex_lock(&info->management_mutex);
		memcpy(&info->i2s_pcm_config, &config->conf.i2s_pcm,
		       sizeof(config->conf.i2s_pcm));
		info->i2s_pcm_config_known = true;
		mutex_unlock(&info->management_mutex);
		break;

	default:
		dev_err(BT_DEV, "Unknown port configuration %d\n",
			config->port);
		err = -EACCES;
		goto error_handling_free_skb;
	};

	cb_info->user = audio_user;
	dev_dbg(BT_DEV, "New resp_state: WAITING\n");
	audio_user->resp_state = WAITING;

	/* Send packet to controller */
	err = pf_data->write(pf_data, skb);
	if (err) {
		dev_err(BT_DEV, "Error %d occurred while transmitting skb\n",
			err);
		goto error_handling_free_skb;
	}

	err = receive_bt_cmd_complete(audio_user,
				      CG2900_BT_VS_SET_HARDWARE_CONFIG,
				      NULL, 0);

	goto finished_unlock_mutex;

error_handling_free_skb:
	kfree_skb(skb);
finished_unlock_mutex:
	dev_dbg(BT_DEV, "New resp_state: IDLE\n");
	audio_user->resp_state = IDLE;
	mutex_unlock(&info->bt_mutex);
	return err;
}

/**
 * set_dai_config_pg2() - Internal implementation of @cg2900_audio_set_dai_config for PG2 hardware.
 * @audio_user:	Pointer to audio user struct.
 * @config:	Pointer to the configuration to set.
 *
 * Sets the Digital Audio Interface (DAI) configuration for PG2
 * hardware. This is an internal function and basic
 * argument-verification should have been done by the caller.
 *
 * Returns:
 *  0 if there is no error.
 *  -EACCESS if port is not supported.
 *  -ENOMEM if not possible to allocate packet.
 *  -ECOMM if no response was received.
 *  -EIO for other errors.
 */
static int set_dai_config_pg2(struct audio_user *audio_user,
			      struct cg2900_dai_config *config)
{
	int err = 0;
	struct cg2900_dai_conf_i2s *i2s;
	struct cg2900_dai_conf_i2s_pcm *i2s_pcm;

	struct mc_vs_port_cfg_i2s i2s_cfg;
	struct mc_vs_port_cfg_pcm_i2s pcm_cfg;
	struct audio_info *info = audio_user->info;

	dev_dbg(BT_DEV, "set_dai_config_pg2 port %d\n", config->port);

	/*
	 * Use mutex to assure that only ONE command is sent at any time on
	 * each channel.
	 */
	mutex_lock(&info->bt_mutex);

	switch (config->port) {
	case PORT_0_I2S:
		i2s = &config->conf.i2s;

		memset(&i2s_cfg, 0, sizeof(i2s_cfg)); /* just to be safe  */

		/* master/slave */
		PORTCFG_I2S_SET_ROLE(i2s_cfg, mc_i2s_role(i2s->mode));

		PORTCFG_I2S_SET_HALFPERIOD(i2s_cfg, i2s->half_period);
		PORTCFG_I2S_SET_CHANNELS(i2s_cfg,
			mc_i2s_channel_select(i2s->channel_sel));
		PORTCFG_I2S_SET_SRATE(i2s_cfg,
			mc_i2s_sample_rate(i2s->sample_rate));
		switch (i2s->word_width) {
		case WORD_WIDTH_16:
			PORTCFG_I2S_SET_WORDLEN(i2s_cfg, CG2900_MC_I2S_WORD_16);
			break;
		case WORD_WIDTH_32:
			PORTCFG_I2S_SET_WORDLEN(i2s_cfg, CG2900_MC_I2S_WORD_32);
			break;
		}

		/* Store the new configuration */
		mutex_lock(&info->management_mutex);
		memcpy(&(info->i2s_config), &(config->conf.i2s),
		       sizeof(config->conf.i2s));
		info->i2s_config_known = true;
		mutex_unlock(&info->management_mutex);

		/* Send */
		err = send_vs_port_cfg(audio_user, CG2900_MC_PORT_I2S,
				       &i2s_cfg, sizeof(i2s_cfg));
		break;

	case PORT_1_I2S_PCM:
		i2s_pcm = &config->conf.i2s_pcm;

		memset(&pcm_cfg, 0, sizeof(pcm_cfg)); /* just to be safe  */

		/* master/slave */
		PORTCFG_PCM_SET_ROLE(pcm_cfg, mc_pcm_role(i2s_pcm->mode));

		/* set direction for all 4 slots */
		PORTCFG_PCM_SET_DIR(pcm_cfg, 0, i2s_pcm->slot_0_dir);
		PORTCFG_PCM_SET_DIR(pcm_cfg, 1, i2s_pcm->slot_1_dir);
		PORTCFG_PCM_SET_DIR(pcm_cfg, 2, i2s_pcm->slot_2_dir);
		PORTCFG_PCM_SET_DIR(pcm_cfg, 3, i2s_pcm->slot_3_dir);

		/* set used SCO slots, other use cases not supported atm */
		PORTCFG_PCM_SET_SCO_USED(pcm_cfg, 0, i2s_pcm->slot_0_used);
		PORTCFG_PCM_SET_SCO_USED(pcm_cfg, 1, i2s_pcm->slot_1_used);
		PORTCFG_PCM_SET_SCO_USED(pcm_cfg, 2, i2s_pcm->slot_2_used);
		PORTCFG_PCM_SET_SCO_USED(pcm_cfg, 3, i2s_pcm->slot_3_used);

		/* slot starts */
		pcm_cfg.slot_start[0] = i2s_pcm->slot_0_start;
		pcm_cfg.slot_start[1] = i2s_pcm->slot_1_start;
		pcm_cfg.slot_start[2] = i2s_pcm->slot_2_start;
		pcm_cfg.slot_start[3] = i2s_pcm->slot_3_start;

		/* audio/voice sample-rate ratio */
		PORTCFG_PCM_SET_RATIO(pcm_cfg, i2s_pcm->ratio);

		/* PCM or I2S mode */
		PORTCFG_PCM_SET_MODE(pcm_cfg, i2s_pcm->protocol);

		pcm_cfg.frame_len = i2s_pcm->duration;

		PORTCFG_PCM_SET_BITCLK(pcm_cfg, i2s_pcm->clk);
		PORTCFG_PCM_SET_SRATE(pcm_cfg,
			mc_pcm_sample_rate(i2s_pcm->sample_rate));

		/* Store the new configuration */
		mutex_lock(&info->management_mutex);
		memcpy(&(info->i2s_pcm_config), &(config->conf.i2s_pcm),
		       sizeof(config->conf.i2s_pcm));
		info->i2s_pcm_config_known = true;
		mutex_unlock(&info->management_mutex);

		/* Send */
		err = send_vs_port_cfg(audio_user, CG2900_MC_PORT_PCM_I2S,
				       &pcm_cfg, sizeof(pcm_cfg));
		break;

	default:
		dev_err(BT_DEV, "Unknown port configuration %d\n",
			config->port);
		err = -EACCES;
	};

	mutex_unlock(&info->bt_mutex);
	return err;
}

/**
 * struct i2s_fm_stream_config_priv - Helper struct for stream i2s-fm streams.
 * @fm_config:	FM endpoint configuration.
 * @rx:		true for FM-RX, false for FM-TX.
 */
struct i2s_fm_stream_config_priv {
	struct cg2900_endpoint_config_fm	*fm_config;
	bool					rx;

};

/**
 * config_i2s_fm_stream() - Callback for @send_vs_session_config.
 * @info:	Audio info structure.
 * @_priv:	Pointer to a @i2s_fm_stream_config_priv struct.
 * @cfg:	Pointer to stream config block in command packet.
 *
 * Fills in stream configuration for I2S-FM RX/TX.
 */

static void config_i2s_fm_stream(struct audio_info *info, void *_priv,
				 struct session_config_stream *cfg)
{
	struct i2s_fm_stream_config_priv *priv = _priv;
	struct session_config_vport *fm;
	struct session_config_vport *i2s;

	cfg->media_type = CG2900_BT_SESSION_MEDIA_TYPE_AUDIO;

	if (info->i2s_config.channel_sel == CHANNEL_SELECTION_BOTH)
		SESSIONCFG_SET_CHANNELS(cfg, CG2900_BT_MEDIA_CONFIG_STEREO);
	else
		SESSIONCFG_SET_CHANNELS(cfg, CG2900_BT_MEDIA_CONFIG_MONO);

	SESSIONCFG_I2S_SET_SRATE(cfg,
		session_config_sample_rate(priv->fm_config->sample_rate));

	cfg->codec_type = CG2900_CODEC_TYPE_NONE;
	/* codec mode and parameters not used  */

	if (priv->rx) {
		fm  = &cfg->inport;  /* FM is input */
		i2s = &cfg->outport; /* I2S is output */
	} else {
		i2s = &cfg->inport;  /* I2S is input */
		fm  = &cfg->outport; /* FM is output */
	}

	fm->type = CG2900_BT_VP_TYPE_FM;

	i2s->type = CG2900_BT_VP_TYPE_I2S;
	i2s->i2s.index   = CG2900_BT_SESSION_I2S_INDEX_I2S;
	i2s->i2s.channel = info->i2s_config.channel_sel;
}

/**
 * conn_start_i2s_to_fm_rx() - Start an audio stream connecting FM RX to I2S.
 * @audio_user:		Audio user to check for.
 * @stream_handle:	[out] Pointer where to store the stream handle.
 *
 * This function sets up an FM RX to I2S stream.
 * It does this by first setting the output mode and then the configuration of
 * the External Sample Rate Converter.
 *
 * Returns:
 *   0 if there is no error.
 *   -ECOMM if no response was received.
 *   -ENOMEM upon allocation errors.
 *   -EIO for other errors.
 */
static int conn_start_i2s_to_fm_rx(struct audio_user *audio_user,
				   unsigned int *stream_handle)
{
	int err = 0;
	union cg2900_endpoint_config_union *fm_config;
	struct audio_info *info = audio_user->info;

	dev_dbg(FM_DEV, "conn_start_i2s_to_fm_rx\n");

	fm_config = find_endpoint(ENDPOINT_FM_RX, &info->endpoints);
	if (!fm_config) {
		dev_err(FM_DEV, "FM RX not configured before stream start\n");
		return -EIO;
	}

	if (!(info->i2s_config_known)) {
		dev_err(FM_DEV,
			"I2S DAI not configured before stream start\n");
		return -EIO;
	}

	/*
	 * Use mutex to assure that only ONE command is sent at any
	 * time on each channel.
	 */
	mutex_lock(&info->fm_mutex);
	mutex_lock(&info->bt_mutex);

	/*
	 * Now set the output mode of the External Sample Rate Converter by
	 * sending HCI_Write command with AUP_EXT_SetMode.
	 */
	err = send_fm_write_1_param(audio_user,
				    CG2900_FM_CMD_ID_AUP_EXT_SET_MODE,
				    CG2900_FM_CMD_AUP_EXT_SET_MODE_PARALLEL);
	if (err)
		goto finished_unlock_mutex;

	/*
	 * Now configure the External Sample Rate Converter by sending
	 * HCI_Write command with AUP_EXT_SetControl.
	 */
	err = send_fm_write_1_param(
		audio_user, CG2900_FM_CMD_ID_AUP_EXT_SET_CTRL,
		fm_get_conversion(fm_config->fm.sample_rate));
	if (err)
		goto finished_unlock_mutex;

	/* Set up the stream */
	if (info->revision == CHIP_REV_PG1) {
		struct i2s_fm_stream_config_priv stream_priv;

		/* Now send HCI_VS_Set_Session_Configuration command */
		stream_priv.fm_config = &fm_config->fm;
		stream_priv.rx = true;
		err = send_vs_session_config(audio_user, config_i2s_fm_stream,
					     &stream_priv);
	} else {
		struct mc_vs_port_cfg_fm fm_cfg;

		memset(&fm_cfg, 0, sizeof(fm_cfg));

		/* Configure port FM RX */
		/* Expects 0-3 - same as user API - so no conversion needed */
		PORTCFG_FM_SET_SRATE(fm_cfg, (u8)fm_config->fm.sample_rate);

		err = send_vs_port_cfg(audio_user, CG2900_MC_PORT_FM_RX_1,
				       &fm_cfg, sizeof(fm_cfg));
		if (err)
			goto finished_unlock_mutex;

		/* CreateStream */
		err = send_vs_create_stream(audio_user,
					    CG2900_MC_PORT_FM_RX_1,
					    CG2900_MC_PORT_I2S,
					    0); /* chip doesn't care */
	}

	if (err < 0)
		goto finished_unlock_mutex;

	/* Store the stream handle (used for start and stop stream) */
	*stream_handle = (u8)err;
	dev_dbg(FM_DEV, "stream_handle set to %d\n", *stream_handle);

	/* Now start the stream */
	if (info->revision == CHIP_REV_PG1)
		err = send_vs_session_ctrl(audio_user, *stream_handle,
					   CG2900_BT_SESSION_START);
	else
		err = send_vs_stream_ctrl(audio_user, *stream_handle,
					  CG2900_MC_STREAM_START);
	/*Let's delete a stream.*/
	if (err < 0) {
		dev_dbg(BT_DEV, "Could not start a stream.");
		(void)send_vs_delete_stream(audio_user, *stream_handle);
	}

finished_unlock_mutex:
	dev_dbg(FM_DEV, "New resp_state: IDLE\n");
	audio_user->resp_state = IDLE;
	mutex_unlock(&info->bt_mutex);
	mutex_unlock(&info->fm_mutex);
	return err;
}

/**
 * conn_start_i2s_to_fm_tx() - Start an audio stream connecting FM TX to I2S.
 * @audio_user:		Audio user to check for.
 * @stream_handle:	[out] Pointer where to store the stream handle.
 *
 * This function sets up an I2S to FM TX stream.
 * It does this by first setting the Audio Input source and then setting the
 * configuration and input source of BT sample rate converter.
 *
 * Returns:
 *   0 if there is no error.
 *   -ECOMM if no response was received.
 *   -ENOMEM upon allocation errors.
 *   -EIO for other errors.
 */
static int conn_start_i2s_to_fm_tx(struct audio_user *audio_user,
				   unsigned int *stream_handle)
{
	int err = 0;
	union cg2900_endpoint_config_union *fm_config;
	struct audio_info *info = audio_user->info;

	dev_dbg(FM_DEV, "conn_start_i2s_to_fm_tx\n");

	fm_config = find_endpoint(ENDPOINT_FM_TX, &info->endpoints);
	if (!fm_config) {
		dev_err(FM_DEV, "FM TX not configured before stream start\n");
		return -EIO;
	}

	if (!(info->i2s_config_known)) {
		dev_err(FM_DEV,
			"I2S DAI not configured before stream start\n");
		return -EIO;
	}

	/*
	 * Use mutex to assure that only ONE command is sent at any time
	 * on each channel.
	 */
	mutex_lock(&info->fm_mutex);
	mutex_lock(&info->bt_mutex);

	/*
	 * Select Audio Input Source by sending HCI_Write command with
	 * AIP_SetMode.
	 */
	dev_dbg(FM_DEV, "FM: AIP_SetMode\n");
	err = send_fm_write_1_param(audio_user, CG2900_FM_CMD_ID_AIP_SET_MODE,
				    CG2900_FM_CMD_AIP_SET_MODE_INPUT_DIG);
	if (err)
		goto finished_unlock_mutex;

	/*
	 * Now configure the BT sample rate converter by sending HCI_Write
	 * command with AIP_BT_SetControl.
	 */
	dev_dbg(FM_DEV, "FM: AIP_BT_SetControl\n");
	err = send_fm_write_1_param(
		audio_user, CG2900_FM_CMD_ID_AIP_BT_SET_CTRL,
		fm_get_conversion(fm_config->fm.sample_rate));
	if (err)
		goto finished_unlock_mutex;

	/*
	 * Now set input of the BT sample rate converter by sending HCI_Write
	 * command with AIP_BT_SetMode.
	 */
	dev_dbg(FM_DEV, "FM: AIP_BT_SetMode\n");
	err = send_fm_write_1_param(audio_user,
				    CG2900_FM_CMD_ID_AIP_BT_SET_MODE,
				    CG2900_FM_CMD_AIP_BT_SET_MODE_INPUT_PAR);
	if (err)
		goto finished_unlock_mutex;

	/* Set up the stream */
	if (info->revision == CHIP_REV_PG1) {
		struct i2s_fm_stream_config_priv stream_priv;

		/* Now send HCI_VS_Set_Session_Configuration command */
		stream_priv.fm_config = &fm_config->fm;
		stream_priv.rx = false;
		err = send_vs_session_config(audio_user, config_i2s_fm_stream,
					     &stream_priv);
	} else {
		struct mc_vs_port_cfg_fm fm_cfg;

		memset(&fm_cfg, 0, sizeof(fm_cfg));

		/* Configure port FM TX */
		/* Expects 0-3 - same as user API - so no conversion needed */
		PORTCFG_FM_SET_SRATE(fm_cfg, (u8)fm_config->fm.sample_rate);

		err = send_vs_port_cfg(audio_user, CG2900_MC_PORT_FM_TX,
				       &fm_cfg, sizeof(fm_cfg));
		if (err)
			goto finished_unlock_mutex;

		/* CreateStream */
		err = send_vs_create_stream(audio_user,
					    CG2900_MC_PORT_I2S,
					    CG2900_MC_PORT_FM_TX,
					    0); /* chip doesn't care */
	}

	if (err < 0)
		goto finished_unlock_mutex;

	/* Store the stream handle (used for start and stop stream) */
	*stream_handle = (u8)err;
	dev_dbg(FM_DEV, "stream_handle set to %d\n", *stream_handle);

	/* Now start the stream */
	if (info->revision == CHIP_REV_PG1)
		err = send_vs_session_ctrl(audio_user, *stream_handle,
					   CG2900_BT_SESSION_START);
	else
		err = send_vs_stream_ctrl(audio_user, *stream_handle,
					  CG2900_MC_STREAM_START);
	/* Let's delete and release stream.*/
	if (err < 0) {
		dev_dbg(BT_DEV, "Could not start a stream.");
		(void)send_vs_delete_stream(audio_user, *stream_handle);
	}

finished_unlock_mutex:
	dev_dbg(FM_DEV, "New resp_state: IDLE\n");
	audio_user->resp_state = IDLE;
	mutex_unlock(&info->bt_mutex);
	mutex_unlock(&info->fm_mutex);
	return err;
}

/**
 * config_pcm_sco_stream() - Callback for @send_vs_session_config.
 * @info:	Audio info structure.
 * @_priv:	Pointer to a @cg2900_endpoint_config_sco_in_out struct.
 * @cfg:	Pointer to stream config block in command packet.
 *
 * Fills in stream configuration for PCM-SCO.
 */
static void config_pcm_sco_stream(struct audio_info *info, void *_priv,
				  struct session_config_stream *cfg)
{
	struct cg2900_endpoint_config_sco_in_out *sco_ep = _priv;

	cfg->media_type = CG2900_BT_SESSION_MEDIA_TYPE_AUDIO;

	SESSIONCFG_SET_CHANNELS(cfg, CG2900_BT_MEDIA_CONFIG_MONO);
	SESSIONCFG_I2S_SET_SRATE(cfg,
		session_config_sample_rate(sco_ep->sample_rate));

	cfg->codec_type = CG2900_CODEC_TYPE_NONE;
	/* codec mode and parameters not used  */

	cfg->inport.type = CG2900_BT_VP_TYPE_BT_SCO;
	cfg->inport.sco.acl_handle = cpu_to_le16(DEFAULT_SCO_HANDLE);

	cfg->outport.type = CG2900_BT_VP_TYPE_PCM;
	cfg->outport.pcm.index = CG2900_BT_SESSION_PCM_INDEX_PCM_I2S;

	SESSIONCFG_PCM_SET_USED(cfg->outport, 0,
				info->i2s_pcm_config.slot_0_used);
	SESSIONCFG_PCM_SET_USED(cfg->outport, 1,
				info->i2s_pcm_config.slot_1_used);
	SESSIONCFG_PCM_SET_USED(cfg->outport, 2,
				info->i2s_pcm_config.slot_2_used);
	SESSIONCFG_PCM_SET_USED(cfg->outport, 3,
				info->i2s_pcm_config.slot_3_used);

	cfg->outport.pcm.slot_start[0] =
		info->i2s_pcm_config.slot_0_start;
	cfg->outport.pcm.slot_start[1] =
		info->i2s_pcm_config.slot_1_start;
	cfg->outport.pcm.slot_start[2] =
		info->i2s_pcm_config.slot_2_start;
	cfg->outport.pcm.slot_start[3] =
		info->i2s_pcm_config.slot_3_start;
}

/**
 * conn_start_pcm_to_sco() - Start an audio stream connecting Bluetooth (e)SCO to PCM_I2S.
 * @audio_user:		Audio user to check for.
 * @stream_handle:	[out] Pointer where to store the stream handle.
 *
 * This function sets up a BT to_from PCM_I2S stream. It does this by
 * first setting the Session configuration and then starting the Audio
 * Stream.
 *
 * Returns:
 *   0 if there is no error.
 *   -ECOMM if no response was received.
 *   -ENOMEM upon allocation errors.
 *   Errors from @cg2900_write
 *   -EIO for other errors.
 */
static int conn_start_pcm_to_sco(struct audio_user *audio_user,
				 unsigned int *stream_handle)
{
	int err = 0;
	union cg2900_endpoint_config_union *bt_config;
	struct audio_info *info = audio_user->info;

	dev_dbg(BT_DEV, "conn_start_pcm_to_sco\n");

	bt_config = find_endpoint(ENDPOINT_BT_SCO_INOUT, &info->endpoints);
	if (!bt_config) {
		dev_err(BT_DEV, "BT not configured before stream start\n");
		return -EIO;
	}

	if (!(info->i2s_pcm_config_known)) {
		dev_err(BT_DEV,
			"I2S_PCM DAI not configured before stream start\n");
		return -EIO;
	}

	/*
	 * Use mutex to assure that only ONE command is sent at any time on each
	 * channel.
	 */
	mutex_lock(&info->bt_mutex);

	/* Set up the stream */
	if (info->revision == CHIP_REV_PG1) {
		err = send_vs_session_config(audio_user, config_pcm_sco_stream,
					     &bt_config->sco);
	} else {
		struct mc_vs_port_cfg_sco sco_cfg;

		/* zero codec params etc */
		memset(&sco_cfg, 0, sizeof(sco_cfg));
		sco_cfg.acl_id = DEFAULT_SCO_HANDLE;
		PORTCFG_SCO_SET_WBS(sco_cfg, 0); /* No WBS yet */
		PORTCFG_SCO_SET_CODEC(sco_cfg, CG2900_CODEC_TYPE_NONE);

		err = send_vs_port_cfg(audio_user, CG2900_MC_PORT_BT_SCO,
				       &sco_cfg, sizeof(sco_cfg));
		if (err)
			goto finished_unlock_mutex;

		/* CreateStream */
		err = send_vs_create_stream(audio_user,
					    CG2900_MC_PORT_PCM_I2S,
					    CG2900_MC_PORT_BT_SCO,
					    0); /* chip doesn't care */
	}

	if (err < 0)
		goto finished_unlock_mutex;

	/* Store the stream handle (used for start and stop stream) */
	*stream_handle = (u8)err;
	dev_dbg(BT_DEV, "stream_handle set to %d\n", *stream_handle);

	/* Now start the stream */
	if (info->revision == CHIP_REV_PG1)
		err = send_vs_session_ctrl(audio_user, *stream_handle,
					   CG2900_BT_SESSION_START);
	else
		err = send_vs_stream_ctrl(audio_user, *stream_handle,
					  CG2900_MC_STREAM_START);
	/* Let's delete and release stream.*/
	if (err < 0) {
		dev_dbg(BT_DEV, "Could not start a stream.");
		(void)send_vs_delete_stream(audio_user, *stream_handle);
	}

finished_unlock_mutex:
	dev_dbg(BT_DEV, "New resp_state: IDLE\n");
	audio_user->resp_state = IDLE;
	mutex_unlock(&info->bt_mutex);
	return err;
}

/**
 * conn_stop_stream() - Stops an audio stream defined by @stream_handle.
 * @audio_user:		Audio user to check for.
 * @stream_handle:	Handle of the audio stream.
 *
 * This function is used to stop an audio stream defined by a stream
 * handle. It does this by first stopping the stream and then
 * resetting the session/stream.
 *
 * Returns:
 *   0 if there is no error.
 *   -ECOMM if no response was received.
 *   -ENOMEM upon allocation errors.
 *   Errors from @cg2900_write.
 *   -EIO for other errors.
 */
static int conn_stop_stream(struct audio_user *audio_user,
			    unsigned int stream_handle)
{
	int err = 0;
	struct audio_info *info = audio_user->info;

	dev_dbg(BT_DEV, "conn_stop_stream handle %d\n", stream_handle);

	/*
	 * Use mutex to assure that only ONE command is sent at any
	 * time on each channel.
	 */
	mutex_lock(&info->bt_mutex);

	/* Now stop the stream */
	if (info->revision == CHIP_REV_PG1)
		err = send_vs_session_ctrl(audio_user, stream_handle,
					   CG2900_BT_SESSION_STOP);
	else
		err = send_vs_stream_ctrl(audio_user, stream_handle,
					  CG2900_MC_STREAM_STOP);
	if (err)
		goto finished_unlock_mutex;

	err = send_vs_delete_stream(audio_user, stream_handle);

finished_unlock_mutex:
	dev_dbg(BT_DEV, "New resp_state: IDLE\n");
	audio_user->resp_state = IDLE;
	mutex_unlock(&info->bt_mutex);
	return err;
}

/**
 * cg2900_audio_get_devices() - Returns connected CG2900 Audio devices.
 * @devices:	Array of CG2900 Audio devices.
 * @size:	Max number of devices in array.
 *
 * Returns:
 *   0 if no devices exist.
 *   > 0 is the number of devices inserted in the list.
 *   -EINVAL upon bad input parameter.
 */
int cg2900_audio_get_devices(struct device *devices[], __u8 size)
{
	struct list_head *cursor;
	struct audio_info *tmp;
	int i = 0;

	if (!size) {
		pr_err("No space to insert devices into list\n");
		return 0;
	}

	if (!devices) {
		pr_err("NULL submitted as devices array\n");
		return -EINVAL;
	}

	/*
	 * Go through and store the devices. If NULL is supplied for dev
	 * just return first device found.
	 */
	list_for_each(cursor, &cg2900_audio_devices) {
		tmp = list_entry(cursor, struct audio_info, list);
		devices[i] = tmp->parent;
		i++;
		if (i == size)
			break;
	}
	return i;
}
EXPORT_SYMBOL_GPL(cg2900_audio_get_devices);

/**
 * cg2900_audio_open() - Opens a session to the ST-Ericsson CG2900 Audio control interface.
 * @session:	[out] Address where to store the session identifier.
 *		Allocated by caller, must not be NULL.
 * @parent:	Parent device representing the CG2900 controller connected.
 *		If NULL is supplied the first available device is used.
 *
 * Returns:
 *   0 if there is no error.
 *   -EACCES if no info structure can be found.
 *   -EINVAL upon bad input parameter.
 *   -ENOMEM upon allocation failure.
 *   -EMFILE if no more user session could be opened.
 *   -EIO upon failure to register to CG2900.
 *   Error codes from get_info.
 */
int cg2900_audio_open(unsigned int *session, struct device *parent)
{
	int err = 0;
	int i;
	struct audio_info *info;
	struct cg2900_user_data *pf_data_bt;
	struct cg2900_user_data *pf_data_fm;

	pr_debug("cg2900_audio_open");

	info = get_info(parent);
	if (!info) {
		pr_err("No audio info exist");
		return -EACCES;
	} else if (IS_ERR(info))
		return PTR_ERR(info);

	if (!session) {
		pr_err("NULL supplied as session");
		return -EINVAL;
	}

	mutex_lock(&info->management_mutex);

	*session = 0;

	/*
	 * First find a free session to use and allocate the session structure.
	 */
	for (i = FIRST_USER;
	     i < MAX_NBR_OF_USERS && cg2900_audio_sessions[i];
	     i++)
		; /* Just loop until found or end reached */

	if (i >= MAX_NBR_OF_USERS) {
		pr_err("Couldn't find free user");
		err = -EMFILE;
		goto finished;
	}

	cg2900_audio_sessions[i] =
		kzalloc(sizeof(*(cg2900_audio_sessions[0])), GFP_KERNEL);
	if (!cg2900_audio_sessions[i]) {
		pr_err("Could not allocate user");
		err = -ENOMEM;
		goto finished;
	}
	pr_debug("Found free session %d", i);
	*session = i;
	info->nbr_of_users_active++;

	cg2900_audio_sessions[*session]->resp_state = IDLE;
	cg2900_audio_sessions[*session]->session = *session;
	cg2900_audio_sessions[*session]->info = info;

	pf_data_bt = dev_get_platdata(info->dev_bt);
	pf_data_fm = dev_get_platdata(info->dev_fm);

	if (info->nbr_of_users_active == 1) {
		struct cg2900_rev_data rev_data;

		/*
		 * First user so register to CG2900 Core.
		 * First the BT audio device.
		 */
		err = pf_data_bt->open(pf_data_bt);
		if (err) {
			dev_err(BT_DEV, "Failed to open BT audio channel\n");
			goto error_handling;
		}

		/* Then the FM audio device */
		err = pf_data_fm->open(pf_data_fm);
		if (err) {
			dev_err(FM_DEV, "Failed to open FM audio channel\n");
			goto error_handling;
		}

		/* Read chip revision data */
		if (!pf_data_bt->get_local_revision(pf_data_bt, &rev_data)) {
			pr_err("Couldn't retrieve revision data");
			err = -EIO;
			goto error_handling;
		}

		/* Decode revision data */
		switch (rev_data.revision) {
		case CG2900_PG1_REV:
		case CG2900_PG1_SPECIAL_REV:
			info->revision = CHIP_REV_PG1;
			break;

		case CG2900_PG2_REV:
			info->revision = CHIP_REV_PG2;
			break;

		default:
			pr_err("Chip rev 0x%04X sub 0x%04X not supported",
			       rev_data.revision, rev_data.sub_version);
			err = -EIO;
			goto error_handling;
		}

		info->state = OPENED;
	}

	pr_info("Session %d opened", *session);

	goto finished;

error_handling:
	if (pf_data_fm->opened)
		pf_data_fm->close(pf_data_fm);
	if (pf_data_bt->opened)
		pf_data_bt->close(pf_data_bt);
	info->nbr_of_users_active--;
	kfree(cg2900_audio_sessions[*session]);
	cg2900_audio_sessions[*session] = NULL;
finished:
	mutex_unlock(&info->management_mutex);
	return err;
}
EXPORT_SYMBOL_GPL(cg2900_audio_open);

/**
 * cg2900_audio_close() - Closes an opened session to the ST-Ericsson CG2900 audio control interface.
 * @session:	[in_out] Pointer to session identifier to close.
 *		Will be 0 after this call.
 *
 * Returns:
 *   0 if there is no error.
 *   -EINVAL upon bad input parameter.
 *   -EIO if driver has not been opened.
 *   -EACCES if session has not opened.
 */
int cg2900_audio_close(unsigned int *session)
{
	int err = 0;
	struct audio_user *audio_user;
	struct audio_info *info;
	struct cg2900_user_data *pf_data_bt;
	struct cg2900_user_data *pf_data_fm;

	pr_debug("cg2900_audio_close");

	if (!session) {
		pr_err("NULL pointer supplied");
		return -EINVAL;
	}

	audio_user = get_session_user(*session);
	if (!audio_user) {
		pr_err("Invalid session ID");
		return -EINVAL;
	}

	info = audio_user->info;

	if (info->state != OPENED) {
		dev_err(BT_DEV, "Audio driver not open\n");
		return -EIO;
	}

	mutex_lock(&info->management_mutex);

	pf_data_bt = dev_get_platdata(info->dev_bt);
	pf_data_fm = dev_get_platdata(info->dev_fm);

	if (!cg2900_audio_sessions[*session]) {
		dev_err(BT_DEV, "Session %d not opened\n", *session);
		err = -EACCES;
		goto err_unlock_mutex;
	}

	kfree(cg2900_audio_sessions[*session]);
	cg2900_audio_sessions[*session] = NULL;

	info->nbr_of_users_active--;
	if (info->nbr_of_users_active == 0) {
		/* No more sessions open. Close channels */
		pf_data_fm->close(pf_data_fm);
		pf_data_bt->close(pf_data_bt);
		info->state = CLOSED;
	}

	dev_info(BT_DEV, "Session %d closed\n", *session);

	*session = 0;

err_unlock_mutex:
	mutex_unlock(&info->management_mutex);
	return err;
}
EXPORT_SYMBOL_GPL(cg2900_audio_close);

/**
 * cg2900_audio_set_dai_config() -  Sets the Digital Audio Interface configuration.
 * @session:	Session identifier this call is related to.
 * @config:	Pointer to the configuration to set.
 *		Allocated by caller, must not be NULL.
 *
 * Sets the Digital Audio Interface (DAI) configuration. The DAI is the external
 * interface between the combo chip and the platform.
 * For example the PCM or I2S interface.
 *
 * Returns:
 *   0 if there is no error.
 *   -EINVAL upon bad input parameter.
 *   -EIO if driver has not been opened.
 *   -ENOMEM upon allocation failure.
 *   -EACCES if trying to set unsupported configuration.
 *   Errors from @receive_bt_cmd_complete.
 */
int cg2900_audio_set_dai_config(unsigned int session,
				struct cg2900_dai_config *config)
{
	int err = 0;
	struct audio_user *audio_user;
	struct audio_info *info;

	pr_debug("cg2900_audio_set_dai_config session %d", session);

	audio_user = get_session_user(session);
	if (!audio_user)
		return -EINVAL;

	info = audio_user->info;

	if (info->state != OPENED) {
		dev_err(BT_DEV, "Audio driver not open\n");
		return -EIO;
	}

	/* Different commands are used for PG1 and PG2 */
	if (info->revision == CHIP_REV_PG1)
		err = set_dai_config_pg1(audio_user, config);
	else if (info->revision == CHIP_REV_PG2)
		err = set_dai_config_pg2(audio_user, config);

	return err;
}
EXPORT_SYMBOL_GPL(cg2900_audio_set_dai_config);

/**
 * cg2900_audio_get_dai_config() - Gets the current Digital Audio Interface configuration.
 * @session:	Session identifier this call is related to.
 * @config:	[out] Pointer to the configuration to get.
 *		Allocated by caller, must not be NULL.
 *
 * Gets the current Digital Audio Interface configuration. Currently this method
 * can only be called after some one has called
 * cg2900_audio_set_dai_config(), there is today no way of getting
 * the static settings file parameters from this method.
 * Note that the @port parameter within @config must be set when calling this
 * function so that the ST-Ericsson CG2900 Audio driver will know which
 * configuration to return.
 *
 * Returns:
 *   0 if there is no error.
 *   -EINVAL upon bad input parameter.
 *   -EIO if driver has not been opened or configuration has not been set.
 */
int cg2900_audio_get_dai_config(unsigned int session,
				struct cg2900_dai_config *config)
{
	int err = 0;
	struct audio_user *audio_user;
	struct audio_info *info;

	pr_debug("cg2900_audio_get_dai_config session %d", session);

	if (!config) {
		pr_err("NULL supplied as config structure");
		return -EINVAL;
	}

	audio_user = get_session_user(session);
	if (!audio_user)
		return -EINVAL;

	info = audio_user->info;

	if (info->state != OPENED) {
		dev_err(BT_DEV, "Audio driver not open\n");
		return -EIO;
	}

	/*
	 * Return DAI configuration based on the received port.
	 * If port has not been configured return error.
	 */
	switch (config->port) {
	case PORT_0_I2S:
		mutex_lock(&info->management_mutex);
		if (info->i2s_config_known)
			memcpy(&config->conf.i2s,
			       &info->i2s_config,
			       sizeof(config->conf.i2s));
		else
			err = -EIO;
		mutex_unlock(&info->management_mutex);
		break;

	case PORT_1_I2S_PCM:
		mutex_lock(&info->management_mutex);
		if (info->i2s_pcm_config_known)
			memcpy(&config->conf.i2s_pcm,
			       &info->i2s_pcm_config,
			       sizeof(config->conf.i2s_pcm));
		else
			err = -EIO;
		mutex_unlock(&info->management_mutex);
		break;

	default:
		dev_err(BT_DEV, "Unknown port configuration %d\n",
			config->port);
		err = -EIO;
		break;
	};

	return err;
}
EXPORT_SYMBOL_GPL(cg2900_audio_get_dai_config);

/**
 * cg2900_audio_config_endpoint() - Configures one endpoint in the combo chip's audio system.
 * @session:	Session identifier this call is related to.
 * @config:	Pointer to the endpoint's configuration structure.
 *
 * Configures one endpoint in the combo chip's audio system.
 * Supported @endpoint_id values are:
 *  * ENDPOINT_BT_SCO_INOUT
 *  * ENDPOINT_BT_A2DP_SRC
 *  * ENDPOINT_FM_RX
 *  * ENDPOINT_FM_TX
 *
 * Returns:
 *   0 if there is no error.
 *   -EINVAL upon bad input parameter.
 *   -EIO if driver has not been opened.
 *   -EACCES if supplied cg2900_dai_config struct contains not supported
 *   endpoint_id.
 */
int cg2900_audio_config_endpoint(unsigned int session,
				 struct cg2900_endpoint_config *config)
{
	struct audio_user *audio_user;
	struct audio_info *info;

	pr_debug("cg2900_audio_config_endpoint\n");

	if (!config) {
		pr_err("NULL supplied as configuration structure");
		return -EINVAL;
	}

	audio_user = get_session_user(session);
	if (!audio_user)
		return -EINVAL;

	info = audio_user->info;

	if (info->state != OPENED) {
		dev_err(BT_DEV, "Audio driver not open\n");
		return -EIO;
	}

	switch (config->endpoint_id) {
	case ENDPOINT_BT_SCO_INOUT:
	case ENDPOINT_BT_A2DP_SRC:
	case ENDPOINT_FM_RX:
	case ENDPOINT_FM_TX:
		add_endpoint(config, &info->endpoints);
		break;

	case ENDPOINT_PORT_0_I2S:
	case ENDPOINT_PORT_1_I2S_PCM:
	case ENDPOINT_SLIMBUS_VOICE:
	case ENDPOINT_SLIMBUS_AUDIO:
	case ENDPOINT_BT_A2DP_SNK:
	case ENDPOINT_ANALOG_OUT:
	case ENDPOINT_DSP_AUDIO_IN:
	case ENDPOINT_DSP_AUDIO_OUT:
	case ENDPOINT_DSP_VOICE_IN:
	case ENDPOINT_DSP_VOICE_OUT:
	case ENDPOINT_DSP_TONE_IN:
	case ENDPOINT_BURST_BUFFER_IN:
	case ENDPOINT_BURST_BUFFER_OUT:
	case ENDPOINT_MUSIC_DECODER:
	case ENDPOINT_HCI_AUDIO_IN:
	default:
		dev_err(BT_DEV, "Unsupported endpoint_id %d\n",
			config->endpoint_id);
		return -EACCES;
	}

	return 0;
}
EXPORT_SYMBOL_GPL(cg2900_audio_config_endpoint);

static bool is_dai_port(enum cg2900_audio_endpoint_id ep)
{
	/* These are the only supported ones */
	return (ep == ENDPOINT_PORT_0_I2S) || (ep == ENDPOINT_PORT_1_I2S_PCM);
}

/**
 * cg2900_audio_start_stream() - Connects two endpoints and starts the audio stream.
 * @session:		Session identifier this call is related to.
 * @ep_1:		One of the endpoints, no relation to direction or role.
 * @ep_2:		The other endpoint, no relation to direction or role.
 * @stream_handle:	Pointer where to store the stream handle.
 *			Allocated by caller, must not be NULL.
 *
 * Connects two endpoints and starts the audio stream.
 * Note that the endpoints need to be configured before the stream is started;
 * DAI endpoints, such as ENDPOINT_PORT_0_I2S, are
 * configured through @cg2900_audio_set_dai_config() while other
 * endpoints are configured through @cg2900_audio_config_endpoint().
 *
 * Supported @endpoint_id values are:
 *  * ENDPOINT_PORT_0_I2S
 *  * ENDPOINT_PORT_1_I2S_PCM
 *  * ENDPOINT_BT_SCO_INOUT
 *  * ENDPOINT_FM_RX
 *  * ENDPOINT_FM_TX
 *
 * Returns:
 *   0 if there is no error.
 *   -EINVAL upon bad input parameter or unsupported configuration.
 *   -EIO if driver has not been opened.
 *   Errors from @conn_start_i2s_to_fm_rx, @conn_start_i2s_to_fm_tx, and
 *   @conn_start_pcm_to_sco.
 */
int cg2900_audio_start_stream(unsigned int session,
			      enum cg2900_audio_endpoint_id ep_1,
			      enum cg2900_audio_endpoint_id ep_2,
			      unsigned int *stream_handle)
{
	int err;
	struct audio_user *audio_user;
	struct audio_info *info;

	pr_debug("cg2900_audio_start_stream session %d ep_1 %d ep_2 %d",
		 session, ep_1, ep_2);

	audio_user = get_session_user(session);
	if (!audio_user)
		return -EINVAL;

	info = audio_user->info;

	if (info->state != OPENED) {
		dev_err(BT_DEV, "Audio driver not open\n");
		return -EIO;
	}

	/* Put digital interface in ep_1 to simplify comparison below */
	if (!is_dai_port(ep_1)) {
		/* Swap endpoints */
		enum cg2900_audio_endpoint_id t = ep_1;
		ep_1 = ep_2;
		ep_2 = t;
	}

	if (ep_1 == ENDPOINT_PORT_1_I2S_PCM && ep_2 == ENDPOINT_BT_SCO_INOUT) {
		err = conn_start_pcm_to_sco(audio_user, stream_handle);
	} else if (ep_1 == ENDPOINT_PORT_0_I2S && ep_2 == ENDPOINT_FM_RX) {
		err = conn_start_i2s_to_fm_rx(audio_user, stream_handle);
	} else if (ep_1 == ENDPOINT_PORT_0_I2S && ep_2 == ENDPOINT_FM_TX) {
		err = conn_start_i2s_to_fm_tx(audio_user, stream_handle);
	} else {
		dev_err(BT_DEV, "Endpoint config not handled: ep1: %d, "
			"ep2: %d\n", ep_1, ep_2);
		err = -EINVAL;
	}

	return err;
}
EXPORT_SYMBOL_GPL(cg2900_audio_start_stream);

/**
 * cg2900_audio_stop_stream() - Stops a stream and disconnects the endpoints.
 * @session:		Session identifier this call is related to.
 * @stream_handle:	Handle to the stream to stop.
 *
 * Returns:
 *   0 if there is no error.
 *   -EINVAL upon bad input parameter.
 *   -EIO if driver has not been opened.
 */
int cg2900_audio_stop_stream(unsigned int session, unsigned int stream_handle)
{
	struct audio_user *audio_user;
	struct audio_info *info;

	pr_debug("cg2900_audio_stop_stream handle %d", stream_handle);

	audio_user = get_session_user(session);
	if (!audio_user)
		return -EINVAL;

	info = audio_user->info;

	if (info->state != OPENED) {
		dev_err(BT_DEV, "Audio driver not open\n");
		return -EIO;
	}

	return conn_stop_stream(audio_user, stream_handle);
}
EXPORT_SYMBOL_GPL(cg2900_audio_stop_stream);

/**
 * audio_dev_open() - Open char device.
 * @inode:	Device driver information.
 * @filp:	Pointer to the file struct.
 *
 * Returns:
 *   0 if there is no error.
 *   -ENOMEM if allocation failed.
 *   Errors from @cg2900_audio_open.
 */
static int audio_dev_open(struct inode *inode, struct file *filp)
{
	int err;
	struct char_dev_info *char_dev_info;
	int minor;
	struct audio_info *info = NULL;
	struct audio_info *tmp;
	struct list_head *cursor;

	pr_debug("audio_dev_open");

	minor = iminor(inode);

	/* Find the info struct for this file */
	list_for_each(cursor, &cg2900_audio_devices) {
		tmp = list_entry(cursor, struct audio_info, list);
		if (tmp->misc_dev.minor == minor) {
			info = tmp;
			break;
		}
	}
	if (!info) {
		pr_err("Could not identify device in inode");
		return -EINVAL;
	}

	/*
	 * Allocate the char dev info structure. It will be stored inside
	 * the file pointer and supplied when file_ops are called.
	 * It's free'd in audio_dev_release.
	 */
	char_dev_info = kzalloc(sizeof(*char_dev_info), GFP_KERNEL);
	if (!char_dev_info) {
		dev_err(BT_DEV, "Couldn't allocate char_dev_info\n");
		return -ENOMEM;
	}
	filp->private_data = char_dev_info;
	char_dev_info->info = info;

	mutex_init(&char_dev_info->management_mutex);
	mutex_init(&char_dev_info->rw_mutex);
	skb_queue_head_init(&char_dev_info->rx_queue);

	mutex_lock(&char_dev_info->management_mutex);
	err = cg2900_audio_open(&char_dev_info->session, info->dev_bt->parent);
	mutex_unlock(&char_dev_info->management_mutex);
	if (err) {
		dev_err(BT_DEV, "Failed to open CG2900 Audio driver (%d)\n",
			err);
		goto error_handling_free_mem;
	}

	return 0;

error_handling_free_mem:
	kfree(char_dev_info);
	filp->private_data = NULL;
	return err;
}

/**
 * audio_dev_release() - Release char device.
 * @inode:	Device driver information.
 * @filp:	Pointer to the file struct.
 *
 * Returns:
 *   0 if there is no error.
 *   -EBADF if NULL pointer was supplied in private data.
 *   Errors from @cg2900_audio_close.
 */
static int audio_dev_release(struct inode *inode, struct file *filp)
{
	int err = 0;
	struct char_dev_info *dev = filp->private_data;
	struct audio_info *info = dev->info;

	dev_dbg(BT_DEV, "audio_dev_release\n");

	mutex_lock(&dev->management_mutex);
	err = cg2900_audio_close(&dev->session);
	if (err)
		/*
		 * Just print the error. Still free the char_dev_info since we
		 * don't know the filp structure is valid after this call
		 */
		dev_err(BT_DEV, "Error %d when closing CG2900 audio driver\n",
			err);

	mutex_unlock(&dev->management_mutex);

	kfree(dev);
	filp->private_data = NULL;

	return err;
}

/**
 * audio_dev_read() - Return information to the user from last @write call.
 * @filp:	Pointer to the file struct.
 * @buf:	Received buffer.
 * @count:	Size of buffer.
 * @f_pos:	Position in buffer.
 *
 * The audio_dev_read() function returns information from
 * the last @write call to same char device.
 * The data is in the following format:
 *   * OpCode of command for this data
 *   * Data content (Length of data is determined by the command OpCode, i.e.
 *     fixed for each command)
 *
 * Returns:
 *   Bytes successfully read (could be 0).
 *   -EBADF if NULL pointer was supplied in private data.
 *   -EFAULT if copy_to_user fails.
 *   -ENOMEM upon allocation failure.
 */
static ssize_t audio_dev_read(struct file *filp, char __user *buf, size_t count,
			      loff_t *f_pos)
{
	struct char_dev_info *dev = filp->private_data;
	struct audio_info *info = dev->info;
	unsigned int bytes_to_copy;
	int err = 0;
	struct sk_buff *skb;

	dev_dbg(BT_DEV, "audio_dev_read count %d\n", count);

	mutex_lock(&dev->rw_mutex);

	skb = skb_dequeue(&dev->rx_queue);
	if (!skb) {
		/* No data to read */
		bytes_to_copy = 0;
		goto finished;
	}

	bytes_to_copy = min(count, (unsigned int)(skb->len));

	err = copy_to_user(buf, skb->data, bytes_to_copy);
	if (err) {
		dev_err(BT_DEV, "copy_to_user error %d\n", err);
		skb_queue_head(&dev->rx_queue, skb);
		err = -EFAULT;
		goto error_handling;
	}

	skb_pull(skb, bytes_to_copy);

	if (skb->len > 0)
		skb_queue_head(&dev->rx_queue, skb);
	else
		kfree_skb(skb);

	goto finished;

error_handling:
	mutex_unlock(&dev->rw_mutex);
	return (ssize_t)err;
finished:
	mutex_unlock(&dev->rw_mutex);
	return bytes_to_copy;
}

/**
 * audio_dev_write() - Call CG2900 Audio API function.
 * @filp:	Pointer to the file struct.
 * @buf:	Write buffer.
 * @count:	Size of the buffer write.
 * @f_pos:	Position of buffer.
 *
 * audio_dev_write() function executes supplied data and
 * interprets it as if it was a function call to the CG2900 Audio API.
 * The data is according to:
 *   * OpCode (4 bytes, see API).
 *   * Data according to OpCode (see API). No padding between parameters.
 *
 * Returns:
 *   Bytes successfully written (could be 0). Equals input @count if successful.
 *   -EBADF if NULL pointer was supplied in private data.
 *   -EFAULT if copy_from_user fails.
 *   Error codes from all CG2900 Audio API functions.
 */
static ssize_t audio_dev_write(struct file *filp, const char __user *buf,
			       size_t count, loff_t *f_pos)
{
	u8 *rec_data;
	struct char_dev_info *dev = filp->private_data;
	struct audio_info *info;
	int err = 0;
	int op_code = 0;
	u8 *curr_data;
	unsigned int stream_handle;
	struct cg2900_dai_config dai_config;
	struct cg2900_endpoint_config ep_config;
	enum cg2900_audio_endpoint_id ep_1;
	enum cg2900_audio_endpoint_id ep_2;
	int bytes_left = count;

	pr_debug("audio_dev_write count %d", count);

	if (!dev) {
		pr_err("No dev supplied in private data");
		return -EBADF;
	}
	info = dev->info;

	rec_data = kmalloc(count, GFP_KERNEL);
	if (!rec_data) {
		dev_err(BT_DEV, "kmalloc failed (%d bytes)\n", count);
		return -ENOMEM;
	}

	mutex_lock(&dev->rw_mutex);

	err = copy_from_user(rec_data, buf, count);
	if (err) {
		dev_err(BT_DEV, "copy_from_user failed (%d)\n", err);
		err = -EFAULT;
		goto finished_mutex_unlock;
	}

	/* Initialize temporary data pointer used to traverse the packet */
	curr_data = rec_data;

	op_code = curr_data[0];
	/* OpCode is int size to keep data int aligned */
	curr_data += sizeof(unsigned int);
	bytes_left -= sizeof(unsigned int);

	switch (op_code) {
	case CG2900_OPCODE_SET_DAI_CONF:
		if (bytes_left < sizeof(dai_config)) {
			dev_err(BT_DEV, "Not enough data supplied for "
				"CG2900_OPCODE_SET_DAI_CONF\n");
			err = -EINVAL;
			goto finished_mutex_unlock;
		}
		memcpy(&dai_config, curr_data, sizeof(dai_config));
		dev_dbg(BT_DEV, "CG2900_OPCODE_SET_DAI_CONF port %d\n",
			dai_config.port);
		err = cg2900_audio_set_dai_config(dev->session, &dai_config);
		break;

	case CG2900_OPCODE_GET_DAI_CONF:
		if (bytes_left < sizeof(dai_config)) {
			dev_err(BT_DEV, "Not enough data supplied for "
				"CG2900_OPCODE_GET_DAI_CONF\n");
			err = -EINVAL;
			goto finished_mutex_unlock;
		}
		/*
		 * Only need to copy the port really, but let's copy
		 * like this for simplicity. It's only test functionality
		 * after all.
		 */
		memcpy(&dai_config, curr_data, sizeof(dai_config));
		dev_dbg(BT_DEV, "CG2900_OPCODE_GET_DAI_CONF port %d\n",
			dai_config.port);
		err = cg2900_audio_get_dai_config(dev->session, &dai_config);
		if (!err) {
			int len;
			struct sk_buff *skb;

			/*
			 * Command succeeded. Store data so it can be returned
			 * when calling read.
			 */
			len = sizeof(op_code) + sizeof(dai_config);
			skb = alloc_skb(len, GFP_KERNEL);
			if (!skb) {
				dev_err(BT_DEV, "CG2900_OPCODE_GET_DAI_CONF: "
						"Could not allocate skb\n");
				err = -ENOMEM;
				goto finished_mutex_unlock;
			}
			memcpy(skb_put(skb, sizeof(op_code)), &op_code,
			       sizeof(op_code));
			memcpy(skb_put(skb, sizeof(dai_config)),
			       &dai_config, sizeof(dai_config));
			skb_queue_tail(&dev->rx_queue, skb);
		}
		break;

	case CG2900_OPCODE_CONFIGURE_ENDPOINT:
		if (bytes_left < sizeof(ep_config)) {
			dev_err(BT_DEV, "Not enough data supplied for "
				"CG2900_OPCODE_CONFIGURE_ENDPOINT\n");
			err = -EINVAL;
			goto finished_mutex_unlock;
		}
		memcpy(&ep_config, curr_data, sizeof(ep_config));
		dev_dbg(BT_DEV, "CG2900_OPCODE_CONFIGURE_ENDPOINT ep_id %d\n",
			ep_config.endpoint_id);
		err = cg2900_audio_config_endpoint(dev->session, &ep_config);
		break;

	case CG2900_OPCODE_START_STREAM:
		if (bytes_left < (sizeof(ep_1) + sizeof(ep_2))) {
			dev_err(BT_DEV, "Not enough data supplied for "
				"CG2900_OPCODE_START_STREAM\n");
			err = -EINVAL;
			goto finished_mutex_unlock;
		}
		memcpy(&ep_1, curr_data, sizeof(ep_1));
		curr_data += sizeof(ep_1);
		memcpy(&ep_2, curr_data, sizeof(ep_2));
		dev_dbg(BT_DEV, "CG2900_OPCODE_START_STREAM ep_1 %d ep_2 %d\n",
			ep_1, ep_2);

		err = cg2900_audio_start_stream(dev->session,
			ep_1, ep_2, &stream_handle);
		if (!err) {
			int len;
			struct sk_buff *skb;

			/*
			 * Command succeeded. Store data so it can be returned
			 * when calling read.
			 */
			len = sizeof(op_code) + sizeof(stream_handle);
			skb = alloc_skb(len, GFP_KERNEL);
			if (!skb) {
				dev_err(BT_DEV, "CG2900_OPCODE_START_STREAM: "
						"Could not allocate skb\n");
				err = -ENOMEM;
				goto finished_mutex_unlock;
			}
			memcpy(skb_put(skb, sizeof(op_code)), &op_code,
			       sizeof(op_code));
			memcpy(skb_put(skb, sizeof(stream_handle)),
			       &stream_handle, sizeof(stream_handle));
			skb_queue_tail(&dev->rx_queue, skb);

			dev_dbg(BT_DEV, "stream_handle %d\n", stream_handle);
		}
		break;

	case CG2900_OPCODE_STOP_STREAM:
		if (bytes_left < sizeof(stream_handle)) {
			dev_err(BT_DEV, "Not enough data supplied for "
				"CG2900_OPCODE_STOP_STREAM\n");
			err = -EINVAL;
			goto finished_mutex_unlock;
		}
		memcpy(&stream_handle, curr_data, sizeof(stream_handle));
		dev_dbg(BT_DEV, "CG2900_OPCODE_STOP_STREAM stream_handle %d\n",
			stream_handle);
		err = cg2900_audio_stop_stream(dev->session, stream_handle);
		break;

	default:
		dev_err(BT_DEV, "Received bad op_code %d\n", op_code);
		break;
	};

finished_mutex_unlock:
	kfree(rec_data);
	mutex_unlock(&dev->rw_mutex);

	if (err)
		return err;
	else
		return count;
}

/**
 * audio_dev_poll() - Handle POLL call to the interface.
 * @filp:	Pointer to the file struct.
 * @wait:	Poll table supplied to caller.
 *
 * This function is used by the User Space application to see if the device is
 * still open and if there is any data available for reading.
 *
 * Returns:
 *   Mask of current set POLL values.
 */
static unsigned int audio_dev_poll(struct file *filp, poll_table *wait)
{
	struct char_dev_info *dev = filp->private_data;
	struct audio_info *info;
	unsigned int mask = 0;

	if (!dev) {
		pr_err("No dev supplied in private data");
		return POLLERR | POLLRDHUP;
	}
	info = dev->info;

	if (RESET == info->state)
		mask |= POLLERR | POLLRDHUP | POLLPRI;
	else
		/* Unless RESET we can transmit */
		mask |= POLLOUT;

	if (!skb_queue_empty(&dev->rx_queue))
		mask |= POLLIN | POLLRDNORM;

	return mask;
}

static const struct file_operations char_dev_fops = {
	.open = audio_dev_open,
	.release = audio_dev_release,
	.read = audio_dev_read,
	.write = audio_dev_write,
	.poll = audio_dev_poll
};

/**
 * probe_common() - Register misc device.
 * @info:	Audio info structure.
 * @dev:	Current device.
 *
 * Returns:
 *   0 if there is no error.
 *   -ENOMEM if allocation fails.
 *   Error codes from misc_register.
 */
static int probe_common(struct audio_info *info, struct device *dev)
{
	struct audio_cb_info *cb_info;
	struct cg2900_user_data *pf_data;
	int err;

	cb_info = kzalloc(sizeof(*cb_info), GFP_KERNEL);
	if (!cb_info) {
		dev_err(dev, "Failed to allocate cb_info\n");
		return -ENOMEM;
	}
	init_waitqueue_head(&cb_info->wq);
	skb_queue_head_init(&cb_info->skb_queue);

	pf_data = dev_get_platdata(dev);
	cg2900_set_usr(pf_data, cb_info);
	pf_data->dev = dev;
	pf_data->read_cb = read_cb;
	pf_data->reset_cb = reset_cb;

	/* Only register misc device when both devices (BT and FM) are probed */
	if (!info->dev_bt || !info->dev_fm)
		return 0;

	/* Prepare and register MISC device */
	info->misc_dev.minor = MISC_DYNAMIC_MINOR;
	info->misc_dev.name = NAME;
	info->misc_dev.fops = &char_dev_fops;
	info->misc_dev.parent = dev;
	info->misc_dev.mode = S_IRUGO | S_IWUGO;

	err = misc_register(&info->misc_dev);
	if (err) {
		dev_err(dev, "Error %d registering misc dev\n", err);
		return err;
	}
	info->misc_registered = true;

	dev_info(dev, "CG2900 Audio driver started\n");
	return 0;
}

/**
 * cg2900_audio_bt_probe() - Initialize CG2900 BT audio resources.
 * @pdev:	Platform device.
 *
 * Returns:
 *   0 if there is no error.
 *   -ENOMEM if allocation fails.
 *   -EEXIST if device has already been started.
 *   Error codes from probe_common.
 */
static int __devinit cg2900_audio_bt_probe(struct platform_device *pdev)
{
	int err;
	struct audio_info *info;

	dev_dbg(&pdev->dev, "cg2900_audio_bt_probe\n");

	info = get_info(&pdev->dev);
	if (IS_ERR(info))
		return PTR_ERR(info);

	info->dev_bt = &pdev->dev;
	dev_set_drvdata(&pdev->dev, info);

	err = probe_common(info, &pdev->dev);
	if (err) {
		dev_err(&pdev->dev, "Could not probe audio BT (%d)\n", err);
		dev_set_drvdata(&pdev->dev, NULL);
		device_removed(info);
	}

	return err;
}

/**
 * cg2900_audio_bt_probe() - Initialize CG2900 FM audio resources.
 * @pdev:	Platform device.
 *
 * Returns:
 *   0 if there is no error.
 *   -ENOMEM if allocation fails.
 *   -EEXIST if device has already been started.
 *   Error codes from probe_common.
 */
static int __devinit cg2900_audio_fm_probe(struct platform_device *pdev)
{
	int err;
	struct audio_info *info;

	dev_dbg(&pdev->dev, "cg2900_audio_fm_probe\n");

	info = get_info(&pdev->dev);
	if (IS_ERR(info))
		return PTR_ERR(info);

	info->dev_fm = &pdev->dev;
	dev_set_drvdata(&pdev->dev, info);

	err = probe_common(info, &pdev->dev);
	if (err) {
		dev_err(&pdev->dev, "Could not probe audio FM (%d)\n", err);
		dev_set_drvdata(&pdev->dev, NULL);
		device_removed(info);
	}

	return err;
}

/**
 * common_remove() - Dergister misc device.
 * @info:	Audio info structure.
 * @dev:	Current device.
 *
 * Returns:
 *   0 if success.
 *   Error codes from misc_deregister.
 */
static int common_remove(struct audio_info *info, struct device *dev)
{
	int err;
	struct audio_cb_info *cb_info;
	struct cg2900_user_data *pf_data;

	pf_data = dev_get_platdata(dev);
	cb_info = cg2900_get_usr(pf_data);
	skb_queue_purge(&cb_info->skb_queue);
	wake_up_all(&cb_info->wq);
	kfree(cb_info);

	if (!info->misc_registered)
		return 0;

	err = misc_deregister(&info->misc_dev);
	if (err)
		dev_err(dev, "Error %d deregistering misc dev\n", err);
	info->misc_registered = false;

	dev_info(dev, "CG2900 Audio driver removed\n");
	return err;
}

/**
 * cg2900_audio_bt_remove() - Release CG2900 audio resources.
 * @pdev:	Platform device.
 *
 * Returns:
 *   0 if success.
 *   Error codes from common_remove.
 */
static int __devexit cg2900_audio_bt_remove(struct platform_device *pdev)
{
	int err;
	struct audio_info *info;

	dev_dbg(&pdev->dev, "cg2900_audio_bt_remove\n");

	info = dev_get_drvdata(&pdev->dev);

	info->dev_bt = NULL;

	err = common_remove(info, &pdev->dev);
	if (err)
		dev_err(&pdev->dev,
			"cg2900_audio_bt_remove:common_remove failed\n");

	device_removed(info);

	return 0;
}

/**
 * cg2900_audio_fm_remove() - Release CG2900 audio resources.
 * @pdev:	Platform device.
 *
 * Returns:
 *   0 if success.
 *   Error codes from common_remove.
 */
static int __devexit cg2900_audio_fm_remove(struct platform_device *pdev)
{
	int err;
	struct audio_info *info;

	dev_dbg(&pdev->dev, "cg2900_audio_fm_remove\n");

	info = dev_get_drvdata(&pdev->dev);

	info->dev_fm = NULL;

	err = common_remove(info, &pdev->dev);
	if (err)
		dev_err(&pdev->dev,
			"cg2900_audio_fm_remove:common_remove failed\n");

	device_removed(info);

	return 0;
}

static struct platform_driver cg2900_audio_bt_driver = {
	.driver = {
		.name	= "cg2900-audiobt",
		.owner	= THIS_MODULE,
	},
	.probe	= cg2900_audio_bt_probe,
	.remove	= __devexit_p(cg2900_audio_bt_remove),
};

static struct platform_driver cg2900_audio_fm_driver = {
	.driver = {
		.name	= "cg2900-audiofm",
		.owner	= THIS_MODULE,
	},
	.probe	= cg2900_audio_fm_probe,
	.remove	= __devexit_p(cg2900_audio_fm_remove),
};

/**
 * cg2900_audio_init() - Initialize module.
 *
 * Registers platform driver.
 */
static int __init cg2900_audio_init(void)
{
	int err;

	pr_debug("cg2900_audio_init");

	err = platform_driver_register(&cg2900_audio_bt_driver);
	if (err)
		return err;
	return platform_driver_register(&cg2900_audio_fm_driver);
}

/**
 * cg2900_audio_exit() - Remove module.
 *
 * Unregisters platform driver.
 */
static void __exit cg2900_audio_exit(void)
{
	pr_debug("cg2900_audio_exit");
	platform_driver_unregister(&cg2900_audio_fm_driver);
	platform_driver_unregister(&cg2900_audio_bt_driver);
}

module_init(cg2900_audio_init);
module_exit(cg2900_audio_exit);

MODULE_AUTHOR("Par-Gunnar Hjalmdahl ST-Ericsson");
MODULE_AUTHOR("Kjell Andersson ST-Ericsson");
MODULE_LICENSE("GPL v2");
MODULE_DESCRIPTION("Linux Bluetooth Audio ST-Ericsson controller");