pspsdk 0.0.2

A SDK for creating PSP modules, including both PRX plugins and regular homebrew apps.
Documentation
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
//! Input/Output operations.
use core::{ffi::c_void, mem, ptr::NonNull};

use bitflag_attr::bitflag;
use pspsdk_macros::psp_stub;

use crate::sys::{
    thread::{CallbackId, EventFlagId, SemaId, ThreadId},
    time::DateTime,
    SceError, SceIntoOkValue, SceResult, SceResult64, SceResultOk, SceSize, SceUid,
};

/// File descriptor UID.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FileId(SceUid);

/// Flags that control how a file is opened and its subsequent behavior.
///
/// The flags can roughly be divided in 3 groups:
/// - **File access mode flags:** These flags specify the access allowed in the file.
/// - **Open mode flags:** These flags control the behavior of the open operations.
///     - These flags can only take effect in open operations. Usually ignored or error on other
///       operations.
/// - **I/O operation mode flags:** These flags control the behavior of the I/O operations (read,
///   write, etc)
///     - These flags are set by open operations.
#[bitflag(u32)]
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Debug, PartialEq, PartialOrd, Eq, Ord, Hash)]
pub enum FileFlags {
    /// File access mode flag. Marks that the file is open for reads only.
    #[doc(alias("SCE_O_RDONLY", "SCE_FREAD", "PSP_O_RDONLY"))]
    ReadOnly = 0x0001,
    /// File access mode flag. Marks that the file is open for writes only.
    #[doc(alias("SCE_O_WRONLY", "SCE_FWRITE", "PSP_O_WRONLY"))]
    WriteOnly = 0x0002,
    /// File access mode flag. Marks that the file is open for reads and writes.
    #[doc(alias("SCE_O_RDWR", "PSP_O_RDWR"))]
    ReadWrite = 0x0003,
    /// I/O operation mode flag. Non-blocking mode.
    ///
    /// Not used/reserved.
    #[doc(alias("SCE_O_NBLOCK", "SCE_FNBLOCK", "PSP_O_NBLOCK"))]
    NonBlock = 0x0004,
    /// I/O operation mode flag. Directory operation mode.
    ///
    /// This flag is only used internally by [`sceIoDopen`].
    #[doc(alias("SCE_O_DIR", "SCE_FDIRO", "PSP_O_DIR"))]
    DirectoryMode = 0x0008,
    /// Unknown mode flag. Read locked (non-shared) (?).
    ///
    /// Not used/reserved.
    #[doc(alias("SCE_FRLOCK"))]
    ReadLocked = 0x0010,
    /// Unknown mode flag. Write locked (non-shared) (?).
    ///
    /// Not used/reserved.
    #[doc(alias("SCE_FWLOCK"))]
    WriteLocked = 0x0020,
    /// I/O operation mode flag. Append mode.
    ///
    /// If this flags is set, the file offset is set to the end of the file prior to each write
    /// operation on the file.
    #[doc(alias("SCE_O_APPEND", "SCE_FAPPEND", "PSP_O_APPEND"))]
    AppendMode = 0x0100,
    /// Open mode flag. Create file if it does not exist.
    ///
    /// This flag has no effect if set and the file exist, unless the [`Exclusive`] flags is also
    /// set, on which case the open operation will fail if the file exists.
    ///
    /// [`Exclusive`]: Self::Exclusive
    #[doc(alias("SCE_O_CREAT", "SCE_FCREAT", "PSP_O_CREAT"))]
    CreateFile = 0x0200,
    /// Open mode flag. Truncate existing file to zero length.
    ///
    /// This flag only has effect on regular files.
    ///
    /// If this flag is set and the file is a regular file, truncates the file to a length of zero
    /// (`0`).
    #[doc(alias("SCE_O_TRUNC", "SCE_FTRUNC", "PSP_O_TRUNC"))]
    Truncate = 0x0400,
    /// Open mode flag. Exclusive file creation.
    ///
    /// If this flag is set with the [`CreateFile`], an open operation will fail if the file
    /// already exists.
    ///
    /// [`CreateFile`]: Self::CreateFile
    #[doc(alias("SCE_O_EXCL", "SCE_EXCL", "PSP_O_EXCL"))]
    Exclusive = 0x0800,
    /// Unknown mode flag. Scan type (?).
    ///
    /// Not used/reserved.
    #[doc(alias("SCE_FSCAN"))]
    Scan   = 0x1000,
    /// Unknown mode flag. Remote command entry (?).
    ///
    /// Not used/reserved.
    #[doc(alias("SCE_FRCOM"))]
    RemoteCommand = 0x2000,
    /// Open mode flag. Do not use device buffer and console interrupt.
    ///
    /// Not used/reserved.
    #[doc(alias("SCE_FNBUF"))]
    NoBuffer = 0x4000,
    /// Open mode flag. No wait (?)
    ///
    /// It is set in some titles I/O operations, but no reference to it on the reversed code on I/O
    /// functions.
    #[doc(alias("SCE_O_NOWAIT", "SCE_FASYNC", "PSP_O_NOWAIT"))]
    NoWait = 0x8000,
    /// I/O operation mode flag. Exclusive access mode.
    ///
    /// When set, only the the same thread that opened the file descriptor or the async thread of
    /// the file descriptor can execute operations on the file.
    #[doc(alias("SCE_O_FDEXCL", "SCE_FFDEXCL"))]
    ExclusiveAccess = 0x01000000,
    /// I/O operation mode flag. Power locked mode.
    ///
    /// When set, all power tick timer will be locked from triggering while the file descriptor is
    /// opened.
    #[doc(alias("SCE_O_PWLOCK", "SCE_FPWLOCK"))]
    PowerLock = 0x02000000,
    /// Open mode flag. Encrypted mode.
    ///
    /// The file uses Kernel/DNAS/NPDRM-encryption.
    #[doc(alias("SCE_O_ENCRYPTED", "SCE_FENCRYPTED"))]
    Encrypted = 0x04000000,
    /// Open mode flag. Global File descriptor mode.
    ///
    /// Attempts to open the file and save the UID in the system global File
    /// descriptor UID list.
    ///
    /// When set, the return value for the [`sceIoOpen`] and [`sceIoOpenAsync`] will
    /// be the index in the list. The real UID then can be retrieved with
    /// [`sceIoGetUID`].
    GlobalFdIndex = 0x08000000,
    /// I/O operation mode flag. DRM protected mode.
    ///
    /// When set, specifies that the opened file descriptor references a file that is DRM
    /// protected.
    ///
    /// Trying to open DRM protected files without this flag will cause errors. Other checks
    /// probably happen on the DRM specific functions that require this flag and more.
    #[doc(alias("SCE_O_FGAMEDATA", "SCE_FGAMEDATA"))]
    DrmProtected = 0x40000000,
}

/// Typed representation of file modes, combining file type and permissions.
///
/// This bitflag type represents the possible file types and permissions that can be associated
/// with a file.
#[bitflag(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[doc(alias("SceMode"))]
pub enum Mode {
    /// Permission flag. Owner read permission.
    #[doc(alias = "S_IRUSR")]
    OwnerRead = 0x0100,
    /// Permission flag. Owner write permission.
    #[doc(alias = "S_IWUSR")]
    OwnerWrite = 0x0080,
    /// Permission flag. Owner execute/search permission.
    #[doc(alias = "S_IXUSR")]
    OwnerExec = 0x0040,
    /// Permission flag. Owner read, write, and execute/search permissions.
    #[doc(alias = "S_IRWXU")]
    OwnerAll = 0x01C0,
    /// Permission flag. Group read permission.
    #[doc(alias = "S_IRGRP")]
    GroupRead = 0x0020,
    /// Permission flag. Group write permission.
    #[doc(alias = "S_IWGRP")]
    GroupWrite = 0x0010,
    /// Permission flag. Group execute/search permission.
    #[doc(alias = "S_IXGRP")]
    GroupExec = 0x0008,
    /// Permission flag. Group read, write, and execute/search permissions.
    #[doc(alias = "S_IRWXG")]
    GroupAll = 0x0038,
    /// Permission flag. Others read permission.
    #[doc(alias = "S_IROTH")]
    OtherRead = 0x0004,
    /// Permission flag. Others write permission.
    #[doc(alias = "S_IWOTH")]
    OtherWrite = 0x0002,
    /// Permission flag. Others execute/search permission.
    #[doc(alias = "S_IXOTH")]
    OtherExec = 0x0001,
    /// Permission flag. Others read, write, and execute/search permissions.
    #[doc(alias = "S_IRWXO")]
    OtherAll = 0x0007,

    /// Special attribute flag. Set-user-ID on execution.
    #[doc(alias = "S_ISUID")]
    IsSetUid = 0x0800,
    /// Special attribute flag. Set-group-ID on execution.
    #[doc(alias = "S_ISGID")]
    IsSetGid = 0x0400,
    /// Special attribute flag. On directories, restricted deletion flag.
    #[doc(alias = "S_ISVTX")]
    IsRestrictDeletion = 0x0200,

