gpuclockctl.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. /*
  2. Copyright (c) 2017-2019, 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 "common-external.h"
  28. #include "common-gpu.h"
  29. #include "common-logging.h"
  30. #include <limits.h>
  31. #include <unistd.h>
  32. /* NV constants */
  33. #define NV_CORE_OFFSET_ATTRIBUTE "GPUGraphicsClockOffset"
  34. #define NV_MEM_OFFSET_ATTRIBUTE "GPUMemoryTransferRateOffset"
  35. #define NV_POWERMIZER_MODE_ATTRIBUTE "GPUPowerMizerMode"
  36. #define NV_PERFMODES_ATTRIBUTE "GPUPerfModes"
  37. #define NV_PCIDEVICE_ATTRIBUTE "PCIDevice"
  38. #define NV_ATTRIBUTE_FORMAT "[gpu:%ld]/%s"
  39. #define NV_PERF_LEVEL_FORMAT "[%ld]"
  40. #define NV_ARG_MAX 128
  41. /* AMD constants */
  42. #define AMD_DRM_PATH "/sys/class/drm/card%ld/device/%s"
  43. /* Plausible extras to add:
  44. * Intel support - https://blog.ffwll.ch/2013/03/overclocking-your-intel-gpu-on-linux.html
  45. * AMD - Allow setting fan speed as well
  46. * Store baseline values with get_gpu_state to apply when leaving gamemode
  47. */
  48. /* Helper to quit with usage */
  49. static const char *usage_text =
  50. "usage: gpuclockctl DEVICE {arg}\n\t\tget - return current values\n\t\tset [NV_CORE NV_MEM "
  51. "NV_POWERMIZER_MODE | AMD_PERFORMANCE_LEVEL] - set current values";
  52. static void print_usage_and_exit(void)
  53. {
  54. fprintf(stderr, "%s\n", usage_text);
  55. exit(EXIT_FAILURE);
  56. }
  57. static const char *get_nv_attr(const char *attr)
  58. {
  59. static char out[EXTERNAL_BUFFER_MAX];
  60. const char *exec_args[] = { "/usr/bin/nvidia-settings", "-q", attr, "-t", NULL };
  61. if (run_external_process(exec_args, out, -1) != 0) {
  62. LOG_ERROR("Failed to get %s!\n", attr);
  63. out[0] = 0;
  64. return NULL;
  65. }
  66. return &out[0];
  67. }
  68. static int set_nv_attr(const char *attr)
  69. {
  70. const char *exec_args_core[] = { "/usr/bin/nvidia-settings", "-a", attr, NULL };
  71. if (run_external_process(exec_args_core, NULL, -1) != 0) {
  72. LOG_ERROR("Failed to set %s!\n", attr);
  73. return -1;
  74. }
  75. return 0;
  76. }
  77. /* Get the nvidia driver index for the current GPU */
  78. static long get_gpu_index_id_nv(struct GameModeGPUInfo *info)
  79. {
  80. if (info->vendor != Vendor_NVIDIA)
  81. return -1;
  82. /* NOTE: This is currently based off of a best guess of how the NVidia gpu index works
  83. * ie. that the index is simply the index into available NV gpus in the same order as drm
  84. * If that is not the case then this may fail to discern the correct GPU
  85. */
  86. int device = 0;
  87. int nv_device = -1;
  88. while (device <= info->device) {
  89. /* Get the vendor for each gpu sequentially */
  90. enum GPUVendor vendor = gamemode_get_gpu_vendor(device++);
  91. switch (vendor) {
  92. case Vendor_NVIDIA:
  93. /* If we've found an nvidia device, increment our counter */
  94. nv_device++;
  95. break;
  96. case Vendor_Invalid:
  97. /* Bail out, we've gone too far */
  98. LOG_ERROR("Failed to find Nvidia GPU with expected index!\n");
  99. break;
  100. default:
  101. /* Non-NV gpu, continue */
  102. break;
  103. }
  104. };
  105. return nv_device;
  106. }
  107. /* Get the max nvidia perf level */
  108. static long get_max_perf_level_nv(struct GameModeGPUInfo *info)
  109. {
  110. if (info->vendor != Vendor_NVIDIA)
  111. return -1;
  112. if (!getenv("DISPLAY"))
  113. LOG_ERROR("Getting Nvidia parameters requires DISPLAY to be set - will likely fail!\n");
  114. char arg[NV_ARG_MAX] = { 0 };
  115. const char *attr;
  116. snprintf(arg, NV_ARG_MAX, NV_ATTRIBUTE_FORMAT, info->device, NV_PERFMODES_ATTRIBUTE);
  117. if ((attr = get_nv_attr(arg)) == NULL) {
  118. return -1;
  119. }
  120. char *ptr = strrchr(attr, ';');
  121. long level = -1;
  122. if (!ptr || sscanf(ptr, "; perf=%ld", &level) != 1) {
  123. LOG_ERROR(
  124. "Output didn't match expected format, couldn't discern highest perf level from "
  125. "nvidia-settings!\n");
  126. LOG_ERROR("Output:%s\n", attr);
  127. return -1;
  128. }
  129. return level;
  130. }
  131. /* Get the nvidia gpu state */
  132. static int get_gpu_state_nv(struct GameModeGPUInfo *info)
  133. {
  134. if (info->vendor != Vendor_NVIDIA)
  135. return -1;
  136. if (!getenv("DISPLAY"))
  137. LOG_ERROR("Getting Nvidia parameters requires DISPLAY to be set - will likely fail!\n");
  138. long perf_level = get_max_perf_level_nv(info);
  139. char arg[NV_ARG_MAX] = { 0 };
  140. const char *attr;
  141. char *end;
  142. /* Get the GPUGraphicsClockOffset parameter */
  143. snprintf(arg,
  144. NV_ARG_MAX,
  145. NV_ATTRIBUTE_FORMAT NV_PERF_LEVEL_FORMAT,
  146. info->device,
  147. NV_CORE_OFFSET_ATTRIBUTE,
  148. perf_level);
  149. if ((attr = get_nv_attr(arg)) == NULL) {
  150. return -1;
  151. }
  152. info->nv_core = strtol(attr, &end, 10);
  153. if (end == attr) {
  154. LOG_ERROR("Failed to parse output for \"%s\" output was \"%s\"!\n", arg, attr);
  155. return -1;
  156. }
  157. /* Get the GPUMemoryTransferRateOffset parameter */
  158. snprintf(arg,
  159. NV_ARG_MAX,
  160. NV_ATTRIBUTE_FORMAT NV_PERF_LEVEL_FORMAT,
  161. info->device,
  162. NV_MEM_OFFSET_ATTRIBUTE,
  163. perf_level);
  164. if ((attr = get_nv_attr(arg)) == NULL) {
  165. return -1;
  166. }
  167. info->nv_mem = strtol(attr, &end, 10);
  168. if (end == attr) {
  169. LOG_ERROR("Failed to parse output for \"%s\" output was \"%s\"!\n", arg, attr);
  170. return -1;
  171. }
  172. /* Get the GPUPowerMizerMode parameter */
  173. snprintf(arg, NV_ARG_MAX, NV_ATTRIBUTE_FORMAT, info->device, NV_POWERMIZER_MODE_ATTRIBUTE);
  174. if ((attr = get_nv_attr(arg)) == NULL) {
  175. return -1;
  176. }
  177. info->nv_powermizer_mode = strtol(attr, &end, 10);
  178. if (end == attr) {
  179. LOG_ERROR("Failed to parse output for \"%s\" output was \"%s\"!\n", arg, attr);
  180. return -1;
  181. }
  182. return 0;
  183. }
  184. /**
  185. * Set the gpu state based on input parameters on Nvidia
  186. */
  187. static int set_gpu_state_nv(struct GameModeGPUInfo *info)
  188. {
  189. int status = 0;
  190. if (info->vendor != Vendor_NVIDIA)
  191. return -1;
  192. if (!getenv("DISPLAY") || !getenv("XAUTHORITY"))
  193. LOG_ERROR(
  194. "Setting Nvidia parameters requires DISPLAY and XAUTHORITY to be set - will likely "
  195. "fail!\n");
  196. long perf_level = get_max_perf_level_nv(info);
  197. char arg[NV_ARG_MAX] = { 0 };
  198. /* Set the GPUGraphicsClockOffset parameter */
  199. if (info->nv_core != -1) {
  200. snprintf(arg,
  201. NV_ARG_MAX,
  202. NV_ATTRIBUTE_FORMAT NV_PERF_LEVEL_FORMAT "=%ld",
  203. info->device,
  204. NV_CORE_OFFSET_ATTRIBUTE,
  205. perf_level,
  206. info->nv_core);
  207. if (set_nv_attr(arg) != 0) {
  208. status = -1;
  209. }
  210. }
  211. /* Set the GPUMemoryTransferRateOffset parameter */
  212. if (info->nv_mem != -1) {
  213. snprintf(arg,
  214. NV_ARG_MAX,
  215. NV_ATTRIBUTE_FORMAT NV_PERF_LEVEL_FORMAT "=%ld",
  216. info->device,
  217. NV_MEM_OFFSET_ATTRIBUTE,
  218. perf_level,
  219. info->nv_mem);
  220. if (set_nv_attr(arg) != 0) {
  221. status = -1;
  222. }
  223. }
  224. /* Set the GPUPowerMizerMode parameter if requested */
  225. if (info->nv_powermizer_mode != -1) {
  226. snprintf(arg,
  227. NV_ARG_MAX,
  228. NV_ATTRIBUTE_FORMAT "=%ld",
  229. info->device,
  230. NV_POWERMIZER_MODE_ATTRIBUTE,
  231. info->nv_powermizer_mode);
  232. if (set_nv_attr(arg) != 0) {
  233. status = -1;
  234. }
  235. }
  236. return status;
  237. }
  238. /**
  239. * Get the gpu state
  240. * Populates the struct with the GPU info on the system
  241. */
  242. static int get_gpu_state_amd(struct GameModeGPUInfo *info)
  243. {
  244. if (info->vendor != Vendor_AMD)
  245. return -1;
  246. /* Get the contents of power_dpm_force_performance_level */
  247. char path[PATH_MAX];
  248. snprintf(path, PATH_MAX, AMD_DRM_PATH, info->device, "power_dpm_force_performance_level");
  249. FILE *file = fopen(path, "r");
  250. if (!file) {
  251. LOG_ERROR("Could not open %s for read (%s)!\n", path, strerror(errno));
  252. return -1;
  253. }
  254. int ret = 0;
  255. char buff[GPU_VALUE_MAX] = { 0 };
  256. if (!fgets(buff, GPU_VALUE_MAX, file)) {
  257. LOG_ERROR("Could not read file %s (%s)!\n", path, strerror(errno));
  258. ret = -1;
  259. }
  260. if (fclose(file) != 0) {
  261. LOG_ERROR("Could not close %s after reading (%s)!\n", path, strerror(errno));
  262. ret = -1;
  263. }
  264. if (ret == 0) {
  265. /* Copy in the value from the file */
  266. strncpy(info->amd_performance_level, buff, GPU_VALUE_MAX - 1);
  267. info->amd_performance_level[GPU_VALUE_MAX - 1] = '\0';
  268. }
  269. return ret;
  270. }
  271. /*
  272. * Simply set an amd drm file to a value
  273. */
  274. static int set_gpu_state_amd_file(const char *filename, long device, const char *value)
  275. {
  276. char path[PATH_MAX];
  277. snprintf(path, PATH_MAX, AMD_DRM_PATH, device, filename);
  278. FILE *file = fopen(path, "w");
  279. if (!file) {
  280. LOG_ERROR("Could not open %s for write (%s)!\n", path, strerror(errno));
  281. return -1;
  282. }
  283. int ret = 0;
  284. if (fprintf(file, "%s", value) < 0) {
  285. LOG_ERROR("Could not write to %s (%s)!\n", path, strerror(errno));
  286. ret = -1;
  287. }
  288. if (fclose(file) != 0) {
  289. LOG_ERROR("Could not close %s after writing (%s)!\n", path, strerror(errno));
  290. ret = -1;
  291. }
  292. return ret;
  293. }
  294. /**
  295. * Set the gpu state based on input parameters on amd
  296. */
  297. static int set_gpu_state_amd(struct GameModeGPUInfo *info)
  298. {
  299. if (info->vendor != Vendor_AMD)
  300. return -1;
  301. /* Must be root to set the state */
  302. if (geteuid() != 0) {
  303. fprintf(stderr, "gpuclockctl must be run as root to set AMD values\n");
  304. print_usage_and_exit();
  305. }
  306. /* First set the amd_performance_level to the chosen setting */
  307. if (set_gpu_state_amd_file("power_dpm_force_performance_level",
  308. info->device,
  309. info->amd_performance_level) != 0)
  310. return -1;
  311. /* TODO: If amd_performance_level is set to "manual" we need to adjust pp_table and/or
  312. pp_od_clk_voltage see
  313. https://dri.freedesktop.org/docs/drm/gpu/amdgpu.html#gpu-power-thermal-controls-and-monitoring
  314. */
  315. return 0;
  316. }
  317. /* Helper to get and verify device value */
  318. static long get_device(const char *val)
  319. {
  320. char *end;
  321. long ret = strtol(val, &end, 10);
  322. if (ret < 0 || end == val) {
  323. LOG_ERROR("Invalid GPU device passed (%ld)!\n", ret);
  324. print_usage_and_exit();
  325. }
  326. return ret;
  327. }
  328. /* Helper to get and verify nv_core and nv_mem value */
  329. static long get_generic_value(const char *val)
  330. {
  331. char *end;
  332. long ret = strtol(val, &end, 10);
  333. if (end == val) {
  334. LOG_ERROR("Invalid value passed (%ld)!\n", ret);
  335. print_usage_and_exit();
  336. }
  337. return ret;
  338. }
  339. /**
  340. * Main entry point, dispatch to the appropriate helper
  341. */
  342. int main(int argc, char *argv[])
  343. {
  344. struct GameModeGPUInfo info;
  345. memset(&info, 0, sizeof(info));
  346. if (argc == 3 && strncmp(argv[2], "get", 3) == 0) {
  347. /* Get and verify the vendor and device */
  348. info.device = get_device(argv[1]);
  349. info.vendor = gamemode_get_gpu_vendor(info.device);
  350. /* Fetch the state and print it out */
  351. switch (info.vendor) {
  352. case Vendor_NVIDIA:
  353. /* Adjust the device number to the gpu index for Nvidia */
  354. info.device = get_gpu_index_id_nv(&info);
  355. if (get_gpu_state_nv(&info) != 0)
  356. exit(EXIT_FAILURE);
  357. printf("%ld %ld %ld\n", info.nv_core, info.nv_mem, info.nv_powermizer_mode);
  358. break;
  359. case Vendor_AMD:
  360. if (get_gpu_state_amd(&info) != 0)
  361. exit(EXIT_FAILURE);
  362. printf("%s\n", info.amd_performance_level);
  363. break;
  364. default:
  365. LOG_ERROR("Currently unsupported GPU vendor 0x%04x, doing nothing!\n",
  366. (unsigned short)info.vendor);
  367. break;
  368. }
  369. } else if (argc >= 4 && argc <= 7 && strncmp(argv[2], "set", 3) == 0) {
  370. /* Get and verify the vendor and device */
  371. info.device = get_device(argv[1]);
  372. info.vendor = gamemode_get_gpu_vendor(info.device);
  373. switch (info.vendor) {
  374. case Vendor_NVIDIA:
  375. if (argc < 4) {
  376. LOG_ERROR("Must pass at least 4 arguments for nvidia gpu!\n");
  377. print_usage_and_exit();
  378. }
  379. info.nv_core = get_generic_value(argv[3]);
  380. info.nv_mem = get_generic_value(argv[4]);
  381. /* Adjust the device number to the gpu index for Nvidia */
  382. info.device = get_gpu_index_id_nv(&info);
  383. /* Optional */
  384. info.nv_powermizer_mode = -1;
  385. if (argc >= 6)
  386. info.nv_powermizer_mode = get_generic_value(argv[5]);
  387. return set_gpu_state_nv(&info);
  388. break;
  389. case Vendor_AMD:
  390. if (argc < 3) {
  391. LOG_ERROR("Must pass performance level for AMD gpu!\n");
  392. print_usage_and_exit();
  393. }
  394. strncpy(info.amd_performance_level, argv[3], GPU_VALUE_MAX - 1);
  395. return set_gpu_state_amd(&info);
  396. break;
  397. default:
  398. LOG_ERROR("Currently unsupported GPU vendor 0x%04x, doing nothing!\n",
  399. (unsigned short)info.vendor);
  400. print_usage_and_exit();
  401. break;
  402. }
  403. } else {
  404. print_usage_and_exit();
  405. }
  406. return EXIT_SUCCESS;
  407. }