xref: /openbmc/linux/tools/bpf/bpftool/map.c (revision 0c7beb2d)
1 // SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)
2 /* Copyright (C) 2017-2018 Netronome Systems, Inc. */
3 
4 #include <assert.h>
5 #include <errno.h>
6 #include <fcntl.h>
7 #include <linux/err.h>
8 #include <linux/kernel.h>
9 #include <net/if.h>
10 #include <stdbool.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include <sys/types.h>
16 #include <sys/stat.h>
17 
18 #include <bpf.h>
19 
20 #include "btf.h"
21 #include "json_writer.h"
22 #include "main.h"
23 
24 const char * const map_type_name[] = {
25 	[BPF_MAP_TYPE_UNSPEC]			= "unspec",
26 	[BPF_MAP_TYPE_HASH]			= "hash",
27 	[BPF_MAP_TYPE_ARRAY]			= "array",
28 	[BPF_MAP_TYPE_PROG_ARRAY]		= "prog_array",
29 	[BPF_MAP_TYPE_PERF_EVENT_ARRAY]		= "perf_event_array",
30 	[BPF_MAP_TYPE_PERCPU_HASH]		= "percpu_hash",
31 	[BPF_MAP_TYPE_PERCPU_ARRAY]		= "percpu_array",
32 	[BPF_MAP_TYPE_STACK_TRACE]		= "stack_trace",
33 	[BPF_MAP_TYPE_CGROUP_ARRAY]		= "cgroup_array",
34 	[BPF_MAP_TYPE_LRU_HASH]			= "lru_hash",
35 	[BPF_MAP_TYPE_LRU_PERCPU_HASH]		= "lru_percpu_hash",
36 	[BPF_MAP_TYPE_LPM_TRIE]			= "lpm_trie",
37 	[BPF_MAP_TYPE_ARRAY_OF_MAPS]		= "array_of_maps",
38 	[BPF_MAP_TYPE_HASH_OF_MAPS]		= "hash_of_maps",
39 	[BPF_MAP_TYPE_DEVMAP]			= "devmap",
40 	[BPF_MAP_TYPE_SOCKMAP]			= "sockmap",
41 	[BPF_MAP_TYPE_CPUMAP]			= "cpumap",
42 	[BPF_MAP_TYPE_XSKMAP]			= "xskmap",
43 	[BPF_MAP_TYPE_SOCKHASH]			= "sockhash",
44 	[BPF_MAP_TYPE_CGROUP_STORAGE]		= "cgroup_storage",
45 	[BPF_MAP_TYPE_REUSEPORT_SOCKARRAY]	= "reuseport_sockarray",
46 	[BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE]	= "percpu_cgroup_storage",
47 	[BPF_MAP_TYPE_QUEUE]			= "queue",
48 	[BPF_MAP_TYPE_STACK]			= "stack",
49 };
50 
51 const size_t map_type_name_size = ARRAY_SIZE(map_type_name);
52 
53 static bool map_is_per_cpu(__u32 type)
54 {
55 	return type == BPF_MAP_TYPE_PERCPU_HASH ||
56 	       type == BPF_MAP_TYPE_PERCPU_ARRAY ||
57 	       type == BPF_MAP_TYPE_LRU_PERCPU_HASH ||
58 	       type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE;
59 }
60 
61 static bool map_is_map_of_maps(__u32 type)
62 {
63 	return type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
64 	       type == BPF_MAP_TYPE_HASH_OF_MAPS;
65 }
66 
67 static bool map_is_map_of_progs(__u32 type)
68 {
69 	return type == BPF_MAP_TYPE_PROG_ARRAY;
70 }
71 
72 static int map_type_from_str(const char *type)
73 {
74 	unsigned int i;
75 
76 	for (i = 0; i < ARRAY_SIZE(map_type_name); i++)
77 		/* Don't allow prefixing in case of possible future shadowing */
78 		if (map_type_name[i] && !strcmp(map_type_name[i], type))
79 			return i;
80 	return -1;
81 }
82 
83 static void *alloc_value(struct bpf_map_info *info)
84 {
85 	if (map_is_per_cpu(info->type))
86 		return malloc(round_up(info->value_size, 8) *
87 			      get_possible_cpus());
88 	else
89 		return malloc(info->value_size);
90 }
91 
92 int map_parse_fd(int *argc, char ***argv)
93 {
94 	int fd;
95 
96 	if (is_prefix(**argv, "id")) {
97 		unsigned int id;
98 		char *endptr;
99 
100 		NEXT_ARGP();
101 
102 		id = strtoul(**argv, &endptr, 0);
103 		if (*endptr) {
104 			p_err("can't parse %s as ID", **argv);
105 			return -1;
106 		}
107 		NEXT_ARGP();
108 
109 		fd = bpf_map_get_fd_by_id(id);
110 		if (fd < 0)
111 			p_err("get map by id (%u): %s", id, strerror(errno));
112 		return fd;
113 	} else if (is_prefix(**argv, "pinned")) {
114 		char *path;
115 
116 		NEXT_ARGP();
117 
118 		path = **argv;
119 		NEXT_ARGP();
120 
121 		return open_obj_pinned_any(path, BPF_OBJ_MAP);
122 	}
123 
124 	p_err("expected 'id' or 'pinned', got: '%s'?", **argv);
125 	return -1;
126 }
127 
128 int map_parse_fd_and_info(int *argc, char ***argv, void *info, __u32 *info_len)
129 {
130 	int err;
131 	int fd;
132 
133 	fd = map_parse_fd(argc, argv);
134 	if (fd < 0)
135 		return -1;
136 
137 	err = bpf_obj_get_info_by_fd(fd, info, info_len);
138 	if (err) {
139 		p_err("can't get map info: %s", strerror(errno));
140 		close(fd);
141 		return err;
142 	}
143 
144 	return fd;
145 }
146 
147 static int do_dump_btf(const struct btf_dumper *d,
148 		       struct bpf_map_info *map_info, void *key,
149 		       void *value)
150 {
151 	int ret;
152 
153 	/* start of key-value pair */
154 	jsonw_start_object(d->jw);
155 
156 	if (map_info->btf_key_type_id) {
157 		jsonw_name(d->jw, "key");
158 
159 		ret = btf_dumper_type(d, map_info->btf_key_type_id, key);
160 		if (ret)
161 			goto err_end_obj;
162 	}
163 
164 	if (!map_is_per_cpu(map_info->type)) {
165 		jsonw_name(d->jw, "value");
166 		ret = btf_dumper_type(d, map_info->btf_value_type_id, value);
167 	} else {
168 		unsigned int i, n, step;
169 
170 		jsonw_name(d->jw, "values");
171 		jsonw_start_array(d->jw);
172 		n = get_possible_cpus();
173 		step = round_up(map_info->value_size, 8);
174 		for (i = 0; i < n; i++) {
175 			jsonw_start_object(d->jw);
176 			jsonw_int_field(d->jw, "cpu", i);
177 			jsonw_name(d->jw, "value");
178 			ret = btf_dumper_type(d, map_info->btf_value_type_id,
179 					      value + i * step);
180 			jsonw_end_object(d->jw);
181 			if (ret)
182 				break;
183 		}
184 		jsonw_end_array(d->jw);
185 	}
186 
187 err_end_obj:
188 	/* end of key-value pair */
189 	jsonw_end_object(d->jw);
190 
191 	return ret;
192 }
193 
194 static json_writer_t *get_btf_writer(void)
195 {
196 	json_writer_t *jw = jsonw_new(stdout);
197 
198 	if (!jw)
199 		return NULL;
200 	jsonw_pretty(jw, true);
201 
202 	return jw;
203 }
204 
205 static void print_entry_json(struct bpf_map_info *info, unsigned char *key,
206 			     unsigned char *value, struct btf *btf)
207 {
208 	jsonw_start_object(json_wtr);
209 
210 	if (!map_is_per_cpu(info->type)) {
211 		jsonw_name(json_wtr, "key");
212 		print_hex_data_json(key, info->key_size);
213 		jsonw_name(json_wtr, "value");
214 		print_hex_data_json(value, info->value_size);
215 		if (btf) {
216 			struct btf_dumper d = {
217 				.btf = btf,
218 				.jw = json_wtr,
219 				.is_plain_text = false,
220 			};
221 
222 			jsonw_name(json_wtr, "formatted");
223 			do_dump_btf(&d, info, key, value);
224 		}
225 	} else {
226 		unsigned int i, n, step;
227 
228 		n = get_possible_cpus();
229 		step = round_up(info->value_size, 8);
230 
231 		jsonw_name(json_wtr, "key");
232 		print_hex_data_json(key, info->key_size);
233 
234 		jsonw_name(json_wtr, "values");
235 		jsonw_start_array(json_wtr);
236 		for (i = 0; i < n; i++) {
237 			jsonw_start_object(json_wtr);
238 
239 			jsonw_int_field(json_wtr, "cpu", i);
240 
241 			jsonw_name(json_wtr, "value");
242 			print_hex_data_json(value + i * step,
243 					    info->value_size);
244 
245 			jsonw_end_object(json_wtr);
246 		}
247 		jsonw_end_array(json_wtr);
248 		if (btf) {
249 			struct btf_dumper d = {
250 				.btf = btf,
251 				.jw = json_wtr,
252 				.is_plain_text = false,
253 			};
254 
255 			jsonw_name(json_wtr, "formatted");
256 			do_dump_btf(&d, info, key, value);
257 		}
258 	}
259 
260 	jsonw_end_object(json_wtr);
261 }
262 
263 static void print_entry_error(struct bpf_map_info *info, unsigned char *key,
264 			      const char *value)
265 {
266 	int value_size = strlen(value);
267 	bool single_line, break_names;
268 
269 	break_names = info->key_size > 16 || value_size > 16;
270 	single_line = info->key_size + value_size <= 24 && !break_names;
271 
272 	printf("key:%c", break_names ? '\n' : ' ');
273 	fprint_hex(stdout, key, info->key_size, " ");
274 
275 	printf(single_line ? "  " : "\n");
276 
277 	printf("value:%c%s", break_names ? '\n' : ' ', value);
278 
279 	printf("\n");
280 }
281 
282 static void print_entry_plain(struct bpf_map_info *info, unsigned char *key,
283 			      unsigned char *value)
284 {
285 	if (!map_is_per_cpu(info->type)) {
286 		bool single_line, break_names;
287 
288 		break_names = info->key_size > 16 || info->value_size > 16;
289 		single_line = info->key_size + info->value_size <= 24 &&
290 			!break_names;
291 
292 		if (info->key_size) {
293 			printf("key:%c", break_names ? '\n' : ' ');
294 			fprint_hex(stdout, key, info->key_size, " ");
295 
296 			printf(single_line ? "  " : "\n");
297 		}
298 
299 		if (info->value_size) {
300 			printf("value:%c", break_names ? '\n' : ' ');
301 			if (value)
302 				fprint_hex(stdout, value, info->value_size,
303 					   " ");
304 			else
305 				printf("<no entry>");
306 		}
307 
308 		printf("\n");
309 	} else {
310 		unsigned int i, n, step;
311 
312 		n = get_possible_cpus();
313 		step = round_up(info->value_size, 8);
314 
315 		if (info->key_size) {
316 			printf("key:\n");
317 			fprint_hex(stdout, key, info->key_size, " ");
318 			printf("\n");
319 		}
320 		if (info->value_size) {
321 			for (i = 0; i < n; i++) {
322 				printf("value (CPU %02d):%c",
323 				       i, info->value_size > 16 ? '\n' : ' ');
324 				if (value)
325 					fprint_hex(stdout, value + i * step,
326 						   info->value_size, " ");
327 				else
328 					printf("<no entry>");
329 				printf("\n");
330 			}
331 		}
332 	}
333 }
334 
335 static char **parse_bytes(char **argv, const char *name, unsigned char *val,
336 			  unsigned int n)
337 {
338 	unsigned int i = 0, base = 0;
339 	char *endptr;
340 
341 	if (is_prefix(*argv, "hex")) {
342 		base = 16;
343 		argv++;
344 	}
345 
346 	while (i < n && argv[i]) {
347 		val[i] = strtoul(argv[i], &endptr, base);
348 		if (*endptr) {
349 			p_err("error parsing byte: %s", argv[i]);
350 			return NULL;
351 		}
352 		i++;
353 	}
354 
355 	if (i != n) {
356 		p_err("%s expected %d bytes got %d", name, n, i);
357 		return NULL;
358 	}
359 
360 	return argv + i;
361 }
362 
363 /* on per cpu maps we must copy the provided value on all value instances */
364 static void fill_per_cpu_value(struct bpf_map_info *info, void *value)
365 {
366 	unsigned int i, n, step;
367 
368 	if (!map_is_per_cpu(info->type))
369 		return;
370 
371 	n = get_possible_cpus();
372 	step = round_up(info->value_size, 8);
373 	for (i = 1; i < n; i++)
374 		memcpy(value + i * step, value, info->value_size);
375 }
376 
377 static int parse_elem(char **argv, struct bpf_map_info *info,
378 		      void *key, void *value, __u32 key_size, __u32 value_size,
379 		      __u32 *flags, __u32 **value_fd)
380 {
381 	if (!*argv) {
382 		if (!key && !value)
383 			return 0;
384 		p_err("did not find %s", key ? "key" : "value");
385 		return -1;
386 	}
387 
388 	if (is_prefix(*argv, "key")) {
389 		if (!key) {
390 			if (key_size)
391 				p_err("duplicate key");
392 			else
393 				p_err("unnecessary key");
394 			return -1;
395 		}
396 
397 		argv = parse_bytes(argv + 1, "key", key, key_size);
398 		if (!argv)
399 			return -1;
400 
401 		return parse_elem(argv, info, NULL, value, key_size, value_size,
402 				  flags, value_fd);
403 	} else if (is_prefix(*argv, "value")) {
404 		int fd;
405 
406 		if (!value) {
407 			if (value_size)
408 				p_err("duplicate value");
409 			else
410 				p_err("unnecessary value");
411 			return -1;
412 		}
413 
414 		argv++;
415 
416 		if (map_is_map_of_maps(info->type)) {
417 			int argc = 2;
418 
419 			if (value_size != 4) {
420 				p_err("value smaller than 4B for map in map?");
421 				return -1;
422 			}
423 			if (!argv[0] || !argv[1]) {
424 				p_err("not enough value arguments for map in map");
425 				return -1;
426 			}
427 
428 			fd = map_parse_fd(&argc, &argv);
429 			if (fd < 0)
430 				return -1;
431 
432 			*value_fd = value;
433 			**value_fd = fd;
434 		} else if (map_is_map_of_progs(info->type)) {
435 			int argc = 2;
436 
437 			if (value_size != 4) {
438 				p_err("value smaller than 4B for map of progs?");
439 				return -1;
440 			}
441 			if (!argv[0] || !argv[1]) {
442 				p_err("not enough value arguments for map of progs");
443 				return -1;
444 			}
445 			if (is_prefix(*argv, "id"))
446 				p_info("Warning: updating program array via MAP_ID, make sure this map is kept open\n"
447 				       "         by some process or pinned otherwise update will be lost");
448 
449 			fd = prog_parse_fd(&argc, &argv);
450 			if (fd < 0)
451 				return -1;
452 
453 			*value_fd = value;
454 			**value_fd = fd;
455 		} else {
456 			argv = parse_bytes(argv, "value", value, value_size);
457 			if (!argv)
458 				return -1;
459 
460 			fill_per_cpu_value(info, value);
461 		}
462 
463 		return parse_elem(argv, info, key, NULL, key_size, value_size,
464 				  flags, NULL);
465 	} else if (is_prefix(*argv, "any") || is_prefix(*argv, "noexist") ||
466 		   is_prefix(*argv, "exist")) {
467 		if (!flags) {
468 			p_err("flags specified multiple times: %s", *argv);
469 			return -1;
470 		}
471 
472 		if (is_prefix(*argv, "any"))
473 			*flags = BPF_ANY;
474 		else if (is_prefix(*argv, "noexist"))
475 			*flags = BPF_NOEXIST;
476 		else if (is_prefix(*argv, "exist"))
477 			*flags = BPF_EXIST;
478 
479 		return parse_elem(argv + 1, info, key, value, key_size,
480 				  value_size, NULL, value_fd);
481 	}
482 
483 	p_err("expected key or value, got: %s", *argv);
484 	return -1;
485 }
486 
487 static int show_map_close_json(int fd, struct bpf_map_info *info)
488 {
489 	char *memlock;
490 
491 	memlock = get_fdinfo(fd, "memlock");
492 
493 	jsonw_start_object(json_wtr);
494 
495 	jsonw_uint_field(json_wtr, "id", info->id);
496 	if (info->type < ARRAY_SIZE(map_type_name))
497 		jsonw_string_field(json_wtr, "type",
498 				   map_type_name[info->type]);
499 	else
500 		jsonw_uint_field(json_wtr, "type", info->type);
501 
502 	if (*info->name)
503 		jsonw_string_field(json_wtr, "name", info->name);
504 
505 	jsonw_name(json_wtr, "flags");
506 	jsonw_printf(json_wtr, "%d", info->map_flags);
507 
508 	print_dev_json(info->ifindex, info->netns_dev, info->netns_ino);
509 
510 	jsonw_uint_field(json_wtr, "bytes_key", info->key_size);
511 	jsonw_uint_field(json_wtr, "bytes_value", info->value_size);
512 	jsonw_uint_field(json_wtr, "max_entries", info->max_entries);
513 
514 	if (memlock)
515 		jsonw_int_field(json_wtr, "bytes_memlock", atoi(memlock));
516 	free(memlock);
517 
518 	if (info->type == BPF_MAP_TYPE_PROG_ARRAY) {
519 		char *owner_prog_type = get_fdinfo(fd, "owner_prog_type");
520 		char *owner_jited = get_fdinfo(fd, "owner_jited");
521 
522 		if (owner_prog_type) {
523 			unsigned int prog_type = atoi(owner_prog_type);
524 
525 			if (prog_type < ARRAY_SIZE(prog_type_name))
526 				jsonw_string_field(json_wtr, "owner_prog_type",
527 						   prog_type_name[prog_type]);
528 			else
529 				jsonw_uint_field(json_wtr, "owner_prog_type",
530 						 prog_type);
531 		}
532 		if (owner_jited)
533 			jsonw_bool_field(json_wtr, "owner_jited",
534 					 !!atoi(owner_jited));
535 
536 		free(owner_prog_type);
537 		free(owner_jited);
538 	}
539 	close(fd);
540 
541 	if (!hash_empty(map_table.table)) {
542 		struct pinned_obj *obj;
543 
544 		jsonw_name(json_wtr, "pinned");
545 		jsonw_start_array(json_wtr);
546 		hash_for_each_possible(map_table.table, obj, hash, info->id) {
547 			if (obj->id == info->id)
548 				jsonw_string(json_wtr, obj->path);
549 		}
550 		jsonw_end_array(json_wtr);
551 	}
552 
553 	jsonw_end_object(json_wtr);
554 
555 	return 0;
556 }
557 
558 static int show_map_close_plain(int fd, struct bpf_map_info *info)
559 {
560 	char *memlock;
561 
562 	memlock = get_fdinfo(fd, "memlock");
563 
564 	printf("%u: ", info->id);
565 	if (info->type < ARRAY_SIZE(map_type_name))
566 		printf("%s  ", map_type_name[info->type]);
567 	else
568 		printf("type %u  ", info->type);
569 
570 	if (*info->name)
571 		printf("name %s  ", info->name);
572 
573 	printf("flags 0x%x", info->map_flags);
574 	print_dev_plain(info->ifindex, info->netns_dev, info->netns_ino);
575 	printf("\n");
576 	printf("\tkey %uB  value %uB  max_entries %u",
577 	       info->key_size, info->value_size, info->max_entries);
578 
579 	if (memlock)
580 		printf("  memlock %sB", memlock);
581 	free(memlock);
582 
583 	if (info->type == BPF_MAP_TYPE_PROG_ARRAY) {
584 		char *owner_prog_type = get_fdinfo(fd, "owner_prog_type");
585 		char *owner_jited = get_fdinfo(fd, "owner_jited");
586 
587 		if (owner_prog_type || owner_jited)
588 			printf("\n\t");
589 		if (owner_prog_type) {
590 			unsigned int prog_type = atoi(owner_prog_type);
591 
592 			if (prog_type < ARRAY_SIZE(prog_type_name))
593 				printf("owner_prog_type %s  ",
594 				       prog_type_name[prog_type]);
595 			else
596 				printf("owner_prog_type %d  ", prog_type);
597 		}
598 		if (owner_jited)
599 			printf("owner%s jited",
600 			       atoi(owner_jited) ? "" : " not");
601 
602 		free(owner_prog_type);
603 		free(owner_jited);
604 	}
605 	close(fd);
606 
607 	printf("\n");
608 	if (!hash_empty(map_table.table)) {
609 		struct pinned_obj *obj;
610 
611 		hash_for_each_possible(map_table.table, obj, hash, info->id) {
612 			if (obj->id == info->id)
613 				printf("\tpinned %s\n", obj->path);
614 		}
615 	}
616 	return 0;
617 }
618 
619 static int do_show(int argc, char **argv)
620 {
621 	struct bpf_map_info info = {};
622 	__u32 len = sizeof(info);
623 	__u32 id = 0;
624 	int err;
625 	int fd;
626 
627 	if (show_pinned)
628 		build_pinned_obj_table(&map_table, BPF_OBJ_MAP);
629 
630 	if (argc == 2) {
631 		fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
632 		if (fd < 0)
633 			return -1;
634 
635 		if (json_output)
636 			return show_map_close_json(fd, &info);
637 		else
638 			return show_map_close_plain(fd, &info);
639 	}
640 
641 	if (argc)
642 		return BAD_ARG();
643 
644 	if (json_output)
645 		jsonw_start_array(json_wtr);
646 	while (true) {
647 		err = bpf_map_get_next_id(id, &id);
648 		if (err) {
649 			if (errno == ENOENT)
650 				break;
651 			p_err("can't get next map: %s%s", strerror(errno),
652 			      errno == EINVAL ? " -- kernel too old?" : "");
653 			break;
654 		}
655 
656 		fd = bpf_map_get_fd_by_id(id);
657 		if (fd < 0) {
658 			if (errno == ENOENT)
659 				continue;
660 			p_err("can't get map by id (%u): %s",
661 			      id, strerror(errno));
662 			break;
663 		}
664 
665 		err = bpf_obj_get_info_by_fd(fd, &info, &len);
666 		if (err) {
667 			p_err("can't get map info: %s", strerror(errno));
668 			close(fd);
669 			break;
670 		}
671 
672 		if (json_output)
673 			show_map_close_json(fd, &info);
674 		else
675 			show_map_close_plain(fd, &info);
676 	}
677 	if (json_output)
678 		jsonw_end_array(json_wtr);
679 
680 	return errno == ENOENT ? 0 : -1;
681 }
682 
683 static int dump_map_elem(int fd, void *key, void *value,
684 			 struct bpf_map_info *map_info, struct btf *btf,
685 			 json_writer_t *btf_wtr)
686 {
687 	int num_elems = 0;
688 	int lookup_errno;
689 
690 	if (!bpf_map_lookup_elem(fd, key, value)) {
691 		if (json_output) {
692 			print_entry_json(map_info, key, value, btf);
693 		} else {
694 			if (btf) {
695 				struct btf_dumper d = {
696 					.btf = btf,
697 					.jw = btf_wtr,
698 					.is_plain_text = true,
699 				};
700 
701 				do_dump_btf(&d, map_info, key, value);
702 			} else {
703 				print_entry_plain(map_info, key, value);
704 			}
705 			num_elems++;
706 		}
707 		return num_elems;
708 	}
709 
710 	/* lookup error handling */
711 	lookup_errno = errno;
712 
713 	if (map_is_map_of_maps(map_info->type) ||
714 	    map_is_map_of_progs(map_info->type))
715 		return 0;
716 
717 	if (json_output) {
718 		jsonw_name(json_wtr, "key");
719 		print_hex_data_json(key, map_info->key_size);
720 		jsonw_name(json_wtr, "value");
721 		jsonw_start_object(json_wtr);
722 		jsonw_string_field(json_wtr, "error", strerror(lookup_errno));
723 		jsonw_end_object(json_wtr);
724 	} else {
725 		if (errno == ENOENT)
726 			print_entry_plain(map_info, key, NULL);
727 		else
728 			print_entry_error(map_info, key,
729 					  strerror(lookup_errno));
730 	}
731 
732 	return 0;
733 }
734 
735 static int do_dump(int argc, char **argv)
736 {
737 	struct bpf_map_info info = {};
738 	void *key, *value, *prev_key;
739 	unsigned int num_elems = 0;
740 	__u32 len = sizeof(info);
741 	json_writer_t *btf_wtr;
742 	struct btf *btf = NULL;
743 	int err;
744 	int fd;
745 
746 	if (argc != 2)
747 		usage();
748 
749 	fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
750 	if (fd < 0)
751 		return -1;
752 
753 	key = malloc(info.key_size);
754 	value = alloc_value(&info);
755 	if (!key || !value) {
756 		p_err("mem alloc failed");
757 		err = -1;
758 		goto exit_free;
759 	}
760 
761 	prev_key = NULL;
762 
763 	err = btf__get_from_id(info.btf_id, &btf);
764 	if (err) {
765 		p_err("failed to get btf");
766 		goto exit_free;
767 	}
768 
769 	if (json_output)
770 		jsonw_start_array(json_wtr);
771 	else
772 		if (btf) {
773 			btf_wtr = get_btf_writer();
774 			if (!btf_wtr) {
775 				p_info("failed to create json writer for btf. falling back to plain output");
776 				btf__free(btf);
777 				btf = NULL;
778 			} else {
779 				jsonw_start_array(btf_wtr);
780 			}
781 		}
782 
783 	while (true) {
784 		err = bpf_map_get_next_key(fd, prev_key, key);
785 		if (err) {
786 			if (errno == ENOENT)
787 				err = 0;
788 			break;
789 		}
790 		num_elems += dump_map_elem(fd, key, value, &info, btf, btf_wtr);
791 		prev_key = key;
792 	}
793 
794 	if (json_output)
795 		jsonw_end_array(json_wtr);
796 	else if (btf) {
797 		jsonw_end_array(btf_wtr);
798 		jsonw_destroy(&btf_wtr);
799 	} else {
800 		printf("Found %u element%s\n", num_elems,
801 		       num_elems != 1 ? "s" : "");
802 	}
803 
804 exit_free:
805 	free(key);
806 	free(value);
807 	close(fd);
808 	btf__free(btf);
809 
810 	return err;
811 }
812 
813 static int alloc_key_value(struct bpf_map_info *info, void **key, void **value)
814 {
815 	*key = NULL;
816 	*value = NULL;
817 
818 	if (info->key_size) {
819 		*key = malloc(info->key_size);
820 		if (!*key) {
821 			p_err("key mem alloc failed");
822 			return -1;
823 		}
824 	}
825 
826 	if (info->value_size) {
827 		*value = alloc_value(info);
828 		if (!*value) {
829 			p_err("value mem alloc failed");
830 			free(*key);
831 			*key = NULL;
832 			return -1;
833 		}
834 	}
835 
836 	return 0;
837 }
838 
839 static int do_update(int argc, char **argv)
840 {
841 	struct bpf_map_info info = {};
842 	__u32 len = sizeof(info);
843 	__u32 *value_fd = NULL;
844 	__u32 flags = BPF_ANY;
845 	void *key, *value;
846 	int fd, err;
847 
848 	if (argc < 2)
849 		usage();
850 
851 	fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
852 	if (fd < 0)
853 		return -1;
854 
855 	err = alloc_key_value(&info, &key, &value);
856 	if (err)
857 		goto exit_free;
858 
859 	err = parse_elem(argv, &info, key, value, info.key_size,
860 			 info.value_size, &flags, &value_fd);
861 	if (err)
862 		goto exit_free;
863 
864 	err = bpf_map_update_elem(fd, key, value, flags);
865 	if (err) {
866 		p_err("update failed: %s", strerror(errno));
867 		goto exit_free;
868 	}
869 
870 exit_free:
871 	if (value_fd)
872 		close(*value_fd);
873 	free(key);
874 	free(value);
875 	close(fd);
876 
877 	if (!err && json_output)
878 		jsonw_null(json_wtr);
879 	return err;
880 }
881 
882 static void print_key_value(struct bpf_map_info *info, void *key,
883 			    void *value)
884 {
885 	json_writer_t *btf_wtr;
886 	struct btf *btf = NULL;
887 	int err;
888 
889 	err = btf__get_from_id(info->btf_id, &btf);
890 	if (err) {
891 		p_err("failed to get btf");
892 		return;
893 	}
894 
895 	if (json_output) {
896 		print_entry_json(info, key, value, btf);
897 	} else if (btf) {
898 		/* if here json_wtr wouldn't have been initialised,
899 		 * so let's create separate writer for btf
900 		 */
901 		btf_wtr = get_btf_writer();
902 		if (!btf_wtr) {
903 			p_info("failed to create json writer for btf. falling back to plain output");
904 			btf__free(btf);
905 			btf = NULL;
906 			print_entry_plain(info, key, value);
907 		} else {
908 			struct btf_dumper d = {
909 				.btf = btf,
910 				.jw = btf_wtr,
911 				.is_plain_text = true,
912 			};
913 
914 			do_dump_btf(&d, info, key, value);
915 			jsonw_destroy(&btf_wtr);
916 		}
917 	} else {
918 		print_entry_plain(info, key, value);
919 	}
920 	btf__free(btf);
921 }
922 
923 static int do_lookup(int argc, char **argv)
924 {
925 	struct bpf_map_info info = {};
926 	__u32 len = sizeof(info);
927 	void *key, *value;
928 	int err;
929 	int fd;
930 
931 	if (argc < 2)
932 		usage();
933 
934 	fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
935 	if (fd < 0)
936 		return -1;
937 
938 	err = alloc_key_value(&info, &key, &value);
939 	if (err)
940 		goto exit_free;
941 
942 	err = parse_elem(argv, &info, key, NULL, info.key_size, 0, NULL, NULL);
943 	if (err)
944 		goto exit_free;
945 
946 	err = bpf_map_lookup_elem(fd, key, value);
947 	if (err) {
948 		if (errno == ENOENT) {
949 			if (json_output) {
950 				jsonw_null(json_wtr);
951 			} else {
952 				printf("key:\n");
953 				fprint_hex(stdout, key, info.key_size, " ");
954 				printf("\n\nNot found\n");
955 			}
956 		} else {
957 			p_err("lookup failed: %s", strerror(errno));
958 		}
959 
960 		goto exit_free;
961 	}
962 
963 	/* here means bpf_map_lookup_elem() succeeded */
964 	print_key_value(&info, key, value);
965 
966 exit_free:
967 	free(key);
968 	free(value);
969 	close(fd);
970 
971 	return err;
972 }
973 
974 static int do_getnext(int argc, char **argv)
975 {
976 	struct bpf_map_info info = {};
977 	__u32 len = sizeof(info);
978 	void *key, *nextkey;
979 	int err;
980 	int fd;
981 
982 	if (argc < 2)
983 		usage();
984 
985 	fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
986 	if (fd < 0)
987 		return -1;
988 
989 	key = malloc(info.key_size);
990 	nextkey = malloc(info.key_size);
991 	if (!key || !nextkey) {
992 		p_err("mem alloc failed");
993 		err = -1;
994 		goto exit_free;
995 	}
996 
997 	if (argc) {
998 		err = parse_elem(argv, &info, key, NULL, info.key_size, 0,
999 				 NULL, NULL);
1000 		if (err)
1001 			goto exit_free;
1002 	} else {
1003 		free(key);
1004 		key = NULL;
1005 	}
1006 
1007 	err = bpf_map_get_next_key(fd, key, nextkey);
1008 	if (err) {
1009 		p_err("can't get next key: %s", strerror(errno));
1010 		goto exit_free;
1011 	}
1012 
1013 	if (json_output) {
1014 		jsonw_start_object(json_wtr);
1015 		if (key) {
1016 			jsonw_name(json_wtr, "key");
1017 			print_hex_data_json(key, info.key_size);
1018 		} else {
1019 			jsonw_null_field(json_wtr, "key");
1020 		}
1021 		jsonw_name(json_wtr, "next_key");
1022 		print_hex_data_json(nextkey, info.key_size);
1023 		jsonw_end_object(json_wtr);
1024 	} else {
1025 		if (key) {
1026 			printf("key:\n");
1027 			fprint_hex(stdout, key, info.key_size, " ");
1028 			printf("\n");
1029 		} else {
1030 			printf("key: None\n");
1031 		}
1032 		printf("next key:\n");
1033 		fprint_hex(stdout, nextkey, info.key_size, " ");
1034 		printf("\n");
1035 	}
1036 
1037 exit_free:
1038 	free(nextkey);
1039 	free(key);
1040 	close(fd);
1041 
1042 	return err;
1043 }
1044 
1045 static int do_delete(int argc, char **argv)
1046 {
1047 	struct bpf_map_info info = {};
1048 	__u32 len = sizeof(info);
1049 	void *key;
1050 	int err;
1051 	int fd;
1052 
1053 	if (argc < 2)
1054 		usage();
1055 
1056 	fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
1057 	if (fd < 0)
1058 		return -1;
1059 
1060 	key = malloc(info.key_size);
1061 	if (!key) {
1062 		p_err("mem alloc failed");
1063 		err = -1;
1064 		goto exit_free;
1065 	}
1066 
1067 	err = parse_elem(argv, &info, key, NULL, info.key_size, 0, NULL, NULL);
1068 	if (err)
1069 		goto exit_free;
1070 
1071 	err = bpf_map_delete_elem(fd, key);
1072 	if (err)
1073 		p_err("delete failed: %s", strerror(errno));
1074 
1075 exit_free:
1076 	free(key);
1077 	close(fd);
1078 
1079 	if (!err && json_output)
1080 		jsonw_null(json_wtr);
1081 	return err;
1082 }
1083 
1084 static int do_pin(int argc, char **argv)
1085 {
1086 	int err;
1087 
1088 	err = do_pin_any(argc, argv, bpf_map_get_fd_by_id);
1089 	if (!err && json_output)
1090 		jsonw_null(json_wtr);
1091 	return err;
1092 }
1093 
1094 static int do_create(int argc, char **argv)
1095 {
1096 	struct bpf_create_map_attr attr = { NULL, };
1097 	const char *pinfile;
1098 	int err, fd;
1099 
1100 	if (!REQ_ARGS(7))
1101 		return -1;
1102 	pinfile = GET_ARG();
1103 
1104 	while (argc) {
1105 		if (!REQ_ARGS(2))
1106 			return -1;
1107 
1108 		if (is_prefix(*argv, "type")) {
1109 			NEXT_ARG();
1110 
1111 			if (attr.map_type) {
1112 				p_err("map type already specified");
1113 				return -1;
1114 			}
1115 
1116 			attr.map_type = map_type_from_str(*argv);
1117 			if ((int)attr.map_type < 0) {
1118 				p_err("unrecognized map type: %s", *argv);
1119 				return -1;
1120 			}
1121 			NEXT_ARG();
1122 		} else if (is_prefix(*argv, "name")) {
1123 			NEXT_ARG();
1124 			attr.name = GET_ARG();
1125 		} else if (is_prefix(*argv, "key")) {
1126 			if (parse_u32_arg(&argc, &argv, &attr.key_size,
1127 					  "key size"))
1128 				return -1;
1129 		} else if (is_prefix(*argv, "value")) {
1130 			if (parse_u32_arg(&argc, &argv, &attr.value_size,
1131 					  "value size"))
1132 				return -1;
1133 		} else if (is_prefix(*argv, "entries")) {
1134 			if (parse_u32_arg(&argc, &argv, &attr.max_entries,
1135 					  "max entries"))
1136 				return -1;
1137 		} else if (is_prefix(*argv, "flags")) {
1138 			if (parse_u32_arg(&argc, &argv, &attr.map_flags,
1139 					  "flags"))
1140 				return -1;
1141 		} else if (is_prefix(*argv, "dev")) {
1142 			NEXT_ARG();
1143 
1144 			if (attr.map_ifindex) {
1145 				p_err("offload device already specified");
1146 				return -1;
1147 			}
1148 
1149 			attr.map_ifindex = if_nametoindex(*argv);
1150 			if (!attr.map_ifindex) {
1151 				p_err("unrecognized netdevice '%s': %s",
1152 				      *argv, strerror(errno));
1153 				return -1;
1154 			}
1155 			NEXT_ARG();
1156 		}
1157 	}
1158 
1159 	if (!attr.name) {
1160 		p_err("map name not specified");
1161 		return -1;
1162 	}
1163 
1164 	set_max_rlimit();
1165 
1166 	fd = bpf_create_map_xattr(&attr);
1167 	if (fd < 0) {
1168 		p_err("map create failed: %s", strerror(errno));
1169 		return -1;
1170 	}
1171 
1172 	err = do_pin_fd(fd, pinfile);
1173 	close(fd);
1174 	if (err)
1175 		return err;
1176 
1177 	if (json_output)
1178 		jsonw_null(json_wtr);
1179 	return 0;
1180 }
1181 
1182 static int do_pop_dequeue(int argc, char **argv)
1183 {
1184 	struct bpf_map_info info = {};
1185 	__u32 len = sizeof(info);
1186 	void *key, *value;
1187 	int err;
1188 	int fd;
1189 
1190 	if (argc < 2)
1191 		usage();
1192 
1193 	fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
1194 	if (fd < 0)
1195 		return -1;
1196 
1197 	err = alloc_key_value(&info, &key, &value);
1198 	if (err)
1199 		goto exit_free;
1200 
1201 	err = bpf_map_lookup_and_delete_elem(fd, key, value);
1202 	if (err) {
1203 		if (errno == ENOENT) {
1204 			if (json_output)
1205 				jsonw_null(json_wtr);
1206 			else
1207 				printf("Error: empty map\n");
1208 		} else {
1209 			p_err("pop failed: %s", strerror(errno));
1210 		}
1211 
1212 		goto exit_free;
1213 	}
1214 
1215 	print_key_value(&info, key, value);
1216 
1217 exit_free:
1218 	free(key);
1219 	free(value);
1220 	close(fd);
1221 
1222 	return err;
1223 }
1224 
1225 static int do_help(int argc, char **argv)
1226 {
1227 	if (json_output) {
1228 		jsonw_null(json_wtr);
1229 		return 0;
1230 	}
1231 
1232 	fprintf(stderr,
1233 		"Usage: %s %s { show | list }   [MAP]\n"
1234 		"       %s %s create     FILE type TYPE key KEY_SIZE value VALUE_SIZE \\\n"
1235 		"                              entries MAX_ENTRIES name NAME [flags FLAGS] \\\n"
1236 		"                              [dev NAME]\n"
1237 		"       %s %s dump       MAP\n"
1238 		"       %s %s update     MAP [key DATA] [value VALUE] [UPDATE_FLAGS]\n"
1239 		"       %s %s lookup     MAP [key DATA]\n"
1240 		"       %s %s getnext    MAP [key DATA]\n"
1241 		"       %s %s delete     MAP  key DATA\n"
1242 		"       %s %s pin        MAP  FILE\n"
1243 		"       %s %s event_pipe MAP [cpu N index M]\n"
1244 		"       %s %s peek       MAP\n"
1245 		"       %s %s push       MAP value VALUE\n"
1246 		"       %s %s pop        MAP\n"
1247 		"       %s %s enqueue    MAP value VALUE\n"
1248 		"       %s %s dequeue    MAP\n"
1249 		"       %s %s help\n"
1250 		"\n"
1251 		"       " HELP_SPEC_MAP "\n"
1252 		"       DATA := { [hex] BYTES }\n"
1253 		"       " HELP_SPEC_PROGRAM "\n"
1254 		"       VALUE := { DATA | MAP | PROG }\n"
1255 		"       UPDATE_FLAGS := { any | exist | noexist }\n"
1256 		"       TYPE := { hash | array | prog_array | perf_event_array | percpu_hash |\n"
1257 		"                 percpu_array | stack_trace | cgroup_array | lru_hash |\n"
1258 		"                 lru_percpu_hash | lpm_trie | array_of_maps | hash_of_maps |\n"
1259 		"                 devmap | sockmap | cpumap | xskmap | sockhash |\n"
1260 		"                 cgroup_storage | reuseport_sockarray | percpu_cgroup_storage }\n"
1261 		"       " HELP_SPEC_OPTIONS "\n"
1262 		"",
1263 		bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
1264 		bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
1265 		bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
1266 		bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
1267 		bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2]);
1268 
1269 	return 0;
1270 }
1271 
1272 static const struct cmd cmds[] = {
1273 	{ "show",	do_show },
1274 	{ "list",	do_show },
1275 	{ "help",	do_help },
1276 	{ "dump",	do_dump },
1277 	{ "update",	do_update },
1278 	{ "lookup",	do_lookup },
1279 	{ "getnext",	do_getnext },
1280 	{ "delete",	do_delete },
1281 	{ "pin",	do_pin },
1282 	{ "event_pipe",	do_event_pipe },
1283 	{ "create",	do_create },
1284 	{ "peek",	do_lookup },
1285 	{ "push",	do_update },
1286 	{ "enqueue",	do_update },
1287 	{ "pop",	do_pop_dequeue },
1288 	{ "dequeue",	do_pop_dequeue },
1289 	{ 0 }
1290 };
1291 
1292 int do_map(int argc, char **argv)
1293 {
1294 	return cmd_select(cmds, argc, argv, do_help);
1295 }
1296