    /// File kind flag. File type of Directory file.
    #[doc(alias = "S_IFDIR")]
    IsDir  = 0x1000,
    /// File kind flag. File type of Regular file.
    #[doc(alias = "S_IFREG")]
    IsRegular = 0x2000,
    /// File kind flag. File type of symbolic Link file.
    #[doc(alias = "S_IFLNK")]
    IsLink = 0x4000,
    /// Bitmask for the file type on [`Mode`].
    #[doc(alias = "S_IFMT")]
    FileKind = 0xF000,
}

/// Possible methods to seek within an file object.
#[repr(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Whence {
    /// Seek offset from the start of the file.
    #[doc(alias("SCE_SEEK_SET", "SEEK_SET"))]
    Start = 0,
    /// Seek offset from the current internal position of the file.
    #[doc(alias("SCE_SEEK_CUR", "SEEK_CUR"))]
    Current = 1,
    /// Seek offset from the end of the file.
    #[doc(alias("SCE_SEEK_END", "SEEK_END"))]
    End   = 2,
}

/// A single directory entry.
#[repr(C)]
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[doc(alias("SceIoDirent"))]
pub struct Dirent {
    /// The file status
    #[doc(alias("d_stat"))]
    pub stat: Stat,
    /// The file name.
    #[doc(alias("d_name"))]
    pub name: [u8; 256],
    /// Device specific data.
    #[doc(alias("d_private"))]
    pub private: *mut DirentFatPrivate,
    pub dummy: u32,
}

/// Private information of a directory (specific to FAT filesystem, which is the only one the PSP
/// has support anyway).
#[repr(C)]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DirentFatPrivate {
    pub size: SceSize,
    pub short_name: [u8; 13],
    _padding: [u8; 3],
    pub long_name: [u8; 1024],
}

/// The status information of a file.
#[repr(C)]
#[doc(alias("SceIoStat"))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Stat {
    /// The file permissions.
    pub mode: Mode,
    /// The file status attributes.
    pub attr: StatAttribute,
    /// The size of the file in bytes.
    pub size: u64,
    /// Creation time.
    pub creation_time: DateTime,
    /// Access time.
    pub access_time: DateTime,
    /// Modification time.
    pub modification_time: DateTime,
    /// Device specific data.
    pub private: [u32; 6],
}

/// Attributes of the file [`Stat`].
#[bitflag(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum StatAttribute {
    /// Symlink.
    Link = 0x0008,
    /// Directory.
    Directory = 0x0010,
    /// Regular file.
    RegularFile = 0x0020,
    /// Hidden read permission.
    ReadPermission = 0x0004,
    /// Hidden write permission.
    WritePermission = 0x0002,
    /// Hidden execution permission.
    ExecPermission = 0x0001,
}

/// What field of stat to change on [`sceIoChstat`].
#[bitflag(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ChangeStatFlag {
    /// Changes [`Stat::mode`].
    Mode = 0x0001,
    /// Changes [`Stat::attr`].
    Attribute = 0x0002,
    /// Changes [`Stat::size`].
    Size = 0x0004,
    /// Changes [`Stat::creation_time`].
    CreationTime = 0x0008,
    /// Changes [`Stat::access_time`].
    AccessTime = 0x0010,
    /// Changes [`Stat::modification_time`].
    ModificationTime = 0x0020,
    /// Changes [`Stat::private`].
    Private = 0x0040,
}

/// Mount flags used on [`sceIoAssign`].
#[bitflag(u32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum AssignFlag {
    /// Mounts as read/write enabled.
    ReadWrite = 0x00,
    /// Mounts as read-only.
    ReadOnly = 0x01,
    /// Mount in ROBUST mode.
    Robust = 0x02,
    /// Set an error if there is anything abnormal in the file system when mounting.
    ErrorCheck = 0x04,
}

/// Drive device information to add with [`sceIoAddDrv`].
#[repr(C)]
#[doc(alias("PspIoDrv", "SceIoDeviceTable"))]
pub struct DriveDevice {
    /// The name of the device to add.
    pub name: *const u8,
    /// The device kind.
    pub kind: DeviceKind,
    /// Unknown.
    ///
    /// ## Known values
    /// - `0x001`: Unknown
    /// - `0x800`: Unknown
    pub unk: u32,
    /// The device short description.
    pub description: *const u8,
    /// A pointer to a filled out functions table.
    pub drive_funcs: NonNull<DriveFunctionTable>,
}

/// Device information.
///
/// Mainly used for the parameter for the [`DriveFunctionTable`] function pointers.
#[repr(C)]
#[doc(alias("PspIoDrvFileArg", "SceIoIob"))]
pub struct IoBlockInfo {
    /// The file flags
    pub flags: FileFlags,
    /// The file system number.
    ///
    /// E.g.: If a file is opened as `host5:/myfile.txt` this field will be `5`.
    pub fs_unit: u32,
    /// A pointer to the device entry data.
    ///
    /// This pointer should never be null in the context of [`DriveFunctionTable`] functions being
    /// called, but it can be before that.
    pub dev_entry: *mut DeviceEntry,
    /// The device attribute.
    ///
    /// It contains the device kind.
    pub dev_attr: DeviceAttribute,
    /// A pointer to a setter defined argument.
    ///
    /// If written by the driver will preserve across calls.
    ///
    /// The actual data types used is device dependent.
    pub private_data: *mut c_void,
    pub cwd: *mut Cwd,
    /// The current file position offset.
    pub file_pos: i64,
    /// The thread UID of (?).
    pub thread_id: ThreadId,
    /// Currently unknown
    pub unk: u32,
    /// Raw UID of the opened file
    pub uid: FileId,
    /// The thread UID of the thread that opened the file.
    pub open_thread_id: ThreadId,
    /// If the file is opened in user mode.
    pub is_user_mode: bool,
    /// If the file was opened with [`FileFlags::PowerLock`].
    pub is_power_locked: bool,
    /// Unknown. It is a boolean of some sort, async related.
    pub unk2: u8,
    /// The async task priority
    pub async_priority: u8,
    /// The thread UID of the thread for the file async operations.
    pub async_thread_id: ThreadId,
    /// The semaphore UID for the file async operations.
    pub async_sema: SemaId,
    /// The event flag UID for the file async operations.
    pub async_event_flag: EventFlagId,
    /// The callback UID for the file async operations.
    pub async_callback: CallbackId,
    /// A pointer to the parameter to pass to `async_callback`.
    pub async_callback_argp: *mut c_void,
    /// Unused.
    pub unused: u32,
    /// The current `k1` register value for async operations
    pub k1: u32,
    /// The async return value of operations.
    pub async_return: i64,
    /// Arguments for the command to use.
    pub async_args: [i32; 6],
    /// The async command to execute.
    pub async_cmd: u32,
    /// The current user level of
    pub user_level: u32,
    pub hook: IoHook,
    pub unk3: u32,
    pub new_path: *mut u8,
    /// The return address.
    pub return_addr: SceSize,
}

/// Device attributes.
///
/// It hold the device kind and other things.
#[bitflag(u32)]
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DeviceAttribute {
    /// Device kind. A device that does nothing.
    DummyDevice = 0x00,
    /// Device kind. A physical character device.
    CharacterDevice = 0x01,
    /// Device kind. A physical block device.
    ///
    /// E.g. A physical UMD drive.
    BlockDevice = 0x04,
    /// Device kind. A filesystem logical device.
    FilesystemDevice = 0x10,
    /// Device kind. A device alias device.
    ///
    /// A device that is simply an alias for another device.
    DeviceAliasDevice = 0x20,
    /// Device kind. A mount point alias device.
    ///
    /// A device that is simply an alias for an mount point.
    MountPointAliasDevice = 0x30,

    /// Device trait. The device has a block alias.
    HasBlockAlias = 0x100,
}

