hashtab.c 69.4 KB
Newer Older
1
// SPDX-License-Identifier: GPL-2.0-only
2
/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com
3
 * Copyright (c) 2016 Facebook
4 5
 */
#include <linux/bpf.h>
6
#include <linux/btf.h>
7 8
#include <linux/jhash.h>
#include <linux/filter.h>
9
#include <linux/rculist_nulls.h>
10
#include <linux/rcupdate_wait.h>
11
#include <linux/random.h>
12
#include <uapi/linux/btf.h>
13
#include <linux/rcupdate_trace.h>
14
#include <linux/btf_ids.h>
15
#include "percpu_freelist.h"
16
#include "bpf_lru_list.h"
17
#include "map_in_map.h"
18
#include <linux/bpf_mem_alloc.h>
19

20 21
#define HTAB_CREATE_FLAG_MASK						\
	(BPF_F_NO_PREALLOC | BPF_F_NO_COMMON_LRU | BPF_F_NUMA_NODE |	\
22
	 BPF_F_ACCESS_MASK | BPF_F_ZERO_SEED)
23

24 25 26 27 28 29 30 31 32 33
#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

34 35 36
/*
 * The bucket lock has two protection scopes:
 *
37
 * 1) Serializing concurrent operations from BPF programs on different
38 39 40 41 42 43 44 45 46 47 48 49 50 51
 *    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
Zhen Lei's avatar
Zhen Lei committed
52
 * protection across the map operation.
53 54 55 56
 *
 * 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
Zhen Lei's avatar
Zhen Lei committed
57
 * allocator calls into code paths which acquire locks with long held lock
58 59 60 61 62 63 64 65
 * 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
66
 *   spin_lock*(); alloc(GFP_ATOMIC); spin_unlock*();
67 68 69 70 71
 * 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
72 73 74 75 76 77
 * atomic contexts even on RT. Before the introduction of bpf_mem_alloc,
 * it is only safe to use raw spinlock for preallocated hash map on a RT kernel,
 * because there is no memory allocation within the lock held sections. However
 * after hash map was fully converted to use bpf_mem_alloc, there will be
 * non-synchronous memory allocation for non-preallocated hash map, so it is
 * safe to always use raw spinlock for bucket lock.
78
 */
79
struct bucket {
80
	struct hlist_nulls_head head;
81
	raw_spinlock_t raw_lock;
82 83
};

84 85 86
#define HASHTAB_MAP_LOCK_COUNT 8
#define HASHTAB_MAP_LOCK_MASK (HASHTAB_MAP_LOCK_COUNT - 1)

87 88
struct bpf_htab {
	struct bpf_map map;
89
	struct bpf_mem_alloc ma;
90
	struct bpf_mem_alloc pcpu_ma;
91
	struct bucket *buckets;
92
	void *elems;
93 94 95 96
	union {
		struct pcpu_freelist freelist;
		struct bpf_lru lru;
	};
97
	struct htab_elem *__percpu *extra_elems;
98 99 100 101 102 103
	/* number of elements in non-preallocated hashtable are kept
	 * in either pcount or count
	 */
	struct percpu_counter pcount;
	atomic_t count;
	bool use_percpu_counter;
104 105
	u32 n_buckets;	/* number of hash buckets */
	u32 elem_size;	/* size of each element in bytes */
106
	u32 hashrnd;
107
	struct lock_class_key lockdep_key;
108
	int __percpu *map_locked[HASHTAB_MAP_LOCK_COUNT];
109 110 111 112
};

/* each htab element is struct htab_elem + key + value */
struct htab_elem {
113
	union {
114
		struct hlist_nulls_node hash_node;
115 116 117 118
		struct {
			void *padding;
			union {
				struct pcpu_freelist_node fnode;
119
				struct htab_elem *batch_flink;
120 121
			};
		};
122
	};
123
	union {
124 125
		/* pointer to per-cpu pointer */
		void *ptr_to_pptr;
126
		struct bpf_lru_node lru_node;
127
	};
128
	u32 hash;
129
	char key[] __aligned(8);
130 131
};

132 133 134 135 136
static inline bool htab_is_prealloc(const struct bpf_htab *htab)
{
	return !(htab->map.map_flags & BPF_F_NO_PREALLOC);
}

137 138
static void htab_init_buckets(struct bpf_htab *htab)
{
139
	unsigned int i;
140 141 142

	for (i = 0; i < htab->n_buckets; i++) {
		INIT_HLIST_NULLS_HEAD(&htab->buckets[i].head, i);
143 144
		raw_spin_lock_init(&htab->buckets[i].raw_lock);
		lockdep_set_class(&htab->buckets[i].raw_lock,
145
					  &htab->lockdep_key);
146
		cond_resched();
147 148 149
	}
}

150 151 152
static inline int htab_lock_bucket(const struct bpf_htab *htab,
				   struct bucket *b, u32 hash,
				   unsigned long *pflags)
153 154 155
{
	unsigned long flags;

156
	hash = hash & min_t(u32, HASHTAB_MAP_LOCK_MASK, htab->n_buckets - 1);
157

158
	preempt_disable();
159
	local_irq_save(flags);
160 161
	if (unlikely(__this_cpu_inc_return(*(htab->map_locked[hash])) != 1)) {
		__this_cpu_dec(*(htab->map_locked[hash]));
162
		local_irq_restore(flags);
163
		preempt_enable();
164 165 166
		return -EBUSY;
	}

167
	raw_spin_lock(&b->raw_lock);
168 169 170
	*pflags = flags;

	return 0;
171 172 173
}

static inline void htab_unlock_bucket(const struct bpf_htab *htab,
174
				      struct bucket *b, u32 hash,
175 176
				      unsigned long flags)
{
177
	hash = hash & min_t(u32, HASHTAB_MAP_LOCK_MASK, htab->n_buckets - 1);
178
	raw_spin_unlock(&b->raw_lock);
179
	__this_cpu_dec(*(htab->map_locked[hash]));
180
	local_irq_restore(flags);
181
	preempt_enable();
182 183
}

184 185 186 187
static bool htab_lru_map_delete_node(void *arg, struct bpf_lru_node *node);

static bool htab_is_lru(const struct bpf_htab *htab)
{
188 189 190 191 192 193 194 195
	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;
196 197
}

198 199 200 201 202 203 204 205 206 207 208
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);
}

209 210 211 212 213
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));
}

214 215
static struct htab_elem *get_htab_elem(struct bpf_htab *htab, int i)
{
216
	return (struct htab_elem *) (htab->elems + i * (u64)htab->elem_size);
217 218
}

219 220 221 222 223 224 225 226 227 228
static bool htab_has_extra_elems(struct bpf_htab *htab)
{
	return !htab_is_percpu(htab) && !htab_is_lru(htab);
}

static void htab_free_prealloced_timers(struct bpf_htab *htab)
{
	u32 num_entries = htab->map.max_entries;
	int i;

229
	if (!btf_record_has_field(htab->map.record, BPF_TIMER))
230 231 232 233 234 235 236 237
		return;
	if (htab_has_extra_elems(htab))
		num_entries += num_possible_cpus();

	for (i = 0; i < num_entries; i++) {
		struct htab_elem *elem;

		elem = get_htab_elem(htab, i);
238
		bpf_obj_free_timer(htab->map.record, elem->key + round_up(htab->map.key_size, 8));
239 240 241 242
		cond_resched();
	}
}

243
static void htab_free_prealloced_fields(struct bpf_htab *htab)
244 245 246 247
{
	u32 num_entries = htab->map.max_entries;
	int i;

248
	if (IS_ERR_OR_NULL(htab->map.record))
249 250 251 252 253 254 255
		return;
	if (htab_has_extra_elems(htab))
		num_entries += num_possible_cpus();
	for (i = 0; i < num_entries; i++) {
		struct htab_elem *elem;

		elem = get_htab_elem(htab, i);
256 257 258 259 260 261 262 263 264 265 266 267
		if (htab_is_percpu(htab)) {
			void __percpu *pptr = htab_elem_get_ptr(elem, htab->map.key_size);
			int cpu;

			for_each_possible_cpu(cpu) {
				bpf_obj_free_fields(htab->map.record, per_cpu_ptr(pptr, cpu));
				cond_resched();
			}
		} else {
			bpf_obj_free_fields(htab->map.record, elem->key + round_up(htab->map.key_size, 8));
			cond_resched();
		}
268 269 270 271
		cond_resched();
	}
}

272 273 274 275
static void htab_free_elems(struct bpf_htab *htab)
{
	int i;

276
	if (!htab_is_percpu(htab))
277 278 279 280 281 282 283 284
		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);
285
		cond_resched();
286 287
	}
free_elems:
288
	bpf_map_area_free(htab->elems);
289 290
}

291 292 293 294 295 296 297 298 299 300 301
/* 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.
 */
302 303 304 305 306 307 308
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) {
309
		bpf_map_inc_elem_count(&htab->map);
310
		l = container_of(node, struct htab_elem, lru_node);
311
		memcpy(l->key, key, htab->map.key_size);
312 313 314 315 316 317 318
		return l;
	}

	return NULL;
}

static int prealloc_init(struct bpf_htab *htab)
319
{
320
	u32 num_entries = htab->map.max_entries;
321 322
	int err = -ENOMEM, i;

323
	if (htab_has_extra_elems(htab))
324 325
		num_entries += num_possible_cpus();

326
	htab->elems = bpf_map_area_alloc((u64)htab->elem_size * num_entries,
327
					 htab->map.numa_node);
328 329 330
	if (!htab->elems)
		return -ENOMEM;

331
	if (!htab_is_percpu(htab))
332 333
		goto skip_percpu_elems;

334
	for (i = 0; i < num_entries; i++) {
335 336 337
		u32 size = round_up(htab->map.value_size, 8);
		void __percpu *pptr;

338 339
		pptr = bpf_map_alloc_percpu(&htab->map, size, 8,
					    GFP_USER | __GFP_NOWARN);
340 341 342 343
		if (!pptr)
			goto free_elems;
		htab_elem_set_ptr(get_htab_elem(htab, i), htab->map.key_size,
				  pptr);
344
		cond_resched();
345 346 347
	}

skip_percpu_elems:
348 349 350 351 352 353 354 355 356 357
	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);

358 359 360
	if (err)
		goto free_elems;

361 362 363
	if (htab_is_lru(htab))
		bpf_lru_populate(&htab->lru, htab->elems,
				 offsetof(struct htab_elem, lru_node),
364
				 htab->elem_size, num_entries);
365
	else
366 367
		pcpu_freelist_populate(&htab->freelist,
				       htab->elems + offsetof(struct htab_elem, fnode),
368
				       htab->elem_size, num_entries);
369

370 371 372 373 374 375 376
	return 0;

free_elems:
	htab_free_elems(htab);
	return err;
}

377 378 379 380 381 382 383 384 385 386
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);
}

