INvDrvServices.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. using Ryujinx.Common;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Cpu;
  4. using Ryujinx.HLE.Exceptions;
  5. using Ryujinx.HLE.HOS.Ipc;
  6. using Ryujinx.HLE.HOS.Services.Nv.NvDrvServices;
  7. using Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostAsGpu;
  8. using Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostChannel;
  9. using Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostCtrl;
  10. using Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvHostCtrlGpu;
  11. using Ryujinx.HLE.HOS.Services.Nv.NvDrvServices.NvMap;
  12. using Ryujinx.HLE.HOS.Services.Nv.Types;
  13. using Ryujinx.Memory;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.Reflection;
  17. namespace Ryujinx.HLE.HOS.Services.Nv
  18. {
  19. [Service("nvdrv")]
  20. [Service("nvdrv:a")]
  21. [Service("nvdrv:s")]
  22. [Service("nvdrv:t")]
  23. class INvDrvServices : IpcService
  24. {
  25. private static Dictionary<string, Type> _deviceFileRegistry = new Dictionary<string, Type>()
  26. {
  27. { "/dev/nvmap", typeof(NvMapDeviceFile) },
  28. { "/dev/nvhost-ctrl", typeof(NvHostCtrlDeviceFile) },
  29. { "/dev/nvhost-ctrl-gpu", typeof(NvHostCtrlGpuDeviceFile) },
  30. { "/dev/nvhost-as-gpu", typeof(NvHostAsGpuDeviceFile) },
  31. { "/dev/nvhost-gpu", typeof(NvHostGpuDeviceFile) },
  32. //{ "/dev/nvhost-msenc", typeof(NvHostChannelDeviceFile) },
  33. { "/dev/nvhost-nvdec", typeof(NvHostChannelDeviceFile) },
  34. //{ "/dev/nvhost-nvjpg", typeof(NvHostChannelDeviceFile) },
  35. { "/dev/nvhost-vic", typeof(NvHostChannelDeviceFile) },
  36. //{ "/dev/nvhost-display", typeof(NvHostChannelDeviceFile) },
  37. };
  38. public static IdDictionary DeviceFileIdRegistry = new IdDictionary();
  39. private IVirtualMemoryManager _clientMemory;
  40. private long _owner;
  41. private bool _transferMemInitialized = false;
  42. public INvDrvServices(ServiceCtx context) : base(context.Device.System.NvDrvServer)
  43. {
  44. _owner = 0;
  45. }
  46. private int Open(ServiceCtx context, string path)
  47. {
  48. if (_deviceFileRegistry.TryGetValue(path, out Type deviceFileClass))
  49. {
  50. ConstructorInfo constructor = deviceFileClass.GetConstructor(new Type[] { typeof(ServiceCtx), typeof(IVirtualMemoryManager), typeof(long) });
  51. NvDeviceFile deviceFile = (NvDeviceFile)constructor.Invoke(new object[] { context, _clientMemory, _owner });
  52. deviceFile.Path = path;
  53. return DeviceFileIdRegistry.Add(deviceFile);
  54. }
  55. else
  56. {
  57. Logger.Warning?.Print(LogClass.ServiceNv, $"Cannot find file device \"{path}\"!");
  58. }
  59. return -1;
  60. }
  61. private NvResult GetIoctlArgument(ServiceCtx context, NvIoctl ioctlCommand, out Span<byte> arguments)
  62. {
  63. (ulong inputDataPosition, ulong inputDataSize) = context.Request.GetBufferType0x21(0);
  64. (ulong outputDataPosition, ulong outputDataSize) = context.Request.GetBufferType0x22(0);
  65. NvIoctl.Direction ioctlDirection = ioctlCommand.DirectionValue;
  66. uint ioctlSize = ioctlCommand.Size;
  67. bool isRead = (ioctlDirection & NvIoctl.Direction.Read) != 0;
  68. bool isWrite = (ioctlDirection & NvIoctl.Direction.Write) != 0;
  69. if ((isWrite && ioctlSize > outputDataSize) || (isRead && ioctlSize > inputDataSize))
  70. {
  71. arguments = null;
  72. Logger.Warning?.Print(LogClass.ServiceNv, "Ioctl size inconsistency found!");
  73. return NvResult.InvalidSize;
  74. }
  75. if (isRead && isWrite)
  76. {
  77. if (outputDataSize < inputDataSize)
  78. {
  79. arguments = null;
  80. Logger.Warning?.Print(LogClass.ServiceNv, "Ioctl size inconsistency found!");
  81. return NvResult.InvalidSize;
  82. }
  83. byte[] outputData = new byte[outputDataSize];
  84. byte[] temp = new byte[inputDataSize];
  85. context.Memory.Read(inputDataPosition, temp);
  86. Buffer.BlockCopy(temp, 0, outputData, 0, temp.Length);
  87. arguments = new Span<byte>(outputData);
  88. }
  89. else if (isWrite)
  90. {
  91. byte[] outputData = new byte[outputDataSize];
  92. arguments = new Span<byte>(outputData);
  93. }
  94. else
  95. {
  96. byte[] temp = new byte[inputDataSize];
  97. context.Memory.Read(inputDataPosition, temp);
  98. arguments = new Span<byte>(temp);
  99. }
  100. return NvResult.Success;
  101. }
  102. private NvResult GetDeviceFileFromFd(int fd, out NvDeviceFile deviceFile)
  103. {
  104. deviceFile = null;
  105. if (fd < 0)
  106. {
  107. return NvResult.InvalidParameter;
  108. }
  109. deviceFile = DeviceFileIdRegistry.GetData<NvDeviceFile>(fd);
  110. if (deviceFile == null)
  111. {
  112. Logger.Warning?.Print(LogClass.ServiceNv, $"Invalid file descriptor {fd}");
  113. return NvResult.NotImplemented;
  114. }
  115. if (deviceFile.Owner != _owner)
  116. {
  117. return NvResult.AccessDenied;
  118. }
  119. return NvResult.Success;
  120. }
  121. private NvResult EnsureInitialized()
  122. {
  123. if (_owner == 0)
  124. {
  125. Logger.Warning?.Print(LogClass.ServiceNv, "INvDrvServices is not initialized!");
  126. return NvResult.NotInitialized;
  127. }
  128. return NvResult.Success;
  129. }
  130. private static NvResult ConvertInternalErrorCode(NvInternalResult errorCode)
  131. {
  132. switch (errorCode)
  133. {
  134. case NvInternalResult.Success:
  135. return NvResult.Success;
  136. case NvInternalResult.Unknown0x72:
  137. return NvResult.AlreadyAllocated;
  138. case NvInternalResult.TimedOut:
  139. case NvInternalResult.TryAgain:
  140. case NvInternalResult.Interrupted:
  141. return NvResult.Timeout;
  142. case NvInternalResult.InvalidAddress:
  143. return NvResult.InvalidAddress;
  144. case NvInternalResult.NotSupported:
  145. case NvInternalResult.Unknown0x18:
  146. return NvResult.NotSupported;
  147. case NvInternalResult.InvalidState:
  148. return NvResult.InvalidState;
  149. case NvInternalResult.ReadOnlyAttribute:
  150. return NvResult.ReadOnlyAttribute;
  151. case NvInternalResult.NoSpaceLeft:
  152. case NvInternalResult.FileTooBig:
  153. return NvResult.InvalidSize;
  154. case NvInternalResult.FileTableOverflow:
  155. case NvInternalResult.BadFileNumber:
  156. return NvResult.FileOperationFailed;
  157. case NvInternalResult.InvalidInput:
  158. return NvResult.InvalidValue;
  159. case NvInternalResult.NotADirectory:
  160. return NvResult.DirectoryOperationFailed;
  161. case NvInternalResult.Busy:
  162. return NvResult.Busy;
  163. case NvInternalResult.BadAddress:
  164. return NvResult.InvalidAddress;
  165. case NvInternalResult.AccessDenied:
  166. case NvInternalResult.OperationNotPermitted:
  167. return NvResult.AccessDenied;
  168. case NvInternalResult.OutOfMemory:
  169. return NvResult.InsufficientMemory;
  170. case NvInternalResult.DeviceNotFound:
  171. return NvResult.ModuleNotPresent;
  172. case NvInternalResult.IoError:
  173. return NvResult.ResourceError;
  174. default:
  175. return NvResult.IoctlFailed;
  176. }
  177. }
  178. [CommandHipc(0)]
  179. // Open(buffer<bytes, 5> path) -> (s32 fd, u32 error_code)
  180. public ResultCode Open(ServiceCtx context)
  181. {
  182. NvResult errorCode = EnsureInitialized();
  183. int fd = -1;
  184. if (errorCode == NvResult.Success)
  185. {
  186. ulong pathPtr = context.Request.SendBuff[0].Position;
  187. ulong pathSize = context.Request.SendBuff[0].Size;
  188. string path = MemoryHelper.ReadAsciiString(context.Memory, pathPtr, (long)pathSize);
  189. fd = Open(context, path);
  190. if (fd == -1)
  191. {
  192. errorCode = NvResult.FileOperationFailed;
  193. }
  194. }
  195. context.ResponseData.Write(fd);
  196. context.ResponseData.Write((uint)errorCode);
  197. return ResultCode.Success;
  198. }
  199. [CommandHipc(1)]
  200. // Ioctl(s32 fd, u32 ioctl_cmd, buffer<bytes, 0x21> in_args) -> (u32 error_code, buffer<bytes, 0x22> out_args)
  201. public ResultCode Ioctl(ServiceCtx context)
  202. {
  203. NvResult errorCode = EnsureInitialized();
  204. if (errorCode == NvResult.Success)
  205. {
  206. int fd = context.RequestData.ReadInt32();
  207. NvIoctl ioctlCommand = context.RequestData.ReadStruct<NvIoctl>();
  208. errorCode = GetIoctlArgument(context, ioctlCommand, out Span<byte> arguments);
  209. if (errorCode == NvResult.Success)
  210. {
  211. errorCode = GetDeviceFileFromFd(fd, out NvDeviceFile deviceFile);
  212. if (errorCode == NvResult.Success)
  213. {
  214. NvInternalResult internalResult = deviceFile.Ioctl(ioctlCommand, arguments);
  215. if (internalResult == NvInternalResult.NotImplemented)
  216. {
  217. throw new NvIoctlNotImplementedException(context, deviceFile, ioctlCommand);
  218. }
  219. errorCode = ConvertInternalErrorCode(internalResult);
  220. if ((ioctlCommand.DirectionValue & NvIoctl.Direction.Write) != 0)
  221. {
  222. context.Memory.Write(context.Request.GetBufferType0x22(0).Position, arguments.ToArray());
  223. }
  224. }
  225. }
  226. }
  227. context.ResponseData.Write((uint)errorCode);
  228. return ResultCode.Success;
  229. }
  230. [CommandHipc(2)]
  231. // Close(s32 fd) -> u32 error_code
  232. public ResultCode Close(ServiceCtx context)
  233. {
  234. NvResult errorCode = EnsureInitialized();
  235. if (errorCode == NvResult.Success)
  236. {
  237. int fd = context.RequestData.ReadInt32();
  238. errorCode = GetDeviceFileFromFd(fd, out NvDeviceFile deviceFile);
  239. if (errorCode == NvResult.Success)
  240. {
  241. deviceFile.Close();
  242. DeviceFileIdRegistry.Delete(fd);
  243. }
  244. }
  245. context.ResponseData.Write((uint)errorCode);
  246. return ResultCode.Success;
  247. }
  248. [CommandHipc(3)]
  249. // Initialize(u32 transfer_memory_size, handle<copy, process> current_process, handle<copy, transfer_memory> transfer_memory) -> u32 error_code
  250. public ResultCode Initialize(ServiceCtx context)
  251. {
  252. long transferMemSize = context.RequestData.ReadInt64();
  253. int transferMemHandle = context.Request.HandleDesc.ToCopy[1];
  254. // TODO: When transfer memory will be implemented, this could be removed.
  255. _transferMemInitialized = true;
  256. int clientHandle = context.Request.HandleDesc.ToCopy[0];
  257. _clientMemory = context.Process.HandleTable.GetKProcess(clientHandle).CpuMemory;
  258. context.Device.System.KernelContext.Syscall.GetProcessId(clientHandle, out _owner);
  259. context.ResponseData.Write((uint)NvResult.Success);
  260. // Close the process and transfer memory handles immediately as we don't use them.
  261. context.Device.System.KernelContext.Syscall.CloseHandle(clientHandle);
  262. context.Device.System.KernelContext.Syscall.CloseHandle(transferMemHandle);
  263. return ResultCode.Success;
  264. }
  265. [CommandHipc(4)]
  266. // QueryEvent(s32 fd, u32 event_id) -> (u32, handle<copy, event>)
  267. public ResultCode QueryEvent(ServiceCtx context)
  268. {
  269. NvResult errorCode = EnsureInitialized();
  270. if (errorCode == NvResult.Success)
  271. {
  272. int fd = context.RequestData.ReadInt32();
  273. uint eventId = context.RequestData.ReadUInt32();
  274. errorCode = GetDeviceFileFromFd(fd, out NvDeviceFile deviceFile);
  275. if (errorCode == NvResult.Success)
  276. {
  277. NvInternalResult internalResult = deviceFile.QueryEvent(out int eventHandle, eventId);
  278. if (internalResult == NvInternalResult.NotImplemented)
  279. {
  280. throw new NvQueryEventNotImplementedException(context, deviceFile, eventId);
  281. }
  282. errorCode = ConvertInternalErrorCode(internalResult);
  283. if (errorCode == NvResult.Success)
  284. {
  285. context.Response.HandleDesc = IpcHandleDesc.MakeCopy(eventHandle);
  286. }
  287. }
  288. }
  289. context.ResponseData.Write((uint)errorCode);
  290. return ResultCode.Success;
  291. }
  292. [CommandHipc(5)]
  293. // MapSharedMemory(s32 fd, u32 argument, handle<copy, shared_memory>) -> u32 error_code
  294. public ResultCode MapSharedMemory(ServiceCtx context)
  295. {
  296. NvResult errorCode = EnsureInitialized();
  297. if (errorCode == NvResult.Success)
  298. {
  299. int fd = context.RequestData.ReadInt32();
  300. uint argument = context.RequestData.ReadUInt32();
  301. int sharedMemoryHandle = context.Request.HandleDesc.ToCopy[0];
  302. errorCode = GetDeviceFileFromFd(fd, out NvDeviceFile deviceFile);
  303. if (errorCode == NvResult.Success)
  304. {
  305. errorCode = ConvertInternalErrorCode(deviceFile.MapSharedMemory(sharedMemoryHandle, argument));
  306. }
  307. }
  308. context.ResponseData.Write((uint)errorCode);
  309. return ResultCode.Success;
  310. }
  311. [CommandHipc(6)]
  312. // GetStatus() -> (unknown<0x20>, u32 error_code)
  313. public ResultCode GetStatus(ServiceCtx context)
  314. {
  315. // TODO: When transfer memory will be implemented, check if it's mapped instead.
  316. if (_transferMemInitialized)
  317. {
  318. // TODO: Populate values when more RE will be done.
  319. NvStatus nvStatus = new NvStatus
  320. {
  321. MemoryValue1 = 0, // GetMemStats(transfer_memory + 0x60, 3)
  322. MemoryValue2 = 0, // GetMemStats(transfer_memory + 0x60, 5)
  323. MemoryValue3 = 0, // transfer_memory + 0x78
  324. MemoryValue4 = 0 // transfer_memory + 0x80
  325. };
  326. context.ResponseData.WriteStruct(nvStatus);
  327. context.ResponseData.Write((uint)NvResult.Success);
  328. Logger.Stub?.PrintStub(LogClass.ServiceNv);
  329. }
  330. else
  331. {
  332. context.ResponseData.Write((uint)NvResult.NotInitialized);
  333. }
  334. return ResultCode.Success;
  335. }
  336. [CommandHipc(7)]
  337. // ForceSetClientPid(u64) -> u32 error_code
  338. public ResultCode ForceSetClientPid(ServiceCtx context)
  339. {
  340. throw new ServiceNotImplementedException(this, context);
  341. }
  342. [CommandHipc(8)]
  343. // SetClientPID(u64, pid) -> u32 error_code
  344. public ResultCode SetClientPid(ServiceCtx context)
  345. {
  346. long pid = context.RequestData.ReadInt64();
  347. context.ResponseData.Write(0);
  348. return ResultCode.Success;
  349. }
  350. [CommandHipc(9)]
  351. // DumpGraphicsMemoryInfo()
  352. public ResultCode DumpGraphicsMemoryInfo(ServiceCtx context)
  353. {
  354. Logger.Stub?.PrintStub(LogClass.ServiceNv);
  355. return ResultCode.Success;
  356. }
  357. [CommandHipc(10)] // 3.0.0+
  358. // InitializeDevtools(u32, handle<copy>) -> u32 error_code;
  359. public ResultCode InitializeDevtools(ServiceCtx context)
  360. {
  361. throw new ServiceNotImplementedException(this, context);
  362. }
  363. [CommandHipc(11)] // 3.0.0+
  364. // Ioctl2(s32 fd, u32 ioctl_cmd, buffer<bytes, 0x21> in_args, buffer<bytes, 0x21> inline_in_buffer) -> (u32 error_code, buffer<bytes, 0x22> out_args)
  365. public ResultCode Ioctl2(ServiceCtx context)
  366. {
  367. NvResult errorCode = EnsureInitialized();
  368. if (errorCode == NvResult.Success)
  369. {
  370. int fd = context.RequestData.ReadInt32();
  371. NvIoctl ioctlCommand = context.RequestData.ReadStruct<NvIoctl>();
  372. (ulong inlineInBufferPosition, ulong inlineInBufferSize) = context.Request.GetBufferType0x21(1);
  373. errorCode = GetIoctlArgument(context, ioctlCommand, out Span<byte> arguments);
  374. byte[] temp = new byte[inlineInBufferSize];
  375. context.Memory.Read(inlineInBufferPosition, temp);
  376. Span<byte> inlineInBuffer = new Span<byte>(temp);
  377. if (errorCode == NvResult.Success)
  378. {
  379. errorCode = GetDeviceFileFromFd(fd, out NvDeviceFile deviceFile);
  380. if (errorCode == NvResult.Success)
  381. {
  382. NvInternalResult internalResult = deviceFile.Ioctl2(ioctlCommand, arguments, inlineInBuffer);
  383. if (internalResult == NvInternalResult.NotImplemented)
  384. {
  385. throw new NvIoctlNotImplementedException(context, deviceFile, ioctlCommand);
  386. }
  387. errorCode = ConvertInternalErrorCode(internalResult);
  388. if ((ioctlCommand.DirectionValue & NvIoctl.Direction.Write) != 0)
  389. {
  390. context.Memory.Write(context.Request.GetBufferType0x22(0).Position, arguments.ToArray());
  391. }
  392. }
  393. }
  394. }
  395. context.ResponseData.Write((uint)errorCode);
  396. return ResultCode.Success;
  397. }
  398. [CommandHipc(12)] // 3.0.0+
  399. // Ioctl3(s32 fd, u32 ioctl_cmd, buffer<bytes, 0x21> in_args) -> (u32 error_code, buffer<bytes, 0x22> out_args, buffer<bytes, 0x22> inline_out_buffer)
  400. public ResultCode Ioctl3(ServiceCtx context)
  401. {
  402. NvResult errorCode = EnsureInitialized();
  403. if (errorCode == NvResult.Success)
  404. {
  405. int fd = context.RequestData.ReadInt32();
  406. NvIoctl ioctlCommand = context.RequestData.ReadStruct<NvIoctl>();
  407. (ulong inlineOutBufferPosition, ulong inlineOutBufferSize) = context.Request.GetBufferType0x22(1);
  408. errorCode = GetIoctlArgument(context, ioctlCommand, out Span<byte> arguments);
  409. byte[] temp = new byte[inlineOutBufferSize];
  410. context.Memory.Read(inlineOutBufferPosition, temp);
  411. Span<byte> inlineOutBuffer = new Span<byte>(temp);
  412. if (errorCode == NvResult.Success)
  413. {
  414. errorCode = GetDeviceFileFromFd(fd, out NvDeviceFile deviceFile);
  415. if (errorCode == NvResult.Success)
  416. {
  417. NvInternalResult internalResult = deviceFile.Ioctl3(ioctlCommand, arguments, inlineOutBuffer);
  418. if (internalResult == NvInternalResult.NotImplemented)
  419. {
  420. throw new NvIoctlNotImplementedException(context, deviceFile, ioctlCommand);
  421. }
  422. errorCode = ConvertInternalErrorCode(internalResult);
  423. if ((ioctlCommand.DirectionValue & NvIoctl.Direction.Write) != 0)
  424. {
  425. context.Memory.Write(context.Request.GetBufferType0x22(0).Position, arguments.ToArray());
  426. context.Memory.Write(inlineOutBufferPosition, inlineOutBuffer.ToArray());
  427. }
  428. }
  429. }
  430. }
  431. context.ResponseData.Write((uint)errorCode);
  432. return ResultCode.Success;
  433. }
  434. [CommandHipc(13)] // 3.0.0+
  435. // FinishInitialize(unknown<8>)
  436. public ResultCode FinishInitialize(ServiceCtx context)
  437. {
  438. Logger.Stub?.PrintStub(LogClass.ServiceNv);
  439. return ResultCode.Success;
  440. }
  441. public static void Destroy()
  442. {
  443. NvHostChannelDeviceFile.Destroy();
  444. foreach (object entry in DeviceFileIdRegistry.Values)
  445. {
  446. NvDeviceFile deviceFile = (NvDeviceFile)entry;
  447. deviceFile.Close();
  448. }
  449. DeviceFileIdRegistry.Clear();
  450. }
  451. }
  452. }