/// Type to maintain the device driver pointers.
#[repr(C)]
#[doc(alias("PspIoDrvFuncs", "SceIoDeviceFunction"))]
#[rustfmt::skip]
pub struct DriveFunctionTable {
    pub init: Option<unsafe extern "C" fn(entry: *mut DeviceEntry) -> SceResult<()>>,
    pub exit: Option<unsafe extern "C" fn(entry: *mut DeviceEntry) -> SceResult<()>>,
    pub open: Option<unsafe extern "C" fn(block: *mut IoBlockInfo, path: *const u8, flags: FileFlags, mode: Mode) -> SceResult<FileId>>,
    pub close: Option<unsafe extern "C" fn(block: *mut IoBlockInfo) -> SceResult<()>>,
    pub read: Option<unsafe extern "C" fn(block: *mut IoBlockInfo, buf: *mut u8, buf_size: SceSize) -> SceResult<SceSize>>,
    pub write: Option<unsafe extern "C" fn(block: *mut IoBlockInfo, buf: *const u8, buf_size: SceSize) -> SceResult<SceSize>>,
    pub lseek: Option<unsafe extern "C" fn(block: *mut IoBlockInfo, offset: i64, whence: Whence) -> i64>,
    pub ioctl: Option<unsafe extern "C" fn(block: *mut IoBlockInfo, cmd: u32, in_buf: *mut u8, in_size: SceSize, out_buf: *mut u8, out_size: SceSize) -> SceResult<u32>>,
    pub remove: Option<unsafe extern "C" fn(block: *mut IoBlockInfo, path: *const u8) -> SceResult<()>>,
    pub mkdir: Option<unsafe extern "C" fn(block: *mut IoBlockInfo, path: *const u8, mode: Mode) -> SceResult<()>>,
    pub rmdir: Option<unsafe extern "C" fn(block: *mut IoBlockInfo, path: *const u8) -> SceResult<()>>,
    pub dopen: Option<unsafe extern "C" fn(block: *mut IoBlockInfo, dir_path: *const u8) -> SceResult<FileId>>,
    pub dclose: Option<unsafe extern "C" fn(block: *mut IoBlockInfo) -> SceResult<()>>,
    pub dread: Option<unsafe extern "C" fn(block: *mut IoBlockInfo, entry_info: &mut Dirent) -> SceResult<u32>>,
    pub get_stat: Option<unsafe extern "C" fn(block: *mut IoBlockInfo, path: *const u8, stat: &mut Stat) -> SceResult<()>>,
    pub change_stat: Option<unsafe extern "C" fn(block: *mut IoBlockInfo, path: *const u8, stat: &Stat, change_bits: ChangeStatFlag) -> SceResult<()>>,
    pub rename: Option<unsafe extern "C" fn(block: *mut IoBlockInfo, old_name: *const u8, new_name: *const u8) -> SceResult<()>>,
    pub chdir: Option<unsafe extern "C" fn(block: *mut IoBlockInfo, path: *const u8) -> SceResult<()>>,
    pub mount: Option<unsafe extern "C" fn(block: *mut IoBlockInfo) -> SceResult<()>>,
    pub unmount: Option<unsafe extern "C" fn(block: *mut IoBlockInfo) -> SceResult<()>>,
    pub devctl: Option<unsafe extern "C" fn(block: *mut IoBlockInfo, dev: *const u8, cmd: u32, in_buf: *mut u8, in_size: SceSize, out_buf: *mut u8, out_size: SceSize) -> SceResult<u32>>,
    pub cancel: Option<unsafe extern "C" fn(block: *mut IoBlockInfo) -> SceResult<()>>,
}

/// Structure passed to the drive function [`DriveFunctionTable::init`] and
/// [`DriveFunctionTable::exit`].
#[repr(C)]
#[doc(alias("PspIoDrvArg", "SceIoDeviceEntry"))]
pub struct DeviceEntry {
    /// A pointer to the original driver which was added.
    pub drv: *mut DriveDevice,
    /// A pointer to a setter defined argument.
    ///
    /// If written by the driver will preserve across calls.
    ///
    /// The actual data types used is device dependent.
    pub private_data: *mut c_void,
    /// The number of file descriptor UID related to the device.
    pub user_fd_count: SceSize,
}

/// Possible device kinds.
#[repr(u32)]
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum DeviceKind {
    /// A device that does nothing.
    Dummy = 0x00,
    /// A physical character device.
    Character = 0x01,
    /// A physical block device.
    ///
    /// E.g. A physical UMD drive.
    Block = 0x04,
    /// A filesystem logical device.
    Filesystem = 0x10,
    /// A device alias device.
    ///
    /// A device that is simply an alias for another device.
    DeviceAlias = 0x20,
    /// A mount point alias device.
    ///
    /// A device that is simply an alias for an mount point.
    MountPointAlias = 0x30,
}

/// Current working directory.
#[repr(C)]
#[doc(alias = "SceIoCwd")]
pub struct Cwd {
    pub next: *mut Cwd,
    pub path_name: *mut u8,
    pub entry: *mut DeviceEntry,
    pub cwd_private: *mut c_void,
    pub ref_count: SceSize,
}

#[repr(C)]
#[doc(alias = "SceIoHook")]
pub struct IoHook {
    // FIXME: *mut SceIoHookArg
    pub arg: *mut c_void,
    pub io_block: *mut IoBlockInfo,
    pub func_table: *mut DriveFunctionTable,
}

