1
0

gamemode-cpu.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. /*
  2. Copyright (c) 2017-2025, Feral Interactive and the GameMode contributors
  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 <linux/limits.h>
  28. #include <dirent.h>
  29. #include <sched.h>
  30. #include "common-cpu.h"
  31. #include "common-external.h"
  32. #include "common-helpers.h"
  33. #include "common-logging.h"
  34. #include "gamemode.h"
  35. #include "gamemode-config.h"
  36. #include "build-config.h"
  37. static int read_small_file(char *path, char **buf, size_t *buflen)
  38. {
  39. FILE *f = fopen(path, "r");
  40. if (!f) {
  41. LOG_ERROR("Couldn't open file at %s : %s\n", path, strerror(errno));
  42. return 0;
  43. }
  44. ssize_t nread = getline(buf, buflen, f);
  45. if (nread == -1) {
  46. LOG_ERROR("Couldn't read file at %s : %s\n", path, strerror(errno));
  47. fclose(f);
  48. return 0;
  49. }
  50. fclose(f);
  51. while (nread > 0 && ((*buf)[nread - 1] == '\n' || (*buf)[nread - 1] == '\r'))
  52. nread--;
  53. (*buf)[nread] = '\0';
  54. return 1;
  55. }
  56. static void set_online_from_list(char *cpulist, GameModeCPUInfo *info)
  57. {
  58. long from, to;
  59. while ((cpulist = parse_cpulist(cpulist, &from, &to))) {
  60. for (long cpu = from; cpu < to + 1; cpu++) {
  61. CPU_SET_S((size_t)cpu, CPU_ALLOC_SIZE(info->num_cpu), info->online);
  62. }
  63. }
  64. }
  65. static int check_pe_cores(char **buf, size_t *buflen, GameModeCPUInfo *info)
  66. {
  67. if (!read_small_file("/sys/devices/cpu_core/cpus", buf, buflen))
  68. return 0;
  69. LOG_MSG("found kernel support for checking P/E-cores\n");
  70. long from, to;
  71. char *list = *buf;
  72. while ((list = parse_cpulist(list, &from, &to))) {
  73. for (long cpu = from; cpu < to + 1; cpu++) {
  74. CPU_SET_S((size_t)cpu, CPU_ALLOC_SIZE(info->num_cpu), info->to_keep);
  75. }
  76. }
  77. if (CPU_EQUAL_S(CPU_ALLOC_SIZE(info->num_cpu), info->online, info->to_keep) ||
  78. CPU_COUNT_S(CPU_ALLOC_SIZE(info->num_cpu), info->to_keep) == 0)
  79. LOG_MSG("kernel did not indicate that this was an P/E-cores system\n");
  80. return 1;
  81. }
  82. static int walk_sysfs(char *cpulist, char **buf, size_t *buflen, GameModeCPUInfo *info)
  83. {
  84. char path[PATH_MAX];
  85. unsigned long long max_cache = 0, max_freq = 0;
  86. long from, to;
  87. cpu_set_t *freq_cores = CPU_ALLOC(info->num_cpu);
  88. char *list = cpulist;
  89. while ((list = parse_cpulist(list, &from, &to))) {
  90. for (long cpu = from; cpu < to + 1; cpu++) {
  91. /* check for L3 cache non-uniformity among the cores */
  92. int ret =
  93. snprintf(path, PATH_MAX, "/sys/devices/system/cpu/cpu%ld/cache/index3/size", cpu);
  94. if (ret > 0 && ret < PATH_MAX) {
  95. if (read_small_file(path, buf, buflen)) {
  96. char *endp;
  97. unsigned long long cache_size = strtoull(*buf, &endp, 10);
  98. if (*endp == 'K') {
  99. cache_size *= 1024;
  100. } else if (*endp == 'M') {
  101. cache_size *= 1024 * 1024;
  102. } else if (*endp == 'G') {
  103. cache_size *= 1024 * 1024 * 1024;
  104. } else if (*endp != '\0') {
  105. LOG_MSG("cpu L3 cache size (%s) on core #%ld is silly\n", *buf, cpu);
  106. cache_size = 0;
  107. }
  108. if (cache_size > max_cache) {
  109. max_cache = cache_size;
  110. CPU_ZERO_S(CPU_ALLOC_SIZE(info->num_cpu), info->to_keep);
  111. }
  112. if (cache_size == max_cache)
  113. CPU_SET_S((size_t)cpu, CPU_ALLOC_SIZE(info->num_cpu), info->to_keep);
  114. }
  115. }
  116. /* check for frequency non-uniformity among the cores */
  117. ret = snprintf(path,
  118. PATH_MAX,
  119. "/sys/devices/system/cpu/cpu%ld/cpufreq/cpuinfo_max_freq",
  120. cpu);
  121. if (ret > 0 && ret < PATH_MAX) {
  122. if (read_small_file(path, buf, buflen)) {
  123. unsigned long long freq = strtoull(*buf, NULL, 10);
  124. unsigned long long cutoff = (freq * 10) / 100;
  125. if (freq > max_freq) {
  126. if (max_freq < freq - cutoff)
  127. CPU_ZERO_S(CPU_ALLOC_SIZE(info->num_cpu), freq_cores);
  128. max_freq = freq;
  129. }
  130. if (freq + cutoff >= max_freq)
  131. CPU_SET_S((size_t)cpu, CPU_ALLOC_SIZE(info->num_cpu), freq_cores);
  132. }
  133. }
  134. }
  135. }
  136. if (CPU_EQUAL_S(CPU_ALLOC_SIZE(info->num_cpu), info->online, info->to_keep) ||
  137. CPU_COUNT_S(CPU_ALLOC_SIZE(info->num_cpu), info->to_keep) == 0) {
  138. LOG_MSG("cpu L3 cache was uniform, this is not a x3D with multiple chiplets\n");
  139. CPU_FREE(info->to_keep);
  140. info->to_keep = freq_cores;
  141. if (CPU_EQUAL_S(CPU_ALLOC_SIZE(info->num_cpu), info->online, info->to_keep) ||
  142. CPU_COUNT_S(CPU_ALLOC_SIZE(info->num_cpu), info->to_keep) == 0)
  143. LOG_MSG("cpu frequency was uniform, this is not a big.LITTLE type of system\n");
  144. } else {
  145. CPU_FREE(freq_cores);
  146. }
  147. return 1;
  148. }
  149. static int walk_string(char *cpulist, char *config_cpulist, GameModeCPUInfo *info)
  150. {
  151. long from, to;
  152. char *list = cpulist;
  153. while ((list = parse_cpulist(list, &from, &to))) {
  154. for (long cpu = from; cpu < to + 1; cpu++) {
  155. CPU_SET_S((size_t)cpu, CPU_ALLOC_SIZE(info->num_cpu), info->online);
  156. if (info->park_or_pin == IS_CPU_PARK)
  157. CPU_SET_S((size_t)cpu, CPU_ALLOC_SIZE(info->num_cpu), info->to_keep);
  158. }
  159. }
  160. list = config_cpulist;
  161. while ((list = parse_cpulist(list, &from, &to))) {
  162. for (long cpu = from; cpu < to + 1; cpu++) {
  163. if (CPU_ISSET_S((size_t)cpu, CPU_ALLOC_SIZE(info->num_cpu), info->online)) {
  164. if (info->park_or_pin == IS_CPU_PARK)
  165. CPU_CLR_S((size_t)cpu, CPU_ALLOC_SIZE(info->num_cpu), info->to_keep);
  166. else
  167. CPU_SET_S((size_t)cpu, CPU_ALLOC_SIZE(info->num_cpu), info->to_keep);
  168. }
  169. }
  170. }
  171. return 1;
  172. }
  173. void game_mode_reconfig_cpu(GameModeConfig *config, GameModeCPUInfo **info)
  174. {
  175. game_mode_unpark_cpu(*info);
  176. game_mode_free_cpu(info);
  177. game_mode_initialise_cpu(config, info);
  178. }
  179. int game_mode_initialise_cpu(GameModeConfig *config, GameModeCPUInfo **info)
  180. {
  181. /* Verify input, this is programmer error */
  182. if (!info || *info)
  183. FATAL_ERROR("Invalid GameModeCPUInfo passed to %s", __func__);
  184. /* Early out if we have this feature turned off */
  185. char park_cores[CONFIG_VALUE_MAX];
  186. char pin_cores[CONFIG_VALUE_MAX];
  187. config_get_cpu_park_cores(config, park_cores);
  188. config_get_cpu_pin_cores(config, pin_cores);
  189. int park_or_pin = -1;
  190. if (pin_cores[0] != '\0') {
  191. if (strcasecmp(pin_cores, "no") == 0 || strcasecmp(pin_cores, "false") == 0 ||
  192. strcmp(pin_cores, "0") == 0) {
  193. park_or_pin = -2;
  194. } else if (strcasecmp(pin_cores, "yes") == 0 || strcasecmp(pin_cores, "true") == 0 ||
  195. strcmp(pin_cores, "1") == 0) {
  196. pin_cores[0] = '\0';
  197. park_or_pin = IS_CPU_PIN;
  198. } else {
  199. park_or_pin = IS_CPU_PIN;
  200. }
  201. }
  202. if (park_or_pin != IS_CPU_PIN && park_cores[0] != '\0') {
  203. if (strcasecmp(park_cores, "no") == 0 || strcasecmp(park_cores, "false") == 0 ||
  204. strcmp(park_cores, "0") == 0) {
  205. if (park_or_pin == -2)
  206. return 0;
  207. park_or_pin = -1;
  208. } else if (strcasecmp(park_cores, "yes") == 0 || strcasecmp(park_cores, "true") == 0 ||
  209. strcmp(park_cores, "1") == 0) {
  210. park_cores[0] = '\0';
  211. park_or_pin = IS_CPU_PARK;
  212. } else {
  213. park_or_pin = IS_CPU_PARK;
  214. }
  215. }
  216. /* always default to pin */
  217. if (park_or_pin != IS_CPU_PARK)
  218. park_or_pin = IS_CPU_PIN;
  219. char *buf = NULL, *buf2 = NULL;
  220. size_t buflen = 0, buf2len = 0;
  221. /* first we find which cores are online, this also helps us to determine the max
  222. * cpu core number that we need to allocate the cpulist later */
  223. if (!read_small_file("/sys/devices/system/cpu/online", &buf, &buflen))
  224. goto error_exit;
  225. long from, to, max = 0;
  226. char *s = buf;
  227. while ((s = parse_cpulist(s, &from, &to))) {
  228. if (to > max)
  229. max = to;
  230. }
  231. /* either parsing failed or we have only a single core, in either case
  232. * we cannot optimize anyway */
  233. if (max == 0)
  234. goto early_exit;
  235. GameModeCPUInfo *new_info = malloc(sizeof(GameModeCPUInfo));
  236. memset(new_info, 0, sizeof(GameModeCPUInfo));
  237. new_info->num_cpu = (size_t)(max + 1);
  238. new_info->park_or_pin = park_or_pin;
  239. new_info->online = CPU_ALLOC(new_info->num_cpu);
  240. new_info->to_keep = CPU_ALLOC(new_info->num_cpu);
  241. CPU_ZERO_S(CPU_ALLOC_SIZE(new_info->num_cpu), new_info->online);
  242. CPU_ZERO_S(CPU_ALLOC_SIZE(new_info->num_cpu), new_info->to_keep);
  243. if (park_or_pin == IS_CPU_PARK && park_cores[0] != '\0') {
  244. if (!walk_string(buf, park_cores, new_info))
  245. goto error_exit;
  246. } else if (park_or_pin == IS_CPU_PIN && pin_cores[0] != '\0') {
  247. if (!walk_string(buf, pin_cores, new_info))
  248. goto error_exit;
  249. } else {
  250. set_online_from_list(buf, new_info);
  251. if (!check_pe_cores(&buf2, &buf2len, new_info)) {
  252. if (!walk_sysfs(buf, &buf2, &buf2len, new_info))
  253. goto error_exit;
  254. }
  255. }
  256. if (park_or_pin == IS_CPU_PARK &&
  257. CPU_EQUAL_S(CPU_ALLOC_SIZE(new_info->num_cpu), new_info->online, new_info->to_keep)) {
  258. game_mode_free_cpu(&new_info);
  259. LOG_MSG("I can find no reason to perform core parking on this system!\n");
  260. goto error_exit;
  261. }
  262. if (CPU_COUNT_S(CPU_ALLOC_SIZE(new_info->num_cpu), new_info->to_keep) == 0) {
  263. game_mode_free_cpu(&new_info);
  264. LOG_MSG("I can find no reason to perform core pinning on this system!\n");
  265. goto error_exit;
  266. }
  267. if (CPU_COUNT_S(CPU_ALLOC_SIZE(new_info->num_cpu), new_info->to_keep) < 4) {
  268. game_mode_free_cpu(&new_info);
  269. LOG_MSG(
  270. "logic or config would result in less than 4 active cores, will not apply cpu core "
  271. "parking/pinning!\n");
  272. goto error_exit;
  273. }
  274. *info = new_info;
  275. early_exit:
  276. free(buf);
  277. free(buf2);
  278. return 0;
  279. error_exit:
  280. free(buf);
  281. free(buf2);
  282. return -1;
  283. }
  284. static int log_state(char *cpulist, int *pos, const long first, const long last)
  285. {
  286. int ret;
  287. if (*pos != 0) {
  288. ret = snprintf(cpulist + *pos, ARG_MAX - (size_t)*pos, ",");
  289. if (ret < 0 || (size_t)ret >= (ARG_MAX - (size_t)*pos)) {
  290. LOG_ERROR("snprintf failed, will not apply cpu core parking!\n");
  291. return 0;
  292. }
  293. *pos += ret;
  294. }
  295. if (first == last)
  296. ret = snprintf(cpulist + *pos, ARG_MAX - (size_t)*pos, "%ld", first);
  297. else
  298. ret = snprintf(cpulist + *pos, ARG_MAX - (size_t)*pos, "%ld-%ld", first, last);
  299. if (ret < 0 || (size_t)ret >= (ARG_MAX - (size_t)*pos)) {
  300. LOG_ERROR("snprintf failed, will not apply cpu core parking!\n");
  301. return 0;
  302. }
  303. *pos += ret;
  304. return 1;
  305. }
  306. int game_mode_park_cpu(const GameModeCPUInfo *info)
  307. {
  308. if (!info || info->park_or_pin == IS_CPU_PIN)
  309. return 0;
  310. long first = -1, last = -1;
  311. char cpulist[ARG_MAX];
  312. int pos = 0;
  313. for (long cpu = 0; cpu < (long)(info->num_cpu); cpu++) {
  314. if (CPU_ISSET_S((size_t)cpu, CPU_ALLOC_SIZE(info->num_cpu), info->online) &&
  315. !CPU_ISSET_S((size_t)cpu, CPU_ALLOC_SIZE(info->num_cpu), info->to_keep)) {
  316. if (first == -1) {
  317. first = cpu;
  318. last = cpu;
  319. } else if (last + 1 == cpu) {
  320. last = cpu;
  321. } else {
  322. if (!log_state(cpulist, &pos, first, last))
  323. return 0;
  324. first = cpu;
  325. last = cpu;
  326. }
  327. }
  328. }
  329. if (first != -1)
  330. log_state(cpulist, &pos, first, last);
  331. const char *const exec_args[] = {
  332. "pkexec", LIBEXECDIR "/cpucorectl", "offline", cpulist, NULL,
  333. };
  334. LOG_MSG("Requesting parking of cores %s\n", cpulist);
  335. int ret = run_external_process(exec_args, NULL, -1);
  336. if (ret != 0) {
  337. LOG_ERROR("Failed to park cpu cores\n");
  338. return ret;
  339. }
  340. return 0;
  341. }
  342. int game_mode_unpark_cpu(const GameModeCPUInfo *info)
  343. {
  344. if (!info || info->park_or_pin == IS_CPU_PIN)
  345. return 0;
  346. long first = -1, last = -1;
  347. char cpulist[ARG_MAX];
  348. int pos = 0;
  349. for (long cpu = 0; cpu < (long)(info->num_cpu); cpu++) {
  350. if (CPU_ISSET_S((size_t)cpu, CPU_ALLOC_SIZE(info->num_cpu), info->online) &&
  351. !CPU_ISSET_S((size_t)cpu, CPU_ALLOC_SIZE(info->num_cpu), info->to_keep)) {
  352. if (first == -1) {
  353. first = cpu;
  354. last = cpu;
  355. } else if (last + 1 == cpu) {
  356. last = cpu;
  357. } else {
  358. if (!log_state(cpulist, &pos, first, last))
  359. return 0;
  360. first = cpu;
  361. last = cpu;
  362. }
  363. }
  364. }
  365. if (first != -1)
  366. log_state(cpulist, &pos, first, last);
  367. const char *const exec_args[] = {
  368. "pkexec", LIBEXECDIR "/cpucorectl", "online", cpulist, NULL,
  369. };
  370. LOG_MSG("Requesting unparking of cores %s\n", cpulist);
  371. int ret = run_external_process(exec_args, NULL, -1);
  372. if (ret != 0) {
  373. LOG_ERROR("Failed to unpark cpu cores\n");
  374. return ret;
  375. }
  376. return 0;
  377. }
  378. static void apply_affinity_mask(pid_t pid, size_t cpusetsize, const cpu_set_t *mask,
  379. const bool be_silent)
  380. {
  381. char buffer[PATH_MAX];
  382. char *proc_path = NULL;
  383. DIR *proc_dir = NULL;
  384. if (!(proc_path = buffered_snprintf(buffer, "/proc/%d/task", pid))) {
  385. if (!be_silent) {
  386. LOG_ERROR("Unable to find executable for PID %d: %s\n", pid, strerror(errno));
  387. }
  388. return;
  389. }
  390. if (!(proc_dir = opendir(proc_path))) {
  391. if (!be_silent) {
  392. LOG_ERROR("Unable to find executable for PID %d: %s\n", pid, strerror(errno));
  393. }
  394. return;
  395. }
  396. struct dirent *entry;
  397. while ((entry = readdir(proc_dir))) {
  398. if (entry->d_name[0] == '.')
  399. continue;
  400. int tid = atoi(entry->d_name);
  401. if (sched_setaffinity(tid, cpusetsize, mask) != 0 && !be_silent)
  402. LOG_ERROR("Failed to pin thread %d: %s\n", tid, strerror(errno));
  403. }
  404. closedir(proc_dir);
  405. }
  406. void game_mode_apply_core_pinning(const GameModeCPUInfo *info, const pid_t client,
  407. const bool be_silent)
  408. {
  409. if (!info || info->park_or_pin == IS_CPU_PARK)
  410. return;
  411. if (!be_silent)
  412. LOG_MSG("Pinning process...\n");
  413. apply_affinity_mask(client, CPU_ALLOC_SIZE(info->num_cpu), info->to_keep, be_silent);
  414. }
  415. void game_mode_undo_core_pinning(const GameModeCPUInfo *info, const pid_t client)
  416. {
  417. if (!info || info->park_or_pin == IS_CPU_PARK)
  418. return;
  419. LOG_MSG("Pinning process back to all online cores...\n");
  420. apply_affinity_mask(client, CPU_ALLOC_SIZE(info->num_cpu), info->online, false);
  421. }
  422. void game_mode_free_cpu(GameModeCPUInfo **info)
  423. {
  424. if ((*info)) {
  425. CPU_FREE((*info)->online);
  426. (*info)->online = NULL;
  427. CPU_FREE((*info)->to_keep);
  428. (*info)->to_keep = NULL;
  429. free(*info);
  430. *info = NULL;
  431. }
  432. }