taskset.c 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * taskset - retrieve or set a processes' CPU affinity
  4. * Copyright (c) 2006 Bernhard Reutner-Fischer
  5. *
  6. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  7. */
  8. //config:config TASKSET
  9. //config: bool "taskset (4.2 kb)"
  10. //config: default y
  11. //config: help
  12. //config: Retrieve or set a processes's CPU affinity.
  13. //config: This requires sched_{g,s}etaffinity support in your libc.
  14. //config:
  15. //config:config FEATURE_TASKSET_FANCY
  16. //config: bool "Fancy output"
  17. //config: default y
  18. //config: depends on TASKSET
  19. //config: help
  20. //config: Needed for machines with more than 32-64 CPUs:
  21. //config: affinity parameter 0xHHHHHHHHHHHHHHHHHHHH can be arbitrarily long
  22. //config: in this case. Otherwise, it is limited to sizeof(long).
  23. //config:
  24. //config:config FEATURE_TASKSET_CPULIST
  25. //config: bool "CPU list support (-c option)"
  26. //config: default y
  27. //config: depends on FEATURE_TASKSET_FANCY
  28. //config: help
  29. //config: Add support for taking/printing affinity as CPU list when '-c'
  30. //config: option is used. For example, it prints '0-3,7' instead of mask '8f'.
  31. //applet:IF_TASKSET(APPLET_NOEXEC(taskset, taskset, BB_DIR_USR_BIN, BB_SUID_DROP, taskset))
  32. //kbuild:lib-$(CONFIG_TASKSET) += taskset.o
  33. //usage:#define taskset_trivial_usage
  34. //usage: "[-p] [HEXMASK] PID | PROG ARGS"
  35. //usage:#define taskset_full_usage "\n\n"
  36. //usage: "Set or get CPU affinity\n"
  37. //usage: "\n -p Operate on an existing PID"
  38. //usage:
  39. //usage:#define taskset_example_usage
  40. //usage: "$ taskset 0x7 ./dgemm_test&\n"
  41. //usage: "$ taskset -p 0x1 $!\n"
  42. //usage: "pid 4790's current affinity mask: 7\n"
  43. //usage: "pid 4790's new affinity mask: 1\n"
  44. //usage: "$ taskset 0x7 /bin/sh -c './taskset -p 0x1 $$'\n"
  45. //usage: "pid 6671's current affinity mask: 1\n"
  46. //usage: "pid 6671's new affinity mask: 1\n"
  47. //usage: "$ taskset -p 1\n"
  48. //usage: "pid 1's current affinity mask: 3\n"
  49. /*
  50. * Not yet implemented:
  51. * -a/--all-tasks (affect all threads)
  52. * needs to get TIDs from /proc/PID/task/ and use _them_ as "pid" in sched_setaffinity(pid)
  53. * -c/--cpu-list (specify CPUs via "1,3,5-7")
  54. */
  55. #include <sched.h>
  56. #include "libbb.h"
  57. typedef unsigned long ul;
  58. #define SZOF_UL (unsigned)(sizeof(ul))
  59. #define BITS_UL (unsigned)(sizeof(ul)*8)
  60. #define MASK_UL (unsigned)(sizeof(ul)*8 - 1)
  61. #if ENABLE_FEATURE_TASKSET_FANCY
  62. #define TASKSET_PRINTF_MASK "%s"
  63. /* craft a string from the mask */
  64. static char *from_mask(const ul *mask, unsigned sz_in_bytes)
  65. {
  66. char *str = xzalloc((sz_in_bytes+1) * 2); /* we will leak it */
  67. char *p = str;
  68. for (;;) {
  69. ul v = *mask++;
  70. if (SZOF_UL == 4)
  71. p += sprintf(p, "%08lx", v);
  72. if (SZOF_UL == 8)
  73. p += sprintf(p, "%016lx", v);
  74. if (SZOF_UL == 16)
  75. p += sprintf(p, "%032lx", v); /* :) */
  76. sz_in_bytes -= SZOF_UL;
  77. if ((int)sz_in_bytes <= 0)
  78. break;
  79. }
  80. while (str[0] == '0' && str[1])
  81. str++;
  82. return str;
  83. }
  84. #else
  85. #define TASKSET_PRINTF_MASK "%lx"
  86. static unsigned long long from_mask(ul *mask, unsigned sz_in_bytes UNUSED_PARAM)
  87. {
  88. return *mask;
  89. }
  90. #endif
  91. static unsigned long *get_aff(int pid, unsigned *sz)
  92. {
  93. int r;
  94. unsigned long *mask = NULL;
  95. unsigned sz_in_bytes = *sz;
  96. for (;;) {
  97. mask = xrealloc(mask, sz_in_bytes);
  98. r = sched_getaffinity(pid, sz_in_bytes, (void*)mask);
  99. if (r == 0)
  100. break;
  101. sz_in_bytes *= 2;
  102. if (errno == EINVAL && (int)sz_in_bytes > 0)
  103. continue;
  104. bb_perror_msg_and_die("can't %cet pid %d's affinity", 'g', pid);
  105. }
  106. //bb_error_msg("get mask[0]:%lx sz_in_bytes:%d", mask[0], sz_in_bytes);
  107. *sz = sz_in_bytes;
  108. return mask;
  109. }
  110. #if ENABLE_FEATURE_TASKSET_CPULIST
  111. /*
  112. * Parse the CPU list and set the mask accordingly.
  113. *
  114. * The list element can be either a CPU index or a range of CPU indices.
  115. * Example: "1,3,5-7". Stride can be specified: "0-7:2" is "0,2,4,6".
  116. * Note: leading and trailing whitespace is not allowed.
  117. * util-linux 2.31 allows leading and sometimes trailing whitespace:
  118. * ok: taskset -c ' 1, 2'
  119. * ok: taskset -c ' 1 , 2'
  120. * ok: taskset -c ' 1-7: 2 ,8'
  121. * not ok: taskset -c ' 1 '
  122. * not ok: taskset -c ' 1-7: 2 '
  123. */
  124. static void parse_cpulist(ul *mask, unsigned max, char *s)
  125. {
  126. char *aff = s;
  127. for (;;) {
  128. unsigned bit, end;
  129. unsigned stride = 1;
  130. bit = end = bb_strtou(s, &s, 10);
  131. if (*s == '-') {
  132. s++;
  133. end = bb_strtou(s, &s, 10);
  134. if (*s == ':') {
  135. s++;
  136. stride = bb_strtou(s, &s, 10);
  137. }
  138. }
  139. if ((*s != ',' && *s != '\0')
  140. || bit > end
  141. || end == UINT_MAX /* bb_strtou returns this on malformed / ERANGE numbers */
  142. || (stride - 1) > (UINT_MAX / 4)
  143. /* disallow 0, malformed input, and too large stride prone to overflows */
  144. ) {
  145. bb_error_msg_and_die("bad affinity '%s'", aff);
  146. }
  147. while (bit <= end && bit < max) {
  148. mask[bit / BITS_UL] |= (1UL << (bit & MASK_UL));
  149. bit += stride;
  150. }
  151. if (*s == '\0')
  152. break;
  153. s++;
  154. }
  155. }
  156. static void print_cpulist(const ul *mask, unsigned mask_size_in_bytes)
  157. {
  158. const ul *mask_end;
  159. const char *delim;
  160. unsigned pos;
  161. ul bit;
  162. mask_end = mask + mask_size_in_bytes / sizeof(mask[0]);
  163. delim = "";
  164. pos = 0;
  165. bit = 1;
  166. for (;;) {
  167. if (*mask & bit) {
  168. unsigned onebit = pos + 1;
  169. printf("%s%u", delim, pos);
  170. do {
  171. pos++;
  172. bit <<= 1;
  173. if (bit == 0) {
  174. mask++;
  175. if (mask >= mask_end)
  176. break;
  177. bit = 1;
  178. }
  179. } while (*mask & bit);
  180. if (onebit != pos)
  181. printf("-%u", pos - 1);
  182. delim = ",";
  183. }
  184. pos++;
  185. bit <<= 1;
  186. if (bit == 0) {
  187. mask++;
  188. if (mask >= mask_end)
  189. break;
  190. bit = 1;
  191. }
  192. }
  193. bb_putchar('\n');
  194. }
  195. #endif
  196. int taskset_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  197. int taskset_main(int argc UNUSED_PARAM, char **argv)
  198. {
  199. ul *mask;
  200. unsigned mask_size_in_bytes;
  201. pid_t pid = 0;
  202. const char *current_new;
  203. char *aff;
  204. unsigned opts;
  205. enum {
  206. OPT_p = 1 << 0,
  207. OPT_c = (1 << 1) * ENABLE_FEATURE_TASKSET_CPULIST,
  208. };
  209. /* NB: we mimic util-linux's taskset: -p does not take
  210. * an argument, i.e., "-pN" is NOT valid, only "-p N"!
  211. * Indeed, util-linux-2.13-pre7 uses:
  212. * getopt_long(argc, argv, "+pchV", ...), not "...p:..." */
  213. opts = getopt32(argv, "^+" "p"IF_FEATURE_TASKSET_CPULIST("c")
  214. "\0" "-1" /* at least 1 arg */);
  215. argv += optind;
  216. aff = *argv++;
  217. if (opts & OPT_p) {
  218. char *pid_str = aff;
  219. if (*argv) { /* "-p <aff> <pid> ...rest.is.ignored..." */
  220. pid_str = *argv; /* NB: *argv != NULL in this case */
  221. }
  222. /* else it was just "-p <pid>", and *argv == NULL */
  223. pid = xatoul_range(pid_str, 1, ((unsigned)(pid_t)ULONG_MAX) >> 1);
  224. } else {
  225. /* <aff> <cmd...> */
  226. if (!*argv)
  227. bb_show_usage();
  228. }
  229. mask_size_in_bytes = SZOF_UL;
  230. current_new = "current";
  231. print_aff:
  232. mask = get_aff(pid, &mask_size_in_bytes);
  233. if (opts & OPT_p) {
  234. #if ENABLE_FEATURE_TASKSET_CPULIST
  235. if (opts & OPT_c) {
  236. printf("pid %d's %s affinity list: ", pid, current_new);
  237. print_cpulist(mask, mask_size_in_bytes);
  238. } else
  239. #endif
  240. printf("pid %d's %s affinity mask: "TASKSET_PRINTF_MASK"\n",
  241. pid, current_new, from_mask(mask, mask_size_in_bytes));
  242. if (*argv == NULL) {
  243. /* Either it was just "-p <pid>",
  244. * or it was "-p <aff> <pid>" and we came here
  245. * for the second time (see goto below) */
  246. return EXIT_SUCCESS;
  247. }
  248. *argv = NULL;
  249. current_new = "new";
  250. }
  251. memset(mask, 0, mask_size_in_bytes);
  252. if (!ENABLE_FEATURE_TASKSET_FANCY) {
  253. /* Affinity was specified, translate it into mask */
  254. /* it is always in hex, skip "0x" if it exists */
  255. if (aff[0] == '0' && (aff[1]|0x20) == 'x')
  256. aff += 2;
  257. mask[0] = xstrtoul(aff, 16);
  258. }
  259. #if ENABLE_FEATURE_TASKSET_CPULIST
  260. else if (opts & OPT_c) {
  261. parse_cpulist(mask, mask_size_in_bytes * 8, aff);
  262. }
  263. #endif
  264. else {
  265. unsigned i;
  266. char *last_char;
  267. /* Affinity was specified, translate it into mask */
  268. /* it is always in hex, skip "0x" if it exists */
  269. if (aff[0] == '0' && (aff[1]|0x20) == 'x')
  270. aff += 2;
  271. i = 0; /* bit pos in mask[] */
  272. /* aff is ASCII hex string, accept very long masks in this form.
  273. * Process hex string AABBCCDD... to ulong mask[]
  274. * from the rightmost nibble, which is least-significant.
  275. * Bits not fitting into mask[] are ignored: (example: 1234
  276. * in 12340000000000000000000000000000000000000ff)
  277. */
  278. last_char = strchrnul(aff, '\0');
  279. while (last_char > aff) {
  280. char c;
  281. ul val;
  282. last_char--;
  283. c = *last_char;
  284. if (isdigit(c))
  285. val = c - '0';
  286. else if ((c|0x20) >= 'a' && (c|0x20) <= 'f')
  287. val = (c|0x20) - ('a' - 10);
  288. else
  289. bb_error_msg_and_die("bad affinity '%s'", aff);
  290. if (i < mask_size_in_bytes * 8) {
  291. mask[i / BITS_UL] |= val << (i & MASK_UL);
  292. //bb_error_msg("bit %d set", i);
  293. }
  294. /* else:
  295. * We can error out here, but we don't.
  296. * For one, kernel itself ignores bits in mask[]
  297. * which do not map to any CPUs:
  298. * if mask[] has one 32-bit long element,
  299. * but you have only 8 CPUs, all bits beyond first 8
  300. * are ignored, silently.
  301. * No point in making bits past 31th to be errors.
  302. */
  303. i += 4;
  304. }
  305. }
  306. /* Set pid's or our own (pid==0) affinity */
  307. if (sched_setaffinity(pid, mask_size_in_bytes, (void*)mask))
  308. bb_perror_msg_and_die("can't %cet pid %d's affinity", 's', pid);
  309. //bb_error_msg("set mask[0]:%lx", mask[0]);
  310. if (!argv[0]) /* "-p <aff> <pid> [...ignored...]" */
  311. goto print_aff; /* print new affinity and exit */
  312. BB_EXECVP_or_die(argv);
  313. }