#[psp_stub(libname = "IoFileMgrForUser", flags = 0x4009, use_crate)]
unsafe extern "C" {
    /// Opens a file with the corresponding file access attributes.
    ///
    /// The function only supports full path.
    ///
    /// If the flag [`FileFlags::CreateFile`] is set in `flags`, the third parameter is used if the
    /// file needs to be created, otherwise it is ignored.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file to open.
    /// - `flags`: The flags with file access attributes.
    /// - `mode`: The permission mode to use. If [`FileFlags::CreateFile`] is set in `flags`, it is
    ///   ignored otherwise.
    ///
    /// # Result Value
    ///
    /// Returns the open file descriptor ID on success, error value otherwise.
    #[nid(0x109F50BC)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoOpen(path: *const u8, flags: FileFlags, mode: Mode) -> SceResult<FileId>;

    /// Opens a file with the corresponding file access attributes asynchronously.
    ///
    /// The function only supports full path.
    ///
    /// If the flag [`FileFlags::CreateFile`] is set in `flags`, the third parameter is used if the
    /// file needs to be created, otherwise it is ignored.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file to open.
    /// - `flags`: The flags with file access attributes.
    /// - `mode`: The permission mode to use. If [`FileFlags::CreateFile`] is set in `flags`, it is
    ///   ignored otherwise.
    ///
    /// # Result Value
    ///
    /// Returns the open file descriptor ID on success, error value otherwise.
    #[nid(0x89AA9906)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoOpenAsync(
        path: *const u8, flags: FileFlags, mode: Mode,
    ) -> SceResult<FileId>;

    /// Closes a open file and deletes the associated file descriptor ID.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x810C4BC3)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoClose(fd: FileId) -> SceResult<()>;

    /// Closes a open file and deletes the associated file descriptor ID asynchronously.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xFF5940B6)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoCloseAsync(fd: FileId) -> SceResult<()>;

    /// Reads data from the file associated to the file descriptor UID to a buffer.
    ///
    /// # Parameter
    ///
    /// - `fd`: The file descriptor UID.
    /// - `buf` **[[Out parameter]]**: A pointer to the buffer to receive the data read.
    /// - `buf_size`: The size of the buffer.
    ///
    /// # Returns Value
    ///
    /// Returns the number of bytes read on success, error value otherwise.
    #[nid(0x6A638D83)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoRead(fd: FileId, buf: *mut u8, buf_size: SceSize) -> SceResult<SceSize>;

    /// Reads data from the file associated to the file descriptor UID to a buffer asynchronously.
    ///
    /// # Parameter
    ///
    /// - `fd`: The file descriptor UID.
    /// - `buf` **[[Out parameter]]**: A pointer to the buffer to receive the data read.
    /// - `buf_size`: The size of the buffer.
    ///
    /// # Returns Value
    ///
    /// Returns the number of bytes read on success, error value otherwise.
    #[nid(0xA0B5A7C2)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoReadAsync(fd: FileId, buf: *mut u8, buf_size: SceSize)
        -> SceResult<SceSize>;

    /// Writes data to the file associated to the file descriptor UID.
    ///
    /// # Parameter
    ///
    /// - `fd`: The file descriptor UID.
    /// - `data` **[[In parameter]]**: A pointer to a buffer data to write.
    /// - `data_size`: The size of `data` buffer.
    ///
    /// # Return Value
    ///
    /// Returns the number of bytes written on success, error value otherwise.
    #[nid(0x42EC03AC)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoWrite(fd: FileId, data: *const u8, data_size: SceSize)
        -> SceResult<SceSize>;

    /// Writes data to the file associated to the file descriptor UID asynchronously.
    ///
    /// # Parameter
    ///
    /// - `fd`: The file descriptor UID.
    /// - `data` **[[In parameter]]**: A pointer to a buffer data to write.
    /// - `data_size`: The size of `data` buffer.
    ///
    /// # Return Value
    ///
    /// Returns the number of bytes written on success, error value otherwise.
    #[nid(0x0FACAB19)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoWriteAsync(
        fd: FileId, data: *const u8, data_size: SceSize,
    ) -> SceResult<SceSize>;

    /// Repositions the file offset of the file descriptor.
    ///
    /// # Parameters
    /// - `fd`: The file descriptor UID.
    /// - `offset`: The relative offset from the start position determined by `whence`.
    /// - `whence`: The start position options to use for the relative `offset`.
    ///
    /// # Return Value
    ///
    /// Returns the position of the internal file offset on success, error value otherwise.
    #[eabi(i_ii_i_rii)]
    #[nid(0x27EB27B8)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceIoLseek(fd: FileId, offset: i64, whence: Whence) -> SceResult64<u64>;

    /// Repositions the file offset of the file descriptor asynchronously.
    ///
    /// # Parameters
    /// - `fd`: The file descriptor UID.
    /// - `offset`: The relative offset from the start position determined by `whence`.
    /// - `whence`: The start position options to use for the relative `offset`.
    ///
    /// # Return Value
    ///
    /// Returns the position of the internal file offset on success, error value otherwise.
    #[eabi(i_ii_i_rii)]
    #[nid(0x71B19E77)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceIoLseekAsync(fd: FileId, offset: i64, whence: Whence) -> SceResult64<u64>;

    /// Repositions the file offset of the file descriptor. (32-bit mode).
    ///
    /// # Parameters
    /// - `fd`: The file descriptor UID.
    /// - `offset`: The relative offset from the start position determined by `whence`.
    /// - `whence`: The start position options to use for the relative `offset`.
    ///
    /// # Return Value
    ///
    /// Returns the position of the internal file offset on success, error value otherwise.
    #[nid(0x68963324)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceIoLseek32(fd: FileId, offset: i32, whence: Whence) -> SceResult<SceSize>;

    /// Repositions the file offset of the file descriptor. (32-bit mode).
    ///
    /// # Parameters
    /// - `fd`: The file descriptor UID.
    /// - `offset`: The relative offset from the start position determined by `whence`.
    /// - `whence`: The start position options to use for the relative `offset`.
    ///
    /// # Return Value
    ///
    /// Returns the position of the internal file offset on success, error value otherwise.
    #[nid(0x1B385D8F)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceIoLseek32Async(fd: FileId, offset: i32, whence: Whence) -> SceResult<SceSize>;

    /// Removes a file associated to a given path.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file to remove.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xF27A9C51)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoRemove(path: *const u8) -> SceResult<()>;

    /// Creates a directory file.
    ///
    /// # Parameters
    ///
    /// - `dir_path` **[[In parameter]]**: The path to create the directory file.
    /// - `mode`: The permission mode to set on the created file.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x06A70004)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoMkdir(dir_path: *const u8, mode: Mode) -> SceResult<()>;

    /// Removes a directory file associated to a given path.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file to remove.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x1117C65F)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoRmdir(path: *const u8) -> SceResult<()>;

    /// Changes the current directory.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file to change.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x55F4717D)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoChdir(path: *const u8) -> SceResult<()>;

    /// Changes the file name to a new name.
    ///
    /// # Parameters
    ///
    /// - `old_name` **[[In parameter]]**: The old name for the file.
    /// - `new_name` **[[In parameter]]**: The new name for the file.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x779103A0)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoRename(old_name: *const u8, new_name: *const u8) -> SceResult<()>;

    /// Opens a directory.
    ///
    /// # Parameters
    ///
    /// - `dir_path` **[[In parameter]]**: The directory path to open.
    ///
    /// # Result Value
    ///
    /// Returns the open file descriptor ID on success, error value otherwise.
    #[nid(0xB29DDF9C)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoDopen(dir_path: *const u8) -> SceResult<FileId>;

    /// Reads an entry from a opened file descriptor UID associated to a file opened with
    /// [`sceIoDopen`].
    ///
    /// # Parameters
    ///
    /// - `dir_fd`: The directory file descriptor UID.
    /// - `entry_info` **[[Out parameter]]**: A reference to the structure to receive the directory
    ///   entry information.
    ///
    /// # Return Value
    ///
    /// Returns, on success, `0` if there is no more directory entries left, `> 0` if there are more
    /// directory entries to go. On error, a error value is returned.
    #[nid(0xE3EB004C)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceIoDread(dir_fd: FileId, entry_info: &mut Dirent) -> SceResult<u32>;

    /// Closes an directory opened with [`sceIoDopen`].
    ///
    /// # Parameters
    ///
    /// - `dir_fd`: The directory file descriptor UID.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xEB092469)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoDclose(dir_fd: FileId) -> SceResult<()>;

    /// Gets the status of a file.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file.
    /// - `stat` **[[Out parameter]]**: A reference to receive the status data from the file.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xACE946E8)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoGetstat(path: *const u8, stat: &mut Stat) -> SceResult<()>;

    /// Changes the status of a file.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file.
    /// - `stat` **[[In parameter]]**: A reference to the status data to modify the file stat.
    /// - `change_bits`: The bitflags of what field of stat to change.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xB8A740F4)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoChstat(
        path: *const u8, stat: &Stat, change_bits: ChangeStatFlag,
    ) -> SceResult<()>;

    /// Assigns one I/O device to another.
    ///
    /// # Parameters
    ///
    /// - `dev` **[[In parameter]]**: The device name to assign.
    /// - `block_dev` **[[In parameter]]**: The block device name to assign from.
    /// - `fs` **[[In parameter]]**: The filesystem device name to map the block device to `dev`.
    /// - `flags`: The mounting modes flags.
    /// - `unk1`: Unknown. Set it to [`null`](core::ptr::null_mut).
    /// - `unk2`: Unknown. Set it to `0`.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[eabi(i6)]
    #[nid(0xB2A628C1)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoAssign(
        dev: *const u8, block_dev: *const u8, fs: *const u8, flags: AssignFlag, unk1: *mut c_void,
        unk2: u32,
    ) -> SceResult<()>;

    /// Unassign an I/O device.
    ///
    /// # Parameters
    ///
    /// - `dev` **[[In parameter]]**: The device name to unassign.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x6D08A871)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoUnassign(dev: *const u8) -> SceResult<()>;

    /// Performs an Device Control command on a device.
    ///
    /// # Parameters
    ///
    /// - `dev` **[[In parameter]]**: The device name.
    /// - `cmd`: The command to send to the device.
    /// - `in_buf` **[[In parameter]]**: A pointer to a data block buffer to send to the device. If
    ///   [`null`](core::ptr::null_mut) it sends no data.
    /// - `in_size`: The size of the `in_buf`.
    /// - `out_buf` **[[Out parameter]]**: A pointer to a data block buffer to receive data from the
    ///   device. If [`null`](core::ptr::null_mut) it receives no data.
    /// - `out_size`: The size of the `out_buf`.
    ///
    /// /// # Return Value
    ///
    /// `Ok` value on success (meaning depends on the command), error value otherwise.
    #[eabi(i6)]
    #[nid(0x54F5FB11)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoDevctl(
        dev: *const u8, cmd: u32, in_buf: *mut u8, in_size: SceSize, out_buf: *mut u8,
        out_size: SceSize,
    ) -> SceResult<u32>;

    /// Performs an I/O Control command on a file.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `cmd`: The command to send to the file.
    /// - `in_buf` **[[In parameter]]**: A pointer to a data block buffer to send to the file. If
    ///   [`null`](core::ptr::null_mut) it sends no data.
    /// - `in_size`: The size of the `in_buf`.
    /// - `out_buf` **[[Out parameter]]**: A pointer to a data block buffer to receive data from the
    ///   file. If [`null`](core::ptr::null_mut) it receives no data.
    /// - `out_size`: The size of the `out_buf`.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success (meaning depends on the command), error value otherwise.
    #[eabi(i6)]
    #[nid(0x63632449)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoIoctl(
        fd: FileId, cmd: u32, in_buf: *mut u8, in_size: SceSize, out_buf: *mut u8,
        out_size: SceSize,
    ) -> SceResult<u32>;

    /// Performs an I/O Control command on a file asynchronously.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `cmd`: The command to send to the device.
    /// - `in_buf` **[[In parameter]]**: A pointer to a data block buffer to send to the device. If
    ///   [`null`](core::ptr::null_mut) it sends no data.
    /// - `in_size`: The size of the `in_buf`.
    /// - `out_buf` **[[Out parameter]]**: A pointer to a data block buffer to receive data from the
    ///   device. If [`null`](core::ptr::null_mut) it receives no data.
    /// - `out_size`: The size of the `out_buf`.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success (meaning depends on the command), error value otherwise.
    #[eabi(i6)]
    #[nid(0xE95A012B)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoIoctlAsync(
        fd: FileId, cmd: u32, in_buf: *mut u8, in_size: SceSize, out_buf: *mut u8,
        out_size: SceSize,
    ) -> SceResult<u32>;

    /// Waits for a file asynchronous action completion.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `return` **[[Out parameter]]**: A reference to the result of the async action.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xE23EEC33)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceIoWaitAsync(fd: FileId, result: &mut i64) -> SceResult<()>;

    /// Waits for a file asynchronous action completion with callbacks.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `return` **[[Out parameter]]**: A reference to the result of the async action.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x35DBD746)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceIoWaitAsyncCB(fd: FileId, result: &mut i64) -> SceResult<()>;

    /// Polls a file asynchronous task completion.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `return` **[[Out parameter]]**: A reference to the result of the async action.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x3251EA56)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceIoPollAsync(fd: FileId, result: &mut i64) -> SceResult<()>;

    /// Gets the completions status of a file asynchronous task.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `pool`: If `0` then waits for the status, otherwise it polls the file descriptor.
    /// - `return` **[[Out parameter]]**: A reference to the result of the async action.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xCB05F8D6)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceIoGetAsyncStat(fd: FileId, poll: u32, result: &mut i64) -> SceResult<()>;

    /// Cancels a file asynchronous task.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xE8BC6571)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceIoCancel(fd: FileId) -> SceResult<()>;

    /// Changes the priority level of a file asynchronous task.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `priority`: The priority level.
    ///   - On user request, it must be `-1` or in the range of `7` to `120`.
    ///   - On kernel request, it must be `-1` or in the range of `0` to `127`.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xB293727F)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceIoChangeAsyncPriority(fd: FileId, priority: i32) -> SceResult<()>;

    /// Sets a callback for the file asynchronous task.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `callback_id`: The callback UID. It is created with [`sceKernelCreateCallback`].
    /// - `argp` **[[In-out parameter]]**: A pointer to the arguments to pass to the callback.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xA12A0514)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoSetAsyncCallback(
        fd: FileId, callback_id: CallbackId, argp: *mut c_void,
    ) -> SceResult<()>;

    /// Gets the device attribute of the opened file descriptor.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    ///
    /// # Returns Value
    ///
    /// Returns the device attribute on success, error value otherwise.
    #[nid(0x08BD7374)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceIoGetDevType(fd: FileId) -> SceResult<DeviceAttribute>;

    /// Gets the list of opened file descriptor UIDs.
    ///
    /// This function filters by caller permission, so callers only receive the file descriptors
    /// they have access.
    ///
    /// # Parameters
    ///
    /// - `fd_list` **[[Out parameter]]**: A pointer to a list to receive the information.
    /// - `fd_list_size`: The total size of `fd_list`.
    /// - `count` **[[Out parameter]]**: A pointer to receive how many file descriptor are open. If
    ///   `null` this information is not retrieved.
    ///
    /// # Return Value
    ///
    /// Returns the number of file descriptor UID added to the list on success, error value
    /// otherwise.
    #[nid(0x5C2BE2CC)]
    #[cfg(not(feature = "kernel"))]
    pub unsafe fn sceIoGetFdList(
        fd_list: *mut FileId, fd_list_size: SceSize, count: *mut SceSize,
    ) -> SceResult<SceSize>;
}

