Linux Audio

Check our new training course

Loading...
v6.2
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3 * Functions to manage eBPF programs attached to cgroups
   4 *
   5 * Copyright (c) 2016 Daniel Mack
   6 */
   7
   8#include <linux/kernel.h>
   9#include <linux/atomic.h>
  10#include <linux/cgroup.h>
  11#include <linux/filter.h>
  12#include <linux/slab.h>
  13#include <linux/sysctl.h>
  14#include <linux/string.h>
  15#include <linux/bpf.h>
  16#include <linux/bpf-cgroup.h>
  17#include <linux/bpf_lsm.h>
  18#include <linux/bpf_verifier.h>
  19#include <net/sock.h>
  20#include <net/bpf_sk_storage.h>
  21
  22#include "../cgroup/cgroup-internal.h"
  23
  24DEFINE_STATIC_KEY_ARRAY_FALSE(cgroup_bpf_enabled_key, MAX_CGROUP_BPF_ATTACH_TYPE);
  25EXPORT_SYMBOL(cgroup_bpf_enabled_key);
  26
  27/* __always_inline is necessary to prevent indirect call through run_prog
  28 * function pointer.
  29 */
  30static __always_inline int
  31bpf_prog_run_array_cg(const struct cgroup_bpf *cgrp,
  32		      enum cgroup_bpf_attach_type atype,
  33		      const void *ctx, bpf_prog_run_fn run_prog,
  34		      int retval, u32 *ret_flags)
  35{
  36	const struct bpf_prog_array_item *item;
  37	const struct bpf_prog *prog;
  38	const struct bpf_prog_array *array;
  39	struct bpf_run_ctx *old_run_ctx;
  40	struct bpf_cg_run_ctx run_ctx;
  41	u32 func_ret;
  42
  43	run_ctx.retval = retval;
  44	migrate_disable();
  45	rcu_read_lock();
  46	array = rcu_dereference(cgrp->effective[atype]);
  47	item = &array->items[0];
  48	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
  49	while ((prog = READ_ONCE(item->prog))) {
  50		run_ctx.prog_item = item;
  51		func_ret = run_prog(prog, ctx);
  52		if (ret_flags) {
  53			*(ret_flags) |= (func_ret >> 1);
  54			func_ret &= 1;
  55		}
  56		if (!func_ret && !IS_ERR_VALUE((long)run_ctx.retval))
  57			run_ctx.retval = -EPERM;
  58		item++;
  59	}
  60	bpf_reset_run_ctx(old_run_ctx);
  61	rcu_read_unlock();
  62	migrate_enable();
  63	return run_ctx.retval;
  64}
  65
  66unsigned int __cgroup_bpf_run_lsm_sock(const void *ctx,
  67				       const struct bpf_insn *insn)
  68{
  69	const struct bpf_prog *shim_prog;
  70	struct sock *sk;
  71	struct cgroup *cgrp;
  72	int ret = 0;
  73	u64 *args;
  74
  75	args = (u64 *)ctx;
  76	sk = (void *)(unsigned long)args[0];
  77	/*shim_prog = container_of(insn, struct bpf_prog, insnsi);*/
  78	shim_prog = (const struct bpf_prog *)((void *)insn - offsetof(struct bpf_prog, insnsi));
  79
  80	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
  81	if (likely(cgrp))
  82		ret = bpf_prog_run_array_cg(&cgrp->bpf,
  83					    shim_prog->aux->cgroup_atype,
  84					    ctx, bpf_prog_run, 0, NULL);
  85	return ret;
  86}
  87
  88unsigned int __cgroup_bpf_run_lsm_socket(const void *ctx,
  89					 const struct bpf_insn *insn)
  90{
  91	const struct bpf_prog *shim_prog;
  92	struct socket *sock;
  93	struct cgroup *cgrp;
  94	int ret = 0;
  95	u64 *args;
  96
  97	args = (u64 *)ctx;
  98	sock = (void *)(unsigned long)args[0];
  99	/*shim_prog = container_of(insn, struct bpf_prog, insnsi);*/
 100	shim_prog = (const struct bpf_prog *)((void *)insn - offsetof(struct bpf_prog, insnsi));
 101
 102	cgrp = sock_cgroup_ptr(&sock->sk->sk_cgrp_data);
 103	if (likely(cgrp))
 104		ret = bpf_prog_run_array_cg(&cgrp->bpf,
 105					    shim_prog->aux->cgroup_atype,
 106					    ctx, bpf_prog_run, 0, NULL);
 107	return ret;
 108}
 109
 110unsigned int __cgroup_bpf_run_lsm_current(const void *ctx,
 111					  const struct bpf_insn *insn)
 112{
 113	const struct bpf_prog *shim_prog;
 114	struct cgroup *cgrp;
 115	int ret = 0;
 116
 117	/*shim_prog = container_of(insn, struct bpf_prog, insnsi);*/
 118	shim_prog = (const struct bpf_prog *)((void *)insn - offsetof(struct bpf_prog, insnsi));
 119
 120	/* We rely on trampoline's __bpf_prog_enter_lsm_cgroup to grab RCU read lock. */
 121	cgrp = task_dfl_cgroup(current);
 122	if (likely(cgrp))
 123		ret = bpf_prog_run_array_cg(&cgrp->bpf,
 124					    shim_prog->aux->cgroup_atype,
 125					    ctx, bpf_prog_run, 0, NULL);
 126	return ret;
 127}
 128
 129#ifdef CONFIG_BPF_LSM
 130struct cgroup_lsm_atype {
 131	u32 attach_btf_id;
 132	int refcnt;
 133};
 134
 135static struct cgroup_lsm_atype cgroup_lsm_atype[CGROUP_LSM_NUM];
 136
 137static enum cgroup_bpf_attach_type
 138bpf_cgroup_atype_find(enum bpf_attach_type attach_type, u32 attach_btf_id)
 139{
 140	int i;
 141
 142	lockdep_assert_held(&cgroup_mutex);
 143
 144	if (attach_type != BPF_LSM_CGROUP)
 145		return to_cgroup_bpf_attach_type(attach_type);
 146
 147	for (i = 0; i < ARRAY_SIZE(cgroup_lsm_atype); i++)
 148		if (cgroup_lsm_atype[i].attach_btf_id == attach_btf_id)
 149			return CGROUP_LSM_START + i;
 150
 151	for (i = 0; i < ARRAY_SIZE(cgroup_lsm_atype); i++)
 152		if (cgroup_lsm_atype[i].attach_btf_id == 0)
 153			return CGROUP_LSM_START + i;
 154
 155	return -E2BIG;
 156
 157}
 158
 159void bpf_cgroup_atype_get(u32 attach_btf_id, int cgroup_atype)
 160{
 161	int i = cgroup_atype - CGROUP_LSM_START;
 162
 163	lockdep_assert_held(&cgroup_mutex);
 164
 165	WARN_ON_ONCE(cgroup_lsm_atype[i].attach_btf_id &&
 166		     cgroup_lsm_atype[i].attach_btf_id != attach_btf_id);
 167
 168	cgroup_lsm_atype[i].attach_btf_id = attach_btf_id;
 169	cgroup_lsm_atype[i].refcnt++;
 170}
 171
 172void bpf_cgroup_atype_put(int cgroup_atype)
 173{
 174	int i = cgroup_atype - CGROUP_LSM_START;
 175
 176	mutex_lock(&cgroup_mutex);
 177	if (--cgroup_lsm_atype[i].refcnt <= 0)
 178		cgroup_lsm_atype[i].attach_btf_id = 0;
 179	WARN_ON_ONCE(cgroup_lsm_atype[i].refcnt < 0);
 180	mutex_unlock(&cgroup_mutex);
 181}
 182#else
 183static enum cgroup_bpf_attach_type
 184bpf_cgroup_atype_find(enum bpf_attach_type attach_type, u32 attach_btf_id)
 185{
 186	if (attach_type != BPF_LSM_CGROUP)
 187		return to_cgroup_bpf_attach_type(attach_type);
 188	return -EOPNOTSUPP;
 189}
 190#endif /* CONFIG_BPF_LSM */
 191
 192void cgroup_bpf_offline(struct cgroup *cgrp)
 193{
 194	cgroup_get(cgrp);
 195	percpu_ref_kill(&cgrp->bpf.refcnt);
 196}
 197
 198static void bpf_cgroup_storages_free(struct bpf_cgroup_storage *storages[])
 199{
 200	enum bpf_cgroup_storage_type stype;
 201
 202	for_each_cgroup_storage_type(stype)
 203		bpf_cgroup_storage_free(storages[stype]);
 204}
 205
 206static int bpf_cgroup_storages_alloc(struct bpf_cgroup_storage *storages[],
 207				     struct bpf_cgroup_storage *new_storages[],
 208				     enum bpf_attach_type type,
 209				     struct bpf_prog *prog,
 210				     struct cgroup *cgrp)
 211{
 212	enum bpf_cgroup_storage_type stype;
 213	struct bpf_cgroup_storage_key key;
 214	struct bpf_map *map;
 215
 216	key.cgroup_inode_id = cgroup_id(cgrp);
 217	key.attach_type = type;
 218
 219	for_each_cgroup_storage_type(stype) {
 220		map = prog->aux->cgroup_storage[stype];
 221		if (!map)
 222			continue;
 223
 224		storages[stype] = cgroup_storage_lookup((void *)map, &key, false);
 225		if (storages[stype])
 226			continue;
 227
 228		storages[stype] = bpf_cgroup_storage_alloc(prog, stype);
 229		if (IS_ERR(storages[stype])) {
 230			bpf_cgroup_storages_free(new_storages);
 231			return -ENOMEM;
 232		}
 233
 234		new_storages[stype] = storages[stype];
 235	}
 236
 237	return 0;
 238}
 239
 240static void bpf_cgroup_storages_assign(struct bpf_cgroup_storage *dst[],
 241				       struct bpf_cgroup_storage *src[])
 242{
 243	enum bpf_cgroup_storage_type stype;
 244
 245	for_each_cgroup_storage_type(stype)
 246		dst[stype] = src[stype];
 247}
 248
 249static void bpf_cgroup_storages_link(struct bpf_cgroup_storage *storages[],
 250				     struct cgroup *cgrp,
 251				     enum bpf_attach_type attach_type)
 252{
 253	enum bpf_cgroup_storage_type stype;
 254
 255	for_each_cgroup_storage_type(stype)
 256		bpf_cgroup_storage_link(storages[stype], cgrp, attach_type);
 257}
 258
 259/* Called when bpf_cgroup_link is auto-detached from dying cgroup.
 260 * It drops cgroup and bpf_prog refcounts, and marks bpf_link as defunct. It
 261 * doesn't free link memory, which will eventually be done by bpf_link's
 262 * release() callback, when its last FD is closed.
 263 */
 264static void bpf_cgroup_link_auto_detach(struct bpf_cgroup_link *link)
 265{
 266	cgroup_put(link->cgroup);
 267	link->cgroup = NULL;
 268}
 269
 270/**
 271 * cgroup_bpf_release() - put references of all bpf programs and
 272 *                        release all cgroup bpf data
 273 * @work: work structure embedded into the cgroup to modify
 274 */
 275static void cgroup_bpf_release(struct work_struct *work)
 276{
 277	struct cgroup *p, *cgrp = container_of(work, struct cgroup,
 278					       bpf.release_work);
 279	struct bpf_prog_array *old_array;
 280	struct list_head *storages = &cgrp->bpf.storages;
 281	struct bpf_cgroup_storage *storage, *stmp;
 282
 283	unsigned int atype;
 284
 285	mutex_lock(&cgroup_mutex);
 286
 287	for (atype = 0; atype < ARRAY_SIZE(cgrp->bpf.progs); atype++) {
 288		struct hlist_head *progs = &cgrp->bpf.progs[atype];
 289		struct bpf_prog_list *pl;
 290		struct hlist_node *pltmp;
 291
 292		hlist_for_each_entry_safe(pl, pltmp, progs, node) {
 293			hlist_del(&pl->node);
 294			if (pl->prog) {
 295				if (pl->prog->expected_attach_type == BPF_LSM_CGROUP)
 296					bpf_trampoline_unlink_cgroup_shim(pl->prog);
 297				bpf_prog_put(pl->prog);
 298			}
 299			if (pl->link) {
 300				if (pl->link->link.prog->expected_attach_type == BPF_LSM_CGROUP)
 301					bpf_trampoline_unlink_cgroup_shim(pl->link->link.prog);
 302				bpf_cgroup_link_auto_detach(pl->link);
 303			}
 304			kfree(pl);
 305			static_branch_dec(&cgroup_bpf_enabled_key[atype]);
 306		}
 307		old_array = rcu_dereference_protected(
 308				cgrp->bpf.effective[atype],
 309				lockdep_is_held(&cgroup_mutex));
 310		bpf_prog_array_free(old_array);
 311	}
 312
 313	list_for_each_entry_safe(storage, stmp, storages, list_cg) {
 314		bpf_cgroup_storage_unlink(storage);
 315		bpf_cgroup_storage_free(storage);
 316	}
 317
 318	mutex_unlock(&cgroup_mutex);
 319
 320	for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
 321		cgroup_bpf_put(p);
 322
 323	percpu_ref_exit(&cgrp->bpf.refcnt);
 324	cgroup_put(cgrp);
 325}
 326
 327/**
 328 * cgroup_bpf_release_fn() - callback used to schedule releasing
 329 *                           of bpf cgroup data
 330 * @ref: percpu ref counter structure
 331 */
 332static void cgroup_bpf_release_fn(struct percpu_ref *ref)
 333{
 334	struct cgroup *cgrp = container_of(ref, struct cgroup, bpf.refcnt);
 335
 336	INIT_WORK(&cgrp->bpf.release_work, cgroup_bpf_release);
 337	queue_work(system_wq, &cgrp->bpf.release_work);
 338}
 339
 340/* Get underlying bpf_prog of bpf_prog_list entry, regardless if it's through
 341 * link or direct prog.
 342 */
 343static struct bpf_prog *prog_list_prog(struct bpf_prog_list *pl)
 344{
 345	if (pl->prog)
 346		return pl->prog;
 347	if (pl->link)
 348		return pl->link->link.prog;
 349	return NULL;
 350}
 351
 352/* count number of elements in the list.
 353 * it's slow but the list cannot be long
 354 */
 355static u32 prog_list_length(struct hlist_head *head)
 356{
 357	struct bpf_prog_list *pl;
 358	u32 cnt = 0;
 359
 360	hlist_for_each_entry(pl, head, node) {
 361		if (!prog_list_prog(pl))
 362			continue;
 363		cnt++;
 364	}
 365	return cnt;
 366}
 367
 368/* if parent has non-overridable prog attached,
 369 * disallow attaching new programs to the descendent cgroup.
 370 * if parent has overridable or multi-prog, allow attaching
 371 */
 372static bool hierarchy_allows_attach(struct cgroup *cgrp,
 373				    enum cgroup_bpf_attach_type atype)
 374{
 375	struct cgroup *p;
 376
 377	p = cgroup_parent(cgrp);
 378	if (!p)
 379		return true;
 380	do {
 381		u32 flags = p->bpf.flags[atype];
 382		u32 cnt;
 383
 384		if (flags & BPF_F_ALLOW_MULTI)
 385			return true;
 386		cnt = prog_list_length(&p->bpf.progs[atype]);
 387		WARN_ON_ONCE(cnt > 1);
 388		if (cnt == 1)
 389			return !!(flags & BPF_F_ALLOW_OVERRIDE);
 390		p = cgroup_parent(p);
 391	} while (p);
 392	return true;
 393}
 394
 395/* compute a chain of effective programs for a given cgroup:
 396 * start from the list of programs in this cgroup and add
 397 * all parent programs.
 398 * Note that parent's F_ALLOW_OVERRIDE-type program is yielding
 399 * to programs in this cgroup
 400 */
 401static int compute_effective_progs(struct cgroup *cgrp,
 402				   enum cgroup_bpf_attach_type atype,
 403				   struct bpf_prog_array **array)
 404{
 405	struct bpf_prog_array_item *item;
 406	struct bpf_prog_array *progs;
 407	struct bpf_prog_list *pl;
 408	struct cgroup *p = cgrp;
 409	int cnt = 0;
 410
 411	/* count number of effective programs by walking parents */
 412	do {
 413		if (cnt == 0 || (p->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
 414			cnt += prog_list_length(&p->bpf.progs[atype]);
 415		p = cgroup_parent(p);
 416	} while (p);
 417
 418	progs = bpf_prog_array_alloc(cnt, GFP_KERNEL);
 419	if (!progs)
 420		return -ENOMEM;
 421
 422	/* populate the array with effective progs */
 423	cnt = 0;
 424	p = cgrp;
 425	do {
 426		if (cnt > 0 && !(p->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
 427			continue;
 428
 429		hlist_for_each_entry(pl, &p->bpf.progs[atype], node) {
 430			if (!prog_list_prog(pl))
 431				continue;
 432
 433			item = &progs->items[cnt];
 434			item->prog = prog_list_prog(pl);
 435			bpf_cgroup_storages_assign(item->cgroup_storage,
 436						   pl->storage);
 437			cnt++;
 438		}
 439	} while ((p = cgroup_parent(p)));
 440
 441	*array = progs;
 442	return 0;
 443}
 444
 445static void activate_effective_progs(struct cgroup *cgrp,
 446				     enum cgroup_bpf_attach_type atype,
 447				     struct bpf_prog_array *old_array)
 448{
 449	old_array = rcu_replace_pointer(cgrp->bpf.effective[atype], old_array,
 450					lockdep_is_held(&cgroup_mutex));
 451	/* free prog array after grace period, since __cgroup_bpf_run_*()
 452	 * might be still walking the array
 453	 */
 454	bpf_prog_array_free(old_array);
 455}
 456
 457/**
 458 * cgroup_bpf_inherit() - inherit effective programs from parent
 459 * @cgrp: the cgroup to modify
 460 */
 461int cgroup_bpf_inherit(struct cgroup *cgrp)
 462{
 463/* has to use marco instead of const int, since compiler thinks
 464 * that array below is variable length
 465 */
 466#define	NR ARRAY_SIZE(cgrp->bpf.effective)
 467	struct bpf_prog_array *arrays[NR] = {};
 468	struct cgroup *p;
 469	int ret, i;
 470
 471	ret = percpu_ref_init(&cgrp->bpf.refcnt, cgroup_bpf_release_fn, 0,
 472			      GFP_KERNEL);
 473	if (ret)
 474		return ret;
 475
 476	for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
 477		cgroup_bpf_get(p);
 478
 479	for (i = 0; i < NR; i++)
 480		INIT_HLIST_HEAD(&cgrp->bpf.progs[i]);
 481
 482	INIT_LIST_HEAD(&cgrp->bpf.storages);
 483
 484	for (i = 0; i < NR; i++)
 485		if (compute_effective_progs(cgrp, i, &arrays[i]))
 486			goto cleanup;
 487
 488	for (i = 0; i < NR; i++)
 489		activate_effective_progs(cgrp, i, arrays[i]);
 490
 491	return 0;
 492cleanup:
 493	for (i = 0; i < NR; i++)
 494		bpf_prog_array_free(arrays[i]);
 495
 496	for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
 497		cgroup_bpf_put(p);
 498
 499	percpu_ref_exit(&cgrp->bpf.refcnt);
 500
 501	return -ENOMEM;
 502}
 503
 504static int update_effective_progs(struct cgroup *cgrp,
 505				  enum cgroup_bpf_attach_type atype)
 506{
 507	struct cgroup_subsys_state *css;
 508	int err;
 509
 510	/* allocate and recompute effective prog arrays */
 511	css_for_each_descendant_pre(css, &cgrp->self) {
 512		struct cgroup *desc = container_of(css, struct cgroup, self);
 513
 514		if (percpu_ref_is_zero(&desc->bpf.refcnt))
 515			continue;
 516
 517		err = compute_effective_progs(desc, atype, &desc->bpf.inactive);
 518		if (err)
 519			goto cleanup;
 520	}
 521
 522	/* all allocations were successful. Activate all prog arrays */
 523	css_for_each_descendant_pre(css, &cgrp->self) {
 524		struct cgroup *desc = container_of(css, struct cgroup, self);
 525
 526		if (percpu_ref_is_zero(&desc->bpf.refcnt)) {
 527			if (unlikely(desc->bpf.inactive)) {
 528				bpf_prog_array_free(desc->bpf.inactive);
 529				desc->bpf.inactive = NULL;
 530			}
 531			continue;
 532		}
 533
 534		activate_effective_progs(desc, atype, desc->bpf.inactive);
 535		desc->bpf.inactive = NULL;
 536	}
 537
 538	return 0;
 539
 540cleanup:
 541	/* oom while computing effective. Free all computed effective arrays
 542	 * since they were not activated
 543	 */
 544	css_for_each_descendant_pre(css, &cgrp->self) {
 545		struct cgroup *desc = container_of(css, struct cgroup, self);
 546
 547		bpf_prog_array_free(desc->bpf.inactive);
 548		desc->bpf.inactive = NULL;
 549	}
 550
 551	return err;
 552}
 553
 554#define BPF_CGROUP_MAX_PROGS 64
 555
 556static struct bpf_prog_list *find_attach_entry(struct hlist_head *progs,
 557					       struct bpf_prog *prog,
 558					       struct bpf_cgroup_link *link,
 559					       struct bpf_prog *replace_prog,
 560					       bool allow_multi)
 561{
 562	struct bpf_prog_list *pl;
 563
 564	/* single-attach case */
 565	if (!allow_multi) {
 566		if (hlist_empty(progs))
 567			return NULL;
 568		return hlist_entry(progs->first, typeof(*pl), node);
 569	}
 570
 571	hlist_for_each_entry(pl, progs, node) {
 572		if (prog && pl->prog == prog && prog != replace_prog)
 573			/* disallow attaching the same prog twice */
 574			return ERR_PTR(-EINVAL);
 575		if (link && pl->link == link)
 576			/* disallow attaching the same link twice */
 577			return ERR_PTR(-EINVAL);
 578	}
 579
 580	/* direct prog multi-attach w/ replacement case */
 581	if (replace_prog) {
 582		hlist_for_each_entry(pl, progs, node) {
 583			if (pl->prog == replace_prog)
 584				/* a match found */
 585				return pl;
 586		}
 587		/* prog to replace not found for cgroup */
 588		return ERR_PTR(-ENOENT);
 589	}
 590
 591	return NULL;
 592}
 593
 594/**
 595 * __cgroup_bpf_attach() - Attach the program or the link to a cgroup, and
 596 *                         propagate the change to descendants
 597 * @cgrp: The cgroup which descendants to traverse
 598 * @prog: A program to attach
 599 * @link: A link to attach
 600 * @replace_prog: Previously attached program to replace if BPF_F_REPLACE is set
 601 * @type: Type of attach operation
 602 * @flags: Option flags
 603 *
 604 * Exactly one of @prog or @link can be non-null.
 605 * Must be called with cgroup_mutex held.
 606 */
 607static int __cgroup_bpf_attach(struct cgroup *cgrp,
 608			       struct bpf_prog *prog, struct bpf_prog *replace_prog,
 609			       struct bpf_cgroup_link *link,
 610			       enum bpf_attach_type type, u32 flags)
 611{
 612	u32 saved_flags = (flags & (BPF_F_ALLOW_OVERRIDE | BPF_F_ALLOW_MULTI));
 613	struct bpf_prog *old_prog = NULL;
 614	struct bpf_cgroup_storage *storage[MAX_BPF_CGROUP_STORAGE_TYPE] = {};
 615	struct bpf_cgroup_storage *new_storage[MAX_BPF_CGROUP_STORAGE_TYPE] = {};
 616	struct bpf_prog *new_prog = prog ? : link->link.prog;
 617	enum cgroup_bpf_attach_type atype;
 618	struct bpf_prog_list *pl;
 619	struct hlist_head *progs;
 620	int err;
 621
 622	if (((flags & BPF_F_ALLOW_OVERRIDE) && (flags & BPF_F_ALLOW_MULTI)) ||
 623	    ((flags & BPF_F_REPLACE) && !(flags & BPF_F_ALLOW_MULTI)))
 624		/* invalid combination */
 625		return -EINVAL;
 626	if (link && (prog || replace_prog))
 627		/* only either link or prog/replace_prog can be specified */
 628		return -EINVAL;
 629	if (!!replace_prog != !!(flags & BPF_F_REPLACE))
 630		/* replace_prog implies BPF_F_REPLACE, and vice versa */
 631		return -EINVAL;
 632
 633	atype = bpf_cgroup_atype_find(type, new_prog->aux->attach_btf_id);
 634	if (atype < 0)
 635		return -EINVAL;
 636
 637	progs = &cgrp->bpf.progs[atype];
 638
 639	if (!hierarchy_allows_attach(cgrp, atype))
 640		return -EPERM;
 641
 642	if (!hlist_empty(progs) && cgrp->bpf.flags[atype] != saved_flags)
 643		/* Disallow attaching non-overridable on top
 644		 * of existing overridable in this cgroup.
 645		 * Disallow attaching multi-prog if overridable or none
 646		 */
 647		return -EPERM;
 648
 649	if (prog_list_length(progs) >= BPF_CGROUP_MAX_PROGS)
 650		return -E2BIG;
 651
 652	pl = find_attach_entry(progs, prog, link, replace_prog,
 653			       flags & BPF_F_ALLOW_MULTI);
 654	if (IS_ERR(pl))
 655		return PTR_ERR(pl);
 656
 657	if (bpf_cgroup_storages_alloc(storage, new_storage, type,
 658				      prog ? : link->link.prog, cgrp))
 659		return -ENOMEM;
 660
 661	if (pl) {
 662		old_prog = pl->prog;
 663	} else {
 664		struct hlist_node *last = NULL;
 665
 666		pl = kmalloc(sizeof(*pl), GFP_KERNEL);
 667		if (!pl) {
 668			bpf_cgroup_storages_free(new_storage);
 669			return -ENOMEM;
 670		}
 671		if (hlist_empty(progs))
 672			hlist_add_head(&pl->node, progs);
 673		else
 674			hlist_for_each(last, progs) {
 675				if (last->next)
 676					continue;
 677				hlist_add_behind(&pl->node, last);
 678				break;
 679			}
 680	}
 681
 682	pl->prog = prog;
 683	pl->link = link;
 684	bpf_cgroup_storages_assign(pl->storage, storage);
 685	cgrp->bpf.flags[atype] = saved_flags;
 686
 687	if (type == BPF_LSM_CGROUP) {
 688		err = bpf_trampoline_link_cgroup_shim(new_prog, atype);
 689		if (err)
 690			goto cleanup;
 691	}
 692
 693	err = update_effective_progs(cgrp, atype);
 694	if (err)
 695		goto cleanup_trampoline;
 696
 697	if (old_prog) {
 698		if (type == BPF_LSM_CGROUP)
 699			bpf_trampoline_unlink_cgroup_shim(old_prog);
 700		bpf_prog_put(old_prog);
 701	} else {
 702		static_branch_inc(&cgroup_bpf_enabled_key[atype]);
 703	}
 704	bpf_cgroup_storages_link(new_storage, cgrp, type);
 705	return 0;
 706
 707cleanup_trampoline:
 708	if (type == BPF_LSM_CGROUP)
 709		bpf_trampoline_unlink_cgroup_shim(new_prog);
 710
 711cleanup:
 712	if (old_prog) {
 713		pl->prog = old_prog;
 714		pl->link = NULL;
 715	}
 716	bpf_cgroup_storages_free(new_storage);
 717	if (!old_prog) {
 718		hlist_del(&pl->node);
 719		kfree(pl);
 720	}
 721	return err;
 722}
 723
 724static int cgroup_bpf_attach(struct cgroup *cgrp,
 725			     struct bpf_prog *prog, struct bpf_prog *replace_prog,
 726			     struct bpf_cgroup_link *link,
 727			     enum bpf_attach_type type,
 728			     u32 flags)
 729{
 730	int ret;
 731
 732	mutex_lock(&cgroup_mutex);
 733	ret = __cgroup_bpf_attach(cgrp, prog, replace_prog, link, type, flags);
 734	mutex_unlock(&cgroup_mutex);
 735	return ret;
 736}
 737
 738/* Swap updated BPF program for given link in effective program arrays across
 739 * all descendant cgroups. This function is guaranteed to succeed.
 740 */
 741static void replace_effective_prog(struct cgroup *cgrp,
 742				   enum cgroup_bpf_attach_type atype,
 743				   struct bpf_cgroup_link *link)
 744{
 745	struct bpf_prog_array_item *item;
 746	struct cgroup_subsys_state *css;
 747	struct bpf_prog_array *progs;
 748	struct bpf_prog_list *pl;
 749	struct hlist_head *head;
 750	struct cgroup *cg;
 751	int pos;
 752
 753	css_for_each_descendant_pre(css, &cgrp->self) {
 754		struct cgroup *desc = container_of(css, struct cgroup, self);
 755
 756		if (percpu_ref_is_zero(&desc->bpf.refcnt))
 757			continue;
 758
 759		/* find position of link in effective progs array */
 760		for (pos = 0, cg = desc; cg; cg = cgroup_parent(cg)) {
 761			if (pos && !(cg->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
 762				continue;
 763
 764			head = &cg->bpf.progs[atype];
 765			hlist_for_each_entry(pl, head, node) {
 766				if (!prog_list_prog(pl))
 767					continue;
 768				if (pl->link == link)
 769					goto found;
 770				pos++;
 771			}
 772		}
 773found:
 774		BUG_ON(!cg);
 775		progs = rcu_dereference_protected(
 776				desc->bpf.effective[atype],
 777				lockdep_is_held(&cgroup_mutex));
 778		item = &progs->items[pos];
 779		WRITE_ONCE(item->prog, link->link.prog);
 780	}
 781}
 782
 783/**
 784 * __cgroup_bpf_replace() - Replace link's program and propagate the change
 785 *                          to descendants
 786 * @cgrp: The cgroup which descendants to traverse
 787 * @link: A link for which to replace BPF program
 788 * @type: Type of attach operation
 
 789 *
 790 * Must be called with cgroup_mutex held.
 791 */
 792static int __cgroup_bpf_replace(struct cgroup *cgrp,
 793				struct bpf_cgroup_link *link,
 794				struct bpf_prog *new_prog)
 795{
 796	enum cgroup_bpf_attach_type atype;
 797	struct bpf_prog *old_prog;
 798	struct bpf_prog_list *pl;
 799	struct hlist_head *progs;
 800	bool found = false;
 801
 802	atype = bpf_cgroup_atype_find(link->type, new_prog->aux->attach_btf_id);
 803	if (atype < 0)
 804		return -EINVAL;
 805
 806	progs = &cgrp->bpf.progs[atype];
 807
 808	if (link->link.prog->type != new_prog->type)
 809		return -EINVAL;
 810
 811	hlist_for_each_entry(pl, progs, node) {
 812		if (pl->link == link) {
 813			found = true;
 814			break;
 815		}
 816	}
 817	if (!found)
 818		return -ENOENT;
 819
 820	old_prog = xchg(&link->link.prog, new_prog);
 821	replace_effective_prog(cgrp, atype, link);
 822	bpf_prog_put(old_prog);
 823	return 0;
 824}
 825
 826static int cgroup_bpf_replace(struct bpf_link *link, struct bpf_prog *new_prog,
 827			      struct bpf_prog *old_prog)
 828{
 829	struct bpf_cgroup_link *cg_link;
 830	int ret;
 831
 832	cg_link = container_of(link, struct bpf_cgroup_link, link);
 833
 834	mutex_lock(&cgroup_mutex);
 835	/* link might have been auto-released by dying cgroup, so fail */
 836	if (!cg_link->cgroup) {
 837		ret = -ENOLINK;
 838		goto out_unlock;
 839	}
 840	if (old_prog && link->prog != old_prog) {
 841		ret = -EPERM;
 842		goto out_unlock;
 843	}
 844	ret = __cgroup_bpf_replace(cg_link->cgroup, cg_link, new_prog);
 845out_unlock:
 846	mutex_unlock(&cgroup_mutex);
 847	return ret;
 848}
 849
 850static struct bpf_prog_list *find_detach_entry(struct hlist_head *progs,
 851					       struct bpf_prog *prog,
 852					       struct bpf_cgroup_link *link,
 853					       bool allow_multi)
 854{
 855	struct bpf_prog_list *pl;
 856
 857	if (!allow_multi) {
 858		if (hlist_empty(progs))
 859			/* report error when trying to detach and nothing is attached */
 860			return ERR_PTR(-ENOENT);
 861
 862		/* to maintain backward compatibility NONE and OVERRIDE cgroups
 863		 * allow detaching with invalid FD (prog==NULL) in legacy mode
 864		 */
 865		return hlist_entry(progs->first, typeof(*pl), node);
 866	}
 867
 868	if (!prog && !link)
 869		/* to detach MULTI prog the user has to specify valid FD
 870		 * of the program or link to be detached
 871		 */
 872		return ERR_PTR(-EINVAL);
 873
 874	/* find the prog or link and detach it */
 875	hlist_for_each_entry(pl, progs, node) {
 876		if (pl->prog == prog && pl->link == link)
 877			return pl;
 878	}
 879	return ERR_PTR(-ENOENT);
 880}
 881
 882/**
 883 * purge_effective_progs() - After compute_effective_progs fails to alloc new
 884 *                           cgrp->bpf.inactive table we can recover by
 885 *                           recomputing the array in place.
 886 *
 887 * @cgrp: The cgroup which descendants to travers
 888 * @prog: A program to detach or NULL
 889 * @link: A link to detach or NULL
 890 * @atype: Type of detach operation
 891 */
 892static void purge_effective_progs(struct cgroup *cgrp, struct bpf_prog *prog,
 893				  struct bpf_cgroup_link *link,
 894				  enum cgroup_bpf_attach_type atype)
 895{
 896	struct cgroup_subsys_state *css;
 897	struct bpf_prog_array *progs;
 898	struct bpf_prog_list *pl;
 899	struct hlist_head *head;
 900	struct cgroup *cg;
 901	int pos;
 902
 903	/* recompute effective prog array in place */
 904	css_for_each_descendant_pre(css, &cgrp->self) {
 905		struct cgroup *desc = container_of(css, struct cgroup, self);
 906
 907		if (percpu_ref_is_zero(&desc->bpf.refcnt))
 908			continue;
 909
 910		/* find position of link or prog in effective progs array */
 911		for (pos = 0, cg = desc; cg; cg = cgroup_parent(cg)) {
 912			if (pos && !(cg->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
 913				continue;
 914
 915			head = &cg->bpf.progs[atype];
 916			hlist_for_each_entry(pl, head, node) {
 917				if (!prog_list_prog(pl))
 918					continue;
 919				if (pl->prog == prog && pl->link == link)
 920					goto found;
 921				pos++;
 922			}
 923		}
 924
 925		/* no link or prog match, skip the cgroup of this layer */
 926		continue;
 927found:
 928		progs = rcu_dereference_protected(
 929				desc->bpf.effective[atype],
 930				lockdep_is_held(&cgroup_mutex));
 931
 932		/* Remove the program from the array */
 933		WARN_ONCE(bpf_prog_array_delete_safe_at(progs, pos),
 934			  "Failed to purge a prog from array at index %d", pos);
 935	}
 936}
 937
 938/**
 939 * __cgroup_bpf_detach() - Detach the program or link from a cgroup, and
 940 *                         propagate the change to descendants
 941 * @cgrp: The cgroup which descendants to traverse
 942 * @prog: A program to detach or NULL
 943 * @link: A link to detach or NULL
 944 * @type: Type of detach operation
 945 *
 946 * At most one of @prog or @link can be non-NULL.
 947 * Must be called with cgroup_mutex held.
 948 */
 949static int __cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
 950			       struct bpf_cgroup_link *link, enum bpf_attach_type type)
 951{
 952	enum cgroup_bpf_attach_type atype;
 953	struct bpf_prog *old_prog;
 954	struct bpf_prog_list *pl;
 955	struct hlist_head *progs;
 956	u32 attach_btf_id = 0;
 957	u32 flags;
 958
 959	if (prog)
 960		attach_btf_id = prog->aux->attach_btf_id;
 961	if (link)
 962		attach_btf_id = link->link.prog->aux->attach_btf_id;
 963
 964	atype = bpf_cgroup_atype_find(type, attach_btf_id);
 965	if (atype < 0)
 966		return -EINVAL;
 967
 968	progs = &cgrp->bpf.progs[atype];
 969	flags = cgrp->bpf.flags[atype];
 970
 971	if (prog && link)
 972		/* only one of prog or link can be specified */
 973		return -EINVAL;
 974
 975	pl = find_detach_entry(progs, prog, link, flags & BPF_F_ALLOW_MULTI);
 976	if (IS_ERR(pl))
 977		return PTR_ERR(pl);
 978
 979	/* mark it deleted, so it's ignored while recomputing effective */
 980	old_prog = pl->prog;
 981	pl->prog = NULL;
 982	pl->link = NULL;
 983
 984	if (update_effective_progs(cgrp, atype)) {
 985		/* if update effective array failed replace the prog with a dummy prog*/
 986		pl->prog = old_prog;
 987		pl->link = link;
 988		purge_effective_progs(cgrp, old_prog, link, atype);
 989	}
 990
 991	/* now can actually delete it from this cgroup list */
 992	hlist_del(&pl->node);
 993
 994	kfree(pl);
 995	if (hlist_empty(progs))
 996		/* last program was detached, reset flags to zero */
 997		cgrp->bpf.flags[atype] = 0;
 998	if (old_prog) {
 999		if (type == BPF_LSM_CGROUP)
1000			bpf_trampoline_unlink_cgroup_shim(old_prog);
1001		bpf_prog_put(old_prog);
1002	}
1003	static_branch_dec(&cgroup_bpf_enabled_key[atype]);
1004	return 0;
1005}
1006
1007static int cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
1008			     enum bpf_attach_type type)
1009{
1010	int ret;
1011
1012	mutex_lock(&cgroup_mutex);
1013	ret = __cgroup_bpf_detach(cgrp, prog, NULL, type);
1014	mutex_unlock(&cgroup_mutex);
1015	return ret;
1016}
1017
1018/* Must be called with cgroup_mutex held to avoid races. */
1019static int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
1020			      union bpf_attr __user *uattr)
1021{
1022	__u32 __user *prog_attach_flags = u64_to_user_ptr(attr->query.prog_attach_flags);
1023	bool effective_query = attr->query.query_flags & BPF_F_QUERY_EFFECTIVE;
1024	__u32 __user *prog_ids = u64_to_user_ptr(attr->query.prog_ids);
1025	enum bpf_attach_type type = attr->query.attach_type;
1026	enum cgroup_bpf_attach_type from_atype, to_atype;
1027	enum cgroup_bpf_attach_type atype;
1028	struct bpf_prog_array *effective;
1029	int cnt, ret = 0, i;
1030	int total_cnt = 0;
1031	u32 flags;
1032
1033	if (effective_query && prog_attach_flags)
1034		return -EINVAL;
1035
1036	if (type == BPF_LSM_CGROUP) {
1037		if (!effective_query && attr->query.prog_cnt &&
1038		    prog_ids && !prog_attach_flags)
1039			return -EINVAL;
1040
1041		from_atype = CGROUP_LSM_START;
1042		to_atype = CGROUP_LSM_END;
1043		flags = 0;
1044	} else {
1045		from_atype = to_cgroup_bpf_attach_type(type);
1046		if (from_atype < 0)
1047			return -EINVAL;
1048		to_atype = from_atype;
1049		flags = cgrp->bpf.flags[from_atype];
1050	}
1051
1052	for (atype = from_atype; atype <= to_atype; atype++) {
1053		if (effective_query) {
1054			effective = rcu_dereference_protected(cgrp->bpf.effective[atype],
1055							      lockdep_is_held(&cgroup_mutex));
1056			total_cnt += bpf_prog_array_length(effective);
1057		} else {
1058			total_cnt += prog_list_length(&cgrp->bpf.progs[atype]);
1059		}
1060	}
1061
1062	/* always output uattr->query.attach_flags as 0 during effective query */
1063	flags = effective_query ? 0 : flags;
1064	if (copy_to_user(&uattr->query.attach_flags, &flags, sizeof(flags)))
1065		return -EFAULT;
1066	if (copy_to_user(&uattr->query.prog_cnt, &total_cnt, sizeof(total_cnt)))
1067		return -EFAULT;
1068	if (attr->query.prog_cnt == 0 || !prog_ids || !total_cnt)
1069		/* return early if user requested only program count + flags */
1070		return 0;
1071
1072	if (attr->query.prog_cnt < total_cnt) {
1073		total_cnt = attr->query.prog_cnt;
1074		ret = -ENOSPC;
1075	}
1076
1077	for (atype = from_atype; atype <= to_atype && total_cnt; atype++) {
1078		if (effective_query) {
1079			effective = rcu_dereference_protected(cgrp->bpf.effective[atype],
1080							      lockdep_is_held(&cgroup_mutex));
1081			cnt = min_t(int, bpf_prog_array_length(effective), total_cnt);
1082			ret = bpf_prog_array_copy_to_user(effective, prog_ids, cnt);
1083		} else {
1084			struct hlist_head *progs;
1085			struct bpf_prog_list *pl;
1086			struct bpf_prog *prog;
1087			u32 id;
1088
1089			progs = &cgrp->bpf.progs[atype];
1090			cnt = min_t(int, prog_list_length(progs), total_cnt);
1091			i = 0;
1092			hlist_for_each_entry(pl, progs, node) {
1093				prog = prog_list_prog(pl);
1094				id = prog->aux->id;
1095				if (copy_to_user(prog_ids + i, &id, sizeof(id)))
1096					return -EFAULT;
1097				if (++i == cnt)
1098					break;
1099			}
1100
1101			if (prog_attach_flags) {
1102				flags = cgrp->bpf.flags[atype];
1103
1104				for (i = 0; i < cnt; i++)
1105					if (copy_to_user(prog_attach_flags + i,
1106							 &flags, sizeof(flags)))
1107						return -EFAULT;
1108				prog_attach_flags += cnt;
1109			}
1110		}
1111
1112		prog_ids += cnt;
1113		total_cnt -= cnt;
1114	}
1115	return ret;
1116}
1117
1118static int cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
1119			    union bpf_attr __user *uattr)
1120{
1121	int ret;
1122
1123	mutex_lock(&cgroup_mutex);
1124	ret = __cgroup_bpf_query(cgrp, attr, uattr);
1125	mutex_unlock(&cgroup_mutex);
1126	return ret;
1127}
1128
1129int cgroup_bpf_prog_attach(const union bpf_attr *attr,
1130			   enum bpf_prog_type ptype, struct bpf_prog *prog)
1131{
1132	struct bpf_prog *replace_prog = NULL;
1133	struct cgroup *cgrp;
1134	int ret;
1135
1136	cgrp = cgroup_get_from_fd(attr->target_fd);
1137	if (IS_ERR(cgrp))
1138		return PTR_ERR(cgrp);
1139
1140	if ((attr->attach_flags & BPF_F_ALLOW_MULTI) &&
1141	    (attr->attach_flags & BPF_F_REPLACE)) {
1142		replace_prog = bpf_prog_get_type(attr->replace_bpf_fd, ptype);
1143		if (IS_ERR(replace_prog)) {
1144			cgroup_put(cgrp);
1145			return PTR_ERR(replace_prog);
1146		}
1147	}
1148
1149	ret = cgroup_bpf_attach(cgrp, prog, replace_prog, NULL,
1150				attr->attach_type, attr->attach_flags);
1151
1152	if (replace_prog)
1153		bpf_prog_put(replace_prog);
1154	cgroup_put(cgrp);
1155	return ret;
1156}
1157
1158int cgroup_bpf_prog_detach(const union bpf_attr *attr, enum bpf_prog_type ptype)
1159{
1160	struct bpf_prog *prog;
1161	struct cgroup *cgrp;
1162	int ret;
1163
1164	cgrp = cgroup_get_from_fd(attr->target_fd);
1165	if (IS_ERR(cgrp))
1166		return PTR_ERR(cgrp);
1167
1168	prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
1169	if (IS_ERR(prog))
1170		prog = NULL;
1171
1172	ret = cgroup_bpf_detach(cgrp, prog, attr->attach_type);
1173	if (prog)
1174		bpf_prog_put(prog);
1175
1176	cgroup_put(cgrp);
1177	return ret;
1178}
1179
1180static void bpf_cgroup_link_release(struct bpf_link *link)
1181{
1182	struct bpf_cgroup_link *cg_link =
1183		container_of(link, struct bpf_cgroup_link, link);
1184	struct cgroup *cg;
1185
1186	/* link might have been auto-detached by dying cgroup already,
1187	 * in that case our work is done here
1188	 */
1189	if (!cg_link->cgroup)
1190		return;
1191
1192	mutex_lock(&cgroup_mutex);
1193
1194	/* re-check cgroup under lock again */
1195	if (!cg_link->cgroup) {
1196		mutex_unlock(&cgroup_mutex);
1197		return;
1198	}
1199
1200	WARN_ON(__cgroup_bpf_detach(cg_link->cgroup, NULL, cg_link,
1201				    cg_link->type));
1202	if (cg_link->type == BPF_LSM_CGROUP)
1203		bpf_trampoline_unlink_cgroup_shim(cg_link->link.prog);
1204
1205	cg = cg_link->cgroup;
1206	cg_link->cgroup = NULL;
1207
1208	mutex_unlock(&cgroup_mutex);
1209
1210	cgroup_put(cg);
1211}
1212
1213static void bpf_cgroup_link_dealloc(struct bpf_link *link)
1214{
1215	struct bpf_cgroup_link *cg_link =
1216		container_of(link, struct bpf_cgroup_link, link);
1217
1218	kfree(cg_link);
1219}
1220
1221static int bpf_cgroup_link_detach(struct bpf_link *link)
1222{
1223	bpf_cgroup_link_release(link);
1224
1225	return 0;
1226}
1227
1228static void bpf_cgroup_link_show_fdinfo(const struct bpf_link *link,
1229					struct seq_file *seq)
1230{
1231	struct bpf_cgroup_link *cg_link =
1232		container_of(link, struct bpf_cgroup_link, link);
1233	u64 cg_id = 0;
1234
1235	mutex_lock(&cgroup_mutex);
1236	if (cg_link->cgroup)
1237		cg_id = cgroup_id(cg_link->cgroup);
1238	mutex_unlock(&cgroup_mutex);
1239
1240	seq_printf(seq,
1241		   "cgroup_id:\t%llu\n"
1242		   "attach_type:\t%d\n",
1243		   cg_id,
1244		   cg_link->type);
1245}
1246
1247static int bpf_cgroup_link_fill_link_info(const struct bpf_link *link,
1248					  struct bpf_link_info *info)
1249{
1250	struct bpf_cgroup_link *cg_link =
1251		container_of(link, struct bpf_cgroup_link, link);
1252	u64 cg_id = 0;
1253
1254	mutex_lock(&cgroup_mutex);
1255	if (cg_link->cgroup)
1256		cg_id = cgroup_id(cg_link->cgroup);
1257	mutex_unlock(&cgroup_mutex);
1258
1259	info->cgroup.cgroup_id = cg_id;
1260	info->cgroup.attach_type = cg_link->type;
1261	return 0;
1262}
1263
1264static const struct bpf_link_ops bpf_cgroup_link_lops = {
1265	.release = bpf_cgroup_link_release,
1266	.dealloc = bpf_cgroup_link_dealloc,
1267	.detach = bpf_cgroup_link_detach,
1268	.update_prog = cgroup_bpf_replace,
1269	.show_fdinfo = bpf_cgroup_link_show_fdinfo,
1270	.fill_link_info = bpf_cgroup_link_fill_link_info,
1271};
1272
1273int cgroup_bpf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
1274{
1275	struct bpf_link_primer link_primer;
1276	struct bpf_cgroup_link *link;
1277	struct cgroup *cgrp;
1278	int err;
1279
1280	if (attr->link_create.flags)
1281		return -EINVAL;
1282
1283	cgrp = cgroup_get_from_fd(attr->link_create.target_fd);
1284	if (IS_ERR(cgrp))
1285		return PTR_ERR(cgrp);
1286
1287	link = kzalloc(sizeof(*link), GFP_USER);
1288	if (!link) {
1289		err = -ENOMEM;
1290		goto out_put_cgroup;
1291	}
1292	bpf_link_init(&link->link, BPF_LINK_TYPE_CGROUP, &bpf_cgroup_link_lops,
1293		      prog);
1294	link->cgroup = cgrp;
1295	link->type = attr->link_create.attach_type;
1296
1297	err = bpf_link_prime(&link->link, &link_primer);
1298	if (err) {
1299		kfree(link);
1300		goto out_put_cgroup;
1301	}
1302
1303	err = cgroup_bpf_attach(cgrp, NULL, NULL, link,
1304				link->type, BPF_F_ALLOW_MULTI);
1305	if (err) {
1306		bpf_link_cleanup(&link_primer);
1307		goto out_put_cgroup;
1308	}
1309
1310	return bpf_link_settle(&link_primer);
1311
1312out_put_cgroup:
1313	cgroup_put(cgrp);
1314	return err;
1315}
1316
1317int cgroup_bpf_prog_query(const union bpf_attr *attr,
1318			  union bpf_attr __user *uattr)
1319{
1320	struct cgroup *cgrp;
1321	int ret;
1322
1323	cgrp = cgroup_get_from_fd(attr->query.target_fd);
1324	if (IS_ERR(cgrp))
1325		return PTR_ERR(cgrp);
1326
1327	ret = cgroup_bpf_query(cgrp, attr, uattr);
1328
1329	cgroup_put(cgrp);
1330	return ret;
1331}
1332
1333/**
1334 * __cgroup_bpf_run_filter_skb() - Run a program for packet filtering
1335 * @sk: The socket sending or receiving traffic
1336 * @skb: The skb that is being sent or received
1337 * @type: The type of program to be executed
1338 *
1339 * If no socket is passed, or the socket is not of type INET or INET6,
1340 * this function does nothing and returns 0.
1341 *
1342 * The program type passed in via @type must be suitable for network
1343 * filtering. No further check is performed to assert that.
1344 *
1345 * For egress packets, this function can return:
1346 *   NET_XMIT_SUCCESS    (0)	- continue with packet output
1347 *   NET_XMIT_DROP       (1)	- drop packet and notify TCP to call cwr
1348 *   NET_XMIT_CN         (2)	- continue with packet output and notify TCP
1349 *				  to call cwr
1350 *   -err			- drop packet
1351 *
1352 * For ingress packets, this function will return -EPERM if any
1353 * attached program was found and if it returned != 1 during execution.
1354 * Otherwise 0 is returned.
1355 */
1356int __cgroup_bpf_run_filter_skb(struct sock *sk,
1357				struct sk_buff *skb,
1358				enum cgroup_bpf_attach_type atype)
1359{
1360	unsigned int offset = skb->data - skb_network_header(skb);
1361	struct sock *save_sk;
1362	void *saved_data_end;
1363	struct cgroup *cgrp;
1364	int ret;
1365
1366	if (!sk || !sk_fullsock(sk))
1367		return 0;
1368
1369	if (sk->sk_family != AF_INET && sk->sk_family != AF_INET6)
1370		return 0;
1371
1372	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1373	save_sk = skb->sk;
1374	skb->sk = sk;
1375	__skb_push(skb, offset);
1376
1377	/* compute pointers for the bpf prog */
1378	bpf_compute_and_save_data_end(skb, &saved_data_end);
1379
1380	if (atype == CGROUP_INET_EGRESS) {
1381		u32 flags = 0;
1382		bool cn;
1383
1384		ret = bpf_prog_run_array_cg(&cgrp->bpf, atype, skb,
1385					    __bpf_prog_run_save_cb, 0, &flags);
1386
1387		/* Return values of CGROUP EGRESS BPF programs are:
1388		 *   0: drop packet
1389		 *   1: keep packet
1390		 *   2: drop packet and cn
1391		 *   3: keep packet and cn
1392		 *
1393		 * The returned value is then converted to one of the NET_XMIT
1394		 * or an error code that is then interpreted as drop packet
1395		 * (and no cn):
1396		 *   0: NET_XMIT_SUCCESS  skb should be transmitted
1397		 *   1: NET_XMIT_DROP     skb should be dropped and cn
1398		 *   2: NET_XMIT_CN       skb should be transmitted and cn
1399		 *   3: -err              skb should be dropped
1400		 */
1401
1402		cn = flags & BPF_RET_SET_CN;
1403		if (ret && !IS_ERR_VALUE((long)ret))
1404			ret = -EFAULT;
1405		if (!ret)
1406			ret = (cn ? NET_XMIT_CN : NET_XMIT_SUCCESS);
1407		else
1408			ret = (cn ? NET_XMIT_DROP : ret);
1409	} else {
1410		ret = bpf_prog_run_array_cg(&cgrp->bpf, atype,
1411					    skb, __bpf_prog_run_save_cb, 0,
1412					    NULL);
1413		if (ret && !IS_ERR_VALUE((long)ret))
1414			ret = -EFAULT;
1415	}
1416	bpf_restore_data_end(skb, saved_data_end);
1417	__skb_pull(skb, offset);
1418	skb->sk = save_sk;
1419
1420	return ret;
1421}
1422EXPORT_SYMBOL(__cgroup_bpf_run_filter_skb);
1423
1424/**
1425 * __cgroup_bpf_run_filter_sk() - Run a program on a sock
1426 * @sk: sock structure to manipulate
1427 * @type: The type of program to be executed
1428 *
1429 * socket is passed is expected to be of type INET or INET6.
1430 *
1431 * The program type passed in via @type must be suitable for sock
1432 * filtering. No further check is performed to assert that.
1433 *
1434 * This function will return %-EPERM if any if an attached program was found
1435 * and if it returned != 1 during execution. In all other cases, 0 is returned.
1436 */
1437int __cgroup_bpf_run_filter_sk(struct sock *sk,
1438			       enum cgroup_bpf_attach_type atype)
1439{
1440	struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1441
1442	return bpf_prog_run_array_cg(&cgrp->bpf, atype, sk, bpf_prog_run, 0,
1443				     NULL);
1444}
1445EXPORT_SYMBOL(__cgroup_bpf_run_filter_sk);
1446
1447/**
1448 * __cgroup_bpf_run_filter_sock_addr() - Run a program on a sock and
1449 *                                       provided by user sockaddr
1450 * @sk: sock struct that will use sockaddr
1451 * @uaddr: sockaddr struct provided by user
1452 * @type: The type of program to be executed
 
 
 
1453 * @t_ctx: Pointer to attach type specific context
1454 * @flags: Pointer to u32 which contains higher bits of BPF program
1455 *         return value (OR'ed together).
1456 *
1457 * socket is expected to be of type INET or INET6.
1458 *
1459 * This function will return %-EPERM if an attached program is found and
1460 * returned value != 1 during execution. In all other cases, 0 is returned.
1461 */
1462int __cgroup_bpf_run_filter_sock_addr(struct sock *sk,
1463				      struct sockaddr *uaddr,
 
1464				      enum cgroup_bpf_attach_type atype,
1465				      void *t_ctx,
1466				      u32 *flags)
1467{
1468	struct bpf_sock_addr_kern ctx = {
1469		.sk = sk,
1470		.uaddr = uaddr,
1471		.t_ctx = t_ctx,
1472	};
1473	struct sockaddr_storage unspec;
1474	struct cgroup *cgrp;
 
1475
1476	/* Check socket family since not all sockets represent network
1477	 * endpoint (e.g. AF_UNIX).
1478	 */
1479	if (sk->sk_family != AF_INET && sk->sk_family != AF_INET6)
 
1480		return 0;
1481
1482	if (!ctx.uaddr) {
1483		memset(&unspec, 0, sizeof(unspec));
1484		ctx.uaddr = (struct sockaddr *)&unspec;
 
 
 
1485	}
1486
1487	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1488	return bpf_prog_run_array_cg(&cgrp->bpf, atype, &ctx, bpf_prog_run,
1489				     0, flags);
 
 
 
 
 
1490}
1491EXPORT_SYMBOL(__cgroup_bpf_run_filter_sock_addr);
1492
1493/**
1494 * __cgroup_bpf_run_filter_sock_ops() - Run a program on a sock
1495 * @sk: socket to get cgroup from
1496 * @sock_ops: bpf_sock_ops_kern struct to pass to program. Contains
1497 * sk with connection information (IP addresses, etc.) May not contain
1498 * cgroup info if it is a req sock.
1499 * @type: The type of program to be executed
1500 *
1501 * socket passed is expected to be of type INET or INET6.
1502 *
1503 * The program type passed in via @type must be suitable for sock_ops
1504 * filtering. No further check is performed to assert that.
1505 *
1506 * This function will return %-EPERM if any if an attached program was found
1507 * and if it returned != 1 during execution. In all other cases, 0 is returned.
1508 */
1509int __cgroup_bpf_run_filter_sock_ops(struct sock *sk,
1510				     struct bpf_sock_ops_kern *sock_ops,
1511				     enum cgroup_bpf_attach_type atype)
1512{
1513	struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1514
1515	return bpf_prog_run_array_cg(&cgrp->bpf, atype, sock_ops, bpf_prog_run,
1516				     0, NULL);
1517}
1518EXPORT_SYMBOL(__cgroup_bpf_run_filter_sock_ops);
1519
1520int __cgroup_bpf_check_dev_permission(short dev_type, u32 major, u32 minor,
1521				      short access, enum cgroup_bpf_attach_type atype)
1522{
1523	struct cgroup *cgrp;
1524	struct bpf_cgroup_dev_ctx ctx = {
1525		.access_type = (access << 16) | dev_type,
1526		.major = major,
1527		.minor = minor,
1528	};
1529	int ret;
1530
1531	rcu_read_lock();
1532	cgrp = task_dfl_cgroup(current);
1533	ret = bpf_prog_run_array_cg(&cgrp->bpf, atype, &ctx, bpf_prog_run, 0,
1534				    NULL);
1535	rcu_read_unlock();
1536
1537	return ret;
1538}
1539
1540BPF_CALL_2(bpf_get_local_storage, struct bpf_map *, map, u64, flags)
1541{
1542	/* flags argument is not used now,
1543	 * but provides an ability to extend the API.
1544	 * verifier checks that its value is correct.
1545	 */
1546	enum bpf_cgroup_storage_type stype = cgroup_storage_type(map);
1547	struct bpf_cgroup_storage *storage;
1548	struct bpf_cg_run_ctx *ctx;
1549	void *ptr;
1550
1551	/* get current cgroup storage from BPF run context */
1552	ctx = container_of(current->bpf_ctx, struct bpf_cg_run_ctx, run_ctx);
1553	storage = ctx->prog_item->cgroup_storage[stype];
1554
1555	if (stype == BPF_CGROUP_STORAGE_SHARED)
1556		ptr = &READ_ONCE(storage->buf)->data[0];
1557	else
1558		ptr = this_cpu_ptr(storage->percpu_buf);
1559
1560	return (unsigned long)ptr;
1561}
1562
1563const struct bpf_func_proto bpf_get_local_storage_proto = {
1564	.func		= bpf_get_local_storage,
1565	.gpl_only	= false,
1566	.ret_type	= RET_PTR_TO_MAP_VALUE,
1567	.arg1_type	= ARG_CONST_MAP_PTR,
1568	.arg2_type	= ARG_ANYTHING,
1569};
1570
1571BPF_CALL_0(bpf_get_retval)
1572{
1573	struct bpf_cg_run_ctx *ctx =
1574		container_of(current->bpf_ctx, struct bpf_cg_run_ctx, run_ctx);
1575
1576	return ctx->retval;
1577}
1578
1579const struct bpf_func_proto bpf_get_retval_proto = {
1580	.func		= bpf_get_retval,
1581	.gpl_only	= false,
1582	.ret_type	= RET_INTEGER,
1583};
1584
1585BPF_CALL_1(bpf_set_retval, int, retval)
1586{
1587	struct bpf_cg_run_ctx *ctx =
1588		container_of(current->bpf_ctx, struct bpf_cg_run_ctx, run_ctx);
1589
1590	ctx->retval = retval;
1591	return 0;
1592}
1593
1594const struct bpf_func_proto bpf_set_retval_proto = {
1595	.func		= bpf_set_retval,
1596	.gpl_only	= false,
1597	.ret_type	= RET_INTEGER,
1598	.arg1_type	= ARG_ANYTHING,
1599};
1600
1601static const struct bpf_func_proto *
1602cgroup_dev_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1603{
1604	const struct bpf_func_proto *func_proto;
1605
1606	func_proto = cgroup_common_func_proto(func_id, prog);
1607	if (func_proto)
1608		return func_proto;
1609
1610	func_proto = cgroup_current_func_proto(func_id, prog);
1611	if (func_proto)
1612		return func_proto;
1613
1614	switch (func_id) {
1615	case BPF_FUNC_perf_event_output:
1616		return &bpf_event_output_data_proto;
1617	default:
1618		return bpf_base_func_proto(func_id);
1619	}
1620}
1621
1622static bool cgroup_dev_is_valid_access(int off, int size,
1623				       enum bpf_access_type type,
1624				       const struct bpf_prog *prog,
1625				       struct bpf_insn_access_aux *info)
1626{
1627	const int size_default = sizeof(__u32);
1628
1629	if (type == BPF_WRITE)
1630		return false;
1631
1632	if (off < 0 || off + size > sizeof(struct bpf_cgroup_dev_ctx))
1633		return false;
1634	/* The verifier guarantees that size > 0. */
1635	if (off % size != 0)
1636		return false;
1637
1638	switch (off) {
1639	case bpf_ctx_range(struct bpf_cgroup_dev_ctx, access_type):
1640		bpf_ctx_record_field_size(info, size_default);
1641		if (!bpf_ctx_narrow_access_ok(off, size, size_default))
1642			return false;
1643		break;
1644	default:
1645		if (size != size_default)
1646			return false;
1647	}
1648
1649	return true;
1650}
1651
1652const struct bpf_prog_ops cg_dev_prog_ops = {
1653};
1654
1655const struct bpf_verifier_ops cg_dev_verifier_ops = {
1656	.get_func_proto		= cgroup_dev_func_proto,
1657	.is_valid_access	= cgroup_dev_is_valid_access,
1658};
1659
1660/**
1661 * __cgroup_bpf_run_filter_sysctl - Run a program on sysctl
1662 *
1663 * @head: sysctl table header
1664 * @table: sysctl table
1665 * @write: sysctl is being read (= 0) or written (= 1)
1666 * @buf: pointer to buffer (in and out)
1667 * @pcount: value-result argument: value is size of buffer pointed to by @buf,
1668 *	result is size of @new_buf if program set new value, initial value
1669 *	otherwise
1670 * @ppos: value-result argument: value is position at which read from or write
1671 *	to sysctl is happening, result is new position if program overrode it,
1672 *	initial value otherwise
1673 * @type: type of program to be executed
1674 *
1675 * Program is run when sysctl is being accessed, either read or written, and
1676 * can allow or deny such access.
1677 *
1678 * This function will return %-EPERM if an attached program is found and
1679 * returned value != 1 during execution. In all other cases 0 is returned.
1680 */
1681int __cgroup_bpf_run_filter_sysctl(struct ctl_table_header *head,
1682				   struct ctl_table *table, int write,
1683				   char **buf, size_t *pcount, loff_t *ppos,
1684				   enum cgroup_bpf_attach_type atype)
1685{
1686	struct bpf_sysctl_kern ctx = {
1687		.head = head,
1688		.table = table,
1689		.write = write,
1690		.ppos = ppos,
1691		.cur_val = NULL,
1692		.cur_len = PAGE_SIZE,
1693		.new_val = NULL,
1694		.new_len = 0,
1695		.new_updated = 0,
1696	};
1697	struct cgroup *cgrp;
1698	loff_t pos = 0;
1699	int ret;
1700
1701	ctx.cur_val = kmalloc_track_caller(ctx.cur_len, GFP_KERNEL);
1702	if (!ctx.cur_val ||
1703	    table->proc_handler(table, 0, ctx.cur_val, &ctx.cur_len, &pos)) {
1704		/* Let BPF program decide how to proceed. */
1705		ctx.cur_len = 0;
1706	}
1707
1708	if (write && *buf && *pcount) {
1709		/* BPF program should be able to override new value with a
1710		 * buffer bigger than provided by user.
1711		 */
1712		ctx.new_val = kmalloc_track_caller(PAGE_SIZE, GFP_KERNEL);
1713		ctx.new_len = min_t(size_t, PAGE_SIZE, *pcount);
1714		if (ctx.new_val) {
1715			memcpy(ctx.new_val, *buf, ctx.new_len);
1716		} else {
1717			/* Let BPF program decide how to proceed. */
1718			ctx.new_len = 0;
1719		}
1720	}
1721
1722	rcu_read_lock();
1723	cgrp = task_dfl_cgroup(current);
1724	ret = bpf_prog_run_array_cg(&cgrp->bpf, atype, &ctx, bpf_prog_run, 0,
1725				    NULL);
1726	rcu_read_unlock();
1727
1728	kfree(ctx.cur_val);
1729
1730	if (ret == 1 && ctx.new_updated) {
1731		kfree(*buf);
1732		*buf = ctx.new_val;
1733		*pcount = ctx.new_len;
1734	} else {
1735		kfree(ctx.new_val);
1736	}
1737
1738	return ret;
1739}
1740
1741#ifdef CONFIG_NET
1742static int sockopt_alloc_buf(struct bpf_sockopt_kern *ctx, int max_optlen,
1743			     struct bpf_sockopt_buf *buf)
1744{
1745	if (unlikely(max_optlen < 0))
1746		return -EINVAL;
1747
1748	if (unlikely(max_optlen > PAGE_SIZE)) {
1749		/* We don't expose optvals that are greater than PAGE_SIZE
1750		 * to the BPF program.
1751		 */
1752		max_optlen = PAGE_SIZE;
1753	}
1754
1755	if (max_optlen <= sizeof(buf->data)) {
1756		/* When the optval fits into BPF_SOCKOPT_KERN_BUF_SIZE
1757		 * bytes avoid the cost of kzalloc.
1758		 */
1759		ctx->optval = buf->data;
1760		ctx->optval_end = ctx->optval + max_optlen;
1761		return max_optlen;
1762	}
1763
1764	ctx->optval = kzalloc(max_optlen, GFP_USER);
1765	if (!ctx->optval)
1766		return -ENOMEM;
1767
1768	ctx->optval_end = ctx->optval + max_optlen;
1769
1770	return max_optlen;
1771}
1772
1773static void sockopt_free_buf(struct bpf_sockopt_kern *ctx,
1774			     struct bpf_sockopt_buf *buf)
1775{
1776	if (ctx->optval == buf->data)
1777		return;
1778	kfree(ctx->optval);
1779}
1780
1781static bool sockopt_buf_allocated(struct bpf_sockopt_kern *ctx,
1782				  struct bpf_sockopt_buf *buf)
1783{
1784	return ctx->optval != buf->data;
1785}
1786
1787int __cgroup_bpf_run_filter_setsockopt(struct sock *sk, int *level,
1788				       int *optname, char __user *optval,
1789				       int *optlen, char **kernel_optval)
1790{
1791	struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1792	struct bpf_sockopt_buf buf = {};
1793	struct bpf_sockopt_kern ctx = {
1794		.sk = sk,
1795		.level = *level,
1796		.optname = *optname,
1797	};
1798	int ret, max_optlen;
1799
1800	/* Allocate a bit more than the initial user buffer for
1801	 * BPF program. The canonical use case is overriding
1802	 * TCP_CONGESTION(nv) to TCP_CONGESTION(cubic).
1803	 */
1804	max_optlen = max_t(int, 16, *optlen);
1805	max_optlen = sockopt_alloc_buf(&ctx, max_optlen, &buf);
1806	if (max_optlen < 0)
1807		return max_optlen;
1808
1809	ctx.optlen = *optlen;
1810
1811	if (copy_from_user(ctx.optval, optval, min(*optlen, max_optlen)) != 0) {
 
1812		ret = -EFAULT;
1813		goto out;
1814	}
1815
1816	lock_sock(sk);
1817	ret = bpf_prog_run_array_cg(&cgrp->bpf, CGROUP_SETSOCKOPT,
1818				    &ctx, bpf_prog_run, 0, NULL);
1819	release_sock(sk);
1820
1821	if (ret)
1822		goto out;
1823
1824	if (ctx.optlen == -1) {
1825		/* optlen set to -1, bypass kernel */
1826		ret = 1;
1827	} else if (ctx.optlen > max_optlen || ctx.optlen < -1) {
1828		/* optlen is out of bounds */
 
 
 
 
 
 
1829		ret = -EFAULT;
1830	} else {
1831		/* optlen within bounds, run kernel handler */
1832		ret = 0;
1833
1834		/* export any potential modifications */
1835		*level = ctx.level;
1836		*optname = ctx.optname;
1837
1838		/* optlen == 0 from BPF indicates that we should
1839		 * use original userspace data.
1840		 */
1841		if (ctx.optlen != 0) {
1842			*optlen = ctx.optlen;
1843			/* We've used bpf_sockopt_kern->buf as an intermediary
1844			 * storage, but the BPF program indicates that we need
1845			 * to pass this data to the kernel setsockopt handler.
1846			 * No way to export on-stack buf, have to allocate a
1847			 * new buffer.
1848			 */
1849			if (!sockopt_buf_allocated(&ctx, &buf)) {
1850				void *p = kmalloc(ctx.optlen, GFP_USER);
1851
1852				if (!p) {
1853					ret = -ENOMEM;
1854					goto out;
1855				}
1856				memcpy(p, ctx.optval, ctx.optlen);
1857				*kernel_optval = p;
1858			} else {
1859				*kernel_optval = ctx.optval;
1860			}
1861			/* export and don't free sockopt buf */
1862			return 0;
1863		}
1864	}
1865
1866out:
1867	sockopt_free_buf(&ctx, &buf);
1868	return ret;
1869}
1870
1871int __cgroup_bpf_run_filter_getsockopt(struct sock *sk, int level,
1872				       int optname, char __user *optval,
1873				       int __user *optlen, int max_optlen,
1874				       int retval)
1875{
1876	struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1877	struct bpf_sockopt_buf buf = {};
1878	struct bpf_sockopt_kern ctx = {
1879		.sk = sk,
1880		.level = level,
1881		.optname = optname,
1882		.current_task = current,
1883	};
 
1884	int ret;
1885
 
1886	ctx.optlen = max_optlen;
1887	max_optlen = sockopt_alloc_buf(&ctx, max_optlen, &buf);
1888	if (max_optlen < 0)
1889		return max_optlen;
1890
1891	if (!retval) {
1892		/* If kernel getsockopt finished successfully,
1893		 * copy whatever was returned to the user back
1894		 * into our temporary buffer. Set optlen to the
1895		 * one that kernel returned as well to let
1896		 * BPF programs inspect the value.
1897		 */
1898
1899		if (get_user(ctx.optlen, optlen)) {
1900			ret = -EFAULT;
1901			goto out;
1902		}
1903
1904		if (ctx.optlen < 0) {
1905			ret = -EFAULT;
1906			goto out;
1907		}
 
1908
1909		if (copy_from_user(ctx.optval, optval,
1910				   min(ctx.optlen, max_optlen)) != 0) {
1911			ret = -EFAULT;
1912			goto out;
1913		}
1914	}
1915
1916	lock_sock(sk);
1917	ret = bpf_prog_run_array_cg(&cgrp->bpf, CGROUP_GETSOCKOPT,
1918				    &ctx, bpf_prog_run, retval, NULL);
1919	release_sock(sk);
1920
1921	if (ret < 0)
1922		goto out;
1923
1924	if (ctx.optlen > max_optlen || ctx.optlen < 0) {
 
 
 
 
 
 
 
1925		ret = -EFAULT;
1926		goto out;
1927	}
1928
1929	if (ctx.optlen != 0) {
1930		if (copy_to_user(optval, ctx.optval, ctx.optlen) ||
1931		    put_user(ctx.optlen, optlen)) {
 
 
 
 
1932			ret = -EFAULT;
1933			goto out;
1934		}
1935	}
1936
1937out:
1938	sockopt_free_buf(&ctx, &buf);
1939	return ret;
1940}
1941
1942int __cgroup_bpf_run_filter_getsockopt_kern(struct sock *sk, int level,
1943					    int optname, void *optval,
1944					    int *optlen, int retval)
1945{
1946	struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1947	struct bpf_sockopt_kern ctx = {
1948		.sk = sk,
1949		.level = level,
1950		.optname = optname,
1951		.optlen = *optlen,
1952		.optval = optval,
1953		.optval_end = optval + *optlen,
1954		.current_task = current,
1955	};
1956	int ret;
1957
1958	/* Note that __cgroup_bpf_run_filter_getsockopt doesn't copy
1959	 * user data back into BPF buffer when reval != 0. This is
1960	 * done as an optimization to avoid extra copy, assuming
1961	 * kernel won't populate the data in case of an error.
1962	 * Here we always pass the data and memset() should
1963	 * be called if that data shouldn't be "exported".
1964	 */
1965
1966	ret = bpf_prog_run_array_cg(&cgrp->bpf, CGROUP_GETSOCKOPT,
1967				    &ctx, bpf_prog_run, retval, NULL);
1968	if (ret < 0)
1969		return ret;
1970
1971	if (ctx.optlen > *optlen)
1972		return -EFAULT;
1973
1974	/* BPF programs can shrink the buffer, export the modifications.
1975	 */
1976	if (ctx.optlen != 0)
1977		*optlen = ctx.optlen;
1978
1979	return ret;
1980}
1981#endif
1982
1983static ssize_t sysctl_cpy_dir(const struct ctl_dir *dir, char **bufp,
1984			      size_t *lenp)
1985{
1986	ssize_t tmp_ret = 0, ret;
1987
1988	if (dir->header.parent) {
1989		tmp_ret = sysctl_cpy_dir(dir->header.parent, bufp, lenp);
1990		if (tmp_ret < 0)
1991			return tmp_ret;
1992	}
1993
1994	ret = strscpy(*bufp, dir->header.ctl_table[0].procname, *lenp);
1995	if (ret < 0)
1996		return ret;
1997	*bufp += ret;
1998	*lenp -= ret;
1999	ret += tmp_ret;
2000
2001	/* Avoid leading slash. */
2002	if (!ret)
2003		return ret;
2004
2005	tmp_ret = strscpy(*bufp, "/", *lenp);
2006	if (tmp_ret < 0)
2007		return tmp_ret;
2008	*bufp += tmp_ret;
2009	*lenp -= tmp_ret;
2010
2011	return ret + tmp_ret;
2012}
2013
2014BPF_CALL_4(bpf_sysctl_get_name, struct bpf_sysctl_kern *, ctx, char *, buf,
2015	   size_t, buf_len, u64, flags)
2016{
2017	ssize_t tmp_ret = 0, ret;
2018
2019	if (!buf)
2020		return -EINVAL;
2021
2022	if (!(flags & BPF_F_SYSCTL_BASE_NAME)) {
2023		if (!ctx->head)
2024			return -EINVAL;
2025		tmp_ret = sysctl_cpy_dir(ctx->head->parent, &buf, &buf_len);
2026		if (tmp_ret < 0)
2027			return tmp_ret;
2028	}
2029
2030	ret = strscpy(buf, ctx->table->procname, buf_len);
2031
2032	return ret < 0 ? ret : tmp_ret + ret;
2033}
2034
2035static const struct bpf_func_proto bpf_sysctl_get_name_proto = {
2036	.func		= bpf_sysctl_get_name,
2037	.gpl_only	= false,
2038	.ret_type	= RET_INTEGER,
2039	.arg1_type	= ARG_PTR_TO_CTX,
2040	.arg2_type	= ARG_PTR_TO_MEM,
2041	.arg3_type	= ARG_CONST_SIZE,
2042	.arg4_type	= ARG_ANYTHING,
2043};
2044
2045static int copy_sysctl_value(char *dst, size_t dst_len, char *src,
2046			     size_t src_len)
2047{
2048	if (!dst)
2049		return -EINVAL;
2050
2051	if (!dst_len)
2052		return -E2BIG;
2053
2054	if (!src || !src_len) {
2055		memset(dst, 0, dst_len);
2056		return -EINVAL;
2057	}
2058
2059	memcpy(dst, src, min(dst_len, src_len));
2060
2061	if (dst_len > src_len) {
2062		memset(dst + src_len, '\0', dst_len - src_len);
2063		return src_len;
2064	}
2065
2066	dst[dst_len - 1] = '\0';
2067
2068	return -E2BIG;
2069}
2070
2071BPF_CALL_3(bpf_sysctl_get_current_value, struct bpf_sysctl_kern *, ctx,
2072	   char *, buf, size_t, buf_len)
2073{
2074	return copy_sysctl_value(buf, buf_len, ctx->cur_val, ctx->cur_len);
2075}
2076
2077static const struct bpf_func_proto bpf_sysctl_get_current_value_proto = {
2078	.func		= bpf_sysctl_get_current_value,
2079	.gpl_only	= false,
2080	.ret_type	= RET_INTEGER,
2081	.arg1_type	= ARG_PTR_TO_CTX,
2082	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
2083	.arg3_type	= ARG_CONST_SIZE,
2084};
2085
2086BPF_CALL_3(bpf_sysctl_get_new_value, struct bpf_sysctl_kern *, ctx, char *, buf,
2087	   size_t, buf_len)
2088{
2089	if (!ctx->write) {
2090		if (buf && buf_len)
2091			memset(buf, '\0', buf_len);
2092		return -EINVAL;
2093	}
2094	return copy_sysctl_value(buf, buf_len, ctx->new_val, ctx->new_len);
2095}
2096
2097static const struct bpf_func_proto bpf_sysctl_get_new_value_proto = {
2098	.func		= bpf_sysctl_get_new_value,
2099	.gpl_only	= false,
2100	.ret_type	= RET_INTEGER,
2101	.arg1_type	= ARG_PTR_TO_CTX,
2102	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
2103	.arg3_type	= ARG_CONST_SIZE,
2104};
2105
2106BPF_CALL_3(bpf_sysctl_set_new_value, struct bpf_sysctl_kern *, ctx,
2107	   const char *, buf, size_t, buf_len)
2108{
2109	if (!ctx->write || !ctx->new_val || !ctx->new_len || !buf || !buf_len)
2110		return -EINVAL;
2111
2112	if (buf_len > PAGE_SIZE - 1)
2113		return -E2BIG;
2114
2115	memcpy(ctx->new_val, buf, buf_len);
2116	ctx->new_len = buf_len;
2117	ctx->new_updated = 1;
2118
2119	return 0;
2120}
2121
2122static const struct bpf_func_proto bpf_sysctl_set_new_value_proto = {
2123	.func		= bpf_sysctl_set_new_value,
2124	.gpl_only	= false,
2125	.ret_type	= RET_INTEGER,
2126	.arg1_type	= ARG_PTR_TO_CTX,
2127	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
2128	.arg3_type	= ARG_CONST_SIZE,
2129};
2130
2131static const struct bpf_func_proto *
2132sysctl_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2133{
2134	const struct bpf_func_proto *func_proto;
2135
2136	func_proto = cgroup_common_func_proto(func_id, prog);
2137	if (func_proto)
2138		return func_proto;
2139
2140	func_proto = cgroup_current_func_proto(func_id, prog);
2141	if (func_proto)
2142		return func_proto;
2143
2144	switch (func_id) {
2145	case BPF_FUNC_sysctl_get_name:
2146		return &bpf_sysctl_get_name_proto;
2147	case BPF_FUNC_sysctl_get_current_value:
2148		return &bpf_sysctl_get_current_value_proto;
2149	case BPF_FUNC_sysctl_get_new_value:
2150		return &bpf_sysctl_get_new_value_proto;
2151	case BPF_FUNC_sysctl_set_new_value:
2152		return &bpf_sysctl_set_new_value_proto;
2153	case BPF_FUNC_ktime_get_coarse_ns:
2154		return &bpf_ktime_get_coarse_ns_proto;
2155	case BPF_FUNC_perf_event_output:
2156		return &bpf_event_output_data_proto;
2157	default:
2158		return bpf_base_func_proto(func_id);
2159	}
2160}
2161
2162static bool sysctl_is_valid_access(int off, int size, enum bpf_access_type type,
2163				   const struct bpf_prog *prog,
2164				   struct bpf_insn_access_aux *info)
2165{
2166	const int size_default = sizeof(__u32);
2167
2168	if (off < 0 || off + size > sizeof(struct bpf_sysctl) || off % size)
2169		return false;
2170
2171	switch (off) {
2172	case bpf_ctx_range(struct bpf_sysctl, write):
2173		if (type != BPF_READ)
2174			return false;
2175		bpf_ctx_record_field_size(info, size_default);
2176		return bpf_ctx_narrow_access_ok(off, size, size_default);
2177	case bpf_ctx_range(struct bpf_sysctl, file_pos):
2178		if (type == BPF_READ) {
2179			bpf_ctx_record_field_size(info, size_default);
2180			return bpf_ctx_narrow_access_ok(off, size, size_default);
2181		} else {
2182			return size == size_default;
2183		}
2184	default:
2185		return false;
2186	}
2187}
2188
2189static u32 sysctl_convert_ctx_access(enum bpf_access_type type,
2190				     const struct bpf_insn *si,
2191				     struct bpf_insn *insn_buf,
2192				     struct bpf_prog *prog, u32 *target_size)
2193{
2194	struct bpf_insn *insn = insn_buf;
2195	u32 read_size;
2196
2197	switch (si->off) {
2198	case offsetof(struct bpf_sysctl, write):
2199		*insn++ = BPF_LDX_MEM(
2200			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
2201			bpf_target_off(struct bpf_sysctl_kern, write,
2202				       sizeof_field(struct bpf_sysctl_kern,
2203						    write),
2204				       target_size));
2205		break;
2206	case offsetof(struct bpf_sysctl, file_pos):
2207		/* ppos is a pointer so it should be accessed via indirect
2208		 * loads and stores. Also for stores additional temporary
2209		 * register is used since neither src_reg nor dst_reg can be
2210		 * overridden.
2211		 */
2212		if (type == BPF_WRITE) {
2213			int treg = BPF_REG_9;
2214
2215			if (si->src_reg == treg || si->dst_reg == treg)
2216				--treg;
2217			if (si->src_reg == treg || si->dst_reg == treg)
2218				--treg;
2219			*insn++ = BPF_STX_MEM(
2220				BPF_DW, si->dst_reg, treg,
2221				offsetof(struct bpf_sysctl_kern, tmp_reg));
2222			*insn++ = BPF_LDX_MEM(
2223				BPF_FIELD_SIZEOF(struct bpf_sysctl_kern, ppos),
2224				treg, si->dst_reg,
2225				offsetof(struct bpf_sysctl_kern, ppos));
2226			*insn++ = BPF_STX_MEM(
2227				BPF_SIZEOF(u32), treg, si->src_reg,
 
2228				bpf_ctx_narrow_access_offset(
2229					0, sizeof(u32), sizeof(loff_t)));
 
2230			*insn++ = BPF_LDX_MEM(
2231				BPF_DW, treg, si->dst_reg,
2232				offsetof(struct bpf_sysctl_kern, tmp_reg));
2233		} else {
2234			*insn++ = BPF_LDX_MEM(
2235				BPF_FIELD_SIZEOF(struct bpf_sysctl_kern, ppos),
2236				si->dst_reg, si->src_reg,
2237				offsetof(struct bpf_sysctl_kern, ppos));
2238			read_size = bpf_size_to_bytes(BPF_SIZE(si->code));
2239			*insn++ = BPF_LDX_MEM(
2240				BPF_SIZE(si->code), si->dst_reg, si->dst_reg,
2241				bpf_ctx_narrow_access_offset(
2242					0, read_size, sizeof(loff_t)));
2243		}
2244		*target_size = sizeof(u32);
2245		break;
2246	}
2247
2248	return insn - insn_buf;
2249}
2250
2251const struct bpf_verifier_ops cg_sysctl_verifier_ops = {
2252	.get_func_proto		= sysctl_func_proto,
2253	.is_valid_access	= sysctl_is_valid_access,
2254	.convert_ctx_access	= sysctl_convert_ctx_access,
2255};
2256
2257const struct bpf_prog_ops cg_sysctl_prog_ops = {
2258};
2259
2260#ifdef CONFIG_NET
2261BPF_CALL_1(bpf_get_netns_cookie_sockopt, struct bpf_sockopt_kern *, ctx)
2262{
2263	const struct net *net = ctx ? sock_net(ctx->sk) : &init_net;
2264
2265	return net->net_cookie;
2266}
2267
2268static const struct bpf_func_proto bpf_get_netns_cookie_sockopt_proto = {
2269	.func		= bpf_get_netns_cookie_sockopt,
2270	.gpl_only	= false,
2271	.ret_type	= RET_INTEGER,
2272	.arg1_type	= ARG_PTR_TO_CTX_OR_NULL,
2273};
2274#endif
2275
2276static const struct bpf_func_proto *
2277cg_sockopt_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2278{
2279	const struct bpf_func_proto *func_proto;
2280
2281	func_proto = cgroup_common_func_proto(func_id, prog);
2282	if (func_proto)
2283		return func_proto;
2284
2285	func_proto = cgroup_current_func_proto(func_id, prog);
2286	if (func_proto)
2287		return func_proto;
2288
2289	switch (func_id) {
2290#ifdef CONFIG_NET
2291	case BPF_FUNC_get_netns_cookie:
2292		return &bpf_get_netns_cookie_sockopt_proto;
2293	case BPF_FUNC_sk_storage_get:
2294		return &bpf_sk_storage_get_proto;
2295	case BPF_FUNC_sk_storage_delete:
2296		return &bpf_sk_storage_delete_proto;
2297	case BPF_FUNC_setsockopt:
2298		if (prog->expected_attach_type == BPF_CGROUP_SETSOCKOPT)
2299			return &bpf_sk_setsockopt_proto;
2300		return NULL;
2301	case BPF_FUNC_getsockopt:
2302		if (prog->expected_attach_type == BPF_CGROUP_SETSOCKOPT)
2303			return &bpf_sk_getsockopt_proto;
2304		return NULL;
2305#endif
2306#ifdef CONFIG_INET
2307	case BPF_FUNC_tcp_sock:
2308		return &bpf_tcp_sock_proto;
2309#endif
2310	case BPF_FUNC_perf_event_output:
2311		return &bpf_event_output_data_proto;
2312	default:
2313		return bpf_base_func_proto(func_id);
2314	}
2315}
2316
2317static bool cg_sockopt_is_valid_access(int off, int size,
2318				       enum bpf_access_type type,
2319				       const struct bpf_prog *prog,
2320				       struct bpf_insn_access_aux *info)
2321{
2322	const int size_default = sizeof(__u32);
2323
2324	if (off < 0 || off >= sizeof(struct bpf_sockopt))
2325		return false;
2326
2327	if (off % size != 0)
2328		return false;
2329
2330	if (type == BPF_WRITE) {
2331		switch (off) {
2332		case offsetof(struct bpf_sockopt, retval):
2333			if (size != size_default)
2334				return false;
2335			return prog->expected_attach_type ==
2336				BPF_CGROUP_GETSOCKOPT;
2337		case offsetof(struct bpf_sockopt, optname):
2338			fallthrough;
2339		case offsetof(struct bpf_sockopt, level):
2340			if (size != size_default)
2341				return false;
2342			return prog->expected_attach_type ==
2343				BPF_CGROUP_SETSOCKOPT;
2344		case offsetof(struct bpf_sockopt, optlen):
2345			return size == size_default;
2346		default:
2347			return false;
2348		}
2349	}
2350
2351	switch (off) {
2352	case offsetof(struct bpf_sockopt, sk):
2353		if (size != sizeof(__u64))
2354			return false;
2355		info->reg_type = PTR_TO_SOCKET;
2356		break;
2357	case offsetof(struct bpf_sockopt, optval):
2358		if (size != sizeof(__u64))
2359			return false;
2360		info->reg_type = PTR_TO_PACKET;
2361		break;
2362	case offsetof(struct bpf_sockopt, optval_end):
2363		if (size != sizeof(__u64))
2364			return false;
2365		info->reg_type = PTR_TO_PACKET_END;
2366		break;
2367	case offsetof(struct bpf_sockopt, retval):
2368		if (size != size_default)
2369			return false;
2370		return prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT;
2371	default:
2372		if (size != size_default)
2373			return false;
2374		break;
2375	}
2376	return true;
2377}
2378
2379#define CG_SOCKOPT_ACCESS_FIELD(T, F)					\
2380	T(BPF_FIELD_SIZEOF(struct bpf_sockopt_kern, F),			\
2381	  si->dst_reg, si->src_reg,					\
2382	  offsetof(struct bpf_sockopt_kern, F))
 
 
 
 
 
 
 
2383
2384static u32 cg_sockopt_convert_ctx_access(enum bpf_access_type type,
2385					 const struct bpf_insn *si,
2386					 struct bpf_insn *insn_buf,
2387					 struct bpf_prog *prog,
2388					 u32 *target_size)
2389{
2390	struct bpf_insn *insn = insn_buf;
2391
2392	switch (si->off) {
2393	case offsetof(struct bpf_sockopt, sk):
2394		*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, sk);
2395		break;
2396	case offsetof(struct bpf_sockopt, level):
2397		if (type == BPF_WRITE)
2398			*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_STX_MEM, level);
2399		else
2400			*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, level);
2401		break;
2402	case offsetof(struct bpf_sockopt, optname):
2403		if (type == BPF_WRITE)
2404			*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_STX_MEM, optname);
2405		else
2406			*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, optname);
2407		break;
2408	case offsetof(struct bpf_sockopt, optlen):
2409		if (type == BPF_WRITE)
2410			*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_STX_MEM, optlen);
2411		else
2412			*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, optlen);
2413		break;
2414	case offsetof(struct bpf_sockopt, retval):
2415		BUILD_BUG_ON(offsetof(struct bpf_cg_run_ctx, run_ctx) != 0);
2416
2417		if (type == BPF_WRITE) {
2418			int treg = BPF_REG_9;
2419
2420			if (si->src_reg == treg || si->dst_reg == treg)
2421				--treg;
2422			if (si->src_reg == treg || si->dst_reg == treg)
2423				--treg;
2424			*insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, treg,
2425					      offsetof(struct bpf_sockopt_kern, tmp_reg));
2426			*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sockopt_kern, current_task),
2427					      treg, si->dst_reg,
2428					      offsetof(struct bpf_sockopt_kern, current_task));
2429			*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct task_struct, bpf_ctx),
2430					      treg, treg,
2431					      offsetof(struct task_struct, bpf_ctx));
2432			*insn++ = BPF_STX_MEM(BPF_FIELD_SIZEOF(struct bpf_cg_run_ctx, retval),
2433					      treg, si->src_reg,
2434					      offsetof(struct bpf_cg_run_ctx, retval));
 
 
2435			*insn++ = BPF_LDX_MEM(BPF_DW, treg, si->dst_reg,
2436					      offsetof(struct bpf_sockopt_kern, tmp_reg));
2437		} else {
2438			*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sockopt_kern, current_task),
2439					      si->dst_reg, si->src_reg,
2440					      offsetof(struct bpf_sockopt_kern, current_task));
2441			*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct task_struct, bpf_ctx),
2442					      si->dst_reg, si->dst_reg,
2443					      offsetof(struct task_struct, bpf_ctx));
2444			*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_cg_run_ctx, retval),
2445					      si->dst_reg, si->dst_reg,
2446					      offsetof(struct bpf_cg_run_ctx, retval));
2447		}
2448		break;
2449	case offsetof(struct bpf_sockopt, optval):
2450		*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, optval);
2451		break;
2452	case offsetof(struct bpf_sockopt, optval_end):
2453		*insn++ = CG_SOCKOPT_ACCESS_FIELD(BPF_LDX_MEM, optval_end);
2454		break;
2455	}
2456
2457	return insn - insn_buf;
2458}
2459
2460static int cg_sockopt_get_prologue(struct bpf_insn *insn_buf,
2461				   bool direct_write,
2462				   const struct bpf_prog *prog)
2463{
2464	/* Nothing to do for sockopt argument. The data is kzalloc'ated.
2465	 */
2466	return 0;
2467}
2468
2469const struct bpf_verifier_ops cg_sockopt_verifier_ops = {
2470	.get_func_proto		= cg_sockopt_func_proto,
2471	.is_valid_access	= cg_sockopt_is_valid_access,
2472	.convert_ctx_access	= cg_sockopt_convert_ctx_access,
2473	.gen_prologue		= cg_sockopt_get_prologue,
2474};
2475
2476const struct bpf_prog_ops cg_sockopt_prog_ops = {
2477};
2478
2479/* Common helpers for cgroup hooks. */
2480const struct bpf_func_proto *
2481cgroup_common_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2482{
2483	switch (func_id) {
2484	case BPF_FUNC_get_local_storage:
2485		return &bpf_get_local_storage_proto;
2486	case BPF_FUNC_get_retval:
2487		switch (prog->expected_attach_type) {
2488		case BPF_CGROUP_INET_INGRESS:
2489		case BPF_CGROUP_INET_EGRESS:
2490		case BPF_CGROUP_SOCK_OPS:
2491		case BPF_CGROUP_UDP4_RECVMSG:
2492		case BPF_CGROUP_UDP6_RECVMSG:
 
2493		case BPF_CGROUP_INET4_GETPEERNAME:
2494		case BPF_CGROUP_INET6_GETPEERNAME:
 
2495		case BPF_CGROUP_INET4_GETSOCKNAME:
2496		case BPF_CGROUP_INET6_GETSOCKNAME:
 
2497			return NULL;
2498		default:
2499			return &bpf_get_retval_proto;
2500		}
2501	case BPF_FUNC_set_retval:
2502		switch (prog->expected_attach_type) {
2503		case BPF_CGROUP_INET_INGRESS:
2504		case BPF_CGROUP_INET_EGRESS:
2505		case BPF_CGROUP_SOCK_OPS:
2506		case BPF_CGROUP_UDP4_RECVMSG:
2507		case BPF_CGROUP_UDP6_RECVMSG:
 
2508		case BPF_CGROUP_INET4_GETPEERNAME:
2509		case BPF_CGROUP_INET6_GETPEERNAME:
 
2510		case BPF_CGROUP_INET4_GETSOCKNAME:
2511		case BPF_CGROUP_INET6_GETSOCKNAME:
 
2512			return NULL;
2513		default:
2514			return &bpf_set_retval_proto;
2515		}
2516	default:
2517		return NULL;
2518	}
2519}
2520
2521/* Common helpers for cgroup hooks with valid process context. */
2522const struct bpf_func_proto *
2523cgroup_current_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2524{
2525	switch (func_id) {
2526	case BPF_FUNC_get_current_uid_gid:
2527		return &bpf_get_current_uid_gid_proto;
2528	case BPF_FUNC_get_current_pid_tgid:
2529		return &bpf_get_current_pid_tgid_proto;
2530	case BPF_FUNC_get_current_comm:
2531		return &bpf_get_current_comm_proto;
2532	case BPF_FUNC_get_current_cgroup_id:
2533		return &bpf_get_current_cgroup_id_proto;
2534	case BPF_FUNC_get_current_ancestor_cgroup_id:
2535		return &bpf_get_current_ancestor_cgroup_id_proto;
2536#ifdef CONFIG_CGROUP_NET_CLASSID
2537	case BPF_FUNC_get_cgroup_classid:
2538		return &bpf_get_cgroup_classid_curr_proto;
2539#endif
2540	default:
2541		return NULL;
2542	}
2543}
v6.9.4
   1// SPDX-License-Identifier: GPL-2.0-only
   2/*
   3 * Functions to manage eBPF programs attached to cgroups
   4 *
   5 * Copyright (c) 2016 Daniel Mack
   6 */
   7
   8#include <linux/kernel.h>
   9#include <linux/atomic.h>
  10#include <linux/cgroup.h>
  11#include <linux/filter.h>
  12#include <linux/slab.h>
  13#include <linux/sysctl.h>
  14#include <linux/string.h>
  15#include <linux/bpf.h>
  16#include <linux/bpf-cgroup.h>
  17#include <linux/bpf_lsm.h>
  18#include <linux/bpf_verifier.h>
  19#include <net/sock.h>
  20#include <net/bpf_sk_storage.h>
  21
  22#include "../cgroup/cgroup-internal.h"
  23
  24DEFINE_STATIC_KEY_ARRAY_FALSE(cgroup_bpf_enabled_key, MAX_CGROUP_BPF_ATTACH_TYPE);
  25EXPORT_SYMBOL(cgroup_bpf_enabled_key);
  26
  27/* __always_inline is necessary to prevent indirect call through run_prog
  28 * function pointer.
  29 */
  30static __always_inline int
  31bpf_prog_run_array_cg(const struct cgroup_bpf *cgrp,
  32		      enum cgroup_bpf_attach_type atype,
  33		      const void *ctx, bpf_prog_run_fn run_prog,
  34		      int retval, u32 *ret_flags)
  35{
  36	const struct bpf_prog_array_item *item;
  37	const struct bpf_prog *prog;
  38	const struct bpf_prog_array *array;
  39	struct bpf_run_ctx *old_run_ctx;
  40	struct bpf_cg_run_ctx run_ctx;
  41	u32 func_ret;
  42
  43	run_ctx.retval = retval;
  44	migrate_disable();
  45	rcu_read_lock();
  46	array = rcu_dereference(cgrp->effective[atype]);
  47	item = &array->items[0];
  48	old_run_ctx = bpf_set_run_ctx(&run_ctx.run_ctx);
  49	while ((prog = READ_ONCE(item->prog))) {
  50		run_ctx.prog_item = item;
  51		func_ret = run_prog(prog, ctx);
  52		if (ret_flags) {
  53			*(ret_flags) |= (func_ret >> 1);
  54			func_ret &= 1;
  55		}
  56		if (!func_ret && !IS_ERR_VALUE((long)run_ctx.retval))
  57			run_ctx.retval = -EPERM;
  58		item++;
  59	}
  60	bpf_reset_run_ctx(old_run_ctx);
  61	rcu_read_unlock();
  62	migrate_enable();
  63	return run_ctx.retval;
  64}
  65
  66unsigned int __cgroup_bpf_run_lsm_sock(const void *ctx,
  67				       const struct bpf_insn *insn)
  68{
  69	const struct bpf_prog *shim_prog;
  70	struct sock *sk;
  71	struct cgroup *cgrp;
  72	int ret = 0;
  73	u64 *args;
  74
  75	args = (u64 *)ctx;
  76	sk = (void *)(unsigned long)args[0];
  77	/*shim_prog = container_of(insn, struct bpf_prog, insnsi);*/
  78	shim_prog = (const struct bpf_prog *)((void *)insn - offsetof(struct bpf_prog, insnsi));
  79
  80	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
  81	if (likely(cgrp))
  82		ret = bpf_prog_run_array_cg(&cgrp->bpf,
  83					    shim_prog->aux->cgroup_atype,
  84					    ctx, bpf_prog_run, 0, NULL);
  85	return ret;
  86}
  87
  88unsigned int __cgroup_bpf_run_lsm_socket(const void *ctx,
  89					 const struct bpf_insn *insn)
  90{
  91	const struct bpf_prog *shim_prog;
  92	struct socket *sock;
  93	struct cgroup *cgrp;
  94	int ret = 0;
  95	u64 *args;
  96
  97	args = (u64 *)ctx;
  98	sock = (void *)(unsigned long)args[0];
  99	/*shim_prog = container_of(insn, struct bpf_prog, insnsi);*/
 100	shim_prog = (const struct bpf_prog *)((void *)insn - offsetof(struct bpf_prog, insnsi));
 101
 102	cgrp = sock_cgroup_ptr(&sock->sk->sk_cgrp_data);
 103	if (likely(cgrp))
 104		ret = bpf_prog_run_array_cg(&cgrp->bpf,
 105					    shim_prog->aux->cgroup_atype,
 106					    ctx, bpf_prog_run, 0, NULL);
 107	return ret;
 108}
 109
 110unsigned int __cgroup_bpf_run_lsm_current(const void *ctx,
 111					  const struct bpf_insn *insn)
 112{
 113	const struct bpf_prog *shim_prog;
 114	struct cgroup *cgrp;
 115	int ret = 0;
 116
 117	/*shim_prog = container_of(insn, struct bpf_prog, insnsi);*/
 118	shim_prog = (const struct bpf_prog *)((void *)insn - offsetof(struct bpf_prog, insnsi));
 119
 120	/* We rely on trampoline's __bpf_prog_enter_lsm_cgroup to grab RCU read lock. */
 121	cgrp = task_dfl_cgroup(current);
 122	if (likely(cgrp))
 123		ret = bpf_prog_run_array_cg(&cgrp->bpf,
 124					    shim_prog->aux->cgroup_atype,
 125					    ctx, bpf_prog_run, 0, NULL);
 126	return ret;
 127}
 128
 129#ifdef CONFIG_BPF_LSM
 130struct cgroup_lsm_atype {
 131	u32 attach_btf_id;
 132	int refcnt;
 133};
 134
 135static struct cgroup_lsm_atype cgroup_lsm_atype[CGROUP_LSM_NUM];
 136
 137static enum cgroup_bpf_attach_type
 138bpf_cgroup_atype_find(enum bpf_attach_type attach_type, u32 attach_btf_id)
 139{
 140	int i;
 141
 142	lockdep_assert_held(&cgroup_mutex);
 143
 144	if (attach_type != BPF_LSM_CGROUP)
 145		return to_cgroup_bpf_attach_type(attach_type);
 146
 147	for (i = 0; i < ARRAY_SIZE(cgroup_lsm_atype); i++)
 148		if (cgroup_lsm_atype[i].attach_btf_id == attach_btf_id)
 149			return CGROUP_LSM_START + i;
 150
 151	for (i = 0; i < ARRAY_SIZE(cgroup_lsm_atype); i++)
 152		if (cgroup_lsm_atype[i].attach_btf_id == 0)
 153			return CGROUP_LSM_START + i;
 154
 155	return -E2BIG;
 156
 157}
 158
 159void bpf_cgroup_atype_get(u32 attach_btf_id, int cgroup_atype)
 160{
 161	int i = cgroup_atype - CGROUP_LSM_START;
 162
 163	lockdep_assert_held(&cgroup_mutex);
 164
 165	WARN_ON_ONCE(cgroup_lsm_atype[i].attach_btf_id &&
 166		     cgroup_lsm_atype[i].attach_btf_id != attach_btf_id);
 167
 168	cgroup_lsm_atype[i].attach_btf_id = attach_btf_id;
 169	cgroup_lsm_atype[i].refcnt++;
 170}
 171
 172void bpf_cgroup_atype_put(int cgroup_atype)
 173{
 174	int i = cgroup_atype - CGROUP_LSM_START;
 175
 176	cgroup_lock();
 177	if (--cgroup_lsm_atype[i].refcnt <= 0)
 178		cgroup_lsm_atype[i].attach_btf_id = 0;
 179	WARN_ON_ONCE(cgroup_lsm_atype[i].refcnt < 0);
 180	cgroup_unlock();
 181}
 182#else
 183static enum cgroup_bpf_attach_type
 184bpf_cgroup_atype_find(enum bpf_attach_type attach_type, u32 attach_btf_id)
 185{
 186	if (attach_type != BPF_LSM_CGROUP)
 187		return to_cgroup_bpf_attach_type(attach_type);
 188	return -EOPNOTSUPP;
 189}
 190#endif /* CONFIG_BPF_LSM */
 191
 192void cgroup_bpf_offline(struct cgroup *cgrp)
 193{
 194	cgroup_get(cgrp);
 195	percpu_ref_kill(&cgrp->bpf.refcnt);
 196}
 197
 198static void bpf_cgroup_storages_free(struct bpf_cgroup_storage *storages[])
 199{
 200	enum bpf_cgroup_storage_type stype;
 201
 202	for_each_cgroup_storage_type(stype)
 203		bpf_cgroup_storage_free(storages[stype]);
 204}
 205
 206static int bpf_cgroup_storages_alloc(struct bpf_cgroup_storage *storages[],
 207				     struct bpf_cgroup_storage *new_storages[],
 208				     enum bpf_attach_type type,
 209				     struct bpf_prog *prog,
 210				     struct cgroup *cgrp)
 211{
 212	enum bpf_cgroup_storage_type stype;
 213	struct bpf_cgroup_storage_key key;
 214	struct bpf_map *map;
 215
 216	key.cgroup_inode_id = cgroup_id(cgrp);
 217	key.attach_type = type;
 218
 219	for_each_cgroup_storage_type(stype) {
 220		map = prog->aux->cgroup_storage[stype];
 221		if (!map)
 222			continue;
 223
 224		storages[stype] = cgroup_storage_lookup((void *)map, &key, false);
 225		if (storages[stype])
 226			continue;
 227
 228		storages[stype] = bpf_cgroup_storage_alloc(prog, stype);
 229		if (IS_ERR(storages[stype])) {
 230			bpf_cgroup_storages_free(new_storages);
 231			return -ENOMEM;
 232		}
 233
 234		new_storages[stype] = storages[stype];
 235	}
 236
 237	return 0;
 238}
 239
 240static void bpf_cgroup_storages_assign(struct bpf_cgroup_storage *dst[],
 241				       struct bpf_cgroup_storage *src[])
 242{
 243	enum bpf_cgroup_storage_type stype;
 244
 245	for_each_cgroup_storage_type(stype)
 246		dst[stype] = src[stype];
 247}
 248
 249static void bpf_cgroup_storages_link(struct bpf_cgroup_storage *storages[],
 250				     struct cgroup *cgrp,
 251				     enum bpf_attach_type attach_type)
 252{
 253	enum bpf_cgroup_storage_type stype;
 254
 255	for_each_cgroup_storage_type(stype)
 256		bpf_cgroup_storage_link(storages[stype], cgrp, attach_type);
 257}
 258
 259/* Called when bpf_cgroup_link is auto-detached from dying cgroup.
 260 * It drops cgroup and bpf_prog refcounts, and marks bpf_link as defunct. It
 261 * doesn't free link memory, which will eventually be done by bpf_link's
 262 * release() callback, when its last FD is closed.
 263 */
 264static void bpf_cgroup_link_auto_detach(struct bpf_cgroup_link *link)
 265{
 266	cgroup_put(link->cgroup);
 267	link->cgroup = NULL;
 268}
 269
 270/**
 271 * cgroup_bpf_release() - put references of all bpf programs and
 272 *                        release all cgroup bpf data
 273 * @work: work structure embedded into the cgroup to modify
 274 */
 275static void cgroup_bpf_release(struct work_struct *work)
 276{
 277	struct cgroup *p, *cgrp = container_of(work, struct cgroup,
 278					       bpf.release_work);
 279	struct bpf_prog_array *old_array;
 280	struct list_head *storages = &cgrp->bpf.storages;
 281	struct bpf_cgroup_storage *storage, *stmp;
 282
 283	unsigned int atype;
 284
 285	cgroup_lock();
 286
 287	for (atype = 0; atype < ARRAY_SIZE(cgrp->bpf.progs); atype++) {
 288		struct hlist_head *progs = &cgrp->bpf.progs[atype];
 289		struct bpf_prog_list *pl;
 290		struct hlist_node *pltmp;
 291
 292		hlist_for_each_entry_safe(pl, pltmp, progs, node) {
 293			hlist_del(&pl->node);
 294			if (pl->prog) {
 295				if (pl->prog->expected_attach_type == BPF_LSM_CGROUP)
 296					bpf_trampoline_unlink_cgroup_shim(pl->prog);
 297				bpf_prog_put(pl->prog);
 298			}
 299			if (pl->link) {
 300				if (pl->link->link.prog->expected_attach_type == BPF_LSM_CGROUP)
 301					bpf_trampoline_unlink_cgroup_shim(pl->link->link.prog);
 302				bpf_cgroup_link_auto_detach(pl->link);
 303			}
 304			kfree(pl);
 305			static_branch_dec(&cgroup_bpf_enabled_key[atype]);
 306		}
 307		old_array = rcu_dereference_protected(
 308				cgrp->bpf.effective[atype],
 309				lockdep_is_held(&cgroup_mutex));
 310		bpf_prog_array_free(old_array);
 311	}
 312
 313	list_for_each_entry_safe(storage, stmp, storages, list_cg) {
 314		bpf_cgroup_storage_unlink(storage);
 315		bpf_cgroup_storage_free(storage);
 316	}
 317
 318	cgroup_unlock();
 319
 320	for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
 321		cgroup_bpf_put(p);
 322
 323	percpu_ref_exit(&cgrp->bpf.refcnt);
 324	cgroup_put(cgrp);
 325}
 326
 327/**
 328 * cgroup_bpf_release_fn() - callback used to schedule releasing
 329 *                           of bpf cgroup data
 330 * @ref: percpu ref counter structure
 331 */
 332static void cgroup_bpf_release_fn(struct percpu_ref *ref)
 333{
 334	struct cgroup *cgrp = container_of(ref, struct cgroup, bpf.refcnt);
 335
 336	INIT_WORK(&cgrp->bpf.release_work, cgroup_bpf_release);
 337	queue_work(system_wq, &cgrp->bpf.release_work);
 338}
 339
 340/* Get underlying bpf_prog of bpf_prog_list entry, regardless if it's through
 341 * link or direct prog.
 342 */
 343static struct bpf_prog *prog_list_prog(struct bpf_prog_list *pl)
 344{
 345	if (pl->prog)
 346		return pl->prog;
 347	if (pl->link)
 348		return pl->link->link.prog;
 349	return NULL;
 350}
 351
 352/* count number of elements in the list.
 353 * it's slow but the list cannot be long
 354 */
 355static u32 prog_list_length(struct hlist_head *head)
 356{
 357	struct bpf_prog_list *pl;
 358	u32 cnt = 0;
 359
 360	hlist_for_each_entry(pl, head, node) {
 361		if (!prog_list_prog(pl))
 362			continue;
 363		cnt++;
 364	}
 365	return cnt;
 366}
 367
 368/* if parent has non-overridable prog attached,
 369 * disallow attaching new programs to the descendent cgroup.
 370 * if parent has overridable or multi-prog, allow attaching
 371 */
 372static bool hierarchy_allows_attach(struct cgroup *cgrp,
 373				    enum cgroup_bpf_attach_type atype)
 374{
 375	struct cgroup *p;
 376
 377	p = cgroup_parent(cgrp);
 378	if (!p)
 379		return true;
 380	do {
 381		u32 flags = p->bpf.flags[atype];
 382		u32 cnt;
 383
 384		if (flags & BPF_F_ALLOW_MULTI)
 385			return true;
 386		cnt = prog_list_length(&p->bpf.progs[atype]);
 387		WARN_ON_ONCE(cnt > 1);
 388		if (cnt == 1)
 389			return !!(flags & BPF_F_ALLOW_OVERRIDE);
 390		p = cgroup_parent(p);
 391	} while (p);
 392	return true;
 393}
 394
 395/* compute a chain of effective programs for a given cgroup:
 396 * start from the list of programs in this cgroup and add
 397 * all parent programs.
 398 * Note that parent's F_ALLOW_OVERRIDE-type program is yielding
 399 * to programs in this cgroup
 400 */
 401static int compute_effective_progs(struct cgroup *cgrp,
 402				   enum cgroup_bpf_attach_type atype,
 403				   struct bpf_prog_array **array)
 404{
 405	struct bpf_prog_array_item *item;
 406	struct bpf_prog_array *progs;
 407	struct bpf_prog_list *pl;
 408	struct cgroup *p = cgrp;
 409	int cnt = 0;
 410
 411	/* count number of effective programs by walking parents */
 412	do {
 413		if (cnt == 0 || (p->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
 414			cnt += prog_list_length(&p->bpf.progs[atype]);
 415		p = cgroup_parent(p);
 416	} while (p);
 417
 418	progs = bpf_prog_array_alloc(cnt, GFP_KERNEL);
 419	if (!progs)
 420		return -ENOMEM;
 421
 422	/* populate the array with effective progs */
 423	cnt = 0;
 424	p = cgrp;
 425	do {
 426		if (cnt > 0 && !(p->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
 427			continue;
 428
 429		hlist_for_each_entry(pl, &p->bpf.progs[atype], node) {
 430			if (!prog_list_prog(pl))
 431				continue;
 432
 433			item = &progs->items[cnt];
 434			item->prog = prog_list_prog(pl);
 435			bpf_cgroup_storages_assign(item->cgroup_storage,
 436						   pl->storage);
 437			cnt++;
 438		}
 439	} while ((p = cgroup_parent(p)));
 440
 441	*array = progs;
 442	return 0;
 443}
 444
 445static void activate_effective_progs(struct cgroup *cgrp,
 446				     enum cgroup_bpf_attach_type atype,
 447				     struct bpf_prog_array *old_array)
 448{
 449	old_array = rcu_replace_pointer(cgrp->bpf.effective[atype], old_array,
 450					lockdep_is_held(&cgroup_mutex));
 451	/* free prog array after grace period, since __cgroup_bpf_run_*()
 452	 * might be still walking the array
 453	 */
 454	bpf_prog_array_free(old_array);
 455}
 456
 457/**
 458 * cgroup_bpf_inherit() - inherit effective programs from parent
 459 * @cgrp: the cgroup to modify
 460 */
 461int cgroup_bpf_inherit(struct cgroup *cgrp)
 462{
 463/* has to use marco instead of const int, since compiler thinks
 464 * that array below is variable length
 465 */
 466#define	NR ARRAY_SIZE(cgrp->bpf.effective)
 467	struct bpf_prog_array *arrays[NR] = {};
 468	struct cgroup *p;
 469	int ret, i;
 470
 471	ret = percpu_ref_init(&cgrp->bpf.refcnt, cgroup_bpf_release_fn, 0,
 472			      GFP_KERNEL);
 473	if (ret)
 474		return ret;
 475
 476	for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
 477		cgroup_bpf_get(p);
 478
 479	for (i = 0; i < NR; i++)
 480		INIT_HLIST_HEAD(&cgrp->bpf.progs[i]);
 481
 482	INIT_LIST_HEAD(&cgrp->bpf.storages);
 483
 484	for (i = 0; i < NR; i++)
 485		if (compute_effective_progs(cgrp, i, &arrays[i]))
 486			goto cleanup;
 487
 488	for (i = 0; i < NR; i++)
 489		activate_effective_progs(cgrp, i, arrays[i]);
 490
 491	return 0;
 492cleanup:
 493	for (i = 0; i < NR; i++)
 494		bpf_prog_array_free(arrays[i]);
 495
 496	for (p = cgroup_parent(cgrp); p; p = cgroup_parent(p))
 497		cgroup_bpf_put(p);
 498
 499	percpu_ref_exit(&cgrp->bpf.refcnt);
 500
 501	return -ENOMEM;
 502}
 503
 504static int update_effective_progs(struct cgroup *cgrp,
 505				  enum cgroup_bpf_attach_type atype)
 506{
 507	struct cgroup_subsys_state *css;
 508	int err;
 509
 510	/* allocate and recompute effective prog arrays */
 511	css_for_each_descendant_pre(css, &cgrp->self) {
 512		struct cgroup *desc = container_of(css, struct cgroup, self);
 513
 514		if (percpu_ref_is_zero(&desc->bpf.refcnt))
 515			continue;
 516
 517		err = compute_effective_progs(desc, atype, &desc->bpf.inactive);
 518		if (err)
 519			goto cleanup;
 520	}
 521
 522	/* all allocations were successful. Activate all prog arrays */
 523	css_for_each_descendant_pre(css, &cgrp->self) {
 524		struct cgroup *desc = container_of(css, struct cgroup, self);
 525
 526		if (percpu_ref_is_zero(&desc->bpf.refcnt)) {
 527			if (unlikely(desc->bpf.inactive)) {
 528				bpf_prog_array_free(desc->bpf.inactive);
 529				desc->bpf.inactive = NULL;
 530			}
 531			continue;
 532		}
 533
 534		activate_effective_progs(desc, atype, desc->bpf.inactive);
 535		desc->bpf.inactive = NULL;
 536	}
 537
 538	return 0;
 539
 540cleanup:
 541	/* oom while computing effective. Free all computed effective arrays
 542	 * since they were not activated
 543	 */
 544	css_for_each_descendant_pre(css, &cgrp->self) {
 545		struct cgroup *desc = container_of(css, struct cgroup, self);
 546
 547		bpf_prog_array_free(desc->bpf.inactive);
 548		desc->bpf.inactive = NULL;
 549	}
 550
 551	return err;
 552}
 553
 554#define BPF_CGROUP_MAX_PROGS 64
 555
 556static struct bpf_prog_list *find_attach_entry(struct hlist_head *progs,
 557					       struct bpf_prog *prog,
 558					       struct bpf_cgroup_link *link,
 559					       struct bpf_prog *replace_prog,
 560					       bool allow_multi)
 561{
 562	struct bpf_prog_list *pl;
 563
 564	/* single-attach case */
 565	if (!allow_multi) {
 566		if (hlist_empty(progs))
 567			return NULL;
 568		return hlist_entry(progs->first, typeof(*pl), node);
 569	}
 570
 571	hlist_for_each_entry(pl, progs, node) {
 572		if (prog && pl->prog == prog && prog != replace_prog)
 573			/* disallow attaching the same prog twice */
 574			return ERR_PTR(-EINVAL);
 575		if (link && pl->link == link)
 576			/* disallow attaching the same link twice */
 577			return ERR_PTR(-EINVAL);
 578	}
 579
 580	/* direct prog multi-attach w/ replacement case */
 581	if (replace_prog) {
 582		hlist_for_each_entry(pl, progs, node) {
 583			if (pl->prog == replace_prog)
 584				/* a match found */
 585				return pl;
 586		}
 587		/* prog to replace not found for cgroup */
 588		return ERR_PTR(-ENOENT);
 589	}
 590
 591	return NULL;
 592}
 593
 594/**
 595 * __cgroup_bpf_attach() - Attach the program or the link to a cgroup, and
 596 *                         propagate the change to descendants
 597 * @cgrp: The cgroup which descendants to traverse
 598 * @prog: A program to attach
 599 * @link: A link to attach
 600 * @replace_prog: Previously attached program to replace if BPF_F_REPLACE is set
 601 * @type: Type of attach operation
 602 * @flags: Option flags
 603 *
 604 * Exactly one of @prog or @link can be non-null.
 605 * Must be called with cgroup_mutex held.
 606 */
 607static int __cgroup_bpf_attach(struct cgroup *cgrp,
 608			       struct bpf_prog *prog, struct bpf_prog *replace_prog,
 609			       struct bpf_cgroup_link *link,
 610			       enum bpf_attach_type type, u32 flags)
 611{
 612	u32 saved_flags = (flags & (BPF_F_ALLOW_OVERRIDE | BPF_F_ALLOW_MULTI));
 613	struct bpf_prog *old_prog = NULL;
 614	struct bpf_cgroup_storage *storage[MAX_BPF_CGROUP_STORAGE_TYPE] = {};
 615	struct bpf_cgroup_storage *new_storage[MAX_BPF_CGROUP_STORAGE_TYPE] = {};
 616	struct bpf_prog *new_prog = prog ? : link->link.prog;
 617	enum cgroup_bpf_attach_type atype;
 618	struct bpf_prog_list *pl;
 619	struct hlist_head *progs;
 620	int err;
 621
 622	if (((flags & BPF_F_ALLOW_OVERRIDE) && (flags & BPF_F_ALLOW_MULTI)) ||
 623	    ((flags & BPF_F_REPLACE) && !(flags & BPF_F_ALLOW_MULTI)))
 624		/* invalid combination */
 625		return -EINVAL;
 626	if (link && (prog || replace_prog))
 627		/* only either link or prog/replace_prog can be specified */
 628		return -EINVAL;
 629	if (!!replace_prog != !!(flags & BPF_F_REPLACE))
 630		/* replace_prog implies BPF_F_REPLACE, and vice versa */
 631		return -EINVAL;
 632
 633	atype = bpf_cgroup_atype_find(type, new_prog->aux->attach_btf_id);
 634	if (atype < 0)
 635		return -EINVAL;
 636
 637	progs = &cgrp->bpf.progs[atype];
 638
 639	if (!hierarchy_allows_attach(cgrp, atype))
 640		return -EPERM;
 641
 642	if (!hlist_empty(progs) && cgrp->bpf.flags[atype] != saved_flags)
 643		/* Disallow attaching non-overridable on top
 644		 * of existing overridable in this cgroup.
 645		 * Disallow attaching multi-prog if overridable or none
 646		 */
 647		return -EPERM;
 648
 649	if (prog_list_length(progs) >= BPF_CGROUP_MAX_PROGS)
 650		return -E2BIG;
 651
 652	pl = find_attach_entry(progs, prog, link, replace_prog,
 653			       flags & BPF_F_ALLOW_MULTI);
 654	if (IS_ERR(pl))
 655		return PTR_ERR(pl);
 656
 657	if (bpf_cgroup_storages_alloc(storage, new_storage, type,
 658				      prog ? : link->link.prog, cgrp))
 659		return -ENOMEM;
 660
 661	if (pl) {
 662		old_prog = pl->prog;
 663	} else {
 664		struct hlist_node *last = NULL;
 665
 666		pl = kmalloc(sizeof(*pl), GFP_KERNEL);
 667		if (!pl) {
 668			bpf_cgroup_storages_free(new_storage);
 669			return -ENOMEM;
 670		}
 671		if (hlist_empty(progs))
 672			hlist_add_head(&pl->node, progs);
 673		else
 674			hlist_for_each(last, progs) {
 675				if (last->next)
 676					continue;
 677				hlist_add_behind(&pl->node, last);
 678				break;
 679			}
 680	}
 681
 682	pl->prog = prog;
 683	pl->link = link;
 684	bpf_cgroup_storages_assign(pl->storage, storage);
 685	cgrp->bpf.flags[atype] = saved_flags;
 686
 687	if (type == BPF_LSM_CGROUP) {
 688		err = bpf_trampoline_link_cgroup_shim(new_prog, atype);
 689		if (err)
 690			goto cleanup;
 691	}
 692
 693	err = update_effective_progs(cgrp, atype);
 694	if (err)
 695		goto cleanup_trampoline;
 696
 697	if (old_prog) {
 698		if (type == BPF_LSM_CGROUP)
 699			bpf_trampoline_unlink_cgroup_shim(old_prog);
 700		bpf_prog_put(old_prog);
 701	} else {
 702		static_branch_inc(&cgroup_bpf_enabled_key[atype]);
 703	}
 704	bpf_cgroup_storages_link(new_storage, cgrp, type);
 705	return 0;
 706
 707cleanup_trampoline:
 708	if (type == BPF_LSM_CGROUP)
 709		bpf_trampoline_unlink_cgroup_shim(new_prog);
 710
 711cleanup:
 712	if (old_prog) {
 713		pl->prog = old_prog;
 714		pl->link = NULL;
 715	}
 716	bpf_cgroup_storages_free(new_storage);
 717	if (!old_prog) {
 718		hlist_del(&pl->node);
 719		kfree(pl);
 720	}
 721	return err;
 722}
 723
 724static int cgroup_bpf_attach(struct cgroup *cgrp,
 725			     struct bpf_prog *prog, struct bpf_prog *replace_prog,
 726			     struct bpf_cgroup_link *link,
 727			     enum bpf_attach_type type,
 728			     u32 flags)
 729{
 730	int ret;
 731
 732	cgroup_lock();
 733	ret = __cgroup_bpf_attach(cgrp, prog, replace_prog, link, type, flags);
 734	cgroup_unlock();
 735	return ret;
 736}
 737
 738/* Swap updated BPF program for given link in effective program arrays across
 739 * all descendant cgroups. This function is guaranteed to succeed.
 740 */
 741static void replace_effective_prog(struct cgroup *cgrp,
 742				   enum cgroup_bpf_attach_type atype,
 743				   struct bpf_cgroup_link *link)
 744{
 745	struct bpf_prog_array_item *item;
 746	struct cgroup_subsys_state *css;
 747	struct bpf_prog_array *progs;
 748	struct bpf_prog_list *pl;
 749	struct hlist_head *head;
 750	struct cgroup *cg;
 751	int pos;
 752
 753	css_for_each_descendant_pre(css, &cgrp->self) {
 754		struct cgroup *desc = container_of(css, struct cgroup, self);
 755
 756		if (percpu_ref_is_zero(&desc->bpf.refcnt))
 757			continue;
 758
 759		/* find position of link in effective progs array */
 760		for (pos = 0, cg = desc; cg; cg = cgroup_parent(cg)) {
 761			if (pos && !(cg->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
 762				continue;
 763
 764			head = &cg->bpf.progs[atype];
 765			hlist_for_each_entry(pl, head, node) {
 766				if (!prog_list_prog(pl))
 767					continue;
 768				if (pl->link == link)
 769					goto found;
 770				pos++;
 771			}
 772		}
 773found:
 774		BUG_ON(!cg);
 775		progs = rcu_dereference_protected(
 776				desc->bpf.effective[atype],
 777				lockdep_is_held(&cgroup_mutex));
 778		item = &progs->items[pos];
 779		WRITE_ONCE(item->prog, link->link.prog);
 780	}
 781}
 782
 783/**
 784 * __cgroup_bpf_replace() - Replace link's program and propagate the change
 785 *                          to descendants
 786 * @cgrp: The cgroup which descendants to traverse
 787 * @link: A link for which to replace BPF program
 788 * @new_prog: &struct bpf_prog for the target BPF program with its refcnt
 789 *            incremented
 790 *
 791 * Must be called with cgroup_mutex held.
 792 */
 793static int __cgroup_bpf_replace(struct cgroup *cgrp,
 794				struct bpf_cgroup_link *link,
 795				struct bpf_prog *new_prog)
 796{
 797	enum cgroup_bpf_attach_type atype;
 798	struct bpf_prog *old_prog;
 799	struct bpf_prog_list *pl;
 800	struct hlist_head *progs;
 801	bool found = false;
 802
 803	atype = bpf_cgroup_atype_find(link->type, new_prog->aux->attach_btf_id);
 804	if (atype < 0)
 805		return -EINVAL;
 806
 807	progs = &cgrp->bpf.progs[atype];
 808
 809	if (link->link.prog->type != new_prog->type)
 810		return -EINVAL;
 811
 812	hlist_for_each_entry(pl, progs, node) {
 813		if (pl->link == link) {
 814			found = true;
 815			break;
 816		}
 817	}
 818	if (!found)
 819		return -ENOENT;
 820
 821	old_prog = xchg(&link->link.prog, new_prog);
 822	replace_effective_prog(cgrp, atype, link);
 823	bpf_prog_put(old_prog);
 824	return 0;
 825}
 826
 827static int cgroup_bpf_replace(struct bpf_link *link, struct bpf_prog *new_prog,
 828			      struct bpf_prog *old_prog)
 829{
 830	struct bpf_cgroup_link *cg_link;
 831	int ret;
 832
 833	cg_link = container_of(link, struct bpf_cgroup_link, link);
 834
 835	cgroup_lock();
 836	/* link might have been auto-released by dying cgroup, so fail */
 837	if (!cg_link->cgroup) {
 838		ret = -ENOLINK;
 839		goto out_unlock;
 840	}
 841	if (old_prog && link->prog != old_prog) {
 842		ret = -EPERM;
 843		goto out_unlock;
 844	}
 845	ret = __cgroup_bpf_replace(cg_link->cgroup, cg_link, new_prog);
 846out_unlock:
 847	cgroup_unlock();
 848	return ret;
 849}
 850
 851static struct bpf_prog_list *find_detach_entry(struct hlist_head *progs,
 852					       struct bpf_prog *prog,
 853					       struct bpf_cgroup_link *link,
 854					       bool allow_multi)
 855{
 856	struct bpf_prog_list *pl;
 857
 858	if (!allow_multi) {
 859		if (hlist_empty(progs))
 860			/* report error when trying to detach and nothing is attached */
 861			return ERR_PTR(-ENOENT);
 862
 863		/* to maintain backward compatibility NONE and OVERRIDE cgroups
 864		 * allow detaching with invalid FD (prog==NULL) in legacy mode
 865		 */
 866		return hlist_entry(progs->first, typeof(*pl), node);
 867	}
 868
 869	if (!prog && !link)
 870		/* to detach MULTI prog the user has to specify valid FD
 871		 * of the program or link to be detached
 872		 */
 873		return ERR_PTR(-EINVAL);
 874
 875	/* find the prog or link and detach it */
 876	hlist_for_each_entry(pl, progs, node) {
 877		if (pl->prog == prog && pl->link == link)
 878			return pl;
 879	}
 880	return ERR_PTR(-ENOENT);
 881}
 882
 883/**
 884 * purge_effective_progs() - After compute_effective_progs fails to alloc new
 885 *                           cgrp->bpf.inactive table we can recover by
 886 *                           recomputing the array in place.
 887 *
 888 * @cgrp: The cgroup which descendants to travers
 889 * @prog: A program to detach or NULL
 890 * @link: A link to detach or NULL
 891 * @atype: Type of detach operation
 892 */
 893static void purge_effective_progs(struct cgroup *cgrp, struct bpf_prog *prog,
 894				  struct bpf_cgroup_link *link,
 895				  enum cgroup_bpf_attach_type atype)
 896{
 897	struct cgroup_subsys_state *css;
 898	struct bpf_prog_array *progs;
 899	struct bpf_prog_list *pl;
 900	struct hlist_head *head;
 901	struct cgroup *cg;
 902	int pos;
 903
 904	/* recompute effective prog array in place */
 905	css_for_each_descendant_pre(css, &cgrp->self) {
 906		struct cgroup *desc = container_of(css, struct cgroup, self);
 907
 908		if (percpu_ref_is_zero(&desc->bpf.refcnt))
 909			continue;
 910
 911		/* find position of link or prog in effective progs array */
 912		for (pos = 0, cg = desc; cg; cg = cgroup_parent(cg)) {
 913			if (pos && !(cg->bpf.flags[atype] & BPF_F_ALLOW_MULTI))
 914				continue;
 915
 916			head = &cg->bpf.progs[atype];
 917			hlist_for_each_entry(pl, head, node) {
 918				if (!prog_list_prog(pl))
 919					continue;
 920				if (pl->prog == prog && pl->link == link)
 921					goto found;
 922				pos++;
 923			}
 924		}
 925
 926		/* no link or prog match, skip the cgroup of this layer */
 927		continue;
 928found:
 929		progs = rcu_dereference_protected(
 930				desc->bpf.effective[atype],
 931				lockdep_is_held(&cgroup_mutex));
 932
 933		/* Remove the program from the array */
 934		WARN_ONCE(bpf_prog_array_delete_safe_at(progs, pos),
 935			  "Failed to purge a prog from array at index %d", pos);
 936	}
 937}
 938
 939/**
 940 * __cgroup_bpf_detach() - Detach the program or link from a cgroup, and
 941 *                         propagate the change to descendants
 942 * @cgrp: The cgroup which descendants to traverse
 943 * @prog: A program to detach or NULL
 944 * @link: A link to detach or NULL
 945 * @type: Type of detach operation
 946 *
 947 * At most one of @prog or @link can be non-NULL.
 948 * Must be called with cgroup_mutex held.
 949 */
 950static int __cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
 951			       struct bpf_cgroup_link *link, enum bpf_attach_type type)
 952{
 953	enum cgroup_bpf_attach_type atype;
 954	struct bpf_prog *old_prog;
 955	struct bpf_prog_list *pl;
 956	struct hlist_head *progs;
 957	u32 attach_btf_id = 0;
 958	u32 flags;
 959
 960	if (prog)
 961		attach_btf_id = prog->aux->attach_btf_id;
 962	if (link)
 963		attach_btf_id = link->link.prog->aux->attach_btf_id;
 964
 965	atype = bpf_cgroup_atype_find(type, attach_btf_id);
 966	if (atype < 0)
 967		return -EINVAL;
 968
 969	progs = &cgrp->bpf.progs[atype];
 970	flags = cgrp->bpf.flags[atype];
 971
 972	if (prog && link)
 973		/* only one of prog or link can be specified */
 974		return -EINVAL;
 975
 976	pl = find_detach_entry(progs, prog, link, flags & BPF_F_ALLOW_MULTI);
 977	if (IS_ERR(pl))
 978		return PTR_ERR(pl);
 979
 980	/* mark it deleted, so it's ignored while recomputing effective */
 981	old_prog = pl->prog;
 982	pl->prog = NULL;
 983	pl->link = NULL;
 984
 985	if (update_effective_progs(cgrp, atype)) {
 986		/* if update effective array failed replace the prog with a dummy prog*/
 987		pl->prog = old_prog;
 988		pl->link = link;
 989		purge_effective_progs(cgrp, old_prog, link, atype);
 990	}
 991
 992	/* now can actually delete it from this cgroup list */
 993	hlist_del(&pl->node);
 994
 995	kfree(pl);
 996	if (hlist_empty(progs))
 997		/* last program was detached, reset flags to zero */
 998		cgrp->bpf.flags[atype] = 0;
 999	if (old_prog) {
1000		if (type == BPF_LSM_CGROUP)
1001			bpf_trampoline_unlink_cgroup_shim(old_prog);
1002		bpf_prog_put(old_prog);
1003	}
1004	static_branch_dec(&cgroup_bpf_enabled_key[atype]);
1005	return 0;
1006}
1007
1008static int cgroup_bpf_detach(struct cgroup *cgrp, struct bpf_prog *prog,
1009			     enum bpf_attach_type type)
1010{
1011	int ret;
1012
1013	cgroup_lock();
1014	ret = __cgroup_bpf_detach(cgrp, prog, NULL, type);
1015	cgroup_unlock();
1016	return ret;
1017}
1018
1019/* Must be called with cgroup_mutex held to avoid races. */
1020static int __cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
1021			      union bpf_attr __user *uattr)
1022{
1023	__u32 __user *prog_attach_flags = u64_to_user_ptr(attr->query.prog_attach_flags);
1024	bool effective_query = attr->query.query_flags & BPF_F_QUERY_EFFECTIVE;
1025	__u32 __user *prog_ids = u64_to_user_ptr(attr->query.prog_ids);
1026	enum bpf_attach_type type = attr->query.attach_type;
1027	enum cgroup_bpf_attach_type from_atype, to_atype;
1028	enum cgroup_bpf_attach_type atype;
1029	struct bpf_prog_array *effective;
1030	int cnt, ret = 0, i;
1031	int total_cnt = 0;
1032	u32 flags;
1033
1034	if (effective_query && prog_attach_flags)
1035		return -EINVAL;
1036
1037	if (type == BPF_LSM_CGROUP) {
1038		if (!effective_query && attr->query.prog_cnt &&
1039		    prog_ids && !prog_attach_flags)
1040			return -EINVAL;
1041
1042		from_atype = CGROUP_LSM_START;
1043		to_atype = CGROUP_LSM_END;
1044		flags = 0;
1045	} else {
1046		from_atype = to_cgroup_bpf_attach_type(type);
1047		if (from_atype < 0)
1048			return -EINVAL;
1049		to_atype = from_atype;
1050		flags = cgrp->bpf.flags[from_atype];
1051	}
1052
1053	for (atype = from_atype; atype <= to_atype; atype++) {
1054		if (effective_query) {
1055			effective = rcu_dereference_protected(cgrp->bpf.effective[atype],
1056							      lockdep_is_held(&cgroup_mutex));
1057			total_cnt += bpf_prog_array_length(effective);
1058		} else {
1059			total_cnt += prog_list_length(&cgrp->bpf.progs[atype]);
1060		}
1061	}
1062
1063	/* always output uattr->query.attach_flags as 0 during effective query */
1064	flags = effective_query ? 0 : flags;
1065	if (copy_to_user(&uattr->query.attach_flags, &flags, sizeof(flags)))
1066		return -EFAULT;
1067	if (copy_to_user(&uattr->query.prog_cnt, &total_cnt, sizeof(total_cnt)))
1068		return -EFAULT;
1069	if (attr->query.prog_cnt == 0 || !prog_ids || !total_cnt)
1070		/* return early if user requested only program count + flags */
1071		return 0;
1072
1073	if (attr->query.prog_cnt < total_cnt) {
1074		total_cnt = attr->query.prog_cnt;
1075		ret = -ENOSPC;
1076	}
1077
1078	for (atype = from_atype; atype <= to_atype && total_cnt; atype++) {
1079		if (effective_query) {
1080			effective = rcu_dereference_protected(cgrp->bpf.effective[atype],
1081							      lockdep_is_held(&cgroup_mutex));
1082			cnt = min_t(int, bpf_prog_array_length(effective), total_cnt);
1083			ret = bpf_prog_array_copy_to_user(effective, prog_ids, cnt);
1084		} else {
1085			struct hlist_head *progs;
1086			struct bpf_prog_list *pl;
1087			struct bpf_prog *prog;
1088			u32 id;
1089
1090			progs = &cgrp->bpf.progs[atype];
1091			cnt = min_t(int, prog_list_length(progs), total_cnt);
1092			i = 0;
1093			hlist_for_each_entry(pl, progs, node) {
1094				prog = prog_list_prog(pl);
1095				id = prog->aux->id;
1096				if (copy_to_user(prog_ids + i, &id, sizeof(id)))
1097					return -EFAULT;
1098				if (++i == cnt)
1099					break;
1100			}
1101
1102			if (prog_attach_flags) {
1103				flags = cgrp->bpf.flags[atype];
1104
1105				for (i = 0; i < cnt; i++)
1106					if (copy_to_user(prog_attach_flags + i,
1107							 &flags, sizeof(flags)))
1108						return -EFAULT;
1109				prog_attach_flags += cnt;
1110			}
1111		}
1112
1113		prog_ids += cnt;
1114		total_cnt -= cnt;
1115	}
1116	return ret;
1117}
1118
1119static int cgroup_bpf_query(struct cgroup *cgrp, const union bpf_attr *attr,
1120			    union bpf_attr __user *uattr)
1121{
1122	int ret;
1123
1124	cgroup_lock();
1125	ret = __cgroup_bpf_query(cgrp, attr, uattr);
1126	cgroup_unlock();
1127	return ret;
1128}
1129
1130int cgroup_bpf_prog_attach(const union bpf_attr *attr,
1131			   enum bpf_prog_type ptype, struct bpf_prog *prog)
1132{
1133	struct bpf_prog *replace_prog = NULL;
1134	struct cgroup *cgrp;
1135	int ret;
1136
1137	cgrp = cgroup_get_from_fd(attr->target_fd);
1138	if (IS_ERR(cgrp))
1139		return PTR_ERR(cgrp);
1140
1141	if ((attr->attach_flags & BPF_F_ALLOW_MULTI) &&
1142	    (attr->attach_flags & BPF_F_REPLACE)) {
1143		replace_prog = bpf_prog_get_type(attr->replace_bpf_fd, ptype);
1144		if (IS_ERR(replace_prog)) {
1145			cgroup_put(cgrp);
1146			return PTR_ERR(replace_prog);
1147		}
1148	}
1149
1150	ret = cgroup_bpf_attach(cgrp, prog, replace_prog, NULL,
1151				attr->attach_type, attr->attach_flags);
1152
1153	if (replace_prog)
1154		bpf_prog_put(replace_prog);
1155	cgroup_put(cgrp);
1156	return ret;
1157}
1158
1159int cgroup_bpf_prog_detach(const union bpf_attr *attr, enum bpf_prog_type ptype)
1160{
1161	struct bpf_prog *prog;
1162	struct cgroup *cgrp;
1163	int ret;
1164
1165	cgrp = cgroup_get_from_fd(attr->target_fd);
1166	if (IS_ERR(cgrp))
1167		return PTR_ERR(cgrp);
1168
1169	prog = bpf_prog_get_type(attr->attach_bpf_fd, ptype);
1170	if (IS_ERR(prog))
1171		prog = NULL;
1172
1173	ret = cgroup_bpf_detach(cgrp, prog, attr->attach_type);
1174	if (prog)
1175		bpf_prog_put(prog);
1176
1177	cgroup_put(cgrp);
1178	return ret;
1179}
1180
1181static void bpf_cgroup_link_release(struct bpf_link *link)
1182{
1183	struct bpf_cgroup_link *cg_link =
1184		container_of(link, struct bpf_cgroup_link, link);
1185	struct cgroup *cg;
1186
1187	/* link might have been auto-detached by dying cgroup already,
1188	 * in that case our work is done here
1189	 */
1190	if (!cg_link->cgroup)
1191		return;
1192
1193	cgroup_lock();
1194
1195	/* re-check cgroup under lock again */
1196	if (!cg_link->cgroup) {
1197		cgroup_unlock();
1198		return;
1199	}
1200
1201	WARN_ON(__cgroup_bpf_detach(cg_link->cgroup, NULL, cg_link,
1202				    cg_link->type));
1203	if (cg_link->type == BPF_LSM_CGROUP)
1204		bpf_trampoline_unlink_cgroup_shim(cg_link->link.prog);
1205
1206	cg = cg_link->cgroup;
1207	cg_link->cgroup = NULL;
1208
1209	cgroup_unlock();
1210
1211	cgroup_put(cg);
1212}
1213
1214static void bpf_cgroup_link_dealloc(struct bpf_link *link)
1215{
1216	struct bpf_cgroup_link *cg_link =
1217		container_of(link, struct bpf_cgroup_link, link);
1218
1219	kfree(cg_link);
1220}
1221
1222static int bpf_cgroup_link_detach(struct bpf_link *link)
1223{
1224	bpf_cgroup_link_release(link);
1225
1226	return 0;
1227}
1228
1229static void bpf_cgroup_link_show_fdinfo(const struct bpf_link *link,
1230					struct seq_file *seq)
1231{
1232	struct bpf_cgroup_link *cg_link =
1233		container_of(link, struct bpf_cgroup_link, link);
1234	u64 cg_id = 0;
1235
1236	cgroup_lock();
1237	if (cg_link->cgroup)
1238		cg_id = cgroup_id(cg_link->cgroup);
1239	cgroup_unlock();
1240
1241	seq_printf(seq,
1242		   "cgroup_id:\t%llu\n"
1243		   "attach_type:\t%d\n",
1244		   cg_id,
1245		   cg_link->type);
1246}
1247
1248static int bpf_cgroup_link_fill_link_info(const struct bpf_link *link,
1249					  struct bpf_link_info *info)
1250{
1251	struct bpf_cgroup_link *cg_link =
1252		container_of(link, struct bpf_cgroup_link, link);
1253	u64 cg_id = 0;
1254
1255	cgroup_lock();
1256	if (cg_link->cgroup)
1257		cg_id = cgroup_id(cg_link->cgroup);
1258	cgroup_unlock();
1259
1260	info->cgroup.cgroup_id = cg_id;
1261	info->cgroup.attach_type = cg_link->type;
1262	return 0;
1263}
1264
1265static const struct bpf_link_ops bpf_cgroup_link_lops = {
1266	.release = bpf_cgroup_link_release,
1267	.dealloc = bpf_cgroup_link_dealloc,
1268	.detach = bpf_cgroup_link_detach,
1269	.update_prog = cgroup_bpf_replace,
1270	.show_fdinfo = bpf_cgroup_link_show_fdinfo,
1271	.fill_link_info = bpf_cgroup_link_fill_link_info,
1272};
1273
1274int cgroup_bpf_link_attach(const union bpf_attr *attr, struct bpf_prog *prog)
1275{
1276	struct bpf_link_primer link_primer;
1277	struct bpf_cgroup_link *link;
1278	struct cgroup *cgrp;
1279	int err;
1280
1281	if (attr->link_create.flags)
1282		return -EINVAL;
1283
1284	cgrp = cgroup_get_from_fd(attr->link_create.target_fd);
1285	if (IS_ERR(cgrp))
1286		return PTR_ERR(cgrp);
1287
1288	link = kzalloc(sizeof(*link), GFP_USER);
1289	if (!link) {
1290		err = -ENOMEM;
1291		goto out_put_cgroup;
1292	}
1293	bpf_link_init(&link->link, BPF_LINK_TYPE_CGROUP, &bpf_cgroup_link_lops,
1294		      prog);
1295	link->cgroup = cgrp;
1296	link->type = attr->link_create.attach_type;
1297
1298	err = bpf_link_prime(&link->link, &link_primer);
1299	if (err) {
1300		kfree(link);
1301		goto out_put_cgroup;
1302	}
1303
1304	err = cgroup_bpf_attach(cgrp, NULL, NULL, link,
1305				link->type, BPF_F_ALLOW_MULTI);
1306	if (err) {
1307		bpf_link_cleanup(&link_primer);
1308		goto out_put_cgroup;
1309	}
1310
1311	return bpf_link_settle(&link_primer);
1312
1313out_put_cgroup:
1314	cgroup_put(cgrp);
1315	return err;
1316}
1317
1318int cgroup_bpf_prog_query(const union bpf_attr *attr,
1319			  union bpf_attr __user *uattr)
1320{
1321	struct cgroup *cgrp;
1322	int ret;
1323
1324	cgrp = cgroup_get_from_fd(attr->query.target_fd);
1325	if (IS_ERR(cgrp))
1326		return PTR_ERR(cgrp);
1327
1328	ret = cgroup_bpf_query(cgrp, attr, uattr);
1329
1330	cgroup_put(cgrp);
1331	return ret;
1332}
1333
1334/**
1335 * __cgroup_bpf_run_filter_skb() - Run a program for packet filtering
1336 * @sk: The socket sending or receiving traffic
1337 * @skb: The skb that is being sent or received
1338 * @atype: The type of program to be executed
1339 *
1340 * If no socket is passed, or the socket is not of type INET or INET6,
1341 * this function does nothing and returns 0.
1342 *
1343 * The program type passed in via @type must be suitable for network
1344 * filtering. No further check is performed to assert that.
1345 *
1346 * For egress packets, this function can return:
1347 *   NET_XMIT_SUCCESS    (0)	- continue with packet output
1348 *   NET_XMIT_DROP       (1)	- drop packet and notify TCP to call cwr
1349 *   NET_XMIT_CN         (2)	- continue with packet output and notify TCP
1350 *				  to call cwr
1351 *   -err			- drop packet
1352 *
1353 * For ingress packets, this function will return -EPERM if any
1354 * attached program was found and if it returned != 1 during execution.
1355 * Otherwise 0 is returned.
1356 */
1357int __cgroup_bpf_run_filter_skb(struct sock *sk,
1358				struct sk_buff *skb,
1359				enum cgroup_bpf_attach_type atype)
1360{
1361	unsigned int offset = -skb_network_offset(skb);
1362	struct sock *save_sk;
1363	void *saved_data_end;
1364	struct cgroup *cgrp;
1365	int ret;
1366
 
 
 
1367	if (sk->sk_family != AF_INET && sk->sk_family != AF_INET6)
1368		return 0;
1369
1370	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1371	save_sk = skb->sk;
1372	skb->sk = sk;
1373	__skb_push(skb, offset);
1374
1375	/* compute pointers for the bpf prog */
1376	bpf_compute_and_save_data_end(skb, &saved_data_end);
1377
1378	if (atype == CGROUP_INET_EGRESS) {
1379		u32 flags = 0;
1380		bool cn;
1381
1382		ret = bpf_prog_run_array_cg(&cgrp->bpf, atype, skb,
1383					    __bpf_prog_run_save_cb, 0, &flags);
1384
1385		/* Return values of CGROUP EGRESS BPF programs are:
1386		 *   0: drop packet
1387		 *   1: keep packet
1388		 *   2: drop packet and cn
1389		 *   3: keep packet and cn
1390		 *
1391		 * The returned value is then converted to one of the NET_XMIT
1392		 * or an error code that is then interpreted as drop packet
1393		 * (and no cn):
1394		 *   0: NET_XMIT_SUCCESS  skb should be transmitted
1395		 *   1: NET_XMIT_DROP     skb should be dropped and cn
1396		 *   2: NET_XMIT_CN       skb should be transmitted and cn
1397		 *   3: -err              skb should be dropped
1398		 */
1399
1400		cn = flags & BPF_RET_SET_CN;
1401		if (ret && !IS_ERR_VALUE((long)ret))
1402			ret = -EFAULT;
1403		if (!ret)
1404			ret = (cn ? NET_XMIT_CN : NET_XMIT_SUCCESS);
1405		else
1406			ret = (cn ? NET_XMIT_DROP : ret);
1407	} else {
1408		ret = bpf_prog_run_array_cg(&cgrp->bpf, atype,
1409					    skb, __bpf_prog_run_save_cb, 0,
1410					    NULL);
1411		if (ret && !IS_ERR_VALUE((long)ret))
1412			ret = -EFAULT;
1413	}
1414	bpf_restore_data_end(skb, saved_data_end);
1415	__skb_pull(skb, offset);
1416	skb->sk = save_sk;
1417
1418	return ret;
1419}
1420EXPORT_SYMBOL(__cgroup_bpf_run_filter_skb);
1421
1422/**
1423 * __cgroup_bpf_run_filter_sk() - Run a program on a sock
1424 * @sk: sock structure to manipulate
1425 * @atype: The type of program to be executed
1426 *
1427 * socket is passed is expected to be of type INET or INET6.
1428 *
1429 * The program type passed in via @type must be suitable for sock
1430 * filtering. No further check is performed to assert that.
1431 *
1432 * This function will return %-EPERM if any if an attached program was found
1433 * and if it returned != 1 during execution. In all other cases, 0 is returned.
1434 */
1435int __cgroup_bpf_run_filter_sk(struct sock *sk,
1436			       enum cgroup_bpf_attach_type atype)
1437{
1438	struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1439
1440	return bpf_prog_run_array_cg(&cgrp->bpf, atype, sk, bpf_prog_run, 0,
1441				     NULL);
1442}
1443EXPORT_SYMBOL(__cgroup_bpf_run_filter_sk);
1444
1445/**
1446 * __cgroup_bpf_run_filter_sock_addr() - Run a program on a sock and
1447 *                                       provided by user sockaddr
1448 * @sk: sock struct that will use sockaddr
1449 * @uaddr: sockaddr struct provided by user
1450 * @uaddrlen: Pointer to the size of the sockaddr struct provided by user. It is
1451 *            read-only for AF_INET[6] uaddr but can be modified for AF_UNIX
1452 *            uaddr.
1453 * @atype: The type of program to be executed
1454 * @t_ctx: Pointer to attach type specific context
1455 * @flags: Pointer to u32 which contains higher bits of BPF program
1456 *         return value (OR'ed together).
1457 *
1458 * socket is expected to be of type INET, INET6 or UNIX.
1459 *
1460 * This function will return %-EPERM if an attached program is found and
1461 * returned value != 1 during execution. In all other cases, 0 is returned.
1462 */
1463int __cgroup_bpf_run_filter_sock_addr(struct sock *sk,
1464				      struct sockaddr *uaddr,
1465				      int *uaddrlen,
1466				      enum cgroup_bpf_attach_type atype,
1467				      void *t_ctx,
1468				      u32 *flags)
1469{
1470	struct bpf_sock_addr_kern ctx = {
1471		.sk = sk,
1472		.uaddr = uaddr,
1473		.t_ctx = t_ctx,
1474	};
1475	struct sockaddr_storage unspec;
1476	struct cgroup *cgrp;
1477	int ret;
1478
1479	/* Check socket family since not all sockets represent network
1480	 * endpoint (e.g. AF_UNIX).
1481	 */
1482	if (sk->sk_family != AF_INET && sk->sk_family != AF_INET6 &&
1483	    sk->sk_family != AF_UNIX)
1484		return 0;
1485
1486	if (!ctx.uaddr) {
1487		memset(&unspec, 0, sizeof(unspec));
1488		ctx.uaddr = (struct sockaddr *)&unspec;
1489		ctx.uaddrlen = 0;
1490	} else {
1491		ctx.uaddrlen = *uaddrlen;
1492	}
1493
1494	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1495	ret = bpf_prog_run_array_cg(&cgrp->bpf, atype, &ctx, bpf_prog_run,
1496				    0, flags);
1497
1498	if (!ret && uaddr)
1499		*uaddrlen = ctx.uaddrlen;
1500
1501	return ret;
1502}
1503EXPORT_SYMBOL(__cgroup_bpf_run_filter_sock_addr);
1504
1505/**
1506 * __cgroup_bpf_run_filter_sock_ops() - Run a program on a sock
1507 * @sk: socket to get cgroup from
1508 * @sock_ops: bpf_sock_ops_kern struct to pass to program. Contains
1509 * sk with connection information (IP addresses, etc.) May not contain
1510 * cgroup info if it is a req sock.
1511 * @atype: The type of program to be executed
1512 *
1513 * socket passed is expected to be of type INET or INET6.
1514 *
1515 * The program type passed in via @type must be suitable for sock_ops
1516 * filtering. No further check is performed to assert that.
1517 *
1518 * This function will return %-EPERM if any if an attached program was found
1519 * and if it returned != 1 during execution. In all other cases, 0 is returned.
1520 */
1521int __cgroup_bpf_run_filter_sock_ops(struct sock *sk,
1522				     struct bpf_sock_ops_kern *sock_ops,
1523				     enum cgroup_bpf_attach_type atype)
1524{
1525	struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1526
1527	return bpf_prog_run_array_cg(&cgrp->bpf, atype, sock_ops, bpf_prog_run,
1528				     0, NULL);
1529}
1530EXPORT_SYMBOL(__cgroup_bpf_run_filter_sock_ops);
1531
1532int __cgroup_bpf_check_dev_permission(short dev_type, u32 major, u32 minor,
1533				      short access, enum cgroup_bpf_attach_type atype)
1534{
1535	struct cgroup *cgrp;
1536	struct bpf_cgroup_dev_ctx ctx = {
1537		.access_type = (access << 16) | dev_type,
1538		.major = major,
1539		.minor = minor,
1540	};
1541	int ret;
1542
1543	rcu_read_lock();
1544	cgrp = task_dfl_cgroup(current);
1545	ret = bpf_prog_run_array_cg(&cgrp->bpf, atype, &ctx, bpf_prog_run, 0,
1546				    NULL);
1547	rcu_read_unlock();
1548
1549	return ret;
1550}
1551
1552BPF_CALL_2(bpf_get_local_storage, struct bpf_map *, map, u64, flags)
1553{
1554	/* flags argument is not used now,
1555	 * but provides an ability to extend the API.
1556	 * verifier checks that its value is correct.
1557	 */
1558	enum bpf_cgroup_storage_type stype = cgroup_storage_type(map);
1559	struct bpf_cgroup_storage *storage;
1560	struct bpf_cg_run_ctx *ctx;
1561	void *ptr;
1562
1563	/* get current cgroup storage from BPF run context */
1564	ctx = container_of(current->bpf_ctx, struct bpf_cg_run_ctx, run_ctx);
1565	storage = ctx->prog_item->cgroup_storage[stype];
1566
1567	if (stype == BPF_CGROUP_STORAGE_SHARED)
1568		ptr = &READ_ONCE(storage->buf)->data[0];
1569	else
1570		ptr = this_cpu_ptr(storage->percpu_buf);
1571
1572	return (unsigned long)ptr;
1573}
1574
1575const struct bpf_func_proto bpf_get_local_storage_proto = {
1576	.func		= bpf_get_local_storage,
1577	.gpl_only	= false,
1578	.ret_type	= RET_PTR_TO_MAP_VALUE,
1579	.arg1_type	= ARG_CONST_MAP_PTR,
1580	.arg2_type	= ARG_ANYTHING,
1581};
1582
1583BPF_CALL_0(bpf_get_retval)
1584{
1585	struct bpf_cg_run_ctx *ctx =
1586		container_of(current->bpf_ctx, struct bpf_cg_run_ctx, run_ctx);
1587
1588	return ctx->retval;
1589}
1590
1591const struct bpf_func_proto bpf_get_retval_proto = {
1592	.func		= bpf_get_retval,
1593	.gpl_only	= false,
1594	.ret_type	= RET_INTEGER,
1595};
1596
1597BPF_CALL_1(bpf_set_retval, int, retval)
1598{
1599	struct bpf_cg_run_ctx *ctx =
1600		container_of(current->bpf_ctx, struct bpf_cg_run_ctx, run_ctx);
1601
1602	ctx->retval = retval;
1603	return 0;
1604}
1605
1606const struct bpf_func_proto bpf_set_retval_proto = {
1607	.func		= bpf_set_retval,
1608	.gpl_only	= false,
1609	.ret_type	= RET_INTEGER,
1610	.arg1_type	= ARG_ANYTHING,
1611};
1612
1613static const struct bpf_func_proto *
1614cgroup_dev_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
1615{
1616	const struct bpf_func_proto *func_proto;
1617
1618	func_proto = cgroup_common_func_proto(func_id, prog);
1619	if (func_proto)
1620		return func_proto;
1621
1622	func_proto = cgroup_current_func_proto(func_id, prog);
1623	if (func_proto)
1624		return func_proto;
1625
1626	switch (func_id) {
1627	case BPF_FUNC_perf_event_output:
1628		return &bpf_event_output_data_proto;
1629	default:
1630		return bpf_base_func_proto(func_id, prog);
1631	}
1632}
1633
1634static bool cgroup_dev_is_valid_access(int off, int size,
1635				       enum bpf_access_type type,
1636				       const struct bpf_prog *prog,
1637				       struct bpf_insn_access_aux *info)
1638{
1639	const int size_default = sizeof(__u32);
1640
1641	if (type == BPF_WRITE)
1642		return false;
1643
1644	if (off < 0 || off + size > sizeof(struct bpf_cgroup_dev_ctx))
1645		return false;
1646	/* The verifier guarantees that size > 0. */
1647	if (off % size != 0)
1648		return false;
1649
1650	switch (off) {
1651	case bpf_ctx_range(struct bpf_cgroup_dev_ctx, access_type):
1652		bpf_ctx_record_field_size(info, size_default);
1653		if (!bpf_ctx_narrow_access_ok(off, size, size_default))
1654			return false;
1655		break;
1656	default:
1657		if (size != size_default)
1658			return false;
1659	}
1660
1661	return true;
1662}
1663
1664const struct bpf_prog_ops cg_dev_prog_ops = {
1665};
1666
1667const struct bpf_verifier_ops cg_dev_verifier_ops = {
1668	.get_func_proto		= cgroup_dev_func_proto,
1669	.is_valid_access	= cgroup_dev_is_valid_access,
1670};
1671
1672/**
1673 * __cgroup_bpf_run_filter_sysctl - Run a program on sysctl
1674 *
1675 * @head: sysctl table header
1676 * @table: sysctl table
1677 * @write: sysctl is being read (= 0) or written (= 1)
1678 * @buf: pointer to buffer (in and out)
1679 * @pcount: value-result argument: value is size of buffer pointed to by @buf,
1680 *	result is size of @new_buf if program set new value, initial value
1681 *	otherwise
1682 * @ppos: value-result argument: value is position at which read from or write
1683 *	to sysctl is happening, result is new position if program overrode it,
1684 *	initial value otherwise
1685 * @atype: type of program to be executed
1686 *
1687 * Program is run when sysctl is being accessed, either read or written, and
1688 * can allow or deny such access.
1689 *
1690 * This function will return %-EPERM if an attached program is found and
1691 * returned value != 1 during execution. In all other cases 0 is returned.
1692 */
1693int __cgroup_bpf_run_filter_sysctl(struct ctl_table_header *head,
1694				   struct ctl_table *table, int write,
1695				   char **buf, size_t *pcount, loff_t *ppos,
1696				   enum cgroup_bpf_attach_type atype)
1697{
1698	struct bpf_sysctl_kern ctx = {
1699		.head = head,
1700		.table = table,
1701		.write = write,
1702		.ppos = ppos,
1703		.cur_val = NULL,
1704		.cur_len = PAGE_SIZE,
1705		.new_val = NULL,
1706		.new_len = 0,
1707		.new_updated = 0,
1708	};
1709	struct cgroup *cgrp;
1710	loff_t pos = 0;
1711	int ret;
1712
1713	ctx.cur_val = kmalloc_track_caller(ctx.cur_len, GFP_KERNEL);
1714	if (!ctx.cur_val ||
1715	    table->proc_handler(table, 0, ctx.cur_val, &ctx.cur_len, &pos)) {
1716		/* Let BPF program decide how to proceed. */
1717		ctx.cur_len = 0;
1718	}
1719
1720	if (write && *buf && *pcount) {
1721		/* BPF program should be able to override new value with a
1722		 * buffer bigger than provided by user.
1723		 */
1724		ctx.new_val = kmalloc_track_caller(PAGE_SIZE, GFP_KERNEL);
1725		ctx.new_len = min_t(size_t, PAGE_SIZE, *pcount);
1726		if (ctx.new_val) {
1727			memcpy(ctx.new_val, *buf, ctx.new_len);
1728		} else {
1729			/* Let BPF program decide how to proceed. */
1730			ctx.new_len = 0;
1731		}
1732	}
1733
1734	rcu_read_lock();
1735	cgrp = task_dfl_cgroup(current);
1736	ret = bpf_prog_run_array_cg(&cgrp->bpf, atype, &ctx, bpf_prog_run, 0,
1737				    NULL);
1738	rcu_read_unlock();
1739
1740	kfree(ctx.cur_val);
1741
1742	if (ret == 1 && ctx.new_updated) {
1743		kfree(*buf);
1744		*buf = ctx.new_val;
1745		*pcount = ctx.new_len;
1746	} else {
1747		kfree(ctx.new_val);
1748	}
1749
1750	return ret;
1751}
1752
1753#ifdef CONFIG_NET
1754static int sockopt_alloc_buf(struct bpf_sockopt_kern *ctx, int max_optlen,
1755			     struct bpf_sockopt_buf *buf)
1756{
1757	if (unlikely(max_optlen < 0))
1758		return -EINVAL;
1759
1760	if (unlikely(max_optlen > PAGE_SIZE)) {
1761		/* We don't expose optvals that are greater than PAGE_SIZE
1762		 * to the BPF program.
1763		 */
1764		max_optlen = PAGE_SIZE;
1765	}
1766
1767	if (max_optlen <= sizeof(buf->data)) {
1768		/* When the optval fits into BPF_SOCKOPT_KERN_BUF_SIZE
1769		 * bytes avoid the cost of kzalloc.
1770		 */
1771		ctx->optval = buf->data;
1772		ctx->optval_end = ctx->optval + max_optlen;
1773		return max_optlen;
1774	}
1775
1776	ctx->optval = kzalloc(max_optlen, GFP_USER);
1777	if (!ctx->optval)
1778		return -ENOMEM;
1779
1780	ctx->optval_end = ctx->optval + max_optlen;
1781
1782	return max_optlen;
1783}
1784
1785static void sockopt_free_buf(struct bpf_sockopt_kern *ctx,
1786			     struct bpf_sockopt_buf *buf)
1787{
1788	if (ctx->optval == buf->data)
1789		return;
1790	kfree(ctx->optval);
1791}
1792
1793static bool sockopt_buf_allocated(struct bpf_sockopt_kern *ctx,
1794				  struct bpf_sockopt_buf *buf)
1795{
1796	return ctx->optval != buf->data;
1797}
1798
1799int __cgroup_bpf_run_filter_setsockopt(struct sock *sk, int *level,
1800				       int *optname, sockptr_t optval,
1801				       int *optlen, char **kernel_optval)
1802{
1803	struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1804	struct bpf_sockopt_buf buf = {};
1805	struct bpf_sockopt_kern ctx = {
1806		.sk = sk,
1807		.level = *level,
1808		.optname = *optname,
1809	};
1810	int ret, max_optlen;
1811
1812	/* Allocate a bit more than the initial user buffer for
1813	 * BPF program. The canonical use case is overriding
1814	 * TCP_CONGESTION(nv) to TCP_CONGESTION(cubic).
1815	 */
1816	max_optlen = max_t(int, 16, *optlen);
1817	max_optlen = sockopt_alloc_buf(&ctx, max_optlen, &buf);
1818	if (max_optlen < 0)
1819		return max_optlen;
1820
1821	ctx.optlen = *optlen;
1822
1823	if (copy_from_sockptr(ctx.optval, optval,
1824			      min(*optlen, max_optlen))) {
1825		ret = -EFAULT;
1826		goto out;
1827	}
1828
1829	lock_sock(sk);
1830	ret = bpf_prog_run_array_cg(&cgrp->bpf, CGROUP_SETSOCKOPT,
1831				    &ctx, bpf_prog_run, 0, NULL);
1832	release_sock(sk);
1833
1834	if (ret)
1835		goto out;
1836
1837	if (ctx.optlen == -1) {
1838		/* optlen set to -1, bypass kernel */
1839		ret = 1;
1840	} else if (ctx.optlen > max_optlen || ctx.optlen < -1) {
1841		/* optlen is out of bounds */
1842		if (*optlen > PAGE_SIZE && ctx.optlen >= 0) {
1843			pr_info_once("bpf setsockopt: ignoring program buffer with optlen=%d (max_optlen=%d)\n",
1844				     ctx.optlen, max_optlen);
1845			ret = 0;
1846			goto out;
1847		}
1848		ret = -EFAULT;
1849	} else {
1850		/* optlen within bounds, run kernel handler */
1851		ret = 0;
1852
1853		/* export any potential modifications */
1854		*level = ctx.level;
1855		*optname = ctx.optname;
1856
1857		/* optlen == 0 from BPF indicates that we should
1858		 * use original userspace data.
1859		 */
1860		if (ctx.optlen != 0) {
1861			*optlen = ctx.optlen;
1862			/* We've used bpf_sockopt_kern->buf as an intermediary
1863			 * storage, but the BPF program indicates that we need
1864			 * to pass this data to the kernel setsockopt handler.
1865			 * No way to export on-stack buf, have to allocate a
1866			 * new buffer.
1867			 */
1868			if (!sockopt_buf_allocated(&ctx, &buf)) {
1869				void *p = kmalloc(ctx.optlen, GFP_USER);
1870
1871				if (!p) {
1872					ret = -ENOMEM;
1873					goto out;
1874				}
1875				memcpy(p, ctx.optval, ctx.optlen);
1876				*kernel_optval = p;
1877			} else {
1878				*kernel_optval = ctx.optval;
1879			}
1880			/* export and don't free sockopt buf */
1881			return 0;
1882		}
1883	}
1884
1885out:
1886	sockopt_free_buf(&ctx, &buf);
1887	return ret;
1888}
1889
1890int __cgroup_bpf_run_filter_getsockopt(struct sock *sk, int level,
1891				       int optname, sockptr_t optval,
1892				       sockptr_t optlen, int max_optlen,
1893				       int retval)
1894{
1895	struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1896	struct bpf_sockopt_buf buf = {};
1897	struct bpf_sockopt_kern ctx = {
1898		.sk = sk,
1899		.level = level,
1900		.optname = optname,
1901		.current_task = current,
1902	};
1903	int orig_optlen;
1904	int ret;
1905
1906	orig_optlen = max_optlen;
1907	ctx.optlen = max_optlen;
1908	max_optlen = sockopt_alloc_buf(&ctx, max_optlen, &buf);
1909	if (max_optlen < 0)
1910		return max_optlen;
1911
1912	if (!retval) {
1913		/* If kernel getsockopt finished successfully,
1914		 * copy whatever was returned to the user back
1915		 * into our temporary buffer. Set optlen to the
1916		 * one that kernel returned as well to let
1917		 * BPF programs inspect the value.
1918		 */
1919		if (copy_from_sockptr(&ctx.optlen, optlen,
1920				      sizeof(ctx.optlen))) {
1921			ret = -EFAULT;
1922			goto out;
1923		}
1924
1925		if (ctx.optlen < 0) {
1926			ret = -EFAULT;
1927			goto out;
1928		}
1929		orig_optlen = ctx.optlen;
1930
1931		if (copy_from_sockptr(ctx.optval, optval,
1932				      min(ctx.optlen, max_optlen))) {
1933			ret = -EFAULT;
1934			goto out;
1935		}
1936	}
1937
1938	lock_sock(sk);
1939	ret = bpf_prog_run_array_cg(&cgrp->bpf, CGROUP_GETSOCKOPT,
1940				    &ctx, bpf_prog_run, retval, NULL);
1941	release_sock(sk);
1942
1943	if (ret < 0)
1944		goto out;
1945
1946	if (!sockptr_is_null(optval) &&
1947	    (ctx.optlen > max_optlen || ctx.optlen < 0)) {
1948		if (orig_optlen > PAGE_SIZE && ctx.optlen >= 0) {
1949			pr_info_once("bpf getsockopt: ignoring program buffer with optlen=%d (max_optlen=%d)\n",
1950				     ctx.optlen, max_optlen);
1951			ret = retval;
1952			goto out;
1953		}
1954		ret = -EFAULT;
1955		goto out;
1956	}
1957
1958	if (ctx.optlen != 0) {
1959		if (!sockptr_is_null(optval) &&
1960		    copy_to_sockptr(optval, ctx.optval, ctx.optlen)) {
1961			ret = -EFAULT;
1962			goto out;
1963		}
1964		if (copy_to_sockptr(optlen, &ctx.optlen, sizeof(ctx.optlen))) {
1965			ret = -EFAULT;
1966			goto out;
1967		}
1968	}
1969
1970out:
1971	sockopt_free_buf(&ctx, &buf);
1972	return ret;
1973}
1974
1975int __cgroup_bpf_run_filter_getsockopt_kern(struct sock *sk, int level,
1976					    int optname, void *optval,
1977					    int *optlen, int retval)
1978{
1979	struct cgroup *cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
1980	struct bpf_sockopt_kern ctx = {
1981		.sk = sk,
1982		.level = level,
1983		.optname = optname,
1984		.optlen = *optlen,
1985		.optval = optval,
1986		.optval_end = optval + *optlen,
1987		.current_task = current,
1988	};
1989	int ret;
1990
1991	/* Note that __cgroup_bpf_run_filter_getsockopt doesn't copy
1992	 * user data back into BPF buffer when reval != 0. This is
1993	 * done as an optimization to avoid extra copy, assuming
1994	 * kernel won't populate the data in case of an error.
1995	 * Here we always pass the data and memset() should
1996	 * be called if that data shouldn't be "exported".
1997	 */
1998
1999	ret = bpf_prog_run_array_cg(&cgrp->bpf, CGROUP_GETSOCKOPT,
2000				    &ctx, bpf_prog_run, retval, NULL);
2001	if (ret < 0)
2002		return ret;
2003
2004	if (ctx.optlen > *optlen)
2005		return -EFAULT;
2006
2007	/* BPF programs can shrink the buffer, export the modifications.
2008	 */
2009	if (ctx.optlen != 0)
2010		*optlen = ctx.optlen;
2011
2012	return ret;
2013}
2014#endif
2015
2016static ssize_t sysctl_cpy_dir(const struct ctl_dir *dir, char **bufp,
2017			      size_t *lenp)
2018{
2019	ssize_t tmp_ret = 0, ret;
2020
2021	if (dir->header.parent) {
2022		tmp_ret = sysctl_cpy_dir(dir->header.parent, bufp, lenp);
2023		if (tmp_ret < 0)
2024			return tmp_ret;
2025	}
2026
2027	ret = strscpy(*bufp, dir->header.ctl_table[0].procname, *lenp);
2028	if (ret < 0)
2029		return ret;
2030	*bufp += ret;
2031	*lenp -= ret;
2032	ret += tmp_ret;
2033
2034	/* Avoid leading slash. */
2035	if (!ret)
2036		return ret;
2037
2038	tmp_ret = strscpy(*bufp, "/", *lenp);
2039	if (tmp_ret < 0)
2040		return tmp_ret;
2041	*bufp += tmp_ret;
2042	*lenp -= tmp_ret;
2043
2044	return ret + tmp_ret;
2045}
2046
2047BPF_CALL_4(bpf_sysctl_get_name, struct bpf_sysctl_kern *, ctx, char *, buf,
2048	   size_t, buf_len, u64, flags)
2049{
2050	ssize_t tmp_ret = 0, ret;
2051
2052	if (!buf)
2053		return -EINVAL;
2054
2055	if (!(flags & BPF_F_SYSCTL_BASE_NAME)) {
2056		if (!ctx->head)
2057			return -EINVAL;
2058		tmp_ret = sysctl_cpy_dir(ctx->head->parent, &buf, &buf_len);
2059		if (tmp_ret < 0)
2060			return tmp_ret;
2061	}
2062
2063	ret = strscpy(buf, ctx->table->procname, buf_len);
2064
2065	return ret < 0 ? ret : tmp_ret + ret;
2066}
2067
2068static const struct bpf_func_proto bpf_sysctl_get_name_proto = {
2069	.func		= bpf_sysctl_get_name,
2070	.gpl_only	= false,
2071	.ret_type	= RET_INTEGER,
2072	.arg1_type	= ARG_PTR_TO_CTX,
2073	.arg2_type	= ARG_PTR_TO_MEM,
2074	.arg3_type	= ARG_CONST_SIZE,
2075	.arg4_type	= ARG_ANYTHING,
2076};
2077
2078static int copy_sysctl_value(char *dst, size_t dst_len, char *src,
2079			     size_t src_len)
2080{
2081	if (!dst)
2082		return -EINVAL;
2083
2084	if (!dst_len)
2085		return -E2BIG;
2086
2087	if (!src || !src_len) {
2088		memset(dst, 0, dst_len);
2089		return -EINVAL;
2090	}
2091
2092	memcpy(dst, src, min(dst_len, src_len));
2093
2094	if (dst_len > src_len) {
2095		memset(dst + src_len, '\0', dst_len - src_len);
2096		return src_len;
2097	}
2098
2099	dst[dst_len - 1] = '\0';
2100
2101	return -E2BIG;
2102}
2103
2104BPF_CALL_3(bpf_sysctl_get_current_value, struct bpf_sysctl_kern *, ctx,
2105	   char *, buf, size_t, buf_len)
2106{
2107	return copy_sysctl_value(buf, buf_len, ctx->cur_val, ctx->cur_len);
2108}
2109
2110static const struct bpf_func_proto bpf_sysctl_get_current_value_proto = {
2111	.func		= bpf_sysctl_get_current_value,
2112	.gpl_only	= false,
2113	.ret_type	= RET_INTEGER,
2114	.arg1_type	= ARG_PTR_TO_CTX,
2115	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
2116	.arg3_type	= ARG_CONST_SIZE,
2117};
2118
2119BPF_CALL_3(bpf_sysctl_get_new_value, struct bpf_sysctl_kern *, ctx, char *, buf,
2120	   size_t, buf_len)
2121{
2122	if (!ctx->write) {
2123		if (buf && buf_len)
2124			memset(buf, '\0', buf_len);
2125		return -EINVAL;
2126	}
2127	return copy_sysctl_value(buf, buf_len, ctx->new_val, ctx->new_len);
2128}
2129
2130static const struct bpf_func_proto bpf_sysctl_get_new_value_proto = {
2131	.func		= bpf_sysctl_get_new_value,
2132	.gpl_only	= false,
2133	.ret_type	= RET_INTEGER,
2134	.arg1_type	= ARG_PTR_TO_CTX,
2135	.arg2_type	= ARG_PTR_TO_UNINIT_MEM,
2136	.arg3_type	= ARG_CONST_SIZE,
2137};
2138
2139BPF_CALL_3(bpf_sysctl_set_new_value, struct bpf_sysctl_kern *, ctx,
2140	   const char *, buf, size_t, buf_len)
2141{
2142	if (!ctx->write || !ctx->new_val || !ctx->new_len || !buf || !buf_len)
2143		return -EINVAL;
2144
2145	if (buf_len > PAGE_SIZE - 1)
2146		return -E2BIG;
2147
2148	memcpy(ctx->new_val, buf, buf_len);
2149	ctx->new_len = buf_len;
2150	ctx->new_updated = 1;
2151
2152	return 0;
2153}
2154
2155static const struct bpf_func_proto bpf_sysctl_set_new_value_proto = {
2156	.func		= bpf_sysctl_set_new_value,
2157	.gpl_only	= false,
2158	.ret_type	= RET_INTEGER,
2159	.arg1_type	= ARG_PTR_TO_CTX,
2160	.arg2_type	= ARG_PTR_TO_MEM | MEM_RDONLY,
2161	.arg3_type	= ARG_CONST_SIZE,
2162};
2163
2164static const struct bpf_func_proto *
2165sysctl_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2166{
2167	const struct bpf_func_proto *func_proto;
2168
2169	func_proto = cgroup_common_func_proto(func_id, prog);
2170	if (func_proto)
2171		return func_proto;
2172
2173	func_proto = cgroup_current_func_proto(func_id, prog);
2174	if (func_proto)
2175		return func_proto;
2176
2177	switch (func_id) {
2178	case BPF_FUNC_sysctl_get_name:
2179		return &bpf_sysctl_get_name_proto;
2180	case BPF_FUNC_sysctl_get_current_value:
2181		return &bpf_sysctl_get_current_value_proto;
2182	case BPF_FUNC_sysctl_get_new_value:
2183		return &bpf_sysctl_get_new_value_proto;
2184	case BPF_FUNC_sysctl_set_new_value:
2185		return &bpf_sysctl_set_new_value_proto;
2186	case BPF_FUNC_ktime_get_coarse_ns:
2187		return &bpf_ktime_get_coarse_ns_proto;
2188	case BPF_FUNC_perf_event_output:
2189		return &bpf_event_output_data_proto;
2190	default:
2191		return bpf_base_func_proto(func_id, prog);
2192	}
2193}
2194
2195static bool sysctl_is_valid_access(int off, int size, enum bpf_access_type type,
2196				   const struct bpf_prog *prog,
2197				   struct bpf_insn_access_aux *info)
2198{
2199	const int size_default = sizeof(__u32);
2200
2201	if (off < 0 || off + size > sizeof(struct bpf_sysctl) || off % size)
2202		return false;
2203
2204	switch (off) {
2205	case bpf_ctx_range(struct bpf_sysctl, write):
2206		if (type != BPF_READ)
2207			return false;
2208		bpf_ctx_record_field_size(info, size_default);
2209		return bpf_ctx_narrow_access_ok(off, size, size_default);
2210	case bpf_ctx_range(struct bpf_sysctl, file_pos):
2211		if (type == BPF_READ) {
2212			bpf_ctx_record_field_size(info, size_default);
2213			return bpf_ctx_narrow_access_ok(off, size, size_default);
2214		} else {
2215			return size == size_default;
2216		}
2217	default:
2218		return false;
2219	}
2220}
2221
2222static u32 sysctl_convert_ctx_access(enum bpf_access_type type,
2223				     const struct bpf_insn *si,
2224				     struct bpf_insn *insn_buf,
2225				     struct bpf_prog *prog, u32 *target_size)
2226{
2227	struct bpf_insn *insn = insn_buf;
2228	u32 read_size;
2229
2230	switch (si->off) {
2231	case offsetof(struct bpf_sysctl, write):
2232		*insn++ = BPF_LDX_MEM(
2233			BPF_SIZE(si->code), si->dst_reg, si->src_reg,
2234			bpf_target_off(struct bpf_sysctl_kern, write,
2235				       sizeof_field(struct bpf_sysctl_kern,
2236						    write),
2237				       target_size));
2238		break;
2239	case offsetof(struct bpf_sysctl, file_pos):
2240		/* ppos is a pointer so it should be accessed via indirect
2241		 * loads and stores. Also for stores additional temporary
2242		 * register is used since neither src_reg nor dst_reg can be
2243		 * overridden.
2244		 */
2245		if (type == BPF_WRITE) {
2246			int treg = BPF_REG_9;
2247
2248			if (si->src_reg == treg || si->dst_reg == treg)
2249				--treg;
2250			if (si->src_reg == treg || si->dst_reg == treg)
2251				--treg;
2252			*insn++ = BPF_STX_MEM(
2253				BPF_DW, si->dst_reg, treg,
2254				offsetof(struct bpf_sysctl_kern, tmp_reg));
2255			*insn++ = BPF_LDX_MEM(
2256				BPF_FIELD_SIZEOF(struct bpf_sysctl_kern, ppos),
2257				treg, si->dst_reg,
2258				offsetof(struct bpf_sysctl_kern, ppos));
2259			*insn++ = BPF_RAW_INSN(
2260				BPF_CLASS(si->code) | BPF_MEM | BPF_SIZEOF(u32),
2261				treg, si->src_reg,
2262				bpf_ctx_narrow_access_offset(
2263					0, sizeof(u32), sizeof(loff_t)),
2264				si->imm);
2265			*insn++ = BPF_LDX_MEM(
2266				BPF_DW, treg, si->dst_reg,
2267				offsetof(struct bpf_sysctl_kern, tmp_reg));
2268		} else {
2269			*insn++ = BPF_LDX_MEM(
2270				BPF_FIELD_SIZEOF(struct bpf_sysctl_kern, ppos),
2271				si->dst_reg, si->src_reg,
2272				offsetof(struct bpf_sysctl_kern, ppos));
2273			read_size = bpf_size_to_bytes(BPF_SIZE(si->code));
2274			*insn++ = BPF_LDX_MEM(
2275				BPF_SIZE(si->code), si->dst_reg, si->dst_reg,
2276				bpf_ctx_narrow_access_offset(
2277					0, read_size, sizeof(loff_t)));
2278		}
2279		*target_size = sizeof(u32);
2280		break;
2281	}
2282
2283	return insn - insn_buf;
2284}
2285
2286const struct bpf_verifier_ops cg_sysctl_verifier_ops = {
2287	.get_func_proto		= sysctl_func_proto,
2288	.is_valid_access	= sysctl_is_valid_access,
2289	.convert_ctx_access	= sysctl_convert_ctx_access,
2290};
2291
2292const struct bpf_prog_ops cg_sysctl_prog_ops = {
2293};
2294
2295#ifdef CONFIG_NET
2296BPF_CALL_1(bpf_get_netns_cookie_sockopt, struct bpf_sockopt_kern *, ctx)
2297{
2298	const struct net *net = ctx ? sock_net(ctx->sk) : &init_net;
2299
2300	return net->net_cookie;
2301}
2302
2303static const struct bpf_func_proto bpf_get_netns_cookie_sockopt_proto = {
2304	.func		= bpf_get_netns_cookie_sockopt,
2305	.gpl_only	= false,
2306	.ret_type	= RET_INTEGER,
2307	.arg1_type	= ARG_PTR_TO_CTX_OR_NULL,
2308};
2309#endif
2310
2311static const struct bpf_func_proto *
2312cg_sockopt_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2313{
2314	const struct bpf_func_proto *func_proto;
2315
2316	func_proto = cgroup_common_func_proto(func_id, prog);
2317	if (func_proto)
2318		return func_proto;
2319
2320	func_proto = cgroup_current_func_proto(func_id, prog);
2321	if (func_proto)
2322		return func_proto;
2323
2324	switch (func_id) {
2325#ifdef CONFIG_NET
2326	case BPF_FUNC_get_netns_cookie:
2327		return &bpf_get_netns_cookie_sockopt_proto;
2328	case BPF_FUNC_sk_storage_get:
2329		return &bpf_sk_storage_get_proto;
2330	case BPF_FUNC_sk_storage_delete:
2331		return &bpf_sk_storage_delete_proto;
2332	case BPF_FUNC_setsockopt:
2333		if (prog->expected_attach_type == BPF_CGROUP_SETSOCKOPT)
2334			return &bpf_sk_setsockopt_proto;
2335		return NULL;
2336	case BPF_FUNC_getsockopt:
2337		if (prog->expected_attach_type == BPF_CGROUP_SETSOCKOPT)
2338			return &bpf_sk_getsockopt_proto;
2339		return NULL;
2340#endif
2341#ifdef CONFIG_INET
2342	case BPF_FUNC_tcp_sock:
2343		return &bpf_tcp_sock_proto;
2344#endif
2345	case BPF_FUNC_perf_event_output:
2346		return &bpf_event_output_data_proto;
2347	default:
2348		return bpf_base_func_proto(func_id, prog);
2349	}
2350}
2351
2352static bool cg_sockopt_is_valid_access(int off, int size,
2353				       enum bpf_access_type type,
2354				       const struct bpf_prog *prog,
2355				       struct bpf_insn_access_aux *info)
2356{
2357	const int size_default = sizeof(__u32);
2358
2359	if (off < 0 || off >= sizeof(struct bpf_sockopt))
2360		return false;
2361
2362	if (off % size != 0)
2363		return false;
2364
2365	if (type == BPF_WRITE) {
2366		switch (off) {
2367		case offsetof(struct bpf_sockopt, retval):
2368			if (size != size_default)
2369				return false;
2370			return prog->expected_attach_type ==
2371				BPF_CGROUP_GETSOCKOPT;
2372		case offsetof(struct bpf_sockopt, optname):
2373			fallthrough;
2374		case offsetof(struct bpf_sockopt, level):
2375			if (size != size_default)
2376				return false;
2377			return prog->expected_attach_type ==
2378				BPF_CGROUP_SETSOCKOPT;
2379		case offsetof(struct bpf_sockopt, optlen):
2380			return size == size_default;
2381		default:
2382			return false;
2383		}
2384	}
2385
2386	switch (off) {
2387	case offsetof(struct bpf_sockopt, sk):
2388		if (size != sizeof(__u64))
2389			return false;
2390		info->reg_type = PTR_TO_SOCKET;
2391		break;
2392	case offsetof(struct bpf_sockopt, optval):
2393		if (size != sizeof(__u64))
2394			return false;
2395		info->reg_type = PTR_TO_PACKET;
2396		break;
2397	case offsetof(struct bpf_sockopt, optval_end):
2398		if (size != sizeof(__u64))
2399			return false;
2400		info->reg_type = PTR_TO_PACKET_END;
2401		break;
2402	case offsetof(struct bpf_sockopt, retval):
2403		if (size != size_default)
2404			return false;
2405		return prog->expected_attach_type == BPF_CGROUP_GETSOCKOPT;
2406	default:
2407		if (size != size_default)
2408			return false;
2409		break;
2410	}
2411	return true;
2412}
2413
2414#define CG_SOCKOPT_READ_FIELD(F)					\
2415	BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sockopt_kern, F),	\
2416		    si->dst_reg, si->src_reg,				\
2417		    offsetof(struct bpf_sockopt_kern, F))
2418
2419#define CG_SOCKOPT_WRITE_FIELD(F)					\
2420	BPF_RAW_INSN((BPF_FIELD_SIZEOF(struct bpf_sockopt_kern, F) |	\
2421		      BPF_MEM | BPF_CLASS(si->code)),			\
2422		     si->dst_reg, si->src_reg,				\
2423		     offsetof(struct bpf_sockopt_kern, F),		\
2424		     si->imm)
2425
2426static u32 cg_sockopt_convert_ctx_access(enum bpf_access_type type,
2427					 const struct bpf_insn *si,
2428					 struct bpf_insn *insn_buf,
2429					 struct bpf_prog *prog,
2430					 u32 *target_size)
2431{
2432	struct bpf_insn *insn = insn_buf;
2433
2434	switch (si->off) {
2435	case offsetof(struct bpf_sockopt, sk):
2436		*insn++ = CG_SOCKOPT_READ_FIELD(sk);
2437		break;
2438	case offsetof(struct bpf_sockopt, level):
2439		if (type == BPF_WRITE)
2440			*insn++ = CG_SOCKOPT_WRITE_FIELD(level);
2441		else
2442			*insn++ = CG_SOCKOPT_READ_FIELD(level);
2443		break;
2444	case offsetof(struct bpf_sockopt, optname):
2445		if (type == BPF_WRITE)
2446			*insn++ = CG_SOCKOPT_WRITE_FIELD(optname);
2447		else
2448			*insn++ = CG_SOCKOPT_READ_FIELD(optname);
2449		break;
2450	case offsetof(struct bpf_sockopt, optlen):
2451		if (type == BPF_WRITE)
2452			*insn++ = CG_SOCKOPT_WRITE_FIELD(optlen);
2453		else
2454			*insn++ = CG_SOCKOPT_READ_FIELD(optlen);
2455		break;
2456	case offsetof(struct bpf_sockopt, retval):
2457		BUILD_BUG_ON(offsetof(struct bpf_cg_run_ctx, run_ctx) != 0);
2458
2459		if (type == BPF_WRITE) {
2460			int treg = BPF_REG_9;
2461
2462			if (si->src_reg == treg || si->dst_reg == treg)
2463				--treg;
2464			if (si->src_reg == treg || si->dst_reg == treg)
2465				--treg;
2466			*insn++ = BPF_STX_MEM(BPF_DW, si->dst_reg, treg,
2467					      offsetof(struct bpf_sockopt_kern, tmp_reg));
2468			*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sockopt_kern, current_task),
2469					      treg, si->dst_reg,
2470					      offsetof(struct bpf_sockopt_kern, current_task));
2471			*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct task_struct, bpf_ctx),
2472					      treg, treg,
2473					      offsetof(struct task_struct, bpf_ctx));
2474			*insn++ = BPF_RAW_INSN(BPF_CLASS(si->code) | BPF_MEM |
2475					       BPF_FIELD_SIZEOF(struct bpf_cg_run_ctx, retval),
2476					       treg, si->src_reg,
2477					       offsetof(struct bpf_cg_run_ctx, retval),
2478					       si->imm);
2479			*insn++ = BPF_LDX_MEM(BPF_DW, treg, si->dst_reg,
2480					      offsetof(struct bpf_sockopt_kern, tmp_reg));
2481		} else {
2482			*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_sockopt_kern, current_task),
2483					      si->dst_reg, si->src_reg,
2484					      offsetof(struct bpf_sockopt_kern, current_task));
2485			*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct task_struct, bpf_ctx),
2486					      si->dst_reg, si->dst_reg,
2487					      offsetof(struct task_struct, bpf_ctx));
2488			*insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct bpf_cg_run_ctx, retval),
2489					      si->dst_reg, si->dst_reg,
2490					      offsetof(struct bpf_cg_run_ctx, retval));
2491		}
2492		break;
2493	case offsetof(struct bpf_sockopt, optval):
2494		*insn++ = CG_SOCKOPT_READ_FIELD(optval);
2495		break;
2496	case offsetof(struct bpf_sockopt, optval_end):
2497		*insn++ = CG_SOCKOPT_READ_FIELD(optval_end);
2498		break;
2499	}
2500
2501	return insn - insn_buf;
2502}
2503
2504static int cg_sockopt_get_prologue(struct bpf_insn *insn_buf,
2505				   bool direct_write,
2506				   const struct bpf_prog *prog)
2507{
2508	/* Nothing to do for sockopt argument. The data is kzalloc'ated.
2509	 */
2510	return 0;
2511}
2512
2513const struct bpf_verifier_ops cg_sockopt_verifier_ops = {
2514	.get_func_proto		= cg_sockopt_func_proto,
2515	.is_valid_access	= cg_sockopt_is_valid_access,
2516	.convert_ctx_access	= cg_sockopt_convert_ctx_access,
2517	.gen_prologue		= cg_sockopt_get_prologue,
2518};
2519
2520const struct bpf_prog_ops cg_sockopt_prog_ops = {
2521};
2522
2523/* Common helpers for cgroup hooks. */
2524const struct bpf_func_proto *
2525cgroup_common_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2526{
2527	switch (func_id) {
2528	case BPF_FUNC_get_local_storage:
2529		return &bpf_get_local_storage_proto;
2530	case BPF_FUNC_get_retval:
2531		switch (prog->expected_attach_type) {
2532		case BPF_CGROUP_INET_INGRESS:
2533		case BPF_CGROUP_INET_EGRESS:
2534		case BPF_CGROUP_SOCK_OPS:
2535		case BPF_CGROUP_UDP4_RECVMSG:
2536		case BPF_CGROUP_UDP6_RECVMSG:
2537		case BPF_CGROUP_UNIX_RECVMSG:
2538		case BPF_CGROUP_INET4_GETPEERNAME:
2539		case BPF_CGROUP_INET6_GETPEERNAME:
2540		case BPF_CGROUP_UNIX_GETPEERNAME:
2541		case BPF_CGROUP_INET4_GETSOCKNAME:
2542		case BPF_CGROUP_INET6_GETSOCKNAME:
2543		case BPF_CGROUP_UNIX_GETSOCKNAME:
2544			return NULL;
2545		default:
2546			return &bpf_get_retval_proto;
2547		}
2548	case BPF_FUNC_set_retval:
2549		switch (prog->expected_attach_type) {
2550		case BPF_CGROUP_INET_INGRESS:
2551		case BPF_CGROUP_INET_EGRESS:
2552		case BPF_CGROUP_SOCK_OPS:
2553		case BPF_CGROUP_UDP4_RECVMSG:
2554		case BPF_CGROUP_UDP6_RECVMSG:
2555		case BPF_CGROUP_UNIX_RECVMSG:
2556		case BPF_CGROUP_INET4_GETPEERNAME:
2557		case BPF_CGROUP_INET6_GETPEERNAME:
2558		case BPF_CGROUP_UNIX_GETPEERNAME:
2559		case BPF_CGROUP_INET4_GETSOCKNAME:
2560		case BPF_CGROUP_INET6_GETSOCKNAME:
2561		case BPF_CGROUP_UNIX_GETSOCKNAME:
2562			return NULL;
2563		default:
2564			return &bpf_set_retval_proto;
2565		}
2566	default:
2567		return NULL;
2568	}
2569}
2570
2571/* Common helpers for cgroup hooks with valid process context. */
2572const struct bpf_func_proto *
2573cgroup_current_func_proto(enum bpf_func_id func_id, const struct bpf_prog *prog)
2574{
2575	switch (func_id) {
2576	case BPF_FUNC_get_current_uid_gid:
2577		return &bpf_get_current_uid_gid_proto;
2578	case BPF_FUNC_get_current_pid_tgid:
2579		return &bpf_get_current_pid_tgid_proto;
2580	case BPF_FUNC_get_current_comm:
2581		return &bpf_get_current_comm_proto;
 
 
 
 
2582#ifdef CONFIG_CGROUP_NET_CLASSID
2583	case BPF_FUNC_get_cgroup_classid:
2584		return &bpf_get_cgroup_classid_curr_proto;
2585#endif
2586	default:
2587		return NULL;
2588	}
2589}