taskset.c 9.2 KB

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