// FIXME: Missing functions
//
// int sceIoGetFdDebugInfo(int fd, SceIoFdDebugInfo *outInfo);
// int sceIoAddHook(SceIoHookType *hook);
#[cfg(feature = "kernel")]
#[psp_stub(libname = "IoFileMgrForKernel", flags = 0x0009, use_crate)]
unsafe extern "C" {
    /// Opens a file with the corresponding file access attributes.
    ///
    /// The function only supports full path.
    ///
    /// If the flag [`FileFlags::CreateFile`] is set in `flags`, the third parameter is used if the
    /// file needs to be created, otherwise it is ignored.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file to open.
    /// - `flags`: The flags with file access attributes.
    /// - `mode`: The permission mode to use. If [`FileFlags::CreateFile`] is set in `flags`, it is
    ///   ignored otherwise.
    ///
    /// # Result Value
    ///
    /// Returns the open file descriptor ID on success, error value otherwise.
    #[nid(0x109F50BC)]
    pub unsafe fn sceIoOpen(path: *const u8, flags: FileFlags, mode: Mode) -> SceResult<FileId>;

    /// Opens a file with the corresponding file access attributes asynchronously.
    ///
    /// The function only supports full path.
    ///
    /// If the flag [`FileFlags::CreateFile`] is set in `flags`, the third parameter is used if the
    /// file needs to be created, otherwise it is ignored.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file to open.
    /// - `flags`: The flags with file access attributes.
    /// - `mode`: The permission mode to use. If [`FileFlags::CreateFile`] is set in `flags`, it is
    ///   ignored otherwise.
    ///
    /// # Result Value
    ///
    /// Returns the open file descriptor ID on success, error value otherwise.
    #[nid(0x89AA9906)]
    pub unsafe fn sceIoOpenAsync(
        path: *const u8, flags: FileFlags, mode: Mode,
    ) -> SceResult<FileId>;

    /// Reopens an existing file descriptor UID.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file to open.
    /// - `flags`: The flags with file access attributes.
    /// - `mode`: The permission mode to use. If [`FileFlags::CreateFile`] is set in `flags`, it is
    ///   ignored otherwise.
    /// - `fd`: The old/closed file descriptor UID.
    ///
    /// # Return Value
    ///
    /// Returns the reopened file descriptor UID on success, error value otherwise.
    #[nid(if cfg!(feature = "psp_660") { 0x947D7A06 }
        else if cfg!(feature = "psp_630") { 0x421B8EB4 }
        else if cfg!(feature = "psp_600") { 0xF0AD3C72 }
        else if cfg!(feature = "psp_570") { 0x593C32F4 }
        else if cfg!(feature = "psp_500") { 0x30DA4775 }
        else if cfg!(feature = "psp_420") { 0x9F096EDF }
        else if cfg!(feature = "psp_395") { 0xD6569E5A }
        else if cfg!(feature = "psp_380") { 0xCB1F53B3 }
        else { 0x3C54E908 }
    )]
    pub unsafe fn sceIoReopen(
        path: *const u8, flags: FileFlags, mode: Mode, fd: FileId,
    ) -> SceResult<FileId>;

    /// Closes a open file and deletes the associated file descriptor ID.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x810C4BC3)]
    pub unsafe fn sceIoClose(fd: FileId) -> SceResult<()>;

    /// Closes a open file and deletes the associated file descriptor ID asynchronously.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xFF5940B6)]
    pub unsafe fn sceIoCloseAsync(fd: FileId) -> SceResult<()>;

    /// Reads data from the file associated to the file descriptor UID to a buffer.
    ///
    /// # Parameter
    ///
    /// - `fd`: The file descriptor UID.
    /// - `buf` **[[Out parameter]]**: A pointer to the buffer to receive the data read.
    /// - `buf_size`: The size of the buffer.
    ///
    /// # Returns Value
    ///
    /// Returns the number of bytes read on success, error value otherwise.
    #[nid(0x6A638D83)]
    pub unsafe fn sceIoRead(fd: FileId, buf: *mut u8, buf_size: SceSize) -> SceResult<SceSize>;

    /// Reads data from the file associated to the file descriptor UID to a buffer asynchronously.
    ///
    /// # Parameter
    ///
    /// - `fd`: The file descriptor UID.
    /// - `buf` **[[Out parameter]]**: A pointer to the buffer to receive the data read.
    /// - `buf_size`: The size of the buffer.
    ///
    /// # Returns Value
    ///
    /// Returns the number of bytes read on success, error value otherwise.
    #[nid(0xA0B5A7C2)]
    pub unsafe fn sceIoReadAsync(fd: FileId, buf: *mut u8, buf_size: SceSize)
        -> SceResult<SceSize>;

    /// Writes data to the file associated to the file descriptor UID.
    ///
    /// # Parameter
    ///
    /// - `fd`: The file descriptor UID.
    /// - `data` **[[In parameter]]**: A pointer to a buffer data to write.
    /// - `data_size`: The size of `data` buffer.
    ///
    /// # Return Value
    ///
    /// Returns the number of bytes written on success, error value otherwise.
    #[nid(0x42EC03AC)]
    pub unsafe fn sceIoWrite(fd: FileId, data: *const u8, data_size: SceSize)
        -> SceResult<SceSize>;

    /// Writes data to the file associated to the file descriptor UID asynchronously.
    ///
    /// # Parameter
    ///
    /// - `fd`: The file descriptor UID.
    /// - `data` **[[In parameter]]**: A pointer to a buffer data to write.
    /// - `data_size`: The size of `data` buffer.
    ///
    /// # Return Value
    ///
    /// Returns the number of bytes written on success, error value otherwise.
    #[nid(0x0FACAB19)]
    pub unsafe fn sceIoWriteAsync(
        fd: FileId, data: *const u8, data_size: SceSize,
    ) -> SceResult<SceSize>;

    /// Repositions the file offset of the file descriptor.
    ///
    /// # Parameters
    /// - `fd`: The file descriptor UID.
    /// - `offset`: The relative offset from the start position determined by `whence`.
    /// - `whence`: The start position options to use for the relative `offset`.
    ///
    /// # Return Value
    ///
    /// Returns the position of the internal file offset on success, error value otherwise.
    #[eabi(i_ii_i_rii)]
    #[nid(0x27EB27B8)]
    pub safe fn sceIoLseek(fd: FileId, offset: i64, whence: Whence) -> SceResult64<u64>;

    /// Repositions the file offset of the file descriptor asynchronously.
    ///
    /// # Parameters
    /// - `fd`: The file descriptor UID.
    /// - `offset`: The relative offset from the start position determined by `whence`.
    /// - `whence`: The start position options to use for the relative `offset`.
    ///
    /// # Return Value
    ///
    /// Returns the position of the internal file offset on success, error value otherwise.
    #[eabi(i_ii_i_rii)]
    #[nid(0x71B19E77)]
    pub safe fn sceIoLseekAsync(fd: FileId, offset: i64, whence: Whence) -> SceResult64<u64>;

    /// Repositions the file offset of the file descriptor. (32-bit mode).
    ///
    /// # Parameters
    /// - `fd`: The file descriptor UID.
    /// - `offset`: The relative offset from the start position determined by `whence`.
    /// - `whence`: The start position options to use for the relative `offset`.
    ///
    /// # Return Value
    ///
    /// Returns the position of the internal file offset on success, error value otherwise.
    #[nid(0x68963324)]
    pub safe fn sceIoLseek32(fd: FileId, offset: i32, whence: Whence) -> SceResult<SceSize>;

    /// Repositions the file offset of the file descriptor asynchronously. (32-bit mode).
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `offset`: The relative offset from the start position determined by `whence`.
    /// - `whence`: The start position options to use for the relative `offset`.
    ///
    /// # Return Value
    ///
    /// Returns the position of the internal file offset on success, error value otherwise.
    #[nid(0x1B385D8F)]
    pub safe fn sceIoLseek32Async(fd: FileId, offset: i32, whence: Whence) -> SceResult<SceSize>;

    /// Removes a file associated to a given path.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file to remove.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xF27A9C51)]
    pub unsafe fn sceIoRemove(path: *const u8) -> SceResult<()>;

    /// Creates a directory file.
    ///
    /// # Parameters
    ///
    /// - `dir_path` **[[In parameter]]**: The path to create the directory file.
    /// - `mode`: The permission mode to set on the created file.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x06A70004)]
    pub unsafe fn sceIoMkdir(dir_path: *const u8, mode: Mode) -> SceResult<()>;

    /// Removes a directory file associated to a given path.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file to remove.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x1117C65F)]
    pub unsafe fn sceIoRmdir(path: *const u8) -> SceResult<()>;

    /// Changes the current directory.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file to change.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x55F4717D)]
    pub unsafe fn sceIoChdir(path: *const u8) -> SceResult<()>;

    /// Changes the file name to a new name.
    ///
    /// # Parameters
    ///
    /// - `old_name` **[[In parameter]]**: The old name for the file.
    /// - `new_name` **[[In parameter]]**: The new name for the file.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x779103A0)]
    pub unsafe fn sceIoRename(old_name: *const u8, new_name: *const u8) -> SceResult<()>;

    /// Opens a directory.
    ///
    /// # Parameters
    ///
    /// - `dir_path` **[[In parameter]]**: The directory path to open.
    ///
    /// # Result Value
    ///
    /// Returns the open file descriptor ID on success, error value otherwise.
    #[nid(0xB29DDF9C)]
    pub unsafe fn sceIoDopen(dir_path: *const u8) -> SceResult<FileId>;

    /// Reads an entry from a opened file descriptor UID associated to a file opened with
    /// [`sceIoDopen`].
    ///
    /// # Parameters
    ///
    /// - `dir_fd`: The file descriptor UID.
    /// - `entry_info` **[[Out parameter]]**: A reference to the structure to receive the directory
    ///   entry information.
    ///
    /// # Return Value
    ///
    /// Returns, on success, `0` if there is no more directory entries left, `> 0` if there are more
    /// directory entries to go. On error, a error value is returned.
    #[nid(0xE3EB004C)]
    pub safe fn sceIoDread(dir_fd: FileId, entry_info: &mut Dirent) -> SceResult<u32>;

    /// Closes an directory opened with [`sceIoDopen`].
    ///
    /// # Parameters
    ///
    /// - `dir_fd`: The directory file descriptor UID.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xEB092469)]
    pub unsafe fn sceIoDclose(dir_fd: FileId) -> SceResult<()>;

    /// Gets the status of a file.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file.
    /// - `stat` **[[Out parameter]]**: A reference to receive the status data from the file.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xACE946E8)]
    pub unsafe fn sceIoGetstat(path: *const u8, stat: &mut Stat) -> SceResult<()>;

    /// Changes the status of a file.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file.
    /// - `stat` **[[In parameter]]**: A reference to the status data to modify the file stat.
    /// - `change_bits`: The bitflags of what field of stat to change.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xB8A740F4)]
    pub unsafe fn sceIoChstat(
        path: *const u8, stat: &Stat, change_bits: ChangeStatFlag,
    ) -> SceResult<()>;

    /// Assigns one I/O device to another.
    ///
    /// # Parameters
    ///
    /// - `dev` **[[In parameter]]**: The device name to assign.
    /// - `block_dev` **[[In parameter]]**: The block device name to assign from.
    /// - `fs` **[[In parameter]]**: The filesystem device name to map the block device to `dev`.
    /// - `flags`: The mounting modes flags.
    /// - `unk1`: Unknown. Set it to [`null`](core::ptr::null_mut).
    /// - `unk2`: Unknown. Set it to `0`.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[eabi(i6)]
    #[nid(0xB2A628C1)]
    pub unsafe fn sceIoAssign(
        dev: *const u8, block_dev: *const u8, fs: *const u8, flags: AssignFlag, unk1: *mut c_void,
        unk2: u32,
    ) -> SceResult<()>;

    /// Unassign an I/O device.
    ///
    /// # Parameters
    ///
    /// - `dev` **[[In parameter]]**: The device name to unassign.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x6D08A871)]
    pub unsafe fn sceIoUnassign(dev: *const u8) -> SceResult<()>;

    /// Performs an Device Control command on a device.
    ///
    /// # Parameters
    ///
    /// - `dev` **[[In parameter]]**: The device name.
    /// - `cmd`: The command to send to the device.
    /// - `in_buf` **[[In parameter]]**: A pointer to a data block buffer to send to the device. If
    ///   [`null`](core::ptr::null_mut) it sends no data.
    /// - `in_size`: The size of the `in_buf`.
    /// - `out_buf` **[[Out parameter]]**: A pointer to a data block buffer to receive data from the
    ///   device. If [`null`](core::ptr::null_mut) it receives no data.
    /// - `out_size`: The size of the `out_buf`.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success (meaning depends on the command), error value otherwise.
    #[eabi(i6)]
    #[nid(0x54F5FB11)]
    pub unsafe fn sceIoDevctl(
        dev: *const u8, cmd: u32, in_buf: *mut u8, in_size: SceSize, out_buf: *mut u8,
        out_size: SceSize,
    ) -> SceResult<u32>;

    /// Performs an I/O Control command on a file.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `cmd`: The command to send to the file.
    /// - `in_buf` **[[In parameter]]**: A pointer to a data block buffer to send to the file. If
    ///   [`null`](core::ptr::null_mut) it sends no data.
    /// - `in_size`: The size of the `in_buf`.
    /// - `out_buf` **[[Out parameter]]**: A pointer to a data block buffer to receive data from the
    ///   file. If [`null`](core::ptr::null_mut) it receives no data.
    /// - `out_size`: The size of the `out_buf`.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success (meaning depends on the command), error value otherwise.
    #[eabi(i6)]
    #[nid(0x63632449)]
    pub unsafe fn sceIoIoctl(
        fd: FileId, cmd: u32, in_buf: *mut u8, in_size: SceSize, out_buf: *mut u8,
        out_size: SceSize,
    ) -> SceResult<i32>;

    /// Performs an I/O Control command on a file asynchronously.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `cmd`: The command to send to the device.
    /// - `in_buf` **[[In parameter]]**: A pointer to a data block buffer to send to the device. If
    ///   [`null`](core::ptr::null_mut) it sends no data.
    /// - `in_size`: The size of the `in_buf`.
    /// - `out_buf` **[[Out parameter]]**: A pointer to a data block buffer to receive data from the
    ///   device. If [`null`](core::ptr::null_mut) it receives no data.
    /// - `out_size`: The size of the `out_buf`.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[eabi(i6)]
    #[nid(0xE95A012B)]
    pub unsafe fn sceIoIoctlAsync(
        fd: FileId, cmd: u32, in_buf: *mut u8, in_size: SceSize, out_buf: *mut u8,
        out_size: SceSize,
    ) -> SceResult<u32>;

    /// Synchronize the file data on the device.
    ///
    /// # Parameters
    ///
    /// - `dev` **[[In parameter]]**: The device name to sync.
    /// - `unk`: Unknown value.
    ///
    /// # Return Value
    ///
    /// Returns an unknown value on success, error value otherwise.
    #[nid(0xAB96437F)]
    pub unsafe fn sceIoSync(dev: *const u8, unk: u32) -> SceResult<u32>;

    /// Waits for a file asynchronous action completion.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `return` **[[Out parameter]]**: A reference to the result of the async action.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xE23EEC33)]
    pub safe fn sceIoWaitAsync(fd: FileId, result: &mut i64) -> SceResult<()>;

    /// Waits for a file asynchronous action completion with callbacks.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `return` **[[Out parameter]]**: A reference to the result of the async action.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x35DBD746)]
    pub safe fn sceIoWaitAsyncCB(fd: FileId, result: &mut i64) -> SceResult<()>;

    /// Polls a file asynchronous task completion.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `return` **[[Out parameter]]**: A reference to the result of the async action.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x3251EA56)]
    pub safe fn sceIoPollAsync(fd: FileId, result: &mut i64) -> SceResult<()>;

    /// Gets the completions status of a file asynchronous task.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `pool`: If `0` then waits for the status, otherwise it polls the file descriptor.
    /// - `return` **[[Out parameter]]**: A reference to the result of the async action.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xCB05F8D6)]
    pub safe fn sceIoGetAsyncStat(fd: FileId, poll: u32, result: &mut i64) -> SceResult<()>;

    /// Cancels a file asynchronous task.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xE8BC6571)]
    pub safe fn sceIoCancel(fd: FileId) -> SceResult<()>;

    /// Changes the priority level of a file asynchronous task.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `priority`: The priority level.
    ///   - On user request, it must be `-1` or in the range of `7` to `120`.
    ///   - On kernel request, it must be `-1` or in the range of `0` to `127`.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xB293727F)]
    pub safe fn sceIoChangeAsyncPriority(fd: FileId, priority: i32) -> SceResult<()>;

    /// Sets a callback for the file asynchronous task.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `callback_id`: The callback UID. It is created with [`sceKernelCreateCallback`].
    /// - `argp` **[[In-out parameter]]**: A pointer to the arguments to pass to the callback.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    ///
    /// [`sceKernelCreateCallback`]: crate::sys::thread::sceKernelCreateCallback
    #[nid(0xA12A0514)]
    pub unsafe fn sceIoSetAsyncCallback(
        fd: FileId, callback_id: CallbackId, argp: *mut c_void,
    ) -> SceResult<()>;

    /// Gets the device attribute of the opened file descriptor.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    ///
    /// # Returns Value
    ///
    /// Returns the device attribute on success, error value otherwise.
    #[nid(0x08BD7374)]
    pub safe fn sceIoGetDevType(fd: FileId) -> SceResult<DeviceAttribute>;

    /// Gets the real file descriptor UID from global list of UID.
    ///
    /// # Parameters
    ///
    /// - `fd`: A file descriptor UID returned from a [`sceIoOpen`]/[`sceIoOpenAsync`] with the
    ///   [`FileFlags::GlobalFdIndex`] set.
    ///
    /// # Return Value
    ///
    /// Returns the real file descriptor UID on success, error value otherwise.
    ///
    /// # Firmware Version
    ///
    /// This API was introduced on PSP firmware version 3.50.
    #[nid(if cfg!(feature = "psp_660") { 0xDCCD6185 }
        else if cfg!(feature = "psp_630") { 0x64ED84C9 }
        else if cfg!(feature = "psp_600") { 0x4F663EBF }
        else if cfg!(feature = "psp_570") { 0xB83F536C }
        else if cfg!(feature = "psp_500") { 0x10656D20 }
        else if cfg!(feature = "psp_420") { 0x6C2EBE4E }
        else if cfg!(feature = "psp_395") { 0x450EDC8A }
        else if cfg!(feature = "psp_380") { 0xE5A18603 }
        else { 0x9B86630B }
    )]
    pub safe fn sceIoGetUID(fd: FileId) -> SceResult<FileId>;

    /// Gets the list of opened file descriptor UIDs.
    ///
    /// This function filters by caller permission, so callers only receive the file descriptors
    /// they have access.
    ///
    /// # Parameters
    ///
    /// - `fd_list` **[[Out parameter]]**: A pointer to a list to receive the information.
    /// - `fd_list_size`: The total size of `fd_list`.
    /// - `count` **[[Out parameter]]**: A pointer to receive how many file descriptor are open. If
    ///   `null` this information is not retrieved.
    ///
    /// # Return Value
    ///
    /// Returns the number of file descriptor UID added to the list on success, error value
    /// otherwise.
    #[nid(0x5C2BE2CC)]
    pub unsafe fn sceIoGetFdList(
        fd_list: *mut FileId, fd_list_size: SceSize, count: *mut SceSize,
    ) -> SceResult<SceSize>;

    /// Adds a new I/O driver to the system.
    ///
    /// # Parameters
    ///
    /// - `drv` **[[In parameter]]**: A pointer to a filled out driver structure.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0x8E982A74)]
    pub unsafe fn sceIoAddDrv(drv: *const DriveDevice) -> SceResult<()>;

    /// Removes a I/O driver from the system.
    ///
    /// This functions fails if the driver doesn't have a [`DriveFunctionTable::exit`]
    /// implementation.
    ///
    /// # Parameters
    ///
    /// - `drv_name` **[[In parameter]]**: The name of the driver to delete (null terminated).
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(0xC7F35804)]
    pub unsafe fn sceIoDelDrv(drv_name: *const u8) -> SceResult<()>;

    /// Forcedly removes a I/O driver from the system.
    ///
    /// This doesn't execute the driver [`DriveFunctionTable::exit`] function like [`sceIoDelDrv`].
    ///
    /// # Parameters
    ///
    /// - `drv_name` **[[In parameter]]**: The name of the driver to delete (null terminated).
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    ///
    /// # Firmware Version
    ///
    /// This API was introduced on PSP firmware version 2.80.
    #[nid(if cfg!(feature = "psp_660") { 0x76DA16E3 }
        // else if cfg!(feature = "psp_630") { 0x5216CE3F }
        // else if cfg!(feature = "psp_600") { 0x5216CE3F }
        else if cfg!(feature = "psp_570") { 0x1D0D4B29 }
        else if cfg!(feature = "psp_500") { 0x5BC52506 }
        else if cfg!(feature = "psp_420") { 0x1F54AE78 }
        else if cfg!(feature = "psp_395") { 0x72AC9C0E }
        else if cfg!(feature = "psp_380") { 0xC27B252F }
        else { 0x5216CE3F }
    )]
    pub unsafe fn sceIoTerminateFd(drv_name: *const u8) -> SceResult<()>;

    /// Gets the user level out of I/O block.
    ///
    /// # Parameters
    ///
    /// - `block` **[[In parameter]]**: A reference of the device block you want to get.
    ///
    /// # Return Value
    ///
    /// Returns the block user level.
    ///
    /// # Firmware Version
    ///
    /// This API was introduced on PSP firmware version 1.52.
    #[nid(if cfg!(feature = "psp_660") { 0x49356C12 }
        else if cfg!(feature = "psp_630") { 0x804DFCE6 }
        else if cfg!(feature = "psp_600") { 0x6CE0E5F0 }
        else if cfg!(feature = "psp_570") { 0xBD7D5591 }
        else if cfg!(feature = "psp_500") { 0xFFE9FFDE }
        else if cfg!(feature = "psp_420") { 0x6A90F545 }
        else if cfg!(feature = "psp_395") { 0x993395FE }
        else if cfg!(feature = "psp_380") { 0x128BD999 }
        else { 0xBD17474F }
    )]
    pub safe fn sceIoGetIobUserLevel(block: &IoBlockInfo) -> u32;

    /// Checks for the validity of a file descriptor.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    /// - `unk`: Unknown, permission related. Checked against a system object if `(obj.attr & unk)
    ///   != 0`.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    ///
    /// # Firmware Version
    ///
    /// This API was introduced on PSP firmware version 3.70.
    #[nid(if cfg!(feature = "psp_660") { 0x2B6A9B21 }
        else if cfg!(feature = "psp_630") { 0x13A4DEB0 }
        else if cfg!(feature = "psp_600") { 0xF2990AC6 }
        else if cfg!(feature = "psp_570") { 0xB3411C4F }
        else if cfg!(feature = "psp_500") { 0x5B00C8FB }
        else if cfg!(feature = "psp_420") { 0x2B8EC797 }
        else if cfg!(feature = "psp_395") { 0x0D6CC391 }
        else if cfg!(feature = "psp_380") { 0x588C6903 }
        else { 0x30E8ABB3 }
    )]
    pub safe fn sceIoValidateFd(fd: FileId, unk: u32) -> SceResult<()>;

    /// Gets the current working directory for a thread.
    ///
    /// # Parameters
    ///
    /// - `thread_id`: The thread UID of the thread.
    /// - `path_buf` **[[Out parameter]]**: A pointer to a buffer to receive the data.
    /// - `path_buf_size`: The size of `path_buf`.
    ///
    /// # Return Value
    ///
    /// Returns the number of characters written to `path_buf` on success, an error value otherwise.
    #[nid(if cfg!(feature = "psp_660") { 0x1FC0620B }
        else if cfg!(feature = "psp_630") { 0x74482CE3 }
        else if cfg!(feature = "psp_600") { 0x0AB86E5D }
        else if cfg!(feature = "psp_570") { 0x2912ADE8 }
        else if cfg!(feature = "psp_500") { 0x957305E4 }
        else if cfg!(feature = "psp_420") { 0x34ADDEA9 }
        else if cfg!(feature = "psp_395") { 0x636BB28B }
        else if cfg!(feature = "psp_380") { 0x0B281A72 }
        else { 0x411106BA }
    )]
    pub unsafe fn sceIoGetThreadCwd(
        thread_id: ThreadId, path_buf: *mut u8, path_buf_size: SceSize,
    ) -> SceResult<SceSize>;

    /// Sets the current working directory for a thread.
    ///
    /// # Parameters
    ///
    /// - `thread_id`: The thread UID of the thread.
    /// - `dir_path` **[[In parameter]]**: The directory path to set.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    #[nid(if cfg!(feature = "psp_660") { 0xC30581F4 }
        else if cfg!(feature = "psp_630") { 0xBCC4C96F }
        else if cfg!(feature = "psp_600") { 0x9D5CDC31 }
        else if cfg!(feature = "psp_570") { 0x8C15C11E }
        else if cfg!(feature = "psp_500") { 0xA72FAEB4 }
        else if cfg!(feature = "psp_420") { 0xC87784D8 }
        else if cfg!(feature = "psp_395") { 0xCA3B4391 }
        else if cfg!(feature = "psp_380") { 0xA16D8C5C }
        else { 0xCB0A151F }
    )]
    pub unsafe fn sceIoChangeThreadCwd(thread_id: ThreadId, dir_path: *const u8) -> SceResult<()>;
}

