Implement bpf map queue
Subsystems (6)
cover Implement bpf map queue
Bpf queue map is a new kind of map that provides a LIFO/FIFO queue implementation.
In some applications, like a SNAT, it is necessary to keep track of a pool of free elemenets, network ports in this case, then a queue can be used for that purpose.
---
Mauricio Vasquez B (3):
bpf: add bpf queue map
selftests/bpf: add test cases for BPF_MAP_TYPE_QUEUE
bpf: add sample for BPF_MAP_TYPE_QUEUE
include/linux/bpf_types.h | 1 include/uapi/linux/bpf.h | 5 + kernel/bpf/Makefile | 2 kernel/bpf/queuemap.c | 287 +++++++++++++++++++++++++++++++ kernel/bpf/syscall.c | 61 +++++-- kernel/bpf/verifier.c | 16 +- samples/bpf/.gitignore | 1 samples/bpf/Makefile | 3 samples/bpf/test_map_in_map_user.c | 9 - samples/bpf/test_queuemap.sh | 37 ++++ samples/bpf/test_queuemap_kern.c | 51 ++++++ samples/bpf/test_queuemap_user.c | 53 ++++++ tools/include/uapi/linux/bpf.h | 5 + tools/testing/selftests/bpf/test_maps.c | 72 ++++++++ 14 files changed, 577 insertions(+), 26 deletions(-) create mode 100644 kernel/bpf/queuemap.c create mode 100755 samples/bpf/test_queuemap.sh create mode 100644 samples/bpf/test_queuemap_kern.c create mode 100644 samples/bpf/test_queuemap_user.c
PATCH 1/3 bpf: add bpf queue map
Bpf queue implements a LIFO/FIFO data containers for ebpf programs.
It allows to push an element to the queue by using the update operation and to pop an element from the queue by using the lookup operation.
A use case for this is to keep track of a pool of elements, like network ports in a SNAT.
--- include/linux/bpf_types.h | 1 include/uapi/linux/bpf.h | 5 + kernel/bpf/Makefile | 2 kernel/bpf/queuemap.c | 287 +++++++++++++++++++++++++++++++++++++++++++++ kernel/bpf/syscall.c | 61 +++++++--- kernel/bpf/verifier.c | 16 ++- 6 files changed, 353 insertions(+), 19 deletions(-) create mode 100644 kernel/bpf/queuemap.c
include/linux/bpf_types.h +1 -0
@@ -58,3 +58,4 @@ BPF_MAP_TYPE(BPF_MAP_TYPE_CPUMAP, cpu_map_ops) BPF_MAP_TYPE(BPF_MAP_TYPE_XSKMAP, xsk_map_ops)#endif #endif +BPF_MAP_TYPE (BPF_MAP_TYPE_QUEUE , queue_map_ops)
include/uapi/linux/bpf.h +5 -0
@@ -120,6 +120,7 @@ enum bpf_map_type {BPF_MAP_TYPE_CPUMAP ,BPF_MAP_TYPE_XSKMAP ,BPF_MAP_TYPE_SOCKHASH , + BPF_MAP_TYPE_QUEUE, }; enum bpf_prog_type {
@@ -255,6 +256,10 @@ enum bpf_attach_type {/* Flag for stack_map, store build_id+offset instead of pointer */ #define BPF_F_STACK_BUILD_ID (1U << 5) +/* Flags for queue_map, type of queue */ +#define BPF_F_QUEUE_FIFO (1U << 16) +#define BPF_F_QUEUE_LIFO (2U << 16) +enum bpf_stack_build_id_status {/* user space need an empty entry to identify end of a trace */ BPF_STACK_BUILD_ID_EMPTY =0 ,
kernel/bpf/Makefile +1 -1
@@ -2,7 +2,7 @@ obj-y := core.o obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o -obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o +obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o queuemap.o obj-$(CONFIG_BPF_SYSCALL) += disasm.o obj-$(CONFIG_BPF_SYSCALL) += btf.o ifeq ($(CONFIG_NET),y)
kernel/bpf/queuemap.c new file +287 -0
287 lines not on this page · raw message
kernel/bpf/syscall.c +46 -15
86 lines not on this page · raw message
kernel/bpf/verifier.c +13 -3
@@ -1976,8 +1976,12 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 regno,return -EACCES ; } -if (arg_type ==ARG_PTR_TO_MAP_KEY || - arg_type ==ARG_PTR_TO_MAP_VALUE ) { +if (arg_type ==ARG_PTR_TO_MAP_KEY ) { + expected_type =PTR_TO_STACK ; +if (!type_is_pkt_pointer (type) && type !=PTR_TO_MAP_VALUE && + type != expected_type && type !=SCALAR_VALUE ) + goto err_type; + }else if (arg_type ==ARG_PTR_TO_MAP_VALUE ) { expected_type =PTR_TO_STACK ;if (!type_is_pkt_pointer (type) && type !=PTR_TO_MAP_VALUE && type != expected_type)
@@ -2021,6 +2025,7 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 regno,/* bpf_map_xxx(map_ptr) call: remember that map_ptr */ meta->map_ptr = reg->map_ptr; }else if (arg_type ==ARG_PTR_TO_MAP_KEY ) { +bool zero_size_allowed = false;/* bpf_map_xxx(..., map_ptr, ..., key) call: * check that [key, key + map->key_size) are within * stack limits and initialized
@@ -2034,8 +2039,13 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 regno,verbose (env,"invalid map_ptr to access map->key\n" );return -EACCES ; } + +if (meta->map_ptr->map_type ==BPF_MAP_TYPE_QUEUE ) + zero_size_allowed = true; + err =check_helper_mem_access (env, regno, - meta->map_ptr->key_size, false, + meta->map_ptr->key_size, + zero_size_allowed,NULL ); }else if (arg_type ==ARG_PTR_TO_MAP_VALUE ) {/* bpf_map_xxx(..., map_ptr, ..., value) call:
PATCH 2/3 selftests/bpf: add test cases for BPF_MAP_TYPE_QUEUE
In reply to Mauricio Vasquez B--- tools/include/uapi/linux/bpf.h | 5 ++ tools/testing/selftests/bpf/test_maps.c | 72 +++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+)
tools/include/uapi/linux/bpf.h +5 -0
@@ -120,6 +120,7 @@ enum bpf_map_type {BPF_MAP_TYPE_CPUMAP ,BPF_MAP_TYPE_XSKMAP ,BPF_MAP_TYPE_SOCKHASH , + BPF_MAP_TYPE_QUEUE, }; enum bpf_prog_type {
@@ -255,6 +256,10 @@ enum bpf_attach_type {/* Flag for stack_map, store build_id+offset instead of pointer */ #define BPF_F_STACK_BUILD_ID (1U << 5) +/* Flags for queue_map, type of queue */ +#define BPF_F_QUEUE_FIFO (1U << 16) +#define BPF_F_QUEUE_LIFO (2U << 16) +enum bpf_stack_build_id_status {/* user space need an empty entry to identify end of a trace */ BPF_STACK_BUILD_ID_EMPTY =0 ,
tools/testing/selftests/bpf/test_maps.c +72 -0
84 lines not on this page · raw message
PATCH 3/3 bpf: add sample for BPF_MAP_TYPE_QUEUE
In reply to Mauricio Vasquez BThe example is made by two parts, a eBPF program that consumes elements from a FIFO queue and prints them in the screen and a user space application that inserts new elements into the queue each time this is executed.
--- samples/bpf/.gitignore | 1 + samples/bpf/Makefile | 3 ++ samples/bpf/test_map_in_map_user.c | 9 +----- samples/bpf/test_queuemap.sh | 37 +++++++++++++++++++++++++ samples/bpf/test_queuemap_kern.c | 51 +++++++++++++++++++++++++++++++++++ samples/bpf/test_queuemap_user.c | 53 ++++++++++++++++++++++++++++++++++++ 6 files changed, 147 insertions(+), 7 deletions(-) create mode 100755 samples/bpf/test_queuemap.sh create mode 100644 samples/bpf/test_queuemap_kern.c create mode 100644 samples/bpf/test_queuemap_user.c
samples/bpf/.gitignore +1 -0
@@ -26,6 +26,7 @@ test_lru_dist test_map_in_map test_overhead test_probe_write_user +test_queuemap trace_event trace_output tracex1
samples/bpf/Makefile +3 -0
@@ -53,6 +53,7 @@ hostprogs-y += xdpsock hostprogs-y += xdp_fwd hostprogs-y += task_fd_query hostprogs-y += xdp_sample_pkts +hostprogs-y += test_queuemap # Libbpf dependencies LIBBPF = $(TOOLS_PATH)/lib/bpf/libbpf.a
@@ -109,6 +110,7 @@ xdpsock-objs := xdpsock_user.o xdp_fwd-objs := xdp_fwd_user.o task_fd_query-objs := bpf_load.o task_fd_query_user.o $(TRACE_HELPERS) xdp_sample_pkts-objs := xdp_sample_pkts_user.o $(TRACE_HELPERS) +test_queuemap-objs := bpf_load.o test_queuemap_user.o # Tell kbuild to always build the programs always := $(hostprogs-y)
@@ -166,6 +168,7 @@ always += xdpsock_kern.o always += xdp_fwd_kern.o always += task_fd_query_kern.o always += xdp_sample_pkts_kern.o +always += test_queuemap_kern.o HOSTCFLAGS += -I$(objtree)/usr/include HOSTCFLAGS += -I$(srctree)/tools/lib/
samples/bpf/test_map_in_map_user.c +2 -7
@@ -1,10 +1,5 @@ -/* -* Copyright (c) 2017 Facebook -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of version 2 of the GNU General Public -* License as published by the Free Software Foundation. -*/ +// SPDX-License-Identifier: GPL-2.0 +/* Copyright (c) 2018 Politecnico di Torino */ #include <sys/resource.h> #include <sys/socket.h> #include <arpa/inet.h>
samples/bpf/test_queuemap.sh new file +37 -0
@@ -0,0 +1,37 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0 + +[[ -z $TC ]] && TC='tc' +[[ -z $IP ]] && IP='ip' + +TEST_QUEUE_USER='./test_queuemap' +TEST_QUEUE_BPF='./test_queuemap_kern.o' + +function config { + $IP netns add ns1 + $IP link add ve1 type veth peer name vens1 + $IP link set dev ve1 up + $IP link set dev ve1 mtu 1500 + $IP link set dev vens1 netns ns1 + + $IP -n ns1 link set dev lo up + $IP -n ns1 link set dev vens1 up + $IP -n ns1 addr add 10.1.1.101/24 dev vens1 + + $IP addr add 10.1.1.1/24 dev ve1 + $TC qdisc add dev ve1 clsact + $TC filter add dev ve1 ingress bpf da obj $TEST_QUEUE_BPF sec test_queue +} + +function cleanup { + set +e + [[ -z $DEBUG ]] || set +x + $IP netns delete ns1 >& /dev/null + $IP link del ve1 >& /dev/null + rm -f /sys/fs/bpf/tc/globals/queue + [[ -z $DEBUG ]] || set -x + set -e +} + +cleanup +config
samples/bpf/test_queuemap_kern.c new file +51 -0
51 lines not on this page · raw message
samples/bpf/test_queuemap_user.c new file +53 -0
53 lines not on this page · raw message
Daniel Borkmann
maintainerRe: [PATCH bpf-next 1/3] bpf: add bpf queue map
In reply to Mauricio Vasquez BQuoted 258 lines · Mauricio Vasquez B
Bpf queue implements a LIFO/FIFO data containers for ebpf programs.
It allows to push an element to the queue by using the update operation and to pop an element from the queue by using the lookup operation.
A use case for this is to keep track of a pool of elements, like network ports in a SNAT.
Signed-off-by Mauricio Vasquez B <[email protected]>--- include/linux/bpf_types.h | 1 include/uapi/linux/bpf.h | 5 + kernel/bpf/Makefile | 2 kernel/bpf/queuemap.c | 287 +++++++++++++++++++++++++++++++++++++++++++++ kernel/bpf/syscall.c | 61 +++++++--- kernel/bpf/verifier.c | 16 ++- 6 files changed, 353 insertions(+), 19 deletions(-) create mode 100644 kernel/bpf/queuemap.cinclude/linux/bpf_types.h +1
-0@@ -58,3 +58,4 @@ BPF_MAP_TYPE(BPF_MAP_TYPE_CPUMAP, cpu_map_ops) BPF_MAP_TYPE(BPF_MAP_TYPE_XSKMAP, xsk_map_ops)#endif #endif +BPF_MAP_TYPE (BPF_MAP_TYPE_QUEUE , queue_map_ops)include/uapi/linux/bpf.h +5
-0@@ -120,6 +120,7 @@ enum bpf_map_type {BPF_MAP_TYPE_CPUMAP ,BPF_MAP_TYPE_XSKMAP ,BPF_MAP_TYPE_SOCKHASH , + BPF_MAP_TYPE_QUEUE, }; enum bpf_prog_type {@@ -255,6 +256,10 @@ enum bpf_attach_type {/* Flag for stack_map, store build_id+offset instead of pointer */ #define BPF_F_STACK_BUILD_ID (1U << 5) +/* Flags for queue_map, type of queue */ +#define BPF_F_QUEUE_FIFO (1U << 16) +#define BPF_F_QUEUE_LIFO (2U << 16) +enum bpf_stack_build_id_status {/* user space need an empty entry to identify end of a trace */ BPF_STACK_BUILD_ID_EMPTY =0 ,kernel/bpf/Makefile +1
-1@@ -2,7 +2,7 @@ obj-y := core.o obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o -obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o +obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o queuemap.o obj-$(CONFIG_BPF_SYSCALL) += disasm.o obj-$(CONFIG_BPF_SYSCALL) += btf.o ifeq ($(CONFIG_NET),y)kernel/bpf/queuemap.c new file +188
-0@@ -0,0 +1,287 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* queuemap.c: BPF queue map +* +* Copyright (c) 2018 Politecnico di Torino +*/ +#include <linux/bpf.h> +#include <linux/rculist.h> +#include <linux/slab.h> +#include "percpu_freelist.h" + +#define QUEUE_CREATE_FLAG_MASK \ + (BPF_F_NO_PREALLOC | BPF_F_NUMA_NODE | BPF_F_RDONLY | BPF_F_WRONLY | \ + BPF_F_QUEUE_FIFO | BPF_F_QUEUE_LIFO) + +enum queue_type { +QUEUE_FIFO = (BPF_F_QUEUE_FIFO >>16 ), +QUEUE_LIFO = (BPF_F_QUEUE_LIFO >>16 ), +}; + +struct bpf_queue { +struct bpf_map map; +struct list_head head; +struct pcpu_freelist freelist; +void *nodes; +enum queue_type type; +raw_spinlock_t lock; +atomic_t count; +u32 node_size; +}; + +struct queue_node { +struct pcpu_freelist_node fnode; +struct bpf_queue *queue; +struct list_head list; +struct rcu_head rcu; +char element[0 ]__aligned(8) ; +}; + +static bool queue_map_is_prealloc (struct bpf_queue *queue) +{ +return !(queue->map.map_flags &BPF_F_NO_PREALLOC ); +} + +/* Called from syscall */ +static int queue_map_alloc_check (union bpf_attr *attr) +{ +/* check sanity of attributes */ +if (attr->max_entries ==0 || attr->key_size !=0 || + attr->value_size ==0 || attr->map_flags & ~QUEUE_CREATE_FLAG_MASK ) +return -EINVAL ; + +if ((attr->map_flags >>16 ) !=QUEUE_FIFO && + (attr->map_flags >>16 ) !=QUEUE_LIFO ) { +return -EINVAL ; + } + +if (attr->value_size >KMALLOC_MAX_SIZE ) +/* if value_size is bigger, the user space won't be able to +* access the elements. +*/ +return -E2BIG ; + +return 0 ; +} + +static int prealloc_init (struct bpf_queue *queue) +{ +u32 node_size =sizeof (struct queue_node ) + +round_up (queue->map.value_size,8 ); +u32 num_entries = queue->map.max_entries; +int err; + + queue->nodes =bpf_map_area_alloc (node_size * num_entries, + queue->map.numa_node); +if (!queue->nodes) +return -ENOMEM ; + + err =pcpu_freelist_init (&queue->freelist); +if (err) + goto free_nodes; + +pcpu_freelist_populate (&queue->freelist, + queue->nodes + + offsetof(struct queue_node , fnode), + node_size, num_entries); + +return 0 ; + +free_nodes: +bpf_map_area_free (queue->nodes); +return err; +} + +static void prealloc_destroy (struct bpf_queue *queue) +{ +bpf_map_area_free (queue->nodes); +pcpu_freelist_destroy (&queue->freelist); +} + +static struct bpf_map *queue_map_alloc (union bpf_attr *attr) +{ +struct bpf_queue *queue; +u64 cost =sizeof (*queue); +int ret; + + queue =kzalloc (sizeof (*queue),GFP_USER ); +if (!queue) +return ERR_PTR (-ENOMEM ); + +bpf_map_init_from_attr (&queue->map, attr); + + queue->node_size =sizeof (struct queue_node ) + +round_up (attr->value_size,8 ); + cost += (u64 ) attr->max_entries * queue->node_size; +if (cost >=U32_MAX -PAGE_SIZE ) { + ret = -E2BIG ; + goto free_queue; + } + + queue->map.pages =round_up (cost,PAGE_SIZE ) >>PAGE_SHIFT ; + + ret =bpf_map_precharge_memlock (queue->map.pages); +if (ret) + goto free_queue; + +INIT_LIST_HEAD (&queue->head); + +raw_spin_lock_init (&queue->lock); + + queue->type = attr->map_flags >>16 ; + +if (queue_map_is_prealloc (queue)) + ret =prealloc_init (queue); +if (ret) + goto free_queue; + +return &queue->map; + +free_queue: +kfree (queue); +return ERR_PTR (ret); +} + +/* Called when map->refcnt goes to zero, either from workqueue or from syscall */ +static void queue_map_free (struct bpf_map *map) +{ + struct bpf_queue *queue = container_of(map, struct bpf_queue, map); +struct queue_node *l; + +/* at this point bpf_prog->aux->refcnt == 0 and this map->refcnt == 0, +* so the programs (can be more than one that used this map) were +* disconnected from events. Wait for outstanding critical sections in +* these programs to complete +*/ +synchronize_rcu (); + +/* some of queue_elem_free_rcu() callbacks for elements of this map may +* not have executed. Wait for them. +*/ +rcu_barrier (); +if (!queue_map_is_prealloc (queue)) +list_for_each_entry_rcu (l, &queue->head, list) { +list_del_rcu (&l->list); +kfree (l); + } +else +prealloc_destroy (queue); +kfree (queue); +} + +static void queue_elem_free_rcu (struct rcu_head *head) +{ + struct queue_node *l = container_of(head, struct queue_node, rcu); +struct bpf_queue *queue = l->queue; + +/* must increment bpf_prog_active to avoid kprobe+bpf triggering while +* we're calling kfree, otherwise deadlock is possible if kprobes +* are placed somewhere inside of slub +*/ +preempt_disable (); +__this_cpu_inc (bpf_prog_active); +if (queue_map_is_prealloc (queue)) +pcpu_freelist_push (&queue->freelist, &l->fnode); +else +kfree (l); +__this_cpu_dec (bpf_prog_active); +preempt_enable ();
kernel/bpf/queuemap.c line 198
Quoted 10 lines
kernel/bpf/queuemap.c new file +10
-0+} + +/* Called from syscall or from eBPF program */ +static void *queue_map_lookup_elem (struct bpf_map *map,void *key) +{ + struct bpf_queue *queue = container_of(map, struct bpf_queue, map); +unsigned long flags; +struct queue_node *node; + +raw_spin_lock_irqsave (&queue->lock, flags);
I think a per-cpu flavor would be very useful here as well in this map type such that we wouldn't need a lock here but only guarantee that preemption is disabled, and it could be used as temp store for the program for example.
Quoted 14 lines
kernel/bpf/queuemap.c new file +14
-0+ node = list_first_or_null_rcu(&queue->head, struct queue_node, list); +if (!node) { +raw_spin_unlock_irqrestore (&queue->lock, flags); +return NULL ; + } + +if (!queue_map_is_prealloc (queue)) +atomic_dec (&queue->count); + +list_del_rcu (&node->list); +call_rcu (&node->rcu, queue_elem_free_rcu); + +raw_spin_unlock_irqrestore (&queue->lock, flags); +
kernel/bpf/queuemap.c line 223
Quoted 10 lines
kernel/bpf/queuemap.c new file +10
-0+return &node->element; +} + +/* Called from syscall or from eBPF program */ +static int queue_map_update_elem (struct bpf_map *map,void *key,void *value, +u64 map_flags) +{ + struct bpf_queue *queue = container_of(map, struct bpf_queue, map); +unsigned long flags; +struct queue_node *new;
Should reject invalid map update flags here.
Quoted 72 lines
kernel/bpf/queuemap.c new file +63
-0+if (!queue_map_is_prealloc (queue)) { +if (atomic_inc_return (&queue->count) > queue->map.max_entries) { +atomic_dec (&queue->count); +return -E2BIG ; + } + + new =kmalloc_node (queue->node_size,GFP_ATOMIC | __GFP_NOWARN, + queue->map.numa_node); +if (!new) { +atomic_dec (&queue->count); +return -ENOMEM ; + } + }else { +struct pcpu_freelist_node *l; + + l =pcpu_freelist_pop (&queue->freelist); +if (!l) +return -E2BIG ; + new = container_of(l, struct queue_node, fnode); + } + +memcpy (new->element, value, queue->map.value_size); + new->queue = queue; + +raw_spin_lock_irqsave (&queue->lock, flags); +switch (queue->type) { +case QUEUE_FIFO : +list_add_tail_rcu (&new->list, &queue->head); +break ; + +case QUEUE_LIFO : +list_add_rcu (&new->list, &queue->head); +break ; + } + +raw_spin_unlock_irqrestore (&queue->lock, flags); + +return 0 ; +} + +/* Called from syscall or from eBPF program */ +static int queue_map_delete_elem (struct bpf_map *map,void *key) +{ +return -EINVAL ; +} + +/* Called from syscall */ +static int queue_map_get_next_key (struct bpf_map *map,void *key, +void *next_key) +{ +return -EINVAL ; +} + +const struct bpf_map_ops queue_map_ops = { + .map_alloc_check = queue_map_alloc_check, + .map_alloc = queue_map_alloc, + .map_free = queue_map_free, + .map_lookup_elem = queue_map_lookup_elem, + .map_update_elem = queue_map_update_elem, + .map_delete_elem = queue_map_delete_elem, + .map_get_next_key = queue_map_get_next_key, +}; +kernel/bpf/syscall.c +1
-0@@ -622,11 +622,19 @@ static int map_lookup_elem(union bpf_attr *attr) err = -EPERM ; goto err_put; } +if (map->map_type !=BPF_MAP_TYPE_QUEUE ) {
kernel/bpf/syscall.c static int map_lookup_elem(union bpf_attr *attr) · line 635
Quoted 10 lines
kernel/bpf/syscall.c +10
-0+ key =memdup_user (ukey, map->key_size); +if (IS_ERR (key)) { + err =PTR_ERR (key); + goto err_put; + } + }else { +if (ukey) { + err = -EINVAL ; + goto err_put; + }
Given you have a fixed key_size of 0, this could probably be made more generic and refactored a bit into a helper to check for 0 map->key_size instead of map type.
Quoted 20 lines
kernel/bpf/syscall.c +5
-8- key =memdup_user (ukey, map->key_size); -if (IS_ERR (key)) { - err =PTR_ERR (key); - goto err_put; + key =NULL ; } if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||@@ -709,10 +717,19 @@ static int map_update_elem(union bpf_attr *attr) goto err_put; } - key =memdup_user (ukey, map->key_size); -if (IS_ERR (key)) { - err =PTR_ERR (key); - goto err_put; +if (map->map_type !=BPF_MAP_TYPE_QUEUE ) { + key =memdup_user (ukey, map->key_size); +if (IS_ERR (key)) { + err =PTR_ERR (key);
kernel/bpf/syscall.c static int map_update_elem(union bpf_attr *attr) · line 733
Quoted 10 lines
kernel/bpf/syscall.c +9
-0+ goto err_put; + } + }else { +if (ukey) { + err = -EINVAL ; + goto err_put; + } + + key =NULL ; }
Ditto, and also further below as well for the other syscall cases.
Quoted 72 lines
kernel/bpf/syscall.c +21
-7if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||@@ -803,10 +820,19 @@ static int map_delete_elem(union bpf_attr *attr) goto err_put; } - key =memdup_user (ukey, map->key_size); -if (IS_ERR (key)) { - err =PTR_ERR (key); - goto err_put; +if (map->map_type !=BPF_MAP_TYPE_QUEUE ) { + key =memdup_user (ukey, map->key_size); +if (IS_ERR (key)) { + err =PTR_ERR (key); + goto err_put; + } + }else { +if (ukey) { + err = -EINVAL ; + goto err_put; + } + + key =NULL ; }if (bpf_map_is_dev_bound (map)) {@@ -855,9 +881,14 @@ static int map_get_next_key(union bpf_attr *attr) }if (ukey) { - key =memdup_user (ukey, map->key_size); -if (IS_ERR (key)) { - err =PTR_ERR (key); +if (map->map_type !=BPF_MAP_TYPE_QUEUE ) { + key =memdup_user (ukey, map->key_size); +if (IS_ERR (key)) { + err =PTR_ERR (key); + goto err_put; + } + }else { + err = -EINVAL ; goto err_put; } }else {kernel/bpf/verifier.c +7
-2@@ -1976,8 +1976,12 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 regno,return -EACCES ; } -if (arg_type ==ARG_PTR_TO_MAP_KEY || - arg_type ==ARG_PTR_TO_MAP_VALUE ) { +if (arg_type ==ARG_PTR_TO_MAP_KEY ) { + expected_type =PTR_TO_STACK ; +if (!type_is_pkt_pointer (type) && type !=PTR_TO_MAP_VALUE && + type != expected_type && type !=SCALAR_VALUE ) + goto err_type; + }else if (arg_type ==ARG_PTR_TO_MAP_VALUE ) { expected_type =PTR_TO_STACK ;if (!type_is_pkt_pointer (type) && type !=PTR_TO_MAP_VALUE && type != expected_type)@@ -2021,6 +2025,7 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 regno,/* bpf_map_xxx(map_ptr) call: remember that map_ptr */ meta->map_ptr = reg->map_ptr; }else if (arg_type ==ARG_PTR_TO_MAP_KEY ) { +bool zero_size_allowed = false;/* bpf_map_xxx(..., map_ptr, ..., key) call: * check that [key, key + map->key_size) are within * stack limits and initialized
kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 regno, · line 2043
Quoted 5 lines
kernel/bpf/verifier.c +2
-0@@ -2034,8 +2039,13 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 regno,verbose (env,"invalid map_ptr to access map->key\n" );return -EACCES ; } + +if (meta->map_ptr->map_type ==BPF_MAP_TYPE_QUEUE )
Here as well.
kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 regno, · line 2044
Quoted 1 line
kernel/bpf/verifier.c +1
-0+ zero_size_allowed = true;
Also, verifier should rather enforce a const NULL key here than allowing one to be set (but not as the only 'valid' input option), meaning, I don't think it would be good to allow a 'zero' sized pointer to stack in this case.
Quoted 8 lines
kernel/bpf/verifier.c +2
-1err =check_helper_mem_access (env, regno, - meta->map_ptr->key_size, false, + meta->map_ptr->key_size, + zero_size_allowed,NULL ); }else if (arg_type ==ARG_PTR_TO_MAP_VALUE ) {/* bpf_map_xxx(..., map_ptr, ..., value) call:
Daniel Borkmann
maintainerRe: [PATCH bpf-next 2/3] selftests/bpf: add test cases for BPF_MAP_TYPE_QUEUE
In reply to Mauricio Vasquez BQuoted 35 lines · Mauricio Vasquez B
Signed-off-by Mauricio Vasquez B <[email protected]>--- tools/include/uapi/linux/bpf.h | 5 ++ tools/testing/selftests/bpf/test_maps.c | 72 +++++++++++++++++++++++++++++++ 2 files changed, 77 insertions(+)tools/include/uapi/linux/bpf.h +5
-0@@ -120,6 +120,7 @@ enum bpf_map_type {BPF_MAP_TYPE_CPUMAP ,BPF_MAP_TYPE_XSKMAP ,BPF_MAP_TYPE_SOCKHASH , + BPF_MAP_TYPE_QUEUE, }; enum bpf_prog_type {@@ -255,6 +256,10 @@ enum bpf_attach_type {/* Flag for stack_map, store build_id+offset instead of pointer */ #define BPF_F_STACK_BUILD_ID (1U << 5) +/* Flags for queue_map, type of queue */ +#define BPF_F_QUEUE_FIFO (1U << 16) +#define BPF_F_QUEUE_LIFO (2U << 16) +enum bpf_stack_build_id_status {/* user space need an empty entry to identify end of a trace */ BPF_STACK_BUILD_ID_EMPTY =0 ,tools/testing/selftests/bpf/test_maps.c +0
-0@@ -457,6 +457,77 @@ static void test_devmap(int task, void *data)close (fd);
tools/testing/selftests/bpf/test_maps.c static void test_devmap(int task, void *data) · line 467
Quoted 10 lines
tools/testing/selftests/bpf/test_maps.c +8
-0} +static void test_queuemap (int task,void *data) +{ +__u32 value; +int fd, i; + +/* test FIFO */ + fd =bpf_create_map (BPF_MAP_TYPE_QUEUE ,0 ,sizeof (value),32 , +BPF_F_QUEUE_FIFO );
We should also feed in 'map_flags' so that both prealloc and non-prealloc will be tested.
Quoted 22 lines
tools/testing/selftests/bpf/test_maps.c +22
-0+if (fd <0 ) { +printf ("Failed to create queuemap '%s'!\n" ,strerror (errno)); +exit (1 ); + } + +/* Push 32 elements */ +for (i =0 ; i <32 ; i++) { + value =1000 - i *3 ; +assert (bpf_map_update_elem (fd,NULL , &value,0 ) ==0 ); + } + +/* Check that element cannot be pushed due to max_entries limit */ + value =1000 ; +assert (bpf_map_update_elem (fd,NULL , &value,0 ) ==-1 && + errno ==E2BIG ); + +/* Pop all elements */ +for (i =0 ; i <32 ; i++) +assert (bpf_map_lookup_elem (fd,NULL , &value) ==0 && + value == (1000 - i *3 )); + +/* Check that there are not elements left */
tools/testing/selftests/bpf/test_maps.c static void test_devmap(int task, void *data) · line 499
Quoted 10 lines
tools/testing/selftests/bpf/test_maps.c +10
-0+assert (bpf_map_lookup_elem (fd,NULL , &value) ==-1 && errno ==ENOENT ); + +assert (bpf_map_delete_elem (fd,NULL ) ==-1 && errno ==EINVAL ); +assert (bpf_map_get_next_key (fd,NULL ,NULL ) ==-1 && errno ==EINVAL ); + +close (fd); + +/* test LIFO */ + fd =bpf_create_map (BPF_MAP_TYPE_QUEUE ,0 ,sizeof (value),32 , +BPF_F_QUEUE_LIFO );
Ditto.
Quoted 43 lines
tools/testing/selftests/bpf/test_maps.c +32
-0+if (fd <0 ) { +printf ("Failed to create queuemap '%s'!\n" ,strerror (errno)); +exit (1 ); + } + +/* Push 32 elements */ +for (i =0 ; i <32 ; i++) { + value =1000 - i *3 ; +assert (bpf_map_update_elem (fd,NULL , &value,0 ) ==0 ); + } + +/* Check that element cannot be pushed due to max_entries limit */ + value =1000 ; +assert (bpf_map_update_elem (fd,NULL , &value,0 ) ==-1 && + errno ==E2BIG ); + +/* Pop all elements */ +for (i =31 ; i >=0 ; i--) +assert (bpf_map_lookup_elem (fd,NULL , &value) ==0 && + value == (1000 - i *3 )); + +/* Check that there are not elements left */ +assert (bpf_map_lookup_elem (fd,NULL , &value) ==-1 && + errno ==ENOENT ); + +assert (bpf_map_delete_elem (fd,NULL ) ==-1 && errno ==EINVAL ); +assert (bpf_map_get_next_key (fd,NULL ,NULL ) ==-1 && errno ==EINVAL ); + +close (fd); +} +#include <sys/socket.h> #include <sys/ioctl.h> #include <arpa/inet.h> @@ -1162,6 +1233,7 @@ static void run_all_tests(void)test_arraymap_percpu_many_keys ();test_devmap (0 ,NULL ); +test_queuemap (0 ,NULL );test_sockmap (0 ,NULL );test_map_large ();
Daniel Borkmann
maintainerRe: [PATCH bpf-next 3/3] bpf: add sample for BPF_MAP_TYPE_QUEUE
In reply to Mauricio Vasquez BQuoted 63 lines · Mauricio Vasquez B
The example is made by two parts, a eBPF program that consumes elements from a FIFO queue and prints them in the screen and a user space application that inserts new elements into the queue each time this is executed.
Signed-off-by Mauricio Vasquez B <[email protected]>--- samples/bpf/.gitignore | 1 + samples/bpf/Makefile | 3 ++ samples/bpf/test_map_in_map_user.c | 9 +----- samples/bpf/test_queuemap.sh | 37 +++++++++++++++++++++++++ samples/bpf/test_queuemap_kern.c | 51 +++++++++++++++++++++++++++++++++++ samples/bpf/test_queuemap_user.c | 53 ++++++++++++++++++++++++++++++++++++ 6 files changed, 147 insertions(+), 7 deletions(-) create mode 100755 samples/bpf/test_queuemap.sh create mode 100644 samples/bpf/test_queuemap_kern.c create mode 100644 samples/bpf/test_queuemap_user.csamples/bpf/.gitignore +1
-0@@ -26,6 +26,7 @@ test_lru_dist test_map_in_map test_overhead test_probe_write_user +test_queuemap trace_event trace_output tracex1samples/bpf/Makefile +3
-0@@ -53,6 +53,7 @@ hostprogs-y += xdpsock hostprogs-y += xdp_fwd hostprogs-y += task_fd_query hostprogs-y += xdp_sample_pkts +hostprogs-y += test_queuemap # Libbpf dependencies LIBBPF = $(TOOLS_PATH)/lib/bpf/libbpf.a@@ -109,6 +110,7 @@ xdpsock-objs := xdpsock_user.o xdp_fwd-objs := xdp_fwd_user.o task_fd_query-objs := bpf_load.o task_fd_query_user.o $(TRACE_HELPERS) xdp_sample_pkts-objs := xdp_sample_pkts_user.o $(TRACE_HELPERS) +test_queuemap-objs := bpf_load.o test_queuemap_user.o # Tell kbuild to always build the programs always := $(hostprogs-y)@@ -166,6 +168,7 @@ always += xdpsock_kern.o always += xdp_fwd_kern.o always += task_fd_query_kern.o always += xdp_sample_pkts_kern.o +always += test_queuemap_kern.o HOSTCFLAGS += -I$(objtree)/usr/include HOSTCFLAGS += -I$(srctree)/tools/lib/samples/bpf/test_map_in_map_user.c +0
-0
samples/bpf/test_map_in_map_user.c line 2
Quoted 9 lines
samples/bpf/test_map_in_map_user.c +2
-7@@ -1,10 +1,5 @@ -/* -* Copyright (c) 2017 Facebook -* -* This program is free software; you can redistribute it and/or -* modify it under the terms of version 2 of the GNU General Public -* License as published by the Free Software Foundation. -*/ +// SPDX-License-Identifier: GPL-2.0 +/* Copyright (c) 2018 Politecnico di Torino */
I don't think you can remove above Copyright and replace it with a different one. ;)
Quoted 88 lines
samples/bpf/test_map_in_map_user.c +0
-0#include <sys/resource.h> #include <sys/socket.h> #include <arpa/inet.h> samples/bpf/test_queuemap.sh new file +37
-0@@ -0,0 +1,37 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0 + +[[ -z $TC ]] && TC='tc' +[[ -z $IP ]] && IP='ip' + +TEST_QUEUE_USER='./test_queuemap' +TEST_QUEUE_BPF='./test_queuemap_kern.o' + +function config { + $IP netns add ns1 + $IP link add ve1 type veth peer name vens1 + $IP link set dev ve1 up + $IP link set dev ve1 mtu 1500 + $IP link set dev vens1 netns ns1 + + $IP -n ns1 link set dev lo up + $IP -n ns1 link set dev vens1 up + $IP -n ns1 addr add 10.1.1.101/24 dev vens1 + + $IP addr add 10.1.1.1/24 dev ve1 + $TC qdisc add dev ve1 clsact + $TC filter add dev ve1 ingress bpf da obj $TEST_QUEUE_BPF sec test_queue +} + +function cleanup { + set +e + [[ -z $DEBUG ]] || set +x + $IP netns delete ns1 >& /dev/null + $IP link del ve1 >& /dev/null + rm -f /sys/fs/bpf/tc/globals/queue + [[ -z $DEBUG ]] || set -x + set -e +} + +cleanup +configsamples/bpf/test_queuemap_kern.c new file +36
-0@@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-2.0 +/* Copyright (c) 2018 Politecnico di Torino */ +#define KBUILD_MODNAME "foo" +#include <linux/ptrace.h> +#include <linux/version.h> +#include <uapi/linux/bpf.h> +#include <uapi/linux/in6.h> +#include <uapi/linux/pkt_cls.h> +#include "bpf_helpers.h" + +#define PIN_GLOBAL_NS 2 + +struct bpf_elf_map { +__u32 type; +__u32 key_size; +__u32 value_size; +__u32 max_entries; +__u32 flags; +__u32 id; +__u32 pinning; +}; + +/* map #0 */ +struct bpf_elf_map SEC("maps") queue = { + .type = BPF_MAP_TYPE_QUEUE, + .key_size = 0, + .value_size = sizeof(u32), + .flags = BPF_F_QUEUE_FIFO, + .max_entries = 1024, + .pinning = PIN_GLOBAL_NS, +}; + +SEC("test_queue") +int _test_queue (struct __sk_buff *skb) +{ +char msg[] ="element is %u\n" ;
samples/bpf/test_queuemap_kern.c line 46
Quoted 10 lines
samples/bpf/test_queuemap_kern.c new file +10
-0+char msg_no[] ="there are not elements\n" ; + +u32 *val =bpf_map_lookup_elem (&queue,NULL ); + +if (!val) { +bpf_trace_printk (msg_no,sizeof (msg_no)); +return TC_ACT_OK ; + } + +bpf_trace_printk (msg,sizeof (msg), *val);
Could we add a more elaborate example? In cover letter and patch 1 which implements the map, you mention SNAT, perhaps it would be useful to make it a minimal sample app.
Quoted 65 lines
samples/bpf/test_queuemap_kern.c new file +5
-0+return TC_ACT_OK ; +} + +char _license[] SEC("license") = "GPL"; +u32 _version SEC("version") = LINUX_VERSION_CODE;samples/bpf/test_queuemap_user.c new file +53
-0@@ -0,0 +1,53 @@ +/* +* Copyright (c) 2018 Politecnico di Torino +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of version 2 of the GNU General Public +* License as published by the Free Software Foundation. +*/ +#include <sys/resource.h> +#include <sys/socket.h> +#include <arpa/inet.h> +#include <stdint.h> +#include <assert.h> +#include <errno.h> +#include <stdlib.h> +#include <stdio.h> +#include <bpf/bpf.h> +#include "bpf_load.h" + +int queue_map; + +static void test_queue_map (void ) +{ +int ret; +uint32_t i; + + queue_map =bpf_obj_get ("/sys/fs/bpf/tc/globals/queue" ); +if (queue_map <0 ) { +fprintf (stderr,"error getting map" ); +return ; + } + +for (i =0 ; i <256 ; i++) { +uint32_t v =1000 - i*3 ; + + ret =bpf_map_update_elem (queue_map,NULL , &v,0 ); +if (ret) +fprintf (stderr,"ret is %d\n" , ret); + } +} + +int main (int argc,char **argv) +{ +struct rlimit r = {RLIM_INFINITY ,RLIM_INFINITY }; +char filename[256 ]; + +assert (!setrlimit (RLIMIT_MEMLOCK , &r)); + +snprintf (filename,sizeof (filename),"%s_kern.o" , argv[0 ]); + +test_queue_map (); + +return 0 ; +}
Daniel Borkmann
maintainerRe: [PATCH bpf-next 1/3] bpf: add bpf queue map
In reply to Mauricio Vasquez BQuoted 9 lines · Mauricio Vasquez B
Bpf queue implements a LIFO/FIFO data containers for ebpf programs.
It allows to push an element to the queue by using the update operation and to pop an element from the queue by using the lookup operation.
A use case for this is to keep track of a pool of elements, like network ports in a SNAT.
Signed-off-by Mauricio Vasquez B <[email protected]>
[...]
kernel/bpf/queuemap.c line 75
Quoted 9 lines
kernel/bpf/queuemap.c new file +9
-0+static int prealloc_init (struct bpf_queue *queue) +{ +u32 node_size =sizeof (struct queue_node ) + +round_up (queue->map.value_size,8 ); +u32 num_entries = queue->map.max_entries; +int err; + + queue->nodes =bpf_map_area_alloc (node_size * num_entries, + queue->map.numa_node);
That doesn't work either. If you don't set numa node, then here in your case you'll always use numa node 0, which is unintentional. You need to get the node via bpf_map_attr_numa_node(attr) helper. Same issue in queue_map_update_elem().
Re: [PATCH bpf-next 1/3] bpf: add bpf queue map
In reply to Mauricio Vasquez BQuoted 1 line · Mauricio Vasquez B
Bpf queue implements a LIFO/FIFO data containers for ebpf programs.
queue/stack datastructure would be a great addition.
Quoted 39 lines
It allows to push an element to the queue by using the update operation and to pop an element from the queue by using the lookup operation.
A use case for this is to keep track of a pool of elements, like network ports in a SNAT.
Signed-off-by Mauricio Vasquez B <[email protected]>--- include/linux/bpf_types.h | 1 include/uapi/linux/bpf.h | 5 + kernel/bpf/Makefile | 2 kernel/bpf/queuemap.c | 287 +++++++++++++++++++++++++++++++++++++++++++++ kernel/bpf/syscall.c | 61 +++++++--- kernel/bpf/verifier.c | 16 ++- 6 files changed, 353 insertions(+), 19 deletions(-) create mode 100644 kernel/bpf/queuemap.cinclude/linux/bpf_types.h +1
-0@@ -58,3 +58,4 @@ BPF_MAP_TYPE(BPF_MAP_TYPE_CPUMAP, cpu_map_ops) BPF_MAP_TYPE(BPF_MAP_TYPE_XSKMAP, xsk_map_ops)#endif #endif +BPF_MAP_TYPE (BPF_MAP_TYPE_QUEUE , queue_map_ops)include/uapi/linux/bpf.h +1
-0@@ -120,6 +120,7 @@ enum bpf_map_type {BPF_MAP_TYPE_CPUMAP ,BPF_MAP_TYPE_XSKMAP ,BPF_MAP_TYPE_SOCKHASH , + BPF_MAP_TYPE_QUEUE, }; enum bpf_prog_type {
include/uapi/linux/bpf.h enum bpf_attach_type { · line 261
Quoted 6 lines
include/uapi/linux/bpf.h +3
-0@@ -255,6 +256,10 @@ enum bpf_attach_type {/* Flag for stack_map, store build_id+offset instead of pointer */ #define BPF_F_STACK_BUILD_ID (1U << 5) +/* Flags for queue_map, type of queue */ +#define BPF_F_QUEUE_FIFO (1U << 16) +#define BPF_F_QUEUE_LIFO (2U << 16)
the choice of flags looks odd.
Why start at bit 16 and why waste two bits?
It's either stack or queue.
May be instead define two map_types:BPF_MAP_TYPE_QUEUE and BPF_MAP_TYPE_STACK
that share common implementation?
And how about adding three new helpers: push/pop/peek as well? Reusing lookup/update is neat, but does lookup == pop
or does lookup == peek ?
I suspect it will be confusing.
Three new helpers cost nothing, but will make bpf progs easier to read.
Could you also add a flag for replacement policy?
In this implementation when max_entries limit is reached the map_update_elem (aka push) will fail with e2big. It would be useful to allow pushing and dropping elements from the other side then such queue/stack can be used to keep track of the last N events (the prog would unconditionally push and user space would swap the queue for new one via map-in-map and drain old queue).
Speaking of map-in-map, please add a test to make sure queue/stack works with hash/array_of_maps.
selftests in patch2 needs to have kernel side as well. it's not enough to test syscall access only.
Re: [PATCH bpf-next 3/3] bpf: add sample for BPF_MAP_TYPE_QUEUE
In reply to Mauricio Vasquez Bsamples/bpf/Makefile xdpsock-objs := xdpsock_user.o · line 116
Quoted 8 lines · Mauricio Vasquez B
samples/bpf/Makefile +1
-0@@ -109,6 +110,7 @@ xdpsock-objs := xdpsock_user.o xdp_fwd-objs := xdp_fwd_user.o task_fd_query-objs := bpf_load.o task_fd_query_user.o $(TRACE_HELPERS) xdp_sample_pkts-objs := xdp_sample_pkts_user.o $(TRACE_HELPERS) +test_queuemap-objs := bpf_load.o test_queuemap_user.o # Tell kbuild to always build the programs always := $(hostprogs-y)
nit: would you mind using libbpf instead of bpf_load.o ?
Re: [PATCH bpf-next 1/3] bpf: add bpf queue map
In reply to Daniel BorkmannQuoted 265 lines · Daniel Borkmann
Quoted 264 lines · Mauricio Vasquez B
Bpf queue implements a LIFO/FIFO data containers for ebpf programs.
It allows to push an element to the queue by using the update operation and to pop an element from the queue by using the lookup operation.
A use case for this is to keep track of a pool of elements, like network ports in a SNAT.
Signed-off-by Mauricio Vasquez B <[email protected]>--- include/linux/bpf_types.h | 1 include/uapi/linux/bpf.h | 5 + kernel/bpf/Makefile | 2 kernel/bpf/queuemap.c | 287 +++++++++++++++++++++++++++++++++++++++++++++ kernel/bpf/syscall.c | 61 +++++++--- kernel/bpf/verifier.c | 16 ++- 6 files changed, 353 insertions(+), 19 deletions(-)create mode 100644
kernel/bpf/queuemap.cinclude/linux/bpf_types.h +1
-0@@ -58,3 +58,4 @@ BPF_MAP_TYPE(BPF_MAP_TYPE_CPUMAP, cpu_map_ops) BPF_MAP_TYPE(BPF_MAP_TYPE_XSKMAP, xsk_map_ops)#endif #endif +BPF_MAP_TYPE (BPF_MAP_TYPE_QUEUE , queue_map_ops)include/uapi/linux/bpf.h +5
-0@@ -120,6 +120,7 @@ enum bpf_map_type {BPF_MAP_TYPE_CPUMAP ,BPF_MAP_TYPE_XSKMAP ,BPF_MAP_TYPE_SOCKHASH , + BPF_MAP_TYPE_QUEUE, }; enum bpf_prog_type {@@ -255,6 +256,10 @@ enum bpf_attach_type {/* Flag for stack_map, store build_id+offset instead of pointer */ #define BPF_F_STACK_BUILD_ID (1U << 5) +/* Flags for queue_map, type of queue */ +#define BPF_F_QUEUE_FIFO (1U << 16) +#define BPF_F_QUEUE_LIFO (2U << 16) +enum bpf_stack_build_id_status {/* user space need an empty entry to identify end of a trace */ BPF_STACK_BUILD_ID_EMPTY =0 ,kernel/bpf/Makefile +1
-1@@ -2,7 +2,7 @@ obj-y := core.o obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o -obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o +obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o queuemap.o obj-$(CONFIG_BPF_SYSCALL) += disasm.o obj-$(CONFIG_BPF_SYSCALL) += btf.o ifeq ($(CONFIG_NET),y)kernel/bpf/queuemap.c new file +194
-0@@ -0,0 +1,287 @@ +// SPDX-License-Identifier: GPL-2.0 +/* +* queuemap.c: BPF queue map +* +* Copyright (c) 2018 Politecnico di Torino +*/ +#include <linux/bpf.h> +#include <linux/rculist.h> +#include <linux/slab.h> +#include "percpu_freelist.h" + +#define QUEUE_CREATE_FLAG_MASK \ + (BPF_F_NO_PREALLOC | BPF_F_NUMA_NODE | BPF_F_RDONLY | BPF_F_WRONLY | \ + BPF_F_QUEUE_FIFO | BPF_F_QUEUE_LIFO) + +enum queue_type { +QUEUE_FIFO = (BPF_F_QUEUE_FIFO >>16 ), +QUEUE_LIFO = (BPF_F_QUEUE_LIFO >>16 ), +}; + +struct bpf_queue { +struct bpf_map map; +struct list_head head; +struct pcpu_freelist freelist; +void *nodes; +enum queue_type type; +raw_spinlock_t lock; +atomic_t count; +u32 node_size; +}; + +struct queue_node { +struct pcpu_freelist_node fnode; +struct bpf_queue *queue; +struct list_head list; +struct rcu_head rcu; +char element[0 ]__aligned(8) ; +}; + +static bool queue_map_is_prealloc (struct bpf_queue *queue) +{ +return !(queue->map.map_flags &BPF_F_NO_PREALLOC ); +} + +/* Called from syscall */ +static int queue_map_alloc_check (union bpf_attr *attr) +{ +/* check sanity of attributes */ +if (attr->max_entries ==0 || attr->key_size !=0 || + attr->value_size ==0 || attr->map_flags & ~QUEUE_CREATE_FLAG_MASK ) +return -EINVAL ; + +if ((attr->map_flags >>16 ) !=QUEUE_FIFO && + (attr->map_flags >>16 ) !=QUEUE_LIFO ) { +return -EINVAL ; + } + +if (attr->value_size >KMALLOC_MAX_SIZE ) +/* if value_size is bigger, the user space won't be able to +* access the elements. +*/ +return -E2BIG ; + +return 0 ; +} + +static int prealloc_init (struct bpf_queue *queue) +{ +u32 node_size =sizeof (struct queue_node ) + +round_up (queue->map.value_size,8 ); +u32 num_entries = queue->map.max_entries; +int err; + + queue->nodes =bpf_map_area_alloc (node_size * num_entries, + queue->map.numa_node); +if (!queue->nodes) +return -ENOMEM ; + + err =pcpu_freelist_init (&queue->freelist); +if (err) + goto free_nodes; + +pcpu_freelist_populate (&queue->freelist, + queue->nodes + + offsetof(struct queue_node , fnode), + node_size, num_entries); + +return 0 ; + +free_nodes: +bpf_map_area_free (queue->nodes); +return err; +} + +static void prealloc_destroy (struct bpf_queue *queue) +{ +bpf_map_area_free (queue->nodes); +pcpu_freelist_destroy (&queue->freelist); +} + +static struct bpf_map *queue_map_alloc (union bpf_attr *attr) +{ +struct bpf_queue *queue; +u64 cost =sizeof (*queue); +int ret; + + queue =kzalloc (sizeof (*queue),GFP_USER ); +if (!queue) +return ERR_PTR (-ENOMEM ); + +bpf_map_init_from_attr (&queue->map, attr); + + queue->node_size =sizeof (struct queue_node ) + +round_up (attr->value_size,8 ); + cost += (u64 ) attr->max_entries * queue->node_size; +if (cost >=U32_MAX -PAGE_SIZE ) { + ret = -E2BIG ; + goto free_queue; + } + + queue->map.pages =round_up (cost,PAGE_SIZE ) >>PAGE_SHIFT ; + + ret =bpf_map_precharge_memlock (queue->map.pages); +if (ret) + goto free_queue; + +INIT_LIST_HEAD (&queue->head); + +raw_spin_lock_init (&queue->lock); + + queue->type = attr->map_flags >>16 ; + +if (queue_map_is_prealloc (queue)) + ret =prealloc_init (queue); +if (ret) + goto free_queue; + +return &queue->map; + +free_queue: +kfree (queue); +return ERR_PTR (ret); +} + +/* Called when map->refcnt goes to zero, either from workqueue or from syscall */ +static void queue_map_free (struct bpf_map *map) +{ + struct bpf_queue *queue = container_of(map, struct bpf_queue, map); +struct queue_node *l; + +/* at this point bpf_prog->aux->refcnt == 0 and this map->refcnt == 0, +* so the programs (can be more than one that used this map) were +* disconnected from events. Wait for outstanding critical sections in +* these programs to complete +*/ +synchronize_rcu (); + +/* some of queue_elem_free_rcu() callbacks for elements of this map may +* not have executed. Wait for them. +*/ +rcu_barrier (); +if (!queue_map_is_prealloc (queue)) +list_for_each_entry_rcu (l, &queue->head, list) { +list_del_rcu (&l->list); +kfree (l); + } +else +prealloc_destroy (queue); +kfree (queue); +} + +static void queue_elem_free_rcu (struct rcu_head *head) +{ + struct queue_node *l = container_of(head, struct queue_node, rcu); +struct bpf_queue *queue = l->queue; + +/* must increment bpf_prog_active to avoid kprobe+bpf triggering while +* we're calling kfree, otherwise deadlock is possible if kprobes +* are placed somewhere inside of slub +*/ +preempt_disable (); +__this_cpu_inc (bpf_prog_active); +if (queue_map_is_prealloc (queue)) +pcpu_freelist_push (&queue->freelist, &l->fnode); +else +kfree (l); +__this_cpu_dec (bpf_prog_active); +preempt_enable (); +} + +/* Called from syscall or from eBPF program */ +static void *queue_map_lookup_elem (struct bpf_map *map,void *key) +{ + struct bpf_queue *queue = container_of(map, struct bpf_queue, map);
Quoted 8 lines
kernel/bpf/queuemap.c line 198
Quoted 4 lines
kernel/bpf/queuemap.c new file +4
-0+unsigned long flags; +struct queue_node *node; + +raw_spin_lock_irqsave (&queue->lock, flags);I think a per-cpu flavor would be very useful here as well in this map type such that we wouldn't need a lock here but only guarantee that preemption is disabled, and it could be used as temp store for the program for example.
I agree. I'd focus for now in the basic implementation, once it is ready we could go ahead with a per-cpu version.
Quoted 18 lines
Quoted 18 lines
kernel/bpf/queuemap.c new file +17
-0+ node = list_first_or_null_rcu(&queue->head, struct queue_node, list); +if (!node) { +raw_spin_unlock_irqrestore (&queue->lock, flags); +return NULL ; + } + +if (!queue_map_is_prealloc (queue)) +atomic_dec (&queue->count); + +list_del_rcu (&node->list); +call_rcu (&node->rcu, queue_elem_free_rcu); + +raw_spin_unlock_irqrestore (&queue->lock, flags); + +return &node->element; +} +
Quoted 8 lines
kernel/bpf/queuemap.c line 223
Quoted 7 lines
kernel/bpf/queuemap.c new file +7
-0+/* Called from syscall or from eBPF program */ +static int queue_map_update_elem (struct bpf_map *map,void *key,void *value, +u64 map_flags) +{ + struct bpf_queue *queue = container_of(map, struct bpf_queue, map); +unsigned long flags; +struct queue_node *new;Should reject invalid map update flags here.
Will do in new push helper proposed by Alexei.
Quoted 78 lines
Quoted 78 lines
kernel/bpf/queuemap.c new file +63
-0+if (!queue_map_is_prealloc (queue)) { +if (atomic_inc_return (&queue->count) > queue->map.max_entries) { +atomic_dec (&queue->count); +return -E2BIG ; + } + + new =kmalloc_node (queue->node_size,GFP_ATOMIC | __GFP_NOWARN, + queue->map.numa_node); +if (!new) { +atomic_dec (&queue->count); +return -ENOMEM ; + } + }else { +struct pcpu_freelist_node *l; + + l =pcpu_freelist_pop (&queue->freelist); +if (!l) +return -E2BIG ; + new = container_of(l, struct queue_node, fnode); + } + +memcpy (new->element, value, queue->map.value_size); + new->queue = queue; + +raw_spin_lock_irqsave (&queue->lock, flags); +switch (queue->type) { +case QUEUE_FIFO : +list_add_tail_rcu (&new->list, &queue->head); +break ; + +case QUEUE_LIFO : +list_add_rcu (&new->list, &queue->head); +break ; + } + +raw_spin_unlock_irqrestore (&queue->lock, flags); + +return 0 ; +} + +/* Called from syscall or from eBPF program */ +static int queue_map_delete_elem (struct bpf_map *map,void *key) +{ +return -EINVAL ; +} + +/* Called from syscall */ +static int queue_map_get_next_key (struct bpf_map *map,void *key, +void *next_key) +{ +return -EINVAL ; +} + +const struct bpf_map_ops queue_map_ops = { + .map_alloc_check = queue_map_alloc_check, + .map_alloc = queue_map_alloc, + .map_free = queue_map_free, + .map_lookup_elem = queue_map_lookup_elem, + .map_update_elem = queue_map_update_elem, + .map_delete_elem = queue_map_delete_elem, + .map_get_next_key = queue_map_get_next_key, +}; +kernel/bpf/syscall.c +6
-0@@ -622,11 +622,19 @@ static int map_lookup_elem(union bpf_attr *attr) err = -EPERM ; goto err_put; } +if (map->map_type !=BPF_MAP_TYPE_QUEUE ) { + key =memdup_user (ukey, map->key_size); +if (IS_ERR (key)) { + err =PTR_ERR (key); + goto err_put; + }
Quoted 8 lines
kernel/bpf/syscall.c static int map_lookup_elem(union bpf_attr *attr) · line 635
Quoted 5 lines
kernel/bpf/syscall.c +5
-0+ }else { +if (ukey) { + err = -EINVAL ; + goto err_put; + }Given you have a fixed
key_sizeof 0, this could probably be made more generic and refactored a bit into a helper to check for 0map->key_sizeinstead of map type.
With a new set of helpers following changes are not needed anymore.
Quoted 126 lines
Quoted 21 lines
kernel/bpf/syscall.c +5
-8- key =memdup_user (ukey, map->key_size); -if (IS_ERR (key)) { - err =PTR_ERR (key); - goto err_put; + key =NULL ; } if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||@@ -709,10 +717,19 @@ static int map_update_elem(union bpf_attr *attr) goto err_put; } - key =memdup_user (ukey, map->key_size); -if (IS_ERR (key)) { - err =PTR_ERR (key); - goto err_put; +if (map->map_type !=BPF_MAP_TYPE_QUEUE ) { + key =memdup_user (ukey, map->key_size); +if (IS_ERR (key)) { + err =PTR_ERR (key);kernel/bpf/syscall.c static int map_update_elem(union bpf_attr *attr) · line 733
Quoted 10 lines
kernel/bpf/syscall.c +9
-0+ goto err_put; + } + }else { +if (ukey) { + err = -EINVAL ; + goto err_put; + } + + key =NULL ; }Ditto, and also further below as well for the other syscall cases.
Quoted 72 lines
kernel/bpf/syscall.c +21
-7if (map->map_type == BPF_MAP_TYPE_PERCPU_HASH ||@@ -803,10 +820,19 @@ static int map_delete_elem(union bpf_attr *attr) goto err_put; } - key =memdup_user (ukey, map->key_size); -if (IS_ERR (key)) { - err =PTR_ERR (key); - goto err_put; +if (map->map_type !=BPF_MAP_TYPE_QUEUE ) { + key =memdup_user (ukey, map->key_size); +if (IS_ERR (key)) { + err =PTR_ERR (key); + goto err_put; + } + }else { +if (ukey) { + err = -EINVAL ; + goto err_put; + } + + key =NULL ; }if (bpf_map_is_dev_bound (map)) {@@ -855,9 +881,14 @@ static int map_get_next_key(union bpf_attr *attr) }if (ukey) { - key =memdup_user (ukey, map->key_size); -if (IS_ERR (key)) { - err =PTR_ERR (key); +if (map->map_type !=BPF_MAP_TYPE_QUEUE ) { + key =memdup_user (ukey, map->key_size); +if (IS_ERR (key)) { + err =PTR_ERR (key); + goto err_put; + } + }else { + err = -EINVAL ; goto err_put; } }else {kernel/bpf/verifier.c +7
-2@@ -1976,8 +1976,12 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 regno,return -EACCES ; } -if (arg_type ==ARG_PTR_TO_MAP_KEY || - arg_type ==ARG_PTR_TO_MAP_VALUE ) { +if (arg_type ==ARG_PTR_TO_MAP_KEY ) { + expected_type =PTR_TO_STACK ; +if (!type_is_pkt_pointer (type) && type !=PTR_TO_MAP_VALUE && + type != expected_type && type !=SCALAR_VALUE ) + goto err_type; + }else if (arg_type ==ARG_PTR_TO_MAP_VALUE ) { expected_type =PTR_TO_STACK ;if (!type_is_pkt_pointer (type) && type !=PTR_TO_MAP_VALUE && type != expected_type)@@ -2021,6 +2025,7 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 regno,/* bpf_map_xxx(map_ptr) call: remember that map_ptr */ meta->map_ptr = reg->map_ptr; }else if (arg_type ==ARG_PTR_TO_MAP_KEY ) { +bool zero_size_allowed = false;/* bpf_map_xxx(..., map_ptr, ..., key) call: * check that [key, key + map->key_size) are within * stack limits and initialized kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 regno, · line 2043
Quoted 5 lines
kernel/bpf/verifier.c +2
-0@@ -2034,8 +2039,13 @@ static int check_func_arg(struct bpf_verifier_env *env, u32 regno,verbose (env,"invalid map_ptr to access map->key\n" );return -EACCES ; } + +if (meta->map_ptr->map_type ==BPF_MAP_TYPE_QUEUE )Here as well.
kernel/bpf/verifier.c static int check_func_arg(struct bpf_verifier_env *env, u32 regno, · line 2044
Quoted 1 line
kernel/bpf/verifier.c +1
-0+ zero_size_allowed = true;Also, verifier should rather enforce a const NULL key here than allowing one to be set (but not as the only 'valid' input option), meaning, I don't think it would be good to allow a 'zero' sized pointer to stack in this case.
Quoted 8 lines
kernel/bpf/verifier.c +2
-1err =check_helper_mem_access (env, regno, - meta->map_ptr->key_size, false, + meta->map_ptr->key_size, + zero_size_allowed,NULL ); }else if (arg_type ==ARG_PTR_TO_MAP_VALUE ) {/* bpf_map_xxx(..., map_ptr, ..., value) call:
Re: [PATCH bpf-next 3/3] bpf: add sample for BPF_MAP_TYPE_QUEUE
In reply to Daniel BorkmannQuoted 66 lines · Daniel Borkmann
Quoted 65 lines · Mauricio Vasquez B
The example is made by two parts, a eBPF program that consumes elements from a FIFO queue and prints them in the screen and a user space application that inserts new elements into the queue each time this is executed.
Signed-off-by Mauricio Vasquez B <[email protected]>--- samples/bpf/.gitignore | 1 + samples/bpf/Makefile | 3 ++ samples/bpf/test_map_in_map_user.c | 9 +----- samples/bpf/test_queuemap.sh | 37 +++++++++++++++++++++++++ samples/bpf/test_queuemap_kern.c | 51 +++++++++++++++++++++++++++++++++++ samples/bpf/test_queuemap_user.c | 53 ++++++++++++++++++++++++++++++++++++ 6 files changed, 147 insertions(+), 7 deletions(-)create mode 100755
samples/bpf/test_queuemap.shcreate mode 100644samples/bpf/test_queuemap_kern.ccreate mode 100644samples/bpf/test_queuemap_user.csamples/bpf/.gitignore +1
-0@@ -26,6 +26,7 @@ test_lru_dist test_map_in_map test_overhead test_probe_write_user +test_queuemap trace_event trace_output tracex1samples/bpf/Makefile +3
-0@@ -53,6 +53,7 @@ hostprogs-y += xdpsock hostprogs-y += xdp_fwd hostprogs-y += task_fd_query hostprogs-y += xdp_sample_pkts +hostprogs-y += test_queuemap # Libbpf dependencies LIBBPF = $(TOOLS_PATH)/lib/bpf/libbpf.a@@ -109,6 +110,7 @@ xdpsock-objs := xdpsock_user.o xdp_fwd-objs := xdp_fwd_user.o task_fd_query-objs := bpf_load.o task_fd_query_user.o $(TRACE_HELPERS) xdp_sample_pkts-objs := xdp_sample_pkts_user.o $(TRACE_HELPERS) +test_queuemap-objs := bpf_load.o test_queuemap_user.o # Tell kbuild to always build the programs always := $(hostprogs-y)@@ -166,6 +168,7 @@ always += xdpsock_kern.o always += xdp_fwd_kern.o always += task_fd_query_kern.o always += xdp_sample_pkts_kern.o +always += test_queuemap_kern.o HOSTCFLAGS += -I$(objtree)/usr/include HOSTCFLAGS += -I$(srctree)/tools/lib/samples/bpf/test_map_in_map_user.c +0
-2@@ -1,10 +1,5 @@ -/* -* Copyright (c) 2017 Facebook
Quoted 8 lines
samples/bpf/test_map_in_map_user.c line 2
Quoted 7 lines
samples/bpf/test_map_in_map_user.c +2
-5-* -* This program is free software; you can redistribute it and/or -* modify it under the terms of version 2 of the GNU General Public -* License as published by the Free Software Foundation. -*/ +// SPDX-License-Identifier: GPL-2.0 +/* Copyright (c) 2018 Politecnico di Torino */ I don't think you can remove above Copyright and replace it with a different one. ;)
Copy-paste on the wrong file. :/
Quoted 94 lines
Quoted 94 lines
samples/bpf/test_map_in_map_user.c +0
-0#include <sys/resource.h> #include <sys/socket.h> #include <arpa/inet.h> samples/bpf/test_queuemap.sh new file +37
-0@@ -0,0 +1,37 @@ +#!/bin/bash +# SPDX-License-Identifier: GPL-2.0 + +[[ -z $TC ]] && TC='tc' +[[ -z $IP ]] && IP='ip' + +TEST_QUEUE_USER='./test_queuemap' +TEST_QUEUE_BPF='./test_queuemap_kern.o' + +function config { + $IP netns add ns1 + $IP link add ve1 type veth peer name vens1 + $IP link set dev ve1 up + $IP link set dev ve1 mtu 1500 + $IP link set dev vens1 netns ns1 + + $IP -n ns1 link set dev lo up + $IP -n ns1 link set dev vens1 up + $IP -n ns1 addr add 10.1.1.101/24 dev vens1 + + $IP addr add 10.1.1.1/24 dev ve1 + $TC qdisc add dev ve1 clsact + $TC filter add dev ve1 ingress bpf da obj $TEST_QUEUE_BPF sec test_queue +} + +function cleanup { + set +e + [[ -z $DEBUG ]] || set +x + $IP netns delete ns1 >& /dev/null + $IP link del ve1 >& /dev/null + rm -f /sys/fs/bpf/tc/globals/queue + [[ -z $DEBUG ]] || set -x + set -e +} + +cleanup +configsamples/bpf/test_queuemap_kern.c new file +41
-0@@ -0,0 +1,51 @@ +// SPDX-License-Identifier: GPL-2.0 +/* Copyright (c) 2018 Politecnico di Torino */ +#define KBUILD_MODNAME "foo" +#include <linux/ptrace.h> +#include <linux/version.h> +#include <uapi/linux/bpf.h> +#include <uapi/linux/in6.h> +#include <uapi/linux/pkt_cls.h> +#include "bpf_helpers.h" + +#define PIN_GLOBAL_NS 2 + +struct bpf_elf_map { +__u32 type; +__u32 key_size; +__u32 value_size; +__u32 max_entries; +__u32 flags; +__u32 id; +__u32 pinning; +}; + +/* map #0 */ +struct bpf_elf_map SEC("maps") queue = { + .type = BPF_MAP_TYPE_QUEUE, + .key_size = 0, + .value_size = sizeof(u32), + .flags = BPF_F_QUEUE_FIFO, + .max_entries = 1024, + .pinning = PIN_GLOBAL_NS, +}; + +SEC("test_queue") +int _test_queue (struct __sk_buff *skb) +{ +char msg[] ="element is %u\n" ; +char msg_no[] ="there are not elements\n" ; + +u32 *val =bpf_map_lookup_elem (&queue,NULL ); + +if (!val) {
Quoted 8 lines
samples/bpf/test_queuemap_kern.c line 46
Quoted 5 lines
samples/bpf/test_queuemap_kern.c new file +5
-0+bpf_trace_printk (msg_no,sizeof (msg_no)); +return TC_ACT_OK ; + } + +bpf_trace_printk (msg,sizeof (msg), *val);Could we add a more elaborate example? In cover letter and patch 1 which implements the map, you mention SNAT, perhaps it would be useful to make it a minimal sample app.
I'll try to create a minimal sample of a SNAT.
Quoted 67 lines
Quoted 66 lines
samples/bpf/test_queuemap_kern.c new file +5
-0+return TC_ACT_OK ; +} + +char _license[] SEC("license") = "GPL"; +u32 _version SEC("version") = LINUX_VERSION_CODE;samples/bpf/test_queuemap_user.c new file +53
-0@@ -0,0 +1,53 @@ +/* +* Copyright (c) 2018 Politecnico di Torino +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of version 2 of the GNU General Public +* License as published by the Free Software Foundation. +*/ +#include <sys/resource.h> +#include <sys/socket.h> +#include <arpa/inet.h> +#include <stdint.h> +#include <assert.h> +#include <errno.h> +#include <stdlib.h> +#include <stdio.h> +#include <bpf/bpf.h> +#include "bpf_load.h" + +int queue_map; + +static void test_queue_map (void ) +{ +int ret; +uint32_t i; + + queue_map =bpf_obj_get ("/sys/fs/bpf/tc/globals/queue" ); +if (queue_map <0 ) { +fprintf (stderr,"error getting map" ); +return ; + } + +for (i =0 ; i <256 ; i++) { +uint32_t v =1000 - i*3 ; + + ret =bpf_map_update_elem (queue_map,NULL , &v,0 ); +if (ret) +fprintf (stderr,"ret is %d\n" , ret); + } +} + +int main (int argc,char **argv) +{ +struct rlimit r = {RLIM_INFINITY ,RLIM_INFINITY }; +char filename[256 ]; + +assert (!setrlimit (RLIMIT_MEMLOCK , &r)); + +snprintf (filename,sizeof (filename),"%s_kern.o" , argv[0 ]); + +test_queue_map (); + +return 0 ; +}
Re: [PATCH bpf-next 1/3] bpf: add bpf queue map
In reply to Daniel BorkmannQuoted 11 lines · Daniel Borkmann
Quoted 9 lines · Mauricio Vasquez B
Bpf queue implements a LIFO/FIFO data containers for ebpf programs.
It allows to push an element to the queue by using the update operation and to pop an element from the queue by using the lookup operation.
A use case for this is to keep track of a pool of elements, like network ports in a SNAT.
Signed-off-by Mauricio Vasquez B <[email protected]>[...]
Quoted 14 lines
kernel/bpf/queuemap.c line 75
Quoted 9 lines
kernel/bpf/queuemap.c new file +9
-0+static int prealloc_init (struct bpf_queue *queue) +{ +u32 node_size =sizeof (struct queue_node ) + +round_up (queue->map.value_size,8 ); +u32 num_entries = queue->map.max_entries; +int err; + + queue->nodes =bpf_map_area_alloc (node_size * num_entries, + queue->map.numa_node);That doesn't work either. If you don't set numa node, then here in your case you'll always use numa node 0, which is unintentional. You need to get the node via
bpf_map_attr_numa_node(attr)helper. Same issue inqueue_map_update_elem().
This should work, map.numa_node is initialized using bpf_map_attr_numa_node() in bpf_map_init_from_attr()
The htab does exactly the same.
Re: [PATCH bpf-next 1/3] bpf: add bpf queue map
In reply to Alexei StarovoitovQuoted 46 lines · Alexei Starovoitov
Quoted 1 line · Mauricio Vasquez B
Bpf queue implements a LIFO/FIFO data containers for ebpf programs.
queue/stack datastructure would be a great addition.
Quoted 42 lines
It allows to push an element to the queue by using the update operation and to pop an element from the queue by using the lookup operation.
A use case for this is to keep track of a pool of elements, like network ports in a SNAT.
Signed-off-by Mauricio Vasquez B <[email protected]>--- include/linux/bpf_types.h | 1 include/uapi/linux/bpf.h | 5 + kernel/bpf/Makefile | 2 kernel/bpf/queuemap.c | 287 +++++++++++++++++++++++++++++++++++++++++++++ kernel/bpf/syscall.c | 61 +++++++--- kernel/bpf/verifier.c | 16 ++- 6 files changed, 353 insertions(+), 19 deletions(-)create mode 100644
kernel/bpf/queuemap.cinclude/linux/bpf_types.h +1
-0@@ -58,3 +58,4 @@ BPF_MAP_TYPE(BPF_MAP_TYPE_CPUMAP, cpu_map_ops) BPF_MAP_TYPE(BPF_MAP_TYPE_XSKMAP, xsk_map_ops)#endif #endif +BPF_MAP_TYPE (BPF_MAP_TYPE_QUEUE , queue_map_ops)include/uapi/linux/bpf.h +1
-0@@ -120,6 +120,7 @@ enum bpf_map_type {BPF_MAP_TYPE_CPUMAP ,BPF_MAP_TYPE_XSKMAP ,BPF_MAP_TYPE_SOCKHASH , + BPF_MAP_TYPE_QUEUE, }; enum bpf_prog_type {@@ -255,6 +256,10 @@ enum bpf_attach_type {/* Flag for stack_map, store build_id+offset instead of pointer */ #define BPF_F_STACK_BUILD_ID (1U << 5)
Quoted 9 lines
include/uapi/linux/bpf.h enum bpf_attach_type { · line 261
Quoted 3 lines
include/uapi/linux/bpf.h +3
-0+/* Flags for queue_map, type of queue */ +#define BPF_F_QUEUE_FIFO (1U << 16) +#define BPF_F_QUEUE_LIFO (2U << 16)the choice of flags looks odd.
Why start at bit 16 and why waste two bits?
It's either stack or queue.
May be instead define twomap_types:BPF_MAP_TYPE_QUEUEandBPF_MAP_TYPE_STACK
that share common implementation?
I like this solution, I'll spin a v2 with two different types of maps.
Quoted 5 lines
And how about adding three new helpers: push/pop/peek as well? Reusing lookup/update is neat, but does lookup == pop
or does lookup == peek ?
I suspect it will be confusing.
Three new helpers cost nothing, but will make bpf progs easier to read.
I agree. I have one doubt here, update/lookup/delete is implemented in all map types, if the operation is not supported it returns -EINVAL. For push/pop/peek, should we implement it in all maps or is it better to check the map type before invoking map->ops->push/pop/seek? (Maybe checking if map->ops->xxx is NULL will also work)
Quoted 8 lines
Could you also add a flag for replacement policy?
In this implementation whenmax_entrieslimit is reached themap_update_elem(aka push) will fail with e2big. It would be useful to allow pushing and dropping elements from the other side then such queue/stack can be used to keep track of the last N events (the prog would unconditionally push and user space would swap the queue for new one via map-in-map and drain old queue).
I like it, will do.
Quoted 2 lines
Speaking of map-in-map, please add a test to make sure queue/stack works with hash/array_of_maps.
Sure.
Quoted 3 lines
selftests in patch2 needs to have kernel side as well. it's not enough to test syscall access only.
Will do.
Re: [PATCH bpf-next 1/3] bpf: add bpf queue map
Quoted 11 lines · Mauricio Vasquez
Quoted 6 lines
And how about adding three new helpers: push/pop/peek as well? Reusing lookup/update is neat, but does lookup == pop
or does lookup == peek ?
I suspect it will be confusing.
Three new helpers cost nothing, but will make bpf progs easier to read.I agree. I have one doubt here, update/lookup/delete is implemented in all map types, if the operation is not supported it returns
-EINVAL. For push/pop/peek, should we implement it in all maps or is it better to check the map type before invoking map->ops->push/pop/seek? (Maybe checking ifmap->ops->xxxis NULL will also work)
Since push/pop/peak are only for this queue/stack I thought we won't be adding 'ops' for them and just call the helpers from progs. But now I'm having second thoughts, since 3 new commands for syscall feels like overkill.
At the same time I still don't feel that lookup == pop is the right alias. Also what peak is going to alias to ?
May be let's go back to your original idea with a tweak:
push == update
peak == lookup
pop = lookup + delete
In other words in case of stack the bpf_map_lookup_elem will return the pointer to value of top element in the stack and bpf_map_delete_elem will delete that top element.
Then in user space we can introduce push/pop always_inline functions like:
void bpf_push(struct bpf_map *map, void *value)
{
bpf_map_update_elem(map, NULL/*key*/, value);
}
void *bpf_pop(struct bpf_map *map)
{
void * val = bpf_map_lookup_elem(map, NULL/*key*/); bpf_map_delete_elem(map, NULL/*key*/); return val;
}
Thoughts?
Daniel Borkmann
maintainerRe: [PATCH bpf-next 1/3] bpf: add bpf queue map
Quoted 32 lines · Alexei Starovoitov
Quoted 11 lines · Mauricio Vasquez
Quoted 6 lines
And how about adding three new helpers: push/pop/peek as well? Reusing lookup/update is neat, but does lookup == pop
or does lookup == peek ?
I suspect it will be confusing.
Three new helpers cost nothing, but will make bpf progs easier to read.I agree. I have one doubt here, update/lookup/delete is implemented in all map types, if the operation is not supported it returns
-EINVAL. For push/pop/peek, should we implement it in all maps or is it better to check the map type before invoking map->ops->push/pop/seek? (Maybe checking ifmap->ops->xxxis NULL will also work)Since push/pop/peak are only for this queue/stack I thought we won't be adding 'ops' for them and just call the helpers from progs. But now I'm having second thoughts, since 3 new commands for syscall feels like overkill.
At the same time I still don't feel that lookup == pop is the right alias. Also what peak is going to alias to ?
May be let's go back to your original idea with a tweak:
push == update
peak == lookup
pop = lookup + delete
In other words in case of stack thebpf_map_lookup_elemwill return the pointer to value of top element in the stack andbpf_map_delete_elemwill delete that top element.
Then in user space we can introduce push/popalways_inlinefunctions like:
voidbpf_push(struct bpf_map *map, void *value)
{
bpf_map_update_elem(map, NULL/*key*/, value);
}
Quoted 8 lines
void *bpf_pop(struct
bpf_map*map)
{
void * val =bpf_map_lookup_elem(map, NULL/*key*/);bpf_map_delete_elem(map, NULL/*key*/); return val;
}Thoughts?
I actually think that having new push/peak/pop BPF map helpers would be fine, as well as having them sit in map->ops. Initially I'd probably leave out the syscall ops counterparts so they can be used only from program.
Potentially array and per-cpu array could implement them even by having an internal pointer to the current slot which we move on push/pop. This would potentially also avoid all the RCU callbacks to free the elements, elem allocations, list locking, and improve cache locality compared to the current implementation.
Agree that existing ops are not the right alias, but deferring to user space as inline function also doesn't really seem like a good fit, imho, so I'd prefer rather to have something native. (Aside from that, the above inline bpf_pop() would also race between CPUs.)
Thanks,
Daniel
Re: [PATCH bpf-next 1/3] bpf: add bpf queue map
Quoted 38 lines · Daniel Borkmann
Quoted 37 lines · Alexei Starovoitov
Quoted 10 lines · Mauricio Vasquez
Quoted 5 lines
And how about adding three new helpers: push/pop/peek as well? Reusing lookup/update is neat, but does lookup == pop
or does lookup == peek ?
I suspect it will be confusing.
Three new helpers cost nothing, but will make bpf progs easier to read.I agree. I have one doubt here, update/lookup/delete is implemented in all map types, if the operation is not supported it returns
-EINVAL. For push/pop/peek, should we implement it in all maps or is it better to check the map type before invoking map->ops->push/pop/seek? (Maybe checking ifmap->ops->xxxis NULL will also work)Since push/pop/peak are only for this queue/stack I thought we won't be adding 'ops' for them and just call the helpers from progs. But now I'm having second thoughts, since 3 new commands for syscall feels like overkill.
At the same time I still don't feel that lookup == pop is the right alias. Also what peak is going to alias to ?
May be let's go back to your original idea with a tweak:
push == update
peak == lookup
pop = lookup + delete
In other words in case of stack thebpf_map_lookup_elemwill return the pointer to value of top element in the stack andbpf_map_delete_elemwill delete that top element.
Then in user space we can introduce push/popalways_inlinefunctions like:
voidbpf_push(struct bpf_map *map, void *value){ bpf_map_update_elem(map, NULL/*key*/, value); }void *bpf_pop(struct
bpf_map*map){ void * val = bpf_map_lookup_elem(map, NULL/*key*/); bpf_map_delete_elem(map, NULL/*key*/); return val; }
Quoted 5 lines
Quoted 1 line
Thoughts?
I actually think that having new push/peak/pop BPF map helpers would be fine, as well as having them sit in
map->ops. Initially I'd probably leave out the syscall ops counterparts so they can be used only from program.
I also think that having the new helpers is good. I don't have a strong opinion about saving them in map->ops or not, in any case it has to be verified that push/pop/peek are only invoked in stack/queue maps. I think we could force in on the verifier, would it be ok?
Quoted 5 lines
Potentially array and per-cpu array could implement them even by having an internal pointer to the current slot which we move on push/pop. This would potentially also avoid all the RCU callbacks to free the elements, elem allocations, list locking, and improve cache locality compared to the current implementation.
I could change the implementation, a linked list is used when BPF_F_NO_PREALLOC is passed, otherwise a plain array with internal indexes is used.
I have a question about RCU and a possible array-based implementation. It should be guarantee that a pointer from a pop() operation is valid for the whole program duration.
If an eBPF program A calls pop() it will get a pointer to the head in the array, and the head index will move, it is possible that a second program B (running on a different CPU) pushes a new element overwriting the element pointed by A. I think we need to use a more sophisticated mechanism than just an array and two indexes. Am I missing something?
Quoted 4 lines
Agree that existing ops are not the right alias, but deferring to user space as inline function also doesn't really seem like a good fit, imho, so I'd prefer rather to have something native. (Aside from that, the above inline
bpf_pop()would also race between CPUs.)
I think we should have push/pop/peek syscalls as well, having a bpf_pop() that is race prone would create problems. Users expected maps operations to be safe, so having one that is not will confuse them.
Quoted 3 lines
Thanks,
Daniel
Thanks,
Mauricio.
Re: [PATCH bpf-next 1/3] bpf: add bpf queue map
Quoted 9 lines · Mauricio Vasquez
Quoted 5 lines
Agree that existing ops are not the right alias, but deferring to user space as inline function also doesn't really seem like a good fit, imho, so I'd prefer rather to have something native. (Aside from that, the above inline
bpf_pop()would also race between CPUs.)I think we should have push/pop/peek syscalls as well, having a
bpf_pop()that is race prone would create problems. Users expected maps operations to be safe, so having one that is not will confuse them.
agree the races are not acceptable.
How about a mixed solution:
- introduce bpf_push/pop/peak helpers that programs will use, so they don't need to pass useless key=NULL
- introduce map->ops->lookup_and_delete and map->ops->lookup_or_init that prog-side helpers can use and syscall has 1-1 mapping for
Native lookup_or_init() helper for programs and syscall is badly missing. Most of the bcc scripts use it and bcc has a racy workaround. Similarly lookup_and_delete() syscall is 1-1 to pop() for stack/queue and useful for regular hash maps.
At the end for stack/queue map the programs will use:
int bpf_push(map, value);value_or_null = bpf_pop(map); // guaranteed non-racy for multi-cpu value_or_null = bpf_peak(map); // racy if 2+ cpus doing it
from syscall:bpf_map_lookup_elem(map, NULL, &value); // returns top of stack bpf_map_lookup_and_delete_elem(map, NULL, &value); // returns top and deletes top atomically bpf_map_update_elem(map, NULL, &value); // pushes new value into stack atomically
Eventually hash and other maps will implement bpf_map_lookup_and_delete() for both bpf progs and syscall.
The main point that prog-side api doesn't have to match 1-1 to syscall-side, since they're different enough already.
Like lookup_or_init() is badly needed for programs, but unnecessary for syscall.
Thoughts?
Re: [PATCH bpf-next 1/3] bpf: add bpf queue map
Quoted 8 lines · Alexei Starovoitov
Quoted 7 lines · Mauricio Vasquez
Quoted 4 lines
Agree that existing ops are not the right alias, but deferring to user space as inline function also doesn't really seem like a good fit, imho, so I'd prefer rather to have something native. (Aside from that, the above inline
bpf_pop()would also race between CPUs.)I think we should have push/pop/peek syscalls as well, having a
bpf_pop()that is race prone would create problems. Users expected maps operations to be safe, so having one that is not will confuse them.
Quoted 6 lines
agree the races are not acceptable.
How about a mixed solution:
- introduce bpf_push/pop/peak helpers that programs will use, so they don't need to pass useless key=NULL
- introducemap->ops->lookup_and_deleteandmap->ops->lookup_or_initthat prog-side helpers can use and syscall has 1-1 mapping for
I think if is a fair solution.
Quoted 7 lines
Native
lookup_or_init()helper for programs and syscall is badly missing. Most of the bcc scripts use it and bcc has a racy workaround. Similarlylookup_and_delete()syscall is 1-1 topop()for stack/queue and useful for regular hash maps.At the end for stack/queue map the programs will use:
intbpf_push(map, value);
Also flags should be passed here.
Quoted 2 lines
value_or_null=bpf_pop(map); // guaranteed non-racy for multi-cpuvalue_or_null=bpf_peak(map); // racy if 2+ cpus doing it
Is there any reason for it to be racy?
Quoted 6 lines
from syscall:
bpf_map_lookup_elem(map, NULL, &value); // returns top of stackbpf_map_lookup_and_delete_elem(map, NULL, &value); // returns top and deletes top atomicallybpf_map_update_elem(map, NULL, &value); // pushes new value into stack atomically
Quoted 9 lines
Eventually hash and other maps will implement
bpf_map_lookup_and_delete()for both bpf progs and syscall.The main point that prog-side api doesn't have to match 1-1 to syscall-side, since they're different enough already.
Likelookup_or_init()is badly needed for programs, but unnecessary for syscall.Thoughts?
I agree with the idea, if there are not more thoughts on this I'd proceed to the implementation.
Re: [PATCH bpf-next 1/3] bpf: add bpf queue map
Quoted 23 lines · Mauricio Vasquez
Quoted 8 lines · Alexei Starovoitov
Quoted 7 lines · Mauricio Vasquez
Quoted 4 lines
Agree that existing ops are not the right alias, but deferring to user space as inline function also doesn't really seem like a good fit, imho, so I'd prefer rather to have something native. (Aside from that, the above inline
bpf_pop()would also race between CPUs.)I think we should have push/pop/peek syscalls as well, having a
bpf_pop()that is race prone would create problems. Users expected maps operations to be safe, so having one that is not will confuse them.Quoted 6 lines
agree the races are not acceptable.
How about a mixed solution:
- introduce bpf_push/pop/peak helpers that programs will use, so they don't need to pass useless key=NULL
- introducemap->ops->lookup_and_deleteandmap->ops->lookup_or_initthat prog-side helpers can use and syscall has 1-1 mapping forI think if is a fair solution.
Quoted 5 lines
Native
lookup_or_init()helper for programs and syscall is badly missing. Most of the bcc scripts use it and bcc has a racy workaround. Similarlylookup_and_delete()syscall is 1-1 topop()for stack/queue and useful for regular hash maps.
Quoted 4 lines
Quoted 2 lines
At the end for stack/queue map the programs will use:
intbpf_push(map, value);Also flags should be passed here.
Good point about flags. Indeed flags should be there for extensibility, but I cannot think of use case for them at the moment. hash's exist/noexist don't apply here.
Would be good to have at least one bit in use from the start.
Quoted 4 lines
Quoted 3 lines
value_or_null=bpf_pop(map); // guaranteed non-racy for multi-cpuvalue_or_null=bpf_peak(map); // racy if 2+ cpus doing itIs there any reason for it to be racy?
because two cpus will be looking at the same element? whethere implementation is array based or link list with rcu the race is still there.