1111
1212#define  NR_VCPU  4
1313
14+ #define  ITERAT_ALL 
15+ 
1416int  main (int  argc , char  * argv [])
1517{
1618	struct  bpf_link  * link  =  NULL ;
1719	struct  bpf_program  * prog ;
1820	struct  bpf_object  * obj ;
1921	char  filename [256 ];
20- 	int  i , fd ;
21- 	int  cur , sum  =  0 , delta  =  0 ;
22+ 	int  fd ;
23+ 	int  cur ;
24+ #ifdef  ITERAT_ALL 
25+ 	int  next_key , lookup_key ;
26+ #else 
2227	/* 
2328	 * pstree can print out each vcpu thread id 
2429	 * pstree -t -p `vminfo -n demo-3 -p` 
@@ -29,6 +34,9 @@ int main(int argc, char *argv[])
2934	 */ 
3035	int  pids [NR_VCPU ] =  {3345 , 3355 , 3366 , 3373 };
3136	int  prev [NR_VCPU ] =  {0 , 0 , 0 , 0 };
37+ 	int  sum  =  0 , delta  =  0 ;
38+ 	int  i ;
39+ #endif 
3240
3341	snprintf (filename , sizeof (filename ), "%s_kern.o" , argv [0 ]);
3442	obj  =  bpf_object__open_file (filename , NULL );
@@ -56,21 +64,36 @@ int main(int argc, char *argv[])
5664		goto cleanup ;
5765	}
5866
67+ 	/* 
68+ 	 * iterating over elements in a BPF Map 
69+ 	 * 
70+ 	 * use `bpf_map_get_next_key` with a lookup key that doesn't exist in the map 
71+ 	 * This forces BPF to start from the beginning of the map 
72+ 	 */ 
5973#if  1 
6074	fd  =  bpf_object__find_map_fd_by_name (obj , "my_map" );
6175	while  (1 )
6276	{
77+ #ifdef  ITERAT_ALL 
78+ 		lookup_key  =  -1 ; /* key not exsit in map */ 
79+ 		while  (bpf_map_get_next_key (fd , & lookup_key , & next_key ) ==  0 )
80+ 		{
81+ 			bpf_map_lookup_elem (fd , & lookup_key , & cur );
82+ 			lookup_key  =  next_key ;
83+ 			printf ("%d:%d\n" , lookup_key , cur );
84+ 		}
85+ #else 
6386		for  (i  =  0 ; i  <  NR_VCPU ; i ++ )
6487		{
6588			bpf_map_lookup_elem (fd , & pids [i ], & cur );
6689			delta  =  cur  -  prev [i ];
6790			sum  +=  delta ;
6891			prev [i ] =  cur ;
6992		}
70- 
71- 		sleep (1 );
7293		printf ("vmexit total: %d\n" , sum );
7394		sum  =  0 ;
95+ #endif 
96+ 		sleep (1 );
7497	}
7598#else 
7699	read_trace_pipe ();
0 commit comments