bpf: fix cgroup bpf release synchronization
authorRoman Gushchin <guro@fb.com>
Tue, 25 Jun 2019 21:38:58 +0000 (14:38 -0700)
committerDaniel Borkmann <daniel@iogearbox.net>
Thu, 27 Jun 2019 20:51:58 +0000 (22:51 +0200)
commite5c891a349d7c556b7b9dc231d6dd78e88a29e5c
tree34f2beb6de8bd858648246c32db562c26a00c390
parent572a6928f9e3689ad2c2f94814e6215104eec1b7
bpf: fix cgroup bpf release synchronization

Since commit 4bfc0bb2c60e ("bpf: decouple the lifetime of cgroup_bpf
from cgroup itself"), cgroup_bpf release occurs asynchronously
(from a worker context), and before the release of the cgroup itself.

This introduced a previously non-existing race between the release
and update paths. E.g. if a leaf's cgroup_bpf is released and a new
bpf program is attached to the one of ancestor cgroups at the same
time. The race may result in double-free and other memory corruptions.

To fix the problem, let's protect the body of cgroup_bpf_release()
with cgroup_mutex, as it was effectively previously, when all this
code was called from the cgroup release path with cgroup mutex held.

Also let's skip cgroups, which have no chances to invoke a bpf
program, on the update path. If the cgroup bpf refcnt reached 0,
it means that the cgroup is offline (no attached processes), and
there are no associated sockets left. It means there is no point
in updating effective progs array! And it can lead to a leak,
if it happens after the release. So, let's skip such cgroups.

Big thanks for Tejun Heo for discovering and debugging of this problem!

Fixes: 4bfc0bb2c60e ("bpf: decouple the lifetime of cgroup_bpf from cgroup itself")
Reported-by: Tejun Heo <tj@kernel.org>
Signed-off-by: Roman Gushchin <guro@fb.com>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Daniel Borkmann <daniel@iogearbox.net>
kernel/bpf/cgroup.c