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