aboutsummaryrefslogtreecommitdiffstats
path: root/src/vty/cpu_sched_vty.c
blob: 3b6067a36465cd30eeed94398b2c58df347033a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
/*! \file cpu_sched_vty.c
 * Implementation to CPU / Threading / Scheduler properties from VTY configuration.
 */
/* (C) 2020 by sysmocom - s.f.m.c. GmbH <info@sysmocom.de>
 *
 * Author: Pau Espin Pedrol <pespin@sysmocom.de>
 *
 * All Rights Reserved
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: GPLv2+
 */

#define _GNU_SOURCE

#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
#include <unistd.h>
#include <sched.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <dirent.h>
#include <pthread.h>
#include <inttypes.h>

#include <osmocom/vty/vty.h>
#include <osmocom/vty/command.h>
#include <osmocom/vty/tdef_vty.h>
#include <osmocom/core/tdef.h>
#include <osmocom/core/fsm.h>
#include <osmocom/core/linuxlist.h>

/*! \addtogroup Tdef_VTY
 *
 * CPU Scheduling related VTY API.
 *
 * @{
 * \file cpu_sched_vty.c
 */

enum sched_vty_thread_id {
	SCHED_VTY_THREAD_SELF,
	SCHED_VTY_THREAD_ALL,
	SCHED_VTY_THREAD_ID,
	SCHED_VTY_THREAD_NAME,
	SCHED_VTY_THREAD_UNKNOWN,
};

struct cpu_affinity_it {
	struct llist_head entry;
	enum sched_vty_thread_id tid_type;
	char bufname[64];
	cpu_set_t *cpuset;
	size_t cpuset_size;
	bool delay;
};

struct sched_vty_opts {
	void *tall_ctx;
	int sched_rr_prio;
	struct llist_head cpu_affinity_li;
	pthread_mutex_t cpu_affinity_li_mutex;
};

static struct sched_vty_opts *sched_vty_opts;

static struct cmd_node sched_node = {
	L_CPU_SCHED_NODE,
	"%s(config-sched)# ",
	1,
};

/* returns number of configured CPUs in the system, or negative otherwise */
static int get_num_cpus() {
	static unsigned int num_cpus = 0;
	long ln;

	if (num_cpus)
		return num_cpus;

	/* This is expensive (goes across /sys, so let's do it only once. It is
	 * guaranteed it won't change during process span anyway). */
	ln = sysconf(_SC_NPROCESSORS_CONF);
	if (ln < 0) {
		LOGP(DLGLOBAL, LOGL_ERROR, "sysconf(_SC_NPROCESSORS_CONF) failed: %s\n",
		     strerror(errno));
		return -1;
	}
	num_cpus = (unsigned int) ln;
	return num_cpus;
}

/* Parses string with CPU hex Affinity Mask, with right-most bit being CPU0, and
 * fills a cpuset of size cpuset_size.
 */
static int parse_cpu_hex_mask(const char *str, cpu_set_t *cpuset, size_t cpuset_size)
{
	int len = strlen(str);
	const char *ptr = str + len - 1;
	int cpu = 0;

	/* skip optional '0x' prefix format */
	if (len >= 2 && str[0] == '0' && str[1] == 'x')
		str += 2;
	CPU_ZERO_S(cpuset_size, cpuset);

	while (ptr >= str) {
		char c = *ptr;
		uint8_t val;

		if (c >= '0' && c <= '9') {
			val = c - '0';
		} else {
			c = (char)tolower((int)c);
			if (c >= 'a' && c <= 'f')
				val = c + (10 - 'a');
			else
				return -1;
		}
		if (val & 0x01)
			CPU_SET_S(cpu, cpuset_size, cpuset);
		if (val & 0x02)
			CPU_SET_S(cpu + 1, cpuset_size, cpuset);
		if (val & 0x04)
			CPU_SET_S(cpu + 2, cpuset_size, cpuset);
		if (val & 0x08)
			CPU_SET_S(cpu + 3, cpuset_size, cpuset);
		ptr--;
		cpu += 4;
	}

	return 0;
}

