1
0

gpuclockctl.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. /*
  2. Copyright (c) 2017-2018, Feral Interactive
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. * Redistributions of source code must retain the above copyright notice,
  7. this list of conditions and the following disclaimer.
  8. * Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. * Neither the name of Feral Interactive nor the names of its contributors
  12. may be used to endorse or promote products derived from this software
  13. without specific prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  15. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  17. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  18. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  19. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  20. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  21. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  22. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  23. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  24. POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #define _GNU_SOURCE
  27. #include "logging.h"
  28. #include "external-helper.h"
  29. #include "gpu-control.h"
  30. /* NV constants */
  31. #define NV_CORE_OFFSET_ATTRIBUTE "GPUGraphicsClockOffset"
  32. #define NV_MEM_OFFSET_ATTRIBUTE "GPUMemoryTransferRateOffset"
  33. #define NV_POWERMIZER_MODE_ATTRIBUTE "GPUPowerMizerMode"
  34. #define NV_PERFMODES_ATTRIBUTE "GPUPerfModes"
  35. #define NV_PCIDEVICE_ATTRIBUTE "PCIDevice"
  36. #define NV_ATTRIBUTE_FORMAT "[gpu:%ld]/%s"
  37. #define NV_PERF_LEVEL_FORMAT "[%ld]"
  38. /* AMD constants */
  39. #define AMD_DRM_PATH "/sys/class/drm/card%ld/device/%s"
  40. /* Plausible extras to add:
  41. * Intel support - https://blog.ffwll.ch/2013/03/overclocking-your-intel-gpu-on-linux.html
  42. * AMD - Allow setting fan speed as well
  43. * Store baseline values with get_gpu_state to apply when leaving gamemode
  44. */
  45. /* Helper to quit with usage */
  46. static const char *usage_text =
  47. "usage: gpuclockctl DEVICE {arg}\n\t\tget - return current values\n\t\tset [NV_CORE NV_MEM "
  48. "NV_POWERMIZER_MODE | AMD_PERFORMANCE_LEVEL] - set current values";
  49. static void print_usage_and_exit(void)
  50. {
  51. fprintf(stderr, "%s\n", usage_text);
  52. exit(EXIT_FAILURE);
  53. }
  54. /* Get the nvidia driver index for the current GPU */
  55. static long get_gpu_index_id_nv(struct GameModeGPUInfo *info)
  56. {
  57. // Default to using the current device number
  58. long gpu_index = info->device;
  59. if (info->vendor != Vendor_NVIDIA)
  60. return -1;
  61. if (!getenv("DISPLAY"))
  62. LOG_ERROR("Getting Nvidia parameters requires DISPLAY to be set - will likely fail!\n");
  63. long current = 0;
  64. do {
  65. char arg[128] = { 0 };
  66. char buf[EXTERNAL_BUFFER_MAX] = { 0 };
  67. char *end;
  68. /* Get the PCI id parameter */
  69. snprintf(arg, 128, NV_ATTRIBUTE_FORMAT, current, NV_PCIDEVICE_ATTRIBUTE);
  70. const char *exec_args_core[] = { "/usr/bin/nvidia-settings", "-q", arg, "-t", NULL };
  71. if (run_external_process(exec_args_core, buf, -1) != 0) {
  72. LOG_ERROR("Failed to get %s! Will be defaulting to nvidia gpu index %ld\n",
  73. arg,
  74. gpu_index);
  75. /* Failure just means we've overrun the device list */
  76. break;
  77. }
  78. long pcidevice = strtol(buf, &end, 10);
  79. if (end == buf) {
  80. LOG_ERROR("Failed to parse output for \"%s\" output was \"%s\"!\n", arg, buf);
  81. break;
  82. }
  83. if (info->device == pcidevice) {
  84. gpu_index = current;
  85. break;
  86. }
  87. } while (true);
  88. return gpu_index;
  89. }
  90. /* Get the max nvidia perf level */
  91. static long get_max_perf_level_nv(struct GameModeGPUInfo *info)
  92. {
  93. if (info->vendor != Vendor_NVIDIA)
  94. return -1;
  95. if (!getenv("DISPLAY"))
  96. LOG_ERROR("Getting Nvidia parameters requires DISPLAY to be set - will likely fail!\n");
  97. char arg[128] = { 0 };
  98. char buf[EXTERNAL_BUFFER_MAX] = { 0 };
  99. snprintf(arg, 128, NV_ATTRIBUTE_FORMAT, info->device, NV_PERFMODES_ATTRIBUTE);
  100. const char *exec_args[] = { "/usr/bin/nvidia-settings", "-q", arg, "-t", NULL };
  101. if (run_external_process(exec_args, buf, -1) != 0) {
  102. LOG_ERROR("Failed to get %s!\n", arg);
  103. return -1;
  104. }
  105. char *ptr = strrchr(buf, ';');
  106. long level = -1;
  107. if (!ptr || sscanf(ptr, "; perf=%ld", &level) != 1) {
  108. LOG_ERROR(
  109. "Output didn't match expected format, couldn't discern highest perf level from "
  110. "nvidia-settings!\n");
  111. LOG_ERROR("Output:%s\n", buf);
  112. return -1;
  113. }
  114. return level;
  115. }
  116. /* Get the nvidia gpu state */
  117. static int get_gpu_state_nv(struct GameModeGPUInfo *info)
  118. {
  119. if (info->vendor != Vendor_NVIDIA)
  120. return -1;
  121. if (!getenv("DISPLAY"))
  122. LOG_ERROR("Getting Nvidia parameters requires DISPLAY to be set - will likely fail!\n");
  123. long perf_level = get_max_perf_level_nv(info);
  124. char arg[128] = { 0 };
  125. char buf[EXTERNAL_BUFFER_MAX] = { 0 };
  126. char *end;
  127. /* Get the GPUGraphicsClockOffset parameter */
  128. snprintf(arg,
  129. 128,
  130. NV_ATTRIBUTE_FORMAT NV_PERF_LEVEL_FORMAT,
  131. info->device,
  132. NV_CORE_OFFSET_ATTRIBUTE,
  133. perf_level);
  134. const char *exec_args_core[] = { "/usr/bin/nvidia-settings", "-q", arg, "-t", NULL };
  135. if (run_external_process(exec_args_core, buf, -1) != 0) {
  136. LOG_ERROR("Failed to get %s!\n", arg);
  137. return -1;
  138. }
  139. info->nv_core = strtol(buf, &end, 10);
  140. if (end == buf) {
  141. LOG_ERROR("Failed to parse output for \"%s\" output was \"%s\"!\n", arg, buf);
  142. return -1;
  143. }
  144. /* Get the GPUMemoryTransferRateOffset parameter */
  145. snprintf(arg,
  146. 128,
  147. NV_ATTRIBUTE_FORMAT NV_PERF_LEVEL_FORMAT,
  148. info->device,
  149. NV_MEM_OFFSET_ATTRIBUTE,
  150. perf_level);
  151. const char *exec_args_mem[] = { "/usr/bin/nvidia-settings", "-q", arg, "-t", NULL };
  152. if (run_external_process(exec_args_mem, buf, -1) != 0) {
  153. LOG_ERROR("Failed to get %s!\n", arg);
  154. return -1;
  155. }
  156. info->nv_mem = strtol(buf, &end, 10);
  157. if (end == buf) {
  158. LOG_ERROR("Failed to parse output for \"%s\" output was \"%s\"!\n", arg, buf);
  159. return -1;
  160. }
  161. /* Get the GPUPowerMizerMode parameter */
  162. snprintf(arg, 128, NV_ATTRIBUTE_FORMAT, info->device, NV_POWERMIZER_MODE_ATTRIBUTE);
  163. const char *exec_args_pm[] = { "/usr/bin/nvidia-settings", "-q", arg, "-t", NULL };
  164. if (run_external_process(exec_args_pm, buf, -1) != 0) {
  165. LOG_ERROR("Failed to get %s!\n", arg);
  166. return -1;
  167. }
  168. info->nv_powermizer_mode = strtol(buf, &end, 10);
  169. if (end == buf) {
  170. LOG_ERROR("Failed to parse output for \"%s\" output was \"%s\"!\n", arg, buf);
  171. return -1;
  172. }
  173. return 0;
  174. }
  175. /**
  176. * Set the gpu state based on input parameters on Nvidia
  177. */
  178. static int set_gpu_state_nv(struct GameModeGPUInfo *info)
  179. {
  180. int status = 0;
  181. if (info->vendor != Vendor_NVIDIA)
  182. return -1;
  183. if (!getenv("DISPLAY") || !getenv("XAUTHORITY"))
  184. LOG_ERROR(
  185. "Setting Nvidia parameters requires DISPLAY and XAUTHORITY to be set - will likely "
  186. "fail!\n");
  187. long perf_level = get_max_perf_level_nv(info);
  188. char arg[128] = { 0 };
  189. /* Set the GPUGraphicsClockOffset parameter */
  190. if (info->nv_core != -1) {
  191. snprintf(arg,
  192. 128,
  193. NV_ATTRIBUTE_FORMAT NV_PERF_LEVEL_FORMAT "=%ld",
  194. info->device,
  195. NV_CORE_OFFSET_ATTRIBUTE,
  196. perf_level,
  197. info->nv_core);
  198. const char *exec_args_core[] = { "/usr/bin/nvidia-settings", "-a", arg, NULL };
  199. if (run_external_process(exec_args_core, NULL, -1) != 0) {
  200. LOG_ERROR("Failed to set %s!\n", arg);
  201. status = -1;
  202. }
  203. }
  204. /* Set the GPUMemoryTransferRateOffset parameter */
  205. if (info->nv_mem != -1) {
  206. snprintf(arg,
  207. 128,
  208. NV_ATTRIBUTE_FORMAT NV_PERF_LEVEL_FORMAT "=%ld",
  209. info->device,
  210. NV_MEM_OFFSET_ATTRIBUTE,
  211. perf_level,
  212. info->nv_mem);
  213. const char *exec_args_mem[] = { "/usr/bin/nvidia-settings", "-a", arg, NULL };
  214. if (run_external_process(exec_args_mem, NULL, -1) != 0) {
  215. LOG_ERROR("Failed to set %s!\n", arg);
  216. status = -1;
  217. }
  218. }
  219. /* Set the GPUPowerMizerMode parameter if requested */
  220. if (info->nv_powermizer_mode != -1) {
  221. snprintf(arg,
  222. 128,
  223. NV_ATTRIBUTE_FORMAT "=%ld",
  224. info->device,
  225. NV_POWERMIZER_MODE_ATTRIBUTE,
  226. info->nv_powermizer_mode);
  227. const char *exec_args_pm[] = { "/usr/bin/nvidia-settings", "-a", arg, NULL };
  228. if (run_external_process(exec_args_pm, NULL, -1) != 0) {
  229. LOG_ERROR("Failed to set %s!\n", arg);
  230. status = -1;
  231. }
  232. }
  233. return status;
  234. }
  235. /**
  236. * Get the gpu state
  237. * Populates the struct with the GPU info on the system
  238. */
  239. static int get_gpu_state_amd(struct GameModeGPUInfo *info)
  240. {
  241. if (info->vendor != Vendor_AMD)
  242. return -1;
  243. /* Get the contents of power_dpm_force_performance_level */
  244. char path[64];
  245. snprintf(path, 64, AMD_DRM_PATH, info->device, "power_dpm_force_performance_level");
  246. FILE *file = fopen(path, "r");
  247. if (!file) {
  248. LOG_ERROR("Could not open %s for read (%s)!\n", path, strerror(errno));
  249. return -1;
  250. }
  251. char buff[CONFIG_VALUE_MAX];
  252. if (!fgets(buff, CONFIG_VALUE_MAX, file)) {
  253. LOG_ERROR("Could not read file %s (%s)!\n", path, strerror(errno));
  254. return -1;
  255. }
  256. if (fclose(file) != 0) {
  257. LOG_ERROR("Could not close %s after reading (%s)!\n", path, strerror(errno));
  258. return -1;
  259. }
  260. /* Copy in the value from the file */
  261. strncpy(info->amd_performance_level, buff, CONFIG_VALUE_MAX);
  262. return info == NULL;
  263. }
  264. /*
  265. * Simply set an amd drm file to a value
  266. */
  267. static int set_gpu_state_amd_file(const char *filename, long device, const char *value)
  268. {
  269. char path[64];
  270. snprintf(path, 64, AMD_DRM_PATH, device, filename);
  271. FILE *file = fopen(path, "w");
  272. if (!file) {
  273. LOG_ERROR("Could not open %s for write (%s)!\n", path, strerror(errno));
  274. return -1;
  275. }
  276. if (fprintf(file, "%s", value) < 0) {
  277. LOG_ERROR("Could not write to %s (%s)!\n", path, strerror(errno));
  278. return -1;
  279. }
  280. if (fclose(file) != 0) {
  281. LOG_ERROR("Could not close %s after writing (%s)!\n", path, strerror(errno));
  282. return -1;
  283. }
  284. return 0;
  285. }
  286. /**
  287. * Set the gpu state based on input parameters on amd
  288. */
  289. static int set_gpu_state_amd(struct GameModeGPUInfo *info)
  290. {
  291. if (info->vendor != Vendor_AMD)
  292. return -1;
  293. /* Must be root to set the state */
  294. if (geteuid() != 0) {
  295. fprintf(stderr, "gpuclockctl must be run as root to set AMD values\n");
  296. print_usage_and_exit();
  297. }
  298. /* First set the amd_performance_level to the chosen setting */
  299. if (set_gpu_state_amd_file("power_dpm_force_performance_level",
  300. info->device,
  301. info->amd_performance_level) != 0)
  302. return -1;
  303. /* TODO: If amd_performance_level is set to "manual" we need to adjust pp_table and/or
  304. pp_od_clk_voltage see
  305. https://dri.freedesktop.org/docs/drm/gpu/amdgpu.html#gpu-power-thermal-controls-and-monitoring
  306. */
  307. return 0;
  308. }
  309. /* Helper to get and verify device value */
  310. static long get_device(const char *val)
  311. {
  312. char *end;
  313. long ret = strtol(val, &end, 10);
  314. if (ret < 0 || end == val) {
  315. LOG_ERROR("Invalid GPU device passed (%ld)!\n", ret);
  316. print_usage_and_exit();
  317. }
  318. return ret;
  319. }
  320. /* Helper to get and verify nv_core and nv_mem value */
  321. static long get_generic_value(const char *val)
  322. {
  323. char *end;
  324. long ret = strtol(val, &end, 10);
  325. if (end == val) {
  326. LOG_ERROR("Invalid value passed (%ld)!\n", ret);
  327. print_usage_and_exit();
  328. }
  329. return ret;
  330. }
  331. /**
  332. * Main entry point, dispatch to the appropriate helper
  333. */
  334. int main(int argc, char *argv[])
  335. {
  336. if (argc == 3 && strncmp(argv[2], "get", 3) == 0) {
  337. /* Get and verify the vendor and device */
  338. struct GameModeGPUInfo info;
  339. memset(&info, 0, sizeof(info));
  340. info.device = get_device(argv[1]);
  341. info.vendor = gamemode_get_gpu_vendor(info.device);
  342. /* Adjust the device number to the gpu index for Nvidia */
  343. if (info.vendor == Vendor_NVIDIA)
  344. info.device = get_gpu_index_id_nv(&info);
  345. /* Fetch the state and print it out */
  346. switch (info.vendor) {
  347. case Vendor_NVIDIA:
  348. if (get_gpu_state_nv(&info) != 0)
  349. exit(EXIT_FAILURE);
  350. printf("%ld %ld %ld\n", info.nv_core, info.nv_mem, info.nv_powermizer_mode);
  351. break;
  352. case Vendor_AMD:
  353. if (get_gpu_state_amd(&info) != 0)
  354. exit(EXIT_FAILURE);
  355. printf("%s\n", info.amd_performance_level);
  356. break;
  357. default:
  358. LOG_ERROR("Currently unsupported GPU vendor 0x%04x, doing nothing!\n",
  359. (short)info.vendor);
  360. break;
  361. }
  362. } else if (argc >= 4 && argc <= 7 && strncmp(argv[2], "set", 3) == 0) {
  363. /* Get and verify the vendor and device */
  364. struct GameModeGPUInfo info;
  365. memset(&info, 0, sizeof(info));
  366. info.device = get_device(argv[1]);
  367. info.vendor = gamemode_get_gpu_vendor(info.device);
  368. switch (info.vendor) {
  369. case Vendor_NVIDIA:
  370. if (argc < 4) {
  371. LOG_ERROR("Must pass at least 4 arguments for nvidia gpu!\n");
  372. print_usage_and_exit();
  373. }
  374. info.nv_core = get_generic_value(argv[3]);
  375. info.nv_mem = get_generic_value(argv[4]);
  376. /* Optional */
  377. info.nv_powermizer_mode = -1;
  378. if (argc >= 6)
  379. info.nv_powermizer_mode = get_generic_value(argv[5]);
  380. return set_gpu_state_nv(&info);
  381. break;
  382. case Vendor_AMD:
  383. if (argc < 3) {
  384. LOG_ERROR("Must pass performance level for AMD gpu!\n");
  385. print_usage_and_exit();
  386. }
  387. strncpy(info.amd_performance_level, argv[3], CONFIG_VALUE_MAX);
  388. return set_gpu_state_amd(&info);
  389. break;
  390. default:
  391. LOG_ERROR("Currently unsupported GPU vendor 0x%04x, doing nothing!\n",
  392. (short)info.vendor);
  393. print_usage_and_exit();
  394. break;
  395. }
  396. } else {
  397. print_usage_and_exit();
  398. }
  399. return EXIT_SUCCESS;
  400. }