387 388
static int alloc_extra_elems(struct bpf_htab *htab)
{
389 390
	struct htab_elem *__percpu *pptr, *l_new;
	struct pcpu_freelist_node *l;
391 392
	int cpu;

393 394
	pptr = bpf_map_alloc_percpu(&htab->map, sizeof(struct htab_elem *), 8,
				    GFP_USER | __GFP_NOWARN);
395 396 397 398
	if (!pptr)
		return -ENOMEM;

	for_each_possible_cpu(cpu) {
399 400 401 402 403 404
		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;
405 406 407 408 409
	}
	htab->extra_elems = pptr;
	return 0;
}

410
/* Called from syscall */
411
static int htab_map_alloc_check(union bpf_attr *attr)
412
{
413 414 415 416
	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);
417 418 419 420 421 422 423
	/* 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);
424
	bool zero_seed = (attr->map_flags & BPF_F_ZERO_SEED);
425
	int numa_node = bpf_map_attr_numa_node(attr);
426

427 428 429
	BUILD_BUG_ON(offsetof(struct htab_elem, fnode.next) !=
		     offsetof(struct htab_elem, hash_node.pprev));

430 431 432 433
	if (zero_seed && !capable(CAP_SYS_ADMIN))
		/* Guard against local DoS, and discourage production use. */
		return -EPERM;

434 435
	if (attr->map_flags & ~HTAB_CREATE_FLAG_MASK ||
	    !bpf_map_flags_access_ok(attr->map_flags))
436
		return -EINVAL;
437

438
	if (!lru && percpu_lru)
439
		return -EINVAL;
440 441

	if (lru && !prealloc)
442
		return -ENOTSUPP;
443

444
	if (numa_node != NUMA_NO_NODE && (percpu || percpu_lru))
445
		return -EINVAL;
446

447 448 449 450 451
	/* 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)
452
		return -EINVAL;
453

454 455 456 457 458
	if ((u64)attr->key_size + attr->value_size >= KMALLOC_MAX_SIZE -
	   sizeof(struct htab_elem))
		/* if key_size + 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
459 460
		 * kmalloc-able later in htab_map_update_elem()
		 */
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
		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;
480
	int err, i;
481

482
	htab = bpf_map_area_alloc(sizeof(*htab), NUMA_NO_NODE);
483 484 485
	if (!htab)
		return ERR_PTR(-ENOMEM);

486 487
	lockdep_register_key(&htab->lockdep_key);

488
	bpf_map_init_from_attr(&htab->map, attr);
489

490 491 492 493 494 495 496 497 498 499 500 501
	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());
	}

502 503 504 505 506 507 508
	/* hash table size must be power of 2; roundup_pow_of_two() can overflow
	 * into UB on 32-bit arches, so check that first
	 */
	err = -E2BIG;
	if (htab->map.max_entries > 1UL << 31)
		goto free_htab;

509 510
	htab->n_buckets = roundup_pow_of_two(htab->map.max_entries);

511
	htab->elem_size = sizeof(struct htab_elem) +
512 513 514 515
			  round_up(htab->map.key_size, 8);
	if (percpu)
		htab->elem_size += sizeof(void *);
	else
516
		htab->elem_size += round_up(htab->map.value_size, 8);
517

518 519
	/* check for u32 overflow */
	if (htab->n_buckets > U32_MAX / sizeof(struct bucket))
520 521
		goto free_htab;

522 523 524 525
	err = bpf_map_init_elem_count(&htab->map);
	if (err)
		goto free_htab;

526
	err = -ENOMEM;
527
	htab->buckets = bpf_map_area_alloc(htab->n_buckets *
528 529
					   sizeof(struct bucket),
					   htab->map.numa_node);
530
	if (!htab->buckets)
531
		goto free_elem_count;
532

533
	for (i = 0; i < HASHTAB_MAP_LOCK_COUNT; i++) {
534 535 536 537
		htab->map_locked[i] = bpf_map_alloc_percpu(&htab->map,
							   sizeof(int),
							   sizeof(int),
							   GFP_USER);
538 539 540 541
		if (!htab->map_locked[i])
			goto free_map_locked;
	}

542 543 544
	if (htab->map.map_flags & BPF_F_ZERO_SEED)
		htab->hashrnd = 0;
	else
545
		htab->hashrnd = get_random_u32();
546

547
	htab_init_buckets(htab);
548

549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
/* compute_batch_value() computes batch value as num_online_cpus() * 2
 * and __percpu_counter_compare() needs
 * htab->max_entries - cur_number_of_elems to be more than batch * num_online_cpus()
 * for percpu_counter to be faster than atomic_t. In practice the average bpf
 * hash map size is 10k, which means that a system with 64 cpus will fill
 * hashmap to 20% of 10k before percpu_counter becomes ineffective. Therefore
 * define our own batch count as 32 then 10k hash map can be filled up to 80%:
 * 10k - 8k > 32 _batch_ * 64 _cpus_
 * and __percpu_counter_compare() will still be fast. At that point hash map
 * collisions will dominate its performance anyway. Assume that hash map filled
 * to 50+% isn't going to be O(1) and use the following formula to choose
 * between percpu_counter and atomic_t.
 */
#define PERCPU_COUNTER_BATCH 32
	if (attr->max_entries / 2 > num_online_cpus() * PERCPU_COUNTER_BATCH)
		htab->use_percpu_counter = true;

	if (htab->use_percpu_counter) {
		err = percpu_counter_init(&htab->pcount, 0, GFP_KERNEL);
		if (err)
			goto free_map_locked;
	}

572 573
	if (prealloc) {
		err = prealloc_init(htab);
574
		if (err)
575
			goto free_map_locked;
576 577 578 579 580 581 582 583 584

		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;
		}
585
	} else {
586
		err = bpf_mem_alloc_init(&htab->ma, htab->elem_size, false);
587 588
		if (err)
			goto free_map_locked;
589 590 591 592 593 594
		if (percpu) {
			err = bpf_mem_alloc_init(&htab->pcpu_ma,
						 round_up(htab->map.value_size, 8), true);
			if (err)
				goto free_map_locked;
		}
595
	}
596 597 598

	return &htab->map;

599 600
free_prealloc:
	prealloc_destroy(htab);
601
free_map_locked:
602 603
	if (htab->use_percpu_counter)
		percpu_counter_destroy(&htab->pcount);
604 605
	for (i = 0; i < HASHTAB_MAP_LOCK_COUNT; i++)
		free_percpu(htab->map_locked[i]);
606
	bpf_map_area_free(htab->buckets);
607
	bpf_mem_alloc_destroy(&htab->pcpu_ma);
608
	bpf_mem_alloc_destroy(&htab->ma);
609 610
free_elem_count:
	bpf_map_free_elem_count(&htab->map);
611
free_htab:
612
	lockdep_unregister_key(&htab->lockdep_key);
613
	bpf_map_area_free(htab);
614 615 616
	return ERR_PTR(err);
}

617
static inline u32 htab_map_hash(const void *key, u32 key_len, u32 hashrnd)
618
{
619 620
	if (likely(key_len % 4 == 0))
		return jhash2(key, key_len / 4, hashrnd);
621
	return jhash(key, key_len, hashrnd);
622 623
}

624
static inline struct bucket *__select_bucket(struct bpf_htab *htab, u32 hash)
625 626 627 628
{
	return &htab->buckets[hash & (htab->n_buckets - 1)];
}

629
static inline struct hlist_nulls_head *select_bucket(struct bpf_htab *htab, u32 hash)
630 631 632 633
{
	return &__select_bucket(htab, hash)->head;
}

634 635
/* this lookup function can only be called with bucket lock taken */
static struct htab_elem *lookup_elem_raw(struct hlist_nulls_head *head, u32 hash,
636 637
					 void *key, u32 key_size)
{
638
	struct hlist_nulls_node *n;
639 640
	struct htab_elem *l;

641
	hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
642 643 644 645 646 647
		if (l->hash == hash && !memcmp(&l->key, key, key_size))
			return l;

	return NULL;
}

648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
/* can be called without bucket lock. it will repeat the loop in
 * the unlikely event when elements moved from one bucket into another
 * while link list is being walked
 */
static struct htab_elem *lookup_nulls_elem_raw(struct hlist_nulls_head *head,
					       u32 hash, void *key,
					       u32 key_size, u32 n_buckets)
{
	struct hlist_nulls_node *n;
	struct htab_elem *l;

again:
	hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
		if (l->hash == hash && !memcmp(&l->key, key, key_size))
			return l;

	if (unlikely(get_nulls_value(n) != (hash & (n_buckets - 1))))
		goto again;

	return NULL;
}

670 671 672 673 674
/* Called from syscall or from eBPF program directly, so
 * arguments have to match bpf_map_lookup_elem() exactly.
 * The return value is adjusted by BPF instructions
 * in htab_map_gen_lookup().
 */
675
static void *__htab_map_lookup_elem(struct bpf_map *map, void *key)
676 677
{
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
678
	struct hlist_nulls_head *head;
679 680 681
	struct htab_elem *l;
	u32 hash, key_size;

682 683
	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
		     !rcu_read_lock_bh_held());
684 685 686

	key_size = map->key_size;

687
	hash = htab_map_hash(key, key_size, htab->hashrnd);
688 689 690

	head = select_bucket(htab, hash);

691
	l = lookup_nulls_elem_raw(head, hash, key, key_size, htab->n_buckets);
692

693 694 695 696 697 698 699
	return l;
}

static void *htab_map_lookup_elem(struct bpf_map *map, void *key)
{
	struct htab_elem *l = __htab_map_lookup_elem(map, key);

700 701 702 703 704 705
	if (l)
		return l->key + round_up(map->key_size, 8);

	return NULL;
}

706 707 708 709 710 711 712 713 714 715 716
/* inline bpf_map_lookup_elem() call.
 * Instead of:
 * bpf_prog
 *   bpf_map_lookup_elem
 *     map->ops->map_lookup_elem
 *       htab_map_lookup_elem
 *         __htab_map_lookup_elem
 * do:
 * bpf_prog
 *   __htab_map_lookup_elem
 */
717
static int htab_map_gen_lookup(struct bpf_map *map, struct bpf_insn *insn_buf)
718 719 720 721
{
	struct bpf_insn *insn = insn_buf;
	const int ret = BPF_REG_0;

722 723
	BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
		     (void *(*)(struct bpf_map *map, void *key))NULL));
724
	*insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
725 726 727 728 729 730 731
	*insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 1);
	*insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
				offsetof(struct htab_elem, key) +
				round_up(map->key_size, 8));
	return insn - insn_buf;
}

732 733
static __always_inline void *__htab_lru_map_lookup_elem(struct bpf_map *map,
							void *key, const bool mark)
734 735 736 737
{
	struct htab_elem *l = __htab_map_lookup_elem(map, key);

	if (l) {
738 739
		if (mark)
			bpf_lru_node_set_ref(&l->lru_node);
740 741 742 743 744 745
		return l->key + round_up(map->key_size, 8);
	}

	return NULL;
}