/* Generates a hexstring in str from cpuset of size cpuset_size */
static int generate_cpu_hex_mask(char *str, size_t str_buf_size,
				 cpu_set_t *cpuset, size_t cpuset_size)
{
	char *ptr = str;
	int cpu;
	bool first_nonzero_found = false;

	/* 2 char per byte, + '0x' prefix + '\0' */
	if (cpuset_size * 2 + 2 + 1 > str_buf_size)
		return -1;

	*ptr++ = '0';
	*ptr++ = 'x';

	for (cpu = cpuset_size*8 - 4; cpu >= 0; cpu -= 4) {
		uint8_t val = 0;

		if (CPU_ISSET_S(cpu, cpuset_size, cpuset))
			val |= 0x01;
		if (CPU_ISSET_S(cpu + 1, cpuset_size, cpuset))
			val |= 0x02;
		if (CPU_ISSET_S(cpu + 2, cpuset_size, cpuset))
			val |= 0x04;
		if (CPU_ISSET_S(cpu + 3, cpuset_size, cpuset))
			val |= 0x08;

		if (val >= 0 && val < 10)
			*ptr = '0' + val;
		else
			*ptr = ('a' - 10) + val;
		if (val)
			first_nonzero_found = true;
		if (first_nonzero_found)
			ptr++;

	}
	if (!first_nonzero_found)
		*ptr++ = '0';
	*ptr = '\0';
	return 0;
}

/* Checks whther a thread identified by tid exists and belongs to the running process */
static bool proc_tid_exists(pid_t tid)
{
	DIR *proc_dir;
	struct dirent *entry;
	char dirname[100];
	int tid_it;
	bool found = false;

	snprintf(dirname, sizeof(dirname), "/proc/%ld/task", (long int)getpid());
	proc_dir = opendir(dirname);
	if (!proc_dir)
		return false; /*FIXME; print error */

	while ((entry = readdir(proc_dir))) {
		if (entry->d_name[0] == '.')
			continue;
		tid_it = atoi(entry->d_name);
		if (tid_it == tid) {
			found = true;
			break;
		}
	}

	closedir(proc_dir);
	return found;
}

/* Checks whther a thread identified by name exists and belongs to the running
 * process, and returns its disocevered TID in res_pid.
 */
static bool proc_name_exists(const char *name, pid_t *res_pid)
{
	DIR *proc_dir;
	struct dirent *entry;
	char path[100];
	char buf[17]; /* 15 + \n + \0 */
	int tid_it;
	int fd;
	pid_t mypid = getpid();
	bool found = false;
	int rc;

	*res_pid = 0;

	snprintf(path, sizeof(path), "/proc/%ld/task", (long int)mypid);
	proc_dir = opendir(path);
	if (!proc_dir)
		return false;

	while ((entry = readdir(proc_dir)))
	{
		if (entry->d_name[0] == '.')
			continue;

		tid_it = atoi(entry->d_name);
		snprintf(path, sizeof(path), "/proc/%ld/task/%ld/comm", (long int)mypid, (long int) tid_it);
		if ((fd = open(path, O_RDONLY)) == -1)
			continue;
		rc = read(fd, buf, sizeof(buf) - 1);
		if (rc >= 0) {
			/* Last may char contain a '\n', get rid of it */
			if (rc > 0 && buf[rc - 1] == '\n')
				buf[rc - 1] = '\0';
			else
				buf[rc] = '\0';
			if (strcmp(name, buf) == 0) {
				*res_pid = tid_it;
				found = true;
			}
		}
		close(fd);

		if (found)
			break;
	}

	closedir(proc_dir);
	return found;
}

/* Parse VTY THREADNAME variable, return its type and fill discovered res_pid if required */
static enum sched_vty_thread_id procname2pid(pid_t *res_pid, const char *str, bool applynow)
{
	size_t i, len;
	char *end;
	bool is_pid = true;

	if (strcmp(str, "all") == 0) {
		*res_pid = 0;
		return SCHED_VTY_THREAD_ALL;
	}

	if (strcmp(str, "self") == 0) {
		*res_pid = 0;
		return SCHED_VTY_THREAD_SELF;
	}

	len = strlen(str);
	for (i = 0; i < len; i++) {
		if (!isdigit(str[i])) {
			is_pid = false;
			break;
		}
	}
	if (is_pid) {
		errno = 0;
		*res_pid = strtoul(str, &end, 0);
		if ((errno == ERANGE && *res_pid == ULONG_MAX) || (errno && !*res_pid) ||
		    str == end) {
			return SCHED_VTY_THREAD_UNKNOWN;
		}
		if (!applynow || proc_tid_exists(*res_pid))
			return SCHED_VTY_THREAD_ID;
		else
			return SCHED_VTY_THREAD_UNKNOWN;
	}

	if (len > 15) {
		/* Thread names only allow up to 15+1 null chars, see man pthread_setname_np */
		return SCHED_VTY_THREAD_UNKNOWN;
	}

	if (applynow) {
		if (proc_name_exists(str, res_pid))
			return SCHED_VTY_THREAD_NAME;
		else
			return SCHED_VTY_THREAD_UNKNOWN;
	} else  {
		/* assume a thread will be named after it */
		*res_pid = 0;
		return SCHED_VTY_THREAD_NAME;
	}
}

