Linux-libre 4.19.123-gnu
[librecmc/linux-libre.git] / tools / bpf / bpftool / map.c
1 /*
2  * Copyright (C) 2017-2018 Netronome Systems, Inc.
3  *
4  * This software is dual licensed under the GNU General License Version 2,
5  * June 1991 as shown in the file COPYING in the top-level directory of this
6  * source tree or the BSD 2-Clause License provided below.  You have the
7  * option to license this software under the complete terms of either license.
8  *
9  * The BSD 2-Clause License:
10  *
11  *     Redistribution and use in source and binary forms, with or
12  *     without modification, are permitted provided that the following
13  *     conditions are met:
14  *
15  *      1. Redistributions of source code must retain the above
16  *         copyright notice, this list of conditions and the following
17  *         disclaimer.
18  *
19  *      2. Redistributions in binary form must reproduce the above
20  *         copyright notice, this list of conditions and the following
21  *         disclaimer in the documentation and/or other materials
22  *         provided with the distribution.
23  *
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
28  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
29  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31  * SOFTWARE.
32  */
33
34 #include <assert.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <linux/err.h>
38 #include <linux/kernel.h>
39 #include <stdbool.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
44 #include <sys/types.h>
45 #include <sys/stat.h>
46
47 #include <bpf.h>
48
49 #include "btf.h"
50 #include "json_writer.h"
51 #include "main.h"
52
53 static const char * const map_type_name[] = {
54         [BPF_MAP_TYPE_UNSPEC]           = "unspec",
55         [BPF_MAP_TYPE_HASH]             = "hash",
56         [BPF_MAP_TYPE_ARRAY]            = "array",
57         [BPF_MAP_TYPE_PROG_ARRAY]       = "prog_array",
58         [BPF_MAP_TYPE_PERF_EVENT_ARRAY] = "perf_event_array",
59         [BPF_MAP_TYPE_PERCPU_HASH]      = "percpu_hash",
60         [BPF_MAP_TYPE_PERCPU_ARRAY]     = "percpu_array",
61         [BPF_MAP_TYPE_STACK_TRACE]      = "stack_trace",
62         [BPF_MAP_TYPE_CGROUP_ARRAY]     = "cgroup_array",
63         [BPF_MAP_TYPE_LRU_HASH]         = "lru_hash",
64         [BPF_MAP_TYPE_LRU_PERCPU_HASH]  = "lru_percpu_hash",
65         [BPF_MAP_TYPE_LPM_TRIE]         = "lpm_trie",
66         [BPF_MAP_TYPE_ARRAY_OF_MAPS]    = "array_of_maps",
67         [BPF_MAP_TYPE_HASH_OF_MAPS]     = "hash_of_maps",
68         [BPF_MAP_TYPE_DEVMAP]           = "devmap",
69         [BPF_MAP_TYPE_SOCKMAP]          = "sockmap",
70         [BPF_MAP_TYPE_CPUMAP]           = "cpumap",
71         [BPF_MAP_TYPE_XSKMAP]           = "xskmap",
72         [BPF_MAP_TYPE_SOCKHASH]         = "sockhash",
73         [BPF_MAP_TYPE_CGROUP_STORAGE]   = "cgroup_storage",
74 };
75
76 static bool map_is_per_cpu(__u32 type)
77 {
78         return type == BPF_MAP_TYPE_PERCPU_HASH ||
79                type == BPF_MAP_TYPE_PERCPU_ARRAY ||
80                type == BPF_MAP_TYPE_LRU_PERCPU_HASH;
81 }
82
83 static bool map_is_map_of_maps(__u32 type)
84 {
85         return type == BPF_MAP_TYPE_ARRAY_OF_MAPS ||
86                type == BPF_MAP_TYPE_HASH_OF_MAPS;
87 }
88
89 static bool map_is_map_of_progs(__u32 type)
90 {
91         return type == BPF_MAP_TYPE_PROG_ARRAY;
92 }
93
94 static void *alloc_value(struct bpf_map_info *info)
95 {
96         if (map_is_per_cpu(info->type))
97                 return malloc(round_up(info->value_size, 8) *
98                               get_possible_cpus());
99         else
100                 return malloc(info->value_size);
101 }
102
103 int map_parse_fd(int *argc, char ***argv)
104 {
105         int fd;
106
107         if (is_prefix(**argv, "id")) {
108                 unsigned int id;
109                 char *endptr;
110
111                 NEXT_ARGP();
112
113                 id = strtoul(**argv, &endptr, 0);
114                 if (*endptr) {
115                         p_err("can't parse %s as ID", **argv);
116                         return -1;
117                 }
118                 NEXT_ARGP();
119
120                 fd = bpf_map_get_fd_by_id(id);
121                 if (fd < 0)
122                         p_err("get map by id (%u): %s", id, strerror(errno));
123                 return fd;
124         } else if (is_prefix(**argv, "pinned")) {
125                 char *path;
126
127                 NEXT_ARGP();
128
129                 path = **argv;
130                 NEXT_ARGP();
131
132                 return open_obj_pinned_any(path, BPF_OBJ_MAP);
133         }
134
135         p_err("expected 'id' or 'pinned', got: '%s'?", **argv);
136         return -1;
137 }
138
139 int map_parse_fd_and_info(int *argc, char ***argv, void *info, __u32 *info_len)
140 {
141         int err;
142         int fd;
143
144         fd = map_parse_fd(argc, argv);
145         if (fd < 0)
146                 return -1;
147
148         err = bpf_obj_get_info_by_fd(fd, info, info_len);
149         if (err) {
150                 p_err("can't get map info: %s", strerror(errno));
151                 close(fd);
152                 return err;
153         }
154
155         return fd;
156 }
157
158 static int do_dump_btf(const struct btf_dumper *d,
159                        struct bpf_map_info *map_info, void *key,
160                        void *value)
161 {
162         int ret;
163
164         /* start of key-value pair */
165         jsonw_start_object(d->jw);
166
167         jsonw_name(d->jw, "key");
168
169         ret = btf_dumper_type(d, map_info->btf_key_type_id, key);
170         if (ret)
171                 goto err_end_obj;
172
173         jsonw_name(d->jw, "value");
174
175         ret = btf_dumper_type(d, map_info->btf_value_type_id, value);
176
177 err_end_obj:
178         /* end of key-value pair */
179         jsonw_end_object(d->jw);
180
181         return ret;
182 }
183
184 static int get_btf(struct bpf_map_info *map_info, struct btf **btf)
185 {
186         struct bpf_btf_info btf_info = { 0 };
187         __u32 len = sizeof(btf_info);
188         __u32 last_size;
189         int btf_fd;
190         void *ptr;
191         int err;
192
193         err = 0;
194         *btf = NULL;
195         btf_fd = bpf_btf_get_fd_by_id(map_info->btf_id);
196         if (btf_fd < 0)
197                 return 0;
198
199         /* we won't know btf_size until we call bpf_obj_get_info_by_fd(). so
200          * let's start with a sane default - 4KiB here - and resize it only if
201          * bpf_obj_get_info_by_fd() needs a bigger buffer.
202          */
203         btf_info.btf_size = 4096;
204         last_size = btf_info.btf_size;
205         ptr = malloc(last_size);
206         if (!ptr) {
207                 err = -ENOMEM;
208                 goto exit_free;
209         }
210
211         bzero(ptr, last_size);
212         btf_info.btf = ptr_to_u64(ptr);
213         err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len);
214
215         if (!err && btf_info.btf_size > last_size) {
216                 void *temp_ptr;
217
218                 last_size = btf_info.btf_size;
219                 temp_ptr = realloc(ptr, last_size);
220                 if (!temp_ptr) {
221                         err = -ENOMEM;
222                         goto exit_free;
223                 }
224                 ptr = temp_ptr;
225                 bzero(ptr, last_size);
226                 btf_info.btf = ptr_to_u64(ptr);
227                 err = bpf_obj_get_info_by_fd(btf_fd, &btf_info, &len);
228         }
229
230         if (err || btf_info.btf_size > last_size) {
231                 err = errno;
232                 goto exit_free;
233         }
234
235         *btf = btf__new((__u8 *)btf_info.btf, btf_info.btf_size, NULL);
236         if (IS_ERR(*btf)) {
237                 err = PTR_ERR(*btf);
238                 *btf = NULL;
239         }
240
241 exit_free:
242         close(btf_fd);
243         free(ptr);
244
245         return err;
246 }
247
248 static json_writer_t *get_btf_writer(void)
249 {
250         json_writer_t *jw = jsonw_new(stdout);
251
252         if (!jw)
253                 return NULL;
254         jsonw_pretty(jw, true);
255
256         return jw;
257 }
258
259 static void print_entry_json(struct bpf_map_info *info, unsigned char *key,
260                              unsigned char *value, struct btf *btf)
261 {
262         jsonw_start_object(json_wtr);
263
264         if (!map_is_per_cpu(info->type)) {
265                 jsonw_name(json_wtr, "key");
266                 print_hex_data_json(key, info->key_size);
267                 jsonw_name(json_wtr, "value");
268                 print_hex_data_json(value, info->value_size);
269                 if (btf) {
270                         struct btf_dumper d = {
271                                 .btf = btf,
272                                 .jw = json_wtr,
273                                 .is_plain_text = false,
274                         };
275
276                         jsonw_name(json_wtr, "formatted");
277                         do_dump_btf(&d, info, key, value);
278                 }
279         } else {
280                 unsigned int i, n, step;
281
282                 n = get_possible_cpus();
283                 step = round_up(info->value_size, 8);
284
285                 jsonw_name(json_wtr, "key");
286                 print_hex_data_json(key, info->key_size);
287
288                 jsonw_name(json_wtr, "values");
289                 jsonw_start_array(json_wtr);
290                 for (i = 0; i < n; i++) {
291                         jsonw_start_object(json_wtr);
292
293                         jsonw_int_field(json_wtr, "cpu", i);
294
295                         jsonw_name(json_wtr, "value");
296                         print_hex_data_json(value + i * step,
297                                             info->value_size);
298
299                         jsonw_end_object(json_wtr);
300                 }
301                 jsonw_end_array(json_wtr);
302         }
303
304         jsonw_end_object(json_wtr);
305 }
306
307 static void print_entry_plain(struct bpf_map_info *info, unsigned char *key,
308                               unsigned char *value)
309 {
310         if (!map_is_per_cpu(info->type)) {
311                 bool single_line, break_names;
312
313                 break_names = info->key_size > 16 || info->value_size > 16;
314                 single_line = info->key_size + info->value_size <= 24 &&
315                         !break_names;
316
317                 printf("key:%c", break_names ? '\n' : ' ');
318                 fprint_hex(stdout, key, info->key_size, " ");
319
320                 printf(single_line ? "  " : "\n");
321
322                 printf("value:%c", break_names ? '\n' : ' ');
323                 fprint_hex(stdout, value, info->value_size, " ");
324
325                 printf("\n");
326         } else {
327                 unsigned int i, n, step;
328
329                 n = get_possible_cpus();
330                 step = round_up(info->value_size, 8);
331
332                 printf("key:\n");
333                 fprint_hex(stdout, key, info->key_size, " ");
334                 printf("\n");
335                 for (i = 0; i < n; i++) {
336                         printf("value (CPU %02d):%c",
337                                i, info->value_size > 16 ? '\n' : ' ');
338                         fprint_hex(stdout, value + i * step,
339                                    info->value_size, " ");
340                         printf("\n");
341                 }
342         }
343 }
344
345 static char **parse_bytes(char **argv, const char *name, unsigned char *val,
346                           unsigned int n)
347 {
348         unsigned int i = 0, base = 0;
349         char *endptr;
350
351         if (is_prefix(*argv, "hex")) {
352                 base = 16;
353                 argv++;
354         }
355
356         while (i < n && argv[i]) {
357                 val[i] = strtoul(argv[i], &endptr, base);
358                 if (*endptr) {
359                         p_err("error parsing byte: %s", argv[i]);
360                         return NULL;
361                 }
362                 i++;
363         }
364
365         if (i != n) {
366                 p_err("%s expected %d bytes got %d", name, n, i);
367                 return NULL;
368         }
369
370         return argv + i;
371 }
372
373 /* on per cpu maps we must copy the provided value on all value instances */
374 static void fill_per_cpu_value(struct bpf_map_info *info, void *value)
375 {
376         unsigned int i, n, step;
377
378         if (!map_is_per_cpu(info->type))
379                 return;
380
381         n = get_possible_cpus();
382         step = round_up(info->value_size, 8);
383         for (i = 1; i < n; i++)
384                 memcpy(value + i * step, value, info->value_size);
385 }
386
387 static int parse_elem(char **argv, struct bpf_map_info *info,
388                       void *key, void *value, __u32 key_size, __u32 value_size,
389                       __u32 *flags, __u32 **value_fd)
390 {
391         if (!*argv) {
392                 if (!key && !value)
393                         return 0;
394                 p_err("did not find %s", key ? "key" : "value");
395                 return -1;
396         }
397
398         if (is_prefix(*argv, "key")) {
399                 if (!key) {
400                         if (key_size)
401                                 p_err("duplicate key");
402                         else
403                                 p_err("unnecessary key");
404                         return -1;
405                 }
406
407                 argv = parse_bytes(argv + 1, "key", key, key_size);
408                 if (!argv)
409                         return -1;
410
411                 return parse_elem(argv, info, NULL, value, key_size, value_size,
412                                   flags, value_fd);
413         } else if (is_prefix(*argv, "value")) {
414                 int fd;
415
416                 if (!value) {
417                         if (value_size)
418                                 p_err("duplicate value");
419                         else
420                                 p_err("unnecessary value");
421                         return -1;
422                 }
423
424                 argv++;
425
426                 if (map_is_map_of_maps(info->type)) {
427                         int argc = 2;
428
429                         if (value_size != 4) {
430                                 p_err("value smaller than 4B for map in map?");
431                                 return -1;
432                         }
433                         if (!argv[0] || !argv[1]) {
434                                 p_err("not enough value arguments for map in map");
435                                 return -1;
436                         }
437
438                         fd = map_parse_fd(&argc, &argv);
439                         if (fd < 0)
440                                 return -1;
441
442                         *value_fd = value;
443                         **value_fd = fd;
444                 } else if (map_is_map_of_progs(info->type)) {
445                         int argc = 2;
446
447                         if (value_size != 4) {
448                                 p_err("value smaller than 4B for map of progs?");
449                                 return -1;
450                         }
451                         if (!argv[0] || !argv[1]) {
452                                 p_err("not enough value arguments for map of progs");
453                                 return -1;
454                         }
455
456                         fd = prog_parse_fd(&argc, &argv);
457                         if (fd < 0)
458                                 return -1;
459
460                         *value_fd = value;
461                         **value_fd = fd;
462                 } else {
463                         argv = parse_bytes(argv, "value", value, value_size);
464                         if (!argv)
465                                 return -1;
466
467                         fill_per_cpu_value(info, value);
468                 }
469
470                 return parse_elem(argv, info, key, NULL, key_size, value_size,
471                                   flags, NULL);
472         } else if (is_prefix(*argv, "any") || is_prefix(*argv, "noexist") ||
473                    is_prefix(*argv, "exist")) {
474                 if (!flags) {
475                         p_err("flags specified multiple times: %s", *argv);
476                         return -1;
477                 }
478
479                 if (is_prefix(*argv, "any"))
480                         *flags = BPF_ANY;
481                 else if (is_prefix(*argv, "noexist"))
482                         *flags = BPF_NOEXIST;
483                 else if (is_prefix(*argv, "exist"))
484                         *flags = BPF_EXIST;
485
486                 return parse_elem(argv + 1, info, key, value, key_size,
487                                   value_size, NULL, value_fd);
488         }
489
490         p_err("expected key or value, got: %s", *argv);
491         return -1;
492 }
493
494 static int show_map_close_json(int fd, struct bpf_map_info *info)
495 {
496         char *memlock;
497
498         memlock = get_fdinfo(fd, "memlock");
499         close(fd);
500
501         jsonw_start_object(json_wtr);
502
503         jsonw_uint_field(json_wtr, "id", info->id);
504         if (info->type < ARRAY_SIZE(map_type_name))
505                 jsonw_string_field(json_wtr, "type",
506                                    map_type_name[info->type]);
507         else
508                 jsonw_uint_field(json_wtr, "type", info->type);
509
510         if (*info->name)
511                 jsonw_string_field(json_wtr, "name", info->name);
512
513         jsonw_name(json_wtr, "flags");
514         jsonw_printf(json_wtr, "%d", info->map_flags);
515
516         print_dev_json(info->ifindex, info->netns_dev, info->netns_ino);
517
518         jsonw_uint_field(json_wtr, "bytes_key", info->key_size);
519         jsonw_uint_field(json_wtr, "bytes_value", info->value_size);
520         jsonw_uint_field(json_wtr, "max_entries", info->max_entries);
521
522         if (memlock)
523                 jsonw_int_field(json_wtr, "bytes_memlock", atoi(memlock));
524         free(memlock);
525
526         if (!hash_empty(map_table.table)) {
527                 struct pinned_obj *obj;
528
529                 jsonw_name(json_wtr, "pinned");
530                 jsonw_start_array(json_wtr);
531                 hash_for_each_possible(map_table.table, obj, hash, info->id) {
532                         if (obj->id == info->id)
533                                 jsonw_string(json_wtr, obj->path);
534                 }
535                 jsonw_end_array(json_wtr);
536         }
537
538         jsonw_end_object(json_wtr);
539
540         return 0;
541 }
542
543 static int show_map_close_plain(int fd, struct bpf_map_info *info)
544 {
545         char *memlock;
546
547         memlock = get_fdinfo(fd, "memlock");
548         close(fd);
549
550         printf("%u: ", info->id);
551         if (info->type < ARRAY_SIZE(map_type_name))
552                 printf("%s  ", map_type_name[info->type]);
553         else
554                 printf("type %u  ", info->type);
555
556         if (*info->name)
557                 printf("name %s  ", info->name);
558
559         printf("flags 0x%x", info->map_flags);
560         print_dev_plain(info->ifindex, info->netns_dev, info->netns_ino);
561         printf("\n");
562         printf("\tkey %uB  value %uB  max_entries %u",
563                info->key_size, info->value_size, info->max_entries);
564
565         if (memlock)
566                 printf("  memlock %sB", memlock);
567         free(memlock);
568
569         printf("\n");
570         if (!hash_empty(map_table.table)) {
571                 struct pinned_obj *obj;
572
573                 hash_for_each_possible(map_table.table, obj, hash, info->id) {
574                         if (obj->id == info->id)
575                                 printf("\tpinned %s\n", obj->path);
576                 }
577         }
578         return 0;
579 }
580
581 static int do_show(int argc, char **argv)
582 {
583         struct bpf_map_info info = {};
584         __u32 len = sizeof(info);
585         __u32 id = 0;
586         int err;
587         int fd;
588
589         if (show_pinned)
590                 build_pinned_obj_table(&map_table, BPF_OBJ_MAP);
591
592         if (argc == 2) {
593                 fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
594                 if (fd < 0)
595                         return -1;
596
597                 if (json_output)
598                         return show_map_close_json(fd, &info);
599                 else
600                         return show_map_close_plain(fd, &info);
601         }
602
603         if (argc)
604                 return BAD_ARG();
605
606         if (json_output)
607                 jsonw_start_array(json_wtr);
608         while (true) {
609                 err = bpf_map_get_next_id(id, &id);
610                 if (err) {
611                         if (errno == ENOENT)
612                                 break;
613                         p_err("can't get next map: %s%s", strerror(errno),
614                               errno == EINVAL ? " -- kernel too old?" : "");
615                         break;
616                 }
617
618                 fd = bpf_map_get_fd_by_id(id);
619                 if (fd < 0) {
620                         if (errno == ENOENT)
621                                 continue;
622                         p_err("can't get map by id (%u): %s",
623                               id, strerror(errno));
624                         break;
625                 }
626
627                 err = bpf_obj_get_info_by_fd(fd, &info, &len);
628                 if (err) {
629                         p_err("can't get map info: %s", strerror(errno));
630                         close(fd);
631                         break;
632                 }
633
634                 if (json_output)
635                         show_map_close_json(fd, &info);
636                 else
637                         show_map_close_plain(fd, &info);
638         }
639         if (json_output)
640                 jsonw_end_array(json_wtr);
641
642         return errno == ENOENT ? 0 : -1;
643 }
644
645 static int do_dump(int argc, char **argv)
646 {
647         struct bpf_map_info info = {};
648         void *key, *value, *prev_key;
649         unsigned int num_elems = 0;
650         __u32 len = sizeof(info);
651         json_writer_t *btf_wtr;
652         struct btf *btf = NULL;
653         int err;
654         int fd;
655
656         if (argc != 2)
657                 usage();
658
659         fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
660         if (fd < 0)
661                 return -1;
662
663         if (map_is_map_of_maps(info.type) || map_is_map_of_progs(info.type)) {
664                 p_err("Dumping maps of maps and program maps not supported");
665                 close(fd);
666                 return -1;
667         }
668
669         key = malloc(info.key_size);
670         value = alloc_value(&info);
671         if (!key || !value) {
672                 p_err("mem alloc failed");
673                 err = -1;
674                 goto exit_free;
675         }
676
677         prev_key = NULL;
678
679         err = get_btf(&info, &btf);
680         if (err) {
681                 p_err("failed to get btf");
682                 goto exit_free;
683         }
684
685         if (json_output)
686                 jsonw_start_array(json_wtr);
687         else
688                 if (btf) {
689                         btf_wtr = get_btf_writer();
690                         if (!btf_wtr) {
691                                 p_info("failed to create json writer for btf. falling back to plain output");
692                                 btf__free(btf);
693                                 btf = NULL;
694                         } else {
695                                 jsonw_start_array(btf_wtr);
696                         }
697                 }
698
699         while (true) {
700                 err = bpf_map_get_next_key(fd, prev_key, key);
701                 if (err) {
702                         if (errno == ENOENT)
703                                 err = 0;
704                         break;
705                 }
706
707                 if (!bpf_map_lookup_elem(fd, key, value)) {
708                         if (json_output)
709                                 print_entry_json(&info, key, value, btf);
710                         else
711                                 if (btf) {
712                                         struct btf_dumper d = {
713                                                 .btf = btf,
714                                                 .jw = btf_wtr,
715                                                 .is_plain_text = true,
716                                         };
717
718                                         do_dump_btf(&d, &info, key, value);
719                                 } else {
720                                         print_entry_plain(&info, key, value);
721                                 }
722                 } else {
723                         if (json_output) {
724                                 jsonw_name(json_wtr, "key");
725                                 print_hex_data_json(key, info.key_size);
726                                 jsonw_name(json_wtr, "value");
727                                 jsonw_start_object(json_wtr);
728                                 jsonw_string_field(json_wtr, "error",
729                                                    "can't lookup element");
730                                 jsonw_end_object(json_wtr);
731                         } else {
732                                 p_info("can't lookup element with key: ");
733                                 fprint_hex(stderr, key, info.key_size, " ");
734                                 fprintf(stderr, "\n");
735                         }
736                 }
737
738                 prev_key = key;
739                 num_elems++;
740         }
741
742         if (json_output)
743                 jsonw_end_array(json_wtr);
744         else if (btf) {
745                 jsonw_end_array(btf_wtr);
746                 jsonw_destroy(&btf_wtr);
747         } else {
748                 printf("Found %u element%s\n", num_elems,
749                        num_elems != 1 ? "s" : "");
750         }
751
752 exit_free:
753         free(key);
754         free(value);
755         close(fd);
756         btf__free(btf);
757
758         return err;
759 }
760
761 static int do_update(int argc, char **argv)
762 {
763         struct bpf_map_info info = {};
764         __u32 len = sizeof(info);
765         __u32 *value_fd = NULL;
766         __u32 flags = BPF_ANY;
767         void *key, *value;
768         int fd, err;
769
770         if (argc < 2)
771                 usage();
772
773         fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
774         if (fd < 0)
775                 return -1;
776
777         key = malloc(info.key_size);
778         value = alloc_value(&info);
779         if (!key || !value) {
780                 p_err("mem alloc failed");
781                 err = -1;
782                 goto exit_free;
783         }
784
785         err = parse_elem(argv, &info, key, value, info.key_size,
786                          info.value_size, &flags, &value_fd);
787         if (err)
788                 goto exit_free;
789
790         err = bpf_map_update_elem(fd, key, value, flags);
791         if (err) {
792                 p_err("update failed: %s", strerror(errno));
793                 goto exit_free;
794         }
795
796 exit_free:
797         if (value_fd)
798                 close(*value_fd);
799         free(key);
800         free(value);
801         close(fd);
802
803         if (!err && json_output)
804                 jsonw_null(json_wtr);
805         return err;
806 }
807
808 static int do_lookup(int argc, char **argv)
809 {
810         struct bpf_map_info info = {};
811         __u32 len = sizeof(info);
812         json_writer_t *btf_wtr;
813         struct btf *btf = NULL;
814         void *key, *value;
815         int err;
816         int fd;
817
818         if (argc < 2)
819                 usage();
820
821         fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
822         if (fd < 0)
823                 return -1;
824
825         key = malloc(info.key_size);
826         value = alloc_value(&info);
827         if (!key || !value) {
828                 p_err("mem alloc failed");
829                 err = -1;
830                 goto exit_free;
831         }
832
833         err = parse_elem(argv, &info, key, NULL, info.key_size, 0, NULL, NULL);
834         if (err)
835                 goto exit_free;
836
837         err = bpf_map_lookup_elem(fd, key, value);
838         if (err) {
839                 if (errno == ENOENT) {
840                         if (json_output) {
841                                 jsonw_null(json_wtr);
842                         } else {
843                                 printf("key:\n");
844                                 fprint_hex(stdout, key, info.key_size, " ");
845                                 printf("\n\nNot found\n");
846                         }
847                 } else {
848                         p_err("lookup failed: %s", strerror(errno));
849                 }
850
851                 goto exit_free;
852         }
853
854         /* here means bpf_map_lookup_elem() succeeded */
855         err = get_btf(&info, &btf);
856         if (err) {
857                 p_err("failed to get btf");
858                 goto exit_free;
859         }
860
861         if (json_output) {
862                 print_entry_json(&info, key, value, btf);
863         } else if (btf) {
864                 /* if here json_wtr wouldn't have been initialised,
865                  * so let's create separate writer for btf
866                  */
867                 btf_wtr = get_btf_writer();
868                 if (!btf_wtr) {
869                         p_info("failed to create json writer for btf. falling back to plain output");
870                         btf__free(btf);
871                         btf = NULL;
872                         print_entry_plain(&info, key, value);
873                 } else {
874                         struct btf_dumper d = {
875                                 .btf = btf,
876                                 .jw = btf_wtr,
877                                 .is_plain_text = true,
878                         };
879
880                         do_dump_btf(&d, &info, key, value);
881                         jsonw_destroy(&btf_wtr);
882                 }
883         } else {
884                 print_entry_plain(&info, key, value);
885         }
886
887 exit_free:
888         free(key);
889         free(value);
890         close(fd);
891         btf__free(btf);
892
893         return err;
894 }
895
896 static int do_getnext(int argc, char **argv)
897 {
898         struct bpf_map_info info = {};
899         __u32 len = sizeof(info);
900         void *key, *nextkey;
901         int err;
902         int fd;
903
904         if (argc < 2)
905                 usage();
906
907         fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
908         if (fd < 0)
909                 return -1;
910
911         key = malloc(info.key_size);
912         nextkey = malloc(info.key_size);
913         if (!key || !nextkey) {
914                 p_err("mem alloc failed");
915                 err = -1;
916                 goto exit_free;
917         }
918
919         if (argc) {
920                 err = parse_elem(argv, &info, key, NULL, info.key_size, 0,
921                                  NULL, NULL);
922                 if (err)
923                         goto exit_free;
924         } else {
925                 free(key);
926                 key = NULL;
927         }
928
929         err = bpf_map_get_next_key(fd, key, nextkey);
930         if (err) {
931                 p_err("can't get next key: %s", strerror(errno));
932                 goto exit_free;
933         }
934
935         if (json_output) {
936                 jsonw_start_object(json_wtr);
937                 if (key) {
938                         jsonw_name(json_wtr, "key");
939                         print_hex_data_json(key, info.key_size);
940                 } else {
941                         jsonw_null_field(json_wtr, "key");
942                 }
943                 jsonw_name(json_wtr, "next_key");
944                 print_hex_data_json(nextkey, info.key_size);
945                 jsonw_end_object(json_wtr);
946         } else {
947                 if (key) {
948                         printf("key:\n");
949                         fprint_hex(stdout, key, info.key_size, " ");
950                         printf("\n");
951                 } else {
952                         printf("key: None\n");
953                 }
954                 printf("next key:\n");
955                 fprint_hex(stdout, nextkey, info.key_size, " ");
956                 printf("\n");
957         }
958
959 exit_free:
960         free(nextkey);
961         free(key);
962         close(fd);
963
964         return err;
965 }
966
967 static int do_delete(int argc, char **argv)
968 {
969         struct bpf_map_info info = {};
970         __u32 len = sizeof(info);
971         void *key;
972         int err;
973         int fd;
974
975         if (argc < 2)
976                 usage();
977
978         fd = map_parse_fd_and_info(&argc, &argv, &info, &len);
979         if (fd < 0)
980                 return -1;
981
982         key = malloc(info.key_size);
983         if (!key) {
984                 p_err("mem alloc failed");
985                 err = -1;
986                 goto exit_free;
987         }
988
989         err = parse_elem(argv, &info, key, NULL, info.key_size, 0, NULL, NULL);
990         if (err)
991                 goto exit_free;
992
993         err = bpf_map_delete_elem(fd, key);
994         if (err)
995                 p_err("delete failed: %s", strerror(errno));
996
997 exit_free:
998         free(key);
999         close(fd);
1000
1001         if (!err && json_output)
1002                 jsonw_null(json_wtr);
1003         return err;
1004 }
1005
1006 static int do_pin(int argc, char **argv)
1007 {
1008         int err;
1009
1010         err = do_pin_any(argc, argv, bpf_map_get_fd_by_id);
1011         if (!err && json_output)
1012                 jsonw_null(json_wtr);
1013         return err;
1014 }
1015
1016 static int do_help(int argc, char **argv)
1017 {
1018         if (json_output) {
1019                 jsonw_null(json_wtr);
1020                 return 0;
1021         }
1022
1023         fprintf(stderr,
1024                 "Usage: %s %s { show | list }   [MAP]\n"
1025                 "       %s %s dump       MAP\n"
1026                 "       %s %s update     MAP  key DATA value VALUE [UPDATE_FLAGS]\n"
1027                 "       %s %s lookup     MAP  key DATA\n"
1028                 "       %s %s getnext    MAP [key DATA]\n"
1029                 "       %s %s delete     MAP  key DATA\n"
1030                 "       %s %s pin        MAP  FILE\n"
1031                 "       %s %s event_pipe MAP [cpu N index M]\n"
1032                 "       %s %s help\n"
1033                 "\n"
1034                 "       " HELP_SPEC_MAP "\n"
1035                 "       DATA := { [hex] BYTES }\n"
1036                 "       " HELP_SPEC_PROGRAM "\n"
1037                 "       VALUE := { DATA | MAP | PROG }\n"
1038                 "       UPDATE_FLAGS := { any | exist | noexist }\n"
1039                 "       " HELP_SPEC_OPTIONS "\n"
1040                 "",
1041                 bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
1042                 bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2],
1043                 bin_name, argv[-2], bin_name, argv[-2], bin_name, argv[-2]);
1044
1045         return 0;
1046 }
1047
1048 static const struct cmd cmds[] = {
1049         { "show",       do_show },
1050         { "list",       do_show },
1051         { "help",       do_help },
1052         { "dump",       do_dump },
1053         { "update",     do_update },
1054         { "lookup",     do_lookup },
1055         { "getnext",    do_getnext },
1056         { "delete",     do_delete },
1057         { "pin",        do_pin },
1058         { "event_pipe", do_event_pipe },
1059         { 0 }
1060 };
1061
1062 int do_map(int argc, char **argv)
1063 {
1064         return cmd_select(cmds, argc, argv, do_help);
1065 }