taskset.c 9.8 KB

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