summaryrefslogtreecommitdiff
path: root/dsp/q6afe.c
blob: ec76c65bf967715708b6571fef7b3c694494daea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
// SPDX-License-Identifier: GPL-2.0-only
/* Copyright (c) 2012-2020, The Linux Foundation. All rights reserved.
 */
#include <linux/slab.h>
#include <linux/debugfs.h>
#include <linux/kernel.h>
#include <linux/kthread.h>
#include <linux/uaccess.h>
#include <linux/wait.h>
#include <linux/jiffies.h>
#include <linux/sched.h>
#include <linux/delay.h>
#include <linux/version.h>
#include <dsp/msm_audio_ion.h>
#include <dsp/apr_audio-v2.h>
#include <dsp/audio_cal_utils.h>
#include <dsp/q6afe-v2.h>
#include <dsp/q6audio-v2.h>
#include <dsp/q6common.h>
#include <dsp/q6core.h>
#include <dsp/msm-audio-event-notify.h>
#include <ipc/apr_tal.h>
#include "adsp_err.h"
#include "q6afecal-hwdep.h"
#if IS_ENABLED(CONFIG_TAS25XX_ALGO)
#include <dsp/tas_qualcomm.h>
#endif

#if IS_ENABLED(CONFIG_TAS25XX_ALGO)
#ifdef INSTANCE_ID_0 /*APR Version 3*/
static int32_t tas_smartamp_algo_callback(uint32_t opcode, uint32_t *payload,
				    uint32_t payload_size);
#else /*APR Version 2*/
static int32_t tas_smartamp_algo_callback(uint32_t *payload,
				    uint32_t payload_size);
#endif /*INSTANCE_ID_0*/
#endif /*CONFIG_TAS25XX_ALGO*/

#define WAKELOCK_TIMEOUT	5000
#define AFE_CLK_TOKEN	1024

#define SP_V4_NUM_MAX_SPKRS SP_V2_NUM_MAX_SPKRS
#define MAX_LSM_SESSIONS 8

struct afe_avcs_payload_port_mapping {
	u16 port_id;
	struct avcs_load_unload_modules_payload *payload;
} __packed;

enum {
	ENCODER_CASE,
	DECODER_CASE,
	/* Add new use case here */
	MAX_ALLOWED_USE_CASES
};

static struct afe_avcs_payload_port_mapping *pm[MAX_ALLOWED_USE_CASES];

enum {
	AFE_COMMON_RX_CAL = 0,
	AFE_COMMON_TX_CAL,
	AFE_LSM_TX_CAL,
	AFE_AANC_CAL,
	AFE_FB_SPKR_PROT_CAL,
	AFE_HW_DELAY_CAL,
	AFE_SIDETONE_CAL,
	AFE_SIDETONE_IIR_CAL,
	AFE_TOPOLOGY_CAL,
	AFE_LSM_TOPOLOGY_CAL,
	AFE_CUST_TOPOLOGY_CAL,
	AFE_FB_SPKR_PROT_TH_VI_CAL,
	AFE_FB_SPKR_PROT_EX_VI_CAL,
	AFE_FB_SPKR_PROT_V4_EX_VI_CAL,
	MAX_AFE_CAL_TYPES
};

enum fbsp_state {
	FBSP_INCORRECT_OP_MODE,
	FBSP_INACTIVE,
	FBSP_WARMUP,
	FBSP_IN_PROGRESS,
	FBSP_SUCCESS,
	FBSP_FAILED,
	MAX_FBSP_STATE
};

static char fbsp_state[MAX_FBSP_STATE][50] = {
	[FBSP_INCORRECT_OP_MODE] = "incorrect operation mode",
	[FBSP_INACTIVE] = "port not started",
	[FBSP_WARMUP] = "waiting for warmup",
	[FBSP_IN_PROGRESS] = "in progress state",
	[FBSP_SUCCESS] = "success",
	[FBSP_FAILED] = "failed"
};

enum v_vali_state {
	V_VALI_FAILED,
	V_VALI_SUCCESS,
	V_VALI_INCORRECT_OP_MODE,
	V_VALI_INACTIVE,
	V_VALI_WARMUP,
	V_VALI_IN_PROGRESS,
	MAX_V_VALI_STATE
};

enum {
	USE_CALIBRATED_R0TO,
	USE_SAFE_R0TO
};

enum {
	QUICK_CALIB_DISABLE,
	QUICK_CALIB_ENABLE
};

enum {
	Q6AFE_MSM_SPKR_PROCESSING = 0,
	Q6AFE_MSM_SPKR_CALIBRATION,
	Q6AFE_MSM_SPKR_FTM_MODE,
	Q6AFE_MSM_SPKR_V_VALI_MODE
};

enum {
	APTX_AD_48 = 0,
	APTX_AD_44_1 = 1
};

enum {
	AFE_MATCHED_PORT_DISABLE,
	AFE_MATCHED_PORT_ENABLE
};

enum {
	AFE_FBSP_V4_EX_VI_MODE_NORMAL = 0,
	AFE_FBSP_V4_EX_VI_MODE_FTM = 1
};

struct wlock {
	struct wakeup_source *ws;
};

static struct wlock wl;

struct afe_sp_v4_th_vi_ftm_get_param_resp {
	struct afe_sp_v4_gen_get_param_resp gen_resp;
	int32_t num_ch;
	/* Number of channels for Rx signal.
	*/

	struct afe_sp_v4_channel_ftm_params
		ch_ftm_params[SP_V4_NUM_MAX_SPKRS];
} __packed;

struct afe_sp_v4_v_vali_get_param_resp {
	struct afe_sp_v4_gen_get_param_resp gen_resp;
	int32_t num_ch;
	/* Number of channels for Rx signal.
	*/

	struct afe_sp_v4_channel_v_vali_params
		ch_v_vali_params[SP_V4_NUM_MAX_SPKRS];
} __packed;

struct afe_sp_v4_ex_vi_ftm_get_param_resp {
	struct afe_sp_v4_gen_get_param_resp gen_resp;
	int32_t num_ch;
	/* Number of channels for Rx signal.
	*/

	struct afe_sp_v4_channel_ex_vi_ftm_params
		ch_ex_vi_ftm_params[SP_V4_NUM_MAX_SPKRS];
} __packed;

struct afe_sp_v4_max_log_get_param_resp {
	struct afe_sp_v4_gen_get_param_resp gen_resp;
	int32_t num_ch;
	/* Number of channels for Rx signal.
	*/

	struct afe_sp_v4_channel_tmax_xmax_params
		ch_max_params[SP_V4_NUM_MAX_SPKRS];
} __packed;

struct afe_ctl {
	void *apr;
	atomic_t state;
	atomic_t status;
	atomic_t clk_state;
	atomic_t clk_status;
	wait_queue_head_t wait[AFE_MAX_PORTS];
	wait_queue_head_t wait_wakeup;
	wait_queue_head_t clk_wait;
	struct task_struct *task;
	wait_queue_head_t lpass_core_hw_wait;
	uint32_t lpass_hw_core_client_hdl[AFE_LPASS_CORE_HW_VOTE_MAX];
	void (*tx_cb)(uint32_t opcode,
		uint32_t token, uint32_t *payload, void *priv);
	void (*rx_cb)(uint32_t opcode,
		uint32_t token, uint32_t *payload, void *priv);
	void *tx_private_data;
	void *rx_private_data;
	uint32_t mmap_handle;

	void (*pri_spdif_tx_cb)(uint32_t opcode,
		uint32_t token, uint32_t *payload, void *priv);
	void (*sec_spdif_tx_cb)(uint32_t opcode,
		uint32_t token, uint32_t *payload, void *priv);
	void *pri_spdif_tx_private_data;
	void *sec_spdif_tx_private_data;
	int pri_spdif_config_change;
	int sec_spdif_config_change;
	struct work_struct afe_spdif_work;

	int	topology[AFE_MAX_PORTS];
	struct cal_type_data *cal_data[MAX_AFE_CAL_TYPES];

	atomic_t mem_map_cal_handles[MAX_AFE_CAL_TYPES];
	atomic_t mem_map_cal_index;
	u32 afe_cal_mode[AFE_MAX_PORTS];

	u16 dtmf_gen_rx_portid;
	struct audio_cal_info_spk_prot_cfg	prot_cfg;
	struct afe_spkr_prot_calib_get_resp	calib_data;
	struct audio_cal_info_sp_th_vi_ftm_cfg	th_ftm_cfg;
	struct audio_cal_info_sp_th_vi_v_vali_cfg	v_vali_cfg;
	struct audio_cal_info_sp_ex_vi_ftm_cfg	ex_ftm_cfg;
	struct afe_sp_th_vi_get_param_resp	th_vi_resp;
	struct afe_sp_th_vi_v_vali_get_param_resp	th_vi_v_vali_resp;
	struct afe_sp_ex_vi_get_param_resp	ex_vi_resp;
	struct afe_sp_rx_tmax_xmax_logging_resp	xt_logging_resp;
	struct afe_sp_v4_th_vi_calib_resp spv4_calib_data;
	struct afe_sp_v4_param_vi_channel_map_cfg v4_ch_map_cfg;
	struct afe_sp_v4_th_vi_ftm_get_param_resp spv4_th_vi_ftm_resp;
	uint32_t spv4_th_vi_ftm_rcvd_param_size;
	struct afe_sp_v4_v_vali_get_param_resp spv4_v_vali_resp;
	uint32_t spv4_v_vali_rcvd_param_size;
	struct afe_sp_v4_ex_vi_ftm_get_param_resp spv4_ex_vi_ftm_resp;
	uint32_t spv4_ex_vi_ftm_rcvd_param_size;
	struct afe_sp_v4_max_log_get_param_resp spv4_max_log_resp;
	uint32_t spv4_max_log_rcvd_param_size;
	struct afe_av_dev_drift_get_param_resp	av_dev_drift_resp;
	struct afe_doa_tracking_mon_get_param_resp	doa_tracking_mon_resp;
	int vi_tx_port;
	int vi_rx_port;
	uint32_t afe_sample_rates[AFE_MAX_PORTS];
	struct aanc_data aanc_info;
	struct mutex afe_cmd_lock;
	struct mutex afe_apr_lock;
	struct mutex afe_clk_lock;
	int set_custom_topology;
	int dev_acdb_id[AFE_MAX_PORTS];
	routing_cb rt_cb;
	struct audio_uevent_data *uevent_data;
	/* cal info for AFE */
	struct afe_fw_info *fw_data;
	u32 island_mode[AFE_MAX_PORTS];
	struct vad_config vad_cfg[AFE_MAX_PORTS];
	struct work_struct afe_dc_work;
	struct notifier_block event_notifier;
	/* FTM spk params */
	uint32_t initial_cal;
	uint32_t v_vali_flag;
#if IS_ENABLED(CONFIG_TAS25XX_ALGO)
	struct afe_smartamp_calib_get_resp tas_calib_data;
	uint32_t tas_module_rx;
	uint32_t tas_module_tx;
#endif	/*CONFIG_TAS25XX_ALGO*/
	uint32_t num_spkrs;
	uint32_t cps_ch_mask;
	struct afe_cps_hw_intf_cfg *cps_config;
	int lsm_afe_ports[MAX_LSM_SESSIONS];
};

struct afe_clkinfo_per_port {
	u16 port_id; /* AFE port ID */
	uint32_t clk_id; /* Clock ID */
};

struct afe_clkinfo_per_port clkinfo_per_port[] = {
	{ AFE_PORT_ID_PRIMARY_MI2S_RX, Q6AFE_LPASS_CLK_ID_PRI_MI2S_IBIT},
	{ AFE_PORT_ID_SECONDARY_MI2S_RX, Q6AFE_LPASS_CLK_ID_SEC_MI2S_IBIT},
	{ AFE_PORT_ID_TERTIARY_MI2S_RX, Q6AFE_LPASS_CLK_ID_TER_MI2S_IBIT},
	{ AFE_PORT_ID_QUATERNARY_MI2S_RX, Q6AFE_LPASS_CLK_ID_QUAD_MI2S_IBIT},
	{ AFE_PORT_ID_QUINARY_MI2S_RX, Q6AFE_LPASS_CLK_ID_QUI_MI2S_IBIT},
	{ AFE_PORT_ID_SENARY_MI2S_RX, Q6AFE_LPASS_CLK_ID_SEN_MI2S_IBIT},
	{ AFE_PORT_ID_PRIMARY_PCM_RX, Q6AFE_LPASS_CLK_ID_PRI_PCM_IBIT},
	{ AFE_PORT_ID_SECONDARY_PCM_RX, Q6AFE_LPASS_CLK_ID_SEC_PCM_IBIT},
	{ AFE_PORT_ID_TERTIARY_PCM_RX, Q6AFE_LPASS_CLK_ID_TER_PCM_IBIT},
	{ AFE_PORT_ID_QUATERNARY_PCM_RX, Q6AFE_LPASS_CLK_ID_QUAD_PCM_IBIT},
	{ AFE_PORT_ID_QUINARY_PCM_RX, Q6AFE_LPASS_CLK_ID_QUIN_PCM_IBIT},
	{ AFE_PORT_ID_SENARY_PCM_RX, Q6AFE_LPASS_CLK_ID_SEN_PCM_IBIT},
	{ AFE_PORT_ID_PRIMARY_TDM_RX, Q6AFE_LPASS_CLK_ID_PRI_TDM_IBIT},
	{ AFE_PORT_ID_SECONDARY_TDM_RX, Q6AFE_LPASS_CLK_ID_SEC_TDM_IBIT},
	{ AFE_PORT_ID_TERTIARY_TDM_RX, Q6AFE_LPASS_CLK_ID_TER_TDM_IBIT},
	{ AFE_PORT_ID_QUATERNARY_TDM_RX, Q6AFE_LPASS_CLK_ID_QUAD_TDM_IBIT},
	{ AFE_PORT_ID_QUINARY_TDM_RX, Q6AFE_LPASS_CLK_ID_QUIN_TDM_IBIT},
	{ AFE_PORT_ID_PRIMARY_SPDIF_RX,
		AFE_CLOCK_SET_CLOCK_ID_PRI_SPDIF_OUTPUT_CORE},
	{ AFE_PORT_ID_PRIMARY_SPDIF_TX,
		AFE_CLOCK_SET_CLOCK_ID_PRI_SPDIF_INPUT_CORE},
	{ AFE_PORT_ID_SECONDARY_SPDIF_RX,
		AFE_CLOCK_SET_CLOCK_ID_SEC_SPDIF_OUTPUT_CORE},
	{ AFE_PORT_ID_SECONDARY_SPDIF_TX,
		AFE_CLOCK_SET_CLOCK_ID_SEC_SPDIF_INPUT_CORE},
	{ AFE_PORT_ID_PRIMARY_META_MI2S_RX,
		Q6AFE_LPASS_CLK_ID_PRI_MI2S_IBIT},
	{ AFE_PORT_ID_SECONDARY_META_MI2S_RX,
		Q6AFE_LPASS_CLK_ID_PRI_MI2S_IBIT},
};

static atomic_t afe_ports_mad_type[SLIMBUS_PORT_LAST - SLIMBUS_0_RX];
static unsigned long afe_configured_cmd;

static struct afe_ctl this_afe;

#define TIMEOUT_MS 1000
#define Q6AFE_MAX_VOLUME 0x3FFF

static int pcm_afe_instance[2];
static int proxy_afe_instance[2];
bool afe_close_done[2] = {true, true};

#define SIZEOF_CFG_CMD(y) \
		(sizeof(struct apr_hdr) + sizeof(u16) + (sizeof(struct y)))

static bool q6afe_is_afe_lsm_port(int port_id);

static void q6afe_unload_avcs_modules(u16 port_id, int index)
{
	int ret = 0;

	ret = q6core_avcs_load_unload_modules(pm[index]->payload,
			AVCS_UNLOAD_MODULES);

	if (ret < 0)
		pr_err("%s: avcs module unload failed %d\n", __func__, ret);

	kfree(pm[index]->payload);
	pm[index]->payload = NULL;
	kfree(pm[index]);
	pm[index] = NULL;
}

static int q6afe_load_avcs_modules(int num_modules, u16 port_id,
		 uint32_t use_case, u32 format_id)
{
	int i = 0;
	int32_t ret = 0;
	size_t payload_size = 0, port_struct_size = 0;
	struct afe_avcs_payload_port_mapping payload_map;
	struct avcs_load_unload_modules_sec_payload sec_payload;

	if (num_modules <= 0) {
		pr_err("%s: Invalid number of modules to load\n", __func__);
		return -EINVAL;
	}

	for (i = 0; i < MAX_ALLOWED_USE_CASES; i++) {
		if (pm[i] == NULL) {
			port_struct_size = sizeof(payload_map);
			pm[i] = kzalloc(port_struct_size, GFP_KERNEL);
			if (!pm[i])
				return -ENOMEM;

			pm[i]->port_id = port_id;
			payload_size = sizeof(uint32_t) + (sizeof(sec_payload)
					* num_modules);
			pm[i]->payload = kzalloc(payload_size, GFP_KERNEL);
			if (!pm[i]->payload) {
				kfree(pm[i]);
				pm[i] = NULL;
				return -ENOMEM;
			}

			/*
			 * index 0 : packetizer/de-packetizer
			 * index 1 : encoder/decoder
			 */

			pm[i]->payload->num_modules = num_modules;

			/*
			 * Remaining fields of payload
			 * are initialized to zero
			 */

			if (use_case == ENCODER_CASE) {
				pm[i]->payload->load_unload_info[0].module_type =
						AMDB_MODULE_TYPE_PACKETIZER;
				pm[i]->payload->load_unload_info[0].id1 =
						AVS_MODULE_ID_PACKETIZER_COP;
				pm[i]->payload->load_unload_info[1].module_type =
						AMDB_MODULE_TYPE_ENCODER;
				pm[i]->payload->load_unload_info[1].id1 =
						format_id;
			} else if (use_case == DECODER_CASE) {
				pm[i]->payload->load_unload_info[0].module_type =
						AMDB_MODULE_TYPE_DEPACKETIZER;
				pm[i]->payload->load_unload_info[0].id1 =
					AVS_MODULE_ID_DEPACKETIZER_COP_V1;

				if (format_id == ENC_CODEC_TYPE_LDAC) {
					pm[i]->payload->load_unload_info[0].id1 =
						AVS_MODULE_ID_DEPACKETIZER_COP;
					goto load_unload;
				}

				pm[i]->payload->load_unload_info[1].module_type =
						AMDB_MODULE_TYPE_DECODER;
				pm[i]->payload->load_unload_info[1].id1 =
						format_id;

			} else {
				pr_err("%s:load usecase %d not supported\n",
					 __func__, use_case);
				ret = -EINVAL;
				goto fail;
			}

load_unload:
			ret = q6core_avcs_load_unload_modules(pm[i]->payload,
						 AVCS_LOAD_MODULES);

			if (ret < 0) {
				pr_err("%s: load failed %d\n", __func__, ret);
				goto fail;
			}
			return 0;
		}

	}

	ret = -EINVAL;
	if (i == MAX_ALLOWED_USE_CASES) {
		pr_err("%s: Not enough ports available\n", __func__);
		return ret;
	}
fail:
	kfree(pm[i]->payload);
	pm[i]->payload = NULL;
	kfree(pm[i]);
	pm[i] = NULL;
	return ret;
}

static int afe_get_cal_hw_delay(int32_t path,
				struct audio_cal_hw_delay_entry *entry);
static int remap_cal_data(struct cal_block_data *cal_block, int cal_index);

int afe_get_spk_initial_cal(void)
{
	return this_afe.initial_cal;
}

void afe_get_spk_r0(int *spk_r0)
{
	uint16_t i = 0;

	for (; i < SP_V2_NUM_MAX_SPKRS; i++)
		spk_r0[i] = this_afe.prot_cfg.r0[i];
}

void afe_get_spk_t0(int *spk_t0)
{
	uint16_t i = 0;

	for (; i < SP_V2_NUM_MAX_SPKRS; i++)
		spk_t0[i] = this_afe.prot_cfg.t0[i];
}

int afe_get_spk_v_vali_flag(void)
{
	return this_afe.v_vali_flag;
}

void afe_get_spk_v_vali_sts(int *spk_v_vali_sts)
{
	uint16_t i = 0;

	for (; i < SP_V2_NUM_MAX_SPKRS; i++)
		spk_v_vali_sts[i] =
			this_afe.th_vi_v_vali_resp.param.status[i];
}

void afe_set_spk_initial_cal(int initial_cal)
{
	this_afe.initial_cal = initial_cal;
}

void afe_set_spk_v_vali_flag(int v_vali_flag)
{
	this_afe.v_vali_flag = v_vali_flag;
}

int afe_get_topology(int port_id)
{
	int topology;
	int port_index = afe_get_port_index(port_id);

	if ((port_index < 0) || (port_index >= AFE_MAX_PORTS)) {
		pr_err("%s: Invalid port index %d\n", __func__, port_index);
		topology = -EINVAL;
		goto done;
	}

	topology = this_afe.topology[port_index];
done:
	return topology;
}

/**
 * afe_set_aanc_info -
 *        Update AFE AANC info
 *
 * @q6_aanc_info: AFE AANC info params
 *
 */
void afe_set_aanc_info(struct aanc_data *q6_aanc_info)
{
	this_afe.aanc_info.aanc_active = q6_aanc_info->aanc_active;
	this_afe.aanc_info.aanc_rx_port = q6_aanc_info->aanc_rx_port;
	this_afe.aanc_info.aanc_tx_port = q6_aanc_info->aanc_tx_port;

	pr_debug("%s: aanc active is %d rx port is 0x%x, tx port is 0x%x\n",
		__func__,
		this_afe.aanc_info.aanc_active,
		this_afe.aanc_info.aanc_rx_port,
		this_afe.aanc_info.aanc_tx_port);
}
EXPORT_SYMBOL(afe_set_aanc_info);

static void afe_callback_debug_print(struct apr_client_data *data)
{
	uint32_t *payload;

	payload = data->payload;

	if (data->payload_size >= 8)
		pr_debug("%s: code = 0x%x PL#0[0x%x], PL#1[0x%x], size = %d\n",
			__func__, data->opcode, payload[0], payload[1],
			data->payload_size);
	else if (data->payload_size >= 4)
		pr_debug("%s: code = 0x%x PL#0[0x%x], size = %d\n",
			__func__, data->opcode, payload[0],
			data->payload_size);
	else
		pr_debug("%s: code = 0x%x, size = %d\n",
			__func__, data->opcode, data->payload_size);
}

static void av_dev_drift_afe_cb_handler(uint32_t opcode, uint32_t *payload,
					uint32_t payload_size)
{
	u32 param_id;
	size_t expected_size =
		sizeof(u32) + sizeof(struct afe_param_id_dev_timing_stats);

	/* Get param ID depending on command type */
	param_id = (opcode == AFE_PORT_CMDRSP_GET_PARAM_V3) ? payload[3] :
							      payload[2];
	if (param_id != AFE_PARAM_ID_DEV_TIMING_STATS) {
		pr_err("%s: Unrecognized param ID %d\n", __func__, param_id);
		return;
	}

	switch (opcode) {
	case AFE_PORT_CMDRSP_GET_PARAM_V2:
		expected_size += sizeof(struct param_hdr_v1);
		if (payload_size < expected_size) {
			pr_err("%s: Error: received size %d, expected size %zu\n",
			       __func__, payload_size, expected_size);
			return;
		}
		/* Repack response to add IID */
		this_afe.av_dev_drift_resp.status = payload[0];
		this_afe.av_dev_drift_resp.pdata.module_id = payload[1];
		this_afe.av_dev_drift_resp.pdata.instance_id = INSTANCE_ID_0;
		this_afe.av_dev_drift_resp.pdata.param_id = payload[2];
		this_afe.av_dev_drift_resp.pdata.param_size = payload[3];
		memcpy(&this_afe.av_dev_drift_resp.timing_stats, &payload[4],
		       sizeof(struct afe_param_id_dev_timing_stats));
		break;
	case AFE_PORT_CMDRSP_GET_PARAM_V3:
		expected_size += sizeof(struct param_hdr_v3);
		if (payload_size < expected_size) {
			pr_err("%s: Error: received size %d, expected size %zu\n",
			       __func__, payload_size, expected_size);
			return;
		}
		memcpy(&this_afe.av_dev_drift_resp, payload,
				sizeof(this_afe.av_dev_drift_resp));
		break;
	default:
		pr_err("%s: Unrecognized command %d\n", __func__, opcode);
		return;
	}

	if (!this_afe.av_dev_drift_resp.status) {
		atomic_set(&this_afe.state, 0);
	} else {
		pr_debug("%s: av_dev_drift_resp status: %d\n", __func__,
			 this_afe.av_dev_drift_resp.status);
		atomic_set(&this_afe.state, -1);
	}
}

static void doa_tracking_mon_afe_cb_handler(uint32_t opcode, uint32_t *payload,
					uint32_t payload_size)
{
	size_t expected_size =
		sizeof(u32) + sizeof(struct doa_tracking_mon_param);

	if (payload[0]) {
		atomic_set(&this_afe.status, payload[0]);
		atomic_set(&this_afe.state, 0);
		pr_err("%s: doa_tracking_mon_resp status: %d payload size %d\n",
			__func__, payload[0], payload_size);
		return;
	}

	switch (opcode) {
	case AFE_PORT_CMDRSP_GET_PARAM_V2:
		expected_size += sizeof(struct param_hdr_v1);
		if (payload_size < expected_size) {
			pr_err("%s: Error: received size %d, expected size %zu\n",
				 __func__, payload_size, expected_size);
			return;
		}
		/* Repack response to add IID */
		this_afe.doa_tracking_mon_resp.status = payload[0];
		this_afe.doa_tracking_mon_resp.pdata.module_id = payload[1];
		this_afe.doa_tracking_mon_resp.pdata.instance_id =
			INSTANCE_ID_0;
		this_afe.doa_tracking_mon_resp.pdata.param_id = payload[2];
		this_afe.doa_tracking_mon_resp.pdata.param_size = payload[3];
		memcpy(&this_afe.doa_tracking_mon_resp.doa, &payload[4],
			sizeof(struct doa_tracking_mon_param));
		break;
	case AFE_PORT_CMDRSP_GET_PARAM_V3:
		expected_size += sizeof(struct param_hdr_v3);
		if (payload_size < expected_size) {
			pr_err("%s: Error: received size %d, expected size %zu\n",
				 __func__, payload_size, expected_size);
			return;
		}
		memcpy(&this_afe.doa_tracking_mon_resp, payload,
			sizeof(this_afe.doa_tracking_mon_resp));
		break;
	default:
		pr_err("%s: Unrecognized command %d\n", __func__, opcode);
		return;
	}

	atomic_set(&this_afe.state, 0);
}

static int32_t sp_make_afe_callback(uint32_t opcode, uint32_t *payload,
				    uint32_t payload_size)
{
	struct param_hdr_v3 param_hdr;
	u32 *data_dest = NULL;
	u32 *data_start = NULL;
	size_t expected_size = sizeof(u32);
	uint32_t num_ch = 0;

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

	/* Set command specific details */
	switch (opcode) {
	case AFE_PORT_CMDRSP_GET_PARAM_V2:
		if (payload_size < (5 * sizeof(uint32_t))) {
			pr_err("%s: Error: size %d is less than expected\n",
				__func__, payload_size);
			return -EINVAL;
		}
		expected_size += sizeof(struct param_hdr_v1);
		param_hdr.module_id = payload[1];
		param_hdr.instance_id = INSTANCE_ID_0;
		param_hdr.param_id = payload[2];
		param_hdr.param_size = payload[3];
		data_start = &payload[4];
		break;
	case AFE_PORT_CMDRSP_GET_PARAM_V3:
		if (payload_size < (6 * sizeof(uint32_t))) {
			pr_err("%s: Error: size %d is less than expected\n",
				__func__, payload_size);
			return -EINVAL;
		}
		expected_size += sizeof(struct param_hdr_v3);
		if (payload_size < expected_size) {
			pr_err("%s: Error: size %d is less than expected\n",
				__func__, payload_size);
			return -EINVAL;
		}
		memcpy(&param_hdr, &payload[1], sizeof(struct param_hdr_v3));
		data_start = &payload[5];
		break;
	default:
		pr_err("%s: Unrecognized command %d\n", __func__, opcode);
		return -EINVAL;
	}

	switch (param_hdr.param_id) {
	case AFE_PARAM_ID_CALIB_RES_CFG_V2:
		expected_size += sizeof(struct asm_calib_res_cfg);
		if (param_hdr.param_size != sizeof(struct asm_calib_res_cfg)) {
			pr_err("%s: Error: param_size %d is greater than expected\n",
				__func__,param_hdr.param_size);
			return -EINVAL;
		}
		data_dest = (u32 *) &this_afe.calib_data;
		break;
	case AFE_PARAM_ID_SP_V2_TH_VI_FTM_PARAMS:
		expected_size += sizeof(struct afe_sp_th_vi_ftm_params);
		if (param_hdr.param_size != sizeof(struct afe_sp_th_vi_ftm_params)) {
			pr_err("%s: Error: param_size %d is greater than expected\n",
				__func__,param_hdr.param_size);
			return -EINVAL;
		}
		data_dest = (u32 *) &this_afe.th_vi_resp;
		break;
	case AFE_PARAM_ID_SP_V2_TH_VI_V_VALI_PARAMS:
		expected_size += sizeof(struct afe_sp_th_vi_v_vali_params);
		if (param_hdr.param_size != sizeof(struct afe_sp_th_vi_v_vali_params)) {
			pr_err("%s: Error: param_size %d is greater than expected\n",
				__func__,param_hdr.param_size);
			return -EINVAL;
		}
		data_dest = (u32 *) &this_afe.th_vi_v_vali_resp;
		break;
	case AFE_PARAM_ID_SP_V2_EX_VI_FTM_PARAMS:
		expected_size += sizeof(struct afe_sp_ex_vi_ftm_params);
		if (param_hdr.param_size != sizeof(struct afe_sp_ex_vi_ftm_params)) {
			pr_err("%s: Error: param_size %d is greater than expected\n",
				__func__,param_hdr.param_size);
			return -EINVAL;
		}
		data_dest = (u32 *) &this_afe.ex_vi_resp;
		break;
	case AFE_PARAM_ID_SP_RX_TMAX_XMAX_LOGGING:
		expected_size += sizeof(
				struct afe_sp_rx_tmax_xmax_logging_param);
		if (param_hdr.param_size != sizeof(struct afe_sp_rx_tmax_xmax_logging_param)) {
			pr_err("%s: Error: param_size %d is greater than expected\n",
				__func__,param_hdr.param_size);
			return -EINVAL;
		}
		data_dest = (u32 *) &this_afe.xt_logging_resp;
		break;
	case AFE_PARAM_ID_SP_V4_CALIB_RES_CFG:
		expected_size += sizeof(
				struct afe_sp_v4_param_th_vi_calib_res_cfg);
		if (param_hdr.param_size != sizeof(
				struct afe_sp_v4_param_th_vi_calib_res_cfg)) {
			pr_err("%s: Error: param_size %d is greater than expected\n",
				__func__,param_hdr.param_size);
			return -EINVAL;
		}
		data_dest = (u32 *) &this_afe.spv4_calib_data;
		break;
	case AFE_PARAM_ID_SP_V4_TH_VI_FTM_PARAMS:
		num_ch = data_start[0];
		if (num_ch > SP_V2_NUM_MAX_SPKRS) {
			pr_err("%s: Error: num_ch %d is greater than expected\n",
				__func__,num_ch);
			return -EINVAL;
		}
		if (param_hdr.param_size != (sizeof(struct afe_sp_v4_param_th_vi_ftm_params) +
			(num_ch * sizeof(struct afe_sp_v4_channel_ftm_params)))) {
			pr_err("%s: Error: param_size %d is greater than expected\n",
				__func__,param_hdr.param_size);
			return -EINVAL;
		}
		this_afe.spv4_th_vi_ftm_rcvd_param_size = param_hdr.param_size;
		data_dest = (u32 *)&this_afe.spv4_th_vi_ftm_resp;
		expected_size +=
			sizeof(struct afe_sp_v4_param_th_vi_ftm_params) +
			(num_ch * sizeof(struct afe_sp_v4_channel_ftm_params));
		break;
	case AFE_PARAM_ID_SP_V4_TH_VI_V_VALI_PARAMS:
		num_ch = data_start[0];
		if (num_ch > SP_V2_NUM_MAX_SPKRS) {
			pr_err("%s: Error: num_ch %d is greater than expected\n",
				__func__,num_ch);
			return -EINVAL;
		}
		if (param_hdr.param_size != (sizeof(struct afe_sp_v4_param_th_vi_v_vali_params) +
				(num_ch *
				sizeof(struct afe_sp_v4_channel_v_vali_params)))) {
			pr_err("%s: Error: param_size %d is greater than expected\n",
				__func__,param_hdr.param_size);
			return -EINVAL;
		}
		this_afe.spv4_v_vali_rcvd_param_size = param_hdr.param_size;
		data_dest = (u32 *)&this_afe.spv4_v_vali_resp;
		expected_size +=
			sizeof(struct afe_sp_v4_param_th_vi_v_vali_params) +
			(num_ch *
			sizeof(struct afe_sp_v4_channel_v_vali_params));
		break;
	case AFE_PARAM_ID_SP_V4_EX_VI_FTM_PARAMS:
		num_ch = data_start[0];
		if (num_ch > SP_V2_NUM_MAX_SPKRS) {
			pr_err("%s: Error: num_ch %d is greater than expected\n",
				__func__,num_ch);
			return -EINVAL;
		}
		if (param_hdr.param_size !=  (sizeof(struct afe_sp_v4_param_ex_vi_ftm_params) +
				(num_ch *
				sizeof(struct afe_sp_v4_channel_ex_vi_ftm_params)))) {
			pr_err("%s: Error: param_size %d is greater than expected\n",
				__func__,param_hdr.param_size);
			return -EINVAL;
		}
		this_afe.spv4_ex_vi_ftm_rcvd_param_size = param_hdr.param_size;
		data_dest = (u32 *)&this_afe.spv4_ex_vi_ftm_resp;
		expected_size +=
		  sizeof(struct afe_sp_v4_param_ex_vi_ftm_params) +
		  (num_ch * sizeof(struct afe_sp_v4_channel_ex_vi_ftm_params));
		break;
	case AFE_PARAM_ID_SP_V4_RX_TMAX_XMAX_LOGGING:
		num_ch = data_start[0];
		if (num_ch > SP_V2_NUM_MAX_SPKRS) {
			pr_err("%s: Error: num_ch %d is greater than expected\n",
				__func__,num_ch);
			return -EINVAL;
		}
		if (param_hdr.param_size != (sizeof(struct afe_sp_v4_param_tmax_xmax_logging) +
				(num_ch *
				sizeof(struct afe_sp_v4_channel_tmax_xmax_params)))) {
			pr_err("%s: Error: param_size %d is greater than expected\n",
				__func__,param_hdr.param_size);
			return -EINVAL;
		}
		this_afe.spv4_max_log_rcvd_param_size = param_hdr.param_size;
		data_dest = (u32 *)&this_afe.spv4_max_log_resp;
		expected_size +=
		  sizeof(struct afe_sp_v4_param_tmax_xmax_logging) +
		  (num_ch * sizeof(struct afe_sp_v4_channel_tmax_xmax_params));
		break;
	default:
		pr_err("%s: Unrecognized param ID %d\n", __func__,
		       param_hdr.param_id);
		return -EINVAL;
	}

	if (!data_dest)
		return -ENOMEM;

	if (payload_size < expected_size) {
		pr_err(
		"%s: Error: received size %d, expected size %zu for param %d\n",
		__func__, payload_size, expected_size,
		param_hdr.param_id);
		return -EINVAL;
	}

	data_dest[0] = payload[0];
	memcpy(&data_dest[1], &param_hdr, sizeof(struct param_hdr_v3));
	memcpy(&data_dest[5], data_start, param_hdr.param_size);

	if (!data_dest[0]) {
		atomic_set(&this_afe.state, 0);
	} else {
		pr_debug("%s: status: %d", __func__, data_dest[0]);
		atomic_set(&this_afe.state, -1);
	}

	return 0;
}

static void afe_notify_dc_presence(void)
{
	pr_debug("%s: DC detected\n", __func__);
	msm_aud_evt_notifier_call_chain(MSM_AUD_DC_EVENT, NULL);

	schedule_work(&this_afe.afe_dc_work);
}

static void afe_notify_dc_presence_work_fn(struct work_struct *work)
{
	int ret = 0;
	char event[] = "DC_PRESENCE=TRUE";

	ret = q6core_send_uevent(this_afe.uevent_data, event);
	if (ret)
		pr_err("%s: Send UEvent %s failed :%d\n",
		       __func__, event, ret);
}

static int afe_aud_event_notify(struct notifier_block *self,
				unsigned long action, void *data)
{
	switch (action) {
	case SWR_WAKE_IRQ_REGISTER:
		afe_send_cmd_wakeup_register(data, true);
		break;
	case SWR_WAKE_IRQ_DEREGISTER:
		afe_send_cmd_wakeup_register(data, false);
		break;
	default:
		pr_err("%s: invalid event type: %lu\n", __func__, action);
		return -EINVAL;
	}

	return 0;
}

static void afe_notify_spdif_fmt_update_work_fn(struct work_struct *work)
{
	int ret = 0;
	char event_pri[] = "PRI_SPDIF_TX=MEDIA_CONFIG_CHANGE";
	char event_sec[] = "SEC_SPDIF_TX=MEDIA_CONFIG_CHANGE";

	if (this_afe.pri_spdif_config_change) {
		this_afe.pri_spdif_config_change = 0;
		ret = q6core_send_uevent(this_afe.uevent_data, event_pri);
		if (ret)
			pr_err("%s: Send UEvent %s failed :%d\n",
			       __func__, event_pri, ret);
	}
	if (this_afe.sec_spdif_config_change) {
		this_afe.sec_spdif_config_change = 0;
		ret = q6core_send_uevent(this_afe.uevent_data, event_sec);
		if (ret)
			pr_err("%s: Send UEvent %s failed :%d\n",
			       __func__, event_sec, ret);
	}
}

static void afe_notify_spdif_fmt_update(void *payload)
{
	struct afe_port_mod_evt_rsp_hdr *evt_pl;

	evt_pl = (struct afe_port_mod_evt_rsp_hdr *)payload;
	if (evt_pl->port_id == AFE_PORT_ID_PRIMARY_SPDIF_TX)
		this_afe.pri_spdif_config_change = 1;
	else
		this_afe.sec_spdif_config_change = 1;

	schedule_work(&this_afe.afe_spdif_work);
}

static bool afe_token_is_valid(uint32_t token)
{
	if (token >= AFE_MAX_PORTS) {
		pr_err("%s: token %d is invalid.\n", __func__, token);
		return false;
	}
	return true;
}

static int32_t afe_callback(struct apr_client_data *data, void *priv)
{
	uint16_t i = 0;

	if (!data) {
		pr_err("%s: Invalid param data\n", __func__);
		return -EINVAL;
	}
	if (data->opcode == RESET_EVENTS) {
		pr_debug("%s: reset event = %d %d apr[%pK]\n",
			__func__,
			data->reset_event, data->reset_proc, this_afe.apr);

		cal_utils_clear_cal_block_q6maps(MAX_AFE_CAL_TYPES,
			this_afe.cal_data);

		/* Reset the custom topology mode: to resend again to AFE. */
		mutex_lock(&this_afe.cal_data[AFE_CUST_TOPOLOGY_CAL]->lock);
		this_afe.set_custom_topology = 1;
		mutex_unlock(&this_afe.cal_data[AFE_CUST_TOPOLOGY_CAL]->lock);
		rtac_clear_mapping(AFE_RTAC_CAL);

		if (this_afe.apr) {
			apr_reset(this_afe.apr);
			atomic_set(&this_afe.state, 0);
			this_afe.apr = NULL;
			rtac_set_afe_handle(this_afe.apr);
		}

		/* Reset the core client handle in SSR/PDR use cases */
		mutex_lock(&this_afe.afe_cmd_lock);
		for (i = 0; i < AFE_LPASS_CORE_HW_VOTE_MAX; i++)
			this_afe.lpass_hw_core_client_hdl[i] = 0;
		mutex_unlock(&this_afe.afe_cmd_lock);

		/*
		 * Pass reset events to proxy driver, if cb is registered
		 */
		if (this_afe.tx_cb) {
			this_afe.tx_cb(data->opcode, data->token,
					data->payload,
					this_afe.tx_private_data);
			this_afe.tx_cb = NULL;
		}
		if (this_afe.rx_cb) {
			this_afe.rx_cb(data->opcode, data->token,
					data->payload,
					this_afe.rx_private_data);
			this_afe.rx_cb = NULL;
		}

		return 0;
	}
	afe_callback_debug_print(data);
	if (data->opcode == AFE_PORT_CMDRSP_GET_PARAM_V2 ||
	    data->opcode == AFE_PORT_CMDRSP_GET_PARAM_V3) {
		uint32_t *payload = data->payload;
		uint32_t param_id;
		uint32_t param_id_pos = 0;

		if (!payload || (data->token >= AFE_MAX_PORTS)) {
			pr_err("%s: Error: size %d payload %pK token %d\n",
				__func__, data->payload_size,
				payload, data->token);
			return -EINVAL;
		}

		if (rtac_make_afe_callback(data->payload,
					   data->payload_size))
			return 0;

		if (data->opcode == AFE_PORT_CMDRSP_GET_PARAM_V3)
			param_id_pos = 4;
		else
			param_id_pos = 3;

		if (data->payload_size >= param_id_pos * sizeof(uint32_t))
				param_id = payload[param_id_pos - 1];
		else {
			pr_err("%s: Error: size %d is less than expected\n",
				__func__, data->payload_size);
			return -EINVAL;
		}

		if (param_id == AUDPROC_PARAM_ID_FFV_DOA_TRACKING_MONITOR) {
			doa_tracking_mon_afe_cb_handler(data->opcode,
				data->payload, data->payload_size);
		} else if (param_id == AFE_PARAM_ID_DEV_TIMING_STATS) {
			av_dev_drift_afe_cb_handler(data->opcode, data->payload,
						    data->payload_size);
		} else {
#if IS_ENABLED(CONFIG_TAS25XX_ALGO)
			u32 *payload32 = data->payload;
			pr_debug("TI-SmartPA: payload1 = 0x%x, 0x%x", payload32[0], payload32[1]);

			if ((payload32[1] == this_afe.tas_module_rx) ||
			   (payload32[1] == this_afe.tas_module_tx)) {
#ifdef INSTANCE_ID_0 /*APR Version 3*/
				if (tas_smartamp_algo_callback(data->opcode, data->payload, data->payload_size))
					return -EINVAL;
#else /*APR Version 2*/
				if (tas_smartamp_algo_callback(data->payload, data->payload_size))
					return -EINVAL;
#endif /* INSTANCE_ID_0 */
			} else if (sp_make_afe_callback(data->opcode, data->payload,
						 data->payload_size)) {
				return -EINVAL;
			}
#else
			if (sp_make_afe_callback(data->opcode, data->payload,
						 data->payload_size))
				return -EINVAL;
#endif /*CONFIG_TAS25XX_ALGO*/
		}
		if (afe_token_is_valid(data->token))
			wake_up(&this_afe.wait[data->token]);
		else
			return -EINVAL;
	} else if (data->opcode == AFE_EVENT_MBHC_DETECTION_SW_WA) {
		msm_aud_evt_notifier_call_chain(SWR_WAKE_IRQ_EVENT, NULL);
	} else if (data->opcode ==
			AFE_CMD_RSP_REMOTE_LPASS_CORE_HW_VOTE_REQUEST) {
		uint32_t *payload = data->payload;

		pr_debug("%s: AFE_CMD_RSP_REMOTE_LPASS_CORE_HW_VOTE_REQUEST handle %d\n",
			__func__, payload[0]);
		if (data->token < AFE_LPASS_CORE_HW_VOTE_MAX)
			this_afe.lpass_hw_core_client_hdl[data->token] =
								payload[0];
		atomic_set(&this_afe.clk_state, 0);
		atomic_set(&this_afe.clk_status, 0);
		wake_up(&this_afe.lpass_core_hw_wait);
	} else if (data->payload_size) {
		uint32_t *payload;
		uint16_t port_id = 0;

		payload = data->payload;
		if (data->opcode == APR_BASIC_RSP_RESULT) {
			if (data->payload_size < (2 * sizeof(uint32_t))) {
				pr_err("%s: Error: size %d is less than expected\n",
					__func__, data->payload_size);
				return -EINVAL;
			}
			pr_debug("%s:opcode = 0x%x cmd = 0x%x status = 0x%x token=%d\n",
				__func__, data->opcode,
				payload[0], payload[1], data->token);
			/* payload[1] contains the error status for response */
			if (payload[1] != 0) {
				if(data->token == AFE_CLK_TOKEN)
					atomic_set(&this_afe.clk_status, payload[1]);
				else
					atomic_set(&this_afe.status, payload[1]);
				pr_err("%s: cmd = 0x%x returned error = 0x%x\n",
					__func__, payload[0], payload[1]);
			}
			switch (payload[0]) {
			case AFE_PORT_CMD_SET_PARAM_V2:
			case AFE_PORT_CMD_SET_PARAM_V3:
				if (rtac_make_afe_callback(payload,
							   data->payload_size))
					return 0;
			case AFE_PORT_CMD_DEVICE_STOP:
			case AFE_PORT_CMD_DEVICE_START:
			case AFE_PSEUDOPORT_CMD_START:
			case AFE_PSEUDOPORT_CMD_STOP:
			case AFE_SERVICE_CMD_SHARED_MEM_MAP_REGIONS:
			case AFE_SERVICE_CMD_SHARED_MEM_UNMAP_REGIONS:
			case AFE_SERVICE_CMD_UNREGISTER_RT_PORT_DRIVER:
			case AFE_PORTS_CMD_DTMF_CTL:
			case AFE_SVC_CMD_SET_PARAM:
			case AFE_SVC_CMD_SET_PARAM_V2:
			case AFE_PORT_CMD_MOD_EVENT_CFG:
				if(data->token == AFE_CLK_TOKEN) {
					atomic_set(&this_afe.clk_state, 0);
					wake_up(&this_afe.clk_wait);
				} else {
					atomic_set(&this_afe.state, 0);
					if (afe_token_is_valid(data->token))
						wake_up(&this_afe.wait[data->token]);
					else
						return -EINVAL;
				}
				break;
			case AFE_SERVICE_CMD_REGISTER_RT_PORT_DRIVER:
				break;
			case AFE_PORT_DATA_CMD_RT_PROXY_PORT_WRITE_V2:
				port_id = RT_PROXY_PORT_001_TX;
				break;
			case AFE_PORT_DATA_CMD_RT_PROXY_PORT_READ_V2:
				port_id = RT_PROXY_PORT_001_RX;
				break;
			case AFE_CMD_ADD_TOPOLOGIES:
				atomic_set(&this_afe.state, 0);
				if (afe_token_is_valid(data->token))
					wake_up(&this_afe.wait[data->token]);
				else
					return -EINVAL;
				pr_debug("%s: AFE_CMD_ADD_TOPOLOGIES cmd 0x%x\n",
						__func__, payload[1]);
				break;
			case AFE_PORT_CMD_GET_PARAM_V2:
			case AFE_PORT_CMD_GET_PARAM_V3:
				/*
				 * Should only come here if there is an APR
				 * error or malformed APR packet. Otherwise
				 * response will be returned as
				 * AFE_PORT_CMDRSP_GET_PARAM_V2/3
				 */
				pr_debug("%s: AFE Get Param opcode 0x%x token 0x%x src %d dest %d\n",
					__func__, data->opcode, data->token,
					data->src_port, data->dest_port);
				if (payload[1] != 0) {
					pr_err("%s: AFE Get Param failed with error %d\n",
					       __func__, payload[1]);
					if (rtac_make_afe_callback(
						    payload,
						    data->payload_size))
						return 0;
				}
				atomic_set(&this_afe.state, payload[1]);
				if (afe_token_is_valid(data->token))
					wake_up(&this_afe.wait[data->token]);
				else
					return -EINVAL;
				break;
			case AFE_CMD_REMOTE_LPASS_CORE_HW_VOTE_REQUEST:
			case AFE_CMD_REMOTE_LPASS_CORE_HW_DEVOTE_REQUEST:
				atomic_set(&this_afe.clk_state, 0);
				if (payload[1] != 0)
					atomic_set(&this_afe.clk_status,
							payload[1]);
				wake_up(&this_afe.lpass_core_hw_wait);
				break;
			case AFE_SVC_CMD_EVENT_CFG:
				atomic_set(&this_afe.state, payload[1]);
				wake_up(&this_afe.wait_wakeup);
				break;
			default:
				pr_err("%s: Unknown cmd 0x%x\n", __func__,
						payload[0]);
				break;
			}
		} else if (data->opcode ==
				AFE_SERVICE_CMDRSP_SHARED_MEM_MAP_REGIONS) {
			pr_debug("%s: mmap_handle: 0x%x, cal index %d\n",
				 __func__, payload[0],
				 atomic_read(&this_afe.mem_map_cal_index));
			if (atomic_read(&this_afe.mem_map_cal_index) != -1)
				atomic_set(&this_afe.mem_map_cal_handles[
					atomic_read(
					&this_afe.mem_map_cal_index)],
					(uint32_t)payload[0]);
			else
				this_afe.mmap_handle = payload[0];
			atomic_set(&this_afe.state, 0);
			if (afe_token_is_valid(data->token))
				wake_up(&this_afe.wait[data->token]);
			else
				return -EINVAL;
		} else if (data->opcode == AFE_EVENT_RT_PROXY_PORT_STATUS) {
			port_id = (uint16_t)(0x0000FFFF & payload[0]);
		} else if (data->opcode == AFE_PORT_MOD_EVENT) {
			u32 flag_dc_presence[2];
			uint32_t *payload = data->payload;
			struct afe_port_mod_evt_rsp_hdr *evt_pl =
				(struct afe_port_mod_evt_rsp_hdr *)payload;

			if (!payload || (data->token >= AFE_MAX_PORTS)) {
				pr_err("%s: Error: size %d payload %pK token %d\n",
					__func__, data->payload_size,
					payload, data->token);
				return -EINVAL;
			}
			if ((evt_pl->module_id == AFE_MODULE_SPEAKER_PROTECTION_V2_EX_VI) &&
			    (evt_pl->event_id == AFE_PORT_SP_DC_DETECTION_EVENT) &&
			    (evt_pl->payload_size == sizeof(flag_dc_presence))) {

				memcpy(&flag_dc_presence,
					(uint8_t *)payload +
					sizeof(struct afe_port_mod_evt_rsp_hdr),
					evt_pl->payload_size);
				if (flag_dc_presence[0] == 1 ||
					flag_dc_presence[1] == 1) {
					afe_notify_dc_presence();
				}
			} else if ((evt_pl->module_id ==
					 AFE_MODULE_SPEAKER_PROTECTION_V4_VI) &&
				(evt_pl->event_id ==
					 AFE_PORT_SP_DC_DETECTION_EVENT)) {
				bool dc_detected = false;
				uint32_t *num_channels =
				    (uint32_t *)((uint8_t *)payload +
				    sizeof(struct afe_port_mod_evt_rsp_hdr));
				uint32_t *dc_presence_flag = num_channels + 1;

				for (i = 0; i < *num_channels; i++) {
					if (dc_presence_flag[i] == 1)
						dc_detected = true;
				}
				if (dc_detected)
					afe_notify_dc_presence();
			} else if (evt_pl->port_id == AFE_PORT_ID_PRIMARY_SPDIF_TX) {
				if (this_afe.pri_spdif_tx_cb) {
					this_afe.pri_spdif_tx_cb(data->opcode,
						data->token, data->payload,
						this_afe.pri_spdif_tx_private_data);
				}
				afe_notify_spdif_fmt_update(data->payload);
			} else if (evt_pl->port_id == AFE_PORT_ID_SECONDARY_SPDIF_TX) {
				if (this_afe.sec_spdif_tx_cb) {
					this_afe.sec_spdif_tx_cb(data->opcode,
						data->token, data->payload,
						this_afe.sec_spdif_tx_private_data);
				}
				afe_notify_spdif_fmt_update(data->payload);
			} else {
				pr_debug("%s: mod ID = 0x%x event_id = 0x%x\n",
						__func__, evt_pl->module_id,
						evt_pl->event_id);
			}
		}
		pr_debug("%s: port_id = 0x%x\n", __func__, port_id);
		switch (port_id) {
		case RT_PROXY_PORT_001_TX: {
			if (this_afe.tx_cb) {
				this_afe.tx_cb(data->opcode, data->token,
					data->payload,
					this_afe.tx_private_data);
			}
			break;
		}
		case RT_PROXY_PORT_001_RX: {
			if (this_afe.rx_cb) {
				this_afe.rx_cb(data->opcode, data->token,
					data->payload,
					this_afe.rx_private_data);
			}
			break;
		}
		default:
			pr_debug("%s: default case 0x%x\n", __func__, port_id);
			break;
		}
	}
	return 0;
}

/**
 * afe_get_port_type -
 *        Retrieve AFE port type whether RX or TX
 *
 * @port_id: AFE Port ID number
 *
 * Returns RX/TX type.
 */
int afe_get_port_type(u16 port_id)
{
	int ret = MSM_AFE_PORT_TYPE_RX;

	switch (port_id) {
	case VOICE_RECORD_RX:
	case VOICE_RECORD_TX:
		ret = MSM_AFE_PORT_TYPE_TX;
		break;
	case VOICE_PLAYBACK_TX:
	case VOICE2_PLAYBACK_TX:
		ret = MSM_AFE_PORT_TYPE_RX;
		break;
	default:
		/* Odd numbered ports are TX and Rx are Even numbered */
		if (port_id & 0x1)
			ret = MSM_AFE_PORT_TYPE_TX;
		else
			ret = MSM_AFE_PORT_TYPE_RX;
		break;
	}

	return ret;
}
EXPORT_SYMBOL(afe_get_port_type);

int afe_sizeof_cfg_cmd(u16 port_id)
{
	int ret_size;

	switch (port_id) {
	case PRIMARY_I2S_RX:
	case PRIMARY_I2S_TX:
	case SECONDARY_I2S_RX:
	case SECONDARY_I2S_TX:
	case MI2S_RX:
	case MI2S_TX:
	case AFE_PORT_ID_PRIMARY_MI2S_RX:
	case AFE_PORT_ID_PRIMARY_MI2S_TX:
	case AFE_PORT_ID_QUATERNARY_MI2S_RX:
	case AFE_PORT_ID_QUATERNARY_MI2S_TX:
	case AFE_PORT_ID_QUINARY_MI2S_RX:
	case AFE_PORT_ID_QUINARY_MI2S_TX:
	case AFE_PORT_ID_SENARY_MI2S_RX:
	case AFE_PORT_ID_SENARY_MI2S_TX:
		ret_size = SIZEOF_CFG_CMD(afe_param_id_i2s_cfg);
		break;
	case AFE_PORT_ID_PRIMARY_META_MI2S_RX:
	case AFE_PORT_ID_SECONDARY_META_MI2S_RX:
		ret_size = SIZEOF_CFG_CMD(afe_param_id_meta_i2s_cfg);
		break;
	case HDMI_RX:
	case HDMI_RX_MS:
	case DISPLAY_PORT_RX:
		ret_size =
		SIZEOF_CFG_CMD(afe_param_id_hdmi_multi_chan_audio_cfg);
		break;
	case AFE_PORT_ID_PRIMARY_SPDIF_RX:
	case AFE_PORT_ID_PRIMARY_SPDIF_TX:
	case AFE_PORT_ID_SECONDARY_SPDIF_RX:
	case AFE_PORT_ID_SECONDARY_SPDIF_TX:
		ret_size =
		SIZEOF_CFG_CMD(afe_param_id_spdif_cfg_v2);
		break;
	case SLIMBUS_0_RX:
	case SLIMBUS_0_TX:
	case SLIMBUS_1_RX:
	case SLIMBUS_1_TX:
	case SLIMBUS_2_RX:
	case SLIMBUS_2_TX:
	case SLIMBUS_3_RX:
	case SLIMBUS_3_TX:
	case SLIMBUS_4_RX:
	case SLIMBUS_4_TX:
	case SLIMBUS_5_RX:
	case SLIMBUS_5_TX:
	case SLIMBUS_6_RX:
	case SLIMBUS_6_TX:
	case SLIMBUS_7_RX:
	case SLIMBUS_7_TX:
	case SLIMBUS_8_RX:
	case SLIMBUS_8_TX:
	case SLIMBUS_9_RX:
	case SLIMBUS_9_TX:
		ret_size = SIZEOF_CFG_CMD(afe_param_id_slimbus_cfg);
		break;
	case VOICE_PLAYBACK_TX:
	case VOICE2_PLAYBACK_TX:
	case VOICE_RECORD_RX:
	case VOICE_RECORD_TX:
		ret_size = SIZEOF_CFG_CMD(afe_param_id_pseudo_port_cfg);
		break;
	case RT_PROXY_PORT_001_RX:
	case RT_PROXY_PORT_001_TX:
	case RT_PROXY_PORT_002_RX:
	case RT_PROXY_PORT_002_TX:
		ret_size = SIZEOF_CFG_CMD(afe_param_id_rt_proxy_port_cfg);
		break;
	case AFE_PORT_ID_USB_RX:
	case AFE_PORT_ID_USB_TX:
		ret_size = SIZEOF_CFG_CMD(afe_param_id_usb_audio_cfg);
		break;
	case AFE_PORT_ID_WSA_CODEC_DMA_RX_0:
	case AFE_PORT_ID_WSA_CODEC_DMA_TX_0:
	case AFE_PORT_ID_WSA_CODEC_DMA_RX_1:
	case AFE_PORT_ID_WSA_CODEC_DMA_TX_1:
	case AFE_PORT_ID_WSA_CODEC_DMA_TX_2:
	case AFE_PORT_ID_VA_CODEC_DMA_TX_0:
	case AFE_PORT_ID_VA_CODEC_DMA_TX_1:
	case AFE_PORT_ID_VA_CODEC_DMA_TX_2:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_0:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_0:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_1:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_1:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_2:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_2:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_3:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_3:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_4:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_4:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_5:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_5:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_6:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_7:
		ret_size = SIZEOF_CFG_CMD(afe_param_id_cdc_dma_cfg_t);
		break;
	case AFE_PORT_ID_PRIMARY_PCM_RX:
	case AFE_PORT_ID_PRIMARY_PCM_TX:
	case AFE_PORT_ID_SECONDARY_PCM_RX:
	case AFE_PORT_ID_SECONDARY_PCM_TX:
	case AFE_PORT_ID_TERTIARY_PCM_RX:
	case AFE_PORT_ID_TERTIARY_PCM_TX:
	case AFE_PORT_ID_QUATERNARY_PCM_RX:
	case AFE_PORT_ID_QUATERNARY_PCM_TX:
	case AFE_PORT_ID_QUINARY_PCM_RX:
	case AFE_PORT_ID_QUINARY_PCM_TX:
	case AFE_PORT_ID_SENARY_PCM_RX:
	case AFE_PORT_ID_SENARY_PCM_TX:
	default:
		pr_debug("%s: default case 0x%x\n", __func__, port_id);
		ret_size = SIZEOF_CFG_CMD(afe_param_id_pcm_cfg);
		break;
	}
	return ret_size;
}

/**
 * afe_q6_interface_prepare -
 *        wrapper API to check Q6 AFE registered to APR otherwise registers
 *
 * Returns 0 on success or error on failure.
 */
int afe_q6_interface_prepare(void)
{
	int ret = 0;

	pr_debug("%s:\n", __func__);

	if (this_afe.apr == NULL) {
		this_afe.apr = apr_register("ADSP", "AFE", afe_callback,
			0xFFFFFFFF, &this_afe);
		if (this_afe.apr == NULL) {
			pr_err("%s: Unable to register AFE\n", __func__);
			ret = -ENETRESET;
		}
		rtac_set_afe_handle(this_afe.apr);
	}
	return ret;
}
EXPORT_SYMBOL(afe_q6_interface_prepare);

/*
 * afe_apr_send_pkt : returns 0 on success, negative otherwise.
 */
static int afe_apr_send_pkt(void *data, wait_queue_head_t *wait)
{
	int ret;

	mutex_lock(&this_afe.afe_apr_lock);
	if (wait)
		atomic_set(&this_afe.state, 1);
	atomic_set(&this_afe.status, 0);
	ret = apr_send_pkt(this_afe.apr, data);
	if (ret > 0) {
		if (wait) {
			ret = wait_event_timeout(*wait,
					(atomic_read(&this_afe.state) == 0),
					msecs_to_jiffies(2 * TIMEOUT_MS));
			if (!ret) {
				pr_err_ratelimited("%s: request timedout\n",
					__func__);
				ret = -ETIMEDOUT;
				trace_printk("%s: wait for ADSP response timed out\n",
					__func__);
			} else if (atomic_read(&this_afe.status) > 0) {
				pr_err("%s: DSP returned error[%s]\n", __func__,
					adsp_err_get_err_str(atomic_read(
					&this_afe.status)));
				ret = adsp_err_get_lnx_err_code(
						atomic_read(&this_afe.status));
			} else {
				ret = 0;
			}
		} else {
			ret = 0;
		}
	} else if (ret == 0) {
		pr_err("%s: packet not transmitted\n", __func__);
		/* apr_send_pkt can return 0 when nothing is transmitted */
		ret = -EINVAL;
	}

	pr_debug("%s: leave %d\n", __func__, ret);
	mutex_unlock(&this_afe.afe_apr_lock);
	return ret;
}
/*
 * afe_apr_send_clk_pkt : returns 0 on success, negative otherwise.
 */
static int afe_apr_send_clk_pkt(void *data, wait_queue_head_t *wait)
{
	int ret;

	if (wait)
		atomic_set(&this_afe.clk_state, 1);
	atomic_set(&this_afe.clk_status, 0);
	ret = apr_send_pkt(this_afe.apr, data);
	if (ret > 0) {
		if (wait) {
			ret = wait_event_timeout(*wait,
					(atomic_read(&this_afe.clk_state) == 0),
					msecs_to_jiffies(2 * TIMEOUT_MS));
			if (!ret) {
				pr_err("%s: timeout\n", __func__);
				ret = -ETIMEDOUT;
			} else if (atomic_read(&this_afe.clk_status) > 0) {
				pr_err("%s: DSP returned error[%s]\n", __func__,
					adsp_err_get_err_str(atomic_read(
					&this_afe.clk_status)));
				ret = adsp_err_get_lnx_err_code(
						atomic_read(&this_afe.clk_status));
			} else {
				ret = 0;
			}
		} else {
			ret = 0;
		}
	} else if (ret == 0) {
		pr_err("%s: packet not transmitted\n", __func__);
		/* apr_send_pkt can return 0 when nothing is transmitted */
		ret = -EINVAL;
	}

	pr_debug("%s: leave %d\n", __func__, ret);
	return ret;
}

/* This function shouldn't be called directly. Instead call q6afe_set_params. */
static int q6afe_set_params_v2(u16 port_id, int index,
			       struct mem_mapping_hdr *mem_hdr,
			       u8 *packed_param_data, u32 packed_data_size)
{
	struct afe_port_cmd_set_param_v2 *set_param = NULL;
	uint32_t size = sizeof(struct afe_port_cmd_set_param_v2);
	int rc = 0;

	if (packed_param_data != NULL)
		size += packed_data_size;
	set_param = kzalloc(size, GFP_KERNEL);
	if (set_param == NULL)
		return -ENOMEM;

	set_param->apr_hdr.hdr_field =
		APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE),
			      APR_PKT_VER);
	set_param->apr_hdr.pkt_size = size;
	set_param->apr_hdr.src_port = 0;
	set_param->apr_hdr.dest_port = 0;
	set_param->apr_hdr.token = index;
	set_param->apr_hdr.opcode = AFE_PORT_CMD_SET_PARAM_V2;
	set_param->port_id = port_id;
	if (packed_data_size > U16_MAX) {
		pr_err("%s: Invalid data size for set params V2 %d\n", __func__,
		       packed_data_size);
		rc = -EINVAL;
		goto done;
	}
	set_param->payload_size = packed_data_size;
	if (mem_hdr != NULL) {
		set_param->mem_hdr = *mem_hdr;
	} else if (packed_param_data != NULL) {
		memcpy(&set_param->param_data, packed_param_data,
		       packed_data_size);
	} else {
		pr_err("%s: Both memory header and param data are NULL\n",
		       __func__);
		rc = -EINVAL;
		goto done;
	}

	rc = afe_apr_send_pkt(set_param, &this_afe.wait[index]);
done:
	kfree(set_param);
	return rc;
}

/* This function shouldn't be called directly. Instead call q6afe_set_params. */
static int q6afe_set_params_v3(u16 port_id, int index,
			       struct mem_mapping_hdr *mem_hdr,
			       u8 *packed_param_data, u32 packed_data_size)
{
	struct afe_port_cmd_set_param_v3 *set_param = NULL;
	uint32_t size = sizeof(struct afe_port_cmd_set_param_v3);
	int rc = 0;

	if (packed_param_data != NULL)
		size += packed_data_size;
	set_param = kzalloc(size, GFP_KERNEL);
	if (set_param == NULL)
		return -ENOMEM;

	set_param->apr_hdr.hdr_field =
		APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE),
			      APR_PKT_VER);
	set_param->apr_hdr.pkt_size = size;
	set_param->apr_hdr.src_port = 0;
	set_param->apr_hdr.dest_port = 0;
	set_param->apr_hdr.token = index;
	set_param->apr_hdr.opcode = AFE_PORT_CMD_SET_PARAM_V3;
	set_param->port_id = port_id;
	set_param->payload_size = packed_data_size;
	if (mem_hdr != NULL) {
		set_param->mem_hdr = *mem_hdr;
	} else if (packed_param_data != NULL) {
		memcpy(&set_param->param_data, packed_param_data,
		       packed_data_size);
	} else {
		pr_err("%s: Both memory header and param data are NULL\n",
		       __func__);
		rc = -EINVAL;
		goto done;
	}

	rc = afe_apr_send_pkt(set_param, &this_afe.wait[index]);
done:
	kfree(set_param);
	return rc;
}

static int q6afe_set_params(u16 port_id, int index,
			    struct mem_mapping_hdr *mem_hdr,
			    u8 *packed_param_data, u32 packed_data_size)
{
	int ret = 0;

	ret = afe_q6_interface_prepare();
	if (ret != 0) {
		pr_err("%s: Q6 interface prepare failed %d\n", __func__, ret);
		return ret;
	}

	port_id = q6audio_get_port_id(port_id);
	ret = q6audio_validate_port(port_id);
	if (ret < 0) {
		pr_err("%s: Not a valid port id = 0x%x ret %d\n", __func__,
		       port_id, ret);
		return -EINVAL;
	}

	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid\n", __func__, index);
		return -EINVAL;
	}

	if (q6common_is_instance_id_supported())
		return q6afe_set_params_v3(port_id, index, mem_hdr,
					   packed_param_data, packed_data_size);
	else
		return q6afe_set_params_v2(port_id, index, mem_hdr,
					   packed_param_data, packed_data_size);
}

static int q6afe_pack_and_set_param_in_band(u16 port_id, int index,
					    struct param_hdr_v3 param_hdr,
					    u8 *param_data)
{
	u8 *packed_param_data = NULL;
	int packed_data_size = sizeof(union param_hdrs) + param_hdr.param_size;
	int ret;

	packed_param_data = kzalloc(packed_data_size, GFP_KERNEL);
	if (packed_param_data == NULL)
		return -ENOMEM;

	ret = q6common_pack_pp_params(packed_param_data, &param_hdr, param_data,
				      &packed_data_size);
	if (ret) {
		pr_err("%s: Failed to pack param header and data, error %d\n",
		       __func__, ret);
		goto fail_cmd;
	}

	ret = q6afe_set_params(port_id, index, NULL, packed_param_data,
			       packed_data_size);

fail_cmd:
	kfree(packed_param_data);
	return ret;
}

static int q6afe_set_aanc_level(void)
{
	struct param_hdr_v3 param_hdr;
	struct afe_param_id_aanc_noise_reduction aanc_noise_level;
	int ret = 0;
	uint16_t tx_port = 0;

	if (!this_afe.aanc_info.aanc_active)
		return -EINVAL;

	pr_debug("%s: level: %d\n", __func__, this_afe.aanc_info.level);
	memset(&aanc_noise_level, 0, sizeof(aanc_noise_level));
	aanc_noise_level.minor_version = 1;
	aanc_noise_level.ad_beta = this_afe.aanc_info.level;

	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_AANC;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_AANC_NOISE_REDUCTION;
	param_hdr.param_size = sizeof(struct afe_param_id_aanc_noise_reduction);

	tx_port = this_afe.aanc_info.aanc_tx_port;
	ret = q6afe_pack_and_set_param_in_band(tx_port,
					       q6audio_get_port_index(tx_port),
					       param_hdr,
					       (u8 *) &aanc_noise_level);
	if (ret)
		pr_err("%s: AANC noise level enable failed for tx_port 0x%x ret %d\n",
			__func__, tx_port, ret);
	return ret;
}

/**
 * afe_set_aanc_noise_level - controls aanc noise reduction strength
 *
 * @level: Noise level to be controlled
 *
 * Returns 0 on success or error on failure.
 */
int afe_set_aanc_noise_level(int level)
{
	int ret = 0;

	if (this_afe.aanc_info.level == level)
		return ret;

	mutex_lock(&this_afe.afe_cmd_lock);
	this_afe.aanc_info.level = level;
	ret = q6afe_set_aanc_level();
	mutex_unlock(&this_afe.afe_cmd_lock);

	return ret;
}
EXPORT_SYMBOL(afe_set_aanc_noise_level);

/* This function shouldn't be called directly. Instead call q6afe_get_param. */
static int q6afe_get_params_v2(u16 port_id, int index,
			       struct mem_mapping_hdr *mem_hdr,
			       struct param_hdr_v3 *param_hdr)
{
	struct afe_port_cmd_get_param_v2 afe_get_param;
	u32 param_size = param_hdr->param_size;

	memset(&afe_get_param, 0, sizeof(afe_get_param));
	afe_get_param.apr_hdr.hdr_field =
		APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE),
			      APR_PKT_VER);
	afe_get_param.apr_hdr.pkt_size = sizeof(afe_get_param);
	afe_get_param.apr_hdr.src_port = 0;
	afe_get_param.apr_hdr.dest_port = 0;
	afe_get_param.apr_hdr.token = index;
	afe_get_param.apr_hdr.opcode = AFE_PORT_CMD_GET_PARAM_V2;
	afe_get_param.port_id = port_id;
	afe_get_param.payload_size = sizeof(struct param_hdr_v1) + param_size;
	if (mem_hdr != NULL)
		afe_get_param.mem_hdr = *mem_hdr;
	/* Set MID and PID in command */
	afe_get_param.module_id = param_hdr->module_id;
	afe_get_param.param_id = param_hdr->param_id;
	/* Set param header in payload */
	afe_get_param.param_hdr.module_id = param_hdr->module_id;
	afe_get_param.param_hdr.param_id = param_hdr->param_id;
	afe_get_param.param_hdr.param_size = param_size;

	return afe_apr_send_pkt(&afe_get_param, &this_afe.wait[index]);
}

/* This function shouldn't be called directly. Instead call q6afe_get_param. */
static int q6afe_get_params_v3(u16 port_id, int index,
			       struct mem_mapping_hdr *mem_hdr,
			       struct param_hdr_v3 *param_hdr)
{
	struct afe_port_cmd_get_param_v3 afe_get_param;

	memset(&afe_get_param, 0, sizeof(afe_get_param));
	afe_get_param.apr_hdr.hdr_field =
		APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE),
			      APR_PKT_VER);
	afe_get_param.apr_hdr.pkt_size = sizeof(afe_get_param);
	afe_get_param.apr_hdr.src_port = 0;
	afe_get_param.apr_hdr.dest_port = 0;
	afe_get_param.apr_hdr.token = index;
	afe_get_param.apr_hdr.opcode = AFE_PORT_CMD_GET_PARAM_V3;
	afe_get_param.port_id = port_id;
	if (mem_hdr != NULL)
		afe_get_param.mem_hdr = *mem_hdr;
	/* Set param header in command, no payload in V3 */
	afe_get_param.param_hdr = *param_hdr;

	return afe_apr_send_pkt(&afe_get_param, &this_afe.wait[index]);
}

/*
 * Calling functions copy param data directly from this_afe. Do not copy data
 * back to caller here.
 */
static int q6afe_get_params(u16 port_id, struct mem_mapping_hdr *mem_hdr,
			    struct param_hdr_v3 *param_hdr)
{
	int index;
	int ret;

	ret = afe_q6_interface_prepare();
	if (ret != 0) {
		pr_err("%s: Q6 interface prepare failed %d\n", __func__, ret);
		return ret;
	}

	port_id = q6audio_get_port_id(port_id);
	ret = q6audio_validate_port(port_id);
	if (ret < 0) {
		pr_err("%s: Not a valid port id = 0x%x ret %d\n", __func__,
		       port_id, ret);
		return -EINVAL;
	}

	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid\n", __func__, index);
		return -EINVAL;
	}

	if (q6common_is_instance_id_supported())
		return q6afe_get_params_v3(port_id, index, NULL, param_hdr);
	else
		return q6afe_get_params_v2(port_id, index, NULL, param_hdr);
}

/*
 * This function shouldn't be called directly. Instead call
 * q6afe_svc_set_params.
 */
static int q6afe_svc_set_params_v1(int index, struct mem_mapping_hdr *mem_hdr,
				   u8 *packed_param_data, u32 packed_data_size)
{
	struct afe_svc_cmd_set_param_v1 *svc_set_param = NULL;
	uint32_t size = sizeof(struct afe_svc_cmd_set_param_v1);
	int rc = 0;

	if (packed_param_data != NULL)
		size += packed_data_size;
	svc_set_param = kzalloc(size, GFP_KERNEL);
	if (svc_set_param == NULL)
		return -ENOMEM;

	svc_set_param->apr_hdr.hdr_field =
		APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE),
			      APR_PKT_VER);
	svc_set_param->apr_hdr.pkt_size = size;
	svc_set_param->apr_hdr.src_port = 0;
	svc_set_param->apr_hdr.dest_port = 0;
	svc_set_param->apr_hdr.token = index;
	svc_set_param->apr_hdr.opcode = AFE_SVC_CMD_SET_PARAM;
	svc_set_param->payload_size = packed_data_size;

	if (mem_hdr != NULL) {
		/* Out of band case. */
		svc_set_param->mem_hdr = *mem_hdr;
	} else if (packed_param_data != NULL) {
		/* In band case. */
		memcpy(&svc_set_param->param_data, packed_param_data,
		       packed_data_size);
	} else {
		pr_err("%s: Both memory header and param data are NULL\n",
		       __func__);
		rc = -EINVAL;
		goto done;
	}

	rc = afe_apr_send_pkt(svc_set_param, &this_afe.wait[index]);
done:
	kfree(svc_set_param);
	return rc;
}

/*
 * This function shouldn't be called directly. Instead call
 * q6afe_svc_set_params.
 */
static int q6afe_svc_set_params_v2(int index, struct mem_mapping_hdr *mem_hdr,
				   u8 *packed_param_data, u32 packed_data_size)
{
	struct afe_svc_cmd_set_param_v2 *svc_set_param = NULL;
	uint16_t size = sizeof(struct afe_svc_cmd_set_param_v2);
	int rc = 0;

	if (packed_param_data != NULL)
		size += packed_data_size;
	svc_set_param = kzalloc(size, GFP_KERNEL);
	if (svc_set_param == NULL)
		return -ENOMEM;

	svc_set_param->apr_hdr.hdr_field =
		APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE),
			      APR_PKT_VER);
	svc_set_param->apr_hdr.pkt_size = size;
	svc_set_param->apr_hdr.src_port = 0;
	svc_set_param->apr_hdr.dest_port = 0;
	svc_set_param->apr_hdr.token = index;
	svc_set_param->apr_hdr.opcode = AFE_SVC_CMD_SET_PARAM_V2;
	svc_set_param->payload_size = packed_data_size;

	if (mem_hdr != NULL) {
		/* Out of band case. */
		svc_set_param->mem_hdr = *mem_hdr;
	} else if (packed_param_data != NULL) {
		/* In band case. */
		memcpy(&svc_set_param->param_data, packed_param_data,
		       packed_data_size);
	} else {
		pr_err("%s: Both memory header and param data are NULL\n",
		       __func__);
		rc = -EINVAL;
		goto done;
	}

	rc = afe_apr_send_pkt(svc_set_param, &this_afe.wait[index]);
done:
	kfree(svc_set_param);
	return rc;
}

/*
 * This function shouldn't be called directly. Instead call
 * q6afe_clk_set_params.
 */
static int q6afe_clk_set_params_v1(int index, struct mem_mapping_hdr *mem_hdr,
				   u8 *packed_param_data, u32 packed_data_size)
{
	struct afe_svc_cmd_set_param_v1 *svc_set_param = NULL;
	uint32_t size = sizeof(struct afe_svc_cmd_set_param_v1);
	int rc = 0;

	if (packed_param_data != NULL)
		size += packed_data_size;
	svc_set_param = kzalloc(size, GFP_KERNEL);
	if (svc_set_param == NULL)
		return -ENOMEM;

	svc_set_param->apr_hdr.hdr_field =
		APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE),
			      APR_PKT_VER);
	svc_set_param->apr_hdr.pkt_size = size;
	svc_set_param->apr_hdr.src_port = 0;
	svc_set_param->apr_hdr.dest_port = 0;
	svc_set_param->apr_hdr.token = AFE_CLK_TOKEN;
	svc_set_param->apr_hdr.opcode = AFE_SVC_CMD_SET_PARAM;
	svc_set_param->payload_size = packed_data_size;

	if (mem_hdr != NULL) {
		/* Out of band case. */
		svc_set_param->mem_hdr = *mem_hdr;
	} else if (packed_param_data != NULL) {
		/* In band case. */
		memcpy(&svc_set_param->param_data, packed_param_data,
		       packed_data_size);
	} else {
		pr_err("%s: Both memory header and param data are NULL\n",
		       __func__);
		rc = -EINVAL;
		goto done;
	}

	rc = afe_apr_send_clk_pkt(svc_set_param, &this_afe.clk_wait);
done:
	kfree(svc_set_param);
	return rc;
}

/*
 * This function shouldn't be called directly. Instead call
 * q6afe_clk_set_params.
 */
static int q6afe_clk_set_params_v2(int index, struct mem_mapping_hdr *mem_hdr,
				   u8 *packed_param_data, u32 packed_data_size)
{
	struct afe_svc_cmd_set_param_v2 *svc_set_param = NULL;
	uint16_t size = sizeof(struct afe_svc_cmd_set_param_v2);
	int rc = 0;

	if (packed_param_data != NULL)
		size += packed_data_size;
	svc_set_param = kzalloc(size, GFP_KERNEL);
	if (svc_set_param == NULL)
		return -ENOMEM;

	svc_set_param->apr_hdr.hdr_field =
		APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD, APR_HDR_LEN(APR_HDR_SIZE),
			      APR_PKT_VER);
	svc_set_param->apr_hdr.pkt_size = size;
	svc_set_param->apr_hdr.src_port = 0;
	svc_set_param->apr_hdr.dest_port = 0;
	svc_set_param->apr_hdr.token = AFE_CLK_TOKEN;
	svc_set_param->apr_hdr.opcode = AFE_SVC_CMD_SET_PARAM_V2;
	svc_set_param->payload_size = packed_data_size;

	if (mem_hdr != NULL) {
		/* Out of band case. */
		svc_set_param->mem_hdr = *mem_hdr;
	} else if (packed_param_data != NULL) {
		/* In band case. */
		memcpy(&svc_set_param->param_data, packed_param_data,
		       packed_data_size);
	} else {
		pr_err("%s: Both memory header and param data are NULL\n",
		       __func__);
		rc = -EINVAL;
		goto done;
	}

	rc = afe_apr_send_clk_pkt(svc_set_param, &this_afe.clk_wait);
done:
	kfree(svc_set_param);
	return rc;
}

static int q6afe_clk_set_params(int index, struct mem_mapping_hdr *mem_hdr,
				u8 *packed_param_data, u32 packed_data_size,
				bool is_iid_supported)
{
	int ret;

	ret = afe_q6_interface_prepare();
	if (ret != 0) {
		pr_err("%s: Q6 interface prepare failed %d\n", __func__, ret);
		return ret;
	}

	if (is_iid_supported)
		return q6afe_clk_set_params_v2(index, mem_hdr,
					       packed_param_data,
					       packed_data_size);
	else
		return q6afe_clk_set_params_v1(index, mem_hdr,
					       packed_param_data,
					       packed_data_size);
}

static int q6afe_svc_set_params(int index, struct mem_mapping_hdr *mem_hdr,
				u8 *packed_param_data, u32 packed_data_size,
				bool is_iid_supported)
{
	int ret;

	ret = afe_q6_interface_prepare();
	if (ret != 0) {
		pr_err("%s: Q6 interface prepare failed %d\n", __func__, ret);
		return ret;
	}

	if (is_iid_supported)
		return q6afe_svc_set_params_v2(index, mem_hdr,
					       packed_param_data,
					       packed_data_size);
	else
		return q6afe_svc_set_params_v1(index, mem_hdr,
					       packed_param_data,
					       packed_data_size);
}

static int q6afe_svc_pack_and_set_param_in_band(int index,
						struct param_hdr_v3 param_hdr,
						u8 *param_data)
{
	u8 *packed_param_data = NULL;
	u32 packed_data_size =
		sizeof(struct param_hdr_v3) + param_hdr.param_size;
	int ret = 0;
	bool is_iid_supported = q6common_is_instance_id_supported();

	packed_param_data = kzalloc(packed_data_size, GFP_KERNEL);
	if (!packed_param_data)
		return -ENOMEM;

	ret = q6common_pack_pp_params_v2(packed_param_data, &param_hdr,
					param_data, &packed_data_size,
					is_iid_supported);
	if (ret) {
		pr_err("%s: Failed to pack parameter header and data, error %d\n",
		       __func__, ret);
		goto done;
	}
	if (param_hdr.module_id == AFE_MODULE_CLOCK_SET)
		ret = q6afe_clk_set_params(index, NULL, packed_param_data,
					packed_data_size, is_iid_supported);
	else
		ret = q6afe_svc_set_params(index, NULL, packed_param_data,
					   packed_data_size, is_iid_supported);

done:
	kfree(packed_param_data);
	return ret;
}

static int afe_send_cal_block(u16 port_id, struct cal_block_data *cal_block)
{
	struct mem_mapping_hdr mem_hdr;
	int payload_size = 0;
	int result = 0;

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

	if (!cal_block) {
		pr_debug("%s: No AFE cal to send!\n", __func__);
		result = -EINVAL;
		goto done;
	}
	if (cal_block->cal_data.size <= 0) {
		pr_debug("%s: AFE cal has invalid size!\n", __func__);
		result = -EINVAL;
		goto done;
	}

	payload_size = cal_block->cal_data.size;
	mem_hdr.data_payload_addr_lsw =
		lower_32_bits(cal_block->cal_data.paddr);
	mem_hdr.data_payload_addr_msw =
		msm_audio_populate_upper_32_bits(cal_block->cal_data.paddr);
	mem_hdr.mem_map_handle = cal_block->map_data.q6map_handle;

	pr_debug("%s: AFE cal sent for device port = 0x%x, cal size = %zd, cal addr = 0x%pK\n",
		__func__, port_id,
		cal_block->cal_data.size, &cal_block->cal_data.paddr);

	result = q6afe_set_params(port_id, q6audio_get_port_index(port_id),
				  &mem_hdr, NULL, payload_size);
	if (result)
		pr_err("%s: AFE cal for port 0x%x failed %d\n",
		       __func__, port_id, result);

done:
	return result;
}


static int afe_send_custom_topology_block(struct cal_block_data *cal_block)
{
	int	result = 0;
	int	index = 0;
	struct cmd_set_topologies afe_cal;

	if (!cal_block) {
		pr_err("%s: No AFE SVC cal to send!\n", __func__);
		return -EINVAL;
	}
	if (cal_block->cal_data.size <= 0) {
		pr_err("%s: AFE SVC cal has invalid size: %zd!\n",
		__func__, cal_block->cal_data.size);
		return -EINVAL;
	}

	afe_cal.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	afe_cal.hdr.pkt_size = sizeof(afe_cal);
	afe_cal.hdr.src_port = 0;
	afe_cal.hdr.dest_port = 0;
	afe_cal.hdr.token = index;
	afe_cal.hdr.opcode = AFE_CMD_ADD_TOPOLOGIES;

	afe_cal.payload_size = cal_block->cal_data.size;
	afe_cal.payload_addr_lsw =
		lower_32_bits(cal_block->cal_data.paddr);
	afe_cal.payload_addr_msw =
		msm_audio_populate_upper_32_bits(cal_block->cal_data.paddr);
	afe_cal.mem_map_handle = cal_block->map_data.q6map_handle;

	pr_debug("%s:cmd_id:0x%x calsize:%zd memmap_hdl:0x%x caladdr:0x%pK",
		__func__, AFE_CMD_ADD_TOPOLOGIES, cal_block->cal_data.size,
		afe_cal.mem_map_handle, &cal_block->cal_data.paddr);

	result = afe_apr_send_pkt(&afe_cal, &this_afe.wait[index]);
	if (result)
		pr_err("%s: AFE send topology for command 0x%x failed %d\n",
		       __func__, AFE_CMD_ADD_TOPOLOGIES, result);

	return result;
}

static void afe_send_custom_topology(void)
{
	struct cal_block_data   *cal_block = NULL;
	int cal_index = AFE_CUST_TOPOLOGY_CAL;
	int ret;

	if (this_afe.cal_data[cal_index] == NULL) {
		pr_err("%s: cal_index %d not allocated!\n",
			__func__, cal_index);
		return;
	}
	mutex_lock(&this_afe.cal_data[cal_index]->lock);

	if (!this_afe.set_custom_topology)
		goto unlock;
	this_afe.set_custom_topology = 0;
	cal_block = cal_utils_get_only_cal_block(this_afe.cal_data[cal_index]);
	if (cal_block == NULL || cal_utils_is_cal_stale(cal_block)) {
		pr_err("%s cal_block not found!!\n", __func__);
		goto unlock;
	}

	pr_debug("%s: Sending cal_index cal %d\n", __func__, cal_index);

	ret = remap_cal_data(cal_block, cal_index);
	if (ret) {
		pr_err("%s: Remap_cal_data failed for cal %d!\n",
			__func__, cal_index);
		goto unlock;
	}
	ret = afe_send_custom_topology_block(cal_block);
	if (ret < 0) {
		pr_err("%s: No cal sent for cal_index %d! ret %d\n",
			__func__, cal_index, ret);
		goto unlock;
	}
	pr_debug("%s:sent custom topology for AFE\n", __func__);
unlock:
	mutex_unlock(&this_afe.cal_data[cal_index]->lock);
}

static int afe_spk_ramp_dn_cfg(int port)
{
	struct param_hdr_v3 param_info;
	int ret = -EINVAL;

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

	if (afe_get_port_type(port) != MSM_AFE_PORT_TYPE_RX) {
		pr_debug("%s: port doesn't match 0x%x\n", __func__, port);
		return 0;
	}
	if (this_afe.prot_cfg.mode == MSM_SPKR_PROT_DISABLED ||
		(this_afe.vi_rx_port != port)) {
		pr_debug("%s: spkr protection disabled port 0x%x %d 0x%x\n",
				__func__, port, ret, this_afe.vi_rx_port);
		return 0;
	}
	param_info.module_id = AFE_MODULE_FB_SPKR_PROT_V2_RX;
	param_info.instance_id = INSTANCE_ID_0;
	param_info.param_id = AFE_PARAM_ID_FBSP_PTONE_RAMP_CFG;
	param_info.param_size = 0;

	ret = q6afe_pack_and_set_param_in_band(port,
					       q6audio_get_port_index(port),
					       param_info, NULL);
	if (ret) {
		pr_err("%s: Failed to set speaker ramp duration param, err %d\n",
		       __func__, ret);
		goto fail_cmd;
	}

	/* dsp needs atleast 15ms to ramp down pilot tone*/
	usleep_range(15000, 15010);
	ret = 0;
fail_cmd:
	pr_debug("%s: config.pdata.param_id 0x%x status %d\n", __func__,
		 param_info.param_id, ret);
	return ret;
}

static int afe_send_cps_config(int src_port)
{
	int i = 0;
	struct param_hdr_v3 param_info;
	int ret = -EINVAL;
	u8 *packed_payload = NULL;
	int cpy_size = 0;
	int ch_copied = 0;
	size_t param_size = 0;

	if ((-1 == this_afe.vi_tx_port) || (!this_afe.cps_ch_mask) ||
	    (!this_afe.cps_config)) {
		pr_err("%s: speaker prot not configured for 0x%x\n", __func__,
		       src_port);
		return -EINVAL;
	}

	param_size = sizeof(struct afe_cps_hw_intf_cfg) -
			sizeof(this_afe.cps_config->spkr_dep_cfg) +
			(sizeof(struct lpass_swr_spkr_dep_cfg_t)
				* this_afe.num_spkrs);

	this_afe.cps_config->hw_reg_cfg.num_spkr = this_afe.num_spkrs;
	packed_payload = kzalloc(param_size, GFP_KERNEL);
	if (packed_payload == NULL)
		return -ENOMEM;

	cpy_size = sizeof(struct afe_cps_hw_intf_cfg) -
			sizeof(this_afe.cps_config->spkr_dep_cfg);
	memcpy(packed_payload, this_afe.cps_config, cpy_size);

	while (ch_copied < this_afe.num_spkrs) {
		if (!(this_afe.cps_ch_mask & (1 << i))) {
			i++;
			continue;
		}

		memcpy(packed_payload + cpy_size,
			&this_afe.cps_config->spkr_dep_cfg[i],
			sizeof(struct lpass_swr_spkr_dep_cfg_t));
		cpy_size += sizeof(struct lpass_swr_spkr_dep_cfg_t);
		ch_copied++;
		i++;
	}

	memset(&param_info, 0, sizeof(param_info));
	param_info.module_id = AFE_MODULE_SPEAKER_PROTECTION_V4_RX;
	param_info.instance_id = INSTANCE_ID_0;
	param_info.param_id = AFE_PARAM_ID_CPS_LPASS_HW_INTF_CFG;
	param_info.param_size = param_size;

	ret = q6afe_pack_and_set_param_in_band(src_port,
					       q6audio_get_port_index(src_port),
					       param_info, packed_payload);
	if (ret)
		pr_err("%s: port = 0x%x param = 0x%x failed %d\n", __func__,
		       src_port, param_info.param_id, ret);

	pr_debug("%s: config.pdata.param_id 0x%x status %d 0x%x\n", __func__,
		 param_info.param_id, ret, src_port);
	kfree(packed_payload);
	return ret;
}

static int afe_spk_prot_prepare(int src_port, int dst_port, int param_id,
		union afe_spkr_prot_config *prot_config, uint32_t param_size)
{
	struct param_hdr_v3 param_info;
	int ret = -EINVAL;

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

	ret = q6audio_validate_port(src_port);
	if (ret < 0) {
		pr_err("%s: Invalid src port 0x%x ret %d", __func__, src_port,
		       ret);
		ret = -EINVAL;
		goto fail_cmd;
	}
	ret = q6audio_validate_port(dst_port);
	if (ret < 0) {
		pr_err("%s: Invalid dst port 0x%x ret %d", __func__,
				dst_port, ret);
		ret = -EINVAL;
		goto fail_cmd;
	}

	switch (param_id) {
	case AFE_PARAM_ID_FBSP_MODE_RX_CFG:
	case AFE_PARAM_ID_SP_RX_LIMITER_TH:
		param_info.module_id = AFE_MODULE_FB_SPKR_PROT_V2_RX;
		break;
	case AFE_PARAM_ID_SP_V4_OP_MODE:
		param_info.module_id = AFE_MODULE_SPEAKER_PROTECTION_V4_RX;
		break;
	case AFE_PARAM_ID_FEEDBACK_PATH_CFG:
		this_afe.vi_tx_port = src_port;
		this_afe.vi_rx_port = dst_port;
		param_info.module_id = AFE_MODULE_FEEDBACK;
		break;
	/*
	 * AFE_PARAM_ID_SPKR_CALIB_VI_PROC_CFG_V2 is same as
	 * AFE_PARAM_ID_SP_V2_TH_VI_MODE_CFG. V_VALI_CFG uses
	 * same module TH_VI.
	 */
	case AFE_PARAM_ID_SPKR_CALIB_VI_PROC_CFG_V2:
	case AFE_PARAM_ID_SP_V2_TH_VI_FTM_CFG:
	case AFE_PARAM_ID_SP_V2_TH_VI_V_VALI_CFG:
		param_info.module_id = AFE_MODULE_SPEAKER_PROTECTION_V2_TH_VI;
		break;
	case AFE_PARAM_ID_SP_V2_EX_VI_MODE_CFG:
	case AFE_PARAM_ID_SP_V2_EX_VI_FTM_CFG:
		param_info.module_id = AFE_MODULE_SPEAKER_PROTECTION_V2_EX_VI;
		break;
	case AFE_PARAM_ID_SP_V4_VI_CHANNEL_MAP_CFG:
	case AFE_PARAM_ID_SP_V4_VI_OP_MODE_CFG:
	case AFE_PARAM_ID_SP_V4_VI_R0T0_CFG:
	case AFE_PARAM_ID_SP_V4_TH_VI_FTM_CFG:
	case AFE_PARAM_ID_SP_V4_TH_VI_V_VALI_CFG:
	case AFE_PARAM_ID_SP_V4_EX_VI_MODE_CFG:
	case AFE_PARAM_ID_SP_V4_EX_VI_FTM_CFG:
		param_info.module_id = AFE_MODULE_SPEAKER_PROTECTION_V4_VI;
		break;
	default:
		pr_err("%s: default case 0x%x\n", __func__, param_id);
		goto fail_cmd;
	}

	param_info.instance_id = INSTANCE_ID_0;
	param_info.param_id = param_id;
	param_info.param_size = param_size;

	ret = q6afe_pack_and_set_param_in_band(src_port,
					       q6audio_get_port_index(src_port),
					       param_info, (u8 *) prot_config);
	if (ret)
		pr_err("%s: port = 0x%x param = 0x%x failed %d\n", __func__,
		       src_port, param_id, ret);

fail_cmd:
	pr_debug("%s: config.pdata.param_id 0x%x status %d 0x%x\n", __func__,
		 param_info.param_id, ret, src_port);
	return ret;
}

static int afe_spkr_prot_reg_event_cfg(u16 port_id, uint32_t module_id)
{
	struct afe_port_cmd_event_cfg *config;
	struct afe_port_cmd_mod_evt_cfg_payload pl;
	int index;
	int ret;
	int num_events = 1;
	int cmd_size = sizeof(struct afe_port_cmd_event_cfg) +
		(num_events * sizeof(struct afe_port_cmd_mod_evt_cfg_payload));

	config = kzalloc(cmd_size, GFP_KERNEL);
	if (!config)
		return -ENOMEM;

	index = q6audio_get_port_index(port_id);
	if (index < 0) {
		pr_err("%s: Invalid index number: %d\n", __func__, index);
		ret = -EINVAL;
		goto fail_idx;
	}

	memset(&pl, 0, sizeof(pl));
	pl.module_id = module_id;
	pl.event_id = AFE_PORT_SP_DC_DETECTION_EVENT;
	pl.reg_flag = AFE_MODULE_REGISTER_EVENT_FLAG;


	config->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	config->hdr.pkt_size = cmd_size;
	config->hdr.src_port = 0;
	config->hdr.dest_port = 0;
	config->hdr.token = index;

	config->hdr.opcode = AFE_PORT_CMD_MOD_EVENT_CFG;
	config->port_id = q6audio_get_port_id(port_id);
	config->num_events = num_events;
	config->version = 1;
	memcpy(config->payload, &pl, sizeof(pl));
	ret = afe_apr_send_pkt((uint32_t *) config, &this_afe.wait[index]);

fail_idx:
	kfree(config);
	return ret;
}

static void afe_send_cal_spv4_tx(int port_id)
{
	union afe_spkr_prot_config afe_spk_config;
	uint32_t size = 0;
	void *tmp_ptr = NULL;
	struct afe_sp_v4_param_th_vi_r0t0_cfg *th_vi_r0t0_cfg;
	struct afe_sp_v4_channel_r0t0 *ch_r0t0_cfg;
	struct afe_sp_v4_param_th_vi_ftm_cfg *th_vi_ftm_cfg;
	struct afe_sp_v4_channel_ftm_cfg *ch_ftm_cfg;
	struct afe_sp_v4_param_th_vi_v_vali_cfg *th_vi_v_vali_cfg;
	struct afe_sp_v4_channel_v_vali_cfg *ch_v_vali_cfg;
	struct afe_sp_v4_param_ex_vi_ftm_cfg *ex_vi_ftm_cfg;
	struct afe_sp_v4_channel_ex_vi_ftm *ch_ex_vi_ftm_cfg;
	uint32_t i = 0;

	pr_debug("%s: Entry.. port_id %d\n", __func__, port_id);

	if (this_afe.vi_tx_port == port_id) {
		memcpy(&afe_spk_config.v4_ch_map_cfg, &this_afe.v4_ch_map_cfg,
			sizeof(struct afe_sp_v4_param_vi_channel_map_cfg));
		if (afe_spk_prot_prepare(port_id, this_afe.vi_rx_port,
			AFE_PARAM_ID_SP_V4_VI_CHANNEL_MAP_CFG, &afe_spk_config,
			sizeof(struct afe_sp_v4_param_vi_channel_map_cfg)))
			pr_info("%s: SPKR_CALIB_CHANNEL_MAP_CFG failed\n",
				 __func__);
	}

	if (this_afe.cal_data[AFE_FB_SPKR_PROT_CAL] == NULL ||
	    this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL] == NULL ||
	    this_afe.cal_data[AFE_FB_SPKR_PROT_EX_VI_CAL] == NULL) {
		pr_info("%s: Returning as no cal data cached\n", __func__);
		return;
	}

	mutex_lock(&this_afe.cal_data[AFE_FB_SPKR_PROT_CAL]->lock);
	if ((this_afe.prot_cfg.mode != MSM_SPKR_PROT_DISABLED) &&
		(this_afe.vi_tx_port == port_id) &&
		(this_afe.prot_cfg.sp_version >= AFE_API_VERSION_V9)) {

		if (this_afe.prot_cfg.mode ==
			MSM_SPKR_PROT_CALIBRATION_IN_PROGRESS) {
			afe_spk_config.v4_vi_op_mode.th_operation_mode =
					Q6AFE_MSM_SPKR_CALIBRATION;
			afe_spk_config.v4_vi_op_mode.th_quick_calib_flag =
					this_afe.prot_cfg.quick_calib_flag;
		} else {
			afe_spk_config.v4_vi_op_mode.th_operation_mode =
					Q6AFE_MSM_SPKR_PROCESSING;
		}

		if (this_afe.th_ftm_cfg.mode == MSM_SPKR_PROT_IN_FTM_MODE)
			afe_spk_config.v4_vi_op_mode.th_operation_mode =
					    Q6AFE_MSM_SPKR_FTM_MODE;
		else if (this_afe.v_vali_cfg.mode ==
					MSM_SPKR_PROT_IN_V_VALI_MODE)
			afe_spk_config.v4_vi_op_mode.th_operation_mode =
					    Q6AFE_MSM_SPKR_V_VALI_MODE;
		if (this_afe.prot_cfg.mode != MSM_SPKR_PROT_NOT_CALIBRATED) {
			struct afe_sp_v4_param_vi_op_mode_cfg *v4_vi_op_mode;

			v4_vi_op_mode = &afe_spk_config.v4_vi_op_mode;
			v4_vi_op_mode->th_r0t0_selection_flag[SP_V2_SPKR_1] =
					    USE_CALIBRATED_R0TO;
			v4_vi_op_mode->th_r0t0_selection_flag[SP_V2_SPKR_2] =
					    USE_CALIBRATED_R0TO;
		} else {
			struct afe_sp_v4_param_vi_op_mode_cfg *v4_vi_op_mode;

			v4_vi_op_mode = &afe_spk_config.v4_vi_op_mode;
			v4_vi_op_mode->th_r0t0_selection_flag[SP_V2_SPKR_1] =
							    USE_SAFE_R0TO;
			v4_vi_op_mode->th_r0t0_selection_flag[SP_V2_SPKR_2] =
							    USE_SAFE_R0TO;
		}
		afe_spk_config.v4_vi_op_mode.num_speakers = this_afe.num_spkrs;
		if (afe_spk_prot_prepare(port_id, 0,
			AFE_PARAM_ID_SP_V4_VI_OP_MODE_CFG,
			&afe_spk_config,
			sizeof(struct afe_sp_v4_param_vi_op_mode_cfg)))
			pr_info("%s: SPKR_CALIB_VI_PROC_CFG failed\n",
				__func__);

		size = sizeof(struct afe_sp_v4_param_th_vi_r0t0_cfg) +
		(this_afe.num_spkrs * sizeof(struct afe_sp_v4_channel_r0t0));
		tmp_ptr = kzalloc(size, GFP_KERNEL);
		if (!tmp_ptr) {
			mutex_unlock(
				&this_afe.cal_data[AFE_FB_SPKR_PROT_CAL]->lock);
			return;
		}
		memset(tmp_ptr, 0, size);

		th_vi_r0t0_cfg =
			(struct afe_sp_v4_param_th_vi_r0t0_cfg *)tmp_ptr;
		ch_r0t0_cfg =
			(struct afe_sp_v4_channel_r0t0 *)(th_vi_r0t0_cfg + 1);

		th_vi_r0t0_cfg->num_speakers = this_afe.num_spkrs;
		for (i = 0; i < this_afe.num_spkrs; i++) {
			ch_r0t0_cfg[i].r0_cali_q24 =
				(uint32_t) this_afe.prot_cfg.r0[i];
			ch_r0t0_cfg[i].t0_cali_q6 =
				(uint32_t) this_afe.prot_cfg.t0[i];
		}
		if (afe_spk_prot_prepare(port_id, 0,
			AFE_PARAM_ID_SP_V4_VI_R0T0_CFG,
			(union afe_spkr_prot_config *)tmp_ptr, size))
			pr_info("%s: th vi ftm cfg failed\n", __func__);

		kfree(tmp_ptr);
	}
	mutex_unlock(&this_afe.cal_data[AFE_FB_SPKR_PROT_CAL]->lock);

	mutex_lock(&this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL]->lock);
	if ((this_afe.th_ftm_cfg.mode == MSM_SPKR_PROT_IN_FTM_MODE) &&
	    (this_afe.vi_tx_port == port_id) &&
	    (this_afe.prot_cfg.sp_version >= AFE_API_VERSION_V9)) {
		size = sizeof(struct afe_sp_v4_param_th_vi_ftm_cfg) +
		(this_afe.num_spkrs * sizeof(struct afe_sp_v4_channel_ftm_cfg));
		tmp_ptr = kzalloc(size, GFP_KERNEL);
		if (!tmp_ptr) {
			mutex_unlock(
			  &this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL]->lock);
			return;
		}
		memset(tmp_ptr, 0, size);

		th_vi_ftm_cfg = (struct afe_sp_v4_param_th_vi_ftm_cfg *)tmp_ptr;
		ch_ftm_cfg =
			 (struct afe_sp_v4_channel_ftm_cfg *)(th_vi_ftm_cfg+1);

		th_vi_ftm_cfg->num_ch = this_afe.num_spkrs;
		for (i = 0; i < this_afe.num_spkrs; i++) {
			ch_ftm_cfg[i].wait_time_ms =
				this_afe.th_ftm_cfg.wait_time[i];
			ch_ftm_cfg[i].ftm_time_ms =
				this_afe.th_ftm_cfg.ftm_time[i];
		}
		if (afe_spk_prot_prepare(port_id, 0,
				AFE_PARAM_ID_SP_V4_TH_VI_FTM_CFG,
				(union afe_spkr_prot_config *)tmp_ptr, size))
			pr_info("%s: th vi ftm cfg failed\n", __func__);

		kfree(tmp_ptr);
		this_afe.th_ftm_cfg.mode = MSM_SPKR_PROT_DISABLED;
	} else if ((this_afe.v_vali_cfg.mode ==
			MSM_SPKR_PROT_IN_V_VALI_MODE) &&
		   (this_afe.vi_tx_port == port_id)) {
		size = sizeof(struct afe_sp_v4_param_th_vi_v_vali_cfg) +
			(this_afe.num_spkrs *
			sizeof(struct afe_sp_v4_channel_v_vali_cfg));
		tmp_ptr = kzalloc(size, GFP_KERNEL);
		if (!tmp_ptr) {
			mutex_unlock(
			  &this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL]->lock);
			return;
		}
		memset(tmp_ptr, 0, size);

		th_vi_v_vali_cfg =
		 (struct afe_sp_v4_param_th_vi_v_vali_cfg *)tmp_ptr;
		ch_v_vali_cfg =
		 (struct afe_sp_v4_channel_v_vali_cfg *)(th_vi_v_vali_cfg + 1);

		th_vi_v_vali_cfg->num_ch = this_afe.num_spkrs;
		for (i = 0; i < this_afe.num_spkrs; i++) {
			ch_v_vali_cfg[i].wait_time_ms =
				this_afe.v_vali_cfg.wait_time[i];
			ch_v_vali_cfg[i].vali_time_ms =
				this_afe.v_vali_cfg.vali_time[i];
		}
		if (afe_spk_prot_prepare(port_id, 0,
				AFE_PARAM_ID_SP_V4_TH_VI_V_VALI_CFG,
				(union afe_spkr_prot_config *)tmp_ptr, size))
			pr_info("%s: th vi v-vali cfg failed\n", __func__);

		kfree(tmp_ptr);
		this_afe.v_vali_cfg.mode = MSM_SPKR_PROT_DISABLED;
	}
	mutex_unlock(&this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL]->lock);

	mutex_lock(&this_afe.cal_data[AFE_FB_SPKR_PROT_EX_VI_CAL]->lock);
	if ((this_afe.ex_ftm_cfg.mode == MSM_SPKR_PROT_IN_FTM_MODE) &&
	    (this_afe.vi_tx_port == port_id) &&
	    (this_afe.prot_cfg.sp_version >= AFE_API_VERSION_V9)) {
		size = sizeof(struct afe_sp_v4_param_ex_vi_ftm_cfg) +
		(this_afe.num_spkrs *
		 sizeof(struct afe_sp_v4_channel_ex_vi_ftm));
		tmp_ptr = kzalloc(size, GFP_KERNEL);
		if (!tmp_ptr) {
			mutex_unlock(
			  &this_afe.cal_data[AFE_FB_SPKR_PROT_EX_VI_CAL]->lock);
			return;
		}
		memset(tmp_ptr, 0, size);

		ex_vi_ftm_cfg = (struct afe_sp_v4_param_ex_vi_ftm_cfg *)tmp_ptr;
		ch_ex_vi_ftm_cfg =
		(struct afe_sp_v4_channel_ex_vi_ftm *)(ex_vi_ftm_cfg + 1);

		afe_spk_config.v4_ex_vi_mode_cfg.operation_mode =
						AFE_FBSP_V4_EX_VI_MODE_FTM;
		if (afe_spk_prot_prepare(port_id, 0,
				 AFE_PARAM_ID_SP_V4_EX_VI_MODE_CFG,
				 &afe_spk_config,
				 sizeof(struct afe_sp_v4_param_ex_vi_mode_cfg)))
			pr_info("%s: ex vi mode cfg failed\n", __func__);

		ex_vi_ftm_cfg->num_ch = this_afe.num_spkrs;

		for (i = 0; i < this_afe.num_spkrs; i++) {
			ch_ex_vi_ftm_cfg[i].wait_time_ms =
				this_afe.ex_ftm_cfg.wait_time[i];
			ch_ex_vi_ftm_cfg[i].ftm_time_ms =
				this_afe.ex_ftm_cfg.ftm_time[i];
		}
		if (afe_spk_prot_prepare(port_id, 0,
				 AFE_PARAM_ID_SP_V4_EX_VI_FTM_CFG,
				 (union afe_spkr_prot_config *)tmp_ptr, size))
			pr_info("%s: ex vi ftm cfg failed\n", __func__);
		kfree(tmp_ptr);
		this_afe.ex_ftm_cfg.mode = MSM_SPKR_PROT_DISABLED;
	}
	mutex_unlock(&this_afe.cal_data[AFE_FB_SPKR_PROT_EX_VI_CAL]->lock);

	/* Register for DC detection event if speaker protection is enabled */
	if (this_afe.prot_cfg.mode != MSM_SPKR_PROT_DISABLED &&
		(this_afe.vi_tx_port == port_id)) {
		afe_spkr_prot_reg_event_cfg(port_id,
					AFE_MODULE_SPEAKER_PROTECTION_V4_VI);
	}

}

static void afe_send_cal_spkr_prot_tx(int port_id)
{
	union afe_spkr_prot_config afe_spk_config;

	if (q6core_get_avcs_api_version_per_service(
		APRV2_IDS_SERVICE_ID_ADSP_AFE_V) >= AFE_API_VERSION_V9) {
		afe_send_cal_spv4_tx(port_id);
		return;
	}

	if (this_afe.cal_data[AFE_FB_SPKR_PROT_CAL] == NULL ||
	    this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL] == NULL ||
	    this_afe.cal_data[AFE_FB_SPKR_PROT_EX_VI_CAL] == NULL)
		return;

	mutex_lock(&this_afe.cal_data[AFE_FB_SPKR_PROT_CAL]->lock);
	if ((this_afe.prot_cfg.mode != MSM_SPKR_PROT_DISABLED) &&
		(this_afe.vi_tx_port == port_id)) {
		if (this_afe.prot_cfg.mode ==
			MSM_SPKR_PROT_CALIBRATION_IN_PROGRESS) {
			afe_spk_config.vi_proc_cfg.operation_mode =
					Q6AFE_MSM_SPKR_CALIBRATION;
			afe_spk_config.vi_proc_cfg.quick_calib_flag =
					this_afe.prot_cfg.quick_calib_flag;
		} else {
			afe_spk_config.vi_proc_cfg.operation_mode =
					Q6AFE_MSM_SPKR_PROCESSING;
		}

		if (this_afe.th_ftm_cfg.mode == MSM_SPKR_PROT_IN_FTM_MODE)
			afe_spk_config.vi_proc_cfg.operation_mode =
					    Q6AFE_MSM_SPKR_FTM_MODE;
		else if (this_afe.v_vali_cfg.mode ==
					MSM_SPKR_PROT_IN_V_VALI_MODE)
			afe_spk_config.vi_proc_cfg.operation_mode =
					    Q6AFE_MSM_SPKR_V_VALI_MODE;
		afe_spk_config.vi_proc_cfg.minor_version = 1;
		afe_spk_config.vi_proc_cfg.r0_cali_q24[SP_V2_SPKR_1] =
			(uint32_t) this_afe.prot_cfg.r0[SP_V2_SPKR_1];
		afe_spk_config.vi_proc_cfg.r0_cali_q24[SP_V2_SPKR_2] =
			(uint32_t) this_afe.prot_cfg.r0[SP_V2_SPKR_2];
		afe_spk_config.vi_proc_cfg.t0_cali_q6[SP_V2_SPKR_1] =
			(uint32_t) this_afe.prot_cfg.t0[SP_V2_SPKR_1];
		afe_spk_config.vi_proc_cfg.t0_cali_q6[SP_V2_SPKR_2] =
			(uint32_t) this_afe.prot_cfg.t0[SP_V2_SPKR_2];
		if (this_afe.prot_cfg.mode != MSM_SPKR_PROT_NOT_CALIBRATED) {
			struct asm_spkr_calib_vi_proc_cfg *vi_proc_cfg;

			vi_proc_cfg = &afe_spk_config.vi_proc_cfg;
			vi_proc_cfg->r0_t0_selection_flag[SP_V2_SPKR_1] =
					    USE_CALIBRATED_R0TO;
			vi_proc_cfg->r0_t0_selection_flag[SP_V2_SPKR_2] =
					    USE_CALIBRATED_R0TO;
		} else {
			struct asm_spkr_calib_vi_proc_cfg *vi_proc_cfg;

			vi_proc_cfg = &afe_spk_config.vi_proc_cfg;
			vi_proc_cfg->r0_t0_selection_flag[SP_V2_SPKR_1] =
							    USE_SAFE_R0TO;
			vi_proc_cfg->r0_t0_selection_flag[SP_V2_SPKR_2] =
							    USE_SAFE_R0TO;
		}
		if (afe_spk_prot_prepare(port_id, 0,
			AFE_PARAM_ID_SPKR_CALIB_VI_PROC_CFG_V2,
			&afe_spk_config, sizeof(union afe_spkr_prot_config)))
			pr_err("%s: SPKR_CALIB_VI_PROC_CFG failed\n",
				__func__);
	}
	mutex_unlock(&this_afe.cal_data[AFE_FB_SPKR_PROT_CAL]->lock);

	mutex_lock(&this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL]->lock);
	if ((this_afe.th_ftm_cfg.mode == MSM_SPKR_PROT_IN_FTM_MODE) &&
	    (this_afe.vi_tx_port == port_id)) {
		afe_spk_config.th_vi_ftm_cfg.minor_version = 1;
		afe_spk_config.th_vi_ftm_cfg.wait_time_ms[SP_V2_SPKR_1] =
			this_afe.th_ftm_cfg.wait_time[SP_V2_SPKR_1];
		afe_spk_config.th_vi_ftm_cfg.wait_time_ms[SP_V2_SPKR_2] =
			this_afe.th_ftm_cfg.wait_time[SP_V2_SPKR_2];
		afe_spk_config.th_vi_ftm_cfg.ftm_time_ms[SP_V2_SPKR_1] =
			this_afe.th_ftm_cfg.ftm_time[SP_V2_SPKR_1];
		afe_spk_config.th_vi_ftm_cfg.ftm_time_ms[SP_V2_SPKR_2] =
			this_afe.th_ftm_cfg.ftm_time[SP_V2_SPKR_2];

		if (afe_spk_prot_prepare(port_id, 0,
				 AFE_PARAM_ID_SP_V2_TH_VI_FTM_CFG,
				 &afe_spk_config,
				 sizeof(union afe_spkr_prot_config)))
			pr_err("%s: th vi ftm cfg failed\n", __func__);
		this_afe.th_ftm_cfg.mode = MSM_SPKR_PROT_DISABLED;
	} else if ((this_afe.v_vali_cfg.mode ==
			MSM_SPKR_PROT_IN_V_VALI_MODE) &&
		   (this_afe.vi_tx_port == port_id)) {
		afe_spk_config.th_vi_v_vali_cfg.minor_version = 1;
		afe_spk_config.th_vi_v_vali_cfg.wait_time_ms[SP_V2_SPKR_1] =
			this_afe.v_vali_cfg.wait_time[SP_V2_SPKR_1];
		afe_spk_config.th_vi_v_vali_cfg.wait_time_ms[SP_V2_SPKR_2] =
			this_afe.v_vali_cfg.wait_time[SP_V2_SPKR_2];
		afe_spk_config.th_vi_v_vali_cfg.vali_time_ms[SP_V2_SPKR_1] =
			this_afe.v_vali_cfg.vali_time[SP_V2_SPKR_1];
		afe_spk_config.th_vi_v_vali_cfg.vali_time_ms[SP_V2_SPKR_2] =
			this_afe.v_vali_cfg.vali_time[SP_V2_SPKR_2];

		if (afe_spk_prot_prepare(port_id, 0,
					 AFE_PARAM_ID_SP_V2_TH_VI_V_VALI_CFG,
					 &afe_spk_config,
					 sizeof(union afe_spkr_prot_config)))
			pr_err("%s: th vi v-vali cfg failed\n", __func__);

		this_afe.v_vali_cfg.mode = MSM_SPKR_PROT_DISABLED;
	}
	mutex_unlock(&this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL]->lock);

	mutex_lock(&this_afe.cal_data[AFE_FB_SPKR_PROT_EX_VI_CAL]->lock);
	if ((this_afe.ex_ftm_cfg.mode == MSM_SPKR_PROT_IN_FTM_MODE) &&
	    (this_afe.vi_tx_port == port_id)) {
		afe_spk_config.ex_vi_mode_cfg.minor_version = 1;
		afe_spk_config.ex_vi_mode_cfg.operation_mode =
						Q6AFE_MSM_SPKR_FTM_MODE;
		if (afe_spk_prot_prepare(port_id, 0,
					 AFE_PARAM_ID_SP_V2_EX_VI_MODE_CFG,
					 &afe_spk_config,
					 sizeof(union afe_spkr_prot_config)))
			pr_err("%s: ex vi mode cfg failed\n", __func__);

		afe_spk_config.ex_vi_ftm_cfg.minor_version = 1;
		afe_spk_config.ex_vi_ftm_cfg.wait_time_ms[SP_V2_SPKR_1] =
			this_afe.ex_ftm_cfg.wait_time[SP_V2_SPKR_1];
		afe_spk_config.ex_vi_ftm_cfg.wait_time_ms[SP_V2_SPKR_2] =
			this_afe.ex_ftm_cfg.wait_time[SP_V2_SPKR_2];
		afe_spk_config.ex_vi_ftm_cfg.ftm_time_ms[SP_V2_SPKR_1] =
			this_afe.ex_ftm_cfg.ftm_time[SP_V2_SPKR_1];
		afe_spk_config.ex_vi_ftm_cfg.ftm_time_ms[SP_V2_SPKR_2] =
			this_afe.ex_ftm_cfg.ftm_time[SP_V2_SPKR_2];

		if (afe_spk_prot_prepare(port_id, 0,
					 AFE_PARAM_ID_SP_V2_EX_VI_FTM_CFG,
					 &afe_spk_config,
					 sizeof(union afe_spkr_prot_config)))
			pr_err("%s: ex vi ftm cfg failed\n", __func__);
		this_afe.ex_ftm_cfg.mode = MSM_SPKR_PROT_DISABLED;
	}
	mutex_unlock(&this_afe.cal_data[AFE_FB_SPKR_PROT_EX_VI_CAL]->lock);

	/* Register for DC detection event if speaker protection is enabled */
	if (this_afe.prot_cfg.mode != MSM_SPKR_PROT_DISABLED &&
		(this_afe.vi_tx_port == port_id)) {
		afe_spkr_prot_reg_event_cfg(port_id,
				AFE_MODULE_SPEAKER_PROTECTION_V2_EX_VI);
	}
}

static void afe_send_cal_spv4_rx(int port_id)
{

	union afe_spkr_prot_config afe_spk_config;

	if (this_afe.cal_data[AFE_FB_SPKR_PROT_CAL] == NULL)
		return;

	mutex_lock(&this_afe.cal_data[AFE_FB_SPKR_PROT_CAL]->lock);
	if (this_afe.prot_cfg.mode != MSM_SPKR_PROT_DISABLED &&
		(this_afe.vi_rx_port == port_id) &&
		(this_afe.prot_cfg.sp_version >= AFE_API_VERSION_V9)) {
		if (this_afe.prot_cfg.mode ==
			MSM_SPKR_PROT_CALIBRATION_IN_PROGRESS)
			afe_spk_config.v4_op_mode.mode =
				Q6AFE_MSM_SPKR_CALIBRATION;
		else
			afe_spk_config.v4_op_mode.mode =
				Q6AFE_MSM_SPKR_PROCESSING;
		if (afe_spk_prot_prepare(port_id, 0,
			AFE_PARAM_ID_SP_V4_OP_MODE,
			&afe_spk_config, sizeof(union afe_spkr_prot_config)))
			pr_info("%s: RX MODE_VI_PROC_CFG failed\n",
				   __func__);
	}
	mutex_unlock(&this_afe.cal_data[AFE_FB_SPKR_PROT_CAL]->lock);
}

static void afe_send_cal_spkr_prot_rx(int port_id)
{
	union afe_spkr_prot_config afe_spk_config;
	union afe_spkr_prot_config afe_spk_limiter_config;

	if (q6core_get_avcs_api_version_per_service(
		APRV2_IDS_SERVICE_ID_ADSP_AFE_V) >= AFE_API_VERSION_V9) {
		afe_send_cal_spv4_rx(port_id);
		return;
	}

	if (this_afe.cal_data[AFE_FB_SPKR_PROT_CAL] == NULL)
		goto done;

	mutex_lock(&this_afe.cal_data[AFE_FB_SPKR_PROT_CAL]->lock);

	if (this_afe.prot_cfg.mode != MSM_SPKR_PROT_DISABLED &&
		(this_afe.vi_rx_port == port_id)) {
		if (this_afe.prot_cfg.mode ==
			MSM_SPKR_PROT_CALIBRATION_IN_PROGRESS)
			afe_spk_config.mode_rx_cfg.mode =
				Q6AFE_MSM_SPKR_CALIBRATION;
		else
			afe_spk_config.mode_rx_cfg.mode =
				Q6AFE_MSM_SPKR_PROCESSING;
		afe_spk_config.mode_rx_cfg.minor_version = 1;
		if (afe_spk_prot_prepare(port_id, 0,
			AFE_PARAM_ID_FBSP_MODE_RX_CFG,
			&afe_spk_config, sizeof(union afe_spkr_prot_config)))
			pr_err("%s: RX MODE_VI_PROC_CFG failed\n",
					   __func__);

		if (afe_spk_config.mode_rx_cfg.mode ==
			Q6AFE_MSM_SPKR_PROCESSING) {
			if (this_afe.prot_cfg.sp_version >=
				AFE_API_VERSION_SUPPORT_SPV3) {
				afe_spk_limiter_config.limiter_th_cfg.
					minor_version = 1;
				afe_spk_limiter_config.limiter_th_cfg.
				lim_thr_per_calib_q27[SP_V2_SPKR_1] =
				this_afe.prot_cfg.limiter_th[SP_V2_SPKR_1];
				afe_spk_limiter_config.limiter_th_cfg.
				lim_thr_per_calib_q27[SP_V2_SPKR_2] =
				this_afe.prot_cfg.limiter_th[SP_V2_SPKR_2];
				if (afe_spk_prot_prepare(port_id, 0,
					AFE_PARAM_ID_SP_RX_LIMITER_TH,
					&afe_spk_limiter_config,
					sizeof(union afe_spkr_prot_config)))
					pr_err("%s: SP_RX_LIMITER_TH failed.\n",
						__func__);
			} else {
				pr_debug("%s: SPv3 failed to apply on AFE API version=%d.\n",
					__func__,
					this_afe.prot_cfg.sp_version);
			}
		}
	}
	mutex_unlock(&this_afe.cal_data[AFE_FB_SPKR_PROT_CAL]->lock);
done:
	return;
}

static int afe_send_hw_delay(u16 port_id, u32 rate)
{
	struct audio_cal_hw_delay_entry delay_entry;
	struct afe_param_id_device_hw_delay_cfg hw_delay;
	struct param_hdr_v3 param_info;
	int ret = -EINVAL;

	pr_debug("%s:\n", __func__);

	memset(&delay_entry, 0, sizeof(delay_entry));
	memset(&param_info, 0, sizeof(param_info));

	delay_entry.sample_rate = rate;
	if (afe_get_port_type(port_id) == MSM_AFE_PORT_TYPE_TX)
		ret = afe_get_cal_hw_delay(TX_DEVICE, &delay_entry);
	else if (afe_get_port_type(port_id) == MSM_AFE_PORT_TYPE_RX)
		ret = afe_get_cal_hw_delay(RX_DEVICE, &delay_entry);

	/*
	 * HW delay is only used for IMS calls to sync audio with video
	 * It is only needed for devices & sample rates used for IMS video
	 * calls. Values are received from ACDB calbration files
	 */
	if (ret != 0) {
		pr_debug("%s: debug: HW delay info not available %d\n",
			__func__, ret);
		goto fail_cmd;
	}

	param_info.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_info.instance_id = INSTANCE_ID_0;
	param_info.param_id = AFE_PARAM_ID_DEVICE_HW_DELAY;
	param_info.param_size = sizeof(hw_delay);

	hw_delay.delay_in_us = delay_entry.delay_usec;
	hw_delay.device_hw_delay_minor_version =
		AFE_API_VERSION_DEVICE_HW_DELAY;

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_info, (u8 *) &hw_delay);
	if (ret)
		pr_err("%s: AFE hw delay for port 0x%x failed %d\n",
		       __func__, port_id, ret);

fail_cmd:
	pr_info("%s: port_id 0x%x rate %u delay_usec %d status %d\n",
	__func__, port_id, rate, delay_entry.delay_usec, ret);
	return ret;
}

static struct cal_block_data *afe_find_cal_topo_id_by_port(
			struct cal_type_data *cal_type, u16 port_id)
{
	struct list_head		*ptr, *next;
	struct cal_block_data	*cal_block = NULL;
	int32_t path;
	struct audio_cal_info_afe_top *afe_top;
	int afe_port_index = q6audio_get_port_index(port_id);

	if (afe_port_index < 0)
		goto err_exit;

	list_for_each_safe(ptr, next,
		&cal_type->cal_blocks) {
		cal_block = list_entry(ptr,
			struct cal_block_data, list);
		/* Skip cal_block if it is already marked stale */
		if (cal_utils_is_cal_stale(cal_block))
			continue;
		pr_info("%s: port id: 0x%x, dev_acdb_id: %d\n", __func__,
			 port_id, this_afe.dev_acdb_id[afe_port_index]);
		path = ((afe_get_port_type(port_id) ==
			MSM_AFE_PORT_TYPE_TX)?(TX_DEVICE):(RX_DEVICE));
		afe_top =
		(struct audio_cal_info_afe_top *)cal_block->cal_info;
		if (afe_top->path == path) {
			if (this_afe.dev_acdb_id[afe_port_index] > 0) {
				if (afe_top->acdb_id ==
				    this_afe.dev_acdb_id[afe_port_index]) {
					pr_info("%s: top_id:%x acdb_id:%d afe_port_id:0x%x\n",
						 __func__, afe_top->topology,
						 afe_top->acdb_id,
						 q6audio_get_port_id(port_id));
					return cal_block;
				}
			} else {
				pr_info("%s: top_id:%x acdb_id:%d afe_port:0x%x\n",
				 __func__, afe_top->topology, afe_top->acdb_id,
				 q6audio_get_port_id(port_id));
				return cal_block;
			}
		}
	}

err_exit:
	return NULL;
}

/*
 * Retrieving cal_block will mark cal_block as stale.
 * Hence it cannot be reused or resent unless the flag
 * is reset.
 */
static int afe_get_cal_topology_id(u16 port_id, u32 *topology_id,
				   int cal_type_index)
{
	int ret = 0;

	struct cal_block_data   *cal_block = NULL;
	struct audio_cal_info_afe_top   *afe_top_info = NULL;

	if (this_afe.cal_data[cal_type_index] == NULL) {
		pr_err("%s: cal_type %d not initialized\n", __func__,
			cal_type_index);
		return -EINVAL;
	}
	if (topology_id == NULL) {
		pr_err("%s: topology_id is NULL\n", __func__);
		return -EINVAL;
	}
	*topology_id = 0;

	mutex_lock(&this_afe.cal_data[cal_type_index]->lock);
	cal_block = afe_find_cal_topo_id_by_port(
		this_afe.cal_data[cal_type_index], port_id);
	if (cal_block == NULL) {
		pr_err("%s: cal_type %d not initialized for this port %d\n",
			__func__, cal_type_index, port_id);
		ret = -EINVAL;
		goto unlock;
	}

	afe_top_info = ((struct audio_cal_info_afe_top *)
		cal_block->cal_info);
	if (!afe_top_info->topology) {
		pr_err("%s: invalid topology id : [%d, %d]\n",
		       __func__, afe_top_info->acdb_id, afe_top_info->topology);
		ret = -EINVAL;
		goto unlock;
	}
	*topology_id = (u32)afe_top_info->topology;
	cal_utils_mark_cal_used(cal_block);

	pr_info("%s: port_id = 0x%x acdb_id = %d topology_id = 0x%x cal_type_index=%d ret=%d\n",
		__func__, port_id, afe_top_info->acdb_id,
		afe_top_info->topology, cal_type_index, ret);
unlock:
	mutex_unlock(&this_afe.cal_data[cal_type_index]->lock);
	return ret;
}

static int afe_send_port_topology_id(u16 port_id)
{
	struct afe_param_id_set_topology_cfg topology;
	struct param_hdr_v3 param_info;
	u32 topology_id = 0;
	int index = 0;
	int ret = 0;

	memset(&topology, 0, sizeof(topology));
	memset(&param_info, 0, sizeof(param_info));
	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		return -EINVAL;
	}

	ret = afe_get_cal_topology_id(port_id, &topology_id, AFE_TOPOLOGY_CAL);
	if (ret < 0 && q6afe_is_afe_lsm_port(port_id)) {
		pr_debug("%s: Check for LSM topology\n", __func__);
		ret = afe_get_cal_topology_id(port_id, &topology_id,
					      AFE_LSM_TOPOLOGY_CAL);
	}
	if (ret || !topology_id) {
		pr_debug("%s: AFE port[%d] get_cal_topology[%d] invalid!\n",
				__func__, port_id, topology_id);
		goto done;
	}

	param_info.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_info.instance_id = INSTANCE_ID_0;
	param_info.param_id = AFE_PARAM_ID_SET_TOPOLOGY;
	param_info.param_size = sizeof(topology);

	topology.minor_version = AFE_API_VERSION_TOPOLOGY_V1;
	topology.topology_id = topology_id;

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_info, (u8 *) &topology);
	if (ret) {
		pr_err("%s: AFE set topology id enable for port 0x%x failed %d\n",
			__func__, port_id, ret);
		goto done;
	}

	this_afe.topology[index] = topology_id;
	rtac_update_afe_topology(port_id);
done:
	pr_info("%s: AFE set topology id 0x%x  enable for port 0x%x ret %d\n",
			__func__, topology_id, port_id, ret);
	return ret;

}


static int afe_get_island_mode(u16 port_id, u32 *island_mode)
{
	int ret = 0;
	int index = 0;
	*island_mode = 0;

	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		return -EINVAL;
	}

	*island_mode = this_afe.island_mode[index];
	return ret;
}

/*
 * afe_send_port_island_mode -
 *         for sending island mode to AFE
 *
 * @port_id: AFE port id number
 *
 * Returns 0 on success or error on failure.
 */
int afe_send_port_island_mode(u16 port_id)
{
	struct afe_param_id_island_cfg_t island_cfg;
	struct param_hdr_v3 param_info;
	u32 island_mode = 0;
	int ret = 0;

	if (!(q6core_get_avcs_api_version_per_service(
		APRV2_IDS_SERVICE_ID_ADSP_AFE_V) >= AFE_API_VERSION_V4)) {
		pr_debug("%s: AFE port[%d] API version is invalid!\n",
				__func__, port_id);
		return 0;
	}

	memset(&island_cfg, 0, sizeof(island_cfg));
	memset(&param_info, 0, sizeof(param_info));

	ret = afe_get_island_mode(port_id, &island_mode);
	if (ret) {
		pr_err("%s: AFE port[%d] get island mode is invalid!\n",
				__func__, port_id);
		return ret;
	}
	param_info.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_info.instance_id = INSTANCE_ID_0;
	param_info.param_id = AFE_PARAM_ID_ISLAND_CONFIG;
	param_info.param_size = sizeof(island_cfg);

	island_cfg.island_cfg_minor_version = AFE_API_VERSION_ISLAND_CONFIG;
	island_cfg.island_enable = island_mode;

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_info, (u8 *) &island_cfg);
	if (ret) {
		pr_err("%s: AFE set island mode enable for port 0x%x failed %d\n",
			__func__, port_id, ret);
		return ret;
	}
	pr_debug("%s: AFE set island mode 0x%x  enable for port 0x%x ret %d\n",
			__func__, island_mode, port_id, ret);
	trace_printk("%s: AFE set island mode 0x%x  enable for port 0x%x ret %d\n",
			__func__, island_mode, port_id, ret);
	return ret;
}
EXPORT_SYMBOL(afe_send_port_island_mode);

static int afe_get_vad_preroll_cfg(u16 port_id, u32 *preroll_cfg)
{
	int ret = 0;
	int index = 0;
	*preroll_cfg = 0;

	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		return -EINVAL;
	}

	*preroll_cfg = this_afe.vad_cfg[index].pre_roll;
	return ret;
}

int afe_send_port_vad_cfg_params(u16 port_id)
{
	struct afe_param_id_vad_cfg_t vad_cfg;
	struct afe_mod_enable_param vad_enable;
	struct param_hdr_v3 param_info;
	u32 pre_roll_cfg = 0;
	struct firmware_cal *hwdep_cal = NULL;
	int ret = 0;
	uint16_t port_index = 0;

	if (!(q6core_get_avcs_api_version_per_service(
	APRV2_IDS_SERVICE_ID_ADSP_AFE_V) >= AFE_API_VERSION_V4)) {
		pr_err("%s: AFE port[%d]: AFE API version doesn't support VAD config\n",
		__func__, port_id);
		return 0;
	}

	port_index = afe_get_port_index(port_id);

	if (this_afe.vad_cfg[port_index].is_enable) {
		memset(&vad_cfg, 0, sizeof(vad_cfg));
		memset(&param_info, 0, sizeof(param_info));

		ret = afe_get_vad_preroll_cfg(port_id, &pre_roll_cfg);
		if (ret) {
			pr_err("%s: AFE port[%d] get preroll cfg is invalid!\n",
					__func__, port_id);
			return ret;
		}
		param_info.module_id = AFE_MODULE_VAD;
		param_info.instance_id = INSTANCE_ID_0;
		param_info.param_id = AFE_PARAM_ID_VAD_CFG;
		param_info.param_size = sizeof(vad_cfg);

		vad_cfg.vad_cfg_minor_version = AFE_API_VERSION_VAD_CFG;
		vad_cfg.pre_roll_in_ms = pre_roll_cfg;

		ret = q6afe_pack_and_set_param_in_band(port_id,
						q6audio_get_port_index(port_id),
						param_info, (u8 *) &vad_cfg);
		if (ret) {
			pr_err("%s: AFE set vad cfg for port 0x%x failed %d\n",
				__func__, port_id, ret);
			return ret;
		}

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

		hwdep_cal = q6afecal_get_fw_cal(this_afe.fw_data,
						Q6AFE_VAD_CORE_CAL);
		if (!hwdep_cal) {
			pr_err("%s: error in retrieving vad core calibration",
				__func__);
			return -EINVAL;
		}

		param_info.module_id = AFE_MODULE_VAD;
		param_info.instance_id = INSTANCE_ID_0;
		param_info.param_id = AFE_PARAM_ID_VAD_CORE_CFG;
		param_info.param_size = hwdep_cal->size;

		ret = q6afe_pack_and_set_param_in_band(port_id,
						q6audio_get_port_index(port_id),
						param_info,
						(u8 *) hwdep_cal->data);
		if (ret) {
			pr_err("%s: AFE set vad cfg for port 0x%x failed %d\n",
				__func__, port_id, ret);
			return ret;
		}
	}

	if (q6core_get_avcs_api_version_per_service(
		APRV2_IDS_SERVICE_ID_ADSP_AFE_V) >= AFE_API_VERSION_V6) {
		memset(&vad_enable, 0, sizeof(vad_enable));
		memset(&param_info, 0, sizeof(param_info));
		param_info.module_id = AFE_MODULE_VAD;
		param_info.instance_id = INSTANCE_ID_0;
		param_info.param_id = AFE_PARAM_ID_ENABLE;
		param_info.param_size = sizeof(vad_enable);

		port_index = afe_get_port_index(port_id);
		vad_enable.enable = this_afe.vad_cfg[port_index].is_enable;

		ret = q6afe_pack_and_set_param_in_band(port_id,
						q6audio_get_port_index(port_id),
						param_info, (u8 *) &vad_enable);
		if (ret) {
			pr_err("%s: AFE set vad enable for port 0x%x failed %d\n",
				__func__, port_id, ret);
			return ret;
		}
	}

	pr_debug("%s: AFE set preroll cfg %d vad core cfg  port 0x%x ret %d\n",
			__func__, pre_roll_cfg, port_id, ret);
	return ret;
}
EXPORT_SYMBOL(afe_send_port_vad_cfg_params);

static int remap_cal_data(struct cal_block_data *cal_block, int cal_index)
{
	int ret = 0;

	if (cal_block->map_data.dma_buf == NULL) {
		pr_err("%s: No ION allocation for cal index %d!\n",
			__func__, cal_index);
		ret = -EINVAL;
		goto done;
	}

	if ((cal_block->map_data.map_size > 0) &&
		(cal_block->map_data.q6map_handle == 0)) {
		atomic_set(&this_afe.mem_map_cal_index, cal_index);
		ret = afe_cmd_memory_map(cal_block->cal_data.paddr,
				cal_block->map_data.map_size);
		atomic_set(&this_afe.mem_map_cal_index, -1);
		if (ret < 0) {
			pr_err("%s: mmap did not work! size = %zd ret %d\n",
				__func__,
				cal_block->map_data.map_size, ret);
			pr_debug("%s: mmap did not work! addr = 0x%pK, size = %zd\n",
				__func__,
				&cal_block->cal_data.paddr,
				cal_block->map_data.map_size);
			goto done;
		}
		cal_block->map_data.q6map_handle = atomic_read(&this_afe.
			mem_map_cal_handles[cal_index]);
	}
done:
	return ret;
}

static struct cal_block_data *afe_find_cal(int cal_index, int port_id)
{
	struct list_head *ptr, *next;
	struct cal_block_data *cal_block = NULL;
	struct audio_cal_info_afe *afe_cal_info = NULL;
	int afe_port_index = q6audio_get_port_index(port_id);

	pr_info("%s: cal_index %d port_id 0x%x port_index %d\n", __func__,
		  cal_index, port_id, afe_port_index);
	if (afe_port_index < 0) {
		pr_err("%s: Error getting AFE port index %d\n",
			__func__, afe_port_index);
		goto exit;
	}

	list_for_each_safe(ptr, next,
			   &this_afe.cal_data[cal_index]->cal_blocks) {
		cal_block = list_entry(ptr, struct cal_block_data, list);
		afe_cal_info = cal_block->cal_info;
		pr_info("%s: acdb_id %d dev_acdb_id %d sample_rate %d afe_sample_rates %d\n",
			__func__, afe_cal_info->acdb_id,
			this_afe.dev_acdb_id[afe_port_index],
			afe_cal_info->sample_rate,
			this_afe.afe_sample_rates[afe_port_index]);
		if ((afe_cal_info->acdb_id ==
		     this_afe.dev_acdb_id[afe_port_index]) &&
		    (afe_cal_info->sample_rate ==
		     this_afe.afe_sample_rates[afe_port_index])) {
			pr_info("%s: cal block is a match, size is %zd\n",
				 __func__, cal_block->cal_data.size);
			goto exit;
		}
	}
	pr_info("%s: no matching cal_block found\n", __func__);
	cal_block = NULL;

exit:
	return cal_block;
}

static int send_afe_cal_type(int cal_index, int port_id)
{
	struct cal_block_data		*cal_block = NULL;
	int ret;
	int afe_port_index = q6audio_get_port_index(port_id);

	pr_info("%s: cal_index is %d\n", __func__, cal_index);

	if (this_afe.cal_data[cal_index] == NULL) {
		pr_warn("%s: cal_index %d not allocated!\n",
			__func__, cal_index);
		ret = -EINVAL;
		goto done;
	}

	if (afe_port_index < 0) {
		pr_err("%s: Error getting AFE port index %d\n",
			__func__, afe_port_index);
		ret = -EINVAL;
		goto done;
	}

	mutex_lock(&this_afe.cal_data[cal_index]->lock);
	pr_info("%s: dev_acdb_id[%d] is %d\n",
			__func__, afe_port_index,
			this_afe.dev_acdb_id[afe_port_index]);
	if (((cal_index == AFE_COMMON_RX_CAL) ||
	     (cal_index == AFE_COMMON_TX_CAL) ||
	     (cal_index == AFE_LSM_TX_CAL)) &&
	    (this_afe.dev_acdb_id[afe_port_index] > 0))
		cal_block = afe_find_cal(cal_index, port_id);
	else
		cal_block = cal_utils_get_only_cal_block(
				this_afe.cal_data[cal_index]);

	if (cal_block == NULL || cal_utils_is_cal_stale(cal_block)) {
		pr_err_ratelimited("%s cal_block not found!!\n", __func__);
		ret = -EINVAL;
		goto unlock;
	}

	pr_info("%s: Sending cal_index cal %d\n", __func__, cal_index);

	ret = remap_cal_data(cal_block, cal_index);
	if (ret) {
		pr_err("%s: Remap_cal_data failed for cal %d!\n",
			__func__, cal_index);
		ret = -EINVAL;
		goto unlock;
	}
	ret = afe_send_cal_block(port_id, cal_block);
	if (ret < 0)
		pr_err("%s: No cal sent for cal_index %d, port_id = 0x%x! ret %d\n",
			__func__, cal_index, port_id, ret);

	cal_utils_mark_cal_used(cal_block);

unlock:
	mutex_unlock(&this_afe.cal_data[cal_index]->lock);
done:
	return ret;
}

void afe_send_cal(u16 port_id)
{
	int ret;

	pr_debug("%s: port_id=0x%x\n", __func__, port_id);

	if (afe_get_port_type(port_id) == MSM_AFE_PORT_TYPE_TX) {
		afe_send_cal_spkr_prot_tx(port_id);
		ret = send_afe_cal_type(AFE_COMMON_TX_CAL, port_id);
		if (ret < 0 && q6afe_is_afe_lsm_port(port_id))
			send_afe_cal_type(AFE_LSM_TX_CAL, port_id);
	} else if (afe_get_port_type(port_id) == MSM_AFE_PORT_TYPE_RX) {
		send_afe_cal_type(AFE_COMMON_RX_CAL, port_id);
		afe_send_cal_spkr_prot_rx(port_id);
	}
}

int afe_turn_onoff_hw_mad(u16 mad_type, u16 enable)
{
	struct afe_param_hw_mad_ctrl mad_enable_param;
	struct param_hdr_v3 param_info;
	int ret;

	pr_debug("%s: enter\n", __func__);

	memset(&mad_enable_param, 0, sizeof(mad_enable_param));
	memset(&param_info, 0, sizeof(param_info));
	param_info.module_id = AFE_MODULE_HW_MAD;
	param_info.instance_id = INSTANCE_ID_0;
	param_info.param_id = AFE_PARAM_ID_HW_MAD_CTRL;
	param_info.param_size = sizeof(mad_enable_param);

	mad_enable_param.minor_version = 1;
	mad_enable_param.mad_type = mad_type;
	mad_enable_param.mad_enable = enable;

	ret = q6afe_pack_and_set_param_in_band(SLIMBUS_5_TX, IDX_GLOBAL_CFG,
					       param_info,
					       (u8 *) &mad_enable_param);
	if (ret)
		pr_err("%s: AFE_PARAM_ID_HW_MAD_CTRL failed %d\n", __func__,
		       ret);
	return ret;
}

static int afe_send_slimbus_slave_cfg(
	struct afe_param_cdc_slimbus_slave_cfg *sb_slave_cfg)
{
	struct param_hdr_v3 param_hdr;
	int ret;

	pr_debug("%s: enter\n", __func__);

	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_CDC_DEV_CFG;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_CDC_SLIMBUS_SLAVE_CFG;
	param_hdr.param_size = sizeof(struct afe_param_cdc_slimbus_slave_cfg);

	ret = q6afe_svc_pack_and_set_param_in_band(IDX_GLOBAL_CFG, param_hdr,
						   (u8 *) sb_slave_cfg);
	if (ret)
		pr_err("%s: AFE_PARAM_ID_CDC_SLIMBUS_SLAVE_CFG failed %d\n",
		       __func__, ret);

	pr_debug("%s: leave %d\n", __func__, ret);
	return ret;
}

static int afe_send_codec_reg_page_config(
	struct afe_param_cdc_reg_page_cfg *cdc_reg_page_cfg)
{
	struct param_hdr_v3 param_hdr;
	int ret;

	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_CDC_DEV_CFG;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_CDC_REG_PAGE_CFG;
	param_hdr.param_size = sizeof(struct afe_param_cdc_reg_page_cfg);

	ret = q6afe_svc_pack_and_set_param_in_band(IDX_GLOBAL_CFG, param_hdr,
						   (u8 *) cdc_reg_page_cfg);
	if (ret)
		pr_err("%s: AFE_PARAM_ID_CDC_REG_PAGE_CFG failed %d\n",
		       __func__, ret);

	return ret;
}

static int afe_send_codec_reg_config(
	struct afe_param_cdc_reg_cfg_data *cdc_reg_cfg)
{
	u8 *packed_param_data = NULL;
	u32 packed_data_size = 0;
	u32 single_param_size = 0;
	u32 max_data_size = 0;
	u32 max_single_param = 0;
	struct param_hdr_v3 param_hdr;
	int idx = 0;
	int ret = -EINVAL;
	bool is_iid_supported = q6common_is_instance_id_supported();

	memset(&param_hdr, 0, sizeof(param_hdr));
	max_single_param = sizeof(struct param_hdr_v3) +
			   sizeof(struct afe_param_cdc_reg_cfg);
	max_data_size = APR_MAX_BUF - sizeof(struct afe_svc_cmd_set_param_v2);
	packed_param_data = kzalloc(max_data_size, GFP_KERNEL);
	if (!packed_param_data)
		return -ENOMEM;

	/* param_hdr is the same for all params sent, set once at top */
	param_hdr.module_id = AFE_MODULE_CDC_DEV_CFG;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_CDC_REG_CFG;
	param_hdr.param_size = sizeof(struct afe_param_cdc_reg_cfg);

	while (idx < cdc_reg_cfg->num_registers) {
		memset(packed_param_data, 0, max_data_size);
		packed_data_size = 0;
		single_param_size = 0;

		while (packed_data_size + max_single_param < max_data_size &&
		       idx < cdc_reg_cfg->num_registers) {
			ret = q6common_pack_pp_params_v2(
				packed_param_data + packed_data_size,
				&param_hdr, (u8 *) &cdc_reg_cfg->reg_data[idx],
				&single_param_size, is_iid_supported);
			if (ret) {
				pr_err("%s: Failed to pack parameters with error %d\n",
				       __func__, ret);
				goto done;
			}
			packed_data_size += single_param_size;
			idx++;
		}

		ret = q6afe_svc_set_params(IDX_GLOBAL_CFG, NULL,
					   packed_param_data, packed_data_size,
					   is_iid_supported);
		if (ret) {
			pr_err("%s: AFE_PARAM_ID_CDC_REG_CFG failed %d\n",
				__func__, ret);
			break;
		}
	}
done:
	kfree(packed_param_data);
	return ret;
}

static int afe_init_cdc_reg_config(void)
{
	struct param_hdr_v3 param_hdr;
	int ret;

	pr_debug("%s: enter\n", __func__);
	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_CDC_DEV_CFG;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_CDC_REG_CFG_INIT;

	ret = q6afe_svc_pack_and_set_param_in_band(IDX_GLOBAL_CFG, param_hdr,
						   NULL);
	if (ret)
		pr_err("%s: AFE_PARAM_ID_CDC_INIT_REG_CFG failed %d\n",
		       __func__, ret);

	return ret;
}

static int afe_send_slimbus_slave_port_cfg(
	struct afe_param_slimbus_slave_port_cfg *slim_slave_config, u16 port_id)
{
	struct param_hdr_v3 param_hdr;
	int ret;

	pr_debug("%s: enter, port_id =  0x%x\n", __func__, port_id);
	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_HW_MAD;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.reserved = 0;
	param_hdr.param_id = AFE_PARAM_ID_SLIMBUS_SLAVE_PORT_CFG;
	param_hdr.param_size = sizeof(struct afe_param_slimbus_slave_port_cfg);

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr,
					       (u8 *) slim_slave_config);
	if (ret)
		pr_err("%s: AFE_PARAM_ID_SLIMBUS_SLAVE_PORT_CFG failed %d\n",
			__func__, ret);

	pr_debug("%s: leave %d\n", __func__, ret);
	return ret;
}
static int afe_aanc_port_cfg(void *apr, uint16_t tx_port, uint16_t rx_port)
{
	struct afe_param_aanc_port_cfg aanc_port_cfg;
	struct param_hdr_v3 param_hdr;
	int ret = 0;

	pr_debug("%s: tx_port 0x%x, rx_port 0x%x\n",
		__func__, tx_port, rx_port);

	pr_debug("%s: AANC sample rate tx rate: %d rx rate %d\n", __func__,
		 this_afe.aanc_info.aanc_tx_port_sample_rate,
		 this_afe.aanc_info.aanc_rx_port_sample_rate);

	memset(&aanc_port_cfg, 0, sizeof(aanc_port_cfg));
	memset(&param_hdr, 0, sizeof(param_hdr));

	/*
	 * If aanc tx sample rate or rx sample rate is zero, skip aanc
	 * configuration as AFE resampler will fail for invalid sample
	 * rates.
	 */
	if (!this_afe.aanc_info.aanc_tx_port_sample_rate ||
	    !this_afe.aanc_info.aanc_rx_port_sample_rate) {
		return -EINVAL;
	}

	param_hdr.module_id = AFE_MODULE_AANC;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_AANC_PORT_CONFIG;
	param_hdr.param_size = sizeof(struct afe_param_aanc_port_cfg);

	aanc_port_cfg.aanc_port_cfg_minor_version =
		AFE_API_VERSION_AANC_PORT_CONFIG;
	aanc_port_cfg.tx_port_sample_rate =
		this_afe.aanc_info.aanc_tx_port_sample_rate;
	aanc_port_cfg.tx_port_channel_map[0] = AANC_TX_VOICE_MIC;
	aanc_port_cfg.tx_port_channel_map[1] = AANC_TX_NOISE_MIC;
	aanc_port_cfg.tx_port_channel_map[2] = AANC_TX_ERROR_MIC;
	aanc_port_cfg.tx_port_channel_map[3] = AANC_TX_MIC_UNUSED;
	aanc_port_cfg.tx_port_channel_map[4] = AANC_TX_MIC_UNUSED;
	aanc_port_cfg.tx_port_channel_map[5] = AANC_TX_MIC_UNUSED;
	aanc_port_cfg.tx_port_channel_map[6] = AANC_TX_MIC_UNUSED;
	aanc_port_cfg.tx_port_channel_map[7] = AANC_TX_MIC_UNUSED;
	aanc_port_cfg.tx_port_num_channels = 3;
	aanc_port_cfg.rx_path_ref_port_id = rx_port;
	aanc_port_cfg.ref_port_sample_rate =
		this_afe.aanc_info.aanc_rx_port_sample_rate;

	ret = q6afe_pack_and_set_param_in_band(tx_port,
					       q6audio_get_port_index(tx_port),
					       param_hdr,
					       (u8 *) &aanc_port_cfg);
	if (ret)
		pr_err("%s: AFE AANC port config failed for tx_port 0x%x, rx_port 0x%x ret %d\n",
		       __func__, tx_port, rx_port, ret);
	else
		q6afe_set_aanc_level();

	return ret;
}

static int afe_aanc_mod_enable(void *apr, uint16_t tx_port, uint16_t enable)
{
	struct afe_mod_enable_param mod_enable;
	struct param_hdr_v3 param_hdr;
	int ret = 0;

	pr_debug("%s: tx_port 0x%x\n", __func__, tx_port);

	memset(&mod_enable, 0, sizeof(mod_enable));
	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_AANC;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_ENABLE;
	param_hdr.param_size = sizeof(struct afe_mod_enable_param);

	mod_enable.enable = enable;
	mod_enable.reserved = 0;

	ret = q6afe_pack_and_set_param_in_band(tx_port,
					       q6audio_get_port_index(tx_port),
					       param_hdr, (u8 *) &mod_enable);
	if (ret)
		pr_err("%s: AFE AANC enable failed for tx_port 0x%x ret %d\n",
			__func__, tx_port, ret);
	return ret;
}

static int afe_send_bank_selection_clip(
		struct afe_param_id_clip_bank_sel *param)
{
	struct param_hdr_v3 param_hdr;
	int ret;

	if (!param) {
		pr_err("%s: Invalid params", __func__);
		return -EINVAL;
	}
	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_CDC_DEV_CFG;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_CLIP_BANK_SEL_CFG;
	param_hdr.param_size = sizeof(struct afe_param_id_clip_bank_sel);

	ret = q6afe_svc_pack_and_set_param_in_band(IDX_GLOBAL_CFG, param_hdr,
						   (u8 *) param);
	if (ret)
		pr_err("%s: AFE_PARAM_ID_CLIP_BANK_SEL_CFG failed %d\n",
		__func__, ret);
	return ret;
}
int afe_send_aanc_version(
	struct afe_param_id_cdc_aanc_version *version_cfg)
{
	struct param_hdr_v3 param_hdr;
	int ret;

	pr_debug("%s: enter\n", __func__);
	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_CDC_DEV_CFG;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_CDC_AANC_VERSION;
	param_hdr.param_size = sizeof(struct afe_param_id_cdc_aanc_version);

	ret = q6afe_svc_pack_and_set_param_in_band(IDX_GLOBAL_CFG, param_hdr,
						   (u8 *) version_cfg);
	if (ret)
		pr_err("%s: AFE_PARAM_ID_CDC_AANC_VERSION failed %d\n",
		__func__, ret);
	return ret;
}

/**
 * afe_port_set_mad_type -
 *        to update mad type
 *
 * @port_id: AFE port id number
 * @mad_type: MAD type enum value
 *
 * Returns 0 on success or error on failure.
 */
int afe_port_set_mad_type(u16 port_id, enum afe_mad_type mad_type)
{
	int i;

	if (port_id == AFE_PORT_ID_TERTIARY_MI2S_TX ||
		port_id == AFE_PORT_ID_INT3_MI2S_TX ||
		port_id == AFE_PORT_ID_TX_CODEC_DMA_TX_3 ||
		port_id == AFE_PORT_ID_PRIMARY_TDM_TX) {
		mad_type = MAD_SW_AUDIO;
		return 0;
	}

	i = port_id - SLIMBUS_0_RX;
	if (i < 0 || i >= ARRAY_SIZE(afe_ports_mad_type)) {
		pr_err("%s: Invalid port_id 0x%x\n", __func__, port_id);
		return -EINVAL;
	}
	atomic_set(&afe_ports_mad_type[i], mad_type);
	return 0;
}
EXPORT_SYMBOL(afe_port_set_mad_type);

/**
 * afe_port_get_mad_type -
 *        to retrieve mad type
 *
 * @port_id: AFE port id number
 *
 * Returns valid enum value on success or MAD_HW_NONE on failure.
 */
enum afe_mad_type afe_port_get_mad_type(u16 port_id)
{
	int i;

	if (port_id == AFE_PORT_ID_TERTIARY_MI2S_TX ||
		port_id == AFE_PORT_ID_INT3_MI2S_TX ||
		port_id == AFE_PORT_ID_TX_CODEC_DMA_TX_3 ||
		port_id == AFE_PORT_ID_PRIMARY_TDM_TX)
		return MAD_SW_AUDIO;

	i = port_id - SLIMBUS_0_RX;
	if (i < 0 || i >= ARRAY_SIZE(afe_ports_mad_type)) {
		pr_debug("%s: Non Slimbus port_id 0x%x\n", __func__, port_id);
		return MAD_HW_NONE;
	}
	return (enum afe_mad_type) atomic_read(&afe_ports_mad_type[i]);
}
EXPORT_SYMBOL(afe_port_get_mad_type);

/**
 * afe_set_config -
 *        to configure AFE session with
 *        specified configuration for given config type
 *
 * @config_type: config type
 * @config_data: configuration to pass to AFE session
 * @arg: argument used in specific config types
 *
 * Returns 0 on success or error value on port start failure.
 */
int afe_set_config(enum afe_config_type config_type, void *config_data, int arg)
{
	int ret;

	pr_debug("%s: enter config_type %d\n", __func__, config_type);
	ret = afe_q6_interface_prepare();
	if (ret) {
		pr_err("%s: Q6 interface prepare failed %d\n", __func__, ret);
		return ret;
	}

	switch (config_type) {
	case AFE_SLIMBUS_SLAVE_CONFIG:
		ret = afe_send_slimbus_slave_cfg(config_data);
		if (!ret)
			ret = afe_init_cdc_reg_config();
		else
			pr_err("%s: Sending slimbus slave config failed %d\n",
			       __func__, ret);
		break;
	case AFE_CDC_REGISTERS_CONFIG:
		ret = afe_send_codec_reg_config(config_data);
		break;
	case AFE_SLIMBUS_SLAVE_PORT_CONFIG:
		ret = afe_send_slimbus_slave_port_cfg(config_data, arg);
		break;
	case AFE_AANC_VERSION:
		ret = afe_send_aanc_version(config_data);
		break;
	case AFE_CLIP_BANK_SEL:
		ret = afe_send_bank_selection_clip(config_data);
		break;
	case AFE_CDC_CLIP_REGISTERS_CONFIG:
		ret = afe_send_codec_reg_config(config_data);
		break;
	case AFE_CDC_REGISTER_PAGE_CONFIG:
		ret = afe_send_codec_reg_page_config(config_data);
		break;
	default:
		pr_err("%s: unknown configuration type %d",
			__func__, config_type);
		ret = -EINVAL;
	}

	if (!ret)
		set_bit(config_type, &afe_configured_cmd);

	return ret;
}
EXPORT_SYMBOL(afe_set_config);

/*
 * afe_clear_config - If SSR happens ADSP loses AFE configs, let AFE driver know
 *		      about the state so client driver can wait until AFE is
 *		      reconfigured.
 */
void afe_clear_config(enum afe_config_type config)
{
	clear_bit(config, &afe_configured_cmd);
}
EXPORT_SYMBOL(afe_clear_config);

bool afe_has_config(enum afe_config_type config)
{
	return !!test_bit(config, &afe_configured_cmd);
}

int afe_send_spdif_clk_cfg(struct afe_param_id_spdif_clk_cfg *cfg,
		u16 port_id)
{
	struct afe_param_id_spdif_clk_cfg clk_cfg;
	struct param_hdr_v3 param_hdr;
	int ret = 0;

	if (!cfg) {
		pr_err("%s: Error, no configuration data\n", __func__);
		return -EINVAL;
	}

	memset(&clk_cfg, 0, sizeof(clk_cfg));
	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_SPDIF_CLK_CONFIG;
	param_hdr.param_size = sizeof(struct afe_param_id_spdif_clk_cfg);

	pr_debug("%s: Minor version = 0x%x clk val = %d clk root = 0x%x port id = 0x%x\n",
		__func__, clk_cfg.clk_cfg_minor_version, clk_cfg.clk_value,
		clk_cfg.clk_root, q6audio_get_port_id(port_id));

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) &clk_cfg);
	if (ret < 0)
		pr_err("%s: AFE send clock config for port 0x%x failed ret = %d\n",
				__func__, port_id, ret);
	return ret;
}

/**
 * afe_send_spdif_ch_status_cfg -
 *        to configure AFE session with
 *        specified channel status configuration
 *
 * @ch_status_cfg: channel status configutation
 * @port_id: AFE port id number
 *
 * Returns 0 on success or error value on port start failure.
 */
int afe_send_spdif_ch_status_cfg(struct afe_param_id_spdif_ch_status_cfg
		*ch_status_cfg,	u16 port_id)
{
	struct param_hdr_v3 param_hdr;
	int ret = 0;

	if (!ch_status_cfg) {
		pr_err("%s: Error, no configuration data\n", __func__);
		return -EINVAL;
	}

	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_SPDIF_CLK_CONFIG;
	param_hdr.param_size = sizeof(struct afe_param_id_spdif_ch_status_cfg);

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) ch_status_cfg);
	if (ret < 0)
		pr_err("%s: AFE send channel status for port 0x%x failed ret = %d\n",
				__func__, port_id, ret);
	return ret;
}
EXPORT_SYMBOL(afe_send_spdif_ch_status_cfg);

int afe_send_cmd_wakeup_register(void *handle, bool enable)
{
	struct afe_svc_cmd_evt_cfg_payload wakeup_irq;
	int ret = 0;

	pr_debug("%s: enter\n", __func__);

	wakeup_irq.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
					    APR_HDR_LEN(APR_HDR_SIZE),
					    APR_PKT_VER);
	wakeup_irq.hdr.pkt_size = sizeof(wakeup_irq);
	wakeup_irq.hdr.src_port = 0;
	wakeup_irq.hdr.dest_port = 0;
	wakeup_irq.hdr.token = 0x0;
	wakeup_irq.hdr.opcode = AFE_SVC_CMD_EVENT_CFG;
	wakeup_irq.event_id = AFE_EVENT_ID_MBHC_DETECTION_SW_WA;
	wakeup_irq.reg_flag = enable;
	pr_debug("%s: cmd wakeup register opcode[0x%x] register:%d\n",
		 __func__, wakeup_irq.hdr.opcode, wakeup_irq.reg_flag);

	ret = afe_apr_send_pkt(&wakeup_irq, &this_afe.wait_wakeup);
	if (ret)
		pr_err("%s: AFE wakeup command register %d failed %d\n",
			__func__, enable, ret);

	return ret;
}
EXPORT_SYMBOL(afe_send_cmd_wakeup_register);

static int afe_send_cmd_port_start(u16 port_id)
{
	struct afe_port_cmd_device_start start;
	int ret, index;

	pr_debug("%s: enter\n", __func__);
	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		return -EINVAL;
	}
	ret = q6audio_validate_port(port_id);
	if (ret < 0) {
		pr_err("%s: port id: 0x%x ret %d\n", __func__, port_id, ret);
		return -EINVAL;
	}

	start.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
					    APR_HDR_LEN(APR_HDR_SIZE),
					    APR_PKT_VER);
	start.hdr.pkt_size = sizeof(start);
	start.hdr.src_port = 0;
	start.hdr.dest_port = 0;
	start.hdr.token = index;
	start.hdr.opcode = AFE_PORT_CMD_DEVICE_START;
	start.port_id = q6audio_get_port_id(port_id);
	pr_debug("%s: cmd device start opcode[0x%x] port id[0x%x]\n",
		 __func__, start.hdr.opcode, start.port_id);

	ret = afe_apr_send_pkt(&start, &this_afe.wait[index]);
	if (ret)
		pr_err("%s: AFE enable for port 0x%x failed %d\n", __func__,
		       port_id, ret);

	return ret;
}

static int afe_aanc_start(uint16_t tx_port_id, uint16_t rx_port_id)
{
	int ret;

	pr_debug("%s:  Tx port is 0x%x, Rx port is 0x%x\n",
		 __func__, tx_port_id, rx_port_id);
	ret = afe_aanc_port_cfg(this_afe.apr, tx_port_id, rx_port_id);
	if (ret) {
		pr_err("%s: Send AANC Port Config failed %d\n",
			__func__, ret);
		goto fail_cmd;
	}
	send_afe_cal_type(AFE_AANC_CAL, tx_port_id);

fail_cmd:
	return ret;
}

/**
 * afe_spdif_port_start - to configure AFE session with
 * specified port configuration
 *
 * @port_id: AFE port id number
 * @spdif_port: spdif port configutation
 * @rate: sampling rate of port
 *
 * Returns 0 on success or error value on port start failure.
 */
int afe_spdif_port_start(u16 port_id, struct afe_spdif_port_config *spdif_port,
		u32 rate)
{
	struct param_hdr_v3 param_hdr;
	uint16_t port_index;
	int ret = 0;

	if (!spdif_port) {
		pr_err("%s: Error, no configuration data\n", __func__);
		ret = -EINVAL;
		return ret;
	}

	pr_debug("%s: port id: 0x%x\n", __func__, port_id);

	memset(&param_hdr, 0, sizeof(param_hdr));
	ret = q6audio_validate_port(port_id);
	if (ret < 0) {
		pr_err("%s: port id: 0x%x ret %d\n", __func__, port_id, ret);
		return -EINVAL;
	}

	afe_send_cal(port_id);
	afe_send_hw_delay(port_id, rate);

	param_hdr.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_SPDIF_CONFIG;
	param_hdr.param_size = sizeof(struct afe_spdif_port_config);

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) spdif_port);
	if (ret) {
		pr_err("%s: AFE enable for port 0x%x failed ret = %d\n",
			__func__, port_id, ret);
		goto fail_cmd;
	}

	port_index = afe_get_port_index(port_id);
	if ((port_index >= 0) && (port_index < AFE_MAX_PORTS)) {
		this_afe.afe_sample_rates[port_index] = rate;
	} else {
		pr_err("%s: Invalid port index %d\n", __func__, port_index);
		ret = -EINVAL;
		goto fail_cmd;
	}

	if (afe_get_port_type(port_id) == MSM_AFE_PORT_TYPE_RX) {
		ret = afe_send_spdif_ch_status_cfg(&spdif_port->ch_status,
						   port_id);
		if (ret < 0) {
			pr_err("%s: afe send failed %d\n", __func__, ret);
			goto fail_cmd;
		}
	}

	return afe_send_cmd_port_start(port_id);

fail_cmd:
	return ret;
}
EXPORT_SYMBOL(afe_spdif_port_start);

/**
 * afe_spdif_reg_event_cfg -
 *         register for event from AFE spdif port
 *
 * @port_id: Port ID to register event
 * @reg_flag: register or unregister
 * @cb: callback function to invoke for events from module
 * @private_data: private data to sent back in callback fn
 *
 * Returns 0 on success or error on failure
 */
int afe_spdif_reg_event_cfg(u16 port_id, u16 reg_flag,
		void (*cb)(uint32_t opcode,
		uint32_t token, uint32_t *payload, void *priv),
		void *private_data)
{
	struct afe_port_cmd_event_cfg *config;
	struct afe_port_cmd_mod_evt_cfg_payload pl;
	int index;
	int ret;
	int num_events = 1;
	int cmd_size = sizeof(struct afe_port_cmd_event_cfg) +
		(num_events * sizeof(struct afe_port_cmd_mod_evt_cfg_payload));

	config = kzalloc(cmd_size, GFP_KERNEL);
	if (!config)
		return -ENOMEM;

	if (port_id == AFE_PORT_ID_PRIMARY_SPDIF_TX) {
		this_afe.pri_spdif_tx_cb = cb;
		this_afe.pri_spdif_tx_private_data = private_data;
	} else if (port_id == AFE_PORT_ID_SECONDARY_SPDIF_TX) {
		this_afe.sec_spdif_tx_cb = cb;
		this_afe.sec_spdif_tx_private_data = private_data;
	} else {
		pr_err("%s: wrong port id 0x%x\n", __func__, port_id);
		ret = -EINVAL;
		goto fail_idx;
	}

	index = q6audio_get_port_index(port_id);
	if (index < 0) {
		pr_err("%s: Invalid index number: %d\n", __func__, index);
		ret = -EINVAL;
		goto fail_idx;
	}

	memset(&pl, 0, sizeof(pl));
	pl.module_id = AFE_MODULE_CUSTOM_EVENTS;
	pl.event_id = AFE_PORT_FMT_UPDATE_EVENT;
	pl.reg_flag = reg_flag;

	config->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	config->hdr.pkt_size = cmd_size;
	config->hdr.src_port = 1;
	config->hdr.dest_port = 1;
	config->hdr.token = index;

	config->hdr.opcode = AFE_PORT_CMD_MOD_EVENT_CFG;
	config->port_id = q6audio_get_port_id(port_id);
	config->num_events = num_events;
	config->version = 1;
	memcpy(config->payload, &pl, sizeof(pl));
	ret = afe_apr_send_pkt((uint32_t *) config, &this_afe.wait[index]);

fail_idx:
	kfree(config);
	return ret;
}
EXPORT_SYMBOL(afe_spdif_reg_event_cfg);

int afe_send_slot_mapping_cfg(
	struct afe_param_id_slot_mapping_cfg *slot_mapping_cfg,
	u16 port_id)
{
	struct param_hdr_v3 param_hdr;
	int ret = 0;

	if (!slot_mapping_cfg) {
		pr_err("%s: Error, no configuration data\n", __func__);
		return -EINVAL;
	}

	pr_debug("%s: port id: 0x%x\n", __func__, port_id);

	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_TDM;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_PORT_SLOT_MAPPING_CONFIG;
	param_hdr.param_size = sizeof(struct afe_param_id_slot_mapping_cfg);

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr,
					       (u8 *) slot_mapping_cfg);
	if (ret < 0)
		pr_err("%s: AFE send slot mapping for port 0x%x failed ret = %d\n",
				__func__, port_id, ret);
	return ret;
}

int afe_send_slot_mapping_cfg_v2(
	struct afe_param_id_slot_mapping_cfg_v2 *slot_mapping_cfg,
	u16 port_id)
{
	struct param_hdr_v3 param_hdr;
	int ret = 0;

	if (!slot_mapping_cfg) {
		pr_err("%s: Error, no configuration data\n", __func__);
		return -EINVAL;
	}

	pr_debug("%s: port id: 0x%x\n", __func__, port_id);

	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_TDM;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_PORT_SLOT_MAPPING_CONFIG;
	param_hdr.param_size = sizeof(struct afe_param_id_slot_mapping_cfg_v2);

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr,
					       (u8 *) slot_mapping_cfg);
	if (ret < 0)
		pr_err("%s: AFE send slot mapping for port 0x%x failed ret = %d\n",
				__func__, port_id, ret);
	return ret;
}

int afe_send_custom_tdm_header_cfg(
	struct afe_param_id_custom_tdm_header_cfg *custom_tdm_header_cfg,
	u16 port_id)
{
	struct param_hdr_v3 param_hdr;
	int ret = 0;

	if (!custom_tdm_header_cfg) {
		pr_err("%s: Error, no configuration data\n", __func__);
		return -EINVAL;
	}

	pr_debug("%s: port id: 0x%x\n", __func__, port_id);

	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_TDM;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_CUSTOM_TDM_HEADER_CONFIG;
	param_hdr.param_size =
		sizeof(struct afe_param_id_custom_tdm_header_cfg);

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr,
					       (u8 *) custom_tdm_header_cfg);
	if (ret < 0)
		pr_err("%s: AFE send custom tdm header for port 0x%x failed ret = %d\n",
				__func__, port_id, ret);
	return ret;
}

/**
 * afe_tdm_port_start - to configure AFE session with
 * specified port configuration
 *
 * @port_id: AFE port id number
 * @tdm_port: TDM port configutation
 * @rate: sampling rate of port
 * @num_groups: number of TDM groups
 *
 * Returns 0 on success or error value on port start failure.
 */
int afe_tdm_port_start(u16 port_id, struct afe_tdm_port_config *tdm_port,
		       u32 rate, u16 num_groups)
{
	struct param_hdr_v3 param_hdr;
	int index = 0;
	uint16_t port_index = 0;
	enum afe_mad_type mad_type = MAD_HW_NONE;
	int ret = 0;

	if (!tdm_port) {
		pr_err("%s: Error, no configuration data\n", __func__);
		return -EINVAL;
	}

	pr_debug("%s: port id: 0x%x\n", __func__, port_id);

	memset(&param_hdr, 0, sizeof(param_hdr));
	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		return -EINVAL;
	}
	ret = q6audio_validate_port(port_id);
	if (ret < 0) {
		pr_err("%s: port id: 0x%x ret %d\n", __func__, port_id, ret);
		return -EINVAL;
	}

	ret = afe_q6_interface_prepare();
	if (ret != 0) {
		pr_err("%s: Q6 interface prepare failed %d\n", __func__, ret);
		return ret;
	}

	if ((index >= 0) && (index < AFE_MAX_PORTS)) {
		this_afe.afe_sample_rates[index] = rate;

		if (this_afe.rt_cb)
			this_afe.dev_acdb_id[index] = this_afe.rt_cb(port_id);
	}

	port_index = afe_get_port_index(port_id);

	/* Also send the topology id here: */
	if (!(this_afe.afe_cal_mode[port_index] == AFE_CAL_MODE_NONE)) {
		/* One time call: only for first time */
		afe_send_custom_topology();
		afe_send_port_topology_id(port_id);
		afe_send_cal(port_id);
		afe_send_hw_delay(port_id, rate);
	}

	/* Start SW MAD module */
	mad_type = afe_port_get_mad_type(port_id);
	pr_debug("%s: port_id 0x%x, mad_type %d\n", __func__, port_id,
		 mad_type);
	if (mad_type != MAD_HW_NONE && mad_type != MAD_SW_AUDIO) {
		if (!afe_has_config(AFE_CDC_REGISTERS_CONFIG) ||
			!afe_has_config(AFE_SLIMBUS_SLAVE_CONFIG)) {
			pr_err("%s: AFE isn't configured yet for\n"
				"HW MAD try Again\n", __func__);
				ret = -EAGAIN;
				goto fail_cmd;
		}
		ret = afe_turn_onoff_hw_mad(mad_type, true);
		if (ret) {
			pr_err("%s: afe_turn_onoff_hw_mad failed %d\n",
			       __func__, ret);
			goto fail_cmd;
		}
	}

	param_hdr.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_TDM_CONFIG;
	param_hdr.param_size = sizeof(struct afe_param_id_tdm_cfg);

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr,
					       (u8 *) &tdm_port->tdm);
	if (ret) {
		pr_err("%s: AFE enable for port 0x%x failed ret = %d\n",
				__func__, port_id, ret);
		goto fail_cmd;
	}

	port_index = afe_get_port_index(port_id);
	if ((port_index >= 0) && (port_index < AFE_MAX_PORTS)) {
		this_afe.afe_sample_rates[port_index] = rate;
	} else {
		pr_err("%s: Invalid port index %d\n", __func__, port_index);
		ret = -EINVAL;
		goto fail_cmd;
	}

	if (q6core_get_avcs_api_version_per_service(
		APRV2_IDS_SERVICE_ID_ADSP_AFE_V) >= AFE_API_VERSION_V3)
		ret = afe_send_slot_mapping_cfg_v2(
				&tdm_port->slot_mapping_v2, port_id);
	else
		ret = afe_send_slot_mapping_cfg(
				&tdm_port->slot_mapping,
				port_id);

	if (ret < 0) {
		pr_err("%s: afe send failed %d\n", __func__, ret);
		goto fail_cmd;
	}

	if (tdm_port->custom_tdm_header.header_type) {
		ret = afe_send_custom_tdm_header_cfg(
			&tdm_port->custom_tdm_header, port_id);
		if (ret < 0) {
			pr_err("%s: afe send failed %d\n", __func__, ret);
			goto fail_cmd;
		}
	}

	ret = afe_send_cmd_port_start(port_id);

fail_cmd:
	return ret;
}
EXPORT_SYMBOL(afe_tdm_port_start);

/**
 * afe_set_cal_mode -
 *         set cal mode for AFE calibration
 *
 * @port_id: AFE port id number
 * @afe_cal_mode: AFE calib mode
 *
 */
void afe_set_cal_mode(u16 port_id, enum afe_cal_mode afe_cal_mode)
{
	uint16_t port_index;

	port_index = afe_get_port_index(port_id);
	this_afe.afe_cal_mode[port_index] = afe_cal_mode;
}
EXPORT_SYMBOL(afe_set_cal_mode);

/**
 * afe_set_vad_cfg -
 *         set configuration for VAD
 *
 * @port_id: AFE port id number
 * @vad_enable: enable/disable vad
 * @preroll_config: Preroll configuration
 *
 */
void afe_set_vad_cfg(u32 vad_enable, u32 preroll_config,
		     u32 port_id)
{
	uint16_t port_index;

	port_index = afe_get_port_index(port_id);
	this_afe.vad_cfg[port_index].is_enable = vad_enable;
	this_afe.vad_cfg[port_index].pre_roll = preroll_config;
}
EXPORT_SYMBOL(afe_set_vad_cfg);

/**
 * afe_get_island_mode_cfg -
 *         get island mode configuration
 *
 * @port_id: AFE port id number
 * @enable_flag: Enable or Disable
 *
 */
void afe_get_island_mode_cfg(u16 port_id, u32 *enable_flag)
{
	uint16_t port_index;

	if (enable_flag) {
		port_index = afe_get_port_index(port_id);
		*enable_flag = this_afe.island_mode[port_index];
	}
}
EXPORT_SYMBOL(afe_get_island_mode_cfg);

/**
 * afe_set_island_mode_cfg -
 *         set island mode configuration
 *
 * @port_id: AFE port id number
 * @enable_flag: Enable or Disable
 *
 */
void afe_set_island_mode_cfg(u16 port_id, u32 enable_flag)
{
	uint16_t port_index;

	port_index = afe_get_port_index(port_id);
	this_afe.island_mode[port_index] = enable_flag;

	trace_printk("%s: set island mode cfg 0x%x for port 0x%x\n",
			__func__, this_afe.island_mode[port_index], port_id);
}
EXPORT_SYMBOL(afe_set_island_mode_cfg);

/**
 * afe_set_routing_callback -
 *         Update callback function for routing
 *
 * @cb: callback function to update with
 *
 */
void afe_set_routing_callback(routing_cb cb)
{
	this_afe.rt_cb = cb;
}
EXPORT_SYMBOL(afe_set_routing_callback);

int afe_port_send_usb_dev_param(u16 port_id, union afe_port_config *afe_config)
{
	struct afe_param_id_usb_audio_dev_params usb_dev;
	struct afe_param_id_usb_audio_dev_lpcm_fmt lpcm_fmt;
	struct afe_param_id_usb_audio_svc_interval svc_int;
	struct param_hdr_v3 param_hdr;
	int ret = 0, index = 0;

	if (!afe_config) {
		pr_err("%s: Error, no configuration data\n", __func__);
		ret = -EINVAL;
		goto exit;
	}

	index = q6audio_get_port_index(port_id);

	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		return -EINVAL;
	}
	memset(&usb_dev, 0, sizeof(usb_dev));
	memset(&lpcm_fmt, 0, sizeof(lpcm_fmt));
	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_hdr.instance_id = INSTANCE_ID_0;

	param_hdr.param_id = AFE_PARAM_ID_USB_AUDIO_DEV_PARAMS;
	param_hdr.param_size = sizeof(usb_dev);
	usb_dev.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
	usb_dev.dev_token = afe_config->usb_audio.dev_token;

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) &usb_dev);
	if (ret) {
		pr_err("%s: AFE device param cmd failed %d\n",
			__func__, ret);
		goto exit;
	}

	param_hdr.param_id = AFE_PARAM_ID_USB_AUDIO_DEV_LPCM_FMT;
	param_hdr.param_size = sizeof(lpcm_fmt);
	lpcm_fmt.cfg_minor_version = AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
	lpcm_fmt.endian = afe_config->usb_audio.endian;

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) &lpcm_fmt);
	if (ret) {
		pr_err("%s: AFE device param cmd LPCM_FMT failed %d\n",
			__func__, ret);
		goto exit;
	}
	param_hdr.param_id = AFE_PARAM_ID_USB_AUDIO_SVC_INTERVAL;
	param_hdr.param_size = sizeof(svc_int);
	svc_int.cfg_minor_version =
		AFE_API_MINOR_VERSION_USB_AUDIO_CONFIG;
	svc_int.svc_interval = afe_config->usb_audio.service_interval;

	pr_debug("%s: AFE device param cmd sending SVC_INTERVAL %d\n",
			__func__, svc_int.svc_interval);

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) &svc_int);

	if (ret) {
		pr_err("%s: AFE device param cmd svc_interval failed %d\n",
			__func__, ret);
		ret = -EINVAL;
		goto exit;
	}
exit:
	return ret;
}

static int q6afe_send_ttp_config(u16 port_id,
			union afe_port_config afe_config,
			struct afe_ttp_config *ttp_cfg)
{
	struct afe_ttp_gen_enable_t ttp_gen_enable;
	struct afe_ttp_gen_cfg_t ttp_gen_cfg;
	struct param_hdr_v3 param_hdr;
	int ret;

	memset(&ttp_gen_enable, 0, sizeof(ttp_gen_enable));
	memset(&ttp_gen_cfg, 0, sizeof(ttp_gen_cfg));
	memset(&param_hdr, 0, sizeof(param_hdr));

	param_hdr.module_id = AFE_MODULE_ID_DECODER;
	param_hdr.instance_id = INSTANCE_ID_0;

	pr_debug("%s: Enable TTP generator\n", __func__);
	ttp_gen_enable = ttp_cfg->ttp_gen_enable;
	param_hdr.param_id = AVS_DEPACKETIZER_PARAM_ID_TTP_GEN_STATE;
	param_hdr.param_size = sizeof(struct afe_ttp_gen_enable_t);
	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr,
					       (u8 *) &ttp_gen_enable);
	if (ret) {
		pr_err("%s: AVS_DEPACKETIZER_PARAM_ID_TTP_GEN_STATE for port 0x%x failed %d\n",
			__func__, port_id, ret);
		goto exit;
	}

	pr_debug("%s: sending TTP generator config\n", __func__);
	ttp_gen_cfg = ttp_cfg->ttp_gen_cfg;
	param_hdr.param_id = AVS_DEPACKETIZER_PARAM_ID_TTP_GEN_CFG;
	param_hdr.param_size = sizeof(struct afe_ttp_gen_cfg_t);
	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr,
					       (u8 *) &ttp_gen_cfg);
	if (ret)
		pr_err("%s: AVS_DEPACKETIZER_PARAM_ID_TTP_GEN_CFG for port 0x%x failed %d\n",
			__func__, port_id, ret);
exit:
	return ret;
}

static int q6afe_send_dec_config(u16 port_id,
			union afe_port_config afe_config,
			struct afe_dec_config *cfg,
			u32 format,
			u16 afe_in_channels, u16 afe_in_bit_width)
{
	struct afe_dec_media_fmt_t dec_media_fmt;
	struct avs_dec_depacketizer_id_param_t dec_depkt_id_param;
	struct avs_dec_congestion_buffer_param_t dec_buffer_id_param;
	struct afe_enc_dec_imc_info_param_t imc_info_param;
	struct afe_port_media_type_t media_type;
	struct afe_matched_port_t matched_port_param;
	struct asm_aptx_ad_speech_mode_cfg_t speech_codec_init_param;
	struct param_hdr_v3 param_hdr;
	int ret;
	u32 dec_fmt;

	memset(&dec_depkt_id_param, 0, sizeof(dec_depkt_id_param));
	memset(&dec_media_fmt, 0, sizeof(dec_media_fmt));
	memset(&imc_info_param, 0, sizeof(imc_info_param));
	memset(&media_type, 0, sizeof(media_type));
	memset(&matched_port_param, 0, sizeof(matched_port_param));
	memset(&speech_codec_init_param, 0, sizeof(speech_codec_init_param));
	memset(&param_hdr, 0, sizeof(param_hdr));

	param_hdr.module_id = AFE_MODULE_ID_DECODER;
	param_hdr.instance_id = INSTANCE_ID_0;

	pr_debug("%s: sending AFE_DECODER_PARAM_ID_DEPACKETIZER to DSP payload\n",
		  __func__);
	param_hdr.param_id = AFE_DECODER_PARAM_ID_DEPACKETIZER_ID;
	param_hdr.param_size = sizeof(struct avs_dec_depacketizer_id_param_t);
	dec_depkt_id_param.dec_depacketizer_id =
					       AFE_MODULE_ID_DEPACKETIZER_COP_V1;
	if (cfg->format == ENC_CODEC_TYPE_LDAC)
		dec_depkt_id_param.dec_depacketizer_id =
					       AFE_MODULE_ID_DEPACKETIZER_COP;
	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr,
					       (u8 *) &dec_depkt_id_param);
	if (ret) {
		pr_err("%s: AFE_DECODER_PARAM_ID_DEPACKETIZER for port 0x%x failed %d\n",
			__func__, port_id, ret);
		goto exit;
	}

	switch (cfg->format) {
	case ASM_MEDIA_FMT_SBC:
	case ASM_MEDIA_FMT_AAC_V2:
	case ASM_MEDIA_FMT_MP3:
		if (port_id == SLIMBUS_9_TX) {
			dec_buffer_id_param.max_nr_buffers  = 200;
			dec_buffer_id_param.pre_buffer_size = 200;
		} else {
			dec_buffer_id_param.max_nr_buffers  = 0;
			dec_buffer_id_param.pre_buffer_size = 0;
		}
		pr_debug("%s: sending AFE_DECODER_PARAM_ID_CONGESTION_BUFFER_SIZE to DSP payload\n",
			  __func__);
		param_hdr.param_id =
			AFE_DECODER_PARAM_ID_CONGESTION_BUFFER_SIZE;
		param_hdr.param_size =
			sizeof(struct avs_dec_congestion_buffer_param_t);
		dec_buffer_id_param.version = 0;
		ret = q6afe_pack_and_set_param_in_band(port_id,
						q6audio_get_port_index(port_id),
						param_hdr,
						(u8 *) &dec_buffer_id_param);
		if (ret) {
			pr_err("%s: AFE_DECODER_PARAM_ID_CONGESTION_BUFFER_SIZE for port 0x%x failed %d\n",
				__func__, port_id, ret);
			goto exit;
		}
		break;
	case ASM_MEDIA_FMT_APTX_ADAPTIVE:
		if (!cfg->abr_dec_cfg.is_abr_enabled) {
			pr_debug("%s: sending aptx adaptive congestion buffer size to dsp\n",
				__func__);
			param_hdr.param_id =
				AFE_DECODER_PARAM_ID_CONGESTION_BUFFER_SIZE;
			param_hdr.param_size =
			   sizeof(struct avs_dec_congestion_buffer_param_t);
			dec_buffer_id_param.version = 0;
			dec_buffer_id_param.max_nr_buffers  = 226;
			dec_buffer_id_param.pre_buffer_size = 226;
			ret = q6afe_pack_and_set_param_in_band(port_id,
						q6audio_get_port_index(port_id),
						param_hdr,
						(u8 *) &dec_buffer_id_param);
			if (ret) {
				pr_err("%s: aptx adaptive congestion buffer size for port 0x%x failed %d\n",
					__func__, port_id, ret);
				goto exit;
			}
			break;
		}
		/* fall through for abr enabled case */
	default:
		pr_debug("%s:sending AFE_ENCDEC_PARAM_ID_DEC_TO_ENC_COMMUNICATION to DSP payload\n",
			  __func__);
		param_hdr.param_id =
			AFE_ENCDEC_PARAM_ID_DEC_TO_ENC_COMMUNICATION;
		param_hdr.param_size =
			sizeof(struct afe_enc_dec_imc_info_param_t);
		imc_info_param.imc_info = cfg->abr_dec_cfg.imc_info;
		ret = q6afe_pack_and_set_param_in_band(port_id,
						q6audio_get_port_index(port_id),
						param_hdr,
						(u8 *) &imc_info_param);
		if (ret) {
			pr_err("%s: AFE_ENCDEC_PARAM_ID_DEC_TO_ENC_COMMUNICATION for port 0x%x failed %d\n",
				__func__, port_id, ret);
			goto exit;
		}
		break;
	}

	pr_debug("%s: Send AFE_API_VERSION_PORT_MEDIA_TYPE to DSP\n", __func__);
	param_hdr.module_id = AFE_MODULE_PORT;
	param_hdr.param_id = AFE_PARAM_ID_PORT_MEDIA_TYPE;
	param_hdr.param_size = sizeof(struct afe_port_media_type_t);
	media_type.minor_version = AFE_API_VERSION_PORT_MEDIA_TYPE;
	switch (cfg->format) {
	case ASM_MEDIA_FMT_AAC_V2:
		media_type.sample_rate =
			cfg->data.aac_config.sample_rate;
		break;
	case ASM_MEDIA_FMT_SBC:
		media_type.sample_rate =
			cfg->data.sbc_config.sample_rate;
		break;
	case ASM_MEDIA_FMT_APTX_ADAPTIVE:
		if (!cfg->abr_dec_cfg.is_abr_enabled) {
			media_type.sample_rate =
			(cfg->data.aptx_ad_config.sample_rate == APTX_AD_44_1) ?
				AFE_PORT_SAMPLE_RATE_44_1K :
				AFE_PORT_SAMPLE_RATE_48K;
			break;
		}
		/* fall through for abr enabled case */
	case ASM_MEDIA_FMT_APTX_AD_SPEECH:
		media_type.sample_rate = AFE_PORT_SAMPLE_RATE_32K;
		break;
	default:
		media_type.sample_rate =
			afe_config.slim_sch.sample_rate;
	}
	if (afe_in_bit_width)
		media_type.bit_width = afe_in_bit_width;
	else
		media_type.bit_width = afe_config.slim_sch.bit_width;

	if (afe_in_channels)
		media_type.num_channels = afe_in_channels;
	else
		media_type.num_channels = afe_config.slim_sch.num_channels;
	media_type.data_format = AFE_PORT_DATA_FORMAT_PCM;
	media_type.reserved = 0;

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) &media_type);
	if (ret) {
		pr_err("%s: AFE_API_VERSION_PORT_MEDIA_TYPE for port 0x%x failed %d\n",
			__func__, port_id, ret);
		goto exit;
	}

	if (format != ASM_MEDIA_FMT_SBC && format != ASM_MEDIA_FMT_AAC_V2 &&
		format != ASM_MEDIA_FMT_APTX_ADAPTIVE &&
		format != ASM_MEDIA_FMT_APTX_AD_SPEECH) {
		pr_debug("%s:Unsuppported dec format. Ignore AFE config %u\n",
				__func__, format);
		goto exit;
	}

	if (format == ASM_MEDIA_FMT_APTX_ADAPTIVE &&
		cfg->abr_dec_cfg.is_abr_enabled) {
		pr_debug("%s: Ignore AFE config for abr case\n", __func__);
		goto exit;
	}
	if (format == ASM_MEDIA_FMT_APTX_AD_SPEECH) {
		pr_debug("%s: sending AFE_PARAM_ID_RATE_MATCHED_PORT to DSP payload\n",
			__func__);
		param_hdr.param_id = AFE_PARAM_ID_RATE_MATCHED_PORT;
		param_hdr.param_size =
			sizeof(struct afe_matched_port_t);
		matched_port_param.minor_version = AFE_API_VERSION_PORT_MEDIA_TYPE;
		matched_port_param.enable = AFE_MATCHED_PORT_ENABLE;
		ret = q6afe_pack_and_set_param_in_band(port_id,
						q6audio_get_port_index(port_id),
						param_hdr,
						(u8 *) &matched_port_param);
		if (ret) {
			pr_err("%s: AFE_PARAM_ID_RATE_MATCHED_PORT for port 0x%x failed %d\n",
				__func__, port_id, ret);
			goto exit;
		}
	}

	pr_debug("%s: sending AFE_DECODER_PARAM_ID_DEC_MEDIA_FMT to DSP payload\n",
		  __func__);
	param_hdr.module_id = AFE_MODULE_ID_DECODER;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_DECODER_PARAM_ID_DEC_FMT_ID;
	param_hdr.param_size = sizeof(dec_fmt);
	dec_fmt = format;
	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) &dec_fmt);
	if (ret) {
		pr_err("%s: AFE_DECODER_PARAM_ID_DEC_MEDIA_FMT for port 0x%x failed %d\n",
			__func__, port_id, ret);
		goto exit;
	}

	switch (cfg->format) {
	case ASM_MEDIA_FMT_AAC_V2:
	case ASM_MEDIA_FMT_APTX_ADAPTIVE:
		param_hdr.param_size = sizeof(struct afe_dec_media_fmt_t);

		pr_debug("%s:send AVS_DECODER_PARAM_ID DEC_MEDIA_FMT to DSP payload\n",
			 __func__);
		param_hdr.param_id = AVS_DECODER_PARAM_ID_DEC_MEDIA_FMT;
		dec_media_fmt.dec_media_config = cfg->data;
		ret = q6afe_pack_and_set_param_in_band(port_id,
						q6audio_get_port_index(port_id),
						param_hdr,
						(u8 *) &dec_media_fmt);
		if (ret) {
			pr_err("%s: AVS_DECODER_PARAM_ID DEC_MEDIA_FMT for port 0x%x failed %d\n",
				__func__, port_id, ret);
			goto exit;
		}
		break;
	case ASM_MEDIA_FMT_APTX_AD_SPEECH:
		param_hdr.param_size =
				sizeof(struct asm_aptx_ad_speech_dec_cfg_t);

		pr_debug("%s: send AVS_DECODER_PARAM_ID_APTX_AD_SPEECH_DEC_INIT to DSP payload\n",
			 __func__);
		param_hdr.param_id =
				AVS_DECODER_PARAM_ID_APTX_AD_SPEECH_DEC_INIT;
		speech_codec_init_param =
				cfg->data.aptx_ad_speech_config.speech_mode;
		ret = q6afe_pack_and_set_param_in_band(port_id,
					q6audio_get_port_index(port_id),
					param_hdr,
					(u8 *) &speech_codec_init_param);
		if (ret) {
			pr_err("%s: AVS_DECODER_PARAM_ID_APTX_ADAPTIVE_SPEECH_DEC_INIT for port 0x%x failed %d\n",
				__func__, port_id, ret);
			goto exit;
		}
		break;
	default:
		pr_debug("%s:No need to send DEC_MEDIA_FMT to DSP payload\n",
			 __func__);
	}

exit:
	return ret;
}

static int q6afe_send_enc_config(u16 port_id,
				 union afe_enc_config_data *cfg, u32 format,
				 union afe_port_config afe_config,
				 u16 afe_in_channels, u16 afe_in_bit_width,
				 u32 scrambler_mode, u32 mono_mode)
{
	u32 enc_fmt;
	struct afe_enc_cfg_blk_param_t enc_blk_param;
	struct afe_param_id_aptx_sync_mode sync_mode_param;
	struct afe_id_aptx_adaptive_enc_init aptx_adaptive_enc_init;
	struct avs_enc_packetizer_id_param_t enc_pkt_id_param;
	struct avs_enc_set_scrambler_param_t enc_set_scrambler_param;
	struct afe_enc_level_to_bitrate_map_param_t map_param;
	struct afe_enc_dec_imc_info_param_t imc_info_param;
	struct asm_aac_frame_size_control_t frame_ctl_param;
	struct afe_port_media_type_t media_type;
	struct aptx_channel_mode_param_t channel_mode_param;
	struct afe_matched_port_t matched_port_param;
	struct asm_aptx_ad_speech_mode_cfg_t speech_codec_init_param;
	struct param_hdr_v3 param_hdr;
	int ret;
	uint32_t frame_size_ctl_value_v2;

	pr_debug("%s:update DSP for enc format = %d\n", __func__, format);

	memset(&enc_blk_param, 0, sizeof(enc_blk_param));
	memset(&sync_mode_param, 0, sizeof(sync_mode_param));
	memset(&aptx_adaptive_enc_init, 0, sizeof(aptx_adaptive_enc_init));
	memset(&enc_pkt_id_param, 0, sizeof(enc_pkt_id_param));
	memset(&enc_set_scrambler_param, 0, sizeof(enc_set_scrambler_param));
	memset(&map_param, 0, sizeof(map_param));
	memset(&imc_info_param, 0, sizeof(imc_info_param));
	memset(&frame_ctl_param, 0, sizeof(frame_ctl_param));
	memset(&media_type, 0, sizeof(media_type));
	memset(&matched_port_param, 0, sizeof(matched_port_param));
	memset(&speech_codec_init_param, 0, sizeof(speech_codec_init_param));
	memset(&param_hdr, 0, sizeof(param_hdr));

	if (format != ASM_MEDIA_FMT_SBC && format != ASM_MEDIA_FMT_AAC_V2 &&
		format != ASM_MEDIA_FMT_APTX && format != ASM_MEDIA_FMT_APTX_HD &&
		format != ASM_MEDIA_FMT_CELT && format != ASM_MEDIA_FMT_LDAC &&
		format != ASM_MEDIA_FMT_APTX_ADAPTIVE &&
		format != ASM_MEDIA_FMT_APTX_AD_SPEECH) {
		pr_err("%s:Unsuppported enc format. Ignore AFE config\n",
				__func__);
		return 0;
	}

	param_hdr.module_id = AFE_MODULE_ID_ENCODER;
	param_hdr.instance_id = INSTANCE_ID_0;

	param_hdr.param_id = AFE_ENCODER_PARAM_ID_ENC_FMT_ID;
	param_hdr.param_size = sizeof(enc_fmt);
	enc_fmt = format;
	pr_debug("%s:sending AFE_ENCODER_PARAM_ID_ENC_FMT_ID payload\n",
		 __func__);
	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) &enc_fmt);
	if (ret) {
		pr_err("%s:unable to send AFE_ENCODER_PARAM_ID_ENC_FMT_ID",
				__func__);
		goto exit;
	}

	if (format == ASM_MEDIA_FMT_LDAC) {
		param_hdr.param_size = sizeof(struct afe_enc_cfg_blk_param_t)
					    - sizeof(struct afe_abr_enc_cfg_t);
		enc_blk_param.enc_cfg_blk_size =
				sizeof(union afe_enc_config_data)
					- sizeof(struct afe_abr_enc_cfg_t);
	} else if (format == ASM_MEDIA_FMT_AAC_V2) {
		param_hdr.param_size = sizeof(enc_blk_param)
				- sizeof(struct asm_aac_frame_size_control_t);
		enc_blk_param.enc_cfg_blk_size =
				sizeof(enc_blk_param.enc_blk_config)
				- sizeof(struct asm_aac_frame_size_control_t);
	} else if (format == ASM_MEDIA_FMT_APTX_AD_SPEECH) {
		param_hdr.param_size = sizeof(struct afe_enc_aptx_ad_speech_cfg_blk_param_t);
		enc_blk_param.enc_cfg_blk_size = sizeof(struct asm_custom_enc_cfg_t);
	} else {
		param_hdr.param_size = sizeof(struct afe_enc_cfg_blk_param_t);
		enc_blk_param.enc_cfg_blk_size =
			sizeof(union afe_enc_config_data);
	}
	pr_debug("%s:send AFE_ENCODER_PARAM_ID_ENC_CFG_BLK to DSP payload\n",
		 __func__);
	param_hdr.param_id = AFE_ENCODER_PARAM_ID_ENC_CFG_BLK;
	enc_blk_param.enc_blk_config = *cfg;
	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr,
					       (u8 *) &enc_blk_param);
	if (ret) {
		pr_err("%s: AFE_ENCODER_PARAM_ID_ENC_CFG_BLK for port 0x%x failed %d\n",
			__func__, port_id, ret);
		goto exit;
	}

	if (format == ASM_MEDIA_FMT_AAC_V2) {
		uint32_t frame_size_ctl_value = enc_blk_param.enc_blk_config.
				aac_config.frame_ctl.ctl_value;
		if (frame_size_ctl_value > 0) {
			param_hdr.param_id =
				AFE_PARAM_ID_AAC_FRM_SIZE_CONTROL;
			param_hdr.param_size = sizeof(frame_ctl_param);
			frame_ctl_param.ctl_type = enc_blk_param.
				enc_blk_config.aac_config.frame_ctl.ctl_type;
			frame_ctl_param.ctl_value = frame_size_ctl_value;

			pr_debug("%s: send AFE_PARAM_ID_AAC_FRM_SIZE_CONTROL\n",
				__func__);
			ret = q6afe_pack_and_set_param_in_band(port_id,
					q6audio_get_port_index(port_id),
					param_hdr,
					(u8 *) &frame_ctl_param);
			if (ret) {
				pr_err("%s: AAC_FRM_SIZE_CONTROL failed %d\n",
					__func__, ret);
				goto exit;
			}
		}
		frame_size_ctl_value_v2 = enc_blk_param.enc_blk_config.
				aac_config.frame_ctl_v2.ctl_value;
		if (frame_size_ctl_value_v2 > 0) {
			param_hdr.param_id =
				AFE_PARAM_ID_AAC_FRM_SIZE_CONTROL;
			param_hdr.param_size = sizeof(frame_ctl_param);
			frame_ctl_param.ctl_type = enc_blk_param.
				enc_blk_config.aac_config.frame_ctl_v2.ctl_type;
			frame_ctl_param.ctl_value = enc_blk_param.
				enc_blk_config.aac_config.frame_ctl_v2.ctl_value;

			pr_debug("%s: send AFE_PARAM_ID_AAC_FRM_SIZE_CONTROL V2\n",
				__func__);
			ret = q6afe_pack_and_set_param_in_band(port_id,
					q6audio_get_port_index(port_id),
					param_hdr,
					(u8 *) &frame_ctl_param);
			if (ret) {
				pr_err("%s: AAC_FRM_SIZE_CONTROL with VBR support failed %d\n",
					__func__, ret);
				goto exit;
			}
		}
	}

	if (format == ASM_MEDIA_FMT_APTX) {
		pr_debug("%s: sending AFE_PARAM_ID_APTX_SYNC_MODE to DSP",
			__func__);
		param_hdr.param_id = AFE_PARAM_ID_APTX_SYNC_MODE;
		param_hdr.param_size =
			sizeof(struct afe_param_id_aptx_sync_mode);
		sync_mode_param.sync_mode =
			enc_blk_param.enc_blk_config.aptx_config.
				aptx_v2_cfg.sync_mode;
		ret = q6afe_pack_and_set_param_in_band(port_id,
					q6audio_get_port_index(port_id),
					param_hdr,
					(u8 *) &sync_mode_param);
		if (ret) {
			pr_err("%s: AFE_PARAM_ID_APTX_SYNC_MODE for port 0x%x failed %d\n",
				__func__, port_id, ret);
			goto exit;
		}
	}
	if (format == ASM_MEDIA_FMT_APTX_ADAPTIVE) {
		pr_debug("%s: sending AFE_ID_APTX_ADAPTIVE_ENC_INIT to DSP\n",
			__func__);
		param_hdr.param_id = AFE_ID_APTX_ADAPTIVE_ENC_INIT;
		param_hdr.param_size =
			sizeof(struct afe_id_aptx_adaptive_enc_init);
		aptx_adaptive_enc_init =
			enc_blk_param.enc_blk_config.aptx_ad_config.
				aptx_ad_cfg;
		ret = q6afe_pack_and_set_param_in_band(port_id,
					q6audio_get_port_index(port_id),
					param_hdr,
					(u8 *) &aptx_adaptive_enc_init);
		if (ret) {
			pr_err("%s: AFE_ID_APTX_ADAPTIVE_ENC_INIT for port 0x%x failed %d\n",
				__func__, port_id, ret);
			goto exit;
		}
	}
	if (format == ASM_MEDIA_FMT_APTX_AD_SPEECH) {
		pr_debug("%s: sending AVS_DECODER_PARAM_ID_APTX_AD_SPEECH_ENC_INIT to DSP\n",
			__func__);
		param_hdr.param_id = AVS_DECODER_PARAM_ID_APTX_AD_SPEECH_ENC_INIT;
		param_hdr.param_size =
			sizeof(struct asm_aptx_ad_speech_dec_cfg_t);
		speech_codec_init_param = cfg->aptx_ad_speech_config.speech_mode;
		ret = q6afe_pack_and_set_param_in_band(port_id,
					q6audio_get_port_index(port_id),
					param_hdr,
					(u8 *) &speech_codec_init_param);
		if (ret) {
			pr_err("%s: AFE_ID_APTX_ADAPTIVE_ENC_INIT for port 0x%x failed %d\n",
				__func__, port_id, ret);
			goto exit;
		}
	}

	pr_debug("%s:sending AFE_ENCODER_PARAM_ID_PACKETIZER to DSP\n",
		 __func__);
	param_hdr.param_id = AFE_ENCODER_PARAM_ID_PACKETIZER_ID;
	param_hdr.param_size = sizeof(struct avs_enc_packetizer_id_param_t);
	enc_pkt_id_param.enc_packetizer_id = AFE_MODULE_ID_PACKETIZER_COP;
	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr,
					       (u8 *) &enc_pkt_id_param);
	if (ret) {
		pr_err("%s: AFE_ENCODER_PARAM_ID_PACKETIZER for port 0x%x failed %d\n",
			__func__, port_id, ret);
		goto exit;
	}

	if (format != ASM_MEDIA_FMT_APTX_AD_SPEECH) {
		pr_debug("%s:sending AFE_ENCODER_PARAM_ID_ENABLE_SCRAMBLING mode= %d to DSP payload\n",
			  __func__, scrambler_mode);
		param_hdr.param_id = AFE_ENCODER_PARAM_ID_ENABLE_SCRAMBLING;
		param_hdr.param_size = sizeof(struct avs_enc_set_scrambler_param_t);
		enc_set_scrambler_param.enable_scrambler = scrambler_mode;
		ret = q6afe_pack_and_set_param_in_band(port_id,
						       q6audio_get_port_index(port_id),
						       param_hdr,
						       (u8 *) &enc_set_scrambler_param);
		if (ret) {
			pr_err("%s: AFE_ENCODER_PARAM_ID_ENABLE_SCRAMBLING for port 0x%x failed %d\n",
				__func__, port_id, ret);
			goto exit;
		}
	}

	if (format == ASM_MEDIA_FMT_APTX) {
		pr_debug("%s:sending CAPI_V2_PARAM_ID_APTX_ENC_SWITCH_TO_MONO mode= %d to DSP payload\n",
			__func__, mono_mode);
		param_hdr.param_id = CAPI_V2_PARAM_ID_APTX_ENC_SWITCH_TO_MONO;
		param_hdr.param_size = sizeof(channel_mode_param);
		channel_mode_param.channel_mode = mono_mode;
		ret = q6afe_pack_and_set_param_in_band(port_id,
				q6audio_get_port_index(port_id),
							param_hdr,
					(u8 *) &channel_mode_param);

		if (ret) {
			pr_err("%s: CAPI_V2_PARAM_ID_APTX_ENC_SWITCH_TO_MONO for port 0x%x failed %d\n",
				__func__, port_id, ret);
		}
	}

	if ((format == ASM_MEDIA_FMT_LDAC &&
	     cfg->ldac_config.abr_config.is_abr_enabled) ||
	     format == ASM_MEDIA_FMT_APTX_ADAPTIVE ||
	     format == ASM_MEDIA_FMT_APTX_AD_SPEECH) {
		if (format != ASM_MEDIA_FMT_APTX_AD_SPEECH) {
			pr_debug("%s:sending AFE_ENCODER_PARAM_ID_BIT_RATE_LEVEL_MAP to DSP payload",
				__func__);
			param_hdr.param_id = AFE_ENCODER_PARAM_ID_BIT_RATE_LEVEL_MAP;
			param_hdr.param_size =
				sizeof(struct afe_enc_level_to_bitrate_map_param_t);
			map_param.mapping_table =
				cfg->ldac_config.abr_config.mapping_info;
			ret = q6afe_pack_and_set_param_in_band(port_id,
							q6audio_get_port_index(port_id),
							param_hdr,
							(u8 *) &map_param);
			if (ret) {
				pr_err("%s: AFE_ENCODER_PARAM_ID_BIT_RATE_LEVEL_MAP for port 0x%x failed %d\n",
					__func__, port_id, ret);
				goto exit;
			}
		}

		pr_debug("%s: sending AFE_ENCDEC_PARAM_ID_DEC_TO_ENC_COMMUNICATION to DSP payload",
				__func__);
		param_hdr.param_id =
			AFE_ENCDEC_PARAM_ID_DEC_TO_ENC_COMMUNICATION;
		param_hdr.param_size =
			sizeof(struct afe_enc_dec_imc_info_param_t);
		if (format == ASM_MEDIA_FMT_APTX_ADAPTIVE)
			imc_info_param.imc_info =
			cfg->aptx_ad_config.abr_cfg.imc_info;
		else if (format == ASM_MEDIA_FMT_APTX_AD_SPEECH)
			imc_info_param.imc_info =
			cfg->aptx_ad_speech_config.imc_info;
		else
			imc_info_param.imc_info =
			cfg->ldac_config.abr_config.imc_info;
		ret = q6afe_pack_and_set_param_in_band(port_id,
						q6audio_get_port_index(port_id),
						param_hdr,
						(u8 *) &imc_info_param);
		if (ret) {
			pr_err("%s: AFE_ENCDEC_PARAM_ID_DEC_TO_ENC_COMMUNICATION for port 0x%x failed %d\n",
					__func__, port_id, ret);
			goto exit;
		}
	}

	pr_debug("%s:Sending AFE_API_VERSION_PORT_MEDIA_TYPE to DSP", __func__);
	param_hdr.module_id = AFE_MODULE_PORT;
	param_hdr.param_id = AFE_PARAM_ID_PORT_MEDIA_TYPE;
	param_hdr.param_size = sizeof(struct afe_port_media_type_t);
	media_type.minor_version = AFE_API_VERSION_PORT_MEDIA_TYPE;
	if (format == ASM_MEDIA_FMT_LDAC)
		media_type.sample_rate =
			cfg->ldac_config.custom_config.sample_rate;
	else if (format == ASM_MEDIA_FMT_APTX_ADAPTIVE)
		media_type.sample_rate =
			cfg->aptx_ad_config.custom_cfg.sample_rate;
	else if (format == ASM_MEDIA_FMT_APTX_AD_SPEECH)
		media_type.sample_rate =
			cfg->aptx_ad_speech_config.custom_cfg.sample_rate;
	else
		media_type.sample_rate =
			afe_config.slim_sch.sample_rate;

	if (afe_in_bit_width)
		media_type.bit_width = afe_in_bit_width;
	else
		media_type.bit_width = afe_config.slim_sch.bit_width;

	if (afe_in_channels)
		media_type.num_channels = afe_in_channels;
	else
		media_type.num_channels = afe_config.slim_sch.num_channels;
	media_type.data_format = AFE_PORT_DATA_FORMAT_PCM;
	media_type.reserved = 0;

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) &media_type);
	if (ret) {
		pr_err("%s: AFE_API_VERSION_PORT_MEDIA_TYPE for port 0x%x failed %d\n",
			__func__, port_id, ret);
		goto exit;
	}

	if (format == ASM_MEDIA_FMT_APTX_AD_SPEECH) {
		pr_debug("%s: sending AFE_PARAM_ID_RATE_MATCHED_PORT to DSP payload",
			__func__);
		param_hdr.param_id = AFE_PARAM_ID_RATE_MATCHED_PORT;
		param_hdr.param_size =
			sizeof(struct afe_matched_port_t);
		matched_port_param.minor_version = AFE_API_VERSION_PORT_MEDIA_TYPE;
		matched_port_param.enable = AFE_MATCHED_PORT_ENABLE;
		ret = q6afe_pack_and_set_param_in_band(port_id,
						q6audio_get_port_index(port_id),
						param_hdr,
						(u8 *) &matched_port_param);
		if (ret) {
			pr_err("%s: AFE_PARAM_ID_RATE_MATCHED_PORT for port 0x%x failed %d\n",
				__func__, port_id, ret);
			goto exit;
		}
	}

exit:
	return ret;
}

int afe_set_tws_channel_mode(u32 format, u16 port_id, u32 channel_mode)
{
	struct aptx_channel_mode_param_t channel_mode_param;
	struct param_hdr_v3 param_info;
	int ret = 0;
	u32 param_id = 0;

	if (format == ASM_MEDIA_FMT_APTX) {
		param_id = CAPI_V2_PARAM_ID_APTX_ENC_SWITCH_TO_MONO;
	} else if (format == ASM_MEDIA_FMT_APTX_ADAPTIVE) {
		param_id = CAPI_V2_PARAM_ID_APTX_AD_ENC_SWITCH_TO_MONO;
	} else {
		pr_err("%s: Not supported format 0x%x\n", __func__, format);
		return -EINVAL;
	}

	memset(&param_info, 0, sizeof(param_info));
	memset(&channel_mode_param, 0, sizeof(channel_mode_param));

	param_info.module_id = AFE_MODULE_ID_ENCODER;
	param_info.instance_id = INSTANCE_ID_0;
	param_info.param_id = param_id;
	param_info.param_size = sizeof(channel_mode_param);

	channel_mode_param.channel_mode = channel_mode;

	ret = q6afe_pack_and_set_param_in_band(port_id,
			q6audio_get_port_index(port_id),
						param_info,
				(u8 *) &channel_mode_param);
	if (ret)
		pr_err("%s: AFE set channel mode cfg for port 0x%x failed %d\n",
			 __func__, port_id, ret);

	return ret;
}
EXPORT_SYMBOL(afe_set_tws_channel_mode);

static int __afe_port_start(u16 port_id, union afe_port_config *afe_config,
			    u32 rate, u16 afe_in_channels, u16 afe_in_bit_width,
			    union afe_enc_config_data *enc_cfg,
			    u32 codec_format, u32 scrambler_mode, u32 mono_mode,
			    struct afe_dec_config *dec_cfg,
			    struct afe_ttp_config *ttp_cfg)
{
	union afe_port_config port_cfg;
	struct param_hdr_v3 param_hdr;
	int ret = 0;
	int cfg_type;
	int index = 0;
	enum afe_mad_type mad_type;
	uint16_t port_index;

	memset(&param_hdr, 0, sizeof(param_hdr));
	memset(&port_cfg, 0, sizeof(port_cfg));

	if (!afe_config) {
		pr_err("%s: Error, no configuration data\n", __func__);
		ret = -EINVAL;
		return ret;
	}

	if ((port_id == RT_PROXY_DAI_001_RX) ||
		(port_id == RT_PROXY_DAI_002_TX)) {
		pr_debug("%s: before incrementing pcm_afe_instance %d port_id 0x%x\n",
			__func__,
			pcm_afe_instance[port_id & 0x1], port_id);
		port_id = VIRTUAL_ID_TO_PORTID(port_id);
		pcm_afe_instance[port_id & 0x1]++;
		return 0;
	}
	if ((port_id == RT_PROXY_DAI_002_RX) ||
			(port_id == RT_PROXY_DAI_001_TX)) {
		pr_debug("%s: before incrementing proxy_afe_instance %d port_id 0x%x\n",
			__func__,
			proxy_afe_instance[port_id & 0x1], port_id);

		if (!afe_close_done[port_id & 0x1]) {
			/*close pcm dai corresponding to the proxy dai*/
			afe_close(port_id - 0x10);
			pcm_afe_instance[port_id & 0x1]++;
			pr_debug("%s: reconfigure afe port again\n", __func__);
		}
		proxy_afe_instance[port_id & 0x1]++;
		afe_close_done[port_id & 0x1] = false;
		port_id = VIRTUAL_ID_TO_PORTID(port_id);
	}

	pr_info("%s: port id: 0x%x\n", __func__, port_id);

	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		return -EINVAL;
	}
	ret = q6audio_validate_port(port_id);
	if (ret < 0) {
		pr_err("%s: port id: 0x%x ret %d\n", __func__, port_id, ret);
		return -EINVAL;
	}

	ret = afe_q6_interface_prepare();
	if (ret != 0) {
		pr_err("%s: Q6 interface prepare failed %d\n", __func__, ret);
		return ret;
	}

	if ((index >= 0) && (index < AFE_MAX_PORTS)) {
		this_afe.afe_sample_rates[index] = rate;

		if (this_afe.rt_cb)
			this_afe.dev_acdb_id[index] = this_afe.rt_cb(port_id);
	}

	mutex_lock(&this_afe.afe_cmd_lock);
	port_index = afe_get_port_index(port_id);

	/* Also send the topology id here: */
	if (!(this_afe.afe_cal_mode[port_index] == AFE_CAL_MODE_NONE)) {
		/* One time call: only for first time */
		afe_send_custom_topology();
		afe_send_port_topology_id(port_id);
		afe_send_cal(port_id);
		afe_send_hw_delay(port_id, rate);
	}

	if ((this_afe.cps_config) &&
	    (this_afe.vi_rx_port == port_id)) {
		afe_send_cps_config(port_id);
	}

	/* Start SW MAD module */
	mad_type = afe_port_get_mad_type(port_id);
	pr_debug("%s: port_id 0x%x, mad_type %d\n", __func__, port_id,
		 mad_type);
	if (mad_type != MAD_HW_NONE && mad_type != MAD_SW_AUDIO) {
		if (!afe_has_config(AFE_CDC_REGISTERS_CONFIG) ||
			!afe_has_config(AFE_SLIMBUS_SLAVE_CONFIG)) {
			pr_err("%s: AFE isn't configured yet for\n"
				"HW MAD try Again\n", __func__);
				ret = -EAGAIN;
				goto fail_cmd;
		}
		ret = afe_turn_onoff_hw_mad(mad_type, true);
		if (ret) {
			pr_err("%s: afe_turn_onoff_hw_mad failed %d\n",
			       __func__, ret);
			goto fail_cmd;
		}
	}

	if ((this_afe.aanc_info.aanc_active) &&
	    (this_afe.aanc_info.aanc_tx_port == port_id)) {
		this_afe.aanc_info.aanc_tx_port_sample_rate = rate;
		port_index =
			afe_get_port_index(this_afe.aanc_info.aanc_rx_port);
		if ((port_index >= 0) && (port_index < AFE_MAX_PORTS)) {
			this_afe.aanc_info.aanc_rx_port_sample_rate =
				this_afe.afe_sample_rates[port_index];
		} else {
			pr_err("%s: Invalid port index %d\n",
				__func__, port_index);
			ret = -EINVAL;
			goto fail_cmd;
		}
		ret = afe_aanc_start(this_afe.aanc_info.aanc_tx_port,
				this_afe.aanc_info.aanc_rx_port);
		pr_debug("%s: afe_aanc_start ret %d\n", __func__, ret);
	}

	if ((port_id == AFE_PORT_ID_USB_RX) ||
	    (port_id == AFE_PORT_ID_USB_TX)) {
		ret = afe_port_send_usb_dev_param(port_id, afe_config);
		if (ret) {
			pr_err("%s: AFE device param for port 0x%x failed %d\n",
				   __func__, port_id, ret);
			ret = -EINVAL;
			goto fail_cmd;
		}
	}

	switch (port_id) {
	case AFE_PORT_ID_PRIMARY_PCM_RX:
	case AFE_PORT_ID_PRIMARY_PCM_TX:
	case AFE_PORT_ID_SECONDARY_PCM_RX:
	case AFE_PORT_ID_SECONDARY_PCM_TX:
	case AFE_PORT_ID_TERTIARY_PCM_RX:
	case AFE_PORT_ID_TERTIARY_PCM_TX:
	case AFE_PORT_ID_QUATERNARY_PCM_RX:
	case AFE_PORT_ID_QUATERNARY_PCM_TX:
	case AFE_PORT_ID_QUINARY_PCM_RX:
	case AFE_PORT_ID_QUINARY_PCM_TX:
	case AFE_PORT_ID_SENARY_PCM_RX:
	case AFE_PORT_ID_SENARY_PCM_TX:
		cfg_type = AFE_PARAM_ID_PCM_CONFIG;
		break;
	case PRIMARY_I2S_RX:
	case PRIMARY_I2S_TX:
	case SECONDARY_I2S_RX:
	case SECONDARY_I2S_TX:
	case MI2S_RX:
	case MI2S_TX:
	case AFE_PORT_ID_PRIMARY_MI2S_RX:
	case AFE_PORT_ID_PRIMARY_MI2S_TX:
	case AFE_PORT_ID_SECONDARY_MI2S_RX:
	case AFE_PORT_ID_SECONDARY_MI2S_RX_SD1:
	case AFE_PORT_ID_SECONDARY_MI2S_TX:
	case AFE_PORT_ID_TERTIARY_MI2S_RX:
	case AFE_PORT_ID_TERTIARY_MI2S_TX:
	case AFE_PORT_ID_QUATERNARY_MI2S_RX:
	case AFE_PORT_ID_QUATERNARY_MI2S_TX:
	case AFE_PORT_ID_QUINARY_MI2S_RX:
	case AFE_PORT_ID_QUINARY_MI2S_TX:
	case AFE_PORT_ID_SENARY_MI2S_RX:
	case AFE_PORT_ID_SENARY_MI2S_TX:
	case AFE_PORT_ID_INT0_MI2S_RX:
	case AFE_PORT_ID_INT0_MI2S_TX:
	case AFE_PORT_ID_INT1_MI2S_RX:
	case AFE_PORT_ID_INT1_MI2S_TX:
	case AFE_PORT_ID_INT2_MI2S_RX:
	case AFE_PORT_ID_INT2_MI2S_TX:
	case AFE_PORT_ID_INT3_MI2S_RX:
	case AFE_PORT_ID_INT3_MI2S_TX:
	case AFE_PORT_ID_INT4_MI2S_RX:
	case AFE_PORT_ID_INT4_MI2S_TX:
	case AFE_PORT_ID_INT5_MI2S_RX:
	case AFE_PORT_ID_INT5_MI2S_TX:
	case AFE_PORT_ID_INT6_MI2S_RX:
	case AFE_PORT_ID_INT6_MI2S_TX:
		cfg_type = AFE_PARAM_ID_I2S_CONFIG;
		break;
	case AFE_PORT_ID_PRIMARY_META_MI2S_RX:
	case AFE_PORT_ID_SECONDARY_META_MI2S_RX:
		cfg_type = AFE_PARAM_ID_META_I2S_CONFIG;
		break;
	case HDMI_RX:
	case HDMI_RX_MS:
	case DISPLAY_PORT_RX:
		cfg_type = AFE_PARAM_ID_HDMI_CONFIG;
		break;
	case VOICE_PLAYBACK_TX:
	case VOICE2_PLAYBACK_TX:
	case VOICE_RECORD_RX:
	case VOICE_RECORD_TX:
		cfg_type = AFE_PARAM_ID_PSEUDO_PORT_CONFIG;
		break;
	case SLIMBUS_0_RX:
	case SLIMBUS_0_TX:
	case SLIMBUS_1_RX:
	case SLIMBUS_1_TX:
	case SLIMBUS_2_RX:
	case SLIMBUS_2_TX:
	case SLIMBUS_3_RX:
	case SLIMBUS_3_TX:
	case SLIMBUS_4_RX:
	case SLIMBUS_4_TX:
	case SLIMBUS_5_RX:
	case SLIMBUS_5_TX:
	case SLIMBUS_6_RX:
	case SLIMBUS_6_TX:
	case SLIMBUS_7_RX:
	case SLIMBUS_7_TX:
	case SLIMBUS_8_RX:
	case SLIMBUS_8_TX:
	case SLIMBUS_9_RX:
	case SLIMBUS_9_TX:
		cfg_type = AFE_PARAM_ID_SLIMBUS_CONFIG;
		break;
	case AFE_PORT_ID_USB_RX:
	case AFE_PORT_ID_USB_TX:
		cfg_type = AFE_PARAM_ID_USB_AUDIO_CONFIG;
		break;
	case RT_PROXY_PORT_001_RX:
	case RT_PROXY_PORT_001_TX:
	case RT_PROXY_PORT_002_RX:
	case RT_PROXY_PORT_002_TX:
		cfg_type = AFE_PARAM_ID_RT_PROXY_CONFIG;
		break;
	case INT_BT_SCO_RX:
	case INT_BT_A2DP_RX:
	case INT_BT_SCO_TX:
	case INT_FM_RX:
	case INT_FM_TX:
		cfg_type = AFE_PARAM_ID_INTERNAL_BT_FM_CONFIG;
		break;
	case AFE_PORT_ID_WSA_CODEC_DMA_RX_0:
	case AFE_PORT_ID_WSA_CODEC_DMA_TX_0:
	case AFE_PORT_ID_WSA_CODEC_DMA_RX_1:
	case AFE_PORT_ID_WSA_CODEC_DMA_TX_1:
	case AFE_PORT_ID_WSA_CODEC_DMA_TX_2:
	case AFE_PORT_ID_VA_CODEC_DMA_TX_0:
	case AFE_PORT_ID_VA_CODEC_DMA_TX_1:
	case AFE_PORT_ID_VA_CODEC_DMA_TX_2:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_0:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_0:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_1:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_1:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_2:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_2:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_3:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_3:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_4:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_4:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_5:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_5:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_6:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_7:
		cfg_type = AFE_PARAM_ID_CODEC_DMA_CONFIG;
		break;
	default:
		pr_err("%s: Invalid port id 0x%x\n", __func__, port_id);
		ret = -EINVAL;
		goto fail_cmd;
	}

	param_hdr.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = cfg_type;
	param_hdr.param_size = sizeof(union afe_port_config);

	port_cfg = *afe_config;
	if (((enc_cfg != NULL) || (dec_cfg != NULL)) &&
	    (codec_format != ASM_MEDIA_FMT_NONE) &&
	    (cfg_type == AFE_PARAM_ID_SLIMBUS_CONFIG)) {
		port_cfg.slim_sch.data_format =
			AFE_SB_DATA_FORMAT_GENERIC_COMPRESSED;
	}
	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) &port_cfg);
	if (ret) {
		pr_err("%s: AFE enable for port 0x%x failed %d\n",
			__func__, port_id, ret);
		goto fail_cmd;
	}

	if ((codec_format != ASM_MEDIA_FMT_NONE) &&
	    (cfg_type == AFE_PARAM_ID_SLIMBUS_CONFIG)) {
		if (enc_cfg != NULL) {
			pr_debug("%s: Found AFE encoder support  for SLIMBUS format = %d\n",
						__func__, codec_format);

			if ((q6core_get_avcs_api_version_per_service(
				APRV2_IDS_SERVICE_ID_ADSP_CORE_V) >=
						AVCS_API_VERSION_V5)) {
				ret = q6afe_load_avcs_modules(2, port_id,
					ENCODER_CASE, codec_format);
				if (ret < 0) {
					pr_err("%s:encoder load for port 0x%x failed %d\n",
						__func__, port_id, ret);
					goto fail_cmd;
				}
			}

			ret = q6afe_send_enc_config(port_id, enc_cfg,
						    codec_format, *afe_config,
						    afe_in_channels,
						    afe_in_bit_width,
						    scrambler_mode, mono_mode);
			if (ret) {
				pr_err("%s: AFE encoder config for port 0x%x failed %d\n",
					__func__, port_id, ret);
				goto fail_cmd;
			}
		}
		if (dec_cfg != NULL) {
			pr_debug("%s: Found AFE decoder support for SLIMBUS format = %d\n",
				__func__, codec_format);

			if ((q6core_get_avcs_api_version_per_service(
				APRV2_IDS_SERVICE_ID_ADSP_CORE_V) >=
				AVCS_API_VERSION_V5)) {
				/*
				 * LDAC and APTX_ADAPTIVE don't require loading decoder module
				 * Only loading de-packetizer module.
				 */
				if (codec_format == ENC_CODEC_TYPE_LDAC ||
					codec_format == ASM_MEDIA_FMT_APTX_ADAPTIVE)
					ret = q6afe_load_avcs_modules(1, port_id,
						DECODER_CASE, codec_format);
				else
					ret = q6afe_load_avcs_modules(2, port_id,
						DECODER_CASE, codec_format);
				if (ret < 0) {
					pr_err("%s:decoder load for port 0x%x failed %d\n",
						__func__, port_id, ret);
					goto fail_cmd;
				}
			}
			ret = q6afe_send_dec_config(port_id, *afe_config,
						    dec_cfg, codec_format,
						    afe_in_channels,
						    afe_in_bit_width);
			if (ret) {
				pr_err("%s: AFE decoder config for port 0x%x failed %d\n",
					 __func__, port_id, ret);
				goto fail_cmd;
			}
		}
		if (ttp_cfg != NULL) {
			ret = q6afe_send_ttp_config(port_id, *afe_config,
						    ttp_cfg);
			if (ret) {
				pr_err("%s: AFE TTP config for port 0x%x failed %d\n",
					 __func__, port_id, ret);
				goto fail_cmd;
			}
		}
	}

	port_index = afe_get_port_index(port_id);
	if ((port_index >= 0) && (port_index < AFE_MAX_PORTS)) {
		/*
		 * If afe_port_start() for tx port called before
		 * rx port, then aanc rx sample rate is zero. So,
		 * AANC state machine in AFE will not get triggered.
		 * Make sure to check whether aanc is active during
		 * afe_port_start() for rx port and if aanc rx
		 * sample rate is zero, call afe_aanc_start to configure
		 * aanc with valid sample rates.
		 */
		if (this_afe.aanc_info.aanc_active &&
		    !this_afe.aanc_info.aanc_rx_port_sample_rate) {
			this_afe.aanc_info.aanc_rx_port_sample_rate =
				this_afe.afe_sample_rates[port_index];
			ret = afe_aanc_start(this_afe.aanc_info.aanc_tx_port,
					this_afe.aanc_info.aanc_rx_port);
			pr_debug("%s: afe_aanc_start ret %d\n", __func__, ret);
		}
	} else {
		pr_err("%s: Invalid port index %d\n", __func__, port_index);
		ret = -EINVAL;
		goto fail_cmd;
	}
	ret = afe_send_cmd_port_start(port_id);

fail_cmd:
	mutex_unlock(&this_afe.afe_cmd_lock);
	return ret;
}

/**
 * afe_port_start - to configure AFE session with
 * specified port configuration
 *
 * @port_id: AFE port id number
 * @afe_config: port configutation
 * @rate: sampling rate of port
 *
 * Returns 0 on success or error value on port start failure.
 */
int afe_port_start(u16 port_id, union afe_port_config *afe_config,
		   u32 rate)
{
	return __afe_port_start(port_id, afe_config, rate, 0, 0, NULL,
				ASM_MEDIA_FMT_NONE, 0, 0, NULL, NULL);
}
EXPORT_SYMBOL(afe_port_start);

/**
 * afe_port_start_v2 - to configure AFE session with
 * specified port configuration and encoder /decoder params
 *
 * @port_id: AFE port id number
 * @afe_config: port configutation
 * @rate: sampling rate of port
 * @enc_cfg: AFE enc configuration information to setup encoder
 * @afe_in_channels: AFE input channel configuration, this needs
 *  update only if input channel is differ from AFE output
 * @dec_cfg: AFE dec configuration information to set up decoder
 *
 * Returns 0 on success or error value on port start failure.
 */
int afe_port_start_v2(u16 port_id, union afe_port_config *afe_config,
		      u32 rate, u16 afe_in_channels, u16 afe_in_bit_width,
		      struct afe_enc_config *enc_cfg,
		      struct afe_dec_config *dec_cfg)
{
	int ret = 0;

	if (enc_cfg != NULL)
		ret = __afe_port_start(port_id, afe_config, rate,
					afe_in_channels, afe_in_bit_width,
					&enc_cfg->data, enc_cfg->format,
					enc_cfg->scrambler_mode,
					enc_cfg->mono_mode, dec_cfg, NULL);
	else if (dec_cfg != NULL)
		ret = __afe_port_start(port_id, afe_config, rate,
					afe_in_channels, afe_in_bit_width,
					NULL, dec_cfg->format, 0, 0,
					dec_cfg, NULL);

	return ret;
}
EXPORT_SYMBOL(afe_port_start_v2);

/**
 * afe_port_start_v3 - to configure AFE session with
 * specified port configuration and encoder /decoder params
 *
 * @port_id: AFE port id number
 * @afe_config: port configuration
 * @rate: sampling rate of port
 * @enc_cfg: AFE enc configuration information to setup encoder
 * @afe_in_channels: AFE input channel configuration, this needs
 *  update only if input channel is differ from AFE output
 * @dec_cfg: AFE dec configuration information to set up decoder
 * @ttp_cfg: TTP generator configuration to enable TTP in AFE
 *
 * Returns 0 on success or error value on port start failure.
 */
int afe_port_start_v3(u16 port_id, union afe_port_config *afe_config,
		      u32 rate, u16 afe_in_channels, u16 afe_in_bit_width,
		      struct afe_enc_config *enc_cfg,
		      struct afe_dec_config *dec_cfg,
		      struct afe_ttp_config *ttp_cfg)
{
	int ret = 0;

	if (dec_cfg != NULL && ttp_cfg != NULL)
		ret = __afe_port_start(port_id, afe_config, rate,
				       afe_in_channels, afe_in_bit_width,
				       NULL, dec_cfg->format, 0, 0,
				       dec_cfg, ttp_cfg);

	return ret;
}
EXPORT_SYMBOL(afe_port_start_v3);

int afe_get_port_index(u16 port_id)
{
	switch (port_id) {
	case PRIMARY_I2S_RX: return IDX_PRIMARY_I2S_RX;
	case PRIMARY_I2S_TX: return IDX_PRIMARY_I2S_TX;
	case AFE_PORT_ID_PRIMARY_PCM_RX:
		return IDX_AFE_PORT_ID_PRIMARY_PCM_RX;
	case AFE_PORT_ID_PRIMARY_PCM_TX:
		return IDX_AFE_PORT_ID_PRIMARY_PCM_TX;
	case AFE_PORT_ID_SECONDARY_PCM_RX:
		return IDX_AFE_PORT_ID_SECONDARY_PCM_RX;
	case AFE_PORT_ID_SECONDARY_PCM_TX:
		return IDX_AFE_PORT_ID_SECONDARY_PCM_TX;
	case AFE_PORT_ID_TERTIARY_PCM_RX:
		return IDX_AFE_PORT_ID_TERTIARY_PCM_RX;
	case AFE_PORT_ID_TERTIARY_PCM_TX:
		return IDX_AFE_PORT_ID_TERTIARY_PCM_TX;
	case AFE_PORT_ID_QUATERNARY_PCM_RX:
		return IDX_AFE_PORT_ID_QUATERNARY_PCM_RX;
	case AFE_PORT_ID_QUATERNARY_PCM_TX:
		return IDX_AFE_PORT_ID_QUATERNARY_PCM_TX;
	case AFE_PORT_ID_QUINARY_PCM_RX:
		return IDX_AFE_PORT_ID_QUINARY_PCM_RX;
	case AFE_PORT_ID_QUINARY_PCM_TX:
		return IDX_AFE_PORT_ID_QUINARY_PCM_TX;
	case AFE_PORT_ID_SENARY_PCM_RX:
		return IDX_AFE_PORT_ID_SENARY_PCM_RX;
	case AFE_PORT_ID_SENARY_PCM_TX:
		return IDX_AFE_PORT_ID_SENARY_PCM_TX;
	case SECONDARY_I2S_RX: return IDX_SECONDARY_I2S_RX;
	case SECONDARY_I2S_TX: return IDX_SECONDARY_I2S_TX;
	case MI2S_RX: return IDX_MI2S_RX;
	case MI2S_TX: return IDX_MI2S_TX;
	case HDMI_RX: return IDX_HDMI_RX;
	case HDMI_RX_MS: return IDX_HDMI_RX_MS;
	case DISPLAY_PORT_RX: return IDX_DISPLAY_PORT_RX;
	case AFE_PORT_ID_PRIMARY_SPDIF_RX: return IDX_PRIMARY_SPDIF_RX;
	case AFE_PORT_ID_PRIMARY_SPDIF_TX: return IDX_PRIMARY_SPDIF_TX;
	case AFE_PORT_ID_SECONDARY_SPDIF_RX: return IDX_SECONDARY_SPDIF_RX;
	case AFE_PORT_ID_SECONDARY_SPDIF_TX: return IDX_SECONDARY_SPDIF_TX;
	case RSVD_2: return IDX_RSVD_2;
	case RSVD_3: return IDX_RSVD_3;
	case DIGI_MIC_TX: return IDX_DIGI_MIC_TX;
	case VOICE_RECORD_RX: return IDX_VOICE_RECORD_RX;
	case VOICE_RECORD_TX: return IDX_VOICE_RECORD_TX;
	case VOICE_PLAYBACK_TX: return IDX_VOICE_PLAYBACK_TX;
	case VOICE2_PLAYBACK_TX: return IDX_VOICE2_PLAYBACK_TX;
	case SLIMBUS_0_RX: return IDX_SLIMBUS_0_RX;
	case SLIMBUS_0_TX: return IDX_SLIMBUS_0_TX;
	case SLIMBUS_1_RX: return IDX_SLIMBUS_1_RX;
	case SLIMBUS_1_TX: return IDX_SLIMBUS_1_TX;
	case SLIMBUS_2_RX: return IDX_SLIMBUS_2_RX;
	case SLIMBUS_2_TX: return IDX_SLIMBUS_2_TX;
	case SLIMBUS_3_RX: return IDX_SLIMBUS_3_RX;
	case SLIMBUS_3_TX: return IDX_SLIMBUS_3_TX;
	case INT_BT_SCO_RX: return IDX_INT_BT_SCO_RX;
	case INT_BT_SCO_TX: return IDX_INT_BT_SCO_TX;
	case INT_BT_A2DP_RX: return IDX_INT_BT_A2DP_RX;
	case INT_FM_RX: return IDX_INT_FM_RX;
	case INT_FM_TX: return IDX_INT_FM_TX;
	case RT_PROXY_PORT_001_RX: return IDX_RT_PROXY_PORT_001_RX;
	case RT_PROXY_PORT_001_TX: return IDX_RT_PROXY_PORT_001_TX;
	case SLIMBUS_4_RX: return IDX_SLIMBUS_4_RX;
	case SLIMBUS_4_TX: return IDX_SLIMBUS_4_TX;
	case SLIMBUS_5_RX: return IDX_SLIMBUS_5_RX;
	case SLIMBUS_5_TX: return IDX_SLIMBUS_5_TX;
	case SLIMBUS_6_RX: return IDX_SLIMBUS_6_RX;
	case SLIMBUS_6_TX: return IDX_SLIMBUS_6_TX;
	case SLIMBUS_7_RX: return IDX_SLIMBUS_7_RX;
	case SLIMBUS_7_TX: return IDX_SLIMBUS_7_TX;
	case SLIMBUS_8_RX: return IDX_SLIMBUS_8_RX;
	case SLIMBUS_8_TX: return IDX_SLIMBUS_8_TX;
	case SLIMBUS_9_RX: return IDX_SLIMBUS_9_RX;
	case SLIMBUS_9_TX: return IDX_SLIMBUS_9_TX;
	case AFE_PORT_ID_USB_RX: return IDX_AFE_PORT_ID_USB_RX;
	case AFE_PORT_ID_USB_TX: return IDX_AFE_PORT_ID_USB_TX;
	case AFE_PORT_ID_PRIMARY_MI2S_RX:
		return IDX_AFE_PORT_ID_PRIMARY_MI2S_RX;
	case AFE_PORT_ID_PRIMARY_MI2S_TX:
		return IDX_AFE_PORT_ID_PRIMARY_MI2S_TX;
	case AFE_PORT_ID_QUATERNARY_MI2S_RX:
		return IDX_AFE_PORT_ID_QUATERNARY_MI2S_RX;
	case AFE_PORT_ID_QUATERNARY_MI2S_TX:
		return IDX_AFE_PORT_ID_QUATERNARY_MI2S_TX;
	case AFE_PORT_ID_SECONDARY_MI2S_RX:
		return IDX_AFE_PORT_ID_SECONDARY_MI2S_RX;
	case AFE_PORT_ID_SECONDARY_MI2S_TX:
		return IDX_AFE_PORT_ID_SECONDARY_MI2S_TX;
	case AFE_PORT_ID_TERTIARY_MI2S_RX:
		return IDX_AFE_PORT_ID_TERTIARY_MI2S_RX;
	case AFE_PORT_ID_TERTIARY_MI2S_TX:
		return IDX_AFE_PORT_ID_TERTIARY_MI2S_TX;
	case AFE_PORT_ID_SECONDARY_MI2S_RX_SD1:
		return IDX_AFE_PORT_ID_SECONDARY_MI2S_RX_SD1;
	case AFE_PORT_ID_QUINARY_MI2S_RX:
		return IDX_AFE_PORT_ID_QUINARY_MI2S_RX;
	case AFE_PORT_ID_QUINARY_MI2S_TX:
		return IDX_AFE_PORT_ID_QUINARY_MI2S_TX;
	case AFE_PORT_ID_SENARY_MI2S_RX:
		return IDX_AFE_PORT_ID_SENARY_MI2S_RX;
	case AFE_PORT_ID_SENARY_MI2S_TX:
		return IDX_AFE_PORT_ID_SENARY_MI2S_TX;
	case AFE_PORT_ID_PRIMARY_TDM_RX:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_RX_0;
	case AFE_PORT_ID_PRIMARY_TDM_TX:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_TX_0;
	case AFE_PORT_ID_PRIMARY_TDM_RX_1:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_RX_1;
	case AFE_PORT_ID_PRIMARY_TDM_TX_1:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_TX_1;
	case AFE_PORT_ID_PRIMARY_TDM_RX_2:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_RX_2;
	case AFE_PORT_ID_PRIMARY_TDM_TX_2:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_TX_2;
	case AFE_PORT_ID_PRIMARY_TDM_RX_3:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_RX_3;
	case AFE_PORT_ID_PRIMARY_TDM_TX_3:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_TX_3;
	case AFE_PORT_ID_PRIMARY_TDM_RX_4:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_RX_4;
	case AFE_PORT_ID_PRIMARY_TDM_TX_4:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_TX_4;
	case AFE_PORT_ID_PRIMARY_TDM_RX_5:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_RX_5;
	case AFE_PORT_ID_PRIMARY_TDM_TX_5:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_TX_5;
	case AFE_PORT_ID_PRIMARY_TDM_RX_6:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_RX_6;
	case AFE_PORT_ID_PRIMARY_TDM_TX_6:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_TX_6;
	case AFE_PORT_ID_PRIMARY_TDM_RX_7:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_RX_7;
	case AFE_PORT_ID_PRIMARY_TDM_TX_7:
		return IDX_AFE_PORT_ID_PRIMARY_TDM_TX_7;
	case AFE_PORT_ID_SECONDARY_TDM_RX:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_RX_0;
	case AFE_PORT_ID_SECONDARY_TDM_TX:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_TX_0;
	case AFE_PORT_ID_SECONDARY_TDM_RX_1:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_RX_1;
	case AFE_PORT_ID_SECONDARY_TDM_TX_1:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_TX_1;
	case AFE_PORT_ID_SECONDARY_TDM_RX_2:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_RX_2;
	case AFE_PORT_ID_SECONDARY_TDM_TX_2:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_TX_2;
	case AFE_PORT_ID_SECONDARY_TDM_RX_3:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_RX_3;
	case AFE_PORT_ID_SECONDARY_TDM_TX_3:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_TX_3;
	case AFE_PORT_ID_SECONDARY_TDM_RX_4:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_RX_4;
	case AFE_PORT_ID_SECONDARY_TDM_TX_4:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_TX_4;
	case AFE_PORT_ID_SECONDARY_TDM_RX_5:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_RX_5;
	case AFE_PORT_ID_SECONDARY_TDM_TX_5:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_TX_5;
	case AFE_PORT_ID_SECONDARY_TDM_RX_6:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_RX_6;
	case AFE_PORT_ID_SECONDARY_TDM_TX_6:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_TX_6;
	case AFE_PORT_ID_SECONDARY_TDM_RX_7:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_RX_7;
	case AFE_PORT_ID_SECONDARY_TDM_TX_7:
		return IDX_AFE_PORT_ID_SECONDARY_TDM_TX_7;
	case AFE_PORT_ID_TERTIARY_TDM_RX:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_RX_0;
	case AFE_PORT_ID_TERTIARY_TDM_TX:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_TX_0;
	case AFE_PORT_ID_TERTIARY_TDM_RX_1:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_RX_1;
	case AFE_PORT_ID_TERTIARY_TDM_TX_1:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_TX_1;
	case AFE_PORT_ID_TERTIARY_TDM_RX_2:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_RX_2;
	case AFE_PORT_ID_TERTIARY_TDM_TX_2:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_TX_2;
	case AFE_PORT_ID_TERTIARY_TDM_RX_3:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_RX_3;
	case AFE_PORT_ID_TERTIARY_TDM_TX_3:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_TX_3;
	case AFE_PORT_ID_TERTIARY_TDM_RX_4:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_RX_4;
	case AFE_PORT_ID_TERTIARY_TDM_TX_4:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_TX_4;
	case AFE_PORT_ID_TERTIARY_TDM_RX_5:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_RX_5;
	case AFE_PORT_ID_TERTIARY_TDM_TX_5:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_TX_5;
	case AFE_PORT_ID_TERTIARY_TDM_RX_6:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_RX_6;
	case AFE_PORT_ID_TERTIARY_TDM_TX_6:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_TX_6;
	case AFE_PORT_ID_TERTIARY_TDM_RX_7:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_RX_7;
	case AFE_PORT_ID_TERTIARY_TDM_TX_7:
		return IDX_AFE_PORT_ID_TERTIARY_TDM_TX_7;
	case AFE_PORT_ID_QUATERNARY_TDM_RX:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_RX_0;
	case AFE_PORT_ID_QUATERNARY_TDM_TX:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_TX_0;
	case AFE_PORT_ID_QUATERNARY_TDM_RX_1:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_RX_1;
	case AFE_PORT_ID_QUATERNARY_TDM_TX_1:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_TX_1;
	case AFE_PORT_ID_QUATERNARY_TDM_RX_2:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_RX_2;
	case AFE_PORT_ID_QUATERNARY_TDM_TX_2:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_TX_2;
	case AFE_PORT_ID_QUATERNARY_TDM_RX_3:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_RX_3;
	case AFE_PORT_ID_QUATERNARY_TDM_TX_3:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_TX_3;
	case AFE_PORT_ID_QUATERNARY_TDM_RX_4:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_RX_4;
	case AFE_PORT_ID_QUATERNARY_TDM_TX_4:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_TX_4;
	case AFE_PORT_ID_QUATERNARY_TDM_RX_5:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_RX_5;
	case AFE_PORT_ID_QUATERNARY_TDM_TX_5:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_TX_5;
	case AFE_PORT_ID_QUATERNARY_TDM_RX_6:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_RX_6;
	case AFE_PORT_ID_QUATERNARY_TDM_TX_6:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_TX_6;
	case AFE_PORT_ID_QUATERNARY_TDM_RX_7:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_RX_7;
	case AFE_PORT_ID_QUATERNARY_TDM_TX_7:
		return IDX_AFE_PORT_ID_QUATERNARY_TDM_TX_7;
	case AFE_PORT_ID_QUINARY_TDM_RX:
		return IDX_AFE_PORT_ID_QUINARY_TDM_RX_0;
	case AFE_PORT_ID_QUINARY_TDM_TX:
		return IDX_AFE_PORT_ID_QUINARY_TDM_TX_0;
	case AFE_PORT_ID_QUINARY_TDM_RX_1:
		return IDX_AFE_PORT_ID_QUINARY_TDM_RX_1;
	case AFE_PORT_ID_QUINARY_TDM_TX_1:
		return IDX_AFE_PORT_ID_QUINARY_TDM_TX_1;
	case AFE_PORT_ID_QUINARY_TDM_RX_2:
		return IDX_AFE_PORT_ID_QUINARY_TDM_RX_2;
	case AFE_PORT_ID_QUINARY_TDM_TX_2:
		return IDX_AFE_PORT_ID_QUINARY_TDM_TX_2;
	case AFE_PORT_ID_QUINARY_TDM_RX_3:
		return IDX_AFE_PORT_ID_QUINARY_TDM_RX_3;
	case AFE_PORT_ID_QUINARY_TDM_TX_3:
		return IDX_AFE_PORT_ID_QUINARY_TDM_TX_3;
	case AFE_PORT_ID_QUINARY_TDM_RX_4:
		return IDX_AFE_PORT_ID_QUINARY_TDM_RX_4;
	case AFE_PORT_ID_QUINARY_TDM_TX_4:
		return IDX_AFE_PORT_ID_QUINARY_TDM_TX_4;
	case AFE_PORT_ID_QUINARY_TDM_RX_5:
		return IDX_AFE_PORT_ID_QUINARY_TDM_RX_5;
	case AFE_PORT_ID_QUINARY_TDM_TX_5:
		return IDX_AFE_PORT_ID_QUINARY_TDM_TX_5;
	case AFE_PORT_ID_QUINARY_TDM_RX_6:
		return IDX_AFE_PORT_ID_QUINARY_TDM_RX_6;
	case AFE_PORT_ID_QUINARY_TDM_TX_6:
		return IDX_AFE_PORT_ID_QUINARY_TDM_TX_6;
	case AFE_PORT_ID_QUINARY_TDM_RX_7:
		return IDX_AFE_PORT_ID_QUINARY_TDM_RX_7;
	case AFE_PORT_ID_QUINARY_TDM_TX_7:
		return IDX_AFE_PORT_ID_QUINARY_TDM_TX_7;
	case AFE_PORT_ID_SENARY_TDM_RX:
		return IDX_AFE_PORT_ID_SENARY_TDM_RX_0;
	case AFE_PORT_ID_SENARY_TDM_TX:
		return IDX_AFE_PORT_ID_SENARY_TDM_TX_0;
	case AFE_PORT_ID_SENARY_TDM_RX_1:
		return IDX_AFE_PORT_ID_SENARY_TDM_RX_1;
	case AFE_PORT_ID_SENARY_TDM_TX_1:
		return IDX_AFE_PORT_ID_SENARY_TDM_TX_1;
	case AFE_PORT_ID_SENARY_TDM_RX_2:
		return IDX_AFE_PORT_ID_SENARY_TDM_RX_2;
	case AFE_PORT_ID_SENARY_TDM_TX_2:
		return IDX_AFE_PORT_ID_SENARY_TDM_TX_2;
	case AFE_PORT_ID_SENARY_TDM_RX_3:
		return IDX_AFE_PORT_ID_SENARY_TDM_RX_3;
	case AFE_PORT_ID_SENARY_TDM_TX_3:
		return IDX_AFE_PORT_ID_SENARY_TDM_TX_3;
	case AFE_PORT_ID_SENARY_TDM_RX_4:
		return IDX_AFE_PORT_ID_SENARY_TDM_RX_4;
	case AFE_PORT_ID_SENARY_TDM_TX_4:
		return IDX_AFE_PORT_ID_SENARY_TDM_TX_4;
	case AFE_PORT_ID_SENARY_TDM_RX_5:
		return IDX_AFE_PORT_ID_SENARY_TDM_RX_5;
	case AFE_PORT_ID_SENARY_TDM_TX_5:
		return IDX_AFE_PORT_ID_SENARY_TDM_TX_5;
	case AFE_PORT_ID_SENARY_TDM_RX_6:
		return IDX_AFE_PORT_ID_SENARY_TDM_RX_6;
	case AFE_PORT_ID_SENARY_TDM_TX_6:
		return IDX_AFE_PORT_ID_SENARY_TDM_TX_6;
	case AFE_PORT_ID_SENARY_TDM_RX_7:
		return IDX_AFE_PORT_ID_SENARY_TDM_RX_7;
	case AFE_PORT_ID_SENARY_TDM_TX_7:
		return IDX_AFE_PORT_ID_SENARY_TDM_TX_7;
	case AFE_PORT_ID_INT0_MI2S_RX:
		return IDX_AFE_PORT_ID_INT0_MI2S_RX;
	case AFE_PORT_ID_INT0_MI2S_TX:
		return IDX_AFE_PORT_ID_INT0_MI2S_TX;
	case AFE_PORT_ID_INT1_MI2S_RX:
		return IDX_AFE_PORT_ID_INT1_MI2S_RX;
	case AFE_PORT_ID_INT1_MI2S_TX:
		return IDX_AFE_PORT_ID_INT1_MI2S_TX;
	case AFE_PORT_ID_INT2_MI2S_RX:
		return IDX_AFE_PORT_ID_INT2_MI2S_RX;
	case AFE_PORT_ID_INT2_MI2S_TX:
		return IDX_AFE_PORT_ID_INT2_MI2S_TX;
	case AFE_PORT_ID_INT3_MI2S_RX:
		return IDX_AFE_PORT_ID_INT3_MI2S_RX;
	case AFE_PORT_ID_INT3_MI2S_TX:
		return IDX_AFE_PORT_ID_INT3_MI2S_TX;
	case AFE_PORT_ID_INT4_MI2S_RX:
		return IDX_AFE_PORT_ID_INT4_MI2S_RX;
	case AFE_PORT_ID_INT4_MI2S_TX:
		return IDX_AFE_PORT_ID_INT4_MI2S_TX;
	case AFE_PORT_ID_INT5_MI2S_RX:
		return IDX_AFE_PORT_ID_INT5_MI2S_RX;
	case AFE_PORT_ID_INT5_MI2S_TX:
		return IDX_AFE_PORT_ID_INT5_MI2S_TX;
	case AFE_PORT_ID_INT6_MI2S_RX:
		return IDX_AFE_PORT_ID_INT6_MI2S_RX;
	case AFE_PORT_ID_INT6_MI2S_TX:
		return IDX_AFE_PORT_ID_INT6_MI2S_TX;
	case AFE_PORT_ID_PRIMARY_META_MI2S_RX:
		return IDX_AFE_PORT_ID_PRIMARY_META_MI2S_RX;
	case AFE_PORT_ID_SECONDARY_META_MI2S_RX:
		return IDX_AFE_PORT_ID_SECONDARY_META_MI2S_RX;
	case AFE_PORT_ID_VA_CODEC_DMA_TX_0:
		return IDX_AFE_PORT_ID_VA_CODEC_DMA_TX_0;
	case AFE_PORT_ID_VA_CODEC_DMA_TX_1:
		return IDX_AFE_PORT_ID_VA_CODEC_DMA_TX_1;
	case AFE_PORT_ID_VA_CODEC_DMA_TX_2:
		return IDX_AFE_PORT_ID_VA_CODEC_DMA_TX_2;
	case AFE_PORT_ID_WSA_CODEC_DMA_RX_0:
		return IDX_AFE_PORT_ID_WSA_CODEC_DMA_RX_0;
	case AFE_PORT_ID_WSA_CODEC_DMA_TX_0:
		return IDX_AFE_PORT_ID_WSA_CODEC_DMA_TX_0;
	case AFE_PORT_ID_WSA_CODEC_DMA_RX_1:
		return IDX_AFE_PORT_ID_WSA_CODEC_DMA_RX_1;
	case AFE_PORT_ID_WSA_CODEC_DMA_TX_1:
		return IDX_AFE_PORT_ID_WSA_CODEC_DMA_TX_1;
	case AFE_PORT_ID_WSA_CODEC_DMA_TX_2:
		return IDX_AFE_PORT_ID_WSA_CODEC_DMA_TX_2;
	case AFE_PORT_ID_RX_CODEC_DMA_RX_0:
		return IDX_AFE_PORT_ID_RX_CODEC_DMA_RX_0;
	case AFE_PORT_ID_TX_CODEC_DMA_TX_0:
		return IDX_AFE_PORT_ID_TX_CODEC_DMA_TX_0;
	case AFE_PORT_ID_RX_CODEC_DMA_RX_1:
		return IDX_AFE_PORT_ID_RX_CODEC_DMA_RX_1;
	case AFE_PORT_ID_TX_CODEC_DMA_TX_1:
		return IDX_AFE_PORT_ID_TX_CODEC_DMA_TX_1;
	case AFE_PORT_ID_RX_CODEC_DMA_RX_2:
		return IDX_AFE_PORT_ID_RX_CODEC_DMA_RX_2;
	case AFE_PORT_ID_TX_CODEC_DMA_TX_2:
		return IDX_AFE_PORT_ID_TX_CODEC_DMA_TX_2;
	case AFE_PORT_ID_RX_CODEC_DMA_RX_3:
		return IDX_AFE_PORT_ID_RX_CODEC_DMA_RX_3;
	case AFE_PORT_ID_TX_CODEC_DMA_TX_3:
		return IDX_AFE_PORT_ID_TX_CODEC_DMA_TX_3;
	case AFE_PORT_ID_RX_CODEC_DMA_RX_4:
		return IDX_AFE_PORT_ID_RX_CODEC_DMA_RX_4;
	case AFE_PORT_ID_TX_CODEC_DMA_TX_4:
		return IDX_AFE_PORT_ID_TX_CODEC_DMA_TX_4;
	case AFE_PORT_ID_RX_CODEC_DMA_RX_5:
		return IDX_AFE_PORT_ID_RX_CODEC_DMA_RX_5;
	case AFE_PORT_ID_TX_CODEC_DMA_TX_5:
		return IDX_AFE_PORT_ID_TX_CODEC_DMA_TX_5;
	case AFE_PORT_ID_RX_CODEC_DMA_RX_6:
		return IDX_AFE_PORT_ID_RX_CODEC_DMA_RX_6;
	case AFE_PORT_ID_RX_CODEC_DMA_RX_7:
		return IDX_AFE_PORT_ID_RX_CODEC_DMA_RX_7;
	case AFE_LOOPBACK_TX:
		return IDX_AFE_LOOPBACK_TX;
	case RT_PROXY_PORT_002_RX:
		return IDX_RT_PROXY_PORT_002_RX;
	case RT_PROXY_PORT_002_TX:
		return IDX_RT_PROXY_PORT_002_TX;
	default:
		pr_err("%s: port 0x%x\n", __func__, port_id);
		return -EINVAL;
	}
}

/**
 * afe_open -
 *         command to open AFE port
 *
 * @port_id: AFE port id
 * @afe_config: AFE port config to pass
 * @rate: sample rate
 *
 * Returns 0 on success or error on failure
 */
int afe_open(u16 port_id,
		union afe_port_config *afe_config, int rate)
{
	struct afe_port_cmd_device_start start;
	union afe_port_config port_cfg;
	struct param_hdr_v3 param_hdr;
	int ret = 0;
	int cfg_type;
	int index = 0;

	memset(&param_hdr, 0, sizeof(param_hdr));
	memset(&start, 0, sizeof(start));
	memset(&port_cfg, 0, sizeof(port_cfg));

	if (!afe_config) {
		pr_err("%s: Error, no configuration data\n", __func__);
		ret = -EINVAL;
		return ret;
	}

	pr_err("%s: port_id 0x%x rate %d\n", __func__, port_id, rate);

	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		return -EINVAL;
	}
	ret = q6audio_validate_port(port_id);
	if (ret < 0) {
		pr_err("%s: Invalid port 0x%x ret %d", __func__, port_id, ret);
		return -EINVAL;
	}

	if ((port_id == RT_PROXY_DAI_001_RX) ||
		(port_id == RT_PROXY_DAI_002_TX)) {
		pr_err("%s: wrong port 0x%x\n", __func__, port_id);
		return -EINVAL;
	}
	if ((port_id == RT_PROXY_DAI_002_RX) ||
		(port_id == RT_PROXY_DAI_001_TX))
		port_id = VIRTUAL_ID_TO_PORTID(port_id);

	ret = afe_q6_interface_prepare();
	if (ret != 0) {
		pr_err("%s: Q6 interface prepare failed %d\n", __func__, ret);
		return -EINVAL;
	}

	if ((index >= 0) && (index < AFE_MAX_PORTS)) {
		this_afe.afe_sample_rates[index] = rate;

		if (this_afe.rt_cb)
			this_afe.dev_acdb_id[index] = this_afe.rt_cb(port_id);
	}

	/* Also send the topology id here: */
	afe_send_custom_topology(); /* One time call: only for first time  */
	afe_send_port_topology_id(port_id);

	ret = q6audio_validate_port(port_id);
	if (ret < 0) {
		pr_err("%s: Failed : Invalid Port id = 0x%x ret %d\n",
			__func__, port_id, ret);
		return -EINVAL;
	}
	mutex_lock(&this_afe.afe_cmd_lock);

	switch (port_id) {
	case PRIMARY_I2S_RX:
	case PRIMARY_I2S_TX:
		cfg_type = AFE_PARAM_ID_I2S_CONFIG;
		break;
	case AFE_PORT_ID_PRIMARY_PCM_RX:
	case AFE_PORT_ID_PRIMARY_PCM_TX:
	case AFE_PORT_ID_SECONDARY_PCM_RX:
	case AFE_PORT_ID_SECONDARY_PCM_TX:
	case AFE_PORT_ID_TERTIARY_PCM_RX:
	case AFE_PORT_ID_TERTIARY_PCM_TX:
	case AFE_PORT_ID_QUATERNARY_PCM_RX:
	case AFE_PORT_ID_QUATERNARY_PCM_TX:
	case AFE_PORT_ID_QUINARY_PCM_RX:
	case AFE_PORT_ID_QUINARY_PCM_TX:
	case AFE_PORT_ID_SENARY_PCM_RX:
	case AFE_PORT_ID_SENARY_PCM_TX:
		cfg_type = AFE_PARAM_ID_PCM_CONFIG;
		break;
	case SECONDARY_I2S_RX:
	case SECONDARY_I2S_TX:
	case AFE_PORT_ID_PRIMARY_MI2S_RX:
	case AFE_PORT_ID_PRIMARY_MI2S_TX:
	case AFE_PORT_ID_QUATERNARY_MI2S_RX:
	case AFE_PORT_ID_QUATERNARY_MI2S_TX:
	case MI2S_RX:
	case MI2S_TX:
	case AFE_PORT_ID_QUINARY_MI2S_RX:
	case AFE_PORT_ID_QUINARY_MI2S_TX:
	case AFE_PORT_ID_SENARY_MI2S_RX:
	case AFE_PORT_ID_SENARY_MI2S_TX:
		cfg_type = AFE_PARAM_ID_I2S_CONFIG;
		break;
	case AFE_PORT_ID_PRIMARY_META_MI2S_RX:
	case AFE_PORT_ID_SECONDARY_META_MI2S_RX:
		cfg_type = AFE_PARAM_ID_META_I2S_CONFIG;
		break;
	case HDMI_RX:
	case HDMI_RX_MS:
	case DISPLAY_PORT_RX:
		cfg_type = AFE_PARAM_ID_HDMI_CONFIG;
		break;
	case AFE_PORT_ID_PRIMARY_SPDIF_RX:
	case AFE_PORT_ID_PRIMARY_SPDIF_TX:
	case AFE_PORT_ID_SECONDARY_SPDIF_RX:
	case AFE_PORT_ID_SECONDARY_SPDIF_TX:
		cfg_type = AFE_PARAM_ID_SPDIF_CONFIG;
		break;
	case SLIMBUS_0_RX:
	case SLIMBUS_0_TX:
	case SLIMBUS_1_RX:
	case SLIMBUS_1_TX:
	case SLIMBUS_2_RX:
	case SLIMBUS_2_TX:
	case SLIMBUS_3_RX:
	case SLIMBUS_3_TX:
	case SLIMBUS_4_RX:
	case SLIMBUS_4_TX:
	case SLIMBUS_5_RX:
	case SLIMBUS_6_RX:
	case SLIMBUS_6_TX:
	case SLIMBUS_7_RX:
	case SLIMBUS_7_TX:
	case SLIMBUS_8_RX:
	case SLIMBUS_8_TX:
	case SLIMBUS_9_RX:
	case SLIMBUS_9_TX:
		cfg_type = AFE_PARAM_ID_SLIMBUS_CONFIG;
		break;
	case AFE_PORT_ID_USB_RX:
	case AFE_PORT_ID_USB_TX:
		cfg_type = AFE_PARAM_ID_USB_AUDIO_CONFIG;
		break;
	case AFE_PORT_ID_WSA_CODEC_DMA_RX_0:
	case AFE_PORT_ID_WSA_CODEC_DMA_TX_0:
	case AFE_PORT_ID_WSA_CODEC_DMA_RX_1:
	case AFE_PORT_ID_WSA_CODEC_DMA_TX_1:
	case AFE_PORT_ID_WSA_CODEC_DMA_TX_2:
	case AFE_PORT_ID_VA_CODEC_DMA_TX_0:
	case AFE_PORT_ID_VA_CODEC_DMA_TX_1:
	case AFE_PORT_ID_VA_CODEC_DMA_TX_2:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_0:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_0:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_1:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_1:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_2:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_2:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_3:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_3:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_4:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_4:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_5:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_5:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_6:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_7:
		cfg_type = AFE_PARAM_ID_CODEC_DMA_CONFIG;
		break;
	default:
		pr_err("%s: Invalid port id 0x%x\n",
			__func__, port_id);
		ret = -EINVAL;
		goto fail_cmd;
	}

	param_hdr.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = cfg_type;
	param_hdr.param_size = sizeof(union afe_port_config);
	port_cfg = *afe_config;

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) &port_cfg);
	if (ret) {
		pr_err("%s: AFE enable for port 0x%x opcode[0x%x]failed %d\n",
			__func__, port_id, cfg_type, ret);
		goto fail_cmd;
	}
	start.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	start.hdr.pkt_size = sizeof(start);
	start.hdr.src_port = 0;
	start.hdr.dest_port = 0;
	start.hdr.token = index;
	start.hdr.opcode = AFE_PORT_CMD_DEVICE_START;
	start.port_id = q6audio_get_port_id(port_id);
	pr_debug("%s: cmd device start opcode[0x%x] port id[0x%x]\n",
		__func__, start.hdr.opcode, start.port_id);

	ret = afe_apr_send_pkt(&start, &this_afe.wait[index]);
	if (ret) {
		pr_err("%s: AFE enable for port 0x%x failed %d\n", __func__,
				port_id, ret);
		goto fail_cmd;
	}

fail_cmd:
	mutex_unlock(&this_afe.afe_cmd_lock);
	return ret;
}
EXPORT_SYMBOL(afe_open);

/**
 * afe_loopback -
 *         command to set loopback between AFE ports
 *
 * @enable: enable or disable loopback
 * @rx_port: AFE RX port ID
 * @tx_port: AFE TX port ID
 *
 * Returns 0 on success or error on failure
 */
int afe_loopback(u16 enable, u16 rx_port, u16 tx_port)
{
	struct afe_loopback_cfg_v1 lb_param;
	struct param_hdr_v3 param_hdr;
	int ret = 0;

	memset(&lb_param, 0, sizeof(lb_param));
	memset(&param_hdr, 0, sizeof(param_hdr));

	if (rx_port == MI2S_RX)
		rx_port = AFE_PORT_ID_PRIMARY_MI2S_RX;
	if (tx_port == MI2S_TX)
		tx_port = AFE_PORT_ID_PRIMARY_MI2S_TX;

	param_hdr.module_id = AFE_MODULE_LOOPBACK;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_LOOPBACK_CONFIG;
	param_hdr.param_size = sizeof(struct afe_loopback_cfg_v1);

	lb_param.dst_port_id = rx_port;
	lb_param.routing_mode = LB_MODE_DEFAULT;
	lb_param.enable = (enable ? 1 : 0);
	lb_param.loopback_cfg_minor_version = AFE_API_VERSION_LOOPBACK_CONFIG;

	ret = q6afe_pack_and_set_param_in_band(tx_port,
					       q6audio_get_port_index(tx_port),
					       param_hdr, (u8 *) &lb_param);
	if (ret)
		pr_err("%s: AFE loopback failed %d\n", __func__, ret);
	return ret;
}
EXPORT_SYMBOL(afe_loopback);

/**
 * afe_loopback_gain -
 *         command to set gain for AFE loopback
 *
 * @port_id: AFE port id
 * @volume: gain value to set
 *
 * Returns 0 on success or error on failure
 */
int afe_loopback_gain(u16 port_id, u16 volume)
{
	struct afe_loopback_gain_per_path_param set_param;
	struct param_hdr_v3 param_hdr;
	int ret = 0;

	memset(&set_param, 0, sizeof(set_param));
	memset(&param_hdr, 0, sizeof(param_hdr));

	if (this_afe.apr == NULL) {
		this_afe.apr = apr_register("ADSP", "AFE", afe_callback,
					0xFFFFFFFF, &this_afe);
		pr_debug("%s: Register AFE\n", __func__);
		if (this_afe.apr == NULL) {
			pr_err("%s: Unable to register AFE\n", __func__);
			ret = -ENODEV;
			return ret;
		}
		rtac_set_afe_handle(this_afe.apr);
	}

	ret = q6audio_validate_port(port_id);
	if (ret < 0) {
		pr_err("%s: Failed : Invalid Port id = 0x%x ret %d\n",
			__func__, port_id, ret);
		ret = -EINVAL;
		goto fail_cmd;
	}

	/* RX ports numbers are even .TX ports numbers are odd. */
	if (port_id % 2 == 0) {
		pr_err("%s: Failed : afe loopback gain only for TX ports. port_id %d\n",
				__func__, port_id);
		ret = -EINVAL;
		goto fail_cmd;
	}

	pr_debug("%s: port 0x%x volume %d\n", __func__, port_id, volume);

	param_hdr.module_id = AFE_MODULE_LOOPBACK;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_LOOPBACK_GAIN_PER_PATH;
	param_hdr.param_size = sizeof(struct afe_loopback_gain_per_path_param);
	set_param.rx_port_id = port_id;
	set_param.gain = volume;

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) &set_param);
	if (ret)
		pr_err("%s: AFE param set failed for port 0x%x ret %d\n",
					__func__, port_id, ret);

fail_cmd:
	return ret;
}
EXPORT_SYMBOL(afe_loopback_gain);

int afe_pseudo_port_start_nowait(u16 port_id)
{
	struct afe_pseudoport_start_command start;
	int ret = 0;

	pr_debug("%s: port_id=0x%x\n", __func__, port_id);
	if (this_afe.apr == NULL) {
		pr_err("%s: AFE APR is not registered\n", __func__);
		return -ENODEV;
	}


	start.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	start.hdr.pkt_size = sizeof(start);
	start.hdr.src_port = 0;
	start.hdr.dest_port = 0;
	start.hdr.token = 0;
	start.hdr.opcode = AFE_PSEUDOPORT_CMD_START;
	start.port_id = port_id;
	start.timing = 1;

	ret = afe_apr_send_pkt(&start, NULL);
	if (ret) {
		pr_err("%s: AFE enable for port 0x%x failed %d\n",
		       __func__, port_id, ret);
		return ret;
	}
	return 0;
}

int afe_start_pseudo_port(u16 port_id)
{
	int ret = 0;
	struct afe_pseudoport_start_command start;
	int index = 0;

	pr_debug("%s: port_id = 0x%x\n", __func__, port_id);

	ret = afe_q6_interface_prepare();
	if (ret != 0) {
		pr_err("%s: Q6 interface prepare failed %d\n", __func__, ret);
		return ret;
	}

	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		return -EINVAL;
	}
	ret = q6audio_validate_port(port_id);
	if (ret < 0) {
		pr_err("%s: Invalid port 0x%x ret %d",
			__func__, port_id, ret);
		return -EINVAL;
	}

	start.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	start.hdr.pkt_size = sizeof(start);
	start.hdr.src_port = 0;
	start.hdr.dest_port = 0;
	start.hdr.token = 0;
	start.hdr.opcode = AFE_PSEUDOPORT_CMD_START;
	start.port_id = port_id;
	start.timing = 1;
	start.hdr.token = index;

	ret = afe_apr_send_pkt(&start, &this_afe.wait[index]);
	if (ret)
		pr_err("%s: AFE enable for port 0x%x failed %d\n",
		       __func__, port_id, ret);
	return ret;
}

#if IS_ENABLED(CONFIG_TAS25XX_ALGO)
/*For DC Detection*/
void (*tas256x_sw_reset)(void *data);
dc_detection_data_t *s_dc_detect;
void register_tas256x_reset_func(void *fptr, dc_detection_data_t *data)
{
	pr_info("[TI-SmartPA:%s] ", __func__);
	tas256x_sw_reset = fptr;
	s_dc_detect = data;
}
EXPORT_SYMBOL(register_tas256x_reset_func);

void afe_tas_smartamp_init(uint32_t module_id_rx, uint32_t module_id_tx)
{
	this_afe.tas_module_rx = module_id_rx;
	this_afe.tas_module_tx = module_id_tx;
}
EXPORT_SYMBOL(afe_tas_smartamp_init);

#ifdef INSTANCE_ID_0 /* APR Version 3 */
static int32_t tas_smartamp_algo_callback(uint32_t opcode, uint32_t *payload,
				    uint32_t payload_size)
{
	struct param_hdr_v3 param_hdr;
	u32 *data_dest = NULL;
	u32 *data_start = NULL;

	pr_debug("[TI-SmartPA:%s] ", __func__);
	memset(&param_hdr, 0, sizeof(param_hdr));
	switch (opcode) {
	case AFE_PORT_CMDRSP_GET_PARAM_V2:
		param_hdr.module_id = payload[1];
		param_hdr.instance_id = INSTANCE_ID_0;
		param_hdr.param_id = payload[2];
		param_hdr.param_size = payload[3];
		data_start = &payload[4];
		break;
	case AFE_PORT_CMDRSP_GET_PARAM_V3:
		memcpy(&param_hdr, &payload[1], sizeof(struct param_hdr_v3));
		data_start = &payload[5];
		break;
	default:
		pr_err("[TI-SmartPA:%s] Unrecognized command %d\n", __func__, opcode);
		return -EINVAL;
	}
	data_dest = (u32 *) &this_afe.tas_calib_data;
	data_dest[0] = payload[0];
	memcpy(&data_dest[1], &param_hdr, sizeof(struct param_hdr_v3));
	memcpy(&data_dest[5], data_start, param_hdr.param_size);
	if (param_hdr.param_id == CAPI_V2_TAS_SA_DC_DETECT) {
		pr_err("[TI-SmartPA:%s] Detected DC, Calling TAS256X Software Reset \n", __func__);
		s_dc_detect->channel = this_afe.tas_calib_data.res_cfg.payload[0];
		tas256x_sw_reset(s_dc_detect);
	}
	if (!data_dest[0]) {
		atomic_set(&this_afe.state, 0);
	} else {
		pr_debug("[TI-SmartPA:%s] status: %d", __func__, data_dest[0]);
		atomic_set(&this_afe.state, -1);
	}
	return 0;
}

int afe_tas_smartamp_get_calib_data(uint32_t module_id, uint32_t param_id,
		int32_t length, uint8_t *data, uint16_t port_id)
{
	int ret = -EINVAL;
	struct param_hdr_v3 param_hdr;
	uint32_t port = 0x0;

	if (!data || length <= 0) {
		pr_err("[TI-SmartPA:%s] Invalid params, length: %d\n",
			__func__, length);
		goto fail_cmd;
	}

	pr_debug("[TI-SmartPA:%s] module id : 0x%x ", __func__, module_id);
	if (module_id == this_afe.tas_module_rx) {
		port = port_id;
	} else if (module_id == this_afe.tas_module_tx) {
		port = port_id + 1;
	} else {
		pr_err("[TI-SmartPA:%s] invalid module id %d\n", module_id);
		goto fail_cmd;
	}

	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = module_id;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = param_id;
	param_hdr.param_size = sizeof(struct afe_smartamp_get_calib);
	ret = q6afe_get_params(port, NULL, &param_hdr);
	if (ret < 0) {
		pr_err("[TI-SmartPA:%s] get param port 0x%x param id[0x%x]failed %d\n",
		       __func__, port, param_hdr.param_id, ret);
		goto fail_cmd;
	}

	memcpy(data, &this_afe.tas_calib_data.res_cfg, length);

	ret = 0;
fail_cmd:
	return ret;
}
EXPORT_SYMBOL(afe_tas_smartamp_get_calib_data);

int afe_tas_smartamp_set_calib_data(uint32_t module_id, uint32_t param_id,
				int32_t length, uint8_t *data, uint16_t port_id)
{
	int ret = -EINVAL;
	uint32_t port = 0x0;
	struct param_hdr_v3 param_hdr;

	u8 *packed_param_data = NULL;
	u32 packed_param_size = 0;
	u32 single_param_size = 0;
	pr_debug("[TI-SmartPA:%s] length: %d\n", __func__, length);
	if (!data || (length < 0)) {
		pr_err("[TI-SmartPA:%s] Invalid params\n", __func__);
		return ret;
	}

	pr_debug("[TI-SmartPA:%s] module id : 0x%x \n", __func__, module_id);
	if (module_id == this_afe.tas_module_rx) {
		port = port_id;
	} else if (module_id == this_afe.tas_module_tx) {
		port = port_id + 1;
	} else {
		pr_err("[TI-SmartPA:%s] invalid module id %d\n", module_id);
		return ret;
	}

	packed_param_size = sizeof(param_hdr) + length;
	packed_param_data = kzalloc(packed_param_size, GFP_KERNEL);
	if (!packed_param_data)
		return -ENOMEM;

	packed_param_size = 0;
	param_hdr.module_id = module_id;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = param_id;
	param_hdr.param_size = length;
	ret = q6common_pack_pp_params(packed_param_data, &param_hdr,
			(u8 *) data, &single_param_size);
	if (ret) {
		pr_err("[TI-SmartPA:%s] Failed to pack param data, error %d\n", __func__,
		       ret);
		goto done;
	}
	packed_param_size += single_param_size;
	ret = q6afe_set_params(port, q6audio_get_port_index(port),
			       NULL, packed_param_data, packed_param_size);
done:
	kfree(packed_param_data);
	return ret;
}
EXPORT_SYMBOL(afe_tas_smartamp_set_calib_data);

#else /* APR Version 2 */
static int32_t tas_smartamp_algo_callback(uint32_t *payload, uint32_t payload_size)
{
	struct afe_smartamp_calib_get_resp *resp =
		(struct afe_smartamp_calib_get_resp *) payload;

	pr_debug("[TI-SmartPA:%s] callback\n", __func__);

	if (!(&(resp->pdata))) {
		pr_err("[TI-SmartPA:%s] Error: resp pdata is NULL", __func__);
		return -EINVAL;
	}

	memcpy(&this_afe.tas_calib_data, payload,
		sizeof(this_afe.tas_calib_data));

	pr_debug("[TI-SmartPA:%s] callback, 0x%x\n", __func__, resp->pdata.param_id);

	if (resp->pdata.param_id == CAPI_V2_TAS_SA_DC_DETECT) {
		s_dc_detect->channel = resp->res_cfg.payload[0];
		pr_err("[TI-SmartPA:%s] Detected DC, Calling TAS256X Software Reset Channel-%s\n", __func__,
			(s_dc_detect->channel == 0)?"Left":"Right");
		tas256x_sw_reset(s_dc_detect);
	}

	if (!this_afe.tas_calib_data.status) {
		atomic_set(&this_afe.state, 0);
	} else {
		pr_debug("[TI-SmartPA:%s] calib resp status: %d", __func__,
			  this_afe.tas_calib_data.status);
		atomic_set(&this_afe.state, -1);
	}

	return 0;
}

/*
* data is writable memroy
* length is the max size of the data
* retuns number of bytes returned by the algorithm
* 	-ve error number in case of failure.
*/
int afe_tas_smartamp_get_calib_data(uint32_t module_id, uint32_t param_id,
		int32_t length, uint8_t *data, uint16_t port_id)
{
	int ret = -EINVAL;
	int index = 0;
	struct afe_smartamp_get_calib calib_resp_o;
	struct afe_smartamp_get_calib *calib_resp = &calib_resp_o;

	if (!data || (length <= 0)) {
		pr_err("[TI-SmartPA: %s] Invalid params\n", __func__);
		goto fail_cmd;
	}
	if ((q6audio_validate_port(port_id) < 0)) {
		pr_err("%s invalid port %d\n", __func__, port_id);
		goto fail_cmd;
	}

	index = q6audio_get_port_index(port_id);
	memset (calib_resp, 0, sizeof(*calib_resp));

	//header
	calib_resp->hdr.hdr_field =
			APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
			APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	calib_resp->hdr.src_svc = APR_SVC_AFE;
	calib_resp->hdr.src_domain = APR_DOMAIN_APPS;
	calib_resp->hdr.dest_svc = APR_SVC_AFE;
	calib_resp->hdr.dest_domain = APR_DOMAIN_ADSP;
	calib_resp->hdr.pkt_size = sizeof(*calib_resp);
	calib_resp->hdr.src_port = 0;
	calib_resp->hdr.dest_port = 0;
	calib_resp->hdr.token = index;
	calib_resp->hdr.opcode =  AFE_PORT_CMD_GET_PARAM_V2;

	//parameter
	calib_resp->get_param.mem_map_handle = 0;
	calib_resp->get_param.module_id = module_id;
	calib_resp->get_param.param_id = param_id;
	calib_resp->get_param.payload_address_lsw = 0;
	calib_resp->get_param.payload_address_msw = 0;
	calib_resp->get_param.payload_size = sizeof(*calib_resp)
				- sizeof(calib_resp->hdr)
				- sizeof(calib_resp->get_param);
	calib_resp->get_param.port_id = q6audio_get_port_id(port_id);

	//data
	calib_resp->pdata.module_id = module_id;
	calib_resp->pdata.param_id = param_id;
	calib_resp->pdata.param_size = sizeof(calib_resp->res_cfg);
	calib_resp->pdata.reserved = 0;
	atomic_set(&this_afe.state, 1);

	ret = apr_send_pkt(this_afe.apr, (uint32_t *)calib_resp);

	if (ret < 0) {
		pr_err("[TI-SmartPA %s]: get param port %d param id[0x%x]failed",
				__func__, port_id, calib_resp->get_param.param_id);
		goto fail_cmd;
	}

	ret = wait_event_timeout(this_afe.wait[index],
			(atomic_read(&this_afe.state) == 0),
			msecs_to_jiffies(TIMEOUT_MS * 5));
	if (!ret) {
		pr_err("[TI-SmartPA %s]: wait_event timeout", __func__);
		ret = -EINVAL;
		goto fail_cmd;
	}
	if (atomic_read(&this_afe.status) != 0) {
		pr_err("[TI-SmartPA %s]: config cmd failed", __func__);
		ret = -EINVAL;
		goto fail_cmd;
	}

	if (length <= sizeof (this_afe.tas_calib_data.res_cfg)) {
		memcpy(data, &this_afe.tas_calib_data.res_cfg, length);
		ret = 0;
	} else {
		ret = -EINVAL;
		memcpy(data, &this_afe.tas_calib_data.res_cfg, length);
	}
	pr_debug("[TI-SmartPA: %s] ret=%d", __func__, ret);

fail_cmd:
	return ret;
}
EXPORT_SYMBOL(afe_tas_smartamp_get_calib_data);

/*
* length -> length in bytes of 'data'
*/
int afe_tas_smartamp_set_calib_data(uint32_t module_id, uint32_t param_id,
		int32_t length, uint8_t *data, uint16_t port_id)
{
	int ret = -EINVAL;
	int index = 0;
	struct afe_smartamp_config_command *config = NULL;
	u8 *cfg = NULL;

	int size = sizeof(struct afe_smartamp_config_command)
				- sizeof(struct afe_smartamp_get_set_params_t)
				+ length;
	if (!data) {
		pr_err("[TI-SmartPA:%s] Invalid params\n", __func__);
		goto fail_cmd;
	}

	cfg = kzalloc(size, GFP_KERNEL);
	if (!cfg) {
		pr_err("[TI-SmartPA:%s] memory allocation failed\n", __func__);
		ret = -ENOMEM;
		goto fail_cmd;
	}

	config = (struct afe_smartamp_config_command *)cfg;
	if (module_id == this_afe.tas_module_rx) {
		port_id = port_id;
	} else if (module_id == this_afe.tas_module_tx) {
		port_id = port_id + 1;
	} else {
		pr_err("[TI-SmartPA: %s] invalid module id %d", __func__, module_id);
		goto fail_cmd;
	}

	if ((q6audio_validate_port(port_id) < 0)) {
		pr_err("[TI-SmartPA: %s] invalid port %d", __func__, port_id);
		goto fail_cmd;
	}

	index = q6audio_get_port_index(port_id);

	//header
	config->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	config->hdr.pkt_size = sizeof(struct afe_smartamp_config_command)
				- sizeof(struct afe_smartamp_get_set_params_t)
				+ length;
	config->hdr.src_port = 0;
	config->hdr.dest_port = 0;
	config->hdr.token = index;
	config->hdr.opcode = AFE_PORT_CMD_SET_PARAM_V2;

	//param
	config->param.port_id = q6audio_get_port_id(port_id);
	config->param.payload_size = sizeof(struct afe_smartamp_config_command)
					- sizeof(struct apr_hdr)
					- sizeof(struct afe_port_cmd_set_param_v2)
					- sizeof(struct afe_smartamp_get_set_params_t)
					+ length;

	//data
	config->pdata.module_id = module_id;
	config->pdata.param_id = param_id;
	config->pdata.param_size = length; //should be same as
					/*
					sizeof(struct afe_smartamp_config_command)
					- sizeof(struct apr_hdr)
					- sizeof(struct afe_port_cmd_set_param_v2)
					- sizeof(struct afe_port_param_data_v2);
					*/

	//access payload pointer
	cfg += (size - length);
	memcpy(cfg, data, length);
	atomic_set(&this_afe.state, 1);
	ret = apr_send_pkt(this_afe.apr, (uint32_t *) config);

	if (ret < 0) {
		pr_err("[TI-SmartPA %s]: Setting param for port %d param[0x%x]failed\n",
		       __func__, port_id, param_id);
		goto fail_cmd;
	}

	ret = wait_event_timeout(this_afe.wait[index],
			(atomic_read(&this_afe.state) == 0),
			msecs_to_jiffies(TIMEOUT_MS*10));
	if (!ret) {
		pr_err("[TI-SmartPA %s]: wait_event timeout\n", __func__);
		ret = -EINVAL;
		goto fail_cmd;
	}
	if (atomic_read(&this_afe.status) != 0) {
		pr_err("[TI-SmartPA %s]: config cmd failed\n", __func__);
		ret = -EINVAL;
		goto fail_cmd;
	}
	ret = 0;

fail_cmd:
	pr_debug("[TI-SmartPA %s]: config->pdata.param_id %x status %d\n",
	__func__, config->pdata.param_id, ret);

	kfree(config);

	return ret;
}
EXPORT_SYMBOL(afe_tas_smartamp_set_calib_data);
#endif /* INSTANCE_ID_0 */
#endif /*CONFIG_TAS25XX_ALGO*/

int afe_pseudo_port_stop_nowait(u16 port_id)
{
	int ret = 0;
	struct afe_pseudoport_stop_command stop;
	int index = 0;

	pr_debug("%s: port_id = 0x%x\n", __func__, port_id);

	if (this_afe.apr == NULL) {
		pr_err("%s: AFE is already closed\n", __func__);
		return -EINVAL;
	}
	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		return -EINVAL;
	}
	ret = q6audio_validate_port(port_id);
	if (ret < 0) {
		pr_err("%s: Invalid port 0x%x ret %d",
			__func__, port_id, ret);
		return -EINVAL;
	}

	stop.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	stop.hdr.pkt_size = sizeof(stop);
	stop.hdr.src_port = 0;
	stop.hdr.dest_port = 0;
	stop.hdr.token = 0;
	stop.hdr.opcode = AFE_PSEUDOPORT_CMD_STOP;
	stop.port_id = port_id;
	stop.reserved = 0;
	stop.hdr.token = index;

	ret = afe_apr_send_pkt(&stop, NULL);
	if (ret)
		pr_err("%s: AFE close failed %d\n", __func__, ret);

	return ret;
}

int afe_port_group_set_param(u16 group_id,
	union afe_port_group_config *afe_group_config)
{
	struct param_hdr_v3 param_hdr;
	int cfg_type;
	int ret;

	if (!afe_group_config) {
		pr_err("%s: Error, no configuration data\n", __func__);
		return -EINVAL;
	}

	pr_debug("%s: group id: 0x%x\n", __func__, group_id);

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

	ret = afe_q6_interface_prepare();
	if (ret != 0) {
		pr_err("%s: Q6 interface prepare failed %d\n", __func__, ret);
		return ret;
	}

	switch (group_id) {
	case AFE_GROUP_DEVICE_ID_PRIMARY_TDM_RX:
	case AFE_GROUP_DEVICE_ID_PRIMARY_TDM_TX:
	case AFE_GROUP_DEVICE_ID_SECONDARY_TDM_RX:
	case AFE_GROUP_DEVICE_ID_SECONDARY_TDM_TX:
	case AFE_GROUP_DEVICE_ID_TERTIARY_TDM_RX:
	case AFE_GROUP_DEVICE_ID_TERTIARY_TDM_TX:
	case AFE_GROUP_DEVICE_ID_QUATERNARY_TDM_RX:
	case AFE_GROUP_DEVICE_ID_QUATERNARY_TDM_TX:
	case AFE_GROUP_DEVICE_ID_QUINARY_TDM_RX:
	case AFE_GROUP_DEVICE_ID_QUINARY_TDM_TX:
	case AFE_GROUP_DEVICE_ID_SENARY_TDM_RX:
	case AFE_GROUP_DEVICE_ID_SENARY_TDM_TX:
		cfg_type = AFE_PARAM_ID_GROUP_DEVICE_TDM_CONFIG;
		break;
	default:
		pr_err("%s: Invalid group id 0x%x\n", __func__, group_id);
		return -EINVAL;
	}

	param_hdr.module_id = AFE_MODULE_GROUP_DEVICE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = cfg_type;
	param_hdr.param_size = sizeof(union afe_port_group_config);

	ret = q6afe_svc_pack_and_set_param_in_band(IDX_GLOBAL_CFG, param_hdr,
						   (u8 *) afe_group_config);
	if (ret)
		pr_err("%s: AFE_PARAM_ID_GROUP_DEVICE_CFG failed %d\n",
			__func__, ret);

	return ret;
}

/**
 * afe_port_tdm_lane_config -
 * to configure group TDM lane mask with specified configuration
 *
 * @group_id: AFE group id number
 * @lane_cfg: TDM lane mask configutation
 *
 * Returns 0 on success or error value on failure.
 */
static int afe_port_tdm_lane_config(u16 group_id,
	struct afe_param_id_tdm_lane_cfg *lane_cfg)
{
	struct param_hdr_v3 param_hdr;
	int ret = 0;

	if (lane_cfg == NULL ||
		lane_cfg->lane_mask == AFE_LANE_MASK_INVALID) {
		pr_debug("%s: lane cfg not supported for group id: 0x%x\n",
			__func__, group_id);
		return ret;
	}

	pr_debug("%s: group id: 0x%x lane mask 0x%x\n", __func__,
		group_id, lane_cfg->lane_mask);

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

	ret = afe_q6_interface_prepare();
	if (ret != 0) {
		pr_err("%s: Q6 interface prepare failed %d\n", __func__, ret);
		return ret;
	}

	param_hdr.module_id = AFE_MODULE_GROUP_DEVICE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_TDM_LANE_CONFIG;
	param_hdr.param_size = sizeof(struct afe_param_id_tdm_lane_cfg);

	ret = q6afe_svc_pack_and_set_param_in_band(IDX_GLOBAL_CFG, param_hdr,
						   (u8 *)lane_cfg);
	if (ret)
		pr_err("%s: AFE_PARAM_ID_TDM_LANE_CONFIG failed %d\n",
			__func__, ret);

	return ret;
}

/**
 * afe_port_group_enable -
 *         command to enable AFE port group
 *
 * @group_id: group ID for AFE port group
 * @afe_group_config: config for AFE group
 * @enable: flag to indicate enable or disable
 * @lane_cfg: TDM lane mask configutation
 *
 * Returns 0 on success or error on failure
 */
int afe_port_group_enable(u16 group_id,
	union afe_port_group_config *afe_group_config,
	u16 enable,
	struct afe_param_id_tdm_lane_cfg *lane_cfg)
{
	struct afe_group_device_enable group_enable;
	struct param_hdr_v3 param_hdr;
	int ret;

	pr_debug("%s: group id: 0x%x enable: %d\n", __func__,
		group_id, enable);

	memset(&group_enable, 0, sizeof(group_enable));
	memset(&param_hdr, 0, sizeof(param_hdr));

	ret = afe_q6_interface_prepare();
	if (ret != 0) {
		pr_err("%s: Q6 interface prepare failed %d\n", __func__, ret);
		return ret;
	}

	if (enable) {
		ret = afe_port_group_set_param(group_id, afe_group_config);
		if (ret < 0) {
			pr_err("%s: afe send failed %d\n", __func__, ret);
			return ret;
		}
		ret = afe_port_tdm_lane_config(group_id, lane_cfg);
		if (ret < 0) {
			pr_err("%s: afe send lane config failed %d\n",
				__func__, ret);
			return ret;
		}
	}

	param_hdr.module_id = AFE_MODULE_GROUP_DEVICE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_GROUP_DEVICE_ENABLE;
	param_hdr.param_size = sizeof(struct afe_group_device_enable);
	group_enable.group_id = group_id;
	group_enable.enable = enable;

	ret = q6afe_svc_pack_and_set_param_in_band(IDX_GLOBAL_CFG, param_hdr,
						   (u8 *) &group_enable);
	if (ret)
		pr_err("%s: AFE_PARAM_ID_GROUP_DEVICE_ENABLE failed %d\n",
			__func__, ret);

	return ret;
}
EXPORT_SYMBOL(afe_port_group_enable);

int afe_stop_pseudo_port(u16 port_id)
{
	int ret = 0;
	struct afe_pseudoport_stop_command stop;
	int index = 0;

	pr_debug("%s: port_id = 0x%x\n", __func__, port_id);

	if (this_afe.apr == NULL) {
		pr_err("%s: AFE is already closed\n", __func__);
		return -EINVAL;
	}

	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		return -EINVAL;
	}
	ret = q6audio_validate_port(port_id);
	if (ret < 0) {
		pr_err("%s: Invalid port 0x%x ret %d\n",
			__func__, port_id, ret);
		return -EINVAL;
	}

	stop.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	stop.hdr.pkt_size = sizeof(stop);
	stop.hdr.src_port = 0;
	stop.hdr.dest_port = 0;
	stop.hdr.token = 0;
	stop.hdr.opcode = AFE_PSEUDOPORT_CMD_STOP;
	stop.port_id = port_id;
	stop.reserved = 0;
	stop.hdr.token = index;

	ret = afe_apr_send_pkt(&stop, &this_afe.wait[index]);
	if (ret)
		pr_err("%s: AFE close failed %d\n", __func__, ret);

	return ret;
}

/**
 * afe_req_mmap_handle -
 *         Retrieve AFE memory map handle
 *
 * @ac: AFE audio client
 *
 * Returns memory map handle
 */
uint32_t afe_req_mmap_handle(struct afe_audio_client *ac)
{
	return ac->mem_map_handle;
}
EXPORT_SYMBOL(afe_req_mmap_handle);

/**
 * q6afe_audio_client_alloc -
 *         Assign new AFE audio client
 *
 * @priv: privata data to hold for audio client
 *
 * Returns ac pointer on success or NULL on failure
 */
struct afe_audio_client *q6afe_audio_client_alloc(void *priv)
{
	struct afe_audio_client *ac;
	int lcnt = 0;

	ac = kzalloc(sizeof(struct afe_audio_client), GFP_KERNEL);
	if (!ac)
		return NULL;

	ac->priv = priv;

	init_waitqueue_head(&ac->cmd_wait);
	INIT_LIST_HEAD(&ac->port[0].mem_map_handle);
	INIT_LIST_HEAD(&ac->port[1].mem_map_handle);
	pr_debug("%s: mem_map_handle list init'ed\n", __func__);
	mutex_init(&ac->cmd_lock);
	for (lcnt = 0; lcnt <= OUT; lcnt++) {
		mutex_init(&ac->port[lcnt].lock);
		spin_lock_init(&ac->port[lcnt].dsp_lock);
	}
	atomic_set(&ac->cmd_state, 0);

	return ac;
}
EXPORT_SYMBOL(q6afe_audio_client_alloc);

/**
 * q6afe_audio_client_buf_alloc_contiguous -
 *         Allocate contiguous shared buffers
 *
 * @dir: RX or TX direction of AFE port
 * @ac: AFE audio client handle
 * @bufsz: size of each shared buffer
 * @bufcnt: number of buffers
 *
 * Returns 0 on success or error on failure
 */
int q6afe_audio_client_buf_alloc_contiguous(unsigned int dir,
			struct afe_audio_client *ac,
			unsigned int bufsz,
			unsigned int bufcnt)
{
	int cnt = 0;
	int rc = 0;
	struct afe_audio_buffer *buf;
	size_t len;

	if (!(ac) || ((dir != IN) && (dir != OUT))) {
		pr_err("%s: ac %pK dir %d\n", __func__, ac, dir);
		return -EINVAL;
	}

	pr_debug("%s: bufsz[%d]bufcnt[%d]\n",
			__func__,
			bufsz, bufcnt);

	if (ac->port[dir].buf) {
		pr_debug("%s: buffer already allocated\n", __func__);
		return 0;
	}
	mutex_lock(&ac->cmd_lock);
	buf = kzalloc(((sizeof(struct afe_audio_buffer))*bufcnt),
			GFP_KERNEL);

	if (!buf) {
		pr_err("%s: null buf\n", __func__);
		mutex_unlock(&ac->cmd_lock);
		goto fail;
	}

	ac->port[dir].buf = buf;

	rc = msm_audio_ion_alloc(&buf[0].dma_buf,
				bufsz * bufcnt,
				&buf[0].phys, &len,
				&buf[0].data);
	if (rc) {
		pr_err("%s: audio ION alloc failed, rc = %d\n",
			__func__, rc);
		mutex_unlock(&ac->cmd_lock);
		goto fail;
	}

	buf[0].used = dir ^ 1;
	buf[0].size = bufsz;
	buf[0].actual_size = bufsz;
	cnt = 1;
	while (cnt < bufcnt) {
		if (bufsz > 0) {
			buf[cnt].data =  buf[0].data + (cnt * bufsz);
			buf[cnt].phys =  buf[0].phys + (cnt * bufsz);
			if (!buf[cnt].data) {
				pr_err("%s: Buf alloc failed\n",
							__func__);
				mutex_unlock(&ac->cmd_lock);
				goto fail;
			}
			buf[cnt].used = dir ^ 1;
			buf[cnt].size = bufsz;
			buf[cnt].actual_size = bufsz;
			pr_debug("%s:  data[%pK]phys[%pK][%pK]\n", __func__,
				   buf[cnt].data,
				   &buf[cnt].phys,
				   &buf[cnt].phys);
		}
		cnt++;
	}
	ac->port[dir].max_buf_cnt = cnt;
	mutex_unlock(&ac->cmd_lock);
	return 0;
fail:
	pr_err("%s: jump fail\n", __func__);
	q6afe_audio_client_buf_free_contiguous(dir, ac);
	return -EINVAL;
}
EXPORT_SYMBOL(q6afe_audio_client_buf_alloc_contiguous);

/**
 * afe_memory_map -
 *         command to map shared buffers to AFE
 *
 * @dma_addr_p: DMA physical address
 * @dma_buf_sz: shared DMA buffer size
 * @ac: AFE audio client handle
 *
 * Returns 0 on success or error on failure
 */
int afe_memory_map(phys_addr_t dma_addr_p, u32 dma_buf_sz,
			struct afe_audio_client *ac)
{
	int ret = 0;

	mutex_lock(&this_afe.afe_cmd_lock);
	ac->mem_map_handle = 0;
	ret = afe_cmd_memory_map(dma_addr_p, dma_buf_sz);
	if (ret < 0) {
		pr_err("%s: afe_cmd_memory_map failed %d\n",
			__func__, ret);

		mutex_unlock(&this_afe.afe_cmd_lock);
		return ret;
	}
	ac->mem_map_handle = this_afe.mmap_handle;
	mutex_unlock(&this_afe.afe_cmd_lock);

	return ret;
}
EXPORT_SYMBOL(afe_memory_map);

int afe_cmd_memory_map(phys_addr_t dma_addr_p, u32 dma_buf_sz)
{
	int ret = 0;
	int cmd_size = 0;
	void    *payload = NULL;
	void    *mmap_region_cmd = NULL;
	struct afe_service_cmd_shared_mem_map_regions *mregion = NULL;
	struct  afe_service_shared_map_region_payload *mregion_pl = NULL;
	int index = 0;

	pr_debug("%s:\n", __func__);

	if (this_afe.apr == NULL) {
		this_afe.apr = apr_register("ADSP", "AFE", afe_callback,
					0xFFFFFFFF, &this_afe);
		pr_debug("%s: Register AFE\n", __func__);
		if (this_afe.apr == NULL) {
			pr_err("%s: Unable to register AFE\n", __func__);
			ret = -ENODEV;
			return ret;
		}
		rtac_set_afe_handle(this_afe.apr);
	}
	if (dma_buf_sz % SZ_4K != 0) {
		/*
		 * The memory allocated by msm_audio_ion_alloc is always 4kB
		 * aligned, ADSP expects the size to be 4kB aligned as well
		 * so re-adjusts the  buffer size before passing to ADSP.
		 */
		dma_buf_sz = PAGE_ALIGN(dma_buf_sz);
	}

	cmd_size = sizeof(struct afe_service_cmd_shared_mem_map_regions)
		+ sizeof(struct afe_service_shared_map_region_payload);

	mmap_region_cmd = kzalloc(cmd_size, GFP_KERNEL);
	if (!mmap_region_cmd)
		return -ENOMEM;

	mregion = (struct afe_service_cmd_shared_mem_map_regions *)
							mmap_region_cmd;
	mregion->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	mregion->hdr.pkt_size = cmd_size;
	mregion->hdr.src_port = 0;
	mregion->hdr.dest_port = 0;
	mregion->hdr.token = 0;
	mregion->hdr.opcode = AFE_SERVICE_CMD_SHARED_MEM_MAP_REGIONS;
	mregion->mem_pool_id = ADSP_MEMORY_MAP_SHMEM8_4K_POOL;
	mregion->num_regions = 1;
	mregion->property_flag = 0x00;
	/* Todo */
	index = mregion->hdr.token = IDX_RSVD_2;

	payload = ((u8 *) mmap_region_cmd +
		   sizeof(struct afe_service_cmd_shared_mem_map_regions));

	mregion_pl = (struct afe_service_shared_map_region_payload *)payload;

	mregion_pl->shm_addr_lsw = lower_32_bits(dma_addr_p);
	mregion_pl->shm_addr_msw = msm_audio_populate_upper_32_bits(dma_addr_p);
	mregion_pl->mem_size_bytes = dma_buf_sz;

	pr_debug("%s: dma_addr_p 0x%pK , size %d\n", __func__,
					&dma_addr_p, dma_buf_sz);
	this_afe.mmap_handle = 0;
	ret = afe_apr_send_pkt((uint32_t *) mmap_region_cmd,
			&this_afe.wait[index]);
	kfree(mmap_region_cmd);
	return ret;
}

int afe_cmd_memory_map_nowait(int port_id, phys_addr_t dma_addr_p,
		u32 dma_buf_sz)
{
	int ret = 0;
	int cmd_size = 0;
	void    *payload = NULL;
	void    *mmap_region_cmd = NULL;
	struct afe_service_cmd_shared_mem_map_regions *mregion = NULL;
	struct  afe_service_shared_map_region_payload *mregion_pl = NULL;
	int index = 0;

	pr_debug("%s:\n", __func__);

	if (this_afe.apr == NULL) {
		this_afe.apr = apr_register("ADSP", "AFE", afe_callback,
					0xFFFFFFFF, &this_afe);
		pr_debug("%s: Register AFE\n", __func__);
		if (this_afe.apr == NULL) {
			pr_err("%s: Unable to register AFE\n", __func__);
			ret = -ENODEV;
			return ret;
		}
		rtac_set_afe_handle(this_afe.apr);
	}
	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		return -EINVAL;
	}
	ret = q6audio_validate_port(port_id);
	if (ret < 0) {
		pr_err("%s: Invalid port 0x%x ret %d",
			__func__, port_id, ret);
		return -EINVAL;
	}

	cmd_size = sizeof(struct afe_service_cmd_shared_mem_map_regions)
		+ sizeof(struct afe_service_shared_map_region_payload);

	mmap_region_cmd = kzalloc(cmd_size, GFP_KERNEL);
	if (!mmap_region_cmd)
		return -ENOMEM;

	mregion = (struct afe_service_cmd_shared_mem_map_regions *)
						mmap_region_cmd;
	mregion->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	mregion->hdr.pkt_size = sizeof(mregion);
	mregion->hdr.src_port = 0;
	mregion->hdr.dest_port = 0;
	mregion->hdr.token = 0;
	mregion->hdr.opcode = AFE_SERVICE_CMD_SHARED_MEM_MAP_REGIONS;
	mregion->mem_pool_id = ADSP_MEMORY_MAP_SHMEM8_4K_POOL;
	mregion->num_regions = 1;
	mregion->property_flag = 0x00;

	payload = ((u8 *) mmap_region_cmd +
		sizeof(struct afe_service_cmd_shared_mem_map_regions));
	mregion_pl = (struct afe_service_shared_map_region_payload *)payload;

	mregion_pl->shm_addr_lsw = lower_32_bits(dma_addr_p);
	mregion_pl->shm_addr_msw = msm_audio_populate_upper_32_bits(dma_addr_p);
	mregion_pl->mem_size_bytes = dma_buf_sz;

	ret = afe_apr_send_pkt(mmap_region_cmd, NULL);
	if (ret)
		pr_err("%s: AFE memory map cmd failed %d\n",
		       __func__, ret);
	kfree(mmap_region_cmd);
	return ret;
}

/**
 * q6afe_audio_client_buf_free_contiguous -
 *         frees the shared contiguous memory
 *
 * @dir: RX or TX direction of port
 * @ac: AFE audio client handle
 *
 */
int q6afe_audio_client_buf_free_contiguous(unsigned int dir,
			struct afe_audio_client *ac)
{
	struct afe_audio_port_data *port;
	int cnt = 0;

	mutex_lock(&ac->cmd_lock);
	port = &ac->port[dir];
	if (!port->buf) {
		pr_err("%s: buf is null\n", __func__);
		mutex_unlock(&ac->cmd_lock);
		return 0;
	}
	cnt = port->max_buf_cnt - 1;

	if (port->buf[0].data) {
		pr_debug("%s: data[%pK], phys[%pK], dma_buf[%pK]\n",
			__func__,
			port->buf[0].data,
			&port->buf[0].phys,
			port->buf[0].dma_buf);
		msm_audio_ion_free(port->buf[0].dma_buf);
		port->buf[0].dma_buf = NULL;
	}

	while (cnt >= 0) {
		port->buf[cnt].data = NULL;
		port->buf[cnt].phys = 0;
		cnt--;
	}
	port->max_buf_cnt = 0;
	kfree(port->buf);
	port->buf = NULL;
	mutex_unlock(&ac->cmd_lock);
	return 0;
}
EXPORT_SYMBOL(q6afe_audio_client_buf_free_contiguous);

/**
 * q6afe_audio_client_free -
 *         frees the audio client from AFE
 *
 * @ac: AFE audio client handle
 *
 */
void q6afe_audio_client_free(struct afe_audio_client *ac)
{
	int loopcnt;
	struct afe_audio_port_data *port;

	if (!ac) {
		pr_err("%s: audio client is NULL\n", __func__);
		return;
	}
	for (loopcnt = 0; loopcnt <= OUT; loopcnt++) {
		port = &ac->port[loopcnt];
		if (!port->buf)
			continue;
		pr_debug("%s: loopcnt = %d\n", __func__, loopcnt);
		q6afe_audio_client_buf_free_contiguous(loopcnt, ac);
	}
	kfree(ac);
}
EXPORT_SYMBOL(q6afe_audio_client_free);

/**
 * afe_cmd_memory_unmap -
 *         command to unmap memory for AFE shared buffer
 *
 * @mem_map_handle: memory map handle to be unmapped
 *
 * Returns 0 on success or error on failure
 */
int afe_cmd_memory_unmap(u32 mem_map_handle)
{
	int ret = 0;
	struct afe_service_cmd_shared_mem_unmap_regions mregion;
	int index = 0;

	pr_debug("%s: handle 0x%x\n", __func__, mem_map_handle);

	if (this_afe.apr == NULL) {
		this_afe.apr = apr_register("ADSP", "AFE", afe_callback,
					0xFFFFFFFF, &this_afe);
		pr_debug("%s: Register AFE\n", __func__);
		if (this_afe.apr == NULL) {
			pr_err("%s: Unable to register AFE\n", __func__);
			ret = -ENODEV;
			return ret;
		}
		rtac_set_afe_handle(this_afe.apr);
	}

	mregion.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	mregion.hdr.pkt_size = sizeof(mregion);
	mregion.hdr.src_port = 0;
	mregion.hdr.dest_port = 0;
	mregion.hdr.token = 0;
	mregion.hdr.opcode = AFE_SERVICE_CMD_SHARED_MEM_UNMAP_REGIONS;
	mregion.mem_map_handle = mem_map_handle;

	/* Todo */
	index = mregion.hdr.token = IDX_RSVD_2;

	atomic_set(&this_afe.status, 0);
	ret = afe_apr_send_pkt(&mregion, &this_afe.wait[index]);
	if (ret)
		pr_err("%s: AFE memory unmap cmd failed %d\n",
		       __func__, ret);

	return ret;
}
EXPORT_SYMBOL(afe_cmd_memory_unmap);

int afe_cmd_memory_unmap_nowait(u32 mem_map_handle)
{
	int ret = 0;
	struct afe_service_cmd_shared_mem_unmap_regions mregion;

	pr_debug("%s: handle 0x%x\n", __func__, mem_map_handle);

	if (this_afe.apr == NULL) {
		this_afe.apr = apr_register("ADSP", "AFE", afe_callback,
					0xFFFFFFFF, &this_afe);
		pr_debug("%s: Register AFE\n", __func__);
		if (this_afe.apr == NULL) {
			pr_err("%s: Unable to register AFE\n", __func__);
			ret = -ENODEV;
			return ret;
		}
		rtac_set_afe_handle(this_afe.apr);
	}

	mregion.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	mregion.hdr.pkt_size = sizeof(mregion);
	mregion.hdr.src_port = 0;
	mregion.hdr.dest_port = 0;
	mregion.hdr.token = 0;
	mregion.hdr.opcode = AFE_SERVICE_CMD_SHARED_MEM_UNMAP_REGIONS;
	mregion.mem_map_handle = mem_map_handle;

	ret = afe_apr_send_pkt(&mregion, NULL);
	if (ret)
		pr_err("%s: AFE memory unmap cmd failed %d\n",
			__func__, ret);
	return ret;
}

/**
 * afe_register_get_events -
 *         register for events from proxy port
 *
 * @port_id: Port ID to register events
 * @cb: callback function to invoke for events from proxy port
 * @private_data: private data to sent back in callback fn
 *
 * Returns 0 on success or error on failure
 */
int afe_register_get_events(u16 port_id,
		void (*cb)(uint32_t opcode,
		uint32_t token, uint32_t *payload, void *priv),
		void *private_data)
{
	int ret = 0;
	struct afe_service_cmd_register_rt_port_driver rtproxy;

	pr_debug("%s: port_id: 0x%x\n", __func__, port_id);

	if (this_afe.apr == NULL) {
		this_afe.apr = apr_register("ADSP", "AFE", afe_callback,
					0xFFFFFFFF, &this_afe);
		pr_debug("%s: Register AFE\n", __func__);
		if (this_afe.apr == NULL) {
			pr_err("%s: Unable to register AFE\n", __func__);
			ret = -ENODEV;
			return ret;
		}
		rtac_set_afe_handle(this_afe.apr);
	}
	if ((port_id == RT_PROXY_DAI_002_RX) ||
		(port_id == RT_PROXY_DAI_001_TX)) {
		port_id = VIRTUAL_ID_TO_PORTID(port_id);
	} else {
		pr_err("%s: wrong port id 0x%x\n", __func__, port_id);
		return -EINVAL;
	}

	if (port_id == RT_PROXY_PORT_001_TX) {
		this_afe.tx_cb = cb;
		this_afe.tx_private_data = private_data;
	} else if (port_id == RT_PROXY_PORT_001_RX) {
		this_afe.rx_cb = cb;
		this_afe.rx_private_data = private_data;
	}

	rtproxy.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	rtproxy.hdr.pkt_size = sizeof(rtproxy);
	rtproxy.hdr.src_port = 1;
	rtproxy.hdr.dest_port = 1;
	rtproxy.hdr.opcode = AFE_SERVICE_CMD_REGISTER_RT_PORT_DRIVER;
	rtproxy.port_id = port_id;
	rtproxy.reserved = 0;

	ret = afe_apr_send_pkt(&rtproxy, NULL);
	if (ret)
		pr_err("%s: AFE  reg. rtproxy_event failed %d\n",
			   __func__, ret);
	return ret;
}
EXPORT_SYMBOL(afe_register_get_events);

/**
 * afe_unregister_get_events -
 *         unregister for events from proxy port
 *
 * @port_id: Port ID to unregister events
 *
 * Returns 0 on success or error on failure
 */
int afe_unregister_get_events(u16 port_id)
{
	int ret = 0;
	struct afe_service_cmd_unregister_rt_port_driver rtproxy;
	int index = 0;

	pr_debug("%s:\n", __func__);

	if (this_afe.apr == NULL) {
		this_afe.apr = apr_register("ADSP", "AFE", afe_callback,
					0xFFFFFFFF, &this_afe);
		pr_debug("%s: Register AFE\n", __func__);
		if (this_afe.apr == NULL) {
			pr_err("%s: Unable to register AFE\n", __func__);
			ret = -ENODEV;
			return ret;
		}
		rtac_set_afe_handle(this_afe.apr);
	}

	if ((port_id == RT_PROXY_DAI_002_RX) ||
		(port_id == RT_PROXY_DAI_001_TX)) {
		port_id = VIRTUAL_ID_TO_PORTID(port_id);
	} else {
		pr_err("%s: wrong port id 0x%x\n", __func__, port_id);
		return -EINVAL;
	}

	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		return -EINVAL;
	}
	ret = q6audio_validate_port(port_id);
	if (ret < 0) {
		pr_err("%s: Invalid port 0x%x ret %d", __func__, port_id, ret);
		return -EINVAL;
	}

	rtproxy.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	rtproxy.hdr.pkt_size = sizeof(rtproxy);
	rtproxy.hdr.src_port = 0;
	rtproxy.hdr.dest_port = 0;
	rtproxy.hdr.token = 0;
	rtproxy.hdr.opcode = AFE_SERVICE_CMD_UNREGISTER_RT_PORT_DRIVER;
	rtproxy.port_id = port_id;
	rtproxy.reserved = 0;

	rtproxy.hdr.token = index;

	if (port_id == RT_PROXY_PORT_001_TX) {
		this_afe.tx_cb = NULL;
		this_afe.tx_private_data = NULL;
	} else if (port_id == RT_PROXY_PORT_001_RX) {
		this_afe.rx_cb = NULL;
		this_afe.rx_private_data = NULL;
	}

	ret = afe_apr_send_pkt(&rtproxy, &this_afe.wait[index]);
	if (ret)
		pr_err("%s: AFE enable Unreg. rtproxy_event failed %d\n",
			   __func__, ret);
	return ret;
}
EXPORT_SYMBOL(afe_unregister_get_events);

/**
 * afe_rt_proxy_port_write -
 *         command for AFE RT proxy port write
 *
 * @buf_addr_p: Physical buffer address with
 *           playback data to proxy port
 * @mem_map_handle: memory map handle of write buffer
 * @bytes: number of bytes to write
 *
 * Returns 0 on success or error on failure
 */
int afe_rt_proxy_port_write(phys_addr_t buf_addr_p,
		u32 mem_map_handle, int bytes)
{
	int ret = 0;
	struct afe_port_data_cmd_rt_proxy_port_write_v2 afecmd_wr;

	if (this_afe.apr == NULL) {
		pr_err("%s: register to AFE is not done\n", __func__);
		ret = -ENODEV;
		return ret;
	}
	pr_debug("%s: buf_addr_p = 0x%pK bytes = %d\n", __func__,
						&buf_addr_p, bytes);

	afecmd_wr.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	afecmd_wr.hdr.pkt_size = sizeof(afecmd_wr);
	afecmd_wr.hdr.src_port = 0;
	afecmd_wr.hdr.dest_port = 0;
	afecmd_wr.hdr.token = 0;
	afecmd_wr.hdr.opcode = AFE_PORT_DATA_CMD_RT_PROXY_PORT_WRITE_V2;
	afecmd_wr.port_id = RT_PROXY_PORT_001_TX;
	afecmd_wr.buffer_address_lsw = lower_32_bits(buf_addr_p);
	afecmd_wr.buffer_address_msw =
			msm_audio_populate_upper_32_bits(buf_addr_p);
	afecmd_wr.mem_map_handle = mem_map_handle;
	afecmd_wr.available_bytes = bytes;
	afecmd_wr.reserved = 0;

	/*
	 * Do not call afe_apr_send_pkt() here as it acquires
	 * a mutex lock inside and this function gets called in
	 * interrupt context leading to scheduler crash
	 */
	atomic_set(&this_afe.status, 0);
	ret = apr_send_pkt(this_afe.apr, (uint32_t *) &afecmd_wr);
	if (ret < 0) {
		pr_err("%s: AFE rtproxy write to port 0x%x failed %d\n",
			__func__, afecmd_wr.port_id, ret);
		ret = -EINVAL;
	}

	return ret;

}
EXPORT_SYMBOL(afe_rt_proxy_port_write);

/**
 * afe_rt_proxy_port_read -
 *         command for AFE RT proxy port read
 *
 * @buf_addr_p: Physical buffer address to fill read data
 * @mem_map_handle: memory map handle for buffer read
 * @bytes: number of bytes to read
 *
 * Returns 0 on success or error on failure
 */
int afe_rt_proxy_port_read(phys_addr_t buf_addr_p,
		u32 mem_map_handle, int bytes)
{
	int ret = 0;
	struct afe_port_data_cmd_rt_proxy_port_read_v2 afecmd_rd;

	if (this_afe.apr == NULL) {
		pr_err("%s: register to AFE is not done\n", __func__);
		ret = -ENODEV;
		return ret;
	}
	pr_debug("%s: buf_addr_p = 0x%pK bytes = %d\n", __func__,
						&buf_addr_p, bytes);

	afecmd_rd.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	afecmd_rd.hdr.pkt_size = sizeof(afecmd_rd);
	afecmd_rd.hdr.src_port = 0;
	afecmd_rd.hdr.dest_port = 0;
	afecmd_rd.hdr.token = 0;
	afecmd_rd.hdr.opcode = AFE_PORT_DATA_CMD_RT_PROXY_PORT_READ_V2;
	afecmd_rd.port_id = RT_PROXY_PORT_001_RX;
	afecmd_rd.buffer_address_lsw = lower_32_bits(buf_addr_p);
	afecmd_rd.buffer_address_msw =
				msm_audio_populate_upper_32_bits(buf_addr_p);
	afecmd_rd.available_bytes = bytes;
	afecmd_rd.mem_map_handle = mem_map_handle;

	/*
	 * Do not call afe_apr_send_pkt() here as it acquires
	 * a mutex lock inside and this function gets called in
	 * interrupt context leading to scheduler crash
	 */
	atomic_set(&this_afe.status, 0);
	ret = apr_send_pkt(this_afe.apr, (uint32_t *) &afecmd_rd);
	if (ret < 0) {
		pr_err("%s: AFE rtproxy read  cmd to port 0x%x failed %d\n",
			__func__, afecmd_rd.port_id, ret);
		ret = -EINVAL;
	}

	return ret;
}
EXPORT_SYMBOL(afe_rt_proxy_port_read);

#ifdef CONFIG_DEBUG_FS
static struct dentry *debugfs_afelb;
static struct dentry *debugfs_afelb_gain;

static int afe_debug_open(struct inode *inode, struct file *file)
{
	file->private_data = inode->i_private;
	pr_info("%s: debug intf %s\n", __func__, (char *) file->private_data);
	return 0;
}

static int afe_get_parameters(char *buf, long int *param1, int num_of_par)
{
	char *token;
	int base, cnt;

	token = strsep(&buf, " ");

	for (cnt = 0; cnt < num_of_par; cnt++) {
		if (token != NULL) {
			if ((token[1] == 'x') || (token[1] == 'X'))
				base = 16;
			else
				base = 10;

			if (kstrtoul(token, base, &param1[cnt]) != 0) {
				pr_err("%s: kstrtoul failed\n",
					__func__);
				return -EINVAL;
			}

			token = strsep(&buf, " ");
		} else {
			pr_err("%s: token NULL\n", __func__);
			return -EINVAL;
		}
	}
	return 0;
}
#define AFE_LOOPBACK_ON (1)
#define AFE_LOOPBACK_OFF (0)
static ssize_t afe_debug_write(struct file *filp,
	const char __user *ubuf, size_t cnt, loff_t *ppos)
{
	char *lb_str = filp->private_data;
	char lbuf[32];
	int rc;
	unsigned long param[5];

	if (cnt > sizeof(lbuf) - 1) {
		pr_err("%s: cnt %zd size %zd\n", __func__, cnt, sizeof(lbuf)-1);
		return -EINVAL;
	}

	rc = copy_from_user(lbuf, ubuf, cnt);
	if (rc) {
		pr_err("%s: copy from user failed %d\n", __func__, rc);
		return -EFAULT;
	}

	lbuf[cnt] = '\0';

	if (!strcmp(lb_str, "afe_loopback")) {
		rc = afe_get_parameters(lbuf, param, 3);
		if (!rc) {
			pr_info("%s: %lu %lu %lu\n", lb_str, param[0], param[1],
				param[2]);

			if ((param[0] != AFE_LOOPBACK_ON) && (param[0] !=
				AFE_LOOPBACK_OFF)) {
				pr_err("%s: Error, parameter 0 incorrect\n",
					__func__);
				rc = -EINVAL;
				goto afe_error;
			}
			if ((q6audio_validate_port(param[1]) < 0) ||
			    (q6audio_validate_port(param[2])) < 0) {
				pr_err("%s: Error, invalid afe port\n",
					__func__);
			}
			if (this_afe.apr == NULL) {
				pr_err("%s: Error, AFE not opened\n", __func__);
				rc = -EINVAL;
			} else {
				rc = afe_loopback(param[0], param[1], param[2]);
			}
		} else {
			pr_err("%s: Error, invalid parameters\n", __func__);
			rc = -EINVAL;
		}

	} else if (!strcmp(lb_str, "afe_loopback_gain")) {
		rc = afe_get_parameters(lbuf, param, 2);
		if (!rc) {
			pr_info("%s: %s %lu %lu\n",
				__func__, lb_str, param[0], param[1]);

			rc = q6audio_validate_port(param[0]);
			if (rc < 0) {
				pr_err("%s: Error, invalid afe port %d %lu\n",
					__func__, rc, param[0]);
				rc = -EINVAL;
				goto afe_error;
			}

			if (param[1] > 100) {
				pr_err("%s: Error, volume should be 0 to 100 percentage param = %lu\n",
					__func__, param[1]);
				rc = -EINVAL;
				goto afe_error;
			}

			param[1] = (Q6AFE_MAX_VOLUME * param[1]) / 100;

			if (this_afe.apr == NULL) {
				pr_err("%s: Error, AFE not opened\n", __func__);
				rc = -EINVAL;
			} else {
				rc = afe_loopback_gain(param[0], param[1]);
			}
		} else {
			pr_err("%s: Error, invalid parameters\n", __func__);
			rc = -EINVAL;
		}
	}

afe_error:
	if (rc == 0)
		rc = cnt;
	else
		pr_err("%s: rc = %d\n", __func__, rc);

	return rc;
}

static const struct file_operations afe_debug_fops = {
	.open = afe_debug_open,
	.write = afe_debug_write
};

static void config_debug_fs_init(void)
{
	debugfs_afelb = debugfs_create_file("afe_loopback",
	0664, NULL, (void *) "afe_loopback",
	&afe_debug_fops);

	debugfs_afelb_gain = debugfs_create_file("afe_loopback_gain",
	0664, NULL, (void *) "afe_loopback_gain",
	&afe_debug_fops);
}
static void config_debug_fs_exit(void)
{
	debugfs_remove(debugfs_afelb);
	debugfs_remove(debugfs_afelb_gain);
}
#else
static void config_debug_fs_init(void)
{
}
static void config_debug_fs_exit(void)
{
}
#endif

/**
 * afe_set_dtmf_gen_rx_portid -
 *         Set port_id for DTMF tone generation
 *
 * @port_id: AFE port id
 * @set: set or reset port id value for dtmf gen
 *
 */
void afe_set_dtmf_gen_rx_portid(u16 port_id, int set)
{
	if (set)
		this_afe.dtmf_gen_rx_portid = port_id;
	else if (this_afe.dtmf_gen_rx_portid == port_id)
		this_afe.dtmf_gen_rx_portid = -1;
}
EXPORT_SYMBOL(afe_set_dtmf_gen_rx_portid);

/**
 * afe_dtmf_generate_rx - command to generate AFE DTMF RX
 *
 * @duration_in_ms: Duration in ms for dtmf tone
 * @high_freq: Higher frequency for dtmf
 * @low_freq: lower frequency for dtmf
 * @gain: Gain value for DTMF tone
 *
 * Returns 0 on success, appropriate error code otherwise
 */
int afe_dtmf_generate_rx(int64_t duration_in_ms,
			 uint16_t high_freq,
			 uint16_t low_freq, uint16_t gain)
{
	int ret = 0;
	int index = 0;
	struct afe_dtmf_generation_command cmd_dtmf;

	pr_debug("%s: DTMF AFE Gen\n", __func__);

	if (afe_validate_port(this_afe.dtmf_gen_rx_portid) < 0) {
		pr_err("%s: Failed : Invalid Port id = 0x%x\n",
		       __func__, this_afe.dtmf_gen_rx_portid);
		ret = -EINVAL;
		goto fail_cmd;
	}

	if (this_afe.apr == NULL) {
		this_afe.apr = apr_register("ADSP", "AFE", afe_callback,
					    0xFFFFFFFF, &this_afe);
		pr_debug("%s: Register AFE\n", __func__);
		if (this_afe.apr == NULL) {
			pr_err("%s: Unable to register AFE\n", __func__);
			ret = -ENODEV;
			return ret;
		}
		rtac_set_afe_handle(this_afe.apr);
	}

	pr_debug("%s: dur=%lld: hfreq=%d lfreq=%d gain=%d portid=0x%x\n",
		__func__,
		duration_in_ms, high_freq, low_freq, gain,
		this_afe.dtmf_gen_rx_portid);

	cmd_dtmf.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	cmd_dtmf.hdr.pkt_size = sizeof(cmd_dtmf);
	cmd_dtmf.hdr.src_port = 0;
	cmd_dtmf.hdr.dest_port = 0;
	cmd_dtmf.hdr.token = 0;
	cmd_dtmf.hdr.opcode = AFE_PORTS_CMD_DTMF_CTL;
	cmd_dtmf.duration_in_ms = duration_in_ms;
	cmd_dtmf.high_freq = high_freq;
	cmd_dtmf.low_freq = low_freq;
	cmd_dtmf.gain = gain;
	cmd_dtmf.num_ports = 1;
	cmd_dtmf.port_ids = q6audio_get_port_id(this_afe.dtmf_gen_rx_portid);

	index = q6audio_get_port_index(this_afe.dtmf_gen_rx_portid);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		ret = -EINVAL;
		goto fail_cmd;
	}
	ret = afe_apr_send_pkt((uint32_t *) &cmd_dtmf,
			&this_afe.wait[index]);
	return ret;
fail_cmd:
	pr_err("%s: failed %d\n", __func__, ret);
	return ret;
}
EXPORT_SYMBOL(afe_dtmf_generate_rx);

static int afe_sidetone_iir(u16 tx_port_id)
{
	int ret;
	uint16_t size = 0;
	int cal_index = AFE_SIDETONE_IIR_CAL;
	int iir_pregain = 0;
	int iir_num_biquad_stages = 0;
	int iir_enable;
	struct cal_block_data *cal_block;
	int mid;
	struct afe_mod_enable_param enable;
	struct afe_sidetone_iir_filter_config_params filter_data;
	struct param_hdr_v3 param_hdr;
	u8 *packed_param_data = NULL;
	u32 packed_param_size = 0;
	u32 single_param_size = 0;
	struct audio_cal_info_sidetone_iir *st_iir_cal_info = NULL;

	memset(&enable, 0, sizeof(enable));
	memset(&filter_data, 0, sizeof(filter_data));
	memset(&param_hdr, 0, sizeof(param_hdr));

	if (this_afe.cal_data[cal_index] == NULL) {
		pr_err("%s: cal data is NULL\n", __func__);
		ret = -EINVAL;
		goto done;
	}
	mutex_lock(&this_afe.cal_data[cal_index]->lock);
	cal_block = cal_utils_get_only_cal_block(this_afe.cal_data[cal_index]);
	if (cal_block == NULL || cal_utils_is_cal_stale(cal_block)) {
		pr_err("%s: cal_block not found\n ", __func__);
		mutex_unlock(&this_afe.cal_data[cal_index]->lock);
		ret = -EINVAL;
		goto done;
	}

	/* Cache data from cal block while inside lock to reduce locked time */
	st_iir_cal_info =
		(struct audio_cal_info_sidetone_iir *) cal_block->cal_info;
	iir_pregain = st_iir_cal_info->pregain;
	iir_enable = st_iir_cal_info->iir_enable;
	iir_num_biquad_stages = st_iir_cal_info->num_biquad_stages;
	mid = st_iir_cal_info->mid;

	/*
	 * calculate the actual size of payload based on no of stages
	 * enabled in calibration
	 */
	size = (MAX_SIDETONE_IIR_DATA_SIZE / MAX_NO_IIR_FILTER_STAGE) *
		iir_num_biquad_stages;
	/*
	 * For an odd number of stages, 2 bytes of padding are
	 * required at the end of the payload.
	 */
	if (iir_num_biquad_stages % 2) {
		pr_debug("%s: adding 2 to size:%d\n", __func__, size);
		size = size + 2;
	}
	memcpy(&filter_data.iir_config, &st_iir_cal_info->iir_config, size);
	mutex_unlock(&this_afe.cal_data[cal_index]->lock);

	packed_param_size =
		sizeof(param_hdr) * 2 + sizeof(enable) + sizeof(filter_data);
	packed_param_data = kzalloc(packed_param_size, GFP_KERNEL);
	if (!packed_param_data)
		return -ENOMEM;
	packed_param_size = 0;

	/*
	 * Set IIR enable params
	 */
	param_hdr.module_id = mid;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_ENABLE;
	param_hdr.param_size = sizeof(enable);
	enable.enable = iir_enable;
	ret = q6common_pack_pp_params(packed_param_data, &param_hdr,
				      (u8 *) &enable, &single_param_size);
	if (ret) {
		pr_err("%s: Failed to pack param data, error %d\n", __func__,
		       ret);
		goto done;
	}
	packed_param_size += single_param_size;

	/*
	 * Set IIR filter config params
	 */
	param_hdr.module_id = mid;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_SIDETONE_IIR_FILTER_CONFIG;
	param_hdr.param_size = sizeof(filter_data.num_biquad_stages) +
			       sizeof(filter_data.pregain) + size;
	filter_data.num_biquad_stages = iir_num_biquad_stages;
	filter_data.pregain = iir_pregain;
	ret = q6common_pack_pp_params(packed_param_data + packed_param_size,
				      &param_hdr, (u8 *) &filter_data,
				      &single_param_size);
	if (ret) {
		pr_err("%s: Failed to pack param data, error %d\n", __func__,
		       ret);
		goto done;
	}
	packed_param_size += single_param_size;

	pr_debug("%s: tx(0x%x)mid(0x%x)iir_en(%d)stg(%d)gain(0x%x)size(%d)\n",
		 __func__, tx_port_id, mid, enable.enable,
		 filter_data.num_biquad_stages, filter_data.pregain,
		 param_hdr.param_size);

	ret = q6afe_set_params(tx_port_id, q6audio_get_port_index(tx_port_id),
			       NULL, packed_param_data, packed_param_size);
	if (ret)
		pr_err("%s: AFE sidetone failed for tx_port(0x%x)\n",
			 __func__, tx_port_id);

done:
	kfree(packed_param_data);
	return ret;
}

static int afe_sidetone(u16 tx_port_id, u16 rx_port_id, bool enable)
{
	int ret;
	int cal_index = AFE_SIDETONE_CAL;
	int sidetone_gain;
	int sidetone_enable;
	struct cal_block_data *cal_block;
	int mid = 0;
	struct afe_loopback_sidetone_gain gain_data;
	struct loopback_cfg_data cfg_data;
	struct param_hdr_v3 param_hdr;
	u8 *packed_param_data = NULL;
	u32 packed_param_size = 0;
	u32 single_param_size = 0;
	struct audio_cal_info_sidetone *st_cal_info = NULL;

	if (this_afe.cal_data[cal_index] == NULL) {
		pr_err("%s: cal data is NULL\n", __func__);
		ret = -EINVAL;
		goto done;
	}

	memset(&gain_data, 0, sizeof(gain_data));
	memset(&cfg_data, 0, sizeof(cfg_data));
	memset(&param_hdr, 0, sizeof(param_hdr));

	packed_param_size =
		sizeof(param_hdr) * 2 + sizeof(gain_data) + sizeof(cfg_data);
	packed_param_data = kzalloc(packed_param_size, GFP_KERNEL);
	if (!packed_param_data)
		return -ENOMEM;
	packed_param_size = 0;

	mutex_lock(&this_afe.cal_data[cal_index]->lock);
	cal_block = cal_utils_get_only_cal_block(this_afe.cal_data[cal_index]);
	if (cal_block == NULL || cal_utils_is_cal_stale(cal_block)) {
		pr_err("%s: cal_block not found\n", __func__);
		mutex_unlock(&this_afe.cal_data[cal_index]->lock);
		ret = -EINVAL;
		goto done;
	}

	/* Cache data from cal block while inside lock to reduce locked time */
	st_cal_info = (struct audio_cal_info_sidetone *) cal_block->cal_info;
	sidetone_gain = st_cal_info->gain;
	sidetone_enable = st_cal_info->enable;
	mid = st_cal_info->mid;
	mutex_unlock(&this_afe.cal_data[cal_index]->lock);

	/* Set gain data. */
	param_hdr.module_id = AFE_MODULE_LOOPBACK;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_LOOPBACK_GAIN_PER_PATH;
	param_hdr.param_size = sizeof(struct afe_loopback_sidetone_gain);
	gain_data.rx_port_id = rx_port_id;
	gain_data.gain = sidetone_gain;
	ret = q6common_pack_pp_params(packed_param_data, &param_hdr,
				      (u8 *) &gain_data, &single_param_size);
	if (ret) {
		pr_err("%s: Failed to pack param data, error %d\n", __func__,
		       ret);
		goto done;
	}
	packed_param_size += single_param_size;

	/* Set configuration data. */
	param_hdr.module_id = AFE_MODULE_LOOPBACK;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_LOOPBACK_CONFIG;
	param_hdr.param_size = sizeof(struct loopback_cfg_data);
	cfg_data.loopback_cfg_minor_version = AFE_API_VERSION_LOOPBACK_CONFIG;
	cfg_data.dst_port_id = rx_port_id;
	cfg_data.routing_mode = LB_MODE_SIDETONE;
	cfg_data.enable = enable;
	ret = q6common_pack_pp_params(packed_param_data + packed_param_size,
				      &param_hdr, (u8 *) &cfg_data,
				      &single_param_size);
	if (ret) {
		pr_err("%s: Failed to pack param data, error %d\n", __func__,
		       ret);
		goto done;
	}
	packed_param_size += single_param_size;

	pr_debug("%s rx(0x%x) tx(0x%x) enable(%d) mid(0x%x) gain(%d) sidetone_enable(%d)\n",
		  __func__, rx_port_id, tx_port_id,
		  enable, mid, sidetone_gain, sidetone_enable);

	ret = q6afe_set_params(tx_port_id, q6audio_get_port_index(tx_port_id),
			       NULL, packed_param_data, packed_param_size);
	if (ret)
		pr_err("%s: AFE sidetone send failed for tx_port:%d rx_port:%d ret:%d\n",
			__func__, tx_port_id, rx_port_id, ret);

done:
	kfree(packed_param_data);
	return ret;
}

int afe_sidetone_enable(u16 tx_port_id, u16 rx_port_id, bool enable)
{
	int ret;
	int index;

	index = q6audio_get_port_index(rx_port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		ret = -EINVAL;
		goto done;
	}
	if (q6audio_validate_port(rx_port_id) < 0) {
		pr_err("%s: Invalid port 0x%x\n",
				__func__, rx_port_id);
		ret = -EINVAL;
		goto done;
	}
	index = q6audio_get_port_index(tx_port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		ret = -EINVAL;
		goto done;
	}
	if (q6audio_validate_port(tx_port_id) < 0) {
		pr_err("%s: Invalid port 0x%x\n",
				__func__, tx_port_id);
		ret = -EINVAL;
		goto done;
	}
	if (enable) {
		ret = afe_sidetone_iir(tx_port_id);
		if (ret)
			goto done;
	}

	ret = afe_sidetone(tx_port_id, rx_port_id, enable);

done:
	return ret;
}

/**
 * afe_set_display_stream - command to update AFE dp port params
 *
 * @rx_port_id: AFE port id
 * @stream_idx: dp controller stream index
 * @ctl_idx: dp controller index
 *
 * Returns 0 on success, appropriate error code otherwise
 */
int afe_set_display_stream(u16 rx_port_id, u32 stream_idx, u32 ctl_idx)
{
	int ret;
	struct param_hdr_v3 param_hdr;
	u32 packed_param_size = 0;
	u8 *packed_param_data = NULL;
	struct afe_display_stream_idx stream_data;
	struct afe_display_ctl_idx ctl_data;
	u32 single_param_size = 0;

	memset(&param_hdr, 0, sizeof(param_hdr));
	memset(&stream_data, 0, sizeof(stream_data));
	memset(&ctl_data, 0, sizeof(ctl_data));

	packed_param_size =
		sizeof(param_hdr) * 2 + sizeof(stream_data) + sizeof(ctl_data);
	packed_param_data = kzalloc(packed_param_size, GFP_KERNEL);
	if (!packed_param_data)
		return -ENOMEM;
	packed_param_size = 0;

	/* Set stream index */
	param_hdr.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_HDMI_DP_MST_VID_IDX_CFG;
	param_hdr.param_size = sizeof(struct afe_display_stream_idx);
	stream_data.minor_version = 1;
	stream_data.stream_idx = stream_idx;
	ret = q6common_pack_pp_params(packed_param_data, &param_hdr,
				      (u8 *) &stream_data, &single_param_size);
	if (ret) {
		pr_err("%s: Failed to pack param data, error %d\n", __func__,
		       ret);
		goto done;
	}
	packed_param_size += single_param_size;

	/* Set controller dptx index */
	param_hdr.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_HDMI_DPTX_IDX_CFG;
	param_hdr.param_size = sizeof(struct afe_display_ctl_idx);
	ctl_data.minor_version = 1;
	ctl_data.ctl_idx = ctl_idx;
	ret = q6common_pack_pp_params(packed_param_data + packed_param_size,
				      &param_hdr, (u8 *) &ctl_data,
				      &single_param_size);
	if (ret) {
		pr_err("%s: Failed to pack param data, error %d\n", __func__,
		       ret);
		goto done;
	}
	packed_param_size += single_param_size;

	pr_debug("%s: rx(0x%x) stream(%d) controller(%d)\n",
		 __func__, rx_port_id, stream_idx, ctl_idx);

	ret = q6afe_set_params(rx_port_id, q6audio_get_port_index(rx_port_id),
			       NULL, packed_param_data, packed_param_size);
	if (ret)
		pr_err("%s: AFE display stream send failed for rx_port:%d ret:%d\n",
			__func__, rx_port_id, ret);

done:
	kfree(packed_param_data);
	return ret;

}
EXPORT_SYMBOL(afe_set_display_stream);

int afe_validate_port(u16 port_id)
{
	int ret;

	switch (port_id) {
	case PRIMARY_I2S_RX:
	case PRIMARY_I2S_TX:
	case AFE_PORT_ID_PRIMARY_PCM_RX:
	case AFE_PORT_ID_PRIMARY_PCM_TX:
	case AFE_PORT_ID_SECONDARY_PCM_RX:
	case AFE_PORT_ID_SECONDARY_PCM_TX:
	case AFE_PORT_ID_TERTIARY_PCM_RX:
	case AFE_PORT_ID_TERTIARY_PCM_TX:
	case AFE_PORT_ID_QUATERNARY_PCM_RX:
	case AFE_PORT_ID_QUATERNARY_PCM_TX:
	case AFE_PORT_ID_QUINARY_PCM_RX:
	case AFE_PORT_ID_QUINARY_PCM_TX:
	case AFE_PORT_ID_SENARY_PCM_RX:
	case AFE_PORT_ID_SENARY_PCM_TX:
	case SECONDARY_I2S_RX:
	case SECONDARY_I2S_TX:
	case MI2S_RX:
	case MI2S_TX:
	case HDMI_RX:
	case HDMI_RX_MS:
	case DISPLAY_PORT_RX:
	case AFE_PORT_ID_PRIMARY_SPDIF_RX:
	case AFE_PORT_ID_PRIMARY_SPDIF_TX:
	case AFE_PORT_ID_SECONDARY_SPDIF_RX:
	case AFE_PORT_ID_SECONDARY_SPDIF_TX:
	case RSVD_2:
	case RSVD_3:
	case DIGI_MIC_TX:
	case VOICE_RECORD_RX:
	case VOICE_RECORD_TX:
	case VOICE_PLAYBACK_TX:
	case VOICE2_PLAYBACK_TX:
	case SLIMBUS_0_RX:
	case SLIMBUS_0_TX:
	case SLIMBUS_1_RX:
	case SLIMBUS_1_TX:
	case SLIMBUS_2_RX:
	case SLIMBUS_2_TX:
	case SLIMBUS_3_RX:
	case INT_BT_SCO_RX:
	case INT_BT_SCO_TX:
	case INT_BT_A2DP_RX:
	case INT_FM_RX:
	case INT_FM_TX:
	case RT_PROXY_PORT_001_RX:
	case RT_PROXY_PORT_001_TX:
	case SLIMBUS_4_RX:
	case SLIMBUS_4_TX:
	case SLIMBUS_5_RX:
	case SLIMBUS_6_RX:
	case SLIMBUS_6_TX:
	case SLIMBUS_7_RX:
	case SLIMBUS_7_TX:
	case SLIMBUS_8_RX:
	case SLIMBUS_8_TX:
	case SLIMBUS_9_RX:
	case SLIMBUS_9_TX:
	case AFE_PORT_ID_USB_RX:
	case AFE_PORT_ID_USB_TX:
	case AFE_PORT_ID_PRIMARY_MI2S_RX:
	case AFE_PORT_ID_PRIMARY_MI2S_TX:
	case AFE_PORT_ID_SECONDARY_MI2S_RX:
	case AFE_PORT_ID_SECONDARY_MI2S_TX:
	case AFE_PORT_ID_QUATERNARY_MI2S_RX:
	case AFE_PORT_ID_QUATERNARY_MI2S_TX:
	case AFE_PORT_ID_TERTIARY_MI2S_RX:
	case AFE_PORT_ID_TERTIARY_MI2S_TX:
	case AFE_PORT_ID_QUINARY_MI2S_RX:
	case AFE_PORT_ID_QUINARY_MI2S_TX:
	case AFE_PORT_ID_SENARY_MI2S_RX:
	case AFE_PORT_ID_SENARY_MI2S_TX:
	case AFE_PORT_ID_PRIMARY_META_MI2S_RX:
	case AFE_PORT_ID_SECONDARY_META_MI2S_RX:
	case AFE_PORT_ID_PRIMARY_TDM_RX:
	case AFE_PORT_ID_PRIMARY_TDM_TX:
	case AFE_PORT_ID_PRIMARY_TDM_RX_1:
	case AFE_PORT_ID_PRIMARY_TDM_TX_1:
	case AFE_PORT_ID_PRIMARY_TDM_RX_2:
	case AFE_PORT_ID_PRIMARY_TDM_TX_2:
	case AFE_PORT_ID_PRIMARY_TDM_RX_3:
	case AFE_PORT_ID_PRIMARY_TDM_TX_3:
	case AFE_PORT_ID_PRIMARY_TDM_RX_4:
	case AFE_PORT_ID_PRIMARY_TDM_TX_4:
	case AFE_PORT_ID_PRIMARY_TDM_RX_5:
	case AFE_PORT_ID_PRIMARY_TDM_TX_5:
	case AFE_PORT_ID_PRIMARY_TDM_RX_6:
	case AFE_PORT_ID_PRIMARY_TDM_TX_6:
	case AFE_PORT_ID_PRIMARY_TDM_RX_7:
	case AFE_PORT_ID_PRIMARY_TDM_TX_7:
	case AFE_PORT_ID_SECONDARY_TDM_RX:
	case AFE_PORT_ID_SECONDARY_TDM_TX:
	case AFE_PORT_ID_SECONDARY_TDM_RX_1:
	case AFE_PORT_ID_SECONDARY_TDM_TX_1:
	case AFE_PORT_ID_SECONDARY_TDM_RX_2:
	case AFE_PORT_ID_SECONDARY_TDM_TX_2:
	case AFE_PORT_ID_SECONDARY_TDM_RX_3:
	case AFE_PORT_ID_SECONDARY_TDM_TX_3:
	case AFE_PORT_ID_SECONDARY_TDM_RX_4:
	case AFE_PORT_ID_SECONDARY_TDM_TX_4:
	case AFE_PORT_ID_SECONDARY_TDM_RX_5:
	case AFE_PORT_ID_SECONDARY_TDM_TX_5:
	case AFE_PORT_ID_SECONDARY_TDM_RX_6:
	case AFE_PORT_ID_SECONDARY_TDM_TX_6:
	case AFE_PORT_ID_SECONDARY_TDM_RX_7:
	case AFE_PORT_ID_SECONDARY_TDM_TX_7:
	case AFE_PORT_ID_TERTIARY_TDM_RX:
	case AFE_PORT_ID_TERTIARY_TDM_TX:
	case AFE_PORT_ID_TERTIARY_TDM_RX_1:
	case AFE_PORT_ID_TERTIARY_TDM_TX_1:
	case AFE_PORT_ID_TERTIARY_TDM_RX_2:
	case AFE_PORT_ID_TERTIARY_TDM_TX_2:
	case AFE_PORT_ID_TERTIARY_TDM_RX_3:
	case AFE_PORT_ID_TERTIARY_TDM_TX_3:
	case AFE_PORT_ID_TERTIARY_TDM_RX_4:
	case AFE_PORT_ID_TERTIARY_TDM_TX_4:
	case AFE_PORT_ID_TERTIARY_TDM_RX_5:
	case AFE_PORT_ID_TERTIARY_TDM_TX_5:
	case AFE_PORT_ID_TERTIARY_TDM_RX_6:
	case AFE_PORT_ID_TERTIARY_TDM_TX_6:
	case AFE_PORT_ID_TERTIARY_TDM_RX_7:
	case AFE_PORT_ID_TERTIARY_TDM_TX_7:
	case AFE_PORT_ID_QUATERNARY_TDM_RX:
	case AFE_PORT_ID_QUATERNARY_TDM_TX:
	case AFE_PORT_ID_QUATERNARY_TDM_RX_1:
	case AFE_PORT_ID_QUATERNARY_TDM_TX_1:
	case AFE_PORT_ID_QUATERNARY_TDM_RX_2:
	case AFE_PORT_ID_QUATERNARY_TDM_TX_2:
	case AFE_PORT_ID_QUATERNARY_TDM_RX_3:
	case AFE_PORT_ID_QUATERNARY_TDM_TX_3:
	case AFE_PORT_ID_QUATERNARY_TDM_RX_4:
	case AFE_PORT_ID_QUATERNARY_TDM_TX_4:
	case AFE_PORT_ID_QUATERNARY_TDM_RX_5:
	case AFE_PORT_ID_QUATERNARY_TDM_TX_5:
	case AFE_PORT_ID_QUATERNARY_TDM_RX_6:
	case AFE_PORT_ID_QUATERNARY_TDM_TX_6:
	case AFE_PORT_ID_QUATERNARY_TDM_RX_7:
	case AFE_PORT_ID_QUATERNARY_TDM_TX_7:
	case AFE_PORT_ID_QUINARY_TDM_RX:
	case AFE_PORT_ID_QUINARY_TDM_TX:
	case AFE_PORT_ID_QUINARY_TDM_RX_1:
	case AFE_PORT_ID_QUINARY_TDM_TX_1:
	case AFE_PORT_ID_QUINARY_TDM_RX_2:
	case AFE_PORT_ID_QUINARY_TDM_TX_2:
	case AFE_PORT_ID_QUINARY_TDM_RX_3:
	case AFE_PORT_ID_QUINARY_TDM_TX_3:
	case AFE_PORT_ID_QUINARY_TDM_RX_4:
	case AFE_PORT_ID_QUINARY_TDM_TX_4:
	case AFE_PORT_ID_QUINARY_TDM_RX_5:
	case AFE_PORT_ID_QUINARY_TDM_TX_5:
	case AFE_PORT_ID_QUINARY_TDM_RX_6:
	case AFE_PORT_ID_QUINARY_TDM_TX_6:
	case AFE_PORT_ID_QUINARY_TDM_RX_7:
	case AFE_PORT_ID_QUINARY_TDM_TX_7:
	case AFE_PORT_ID_SENARY_TDM_RX:
	case AFE_PORT_ID_SENARY_TDM_TX:
	case AFE_PORT_ID_SENARY_TDM_RX_1:
	case AFE_PORT_ID_SENARY_TDM_TX_1:
	case AFE_PORT_ID_SENARY_TDM_RX_2:
	case AFE_PORT_ID_SENARY_TDM_TX_2:
	case AFE_PORT_ID_SENARY_TDM_RX_3:
	case AFE_PORT_ID_SENARY_TDM_TX_3:
	case AFE_PORT_ID_SENARY_TDM_RX_4:
	case AFE_PORT_ID_SENARY_TDM_TX_4:
	case AFE_PORT_ID_SENARY_TDM_RX_5:
	case AFE_PORT_ID_SENARY_TDM_TX_5:
	case AFE_PORT_ID_SENARY_TDM_RX_6:
	case AFE_PORT_ID_SENARY_TDM_TX_6:
	case AFE_PORT_ID_SENARY_TDM_RX_7:
	case AFE_PORT_ID_SENARY_TDM_TX_7:
	case AFE_PORT_ID_INT0_MI2S_RX:
	case AFE_PORT_ID_INT1_MI2S_RX:
	case AFE_PORT_ID_INT2_MI2S_RX:
	case AFE_PORT_ID_INT3_MI2S_RX:
	case AFE_PORT_ID_INT4_MI2S_RX:
	case AFE_PORT_ID_INT5_MI2S_RX:
	case AFE_PORT_ID_INT6_MI2S_RX:
	case AFE_PORT_ID_INT0_MI2S_TX:
	case AFE_PORT_ID_INT1_MI2S_TX:
	case AFE_PORT_ID_INT2_MI2S_TX:
	case AFE_PORT_ID_INT3_MI2S_TX:
	case AFE_PORT_ID_INT4_MI2S_TX:
	case AFE_PORT_ID_INT5_MI2S_TX:
	case AFE_PORT_ID_INT6_MI2S_TX:
	case AFE_PORT_ID_WSA_CODEC_DMA_RX_0:
	case AFE_PORT_ID_WSA_CODEC_DMA_TX_0:
	case AFE_PORT_ID_WSA_CODEC_DMA_RX_1:
	case AFE_PORT_ID_WSA_CODEC_DMA_TX_1:
	case AFE_PORT_ID_WSA_CODEC_DMA_TX_2:
	case AFE_PORT_ID_VA_CODEC_DMA_TX_0:
	case AFE_PORT_ID_VA_CODEC_DMA_TX_1:
	case AFE_PORT_ID_VA_CODEC_DMA_TX_2:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_0:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_0:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_1:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_1:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_2:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_2:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_3:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_3:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_4:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_4:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_5:
	case AFE_PORT_ID_TX_CODEC_DMA_TX_5:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_6:
	case AFE_PORT_ID_RX_CODEC_DMA_RX_7:
	case RT_PROXY_PORT_002_RX:
	case RT_PROXY_PORT_002_TX:
	{
		ret = 0;
		break;
	}

	default:
		pr_err("%s: default ret 0x%x\n", __func__, port_id);
		ret = -EINVAL;
	}

	return ret;
}

int afe_convert_virtual_to_portid(u16 port_id)
{
	int ret;

	/*
	 * if port_id is virtual, convert to physical..
	 * if port_id is already physical, return physical
	 */
	if (afe_validate_port(port_id) < 0) {
		if (port_id == RT_PROXY_DAI_001_RX ||
		    port_id == RT_PROXY_DAI_001_TX ||
		    port_id == RT_PROXY_DAI_002_RX ||
		    port_id == RT_PROXY_DAI_002_TX) {
			ret = VIRTUAL_ID_TO_PORTID(port_id);
		} else {
			pr_err("%s: wrong port 0x%x\n",
				__func__, port_id);
			ret = -EINVAL;
		}
	} else
		ret = port_id;

	return ret;
}
int afe_port_stop_nowait(int port_id)
{
	struct afe_port_cmd_device_stop stop;
	int ret = 0;

	if (this_afe.apr == NULL) {
		pr_err("%s: AFE is already closed\n", __func__);
		ret = -EINVAL;
		goto fail_cmd;
	}
	pr_debug("%s: port_id = 0x%x\n", __func__, port_id);
	port_id = q6audio_convert_virtual_to_portid(port_id);

	stop.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	stop.hdr.pkt_size = sizeof(stop);
	stop.hdr.src_port = 0;
	stop.hdr.dest_port = 0;
	stop.hdr.token = 0;
	stop.hdr.opcode = AFE_PORT_CMD_DEVICE_STOP;
	stop.port_id = port_id;
	stop.reserved = 0;

	ret = afe_apr_send_pkt(&stop, NULL);
	if (ret)
		pr_err("%s: AFE close failed %d\n", __func__, ret);

fail_cmd:
	return ret;

}

/**
 * afe_close - command to close AFE port
 *
 * @port_id: AFE port id
 *
 * Returns 0 on success, appropriate error code otherwise
 */
int afe_close(int port_id)
{
	struct afe_port_cmd_device_stop stop;
	enum afe_mad_type mad_type;
	int ret = 0;
	u16 i;
	int index = 0;
	uint16_t port_index;

	if (this_afe.apr == NULL) {
		pr_err("%s: AFE is already closed\n", __func__);
		if ((port_id == RT_PROXY_DAI_001_RX) ||
		    (port_id == RT_PROXY_DAI_002_TX))
			pcm_afe_instance[port_id & 0x1] = 0;
		if ((port_id == RT_PROXY_DAI_002_RX) ||
		    (port_id == RT_PROXY_DAI_001_TX))
			proxy_afe_instance[port_id & 0x1] = 0;
		afe_close_done[port_id & 0x1] = true;
		ret = -EINVAL;
		goto fail_cmd;
	}
	pr_info("%s: port_id = 0x%x\n", __func__, port_id);
	if ((port_id == RT_PROXY_DAI_001_RX) ||
			(port_id == RT_PROXY_DAI_002_TX)) {
		pr_debug("%s: before decrementing pcm_afe_instance %d\n",
			__func__, pcm_afe_instance[port_id & 0x1]);
		port_id = VIRTUAL_ID_TO_PORTID(port_id);
		pcm_afe_instance[port_id & 0x1]--;
		if ((!(pcm_afe_instance[port_id & 0x1] == 0 &&
			proxy_afe_instance[port_id & 0x1] == 0)) ||
			afe_close_done[port_id & 0x1] == true)
			return 0;

		afe_close_done[port_id & 0x1] = true;
	}

	if ((port_id == RT_PROXY_DAI_002_RX) ||
		(port_id == RT_PROXY_DAI_001_TX)) {
		pr_debug("%s: before decrementing proxy_afe_instance %d\n",
			__func__, proxy_afe_instance[port_id & 0x1]);
		port_id = VIRTUAL_ID_TO_PORTID(port_id);
		proxy_afe_instance[port_id & 0x1]--;
		if ((!(pcm_afe_instance[port_id & 0x1] == 0 &&
			proxy_afe_instance[port_id & 0x1] == 0)) ||
			afe_close_done[port_id & 0x1] == true)
			return 0;

		afe_close_done[port_id & 0x1] = true;
	}

	port_id = q6audio_convert_virtual_to_portid(port_id);
	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		return -EINVAL;
	}
	ret = q6audio_validate_port(port_id);
	if (ret < 0) {
		pr_warn("%s: Not a valid port id 0x%x ret %d\n",
			__func__, port_id, ret);
		return -EINVAL;
	}

	mad_type = afe_port_get_mad_type(port_id);
	pr_debug("%s: port_id 0x%x, mad_type %d\n", __func__, port_id,
		 mad_type);
	if (mad_type != MAD_HW_NONE && mad_type != MAD_SW_AUDIO) {
		pr_debug("%s: Turn off MAD\n", __func__);
		ret = afe_turn_onoff_hw_mad(mad_type, false);
		if (ret) {
			pr_err("%s: afe_turn_onoff_hw_mad failed %d\n",
			       __func__, ret);
			return ret;
		}
	} else {
		pr_debug("%s: Not a MAD port\n", __func__);
	}

	mutex_lock(&this_afe.afe_cmd_lock);
	port_index = afe_get_port_index(port_id);
	if ((port_index >= 0) && (port_index < AFE_MAX_PORTS)) {
		this_afe.afe_sample_rates[port_index] = 0;
		this_afe.topology[port_index] = 0;
		this_afe.dev_acdb_id[port_index] = 0;
	} else {
		pr_err("%s: port %d\n", __func__, port_index);
		ret = -EINVAL;
		goto fail_cmd;
	}

	if ((port_id == this_afe.aanc_info.aanc_tx_port) &&
	    (this_afe.aanc_info.aanc_active)) {
		memset(&this_afe.aanc_info, 0x00, sizeof(this_afe.aanc_info));
		ret = afe_aanc_mod_enable(this_afe.apr, port_id, 0);
		if (ret)
			pr_err("%s: AFE mod disable failed %d\n",
				__func__, ret);
	}

	/*
	 * even if ramp down configuration failed it is not serious enough to
	 * warrant bailaing out.
	 */
	if (q6core_get_avcs_api_version_per_service(
		APRV2_IDS_SERVICE_ID_ADSP_AFE_V) < AFE_API_VERSION_V9) {
		if (afe_spk_ramp_dn_cfg(port_id) < 0)
			pr_err("%s: ramp down config failed\n", __func__);
	}

	stop.hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE), APR_PKT_VER);
	stop.hdr.pkt_size = sizeof(stop);
	stop.hdr.src_port = 0;
	stop.hdr.dest_port = 0;
	stop.hdr.token = index;
	stop.hdr.opcode = AFE_PORT_CMD_DEVICE_STOP;
	stop.port_id = q6audio_get_port_id(port_id);
	stop.reserved = 0;

	ret = afe_apr_send_pkt(&stop, &this_afe.wait[index]);
	if (ret)
		pr_err("%s: AFE close failed %d\n", __func__, ret);

fail_cmd:
	if ((q6core_get_avcs_api_version_per_service(
		APRV2_IDS_SERVICE_ID_ADSP_CORE_V) >= AVCS_API_VERSION_V5)) {
		for (i = 0; i < MAX_ALLOWED_USE_CASES; i++) {
			if (pm[i] && pm[i]->port_id == port_id) {
				q6afe_unload_avcs_modules(port_id, i);
				break;
			}
		}
	}
	mutex_unlock(&this_afe.afe_cmd_lock);
	return ret;
}
EXPORT_SYMBOL(afe_close);

int afe_set_digital_codec_core_clock(u16 port_id,
				struct afe_digital_clk_cfg *cfg)
{
	struct afe_digital_clk_cfg clk_cfg;
	struct param_hdr_v3 param_hdr;
	int ret = 0;

	if (!cfg) {
		pr_err("%s: clock cfg is NULL\n", __func__);
		return -EINVAL;
	}

	memset(&clk_cfg, 0, sizeof(clk_cfg));
	memset(&param_hdr, 0, sizeof(param_hdr));

	/*default rx port is taken to enable the codec digital clock*/
	param_hdr.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_INTERNAL_DIGIATL_CDC_CLK_CONFIG;
	param_hdr.param_size = sizeof(struct afe_digital_clk_cfg);
	clk_cfg = *cfg;

	pr_debug("%s: Minor version =0x%x clk val = %d\n"
		 "clk root = 0x%x resrv = 0x%x\n",
		 __func__, cfg->i2s_cfg_minor_version, cfg->clk_val,
		 cfg->clk_root, cfg->reserved);

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) &clk_cfg);
	if (ret < 0)
		pr_err("%s: AFE enable for port 0x%x ret %d\n", __func__,
		       port_id, ret);
	return ret;
}

/**
 * afe_set_lpass_clock - Enable AFE lpass clock
 *
 * @port_id: AFE port id
 * @cfg: pointer to clk set struct
 *
 * Returns 0 on success, appropriate error code otherwise
 */
int afe_set_lpass_clock(u16 port_id, struct afe_clk_cfg *cfg)
{
	struct afe_clk_cfg clk_cfg;
	struct param_hdr_v3 param_hdr;
	int ret = 0;

	if (!cfg) {
		pr_err("%s: clock cfg is NULL\n", __func__);
		return -EINVAL;
	}

	memset(&clk_cfg, 0, sizeof(clk_cfg));
	memset(&param_hdr, 0, sizeof(param_hdr));

	ret = q6audio_is_digital_pcm_interface(port_id);
	if (ret < 0) {
		pr_err("%s: q6audio_is_digital_pcm_interface fail %d\n",
			__func__, ret);
		return -EINVAL;
	}

	mutex_lock(&this_afe.afe_cmd_lock);
	param_hdr.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_LPAIF_CLK_CONFIG;
	param_hdr.param_size = sizeof(clk_cfg);
	clk_cfg = *cfg;

	pr_debug("%s: Minor version =0x%x clk val1 = %d\n"
		 "clk val2 = %d, clk src = 0x%x\n"
		 "clk root = 0x%x clk mode = 0x%x resrv = 0x%x\n"
		 "port id = 0x%x\n",
		 __func__, cfg->i2s_cfg_minor_version,
		 cfg->clk_val1, cfg->clk_val2, cfg->clk_src,
		 cfg->clk_root, cfg->clk_set_mode,
		 cfg->reserved, q6audio_get_port_id(port_id));

	trace_printk("%s: Minor version =0x%x clk val1 = %d\n"
		 "clk val2 = %d, clk src = 0x%x\n"
		 "clk root = 0x%x clk mode = 0x%x resrv = 0x%x\n"
		 "port id = 0x%x\n",
		 __func__, cfg->i2s_cfg_minor_version,
		 cfg->clk_val1, cfg->clk_val2, cfg->clk_src,
		 cfg->clk_root, cfg->clk_set_mode,
		 cfg->reserved, q6audio_get_port_id(port_id));

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) &clk_cfg);
	if (ret < 0)
		pr_err("%s: AFE enable for port 0x%x ret %d\n",
		       __func__, port_id, ret);

	mutex_unlock(&this_afe.afe_cmd_lock);
	return ret;
}
EXPORT_SYMBOL(afe_set_lpass_clock);

static int afe_get_port_idx(u16 port_id)
{
	u16 afe_port = 0;
	int i = -EINVAL;

	pr_debug("%s: port id 0x%x\n", __func__, port_id);

	if ((port_id >= AFE_PORT_ID_TDM_PORT_RANGE_START) &&
		(port_id <= AFE_PORT_ID_TDM_PORT_RANGE_END))
		afe_port = port_id & 0xFFF0;
	else if ((port_id == AFE_PORT_ID_PRIMARY_SPDIF_RX) ||
		 (port_id == AFE_PORT_ID_PRIMARY_SPDIF_TX) ||
		 (port_id == AFE_PORT_ID_SECONDARY_SPDIF_RX) ||
		 (port_id == AFE_PORT_ID_SECONDARY_SPDIF_TX))
		afe_port = port_id;
	else
		afe_port = port_id & 0xFFFE;

	for (i = 0; i < ARRAY_SIZE(clkinfo_per_port); i++) {
		if (afe_port == clkinfo_per_port[i].port_id) {
			pr_debug("%s: idx 0x%x port id 0x%x\n", __func__,
				  i, afe_port);
			return i;
		}
	}

	pr_debug("%s: cannot get idx for port id 0x%x\n", __func__,
		afe_port);

	return -EINVAL;
}

static int afe_get_clk_id(u16 port_id)
{
	u16 afe_port = 0;
	uint32_t clk_id = -EINVAL;
	int idx = 0;

	idx = afe_get_port_idx(port_id);
	if (idx < 0) {
		pr_err("%s: cannot get clock id for port id 0x%x\n", __func__,
			afe_port);
		return -EINVAL;
	}

	clk_id = clkinfo_per_port[idx].clk_id;
	pr_debug("%s: clk id 0x%x port id 0x%x\n", __func__, clk_id,
		  afe_port);

	return clk_id;
}

/**
 * afe_set_clk_id - Update clock id for AFE port
 *
 * @port_id: AFE port id
 * @clk_id: CLock ID
 *
 * Returns 0 on success, appropriate error code otherwise
 */
int afe_set_clk_id(u16 port_id, uint32_t clk_id)
{
	u16 afe_port = 0;
	int idx = 0;

	idx = afe_get_port_idx(port_id);
	if (idx < 0) {
		pr_debug("%s: cannot set clock id for port id 0x%x\n", __func__,
			afe_port);
		return -EINVAL;
	}

	clkinfo_per_port[idx].clk_id = clk_id;
	pr_debug("%s: updated clk id 0x%x port id 0x%x\n", __func__,
		  clkinfo_per_port[idx].clk_id, afe_port);

	return 0;
}
EXPORT_SYMBOL(afe_set_clk_id);

/**
 * afe_set_pll_clk_drift - Set audio interface PLL clock drift
 *
 * @port_id: AFE port id
 * @set_clk_drift: clk drift to adjust PLL
 * @clk_reset: reset Interface clock to original value
 *
 * Returns 0 on success, appropriate error code otherwise
 */
int afe_set_pll_clk_drift(u16 port_id, int32_t set_clk_drift,
			  uint32_t clk_reset)
{
	struct afe_set_clk_drift clk_drift;
	struct param_hdr_v3 param_hdr;
	uint32_t clk_id;
	int index = 0, ret = 0;

	memset(&param_hdr, 0, sizeof(param_hdr));
	memset(&clk_drift, 0, sizeof(clk_drift));

	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: index[%d] invalid!\n", __func__, index);
		return -EINVAL;
	}

	ret = afe_q6_interface_prepare();
	if (ret != 0) {
		pr_err_ratelimited("%s: Q6 interface prepare failed %d\n",
				    __func__, ret);
		return ret;
	}

	clk_id = afe_get_clk_id(port_id);
	if (clk_id < 0) {
		pr_err("%s: cannot get clk id for port id 0x%x\n",
			__func__, port_id);
		return -EINVAL;
	}

	if (clk_id & 0x01) {
		pr_err("%s: cannot adjust clock drift for external clock id 0x%x\n",
			__func__, clk_id);
		return -EINVAL;
	}

	clk_drift.clk_drift = set_clk_drift;
	clk_drift.clk_reset = clk_reset;
	clk_drift.clk_id = clk_id;
	pr_debug("%s: clk id = 0x%x clk drift  = %d clk reset = %d port id 0x%x\n",
		  __func__, clk_drift.clk_id, clk_drift.clk_drift,
		 clk_drift.clk_reset, port_id);

	mutex_lock(&this_afe.afe_clk_lock);
	param_hdr.module_id = AFE_MODULE_CLOCK_SET;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_CLOCK_ADJUST;
	param_hdr.param_size = sizeof(struct afe_set_clk_drift);

	ret = q6afe_svc_pack_and_set_param_in_band(index, param_hdr,
						   (u8 *) &clk_drift);
	if (ret < 0)
		pr_err_ratelimited("%s: AFE PLL clk drift failed with ret %d\n",
				    __func__, ret);

	mutex_unlock(&this_afe.afe_clk_lock);
	return ret;
}
EXPORT_SYMBOL(afe_set_pll_clk_drift);

/**
 * afe_set_lpass_clk_cfg - Set AFE clk config
 *
 * @index: port index
 * @cfg: pointer to clk set struct
 *
 * Returns 0 on success, appropriate error code otherwise
 */
int afe_set_lpass_clk_cfg(int index, struct afe_clk_set *cfg)
{
	struct param_hdr_v3 param_hdr;
	int ret = 0;

	if (!cfg) {
		pr_err("%s: clock cfg is NULL\n", __func__);
		ret = -EINVAL;
		return ret;
	}

	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: index[%d] invalid!\n", __func__, index);
		return -EINVAL;
	}

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

	mutex_lock(&this_afe.afe_clk_lock);
	param_hdr.module_id = AFE_MODULE_CLOCK_SET;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_CLOCK_SET;
	param_hdr.param_size = sizeof(struct afe_clk_set);


	pr_debug("%s: Minor version =0x%x clk id = %d\n"
		 "clk freq (Hz) = %d, clk attri = 0x%x\n"
		 "clk root = 0x%x clk enable = 0x%x\n",
		 __func__, cfg->clk_set_minor_version,
		 cfg->clk_id, cfg->clk_freq_in_hz, cfg->clk_attri,
		 cfg->clk_root, cfg->enable);

	trace_printk("%s: Minor version =0x%x clk id = %d\n"
		 "clk freq (Hz) = %d, clk attri = 0x%x\n"
		 "clk root = 0x%x clk enable = 0x%x\n",
		 __func__, cfg->clk_set_minor_version,
		 cfg->clk_id, cfg->clk_freq_in_hz, cfg->clk_attri,
		 cfg->clk_root, cfg->enable);

	ret = q6afe_svc_pack_and_set_param_in_band(index, param_hdr,
						   (u8 *) cfg);
	if (ret < 0) {
		pr_err_ratelimited("%s: AFE clk cfg failed with ret %d\n",
				__func__, ret);
		trace_printk("%s: AFE clk cfg failed with ret %d\n",
		       __func__, ret);
	}

	mutex_unlock(&this_afe.afe_clk_lock);
	return ret;
}
EXPORT_SYMBOL(afe_set_lpass_clk_cfg);

/**
 * afe_set_lpass_clock_v2 - Enable AFE lpass clock
 *
 * @port_id: AFE port id
 * @cfg: pointer to clk set struct
 *
 * Returns 0 on success, appropriate error code otherwise
 */
int afe_set_lpass_clock_v2(u16 port_id, struct afe_clk_set *cfg)
{
	int index = 0;
	int ret = 0;

	index = q6audio_get_port_index(port_id);
	if (index < 0 || index >= AFE_MAX_PORTS) {
		pr_err("%s: AFE port index[%d] invalid!\n",
				__func__, index);
		return -EINVAL;
	}
	ret = q6audio_is_digital_pcm_interface(port_id);
	if (ret < 0) {
		pr_err("%s: q6audio_is_digital_pcm_interface fail %d\n",
			__func__, ret);
		return -EINVAL;
	}

	ret = afe_set_clk_id(port_id, cfg->clk_id);
	if (ret < 0)
		pr_debug("%s: afe_set_clk_id fail %d\n", __func__, ret);

	ret = afe_set_lpass_clk_cfg(index, cfg);
	if (ret)
		pr_err("%s: afe_set_lpass_clk_cfg_v2 failed %d\n",
			__func__, ret);

	return ret;
}
EXPORT_SYMBOL(afe_set_lpass_clock_v2);

int afe_set_lpass_internal_digital_codec_clock(u16 port_id,
			struct afe_digital_clk_cfg *cfg)
{
	struct afe_digital_clk_cfg clk_cfg;
	struct param_hdr_v3 param_hdr;
	int ret = 0;

	if (!cfg) {
		pr_err("%s: clock cfg is NULL\n", __func__);
		return -EINVAL;
	}

	memset(&clk_cfg, 0, sizeof(clk_cfg));
	memset(&param_hdr, 0, sizeof(param_hdr));

	ret = q6audio_is_digital_pcm_interface(port_id);
	if (ret < 0) {
		pr_err("%s: q6audio_is_digital_pcm_interface fail %d\n",
			__func__, ret);
		return -EINVAL;
	}

	param_hdr.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_INTERNAL_DIGIATL_CDC_CLK_CONFIG;
	param_hdr.param_size = sizeof(clk_cfg);
	clk_cfg = *cfg;

	pr_debug("%s: Minor version =0x%x clk val = %d\n"
		 "clk root = 0x%x resrv = 0x%x port id = 0x%x\n",
		 __func__, cfg->i2s_cfg_minor_version,
		 cfg->clk_val, cfg->clk_root, cfg->reserved,
		 q6audio_get_port_id(port_id));

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) &clk_cfg);
	if (ret < 0)
		pr_err("%s: AFE enable for port 0x0x%x ret %d\n",
		       __func__, port_id, ret);

	return ret;
}
/**
 * afe_enable_lpass_core_shared_clock -
 *      Configures the core clk on LPASS.
 *      Need on targets where lpass provides
 *      clocks
 * @port_id: afe port id
 * @enable: enable or disable clk
 *
 * Returns success or failure of call.
 */
int afe_enable_lpass_core_shared_clock(u16 port_id, u32 enable)
{
	struct afe_param_id_lpass_core_shared_clk_cfg clk_cfg;
	struct param_hdr_v3 param_hdr;
	int ret = 0;

	memset(&clk_cfg, 0, sizeof(clk_cfg));
	memset(&param_hdr, 0, sizeof(param_hdr));

	ret = q6audio_is_digital_pcm_interface(port_id);
	if (ret < 0) {
		pr_err("%s: q6audio_is_digital_pcm_interface fail %d\n",
		       __func__, ret);
		return -EINVAL;
	}

	mutex_lock(&this_afe.afe_cmd_lock);
	param_hdr.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_LPASS_CORE_SHARED_CLOCK_CONFIG;
	param_hdr.param_size = sizeof(clk_cfg);
	clk_cfg.lpass_core_shared_clk_cfg_minor_version =
		AFE_API_VERSION_LPASS_CORE_SHARED_CLK_CONFIG;
	clk_cfg.enable = enable;

	pr_debug("%s: port id = %d, enable = %d\n",
		 __func__, q6audio_get_port_id(port_id), enable);

	ret = q6afe_pack_and_set_param_in_band(port_id,
					       q6audio_get_port_index(port_id),
					       param_hdr, (u8 *) &clk_cfg);
	if (ret < 0)
		pr_err("%s: AFE enable for port 0x%x ret %d\n",
		       __func__, port_id, ret);

	mutex_unlock(&this_afe.afe_cmd_lock);
	return ret;
}
EXPORT_SYMBOL(afe_enable_lpass_core_shared_clock);

/**
 * q6afe_check_osr_clk_freq -
 *   Gets supported OSR CLK frequencies
 *
 * @freq: frequency to check
 *
 * Returns success if freq is supported.
 */
int q6afe_check_osr_clk_freq(u32 freq)
{
	int ret = 0;

	switch (freq) {
	case Q6AFE_LPASS_OSR_CLK_12_P288_MHZ:
	case Q6AFE_LPASS_OSR_CLK_9_P600_MHZ:
	case Q6AFE_LPASS_OSR_CLK_8_P192_MHZ:
	case Q6AFE_LPASS_OSR_CLK_6_P144_MHZ:
	case Q6AFE_LPASS_OSR_CLK_4_P096_MHZ:
	case Q6AFE_LPASS_OSR_CLK_3_P072_MHZ:
	case Q6AFE_LPASS_OSR_CLK_2_P048_MHZ:
	case Q6AFE_LPASS_OSR_CLK_1_P536_MHZ:
	case Q6AFE_LPASS_OSR_CLK_1_P024_MHZ:
	case Q6AFE_LPASS_OSR_CLK_768_kHZ:
	case Q6AFE_LPASS_OSR_CLK_512_kHZ:
		break;
	default:
		pr_err("%s: default freq 0x%x\n",
			__func__, freq);
		ret = -EINVAL;
	}
	return ret;
}
EXPORT_SYMBOL(q6afe_check_osr_clk_freq);

static int afe_get_spv4_th_vi_v_vali_data(void *params, uint32_t size)
{
	struct param_hdr_v3 param_hdr;
	int port = SLIMBUS_4_TX;
	int ret = -EINVAL;
	uint32_t min_size = 0;
	struct afe_sp_v4_channel_v_vali_params *v_vali_params = NULL;

	if (!params) {
		pr_err("%s: Invalid params\n", __func__);
		goto done;
	}
	if (this_afe.vi_tx_port != -1)
		port = this_afe.vi_tx_port;

	mutex_lock(&this_afe.afe_cmd_lock);
	memset(&param_hdr, 0, sizeof(param_hdr));

	param_hdr.module_id = AFE_MODULE_SPEAKER_PROTECTION_V4_VI;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_SP_V4_TH_VI_V_VALI_PARAMS;
	param_hdr.param_size = size;

	ret = q6afe_get_params(port, NULL, &param_hdr);
	if (ret) {
		pr_err("%s: Failed to get TH VI V-Vali data\n", __func__);
		goto get_params_fail;
	}

	min_size = (size < this_afe.spv4_v_vali_rcvd_param_size) ?
		size : this_afe.spv4_v_vali_rcvd_param_size;
	memcpy(params, (void*)&this_afe.spv4_v_vali_resp.num_ch, min_size);

	v_vali_params = &this_afe.spv4_v_vali_resp.ch_v_vali_params[0];

	pr_debug("%s: num_ch %d  Vrms %d %d status %d %d\n", __func__,
		this_afe.spv4_v_vali_resp.num_ch,
		v_vali_params[SP_V2_SPKR_1].vrms_q24,
		v_vali_params[SP_V2_SPKR_2].vrms_q24,
		v_vali_params[SP_V2_SPKR_1].status,
		v_vali_params[SP_V2_SPKR_2].status);

	/*using the non-spv4 status varaible to support v_vali debug app. */
	this_afe.th_vi_v_vali_resp.param.status[SP_V2_SPKR_1] =
		 v_vali_params[SP_V2_SPKR_1].status;
	this_afe.th_vi_v_vali_resp.param.status[SP_V2_SPKR_2] =
		 v_vali_params[SP_V2_SPKR_2].status;

	ret = 0;
get_params_fail:
	mutex_unlock(&this_afe.afe_cmd_lock);
done:
	return ret;
}

static int afe_get_sp_th_vi_v_vali_data(
		struct afe_sp_th_vi_v_vali_get_param *th_vi_v_vali)
{
	struct param_hdr_v3 param_hdr;
	int port = SLIMBUS_4_TX;
	int ret = -EINVAL;

	if (!th_vi_v_vali) {
		pr_err("%s: Invalid params\n", __func__);
		goto done;
	}
	if (this_afe.vi_tx_port != -1)
		port = this_afe.vi_tx_port;

	mutex_lock(&this_afe.afe_cmd_lock);
	memset(&param_hdr, 0, sizeof(param_hdr));

	param_hdr.module_id = AFE_MODULE_SPEAKER_PROTECTION_V2_TH_VI;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_SP_V2_TH_VI_V_VALI_PARAMS;
	param_hdr.param_size = sizeof(struct afe_sp_th_vi_v_vali_params);

	ret = q6afe_get_params(port, NULL, &param_hdr);
	if (ret) {
		pr_err("%s: Failed to get TH VI V-Vali data\n", __func__);
		goto get_params_fail;
	}

	th_vi_v_vali->pdata = param_hdr;
	memcpy(&th_vi_v_vali->param, &this_afe.th_vi_v_vali_resp.param,
		sizeof(this_afe.th_vi_v_vali_resp.param));
	pr_debug("%s:  Vrms %d %d status %d %d\n", __func__,
		 th_vi_v_vali->param.vrms_q24[SP_V2_SPKR_1],
		 th_vi_v_vali->param.vrms_q24[SP_V2_SPKR_2],
		 th_vi_v_vali->param.status[SP_V2_SPKR_1],
		 th_vi_v_vali->param.status[SP_V2_SPKR_2]);
	ret = 0;
get_params_fail:
	mutex_unlock(&this_afe.afe_cmd_lock);
done:
	return ret;
}

static int afe_get_spv4_th_vi_ftm_data(void *params, uint32_t size)
{
	struct param_hdr_v3 param_hdr;
	int port = SLIMBUS_4_TX;
	int ret = -EINVAL;
	uint32_t min_size = 0;
	struct afe_sp_v4_channel_ftm_params *th_vi_params;

	if (!params) {
		pr_err("%s: Invalid params\n", __func__);
		goto done;
	}
	if (this_afe.vi_tx_port != -1)
		port = this_afe.vi_tx_port;

	mutex_lock(&this_afe.afe_cmd_lock);
	memset(&param_hdr, 0, sizeof(param_hdr));

	param_hdr.module_id = AFE_MODULE_SPEAKER_PROTECTION_V4_VI;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_SP_V4_TH_VI_FTM_PARAMS;
	param_hdr.param_size = size;

	ret = q6afe_get_params(port, NULL, &param_hdr);
	if (ret) {
		pr_err("%s: Failed to get TH VI FTM data\n", __func__);
		goto get_params_fail;
	}

	min_size = (size < this_afe.spv4_th_vi_ftm_rcvd_param_size) ?
		size : this_afe.spv4_th_vi_ftm_rcvd_param_size;
	memcpy(params, (void*)&this_afe.spv4_th_vi_ftm_resp.num_ch, min_size);

	th_vi_params = &this_afe.spv4_th_vi_ftm_resp.ch_ftm_params[0];
	pr_debug("%s:num_ch %d, DC resistance %d %d temp %d %d status %d %d\n",
		 __func__, this_afe.spv4_th_vi_ftm_resp.num_ch,
		th_vi_params[SP_V2_SPKR_1].dc_res_q24,
		th_vi_params[SP_V2_SPKR_2].dc_res_q24,
		th_vi_params[SP_V2_SPKR_1].temp_q22,
		th_vi_params[SP_V2_SPKR_2].temp_q22,
		th_vi_params[SP_V2_SPKR_1].status,
		th_vi_params[SP_V2_SPKR_2].status);
	ret = 0;
get_params_fail:
	mutex_unlock(&this_afe.afe_cmd_lock);
done:
	return ret;
}

static int afe_get_sp_th_vi_ftm_data(struct afe_sp_th_vi_get_param *th_vi)
{
	struct param_hdr_v3 param_hdr;
	int port = SLIMBUS_4_TX;
	int ret = -EINVAL;

	if (!th_vi) {
		pr_err("%s: Invalid params\n", __func__);
		goto done;
	}
	if (this_afe.vi_tx_port != -1)
		port = this_afe.vi_tx_port;

	mutex_lock(&this_afe.afe_cmd_lock);
	memset(&param_hdr, 0, sizeof(param_hdr));

	param_hdr.module_id = AFE_MODULE_SPEAKER_PROTECTION_V2_TH_VI;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_SP_V2_TH_VI_FTM_PARAMS;
	param_hdr.param_size = sizeof(struct afe_sp_th_vi_ftm_params);

	ret = q6afe_get_params(port, NULL, &param_hdr);
	if (ret) {
		pr_err("%s: Failed to get TH VI FTM data\n", __func__);
		goto get_params_fail;
	}

	th_vi->pdata = param_hdr;
	memcpy(&th_vi->param, &this_afe.th_vi_resp.param,
		sizeof(this_afe.th_vi_resp.param));
	pr_debug("%s: DC resistance %d %d temp %d %d status %d %d\n",
		 __func__, th_vi->param.dc_res_q24[SP_V2_SPKR_1],
		 th_vi->param.dc_res_q24[SP_V2_SPKR_2],
		 th_vi->param.temp_q22[SP_V2_SPKR_1],
		 th_vi->param.temp_q22[SP_V2_SPKR_2],
		 th_vi->param.status[SP_V2_SPKR_1],
		 th_vi->param.status[SP_V2_SPKR_2]);
	ret = 0;
get_params_fail:
	mutex_unlock(&this_afe.afe_cmd_lock);
done:
	return ret;
}

static int afe_get_spv4_ex_vi_ftm_data(void *params, uint32_t size)
{
	struct param_hdr_v3 param_hdr;
	int port = SLIMBUS_4_TX;
	int ret = -EINVAL;
	uint32_t min_size = 0;
	struct afe_sp_v4_channel_ex_vi_ftm_params *ex_vi_ftm_param;

	if (!params) {
		pr_err("%s: Invalid params\n", __func__);
		goto done;
	}
	if (this_afe.vi_tx_port != -1)
		port = this_afe.vi_tx_port;

	mutex_lock(&this_afe.afe_cmd_lock);
	memset(&param_hdr, 0, sizeof(param_hdr));

	param_hdr.module_id = AFE_MODULE_SPEAKER_PROTECTION_V4_VI;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_SP_V4_EX_VI_FTM_PARAMS;
	param_hdr.param_size = size;

	ret = q6afe_get_params(port, NULL, &param_hdr);
	if (ret < 0) {
		pr_err("%s: get param port 0x%x param id[0x%x]failed %d\n",
		       __func__, port, param_hdr.param_id, ret);
		goto get_params_fail;
	}

	min_size = (size < this_afe.spv4_ex_vi_ftm_rcvd_param_size) ?
		size : this_afe.spv4_ex_vi_ftm_rcvd_param_size;
	memcpy(params, (void*)&this_afe.spv4_ex_vi_ftm_resp.num_ch, min_size);

	ex_vi_ftm_param = &this_afe.spv4_ex_vi_ftm_resp.ch_ex_vi_ftm_params[0];

	pr_debug("%s:num_ch %d, res %d %d forcefactor %d %d Dmping kg/s %d %d\n"
		"stiffness N/mm %d %d freq %d %d Qfactor %d %d status %d %d",
		__func__, this_afe.spv4_ex_vi_ftm_resp.num_ch,
		ex_vi_ftm_param[SP_V2_SPKR_1].ftm_re_q24,
		ex_vi_ftm_param[SP_V2_SPKR_2].ftm_re_q24,
		ex_vi_ftm_param[SP_V2_SPKR_1].ftm_Bl_q24,
		ex_vi_ftm_param[SP_V2_SPKR_2].ftm_Bl_q24,
		ex_vi_ftm_param[SP_V2_SPKR_1].ftm_Rms_q24,
		ex_vi_ftm_param[SP_V2_SPKR_2].ftm_Rms_q24,
		ex_vi_ftm_param[SP_V2_SPKR_1].ftm_Kms_q24,
		ex_vi_ftm_param[SP_V2_SPKR_2].ftm_Kms_q24,
		ex_vi_ftm_param[SP_V2_SPKR_1].ftm_Fres_q20,
		ex_vi_ftm_param[SP_V2_SPKR_2].ftm_Fres_q20,
		ex_vi_ftm_param[SP_V2_SPKR_1].ftm_Qms_q24,
		ex_vi_ftm_param[SP_V2_SPKR_2].ftm_Qms_q24,
		ex_vi_ftm_param[SP_V2_SPKR_1].status,
		ex_vi_ftm_param[SP_V2_SPKR_2].status);
	ret = 0;
get_params_fail:
	mutex_unlock(&this_afe.afe_cmd_lock);
done:
	return ret;
}

static int afe_get_sp_ex_vi_ftm_data(struct afe_sp_ex_vi_get_param *ex_vi)
{
	struct param_hdr_v3 param_hdr;
	int port = SLIMBUS_4_TX;
	int ret = -EINVAL;

	if (!ex_vi) {
		pr_err("%s: Invalid params\n", __func__);
		goto done;
	}
	if (this_afe.vi_tx_port != -1)
		port = this_afe.vi_tx_port;

	mutex_lock(&this_afe.afe_cmd_lock);
	memset(&param_hdr, 0, sizeof(param_hdr));

	param_hdr.module_id = AFE_MODULE_SPEAKER_PROTECTION_V2_EX_VI;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_SP_V2_EX_VI_FTM_PARAMS;
	param_hdr.param_size = sizeof(struct afe_sp_ex_vi_ftm_params);

	ret = q6afe_get_params(port, NULL, &param_hdr);
	if (ret < 0) {
		pr_err("%s: get param port 0x%x param id[0x%x]failed %d\n",
		       __func__, port, param_hdr.param_id, ret);
		goto get_params_fail;
	}

	ex_vi->pdata = param_hdr;
	memcpy(&ex_vi->param, &this_afe.ex_vi_resp.param,
		sizeof(this_afe.ex_vi_resp.param));
	pr_debug("%s: freq %d %d resistance %d %d qfactor %d %d state %d %d\n",
		 __func__, ex_vi->param.freq_q20[SP_V2_SPKR_1],
		 ex_vi->param.freq_q20[SP_V2_SPKR_2],
		 ex_vi->param.resis_q24[SP_V2_SPKR_1],
		 ex_vi->param.resis_q24[SP_V2_SPKR_2],
		 ex_vi->param.qmct_q24[SP_V2_SPKR_1],
		 ex_vi->param.qmct_q24[SP_V2_SPKR_2],
		 ex_vi->param.status[SP_V2_SPKR_1],
		 ex_vi->param.status[SP_V2_SPKR_2]);
	ret = 0;
get_params_fail:
	mutex_unlock(&this_afe.afe_cmd_lock);
done:
	return ret;
}

int afe_get_sp_v4_rx_tmax_xmax_logging_data(
		struct afe_sp_rx_tmax_xmax_logging_param *xt_logging,
		u16 port_id)
{
	struct param_hdr_v3 param_hdr;
	int ret = -EINVAL;
	struct afe_sp_v4_channel_tmax_xmax_params *tx_channel_params;
	uint32_t i, size = 0;

	if (!xt_logging) {
		pr_err("%s: Invalid params\n", __func__);
		goto done;
	}

	size = sizeof(struct afe_sp_v4_param_tmax_xmax_logging) +
		(SP_V2_NUM_MAX_SPKRS *
		 sizeof(struct afe_sp_v4_channel_tmax_xmax_params));
	memset(&param_hdr, 0, sizeof(param_hdr));

	param_hdr.module_id = AFE_MODULE_SPEAKER_PROTECTION_V4_RX;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_SP_V4_RX_TMAX_XMAX_LOGGING;
	param_hdr.param_size = size;

	ret = q6afe_get_params(port_id, NULL, &param_hdr);
	if (ret) {
		pr_err("%s: Failed to get Tmax Xmax logging data\n", __func__);
		goto get_params_fail;
	}

	tx_channel_params = &this_afe.spv4_max_log_resp.ch_max_params[0];
	for (i = 0; i < this_afe.spv4_max_log_resp.num_ch; i++) {

		xt_logging->max_excursion[i] =
			tx_channel_params[i].max_excursion;
		xt_logging->count_exceeded_excursion[i] =
			tx_channel_params[i].count_exceeded_excursion;
		xt_logging->max_temperature[i] =
			tx_channel_params[i].max_temperature;
		xt_logging->count_exceeded_temperature[i] =
			tx_channel_params[i].count_exceeded_temperature;
	}

	ret = 0;
get_params_fail:
done:
	return ret;
}

/**
 * afe_get_sp_rx_tmax_xmax_logging_data -
 *       command to get excursion logging data from DSP
 *
 * @xt_logging: excursion logging params
 * @port: AFE port ID
 *
 * Returns 0 on success or error on failure
 */
int afe_get_sp_rx_tmax_xmax_logging_data(
			struct afe_sp_rx_tmax_xmax_logging_param *xt_logging,
			u16 port_id)
{
	struct param_hdr_v3 param_hdr;
	int ret = -EINVAL;

	if (!xt_logging) {
		pr_err("%s: Invalid params\n", __func__);
		goto done;
	}

	mutex_lock(&this_afe.afe_cmd_lock);
	if (q6core_get_avcs_api_version_per_service(
		APRV2_IDS_SERVICE_ID_ADSP_AFE_V) >= AFE_API_VERSION_V9) {
		ret = afe_get_sp_v4_rx_tmax_xmax_logging_data(xt_logging,
								 port_id);
	} else {
		memset(&param_hdr, 0, sizeof(param_hdr));

		param_hdr.module_id = AFE_MODULE_FB_SPKR_PROT_V2_RX;
		param_hdr.instance_id = INSTANCE_ID_0;
		param_hdr.param_id = AFE_PARAM_ID_SP_RX_TMAX_XMAX_LOGGING;
		param_hdr.param_size =
			 sizeof(struct afe_sp_rx_tmax_xmax_logging_param);

		ret = q6afe_get_params(port_id, NULL, &param_hdr);
		if (ret < 0) {
			pr_err(
			"%s: get param port 0x%x param id[0x%x]failed %d\n",
			__func__, port_id, param_hdr.param_id, ret);
			goto get_params_fail;
		}

		memcpy(xt_logging, &this_afe.xt_logging_resp.param,
			sizeof(this_afe.xt_logging_resp.param));
	}
	pr_debug("%s: max_excursion %d %d count_exceeded_excursion %d %d"
		" max_temperature %d %d count_exceeded_temperature %d %d\n",
		 __func__, xt_logging->max_excursion[SP_V2_SPKR_1],
		 xt_logging->max_excursion[SP_V2_SPKR_2],
		 xt_logging->count_exceeded_excursion[SP_V2_SPKR_1],
		 xt_logging->count_exceeded_excursion[SP_V2_SPKR_2],
		 xt_logging->max_temperature[SP_V2_SPKR_1],
		 xt_logging->max_temperature[SP_V2_SPKR_2],
		 xt_logging->count_exceeded_temperature[SP_V2_SPKR_1],
		 xt_logging->count_exceeded_temperature[SP_V2_SPKR_2]);
get_params_fail:
	mutex_unlock(&this_afe.afe_cmd_lock);
done:
	return ret;
}
EXPORT_SYMBOL(afe_get_sp_rx_tmax_xmax_logging_data);

/**
 * afe_get_av_dev_drift -
 *       command to retrieve AV drift
 *
 * @timing_stats: timing stats to be updated with AV drift values
 * @port: AFE port ID
 *
 * Returns 0 on success or error on failure
 */
int afe_get_av_dev_drift(struct afe_param_id_dev_timing_stats *timing_stats,
			 u16 port)
{
	struct param_hdr_v3 param_hdr;
	int ret = -EINVAL;

	if (!timing_stats) {
		pr_err("%s: Invalid params\n", __func__);
		goto exit;
	}

	mutex_lock(&this_afe.afe_cmd_lock);
	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_AUDIO_DEV_INTERFACE;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_DEV_TIMING_STATS;
	param_hdr.param_size = sizeof(struct afe_param_id_dev_timing_stats);

	ret = q6afe_get_params(port, NULL, &param_hdr);
	if (ret < 0) {
		pr_err("%s: get param port 0x%x param id[0x%x] failed %d\n",
		       __func__, port, param_hdr.param_id, ret);
		goto get_params_fail;
	}

	memcpy(timing_stats, &this_afe.av_dev_drift_resp.timing_stats,
	       param_hdr.param_size);
	ret = 0;
get_params_fail:
	mutex_unlock(&this_afe.afe_cmd_lock);
exit:
	return ret;
}
EXPORT_SYMBOL(afe_get_av_dev_drift);

/**
 * afe_get_doa_tracking_mon -
 *       command to retrieve doa tracking monitor data
 *
 * @port: AFE port ID
 * @doa_tracking_data: param to be updated with doa tracking data
 *
 * Returns 0 on success or error on failure
 */
int afe_get_doa_tracking_mon(u16 port,
		struct doa_tracking_mon_param *doa_tracking_data)
{
	struct param_hdr_v3 param_hdr;
	int ret = -EINVAL, i = 0;

	if (!doa_tracking_data) {
		pr_err("%s: Invalid params\n", __func__);
		goto exit;
	}

	mutex_lock(&this_afe.afe_cmd_lock);
	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AUDPROC_MODULE_ID_FFNS;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AUDPROC_PARAM_ID_FFV_DOA_TRACKING_MONITOR;
	param_hdr.param_size = sizeof(struct doa_tracking_mon_param);

	ret = q6afe_get_params(port, NULL, &param_hdr);
	if (ret < 0) {
		pr_err("%s: get param port 0x%x param id[0x%x] failed %d\n",
			 __func__, port, param_hdr.param_id, ret);
		goto get_params_fail;
	}

	memcpy(doa_tracking_data, &this_afe.doa_tracking_mon_resp.doa,
			param_hdr.param_size);
	for (i = 0; i < MAX_DOA_TRACKING_ANGLES; i++) {
		pr_debug("%s: target angle[%d] = %d\n",
			 __func__, i, doa_tracking_data->target_angle_L16[i]);
		pr_debug("%s: interference angle[%d] = %d\n",
			 __func__, i, doa_tracking_data->interf_angle_L16[i]);
	}

get_params_fail:
	mutex_unlock(&this_afe.afe_cmd_lock);
exit:
	return ret;
}
EXPORT_SYMBOL(afe_get_doa_tracking_mon);

static int afe_spv4_get_calib_data(
		struct afe_sp_v4_th_vi_calib_resp *calib_resp)
{
	struct param_hdr_v3 param_hdr;
	int port = SLIMBUS_4_TX;
	int ret = -EINVAL;

	if (!calib_resp) {
		pr_err("%s: Invalid params\n", __func__);
		goto fail_cmd;
	}
	if (this_afe.vi_tx_port != -1)
		port = this_afe.vi_tx_port;

	mutex_lock(&this_afe.afe_cmd_lock);
	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_SPEAKER_PROTECTION_V4_VI;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_SP_V4_CALIB_RES_CFG;
	param_hdr.param_size = sizeof(struct afe_sp_v4_th_vi_calib_resp);

	ret = q6afe_get_params(port, NULL, &param_hdr);
	if (ret < 0) {
		pr_err("%s: get param port 0x%x param id[0x%x]failed %d\n",
		       __func__, port, param_hdr.param_id, ret);
		goto get_params_fail;
	}
	memcpy(&calib_resp->res_cfg, &this_afe.spv4_calib_data.res_cfg,
		sizeof(this_afe.calib_data.res_cfg));
	pr_info("%s: state %s resistance %d %d\n", __func__,
		fbsp_state[calib_resp->res_cfg.th_vi_ca_state],
		calib_resp->res_cfg.r0_cali_q24[SP_V2_SPKR_1],
		calib_resp->res_cfg.r0_cali_q24[SP_V2_SPKR_2]);
	ret = 0;
get_params_fail:
	mutex_unlock(&this_afe.afe_cmd_lock);
fail_cmd:
	return ret;
}

int afe_spk_prot_get_calib_data(struct afe_spkr_prot_get_vi_calib *calib_resp)
{
	struct param_hdr_v3 param_hdr;
	int port = SLIMBUS_4_TX;
	int ret = -EINVAL;

	if (!calib_resp) {
		pr_err("%s: Invalid params\n", __func__);
		goto fail_cmd;
	}
	if (this_afe.vi_tx_port != -1)
		port = this_afe.vi_tx_port;

	mutex_lock(&this_afe.afe_cmd_lock);
	memset(&param_hdr, 0, sizeof(param_hdr));
	param_hdr.module_id = AFE_MODULE_FB_SPKR_PROT_VI_PROC_V2;
	param_hdr.instance_id = INSTANCE_ID_0;
	param_hdr.param_id = AFE_PARAM_ID_CALIB_RES_CFG_V2;
	param_hdr.param_size = sizeof(struct afe_spkr_prot_get_vi_calib);

	ret = q6afe_get_params(port, NULL, &param_hdr);
	if (ret < 0) {
		pr_err("%s: get param port 0x%x param id[0x%x]failed %d\n",
		       __func__, port, param_hdr.param_id, ret);
		goto get_params_fail;
	}
	memcpy(&calib_resp->res_cfg, &this_afe.calib_data.res_cfg,
		sizeof(this_afe.calib_data.res_cfg));
	pr_info("%s: state %s resistance %d %d\n", __func__,
		fbsp_state[calib_resp->res_cfg.th_vi_ca_state],
		calib_resp->res_cfg.r0_cali_q24[SP_V2_SPKR_1],
		calib_resp->res_cfg.r0_cali_q24[SP_V2_SPKR_2]);
	ret = 0;
get_params_fail:
	mutex_unlock(&this_afe.afe_cmd_lock);
fail_cmd:
	return ret;
}

/**
 * afe_spk_prot_feed_back_cfg -
 *       command to setup spk protection feedback config
 *
 * @src_port: source port id
 * @dst_port: destination port id
 * @l_ch: left speaker active or not
 * @r_ch: right speaker active or not
 * @enable: flag to enable or disable
 *
 * Returns 0 on success or error on failure
 */
int afe_spk_prot_feed_back_cfg(int src_port, int dst_port,
	int l_ch, int r_ch, u32 enable)
{
	int ret = -EINVAL;
	union afe_spkr_prot_config prot_config;
	int index = 0;

	if (!enable) {
		pr_debug("%s: Disable Feedback tx path", __func__);
		this_afe.vi_tx_port = -1;
		this_afe.vi_rx_port = -1;
		return 0;
	}

	if ((q6audio_validate_port(src_port) < 0) ||
		(q6audio_validate_port(dst_port) < 0)) {
		pr_err("%s: invalid ports src 0x%x dst 0x%x",
			__func__, src_port, dst_port);
		goto fail_cmd;
	}
	if (!l_ch && !r_ch) {
		pr_err("%s: error ch values zero\n", __func__);
		goto fail_cmd;
	}
	pr_debug("%s: src_port 0x%x  dst_port 0x%x l_ch %d r_ch %d\n",
		 __func__, src_port, dst_port, l_ch, r_ch);
	if (q6core_get_avcs_api_version_per_service(
		APRV2_IDS_SERVICE_ID_ADSP_AFE_V) >= AFE_API_VERSION_V9) {
		if (l_ch) {
			this_afe.v4_ch_map_cfg.chan_info[index++] = 1;
			this_afe.v4_ch_map_cfg.chan_info[index++] = 2;
		}
		if (r_ch) {
			this_afe.v4_ch_map_cfg.chan_info[index++] = 3;
			this_afe.v4_ch_map_cfg.chan_info[index++] = 4;
		}
		this_afe.v4_ch_map_cfg.num_channels = index;
		this_afe.num_spkrs = index / 2;
	}

	index = 0;
	memset(&prot_config, 0, sizeof(prot_config));
	prot_config.feedback_path_cfg.dst_portid =
		q6audio_get_port_id(dst_port);
	if (l_ch) {
		prot_config.feedback_path_cfg.chan_info[index++] = 1;
		prot_config.feedback_path_cfg.chan_info[index++] = 2;
	}
	if (r_ch) {
		prot_config.feedback_path_cfg.chan_info[index++] = 3;
		prot_config.feedback_path_cfg.chan_info[index++] = 4;
	}

	prot_config.feedback_path_cfg.num_channels = index;
	pr_debug("%s no of channels: %d\n", __func__, index);
	prot_config.feedback_path_cfg.minor_version = 1;
	ret = afe_spk_prot_prepare(src_port, dst_port,
			AFE_PARAM_ID_FEEDBACK_PATH_CFG, &prot_config,
			 sizeof(union afe_spkr_prot_config));

fail_cmd:
	return ret;
}
EXPORT_SYMBOL(afe_spk_prot_feed_back_cfg);

static int get_cal_type_index(int32_t cal_type)
{
	int ret = -EINVAL;

	switch (cal_type) {
	case AFE_COMMON_RX_CAL_TYPE:
		ret = AFE_COMMON_RX_CAL;
		break;
	case AFE_COMMON_TX_CAL_TYPE:
		ret = AFE_COMMON_TX_CAL;
		break;
	case AFE_LSM_TX_CAL_TYPE:
		ret = AFE_LSM_TX_CAL;
		break;
	case AFE_AANC_CAL_TYPE:
		ret = AFE_AANC_CAL;
		break;
	case AFE_HW_DELAY_CAL_TYPE:
		ret = AFE_HW_DELAY_CAL;
		break;
	case AFE_FB_SPKR_PROT_CAL_TYPE:
		ret = AFE_FB_SPKR_PROT_CAL;
		break;
	case AFE_SIDETONE_CAL_TYPE:
		ret = AFE_SIDETONE_CAL;
		break;
	case AFE_SIDETONE_IIR_CAL_TYPE:
		ret = AFE_SIDETONE_IIR_CAL;
		break;
	case AFE_TOPOLOGY_CAL_TYPE:
		ret = AFE_TOPOLOGY_CAL;
		break;
	case AFE_LSM_TOPOLOGY_CAL_TYPE:
		ret = AFE_LSM_TOPOLOGY_CAL;
		break;
	case AFE_CUST_TOPOLOGY_CAL_TYPE:
		ret = AFE_CUST_TOPOLOGY_CAL;
		break;
	default:
		pr_err("%s: invalid cal type %d!\n", __func__, cal_type);
	}
	return ret;
}

int afe_alloc_cal(int32_t cal_type, size_t data_size,
						void *data)
{
	int				ret = 0;
	int				cal_index;

	cal_index = get_cal_type_index(cal_type);
	pr_debug("%s: cal_type = %d cal_index = %d\n",
		  __func__, cal_type, cal_index);

	if (cal_index < 0) {
		pr_err("%s: could not get cal index %d!\n",
			__func__, cal_index);
		ret = -EINVAL;
		goto done;
	}

	mutex_lock(&this_afe.afe_cmd_lock);
	ret = cal_utils_alloc_cal(data_size, data,
		this_afe.cal_data[cal_index], 0, NULL);
	if (ret < 0) {
		pr_err("%s: cal_utils_alloc_block failed, ret = %d, cal type = %d!\n",
			__func__, ret, cal_type);
		ret = -EINVAL;
		mutex_unlock(&this_afe.afe_cmd_lock);
		goto done;
	}
	mutex_unlock(&this_afe.afe_cmd_lock);
done:
	return ret;
}

static int afe_dealloc_cal(int32_t cal_type, size_t data_size,
							void *data)
{
	int ret = 0;
	int cal_index;

	pr_debug("%s:\n", __func__);

	cal_index = get_cal_type_index(cal_type);
	if (cal_index < 0) {
		pr_err("%s: could not get cal index %d!\n",
			__func__, cal_index);
		ret = -EINVAL;
		goto done;
	}

	ret = cal_utils_dealloc_cal(data_size, data,
		this_afe.cal_data[cal_index]);
	if (ret < 0) {
		pr_err("%s: cal_utils_dealloc_block failed, ret = %d, cal type = %d!\n",
			__func__, ret, cal_type);
		ret = -EINVAL;
		goto done;
	}
done:
	return ret;
}

static int afe_set_cal(int32_t cal_type, size_t data_size,
						void *data)
{
	int ret = 0;
	int cal_index;

	pr_debug("%s:\n", __func__);

	cal_index = get_cal_type_index(cal_type);
	if (cal_index < 0) {
		pr_err("%s: could not get cal index %d!\n",
			__func__, cal_index);
		ret = -EINVAL;
		goto done;
	}

	ret = cal_utils_set_cal(data_size, data,
		this_afe.cal_data[cal_index], 0, NULL);
	if (ret < 0) {
		pr_err("%s: cal_utils_set_cal failed, ret = %d, cal type = %d!\n",
			__func__, ret, cal_type);
		ret = -EINVAL;
		goto done;
	}

	if (cal_index == AFE_CUST_TOPOLOGY_CAL) {
		mutex_lock(&this_afe.cal_data[AFE_CUST_TOPOLOGY_CAL]->lock);
		this_afe.set_custom_topology = 1;
		pr_debug("%s:[AFE_CUSTOM_TOPOLOGY] ret = %d, cal type = %d!\n",
			__func__, ret, cal_type);
		mutex_unlock(&this_afe.cal_data[AFE_CUST_TOPOLOGY_CAL]->lock);
	}

done:
	return ret;
}

static struct cal_block_data *afe_find_hw_delay_by_path(
			struct cal_type_data *cal_type, int path)
{
	struct list_head *ptr, *next;
	struct cal_block_data *cal_block = NULL;

	pr_debug("%s:\n", __func__);

	list_for_each_safe(ptr, next,
		&cal_type->cal_blocks) {

		cal_block = list_entry(ptr,
			struct cal_block_data, list);

		if (cal_utils_is_cal_stale(cal_block))
			continue;

		if (((struct audio_cal_info_hw_delay *)cal_block->cal_info)
			->path == path) {
			return cal_block;
		}
	}
	return NULL;
}

static int afe_get_cal_hw_delay(int32_t path,
				struct audio_cal_hw_delay_entry *entry)
{
	int ret = 0;
	int i;
	struct cal_block_data		*cal_block = NULL;
	struct audio_cal_hw_delay_data	*hw_delay_info = NULL;

	pr_debug("%s:\n", __func__);

	if (this_afe.cal_data[AFE_HW_DELAY_CAL] == NULL) {
		pr_err("%s: AFE_HW_DELAY_CAL not initialized\n", __func__);
		ret = -EINVAL;
		goto done;
	}
	if (entry == NULL) {
		pr_err("%s: entry is NULL\n", __func__);
		ret = -EINVAL;
		goto done;
	}
	if ((path >= MAX_PATH_TYPE) || (path < 0)) {
		pr_err("%s: bad path: %d\n",
		       __func__, path);
		ret = -EINVAL;
		goto done;
	}

	mutex_lock(&this_afe.cal_data[AFE_HW_DELAY_CAL]->lock);
	cal_block = afe_find_hw_delay_by_path(
		this_afe.cal_data[AFE_HW_DELAY_CAL], path);
	if (cal_block == NULL)
		goto unlock;

	hw_delay_info = &((struct audio_cal_info_hw_delay *)
		cal_block->cal_info)->data;
	if (hw_delay_info->num_entries > MAX_HW_DELAY_ENTRIES) {
		pr_err("%s: invalid num entries: %d\n",
		       __func__, hw_delay_info->num_entries);
		ret = -EINVAL;
		goto unlock;
	}

	for (i = 0; i < hw_delay_info->num_entries; i++) {
		if (hw_delay_info->entry[i].sample_rate ==
			entry->sample_rate) {
			entry->delay_usec = hw_delay_info->entry[i].delay_usec;
			break;
		}
	}
	if (i == hw_delay_info->num_entries) {
		pr_err("%s: Unable to find delay for sample rate %d\n",
		       __func__, entry->sample_rate);
		ret = -EFAULT;
		goto unlock;
	}

	cal_utils_mark_cal_used(cal_block);
	pr_debug("%s: Path = %d samplerate = %u usec = %u status %d\n",
		 __func__, path, entry->sample_rate, entry->delay_usec, ret);
unlock:
	mutex_unlock(&this_afe.cal_data[AFE_HW_DELAY_CAL]->lock);
done:
	return ret;
}

static int afe_set_cal_sp_th_vi_v_vali_cfg(int32_t cal_type, size_t data_size,
					void *data)
{
	int ret = 0;
	struct audio_cal_type_sp_th_vi_v_vali_cfg *cal_data = data;

	if (cal_data == NULL || data_size != sizeof(*cal_data))
		goto done;

	memcpy(&this_afe.v_vali_cfg, &cal_data->cal_info,
		sizeof(this_afe.v_vali_cfg));
done:
	return ret;
}

static int afe_set_cal_sp_th_vi_ftm_cfg(int32_t cal_type, size_t data_size,
					void *data)
{
	int ret = 0;
	struct audio_cal_type_sp_th_vi_ftm_cfg *cal_data = data;

	if (cal_data == NULL || data_size != sizeof(*cal_data))
		goto done;

	memcpy(&this_afe.th_ftm_cfg, &cal_data->cal_info,
		sizeof(this_afe.th_ftm_cfg));
done:
	return ret;
}

static int afe_set_cal_sp_th_vi_cfg(int32_t cal_type, size_t data_size,
				    void *data)
{
	int ret = 0;
	struct audio_cal_type_sp_th_vi_ftm_cfg *cal_data = data;
	uint32_t mode;

	if (cal_data == NULL ||
	    data_size > sizeof(*cal_data) ||
	    (data_size < sizeof(cal_data->cal_hdr) +
		sizeof(cal_data->cal_data) +
		sizeof(cal_data->cal_info.mode)) ||
	    this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL] == NULL)
		goto done;

	mutex_lock(&this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL]->lock);
	mode = cal_data->cal_info.mode;
	pr_debug("%s: cal_type = %d, mode = %d\n", __func__, cal_type, mode);
	if (mode == MSM_SPKR_PROT_IN_FTM_MODE) {
		ret = afe_set_cal_sp_th_vi_ftm_cfg(cal_type,
						data_size, data);
	} else if (mode == MSM_SPKR_PROT_IN_V_VALI_MODE) {
		ret = afe_set_cal_sp_th_vi_v_vali_cfg(cal_type,
						data_size, data);
	}
	mutex_unlock(&this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL]->lock);
done:
	return ret;
}

static int afe_set_cal_sp_ex_vi_ftm_cfg(int32_t cal_type, size_t data_size,
					void *data)
{
	int ret = 0;
	struct audio_cal_type_sp_ex_vi_ftm_cfg *cal_data = data;

	if (this_afe.cal_data[AFE_FB_SPKR_PROT_EX_VI_CAL] == NULL ||
	    cal_data == NULL ||
	    data_size != sizeof(*cal_data))
		goto done;

	pr_debug("%s: cal_type = %d\n", __func__, cal_type);
	mutex_lock(&this_afe.cal_data[AFE_FB_SPKR_PROT_EX_VI_CAL]->lock);
	memcpy(&this_afe.ex_ftm_cfg, &cal_data->cal_info,
		sizeof(this_afe.ex_ftm_cfg));
	mutex_unlock(&this_afe.cal_data[AFE_FB_SPKR_PROT_EX_VI_CAL]->lock);
done:
	return ret;
}

static int afe_set_cal_fb_spkr_prot(int32_t cal_type, size_t data_size,
								void *data)
{
	int ret = 0;
	struct audio_cal_type_fb_spk_prot_cfg	*cal_data = data;

	pr_debug("%s:\n", __func__);

	if (this_afe.cal_data[AFE_FB_SPKR_PROT_CAL] == NULL)
		goto done;
	if (cal_data == NULL)
		goto done;
	if (data_size != sizeof(*cal_data))
		goto done;

	if (cal_data->cal_info.mode == MSM_SPKR_PROT_CALIBRATION_IN_PROGRESS)
		__pm_wakeup_event(wl.ws, jiffies_to_msecs(WAKELOCK_TIMEOUT));
	mutex_lock(&this_afe.cal_data[AFE_FB_SPKR_PROT_CAL]->lock);
	memcpy(&this_afe.prot_cfg, &cal_data->cal_info,
		sizeof(this_afe.prot_cfg));
	mutex_unlock(&this_afe.cal_data[AFE_FB_SPKR_PROT_CAL]->lock);
done:
	return ret;
}

static int afe_get_cal_sp_th_vi_v_vali_param(int32_t cal_type, size_t data_size,
					  void *data)
{
	int i, ret = 0;
	struct audio_cal_type_sp_th_vi_v_vali_param *cal_data = data;
	struct afe_sp_th_vi_v_vali_get_param th_vi_v_vali;
	uint32_t size;
	void *params = NULL;
	struct afe_sp_v4_channel_v_vali_params *v_vali_params;

	if (this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL] == NULL ||
	    cal_data == NULL ||
	    data_size != sizeof(*cal_data))
		goto done;

	for (i = 0; i < SP_V2_NUM_MAX_SPKRS; i++) {
		cal_data->cal_info.status[i] = -EINVAL;
		cal_data->cal_info.vrms_q24[i] = -1;
	}
	if (q6core_get_avcs_api_version_per_service(
		APRV2_IDS_SERVICE_ID_ADSP_AFE_V) >= AFE_API_VERSION_V9) {
		size = sizeof(struct afe_sp_v4_param_th_vi_v_vali_params) +
			(SP_V2_NUM_MAX_SPKRS *
			 sizeof(struct afe_sp_v4_channel_v_vali_params));
		params = kzalloc(size, GFP_KERNEL);
		if (!params)
			return -ENOMEM;
		v_vali_params =
		    (struct afe_sp_v4_channel_v_vali_params *)((u8 *)params +
		    sizeof(struct afe_sp_v4_param_th_vi_v_vali_params));

		if (!afe_get_spv4_th_vi_v_vali_data(params, size)) {
			for (i = 0; i < SP_V2_NUM_MAX_SPKRS; i++) {
				pr_debug("%s: ftm param status = %d\n",
					  __func__, v_vali_params[i].status);
				if (v_vali_params[i].status ==
							 V_VALI_IN_PROGRESS) {
					cal_data->cal_info.status[i] = -EAGAIN;
				} else if (v_vali_params[i].status ==
							 V_VALI_SUCCESS) {
					cal_data->cal_info.status[i] =
						V_VALI_SUCCESS;
					cal_data->cal_info.vrms_q24[i] =
						v_vali_params[i].vrms_q24;
				}
			}
		}
		kfree(params);
	} else {
		if (!afe_get_sp_th_vi_v_vali_data(&th_vi_v_vali)) {
			for (i = 0; i < SP_V2_NUM_MAX_SPKRS; i++) {
				pr_debug(
				"%s: v-vali param status = %d\n",
				__func__, th_vi_v_vali.param.status[i]);
				if (th_vi_v_vali.param.status[i] ==
						V_VALI_IN_PROGRESS) {
					cal_data->cal_info.status[i] = -EAGAIN;
				} else if (th_vi_v_vali.param.status[i] ==
						V_VALI_SUCCESS) {
					cal_data->cal_info.status[i] =
					 V_VALI_SUCCESS;
					cal_data->cal_info.vrms_q24[i] =
						th_vi_v_vali.param.vrms_q24[i];
				}
			}
		}
	}
	this_afe.v_vali_flag = 0;
done:
	return ret;
}

static int afe_get_cal_sp_th_vi_ftm_param(int32_t cal_type, size_t data_size,
					  void *data)
{
	int i, ret = 0;
	struct audio_cal_type_sp_th_vi_param *cal_data = data;
	struct afe_sp_th_vi_get_param th_vi;
	uint32_t size;
	void *params = NULL;
	struct afe_sp_v4_channel_ftm_params *th_vi_ftm_params;

	if (this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL] == NULL ||
	    cal_data == NULL ||
	    data_size != sizeof(*cal_data))
		goto done;

	for (i = 0; i < SP_V2_NUM_MAX_SPKRS; i++) {
		cal_data->cal_info.status[i] = -EINVAL;
		cal_data->cal_info.r_dc_q24[i] = -1;
		cal_data->cal_info.temp_q22[i] = -1;
	}
	if (q6core_get_avcs_api_version_per_service(
		APRV2_IDS_SERVICE_ID_ADSP_AFE_V) >= AFE_API_VERSION_V9) {
		size = sizeof(struct afe_sp_v4_param_th_vi_ftm_params) +
			(SP_V2_NUM_MAX_SPKRS *
			 sizeof(struct afe_sp_v4_channel_ftm_params));
		params = kzalloc(size, GFP_KERNEL);
		if (!params)
			return -ENOMEM;
		th_vi_ftm_params = (struct afe_sp_v4_channel_ftm_params *)
		((u8 *)params +
		sizeof(struct afe_sp_v4_param_th_vi_ftm_params));

		if (!afe_get_spv4_th_vi_ftm_data(params, size)) {
			for (i = 0; i < SP_V2_NUM_MAX_SPKRS; i++) {
				pr_debug("%s: SP V4 ftm param status = %d\n",
					  __func__, th_vi_ftm_params[i].status);
				if (th_vi_ftm_params[i].status ==
							 FBSP_IN_PROGRESS) {
					cal_data->cal_info.status[i] = -EAGAIN;
				} else if (th_vi_ftm_params[i].status ==
							 FBSP_SUCCESS) {
					cal_data->cal_info.status[i] = 0;
					cal_data->cal_info.r_dc_q24[i] =
						th_vi_ftm_params[i].dc_res_q24;
					cal_data->cal_info.temp_q22[i] =
						th_vi_ftm_params[i].temp_q22;
				}
			}
		}
		kfree(params);
	} else {

		if (!afe_get_sp_th_vi_ftm_data(&th_vi)) {
			for (i = 0; i < SP_V2_NUM_MAX_SPKRS; i++) {
				pr_debug("%s: ftm param status = %d\n",
					  __func__, th_vi.param.status[i]);
				if (th_vi.param.status[i] == FBSP_IN_PROGRESS) {
					cal_data->cal_info.status[i] = -EAGAIN;
				} else if (th_vi.param.status[i] ==
								 FBSP_SUCCESS) {
					cal_data->cal_info.status[i] = 0;
					cal_data->cal_info.r_dc_q24[i] =
						th_vi.param.dc_res_q24[i];
					cal_data->cal_info.temp_q22[i] =
						th_vi.param.temp_q22[i];
				}
			}
		}
	}
done:
	return ret;
}

static int afe_get_cal_sp_th_vi_param(int32_t cal_type, size_t data_size,
				      void *data)
{
	struct audio_cal_type_sp_th_vi_param *cal_data = data;
	uint32_t mode;
	int ret = 0;

	if (cal_data == NULL ||
	    data_size > sizeof(*cal_data) ||
	    (data_size < sizeof(cal_data->cal_hdr) +
		sizeof(cal_data->cal_data) +
		sizeof(cal_data->cal_info.mode)) ||
	    this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL] == NULL)
		return 0;

	mutex_lock(&this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL]->lock);
	mode = cal_data->cal_info.mode;
	pr_debug("%s: cal_type = %d,mode = %d\n", __func__, cal_type, mode);
	if (mode == MSM_SPKR_PROT_IN_V_VALI_MODE)
		ret = afe_get_cal_sp_th_vi_v_vali_param(cal_type,
						data_size, data);
	else
		ret = afe_get_cal_sp_th_vi_ftm_param(cal_type,
						data_size, data);
	mutex_unlock(&this_afe.cal_data[AFE_FB_SPKR_PROT_TH_VI_CAL]->lock);
	return ret;
}

static int afe_get_cal_spv4_ex_vi_ftm_param(int32_t cal_type, size_t data_size,
					  void *data)
{
	int i, ret = 0;
	struct audio_cal_type_sp_v4_ex_vi_param *cal_data = data;
	uint32_t size;
	void *params = NULL;
	struct afe_sp_v4_channel_ex_vi_ftm_params *ex_vi_ftm_param;

	pr_debug("%s: cal_type = %d\n", __func__, cal_type);
	if (this_afe.cal_data[AFE_FB_SPKR_PROT_V4_EX_VI_CAL] == NULL ||
	    cal_data == NULL ||
	    data_size != sizeof(*cal_data))
		goto done;

	mutex_lock(&this_afe.cal_data[AFE_FB_SPKR_PROT_V4_EX_VI_CAL]->lock);
	for (i = 0; i < SP_V2_NUM_MAX_SPKRS; i++) {
		cal_data->cal_info.status[i] = -EINVAL;
		cal_data->cal_info.ftm_re_q24[i] = -1;
		cal_data->cal_info.ftm_re_q24[i] = -1;
		cal_data->cal_info.ftm_Rms_q24[i] = -1;
		cal_data->cal_info.ftm_Kms_q24[i] = -1;
		cal_data->cal_info.ftm_freq_q20[i] = -1;
		cal_data->cal_info.ftm_Qms_q24[i] = -1;
	}

	size = sizeof(struct afe_sp_v4_param_ex_vi_ftm_params) +
		(SP_V2_NUM_MAX_SPKRS *
		sizeof(struct afe_sp_v4_channel_ex_vi_ftm_params));
	params = kzalloc(size, GFP_KERNEL);
	if (!params) {
		mutex_unlock(
		  &this_afe.cal_data[AFE_FB_SPKR_PROT_V4_EX_VI_CAL]->lock);
		return -ENOMEM;
	}
	ex_vi_ftm_param = (struct afe_sp_v4_channel_ex_vi_ftm_params *)
		((u8 *)params +
		sizeof(struct afe_sp_v4_param_ex_vi_ftm_params));

	if (!afe_get_spv4_ex_vi_ftm_data(params, size)) {
		for (i = 0; i < SP_V2_NUM_MAX_SPKRS; i++) {
			pr_debug("%s: ftm param status = %d\n",
				  __func__, ex_vi_ftm_param[i].status);
			if (ex_vi_ftm_param[i].status == FBSP_IN_PROGRESS) {
				cal_data->cal_info.status[i] = -EAGAIN;
			} else if (ex_vi_ftm_param[i].status == FBSP_SUCCESS) {
				cal_data->cal_info.status[i] = 0;
				cal_data->cal_info.ftm_re_q24[i] =
					ex_vi_ftm_param[i].ftm_re_q24;
				cal_data->cal_info.ftm_Bl_q24[i] =
					ex_vi_ftm_param[i].ftm_Bl_q24;
				cal_data->cal_info.ftm_Rms_q24[i] =
					ex_vi_ftm_param[i].ftm_Rms_q24;
				cal_data->cal_info.ftm_Kms_q24[i] =
					ex_vi_ftm_param[i].ftm_Kms_q24;
				cal_data->cal_info.ftm_freq_q20[i] =
					ex_vi_ftm_param[i].ftm_Fres_q20;
				cal_data->cal_info.ftm_Qms_q24[i] =
					ex_vi_ftm_param[i].ftm_Qms_q24;
			}
		}
	}
	kfree(params);

	mutex_unlock(&this_afe.cal_data[AFE_FB_SPKR_PROT_V4_EX_VI_CAL]->lock);
done:
	return ret;
}

static int afe_get_cal_sp_ex_vi_ftm_param(int32_t cal_type, size_t data_size,
					  void *data)
{
	int i, ret = 0;
	struct audio_cal_type_sp_ex_vi_param *cal_data = data;
	struct afe_sp_ex_vi_get_param ex_vi;

	pr_debug("%s: cal_type = %d\n", __func__, cal_type);
	if (this_afe.cal_data[AFE_FB_SPKR_PROT_EX_VI_CAL] == NULL ||
	    cal_data == NULL ||
	    data_size != sizeof(*cal_data))
		goto done;

	mutex_lock(&this_afe.cal_data[AFE_FB_SPKR_PROT_EX_VI_CAL]->lock);
	for (i = 0; i < SP_V2_NUM_MAX_SPKRS; i++) {
		cal_data->cal_info.status[i] = -EINVAL;
		cal_data->cal_info.freq_q20[i] = -1;
		cal_data->cal_info.resis_q24[i] = -1;
		cal_data->cal_info.qmct_q24[i] = -1;
	}
	if (!afe_get_sp_ex_vi_ftm_data(&ex_vi)) {
		for (i = 0; i < SP_V2_NUM_MAX_SPKRS; i++) {
			pr_debug("%s: ftm param status = %d\n",
				  __func__, ex_vi.param.status[i]);
			if (ex_vi.param.status[i] == FBSP_IN_PROGRESS) {
				cal_data->cal_info.status[i] = -EAGAIN;
			} else if (ex_vi.param.status[i] == FBSP_SUCCESS) {
				cal_data->cal_info.status[i] = 0;
				cal_data->cal_info.freq_q20[i] =
					ex_vi.param.freq_q20[i];
				cal_data->cal_info.resis_q24[i] =
					ex_vi.param.resis_q24[i];
				cal_data->cal_info.qmct_q24[i] =
					ex_vi.param.qmct_q24[i];
			}
		}
	}
	mutex_unlock(&this_afe.cal_data[AFE_FB_SPKR_PROT_EX_VI_CAL]->lock);
done:
	return ret;
}

static int afe_get_cal_fb_spkr_prot(int32_t cal_type, size_t data_size,
								void *data)
{
	int ret = 0;
	struct audio_cal_type_fb_spk_prot_status *cal_data = data;
	struct afe_spkr_prot_get_vi_calib calib_resp;
	struct afe_sp_v4_th_vi_calib_resp spv4_calib_resp;

	pr_debug("%s:\n", __func__);

	if (this_afe.cal_data[AFE_FB_SPKR_PROT_CAL] == NULL)
		goto done;
	if (cal_data == NULL)
		goto done;
	if (data_size != sizeof(*cal_data))
		goto done;

	mutex_lock(&this_afe.cal_data[AFE_FB_SPKR_PROT_CAL]->lock);
	if (this_afe.prot_cfg.mode == MSM_SPKR_PROT_CALIBRATED) {
		cal_data->cal_info.r0[SP_V2_SPKR_1] =
			this_afe.prot_cfg.r0[SP_V2_SPKR_1];
		cal_data->cal_info.r0[SP_V2_SPKR_2] =
			this_afe.prot_cfg.r0[SP_V2_SPKR_2];
		cal_data->cal_info.status = 0;
	} else if (this_afe.prot_cfg.mode ==
			MSM_SPKR_PROT_CALIBRATION_IN_PROGRESS) {
		/*Call AFE to query the status*/
		cal_data->cal_info.status = -EINVAL;
		cal_data->cal_info.r0[SP_V2_SPKR_1] = -1;
		cal_data->cal_info.r0[SP_V2_SPKR_2] = -1;
		if (this_afe.prot_cfg.sp_version >= AFE_API_VERSION_V9) {
			if (!(q6core_get_avcs_api_version_per_service(
				APRV2_IDS_SERVICE_ID_ADSP_AFE_V) >=
							 AFE_API_VERSION_V9)) {
				pr_debug(
				"%s: AFE API version is not supported!\n",
				__func__);
				goto done;
			}
			if (!afe_spv4_get_calib_data(&spv4_calib_resp)) {
				if (spv4_calib_resp.res_cfg.th_vi_ca_state ==
							FBSP_IN_PROGRESS)
					cal_data->cal_info.status = -EAGAIN;
				else if (
				    spv4_calib_resp.res_cfg.th_vi_ca_state ==
							FBSP_SUCCESS) {
					cal_data->cal_info.status = 0;
					cal_data->cal_info.r0[SP_V2_SPKR_1] =
					spv4_calib_resp.res_cfg.r0_cali_q24[
					    SP_V2_SPKR_1];
					cal_data->cal_info.r0[SP_V2_SPKR_2] =
					spv4_calib_resp.res_cfg.r0_cali_q24[
					    SP_V2_SPKR_2];
				}
			}
		} else {

			if (!afe_spk_prot_get_calib_data(&calib_resp)) {
				if (calib_resp.res_cfg.th_vi_ca_state ==
							FBSP_IN_PROGRESS)
					cal_data->cal_info.status = -EAGAIN;
				else if (calib_resp.res_cfg.th_vi_ca_state ==
								FBSP_SUCCESS) {
					cal_data->cal_info.status = 0;
					cal_data->cal_info.r0[SP_V2_SPKR_1] =
					calib_resp.res_cfg.r0_cali_q24[
					    SP_V2_SPKR_1];
					cal_data->cal_info.r0[SP_V2_SPKR_2] =
					calib_resp.res_cfg.r0_cali_q24[
					    SP_V2_SPKR_2];
				}
			}
		}
		if (!cal_data->cal_info.status) {
			this_afe.prot_cfg.mode =
				MSM_SPKR_PROT_CALIBRATED;
			this_afe.prot_cfg.r0[SP_V2_SPKR_1] =
				cal_data->cal_info.r0[SP_V2_SPKR_1];
			this_afe.prot_cfg.r0[SP_V2_SPKR_2] =
				cal_data->cal_info.r0[SP_V2_SPKR_2];
		}
	} else {
		/*Indicates calibration data is invalid*/
		cal_data->cal_info.status = -EINVAL;
		cal_data->cal_info.r0[SP_V2_SPKR_1] = -1;
		cal_data->cal_info.r0[SP_V2_SPKR_2] = -1;
	}
	this_afe.initial_cal = 0;
	mutex_unlock(&this_afe.cal_data[AFE_FB_SPKR_PROT_CAL]->lock);
	__pm_relax(wl.ws);
done:
	return ret;
}

static int afe_map_cal_data(int32_t cal_type,
				struct cal_block_data *cal_block)
{
	int ret = 0;
	int cal_index;

	pr_debug("%s:\n", __func__);

	cal_index = get_cal_type_index(cal_type);
	if (cal_index < 0) {
		pr_err("%s: could not get cal index %d!\n",
			__func__, cal_index);
		ret = -EINVAL;
		goto done;
	}

	atomic_set(&this_afe.mem_map_cal_index, cal_index);
	ret = afe_cmd_memory_map(cal_block->cal_data.paddr,
			cal_block->map_data.map_size);
	atomic_set(&this_afe.mem_map_cal_index, -1);
	if (ret < 0) {
		pr_err("%s: mmap did not work! size = %zd ret %d\n",
			__func__,
			cal_block->map_data.map_size, ret);
		pr_debug("%s: mmap did not work! addr = 0x%pK, size = %zd\n",
			__func__,
			&cal_block->cal_data.paddr,
			cal_block->map_data.map_size);
		goto done;
	}
	cal_block->map_data.q6map_handle = atomic_read(&this_afe.
		mem_map_cal_handles[cal_index]);
done:
	return ret;
}

static int afe_unmap_cal_data(int32_t cal_type,
				struct cal_block_data *cal_block)
{
	int ret = 0;
	int cal_index;

	pr_debug("%s:\n", __func__);

	cal_index = get_cal_type_index(cal_type);
	if (cal_index < 0) {
		pr_err("%s: could not get cal index %d!\n",
			__func__, cal_index);
		ret = -EINVAL;
		goto done;
	}

	if (cal_block == NULL) {
		pr_err("%s: Cal block is NULL!\n",
						__func__);
		goto done;
	}

	if (cal_block->map_data.q6map_handle == 0) {
		pr_err("%s: Map handle is NULL, nothing to unmap\n",
				__func__);
		goto done;
	}

	atomic_set(&this_afe.mem_map_cal_handles[cal_index],
		cal_block->map_data.q6map_handle);
	atomic_set(&this_afe.mem_map_cal_index, cal_index);
	ret = afe_cmd_memory_unmap_nowait(
		cal_block->map_data.q6map_handle);
	atomic_set(&this_afe.mem_map_cal_index, -1);
	if (ret < 0) {
		pr_err("%s: unmap did not work! cal_type %i ret %d\n",
			__func__, cal_index, ret);
	}
	cal_block->map_data.q6map_handle = 0;
done:
	return ret;
}

static void afe_delete_cal_data(void)
{
	pr_debug("%s:\n", __func__);

	cal_utils_destroy_cal_types(MAX_AFE_CAL_TYPES, this_afe.cal_data);
}

static int afe_init_cal_data(void)
{
	int ret = 0;
	struct cal_type_info	cal_type_info[] = {
		{{AFE_COMMON_RX_CAL_TYPE,
		{afe_alloc_cal, afe_dealloc_cal, NULL,
		afe_set_cal, NULL, NULL} },
		{afe_map_cal_data, afe_unmap_cal_data,
		cal_utils_match_buf_num} },

		{{AFE_COMMON_TX_CAL_TYPE,
		{afe_alloc_cal, afe_dealloc_cal, NULL,
		afe_set_cal, NULL, NULL} },
		{afe_map_cal_data, afe_unmap_cal_data,
		cal_utils_match_buf_num} },

		{{AFE_LSM_TX_CAL_TYPE,
		{afe_alloc_cal, afe_dealloc_cal, NULL,
		afe_set_cal, NULL, NULL} },
		{afe_map_cal_data, afe_unmap_cal_data,
		cal_utils_match_buf_num} },

		{{AFE_AANC_CAL_TYPE,
		{afe_alloc_cal, afe_dealloc_cal, NULL,
		afe_set_cal, NULL, NULL} },
		{afe_map_cal_data, afe_unmap_cal_data,
		cal_utils_match_buf_num} },

		{{AFE_FB_SPKR_PROT_CAL_TYPE,
		{NULL, NULL, NULL, afe_set_cal_fb_spkr_prot,
		afe_get_cal_fb_spkr_prot, NULL} },
		{NULL, NULL, cal_utils_match_buf_num} },

		{{AFE_HW_DELAY_CAL_TYPE,
		{NULL, NULL, NULL,
		afe_set_cal, NULL, NULL} },
		{NULL, NULL, cal_utils_match_buf_num} },

		{{AFE_SIDETONE_CAL_TYPE,
		{NULL, NULL, NULL,
		afe_set_cal, NULL, NULL} },
		{NULL, NULL, cal_utils_match_buf_num} },

		{{AFE_SIDETONE_IIR_CAL_TYPE,
		{NULL, NULL, NULL,
		afe_set_cal, NULL, NULL} },
		{NULL, NULL, cal_utils_match_buf_num} },

		{{AFE_TOPOLOGY_CAL_TYPE,
		{NULL, NULL, NULL,
		afe_set_cal, NULL, NULL} },
		{NULL, NULL,
		cal_utils_match_buf_num} },

		{{AFE_LSM_TOPOLOGY_CAL_TYPE,
		{NULL, NULL, NULL,
		afe_set_cal, NULL, NULL} },
		{NULL, NULL,
		cal_utils_match_buf_num} },

		{{AFE_CUST_TOPOLOGY_CAL_TYPE,
		{afe_alloc_cal, afe_dealloc_cal, NULL,
		afe_set_cal, NULL, NULL} },
		{afe_map_cal_data, afe_unmap_cal_data,
		cal_utils_match_buf_num} },

		{{AFE_FB_SPKR_PROT_TH_VI_CAL_TYPE,
		{NULL, NULL, NULL, afe_set_cal_sp_th_vi_cfg,
		afe_get_cal_sp_th_vi_param, NULL} },
		{NULL, NULL, cal_utils_match_buf_num} },

		{{AFE_FB_SPKR_PROT_EX_VI_CAL_TYPE,
		{NULL, NULL, NULL, afe_set_cal_sp_ex_vi_ftm_cfg,
		afe_get_cal_sp_ex_vi_ftm_param, NULL} },
		{NULL, NULL, cal_utils_match_buf_num} },

		{{AFE_FB_SPKR_PROT_V4_EX_VI_CAL_TYPE,
		{NULL, NULL, NULL, NULL,
		afe_get_cal_spv4_ex_vi_ftm_param, NULL} },
		{NULL, NULL, cal_utils_match_buf_num} },
	};
	pr_debug("%s:\n", __func__);

	ret = cal_utils_create_cal_types(MAX_AFE_CAL_TYPES, this_afe.cal_data,
		cal_type_info);
	if (ret < 0) {
		pr_err("%s: could not create cal type! %d\n",
			__func__, ret);
		ret = -EINVAL;
		goto err;
	}

	return ret;
err:
	afe_delete_cal_data();
	return ret;
}

int afe_map_rtac_block(struct rtac_cal_block_data *cal_block)
{
	int result = 0;

	pr_debug("%s:\n", __func__);

	if (cal_block == NULL) {
		pr_err("%s: cal_block is NULL!\n",
			__func__);
		result = -EINVAL;
		goto done;
	}

	if (cal_block->cal_data.paddr == 0) {
		pr_debug("%s: No address to map!\n",
			__func__);
		result = -EINVAL;
		goto done;
	}

	if (cal_block->map_data.map_size == 0) {
		pr_debug("%s: map size is 0!\n",
			__func__);
		result = -EINVAL;
		goto done;
	}

	result = afe_cmd_memory_map(cal_block->cal_data.paddr,
		cal_block->map_data.map_size);
	if (result < 0) {
		pr_err("%s: afe_cmd_memory_map failed for addr = 0x%pK, size = %d, err %d\n",
			__func__, &cal_block->cal_data.paddr,
			cal_block->map_data.map_size, result);
		return result;
	}
	cal_block->map_data.map_handle = this_afe.mmap_handle;

done:
	return result;
}

int afe_unmap_rtac_block(uint32_t *mem_map_handle)
{
	int result = 0;

	pr_debug("%s:\n", __func__);

	if (mem_map_handle == NULL) {
		pr_err("%s: Map handle is NULL, nothing to unmap\n",
			__func__);
		goto done;
	}

	if (*mem_map_handle == 0) {
		pr_debug("%s: Map handle is 0, nothing to unmap\n",
			__func__);
		goto done;
	}

	result = afe_cmd_memory_unmap(*mem_map_handle);
	if (result) {
		pr_err("%s: AFE memory unmap failed %d, handle 0x%x\n",
		     __func__, result, *mem_map_handle);
		goto done;
	} else {
		*mem_map_handle = 0;
	}

done:
	return result;
}

static void afe_release_uevent_data(struct kobject *kobj)
{
	struct audio_uevent_data *data = container_of(kobj,
		struct audio_uevent_data, kobj);

	kfree(data);
}

int __init afe_init(void)
{
	int i = 0, ret;

	atomic_set(&this_afe.state, 0);
	atomic_set(&this_afe.status, 0);
	atomic_set(&this_afe.clk_state, 0);
	atomic_set(&this_afe.clk_status, 0);
	atomic_set(&this_afe.mem_map_cal_index, -1);
	this_afe.apr = NULL;
	this_afe.dtmf_gen_rx_portid = -1;
	this_afe.mmap_handle = 0;
	this_afe.vi_tx_port = -1;
	this_afe.vi_rx_port = -1;
	for (i = 0; i < AFE_LPASS_CORE_HW_VOTE_MAX; i++)
		this_afe.lpass_hw_core_client_hdl[i] = 0;
	this_afe.prot_cfg.mode = MSM_SPKR_PROT_DISABLED;
	this_afe.th_ftm_cfg.mode = MSM_SPKR_PROT_DISABLED;
	this_afe.ex_ftm_cfg.mode = MSM_SPKR_PROT_DISABLED;
	mutex_init(&this_afe.afe_cmd_lock);
	mutex_init(&this_afe.afe_apr_lock);
	mutex_init(&this_afe.afe_clk_lock);
	for (i = 0; i < AFE_MAX_PORTS; i++) {
		this_afe.afe_cal_mode[i] = AFE_CAL_MODE_DEFAULT;
		this_afe.afe_sample_rates[i] = 0;
		this_afe.dev_acdb_id[i] = 0;
		this_afe.island_mode[i] = 0;
		this_afe.vad_cfg[i].is_enable = 0;
		this_afe.vad_cfg[i].pre_roll = 0;
		init_waitqueue_head(&this_afe.wait[i]);
	}
	init_waitqueue_head(&this_afe.wait_wakeup);
	init_waitqueue_head(&this_afe.lpass_core_hw_wait);
	init_waitqueue_head(&this_afe.clk_wait);
	for (i = 0; i < MAX_LSM_SESSIONS; i++)
		this_afe.lsm_afe_ports[i] = 0xffff;
	ret = afe_init_cal_data();
	if (ret)
		pr_err("%s: could not init cal data! %d\n", __func__, ret);

	config_debug_fs_init();

	this_afe.uevent_data = kzalloc(sizeof(*(this_afe.uevent_data)), GFP_KERNEL);
	if (!this_afe.uevent_data)
		return -ENOMEM;
#if (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 19, 110))
	wl.ws = wakeup_source_register(NULL, "spkr-prot");
#else
	wl.ws = wakeup_source_register("spkr-prot");
#endif
	/*
	 * Set release function to cleanup memory related to kobject
	 * before initializing the kobject.
	 */
	this_afe.uevent_data->ktype.release = afe_release_uevent_data;
	q6core_init_uevent_data(this_afe.uevent_data, "q6afe_uevent");

	INIT_WORK(&this_afe.afe_dc_work, afe_notify_dc_presence_work_fn);
	INIT_WORK(&this_afe.afe_spdif_work,
		  afe_notify_spdif_fmt_update_work_fn);

	this_afe.event_notifier.notifier_call  = afe_aud_event_notify;
	msm_aud_evt_blocking_register_client(&this_afe.event_notifier);

	return 0;
}

void afe_exit(void)
{
	if (this_afe.apr) {
		apr_reset(this_afe.apr);
		atomic_set(&this_afe.state, 0);
		this_afe.apr = NULL;
		rtac_set_afe_handle(this_afe.apr);
	}

	q6core_destroy_uevent_data(this_afe.uevent_data);

	afe_delete_cal_data();

	config_debug_fs_exit();
	mutex_destroy(&this_afe.afe_cmd_lock);
	mutex_destroy(&this_afe.afe_apr_lock);
	mutex_destroy(&this_afe.afe_clk_lock);
	wakeup_source_unregister(wl.ws);
}

/*
 * afe_cal_init_hwdep -
 *        Initiliaze AFE HW dependent Node
 *
 * @card: pointer to sound card
 *
 */
int afe_cal_init_hwdep(void *card)
{
	int ret = 0;

	this_afe.fw_data = kzalloc(sizeof(*(this_afe.fw_data)),
				      GFP_KERNEL);
	if (!this_afe.fw_data)
		return -ENOMEM;

	set_bit(Q6AFE_VAD_CORE_CAL, this_afe.fw_data->cal_bit);
	ret = q6afe_cal_create_hwdep(this_afe.fw_data, Q6AFE_HWDEP_NODE, card);
	if (ret < 0) {
		pr_err("%s: couldn't create hwdep for AFE %d\n", __func__, ret);
		return ret;
	}
	return ret;
}
EXPORT_SYMBOL(afe_cal_init_hwdep);

/*
 * afe_vote_lpass_core_hw -
 *        Voting for lpass core hardware
 *
 * @hw_block_id: id of the hardware block
 * @client_name: client name
 * @client_handle: client handle
 *
 */
int afe_vote_lpass_core_hw(uint32_t hw_block_id, char *client_name,
			uint32_t *client_handle)
{
	struct afe_cmd_remote_lpass_core_hw_vote_request hw_vote_cfg;
	struct afe_cmd_remote_lpass_core_hw_vote_request *cmd_ptr =
						&hw_vote_cfg;
	int ret = 0;

	if (!client_handle) {
		pr_err("%s: Invalid client_handle\n", __func__);
		return -EINVAL;
	}

	if (!client_name) {
		pr_err("%s: Invalid client_name\n", __func__);
		*client_handle = 0;
		return -EINVAL;
	}

	ret = afe_q6_interface_prepare();
	if(ret) {
		pr_err("%s: Q6 interface prepare failed %d\n", __func__, ret);
		return ret;
	}

	mutex_lock(&this_afe.afe_clk_lock);

	memset(cmd_ptr, 0, sizeof(hw_vote_cfg));

	cmd_ptr->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE),
				APR_PKT_VER);
	cmd_ptr->hdr.pkt_size = sizeof(hw_vote_cfg);
	cmd_ptr->hdr.src_port = 0;
	cmd_ptr->hdr.dest_port = 0;
	cmd_ptr->hdr.token = hw_block_id;
	cmd_ptr->hdr.opcode = AFE_CMD_REMOTE_LPASS_CORE_HW_VOTE_REQUEST;
	cmd_ptr->hw_block_id = hw_block_id;
	strlcpy(cmd_ptr->client_name, client_name,
			sizeof(cmd_ptr->client_name));

	pr_debug("%s: lpass core hw vote opcode[0x%x] hw id[0x%x]\n",
		__func__, cmd_ptr->hdr.opcode, cmd_ptr->hw_block_id);

	trace_printk("%s: lpass core hw vote opcode[0x%x] hw id[0x%x]\n",
		__func__, cmd_ptr->hdr.opcode, cmd_ptr->hw_block_id);
	*client_handle = 0;

	ret = afe_apr_send_clk_pkt((uint32_t *)cmd_ptr,
				&this_afe.lpass_core_hw_wait);
	if (ret == 0) {
		*client_handle = this_afe.lpass_hw_core_client_hdl[hw_block_id];
		pr_debug("%s: lpass_hw_core_client_hdl %d\n", __func__,
			this_afe.lpass_hw_core_client_hdl[hw_block_id]);
	}
	mutex_unlock(&this_afe.afe_clk_lock);
	return ret;
}
EXPORT_SYMBOL(afe_vote_lpass_core_hw);

/*
 * afe_unvote_lpass_core_hw -
 *        unvoting for lpass core hardware
 *
 * @hw_block_id: id of the hardware block
 * @client_handle: client handle
 *
 */
int afe_unvote_lpass_core_hw(uint32_t hw_block_id, uint32_t client_handle)
{
	struct afe_cmd_remote_lpass_core_hw_devote_request hw_vote_cfg;
	struct afe_cmd_remote_lpass_core_hw_devote_request *cmd_ptr =
						&hw_vote_cfg;
	int ret = 0;

	ret = afe_q6_interface_prepare();
	if(ret) {
		pr_err("%s: Q6 interface prepare failed %d\n", __func__, ret);
		return ret;
	}

	mutex_lock(&this_afe.afe_clk_lock);

	if (!this_afe.lpass_hw_core_client_hdl[hw_block_id]) {
		pr_debug("%s: SSR in progress, return\n", __func__);
		trace_printk("%s: SSR in progress, return\n", __func__);
		goto done;
	}

	memset(cmd_ptr, 0, sizeof(hw_vote_cfg));

	cmd_ptr->hdr.hdr_field = APR_HDR_FIELD(APR_MSG_TYPE_SEQ_CMD,
				APR_HDR_LEN(APR_HDR_SIZE),
				APR_PKT_VER);
	cmd_ptr->hdr.pkt_size = sizeof(hw_vote_cfg);
	cmd_ptr->hdr.src_port = 0;
	cmd_ptr->hdr.dest_port = 0;
	cmd_ptr->hdr.token = 0;
	cmd_ptr->hdr.opcode = AFE_CMD_REMOTE_LPASS_CORE_HW_DEVOTE_REQUEST;
	cmd_ptr->hw_block_id = hw_block_id;
	cmd_ptr->client_handle = client_handle;

	pr_debug("%s: lpass core hw unvote opcode[0x%x] hw id[0x%x]\n",
		__func__, cmd_ptr->hdr.opcode, cmd_ptr->hw_block_id);

	trace_printk("%s: lpass core hw unvote opcode[0x%x] hw id[0x%x]\n",
		__func__, cmd_ptr->hdr.opcode, cmd_ptr->hw_block_id);

	if (cmd_ptr->client_handle <= 0) {
		pr_err("%s: invalid client handle\n", __func__);
		ret = -EINVAL;
		goto done;
	}

	ret = afe_apr_send_clk_pkt((uint32_t *)cmd_ptr,
				&this_afe.lpass_core_hw_wait);
done:
	mutex_unlock(&this_afe.afe_clk_lock);
	return ret;
}
EXPORT_SYMBOL(afe_unvote_lpass_core_hw);

/**
 * afe_set_cps_config -
 *         to set cps speaker protection configuration
 *
 * @src_port: source port to send configuration to
 * @cps_config: cps speaker protection v4 configuration
 * @ch_mask: channel mask
 *
 */
void afe_set_cps_config(int src_port,
			struct afe_cps_hw_intf_cfg *cps_config,
			u32 ch_mask)
{
	this_afe.cps_config = NULL;
	this_afe.cps_ch_mask = 0;

	if (!cps_config) {
		pr_err("%s: cps config is NULL\n", __func__);
		return;
	}

	if (q6audio_validate_port(src_port) < 0) {
		pr_err("%s: Invalid src port 0x%x\n", __func__, src_port);
		return;
	}

	this_afe.cps_ch_mask = ch_mask;
	this_afe.cps_config = cps_config;
}
EXPORT_SYMBOL(afe_set_cps_config);

static bool q6afe_is_afe_lsm_port(int port_id)
{
	int i = 0;

	for (i = 0; i < MAX_LSM_SESSIONS; i++) {
		if (port_id == this_afe.lsm_afe_ports[i])
			return true;
	}
	return false;
}

/**
 * afe_set_lsm_afe_port_id -
 *            Update LSM AFE port
 * idx: LSM port index
 * lsm_port: LSM port id
*/
void afe_set_lsm_afe_port_id(int idx, int lsm_port)
{
	if (idx < 0 || idx >= MAX_LSM_SESSIONS) {
		pr_err("%s: %d Invalid lsm port index\n", __func__, idx);
		return;
	}
	this_afe.lsm_afe_ports[idx] = lsm_port;
}
EXPORT_SYMBOL(afe_set_lsm_afe_port_id);