1
0

gamemode.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  1. /*
  2. Copyright (c) 2017-2018, Feral Interactive
  3. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. * Redistributions of source code must retain the above copyright notice,
  7. this list of conditions and the following disclaimer.
  8. * Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in the
  10. documentation and/or other materials provided with the distribution.
  11. * Neither the name of Feral Interactive nor the names of its contributors
  12. may be used to endorse or promote products derived from this software
  13. without specific prior written permission.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  15. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  17. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  18. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  19. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  20. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  21. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  22. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  23. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  24. POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #define _GNU_SOURCE
  27. #include "gamemode.h"
  28. #include "daemon_config.h"
  29. #include "governors-query.h"
  30. #include "governors.h"
  31. #include "logging.h"
  32. #include <linux/limits.h>
  33. #include <linux/sched.h>
  34. #include <pthread.h>
  35. #include <sched.h>
  36. #include <signal.h>
  37. #include <stdatomic.h>
  38. #include <string.h>
  39. #include <sys/resource.h>
  40. #include <sys/sysinfo.h>
  41. #include <systemd/sd-daemon.h>
  42. /* SCHED_ISO may not be defined as it is a reserved value not yet
  43. * implemented in official kernel sources, see linux/sched.h.
  44. */
  45. #ifndef SCHED_ISO
  46. #define SCHED_ISO 4
  47. #endif
  48. /* Priority to renice the process to.
  49. */
  50. #define NICE_DEFAULT_PRIORITY -4
  51. /**
  52. * The GameModeClient encapsulates the remote connection, providing a list
  53. * form to contain the pid and credentials.
  54. */
  55. typedef struct GameModeClient {
  56. pid_t pid; /**< Process ID */
  57. struct GameModeClient *next; /**<Next client in the list */
  58. char *executable; /**<Process executable */
  59. } GameModeClient;
  60. struct GameModeContext {
  61. pthread_rwlock_t rwlock; /**<Guard access to the client list */
  62. _Atomic int refcount; /**<Allow cycling the game mode */
  63. GameModeClient *client; /**<Pointer to first client */
  64. GameModeConfig *config; /**<Pointer to config object */
  65. char initial_cpu_mode[64]; /**<Only updates when we can */
  66. /* Reaper control */
  67. struct {
  68. pthread_t thread;
  69. bool running;
  70. pthread_mutex_t mutex;
  71. pthread_cond_t condition;
  72. } reaper;
  73. };
  74. static GameModeContext instance = { 0 };
  75. /* Maximum number of concurrent processes we'll sanely support */
  76. #define MAX_GAMES 256
  77. /**
  78. * Protect against signals
  79. */
  80. static volatile bool had_context_init = false;
  81. static GameModeClient *game_mode_client_new(pid_t pid);
  82. static void game_mode_client_free(GameModeClient *client);
  83. static bool game_mode_context_has_client(GameModeContext *self, pid_t client);
  84. static int game_mode_context_num_clients(GameModeContext *self);
  85. static void *game_mode_context_reaper(void *userdata);
  86. static void game_mode_context_enter(GameModeContext *self);
  87. static void game_mode_context_leave(GameModeContext *self);
  88. static char *game_mode_context_find_exe(pid_t pid);
  89. void game_mode_context_init(GameModeContext *self)
  90. {
  91. if (had_context_init) {
  92. LOG_ERROR("Context already initialised\n");
  93. return;
  94. }
  95. had_context_init = true;
  96. self->refcount = ATOMIC_VAR_INIT(0);
  97. /* clear the initial string */
  98. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  99. /* Initialise the config */
  100. self->config = config_create();
  101. config_init(self->config);
  102. pthread_rwlock_init(&self->rwlock, NULL);
  103. pthread_mutex_init(&self->reaper.mutex, NULL);
  104. pthread_cond_init(&self->reaper.condition, NULL);
  105. /* Get the reaper thread going */
  106. self->reaper.running = true;
  107. if (pthread_create(&self->reaper.thread, NULL, game_mode_context_reaper, self) != 0) {
  108. FATAL_ERROR("Couldn't construct a new thread");
  109. }
  110. }
  111. void game_mode_context_destroy(GameModeContext *self)
  112. {
  113. if (!had_context_init) {
  114. return;
  115. }
  116. /* Leave game mode now */
  117. if (game_mode_context_num_clients(self) > 0) {
  118. game_mode_context_leave(self);
  119. }
  120. had_context_init = false;
  121. game_mode_client_free(self->client);
  122. self->reaper.running = false;
  123. /* We might be stuck waiting, so wake it up again */
  124. pthread_mutex_lock(&self->reaper.mutex);
  125. pthread_cond_signal(&self->reaper.condition);
  126. pthread_mutex_unlock(&self->reaper.mutex);
  127. /* Join the thread as soon as possible */
  128. pthread_join(self->reaper.thread, NULL);
  129. pthread_cond_destroy(&self->reaper.condition);
  130. pthread_mutex_destroy(&self->reaper.mutex);
  131. /* Destroy the config object */
  132. config_destroy(self->config);
  133. pthread_rwlock_destroy(&self->rwlock);
  134. }
  135. /**
  136. * Apply scheduling policies
  137. *
  138. * This tries to change the scheduler of the client to soft realtime mode
  139. * available in some kernels as SCHED_ISO. It also tries to adjust the nice
  140. * level. If some of each fail, ignore this and log a warning.
  141. *
  142. * We don't need to store the current values because when the client exits,
  143. * everything will be good: Scheduling is only applied to the client and
  144. * its children.
  145. */
  146. static void game_mode_apply_scheduler(GameModeContext *self, pid_t client)
  147. {
  148. LOG_MSG("Setting scheduling policies...\n");
  149. /*
  150. * read configuration "renice" (1..20)
  151. */
  152. long int renice = 0;
  153. config_get_renice_value(self->config, &renice);
  154. if ((renice < 1) || (renice > 20)) {
  155. LOG_ERROR("Renice value [%ld] defaulted to [%d].\n", renice, -NICE_DEFAULT_PRIORITY);
  156. renice = NICE_DEFAULT_PRIORITY;
  157. } else {
  158. renice = -renice;
  159. }
  160. /*
  161. * don't adjust priority if it was already adjusted
  162. */
  163. if (getpriority(PRIO_PROCESS, (id_t)client) != 0) {
  164. LOG_ERROR("Client [%d] already reniced, ignoring.\n", client);
  165. } else if (setpriority(PRIO_PROCESS, (id_t)client, (int)renice)) {
  166. LOG_ERROR(
  167. "Renicing client [%d] failed with error %d, ignoring (your user may not have "
  168. "permission to do this).\n",
  169. client,
  170. errno);
  171. }
  172. /*
  173. * read configuration "softrealtime" (on, off, auto)
  174. */
  175. char softrealtime[CONFIG_VALUE_MAX] = { 0 };
  176. config_get_soft_realtime(self->config, softrealtime);
  177. /*
  178. * Enable unconditionally or auto-detect soft realtime usage,
  179. * auto detection is based on observations where dual-core CPU suffered
  180. * priority inversion problems with the graphics driver thus running
  181. * slower as a result, so enable only with more than 3 cores.
  182. */
  183. bool enable_softrealtime = (strcmp(softrealtime, "on") == 0) || (get_nprocs() > 3);
  184. /*
  185. * Actually apply the scheduler policy if not explicitly turned off
  186. */
  187. if (!(strcmp(softrealtime, "off") == 0) && (enable_softrealtime)) {
  188. const struct sched_param p = { .sched_priority = 0 };
  189. if (sched_setscheduler(client, SCHED_ISO, &p)) {
  190. LOG_ERROR(
  191. "Setting client [%d] to SCHED_ISO failed with error %d, ignoring (your "
  192. "kernel may not support this).\n",
  193. client,
  194. errno);
  195. }
  196. } else {
  197. LOG_ERROR("Not using softrealtime, setting is '%s'.\n", softrealtime);
  198. }
  199. }
  200. /**
  201. * Pivot into game mode.
  202. *
  203. * This is only possible after game_mode_context_init has made a GameModeContext
  204. * usable, and should always be followed by a game_mode_context_leave.
  205. */
  206. static void game_mode_context_enter(GameModeContext *self)
  207. {
  208. LOG_MSG("Entering Game Mode...\n");
  209. sd_notifyf(0, "STATUS=%sGameMode is now active.%s\n", "\x1B[1;32m", "\x1B[0m");
  210. char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX];
  211. memset(scripts, 0, sizeof(scripts));
  212. config_get_gamemode_start_scripts(self->config, scripts);
  213. unsigned int i = 0;
  214. while (*scripts[i] != '\0' && i < CONFIG_LIST_MAX) {
  215. LOG_MSG("Executing script [%s]\n", scripts[i]);
  216. int err;
  217. if ((err = system(scripts[i])) != 0) {
  218. /* Log the failure, but this is not fatal */
  219. LOG_ERROR("Script [%s] failed with error %d\n", scripts[i], err);
  220. }
  221. i++;
  222. }
  223. /* Read the initial governor state so we can revert it correctly */
  224. const char *initial_state = get_gov_state();
  225. if (initial_state) {
  226. /* store the initial cpu governor mode */
  227. strncpy(self->initial_cpu_mode, initial_state, sizeof(self->initial_cpu_mode) - 1);
  228. self->initial_cpu_mode[sizeof(self->initial_cpu_mode) - 1] = '\0';
  229. LOG_MSG("governor was initially set to [%s]\n", initial_state);
  230. /* Choose the desired governor */
  231. char desired[CONFIG_VALUE_MAX] = { 0 };
  232. config_get_desired_governor(self->config, desired);
  233. const char *desiredGov = desired[0] != '\0' ? desired : "performance";
  234. /* set the governor to performance */
  235. if (!set_governors(desiredGov)) {
  236. /* if the set fails, clear the initial mode so we don't try and reset it back and fail
  237. * again, presumably */
  238. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  239. }
  240. }
  241. }
  242. /**
  243. * Pivot out of game mode.
  244. *
  245. * Should only be called after both init and game_mode_context_enter have
  246. * been performed.
  247. */
  248. static void game_mode_context_leave(GameModeContext *self)
  249. {
  250. LOG_MSG("Leaving Game Mode...\n");
  251. sd_notifyf(0, "STATUS=%sGameMode is currently deactivated.%s\n", "\x1B[1;36m", "\x1B[0m");
  252. /* Reset the governer state back to initial */
  253. if (self->initial_cpu_mode[0] != '\0') {
  254. /* Choose the governor to reset to, using the config to override */
  255. char defaultgov[CONFIG_VALUE_MAX] = { 0 };
  256. config_get_default_governor(self->config, defaultgov);
  257. const char *gov_mode = defaultgov[0] != '\0' ? defaultgov : self->initial_cpu_mode;
  258. set_governors(gov_mode);
  259. memset(self->initial_cpu_mode, 0, sizeof(self->initial_cpu_mode));
  260. }
  261. char scripts[CONFIG_LIST_MAX][CONFIG_VALUE_MAX];
  262. memset(scripts, 0, sizeof(scripts));
  263. config_get_gamemode_end_scripts(self->config, scripts);
  264. unsigned int i = 0;
  265. while (*scripts[i] != '\0' && i < CONFIG_LIST_MAX) {
  266. LOG_MSG("Executing script [%s]\n", scripts[i]);
  267. int err;
  268. if ((err = system(scripts[i])) != 0) {
  269. /* Log the failure, but this is not fatal */
  270. LOG_ERROR("Script [%s] failed with error %d\n", scripts[i], err);
  271. }
  272. i++;
  273. }
  274. }
  275. /**
  276. * Automatically expire all dead processes
  277. *
  278. * This has to take special care to ensure thread safety and ensuring that our
  279. * pointer is never cached incorrectly.
  280. */
  281. static void game_mode_context_auto_expire(GameModeContext *self)
  282. {
  283. bool removing = true;
  284. while (removing) {
  285. pthread_rwlock_rdlock(&self->rwlock);
  286. removing = false;
  287. /* Each time we hit an expired game, start the loop back */
  288. for (GameModeClient *client = self->client; client; client = client->next) {
  289. if (kill(client->pid, 0) != 0) {
  290. LOG_MSG("Removing expired game [%i]...\n", client->pid);
  291. pthread_rwlock_unlock(&self->rwlock);
  292. game_mode_context_unregister(self, client->pid);
  293. removing = true;
  294. break;
  295. }
  296. }
  297. if (!removing) {
  298. pthread_rwlock_unlock(&self->rwlock);
  299. break;
  300. }
  301. }
  302. }
  303. /**
  304. * Determine if the client is already known to the context
  305. */
  306. static bool game_mode_context_has_client(GameModeContext *self, pid_t client)
  307. {
  308. bool found = false;
  309. pthread_rwlock_rdlock(&self->rwlock);
  310. /* Walk all clients and find a matching pid */
  311. for (GameModeClient *cl = self->client; cl; cl = cl->next) {
  312. if (cl->pid == client) {
  313. found = true;
  314. break;
  315. }
  316. }
  317. pthread_rwlock_unlock(&self->rwlock);
  318. return found;
  319. }
  320. /**
  321. * Helper to grab the current number of clients we know about
  322. */
  323. static int game_mode_context_num_clients(GameModeContext *self)
  324. {
  325. return atomic_load(&self->refcount);
  326. }
  327. bool game_mode_context_register(GameModeContext *self, pid_t client)
  328. {
  329. /* Construct a new client if we can */
  330. GameModeClient *cl = NULL;
  331. /* Cap the total number of active clients */
  332. if (game_mode_context_num_clients(self) + 1 > MAX_GAMES) {
  333. LOG_ERROR("Max games (%d) reached, not registering %d\n", MAX_GAMES, client);
  334. return false;
  335. }
  336. cl = game_mode_client_new(client);
  337. if (!cl) {
  338. fputs("OOM\n", stderr);
  339. return false;
  340. }
  341. cl->executable = game_mode_context_find_exe(client);
  342. if (game_mode_context_has_client(self, client)) {
  343. LOG_ERROR("Addition requested for already known process [%d]\n", client);
  344. goto error_cleanup;
  345. }
  346. /* Check our blacklist and whitelist */
  347. if (!config_get_client_whitelisted(self->config, cl->executable)) {
  348. LOG_MSG("Client [%s] was rejected (not in whitelist)\n", cl->executable);
  349. goto error_cleanup;
  350. } else if (config_get_client_blacklisted(self->config, cl->executable)) {
  351. LOG_MSG("Client [%s] was rejected (in blacklist)\n", cl->executable);
  352. goto error_cleanup;
  353. }
  354. /* Begin a write lock now to insert our new client at list start */
  355. pthread_rwlock_wrlock(&self->rwlock);
  356. LOG_MSG("Adding game: %d [%s]\n", client, cl->executable);
  357. /* Update the list */
  358. cl->next = self->client;
  359. self->client = cl;
  360. pthread_rwlock_unlock(&self->rwlock);
  361. /* First add, init */
  362. if (atomic_fetch_add_explicit(&self->refcount, 1, memory_order_seq_cst) == 0) {
  363. game_mode_context_enter(self);
  364. }
  365. /* Apply scheduler policies */
  366. game_mode_apply_scheduler(self, client);
  367. return true;
  368. error_cleanup:
  369. game_mode_client_free(cl);
  370. return false;
  371. }
  372. bool game_mode_context_unregister(GameModeContext *self, pid_t client)
  373. {
  374. GameModeClient *cl = NULL;
  375. GameModeClient *prev = NULL;
  376. bool found = false;
  377. /* Requires locking. */
  378. pthread_rwlock_wrlock(&self->rwlock);
  379. for (prev = cl = self->client; cl; cl = cl->next) {
  380. if (cl->pid != client) {
  381. prev = cl;
  382. continue;
  383. }
  384. LOG_MSG("Removing game: %d [%s]\n", client, cl->executable);
  385. /* Found it */
  386. found = true;
  387. prev->next = cl->next;
  388. if (cl == self->client) {
  389. self->client = cl->next;
  390. }
  391. cl->next = NULL;
  392. game_mode_client_free(cl);
  393. break;
  394. }
  395. /* Unlock here, potentially yielding */
  396. pthread_rwlock_unlock(&self->rwlock);
  397. if (!found) {
  398. LOG_ERROR("Removal requested for unknown process [%d]\n", client);
  399. return false;
  400. }
  401. /* When we hit bottom then end the game mode */
  402. if (atomic_fetch_sub_explicit(&self->refcount, 1, memory_order_seq_cst) == 1) {
  403. game_mode_context_leave(self);
  404. }
  405. return true;
  406. }
  407. int game_mode_context_query_status(GameModeContext *self, pid_t client)
  408. {
  409. GameModeClient *cl = NULL;
  410. int ret = 0;
  411. /*
  412. * Check the current refcount on gamemode, this equates to whether gamemode is active or not,
  413. * see game_mode_context_register and game_mode_context_unregister
  414. */
  415. if (atomic_load_explicit(&self->refcount, memory_order_seq_cst)) {
  416. ret++;
  417. /* Check if the current client is registered */
  418. /* Requires locking. */
  419. pthread_rwlock_rdlock(&self->rwlock);
  420. for (cl = self->client; cl; cl = cl->next) {
  421. if (cl->pid != client) {
  422. continue;
  423. }
  424. /* Found it */
  425. ret++;
  426. break;
  427. }
  428. /* Unlock here, potentially yielding */
  429. pthread_rwlock_unlock(&self->rwlock);
  430. }
  431. return ret;
  432. }
  433. /**
  434. * Construct a new GameModeClient for the given process ID
  435. *
  436. * This is deliberately OOM safe
  437. */
  438. static GameModeClient *game_mode_client_new(pid_t pid)
  439. {
  440. GameModeClient c = {
  441. .next = NULL,
  442. .pid = pid,
  443. };
  444. GameModeClient *ret = NULL;
  445. ret = calloc(1, sizeof(struct GameModeClient));
  446. if (!ret) {
  447. return NULL;
  448. }
  449. *ret = c;
  450. return ret;
  451. }
  452. /**
  453. * Free a client and the next element in the list.
  454. */
  455. static void game_mode_client_free(GameModeClient *client)
  456. {
  457. if (!client) {
  458. return;
  459. }
  460. if (client->next) {
  461. game_mode_client_free(client->next);
  462. }
  463. if (client->executable) {
  464. free(client->executable);
  465. }
  466. free(client);
  467. }
  468. /**
  469. * We continuously run until told otherwise.
  470. */
  471. static void *game_mode_context_reaper(void *userdata)
  472. {
  473. /* Stack, not allocated, won't disappear. */
  474. GameModeContext *self = userdata;
  475. long reaper_interval = 0.0f;
  476. config_get_reaper_thread_frequency(self->config, &reaper_interval);
  477. struct timespec ts = { 0, 0 };
  478. ts.tv_sec = time(NULL) + reaper_interval;
  479. while (self->reaper.running) {
  480. /* Wait for condition */
  481. pthread_mutex_lock(&self->reaper.mutex);
  482. pthread_cond_timedwait(&self->reaper.condition, &self->reaper.mutex, &ts);
  483. pthread_mutex_unlock(&self->reaper.mutex);
  484. /* Highly possible the main thread woke us up to exit */
  485. if (!self->reaper.running) {
  486. return NULL;
  487. }
  488. /* Expire remaining entries */
  489. game_mode_context_auto_expire(self);
  490. ts.tv_sec = time(NULL) + reaper_interval;
  491. }
  492. return NULL;
  493. }
  494. GameModeContext *game_mode_context_instance()
  495. {
  496. return &instance;
  497. }
  498. /**
  499. * Attempt to locate the exe for the process.
  500. * We might run into issues if the process is running under an odd umask.
  501. */
  502. static char *game_mode_context_find_exe(pid_t pid)
  503. {
  504. static char proc_path[PATH_MAX] = { 0 };
  505. if (snprintf(proc_path, sizeof(proc_path), "/proc/%d/exe", pid) < 0) {
  506. LOG_ERROR("Unable to find executable for PID %d: %s\n", pid, strerror(errno));
  507. return NULL;
  508. }
  509. /* Allocate the realpath if possible */
  510. return realpath(proc_path, NULL);
  511. }