gamemode.c 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. /*
  2. Copyright (c) 2017, 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 "governors.h"
  29. #include "logging.h"
  30. #include <linux/limits.h>
  31. #include <pthread.h>
  32. #include <signal.h>
  33. #include <stdatomic.h>
  34. #include <string.h>
  35. /**
  36. * The GameModeClient encapsulates the remote connection, providing a list
  37. * form to contain the pid and credentials.
  38. */
  39. typedef struct GameModeClient {
  40. pid_t pid; /**< Process ID */
  41. struct GameModeClient *next; /**<Next client in the list */
  42. char *executable; /**<Process executable */
  43. } GameModeClient;
  44. struct GameModeContext {
  45. pthread_rwlock_t rwlock; /**<Guard access to the client list */
  46. _Atomic int refcount; /**<Allow cycling the game mode */
  47. GameModeClient *client; /**<Pointer to first client */
  48. bool performance_mode; /**<Only updates when we can */
  49. /* Reaper control */
  50. struct {
  51. pthread_t thread;
  52. bool running;
  53. pthread_mutex_t mutex;
  54. pthread_cond_t condition;
  55. } reaper;
  56. };
  57. static GameModeContext instance = { 0 };
  58. /* Maximum number of concurrent processes we'll sanely support */
  59. #define MAX_GAMES 256
  60. /* How often our reaper thread will run */
  61. #define SLEEP_INTERVAL 5
  62. /**
  63. * Protect against signals
  64. */
  65. static volatile bool had_context_init = false;
  66. static GameModeClient *game_mode_client_new(pid_t pid);
  67. static void game_mode_client_free(GameModeClient *client);
  68. static bool game_mode_context_has_client(GameModeContext *self, pid_t client);
  69. static int game_mode_context_num_clients(GameModeContext *self);
  70. static void *game_mode_context_reaper(void *userdata);
  71. static void game_mode_context_enter(GameModeContext *self);
  72. static void game_mode_context_leave(GameModeContext *self);
  73. static char *game_mode_context_find_exe(pid_t pid);
  74. void game_mode_context_init(GameModeContext *self)
  75. {
  76. if (had_context_init) {
  77. LOG_ERROR("Context already initialised\n");
  78. return;
  79. }
  80. had_context_init = true;
  81. self->refcount = ATOMIC_VAR_INIT(0);
  82. /* Read current governer state before setting up any message handling */
  83. update_initial_gov_state();
  84. LOG_MSG("governor is set to [%s]\n", get_initial_governor());
  85. pthread_mutex_init(&self->reaper.mutex, NULL);
  86. pthread_cond_init(&self->reaper.condition, NULL);
  87. /* Get the reaper thread going */
  88. self->reaper.running = true;
  89. if (pthread_create(&self->reaper.thread, NULL, game_mode_context_reaper, self) != 0) {
  90. FATAL_ERROR("Couldn't construct a new thread");
  91. }
  92. }
  93. void game_mode_context_destroy(GameModeContext *self)
  94. {
  95. if (!had_context_init) {
  96. return;
  97. }
  98. /* Leave game mode now */
  99. if (game_mode_context_num_clients(self) > 0) {
  100. game_mode_context_leave(self);
  101. }
  102. had_context_init = false;
  103. game_mode_client_free(self->client);
  104. self->reaper.running = false;
  105. /* We might be stuck waiting, so wake it up again */
  106. pthread_mutex_lock(&self->reaper.mutex);
  107. pthread_cond_signal(&self->reaper.condition);
  108. pthread_mutex_unlock(&self->reaper.mutex);
  109. /* Join the thread as soon as possible */
  110. pthread_join(self->reaper.thread, NULL);
  111. pthread_cond_destroy(&self->reaper.condition);
  112. pthread_mutex_destroy(&self->reaper.mutex);
  113. pthread_rwlock_destroy(&self->rwlock);
  114. }
  115. /**
  116. * Pivot into game mode.
  117. *
  118. * This is only possible after game_mode_context_init has made a GameModeContext
  119. * usable, and should always be followed by a game_mode_context_leave.
  120. */
  121. static void game_mode_context_enter(GameModeContext *self)
  122. {
  123. LOG_MSG("Entering Game Mode...\n");
  124. if (!self->performance_mode && set_governors("performance")) {
  125. self->performance_mode = true;
  126. }
  127. }
  128. /**
  129. * Pivot out of game mode.
  130. *
  131. * Should only be called after both init and game_mode_context_enter have
  132. * been performed.
  133. */
  134. static void game_mode_context_leave(GameModeContext *self)
  135. {
  136. LOG_MSG("Leaving Game Mode...\n");
  137. if (self->performance_mode && set_governors(NULL)) {
  138. self->performance_mode = false;
  139. }
  140. }
  141. /**
  142. * Automatically expire all dead processes
  143. *
  144. * This has to take special care to ensure thread safety and ensuring that our
  145. * pointer is never cached incorrectly.
  146. */
  147. static void game_mode_context_auto_expire(GameModeContext *self)
  148. {
  149. bool removing = true;
  150. while (removing) {
  151. pthread_rwlock_rdlock(&self->rwlock);
  152. removing = false;
  153. /* Each time we hit an expired game, start the loop back */
  154. for (GameModeClient *client = self->client; client; client = client->next) {
  155. if (kill(client->pid, 0) != 0) {
  156. LOG_MSG("Removing expired game [%i]...\n", client->pid);
  157. pthread_rwlock_unlock(&self->rwlock);
  158. game_mode_context_unregister(self, client->pid);
  159. removing = true;
  160. break;
  161. }
  162. }
  163. if (!removing) {
  164. pthread_rwlock_unlock(&self->rwlock);
  165. break;
  166. }
  167. }
  168. }
  169. /**
  170. * Determine if the client is already known to the context
  171. */
  172. static bool game_mode_context_has_client(GameModeContext *self, pid_t client)
  173. {
  174. bool found = false;
  175. pthread_rwlock_rdlock(&self->rwlock);
  176. /* Walk all clients and find a matching pid */
  177. for (GameModeClient *cl = self->client; cl; cl = cl->next) {
  178. if (cl->pid == client) {
  179. found = true;
  180. break;
  181. }
  182. }
  183. pthread_rwlock_unlock(&self->rwlock);
  184. return found;
  185. }
  186. /**
  187. * Helper to grab the current number of clients we know about
  188. */
  189. static int game_mode_context_num_clients(GameModeContext *self)
  190. {
  191. return atomic_load(&self->refcount);
  192. }
  193. bool game_mode_context_register(GameModeContext *self, pid_t client)
  194. {
  195. /* Construct a new client if we can */
  196. GameModeClient *cl = NULL;
  197. cl = game_mode_client_new(client);
  198. if (!cl) {
  199. fputs("OOM\n", stderr);
  200. return false;
  201. }
  202. cl->executable = game_mode_context_find_exe(client);
  203. if (game_mode_context_has_client(self, client)) {
  204. LOG_ERROR("Addition requested for already known process [%d]\n", client);
  205. return false;
  206. }
  207. /* Cap the total number of active clients */
  208. if (game_mode_context_num_clients(self) + 1 > MAX_GAMES) {
  209. LOG_ERROR("Max games (%d) reached, not registering %d\n", MAX_GAMES, client);
  210. return false;
  211. }
  212. /* Begin a write lock now to insert our new client at list start */
  213. pthread_rwlock_wrlock(&self->rwlock);
  214. LOG_MSG("Adding game: %d [%s]\n", client, cl->executable);
  215. /* Update the list */
  216. cl->next = self->client;
  217. self->client = cl;
  218. pthread_rwlock_unlock(&self->rwlock);
  219. /* First add, init */
  220. if (atomic_fetch_add_explicit(&self->refcount, 1, memory_order_seq_cst) == 0) {
  221. game_mode_context_enter(self);
  222. }
  223. return true;
  224. }
  225. bool game_mode_context_unregister(GameModeContext *self, pid_t client)
  226. {
  227. GameModeClient *cl = NULL;
  228. GameModeClient *prev = NULL;
  229. bool found = false;
  230. /* Requires locking. */
  231. pthread_rwlock_wrlock(&self->rwlock);
  232. for (prev = cl = self->client; cl; cl = cl->next) {
  233. if (cl->pid != client) {
  234. prev = cl;
  235. continue;
  236. }
  237. LOG_MSG("Removing game: %d [%s]\n", client, cl->executable);
  238. /* Found it */
  239. found = true;
  240. prev->next = cl->next;
  241. if (cl == self->client) {
  242. self->client = cl->next;
  243. }
  244. cl->next = NULL;
  245. game_mode_client_free(cl);
  246. break;
  247. }
  248. /* Unlock here, potentially yielding */
  249. pthread_rwlock_unlock(&self->rwlock);
  250. if (!found) {
  251. LOG_ERROR("Removal requested for unknown process [%d]\n", client);
  252. return false;
  253. }
  254. /* When we hit bottom then end the game mode */
  255. if (atomic_fetch_sub_explicit(&self->refcount, 1, memory_order_seq_cst) == 1) {
  256. game_mode_context_leave(self);
  257. }
  258. return true;
  259. }
  260. /**
  261. * Construct a new GameModeClient for the given process ID
  262. *
  263. * This is deliberately OOM safe
  264. */
  265. static GameModeClient *game_mode_client_new(pid_t pid)
  266. {
  267. GameModeClient c = {
  268. .next = NULL,
  269. .pid = pid,
  270. };
  271. GameModeClient *ret = NULL;
  272. ret = calloc(1, sizeof(struct GameModeClient));
  273. if (!ret) {
  274. return NULL;
  275. }
  276. *ret = c;
  277. return ret;
  278. }
  279. /**
  280. * Free a client and the next element in the list.
  281. */
  282. static void game_mode_client_free(GameModeClient *client)
  283. {
  284. if (!client) {
  285. return;
  286. }
  287. if (client->next) {
  288. game_mode_client_free(client->next);
  289. }
  290. if (client->executable) {
  291. free(client->executable);
  292. }
  293. free(client);
  294. }
  295. /**
  296. * We continuously run until told otherwise.
  297. */
  298. static void *game_mode_context_reaper(void *userdata)
  299. {
  300. /* Stack, not allocated, won't disappear. */
  301. GameModeContext *self = userdata;
  302. struct timespec ts = { 0, 0 };
  303. ts.tv_sec = time(NULL) + SLEEP_INTERVAL;
  304. while (self->reaper.running) {
  305. /* Wait for condition */
  306. pthread_mutex_lock(&self->reaper.mutex);
  307. pthread_cond_timedwait(&self->reaper.condition, &self->reaper.mutex, &ts);
  308. pthread_mutex_unlock(&self->reaper.mutex);
  309. /* Highly possible the main thread woke us up to exit */
  310. if (!self->reaper.running) {
  311. return NULL;
  312. }
  313. /* Expire remaining entries */
  314. game_mode_context_auto_expire(self);
  315. ts.tv_sec = time(NULL) + SLEEP_INTERVAL;
  316. }
  317. return NULL;
  318. }
  319. GameModeContext *game_mode_context_instance()
  320. {
  321. return &instance;
  322. }
  323. /**
  324. * Attempt to locate the exe for the process.
  325. * We might run into issues if the process is running under an odd umask.
  326. */
  327. static char *game_mode_context_find_exe(pid_t pid)
  328. {
  329. static char proc_path[PATH_MAX] = { 0 };
  330. if (snprintf(proc_path, sizeof(proc_path), "/proc/%d/exe", pid) < 0) {
  331. LOG_ERROR("Unable to find executable for PID %d: %s\n", pid, strerror(errno));
  332. return NULL;
  333. }
  334. /* Allocate the realpath if possible */
  335. return realpath(proc_path, NULL);
  336. }