xref: /openbmc/linux/tools/net/ynl/samples/netdev.c (revision 6db6b729)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <stdio.h>
3 #include <string.h>
4 
5 #include <ynl.h>
6 
7 #include <net/if.h>
8 
9 #include "netdev-user.h"
10 
11 /* netdev genetlink family code sample
12  * This sample shows off basics of the netdev family but also notification
13  * handling, hence the somewhat odd UI. We subscribe to notifications first
14  * then wait for ifc selection, so the socket may already accumulate
15  * notifications as we wait. This allows us to test that YNL can handle
16  * requests and notifications getting interleaved.
17  */
18 
19 static void netdev_print_device(struct netdev_dev_get_rsp *d, unsigned int op)
20 {
21 	char ifname[IF_NAMESIZE];
22 	const char *name;
23 
24 	if (!d->_present.ifindex)
25 		return;
26 
27 	name = if_indextoname(d->ifindex, ifname);
28 	if (name)
29 		printf("%8s", name);
30 	printf("[%d]\t", d->ifindex);
31 
32 	if (!d->_present.xdp_features)
33 		return;
34 
35 	printf("%llx:", d->xdp_features);
36 	for (int i = 0; d->xdp_features > 1U << i; i++) {
37 		if (d->xdp_features & (1U << i))
38 			printf(" %s", netdev_xdp_act_str(1 << i));
39 	}
40 
41 	printf(" xdp-zc-max-segs=%u", d->xdp_zc_max_segs);
42 
43 	name = netdev_op_str(op);
44 	if (name)
45 		printf(" (ntf: %s)", name);
46 	printf("\n");
47 }
48 
49 int main(int argc, char **argv)
50 {
51 	struct netdev_dev_get_list *devs;
52 	struct ynl_ntf_base_type *ntf;
53 	struct ynl_error yerr;
54 	struct ynl_sock *ys;
55 	int ifindex = 0;
56 
57 	if (argc > 1)
58 		ifindex = strtol(argv[1], NULL, 0);
59 
60 	ys = ynl_sock_create(&ynl_netdev_family, &yerr);
61 	if (!ys) {
62 		fprintf(stderr, "YNL: %s\n", yerr.msg);
63 		return 1;
64 	}
65 
66 	if (ynl_subscribe(ys, "mgmt"))
67 		goto err_close;
68 
69 	printf("Select ifc ($ifindex; or 0 = dump; or -2 ntf check): ");
70 	scanf("%d", &ifindex);
71 
72 	if (ifindex > 0) {
73 		struct netdev_dev_get_req *req;
74 		struct netdev_dev_get_rsp *d;
75 
76 		req = netdev_dev_get_req_alloc();
77 		netdev_dev_get_req_set_ifindex(req, ifindex);
78 
79 		d = netdev_dev_get(ys, req);
80 		netdev_dev_get_req_free(req);
81 		if (!d)
82 			goto err_close;
83 
84 		netdev_print_device(d, 0);
85 		netdev_dev_get_rsp_free(d);
86 	} else if (!ifindex) {
87 		devs = netdev_dev_get_dump(ys);
88 		if (!devs)
89 			goto err_close;
90 
91 		ynl_dump_foreach(devs, d)
92 			netdev_print_device(d, 0);
93 		netdev_dev_get_list_free(devs);
94 	} else if (ifindex == -2) {
95 		ynl_ntf_check(ys);
96 	}
97 	while ((ntf = ynl_ntf_dequeue(ys))) {
98 		netdev_print_device((struct netdev_dev_get_rsp *)&ntf->data,
99 				    ntf->cmd);
100 		ynl_ntf_free(ntf);
101 	}
102 
103 	ynl_sock_destroy(ys);
104 	return 0;
105 
106 err_close:
107 	fprintf(stderr, "YNL: %s\n", ys->err.msg);
108 	ynl_sock_destroy(ys);
109 	return 2;
110 }
111