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>
9 #include <linux/btf_ids.h>
10 #include <linux/bpf_local_storage.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>
18 #define BPF_LOCAL_STORAGE_CREATE_FLAG_MASK (BPF_F_NO_PREALLOC | BPF_F_CLONE)
20 static struct bpf_local_storage_map_bucket *
21 select_bucket(struct bpf_local_storage_map *smap,
22 struct bpf_local_storage_elem *selem)
24 return &smap->buckets[hash_ptr(selem, smap->bucket_log)];
27 static int mem_charge(struct bpf_local_storage_map *smap, void *owner, u32 size)
29 struct bpf_map *map = &smap->map;
31 if (!map->ops->map_local_storage_charge)
34 return map->ops->map_local_storage_charge(smap, owner, size);
37 static void mem_uncharge(struct bpf_local_storage_map *smap, void *owner,
40 struct bpf_map *map = &smap->map;
42 if (map->ops->map_local_storage_uncharge)
43 map->ops->map_local_storage_uncharge(smap, owner, size);
46 static struct bpf_local_storage __rcu **
47 owner_storage(struct bpf_local_storage_map *smap, void *owner)
49 struct bpf_map *map = &smap->map;
51 return map->ops->map_owner_storage_ptr(owner);
54 static bool selem_linked_to_storage_lockless(const struct bpf_local_storage_elem *selem)
56 return !hlist_unhashed_lockless(&selem->snode);
59 static bool selem_linked_to_storage(const struct bpf_local_storage_elem *selem)
61 return !hlist_unhashed(&selem->snode);
64 static bool selem_linked_to_map_lockless(const struct bpf_local_storage_elem *selem)
66 return !hlist_unhashed_lockless(&selem->map_node);
69 static bool selem_linked_to_map(const struct bpf_local_storage_elem *selem)
71 return !hlist_unhashed(&selem->map_node);
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)
78 struct bpf_local_storage_elem *selem;
80 if (charge_mem && mem_charge(smap, owner, smap->elem_size))
83 selem = bpf_map_kzalloc(&smap->map, smap->elem_size,
84 gfp_flags | __GFP_NOWARN);
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 */
93 mem_uncharge(smap, owner, smap->elem_size);
98 void bpf_local_storage_free_rcu(struct rcu_head *rcu)
100 struct bpf_local_storage *local_storage;
102 /* If RCU Tasks Trace grace period implies RCU grace period, do
103 * kfree(), else do kfree_rcu().
105 local_storage = container_of(rcu, struct bpf_local_storage, rcu);
106 if (rcu_trace_implies_rcu_gp())
107 kfree(local_storage);
109 kfree_rcu(local_storage, rcu);
112 static void bpf_selem_free_rcu(struct rcu_head *rcu)
114 struct bpf_local_storage_elem *selem;
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.
124 if (selem->can_use_smap)
125 bpf_obj_free_fields(SDATA(selem)->smap->map.record, SDATA(selem)->data);
129 static void bpf_selem_free_tasks_trace_rcu(struct rcu_head *rcu)
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);
135 call_rcu(rcu, bpf_selem_free_rcu);
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.
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)
146 struct bpf_local_storage_map *smap;
147 bool free_local_storage;
150 smap = rcu_dereference_check(SDATA(selem)->smap, bpf_rcu_lock_held());
151 owner = local_storage->owner;
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.
158 mem_uncharge(smap, owner, smap->elem_size);
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;
166 /* After this RCU_INIT, owner may be freed and cannot be used */
167 RCU_INIT_POINTER(*owner_storage(smap, owner), NULL);
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.
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).
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.
183 hlist_del_init_rcu(&selem->snode);
184 if (rcu_access_pointer(local_storage->cache[smap->cache_idx]) ==
186 RCU_INIT_POINTER(local_storage->cache[smap->cache_idx], NULL);
189 call_rcu_tasks_trace(&selem->rcu, bpf_selem_free_tasks_trace_rcu);
191 call_rcu(&selem->rcu, bpf_selem_free_rcu);
193 return free_local_storage;
196 static void __bpf_selem_unlink_storage(struct bpf_local_storage_elem *selem,
199 struct bpf_local_storage *local_storage;
200 bool free_local_storage = false;
203 if (unlikely(!selem_linked_to_storage_lockless(selem)))
204 /* selem has already been unlinked from sk */
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);
215 if (free_local_storage) {
217 call_rcu_tasks_trace(&local_storage->rcu,
218 bpf_local_storage_free_rcu);
220 kfree_rcu(local_storage, rcu);
224 void bpf_selem_link_storage_nolock(struct bpf_local_storage *local_storage,
225 struct bpf_local_storage_elem *selem)
227 RCU_INIT_POINTER(selem->local_storage, local_storage);
228 hlist_add_head_rcu(&selem->snode, &local_storage->list);
231 void bpf_selem_unlink_map(struct bpf_local_storage_elem *selem)
233 struct bpf_local_storage_map *smap;
234 struct bpf_local_storage_map_bucket *b;
237 if (unlikely(!selem_linked_to_map_lockless(selem)))
238 /* selem has already be unlinked from smap */
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);
249 void bpf_selem_link_map(struct bpf_local_storage_map *smap,
250 struct bpf_local_storage_elem *selem)
252 struct bpf_local_storage_map_bucket *b = select_bucket(smap, selem);
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);
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.
263 selem->can_use_smap = !IS_ERR_OR_NULL(smap->map.record);
266 void bpf_selem_unlink(struct bpf_local_storage_elem *selem, bool use_trace_rcu)
268 /* Always unlink from map before unlinking from local_storage
269 * because selem will be freed after successfully unlinked from
272 bpf_selem_unlink_map(selem);
273 __bpf_selem_unlink_storage(selem, use_trace_rcu);
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,
282 struct bpf_local_storage_data *sdata;
283 struct bpf_local_storage_elem *selem;
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)
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)
300 sdata = SDATA(selem);
301 if (cacheit_lockit) {
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().
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],
313 raw_spin_unlock_irqrestore(&local_storage->lock, flags);
319 static int check_flags(const struct bpf_local_storage_data *old_sdata,
322 if (old_sdata && (map_flags & ~BPF_F_LOCK) == BPF_NOEXIST)
323 /* elem already exists */
326 if (!old_sdata && (map_flags & ~BPF_F_LOCK) == BPF_EXIST)
327 /* elem doesn't exist, cannot update it */
333 int bpf_local_storage_alloc(void *owner,
334 struct bpf_local_storage_map *smap,
335 struct bpf_local_storage_elem *first_selem,
338 struct bpf_local_storage *prev_storage, *storage;
339 struct bpf_local_storage **owner_storage_ptr;
342 err = mem_charge(smap, owner, sizeof(*storage));
346 storage = bpf_map_kzalloc(&smap->map, sizeof(*storage),
347 gfp_flags | __GFP_NOWARN);
353 INIT_HLIST_HEAD(&storage->list);
354 raw_spin_lock_init(&storage->lock);
355 storage->owner = owner;
357 bpf_selem_link_storage_nolock(storage, first_selem);
358 bpf_selem_link_map(smap, first_selem);
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.
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.
372 prev_storage = cmpxchg(owner_storage_ptr, NULL, storage);
373 if (unlikely(prev_storage)) {
374 bpf_selem_unlink_map(first_selem);
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().
393 mem_uncharge(smap, owner, sizeof(*storage));
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).
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)
406 struct bpf_local_storage_data *old_sdata = NULL;
407 struct bpf_local_storage_elem *selem = NULL;
408 struct bpf_local_storage *local_storage;
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);
419 if (gfp_flags == GFP_KERNEL && (map_flags & ~BPF_F_LOCK) != BPF_NOEXIST)
420 return ERR_PTR(-EINVAL);
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);
430 selem = bpf_selem_alloc(smap, owner, value, true, gfp_flags);
432 return ERR_PTR(-ENOMEM);
434 err = bpf_local_storage_alloc(owner, smap, selem, gfp_flags);
437 mem_uncharge(smap, owner, smap->elem_size);
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.
450 bpf_local_storage_lookup(local_storage, smap, false);
451 err = check_flags(old_sdata, map_flags);
454 if (old_sdata && selem_linked_to_storage_lockless(SELEM(old_sdata))) {
455 copy_map_value_locked(&smap->map, old_sdata->data,
461 if (gfp_flags == GFP_KERNEL) {
462 selem = bpf_selem_alloc(smap, owner, value, true, gfp_flags);
464 return ERR_PTR(-ENOMEM);
467 raw_spin_lock_irqsave(&local_storage->lock, flags);
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
480 old_sdata = bpf_local_storage_lookup(local_storage, smap, false);
481 err = check_flags(old_sdata, map_flags);
485 if (old_sdata && (map_flags & BPF_F_LOCK)) {
486 copy_map_value_locked(&smap->map, old_sdata->data, value,
488 selem = SELEM(old_sdata);
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().
502 selem = bpf_selem_alloc(smap, owner, value, !old_sdata, gfp_flags);
509 /* First, link the new selem to the map */
510 bpf_selem_link_map(smap, selem);
512 /* Second, link (and publish) the new selem to local_storage */
513 bpf_selem_link_storage_nolock(local_storage, selem);
515 /* Third, remove old selem, SELEM(old_sdata) */
517 bpf_selem_unlink_map(SELEM(old_sdata));
518 bpf_selem_unlink_storage_nolock(local_storage, SELEM(old_sdata),
523 raw_spin_unlock_irqrestore(&local_storage->lock, flags);
527 raw_spin_unlock_irqrestore(&local_storage->lock, flags);
529 mem_uncharge(smap, owner, smap->elem_size);
535 static u16 bpf_local_storage_cache_idx_get(struct bpf_local_storage_cache *cache)
537 u64 min_usage = U64_MAX;
540 spin_lock(&cache->idx_lock);
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];
547 /* Found a free cache_idx */
552 cache->idx_usage_counts[res]++;
554 spin_unlock(&cache->idx_lock);
559 static void bpf_local_storage_cache_idx_free(struct bpf_local_storage_cache *cache,
562 spin_lock(&cache->idx_lock);
563 cache->idx_usage_counts[idx]--;
564 spin_unlock(&cache->idx_lock);
567 int bpf_local_storage_map_alloc_check(union bpf_attr *attr)
569 if (attr->map_flags & ~BPF_LOCAL_STORAGE_CREATE_FLAG_MASK ||
570 !(attr->map_flags & BPF_F_NO_PREALLOC) ||
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)
580 if (attr->value_size > BPF_LOCAL_STORAGE_MAX_VALUE_SIZE)
586 static struct bpf_local_storage_map *__bpf_local_storage_map_alloc(union bpf_attr *attr)
588 struct bpf_local_storage_map *smap;
592 smap = bpf_map_area_alloc(sizeof(*smap), NUMA_NO_NODE);
594 return ERR_PTR(-ENOMEM);
595 bpf_map_init_from_attr(&smap->map, attr);
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);
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);
609 for (i = 0; i < nbuckets; i++) {
610 INIT_HLIST_HEAD(&smap->buckets[i].list);
611 raw_spin_lock_init(&smap->buckets[i].lock);
614 smap->elem_size = offsetof(struct bpf_local_storage_elem,
615 sdata.data[attr->value_size]);
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)
627 if (BTF_INFO_KIND(key_type->info) != BTF_KIND_INT)
630 int_data = *(u32 *)(key_type + 1);
631 if (BTF_INT_BITS(int_data) != 32 || BTF_INT_OFFSET(int_data))
637 bool bpf_local_storage_unlink_nolock(struct bpf_local_storage *local_storage)
639 struct bpf_local_storage_elem *selem;
640 bool free_storage = false;
641 struct hlist_node *n;
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.
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.
652 hlist_for_each_entry_safe(selem, n, &local_storage->list, snode) {
653 /* Always unlink from map before unlinking from
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.
663 free_storage = bpf_selem_unlink_storage_nolock(
664 local_storage, selem, false, false);
671 bpf_local_storage_map_alloc(union bpf_attr *attr,
672 struct bpf_local_storage_cache *cache)
674 struct bpf_local_storage_map *smap;
676 smap = __bpf_local_storage_map_alloc(attr);
678 return ERR_CAST(smap);
680 smap->cache_idx = bpf_local_storage_cache_idx_get(cache);
684 void bpf_local_storage_map_free(struct bpf_map *map,
685 struct bpf_local_storage_cache *cache,
686 int __percpu *busy_counter)
688 struct bpf_local_storage_map_bucket *b;
689 struct bpf_local_storage_elem *selem;
690 struct bpf_local_storage_map *smap;
693 smap = (struct bpf_local_storage_map *)map;
694 bpf_local_storage_cache_idx_free(cache, smap->cache_idx);
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.
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.
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().
711 for (i = 0; i < (1U << smap->bucket_log); i++) {
712 b = &smap->buckets[i];
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))) {
721 this_cpu_inc(*busy_counter);
723 bpf_selem_unlink(selem, false);
725 this_cpu_dec(*busy_counter);
733 /* While freeing the storage we may still need to access the map.
735 * e.g. when bpf_sk_storage_free() has unlinked selem from the map
736 * which then made the above while((selem = ...)) loop
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().
743 * Hence, wait another rcu grace period for the storage to be freed.
747 /* Only delay freeing of smap, buckets are not needed anymore */
748 kvfree(smap->buckets);
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.
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.
767 bpf_map_area_free(smap);