Starvation possible in futexes 8(
PATCH 1/1 Starvation possible in futexes 8(
Due to a bug (spotted by Anton) in my "starve.c" code, it wasn't working properly.
Testing it properly, as below, shows how easy it is to starve someone on SMP in the case of an extremely rapid release and reaquisition of a lock. Even doing a yield() in the up case doesn't help, if they are scheduled on a different CPU.
I tried waiting for the woken task to ack, but I think it's better to return to Hubertus' FUTEX_UP_FAIR. Updated and attached (untested).
Thoughts?
Rusty.
--
Anyone who quotes me in their sig is an idiot. -- Rusty Russell.
include/linux/futex.h +1 -0
@@ -4,5 +4,6 @@/* Second argument to futex syscall */ #define FUTEX_UP (0)#define FUTEX_DOWN (1) +#define FUTEX_UP_FAIR (2)#endif
kernel/futex.c +36 -11
96 lines not on this page · raw message
================
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/time.h>
#include <time.h>
#include <signal.h>
#include <sched.h>
#include "usersem.h"
#ifndef PROT_SEM
#define PROT_SEM 0x8
#endif
static void spinner(struct futex *sem, int hold)
{
while (1) {
futex_down(sem);
if (hold) sleep(1);
futex_up(sem);
}
}/* Test maximum time to lock given furious spinners. */ int main(int argc, char *argv[])
{
struct futex *sem;
unsigned int i;
unsigned long maxtime = 0;
int fd;
pid_t children[100];
if (argc != 4) {
fprintf(stderr, "Usage: starve <file> <numspinners> <iterations>\n");
exit(1);
}
fd = open(argv[1], O_RDWR);
if (fd < 0) {
perror("opening file");
exit(1);
}
sem = mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (sem == MAP_FAILED) {
perror("mmap");
exit(1);
}
if (futex_region(sem, 4096) != 0) {
perror("futex_region");
exit(1);
}
futex_init(sem);
for (i = 0; i < atoi(argv[2]); i++) {
children[i] = fork();
if (children[i] == 0)
spinner(sem, 1);
}
for (i = 0; i < atoi(argv[3]); i++) {
struct timeval start, end, diff;
sleep(1);
gettimeofday(&start, NULL);
futex_down(sem);
gettimeofday(&end, NULL);
futex_up(sem);
timersub(&end, &start, &diff);
printf("Wait time: %lu.%06lu\n", diff.tv_sec, diff.tv_usec);
if (diff.tv_sec * 1000000 + diff.tv_usec > maxtime)
maxtime = diff.tv_sec * 1000000 + diff.tv_usec;
}
/* Kill children */
for (i = 0; i < atoi(argv[2]); i++)
kill(children[i], SIGTERM);
printf("Worst case: %lu\n", maxtime);
exit(0);
}