Debian Codegraph @

src/xdp.c

raw symbols SCIP
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3 * Copyright (C) 2021-2025 Linutronix GmbH
4 * Author Kurt Kanzenbach <[email protected]>
5 */
6
7 #include <errno.h>
8 #include <stdlib.h>
9 #include <unistd.h>
10
11 #include <net/if.h>
12 #include <netdb.h>
13
14 #include <arpa/inet.h>
15
16 #include <linux/if_ether.h>
17 #include <linux/if_link.h>
18 #include <linux/ip.h>
19 #include <linux/limits.h>
20 #include <linux/net_tstamp.h>
21 #include <linux/sockios.h>
22 #include <linux/udp.h>
23 #include <stdio.h>
24 #include <sys/ioctl.h>
25
26 #include "app_config.h"
27
28 #include "config.h"
29 #include "log.h"
30 #include "net.h"
31 #include "security.h"
32 #include "stat.h"
33 #include "tx_time.h"
34 #include "utils.h"
35 #include "xdp.h"
36 #include "xdp_metadata.h"
37
38 static int program_loaded;
39 static int xsks_map;
40
41 static enum xdp_attach_mode xdp_flags(bool skb_mode)
42 {
43 return skb_mode ? XDP_MODE_SKB : XDP_MODE_NATIVE;
44 }
45
46 static void xdp_set_prog_bind_flags(struct bpf_object *obj, unsigned int if_index)
47 {
48 #ifdef RX_TIMESTAMP
49 struct bpf_program *bpf_prog = bpf_object__find_program_by_name(obj, "xdp_sock_prog");
50
51 bpf_program__set_ifindex(bpf_prog, if_index);
52 bpf_program__set_flags(bpf_prog, BPF_F_XDP_DEV_BOUND_ONLY);
53 setenv("LIBXDP_SKIP_DISPATCHER", "1", 1);
54 #endif
55 }
56
57 #ifdef TX_TIMESTAMP
58 static int xdp_enable_hw_tx_timestamping(const char *if_name)
59 {
60 struct ifreq ifr = {};
61 struct hwtstamp_config hwconfig = {};
62 int socket_fd;
63
64 socket_fd = socket(PF_INET, SOCK_DGRAM, 0);
65 if (socket_fd < 0) {
66 fprintf(stderr, "XdpTxHwTs: Failed to create socket for interface %s: %s\n",
67 if_name, strerror(errno));
68 return -errno;
69 }
70
71 strncpy(ifr.ifr_name, if_name, IFNAMSIZ - 1);
72 ifr.ifr_name[IFNAMSIZ - 1] = '\0';
73 ifr.ifr_data = (char *)&hwconfig;
74
75 if (ioctl(socket_fd, SIOCGHWTSTAMP, &ifr) < 0) {
76 fprintf(stderr, "XdpTxHwTs: Failed to read HW timestamp config for %s: %s\n",
77 if_name, strerror(errno));
78 close(socket_fd);
79 return -errno;
80 }
81
82 if (hwconfig.rx_filter != HWTSTAMP_FILTER_NONE) {
83 log_message(
84 LOG_LEVEL_INFO,
85 "XdpTxHwTs: ptp4l or another service already configured RX HW timestamping "
86 "on %s — keeping existing RX settings\n",
87 if_name);
88 }
89
90 if (hwconfig.tx_type == HWTSTAMP_TX_ON) {
91 log_message(
92 LOG_LEVEL_INFO,
93 "XdpTxHwTs: TX HW timestamping already enabled on %s — skipping reapply\n",
94 if_name);
95 close(socket_fd);
96 return 0;
97 }
98
99 /* Only change TX type, keep RX settings */
100 hwconfig.tx_type = HWTSTAMP_TX_ON;
101 ifr.ifr_data = (char *)&hwconfig;
102
103 if (ioctl(socket_fd, SIOCSHWTSTAMP, &ifr) < 0) {
104 if (errno == EINVAL || errno == EOPNOTSUPP) {
105 fprintf(stderr,
106 "XdpTxHwTs: HW timestamping not supported by driver on %s\n",
107 if_name);
108 } else {
109 fprintf(stderr,
110 "XdpTxHwTs: Failed to enable HW TX timestamping on %s: %s\n",
111 if_name, strerror(errno));
112 }
113 close(socket_fd);
114 return -errno;
115 }
116
117 log_message(
118 LOG_LEVEL_INFO,
119 "XdpTxHwTs: HW TX timestamping enabled for interface %s (RX config preserved)\n",
120 if_name);
121 close(socket_fd);
122 return 0;
123 }
124
125 static void xdp_process_tx_timestamp(struct xdp_socket *xsk, uint32_t idx_cq)
126 {
127 struct round_trip_context *rtt = xsk->tx_hwts.rtt;
128 uint64_t addr = *xsk_ring_cons__comp_addr(&xsk->umem.cq, idx_cq);
129 unsigned char *data = xsk_umem__get_data(xsk->umem.buffer, addr);
130 struct xsk_tx_metadata *meta =
131 (struct xsk_tx_metadata *)(data - sizeof(struct xsk_tx_metadata));
132
133 log_message(LOG_LEVEL_DEBUG,
134 "XdpTxHwTs CQ[%u]: addr=0x%llx, flags=0x%llx, ts=%llu, seq_lagged=%llu\n",
135 idx_cq, (unsigned long long)addr, (unsigned long long)meta->flags,
136 (unsigned long long)meta->completion.tx_timestamp,
137 (unsigned long long)xsk->tx_hwts.seq_lagged);
138
139 if (meta->flags & XDP_TXMD_FLAGS_TIMESTAMP) {
140 /* Determine frame type from the round trip context */
141 enum stat_frame_type frame_type = (enum stat_frame_type)(rtt - round_trip_contexts);
142
143 /* Use seq_lagged for now, but only process if HW timestamp is valid */
144 uint64_t seq = xsk->tx_hwts.seq_lagged;
145 size_t idx = seq % rtt->backlog_len;
146
147 /* Continue only if both HW and SW timestamps are valid */
148 if (meta->completion.tx_timestamp > 0 && rtt->backlog[idx].sw_ts > 0) {
149 rtt->backlog[idx].hw_ts = meta->completion.tx_timestamp;
150
151 /* Increment TX HW timestamp count for this cycle */
152 xsk->tx_hwts.count++;
153
154 stat_frame_sent_latency(frame_type, seq);
155
156 /* Handle timestamp processing based on frames per cycle */
157 if (xsk->tx_hwts.frames_per_cycle == 1) {
158 /*
159 * Single frame case: measure only ProcFirst (since first == last)
160 */
161 if (log_stat_user_selected == LOG_TX_TIMESTAMPS &&
162 config_have_rx_timestamp() &&
163 meta->completion.tx_timestamp > rtt->backlog[idx].sw_ts) {
164 stat_proc_first_latency(frame_type, seq,
165 meta->completion.tx_timestamp);
166 }
167 /* Reset TX HW timestamp count for next cycle */
168 xsk->tx_hwts.count = 0;
169 } else {
170 /*
171 * Multiple frames case: handle first and last separately.
172 * First timestamp completion corresponds to the first
173 * packet (ProcFirst).
174 */
175 if (xsk->tx_hwts.count == 1) {
176 /*
177 * Calculate ProcFirst latency (1st RX HW to 1st TX HW) only
178 * for mirror mode and valid HW timestamp.
179 */
180 if (log_stat_user_selected == LOG_TX_TIMESTAMPS &&
181 config_have_rx_timestamp() &&
182 meta->completion.tx_timestamp >
183 rtt->backlog[idx].sw_ts) {
184 stat_proc_first_latency(
185 frame_type, seq,
186 meta->completion.tx_timestamp);
187 }
188 }
189 /* Second timestamp completion corresponds to the last packet
190 (ProcBatch) */
191 else if (xsk->tx_hwts.count == 2) {
192 /*
193 * We timestamp two packets per cycle: first (i==0)
194 * and last (i==num_frames-1). Therefore,
195 * tx_hwts.count == 2 always refers to the last packet,
196 * regardless of the number of frames per cycle.
197 *
198 * Calculate ProcBatch latency (1st RX HW to last TX HW)
199 * for mirror mode and valid HW timestamp.
200 */
201 if (log_stat_user_selected == LOG_TX_TIMESTAMPS &&
202 config_have_rx_timestamp() &&
203 meta->completion.tx_timestamp >
204 rtt->backlog[idx].sw_ts) {
205 stat_proc_batch_latency(
206 frame_type, seq,
207 meta->completion.tx_timestamp);
208 }
209
210 /* Reset TX HW timestamp count for next cycle */
211 xsk->tx_hwts.count = 0;
212 }
213 }
214 } else {
215 log_message(LOG_LEVEL_DEBUG,
216 "XdpTxHwTs: Invalid timestamps for seq=%llu (HW=%llu, "
217 "SW=%llu), skipping\n",
218 (unsigned long long)seq,
219 (unsigned long long)meta->completion.tx_timestamp,
220 (unsigned long long)rtt->backlog[idx].sw_ts);
221 }
222 } else {
223 uint64_t seq = xsk->tx_hwts.seq_lagged;
224 size_t idx = seq % rtt->backlog_len;
225
226 log_message(LOG_LEVEL_WARNING,
227 "XDP TX HW timestamp missing for expected seq %" PRIu64 ", idx=%zu\n",
228 seq, idx);
229 }
230 }
231 #endif
232
233 static int xdp_load_program(struct xdp_socket *xsk, const char *interface, const char *xdp_program,
234 int skb_mode)
235 {
236 struct xdp_program *prog;
237 struct bpf_object *obj;
238 unsigned int if_index;
239 struct bpf_map *map;
240 int ret;
241
242 if (!xdp_program) {
243 fprintf(stderr, "No XDP program specified!\n");
244 fprintf(stderr, "Have a look at the example configurations.\n");
245 return -EINVAL;
246 }
247
248 /*
249 * The eBPF program for this application instance needs to be attached to the network
250 * interface only once.
251 *
252 * When multiple instances are executed in parallel, xdp_program__attach() will try to
253 * automatically attach the new eBPF program to the existing ones by utilizing the libxdp
254 * dispatcher master program. Therefore, all applications have to use libxdp and specify
255 * their metadata e.g., priority accordingly.
256 */
257 if (program_loaded)
258 return 0;
259
260 if_index = if_nametoindex(interface);
261 if (!if_index) {
262 fprintf(stderr, "if_nametoindex() failed\n");
263 return -EINVAL;
264 }
265
266 prog = xdp_program__open_file(xdp_program, "xdp_sock", NULL);
267 ret = libxdp_get_error(prog);
268 if (ret) {
269 char tmp[PATH_MAX];
270
271 /* Try to load the XDP program from data directory instead */
272 snprintf(tmp, sizeof(tmp), "%s/%s", INSTALL_EBPF_DIR, xdp_program);
273 prog = xdp_program__open_file(tmp, "xdp_sock", NULL);
274 ret = libxdp_get_error(prog);
275 if (ret) {
276 fprintf(stderr, "xdp_program__open_file() failed\n");
277 return -EINVAL;
278 }
279 }
280
281 obj = xdp_program__bpf_obj(prog);
282 if (config_have_rx_timestamp())
283 xdp_set_prog_bind_flags(obj, if_index);
284
285 ret = xdp_program__attach(prog, if_index, xdp_flags(skb_mode), 0);
286 if (ret) {
287 fprintf(stderr, "xdp_program__attach() failed\n");
288 return -EINVAL;
289 }
290
291 /* Locate xsks_map for AF_XDP socket code */
292 map = bpf_object__find_map_by_name(obj, "xsks_map");
293 xsks_map = bpf_map__fd(map);
294 if (xsks_map < 0) {
295 fprintf(stderr, "No xsks_map found!\n");
296 return -EINVAL;
297 }
298
299 program_loaded = 1;
300 xsk->prog = prog;
301
302 return 0;
303 }
304
305 static int xdp_configure_socket_options(struct xdp_socket *xsk, bool busy_poll_mode)
306 {
307 int ret = -EINVAL;
308
309 if (!busy_poll_mode)
310 return 0;
311
312 #if defined(HAVE_SO_BUSY_POLL) && defined(HAVE_SO_PREFER_BUSY_POLL) && \
313 defined(HAVE_SO_BUSY_POLL_BUDGET)
314 int opt;
315
316 /* busy poll enable */
317 opt = 1;
318 ret = setsockopt(xsk_socket__fd(xsk->xsk), SOL_SOCKET, SO_PREFER_BUSY_POLL, (void *)&opt,
319 sizeof(opt));
320 if (ret) {
321 perror("setsockopt() failed");
322 return ret;
323 }
324
325 /* poll for 20us if socket not ready */
326 opt = 20;
327 ret = setsockopt(xsk_socket__fd(xsk->xsk), SOL_SOCKET, SO_BUSY_POLL, (void *)&opt,
328 sizeof(opt));
329 if (ret) {
330 perror("setsockopt() failed");
331 return ret;
332 }
333
334 /* send/recv XDP_BATCH_SIZE packets at most */
335 opt = XDP_BATCH_SIZE;
336 ret = setsockopt(xsk_socket__fd(xsk->xsk), SOL_SOCKET, SO_BUSY_POLL_BUDGET, (void *)&opt,
337 sizeof(opt));
338 if (ret) {
339 perror("setsockopt() failed");
340 return ret;
341 }
342
343 xsk->busy_poll_mode = true;
344 #endif
345
346 return ret;
347 }
348
349 static int xdp_umem_create(struct xdp_socket *xsk, bool tx_time_mode, bool tx_hwtstamp_mode)
350 {
351 void *buffer = NULL;
352 int ret;
353
354 /* Allocate user space memory for xdp frames */
355 ret = posix_memalign(&buffer, sysconf(_SC_PAGE_SIZE), XDP_NUM_FRAMES * XDP_FRAME_SIZE);
356 if (ret) {
357 fprintf(stderr, "posix_memalign() failed\n");
358 return -ENOMEM;
359 }
360 memset(buffer, '\0', XDP_NUM_FRAMES * XDP_FRAME_SIZE);
361
362 /*
363 * libxdp >= 1.5.0 supports Tx metadata via xsk_umem__create_opts().
364 * Enable metadata if either tx_time_mode or tx_hwtstamp_mode is true.
365 */
366 #if defined(HAVE_XDP_TX_TIME) || defined(TX_TIMESTAMP)
367 bool use_tx_metadata = tx_time_mode || tx_hwtstamp_mode;
368
369 DECLARE_LIBXDP_OPTS(
370 xsk_umem_opts, cfg, .size = XDP_NUM_FRAMES * XDP_FRAME_SIZE,
371 .fill_size = XSK_RING_PROD__DEFAULT_NUM_DESCS,
372 .comp_size = XSK_RING_CONS__DEFAULT_NUM_DESCS, .frame_size = XDP_FRAME_SIZE,
373 .frame_headroom = XSK_UMEM__DEFAULT_FRAME_HEADROOM,
374 /* struct xsk_tx_metadata contains all AF_XDP offload requests. */
375 .flags = use_tx_metadata ? XDP_UMEM_TX_METADATA_LEN : 0,
376 .tx_metadata_len = use_tx_metadata ? sizeof(struct xsk_tx_metadata) : 0, );
377
378 xsk->umem.umem = xsk_umem__create_opts(buffer, &xsk->umem.fq, &xsk->umem.cq, &cfg);
379 if (!xsk->umem.umem) {
380 ret = -errno;
381 fprintf(stderr, "xsk_umem__create_opts() failed: %s\n", strerror(-ret));
382 goto err;
383 }
384 #else
385 struct xsk_umem_config cfg = {
386 .fill_size = XSK_RING_PROD__DEFAULT_NUM_DESCS,
387 .comp_size = XSK_RING_CONS__DEFAULT_NUM_DESCS,
388 .frame_size = XDP_FRAME_SIZE,
389 .frame_headroom = XSK_UMEM__DEFAULT_FRAME_HEADROOM,
390 .flags = 0,
391 };
392
393 ret = xsk_umem__create(&xsk->umem.umem, buffer, XDP_NUM_FRAMES * XDP_FRAME_SIZE,
394 &xsk->umem.fq, &xsk->umem.cq, &cfg);
395 if (ret) {
396 fprintf(stderr, "xsk_umem__create() failed: %s\n", strerror(-ret));
397 goto err;
398 }
399 #endif
400
401 xsk->umem.buffer = buffer;
402 xsk->tx_time_mode = tx_time_mode;
403 xsk->tx_hwtstamp_mode = tx_hwtstamp_mode;
404 return 0;
405
406 err:
407 free(buffer);
408 return ret;
409 }
410
411 struct xdp_socket *xdp_open_socket(const char *interface, const char *xdp_program, int queue,
412 bool skb_mode, bool zero_copy_mode, bool wakeup_mode,
413 bool busy_poll_mode, bool tx_time_mode, bool tx_hwtstamp_mode)
414 {
415 struct xsk_socket_config xsk_cfg;
416 struct xdp_socket *xsk;
417 int ret, i, fd;
418 uint32_t idx;
419
420 xsk = calloc(1, sizeof(*xsk));
421 if (!xsk)
422 return NULL;
423
424 ret = xdp_load_program(xsk, interface, xdp_program, skb_mode);
425 if (ret)
426 goto err;
427
428 #ifdef TX_TIMESTAMP
429 /* Enable HW TX timestamping if requested */
430 if (tx_hwtstamp_mode) {
431 ret = xdp_enable_hw_tx_timestamping(interface);
432 if (ret) {
433 fprintf(stderr, "Failed to enable HW TX timestamping on %s!\n", interface);
434 goto err;
435 }
436 }
437 #endif
438
439 /* Allocate and register AF_XDP umem area */
440 ret = xdp_umem_create(xsk, tx_time_mode, tx_hwtstamp_mode);
441 if (ret) {
442 fprintf(stderr, "Failed to allocate AF_XDP UMEM area!\n");
443 goto err2;
444 }
445
446 /* Add some buffers */
447 ret = xsk_ring_prod__reserve(&xsk->umem.fq, XSK_RING_PROD__DEFAULT_NUM_DESCS, &idx);
448 if (ret != XSK_RING_PROD__DEFAULT_NUM_DESCS) {
449 fprintf(stderr, "xsk_ring_prod__reserve() failed\n");
450 goto err3;
451 }
452
453 for (i = 0; i < XSK_RING_PROD__DEFAULT_NUM_DESCS; i++) {
454 *xsk_ring_prod__fill_addr(&xsk->umem.fq, idx) = i * XDP_FRAME_SIZE;
455
456 /* Reserve space for Tx Meta Data on retransmit. */
457 #if defined(HAVE_XDP_TX_TIME) || defined(TX_TIMESTAMP)
458 if (tx_time_mode || tx_hwtstamp_mode)
459 *xsk_ring_prod__fill_addr(&xsk->umem.fq, idx) +=
460 sizeof(struct xsk_tx_metadata);
461 #endif
462 idx++;
463 }
464
465 xsk_ring_prod__submit(&xsk->umem.fq, XSK_RING_PROD__DEFAULT_NUM_DESCS);
466
467 /* Create XDP socket */
468 xsk_cfg.rx_size = XSK_RING_CONS__DEFAULT_NUM_DESCS;
469 xsk_cfg.tx_size = XSK_RING_PROD__DEFAULT_NUM_DESCS;
470 xsk_cfg.libbpf_flags = XSK_LIBBPF_FLAGS__INHIBIT_PROG_LOAD;
471 xsk_cfg.xdp_flags = skb_mode ? XDP_FLAGS_SKB_MODE : XDP_FLAGS_DRV_MODE;
472 xsk_cfg.bind_flags = wakeup_mode ? XDP_USE_NEED_WAKEUP : 0;
473 xsk_cfg.bind_flags |= zero_copy_mode ? XDP_ZEROCOPY : XDP_COPY;
474
475 ret = xsk_socket__create(&xsk->xsk, interface, queue, xsk->umem.umem, &xsk->rx, &xsk->tx,
476 &xsk_cfg);
477 if (ret) {
478 fprintf(stderr, "xsk_socket__create() failed: %s\n", strerror(-ret));
479 goto err3;
480 }
481
482 /* Add xsk into xsks_map */
483 fd = xsk_socket__fd(xsk->xsk);
484 ret = bpf_map_update_elem(xsks_map, &queue, &fd, 0);
485 if (ret) {
486 fprintf(stderr, "bpf_map_update_elem() failed: %s\n", strerror(-ret));
487 goto err4;
488 }
489
490 /* Set socket options */
491 ret = xdp_configure_socket_options(xsk, busy_poll_mode);
492 if (ret) {
493 fprintf(stderr, "Failed to configure busy polling!\n");
494 goto err4;
495 }
496
497 return xsk;
498
499 err4:
500 xsk_socket__delete(xsk->xsk);
501 err3:
502 free(xsk->umem.buffer);
503 xsk_umem__delete(xsk->umem.umem);
504 err2:
505 err:
506 free(xsk);
507 return NULL;
508 }
509
510 void xdp_close_socket(struct xdp_socket *xsk, const char *interface, bool skb_mode)
511 {
512 unsigned int if_index;
513
514 if (!xsk)
515 return;
516
517 xsk_socket__delete(xsk->xsk);
518 xsk_umem__delete(xsk->umem.umem);
519
520 if_index = if_nametoindex(interface);
521 if (!if_index) {
522 fprintf(stderr, "if_nametoindex() failed\n");
523 return;
524 }
525
526 if (xsk->prog) {
527 xdp_program__detach(xsk->prog, if_index, xdp_flags(skb_mode), 0);
528 xdp_program__close(xsk->prog);
529 program_loaded = 0;
530 }
531
532 free(xsk->umem.buffer);
533 free(xsk);
534 }
535
536 void xdp_complete_tx_only(struct xdp_socket *xsk)
537 {
538 size_t ndescs = xsk->outstanding_tx;
539 unsigned int received;
540 uint32_t idx_cq = 0;
541
542 if (!xsk->outstanding_tx)
543 return;
544
545 /* Kick kernel to Tx packets */
546 if (xsk->busy_poll_mode || xsk_ring_prod__needs_wakeup(&xsk->tx))
547 sendto(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, 0);
548
549 /* Buffers transmitted? */
550 received = xsk_ring_cons__peek(&xsk->umem.cq, ndescs, &idx_cq);
551 if (!received)
552 return;
553
554 #ifdef TX_TIMESTAMP
555 if (xsk->tx_hwtstamp_mode) {
556 xdp_process_tx_timestamp(xsk, idx_cq);
557 }
558 #endif
559
560 xsk_ring_cons__release(&xsk->umem.cq, received);
561 xsk->outstanding_tx -= received;
562 }
563
564 void xdp_complete_tx(struct xdp_socket *xsk)
565 {
566 size_t ndescs = xsk->outstanding_tx;
567 uint32_t idx_cq = 0, idx_fq = 0;
568 unsigned int received;
569 int ret, i;
570
571 if (!xsk->outstanding_tx)
572 return;
573
574 /* Kick kernel to Tx packets */
575 if (xsk->busy_poll_mode || xsk_ring_prod__needs_wakeup(&xsk->tx))
576 sendto(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, 0);
577
578 /* Buffers transmitted? */
579 received = xsk_ring_cons__peek(&xsk->umem.cq, ndescs, &idx_cq);
580 if (!received)
581 return;
582
583 #ifdef TX_TIMESTAMP
584 if (xsk->tx_hwtstamp_mode) {
585 /* Process all TX completions */
586 for (i = 0; i < received; ++i) {
587 uint64_t addr = *xsk_ring_cons__comp_addr(&xsk->umem.cq, idx_cq + i);
588 unsigned char *data = xsk_umem__get_data(xsk->umem.buffer, addr);
589 struct xsk_tx_metadata *meta =
590 (struct xsk_tx_metadata *)(data - sizeof(struct xsk_tx_metadata));
591
592 /* Only process completions that have timestamp metadata */
593 if (meta->flags & XDP_TXMD_FLAGS_TIMESTAMP) {
594 xdp_process_tx_timestamp(xsk, idx_cq + i);
595 }
596 }
597 }
598 #endif
599
600 /* Re-add for Rx */
601 ret = xsk_ring_prod__reserve(&xsk->umem.fq, received, &idx_fq);
602 while (ret != received) {
603 if (ret < 0)
604 log_message(LOG_LEVEL_ERROR, "XdpTx: xsk_ring_prod__reserve() failed\n");
605
606 if (xsk->busy_poll_mode || xsk_ring_prod__needs_wakeup(&xsk->umem.fq))
607 recvfrom(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, NULL);
608 ret = xsk_ring_prod__reserve(&xsk->umem.fq, received, &idx_fq);
609 }
610
611 /*
612 * Use explicit indexing to avoid re-reading comp[0], which was already accessed for HW
613 * timestamping
614 */
615 for (i = 0; i < received; ++i) {
616 uint64_t addr = *xsk_ring_cons__comp_addr(&xsk->umem.cq, idx_cq + i);
617 *xsk_ring_prod__fill_addr(&xsk->umem.fq, idx_fq + i) = addr;
618 }
619
620 xsk_ring_prod__submit(&xsk->umem.fq, received);
621 xsk_ring_cons__release(&xsk->umem.cq, received);
622 xsk->outstanding_tx -= received;
623 }
624
625 static unsigned char *xdp_prepare_tx_desc(struct xdp_socket *xsk, struct xdp_desc *tx_desc,
626 const struct xdp_tx_time *tx_time, int i, int num_frames,
627 bool tx)
628 {
629 unsigned char *data;
630
631 #if defined(HAVE_XDP_TX_TIME) || defined(TX_TIMESTAMP)
632 /* Add Tx Time or Tx HW Timestamp request if supported */
633 if (xsk->tx_time_mode || xsk->tx_hwtstamp_mode) {
634 struct xsk_tx_metadata *meta;
635
636 /* Reserve meta data space for Tx Time and Tx HW Timestamp */
637 if (tx)
638 tx_desc->addr += sizeof(struct xsk_tx_metadata);
639
640 data = xsk_umem__get_data(xsk->umem.buffer, tx_desc->addr);
641 meta = (struct xsk_tx_metadata *)(data - sizeof(struct xsk_tx_metadata));
642
643 /* Zero out entire metadata struct before filling */
644 memset(meta, 0, sizeof(*meta));
645
646 /* Set flags and request fields */
647 meta->flags = 0;
648 #ifdef HAVE_XDP_TX_TIME
649 if (xsk->tx_time_mode) {
650 uint64_t time;
651
652 meta->flags |= XDP_TXMD_FLAGS_LAUNCH_TIME;
653 time = tx_time_get_frame_tx_time(
654 tx_time->sequence_counter_begin + i, tx_time->duration,
655 tx_time->num_frames_per_cycle, tx_time->tx_time_offset,
656 tx_time->traffic_class);
657 meta->request.launch_time = time;
658 }
659 #endif
660 #ifdef TX_TIMESTAMP
661 /* Timestamp first packet and last packet per cycle */
662 if (xsk->tx_hwtstamp_mode && (i == 0 || i == num_frames - 1)) {
663 meta->flags |= XDP_TXMD_FLAGS_TIMESTAMP;
664 /* Initialize TX HW timestamp */
665 meta->completion.tx_timestamp = 0;
666 }
667 #endif
668 tx_desc->options |= XDP_TX_METADATA;
669 } else {
670 data = xsk_umem__get_data(xsk->umem.buffer, tx_desc->addr);
671 }
672 #else
673 data = xsk_umem__get_data(xsk->umem.buffer, tx_desc->addr);
674 #endif
675
676 return data;
677 }
678
679 void xdp_gen_and_send_frames(struct xdp_socket *xsk, const struct xdp_gen_config *xdp)
680 {
681 struct timespec tx_time = {};
682 uint32_t idx = 0;
683 size_t i;
684
685 if (xdp->num_frames_per_cycle == 0)
686 return;
687
688 if (xsk_ring_prod__reserve(&xsk->tx, xdp->num_frames_per_cycle, &idx) <
689 xdp->num_frames_per_cycle) {
690 /*
691 * This should never happen. It means there're no more Tx descriptors available to
692 * transmit the frames from this very period. The only thing we can do here, is to
693 * come back later and hope the hardware did transmit some frames.
694 */
695 log_message(LOG_LEVEL_ERROR, "XdpTx: Cannot allocate Tx descriptors!\n");
696 xdp_complete_tx_only(xsk);
697 return;
698 }
699
700 clock_gettime(app_config.application_clock_id, &tx_time);
701
702 for (i = 0; i < xdp->num_frames_per_cycle; ++i) {
703 struct xdp_desc *tx_desc = xsk_ring_prod__tx_desc(&xsk->tx, idx + i);
704 struct prepare_frame_config frame_config;
705 struct vlan_ethernet_header *eth;
706 unsigned char *data;
707 int ret;
708
709 tx_desc->addr = *xdp->frame_number * XDP_FRAME_SIZE;
710 tx_desc->len = xdp->frame_length;
711
712 *xdp->frame_number += 1;
713 *xdp->frame_number = (*xdp->frame_number % XSK_RING_CONS__DEFAULT_NUM_DESCS) +
714 XSK_RING_PROD__DEFAULT_NUM_DESCS;
715
716 /* Get frame and prepare it */
717 data = xdp_prepare_tx_desc(xsk, tx_desc, xdp->tx_time, i, xdp->num_frames_per_cycle,
718 true);
719
720 frame_config.mode = xdp->mode;
721 frame_config.security_context = xdp->security_context;
722 frame_config.iv_prefix = xdp->iv_prefix;
723 frame_config.payload_pattern = xdp->payload_pattern;
724 frame_config.payload_pattern_length = xdp->payload_pattern_length;
725 frame_config.frame_data = data;
726 frame_config.frame_length = xdp->frame_length;
727 frame_config.num_frames_per_cycle = xdp->num_frames_per_cycle;
728 frame_config.sequence_counter = xdp->sequence_counter_begin + i;
729 frame_config.tx_timestamp = ts_to_ns(&tx_time);
730 frame_config.meta_data_offset = xdp->meta_data_offset;
731
732 ret = prepare_frame_for_tx(&frame_config);
733 if (ret)
734 log_message(LOG_LEVEL_ERROR, "XdpTx: Failed to prepare frame for Tx!\n");
735
736 /*
737 * In debug monitor mode the first frame of each burst should have a different
738 * DA. This way, the oscilloscope can trigger for it.
739 */
740 if (app_config.debug_monitor_mode && i == 0) {
741 eth = (struct vlan_ethernet_header *)data;
742 memcpy(eth->destination, app_config.debug_monitor_destination, ETH_ALEN);
743 }
744 }
745
746 xsk_ring_prod__submit(&xsk->tx, xdp->num_frames_per_cycle);
747 xsk->outstanding_tx += xdp->num_frames_per_cycle;
748
749 /* Kick Tx */
750 xdp_complete_tx_only(xsk);
751
752 /* Log SW timestamps */
753 #ifdef TX_TIMESTAMP
754 if (xsk->tx_hwtstamp_mode) {
755 /*
756 * When TX HW timestamping is enabled, record SW timestamp once per cycle
757 * (for the first frame in this cycle) and count all frames
758 */
759 stat_frames_sent_batch(xdp->frame_type, xdp->sequence_counter_begin,
760 xdp->num_frames_per_cycle);
761
762 /* Update the sequence number for expected HW timestamp in next cycle */
763 xsk->tx_hwts.seq_lagged = xdp->sequence_counter_begin;
764 return;
765 }
766 #endif
767 /* Normal mode: record SW timestamp for each frame */
768 for (i = 0; i < xdp->num_frames_per_cycle; ++i)
769 stat_frame_sent(xdp->frame_type, xdp->sequence_counter_begin + i);
770 }
771
772 void xdp_get_timestamp_metadata(void *data, uint64_t *rx_hw_ts, uint64_t *rx_sw_ts)
773 {
774 struct xdp_meta *meta;
775
776 meta = data - sizeof(*meta);
777
778 if (meta->hint_valid & XDP_META_FIELD_TS) {
779 *rx_hw_ts = meta->rx_hw_timestamp;
780 *rx_sw_ts = meta->rx_sw_timestamp;
781 } else {
782 *rx_hw_ts = 0;
783 *rx_sw_ts = 0;
784 }
785 }
786
787 unsigned int xdp_receive_frames(struct xdp_socket *xsk, size_t frame_length, bool mirror_enabled,
788 int (*receive_function)(void *data, unsigned char *, size_t),
789 void *data, const struct xdp_tx_time *tx_time)
790 {
791 uint32_t idx_rx = 0, idx_tx = 0, idx_fq = 0, len;
792 unsigned int received, i;
793 unsigned char *packet;
794 uint64_t addr, orig;
795 int ret;
796
797 /* Receive frames when in busy polling mode */
798 if (xsk->busy_poll_mode)
799 recvfrom(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, NULL);
800
801 /* Check for received frames */
802 received = xsk_ring_cons__peek(&xsk->rx, XDP_BATCH_SIZE, &idx_rx);
803 if (!received) {
804 if (xsk_ring_prod__needs_wakeup(&xsk->umem.fq))
805 recvfrom(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL, NULL);
806 return 0;
807 }
808
809 /*
810 * For mirror reserve space in Tx queue to re-transmit the frames. Otherwise, recycle the Rx
811 * frames immediately.
812 */
813 if (mirror_enabled) {
814 /* Reserve space in Tx ring */
815 ret = xsk_ring_prod__reserve(&xsk->tx, received, &idx_tx);
816 while (ret != received) {
817 if (ret < 0)
818 log_message(LOG_LEVEL_ERROR,
819 "XdpRx: xsk_ring_prod__reserve() failed\n");
820
821 if (xsk->busy_poll_mode || xsk_ring_prod__needs_wakeup(&xsk->tx))
822 recvfrom(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL,
823 NULL);
824 ret = xsk_ring_prod__reserve(&xsk->tx, received, &idx_tx);
825 }
826 } else {
827 /* Reserve space in fill queue */
828 ret = xsk_ring_prod__reserve(&xsk->umem.fq, received, &idx_fq);
829 while (ret != received) {
830 if (ret < 0)
831 log_message(LOG_LEVEL_ERROR,
832 "XdpRx: xsk_ring_prod__reserve() failed\n");
833
834 if (xsk->busy_poll_mode || xsk_ring_prod__needs_wakeup(&xsk->umem.fq))
835 recvfrom(xsk_socket__fd(xsk->xsk), NULL, 0, MSG_DONTWAIT, NULL,
836 NULL);
837 ret = xsk_ring_prod__reserve(&xsk->umem.fq, received, &idx_fq);
838 }
839 }
840
841 for (i = 0; i < received; ++i) {
842 /* Get the packet */
843 addr = xsk_ring_cons__rx_desc(&xsk->rx, idx_rx)->addr;
844 len = xsk_ring_cons__rx_desc(&xsk->rx, idx_rx++)->len;
845 orig = xsk_umem__extract_addr(addr);
846
847 /* Parse it */
848 addr = xsk_umem__add_offset_to_addr(addr);
849 packet = xsk_umem__get_data(xsk->umem.buffer, addr);
850 receive_function(data, packet, len);
851
852 if (mirror_enabled) {
853 struct xdp_desc *tx_desc = xsk_ring_prod__tx_desc(&xsk->tx, idx_tx++);
854
855 /* Store received frame in Tx ring */
856 tx_desc->addr = orig;
857 tx_desc->len = frame_length;
858
859 /* Prepare tx desc with Tx Time or Tx HW timestamp */
860 if (xsk->tx_time_mode || xsk->tx_hwtstamp_mode)
861 xdp_prepare_tx_desc(xsk, tx_desc, tx_time, i, received, false);
862 } else {
863 /* Move buffer back to fill queue */
864 *xsk_ring_prod__fill_addr(&xsk->umem.fq, idx_fq++) = orig;
865 }
866 }
867
868 if (mirror_enabled) {
869 xsk_ring_cons__release(&xsk->rx, received);
870 } else {
871 xsk_ring_prod__submit(&xsk->umem.fq, received);
872 xsk_ring_cons__release(&xsk->rx, received);
873 }
874
875 return received;
876 }