bpf: Optimize element count in non-preallocated hash map.
[platform/kernel/linux-starfive.git] / kernel / bpf / hashtab.c
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 #include <linux/jhash.h>
8 #include <linux/filter.h>
9 #include <linux/rculist_nulls.h>
10 #include <linux/random.h>
11 #include <uapi/linux/btf.h>
12 #include <linux/rcupdate_trace.h>
13 #include <linux/btf_ids.h>
14 #include "percpu_freelist.h"
15 #include "bpf_lru_list.h"
16 #include "map_in_map.h"
17 #include <linux/bpf_mem_alloc.h>
18
19 #define HTAB_CREATE_FLAG_MASK                                           \
20         (BPF_F_NO_PREALLOC | BPF_F_NO_COMMON_LRU | BPF_F_NUMA_NODE |    \
21          BPF_F_ACCESS_MASK | BPF_F_ZERO_SEED)
22
23 #define BATCH_OPS(_name)                        \
24         .map_lookup_batch =                     \
25         _name##_map_lookup_batch,               \
26         .map_lookup_and_delete_batch =          \
27         _name##_map_lookup_and_delete_batch,    \
28         .map_update_batch =                     \
29         generic_map_update_batch,               \
30         .map_delete_batch =                     \
31         generic_map_delete_batch
32
33 /*
34  * The bucket lock has two protection scopes:
35  *
36  * 1) Serializing concurrent operations from BPF programs on different
37  *    CPUs
38  *
39  * 2) Serializing concurrent operations from BPF programs and sys_bpf()
40  *
41  * BPF programs can execute in any context including perf, kprobes and
42  * tracing. As there are almost no limits where perf, kprobes and tracing
43  * can be invoked from the lock operations need to be protected against
44  * deadlocks. Deadlocks can be caused by recursion and by an invocation in
45  * the lock held section when functions which acquire this lock are invoked
46  * from sys_bpf(). BPF recursion is prevented by incrementing the per CPU
47  * variable bpf_prog_active, which prevents BPF programs attached to perf
48  * events, kprobes and tracing to be invoked before the prior invocation
49  * from one of these contexts completed. sys_bpf() uses the same mechanism
50  * by pinning the task to the current CPU and incrementing the recursion
51  * protection across the map operation.
52  *
53  * This has subtle implications on PREEMPT_RT. PREEMPT_RT forbids certain
54  * operations like memory allocations (even with GFP_ATOMIC) from atomic
55  * contexts. This is required because even with GFP_ATOMIC the memory
56  * allocator calls into code paths which acquire locks with long held lock
57  * sections. To ensure the deterministic behaviour these locks are regular
58  * spinlocks, which are converted to 'sleepable' spinlocks on RT. The only
59  * true atomic contexts on an RT kernel are the low level hardware
60  * handling, scheduling, low level interrupt handling, NMIs etc. None of
61  * these contexts should ever do memory allocations.
62  *
63  * As regular device interrupt handlers and soft interrupts are forced into
64  * thread context, the existing code which does
65  *   spin_lock*(); alloc(GFP_ATOMIC); spin_unlock*();
66  * just works.
67  *
68  * In theory the BPF locks could be converted to regular spinlocks as well,
69  * but the bucket locks and percpu_freelist locks can be taken from
70  * arbitrary contexts (perf, kprobes, tracepoints) which are required to be
71  * atomic contexts even on RT. These mechanisms require preallocated maps,
72  * so there is no need to invoke memory allocations within the lock held
73  * sections.
74  *
75  * BPF maps which need dynamic allocation are only used from (forced)
76  * thread context on RT and can therefore use regular spinlocks which in
77  * turn allows to invoke memory allocations from the lock held section.
78  *
79  * On a non RT kernel this distinction is neither possible nor required.
80  * spinlock maps to raw_spinlock and the extra code is optimized out by the
81  * compiler.
82  */
83 struct bucket {
84         struct hlist_nulls_head head;
85         union {
86                 raw_spinlock_t raw_lock;
87                 spinlock_t     lock;
88         };
89 };
90
91 #define HASHTAB_MAP_LOCK_COUNT 8
92 #define HASHTAB_MAP_LOCK_MASK (HASHTAB_MAP_LOCK_COUNT - 1)
93
94 struct bpf_htab {
95         struct bpf_map map;
96         struct bpf_mem_alloc ma;
97         struct bucket *buckets;
98         void *elems;
99         union {
100                 struct pcpu_freelist freelist;
101                 struct bpf_lru lru;
102         };
103         struct htab_elem *__percpu *extra_elems;
104         /* number of elements in non-preallocated hashtable are kept
105          * in either pcount or count
106          */
107         struct percpu_counter pcount;
108         atomic_t count;
109         bool use_percpu_counter;
110         u32 n_buckets;  /* number of hash buckets */
111         u32 elem_size;  /* size of each element in bytes */
112         u32 hashrnd;
113         struct lock_class_key lockdep_key;
114         int __percpu *map_locked[HASHTAB_MAP_LOCK_COUNT];
115 };
116
117 /* each htab element is struct htab_elem + key + value */
118 struct htab_elem {
119         union {
120                 struct hlist_nulls_node hash_node;
121                 struct {
122                         void *padding;
123                         union {
124                                 struct bpf_htab *htab;
125                                 struct pcpu_freelist_node fnode;
126                                 struct htab_elem *batch_flink;
127                         };
128                 };
129         };
130         union {
131                 struct rcu_head rcu;
132                 struct bpf_lru_node lru_node;
133         };
134         u32 hash;
135         char key[] __aligned(8);
136 };
137
138 static inline bool htab_is_prealloc(const struct bpf_htab *htab)
139 {
140         return !(htab->map.map_flags & BPF_F_NO_PREALLOC);
141 }
142
143 static inline bool htab_use_raw_lock(const struct bpf_htab *htab)
144 {
145         return (!IS_ENABLED(CONFIG_PREEMPT_RT) || htab_is_prealloc(htab));
146 }
147
148 static void htab_init_buckets(struct bpf_htab *htab)
149 {
150         unsigned int i;
151
152         for (i = 0; i < htab->n_buckets; i++) {
153                 INIT_HLIST_NULLS_HEAD(&htab->buckets[i].head, i);
154                 if (htab_use_raw_lock(htab)) {
155                         raw_spin_lock_init(&htab->buckets[i].raw_lock);
156                         lockdep_set_class(&htab->buckets[i].raw_lock,
157                                           &htab->lockdep_key);
158                 } else {
159                         spin_lock_init(&htab->buckets[i].lock);
160                         lockdep_set_class(&htab->buckets[i].lock,
161                                           &htab->lockdep_key);
162                 }
163                 cond_resched();
164         }
165 }
166
167 static inline int htab_lock_bucket(const struct bpf_htab *htab,
168                                    struct bucket *b, u32 hash,
169                                    unsigned long *pflags)
170 {
171         unsigned long flags;
172         bool use_raw_lock;
173
174         hash = hash & HASHTAB_MAP_LOCK_MASK;
175
176         use_raw_lock = htab_use_raw_lock(htab);
177         if (use_raw_lock)
178                 preempt_disable();
179         else
180                 migrate_disable();
181         if (unlikely(__this_cpu_inc_return(*(htab->map_locked[hash])) != 1)) {
182                 __this_cpu_dec(*(htab->map_locked[hash]));
183                 if (use_raw_lock)
184                         preempt_enable();
185                 else
186                         migrate_enable();
187                 return -EBUSY;
188         }
189
190         if (use_raw_lock)
191                 raw_spin_lock_irqsave(&b->raw_lock, flags);
192         else
193                 spin_lock_irqsave(&b->lock, flags);
194         *pflags = flags;
195
196         return 0;
197 }
198
199 static inline void htab_unlock_bucket(const struct bpf_htab *htab,
200                                       struct bucket *b, u32 hash,
201                                       unsigned long flags)
202 {
203         bool use_raw_lock = htab_use_raw_lock(htab);
204
205         hash = hash & HASHTAB_MAP_LOCK_MASK;
206         if (use_raw_lock)
207                 raw_spin_unlock_irqrestore(&b->raw_lock, flags);
208         else
209                 spin_unlock_irqrestore(&b->lock, flags);
210         __this_cpu_dec(*(htab->map_locked[hash]));
211         if (use_raw_lock)
212                 preempt_enable();
213         else
214                 migrate_enable();
215 }
216
217 static bool htab_lru_map_delete_node(void *arg, struct bpf_lru_node *node);
218
219 static bool htab_is_lru(const struct bpf_htab *htab)
220 {
221         return htab->map.map_type == BPF_MAP_TYPE_LRU_HASH ||
222                 htab->map.map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH;
223 }
224
225 static bool htab_is_percpu(const struct bpf_htab *htab)
226 {
227         return htab->map.map_type == BPF_MAP_TYPE_PERCPU_HASH ||
228                 htab->map.map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH;
229 }
230
231 static inline void htab_elem_set_ptr(struct htab_elem *l, u32 key_size,
232                                      void __percpu *pptr)
233 {
234         *(void __percpu **)(l->key + key_size) = pptr;
235 }
236
237 static inline void __percpu *htab_elem_get_ptr(struct htab_elem *l, u32 key_size)
238 {
239         return *(void __percpu **)(l->key + key_size);
240 }
241
242 static void *fd_htab_map_get_ptr(const struct bpf_map *map, struct htab_elem *l)
243 {
244         return *(void **)(l->key + roundup(map->key_size, 8));
245 }
246
247 static struct htab_elem *get_htab_elem(struct bpf_htab *htab, int i)
248 {
249         return (struct htab_elem *) (htab->elems + i * (u64)htab->elem_size);
250 }
251
252 static bool htab_has_extra_elems(struct bpf_htab *htab)
253 {
254         return !htab_is_percpu(htab) && !htab_is_lru(htab);
255 }
256
257 static void htab_free_prealloced_timers(struct bpf_htab *htab)
258 {
259         u32 num_entries = htab->map.max_entries;
260         int i;
261
262         if (!map_value_has_timer(&htab->map))
263                 return;
264         if (htab_has_extra_elems(htab))
265                 num_entries += num_possible_cpus();
266
267         for (i = 0; i < num_entries; i++) {
268                 struct htab_elem *elem;
269
270                 elem = get_htab_elem(htab, i);
271                 bpf_timer_cancel_and_free(elem->key +
272                                           round_up(htab->map.key_size, 8) +
273                                           htab->map.timer_off);
274                 cond_resched();
275         }
276 }
277
278 static void htab_free_prealloced_kptrs(struct bpf_htab *htab)
279 {
280         u32 num_entries = htab->map.max_entries;
281         int i;
282
283         if (!map_value_has_kptrs(&htab->map))
284                 return;
285         if (htab_has_extra_elems(htab))
286                 num_entries += num_possible_cpus();
287
288         for (i = 0; i < num_entries; i++) {
289                 struct htab_elem *elem;
290
291                 elem = get_htab_elem(htab, i);
292                 bpf_map_free_kptrs(&htab->map, elem->key + round_up(htab->map.key_size, 8));
293                 cond_resched();
294         }
295 }
296
297 static void htab_free_elems(struct bpf_htab *htab)
298 {
299         int i;
300
301         if (!htab_is_percpu(htab))
302                 goto free_elems;
303
304         for (i = 0; i < htab->map.max_entries; i++) {
305                 void __percpu *pptr;
306
307                 pptr = htab_elem_get_ptr(get_htab_elem(htab, i),
308                                          htab->map.key_size);
309                 free_percpu(pptr);
310                 cond_resched();
311         }
312 free_elems:
313         bpf_map_area_free(htab->elems);
314 }
315
316 /* The LRU list has a lock (lru_lock). Each htab bucket has a lock
317  * (bucket_lock). If both locks need to be acquired together, the lock
318  * order is always lru_lock -> bucket_lock and this only happens in
319  * bpf_lru_list.c logic. For example, certain code path of
320  * bpf_lru_pop_free(), which is called by function prealloc_lru_pop(),
321  * will acquire lru_lock first followed by acquiring bucket_lock.
322  *
323  * In hashtab.c, to avoid deadlock, lock acquisition of
324  * bucket_lock followed by lru_lock is not allowed. In such cases,
325  * bucket_lock needs to be released first before acquiring lru_lock.
326  */
327 static struct htab_elem *prealloc_lru_pop(struct bpf_htab *htab, void *key,
328                                           u32 hash)
329 {
330         struct bpf_lru_node *node = bpf_lru_pop_free(&htab->lru, hash);
331         struct htab_elem *l;
332
333         if (node) {
334                 l = container_of(node, struct htab_elem, lru_node);
335                 memcpy(l->key, key, htab->map.key_size);
336                 return l;
337         }
338
339         return NULL;
340 }
341
342 static int prealloc_init(struct bpf_htab *htab)
343 {
344         u32 num_entries = htab->map.max_entries;
345         int err = -ENOMEM, i;
346
347         if (htab_has_extra_elems(htab))
348                 num_entries += num_possible_cpus();
349
350         htab->elems = bpf_map_area_alloc((u64)htab->elem_size * num_entries,
351                                          htab->map.numa_node);
352         if (!htab->elems)
353                 return -ENOMEM;
354
355         if (!htab_is_percpu(htab))
356                 goto skip_percpu_elems;
357
358         for (i = 0; i < num_entries; i++) {
359                 u32 size = round_up(htab->map.value_size, 8);
360                 void __percpu *pptr;
361
362                 pptr = bpf_map_alloc_percpu(&htab->map, size, 8,
363                                             GFP_USER | __GFP_NOWARN);
364                 if (!pptr)
365                         goto free_elems;
366                 htab_elem_set_ptr(get_htab_elem(htab, i), htab->map.key_size,
367                                   pptr);
368                 cond_resched();
369         }
370
371 skip_percpu_elems:
372         if (htab_is_lru(htab))
373                 err = bpf_lru_init(&htab->lru,
374                                    htab->map.map_flags & BPF_F_NO_COMMON_LRU,
375                                    offsetof(struct htab_elem, hash) -
376                                    offsetof(struct htab_elem, lru_node),
377                                    htab_lru_map_delete_node,
378                                    htab);
379         else
380                 err = pcpu_freelist_init(&htab->freelist);
381
382         if (err)
383                 goto free_elems;
384
385         if (htab_is_lru(htab))
386                 bpf_lru_populate(&htab->lru, htab->elems,
387                                  offsetof(struct htab_elem, lru_node),
388                                  htab->elem_size, num_entries);
389         else
390                 pcpu_freelist_populate(&htab->freelist,
391                                        htab->elems + offsetof(struct htab_elem, fnode),
392                                        htab->elem_size, num_entries);
393
394         return 0;
395
396 free_elems:
397         htab_free_elems(htab);
398         return err;
399 }
400
401 static void prealloc_destroy(struct bpf_htab *htab)
402 {
403         htab_free_elems(htab);
404
405         if (htab_is_lru(htab))
406                 bpf_lru_destroy(&htab->lru);
407         else
408                 pcpu_freelist_destroy(&htab->freelist);
409 }
410
411 static int alloc_extra_elems(struct bpf_htab *htab)
412 {
413         struct htab_elem *__percpu *pptr, *l_new;
414         struct pcpu_freelist_node *l;
415         int cpu;
416
417         pptr = bpf_map_alloc_percpu(&htab->map, sizeof(struct htab_elem *), 8,
418                                     GFP_USER | __GFP_NOWARN);
419         if (!pptr)
420                 return -ENOMEM;
421
422         for_each_possible_cpu(cpu) {
423                 l = pcpu_freelist_pop(&htab->freelist);
424                 /* pop will succeed, since prealloc_init()
425                  * preallocated extra num_possible_cpus elements
426                  */
427                 l_new = container_of(l, struct htab_elem, fnode);
428                 *per_cpu_ptr(pptr, cpu) = l_new;
429         }
430         htab->extra_elems = pptr;
431         return 0;
432 }
433
434 /* Called from syscall */
435 static int htab_map_alloc_check(union bpf_attr *attr)
436 {
437         bool percpu = (attr->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
438                        attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);
439         bool lru = (attr->map_type == BPF_MAP_TYPE_LRU_HASH ||
440                     attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);
441         /* percpu_lru means each cpu has its own LRU list.
442          * it is different from BPF_MAP_TYPE_PERCPU_HASH where
443          * the map's value itself is percpu.  percpu_lru has
444          * nothing to do with the map's value.
445          */
446         bool percpu_lru = (attr->map_flags & BPF_F_NO_COMMON_LRU);
447         bool prealloc = !(attr->map_flags & BPF_F_NO_PREALLOC);
448         bool zero_seed = (attr->map_flags & BPF_F_ZERO_SEED);
449         int numa_node = bpf_map_attr_numa_node(attr);
450
451         BUILD_BUG_ON(offsetof(struct htab_elem, htab) !=
452                      offsetof(struct htab_elem, hash_node.pprev));
453         BUILD_BUG_ON(offsetof(struct htab_elem, fnode.next) !=
454                      offsetof(struct htab_elem, hash_node.pprev));
455
456         if (lru && !bpf_capable())
457                 /* LRU implementation is much complicated than other
458                  * maps.  Hence, limit to CAP_BPF.
459                  */
460                 return -EPERM;
461
462         if (zero_seed && !capable(CAP_SYS_ADMIN))
463                 /* Guard against local DoS, and discourage production use. */
464                 return -EPERM;
465
466         if (attr->map_flags & ~HTAB_CREATE_FLAG_MASK ||
467             !bpf_map_flags_access_ok(attr->map_flags))
468                 return -EINVAL;
469
470         if (!lru && percpu_lru)
471                 return -EINVAL;
472
473         if (lru && !prealloc)
474                 return -ENOTSUPP;
475
476         if (numa_node != NUMA_NO_NODE && (percpu || percpu_lru))
477                 return -EINVAL;
478
479         /* check sanity of attributes.
480          * value_size == 0 may be allowed in the future to use map as a set
481          */
482         if (attr->max_entries == 0 || attr->key_size == 0 ||
483             attr->value_size == 0)
484                 return -EINVAL;
485
486         if ((u64)attr->key_size + attr->value_size >= KMALLOC_MAX_SIZE -
487            sizeof(struct htab_elem))
488                 /* if key_size + value_size is bigger, the user space won't be
489                  * able to access the elements via bpf syscall. This check
490                  * also makes sure that the elem_size doesn't overflow and it's
491                  * kmalloc-able later in htab_map_update_elem()
492                  */
493                 return -E2BIG;
494
495         return 0;
496 }
497
498 static struct bpf_map *htab_map_alloc(union bpf_attr *attr)
499 {
500         bool percpu = (attr->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
501                        attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);
502         bool lru = (attr->map_type == BPF_MAP_TYPE_LRU_HASH ||
503                     attr->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH);
504         /* percpu_lru means each cpu has its own LRU list.
505          * it is different from BPF_MAP_TYPE_PERCPU_HASH where
506          * the map's value itself is percpu.  percpu_lru has
507          * nothing to do with the map's value.
508          */
509         bool percpu_lru = (attr->map_flags & BPF_F_NO_COMMON_LRU);
510         bool prealloc = !(attr->map_flags & BPF_F_NO_PREALLOC);
511         struct bpf_htab *htab;
512         int err, i;
513
514         htab = bpf_map_area_alloc(sizeof(*htab), NUMA_NO_NODE);
515         if (!htab)
516                 return ERR_PTR(-ENOMEM);
517
518         lockdep_register_key(&htab->lockdep_key);
519
520         bpf_map_init_from_attr(&htab->map, attr);
521
522         if (percpu_lru) {
523                 /* ensure each CPU's lru list has >=1 elements.
524                  * since we are at it, make each lru list has the same
525                  * number of elements.
526                  */
527                 htab->map.max_entries = roundup(attr->max_entries,
528                                                 num_possible_cpus());
529                 if (htab->map.max_entries < attr->max_entries)
530                         htab->map.max_entries = rounddown(attr->max_entries,
531                                                           num_possible_cpus());
532         }
533
534         /* hash table size must be power of 2 */
535         htab->n_buckets = roundup_pow_of_two(htab->map.max_entries);
536
537         htab->elem_size = sizeof(struct htab_elem) +
538                           round_up(htab->map.key_size, 8);
539         if (percpu)
540                 htab->elem_size += sizeof(void *);
541         else
542                 htab->elem_size += round_up(htab->map.value_size, 8);
543
544         err = -E2BIG;
545         /* prevent zero size kmalloc and check for u32 overflow */
546         if (htab->n_buckets == 0 ||
547             htab->n_buckets > U32_MAX / sizeof(struct bucket))
548                 goto free_htab;
549
550         err = -ENOMEM;
551         htab->buckets = bpf_map_area_alloc(htab->n_buckets *
552                                            sizeof(struct bucket),
553                                            htab->map.numa_node);
554         if (!htab->buckets)
555                 goto free_htab;
556
557         for (i = 0; i < HASHTAB_MAP_LOCK_COUNT; i++) {
558                 htab->map_locked[i] = bpf_map_alloc_percpu(&htab->map,
559                                                            sizeof(int),
560                                                            sizeof(int),
561                                                            GFP_USER);
562                 if (!htab->map_locked[i])
563                         goto free_map_locked;
564         }
565
566         if (htab->map.map_flags & BPF_F_ZERO_SEED)
567                 htab->hashrnd = 0;
568         else
569                 htab->hashrnd = get_random_int();
570
571         htab_init_buckets(htab);
572
573 /* compute_batch_value() computes batch value as num_online_cpus() * 2
574  * and __percpu_counter_compare() needs
575  * htab->max_entries - cur_number_of_elems to be more than batch * num_online_cpus()
576  * for percpu_counter to be faster than atomic_t. In practice the average bpf
577  * hash map size is 10k, which means that a system with 64 cpus will fill
578  * hashmap to 20% of 10k before percpu_counter becomes ineffective. Therefore
579  * define our own batch count as 32 then 10k hash map can be filled up to 80%:
580  * 10k - 8k > 32 _batch_ * 64 _cpus_
581  * and __percpu_counter_compare() will still be fast. At that point hash map
582  * collisions will dominate its performance anyway. Assume that hash map filled
583  * to 50+% isn't going to be O(1) and use the following formula to choose
584  * between percpu_counter and atomic_t.
585  */
586 #define PERCPU_COUNTER_BATCH 32
587         if (attr->max_entries / 2 > num_online_cpus() * PERCPU_COUNTER_BATCH)
588                 htab->use_percpu_counter = true;
589
590         if (htab->use_percpu_counter) {
591                 err = percpu_counter_init(&htab->pcount, 0, GFP_KERNEL);
592                 if (err)
593                         goto free_map_locked;
594         }
595
596         if (prealloc) {
597                 err = prealloc_init(htab);
598                 if (err)
599                         goto free_map_locked;
600
601                 if (!percpu && !lru) {
602                         /* lru itself can remove the least used element, so
603                          * there is no need for an extra elem during map_update.
604                          */
605                         err = alloc_extra_elems(htab);
606                         if (err)
607                                 goto free_prealloc;
608                 }
609         } else {
610                 err = bpf_mem_alloc_init(&htab->ma, htab->elem_size);
611                 if (err)
612                         goto free_map_locked;
613         }
614
615         return &htab->map;
616
617 free_prealloc:
618         prealloc_destroy(htab);
619 free_map_locked:
620         for (i = 0; i < HASHTAB_MAP_LOCK_COUNT; i++)
621                 free_percpu(htab->map_locked[i]);
622         bpf_map_area_free(htab->buckets);
623         bpf_mem_alloc_destroy(&htab->ma);
624 free_htab:
625         lockdep_unregister_key(&htab->lockdep_key);
626         bpf_map_area_free(htab);
627         return ERR_PTR(err);
628 }
629
630 static inline u32 htab_map_hash(const void *key, u32 key_len, u32 hashrnd)
631 {
632         return jhash(key, key_len, hashrnd);
633 }
634
635 static inline struct bucket *__select_bucket(struct bpf_htab *htab, u32 hash)
636 {
637         return &htab->buckets[hash & (htab->n_buckets - 1)];
638 }
639
640 static inline struct hlist_nulls_head *select_bucket(struct bpf_htab *htab, u32 hash)
641 {
642         return &__select_bucket(htab, hash)->head;
643 }
644
645 /* this lookup function can only be called with bucket lock taken */
646 static struct htab_elem *lookup_elem_raw(struct hlist_nulls_head *head, u32 hash,
647                                          void *key, u32 key_size)
648 {
649         struct hlist_nulls_node *n;
650         struct htab_elem *l;
651
652         hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
653                 if (l->hash == hash && !memcmp(&l->key, key, key_size))
654                         return l;
655
656         return NULL;
657 }
658
659 /* can be called without bucket lock. it will repeat the loop in
660  * the unlikely event when elements moved from one bucket into another
661  * while link list is being walked
662  */
663 static struct htab_elem *lookup_nulls_elem_raw(struct hlist_nulls_head *head,
664                                                u32 hash, void *key,
665                                                u32 key_size, u32 n_buckets)
666 {
667         struct hlist_nulls_node *n;
668         struct htab_elem *l;
669
670 again:
671         hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
672                 if (l->hash == hash && !memcmp(&l->key, key, key_size))
673                         return l;
674
675         if (unlikely(get_nulls_value(n) != (hash & (n_buckets - 1))))
676                 goto again;
677
678         return NULL;
679 }
680
681 /* Called from syscall or from eBPF program directly, so
682  * arguments have to match bpf_map_lookup_elem() exactly.
683  * The return value is adjusted by BPF instructions
684  * in htab_map_gen_lookup().
685  */
686 static void *__htab_map_lookup_elem(struct bpf_map *map, void *key)
687 {
688         struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
689         struct hlist_nulls_head *head;
690         struct htab_elem *l;
691         u32 hash, key_size;
692
693         WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
694                      !rcu_read_lock_bh_held());
695
696         key_size = map->key_size;
697
698         hash = htab_map_hash(key, key_size, htab->hashrnd);
699
700         head = select_bucket(htab, hash);
701
702         l = lookup_nulls_elem_raw(head, hash, key, key_size, htab->n_buckets);
703
704         return l;
705 }
706
707 static void *htab_map_lookup_elem(struct bpf_map *map, void *key)
708 {
709         struct htab_elem *l = __htab_map_lookup_elem(map, key);
710
711         if (l)
712                 return l->key + round_up(map->key_size, 8);
713
714         return NULL;
715 }
716
717 /* inline bpf_map_lookup_elem() call.
718  * Instead of:
719  * bpf_prog
720  *   bpf_map_lookup_elem
721  *     map->ops->map_lookup_elem
722  *       htab_map_lookup_elem
723  *         __htab_map_lookup_elem
724  * do:
725  * bpf_prog
726  *   __htab_map_lookup_elem
727  */
728 static int htab_map_gen_lookup(struct bpf_map *map, struct bpf_insn *insn_buf)
729 {
730         struct bpf_insn *insn = insn_buf;
731         const int ret = BPF_REG_0;
732
733         BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
734                      (void *(*)(struct bpf_map *map, void *key))NULL));
735         *insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
736         *insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 1);
737         *insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
738                                 offsetof(struct htab_elem, key) +
739                                 round_up(map->key_size, 8));
740         return insn - insn_buf;
741 }
742
743 static __always_inline void *__htab_lru_map_lookup_elem(struct bpf_map *map,
744                                                         void *key, const bool mark)
745 {
746         struct htab_elem *l = __htab_map_lookup_elem(map, key);
747
748         if (l) {
749                 if (mark)
750                         bpf_lru_node_set_ref(&l->lru_node);
751                 return l->key + round_up(map->key_size, 8);
752         }
753
754         return NULL;
755 }
756
757 static void *htab_lru_map_lookup_elem(struct bpf_map *map, void *key)
758 {
759         return __htab_lru_map_lookup_elem(map, key, true);
760 }
761
762 static void *htab_lru_map_lookup_elem_sys(struct bpf_map *map, void *key)
763 {
764         return __htab_lru_map_lookup_elem(map, key, false);
765 }
766
767 static int htab_lru_map_gen_lookup(struct bpf_map *map,
768                                    struct bpf_insn *insn_buf)
769 {
770         struct bpf_insn *insn = insn_buf;
771         const int ret = BPF_REG_0;
772         const int ref_reg = BPF_REG_1;
773
774         BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
775                      (void *(*)(struct bpf_map *map, void *key))NULL));
776         *insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
777         *insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 4);
778         *insn++ = BPF_LDX_MEM(BPF_B, ref_reg, ret,
779                               offsetof(struct htab_elem, lru_node) +
780                               offsetof(struct bpf_lru_node, ref));
781         *insn++ = BPF_JMP_IMM(BPF_JNE, ref_reg, 0, 1);
782         *insn++ = BPF_ST_MEM(BPF_B, ret,
783                              offsetof(struct htab_elem, lru_node) +
784                              offsetof(struct bpf_lru_node, ref),
785                              1);
786         *insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
787                                 offsetof(struct htab_elem, key) +
788                                 round_up(map->key_size, 8));
789         return insn - insn_buf;
790 }
791
792 static void check_and_free_fields(struct bpf_htab *htab,
793                                   struct htab_elem *elem)
794 {
795         void *map_value = elem->key + round_up(htab->map.key_size, 8);
796
797         if (map_value_has_timer(&htab->map))
798                 bpf_timer_cancel_and_free(map_value + htab->map.timer_off);
799         if (map_value_has_kptrs(&htab->map))
800                 bpf_map_free_kptrs(&htab->map, map_value);
801 }
802
803 /* It is called from the bpf_lru_list when the LRU needs to delete
804  * older elements from the htab.
805  */
806 static bool htab_lru_map_delete_node(void *arg, struct bpf_lru_node *node)
807 {
808         struct bpf_htab *htab = arg;
809         struct htab_elem *l = NULL, *tgt_l;
810         struct hlist_nulls_head *head;
811         struct hlist_nulls_node *n;
812         unsigned long flags;
813         struct bucket *b;
814         int ret;
815
816         tgt_l = container_of(node, struct htab_elem, lru_node);
817         b = __select_bucket(htab, tgt_l->hash);
818         head = &b->head;
819
820         ret = htab_lock_bucket(htab, b, tgt_l->hash, &flags);
821         if (ret)
822                 return false;
823
824         hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
825                 if (l == tgt_l) {
826                         hlist_nulls_del_rcu(&l->hash_node);
827                         check_and_free_fields(htab, l);
828                         break;
829                 }
830
831         htab_unlock_bucket(htab, b, tgt_l->hash, flags);
832
833         return l == tgt_l;
834 }
835
836 /* Called from syscall */
837 static int htab_map_get_next_key(struct bpf_map *map, void *key, void *next_key)
838 {
839         struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
840         struct hlist_nulls_head *head;
841         struct htab_elem *l, *next_l;
842         u32 hash, key_size;
843         int i = 0;
844
845         WARN_ON_ONCE(!rcu_read_lock_held());
846
847         key_size = map->key_size;
848
849         if (!key)
850                 goto find_first_elem;
851
852         hash = htab_map_hash(key, key_size, htab->hashrnd);
853
854         head = select_bucket(htab, hash);
855
856         /* lookup the key */
857         l = lookup_nulls_elem_raw(head, hash, key, key_size, htab->n_buckets);
858
859         if (!l)
860                 goto find_first_elem;
861
862         /* key was found, get next key in the same bucket */
863         next_l = hlist_nulls_entry_safe(rcu_dereference_raw(hlist_nulls_next_rcu(&l->hash_node)),
864                                   struct htab_elem, hash_node);
865
866         if (next_l) {
867                 /* if next elem in this hash list is non-zero, just return it */
868                 memcpy(next_key, next_l->key, key_size);
869                 return 0;
870         }
871
872         /* no more elements in this hash list, go to the next bucket */
873         i = hash & (htab->n_buckets - 1);
874         i++;
875
876 find_first_elem:
877         /* iterate over buckets */
878         for (; i < htab->n_buckets; i++) {
879                 head = select_bucket(htab, i);
880
881                 /* pick first element in the bucket */
882                 next_l = hlist_nulls_entry_safe(rcu_dereference_raw(hlist_nulls_first_rcu(head)),
883                                           struct htab_elem, hash_node);
884                 if (next_l) {
885                         /* if it's not empty, just return it */
886                         memcpy(next_key, next_l->key, key_size);
887                         return 0;
888                 }
889         }
890
891         /* iterated over all buckets and all elements */
892         return -ENOENT;
893 }
894
895 static void htab_elem_free(struct bpf_htab *htab, struct htab_elem *l)
896 {
897         if (htab->map.map_type == BPF_MAP_TYPE_PERCPU_HASH)
898                 free_percpu(htab_elem_get_ptr(l, htab->map.key_size));
899         check_and_free_fields(htab, l);
900         bpf_mem_cache_free(&htab->ma, l);
901 }
902
903 static void htab_elem_free_rcu(struct rcu_head *head)
904 {
905         struct htab_elem *l = container_of(head, struct htab_elem, rcu);
906         struct bpf_htab *htab = l->htab;
907
908         htab_elem_free(htab, l);
909 }
910
911 static void htab_put_fd_value(struct bpf_htab *htab, struct htab_elem *l)
912 {
913         struct bpf_map *map = &htab->map;
914         void *ptr;
915
916         if (map->ops->map_fd_put_ptr) {
917                 ptr = fd_htab_map_get_ptr(map, l);
918                 map->ops->map_fd_put_ptr(ptr);
919         }
920 }
921
922 static bool is_map_full(struct bpf_htab *htab)
923 {
924         if (htab->use_percpu_counter)
925                 return __percpu_counter_compare(&htab->pcount, htab->map.max_entries,
926                                                 PERCPU_COUNTER_BATCH) >= 0;
927         return atomic_read(&htab->count) >= htab->map.max_entries;
928 }
929
930 static void inc_elem_count(struct bpf_htab *htab)
931 {
932         if (htab->use_percpu_counter)
933                 percpu_counter_add_batch(&htab->pcount, 1, PERCPU_COUNTER_BATCH);
934         else
935                 atomic_inc(&htab->count);
936 }
937
938 static void dec_elem_count(struct bpf_htab *htab)
939 {
940         if (htab->use_percpu_counter)
941                 percpu_counter_add_batch(&htab->pcount, -1, PERCPU_COUNTER_BATCH);
942         else
943                 atomic_dec(&htab->count);
944 }
945
946
947 static void free_htab_elem(struct bpf_htab *htab, struct htab_elem *l)
948 {
949         htab_put_fd_value(htab, l);
950
951         if (htab_is_prealloc(htab)) {
952                 check_and_free_fields(htab, l);
953                 __pcpu_freelist_push(&htab->freelist, &l->fnode);
954         } else {
955                 dec_elem_count(htab);
956                 l->htab = htab;
957                 call_rcu(&l->rcu, htab_elem_free_rcu);
958         }
959 }
960
961 static void pcpu_copy_value(struct bpf_htab *htab, void __percpu *pptr,
962                             void *value, bool onallcpus)
963 {
964         if (!onallcpus) {
965                 /* copy true value_size bytes */
966                 memcpy(this_cpu_ptr(pptr), value, htab->map.value_size);
967         } else {
968                 u32 size = round_up(htab->map.value_size, 8);
969                 int off = 0, cpu;
970
971                 for_each_possible_cpu(cpu) {
972                         bpf_long_memcpy(per_cpu_ptr(pptr, cpu),
973                                         value + off, size);
974                         off += size;
975                 }
976         }
977 }
978
979 static void pcpu_init_value(struct bpf_htab *htab, void __percpu *pptr,
980                             void *value, bool onallcpus)
981 {
982         /* When using prealloc and not setting the initial value on all cpus,
983          * zero-fill element values for other cpus (just as what happens when
984          * not using prealloc). Otherwise, bpf program has no way to ensure
985          * known initial values for cpus other than current one
986          * (onallcpus=false always when coming from bpf prog).
987          */
988         if (htab_is_prealloc(htab) && !onallcpus) {
989                 u32 size = round_up(htab->map.value_size, 8);
990                 int current_cpu = raw_smp_processor_id();
991                 int cpu;
992
993                 for_each_possible_cpu(cpu) {
994                         if (cpu == current_cpu)
995                                 bpf_long_memcpy(per_cpu_ptr(pptr, cpu), value,
996                                                 size);
997                         else
998                                 memset(per_cpu_ptr(pptr, cpu), 0, size);
999                 }
1000         } else {
1001                 pcpu_copy_value(htab, pptr, value, onallcpus);
1002         }
1003 }
1004
1005 static bool fd_htab_map_needs_adjust(const struct bpf_htab *htab)
1006 {
1007         return htab->map.map_type == BPF_MAP_TYPE_HASH_OF_MAPS &&
1008                BITS_PER_LONG == 64;
1009 }
1010
1011 static struct htab_elem *alloc_htab_elem(struct bpf_htab *htab, void *key,
1012                                          void *value, u32 key_size, u32 hash,
1013                                          bool percpu, bool onallcpus,
1014                                          struct htab_elem *old_elem)
1015 {
1016         u32 size = htab->map.value_size;
1017         bool prealloc = htab_is_prealloc(htab);
1018         struct htab_elem *l_new, **pl_new;
1019         void __percpu *pptr;
1020
1021         if (prealloc) {
1022                 if (old_elem) {
1023                         /* if we're updating the existing element,
1024                          * use per-cpu extra elems to avoid freelist_pop/push
1025                          */
1026                         pl_new = this_cpu_ptr(htab->extra_elems);
1027                         l_new = *pl_new;
1028                         htab_put_fd_value(htab, old_elem);
1029                         *pl_new = old_elem;
1030                 } else {
1031                         struct pcpu_freelist_node *l;
1032
1033                         l = __pcpu_freelist_pop(&htab->freelist);
1034                         if (!l)
1035                                 return ERR_PTR(-E2BIG);
1036                         l_new = container_of(l, struct htab_elem, fnode);
1037                 }
1038         } else {
1039                 if (is_map_full(htab))
1040                         if (!old_elem)
1041                                 /* when map is full and update() is replacing
1042                                  * old element, it's ok to allocate, since
1043                                  * old element will be freed immediately.
1044                                  * Otherwise return an error
1045                                  */
1046                                 return ERR_PTR(-E2BIG);
1047                 inc_elem_count(htab);
1048                 l_new = bpf_mem_cache_alloc(&htab->ma);
1049                 if (!l_new) {
1050                         l_new = ERR_PTR(-ENOMEM);
1051                         goto dec_count;
1052                 }
1053                 check_and_init_map_value(&htab->map,
1054                                          l_new->key + round_up(key_size, 8));
1055         }
1056
1057         memcpy(l_new->key, key, key_size);
1058         if (percpu) {
1059                 size = round_up(size, 8);
1060                 if (prealloc) {
1061                         pptr = htab_elem_get_ptr(l_new, key_size);
1062                 } else {
1063                         /* alloc_percpu zero-fills */
1064                         pptr = bpf_map_alloc_percpu(&htab->map, size, 8,
1065                                                     GFP_NOWAIT | __GFP_NOWARN);
1066                         if (!pptr) {
1067                                 bpf_mem_cache_free(&htab->ma, l_new);
1068                                 l_new = ERR_PTR(-ENOMEM);
1069                                 goto dec_count;
1070                         }
1071                 }
1072
1073                 pcpu_init_value(htab, pptr, value, onallcpus);
1074
1075                 if (!prealloc)
1076                         htab_elem_set_ptr(l_new, key_size, pptr);
1077         } else if (fd_htab_map_needs_adjust(htab)) {
1078                 size = round_up(size, 8);
1079                 memcpy(l_new->key + round_up(key_size, 8), value, size);
1080         } else {
1081                 copy_map_value(&htab->map,
1082                                l_new->key + round_up(key_size, 8),
1083                                value);
1084         }
1085
1086         l_new->hash = hash;
1087         return l_new;
1088 dec_count:
1089         dec_elem_count(htab);
1090         return l_new;
1091 }
1092
1093 static int check_flags(struct bpf_htab *htab, struct htab_elem *l_old,
1094                        u64 map_flags)
1095 {
1096         if (l_old && (map_flags & ~BPF_F_LOCK) == BPF_NOEXIST)
1097                 /* elem already exists */
1098                 return -EEXIST;
1099
1100         if (!l_old && (map_flags & ~BPF_F_LOCK) == BPF_EXIST)
1101                 /* elem doesn't exist, cannot update it */
1102                 return -ENOENT;
1103
1104         return 0;
1105 }
1106
1107 /* Called from syscall or from eBPF program */
1108 static int htab_map_update_elem(struct bpf_map *map, void *key, void *value,
1109                                 u64 map_flags)
1110 {
1111         struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1112         struct htab_elem *l_new = NULL, *l_old;
1113         struct hlist_nulls_head *head;
1114         unsigned long flags;
1115         struct bucket *b;
1116         u32 key_size, hash;
1117         int ret;
1118
1119         if (unlikely((map_flags & ~BPF_F_LOCK) > BPF_EXIST))
1120                 /* unknown flags */
1121                 return -EINVAL;
1122
1123         WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1124                      !rcu_read_lock_bh_held());
1125
1126         key_size = map->key_size;
1127
1128         hash = htab_map_hash(key, key_size, htab->hashrnd);
1129
1130         b = __select_bucket(htab, hash);
1131         head = &b->head;
1132
1133         if (unlikely(map_flags & BPF_F_LOCK)) {
1134                 if (unlikely(!map_value_has_spin_lock(map)))
1135                         return -EINVAL;
1136                 /* find an element without taking the bucket lock */
1137                 l_old = lookup_nulls_elem_raw(head, hash, key, key_size,
1138                                               htab->n_buckets);
1139                 ret = check_flags(htab, l_old, map_flags);
1140                 if (ret)
1141                         return ret;
1142                 if (l_old) {
1143                         /* grab the element lock and update value in place */
1144                         copy_map_value_locked(map,
1145                                               l_old->key + round_up(key_size, 8),
1146                                               value, false);
1147                         return 0;
1148                 }
1149                 /* fall through, grab the bucket lock and lookup again.
1150                  * 99.9% chance that the element won't be found,
1151                  * but second lookup under lock has to be done.
1152                  */
1153         }
1154
1155         ret = htab_lock_bucket(htab, b, hash, &flags);
1156         if (ret)
1157                 return ret;
1158
1159         l_old = lookup_elem_raw(head, hash, key, key_size);
1160
1161         ret = check_flags(htab, l_old, map_flags);
1162         if (ret)
1163                 goto err;
1164
1165         if (unlikely(l_old && (map_flags & BPF_F_LOCK))) {
1166                 /* first lookup without the bucket lock didn't find the element,
1167                  * but second lookup with the bucket lock found it.
1168                  * This case is highly unlikely, but has to be dealt with:
1169                  * grab the element lock in addition to the bucket lock
1170                  * and update element in place
1171                  */
1172                 copy_map_value_locked(map,
1173                                       l_old->key + round_up(key_size, 8),
1174                                       value, false);
1175                 ret = 0;
1176                 goto err;
1177         }
1178
1179         l_new = alloc_htab_elem(htab, key, value, key_size, hash, false, false,
1180                                 l_old);
1181         if (IS_ERR(l_new)) {
1182                 /* all pre-allocated elements are in use or memory exhausted */
1183                 ret = PTR_ERR(l_new);
1184                 goto err;
1185         }
1186
1187         /* add new element to the head of the list, so that
1188          * concurrent search will find it before old elem
1189          */
1190         hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1191         if (l_old) {
1192                 hlist_nulls_del_rcu(&l_old->hash_node);
1193                 if (!htab_is_prealloc(htab))
1194                         free_htab_elem(htab, l_old);
1195                 else
1196                         check_and_free_fields(htab, l_old);
1197         }
1198         ret = 0;
1199 err:
1200         htab_unlock_bucket(htab, b, hash, flags);
1201         return ret;
1202 }
1203
1204 static void htab_lru_push_free(struct bpf_htab *htab, struct htab_elem *elem)
1205 {
1206         check_and_free_fields(htab, elem);
1207         bpf_lru_push_free(&htab->lru, &elem->lru_node);
1208 }
1209
1210 static int htab_lru_map_update_elem(struct bpf_map *map, void *key, void *value,
1211                                     u64 map_flags)
1212 {
1213         struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1214         struct htab_elem *l_new, *l_old = NULL;
1215         struct hlist_nulls_head *head;
1216         unsigned long flags;
1217         struct bucket *b;
1218         u32 key_size, hash;
1219         int ret;
1220
1221         if (unlikely(map_flags > BPF_EXIST))
1222                 /* unknown flags */
1223                 return -EINVAL;
1224
1225         WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1226                      !rcu_read_lock_bh_held());
1227
1228         key_size = map->key_size;
1229
1230         hash = htab_map_hash(key, key_size, htab->hashrnd);
1231
1232         b = __select_bucket(htab, hash);
1233         head = &b->head;
1234
1235         /* For LRU, we need to alloc before taking bucket's
1236          * spinlock because getting free nodes from LRU may need
1237          * to remove older elements from htab and this removal
1238          * operation will need a bucket lock.
1239          */
1240         l_new = prealloc_lru_pop(htab, key, hash);
1241         if (!l_new)
1242                 return -ENOMEM;
1243         copy_map_value(&htab->map,
1244                        l_new->key + round_up(map->key_size, 8), value);
1245
1246         ret = htab_lock_bucket(htab, b, hash, &flags);
1247         if (ret)
1248                 return ret;
1249
1250         l_old = lookup_elem_raw(head, hash, key, key_size);
1251
1252         ret = check_flags(htab, l_old, map_flags);
1253         if (ret)
1254                 goto err;
1255
1256         /* add new element to the head of the list, so that
1257          * concurrent search will find it before old elem
1258          */
1259         hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1260         if (l_old) {
1261                 bpf_lru_node_set_ref(&l_new->lru_node);
1262                 hlist_nulls_del_rcu(&l_old->hash_node);
1263         }
1264         ret = 0;
1265
1266 err:
1267         htab_unlock_bucket(htab, b, hash, flags);
1268
1269         if (ret)
1270                 htab_lru_push_free(htab, l_new);
1271         else if (l_old)
1272                 htab_lru_push_free(htab, l_old);
1273
1274         return ret;
1275 }
1276
1277 static int __htab_percpu_map_update_elem(struct bpf_map *map, void *key,
1278                                          void *value, u64 map_flags,
1279                                          bool onallcpus)
1280 {
1281         struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1282         struct htab_elem *l_new = NULL, *l_old;
1283         struct hlist_nulls_head *head;
1284         unsigned long flags;
1285         struct bucket *b;
1286         u32 key_size, hash;
1287         int ret;
1288
1289         if (unlikely(map_flags > BPF_EXIST))
1290                 /* unknown flags */
1291                 return -EINVAL;
1292
1293         WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1294                      !rcu_read_lock_bh_held());
1295
1296         key_size = map->key_size;
1297
1298         hash = htab_map_hash(key, key_size, htab->hashrnd);
1299
1300         b = __select_bucket(htab, hash);
1301         head = &b->head;
1302
1303         ret = htab_lock_bucket(htab, b, hash, &flags);
1304         if (ret)
1305                 return ret;
1306
1307         l_old = lookup_elem_raw(head, hash, key, key_size);
1308
1309         ret = check_flags(htab, l_old, map_flags);
1310         if (ret)
1311                 goto err;
1312
1313         if (l_old) {
1314                 /* per-cpu hash map can update value in-place */
1315                 pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size),
1316                                 value, onallcpus);
1317         } else {
1318                 l_new = alloc_htab_elem(htab, key, value, key_size,
1319                                         hash, true, onallcpus, NULL);
1320                 if (IS_ERR(l_new)) {
1321                         ret = PTR_ERR(l_new);
1322                         goto err;
1323                 }
1324                 hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1325         }
1326         ret = 0;
1327 err:
1328         htab_unlock_bucket(htab, b, hash, flags);
1329         return ret;
1330 }
1331
1332 static int __htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key,
1333                                              void *value, u64 map_flags,
1334                                              bool onallcpus)
1335 {
1336         struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1337         struct htab_elem *l_new = NULL, *l_old;
1338         struct hlist_nulls_head *head;
1339         unsigned long flags;
1340         struct bucket *b;
1341         u32 key_size, hash;
1342         int ret;
1343
1344         if (unlikely(map_flags > BPF_EXIST))
1345                 /* unknown flags */
1346                 return -EINVAL;
1347
1348         WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1349                      !rcu_read_lock_bh_held());
1350
1351         key_size = map->key_size;
1352
1353         hash = htab_map_hash(key, key_size, htab->hashrnd);
1354
1355         b = __select_bucket(htab, hash);
1356         head = &b->head;
1357
1358         /* For LRU, we need to alloc before taking bucket's
1359          * spinlock because LRU's elem alloc may need
1360          * to remove older elem from htab and this removal
1361          * operation will need a bucket lock.
1362          */
1363         if (map_flags != BPF_EXIST) {
1364                 l_new = prealloc_lru_pop(htab, key, hash);
1365                 if (!l_new)
1366                         return -ENOMEM;
1367         }
1368
1369         ret = htab_lock_bucket(htab, b, hash, &flags);
1370         if (ret)
1371                 return ret;
1372
1373         l_old = lookup_elem_raw(head, hash, key, key_size);
1374
1375         ret = check_flags(htab, l_old, map_flags);
1376         if (ret)
1377                 goto err;
1378
1379         if (l_old) {
1380                 bpf_lru_node_set_ref(&l_old->lru_node);
1381
1382                 /* per-cpu hash map can update value in-place */
1383                 pcpu_copy_value(htab, htab_elem_get_ptr(l_old, key_size),
1384                                 value, onallcpus);
1385         } else {
1386                 pcpu_init_value(htab, htab_elem_get_ptr(l_new, key_size),
1387                                 value, onallcpus);
1388                 hlist_nulls_add_head_rcu(&l_new->hash_node, head);
1389                 l_new = NULL;
1390         }
1391         ret = 0;
1392 err:
1393         htab_unlock_bucket(htab, b, hash, flags);
1394         if (l_new)
1395                 bpf_lru_push_free(&htab->lru, &l_new->lru_node);
1396         return ret;
1397 }
1398
1399 static int htab_percpu_map_update_elem(struct bpf_map *map, void *key,
1400                                        void *value, u64 map_flags)
1401 {
1402         return __htab_percpu_map_update_elem(map, key, value, map_flags, false);
1403 }
1404
1405 static int htab_lru_percpu_map_update_elem(struct bpf_map *map, void *key,
1406                                            void *value, u64 map_flags)
1407 {
1408         return __htab_lru_percpu_map_update_elem(map, key, value, map_flags,
1409                                                  false);
1410 }
1411
1412 /* Called from syscall or from eBPF program */
1413 static int htab_map_delete_elem(struct bpf_map *map, void *key)
1414 {
1415         struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1416         struct hlist_nulls_head *head;
1417         struct bucket *b;
1418         struct htab_elem *l;
1419         unsigned long flags;
1420         u32 hash, key_size;
1421         int ret;
1422
1423         WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1424                      !rcu_read_lock_bh_held());
1425
1426         key_size = map->key_size;
1427
1428         hash = htab_map_hash(key, key_size, htab->hashrnd);
1429         b = __select_bucket(htab, hash);
1430         head = &b->head;
1431
1432         ret = htab_lock_bucket(htab, b, hash, &flags);
1433         if (ret)
1434                 return ret;
1435
1436         l = lookup_elem_raw(head, hash, key, key_size);
1437
1438         if (l) {
1439                 hlist_nulls_del_rcu(&l->hash_node);
1440                 free_htab_elem(htab, l);
1441         } else {
1442                 ret = -ENOENT;
1443         }
1444
1445         htab_unlock_bucket(htab, b, hash, flags);
1446         return ret;
1447 }
1448
1449 static int htab_lru_map_delete_elem(struct bpf_map *map, void *key)
1450 {
1451         struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1452         struct hlist_nulls_head *head;
1453         struct bucket *b;
1454         struct htab_elem *l;
1455         unsigned long flags;
1456         u32 hash, key_size;
1457         int ret;
1458
1459         WARN_ON_ONCE(!rcu_read_lock_held() && !rcu_read_lock_trace_held() &&
1460                      !rcu_read_lock_bh_held());
1461
1462         key_size = map->key_size;
1463
1464         hash = htab_map_hash(key, key_size, htab->hashrnd);
1465         b = __select_bucket(htab, hash);
1466         head = &b->head;
1467
1468         ret = htab_lock_bucket(htab, b, hash, &flags);
1469         if (ret)
1470                 return ret;
1471
1472         l = lookup_elem_raw(head, hash, key, key_size);
1473
1474         if (l)
1475                 hlist_nulls_del_rcu(&l->hash_node);
1476         else
1477                 ret = -ENOENT;
1478
1479         htab_unlock_bucket(htab, b, hash, flags);
1480         if (l)
1481                 htab_lru_push_free(htab, l);
1482         return ret;
1483 }
1484
1485 static void delete_all_elements(struct bpf_htab *htab)
1486 {
1487         int i;
1488
1489         /* It's called from a worker thread, so disable migration here,
1490          * since bpf_mem_cache_free() relies on that.
1491          */
1492         migrate_disable();
1493         for (i = 0; i < htab->n_buckets; i++) {
1494                 struct hlist_nulls_head *head = select_bucket(htab, i);
1495                 struct hlist_nulls_node *n;
1496                 struct htab_elem *l;
1497
1498                 hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
1499                         hlist_nulls_del_rcu(&l->hash_node);
1500                         htab_elem_free(htab, l);
1501                 }
1502         }
1503         migrate_enable();
1504 }
1505
1506 static void htab_free_malloced_timers(struct bpf_htab *htab)
1507 {
1508         int i;
1509
1510         rcu_read_lock();
1511         for (i = 0; i < htab->n_buckets; i++) {
1512                 struct hlist_nulls_head *head = select_bucket(htab, i);
1513                 struct hlist_nulls_node *n;
1514                 struct htab_elem *l;
1515
1516                 hlist_nulls_for_each_entry(l, n, head, hash_node) {
1517                         /* We don't reset or free kptr on uref dropping to zero,
1518                          * hence just free timer.
1519                          */
1520                         bpf_timer_cancel_and_free(l->key +
1521                                                   round_up(htab->map.key_size, 8) +
1522                                                   htab->map.timer_off);
1523                 }
1524                 cond_resched_rcu();
1525         }
1526         rcu_read_unlock();
1527 }
1528
1529 static void htab_map_free_timers(struct bpf_map *map)
1530 {
1531         struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1532
1533         /* We don't reset or free kptr on uref dropping to zero. */
1534         if (!map_value_has_timer(&htab->map))
1535                 return;
1536         if (!htab_is_prealloc(htab))
1537                 htab_free_malloced_timers(htab);
1538         else
1539                 htab_free_prealloced_timers(htab);
1540 }
1541
1542 /* Called when map->refcnt goes to zero, either from workqueue or from syscall */
1543 static void htab_map_free(struct bpf_map *map)
1544 {
1545         struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1546         int i;
1547
1548         /* bpf_free_used_maps() or close(map_fd) will trigger this map_free callback.
1549          * bpf_free_used_maps() is called after bpf prog is no longer executing.
1550          * There is no need to synchronize_rcu() here to protect map elements.
1551          */
1552
1553         /* some of free_htab_elem() callbacks for elements of this map may
1554          * not have executed. Wait for them.
1555          */
1556         rcu_barrier();
1557         if (!htab_is_prealloc(htab)) {
1558                 delete_all_elements(htab);
1559         } else {
1560                 htab_free_prealloced_kptrs(htab);
1561                 prealloc_destroy(htab);
1562         }
1563
1564         bpf_map_free_kptr_off_tab(map);
1565         free_percpu(htab->extra_elems);
1566         bpf_map_area_free(htab->buckets);
1567         bpf_mem_alloc_destroy(&htab->ma);
1568         if (htab->use_percpu_counter)
1569                 percpu_counter_destroy(&htab->pcount);
1570         for (i = 0; i < HASHTAB_MAP_LOCK_COUNT; i++)
1571                 free_percpu(htab->map_locked[i]);
1572         lockdep_unregister_key(&htab->lockdep_key);
1573         bpf_map_area_free(htab);
1574 }
1575
1576 static void htab_map_seq_show_elem(struct bpf_map *map, void *key,
1577                                    struct seq_file *m)
1578 {
1579         void *value;
1580
1581         rcu_read_lock();
1582
1583         value = htab_map_lookup_elem(map, key);
1584         if (!value) {
1585                 rcu_read_unlock();
1586                 return;
1587         }
1588
1589         btf_type_seq_show(map->btf, map->btf_key_type_id, key, m);
1590         seq_puts(m, ": ");
1591         btf_type_seq_show(map->btf, map->btf_value_type_id, value, m);
1592         seq_puts(m, "\n");
1593
1594         rcu_read_unlock();
1595 }
1596
1597 static int __htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
1598                                              void *value, bool is_lru_map,
1599                                              bool is_percpu, u64 flags)
1600 {
1601         struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1602         struct hlist_nulls_head *head;
1603         unsigned long bflags;
1604         struct htab_elem *l;
1605         u32 hash, key_size;
1606         struct bucket *b;
1607         int ret;
1608
1609         key_size = map->key_size;
1610
1611         hash = htab_map_hash(key, key_size, htab->hashrnd);
1612         b = __select_bucket(htab, hash);
1613         head = &b->head;
1614
1615         ret = htab_lock_bucket(htab, b, hash, &bflags);
1616         if (ret)
1617                 return ret;
1618
1619         l = lookup_elem_raw(head, hash, key, key_size);
1620         if (!l) {
1621                 ret = -ENOENT;
1622         } else {
1623                 if (is_percpu) {
1624                         u32 roundup_value_size = round_up(map->value_size, 8);
1625                         void __percpu *pptr;
1626                         int off = 0, cpu;
1627
1628                         pptr = htab_elem_get_ptr(l, key_size);
1629                         for_each_possible_cpu(cpu) {
1630                                 bpf_long_memcpy(value + off,
1631                                                 per_cpu_ptr(pptr, cpu),
1632                                                 roundup_value_size);
1633                                 off += roundup_value_size;
1634                         }
1635                 } else {
1636                         u32 roundup_key_size = round_up(map->key_size, 8);
1637
1638                         if (flags & BPF_F_LOCK)
1639                                 copy_map_value_locked(map, value, l->key +
1640                                                       roundup_key_size,
1641                                                       true);
1642                         else
1643                                 copy_map_value(map, value, l->key +
1644                                                roundup_key_size);
1645                         check_and_init_map_value(map, value);
1646                 }
1647
1648                 hlist_nulls_del_rcu(&l->hash_node);
1649                 if (!is_lru_map)
1650                         free_htab_elem(htab, l);
1651         }
1652
1653         htab_unlock_bucket(htab, b, hash, bflags);
1654
1655         if (is_lru_map && l)
1656                 htab_lru_push_free(htab, l);
1657
1658         return ret;
1659 }
1660
1661 static int htab_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
1662                                            void *value, u64 flags)
1663 {
1664         return __htab_map_lookup_and_delete_elem(map, key, value, false, false,
1665                                                  flags);
1666 }
1667
1668 static int htab_percpu_map_lookup_and_delete_elem(struct bpf_map *map,
1669                                                   void *key, void *value,
1670                                                   u64 flags)
1671 {
1672         return __htab_map_lookup_and_delete_elem(map, key, value, false, true,
1673                                                  flags);
1674 }
1675
1676 static int htab_lru_map_lookup_and_delete_elem(struct bpf_map *map, void *key,
1677                                                void *value, u64 flags)
1678 {
1679         return __htab_map_lookup_and_delete_elem(map, key, value, true, false,
1680                                                  flags);
1681 }
1682
1683 static int htab_lru_percpu_map_lookup_and_delete_elem(struct bpf_map *map,
1684                                                       void *key, void *value,
1685                                                       u64 flags)
1686 {
1687         return __htab_map_lookup_and_delete_elem(map, key, value, true, true,
1688                                                  flags);
1689 }
1690
1691 static int
1692 __htab_map_lookup_and_delete_batch(struct bpf_map *map,
1693                                    const union bpf_attr *attr,
1694                                    union bpf_attr __user *uattr,
1695                                    bool do_delete, bool is_lru_map,
1696                                    bool is_percpu)
1697 {
1698         struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
1699         u32 bucket_cnt, total, key_size, value_size, roundup_key_size;
1700         void *keys = NULL, *values = NULL, *value, *dst_key, *dst_val;
1701         void __user *uvalues = u64_to_user_ptr(attr->batch.values);
1702         void __user *ukeys = u64_to_user_ptr(attr->batch.keys);
1703         void __user *ubatch = u64_to_user_ptr(attr->batch.in_batch);
1704         u32 batch, max_count, size, bucket_size, map_id;
1705         struct htab_elem *node_to_free = NULL;
1706         u64 elem_map_flags, map_flags;
1707         struct hlist_nulls_head *head;
1708         struct hlist_nulls_node *n;
1709         unsigned long flags = 0;
1710         bool locked = false;
1711         struct htab_elem *l;
1712         struct bucket *b;
1713         int ret = 0;
1714
1715         elem_map_flags = attr->batch.elem_flags;
1716         if ((elem_map_flags & ~BPF_F_LOCK) ||
1717             ((elem_map_flags & BPF_F_LOCK) && !map_value_has_spin_lock(map)))
1718                 return -EINVAL;
1719
1720         map_flags = attr->batch.flags;
1721         if (map_flags)
1722                 return -EINVAL;
1723
1724         max_count = attr->batch.count;
1725         if (!max_count)
1726                 return 0;
1727
1728         if (put_user(0, &uattr->batch.count))
1729                 return -EFAULT;
1730
1731         batch = 0;
1732         if (ubatch && copy_from_user(&batch, ubatch, sizeof(batch)))
1733                 return -EFAULT;
1734
1735         if (batch >= htab->n_buckets)
1736                 return -ENOENT;
1737
1738         key_size = htab->map.key_size;
1739         roundup_key_size = round_up(htab->map.key_size, 8);
1740         value_size = htab->map.value_size;
1741         size = round_up(value_size, 8);
1742         if (is_percpu)
1743                 value_size = size * num_possible_cpus();
1744         total = 0;
1745         /* while experimenting with hash tables with sizes ranging from 10 to
1746          * 1000, it was observed that a bucket can have up to 5 entries.
1747          */
1748         bucket_size = 5;
1749
1750 alloc:
1751         /* We cannot do copy_from_user or copy_to_user inside
1752          * the rcu_read_lock. Allocate enough space here.
1753          */
1754         keys = kvmalloc_array(key_size, bucket_size, GFP_USER | __GFP_NOWARN);
1755         values = kvmalloc_array(value_size, bucket_size, GFP_USER | __GFP_NOWARN);
1756         if (!keys || !values) {
1757                 ret = -ENOMEM;
1758                 goto after_loop;
1759         }
1760
1761 again:
1762         bpf_disable_instrumentation();
1763         rcu_read_lock();
1764 again_nocopy:
1765         dst_key = keys;
1766         dst_val = values;
1767         b = &htab->buckets[batch];
1768         head = &b->head;
1769         /* do not grab the lock unless need it (bucket_cnt > 0). */
1770         if (locked) {
1771                 ret = htab_lock_bucket(htab, b, batch, &flags);
1772                 if (ret) {
1773                         rcu_read_unlock();
1774                         bpf_enable_instrumentation();
1775                         goto after_loop;
1776                 }
1777         }
1778
1779         bucket_cnt = 0;
1780         hlist_nulls_for_each_entry_rcu(l, n, head, hash_node)
1781                 bucket_cnt++;
1782
1783         if (bucket_cnt && !locked) {
1784                 locked = true;
1785                 goto again_nocopy;
1786         }
1787
1788         if (bucket_cnt > (max_count - total)) {
1789                 if (total == 0)
1790                         ret = -ENOSPC;
1791                 /* Note that since bucket_cnt > 0 here, it is implicit
1792                  * that the locked was grabbed, so release it.
1793                  */
1794                 htab_unlock_bucket(htab, b, batch, flags);
1795                 rcu_read_unlock();
1796                 bpf_enable_instrumentation();
1797                 goto after_loop;
1798         }
1799
1800         if (bucket_cnt > bucket_size) {
1801                 bucket_size = bucket_cnt;
1802                 /* Note that since bucket_cnt > 0 here, it is implicit
1803                  * that the locked was grabbed, so release it.
1804                  */
1805                 htab_unlock_bucket(htab, b, batch, flags);
1806                 rcu_read_unlock();
1807                 bpf_enable_instrumentation();
1808                 kvfree(keys);
1809                 kvfree(values);
1810                 goto alloc;
1811         }
1812
1813         /* Next block is only safe to run if you have grabbed the lock */
1814         if (!locked)
1815                 goto next_batch;
1816
1817         hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
1818                 memcpy(dst_key, l->key, key_size);
1819
1820                 if (is_percpu) {
1821                         int off = 0, cpu;
1822                         void __percpu *pptr;
1823
1824                         pptr = htab_elem_get_ptr(l, map->key_size);
1825                         for_each_possible_cpu(cpu) {
1826                                 bpf_long_memcpy(dst_val + off,
1827                                                 per_cpu_ptr(pptr, cpu), size);
1828                                 off += size;
1829                         }
1830                 } else {
1831                         value = l->key + roundup_key_size;
1832                         if (map->map_type == BPF_MAP_TYPE_HASH_OF_MAPS) {
1833                                 struct bpf_map **inner_map = value;
1834
1835                                  /* Actual value is the id of the inner map */
1836                                 map_id = map->ops->map_fd_sys_lookup_elem(*inner_map);
1837                                 value = &map_id;
1838                         }
1839
1840                         if (elem_map_flags & BPF_F_LOCK)
1841                                 copy_map_value_locked(map, dst_val, value,
1842                                                       true);
1843                         else
1844                                 copy_map_value(map, dst_val, value);
1845                         check_and_init_map_value(map, dst_val);
1846                 }
1847                 if (do_delete) {
1848                         hlist_nulls_del_rcu(&l->hash_node);
1849
1850                         /* bpf_lru_push_free() will acquire lru_lock, which
1851                          * may cause deadlock. See comments in function
1852                          * prealloc_lru_pop(). Let us do bpf_lru_push_free()
1853                          * after releasing the bucket lock.
1854                          */
1855                         if (is_lru_map) {
1856                                 l->batch_flink = node_to_free;
1857                                 node_to_free = l;
1858                         } else {
1859                                 free_htab_elem(htab, l);
1860                         }
1861                 }
1862                 dst_key += key_size;
1863                 dst_val += value_size;
1864         }
1865
1866         htab_unlock_bucket(htab, b, batch, flags);
1867         locked = false;
1868
1869         while (node_to_free) {
1870                 l = node_to_free;
1871                 node_to_free = node_to_free->batch_flink;
1872                 htab_lru_push_free(htab, l);
1873         }
1874
1875 next_batch:
1876         /* If we are not copying data, we can go to next bucket and avoid
1877          * unlocking the rcu.
1878          */
1879         if (!bucket_cnt && (batch + 1 < htab->n_buckets)) {
1880                 batch++;
1881                 goto again_nocopy;
1882         }
1883
1884         rcu_read_unlock();
1885         bpf_enable_instrumentation();
1886         if (bucket_cnt && (copy_to_user(ukeys + total * key_size, keys,
1887             key_size * bucket_cnt) ||
1888             copy_to_user(uvalues + total * value_size, values,
1889             value_size * bucket_cnt))) {
1890                 ret = -EFAULT;
1891                 goto after_loop;
1892         }
1893
1894         total += bucket_cnt;
1895         batch++;
1896         if (batch >= htab->n_buckets) {
1897                 ret = -ENOENT;
1898                 goto after_loop;
1899         }
1900         goto again;
1901
1902 after_loop:
1903         if (ret == -EFAULT)
1904                 goto out;
1905
1906         /* copy # of entries and next batch */
1907         ubatch = u64_to_user_ptr(attr->batch.out_batch);
1908         if (copy_to_user(ubatch, &batch, sizeof(batch)) ||
1909             put_user(total, &uattr->batch.count))
1910                 ret = -EFAULT;
1911
1912 out:
1913         kvfree(keys);
1914         kvfree(values);
1915         return ret;
1916 }
1917
1918 static int
1919 htab_percpu_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
1920                              union bpf_attr __user *uattr)
1921 {
1922         return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1923                                                   false, true);
1924 }
1925
1926 static int
1927 htab_percpu_map_lookup_and_delete_batch(struct bpf_map *map,
1928                                         const union bpf_attr *attr,
1929                                         union bpf_attr __user *uattr)
1930 {
1931         return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1932                                                   false, true);
1933 }
1934
1935 static int
1936 htab_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
1937                       union bpf_attr __user *uattr)
1938 {
1939         return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1940                                                   false, false);
1941 }
1942
1943 static int
1944 htab_map_lookup_and_delete_batch(struct bpf_map *map,
1945                                  const union bpf_attr *attr,
1946                                  union bpf_attr __user *uattr)
1947 {
1948         return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1949                                                   false, false);
1950 }
1951
1952 static int
1953 htab_lru_percpu_map_lookup_batch(struct bpf_map *map,
1954                                  const union bpf_attr *attr,
1955                                  union bpf_attr __user *uattr)
1956 {
1957         return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1958                                                   true, true);
1959 }
1960
1961 static int
1962 htab_lru_percpu_map_lookup_and_delete_batch(struct bpf_map *map,
1963                                             const union bpf_attr *attr,
1964                                             union bpf_attr __user *uattr)
1965 {
1966         return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1967                                                   true, true);
1968 }
1969
1970 static int
1971 htab_lru_map_lookup_batch(struct bpf_map *map, const union bpf_attr *attr,
1972                           union bpf_attr __user *uattr)
1973 {
1974         return __htab_map_lookup_and_delete_batch(map, attr, uattr, false,
1975                                                   true, false);
1976 }
1977
1978 static int
1979 htab_lru_map_lookup_and_delete_batch(struct bpf_map *map,
1980                                      const union bpf_attr *attr,
1981                                      union bpf_attr __user *uattr)
1982 {
1983         return __htab_map_lookup_and_delete_batch(map, attr, uattr, true,
1984                                                   true, false);
1985 }
1986
1987 struct bpf_iter_seq_hash_map_info {
1988         struct bpf_map *map;
1989         struct bpf_htab *htab;
1990         void *percpu_value_buf; // non-zero means percpu hash
1991         u32 bucket_id;
1992         u32 skip_elems;
1993 };
1994
1995 static struct htab_elem *
1996 bpf_hash_map_seq_find_next(struct bpf_iter_seq_hash_map_info *info,
1997                            struct htab_elem *prev_elem)
1998 {
1999         const struct bpf_htab *htab = info->htab;
2000         u32 skip_elems = info->skip_elems;
2001         u32 bucket_id = info->bucket_id;
2002         struct hlist_nulls_head *head;
2003         struct hlist_nulls_node *n;
2004         struct htab_elem *elem;
2005         struct bucket *b;
2006         u32 i, count;
2007
2008         if (bucket_id >= htab->n_buckets)
2009                 return NULL;
2010
2011         /* try to find next elem in the same bucket */
2012         if (prev_elem) {
2013                 /* no update/deletion on this bucket, prev_elem should be still valid
2014                  * and we won't skip elements.
2015                  */
2016                 n = rcu_dereference_raw(hlist_nulls_next_rcu(&prev_elem->hash_node));
2017                 elem = hlist_nulls_entry_safe(n, struct htab_elem, hash_node);
2018                 if (elem)
2019                         return elem;
2020
2021                 /* not found, unlock and go to the next bucket */
2022                 b = &htab->buckets[bucket_id++];
2023                 rcu_read_unlock();
2024                 skip_elems = 0;
2025         }
2026
2027         for (i = bucket_id; i < htab->n_buckets; i++) {
2028                 b = &htab->buckets[i];
2029                 rcu_read_lock();
2030
2031                 count = 0;
2032                 head = &b->head;
2033                 hlist_nulls_for_each_entry_rcu(elem, n, head, hash_node) {
2034                         if (count >= skip_elems) {
2035                                 info->bucket_id = i;
2036                                 info->skip_elems = count;
2037                                 return elem;
2038                         }
2039                         count++;
2040                 }
2041
2042                 rcu_read_unlock();
2043                 skip_elems = 0;
2044         }
2045
2046         info->bucket_id = i;
2047         info->skip_elems = 0;
2048         return NULL;
2049 }
2050
2051 static void *bpf_hash_map_seq_start(struct seq_file *seq, loff_t *pos)
2052 {
2053         struct bpf_iter_seq_hash_map_info *info = seq->private;
2054         struct htab_elem *elem;
2055
2056         elem = bpf_hash_map_seq_find_next(info, NULL);
2057         if (!elem)
2058                 return NULL;
2059
2060         if (*pos == 0)
2061                 ++*pos;
2062         return elem;
2063 }
2064
2065 static void *bpf_hash_map_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2066 {
2067         struct bpf_iter_seq_hash_map_info *info = seq->private;
2068
2069         ++*pos;
2070         ++info->skip_elems;
2071         return bpf_hash_map_seq_find_next(info, v);
2072 }
2073
2074 static int __bpf_hash_map_seq_show(struct seq_file *seq, struct htab_elem *elem)
2075 {
2076         struct bpf_iter_seq_hash_map_info *info = seq->private;
2077         u32 roundup_key_size, roundup_value_size;
2078         struct bpf_iter__bpf_map_elem ctx = {};
2079         struct bpf_map *map = info->map;
2080         struct bpf_iter_meta meta;
2081         int ret = 0, off = 0, cpu;
2082         struct bpf_prog *prog;
2083         void __percpu *pptr;
2084
2085         meta.seq = seq;
2086         prog = bpf_iter_get_info(&meta, elem == NULL);
2087         if (prog) {
2088                 ctx.meta = &meta;
2089                 ctx.map = info->map;
2090                 if (elem) {
2091                         roundup_key_size = round_up(map->key_size, 8);
2092                         ctx.key = elem->key;
2093                         if (!info->percpu_value_buf) {
2094                                 ctx.value = elem->key + roundup_key_size;
2095                         } else {
2096                                 roundup_value_size = round_up(map->value_size, 8);
2097                                 pptr = htab_elem_get_ptr(elem, map->key_size);
2098                                 for_each_possible_cpu(cpu) {
2099                                         bpf_long_memcpy(info->percpu_value_buf + off,
2100                                                         per_cpu_ptr(pptr, cpu),
2101                                                         roundup_value_size);
2102                                         off += roundup_value_size;
2103                                 }
2104                                 ctx.value = info->percpu_value_buf;
2105                         }
2106                 }
2107                 ret = bpf_iter_run_prog(prog, &ctx);
2108         }
2109
2110         return ret;
2111 }
2112
2113 static int bpf_hash_map_seq_show(struct seq_file *seq, void *v)
2114 {
2115         return __bpf_hash_map_seq_show(seq, v);
2116 }
2117
2118 static void bpf_hash_map_seq_stop(struct seq_file *seq, void *v)
2119 {
2120         if (!v)
2121                 (void)__bpf_hash_map_seq_show(seq, NULL);
2122         else
2123                 rcu_read_unlock();
2124 }
2125
2126 static int bpf_iter_init_hash_map(void *priv_data,
2127                                   struct bpf_iter_aux_info *aux)
2128 {
2129         struct bpf_iter_seq_hash_map_info *seq_info = priv_data;
2130         struct bpf_map *map = aux->map;
2131         void *value_buf;
2132         u32 buf_size;
2133
2134         if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||
2135             map->map_type == BPF_MAP_TYPE_LRU_PERCPU_HASH) {
2136                 buf_size = round_up(map->value_size, 8) * num_possible_cpus();
2137                 value_buf = kmalloc(buf_size, GFP_USER | __GFP_NOWARN);
2138                 if (!value_buf)
2139                         return -ENOMEM;
2140
2141                 seq_info->percpu_value_buf = value_buf;
2142         }
2143
2144         bpf_map_inc_with_uref(map);
2145         seq_info->map = map;
2146         seq_info->htab = container_of(map, struct bpf_htab, map);
2147         return 0;
2148 }
2149
2150 static void bpf_iter_fini_hash_map(void *priv_data)
2151 {
2152         struct bpf_iter_seq_hash_map_info *seq_info = priv_data;
2153
2154         bpf_map_put_with_uref(seq_info->map);
2155         kfree(seq_info->percpu_value_buf);
2156 }
2157
2158 static const struct seq_operations bpf_hash_map_seq_ops = {
2159         .start  = bpf_hash_map_seq_start,
2160         .next   = bpf_hash_map_seq_next,
2161         .stop   = bpf_hash_map_seq_stop,
2162         .show   = bpf_hash_map_seq_show,
2163 };
2164
2165 static const struct bpf_iter_seq_info iter_seq_info = {
2166         .seq_ops                = &bpf_hash_map_seq_ops,
2167         .init_seq_private       = bpf_iter_init_hash_map,
2168         .fini_seq_private       = bpf_iter_fini_hash_map,
2169         .seq_priv_size          = sizeof(struct bpf_iter_seq_hash_map_info),
2170 };
2171
2172 static int bpf_for_each_hash_elem(struct bpf_map *map, bpf_callback_t callback_fn,
2173                                   void *callback_ctx, u64 flags)
2174 {
2175         struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2176         struct hlist_nulls_head *head;
2177         struct hlist_nulls_node *n;
2178         struct htab_elem *elem;
2179         u32 roundup_key_size;
2180         int i, num_elems = 0;
2181         void __percpu *pptr;
2182         struct bucket *b;
2183         void *key, *val;
2184         bool is_percpu;
2185         u64 ret = 0;
2186
2187         if (flags != 0)
2188                 return -EINVAL;
2189
2190         is_percpu = htab_is_percpu(htab);
2191
2192         roundup_key_size = round_up(map->key_size, 8);
2193         /* disable migration so percpu value prepared here will be the
2194          * same as the one seen by the bpf program with bpf_map_lookup_elem().
2195          */
2196         if (is_percpu)
2197                 migrate_disable();
2198         for (i = 0; i < htab->n_buckets; i++) {
2199                 b = &htab->buckets[i];
2200                 rcu_read_lock();
2201                 head = &b->head;
2202                 hlist_nulls_for_each_entry_rcu(elem, n, head, hash_node) {
2203                         key = elem->key;
2204                         if (is_percpu) {
2205                                 /* current cpu value for percpu map */
2206                                 pptr = htab_elem_get_ptr(elem, map->key_size);
2207                                 val = this_cpu_ptr(pptr);
2208                         } else {
2209                                 val = elem->key + roundup_key_size;
2210                         }
2211                         num_elems++;
2212                         ret = callback_fn((u64)(long)map, (u64)(long)key,
2213                                           (u64)(long)val, (u64)(long)callback_ctx, 0);
2214                         /* return value: 0 - continue, 1 - stop and return */
2215                         if (ret) {
2216                                 rcu_read_unlock();
2217                                 goto out;
2218                         }
2219                 }
2220                 rcu_read_unlock();
2221         }
2222 out:
2223         if (is_percpu)
2224                 migrate_enable();
2225         return num_elems;
2226 }
2227
2228 BTF_ID_LIST_SINGLE(htab_map_btf_ids, struct, bpf_htab)
2229 const struct bpf_map_ops htab_map_ops = {
2230         .map_meta_equal = bpf_map_meta_equal,
2231         .map_alloc_check = htab_map_alloc_check,
2232         .map_alloc = htab_map_alloc,
2233         .map_free = htab_map_free,
2234         .map_get_next_key = htab_map_get_next_key,
2235         .map_release_uref = htab_map_free_timers,
2236         .map_lookup_elem = htab_map_lookup_elem,
2237         .map_lookup_and_delete_elem = htab_map_lookup_and_delete_elem,
2238         .map_update_elem = htab_map_update_elem,
2239         .map_delete_elem = htab_map_delete_elem,
2240         .map_gen_lookup = htab_map_gen_lookup,
2241         .map_seq_show_elem = htab_map_seq_show_elem,
2242         .map_set_for_each_callback_args = map_set_for_each_callback_args,
2243         .map_for_each_callback = bpf_for_each_hash_elem,
2244         BATCH_OPS(htab),
2245         .map_btf_id = &htab_map_btf_ids[0],
2246         .iter_seq_info = &iter_seq_info,
2247 };
2248
2249 const struct bpf_map_ops htab_lru_map_ops = {
2250         .map_meta_equal = bpf_map_meta_equal,
2251         .map_alloc_check = htab_map_alloc_check,
2252         .map_alloc = htab_map_alloc,
2253         .map_free = htab_map_free,
2254         .map_get_next_key = htab_map_get_next_key,
2255         .map_release_uref = htab_map_free_timers,
2256         .map_lookup_elem = htab_lru_map_lookup_elem,
2257         .map_lookup_and_delete_elem = htab_lru_map_lookup_and_delete_elem,
2258         .map_lookup_elem_sys_only = htab_lru_map_lookup_elem_sys,
2259         .map_update_elem = htab_lru_map_update_elem,
2260         .map_delete_elem = htab_lru_map_delete_elem,
2261         .map_gen_lookup = htab_lru_map_gen_lookup,
2262         .map_seq_show_elem = htab_map_seq_show_elem,
2263         .map_set_for_each_callback_args = map_set_for_each_callback_args,
2264         .map_for_each_callback = bpf_for_each_hash_elem,
2265         BATCH_OPS(htab_lru),
2266         .map_btf_id = &htab_map_btf_ids[0],
2267         .iter_seq_info = &iter_seq_info,
2268 };
2269
2270 /* Called from eBPF program */
2271 static void *htab_percpu_map_lookup_elem(struct bpf_map *map, void *key)
2272 {
2273         struct htab_elem *l = __htab_map_lookup_elem(map, key);
2274
2275         if (l)
2276                 return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size));
2277         else
2278                 return NULL;
2279 }
2280
2281 static void *htab_percpu_map_lookup_percpu_elem(struct bpf_map *map, void *key, u32 cpu)
2282 {
2283         struct htab_elem *l;
2284
2285         if (cpu >= nr_cpu_ids)
2286                 return NULL;
2287
2288         l = __htab_map_lookup_elem(map, key);
2289         if (l)
2290                 return per_cpu_ptr(htab_elem_get_ptr(l, map->key_size), cpu);
2291         else
2292                 return NULL;
2293 }
2294
2295 static void *htab_lru_percpu_map_lookup_elem(struct bpf_map *map, void *key)
2296 {
2297         struct htab_elem *l = __htab_map_lookup_elem(map, key);
2298
2299         if (l) {
2300                 bpf_lru_node_set_ref(&l->lru_node);
2301                 return this_cpu_ptr(htab_elem_get_ptr(l, map->key_size));
2302         }
2303
2304         return NULL;
2305 }
2306
2307 static void *htab_lru_percpu_map_lookup_percpu_elem(struct bpf_map *map, void *key, u32 cpu)
2308 {
2309         struct htab_elem *l;
2310
2311         if (cpu >= nr_cpu_ids)
2312                 return NULL;
2313
2314         l = __htab_map_lookup_elem(map, key);
2315         if (l) {
2316                 bpf_lru_node_set_ref(&l->lru_node);
2317                 return per_cpu_ptr(htab_elem_get_ptr(l, map->key_size), cpu);
2318         }
2319
2320         return NULL;
2321 }
2322
2323 int bpf_percpu_hash_copy(struct bpf_map *map, void *key, void *value)
2324 {
2325         struct htab_elem *l;
2326         void __percpu *pptr;
2327         int ret = -ENOENT;
2328         int cpu, off = 0;
2329         u32 size;
2330
2331         /* per_cpu areas are zero-filled and bpf programs can only
2332          * access 'value_size' of them, so copying rounded areas
2333          * will not leak any kernel data
2334          */
2335         size = round_up(map->value_size, 8);
2336         rcu_read_lock();
2337         l = __htab_map_lookup_elem(map, key);
2338         if (!l)
2339                 goto out;
2340         /* We do not mark LRU map element here in order to not mess up
2341          * eviction heuristics when user space does a map walk.
2342          */
2343         pptr = htab_elem_get_ptr(l, map->key_size);
2344         for_each_possible_cpu(cpu) {
2345                 bpf_long_memcpy(value + off,
2346                                 per_cpu_ptr(pptr, cpu), size);
2347                 off += size;
2348         }
2349         ret = 0;
2350 out:
2351         rcu_read_unlock();
2352         return ret;
2353 }
2354
2355 int bpf_percpu_hash_update(struct bpf_map *map, void *key, void *value,
2356                            u64 map_flags)
2357 {
2358         struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2359         int ret;
2360
2361         rcu_read_lock();
2362         if (htab_is_lru(htab))
2363                 ret = __htab_lru_percpu_map_update_elem(map, key, value,
2364                                                         map_flags, true);
2365         else
2366                 ret = __htab_percpu_map_update_elem(map, key, value, map_flags,
2367                                                     true);
2368         rcu_read_unlock();
2369
2370         return ret;
2371 }
2372
2373 static void htab_percpu_map_seq_show_elem(struct bpf_map *map, void *key,
2374                                           struct seq_file *m)
2375 {
2376         struct htab_elem *l;
2377         void __percpu *pptr;
2378         int cpu;
2379
2380         rcu_read_lock();
2381
2382         l = __htab_map_lookup_elem(map, key);
2383         if (!l) {
2384                 rcu_read_unlock();
2385                 return;
2386         }
2387
2388         btf_type_seq_show(map->btf, map->btf_key_type_id, key, m);
2389         seq_puts(m, ": {\n");
2390         pptr = htab_elem_get_ptr(l, map->key_size);
2391         for_each_possible_cpu(cpu) {
2392                 seq_printf(m, "\tcpu%d: ", cpu);
2393                 btf_type_seq_show(map->btf, map->btf_value_type_id,
2394                                   per_cpu_ptr(pptr, cpu), m);
2395                 seq_puts(m, "\n");
2396         }
2397         seq_puts(m, "}\n");
2398
2399         rcu_read_unlock();
2400 }
2401
2402 const struct bpf_map_ops htab_percpu_map_ops = {
2403         .map_meta_equal = bpf_map_meta_equal,
2404         .map_alloc_check = htab_map_alloc_check,
2405         .map_alloc = htab_map_alloc,
2406         .map_free = htab_map_free,
2407         .map_get_next_key = htab_map_get_next_key,
2408         .map_lookup_elem = htab_percpu_map_lookup_elem,
2409         .map_lookup_and_delete_elem = htab_percpu_map_lookup_and_delete_elem,
2410         .map_update_elem = htab_percpu_map_update_elem,
2411         .map_delete_elem = htab_map_delete_elem,
2412         .map_lookup_percpu_elem = htab_percpu_map_lookup_percpu_elem,
2413         .map_seq_show_elem = htab_percpu_map_seq_show_elem,
2414         .map_set_for_each_callback_args = map_set_for_each_callback_args,
2415         .map_for_each_callback = bpf_for_each_hash_elem,
2416         BATCH_OPS(htab_percpu),
2417         .map_btf_id = &htab_map_btf_ids[0],
2418         .iter_seq_info = &iter_seq_info,
2419 };
2420
2421 const struct bpf_map_ops htab_lru_percpu_map_ops = {
2422         .map_meta_equal = bpf_map_meta_equal,
2423         .map_alloc_check = htab_map_alloc_check,
2424         .map_alloc = htab_map_alloc,
2425         .map_free = htab_map_free,
2426         .map_get_next_key = htab_map_get_next_key,
2427         .map_lookup_elem = htab_lru_percpu_map_lookup_elem,
2428         .map_lookup_and_delete_elem = htab_lru_percpu_map_lookup_and_delete_elem,
2429         .map_update_elem = htab_lru_percpu_map_update_elem,
2430         .map_delete_elem = htab_lru_map_delete_elem,
2431         .map_lookup_percpu_elem = htab_lru_percpu_map_lookup_percpu_elem,
2432         .map_seq_show_elem = htab_percpu_map_seq_show_elem,
2433         .map_set_for_each_callback_args = map_set_for_each_callback_args,
2434         .map_for_each_callback = bpf_for_each_hash_elem,
2435         BATCH_OPS(htab_lru_percpu),
2436         .map_btf_id = &htab_map_btf_ids[0],
2437         .iter_seq_info = &iter_seq_info,
2438 };
2439
2440 static int fd_htab_map_alloc_check(union bpf_attr *attr)
2441 {
2442         if (attr->value_size != sizeof(u32))
2443                 return -EINVAL;
2444         return htab_map_alloc_check(attr);
2445 }
2446
2447 static void fd_htab_map_free(struct bpf_map *map)
2448 {
2449         struct bpf_htab *htab = container_of(map, struct bpf_htab, map);
2450         struct hlist_nulls_node *n;
2451         struct hlist_nulls_head *head;
2452         struct htab_elem *l;
2453         int i;
2454
2455         for (i = 0; i < htab->n_buckets; i++) {
2456                 head = select_bucket(htab, i);
2457
2458                 hlist_nulls_for_each_entry_safe(l, n, head, hash_node) {
2459                         void *ptr = fd_htab_map_get_ptr(map, l);
2460
2461                         map->ops->map_fd_put_ptr(ptr);
2462                 }
2463         }
2464
2465         htab_map_free(map);
2466 }
2467
2468 /* only called from syscall */
2469 int bpf_fd_htab_map_lookup_elem(struct bpf_map *map, void *key, u32 *value)
2470 {
2471         void **ptr;
2472         int ret = 0;
2473
2474         if (!map->ops->map_fd_sys_lookup_elem)
2475                 return -ENOTSUPP;
2476
2477         rcu_read_lock();
2478         ptr = htab_map_lookup_elem(map, key);
2479         if (ptr)
2480                 *value = map->ops->map_fd_sys_lookup_elem(READ_ONCE(*ptr));
2481         else
2482                 ret = -ENOENT;
2483         rcu_read_unlock();
2484
2485         return ret;
2486 }
2487
2488 /* only called from syscall */
2489 int bpf_fd_htab_map_update_elem(struct bpf_map *map, struct file *map_file,
2490                                 void *key, void *value, u64 map_flags)
2491 {
2492         void *ptr;
2493         int ret;
2494         u32 ufd = *(u32 *)value;
2495
2496         ptr = map->ops->map_fd_get_ptr(map, map_file, ufd);
2497         if (IS_ERR(ptr))
2498                 return PTR_ERR(ptr);
2499
2500         ret = htab_map_update_elem(map, key, &ptr, map_flags);
2501         if (ret)
2502                 map->ops->map_fd_put_ptr(ptr);
2503
2504         return ret;
2505 }
2506
2507 static struct bpf_map *htab_of_map_alloc(union bpf_attr *attr)
2508 {
2509         struct bpf_map *map, *inner_map_meta;
2510
2511         inner_map_meta = bpf_map_meta_alloc(attr->inner_map_fd);
2512         if (IS_ERR(inner_map_meta))
2513                 return inner_map_meta;
2514
2515         map = htab_map_alloc(attr);
2516         if (IS_ERR(map)) {
2517                 bpf_map_meta_free(inner_map_meta);
2518                 return map;
2519         }
2520
2521         map->inner_map_meta = inner_map_meta;
2522
2523         return map;
2524 }
2525
2526 static void *htab_of_map_lookup_elem(struct bpf_map *map, void *key)
2527 {
2528         struct bpf_map **inner_map  = htab_map_lookup_elem(map, key);
2529
2530         if (!inner_map)
2531                 return NULL;
2532
2533         return READ_ONCE(*inner_map);
2534 }
2535
2536 static int htab_of_map_gen_lookup(struct bpf_map *map,
2537                                   struct bpf_insn *insn_buf)
2538 {
2539         struct bpf_insn *insn = insn_buf;
2540         const int ret = BPF_REG_0;
2541
2542         BUILD_BUG_ON(!__same_type(&__htab_map_lookup_elem,
2543                      (void *(*)(struct bpf_map *map, void *key))NULL));
2544         *insn++ = BPF_EMIT_CALL(__htab_map_lookup_elem);
2545         *insn++ = BPF_JMP_IMM(BPF_JEQ, ret, 0, 2);
2546         *insn++ = BPF_ALU64_IMM(BPF_ADD, ret,
2547                                 offsetof(struct htab_elem, key) +
2548                                 round_up(map->key_size, 8));
2549         *insn++ = BPF_LDX_MEM(BPF_DW, ret, ret, 0);
2550
2551         return insn - insn_buf;
2552 }
2553
2554 static void htab_of_map_free(struct bpf_map *map)
2555 {
2556         bpf_map_meta_free(map->inner_map_meta);
2557         fd_htab_map_free(map);
2558 }
2559
2560 const struct bpf_map_ops htab_of_maps_map_ops = {
2561         .map_alloc_check = fd_htab_map_alloc_check,
2562         .map_alloc = htab_of_map_alloc,
2563         .map_free = htab_of_map_free,
2564         .map_get_next_key = htab_map_get_next_key,
2565         .map_lookup_elem = htab_of_map_lookup_elem,
2566         .map_delete_elem = htab_map_delete_elem,
2567         .map_fd_get_ptr = bpf_map_fd_get_ptr,
2568         .map_fd_put_ptr = bpf_map_fd_put_ptr,
2569         .map_fd_sys_lookup_elem = bpf_map_fd_sys_lookup_elem,
2570         .map_gen_lookup = htab_of_map_gen_lookup,
2571         .map_check_btf = map_check_no_btf,
2572         BATCH_OPS(htab),
2573         .map_btf_id = &htab_map_btf_ids[0],
2574 };