746 747 748 749 750 751 752 753 754 755
static void *htab_lru_map_lookup_elem(struct bpf_map *map, void *key)
{
	return __htab_lru_map_lookup_elem(map, key, true);
}

static void *htab_lru_map_lookup_elem_sys(struct bpf_map *map, void *key)
{
	return __htab_lru_map_lookup_elem(map, key, false);
}

756
static int htab_lru_map_gen_lookup(struct bpf_map *map,
757 758 759 760
				   struct bpf_insn *insn_buf)
{
	struct bpf_insn *insn = insn_buf;
	const int ret = BPF_REG_0;
761
	const int ref_reg = BPF_REG_1;
762

763 764
	BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
		     (void *(*)(struct bpf_map *map, void *key))NULL));
765
	*insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
766 767 768 769 770
	*insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 4);
	*insn++ = BPF_LDX_MEM(BPF_B, ref_reg, ret,
			      offsetof(struct htab_elem, lru_node) +
			      offsetof(struct bpf_lru_node, ref));
	*insn++ = BPF_JMP_IMM(BPF_JNE, ref_reg, 0, 1);
771 772 773 774 775 776 777 778 779 780
	*insn++ = BPF_ST_MEM(BPF_B, ret,
			     offsetof(struct htab_elem, lru_node) +
			     offsetof(struct bpf_lru_node, ref),
			     1);
	*insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
				offsetof(struct htab_elem, key) +
				round_up(map->key_size, 8));
	return insn - insn_buf;
}

781 782
static void check_and_free_fields(struct bpf_htab *htab,
				  struct htab_elem *elem)
783
{
784 785 786
	if (htab_is_percpu(htab)) {
		void __percpu *pptr = htab_elem_get_ptr(elem, htab->map.key_size);
		int cpu;
787

788 789 790 791 792 793 794
		for_each_possible_cpu(cpu)
			bpf_obj_free_fields(htab->map.record, per_cpu_ptr(pptr, cpu));
	} else {
		void *map_value = elem->key + round_up(htab->map.key_size, 8);

		bpf_obj_free_fields(htab->map.record, map_value);
	}
795 796
}

797 798 799 800 801
/* It is called from the bpf_lru_list when the LRU needs to delete
 * older elements from the htab.
 */
static bool htab_lru_map_delete_node(void *arg, struct bpf_lru_node *node)
{
802
	struct bpf_htab *htab = arg;
803 804 805
	struct htab_elem *l = NULL, *tgt_l;
	struct hlist_nulls_head *head;
	struct hlist_nulls_node *n;
806 807
	unsigned long flags;
	struct bucket *b;
808
	int ret;
809 810 811 812 813

	tgt_l = container_of(node, struct htab_elem, lru_node);
	b = __select_bucket(htab, tgt_l->hash);
	head = &b->head;

814 815 816
	ret = htab_lock_bucket(htab, b, tgt_l->hash, &flags);
	if (ret)
		return false;
817

818
	hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
819
		if (l == tgt_l) {
820
			hlist_nulls_del_rcu(&l->hash_node);
821
			check_and_free_fields(htab, l);
822
			bpf_map_dec_elem_count(&htab->map);
823 824 825
			break;
		}

826
	htab_unlock_bucket(htab, b, tgt_l->hash, flags);
827 828 829 830

	return l == tgt_l;
}

831 832 833 834
/* Called from syscall */
static int htab_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
{
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
835
	struct hlist_nulls_head *head;
836 837
	struct htab_elem *l, *next_l;
	u32 hash, key_size;
838
	int i = 0;
839 840 841 842 843

	WARN_ON_ONCE(!rcu_read_lock_held());

	key_size = map->key_size;

844 845 846
	if (!key)
		goto find_first_elem;

847
	hash = htab_map_hash(key, key_size, htab->hashrnd);
848 849 850 851

	head = select_bucket(htab, hash);

	/* lookup the key */
852
	l = lookup_nulls_elem_raw(head, hash, key, key_size, htab->n_buckets);
853

854
	if (!l)
855 856 857
		goto find_first_elem;

	/* key was found, get next key in the same bucket */
858
	next_l = hlist_nulls_entry_safe(rcu_dereference_raw(hlist_nulls_next_rcu(&l->hash_node)),
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
				  struct htab_elem, hash_node);

	if (next_l) {
		/* if next elem in this hash list is non-zero, just return it */
		memcpy(next_key, next_l->key, key_size);
		return 0;
	}

	/* no more elements in this hash list, go to the next bucket */
	i = hash & (htab->n_buckets - 1);
	i++;

find_first_elem:
	/* iterate over buckets */
	for (; i < htab->n_buckets; i++) {
		head = select_bucket(htab, i);

		/* pick first element in the bucket */
877
		next_l = hlist_nulls_entry_safe(rcu_dereference_raw(hlist_nulls_first_rcu(head)),
878 879 880 881 882 883 884 885
					  struct htab_elem, hash_node);
		if (next_l) {
			/* if it's not empty, just return it */
			memcpy(next_key, next_l->key, key_size);
			return 0;
		}
	}

886
	/* iterated over all buckets and all elements */
887 888 889
	return -ENOENT;
}

890
static void htab_elem_free(struct bpf_htab *htab, struct htab_elem *l)
891
{
892
	check_and_free_fields(htab, l);
893
	if (htab->map.map_type == BPF_MAP_TYPE_PERCPU_HASH)
894
		bpf_mem_cache_free(&htab->pcpu_ma, l->ptr_to_pptr);
895
	bpf_mem_cache_free(&htab->ma, l);
896 897
}

898
static void htab_put_fd_value(struct bpf_htab *htab, struct htab_elem *l)
899
{
900
	struct bpf_map *map = &htab->map;
901
	void *ptr;
902 903

	if (map->ops->map_fd_put_ptr) {
904
		ptr = fd_htab_map_get_ptr(map, l);
905
		map->ops->map_fd_put_ptr(map, ptr, true);
906
	}
907 908
}

909 910 911 912 913 914 915 916 917 918
static bool is_map_full(struct bpf_htab *htab)
{
	if (htab->use_percpu_counter)
		return __percpu_counter_compare(&htab->pcount, htab->map.max_entries,
						PERCPU_COUNTER_BATCH) >= 0;
	return atomic_read(&htab->count) >= htab->map.max_entries;
}

static void inc_elem_count(struct bpf_htab *htab)
{
919 920
	bpf_map_inc_elem_count(&htab->map);

921 922 923 924 925 926 927 928
	if (htab->use_percpu_counter)
		percpu_counter_add_batch(&htab->pcount, 1, PERCPU_COUNTER_BATCH);
	else
		atomic_inc(&htab->count);
}

static void dec_elem_count(struct bpf_htab *htab)
{
929 930
	bpf_map_dec_elem_count(&htab->map);

931 932 933 934 935 936 937
	if (htab->use_percpu_counter)
		percpu_counter_add_batch(&htab->pcount, -1, PERCPU_COUNTER_BATCH);
	else
		atomic_dec(&htab->count);
}


938 939 940
static void free_htab_elem(struct bpf_htab *htab, struct htab_elem *l)
{
	htab_put_fd_value(htab, l);
941

942
	if (htab_is_prealloc(htab)) {
943
		bpf_map_dec_elem_count(&htab->map);
944
		check_and_free_fields(htab, l);
945
		__pcpu_freelist_push(&htab->freelist, &l->fnode);
946
	} else {
947
		dec_elem_count(htab);
948
		htab_elem_free(htab, l);
949 950 951
	}
}

952 953 954 955 956
static void pcpu_copy_value(struct bpf_htab *htab, void __percpu *pptr,
			    void *value, bool onallcpus)
{
	if (!onallcpus) {
		/* copy true value_size bytes */
957
		copy_map_value(&htab->map, this_cpu_ptr(pptr), value);
958 959 960 961 962
	} else {
		u32 size = round_up(htab->map.value_size, 8);
		int off = 0, cpu;

		for_each_possible_cpu(cpu) {
963
			copy_map_value_long(&htab->map, per_cpu_ptr(pptr, cpu), value + off);
964 965 966 967 968
			off += size;
		}
	}
}

969 970 971
static void pcpu_init_value(struct bpf_htab *htab, void __percpu *pptr,
			    void *value, bool onallcpus)
{
972 973
	/* When not setting the initial value on all cpus, zero-fill element
	 * values for other cpus. Otherwise, bpf program has no way to ensure
974 975 976
	 * known initial values for cpus other than current one
	 * (onallcpus=false always when coming from bpf prog).
	 */
977
	if (!onallcpus) {
978 979 980 981 982
		int current_cpu = raw_smp_processor_id();
		int cpu;

		for_each_possible_cpu(cpu) {
			if (cpu == current_cpu)
983 984 985
				copy_map_value_long(&htab->map, per_cpu_ptr(pptr, cpu), value);
			else /* Since elem is preallocated, we cannot touch special fields */
				zero_map_value(&htab->map, per_cpu_ptr(pptr, cpu));
986 987 988 989 990 991
		}
	} else {
		pcpu_copy_value(htab, pptr, value, onallcpus);
	}
}

992 993 994 995 996 997
static bool fd_htab_map_needs_adjust(const struct bpf_htab *htab)
{
	return htab->map.map_type == BPF_MAP_TYPE_HASH_OF_MAPS &&
	       BITS_PER_LONG == 64;
}

998 999
static struct htab_elem *alloc_htab_elem(struct bpf_htab *htab, void *key,
					 void *value, u32 key_size, u32 hash,
1000
					 bool percpu, bool onallcpus,
1001
					 struct htab_elem *old_elem)