/* Wrapper for sched_setaffinity applying to single thread or all threads in process based on tid_type. */
static int my_sched_setaffinity(enum sched_vty_thread_id tid_type, pid_t pid,
				cpu_set_t *cpuset, size_t cpuset_size)
{
	DIR *proc_dir;
	struct dirent *entry;
	char dirname[100];
	char str_mask[1024];
	int tid_it;
	int rc = 0;

	if (generate_cpu_hex_mask(str_mask, sizeof(str_mask), cpuset, cpuset_size) < 0)
		str_mask[0] = '\0';

	if (tid_type != SCHED_VTY_THREAD_ALL) {
		LOGP(DLGLOBAL, LOGL_NOTICE, "Setting CPU affinity mask for tid %lu to: %s\n",
		     (unsigned long) pid, str_mask);

		rc = sched_setaffinity(pid, sizeof(cpu_set_t), cpuset);
		return rc;
	}

	snprintf(dirname, sizeof(dirname), "/proc/%ld/task", (long int)getpid());
	proc_dir = opendir(dirname);
	if (!proc_dir)
		return -EINVAL;

	while ((entry = readdir(proc_dir)))
	{
		if (entry->d_name[0] == '.')
			continue;
		tid_it = atoi(entry->d_name);
		LOGP(DLGLOBAL, LOGL_NOTICE, "Setting CPU affinity mask for tid %lu to: %s\n",
		     (unsigned long) tid_it, str_mask);

		rc = sched_setaffinity(tid_it, sizeof(cpu_set_t), cpuset);
		if (rc == -1)
			break;
	}

	closedir(proc_dir);
	return rc;

}

DEFUN(cfg_sched_cpu_affinity, cfg_sched_cpu_affinity_cmd,
	"cpu-affinity (self|all|<0-4294967295>|THREADNAME) CPUHEXMASK [delay]",
	"Set CPU affinity mask on a (group of) thread(s)\n"
	"Set CPU affinity mask on thread running the VTY\n"
	"Set CPU affinity mask on all process' threads\n"
	"Set CPU affinity mask on a thread with specified PID\n"
	"Set CPU affinity mask on a thread with specified thread name\n"
	"CPU affinity mask\n"
	"If set, delay applying the affinity mask now and let the app handle it at a later point\n")
{
	const char* str_who = argv[0];
	const char *str_mask = argv[1];
	bool applynow = (argc != 3);
	int rc;
	pid_t pid;
	enum sched_vty_thread_id tid_type;
	struct cpu_affinity_it *it, *it_next;
	cpu_set_t *cpuset;
	size_t cpuset_size;

	tid_type = procname2pid(&pid, str_who, applynow);
	if (tid_type == SCHED_VTY_THREAD_UNKNOWN) {
		vty_out(vty, "%% Failed parsing target thread %s%s",
		        str_who, VTY_NEWLINE);
		return CMD_WARNING;
	}

	if (tid_type == SCHED_VTY_THREAD_ID && !applynow)  {
		vty_out(vty, "%% It makes no sense to delay applying cpu-affinity on tid %lu%s",
			(unsigned long)pid, VTY_NEWLINE);
		return CMD_WARNING;
	}
	if (tid_type == SCHED_VTY_THREAD_ALL && !applynow)  {
		vty_out(vty, "%% It makes no sense to delay applying cpu-affinity on all threads%s",
			VTY_NEWLINE);
		return CMD_WARNING;
	}

	cpuset = CPU_ALLOC(get_num_cpus());
	cpuset_size = CPU_ALLOC_SIZE(get_num_cpus());
	if (parse_cpu_hex_mask(str_mask, cpuset, cpuset_size) < 0) {
		vty_out(vty, "%% Failed parsing CPU Affinity Mask %s%s",
		    str_mask, VTY_NEWLINE);
		CPU_FREE(cpuset);
		return CMD_WARNING;
	}

	if (applynow) {
		rc = my_sched_setaffinity(tid_type, pid, cpuset, cpuset_size);
		if (rc == -1) {
			vty_out(vty, "%% Failed setting sched CPU Affinity Mask %s: %s%s",
				str_mask, strerror(errno), VTY_NEWLINE);
			CPU_FREE(cpuset);
			return CMD_WARNING;
		}
	}

	/* Keep history of cmds applied to be able to rewrite config. If PID was passed
	   directly it makes no sense to store it since PIDs are temporary */
	if (tid_type == SCHED_VTY_THREAD_SELF ||
	    tid_type == SCHED_VTY_THREAD_ALL ||
	    tid_type == SCHED_VTY_THREAD_NAME) {
		pthread_mutex_lock(&sched_vty_opts->cpu_affinity_li_mutex);

		/* Drop previous entries matching, since they will be overwritten */
		llist_for_each_entry_safe(it, it_next, &sched_vty_opts->cpu_affinity_li, entry) {
			if (strcmp(it->bufname, str_who) == 0) {
				llist_del(&it->entry);
				CPU_FREE(it->cpuset);
				talloc_free(it);
				break;
			}
		}
		it = talloc_zero(sched_vty_opts->tall_ctx, struct cpu_affinity_it);
		OSMO_STRLCPY_ARRAY(it->bufname, str_who);
		it->tid_type = tid_type;
		it->cpuset = cpuset;
		it->cpuset_size = cpuset_size;
		it->delay = !applynow;
		llist_add_tail(&it->entry, &sched_vty_opts->cpu_affinity_li);

		pthread_mutex_unlock(&sched_vty_opts->cpu_affinity_li_mutex);
	} else {
		/* We don't need cpuset for later, free it: */
		CPU_FREE(cpuset);
	}
	return CMD_SUCCESS;
}