// FIXME (Low-priority): Add missing itens
// - (fdgetc, 0xD2B2A2A7)
// - (fdgets, 0x11A5127A)
// - (fdprintf, 0x2CCF071A)
// - (fdputc, 0x4F78930A)
// - (fdputs, 0x36B23B8B)
// - (getchar, 0x7E338487)
// - (gets, 0xBFF7E760)
// - (printf, 0xCAB439DF)
// - (putchar, 0xD768752A)
// - (puts, 0xD97C8CB9)
#[psp_stub(libname = "StdioForUser", flags = 0x4009, use_crate)]
unsafe extern "C" {
    /// Function to get the current standard in file ID
    ///
    /// # Return Value
    ///
    /// The stdin file ID.
    #[nid(0x172D316E)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceKernelStdin() -> FileId;

    /// Function to get the current standard out file ID
    ///
    /// # Return Value
    ///
    /// The stdout file ID.
    #[nid(0xA6BAB2E9)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceKernelStdout() -> FileId;

    /// Function to get the current standard error file ID
    ///
    /// # Return Value
    ///
    /// The stderr file ID.
    #[nid(0xF78BA90A)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceKernelStderr() -> FileId;

    /// Register a file descriptor as PIPE to stdout.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    ///
    /// # Firmware Version
    ///
    /// This API was introduced on PSP firmware version 2.00.
    #[nid(0x432D8F5C)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceKernelRegisterStdoutPipe(fd: FileId) -> SceResult<()>;

    /// Register a file descriptor as PIPE to stderr.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    ///
    /// # Firmware Version
    ///
    /// This API was introduced on PSP firmware version 2.00.
    #[nid(0x6F797E03)]
    #[cfg(not(feature = "kernel"))]
    pub safe fn sceKernelRegisterStderrPipe(fd: FileId) -> SceResult<()>;
}