1002
{
1003
	u32 size = htab->map.value_size;
1004 1005
	bool prealloc = htab_is_prealloc(htab);
	struct htab_elem *l_new, **pl_new;
1006 1007
	void __percpu *pptr;

1008
	if (prealloc) {
1009 1010 1011 1012 1013 1014
		if (old_elem) {
			/* if we're updating the existing element,
			 * use per-cpu extra elems to avoid freelist_pop/push
			 */
			pl_new = this_cpu_ptr(htab->extra_elems);
			l_new = *pl_new;
1015
			htab_put_fd_value(htab, old_elem);
1016 1017 1018
			*pl_new = old_elem;
		} else {
			struct pcpu_freelist_node *l;
1019

1020
			l = __pcpu_freelist_pop(&htab->freelist);
1021 1022
			if (!l)
				return ERR_PTR(-E2BIG);
1023
			l_new = container_of(l, struct htab_elem, fnode);
1024
			bpf_map_inc_elem_count(&htab->map);
1025
		}
1026
	} else {
1027 1028
		if (is_map_full(htab))
			if (!old_elem)
1029 1030 1031 1032 1033
				/* when map is full and update() is replacing
				 * old element, it's ok to allocate, since
				 * old element will be freed immediately.
				 * Otherwise return an error
				 */
1034 1035
				return ERR_PTR(-E2BIG);
		inc_elem_count(htab);
1036
		l_new = bpf_mem_cache_alloc(&htab->ma);
1037 1038 1039 1040
		if (!l_new) {
			l_new = ERR_PTR(-ENOMEM);
			goto dec_count;
		}
1041
	}
1042 1043 1044

	memcpy(l_new->key, key, key_size);
	if (percpu) {
1045 1046 1047 1048
		if (prealloc) {
			pptr = htab_elem_get_ptr(l_new, key_size);
		} else {
			/* alloc_percpu zero-fills */
1049
			pptr = bpf_mem_cache_alloc(&htab->pcpu_ma);
1050
			if (!pptr) {
1051
				bpf_mem_cache_free(&htab->ma, l_new);
1052 1053
				l_new = ERR_PTR(-ENOMEM);
				goto dec_count;
1054
			}
1055 1056
			l_new->ptr_to_pptr = pptr;
			pptr = *(void **)pptr;
1057 1058
		}

1059
		pcpu_init_value(htab, pptr, value, onallcpus);
1060

1061 1062
		if (!prealloc)
			htab_elem_set_ptr(l_new, key_size, pptr);
1063 1064
	} else if (fd_htab_map_needs_adjust(htab)) {
		size = round_up(size, 8);
1065
		memcpy(l_new->key + round_up(key_size, 8), value, size);
1066 1067 1068 1069
	} else {
		copy_map_value(&htab->map,
			       l_new->key + round_up(key_size, 8),
			       value);
1070 1071 1072 1073
	}

	l_new->hash = hash;
	return l_new;
1074
dec_count:
1075
	dec_elem_count(htab);
1076
	return l_new;
1077 1078 1079 1080 1081
}

static int check_flags(struct bpf_htab *htab, struct htab_elem *l_old,
		       u64 map_flags)
{
1082
	if (l_old && (map_flags & ~BPF_F_LOCK) == BPF_NOEXIST)
1083 1084 1085
		/* elem already exists */
		return -EEXIST;

1086
	if (!l_old && (map_flags & ~BPF_F_LOCK) == BPF_EXIST)
1087 1088 1089 1090 1091 1092
		/* elem doesn't exist, cannot update it */
		return -ENOENT;

	return 0;
}

1093
/* Called from syscall or from eBPF program */
1094 1095
static long htab_map_update_elem(struct bpf_map *map, void *key, void *value,
				 u64 map_flags)
1096 1097
{
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1098
	struct htab_elem *l_new = NULL, *l_old;
1099
	struct hlist_nulls_head *head;
1100
	unsigned long flags;
1101 1102
	struct bucket *b;
	u32 key_size, hash;
1103 1104
	int ret;

1105
	if (unlikely((map_flags & ~BPF_F_LOCK) > BPF_EXIST))
1106 1107 1108
		/* unknown flags */
		return -EINVAL;

1109 1110
	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
		     !rcu_read_lock_bh_held());
1111 1112 1113

	key_size = map->key_size;

1114
	hash = htab_map_hash(key, key_size, htab->hashrnd);
1115 1116

	b = __select_bucket(htab, hash);
1117
	head = &b->head;
1118

1119
	if (unlikely(map_flags & BPF_F_LOCK)) {
1120
		if (unlikely(!btf_record_has_field(map->record, BPF_SPIN_LOCK)))
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
			return -EINVAL;
		/* find an element without taking the bucket lock */
		l_old = lookup_nulls_elem_raw(head, hash, key, key_size,
					      htab->n_buckets);
		ret = check_flags(htab, l_old, map_flags);
		if (ret)
			return ret;
		if (l_old) {
			/* grab the element lock and update value in place */
			copy_map_value_locked(map,
					      l_old->key + round_up(key_size, 8),
					      value, false);
			return 0;
		}
		/* fall through, grab the bucket lock and lookup again.
		 * 99.9% chance that the element won't be found,
		 * but second lookup under lock has to be done.
		 */
	}

1141 1142 1143
	ret = htab_lock_bucket(htab, b, hash, &flags);
	if (ret)
		return ret;
1144

1145
	l_old = lookup_elem_raw(head, hash, key, key_size);
1146

1147 1148
	ret = check_flags(htab, l_old, map_flags);
	if (ret)
1149 1150
		goto err;

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
	if (unlikely(l_old && (map_flags & BPF_F_LOCK))) {
		/* first lookup without the bucket lock didn't find the element,
		 * but second lookup with the bucket lock found it.
		 * This case is highly unlikely, but has to be dealt with:
		 * grab the element lock in addition to the bucket lock
		 * and update element in place
		 */
		copy_map_value_locked(map,
				      l_old->key + round_up(key_size, 8),
				      value, false);
		ret = 0;
		goto err;
	}

1165
	l_new = alloc_htab_elem(htab, key, value, key_size, hash, false, false,
1166
				l_old);
1167 1168 1169 1170 1171 1172
	if (IS_ERR(l_new)) {
		/* all pre-allocated elements are in use or memory exhausted */
		ret = PTR_ERR(l_new);
		goto err;
	}

1173 1174
	/* add new element to the head of the list, so that
	 * concurrent search will find it before old elem
1175
	 */
1176
	hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1177
	if (l_old) {
1178
		hlist_nulls_del_rcu(&l_old->hash_node);
1179 1180
		if (!htab_is_prealloc(htab))
			free_htab_elem(htab, l_old);
1181
		else
1182
			check_and_free_fields(htab, l_old);
1183
	}
1184
	ret = 0;
1185
err:
1186
	htab_unlock_bucket(htab, b, hash, flags);
1187 1188 1189
	return ret;
}

1190 1191
static void htab_lru_push_free(struct bpf_htab *htab, struct htab_elem *elem)
{
1192
	check_and_free_fields(htab, elem);
1193
	bpf_map_dec_elem_count(&htab->map);
1194 1195 1196
	bpf_lru_push_free(&htab->lru, &elem->lru_node);
}

1197 1198
static long htab_lru_map_update_elem(struct bpf_map *map, void *key, void *value,
				     u64 map_flags)
1199 1200 1201
{
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
	struct htab_elem *l_new, *l_old = NULL;
1202
	struct hlist_nulls_head *head;
1203 1204 1205 1206 1207 1208 1209 1210 1211
	unsigned long flags;
	struct bucket *b;
	u32 key_size, hash;
	int ret;

	if (unlikely(map_flags > BPF_EXIST))
		/* unknown flags */
		return -EINVAL;

1212 1213
	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
		     !rcu_read_lock_bh_held());
1214 1215 1216

	key_size = map->key_size;

1217
	hash = htab_map_hash(key, key_size, htab->hashrnd);
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229

	b = __select_bucket(htab, hash);
	head = &b->head;

	/* For LRU, we need to alloc before taking bucket's
	 * spinlock because getting free nodes from LRU may need
	 * to remove older elements from htab and this removal
	 * operation will need a bucket lock.
	 */
	l_new = prealloc_lru_pop(htab, key, hash);
	if (!l_new)
		return -ENOMEM;
1230 1231
	copy_map_value(&htab->map,
		       l_new->key + round_up(map->key_size, 8), value);
1232

1233 1234
	ret = htab_lock_bucket(htab, b, hash, &flags);
	if (ret)
1235
		goto err_lock_bucket;
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245

	l_old = lookup_elem_raw(head, hash, key, key_size);

	ret = check_flags(htab, l_old, map_flags);
	if (ret)
		goto err;

	/* add new element to the head of the list, so that
	 * concurrent search will find it before old elem
	 */
1246
	hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1247 1248
	if (l_old) {
		bpf_lru_node_set_ref(&l_new->lru_node);
1249
		hlist_nulls_del_rcu(&l_old->hash_node);
1250 1251 1252 1253
	}
	ret = 0;

err:
1254
	htab_unlock_bucket(htab, b, hash, flags);
1255

1256
err_lock_bucket:
1257
	if (ret)
1258
		htab_lru_push_free(htab, l_new);
1259
	else if (l_old)
1260
		htab_lru_push_free(htab, l_old);
1261 1262 1263 1264

	return ret;
}

1265 1266 1267
static long __htab_percpu_map_update_elem(struct bpf_map *map, void *key,
					  void *value, u64 map_flags,
					  bool onallcpus)
1268 1269 1270
{
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
	struct htab_elem *l_new = NULL, *l_old;
1271
	struct hlist_nulls_head *head;
1272 1273 1274 1275 1276 1277 1278 1279 1280
	unsigned long flags;
	struct bucket *b;
	u32 key_size, hash;
	int ret;

	if (unlikely(map_flags > BPF_EXIST))
		/* unknown flags */
		return -EINVAL;

1281 1282
	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
		     !rcu_read_lock_bh_held());
1283 1284 1285

	key_size = map->key_size;

1286
	hash = htab_map_hash(key, key_size, htab->hashrnd);
1287 1288 1289 1290

	b = __select_bucket(htab, hash);
	head = &b->head;

1291 1292 1293
	ret = htab_lock_bucket(htab, b, hash, &flags);
	if (ret)
		return ret;
1294 1295 1296 1297 1298 1299 1300 1301 1302

	l_old = lookup_elem_raw(head, hash, key, key_size);

	ret = check_flags(htab, l_old, map_flags);
	if (ret)
		goto err;

	if (l_old) {
		/* per-cpu hash map can update value in-place */
1303 1304
		pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size),
				value, onallcpus);
1305 1306
	} else {
		l_new = alloc_htab_elem(htab, key, value, key_size,
1307
					hash, true, onallcpus, NULL);
1308 1309
		if (IS_ERR(l_new)) {
			ret = PTR_ERR(l_new);
1310 1311
			goto err;
		}
1312
		hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1313 1314 1315
	}
	ret = 0;
err:
1316
	htab_unlock_bucket(htab, b, hash, flags);
1317 1318 1319
	return ret;
}

1320 1321 1322
static long __htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key,
					      void *value, u64 map_flags,
					      bool onallcpus)
1323 1324 1325
{
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
	struct htab_elem *l_new = NULL, *l_old;
1326
	struct hlist_nulls_head *head;
1327 1328 1329 1330 1331 1332 1333 1334 1335
	unsigned long flags;
	struct bucket *b;
	u32 key_size, hash;
	int ret;

	if (unlikely(map_flags > BPF_EXIST))
		/* unknown flags */
		return -EINVAL;

1336 1337
	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
		     !rcu_read_lock_bh_held());
1338 1339 1340

	key_size = map->key_size;

1341
	hash = htab_map_hash(key, key_size, htab->hashrnd);
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356

	b = __select_bucket(htab, hash);
	head = &b->head;

	/* For LRU, we need to alloc before taking bucket's
	 * spinlock because LRU's elem alloc may need
	 * to remove older elem from htab and this removal
	 * operation will need a bucket lock.
	 */
	if (map_flags != BPF_EXIST) {
		l_new = prealloc_lru_pop(htab, key, hash);
		if (!l_new)
			return -ENOMEM;
	}

1357 1358
	ret = htab_lock_bucket(htab, b, hash, &flags);
	if (ret)
