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