#[cfg(feature = "kernel")]
#[psp_stub(libname = "StdioForKernel", flags = 0x0009, use_crate)]
unsafe extern "C" {
    /// Function to get the current standard in file ID
    ///
    /// # Return Value
    ///
    /// The stdin file ID.
    #[nid(0x172D316E)]
    pub safe fn sceKernelStdin() -> FileId;

    /// Function to get the current standard out file ID
    ///
    /// # Return Value
    ///
    /// The stdout file ID.
    #[nid(0xA6BAB2E9)]
    pub safe fn sceKernelStdout() -> FileId;

    /// Function to get the current standard error file ID
    ///
    /// # Return Value
    ///
    /// The stderr file ID.
    #[nid(0xF78BA90A)]
    pub safe fn sceKernelStderr() -> FileId;

    /// Register a file descriptor as PIPE to stdout.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    ///
    /// # Firmware Version
    ///
    /// This API was introduced on PSP firmware version 2.00.
    #[nid(0x432D8F5C)]
    pub safe fn sceKernelRegisterStdoutPipe(fd: FileId) -> SceResult<()>;

    /// Register a file descriptor as PIPE to stderr.
    ///
    /// # Parameters
    ///
    /// - `fd`: The file descriptor UID.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    ///
    /// # Firmware Version
    ///
    /// This API was introduced on PSP firmware version 2.00.
    #[nid(0x6F797E03)]
    pub safe fn sceKernelRegisterStderrPipe(fd: FileId) -> SceResult<()>;

    /// Reopens the standard Out.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file to open.
    /// - `flags`: The flags with file access attributes.
    /// - `mode`: The permission mode to use. If [`FileFlags::CreateFile`] is set in `flags`, it is
    ///   ignored otherwise.
    ///
    /// # Return Value
    ///
    /// Returns the reopened file descriptor UID on success, error value otherwise.
    #[nid(0x98220F3E)]
    pub unsafe fn sceKernelStdoutReopen(
        path: *const u8, flags: FileFlags, mode: Mode,
    ) -> SceResult<FileId>;

    /// Reopens the standard Error.
    ///
    /// # Parameters
    ///
    /// - `path` **[[In parameter]]**: The path to the file to open.
    /// - `flags`: The flags with file access attributes.
    /// - `mode`: The permission mode to use. If [`FileFlags::CreateFile`] is set in `flags`, it is
    ///   ignored otherwise.
    ///
    /// # Return Value
    ///
    /// Returns the reopened file descriptor UID on success, error value otherwise.
    #[nid(0xFB5380C5)]
    pub unsafe fn sceKernelStderrReopen(
        path: *const u8, flags: FileFlags, mode: Mode,
    ) -> SceResult<FileId>;

    /// Resets the standard Out.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    ///
    /// # Firmware Version
    ///
    /// This API was introduced on PSP firmware version 2.00.
    #[nid(0x2D8551AB)]
    pub safe fn sceKernelStdoutReset() -> SceResult<()>;

    /// Resets the standard Error.
    ///
    /// # Return Value
    ///
    /// `Ok` value on success, error value otherwise.
    ///
    /// # Firmware Version
    ///
    /// This API was introduced on PSP firmware version 2.00.
    #[nid(0x9662BF86)]
    pub safe fn sceKernelStderrReset() -> SceResult<()>;
}