1359
		goto err_lock_bucket;
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373

	l_old = lookup_elem_raw(head, hash, key, key_size);

	ret = check_flags(htab, l_old, map_flags);
	if (ret)
		goto err;

	if (l_old) {
		bpf_lru_node_set_ref(&l_old->lru_node);

		/* per-cpu hash map can update value in-place */
		pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size),
				value, onallcpus);
	} else {
1374
		pcpu_init_value(htab, htab_elem_get_ptr(l_new, key_size),
1375
				value, onallcpus);
1376
		hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1377 1378 1379 1380
		l_new = NULL;
	}
	ret = 0;
err:
1381
	htab_unlock_bucket(htab, b, hash, flags);
1382
err_lock_bucket:
1383 1384
	if (l_new) {
		bpf_map_dec_elem_count(&htab->map);
1385
		bpf_lru_push_free(&htab->lru, &l_new->lru_node);
1386
	}
1387 1388 1389
	return ret;
}

1390 1391
static long htab_percpu_map_update_elem(struct bpf_map *map, void *key,
					void *value, u64 map_flags)
1392 1393 1394 1395
{
	return __htab_percpu_map_update_elem(map, key, value, map_flags, false);
}

1396 1397
static long htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key,
					    void *value, u64 map_flags)
1398 1399 1400 1401 1402
{
	return __htab_lru_percpu_map_update_elem(map, key, value, map_flags,
						 false);
}

1403
/* Called from syscall or from eBPF program */
1404
static long htab_map_delete_elem(struct bpf_map *map, void *key)
1405 1406
{
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1407
	struct hlist_nulls_head *head;
1408
	struct bucket *b;
1409 1410 1411
	struct htab_elem *l;
	unsigned long flags;
	u32 hash, key_size;
1412
	int ret;
1413

1414 1415
	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
		     !rcu_read_lock_bh_held());
1416 1417 1418

	key_size = map->key_size;

1419
	hash = htab_map_hash(key, key_size, htab->hashrnd);
1420 1421
	b = __select_bucket(htab, hash);
	head = &b->head;
1422

1423 1424 1425
	ret = htab_lock_bucket(htab, b, hash, &flags);
	if (ret)
		return ret;
1426 1427 1428 1429

	l = lookup_elem_raw(head, hash, key, key_size);

	if (l) {
1430
		hlist_nulls_del_rcu(&l->hash_node);
1431
		free_htab_elem(htab, l);
1432 1433
	} else {
		ret = -ENOENT;
1434 1435
	}

1436
	htab_unlock_bucket(htab, b, hash, flags);
1437 1438 1439
	return ret;
}

1440
static long htab_lru_map_delete_elem(struct bpf_map *map, void *key)
1441 1442
{
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1443
	struct hlist_nulls_head *head;
1444 1445 1446 1447
	struct bucket *b;
	struct htab_elem *l;
	unsigned long flags;
	u32 hash, key_size;
1448
	int ret;
1449

1450 1451
	WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
		     !rcu_read_lock_bh_held());
1452 1453 1454

	key_size = map->key_size;

1455
	hash = htab_map_hash(key, key_size, htab->hashrnd);
1456 1457 1458
	b = __select_bucket(htab, hash);
	head = &b->head;

1459 1460 1461
	ret = htab_lock_bucket(htab, b, hash, &flags);
	if (ret)
		return ret;
1462 1463 1464

	l = lookup_elem_raw(head, hash, key, key_size);

1465
	if (l)
1466
		hlist_nulls_del_rcu(&l->hash_node);
1467 1468
	else
		ret = -ENOENT;
1469

1470
	htab_unlock_bucket(htab, b, hash, flags);
1471
	if (l)
1472
		htab_lru_push_free(htab, l);
1473 1474 1475
	return ret;
}

1476 1477 1478 1479
static void delete_all_elements(struct bpf_htab *htab)
{
	int i;

1480 1481 1482 1483
	/* It's called from a worker thread, so disable migration here,
	 * since bpf_mem_cache_free() relies on that.
	 */
	migrate_disable();
1484
	for (i = 0; i < htab->n_buckets; i++) {
1485 1486
		struct hlist_nulls_head *head = select_bucket(htab, i);
		struct hlist_nulls_node *n;
1487 1488
		struct htab_elem *l;

1489 1490
		hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
			hlist_nulls_del_rcu(&l->hash_node);
1491
			htab_elem_free(htab, l);
1492
		}
1493
		cond_resched();
1494
	}
1495
	migrate_enable();
1496
}
1497

1498 1499 1500 1501 1502 1503 1504 1505 1506 1507
static void htab_free_malloced_timers(struct bpf_htab *htab)
{
	int i;

	rcu_read_lock();
	for (i = 0; i < htab->n_buckets; i++) {
		struct hlist_nulls_head *head = select_bucket(htab, i);
		struct hlist_nulls_node *n;
		struct htab_elem *l;

1508
		hlist_nulls_for_each_entry(l, n, head, hash_node) {
1509 1510
			/* We only free timer on uref dropping to zero */
			bpf_obj_free_timer(htab->map.record, l->key + round_up(htab->map.key_size, 8));
1511
		}
1512 1513 1514 1515 1516 1517 1518 1519 1520
		cond_resched_rcu();
	}
	rcu_read_unlock();
}

static void htab_map_free_timers(struct bpf_map *map)
{
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);

1521 1522
	/* We only free timer on uref dropping to zero */
	if (!btf_record_has_field(htab->map.record, BPF_TIMER))
1523 1524 1525 1526 1527 1528 1529
		return;
	if (!htab_is_prealloc(htab))
		htab_free_malloced_timers(htab);
	else
		htab_free_prealloced_timers(htab);
}

1530 1531 1532 1533
/* Called when map->refcnt goes to zero, either from workqueue or from syscall */
static void htab_map_free(struct bpf_map *map)
{
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1534
	int i;
1535

1536 1537 1538
	/* bpf_free_used_maps() or close(map_fd) will trigger this map_free callback.
	 * bpf_free_used_maps() is called after bpf prog is no longer executing.
	 * There is no need to synchronize_rcu() here to protect map elements.
1539 1540
	 */

1541 1542 1543
	/* htab no longer uses call_rcu() directly. bpf_mem_alloc does it
	 * underneath and is reponsible for waiting for callbacks to finish
	 * during bpf_mem_alloc_destroy().
1544
	 */
1545
	if (!htab_is_prealloc(htab)) {
1546
		delete_all_elements(htab);
1547
	} else {
1548
		htab_free_prealloced_fields(htab);
1549
		prealloc_destroy(htab);
1550
	}
1551

1552
	bpf_map_free_elem_count(map);
1553
	free_percpu(htab->extra_elems);
1554
	bpf_map_area_free(htab->buckets);
1555
	bpf_mem_alloc_destroy(&htab->pcpu_ma);
1556
	bpf_mem_alloc_destroy(&htab->ma);
1557 1558
	if (htab->use_percpu_counter)
		percpu_counter_destroy(&htab->pcount);
1559 1560
	for (i = 0; i < HASHTAB_MAP_LOCK_COUNT; i++)
		free_percpu(htab->map_locked[i]);
1561
	lockdep_unregister_key(&htab->lockdep_key);
1562
	bpf_map_area_free(htab);
1563 1564
}

1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
static void htab_map_seq_show_elem(struct bpf_map *map, void *key,
				   struct seq_file *m)
{
	void *value;

	rcu_read_lock();

	value = htab_map_lookup_elem(map, key);
	if (!value) {
		rcu_read_unlock();
		return;
	}

	btf_type_seq_show(map->btf, map->btf_key_type_id, key, m);
	seq_puts(m, ": ");
	btf_type_seq_show(map->btf, map->btf_value_type_id, value, m);
	seq_puts(m, "\n");

	rcu_read_unlock();
}

1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
static int __htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
					     void *value, bool is_lru_map,
					     bool is_percpu, u64 flags)
{
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
	struct hlist_nulls_head *head;
	unsigned long bflags;
	struct htab_elem *l;
	u32 hash, key_size;
	struct bucket *b;
	int ret;

	key_size = map->key_size;

	hash = htab_map_hash(key, key_size, htab->hashrnd);
	b = __select_bucket(htab, hash);
	head = &b->head;

	ret = htab_lock_bucket(htab, b, hash, &bflags);
	if (ret)
		return ret;

	l = lookup_elem_raw(head, hash, key, key_size);
	if (!l) {
		ret = -ENOENT;
	} else {
		if (is_percpu) {
			u32 roundup_value_size = round_up(map->value_size, 8);
			void __percpu *pptr;
			int off = 0, cpu;

			pptr = htab_elem_get_ptr(l, key_size);
			for_each_possible_cpu(cpu) {
1619 1620
				copy_map_value_long(&htab->map, value + off, per_cpu_ptr(pptr, cpu));
				check_and_init_map_value(&htab->map, value + off);
1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632
				off += roundup_value_size;
			}
		} else {
			u32 roundup_key_size = round_up(map->key_size, 8);

			if (flags & BPF_F_LOCK)
				copy_map_value_locked(map, value, l->key +
						      roundup_key_size,
						      true);
			else
				copy_map_value(map, value, l->key +
					       roundup_key_size);
1633
			/* Zeroing special fields in the temp buffer */
1634
			check_and_init_map_value(map, value);
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644
		}

		hlist_nulls_del_rcu(&l->hash_node);
		if (!is_lru_map)
			free_htab_elem(htab, l);
	}

	htab_unlock_bucket(htab, b, hash, bflags);

	if (is_lru_map && l)
1645
		htab_lru_push_free(htab, l);
1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679

	return ret;
}

static int htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
					   void *value, u64 flags)
{
	return __htab_map_lookup_and_delete_elem(map, key, value, false, false,
						 flags);
}

static int htab_percpu_map_lookup_and_delete_elem(struct bpf_map *map,
						  void *key, void *value,
						  u64 flags)
{
	return __htab_map_lookup_and_delete_elem(map, key, value, false, true,
						 flags);
}

static int htab_lru_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
					       void *value, u64 flags)
{
	return __htab_map_lookup_and_delete_elem(map, key, value, true, false,
						 flags);
}

static int htab_lru_percpu_map_lookup_and_delete_elem(struct bpf_map *map,
						      void *key, void *value,
						      u64 flags)
{
	return __htab_map_lookup_and_delete_elem(map, key, value, true, true,
						 flags);
}

