taskset.c 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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: "[-ap] [HEXMASK"IF_FEATURE_TASKSET_CPULIST(" | -c LIST")"] { 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 PID"
  38. //usage: "\n -a Operate on all threads"
  39. //usage: "\n -c Affinity is a list, not mask"
  40. //usage:
  41. //usage:#define taskset_example_usage
  42. //usage: "$ taskset 0x7 ./dgemm_test&\n"
  43. //usage: "$ taskset -p 0x1 $!\n"
  44. //usage: "pid 4790's current affinity mask: 7\n"
  45. //usage: "pid 4790's new affinity mask: 1\n"
  46. //usage: "$ taskset 0x7 /bin/sh -c './taskset -p 0x1 $$'\n"
  47. //usage: "pid 6671's current affinity mask: 1\n"
  48. //usage: "pid 6671's new affinity mask: 1\n"
  49. //usage: "$ taskset -p 1\n"
  50. //usage: "pid 1's current affinity mask: 3\n"
  51. /*
  52. * Not yet implemented:
  53. * -a/--all-tasks (affect all threads)
  54. * needs to get TIDs from /proc/PID/task/ and use _them_ as "pid" in sched_setaffinity(pid)
  55. */
  56. #include <sched.h>
  57. #include "libbb.h"
  58. typedef unsigned long ul;
  59. #define SZOF_UL (unsigned)(sizeof(ul))
  60. #define BITS_UL (unsigned)(sizeof(ul)*8)
  61. #define MASK_UL (unsigned)(sizeof(ul)*8 - 1)
  62. #if ENABLE_FEATURE_TASKSET_FANCY
  63. #define TASKSET_PRINTF_MASK "%s"
  64. /* craft a string from the mask */
  65. static char *from_mask(const ul *mask, unsigned sz_in_bytes)
  66. {
  67. char *str = xzalloc((sz_in_bytes+1) * 2); /* we will leak it */
  68. char *p = str;
  69. for (;;) {
  70. ul v = *mask++;
  71. if (SZOF_UL == 4)
  72. p += sprintf(p, "%08lx", v);
  73. if (SZOF_UL == 8)
  74. p += sprintf(p, "%016lx", v);
  75. if (SZOF_UL == 16)
  76. p += sprintf(p, "%032lx", v); /* :) */
  77. sz_in_bytes -= SZOF_UL;
  78. if ((int)sz_in_bytes <= 0)
  79. break;
  80. }
  81. while (str[0] == '0' && str[1])
  82. str++;
  83. return str;
  84. }
  85. #else
  86. #define TASKSET_PRINTF_MASK "%lx"
  87. static unsigned long from_mask(ul *mask, unsigned sz_in_bytes UNUSED_PARAM)
  88. {
  89. return *mask;
  90. }
  91. #endif
  92. static unsigned long *get_aff(int pid, unsigned *sz)
  93. {
  94. int r;
  95. unsigned long *mask = NULL;
  96. unsigned sz_in_bytes = *sz;
  97. for (;;) {
  98. mask = xrealloc(mask, sz_in_bytes);
  99. r = sched_getaffinity(pid, sz_in_bytes, (void*)mask);
  100. if (r == 0)
  101. break;
  102. sz_in_bytes *= 2;
  103. if (errno == EINVAL && (int)sz_in_bytes > 0)
  104. continue;
  105. bb_perror_msg_and_die("can't %cet pid %d's affinity", 'g', pid);
  106. }
  107. //bb_error_msg("get mask[0]:%lx sz_in_bytes:%d", mask[0], sz_in_bytes);
  108. *sz = sz_in_bytes;
  109. return mask;
  110. }
  111. #if ENABLE_FEATURE_TASKSET_CPULIST
  112. /*
  113. * Parse the CPU list and set the mask accordingly.
  114. *
  115. * The list element can be either a CPU index or a range of CPU indices.
  116. * Example: "1,3,5-7". Stride can be specified: "0-7:2" is "0,2,4,6".
  117. * Note: leading and trailing whitespace is not allowed.
  118. * util-linux 2.31 allows leading and sometimes trailing whitespace:
  119. * ok: taskset -c ' 1, 2'
  120. * ok: taskset -c ' 1 , 2'
  121. * ok: taskset -c ' 1-7: 2 ,8'
  122. * not ok: taskset -c ' 1 '
  123. * not ok: taskset -c ' 1-7: 2 '
  124. */
  125. static void parse_cpulist(ul *mask, unsigned max, char *s)
  126. {
  127. char *aff = s;
  128. for (;;) {
  129. unsigned bit, end;
  130. unsigned stride = 1;
  131. bit = end = bb_strtou(s, &s, 10);
  132. if (*s == '-') {
  133. s++;
  134. end = bb_strtou(s, &s, 10);
  135. if (*s == ':') {
  136. s++;
  137. stride = bb_strtou(s, &s, 10);
  138. }
  139. }
  140. if ((*s != ',' && *s != '\0')
  141. || bit > end
  142. || end == UINT_MAX /* bb_strtou returns this on malformed / ERANGE numbers */
  143. || (stride - 1) > (UINT_MAX / 4)
  144. /* disallow 0, malformed input, and too large stride prone to overflows */
  145. ) {
  146. bb_error_msg_and_die("bad affinity '%s'", aff);
  147. }
  148. while (bit <= end && bit < max) {
  149. mask[bit / BITS_UL] |= (1UL << (bit & MASK_UL));
  150. bit += stride;
  151. }
  152. if (*s == '\0')
  153. break;
  154. s++;
  155. }
  156. }
  157. static void print_cpulist(const ul *mask, unsigned mask_size_in_bytes)
  158. {
  159. const ul *mask_end;
  160. const char *delim;
  161. unsigned pos;
  162. ul bit;
  163. mask_end = mask + mask_size_in_bytes / sizeof(mask[0]);
  164. delim = "";
  165. pos = 0;
  166. bit = 1;
  167. for (;;) {
  168. if (*mask & bit) {
  169. unsigned onebit = pos + 1;
  170. printf("%s%u", delim, pos);
  171. do {
  172. pos++;
  173. bit <<= 1;
  174. if (bit == 0) {
  175. mask++;
  176. if (mask >= mask_end)
  177. break;
  178. bit = 1;
  179. }
  180. } while (*mask & bit);
  181. if (onebit != pos)
  182. printf("-%u", pos - 1);
  183. delim = ",";
  184. }
  185. pos++;
  186. bit <<= 1;
  187. if (bit == 0) {
  188. mask++;
  189. if (mask >= mask_end)
  190. break;
  191. bit = 1;
  192. }
  193. }
  194. bb_putchar('\n');
  195. }
  196. #endif
  197. enum {
  198. OPT_p = 1 << 0,
  199. OPT_a = 1 << 1,
  200. OPT_c = (1 << 2) * ENABLE_FEATURE_TASKSET_CPULIST,
  201. };
  202. static int process_pid_str(const char *pid_str, unsigned opts, char *aff)
  203. {
  204. ul *mask;
  205. unsigned mask_size_in_bytes;
  206. const char *current_new;
  207. pid_t pid = !pid_str ? 0 : xatou_range(pid_str, 1, INT_MAX); /* disallow "0": "taskset -p 0" should fail */
  208. mask_size_in_bytes = SZOF_UL;
  209. current_new = "current";
  210. print_aff:
  211. mask = get_aff(pid, &mask_size_in_bytes);
  212. if (opts & OPT_p) {
  213. #if ENABLE_FEATURE_TASKSET_CPULIST
  214. if (opts & OPT_c) {
  215. printf("pid %d's %s affinity list: ", pid, current_new);
  216. print_cpulist(mask, mask_size_in_bytes);
  217. } else
  218. #endif
  219. printf("pid %d's %s affinity mask: "TASKSET_PRINTF_MASK"\n",
  220. pid, current_new, from_mask(mask, mask_size_in_bytes));
  221. if (!aff) {
  222. /* Either it was just "-p <pid>",
  223. * or it was "-p <aff> <pid>" and we came here
  224. * for the second time (see goto below) */
  225. return 0;
  226. }
  227. current_new = "new";
  228. }
  229. memset(mask, 0, mask_size_in_bytes);
  230. if (!ENABLE_FEATURE_TASKSET_FANCY) {
  231. /* Affinity was specified, translate it into mask */
  232. /* it is always in hex, skip "0x" if it exists */
  233. if (aff[0] == '0' && (aff[1]|0x20) == 'x')
  234. aff += 2;
  235. mask[0] = xstrtoul(aff, 16);
  236. }
  237. #if ENABLE_FEATURE_TASKSET_CPULIST
  238. else if (opts & OPT_c) {
  239. parse_cpulist(mask, mask_size_in_bytes * 8, aff);
  240. }
  241. #endif
  242. else {
  243. unsigned i;
  244. char *last_char;
  245. /* Affinity was specified, translate it into mask */
  246. /* it is always in hex, skip "0x" if it exists */
  247. if (aff[0] == '0' && (aff[1]|0x20) == 'x')
  248. aff += 2;
  249. i = 0; /* bit pos in mask[] */
  250. /* aff is ASCII hex string, accept very long masks in this form.
  251. * Process hex string AABBCCDD... to ulong mask[]
  252. * from the rightmost nibble, which is least-significant.
  253. * Bits not fitting into mask[] are ignored: (example: 1234
  254. * in 12340000000000000000000000000000000000000ff)
  255. */
  256. last_char = strchrnul(aff, '\0');
  257. while (last_char > aff) {
  258. char c;
  259. ul val;
  260. last_char--;
  261. c = *last_char;
  262. if (isdigit(c))
  263. val = c - '0';
  264. else if ((c|0x20) >= 'a' && (c|0x20) <= 'f')
  265. val = (c|0x20) - ('a' - 10);
  266. else
  267. bb_error_msg_and_die("bad affinity '%s'", aff);
  268. if (i < mask_size_in_bytes * 8) {
  269. mask[i / BITS_UL] |= val << (i & MASK_UL);
  270. //bb_error_msg("bit %d set", i);
  271. }
  272. /* else:
  273. * We can error out here, but we don't.
  274. * For one, kernel itself ignores bits in mask[]
  275. * which do not map to any CPUs:
  276. * if mask[] has one 32-bit long element,
  277. * but you have only 8 CPUs, all bits beyond first 8
  278. * are ignored, silently.
  279. * No point in making bits past 31th to be errors.
  280. */
  281. i += 4;
  282. }
  283. }
  284. /* Set pid's or our own (pid==0) affinity */
  285. if (sched_setaffinity(pid, mask_size_in_bytes, (void*)mask))
  286. bb_perror_msg_and_die("can't %cet pid %d's affinity", 's', pid);
  287. //bb_error_msg("set mask[0]:%lx", mask[0]);
  288. if ((opts & OPT_p) && aff) { /* "-p <aff> <pid> [...ignored...]" */
  289. aff = NULL;
  290. goto print_aff; /* print new affinity and exit */
  291. }
  292. return 0;
  293. }
  294. static int FAST_FUNC iter(const char *dn UNUSED_PARAM, struct dirent *ent, void *aff)
  295. {
  296. if (isdigit(ent->d_name[0]))
  297. return process_pid_str(ent->d_name, option_mask32, aff);
  298. return 0;
  299. }
  300. int taskset_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  301. int taskset_main(int argc UNUSED_PARAM, char **argv)
  302. {
  303. const char *pid_str;
  304. char *aff;
  305. unsigned opts;
  306. /* NB: we mimic util-linux's taskset: -p does not take
  307. * an argument, i.e., "-pN" is NOT valid, only "-p N"!
  308. * Indeed, util-linux-2.13-pre7 uses:
  309. * getopt_long(argc, argv, "+pchV", ...), not "...p:..." */
  310. opts = getopt32(argv, "^+" "pa"IF_FEATURE_TASKSET_CPULIST("c")
  311. "\0" "-1" /* at least 1 arg */);
  312. argv += optind;
  313. aff = *argv++;
  314. if (!(opts & OPT_p)) {
  315. /* <aff> <cmd...> */
  316. if (!*argv)
  317. bb_show_usage();
  318. process_pid_str(NULL, opts, aff);
  319. BB_EXECVP_or_die(argv);
  320. }
  321. pid_str = aff;
  322. if (*argv) /* "-p <aff> <pid> ...rest.is.ignored..." */
  323. pid_str = *argv;
  324. else
  325. aff = NULL;
  326. if (opts & OPT_a) {
  327. char *dn;
  328. int r;
  329. dn = xasprintf("/proc/%s/task", pid_str);
  330. r = iterate_on_dir(dn, iter, aff);
  331. IF_FEATURE_CLEAN_UP(free(dn);)
  332. if (r == 0)
  333. return r; /* EXIT_SUCCESS */
  334. /* else: no /proc/PID/task, act as if no -a was given */
  335. }
  336. return process_pid_str(pid_str, opts, aff);
  337. }