aboutsummaryrefslogtreecommitdiff
path: root/src/api.c
blob: 35ae4c2a554c48885f04d4771cc4cd4a4aec172b (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
/*
 * Copyright 2022 The Hafnium Authors.
 *
 * Use of this source code is governed by a BSD-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/BSD-3-Clause.
 */

#include "hf/api.h"

#include "hf/arch/cpu.h"
#include "hf/arch/ffa.h"
#include "hf/arch/mm.h"
#include "hf/arch/other_world.h"
#include "hf/arch/plat/ffa.h"
#include "hf/arch/timer.h"
#include "hf/arch/vm.h"

#include "hf/check.h"
#include "hf/dlog.h"
#include "hf/ffa_internal.h"
#include "hf/ffa_memory.h"
#include "hf/mm.h"
#include "hf/plat/console.h"
#include "hf/plat/interrupts.h"
#include "hf/spinlock.h"
#include "hf/static_assert.h"
#include "hf/std.h"
#include "hf/vm.h"

#include "vmapi/hf/call.h"
#include "vmapi/hf/ffa.h"

static_assert(sizeof(struct ffa_partition_info_v1_0) == 8,
	      "Partition information descriptor size doesn't match the one in "
	      "the FF-A 1.0 EAC specification, Table 82.");
static_assert(sizeof(struct ffa_partition_info) == 24,
	      "Partition information descriptor size doesn't match the one in "
	      "the FF-A 1.1 BETA0 EAC specification, Table 13.34.");

/*
 * To eliminate the risk of deadlocks, we define a partial order for the
 * acquisition of locks held concurrently by the same physical CPU. Our current
 * ordering requirements are as follows:
 *
 * vm::lock -> vcpu::lock -> mm_stage1_lock -> dlog sl
 *
 * Locks of the same kind require the lock of lowest address to be locked first,
 * see `sl_lock_both()`.
 */

static_assert(HF_MAILBOX_SIZE == PAGE_SIZE,
	      "Currently, a page is mapped for the send and receive buffers so "
	      "the maximum request is the size of a page.");

static_assert(MM_PPOOL_ENTRY_SIZE >= HF_MAILBOX_SIZE,
	      "The page pool entry size must be at least as big as the mailbox "
	      "size, so that memory region descriptors can be copied from the "
	      "mailbox for memory sharing.");

static struct mpool api_page_pool;

/**
 * Initialises the API page pool by taking ownership of the contents of the
 * given page pool.
 */
void api_init(struct mpool *ppool)
{
	mpool_init_from(&api_page_pool, ppool);
}

/**
 * Get target VM vCPU:
 * If VM is UP then return first vCPU.
 * If VM is MP then return vCPU whose index matches current CPU index.
 */
struct vcpu *api_ffa_get_vm_vcpu(struct vm *vm, struct vcpu *current)
{
	ffa_vcpu_index_t current_cpu_index = cpu_index(current->cpu);
	struct vcpu *vcpu = NULL;

	CHECK((vm != NULL) && (current != NULL));

	if (vm->vcpu_count == 1) {
		vcpu = vm_get_vcpu(vm, 0);
	} else if (current_cpu_index < vm->vcpu_count) {
		vcpu = vm_get_vcpu(vm, current_cpu_index);
	}

	return vcpu;
}

/**
 * Switches the physical CPU back to the corresponding vCPU of the VM whose ID
 * is given as argument of the function.
 *
 * Called to change the context between SPs for direct messaging (when Hafnium
 * is SPMC), and on the context of the remaining 'api_switch_to_*' functions.
 *
 * This function works for partitions that are:
 * - UP migratable.
 * - MP with pinned Execution Contexts.
 */
static struct vcpu *api_switch_to_vm(struct vcpu *current,
				     struct ffa_value to_ret,
				     enum vcpu_state vcpu_state,
				     ffa_vm_id_t to_id)
{
	struct vm *to_vm = vm_find(to_id);
	struct vcpu *next = api_ffa_get_vm_vcpu(to_vm, current);

	CHECK(next != NULL);

	/* Set the return value for the target VM. */
	arch_regs_set_retval(&next->regs, to_ret);

	/* Set the current vCPU state. */
	sl_lock(&current->lock);
	current->state = vcpu_state;
	sl_unlock(&current->lock);

	return next;
}

/**
 * Switches the physical CPU back to the corresponding vCPU of the primary VM.
 *
 * This triggers the scheduling logic to run. Run in the context of secondary VM
 * to cause FFA_RUN to return and the primary VM to regain control of the CPU.
 */
static struct vcpu *api_switch_to_primary(struct vcpu *current,
					  struct ffa_value primary_ret,
					  enum vcpu_state secondary_state)
{
	/*
	 * If the secondary is blocked but has a timer running, sleep until the
	 * timer fires rather than indefinitely.
	 */
	switch (primary_ret.func) {
	case HF_FFA_RUN_WAIT_FOR_INTERRUPT:
	case FFA_MSG_WAIT_32: {
		if (arch_timer_enabled_current()) {
			uint64_t remaining_ns =
				arch_timer_remaining_ns_current();

			if (remaining_ns == 0) {
				/*
				 * Timer is pending, so the current vCPU should
				 * be run again right away.
				 */
				primary_ret = (struct ffa_value){
					.func = FFA_INTERRUPT_32};

			} else {
				primary_ret.arg2 = remaining_ns;
			}
		} else {
			primary_ret.arg2 = FFA_SLEEP_INDEFINITE;
		}
		break;
	}

	default:
		/* Do nothing. */
		break;
	}

	return api_switch_to_vm(current, primary_ret, secondary_state,
				HF_PRIMARY_VM_ID);
}

/**
 * Choose next vCPU to run to be the counterpart vCPU in the other
 * world (run the normal world if currently running in the secure
 * world). Set current vCPU state to the given vcpu_state parameter.
 * Set FF-A return values to the target vCPU in the other world.
 *
 * Called in context of a direct message response from a secure
 * partition to a VM.
 */
struct vcpu *api_switch_to_other_world(struct vcpu *current,
				       struct ffa_value other_world_ret,
				       enum vcpu_state vcpu_state)
{
	return api_switch_to_vm(current, other_world_ret, vcpu_state,
				HF_OTHER_WORLD_ID);
}

/**
 * Checks whether the given `to` VM's mailbox is currently busy, and optionally
 * registers the `from` VM to be notified when it becomes available.
 */
static bool msg_receiver_busy(struct vm_locked to, struct vm *from, bool notify)
{
	if (to.vm->mailbox.state != MAILBOX_STATE_EMPTY ||
	    to.vm->mailbox.recv == NULL) {
		/*
		 * Fail if the receiver isn't currently ready to receive data,
		 * setting up for notification if requested.
		 */
		if (notify) {
			struct wait_entry *entry =
				vm_get_wait_entry(from, to.vm->id);

			/* Append waiter only if it's not there yet. */
			if (list_empty(&entry->wait_links)) {
				list_append(&to.vm->mailbox.waiter_list,
					    &entry->wait_links);
			}
		}

		return true;
	}

	return false;
}

/**
 * Returns true if the given vCPU is executing in context of an
 * FFA_MSG_SEND_DIRECT_REQ invocation.
 */
static bool is_ffa_direct_msg_request_ongoing(struct vcpu_locked locked)
{
	return locked.vcpu->direct_request_origin_vm_id != HF_INVALID_VM_ID;
}

/**
 * Returns true if the VM owning the given vCPU is supporting managed exit and
 * the vCPU is currently processing a managed exit.
 */
static bool api_ffa_is_managed_exit_ongoing(struct vcpu_locked vcpu_locked)
{
	return (plat_ffa_vm_managed_exit_supported(vcpu_locked.vcpu->vm) &&
		vcpu_locked.vcpu->processing_managed_exit);
}

/**
 * Returns to the primary VM and signals that the vCPU still has work to do so.
 */
struct vcpu *api_preempt(struct vcpu *current)
{
	struct ffa_value ret = {
		.func = FFA_INTERRUPT_32,
		.arg1 = ffa_vm_vcpu(current->vm->id, vcpu_index(current)),
	};

	return api_switch_to_primary(current, ret, VCPU_STATE_PREEMPTED);
}

/**
 * Puts the current vCPU in wait for interrupt mode, and returns to the primary
 * VM.
 */
struct vcpu *api_wait_for_interrupt(struct vcpu *current)
{
	struct ffa_value ret = {
		.func = HF_FFA_RUN_WAIT_FOR_INTERRUPT,
		.arg1 = ffa_vm_vcpu(current->vm->id, vcpu_index(current)),
	};

	return api_switch_to_primary(current, ret,
				     VCPU_STATE_BLOCKED_INTERRUPT);
}

/**
 * Puts the current vCPU in off mode, and returns to the primary VM.
 */
struct vcpu *api_vcpu_off(struct vcpu *current)
{
	struct ffa_value ret = {
		.func = HF_FFA_RUN_WAIT_FOR_INTERRUPT,
		.arg1 = ffa_vm_vcpu(current->vm->id, vcpu_index(current)),
	};

	/*
	 * Disable the timer, so the scheduler doesn't get told to call back
	 * based on it.
	 */
	arch_timer_disable_current();

	return api_switch_to_primary(current, ret, VCPU_STATE_OFF);
}

/**
 * The current vCPU is blocked on some resource and needs to relinquish
 * control back to the execution context of the endpoint that originally
 * allocated cycles to it.
 */
struct ffa_value api_yield(struct vcpu *current, struct vcpu **next)
{
	struct ffa_value ret = (struct ffa_value){.func = FFA_SUCCESS_32};
	struct vcpu_locked current_locked;
	bool is_direct_request_ongoing;

	if (current->vm->id == HF_PRIMARY_VM_ID) {
		/* NOOP on the primary as it makes the scheduling decisions. */
		return ret;
	}

	current_locked = vcpu_lock(current);
	is_direct_request_ongoing =
		is_ffa_direct_msg_request_ongoing(current_locked);
	vcpu_unlock(&current_locked);

	if (is_direct_request_ongoing) {
		return ffa_error(FFA_DENIED);
	}

	*next = api_switch_to_primary(
		current,
		(struct ffa_value){.func = FFA_YIELD_32,
				   .arg1 = ffa_vm_vcpu(current->vm->id,
						       vcpu_index(current))},
		VCPU_STATE_BLOCKED);

	return ret;
}

/**
 * Switches to the primary so that it can switch to the target, or kick it if it
 * is already running on a different physical CPU.
 */
struct vcpu *api_wake_up(struct vcpu *current, struct vcpu *target_vcpu)
{
	struct ffa_value ret = {
		.func = FFA_INTERRUPT_32,
		.arg1 = ffa_vm_vcpu(target_vcpu->vm->id,
				    vcpu_index(target_vcpu)),
	};
	return api_switch_to_primary(current, ret, VCPU_STATE_BLOCKED);
}

/**
 * Aborts the vCPU and triggers its VM to abort fully.
 */
struct vcpu *api_abort(struct vcpu *current)
{
	struct ffa_value ret = ffa_error(FFA_ABORTED);

	dlog_notice("Aborting VM %#x vCPU %u\n", current->vm->id,
		    vcpu_index(current));

	if (current->vm->id == HF_PRIMARY_VM_ID) {
		/* TODO: what to do when the primary aborts? */
		for (;;) {
			/* Do nothing. */
		}
	}

	atomic_store_explicit(&current->vm->aborting, true,
			      memory_order_relaxed);

	/* TODO: free resources once all vCPUs abort. */

	return api_switch_to_primary(current, ret, VCPU_STATE_ABORTED);
}

/*
 * Format the partition info descriptors according to the version supported
 * by the endpoint and return the size of the array created.
 */
static struct ffa_value send_versioned_partition_info_descriptors(
	struct vm_locked vm_locked, struct ffa_partition_info *partitions,
	uint32_t vm_count)
{
	struct vm *vm = vm_locked.vm;
	uint32_t version = vm->ffa_version;
	uint32_t partition_info_size;
	uint32_t buffer_size;
	struct ffa_value ret;

	if (msg_receiver_busy(vm_locked, NULL, false)) {
		/*
		 * Can't retrieve memory information if the mailbox is not
		 * available.
		 */
		dlog_verbose("RX buffer not ready.\n");
		return ffa_error(FFA_BUSY);
	}

	/* Acquire receiver's RX buffer. */
	if (!plat_ffa_acquire_receiver_rx(vm_locked, &ret)) {
		dlog_verbose("Failed to acquire RX buffer for VM %x\n", vm->id);
		return ret;
	}

	if (version == MAKE_FFA_VERSION(1, 0)) {
		struct ffa_partition_info_v1_0 *recv_mailbox = vm->mailbox.recv;

		partition_info_size = sizeof(struct ffa_partition_info_v1_0);
		buffer_size = partition_info_size * vm_count;
		if (buffer_size > HF_MAILBOX_SIZE) {
			dlog_error(
				"Partition information does not fit in the "
				"VM's RX "
				"buffer.\n");
			return ffa_error(FFA_NO_MEMORY);
		}

		for (uint32_t i = 0; i < vm_count; i++) {
			/*
			 * Populate the VM's RX buffer with the partition
			 * information.
			 */
			recv_mailbox[i].vm_id = partitions[i].vm_id;
			recv_mailbox[i].vcpu_count = partitions[i].vcpu_count;
			recv_mailbox[i].properties = partitions[i].properties;
		}

	} else {
		partition_info_size = sizeof(struct ffa_partition_info);
		buffer_size = partition_info_size * vm_count;
		if (buffer_size > HF_MAILBOX_SIZE) {
			dlog_error(
				"Partition information does not fit in the "
				"VM's RX "
				"buffer.\n");
			return ffa_error(FFA_NO_MEMORY);
		}

		/* Populate the VM's RX buffer with the partition information.
		 */
		memcpy_s(vm->mailbox.recv, HF_MAILBOX_SIZE, partitions,
			 buffer_size);
	}

	vm->mailbox.recv_size = buffer_size;

	/* Sender is Hypervisor in the normal world (TEE in secure world). */
	vm->mailbox.recv_sender = HF_VM_ID_BASE;
	vm->mailbox.recv_func = FFA_PARTITION_INFO_GET_32;
	vm->mailbox.state = MAILBOX_STATE_READ;

	/*
	 * Return the count of partition information descriptors in w2
	 * and the size of the descriptors in w3.
	 */
	return (struct ffa_value){.func = FFA_SUCCESS_32,
				  .arg2 = vm_count,
				  .arg3 = partition_info_size};
}

struct ffa_value api_ffa_partition_info_get(struct vcpu *current,
					    const struct ffa_uuid *uuid,
					    const uint32_t flags)
{
	struct vm *current_vm = current->vm;
	ffa_vm_count_t vm_count = 0;
	bool count_flag = (flags && FFA_PARTITION_COUNT_FLAG_MASK) ==
			  FFA_PARTITION_COUNT_FLAG;
	bool uuid_is_null = ffa_uuid_is_null(uuid);
	struct ffa_partition_info partitions[2 * MAX_VMS] = {0};
	struct vm_locked vm_locked;
	struct ffa_value ret;

	/* Bits 31:1 Must Be Zero */
	if ((flags & ~FFA_PARTITION_COUNT_FLAG) != 0) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/*
	 * No need to count if we are returning the number of paritions as we
	 * already know this.
	 */
	if (uuid_is_null && count_flag) {
		vm_count = vm_get_count();
	} else {
		/*
		 * Iterate through the VMs to find the ones with a matching
		 * UUID. A Null UUID retrieves information for all VMs.
		 */
		for (uint16_t index = 0; index < vm_get_count(); ++index) {
			struct vm *vm = vm_find_index(index);

			if (uuid_is_null || ffa_uuid_equal(uuid, &vm->uuid)) {
				uint16_t array_index = vm_count;

				++vm_count;
				if (count_flag) {
					continue;
				}

				partitions[array_index].vm_id = vm->id;
				partitions[array_index].vcpu_count =
					vm->vcpu_count;
				partitions[array_index].properties =
					plat_ffa_partition_properties(
						current_vm->id, vm);
				partitions[array_index].properties |=
					vm_are_notifications_enabled(vm)
						? FFA_PARTITION_NOTIFICATION
						: 0;
				if (uuid_is_null) {
					partitions[array_index].uuid = vm->uuid;
				}
			}
		}
	}

	/* If UUID is Null vm_count must not be zero at this stage. */
	CHECK(!uuid_is_null || vm_count != 0);

	/*
	 * When running the Hypervisor:
	 * - If UUID is Null the Hypervisor forwards the query to the SPMC for
	 * it to fill with secure partitions information.
	 * - If UUID is non-Null vm_count may be zero because the UUID matches
	 * a secure partition and the query is forwarded to the SPMC.
	 * When running the SPMC:
	 * - If UUID is non-Null and vm_count is zero it means there is no such
	 * partition identified in the system.
	 */
	plat_ffa_partition_info_get_forward(uuid, flags, partitions, &vm_count);

	/*
	 * Unrecognized UUID: does not match any of the VMs (or SPs)
	 * and is not Null.
	 */
	if (vm_count == 0) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/*
	 * If the count flag is set we don't need to return the partition info
	 * descriptors.
	 */
	if (count_flag) {
		return (struct ffa_value){.func = FFA_SUCCESS_32,
					  .arg2 = vm_count};
	}

	vm_locked = vm_lock(current_vm);
	ret = send_versioned_partition_info_descriptors(vm_locked, partitions,
							vm_count);
	vm_unlock(&vm_locked);
	return ret;
}

/**
 * Returns the ID of the VM.
 */
struct ffa_value api_ffa_id_get(const struct vcpu *current)
{
	return (struct ffa_value){.func = FFA_SUCCESS_32,
				  .arg2 = current->vm->id};
}

/**
 * Returns the SPMC FF-A ID at NS virtual/physical and secure virtual
 * FF-A instances.
 * DEN0077A FF-A v1.1 Beta0 section 13.9 FFA_SPM_ID_GET.
 */
struct ffa_value api_ffa_spm_id_get(void)
{
#if (MAKE_FFA_VERSION(1, 1) <= FFA_VERSION_COMPILED)
	/*
	 * Return the SPMC ID that was fetched during FF-A
	 * initialization.
	 */
	return (struct ffa_value){.func = FFA_SUCCESS_32,
				  .arg2 = arch_ffa_spmc_id_get()};
#else
	return ffa_error(FFA_NOT_SUPPORTED);
#endif
}

/**
 * This function is called by the architecture-specific context switching
 * function to indicate that register state for the given vCPU has been saved
 * and can therefore be used by other pCPUs.
 */
void api_regs_state_saved(struct vcpu *vcpu)
{
	sl_lock(&vcpu->lock);
	vcpu->regs_available = true;
	sl_unlock(&vcpu->lock);
}

/**
 * Retrieves the next waiter and removes it from the wait list if the VM's
 * mailbox is in a writable state.
 */
static struct wait_entry *api_fetch_waiter(struct vm_locked locked_vm)
{
	struct wait_entry *entry;
	struct vm *vm = locked_vm.vm;

	if (vm->mailbox.state != MAILBOX_STATE_EMPTY ||
	    vm->mailbox.recv == NULL || list_empty(&vm->mailbox.waiter_list)) {
		/* The mailbox is not writable or there are no waiters. */
		return NULL;
	}

	/* Remove waiter from the wait list. */
	entry = CONTAINER_OF(vm->mailbox.waiter_list.next, struct wait_entry,
			     wait_links);
	list_remove(&entry->wait_links);
	return entry;
}

/**
 * Assuming that the arguments have already been checked by the caller, injects
 * a virtual interrupt of the given ID into the given target vCPU. This doesn't
 * cause the vCPU to actually be run immediately; it will be taken when the vCPU
 * is next run, which is up to the scheduler.
 *
 * Returns:
 *  - 0 on success if no further action is needed.
 *  - 1 if it was called by the primary VM and the primary VM now needs to wake
 *    up or kick the target vCPU.
 */
int64_t api_interrupt_inject_locked(struct vcpu_locked target_locked,
				    uint32_t intid, struct vcpu *current,
				    struct vcpu **next)
{
	struct vcpu *target_vcpu = target_locked.vcpu;
	struct interrupts *interrupts = &target_vcpu->interrupts;
	int64_t ret = 0;

	/*
	 * We only need to change state and (maybe) trigger a virtual interrupt
	 * if it is enabled and was not previously pending. Otherwise we can
	 * skip everything except setting the pending bit.
	 */
	if (!(vcpu_is_virt_interrupt_enabled(interrupts, intid) &&
	      !vcpu_is_virt_interrupt_pending(interrupts, intid))) {
		goto out;
	}

	/* Increment the count. */
	vcpu_interrupt_count_increment(target_locked, interrupts, intid);

	/*
	 * Only need to update state if there was not already an
	 * interrupt enabled and pending.
	 */
	if (vcpu_interrupt_count_get(target_locked) != 1) {
		goto out;
	}

	if (current->vm->id == HF_PRIMARY_VM_ID) {
		/*
		 * If the call came from the primary VM, let it know that it
		 * should run or kick the target vCPU.
		 */
		ret = 1;
	} else if (current != target_vcpu && next != NULL) {
		*next = api_wake_up(current, target_vcpu);
	}

out:
	/* Either way, make it pending. */
	vcpu_virt_interrupt_set_pending(interrupts, intid);

	return ret;
}

/* Wrapper to internal_interrupt_inject with locking of target vCPU */
static int64_t internal_interrupt_inject(struct vcpu *target_vcpu,
					 uint32_t intid, struct vcpu *current,
					 struct vcpu **next)
{
	int64_t ret;
	struct vcpu_locked target_locked;

	target_locked = vcpu_lock(target_vcpu);
	ret = api_interrupt_inject_locked(target_locked, intid, current, next);
	vcpu_unlock(&target_locked);

	return ret;
}

/**
 * Constructs the return value from a successful FFA_MSG_POLL or
 * FFA_MSG_WAIT call.
 *
 * Note: FFA_MSG_POLL is deprecated in FF-A v1.1 and should not be used with
 * FFA_MSG_SEND2; no check is done on mixing FF-A v1.0 and FF-A v1.1 indirect
 * message protocols.
 */
static struct ffa_value ffa_msg_recv_return(const struct vm *receiver)
{
	switch (receiver->mailbox.recv_func) {
	case FFA_MSG_SEND_32:
		return (struct ffa_value){
			.func = FFA_MSG_SEND_32,
			.arg1 = (receiver->mailbox.recv_sender << 16) |
				receiver->id,
			.arg3 = receiver->mailbox.recv_size};
	case FFA_MSG_SEND2_32:
		return (struct ffa_value){
			.func = FFA_RUN_32,
			/*
			 * TODO: FFA_RUN should return vCPU and VM ID in arg1.
			 * Retrieving vCPU requires a rework of the function,
			 * while receiver ID must be set because it's checked by
			 * other APIs (eg: FFA_NOTIFICATION_GET).
			 */
			.arg1 = receiver->id};
	default:
		/* This should never be reached, but return an error in case. */
		dlog_error("Tried to return an invalid message function %#x\n",
			   receiver->mailbox.recv_func);
		return ffa_error(FFA_DENIED);
	}
}

struct ffa_value api_ffa_msg_wait(struct vcpu *current, struct vcpu **next,
				  struct ffa_value *args)
{
	struct ffa_value ret;

	if (args->arg1 != 0U || args->arg2 != 0U || args->arg3 != 0U ||
	    args->arg4 != 0U || args->arg5 != 0U || args->arg6 != 0U ||
	    args->arg7 != 0U) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	if (plat_ffa_msg_wait_prepare(current, next, &ret)) {
		return ret;
	}

	return api_ffa_msg_recv(true, current, next);
}

/**
 * Prepares the vCPU to run by updating its state and fetching whether a return
 * value needs to be forced onto the vCPU.
 */
static bool api_vcpu_prepare_run(struct vcpu *current, struct vcpu *vcpu,
				 struct ffa_value *run_ret)
{
	struct vcpu_locked vcpu_locked;
	struct vm_locked vm_locked;
	bool ret;
	uint64_t timer_remaining_ns = FFA_SLEEP_INDEFINITE;
	bool need_vm_lock;

	/*
	 * Check that the registers are available so that the vCPU can be run.
	 *
	 * The VM lock is not needed in the common case so it must only be taken
	 * when it is going to be needed. This ensures there are no inter-vCPU
	 * dependencies in the common run case meaning the sensitive context
	 * switch performance is consistent.
	 */
	vcpu_locked = vcpu_lock(vcpu);

#if SECURE_WORLD == 1
	bool is_vcpu_reset_and_start = vcpu_secondary_reset_and_start(
		vcpu_locked, vcpu->vm->secondary_ep, 0);
	if (is_vcpu_reset_and_start) {
		dlog_verbose("%s secondary cold boot vmid %#x vcpu id %#x\n",
			     __func__, vcpu->vm->id, current->cpu->id);
	}

#endif
	/* The VM needs to be locked to deliver mailbox messages. */
	need_vm_lock = vcpu->state == VCPU_STATE_WAITING ||
		       (!vcpu->vm->el0_partition &&
			(vcpu->state == VCPU_STATE_BLOCKED_INTERRUPT ||
			 vcpu->state == VCPU_STATE_BLOCKED ||
			 vcpu->state == VCPU_STATE_PREEMPTED));

	if (need_vm_lock) {
		vcpu_unlock(&vcpu_locked);
		vm_locked = vm_lock(vcpu->vm);
		vcpu_locked = vcpu_lock(vcpu);
	}

	/*
	 * If the vCPU is already running somewhere then we can't run it here
	 * simultaneously. While it is actually running then the state should be
	 * `VCPU_STATE_RUNNING` and `regs_available` should be false. Once it
	 * stops running but while Hafnium is in the process of switching back
	 * to the primary there will be a brief period while the state has been
	 * updated but `regs_available` is still false (until
	 * `api_regs_state_saved` is called). We can't start running it again
	 * until this has finished, so count this state as still running for the
	 * purposes of this check.
	 */
	if (vcpu->state == VCPU_STATE_RUNNING || !vcpu->regs_available) {
		/*
		 * vCPU is running on another pCPU.
		 *
		 * It's okay not to return the sleep duration here because the
		 * other physical CPU that is currently running this vCPU will
		 * return the sleep duration if needed.
		 */
		*run_ret = ffa_error(FFA_BUSY);
		ret = false;
		goto out;
	}

	if (atomic_load_explicit(&vcpu->vm->aborting, memory_order_relaxed)) {
		if (vcpu->state != VCPU_STATE_ABORTED) {
			dlog_notice("Aborting VM %#x vCPU %u\n", vcpu->vm->id,
				    vcpu_index(vcpu));
			vcpu->state = VCPU_STATE_ABORTED;
		}
		ret = false;
		goto out;
	}

	switch (vcpu->state) {
	case VCPU_STATE_RUNNING:
	case VCPU_STATE_OFF:
	case VCPU_STATE_ABORTED:
		ret = false;
		goto out;

	case VCPU_STATE_WAITING:
		/*
		 * An initial FFA_RUN is necessary for secondary VM/SP to reach
		 * the message wait loop.
		 */
		if (!vcpu->is_bootstrapped) {
			vcpu->is_bootstrapped = true;
			break;
		}

		assert(need_vm_lock == true);
		if (!vm_locked.vm->el0_partition &&
		    plat_ffa_inject_notification_pending_interrupt(
			    vcpu_locked, current, vm_locked)) {
			break;
		}

		/*
		 * A pending message allows the vCPU to run so the message can
		 * be delivered directly.
		 */
		if (vcpu->vm->mailbox.state == MAILBOX_STATE_RECEIVED) {
			arch_regs_set_retval(&vcpu->regs,
					     ffa_msg_recv_return(vcpu->vm));
			if (vcpu->vm->mailbox.recv_func == FFA_MSG_SEND_32) {
				vcpu->vm->mailbox.state = MAILBOX_STATE_READ;
			}
			break;
		}

		if (vcpu_interrupt_count_get(vcpu_locked) > 0) {
			break;
		}

		if (arch_timer_enabled(&vcpu->regs)) {
			timer_remaining_ns =
				arch_timer_remaining_ns(&vcpu->regs);
			if (timer_remaining_ns == 0) {
				break;
			}
		} else {
			dlog_verbose("Timer disabled\n");
		}
		run_ret->func = FFA_MSG_WAIT_32;
		run_ret->arg1 = ffa_vm_vcpu(vcpu->vm->id, vcpu_index(vcpu));
		run_ret->arg2 = timer_remaining_ns;
		ret = false;
		goto out;
	case VCPU_STATE_BLOCKED_INTERRUPT:
		if (need_vm_lock &&
		    plat_ffa_inject_notification_pending_interrupt(
			    vcpu_locked, current, vm_locked)) {
			assert(vcpu_interrupt_count_get(vcpu_locked) > 0);
			break;
		}

		/* Allow virtual interrupts to be delivered. */
		if (vcpu_interrupt_count_get(vcpu_locked) > 0) {
			break;
		}

		if (arch_timer_enabled(&vcpu->regs)) {
			timer_remaining_ns =
				arch_timer_remaining_ns(&vcpu->regs);

			/*
			 * The timer expired so allow the interrupt to be
			 * delivered.
			 */
			if (timer_remaining_ns == 0) {
				break;
			}
		}

		/*
		 * The vCPU is not ready to run, return the appropriate code to
		 * the primary which called vcpu_run.
		 */
		run_ret->func = HF_FFA_RUN_WAIT_FOR_INTERRUPT;
		run_ret->arg1 = ffa_vm_vcpu(vcpu->vm->id, vcpu_index(vcpu));
		run_ret->arg2 = timer_remaining_ns;

		ret = false;
		goto out;

	case VCPU_STATE_BLOCKED:
		/* A blocked vCPU is run unconditionally. Fall through. */
	case VCPU_STATE_PREEMPTED:
		/* Check NPI is to be injected here. */
		if (need_vm_lock) {
			plat_ffa_inject_notification_pending_interrupt(
				vcpu_locked, current, vm_locked);
		}
		break;
	default:
		/*
		 * Execution not expected to reach here. Deny the request
		 * gracefully.
		 */
		*run_ret = ffa_error(FFA_DENIED);
		ret = false;
		goto out;
	}

	/* It has been decided that the vCPU should be run. */
	vcpu->cpu = current->cpu;
	vcpu->state = VCPU_STATE_RUNNING;

#if SECURE_WORLD == 1
	/* Set the designated GP register with the vCPU ID. */
	if (is_vcpu_reset_and_start) {
		vcpu_set_phys_core_idx(vcpu_locked.vcpu);
	}
#endif

	/*
	 * Mark the registers as unavailable now that we're about to reflect
	 * them onto the real registers. This will also prevent another physical
	 * CPU from trying to read these registers.
	 */
	vcpu->regs_available = false;

	ret = true;

out:
	vcpu_unlock(&vcpu_locked);
	if (need_vm_lock) {
		vm_unlock(&vm_locked);
	}
	return ret;
}

struct ffa_value api_ffa_run(ffa_vm_id_t vm_id, ffa_vcpu_index_t vcpu_idx,
			     struct vcpu *current, struct vcpu **next)
{
	struct vm *vm;
	struct vcpu *vcpu;
	struct ffa_value ret = ffa_error(FFA_INVALID_PARAMETERS);

	if (!plat_ffa_run_checks(current, vm_id, vcpu_idx, &ret, next)) {
		return ret;
	}

	if (plat_ffa_run_forward(vm_id, vcpu_idx, &ret)) {
		return ret;
	}

	/* The requested VM must exist. */
	vm = vm_find(vm_id);
	if (vm == NULL) {
		goto out;
	}

	/* The requested vCPU must exist. */
	if (vcpu_idx >= vm->vcpu_count) {
		goto out;
	}

	/* Update state if allowed. */
	vcpu = vm_get_vcpu(vm, vcpu_idx);
	if (!api_vcpu_prepare_run(current, vcpu, &ret)) {
		goto out;
	}

	/*
	 * Inject timer interrupt if timer has expired. It's safe to access
	 * vcpu->regs here because api_vcpu_prepare_run already made sure that
	 * regs_available was true (and then set it to false) before returning
	 * true.
	 */
	if (arch_timer_pending(&vcpu->regs)) {
		/* Make virtual timer interrupt pending. */
		internal_interrupt_inject(vcpu, HF_VIRTUAL_TIMER_INTID, vcpu,
					  NULL);

		/*
		 * Set the mask bit so the hardware interrupt doesn't fire
		 * again. Ideally we wouldn't do this because it affects what
		 * the secondary vCPU sees, but if we don't then we end up with
		 * a loop of the interrupt firing each time we try to return to
		 * the secondary vCPU.
		 */
		arch_timer_mask(&vcpu->regs);
	}

	/* Switch to the vCPU. */
	*next = vcpu;

	/*
	 * Set a placeholder return code to the scheduler. This will be
	 * overwritten when the switch back to the primary occurs.
	 */
	ret.func = FFA_INTERRUPT_32;
	ret.arg1 = 0;
	ret.arg2 = 0;

out:
	return ret;
}

/**
 * Check that the mode indicates memory that is valid, owned and exclusive.
 */
static bool api_mode_valid_owned_and_exclusive(uint32_t mode)
{
	return (mode & (MM_MODE_D | MM_MODE_INVALID | MM_MODE_UNOWNED |
			MM_MODE_SHARED)) == 0;
}

/**
 * Determines the value to be returned by api_ffa_rxtx_map and
 * api_ffa_rx_release after they've succeeded. If a secondary VM is running and
 * there are waiters, it also switches back to the primary VM for it to wake
 * waiters up.
 */
static struct ffa_value api_waiter_result(struct vm_locked locked_vm,
					  struct vcpu *current,
					  struct vcpu **next)
{
	struct vm *vm = locked_vm.vm;

	if (list_empty(&vm->mailbox.waiter_list)) {
		/* No waiters, nothing else to do. */
		return (struct ffa_value){.func = FFA_SUCCESS_32};
	}

	if (vm->id == HF_PRIMARY_VM_ID) {
		/* The caller is the primary VM. Tell it to wake up waiters. */
		return (struct ffa_value){.func = FFA_RX_RELEASE_32};
	}

	/*
	 * Switch back to the primary VM, informing it that there are waiters
	 * that need to be notified.
	 */
	*next = api_switch_to_primary(
		current, (struct ffa_value){.func = FFA_RX_RELEASE_32},
		VCPU_STATE_WAITING);

	return (struct ffa_value){.func = FFA_SUCCESS_32};
}

/**
 * Configures the hypervisor's stage-1 view of the send and receive pages.
 */
static bool api_vm_configure_stage1(struct mm_stage1_locked mm_stage1_locked,
				    struct vm_locked vm_locked,
				    paddr_t pa_send_begin, paddr_t pa_send_end,
				    paddr_t pa_recv_begin, paddr_t pa_recv_end,
				    uint32_t extra_attributes,
				    struct mpool *local_page_pool)
{
	bool ret;

	/* Map the send page as read-only in the hypervisor address space. */
	vm_locked.vm->mailbox.send =
		mm_identity_map(mm_stage1_locked, pa_send_begin, pa_send_end,
				MM_MODE_R | extra_attributes, local_page_pool);
	if (!vm_locked.vm->mailbox.send) {
		/* TODO: partial defrag of failed range. */
		/* Recover any memory consumed in failed mapping. */
		mm_defrag(mm_stage1_locked, local_page_pool);
		goto fail;
	}

	/*
	 * Map the receive page as writable in the hypervisor address space. On
	 * failure, unmap the send page before returning.
	 */
	vm_locked.vm->mailbox.recv =
		mm_identity_map(mm_stage1_locked, pa_recv_begin, pa_recv_end,
				MM_MODE_W | extra_attributes, local_page_pool);
	if (!vm_locked.vm->mailbox.recv) {
		/* TODO: partial defrag of failed range. */
		/* Recover any memory consumed in failed mapping. */
		mm_defrag(mm_stage1_locked, local_page_pool);
		goto fail_undo_send;
	}

	ret = true;
	goto out;

	/*
	 * The following mappings will not require more memory than is available
	 * in the local pool.
	 */
fail_undo_send:
	vm_locked.vm->mailbox.send = NULL;
	CHECK(mm_unmap(mm_stage1_locked, pa_send_begin, pa_send_end,
		       local_page_pool));

fail:
	ret = false;

out:
	return ret;
}

/**
 * Sanity checks and configures the send and receive pages in the VM stage-2
 * and hypervisor stage-1 page tables.
 *
 * Returns:
 *  - FFA_ERROR FFA_INVALID_PARAMETERS if the given addresses are not properly
 *    aligned, are the same or have invalid attributes.
 *  - FFA_ERROR FFA_NO_MEMORY if the hypervisor was unable to map the buffers
 *    due to insuffient page table memory.
 *  - FFA_ERROR FFA_DENIED if the pages are already mapped.
 *  - FFA_SUCCESS on success if no further action is needed.
 */

struct ffa_value api_vm_configure_pages(
	struct mm_stage1_locked mm_stage1_locked, struct vm_locked vm_locked,
	ipaddr_t send, ipaddr_t recv, uint32_t page_count,
	struct mpool *local_page_pool)
{
	struct ffa_value ret;
	paddr_t pa_send_begin;
	paddr_t pa_send_end;
	paddr_t pa_recv_begin;
	paddr_t pa_recv_end;
	uint32_t orig_send_mode = 0;
	uint32_t orig_recv_mode = 0;
	uint32_t extra_attributes;

	/* We only allow these to be setup once. */
	if (vm_locked.vm->mailbox.send || vm_locked.vm->mailbox.recv) {
		ret = ffa_error(FFA_DENIED);
		goto out;
	}

	/* Hafnium only supports a fixed size of RX/TX buffers. */
	if (page_count != HF_MAILBOX_SIZE / FFA_PAGE_SIZE) {
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	/* Fail if addresses are not page-aligned. */
	if (!is_aligned(ipa_addr(send), PAGE_SIZE) ||
	    !is_aligned(ipa_addr(recv), PAGE_SIZE)) {
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	/* Convert to physical addresses. */
	pa_send_begin = pa_from_ipa(send);
	pa_send_end = pa_add(pa_send_begin, HF_MAILBOX_SIZE);
	pa_recv_begin = pa_from_ipa(recv);
	pa_recv_end = pa_add(pa_recv_begin, HF_MAILBOX_SIZE);

	/* Fail if the same page is used for the send and receive pages. */
	if (pa_addr(pa_send_begin) == pa_addr(pa_recv_begin)) {
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	/* Set stage 2 translation tables only for virtual FF-A instances. */
	if (vm_id_is_current_world(vm_locked.vm->id)) {
		/*
		 * Ensure the pages are valid, owned and exclusive to the VM and
		 * that the VM has the required access to the memory.
		 */
		if (!vm_mem_get_mode(vm_locked, send, ipa_add(send, PAGE_SIZE),
				     &orig_send_mode) ||
		    !api_mode_valid_owned_and_exclusive(orig_send_mode) ||
		    (orig_send_mode & MM_MODE_R) == 0 ||
		    (orig_send_mode & MM_MODE_W) == 0) {
			dlog_error(
				"VM doesn't have required access rights to map "
				"TX buffer in stage 2.\n");
			ret = ffa_error(FFA_INVALID_PARAMETERS);
			goto out;
		}

		if (!vm_mem_get_mode(vm_locked, recv, ipa_add(recv, PAGE_SIZE),
				     &orig_recv_mode) ||
		    !api_mode_valid_owned_and_exclusive(orig_recv_mode) ||
		    (orig_recv_mode & MM_MODE_R) == 0) {
			dlog_error(
				"VM doesn't have required access rights to map "
				"RX buffer in stage 2.\n");
			ret = ffa_error(FFA_INVALID_PARAMETERS);
			goto out;
		}

		/* Take memory ownership away from the VM and mark as shared. */
		uint32_t mode = MM_MODE_UNOWNED | MM_MODE_SHARED | MM_MODE_R |
				MM_MODE_W;
		if (vm_locked.vm->el0_partition) {
			mode |= MM_MODE_USER | MM_MODE_NG;
		}

		if (!vm_identity_map(vm_locked, pa_send_begin, pa_send_end,
				     mode, local_page_pool, NULL)) {
			dlog_error(
				"Cannot allocate a new entry in stage 2 "
				"translation table.\n");
			ret = ffa_error(FFA_NO_MEMORY);
			goto out;
		}

		mode = MM_MODE_UNOWNED | MM_MODE_SHARED | MM_MODE_R;
		if (vm_locked.vm->el0_partition) {
			mode |= MM_MODE_USER | MM_MODE_NG;
		}

		if (!vm_identity_map(vm_locked, pa_recv_begin, pa_recv_end,
				     mode, local_page_pool, NULL)) {
			/* TODO: partial defrag of failed range. */
			/* Recover any memory consumed in failed mapping. */
			vm_ptable_defrag(vm_locked, local_page_pool);
			goto fail_undo_send;
		}
	}

	/* Get extra send/recv pages mapping attributes for the given VM ID. */
	extra_attributes = arch_mm_extra_attributes_from_vm(vm_locked.vm->id);

	/*
	 * For EL0 partitions, since both the partition and the hypervisor code
	 * use the EL2&0 translation regime, it is critical to mark the mappings
	 * of the send and recv buffers as non-global in the TLB. For one, if we
	 * dont mark it as non-global, it would cause TLB conflicts since there
	 * would be an identity mapping with non-global attribute in the
	 * partitions page tables, but another identity mapping in the
	 * hypervisor page tables with the global attribute. The other issue is
	 * one of security, we dont want other partitions to be able to access
	 * other partitions buffers through cached translations.
	 */
	if (vm_locked.vm->el0_partition) {
		extra_attributes |= MM_MODE_NG;
	}

	if (!api_vm_configure_stage1(mm_stage1_locked, vm_locked, pa_send_begin,
				     pa_send_end, pa_recv_begin, pa_recv_end,
				     extra_attributes, local_page_pool)) {
		goto fail_undo_send_and_recv;
	}

	ret = (struct ffa_value){.func = FFA_SUCCESS_32};
	goto out;

fail_undo_send_and_recv:
	CHECK(vm_identity_map(vm_locked, pa_recv_begin, pa_recv_end,
			      orig_recv_mode, local_page_pool, NULL));

fail_undo_send:
	CHECK(vm_identity_map(vm_locked, pa_send_begin, pa_send_end,
			      orig_send_mode, local_page_pool, NULL));
	ret = ffa_error(FFA_NO_MEMORY);

out:
	return ret;
}

static void api_get_rxtx_description(struct vm_locked vm_locked, ipaddr_t *send,
				     ipaddr_t *recv, uint32_t *page_count,
				     ffa_vm_id_t *owner_vm_id)
{
	/*
	 * If the message has been forwarded the effective addresses are in
	 * hypervisor's TX buffer.
	 */
	bool forwarded = (vm_locked.vm->id == HF_OTHER_WORLD_ID) &&
			 (ipa_addr(*send) == 0) && (ipa_addr(*recv) == 0) &&
			 (*page_count == 0);

	if (forwarded) {
		struct ffa_endpoint_rx_tx_descriptor *endpoint_desc =
			(struct ffa_endpoint_rx_tx_descriptor *)
				vm_locked.vm->mailbox.send;
		struct ffa_composite_memory_region *rx_region =
			ffa_enpoint_get_rx_memory_region(endpoint_desc);
		struct ffa_composite_memory_region *tx_region =
			ffa_enpoint_get_tx_memory_region(endpoint_desc);

		*owner_vm_id = endpoint_desc->endpoint_id;
		*recv = ipa_init(rx_region->constituents[0].address);
		*send = ipa_init(tx_region->constituents[0].address);
		*page_count = rx_region->constituents[0].page_count;
	} else {
		*owner_vm_id = vm_locked.vm->id;
	}
}
/**
 * Configures the VM to send/receive data through the specified pages. The pages
 * must not be shared. Locking of the page tables combined with a local memory
 * pool ensures there will always be enough memory to recover from any errors
 * that arise. The stage-1 page tables must be locked so memory cannot be taken
 * by another core which could result in this transaction being unable to roll
 * back in the case of an error.
 *
 * Returns:
 *  - FFA_ERROR FFA_INVALID_PARAMETERS if the given addresses are not properly
 *    aligned, are the same or have invalid attributes.
 *  - FFA_ERROR FFA_NO_MEMORY if the hypervisor was unable to map the buffers
 *    due to insuffient page table memory.
 *  - FFA_ERROR FFA_DENIED if the pages are already mapped.
 *  - FFA_SUCCESS on success if no further action is needed.
 */
struct ffa_value api_ffa_rxtx_map(ipaddr_t send, ipaddr_t recv,
				  uint32_t page_count, struct vcpu *current)
{
	struct vm *vm = current->vm;
	struct ffa_value ret;
	struct vm_locked vm_locked;
	struct vm_locked owner_vm_locked;
	struct mm_stage1_locked mm_stage1_locked;
	struct mpool local_page_pool;
	ffa_vm_id_t owner_vm_id;

	vm_locked = vm_lock(vm);
	/*
	 * Get the original buffer addresses and VM ID in case of forwarded
	 * message.
	 */
	api_get_rxtx_description(vm_locked, &send, &recv, &page_count,
				 &owner_vm_id);
	vm_unlock(&vm_locked);

	owner_vm_locked = plat_ffa_vm_find_locked_create(owner_vm_id);
	if (owner_vm_locked.vm == NULL) {
		dlog_error("Cannot map RX/TX for VM ID %#x, not found.\n",
			   owner_vm_id);
		return ffa_error(FFA_DENIED);
	}

	/*
	 * Create a local pool so any freed memory can't be used by another
	 * thread. This is to ensure the original mapping can be restored if any
	 * stage of the process fails.
	 */
	mpool_init_with_fallback(&local_page_pool, &api_page_pool);

	mm_stage1_locked = mm_lock_stage1();

	ret = api_vm_configure_pages(mm_stage1_locked, owner_vm_locked, send,
				     recv, page_count, &local_page_pool);
	if (ret.func != FFA_SUCCESS_32) {
		goto exit;
	}

	/* Forward buffer mapping to SPMC if coming from a VM. */
	plat_ffa_rxtx_map_forward(owner_vm_locked);

	ret = (struct ffa_value){.func = FFA_SUCCESS_32};

exit:
	mpool_fini(&local_page_pool);
	mm_unlock_stage1(&mm_stage1_locked);
	vm_unlock(&owner_vm_locked);

	return ret;
}

/**
 * Unmaps the RX/TX buffer pair with a partition or partition manager from the
 * translation regime of the caller. Unmap the region for the hypervisor and
 * set the memory region to owned and exclusive for the component. Since the
 * memory region mapped in the page table, when the buffers were originally
 * created we can safely remap it.
 *
 * Returns:
 *   - FFA_ERROR FFA_INVALID_PARAMETERS if there is no buffer pair registered on
 *     behalf of the caller.
 *   - FFA_SUCCESS on success if no further action is needed.
 */
struct ffa_value api_ffa_rxtx_unmap(ffa_vm_id_t allocator_id,
				    struct vcpu *current)
{
	struct vm *vm = current->vm;
	struct vm_locked vm_locked;
	ffa_vm_id_t owner_vm_id;
	struct mm_stage1_locked mm_stage1_locked;
	paddr_t send_pa_begin;
	paddr_t send_pa_end;
	paddr_t recv_pa_begin;
	paddr_t recv_pa_end;
	struct ffa_value ret = (struct ffa_value){.func = FFA_SUCCESS_32};

	/* Ensure `allocator_id` is set only at Non-Secure Physical instance. */
	if (vm_id_is_current_world(vm->id) && (allocator_id != 0)) {
		dlog_error("`allocator_id` must be 0 at virtual instances.\n");
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/* VM ID of which buffers have to be unmapped. */
	owner_vm_id = (allocator_id != 0) ? allocator_id : vm->id;

	vm_locked = plat_ffa_vm_find_locked(owner_vm_id);
	vm = vm_locked.vm;
	if (vm == NULL) {
		dlog_error("Cannot unmap RX/TX for VM ID %#x, not found.\n",
			   owner_vm_id);
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/* Get send and receive buffers. */
	if (vm->mailbox.send == NULL || vm->mailbox.recv == NULL) {
		dlog_verbose(
			"No buffer pair registered on behalf of the caller.\n");
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	/* Currently a mailbox size of 1 page is assumed. */
	send_pa_begin = pa_from_va(va_from_ptr(vm->mailbox.send));
	send_pa_end = pa_add(send_pa_begin, HF_MAILBOX_SIZE);
	recv_pa_begin = pa_from_va(va_from_ptr(vm->mailbox.recv));
	recv_pa_end = pa_add(recv_pa_begin, HF_MAILBOX_SIZE);

	mm_stage1_locked = mm_lock_stage1();

	/* Reset stage 2 mapping only for virtual FF-A instances. */
	if (vm_id_is_current_world(owner_vm_id)) {
		/*
		 * Set the memory region of the buffers back to the default mode
		 * for the VM. Since this memory region was already mapped for
		 * the RXTX buffers we can safely remap them.
		 */
		CHECK(vm_identity_map(vm_locked, send_pa_begin, send_pa_end,
				      MM_MODE_R | MM_MODE_W | MM_MODE_X,
				      &api_page_pool, NULL));

		CHECK(vm_identity_map(vm_locked, recv_pa_begin, recv_pa_end,
				      MM_MODE_R | MM_MODE_W | MM_MODE_X,
				      &api_page_pool, NULL));
	}

	/* Unmap the buffers in the partition manager. */
	CHECK(mm_unmap(mm_stage1_locked, send_pa_begin, send_pa_end,
		       &api_page_pool));
	CHECK(mm_unmap(mm_stage1_locked, recv_pa_begin, recv_pa_end,
		       &api_page_pool));

	vm->mailbox.send = NULL;
	vm->mailbox.recv = NULL;
	plat_ffa_vm_destroy(vm_locked);

	/* Forward buffer unmapping to SPMC if coming from a VM. */
	plat_ffa_rxtx_unmap_forward(owner_vm_id);

	mm_unlock_stage1(&mm_stage1_locked);

out:
	vm_unlock(&vm_locked);

	return ret;
}

/**
 * Notifies the `to` VM about the message currently in its mailbox, possibly
 * with the help of the primary VM.
 */
static struct ffa_value deliver_msg(struct vm_locked to, ffa_vm_id_t from_id,
				    struct vcpu *current, struct vcpu **next)
{
	struct ffa_value ret = (struct ffa_value){.func = FFA_SUCCESS_32};
	struct ffa_value primary_ret = {
		.func = FFA_MSG_SEND_32,
		.arg1 = ((uint32_t)from_id << 16) | to.vm->id,
	};

	/* Messages for the primary VM are delivered directly. */
	if (to.vm->id == HF_PRIMARY_VM_ID) {
		/*
		 * Only tell the primary VM the size and other details if the
		 * message is for it, to avoid leaking data about messages for
		 * other VMs.
		 */
		primary_ret = ffa_msg_recv_return(to.vm);

		to.vm->mailbox.state = MAILBOX_STATE_READ;
		*next = api_switch_to_primary(current, primary_ret,
					      VCPU_STATE_BLOCKED);
		return ret;
	}

	to.vm->mailbox.state = MAILBOX_STATE_RECEIVED;

	/* Messages for the TEE are sent on via the dispatcher. */
	if (to.vm->id == HF_TEE_VM_ID) {
		struct ffa_value call = ffa_msg_recv_return(to.vm);

		ret = arch_other_world_call(call);
		/*
		 * After the call to the TEE completes it must have finished
		 * reading its RX buffer, so it is ready for another message.
		 */
		to.vm->mailbox.state = MAILBOX_STATE_EMPTY;
		/*
		 * Don't return to the primary VM in this case, as the TEE is
		 * not (yet) scheduled via FF-A.
		 */
		return ret;
	}

	/* Return to the primary VM directly or with a switch. */
	if (from_id != HF_PRIMARY_VM_ID) {
		*next = api_switch_to_primary(current, primary_ret,
					      VCPU_STATE_BLOCKED);
	}

	return ret;
}

/**
 * Copies data from the sender's send buffer to the recipient's receive buffer
 * and notifies the recipient.
 *
 * If the recipient's receive buffer is busy, it can optionally register the
 * caller to be notified when the recipient's receive buffer becomes available.
 */
struct ffa_value api_ffa_msg_send(ffa_vm_id_t sender_vm_id,
				  ffa_vm_id_t receiver_vm_id, uint32_t size,
				  uint32_t attributes, struct vcpu *current,
				  struct vcpu **next)
{
	struct vm *from = current->vm;
	struct vm *to;
	struct vm_locked to_locked;
	const void *from_msg;
	struct ffa_value ret;
	struct vcpu_locked current_locked;
	bool is_direct_request_ongoing;
	bool notify =
		(attributes & FFA_MSG_SEND_NOTIFY_MASK) == FFA_MSG_SEND_NOTIFY;

	/* Ensure sender VM ID corresponds to the current VM. */
	if (sender_vm_id != from->id) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/* Disallow reflexive requests as this suggests an error in the VM. */
	if (receiver_vm_id == from->id) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/* Limit the size of transfer. */
	if (size > FFA_MSG_PAYLOAD_MAX) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/*
	 * Deny if vCPU is executing in context of an FFA_MSG_SEND_DIRECT_REQ
	 * invocation.
	 */
	current_locked = vcpu_lock(current);
	is_direct_request_ongoing =
		is_ffa_direct_msg_request_ongoing(current_locked);
	vcpu_unlock(&current_locked);

	if (is_direct_request_ongoing) {
		return ffa_error(FFA_DENIED);
	}

	/* Ensure the receiver VM exists. */
	to = vm_find(receiver_vm_id);
	if (to == NULL) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/*
	 * Check that the sender has configured its send buffer. If the tx
	 * mailbox at from_msg is configured (i.e. from_msg != NULL) then it can
	 * be safely accessed after releasing the lock since the tx mailbox
	 * address can only be configured once.
	 */
	sl_lock(&from->lock);
	from_msg = from->mailbox.send;
	sl_unlock(&from->lock);

	if (from_msg == NULL) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	to_locked = vm_lock(to);

	if (msg_receiver_busy(to_locked, from, notify)) {
		ret = ffa_error(FFA_BUSY);
		goto out;
	}

	/* Copy data. */
	memcpy_s(to->mailbox.recv, FFA_MSG_PAYLOAD_MAX, from_msg, size);
	to->mailbox.recv_size = size;
	to->mailbox.recv_sender = sender_vm_id;
	to->mailbox.recv_func = FFA_MSG_SEND_32;
	ret = deliver_msg(to_locked, sender_vm_id, current, next);

out:
	vm_unlock(&to_locked);

	return ret;
}

/**
 * Copies data from the sender's send buffer to the recipient's receive buffer
 * and notifies the receiver.
 */
struct ffa_value api_ffa_msg_send2(ffa_vm_id_t sender_vm_id, uint32_t flags,
				   struct vcpu *current)
{
	struct vm *from = current->vm;
	struct vm *to;
	struct vm_locked to_locked;
	ffa_vm_id_t msg_sender_id;
	struct vm_locked sender_locked;
	const void *from_msg;
	struct ffa_value ret;
	struct ffa_partition_rxtx_header header;
	ffa_vm_id_t sender_id;
	ffa_vm_id_t receiver_id;
	uint32_t msg_size;
	ffa_notifications_bitmap_t rx_buffer_full;

	/* Only Hypervisor can set `sender_vm_id` when forwarding messages. */
	if (from->id != HF_HYPERVISOR_VM_ID && sender_vm_id != 0) {
		dlog_error("Sender VM ID must be zero.\n");
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/*
	 * Get message sender's mailbox, which can be different to the `from` vm
	 * when the message is forwarded.
	 */
	msg_sender_id = (sender_vm_id != 0) ? sender_vm_id : from->id;
	sender_locked = plat_ffa_vm_find_locked(msg_sender_id);
	if (sender_locked.vm == NULL) {
		dlog_error("Cannot send message from VM ID %#x, not found.\n",
			   msg_sender_id);
		return ffa_error(FFA_DENIED);
	}

	from_msg = sender_locked.vm->mailbox.send;
	if (from_msg == NULL) {
		dlog_error("Cannot retrieve TX buffer for VM ID %#x.\n",
			   msg_sender_id);
		ret = ffa_error(FFA_DENIED);
		goto out_unlock_sender;
	}

	/*
	 * Copy message header as safety measure to avoid multiple accesses to
	 * unsafe memory which could be 'corrupted' between safety checks and
	 * final buffer copy.
	 */
	memcpy_s(&header, FFA_RXTX_HEADER_SIZE, from_msg, FFA_RXTX_HEADER_SIZE);
	sender_id = ffa_rxtx_header_sender(&header);
	receiver_id = ffa_rxtx_header_receiver(&header);

	/* Ensure Sender IDs from API and from message header match. */
	if (msg_sender_id != sender_id) {
		dlog_error(
			"Message sender VM ID (%#x) doesn't match header's VM "
			"ID (%#x).\n",
			msg_sender_id, sender_id);
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out_unlock_sender;
	}

	/* Disallow reflexive requests as this suggests an error in the VM. */
	if (receiver_id == sender_id) {
		dlog_error("Sender and receive VM IDs must be different.\n");
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out_unlock_sender;
	}

	/* `flags` can be set only at secure virtual FF-A instances. */
	if (plat_ffa_is_vm_id(sender_id) && (flags != 0)) {
		dlog_error("flags must be zero.\n");
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/*
	 * Check if the message has to be forwarded to the SPMC, in
	 * this case return, the SPMC will handle the buffer copy.
	 */
	if (plat_ffa_msg_send2_forward(receiver_id, sender_id, &ret)) {
		goto out_unlock_sender;
	}

	/* Ensure the receiver VM exists. */
	to_locked = plat_ffa_vm_find_locked(receiver_id);
	to = to_locked.vm;

	if (to == NULL) {
		dlog_error("Cannot deliver message to VM %#x, not found.\n",
			   receiver_id);
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out_unlock_sender;
	}

	/*
	 * Check sender and receiver can use indirect messages.
	 * Sender is the VM/SP who originally sent the message, not the
	 * hypervisor possibly relaying it.
	 */
	if (!plat_ffa_is_indirect_msg_supported(sender_locked, to_locked)) {
		dlog_verbose("VM %#x doesn't support indirect message\n",
			     sender_id);
		ret = ffa_error(FFA_DENIED);
		goto out;
	}

	if (to->mailbox.state != MAILBOX_STATE_EMPTY ||
	    to->mailbox.recv == NULL) {
		dlog_error(
			"Cannot deliver message to VM %#x, RX buffer not "
			"ready.\n",
			receiver_id);
		ret = ffa_error(FFA_BUSY);
		goto out;
	}

	/* Acquire receiver's RX buffer. */
	if (!plat_ffa_acquire_receiver_rx(to_locked, &ret)) {
		dlog_error("Failed to acquire RX buffer for VM %#x\n", to->id);
		goto out;
	}

	/* Check the size of transfer. */
	msg_size = FFA_RXTX_HEADER_SIZE + header.size;
	if ((msg_size > FFA_PARTITION_MSG_PAYLOAD_MAX) ||
	    (header.size > FFA_PARTITION_MSG_PAYLOAD_MAX)) {
		dlog_error("Message is too big.\n");
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	/* Copy data. */
	memcpy_s(to->mailbox.recv, FFA_MSG_PAYLOAD_MAX, from_msg, msg_size);
	to->mailbox.recv_size = msg_size;
	to->mailbox.recv_sender = sender_id;
	to->mailbox.recv_func = FFA_MSG_SEND2_32;
	to->mailbox.state = MAILBOX_STATE_RECEIVED;

	rx_buffer_full = plat_ffa_is_vm_id(sender_id)
				 ? FFA_NOTIFICATION_HYP_BUFFER_FULL_MASK
				 : FFA_NOTIFICATION_SPM_BUFFER_FULL_MASK;
	vm_notifications_framework_set_pending(to_locked, rx_buffer_full);

	if ((FFA_NOTIFICATIONS_FLAG_DELAY_SRI & flags) == 0) {
		dlog_verbose("SRI was NOT delayed. vcpu: %u!\n",
			     vcpu_index(current));
		plat_ffa_sri_trigger_not_delayed(current->cpu);
	} else {
		plat_ffa_sri_state_set(DELAYED);
	}

	ret = (struct ffa_value){.func = FFA_SUCCESS_32};

out:
	vm_unlock(&to_locked);

out_unlock_sender:
	vm_unlock(&sender_locked);

	return ret;
}

/**
 * Checks whether the vCPU's attempt to block for a message has already been
 * interrupted or whether it is allowed to block.
 */
static bool api_ffa_msg_recv_block_interrupted(struct vcpu *current)
{
	struct vcpu_locked current_locked;
	bool interrupted;

	current_locked = vcpu_lock(current);

	/*
	 * Don't block if there are enabled and pending interrupts, to match
	 * behaviour of wait_for_interrupt.
	 */
	interrupted = (vcpu_interrupt_count_get(current_locked) > 0);

	vcpu_unlock(&current_locked);

	return interrupted;
}

/**
 * Receives a message from the mailbox. If one isn't available, this function
 * can optionally block the caller until one becomes available.
 *
 * No new messages can be received until the mailbox has been cleared.
 */
struct ffa_value api_ffa_msg_recv(bool block, struct vcpu *current,
				  struct vcpu **next)
{
	bool is_direct_request_ongoing;
	struct vcpu_locked current_locked;
	struct vm *vm = current->vm;
	struct ffa_value return_code;
	bool is_from_secure_world =
		(current->vm->id & HF_VM_ID_WORLD_MASK) != 0;

	/*
	 * The primary VM will receive messages as a status code from running
	 * vCPUs and must not call this function.
	 */
	if (!is_from_secure_world && vm->id == HF_PRIMARY_VM_ID) {
		return ffa_error(FFA_NOT_SUPPORTED);
	}

	/*
	 * Deny if vCPU is executing in context of an FFA_MSG_SEND_DIRECT_REQ
	 * invocation.
	 */
	current_locked = vcpu_lock(current);
	is_direct_request_ongoing =
		is_ffa_direct_msg_request_ongoing(current_locked);
	vcpu_unlock(&current_locked);

	if (is_direct_request_ongoing) {
		return ffa_error(FFA_DENIED);
	}

	sl_lock(&vm->lock);

	/* Return pending messages without blocking. */
	if (vm->mailbox.state == MAILBOX_STATE_RECEIVED) {
		return_code = ffa_msg_recv_return(vm);
		if (return_code.func == FFA_MSG_SEND_32) {
			vm->mailbox.state = MAILBOX_STATE_READ;
		}
		goto out;
	}

	/* No pending message so fail if not allowed to block. */
	if (!block) {
		return_code = ffa_error(FFA_RETRY);
		goto out;
	}

	/*
	 * From this point onward this call can only be interrupted or a message
	 * received. If a message is received the return value will be set at
	 * that time to FFA_SUCCESS.
	 */
	return_code = ffa_error(FFA_INTERRUPTED);
	if (api_ffa_msg_recv_block_interrupted(current)) {
		goto out;
	}

	if (is_from_secure_world) {
		/* Return to other world if caller is a SP. */
		*next = api_switch_to_other_world(
			current, (struct ffa_value){.func = FFA_MSG_WAIT_32},
			VCPU_STATE_WAITING);
	} else {
		/* Switch back to primary VM to block. */
		struct ffa_value run_return = {
			.func = FFA_MSG_WAIT_32,
			.arg1 = ffa_vm_vcpu(vm->id, vcpu_index(current)),
		};

		*next = api_switch_to_primary(current, run_return,
					      VCPU_STATE_WAITING);
	}
out:
	sl_unlock(&vm->lock);

	return return_code;
}

/**
 * Retrieves the next VM whose mailbox became writable. For a VM to be notified
 * by this function, the caller must have called api_mailbox_send before with
 * the notify argument set to true, and this call must have failed because the
 * mailbox was not available.
 *
 * It should be called repeatedly to retrieve a list of VMs.
 *
 * Returns -1 if no VM became writable, or the id of the VM whose mailbox
 * became writable.
 */
int64_t api_mailbox_writable_get(const struct vcpu *current)
{
	struct vm *vm = current->vm;
	struct wait_entry *entry;
	int64_t ret;

	sl_lock(&vm->lock);
	if (list_empty(&vm->mailbox.ready_list)) {
		ret = -1;
		goto exit;
	}

	entry = CONTAINER_OF(vm->mailbox.ready_list.next, struct wait_entry,
			     ready_links);
	list_remove(&entry->ready_links);
	ret = vm_id_for_wait_entry(vm, entry);

exit:
	sl_unlock(&vm->lock);
	return ret;
}

/**
 * Retrieves the next VM waiting to be notified that the mailbox of the
 * specified VM became writable. Only primary VMs are allowed to call this.
 *
 * Returns -1 on failure or if there are no waiters; the VM id of the next
 * waiter otherwise.
 */
int64_t api_mailbox_waiter_get(ffa_vm_id_t vm_id, const struct vcpu *current)
{
	struct vm *vm;
	struct vm_locked locked;
	struct wait_entry *entry;
	struct vm *waiting_vm;

	/* Only primary VMs are allowed to call this function. */
	if (current->vm->id != HF_PRIMARY_VM_ID) {
		return -1;
	}

	vm = vm_find(vm_id);
	if (vm == NULL) {
		return -1;
	}

	/* Check if there are outstanding notifications from given VM. */
	locked = vm_lock(vm);
	entry = api_fetch_waiter(locked);
	vm_unlock(&locked);

	if (entry == NULL) {
		return -1;
	}

	/* Enqueue notification to waiting VM. */
	waiting_vm = entry->waiting_vm;

	sl_lock(&waiting_vm->lock);
	if (list_empty(&entry->ready_links)) {
		list_append(&waiting_vm->mailbox.ready_list,
			    &entry->ready_links);
	}
	sl_unlock(&waiting_vm->lock);

	return waiting_vm->id;
}

/**
 * Releases the caller's mailbox so that a new message can be received. The
 * caller must have copied out all data they wish to preserve as new messages
 * will overwrite the old and will arrive asynchronously.
 *
 * Returns:
 *  - FFA_ERROR FFA_INVALID_PARAMETERS if message is forwarded to SPMC but
 *    there's no buffer pair mapped.
 *  - FFA_ERROR FFA_DENIED on failure, if the mailbox hasn't been read.
 *  - FFA_SUCCESS on success if no further action is needed.
 *  - FFA_RX_RELEASE if it was called by the primary VM and the primary VM now
 *    needs to wake up or kick waiters. Waiters should be retrieved by calling
 *    hf_mailbox_waiter_get.
 */
struct ffa_value api_ffa_rx_release(ffa_vm_id_t receiver_id,
				    struct vcpu *current, struct vcpu **next)
{
	struct vm *current_vm = current->vm;
	struct vm *vm;
	struct vm_locked vm_locked;
	ffa_vm_id_t current_vm_id = current_vm->id;
	ffa_vm_id_t release_vm_id;
	struct ffa_value ret;

	/* `receiver_id` can be set only at Non-Secure Physical interface. */
	if (vm_id_is_current_world(current_vm_id) && (receiver_id != 0)) {
		dlog_error("Invalid `receiver_id`, must be zero.\n");
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/*
	 * VM ID to be released: `receiver_id` if message has been forwarded by
	 * Hypervisor to release a VM's buffer, current VM ID otherwise.
	 */
	if (vm_id_is_current_world(current_vm_id) || (receiver_id == 0)) {
		release_vm_id = current_vm_id;
	} else {
		release_vm_id = receiver_id;
	}

	vm_locked = plat_ffa_vm_find_locked(release_vm_id);
	vm = vm_locked.vm;
	if (vm == NULL) {
		dlog_error("No buffer registered for VM ID %#x.\n",
			   release_vm_id);
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	if (!plat_ffa_rx_release_forward(vm_locked, &ret)) {
		dlog_verbose("RX_RELEASE forward failed for VM ID %#x.\n",
			     release_vm_id);
		goto out;
	}

	/*
	 * When SPMC owns a VM's RX buffer, the Hypervisor's view can be out of
	 * sync: reset it to empty and exit.
	 */
	if (plat_ffa_rx_release_forwarded(vm_locked)) {
		ret = (struct ffa_value){.func = FFA_SUCCESS_32};
		goto out;
	}

	switch (vm->mailbox.state) {
	case MAILBOX_STATE_EMPTY:
		ret = ffa_error(FFA_DENIED);
		break;

	case MAILBOX_STATE_RECEIVED:
		if (release_vm_id == current_vm_id) {
			/*
			 * VM requesting to release its own RX buffer,
			 * must be in READ state.
			 */
			ret = ffa_error(FFA_DENIED);
		} else {
			/*
			 * Forwarded message from Hypervisor to release a VM
			 * RX buffer, SPMC's mailbox view can be still in
			 * RECEIVED state.
			 */
			ret = (struct ffa_value){.func = FFA_SUCCESS_32};
			vm->mailbox.state = MAILBOX_STATE_EMPTY;
		}
		break;

	case MAILBOX_STATE_READ:
		ret = api_waiter_result(vm_locked, current, next);
		vm->mailbox.state = MAILBOX_STATE_EMPTY;
		break;
	}

out:
	vm_unlock(&vm_locked);

	return ret;
}

/**
 * Acquire ownership of an RX buffer before writing to it. Both
 * Hypervisor and SPMC are producers of VM's RX buffer, and they
 * could contend for the same buffer. SPMC owns VM's RX buffer after
 * it's mapped in its translation regime. This ABI should be
 * used by the Hypervisor to get the ownership of a VM's RX buffer
 * from the SPMC solving the aforementioned possible contention.
 *
 * Returns:
 * - FFA_DENIED: callee cannot relinquish ownership of RX buffer.
 * - FFA_INVALID_PARAMETERS: there is no buffer pair registered for the VM.
 * - FFA_NOT_SUPPORTED: function not implemented at the FF-A instance.
 */
struct ffa_value api_ffa_rx_acquire(ffa_vm_id_t receiver_id,
				    struct vcpu *current)
{
	struct vm_locked receiver_locked;
	struct vm *receiver;
	struct ffa_value ret;

	if ((current->vm->id != HF_HYPERVISOR_VM_ID) ||
	    !plat_ffa_is_vm_id(receiver_id)) {
		dlog_error(
			"FFA_RX_ACQUIRE not supported at this FF-A "
			"instance.\n");
		return ffa_error(FFA_NOT_SUPPORTED);
	}

	receiver_locked = plat_ffa_vm_find_locked(receiver_id);
	receiver = receiver_locked.vm;

	if (receiver == NULL || receiver->mailbox.recv == NULL) {
		dlog_error("Cannot retrieve RX buffer for VM ID %#x.\n",
			   receiver_id);
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	if (receiver->mailbox.state != MAILBOX_STATE_EMPTY) {
		dlog_error("Mailbox busy for VM ID %#x.\n", receiver_id);
		ret = ffa_error(FFA_DENIED);
		goto out;
	}

	receiver->mailbox.state = MAILBOX_STATE_RECEIVED;

	ret = (struct ffa_value){.func = FFA_SUCCESS_32};

out:
	vm_unlock(&receiver_locked);

	return ret;
}

/**
 * Enables or disables a given interrupt ID for the calling vCPU.
 *
 * Returns 0 on success, or -1 if the intid is invalid.
 */
int64_t api_interrupt_enable(uint32_t intid, bool enable,
			     enum interrupt_type type, struct vcpu *current)
{
	struct vcpu_locked current_locked;
	struct interrupts *interrupts = &current->interrupts;

	if (intid >= HF_NUM_INTIDS) {
		return -1;
	}

	current_locked = vcpu_lock(current);
	if (enable) {
		/*
		 * If it is pending and was not enabled before, increment the
		 * count.
		 */
		if (vcpu_is_virt_interrupt_pending(interrupts, intid) &&
		    !vcpu_is_virt_interrupt_enabled(interrupts, intid)) {
			vcpu_interrupt_count_increment(current_locked,
						       interrupts, intid);
		}
		vcpu_virt_interrupt_set_enabled(interrupts, intid);
		vcpu_virt_interrupt_set_type(interrupts, intid, type);
	} else {
		/*
		 * If it is pending and was enabled before, decrement the count.
		 */
		if (vcpu_is_virt_interrupt_pending(interrupts, intid) &&
		    vcpu_is_virt_interrupt_enabled(interrupts, intid)) {
			vcpu_interrupt_count_decrement(current_locked,
						       interrupts, intid);
		}
		vcpu_virt_interrupt_clear_enabled(interrupts, intid);
		vcpu_virt_interrupt_set_type(interrupts, intid,
					     INTERRUPT_TYPE_IRQ);
	}

	vcpu_unlock(&current_locked);
	return 0;
}

/**
 * Returns the ID of the next pending interrupt for the calling vCPU, and
 * acknowledges it (i.e. marks it as no longer pending). Returns
 * HF_INVALID_INTID if there are no pending interrupts.
 */
uint32_t api_interrupt_get(struct vcpu *current)
{
	uint32_t i;
	uint32_t first_interrupt = HF_INVALID_INTID;
	struct vcpu_locked current_locked;
	struct interrupts *interrupts = &current->interrupts;

	/*
	 * Find the first enabled and pending interrupt ID, return it, and
	 * deactivate it.
	 */
	current_locked = vcpu_lock(current);
	for (i = 0; i < HF_NUM_INTIDS / INTERRUPT_REGISTER_BITS; ++i) {
		uint32_t enabled_and_pending =
			interrupts->interrupt_enabled.bitmap[i] &
			interrupts->interrupt_pending.bitmap[i];

		if (enabled_and_pending != 0) {
			uint8_t bit_index = ctz(enabled_and_pending);

			first_interrupt =
				i * INTERRUPT_REGISTER_BITS + bit_index;

			/*
			 * Mark it as no longer pending and decrement the count.
			 */
			vcpu_virt_interrupt_clear_pending(interrupts,
							  first_interrupt);

			vcpu_interrupt_count_decrement(
				current_locked, interrupts, first_interrupt);
			break;
		}
	}

	vcpu_unlock(&current_locked);
	return first_interrupt;
}

/**
 * Returns whether the current vCPU is allowed to inject an interrupt into the
 * given VM and vCPU.
 */
static inline bool is_injection_allowed(uint32_t target_vm_id,
					struct vcpu *current)
{
	uint32_t current_vm_id = current->vm->id;

	/*
	 * The primary VM is allowed to inject interrupts into any VM. Secondary
	 * VMs are only allowed to inject interrupts into their own vCPUs.
	 */
	return current_vm_id == HF_PRIMARY_VM_ID ||
	       current_vm_id == target_vm_id;
}

/**
 * Injects a virtual interrupt of the given ID into the given target vCPU.
 * This doesn't cause the vCPU to actually be run immediately; it will be taken
 * when the vCPU is next run, which is up to the scheduler.
 *
 * Returns:
 *  - -1 on failure because the target VM or vCPU doesn't exist, the interrupt
 *    ID is invalid, or the current VM is not allowed to inject interrupts to
 *    the target VM.
 *  - 0 on success if no further action is needed.
 *  - 1 if it was called by the primary VM and the primary VM now needs to wake
 *    up or kick the target vCPU.
 */
int64_t api_interrupt_inject(ffa_vm_id_t target_vm_id,
			     ffa_vcpu_index_t target_vcpu_idx, uint32_t intid,
			     struct vcpu *current, struct vcpu **next)
{
	struct vcpu *target_vcpu;
	struct vm *target_vm = vm_find(target_vm_id);

	if (intid >= HF_NUM_INTIDS) {
		return -1;
	}

	if (target_vm == NULL) {
		return -1;
	}

	if (target_vcpu_idx >= target_vm->vcpu_count) {
		/* The requested vCPU must exist. */
		return -1;
	}

	if (!is_injection_allowed(target_vm_id, current)) {
		return -1;
	}

	target_vcpu = vm_get_vcpu(target_vm, target_vcpu_idx);

	dlog_verbose(
		"Injecting interrupt %u for VM %#x vCPU %u from VM %#x vCPU "
		"%u\n",
		intid, target_vm_id, target_vcpu_idx, current->vm->id,
		vcpu_index(current));
	return internal_interrupt_inject(target_vcpu, intid, current, next);
}

/** Returns the version of the implemented FF-A specification. */
struct ffa_value api_ffa_version(struct vcpu *current,
				 uint32_t requested_version)
{
	struct vm_locked current_vm_locked;

	/*
	 * Ensure that both major and minor revision representation occupies at
	 * most 15 bits.
	 */
	static_assert(0x8000 > FFA_VERSION_MAJOR,
		      "Major revision representation takes more than 15 bits.");
	static_assert(0x10000 > FFA_VERSION_MINOR,
		      "Minor revision representation takes more than 16 bits.");
	if (requested_version & FFA_VERSION_RESERVED_BIT) {
		/* Invalid encoding, return an error. */
		return (struct ffa_value){.func = (uint32_t)FFA_NOT_SUPPORTED};
	}

	current_vm_locked = vm_lock(current->vm);
	current_vm_locked.vm->ffa_version = requested_version;
	vm_unlock(&current_vm_locked);

	return ((struct ffa_value){.func = FFA_VERSION_COMPILED});
}

int64_t api_debug_log(char c, struct vcpu *current)
{
	bool flush;
	struct vm *vm = current->vm;
	struct vm_locked vm_locked = vm_lock(vm);

	if (c == '\n' || c == '\0') {
		flush = true;
	} else {
		vm->log_buffer[vm->log_buffer_length++] = c;
		flush = (vm->log_buffer_length == sizeof(vm->log_buffer));
	}

	if (flush) {
		dlog_flush_vm_buffer(vm->id, vm->log_buffer,
				     vm->log_buffer_length);
		vm->log_buffer_length = 0;
	}

	vm_unlock(&vm_locked);

	return 0;
}

/**
 * Helper for success return of FFA_FEATURES, for when it is used to query
 * an interrupt ID.
 */
struct ffa_value api_ffa_feature_success(uint32_t arg2)
{
	return (struct ffa_value){
		.func = FFA_SUCCESS_32, .arg1 = 0U, .arg2 = arg2};
}

/**
 * Discovery function returning information about the implementation of optional
 * FF-A interfaces.
 */
struct ffa_value api_ffa_features(uint32_t feature_function_id)
{
	/*
	 * According to table 13.8 of FF-A v1.1 Beta 0 spec, bits [30:8] MBZ
	 * if using a feature ID.
	 */
	if ((feature_function_id & FFA_FEATURES_FUNC_ID_MASK) == 0U &&
	    (feature_function_id & ~FFA_FEATURES_FEATURE_ID_MASK) != 0U) {
		return ffa_error(FFA_NOT_SUPPORTED);
	}

	switch (feature_function_id) {
	/* Check support of the given Function ID. */
	case FFA_ERROR_32:
	case FFA_SUCCESS_32:
	case FFA_INTERRUPT_32:
	case FFA_VERSION_32:
	case FFA_FEATURES_32:
	case FFA_RX_RELEASE_32:
	case FFA_RXTX_MAP_64:
	case FFA_RXTX_UNMAP_32:
	case FFA_PARTITION_INFO_GET_32:
	case FFA_ID_GET_32:
	case FFA_MSG_WAIT_32:
	case FFA_RUN_32:
	case FFA_MEM_DONATE_32:
	case FFA_MEM_LEND_32:
	case FFA_MEM_SHARE_32:
	case FFA_MEM_RETRIEVE_REQ_32:
	case FFA_MEM_RETRIEVE_RESP_32:
	case FFA_MEM_RELINQUISH_32:
	case FFA_MEM_RECLAIM_32:
	case FFA_MEM_FRAG_RX_32:
	case FFA_MEM_FRAG_TX_32:
	case FFA_MSG_SEND_DIRECT_RESP_64:
	case FFA_MSG_SEND_DIRECT_RESP_32:
	case FFA_MSG_SEND_DIRECT_REQ_64:
	case FFA_MSG_SEND_DIRECT_REQ_32:
#if (MAKE_FFA_VERSION(1, 1) <= FFA_VERSION_COMPILED)
	/* FF-A v1.1 features. */
	case FFA_SPM_ID_GET_32:
	case FFA_NOTIFICATION_BITMAP_CREATE_32:
	case FFA_NOTIFICATION_BITMAP_DESTROY_32:
	case FFA_NOTIFICATION_BIND_32:
	case FFA_NOTIFICATION_UNBIND_32:
	case FFA_NOTIFICATION_SET_32:
	case FFA_NOTIFICATION_GET_32:
	case FFA_NOTIFICATION_INFO_GET_64:
	case FFA_MEM_PERM_GET_32:
	case FFA_MEM_PERM_SET_32:
	case FFA_MEM_PERM_GET_64:
	case FFA_MEM_PERM_SET_64:
	case FFA_MSG_SEND2_32:
#endif
		return (struct ffa_value){.func = FFA_SUCCESS_32};

#if (MAKE_FFA_VERSION(1, 1) <= FFA_VERSION_COMPILED)
	/* Check support of a feature provided respective feature ID. */
	case FFA_FEATURE_NPI:
		return api_ffa_feature_success(HF_NOTIFICATION_PENDING_INTID);
	case FFA_FEATURE_SRI:
		return api_ffa_feature_success(HF_SCHEDULE_RECEIVER_INTID);
#endif
	/* Platform specific feature support. */
	default:
		return arch_ffa_features(feature_function_id);
	}
}

/**
 * FF-A specification states that x2/w2 Must Be Zero for direct messaging
 * interfaces.
 */
static inline bool api_ffa_dir_msg_is_arg2_zero(struct ffa_value args)
{
	return args.arg2 == 0U;
}

/**
 * Limits size of arguments in ffa_value structure to 32-bit.
 */
static struct ffa_value api_ffa_value_copy32(struct ffa_value args)
{
	return (struct ffa_value){
		.func = (uint32_t)args.func,
		.arg1 = (uint32_t)args.arg1,
		.arg2 = (uint32_t)0,
		.arg3 = (uint32_t)args.arg3,
		.arg4 = (uint32_t)args.arg4,
		.arg5 = (uint32_t)args.arg5,
		.arg6 = (uint32_t)args.arg6,
		.arg7 = (uint32_t)args.arg7,
	};
}

/**
 * Helper to copy direct message payload, depending on SMC used and expected
 * registers size.
 */
static struct ffa_value api_ffa_dir_msg_value(struct ffa_value args)
{
	if (args.func == FFA_MSG_SEND_DIRECT_REQ_32 ||
	    args.func == FFA_MSG_SEND_DIRECT_RESP_32) {
		return api_ffa_value_copy32(args);
	}

	return (struct ffa_value){
		.func = args.func,
		.arg1 = args.arg1,
		.arg2 = 0,
		.arg3 = args.arg3,
		.arg4 = args.arg4,
		.arg5 = args.arg5,
		.arg6 = args.arg6,
		.arg7 = args.arg7,
	};
}

/**
 * Send an FF-A direct message request.
 */
struct ffa_value api_ffa_msg_send_direct_req(ffa_vm_id_t sender_vm_id,
					     ffa_vm_id_t receiver_vm_id,
					     struct ffa_value args,
					     struct vcpu *current,
					     struct vcpu **next)
{
	struct ffa_value ret;
	struct vm *receiver_vm;
	struct vm_locked receiver_locked;
	struct vcpu *receiver_vcpu;
	struct two_vcpu_locked vcpus_locked;

	if (!api_ffa_dir_msg_is_arg2_zero(args)) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	if (!plat_ffa_is_direct_request_valid(current, sender_vm_id,
					      receiver_vm_id)) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	if (plat_ffa_direct_request_forward(receiver_vm_id, args, &ret)) {
		return ret;
	}

	ret = (struct ffa_value){.func = FFA_INTERRUPT_32};

	receiver_vm = vm_find(receiver_vm_id);
	if (receiver_vm == NULL) {
		dlog_verbose("Invalid Receiver!\n");
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/*
	 * Check if sender supports sending direct message req, and if
	 * receiver supports receipt of direct message requests.
	 */
	if (!plat_ffa_is_direct_request_supported(current->vm, receiver_vm)) {
		return ffa_error(FFA_DENIED);
	}

	/*
	 * Per FF-A EAC spec section 4.4.1 the firmware framework supports
	 * UP (migratable) or MP partitions with a number of vCPUs matching the
	 * number of PEs in the system. It further states that MP partitions
	 * accepting direct request messages cannot migrate.
	 */
	receiver_vcpu = api_ffa_get_vm_vcpu(receiver_vm, current);
	if (receiver_vcpu == NULL) {
		dlog_verbose("Invalid vCPU!\n");
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	receiver_locked = vm_lock(receiver_vm);
	vcpus_locked = vcpu_lock_both(receiver_vcpu, current);

	/*
	 * If destination vCPU is executing or already received an
	 * FFA_MSG_SEND_DIRECT_REQ then return to caller hinting recipient is
	 * busy. There is a brief period of time where the vCPU state has
	 * changed but regs_available is still false thus consider this case as
	 * the vCPU not yet ready to receive a direct message request.
	 */
	if (is_ffa_direct_msg_request_ongoing(vcpus_locked.vcpu1) ||
	    receiver_vcpu->state == VCPU_STATE_RUNNING ||
	    !receiver_vcpu->regs_available) {
		dlog_verbose("Receiver is busy with another request.\n");
		ret = ffa_error(FFA_BUSY);
		goto out;
	}

	if (atomic_load_explicit(&receiver_vcpu->vm->aborting,
				 memory_order_relaxed)) {
		if (receiver_vcpu->state != VCPU_STATE_ABORTED) {
			dlog_notice("Aborting VM %#x vCPU %u\n",
				    receiver_vcpu->vm->id,
				    vcpu_index(receiver_vcpu));
			receiver_vcpu->state = VCPU_STATE_ABORTED;
		}

		ret = ffa_error(FFA_ABORTED);
		goto out;
	}

	switch (receiver_vcpu->state) {
	case VCPU_STATE_OFF:
	case VCPU_STATE_RUNNING:
	case VCPU_STATE_ABORTED:
	case VCPU_STATE_BLOCKED_INTERRUPT:
	case VCPU_STATE_BLOCKED:
	case VCPU_STATE_PREEMPTED:
		dlog_verbose("Receiver's vCPU can't receive request (%u)!\n",
			     vcpu_index(receiver_vcpu));
		ret = ffa_error(FFA_BUSY);
		goto out;
	case VCPU_STATE_WAITING:
		/*
		 * We expect target vCPU to be in WAITING state after either
		 * having called ffa_msg_wait or sent a direct message response.
		 */
		break;
	}

	/* Inject timer interrupt if any pending */
	if (arch_timer_pending(&receiver_vcpu->regs)) {
		api_interrupt_inject_locked(vcpus_locked.vcpu1,
					    HF_VIRTUAL_TIMER_INTID, current,
					    NULL);

		arch_timer_mask(&receiver_vcpu->regs);
	}

	/* The receiver vCPU runs upon direct message invocation */
	receiver_vcpu->cpu = current->cpu;
	receiver_vcpu->state = VCPU_STATE_RUNNING;
	receiver_vcpu->regs_available = false;
	receiver_vcpu->direct_request_origin_vm_id = sender_vm_id;

	arch_regs_set_retval(&receiver_vcpu->regs, api_ffa_dir_msg_value(args));

	current->state = VCPU_STATE_BLOCKED;

	/* Switch to receiver vCPU targeted to by direct msg request */
	*next = receiver_vcpu;

	if (!receiver_locked.vm->el0_partition) {
		/*
		 * If the scheduler in the system is giving CPU cycles to the
		 * receiver, due to pending notifications, inject the NPI
		 * interrupt. Following call assumes that '*next' has been set
		 * to receiver_vcpu.
		 */
		plat_ffa_inject_notification_pending_interrupt(
			vcpus_locked.vcpu1.vcpu == receiver_vcpu
				? vcpus_locked.vcpu1
				: vcpus_locked.vcpu2,
			current, receiver_locked);
	}

	/*
	 * Since this flow will lead to a VM switch, the return value will not
	 * be applied to current vCPU.
	 */

out:
	sl_unlock(&receiver_vcpu->lock);
	sl_unlock(&current->lock);
	vm_unlock(&receiver_locked);

	return ret;
}

/**
 * Send an FF-A direct message response.
 */
struct ffa_value api_ffa_msg_send_direct_resp(ffa_vm_id_t sender_vm_id,
					      ffa_vm_id_t receiver_vm_id,
					      struct ffa_value args,
					      struct vcpu *current,
					      struct vcpu **next)
{
	struct vcpu_locked current_locked;

	if (!api_ffa_dir_msg_is_arg2_zero(args)) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	struct ffa_value to_ret = api_ffa_dir_msg_value(args);

	if (!plat_ffa_is_direct_response_valid(current, sender_vm_id,
					       receiver_vm_id)) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	current_locked = vcpu_lock(current);
	if (api_ffa_is_managed_exit_ongoing(current_locked)) {
		/*
		 * No need for REQ/RESP state management as managed exit does
		 * not have corresponding REQ pair.
		 */
		if (receiver_vm_id != HF_PRIMARY_VM_ID) {
			vcpu_unlock(&current_locked);
			return ffa_error(FFA_DENIED);
		}

		/*
		 * Per FF-A v1.1 Beta section 8.4.1.2 bullet 6, SPMC can signal
		 * a secure interrupt to a SP that is performing managed exit.
		 * We have taken a implementation defined choice to not allow
		 * Managed exit while a SP is processing a secure interrupt.
		 */
		CHECK(!current->processing_secure_interrupt);

		plat_interrupts_set_priority_mask(current->priority_mask);
		current->processing_managed_exit = false;
	} else {
		/*
		 * Ensure the terminating FFA_MSG_SEND_DIRECT_REQ had a
		 * defined originator.
		 */
		if (!is_ffa_direct_msg_request_ongoing(current_locked)) {
			/*
			 * Sending direct response but direct request origin
			 * vCPU is not set.
			 */
			vcpu_unlock(&current_locked);
			return ffa_error(FFA_DENIED);
		}

		/* Refer to FF-A v1.1 Beta0 section 7.3 bulet 3. */
		if (current->direct_request_origin_vm_id != receiver_vm_id) {
			vcpu_unlock(&current_locked);
			return ffa_error(FFA_DENIED);
		}
	}

	/* Clear direct request origin for the caller. */
	current->direct_request_origin_vm_id = HF_INVALID_VM_ID;

	vcpu_unlock(&current_locked);

	if (!vm_id_is_current_world(receiver_vm_id)) {
		*next = api_switch_to_other_world(
			current, to_ret,
			/*
			 * Current vcpu sent a direct response. It moves to
			 * waiting state.
			 */
			VCPU_STATE_WAITING);
	} else if (receiver_vm_id == HF_PRIMARY_VM_ID) {
		*next = api_switch_to_primary(
			current, to_ret,
			/*
			 * Current vcpu sent a direct response. It moves to
			 * waiting state.
			 */
			VCPU_STATE_WAITING);
	} else if (vm_id_is_current_world(receiver_vm_id)) {
		/*
		 * It is expected the receiver_vm_id to be from an SP, otherwise
		 * 'plat_ffa_is_direct_response_valid' should have
		 * made function return error before getting to this point.
		 */
		*next = api_switch_to_vm(current, to_ret,
					 /*
					  * current vcpu sent a direct response.
					  * It moves to waiting state.
					  */
					 VCPU_STATE_WAITING, receiver_vm_id);
	} else {
		panic("Invalid direct message response invocation");
	}

	return (struct ffa_value){.func = FFA_INTERRUPT_32};
}

static bool api_memory_region_check_flags(
	struct ffa_memory_region *memory_region, uint32_t share_func)
{
	switch (share_func) {
	case FFA_MEM_SHARE_32:
		if ((memory_region->flags & FFA_MEMORY_REGION_FLAG_CLEAR) !=
		    0U) {
			return false;
		}
		/* Intentional fall-through */
	case FFA_MEM_LEND_32:
	case FFA_MEM_DONATE_32: {
		/* Bits 31:2 Must Be Zero. */
		ffa_memory_receiver_flags_t to_mask =
			~(FFA_MEMORY_REGION_FLAG_CLEAR |
			  FFA_MEMORY_REGION_FLAG_TIME_SLICE);

		if ((memory_region->flags & to_mask) != 0U) {
			return false;
		}
		break;
	}
	default:
		panic("Check for mem send calls only.\n");
	}

	/* Last check reserved values are 0 */
	return true;
}

struct ffa_value api_ffa_mem_send(uint32_t share_func, uint32_t length,
				  uint32_t fragment_length, ipaddr_t address,
				  uint32_t page_count, struct vcpu *current)
{
	struct vm *from = current->vm;
	struct vm *to;
	const void *from_msg;
	struct ffa_memory_region *memory_region;
	struct ffa_value ret;
	bool targets_other_world = false;

	if (ipa_addr(address) != 0 || page_count != 0) {
		/*
		 * Hafnium only supports passing the descriptor in the TX
		 * mailbox.
		 */
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	if (fragment_length > length) {
		dlog_verbose(
			"Fragment length %d greater than total length %d.\n",
			fragment_length, length);
		return ffa_error(FFA_INVALID_PARAMETERS);
	}
	if (fragment_length < sizeof(struct ffa_memory_region) +
				      sizeof(struct ffa_memory_access)) {
		dlog_verbose(
			"Initial fragment length %d smaller than header size "
			"%d.\n",
			fragment_length,
			sizeof(struct ffa_memory_region) +
				sizeof(struct ffa_memory_access));
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/*
	 * Check that the sender has configured its send buffer. If the TX
	 * mailbox at from_msg is configured (i.e. from_msg != NULL) then it can
	 * be safely accessed after releasing the lock since the TX mailbox
	 * address can only be configured once.
	 */
	sl_lock(&from->lock);
	from_msg = from->mailbox.send;
	sl_unlock(&from->lock);

	if (from_msg == NULL) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/*
	 * Copy the memory region descriptor to a fresh page from the memory
	 * pool. This prevents the sender from changing it underneath us, and
	 * also lets us keep it around in the share state table if needed.
	 */
	if (fragment_length > HF_MAILBOX_SIZE ||
	    fragment_length > MM_PPOOL_ENTRY_SIZE) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}
	memory_region = (struct ffa_memory_region *)mpool_alloc(&api_page_pool);
	if (memory_region == NULL) {
		dlog_verbose("Failed to allocate memory region copy.\n");
		return ffa_error(FFA_NO_MEMORY);
	}
	memcpy_s(memory_region, MM_PPOOL_ENTRY_SIZE, from_msg, fragment_length);

	/* The sender must match the caller. */
	if (memory_region->sender != from->id) {
		dlog_verbose("Memory region sender doesn't match caller.\n");
		ret = ffa_error(FFA_DENIED);
		goto out;
	}

	if (!api_memory_region_check_flags(memory_region, share_func)) {
		dlog_verbose(
			"Memory region reserved arguments must be zero.\n");
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	if (memory_region->receiver_count == 0U) {
		dlog_verbose("Receiver count can't be 0.\n");
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	if (share_func == FFA_MEM_DONATE_32 &&
	    memory_region->receiver_count != 1U) {
		dlog_verbose(
			"FFA_MEM_DONATE only supports one recipient. "
			"Specified %u\n",
			memory_region->receiver_count);
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	if (memory_region->receiver_count > MAX_MEM_SHARE_RECIPIENTS) {
		dlog_verbose(
			"Max number of recipients supported is %u "
			"specified %u\n",
			MAX_MEM_SHARE_RECIPIENTS,
			memory_region->receiver_count);
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	/*
	 * Ensure that the receiver VM exists and isn't the same as the sender.
	 * If there is a receiver from the other world, track it for later
	 * forwarding if needed.
	 */
	for (uint32_t i = 0U; i < memory_region->receiver_count; i++) {
		ffa_vm_id_t receiver_id =
			memory_region->receivers[i]
				.receiver_permissions.receiver;
		to = vm_find(receiver_id);

		if (vm_id_is_current_world(receiver_id) &&
		    (to == NULL || to == from)) {
			dlog_verbose("%s: invalid receiver.\n", __func__);
			ret = ffa_error(FFA_INVALID_PARAMETERS);
			goto out;
		}

		if (!plat_ffa_is_memory_send_valid(receiver_id, share_func)) {
			ret = ffa_error(FFA_DENIED);
			goto out;
		}

		/* Capture if any of the receivers is from the other world. */
		if (!targets_other_world) {
			targets_other_world =
				!vm_id_is_current_world(receiver_id);
		}
	}

	/* Allow for one memory region to be shared to the TEE. */
	if (targets_other_world) {
		assert(memory_region->receiver_count == 1 &&
		       to->id == HF_TEE_VM_ID);
		/*
		 * The 'to' VM lock is only needed in the case that it is the
		 * TEE VM.
		 */
		struct two_vm_locked vm_to_from_lock = vm_lock_both(to, from);

		if (msg_receiver_busy(vm_to_from_lock.vm1, from, false)) {
			ret = ffa_error(FFA_BUSY);
			goto out_unlock;
		}

		ret = ffa_memory_tee_send(
			vm_to_from_lock.vm2, vm_to_from_lock.vm1, memory_region,
			length, fragment_length, share_func, &api_page_pool);
		/*
		 * ffa_tee_memory_send takes ownership of the memory_region, so
		 * make sure we don't free it.
		 */
		memory_region = NULL;

	out_unlock:
		vm_unlock(&vm_to_from_lock.vm1);
		vm_unlock(&vm_to_from_lock.vm2);
	} else {
		struct vm_locked from_locked = vm_lock(from);

		ret = ffa_memory_send(from_locked, memory_region, length,
				      fragment_length, share_func,
				      &api_page_pool);
		/*
		 * ffa_memory_send takes ownership of the memory_region, so
		 * make sure we don't free it.
		 */
		memory_region = NULL;

		vm_unlock(&from_locked);
	}

out:
	if (memory_region != NULL) {
		mpool_free(&api_page_pool, memory_region);
	}

	return ret;
}

struct ffa_value api_ffa_mem_retrieve_req(uint32_t length,
					  uint32_t fragment_length,
					  ipaddr_t address, uint32_t page_count,
					  struct vcpu *current)
{
	struct vm *to = current->vm;
	struct vm_locked to_locked;
	const void *to_msg;
	struct ffa_memory_region *retrieve_request;
	uint32_t message_buffer_size;
	struct ffa_value ret;

	if (ipa_addr(address) != 0 || page_count != 0) {
		/*
		 * Hafnium only supports passing the descriptor in the TX
		 * mailbox.
		 */
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	if (fragment_length != length) {
		dlog_verbose("Fragmentation not yet supported.\n");
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	retrieve_request =
		(struct ffa_memory_region *)cpu_get_buffer(current->cpu);
	message_buffer_size = cpu_get_buffer_size(current->cpu);
	if (length > HF_MAILBOX_SIZE || length > message_buffer_size) {
		dlog_verbose("Retrieve request too long.\n");
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	to_locked = vm_lock(to);
	to_msg = to->mailbox.send;

	if (to_msg == NULL) {
		dlog_verbose("TX buffer not setup.\n");
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	/*
	 * Copy the retrieve request descriptor to an internal buffer, so that
	 * the caller can't change it underneath us.
	 */
	memcpy_s(retrieve_request, message_buffer_size, to_msg, length);

	if (msg_receiver_busy(to_locked, NULL, false)) {
		/*
		 * Can't retrieve memory information if the mailbox is not
		 * available.
		 */
		dlog_verbose("RX buffer not ready.\n");
		ret = ffa_error(FFA_BUSY);
		goto out;
	}

	ret = ffa_memory_retrieve(to_locked, retrieve_request, length,
				  &api_page_pool);

out:
	vm_unlock(&to_locked);
	return ret;
}

struct ffa_value api_ffa_mem_relinquish(struct vcpu *current)
{
	struct vm *from = current->vm;
	struct vm_locked from_locked;
	const void *from_msg;
	struct ffa_mem_relinquish *relinquish_request;
	uint32_t message_buffer_size;
	struct ffa_value ret;
	uint32_t length;

	from_locked = vm_lock(from);
	from_msg = from->mailbox.send;

	if (from_msg == NULL) {
		dlog_verbose("TX buffer not setup.\n");
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	/*
	 * Calculate length from relinquish descriptor before copying. We will
	 * check again later to make sure it hasn't changed.
	 */
	length = sizeof(struct ffa_mem_relinquish) +
		 ((struct ffa_mem_relinquish *)from_msg)->endpoint_count *
			 sizeof(ffa_vm_id_t);
	/*
	 * Copy the relinquish descriptor to an internal buffer, so that the
	 * caller can't change it underneath us.
	 */
	relinquish_request =
		(struct ffa_mem_relinquish *)cpu_get_buffer(current->cpu);
	message_buffer_size = cpu_get_buffer_size(current->cpu);
	if (length > HF_MAILBOX_SIZE || length > message_buffer_size) {
		dlog_verbose("Relinquish message too long.\n");
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}
	memcpy_s(relinquish_request, message_buffer_size, from_msg, length);

	if (sizeof(struct ffa_mem_relinquish) +
		    relinquish_request->endpoint_count * sizeof(ffa_vm_id_t) !=
	    length) {
		dlog_verbose(
			"Endpoint count changed while copying to internal "
			"buffer.\n");
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	ret = ffa_memory_relinquish(from_locked, relinquish_request,
				    &api_page_pool);

out:
	vm_unlock(&from_locked);
	return ret;
}

struct ffa_value api_ffa_mem_reclaim(ffa_memory_handle_t handle,
				     ffa_memory_region_flags_t flags,
				     struct vcpu *current)
{
	struct vm *to = current->vm;
	struct ffa_value ret;

	if (plat_ffa_memory_handle_allocated_by_current_world(handle)) {
		struct vm_locked to_locked = vm_lock(to);

		ret = ffa_memory_reclaim(to_locked, handle, flags,
					 &api_page_pool);

		vm_unlock(&to_locked);
	} else {
		struct vm *from = vm_find(HF_TEE_VM_ID);
		struct two_vm_locked vm_to_from_lock = vm_lock_both(to, from);

		ret = ffa_memory_tee_reclaim(vm_to_from_lock.vm1,
					     vm_to_from_lock.vm2, handle, flags,
					     &api_page_pool);

		vm_unlock(&vm_to_from_lock.vm1);
		vm_unlock(&vm_to_from_lock.vm2);
	}

	return ret;
}

struct ffa_value api_ffa_mem_frag_rx(ffa_memory_handle_t handle,
				     uint32_t fragment_offset,
				     ffa_vm_id_t sender_vm_id,
				     struct vcpu *current)
{
	struct vm *to = current->vm;
	struct vm_locked to_locked;
	struct ffa_value ret;

	/* Sender ID MBZ at virtual instance. */
	if (sender_vm_id != 0) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	to_locked = vm_lock(to);

	if (msg_receiver_busy(to_locked, NULL, false)) {
		/*
		 * Can't retrieve memory information if the mailbox is not
		 * available.
		 */
		dlog_verbose("RX buffer not ready.\n");
		ret = ffa_error(FFA_BUSY);
		goto out;
	}

	ret = ffa_memory_retrieve_continue(to_locked, handle, fragment_offset,
					   &api_page_pool);

out:
	vm_unlock(&to_locked);
	return ret;
}

struct ffa_value api_ffa_mem_frag_tx(ffa_memory_handle_t handle,
				     uint32_t fragment_length,
				     ffa_vm_id_t sender_vm_id,
				     struct vcpu *current)
{
	struct vm *from = current->vm;
	const void *from_msg;
	void *fragment_copy;
	struct ffa_value ret;

	/* Sender ID MBZ at virtual instance. */
	if (sender_vm_id != 0) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/*
	 * Check that the sender has configured its send buffer. If the TX
	 * mailbox at from_msg is configured (i.e. from_msg != NULL) then it can
	 * be safely accessed after releasing the lock since the TX mailbox
	 * address can only be configured once.
	 */
	sl_lock(&from->lock);
	from_msg = from->mailbox.send;
	sl_unlock(&from->lock);

	if (from_msg == NULL) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/*
	 * Copy the fragment to a fresh page from the memory pool. This prevents
	 * the sender from changing it underneath us, and also lets us keep it
	 * around in the share state table if needed.
	 */
	if (fragment_length > HF_MAILBOX_SIZE ||
	    fragment_length > MM_PPOOL_ENTRY_SIZE) {
		dlog_verbose(
			"Fragment length %d larger than mailbox size %d.\n",
			fragment_length, HF_MAILBOX_SIZE);
		return ffa_error(FFA_INVALID_PARAMETERS);
	}
	if (fragment_length < sizeof(struct ffa_memory_region_constituent) ||
	    fragment_length % sizeof(struct ffa_memory_region_constituent) !=
		    0) {
		dlog_verbose("Invalid fragment length %d.\n", fragment_length);
		return ffa_error(FFA_INVALID_PARAMETERS);
	}
	fragment_copy = mpool_alloc(&api_page_pool);
	if (fragment_copy == NULL) {
		dlog_verbose("Failed to allocate fragment copy.\n");
		return ffa_error(FFA_NO_MEMORY);
	}
	memcpy_s(fragment_copy, MM_PPOOL_ENTRY_SIZE, from_msg, fragment_length);

	/*
	 * Hafnium doesn't support fragmentation of memory retrieve requests
	 * (because it doesn't support caller-specified mappings, so a request
	 * will never be larger than a single page), so this must be part of a
	 * memory send (i.e. donate, lend or share) request.
	 *
	 * We can tell from the handle whether the memory transaction is for the
	 * TEE or not.
	 */
	if ((handle & FFA_MEMORY_HANDLE_ALLOCATOR_MASK) ==
	    FFA_MEMORY_HANDLE_ALLOCATOR_HYPERVISOR) {
		struct vm_locked from_locked = vm_lock(from);

		ret = ffa_memory_send_continue(from_locked, fragment_copy,
					       fragment_length, handle,
					       &api_page_pool);
		/*
		 * `ffa_memory_send_continue` takes ownership of the
		 * fragment_copy, so we don't need to free it here.
		 */
		vm_unlock(&from_locked);
	} else {
		struct vm *to = vm_find(HF_TEE_VM_ID);
		struct two_vm_locked vm_to_from_lock = vm_lock_both(to, from);

		/*
		 * The TEE RX buffer state is checked in
		 * `ffa_memory_tee_send_continue` rather than here, as we need
		 * to return `FFA_MEM_FRAG_RX` with the current offset rather
		 * than FFA_ERROR FFA_BUSY in case it is busy.
		 */

		ret = ffa_memory_tee_send_continue(
			vm_to_from_lock.vm2, vm_to_from_lock.vm1, fragment_copy,
			fragment_length, handle, &api_page_pool);
		/*
		 * `ffa_memory_tee_send_continue` takes ownership of the
		 * fragment_copy, so we don't need to free it here.
		 */

		vm_unlock(&vm_to_from_lock.vm1);
		vm_unlock(&vm_to_from_lock.vm2);
	}

	return ret;
}

/**
 * Register an entry point for a vCPU in warm boot cases.
 * DEN0077A FF-A v1.1 Beta0 section 18.3.2.1 FFA_SECONDARY_EP_REGISTER.
 */
struct ffa_value api_ffa_secondary_ep_register(ipaddr_t entry_point,
					       struct vcpu *current)
{
	struct vm_locked vm_locked;
	struct ffa_value ret = ffa_error(FFA_DENIED);

	/*
	 * Reject if interface is not supported at this FF-A instance
	 * (DEN0077A FF-A v1.1 Beta0 Table 18.29) or the VM is UP.
	 */
	if (!plat_ffa_is_secondary_ep_register_supported() ||
	    current->vm->vcpu_count == 1) {
		return ffa_error(FFA_NOT_SUPPORTED);
	}

	/*
	 * No further check is made on the address validity
	 * (FF-A v1.1 Beta0 Table 18.29) as the VM boundaries are not known
	 * from the VM or vCPU structure.
	 * DEN0077A FF-A v1.1 Beta0 section 18.3.2.1.1:
	 * For each SP [...] the Framework assumes that the same entry point
	 * address is used for initializing any execution context during a
	 * secondary cold boot.
	 * If this function is invoked multiple times, then the entry point
	 * address specified in the last valid invocation must be used by the
	 * callee.
	 */
	vm_locked = vm_lock(current->vm);
	if (vm_locked.vm->initialized) {
		goto out;
	}

	vm_locked.vm->secondary_ep = entry_point;

	ret = (struct ffa_value){.func = FFA_SUCCESS_32};

out:
	vm_unlock(&vm_locked);

	return ret;
}

struct ffa_value api_ffa_notification_bitmap_create(ffa_vm_id_t vm_id,
						    ffa_vcpu_count_t vcpu_count,
						    struct vcpu *current)
{
	if (!plat_ffa_is_notifications_create_valid(current, vm_id)) {
		dlog_verbose("Bitmap create for NWd VM IDs only (%x).\n",
			     vm_id);
		return ffa_error(FFA_NOT_SUPPORTED);
	}

	return plat_ffa_notifications_bitmap_create(vm_id, vcpu_count);
}

struct ffa_value api_ffa_notification_bitmap_destroy(ffa_vm_id_t vm_id,
						     struct vcpu *current)
{
	/*
	 * Validity of use of this interface is the same as for bitmap create.
	 */
	if (!plat_ffa_is_notifications_create_valid(current, vm_id)) {
		dlog_verbose("Bitmap destroy for NWd VM IDs only (%x).\n",
			     vm_id);
		return ffa_error(FFA_NOT_SUPPORTED);
	}

	return plat_ffa_notifications_bitmap_destroy(vm_id);
}

struct ffa_value api_ffa_notification_update_bindings(
	ffa_vm_id_t sender_vm_id, ffa_vm_id_t receiver_vm_id, uint32_t flags,
	ffa_notifications_bitmap_t notifications, bool is_bind,
	struct vcpu *current)
{
	struct ffa_value ret = {.func = FFA_SUCCESS_32};
	struct vm_locked receiver_locked;
	const bool is_per_vcpu = (flags & FFA_NOTIFICATION_FLAG_PER_VCPU) != 0U;
	const ffa_vm_id_t id_to_update =
		is_bind ? sender_vm_id : HF_INVALID_VM_ID;
	const ffa_vm_id_t id_to_validate =
		is_bind ? HF_INVALID_VM_ID : sender_vm_id;

	if (!plat_ffa_is_notifications_bind_valid(current, sender_vm_id,
						  receiver_vm_id)) {
		dlog_verbose("Invalid use of notifications bind interface.\n");
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	if (plat_ffa_notifications_update_bindings_forward(
		    receiver_vm_id, sender_vm_id, flags, notifications, is_bind,
		    &ret)) {
		return ret;
	}

	if (notifications == 0U) {
		dlog_verbose("No notifications have been specified.\n");
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/**
	 * This check assumes receiver is the current VM, and has been enforced
	 * by 'plat_ffa_is_notifications_bind_valid'.
	 */
	receiver_locked = plat_ffa_vm_find_locked(receiver_vm_id);

	if (receiver_locked.vm == NULL) {
		dlog_verbose("Receiver doesn't exist!\n");
		return ffa_error(FFA_DENIED);
	}

	if (!vm_locked_are_notifications_enabled(receiver_locked)) {
		dlog_verbose("Notifications are not enabled.\n");
		ret = ffa_error(FFA_NOT_SUPPORTED);
		goto out;
	}

	if (is_bind && vm_id_is_current_world(sender_vm_id) &&
	    vm_find(sender_vm_id) == NULL) {
		dlog_verbose("Sender VM does not exist!\n");
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	/*
	 * Can't bind/unbind notifications if at least one is bound to a
	 * different sender.
	 */
	if (!vm_notifications_validate_bound_sender(
		    receiver_locked, plat_ffa_is_vm_id(sender_vm_id),
		    id_to_validate, notifications)) {
		dlog_verbose("Notifications are bound to other sender.\n");
		ret = ffa_error(FFA_DENIED);
		goto out;
	}

	/**
	 * Check if there is a pending notification within those specified in
	 * the bitmap.
	 */
	if (vm_are_notifications_pending(receiver_locked,
					 plat_ffa_is_vm_id(sender_vm_id),
					 notifications)) {
		dlog_verbose("Notifications within '%x' pending.\n",
			     notifications);
		ret = ffa_error(FFA_DENIED);
		goto out;
	}

	vm_notifications_update_bindings(
		receiver_locked, plat_ffa_is_vm_id(sender_vm_id), id_to_update,
		notifications, is_per_vcpu && is_bind);

out:
	vm_unlock(&receiver_locked);
	return ret;
}

struct ffa_value api_ffa_notification_set(
	ffa_vm_id_t sender_vm_id, ffa_vm_id_t receiver_vm_id, uint32_t flags,
	ffa_notifications_bitmap_t notifications, struct vcpu *current)
{
	struct ffa_value ret;
	struct vm_locked receiver_locked;

	/*
	 * Check if is per-vCPU or global, and extracting vCPU ID according
	 * to table 17.19 of the FF-A v1.1 Beta 0 spec.
	 */
	bool is_per_vcpu = (flags & FFA_NOTIFICATION_FLAG_PER_VCPU) != 0U;
	ffa_vcpu_index_t vcpu_id = (uint16_t)(flags >> 16);

	if (!plat_ffa_is_notification_set_valid(current, sender_vm_id,
						receiver_vm_id)) {
		dlog_verbose("Invalid use of notifications set interface.\n");
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	if (notifications == 0U) {
		dlog_verbose("No notifications have been specified.\n");
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	if (plat_ffa_notification_set_forward(sender_vm_id, receiver_vm_id,
					      flags, notifications, &ret)) {
		return ret;
	}

	/*
	 * This check assumes receiver is the current VM, and has been enforced
	 * by 'plat_ffa_is_notification_set_valid'.
	 */
	receiver_locked = plat_ffa_vm_find_locked(receiver_vm_id);

	if (receiver_locked.vm == NULL) {
		dlog_verbose("Receiver ID is not valid.\n");
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	if (!vm_locked_are_notifications_enabled(receiver_locked)) {
		dlog_verbose("Receiver's notifications not enabled.\n");
		ret = ffa_error(FFA_DENIED);
		goto out;
	}

	/*
	 * If notifications are not bound to the sender, they wouldn't be
	 * enabled either for the receiver.
	 */
	if (!vm_notifications_validate_binding(
		    receiver_locked, plat_ffa_is_vm_id(sender_vm_id),
		    sender_vm_id, notifications, is_per_vcpu)) {
		dlog_verbose("Notifications bindings not valid.\n");
		ret = ffa_error(FFA_DENIED);
		goto out;
	}

	if (is_per_vcpu && vcpu_id >= receiver_locked.vm->vcpu_count) {
		dlog_verbose("Invalid VCPU ID!\n");
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	/* Set notifications pending. */
	vm_notifications_partition_set_pending(
		receiver_locked, plat_ffa_is_vm_id(sender_vm_id), notifications,
		vcpu_id, is_per_vcpu);

	dlog_verbose("Set the notifications: %x.\n", notifications);

	if ((FFA_NOTIFICATIONS_FLAG_DELAY_SRI & flags) == 0) {
		dlog_verbose("SRI was NOT delayed. vcpu: %u!\n",
			     vcpu_index(current));
		plat_ffa_sri_trigger_not_delayed(current->cpu);
	} else {
		plat_ffa_sri_state_set(DELAYED);
	}

	ret = (struct ffa_value){.func = FFA_SUCCESS_32};
out:
	vm_unlock(&receiver_locked);

	return ret;
}

static struct ffa_value api_ffa_notification_get_success_return(
	ffa_notifications_bitmap_t from_sp, ffa_notifications_bitmap_t from_vm,
	ffa_notifications_bitmap_t from_framework)
{
	return (struct ffa_value){
		.func = FFA_SUCCESS_32,
		.arg1 = 0U,
		.arg2 = (uint32_t)from_sp,
		.arg3 = (uint32_t)(from_sp >> 32),
		.arg4 = (uint32_t)from_vm,
		.arg5 = (uint32_t)(from_vm >> 32),
		.arg6 = (uint32_t)from_framework,
		.arg7 = (uint32_t)(from_framework >> 32),
	};
}

struct ffa_value api_ffa_notification_get(ffa_vm_id_t receiver_vm_id,
					  ffa_vcpu_index_t vcpu_id,
					  uint32_t flags, struct vcpu *current)
{
	ffa_notifications_bitmap_t framework_notifications = 0;
	ffa_notifications_bitmap_t sp_notifications = 0;
	ffa_notifications_bitmap_t vm_notifications = 0;
	struct vm_locked receiver_locked;
	struct ffa_value ret;
	const uint32_t flags_mbz = ~(FFA_NOTIFICATION_FLAG_BITMAP_HYP |
				     FFA_NOTIFICATION_FLAG_BITMAP_SPM |
				     FFA_NOTIFICATION_FLAG_BITMAP_SP |
				     FFA_NOTIFICATION_FLAG_BITMAP_VM);

	/* The FF-A v1.1 EAC0 specification states bits [31:4] Must Be Zero. */
	if ((flags & flags_mbz) != 0U) {
		dlog_verbose(
			"Invalid flags bit(s) set in notifications get. [31:4] "
			"MBZ(%x)\n",
			flags);
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/*
	 * Following check should capture wrong uses of the interface,
	 * depending on whether Hafnium is SPMC or hypervisor. On the
	 * rest of the function it is assumed this condition is met.
	 */
	if (!plat_ffa_is_notification_get_valid(current, receiver_vm_id,
						flags)) {
		dlog_verbose("Invalid use of notifications get interface.\n");
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/*
	 * This check assumes receiver is the current VM, and has been enforced
	 * by `plat_ffa_is_notifications_get_valid`.
	 */
	receiver_locked = plat_ffa_vm_find_locked(receiver_vm_id);

	/*
	 * `plat_ffa_is_notifications_get_valid` ensures following is never
	 * true.
	 */
	CHECK(receiver_locked.vm != NULL);

	if (receiver_locked.vm->vcpu_count <= vcpu_id ||
	    (receiver_locked.vm->vcpu_count != 1 &&
	     cpu_index(current->cpu) != vcpu_id)) {
		dlog_verbose(
			"Invalid VCPU ID %u. vcpu count %u current core: %u!\n",
			vcpu_id, receiver_locked.vm->vcpu_count,
			cpu_index(current->cpu));
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	if ((flags & FFA_NOTIFICATION_FLAG_BITMAP_SP) != 0U) {
		if (!plat_ffa_notifications_get_from_sp(
			    receiver_locked, vcpu_id, &sp_notifications,
			    &ret)) {
			dlog_verbose("Failed to get notifications from sps.");
			goto out;
		}
	}

	if ((flags & FFA_NOTIFICATION_FLAG_BITMAP_VM) != 0U) {
		vm_notifications = vm_notifications_partition_get_pending(
			receiver_locked, true, vcpu_id);
	}

	if ((flags & FFA_NOTIFICATION_FLAG_BITMAP_HYP) != 0U ||
	    (flags & FFA_NOTIFICATION_FLAG_BITMAP_SPM) != 0U) {
		if (!plat_ffa_notifications_get_framework_notifications(
			    receiver_locked, &framework_notifications, flags,
			    vcpu_id, &ret)) {
			dlog_verbose(
				"Failed to get notifications from "
				"framework.\n");
			goto out;
		}
	}

	ret = api_ffa_notification_get_success_return(
		sp_notifications, vm_notifications, framework_notifications);

	/*
	 * If there are no more pending notifications, change `sri_state` to
	 * handled.
	 */
	if (vm_is_notifications_pending_count_zero()) {
		plat_ffa_sri_state_set(HANDLED);
	}

	if (!receiver_locked.vm->el0_partition &&
	    !vm_are_global_notifications_pending(receiver_locked)) {
		vm_notifications_set_npi_injected(receiver_locked, false);
	}

out:
	vm_unlock(&receiver_locked);

	return ret;
}

/**
 * Prepares successful return for FFA_NOTIFICATION_INFO_GET, as described by
 * the section 17.7.1 of the FF-A v1.1 Beta0 specification.
 */
static struct ffa_value api_ffa_notification_info_get_success_return(
	const uint16_t *ids, uint32_t ids_count, const uint32_t *lists_sizes,
	uint32_t lists_count)
{
	struct ffa_value ret = (struct ffa_value){.func = FFA_SUCCESS_64};

	/*
	 * Copying content of ids into ret structure. Use 5 registers (x3-x7) to
	 * hold the list of ids.
	 */
	memcpy_s(&ret.arg3,
		 sizeof(ret.arg3) * FFA_NOTIFICATIONS_INFO_GET_REGS_RET, ids,
		 sizeof(ids[0]) * ids_count);

	/*
	 * According to the spec x2 should have:
	 * - Bit flagging if there are more notifications pending;
	 * - The total number of elements (i.e. total list size);
	 * - The number of VCPU IDs within each VM specific list.
	 */
	ret.arg2 = vm_notifications_pending_not_retrieved_by_scheduler()
			   ? FFA_NOTIFICATIONS_INFO_GET_FLAG_MORE_PENDING
			   : 0;

	ret.arg2 |= (lists_count & FFA_NOTIFICATIONS_LISTS_COUNT_MASK)
		    << FFA_NOTIFICATIONS_LISTS_COUNT_SHIFT;

	for (unsigned int i = 0; i < lists_count; i++) {
		ret.arg2 |= (lists_sizes[i] & FFA_NOTIFICATIONS_LIST_SIZE_MASK)
			    << FFA_NOTIFICATIONS_LIST_SHIFT(i + 1);
	}

	return ret;
}

struct ffa_value api_ffa_notification_info_get(struct vcpu *current)
{
	/*
	 * Following set of variables should be populated with the return info.
	 * At a successfull handling of this interface, they should be used
	 * to populate the 'ret' structure in accordance to the table 17.29
	 * of the FF-A v1.1 Beta0 specification.
	 */
	uint16_t ids[FFA_NOTIFICATIONS_INFO_GET_MAX_IDS];
	uint32_t lists_sizes[FFA_NOTIFICATIONS_INFO_GET_MAX_IDS] = {0};
	uint32_t lists_count = 0;
	uint32_t ids_count = 0;
	bool list_is_full = false;
	struct ffa_value result;

	/*
	 * This interface can only be called at NS virtual/physical FF-A
	 * instance by the endpoint implementing the primary scheduler and the
	 * Hypervisor/OS kernel.
	 * In the SPM, following check passes if call has been forwarded from
	 * the hypervisor.
	 */
	if (current->vm->id != HF_PRIMARY_VM_ID) {
		dlog_verbose(
			"Only the receiver's scheduler can use this "
			"interface\n");
		return ffa_error(FFA_NOT_SUPPORTED);
	}

	/*
	 * Forward call to the other world, and fill the arrays used to assemble
	 * return.
	 */
	plat_ffa_notification_info_get_forward(
		ids, &ids_count, lists_sizes, &lists_count,
		FFA_NOTIFICATIONS_INFO_GET_MAX_IDS);

	list_is_full = ids_count == FFA_NOTIFICATIONS_INFO_GET_MAX_IDS;

	/* Get notifications' info from this world */
	for (ffa_vm_count_t index = 0; index < vm_get_count() && !list_is_full;
	     ++index) {
		struct vm_locked vm_locked = vm_lock(vm_find_index(index));

		list_is_full = vm_notifications_info_get(
			vm_locked, ids, &ids_count, lists_sizes, &lists_count,
			FFA_NOTIFICATIONS_INFO_GET_MAX_IDS);

		vm_unlock(&vm_locked);
	}

	if (!list_is_full) {
		/* Grab notifications info from other world */
		plat_ffa_vm_notifications_info_get(
			ids, &ids_count, lists_sizes, &lists_count,
			FFA_NOTIFICATIONS_INFO_GET_MAX_IDS);
	}

	if (ids_count == 0) {
		dlog_verbose(
			"Notification info get has no data to retrieve.\n");
		result = ffa_error(FFA_NO_DATA);
	} else {
		result = api_ffa_notification_info_get_success_return(
			ids, ids_count, lists_sizes, lists_count);
	}

	plat_ffa_sri_state_set(HANDLED);

	return result;
}

struct ffa_value api_ffa_mem_perm_get(vaddr_t base_addr, struct vcpu *current)
{
	struct vm_locked vm_locked;
	struct ffa_value ret = ffa_error(FFA_INVALID_PARAMETERS);
	bool mode_ret = false;
	uint32_t mode = 0;

	if (!plat_ffa_is_mem_perm_get_valid(current)) {
		return ffa_error(FFA_NOT_SUPPORTED);
	}

	if (!(current->vm->el0_partition)) {
		return ffa_error(FFA_DENIED);
	}

	vm_locked = vm_lock(current->vm);

	/*
	 * mm_get_mode is used to check if the given base_addr page is already
	 * mapped. If the page is unmapped, return error. If the page is mapped
	 * appropriate attributes are returned to the caller. Note that
	 * mm_get_mode returns true if the address is in the valid VA range as
	 * supported by the architecture and MMU configurations, as opposed to
	 * whether a page is mapped or not. For a page to be known as mapped,
	 * the API must return true AND the returned mode must not have
	 * MM_MODE_INVALID set.
	 */
	mode_ret = mm_get_mode(&vm_locked.vm->ptable, base_addr,
			       va_add(base_addr, PAGE_SIZE), &mode);
	if (!mode_ret || (mode & MM_MODE_INVALID)) {
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	/* No memory should be marked RWX */
	CHECK((mode & (MM_MODE_R | MM_MODE_W | MM_MODE_X)) !=
	      (MM_MODE_R | MM_MODE_W | MM_MODE_X));

	/*
	 * S-EL0 partitions are expected to have all their pages marked as
	 * non-global.
	 */
	CHECK((mode & (MM_MODE_NG | MM_MODE_USER)) ==
	      (MM_MODE_NG | MM_MODE_USER));

	if (mode & MM_MODE_W) {
		/* No memory should be writeable but not readable. */
		CHECK(mode & MM_MODE_R);
		ret = (struct ffa_value){.func = FFA_SUCCESS_32,
					 .arg2 = (uint32_t)(FFA_MEM_PERM_RW)};
	} else if (mode & MM_MODE_R) {
		ret = (struct ffa_value){.func = FFA_SUCCESS_32,
					 .arg2 = (uint32_t)(FFA_MEM_PERM_RX)};
		if (!(mode & MM_MODE_X)) {
			ret.arg2 = (uint32_t)(FFA_MEM_PERM_RO);
		}
	}
out:
	vm_unlock(&vm_locked);
	return ret;
}

struct ffa_value api_ffa_mem_perm_set(vaddr_t base_addr, uint32_t page_count,
				      uint32_t mem_perm, struct vcpu *current)
{
	struct vm_locked vm_locked;
	struct ffa_value ret;
	bool mode_ret = false;
	uint32_t original_mode;
	uint32_t new_mode;
	struct mpool local_page_pool;

	if (!plat_ffa_is_mem_perm_set_valid(current)) {
		return ffa_error(FFA_NOT_SUPPORTED);
	}

	if (!(current->vm->el0_partition)) {
		return ffa_error(FFA_DENIED);
	}

	if (!is_aligned(va_addr(base_addr), PAGE_SIZE)) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	if ((mem_perm != FFA_MEM_PERM_RW) && (mem_perm != FFA_MEM_PERM_RO) &&
	    (mem_perm != FFA_MEM_PERM_RX)) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	/*
	 * Create a local pool so any freed memory can't be used by another
	 * thread. This is to ensure the original mapping can be restored if any
	 * stage of the process fails.
	 */
	mpool_init_with_fallback(&local_page_pool, &api_page_pool);

	vm_locked = vm_lock(current->vm);

	/*
	 * All regions accessible by the partition are mapped during boot. If we
	 * cannot get a successful translation for the page range, the request
	 * to change permissions is rejected.
	 * mm_get_mode is used to check if the given address range is already
	 * mapped. If the range is unmapped, return error. If the range is
	 * mapped appropriate attributes are returned to the caller. Note that
	 * mm_get_mode returns true if the address is in the valid VA range as
	 * supported by the architecture and MMU configurations, as opposed to
	 * whether a page is mapped or not. For a page to be known as mapped,
	 * the API must return true AND the returned mode must not have
	 * MM_MODE_INVALID set.
	 */

	mode_ret = mm_get_mode(&vm_locked.vm->ptable, base_addr,
			       va_add(base_addr, page_count * PAGE_SIZE),
			       &original_mode);
	if (!mode_ret || (original_mode & MM_MODE_INVALID)) {
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	/* Device memory cannot be marked as executable */
	if ((original_mode & MM_MODE_D) && (mem_perm == FFA_MEM_PERM_RX)) {
		ret = ffa_error(FFA_INVALID_PARAMETERS);
		goto out;
	}

	new_mode = MM_MODE_USER | MM_MODE_NG;

	if (mem_perm == FFA_MEM_PERM_RW) {
		new_mode |= MM_MODE_R | MM_MODE_W;
	} else if (mem_perm == FFA_MEM_PERM_RX) {
		new_mode |= MM_MODE_R | MM_MODE_X;
	} else if (mem_perm == FFA_MEM_PERM_RO) {
		new_mode |= MM_MODE_R;
	}

	/*
	 * Safe to re-map memory, since we know the requested permissions are
	 * valid, and the memory requested to be re-mapped is also valid.
	 */
	if (!mm_identity_prepare(
		    &vm_locked.vm->ptable, pa_from_va(base_addr),
		    pa_from_va(va_add(base_addr, page_count * PAGE_SIZE)),
		    new_mode, &local_page_pool)) {
		/*
		 * Defrag the table into the local page pool.
		 * mm_identity_prepare could have allocated or freed pages to
		 * split blocks or tables etc.
		 */
		mm_stage1_defrag(&vm_locked.vm->ptable, &local_page_pool);

		/*
		 * Guaranteed to succeed mapping with old mode since the mapping
		 * with old mode already existed and we have a local page pool
		 * that should have sufficient memory to go back to the original
		 * state.
		 */
		CHECK(mm_identity_prepare(
			&vm_locked.vm->ptable, pa_from_va(base_addr),
			pa_from_va(va_add(base_addr, page_count * PAGE_SIZE)),
			original_mode, &local_page_pool));
		mm_identity_commit(
			&vm_locked.vm->ptable, pa_from_va(base_addr),
			pa_from_va(va_add(base_addr, page_count * PAGE_SIZE)),
			original_mode, &local_page_pool);

		mm_stage1_defrag(&vm_locked.vm->ptable, &api_page_pool);
		ret = ffa_error(FFA_NO_MEMORY);
		goto out;
	}

	mm_identity_commit(
		&vm_locked.vm->ptable, pa_from_va(base_addr),
		pa_from_va(va_add(base_addr, page_count * PAGE_SIZE)), new_mode,
		&local_page_pool);

	ret = (struct ffa_value){.func = FFA_SUCCESS_32};

out:
	mpool_fini(&local_page_pool);
	vm_unlock(&vm_locked);

	return ret;
}

/**
 * Helper function for FFA_CONSOLE_LOG ABI.
 * Writes number of characters to a given VM buffer.
 */
static rsize_t arg_to_char_helper(struct vm_locked from_locked,
				  const uint64_t src, rsize_t src_size,
				  rsize_t to_write)
{
	bool flush = false;
	char c;
	rsize_t size = src_size < to_write ? src_size : to_write;
	rsize_t written = 0;

	if (size == 0) {
		return 0;
	}

	while (written < size) {
		c = ((char *)&src)[written++];
		if (c == '\n' || c == '\0') {
			flush = true;
		} else {
			from_locked.vm->log_buffer
				[from_locked.vm->log_buffer_length++] = c;
			flush = (from_locked.vm->log_buffer_length ==
				 LOG_BUFFER_SIZE);
		}

		if (flush) {
			dlog_flush_vm_buffer(from_locked.vm->id,
					     from_locked.vm->log_buffer,
					     from_locked.vm->log_buffer_length);
			from_locked.vm->log_buffer_length = 0;
		}
	}

	return written;
}

/**
 * Implements FFA_CONSOLE_LOG buffered logging.
 */
struct ffa_value api_ffa_console_log(const struct ffa_value args,
				     struct vcpu *current)
{
	struct vm *vm = current->vm;
	struct vm_locked vm_locked;
	size_t chars_in_param = args.func == FFA_CONSOLE_LOG_32
					? sizeof(uint32_t)
					: sizeof(uint64_t);
	size_t total_to_write = args.arg1;

	if (total_to_write == 0 || total_to_write > chars_in_param * 6) {
		return ffa_error(FFA_INVALID_PARAMETERS);
	}

	vm_locked = vm_lock(vm);

	total_to_write -= arg_to_char_helper(vm_locked, args.arg2,
					     chars_in_param, total_to_write);
	total_to_write -= arg_to_char_helper(vm_locked, args.arg3,
					     chars_in_param, total_to_write);
	total_to_write -= arg_to_char_helper(vm_locked, args.arg4,
					     chars_in_param, total_to_write);
	total_to_write -= arg_to_char_helper(vm_locked, args.arg5,
					     chars_in_param, total_to_write);
	total_to_write -= arg_to_char_helper(vm_locked, args.arg6,
					     chars_in_param, total_to_write);
	arg_to_char_helper(vm_locked, args.arg7, chars_in_param,
			   total_to_write);

	vm_unlock(&vm_locked);

	return (struct ffa_value){.func = FFA_SUCCESS_32};
}