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

/* RT-Thread System call */
#include <rtthread.h>
#include <rthw.h>
#include <board.h>

#include <string.h>
#include <stdint.h>

#define DBG_TAG    "lwp.syscall"
#define DBG_LVL    DBG_INFO
#include <rtdbg.h>

#include "syscall_generic.h"

#include "libc_musl.h"
#include "lwp_internal.h"
#ifdef ARCH_MM_MMU
#include <mm_aspace.h>
#include <lwp_user_mm.h>
#include <lwp_arch.h>
#endif

#include <fcntl.h>
#include <sys/utsname.h>

#ifdef RT_USING_DFS
#include <eventfd.h>
#include <poll.h>
#include <sys/epoll.h>
#include <sys/select.h>
#include <dfs_file.h>
#ifdef RT_USING_DFS_V2
#include <dfs_dentry.h>
#endif
#include <unistd.h>
#include <stdio.h> /* rename() */
#include <sys/stat.h>
#include <sys/statfs.h> /* statfs() */
#include <sys/timerfd.h>
#include <sys/ioctl.h>
#ifdef RT_USING_MUSLLIBC
#include <sys/signalfd.h>
#endif
#endif

#include "mqueue.h"

#ifdef RT_USING_SAL
    #include <netdev_ipaddr.h>
    #include <netdev.h>

    #include <sal_netdb.h>
    #include <sal_socket.h>
    #include <sys/socket.h>

#endif /* RT_USING_SAL */

#if (defined(RT_USING_SAL) && defined(SAL_USING_POSIX))
    #include <sys/socket.h>

    #define SYSCALL_NET(f)      f
#else
    #define SYSCALL_NET(f)      SYSCALL_SIGN(sys_notimpl)
#endif /* (defined(RT_USING_SAL) && defined(SAL_USING_POSIX)) */

#if defined(RT_USING_DFS) && defined(ARCH_MM_MMU)
    #define SYSCALL_USPACE(f)   f
#else
    #define SYSCALL_USPACE(f)   SYSCALL_SIGN(sys_notimpl)
#endif /* defined(RT_USING_DFS) && defined(ARCH_MM_MMU) */

#include "lwp_ipc_internal.h"
#include <sched.h>

#include <sys/sysinfo.h>

#ifndef GRND_NONBLOCK
#define GRND_NONBLOCK   0x0001
#endif /* GRND_NONBLOCK */

#ifndef GRND_RANDOM
#define GRND_RANDOM 0x0002
#endif /*GRND_RANDOM */

#ifndef RT_USING_POSIX_TIMER
#error "No definition RT_USING_POSIX_TIMER"
#endif /* RT_USING_POSIX_TIMER */

#ifndef RT_USING_POSIX_CLOCK
#error "No definition RT_USING_POSIX_CLOCK"
#endif /* RT_USING_POSIX_CLOCK */

void lwp_cleanup(struct rt_thread *tid);

#ifdef ARCH_MM_MMU
    #define ALLOC_KERNEL_STACK_SIZE 5120

    static void *kmem_get(size_t size)
    {
        return rt_malloc(size);
    }

    static void kmem_put(void *kptr)
    {
        rt_free(kptr);
    }
#else /* ARCH_MM_MMU */
    #define ALLOC_KERNEL_STACK_SIZE 1536
    #define ALLOC_KERNEL_STACK_SIZE_MIN 1024
    #define ALLOC_KERNEL_STACK_SIZE_MAX 4096

    extern void set_user_context(void *stack);
#endif /* ARCH_MM_MMU */

#ifdef RT_USING_SAL
    /* The same socket option is defined differently in the user interfaces and the
    * implementation. The options should be converted in the kernel. */
    #include "lwp_sys_socket.h"

    static void convert_sockopt(int *level, int *optname)
    {
        if (*level == INTF_SOL_SOCKET)
        {
            *level = IMPL_SOL_SOCKET;

            switch (*optname)
            {
                case INTF_SO_REUSEADDR:
                    *optname = IMPL_SO_REUSEADDR;
                    break;
                case INTF_SO_KEEPALIVE:
                    *optname = IMPL_SO_KEEPALIVE;
                    break;
                case INTF_SO_BROADCAST:
                    *optname = IMPL_SO_BROADCAST;
                    break;
                case INTF_SO_ACCEPTCONN:
                    *optname = IMPL_SO_ACCEPTCONN;
                    break;
                case INTF_SO_DONTROUTE:
                    *optname = IMPL_SO_DONTROUTE;
                    break;
                case INTF_SO_LINGER:
                    *optname = IMPL_SO_LINGER;
                    break;
                case INTF_SO_OOBINLINE:
                    *optname = IMPL_SO_OOBINLINE;
                    break;
                case INTF_SO_REUSEPORT:
                    *optname = IMPL_SO_REUSEPORT;
                    break;
                case INTF_SO_SNDBUF:
                    *optname = IMPL_SO_SNDBUF;
                    break;
                case INTF_SO_RCVBUF:
                    *optname = IMPL_SO_RCVBUF;
                    break;
                case INTF_SO_SNDLOWAT:
                    *optname = IMPL_SO_SNDLOWAT;
                    break;
                case INTF_SO_RCVLOWAT:
                    *optname = IMPL_SO_RCVLOWAT;
                    break;
                case INTF_SO_SNDTIMEO:
                    *optname = IMPL_SO_SNDTIMEO;
                    break;
                case INTF_SO_RCVTIMEO:
                    *optname = IMPL_SO_RCVTIMEO;
                    break;
                case INTF_SO_ERROR:
                    *optname = IMPL_SO_ERROR;
                    break;
                case INTF_SO_TYPE:
                    *optname = IMPL_SO_TYPE;
                    break;
                case INTF_SO_NO_CHECK:
                    *optname = IMPL_SO_NO_CHECK;
                    break;
                case INTF_SO_BINDTODEVICE:
                    *optname = IMPL_SO_BINDTODEVICE;
                    break;
                case INTF_SO_TIMESTAMPNS:
                    *optname = IMPL_SO_TIMESTAMPNS;
                    break;
                case INTF_SO_TIMESTAMPING:
                    *optname = IMPL_SO_TIMESTAMPING;
                    break;
                case INTF_SO_SELECT_ERR_QUEUE:
                    *optname = IMPL_SO_SELECT_ERR_QUEUE;
                    break;

                /*
                * SO_DONTLINGER (*level = ((int)(~SO_LINGER))),
                * SO_USELOOPBACK (*level = 0x0040) and
                * SO_CONTIMEO (*level = 0x1009) are not supported for now.
                */
                default:
                    *optname = 0;
                    break;
            }
            return;
        }

        if (*level == INTF_IPPROTO_IP)
        {
            *level = IMPL_IPPROTO_IP;

            switch (*optname)
            {
                case INTF_IP_TTL:
                    *optname = IMPL_IP_TTL;
                    break;
                case INTF_IP_TOS:
                    *optname = IMPL_IP_TOS;
                    break;
                case INTF_IP_MULTICAST_TTL:
                    *optname = IMPL_IP_MULTICAST_TTL;
                    break;
                case INTF_IP_MULTICAST_IF:
                    *optname = IMPL_IP_MULTICAST_IF;
                    break;
                case INTF_IP_MULTICAST_LOOP:
                    *optname = IMPL_IP_MULTICAST_LOOP;
                    break;
                case INTF_IP_ADD_MEMBERSHIP:
                    *optname = IMPL_IP_ADD_MEMBERSHIP;
                    break;
                case INTF_IP_DROP_MEMBERSHIP:
                    *optname = IMPL_IP_DROP_MEMBERSHIP;
                    break;
                default:
                    break;
            }
        }

        if (*level == INTF_IPPROTO_TCP)
        {
            *level = IMPL_IPPROTO_TCP;

            switch (*optname)
            {
                case INTF_TCP_NODELAY:
                    *optname = IMPL_TCP_NODELAY;
                    break;
                case INTF_TCP_KEEPALIVE:
                    *optname = IMPL_TCP_KEEPALIVE;
                    break;
                case INTF_TCP_KEEPIDLE:
                    *optname = IMPL_TCP_KEEPIDLE;
                    break;
                case INTF_TCP_KEEPINTVL:
                    *optname = IMPL_TCP_KEEPINTVL;
                    break;
                case INTF_TCP_KEEPCNT:
                    *optname = IMPL_TCP_KEEPCNT;
                    break;
                default:
                    break;
            }
            return;
        }

        if (*level == INTF_IPPROTO_IPV6)
        {
            *level = IMPL_IPPROTO_IPV6;

            switch (*optname)
            {
                case INTF_IPV6_V6ONLY:
                    *optname = IMPL_IPV6_V6ONLY;
                    break;
                default:
                    break;
            }
            return;
        }

    }
#endif  /* RT_USING_SAL */

#if defined(RT_USING_LWIP) || defined(SAL_USING_UNET)
    static void sockaddr_tolwip(const struct musl_sockaddr *std, struct sockaddr *lwip)
    {
        if (std && lwip)
        {
            lwip->sa_len = sizeof(*lwip);
            lwip->sa_family = (sa_family_t) std->sa_family;
            memcpy(lwip->sa_data, std->sa_data, sizeof(lwip->sa_data));
        }
    }

    static void sockaddr_tomusl(const struct sockaddr *lwip, struct musl_sockaddr *std)
    {
        if (std && lwip)
        {
            std->sa_family = (uint16_t) lwip->sa_family;
            memcpy(std->sa_data, lwip->sa_data, sizeof(std->sa_data));
        }
    }
#endif

static void _crt_thread_entry(void *parameter)
{
    rt_thread_t tid;
    rt_size_t user_stack;

    tid = rt_thread_self();

    user_stack = (rt_size_t)tid->user_stack + tid->user_stack_size;
    user_stack &= ~7; /* align 8 */

#ifdef ARCH_MM_MMU
    arch_crt_start_umode(parameter, tid->user_entry, (void *)user_stack, (char *)tid->stack_addr + tid->stack_size);
#else
    set_user_context((void*)user_stack);
    arch_start_umode(parameter, tid->user_entry, ((struct rt_lwp *)tid->lwp)->data_entry, (void*)user_stack);
#endif /* ARCH_MM_MMU */
}

/**
 * @brief Terminates all threads in the current thread group.
 *
 * This system call ends execution for all threads within the same thread group,
 * releasing resources such as memory and file descriptors. It is typically used
 * in multithreaded environments to ensure a clean exit for the entire process.
 *
 * @param value The exit code to be returned to the parent process.
 * @return sysret_t: return value of the system call execution.
 */
sysret_t sys_exit_group(int value)
{
    sysret_t rc = 0;
    lwp_status_t lwp_status;
    struct rt_lwp *lwp = lwp_self();

    if (lwp)
    {
        lwp_status = LWP_CREATE_STAT_EXIT(value);
        lwp_exit(lwp, lwp_status);
    }
    else
    {
        LOG_E("Can't find matching process of current thread");
        rc = -EINVAL;
    }

    return rc;
}

/**
 * @brief Terminates the calling thread and exits the process.
 *
 * This system call ends the execution of the calling thread and the process
 * it belongs to.
 *
 * @param status The exit code to be returned to the parent process.
 *               A value of 0 typically indicates successful execution, while
 *               non-zero values indicate an error or specific exit condition.
 * @return sysret_t: return value of the system call execution.
 *
 * @note Unlike `sys_exit_group`, which terminates all threads in a thread group,
 *       `sys_exit` only terminates the calling thread and the process.
 */
sysret_t sys_exit(int status)
{
    sysret_t rc = 0;
    rt_thread_t tid;

    tid = rt_thread_self();
    if (tid && tid->lwp)
    {
        lwp_thread_exit(tid, status);
    }
    else
    {
        LOG_E("Can't find matching process of current thread");
        rc = -EINVAL;
    }

    return rc;
}

/**
 * @brief Reads data from a file descriptor into a buffer.
 *
 * This system call reads up to `nbyte` bytes of data from the file descriptor
 * specified by `fd` into the buffer pointed to by `buf`.
 *
 * @param fd The file descriptor to read from. This should be a valid file
 *           descriptor obtained through system calls like `open()` or `socket()`.
 * @param buf A pointer to the buffer where the read data will be stored. The buffer
 *            must have enough space to accommodate up to `nbyte` bytes.
 * @param nbyte The maximum number of bytes to read. If the file contains fewer
 *              bytes than `nbyte`, only the available bytes will be read.
 * @return The number of bytes actually read, which may be less than `nbyte` if fewer
 *         bytes are available or if the end of the file is reached. Returns `0` if
 *         the end of the file is encountered. On error, returns `errno`.
 * @warning Ensure the buffer `buf` has sufficient space to hold the requested number
 *          of bytes, as failing to do so may result in undefined behavior.
 */
ssize_t sys_read(int fd, void *buf, size_t nbyte)
{
#ifdef ARCH_MM_MMU
    void *kmem = RT_NULL;
    ssize_t ret = -1;

    if (!nbyte)
    {
        return -EINVAL;
    }

    if (!lwp_user_accessable((void *)buf, nbyte))
    {
        return -EFAULT;
    }

    kmem = kmem_get(nbyte);
    if (!kmem)
    {
        return -ENOMEM;
    }

    ret = read(fd, kmem, nbyte);
    if (ret > 0)
    {
        if (ret != lwp_put_to_user(buf, kmem, ret))
            return -EFAULT;
    }

    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    kmem_put(kmem);

    return ret;
#else
    if (!lwp_user_accessable((void *)buf, nbyte))
    {
        return -EFAULT;
    }
    ssize_t ret = read(fd, buf, nbyte);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Writes data from a buffer to a file descriptor.
 *
 * This system call writes up to `nbyte` bytes of data from the buffer pointed
 * to by `buf` to the file descriptor specified by `fd`.
 *
 * @param fd The file descriptor to write to. This should be a valid file
 *           descriptor obtained through system calls like `open()` or `socket()`.
 * @param buf A pointer to the buffer containing the data to be written. The
 *            buffer must remain valid and accessible for the duration of the
 *            write operation.
 * @param nbyte The number of bytes to write from the buffer. If the file descriptor
 *              refers to a device or a socket, the actual number of bytes written
 *              may be less than `nbyte`.
 * @return The number of bytes actually written. This may be less than `nbyte` if
 *         the underlying resource cannot accept more data at the moment. On error,
 *         returns `errno`.
 *
 * @warning Ensure the buffer `buf` contains at least `nbyte` valid bytes to
 *          avoid undefined behavior. Additionally, verify that `fd` is writable
 *          to prevent errors.
 *
 * @see sys_read(), write()
 */
ssize_t sys_write(int fd, const void *buf, size_t nbyte)
{
#ifdef ARCH_MM_MMU
    void *kmem = RT_NULL;
    ssize_t ret = -1;

    if (nbyte)
    {
        if (!lwp_user_accessable((void *)buf, nbyte))
        {
            return -EFAULT;
        }

        kmem = kmem_get(nbyte);
        if (!kmem)
        {
            return -ENOMEM;
        }

        lwp_get_from_user(kmem, (void *)buf, nbyte);
    }

    ret = write(fd, kmem, nbyte);
    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    kmem_put(kmem);

    return ret;
#else
    if (!lwp_user_accessable((void *)buf, nbyte))
    {
        return -EFAULT;
    }
    ssize_t ret = write(fd, buf, nbyte);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Repositions the file offset of the open file descriptor.
 *
 * This system call sets the file offset for the open file descriptor `fd`
 * to a new position based on the `offset` and `whence` parameters. It is used
 * for seeking within files, enabling random access to file content.
 *
 * @param fd The file descriptor whose offset is to be modified. The descriptor
 *           must refer to a file capable of seeking (e.g., regular files, but
 *           not pipes or sockets).
 * @param offset The new offset value relative to the position specified by `whence`.
 *               Can be a positive or negative value, depending on the seek direction.
 * @param whence The reference point for the new offset. Must be one of the following:
 *               - `SEEK_SET`: Set the offset to `offset` bytes from the beginning of the file.
 *               - `SEEK_CUR`: Set the offset to its current position plus `offset`.
 *               - `SEEK_END`: Set the offset to the size of the file plus `offset`.
 * @return On success, returns the resulting offset location as measured in bytes
 *         from the beginning of the file. On failure, returns `errno`.
 *
 * @warning Ensure the file descriptor `fd` supports seeking. Using this function
 *          on non-seekable file descriptors (e.g., pipes or sockets) will result in an error.
 *
 * @see sys_read(), sys_write(), lseek()
 */
size_t sys_lseek(int fd, size_t offset, int whence)
{
    ssize_t ret = lseek(fd, offset, whence);
    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Opens or creates a file, returning a file descriptor.
 *
 * This system call opens the file specified by `name` with the specified
 * access mode and flags. If the file does not exist and the `O_CREAT` flag
 * is provided, it will create the file with the specified mode.
 *
 * @param name The path to the file to be opened. This can be an absolute or
 *             relative path.
 * @param flag Flags controlling how the file is opened. Common values include:
 *             - `O_RDONLY`: Open the file for read-only access.
 *             - `O_WRONLY`: Open the file for write-only access.
 *             - `O_RDWR`: Open the file for both reading and writing.
 *             - `O_CREAT`: Create the file if it does not exist (requires a mode argument).
 *             - `O_TRUNC`: Truncate the file to zero length if it exists.
 *             - `O_APPEND`: Open the file in append mode.
 * @param ... Optional. If the `O_CREAT` flag is specified, an additional
 *            `mode_t` argument must be provided, defining the file permissions
 *            (e.g., `0644` for user-read/write and group/world-read).
 * @return On success, returns the file descriptor.
 *         On failure, returns `errno`.
 *
 * @note The file descriptor returned can be used with other system calls like
 *       `sys_read()`, `sys_write()`, and `sys_close()`.
 *
 * @warning When using the `O_CREAT` flag, ensure to provide the `mode` argument
 *          to avoid undefined behavior. Additionally, verify that the process
 *          has the necessary permissions to access or create the file.
 *
 * @see sys_close(), sys_read(), sys_write(), open()
 */
sysret_t sys_open(const char *name, int flag, ...)
{
#ifdef ARCH_MM_MMU
    int ret = -1;
    rt_size_t len = 0;
    char *kname = RT_NULL;
    mode_t mode = 0;

    if (!lwp_user_accessable((void *)name, 1))
    {
        return -EFAULT;
    }

    len = lwp_user_strlen(name);
    if (!len)
    {
        return -EINVAL;
    }

    kname = (char *)kmem_get(len + 1);
    if (!kname)
    {
        return -ENOMEM;
    }

    if ((flag & O_CREAT) || (flag & O_TMPFILE) == O_TMPFILE)
    {
        va_list ap;
        va_start(ap, flag);
        mode = va_arg(ap, mode_t);
        va_end(ap);
    }

    if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
    {
        kmem_put(kname);
        return -EINVAL;
    }

    ret = open(kname, flag, mode);
    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    kmem_put(kname);

    return ret;
#else
    int ret;
    mode_t mode = 0;

    if (!lwp_user_accessable((void *)name, 1))
    {
        return -EFAULT;
    }

    if ((flag & O_CREAT) || (flag & O_TMPFILE) == O_TMPFILE)
    {
        va_list ap;
        va_start(ap, flag);
        mode = va_arg(ap, mode_t);
        va_end(ap);
    }

    ret = open(name, flag, mode);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Opens or creates a file relative to a directory file descriptor.
 *
 * This system call opens the file specified by `name`, relative to the directory
 * indicated by `dirfd`, with the specified flags and mode. It provides more
 * flexibility than `sys_open` for handling files in specific directory contexts.
 *
 * @param dirfd The file descriptor of the directory relative to which the file is opened.
 *              Special values include:
 *              - `AT_FDCWD`: Use the current working directory as the base.
 * @param name The path to the file to be opened. If `name` is absolute, `dirfd` is ignored.
 * @param flag Flags controlling how the file is opened. Common values include:
 *             - `O_RDONLY`: Open the file for read-only access.
 *             - `O_WRONLY`: Open the file for write-only access.
 *             - `O_RDWR`: Open the file for both reading and writing.
 *             - `O_CREAT`: Create the file if it does not exist.
 *             - `O_TRUNC`: Truncate the file to zero length if it exists.
 *             - `O_APPEND`: Open the file in append mode.
 *             - `O_EXCL`: Ensure the file is created exclusively (used with `O_CREAT`).
 * @param mode The permissions to set if the file is created (e.g., `0644` for user read/write
 *             and group/world read). This parameter is ignored unless `O_CREAT` is specified.
 * @return On success, returns the file descriptor.
 *         On failure, returns `errno`.
 *
 * @note The `sys_openat` system call is particularly useful for implementing secure
 *       directory traversal and operations, as it avoids race conditions when working
 *       with relative paths.
 *
 * @warning Ensure that `dirfd` is a valid directory file descriptor if a relative
 *          `name` is provided. Combining `O_CREAT` and `mode` requires proper handling
 *          to avoid unintended permission settings.
 *
 * @see sys_open(), sys_read(), sys_write(), sys_close()
 */
sysret_t sys_openat(int dirfd, const char *name, int flag, mode_t mode)
{
#ifdef ARCH_MM_MMU
    int ret = -1;
    rt_size_t len = 0;
    char *kname = RT_NULL;

    len = lwp_user_strlen(name);
    if (len <= 0)
    {
        return -EINVAL;
    }

    kname = (char *)kmem_get(len + 1);
    if (!kname)
    {
        return -ENOMEM;
    }

    lwp_get_from_user(kname, (void *)name, len + 1);
    ret = openat(dirfd, kname, flag, mode);
    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    kmem_put(kname);

    return ret;
#else
    if (!lwp_user_accessable((void *)name, 1))
    {
        return -EFAULT;
    }
    int ret = openat(dirfd, name, flag, mode);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Closes a file descriptor.
 *
 * This system call closes the file descriptor specified by `fd`, releasing any
 * resources associated with it. Once closed, the file descriptor can no longer
 * be used for operations such as reading or writing, and it may be reassigned
 * by subsequent calls to functions like `sys_open()`.
 *
 * @param fd The file descriptor to be closed. This must be a valid open file descriptor.
 * @return On success, returns 0. On failure, returns `errno`.
 *
 * @note Closing a file descriptor that is already closed results in an error.
 *       Additionally, if the file descriptor refers to a file or resource shared
 *       among multiple processes or threads, only the reference count is decremented,
 *       and the resource itself is not released until all references are closed.
 *
 * @warning Always ensure `fd` is valid before calling this function. Attempting
 *          to close an invalid or already closed descriptor may lead to undefined
 *          behavior or errors.
 *
 * @see sys_open(), sys_read(), sys_write(), close()
 */
sysret_t sys_close(int fd)
{
    int ret = close(fd);
    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Performs control operations on a file descriptor.
 *
 * This system call allows a program to manipulate the behavior of a device or file
 * associated with the file descriptor `fd` by issuing a control command (`cmd`).
 * The function provides an interface to interact with device drivers, such as modifying
 * the settings of a device or performing custom operations.
 *
 * @param fd The file descriptor representing the device or file on which the ioctl
 *           command will be performed. This should be a valid, open file descriptor.
 * @param cmd The control command to be executed. The exact behavior depends on the
 *            device and the command. Commands are usually defined by the device driver
 *            or the kernel and can vary widely.
 * @param data A pointer to a buffer used for passing data to and from the command.
 *             The contents of the buffer depend on the specific command. For input
 *             commands, it may contain the data to be written to the device. For output
 *             commands, it may hold the data returned by the device.
 * @return On success, returns 0. On failure, returns `errno`.
 *
 * @note The actual functionality of `sys_ioctl` depends heavily on the specific `cmd`
 *       and the type of device associated with the file descriptor `fd`. Each device
 *       may have a different set of valid ioctl commands.
 *
 * @warning Ensure that `fd` refers to a valid file descriptor for a device that supports
 *          ioctl commands. Providing an invalid command or using an unsupported device
 *          may lead to undefined behavior or errors.
 *
 * @see sys_open(), sys_read(), sys_write(), ioctl()
 */
sysret_t sys_ioctl(int fd, unsigned long cmd, void* data)
{
    int ret = ioctl(fd, cmd, data);
    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Retrieves information about a file associated with a file descriptor.
 *
 * This system call retrieves the status information about the file referred to
 * by the file descriptor `file` and stores it in the structure pointed to by `buf`.
 * It is typically used to obtain metadata such as file size, permissions, type,
 * and timestamps.
 *
 * @param file The file descriptor referring to an open file. It must be a valid file
 *             descriptor returned by `sys_open()` or similar system calls.
 * @param buf A pointer to a `struct stat` that will be populated with the file's
 *            status information, including attributes like size, access times,
 *            permissions, and more.
 * @return On success, returns `0`. On failure, returns `errno` to indicate the error.
 *
 * @note The structure `struct stat` typically includes the following fields:
 *       - `st_size`: Size of the file in bytes.
 *       - `st_mode`: File type and permissions.
 *       - `st_mtime`: Last modification time.
 *       - `st_atime`: Last access time.
 *       - `st_ctime`: Time of last status change.
 *
 * @warning Ensure that `file` is a valid, open file descriptor. Invalid file
 *          descriptors or unsupported file types may lead to errors when using
 *          this function.
 *
 * @see sys_open(), sys_close(), stat(), fstat()
 */
sysret_t sys_fstat(int file, struct stat *buf)
{
#ifdef ARCH_MM_MMU
    int ret = -1;
    struct stat statbuff = {0};

    if (!lwp_user_accessable((void *)buf, sizeof(struct stat)))
    {
        return -EFAULT;
    }
    else
    {
        ret = fstat(file, &statbuff);

        if (ret == 0)
        {
            lwp_put_to_user(buf, &statbuff, sizeof statbuff);
        }
        else
        {
            ret = GET_ERRNO();
        }

        return ret;
    }
#else
    if (!lwp_user_accessable((void *)buf, sizeof(struct stat)))
    {
        return -EFAULT;
    }
    int ret = fstat(file, buf);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Monitors multiple file descriptors to see if they are ready for I/O.
 *
 * This system call monitors the file descriptors specified in `fds` for any
 * I/O events such as readiness for reading, writing, or exceptional conditions.
 * It waits up to the specified timeout and returns with information about which
 * file descriptors are ready for the requested operations.
 *
 * @param fds An array of `struct pollfd` structures, each specifying a file descriptor
 *            to be monitored and the events to be checked for. On return, each structure
 *            will contain the result of the poll operation for that file descriptor.
 * @param nfds The number of elements in the `fds` array.
 * @param timeout The maximum time (in milliseconds) to wait for events. If `timeout`
 *                is `-1`, the call will block indefinitely. If `timeout` is `0`,
 *                the call will return immediately.
 * @return On success, returns the number of file descriptors with events that are ready,
 *         or `0` if the timeout expired with no events. On error, returns `-1` and sets `errno`.
 *
 * @note The `pollfd` structure used for each file descriptor contains the following fields:
 *       - `fd`: The file descriptor to be monitored.
 *       - `events`: The events to monitor (e.g., `POLLIN`, `POLLOUT`).
 *       - `revents`: The events that actually occurred.
 *
 * @warning Ensure that `fds` contains valid file descriptors. Invalid descriptors or
 *          unsupported types (such as sockets) may result in errors. Also, be mindful
 *          of the timeout behavior - passing `0` will cause an immediate return, and passing
 *          `-1` will block indefinitely.
 *
 * @see sys_select(), poll(), select()
 */
sysret_t sys_poll(struct pollfd *fds, nfds_t nfds, int timeout)
{
    int ret = -1;
#ifdef ARCH_MM_MMU
    struct pollfd *kfds = RT_NULL;

    if (!lwp_user_accessable((void *)fds, nfds * sizeof *fds))
    {
        return -EFAULT;
    }

    kfds = (struct pollfd *)kmem_get(nfds * sizeof *kfds);
    if (!kfds)
    {
        return -ENOMEM;
    }

    lwp_get_from_user(kfds, fds, nfds * sizeof *kfds);

    ret = poll(kfds, nfds, timeout);
    if (ret > 0)
    {
        lwp_put_to_user(fds, kfds, nfds * sizeof *kfds);
    }

    kmem_put(kfds);
    return ret;
#else
    if (!lwp_user_accessable((void *)fds, nfds * sizeof *fds))
    {
        return -EFAULT;
    }
    ret = poll(fds, nfds, timeout);
    return ret;
#endif /* ARCH_MM_MMU */
}

/**
 * @brief Monitors multiple file descriptors for readiness to perform I/O operations.
 *
 * This system call allows a program to monitor multiple file descriptors to see if
 * they are ready for reading, writing, or have exceptional conditions. It waits
 * for one or more of the file descriptors to become ready or for the specified
 * timeout to expire.
 *
 * @param nfds The highest-numbered file descriptor in any of the sets, plus one.
 *             This is the number of file descriptors to monitor.
 * @param readfds A pointer to an `fd_set` structure specifying the file descriptors
 *                to be checked for readability. If a file descriptor is ready to
 *                read, it will be set in the returned `fd_set`.
 * @param writefds A pointer to an `fd_set` structure specifying the file descriptors
 *                 to be checked for writability. If a file descriptor is ready to
 *                 write, it will be set in the returned `fd_set`.
 * @param exceptfds A pointer to an `fd_set` structure specifying the file descriptors
 *                  to be checked for exceptional conditions (e.g., out-of-band data).
 *                  If a file descriptor has exceptional conditions, it will be set in
 *                  the returned `fd_set`.
 * @param timeout A pointer to a `struct timeval` that specifies the maximum time
 *                to wait for an event. If `NULL`, the call blocks indefinitely. If
 *                `timeout` is `0`, the call will return immediately.
 * @return On success, returns the number of file descriptors that are ready for
 *         the requested operations, or `0` if the timeout expired without any events.
 *         On error, returns `-1` and sets `errno`.
 *
 * @note The `fd_set` structures should be initialized using the `FD_ZERO` macro
 *       and populated using the `FD_SET` macro. After the call, the `fd_set` structures
 *       will contain the file descriptors that are ready for the requested operations.
 *
 * @warning Ensure that the `fd_set` structures are properly initialized and that
 *          `nfds` correctly reflects the number of file descriptors to monitor.
 *          Passing invalid file descriptors or incorrect `nfds` can lead to undefined behavior.
 *
 * @see sys_poll(), sys_read(), sys_write(), poll(), select()
 */
sysret_t sys_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
{
#ifdef ARCH_MM_MMU
    int ret = -1;
    fd_set *kreadfds = RT_NULL, *kwritefds = RT_NULL, *kexceptfds = RT_NULL;

    if (readfds)
    {
        if (!lwp_user_accessable((void *)readfds, sizeof *readfds))
        {
            SET_ERRNO(EFAULT);
            goto quit;
        }
        kreadfds = (fd_set *)kmem_get(sizeof *kreadfds);
        if (!kreadfds)
        {
            SET_ERRNO(ENOMEM);
            goto quit;
        }
        lwp_get_from_user(kreadfds, readfds, sizeof *kreadfds);
    }
    if (writefds)
    {
        if (!lwp_user_accessable((void *)writefds, sizeof *writefds))
        {
            SET_ERRNO(EFAULT);
            goto quit;
        }
        kwritefds = (fd_set *)kmem_get(sizeof *kwritefds);
        if (!kwritefds)
        {
            SET_ERRNO(ENOMEM);
            goto quit;
        }
        lwp_get_from_user(kwritefds, writefds, sizeof *kwritefds);
    }
    if (exceptfds)
    {
        if (!lwp_user_accessable((void *)exceptfds, sizeof *exceptfds))
        {
            SET_ERRNO(EFAULT);
            goto quit;
        }
        kexceptfds = (fd_set *)kmem_get(sizeof *kexceptfds);
        if (!kexceptfds)
        {
            SET_ERRNO(EINVAL);
            goto quit;
        }
        lwp_get_from_user(kexceptfds, exceptfds, sizeof *kexceptfds);
    }

    ret = select(nfds, kreadfds, kwritefds, kexceptfds, timeout);
    if (kreadfds)
    {
        lwp_put_to_user(readfds, kreadfds, sizeof *kreadfds);
    }
    if (kwritefds)
    {
        lwp_put_to_user(writefds, kwritefds, sizeof *kwritefds);
    }
    if (kexceptfds)
    {
        lwp_put_to_user(exceptfds, kexceptfds, sizeof *kexceptfds);
    }
quit:
    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    if (kreadfds)
    {
        kmem_put(kreadfds);
    }
    if (kwritefds)
    {
        kmem_put(kwritefds);
    }
    if (kexceptfds)
    {
        kmem_put(kexceptfds);
    }
    return ret;
#else
    int ret;

    if (!lwp_user_accessable((void *)readfds, sizeof *readfds))
    {
        return -EFAULT;
    }
    if (!lwp_user_accessable((void *)writefds, sizeof *writefds))
    {
        return -EFAULT;
    }
    if (!lwp_user_accessable((void *)exceptfds, sizeof *exceptfds))
    {
        return -EFAULT;
    }
    ret = select(nfds, readfds, writefds, exceptfds, timeout);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Removes a file or symbolic link from the filesystem.
 *
 * This system call deletes the file or symbolic link specified by `pathname`.
 * After the call, the file will be unlinked from the filesystem, meaning it will
 * no longer be accessible via its pathname. If the file is still open, it will
 * remain available to processes that have it open until all file descriptors are
 * closed. If the file is a regular file and has no other hard links, it will be
 * removed from the disk once all references to it are closed.
 *
 * @param pathname The path to the file or symbolic link to be removed. It can be
 *                 an absolute or relative path.
 * @return On success, returns `0`. On failure, returns `errno` to indicate
 *         the error.
 *
 * @note If the file is currently being used by a process (i.e., the file descriptor
 *       is still open), it will not be immediately removed from the disk. The actual
 *       removal occurs once the file is no longer in use. Symbolic links are removed
 *       as soon as the call is executed.
 *
 * @warning Ensure that the file or link to be removed exists and that the `pathname`
 *          is correctly specified. The operation will fail if the file is open and
 *          in use by other processes or if the pathname does not exist.
 *
 * @see sys_open(), sys_remove(), unlink()
 */
sysret_t sys_unlink(const char *pathname)
{
#ifdef ARCH_MM_MMU
    int ret = -1;
    rt_size_t len = 0;
    char *kname = RT_NULL;

    len = lwp_user_strlen(pathname);
    if (!len)
    {
        return -EINVAL;
    }

    kname = (char *)kmem_get(len + 1);
    if (!kname)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(kname, (void *)pathname, len + 1) != (len + 1))
    {
        kmem_put(kname);
        return -EINVAL;
    }
    ret = unlink(kname);
    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    kmem_put(kname);
    return ret;
#else
    int ret = 0;
    ret = unlink(pathname);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Suspends execution for a specified amount of time.
 *
 * This system call suspends the execution of the calling thread for the duration
 * specified by the `rqtp` argument. The `rqtp` argument is a pointer to a `struct timespec`
 * that defines the sleep time in seconds and nanoseconds. If the sleep is interrupted by a signal,
 * the function may return early with the remaining time in `rmtp`, which is an optional argument.
 *
 * @param rqtp A pointer to a `struct timespec` that specifies the requested sleep time.
 *             The structure contains two fields: `tv_sec` (seconds) and `tv_nsec` (nanoseconds).
 * @param rmtp A pointer to a `struct timespec` where the remaining time will be stored if the
 *             sleep is interrupted by a signal. This can be `NULL` if the remaining time is not needed.
 * @return On success, returns `0`. On failure, returns `errno` to indicate the error.
 *
 * @note The `timespec` structure has two fields:
 *       - `tv_sec`: The number of whole seconds to sleep.
 *       - `tv_nsec`: The number of nanoseconds to sleep after the seconds. This value should be
 *         in the range [0, 1,000,000,000) nanoseconds.
 *
 * @warning Ensure that the values in `rqtp` are within valid ranges. A `tv_nsec` value greater than
 *          or equal to 1,000,000,000 will result in an error. If `rmtp` is provided, the caller
 *          must ensure the buffer is large enough to store the remaining time.
 *
 * @see sys_sleep(), clock_nanosleep(), nanosleep()
 */
sysret_t sys_nanosleep(const struct timespec *rqtp, struct timespec *rmtp)
{
    int ret = 0;
    LOG_D("sys_nanosleep\n");
    if (!lwp_user_accessable((void *)rqtp, sizeof *rqtp))
        return -EFAULT;

#ifdef ARCH_MM_MMU
    struct timespec rqtp_k;
    struct timespec rmtp_k;

    lwp_get_from_user(&rqtp_k, (void *)rqtp, sizeof rqtp_k);
    ret = nanosleep(&rqtp_k, &rmtp_k);
    if ((ret != -1 || rt_get_errno() == EINTR) && rmtp && lwp_user_accessable((void *)rmtp, sizeof *rmtp))
    {
        lwp_put_to_user(rmtp, (void *)&rmtp_k, sizeof rmtp_k);
        if(ret != 0)
            return -EINTR;
    }
#else
    if (rmtp)
    {
        if (!lwp_user_accessable((void *)rmtp, sizeof *rmtp))
            return -EFAULT;
        ret = nanosleep(rqtp, rmtp);
    }
#endif
    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Retrieves the current time and timezone information.
 *
 * This system call retrieves the current time in seconds and microseconds since
 * the Unix epoch (1970-01-01 00:00:00 UTC) and stores it in the `tp` argument.
 * It also retrieves the timezone information, if requested, and stores it in the
 * `tzp` argument. The time returned is the local time of the system unless
 * UTC is specified.
 *
 * @param tp A pointer to a `struct timeval` where the current time will be stored.
 *           The `struct timeval` contains two fields:
 *           - `tv_sec`: The number of seconds since the Unix epoch.
 *           - `tv_usec`: The number of microseconds past `tv_sec`.
 * @param tzp A pointer to a `struct timezone` where the timezone information will
 *            be stored. This structure contains two fields:
 *            - `tz_minuteswest`: The number of minutes west of UTC.
 *            - `tz_dsttime`: A flag indicating the type of daylight saving time (DST) adjustment.
 *            If `tzp` is `NULL`, timezone information is not provided.
 * @return On success, returns `0`. On failure, returns error code.
 *
 * @note The `struct timeval` represents the current time in seconds and microseconds,
 *       while `struct timezone` provides information on the timezone relative to UTC
 *       and any daylight saving adjustments.
 *
 * @warning Ensure that `tp` and `tzp` are valid pointers before calling the function.
 *          If you don't need timezone information, you can pass `NULL` for `tzp`.
 *
 * @see sys_time(), time(), gettimeofday()
 */
sysret_t sys_gettimeofday(struct timeval *tp, struct timezone *tzp)
{
#ifdef ARCH_MM_MMU
    struct timeval t_k;

    if (tp)
    {
        if (!lwp_user_accessable((void *)tp, sizeof *tp))
        {
            return -EFAULT;
        }

        t_k.tv_sec = rt_tick_get() / RT_TICK_PER_SECOND;
        t_k.tv_usec = (rt_tick_get() % RT_TICK_PER_SECOND) * (1000000 / RT_TICK_PER_SECOND);

        lwp_put_to_user(tp, (void *)&t_k, sizeof t_k);
    }
#else
    if (tp)
    {
        if (!lwp_user_accessable((void *)tp, sizeof *tp))
        {
            return -EFAULT;
        }
        tp->tv_sec = rt_tick_get() / RT_TICK_PER_SECOND;
        tp->tv_usec = (rt_tick_get() % RT_TICK_PER_SECOND) * (1000000 / RT_TICK_PER_SECOND);
    }
#endif

    return 0;
}

/**
 * @brief Sets the system's current time and timezone information.
 *
 * @param tv A pointer to a `struct timeval` that contains the new system time to set.
 *           The `struct timeval` consists of:
 *           - `tv_sec`: The number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC).
 *           - `tv_usec`: The number of microseconds past `tv_sec`.
 * @param tzp A pointer to a `struct timezone` that contains the new timezone settings.
 *            The `struct timezone` consists of:
 *            - `tz_minuteswest`: The number of minutes west of UTC.
 *            - `tz_dsttime`: The type of daylight saving time adjustment.
 *            If `tzp` is `NULL`, the timezone information is not changed.
 * @return On success, returns `0`. On failure, returns error code.
 *
 * @note haven't supported now.
 *
 * @see sys_gettimeofday(), settimeofday(), time()
 */
sysret_t sys_settimeofday(const struct timeval *tv, const struct timezone *tzp)
{
    return 0;
}

/**
 * @brief Replaces the current process with a new process.
 *
 * This system call loads a new program into the current process's address space,
 * replacing the current program with the one specified by `filename`. It passes the
 * arguments `argv` and environment variables `envp` to the new program. If the execution
 * is successful, the current process is completely replaced, and no code after the
 * `sys_exec` call is executed. If an error occurs, the system call returns, and the
 * current process continues executing.
 *
 * @param filename The path to the executable file to be run. This can be an absolute
 *                 or relative path.
 * @param argc The number of arguments passed to the new program. This includes the
 *             executable name itself as the first argument.
 * @param argv An array of strings (character pointers), where each string is an argument
 *             passed to the new program. The first element (`argv[0]`) is conventionally
 *             the name of the executable.
 * @param envp An array of strings representing the environment variables for the new
 *             process. The array is terminated by a `NULL` pointer.
 * @return This function does not return on success, as the current process is replaced.
 *         On failure, it returns error code to indicate the error.
 *
 * @note The new process inherits most of the attributes of the current process, such
 *       as file descriptors, unless explicitly modified. It is important that `argv`
 *       and `envp` are properly formatted, and the `filename` points to a valid executable.
 *
 * @warning If `filename` is invalid or not an executable, or if the arguments or
 *          environment variables are incorrectly set, the system call will fail and
 *          return `-1`. Ensure that the executable file is accessible and that `argv`
 *          and `envp` are properly constructed.
 *
 * @see execve(), execvp(), execv(), execle()
 */
sysret_t sys_exec(char *filename, int argc, char **argv, char **envp)
{
    int ret = 0;
    int len = 0;
    char *kfilename = RT_NULL;

    len = lwp_user_strlen(filename);
    if (len <= 0)
    {
        return -EFAULT;
    }

    kfilename = (char *)kmem_get(len + 1);
    if (!kfilename)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(kfilename, (void *)filename, len + 1) != (len + 1))
    {
        kmem_put(kfilename);
        return -EFAULT;
    }

    ret = lwp_execve(kfilename, 0, argc, argv, envp);

    kmem_put(kfilename);

    return ret;
}

/**
 * @brief Sends a signal to a process or a group of processes.
 *
 * This system call sends the signal specified by `signo` to the process or process group
 * identified by `pid`. If `pid` is positive, the signal is sent to the process with the
 * specified process ID. If `pid` is `0`, the signal is sent to all processes in the
 * same process group as the caller. If `pid` is `-1`, the signal is sent to all processes
 * except for the caller. If `pid` is less than `-1`, the signal is sent to all processes
 * in the process group with the process group ID equal to `-pid`.
 *
 * @param pid The process ID or process group ID to which the signal is to be sent.
 *            - A positive value sends the signal to the process with that ID.
 *            - `0` sends the signal to all processes in the same process group as the caller.
 *            - `-1` sends the signal to all processes except the caller.
 *            - A negative value sends the signal to all processes in the process group
 *              with the process group ID equal to `-pid`.
 * @param signo The signal to send. This is an integer value that specifies the signal
 *              type. Common signal values include:
 *              - `SIGTERM` (terminate process)
 *              - `SIGKILL` (force kill process)
 *              - `SIGSTOP` (suspend process)
 *              - `SIGCONT` (resume process)
 * @return On success, returns `0`. On failure, it returns error code to indicate the error.
 *
 * @note Signals are a mechanism for inter-process communication, allowing processes
 *       to send notifications or requests to other processes. The behavior of signals
 *       depends on the signal type and how the receiving process handles them.
 *
 * @warning The `signo` value must be a valid signal number. Passing an invalid signal
 *          number or an invalid `pid` may result in an error. Additionally, some signals
 *          (e.g., `SIGKILL`) cannot be caught or ignored by processes.
 *
 * @see signal(), killpg(), raise()
 */
sysret_t sys_kill(int pid, int signo)
{
    rt_err_t kret = 0;
    sysret_t sysret;
    struct rt_lwp *lwp = RT_NULL;

    /* handling the semantics of sys_kill */
    if (pid > 0)
    {
        /**
         * Brief: Match the pid and send signal to the lwp if found
         * Note: Critical Section
         * - pid tree (READ. since the lwp is fetch from the pid tree, it must stay there)
         */
        lwp_pid_lock_take();
        lwp = lwp_from_pid_raw_locked(pid);
        if (lwp)
        {
            lwp_ref_inc(lwp);
            lwp_pid_lock_release();
        }
        else
        {
            lwp_pid_lock_release();
            kret = -RT_ENOENT;
        }

        if (lwp)
        {
            kret = lwp_signal_kill(lwp, signo, SI_USER, 0);
            lwp_ref_dec(lwp);
        }
    }
    else if (pid < -1 || pid == 0)
    {
        pid_t pgid = 0;
        rt_processgroup_t group;

        if (pid == 0)
        {
            /**
             * sig shall be sent to all processes (excluding an unspecified set
             * of system processes) whose process group ID is equal to the process
             * group ID of the sender, and for which the process has permission to
             * send a signal.
             */
            pgid = lwp_pgid_get_byprocess(lwp_self());
        }
        else
        {
            /**
             * sig shall be sent to all processes (excluding an unspecified set
             * of system processes) whose process group ID is equal to the absolute
             * value of pid, and for which the process has permission to send a signal.
             */
            pgid = -pid;
        }

        group = lwp_pgrp_find(pgid);
        if (group != RT_NULL)
        {
            PGRP_LOCK(group);
            kret = lwp_pgrp_signal_kill(group, signo, SI_USER, 0);
            PGRP_UNLOCK(group);
        }
        else
        {
            kret = -ECHILD;
        }
    }
    else if (pid == -1)
    {
        /**
         * sig shall be sent to all processes (excluding an unspecified set
         * of system processes) for which the process has permission to send
         * that signal.
         */
        kret = lwp_signal_kill_all(signo, SI_USER, 0);
    }

    switch (kret)
    {
        case -RT_ENOENT:
        case -ECHILD:
            sysret = -ESRCH;
            break;
        case -RT_EINVAL:
            sysret = -EINVAL;
            break;
        case -RT_ENOSYS:
            sysret = -ENOSYS;
            break;

        /**
         * kill() never returns ENOMEM, so return normally to caller.
         * IEEE Std 1003.1-2017 says the kill() function is successful
         * if the process has permission to send sig to any of the
         * processes specified by pid.
         */
        case -RT_ENOMEM:
        default:
            sysret = 0;
    }
    return sysret;
}

/**
 * @brief Retrieves the process ID of the calling process.
 *
 * This system call returns the process ID (PID) of the calling process. The PID is a
 * unique identifier assigned by the operating system to each running process. It can
 * be used to refer to or manipulate the process in subsequent system calls.
 *
 * @return The PID of the calling process. On failure, returns `-1` and sets `errno`
 *         to indicate the error (although this function typically does not fail).
 *
 * @note The PID returned by this function is a positive integer, and it remains
 *       unique during the lifetime of the process. This value can be used to manage
 *       the process, including sending signals or querying process information.
 *
 * @warning This function does not take any arguments and is typically used when
 *          a process needs to obtain its own PID for management or logging purposes.
 *
 * @see getppid(), getuid(), getgid()
 */
sysret_t sys_getpid(void)
{
    return lwp_getpid();
}

/**
 * @brief Retrieves the parent process ID of the calling process.
 *
 * This system call returns the process ID (PID) of the parent process of the calling process.
 * The parent process is the process that created the calling process, typically through a
 * system call like `fork()`. This information can be useful for process management and
 * for determining the hierarchy of processes.
 *
 * @return The PID of the parent process. If the calling process has no parent (for example,
 *         the init process), it typically returns `1` as the PID of the system's "root" process.
 *         On failure, returns `-1` and sets `errno` to indicate the error (although this function
 *         typically does not fail).
 *
 * @note The `getppid()` function is commonly used when a process needs to know which
 *       process is responsible for it, or for managing relationships between parent and child processes.
 *
 * @warning This function does not take any arguments and is typically used when the
 *          process requires information about its parent. It should not be confused with `getpid()`,
 *          which retrieves the PID of the calling process itself.
 *
 * @see getpid(), getuid(), getgid()
 */
sysret_t sys_getppid(void)
{
    rt_lwp_t process;

    process = lwp_self();
    if (process->parent == RT_NULL)
    {
        LOG_E("%s: process %d has no parent process", __func__, lwp_to_pid(process));
        return 0;
    }
    else
    {
        return lwp_to_pid(process->parent);
    }
}

/**
 * @brief Retrieves the priority of a process or process group.
 *
 * This system call returns the priority of a process or a process group, depending on
 * the value of the `which` argument.
 *
 * @param which The entity for which the priority is being requested. Possible values include:
 *              - `PRIO_PROCESS`: Retrieves the priority of the process specified by `who`.
 *              - `PRIO_PGRP`: Retrieves the priority of the process group specified by `who`. (Currently not supported.)
 *              - `PRIO_USER`: Retrieves the priority of the user specified by `who` (the user ID). (Currently not supported.)
 * @param who The ID of the process, process group, or user. The meaning of this parameter
 *            depends on the value of `which`:
 *            - When `which` is `PRIO_PROCESS`, `who` is the process ID (PID) of the process.
 *            - When `which` is `PRIO_PGRP`(Currently not supported.), `who` is the process group ID (PGID).
 *            - When `which` is `PRIO_USER`(Currently not supported.), `who` is the user ID (UID) of the user whose
 *              priority is being queried.
 * @return On success, returns the priority value (a negative integer indicates a lower
 *         priority).
 *
 * @warning Ensure that `which` and `who` are correctly specified to avoid errors.
 *          Invalid values for `which` or `who` may result in an error, and the function
 *          will return `-1`.
 *
 * @see setpriority(), getpid(), getppid()
 */
sysret_t sys_getpriority(int which, id_t who)
{
    long prio = 0xff;

    if (which == PRIO_PROCESS)
    {
        struct rt_lwp *lwp = RT_NULL;

        lwp_pid_lock_take();
        lwp = lwp_from_pid_locked(who);

        if (lwp)
        {
            rt_thread_t thread = rt_list_entry(lwp->t_grp.prev, struct rt_thread, sibling);
            prio = RT_SCHED_PRIV(thread).current_priority;
        }

        lwp_pid_lock_release();
    }

    return prio;
}

/**
 * @brief Sets the priority of a process, process group, or user.
 *
 * This system call sets the priority of a process, process group, or user, depending
 * on the value of the `which` argument. The priority is used by the operating system
 * for scheduling processes. Lower numerical values represent higher priority in many
 * systems, and the priority range may be system-specific.
 *
 * @param which The entity for which the priority is being set. Possible values include:
 *              - `PRIO_PROCESS`: Sets the priority of the process specified by `who`.
 *              - `PRIO_PGRP`: Sets the priority of the process group specified by `who`.(Currently not supported.)
 *              - `PRIO_USER`: Sets the priority of the user specified by `who` (the user ID).(Currently not supported.)
 * @param who The ID of the process, process group, or user for which the priority is being set.
 *            The meaning of this parameter depends on the value of `which`:
 *            - When `which` is `PRIO_PROCESS`, `who` is the process ID (PID) of the process.
 *            - When `which` is `PRIO_PGRP`(Currently not supported.)  , `who` is the process group ID (PGID).
 *            - When `which` is `PRIO_USER`(Currently not supported.)  , `who` is the user ID (UID) of the user whose priority
 *              is being set.
 * @param prio The priority value to set.
 * @return On success, returns `0`. On failure, returns `-1`.
 *
 * @note This function modifies the priority of the specified process, process group, or user.
 *       The priority value is system-specific and may vary based on the system's scheduling
 *       policies. Ensure that the specified priority is within the acceptable range.
 *
 * @warning Ensure that `which`, `who`, and `prio` are valid. Invalid values for these
 *          parameters can result in errors, and the system call will return `-1`.
 *
 * @see getpriority(), getpid(), getppid()
 */
sysret_t sys_setpriority(int which, id_t who, int prio)
{
    if (which == PRIO_PROCESS)
    {
        struct rt_lwp *lwp = RT_NULL;

        lwp_pid_lock_take();
        lwp = lwp_from_pid_locked(who);

        if (lwp && prio >= 0 && prio < RT_THREAD_PRIORITY_MAX)
        {
            rt_list_t *list;
            rt_thread_t thread;
            for (list = lwp->t_grp.next; list != &lwp->t_grp; list = list->next)
            {
                thread = rt_list_entry(list, struct rt_thread, sibling);
                rt_thread_control(thread, RT_THREAD_CTRL_RESET_PRIORITY, &prio);
            }
            lwp_pid_lock_release();
            return 0;
        }
        else
        {
            lwp_pid_lock_release();
        }
    }

    return -1;
}

/**
 * @brief Creates a semaphore.
 *
 * This system call creates a new semaphore with the specified `name` and initializes
 * its value. The semaphore is used for synchronizing access to shared resources in
 * concurrent programming. The semaphore's behavior is defined by the value (`value`)
 * and any flags (`flag`) that specify additional properties or settings.
 *
 * @param name The name of the semaphore. This is a string used to identify the semaphore
 *             in the system. The name must be unique if the system requires it for reference.
 * @param value The initial value of the semaphore. The value typically represents the
 *              number of available resources or tokens. The semaphore will be initialized
 *              with this value.
 * @param flag The flag that specifies the attributes or properties of the semaphore.
 *             Flags can be used to define various characteristics of the semaphore,
 *             such as whether it is binary or counting, whether it is shared, etc.
 *
 * @return On success, returns a handle or reference to the created semaphore. On failure,
 *         returns `NULL`.
 *
 * @note Semaphores are commonly used in multithreading and multiprocessing environments
 *       to synchronize access to shared resources and ensure proper order of execution.
 *       The behavior of the semaphore depends on its type and the system's implementation.
 *
 * @warning Ensure that the `name` is unique and appropriate for your system's naming
 *          conventions. Invalid values for `value` or `flag` may lead to errors in semaphore
 *          creation.
 *
 * @see sem_wait(), sem_post(), sem_destroy()
 */
rt_sem_t sys_sem_create(const char *name, rt_uint32_t value, rt_uint8_t flag)
{
    int len = 0;
    char *kname = RT_NULL;

    len = lwp_user_strlen(name);
    if (len <= 0)
    {
        return RT_NULL;
    }

    kname = (char *)kmem_get(len + 1);
    if (!kname)
    {
        return RT_NULL;
    }

    if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
    {
        kmem_put(kname);
        return RT_NULL;
    }

    rt_sem_t sem = rt_sem_create(kname, value, flag);
    if (lwp_user_object_add(lwp_self(), (rt_object_t)sem) != 0)
    {
        rt_sem_delete(sem);
        sem = NULL;
    }

    kmem_put(kname);

    return sem;
}

/**
 * @brief Deletes a semaphore and releases associated resources.
 *
 * This system call deletes an existing semaphore identified by the given handle `sem`.
 * It releases any resources associated with the semaphore and ensures that it is no longer
 * available for further synchronization operations. After deletion, the semaphore handle
 * is invalid and should not be used.
 *
 * @param sem The semaphore handle to be deleted. This handle is obtained when the semaphore
 *            is created using `sys_sem_create()` or similar functions.
 *
 * @return On success, returns `0`. On failure, returns error code.
 *
 * @note Deleting a semaphore is a critical operation that should be performed only when
 *       the semaphore is no longer needed and no tasks are currently waiting or posting
 *       to it. Deleting a semaphore while it is still in use may lead to undefined behavior.
 *
 * @warning Ensure that no tasks are using or blocking on the semaphore before deleting it.
 *          Using a deleted semaphore will result in undefined behavior and potential system errors.
 *
 * @see sys_sem_create(), sem_wait(), sem_post()
 */
sysret_t sys_sem_delete(rt_sem_t sem)
{
    return lwp_user_object_delete(lwp_self(), (rt_object_t)sem);
}

/**
 * @brief Attempts to take (acquire) a semaphore.
 *
 * This system call attempts to acquire a semaphore, blocking the calling task until the
 * semaphore becomes available or the specified timeout expires. If the semaphore is already
 * available, the calling task will immediately take it and proceed. If the semaphore is not
 * available, the task will block until the semaphore becomes available or the timeout period
 * has elapsed. The `time` parameter specifies the maximum amount of time the task will block
 * waiting for the semaphore.
 *
 * @param sem The semaphore handle to be taken. This handle is obtained when the semaphore
 *            is created using `sys_sem_create()` or similar functions.
 * @param time The maximum time to wait for the semaphore to become available. If the semaphore
 *             is not acquired within this time period, the function will return with an error.
 *             A value of `0` means no waiting (non-blocking), while a negative value may indicate
 *             an infinite wait, depending on the system's implementation.
 *
 * @return On success, returns `0` if the semaphore was successfully taken. On failure, returns error code.
 *
 * @warning Ensure that the semaphore handle is valid and has been properly created before
 *          calling this function. If the semaphore is deleted or invalid, the behavior of
 *          this function is undefined.
 *
 * @see sys_sem_create(), sys_sem_delete(), sem_post()
 */
sysret_t sys_sem_take(rt_sem_t sem, rt_int32_t time)
{
    return rt_sem_take_interruptible(sem, time);
}

/**
 * @brief Releases a semaphore and wakes up any waiting tasks.
 *
 * This system call releases a semaphore, incrementing its value and allowing any tasks
 * that are blocked (waiting) on the semaphore to proceed. If there are tasks waiting for
 * the semaphore, one of them will be unblocked and allowed to take the semaphore.
 * The release operation does not block the calling task, and it will return immediately.
 *
 * @param sem The semaphore handle to be released. This handle is obtained when the semaphore
 *            is created using `sys_sem_create()` or similar functions.
 *
 * @return On success, returns `0`. On failure, returns error code.
 *
 * @warning Ensure that the semaphore handle is valid before calling this function. If the semaphore
 *          is deleted or invalid, the behavior of this function is undefined.
 *
 * @see sys_sem_create(), sys_sem_delete(), sys_sem_take()
 */
sysret_t sys_sem_release(rt_sem_t sem)
{
    return rt_sem_release(sem);
}

/**
 * @brief Creates a mutex.
 *
 * This system call creates a new mutex with the specified `name` and initializes it
 * with the given `flag`. The mutex is used for synchronizing access to shared resources
 * between tasks. Mutexes are typically used to ensure that only one task can access
 * a critical section of code or a resource at a time. The `flag` parameter allows
 * for setting certain properties of the mutex, such as whether it is recursive or whether
 * it can be used by multiple tasks.
 *
 * @param name The name of the mutex. This is a string used to uniquely identify the mutex
 *             within the system. The name must be unique if the system requires it.
 * @param flag The flag that specifies the attributes or properties of the mutex. Flags can
 *             define various mutex behaviors, such as whether the mutex is recursive (allows
 *             the same task to lock it multiple times) or whether it can be shared across
 *             different parts of the system.
 *
 * @return On success, returns a handle to the created mutex. On failure, returns `-RT_NULL`.
 *
 * @note Mutexes are typically used to prevent race conditions and ensure mutual exclusion
 *       when multiple tasks or threads are accessing shared resources.
 *
 * @warning Ensure that the `name` is unique and appropriate according to the system's
 *          naming conventions. Invalid values for `flag` or `name` may result in errors.
 *
 * @see sys_mutex_delete(), sys_mutex_lock(), sys_mutex_unlock()
 */
rt_mutex_t sys_mutex_create(const char *name, rt_uint8_t flag)
{
    int len = 0;
    char *kname = RT_NULL;
    rt_mutex_t mutex = RT_NULL;

    len = lwp_user_strlen(name);
    if (len <= 0)
    {
        return RT_NULL;
    }

    kname = (char *)kmem_get(len + 1);
    if (!kname)
    {
        return RT_NULL;
    }

    if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
    {
        kmem_put(kname);
        return RT_NULL;
    }

    mutex = rt_mutex_create(kname, flag);
    if(mutex == RT_NULL)
        return RT_NULL;

    if (lwp_user_object_add(lwp_self(), (rt_object_t)mutex) != 0)
    {
        rt_mutex_delete(mutex);
        mutex = RT_NULL;
    }

    kmem_put(kname);

    return mutex;
}

/**
 * @brief Deletes a mutex and releases associated resources.
 *
 * This system call deletes an existing mutex identified by the given handle `mutex`.
 * It releases any resources associated with the mutex and ensures that it is no longer
 * available for further synchronization operations. After deletion, the mutex handle
 * becomes invalid and should not be used. This operation also ensures that no tasks
 * can block or attempt to lock the mutex after it has been deleted.
 *
 * @param mutex The mutex handle to be deleted. This handle is obtained when the mutex
 *              is created using `sys_mutex_create()` or similar functions.
 *
 * @return On success, returns `0`. On failure, returns error code.
 *
 * @warning Ensure that the mutex handle is valid before calling this function. Deleting
 *          an already deleted or invalid mutex will result in undefined behavior.
 *
 * @see sys_mutex_create(), sys_mutex_lock(), sys_mutex_unlock()
 */
sysret_t sys_mutex_delete(rt_mutex_t mutex)
{
    return lwp_user_object_delete(lwp_self(), (rt_object_t)mutex);
}

/**
 * @brief Attempts to acquire (lock) a mutex.
 *
 * This system call attempts to acquire a mutex, blocking the calling task until the
 * mutex becomes available or the specified timeout expires. If the mutex is available,
 * the calling task will immediately acquire it and proceed. If the mutex is already locked
 * by another task, the calling task will block until the mutex is released or the timeout
 * period elapses. The `time` parameter specifies the maximum amount of time the task will
 * block while waiting for the mutex.
 *
 * @param mutex The mutex handle to be locked. This handle is obtained when the mutex is
 *              created using `sys_mutex_create()` or similar functions.
 * @param time The maximum time to wait for the mutex to become available. If the mutex
 *             is not acquired within this time period, the function will return an error.
 *             A value of `0` means no waiting (non-blocking), while a negative value may
 *             indicate an infinite wait.
 *
 * @return On success, returns `0` if the mutex was successfully acquired. On failure, returns error code.
 *
 * @warning Ensure that the mutex handle is valid and has been properly created before
 *          calling this function. If the mutex is deleted or invalid, the behavior of
 *          this function is undefined.
 *
 * @see sys_mutex_create(), sys_mutex_delete(), sys_mutex_unlock()
 */
sysret_t sys_mutex_take(rt_mutex_t mutex, rt_int32_t time)
{
    return rt_mutex_take_interruptible(mutex, time);
}

/**
 * @brief Releases (unlocks) a mutex.
 *
 * This system call releases a mutex that was previously acquired (locked) by the calling task.
 * If any other task is waiting for the mutex, one of them will be unblocked and allowed to
 * acquire the mutex. The release operation does not block the calling task, and it will return
 * immediately after unlocking the mutex.
 *
 * @param mutex The mutex handle to be released. This handle is obtained when the mutex is
 *              created using `sys_mutex_create()` or similar functions.
 *
 * @return On success, returns `0`. On failure, returns error code.
 *
 * @warning Ensure that the mutex handle is valid before calling this function. Attempting
 *          to release a mutex that has not been locked or is already released can result
 *          in undefined behavior.
 *
 * @see sys_mutex_create(), sys_mutex_delete(), sys_mutex_take()
 */
sysret_t sys_mutex_release(rt_mutex_t mutex)
{
    return rt_mutex_release(mutex);
}

#ifdef ARCH_MM_MMU
/**
 * @brief Adjusts the end of the data segment (heap) of the calling process.
 *
 * This system call changes the location of the program break, which defines the end of
 * the data segment (heap) of the calling process. It provides a unified interface for adjusting
 * the heap size. The `addr` parameter specifies the new location for the program break.
 *
 * @param addr The new program break location. If `addr` is `NULL`, the current program
 *             break is returned. If a valid address is provided, the program break will
 *             be adjusted to this address. The address must be page-aligned, and changes
 *             must stay within the process's allowed address space.
 *
 * @return On success, returns the new program break.
 *
 * @note This function is typically used to manage heap space in a process. The program
 *       break adjustment can impact memory allocations and deallocations in the heap.
 *
 * @warning The `addr` must be a valid address within the process's allocated memory
 *          space. Attempting to set an invalid program break address may result in
 *          undefined behavior or memory corruption.
 *
 * @see malloc(), free(), sys_sbrk()
 */
rt_base_t sys_brk(void *addr)
{
    return lwp_brk(addr);
}

/**
 * @brief Maps a file or device into memory.
 *
 * This system call implements the `mmap2` system call, which maps a file or device into memory.
 * It provides a way for processes to access file contents directly in memory, bypassing
 * the need for explicit read or write operations. This function supports advanced memory
 * mapping options such as shared or private mappings, specific protection flags, and
 * offset alignment.
 *
 * @param addr The starting address for the memory mapping. If `NULL`, the kernel chooses
 *             the address. If not `NULL`, the address must be page-aligned and meet
 *             platform-specific alignment constraints.
 * @param length The length of the memory mapping in bytes. This value is rounded up to
 *               the nearest page size.
 * @param prot The memory protection flags. Possible values include:
 *             - `PROT_READ`: Pages can be read.
 *             - `PROT_WRITE`: Pages can be written.
 *             - `PROT_EXEC`: Pages can be executed.
 *             - `PROT_NONE`: Pages cannot be accessed.
 *             These flags can be combined using bitwise OR (`|`).
 * @param flags Flags that determine the type and behavior of the mapping. Possible values include:
 *              - `MAP_SHARED`: Updates are visible to other processes that map this file.
 *              - `MAP_PRIVATE`: Updates are not visible to other processes and are not written to the file.
 *              - `MAP_FIXED`: Use the exact address specified in `addr`.
 *              - `MAP_ANONYMOUS`: The mapping is not backed by a file and uses zero-initialized memory.
 * @param fd The file descriptor of the file to map. If `MAP_ANONYMOUS` is set in `flags`,
 *           `fd` is ignored and should be set to `-1`.
 * @param pgoffset The offset in the file where the mapping starts, specified in pages (not bytes).
 *                 This allows finer-grained control over the starting point of the mapping.
 *
 * @return On success, returns a pointer to the mapped memory region.
 *
 * @warning Ensure that the combination of `addr`, `length`, `prot`, `flags`, and `fd` is valid.
 *          Improper use may lead to undefined behavior or memory access violations.
 *
 * @see mmap(), munmap(), msync()
 */
void *sys_mmap2(void *addr, size_t length, int prot,
        int flags, int fd, size_t pgoffset)
{
    sysret_t rc = 0;
    long offset = 0;

    /* aligned for user addr */
    if ((rt_base_t)addr & ARCH_PAGE_MASK)
    {
        if (flags & MAP_FIXED)
            rc = -EINVAL;
        else
        {
            offset = (char *)addr - (char *)RT_ALIGN_DOWN((rt_base_t)addr, ARCH_PAGE_SIZE);
            length += offset;
            addr = (void *)RT_ALIGN_DOWN((rt_base_t)addr, ARCH_PAGE_SIZE);
        }
    }

    if (rc == 0)
    {
        /* fix parameter passing (both along have same effect) */
        if (fd == -1 || flags & MAP_ANONYMOUS)
        {
            fd = -1;
            /* MAP_SHARED has no effect and treated as nothing */
            flags &= ~MAP_SHARED;
            flags |= MAP_PRIVATE | MAP_ANONYMOUS;
        }
        rc = (sysret_t)lwp_mmap2(lwp_self(), addr, length, prot, flags, fd, pgoffset);
    }

    return rc < 0 ? (char *)rc : (char *)rc + offset;
}

/**
 * @brief Unmaps a memory region previously mapped with mmap or mmap2.
 *
 * This system call implements the `munmap` system call, which removes a mapping
 * for a region of memory that was previously created using `mmap` or `mmap2`.
 *
 * @param addr The starting address of the memory region to unmap. This address
 *             must be page-aligned and refer to a region previously mapped.
 * @param length The length of the memory region to unmap, in bytes. This value
 *               is rounded up to the nearest page size internally if needed.
 *
 * @return On success, returns `0`. On failure, returns error code.
 *
 * @warning
 * - Ensure the specified memory region corresponds to a valid, active mapping.
 *   Providing invalid parameters may result in undefined behavior.
 * - Unmapping a region that is still in use by another thread or process can
 *   cause concurrency issues or data corruption.
 *
 * @see mmap(), mmap2(), msync()
 */
sysret_t sys_munmap(void *addr, size_t length)
{
    return lwp_munmap(lwp_self(), addr, length);
}

/**
 * @brief Changes the size or location of an existing memory mapping.
 *
 * This system call implements the `mremap` system call, allowing the resizing
 * or relocation of a previously created memory mapping. It is typically used
 * to dynamically adjust memory allocation for mapped regions without unmapping
 * and remapping them explicitly.
 *
 * @param old_address The starting address of the existing memory mapping to be resized
 *                    or relocated. This must be the address returned by a previous
 *                    `mmap` or `mremap` call.
 * @param old_size The current size of the memory mapping, in bytes. It must match
 *                 the size of the original mapping.
 * @param new_size The new desired size of the memory mapping, in bytes. The size will
 *                 be rounded up to the nearest page size if necessary.
 * @param flags Options to control the behavior of the remapping. Possible values include:
 *              - `MREMAP_MAYMOVE`: Allows the kernel to move the mapping to a new
 *                address if the current region cannot be resized in place.
 *              - `MREMAP_FIXED`: Requires the mapping to be relocated to the
 *                specified `new_address`. This flag must be used with caution.
 * @param new_address If `MREMAP_FIXED` is set in `flags`, this specifies the address
 *                    for the new mapping. Otherwise, it is ignored.
 *
 * @return On success, returns a pointer to the resized or relocated memory mapping.
 *
 * @warning
 * - Ensure that the `old_address` and `old_size` correspond to a valid, existing mapping.
 *
 * @see mmap(), munmap(), msync()
 */
void *sys_mremap(void *old_address, size_t old_size,
             size_t new_size, int flags, void *new_address)
{
    return lwp_mremap(lwp_self(), old_address, old_size, new_size, flags, new_address);
}

sysret_t sys_madvise(void *addr, size_t len, int behav)
{
    return -ENOSYS;
}
#endif

/**
 * @brief Creates an event object for inter-thread or inter-process communication.
 *
 * @param name A string representing the name of the event. If `NULL`, the event will
 *             be created without a name. Named events can be identified and accessed
 *             globally if supported by the system.
 * @param flag Specifies the behavior of the event. Possible values include:
 *             - `RT_IPC_FLAG_FIFO`: Events are handled in a first-in, first-out order.
 *             - `RT_IPC_FLAG_PRIO`: Events are handled in priority order.
 *
 * @return On success, returns a handle (`rt_event_t`) to the created event. On failure,
 *         returns `-RT_NULL` to indicate that the event could not be created.
 *
 * @note
 * - The event object must be explicitly deleted using `sys_event_delete` when it is
 *   no longer needed to free system resources.
 *
 * @warning
 * - Ensure that sufficient system resources (e.g., memory) are available to create
 *   the event. If resources are insufficient, the function will fail.
 * - Named events can potentially lead to naming conflicts if multiple events with
 *   the same name are created. Use unique names to avoid such issues.
 *
 * @see sys_event_delete(), sys_event_send(), sys_event_recv()
 */
rt_event_t sys_event_create(const char *name, rt_uint8_t flag)
{
    int len = 0;
    rt_event_t event = RT_NULL;
    char *kname = RT_NULL;

    len = lwp_user_strlen(name);
    if (len <= 0)
    {
        return RT_NULL;
    }

    kname = (char *)kmem_get(len + 1);
    if (!kname)
    {
        return RT_NULL;
    }

    if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
    {
        kmem_put(kname);
        return RT_NULL;
    }

    event = rt_event_create(kname, flag);
    if (lwp_user_object_add(lwp_self(), (rt_object_t)event) != 0)
    {
        rt_event_delete(event);
        event = NULL;
    }

    kmem_put(kname);

    return event;
}

/**
 * @brief Deletes a system event object.
 *
 * This system call removes the specified system event object, releasing
 * any resources associated with it. After deletion, the event object
 * should not be used.
 *
 * @param[in] event The handle to the event object to be deleted.
 *                  Must be a valid `rt_event_t` object.
 *
 * @return sysret_t Returns a status code indicating the result of the
 *                   operation:
 *                   - `0` if the operation was successful.
 *                   - An appropriate error code otherwise.
 *
 * @note Ensure that the event is no longer being accessed by any
 *       threads or tasks before calling this function.
 *
 * @warning Deleting an event that is in use or invalid may lead to
 *          undefined behavior.
 * @see sys_event_create(), sys_event_send(), sys_event_recv()
 */
sysret_t sys_event_delete(rt_event_t event)
{
    return lwp_user_object_delete(lwp_self(), (rt_object_t)event);
}

/**
 * @brief Sends an event to the specified event object.
 *
 * This system call sends an event to the specified event object, setting
 * the specified bits in the event object's set. The event can be used
 * to signal other threads or tasks that a particular condition has
 * occurred.
 *
 * @param[in] event The handle to the event object to which the event
 *                  will be sent. Must be a valid `rt_event_t` object.
 * @param[in] set The bits to set in the event object's set. The bits
 *                are specified as a bitmask, where each bit represents
 *                a different event condition.
 *
 * @return sysret_t Returns a status code indicating the result of the
 *                   operation:
 *                   - `0` if the operation was successful.
 *                   - An appropriate error code otherwise.
 *
 * @note The event object must be created before sending events to it.
 *
 * @warning Ensure that the event object is valid and has been created
 *          before calling this function.
 * @see sys_event_create(), sys_event_recv()
 */
sysret_t sys_event_send(rt_event_t event, rt_uint32_t set)
{
    return rt_event_send(event, set);
}

/**
 * @brief Receives an event from the specified event object.
 *
 * This system call waits for an event to be received from the specified
 * event object. The function blocks until the specified event bits are
 * set in the event object's set or the specified timeout period has
 * elapsed. If the event is received, the function returns the set of
 * bits that were set in the event object.
 *
 * @param[in] event The handle to the event object from which the event
 *                  will be received. Must be a valid `rt_event_t` object.
 * @param[in] set The bits to wait for in the event object's set. The
 *                bits are specified as a bitmask, where each bit
 *                represents a different event condition.
 * @param[in] opt The options for receiving the event. Possible values
 *                include:
 *                - `EV_EVENT_ANY`: Wait for any of the specified bits
 *                  to be set.
 *                - `EV_EVENT_ALL`: Wait for all of the specified bits
 *                  to be set.
 * @param[in] timeout The maximum time to wait for the event to be
 *                    received, in milliseconds. A value of `0` means
 *                    no waiting (non-blocking), while a negative value
 *                    may indicate an infinite wait.
 * @param[out] recved A pointer to a variable that will receive the set
 *                    of bits that were set in the event object. If the
 *                    event is received, this variable will be updated
 *                    with the set of bits.
 *
 * @return sysret_t Returns a status code indicating the result of the
 *                   operation:
 *                   - `0` if the operation was successful.
 *                   - An appropriate error code otherwise.
 *
 * @note The event object must be created before receiving events from it.
 *
 * @warning Ensure that the event object is valid and has been created
 *          before calling this function.
 * @see sys_event_create(), sys_event_send()
 */
sysret_t sys_event_recv(rt_event_t   event,
                       rt_uint32_t  set,
                       rt_uint8_t   opt,
                       rt_int32_t   timeout,
                       rt_uint32_t *recved)
{
    int ret = 0;
    rt_uint32_t krecved;

    if ((recved != NULL) && !lwp_user_accessable((void *)recved, sizeof(rt_uint32_t *)))
    {
        return -EFAULT;
    }

    ret = rt_event_recv(event, set, opt, timeout, &krecved);
    if ((ret == RT_EOK) && recved)
    {
        lwp_put_to_user((void *)recved, &krecved, sizeof(rt_uint32_t *));
    }

    return ret;
}

/**
 * @brief Creates a mailbox for inter-thread or inter-process communication.
 *
 * This system call creates a mailbox object with the specified name and size.
 * The mailbox is used to exchange messages between threads or tasks in a
 * synchronized manner. The mailbox can be used to send and receive messages
 * of a specified size.
 *
 * @param[in] name A string representing the name of the mailbox. If `NULL`,
 *                 the mailbox will be created without a name. Named mailboxes
 *                 can be identified and accessed globally if supported by the system.
 * @param[in] size The size of the mailbox, which determines the maximum number
 *                 of messages that can be stored in the mailbox at any given time.
 * @param[in] flag The behavior of the mailbox. Possible values include:
 *                 - `RT_IPC_FLAG_FIFO`: Messages are handled in a first-in, first-out order.
 *                 - `RT_IPC_FLAG_PRIO`: Messages are handled in priority order.
 *
 * @return rt_mailbox_t Returns a handle to the created mailbox object.
 *                      On failure, returns `-RT_NULL`.
 *
 * @note
 * - The mailbox object must be explicitly deleted using `sys_mb_delete` when it is
 *   no longer needed to free system resources.
 *
 * @warning
 * - Ensure that sufficient system resources (e.g., memory) are available to create
 *   the mailbox. If resources are insufficient, the function will fail.
 * - Named mailboxes can potentially lead to naming conflicts if multiple mailboxes
 *   with the same name are created. Use unique names to avoid such issues.
 *
 * @see sys_mb_delete(), sys_mb_send(), sys_mb_recv()
 */
rt_mailbox_t sys_mb_create(const char *name, rt_size_t size, rt_uint8_t flag)
{
    int len = 0;
    rt_mailbox_t mb = RT_NULL;
    char *kname = RT_NULL;

    len = lwp_user_strlen(name);
    if (len <= 0)
    {
        return RT_NULL;
    }

    kname = (char *)kmem_get(len + 1);
    if (!kname)
    {
        return RT_NULL;
    }

    if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
    {
        kmem_put(kname);
        return RT_NULL;
    }

    mb = rt_mb_create(kname, size, flag);
    if (lwp_user_object_add(lwp_self(), (rt_object_t)mb) != 0)
    {
        rt_mb_delete(mb);
        mb = NULL;
    }

    kmem_put(kname);

    return mb;
}

/**
 * @brief Deletes a mailbox object.
 *
 * This system call deletes the specified mailbox object, releasing any resources
 * associated with it. After deletion, the mailbox object should not be used.
 *
 * @param[in] mb The handle to the mailbox object to be deleted.
 *               Must be a valid `rt_mailbox_t` object.
 *
 * @return sysret_t Returns a status code indicating the result of the operation:
 *                   - `0` if the operation was successful.
 *                   - An appropriate error code otherwise.
 *
 * @note Ensure that the mailbox is no longer being accessed by any threads or tasks
 *       before calling this function.
 *
 * @warning Deleting a mailbox that is in use or invalid may lead to undefined behavior.
 *
 * @see sys_mb_create(), sys_mb_send(), sys_mb_recv()
 */
sysret_t sys_mb_delete(rt_mailbox_t mb)
{
    return lwp_user_object_delete(lwp_self(), (rt_object_t)mb);
}

/**
 * @brief Sends a message to a mailbox object.
 *
 * This system call posts a message (a single value) to the specified mailbox.
 * If the mailbox is full, the function will return an error code immediately without waiting time.
 *
 * @param[in] mb    The handle to the mailbox object where the message
 *                  will be sent. Must be a valid `rt_mailbox_t` object.
 * @param[in] value The value to be sent to the mailbox. Typically, this
 *                  is a pointer or an integral value that represents
 *                  the message content.
 *
 * @return sysret_t Returns a status code indicating the result of the
 *                   operation:
 *                   - `0` if the message was successfully sent.
 *                   - `-RT_EFULL` if the mailbox is full.
 *                   - An appropriate error code for other failures.
 *
 * @note Ensure the mailbox has been properly initialized before calling
 *       this function. Sending messages to an uninitialized or invalid
 *       mailbox may result in undefined behavior.
 *
 * @warning If the mailbox is full and the function blocks, ensure
 *          proper handling to avoid potential deadlocks.
 *
 * @see sys_mb_create(), sys_mb_recv(), sys_mb_send_wait()
 */
sysret_t sys_mb_send(rt_mailbox_t mb, rt_ubase_t value)
{
    return rt_mb_send(mb, value);
}

/**
 * @brief Sends a message to a mailbox object with a timeout.
 *
 * This system call attempts to post a message (a single value) to the specified mailbox.
 * If the mailbox is full, the function will wait for a specified timeout period
 * for space to become available. If the timeout expires before the message is sent,
 * the function returns an error.
 *
 * @param[in] mb       The handle to the mailbox object where the message
 *                     will be sent. Must be a valid `rt_mailbox_t` object.
 * @param[in] value    The value to be sent to the mailbox. Typically, this
 *                     is a pointer or an integral value representing the
 *                     message content.
 * @param[in] timeout  The maximum time to wait for space to become available
 *                     in the mailbox, in milliseconds.
 *                     - a negative value can be used to wait indefinitely.
 *                     - `0` can be used for non-blocking behavior.
 *
 * @return sysret_t Returns a status code indicating the result of the
 *                   operation:
 *                   - `0` if the message was successfully sent.
 *                   - `-RT_ETIMEOUT` if the operation timed out.
 *                   - `-RT_EFULL` if the mailbox is full and `timeout` is `0`.
 *                   - An appropriate error code for other failures.
 *
 * @note Ensure the mailbox has been properly initialized before calling this function.
 *       Passing an uninitialized or invalid mailbox handle may result in undefined behavior.
 *
 * @warning Using a negative value without appropriate logic may lead to indefinite blocking,
 *          potentially causing deadlocks.
 * @see sys_mb_send()
 */
sysret_t sys_mb_send_wait(rt_mailbox_t mb,
                         rt_ubase_t  value,
                         rt_int32_t   timeout)
{
    return rt_mb_send_wait(mb, value, timeout);
}

/**
 * @brief Receives a message from a mailbox with a timeout.
 *
 * This system call attempts to receive a message from the specified mailbox.
 * If the mailbox is empty, the function will wait for a specified timeout
 * period for a message to arrive. If no message is received within the timeout,
 * an error is returned.
 *
 * @param[in]  mb       The handle to the mailbox object from which the message
 *                      is to be received. Must be a valid `rt_mailbox_t` object.
 * @param[out] value    Pointer to a variable where the received message will
 *                      be stored. Must not be NULL.
 * @param[in]  timeout  The maximum time to wait for a message, in milliseconds.
 *                      - a negative value: Wait indefinitely until a message is available.
 *                      - `0`: Non-blocking mode. If no message is available, return immediately.
 *
 * @return sysret_t Returns a status code indicating the result of the operation:
 *                   - `0`: The message was successfully received.
 *                   - `-RT_ETIMEOUT`: The operation timed out before a message was received.
 *                   - Other error codes may indicate failures.
 *
 * @note Ensure the mailbox is properly initialized and the `value` pointer
 *       is valid before calling this function. Passing an invalid mailbox
 *       or NULL `value` pointer may lead to undefined behavior.
 *
 * @warning Using a negative value without proper safeguards may cause
 *          indefinite blocking, potentially resulting in deadlocks.
 */
sysret_t sys_mb_recv(rt_mailbox_t mb, rt_ubase_t *value, rt_int32_t timeout)
{
    int ret = 0;
    rt_ubase_t *kvalue;

    if (!lwp_user_accessable((void *)value, sizeof(rt_ubase_t *)))
    {
        return -EFAULT;
    }

    kvalue = kmem_get(sizeof(rt_ubase_t *));
    if (kvalue == RT_NULL)
    {
        return -ENOMEM;
    }

    ret = rt_mb_recv(mb, (rt_ubase_t *)kvalue, timeout);
    if (ret == RT_EOK)
    {
        lwp_put_to_user(value, kvalue, sizeof(rt_ubase_t *));
    }

    kmem_put(kvalue);

    return ret;
}

rt_weak int syslog_ctrl(int type, char *buf, int len)
{
    return -EINVAL;
}

/**
 * @brief Sends a log message to the system log.
 *
 * This system call sends a message to the system log for recording or debugging purposes.
 *
 * @param[in] type  The type of the log message, typically representing the severity
 *                  or category (e.g., debug, info, warning, error). This should be
 *                  a valid predefined log type.
 * @param[in] buf   A pointer to a buffer containing the log message. Must be a
 *                  null-terminated string and a valid pointer.
 * @param[in] len   The length of the log message to be sent, excluding the null
 *                  terminator. If the length exceeds the system log's limit,
 *                  the message may be truncated.
 *
 * @return sysret_t Returns a status code indicating the result of the operation:
 *                   - `0`: The log message was successfully recorded.
 *                   - Other error codes may indicate additional failures.
 *
 * @note Ensure the log type is a valid predefined value supported by the system.
 *       The buffer must remain valid and accessible during the execution of this function.
 *
 * @warning Sending excessively large or frequent log messages may impact system performance.
 */
sysret_t sys_syslog(int type, char *buf, int len)
{
    char *tmp;
    int ret = -1;

    if (!lwp_user_accessable((void *)buf, len))
    {
        return -EFAULT;
    }

    tmp = (char *)rt_malloc(len);
    if (!tmp)
    {
        return -ENOMEM;
    }

    ret = syslog_ctrl(type, tmp, len);
    lwp_put_to_user(buf, tmp, len);
    rt_free(tmp);

    return ret;
}

/**
 * @brief Creates a message queue.
 *
 * This system call creates a new message queue with a specified name, message size,
 * maximum number of messages, and associated flags. The message queue allows
 * messages of a given size to be sent and received between tasks or threads.
 *
 * @param[in]  name      The name of the message queue. It should be a unique
 *                       identifier and a null-terminated string.
 * @param[in]  msg_size  The size of each message in the queue. This defines
 *                       the maximum size for individual messages that can
 *                       be sent or received.
 * @param[in]  max_msgs  The maximum number of messages the queue can hold.
 *                       If the queue is full, further send operations may
 *                       block or return an error depending on the flags.
 * @param[in]  flag      Flags that control the behavior of the message queue.
 *                       This can specify whether the queue is blocking,
 *                       non-blocking, or has other specific attributes.
 *
 * @return rt_mq_t  Returns the handle to the created message queue, or `NULL`
 *                  if the creation failed (e.g., due to invalid parameters
 *                  or insufficient resources).
 *
 * @note Ensure that the message queue name is unique. The size of the messages
 *       and the number of messages should be chosen based on the application
 *       requirements.
 *
 * @warning Creating too many message queues or setting an overly large
 *          `max_msgs` may lead to resource exhaustion.
 */
rt_mq_t sys_mq_create(const char *name,
                     rt_size_t   msg_size,
                     rt_size_t   max_msgs,
                     rt_uint8_t  flag)
{
    rt_mq_t mq = RT_NULL;

    int len = 0;
    char *kname = RT_NULL;

    len = lwp_user_strlen(name);
    if (len <= 0)
    {
        return RT_NULL;
    }

    kname = (char *)kmem_get(len + 1);
    if (!kname)
    {
        return RT_NULL;
    }

    if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
    {
        kmem_put(kname);
        return RT_NULL;
    }

    mq = rt_mq_create(kname, msg_size, max_msgs, flag);
    if (lwp_user_object_add(lwp_self(), (rt_object_t)mq) != 0)
    {
        rt_mq_delete(mq);
        mq = NULL;
    }

    kmem_put(kname);

    return mq;
}

/**
 * @brief Deletes a message queue.
 *
 * This system call deletes the specified message queue and releases any resources
 * associated with it. After calling this function, the message queue handle
 * becomes invalid and should not be used.
 *
 * @param[in] mq  The handle to the message queue to be deleted.
 *               Must be a valid `rt_mq_t` object.
 *
 * @return sysret_t Returns a status code indicating the result of the operation:
 *                   - `0`: The message queue was successfully deleted.
 *                   - An appropriate error code for other failures.
 *
 * @note Ensure that no tasks or threads are using the message queue before
 *       deleting it to avoid undefined behavior or data loss.
 *
 * @warning Deleting an active message queue that is being used by tasks or
 *          threads may lead to resource leaks or corruption. Ensure proper
 *          synchronization before deletion.
 */
sysret_t sys_mq_delete(rt_mq_t mq)
{
    return lwp_user_object_delete(lwp_self(), (rt_object_t)mq);
}

/**
 * @brief Sends a message to a message queue.
 *
 * This system call sends a message to the specified message queue. The message
 * is copied into the queue's buffer. If the queue is full, the behavior will
 * depend on the flags set during queue creation (e.g., whether it is blocking
 * or non-blocking).
 *
 * @param[in] mq     The handle to the message queue where the message will be sent.
 *                   Must be a valid `rt_mq_t` object.
 * @param[in] buffer A pointer to the message data to be sent. This must not be NULL.
 * @param[in] size   The size of the message to be sent, in bytes. This should be
 *                   less than or equal to the maximum message size defined when
 *                   the queue was created.
 *
 * @return sysret_t  Returns a status code indicating the result of the operation:
 *                    - `0`: The message was successfully sent to the queue.
 *                    - An appropriate error code for other failures.
 *
 * @note Ensure that the message size does not exceed the maximum allowed message
 *       size when the queue was created. Passing an invalid queue handle or buffer
 *       may result in undefined behavior.
 *
 * @warning Sending messages to a full queue in blocking mode may cause the calling
 *          task or thread to block indefinitely if not properly handled.
 */
sysret_t sys_mq_send(rt_mq_t mq, void *buffer, rt_size_t size)
{
    int ret = 0;
    void *kbuffer = RT_NULL;

    if (!lwp_user_accessable((void *)buffer, size))
    {
        return -EFAULT;
    }

    kbuffer = kmem_get(size);
    if (kbuffer == RT_NULL)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(kbuffer, buffer, size) != size)
    {
        kmem_put(kbuffer);
        return -EINVAL;
    }

    ret = rt_mq_send(mq, kbuffer, size);

    kmem_put(kbuffer);

    return ret;
}

/**
 * @brief Sends an urgent message to a message queue.
 *
 * This system call sends a message to the specified message queue with higher priority,
 * meaning it will be placed at the front of the queue, bypassing normal message
 * order. The message is copied into the queue's buffer. If the queue is full,
 * the behavior will depend on the flags set during queue creation (e.g., whether
 * it is blocking or non-blocking).
 *
 * @param[in] mq     The handle to the message queue where the message will be sent.
 *                   Must be a valid `rt_mq_t` object.
 * @param[in] buffer A pointer to the message data to be sent. This must not be NULL.
 * @param[in] size   The size of the message to be sent, in bytes. This should be
 *                   less than or equal to the maximum message size defined when
 *                   the queue was created.
 *
 * @return sysret_t  Returns a status code indicating the result of the operation:
 *                    - `0`: The urgent message was successfully sent to the queue.
 *                    - `-RT_EFULL`: The queue is full and the message could not be sent.
 *                    - An appropriate error code for other failures.
 *
 * @note Ensure that the message size does not exceed the maximum allowed message
 *       size when the queue was created. The urgent message will be processed before
 *       other normal messages in the queue.
 *
 * @warning Sending urgent messages to a full queue in blocking mode may cause the
 *          calling task or thread to block indefinitely if not properly handled.
 */
sysret_t sys_mq_urgent(rt_mq_t mq, void *buffer, rt_size_t size)
{
    int ret = 0;
    void *kbuffer = RT_NULL;

    if (!lwp_user_accessable((void *)buffer, size))
    {
        return -EFAULT;
    }

    kbuffer = kmem_get(size);
    if (kbuffer == RT_NULL)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(kbuffer, buffer, size) != size)
    {
        kmem_put(kbuffer);
        return -EINVAL;
    }

    ret = rt_mq_urgent(mq, kbuffer, size);

    kmem_put(kbuffer);

    return ret;
}

/**
 * @brief Receives a message from a message queue.
 *
 * This system call attempts to receive a message from the specified message queue.
 * The message is copied into the provided buffer. If no message is available
 * in the queue, the function will block for a specified timeout period before
 * returning. If the timeout expires without receiving a message, an error is returned.
 *
 * @param[in]  mq       The handle to the message queue from which the message
 *                      will be received. Must be a valid `rt_mq_t` object.
 * @param[out] buffer   A pointer to the buffer where the received message will
 *                      be stored. Must not be NULL and large enough to hold the
 *                      message.
 * @param[in]  size     The size of the buffer, in bytes. This should be at least
 *                      the size of a message in the queue.
 * @param[in]  timeout  The maximum time to wait for a message, in milliseconds.
 *                      - a negative value: Wait indefinitely until a message is available.
 *                      - `0`: Non-blocking mode. If no message is available, return immediately.
 *
 * @return sysret_t Returns a status code indicating the result of the operation:
 *                   - `0`: The message was successfully received.
 *                   - `-RT_ETIMEOUT`: The operation timed out before a message was received.
 *                   - Other error codes may indicate additional failures.
 *
 * @note Ensure the buffer is large enough to store the message received from the queue.
 *       If the buffer is too small, the function may fail or behave unexpectedly.
 *
 * @warning Using a negative value without proper safeguards may cause indefinite
 *          blocking, potentially resulting in deadlocks if no message is received.
 */
sysret_t sys_mq_recv(rt_mq_t    mq,
                    void      *buffer,
                    rt_size_t  size,
                    rt_int32_t timeout)
{
    int ret = 0;
    void *kbuffer = RT_NULL;

    if (!lwp_user_accessable((void *)buffer, size))
    {
        return -EFAULT;
    }

    kbuffer = kmem_get(size);
    if (kbuffer == RT_NULL)
    {
        return -ENOMEM;
    }

    ret = rt_mq_recv(mq, kbuffer, size, timeout);
    if (ret > 0)
        lwp_put_to_user((void *)buffer, (void *)kbuffer, ret);

    kmem_put(kbuffer);

    return ret;
}

static void timer_timeout_callback(void *parameter)
{
    rt_sem_t sem = (rt_sem_t)parameter;
    rt_sem_release(sem);
}

/**
 * @brief Creates a timer.
 *
 * This system call creates a timer that can be used to trigger events or
 * actions after a specified timeout or interval. The timer will operate in a
 * real-time manner and can be configured to trigger once or repeatedly. The
 * created timer can be started, stopped, or deleted as required.
 *
 * @param[in]  name   The name of the timer. It should be a unique string identifier.
 *                    The name is used for debugging and logging purposes.
 * @param[in]  data   A pointer to user-defined data that will be passed to the timer's
 *                    callback function when it is triggered. This may be used to carry
 *                    context or other necessary information for the callback.
 * @param[in]  period The timer period in milliseconds. The timer will trigger every
 *                    `period` milliseconds, or after the specified timeout.
 * @param[in]  flag   Flags that control the behavior of the timer. These can specify
 *                    whether the timer is one-shot (triggers once) or periodic
 *                    (triggers repeatedly).
 *
 * @return rt_timer_t Returns the handle to the created timer, or `NULL` if the creation failed.
 *
 * @note The timer callback function must be implemented to handle the event triggered
 *       by the timer. Ensure that the `data` parameter, if used, is properly handled
 *       in the callback.
 *
 * @warning Ensure the timer's period and flags are configured correctly to avoid
 *          undesired behavior, especially if the timer is periodic.
 */
rt_timer_t sys_rt_timer_create(const char *name,
                               void *data,
                               rt_tick_t time,
                               rt_uint8_t flag)
{
    int len = 0;
    char *kname = RT_NULL;
    rt_timer_t timer = RT_NULL;

    len = lwp_user_strlen(name);
    if (len <= 0)
    {
        return RT_NULL;
    }

    kname = (char *)kmem_get(len + 1);
    if (!kname)
    {
        return RT_NULL;
    }

    if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
    {
        kmem_put(kname);
        return RT_NULL;
    }

    timer = rt_timer_create(kname, timer_timeout_callback, (void *)data, time, flag);
    if (lwp_user_object_add(lwp_self(), (rt_object_t)timer) != 0)
    {
        rt_timer_delete(timer);
        timer = NULL;
    }

    kmem_put(kname);

    return timer;
}

/**
 * @brief Deletes a timer.
 *
 * This system call deletes the specified timer and releases any resources
 * associated with it. Once the timer is deleted, its handle becomes invalid,
 * and any further operations on the timer should be avoided.
 *
 * @param[in] timer  The handle to the timer to be deleted. Must be a valid `rt_timer_t` object.
 *
 * @return sysret_t Returns a status code indicating the result of the operation:
 *                   - `0`: The timer was successfully deleted.
 *                   - Other error codes may indicate additional failures.
 *
 * @note Ensure that the timer is not active or being used before deleting it to avoid
 *       any unexpected behavior or resource leaks.
 *
 * @warning Deleting an active timer may lead to undefined behavior, especially
 *          if the timer is in the middle of triggering or executing its callback.
 */
sysret_t sys_rt_timer_delete(rt_timer_t timer)
{
    return lwp_user_object_delete(lwp_self(), (rt_object_t)timer);
}

/**
 * @brief Starts a timer.
 *
 * This system call starts the specified timer, causing it to begin counting down
 * based on its configured period. Once the timer reaches the set period, it triggers the
 * associated callback function. The behavior depends on whether the timer is configured
 * as one-shot or periodic.
 *
 * @param[in] timer  The handle to the timer to be started. Must be a valid `rt_timer_t` object.
 *
 * @return sysret_t  Returns a status code indicating the result of the operation:
 *                    - `0`: The timer was successfully started.
 *                    - Other error codes may indicate additional failures.
 *
 * @note Ensure that the timer has been created and is in a valid state before attempting to start it.
 *
 * @warning Starting a timer that is already running may lead to undefined behavior. Ensure that the
 *          timer is stopped or not in use before starting it.
 */
sysret_t sys_rt_timer_start(rt_timer_t timer)
{
    return rt_timer_start(timer);
}

/**
 * @brief Stops a timer.
 *
 * This system call stops the specified timer, halting its countdown and
 * preventing it from triggering further callbacks. If the timer is periodic,
 * stopping it will prevent further periodic triggers until it is started again.
 *
 * @param[in] timer  The handle to the timer to be stopped. Must be a valid `rt_timer_t` object.
 *
 * @return sysret_t  Returns a status code indicating the result of the operation:
 *                    - `0`: The timer was successfully stopped.
 *                    - Other error codes may indicate additional failures.
 *
 * @note Ensure that the timer is in a valid state before attempting to stop it.
 *       Stopping an inactive or already stopped timer may not have any effect.
 *
 * @warning Stopping a timer that is actively triggering or in use may disrupt its expected
 *          behavior. Ensure proper synchronization or state management when stopping
 *          the timer during active use.
 */
sysret_t sys_rt_timer_stop(rt_timer_t timer)
{
    return rt_timer_stop(timer);
}

/**
 * @brief Controls various properties of a timer.
 *
 * This system call provides control over various aspects of a timer, such as
 * modifying its configuration, querying its status, or changing its behavior.
 * The specific behavior is determined by the command (`cmd`) and any associated arguments (`arg`).
 *
 * @param[in]  timer  The handle to the timer to be controlled. Must be a valid `rt_timer_t` object.
 * @param[in]  cmd    The command to execute. The meaning of this parameter depends on the command value.
 *                    Common commands might include modifying the timer period, changing its callback,
 *                    or querying its current state.
 * @param[in]  arg    A pointer to any additional arguments needed for the command. The type and content
 *                    of this argument depend on the specific command being executed.
 *
 * @return sysret_t  Returns a status code indicating the result of the operation:
 *                    - `0`: The timer control operation was successful.
 *                    - Other error codes may indicate additional failures.
 *
 * @note Ensure that the provided command (`cmd`) is valid for the specific timer implementation.
 *       Incorrect commands or arguments may lead to unexpected behavior or errors.
 *
 * @warning Using invalid or unsupported commands may cause undefined behavior or crashes.
 */
sysret_t sys_rt_timer_control(rt_timer_t timer, int cmd, void *arg)
{
    return rt_timer_control(timer, cmd, arg);
}

/* MUSL compatible */
struct ksigevent
{
    union sigval sigev_value;
    int sigev_signo;
    int sigev_notify;
    int sigev_tid;
};

/* to protect unsafe implementation in current rt-smart toolchain */
RT_STATIC_ASSERT(sigevent_compatible, offsetof(struct ksigevent, sigev_tid) == offsetof(struct sigevent, sigev_notify_function));

/**
 * @brief Creates a per-process timer.
 *
 * This system call creates a new timer associated with the specified clock, and
 * initializes the timer with the provided event notification attributes.
 * Once created, the timer can be started, stopped, or controlled as needed.
 * The timer will trigger when the specified expiration time or interval is reached.
 *
 * @param[in]  clockid   The clock to be used for the timer. Common clock values include:
 *                       - `CLOCK_REALTIME`: System real-time clock.
 *                       - `CLOCK_MONOTONIC`: Monotonic clock that cannot be set and is not affected by system time changes.
 *                       - Other clock IDs can be used depending on the platform and requirements.
 * @param[in]  sevp      A pointer to a `sigevent` structure that specifies how the process
 *                       should be notified when the timer expires. This can include notification
 *                       types such as signal delivery, thread notification, or posting to a queue.
 * @param[out] timerid   A pointer to a `timer_t` variable where the created timer's ID will be stored.
 *                       The timer ID will be used for subsequent timer operations (e.g., starting, stopping).
 *
 * @return sysret_t      Returns a status code indicating the result of the operation:
 *                       - `0`: The timer was successfully created.
 *                       - Other error codes may indicate additional failures.
 *
 * @warning Ensure that the provided `sigevent` structure is properly configured, as invalid or
 *          unsupported notification types may result in unexpected behavior.
 */
sysret_t sys_timer_create(clockid_t clockid, struct sigevent *restrict sevp, timer_t *restrict timerid)
{
    int ret = 0;
#ifdef ARCH_MM_MMU
    struct sigevent sevp_k;
    timer_t timerid_k;
    int utimer;

    if (sevp == NULL)
    {
        sevp_k.sigev_notify = SIGEV_SIGNAL;
        sevp_k.sigev_signo = SIGALRM;
        sevp = &sevp_k;
    }
    else
    {
        /* clear extra bytes if any */
        if (sizeof(struct ksigevent) < sizeof(struct sigevent))
            memset(&sevp_k, 0, sizeof(sevp_k));

        /* musl passes `struct ksigevent` to kernel, we shoule only get size of that bytes */
        if (!lwp_get_from_user(&sevp_k, (void *)sevp, sizeof(struct ksigevent)))
        {
            return -EINVAL;
        }
    }

    ret = _SYS_WRAP(timer_create(clockid, &sevp_k, &timerid_k));

    if (ret != -RT_ERROR)
    {
        utimer = (rt_ubase_t)timerid_k;
        if (!lwp_put_to_user(sevp, (void *)&sevp_k, sizeof(struct ksigevent)) ||
            !lwp_put_to_user(timerid, (void *)&utimer, sizeof(utimer)))
            ret = -EINVAL;
    }
#else
    ret = _SYS_WRAP(timer_create(clockid, sevp, timerid));
#endif
    return ret;
}

/**
 * @brief Deletes a timer.
 *
 * This system call deletes the specified timer and releases any resources associated
 * with it. Once the timer is deleted, it can no longer be used, and any further
 * operations on the timer (such as starting or stopping) will result in an error.
 *
 * @param[in] timerid  The ID of the timer to be deleted. This is the timer handle
 *                     returned by `sys_timer_create`.
 *
 * @return sysret_t    Returns a status code indicating the result of the operation:
 *                     - `0`: The timer was successfully deleted.
 *                     - Other error codes may indicate additional failures.
 *
 * @note After calling this function, the timer ID becomes invalid, and it should
 *       not be used in any further operations.
 *
 * @warning Make sure the timer is not active or in use when attempting to delete it,
 *          as deleting an active timer may cause unexpected behavior or resource leaks.
 */
sysret_t sys_timer_delete(timer_t timerid)
{
    int ret = timer_delete(timerid);
    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Changes the time or interval of an existing timer.
 *
 * This system call modifies the expiration time or interval of a previously created
 * timer. It can either set a new expiration time for the timer or update the
 * interval for periodic timers. The timer can be started or modified based on
 * the flags provided. The current (old) timer settings can be retrieved if
 * requested.
 *
 * @param[in]  timerid      The ID of the timer to modify. This is the timer handle
 *                          returned by `sys_timer_create`.
 * @param[in]  flags        Flags that control the behavior of the operation. Common
 *                          values include:
 *                          - `TIMER_ABSTIME`: Specifies that `new_value` contains
 *                            an absolute time. Otherwise, it is treated as relative.
 * @param[in]  new_value    A pointer to the `itimerspec` structure specifying
 *                          the new time settings for the timer. The structure includes:
 *                          - `it_value`: The initial expiration time (relative or absolute).
 *                          - `it_interval`: The period for periodic timers.
 * @param[out] old_value    A pointer to an `itimerspec` structure where the previous
 *                          timer settings will be stored. If NULL, the old value is ignored.
 *
 * @return sysret_t         Returns a status code indicating the result of the operation:
 *                          - `0`: The timer time/interval was successfully updated.
 *                          - Other error codes may indicate additional failures.
 *
 * @warning Modifying a timer that is currently active can cause timing-related issues
 *          if not handled correctly. Make sure the timer is in an appropriate state
 *          before making changes.
 */
sysret_t sys_timer_settime(timer_t timerid, int flags,
                           const struct itimerspec *restrict new_value,
                           struct itimerspec *restrict old_value)
{
    int ret = 0;
#ifdef ARCH_MM_MMU
    struct itimerspec new_value_k;
    struct itimerspec old_value_k;

    if (!lwp_get_from_user(&new_value_k, (void *)new_value, sizeof(*new_value)) ||
        (old_value && !lwp_get_from_user(&old_value_k, (void *)old_value, sizeof(*old_value))))
    {
        return -EFAULT;
    }

    ret = timer_settime(timerid, flags, &new_value_k, &old_value_k);
    lwp_put_to_user(old_value, (void *)&old_value_k, sizeof old_value_k);

#else
    ret = timer_settime(timerid, flags, new_value, old_value);
#endif
    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Retrieves the current time and interval of a timer.
 *
 * This system call fetches the current expiration time (`it_value`) and interval (`it_interval`)
 * of a previously created timer. It allows the caller to determine the current state of the timer,
 * whether it is one-shot or periodic, and the remaining time before expiration.
 *
 * @param[in]  timerid      The ID of the timer to query. This is the timer handle
 *                          returned by `sys_timer_create`.
 * @param[out] curr_value   A pointer to an `itimerspec` structure where the current timer values
 *                          will be stored. This structure includes:
 *                          - `it_value`: The remaining time until the timer expires.
 *                          - `it_interval`: The interval between subsequent expirations (for periodic timers).
 *
 * @return sysret_t         Returns a status code indicating the result of the operation:
 *                          - `0`: The current time/interval was successfully retrieved.
 *                          - Other error codes may indicate additional failures.
 *
 * @warning Ensure that the timer ID is valid before calling this function, as invalid timer IDs
 *          will result in errors.
 */
sysret_t sys_timer_gettime(timer_t timerid, struct itimerspec *curr_value)
{
    int ret = 0;
#ifdef ARCH_MM_MMU

    struct itimerspec curr_value_k;
    lwp_get_from_user(&curr_value_k, (void *)curr_value, sizeof curr_value_k);
    ret = timer_gettime(timerid, &curr_value_k);
    lwp_put_to_user(curr_value, (void *)&curr_value_k, sizeof curr_value_k);
#else
    ret = timer_gettime(timerid, curr_value);
#endif
    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Retrieves the overrun count for a periodic timer.
 *
 * This system call retrieves the number of times a periodic timer has "overrun." An overrun occurs
 * when a timer expires before the previous expiration has been acknowledged or handled. For periodic
 * timers, this indicates how many times the timer's expiration has been missed due to delayed processing
 * or handling.
 *
 * @param[in]  timerid      The ID of the timer to query. This is the timer handle
 *                          returned by `sys_timer_create`.
 *
 * @return sysret_t         Returns a status code indicating the result of the operation:
 *                          - `0`: The overrun count was successfully retrieved.
 *                         - Other error codes may indicate additional failures.
 *
 * @warning Ensure that the timer ID is valid before calling this function, as invalid timer IDs
 *          will result in errors.
 */
sysret_t sys_timer_getoverrun(timer_t timerid)
{
    int ret = 0;
    ret = timer_getoverrun(timerid);
    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Creates a new thread.
 *
 * This system call creates a new thread within the calling process. The newly created
 * thread starts executing the function specified by the `arg` argument, which typically
 * contains the necessary arguments or function pointer for the thread's execution.
 *
 * @param[in] arg     An array of arguments that will be passed to the function executed
 *                    by the new thread. This can include function pointers, structures,
 *                    or any necessary data the thread will need to execute its work.
 *
 * @return rt_thread_t    Returns a handle to the newly created thread. If the thread
 *                        creation fails, `NULL` is returned.
 *
 * @warning Ensure that the system has sufficient resources to create a new thread.
 *          Thread creation failures can occur if system limits are exceeded or resources
 *          are unavailable.
 */
rt_thread_t sys_thread_create(void *arg[])
{
    void *user_stack = 0;
    struct rt_lwp *lwp = 0;
    rt_thread_t thread = RT_NULL;
    int tid = 0;

    lwp = rt_thread_self()->lwp;
    lwp_ref_inc(lwp);
#ifdef ARCH_MM_MMU
    user_stack = lwp_map_user(lwp, 0, (size_t)arg[3], 0);
    if (!user_stack)
    {
        goto fail;
    }
    if ((tid = lwp_tid_get()) == 0)
    {
        goto fail;
    }
    thread = rt_thread_create((const char *)arg[0],
            _crt_thread_entry,
            (void *)arg[2],
            ALLOC_KERNEL_STACK_SIZE,
            (rt_uint8_t)(size_t)arg[4],
            (rt_uint32_t)(rt_size_t)arg[5]);
    if (!thread)
    {
        goto fail;
    }

#ifdef RT_USING_SMP
    RT_SCHED_CTX(thread).bind_cpu = lwp->bind_cpu;
#endif
    thread->cleanup = lwp_cleanup;
    thread->user_entry = (void (*)(void *))arg[1];
    thread->user_stack = (void *)user_stack;
    thread->user_stack_size = (rt_size_t)arg[3];
#else
    rt_uint32_t kstack_size = (rt_uint32_t)arg[7];
    if (kstack_size < ALLOC_KERNEL_STACK_SIZE_MIN)
    {
        /* When kstack size is 0, the default size of the kernel stack is used */
        kstack_size = kstack_size ? ALLOC_KERNEL_STACK_SIZE_MIN : ALLOC_KERNEL_STACK_SIZE;
    }
    else if (kstack_size > ALLOC_KERNEL_STACK_SIZE_MAX)
    {
        kstack_size = ALLOC_KERNEL_STACK_SIZE_MAX;
    }

    user_stack  = (void *)arg[3];
    if ((!user_stack) || ((rt_uint32_t)arg[6] == RT_NULL))
    {
        goto fail;
    }

    if ((tid = lwp_tid_get()) == 0)
    {
        goto fail;
    }

    thread = rt_thread_create((const char *)arg[0], _crt_thread_entry, (void *)arg[2], kstack_size, (rt_uint8_t)(size_t)arg[5], (rt_uint32_t)arg[6]);
    if (!thread)
    {
        goto fail;
    }
    thread->cleanup = lwp_cleanup;
    thread->user_entry = (void (*)(void *))arg[1];
    thread->user_stack = (void *)user_stack;
    thread->user_stack_size = (uint32_t)arg[4];
    rt_memset(thread->user_stack, '#', thread->user_stack_size);
#endif /* ARCH_MM_MMU */

    thread->lwp = (void*)lwp;
    thread->tid = tid;
    lwp_tid_set_thread(tid, thread);

    if (lwp->debug)
    {
        rt_thread_control(thread, RT_THREAD_CTRL_BIND_CPU, (void*)0);
    }

    LWP_LOCK(lwp);
    rt_list_insert_after(&lwp->t_grp, &thread->sibling);
    LWP_UNLOCK(lwp);

    return thread;

fail:
    lwp_tid_put(tid);
    if (lwp)
    {
        lwp_ref_dec(lwp);
    }
    return RT_NULL;
}

#ifdef ARCH_MM_MMU

long _sys_clone(void *arg[])
{
    struct rt_lwp *lwp = 0;
    rt_thread_t thread = RT_NULL;
    rt_thread_t self = RT_NULL;
    int tid = 0;
    rt_err_t err;

    unsigned long flags = 0;
    void *user_stack = RT_NULL;
    int *new_tid = RT_NULL;
    void *tls = RT_NULL;
    /*
       musl call flags (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND
       | CLONE_THREAD | CLONE_SYSVSEM | CLONE_SETTLS
       | CLONE_PARENT_SETTID | CLONE_CHILD_CLEARTID | CLONE_DETACHED);
       */

    /* check args */
    if (!lwp_user_accessable(arg, sizeof(void *[SYS_CLONE_ARGS_NR])))
    {
        return -EFAULT;
    }

    flags = (unsigned long)(size_t)arg[0];
    if ((flags & (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_THREAD | CLONE_SYSVSEM))
            != (CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_THREAD | CLONE_SYSVSEM))
    {
        return -EINVAL;
    }

    user_stack = arg[1];
    new_tid = (int *)arg[2];
    tls = (void *)arg[3];

    if ((flags & CLONE_PARENT_SETTID) == CLONE_PARENT_SETTID)
    {
        if (!lwp_user_accessable(new_tid, sizeof(int)))
        {
            return -EFAULT;
        }
    }

    self = rt_thread_self();
    lwp = self->lwp;
    lwp_ref_inc(lwp);
    if (!user_stack)
    {
        SET_ERRNO(EINVAL);
        goto fail;
    }
    if ((tid = lwp_tid_get()) == 0)
    {
        SET_ERRNO(ENOMEM);
        goto fail;
    }

    thread = rt_thread_create(self->parent.name,
            RT_NULL,
            RT_NULL,
            self->stack_size,
            RT_SCHED_PRIV(self).init_priority,
            RT_SCHED_PRIV(self).init_tick);
    if (!thread)
    {
        goto fail;
    }

#ifdef RT_USING_SMP
    RT_SCHED_CTX(self).bind_cpu = lwp->bind_cpu;
#endif
    thread->cleanup = lwp_cleanup;
    thread->user_entry = RT_NULL;
    thread->user_stack = RT_NULL;
    thread->user_stack_size = 0;
    thread->lwp = (void *)lwp;
    thread->tid = tid;

    if ((flags & CLONE_SETTLS) == CLONE_SETTLS)
    {
        thread->thread_idr = tls;
    }
    if ((flags & CLONE_PARENT_SETTID) == CLONE_PARENT_SETTID)
    {
        *new_tid = (int)(tid);
    }
    if ((flags & CLONE_CHILD_CLEARTID) == CLONE_CHILD_CLEARTID)
    {
        thread->clear_child_tid = (int *)arg[4];
    }

    if (lwp->debug)
    {
        rt_thread_control(thread, RT_THREAD_CTRL_BIND_CPU, (void*)0);
    }

    LWP_LOCK(lwp);
    rt_list_insert_after(&lwp->t_grp, &thread->sibling);
    LWP_UNLOCK(lwp);

    /* copy origin stack */
    lwp_memcpy(thread->stack_addr, self->stack_addr, thread->stack_size);
    lwp_tid_set_thread(tid, thread);
    arch_set_thread_context(arch_clone_exit,
            (void *)((char *)thread->stack_addr + thread->stack_size),
            user_stack, &thread->sp);
    /* new thread never reach there */
    rt_thread_startup(thread);
    return (long)tid;
fail:
    err = GET_ERRNO();
    RT_ASSERT(err < 0);

    lwp_tid_put(tid);
    if (thread)
    {
        rt_thread_delete(thread);
    }
    if (lwp)
    {
        lwp_ref_dec(lwp);
    }
    return (long)err;
}

/**
 * @brief Creates a new process or thread (clone).
 *
 * This system call creates a new process or thread by duplicating the calling process.
 * The new process/thread begins execution by calling the function specified in the
 * `arg[]` array, which typically contains the necessary arguments or function pointer.
 * It is used to implement process/thread creation in the system and is often a lower-level
 * operation in process management.
 *
 * @param[in] arg   An array of arguments passed to the new process or thread. This could
 *                  include function pointers, structures, or any necessary data the
 *                  new process/thread will need to execute its work.
 *
 * @return long     Returns a status code or the process/thread ID of the newly created
 *                  process/thread. On success, it may return a positive value (such as a
 *                  thread ID). On failure, a negative value indicating the error is returned.
 *
 * @warning Be cautious when using this function as improper management of process/thread
 *          creation can lead to resource exhaustion, deadlocks, or other synchronization issues.
 */
rt_weak long sys_clone(void *arg[])
{
    return _sys_clone(arg);
}

static void lwp_struct_copy(struct rt_lwp *dst, struct rt_lwp *src)
{
#ifdef ARCH_MM_MMU
    dst->end_heap = src->end_heap;
#endif
    dst->lwp_type = src->lwp_type;
    dst->text_entry = src->text_entry;
    dst->text_size = src->text_size;
    dst->data_entry = src->data_entry;
    dst->data_size = src->data_size;
    dst->args = src->args;
    dst->background = src->background;
    dst->tty = src->tty;

    /* terminal API */
    dst->term_ctrlterm = src->term_ctrlterm;

    rt_memcpy(dst->cmd, src->cmd, RT_NAME_MAX);
    if (src->exe_file)
    {
        if (dst->exe_file)
        {
            rt_free(dst->exe_file);
        }
        dst->exe_file = strndup(src->exe_file, DFS_PATH_MAX);
    }

    rt_memcpy(&dst->signal.sig_action, &src->signal.sig_action, sizeof(dst->signal.sig_action));
    rt_memcpy(&dst->signal.sig_action_mask, &src->signal.sig_action_mask, sizeof(dst->signal.sig_action_mask));
    rt_memcpy(&dst->signal.sig_action_nodefer, &src->signal.sig_action_nodefer, sizeof(dst->signal.sig_action_nodefer));
    rt_memcpy(&dst->signal.sig_action_onstack, &src->signal.sig_action_onstack, sizeof(dst->signal.sig_action_onstack));
    rt_memcpy(&dst->signal.sig_action_restart, &dst->signal.sig_action_restart, sizeof(dst->signal.sig_action_restart));
    rt_memcpy(&dst->signal.sig_action_siginfo, &dst->signal.sig_action_siginfo, sizeof(dst->signal.sig_action_siginfo));
    rt_memcpy(&dst->signal.sig_action_nocldstop, &dst->signal.sig_action_nocldstop, sizeof(dst->signal.sig_action_nocldstop));
    rt_memcpy(&dst->signal.sig_action_nocldwait, &dst->signal.sig_action_nocldwait, sizeof(dst->signal.sig_action_nocldwait));
    rt_strcpy(dst->working_directory, src->working_directory);
}

static int lwp_copy_files(struct rt_lwp *dst, struct rt_lwp *src)
{
    struct dfs_fdtable *dst_fdt;
    struct dfs_fdtable *src_fdt;

    src_fdt = &src->fdt;
    dst_fdt = &dst->fdt;
    /* init fds */
    dst_fdt->fds = rt_calloc(src_fdt->maxfd, sizeof(void *));
    if (dst_fdt->fds)
    {
        struct dfs_file *d_s;
        int i;

        dst_fdt->maxfd = src_fdt->maxfd;

        dfs_file_lock();
        /* dup files */
        for (i = 0; i < src_fdt->maxfd; i++)
        {
            d_s = fdt_get_file(src_fdt, i);
            if (d_s)
            {
                dst_fdt->fds[i] = d_s;
                d_s->ref_count++;
            }
        }
        dfs_file_unlock();
        return 0;
    }
    return -RT_ERROR;
}

sysret_t _sys_fork(void)
{
    int tid = 0;
    sysret_t falival = 0;
    struct rt_lwp *lwp = RT_NULL;
    struct rt_lwp *self_lwp = RT_NULL;
    rt_thread_t thread = RT_NULL;
    rt_thread_t self_thread = RT_NULL;
    void *user_stack = RT_NULL;
    rt_processgroup_t group;

    /* new lwp */
    lwp = lwp_create(LWP_CREATE_FLAG_ALLOC_PID);
    if (!lwp)
    {
        SET_ERRNO(ENOMEM);
        goto fail;
    }

    /* new tid */
    if ((tid = lwp_tid_get()) == 0)
    {
        SET_ERRNO(ENOMEM);
        goto fail;
    }

    /* user space init */
    if (lwp_user_space_init(lwp, 1) != 0)
    {
        SET_ERRNO(ENOMEM);
        goto fail;
    }

    self_lwp = lwp_self();

    /* copy address space of process from this proc to forked one */
    if (lwp_fork_aspace(lwp, self_lwp) != 0)
    {
        SET_ERRNO(ENOMEM);
        goto fail;
    }

    /* copy lwp struct data */
    lwp_struct_copy(lwp, self_lwp);

    /* copy files */
    if (lwp_copy_files(lwp, self_lwp) != 0)
    {
        SET_ERRNO(ENOMEM);
        goto fail;
    }

    /* create thread */
    self_thread = rt_thread_self();

    thread = rt_thread_create(self_thread->parent.name,
            RT_NULL,
            RT_NULL,
            self_thread->stack_size,
            RT_SCHED_PRIV(self_thread).init_priority,
            RT_SCHED_PRIV(self_thread).init_tick);
    if (!thread)
    {
        SET_ERRNO(ENOMEM);
        goto fail;
    }

    thread->cleanup = self_thread->cleanup;
    thread->user_entry = self_thread->user_entry;
    thread->user_stack = self_thread->user_stack;
    thread->user_stack_size = self_thread->user_stack_size;
    thread->signal.sigset_mask = self_thread->signal.sigset_mask;
    thread->thread_idr = self_thread->thread_idr;
    thread->clear_child_tid = self_thread->clear_child_tid;
    thread->lwp = (void *)lwp;
    thread->tid = tid;

    LWP_LOCK(self_lwp);
    /* add thread to lwp process */
    rt_list_insert_after(&lwp->t_grp, &thread->sibling);
    LWP_UNLOCK(self_lwp);

    lwp_children_register(self_lwp, lwp);

    /* set pgid and sid */
    group = lwp_pgrp_find(lwp_pgid_get_byprocess(self_lwp));
    if (group)
    {
        lwp_pgrp_insert(group, lwp);
    }
    else
    {
        LOG_W("the process group of pid: %d cannot be found", lwp_pgid_get_byprocess(self_lwp));
    }

    /* copy kernel stack context from self thread */
    lwp_memcpy(thread->stack_addr, self_thread->stack_addr, self_thread->stack_size);
    lwp_tid_set_thread(tid, thread);

    /* duplicate user objects */
    lwp_user_object_dup(lwp, self_lwp);

    user_stack = arch_get_user_sp();
    arch_set_thread_context(arch_fork_exit,
            (void *)((char *)thread->stack_addr + thread->stack_size),
            user_stack, &thread->sp);

    rt_thread_startup(thread);
    return lwp_to_pid(lwp);
fail:
    falival = GET_ERRNO();

    if (tid != 0)
    {
        lwp_tid_put(tid);
    }
    if (thread)
    {
        rt_thread_delete(thread);
    }
    if (lwp)
    {
        lwp_ref_dec(lwp);
    }
    return falival;
}

/* arm needs to wrap fork/clone call to preserved lr & caller saved regs */

/**
 * @brief Creates a child process by duplicating the calling process.
 *
 * This system call creates a new child process by duplicating the calling process. The
 * new child process is a copy of the parent process, except for the returned value.
 * The child process starts executing from the point of the fork, but the return value
 * differs between the parent and child: the parent receives the process ID (PID) of the
 * child, and the child receives a return value of 0.
 *
 * @return sysret_t    Returns a status code indicating the result of the operation:
 *                      - A positive value (the child's PID) is returned to the parent.
 *                      - A value of 0 is returned to the child process.
 *                      - A negative value indicates an error (e.g., resource limits exceeded).
 *
 * @note This function is commonly used in operating systems to create new processes.
 *
 * @warning Be aware that improper management of child processes (such as failing to handle
 *          process termination or excessive forking) can lead to resource exhaustion or
 *          other system issues. Ensure proper process handling in the parent and child
 *          processes to avoid leaks and inconsistencies.
 */
rt_weak sysret_t sys_fork(void)
{
    return _sys_fork();
}

rt_weak sysret_t sys_vfork(void)
{
    return sys_fork();
}

#define _swap_lwp_data(lwp_used, lwp_new, type, member) \
    do {\
        type tmp;\
        tmp = lwp_used->member;\
        lwp_used->member = lwp_new->member;\
        lwp_new->member = tmp;\
    } while (0)

/**
 * @brief Executes a program in the current process.
 *
 * This system call replaces the current process image with a new program specified by the
 * `path` argument. It loads the program located at the given `path` and passes the arguments
 * (`argv`) and environment variables (`envp`) to it. This effectively replaces the calling
 * process with a new one, and if successful, it never returns. If there is an error, the current
 * process continues to execute, and an error code is returned.
 *
 * @param[in]  path   The path to the executable file to be executed. This should be an
 *                    absolute or relative file path to the program.
 * @param[in]  argv   An array of arguments to pass to the new program. The first element
 *                    (`argv[0]`) should typically be the name of the program, and the array
 *                    should be terminated with a `NULL` pointer.
 * @param[in]  envp   An array of environment variables to pass to the new program. This is
 *                    typically in the form of `key=value` strings, with the array terminated
 *                    by a `NULL` pointer.
 *
 * @return sysret_t  Returns a status code:
 *                    - `0`: The program was successfully executed (this value is
 *                      never returned since the process is replaced).
 *                   - Other error codes may indicate issues with the program execution
 *
 * @note If `execve` is successful, it does not return to the calling function. The process
 *       image is replaced by the new program.
 */
sysret_t sys_execve(const char *path, char *const argv[], char *const envp[])
{
    rt_err_t error = -1;
    size_t len;
    struct rt_lwp *new_lwp = NULL;
    struct rt_lwp *lwp;
    int uni_thread;
    rt_thread_t thread;
    struct process_aux *aux;
    struct lwp_args_info args_info;
    char *kpath = RT_NULL;

    lwp = lwp_self();
    thread = rt_thread_self();
    uni_thread = 1;

    LWP_LOCK(lwp);
    if (lwp->t_grp.prev != &thread->sibling)
    {
        uni_thread = 0;
    }
    if (lwp->t_grp.next != &thread->sibling)
    {
        uni_thread = 0;
    }
    LWP_UNLOCK(lwp);

    if (!uni_thread)
    {
        return -EINVAL;
    }

    len = lwp_user_strlen(path);
    if (len <= 0)
    {
        return -EFAULT;
    }

    kpath = rt_malloc(len + 1);
    if (!kpath)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(kpath, (void *)path, len) != len)
    {
        rt_free(kpath);
        return -EFAULT;
    }
    kpath[len] = '\0';

    if (access(kpath, X_OK) != 0)
    {
        error = rt_get_errno();
        rt_free(kpath);
        return (sysret_t)error;
    }

    /* setup args */
    error = lwp_args_init(&args_info);
    if (error)
    {
        rt_free(kpath);
        return -ENOMEM;
    }

    if (argv)
    {
        error = lwp_args_put_argv(&args_info, (void *)argv);
        if (error)
        {
            error = -EFAULT;
            goto quit;
        }
    }

    if (envp)
    {
        error = lwp_args_put_envp(&args_info, (void *)envp);
        if (error)
        {
            error = -EFAULT;
            goto quit;
        }
    }

    /* alloc new lwp to operation */
    new_lwp = lwp_create(LWP_CREATE_FLAG_NONE);
    if (!new_lwp)
    {
        error = -ENOMEM;
        goto quit;
    }

    error = lwp_user_space_init(new_lwp, 0);
    if (error != 0)
    {
        error = -ENOMEM;
        goto quit;
    }

    /* file is a script ? */
    path = kpath;
    while (1)
    {
        error = lwp_args_load_script(&args_info, path);
        if (error != 0)
        {
            break;
        }
        path = lwp_args_get_argv_0(&args_info);
    }

    /* now load elf */
    if ((aux = lwp_argscopy(new_lwp, &args_info)) == NULL)
    {
        error = -ENOMEM;
        goto quit;
    }
    error = lwp_load(path, new_lwp, RT_NULL, 0, aux);
    if (error == RT_EOK)
    {
        int off = 0;
        int last_backslash = 0;

        /* clear all user objects */
        lwp_user_object_clear(lwp);

        /* find last \ or / to get base name */
        while (1)
        {
            char c = path[off++];

            if (c == '\0')
            {
                break;
            }
            if (c == '\\' || c == '/')
            {
                last_backslash = off;
            }
        }

        /**
         * Set thread name and swap the data of lwp and new_lwp.
         * Since no other threads can access the lwp field, it't uneccessary to
         * take a lock here
         */
        RT_ASSERT(rt_list_entry(lwp->t_grp.prev, struct rt_thread, sibling) == thread);

        strncpy(thread->parent.name, path + last_backslash, RT_NAME_MAX - 1);
        strncpy(lwp->cmd, new_lwp->cmd, RT_NAME_MAX);
        rt_free(lwp->exe_file);
        lwp->exe_file = strndup(new_lwp->exe_file, DFS_PATH_MAX);

#ifdef ARCH_MM_MMU
        _swap_lwp_data(lwp, new_lwp, struct rt_aspace *, aspace);

        _swap_lwp_data(lwp, new_lwp, size_t, end_heap);
#endif
        _swap_lwp_data(lwp, new_lwp, uint8_t, lwp_type);
        _swap_lwp_data(lwp, new_lwp, void *, text_entry);
        _swap_lwp_data(lwp, new_lwp, uint32_t, text_size);
        _swap_lwp_data(lwp, new_lwp, void *, data_entry);
        _swap_lwp_data(lwp, new_lwp, uint32_t, data_size);

        _swap_lwp_data(lwp, new_lwp, void *, args);

        lwp_thread_signal_detach(&thread->signal);
        rt_memset(&thread->signal.sigset_mask, 0, sizeof(thread->signal.sigset_mask));

        lwp_signal_detach(&lwp->signal);
        lwp_signal_init(&lwp->signal);

        /* to do: clsoe files with flag CLOEXEC, recy sub-thread */

        lwp_aspace_switch(thread);

        lwp_ref_dec(new_lwp);
        arch_start_umode(lwp->args,
                lwp->text_entry,
                (void*)USER_STACK_VEND,
                (char *)thread->stack_addr + thread->stack_size);
        /* never reach here */
    }
    error = -EINVAL;
quit:
    if (kpath)
    {
        rt_free(kpath);
    }
    lwp_args_detach(&args_info);
    if (new_lwp)
    {
        lwp_ref_dec(new_lwp);
    }
    return error;
}
#endif /* ARCH_MM_MMU */

/**
 * @brief Deletes a thread.
 *
 * This system call is used to delete an existing thread. The specified thread is terminated,
 * and its resources are released. If the thread is currently running, it will be forcefully
 * terminated. The thread identifier (`thread`) refers to the thread that is to be deleted.
 *
 * @param[in] thread   The identifier of the thread to be deleted.
 *
 * @return sysret_t    Returns a status code:
 *                      - `SYSRET_OK`: The thread was successfully deleted.
 *                     - Other error codes may indicate additional failures.
 *
 * @note This function should be used carefully, as forcefully terminating a thread may
 *       lead to resource leaks or inconsistent state if the thread is performing critical
 *       operations at the time of termination.
 *
 * @warning Ensure that the thread being deleted has completed its necessary operations
 *          and that there are no outstanding resources or critical tasks before deleting
 *          it. Otherwise, it might lead to undefined behavior or resource leaks.
 */
sysret_t sys_thread_delete(rt_thread_t thread)
{
#ifdef ARCH_MM_MMU
    return rt_thread_delete(thread);
#else
    sysret_t ret = 0;

    if(thread->parent.type != RT_Object_Class_Thread)
    {
        ret = -EINVAL;
        goto __exit;
    }

    ret = rt_thread_delete(thread);

    if (rt_thread_self() == thread)
    {
        rt_schedule();
    }

__exit:
    return ret;
#endif
}

/**
 * @brief Starts a previously created thread.
 *
 * This system call is used to start a thread that was created but has not yet started running.
 * It initiates the thread's execution, allowing it to begin performing its assigned task.
 * The `thread` parameter refers to the thread that is to be started.
 *
 * @param[in] thread   The identifier of the thread to be started.
 *
 * @return sysret_t    Returns a status code:
 *                      - `0`: The thread was successfully started.
 *                      - Other error codes may indicate additional failures.
 *
 * @warning Ensure that the thread has been correctly initialized and is in a valid state
 *          before calling this function to avoid undefined behavior. Improper initialization
 *          could lead to issues such as the thread not running as expected.
 */
sysret_t sys_thread_startup(rt_thread_t thread)
{
    return rt_thread_startup(thread);
}

/**
 * @brief Retrieves the identifier of the current thread.
 *
 * This system call returns the thread identifier of the currently executing thread. It allows
 * a thread to obtain its own identifier, which can be useful for various thread management
 * tasks such as self-identification, logging, or checking the thread's status.
 *
 * @return rt_thread_t  The identifier of the current thread.
 *                      If no thread is currently executing, a null or invalid thread ID
 *                      might be returned depending on the system's implementation.
 *
 * @note This function is typically used when a thread needs to identify itself, especially
 *       in cases where thread management is performed dynamically or the thread identifier
 *       is required for synchronization or debugging purposes.
 *
 * @warning Be aware that in environments where there is no concept of threads or if the
 *          current context is not a thread (e.g., during interrupt handling or early system
 *          initialization), the return value might be invalid.
 */
rt_thread_t sys_thread_self(void)
{
    return rt_thread_self();
}

/* sys channel */

/**
 * @brief Opens a communication channel.
 *
 * This system call is used to open a communication channel with a specified name and set of flags.
 * The channel allows for inter-process or inter-thread communication, depending on the underlying system.
 * The `name` parameter specifies the name of the channel, while the `flags` parameter allows
 * configuration of the channel's behavior (e.g., read/write permissions, blocking or non-blocking mode).
 *
 * @param[in] name   The name of the communication channel to be opened.
 * @param[in] flags  The flags to configure the behavior of the channel. These flags may
 *                   define various properties such as access mode (e.g., read-only, write-only)
 *                   or synchronization mode (e.g., blocking, non-blocking).
 *
 * @return sysret_t  Returns a status code:
 *                    - `0`: The channel was successfully opened.
 *                    - Other error codes may indicate issues with the channel opening process.
 *
 * @warning Ensure that the correct flags are passed to configure the channel as required,
 *          as improper configuration might lead to access issues, data loss, or undefined behavior.
 */
sysret_t sys_channel_open(const char *name, int flags)
{
    rt_size_t ret = 0;
    char *kname = RT_NULL;
    int len = 0;

    len = lwp_user_strlen(name);
    if (len <= 0)
    {
        return -EFAULT;
    }

    kname = (char *)kmem_get(len + 1);
    if (!kname)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
    {
        kmem_put(kname);
        return -EFAULT;
    }

    ret = lwp_channel_open(FDT_TYPE_LWP, kname, flags);

    kmem_put(kname);

    return ret;
}

/**
 * @brief Closes an open communication channel.
 *
 * This system call is used to close an already open communication channel specified by the file descriptor `fd`.
 * After closing, the channel can no longer be used for communication, and any resources associated with
 * the channel will be released. This function is necessary for proper resource management, ensuring that
 * system resources (e.g., memory or file handles) are freed when no longer needed.
 *
 * @param[in] fd     The file descriptor of the communication channel to be closed.
 *
 * @return sysret_t  Returns a status code:
 *                    - `SYSRET_OK`: The channel was successfully closed.
 *                    - Other error codes may indicate issues with the channel closing process.
 *
 * @note This function should be called after communication is finished and the channel is no longer
 *       needed, to release any system resources associated with it.
 *
 * @warning Calling this function on an invalid or already closed file descriptor may lead to
 *          undefined behavior or errors. Ensure that the file descriptor is valid and that the
 *          channel is not already closed before attempting to close it.
 */
sysret_t sys_channel_close(int fd)
{
    return lwp_channel_close(FDT_TYPE_LWP, fd);
}

/**
 * @brief Sends a message through a communication channel.
 *
 * This system call is used to send a message through a specified communication channel identified
 * by the file descriptor `fd`. The message to be sent is provided in the `data` parameter.
 * It allows inter-process or inter-thread communication by transmitting the given message over
 * the open channel.
 *
 * @param[in] fd     The file descriptor of the communication channel to send the message to.
 * @param[in] data   The message data to be sent. This parameter is typically a structure
 *                   containing the message content and metadata.
 *
 * @return sysret_t  Returns a status code:
 *                    - `0`: The message was successfully sent.
 *                    - Other error codes may indicate issues with the message sending process.
 *
 * @note Ensure the channel is open and properly configured for sending messages before
 *       calling this function. Additionally, confirm that the `data` structure is valid and
 *       initialized with the appropriate content.
 *
 * @warning Failure to verify the channel's readiness or the validity of the data may lead
 *          to errors, data loss, or undefined behavior.
 */
sysret_t sys_channel_send(int fd, rt_channel_msg_t data)
{
    rt_size_t ret = 0;
    rt_channel_msg_t kdata = RT_NULL;

    if (!lwp_user_accessable((void *)data, sizeof(*data)))
    {
        return -EFAULT;
    }

    kdata = kmem_get(sizeof(*data));
    if (kdata == RT_NULL)
        return -ENOMEM;

    if (lwp_get_from_user(kdata, data, sizeof(*kdata)) != sizeof(*kdata))
    {
        kmem_put(kdata);
        return -EFAULT;
    }

    ret = lwp_channel_send(FDT_TYPE_LWP, fd, kdata);

    kmem_put(kdata);

    return ret;
}

/**
 * @brief Sends a message through a communication channel and waits for a response with a timeout.
 *
 * This system call sends a message (`data`) through a specified communication channel identified by the file descriptor `fd`.
 * It then waits for a response (`data_ret`) within the specified timeout period. This is a synchronous operation
 * commonly used in request-response communication patterns between processes or threads.
 *
 * @param[in]  fd        The file descriptor of the communication channel to send the message to.
 * @param[in]  data      The message data to be sent. This is typically a structure containing
 *                       the message content and metadata.
 * @param[out] data_ret  The buffer to store the response message received from the channel.
 * @param[in]  time      The timeout period (in milliseconds) to wait for the response.
 *                       If set to a negative value, the function will wait indefinitely.
 *
 * @return sysret_t      Returns a status code:
 *                        - `0`: The message was successfully sent, and a response was received.
 *                        - Other error codes may indicate issues with the communication process.
 *
 * @note This function combines sending and receiving operations into a single atomic action.
 *       It is useful for scenarios requiring synchronous communication with a defined timeout
 *       to handle cases where a response may not be immediately available.
 *
 * @warning Ensure that the channel is open and properly configured for bidirectional communication.
 *          Verify that the `data` structure is valid and initialized, and the `data_ret` buffer is large
 *          enough to store the expected response to avoid memory issues or data corruption.
 */
sysret_t sys_channel_send_recv_timeout(int fd, rt_channel_msg_t data, rt_channel_msg_t data_ret, rt_int32_t time)
{
    rt_size_t ret = 0;
    rt_channel_msg_t kdata = RT_NULL;
    rt_channel_msg_t kdata_ret = RT_NULL;

    if (!lwp_user_accessable((void *)data, sizeof(*data)))
    {
        return -EFAULT;
    }

    kdata = kmem_get(sizeof(*data));
    if (kdata == RT_NULL)
        return -ENOMEM;

    if (lwp_get_from_user(kdata, data, sizeof(*kdata)) != sizeof(*kdata))
    {
        kmem_put(kdata);
        return -EFAULT;
    }

    kdata_ret = kmem_get(sizeof(*data_ret));
    if (kdata_ret == RT_NULL)
        return -ENOMEM;

    ret = lwp_channel_send_recv_timeout(FDT_TYPE_LWP, fd, kdata, kdata_ret, time);

    lwp_put_to_user(data_ret, kdata_ret, sizeof(*kdata_ret));
    kmem_put(kdata);
    kmem_put(kdata_ret);

    return ret;
}

/**
 * @brief Sends a reply message through a communication channel.
 *
 * This system call is used to send a reply (`data`) through a communication channel identified
 * by the file descriptor `fd`. It is typically called in response to a received request
 * within a request-response communication pattern. The reply is sent to the requesting entity
 * through the same channel.
 *
 * @param[in] fd     The file descriptor of the communication channel to send the reply to.
 * @param[in] data   The reply message to be sent. This is typically a structure containing
 *                   the reply content and metadata.
 *
 * @return sysret_t  Returns a status code:
 *                    - `0`: The reply was successfully sent.
 *                    - Other error codes may indicate issues with the reply sending process.
 *
 * @note This function is usually called in a server or responder context, where a request
 *       is received, processed, and the result is sent back to the requester. Ensure that
 *       the channel is open and configured to send replies before calling this function.
 *
 * @warning Ensure the `data` structure is valid and properly initialized before sending.
 *          Sending invalid or corrupted data may lead to unexpected behavior or communication failures.
 */
sysret_t sys_channel_reply(int fd, rt_channel_msg_t data)
{
    rt_size_t ret = 0;
    rt_channel_msg_t kdata = RT_NULL;

    if (!lwp_user_accessable((void *)data, sizeof(*data)))
    {
        return -EFAULT;
    }

    kdata = kmem_get(sizeof(*data));
    if (kdata == RT_NULL)
        return -ENOMEM;

    if (lwp_get_from_user(kdata, data, sizeof(*kdata)) != sizeof(*data))
    {
        kmem_put(kdata);
        return -EFAULT;
    }

    ret = lwp_channel_reply(FDT_TYPE_LWP, fd, kdata);

    kmem_put(kdata);

    return ret;
}

/**
 * @brief Receives a message from a communication channel with a timeout.
 *
 * This system call attempts to receive a message from a specified communication channel identified
 * by the file descriptor `fd`. The received message is stored in the `data` buffer. If no message
 * is available within the specified timeout period, the function returns with a timeout status.
 *
 * @param[in]  fd     The file descriptor of the communication channel to receive the message from.
 * @param[out] data   The buffer to store the received message. This parameter is typically a
 *                    structure containing the message content and metadata.
 * @param[in]  time   The timeout period (in milliseconds) to wait for a message.
 *                    A negative value indicates that the function will wait indefinitely.
 *
 * @return sysret_t   Returns a status code:
 *                     - `0`: A message was successfully received.
 *                     - `-ETIMEDOUT`: The operation timed out before a message was received.
 *                     - Other error codes may indicate issues with the message receiving process.
 *
 * @note This function is useful in scenarios where blocking indefinitely is not desirable,
 *       allowing the caller to specify a timeout for receiving messages. It is commonly
 *       used in event-driven or time-sensitive communication systems.
 *
 * @warning Ensure that the channel is open and configured for receiving messages before calling
 *          this function. The `data` buffer must be valid and large enough to store the expected
 *          message to avoid memory corruption or data loss.
 */
sysret_t sys_channel_recv_timeout(int fd, rt_channel_msg_t data, rt_int32_t time)
{
    rt_size_t ret = 0;
    rt_channel_msg_t kdata = RT_NULL;

    kdata = kmem_get(sizeof(*data));
    if (kdata == RT_NULL)
        return -ENOMEM;

    ret = lwp_channel_recv_timeout(FDT_TYPE_LWP, fd, kdata, time);

    lwp_put_to_user(data, kdata, sizeof(*kdata));
    kmem_put(kdata);

    return ret;
}

static struct rt_semaphore critical_lock;

static int critical_init(void)
{
    rt_sem_init(&critical_lock, "ct_lock", 1, RT_IPC_FLAG_FIFO);
    return 0;
}
INIT_DEVICE_EXPORT(critical_init);

/**
 * @brief Enters a critical section to prevent context switching or interrupts.
 *
 * @note Critical sections are typically used to protect shared resources or perform
 *       non-interruptible operations. Ensure to exit the critical section as soon as
 *       possible by calling `sys_exit_critical` to avoid system performance degradation
 *       or deadlocks.
 *
 * @warning Failure to exit a critical section (e.g., due to an exception or missing
 *          `sys_exit_critical` call) may lead to system instability or a complete halt.
 */
void sys_enter_critical(void)
{
    rt_sem_take(&critical_lock, RT_WAITING_FOREVER);
}

/**
 * @brief Exits a critical section and restores the system's previous state.
 *
 * @note Exiting the critical section as soon as the protected operation is completed
 *       is essential to avoid performance degradation or system deadlocks. Ensure
 *       that every call to `sys_enter_critical` is matched with a corresponding
 *       `sys_exit_critical` call.
 *
 * @warning Calling this function without a prior `sys_enter_critical` may result
 *          in undefined behavior or system instability. Use carefully in nested
 *          critical sections and ensure proper tracking of critical section depth
 *          if required.
 */
void sys_exit_critical(void)
{
    rt_sem_release(&critical_lock);
}

/* syscall: "sys_log" ret: "int" args: "const char*" "size" */
static int __sys_log_enable = 0;
static int sys_log_enable(int argc, char** argv)
{
    if (argc == 1)
    {
        rt_kprintf("sys_log = %d\n", __sys_log_enable);
        return 0;
    }
    else
    {
        __sys_log_enable = atoi(argv[1]);
    }

    return 0;
}
MSH_CMD_EXPORT_ALIAS(sys_log_enable, sys_log, sys_log 1(enable)/0(disable));

/**
 * @brief Logs a message to the system logging mechanism.
 *
 * This system call writes a log message to the system log for diagnostic or informational purposes.
 * The message is specified by the `log` parameter, and its size is given by the `size` parameter.
 * The logging mechanism is typically used for tracking system events, debugging, or reporting errors.
 *
 * @param[in] log   A pointer to the message to be logged. The message should be a valid character
 *                  array or string.
 * @param[in] size  The size of the log message in bytes. This specifies the number of bytes to write
 *                  from the `log` buffer.
 *
 * @return sysret_t Returns a status code:
 *                   - `0`: The log message was successfully written.
 *                   - Other error codes may indicate issues with the logging process.
 *
 * @note Ensure that the `log` pointer is valid and points to a properly initialized memory buffer.
 *       Truncation may occur if the logging system has a size limitation. Logging should not be used
 *       in performance-critical paths as it may introduce latency.
 *
 * @warning Passing a `NULL` pointer or an invalid `size` may lead to undefined behavior. Ensure the
 *          logging system is properly initialized before invoking this function.
 */
sysret_t sys_log(const char* log, int size)
{
    char *klog = RT_NULL;
    rt_device_t console = RT_NULL;

    if (!lwp_user_accessable((void *)log, size))
        return -EFAULT;

    klog = kmem_get(size);
    if (klog == RT_NULL)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user((void *)klog, (void *)log, size) != size)
    {
        kmem_put(klog);
        return -EINVAL;
    }

    console = rt_console_get_device();

    if (console && __sys_log_enable)
    {
        rt_device_write(console, -1, klog, size);
    }

    kmem_put(klog);

    return 0;
}

/**
 * @brief Retrieves information about a file or directory.
 *
 * This system call obtains metadata about the specified file or directory and stores it in
 * the `buf` structure. The metadata includes attributes such as file size, permissions,
 * ownership, and timestamps.
 *
 * @param[in]  file  A pointer to the path of the file or directory to be queried.
 *                   The path should be a null-terminated string.
 * @param[out] buf   A pointer to a `struct stat` structure where the file's metadata
 *                   will be stored. This structure must be allocated by the caller.
 *
 * @return sysret_t  Returns a status code:
 *                    - `0`: The operation completed successfully, and the metadata
 *                      has been written to `buf`.
 *                    - Other error codes may indicate issues with the file path.
 *
 * @note The `file` path must be valid and accessible by the calling process. Ensure that
 *       the `buf` pointer points to a properly allocated memory region.
 *
 * @warning Passing a `NULL` pointer for `file` or `buf` may result in undefined behavior.
 *          Check all inputs before invoking this function to avoid potential issues.
 */
sysret_t sys_stat(const char *file, struct stat *buf)
{
    int ret = 0;
    size_t len;
    size_t copy_len;
    char *copy_path;
    struct stat statbuff = {0};

    if (!lwp_user_accessable((void *)buf, sizeof(struct stat)))
    {
        return -EFAULT;
    }

    len = lwp_user_strlen(file);
    if (len <= 0)
    {
        return -EFAULT;
    }

    copy_path = (char*)rt_malloc(len + 1);
    if (!copy_path)
    {
        return -ENOMEM;
    }

    copy_len = lwp_get_from_user(copy_path, (void*)file, len);
    if (copy_len == 0)
    {
        rt_free(copy_path);
        return -EFAULT;
    }
    copy_path[copy_len] = '\0';

    ret = _SYS_WRAP(stat(copy_path, &statbuff));
    rt_free(copy_path);

    if (ret == 0)
    {
        lwp_put_to_user(buf, &statbuff, sizeof statbuff);
    }

    return ret;
}

/**
 * @brief Retrieves metadata about a file or symbolic link.
 *
 * This system call obtains metadata for the specified file or symbolic link and stores
 * it in the `buf` structure. Unlike `sys_stat`, if the specified path refers to a
 * symbolic link, this function retrieves information about the link itself, not the
 * target it points to.
 *
 * @param[in]  file  A pointer to the path of the file or symbolic link to be queried.
 *                   The path must be a null-terminated string.
 * @param[out] buf   A pointer to a `struct stat` structure where the metadata will be
 *                   stored. This structure must be allocated by the caller.
 *
 * @return sysret_t  Returns a status code:
 *                    - `0`: The operation completed successfully, and the metadata
 *                      has been written to `buf`.
 *                   - Other error codes may indicate issues with the file path.
 *
 * @note This function is particularly useful for handling symbolic links when you want
 *       to get information about the link itself rather than the target file or directory.
 *       The `file` path must be valid and accessible by the calling process.
 *
 * @warning Passing a `NULL` pointer for `file` or `buf` may result in undefined behavior.
 *          Always check inputs for validity before invoking this function.
 */
sysret_t sys_lstat(const char *file, struct stat *buf)
{
    int ret = 0;
    size_t len;
    size_t copy_len;
    char *copy_path;
    struct stat statbuff = {0};

    if (!lwp_user_accessable((void *)buf, sizeof(struct stat)))
    {
        return -EFAULT;
    }

    len = lwp_user_strlen(file);
    if (len <= 0)
    {
        return -EFAULT;
    }

    copy_path = (char*)rt_malloc(len + 1);
    if (!copy_path)
    {
        return -ENOMEM;
    }

    copy_len = lwp_get_from_user(copy_path, (void*)file, len);
    if (copy_len == 0)
    {
        rt_free(copy_path);
        return -EFAULT;
    }
    copy_path[copy_len] = '\0';
#ifdef RT_USING_DFS_V2
    ret = _SYS_WRAP(dfs_file_lstat(copy_path, &statbuff));
#else
    ret = _SYS_WRAP(stat(copy_path, &statbuff));
#endif
    rt_free(copy_path);

    if (ret == 0)
    {
        lwp_put_to_user(buf, &statbuff, sizeof statbuff);
    }

    return ret;
}

sysret_t sys_notimpl(void)
{
    return -ENOSYS;
}

uint32_t sys_hw_interrupt_disable(void)
{
    return rt_hw_interrupt_disable();
}

void sys_hw_interrupt_enable(uint32_t level)
{
    rt_hw_interrupt_enable(level);
}

#ifdef ARCH_MM_MMU
/**
 * @brief Allocates or retrieves a shared memory segment.
 *
 * This system call allocates a new shared memory segment or retrieves an existing one
 * based on the specified `key`. Shared memory allows processes to communicate by
 * sharing a region of memory.
 *
 * @param[in] key     A unique identifier for the shared memory segment. If `key` matches
 *                    an existing segment, it will be retrieved. If `create` is set and the
 *                    segment does not exist, a new one will be created.
 * @param[in] size    The size (in bytes) of the shared memory segment. If creating a new
 *                    segment, this specifies its size. If retrieving an existing segment,
 *                    `size` is ignored.
 * @param[in] create  A flag indicating whether to create the segment if it does not exist:
 *                    - `1`: Create the shared memory segment if it does not exist.
 *                    - `0`: Only retrieve an existing segment.
 *
 * @return sysret_t   Returns a status code:
 *                    - `0`: The shared memory segment was successfully created or
 *                      retrieved.
 *                    - Other error codes may indicate issues with the shared memory
 *
 * @note Shared memory segments identified by the same `key` are accessible across
 *       processes. Ensure proper synchronization mechanisms (e.g., semaphores) are in
 *       place to manage access to the shared memory.
 *
 * @warning Using a `NULL` or invalid `key` may result in undefined behavior. When creating
 *          a new segment, ensure that `size` is non-zero and meaningful.
 */
sysret_t sys_shmget(size_t key, size_t size, int create)
{
    return lwp_shmget(key, size, create);
}

/**
 * @brief Removes a shared memory segment.
 *
 * This system call removes the specified shared memory segment identified by its `id`.
 * Once removed, the segment will no longer be accessible, and any memory associated
 * with it will be freed. It is typically used to clean up shared memory resources
 * when they are no longer needed.
 *
 * @param[in] id  The identifier of the shared memory segment to be removed. This identifier
 *                was obtained when the segment was created or retrieved using `sys_shmget`.
 *
 * @return sysret_t  Returns a status code:
 *                    - `0`: The shared memory segment was successfully removed.
 *                    - Other error codes may indicate issues with the shared memory removal.
 *
 * @note This function should be called only when all processes that were using the shared
 *       memory segment have finished accessing it. Removing the segment while it is in use
 *       by another process may result in undefined behavior or memory corruption.
 *
 * @warning Ensure that the shared memory segment is no longer needed by any process before
 *          calling this function to avoid premature removal and potential data loss.
 */
sysret_t sys_shmrm(int id)
{
    return lwp_shmrm(id);
}

/**
 * @brief Attaches a shared memory segment to the calling process's address space.
 *
 * This system call maps a shared memory segment identified by `id` into the calling
 * process's address space. The segment can then be accessed using the returned virtual
 * address. If the segment was previously detached or created, it will be made available
 * for reading and writing.
 *
 * @param[in] id         The identifier of the shared memory segment to be attached.
 *                       This identifier was obtained when the segment was created
 *                       or retrieved using `sys_shmget`.
 * @param[in] shm_vaddr  A pointer to the desired virtual address where the shared
 *                       memory segment should be mapped. If `NULL`, the system will
 *                       choose an appropriate address.
 *
 * @return void*        Returns the virtual address where the shared memory segment
 *                      is mapped. On success, this will be the address in the
 *                      calling process's address space. If the attachment fails,
 *                      `NULL` is returned.
 *
 * @note Once the shared memory segment is attached, it can be accessed like any
 *       regular memory, but it should be used with caution, especially in multi-process
 *       environments. Ensure that proper synchronization mechanisms (e.g., semaphores)
 *       are used to manage concurrent access.
 *
 * @warning Ensure that the shared memory segment is properly allocated and not in use
 *          by other processes before attaching it. Passing invalid `id` or an inaccessible
 *          segment may result in undefined behavior.
 */
void* sys_shmat(int id, void* shm_vaddr)
{
    return lwp_shmat(id, shm_vaddr);
}

/**
 * @brief Detaches a shared memory segment from the calling process's address space.
 *
 * This system call detaches the shared memory segment previously attached to the calling
 * process's address space using `sys_shmat`. After calling this function, the shared
 * memory will no longer be accessible via the returned address.
 *
 * @param[in] shm_vaddr  A pointer to the virtual address where the shared memory
 *                       segment was previously mapped. This address was returned
 *                       by the `sys_shmat` function.
 *
 * @return sysret_t      Returns a status code:
 *                       - `0`: The shared memory segment was successfully detached.
 *                       - Other error codes may indicate issues with the detachment process.
 *
 * @note It is important to ensure that no processes are using the shared memory segment
 *       before detaching it. Detaching the segment while it is still being accessed
 *       may lead to undefined behavior.
 *
 * @warning Ensure that `shm_vaddr` corresponds to a valid attached address returned
 *          by `sys_shmat`. Passing an incorrect or uninitialized address may result
 *          in undefined behavior.
 */
sysret_t sys_shmdt(void* shm_vaddr)
{
    return lwp_shmdt(shm_vaddr);
}
#elif defined RT_LWP_USING_SHM

/**
 * @brief Allocates a new shared memory segment.
 *
 * This system call allocates a new shared memory segment of the specified size and
 * returns a pointer to the allocated memory. The allocated segment can be used for
 * inter-process communication or shared memory access. The segment is typically
 * managed by the system, and it can be accessed by other processes with appropriate
 * synchronization.
 *
 * @param[in] size  The size (in bytes) of the shared memory segment to be allocated.
 *
 * @return void*    Returns a pointer to the allocated shared memory segment.
 *                  If the allocation fails, `RT_NULL` is returned.
 *
 * @note The allocated shared memory segment can be used like regular memory,
 *       but it should be accessed with proper synchronization mechanisms (e.g.,
 *       semaphores or mutexes) to avoid race conditions or data corruption in
 *       multi-process environments.
 *
 * @warning Ensure that the `size` parameter is a valid, non-zero value, and that
 *          there is enough system memory to allocate the requested size.
 *          Failure to do so may result in errors or resource exhaustion.
 */
void *sys_shm_alloc(int size)
{
    if (size < 0)
    {
        return RT_NULL;
    }
    return lwp_shm_alloc((rt_size_t)size);
}

/**
 * @brief Retains an existing shared memory segment.
 *
 * This system call retains an existing shared memory segment that was previously
 * allocated or attached, ensuring it remains available for further use. It is
 * typically used to increment the reference count or to ensure the segment is
 * not removed or deallocated while it is still being used.
 *
 * @param[in] mem  A pointer to the shared memory segment to retain. This should be
 *                 the address previously returned by a memory allocation or
 *                 attachment function such as `sys_shmat` or `sys_shm_alloc`.
 *
 * @return void*   Returns the original pointer `mem` if the retention is successful.
 *                  If the operation fails, `NULL` is returned.
 *
 * @note This function does not affect the actual content of the shared memory segment,
 *       but ensures the segment is not removed or deallocated while still in use.
 *       It is generally used in conjunction with `sys_shmdt` or `sys_shmrm` to ensure
 *       proper resource management.
 *
 * @warning Ensure that the provided pointer `mem` corresponds to a valid shared
 *          memory segment that is currently allocated or attached. Passing an
 *          invalid or uninitialized pointer may result in undefined behavior.
 */
void *sys_shm_retain(void *mem)
{
    if (!lwp_user_accessable(mem, sizeof (void *)))
    {
        return RT_NULL;
    }
    return lwp_shm_retain(mem);
}

/**
 * @brief Frees a previously allocated shared memory segment.
 *
 * This system call frees a shared memory segment that was previously allocated or
 * retained using functions like `sys_shm_alloc` or `sys_shm_retain`. It ensures
 * that the shared memory is properly deallocated, making it available for future
 * allocations or for removal from the system.
 *
 * @param[in] mem  A pointer to the shared memory segment to be freed. This should be
 *                 the address returned by a memory allocation or retention function.
 *
 * @return sysret_t  Returns a status code:
 *                   - `0`: The shared memory segment was successfully freed.
 *                   - Other error codes may indicate issues with the memory deallocation.
 *
 * @note After calling this function, the memory will be deallocated, and any subsequent
 *       access to the freed memory will result in undefined behavior. Ensure that no
 *       processes are using the shared memory before calling this function.
 *
 * @warning Ensure that `mem` corresponds to a valid shared memory segment that was
 *          previously allocated or retained. Passing an invalid or already freed
 *          pointer may result in undefined behavior.
 */
sysret_t sys_shm_free(void *mem)
{
    if (!lwp_user_accessable(mem, sizeof (void *)))
    {
        return -EFAULT;
    }
    lwp_shm_free(mem);
    return 0;
}
#endif

/* device interfaces */

/**
 * @brief Initializes a device.
 *
 * This system call initializes the specified device, preparing it for use. Device initialization
 * typically involves setting up necessary hardware configurations, registering device drivers,
 * and ensuring that the device is in a ready state for further operations. This function should
 * be called before interacting with the device.
 *
 * @param[in] dev  A pointer to the device structure that represents the device to be initialized.
 *                 This structure contains device-specific configuration and state information.
 *
 * @return sysret_t  Returns a status code:
 *                   - `0`: The device was successfully initialized.
 *                   - Other error codes may indicate issues with the device initialization process.
 *
 * @note This function is typically called once during system startup or when a device is
 *       first accessed. It ensures that all necessary setup steps are completed before
 *       the device can be used.
 *
 * @warning Ensure that the device passed to this function is valid and properly configured
 *          before initialization. Initializing an invalid or improperly configured device
 *          may result in unpredictable behavior.
 */
sysret_t sys_device_init(rt_device_t dev)
{
    return rt_device_init(dev);
}

/**
 * @brief Registers a device with the system.
 *
 * This system call registers a device with the system, making it available for interaction
 * by the operating system or other components. Registration typically involves associating
 * the device with a name and setting up the necessary flags for the device's behavior.
 *
 * @param[in] dev     A pointer to the device structure that represents the device to be registered.
 *                    This structure contains the device's configuration, capabilities, and state.
 * @param[in] name    A string representing the name by which the device will be identified in the system.
 *                    This name is used for device lookup and reference.
 * @param[in] flags   A set of flags that configure the behavior of the device, such as enabling
 *                    or disabling certain features, or specifying the device's mode of operation.
 *
 * @return sysret_t   Returns a status code:
 *                    - `0`: The device was successfully registered.
 *                    - Other error codes may indicate issues with the device registration process.
 *
 * @note This function should be called after the device has been initialized (via `sys_device_init`)
 *       and before the device is used by the system or other components.
 *
 * @warning Ensure that the `name` provided is unique and not already in use by another device in the system.
 *          Passing invalid `dev` or `flags` may result in unexpected behavior or failure of device registration.
 */
sysret_t sys_device_register(rt_device_t dev, const char *name, rt_uint16_t flags)
{
    return rt_device_register(dev, name, flags);
}

/**
 * @brief Controls a device by sending a command.
 *
 * This system call sends a control command to the specified device, allowing the system or other
 * components to modify the device's behavior or state. The command is specified by the `cmd`
 * parameter, and the arguments for the command are passed via the `arg` parameter.
 *
 * @param[in] dev   A pointer to the device structure representing the device to be controlled.
 *                  The device must have been previously registered and initialized.
 * @param[in] cmd   The control command to be sent to the device. The meaning and behavior of the
 *                  command are device-specific and depend on the device type.
 * @param[in] arg   A pointer to the arguments required by the command. The type and content of
 *                  the arguments are determined by the command. Some commands may not require
 *                  arguments, in which case `arg` can be `NULL`.
 *
 * @return sysret_t Returns a status code:
 *                   - `0`: The command was successfully executed on the device.
 *                   - Other error codes may indicate issues with the command execution or device control.
 *
 * @note The set of available commands (`cmd`) and the expected argument types (`arg`) are specific
 *       to each device. Refer to the device documentation for the supported commands and argument
 *       formats.
 *
 * @warning Ensure that the `dev` pointer is valid and points to a correctly initialized device.
 *          Providing an invalid device or incorrect command may result in undefined behavior.
 */
sysret_t sys_device_control(rt_device_t dev, int cmd, void *arg)
{
    return rt_device_control(dev, cmd, arg);
}

/**
 * @brief Finds a device by its name.
 *
 * This system call searches for a device that has been registered with the system using the
 * specified name. If the device exists, a pointer to the device structure is returned,
 * allowing further interaction with the device. If no device with the specified name is found,
 * a `NULL` pointer is returned.
 *
 * @param[in] name  The name of the device to search for. This name must match the name used
 *                  during device registration (e.g., via `sys_device_register`).
 *
 * @return rt_device_t  Returns a pointer to the device structure if the device is found.
 *                      Returns `NULL` if no device with the specified name exists.
 *
 * @note The device must have been previously registered with the system using `sys_device_register`.
 *
 * @warning Ensure that the provided `name` is a valid string and corresponds to a registered device.
 *          Passing an invalid or non-registered name will result in `NULL` being returned.
 */
rt_device_t sys_device_find(const char* name)
{
    return rt_device_find(name);
}

/**
 * @brief Opens a device for use.
 *
 * This system call opens the specified device, making it ready for interaction with the system
 * or other components. The device must have been previously registered and initialized.
 * The `oflag` parameter specifies the open mode, which may determine how the device is accessed
 * (e.g., read, write, or exclusive access).
 *
 * @param[in] dev    A pointer to the device structure representing the device to be opened.
 *                   The device must be registered and initialized before being opened.
 * @param[in] oflag  The open flags that determine the mode of access to the device. These flags
 *                   may specify read, write, or other modes of operation, depending on the device's capabilities.
 *
 * @return sysret_t  Returns a status code:
 *                    - `0`: The device was successfully opened.
 *                    - Other error codes may indicate issues with the device opening process.
 *
 * @note The open flags (`oflag`) should be set according to the device's capabilities. For example,
 *       some devices may support read or write operations, while others may only support one of them.
 *       Check the device documentation for supported flags.
 *
 * @warning Ensure that the device pointer (`dev`) is valid and that the device has been initialized
 *          properly. Incorrect flags or attempting to open a device that is already in use may result
 *          in errors or undefined behavior.
 */
sysret_t sys_device_open(rt_device_t dev, rt_uint16_t oflag)
{
    return rt_device_open(dev, oflag);
}

/**
 * @brief Closes an open device.
 *
 * This system call closes an open device, releasing any resources or locks associated with it
 * and making it unavailable for further interaction until it is opened again. The device must
 * have been previously opened using `sys_device_open`. After calling this function, any further
 * attempts to interact with the device will result in an error unless the device is opened again.
 *
 * @param[in] dev  A pointer to the device structure representing the device to be closed.
 *                 The device must be open before it can be closed.
 *
 * @return sysret_t  Returns a status code:
 *                    - `0`: The device was successfully closed.
 *                    - Other error codes may indicate issues with the device closing process.
 *
 * @note This function should be called when the device is no longer needed or before shutting
 *       down the system to release device resources properly.
 *
 * @warning Ensure that the device has been opened before calling this function. Calling this function
 *          on an uninitialized or already closed device may result in undefined behavior or errors.
 */
sysret_t sys_device_close(rt_device_t dev)
{
    return rt_device_close(dev);
}

/**
 * @brief Reads data from an open device.
 *
 * This system call reads data from the specified device, starting at the given position and
 * storing the data in the provided buffer. The device must be open before this function can be called.
 * The amount of data to read is determined by the `size` parameter.
 *
 * @param[in]  dev     A pointer to the device structure representing the device to read from.
 *                     The device must be open and ready for reading.
 * @param[in]  pos     The position within the device from which to begin reading. For devices that
 *                     support seeking, this value is used to specify the starting point.
 * @param[out] buffer  A pointer to the buffer where the read data will be stored. This buffer should
 *                     be large enough to hold the specified amount of data.
 * @param[in]  size    The number of bytes to read from the device. This value determines how much
 *                     data is read into the buffer.
 *
 * @return rt_ssize_t  Returns the number of bytes actually read from the device:
 *                      - On success: The number of bytes read, which may be less than `size` if
 *                        the end of the device is reached or other factors limit the read.
 *                      - On failure: A negative error code.
 *
 * @note The device must be open and in a readable state before calling this function.
 *       The `pos` parameter allows seeking within the device if it supports such operations.
 *
 * @warning Ensure that the buffer provided is large enough to hold the data being read.
 *          Providing an insufficient buffer may result in undefined behavior.
 */
rt_ssize_t sys_device_read(rt_device_t dev, rt_off_t pos, void *buffer, rt_size_t size)
{
    return rt_device_read(dev, pos, buffer, size);
}

/**
 * @brief Writes data to an open device.
 *
 * This system call writes data to the specified device, starting at the given position and using
 * the provided buffer. The device must be open and ready for writing. The amount of data to write
 * is determined by the `size` parameter.
 *
 * @param[in]  dev     A pointer to the device structure representing the device to write to.
 *                     The device must be open and ready for writing.
 * @param[in]  pos     The position within the device where the writing should start. For devices
 *                     that support seeking, this value specifies the location to begin writing.
 * @param[in]  buffer  A pointer to the buffer containing the data to be written to the device.
 *                     This buffer should contain the data to be written and should be large enough
 *                     to accommodate the specified size.
 * @param[in]  size    The number of bytes to write to the device. This value indicates how much
 *                     data should be written from the buffer to the device.
 *
 * @return rt_ssize_t  Returns the number of bytes actually written to the device:
 *                      - On success: The number of bytes written, which may be less than `size`
 *                        if there is an issue with the device or the data was truncated.
 *                      - On failure: A negative error code.
 *
 * @note The device must be open and in a writable state before calling this function.
 *       The `pos` parameter allows seeking within the device if it supports such operations.
 *
 * @warning Ensure that the buffer provided contains valid data and that it is large enough
 *          to fit the amount of data specified by `size`. Providing an insufficient buffer
 *          or invalid data may lead to undefined behavior.
 */
rt_ssize_t sys_device_write(rt_device_t dev, rt_off_t pos, const void *buffer, rt_size_t size)
{
    return rt_device_write(dev, pos, buffer, size);
}

#ifdef RT_USING_SAL
/* network interfaces */

/**
 * @brief Accepts a connection on a socket.
 *
 * This system call is used to accept a pending connection request on a socket. It extracts the
 * first connection request from the incoming queue, creates a new socket for the connection,
 * and stores the address information of the remote peer in the provided address structure.
 * The original socket must be a listening socket that has been previously bound and set to listen
 * for incoming connections.
 *
 * @param[in]  socket    The listening socket file descriptor that is waiting for incoming connections.
 *                       This socket must be in a listening state, created using `sys_socket` and
 *                       bound to an address using `sys_bind`.
 * @param[out] addr      A pointer to a `musl_sockaddr` structure where the address of the connecting
 *                       client will be stored. The structure is populated with information such as
 *                       the client's IP address and port number.
 * @param[in,out] addrlen A pointer to a socklen_t variable that specifies the size of the `addr`
 *                        structure on input. On output, it will contain the actual size of the
 *                        address returned in `addr`.
 *
 * @return sysret_t      Returns a socket descriptor for the new connection on success, or
 *                        `SYSRET_ERROR` on failure:
 *                        - On success: A new socket descriptor that can be used for further
 *                          communication with the connected peer.
 *                        - On failure: A negative error code indicating the reason for the failure.
 *
 * @note The socket passed as `socket` must be in a listening state and ready to accept incoming
 *       connections. The `addr` structure is populated with the client's address details, which can
 *       be used for further operations, such as identifying the client.
 *
 * @warning Ensure that the `addr` structure is sufficiently large to hold the address information.
 *          The `addrlen` parameter must be set to the size of the `musl_sockaddr` structure before
 *          calling this function. Calling the function with an incorrectly sized `addrlen` may lead
 *          to buffer overflows or undefined behavior.
 */
sysret_t sys_accept(int socket, struct musl_sockaddr *addr, socklen_t *addrlen)
{
    int ret = -1;
    struct sockaddr ksa;
    struct musl_sockaddr kmusladdr;
    socklen_t uaddrlen;
    socklen_t kaddrlen;

    if (addr)
    {
        if (!lwp_user_accessable(addrlen, sizeof(socklen_t)))
        {
            return -EFAULT;
        }
        lwp_get_from_user(&uaddrlen, addrlen, sizeof(socklen_t));
        if (!uaddrlen)
        {
            return -EINVAL;
        }

        if (!lwp_user_accessable(addr, uaddrlen))
        {
            return -EFAULT;
        }
    }

    kaddrlen = sizeof(struct sockaddr);
    ret = accept(socket, &ksa, &kaddrlen);
    if (ret >= 0)
    {
        if (addr)
        {
            sockaddr_tomusl(&ksa, &kmusladdr);
            if (uaddrlen > sizeof(struct musl_sockaddr))
            {
                uaddrlen = sizeof(struct musl_sockaddr);
            }
            lwp_put_to_user(addr, &kmusladdr, uaddrlen);
            lwp_put_to_user(addrlen, &uaddrlen, sizeof(socklen_t));
        }
    }
    return ret;
}

/**
 * @brief Binds a socket to a local address.
 *
 * This system call binds a socket to a specific local address and port. The socket must be created
 * using `sys_socket` before it can be bound. The `bind` operation allows the application to associate
 * a socket with a specific address, such as an IP address and port number, which can then be used
 * for sending or receiving data.
 *
 * @param[in]  socket  The socket descriptor to which the address will be bound. This socket must
 *                     be created using `sys_socket` and should not already be bound to another address.
 * @param[in]  name    A pointer to a `musl_sockaddr` structure that contains the address to which
 *                     the socket will be bound. This can represent an IP address and port number.
 * @param[in]  namelen The size of the `musl_sockaddr` structure in bytes. This value should be set
 *                     to the actual size of the `name` structure before calling this function.
 *
 * @return sysret_t    Returns `0` on success, or a negative error code on failure.
 *
 * @note The `socket` must be created before calling this function, and the address provided in `name`
 *       should be a valid local address for the socket. This operation is typically used for server-side
 *       sockets that listen for incoming connections or for any socket that needs to specify its local
 *       address before communication.
 *
 * @warning If the specified address is already in use by another socket or if the socket type is incompatible
 *          with the address, the function will return an error. Ensure that the address is not in use and is
 *          valid for the socket type.
 */
sysret_t sys_bind(int socket, const struct musl_sockaddr *name, socklen_t namelen)
{
    rt_err_t ret = 0;
    struct sockaddr sa;
    struct sockaddr_un un_addr;
    struct musl_sockaddr kname;
    rt_uint16_t family = 0;

    if (!lwp_user_accessable((void *)name, namelen))
    {
        return -EFAULT;
    }

    lwp_get_from_user(&family, (void *)name, 2);
    if (family == AF_UNIX)
    {
        lwp_get_from_user(&un_addr, (void *)name, sizeof(struct sockaddr_un));
        ret = bind(socket, (struct sockaddr *)&un_addr, namelen);
    }
    else if (family == AF_NETLINK)
    {
        lwp_get_from_user(&sa, (void *)name, namelen);
        ret = bind(socket, &sa, namelen);
    }
    else
    {
        lwp_get_from_user(&kname, (void *)name, namelen);
        sockaddr_tolwip(&kname, &sa);
        ret = bind(socket, &sa, namelen);
    }

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Shuts down part of a full-duplex connection.
 *
 * This system call disables further send or receive operations on a socket. The `how` parameter
 * specifies which part of the connection should be shut down. This operation is typically used
 * when the application no longer needs to send or receive data, but wants to keep the connection open
 * for other purposes (e.g., receiving shutdown acknowledgment).
 *
 * @param[in]  socket  The socket descriptor to be shut down. This socket must be an open socket that
 *                     has been created using `sys_socket`.
 * @param[in]  how     The shutdown behavior:
 *                     - `SHUT_RD`: Disables further receives on the socket. The application can no longer
 *                       receive data from this socket.
 *                     - `SHUT_WR`: Disables further sends on the socket. The application can no longer
 *                       send data through this socket.
 *                     - `SHUT_RDWR`: Disables both sends and receives on the socket. The socket is
 *                       fully shut down for communication.
 *
 * @return sysret_t    Returns `0` on success, or a negative error code (e.g., `SYSRET_ERROR`) on failure.
 *
 * @note The `socket` should be open and in a connected state when calling this function. The `how`
 *       parameter determines which part of the connection is to be shut down, allowing for finer control
 *       over communication termination.
 *
 * @warning Once a socket is shut down with `SHUT_RD`, no further data can be received on it. Similarly,
 *          after `SHUT_WR`, no more data can be sent. Calling `sys_shutdown` with incompatible `how` values
 *          or on an invalid socket may result in errors.
 */
sysret_t sys_shutdown(int socket, int how)
{
    return shutdown(socket, how);
}

/**
 * @brief Retrieves the address of the peer connected to a socket.
 *
 * This system call retrieves the address of the peer (remote endpoint) that is connected to the specified
 * socket. The socket must be connected (i.e., for stream-oriented protocols such as TCP). The address
 * of the peer is stored in the `name` structure, and the size of the structure is updated in `namelen`.
 *
 * @param[in]  socket    The socket descriptor of the connected socket. This socket must be in a connected
 *                       state (e.g., after a successful `sys_connect` or `sys_accept` call).
 * @param[out] name      A pointer to a `musl_sockaddr` structure where the address of the peer will be
 *                       stored. This structure will be populated with the peer's IP address and port number.
 * @param[in,out] namelen A pointer to a `socklen_t` variable that specifies the size of the `name` structure
 *                        on input. On output, it will contain the actual size of the address returned in `name`.
 *
 * @return sysret_t      Returns `SYSRET_OK` on success, or a negative error code on failure.
 *
 * @note The `socket` must be in a connected state when calling this function. The `name` structure will
 *       contain the peer's address information, which can be used for logging, debugging, or further
 *       communication.
 *
 * @warning Ensure that the `name` structure is sufficiently large to hold the peer's address information.
 *          The `namelen` parameter must be set to the size of the `name` structure before calling this function.
 *          Failing to provide a correctly sized `namelen` could result in buffer overflows or undefined behavior.
 */
sysret_t sys_getpeername(int socket, struct musl_sockaddr *name, socklen_t *namelen)
{
    int ret = -1;
    struct sockaddr sa;
    struct musl_sockaddr kname;
    socklen_t unamelen;
    socklen_t knamelen;

    if (!lwp_user_accessable(namelen, sizeof(socklen_t)))
    {
        return -EFAULT;
    }
    lwp_get_from_user(&unamelen, namelen, sizeof(socklen_t));
    if (!unamelen)
    {
        return -EINVAL;
    }

    if (!lwp_user_accessable(name, unamelen))
    {
        return -EFAULT;
    }

    knamelen = sizeof(struct sockaddr);
    ret = getpeername(socket, &sa, &knamelen);

    if (ret == 0)
    {
        sockaddr_tomusl(&sa, &kname);
        if (unamelen > sizeof(struct musl_sockaddr))
        {
            unamelen = sizeof(struct musl_sockaddr);
        }
        lwp_put_to_user(name, &kname, unamelen);
        lwp_put_to_user(namelen, &unamelen, sizeof(socklen_t));
    }
    else
    {
        ret = GET_ERRNO();
    }

    return ret;
}

/**
 * @brief Retrieves the local address of the socket.
 *
 * This system call retrieves the local address (local endpoint) that is bound to the specified socket.
 * The socket must be created and, if necessary, bound to a local address using `sys_bind`. The address
 * of the local endpoint is stored in the `name` structure, and the size of the structure is updated in `namelen`.
 *
 * @param[in]  socket    The socket descriptor of the socket. This socket must be created and, if required,
 *                       bound to a local address.
 * @param[out] name      A pointer to a `musl_sockaddr` structure where the local address of the socket will
 *                       be stored. This structure will be populated with the local IP address and port number.
 * @param[in,out] namelen A pointer to a `socklen_t` variable that specifies the size of the `name` structure
 *                        on input. On output, it will contain the actual size of the address returned in `name`.
 *
 * @return sysret_t      Returns `0` on success, or a negative error code on failure.
 *
 * @note The `socket` must be created and, if needed, bound to a local address using `sys_bind`.
 *       The `name` structure will contain the local address of the socket, which can be used for logging,
 *       debugging, or further communication.
 *
 * @warning Ensure that the `name` structure is sufficiently large to hold the local address information.
 *          The `namelen` parameter must be set to the size of the `name` structure before calling this function.
 *          Failing to provide a correctly sized `namelen` could result in buffer overflows or undefined behavior.
 */
sysret_t sys_getsockname(int socket, struct musl_sockaddr *name, socklen_t *namelen)
{
    int ret = -1;
    struct sockaddr sa;
    struct musl_sockaddr kname;
    socklen_t unamelen;
    socklen_t knamelen;

    if (!lwp_user_accessable(namelen, sizeof (socklen_t)))
    {
        return -EFAULT;
    }
    lwp_get_from_user(&unamelen, namelen, sizeof (socklen_t));
    if (!unamelen)
    {
        return -EINVAL;
    }

    if (!lwp_user_accessable(name, unamelen))
    {
        return -EFAULT;
    }

    knamelen = sizeof(struct sockaddr);
    ret = getsockname(socket, &sa, &knamelen);
    if (ret == 0)
    {
        sockaddr_tomusl(&sa, &kname);
        if (unamelen > sizeof(struct musl_sockaddr))
        {
            unamelen = sizeof(struct musl_sockaddr);
        }
        lwp_put_to_user(name, &kname, unamelen);
        lwp_put_to_user(namelen, &unamelen, sizeof(socklen_t));
    }
    else
    {
        ret = GET_ERRNO();
    }
    return ret;
}

/**
 * @brief Retrieves the value of a socket option.
 *
 * This system call retrieves the current value of a socket option for the specified socket. The socket
 * options allow fine-grained control over various aspects of socket behavior, such as timeouts, buffering,
 * and connection settings. The option value is stored in the `optval` buffer, and the size of the buffer
 * is specified by the `optlen` parameter.
 *
 * @param[in]  socket    The socket descriptor for which the option value is being retrieved. The socket
 *                       must be valid and open.
 * @param[in]  level     The level at which the option is defined. Typically, this is `SOL_SOCKET` for general
 *                       socket options, or a protocol-specific level (e.g., `IPPROTO_TCP` for TCP options).
 * @param[in]  optname   The option name. This specifies which socket option to retrieve (e.g., `SO_RCVBUF`
 *                       for receive buffer size or `SO_RCVBUF` for send buffer size).
 * @param[out] optval    A pointer to a buffer where the option value will be stored. The buffer's type depends
 *                       on the option being retrieved.
 * @param[in,out] optlen A pointer to a `socklen_t` variable that specifies the size of the `optval` buffer on
 *                       input. On output, it will contain the actual size of the option value retrieved.
 *
 * @return sysret_t      Returns `0` on success, or a negative error code on failure.
 *
 * @note The `socket` must be valid and open when calling this function. The `level` and `optname` parameters
 *       define the specific option to be retrieved. The `optval` buffer will contain the option value after
 *       the function call, and `optlen` will be updated to reflect the size of the retrieved value.
 *
 * @warning Ensure that the `optval` buffer is large enough to hold the value for the specified option.
 *          The `optlen` parameter must be set to the correct size of the buffer before calling this function.
 *          Failing to provide a correctly sized buffer could result in undefined behavior or buffer overflows.
 */
sysret_t sys_getsockopt(int socket, int level, int optname, void *optval, socklen_t *optlen)
{
    int ret = 0;
    socklen_t koptlen = 0;
    void *koptval = RT_NULL;

    if (!lwp_user_accessable((void *)optlen, sizeof(uint32_t)))
        return -EFAULT;

    if (lwp_get_from_user(&koptlen, optlen, sizeof(uint32_t)) != sizeof(uint32_t))
    {
        return -EINVAL;
    }

    if (!lwp_user_accessable((void *)optval, koptlen))
        return -EFAULT;

    koptval = kmem_get(koptlen);
    if (koptval == RT_NULL)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(koptval, optval, koptlen) != koptlen)
    {
        kmem_put(koptval);
        return -EINVAL;
    }

    convert_sockopt(&level, &optname);
    ret = getsockopt(socket, level, optname, koptval, &koptlen);

    lwp_put_to_user((void *)optval, koptval, koptlen);
    lwp_put_to_user((void *)optlen, &koptlen, sizeof(uint32_t));

    kmem_put(koptval);

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Sets the value of a socket option.
 *
 * This system call sets a socket option for the specified socket. Socket options control various aspects
 * of socket behavior, such as timeouts, buffer sizes, or connection parameters. The option value is
 * provided in the `optval` buffer, and its length is specified by the `optlen` parameter.
 *
 * @param[in]  socket    The socket descriptor for which the option is being set. The socket must be valid and open.
 * @param[in]  level     The level at which the option is defined. This can be `SOL_SOCKET` for general socket options,
 *                       or a protocol-specific level (e.g., `IPPROTO_TCP` for TCP options).
 * @param[in]  optname   The option name. This specifies which socket option to set (e.g., `SO_RCVBUF` for receive buffer size).
 * @param[in]  optval    A pointer to the buffer that contains the option value to set. The format of this buffer depends
 *                       on the option being set.
 * @param[in]  optlen    The size of the `optval` buffer. This specifies the length of the data to be used when setting
 *                       the option value.
 *
 * @return sysret_t      Returns `0` on success, or a negative error code on failure:
 *
 * @note The `socket` must be valid and open. The `level` and `optname` parameters define the specific option to be set,
 *       and the `optval` buffer should contain the appropriate value for that option. The `optlen` parameter must
 *       match the size of the `optval` buffer.
 *
 * @warning Ensure that the `optval` buffer contains valid data for the specified option. The `optlen` parameter must be
 *          set to the correct size of the `optval` buffer before calling this function. Failing to provide a correctly
 *          sized buffer could result in undefined behavior or errors.
 */
sysret_t sys_setsockopt(int socket, int level, int optname, const void *optval, socklen_t optlen)
{
    int ret;
    void *koptval = RT_NULL;

    if (!lwp_user_accessable((void *)optval, optlen))
        return -EFAULT;

    koptval = kmem_get(optlen);
    if (koptval == RT_NULL)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(koptval, (void *)optval, optlen) != optlen)
    {
        kmem_put(koptval);
        return -EINVAL;
    }

    convert_sockopt(&level, &optname);
    ret = setsockopt(socket, level, optname, koptval, optlen);

    kmem_put(koptval);

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Establishes a connection to a remote socket.
 *
 * This system call attempts to establish a connection to a remote socket specified by the `name` parameter.
 * It is typically used for client-side socket operations to connect to a server. The connection is established
 * by using the specified socket descriptor and the address of the remote server.
 *
 * @param[in]  socket   The socket descriptor for the connection attempt. The socket must be valid and in a
 *                      `SOCK_STREAM` or `SOCK_DGRAM` state, depending on the protocol.
 * @param[in]  name     A pointer to a `sockaddr` structure containing the address of the remote host. This address
 *                      must include the correct IP address and port number for the connection.
 * @param[in]  namelen  The size of the `sockaddr` structure pointed to by `name`. This should match the size
 *                      of the address structure (e.g., `sizeof(struct sockaddr_in)` for IPv4).
 *
 * @return sysret_t     Returns `0` on success, or a negative error code on failure:
 *
 * @note This function may block if the connection is being established, depending on the socket's configuration.
 *       For non-blocking sockets, it will return immediately, even if the connection has not been established.
 *
 * @warning The `socket` must be of a valid type (e.g., `SOCK_STREAM` for TCP or `SOCK_DGRAM` for UDP).
 *          The `name` parameter must point to a valid `sockaddr` structure that contains a correctly formatted address.
 */
sysret_t sys_connect(int socket, const struct musl_sockaddr *name, socklen_t namelen)
{
    int ret = 0;
    rt_uint16_t family = 0;
    struct sockaddr sa;
    struct musl_sockaddr kname;
    struct sockaddr_un addr_un;

    if (!lwp_user_accessable((void *)name, namelen))
    {
        return -EFAULT;
    }

    lwp_get_from_user(&family, (void *)name, 2);
    if (family == AF_UNIX)
    {
        if (!lwp_user_accessable((void *)name, sizeof(struct sockaddr_un)))
        {
            return -EFAULT;
        }

        lwp_get_from_user(&addr_un, (void *)name, sizeof(struct sockaddr_un));
        ret = connect(socket, (struct sockaddr *)(&addr_un), namelen);
    }
    else
    {
        lwp_get_from_user(&kname, (void *)name, namelen);
        sockaddr_tolwip(&kname, &sa);
        ret = connect(socket, &sa, namelen);
    }

    return ret;
}

/**
 * @brief Prepares a socket to accept incoming connection requests.
 *
 * This system call marks a socket as a passive socket, indicating that it will be used to accept
 * incoming connection requests. It is typically used on server-side sockets after binding a
 * local address and port using `sys_bind()`.
 *
 * @param[in]  socket   The socket descriptor to be set up for listening. The socket must be valid
 *                      and of type `SOCK_STREAM` (for TCP connections).
 * @param[in]  backlog  The maximum number of pending connections that can be queued. This value
 *                      is system-dependent and may be limited to a lower maximum.
 *
 * @return sysret_t     Returns `0` on success, or a negative error code on failure.
 *
 * @note Before calling this function, the socket must be bound to a local address and port using
 *       `sys_bind()`. Only sockets of type `SOCK_STREAM` can be used for listening. The actual
 *       maximum queue length may be less than the specified `backlog` value, depending on system limits.
 *
 * @warning Ensure that the socket is properly initialized, bound, and of the correct type before calling this function.
 *          Failure to do so will result in undefined behavior or errors.
 */
sysret_t sys_listen(int socket, int backlog)
{
    return listen(socket, backlog);
}

#define MUSLC_MSG_OOB       0x0001
#define MUSLC_MSG_PEEK      0x0002
#define MUSLC_MSG_DONTWAIT  0x0040
#define MUSLC_MSG_WAITALL   0x0100
#define MUSLC_MSG_MORE      0x8000

static int netflags_muslc_2_lwip(int flags)
{
    int flgs = 0;

    if (flags & MUSLC_MSG_PEEK)
    {
        flgs |= MSG_PEEK;
    }
    if (flags & MUSLC_MSG_WAITALL)
    {
        flgs |= MSG_WAITALL;
    }
    if (flags & MUSLC_MSG_OOB)
    {
        flgs |= MSG_OOB;
    }
    if (flags & MUSLC_MSG_DONTWAIT)
    {
        flgs |= MSG_DONTWAIT;
    }
    if (flags & MUSLC_MSG_MORE)
    {
        flgs |= MSG_MORE;
    }
    if (flags & MSG_ERRQUEUE)
    {
        flgs |= MSG_ERRQUEUE;
    }

    return flgs;
}

#ifdef ARCH_MM_MMU
static int copy_msghdr_from_user(struct msghdr *kmsg, struct msghdr *umsg,
        struct iovec **out_iov, void **out_msg_control)
{
    size_t iovs_size;
    struct iovec *uiov, *kiov;
    size_t iovs_buffer_size = 0;
    void *iovs_buffer;

    if (!lwp_user_accessable(umsg, sizeof(*umsg)))
    {
        return -EFAULT;
    }

    lwp_get_from_user(kmsg, umsg, sizeof(*kmsg));

    iovs_size = sizeof(*kmsg->msg_iov) * kmsg->msg_iovlen;
    if (!lwp_user_accessable(kmsg->msg_iov, iovs_size))
    {
        return -EFAULT;
    }

    /* user and kernel */
    kiov = kmem_get(iovs_size * 2);
    if (!kiov)
    {
        return -ENOMEM;
    }

    uiov = (void *)kiov + iovs_size;
    lwp_get_from_user(uiov, kmsg->msg_iov, iovs_size);

    if (out_iov)
    {
        *out_iov = uiov;
    }
    kmsg->msg_iov = kiov;

    for (int i = 0; i < kmsg->msg_iovlen; ++i)
    {
        /*
         * We MUST check we can copy data to user after socket done in uiov
         * otherwise we will be lost the messages from the network!
         */
        if (!lwp_user_accessable(uiov->iov_base, uiov->iov_len))
        {
            kmem_put(kmsg->msg_iov);

            return -EPERM;
        }

        iovs_buffer_size += uiov->iov_len;
        kiov->iov_len = uiov->iov_len;

        ++kiov;
        ++uiov;
    }

    /* msg_iov and msg_control */
    iovs_buffer = kmem_get(iovs_buffer_size + kmsg->msg_controllen);

    if (!iovs_buffer)
    {
        kmem_put(kmsg->msg_iov);

        return -ENOMEM;
    }

    kiov = kmsg->msg_iov;

    for (int i = 0; i < kmsg->msg_iovlen; ++i)
    {
        kiov->iov_base = iovs_buffer;
        iovs_buffer += kiov->iov_len;
        ++kiov;
    }

    *out_msg_control = kmsg->msg_control;
    /* msg_control is the end of the iovs_buffer */
    kmsg->msg_control = iovs_buffer;

    return 0;
}
#endif /* ARCH_MM_MMU */

/**
 * @brief Receives a message from a socket using a message header structure.
 *
 * This system call is used to receive data and associated metadata from a socket.
 * It supports both stream-oriented and message-oriented sockets and allows control
 * over the behavior of the receiving operation via the `flags` parameter.
 *
 * @param[in]  socket   The socket descriptor from which the message will be received.
 *                      The socket must be in a valid and connected state for stream-oriented
 *                      sockets or bound for message-oriented sockets.
 * @param[out] msg      A pointer to an `msghdr` structure that specifies message buffers and
 *                      will receive the incoming data. The structure also stores ancillary
 *                      data for advanced socket operations.
 * @param[in]  flags    Modifiers that control the behavior of the receive operation. Common
 *                      flags include:
 *                       - `MSG_PEEK`: Peek at the incoming data without removing it from the queue.
 *                       - `MSG_WAITALL`: Wait for the full request to be satisfied before returning.
 *                       - `MSG_DONTWAIT`: Perform a non-blocking receive operation.
 *
 * @return sysret_t     Returns `0` on success, or a negative error code on failure.
 *
 * @note The `msghdr` structure should be initialized properly, including setting up buffers for
 *       receiving the data. The function can return fewer bytes than expected depending on socket
 *       type and flags. For stream-oriented sockets, partial data may be received.
 *
 * @warning The `socket` must be valid and in an appropriate state. If the socket is non-blocking
 *          and no data is available, the function will return immediately.
 *
 * @see sys_sendmsg()
 */
sysret_t sys_recvmsg(int socket, struct msghdr *msg, int flags)
{
    int flgs, ret = -1;
    struct msghdr kmsg;
#ifdef ARCH_MM_MMU
    void *msg_control;
    struct iovec *uiov, *kiov;
#endif

    if (!msg)
    {
        return -EPERM;
    }

    flgs = netflags_muslc_2_lwip(flags);

#ifdef ARCH_MM_MMU
    ret = copy_msghdr_from_user(&kmsg, msg, &uiov, &msg_control);

    if (!ret)
    {
        ret = recvmsg(socket, &kmsg, flgs);

        if (ret < 0)
        {
            goto _free_res;
        }

        kiov = kmsg.msg_iov;

        for (int i = 0; i < kmsg.msg_iovlen; ++i)
        {
            lwp_put_to_user(uiov->iov_base, kiov->iov_base, kiov->iov_len);

            ++kiov;
            ++uiov;
        }

        lwp_put_to_user(msg_control, kmsg.msg_control, kmsg.msg_controllen);
        lwp_put_to_user(&msg->msg_flags, &kmsg.msg_flags, sizeof(kmsg.msg_flags));

    _free_res:
        kmem_put(kmsg.msg_iov->iov_base);
        kmem_put(kmsg.msg_iov);
    }
#else
    rt_memcpy(&kmsg, msg, sizeof(kmsg));

    ret = recvmsg(socket, &kmsg, flgs);

    if (!ret)
    {
        msg->msg_flags = kmsg.msg_flags;
    }
#endif /* ARCH_MM_MMU */

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Receives data from a socket, optionally capturing the source address.
 *
 * This system call is used to receive data from a socket. For connectionless sockets, it also
 * retrieves the address of the sender. It supports both blocking and non-blocking operations
 * depending on the socket configuration and the specified flags.
 *
 * @param[in]  socket   The socket descriptor from which the data will be received. The socket
 *                      must be valid and appropriately configured (e.g., connected or bound).
 * @param[out] mem      A pointer to the buffer where the received data will be stored.
 * @param[in]  len      The maximum number of bytes to receive. This defines the size of the `mem` buffer.
 * @param[in]  flags    Modifiers that control the behavior of the receive operation. Common
 *                      flags include:
 *                       - `MSG_PEEK`: Peek at the incoming data without removing it from the queue.
 *                       - `MSG_WAITALL`: Wait for the full request to be satisfied before returning.
 *                       - `MSG_DONTWAIT`: Perform a non-blocking receive operation.
 * @param[out] from     A pointer to a `musl_sockaddr` structure that will hold the address of
 *                      the sender. This parameter can be `NULL` if the sender's address is not needed.
 * @param[in,out] fromlen A pointer to a `socklen_t` variable indicating the size of the `from` buffer.
 *                        On return, it will be updated with the actual size of the sender's address.
 *                        This parameter is ignored if `from` is `NULL`.
 *
 * @return sysret_t     Returns `0` on success, or a negative error code on failure:
 *
 * @note For stream-oriented sockets, this function behaves like `sys_recv()`, and the `from` and
 *       `fromlen` parameters are ignored. For datagram-oriented sockets, the function fills `from`
 *       with the address of the sender.
 *
 * @warning The `socket` must be valid and configured for receiving data. If the `mem` buffer is
 *          smaller than the received data, excess data may be discarded. In non-blocking mode,
 *          if no data is available, the function returns immediately.
 *
 * @see sys_sendto(), sys_recv()
 */
sysret_t sys_recvfrom(int socket, void *mem, size_t len, int flags,
      struct musl_sockaddr *from, socklen_t *fromlen)
{
    int flgs = 0;
#ifdef ARCH_MM_MMU
    int ret = -1;
    void *kmem = RT_NULL;
#endif

    flgs = netflags_muslc_2_lwip(flags);
#ifdef ARCH_MM_MMU
    if (!len)
    {
        return -EINVAL;
    }

    if (!lwp_user_accessable((void *)mem, len))
    {
        return -EFAULT;
    }

    kmem = kmem_get(len);
    if (!kmem)
    {
        return -ENOMEM;
    }

    if (flags == 0x2)
    {
        flags = 0x1;
    }

    if (from)
    {
        struct sockaddr sa;

        ret = recvfrom(socket, kmem, len, flgs, &sa, fromlen);
        sockaddr_tomusl(&sa, from);
    }
    else
    {
        ret = recvfrom(socket, kmem, len, flgs, NULL, NULL);
    }

    if (ret > 0)
    {
        lwp_put_to_user(mem, kmem, len);
    }

    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    kmem_put(kmem);

    return ret;
#else
    int ret = -1;
    if (from)
    {
        struct sockaddr sa = {0};

        ret = recvfrom(socket, mem, len, flgs, &sa, fromlen);
        sockaddr_tomusl(&sa, from);
    }
    else
    {
        ret = recvfrom(socket, mem, len, flags, NULL, NULL);
    }
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Receives data from a connected socket.
 *
 * This system call is used to receive data from a socket that is in a connected state.
 * It supports various flags to modify the behavior of the receive operation.
 *
 * @param[in]  socket   The socket descriptor from which the data will be received.
 *                      The socket must be in a valid and connected state.
 * @param[out] mem      A pointer to the buffer where the received data will be stored.
 * @param[in]  len      The maximum number of bytes to receive. This defines the size of the `mem` buffer.
 * @param[in]  flags    Modifiers that control the behavior of the receive operation. Common flags include:
 *                       - `MSG_PEEK`: Peek at the incoming data without removing it from the queue.
 *                       - `MSG_WAITALL`: Wait for the full request to be satisfied before returning.
 *                       - `MSG_DONTWAIT`: Perform a non-blocking receive operation.
 *
 * @return sysret_t     Returns `0` on success, or a negative error code on failure.
 *
 * @note The function is designed for connected sockets, such as stream-oriented sockets (e.g., TCP).
 *       For datagram-oriented sockets (e.g., UDP), use `sys_recvfrom()` to capture the sender's address if needed.
 *
 * @warning The `socket` must be valid and in a connected state. If the `mem` buffer is smaller than the
 *          received data, excess data may be discarded. For non-blocking sockets, the function returns
 *          immediately if no data is available.
 *
 * @see sys_send(), sys_recvfrom()
 */
sysret_t sys_recv(int socket, void *mem, size_t len, int flags)
{
    int flgs = 0;
    int ret;
    void *kmem = RT_NULL;

    if (!lwp_user_accessable((void *)mem, len))
        return -EFAULT;

    kmem = kmem_get(sizeof(*kmem));
    if (kmem == RT_NULL)
    {
        return -ENOMEM;
    }

    flgs = netflags_muslc_2_lwip(flags);
    ret = recvfrom(socket, kmem, len, flgs, NULL, NULL);

    lwp_put_to_user((void *)mem, kmem, len);
    kmem_put(kmem);

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Sends a message from a socket using scatter-gather I/O.
 *
 * This system call sends data from multiple buffers specified in the `msghdr` structure. It is particularly
 * useful for advanced socket operations requiring ancillary data or scatter-gather I/O.
 *
 * @param[in] socket   The socket descriptor through which the data will be sent. The socket must be
 *                     valid and, for connection-oriented sockets, in a connected state.
 * @param[in] msg      A pointer to a `msghdr` structure that specifies the message to be sent. This structure includes:
 *                      - `msg_name`: Optional address of the target (used for connectionless sockets like UDP).
 *                      - `msg_namelen`: Length of the address in `msg_name`.
 *                      - `msg_iov`: An array of `iovec` structures pointing to the data buffers.
 *                      - `msg_iovlen`: The number of elements in the `msg_iov` array.
 *                      - `msg_control`: Optional ancillary data (e.g., file descriptors).
 *                      - `msg_controllen`: Length of the ancillary data.
 *                      - `msg_flags`: Flags for the message (e.g., end-of-record markers).
 * @param[in] flags    Flags that modify the behavior of the send operation. Common flags include:
 *                      - `MSG_DONTWAIT`: Perform a non-blocking send operation.
 *                      - `MSG_EOR`: Indicates the end of a record.
 *                      - `MSG_NOSIGNAL`: Prevent the function from raising `SIGPIPE` on errors.
 *
 * @return sysret_t    Returns `0` on success, or a negative error code on failure.
 *
 * @note This function is versatile and supports both connection-oriented (e.g., TCP) and
 *       connectionless (e.g., UDP) sockets. For simpler use cases, consider using `sys_send()` or `sys_sendto()`.
 *
 * @warning The `socket` must be configured correctly for the intended communication. For non-blocking sockets,
 *          the function may return immediately if the send buffer is full. Ancillary data in `msg_control`
 *          must be formatted correctly to avoid undefined behavior.
 *
 * @see sys_send(), sys_sendto(), sys_recvmsg()
 */
sysret_t sys_sendmsg(int socket, const struct msghdr *msg, int flags)
{
    int flgs, ret = -1;
    struct msghdr kmsg;
#ifdef ARCH_MM_MMU
    void *msg_control;
    struct iovec *uiov, *kiov;
#endif
    if (!msg)
    {
        return -EPERM;
    }

    flgs = netflags_muslc_2_lwip(flags);

#ifdef ARCH_MM_MMU
    ret = copy_msghdr_from_user(&kmsg, (struct msghdr *)msg, &uiov, &msg_control);

    if (!ret)
    {
        kiov = kmsg.msg_iov;

        for (int i = 0; i < kmsg.msg_iovlen; ++i)
        {
            lwp_get_from_user(kiov->iov_base, uiov->iov_base, kiov->iov_len);

            ++kiov;
            ++uiov;
        }

        lwp_get_from_user(kmsg.msg_control, msg_control, kmsg.msg_controllen);

        ret = sendmsg(socket, &kmsg, flgs);

        kmem_put(kmsg.msg_iov->iov_base);
        kmem_put(kmsg.msg_iov);
    }
#else
    rt_memcpy(&kmsg, msg, sizeof(kmsg));

    ret = sendmsg(socket, &kmsg, flgs);

    if (!ret)
    {
        msg->msg_flags = kmsg.msg_flags;
    }
#endif /* ARCH_MM_MMU */

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Sends data to a specific address using a socket.
 *
 * This system call is used to send data from a socket to a specified address. It is commonly
 * used with connectionless sockets (e.g., UDP) but can also be used with connection-oriented
 * sockets if the destination address needs to be overridden.
 *
 * @param[in] socket   The socket descriptor used for sending data. It must be valid and
 *                     properly configured for communication.
 * @param[in] dataptr  A pointer to the buffer containing the data to be sent.
 * @param[in] size     The size, in bytes, of the data to be sent.
 * @param[in] flags    Flags that modify the behavior of the send operation. Common flags include:
 *                      - `MSG_DONTWAIT`: Perform a non-blocking send operation.
 *                      - `MSG_NOSIGNAL`: Prevent the function from raising `SIGPIPE` on errors.
 * @param[in] to       A pointer to a `musl_sockaddr` structure that specifies the destination address.
 *                     This parameter can be `NULL` if the socket is connection-oriented.
 * @param[in] tolen    The length of the address structure pointed to by `to`.
 *
 * @return sysret_t    Returns `0` on success, or a negative error code on failure.
 *
 * @note For connectionless sockets (e.g., UDP), `to` and `tolen` must specify a valid destination address.
 *       For connection-oriented sockets (e.g., TCP), these parameters can be ignored if the connection
 *       is already established.
 *
 * @warning Ensure that the buffer size (`size`) matches the expected size for the data protocol in use.
 *          For non-blocking sockets, this function may return immediately if the send buffer is full.
 *
 * @see sys_send(), sys_sendmsg(), sys_recvfrom()
 */
sysret_t sys_sendto(int socket, const void *dataptr, size_t size, int flags,
    const struct musl_sockaddr *to, socklen_t tolen)
{
    int flgs = 0;
#ifdef ARCH_MM_MMU
    int ret = -1;
    void *kmem = RT_NULL;
#endif

    flgs = netflags_muslc_2_lwip(flags);
#ifdef ARCH_MM_MMU
    if (!size)
    {
        return -EINVAL;
    }

    if (!lwp_user_accessable((void *)dataptr, size))
    {
        return -EFAULT;
    }

    kmem = kmem_get(size);
    if (!kmem)
    {
        return -ENOMEM;
    }

    lwp_get_from_user(kmem, (void *)dataptr, size);

    if (to)
    {
        struct sockaddr sa;
        sockaddr_tolwip(to, &sa);

        ret = sendto(socket, kmem, size, flgs, &sa, tolen);
    }
    else
    {
        ret = sendto(socket, kmem, size, flgs, NULL, tolen);
    }

    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    kmem_put(kmem);

    return ret;
#else
    int ret;
    if (to)
    {
        struct sockaddr sa;
        sockaddr_tolwip(to, &sa);

        ret = sendto(socket, dataptr, size, flgs, &sa, tolen);
    }
    else
    {
        ret = sendto(socket, dataptr, size, flgs, NULL, tolen);
    }
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Sends data over a connected socket.
 *
 * This system call sends data from the specified buffer through a connected socket. It is typically
 * used with connection-oriented sockets (e.g., TCP) but can also work with connectionless sockets
 * (e.g., UDP) if a connection is established using `sys_connect()`.
 *
 * @param[in] socket   The socket descriptor used for sending data. It must be a valid socket
 *                     and, for connection-oriented sockets, in a connected state.
 * @param[in] dataptr  A pointer to the buffer containing the data to be sent.
 * @param[in] size     The size, in bytes, of the data to be sent.
 * @param[in] flags    Flags that modify the behavior of the send operation. Common flags include:
 *                      - `MSG_DONTWAIT`: Perform a non-blocking send operation.
 *                      - `MSG_NOSIGNAL`: Prevent the function from raising `SIGPIPE` on errors.
 *
 * @return sysret_t    Returns `0` on success, or a negative error code on failure.
 *
 * @note For connection-oriented sockets, the socket must already be connected using `sys_connect()` or
 *       `sys_accept()`. For connectionless sockets, use `sys_sendto()` to specify the destination address.
 *
 * @warning If the socket is in non-blocking mode and the send buffer is full, this function may return
 *          immediately with an error. Ensure that the size of the data (`size`) matches the protocol's
 *          expectations to avoid truncation or overflow issues.
 *
 * @see sys_sendto(), sys_sendmsg(), sys_recv()
 */
sysret_t sys_send(int socket, const void *dataptr, size_t size, int flags)
{
    int flgs = 0;
    int ret = 0;
    void *kdataptr = RT_NULL;

    if (!lwp_user_accessable((void *)dataptr, size))
        return -EFAULT;

    kdataptr = kmem_get(size);
    if (kdataptr == RT_NULL)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(kdataptr, (void *)dataptr, size) != size)
    {
        kmem_put(kdataptr);
        return -EINVAL;
    }

    flgs = netflags_muslc_2_lwip(flags);
    ret = sendto(socket, kdataptr, size, flgs, NULL, 0);

    kmem_put(kdataptr);

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Creates a new socket for communication.
 *
 * This system call creates a new socket endpoint for communication and returns a file descriptor
 * that can be used for subsequent socket operations, such as binding, connecting, or data transfer.
 *
 * @param[in] domain   Specifies the protocol family to be used for the socket. Common values include:
 *                      - `AF_INET`: IPv4 Internet protocols.
 *                      - `AF_INET6`: IPv6 Internet protocols.
 *                      - `AF_UNIX`: Local communication using UNIX domain sockets.
 * @param[in] type     Specifies the type of socket to be created. Common values include:
 *                      - `SOCK_STREAM`: Provides sequenced, reliable, two-way, connection-based byte streams.
 *                      - `SOCK_DGRAM`: Supports datagrams (connectionless, unreliable messages of fixed maximum length).
 *                      - `SOCK_RAW`: Provides raw network protocol access.
 * @param[in] protocol Specifies the specific protocol to be used. Typically set to `0` to use the default
 *                     protocol for the specified domain and type.
 *
 * @return sysret_t    Returns the socket file descriptor on success, or a negative error code on failure.
 *
 * @note The returned socket descriptor must be closed using `sys_close()` to release system resources.
 *
 * @warning Ensure the combination of `domain`, `type`, and `protocol` is valid. Invalid combinations
 *          may result in errors. For example, specifying `AF_INET` with `SOCK_DGRAM` is valid for UDP,
 *          but with `SOCK_STREAM` it is used for TCP.
 *
 * @see sys_bind(), sys_connect(), sys_accept(), sys_close()
 */
sysret_t sys_socket(int domain, int type, int protocol)
{
    int fd = -1;
    int nonblock = 0;
    /* not support SOCK_CLOEXEC type */
    if (type & SOCK_CLOEXEC)
    {
        type &= ~SOCK_CLOEXEC;
    }
    if (type & SOCK_NONBLOCK)
    {
        nonblock = 1;
        type &= ~SOCK_NONBLOCK;
    }

    fd = socket(domain, type, protocol);
    if (fd < 0)
    {
        goto out;
    }
    if (nonblock)
    {
        fcntl(fd, F_SETFL, O_NONBLOCK);
    }

out:
    return (fd < 0 ? GET_ERRNO() : fd);
}

/**
 * @brief Creates a pair of connected sockets.
 *
 * This system call creates two connected sockets that can be used for bidirectional communication
 * between processes or threads. The sockets are returned as file descriptors in the `fd` array.
 *
 * @param[in] domain   Specifies the protocol family to be used for the sockets. Common values include:
 *                      - `AF_UNIX`: Local communication using UNIX domain sockets.
 * @param[in] type     Specifies the type of socket to be created. Common values include:
 *                      - `SOCK_STREAM`: Provides sequenced, reliable, two-way, connection-based byte streams.
 *                      - `SOCK_DGRAM`: Supports datagrams (connectionless, unreliable messages of fixed maximum length).
 * @param[in] protocol Specifies the specific protocol to be used. Typically set to `0` to use the default
 *                     protocol for the specified domain and type.
 * @param[out] fd      An array of two integers where the connected socket descriptors will be stored.
 *                     After a successful call:
 *                      - `fd[0]`: The first socket descriptor.
 *                      - `fd[1]`: The second socket descriptor.
 *
 * @return sysret_t    Returns `0` on success, or a negative error code on failure.
 *
 * @note The sockets in the pair are connected and can be used for inter-process communication
 *       (IPC) or between threads in the same process.
 *
 * @warning Ensure the `domain`, `type`, and `protocol` combination is valid. This function is typically
 *          supported only for `AF_UNIX` domain.
 *
 * @see sys_socket(), sys_close()
 */
sysret_t sys_socketpair(int domain, int type, int protocol, int fd[2])
{
#ifdef RT_USING_SAL
    int ret = 0;
    int k_fd[2];

    if (!lwp_user_accessable((void *)fd, sizeof(int [2])))
    {
        return -EFAULT;
    }

    ret = socketpair(domain, type, protocol, k_fd);

    if (ret == 0)
    {
        lwp_put_to_user(fd, k_fd, sizeof(int [2]));
    }

    return ret;
#else
    return -ELIBACC;
#endif
}

/**
 * @brief Closes an open socket.
 *
 * This system call is used to close a previously opened socket. Once the socket is closed, it is no longer
 * valid for any further operations, such as sending, receiving, or other socket-related functions.
 *
 * @param[in] socket  The socket descriptor to be closed. This descriptor must be a valid socket that was
 *                    previously created with `sys_socket()` or related functions.
 *
 * @return sysret_t   Returns `0` on success, or a negative error code on failure.
 *
 * @note Once a socket is closed, any attempts to use the socket for communication will result in an error.
 *       The system will release any resources associated with the socket.
 *
 * @warning Make sure that no data is being transferred or pending on the socket before closing it.
 *          Closing an active socket might lead to data loss.
 *
 * @see sys_socket(), sys_shutdown()
 */
sysret_t sys_closesocket(int socket)
{
    return closesocket(socket);
}

#endif

/**
 * @brief Finds a thread by its name.
 *
 * This system call is used to search for a thread based on its name. It returns a reference to the
 * thread if found, otherwise it returns `RT_NULL`. The name comparison is case-sensitive.
 *
 * @param[in] name    The name of the thread to search for. This should be a valid string that
 *                    uniquely identifies the thread within the system.
 *
 * @return rt_thread_t   The thread object corresponding to the given name, or `RT_NULL` if no
 *                        matching thread was found.
 *
 * @note The thread name is typically assigned when the thread is created, and it can be used to
 *       identify threads in the system.
 *
 * @warning Ensure that the `name` string is correctly set and unique within the system to avoid
 *          unexpected behavior.
 *
 * @see sys_thread_create(), sys_thread_delete()
 */
rt_thread_t sys_thread_find(char *name)
{
    int len = 0;
    char *kname = RT_NULL;
    rt_thread_t thread;

    len = lwp_user_strlen(name);
    if (len <= 0)
    {
        return RT_NULL;
    }

    kname = (char *)kmem_get(len + 1);
    if (!kname)
    {
        return RT_NULL;
    }

    if (lwp_get_from_user(kname, (void *)name, len + 1) != (len + 1))
    {
        kmem_put(kname);
        return RT_NULL;
    }

    thread = rt_thread_find(name);

    kmem_put(kname);

    return thread;
}

/**
 * @brief Gets the current system tick count.
 *
 * This system call returns the current value of the system tick counter, which is typically incremented
 * at a fixed interval (e.g., every millisecond or microsecond). The tick count can be used for timing
 * purposes, such as measuring the elapsed time or triggering time-based events.
 *
 * @return rt_tick_t    The current value of the system tick counter.
 *
 * @note The system tick counter typically wraps around after reaching its maximum value, so the
 *       returned tick value may reset after a certain period of time, depending on the configuration
 *       of the system tick timer.
 *
 * @warning Be cautious when using the tick value for time-based calculations, as the counter may
 *          overflow and wrap around. Ensure that the code handling the tick count properly accounts
 *          for potential overflow.
 *
 * @see sys_tick_init(), sys_tick_delay()
 */
rt_tick_t sys_tick_get(void)
{
    return rt_tick_get();
}

/**
 * @brief Delays the current thread for a specified number of milliseconds.
 *
 * This system call puts the calling thread to sleep for a given number of milliseconds. It is a blocking
 * call, meaning the thread will not execute any further instructions until the specified delay has
 * passed. The delay is achieved by the system's timer mechanism.
 *
 * @param[in] ms   The number of milliseconds to delay. The value must be a positive integer.
 *
 * @return sysret_t   Returns `0` on success, or a negative error code on failure.
 *
 * @note This function is useful for introducing a fixed delay in time-sensitive applications or when
 *       the thread needs to be paused before continuing execution.
 *
 * @warning Be cautious when using this function in real-time or time-critical applications, as
 *          excessive delays may affect overall system performance or responsiveness.
 *
 * @see sys_thread_delay(), sys_thread_sleep()
 */
sysret_t sys_thread_mdelay(rt_int32_t ms)
{
    return rt_thread_mdelay(ms);
}

struct k_sigaction {
    void (*handler)(int);
    unsigned long flags;
    void (*restorer)(void);
    unsigned mask[2];
};

/**
 * @brief Changes the action taken by the system on receiving a signal.
 *
 * This system call allows a process to specify how signals should be handled. It allows you to set a
 * new action for a specific signal, retrieve the old action, and define the signal mask that should
 * be applied during the execution of the signal handler.
 *
 * @param[in] sig         The signal number for which the action is to be set or retrieved.
 *                        Signal numbers are typically defined as constants (e.g., `SIGINT`, `SIGTERM`).
 * @param[in] act         A pointer to a `k_sigaction` structure that specifies the new action for the signal.
 *                        If `act` is `NULL`, the signal's action is not changed.
 * @param[out] oact       A pointer to a `k_sigaction` structure where the old action will be stored.
 *                        If `oact` is `NULL`, the old action is not retrieved.
 * @param[in] sigsetsize  The size of the `sigset_t` structure used in `k_sigaction`. This is to ensure the
 *                        compatibility with the signal mask size.
 *
 * @return sysret_t      Returns `0` on success or a negative error code on failure.
 *
 * @note The `k_sigaction` structure allows you to specify the signal handler, signal mask, and flags for
 *       the signal action. It is important to correctly configure the handler to prevent unexpected
 *       behavior in the signal handling process.
 *
 * @warning Be cautious when modifying signal handling behavior, as incorrect configuration may result
 *          in unhandled signals or undefined behavior. Signal handlers should be designed to perform
 *          minimal, safe operations.
 *
 * @see sys_signal(), sys_sigprocmask()
 */
sysret_t sys_sigaction(int sig, const struct k_sigaction *act,
                       struct k_sigaction *oact, size_t sigsetsize)
{
    int ret = -RT_EINVAL;
    struct rt_lwp *lwp;
    struct lwp_sigaction kact, *pkact = RT_NULL;
    struct lwp_sigaction koact, *pkoact = RT_NULL;

    if (!sigsetsize)
    {
        SET_ERRNO(EINVAL);
        goto out;
    }
    if (sigsetsize > sizeof(lwp_sigset_t))
    {
        sigsetsize = sizeof(lwp_sigset_t);
    }
    if (!act && !oact)
    {
        SET_ERRNO(EINVAL);
        goto out;
    }
    if (oact)
    {
        if (!lwp_user_accessable((void *)oact, sizeof(*oact)))
        {
            SET_ERRNO(EFAULT);
            goto out;
        }
        pkoact = &koact;
    }
    if (act)
    {
        if (!lwp_user_accessable((void *)act, sizeof(*act)))
        {
            SET_ERRNO(EFAULT);
            goto out;
        }
        kact.sa_flags = act->flags;
        kact.__sa_handler._sa_handler = act->handler;
        lwp_memcpy(&kact.sa_mask, &act->mask, sigsetsize);
        kact.sa_restorer = act->restorer;
        pkact = &kact;
    }

    lwp = lwp_self();
    RT_ASSERT(lwp);
    ret = lwp_signal_action(lwp, sig, pkact, pkoact);
#ifdef ARCH_MM_MMU
    if (ret == 0 && oact)
    {
        lwp_put_to_user(&oact->handler, &pkoact->__sa_handler._sa_handler, sizeof(void (*)(int)));
        lwp_put_to_user(&oact->mask, &pkoact->sa_mask, sigsetsize);
        lwp_put_to_user(&oact->flags, &pkoact->sa_flags, sizeof(int));
        lwp_put_to_user(&oact->restorer, &pkoact->sa_restorer, sizeof(void (*)(void)));
    }
#endif /* ARCH_MM_MMU */
out:
    return (ret < 0 ? GET_ERRNO() : ret);
}

static int mask_command_u2k[] = {
    [SIG_BLOCK] = LWP_SIG_MASK_CMD_BLOCK,
    [SIG_UNBLOCK] = LWP_SIG_MASK_CMD_UNBLOCK,
    [SIG_SETMASK] = LWP_SIG_MASK_CMD_SET_MASK,
};

/**
 * @brief Sets or retrieves the signal mask for the calling process.
 *
 * This system call allows the caller to block or unblock signals by modifying the signal mask. The signal
 * mask determines which signals are blocked and which signals can be delivered to the process. The
 * function can also be used to retrieve the current signal mask.
 *
 * @param[in] how      The action to be taken on the signal mask. It can be one of the following values:
 *                     - `SIG_BLOCK`: Add the signals in `sigset` to the current mask.
 *                     - `SIG_UNBLOCK`: Remove the signals in `sigset` from the current mask.
 *                     - `SIG_SETMASK`: Set the signal mask to the value in `sigset`, replacing the current mask.
 * @param[in] sigset   A pointer to a `sigset_t` structure that specifies the signals to be blocked or unblocked.
 *                     This parameter is ignored when `how` is `SIG_SETMASK`, in which case `sigset` is used
 *                     as the new signal mask.
 * @param[out] oset    A pointer to a `sigset_t` structure where the previous signal mask will be stored.
 *                     If `oset` is `NULL`, the previous signal mask will not be returned.
 * @param[in] size     The size of the `sigset_t` structure, ensuring compatibility with the signal mask.
 *
 * @return sysret_t   Returns `0` on success or a negative error code on failure.
 *
 * @note Modifying the signal mask prevents signals from being delivered to the process while they are blocked.
 *       Once the signals are unblocked, they will be delivered to the process if they are pending.
 *
 * @warning Be careful when blocking signals, especially critical ones like `SIGKILL`, as it may interfere
 *          with the normal operation of the system. Ensure that signal masks are managed carefully to avoid
 *          missing important signals.
 *
 * @see sys_sigaction(), sys_sigpending()
 */
sysret_t sys_sigprocmask(int how, const sigset_t *sigset, sigset_t *oset, size_t size)
{
    int ret = -1;
    lwp_sigset_t *pnewset = RT_NULL, *poldset = RT_NULL;
#ifdef ARCH_MM_MMU
    lwp_sigset_t newset, oldset;
#endif /* ARCH_MM_MMU*/

    if (!size)
    {
        return -EINVAL;
    }
    if (!oset && !sigset)
    {
        return -EINVAL;
    }
    if (size > sizeof(lwp_sigset_t))
    {
        size = sizeof(lwp_sigset_t);
    }
    if (oset)
    {
#ifdef ARCH_MM_MMU
        if (!lwp_user_accessable((void *)oset, size))
        {
            return -EFAULT;
        }
        poldset = &oldset;
#else
        if (!lwp_user_accessable((void *)oset, size))
        {
            return -EFAULT;
        }
        poldset = (lwp_sigset_t *)oset;
#endif
    }
    if (sigset)
    {
#ifdef ARCH_MM_MMU
        if (!lwp_user_accessable((void *)sigset, size))
        {
            return -EFAULT;
        }
        lwp_get_from_user(&newset, (void *)sigset, size);
        pnewset = &newset;
#else
        if (!lwp_user_accessable((void *)sigset, size))
        {
            return -EFAULT;
        }
        pnewset = (lwp_sigset_t *)sigset;
#endif /* ARCH_MM_MMU */
    }
    ret = lwp_thread_signal_mask(rt_thread_self(), mask_command_u2k[how], pnewset, poldset);
#ifdef ARCH_MM_MMU
    if (ret < 0)
    {
        return ret;
    }
    if (oset)
    {
        lwp_put_to_user(oset, poldset, size);
    }
#endif /* ARCH_MM_MMU */
    return (ret < 0 ? -EFAULT: ret);
}

/**
 * @brief Retrieves the set of signals that are pending for delivery to the calling process.
 *
 * This system call allows a process to query the set of signals that are pending, i.e., signals that have
 * been sent to the process but have not yet been delivered because the process is blocking those signals
 * or has not yet handled them. The function returns the set of signals that are waiting to be delivered.
 *
 * @param[out] sigset   A pointer to a `sigset_t` structure where the set of pending signals will be stored.
 *                      The `sigset_t` structure will contain the signals that are pending for delivery.
 * @param[in] sigsize   The size of the `sigset_t` structure, used to ensure compatibility with the signal set.
 *
 * @return sysret_t    Returns `0` on success or a negative error code on failure.
 *
 * @note The returned signal set will contain the signals that have been sent to the process but are blocked,
 *       or that are waiting to be handled. These signals will be delivered once they are unblocked or the
 *       process handles them.
 *
 * @warning Be cautious when querying pending signals, as unblocking too many signals at once may lead
 *          to unexpected behavior or a flood of signal deliveries. It's recommended to carefully manage
 *          the signals the process can accept at any given time.
 *
 * @see sys_sigaction(), sys_sigprocmask()
 */
sysret_t sys_sigpending(sigset_t *sigset, size_t sigsize)
{
    sysret_t ret = 0;
    lwp_sigset_t lwpset;

    /* Verify and Get sigset, timeout */
    if (!sigset || !lwp_user_accessable((void *)sigset, sigsize))
    {
        ret = -EFAULT;
    }
    else
    {
        /* Fit sigset size to lwp set */
        if (sizeof(lwpset) < sigsize)
        {
            LOG_I("%s: sigsize (%lx) extends lwp sigset chunk\n", __func__, sigsize);
            sigsize = sizeof(lwpset);
        }

        lwp_thread_signal_pending(rt_thread_self(), &lwpset);

        if (!lwp_put_to_user(sigset, &lwpset, sigsize))
            RT_ASSERT(0);   /* should never happened */
    }

    return ret;
}

/**
 * @brief Waits for a signal to be delivered, with a timeout.
 *
 * This system call allows a process to wait for one of the signals specified in the `sigset` to be delivered.
 * The process will block until a signal in the set is received or the specified timeout period expires.
 * If the signal is received before the timeout, information about the signal will be returned in the `siginfo_t` structure.
 * If the timeout expires without any signal being delivered, the function will return with an appropriate error code.
 *
 * @param[in] sigset   A pointer to a `sigset_t` structure that specifies the set of signals to wait for.
 *                     The function will block until a signal in this set is received, or the timeout expires.
 * @param[out] info    A pointer to a `siginfo_t` structure where information about the delivered signal will be stored.
 *                     If no signal is received before the timeout, this structure will not be filled.
 * @param[in] timeout  A pointer to a `timespec` structure that specifies the maximum amount of time to wait
 *                     for a signal to be delivered. If this value is `NULL`, the function will wait indefinitely.
 * @param[in] sigsize  The size of the `sigset_t` structure, ensuring compatibility with the signal set.
 *
 * @return sysret_t   Returns `0` on success or a negative error code on failure.
 *
 * @note If the `timeout` is `NULL`, the function will block indefinitely until a signal is delivered.
 *       If a signal is received, the corresponding information is returned in the `siginfo_t` structure.
 *       The `sigset` should contain only the signals you are interested in.
 *
 * @warning If the timeout expires, no signal will be delivered, and the function will return a timeout error.
 *          Make sure to handle the timeout case correctly to prevent any unexpected behavior.
 *
 * @see sys_sigaction(), sys_sigtimedwait()
 */
sysret_t sys_sigtimedwait(const sigset_t *sigset, siginfo_t *info, const struct timespec *timeout, size_t sigsize)
{
    int sig;
    size_t ret;
    lwp_sigset_t lwpset;
    siginfo_t kinfo;
    struct timespec ktimeout;
    struct timespec *ptimeout;

    /* for RT_ASSERT */
    RT_UNUSED(ret);

    /* Fit sigset size to lwp set */
    if (sizeof(lwpset) < sigsize)
    {
        LOG_I("%s: sigsize (%lx) extends lwp sigset chunk\n", __func__, sigsize);
        sigsize = sizeof(lwpset);
    }
    else
    {
        /* if sigset of user is smaller, clear extra space */
        memset(&lwpset, 0, sizeof(lwpset));
    }

    /* Verify and Get sigset, timeout */
    if (!sigset || !lwp_user_accessable((void *)sigset, sigsize))
    {
        return -EFAULT;
    }
    else
    {
        ret = lwp_get_from_user(&lwpset, (void *)sigset, sigsize);
        RT_ASSERT(ret == sigsize);
    }

    if (timeout)
    {
        if (!lwp_user_accessable((void *)timeout, sizeof(*timeout)))
            return -EFAULT;
        else
        {
            ret = lwp_get_from_user(&ktimeout, (void *)timeout, sizeof(*timeout));
            ptimeout = &ktimeout;
            RT_ASSERT(ret == sizeof(*timeout));
        }
    }
    else
    {
        ptimeout = RT_NULL;
    }

    sig = lwp_thread_signal_timedwait(rt_thread_self(), &lwpset, &kinfo, ptimeout);

    if (sig > 0 && info)
    {
        if (!lwp_user_accessable((void *)info, sizeof(*info)))
            return -EFAULT;
        else
        {
            ret = lwp_put_to_user(info, &kinfo, sizeof(*info));
            RT_ASSERT(ret == sizeof(*info));
        }
    }

    return sig;
}

/**
 * @brief Sends a signal to a specific thread.
 *
 * This system call allows a process to send a signal to a specific thread within the same process.
 * The signal specified by the `sig` parameter will be delivered to the thread with the ID `tid`.
 * This function is similar to `kill()`, but it targets a specific thread rather than a process.
 *
 * @param[in] tid   The thread ID to which the signal will be sent. This ID identifies the target thread within the same process.
 * @param[in] sig   The signal number to be sent to the specified thread. The signal can be any valid signal number.
 *
 * @return sysret_t Returns `0` on success or a negative error code on failure.
 *
 * @note The `sig` parameter must be a valid signal number. It can range from `1` to `31`, or be one of the predefined signal constants like `SIGKILL`, `SIGTERM`, etc.
 *       If the target thread does not exist or is not eligible to receive the signal, the function will fail.
 *
 * @warning If an invalid signal number is provided or the target thread does not exist, an error will be returned.
 *          Be careful when sending signals, as some signals (e.g., `SIGKILL`) can immediately terminate the target thread.
 *
 * @see sys_kill(), sys_sigaction()
 */
sysret_t sys_tkill(int tid, int sig)
{
#ifdef ARCH_MM_MMU
    rt_thread_t thread;
    sysret_t ret;

    /**
     * Brief: Match a tid and do the kill
     *
     * Note: Critical Section
     * - the thread (READ. may be released at the meantime; protected by locked)
     */
    thread = lwp_tid_get_thread_and_inc_ref(tid);
    ret = lwp_thread_signal_kill(thread, sig, SI_USER, 0);
    lwp_tid_dec_ref(thread);

    return ret;
#else
    return lwp_thread_kill((rt_thread_t)tid, sig);
#endif
}

/**
 * @brief Manipulates the signal mask for the current thread.
 *
 * This function allows a thread to modify its signal mask, which controls which signals are blocked (prevented from delivery).
 * The signal mask can be modified by adding, removing, or setting the signal set as a whole, depending on the `how` parameter.
 * The `sigset` specifies the signals to be manipulated, and the current signal mask before modification can be retrieved in `oset`.
 *
 * @param[in] how     The operation to perform on the signal mask. It can be one of the following values:
 *                    - `SIG_BLOCK`: Add the signals in `sigset` to the current mask (block those signals).
 *                    - `SIG_UNBLOCK`: Remove the signals in `sigset` from the current mask (unblock those signals).
 *                    - `SIG_SETMASK`: Set the signal mask to the signals specified in `sigset` (replace the current mask).
 * @param[in] sigset  A pointer to an `lwp_sigset_t` structure that specifies the set of signals to be manipulated.
 *                    Signals in this set will be added, removed, or set in the current thread's signal mask based on the `how` parameter.
 * @param[out] oset   A pointer to an `lwp_sigset_t` structure where the previous signal mask will be stored.
 *                    This allows the caller to restore the previous mask if needed.
 * @param[in] size    The size of the `lwp_sigset_t` structure. This ensures that the correct structure size is used during signal mask manipulation.
 *
 * @return sysret_t   Returns `0` on success or a negative error code on failure.
 *
 * @note The `sigset` structure should contain only valid signal numbers. If `how` is `SIG_SETMASK`, the entire signal mask will be replaced by the contents of `sigset`.
 *       If `how` is `SIG_BLOCK` or `SIG_UNBLOCK`, the signals in `sigset` will be added or removed from the current mask, respectively.
 *
 * @warning Be cautious when modifying the signal mask, as blocking signals can cause the thread to miss important signals.
 *          If a signal is blocked, it will not be delivered to the thread until it is unblocked, or the thread is explicitly made to handle it.
 *
 * @see sys_sigaction(), sys_thread_sigpending()
 */
sysret_t sys_thread_sigprocmask(int how, const lwp_sigset_t *sigset, lwp_sigset_t *oset, size_t size)
{
    int ret = -1;
    lwp_sigset_t *pnewset = RT_NULL, *poldset = RT_NULL;
#ifdef ARCH_MM_MMU
    lwp_sigset_t newset, oldset;
#endif /* ARCH_MM_MMU */

    if (!size)
    {
        return -EINVAL;
    }
    if (!oset && !sigset)
    {
        return -EINVAL;
    }
    if (size != sizeof(lwp_sigset_t))
    {
        return -EINVAL;
    }
    if (oset)
    {
#ifdef ARCH_MM_MMU
        if (!lwp_user_accessable((void *)oset, size))
        {
            return -EFAULT;
        }
        poldset = &oldset;
#else
        if (!lwp_user_accessable((void *)oset, size))
        {
            return -EFAULT;
        }
        poldset = oset;
#endif
    }
    if (sigset)
    {
#ifdef ARCH_MM_MMU
        if (!lwp_user_accessable((void *)sigset, size))
        {
            return -EFAULT;
        }
        lwp_get_from_user(&newset, (void *)sigset, sizeof(lwp_sigset_t));
        pnewset = &newset;
#else
        if (!lwp_user_accessable((void *)sigset, size))
        {
            return -EFAULT;
        }
        pnewset = (lwp_sigset_t *)sigset;
#endif
    }
    ret = lwp_thread_signal_mask(rt_thread_self(), mask_command_u2k[how], pnewset, poldset);
    if (ret < 0)
    {
        return ret;
    }
#ifdef ARCH_MM_MMU
    if (oset)
    {
        lwp_put_to_user(oset, poldset, sizeof(lwp_sigset_t));
    }
#endif
    return (ret < 0 ? -EFAULT: ret);
}

#ifndef ARCH_MM_MMU

/**
 * @brief Sets the signal handler for a specific signal in the current thread.
 *
 * This function allows a thread to set a custom signal handler for a specific signal.
 * When the specified signal is received, the corresponding handler function (`func`) will be invoked.
 * The handler will be executed in the context of the current thread, allowing it to handle signals as needed.
 *
 * @param[in] sig    The signal number for which the handler is being set. This should be a valid signal number.
 * @param[in] func   The signal handler function to be set. This function will be called when the specified signal is received.
 *                   The signature of `func` should match the expected format for signal handlers.
 *
 * @return sysret_t  Returns `0` on success or a negative error code on failure.
 *
 * @note The `func` parameter must be a valid function pointer. It will be called when the signal specified by `sig` is received by the thread.
 *       The handler function typically has the signature: `void handler(int sig)`, where `sig` is the signal number.
 *
 * @warning Setting a custom signal handler may override any default actions for that signal.
 *          It is important to ensure that the handler function is properly designed to handle the signal appropriately.
 *          For example, some signals may require special handling (e.g., `SIGKILL` cannot be caught).
 *
 * @see sys_signal(), sys_lwp_sigaction()
 */
sysret_t sys_lwp_sighandler_set(int sig, lwp_sighandler_t func)
{
    if (!lwp_user_accessable((void *)func, sizeof(lwp_sighandler_t)))
    {
        return -EFAULT;
    }

    lwp_sighandler_set(sig, func);
    return 0;
}

/**
 * @brief Sets the signal handler for a specific signal in the target thread.
 *
 * This function allows setting a custom signal handler for a specific signal within a particular thread.
 * When the specified signal is delivered to the thread, the corresponding handler function (`func`) will be invoked.
 * The handler is executed in the context of the thread that receives the signal.
 *
 * @param[in] sig    The signal number for which the handler is being set. This should be a valid signal number.
 * @param[in] func   The signal handler function to be set. This function will be called when the specified signal is delivered to the target thread.
 *                   The handler function should have the signature `void func(int sig)`.
 *
 * @return sysret_t  Returns `0` on success or a negative error code on failure.
 *
 * @note The `func` parameter must be a valid function pointer, and it will be invoked when the signal specified by `sig` is delivered to the target thread.
 *       The handler function typically has the signature: `void handler(int sig)`, where `sig` is the signal number.
 *
 * @warning Setting a custom signal handler may override any default actions for that signal.
 *          It is important to ensure that the handler function is properly designed to handle the signal appropriately.
 *          For example, some signals may require special handling (e.g., `SIGKILL` cannot be caught).
 *
 * @see sys_thread_sigprocmask(), sys_thread_sigaction(), sys_signal()
 */
sysret_t sys_thread_sighandler_set(int sig, lwp_sighandler_t func)
{
    if (!lwp_user_accessable((void *)func, sizeof(lwp_sighandler_t)))
    {
        return -EFAULT;
    }

    lwp_thread_sighandler_set(sig, func);
    return 0;
}
#endif /* not defined ARCH_MM_MMU */

/**
 * @brief Waits for the termination of a child process.
 *
 * This function makes the calling process wait until one of its child processes terminates or until a
 * specified condition is met. The function retrieves information about the terminated child process,
 * including its exit status, and can also handle other process-related events, such as stopping or
 * continuing execution.
 *
 * @param[in] pid     The process ID of the child process to wait for. If `pid` is:
 *                    - `-1`: Wait for any child process.
 *                    - `0`: Wait for any child process in the same process group.
 *                    - > 0: Wait for the child process with the specified process ID.
 * @param[out] status A pointer to an integer where the exit status of the terminated child process will be stored.
 *                    This value provides information about the child's termination status, such as normal exit,
 *                    signal termination, etc.
 * @param[in] options A bitmask of options that control the behavior of the function. It can include:
 *                    - `WNOHANG`: Return immediately if no child has exited.
 *                    - `WUNTRACED`: Report status of stopped child processes.
 *                    - Other flags can be defined depending on the implementation.
 *
 * @return sysret_t  Returns the process ID of the child process that terminated on success, or a negative error code on failure.
 *
 * @note The `status` argument provides detailed information about the termination of the child process. To interpret this
 *       status, macros such as `WIFEXITED()`, `WIFSIGNALED()`, and `WEXITSTATUS()` are commonly used.
 *
 * @warning This function should be used carefully when managing child processes, as not properly handling child processes
 *          may lead to zombie processes.
 *
 * @see sys_wait(), sys_waitid()
 */
sysret_t sys_waitpid(int32_t pid, int *status, int options)
{
    int ret = -1;
#ifdef ARCH_MM_MMU
    if (!lwp_user_accessable((void *)status, sizeof(int)))
    {
        return -EFAULT;
    }
    else
    {
        ret = lwp_waitpid(pid, status, options, RT_NULL);
    }
#else
    if (!lwp_user_accessable((void *)status, sizeof(int)))
    {
        return -EFAULT;
    }
    ret = waitpid(pid, status, options);
#endif
    return ret;
}

#if defined(RT_USING_SAL) && defined(SAL_USING_POSIX)
struct musl_addrinfo
{
    int ai_flags;
    int ai_family;
    int ai_socktype;
    int ai_protocol;
    socklen_t ai_addrlen;

    struct musl_sockaddr *ai_addr;
    char *ai_canonname;

    struct musl_addrinfo *ai_next;
};

/**
 * @brief Resolves network addresses and service names into a list of address structures.
 *
 * This function provides a mechanism for resolving a host name and service name (or port number)
 * into a list of address structures suitable for use with socket-based communication. The function
 * can handle both IPv4 and IPv6 addresses and provides a flexible way to specify different types
 * of address and service resolution options.
 *
 * @param[in] nodename  The host name to be resolved. This can be a DNS name or an IP address in string format.
 *                      If `nodename` is `NULL`, the function will resolve the local host.
 * @param[in] servname  The service name (e.g., "http") or port number to be resolved. If `servname` is `NULL`,
 *                      the function will resolve the port number or address without any service association.
 * @param[in] hints     A pointer to a `struct musl_addrinfo` that provides hints for the address resolution.
 *                      It can be used to specify criteria such as the desired address family (IPv4 or IPv6),
 *                      socket type, protocol, and flags for resolution.
 * @param[out] res      A pointer to a `struct musl_addrinfo` that will be filled with the resolved address
 *                      information. The resulting linked list will contain one or more `struct musl_sockaddr`
 *                      structures, each representing a different address that can be used for communication.
 *
 * @return sysret_t     Returns `0` on success, indicating that the address resolution was successful.
 *                       On failure, returns a negative error code.
 *
 * @note The `res` parameter points to a linked list of resolved address structures. Each node in the list
 *       contains a different resolved address and can be used for socket connection purposes.
 *       It is important to free the memory allocated for the list after it is no longer needed, using `freeaddrinfo()`.
 *
 * @warning The `hints` structure allows you to specify various options for the resolution. However, incorrect
 *          hints may lead to unexpected or incorrect results. For example, if you request IPv6 addresses but
 *          the host only supports IPv4, the function may not return the expected results.
 *
 * @see freeaddrinfo(), sys_socket(), sys_connect(), sys_gethostbyname(), sys_gethostbyaddr()
 */
sysret_t sys_getaddrinfo(const char *nodename,
        const char *servname,
        const struct musl_addrinfo *hints,
        struct musl_addrinfo *res)
{
    int ret = -1;
    struct addrinfo *k_res = NULL;
    char *k_nodename = NULL;
    char *k_servname = NULL;
    struct addrinfo *k_hints = NULL;
#ifdef ARCH_MM_MMU
    int len = 0;
#endif

#ifdef ARCH_MM_MMU
    if (!lwp_user_accessable((void *)res, sizeof(*res)))
    {
        SET_ERRNO(EFAULT);
        goto exit;
    }
#endif
    if (nodename)
    {
#ifdef ARCH_MM_MMU
        len = lwp_user_strlen(nodename);
        if (len <= 0)
        {
            SET_ERRNO(EFAULT);
            goto exit;
        }

        k_nodename = (char *)kmem_get(len + 1);
        if (!k_nodename)
        {
            SET_ERRNO(ENOMEM);
            goto exit;
        }

        if (lwp_get_from_user(k_nodename, (void *)nodename, len + 1) != len + 1)
        {
            SET_ERRNO(EFAULT);
            goto exit;
        }
#else
        k_nodename = rt_strdup(nodename);
        if (!k_nodename)
        {
            SET_ERRNO(ENOMEM);
            goto exit;
        }
#endif
    }
    if (servname)
    {
#ifdef ARCH_MM_MMU
        len = lwp_user_strlen(servname);
        if (len <= 0)
        {
            SET_ERRNO(EFAULT);
            goto exit;
        }

        k_servname = (char *)kmem_get(len + 1);
        if (!k_servname)
        {
            SET_ERRNO(ENOMEM);
            goto exit;
        }

        if (lwp_get_from_user(k_servname, (void *)servname, len + 1) < 0)
        {
            SET_ERRNO(EFAULT);
            goto exit;
        }
#else
        k_servname = rt_strdup(servname);
        if (!k_servname)
        {
            SET_ERRNO(ENOMEM);
            goto exit;
        }
#endif
    }

    if (hints)
    {
#ifdef ARCH_MM_MMU
        if (!lwp_user_accessable((void *)hints, sizeof(*hints)))
        {
            SET_ERRNO(EFAULT);
            goto exit;
        }
#endif
        k_hints = (struct addrinfo *) rt_malloc(sizeof *hints);
        if (!k_hints)
        {
            SET_ERRNO(ENOMEM);
            goto exit;
        }

        rt_memset(k_hints, 0x0, sizeof(struct addrinfo));
        k_hints->ai_flags    = hints->ai_flags;
        k_hints->ai_family   = hints->ai_family;
        k_hints->ai_socktype = hints->ai_socktype;
        k_hints->ai_protocol = hints->ai_protocol;
        k_hints->ai_addrlen  = hints->ai_addrlen;
    }

    ret = sal_getaddrinfo(k_nodename, k_servname, k_hints, &k_res);
    if (ret == 0)
    {
        /* set sockaddr */
        sockaddr_tomusl(k_res->ai_addr, res->ai_addr);
        res->ai_addrlen = k_res->ai_addrlen;

        /* set up addrinfo */
        res->ai_family = k_res->ai_family;
        res->ai_flags  = k_res->ai_flags;
        res->ai_next = NULL;

        if (hints != NULL)
        {
            /* copy socktype & protocol from hints if specified */
            res->ai_socktype = hints->ai_socktype;
            res->ai_protocol = hints->ai_protocol;
        }

        sal_freeaddrinfo(k_res);
        k_res = NULL;
    }

exit:
    if (ret < 0)
    {
        ret = GET_ERRNO();
    }
#ifdef ARCH_MM_MMU
    if (k_nodename)
    {
        kmem_put(k_nodename);
    }
#else
    if (k_nodename)
    {
        rt_free(k_nodename);
    }
#endif
#ifdef ARCH_MM_MMU
    if (k_servname)
    {
        kmem_put(k_servname);
    }
#else
    if (k_servname)
    {
        rt_free(k_servname);
    }
#endif
    if (k_hints)
    {
        rt_free(k_hints);
    }

    return ret;
}

#define HOSTENT_BUFSZ   512

/**
 * @brief Resolves a host name to an address, with support for specifying the address family.
 *
 * This function performs a lookup of the specified host name, and resolves it to an address,
 * while allowing the caller to specify the desired address family (e.g., IPv4 or IPv6). It is
 * a reentrant version of `gethostbyname2`, meaning it is safe for use in multi-threaded applications.
 * The results are returned in a user-provided buffer to avoid memory allocation overhead.
 *
 * @param[in] name      The host name to be resolved. This can be a DNS name or an IP address in string format.
 * @param[in] af        The address family to use for the resolution. Common values are:
 *                      - `AF_INET` for IPv4 addresses.
 *                      - `AF_INET6` for IPv6 addresses.
 * @param[out] ret      A pointer to a `struct hostent` where the resolved host information will be stored.
 *                      This includes the host name, alias names, address type, and the address itself.
 * @param[in] buf       A buffer to store additional information required for the `struct hostent` structure.
 *                      This is needed to ensure the reentrant behavior and avoid memory allocation.
 * @param[in] buflen    The size of the buffer provided.
 * @param[out] result   A pointer to a `struct hostent*` that will point to the resolved host entry.
 *                      This will be set to the value of `ret` upon success.
 * @param[out] err      A pointer to an integer where error codes will be stored. If the function fails,
 *                      `err` will contain a non-zero value corresponding to the error.
 *
 * @return sysret_t     Returns `0` on success, indicating the resolution was successful.
 *                       On failure, returns a negative error code that indicates the failure reason.
 *
 * @note This function is reentrant and thread-safe, meaning it does not use static memory or global state.
 *       It relies on the buffers provided by the caller to store the resolved data.
 *
 * @see gethostbyname2(), sys_gethostbyname(), sys_socket(), sys_connect(), sys_getaddrinfo()
 */
sysret_t sys_gethostbyname2_r(const char *name, int af, struct hostent *ret,
        char *buf, size_t buflen,
        struct hostent **result, int *err)
{
    int ret_val = -1;
    int sal_ret = -1 , sal_err = -1;
    struct hostent sal_he, sal_tmp;
    struct hostent *sal_result = NULL;
    char *sal_buf = NULL;
    char *k_name  = NULL;
    int len = 0;

#ifdef ARCH_MM_MMU
    if (!lwp_user_accessable((void *)err, sizeof(*err)))
    {
        SET_ERRNO(EFAULT);
        goto __exit;
    }

    if (!lwp_user_accessable((void *)result, sizeof(*result))
    || !lwp_user_accessable((void *)ret, sizeof(*ret))
    || !lwp_user_accessable((void *)buf, buflen))
    {
        /* not all arguments given */
        *err = EFAULT;
        SET_ERRNO(EFAULT);
        goto __exit;
    }

    len = lwp_user_strlen(name);
    if (len <= 0)
    {
        *err = EFAULT;
        SET_ERRNO(EFAULT);
        goto __exit;
    }

    k_name = (char *)kmem_get(len + 1);
    if (!k_name)
    {
        SET_ERRNO(ENOMEM);
        goto __exit;
    }

    if (lwp_get_from_user(k_name, (void *)name, len + 1) < 0)
    {
        SET_ERRNO(EFAULT);
        goto __exit;
    }
#else
    k_name = rt_strdup(name);
    if (k_name == NULL)
    {
        SET_ERRNO(ENOMEM);
        goto __exit;
    }
#endif

    *result = ret;
    sal_buf = (char *)malloc(HOSTENT_BUFSZ);
    if (sal_buf == NULL)
    {
        SET_ERRNO(ENOMEM);
        goto __exit;
    }

    /* get host by name in SAL */
    sal_ret = sal_gethostbyname_r(k_name, &sal_he, sal_buf, HOSTENT_BUFSZ, &sal_result, &sal_err);
    if (sal_ret == 0)
    {
        int index = 0, cnt = 0;
        char *ptr = buf;

        /* get counter */
        index = 0;
        while (sal_he.h_addr_list[index] != NULL)
        {
            index++;
        }
        cnt = index + 1;

#ifdef ARCH_MM_MMU
        /* update user space hostent */
        lwp_put_to_user(buf, k_name, buflen - (ptr - buf));
        lwp_memcpy(&sal_tmp, &sal_he, sizeof(sal_he));
        sal_tmp.h_name = ptr;
        ptr += rt_strlen(k_name);

        sal_tmp.h_addr_list = (char**)ptr;
        ptr += cnt * sizeof(char *);

        index = 0;
        while (sal_he.h_addr_list[index] != NULL)
        {
            sal_tmp.h_addr_list[index] = ptr;
            lwp_memcpy(ptr, sal_he.h_addr_list[index], sal_he.h_length);

            ptr += sal_he.h_length;
            index++;
        }
        sal_tmp.h_addr_list[index] = NULL;
        lwp_put_to_user(ret, &sal_tmp, sizeof(sal_tmp));
#else
        /* update user space hostent */
        ret->h_addrtype = sal_he.h_addrtype;
        ret->h_length   = sal_he.h_length;

        rt_strncpy(ptr, k_name, buflen - (ptr - buf));
        ret->h_name = ptr;
        ptr += strlen(k_name);

        ret->h_addr_list = (char**)ptr;
        ptr += cnt * sizeof(char *);

        index = 0;
        while (sal_he.h_addr_list[index] != NULL)
        {
            ret->h_addr_list[index] = ptr;
            lwp_memcpy(ptr, sal_he.h_addr_list[index], sal_he.h_length);

            ptr += sal_he.h_length;
            index++;
        }
        ret->h_addr_list[index] = NULL;
#endif
        ret_val = 0;
    }
    else
    {
        SET_ERRNO(EINVAL);
    }

__exit:
    if (ret_val < 0)
    {
        ret_val = GET_ERRNO();
    }

    /* release buffer */
    if (sal_buf)
    {
        free(sal_buf);
    }
#ifdef ARCH_MM_MMU
    if (k_name)
    {
        kmem_put(k_name);
    }
#else
    if (k_name)
    {
        free(k_name);
    }
#endif

    return ret_val;
}
#endif

/**
 * @brief Gets the current working directory.
 *
 * This function retrieves the absolute pathname of the current working directory
 * and stores it in the provided buffer. The buffer must be large enough to hold
 * the directory path, including the null-terminator. If the buffer is too small,
 * the function will return an error.
 *
 * @param[out] buf     A pointer to a buffer where the current working directory
 *                     path will be stored. The buffer should be large enough
 *                     to hold the path, including the null-terminator.
 * @param[in] size     The size of the buffer in bytes. The buffer must be large enough
 *                     to accommodate the full path.
 *
 * @return long        On success, returns the number of bytes written to the buffer
 *                     (not including the null-terminator). If the buffer is not large
 *                     enough, returns a negative error code.
 *
 * @note The maximum path length depends on the system's configuration.
 *       Ensure the buffer size is sufficient to hold the entire path.
 *
 * @see sys_chdir(), sys_getcwd_r(), sys_realpath()
 */
long sys_getcwd(char *buf, size_t size)
{
    char *tmp = RT_NULL;
    long ret = -1;

    if (!lwp_user_accessable((void *)buf, size))
    {
        return ret;
    }

    tmp = (char *)rt_malloc(size);
    if (!tmp)
    {
        return ret;
    }

    if (getcwd(tmp, size) != RT_NULL)
    {
        if (lwp_put_to_user(buf, tmp, size) > 0)
        {
            if (buf != RT_NULL)
                ret = strlen(buf);
            else
                ret = -EFAULT;
        }
    }

    rt_free(tmp);

    return ret;
}

/**
 * @brief Changes the current working directory.
 *
 * This function changes the current working directory of the calling process
 * to the directory specified by the given path. The path can be absolute or
 * relative. If the specified path does not exist or the process does not have
 * sufficient permissions, the function will return an error.
 *
 * @param[in] path     The path to the new working directory. This can be either
 *                     an absolute or a relative path.
 *
 * @return sysret_t    Returns `0` on success, indicating that the working
 *                     directory was successfully changed. On failure, returns a
 *                     negative error code indicating the reason for failure.
 *
 * @note If the specified path is a relative path, it is interpreted relative
 *       to the current working directory.
 *
 * @see sys_getcwd(), sys_chdir() for changing directories, sys_opendir(), sys_stat()
 */
sysret_t sys_chdir(const char *path)
{
#ifdef ARCH_MM_MMU
    int err = 0;
    int len = 0;
    int errcode;
    char *kpath = RT_NULL;

    len = lwp_user_strlen(path);
    if (len <= 0)
    {
        return -EFAULT;
    }

    kpath = (char *)kmem_get(len + 1);
    if (!kpath)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(kpath, (void *)path, len + 1) != (len + 1))
    {
        kmem_put(kpath);
        return -EINVAL;
    }

    err = chdir(kpath);
    errcode = err != 0 ? GET_ERRNO() : 0;

    kmem_put(kpath);

    return errcode;
#else
    int ret = chdir(path);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Changes the current working directory to the one associated with the specified file descriptor.
 *
 * This function changes the current working directory of the calling process
 * to the directory associated with the file descriptor `fd`. The file descriptor
 * should refer to an open directory. If the file descriptor does not refer to a
 * directory, or if the process lacks the necessary permissions, the function will
 * return an error.
 *
 * @param[in] fd   The file descriptor referring to the directory to which the current
 *                 working directory should be changed.
 *
 * @return sysret_t    Returns `0` on success, indicating the current working directory
 *                     was successfully changed. On failure, returns a negative error code.
 *
 * @note The file descriptor must refer to a directory. If it refers to a file or other
 *       non-directory object, the operation will fail.
 *
 * @see sys_chdir(), sys_getcwd(), sys_opendir(), sys_open()
 */
sysret_t sys_fchdir(int fd)
{
    int errcode = -ENOSYS;
#ifdef ARCH_MM_MMU
#ifdef RT_USING_DFS_V2
    int err = -1;
    struct dfs_file *d;
    char *kpath;

    d = fd_get(fd);
    if (!d || !d->vnode)
    {
        return -EBADF;
    }
    kpath = dfs_dentry_full_path(d->dentry);
    if (!kpath)
    {
        return -EACCES;
    }

    err = chdir(kpath);
    errcode = err != 0 ? GET_ERRNO() : 0;

    kmem_put(kpath);
#endif
#endif
    return errcode;
}

/**
 * @brief Creates a new directory with the specified path and mode.
 *
 * This function creates a new directory with the specified path and mode.
 * The directory is created with the permissions specified by the `mode` parameter.
 * If the directory already exists, the function will return an error.
 *
 * @param[in] path     The path of the directory to be created. This can be an absolute
 *                     or relative path. If the directory does not exist, it will be created.
 * @param[in] mode     The permissions to be set for the new directory. This parameter
 *                     specifies the access permissions for the directory owner, group, and others.
 *
 * @return sysret_t    Returns `0` on success, indicating that the directory was successfully
 *                     created. On failure, returns a negative error code indicating the reason for failure.
 *
 * @note The `mode` parameter specifies the permissions for the new directory. The permissions
 *       are typically specified using the `S_IRWXU`, `S_IRWXG`, and `S_IRWXO` macros, which
 *       define the read, write, and execute permissions for the owner, group, and others.
 *
 * @see sys_rmdir(), sys_chdir(), sys_mkdirat()
 */
sysret_t sys_mkdir(const char *path, mode_t mode)
{
#ifdef ARCH_MM_MMU
    int err = 0;
    int len = 0;
    char *kpath = RT_NULL;

    len = lwp_user_strlen(path);
    if (len <= 0)
    {
        return -EFAULT;
    }

    kpath = (char *)kmem_get(len + 1);
    if (!kpath)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(kpath, (void *)path, len + 1) != (len + 1))
    {
        kmem_put(kpath);
        return -EINVAL;
    }

    err = _SYS_WRAP(mkdir(kpath, mode));

    kmem_put(kpath);

    return err;
#else
    int ret = mkdir(path, mode);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Removes the specified directory.
 *
 * This function removes the directory specified by the given path. The directory
 * must be empty for the operation to succeed. If the directory is not empty, the
 * function will return an error. If the directory does not exist or the process
 * lacks the necessary permissions, the function will also return an error.
 *
 * @param[in] path     The path of the directory to be removed. This can be an absolute
 *                     or relative path. The directory must be empty for the operation to succeed.
 *
 * @return sysret_t    Returns `0` on success, indicating that the directory was successfully
 *                     removed. On failure, returns a negative error code indicating the reason for failure.
 *
 * @note The directory must be empty for the operation to succeed. If the directory contains
 *       files or subdirectories, the operation will fail. To remove a non-empty directory,
 *       the contents must be deleted first.
 *
 * @see sys_mkdir(), sys_chdir(), sys_rmdirat()
 */
sysret_t sys_rmdir(const char *path)
{
    int err = 0;
    int ret = 0;
#ifdef ARCH_MM_MMU
    int len = 0;
    char *kpath = RT_NULL;

    len = lwp_user_strlen(path);
    if (len <= 0)
    {
        return -EFAULT;
    }

    kpath = (char *)kmem_get(len + 1);
    if (!kpath)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(kpath, (void *)path, len + 1) != (len + 1))
    {
        kmem_put(kpath);
        return -EINVAL;
    }

    ret = rmdir(kpath);
    if(ret < 0)
    {
        err = GET_ERRNO();
    }

    kmem_put(kpath);

    return (err < 0 ? err : ret);
#else
    ret = rmdir(path);
    if(ret < 0)
    {
        err = GET_ERRNO();
    }
    return (err < 0 ? err : ret);
#endif
}

/**
 * @brief Reads directory entries.
 *
 * This function reads the directory entries from the directory stream specified by the file descriptor `fd`.
 * It stores the directory entries in the buffer pointed to by `dirp`, up to the specified number of bytes (`nbytes`).
 * The entries are returned in a format compatible with the `struct libc_dirent` structure.
 *
 * @param[in] fd      The file descriptor referring to an open directory. This descriptor must be obtained
 *                    from a call to `sys_open()` with the appropriate flags for directory reading.
 * @param[out] dirp   A pointer to a buffer where the directory entries will be stored.
 *                    The buffer must be large enough to hold at least `nbytes` bytes of directory entries.
 * @param[in] nbytes  The size of the buffer (`dirp`) in bytes. It limits the number of directory entries
 *                    that can be read in a single call. The function will return as many entries as possible
 *                    that fit within the buffer size.
 *
 * @return sysret_t   Returns the number of bytes read on success, which may be less than `nbytes` if there
 *                     are fewer entries in the directory or if the buffer is too small.
 *                     On failure, returns a negative error code.
 *
 * @note If the function returns 0, it indicates the end of the directory stream. A negative return value
 *       indicates an error. The caller can use the returned number of bytes to process the entries in `dirp`.
 *
 * @see sys_open(), sys_close(), sys_readdir(), sys_stat()
 */
sysret_t sys_getdents(int fd, struct libc_dirent *dirp, size_t nbytes)
{
    int ret = -1;
    struct dfs_file *file;
    size_t cnt = (nbytes / sizeof(struct libc_dirent));
    size_t rtt_nbytes = 0;
    struct dirent *rtt_dirp;

#ifdef ARCH_MM_MMU
    if (!lwp_user_accessable((void *)dirp, sizeof(struct libc_dirent)))
    {
        return -EFAULT;
    }
#endif

    if (cnt == 0)
    {
        return -EINVAL;
    }
    rtt_nbytes = cnt * sizeof(struct dirent);
    rtt_dirp = (struct dirent *)rt_malloc(rtt_nbytes);
    if (!rtt_dirp)
    {
        return -ENOMEM;
    }
    file = fd_get(fd);
    ret = dfs_file_getdents(file, rtt_dirp, rtt_nbytes);
    if (ret > 0)
    {
        size_t i = 0;
        cnt = ret / sizeof(struct dirent);
        for (i = 0; i < cnt; i++)
        {
            dirp[i].d_ino = 0;
            dirp[i].d_off = i*sizeof(struct libc_dirent);
            dirp[i].d_type = rtt_dirp[i].d_type;
            dirp[i].d_reclen = sizeof(struct libc_dirent);
            strcpy(dirp[i].d_name, rtt_dirp[i].d_name);
        }
        ret = cnt * sizeof(struct libc_dirent);
    }

    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    rt_free(rtt_dirp);

    return ret;
}

/**
 * @brief Retrieves the current value of the error code.
 *
 * This function returns the most recent error code set by a system call. The error code is typically set
 * when a system call fails. This function allows users to retrieve the last error that occurred, helping to
 * diagnose issues or handle errors in a more controlled manner.
 *
 * @return sysret_t  The current error code. A value of `0` indicates no error, while a non-zero value
 *                   represents the most recent error. The error codes are system-specific and can
 *                   represent various failure conditions (e.g., `EINVAL`, `ENOMEM`, `EIO`).
 *
 * @note The error code returned is specific to the current thread or process and is typically updated
 *       each time a system call fails. The error code is persistent until it is overwritten by the next
 *       failed system call or explicitly reset.
 *
 * @see sys_set_errno(), sys_perror(), sys_strerror()
 */
sysret_t sys_get_errno(void)
{
    return rt_get_errno();
}

#ifdef ARCH_MM_MMU

/**
 * @brief Sets the thread-specific data area.
 *
 * This function is used to associate a specific area of memory with the current thread. The area pointed to
 * by `p` is set as the thread's local storage. Thread-specific data is used to store data that is unique to
 * each thread, allowing different threads to maintain independent state information.
 *
 * @param[in] p  A pointer to the memory area that is to be set as the thread's local storage. This area
 *               will be used by the thread to store its specific data. The structure and size of the data
 *               area depend on the implementation and use case.
 *
 * @return sysret_t   Returns `0` on success. On failure, it returns a negative error code.
 *
 * @note This function is typically used to set up thread-specific storage for managing data that should
 *       not be shared between threads. The data area is accessible only by the thread that set it, ensuring
 *       thread safety for the stored information.
 *
 * @see sys_get_thread_area(), sys_thread_create(), sys_thread_self()
 */
sysret_t sys_set_thread_area(void *p)
{
    rt_thread_t thread;

    thread = rt_thread_self();
    thread->thread_idr = p;
    arch_set_thread_area(p);

    return 0;
}

/**
 * @brief Sets the address at which the thread ID is stored.
 *
 * This function sets the address of a variable that will store the thread ID for the calling thread.
 * The specified address `tidptr` will hold the thread's unique identifier. This can be useful for
 * managing thread-specific state or for synchronization mechanisms where the thread's ID needs to be
 * shared or checked by other parts of the system.
 *
 * @param[in] tidptr  A pointer to an integer where the thread ID will be stored. This value will
 *                    hold the calling thread's ID, and it can be accessed to identify the thread
 *                    later. The value of the thread ID can be used in various thread management
 *                    operations.
 *
 * @return sysret_t   Returns `0` on success. On failure, returns a negative error code.
 *
 * @note This function is typically used in systems that require associating a specific address with the
 *       thread ID, often in real-time or embedded systems where managing and accessing thread IDs is
 *       crucial for scheduling or resource allocation.
 *
 * @see sys_get_tid(), sys_thread_self(), sys_thread_create()
 */
sysret_t sys_set_tid_address(int *tidptr)
{
    rt_thread_t thread;

#ifdef ARCH_MM_MMU
    if (!lwp_user_accessable((void *)tidptr, sizeof(int)))
    {
        return -EFAULT;
    }
#endif
    thread = rt_thread_self();
    thread->clear_child_tid = tidptr;
    return thread->tid;
}
#endif /* ARCH_MM_MMU */

/**
 * @brief Gets the thread ID of the calling thread.
 *
 * This function returns the unique thread identifier (thread ID) for the calling thread. The thread ID
 * can be used to uniquely identify the thread within the system and is typically used for debugging,
 * thread management, or scheduling purposes.
 *
 * @return sysret_t   The thread ID of the calling thread. The value is typically a positive integer
 *                     representing the unique ID assigned to the thread. In case of failure, an error code
 *                     may be returned.
 *
 * @note The thread ID returned by this function is unique within the system, and it may be used to
 *       reference or manipulate the specific thread associated with the ID.
 *
 * @see sys_set_tid_address(), sys_thread_self(), sys_thread_create()
 */
sysret_t sys_gettid(void)
{
    return rt_thread_self()->tid;
}

/**
 * @brief Checks the accessibility of a file or directory.
 *
 * This function checks whether the calling process has the specified access rights for the given file or directory.
 * The check is performed based on the provided `mode`, which can indicate whether read, write, or execute permissions
 * are required.
 *
 * @param[in] filename  The path to the file or directory whose accessibility is being checked.
 * @param[in] mode      The access mode to check for. This can be a combination of the following:
 *                      - `R_OK`: Check for read permission.
 *                      - `W_OK`: Check for write permission.
 *                      - `X_OK`: Check for execute permission.
 *                      - `F_OK`: Check if the file exists.
 *
 * @return sysret_t     Returns `0` if the specified access is allowed. On failure, returns a negative error code.
 *
 * @note This function does not modify the file or directory, it only checks if the specified access rights are granted.
 *
 * @see sys_open(), sys_stat(), sys_fstat(), sys_chmod(), sys_chown()
 */
sysret_t sys_access(const char *filename, int mode)
{
    int ret = 0;
#ifdef ARCH_MM_MMU
    rt_size_t len = 0;
    char *kfilename = RT_NULL;

    len = lwp_user_strlen(filename);
    if (len <= 0)
    {
        return -EINVAL;
    }

    kfilename = (char *)kmem_get(len + 1);
    if (!kfilename)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(kfilename, (void *)filename, len + 1) != (len + 1))
    {
        kmem_put(kfilename);
        return -EFAULT;
    }

    ret = access(kfilename, mode);
    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    kmem_put(kfilename);
    return ret;
#else
    ret = access(filename, mode);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Creates a pipe, a unidirectional data channel.
 *
 * This function creates a pipe, which is a unidirectional data channel used for inter-process communication.
 * The pipe consists of two file descriptors: one for reading from the pipe and one for writing to the pipe.
 * The pipe is used for passing data between processes or threads, typically in a producer-consumer scenario.
 *
 * @param[out] fd  An array of two integers where the file descriptors for the read and write ends of the pipe will be stored.
 *                 - `fd[0]`: The file descriptor for reading from the pipe.
 *                 - `fd[1]`: The file descriptor for writing to the pipe.
 *
 * @return sysret_t   Returns `0` on success. On failure, returns a negative error code.
 *
 * @note The pipe created by this function is typically used for simple communication between processes or threads.
 *       The data written to `fd[1]` can be read from `fd[0]`. After usage, both file descriptors should be closed.
 *
 * @see sys_read(), sys_write(), sys_close(), sys_fork(), sys_execve()
 */
sysret_t sys_pipe(int fd[2])
{
    int ret;
    int kfd[2] = {0, 0};

    if (!lwp_user_accessable((void *)fd, sizeof(int[2])))
    {
        return -EFAULT;
    }

    ret = pipe(kfd);

    lwp_put_to_user((void *)fd, kfd, sizeof(int[2]));

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Waits for a process to change state.
 *
 * This function suspends the execution of the calling process until one of its child processes terminates
 * or a specified process (identified by `pid`) changes its state. The function returns the process ID of the child
 * process that terminated, and provides information about its exit status and resource usage.
 *
 * @param[in]  pid      The process ID of the child process to wait for. The behavior of this parameter can be one of the following:
 *                      - `pid > 0`: Wait for the child process with the specified PID.
 *                      - `pid == 0`: Wait for any child process in the same process group.
 *                      - `pid == -1`: Wait for any child process (default behavior).
 *                      - `pid < -1`: Wait for any child process in the specified process group.
 *
 * @param[out] status   A pointer to an integer where the exit status of the terminated child process will be stored.
 *                      This status can be interpreted using macros such as `WIFEXITED` or `WIFSIGNALED`.
 *
 * @param[in]  options  Options for the wait operation, which can include:
 *                      - `WNOHANG`: Return immediately if no child has exited.
 *                      - `WUNTRACED`: Return if a child has stopped, but not yet terminated.
 *
 * @param[out] ru       A pointer to a `struct rusage` where resource usage information of the child process will be stored.
 *                      This includes information such as CPU time consumed by the child process.
 *
 * @return sysret_t     Returns the process ID of the terminated child on success. In case of failure, a negative error code is returned.
 *
 * @note This function is useful for monitoring and cleaning up child processes in parent-child relationships.
 *       The `status` value can be further analyzed to determine if the child process terminated normally or due to a signal.
 *
 * @see sys_waitpid(), sys_fork(), sys_exit()
 */
sysret_t sys_wait4(pid_t pid, int *status, int options, struct rusage *ru)
{
    return lwp_waitpid(pid, status, options, ru);
}

/**
 * @brief Sets the time of a specified clock.
 *
 * This function sets the time of the specified clock (identified by `clk`) to the given value. The time is provided
 * as a `struct timespec` containing seconds and nanoseconds. This function can be used to set the system clock or
 * other specific clocks, such as monotonic or real-time clocks.
 *
 * @param[in] clk  The clock ID for which to set the time. The clock can be one of the following:
 *                 - `CLOCK_REALTIME`: Set the system's real-time clock.
 *                 - `CLOCK_MONOTONIC`: Set the monotonic clock, which measures time since some unspecified starting point.
 *                 - `CLOCK_PROCESS_CPUTIME_ID`: Set the CPU time used by the process.
 *                 - `CLOCK_THREAD_CPUTIME_ID`: Set the CPU time used by the current thread.
 *
 * @param[in] ts   A pointer to a `struct timespec` containing the new time to set for the specified clock.
 *                 - `ts->tv_sec`: Seconds since the epoch (for `CLOCK_REALTIME`) or since some unspecified start point (for other clocks).
 *                 - `ts->tv_nsec`: Nanoseconds within the current second.
 *
 * @return sysret_t  Returns `0` on success. On failure, returns a negative error code.
 *
 * @note This function requires appropriate permissions for setting the system's clock. In some systems, only privileged users
 *       may change the `CLOCK_REALTIME` clock.
 *
 * @see sys_clock_gettime(), sys_clock_getres()
 */
sysret_t sys_clock_settime(clockid_t clk, const struct timespec *ts)
{
    int ret = 0;
#ifdef ARCH_MM_MMU
    size_t size = sizeof(struct timespec);
    struct timespec *kts = NULL;

    if (!lwp_user_accessable((void *)ts, size))
    {
        return -EFAULT;
    }

    kts = kmem_get(size);
    if (!kts)
    {
        return -ENOMEM;
    }

    lwp_get_from_user(kts, (void *)ts, size);
    ret = clock_settime(clk, kts);
    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    kmem_put(kts);

    return ret;
#else
    if (!lwp_user_accessable((void *)ts, sizeof(struct timespec)))
    {
        return -EFAULT;
    }
    ret = clock_settime(clk, ts);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Retrieves the current time of a specified clock.
 *
 * This function retrieves the current time of the specified clock (identified by `clk`) and stores it in the
 * `struct timespec` pointed to by `ts`. The time is expressed in seconds and nanoseconds. The clock can be
 * one of several types, such as real-time, monotonic, or process-specific clocks.
 *
 * @param[in] clk  The clock ID for which to get the time. The clock can be one of the following:
 *                 - `CLOCK_REALTIME`: Get the system's real-time clock.
 *                 - `CLOCK_MONOTONIC`: Get the monotonic clock, which measures time since some unspecified starting point.
 *                 - `CLOCK_PROCESS_CPUTIME_ID`: Get the CPU time used by the process.
 *                 - `CLOCK_THREAD_CPUTIME_ID`: Get the CPU time used by the current thread.
 *
 * @param[out] ts  A pointer to a `struct timespec` where the current time for the specified clock will be stored.
 *                 - `ts->tv_sec`: Seconds since the epoch (for `CLOCK_REALTIME`) or since some unspecified start point (for other clocks).
 *                 - `ts->tv_nsec`: Nanoseconds within the current second.
 *
 * @return sysret_t  Returns `0` on success. On failure, returns a negative error code.
 *
 * @note This function requires appropriate permissions for retrieving certain clocks (e.g., `CLOCK_REALTIME`).
 *
 * @see sys_clock_settime(), sys_clock_getres()
 */
sysret_t sys_clock_gettime(clockid_t clk, struct timespec *ts)
{
    int ret = 0;
#ifdef ARCH_MM_MMU
    size_t size = sizeof(struct timespec);
    struct timespec *kts = NULL;

    if (!lwp_user_accessable((void *)ts, size))
    {
        return -EFAULT;
    }

    kts = kmem_get(size);
    if (!kts)
    {
        return -ENOMEM;
    }

    ret = clock_gettime(clk, kts);
    if (ret != -1)
        lwp_put_to_user(ts, kts, size);

    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    kmem_put(kts);

    return ret;
#else
    if (!lwp_user_accessable((void *)ts, sizeof(struct timespec)))
    {
        return -EFAULT;
    }
    ret = clock_gettime(clk, ts);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Suspends the execution of the calling thread for the specified time duration.
 *
 * This function causes the calling thread to sleep for the specified time duration, which is provided as a
 * `struct timespec` containing seconds and nanoseconds. The sleep is done based on the specified clock (identified by `clk`).
 * If the `flags` parameter is set to `TIMER_ABSTIME`, the specified time represents an absolute time, otherwise,
 * it represents a relative time interval.
 *
 * @param[in] clk   The clock ID for which to perform the sleep. The clock can be one of the following:
 *                  - `CLOCK_REALTIME`: Use the system's real-time clock.
 *                  - `CLOCK_MONOTONIC`: Use the monotonic clock, which measures time since some unspecified starting point.
 *                  - `CLOCK_PROCESS_CPUTIME_ID`: Use the CPU time used by the process.
 *                  - `CLOCK_THREAD_CPUTIME_ID`: Use the CPU time used by the current thread.
 *
 * @param[in] flags The sleep behavior flags. The possible flags are:
 *                  - `0`: The sleep duration is relative to the current time.
 *                  - `TIMER_ABSTIME`: The sleep duration is absolute (measured from the specified clock).
 *
 * @param[in] rqtp  A pointer to a `struct timespec` containing the requested sleep time.
 *                  - `rqtp->tv_sec`: Seconds to sleep.
 *                  - `rqtp->tv_nsec`: Nanoseconds to sleep (0 ≤ `rqtp->tv_nsec` < 1 billion).
 *
 * @param[out] rmtp A pointer to a `struct timespec` where the remaining time will be stored if the sleep is interrupted.
 *                  If the sleep completes successfully, `rmtp` will not be modified.
 *                  - `rmtp->tv_sec`: Remaining seconds.
 *                  - `rmtp->tv_nsec`: Remaining nanoseconds.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note This function can be interrupted by signals. In that case, the remaining time is returned in `rmtp`.
 *       If the sleep is not interrupted, the function returns `SYSRET_OK` when the requested time has passed.
 *
 * @see sys_clock_gettime(), sys_clock_settime(), sys_nanosleep()
 */
sysret_t sys_clock_nanosleep(clockid_t clk, int flags, const struct timespec *rqtp, struct timespec *rmtp)
{
    int ret = 0;
    LOG_D("sys_nanosleep\n");
    if (!lwp_user_accessable((void *)rqtp, sizeof *rqtp))
        return -EFAULT;

#ifdef ARCH_MM_MMU
    struct timespec rqtp_k;
    struct timespec rmtp_k;

    lwp_get_from_user(&rqtp_k, (void *)rqtp, sizeof rqtp_k);
    ret = clock_nanosleep(clk, flags, &rqtp_k, &rmtp_k);
    if ((ret != -1 || rt_get_errno() == EINTR) && rmtp && lwp_user_accessable((void *)rmtp, sizeof *rmtp))
    {
        lwp_put_to_user(rmtp, (void *)&rmtp_k, sizeof rmtp_k);
                if(ret != 0)
            return -EINTR;
    }
#else
    if (rmtp)
    {
        if (!lwp_user_accessable((void *)rmtp, sizeof *rmtp))
            return -EFAULT;
        ret = clock_nanosleep(clk, flags, rqtp, rmtp);
    }
#endif
    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Get the resolution of the specified clock.
 *
 * This function retrieves the resolution of the specified clock, which is the smallest time interval that the clock can measure.
 * The resolution is returned in a `struct timespec` which contains seconds and nanoseconds.
 *
 * @param[in] clk   The clock ID for which to get the resolution. The clock can be one of the following:
 *                  - `CLOCK_REALTIME`: System's real-time clock.
 *                  - `CLOCK_MONOTONIC`: Monotonic clock (measures time since an unspecified point).
 *                  - `CLOCK_PROCESS_CPUTIME_ID`: CPU time consumed by the current process.
 *                  - `CLOCK_THREAD_CPUTIME_ID`: CPU time consumed by the current thread.
 *
 * @param[out] ts   A pointer to a `struct timespec` where the clock's resolution will be stored.
 *                  - `ts->tv_sec`: The number of seconds in the resolution.
 *                  - `ts->tv_nsec`: The number of nanoseconds in the resolution (0 ≤ `ts->tv_nsec` < 1 billion).
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note The resolution may be zero for some clocks, depending on the system's configuration.
 *       A clock's resolution determines the smallest unit of time the clock can measure.
 *
 * @see sys_clock_gettime(), sys_clock_settime(), sys_clock_nanosleep()
 */
sysret_t sys_clock_getres(clockid_t clk, struct timespec *ts)
{
    int ret = 0;
#ifdef ARCH_MM_MMU
    struct timespec kts;
    size_t size = sizeof(struct timespec);

    if (!lwp_user_accessable((void *)ts, size))
    {
        return -EFAULT;
    }

    ret = clock_getres(clk, &kts);

    if (ret != -1)
        lwp_put_to_user(ts, &kts, size);
#else
    if (!lwp_user_accessable((void *)ts, sizeof(struct timespec)))
    {
        return -EFAULT;
    }
    ret = clock_getres(clk, ts);
#endif
    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Rename or move a file or directory.
 *
 * This function renames or moves a file or directory from `oldpath` to `newpath`.
 * If the `newpath` exists, it may be overwritten depending on the system's file system behavior and
 * the permissions of the files involved.
 *
 * @param[in] oldpath  The current path of the file or directory to rename or move.
 * @param[in] newpath  The new path or name to which the file or directory should be renamed or moved.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note If `oldpath` and `newpath` refer to different file systems, the behavior may vary,
 *       as the operation might involve copying and removing files instead of simply renaming them.
 *       The success of the operation also depends on the permissions of the source and destination.
 *
 * @see sys_unlink(), sys_mkdir(), sys_access()
 */
sysret_t sys_rename(const char *oldpath, const char *newpath)
{
    int ret = -1;
#ifdef ARCH_MM_MMU
    int err;

    err = lwp_user_strlen(oldpath);
    if (err <= 0)
    {
        return -EFAULT;
    }

    err = lwp_user_strlen(newpath);
    if (err <= 0)
    {
        return -EFAULT;
    }
#endif
    ret = rename(oldpath, newpath);
    return (ret < 0 ? GET_ERRNO() : ret);
}

typedef unsigned long long rlim_t;

struct rlimit {
    rlim_t rlim_cur;
    rlim_t rlim_max;
};

#define RLIMIT_CPU     0
#define RLIMIT_FSIZE   1
#define RLIMIT_DATA    2
#define RLIMIT_STACK   3
#define RLIMIT_CORE    4
#define RLIMIT_RSS     5
#define RLIMIT_NPROC   6
#define RLIMIT_NOFILE  7
#define RLIMIT_MEMLOCK 8
#define RLIMIT_AS      9

sysret_t sys_prlimit64(pid_t pid,
        unsigned int resource,
        const struct rlimit *new_rlim,
        struct rlimit *old_rlim)
{
    return -ENOSYS;
}

/**
 * @brief Get resource limits.
 *
 * This function retrieves the current resource limits for the specified resource type.
 * The resource limit specifies the maximum value for a particular resource that a process or thread can use.
 * The limits are returned in an array `rlim` where:
 * - `rlim[0]` represents the soft limit (the current value).
 * - `rlim[1]` represents the hard limit (the maximum allowable value).
 *
 * @param[in] resource  The resource for which to get the limits. It can be one of the following:
 *                      - `RLIMIT_NOFILE`: Maximum number of file descriptors.
 *
 * @param[out] rlim    An array to store the resource limits. The array should have at least 2 elements:
 *                     - `rlim[0]`: The soft limit for the resource.
 *                     - `rlim[1]`: The hard limit for the resource.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note The limits returned by `sys_getrlimit` are subject to system constraints and may vary across different systems.
 *
 * @see sys_setrlimit(), sys_getrlimit64(), sys_getrusage()
 */
sysret_t sys_getrlimit(unsigned int resource, unsigned long rlim[2])
{
    int ret = -1;
    unsigned long krlim[2] = {0, 0};

    if (!lwp_user_accessable((void *)rlim, sizeof(unsigned long [2])))
    {
        return -EFAULT;
    }

    if (lwp_get_from_user(krlim, rlim, sizeof(unsigned long [2])) != sizeof(unsigned long [2]))
    {
        return -EINVAL;
    }

    switch (resource)
    {
    case RLIMIT_NOFILE:
        {
            struct dfs_fdtable *fdt = dfs_fdtable_get();

            dfs_file_lock();
            krlim[0] = fdt->maxfd;
            dfs_file_unlock();
            krlim[1] = DFS_FD_MAX;
            ret = 0;
        }
        break;
    default:
        return -EINVAL;
        break;
    }

    lwp_put_to_user((void *)rlim, krlim, sizeof(unsigned long [2]));

    return (ret < 0 ? GET_ERRNO() : ret);
}

sysret_t sys_setrlimit(unsigned int resource, struct rlimit *rlim)
{
    return -ENOSYS;
}

/**
 * @brief Get random data from the kernel's random number generator.
 *
 * This function retrieves cryptographically secure random data from the kernel's random number generator
 * and stores it in the buffer provided by the user. The data can be used for cryptographic operations or
 * other applications requiring randomization.
 *
 * @param[out] buf     A pointer to the buffer where the random data will be stored. The buffer must be large
 *                     enough to hold the requested amount of random data.
 * @param[in]  buflen  The number of bytes of random data to retrieve. This value must be a positive integer.
 * @param[in]  flags   Optional flags to modify the behavior of the random data retrieval. Possible values may include:
 *                     - `GRND_RANDOM`: Requests random data from the system's non-blocking random source.
 *                     - `GRND_NONBLOCK`: Instructs the function to return immediately even if insufficient entropy is available.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note
 * - If the `GRND_NONBLOCK` flag is not set and there is insufficient entropy in the system's random pool,
 *   this function may block until enough entropy is available.
 * - The function returns cryptographically secure random data, suitable for use in secure applications.
 *
 * @see sys_random(), sys_getentropy()
 */
sysret_t sys_getrandom(void *buf, size_t buflen, unsigned int flags)
{
    int ret = -1;
    int count = 0;
    void *kmem = RT_NULL;
    rt_device_t rd_dev = RT_NULL;

    if (flags & GRND_RANDOM)
        rd_dev = rt_device_find("random");
    else
        rd_dev = rt_device_find("urandom");

    if (rd_dev == RT_NULL)
    {
        return -EFAULT;
    }

    if (rt_device_open(rd_dev, RT_DEVICE_OFLAG_RDONLY) != RT_EOK)
    {
        return -EFAULT;
    }

    if (!lwp_user_accessable(buf, buflen))
    {
        rt_device_close(rd_dev);
        return -EFAULT;
    }

#ifdef ARCH_MM_MMU
    kmem = kmem_get(buflen);
    if (!kmem)
    {
        rt_device_close(rd_dev);
        return -ENOMEM;
    }

    while (count < buflen)
    {
        ret = rt_device_read(rd_dev, count, (char *)kmem + count, buflen - count);
        if (ret <= 0)
            break;
        count += ret;
    }
    rt_device_close(rd_dev);

    ret = count;
    if (count > 0)
    {
        ret = lwp_put_to_user(buf, kmem, count);
    }
    kmem_put(kmem);
#else
    while (count < buflen)
    {
        ret = rt_device_read(rd_dev, count, (char *)kmem + count, buflen - count);
        if (ret <= 0)
            break;
        count += ret;
    }
    rt_device_close(rd_dev);

    ret = count;
#endif
    return ret;
}

/**
 * @brief Read the value of a symbolic link.
 *
 * This function reads the value of a symbolic link and stores it in the provided buffer. The value is the
 * path to which the symbolic link points. If the symbolic link is too long to fit in the provided buffer,
 * the function returns the number of bytes needed to store the entire path (not including the terminating null byte).
 *
 * @param[in]  path   The path of the symbolic link to read.
 * @param[out] buf    A buffer where the symbolic link's target will be stored. The buffer must be large enough
 *                    to hold the path of the symbolic link.
 * @param[in]  bufsz  The size of the buffer `buf`. It specifies the maximum number of bytes to read.
 *
 * @return ssize_t The number of bytes written to `buf` (excluding the terminating null byte) on success.
 *                 On failure, it returns a negative error code:
 *                 - `-EINVAL`: Invalid path.
 *                 - `-ENOMEM`: Insufficient memory to read the link.
 *                 - `-EFAULT`: Invalid address for the `buf`.
 *
 * @note It will (silently) truncate the contents(to a length of bufsiz characters),
 *       in case the buffer is too small to hold all of the contents.
 *
 * @see sys_symlink(), sys_lstat()
 */
ssize_t sys_readlink(char* path, char *buf, size_t bufsz)
{
    size_t len, copy_len;
    int err, rtn;
    char *copy_path;

    len = lwp_user_strlen(path);
    if (len <= 0)
    {
        return -EFAULT;
    }

    if (!lwp_user_accessable(buf, bufsz))
    {
        return -EINVAL;
    }

    copy_path = (char*)rt_malloc(len + 1);
    if (!copy_path)
    {
        return -ENOMEM;
    }

    copy_len = lwp_get_from_user(copy_path, path, len);
    copy_path[copy_len] = '\0';

    char *link_fn = (char *)rt_malloc(DFS_PATH_MAX);
    if (link_fn)
    {
        err = dfs_file_readlink(copy_path, link_fn, DFS_PATH_MAX);
        if (err > 0)
        {
            buf[bufsz > err ? err : bufsz] = '\0';
            rtn = lwp_put_to_user(buf, link_fn, bufsz > err ? err : bufsz);
        }
        else
        {
            rtn = -EIO;
        }
        rt_free(link_fn);
    }
    else
    {
        rtn = -ENOMEM;
    }

    rt_free(copy_path);
    return rtn;
}

/**
 * @brief Set the CPU affinity mask of a process.
 *
 * This function sets the CPU affinity mask for a specified process. The affinity mask determines which CPUs the
 * process is allowed to execute on. The process will be restricted to the CPUs specified in the mask.
 *
 * @param[in] pid     The process ID of the process whose CPU affinity is to be set. If the `pid` is `0`, the
 *                    affinity of the calling process will be modified.
 * @param[in] size    The size (in bytes) of the CPU set, typically `sizeof(cpu_set_t)`.
 * @param[in] set     A pointer to the CPU set. The CPU set is a bitmask representing which CPUs the process
 *                    is allowed to run on. The bitmask must have enough bits to cover the number of CPUs on the system.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note The CPU set is represented as a bitmask where each bit corresponds to a CPU. If the bit is set, the process
 *       can execute on that CPU. The number of CPUs is platform-dependent, and the size of `set` must be large enough
 *       to hold a bit for each CPU.
 *
 * @see sys_sched_getaffinity(), sys_setcpu()
 */
sysret_t sys_sched_setaffinity(pid_t pid, size_t size, void *set)
{
    void *kset = RT_NULL;

    if (size <= 0 || size > sizeof(cpu_set_t))
    {
        return -EINVAL;
    }
    if (!lwp_user_accessable((void *)set, size))
        return -EFAULT;

    kset = kmem_get(size);
    if (kset == RT_NULL)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(kset, set, size) != size)
    {
        kmem_put(kset);
        return -EINVAL;
    }

    for (int i = 0;i < size * 8; i++)
    {
        if (CPU_ISSET_S(i, size, kset))
        {
            kmem_put(kset);

            /**
             * yes it's tricky.
             * But when we talk about 'pid' from GNU libc, it's the 'task-id'
             * aka 'thread->tid' known in kernel.
             */
            return lwp_setaffinity(pid, i);
        }
    }

    kmem_put(kset);

    return -1;
}

/**
 * @brief Get the CPU affinity mask of a process.
 *
 * This function retrieves the CPU affinity mask for a specified process. The affinity mask indicates which CPUs the
 * process is allowed to execute on. The process can run on any of the CPUs represented by the bits set in the mask.
 *
 * @param[in]  pid    The process ID of the process whose CPU affinity is to be retrieved. If `pid` is `0`, the
 *                    affinity mask of the calling process will be retrieved.
 * @param[in]  size   The size (in bytes) of the CPU set, typically `sizeof(cpu_set_t)`.
 * @param[out] set    A pointer to a buffer where the CPU affinity mask will be stored. The mask is represented
 *                    as a bitmask, where each bit corresponds to a CPU. The bit is set if the process can run on that CPU.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note The CPU set is represented as a bitmask where each bit corresponds to a CPU. If the bit is set, the process
 *       can execute on that CPU. The number of CPUs is platform-dependent, and the size of `set` must be large enough
 *       to hold a bit for each CPU.
 *
 * @see sys_sched_setaffinity(), sys_getcpu()
 */
sysret_t sys_sched_getaffinity(const pid_t pid, size_t size, void *set)
{
#ifdef ARCH_MM_MMU
    LWP_DEF_RETURN_CODE(rc);
    void *mask;
    struct rt_lwp *lwp;

    if (size <= 0 || size > sizeof(cpu_set_t))
    {
        return -EINVAL;
    }
    if (!lwp_user_accessable(set, size))
    {
        return -EFAULT;
    }
    mask = kmem_get(size);
    if (!mask)
    {
        return -ENOMEM;
    }

    CPU_ZERO_S(size, mask);

    lwp_pid_lock_take();
    lwp = lwp_from_pid_locked(pid);

    if (!lwp)
    {
        rc = -ESRCH;
    }
    else
    {
#ifdef RT_USING_SMP
        if (lwp->bind_cpu == RT_CPUS_NR)    /* not bind */
        {
            for(int i = 0; i < RT_CPUS_NR; i++)
            {
                CPU_SET_S(i, size, mask);
            }
        }
        else /* set bind cpu */
        {
            /* TODO: only single-core bindings are now supported of rt-smart */
            CPU_SET_S(lwp->bind_cpu, size, mask);
        }
#else
        CPU_SET_S(0, size, mask);
#endif

        if (lwp_put_to_user(set, mask, size) != size)
            rc = -EFAULT;
        else
            rc = size;
    }

    lwp_pid_lock_release();

    kmem_put(mask);

    LWP_RETURN(rc);
#else
    return -1;
#endif
}

/**
 * @brief Retrieve system information.
 *
 * This function provides details about the current state of the system, such as uptime, memory usage,
 * load average, and other key statistics. The information is stored in a structure pointed to by `info`.
 *
 * @param[out] info A pointer to a buffer where system information will be stored. The structure should
 *                  be compatible with the format expected by the system, typically `struct sysinfo`.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note The structure of `info` must be predefined and consistent with the system's expectations.
 *       This function does not allocate memory for `info`; the caller must provide sufficient
 *       memory for the structure.
 */
sysret_t sys_sysinfo(void *info)
{
#ifdef ARCH_MM_MMU
    struct sysinfo kinfo = {0};
    rt_size_t total_pages = 0, free_pages = 0;

    if (!lwp_user_accessable(info, sizeof(struct sysinfo)))
    {
        return -EFAULT;
    }

    kinfo.uptime = rt_tick_get_millisecond() / 1000;
    /* TODO: 1, 5, and 15 minute load averages */
    kinfo.loads[0] = kinfo.loads[1] = kinfo.loads[2] = rt_object_get_length(RT_Object_Class_Thread);
    rt_page_get_info(&total_pages, &free_pages);
    kinfo.totalram = total_pages;
    kinfo.freeram = free_pages;

    /* TODO: implementation procfs, here is counter the lwp number */
    struct lwp_avl_struct *pids = lwp_get_pid_ary();
    for (int index = 0; index < RT_LWP_MAX_NR; index++)
    {
        struct rt_lwp *lwp = (struct rt_lwp *)pids[index].data;

        if (lwp)
        {
            kinfo.procs++;
        }
    }

    rt_page_high_get_info(&total_pages, &free_pages);
    kinfo.totalhigh = total_pages;
    kinfo.freehigh = free_pages;
    kinfo.mem_unit = ARCH_PAGE_SIZE;

    if (lwp_put_to_user(info, &kinfo, sizeof(struct sysinfo)) != sizeof(struct sysinfo))
    {
        return -EFAULT;
    }

    return 0;
#else
    return -1;
#endif
}

/**
 * @brief Set scheduling parameters for a specific thread.
 *
 * This function allows setting the scheduling parameters for a thread identified by its thread ID (`tid`).
 * The parameters are provided via the `param` argument, which should be a structure compatible with the
 * system's scheduling policies.
 *
 * @param[in] tid The thread ID of the target thread for which the scheduling parameters are to be set.
 * @param[in] param A pointer to a structure containing the new scheduling parameters. The structure
 *                  typically includes fields like priority and policy.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note The caller must have appropriate permissions to change the scheduling parameters of the specified thread.
 *       The exact structure and fields of `param` depend on the system's implementation and scheduling policies.
 */
sysret_t sys_sched_setparam(pid_t tid, void *param)
{
    struct sched_param *sched_param = RT_NULL;
    rt_thread_t thread;
    int ret = -1;

    if (!lwp_user_accessable(param, sizeof(struct sched_param)))
    {
        return -EFAULT;
    }

    sched_param = kmem_get(sizeof(struct sched_param));
    if (sched_param == RT_NULL)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(sched_param, param, sizeof(struct sched_param)) != sizeof(struct sched_param))
    {
        kmem_put(sched_param);
        return -EINVAL;
    }

    thread = lwp_tid_get_thread_and_inc_ref(tid);

    if (thread)
    {
        ret = rt_thread_control(thread, RT_THREAD_CTRL_RESET_PRIORITY, (void *)&sched_param->sched_priority);
    }

    lwp_tid_dec_ref(thread);

    kmem_put(sched_param);

    return ret;
}

/**
 * @brief Relinquish the processor voluntarily.
 *
 * This function causes the calling thread to yield the processor, allowing other threads
 * that are ready to run to execute. The thread will be placed back into the scheduler's
 * ready queue and may be rescheduled according to its priority and the system's scheduling policy.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note This function is typically used in cooperative multitasking scenarios or when a thread
 *       explicitly determines it no longer needs the processor at the moment.
 */
sysret_t sys_sched_yield(void)
{
    rt_thread_yield();
    return 0;
}

/**
 * @brief Retrieve the scheduling parameters of a specific thread.
 *
 * This function retrieves the scheduling parameters of the thread identified by the thread ID (`tid`).
 * The retrieved parameters are stored in the structure pointed to by the `param` argument.
 *
 * @param[in]  tid   The thread ID of the target thread whose scheduling parameters are to be retrieved.
 * @param[out] param A pointer to a structure where the scheduling parameters will be stored. The structure
 *                   typically includes fields like priority and policy.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note The caller must have appropriate permissions to query the scheduling parameters of the specified thread.
 *       The exact structure and fields of `param` depend on the system's implementation and scheduling policies.
 */
sysret_t sys_sched_getparam(const pid_t tid, void *param)
{
    struct sched_param *sched_param = RT_NULL;
    rt_thread_t thread;
    int ret = -1;

    if (!lwp_user_accessable(param, sizeof(struct sched_param)))
    {
        return -EFAULT;
    }

    sched_param = kmem_get(sizeof(struct sched_param));
    if (sched_param == RT_NULL)
    {
        return -ENOMEM;
    }

    thread = lwp_tid_get_thread_and_inc_ref(tid);

    if (thread)
    {
        sched_param->sched_priority = RT_SCHED_PRIV(thread).current_priority;
        ret = 0;
    }

    lwp_tid_dec_ref(thread);

    lwp_put_to_user((void *)param, sched_param, sizeof(struct sched_param));
    kmem_put(sched_param);

    return ret;
}

/**
 * @brief Get the maximum priority for a given scheduling policy.
 *
 * This function retrieves the maximum priority value that can be used with the specified
 * scheduling policy.
 *
 * @param[in] policy The scheduling policy for which to retrieve the maximum priority.
 *
 * @return sysret_t Returns the maximum priority value on success. On failure, returns a
 *                  negative error code.
 *
 * @note The valid priority range depends on the system's configuration and the selected
 *       scheduling policy. The returned value represents the highest priority that can
 *       be assigned to a thread using the given policy.
 */
sysret_t sys_sched_get_priority_max(int policy)
{
    if(policy < 0)
    {
        SET_ERRNO(EINVAL);
        return -rt_get_errno();
    }
    return RT_THREAD_PRIORITY_MAX;
}

/**
 * @brief Get the minimum priority for a given scheduling policy.
 *
 * This function retrieves the minimum priority value that can be used with the specified
 * scheduling policy.
 *
 * @param[in] policy The scheduling policy for which to retrieve the minimum priority.
 *
 * @return sysret_t Returns the minimum priority value on success. On failure, returns a
 *                  negative error code.
 *
 * @note The valid priority range depends on the system's configuration and the selected
 *       scheduling policy. The returned value represents the lowest priority that can
 *       be assigned to a thread using the given policy.
 */
sysret_t sys_sched_get_priority_min(int policy)
{
    if(policy < 0)
    {
        SET_ERRNO(EINVAL);
        return -rt_get_errno();
    }
    return 0;
}

/**
 * @brief Set the scheduling policy and parameters for a thread.
 *
 * This function sets the scheduling policy and associated parameters for the specified thread.
 * It allows controlling the scheduling behavior of threads.
 *
 * @param[in] tid    The thread ID of the target thread.
 * @param[in] policy The scheduling policy to be applied. Common values include:
 *                   - `SCHED_FIFO`: First-in, first-out scheduling.
 *                   - `SCHED_RR`: Round-robin scheduling.
 *                   - `SCHED_OTHER`: Default or standard scheduling.
 * @param[in] param  Pointer to a structure containing scheduling parameters, such as priority.
 *                   The structure type depends on the system implementation.
 *
 * @return sysret_t Returns 0 on success. On failure, returns a negative error code.
 *
 * @note This function requires appropriate permissions to modify the scheduling settings
 *       of another thread. For most systems, elevated privileges may be required.
 *       Ensure the `param` structure is properly initialized for the given `policy`.
 */
sysret_t sys_sched_setscheduler(int tid, int policy, void *param)
{
    sysret_t ret;
    struct sched_param *sched_param = RT_NULL;
    rt_thread_t thread = RT_NULL;

    if (!lwp_user_accessable(param, sizeof(struct sched_param)))
    {
        return -EFAULT;
    }

    sched_param = kmem_get(sizeof(struct sched_param));
    if (sched_param == RT_NULL)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(sched_param, param, sizeof(struct sched_param)) != sizeof(struct sched_param))
    {
        kmem_put(sched_param);
        return -EINVAL;
    }

    thread = lwp_tid_get_thread_and_inc_ref(tid);
    ret = rt_thread_control(thread, RT_THREAD_CTRL_RESET_PRIORITY, (void *)&sched_param->sched_priority);
    lwp_tid_dec_ref(thread);

    kmem_put(sched_param);

    return ret;
}

/**
 * @brief Get the scheduling policy of a thread.
 *
 * This function retrieves the current scheduling policy of the specified thread.
 *
 * @param[in] tid The thread ID of the target thread.
 *
 * @return sysret_t Returns the scheduling policy of the thread on success. On failure,
 *                  returns a negative error code.
 *
 * @note The caller must have appropriate permissions to query the scheduling policy
 *       of the specified thread.
 */
sysret_t sys_sched_getscheduler(int tid)
{
    rt_thread_t thread = RT_NULL;
    int rtn;

    thread = lwp_tid_get_thread_and_inc_ref(tid);
    lwp_tid_dec_ref(thread);

    if (thread)
    {
        rtn = SCHED_RR;
    }
    else
    {
        rtn = -ESRCH;
    }

    return rtn;
}

/**
 * @brief Flush the file descriptors' data to disk.
 *
 * This function flushes all modified data of the file associated with the specified
 * file descriptor to disk, ensuring that any changes made to the file are committed
 * to permanent storage.
 *
 * @param[in] fd The file descriptor associated with the file to be flushed. It should
 *               refer to an open file.
 *
 * @return sysret_t Returns `0` (0) on success. On failure, returns a negative
 *                  error code.
 *
 * @note The `fsync` function ensures that all data written to the file is physically
 *       stored on disk, but it does not guarantee that all file metadata is flushed.
 *       To flush both data and metadata, `fdatasync` can be used.
 */
sysret_t sys_fsync(int fd)
{
    int res = fsync(fd);
    if (res < 0)
        res = rt_get_errno();
    return res;
}

/**
 * @brief Open a message queue.
 *
 * This function opens a message queue for communication between processes.
 * It can create a new message queue or open an existing one, depending on the specified
 * flags.
 *
 * @param[in] name  The name of the message queue. The name should be a null-terminated
 *                  string and is subject to system-specific naming conventions.
 * @param[in] flags Flags that control the behavior of the message queue. Common flags include:
 *                  - `O_CREAT`: Create the message queue if it does not exist.
 *                  - `O_EXCL`: Fail if the message queue already exists.
 *                  - `O_RDONLY`: Open the queue for reading.
 *                  - `O_WRONLY`: Open the queue for writing.
 *                  - `O_RDWR`: Open the queue for both reading and writing.
 * @param[in] mode  The mode to be applied when creating the message queue, which defines
 *                  the permissions for the message queue (e.g., read, write).
 * @param[in] attr  A pointer to a `struct mq_attr` that defines the attributes of the
 *                  message queue, such as the maximum number of messages and the size of
 *                  each message. If `NULL`, default values are used.
 *
 * @return mqd_t Returns a non-negative file descriptor for the message queue on success.
 *               On failure, returns `-1` and sets `errno` to indicate the error.
 *
 * @note If the message queue is created, its attributes (such as the maximum number of
 *       messages and message size) must be defined in the `mq_attr` structure. If the
 *       `O_CREAT` flag is not specified and the queue does not exist, the function will
 *       return `-1`.
 */
mqd_t sys_mq_open(const char *name, int flags, mode_t mode, struct mq_attr *attr)
{
    mqd_t mqdes;
    sysret_t ret = 0;
#ifdef ARCH_MM_MMU
    char *kname = RT_NULL;
    rt_size_t len = 0;
    struct mq_attr attr_k;

    len = lwp_user_strlen(name);
    if (!len)
        return (mqd_t)-EINVAL;

    kname = (char *)kmem_get(len + 1);
    if (!kname)
        return (mqd_t)-ENOMEM;

    if (attr == NULL)
    {
        attr_k.mq_maxmsg = 10;
        attr_k.mq_msgsize = 8192;
        attr_k.mq_flags = 0;
        attr = &attr_k;
    }
    else
    {
        if (!lwp_get_from_user(&attr_k, (void *)attr, sizeof(struct mq_attr)))
            return -EINVAL;
    }

    lwp_get_from_user(kname, (void *)name, len + 1);
    mqdes = mq_open(kname, flags, mode, &attr_k);
    if (mqdes == -1)
    {
        ret = GET_ERRNO();
    }
    lwp_put_to_user(attr, &attr_k, sizeof(struct mq_attr));
    kmem_put(kname);
#else
    mqdes = mq_open(name, flags, mode, attr);
#endif
    if (mqdes == -1)
        return (mqd_t)ret;
    else
        return mqdes;
}

/**
 * @brief Remove a message queue.
 *
 * This function removes a message queue identified by its name. If the message queue
 * is open by any process, it will be removed only when all the processes close their
 * file descriptors associated with the message queue.
 *
 * @param[in] name The name of the message queue to be removed. It should be a null-terminated
 *                 string that conforms to system-specific naming conventions.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative
 *                  error code.
 *
 * @note After a successful call, the message queue is removed from the system. However,
 *       the removal will not take effect until all processes close their file descriptors
 *       associated with the queue. The function will fail if the message queue is still
 *       open by other processes.
 */
sysret_t sys_mq_unlink(const char *name)
{
    int ret = 0;
#ifdef ARCH_MM_MMU
    char *kname = RT_NULL;
    rt_size_t len = 0;

    len = lwp_user_strlen(name);
    if (!len)
        return -EINVAL;
    kname = (char *)kmem_get(len + 1);
    if (!kname)
        return -ENOMEM;

    lwp_get_from_user(kname, (void *)name, len + 1);
    ret = mq_unlink(kname);
    if (ret < 0)
    {
        ret = GET_ERRNO();
    }
    kmem_put(kname);
    return ret;
#else
    ret = mq_unlink(name);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Send a message to a message queue with a timeout.
 *
 * This function sends a message to the specified message queue, but it allows the sender
 * to specify a timeout. If the message queue is full, the function will block until either
 * space becomes available or the specified timeout expires. If the timeout expires without
 * space being available, the function returns an error.
 *
 * @param[in] mqd   The message queue descriptor returned by `sys_mq_open`.
 * @param[in] msg   A pointer to the message to be sent.
 * @param[in] len   The length of the message to send.
 * @param[in] prio  The priority of the message (higher values indicate higher priority).
 * @param[in] at    A pointer to a `timespec` structure that specifies the absolute timeout.
 *                  If the timeout expires before the message can be sent, the function returns
 *                  an error.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error
 *                  code.
 *
 * @note The function uses the `timespec` structure to specify the absolute timeout. The
 *       `at` parameter should indicate the time at which the operation should time out.
 *       If the timeout is `NULL`, the function will not apply any timeout (it will block
 *       indefinitely until the message is sent).
 *
 * @see sys_mq_send
 */
sysret_t sys_mq_timedsend(mqd_t mqd, const char *msg, size_t len, unsigned prio, const struct timespec *at)
{
    int ret = 0;
#ifdef ARCH_MM_MMU
    char *kmsg = RT_NULL;
    struct timespec at_k;

    kmsg = (char *)kmem_get(len + 1);
    if (!kmsg)
        return -ENOMEM;

    lwp_get_from_user(&at_k, (void *)at, sizeof(struct timespec));
    lwp_get_from_user(kmsg, (void *)msg, len + 1);
    ret = mq_timedsend(mqd, kmsg, len, prio, &at_k);
    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    kmem_put(kmsg);

    return ret;
#else
    ret = mq_timedsend(mqd, msg, len, prio, at);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Receive a message from a message queue with a timeout.
 *
 * This function attempts to receive a message from the specified message queue, but it
 * allows the receiver to specify a timeout. If the queue is empty, the function will block
 * until either a message becomes available or the specified timeout expires. If the timeout
 * expires without receiving a message, the function returns an error.
 *
 * @param[in] mqd    The message queue descriptor returned by `sys_mq_open`.
 * @param[out] msg   A pointer to the buffer where the received message will be stored.
 * @param[in] len    The maximum length of the buffer to store the received message.
 * @param[out] prio  A pointer to an unsigned integer that will be set to the priority
 *                   of the received message.
 * @param[in] at     A pointer to a `timespec` structure that specifies the absolute timeout.
 *                   If the timeout expires before a message is received, the function will
 *                   return an error.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note The function uses the `timespec` structure to specify the absolute timeout. The
 *       `at` parameter should indicate the time at which the operation should time out.
 *       If the timeout is `NULL`, the function will block indefinitely until a message is
 *       received.
 *
 * @see sys_mq_receive
 */
sysret_t sys_mq_timedreceive(mqd_t mqd, char *restrict msg, size_t len, unsigned *restrict prio, const struct timespec *restrict at)
{
    int ret = 0;
#ifdef ARCH_MM_MMU
    char *restrict kmsg = RT_NULL;

    struct timespec at_k;

    kmsg = (char *restrict)kmem_get(len + 1);
    if (!kmsg)
        return -ENOMEM;

    lwp_get_from_user(kmsg, (void *)msg, len + 1);
    if (at == RT_NULL)
    {
        ret = mq_timedreceive(mqd, kmsg, len, prio, RT_NULL);
    }
    else
    {
        if (!lwp_get_from_user(&at_k, (void *)at, sizeof(struct timespec)))
            return -EINVAL;
        ret = mq_timedreceive(mqd, kmsg, len, prio, &at_k);
    }

    if (ret > 0)
        lwp_put_to_user(msg, kmsg, len + 1);

    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    kmem_put(kmsg);

    return ret;
#else
    ret = mq_timedreceive(mqd, msg, len, prio, at);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Set up asynchronous notification for a message queue.
 *
 * This function configures asynchronous notification for a message queue. When a message
 * is available in the queue, the system can notify the calling process through a signal
 * or another method specified in the `sigevent` structure. This is typically used to allow
 * a process to be notified when a message arrives without having to block in the receive call.
 *
 * @param[in] mqd  The message queue descriptor returned by `sys_mq_open`.
 * @param[in] sev  A pointer to a `sigevent` structure that specifies the notification
 *                 mechanism to be used when a message is received. It could include
 *                 signals or other notification types such as event flags or message passing.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note This function enables asynchronous notification, but the specific behavior depends
 *       on the configuration specified in the `sev` parameter, which could involve signals
 *       or other forms of notification.
 *
 * @see sys_mq_send, sys_mq_timedreceive
 */
sysret_t sys_mq_notify(mqd_t mqd, const struct sigevent *sev)
{
    int ret = 0;
#ifdef ARCH_MM_MMU
    struct sigevent sev_k;
    lwp_get_from_user(&sev_k, (void *)sev, sizeof(struct timespec));
    ret = mq_notify(mqd, &sev_k);
#else
    ret = mq_notify(mqd, sev);
#endif
    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Get or set attributes of a message queue.
 *
 * This function allows you to get or set the attributes of an existing message queue.
 * If the `new` attribute structure is non-NULL, it updates the message queue with the new
 * attributes. Otherwise, If the `old` attribute structure is non-NULL, it will return the current
 * attributes of the message queue.
 *
 * @param[in] mqd  The message queue descriptor returned by `sys_mq_open`.
 * @param[in] new  A pointer to a `mq_attr` structure containing the new attributes to set.
 *                 If `NULL`, the function will not modify the message queue attributes.
 * @param[out] old A pointer to a `mq_attr` structure where the current message queue
 *                 attributes will be returned. If `NULL`, the current attributes will not
 *                 be returned.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note The `mq_attr` structure contains parameters like the maximum number of messages,
 *       the maximum message size, and other attributes that control the behavior of the
 *       message queue.
 *
 * @see sys_mq_open, sys_mq_notify
 */
sysret_t sys_mq_getsetattr(mqd_t mqd, const struct mq_attr *restrict new, struct mq_attr *restrict old)
{
    int ret = 0;
#ifdef ARCH_MM_MMU
    size_t size = sizeof(struct mq_attr);
    struct mq_attr *restrict knew = NULL;
    struct mq_attr *restrict kold = NULL;

    if (new != RT_NULL)
    {
        if (!lwp_user_accessable((void *)new, size))
            return -EFAULT;
        knew = kmem_get(size);
        if (!knew)
            return -ENOMEM;
        lwp_get_from_user(knew, (void *)new, size);
    }

    if (!lwp_user_accessable((void *)old, size))
        return -EFAULT;
    kold = kmem_get(size);
    if (!kold)
        return -ENOMEM;

    lwp_get_from_user(kold, (void *)old, size);
    ret = mq_setattr(mqd, knew, kold);
    if (ret != -1)
        lwp_put_to_user(old, kold, size);

    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    kmem_put(kold);
    if (new != RT_NULL)
        kmem_put(knew);

    return ret;
#else
    ret = mq_setattr(mqd, new, old);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}

/**
 * @brief Close a message queue descriptor.
 *
 * This function closes a message queue descriptor. After calling this function, the
 * descriptor can no longer be used to interact with the message queue. Any resources
 * associated with the descriptor are released. If the message queue was opened with the
 * `O_CLOEXEC` flag, it will be automatically closed when the calling process executes
 * an `exec` system call.
 *
 * @param[in] mqd  The message queue descriptor to be closed. It was previously returned
 *                 by `sys_mq_open`.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @see sys_mq_open, sys_mq_unlink
 */
sysret_t sys_mq_close(mqd_t mqd)
{
    int ret = 0;
#ifdef ARCH_MM_MMU
    ret = mq_close(mqd);
#else
    ret = mq_close(mqd);
#endif
    return (ret < 0 ? GET_ERRNO() : ret);
}

#define ICACHE (1<<0)
#define DCACHE (1<<1)
#define BCACHE (ICACHE|DCACHE)

/**
 * @brief Flush the cache for a specified memory region.
 *
 * This function flushes the cache for a specified memory region. It is commonly used
 * to ensure that the contents of a memory region are written back to the main memory
 * or that stale cache entries are invalidated. The cache operation can be controlled
 * by the `cache` parameter to determine whether to clean or invalidate the cache.
 *
 * @param[in] addr   The starting address of the memory region to flush.
 * @param[in] size   The size of the memory region to flush, in bytes.
 * @param[in] cache  A flag to specify the cache operation:
 *                   - `CACHE_CLEAN`: Clean the cache (write back to memory).
 *                   - `CACHE_INVALIDATE`: Invalidate the cache (discard cached data).
 *                   - `CACHE_FLUSH`: Both clean and invalidate the cache.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note This function is typically used in low-level operations or in systems where
 *       cache coherence between memory and cache is critical.
 */
rt_weak sysret_t sys_cacheflush(void *addr, int size, int cache)
{
    if (!lwp_user_accessable(addr, size))
        return -EFAULT;

    if (((size_t)addr < (size_t)addr + size) &&
        ((size_t)addr >= USER_VADDR_START) &&
        ((size_t)addr + size < USER_VADDR_TOP))
    {
        if ((cache & DCACHE))
        {
            rt_hw_cpu_dcache_clean_and_invalidate(addr, size);
        }

        if ((cache & ICACHE))
        {
            rt_hw_cpu_icache_invalidate(addr, size);
        }

        return 0;
    }
    return -EFAULT;
}

/**
 * @brief Get system information.
 *
 * This function retrieves information about the current system, such as the system name,
 * version, release, architecture, and other details. The information is stored in the
 * `utsname` structure pointed to by the `uts` parameter.
 *
 * @param[out] uts  A pointer to a `utsname` structure where the system information will
 *                  be stored. The structure includes fields such as:
 *                  - `sysname`: Operating system name.
 *                  - `nodename`: Network node hostname.
 *                  - `release`: Operating system release version.
 *                  - `version`: Operating system version.
 *                  - `machine`: Hardware identifier (architecture).
 *
 * @return sysret_t Returns `SYSRET_OK` (0) on success. On failure, returns a negative error code.
 *
 * @note This function provides details about the system environment, which may be useful
 *       for applications needing to adapt to different system configurations.
 *
 * @see sys_gethostname, sys_uname
 */
sysret_t sys_uname(struct utsname *uts)
{
    struct utsname utsbuff = {0};
    int ret = 0;
    const char *machine;

    if (!lwp_user_accessable((void *)uts, sizeof(struct utsname)))
    {
        return -EFAULT;
    }
    rt_strncpy(utsbuff.sysname, "RT-Thread", sizeof(utsbuff.sysname));
    utsbuff.nodename[0] = '\0';
    ret = rt_snprintf(utsbuff.release, sizeof(utsbuff.release), "%u.%u.%u",
                      RT_VERSION_MAJOR, RT_VERSION_MINOR, RT_VERSION_PATCH);
    if (ret < 0)
    {
        return -EIO;
    }
    ret = rt_snprintf(utsbuff.version, sizeof(utsbuff.version), "RT-Thread %u.%u.%u %s %s",
                      RT_VERSION_MAJOR, RT_VERSION_MINOR, RT_VERSION_PATCH, __DATE__, __TIME__);
    if (ret < 0)
    {
        return -EIO;
    }

    machine = rt_hw_cpu_arch();
    rt_strncpy(utsbuff.machine, machine, sizeof(utsbuff.machine));

    utsbuff.domainname[0] = '\0';
    lwp_put_to_user(uts, &utsbuff, sizeof utsbuff);
    return 0;
}

/**
 * @brief Get filesystem statistics.
 *
 * This function retrieves statistics about the filesystem at the specified path,
 * storing the results in the provided `statfs` structure. It can be used to obtain
 * information such as the total number of blocks, free blocks, available inodes, etc.
 *
 * @param[in]  path  The path to the filesystem to query. If the path is the root directory
 *                   (`"/"`), it returns statistics for the root filesystem.
 * @param[out] buf   A pointer to a `statfs` structure where the filesystem statistics will
 *                   be stored. This structure includes information such as:
 *                   - `f_type`: The type of the filesystem.
 *                   - `f_bsize`: The optimal block size for I/O operations.
 *                   - `f_blocks`: Total number of blocks in the filesystem.
 *                   - `f_bfree`: Number of free blocks.
 *                   - `f_bavail`: Number of free blocks available to non-superuser.
 *                   - `f_files`: Total number of file nodes (inodes).
 *                   - `f_ffree`: Number of free inodes.
 *                   - `f_favail`: Number of inodes available to non-superuser.
 *                   - `f_flag`: Flags describing the filesystem.
 *                   - `f_namelen`: Maximum length of a filename.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note This function is useful for determining the available space and file system
 *       characteristics of a mounted filesystem.
 *
 * @see sys_fstatfs
 */
sysret_t sys_statfs(const char *path, struct statfs *buf)
{
    int ret = 0;
    size_t len;
    size_t copy_len;
    char *copy_path;
    struct statfs statfsbuff = {0};

    if (!lwp_user_accessable((void *)buf, sizeof(struct statfs)))
    {
        return -EFAULT;
    }

    len = lwp_user_strlen(path);
    if (len <= 0)
    {
        return -EFAULT;
    }

    copy_path = (char*)rt_malloc(len + 1);
    if (!copy_path)
    {
        return -ENOMEM;
    }

    copy_len = lwp_get_from_user(copy_path, (void*)path, len);
    if (copy_len == 0)
    {
        rt_free(copy_path);
        return -EFAULT;
    }
    copy_path[copy_len] = '\0';

    ret = _SYS_WRAP(statfs(copy_path, &statfsbuff));
    rt_free(copy_path);

    if (ret == 0)
    {
        lwp_put_to_user(buf, &statfsbuff, sizeof statfsbuff);
    }

    return ret;
}

/**
 * @brief Get extended filesystem statistics (64-bit).
 *
 * This function retrieves extended statistics about the filesystem at the specified path,
 * using 64-bit values for larger filesystems or filesystems with a large number of blocks or inodes.
 * The information is stored in the provided `statfs` structure, which includes details such as total
 * blocks, free blocks, available inodes, etc.
 *
 * @param[in]  path  The path to the filesystem to query. Typically, this would be the root directory
 *                   (`"/"`) for the root filesystem, or any other directory on the filesystem.
 * @param[in]  sz    The size of the `statfs` structure. This parameter allows for future extensions
 *                   of the `statfs` structure without breaking compatibility with older applications.
 * @param[out] buf   A pointer to a `statfs` structure where the extended filesystem statistics
 *                   will be stored. This structure includes information such as:
 *                   - `f_bsize`: The optimal block size for I/O operations.
 *                   - `f_blocks`: Total number of blocks in the filesystem.
 *                   - `f_bfree`: Number of free blocks.
 *                   - `f_bavail`: Number of free blocks available to non-superuser.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note This function is particularly useful for querying large filesystems or filesystems with
 *       64-bit addresses or data values, and is an extended version of the standard `sys_statfs`.
 *
 * @see sys_statfs
 */
sysret_t sys_statfs64(const char *path, size_t sz, struct statfs *buf)
{
    int ret = 0;
    size_t len;
    size_t copy_len;
    char *copy_path;
    struct statfs statfsbuff = {0};

    if (!lwp_user_accessable((void *)buf, sizeof(struct statfs)))
    {
        return -EFAULT;
    }

    if (sz != sizeof(struct statfs))
    {
        return -EINVAL;
    }

    len = lwp_user_strlen(path);
    if (len <= 0)
    {
        return -EFAULT;
    }

    copy_path = (char*)rt_malloc(len + 1);
    if (!copy_path)
    {
        return -ENOMEM;
    }

    copy_len = lwp_get_from_user(copy_path, (void*)path, len);
    if (copy_len == 0)
    {
        rt_free(copy_path);
        return -EFAULT;
    }
    copy_path[copy_len] = '\0';

    ret = _SYS_WRAP(statfs(copy_path, &statfsbuff));
    rt_free(copy_path);

    if (ret == 0)
    {
        lwp_put_to_user(buf, &statfsbuff, sizeof statfsbuff);
    }

    return ret;
}

/**
 * @brief Get filesystem statistics for a file descriptor.
 *
 * This function retrieves statistics about the filesystem containing the file referred to by the
 * file descriptor `fd`. The information is stored in the provided `statfs` structure, which includes
 * details such as total blocks, free blocks, available inodes, etc.
 *
 * @param[in]  fd    The file descriptor referring to an open file. The file descriptor must be
 *                   valid and represent a file on a mounted filesystem.
 * @param[out] buf   A pointer to a `statfs` structure where the filesystem statistics will be
 *                   stored. This structure includes information such as:
 *                   - `f_bsize`: The optimal block size for I/O operations.
 *                   - `f_blocks`: Total number of blocks in the filesystem.
 *                   - `f_bfree`: Number of free blocks.
 *                   - `f_bavail`: Number of free blocks available to non-superuser.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note This function is useful for obtaining filesystem information about a specific file
 *       represented by its file descriptor, rather than querying the filesystem associated with
 *       a specific path.
 *
 * @see sys_statfs
 */
sysret_t sys_fstatfs(int fd, struct statfs *buf)
{
    int ret = 0;
    struct statfs statfsbuff = {0};

    if (!lwp_user_accessable((void *)buf, sizeof(struct statfs)))
    {
        return -EFAULT;
    }

    ret = _SYS_WRAP(fstatfs(fd, &statfsbuff));

    if (ret == 0)
    {
        lwp_put_to_user(buf, &statfsbuff, sizeof statfsbuff);
    }

    return ret;
}

/**
 * @brief Get 64-bit filesystem statistics for a file descriptor.
 *
 * This function retrieves 64-bit statistics about the filesystem containing the file referred to by
 * the file descriptor `fd`. The statistics are stored in the provided `statfs` structure, which
 * includes details such as total blocks, free blocks, available inodes, etc. The function differs
 * from `sys_fstatfs` in that it supports 64-bit values for filesystem sizes and counts.
 *
 * @param[in]  fd    The file descriptor referring to an open file. The file descriptor must be
 *                   valid and represent a file on a mounted filesystem.
 * @param[in]  sz    The size of the `statfs` structure (typically used to ensure compatibility with
 *                   different versions of the structure).
 * @param[out] buf   A pointer to a `statfs` structure where the filesystem statistics will be
 *                   stored. This structure includes information such as:
 *                   - `f_bsize`: The optimal block size for I/O operations.
 *                   - `f_blocks`: Total number of blocks in the filesystem (64-bit).
 *                   - `f_bfree`: Number of free blocks (64-bit).
 *                   - `f_bavail`: Number of free blocks available to non-superuser (64-bit).
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 * @note This function is particularly useful for systems supporting 64-bit filesystem statistics.
 *       It provides extended accuracy for large filesystems, including those with very large
 *       numbers of blocks or inodes.
 *
 * @see sys_fstatfs
 */
sysret_t sys_fstatfs64(int fd, size_t sz, struct statfs *buf)
{
    int ret = 0;
    struct statfs statfsbuff = {0};

    if (!lwp_user_accessable((void *)buf, sizeof(struct statfs)))
    {
        return -EFAULT;
    }

    if (sz != sizeof(struct statfs))
    {
        return -EINVAL;
    }

    ret = _SYS_WRAP(fstatfs(fd, &statfsbuff));

    if (ret == 0)
    {
        lwp_put_to_user(buf, &statfsbuff, sizeof statfsbuff);
    }

    return ret;
}

static char *_cp_from_usr_string(char *dst, char *src, size_t length)
{
    char *rc;
    size_t copied_bytes;
    if (length)
    {
        copied_bytes = lwp_get_from_user(dst, src, length);
        dst[copied_bytes] = '\0';
        rc = dst;
    }
    else
    {
        rc = RT_NULL;
    }
    return rc;
}

/**
 * @brief Mount a filesystem.
 *
 * This function mounts a filesystem onto a specified directory. It allows for mounting various
 * types of filesystems, including but not limited to `ext4`, `nfs`, and `tmpfs`. The function
 * allows the specification of the source device, the target mount point, and additional parameters
 * such as filesystem type, mount flags, and extra data.
 *
 * @param[in]  source        The source of the filesystem, which can be a device (e.g., `/dev/sda1`)
 *                           or a network resource (e.g., a NFS share). For certain filesystems like
 *                           `tmpfs`, this can be `NULL`.
 * @param[in]  target        The target directory where the filesystem will be mounted.
 *                           This should be an existing empty directory.
 * @param[in]  filesystemtype The type of filesystem to mount, e.g., `ext4`, `tmpfs`, `nfs`, etc.
 * @param[in]  mountflags    Flags that control the mount operation, such as `MS_RDONLY` for read-only
 *                           mounts or `MS_NODEV` to prevent device files from being created.
 * @param[in]  data          Optional data that is passed to the filesystem's mount handler. This
 *                           may be used for setting up specific parameters for the filesystem type.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note Mounting a filesystem on an existing mount point can replace the existing filesystem at that
 *       location. Make sure the target directory is empty before mounting to avoid any conflicts.
 */
sysret_t sys_mount(char *source, char *target, char *filesystemtype,
                   unsigned long mountflags, void *data)
{
    char *kbuffer, *ksource, *ktarget, *kfs;
    size_t len_source, len_target, len_fs;
    char *tmp = NULL;
    int ret = 0;
    struct stat buf = {0};
    char *dev_fullpath = RT_NULL;

    len_source = source ? lwp_user_strlen(source) : 0;
    if (len_source < 0)
        return -EINVAL;

    len_target = target ? lwp_user_strlen(target) : 0;
    if (len_target <= 0)
        return -EINVAL;

    len_fs = filesystemtype ? lwp_user_strlen(filesystemtype) : 0;
    if (len_fs < 0)
        return -EINVAL;

    kbuffer = (char *)rt_malloc(len_source + 1 + len_target + 1 + len_fs + 1);
    if (!kbuffer)
    {
        return -ENOMEM;
    }

    /* get parameters from user space */
    ksource = kbuffer;
    ktarget = ksource + len_source + 1;
    kfs = ktarget + len_target + 1;
    ksource = _cp_from_usr_string(ksource, source, len_source);
    ktarget = _cp_from_usr_string(ktarget, target, len_target);
    kfs = _cp_from_usr_string(kfs, filesystemtype, len_fs);

    if (mountflags & MS_REMOUNT)
    {
        ret = dfs_remount(ktarget, mountflags, data);
    }
    else
    {
        if (strcmp(kfs, "nfs") == 0)
        {
            tmp = ksource;
            ksource = NULL;
        }
        if (strcmp(kfs, "tmp") == 0)
        {
            ksource = NULL;
        }

        if (ksource && !dfs_file_stat(ksource, &buf) && S_ISBLK(buf.st_mode))
        {
            dev_fullpath = dfs_normalize_path(RT_NULL, ksource);
            RT_ASSERT(rt_strncmp(dev_fullpath, "/dev/", sizeof("/dev/") - 1) == 0);
            ret = dfs_mount(dev_fullpath + sizeof("/dev/") - 1, ktarget, kfs, 0, tmp);
        }
        else
        {
            ret = dfs_mount(ksource, ktarget, kfs, 0, tmp);
        }

        if (ret < 0)
        {
            ret = -rt_get_errno();
        }
    }

    rt_free(kbuffer);
    rt_free(dev_fullpath);
    return ret;
}

/**
 * @brief Unmount a filesystem.
 *
 * This function unmounts a previously mounted filesystem from a specified target directory or file.
 * It removes the filesystem from the system, making the resources associated with it available for
 * other uses. It can also support additional flags to control the unmounting behavior.
 *
 * @param[in]  __special_file The target directory or mount point from which the filesystem is to be
 *                            unmounted. This should be a valid mount point that was previously mounted.
 * @param[in]  __flags        Flags that control the unmounting behavior. Common flags include:
 *                            - `MNT_FORCE`: Forces the unmount even if the filesystem is busy.
 *                            - `MNT_DETACH`: Detaches the filesystem, allowing it to be unmounted
 *                              asynchronously.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note The `MNT_FORCE` flag should be used with caution, as it may result in data loss or corruption
 *       if there are pending writes or active processes using the filesystem.
 *
 * @see sys_mount
 */
sysret_t sys_umount2(char *__special_file, int __flags)
{
    char *copy_special_file;
    size_t len_special_file, copy_len_special_file;
    int ret = 0;

    len_special_file = lwp_user_strlen(__special_file);
    if (len_special_file <= 0)
    {
        return -EFAULT;
    }

    copy_special_file = (char*)rt_malloc(len_special_file + 1);
    if (!copy_special_file)
    {
        return -ENOMEM;
    }

    copy_len_special_file = lwp_get_from_user(copy_special_file, __special_file, len_special_file);
    copy_special_file[copy_len_special_file] = '\0';

    ret = dfs_unmount(copy_special_file);
    rt_free(copy_special_file);

    return ret;
}

/**
 * @brief Create a new hard link to an existing file.
 *
 * This function creates a new hard link to an existing file, making the file accessible from
 * multiple filenames. The new link points to the same inode as the existing file, meaning
 * both names refer to the same underlying data. The link count for the file is incremented.
 *
 * @param[in]  existing The path to the existing file. It must be an absolute or relative path
 *                      to a file that already exists.
 * @param[in]  new      The path to the new link to be created. This can be a new filename or
 *                      an existing directory where the link will be placed.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note Hard links share the same inode number, meaning changes to the data of the file via one
 *       link will be reflected in all hard links. Deleting any of the links will not remove the
 *       file data until all links are deleted.
 */
sysret_t sys_link(const char *existing, const char *new)
{
    int ret = -1;
    int err = 0;
#ifdef RT_USING_DFS_V2
#ifdef ARCH_MM_MMU
    int len = 0;
    char *kexisting = RT_NULL;
    char *knew = RT_NULL;

    len = lwp_user_strlen(existing);
    if (len <= 0)
    {
        return -EFAULT;
    }

    kexisting = (char *)kmem_get(len + 1);
    if (!kexisting)
    {
        return -ENOMEM;
    }

    if (lwp_get_from_user(kexisting, (void *)existing, len + 1) != (len + 1))
    {
        kmem_put(kexisting);
        return -EINVAL;
    }

    len = lwp_user_strlen(new);
    if (len <= 0)
    {
        kmem_put(kexisting);
        return -EFAULT;
    }

    knew = (char *)kmem_get(len + 1);
    if (!knew)
    {
        kmem_put(kexisting);
        return -ENOMEM;
    }

    if (lwp_get_from_user(knew, (void *)new, len + 1) != (len + 1))
    {
        kmem_put(knew);
        kmem_put(kexisting);
        return -EINVAL;
    }

    ret = dfs_file_link(kexisting, knew);
    if(ret  < 0)
    {
        err = GET_ERRNO();
    }

    kmem_put(knew);
    kmem_put(kexisting);
#else
    ret = dfs_file_link(existing, new);
#endif
#else
    SET_ERRNO(EFAULT);
    err = GET_ERRNO();
#endif

    return (err < 0 ? err : ret);
}

/**
 * @brief Create a symbolic link to an existing file or directory.
 *
 * This function creates a new symbolic link, which is a special file that contains a reference
 * to another file or directory. The symbolic link allows for easy redirection or aliasing of
 * file paths. Unlike a hard link, a symbolic link can point to a file or directory across
 * different file systems.
 *
 * @param[in]  existing The path to the existing file or directory that the symbolic link
 *                      will refer to. It must be an absolute or relative path.
 * @param[in]  new      The path to the new symbolic link to be created. This must be a valid
 *                      path where the link will be placed.
 *
 * @return sysret_t Returns `0` on success. On failure, returns a negative error code.
 *
 * @note A symbolic link is distinct from a hard link in that it points to the path of the target
 *       file or directory, rather than directly to the inode. If the target file or directory is
 *       removed or moved, the symbolic link will become "broken" and will not resolve to a valid
 *       location.
 */
sysret_t sys_symlink(const char *existing, const char *new)
{
    int ret = -1;
    int err = 0 ;
#ifdef ARCH_MM_MMU

    ret = lwp_user_strlen(existing);
    if (ret <= 0)
    {
        return -EFAULT;
    }

    ret = lwp_user_strlen(new);
    if (ret <= 0)
    {
        return -EFAULT;
    }
#endif
#ifdef RT_USING_DFS_V2
    ret = dfs_file_symlink(existing, new);
    if(ret < 0)
    {
        err = GET_ERRNO();
    }
#else
    SET_ERRNO(EFAULT);
#endif
    return (err < 0 ? err : ret);
}

/**
 * @brief Create an event file descriptor.
 *
 * This function creates an eventfd, which is a file descriptor used for event notification.
 * Eventfd is a simple mechanism to notify threads or processes about certain events using
 * an integer counter. It is typically used for inter-process communication (IPC) or
 * synchronization purposes, where one thread or process increments the counter to signal
 * another thread or process.
 *
 * @param[in] count  Initial value for the eventfd counter. It can be set to a non-zero
 *                   value to initialize the counter to that value.
 * @param[in] flags  Flags that control the behavior of the eventfd. Valid flags include:
 *                   - `EFD_CLOEXEC`: Set the close-on-exec flag for the eventfd.
 *                   - `EFD_NONBLOCK`: Set the non-blocking flag for the eventfd.
 *
 * @return sysret_t On success, returns a valid file descriptor referring to the eventfd. On
 *                  failure, returns a negative error code.
 *
 * @note Eventfd can be used for both counting and signaling purposes. It provides
 *       efficient signaling between threads or processes.
 */
sysret_t sys_eventfd2(unsigned int count, int flags)
{
    int ret;

    ret = eventfd(count, flags);
    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Create an epoll instance.
 *
 * This function creates an epoll instance, which is used for monitoring multiple file descriptors
 * to see if I/O is possible on them. It allows a program to efficiently wait for events such as
 * data being available for reading or space becoming available for writing. Epoll provides a scalable
 * mechanism for managing large numbers of file descriptors.
 *
 * @param[in] flags  Flags that control the behavior of the epoll instance. The valid flags include:
 *                   - `EPOLL_CLOEXEC`: Set the close-on-exec flag for the epoll instance.
 *                   - `EPOLL_NONBLOCK`: Set the non-blocking flag for the epoll instance.
 *
 * @return sysret_t On success, returns a file descriptor for the epoll instance. On failure,
 *                  returns a negative error code.
 *
 * @note The `sys_epoll_create1` function is similar to `sys_epoll_create`, but it allows for
 *       additional control over the epoll instance creation via flags.
 */
sysret_t sys_epoll_create1(int flags)
{
    int ret;

    ret = epoll_create(flags);

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Control an epoll instance.
 *
 * This function performs control operations on an epoll instance, such as adding, modifying,
 * or removing file descriptors from the epoll instance's interest list.
 *
 * @param[in] fd    The file descriptor of the epoll instance created using `sys_epoll_create` or `sys_epoll_create1`.
 * @param[in] op    The operation to perform on the epoll instance. It can be one of the following:
 *                  - `EPOLL_CTL_ADD`: Add the specified file descriptor to the epoll interest list.
 *                  - `EPOLL_CTL_MOD`: Modify the event mask of an existing file descriptor in the epoll interest list.
 *                  - `EPOLL_CTL_DEL`: Remove the specified file descriptor from the epoll interest list.
 * @param[in] fd2   The file descriptor to be added, modified, or removed from the epoll interest list.
 * @param[in] ev    A pointer to an `epoll_event` structure that describes the event to be associated with `fd2`.
 *                  This parameter is required for `EPOLL_CTL_ADD` and `EPOLL_CTL_MOD`, but not for `EPOLL_CTL_DEL`.
 *
 * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
 *
 * @note This function is typically used to manage the set of file descriptors monitored by an epoll instance.
 */
sysret_t sys_epoll_ctl(int fd, int op, int fd2, struct epoll_event *ev)
{
    int ret = 0;
    struct epoll_event *kev = RT_NULL;

    if (ev)
    {
        if (!lwp_user_accessable((void *)ev, sizeof(struct epoll_event)))
        return -EFAULT;

        kev = kmem_get(sizeof(struct epoll_event));
        if (kev == RT_NULL)
        {
            return -ENOMEM;
        }

        if (lwp_get_from_user(kev, ev, sizeof(struct epoll_event)) != sizeof(struct epoll_event))
        {
            kmem_put(kev);
            return -EINVAL;
        }

        ret = epoll_ctl(fd, op, fd2, kev);

        kmem_put(kev);
    }
    else
    {
         ret = epoll_ctl(fd, op, fd2, RT_NULL);
    }

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Wait for events on an epoll file descriptor, with the ability to block for specific signals.
 *
 * This function waits for events on an epoll file descriptor. It blocks until one or more events
 * are available or a timeout occurs. In addition to waiting for events, it can also block for specific signals
 * as specified by the `sigs` argument.
 *
 * @param[in] fd          The file descriptor of the epoll instance, created using `sys_epoll_create` or `sys_epoll_create1`.
 * @param[out] ev         A pointer to an array of `epoll_event` structures that will receive the events that have occurred.
 * @param[in] cnt         The maximum number of events to return. This specifies the size of the `ev` array.
 * @param[in] to          The timeout in milliseconds. A negative value means no timeout, and `0` means non-blocking.
 * @param[in] sigs        A pointer to a signal set (`sigset_t`) that specifies the signals to block during the wait.
 *                        If `NULL`, no signals are blocked.
 * @param[in] sigsetsize  The size of the signal set (`sigs`) in bytes. This should be the size of `sigset_t` if `sigs` is not `NULL`.
 *
 * @return sysret_t On success, returns the number of events returned (may be `0` if the timeout expires with no events).
 *                  On failure, returns a negative error code.
 *
 * @note This function is similar to `sys_epoll_wait`, but it also allows for signal handling, blocking the calling thread
 *       from receiving signals specified in the `sigs` set while waiting for events.
 */
sysret_t sys_epoll_pwait(int fd,
        struct epoll_event *ev,
        int cnt,
        int to,
        const sigset_t *sigs,
        unsigned long sigsetsize)
{
    int ret = 0;
    struct epoll_event *kev = RT_NULL;
    sigset_t *ksigs = RT_NULL;

    if (!lwp_user_accessable((void *)ev, cnt * sizeof(struct epoll_event)))
        return -EFAULT;

    kev = kmem_get(cnt * sizeof(struct epoll_event));
    if (kev == RT_NULL)
    {
        return -ENOMEM;
    }

    if (sigs != RT_NULL)
    {
        if (!lwp_user_accessable((void *)sigs, sizeof(sigset_t)))
        {
            kmem_put(kev);
            return -EFAULT;
        }

        ksigs = kmem_get(sizeof(sigset_t));
        if (ksigs == RT_NULL)
        {
            kmem_put(kev);
            return -ENOMEM;
        }

        if (lwp_get_from_user(ksigs, (void *)sigs, sizeof(sigset_t)) != sizeof(sigset_t))
        {
            kmem_put(kev);
            kmem_put(ksigs);
            return -EINVAL;
        }
    }

    ret = epoll_pwait(fd, kev, cnt, to, ksigs);

    if (ret > 0)
    {
        lwp_put_to_user((void *)ev, kev, ret * sizeof(struct epoll_event));
    }

    if (sigs != RT_NULL)
        kmem_put(ksigs);

    kmem_put(kev);

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Truncate a file to a specified length.
 *
 * This function resizes the file associated with the given file descriptor `fd` to the specified length.
 * If the current size of the file is greater than the specified length, the file is truncated. If the file is smaller,
 * it is extended, and the new space is initialized to zero.
 *
 * @param[in] fd       The file descriptor referring to the file to truncate. This must be a valid open file descriptor.
 * @param[in] length   The new length of the file. The file will be truncated or extended to this size.
 *
 * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
 *
 * @note The file descriptor `fd` must be opened with write permissions for this operation to succeed.
 */
sysret_t sys_ftruncate(int fd, size_t length)
{
    int ret;

    ret = ftruncate(fd, length);

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Set file access and modification times.
 *
 * This function updates the access and modification times of a file or directory referenced by `__fd` or `__path`.
 * If `__fd` is a valid file descriptor, the times will be applied to the file or directory it refers to.
 * If `__fd` is `AT_FDCWD`, the times will be applied to the file or directory specified by `__path`.
 * The `__times` argument consists of two `timespec` values: the first represents the access time,
 * and the second represents the modification time. If `__times` is `NULL`, the current time is used.
 *
 * @param[in] __fd       The file descriptor of the file or directory to modify, or `AT_FDCWD` to modify using `__path`.
 * @param[in] __path     The path to the file or directory to modify. Ignored if `__fd` is not `AT_FDCWD`.
 * @param[in] __times    An array of two `timespec` structures. The first element is the access time, and the second is the modification time.
 *                       If `__times` is `NULL`, the current time is used for both access and modification times.
 * @param[in] __flags    Flags to modify behavior. Supported flags include:
 *                       - `AT_SYMLINK_NOFOLLOW`: Do not follow symbolic links.
 *                       - `AT_NO_AUTOMOUNT`: Do not trigger automounting.
 *
 * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
 *
 * @note This function modifies both access and modification times of files, and may affect file system timestamps.
 */
sysret_t sys_utimensat(int __fd, const char *__path, const struct timespec __times[2], int __flags)
{
#ifdef RT_USING_DFS_V2
#ifdef ARCH_MM_MMU
    int ret = -1;
    rt_size_t len = 0;
    char *kpath = RT_NULL;

    len = lwp_user_strlen(__path);
    if (len <= 0)
    {
        return -EINVAL;
    }

    kpath = (char *)kmem_get(len + 1);
    if (!kpath)
    {
        return -ENOMEM;
    }

    lwp_get_from_user(kpath, (void *)__path, len + 1);
    ret = utimensat(__fd, kpath, __times, __flags);

    kmem_put(kpath);

    return ret;
#else
    if (!lwp_user_accessable((void *)__path, 1))
    {
        return -EFAULT;
    }
    int ret = utimensat(__fd, __path, __times, __flags);
    return ret;
#endif
#else
    return -1;
#endif
}

/**
 * @brief Change file permissions.
 *
 * This function changes the permissions of a file or directory specified by the `pathname`.
 * The new permissions are specified using the `mode` argument, which is a bitwise OR of permission bits.
 * The permissions apply to the file owner, group, and others, depending on the value of `mode`.
 *
 * @param[in] pathname  The path to the file or directory whose permissions are to be changed.
 * @param[in] mode      The new permissions to set, represented as a bitwise OR of permission flags.
 *                      For example, `S_IRUSR`, `S_IWUSR`, `S_IRGRP`, etc.
 *
 * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
 *
 * @note If the file or directory is a symbolic link, this function will modify the permissions of the symbolic link itself,
 *       not the target file or directory.
 */
sysret_t sys_chmod(const char *pathname, mode_t mode)
{
    char *copy_file;
    size_t len_file, copy_len_file;
    struct dfs_attr attr = {0};
    int ret = 0;

    len_file = lwp_user_strlen(pathname);
    if (len_file <= 0)
    {
        return -EFAULT;
    }

    copy_file = (char*)rt_malloc(len_file + 1);
    if (!copy_file)
    {
        return -ENOMEM;
    }

    copy_len_file = lwp_get_from_user(copy_file, (void *)pathname, len_file);

    attr.st_mode = mode;
    attr.ia_valid |= ATTR_MODE_SET;

    copy_file[copy_len_file] = '\0';
    ret = dfs_file_setattr(copy_file, &attr);
    rt_free(copy_file);

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Change the ownership of a file or directory.
 *
 * This function changes the owner and/or group of the file or directory specified by `pathname`.
 * The `owner` and `group` parameters represent the new owner and group IDs, respectively. If either
 * parameter is set to `-1`, that aspect (owner or group) will remain unchanged.
 *
 * @param[in] pathname  The path to the file or directory whose ownership is to be changed.
 * @param[in] owner     The new owner ID. If set to `-1`, the owner's ID is not changed.
 * @param[in] group     The new group ID. If set to `-1`, the group's ID is not changed.
 *
 * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
 *
 * @note The caller must have the appropriate permissions (i.e., be the superuser or the file owner)
 *       to change the ownership of a file or directory.
 */
sysret_t sys_chown(const char *pathname, uid_t owner, gid_t group)
{
    char *copy_file;
    size_t len_file, copy_len_file;
    struct dfs_attr attr = {0};
    int ret = 0;

    len_file = lwp_user_strlen(pathname);
    if (len_file <= 0)
    {
        return -EFAULT;
    }

    copy_file = (char*)rt_malloc(len_file + 1);
    if (!copy_file)
    {
        return -ENOMEM;
    }

    copy_len_file = lwp_get_from_user(copy_file, (void *)pathname, len_file);

    if(owner >= 0)
    {
        attr.st_uid = owner;
        attr.ia_valid |= ATTR_UID_SET;
    }

    if(group >= 0)
    {
        attr.st_gid = group;
        attr.ia_valid |= ATTR_GID_SET;
    }

    copy_file[copy_len_file] = '\0';
    ret = dfs_file_setattr(copy_file, &attr);
    rt_free(copy_file);

    return (ret < 0 ? GET_ERRNO() : ret);
}

#ifndef LWP_USING_RUNTIME
sysret_t lwp_teardown(struct rt_lwp *lwp, void (*cb)(void))
{
    /* if no LWP_USING_RUNTIME configured */
    return -ENOSYS;
}
#endif

/**
 * @brief Reboot the system.
 *
 * This function initiates a system reboot with a specific reboot type and optional arguments.
 * The reboot process is performed by passing `magic` and `magic2` as security keys to validate the
 * reboot request, along with the desired reboot type (`type`) and optional argument (`arg`) that
 * may contain additional parameters depending on the reboot type.
 *
 * @param[in] magic   A magic number for security validation, typically used to verify that the caller
 *                    has sufficient privileges (e.g., root).
 * @param[in] magic2  A second magic number for additional security verification, used in combination
 *                    with `magic` to validate the reboot request.
 * @param[in] type    The type of reboot to perform, such as `RB_AUTOBOOT`, `RB_HALT`, `RB_RESTART`,
 *                    etc. The exact values may depend on the platform.
 * @param[in] arg     An optional argument for the reboot process. This can provide additional data,
 *                    such as a specific shutdown procedure, depending on the type of reboot.
 *
 * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
 *
 * @note This operation is typically available to the system administrator (root) and should be used
 *       with caution as it can cause the system to restart or shut down.
 */
sysret_t sys_reboot(int magic, int magic2, int type, void *arg)
{
    sysret_t rc;
    switch (type)
    {
        /* Hardware reset */
        case RB_AUTOBOOT:
            rc = lwp_teardown(lwp_self(), rt_hw_cpu_reset);
            break;

        /* Stop system and switch power off */
        case RB_POWER_OFF:
            rc = lwp_teardown(lwp_self(), rt_hw_cpu_shutdown);
            break;
        default:
            rc = -ENOSYS;
    }

    return rc;
}

/**
 * @brief Read data from a file descriptor at a specific offset.
 *
 * This function reads data from a file descriptor `fd` into the buffer `buf`, starting from the
 * specified byte `offset`. Unlike a regular `read` call, `sys_pread64` allows the file pointer to
 * remain unchanged after the read, as the operation directly accesses the file at the provided
 * offset.
 *
 * @param[in] fd      The file descriptor from which to read. It must be a valid open file descriptor.
 * @param[out] buf    A pointer to the buffer where the read data will be stored.
 * @param[in] size    The number of bytes to read from the file.
 * @param[in] offset  The offset in bytes from the beginning of the file to start reading from.
 *
 * @return ssize_t On success, returns the number of bytes read (which may be less than `size` if
 *                  the end of the file is reached). On error, returns a negative error code.
 *
 * @note This function is particularly useful for random access to files, allowing for efficient
 *       reads from arbitrary positions without affecting the current file pointer.
 */
ssize_t sys_pread64(int fd, void *buf, int size, size_t offset)
#ifdef RT_USING_DFS_V2
{
    ssize_t pread(int fd, void *buf, size_t len, size_t offset);
#ifdef ARCH_MM_MMU
    ssize_t ret = -1;
    void *kmem = RT_NULL;

    if (!size)
    {
        return -EINVAL;
    }

    if (!lwp_user_accessable((void *)buf, size))
    {
        return -EFAULT;
    }
    kmem = kmem_get(size);
    if (!kmem)
    {
        return -ENOMEM;
    }

    ret = pread(fd, kmem, size, offset);
    if (ret > 0)
    {
        lwp_put_to_user(buf, kmem, ret);
    }

    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    kmem_put(kmem);

    return ret;
#else
    if (!lwp_user_accessable((void *)buf, size))
    {
        return -EFAULT;
    }

    ssize_t ret = pread(fd, kmem, size, offset);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}
#else
{
    ssize_t ret = -ENOSYS;
    return (ret < 0 ? GET_ERRNO() : ret);
}
#endif

/**
 * @brief Write data to a file descriptor at a specific offset.
 *
 * This function writes data from the buffer `buf` to the file descriptor `fd`, starting at the
 * specified byte `offset`. Unlike a regular `write` call, `sys_pwrite64` allows the file pointer to
 * remain unchanged after the write, as the operation directly writes the data to the file at the
 * provided offset.
 *
 * @param[in] fd      The file descriptor to which the data will be written. It must be a valid open
 *                    file descriptor.
 * @param[in] buf     A pointer to the buffer containing the data to be written.
 * @param[in] size    The number of bytes to write to the file.
 * @param[in] offset  The offset in bytes from the beginning of the file to start writing to.
 *
 * @return ssize_t On success, returns the number of bytes written (which may be less than `size` if
 *                  the write operation is partial). On error, returns a negative error code.
 *
 * @note This function is particularly useful for random access to files, allowing for efficient
 *       writes to arbitrary positions without affecting the current file pointer.
 */
ssize_t sys_pwrite64(int fd, void *buf, int size, size_t offset)
#ifdef RT_USING_DFS_V2
{
    ssize_t pwrite(int fd, const void *buf, size_t len, size_t offset);
#ifdef ARCH_MM_MMU
    ssize_t ret = -1;
    void *kmem = RT_NULL;

    if (!size)
    {
        return -EINVAL;
    }

    if (!lwp_user_accessable((void *)buf, size))
    {
        return -EFAULT;
    }
    kmem = kmem_get(size);
    if (!kmem)
    {
        return -ENOMEM;
    }

    lwp_get_from_user(kmem, (void *)buf, size);

    ret = pwrite(fd, kmem, size, offset);
    if (ret < 0)
    {
        ret = GET_ERRNO();
    }

    kmem_put(kmem);

    return ret;
#else
    if (!lwp_user_accessable((void *)buf, size))
    {
        return -EFAULT;
    }

    ssize_t ret = pwrite(fd, kmem, size, offset);
    return (ret < 0 ? GET_ERRNO() : ret);
#endif
}
#else
{
    ssize_t ret = -ENOSYS;
    return (ret < 0 ? GET_ERRNO() : ret);
}
#endif

/**
 * @brief Create a timer file descriptor.
 *
 * This function creates a timer that can be used to notify a process after a specified
 * amount of time has passed. The timer is represented by a file descriptor, which can be
 * used with functions such as `read` and `poll` to monitor and retrieve notifications
 * about timer expirations.
 *
 * @param[in] clockid The clock to use for the timer. Possible values include:
 *                    - `CLOCK_REALTIME`: The system's real-time clock.
 *                    - `CLOCK_MONOTONIC`: A clock that cannot be set and is not affected by
 *                      changes in the system time.
 * @param[in] flags   Flags that modify the behavior of the timer. The commonly used values are:
 *                    - `TFD_CLOEXEC`: Set the close-on-exec flag for the file descriptor.
 *                    - `TFD_NONBLOCK`: Set the non-blocking flag for the file descriptor.
 *
 * @return sysret_t On success, returns a non-negative file descriptor that refers to the timer.
 *                   On failure, returns a negative error code.
 *
 * @note The timer created by this function can be used to create periodic or one-shot timers.
 *       The timer can be configured using `timerfd_settime` and notifications can be retrieved
 *       by reading from the returned file descriptor.
 */
sysret_t sys_timerfd_create(int clockid, int flags)
{
    int ret;

    ret = timerfd_create(clockid, flags);

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Set or modify the expiration time for a timer.
 *
 * This function is used to arm or re-arm a timer associated with a file descriptor created
 * by `sys_timerfd_create`. It allows setting a new expiration time and can also return
 * the previous timer configuration.
 *
 * @param[in] fd     The file descriptor referring to the timer, which was created using
 *                   `sys_timerfd_create`.
 * @param[in] flags  Flags that modify the behavior of the timer. The commonly used values are:
 *                   - `TFD_TIMER_ABSTIME`: If set, the `new` expiration time is an absolute time.
 *                   - `TFD_TIMER_RELATIVE`: The default behavior, where `new` expiration time is
 *                     a relative time from now.
 * @param[in] new    A pointer to a `struct itimerspec` specifying the new expiration time.
 *                   It contains two fields:
 *                   - `it_value`: The initial expiration time of the timer.
 *                   - `it_interval`: The period of periodic timers (if zero, the timer is one-shot).
 * @param[out] old   A pointer to a `struct itimerspec` where the previous timer configuration
 *                   will be stored. This can be `NULL` if the previous configuration is not needed.
 *
 * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
 *
 * @note This function allows for both one-shot and periodic timers. If the timer is periodic,
 *       it will continue triggering at intervals specified in `it_interval` until canceled or modified.
 *       When a timer expires, the associated file descriptor becomes readable, and the application
 *       can retrieve the expiration event by reading from the file descriptor.
 */
sysret_t sys_timerfd_settime(int fd, int flags, const struct itimerspec *new, struct itimerspec *old)
{
    int ret = -1;
    struct itimerspec *knew = RT_NULL;
    struct itimerspec *kold = RT_NULL;

    if (new == RT_NULL)
        return -EINVAL;

    if (!lwp_user_accessable((void *)new, sizeof(struct itimerspec)))
    {
        return -EFAULT;
    }

    knew = kmem_get(sizeof(struct itimerspec));

    if (knew)
    {
        lwp_get_from_user(knew, (void*)new, sizeof(struct itimerspec));

        if (old)
        {
            if (!lwp_user_accessable((void *)old, sizeof(struct itimerspec)))
            {
                kmem_put(knew);
                return -EFAULT;
            }

            kold = kmem_get(sizeof(struct itimerspec));
            if (kold == RT_NULL)
            {
                kmem_put(knew);
                return -ENOMEM;
            }
        }

        ret = timerfd_settime(fd, flags, knew, kold);

        if (old)
        {
            lwp_put_to_user(old, kold, sizeof(*kold));
            kmem_put(kold);
        }

        kmem_put(knew);
    }

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Retrieve the current configuration of a timer.
 *
 * This function is used to obtain the current expiration time and interval of a timer associated
 * with a file descriptor created by `sys_timerfd_create`. It allows querying the current state
 * of the timer, including the time remaining until the next expiration and the period (for periodic timers).
 *
 * @param[in] fd    The file descriptor referring to the timer, which was created using
 *                  `sys_timerfd_create`.
 * @param[out] cur  A pointer to a `struct itimerspec` where the current timer configuration will
 *                  be stored. This structure contains:
 *                  - `it_value`: The time remaining until the timer expires.
 *                  - `it_interval`: The period for periodic timers (zero for one-shot timers).
 *
 * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
 *
 * @note The timer's `it_value` field will contain the time remaining until the next expiration.
 *       If the timer is periodic, the `it_interval` field will contain the period for the next expiration.
 *       If the timer has expired and there is no further interval (for one-shot timers), `it_value` will
 *       contain a value of `0`.
 */
sysret_t sys_timerfd_gettime(int fd, struct itimerspec *cur)
{
    int ret = -1;
    struct itimerspec *kcur;

    if (cur == RT_NULL)
        return -EINVAL;

    if (!lwp_user_accessable((void *)cur, sizeof(struct itimerspec)))
    {
        return -EFAULT;
    }

    kcur = kmem_get(sizeof(struct itimerspec));

    if (kcur)
    {
        lwp_get_from_user(kcur, cur, sizeof(struct itimerspec));
        ret = timerfd_gettime(fd, kcur);
        lwp_put_to_user(cur, kcur, sizeof(struct itimerspec));
        kmem_put(kcur);
    }

    return (ret < 0 ? GET_ERRNO() : ret);
}

/**
 * @brief Create a file descriptor for receiving signals.
 *
 * This function creates a file descriptor that can be used to receive signals, similar to how a
 * regular file descriptor is used. The signals specified in the provided signal mask are blocked
 * for the calling thread, and any matching signals will be reported through the file descriptor.
 * This allows signals to be handled in a more controlled, non-interrupt-driven way by using
 * standard I/O operations (e.g., `read()` or `select()`) on the file descriptor.
 *
 * @param[in] fd    A file descriptor associated with the process, typically obtained from
 *                  `sys_signalfd()` or a similar mechanism. If `fd` is `-1`, a new file descriptor
 *                  will be created.
 * @param[in] mask  A pointer to the signal mask (`sigset_t`) that specifies the signals that
 *                  should be received by the file descriptor. Only signals in the mask will be
 *                  reported.
 * @param[in] flags Additional flags to control the behavior of the signalfd. Common flags
 *                  include `O_NONBLOCK` for non-blocking operation.
 *
 * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
 *
 * @note The caller must call `read()` on the resulting file descriptor to actually receive signals.
 *       Each read returns a `struct signalfd_siginfo` containing the signal number, and additional
 *       information, such as the signal source and sender.
 *
 * @see sys_read(), sigprocmask(), sigaction(), sigsuspend().
 */
sysret_t sys_signalfd(int fd, const sigset_t *mask, int flags)
{
    int ret = 0;
    sigset_t *kmask = RT_NULL;

#ifdef RT_USING_MUSLLIBC
    if (mask == RT_NULL)
        return -EINVAL;

    if (!lwp_user_accessable((void *)mask, sizeof(struct itimerspec)))
    {
        return -EFAULT;
    }

    kmask = kmem_get(sizeof(struct itimerspec));

    if (kmask)
    {
        if (lwp_get_from_user(kmask, (void *)mask, sizeof(struct itimerspec)) != sizeof(struct itimerspec))
        {
            kmem_put(kmask);
            return -EFAULT;
        }

        ret = signalfd(fd, mask, flags);
        kmem_put(kmask);
    }
#endif

    return (ret < 0 ? GET_ERRNO() : ret);
}

sysret_t sys_memfd_create()
{
    return 0;
}

/**
 * @brief Set the value of an interval timer.
 *
 * This function is used to set the value of a specified timer that generates periodic signals
 * after the specified intervals. The timer can be configured to generate a signal when it expires,
 * and it can be used for tasks like scheduling periodic events.
 *
 * @param[in] which Specifies which timer to set. Possible values include:
 *                  - `ITIMER_REAL`: Timer that decrements in real time and sends `SIGALRM` when expired.
 *                  - `ITIMER_VIRTUAL`: Timer that decrements only while the process is executing.
 *                  - `ITIMER_PROF`: Timer that decrements while the process is executing or when it is
 *                    executing in the kernel.
 * @param[in] new A pointer to a `struct itimerspec` containing the new value for the timer.
 *                The `itimerspec` structure contains two `timespec` fields: `it_value` for the initial
 *                expiration time and `it_interval` for the interval between successive expirations.
 * @param[out] old A pointer to a `struct itimerspec` where the previous timer values (before the
 *                 timer is set) will be stored.
 *
 * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
 *
 * @note If the specified timer is already active, it will be updated with the new values. The timer
 *       will start at the `it_value` time and will repeat at the interval specified in `it_interval`.
 *       If `it_interval` is set to `0`, the timer will not repeat and will only expire once.
 *
 * @see sys_getitimer(), sigaction(), alarm(), setitimer().
 */
sysret_t sys_setitimer(int which, const struct itimerspec *restrict new, struct itimerspec *restrict old)
{
    sysret_t rc = 0;
    rt_lwp_t lwp = lwp_self();
    struct itimerspec new_value_k;
    struct itimerspec old_value_k;

    if (lwp_get_from_user(&new_value_k, (void *)new, sizeof(*new)) != sizeof(*new))
    {
        return -EFAULT;
    }

    rc = lwp_signal_setitimer(lwp, which, &new_value_k, &old_value_k);
    if (old && lwp_put_to_user(old, (void *)&old_value_k, sizeof old_value_k) != sizeof old_value_k)
        return -EFAULT;

    return rc;
}

/**
 * @brief Set the robust list for the current thread.
 *
 * The `sys_set_robust_list` function sets the robust list for the calling thread. The robust list is
 * a list of `struct robust_list_head` elements that contain information about mutexes or other
 * resources that need to be cleaned up if the thread dies unexpectedly.
 *
 * This function is typically used for thread safety in multi-threaded programs, where robust mutexes
 * can be used to avoid leaving resources in an inconsistent state when a thread is terminated
 * without properly unlocking locks or releasing resources.
 *
 * @param[in] head A pointer to the robust list to be set. This list contains `struct robust_list_head`
 *                 entries which are used by the kernel to maintain information about robust mutexes.
 * @param[in] len The length of the robust list (the number of entries in the list). This should correspond
 *                to the size of the list in memory, generally expressed in bytes.
 *
 * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
 *
 * @note The robust list should be set during the initialization of a thread or task, and it may be
 *       used by the kernel to track which mutexes need to be cleaned up in case of failure.
 *       The list may be manipulated using related functions such as `sys_get_robust_list`.
 *
 * @see sys_get_robust_list(), robust_mutex, pthread_mutex, set_robust_list.
 */
sysret_t sys_set_robust_list(struct robust_list_head *head, size_t len)
{
    if (len != sizeof(*head))
        return -EINVAL;

    rt_thread_self()->robust_list = head;
    return 0;
}

/**
 * @brief Get the robust list for the specified thread.
 *
 * The `sys_get_robust_list` function retrieves the robust list associated with the given thread.
 * The robust list contains `struct robust_list_head` entries used by the kernel to manage
 * robust mutexes and other resources that need to be cleaned up if the thread terminates unexpectedly.
 *
 * This function is primarily used to retrieve the robust list for a specific thread, so that
 * the caller can inspect or manipulate the robust list to handle clean-up operations in case
 * the thread exits while holding resources.
 *
 * @param[in] tid The thread ID of the thread whose robust list is to be retrieved.
 *
 * @param[out] head_ptr A pointer to a pointer to `struct robust_list_head`. On success,
 *                      this will point to the robust list for the specified thread.
 *
 * @param[out] len_ptr A pointer to a variable that will hold the length of the robust list
 *                     (i.e., the number of entries in the list).
 *
 * @return sysret_t On success, returns `0`. On failure, returns a negative error code.
 *
 * @note The robust list is used to track mutexes and other resources that need to be cleaned up
 *       if a thread terminates without releasing the resources properly. It is typically used by
 *       the kernel for thread safety and resource management in multi-threaded programs.
 *
 * @see sys_set_robust_list(), robust_mutex, pthread_mutex, get_robust_list.
 */
sysret_t sys_get_robust_list(int tid, struct robust_list_head **head_ptr, size_t *len_ptr)
{
    rt_thread_t thread;
    size_t len;
    struct robust_list_head *head;

    if (!lwp_user_accessable((void *)head_ptr, sizeof(struct robust_list_head *)))
    {
        return -EFAULT;
    }
    if (!lwp_user_accessable((void *)len_ptr, sizeof(size_t)))
    {
        return -EFAULT;
    }

    if (tid == 0)
    {
        thread = rt_thread_self();
        head = thread->robust_list;
    }
    else
    {
        thread = lwp_tid_get_thread_and_inc_ref(tid);
        if (thread)
        {
            head = thread->robust_list;
            lwp_tid_dec_ref(thread);
        }
        else
        {
            return -ESRCH;
        }
    }

    len = sizeof(*(head));

    if (!lwp_put_to_user(len_ptr, &len, sizeof(size_t)))
        return -EFAULT;
    if (!lwp_put_to_user(head_ptr, &head, sizeof(struct robust_list_head *)))
        return -EFAULT;

    return 0;
}

const static struct rt_syscall_def func_table[] =
{
    SYSCALL_SIGN(sys_exit),            /* 01 */
    SYSCALL_SIGN(sys_read),
    SYSCALL_SIGN(sys_write),
    SYSCALL_SIGN(sys_lseek),
    SYSCALL_SIGN(sys_open),            /* 05 */
    SYSCALL_SIGN(sys_close),
    SYSCALL_SIGN(sys_ioctl),
    SYSCALL_SIGN(sys_fstat),
    SYSCALL_SIGN(sys_poll),
    SYSCALL_SIGN(sys_nanosleep),       /* 10 */
    SYSCALL_SIGN(sys_gettimeofday),
    SYSCALL_SIGN(sys_settimeofday),
    SYSCALL_SIGN(sys_exec),
    SYSCALL_SIGN(sys_kill),
    SYSCALL_SIGN(sys_getpid),          /* 15 */
    SYSCALL_SIGN(sys_getpriority),
    SYSCALL_SIGN(sys_setpriority),
    SYSCALL_SIGN(sys_sem_create),
    SYSCALL_SIGN(sys_sem_delete),
    SYSCALL_SIGN(sys_sem_take),        /* 20 */
    SYSCALL_SIGN(sys_sem_release),
    SYSCALL_SIGN(sys_mutex_create),
    SYSCALL_SIGN(sys_mutex_delete),
    SYSCALL_SIGN(sys_mutex_take),
    SYSCALL_SIGN(sys_mutex_release),   /* 25 */
    SYSCALL_SIGN(sys_event_create),
    SYSCALL_SIGN(sys_event_delete),
    SYSCALL_SIGN(sys_event_send),
    SYSCALL_SIGN(sys_event_recv),
    SYSCALL_SIGN(sys_mb_create),       /* 30 */
    SYSCALL_SIGN(sys_mb_delete),
    SYSCALL_SIGN(sys_mb_send),
    SYSCALL_SIGN(sys_mb_send_wait),
    SYSCALL_SIGN(sys_mb_recv),
    SYSCALL_SIGN(sys_mq_create),       /* 35 */
    SYSCALL_SIGN(sys_mq_delete),
    SYSCALL_SIGN(sys_mq_send),
    SYSCALL_SIGN(sys_mq_urgent),
    SYSCALL_SIGN(sys_mq_recv),
    SYSCALL_SIGN(sys_thread_create),   /* 40 */
    SYSCALL_SIGN(sys_thread_delete),
    SYSCALL_SIGN(sys_thread_startup),
    SYSCALL_SIGN(sys_thread_self),
    SYSCALL_SIGN(sys_channel_open),
    SYSCALL_SIGN(sys_channel_close),   /* 45 */
    SYSCALL_SIGN(sys_channel_send),
    SYSCALL_SIGN(sys_channel_send_recv_timeout),
    SYSCALL_SIGN(sys_channel_reply),
    SYSCALL_SIGN(sys_channel_recv_timeout),
    SYSCALL_SIGN(sys_enter_critical),  /* 50 */
    SYSCALL_SIGN(sys_exit_critical),

    SYSCALL_USPACE(SYSCALL_SIGN(sys_brk)),
    SYSCALL_USPACE(SYSCALL_SIGN(sys_mmap2)),
    SYSCALL_USPACE(SYSCALL_SIGN(sys_munmap)),
#ifdef ARCH_MM_MMU
    SYSCALL_USPACE(SYSCALL_SIGN(sys_shmget)), /* 55 */
    SYSCALL_USPACE(SYSCALL_SIGN(sys_shmrm)),
    SYSCALL_USPACE(SYSCALL_SIGN(sys_shmat)),
    SYSCALL_USPACE(SYSCALL_SIGN(sys_shmdt)),
#else
#ifdef RT_LWP_USING_SHM
    SYSCALL_SIGN(sys_shm_alloc),      /* 55 */
    SYSCALL_SIGN(sys_shm_free),
    SYSCALL_SIGN(sys_shm_retain),
    SYSCALL_SIGN(sys_notimpl),
#else
    SYSCALL_SIGN(sys_notimpl),      /* 55 */
    SYSCALL_SIGN(sys_notimpl),
    SYSCALL_SIGN(sys_notimpl),
    SYSCALL_SIGN(sys_notimpl),
#endif /* RT_LWP_USING_SHM */
#endif /* ARCH_MM_MMU */
    SYSCALL_SIGN(sys_device_init),
    SYSCALL_SIGN(sys_device_register), /* 60 */
    SYSCALL_SIGN(sys_device_control),
    SYSCALL_SIGN(sys_device_find),
    SYSCALL_SIGN(sys_device_open),
    SYSCALL_SIGN(sys_device_close),
    SYSCALL_SIGN(sys_device_read),    /* 65 */
    SYSCALL_SIGN(sys_device_write),

    SYSCALL_SIGN(sys_stat),
    SYSCALL_SIGN(sys_thread_find),

    SYSCALL_NET(SYSCALL_SIGN(sys_accept)),
    SYSCALL_NET(SYSCALL_SIGN(sys_bind)),      /* 70 */
    SYSCALL_NET(SYSCALL_SIGN(sys_shutdown)),
    SYSCALL_NET(SYSCALL_SIGN(sys_getpeername)),
    SYSCALL_NET(SYSCALL_SIGN(sys_getsockname)),
    SYSCALL_NET(SYSCALL_SIGN(sys_getsockopt)),
    SYSCALL_NET(SYSCALL_SIGN(sys_setsockopt)), /* 75 */
    SYSCALL_NET(SYSCALL_SIGN(sys_connect)),
    SYSCALL_NET(SYSCALL_SIGN(sys_listen)),
    SYSCALL_NET(SYSCALL_SIGN(sys_recv)),
    SYSCALL_NET(SYSCALL_SIGN(sys_recvfrom)),
    SYSCALL_NET(SYSCALL_SIGN(sys_send)),      /* 80 */
    SYSCALL_NET(SYSCALL_SIGN(sys_sendto)),
    SYSCALL_NET(SYSCALL_SIGN(sys_socket)),

    SYSCALL_NET(SYSCALL_SIGN(sys_closesocket)),
    SYSCALL_NET(SYSCALL_SIGN(sys_getaddrinfo)),
    SYSCALL_NET(SYSCALL_SIGN(sys_gethostbyname2_r)), /* 85 */

    SYSCALL_NET(SYSCALL_SIGN(sys_sendmsg)),
    SYSCALL_NET(SYSCALL_SIGN(sys_recvmsg)),
    SYSCALL_SIGN(sys_notimpl),    /* network */
    SYSCALL_SIGN(sys_notimpl),    /* network */
    SYSCALL_SIGN(sys_notimpl),    /* network, 90 */
    SYSCALL_SIGN(sys_notimpl),    /* network */
    SYSCALL_SIGN(sys_notimpl),    /* network */
    SYSCALL_SIGN(sys_notimpl),    /* network */

#ifdef RT_USING_DFS
    SYSCALL_SIGN(sys_select),
#else
    SYSCALL_SIGN(sys_notimpl),
#endif

    SYSCALL_SIGN(sys_notimpl),    /* SYSCALL_SIGN(sys_hw_interrupt_disable), 95 */
    SYSCALL_SIGN(sys_notimpl),    /* SYSCALL_SIGN(sys_hw_interrupt_enable) */

    SYSCALL_SIGN(sys_tick_get),
    SYSCALL_SIGN(sys_exit_group),

    SYSCALL_SIGN(sys_notimpl),    /* rt_delayed_work_init */
    SYSCALL_SIGN(sys_notimpl),    /* rt_work_submit, 100 */
    SYSCALL_SIGN(sys_notimpl),    /* rt_wqueue_wakeup */
    SYSCALL_SIGN(sys_thread_mdelay),
    SYSCALL_SIGN(sys_sigaction),
    SYSCALL_SIGN(sys_sigprocmask),
    SYSCALL_SIGN(sys_tkill),             /* 105 */
    SYSCALL_SIGN(sys_thread_sigprocmask),
#ifdef ARCH_MM_MMU
    SYSCALL_SIGN(sys_cacheflush),
    SYSCALL_SIGN(sys_notimpl),
    SYSCALL_SIGN(sys_notimpl),
#else
    SYSCALL_SIGN(sys_notimpl),
    SYSCALL_SIGN(sys_lwp_sighandler_set),
    SYSCALL_SIGN(sys_thread_sighandler_set),
#endif
    SYSCALL_SIGN(sys_waitpid),          /* 110 */

    SYSCALL_SIGN(sys_rt_timer_create),
    SYSCALL_SIGN(sys_rt_timer_delete),
    SYSCALL_SIGN(sys_rt_timer_start),
    SYSCALL_SIGN(sys_rt_timer_stop),
    SYSCALL_SIGN(sys_rt_timer_control),  /* 115 */
    SYSCALL_SIGN(sys_getcwd),
    SYSCALL_SIGN(sys_chdir),
    SYSCALL_SIGN(sys_unlink),
    SYSCALL_SIGN(sys_mkdir),
    SYSCALL_SIGN(sys_rmdir),          /* 120 */
    SYSCALL_SIGN(sys_getdents),
    SYSCALL_SIGN(sys_get_errno),
#ifdef ARCH_MM_MMU
    SYSCALL_SIGN(sys_set_thread_area),
    SYSCALL_SIGN(sys_set_tid_address),
#else
    SYSCALL_SIGN(sys_notimpl),
    SYSCALL_SIGN(sys_notimpl),
#endif
    SYSCALL_SIGN(sys_access),         /* 125 */
    SYSCALL_SIGN(sys_pipe),
    SYSCALL_SIGN(sys_clock_settime),
    SYSCALL_SIGN(sys_clock_gettime),
    SYSCALL_SIGN(sys_clock_getres),
    SYSCALL_USPACE(SYSCALL_SIGN(sys_clone)),            /* 130 */
    SYSCALL_USPACE(SYSCALL_SIGN(sys_futex)),
    SYSCALL_SIGN(sys_notimpl),                          /* discarded: sys_pmutex */
    SYSCALL_SIGN(sys_dup),
    SYSCALL_SIGN(sys_dup2),
    SYSCALL_SIGN(sys_rename),                           /* 135 */
    SYSCALL_USPACE(SYSCALL_SIGN(sys_fork)),
    SYSCALL_USPACE(SYSCALL_SIGN(sys_execve)),
    SYSCALL_USPACE(SYSCALL_SIGN(sys_vfork)),
    SYSCALL_SIGN(sys_gettid),
    SYSCALL_SIGN(sys_prlimit64),                        /* 140 */
    SYSCALL_SIGN(sys_getrlimit),
    SYSCALL_SIGN(sys_setrlimit),
    SYSCALL_SIGN(sys_setsid),
    SYSCALL_SIGN(sys_getrandom),
    SYSCALL_SIGN(sys_readlink),                         /* 145 */
    SYSCALL_USPACE(SYSCALL_SIGN(sys_mremap)),
    SYSCALL_USPACE(SYSCALL_SIGN(sys_madvise)),
    SYSCALL_SIGN(sys_sched_setparam),
    SYSCALL_SIGN(sys_sched_getparam),
    SYSCALL_SIGN(sys_sched_get_priority_max),           /* 150 */
    SYSCALL_SIGN(sys_sched_get_priority_min),
    SYSCALL_SIGN(sys_sched_setscheduler),
    SYSCALL_SIGN(sys_sched_getscheduler),
    SYSCALL_SIGN(sys_sched_setaffinity),
    SYSCALL_SIGN(sys_fsync),                            /* 155 */
    SYSCALL_SIGN(sys_clock_nanosleep),
    SYSCALL_SIGN(sys_timer_create),
    SYSCALL_SIGN(sys_timer_delete),
    SYSCALL_SIGN(sys_timer_settime),
    SYSCALL_SIGN(sys_timer_gettime),                    /* 160 */
    SYSCALL_SIGN(sys_timer_getoverrun),
    SYSCALL_SIGN(sys_mq_open),
    SYSCALL_SIGN(sys_mq_unlink),
    SYSCALL_SIGN(sys_mq_timedsend),
    SYSCALL_SIGN(sys_mq_timedreceive),                  /* 165 */
    SYSCALL_SIGN(sys_mq_notify),
    SYSCALL_SIGN(sys_mq_getsetattr),
    SYSCALL_SIGN(sys_mq_close),
    SYSCALL_SIGN(sys_lstat),
    SYSCALL_SIGN(sys_uname),                            /* 170 */
    SYSCALL_SIGN(sys_statfs),
    SYSCALL_SIGN(sys_statfs64),
    SYSCALL_SIGN(sys_fstatfs),
    SYSCALL_SIGN(sys_fstatfs64),
    SYSCALL_SIGN(sys_openat),                           /* 175 */
    SYSCALL_SIGN(sys_mount),
    SYSCALL_SIGN(sys_umount2),
    SYSCALL_SIGN(sys_link),
    SYSCALL_SIGN(sys_symlink),
    SYSCALL_SIGN(sys_sched_getaffinity),                /* 180 */
    SYSCALL_SIGN(sys_sysinfo),
    SYSCALL_SIGN(sys_chmod),
    SYSCALL_SIGN(sys_reboot),
    SYSCALL_SIGN(sys_sched_yield),
    SYSCALL_SIGN(sys_pread64),                          /* 185 */
    SYSCALL_SIGN(sys_pwrite64),
    SYSCALL_SIGN(sys_sigpending),
    SYSCALL_SIGN(sys_sigtimedwait),
    SYSCALL_SIGN(sys_notimpl),
    SYSCALL_SIGN(sys_notimpl),                          /* 190 */
    SYSCALL_SIGN(sys_eventfd2),
    SYSCALL_SIGN(sys_epoll_create1),
    SYSCALL_SIGN(sys_epoll_ctl),
    SYSCALL_SIGN(sys_epoll_pwait),
    SYSCALL_SIGN(sys_notimpl),                          /* 195 */
    SYSCALL_SIGN(sys_timerfd_create),
    SYSCALL_SIGN(sys_timerfd_settime),
    SYSCALL_SIGN(sys_timerfd_gettime),
    SYSCALL_SIGN(sys_signalfd),
    SYSCALL_SIGN(sys_memfd_create),                     /* 200 */
    SYSCALL_SIGN(sys_ftruncate),
    SYSCALL_SIGN(sys_setitimer),
    SYSCALL_SIGN(sys_utimensat),
#ifdef RT_USING_POSIX_SOCKET
    SYSCALL_SIGN(sys_syslog),
    SYSCALL_SIGN(sys_socketpair),                             /* 205 */
#else
    SYSCALL_SIGN(sys_notimpl),
    SYSCALL_SIGN(sys_notimpl),                          /* 205 */
#endif
    SYSCALL_SIGN(sys_wait4),
    SYSCALL_SIGN(sys_set_robust_list),
    SYSCALL_SIGN(sys_get_robust_list),
    SYSCALL_SIGN(sys_setpgid),
    SYSCALL_SIGN(sys_getpgid),                          /* 210 */
    SYSCALL_SIGN(sys_getsid),
    SYSCALL_SIGN(sys_getppid),
    SYSCALL_SIGN(sys_fchdir),
    SYSCALL_SIGN(sys_chown),
};

const void *lwp_get_sys_api(rt_uint32_t number)
{
    const void *func = (const void *)sys_notimpl;

    if (number == 0xff)
    {
        func = (void *)sys_log;
    }
    else
    {
        number -= 1;
        if (number < sizeof(func_table) / sizeof(func_table[0]))
        {
            func = func_table[number].func;
        }
        else
        {
            if (__sys_log_enable)
            {
                LOG_I("Unimplement syscall %d", number);
            }
        }
    }

    return func;
}

const char *lwp_get_syscall_name(rt_uint32_t number)
{
    const char *name = "sys_notimpl";

    if (number == 0xff)
    {
        name = "sys_log";
    }
    else
    {
        number -= 1;
        if (number < sizeof(func_table) / sizeof(func_table[0]))
        {
            name = (char*)func_table[number].name;
        }
        else
        {
            if (__sys_log_enable)
            {
                LOG_I("Unimplement syscall %d", number);
            }
        }
    }

    /* skip sys_ */
    return name;
}