bpf: introduce per-cpu maps
Subsystems (4)
PATCH 1/6 bpf: introduce BPF_MAP_TYPE_PERCPU_HASH map
In reply to Alexei StarovoitovIntroduce BPF_MAP_TYPE_PERCPU_HASH map type which is used to do accurate counters without need to use BPF_XADD instruction which turned out to be too costly for high-performance network monitoring. In the typical use case the 'key' is the flow tuple or other long living object that sees a lot of events per second.
bpf_map_lookup_elem() returns per-cpu area. Example:
struct {
u32 packets;
u32 bytes;
} * ptr = bpf_map_lookup_elem(&map, &key);
/* ptr points to this_cpu area of the value, so the following
* increments will not collide with other cpus
*/ptr->packets ++;ptr->bytes += skb->len;
bpf_update_elem() atomically creates a new element where all per-cpu values are zero initialized and this_cpu value is populated with given 'value'.
Note that non-per-cpu hash map always allocates new element and then deletes old after rcu grace period to maintain atomicity of update. Per-cpu hash map updates element values in-place.
--- include/uapi/linux/bpf.h | 1 + kernel/bpf/hashtab.c | 275 +++++++++++++++++++++++++++++++++++++++-------- 2 files changed, 229 insertions(+), 47 deletions(-)
include/uapi/linux/bpf.h +1 -0
@@ -81,6 +81,7 @@ enum bpf_map_type {BPF_MAP_TYPE_ARRAY ,BPF_MAP_TYPE_PROG_ARRAY ,BPF_MAP_TYPE_PERF_EVENT_ARRAY , + BPF_MAP_TYPE_PERCPU_HASH, }; enum bpf_prog_type {
kernel/bpf/hashtab.c +228 -47
391 lines not on this page · raw message
Signature · 1 line
2.4.6
PATCH 2/6 bpf: introduce BPF_MAP_TYPE_PERCPU_ARRAY map
In reply to Alexei StarovoitovPrimary use case is a histogram array of latency
where bpf program computes the latency of block requests or other events and stores histogram of latency into array of 64 elements. All cpus are constantly running, so normal increment is not accurate, bpf_xadd causes cache ping-pong and this per-cpu approach allows fastest collision-free counters.
--- include/linux/bpf.h | 1 + include/uapi/linux/bpf.h | 1 + kernel/bpf/arraymap.c | 102 ++++++++++++++++++++++++++++++++++++++++++----- 3 files changed, 93 insertions(+), 11 deletions(-)
include/linux/bpf.h +1 -0
@@ -151,6 +151,7 @@ struct bpf_array {union {char value[0 ]__aligned(8) ;void *ptrs[0 ]__aligned(8) ; +void __percpu *pptrs[0 ]__aligned(8) ; }; };#define MAX_TAIL_CALL_CNT 32
include/uapi/linux/bpf.h +1 -0
@@ -82,6 +82,7 @@ enum bpf_map_type {BPF_MAP_TYPE_PROG_ARRAY ,BPF_MAP_TYPE_PERF_EVENT_ARRAY ,BPF_MAP_TYPE_PERCPU_HASH , + BPF_MAP_TYPE_PERCPU_ARRAY, }; enum bpf_prog_type {
kernel/bpf/arraymap.c +91 -11
172 lines not on this page · raw message
Signature · 1 line
2.4.6
cover bpf: introduce per-cpu maps
We've started to use bpf to trace every packet and atomic add instruction (event JITed) started to show up in perf profile. The solution is to do per-cpu counters.
For PERCPU_(HASH|ARRAY) map the existing bpf_map_lookup() helper returns per-cpu area which bpf programs can use to store and increment the counters. The BPF_MAP_LOOKUP_ELEM syscall command returns areas from all cpus and user process aggregates the counters. The usage example is in patch 6. The api turned out to be very easy to use from bpf program and from user space.
Long term we were discussing to add 'bounded loop' instruction, so bpf programs can do aggregation within the program which may help some use cases. Right now user space aggregation of per-cpu counters fits the best.
This patch set is new approach for per-cpu hash and array maps. I've reused the map tests written by Martin and Ming, but implementation and api is new. Old discussion here:
http://thread.gmane.org/gmane.linux.kernel/2123800/focus=2126435
Alexei Starovoitov (4):
bpf: introduce BPF_MAP_TYPE_PERCPU_HASH map
bpf: introduce BPF_MAP_TYPE_PERCPU_ARRAY map
bpf: add lookup/update support for per-cpu hash and array maps samples/bpf: update tracex[23] examples to use per-cpu maps
Martin KaFai Lau (1):
samples/bpf: unit test for BPF_MAP_TYPE_PERCPU_HASH
[email protected] (1):
samples/bpf: unit test for BPF_MAP_TYPE_PERCPU_ARRAY
include/linux/bpf.h | 24 ++++ include/uapi/linux/bpf.h | 2 + kernel/bpf/arraymap.c | 166 ++++++++++++++++++++-- kernel/bpf/hashtab.c | 340 ++++++++++++++++++++++++++++++++++++++------- kernel/bpf/syscall.c | 57 +++++--- samples/bpf/test_maps.c | 188 +++++++++++++++++++++++++ samples/bpf/tracex2_kern.c | 2 +- samples/bpf/tracex2_user.c | 7 +- samples/bpf/tracex3_kern.c | 8 +- samples/bpf/tracex3_user.c | 21 ++- 10 files changed, 727 insertions(+), 88 deletions(-)
Signature · 1 line
2.4.6
PATCH 3/6 bpf: add lookup/update support for per-cpu hash and array maps
The functions bpf_map_lookup_elem(map, key, value) and bpf_map_update_elem(map, key, value, flags) need to get/set values from all-cpus for per-cpu hash and array maps, so that user space can aggregate/update them as necessary.
Example of single counter aggregation in user space:
unsigned int nr_cpus = sysconf(_SC_NPROCESSORS_CONF); long values[nr_cpus];
long value = 0;
bpf_lookup_elem(fd, key, values);
for (i = 0; i < nr_cpus; i++)
value += values[i];The user space must provide round_up(value_size, 8) * nr_cpus array to get/set values, since kernel will use 'long' copy of per-cpu values to try to copy good counters atomically. It's a best-effort, since bpf programs and user space are racing to access the same memory.
--- include/linux/bpf.h | 23 ++++++++++++++ kernel/bpf/arraymap.c | 64 +++++++++++++++++++++++++++++++++++++++ kernel/bpf/hashtab.c | 83 +++++++++++++++++++++++++++++++++++++++++++++------ kernel/bpf/syscall.c | 57 ++++++++++++++++++++++++----------- 4 files changed, 201 insertions(+), 26 deletions(-)
include/linux/bpf.h +23 -0
@@ -183,6 +183,29 @@ int bpf_prog_new_fd(struct bpf_prog *prog);int bpf_obj_pin_user (u32 ufd,const char __user *pathname);int bpf_obj_get_user (const char __user *pathname); +int bpf_percpu_hash_copy (struct bpf_map *map,void *key,void *value); +int bpf_percpu_array_copy (struct bpf_map *map,void *key,void *value); +int bpf_percpu_hash_update (struct bpf_map *map,void *key,void *value, +u64 flags); +int bpf_percpu_array_update (struct bpf_map *map,void *key,void *value, +u64 flags); + +/* memcpy that is used with 8-byte aligned pointers, power-of-8 size and +* forced to use 'long' read/writes to try to atomically copy long counters. +* Best-effort only. No barriers here, since it _will_ race with concurrent +* updates from BPF programs. Called from bpf syscall and mostly used with +* size 8 or 16 bytes, so ask compiler to inline it. +*/ +static inline void bpf_long_memcpy (void *dst,const void *src,u32 size) +{ +const long *lsrc = src; +long *ldst = dst; + + size /=sizeof (long ); +while (size--) + *ldst++ = *lsrc++; +} +/* verify correctness of eBPF program */ int bpf_check (struct bpf_prog **fp,union bpf_attr *attr);#else
kernel/bpf/arraymap.c +64 -0
76 lines not on this page · raw message
kernel/bpf/hashtab.c +74 -9
128 lines not on this page · raw message
kernel/bpf/syscall.c +40 -17
96 lines not on this page · raw message
Signature · 1 line
2.4.6
PATCH 4/6 samples/bpf: unit test for BPF_MAP_TYPE_PERCPU_HASH
In reply to Alexei StarovoitovFrom: Martin KaFai Lau <[email protected]>
A sanity test for BPF_MAP_TYPE_PERCPU_HASH.
--- samples/bpf/test_maps.c | 96 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+)
samples/bpf/test_maps.c +96 -0
@@ -89,6 +89,100 @@ static void test_hashmap_sanity(int i, void *data)close (map_fd); } +/* sanity tests for percpu map API */ +static void test_percpu_hashmap_sanity (int task,void *data) +{ +long long key, next_key; +int expected_key_mask =0 ; +unsigned int nr_cpus =sysconf (_SC_NPROCESSORS_CONF); +long long value[nr_cpus]; +int map_fd, i; + + map_fd =bpf_create_map (BPF_MAP_TYPE_PERCPU_HASH ,sizeof (key), +sizeof (value[0 ]),2 ); +if (map_fd <0 ) { +printf ("failed to create hashmap '%s'\n" ,strerror (errno)); +exit (1 ); + } + +for (i =0 ; i < nr_cpus; i++) + value[i] = i +100 ; + key =1 ; +/* insert key=1 element */ +assert (!(expected_key_mask & key)); +assert (bpf_update_elem (map_fd, &key, value,BPF_ANY ) ==0 ); + expected_key_mask |= key; + +/* BPF_NOEXIST means: add new element if it doesn't exist */ +assert (bpf_update_elem (map_fd, &key, value,BPF_NOEXIST ) ==-1 && +/* key=1 already exists */ + errno ==EEXIST ); + +/* -1 is an invalid flag */ +assert (bpf_update_elem (map_fd, &key, value,-1 ) ==-1 && + errno ==EINVAL ); + +/* check that key=1 can be found. value could be 0 if the lookup +* was run from a different cpu. +*/ + value[0 ] =1 ; +assert (bpf_lookup_elem (map_fd, &key, value) ==0 && value[0 ] ==100 ); + + key =2 ; +/* check that key=2 is not found */ +assert (bpf_lookup_elem (map_fd, &key, value) ==-1 && errno ==ENOENT ); + +/* BPF_EXIST means: update existing element */ +assert (bpf_update_elem (map_fd, &key, value,BPF_EXIST ) ==-1 && +/* key=2 is not there */ + errno ==ENOENT ); + +/* insert key=2 element */ +assert (!(expected_key_mask & key)); +assert (bpf_update_elem (map_fd, &key, value,BPF_NOEXIST ) ==0 ); + expected_key_mask |= key; + +/* key=1 and key=2 were inserted, check that key=0 cannot be inserted +* due to max_entries limit +*/ + key =0 ; +assert (bpf_update_elem (map_fd, &key, value,BPF_NOEXIST ) ==-1 && + errno ==E2BIG ); + +/* check that key = 0 doesn't exist */ +assert (bpf_delete_elem (map_fd, &key) ==-1 && errno ==ENOENT ); + +/* iterate over two elements */ +while (!bpf_get_next_key (map_fd, &key, &next_key)) { +assert ((expected_key_mask & next_key) == next_key); + expected_key_mask &= ~next_key; + +assert (bpf_lookup_elem (map_fd, &next_key, value) ==0 ); +for (i =0 ; i < nr_cpus; i++) +assert (value[i] == i +100 ); + + key = next_key; + } +assert (errno ==ENOENT ); + +/* Update with BPF_EXIST */ + key =1 ; +assert (bpf_update_elem (map_fd, &key, value,BPF_EXIST ) ==0 ); + +/* delete both elements */ + key =1 ; +assert (bpf_delete_elem (map_fd, &key) ==0 ); + key =2 ; +assert (bpf_delete_elem (map_fd, &key) ==0 ); +assert (bpf_delete_elem (map_fd, &key) ==-1 && errno ==ENOENT ); + + key =0 ; +/* check that map is empty */ +assert (bpf_get_next_key (map_fd, &key, &next_key) ==-1 && + errno ==ENOENT ); +close (map_fd); +} +static void test_arraymap_sanity (int i,void *data) {int key, next_key, map_fd;
@@ -209,6 +303,7 @@ static void run_parallel(int tasks, void (*fn)(int i, void *data), void *data)static void test_map_stress (void ) {run_parallel (100 , test_hashmap_sanity,NULL ); +run_parallel (100 , test_percpu_hashmap_sanity,NULL );run_parallel (100 , test_arraymap_sanity,NULL ); }
@@ -282,6 +377,7 @@ static void test_map_parallel(void)int main (void ) {test_hashmap_sanity (0 ,NULL ); +test_percpu_hashmap_sanity (0 ,NULL );test_arraymap_sanity (0 ,NULL );test_map_large ();test_map_parallel ();
Signature · 1 line
2.4.6
PATCH 6/6 samples/bpf: update tracex[23] examples to use per-cpu maps
In reply to Alexei Starovoitov--- samples/bpf/tracex2_kern.c | 2 +- samples/bpf/tracex2_user.c | 7 ++++++- samples/bpf/tracex3_kern.c | 8 ++++---- samples/bpf/tracex3_user.c | 21 ++++++++++++++------- 4 files changed, 25 insertions(+), 13 deletions(-)
samples/bpf/tracex2_kern.c +1 -1
@@ -70,7 +70,7 @@ struct hist_key { }; struct bpf_map_def SEC("maps") my_hist_map = { - .type = BPF_MAP_TYPE_HASH, + .type = BPF_MAP_TYPE_PERCPU_HASH, .key_size = sizeof(struct hist_key), .value_size = sizeof(long), .max_entries = 1024,
samples/bpf/tracex2_user.c +6 -1
@@ -37,6 +37,8 @@ struct hist_key {static void print_hist_for_pid (int fd,void *task) {struct hist_key key = {}, next_key; +unsigned int nr_cpus =sysconf (_SC_NPROCESSORS_CONF); +long values[nr_cpus];char starstr[MAX_STARS ];long value;long data[MAX_INDEX ] = {};
@@ -49,7 +51,10 @@ static void print_hist_for_pid(int fd, void *task) key = next_key;continue ; } -bpf_lookup_elem (fd, &next_key, &value); +bpf_lookup_elem (fd, &next_key, values); + value =0 ; +for (i =0 ; i < nr_cpus; i++) + value += values[i]; ind = next_key.index; data[ind] = value;if (value && ind > max_ind)
samples/bpf/tracex3_kern.c +4 -4
@@ -20,7 +20,7 @@ struct bpf_map_def SEC("maps") my_map = {/* kprobe is NOT a stable ABI. If kernel internals change this bpf+kprobe * example will no longer be meaningful */ -SEC("kprobe/blk_mq_start_request") +SEC("kprobe/blk_start_request")int bpf_prog1 (struct pt_regs *ctx) {long rq =PT_REGS_PARM1 (ctx);
@@ -42,13 +42,13 @@ static unsigned int log2l(unsigned long long n)#define SLOTS 100 struct bpf_map_def SEC("maps") lat_map = { - .type = BPF_MAP_TYPE_ARRAY, + .type = BPF_MAP_TYPE_PERCPU_ARRAY, .key_size = sizeof(u32), .value_size = sizeof(u64), .max_entries = SLOTS, }; -SEC("kprobe/blk_update_request") +SEC("kprobe/blk_account_io_completion")int bpf_prog2 (struct pt_regs *ctx) {long rq =PT_REGS_PARM1 (ctx);
@@ -81,7 +81,7 @@ int bpf_prog2(struct pt_regs *ctx) value =bpf_map_lookup_elem (&lat_map, &index);if (value) -__sync_fetch_and_add ((long *)value,1 ); + *value +=1 ;return 0 ; }
samples/bpf/tracex3_user.c +14 -7
@@ -20,11 +20,13 @@static void clear_stats (int fd) { +unsigned int nr_cpus =sysconf (_SC_NPROCESSORS_CONF); +__u64 values[nr_cpus];__u32 key; -__u64 value =0 ; +memset (values,0 ,sizeof (values));for (key =0 ; key <SLOTS ; key++) -bpf_update_elem (fd, &key, &value,BPF_ANY ); +bpf_update_elem (fd, &key, values,BPF_ANY ); }const char *color[] = {
@@ -75,15 +77,20 @@ static void print_banner(void)static void print_hist (int fd) { -__u32 key; -__u64 value; -__u64 cnt[SLOTS ]; -__u64 max_cnt =0 ; +unsigned int nr_cpus =sysconf (_SC_NPROCESSORS_CONF);__u64 total_events =0 ; +long values[nr_cpus]; +__u64 max_cnt =0 ; +__u64 cnt[SLOTS ]; +__u64 value; +__u32 key; +int i;for (key =0 ; key <SLOTS ; key++) { +bpf_lookup_elem (fd, &key, values); value =0 ; -bpf_lookup_elem (fd, &key, &value); +for (i =0 ; i < nr_cpus; i++) + value += values[i]; cnt[key] = value; total_events += value;if (value > max_cnt)
Signature · 1 line
2.4.6
PATCH 5/6 samples/bpf: unit test for BPF_MAP_TYPE_PERCPU_ARRAY
In reply to Alexei StarovoitovFrom: "[email protected]" <[email protected]>
A sanity test for BPF_MAP_TYPE_PERCPU_ARRAY
--- samples/bpf/test_maps.c | 92 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+)
samples/bpf/test_maps.c +92 -0
@@ -236,6 +236,94 @@ static void test_arraymap_sanity(int i, void *data)close (map_fd); } +static void test_percpu_arraymap_many_keys (void ) +{ +unsigned nr_cpus =sysconf (_SC_NPROCESSORS_CONF); +unsigned nr_keys =20000 ; +long values[nr_cpus]; +int key, map_fd, i; + + map_fd =bpf_create_map (BPF_MAP_TYPE_PERCPU_ARRAY ,sizeof (key), +sizeof (values[0 ]), nr_keys); +if (map_fd <0 ) { +printf ("failed to create per-cpu arraymap '%s'\n" , +strerror (errno)); +exit (1 ); + } + +for (i =0 ; i < nr_cpus; i++) + values[i] = i +10 ; + +for (key =0 ; key < nr_keys; key++) +assert (bpf_update_elem (map_fd, &key, values,BPF_ANY ) ==0 ); + +for (key =0 ; key < nr_keys; key++) { +for (i =0 ; i < nr_cpus; i++) + values[i] =0 ; +assert (bpf_lookup_elem (map_fd, &key, values) ==0 ); +for (i =0 ; i < nr_cpus; i++) +assert (values[i] == i +10 ); + } + +close (map_fd); +} + +static void test_percpu_arraymap_sanity (int i,void *data) +{ +unsigned nr_cpus =sysconf (_SC_NPROCESSORS_CONF); +long values[nr_cpus]; +int key, next_key, map_fd; + + map_fd =bpf_create_map (BPF_MAP_TYPE_PERCPU_ARRAY ,sizeof (key), +sizeof (values[0 ]),2 ); +if (map_fd <0 ) { +printf ("failed to create arraymap '%s'\n" ,strerror (errno)); +exit (1 ); + } + +for (i =0 ; i < nr_cpus; i++) + values[i] = i +100 ; + + key =1 ; +/* insert key=1 element */ +assert (bpf_update_elem (map_fd, &key, values,BPF_ANY ) ==0 ); + + values[0 ] =0 ; +assert (bpf_update_elem (map_fd, &key, values,BPF_NOEXIST ) ==-1 && + errno ==EEXIST ); + +/* check that key=1 can be found */ +assert (bpf_lookup_elem (map_fd, &key, values) ==0 && values[0 ] ==100 ); + + key =0 ; +/* check that key=0 is also found and zero initialized */ +assert (bpf_lookup_elem (map_fd, &key, values) ==0 && + values[0 ] ==0 && values[nr_cpus -1 ] ==0 ); + + +/* check that key=2 cannot be inserted due to max_entries limit */ + key =2 ; +assert (bpf_update_elem (map_fd, &key, values,BPF_EXIST ) ==-1 && + errno ==E2BIG ); + +/* check that key = 2 doesn't exist */ +assert (bpf_lookup_elem (map_fd, &key, values) ==-1 && errno ==ENOENT ); + +/* iterate over two elements */ +assert (bpf_get_next_key (map_fd, &key, &next_key) ==0 && + next_key ==0 ); +assert (bpf_get_next_key (map_fd, &next_key, &next_key) ==0 && + next_key ==1 ); +assert (bpf_get_next_key (map_fd, &next_key, &next_key) ==-1 && + errno ==ENOENT ); + +/* delete shouldn't succeed */ + key =1 ; +assert (bpf_delete_elem (map_fd, &key) ==-1 && errno ==EINVAL ); + +close (map_fd); +} +#define MAP_SIZE (32 * 1024)static void test_map_large (void ) {
@@ -305,6 +393,7 @@ static void test_map_stress(void)run_parallel (100 , test_hashmap_sanity,NULL );run_parallel (100 , test_percpu_hashmap_sanity,NULL );run_parallel (100 , test_arraymap_sanity,NULL ); +run_parallel (100 , test_percpu_arraymap_sanity,NULL ); }#define TASKS 1024
@@ -379,6 +468,9 @@ int main(void)test_hashmap_sanity (0 ,NULL );test_percpu_hashmap_sanity (0 ,NULL );test_arraymap_sanity (0 ,NULL ); +test_percpu_arraymap_sanity (0 ,NULL ); +test_percpu_arraymap_many_keys (); +test_map_large ();test_map_parallel ();test_map_stress ();
Signature · 1 line
2.4.6
David Miller
maintainerFrom: Alexei Starovoitov <[email protected]>
Date: Mon, 1 Feb 2016 22:39:52 -0800
Quoted 14 lines
We've started to use bpf to trace every packet and atomic add instruction (event JITed) started to show up in perf profile. The solution is to do per-cpu counters.
ForPERCPU_(HASH|ARRAY)map the existingbpf_map_lookup()helper returns per-cpu area which bpf programs can use to store and increment the counters. TheBPF_MAP_LOOKUP_ELEMsyscall command returns areas from all cpus and user process aggregates the counters. The usage example is in patch 6. The api turned out to be very easy to use from bpf program and from user space.
Long term we were discussing to add 'bounded loop' instruction, so bpf programs can do aggregation within the program which may help some use cases. Right now user space aggregation of per-cpu counters fits the best.
Quoted 4 lines
This patch set is new approach for per-cpu hash and array maps. I've reused the map tests written by Martin and Ming, but implementation and api is new. Old discussion here:
http://thread.gmane.org/gmane.linux.kernel/2123800/focus=2126435
Series applied, thanks Alexei.