1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691
static int
__htab_map_lookup_and_delete_batch(struct bpf_map *map,
				   const union bpf_attr *attr,
				   union bpf_attr __user *uattr,
				   bool do_delete, bool is_lru_map,
				   bool is_percpu)
{
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
	u32 bucket_cnt, total, key_size, value_size, roundup_key_size;
	void *keys = NULL, *values = NULL, *value, *dst_key, *dst_val;
	void __user *uvalues = u64_to_user_ptr(attr->batch.values);
	void __user *ukeys = u64_to_user_ptr(attr->batch.keys);
1692
	void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1693
	u32 batch, max_count, size, bucket_size, map_id;
1694
	struct htab_elem *node_to_free = NULL;
1695 1696 1697
	u64 elem_map_flags, map_flags;
	struct hlist_nulls_head *head;
	struct hlist_nulls_node *n;
1698 1699
	unsigned long flags = 0;
	bool locked = false;
1700 1701 1702 1703 1704 1705
	struct htab_elem *l;
	struct bucket *b;
	int ret = 0;

	elem_map_flags = attr->batch.elem_flags;
	if ((elem_map_flags & ~BPF_F_LOCK) ||
1706
	    ((elem_map_flags & BPF_F_LOCK) && !btf_record_has_field(map->record, BPF_SPIN_LOCK)))
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734
		return -EINVAL;

	map_flags = attr->batch.flags;
	if (map_flags)
		return -EINVAL;

	max_count = attr->batch.count;
	if (!max_count)
		return 0;

	if (put_user(0, &uattr->batch.count))
		return -EFAULT;

	batch = 0;
	if (ubatch && copy_from_user(&batch, ubatch, sizeof(batch)))
		return -EFAULT;

	if (batch >= htab->n_buckets)
		return -ENOENT;

	key_size = htab->map.key_size;
	roundup_key_size = round_up(htab->map.key_size, 8);
	value_size = htab->map.value_size;
	size = round_up(value_size, 8);
	if (is_percpu)
		value_size = size * num_possible_cpus();
	total = 0;
	/* while experimenting with hash tables with sizes ranging from 10 to
Tom Rix's avatar
Tom Rix committed
1735
	 * 1000, it was observed that a bucket can have up to 5 entries.
1736 1737 1738 1739 1740 1741 1742
	 */
	bucket_size = 5;

alloc:
	/* We cannot do copy_from_user or copy_to_user inside
	 * the rcu_read_lock. Allocate enough space here.
	 */
1743 1744
	keys = kvmalloc_array(key_size, bucket_size, GFP_USER | __GFP_NOWARN);
	values = kvmalloc_array(value_size, bucket_size, GFP_USER | __GFP_NOWARN);
1745 1746 1747 1748 1749 1750
	if (!keys || !values) {
		ret = -ENOMEM;
		goto after_loop;
	}

again:
1751
	bpf_disable_instrumentation();
1752 1753 1754 1755 1756 1757
	rcu_read_lock();
again_nocopy:
	dst_key = keys;
	dst_val = values;
	b = &htab->buckets[batch];
	head = &b->head;
1758
	/* do not grab the lock unless need it (bucket_cnt > 0). */
1759 1760
	if (locked) {
		ret = htab_lock_bucket(htab, b, batch, &flags);
1761 1762 1763 1764 1765
		if (ret) {
			rcu_read_unlock();
			bpf_enable_instrumentation();
			goto after_loop;
		}
1766
	}
1767 1768 1769 1770 1771

	bucket_cnt = 0;
	hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
		bucket_cnt++;

1772 1773 1774 1775 1776
	if (bucket_cnt && !locked) {
		locked = true;
		goto again_nocopy;
	}

1777 1778 1779
	if (bucket_cnt > (max_count - total)) {
		if (total == 0)
			ret = -ENOSPC;
1780 1781 1782
		/* Note that since bucket_cnt > 0 here, it is implicit
		 * that the locked was grabbed, so release it.
		 */
1783
		htab_unlock_bucket(htab, b, batch, flags);
1784
		rcu_read_unlock();
1785
		bpf_enable_instrumentation();
1786 1787 1788 1789 1790
		goto after_loop;
	}

	if (bucket_cnt > bucket_size) {
		bucket_size = bucket_cnt;
1791 1792 1793
		/* Note that since bucket_cnt > 0 here, it is implicit
		 * that the locked was grabbed, so release it.
		 */
1794
		htab_unlock_bucket(htab, b, batch, flags);
1795
		rcu_read_unlock();
1796
		bpf_enable_instrumentation();
1797 1798 1799 1800 1801
		kvfree(keys);
		kvfree(values);
		goto alloc;
	}

1802 1803 1804 1805
	/* Next block is only safe to run if you have grabbed the lock */
	if (!locked)
		goto next_batch;

1806 1807 1808 1809 1810 1811 1812 1813 1814
	hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
		memcpy(dst_key, l->key, key_size);

		if (is_percpu) {
			int off = 0, cpu;
			void __percpu *pptr;

			pptr = htab_elem_get_ptr(l, map->key_size);
			for_each_possible_cpu(cpu) {
1815 1816
				copy_map_value_long(&htab->map, dst_val + off, per_cpu_ptr(pptr, cpu));
				check_and_init_map_value(&htab->map, dst_val + off);
1817 1818 1819 1820
				off += size;
			}
		} else {
			value = l->key + roundup_key_size;
1821 1822 1823 1824 1825 1826 1827 1828
			if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
				struct bpf_map **inner_map = value;

				 /* Actual value is the id of the inner map */
				map_id = map->ops->map_fd_sys_lookup_elem(*inner_map);
				value = &map_id;
			}

1829 1830 1831 1832 1833
			if (elem_map_flags & BPF_F_LOCK)
				copy_map_value_locked(map, dst_val, value,
						      true);
			else
				copy_map_value(map, dst_val, value);
1834
			/* Zeroing special fields in the temp buffer */
1835
			check_and_init_map_value(map, dst_val);
1836 1837 1838
		}
		if (do_delete) {
			hlist_nulls_del_rcu(&l->hash_node);
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848

			/* bpf_lru_push_free() will acquire lru_lock, which
			 * may cause deadlock. See comments in function
			 * prealloc_lru_pop(). Let us do bpf_lru_push_free()
			 * after releasing the bucket lock.
			 */
			if (is_lru_map) {
				l->batch_flink = node_to_free;
				node_to_free = l;
			} else {
1849
				free_htab_elem(htab, l);
1850
			}
1851 1852 1853 1854 1855
		}
		dst_key += key_size;
		dst_val += value_size;
	}

1856
	htab_unlock_bucket(htab, b, batch, flags);
1857
	locked = false;
1858 1859 1860 1861

	while (node_to_free) {
		l = node_to_free;
		node_to_free = node_to_free->batch_flink;
1862
		htab_lru_push_free(htab, l);
1863 1864
	}

1865
next_batch:
1866 1867 1868 1869 1870 1871 1872 1873 1874
	/* If we are not copying data, we can go to next bucket and avoid
	 * unlocking the rcu.
	 */
	if (!bucket_cnt && (batch + 1 < htab->n_buckets)) {
		batch++;
		goto again_nocopy;
	}

	rcu_read_unlock();
1875
	bpf_enable_instrumentation();
1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
	if (bucket_cnt && (copy_to_user(ukeys + total * key_size, keys,
	    key_size * bucket_cnt) ||
	    copy_to_user(uvalues + total * value_size, values,
	    value_size * bucket_cnt))) {
		ret = -EFAULT;
		goto after_loop;
	}

	total += bucket_cnt;
	batch++;
	if (batch >= htab->n_buckets) {
		ret = -ENOENT;
		goto after_loop;
	}
	goto again;

after_loop:
	if (ret == -EFAULT)
		goto out;

	/* copy # of entries and next batch */
	ubatch = u64_to_user_ptr(attr->batch.out_batch);
	if (copy_to_user(ubatch, &batch, sizeof(batch)) ||
	    put_user(total, &uattr->batch.count))
		ret = -EFAULT;

out:
	kvfree(keys);
	kvfree(values);
	return ret;
}

static int
htab_percpu_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
			     union bpf_attr __user *uattr)
{
	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
						  false, true);
}

static int
htab_percpu_map_lookup_and_delete_batch(struct bpf_map *map,
					const union bpf_attr *attr,
					union bpf_attr __user *uattr)
{
	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
						  false, true);
}

static int
htab_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
		      union bpf_attr __user *uattr)
{
	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
						  false, false);
}

static int
htab_map_lookup_and_delete_batch(struct bpf_map *map,
				 const union bpf_attr *attr,
				 union bpf_attr __user *uattr)
{
	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
						  false, false);
}

static int
htab_lru_percpu_map_lookup_batch(struct bpf_map *map,
				 const union bpf_attr *attr,
				 union bpf_attr __user *uattr)
{
	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
						  true, true);
}

static int
htab_lru_percpu_map_lookup_and_delete_batch(struct bpf_map *map,
					    const union bpf_attr *attr,
					    union bpf_attr __user *uattr)
{
	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
						  true, true);
}

static int
htab_lru_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
			  union bpf_attr __user *uattr)
{
	return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
						  true, false);
}

static int
htab_lru_map_lookup_and_delete_batch(struct bpf_map *map,
				     const union bpf_attr *attr,
				     union bpf_attr __user *uattr)
{
	return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
						  true, false);
}

1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
struct bpf_iter_seq_hash_map_info {
	struct bpf_map *map;
	struct bpf_htab *htab;
	void *percpu_value_buf; // non-zero means percpu hash
	u32 bucket_id;
	u32 skip_elems;
};

static struct htab_elem *
bpf_hash_map_seq_find_next(struct bpf_iter_seq_hash_map_info *info,
			   struct htab_elem *prev_elem)
{
	const struct bpf_htab *htab = info->htab;
	u32 skip_elems = info->skip_elems;
	u32 bucket_id = info->bucket_id;
	struct hlist_nulls_head *head;
	struct hlist_nulls_node *n;
	struct htab_elem *elem;
	struct bucket *b;
	u32 i, count;

	if (bucket_id >= htab->n_buckets)
		return NULL;

	/* try to find next elem in the same bucket */
	if (prev_elem) {
		/* no update/deletion on this bucket, prev_elem should be still valid
		 * and we won't skip elements.
		 */
		n = rcu_dereference_raw(hlist_nulls_next_rcu(&prev_elem->hash_node));
		elem = hlist_nulls_entry_safe(n, struct htab_elem, hash_node);
		if (elem)
			return elem;

		/* not found, unlock and go to the next bucket */
		b = &htab->buckets[bucket_id++];
2013
		rcu_read_unlock();
2014 2015 2016 2017 2018
		skip_elems = 0;
	}

	for (i = bucket_id; i < htab->n_buckets; i++) {
		b = &htab->buckets[i];
2019
		rcu_read_lock();
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031

		count = 0;
		head = &b->head;
		hlist_nulls_for_each_entry_rcu(elem, n, head, hash_node) {
			if (count >= skip_elems) {
				info->bucket_id = i;
				info->skip_elems = count;
				return elem;
			}
			count++;
		}

2032
		rcu_read_unlock();
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
		skip_elems = 0;
	}

	info->bucket_id = i;
	info->skip_elems = 0;
	return NULL;
}

static void *bpf_hash_map_seq_start(struct seq_file *seq, loff_t *pos)
{
	struct bpf_iter_seq_hash_map_info *info = seq->private;
	struct htab_elem *elem;

	elem = bpf_hash_map_seq_find_next(info, NULL);
	if (!elem)
		return NULL;

	if (*pos == 0)
		++*pos;
	return elem;
}

