Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save alessandrocarminati/d77049d283d0ffe15fc01f825c703651 to your computer and use it in GitHub Desktop.
Save alessandrocarminati/d77049d283d0ffe15fc01f825c703651 to your computer and use it in GitHub Desktop.
resctrl_cache_alloc.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/stat.h>
#include <regex.h>
#define MAX_BUFFER_SIZE 512
int main(int argc, char *argv[]) {
char rest[MAX_BUFFER_SIZE]={0};
char format[MAX_BUFFER_SIZE];
char buffer[MAX_BUFFER_SIZE];
char hex[MAX_BUFFER_SIZE];
unsigned long mask = 1;
regmatch_t pmatch[3];
unsigned long number;
unsigned long num;
int count = 0;
regex_t regex;
char *errc;
FILE *file;
FILE *out;
int reti;
int pid;
if (argc != 2) {
printf("Usage: %s <pid>\n", argv[0]);
return -1;
}
pid = strtol(argv[1], &errc, 10);
if (pid ==0) {
perror("Pid is supposed to be a number\n");
return -1;
}
if (kill(pid, 0) == -1) {
perror("Pid not running");
return -1;
}
file = fopen("/sys/fs/resctrl/schemata", "r");
if (file == NULL) {
perror("Failed to access /sys/fs/resctrl/schemata\n is resctrl filesystem mounted?\n try: mount -t resctrl resctrl /sys/fs/resctrl");
return -1;
}
while (fgets(buffer, sizeof(buffer), file)) {
reti = regcomp(&regex, "L3:[0-9]+=([0-9a-f]+)(.*)\n", REG_EXTENDED);
if (reti) {
fprintf(stderr, "Could not compile regex\n");
return -1;
}
reti = regexec(&regex, buffer, 3, pmatch, 0);
if (!reti) {
memcpy(hex, buffer + pmatch[1].rm_so, pmatch[1].rm_eo - pmatch[1].rm_so);
printf("0 start=%d, len=%d\n", pmatch[0].rm_so, pmatch[0].rm_eo);
printf("1 start=%d, len=%d\n", pmatch[1].rm_so, pmatch[1].rm_eo);
printf("2 start=%d, len=%d\n", pmatch[2].rm_so, pmatch[2].rm_eo);
memcpy(rest, buffer + pmatch[2].rm_so, pmatch[2].rm_eo - pmatch[2].rm_so);
printf("but=%s, the rest='%s'\n", buffer, rest);
hex[pmatch[1].rm_eo - pmatch[1].rm_so] = '\0';
num = strtoul(hex, NULL, 16);
while (mask !=0 ) {
if (num & mask) count++;
mask <<= 1;
}
number = (1UL << (count / 2)) - 1;
printf("%d\n", snprintf(format, sizeof(format), "L3:0=%%0%dlx%%s\n", count / 4));
printf("%s\n", format);
printf("restricting PID %d to socket0 and allocate 50%% of the cache to it\n", pid);
mkdir("/sys/fs/resctrl/1", 0666);
out = fopen("/sys/fs/resctrl/schemata", "w+");
fprintf(out, format, num - number, rest);
fclose(out);
out = fopen("/sys/fs/resctrl/1/schemata", "w+");
fprintf(out, format, number, rest);
fclose(out);
out = fopen("/sys/fs/resctrl/1/tasks", "w+");
fprintf(out, "%d\n", pid);
fclose(out);
regfree(&regex);
fclose(file);
return 0;
}
regfree(&regex);
}
printf("No matching line found in schemata\n");
fclose(file);
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment