gamemode-context.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  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-governors.h"
  29. #include "common-helpers.h"
  30. #include "common-logging.h"
  31. #include "gamemode.h"
  32. #include "gamemode-config.h"
  33. #include "build-config.h"
  34. #include <assert.h>
  35. #include <fcntl.h>
  36. #include <pthread.h>
  37. #include <stdatomic.h>
  38. #include <stdlib.h>
  39. #include <systemd/sd-daemon.h> /* TODO: Move usage to gamemode-dbus.c */
  40. #include <unistd.h>
  41. /**
  42. * The GameModeClient encapsulates the remote connection, providing a list
  43. * form to contain the pid and credentials.
  44. */
  45. struct GameModeClient {
  46. _Atomic int refcount; /**<Allow outside usage */
  47. pid_t pid; /**< Process ID */
  48. struct GameModeClient *next; /**<Next client in the list */
  49. char executable[PATH_MAX]; /**<Process executable */
  50. };
  51. struct GameModeContext {
  52. pthread_rwlock_t rwlock; /**<Guard access to the client list */
  53. _Atomic int refcount; /**<Allow cycling the game mode */
  54. GameModeClient *client; /**<Pointer to first client */
  55. GameModeConfig *config; /**<Pointer to config object */
  56. char initial_cpu_mode[64]; /**<Only updates when we can */
  57. struct GameModeGPUInfo *stored_gpu; /**<Stored GPU info for the current GPU */
  58. struct GameModeGPUInfo *target_gpu; /**<Target GPU info for the current GPU */
  59. /* Reaper control */
  60. struct {
  61. pthread_t thread;
  62. bool running;
  63. pthread_mutex_t mutex;
  64. pthread_cond_t condition;
  65. } reaper;
  66. };
  67. static GameModeContext instance = { 0 };
  68. /**
  69. * Protect against signals
  70. */
  71. static volatile bool had_context_init = false;
  72. static GameModeClient *game_mode_client_new(pid_t pid, char *exe);
  73. static const GameModeClient *game_mode_context_has_client(GameModeContext *self, pid_t client);
  74. static void *game_mode_context_reaper(void *userdata);
  75. static void game_mode_context_enter(GameModeContext *self);
  76. static void game_mode_context_leave(GameModeContext *self);
  77. static char *game_mode_context_find_exe(pid_t pid);
  78. static void game_mode_execute_scripts(char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX], int timeout);
  79. static void start_reaper_thread(GameModeContext *self)
  80. {
  81. pthread_mutex_init(&self->reaper.mutex, NULL);
  82. pthread_cond_init(&self->reaper.condition, NULL);
  83. self->reaper.running = true;
  84. if (pthread_create(&self->reaper.thread, NULL, game_mode_context_reaper, self) != 0) {
  85. FATAL_ERROR("Couldn't construct a new thread");
  86. }
  87. }
  88. void game_mode_context_init(GameModeContext *self)
  89. {
  90. if (had_context_init) {
  91. LOG_ERROR("Context already initialised\n");
  92. return;
  93. }
  94. had_context_init = true;
  95. self->refcount = ATOMIC_VAR_INIT(0);
  96. /* clear the initial string */
  97. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  98. /* Initialise the config */
  99. self->config = config_create();
  100. config_init(self->config);
  101. /* Initialise the current GPU info */
  102. game_mode_initialise_gpu(self->config, &self->stored_gpu);
  103. game_mode_initialise_gpu(self->config, &self->target_gpu);
  104. pthread_rwlock_init(&self->rwlock, NULL);
  105. /* Get the reaper thread going */
  106. start_reaper_thread(self);
  107. }
  108. static void end_reaper_thread(GameModeContext *self)
  109. {
  110. self->reaper.running = false;
  111. /* We might be stuck waiting, so wake it up again */
  112. pthread_mutex_lock(&self->reaper.mutex);
  113. pthread_cond_signal(&self->reaper.condition);
  114. pthread_mutex_unlock(&self->reaper.mutex);
  115. /* Join the thread as soon as possible */
  116. pthread_join(self->reaper.thread, NULL);
  117. pthread_cond_destroy(&self->reaper.condition);
  118. pthread_mutex_destroy(&self->reaper.mutex);
  119. }
  120. void game_mode_context_destroy(GameModeContext *self)
  121. {
  122. if (!had_context_init) {
  123. return;
  124. }
  125. /* Leave game mode now */
  126. if (game_mode_context_num_clients(self) > 0) {
  127. game_mode_context_leave(self);
  128. }
  129. had_context_init = false;
  130. game_mode_client_unref(self->client);
  131. end_reaper_thread(self);
  132. /* Destroy the gpu object */
  133. game_mode_free_gpu(&self->stored_gpu);
  134. game_mode_free_gpu(&self->target_gpu);
  135. /* Destroy the config object */
  136. config_destroy(self->config);
  137. pthread_rwlock_destroy(&self->rwlock);
  138. }
  139. /**
  140. * Pivot into game mode.
  141. *
  142. * This is only possible after game_mode_context_init has made a GameModeContext
  143. * usable, and should always be followed by a game_mode_context_leave.
  144. */
  145. static void game_mode_context_enter(GameModeContext *self)
  146. {
  147. LOG_MSG("Entering Game Mode...\n");
  148. sd_notifyf(0, "STATUS=%sGameMode is now active.%s\n", "\x1B[1;32m", "\x1B[0m");
  149. /* Read the initial governor state so we can revert it correctly */
  150. const char *initial_state = get_gov_state();
  151. if (initial_state) {
  152. /* store the initial cpu governor mode */
  153. strncpy(self->initial_cpu_mode, initial_state, sizeof(self->initial_cpu_mode) - 1);
  154. self->initial_cpu_mode[sizeof(self->initial_cpu_mode) - 1] = '\0';
  155. LOG_MSG("governor was initially set to [%s]\n", initial_state);
  156. /* Choose the desired governor */
  157. char desired[CONFIG_VALUE_MAX] = { 0 };
  158. config_get_desired_governor(self->config, desired);
  159. const char *desiredGov = desired[0] != '\0' ? desired : "performance";
  160. const char *const exec_args[] = {
  161. "/usr/bin/pkexec", LIBEXECDIR "/cpugovctl", "set", desiredGov, NULL,
  162. };
  163. LOG_MSG("Requesting update of governor policy to %s\n", desiredGov);
  164. if (run_external_process(exec_args, NULL, -1) != 0) {
  165. LOG_ERROR("Failed to update cpu governor policy\n");
  166. /* if the set fails, clear the initial mode so we don't try and reset it back and fail
  167. * again, presumably */
  168. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  169. }
  170. }
  171. /* Inhibit the screensaver */
  172. if (config_get_inhibit_screensaver(self->config))
  173. game_mode_inhibit_screensaver(true);
  174. /* Apply GPU optimisations by first getting the current values, and then setting the target */
  175. game_mode_get_gpu(self->stored_gpu);
  176. game_mode_apply_gpu(self->target_gpu);
  177. /* Run custom scripts last - ensures the above are applied first and these scripts can react to
  178. * them if needed */
  179. char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX];
  180. memset(scripts, 0, sizeof(scripts));
  181. config_get_gamemode_start_scripts(self->config, scripts);
  182. long timeout = config_get_script_timeout(self->config);
  183. game_mode_execute_scripts(scripts, (int)timeout);
  184. }
  185. /**
  186. * Pivot out of game mode.
  187. *
  188. * Should only be called after both init and game_mode_context_enter have
  189. * been performed.
  190. */
  191. static void game_mode_context_leave(GameModeContext *self)
  192. {
  193. LOG_MSG("Leaving Game Mode...\n");
  194. sd_notifyf(0, "STATUS=%sGameMode is currently deactivated.%s\n", "\x1B[1;36m", "\x1B[0m");
  195. /* Remove GPU optimisations */
  196. game_mode_apply_gpu(self->stored_gpu);
  197. /* UnInhibit the screensaver */
  198. if (config_get_inhibit_screensaver(self->config))
  199. game_mode_inhibit_screensaver(false);
  200. /* Reset the governer state back to initial */
  201. if (self->initial_cpu_mode[0] != '\0') {
  202. /* Choose the governor to reset to, using the config to override */
  203. char defaultgov[CONFIG_VALUE_MAX] = { 0 };
  204. config_get_default_governor(self->config, defaultgov);
  205. const char *gov_mode = defaultgov[0] != '\0' ? defaultgov : self->initial_cpu_mode;
  206. const char *const exec_args[] = {
  207. "/usr/bin/pkexec", LIBEXECDIR "/cpugovctl", "set", gov_mode, NULL,
  208. };
  209. LOG_MSG("Requesting update of governor policy to %s\n", gov_mode);
  210. if (run_external_process(exec_args, NULL, -1) != 0) {
  211. LOG_ERROR("Failed to update cpu governor policy\n");
  212. }
  213. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  214. }
  215. char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX];
  216. memset(scripts, 0, sizeof(scripts));
  217. config_get_gamemode_end_scripts(self->config, scripts);
  218. long timeout = config_get_script_timeout(self->config);
  219. game_mode_execute_scripts(scripts, (int)timeout);
  220. }
  221. /**
  222. * Automatically expire all dead processes
  223. *
  224. * This has to take special care to ensure thread safety and ensuring that our
  225. * pointer is never cached incorrectly.
  226. */
  227. static void game_mode_context_auto_expire(GameModeContext *self)
  228. {
  229. bool removing = true;
  230. while (removing) {
  231. pthread_rwlock_rdlock(&self->rwlock);
  232. removing = false;
  233. /* Each time we hit an expired game, start the loop back */
  234. for (GameModeClient *client = self->client; client; client = client->next) {
  235. if (kill(client->pid, 0) != 0) {
  236. LOG_MSG("Removing expired game [%i]...\n", client->pid);
  237. pthread_rwlock_unlock(&self->rwlock);
  238. game_mode_context_unregister(self, client->pid, client->pid);
  239. removing = true;
  240. break;
  241. }
  242. }
  243. if (!removing) {
  244. pthread_rwlock_unlock(&self->rwlock);
  245. break;
  246. }
  247. if (game_mode_context_num_clients(self) == 0)
  248. LOG_MSG("Properly cleaned up all expired games.\n");
  249. }
  250. }
  251. /**
  252. * Determine if the client is already known to the context
  253. */
  254. static const GameModeClient *game_mode_context_has_client(GameModeContext *self, pid_t client)
  255. {
  256. const GameModeClient *found = NULL;
  257. pthread_rwlock_rdlock(&self->rwlock);
  258. /* Walk all clients and find a matching pid */
  259. for (GameModeClient *cl = self->client; cl; cl = cl->next) {
  260. if (cl->pid == client) {
  261. found = cl;
  262. break;
  263. }
  264. }
  265. pthread_rwlock_unlock(&self->rwlock);
  266. return found;
  267. }
  268. int game_mode_context_num_clients(GameModeContext *self)
  269. {
  270. return atomic_load(&self->refcount);
  271. }
  272. pid_t *game_mode_context_list_clients(GameModeContext *self, unsigned int *count)
  273. {
  274. pid_t *res = NULL;
  275. unsigned int i = 0;
  276. unsigned int n;
  277. pthread_rwlock_rdlock(&self->rwlock);
  278. n = (unsigned int)atomic_load(&self->refcount);
  279. if (n > 0)
  280. res = (pid_t *)malloc(n * sizeof(pid_t));
  281. for (GameModeClient *cl = self->client; cl; cl = cl->next) {
  282. assert(n > i);
  283. res[i] = cl->pid;
  284. i++;
  285. }
  286. *count = i;
  287. pthread_rwlock_unlock(&self->rwlock);
  288. return res;
  289. }
  290. GameModeClient *game_mode_context_lookup_client(GameModeContext *self, pid_t client)
  291. {
  292. GameModeClient *found = NULL;
  293. pthread_rwlock_rdlock(&self->rwlock);
  294. /* Walk all clients and find a matching pid */
  295. for (GameModeClient *cl = self->client; cl; cl = cl->next) {
  296. if (cl->pid == client) {
  297. found = cl;
  298. break;
  299. }
  300. }
  301. if (found) {
  302. game_mode_client_ref(found);
  303. }
  304. pthread_rwlock_unlock(&self->rwlock);
  305. return found;
  306. }
  307. static int game_mode_apply_client_optimisations(GameModeContext *self, pid_t client)
  308. {
  309. /* Store current renice and apply */
  310. game_mode_apply_renice(self, client, 0 /* expect zero value to start with */);
  311. /* Store current ioprio value and apply */
  312. game_mode_apply_ioprio(self, client, IOPRIO_DEFAULT);
  313. /* Apply scheduler policies */
  314. game_mode_apply_scheduling(self, client);
  315. return 0;
  316. }
  317. int game_mode_context_register(GameModeContext *self, pid_t client, pid_t requester)
  318. {
  319. errno = 0;
  320. /* Construct a new client if we can */
  321. GameModeClient *cl = NULL;
  322. char *executable = NULL;
  323. int err = -1;
  324. /* Check our requester config first */
  325. if (requester != client) {
  326. /* Lookup the executable first */
  327. executable = game_mode_context_find_exe(requester);
  328. if (!executable) {
  329. goto error_cleanup;
  330. }
  331. /* Check our blacklist and whitelist */
  332. if (!config_get_supervisor_whitelisted(self->config, executable)) {
  333. LOG_MSG("Supervisor [%s] was rejected (not in whitelist)\n", executable);
  334. err = -2;
  335. goto error_cleanup;
  336. } else if (config_get_supervisor_blacklisted(self->config, executable)) {
  337. LOG_MSG("Supervisor [%s] was rejected (in blacklist)\n", executable);
  338. err = -2;
  339. goto error_cleanup;
  340. }
  341. /* We're done with the requestor */
  342. free(executable);
  343. executable = NULL;
  344. } else if (config_get_require_supervisor(self->config)) {
  345. LOG_ERROR("Direct request made but require_supervisor was set, rejecting request!\n");
  346. err = -2;
  347. goto error_cleanup;
  348. }
  349. /* Check the PID first to spare a potentially expensive lookup for the exe */
  350. pthread_rwlock_rdlock(&self->rwlock); // ensure our pointer is sane
  351. const GameModeClient *existing = game_mode_context_has_client(self, client);
  352. if (existing) {
  353. LOG_HINTED(ERROR,
  354. "Addition requested for already known client %d [%s].\n",
  355. " -- This may happen due to using exec or shell wrappers. You may want to\n"
  356. " -- blacklist this client so GameMode can see its final name here.\n",
  357. existing->pid,
  358. existing->executable);
  359. pthread_rwlock_unlock(&self->rwlock);
  360. goto error_cleanup;
  361. }
  362. pthread_rwlock_unlock(&self->rwlock);
  363. /* Lookup the executable first */
  364. executable = game_mode_context_find_exe(client);
  365. if (!executable)
  366. goto error_cleanup;
  367. /* Check our blacklist and whitelist */
  368. if (!config_get_client_whitelisted(self->config, executable)) {
  369. LOG_MSG("Client [%s] was rejected (not in whitelist)\n", executable);
  370. goto error_cleanup;
  371. } else if (config_get_client_blacklisted(self->config, executable)) {
  372. LOG_MSG("Client [%s] was rejected (in blacklist)\n", executable);
  373. goto error_cleanup;
  374. }
  375. /* From now on we depend on the client, initialize it */
  376. cl = game_mode_client_new(client, executable);
  377. if (!cl)
  378. goto error_cleanup;
  379. free(executable); /* we're now done with memory */
  380. /* Begin a write lock now to insert our new client at list start */
  381. pthread_rwlock_wrlock(&self->rwlock);
  382. LOG_MSG("Adding game: %d [%s]\n", client, cl->executable);
  383. /* Update the list */
  384. cl->next = self->client;
  385. self->client = cl;
  386. /* First add, init */
  387. if (atomic_fetch_add_explicit(&self->refcount, 1, memory_order_seq_cst) == 0) {
  388. game_mode_context_enter(self);
  389. }
  390. game_mode_apply_client_optimisations(self, client);
  391. /* Unlock now we're done applying optimisations */
  392. pthread_rwlock_unlock(&self->rwlock);
  393. game_mode_client_registered(client);
  394. return 0;
  395. error_cleanup:
  396. if (errno != 0)
  397. LOG_ERROR("Failed to register client [%d]: %s\n", client, strerror(errno));
  398. free(executable);
  399. game_mode_client_unref(cl);
  400. return err;
  401. }
  402. static int game_mode_remove_client_optimisations(GameModeContext *self, pid_t client)
  403. {
  404. /* Restore the ioprio value for the process, expecting it to be the config value */
  405. game_mode_apply_ioprio(self, client, (int)config_get_ioprio_value(self->config));
  406. /* Restore the renice value for the process, expecting it to be our config value */
  407. game_mode_apply_renice(self, client, (int)config_get_renice_value(self->config));
  408. return 0;
  409. }
  410. int game_mode_context_unregister(GameModeContext *self, pid_t client, pid_t requester)
  411. {
  412. GameModeClient *cl = NULL;
  413. GameModeClient *prev = NULL;
  414. bool found = false;
  415. /* Check our requester config first */
  416. if (requester != client) {
  417. /* Lookup the executable first */
  418. char *executable = game_mode_context_find_exe(requester);
  419. if (!executable) {
  420. return -1;
  421. }
  422. /* Check our blacklist and whitelist */
  423. if (!config_get_supervisor_whitelisted(self->config, executable)) {
  424. LOG_MSG("Supervisor [%s] was rejected (not in whitelist)\n", executable);
  425. free(executable);
  426. return -2;
  427. } else if (config_get_supervisor_blacklisted(self->config, executable)) {
  428. LOG_MSG("Supervisor [%s] was rejected (in blacklist)\n", executable);
  429. free(executable);
  430. return -2;
  431. }
  432. free(executable);
  433. } else if (config_get_require_supervisor(self->config)) {
  434. LOG_ERROR("Direct request made but require_supervisor was set, rejecting request!\n");
  435. return -2;
  436. }
  437. /* Requires locking. */
  438. pthread_rwlock_wrlock(&self->rwlock);
  439. for (prev = cl = self->client; cl; cl = cl->next) {
  440. if (cl->pid != client) {
  441. prev = cl;
  442. continue;
  443. }
  444. LOG_MSG("Removing game: %d [%s]\n", client, cl->executable);
  445. /* Found it */
  446. found = true;
  447. prev->next = cl->next;
  448. if (cl == self->client) {
  449. self->client = cl->next;
  450. }
  451. cl->next = NULL;
  452. game_mode_client_unref(cl);
  453. break;
  454. }
  455. if (!found) {
  456. LOG_HINTED(
  457. ERROR,
  458. "Removal requested for unknown process [%d].\n",
  459. " -- The parent process probably forked and tries to unregister from the wrong\n"
  460. " -- process now. We cannot work around this. This message will likely be paired\n"
  461. " -- with a nearby 'Removing expired game' which means we cleaned up properly\n"
  462. " -- (we will log this event). This hint will be displayed only once.\n",
  463. client);
  464. pthread_rwlock_unlock(&self->rwlock);
  465. return -1;
  466. }
  467. /* When we hit bottom then end the game mode */
  468. if (atomic_fetch_sub_explicit(&self->refcount, 1, memory_order_seq_cst) == 1) {
  469. game_mode_context_leave(self);
  470. }
  471. game_mode_remove_client_optimisations(self, client);
  472. /* Unlock now we're done applying optimisations */
  473. pthread_rwlock_unlock(&self->rwlock);
  474. game_mode_client_unregistered(client);
  475. return 0;
  476. }
  477. int game_mode_context_query_status(GameModeContext *self, pid_t client, pid_t requester)
  478. {
  479. GameModeClient *cl = NULL;
  480. int ret = 0;
  481. /* First check the requester settings if appropriate */
  482. if (client != requester) {
  483. char *executable = game_mode_context_find_exe(requester);
  484. if (!executable) {
  485. return -1;
  486. }
  487. /* Check our blacklist and whitelist */
  488. if (!config_get_supervisor_whitelisted(self->config, executable)) {
  489. LOG_MSG("Supervisor [%s] was rejected (not in whitelist)\n", executable);
  490. free(executable);
  491. return -2;
  492. } else if (config_get_supervisor_blacklisted(self->config, executable)) {
  493. LOG_MSG("Supervisor [%s] was rejected (in blacklist)\n", executable);
  494. free(executable);
  495. return -2;
  496. }
  497. free(executable);
  498. }
  499. /*
  500. * Check the current refcount on gamemode, this equates to whether gamemode is active or not,
  501. * see game_mode_context_register and game_mode_context_unregister
  502. */
  503. if (atomic_load_explicit(&self->refcount, memory_order_seq_cst)) {
  504. ret++;
  505. /* Check if the current client is registered */
  506. /* Requires locking. */
  507. pthread_rwlock_rdlock(&self->rwlock);
  508. for (cl = self->client; cl; cl = cl->next) {
  509. if (cl->pid != client) {
  510. continue;
  511. }
  512. /* Found it */
  513. ret++;
  514. break;
  515. }
  516. /* Unlock here, potentially yielding */
  517. pthread_rwlock_unlock(&self->rwlock);
  518. }
  519. return ret;
  520. }
  521. /**
  522. * Construct a new GameModeClient for the given process ID
  523. *
  524. * This is deliberately OOM safe
  525. */
  526. static GameModeClient *game_mode_client_new(pid_t pid, char *executable)
  527. {
  528. /* This bit seems to be formatted differently by different clang-format versions */
  529. /* clang-format off */
  530. GameModeClient c = {
  531. .next = NULL,
  532. .pid = pid,
  533. };
  534. /* clang-format on */
  535. GameModeClient *ret = NULL;
  536. ret = calloc(1, sizeof(struct GameModeClient));
  537. if (!ret) {
  538. return NULL;
  539. }
  540. *ret = c;
  541. ret->refcount = ATOMIC_VAR_INIT(1);
  542. strncpy(ret->executable, executable, PATH_MAX - 1);
  543. return ret;
  544. }
  545. /**
  546. * Unref a client and the next element in the list, if non-null.
  547. */
  548. void game_mode_client_unref(GameModeClient *client)
  549. {
  550. if (!client) {
  551. return;
  552. }
  553. if (atomic_fetch_sub_explicit(&client->refcount, 1, memory_order_seq_cst) > 1) {
  554. return; /* object is still alive */
  555. }
  556. if (client->next) {
  557. game_mode_client_unref(client->next);
  558. }
  559. free(client);
  560. }
  561. void game_mode_client_ref(GameModeClient *client)
  562. {
  563. if (!client) {
  564. return;
  565. }
  566. atomic_fetch_add_explicit(&client->refcount, 1, memory_order_seq_cst);
  567. }
  568. /**
  569. * The process identifier of the client.
  570. */
  571. pid_t game_mode_client_get_pid(GameModeClient *client)
  572. {
  573. assert(client != NULL);
  574. return client->pid;
  575. }
  576. /**
  577. * The path to the executable of client.
  578. */
  579. const char *game_mode_client_get_executable(GameModeClient *client)
  580. {
  581. assert(client != NULL);
  582. return client->executable;
  583. }
  584. /* Internal refresh config function (assumes no contention with reaper thread) */
  585. static void game_mode_reload_config_internal(GameModeContext *self)
  586. {
  587. LOG_MSG("Reloading config...\n");
  588. /* Make sure we have a readwrite lock on ourselves */
  589. pthread_rwlock_wrlock(&self->rwlock);
  590. /* Remove current optimisations when we're already active */
  591. if (game_mode_context_num_clients(self)) {
  592. for (GameModeClient *cl = self->client; cl; cl = cl->next)
  593. game_mode_remove_client_optimisations(self, cl->pid);
  594. game_mode_context_leave(self);
  595. }
  596. /* Reload the config */
  597. config_reload(self->config);
  598. /* Re-apply all current optimisations */
  599. if (game_mode_context_num_clients(self)) {
  600. /* Start the global context back up */
  601. game_mode_context_enter(self);
  602. for (GameModeClient *cl = self->client; cl; cl = cl->next)
  603. game_mode_apply_client_optimisations(self, cl->pid);
  604. }
  605. pthread_rwlock_unlock(&self->rwlock);
  606. LOG_MSG("Config reload complete\n");
  607. }
  608. /**
  609. * We continuously run until told otherwise.
  610. */
  611. static void *game_mode_context_reaper(void *userdata)
  612. {
  613. /* Stack, not allocated, won't disappear. */
  614. GameModeContext *self = userdata;
  615. long reaper_interval = config_get_reaper_frequency(self->config);
  616. struct timespec ts = { 0, 0 };
  617. ts.tv_sec = time(NULL) + reaper_interval;
  618. while (self->reaper.running) {
  619. /* Wait for condition */
  620. pthread_mutex_lock(&self->reaper.mutex);
  621. pthread_cond_timedwait(&self->reaper.condition, &self->reaper.mutex, &ts);
  622. pthread_mutex_unlock(&self->reaper.mutex);
  623. /* Highly possible the main thread woke us up to exit */
  624. if (!self->reaper.running) {
  625. return NULL;
  626. }
  627. /* Expire remaining entries */
  628. game_mode_context_auto_expire(self);
  629. /* Check if we should be reloading the config, and do so if needed */
  630. if (config_needs_reload(self->config)) {
  631. LOG_MSG("Detected config file changes\n");
  632. game_mode_reload_config_internal(self);
  633. }
  634. ts.tv_sec = time(NULL) + reaper_interval;
  635. }
  636. return NULL;
  637. }
  638. GameModeContext *game_mode_context_instance(void)
  639. {
  640. return &instance;
  641. }
  642. GameModeConfig *game_mode_config_from_context(const GameModeContext *context)
  643. {
  644. return context ? context->config : NULL;
  645. }
  646. /**
  647. * Attempt to locate the exe for the process.
  648. * We might run into issues if the process is running under an odd umask.
  649. */
  650. static char *game_mode_context_find_exe(pid_t pid)
  651. {
  652. char buffer[PATH_MAX];
  653. char *proc_path = NULL, *wine_exe = NULL;
  654. autoclose_fd int pidfd = -1;
  655. ssize_t r;
  656. if (!(proc_path = buffered_snprintf(buffer, "/proc/%d", pid)))
  657. goto fail;
  658. /* Translate /proc/<pid>/exe to the application binary */
  659. pidfd = openat(AT_FDCWD, proc_path, O_RDONLY | O_NONBLOCK | O_DIRECTORY | O_CLOEXEC | O_NOCTTY);
  660. if (pidfd == -1)
  661. goto fail;
  662. r = readlinkat(pidfd, "exe", buffer, sizeof(buffer));
  663. if (r == sizeof(buffer)) {
  664. errno = ENAMETOOLONG;
  665. r = -1;
  666. }
  667. if (r == -1)
  668. goto fail;
  669. buffer[r] = '\0';
  670. char *exe = strdup(buffer);
  671. /* Resolve for wine if appropriate */
  672. if ((wine_exe = game_mode_resolve_wine_preloader(exe, pid))) {
  673. free(exe);
  674. exe = wine_exe;
  675. }
  676. return exe;
  677. fail:
  678. if (errno != 0) // otherwise a proper message was logged before
  679. LOG_ERROR("Unable to find executable for PID %d: %s\n", pid, strerror(errno));
  680. return NULL;
  681. }
  682. /* Executes a set of scripts */
  683. static void game_mode_execute_scripts(char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX], int timeout)
  684. {
  685. unsigned int i = 0;
  686. while (*scripts[i] != '\0' && i < CONFIG_LIST_MAX) {
  687. LOG_MSG("Executing script [%s]\n", scripts[i]);
  688. int err;
  689. const char *args[] = { "/bin/sh", "-c", scripts[i], NULL };
  690. if ((err = run_external_process(args, NULL, timeout)) != 0) {
  691. /* Log the failure, but this is not fatal */
  692. LOG_ERROR("Script [%s] failed with error %d\n", scripts[i], err);
  693. }
  694. i++;
  695. }
  696. }
  697. /*
  698. * Reload the current configuration
  699. *
  700. * Reloading the configuration completely live would be problematic for various optimisation values,
  701. * to ensure we have a fully clean state, we tear down the whole gamemode state and regrow it with a
  702. * new config, remembering the registered games
  703. */
  704. int game_mode_reload_config(GameModeContext *self)
  705. {
  706. /* Stop the reaper thread first */
  707. end_reaper_thread(self);
  708. game_mode_reload_config_internal(self);
  709. /* Restart the reaper thread back up again */
  710. start_reaper_thread(self);
  711. return 0;
  712. }