History

bpf: Implement bpf_link-based cgroup BPF program attachment

Implement new sub-command to attach cgroup BPF programs and return FD-based bpf_link back on success. bpf_link, once attached to cgroup, cannot be replaced, except by owner having its FD. Cgroup bpf_link supports only BPF_F_ALLOW_MULTI semantics. Both link-based and prog-based BPF_F_ALLOW_MULTI attachments can be freely intermixed. To prevent bpf_cgroup_link from keeping cgroup alive past the point when no BPF program can be executed, implement auto-detachment of link. When cgroup_bpf_release() is called, all attached bpf_links are forced to release cgroup refcounts, but they leave bpf_link otherwise active and allocated, as well as still owning underlying bpf_prog. This is because user-space might still have FDs open and active, so bpf_link as a user-referenced object can't be freed yet. Once last active FD is closed, bpf_link will be freed and underlying bpf_prog refcount will be dropped. But cgroup refcount won't be touched, because cgroup is released already. The inherent race between bpf_cgroup_link release (from closing last FD) and cgroup_bpf_release() is resolved by both operations taking cgroup_mutex. So the only additional check required is when bpf_cgroup_link attempts to detach itself from cgroup. At that time we need to check whether there is still cgroup associated with that link. And if not, exit with success, because bpf_cgroup_link was already successfully detached.

Andrii Nakryiko committed 6 years ago

Commit af6eea51 parent e5ffcc97 files · +354 −98Browse files

Showing the changes to include/uapi/linux (1 of 7 files). Show all

Unified · Split

include/uapi/linux/bpf.h+9−1
@@ -111,6 +111,7 @@ enum bpf_cmd { · 110 unmodified lines
111111 BPF_MAP_LOOKUP_AND_DELETE_BATCH,
112112 BPF_MAP_UPDATE_BATCH,
113113 BPF_MAP_DELETE_BATCH,
114+ BPF_LINK_CREATE,
114115 };
115116
116117 enum bpf_map_type {
@@ -541,7 +542,7 @@ union bpf_attr { · 424 unmodified lines
541542 __u32 prog_cnt;
542543 } query;
543544
544− struct {
545+ struct { /* anonymous struct used by BPF_RAW_TRACEPOINT_OPEN command */
545546 __u64 name;
546547 __u32 prog_fd;
547548 } raw_tracepoint;
@@ -569,6 +570,13 @@ union bpf_attr { · 21 unmodified lines
569570 __u64 probe_offset; /* output: probe_offset */
570571 __u64 probe_addr; /* output: probe_addr */
571572 } task_fd_query;
573+
574+ struct { /* struct used by BPF_LINK_CREATE command */
575+ __u32 prog_fd; /* eBPF program to attach */
576+ __u32 target_fd; /* object to attach to */
577+ __u32 attach_type; /* attach type */
578+ __u32 flags; /* extra flags */
579+ } link_create;
572580 } __attribute__((aligned(8)));
573581
574582 /* The description below is an attempt at providing documentation to eBPF