static void *bpf_hash_map_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
	struct bpf_iter_seq_hash_map_info *info = seq->private;

	++*pos;
	++info->skip_elems;
	return bpf_hash_map_seq_find_next(info, v);
}

static int __bpf_hash_map_seq_show(struct seq_file *seq, struct htab_elem *elem)
{
	struct bpf_iter_seq_hash_map_info *info = seq->private;
	u32 roundup_key_size, roundup_value_size;
	struct bpf_iter__bpf_map_elem ctx = {};
	struct bpf_map *map = info->map;
	struct bpf_iter_meta meta;
	int ret = 0, off = 0, cpu;
	struct bpf_prog *prog;
	void __percpu *pptr;

	meta.seq = seq;
	prog = bpf_iter_get_info(&meta, elem == NULL);
	if (prog) {
		ctx.meta = &meta;
		ctx.map = info->map;
		if (elem) {
			roundup_key_size = round_up(map->key_size, 8);
			ctx.key = elem->key;
			if (!info->percpu_value_buf) {
				ctx.value = elem->key + roundup_key_size;
			} else {
				roundup_value_size = round_up(map->value_size, 8);
				pptr = htab_elem_get_ptr(elem, map->key_size);
				for_each_possible_cpu(cpu) {
2089 2090 2091
					copy_map_value_long(map, info->percpu_value_buf + off,
							    per_cpu_ptr(pptr, cpu));
					check_and_init_map_value(map, info->percpu_value_buf + off);
2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
					off += roundup_value_size;
				}
				ctx.value = info->percpu_value_buf;
			}
		}
		ret = bpf_iter_run_prog(prog, &ctx);
	}

	return ret;
}

static int bpf_hash_map_seq_show(struct seq_file *seq, void *v)
{
	return __bpf_hash_map_seq_show(seq, v);
}

static void bpf_hash_map_seq_stop(struct seq_file *seq, void *v)
{
	if (!v)
		(void)__bpf_hash_map_seq_show(seq, NULL);
	else
2113
		rcu_read_unlock();
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133
}

static int bpf_iter_init_hash_map(void *priv_data,
				  struct bpf_iter_aux_info *aux)
{
	struct bpf_iter_seq_hash_map_info *seq_info = priv_data;
	struct bpf_map *map = aux->map;
	void *value_buf;
	u32 buf_size;

	if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
	    map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
		buf_size = round_up(map->value_size, 8) * num_possible_cpus();
		value_buf = kmalloc(buf_size, GFP_USER | __GFP_NOWARN);
		if (!value_buf)
			return -ENOMEM;

		seq_info->percpu_value_buf = value_buf;
	}

2134
	bpf_map_inc_with_uref(map);
2135 2136 2137 2138 2139 2140 2141 2142 2143
	seq_info->map = map;
	seq_info->htab = container_of(map, struct bpf_htab, map);
	return 0;
}

static void bpf_iter_fini_hash_map(void *priv_data)
{
	struct bpf_iter_seq_hash_map_info *seq_info = priv_data;

2144
	bpf_map_put_with_uref(seq_info->map);
2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161
	kfree(seq_info->percpu_value_buf);
}

static const struct seq_operations bpf_hash_map_seq_ops = {
	.start	= bpf_hash_map_seq_start,
	.next	= bpf_hash_map_seq_next,
	.stop	= bpf_hash_map_seq_stop,
	.show	= bpf_hash_map_seq_show,
};

static const struct bpf_iter_seq_info iter_seq_info = {
	.seq_ops		= &bpf_hash_map_seq_ops,
	.init_seq_private	= bpf_iter_init_hash_map,
	.fini_seq_private	= bpf_iter_fini_hash_map,
	.seq_priv_size		= sizeof(struct bpf_iter_seq_hash_map_info),
};

2162 2163
static long bpf_for_each_hash_elem(struct bpf_map *map, bpf_callback_t callback_fn,
				   void *callback_ctx, u64 flags)
2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201
{
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
	struct hlist_nulls_head *head;
	struct hlist_nulls_node *n;
	struct htab_elem *elem;
	u32 roundup_key_size;
	int i, num_elems = 0;
	void __percpu *pptr;
	struct bucket *b;
	void *key, *val;
	bool is_percpu;
	u64 ret = 0;

	if (flags != 0)
		return -EINVAL;

	is_percpu = htab_is_percpu(htab);

	roundup_key_size = round_up(map->key_size, 8);
	/* disable migration so percpu value prepared here will be the
	 * same as the one seen by the bpf program with bpf_map_lookup_elem().
	 */
	if (is_percpu)
		migrate_disable();
	for (i = 0; i < htab->n_buckets; i++) {
		b = &htab->buckets[i];
		rcu_read_lock();
		head = &b->head;
		hlist_nulls_for_each_entry_rcu(elem, n, head, hash_node) {
			key = elem->key;
			if (is_percpu) {
				/* current cpu value for percpu map */
				pptr = htab_elem_get_ptr(elem, map->key_size);
				val = this_cpu_ptr(pptr);
			} else {
				val = elem->key + roundup_key_size;
			}
			num_elems++;
2202 2203
			ret = callback_fn((u64)(long)map, (u64)(long)key,
					  (u64)(long)val, (u64)(long)callback_ctx, 0);
2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217
			/* return value: 0 - continue, 1 - stop and return */
			if (ret) {
				rcu_read_unlock();
				goto out;
			}
		}
		rcu_read_unlock();
	}
out:
	if (is_percpu)
		migrate_enable();
	return num_elems;
}

Yafang Shao's avatar
Yafang Shao committed
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255
static u64 htab_map_mem_usage(const struct bpf_map *map)
{
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
	u32 value_size = round_up(htab->map.value_size, 8);
	bool prealloc = htab_is_prealloc(htab);
	bool percpu = htab_is_percpu(htab);
	bool lru = htab_is_lru(htab);
	u64 num_entries;
	u64 usage = sizeof(struct bpf_htab);

	usage += sizeof(struct bucket) * htab->n_buckets;
	usage += sizeof(int) * num_possible_cpus() * HASHTAB_MAP_LOCK_COUNT;
	if (prealloc) {
		num_entries = map->max_entries;
		if (htab_has_extra_elems(htab))
			num_entries += num_possible_cpus();

		usage += htab->elem_size * num_entries;

		if (percpu)
			usage += value_size * num_possible_cpus() * num_entries;
		else if (!lru)
			usage += sizeof(struct htab_elem *) * num_possible_cpus();
	} else {
#define LLIST_NODE_SZ sizeof(struct llist_node)

		num_entries = htab->use_percpu_counter ?
					  percpu_counter_sum(&htab->pcount) :
					  atomic_read(&htab->count);
		usage += (htab->elem_size + LLIST_NODE_SZ) * num_entries;
		if (percpu) {
			usage += (LLIST_NODE_SZ + sizeof(void *)) * num_entries;
			usage += value_size * num_possible_cpus() * num_entries;
		}
	}
	return usage;
}

2256
BTF_ID_LIST_SINGLE(htab_map_btf_ids, struct, bpf_htab)
2257
const struct bpf_map_ops htab_map_ops = {
2258
	.map_meta_equal = bpf_map_meta_equal,
2259
	.map_alloc_check = htab_map_alloc_check,
2260 2261 2262
	.map_alloc = htab_map_alloc,
	.map_free = htab_map_free,
	.map_get_next_key = htab_map_get_next_key,
2263
	.map_release_uref = htab_map_free_timers,
2264
	.map_lookup_elem = htab_map_lookup_elem,
2265
	.map_lookup_and_delete_elem = htab_map_lookup_and_delete_elem,
2266 2267
	.map_update_elem = htab_map_update_elem,
	.map_delete_elem = htab_map_delete_elem,
2268
	.map_gen_lookup = htab_map_gen_lookup,
2269
	.map_seq_show_elem = htab_map_seq_show_elem,
2270 2271
	.map_set_for_each_callback_args = map_set_for_each_callback_args,
	.map_for_each_callback = bpf_for_each_hash_elem,
Yafang Shao's avatar
Yafang Shao committed
2272
	.map_mem_usage = htab_map_mem_usage,
2273
	BATCH_OPS(htab),
2274
	.map_btf_id = &htab_map_btf_ids[0],
2275
	.iter_seq_info = &iter_seq_info,
2276 2277
};

2278
const struct bpf_map_ops htab_lru_map_ops = {
2279
	.map_meta_equal = bpf_map_meta_equal,
2280
	.map_alloc_check = htab_map_alloc_check,
2281 2282 2283
	.map_alloc = htab_map_alloc,
	.map_free = htab_map_free,
	.map_get_next_key = htab_map_get_next_key,
2284
	.map_release_uref = htab_map_free_timers,
2285
	.map_lookup_elem = htab_lru_map_lookup_elem,
2286
	.map_lookup_and_delete_elem = htab_lru_map_lookup_and_delete_elem,
2287
	.map_lookup_elem_sys_only = htab_lru_map_lookup_elem_sys,
2288 2289
	.map_update_elem = htab_lru_map_update_elem,
	.map_delete_elem = htab_lru_map_delete_elem,
2290
	.map_gen_lookup = htab_lru_map_gen_lookup,
2291
	.map_seq_show_elem = htab_map_seq_show_elem,
2292 2293
	.map_set_for_each_callback_args = map_set_for_each_callback_args,
	.map_for_each_callback = bpf_for_each_hash_elem,
Yafang Shao's avatar
Yafang Shao committed
2294
	.map_mem_usage = htab_map_mem_usage,
2295
	BATCH_OPS(htab_lru),
2296
	.map_btf_id = &htab_map_btf_ids[0],
2297
	.iter_seq_info = &iter_seq_info,
2298 2299
};

2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310
/* Called from eBPF program */
static void *htab_percpu_map_lookup_elem(struct bpf_map *map, void *key)
{
	struct htab_elem *l = __htab_map_lookup_elem(map, key);

	if (l)
		return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size));
	else
		return NULL;
}

2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
/* inline bpf_map_lookup_elem() call for per-CPU hashmap */
static int htab_percpu_map_gen_lookup(struct bpf_map *map, struct bpf_insn *insn_buf)
{
	struct bpf_insn *insn = insn_buf;

	if (!bpf_jit_supports_percpu_insn())
		return -EOPNOTSUPP;

	BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
		     (void *(*)(struct bpf_map *map, void *key))NULL));
	*insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
	*insn++ = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 3);
	*insn++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_0,
				offsetof(struct htab_elem, key) + map->key_size);
	*insn++ = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_0, 0);
	*insn++ = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);

	return insn - insn_buf;
}

2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344
static void *htab_percpu_map_lookup_percpu_elem(struct bpf_map *map, void *key, u32 cpu)
{
	struct htab_elem *l;

	if (cpu >= nr_cpu_ids)
		return NULL;

	l = __htab_map_lookup_elem(map, key);
	if (l)
		return per_cpu_ptr(htab_elem_get_ptr(l, map->key_size), cpu);
	else
		return NULL;
}