static int set_sched_rr(unsigned int prio)
{
	struct sched_param param;
	int rc;
	memset(&param, 0, sizeof(param));
	param.sched_priority = prio;
	LOGP(DLGLOBAL, LOGL_NOTICE, "Setting SCHED_RR priority %d\n", param.sched_priority);
	rc = sched_setscheduler(getpid(), SCHED_RR, &param);
	if (rc == -1) {
		LOGP(DLGLOBAL, LOGL_FATAL, "Setting SCHED_RR priority %d failed: %s\n",
		     param.sched_priority, strerror(errno));
		return -1;
	}
	return 0;
}

DEFUN(cfg_sched_policy, cfg_sched_policy_cmd,
	"policy rr <1-32>",
	"Set the scheduling policy to use for the process\n"
	"Use the SCHED_RR real-time scheduling algorithm\n"
	"Set the SCHED_RR real-time priority\n")
{
	sched_vty_opts->sched_rr_prio = atoi(argv[0]);

	if (set_sched_rr(sched_vty_opts->sched_rr_prio) < 0) {
		vty_out(vty, "%% Failed setting SCHED_RR priority %d%s",
			sched_vty_opts->sched_rr_prio, VTY_NEWLINE);
		return CMD_WARNING;
	}

	return CMD_SUCCESS;
}

DEFUN(cfg_sched,
      cfg_sched_cmd,
      "cpu-sched", "Configure CPU Scheduler related settings")
{
	vty->index = NULL;
	vty->node = L_CPU_SCHED_NODE;

	return CMD_SUCCESS;
}

DEFUN(show_sched_threads, show_sched_threads_cmd,
	"show cpu-sched threads",
	SHOW_STR
	"Show Sched section information\n"
	"Show information about running threads)\n")
{
	DIR *proc_dir;
	struct dirent *entry;
	char path[100];
	char name[17];
	char str_mask[1024];
	int tid_it;
	int fd;
	pid_t mypid = getpid();
	int rc;
	cpu_set_t *cpuset;
	size_t cpuset_size;

	vty_out(vty, "Thread list for PID %lu:%s", (unsigned long) mypid, VTY_NEWLINE);

	snprintf(path, sizeof(path), "/proc/%ld/task", (long int)mypid);
	proc_dir = opendir(path);
	if (!proc_dir) {
		vty_out(vty, "%% Failed opening dir%s%s", path, VTY_NEWLINE);
		return CMD_WARNING;
	}

	while ((entry = readdir(proc_dir)))
	{
		if (entry->d_name[0] == '.')
			continue;

		tid_it = atoi(entry->d_name);
		snprintf(path, sizeof(path), "/proc/%ld/task/%ld/comm", (long int)mypid, (long int)tid_it);
		if ((fd = open(path, O_RDONLY)) != -1) {
			rc = read(fd, name, sizeof(name) - 1);
			if (rc >= 0) {
				/* Last may char contain a '\n', get rid of it */
				if (rc > 0 && name[rc - 1] == '\n')
					name[rc - 1] = '\0';
				else
					name[rc] = '\0';
			}
			close(fd);
		} else {
			name[0] = '\0';
		}

		str_mask[0] = '\0';
		cpuset = CPU_ALLOC(get_num_cpus());
		cpuset_size = CPU_ALLOC_SIZE(get_num_cpus());
		CPU_ZERO_S(cpuset_size, cpuset);
		if (sched_getaffinity(tid_it, cpuset_size, cpuset) == 0) {
			if (generate_cpu_hex_mask(str_mask, sizeof(str_mask), cpuset, cpuset_size) < 0)
				str_mask[0] = '\0';
		}
		CPU_FREE(cpuset);

		vty_out(vty, " TID: %lu, NAME: '%s', cpu-affinity: %s%s",
			(unsigned long) tid_it, name, str_mask, VTY_NEWLINE);
	}

	closedir(proc_dir);
	return CMD_SUCCESS;
}

