Merge branch 'Add support for kptrs in more BPF maps'
[platform/kernel/linux-starfive.git] / kernel / bpf / bpf_local_storage.c
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2019 Facebook  */
3 #include <linux/rculist.h>
4 #include <linux/list.h>
5 #include <linux/hash.h>
6 #include <linux/types.h>
7 #include <linux/spinlock.h>
8 #include <linux/bpf.h>
9 #include <linux/btf_ids.h>
10 #include <linux/bpf_local_storage.h>
11 #include <net/sock.h>
12 #include <uapi/linux/sock_diag.h>
13 #include <uapi/linux/btf.h>
14 #include <linux/rcupdate.h>
15 #include <linux/rcupdate_trace.h>
16 #include <linux/rcupdate_wait.h>
17
18 #define BPF_LOCAL_STORAGE_CREATE_FLAG_MASK (BPF_F_NO_PREALLOC | BPF_F_CLONE)
19
20 static struct bpf_local_storage_map_bucket *
21 select_bucket(struct bpf_local_storage_map *smap,
22               struct bpf_local_storage_elem *selem)
23 {
24         return &smap->buckets[hash_ptr(selem, smap->bucket_log)];
25 }
26
27 static int mem_charge(struct bpf_local_storage_map *smap, void *owner, u32 size)
28 {
29         struct bpf_map *map = &smap->map;
30
31         if (!map->ops->map_local_storage_charge)
32                 return 0;
33
34         return map->ops->map_local_storage_charge(smap, owner, size);
35 }
36
37 static void mem_uncharge(struct bpf_local_storage_map *smap, void *owner,
38                          u32 size)
39 {
40         struct bpf_map *map = &smap->map;
41
42         if (map->ops->map_local_storage_uncharge)
43                 map->ops->map_local_storage_uncharge(smap, owner, size);
44 }
45
46 static struct bpf_local_storage __rcu **
47 owner_storage(struct bpf_local_storage_map *smap, void *owner)
48 {
49         struct bpf_map *map = &smap->map;
50
51         return map->ops->map_owner_storage_ptr(owner);
52 }
53
54 static bool selem_linked_to_storage_lockless(const struct bpf_local_storage_elem *selem)
55 {
56         return !hlist_unhashed_lockless(&selem->snode);
57 }
58
59 static bool selem_linked_to_storage(const struct bpf_local_storage_elem *selem)
60 {
61         return !hlist_unhashed(&selem->snode);
62 }
63
64 static bool selem_linked_to_map_lockless(const struct bpf_local_storage_elem *selem)
65 {
66         return !hlist_unhashed_lockless(&selem->map_node);
67 }
68
69 static bool selem_linked_to_map(const struct bpf_local_storage_elem *selem)
70 {
71         return !hlist_unhashed(&selem->map_node);
72 }
73
74 struct bpf_local_storage_elem *
75 bpf_selem_alloc(struct bpf_local_storage_map *smap, void *owner,
76                 void *value, bool charge_mem, gfp_t gfp_flags)
77 {
78         struct bpf_local_storage_elem *selem;
79
80         if (charge_mem && mem_charge(smap, owner, smap->elem_size))
81                 return NULL;
82
83         selem = bpf_map_kzalloc(&smap->map, smap->elem_size,
84                                 gfp_flags | __GFP_NOWARN);
85         if (selem) {
86                 if (value)
87                         copy_map_value(&smap->map, SDATA(selem)->data, value);
88                 /* No need to call check_and_init_map_value as memory is zero init */
89                 return selem;
90         }
91
92         if (charge_mem)
93                 mem_uncharge(smap, owner, smap->elem_size);
94
95         return NULL;
96 }
97
98 void bpf_local_storage_free_rcu(struct rcu_head *rcu)
99 {
100         struct bpf_local_storage *local_storage;
101
102         /* If RCU Tasks Trace grace period implies RCU grace period, do
103          * kfree(), else do kfree_rcu().
104          */
105         local_storage = container_of(rcu, struct bpf_local_storage, rcu);
106         if (rcu_trace_implies_rcu_gp())
107                 kfree(local_storage);
108         else
109                 kfree_rcu(local_storage, rcu);
110 }
111
112 static void bpf_selem_free_rcu(struct rcu_head *rcu)
113 {
114         struct bpf_local_storage_elem *selem;
115
116         selem = container_of(rcu, struct bpf_local_storage_elem, rcu);
117         /* The can_use_smap bool is set whenever we need to free additional
118          * fields in selem data before freeing selem. bpf_local_storage_map_free
119          * only executes rcu_barrier to wait for RCU callbacks when it has
120          * special fields, hence we can only conditionally dereference smap, as
121          * by this time the map might have already been freed without waiting
122          * for our call_rcu callback if it did not have any special fields.
123          */
124         if (selem->can_use_smap)
125                 bpf_obj_free_fields(SDATA(selem)->smap->map.record, SDATA(selem)->data);
126         kfree(selem);
127 }
128
129 static void bpf_selem_free_tasks_trace_rcu(struct rcu_head *rcu)
130 {
131         /* Free directly if Tasks Trace RCU GP also implies RCU GP */
132         if (rcu_trace_implies_rcu_gp())
133                 bpf_selem_free_rcu(rcu);
134         else
135                 call_rcu(rcu, bpf_selem_free_rcu);
136 }
137
138 /* local_storage->lock must be held and selem->local_storage == local_storage.
139  * The caller must ensure selem->smap is still valid to be
140  * dereferenced for its smap->elem_size and smap->cache_idx.
141  */
142 static bool bpf_selem_unlink_storage_nolock(struct bpf_local_storage *local_storage,
143                                             struct bpf_local_storage_elem *selem,
144                                             bool uncharge_mem, bool use_trace_rcu)
145 {
146         struct bpf_local_storage_map *smap;
147         bool free_local_storage;
148         void *owner;
149
150         smap = rcu_dereference_check(SDATA(selem)->smap, bpf_rcu_lock_held());
151         owner = local_storage->owner;
152
153         /* All uncharging on the owner must be done first.
154          * The owner may be freed once the last selem is unlinked
155          * from local_storage.
156          */
157         if (uncharge_mem)
158                 mem_uncharge(smap, owner, smap->elem_size);
159
160         free_local_storage = hlist_is_singular_node(&selem->snode,
161                                                     &local_storage->list);
162         if (free_local_storage) {
163                 mem_uncharge(smap, owner, sizeof(struct bpf_local_storage));
164                 local_storage->owner = NULL;
165
166                 /* After this RCU_INIT, owner may be freed and cannot be used */
167                 RCU_INIT_POINTER(*owner_storage(smap, owner), NULL);
168
169                 /* local_storage is not freed now.  local_storage->lock is
170                  * still held and raw_spin_unlock_bh(&local_storage->lock)
171                  * will be done by the caller.
172                  *
173                  * Although the unlock will be done under
174                  * rcu_read_lock(),  it is more intuitive to
175                  * read if the freeing of the storage is done
176                  * after the raw_spin_unlock_bh(&local_storage->lock).
177                  *
178                  * Hence, a "bool free_local_storage" is returned
179                  * to the caller which then calls then frees the storage after
180                  * all the RCU grace periods have expired.
181                  */
182         }
183         hlist_del_init_rcu(&selem->snode);
184         if (rcu_access_pointer(local_storage->cache[smap->cache_idx]) ==
185             SDATA(selem))
186                 RCU_INIT_POINTER(local_storage->cache[smap->cache_idx], NULL);
187
188         if (use_trace_rcu)
189                 call_rcu_tasks_trace(&selem->rcu, bpf_selem_free_tasks_trace_rcu);
190         else
191                 call_rcu(&selem->rcu, bpf_selem_free_rcu);
192
193         return free_local_storage;
194 }
195
196 static void __bpf_selem_unlink_storage(struct bpf_local_storage_elem *selem,
197                                        bool use_trace_rcu)
198 {
199         struct bpf_local_storage *local_storage;
200         bool free_local_storage = false;
201         unsigned long flags;
202
203         if (unlikely(!selem_linked_to_storage_lockless(selem)))
204                 /* selem has already been unlinked from sk */
205                 return;
206
207         local_storage = rcu_dereference_check(selem->local_storage,
208                                               bpf_rcu_lock_held());
209         raw_spin_lock_irqsave(&local_storage->lock, flags);
210         if (likely(selem_linked_to_storage(selem)))
211                 free_local_storage = bpf_selem_unlink_storage_nolock(
212                         local_storage, selem, true, use_trace_rcu);
213         raw_spin_unlock_irqrestore(&local_storage->lock, flags);
214
215         if (free_local_storage) {
216                 if (use_trace_rcu)
217                         call_rcu_tasks_trace(&local_storage->rcu,
218                                      bpf_local_storage_free_rcu);
219                 else
220                         kfree_rcu(local_storage, rcu);
221         }
222 }
223
224 void bpf_selem_link_storage_nolock(struct bpf_local_storage *local_storage,
225                                    struct bpf_local_storage_elem *selem)
226 {
227         RCU_INIT_POINTER(selem->local_storage, local_storage);
228         hlist_add_head_rcu(&selem->snode, &local_storage->list);
229 }
230
231 void bpf_selem_unlink_map(struct bpf_local_storage_elem *selem)
232 {
233         struct bpf_local_storage_map *smap;
234         struct bpf_local_storage_map_bucket *b;
235         unsigned long flags;
236
237         if (unlikely(!selem_linked_to_map_lockless(selem)))
238                 /* selem has already be unlinked from smap */
239                 return;
240
241         smap = rcu_dereference_check(SDATA(selem)->smap, bpf_rcu_lock_held());
242         b = select_bucket(smap, selem);
243         raw_spin_lock_irqsave(&b->lock, flags);
244         if (likely(selem_linked_to_map(selem)))
245                 hlist_del_init_rcu(&selem->map_node);
246         raw_spin_unlock_irqrestore(&b->lock, flags);
247 }
248
249 void bpf_selem_link_map(struct bpf_local_storage_map *smap,
250                         struct bpf_local_storage_elem *selem)
251 {
252         struct bpf_local_storage_map_bucket *b = select_bucket(smap, selem);
253         unsigned long flags;
254
255         raw_spin_lock_irqsave(&b->lock, flags);
256         RCU_INIT_POINTER(SDATA(selem)->smap, smap);
257         hlist_add_head_rcu(&selem->map_node, &b->list);
258         raw_spin_unlock_irqrestore(&b->lock, flags);
259
260         /* If our data will have special fields, smap will wait for us to use
261          * its record in bpf_selem_free_* RCU callbacks before freeing itself.
262          */
263         selem->can_use_smap = !IS_ERR_OR_NULL(smap->map.record);
264 }
265
266 void bpf_selem_unlink(struct bpf_local_storage_elem *selem, bool use_trace_rcu)
267 {
268         /* Always unlink from map before unlinking from local_storage
269          * because selem will be freed after successfully unlinked from
270          * the local_storage.
271          */
272         bpf_selem_unlink_map(selem);
273         __bpf_selem_unlink_storage(selem, use_trace_rcu);
274 }
275
276 /* If cacheit_lockit is false, this lookup function is lockless */
277 struct bpf_local_storage_data *
278 bpf_local_storage_lookup(struct bpf_local_storage *local_storage,
279                          struct bpf_local_storage_map *smap,
280                          bool cacheit_lockit)
281 {
282         struct bpf_local_storage_data *sdata;
283         struct bpf_local_storage_elem *selem;
284
285         /* Fast path (cache hit) */
286         sdata = rcu_dereference_check(local_storage->cache[smap->cache_idx],
287                                       bpf_rcu_lock_held());
288         if (sdata && rcu_access_pointer(sdata->smap) == smap)
289                 return sdata;
290
291         /* Slow path (cache miss) */
292         hlist_for_each_entry_rcu(selem, &local_storage->list, snode,
293                                   rcu_read_lock_trace_held())
294                 if (rcu_access_pointer(SDATA(selem)->smap) == smap)
295                         break;
296
297         if (!selem)
298                 return NULL;
299
300         sdata = SDATA(selem);
301         if (cacheit_lockit) {
302                 unsigned long flags;
303
304                 /* spinlock is needed to avoid racing with the
305                  * parallel delete.  Otherwise, publishing an already
306                  * deleted sdata to the cache will become a use-after-free
307                  * problem in the next bpf_local_storage_lookup().
308                  */
309                 raw_spin_lock_irqsave(&local_storage->lock, flags);
310                 if (selem_linked_to_storage(selem))
311                         rcu_assign_pointer(local_storage->cache[smap->cache_idx],
312                                            sdata);
313                 raw_spin_unlock_irqrestore(&local_storage->lock, flags);
314         }
315
316         return sdata;
317 }
318
319 static int check_flags(const struct bpf_local_storage_data *old_sdata,
320                        u64 map_flags)
321 {
322         if (old_sdata && (map_flags & ~BPF_F_LOCK) == BPF_NOEXIST)
323                 /* elem already exists */
324                 return -EEXIST;
325
326         if (!old_sdata && (map_flags & ~BPF_F_LOCK) == BPF_EXIST)
327                 /* elem doesn't exist, cannot update it */
328                 return -ENOENT;
329
330         return 0;
331 }
332
333 int bpf_local_storage_alloc(void *owner,
334                             struct bpf_local_storage_map *smap,
335                             struct bpf_local_storage_elem *first_selem,
336                             gfp_t gfp_flags)
337 {
338         struct bpf_local_storage *prev_storage, *storage;
339         struct bpf_local_storage **owner_storage_ptr;
340         int err;
341
342         err = mem_charge(smap, owner, sizeof(*storage));
343         if (err)
344                 return err;
345
346         storage = bpf_map_kzalloc(&smap->map, sizeof(*storage),
347                                   gfp_flags | __GFP_NOWARN);
348         if (!storage) {
349                 err = -ENOMEM;
350                 goto uncharge;
351         }
352
353         INIT_HLIST_HEAD(&storage->list);
354         raw_spin_lock_init(&storage->lock);
355         storage->owner = owner;
356
357         bpf_selem_link_storage_nolock(storage, first_selem);
358         bpf_selem_link_map(smap, first_selem);
359
360         owner_storage_ptr =
361                 (struct bpf_local_storage **)owner_storage(smap, owner);
362         /* Publish storage to the owner.
363          * Instead of using any lock of the kernel object (i.e. owner),
364          * cmpxchg will work with any kernel object regardless what
365          * the running context is, bh, irq...etc.
366          *
367          * From now on, the owner->storage pointer (e.g. sk->sk_bpf_storage)
368          * is protected by the storage->lock.  Hence, when freeing
369          * the owner->storage, the storage->lock must be held before
370          * setting owner->storage ptr to NULL.
371          */
372         prev_storage = cmpxchg(owner_storage_ptr, NULL, storage);
373         if (unlikely(prev_storage)) {
374                 bpf_selem_unlink_map(first_selem);
375                 err = -EAGAIN;
376                 goto uncharge;
377
378                 /* Note that even first_selem was linked to smap's
379                  * bucket->list, first_selem can be freed immediately
380                  * (instead of kfree_rcu) because
381                  * bpf_local_storage_map_free() does a
382                  * synchronize_rcu_mult (waiting for both sleepable and
383                  * normal programs) before walking the bucket->list.
384                  * Hence, no one is accessing selem from the
385                  * bucket->list under rcu_read_lock().
386                  */
387         }
388
389         return 0;
390
391 uncharge:
392         kfree(storage);
393         mem_uncharge(smap, owner, sizeof(*storage));
394         return err;
395 }
396
397 /* sk cannot be going away because it is linking new elem
398  * to sk->sk_bpf_storage. (i.e. sk->sk_refcnt cannot be 0).
399  * Otherwise, it will become a leak (and other memory issues
400  * during map destruction).
401  */
402 struct bpf_local_storage_data *
403 bpf_local_storage_update(void *owner, struct bpf_local_storage_map *smap,
404                          void *value, u64 map_flags, gfp_t gfp_flags)
405 {
406         struct bpf_local_storage_data *old_sdata = NULL;
407         struct bpf_local_storage_elem *selem = NULL;
408         struct bpf_local_storage *local_storage;
409         unsigned long flags;
410         int err;
411
412         /* BPF_EXIST and BPF_NOEXIST cannot be both set */
413         if (unlikely((map_flags & ~BPF_F_LOCK) > BPF_EXIST) ||
414             /* BPF_F_LOCK can only be used in a value with spin_lock */
415             unlikely((map_flags & BPF_F_LOCK) &&
416                      !btf_record_has_field(smap->map.record, BPF_SPIN_LOCK)))
417                 return ERR_PTR(-EINVAL);
418
419         if (gfp_flags == GFP_KERNEL && (map_flags & ~BPF_F_LOCK) != BPF_NOEXIST)
420                 return ERR_PTR(-EINVAL);
421
422         local_storage = rcu_dereference_check(*owner_storage(smap, owner),
423                                               bpf_rcu_lock_held());
424         if (!local_storage || hlist_empty(&local_storage->list)) {
425                 /* Very first elem for the owner */
426                 err = check_flags(NULL, map_flags);
427                 if (err)
428                         return ERR_PTR(err);
429
430                 selem = bpf_selem_alloc(smap, owner, value, true, gfp_flags);
431                 if (!selem)
432                         return ERR_PTR(-ENOMEM);
433
434                 err = bpf_local_storage_alloc(owner, smap, selem, gfp_flags);
435                 if (err) {
436                         kfree(selem);
437                         mem_uncharge(smap, owner, smap->elem_size);
438                         return ERR_PTR(err);
439                 }
440
441                 return SDATA(selem);
442         }
443
444         if ((map_flags & BPF_F_LOCK) && !(map_flags & BPF_NOEXIST)) {
445                 /* Hoping to find an old_sdata to do inline update
446                  * such that it can avoid taking the local_storage->lock
447                  * and changing the lists.
448                  */
449                 old_sdata =
450                         bpf_local_storage_lookup(local_storage, smap, false);
451                 err = check_flags(old_sdata, map_flags);
452                 if (err)
453                         return ERR_PTR(err);
454                 if (old_sdata && selem_linked_to_storage_lockless(SELEM(old_sdata))) {
455                         copy_map_value_locked(&smap->map, old_sdata->data,
456                                               value, false);
457                         return old_sdata;
458                 }
459         }
460
461         if (gfp_flags == GFP_KERNEL) {
462                 selem = bpf_selem_alloc(smap, owner, value, true, gfp_flags);
463                 if (!selem)
464                         return ERR_PTR(-ENOMEM);
465         }
466
467         raw_spin_lock_irqsave(&local_storage->lock, flags);
468
469         /* Recheck local_storage->list under local_storage->lock */
470         if (unlikely(hlist_empty(&local_storage->list))) {
471                 /* A parallel del is happening and local_storage is going
472                  * away.  It has just been checked before, so very
473                  * unlikely.  Return instead of retry to keep things
474                  * simple.
475                  */
476                 err = -EAGAIN;
477                 goto unlock_err;
478         }
479
480         old_sdata = bpf_local_storage_lookup(local_storage, smap, false);
481         err = check_flags(old_sdata, map_flags);
482         if (err)
483                 goto unlock_err;
484
485         if (old_sdata && (map_flags & BPF_F_LOCK)) {
486                 copy_map_value_locked(&smap->map, old_sdata->data, value,
487                                       false);
488                 selem = SELEM(old_sdata);
489                 goto unlock;
490         }
491
492         if (gfp_flags != GFP_KERNEL) {
493                 /* local_storage->lock is held.  Hence, we are sure
494                  * we can unlink and uncharge the old_sdata successfully
495                  * later.  Hence, instead of charging the new selem now
496                  * and then uncharge the old selem later (which may cause
497                  * a potential but unnecessary charge failure),  avoid taking
498                  * a charge at all here (the "!old_sdata" check) and the
499                  * old_sdata will not be uncharged later during
500                  * bpf_selem_unlink_storage_nolock().
501                  */
502                 selem = bpf_selem_alloc(smap, owner, value, !old_sdata, gfp_flags);
503                 if (!selem) {
504                         err = -ENOMEM;
505                         goto unlock_err;
506                 }
507         }
508
509         /* First, link the new selem to the map */
510         bpf_selem_link_map(smap, selem);
511
512         /* Second, link (and publish) the new selem to local_storage */
513         bpf_selem_link_storage_nolock(local_storage, selem);
514
515         /* Third, remove old selem, SELEM(old_sdata) */
516         if (old_sdata) {
517                 bpf_selem_unlink_map(SELEM(old_sdata));
518                 bpf_selem_unlink_storage_nolock(local_storage, SELEM(old_sdata),
519                                                 false, true);
520         }
521
522 unlock:
523         raw_spin_unlock_irqrestore(&local_storage->lock, flags);
524         return SDATA(selem);
525
526 unlock_err:
527         raw_spin_unlock_irqrestore(&local_storage->lock, flags);
528         if (selem) {
529                 mem_uncharge(smap, owner, smap->elem_size);
530                 kfree(selem);
531         }
532         return ERR_PTR(err);
533 }
534
535 static u16 bpf_local_storage_cache_idx_get(struct bpf_local_storage_cache *cache)
536 {
537         u64 min_usage = U64_MAX;
538         u16 i, res = 0;
539
540         spin_lock(&cache->idx_lock);
541
542         for (i = 0; i < BPF_LOCAL_STORAGE_CACHE_SIZE; i++) {
543                 if (cache->idx_usage_counts[i] < min_usage) {
544                         min_usage = cache->idx_usage_counts[i];
545                         res = i;
546
547                         /* Found a free cache_idx */
548                         if (!min_usage)
549                                 break;
550                 }
551         }
552         cache->idx_usage_counts[res]++;
553
554         spin_unlock(&cache->idx_lock);
555
556         return res;
557 }
558
559 static void bpf_local_storage_cache_idx_free(struct bpf_local_storage_cache *cache,
560                                              u16 idx)
561 {
562         spin_lock(&cache->idx_lock);
563         cache->idx_usage_counts[idx]--;
564         spin_unlock(&cache->idx_lock);
565 }
566
567 int bpf_local_storage_map_alloc_check(union bpf_attr *attr)
568 {
569         if (attr->map_flags & ~BPF_LOCAL_STORAGE_CREATE_FLAG_MASK ||
570             !(attr->map_flags & BPF_F_NO_PREALLOC) ||
571             attr->max_entries ||
572             attr->key_size != sizeof(int) || !attr->value_size ||
573             /* Enforce BTF for userspace sk dumping */
574             !attr->btf_key_type_id || !attr->btf_value_type_id)
575                 return -EINVAL;
576
577         if (!bpf_capable())
578                 return -EPERM;
579
580         if (attr->value_size > BPF_LOCAL_STORAGE_MAX_VALUE_SIZE)
581                 return -E2BIG;
582
583         return 0;
584 }
585
586 static struct bpf_local_storage_map *__bpf_local_storage_map_alloc(union bpf_attr *attr)
587 {
588         struct bpf_local_storage_map *smap;
589         unsigned int i;
590         u32 nbuckets;
591
592         smap = bpf_map_area_alloc(sizeof(*smap), NUMA_NO_NODE);
593         if (!smap)
594                 return ERR_PTR(-ENOMEM);
595         bpf_map_init_from_attr(&smap->map, attr);
596
597         nbuckets = roundup_pow_of_two(num_possible_cpus());
598         /* Use at least 2 buckets, select_bucket() is undefined behavior with 1 bucket */
599         nbuckets = max_t(u32, 2, nbuckets);
600         smap->bucket_log = ilog2(nbuckets);
601
602         smap->buckets = bpf_map_kvcalloc(&smap->map, sizeof(*smap->buckets),
603                                          nbuckets, GFP_USER | __GFP_NOWARN);
604         if (!smap->buckets) {
605                 bpf_map_area_free(smap);
606                 return ERR_PTR(-ENOMEM);
607         }
608
609         for (i = 0; i < nbuckets; i++) {
610                 INIT_HLIST_HEAD(&smap->buckets[i].list);
611                 raw_spin_lock_init(&smap->buckets[i].lock);
612         }
613
614         smap->elem_size = offsetof(struct bpf_local_storage_elem,
615                                    sdata.data[attr->value_size]);
616
617         return smap;
618 }
619
620 int bpf_local_storage_map_check_btf(const struct bpf_map *map,
621                                     const struct btf *btf,
622                                     const struct btf_type *key_type,
623                                     const struct btf_type *value_type)
624 {
625         u32 int_data;
626
627         if (BTF_INFO_KIND(key_type->info) != BTF_KIND_INT)
628                 return -EINVAL;
629
630         int_data = *(u32 *)(key_type + 1);
631         if (BTF_INT_BITS(int_data) != 32 || BTF_INT_OFFSET(int_data))
632                 return -EINVAL;
633
634         return 0;
635 }
636
637 bool bpf_local_storage_unlink_nolock(struct bpf_local_storage *local_storage)
638 {
639         struct bpf_local_storage_elem *selem;
640         bool free_storage = false;
641         struct hlist_node *n;
642
643         /* Neither the bpf_prog nor the bpf_map's syscall
644          * could be modifying the local_storage->list now.
645          * Thus, no elem can be added to or deleted from the
646          * local_storage->list by the bpf_prog or by the bpf_map's syscall.
647          *
648          * It is racing with bpf_local_storage_map_free() alone
649          * when unlinking elem from the local_storage->list and
650          * the map's bucket->list.
651          */
652         hlist_for_each_entry_safe(selem, n, &local_storage->list, snode) {
653                 /* Always unlink from map before unlinking from
654                  * local_storage.
655                  */
656                 bpf_selem_unlink_map(selem);
657                 /* If local_storage list has only one element, the
658                  * bpf_selem_unlink_storage_nolock() will return true.
659                  * Otherwise, it will return false. The current loop iteration
660                  * intends to remove all local storage. So the last iteration
661                  * of the loop will set the free_cgroup_storage to true.
662                  */
663                 free_storage = bpf_selem_unlink_storage_nolock(
664                         local_storage, selem, false, false);
665         }
666
667         return free_storage;
668 }
669
670 struct bpf_map *
671 bpf_local_storage_map_alloc(union bpf_attr *attr,
672                             struct bpf_local_storage_cache *cache)
673 {
674         struct bpf_local_storage_map *smap;
675
676         smap = __bpf_local_storage_map_alloc(attr);
677         if (IS_ERR(smap))
678                 return ERR_CAST(smap);
679
680         smap->cache_idx = bpf_local_storage_cache_idx_get(cache);
681         return &smap->map;
682 }
683
684 void bpf_local_storage_map_free(struct bpf_map *map,
685                                 struct bpf_local_storage_cache *cache,
686                                 int __percpu *busy_counter)
687 {
688         struct bpf_local_storage_map_bucket *b;
689         struct bpf_local_storage_elem *selem;
690         struct bpf_local_storage_map *smap;
691         unsigned int i;
692
693         smap = (struct bpf_local_storage_map *)map;
694         bpf_local_storage_cache_idx_free(cache, smap->cache_idx);
695
696         /* Note that this map might be concurrently cloned from
697          * bpf_sk_storage_clone. Wait for any existing bpf_sk_storage_clone
698          * RCU read section to finish before proceeding. New RCU
699          * read sections should be prevented via bpf_map_inc_not_zero.
700          */
701         synchronize_rcu();
702
703         /* bpf prog and the userspace can no longer access this map
704          * now.  No new selem (of this map) can be added
705          * to the owner->storage or to the map bucket's list.
706          *
707          * The elem of this map can be cleaned up here
708          * or when the storage is freed e.g.
709          * by bpf_sk_storage_free() during __sk_destruct().
710          */
711         for (i = 0; i < (1U << smap->bucket_log); i++) {
712                 b = &smap->buckets[i];
713
714                 rcu_read_lock();
715                 /* No one is adding to b->list now */
716                 while ((selem = hlist_entry_safe(
717                                 rcu_dereference_raw(hlist_first_rcu(&b->list)),
718                                 struct bpf_local_storage_elem, map_node))) {
719                         if (busy_counter) {
720                                 migrate_disable();
721                                 this_cpu_inc(*busy_counter);
722                         }
723                         bpf_selem_unlink(selem, false);
724                         if (busy_counter) {
725                                 this_cpu_dec(*busy_counter);
726                                 migrate_enable();
727                         }
728                         cond_resched_rcu();
729                 }
730                 rcu_read_unlock();
731         }
732
733         /* While freeing the storage we may still need to access the map.
734          *
735          * e.g. when bpf_sk_storage_free() has unlinked selem from the map
736          * which then made the above while((selem = ...)) loop
737          * exit immediately.
738          *
739          * However, while freeing the storage one still needs to access the
740          * smap->elem_size to do the uncharging in
741          * bpf_selem_unlink_storage_nolock().
742          *
743          * Hence, wait another rcu grace period for the storage to be freed.
744          */
745         synchronize_rcu();
746
747         /* Only delay freeing of smap, buckets are not needed anymore */
748         kvfree(smap->buckets);
749
750         /* When local storage has special fields, callbacks for
751          * bpf_selem_free_rcu and bpf_selem_free_tasks_trace_rcu will keep using
752          * the map BTF record, we need to execute an RCU barrier to wait for
753          * them as the record will be freed right after our map_free callback.
754          */
755         if (!IS_ERR_OR_NULL(smap->map.record)) {
756                 rcu_barrier_tasks_trace();
757                 /* We cannot skip rcu_barrier() when rcu_trace_implies_rcu_gp()
758                  * is true, because while call_rcu invocation is skipped in that
759                  * case in bpf_selem_free_tasks_trace_rcu (and all local storage
760                  * maps pass use_trace_rcu = true), there can be call_rcu
761                  * callbacks based on use_trace_rcu = false in the earlier while
762                  * ((selem = ...)) loop or from bpf_local_storage_unlink_nolock
763                  * called from owner's free path.
764                  */
765                 rcu_barrier();
766         }
767         bpf_map_area_free(smap);
768 }