gamemode-context.c 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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 "common-external.h"
  28. #include "common-governors.h"
  29. #include "common-helpers.h"
  30. #include "common-logging.h"
  31. #include "common-power.h"
  32. #include "common-profile.h"
  33. #include "common-splitlock.h"
  34. #include "gamemode.h"
  35. #include "gamemode-config.h"
  36. #include "build-config.h"
  37. #include <assert.h>
  38. #include <fcntl.h>
  39. #include <pthread.h>
  40. #include <signal.h>
  41. #include <stdatomic.h>
  42. #include <stdlib.h>
  43. #include <sys/time.h>
  44. #include <systemd/sd-daemon.h> /* TODO: Move usage to gamemode-dbus.c */
  45. #include <unistd.h>
  46. /**
  47. * The GameModeClient encapsulates the remote connection, providing a list
  48. * form to contain the pid and credentials.
  49. */
  50. struct GameModeClient {
  51. _Atomic int refcount; /**<Allow outside usage */
  52. pid_t pid; /**< Process ID */
  53. pid_t requester; /**< Process ID that requested it */
  54. struct GameModeClient *next; /**<Next client in the list */
  55. char executable[PATH_MAX]; /**<Process executable */
  56. time_t timestamp; /**<When was the client registered */
  57. };
  58. enum GameModeGovernor {
  59. GAME_MODE_GOVERNOR_DEFAULT,
  60. GAME_MODE_GOVERNOR_DESIRED,
  61. GAME_MODE_GOVERNOR_IGPU_DESIRED,
  62. };
  63. enum GameModeProfile {
  64. GAME_MODE_PROFILE_DEFAULT,
  65. GAME_MODE_PROFILE_DESIRED,
  66. };
  67. struct GameModeContext {
  68. pthread_rwlock_t rwlock; /**<Guard access to the client list */
  69. _Atomic int refcount; /**<Allow cycling the game mode */
  70. GameModeClient *client; /**<Pointer to first client */
  71. GameModeConfig *config; /**<Pointer to config object */
  72. char initial_cpu_mode[64]; /**<Only updates when we can */
  73. enum GameModeGovernor current_govenor;
  74. char initial_profile[64];
  75. enum GameModeProfile current_profile;
  76. struct GameModeGPUInfo *stored_gpu; /**<Stored GPU info for the current GPU */
  77. struct GameModeGPUInfo *target_gpu; /**<Target GPU info for the current GPU */
  78. struct GameModeCPUInfo *cpu; /**<Stored CPU info for the current CPU */
  79. GameModeIdleInhibitor *idle_inhibitor;
  80. bool igpu_optimization_enabled;
  81. uint32_t last_cpu_energy_uj;
  82. uint32_t last_igpu_energy_uj;
  83. long initial_split_lock_mitigate;
  84. /* Reaper control */
  85. struct {
  86. pthread_t thread;
  87. bool running;
  88. pthread_mutex_t mutex;
  89. pthread_cond_t condition;
  90. } reaper;
  91. };
  92. static GameModeContext instance = { 0 };
  93. /**
  94. * Protect against signals
  95. */
  96. static volatile bool had_context_init = false;
  97. static GameModeClient *game_mode_client_new(pid_t pid, char *exe, pid_t req);
  98. static const GameModeClient *game_mode_context_has_client(GameModeContext *self, pid_t client);
  99. static void *game_mode_context_reaper(void *userdata);
  100. static void game_mode_context_enter(GameModeContext *self);
  101. static void game_mode_context_leave(GameModeContext *self);
  102. static char *game_mode_context_find_exe(pid_t pid);
  103. static void game_mode_execute_scripts(char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX], int timeout);
  104. static int game_mode_disable_splitlock(GameModeContext *self, bool disable);
  105. static void start_reaper_thread(GameModeContext *self)
  106. {
  107. pthread_mutex_init(&self->reaper.mutex, NULL);
  108. pthread_cond_init(&self->reaper.condition, NULL);
  109. self->reaper.running = true;
  110. if (pthread_create(&self->reaper.thread, NULL, game_mode_context_reaper, self) != 0) {
  111. FATAL_ERROR("Couldn't construct a new thread");
  112. }
  113. }
  114. void game_mode_context_init(GameModeContext *self)
  115. {
  116. if (had_context_init) {
  117. LOG_ERROR("Context already initialised\n");
  118. return;
  119. }
  120. had_context_init = true;
  121. self->refcount = ATOMIC_VAR_INIT(0);
  122. /* clear the initial string */
  123. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  124. /* Initialise the config */
  125. self->config = config_create();
  126. config_init(self->config);
  127. self->current_govenor = GAME_MODE_GOVERNOR_DEFAULT;
  128. /* Initialise the current GPU info */
  129. game_mode_initialise_gpu(self->config, &self->stored_gpu);
  130. game_mode_initialise_gpu(self->config, &self->target_gpu);
  131. /* Initialise the current CPU info */
  132. game_mode_initialise_cpu(self->config, &self->cpu);
  133. self->initial_split_lock_mitigate = -1;
  134. pthread_rwlock_init(&self->rwlock, NULL);
  135. /* Get the reaper thread going */
  136. start_reaper_thread(self);
  137. }
  138. static void end_reaper_thread(GameModeContext *self)
  139. {
  140. self->reaper.running = false;
  141. /* We might be stuck waiting, so wake it up again */
  142. pthread_mutex_lock(&self->reaper.mutex);
  143. pthread_cond_signal(&self->reaper.condition);
  144. pthread_mutex_unlock(&self->reaper.mutex);
  145. /* Join the thread as soon as possible */
  146. pthread_join(self->reaper.thread, NULL);
  147. pthread_cond_destroy(&self->reaper.condition);
  148. pthread_mutex_destroy(&self->reaper.mutex);
  149. }
  150. void game_mode_context_destroy(GameModeContext *self)
  151. {
  152. if (!had_context_init) {
  153. return;
  154. }
  155. /* Leave game mode now */
  156. if (game_mode_context_num_clients(self) > 0) {
  157. game_mode_context_leave(self);
  158. }
  159. had_context_init = false;
  160. game_mode_client_unref(self->client);
  161. end_reaper_thread(self);
  162. /* Destroy the gpu object */
  163. game_mode_free_gpu(&self->stored_gpu);
  164. game_mode_free_gpu(&self->target_gpu);
  165. /* Destroy the cpu object */
  166. game_mode_free_cpu(&self->cpu);
  167. /* Destroy the config object */
  168. config_destroy(self->config);
  169. pthread_rwlock_destroy(&self->rwlock);
  170. }
  171. static void game_mode_store_splitlock(GameModeContext *self)
  172. {
  173. long initial_state = get_splitlock_state();
  174. self->initial_split_lock_mitigate = initial_state;
  175. LOG_MSG("split lock mitigation was initially set to [%ld]\n", initial_state);
  176. }
  177. static int game_mode_disable_splitlock(GameModeContext *self, bool disable)
  178. {
  179. if (!config_get_disable_splitlock(self->config))
  180. return 0;
  181. long value_num = self->initial_split_lock_mitigate;
  182. char value_str[40];
  183. if (disable && value_num == 0)
  184. return 0;
  185. if (value_num == -1)
  186. return 0;
  187. sprintf(value_str, "%ld", value_num);
  188. const char *const exec_args[] = {
  189. "pkexec", LIBEXECDIR "/procsysctl", "split_lock_mitigate", value_str, NULL,
  190. };
  191. LOG_MSG("Requesting update of split_lock_mitigate to %s\n", value_str);
  192. int ret = run_external_process(exec_args, NULL, -1);
  193. if (ret != 0) {
  194. LOG_ERROR("Failed to update split_lock_mitigate\n");
  195. return ret;
  196. }
  197. return 0;
  198. }
  199. static void game_mode_store_governor(GameModeContext *self)
  200. {
  201. if (self->current_govenor != GAME_MODE_GOVERNOR_DEFAULT)
  202. return;
  203. const char *initial_state = get_gov_state();
  204. if (initial_state == NULL)
  205. return;
  206. strncpy(self->initial_cpu_mode, initial_state, sizeof(self->initial_cpu_mode) - 1);
  207. self->initial_cpu_mode[sizeof(self->initial_cpu_mode) - 1] = '\0';
  208. LOG_MSG("governor was initially set to [%s]\n", initial_state);
  209. }
  210. static int game_mode_set_governor(GameModeContext *self, enum GameModeGovernor gov)
  211. {
  212. if (self->current_govenor == gov) {
  213. return 0;
  214. }
  215. char *gov_str = NULL;
  216. char gov_config_str[CONFIG_VALUE_MAX] = { 0 };
  217. switch (gov) {
  218. case GAME_MODE_GOVERNOR_DEFAULT:
  219. config_get_default_governor(self->config, gov_config_str);
  220. gov_str = gov_config_str[0] != '\0' ? gov_config_str : self->initial_cpu_mode;
  221. break;
  222. case GAME_MODE_GOVERNOR_DESIRED:
  223. config_get_desired_governor(self->config, gov_config_str);
  224. gov_str = gov_config_str[0] != '\0' ? gov_config_str : "performance";
  225. break;
  226. case GAME_MODE_GOVERNOR_IGPU_DESIRED:
  227. config_get_igpu_desired_governor(self->config, gov_config_str);
  228. gov_str = gov_config_str[0] != '\0' ? gov_config_str : "powersave";
  229. break;
  230. default:
  231. assert(!"Invalid governor requested");
  232. }
  233. const char *const exec_args[] = {
  234. "pkexec", LIBEXECDIR "/cpugovctl", "set", gov_str, NULL,
  235. };
  236. LOG_MSG("Requesting update of governor policy to %s\n", gov_str);
  237. int ret = run_external_process(exec_args, NULL, -1);
  238. if (ret != 0) {
  239. LOG_ERROR("Failed to update cpu governor policy\n");
  240. return ret;
  241. }
  242. /* Update the current govenor only if we succeed at setting govenors. */
  243. self->current_govenor = gov;
  244. return 0;
  245. }
  246. static void game_mode_store_profile(GameModeContext *self)
  247. {
  248. if (self->current_profile != GAME_MODE_PROFILE_DEFAULT)
  249. return;
  250. const char *initial_state = get_profile_state();
  251. if (initial_state == NULL)
  252. return;
  253. strncpy(self->initial_profile, initial_state, sizeof(self->initial_profile) - 1);
  254. self->initial_profile[sizeof(self->initial_profile) - 1] = '\0';
  255. LOG_MSG("platform profile was initially set to [%s]\n", initial_state);
  256. }
  257. static int game_mode_set_profile(GameModeContext *self, enum GameModeProfile prof)
  258. {
  259. if (self->current_profile == prof) {
  260. return 0;
  261. }
  262. const char *prof_str = NULL;
  263. char prof_config_str[CONFIG_VALUE_MAX] = { 0 };
  264. switch (prof) {
  265. case GAME_MODE_PROFILE_DEFAULT:
  266. config_get_default_profile(self->config, prof_config_str);
  267. prof_str = prof_config_str[0] != '\0' ? prof_config_str : self->initial_profile;
  268. break;
  269. case GAME_MODE_PROFILE_DESIRED:
  270. config_get_desired_profile(self->config, prof_config_str);
  271. prof_str = prof_config_str[0] != '\0' ? prof_config_str : "performance";
  272. break;
  273. default:
  274. assert(!"Invalid platform profile requested");
  275. }
  276. const char *const exec_args[] = {
  277. "pkexec", LIBEXECDIR "/platprofctl", "set", prof_str, NULL,
  278. };
  279. LOG_MSG("Requesting update of platform profile to %s\n", prof_str);
  280. int ret = run_external_process(exec_args, NULL, -1);
  281. if (ret != 0) {
  282. LOG_ERROR("Failed to update platform profile\n");
  283. return ret;
  284. }
  285. /* Update the current govenor only if we succeed at setting govenors. */
  286. self->current_profile = prof;
  287. return 0;
  288. }
  289. static void game_mode_enable_igpu_optimization(GameModeContext *self)
  290. {
  291. float threshold = config_get_igpu_power_threshold(self->config);
  292. /* There's no way the GPU is using 10000x the power. This lets us
  293. * short-circuit if the config file specifies an invalid threshold
  294. * and we want to disable the iGPU heuristic.
  295. */
  296. if (threshold < 10000 && get_cpu_energy_uj(&self->last_cpu_energy_uj) &&
  297. get_igpu_energy_uj(&self->last_igpu_energy_uj)) {
  298. LOG_MSG(
  299. "Successfully queried power data for the CPU and iGPU. "
  300. "Enabling the integrated GPU optimization");
  301. self->igpu_optimization_enabled = true;
  302. }
  303. }
  304. static void game_mode_disable_igpu_optimization(GameModeContext *self)
  305. {
  306. self->igpu_optimization_enabled = false;
  307. }
  308. static void game_mode_check_igpu_energy(GameModeContext *self)
  309. {
  310. pthread_rwlock_wrlock(&self->rwlock);
  311. /* We only care if we're not in the default governor */
  312. if (self->current_govenor == GAME_MODE_GOVERNOR_DEFAULT)
  313. goto unlock;
  314. if (!self->igpu_optimization_enabled)
  315. goto unlock;
  316. uint32_t cpu_energy_uj, igpu_energy_uj;
  317. if (!get_cpu_energy_uj(&cpu_energy_uj) || !get_igpu_energy_uj(&igpu_energy_uj)) {
  318. /* We've already succeeded at getting power information once so
  319. * failing here is possible but very unexpected. */
  320. self->igpu_optimization_enabled = false;
  321. LOG_ERROR("Failed to get CPU and iGPU power data\n");
  322. goto unlock;
  323. }
  324. /* The values we query from RAPL are in units of microjoules of energy
  325. * used since boot or since the last time the counter rolled over. You
  326. * can get average power over some time window T by sampling before and
  327. * after and doing the following calculation
  328. *
  329. * power_uw = (energy_uj_after - energy_uj_before) / seconds
  330. *
  331. * To get the power in Watts (rather than microwatts), you can simply
  332. * divide by 1000000.
  333. *
  334. * Because we're only concerned with the ratio between the GPU and CPU
  335. * power, we never bother dividing by 1000000 the length of time of the
  336. * sampling window because that would just algebraically cancel out.
  337. * Instead, we divide the GPU energy used in the window (difference of
  338. * before and after) by the CPU energy used. It nicely provides the
  339. * ratio of the averages and there are no instantaneous sampling
  340. * problems.
  341. *
  342. * Overflow is possible here. However, that would simply mean that
  343. * the HW counter has overflowed and us wrapping around is probably
  344. * the right thing to do. Wrapping at 32 bits is exactly what the
  345. * Linux kernel's turbostat utility does so it's probably right.
  346. */
  347. uint32_t cpu_energy_delta_uj = cpu_energy_uj - self->last_cpu_energy_uj;
  348. uint32_t igpu_energy_delta_uj = igpu_energy_uj - self->last_igpu_energy_uj;
  349. self->last_cpu_energy_uj = cpu_energy_uj;
  350. self->last_igpu_energy_uj = igpu_energy_uj;
  351. if (cpu_energy_delta_uj == 0) {
  352. LOG_ERROR("CPU reported no energy used\n");
  353. goto unlock;
  354. }
  355. float threshold = config_get_igpu_power_threshold(self->config);
  356. double ratio = (double)igpu_energy_delta_uj / (double)cpu_energy_delta_uj;
  357. if (ratio > threshold) {
  358. game_mode_set_governor(self, GAME_MODE_GOVERNOR_IGPU_DESIRED);
  359. } else {
  360. game_mode_set_governor(self, GAME_MODE_GOVERNOR_DESIRED);
  361. }
  362. unlock:
  363. pthread_rwlock_unlock(&self->rwlock);
  364. }
  365. static void game_mode_context_store_defaults(GameModeContext *self)
  366. {
  367. game_mode_store_profile(self);
  368. game_mode_store_governor(self);
  369. game_mode_store_splitlock(self);
  370. }
  371. /**
  372. * Pivot into game mode.
  373. *
  374. * This is only possible after game_mode_context_init has made a GameModeContext
  375. * usable, and should always be followed by a game_mode_context_leave.
  376. */
  377. static void game_mode_context_enter(GameModeContext *self)
  378. {
  379. LOG_MSG("Entering Game Mode...\n");
  380. sd_notifyf(0, "STATUS=%sGameMode is now active.%s\n", "\x1B[1;32m", "\x1B[0m");
  381. /* Store the default value for everything before anything changes. */
  382. game_mode_context_store_defaults(self);
  383. /* Set the profile before anything else since it can restrict things
  384. * like the governor.
  385. */
  386. game_mode_set_profile(self, GAME_MODE_PROFILE_DESIRED);
  387. if (game_mode_set_governor(self, GAME_MODE_GOVERNOR_DESIRED) == 0) {
  388. /* We just switched to a non-default governor. Enable the iGPU
  389. * optimization.
  390. */
  391. game_mode_enable_igpu_optimization(self);
  392. }
  393. /* Inhibit the screensaver */
  394. if (config_get_inhibit_screensaver(self->config)) {
  395. game_mode_destroy_idle_inhibitor(self->idle_inhibitor);
  396. self->idle_inhibitor = game_mode_create_idle_inhibitor();
  397. }
  398. game_mode_disable_splitlock(self, true);
  399. /* Apply GPU optimisations by first getting the current values, and then setting the target */
  400. game_mode_get_gpu(self->stored_gpu);
  401. game_mode_apply_gpu(self->target_gpu);
  402. game_mode_park_cpu(self->cpu);
  403. /* Run custom scripts last - ensures the above are applied first and these scripts can react to
  404. * them if needed */
  405. char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX];
  406. memset(scripts, 0, sizeof(scripts));
  407. config_get_gamemode_start_scripts(self->config, scripts);
  408. long timeout = config_get_script_timeout(self->config);
  409. game_mode_execute_scripts(scripts, (int)timeout);
  410. }
  411. /**
  412. * Pivot out of game mode.
  413. *
  414. * Should only be called after both init and game_mode_context_enter have
  415. * been performed.
  416. */
  417. static void game_mode_context_leave(GameModeContext *self)
  418. {
  419. LOG_MSG("Leaving Game Mode...\n");
  420. sd_notifyf(0, "STATUS=%sGameMode is currently deactivated.%s\n", "\x1B[1;36m", "\x1B[0m");
  421. /* Restore profile before anything else since it can restrict things
  422. * like the governor.
  423. */
  424. game_mode_set_profile(self, GAME_MODE_PROFILE_DEFAULT);
  425. /* Remove GPU optimisations */
  426. game_mode_apply_gpu(self->stored_gpu);
  427. game_mode_unpark_cpu(self->cpu);
  428. /* UnInhibit the screensaver */
  429. if (config_get_inhibit_screensaver(self->config)) {
  430. game_mode_destroy_idle_inhibitor(self->idle_inhibitor);
  431. self->idle_inhibitor = NULL;
  432. }
  433. game_mode_disable_splitlock(self, false);
  434. game_mode_set_governor(self, GAME_MODE_GOVERNOR_DEFAULT);
  435. game_mode_disable_igpu_optimization(self);
  436. char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX];
  437. memset(scripts, 0, sizeof(scripts));
  438. config_get_gamemode_end_scripts(self->config, scripts);
  439. long timeout = config_get_script_timeout(self->config);
  440. game_mode_execute_scripts(scripts, (int)timeout);
  441. }
  442. /**
  443. * Automatically expire all dead processes
  444. *
  445. * This has to take special care to ensure thread safety and ensuring that our
  446. * pointer is never cached incorrectly.
  447. */
  448. static void game_mode_context_auto_expire(GameModeContext *self)
  449. {
  450. bool removing = true;
  451. while (removing) {
  452. pthread_rwlock_rdlock(&self->rwlock);
  453. removing = false;
  454. /* Each time we hit an expired game, start the loop back */
  455. for (GameModeClient *client = self->client; client; client = client->next) {
  456. if (kill(client->pid, 0) != 0) {
  457. LOG_MSG("Removing expired game [%i]...\n", client->pid);
  458. pthread_rwlock_unlock(&self->rwlock);
  459. game_mode_context_unregister(self, client->pid, client->pid);
  460. removing = true;
  461. break;
  462. }
  463. }
  464. if (!removing) {
  465. pthread_rwlock_unlock(&self->rwlock);
  466. break;
  467. }
  468. if (game_mode_context_num_clients(self) == 0)
  469. LOG_MSG("Properly cleaned up all expired games.\n");
  470. }
  471. }
  472. /**
  473. * Determine if the client is already known to the context
  474. */
  475. static const GameModeClient *game_mode_context_has_client(GameModeContext *self, pid_t client)
  476. {
  477. const GameModeClient *found = NULL;
  478. pthread_rwlock_rdlock(&self->rwlock);
  479. /* Walk all clients and find a matching pid */
  480. for (GameModeClient *cl = self->client; cl; cl = cl->next) {
  481. if (cl->pid == client) {
  482. found = cl;
  483. break;
  484. }
  485. }
  486. pthread_rwlock_unlock(&self->rwlock);
  487. return found;
  488. }
  489. int game_mode_context_num_clients(GameModeContext *self)
  490. {
  491. return atomic_load(&self->refcount);
  492. }
  493. pid_t *game_mode_context_list_clients(GameModeContext *self, unsigned int *count)
  494. {
  495. pid_t *res = NULL;
  496. unsigned int i = 0;
  497. unsigned int n;
  498. pthread_rwlock_rdlock(&self->rwlock);
  499. n = (unsigned int)atomic_load(&self->refcount);
  500. if (n > 0)
  501. res = (pid_t *)malloc(n * sizeof(pid_t));
  502. for (GameModeClient *cl = self->client; cl; cl = cl->next) {
  503. assert(n > i);
  504. res[i] = cl->pid;
  505. i++;
  506. }
  507. *count = i;
  508. pthread_rwlock_unlock(&self->rwlock);
  509. return res;
  510. }
  511. GameModeClient *game_mode_context_lookup_client(GameModeContext *self, pid_t client)
  512. {
  513. GameModeClient *found = NULL;
  514. pthread_rwlock_rdlock(&self->rwlock);
  515. /* Walk all clients and find a matching pid */
  516. for (GameModeClient *cl = self->client; cl; cl = cl->next) {
  517. if (cl->pid == client) {
  518. found = cl;
  519. break;
  520. }
  521. }
  522. if (found) {
  523. game_mode_client_ref(found);
  524. }
  525. pthread_rwlock_unlock(&self->rwlock);
  526. return found;
  527. }
  528. static int game_mode_apply_client_optimisations(GameModeContext *self, pid_t client)
  529. {
  530. /* Store current renice and apply */
  531. game_mode_apply_renice(self, client, 0 /* expect zero value to start with */);
  532. /* Store current ioprio value and apply */
  533. game_mode_apply_ioprio(self, client, IOPRIO_DEFAULT);
  534. /* Apply scheduler policies */
  535. game_mode_apply_scheduling(self, client);
  536. /* Apply core pinning */
  537. game_mode_apply_core_pinning(self->cpu, client, false);
  538. return 0;
  539. }
  540. int game_mode_context_register(GameModeContext *self, pid_t client, pid_t requester)
  541. {
  542. errno = 0;
  543. /* Construct a new client if we can */
  544. char *executable = NULL;
  545. int err = -1;
  546. /* Check our requester config first */
  547. if (requester != client) {
  548. /* Lookup the executable first */
  549. executable = game_mode_context_find_exe(requester);
  550. if (!executable) {
  551. goto error_cleanup;
  552. }
  553. /* Check our blacklist and whitelist */
  554. if (!config_get_supervisor_whitelisted(self->config, executable)) {
  555. LOG_MSG("Supervisor [%s] was rejected (not in whitelist)\n", executable);
  556. err = -2;
  557. goto error_cleanup;
  558. } else if (config_get_supervisor_blacklisted(self->config, executable)) {
  559. LOG_MSG("Supervisor [%s] was rejected (in blacklist)\n", executable);
  560. err = -2;
  561. goto error_cleanup;
  562. }
  563. /* We're done with the requestor */
  564. free(executable);
  565. executable = NULL;
  566. } else if (config_get_require_supervisor(self->config)) {
  567. LOG_ERROR("Direct request made but require_supervisor was set, rejecting request!\n");
  568. err = -2;
  569. goto error_cleanup;
  570. }
  571. /* Check the PID first to spare a potentially expensive lookup for the exe */
  572. pthread_rwlock_rdlock(&self->rwlock); // ensure our pointer is sane
  573. const GameModeClient *existing = game_mode_context_has_client(self, client);
  574. if (existing) {
  575. LOG_HINTED(ERROR,
  576. "Addition requested for already known client %d [%s].\n",
  577. " -- This may happen due to using exec or shell wrappers. You may want to\n"
  578. " -- blacklist this client so GameMode can see its final name here.\n",
  579. existing->pid,
  580. existing->executable);
  581. pthread_rwlock_unlock(&self->rwlock);
  582. goto error_cleanup;
  583. }
  584. pthread_rwlock_unlock(&self->rwlock);
  585. /* Lookup the executable first */
  586. executable = game_mode_context_find_exe(client);
  587. if (!executable)
  588. goto error_cleanup;
  589. /* Check our blacklist and whitelist */
  590. if (!config_get_client_whitelisted(self->config, executable)) {
  591. LOG_MSG("Client [%s] was rejected (not in whitelist)\n", executable);
  592. goto error_cleanup;
  593. } else if (config_get_client_blacklisted(self->config, executable)) {
  594. LOG_MSG("Client [%s] was rejected (in blacklist)\n", executable);
  595. goto error_cleanup;
  596. }
  597. /* From now on we depend on the client, initialize it */
  598. GameModeClient *cl = game_mode_client_new(client, executable, requester);
  599. if (!cl)
  600. goto error_cleanup;
  601. free(executable); /* we're now done with memory */
  602. /* Begin a write lock now to insert our new client at list start */
  603. pthread_rwlock_wrlock(&self->rwlock);
  604. LOG_MSG("Adding game: %d [%s]\n", client, cl->executable);
  605. /* Update the list */
  606. cl->next = self->client;
  607. self->client = cl;
  608. /* First add, init */
  609. if (atomic_fetch_add_explicit(&self->refcount, 1, memory_order_seq_cst) == 0) {
  610. game_mode_context_enter(self);
  611. }
  612. game_mode_apply_client_optimisations(self, client);
  613. /* Unlock now we're done applying optimisations */
  614. pthread_rwlock_unlock(&self->rwlock);
  615. game_mode_client_registered(client);
  616. return 0;
  617. error_cleanup:
  618. if (errno != 0)
  619. LOG_ERROR("Failed to register client [%d]: %s\n", client, strerror(errno));
  620. free(executable);
  621. return err;
  622. }
  623. static int game_mode_remove_client_optimisations(GameModeContext *self, pid_t client)
  624. {
  625. /* Restore the ioprio value for the process, expecting it to be the config value */
  626. game_mode_apply_ioprio(self, client, (int)config_get_ioprio_value(self->config));
  627. /* Restore the renice value for the process, expecting it to be our config value */
  628. game_mode_apply_renice(self, client, (int)config_get_renice_value(self->config));
  629. /* Restore the process affinity to all online cores */
  630. game_mode_undo_core_pinning(self->cpu, client);
  631. return 0;
  632. }
  633. int game_mode_context_unregister(GameModeContext *self, pid_t client, pid_t requester)
  634. {
  635. GameModeClient *cl = NULL;
  636. GameModeClient *prev = NULL;
  637. bool found = false;
  638. /* Check our requester config first */
  639. if (requester != client) {
  640. /* Lookup the executable first */
  641. char *executable = game_mode_context_find_exe(requester);
  642. if (!executable) {
  643. return -1;
  644. }
  645. /* Check our blacklist and whitelist */
  646. if (!config_get_supervisor_whitelisted(self->config, executable)) {
  647. LOG_MSG("Supervisor [%s] was rejected (not in whitelist)\n", executable);
  648. free(executable);
  649. return -2;
  650. } else if (config_get_supervisor_blacklisted(self->config, executable)) {
  651. LOG_MSG("Supervisor [%s] was rejected (in blacklist)\n", executable);
  652. free(executable);
  653. return -2;
  654. }
  655. free(executable);
  656. } else if (config_get_require_supervisor(self->config)) {
  657. LOG_ERROR("Direct request made but require_supervisor was set, rejecting request!\n");
  658. return -2;
  659. }
  660. /* Requires locking. */
  661. pthread_rwlock_wrlock(&self->rwlock);
  662. for (prev = cl = self->client; cl; cl = cl->next) {
  663. if (cl->pid != client) {
  664. prev = cl;
  665. continue;
  666. }
  667. LOG_MSG("Removing game: %d [%s]\n", client, cl->executable);
  668. /* Found it */
  669. found = true;
  670. prev->next = cl->next;
  671. if (cl == self->client) {
  672. self->client = cl->next;
  673. }
  674. cl->next = NULL;
  675. game_mode_client_unref(cl);
  676. break;
  677. }
  678. if (!found) {
  679. LOG_HINTED(
  680. ERROR,
  681. "Removal requested for unknown process [%d].\n",
  682. " -- The parent process probably forked and tries to unregister from the wrong\n"
  683. " -- process now. We cannot work around this. This message will likely be paired\n"
  684. " -- with a nearby 'Removing expired game' which means we cleaned up properly\n"
  685. " -- (we will log this event). This hint will be displayed only once.\n",
  686. client);
  687. pthread_rwlock_unlock(&self->rwlock);
  688. return -1;
  689. }
  690. /* When we hit bottom then end the game mode */
  691. if (atomic_fetch_sub_explicit(&self->refcount, 1, memory_order_seq_cst) == 1) {
  692. game_mode_context_leave(self);
  693. }
  694. game_mode_remove_client_optimisations(self, client);
  695. /* Unlock now we're done applying optimisations */
  696. pthread_rwlock_unlock(&self->rwlock);
  697. game_mode_client_unregistered(client);
  698. return 0;
  699. }
  700. int game_mode_context_query_status(GameModeContext *self, pid_t client, pid_t requester)
  701. {
  702. GameModeClient *cl = NULL;
  703. int ret = 0;
  704. /* First check the requester settings if appropriate */
  705. if (client != requester) {
  706. char *executable = game_mode_context_find_exe(requester);
  707. if (!executable) {
  708. return -1;
  709. }
  710. /* Check our blacklist and whitelist */
  711. if (!config_get_supervisor_whitelisted(self->config, executable)) {
  712. LOG_MSG("Supervisor [%s] was rejected (not in whitelist)\n", executable);
  713. free(executable);
  714. return -2;
  715. } else if (config_get_supervisor_blacklisted(self->config, executable)) {
  716. LOG_MSG("Supervisor [%s] was rejected (in blacklist)\n", executable);
  717. free(executable);
  718. return -2;
  719. }
  720. free(executable);
  721. }
  722. /*
  723. * Check the current refcount on gamemode, this equates to whether gamemode is active or not,
  724. * see game_mode_context_register and game_mode_context_unregister
  725. */
  726. if (atomic_load_explicit(&self->refcount, memory_order_seq_cst)) {
  727. ret++;
  728. /* Check if the current client is registered */
  729. /* Requires locking. */
  730. pthread_rwlock_rdlock(&self->rwlock);
  731. for (cl = self->client; cl; cl = cl->next) {
  732. if (cl->pid != client) {
  733. continue;
  734. }
  735. /* Found it */
  736. ret++;
  737. break;
  738. }
  739. /* Unlock here, potentially yielding */
  740. pthread_rwlock_unlock(&self->rwlock);
  741. }
  742. return ret;
  743. }
  744. /**
  745. * Construct a new GameModeClient for the given process ID
  746. *
  747. * This is deliberately OOM safe
  748. */
  749. static GameModeClient *game_mode_client_new(pid_t pid, char *executable, pid_t requester)
  750. {
  751. /* This bit seems to be formatted differently by different clang-format versions */
  752. /* clang-format off */
  753. GameModeClient c = {
  754. .next = NULL,
  755. .pid = pid,
  756. .requester = requester,
  757. .timestamp = 0,
  758. };
  759. /* clang-format on */
  760. GameModeClient *ret = NULL;
  761. struct timeval now = {
  762. 0,
  763. };
  764. int r;
  765. r = gettimeofday(&now, NULL);
  766. if (r == 0)
  767. c.timestamp = now.tv_sec;
  768. ret = calloc(1, sizeof(struct GameModeClient));
  769. if (!ret) {
  770. return NULL;
  771. }
  772. *ret = c;
  773. ret->refcount = ATOMIC_VAR_INIT(1);
  774. strncpy(ret->executable, executable, PATH_MAX - 1);
  775. return ret;
  776. }
  777. /**
  778. * Unref a client and the next element in the list, if non-null.
  779. */
  780. void game_mode_client_unref(GameModeClient *client)
  781. {
  782. if (!client) {
  783. return;
  784. }
  785. if (atomic_fetch_sub_explicit(&client->refcount, 1, memory_order_seq_cst) > 1) {
  786. return; /* object is still alive */
  787. }
  788. if (client->next) {
  789. game_mode_client_unref(client->next);
  790. }
  791. free(client);
  792. }
  793. void game_mode_client_ref(GameModeClient *client)
  794. {
  795. if (!client) {
  796. return;
  797. }
  798. atomic_fetch_add_explicit(&client->refcount, 1, memory_order_seq_cst);
  799. }
  800. /**
  801. * The process identifier of the client.
  802. */
  803. pid_t game_mode_client_get_pid(GameModeClient *client)
  804. {
  805. assert(client != NULL);
  806. return client->pid;
  807. }
  808. /**
  809. * The path to the executable of client.
  810. */
  811. const char *game_mode_client_get_executable(GameModeClient *client)
  812. {
  813. assert(client != NULL);
  814. return client->executable;
  815. }
  816. /**
  817. * The process identifier of the requester.
  818. */
  819. pid_t game_mode_client_get_requester(GameModeClient *client)
  820. {
  821. assert(client != NULL);
  822. return client->requester;
  823. }
  824. /**
  825. * The time that game mode was requested for the client.
  826. */
  827. uint64_t game_mode_client_get_timestamp(GameModeClient *client)
  828. {
  829. assert(client != NULL);
  830. return (uint64_t)client->timestamp;
  831. }
  832. static void game_mode_reapply_core_pinning_internal(GameModeContext *self)
  833. {
  834. pthread_rwlock_wrlock(&self->rwlock);
  835. if (game_mode_context_num_clients(self)) {
  836. for (GameModeClient *cl = self->client; cl; cl = cl->next)
  837. game_mode_apply_core_pinning(self->cpu, cl->pid, true);
  838. }
  839. pthread_rwlock_unlock(&self->rwlock);
  840. }
  841. /* Internal refresh config function (assumes no contention with reaper thread) */
  842. static void game_mode_reload_config_internal(GameModeContext *self)
  843. {
  844. LOG_MSG("Reloading config...\n");
  845. /* Make sure we have a readwrite lock on ourselves */
  846. pthread_rwlock_wrlock(&self->rwlock);
  847. /* Remove current optimisations when we're already active */
  848. if (game_mode_context_num_clients(self)) {
  849. for (GameModeClient *cl = self->client; cl; cl = cl->next)
  850. game_mode_remove_client_optimisations(self, cl->pid);
  851. game_mode_context_leave(self);
  852. }
  853. /* Reload the config */
  854. config_reload(self->config);
  855. game_mode_reconfig_cpu(self->config, &self->cpu);
  856. /* Re-apply all current optimisations */
  857. if (game_mode_context_num_clients(self)) {
  858. /* Start the global context back up */
  859. game_mode_context_enter(self);
  860. for (GameModeClient *cl = self->client; cl; cl = cl->next)
  861. game_mode_apply_client_optimisations(self, cl->pid);
  862. }
  863. pthread_rwlock_unlock(&self->rwlock);
  864. LOG_MSG("Config reload complete\n");
  865. }
  866. /**
  867. * We continuously run until told otherwise.
  868. */
  869. static void *game_mode_context_reaper(void *userdata)
  870. {
  871. /* Stack, not allocated, won't disappear. */
  872. GameModeContext *self = userdata;
  873. long reaper_interval = config_get_reaper_frequency(self->config);
  874. struct timespec ts = { 0, 0 };
  875. ts.tv_sec = time(NULL) + reaper_interval;
  876. while (self->reaper.running) {
  877. /* Wait for condition */
  878. pthread_mutex_lock(&self->reaper.mutex);
  879. pthread_cond_timedwait(&self->reaper.condition, &self->reaper.mutex, &ts);
  880. pthread_mutex_unlock(&self->reaper.mutex);
  881. /* Highly possible the main thread woke us up to exit */
  882. if (!self->reaper.running) {
  883. return NULL;
  884. }
  885. /* Check on the CPU/iGPU energy balance */
  886. game_mode_check_igpu_energy(self);
  887. /* Expire remaining entries */
  888. game_mode_context_auto_expire(self);
  889. /* Re apply the thread affinity mask (aka core pinning) */
  890. game_mode_reapply_core_pinning_internal(self);
  891. /* Check if we should be reloading the config, and do so if needed */
  892. if (config_needs_reload(self->config)) {
  893. LOG_MSG("Detected config file changes\n");
  894. game_mode_reload_config_internal(self);
  895. }
  896. ts.tv_sec = time(NULL) + reaper_interval;
  897. }
  898. return NULL;
  899. }
  900. GameModeContext *game_mode_context_instance(void)
  901. {
  902. return &instance;
  903. }
  904. GameModeConfig *game_mode_config_from_context(const GameModeContext *context)
  905. {
  906. return context ? context->config : NULL;
  907. }
  908. /**
  909. * Attempt to locate the exe for the process.
  910. * We might run into issues if the process is running under an odd umask.
  911. */
  912. static char *game_mode_context_find_exe(pid_t pid)
  913. {
  914. char buffer[PATH_MAX];
  915. char *proc_path = NULL, *wine_exe = NULL;
  916. autoclose_fd int pidfd = -1;
  917. ssize_t r;
  918. if (!(proc_path = buffered_snprintf(buffer, "/proc/%d", pid)))
  919. goto fail;
  920. /* Translate /proc/<pid>/exe to the application binary */
  921. pidfd = openat(AT_FDCWD, proc_path, O_RDONLY | O_NONBLOCK | O_DIRECTORY | O_CLOEXEC | O_NOCTTY);
  922. if (pidfd == -1)
  923. goto fail;
  924. r = readlinkat(pidfd, "exe", buffer, sizeof(buffer));
  925. if (r == sizeof(buffer)) {
  926. errno = ENAMETOOLONG;
  927. r = -1;
  928. }
  929. if (r == -1)
  930. goto fail;
  931. buffer[r] = '\0';
  932. char *exe = strdup(buffer);
  933. /* Resolve for wine if appropriate */
  934. if ((wine_exe = game_mode_resolve_wine_preloader(exe, pid))) {
  935. free(exe);
  936. exe = wine_exe;
  937. }
  938. return exe;
  939. fail:
  940. if (errno != 0) // otherwise a proper message was logged before
  941. LOG_ERROR("Unable to find executable for PID %d: %s\n", pid, strerror(errno));
  942. return NULL;
  943. }
  944. /* Executes a set of scripts */
  945. static void game_mode_execute_scripts(char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX], int timeout)
  946. {
  947. unsigned int i = 0;
  948. while (i < CONFIG_LIST_MAX && *scripts[i] != '\0') {
  949. LOG_MSG("Executing script [%s]\n", scripts[i]);
  950. int err;
  951. const char *args[] = { "/bin/sh", "-c", scripts[i], NULL };
  952. if ((err = run_external_process(args, NULL, timeout)) != 0) {
  953. /* Log the failure, but this is not fatal */
  954. LOG_ERROR("Script [%s] failed with error %d\n", scripts[i], err);
  955. }
  956. i++;
  957. }
  958. }
  959. /*
  960. * Reload the current configuration
  961. *
  962. * Reloading the configuration completely live would be problematic for various optimisation values,
  963. * to ensure we have a fully clean state, we tear down the whole gamemode state and regrow it with a
  964. * new config, remembering the registered games
  965. */
  966. int game_mode_reload_config(GameModeContext *self)
  967. {
  968. /* Stop the reaper thread first */
  969. end_reaper_thread(self);
  970. game_mode_reload_config_internal(self);
  971. /* Restart the reaper thread back up again */
  972. start_reaper_thread(self);
  973. return 0;
  974. }