summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBen Gamari <ben@smart-cactus.org>2020-10-22 12:02:58 -0400
committerBen Gamari <ben@well-typed.com>2020-12-01 12:48:53 -0500
commit68e93f4dc8c55737df57d84e814e849beb2e366c (patch)
tree1621de5951aced859e7d2fa0b2d0451d2edc7e49
parent914196db5d1e0709f3707fcbdfdfe7ac7bd74e3a (diff)
downloadhaskell-68e93f4dc8c55737df57d84e814e849beb2e366c.tar.gz
Capabiliity: Properly fix data race on n_returning_tasks
There is a real data race but can be made safe by using proper atomic (but relaxed) accesses.
-rw-r--r--includes/stg/SMP.h1
-rw-r--r--rts/Capability.c10
-rw-r--r--rts/Schedule.c9
3 files changed, 16 insertions, 4 deletions
diff --git a/includes/stg/SMP.h b/includes/stg/SMP.h
index 2a3e7308ef..ad1303c9e3 100644
--- a/includes/stg/SMP.h
+++ b/includes/stg/SMP.h
@@ -440,6 +440,7 @@ load_load_barrier(void) {
// Relaxed atomic operations.
#define RELAXED_LOAD(ptr) __atomic_load_n(ptr, __ATOMIC_RELAXED)
#define RELAXED_STORE(ptr,val) __atomic_store_n(ptr, val, __ATOMIC_RELAXED)
+#define RELAXED_ADD(ptr,val) __atomic_add_fetch(ptr, val, __ATOMIC_RELAXED)
// Acquire/release atomic operations
#define ACQUIRE_LOAD(ptr) __atomic_load_n(ptr, __ATOMIC_ACQUIRE)
diff --git a/rts/Capability.c b/rts/Capability.c
index be337da0da..43a69683e8 100644
--- a/rts/Capability.c
+++ b/rts/Capability.c
@@ -213,7 +213,10 @@ newReturningTask (Capability *cap, Task *task)
cap->returning_tasks_hd = task;
}
cap->returning_tasks_tl = task;
- cap->n_returning_tasks++;
+
+ // See Note [Data race in shouldYieldCapability] in Schedule.c.
+ RELAXED_ADD(&cap->n_returning_tasks, 1);
+
ASSERT_RETURNING_TASKS(cap,task);
}
@@ -229,7 +232,10 @@ popReturningTask (Capability *cap)
cap->returning_tasks_tl = NULL;
}
task->next = NULL;
- cap->n_returning_tasks--;
+
+ // See Note [Data race in shouldYieldCapability] in Schedule.c.
+ RELAXED_ADD(&cap->n_returning_tasks, -1);
+
ASSERT_RETURNING_TASKS(cap,task);
return task;
}
diff --git a/rts/Schedule.c b/rts/Schedule.c
index da8ba223c2..11e725b9ab 100644
--- a/rts/Schedule.c
+++ b/rts/Schedule.c
@@ -637,9 +637,14 @@ shouldYieldCapability (Capability *cap, Task *task, bool didGcLast)
// Capability keeps forcing a GC and the other Capabilities make no
// progress at all.
+ // Note [Data race in shouldYieldCapability]
+ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// We would usually need to hold cap->lock to look at n_returning_tasks but
- // we don't here since this is just an approximate predicate.
- TSAN_ANNOTATE_BENIGN_RACE(&cap->n_returning_tasks, "shouldYieldCapability");
+ // we don't here since this is just an approximate predicate. We
+ // consequently need to use atomic accesses whenever touching
+ // n_returning_tasks. However, since this is an approximate predicate we can
+ // use a RELAXED ordering.
+
return ((RELAXED_LOAD(&pending_sync) && !didGcLast) ||
RELAXED_LOAD(&cap->n_returning_tasks) != 0 ||
(!emptyRunQueue(cap) && (task->incall->tso == NULL