2115 lines · 54.2 KB · C
RawDownload
// SPDX-License-Identifier: GPL-2.0-only/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com * Copyright (c) 2016 Facebook */#include <linux/bpf.h>#include <linux/btf.h>#include <linux/jhash.h>#include <linux/filter.h>#include <linux/rculist_nulls.h>#include <linux/random.h>#include <uapi/linux/btf.h>#include "percpu_freelist.h"#include "bpf_lru_list.h"#include "map_in_map.h" #define HTAB_CREATE_FLAG_MASK						\	(BPF_F_NO_PREALLOC | BPF_F_NO_COMMON_LRU | BPF_F_NUMA_NODE |	\	 BPF_F_ACCESS_MASK | BPF_F_ZERO_SEED) #define BATCH_OPS(_name)			\	.map_lookup_batch =			\	_name##_map_lookup_batch,		\	.map_lookup_and_delete_batch =		\	_name##_map_lookup_and_delete_batch,	\	.map_update_batch =			\	generic_map_update_batch,		\	.map_delete_batch =			\	generic_map_delete_batch /* * The bucket lock has two protection scopes: * * 1) Serializing concurrent operations from BPF programs on differrent *    CPUs * * 2) Serializing concurrent operations from BPF programs and sys_bpf() * * BPF programs can execute in any context including perf, kprobes and * tracing. As there are almost no limits where perf, kprobes and tracing * can be invoked from the lock operations need to be protected against * deadlocks. Deadlocks can be caused by recursion and by an invocation in * the lock held section when functions which acquire this lock are invoked * from sys_bpf(). BPF recursion is prevented by incrementing the per CPU * variable bpf_prog_active, which prevents BPF programs attached to perf * events, kprobes and tracing to be invoked before the prior invocation * from one of these contexts completed. sys_bpf() uses the same mechanism * by pinning the task to the current CPU and incrementing the recursion * protection accross the map operation. * * This has subtle implications on PREEMPT_RT. PREEMPT_RT forbids certain * operations like memory allocations (even with GFP_ATOMIC) from atomic * contexts. This is required because even with GFP_ATOMIC the memory * allocator calls into code pathes which acquire locks with long held lock * sections. To ensure the deterministic behaviour these locks are regular * spinlocks, which are converted to 'sleepable' spinlocks on RT. The only * true atomic contexts on an RT kernel are the low level hardware * handling, scheduling, low level interrupt handling, NMIs etc. None of * these contexts should ever do memory allocations. * * As regular device interrupt handlers and soft interrupts are forced into * thread context, the existing code which does *   spin_lock*(); alloc(GPF_ATOMIC); spin_unlock*(); * just works. * * In theory the BPF locks could be converted to regular spinlocks as well, * but the bucket locks and percpu_freelist locks can be taken from * arbitrary contexts (perf, kprobes, tracepoints) which are required to be * atomic contexts even on RT. These mechanisms require preallocated maps, * so there is no need to invoke memory allocations within the lock held * sections. * * BPF maps which need dynamic allocation are only used from (forced) * thread context on RT and can therefore use regular spinlocks which in * turn allows to invoke memory allocations from the lock held section. * * On a non RT kernel this distinction is neither possible nor required. * spinlock maps to raw_spinlock and the extra code is optimized out by the * compiler. */struct bucket {	struct hlist_nulls_head head;	union {		raw_spinlock_t raw_lock;		spinlock_t     lock;	};}; struct bpf_htab {	struct bpf_map map;	struct bucket *buckets;	void *elems;	union {		struct pcpu_freelist freelist;		struct bpf_lru lru;	};	struct htab_elem *__percpu *extra_elems;	atomic_t count;	/* number of elements in this hashtable */	u32 n_buckets;	/* number of hash buckets */	u32 elem_size;	/* size of each element in bytes */	u32 hashrnd;}; /* each htab element is struct htab_elem + key + value */struct htab_elem {	union {		struct hlist_nulls_node hash_node;		struct {			void *padding;			union {				struct bpf_htab *htab;				struct pcpu_freelist_node fnode;				struct htab_elem *batch_flink;			};		};	};	union {		struct rcu_head rcu;		struct bpf_lru_node lru_node;	};	u32 hash;	char key[] __aligned(8);}; static inline bool htab_is_prealloc(const struct bpf_htab *htab){	return !(htab->map.map_flags & BPF_F_NO_PREALLOC);} static inline bool htab_use_raw_lock(const struct bpf_htab *htab){	return (!IS_ENABLED(CONFIG_PREEMPT_RT) || htab_is_prealloc(htab));} static void htab_init_buckets(struct bpf_htab *htab){	unsigned i; 	for (i = 0; i < htab->n_buckets; i++) {		INIT_HLIST_NULLS_HEAD(&htab->buckets[i].head, i);		if (htab_use_raw_lock(htab))			raw_spin_lock_init(&htab->buckets[i].raw_lock);		else			spin_lock_init(&htab->buckets[i].lock);	}} static inline unsigned long htab_lock_bucket(const struct bpf_htab *htab,					     struct bucket *b){	unsigned long flags; 	if (htab_use_raw_lock(htab))		raw_spin_lock_irqsave(&b->raw_lock, flags);	else		spin_lock_irqsave(&b->lock, flags);	return flags;} static inline void htab_unlock_bucket(const struct bpf_htab *htab,				      struct bucket *b,				      unsigned long flags){	if (htab_use_raw_lock(htab))		raw_spin_unlock_irqrestore(&b->raw_lock, flags);	else		spin_unlock_irqrestore(&b->lock, flags);} static bool htab_lru_map_delete_node(void *arg, struct bpf_lru_node *node); static bool htab_is_lru(const struct bpf_htab *htab){	return htab->map.map_type == BPF_MAP_TYPE_LRU_HASH ||		htab->map.map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH;} static bool htab_is_percpu(const struct bpf_htab *htab){	return htab->map.map_type == BPF_MAP_TYPE_PERCPU_HASH ||		htab->map.map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH;} static inline void htab_elem_set_ptr(struct htab_elem *l, u32 key_size,				     void __percpu *pptr){	*(void __percpu **)(l->key + key_size) = pptr;} static inline void __percpu *htab_elem_get_ptr(struct htab_elem *l, u32 key_size){	return *(void __percpu **)(l->key + key_size);} static void *fd_htab_map_get_ptr(const struct bpf_map *map, struct htab_elem *l){	return *(void **)(l->key + roundup(map->key_size, 8));} static struct htab_elem *get_htab_elem(struct bpf_htab *htab, int i){	return (struct htab_elem *) (htab->elems + i * htab->elem_size);} static void htab_free_elems(struct bpf_htab *htab){	int i; 	if (!htab_is_percpu(htab))		goto free_elems; 	for (i = 0; i < htab->map.max_entries; i++) {		void __percpu *pptr; 		pptr = htab_elem_get_ptr(get_htab_elem(htab, i),					 htab->map.key_size);		free_percpu(pptr);		cond_resched();	}free_elems:	bpf_map_area_free(htab->elems);} /* The LRU list has a lock (lru_lock). Each htab bucket has a lock * (bucket_lock). If both locks need to be acquired together, the lock * order is always lru_lock -> bucket_lock and this only happens in * bpf_lru_list.c logic. For example, certain code path of * bpf_lru_pop_free(), which is called by function prealloc_lru_pop(), * will acquire lru_lock first followed by acquiring bucket_lock. * * In hashtab.c, to avoid deadlock, lock acquisition of * bucket_lock followed by lru_lock is not allowed. In such cases, * bucket_lock needs to be released first before acquiring lru_lock. */static struct htab_elem *prealloc_lru_pop(struct bpf_htab *htab, void *key,					  u32 hash){	struct bpf_lru_node *node = bpf_lru_pop_free(&htab->lru, hash);	struct htab_elem *l; 	if (node) {		l = container_of(node, struct htab_elem, lru_node);		memcpy(l->key, key, htab->map.key_size);		return l;	} 	return NULL;} static int prealloc_init(struct bpf_htab *htab){	u32 num_entries = htab->map.max_entries;	int err = -ENOMEM, i; 	if (!htab_is_percpu(htab) && !htab_is_lru(htab))		num_entries += num_possible_cpus(); 	htab->elems = bpf_map_area_alloc(htab->elem_size * num_entries,					 htab->map.numa_node);	if (!htab->elems)		return -ENOMEM; 	if (!htab_is_percpu(htab))		goto skip_percpu_elems; 	for (i = 0; i < num_entries; i++) {		u32 size = round_up(htab->map.value_size, 8);		void __percpu *pptr; 		pptr = __alloc_percpu_gfp(size, 8, GFP_USER | __GFP_NOWARN);		if (!pptr)			goto free_elems;		htab_elem_set_ptr(get_htab_elem(htab, i), htab->map.key_size,				  pptr);		cond_resched();	} skip_percpu_elems:	if (htab_is_lru(htab))		err = bpf_lru_init(&htab->lru,				   htab->map.map_flags & BPF_F_NO_COMMON_LRU,				   offsetof(struct htab_elem, hash) -				   offsetof(struct htab_elem, lru_node),				   htab_lru_map_delete_node,				   htab);	else		err = pcpu_freelist_init(&htab->freelist); 	if (err)		goto free_elems; 	if (htab_is_lru(htab))		bpf_lru_populate(&htab->lru, htab->elems,				 offsetof(struct htab_elem, lru_node),				 htab->elem_size, num_entries);	else		pcpu_freelist_populate(&htab->freelist,				       htab->elems + offsetof(struct htab_elem, fnode),				       htab->elem_size, num_entries); 	return 0; free_elems:	htab_free_elems(htab);	return err;} static void prealloc_destroy(struct bpf_htab *htab){	htab_free_elems(htab); 	if (htab_is_lru(htab))		bpf_lru_destroy(&htab->lru);	else		pcpu_freelist_destroy(&htab->freelist);} static int alloc_extra_elems(struct bpf_htab *htab){	struct htab_elem *__percpu *pptr, *l_new;	struct pcpu_freelist_node *l;	int cpu; 	pptr = __alloc_percpu_gfp(sizeof(struct htab_elem *), 8,				  GFP_USER | __GFP_NOWARN);	if (!pptr)		return -ENOMEM; 	for_each_possible_cpu(cpu) {		l = pcpu_freelist_pop(&htab->freelist);		/* pop will succeed, since prealloc_init()		 * preallocated extra num_possible_cpus elements		 */		l_new = container_of(l, struct htab_elem, fnode);		*per_cpu_ptr(pptr, cpu) = l_new;	}	htab->extra_elems = pptr;	return 0;} /* Called from syscall */static int htab_map_alloc_check(union bpf_attr *attr){	bool percpu = (attr->map_type == BPF_MAP_TYPE_PERCPU_HASH ||		       attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);	bool lru = (attr->map_type == BPF_MAP_TYPE_LRU_HASH ||		    attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);	/* percpu_lru means each cpu has its own LRU list.	 * it is different from BPF_MAP_TYPE_PERCPU_HASH where	 * the map's value itself is percpu.  percpu_lru has	 * nothing to do with the map's value.	 */	bool percpu_lru = (attr->map_flags & BPF_F_NO_COMMON_LRU);	bool prealloc = !(attr->map_flags & BPF_F_NO_PREALLOC);	bool zero_seed = (attr->map_flags & BPF_F_ZERO_SEED);	int numa_node = bpf_map_attr_numa_node(attr); 	BUILD_BUG_ON(offsetof(struct htab_elem, htab) !=		     offsetof(struct htab_elem, hash_node.pprev));	BUILD_BUG_ON(offsetof(struct htab_elem, fnode.next) !=		     offsetof(struct htab_elem, hash_node.pprev)); 	if (lru && !bpf_capable())		/* LRU implementation is much complicated than other		 * maps.  Hence, limit to CAP_BPF.		 */		return -EPERM; 	if (zero_seed && !capable(CAP_SYS_ADMIN))		/* Guard against local DoS, and discourage production use. */		return -EPERM; 	if (attr->map_flags & ~HTAB_CREATE_FLAG_MASK ||	    !bpf_map_flags_access_ok(attr->map_flags))		return -EINVAL; 	if (!lru && percpu_lru)		return -EINVAL; 	if (lru && !prealloc)		return -ENOTSUPP; 	if (numa_node != NUMA_NO_NODE && (percpu || percpu_lru))		return -EINVAL; 	/* check sanity of attributes.	 * value_size == 0 may be allowed in the future to use map as a set	 */	if (attr->max_entries == 0 || attr->key_size == 0 ||	    attr->value_size == 0)		return -EINVAL; 	if (attr->key_size > MAX_BPF_STACK)		/* eBPF programs initialize keys on stack, so they cannot be		 * larger than max stack size		 */		return -E2BIG; 	if (attr->value_size >= KMALLOC_MAX_SIZE -	    MAX_BPF_STACK - sizeof(struct htab_elem))		/* if value_size is bigger, the user space won't be able to		 * access the elements via bpf syscall. This check also makes		 * sure that the elem_size doesn't overflow and it's		 * kmalloc-able later in htab_map_update_elem()		 */		return -E2BIG; 	return 0;} static struct bpf_map *htab_map_alloc(union bpf_attr *attr){	bool percpu = (attr->map_type == BPF_MAP_TYPE_PERCPU_HASH ||		       attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);	bool lru = (attr->map_type == BPF_MAP_TYPE_LRU_HASH ||		    attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);	/* percpu_lru means each cpu has its own LRU list.	 * it is different from BPF_MAP_TYPE_PERCPU_HASH where	 * the map's value itself is percpu.  percpu_lru has	 * nothing to do with the map's value.	 */	bool percpu_lru = (attr->map_flags & BPF_F_NO_COMMON_LRU);	bool prealloc = !(attr->map_flags & BPF_F_NO_PREALLOC);	struct bpf_htab *htab;	u64 cost;	int err; 	htab = kzalloc(sizeof(*htab), GFP_USER);	if (!htab)		return ERR_PTR(-ENOMEM); 	bpf_map_init_from_attr(&htab->map, attr); 	if (percpu_lru) {		/* ensure each CPU's lru list has >=1 elements.		 * since we are at it, make each lru list has the same		 * number of elements.		 */		htab->map.max_entries = roundup(attr->max_entries,						num_possible_cpus());		if (htab->map.max_entries < attr->max_entries)			htab->map.max_entries = rounddown(attr->max_entries,							  num_possible_cpus());	} 	/* hash table size must be power of 2 */	htab->n_buckets = roundup_pow_of_two(htab->map.max_entries); 	htab->elem_size = sizeof(struct htab_elem) +			  round_up(htab->map.key_size, 8);	if (percpu)		htab->elem_size += sizeof(void *);	else		htab->elem_size += round_up(htab->map.value_size, 8); 	err = -E2BIG;	/* prevent zero size kmalloc and check for u32 overflow */	if (htab->n_buckets == 0 ||	    htab->n_buckets > U32_MAX / sizeof(struct bucket))		goto free_htab; 	cost = (u64) htab->n_buckets * sizeof(struct bucket) +	       (u64) htab->elem_size * htab->map.max_entries; 	if (percpu)		cost += (u64) round_up(htab->map.value_size, 8) *			num_possible_cpus() * htab->map.max_entries;	else	       cost += (u64) htab->elem_size * num_possible_cpus(); 	/* if map size is larger than memlock limit, reject it */	err = bpf_map_charge_init(&htab->map.memory, cost);	if (err)		goto free_htab; 	err = -ENOMEM;	htab->buckets = bpf_map_area_alloc(htab->n_buckets *					   sizeof(struct bucket),					   htab->map.numa_node);	if (!htab->buckets)		goto free_charge; 	if (htab->map.map_flags & BPF_F_ZERO_SEED)		htab->hashrnd = 0;	else		htab->hashrnd = get_random_int(); 	htab_init_buckets(htab); 	if (prealloc) {		err = prealloc_init(htab);		if (err)			goto free_buckets; 		if (!percpu && !lru) {			/* lru itself can remove the least used element, so			 * there is no need for an extra elem during map_update.			 */			err = alloc_extra_elems(htab);			if (err)				goto free_prealloc;

Lines 1–500 of 2115.