Skip to contentSkip to conversation

Taskset: check first whether affinity is settable

PATCH Superseded Carsten Emde 1 participant 2 messages Aug 5, 2022 Util-Linux package

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#1 lore raw

PATCH 1/1 Taskset: check first whether affinity is settable

In reply to Carsten Emde

If the PF_NO_SETAFFINITY process flag is set, the user may not know why the affinity is not settable. Write a respective message and do not attempt to set the affinity of this process.

---
 schedutils/taskset.c |   34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
schedutils/taskset.c +34 -0
Index: util-linux/schedutils/taskset.c
===================================================================
@@ -35,6 +35,11 @@
 #include "c.h"
 #include "closestream.h"
 
+#ifndef PF_NO_SETAFFINITY
+#define PF_NO_SETAFFINITY 0x04000000
+#endif
+#define PF_NO_SETAFFINITY_FLAG 9
+
 struct taskset {
 	pid_t		pid;		/* task PID */
 	cpu_set_t	*set;		/* task CPU mask */
@@ -114,6 +119,8 @@ static void __attribute__((__noreturn__)
 
 static void do_taskset(struct taskset *ts, size_t setsize, cpu_set_t *set)
 {
+	char statfilename[32];
+
 	/* read the current mask */
 	if (ts->pid) {
 		if (sched_getaffinity(ts->pid, ts->setsize, ts->set) < 0)
@@ -124,6 +131,33 @@ static void do_taskset(struct taskset *t
 	if (ts->get_only)
 		return;
 
+	/* check whether settable */
+	if (snprintf(statfilename, sizeof(statfilename), "/proc/%d/stat", ts->pid) > 0) {
+		int statfd;
+
+		if ((statfd = open(statfilename, S_IREAD)) > 0) {
+			char stat[1024];
+
+			if (read(statfd, stat, sizeof(stat)) > 0) {
+				char *endptr, *token = strtok(stat, " ");
+				int flags, flagno = PF_NO_SETAFFINITY_FLAG;
+
+				while (token && --flagno > 0)
+					token = strtok(NULL, " ");
+				if (flagno == 0 && *token != '\0') {
+					flags = strtol(token, &endptr, 10);
+					if (endptr == token + strlen(token)) {
+						if (flags & PF_NO_SETAFFINITY) {
+							fputs("warning: affinity cannot be set due to PF_NO_SETAFFINITY flag set\n", stderr);
+							errno = EINVAL;
+							err_affinity(ts->pid, 1);
+						}
+					}
+				}
+			}
+		}
+	}
+
 	/* set new mask */
 	if (sched_setaffinity(ts->pid, setsize, set) < 0)
 		err_affinity(ts->pid, 1);
#0 lore raw

cover Taskset: check first whether affinity is settable

If the PF_NO_SETAFFINITY process flag is set, the user may not know why the affinity is not settable. Write a respective message and do not attempt to set the affinity of this process.