static int config_write_sched(struct vty *vty)
{
	struct cpu_affinity_it *it;
	char str_mask[1024];

	/* Only add the node if there's something to write under it */
	if (sched_vty_opts->sched_rr_prio || !llist_empty(&sched_vty_opts->cpu_affinity_li))
		vty_out(vty, "cpu-sched%s", VTY_NEWLINE);

	if (sched_vty_opts->sched_rr_prio)
		vty_out(vty, " policy rr %d%s", sched_vty_opts->sched_rr_prio, VTY_NEWLINE);

	llist_for_each_entry(it, &sched_vty_opts->cpu_affinity_li, entry) {
		if (generate_cpu_hex_mask(str_mask, sizeof(str_mask), it->cpuset, it->cpuset_size) < 0)
			OSMO_STRLCPY_ARRAY(str_mask, "ERROR");
		vty_out(vty, " cpu-affinity %s %s%s%s", it->bufname, str_mask,
			it->delay ? " delay" : "", VTY_NEWLINE);
	}

	return CMD_SUCCESS;
}

/*! Initialize sched VTY nodes
 * \param[in] tall_ctx  Talloc context to use internally by vty_sched subsystem.
 * \return 0 on success, non-zero on error.
 */
int osmo_cpu_sched_vty_init(void *tall_ctx)
{
	OSMO_ASSERT(!sched_vty_opts); /* assert only called once */

	sched_vty_opts = talloc_zero(tall_ctx, struct sched_vty_opts);
	sched_vty_opts->tall_ctx = tall_ctx;
	INIT_LLIST_HEAD(&sched_vty_opts->cpu_affinity_li);
	pthread_mutex_init(&sched_vty_opts->cpu_affinity_li_mutex, NULL);

	install_element(CONFIG_NODE, &cfg_sched_cmd);
	install_node(&sched_node, config_write_sched);

	install_element(L_CPU_SCHED_NODE, &cfg_sched_policy_cmd);
	install_element(L_CPU_SCHED_NODE, &cfg_sched_cpu_affinity_cmd);

	install_element_ve(&show_sched_threads_cmd);

	/* Initialize amount of cpus now */
	if (get_num_cpus() < 0)
		return -1;

	return 0;
}

/*! Apply cpu-affinity on calling thread based on VTY configuration
 * \return 0 on success, non-zero on error.
 */
int osmo_cpu_sched_vty_apply_localthread(void)
{
	struct cpu_affinity_it *it, *it_match = NULL;
	char name[16];  /* 15 + \0 */
	char str_mask[1024];
	bool has_name = false;
	int rc = 0;

	/* Assert subsystem was inited and structs are preset */
	OSMO_ASSERT(sched_vty_opts);

	if (pthread_getname_np(pthread_self(), name, sizeof(name)) == 0)
		has_name = true;

	/* Get latest matching mask for the thread */
	pthread_mutex_lock(&sched_vty_opts->cpu_affinity_li_mutex);
	llist_for_each_entry(it, &sched_vty_opts->cpu_affinity_li, entry) {
		switch (it->tid_type) {
		case SCHED_VTY_THREAD_SELF:
			continue; /* self to the VTY thread, not us */
		case SCHED_VTY_THREAD_ALL:
			it_match = it;
			break;
		case SCHED_VTY_THREAD_NAME:
			if (!has_name)
				continue;
			if (strcmp(name, it->bufname) != 0)
				continue;
			it_match = it;
			break;
		default:
			OSMO_ASSERT(0);
		}
	}

	if (it_match) {
		rc = my_sched_setaffinity(SCHED_VTY_THREAD_SELF, 0, it_match->cpuset, it_match->cpuset_size);
		if (rc == -1) {
			if (generate_cpu_hex_mask(str_mask, sizeof(str_mask),
						  it_match->cpuset, it_match->cpuset_size) < 0)
				str_mask[0] = '\0';
			LOGP(DLGLOBAL, LOGL_FATAL, "Setting cpu-affinity mask %s failed: %s\n",
			     str_mask, strerror(errno));
		}
	}
	pthread_mutex_unlock(&sched_vty_opts->cpu_affinity_li_mutex);
	return rc;
}

/*! @} */