2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356
static void *htab_lru_percpu_map_lookup_elem(struct bpf_map *map, void *key)
{
	struct htab_elem *l = __htab_map_lookup_elem(map, key);

	if (l) {
		bpf_lru_node_set_ref(&l->lru_node);
		return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size));
	}

	return NULL;
}

2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372
static void *htab_lru_percpu_map_lookup_percpu_elem(struct bpf_map *map, void *key, u32 cpu)
{
	struct htab_elem *l;

	if (cpu >= nr_cpu_ids)
		return NULL;

	l = __htab_map_lookup_elem(map, key);
	if (l) {
		bpf_lru_node_set_ref(&l->lru_node);
		return per_cpu_ptr(htab_elem_get_ptr(l, map->key_size), cpu);
	}

	return NULL;
}

2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
int bpf_percpu_hash_copy(struct bpf_map *map, void *key, void *value)
{
	struct htab_elem *l;
	void __percpu *pptr;
	int ret = -ENOENT;
	int cpu, off = 0;
	u32 size;

	/* per_cpu areas are zero-filled and bpf programs can only
	 * access 'value_size' of them, so copying rounded areas
	 * will not leak any kernel data
	 */
	size = round_up(map->value_size, 8);
	rcu_read_lock();
	l = __htab_map_lookup_elem(map, key);
	if (!l)
		goto out;
2390 2391 2392
	/* We do not mark LRU map element here in order to not mess up
	 * eviction heuristics when user space does a map walk.
	 */
2393 2394
	pptr = htab_elem_get_ptr(l, map->key_size);
	for_each_possible_cpu(cpu) {
2395 2396
		copy_map_value_long(map, value + off, per_cpu_ptr(pptr, cpu));
		check_and_init_map_value(map, value + off);
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407
		off += size;
	}
	ret = 0;
out:
	rcu_read_unlock();
	return ret;
}

int bpf_percpu_hash_update(struct bpf_map *map, void *key, void *value,
			   u64 map_flags)
{
2408
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2409 2410 2411
	int ret;

	rcu_read_lock();
2412 2413 2414 2415 2416 2417
	if (htab_is_lru(htab))
		ret = __htab_lru_percpu_map_update_elem(map, key, value,
							map_flags, true);
	else
		ret = __htab_percpu_map_update_elem(map, key, value, map_flags,
						    true);
2418 2419 2420
	rcu_read_unlock();

	return ret;
2421 2422
}

2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451
static void htab_percpu_map_seq_show_elem(struct bpf_map *map, void *key,
					  struct seq_file *m)
{
	struct htab_elem *l;
	void __percpu *pptr;
	int cpu;

	rcu_read_lock();

	l = __htab_map_lookup_elem(map, key);
	if (!l) {
		rcu_read_unlock();
		return;
	}

	btf_type_seq_show(map->btf, map->btf_key_type_id, key, m);
	seq_puts(m, ": {\n");
	pptr = htab_elem_get_ptr(l, map->key_size);
	for_each_possible_cpu(cpu) {
		seq_printf(m, "\tcpu%d: ", cpu);
		btf_type_seq_show(map->btf, map->btf_value_type_id,
				  per_cpu_ptr(pptr, cpu), m);
		seq_puts(m, "\n");
	}
	seq_puts(m, "}\n");

	rcu_read_unlock();
}

2452
const struct bpf_map_ops htab_percpu_map_ops = {
2453
	.map_meta_equal = bpf_map_meta_equal,
2454
	.map_alloc_check = htab_map_alloc_check,
2455 2456 2457 2458
	.map_alloc = htab_map_alloc,
	.map_free = htab_map_free,
	.map_get_next_key = htab_map_get_next_key,
	.map_lookup_elem = htab_percpu_map_lookup_elem,
2459
	.map_gen_lookup = htab_percpu_map_gen_lookup,
2460
	.map_lookup_and_delete_elem = htab_percpu_map_lookup_and_delete_elem,
2461 2462
	.map_update_elem = htab_percpu_map_update_elem,
	.map_delete_elem = htab_map_delete_elem,
2463
	.map_lookup_percpu_elem = htab_percpu_map_lookup_percpu_elem,
2464
	.map_seq_show_elem = htab_percpu_map_seq_show_elem,
2465 2466
	.map_set_for_each_callback_args = map_set_for_each_callback_args,
	.map_for_each_callback = bpf_for_each_hash_elem,
Yafang Shao's avatar
Yafang Shao committed
2467
	.map_mem_usage = htab_map_mem_usage,
2468
	BATCH_OPS(htab_percpu),
2469
	.map_btf_id = &htab_map_btf_ids[0],
2470
	.iter_seq_info = &iter_seq_info,
2471 2472
};

2473
const struct bpf_map_ops htab_lru_percpu_map_ops = {
2474
	.map_meta_equal = bpf_map_meta_equal,
2475
	.map_alloc_check = htab_map_alloc_check,
2476 2477 2478 2479
	.map_alloc = htab_map_alloc,
	.map_free = htab_map_free,
	.map_get_next_key = htab_map_get_next_key,
	.map_lookup_elem = htab_lru_percpu_map_lookup_elem,
2480
	.map_lookup_and_delete_elem = htab_lru_percpu_map_lookup_and_delete_elem,
2481 2482
	.map_update_elem = htab_lru_percpu_map_update_elem,
	.map_delete_elem = htab_lru_map_delete_elem,
2483
	.map_lookup_percpu_elem = htab_lru_percpu_map_lookup_percpu_elem,
2484
	.map_seq_show_elem = htab_percpu_map_seq_show_elem,
2485 2486
	.map_set_for_each_callback_args = map_set_for_each_callback_args,
	.map_for_each_callback = bpf_for_each_hash_elem,
Yafang Shao's avatar
Yafang Shao committed
2487
	.map_mem_usage = htab_map_mem_usage,
2488
	BATCH_OPS(htab_lru_percpu),
2489
	.map_btf_id = &htab_map_btf_ids[0],
2490
	.iter_seq_info = &iter_seq_info,
2491 2492
};

2493
static int fd_htab_map_alloc_check(union bpf_attr *attr)
2494 2495
{
	if (attr->value_size != sizeof(u32))
2496 2497
		return -EINVAL;
	return htab_map_alloc_check(attr);
2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513
}

static void fd_htab_map_free(struct bpf_map *map)
{
	struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
	struct hlist_nulls_node *n;
	struct hlist_nulls_head *head;
	struct htab_elem *l;
	int i;

	for (i = 0; i < htab->n_buckets; i++) {
		head = select_bucket(htab, i);

		hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
			void *ptr = fd_htab_map_get_ptr(map, l);

2514
			map->ops->map_fd_put_ptr(map, ptr, false);
2515 2516 2517 2518 2519 2520
		}
	}

	htab_map_free(map);
}

2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
/* only called from syscall */
int bpf_fd_htab_map_lookup_elem(struct bpf_map *map, void *key, u32 *value)
{
	void **ptr;
	int ret = 0;

	if (!map->ops->map_fd_sys_lookup_elem)
		return -ENOTSUPP;

	rcu_read_lock();
	ptr = htab_map_lookup_elem(map, key);
	if (ptr)
		*value = map->ops->map_fd_sys_lookup_elem(READ_ONCE(*ptr));
	else
		ret = -ENOENT;
	rcu_read_unlock();

	return ret;
}

2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552
/* only called from syscall */
int bpf_fd_htab_map_update_elem(struct bpf_map *map, struct file *map_file,
				void *key, void *value, u64 map_flags)
{
	void *ptr;
	int ret;
	u32 ufd = *(u32 *)value;

	ptr = map->ops->map_fd_get_ptr(map, map_file, ufd);
	if (IS_ERR(ptr))
		return PTR_ERR(ptr);

2553 2554 2555 2556 2557
	/* The htab bucket lock is always held during update operations in fd
	 * htab map, and the following rcu_read_lock() is only used to avoid
	 * the WARN_ON_ONCE in htab_map_update_elem().
	 */
	rcu_read_lock();
2558
	ret = htab_map_update_elem(map, key, &ptr, map_flags);
2559
	rcu_read_unlock();
2560
	if (ret)
2561
		map->ops->map_fd_put_ptr(map, ptr, false);
2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573

	return ret;
}

static struct bpf_map *htab_of_map_alloc(union bpf_attr *attr)
{
	struct bpf_map *map, *inner_map_meta;

	inner_map_meta = bpf_map_meta_alloc(attr->inner_map_fd);
	if (IS_ERR(inner_map_meta))
		return inner_map_meta;

2574
	map = htab_map_alloc(attr);
2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594
	if (IS_ERR(map)) {
		bpf_map_meta_free(inner_map_meta);
		return map;
	}

	map->inner_map_meta = inner_map_meta;

	return map;
}

static void *htab_of_map_lookup_elem(struct bpf_map *map, void *key)
{
	struct bpf_map **inner_map  = htab_map_lookup_elem(map, key);

	if (!inner_map)
		return NULL;

	return READ_ONCE(*inner_map);
}

2595
static int htab_of_map_gen_lookup(struct bpf_map *map,
2596 2597 2598 2599 2600
				  struct bpf_insn *insn_buf)
{
	struct bpf_insn *insn = insn_buf;
	const int ret = BPF_REG_0;

2601 2602
	BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
		     (void *(*)(struct bpf_map *map, void *key))NULL));
2603
	*insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
2604 2605 2606 2607 2608 2609 2610 2611 2612
	*insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 2);
	*insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
				offsetof(struct htab_elem, key) +
				round_up(map->key_size, 8));
	*insn++ = BPF_LDX_MEM(BPF_DW, ret, ret, 0);

	return insn - insn_buf;
}

2613 2614 2615 2616 2617 2618
static void htab_of_map_free(struct bpf_map *map)
{
	bpf_map_meta_free(map->inner_map_meta);
	fd_htab_map_free(map);
}

2619
const struct bpf_map_ops htab_of_maps_map_ops = {
2620
	.map_alloc_check = fd_htab_map_alloc_check,
2621 2622 2623 2624 2625 2626 2627
	.map_alloc = htab_of_map_alloc,
	.map_free = htab_of_map_free,
	.map_get_next_key = htab_map_get_next_key,
	.map_lookup_elem = htab_of_map_lookup_elem,
	.map_delete_elem = htab_map_delete_elem,
	.map_fd_get_ptr = bpf_map_fd_get_ptr,
	.map_fd_put_ptr = bpf_map_fd_put_ptr,
2628
	.map_fd_sys_lookup_elem = bpf_map_fd_sys_lookup_elem,
2629
	.map_gen_lookup = htab_of_map_gen_lookup,
2630
	.map_check_btf = map_check_no_btf,
Yafang Shao's avatar
Yafang Shao committed
2631
	.map_mem_usage = htab_map_mem_usage,
2632
	BATCH_OPS(htab),
2633
	.map_btf_id = &htab_map_btf_ids[0],
2634
};