impl FileId {
    /// Create a new file descriptor ID from a raw value.
    ///
    /// This functions checks for the value of `raw` to be a in the range of possible `SceAtracId`
    /// values used by the PSP OS, returning an [`None`] otherwise.
    pub const fn from_raw(raw: u32) -> Option<Self> {
        if let 0..=0x7FFFFFFF = raw {
            Some(unsafe { Self::from_raw_unchecked(raw) })
        } else {
            None
        }
    }

    /// Create a new file descriptor ID structure from a raw value without checking value range.
    ///
    /// # Safety
    ///
    /// Immediate language UB if `val` is not within the valid range for this
    /// type, as it violates the validity invariant.
    #[inline]
    pub const unsafe fn from_raw_unchecked(raw: u32) -> Self {
        Self(unsafe { SceUid::from_raw_unchecked(raw) })
    }

    #[inline]
    pub const fn to_inner(self) -> u32 {
        // SAFETY: pattern types are always legal values of their base type
        // (Not using `.0` because that has perf regressions.)
        unsafe { core::mem::transmute(self) }
    }
}

impl crate::private::Sealed for FileId {}
unsafe impl SceResultOk for FileId {
    unsafe fn handle_ok_value(ok_value: u32) -> Result<Self, SceError> {
        unsafe { SceUid::handle_ok_value(ok_value).map(Self) }
    }
}
unsafe impl SceIntoOkValue for FileId {
    fn into_ok_value(self) -> u32 {
        self.to_inner()
    }
}

impl DeviceAttribute {
    pub const fn device_kind(self) -> DeviceKind {
        // Safety: the device kind is hold in the last 8bits and will always be one of the device
        // kind values
        unsafe { mem::transmute(self.and(Self::from_bits_retain(0xFF)).bits()) }
    }
}

impl crate::private::Sealed for DeviceAttribute {}
unsafe impl SceResultOk for DeviceAttribute {
    unsafe fn handle_ok_value(ok_value: u32) -> Result<Self, SceError> {
        Ok(Self::from_bits_retain(ok_value))
    }
}
unsafe impl SceIntoOkValue for DeviceAttribute {
    fn into_ok_value(self) -> u32 {
        self.0
    }
}