gamemoded.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. /**
  27. * Simple daemon to allow user space programs to control the CPU governors
  28. *
  29. * The main process is responsible for bootstrapping the D-BUS daemon, caching
  30. * the initial governor settings, and then responding to requests over D-BUS.
  31. *
  32. * Clients register their pid(s) with the service, which are routinely checked
  33. * to see if they've expired. Once we reach our first actively registered client
  34. * we put the system into "game mode", i.e. move the CPU governor into a performance
  35. * mode.
  36. *
  37. * Upon exit, or when all clients have stopped running, we put the system back
  38. * into the default governor policy, which is invariably powersave or similar
  39. * on laptops. This ensures that the system is obtaining the maximum performance
  40. * whilst gaming, and allowed to sanely return to idle once the workload is
  41. * complete.
  42. */
  43. #define _GNU_SOURCE
  44. #include "gamemode.h"
  45. #include "common-logging.h"
  46. #include "gamemode-config.h"
  47. #include "gamemode_client.h"
  48. #include "build-config.h"
  49. #include <fcntl.h>
  50. #include <getopt.h>
  51. #include <signal.h>
  52. #include <sys/stat.h>
  53. #include <systemd/sd-daemon.h> /* TODO: Move usage to gamemode-dbus.c */
  54. #include <unistd.h>
  55. #define USAGE_TEXT \
  56. "Usage: %s [-d] [-l] [-r] [-t] [-h] [-v]\n\n" \
  57. " -r[PID], --request=[PID] Toggle gamemode for process\n" \
  58. " When no PID given, requests gamemode and pauses\n" \
  59. " -s[PID], --status=[PID] Query the status of gamemode for process\n" \
  60. " When no PID given, queries the status globally\n" \
  61. " -d, --daemonize Daemonize self after launch\n" \
  62. " -l, --log-to-syslog Log to syslog\n" \
  63. " -t, --test Run tests\n" \
  64. " -h, --help Print this help\n" \
  65. " -v, --version Print version\n" \
  66. "\n" \
  67. "See man page for more information.\n"
  68. #define VERSION_TEXT "gamemode version: v" GAMEMODE_VERSION "\n"
  69. static void sigint_handler(__attribute__((unused)) int signo)
  70. {
  71. LOG_MSG("Quitting by request...\n");
  72. sd_notify(0, "STATUS=GameMode is quitting by request...\n");
  73. /* Clean up nicely */
  74. game_mode_context_destroy(game_mode_context_instance());
  75. _Exit(EXIT_SUCCESS);
  76. }
  77. static void sigint_handler_noexit(__attribute__((unused)) int signo)
  78. {
  79. LOG_MSG("Quitting by request...\n");
  80. }
  81. /**
  82. * Helper to perform standard UNIX daemonization
  83. */
  84. static void daemonize(const char *name)
  85. {
  86. /* Initial fork */
  87. pid_t pid = fork();
  88. if (pid < 0) {
  89. FATAL_ERRORNO("Failed to fork");
  90. }
  91. if (pid != 0) {
  92. LOG_MSG("Daemon launched as %s...\n", name);
  93. exit(EXIT_SUCCESS);
  94. }
  95. /* Fork a second time */
  96. pid = fork();
  97. if (pid < 0) {
  98. FATAL_ERRORNO("Failed to fork");
  99. } else if (pid > 0) {
  100. exit(EXIT_SUCCESS);
  101. }
  102. /* Now continue execution */
  103. umask(0022);
  104. if (setsid() < 0) {
  105. FATAL_ERRORNO("Failed to create process group\n");
  106. }
  107. if (chdir("/") < 0) {
  108. FATAL_ERRORNO("Failed to change to root directory\n");
  109. }
  110. /* replace standard file descriptors by /dev/null */
  111. int devnull_r = open("/dev/null", O_RDONLY);
  112. int devnull_w = open("/dev/null", O_WRONLY);
  113. if (devnull_r == -1 || devnull_w == -1)
  114. {
  115. LOG_ERROR("Failed to redirect standard input and output to /dev/null\n");
  116. }
  117. else
  118. {
  119. dup2(devnull_r, STDIN_FILENO);
  120. dup2(devnull_w, STDOUT_FILENO);
  121. dup2(devnull_w, STDERR_FILENO);
  122. close(devnull_r);
  123. close(devnull_w);
  124. }
  125. }
  126. /**
  127. * Main bootstrap entry into gamemoded
  128. */
  129. int main(int argc, char *argv[])
  130. {
  131. GameModeContext *context = NULL;
  132. /* Gather command line options */
  133. bool daemon = false;
  134. bool use_syslog = false;
  135. int opt = 0;
  136. /* Options struct for getopt_long */
  137. static struct option long_options[] = {
  138. { "daemonize", no_argument, 0, 'd' }, { "log-to-syslog", no_argument, 0, 'l' },
  139. { "request", optional_argument, 0, 'r' }, { "test", no_argument, 0, 't' },
  140. { "status", optional_argument, 0, 's' }, { "help", no_argument, 0, 'h' },
  141. { "version", no_argument, 0, 'v' }, { NULL, 0, NULL, 0 },
  142. };
  143. static const char *short_options = "dls::r::tvh";
  144. while ((opt = getopt_long(argc, argv, short_options, long_options, 0)) != -1) {
  145. switch (opt) {
  146. case 'd':
  147. daemon = true;
  148. break;
  149. case 'l':
  150. use_syslog = true;
  151. break;
  152. case 's':
  153. if (optarg != NULL) {
  154. pid_t pid = atoi(optarg);
  155. switch (gamemode_query_status_for(pid)) {
  156. case 0: /* inactive */
  157. LOG_MSG("gamemode is inactive\n");
  158. break;
  159. case 1: /* active not not registered */
  160. LOG_MSG("gamemode is active but [%d] not registered\n", pid);
  161. break;
  162. case 2: /* active for client */
  163. LOG_MSG("gamemode is active and [%d] registered\n", pid);
  164. break;
  165. case -1:
  166. LOG_ERROR("gamemode_query_status_for(%d) failed: %s\n",
  167. pid,
  168. gamemode_error_string());
  169. exit(EXIT_FAILURE);
  170. default:
  171. LOG_ERROR("gamemode_query_status returned unexpected value 2\n");
  172. exit(EXIT_FAILURE);
  173. }
  174. } else {
  175. int ret = 0;
  176. switch ((ret = gamemode_query_status())) {
  177. case 0: /* inactive */
  178. LOG_MSG("gamemode is inactive\n");
  179. break;
  180. case 1: /* active */
  181. LOG_MSG("gamemode is active\n");
  182. break;
  183. case -1: /* error */
  184. LOG_ERROR("gamemode status request failed: %s\n", gamemode_error_string());
  185. exit(EXIT_FAILURE);
  186. default: /* unexpected value eg. 2 */
  187. LOG_ERROR("gamemode_query_status returned unexpected value %d\n", ret);
  188. exit(EXIT_FAILURE);
  189. }
  190. }
  191. exit(EXIT_SUCCESS);
  192. case 'r':
  193. if (optarg != NULL) {
  194. pid_t pid = atoi(optarg);
  195. /* toggle gamemode for the process */
  196. switch (gamemode_query_status_for(pid)) {
  197. case 0: /* inactive */
  198. case 1: /* active not not registered */
  199. LOG_MSG("gamemode not active for client, requesting start for %d...\n", pid);
  200. if (gamemode_request_start_for(pid) < 0) {
  201. LOG_ERROR("gamemode_request_start_for(%d) failed: %s\n",
  202. pid,
  203. gamemode_error_string());
  204. exit(EXIT_FAILURE);
  205. }
  206. LOG_MSG("request succeeded\n");
  207. break;
  208. case 2: /* active for client */
  209. LOG_MSG("gamemode active for client, requesting end for %d...\n", pid);
  210. if (gamemode_request_end_for(pid) < 0) {
  211. LOG_ERROR("gamemode_request_end_for(%d) failed: %s\n",
  212. pid,
  213. gamemode_error_string());
  214. exit(EXIT_FAILURE);
  215. }
  216. LOG_MSG("request succeeded\n");
  217. break;
  218. case -1: /* error */
  219. LOG_ERROR("gamemode_query_status_for(%d) failed: %s\n",
  220. pid,
  221. gamemode_error_string());
  222. exit(EXIT_FAILURE);
  223. }
  224. } else {
  225. /* Request gamemode for this process */
  226. if (gamemode_request_start() < 0) {
  227. LOG_ERROR("gamemode request failed: %s\n", gamemode_error_string());
  228. exit(EXIT_FAILURE);
  229. }
  230. /* Request and report on the status */
  231. switch (gamemode_query_status()) {
  232. case 2: /* active for this client */
  233. LOG_MSG("gamemode request succeeded and is active\n");
  234. break;
  235. case 1: /* active */
  236. LOG_ERROR("gamemode request succeeded and is active but registration failed\n");
  237. exit(EXIT_FAILURE);
  238. case 0: /* inactive */
  239. LOG_ERROR("gamemode request succeeded but is not active\n");
  240. exit(EXIT_FAILURE);
  241. case -1: /* error */
  242. LOG_ERROR("gamemode_query_status failed: %s\n", gamemode_error_string());
  243. exit(EXIT_FAILURE);
  244. }
  245. /* Simply pause and wait a SIGINT */
  246. if (signal(SIGINT, sigint_handler_noexit) == SIG_ERR) {
  247. FATAL_ERRORNO("Could not catch SIGINT");
  248. }
  249. pause();
  250. /* Explicitly clean up */
  251. if (gamemode_request_end() < 0) {
  252. LOG_ERROR("gamemode request failed: %s\n", gamemode_error_string());
  253. exit(EXIT_FAILURE);
  254. }
  255. }
  256. exit(EXIT_SUCCESS);
  257. case 't': {
  258. int status = game_mode_run_client_tests();
  259. exit(status);
  260. }
  261. case 'v':
  262. LOG_MSG(VERSION_TEXT);
  263. exit(EXIT_SUCCESS);
  264. case 'h':
  265. LOG_MSG(USAGE_TEXT, argv[0]);
  266. exit(EXIT_SUCCESS);
  267. default:
  268. fprintf(stderr, USAGE_TEXT, argv[0]);
  269. exit(EXIT_FAILURE);
  270. }
  271. }
  272. /* If syslog is requested, set it up with our process name */
  273. if (use_syslog) {
  274. set_use_syslog(argv[0]);
  275. }
  276. /* Daemonize ourselves first if asked */
  277. if (daemon) {
  278. daemonize(argv[0]);
  279. }
  280. /* Log a version message on startup */
  281. LOG_MSG("v%s\n", GAMEMODE_VERSION);
  282. /* Set up the game mode context */
  283. context = game_mode_context_instance();
  284. game_mode_context_init(context);
  285. /* Handle quits cleanly */
  286. if (signal(SIGINT, sigint_handler) == SIG_ERR) {
  287. FATAL_ERRORNO("Could not catch SIGINT");
  288. }
  289. if (signal(SIGTERM, sigint_handler) == SIG_ERR) {
  290. FATAL_ERRORNO("Could not catch SIGTERM");
  291. }
  292. /* Run the main dbus message loop */
  293. game_mode_context_loop(context);
  294. game_mode_context_destroy(context);
  295. /* Log we're finished */
  296. LOG_MSG("Quitting naturally...\n");
  297. sd_notify(0, "STATUS=GameMode is quitting naturally...\n");
  298. }