LCOV - code coverage report
Current view: top level - disco/net/xdp - fd_xdp_tile.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 337 964 35.0 %
Date: 2026-07-11 05:27:41 Functions: 18 66 27.3 %

          Line data    Source code
       1             : /* The xdp tile translates between AF_XDP and fd_tango
       2             :    traffic.  It is responsible for setting up the XDP and
       3             :    XSK socket configuration. */
       4             : 
       5             : #include "../fd_net_tile.h"
       6             : 
       7             : #include <errno.h>
       8             : #include <fcntl.h>
       9             : #include <net/if.h>
      10             : #include <netinet/in.h>
      11             : #include <sys/socket.h> /* MSG_DONTWAIT needed before importing the net seccomp filter */
      12             : #include <linux/if_xdp.h>
      13             : 
      14             : #include "../fd_net_common.h"
      15             : #include "../../metrics/fd_metrics.h"
      16             : #include "../../netlink/fd_netlink_tile.h" /* neigh4_solicit */
      17             : #include "../../topo/fd_topo.h"
      18             : 
      19             : #include "../../../waltz/ip/fd_fib4.h"
      20             : #include "../../../waltz/neigh/fd_neigh4_map.h"
      21             : #include "../../../waltz/mib/fd_netdev_tbl.h"
      22             : #include "../../../waltz/xdp/fd_xdp_redirect_user.h" /* fd_xsk_activate */
      23             : #include "../../../waltz/xdp/fd_xsk.h"
      24             : #include "../../../util/log/fd_dtrace.h"
      25             : #include "../../../util/net/fd_eth.h"
      26             : #include "../../../util/net/fd_ip4.h"
      27             : #include "../../../util/net/fd_gre.h"
      28             : #include "../../../util/pod/fd_pod_format.h"
      29             : 
      30             : #include <unistd.h>
      31             : #include <linux/if.h> /* struct ifreq */
      32             : #include <sys/ioctl.h>
      33             : #include <linux/if_arp.h>
      34             : 
      35             : #include "generated/fd_xdp_tile_seccomp.h"
      36             : 
      37             : /* MAX_NET_INS controls the max number of TX links that a net tile can
      38             :    serve. */
      39             : 
      40             : #define MAX_NET_INS (32UL)
      41             : 
      42             : /* FD_XDP_STATS_INTERVAL_NS controls the XDP stats refresh interval.
      43             :    This should be lower than the interval at which the metrics tile
      44             :    collects metrics. */
      45             : 
      46           0 : #define FD_XDP_STATS_INTERVAL_NS (11e6) /* 11ms */
      47             : 
      48             : /* XSK_IDX_{MAIN,LO} are the hardcoded XSK indices in ctx->xsk[ ... ].
      49             :    Only net tile 0 has XSK_IDX_LO, all net tiles have XSK_IDX_MAIN. */
      50             : 
      51          30 : #define XSK_IDX_MAIN 0
      52          18 : #define XSK_IDX_LO   1
      53             : 
      54             : /* XSK 'busy_poll_usecs' value (max amount of time
      55             :    spent spinning in a NAPI poll before returning back to
      56             :    userspace if the processing budget hasn't already ran out).
      57             : 
      58             :    64us chosen based on napibusy configuration tested and
      59             :    shown in https://lwn.net/Articles/997491/ Linux patch
      60             :    cover letter.  Chosen over fullbusy since for Firedancer
      61             :    the values of fullbusy are unnecessarily high and could
      62             :    cause some extra latency to regular non-Firedancer traffic.*/
      63           0 : #define PREFBUSY_TIME_BUDGET_MICROS (64L)
      64             : 
      65             : /* PREFBUSY_RX_BUDGET is the NAPI RX processing budget (max num RX
      66             :    packets that the NIC driver can move from the hw rings into the
      67             :    XSK rings per poll).
      68             : 
      69             :    Default RX budget used by NIC drivers is 64, therefore
      70             :    it is safest to use 64 in prefbusy polling.  Also reduces
      71             :    TX starvation risks as the TX budget set by the NIC driver
      72             :    is also generally 64. */
      73           0 : #define PREFBUSY_RX_BUDGET (64L)
      74             : 
      75             : /* Min time between each prefbusy poll.  Necessary to avoid a no RX
      76             :    scenario livelocking TX with overly frequent sendto calls, given
      77             :    prefbusy polls whenever the RX queue is empty.
      78             : 
      79             :    Value chosen based on experimentation on ixgbe, mlx5 and i40e as well
      80             :    as on varying CPUs and clock speeds.  Too low -> lower max TX
      81             :    throughput when RX is very low.  Too high -> lower max RX and TX throughput. */
      82           0 : #define PREFBUSY_MIN_INTERVAL_NS (5e3) /* 5us */
      83             : 
      84             : /* Max time since last prefbusy poll before a prefbusy poll is
      85             :    forced (has been read that polling can sometimes resolve a stall).
      86             : 
      87             :    Exact value again not particularly important as this is just extra
      88             :    protection against stalls which have not been observed in testing but
      89             :    are still good to protect against since there is no cost to doing so.
      90             : 
      91             :    Value of 150us chosen since it is easily large enough to not interfere
      92             :    with standard prefbusy runtime unless there is a serious problem. */
      93           0 : #define PREFBUSY_STALL_TIMEOUT_NS (150e3) /* 150us */
      94             : 
      95             : /* MAX_GRE_CNT is the maximum number of GRE tunnels the XDP tile will
      96             :    monitor.  If a packet comes in with a source IP that doesn't match
      97             :    the endpoint of one of the first MAX_GRE_CNT tunnels (in the order
      98             :    the OS enumerates them), it will be dropped.  This is limited for
      99             :    performance reasons. */
     100         111 : #define MAX_GRE_CNT 4UL
     101             : 
     102             : /* fd_net_in_ctx_t contains consumer information for an incoming tango
     103             :    link.  It is used as part of the TX path. */
     104             : 
     105             : typedef struct {
     106             :   fd_wksp_t * mem;
     107             :   ulong       chunk0;
     108             :   ulong       wmark;
     109             : } fd_net_in_ctx_t;
     110             : 
     111             : /* fd_net_out_ctx_t contains publisher information for a link to a
     112             :    downstream app tile.  It is used as part of the RX path. */
     113             : 
     114             : typedef struct {
     115             :   fd_frag_meta_t * mcache;
     116             :   ulong *          sync;
     117             :   ulong            depth;
     118             :   ulong            seq;
     119             : } fd_net_out_ctx_t;
     120             : 
     121             : /* fd_net_flusher_t controls the pacing of XDP sendto calls for flushing
     122             :    TX batches.  In the 'wakeup' XDP mode, no TX occurs unless the net
     123             :    tile wakes up the kernel periodically using the sendto() syscall.
     124             :    If sendto() is called too frequently, time is wasted on context
     125             :    switches.  If sendto() is called not often enough, packets are
     126             :    delayed or dropped.  sendto() calls make almost no guarantees how
     127             :    much packets are sent out, nor do they indicate when the kernel
     128             :    finishes a wakeup call (asynchronously dispatched).  The net tile
     129             :    thus uses a myraid of flush triggers that were tested for best
     130             :    performance. */
     131             : 
     132             : struct fd_net_flusher {
     133             : 
     134             :   /* Packets that were enqueued after the last sendto() wakeup are
     135             :      considered "pending".  If there are more than pending_wmark packets
     136             :      pending, a wakeup is dispatched.  Thus, this dispatch trigger is
     137             :      proportional to packet rate, but does not trigger if I/O is seldom. */
     138             :   ulong pending_cnt;
     139             :   ulong pending_wmark;
     140             : 
     141             :   /* Sometimes, packets are not flushed out even after a sendto()
     142             :      wakeup.  This can result in the tail of a burst getting delayed or
     143             :      overrun.  If more than tail_flush_backoff ticks pass since the last
     144             :      sendto() wakeup and there are still unacknowledged packets in the
     145             :      TX ring, issues another wakeup. Only used by "softirq" poll mode. */
     146             :   long next_tail_flush_ticks;
     147             :   long tail_flush_backoff;
     148             : 
     149             :   /* When the most recent prefbusy poll was. */
     150             :   long prefbusy_last_poll_ticks;
     151             :   /* Min time between each prefbusy poll. */
     152             :   long prefbusy_min_interval_ticks;
     153             :   /* Max time since last prefbusy poll before a prefbusy poll is
     154             :      forced (has been read that polling can sometimes resolve a stall). */
     155             :   long prefbusy_stall_timeout_ticks;
     156             : };
     157             : 
     158             : typedef struct fd_net_flusher fd_net_flusher_t;
     159             : 
     160             : FD_PROTOTYPES_BEGIN
     161             : 
     162             : /* fd_net_flusher_inc marks a new packet as enqueued. */
     163             : 
     164             : static inline void
     165             : fd_net_flusher_inc( fd_net_flusher_t * flusher,
     166          18 :                     long               now ) {
     167          18 :   flusher->pending_cnt++;
     168          18 :   long next_flush = now + flusher->tail_flush_backoff;
     169          18 :   flusher->next_tail_flush_ticks = fd_long_min( flusher->next_tail_flush_ticks, next_flush );
     170          18 : }
     171             : 
     172             : /* fd_net_flusher_check returns 1 if a sendto() wakeup should be issued
     173             :    immediately.  now is a recent fd_tickcount() value.
     174             :    If tx_ring_empty==0 then the kernel is caught up with the net tile
     175             :    on the XDP TX ring.  (Otherwise, the kernel is behind the net tile) */
     176             : 
     177             : static inline int
     178             : fd_net_flusher_check( fd_net_flusher_t * flusher,
     179             :                       long               now,
     180          27 :                       int                tx_ring_empty ) {
     181          27 :   int flush_level   = flusher->pending_cnt >= flusher->pending_wmark;
     182          27 :   int flush_timeout = now >= flusher->next_tail_flush_ticks;
     183          27 :   int flush         = flush_level || flush_timeout;
     184          27 :   if( !flush ) return 0;
     185          27 :   if( FD_UNLIKELY( tx_ring_empty ) ) {
     186             :     /* Flush requested but caught up */
     187           3 :     flusher->pending_cnt           = 0UL;
     188           3 :     flusher->next_tail_flush_ticks = LONG_MAX;
     189           3 :     return 0;
     190           3 :   }
     191          24 :   return 1;
     192          27 : }
     193             : 
     194             : /* fd_net_flusher_wakeup signals a sendto() wakeup was done.  now is a
     195             :    recent fd_tickcount() value. */
     196             : 
     197             : static inline void
     198             : fd_net_flusher_wakeup( fd_net_flusher_t * flusher,
     199          24 :                        long               now ) {
     200          24 :   flusher->pending_cnt           = 0UL;
     201          24 :   flusher->next_tail_flush_ticks = now + flusher->tail_flush_backoff;
     202          24 : }
     203             : 
     204             : FD_PROTOTYPES_END
     205             : 
     206             : /* fd_net_free_ring is a FIFO queue that stores pointers to free XDP TX
     207             :    frames. */
     208             : 
     209             : struct fd_net_free_ring {
     210             :   ulong   prod;
     211             :   ulong   cons;
     212             :   ulong   depth;
     213             :   ulong * queue;
     214             : };
     215             : typedef struct fd_net_free_ring fd_net_free_ring_t;
     216             : 
     217             : typedef struct {
     218             :   /* An "XSK" is an AF_XDP socket */
     219             :   uint     xsk_cnt;
     220             :   fd_xsk_t xsk[ 2 ];
     221             :   int      prog_link_fds[ 2 ];
     222             :   uint     if_virt;
     223             : 
     224             :   /* UMEM frame region within dcache */
     225             :   void *   umem;    /* Start of UMEM */
     226             :   ulong    umem_sz; /* Size  of UMEM */
     227             : 
     228             :   /* UMEM chunk region within workspace */
     229             :   uint     umem_chunk0; /* Lowest allowed chunk number */
     230             :   uint     umem_wmark;  /* Highest allowed chunk number */
     231             : 
     232             :   /* All net tiles are subscribed to the same TX links.  (These are
     233             :      incoming links from app tiles asking the net tile to send out packets)
     234             :      The net tiles "take turns" doing TX jobs based on the L3+L4 dst hash.
     235             :      net_tile_id is the index of the current interface, net_tile_cnt is the
     236             :      total amount of interfaces. */
     237             :   uint net_tile_id;
     238             :   uint net_tile_cnt;
     239             : 
     240             :   /* Details pertaining to an inflight send op */
     241             :   struct {
     242             :     uint   xsk_idx;
     243             :     void * frame;
     244             :     uchar  mac_addrs[12];     /* First 12 bytes of Ethernet header */
     245             :     uint   src_ip;            /* src_ip in net order */
     246             : 
     247             :     uint   use_gre;           /* The tx packet will be GRE-encapsulated */
     248             :     uint   gre_outer_src_ip;  /* For GRE: Outer iphdr's src_ip in net order */
     249             :     uint   gre_outer_dst_ip;  /* For GRE: Outer iphdr's dst_ip in net order */
     250             :   } tx_op;
     251             : 
     252             :   /* Round-robin cycle serivce operations */
     253             :   uint rr_idx;
     254             : 
     255             :   /* Ring tracking free packet buffers */
     256             :   fd_net_free_ring_t free_tx;
     257             : 
     258             :   uchar  src_mac_addr[6];
     259             :   uint   default_address;
     260             : 
     261             :   uint   bind_address;
     262             :   ushort shred_listen_port;
     263             :   ushort quic_transaction_listen_port;
     264             :   ushort legacy_transaction_listen_port;
     265             :   ushort gossip_listen_port;
     266             :   ushort repair_client_listen_port;
     267             :   ushort repair_serve_listen_port;
     268             :   ushort txsend_src_port;
     269             : 
     270             :   ulong in_cnt;
     271             :   fd_net_in_ctx_t in[ MAX_NET_INS ];
     272             : 
     273             :   fd_net_out_ctx_t quic_out[1];
     274             :   fd_net_out_ctx_t shred_out[1];
     275             :   fd_net_out_ctx_t gossvf_out[1];
     276             :   fd_net_out_ctx_t repair_out[1];
     277             :   fd_net_out_ctx_t txsend_out[1];
     278             : 
     279             :   fd_net_out_ctx_t rserve_out[1];
     280             :   int rserve_enabled;
     281             : 
     282             :   /* XDP stats refresh timer */
     283             :   long xdp_stats_interval_ticks;
     284             :   long next_xdp_stats_refresh;
     285             : 
     286             :   /* TX flush timers */
     287             :   fd_net_flusher_t tx_flusher[2]; /* one per XSK */
     288             : 
     289             :   /* Route and neighbor tables */
     290             :   fd_fib4_t fib_local[1];
     291             :   fd_fib4_t fib_main[1];
     292             :   fd_neigh4_hmap_t  neigh4[1];
     293             :   fd_netlink_neigh4_solicit_link_t neigh4_solicit[1];
     294             : 
     295             :   /* Netdev table */
     296             :   fd_netdev_tbl_join_t netdev_tbl;                 /* local copy in scratch (hot path) */
     297             :   fd_netdev_tbl_join_t netdev_shared;              /* shared table in netbase (seqlock protected) */
     298             :   uint                 gre_tunnel_ip[MAX_GRE_CNT]; /* 0 means unused */
     299             : 
     300             :   struct {
     301             :     ulong rx_pkt_cnt;
     302             :     ulong rx_bytes_total;
     303             :     ulong rx_src_addr_invalid_cnt;
     304             :     ulong rx_undersz_cnt;
     305             :     ulong rx_fill_blocked_cnt;
     306             :     ulong rx_backp_cnt;
     307             :     long  rx_busy_cnt;
     308             :     long  rx_idle_cnt;
     309             : 
     310             :     ulong tx_submit_cnt;
     311             :     ulong tx_complete_cnt;
     312             :     ulong tx_bytes_total;
     313             :     ulong tx_route_fail_cnt;
     314             :     ulong tx_no_xdp_cnt;
     315             :     ulong tx_neigh_fail_cnt;
     316             :     ulong tx_full_fail_cnt;
     317             :     long  tx_busy_cnt;
     318             :     long  tx_idle_cnt;
     319             : 
     320             :     ulong xsk_tx_wakeup_cnt;
     321             :     ulong xsk_rx_wakeup_cnt;
     322             : 
     323             :     ulong rx_gre_cnt;
     324             :     ulong rx_gre_ignored_cnt;
     325             :     ulong rx_gre_inv_pkt_cnt;
     326             :     ulong tx_gre_cnt;
     327             :     ulong tx_gre_route_fail_cnt;
     328             :   } metrics;
     329             : } fd_net_ctx_t;
     330             : 
     331             : FD_FN_CONST static inline ulong
     332           9 : scratch_align( void ) {
     333           9 :   return 4096UL;
     334           9 : }
     335             : 
     336             : FD_FN_PURE static inline ulong
     337           3 : scratch_footprint( fd_topo_tile_t const * tile ) {
     338           3 :   ulong l = FD_LAYOUT_INIT;
     339           3 :   l = FD_LAYOUT_APPEND( l, alignof(fd_net_ctx_t), sizeof(fd_net_ctx_t)                      );
     340           3 :   l = FD_LAYOUT_APPEND( l, alignof(ulong),        tile->xdp.free_ring_depth * sizeof(ulong) );
     341           3 :   l = FD_LAYOUT_APPEND( l, fd_netdev_tbl_align(), fd_netdev_tbl_footprint( NETDEV_MAX, BOND_MASTER_MAX ) );
     342           3 :   return FD_LAYOUT_FINI( l, scratch_align() );
     343           3 : }
     344             : 
     345             : static void
     346           0 : metrics_write( fd_net_ctx_t * ctx ) {
     347           0 :   FD_MCNT_SET(   NET, PKT_RX,              ctx->metrics.rx_pkt_cnt          );
     348           0 :   FD_MCNT_SET(   NET, PKT_RX_BYTES,        ctx->metrics.rx_bytes_total      );
     349           0 :   FD_MCNT_SET(   NET, PKT_RX_UNDERSIZE,    ctx->metrics.rx_undersz_cnt      );
     350           0 :   FD_MCNT_SET(   NET, PKT_RX_FILL_RING_FULL, ctx->metrics.rx_fill_blocked_cnt );
     351           0 :   FD_MCNT_SET(   NET, PKT_RX_BACKPRESSURE, ctx->metrics.rx_backp_cnt        );
     352           0 :   FD_MGAUGE_SET( NET, RX_BUFFER_BUSY, (ulong)fd_long_max( ctx->metrics.rx_busy_cnt, 0L ) );
     353           0 :   FD_MGAUGE_SET( NET, RX_BUFFER_IDLE, (ulong)fd_long_max( ctx->metrics.rx_idle_cnt, 0L ) );
     354           0 :   FD_MGAUGE_SET( NET, TX_BUFFER_BUSY, (ulong)fd_long_max( ctx->metrics.tx_busy_cnt, 0L ) );
     355           0 :   FD_MGAUGE_SET( NET, TX_BUFFER_IDLE, (ulong)fd_long_max( ctx->metrics.tx_idle_cnt, 0L ) );
     356             : 
     357           0 :   FD_MCNT_SET( NET, PKT_TX_SUBMITTED,     ctx->metrics.tx_submit_cnt     );
     358           0 :   FD_MCNT_SET( NET, PKT_TX_COMPLETED,     ctx->metrics.tx_complete_cnt   );
     359           0 :   FD_MCNT_SET( NET, PKT_TX_BYTES,         ctx->metrics.tx_bytes_total    );
     360           0 :   FD_MCNT_SET( NET, PKT_TX_NO_ROUTE,    ctx->metrics.tx_route_fail_cnt );
     361           0 :   FD_MCNT_SET( NET, PKT_TX_NO_NEIGHBOR, ctx->metrics.tx_neigh_fail_cnt );
     362           0 :   FD_MCNT_SET( NET, PKT_TX_RING_FULL,     ctx->metrics.tx_full_fail_cnt  );
     363             : 
     364           0 :   FD_MCNT_SET( NET, XSK_SYSCALL_TX,    ctx->metrics.xsk_tx_wakeup_cnt    );
     365           0 :   FD_MCNT_SET( NET, XSK_SYSCALL_RX,    ctx->metrics.xsk_rx_wakeup_cnt    );
     366             : 
     367           0 :   FD_MCNT_SET( NET, GRE_PKT_RX,            ctx->metrics.rx_gre_cnt            );
     368           0 :   FD_MCNT_SET( NET, GRE_PKT_RX_INVALID,    ctx->metrics.rx_gre_inv_pkt_cnt    );
     369           0 :   FD_MCNT_SET( NET, GRE_PKT_RX_IGNORED,    ctx->metrics.rx_gre_ignored_cnt    );
     370           0 :   FD_MCNT_SET( NET, GRE_PKT_TX_SUBMITTED,            ctx->metrics.tx_gre_cnt            );
     371           0 :   FD_MCNT_SET( NET, GRE_PKT_TX_NO_ROUTE, ctx->metrics.tx_gre_route_fail_cnt );
     372           0 :   FD_MCNT_SET( NET, PKT_RX_SRC_INVALID, ctx->metrics.rx_src_addr_invalid_cnt );
     373           0 : }
     374             : 
     375             : struct xdp_statistics_v0 {
     376             :   __u64 rx_dropped; /* Dropped for other reasons */
     377             :   __u64 rx_invalid_descs; /* Dropped due to invalid descriptor */
     378             :   __u64 tx_invalid_descs; /* Dropped due to invalid descriptor */
     379             : };
     380             : 
     381             : struct xdp_statistics_v1 {
     382             :   __u64 rx_dropped; /* Dropped for other reasons */
     383             :   __u64 rx_invalid_descs; /* Dropped due to invalid descriptor */
     384             :   __u64 tx_invalid_descs; /* Dropped due to invalid descriptor */
     385             :   __u64 rx_ring_full; /* Dropped due to rx ring being full */
     386             :   __u64 rx_fill_ring_empty_descs; /* Failed to retrieve item from fill ring */
     387             :   __u64 tx_ring_empty_descs; /* Failed to retrieve item from tx ring */
     388             : };
     389             : 
     390             : static void
     391           0 : poll_xdp_statistics( fd_net_ctx_t * ctx ) {
     392           0 :   struct xdp_statistics_v1 stats = {0};
     393           0 :   ulong xsk_cnt = ctx->xsk_cnt;
     394           0 :   for( ulong j=0UL; j<xsk_cnt; j++ ) {
     395           0 :     struct xdp_statistics_v1 sub_stats = {0};
     396           0 :     uint optlen = (uint)sizeof(struct xdp_statistics_v1);
     397           0 :     if( FD_UNLIKELY( -1==getsockopt( ctx->xsk[ j ].xsk_fd, SOL_XDP, XDP_STATISTICS, &sub_stats, &optlen ) ) )
     398           0 :       FD_LOG_ERR(( "getsockopt(SOL_XDP, XDP_STATISTICS) failed: %s", strerror( errno ) ));
     399           0 :     if( FD_UNLIKELY( optlen!=sizeof(struct xdp_statistics_v0) &&
     400           0 :                      optlen!=sizeof(struct xdp_statistics_v1) ) ) {
     401           0 :       FD_LOG_ERR(( "getsockopt(SOL_XDP, XDP_STATISTICS) returned unexpected size %u", optlen ));
     402           0 :     }
     403           0 :     stats.rx_dropped               += sub_stats.rx_dropped;
     404           0 :     stats.rx_invalid_descs         += sub_stats.rx_invalid_descs;
     405           0 :     stats.tx_invalid_descs         += sub_stats.tx_invalid_descs;
     406           0 :     stats.rx_ring_full             += sub_stats.rx_ring_full;
     407           0 :     stats.rx_fill_ring_empty_descs += sub_stats.rx_fill_ring_empty_descs;
     408           0 :     stats.tx_ring_empty_descs      += sub_stats.tx_ring_empty_descs;
     409           0 :   }
     410             : 
     411           0 :   FD_MCNT_SET( NET, XDP_RX_OTHER_DROPPED,         stats.rx_dropped               );
     412           0 :   FD_MCNT_SET( NET, XDP_RX_INVALID_DESCRIPTOR,    stats.rx_invalid_descs         );
     413           0 :   FD_MCNT_SET( NET, XDP_TX_INVALID_DESCRIPTOR,    stats.tx_invalid_descs         );
     414           0 :   FD_MCNT_SET( NET, XDP_RX_RING_FULL,             stats.rx_ring_full             );
     415           0 :   FD_MCNT_SET( NET, XDP_RX_FILL_RING_EMPTY,       stats.rx_fill_ring_empty_descs );
     416           0 :   FD_MCNT_SET( NET, XDP_TX_RING_EMPTY,            stats.tx_ring_empty_descs      );
     417           0 : }
     418             : 
     419             : /* net_is_fatal_xdp_error returns 1 if the given errno returned by an
     420             :    XDP API indicates a non-recoverable error code.  The net tile should
     421             :    crash if it sees such an error so the problem does not go undetected.
     422             :    Otherwise, returns 0. */
     423             : 
     424             : static int
     425           0 : net_is_fatal_xdp_error( int err ) {
     426           0 :   return err==ESOCKTNOSUPPORT || err==EOPNOTSUPP || err==EINVAL ||
     427           0 :          err==EPERM;
     428           0 : }
     429             : 
     430             : /* net_gre_tunnel_ip fills ctx->gre_tunnel_ip.  The first gre_tunnel_cnt
     431             :    entries will be populated with the IP address of the GRE tunnel peer
     432             :    for the first gre_tunnel_cnt untagged GRE tunnels, and the rest of
     433             :    the entries will be set to 0, where gre_tunnel_cnt = min(MAX_GRE_CNT,
     434             :    the number of untagged GRE tunnels).  Returns gre_tunnel_cnt. */
     435             : 
     436             : static ulong
     437           6 : net_gre_tunnel_ip( fd_net_ctx_t * ctx ) {
     438           6 :   fd_netdev_t * dev_tbl = ctx->netdev_tbl.dev_tbl;
     439           6 :   ushort        dev_cnt = ctx->netdev_tbl.hdr->dev_cnt;
     440             : 
     441           6 :   ulong gre_tunnel_cnt = 0UL;
     442           6 :   memset( ctx->gre_tunnel_ip, '\0', MAX_GRE_CNT*sizeof(uint) );
     443          21 :   for( ushort if_idx = 0; (if_idx<dev_cnt) & (gre_tunnel_cnt<MAX_GRE_CNT); if_idx++ ) {
     444          15 :     fd_netdev_t const * dev = dev_tbl+if_idx;
     445          15 :     if( dev->dev_type==ARPHRD_IPGRE && dev->gre_dst_ip ) ctx->gre_tunnel_ip[ gre_tunnel_cnt++ ] = dev->gre_dst_ip;
     446          15 :   }
     447           6 :   return gre_tunnel_cnt;
     448           6 : }
     449             : 
     450             : 
     451             : /* net_tx_ready returns 1 if we can submit a job to this TX ring, and 0 otherwise.
     452             :    Reasons for block include:
     453             :    - No TX buffer is available (free ring empty)
     454             :    - TX ring is full
     455             : 
     456             :    tx_ring: pointer to the XDP TX ring
     457             :    free_ring: pointer to the free TX ring */
     458             : 
     459             : static int
     460             : net_tx_ready( fd_xdp_ring_t *      tx_ring,
     461          42 :               fd_net_free_ring_t * free_ring ) {
     462          42 :   if( FD_UNLIKELY( free_ring->prod == free_ring->cons ) ) return 0; /* drop - no free buffers */
     463          36 :   if( FD_UNLIKELY( fd_xdp_ring_full( tx_ring ) ) )        return 0; /* drop - tx ring full */
     464          33 :   return 1;
     465          36 : }
     466             : 
     467             : /* net_rx_wakeup triggers xsk_recvmsg to run in the kernel.  Needs to be
     468             :    called periodically in order to receive packets. */
     469             : 
     470             : static void
     471             : net_rx_wakeup( fd_net_ctx_t * ctx,
     472             :                fd_xsk_t *     xsk,
     473           0 :                int *          charge_busy ) {
     474           0 :   FD_VOLATILE( *xsk->ring_rx.cons ) = xsk->ring_rx.cached_cons; /* write-back local copies to fseqs */
     475           0 :   FD_VOLATILE( *xsk->ring_fr.prod ) = xsk->ring_fr.cached_prod;
     476           0 :   if( !fd_xsk_rx_need_wakeup( xsk ) ) return;
     477           0 :   *charge_busy = 1;
     478           0 :   struct msghdr _ignored[ 1 ] = { 0 };
     479           0 :   if( FD_UNLIKELY( -1==recvmsg( xsk->xsk_fd, _ignored, MSG_DONTWAIT ) ) ) {
     480           0 :     if( FD_UNLIKELY( net_is_fatal_xdp_error( errno ) ) ) {
     481           0 :       FD_LOG_ERR(( "xsk recvmsg failed xsk_fd=%d (%i-%s)", xsk->xsk_fd, errno, fd_io_strerror( errno ) ));
     482           0 :     }
     483           0 :     if( FD_UNLIKELY( errno!=EAGAIN ) ) {
     484           0 :       long ts = fd_log_wallclock();
     485           0 :       if( ts > xsk->log_suppress_until_ns ) {
     486           0 :         FD_LOG_WARNING(( "xsk recvmsg failed xsk_fd=%d (%i-%s)", xsk->xsk_fd, errno, fd_io_strerror( errno ) ));
     487           0 :         xsk->log_suppress_until_ns = ts + (long)1e9;
     488           0 :       }
     489           0 :     }
     490           0 :   }
     491           0 :   ctx->metrics.xsk_rx_wakeup_cnt++;
     492           0 : }
     493             : 
     494             : /* net_tx_wakeup triggers xsk_sendmsg to run in the kernel.  Needs to be
     495             :    called periodically in order to transmit packets. Should only be called
     496             :    if there are unconsumed packets in Tx ring. */
     497             : 
     498             : static void
     499             : net_tx_wakeup( fd_net_ctx_t * ctx,
     500             :                fd_xsk_t *     xsk,
     501          24 :                int *          charge_busy ) {
     502          24 :   FD_VOLATILE( *xsk->ring_tx.prod ) = xsk->ring_tx.cached_prod; /* write-back local copies to fseqs */
     503          24 :   FD_VOLATILE( *xsk->ring_cr.cons ) = xsk->ring_cr.cached_cons;
     504          24 :   if( !fd_xsk_tx_need_wakeup( xsk ) ) return;
     505           0 :   *charge_busy = 1;
     506           0 :   if( FD_UNLIKELY( -1==sendto( xsk->xsk_fd, NULL, 0, MSG_DONTWAIT, NULL, 0 ) ) ) {
     507           0 :     if( FD_UNLIKELY( net_is_fatal_xdp_error( errno ) ) ) {
     508           0 :       FD_LOG_ERR(( "xsk sendto failed xsk_fd=%d (%i-%s)", xsk->xsk_fd, errno, fd_io_strerror( errno ) ));
     509           0 :     }
     510           0 :     if( FD_UNLIKELY( errno!=EAGAIN ) ) {
     511           0 :       long ts = fd_log_wallclock();
     512           0 :       if( ts > xsk->log_suppress_until_ns ) {
     513           0 :         FD_LOG_WARNING(( "xsk sendto failed xsk_fd=%d (%i-%s)", xsk->xsk_fd, errno, fd_io_strerror( errno ) ));
     514           0 :         xsk->log_suppress_until_ns = ts + (long)1e9;
     515           0 :       }
     516           0 :     }
     517           0 :   }
     518           0 :   ctx->metrics.xsk_tx_wakeup_cnt++;
     519           0 : }
     520             : 
     521             : /* net_tx_periodic_wakeup does a timer based xsk_sendmsg wakeup. */
     522             : 
     523             : static inline int
     524             : net_tx_periodic_wakeup( fd_net_ctx_t * ctx,
     525             :                         uint           xsk_idx,
     526             :                         long           now,
     527          27 :                         int *          charge_busy ) {
     528          27 :   fd_xdp_ring_t * tx_ring        = &ctx->xsk[ xsk_idx ].ring_tx;
     529          27 :   int             tx_ring_empty  = fd_xdp_ring_empty( tx_ring, FD_XDP_RING_ROLE_PROD );
     530          27 :   if( fd_net_flusher_check( ctx->tx_flusher+xsk_idx, now, tx_ring_empty ) ) {
     531          24 :     net_tx_wakeup( ctx, &ctx->xsk[ xsk_idx ], charge_busy );
     532          24 :     fd_net_flusher_wakeup( ctx->tx_flusher+xsk_idx, now );
     533          24 :   }
     534          27 :   return 0;
     535          27 : }
     536             : 
     537             : static void
     538           0 : during_housekeeping( fd_net_ctx_t * ctx ) {
     539           0 :   long now = fd_tickcount();
     540           0 :   if( FD_LIKELY( !fd_seqlock_locked_hint( &ctx->netdev_shared.hdr->seqlock ) ) ) {
     541           0 :     fd_netdev_tbl_copy( &ctx->netdev_tbl, &ctx->netdev_shared );
     542           0 :   }
     543           0 :   net_gre_tunnel_ip( ctx );
     544             : 
     545           0 :   ctx->metrics.rx_busy_cnt = 0UL;
     546           0 :   ctx->metrics.rx_idle_cnt = 0UL;
     547           0 :   ctx->metrics.tx_busy_cnt = 0UL;
     548           0 :   ctx->metrics.tx_idle_cnt = fd_seq_diff( ctx->free_tx.prod, ctx->free_tx.cons );
     549           0 :   for( uint j=0U; j<ctx->xsk_cnt; j++ ) {
     550           0 :     fd_xsk_t * xsk = &ctx->xsk[ j ];
     551           0 :     FD_COMPILER_MFENCE();
     552             :     /* Write back local copies to fseqs that we own */
     553           0 :     FD_VOLATILE( *xsk->ring_fr.prod ) = xsk->ring_fr.cached_prod;
     554           0 :     FD_VOLATILE( *xsk->ring_rx.cons ) = xsk->ring_rx.cached_cons;
     555           0 :     FD_VOLATILE( *xsk->ring_tx.prod ) = xsk->ring_tx.cached_prod;
     556           0 :     FD_VOLATILE( *xsk->ring_cr.cons ) = xsk->ring_cr.cached_cons;
     557             : 
     558             :     /* Refresh kernel-owned seq numbers for accurate stats */
     559           0 :     xsk->ring_fr.cached_cons = FD_VOLATILE_CONST( *xsk->ring_fr.cons );
     560           0 :     xsk->ring_rx.cached_prod = FD_VOLATILE_CONST( *xsk->ring_rx.prod );
     561           0 :     xsk->ring_tx.cached_cons = FD_VOLATILE_CONST( *xsk->ring_tx.cons );
     562           0 :     xsk->ring_cr.cached_prod = FD_VOLATILE_CONST( *xsk->ring_cr.prod );
     563             : 
     564           0 :     FD_COMPILER_MFENCE();
     565           0 :     ctx->metrics.rx_busy_cnt += (long)(int)( xsk->ring_rx.cached_prod - xsk->ring_rx.cached_cons );
     566           0 :     ctx->metrics.rx_idle_cnt += (long)(int)( xsk->ring_fr.cached_prod - xsk->ring_fr.cached_cons );
     567           0 :     ctx->metrics.tx_busy_cnt += (long)(int)( xsk->ring_tx.cached_prod - xsk->ring_tx.cached_cons );
     568           0 :     ctx->metrics.tx_busy_cnt += (long)(int)( xsk->ring_cr.cached_prod - xsk->ring_cr.cached_cons );
     569           0 :   }
     570             : 
     571           0 :   if( now > ctx->next_xdp_stats_refresh ) {
     572           0 :     ctx->next_xdp_stats_refresh = now + ctx->xdp_stats_interval_ticks;
     573           0 :     poll_xdp_statistics( ctx );
     574           0 :   }
     575           0 : }
     576             : 
     577             : 
     578             : /* net_tx_route resolves the xsk index, src ip address, src MAC address, and
     579             :    dst MAC address.  Returns 1 on success, 0 on failure.
     580             :    On success, tx_op->{xsk_idx,src_ip,mac_addrs} is set, and if the dst_ip
     581             :    belongs to a GRE interface, is_gre_inf will set to 1 and
     582             :    tx_op->{gre_outer_src_ip, gre_outer_dst_ip} will be loaded from the netdev
     583             :    table. is_gre_inf is set to 0 if dst_ip doesn't belong to a GRE interface. */
     584             : 
     585             : static int
     586             : net_tx_route( fd_net_ctx_t * ctx,
     587             :               uint           dst_ip,
     588          33 :               uint *         is_gre_inf ) {
     589             : 
     590             :   /* Route lookup */
     591             : 
     592          33 :   fd_fib4_hop_t hop[2] = {0};
     593          33 :   hop[0] = fd_fib4_lookup( ctx->fib_local, dst_ip, 0UL );
     594          33 :   hop[1] = fd_fib4_lookup( ctx->fib_main,  dst_ip, 0UL );
     595          33 :   fd_fib4_hop_t const * next_hop = fd_fib4_hop_or( hop+0, hop+1 );
     596             : 
     597          33 :   uint rtype   = next_hop->rtype;
     598          33 :   uint if_idx  = next_hop->if_idx;
     599          33 :   uint ip4_src = next_hop->ip4_src;
     600             : 
     601          33 :   if( FD_UNLIKELY( rtype==FD_FIB4_RTYPE_LOCAL ) ) {
     602           0 :     rtype  = FD_FIB4_RTYPE_UNICAST;
     603           0 :     if_idx = 1;
     604           0 :   }
     605             : 
     606          33 :   if( FD_UNLIKELY( rtype!=FD_FIB4_RTYPE_UNICAST ) ) {
     607           0 :     ctx->metrics.tx_route_fail_cnt++;
     608           0 :     return 0;
     609           0 :   }
     610             : 
     611          33 :   fd_netdev_t * netdev = fd_netdev_tbl_query( &ctx->netdev_tbl, if_idx );
     612          33 :   if( !netdev ) {
     613           3 :     ctx->metrics.tx_route_fail_cnt++;
     614           3 :     return 0;
     615           3 :   }
     616             : 
     617          30 :   ip4_src = fd_uint_if( !!ctx->bind_address, ctx->bind_address, ip4_src );
     618          30 :   ctx->tx_op.src_ip  = ip4_src;
     619          30 :   ctx->tx_op.xsk_idx = UINT_MAX;
     620             : 
     621          30 :   FD_TEST( is_gre_inf );
     622          30 :   *is_gre_inf = 0;
     623          30 :   if( netdev->dev_type==ARPHRD_LOOPBACK ) {
     624             :     /* Set Ethernet src and dst address to 00:00:00:00:00:00 */
     625           0 :     memset( ctx->tx_op.mac_addrs, 0, 12UL );
     626           0 :     ctx->tx_op.xsk_idx = XSK_IDX_LO;
     627             :     /* Set preferred src address to 127.0.0.1 if no bind address is set */
     628           0 :     if( !ctx->tx_op.src_ip ) ctx->tx_op.src_ip = FD_IP4_ADDR( 127,0,0,1 );
     629           0 :     return 1;
     630          30 :   } else if( netdev->dev_type==ARPHRD_IPGRE ) {
     631             :     /* skip MAC addrs lookup for GRE inner dst ip */
     632          12 :     if( netdev->gre_src_ip ) ctx->tx_op.gre_outer_src_ip = netdev->gre_src_ip;
     633          12 :     ctx->tx_op.gre_outer_dst_ip = netdev->gre_dst_ip;
     634          12 :     *is_gre_inf = 1;
     635          12 :     return 1;
     636          12 :   }
     637             : 
     638          18 :   if( FD_UNLIKELY( netdev->dev_type!=ARPHRD_ETHER ) ) return 0; // drop
     639             : 
     640          18 :   if( FD_UNLIKELY( if_idx!=ctx->if_virt ) ) {
     641           0 :     ctx->metrics.tx_no_xdp_cnt++;
     642           0 :     return 0;
     643           0 :   }
     644          18 :   ctx->tx_op.xsk_idx = XSK_IDX_MAIN;
     645             : 
     646             :   /* Neighbor resolve */
     647          18 :   uint neigh_ip = next_hop->ip4_gw;
     648          18 :   if( !neigh_ip ) neigh_ip = dst_ip;
     649             : 
     650          18 :   fd_neigh4_entry_t neigh[1];
     651          18 :   int neigh_res = fd_neigh4_hmap_query_entry( ctx->neigh4, neigh_ip, neigh );
     652          18 :   if( FD_UNLIKELY( neigh_res!=FD_MAP_SUCCESS ) ) {
     653             :     /* Neighbor not found */
     654           0 :     fd_netlink_neigh4_solicit( ctx->neigh4_solicit, neigh_ip, if_idx, fd_frag_meta_ts_comp( fd_tickcount() ) );
     655           0 :     ctx->metrics.tx_neigh_fail_cnt++;
     656           0 :     return 0;
     657           0 :   }
     658          18 :   if( FD_UNLIKELY( neigh->state != FD_NEIGH4_STATE_ACTIVE ) ) {
     659           0 :     ctx->metrics.tx_neigh_fail_cnt++;
     660           0 :     return 0;
     661           0 :   }
     662          18 :   ip4_src = fd_uint_if( !ip4_src, ctx->default_address, ip4_src );
     663          18 :   ctx->tx_op.src_ip = ip4_src;
     664          18 :   memcpy( ctx->tx_op.mac_addrs+0, neigh->mac_addr, 6 );
     665          18 :   memcpy( ctx->tx_op.mac_addrs+6, netdev->mac_addr,  6 );
     666             : 
     667          18 :   return 1;
     668          18 : }
     669             : 
     670             : /* before_frag is called when a new metadata descriptor for a TX job is
     671             :    found.  This callback determines whether this net tile is responsible
     672             :    for the TX job.  If so, it prepares the TX op for the during_frag and
     673             :    after_frag callbacks. */
     674             : 
     675             : static inline int
     676             : before_frag( fd_net_ctx_t * ctx,
     677             :              ulong          in_idx,
     678             :              ulong          seq,
     679          18 :              ulong          sig ) {
     680          18 :   (void)in_idx; (void)seq;
     681             : 
     682             :   /* Find interface index of next packet */
     683          18 :   ulong proto = fd_disco_netmux_sig_proto( sig );
     684          18 :   if( FD_UNLIKELY( proto!=DST_PROTO_OUTGOING ) ) return 1;
     685             : 
     686             :   /* Load balance TX */
     687          18 :   uint net_tile_cnt = ctx->net_tile_cnt;
     688          18 :   uint hash         = (uint)fd_disco_netmux_sig_hash( sig );
     689          18 :   uint target_idx   = hash % net_tile_cnt;
     690          18 :   uint net_tile_id  = ctx->net_tile_id;
     691          18 :   uint dst_ip       = fd_disco_netmux_sig_ip( sig );
     692             : 
     693             :   /* Skip if another net tile is responsible for this packet.
     694             :      Fast path for net tiles other than net_tile 0. */
     695             : 
     696          18 :   if( net_tile_id!=0 && net_tile_id!=target_idx ) return 1; /* ignore */
     697             : 
     698             : 
     699          18 :   ctx->tx_op.use_gre          = 0;
     700          18 :   ctx->tx_op.gre_outer_dst_ip = 0;
     701          18 :   ctx->tx_op.gre_outer_src_ip = 0;
     702          18 :   uint is_gre_inf             = 0;
     703             : 
     704          18 :   if( FD_UNLIKELY( !net_tx_route( ctx, dst_ip, &is_gre_inf ) ) ) {
     705           0 :     return 1; /* metrics incremented by net_tx_route */
     706           0 :   }
     707             : 
     708          18 :   uint xsk_idx     = ctx->tx_op.xsk_idx;
     709             : 
     710          18 :   if( is_gre_inf ) {
     711          12 :     uint inner_src_ip = ctx->tx_op.src_ip;
     712          12 :     if( FD_UNLIKELY( !inner_src_ip ) ) {
     713           0 :       ctx->metrics.tx_gre_route_fail_cnt++;
     714           0 :       return 1;
     715           0 :     }
     716             :     /* Find the MAC addrs for the eth hdr, and src ip for outer ip4 hdr if not found in netdev tbl */
     717          12 :     ctx->tx_op.src_ip  = 0;
     718          12 :     is_gre_inf         = 0;
     719          12 :     if( FD_UNLIKELY( !net_tx_route( ctx, ctx->tx_op.gre_outer_dst_ip, &is_gre_inf ) ) ) {
     720           0 :       ctx->metrics.tx_gre_route_fail_cnt++;
     721           0 :       return 1;
     722           0 :     }
     723          12 :     if( is_gre_inf ) {
     724             :       /* Only one layer of tunnelling supported */
     725           0 :       ctx->metrics.tx_gre_route_fail_cnt++;
     726           0 :       return 1;
     727           0 :     }
     728          12 :     if( !ctx->tx_op.gre_outer_src_ip ) {
     729           6 :       ctx->tx_op.gre_outer_src_ip = ctx->tx_op.src_ip;
     730           6 :     }
     731          12 :     ctx->tx_op.use_gre = 1; /* indicate to during_frag to use GRE header */
     732          12 :     ctx->tx_op.src_ip  = inner_src_ip;
     733          12 :     xsk_idx = XSK_IDX_MAIN;
     734          12 :   }
     735             : 
     736          18 :   if( FD_UNLIKELY( xsk_idx>=ctx->xsk_cnt ) ) {
     737             :     /* Packet does not route to an XDP interface */
     738           0 :     ctx->metrics.tx_no_xdp_cnt++;
     739           0 :     return 1;
     740           0 :   }
     741             : 
     742          18 :   if( xsk_idx==XSK_IDX_LO ) target_idx = 0; /* loopback always targets tile 0 */
     743             : 
     744             :   /* Skip if another net tile is responsible for this packet */
     745             : 
     746          18 :   if( net_tile_id!=target_idx ) return 1; /* ignore */
     747             : 
     748             :   /* Skip if TX is blocked */
     749             : 
     750          18 :   fd_xsk_t *           xsk  = &ctx->xsk[ xsk_idx ];
     751          18 :   fd_net_free_ring_t * free = &ctx->free_tx;
     752          18 :   if( FD_UNLIKELY( !net_tx_ready( &xsk->ring_tx, free ) ) ) {
     753           0 :     ctx->metrics.tx_full_fail_cnt++;
     754           0 :     return 1;
     755           0 :   }
     756             : 
     757             :   /* Allocate buffer for receive */
     758          18 :   ulong                alloc_seq = free->cons;
     759          18 :   void *               frame     = (void *)free->queue[ alloc_seq % free->depth ];
     760          18 :   free->cons = fd_seq_inc( alloc_seq, 1UL );
     761             : 
     762          18 :   ctx->tx_op.frame = frame;
     763             : 
     764          18 :   return 0; /* continue */
     765          18 : }
     766             : 
     767             : /* during_frag is called when before_frag has committed to transmit an
     768             :    outgoing packet. */
     769             : 
     770             : static inline void
     771             : during_frag( fd_net_ctx_t * ctx,
     772             :              ulong          in_idx,
     773             :              ulong          seq FD_PARAM_UNUSED,
     774             :              ulong          sig FD_PARAM_UNUSED,
     775             :              ulong          chunk,
     776             :              ulong          sz,
     777          18 :              ulong          ctl FD_PARAM_UNUSED ) {
     778          18 :   if( FD_UNLIKELY( chunk<ctx->in[ in_idx ].chunk0 || chunk>ctx->in[ in_idx ].wmark || sz>FD_NET_MTU ) )
     779           0 :     FD_LOG_ERR(( "chunk %lu %lu corrupt, not in range [%lu,%lu]", chunk, sz, ctx->in[ in_idx ].chunk0, ctx->in[ in_idx ].wmark ));
     780             : 
     781          18 :   if( FD_UNLIKELY( sz<( sizeof(fd_eth_hdr_t)+sizeof(fd_ip4_hdr_t) ) ) )
     782           0 :     FD_LOG_ERR(( "packet too small %lu (in_idx=%lu)", sz, in_idx ));
     783             : 
     784          18 :   if( FD_UNLIKELY( sz>FD_ETH_PAYLOAD_MAX ) )
     785           0 :     FD_LOG_ERR(( "packet too big %lu (in_idx=%lu)", sz, in_idx ));
     786             : 
     787          18 :   void * frame = ctx->tx_op.frame;
     788          18 :   if( FD_UNLIKELY( (ulong)frame < (ulong)ctx->umem ) )
     789           0 :     FD_LOG_ERR(( "frame %p out of bounds (below %p)", frame, (void *)ctx->umem ));
     790          18 :   ulong umem_off = (ulong)frame - (ulong)ctx->umem;
     791          18 :   if( FD_UNLIKELY( (ulong)umem_off > (ulong)ctx->umem_sz ) )
     792           0 :     FD_LOG_ERR(( "frame %p out of bounds (beyond %p)", frame, (void *)ctx->umem_sz ));
     793             : 
     794             :   /* Speculatively copy frame into XDP buffer */
     795          18 :   uchar const * src = fd_chunk_to_laddr_const( ctx->in[ in_idx ].mem, chunk );
     796             : 
     797          18 :   if( ctx->tx_op.use_gre ) {
     798             :     /* Discard the ethernet hdr from src. Copy the rest to where the inner ip4_hdr is.
     799             :        Safe from overflow: FD_ETH_PAYLOAD_MAX + header overhead < frame size (2048UL) */
     800          12 :     ulong overhead = sizeof(fd_eth_hdr_t) + sizeof(fd_ip4_hdr_t) + sizeof(fd_gre_hdr_t);
     801          12 :     fd_memcpy( (void *)( (ulong)ctx->tx_op.frame + overhead ), src + sizeof(fd_eth_hdr_t), sz - sizeof(fd_eth_hdr_t) );
     802          12 :   } else {
     803           6 :     fd_memcpy( ctx->tx_op.frame, src, sz );
     804           6 :   }
     805          18 : }
     806             : 
     807             : /* after_frag is called when the during_frag memcpy was _not_ overrun. */
     808             : 
     809             : static void
     810             : after_frag( fd_net_ctx_t *      ctx,
     811             :             ulong               in_idx,
     812             :             ulong               seq,
     813             :             ulong               sig,
     814             :             ulong               sz,
     815             :             ulong               tsorig,
     816             :             ulong               tspub,
     817          18 :             fd_stem_context_t * stem ) {
     818          18 :   (void)in_idx; (void)seq; (void)sig; (void)tsorig; (void)tspub; (void)stem;
     819             : 
     820             :   /* Current send operation */
     821             : 
     822          18 :   uchar *    frame   = ctx->tx_op.frame;
     823          18 :   uint       xsk_idx = ctx->tx_op.xsk_idx;
     824             : 
     825             :   /* Select Ethernet addresses */
     826          18 :   memcpy( frame, ctx->tx_op.mac_addrs, 12 );
     827             : 
     828          18 :   uchar * iphdr = frame + sizeof(fd_eth_hdr_t);
     829             : 
     830          18 :   if( ctx->tx_op.use_gre ) {
     831             : 
     832             :     /* For GRE packets, the ethertype will always be FD_ETH_HDR_TYPE_IP. outer source ip can't be 0 */
     833          12 :     if( FD_UNLIKELY( ctx->tx_op.gre_outer_src_ip==0 ) ) {
     834           0 :       ctx->metrics.tx_gre_route_fail_cnt++;
     835           0 :       return;
     836           0 :     }
     837             : 
     838             :     /* Write the last two bytes for eth_hdr */
     839          12 :     FD_STORE( ushort, frame+12, fd_ushort_bswap( FD_ETH_HDR_TYPE_IP ) );
     840             : 
     841          12 :     uchar * outer_iphdr       = frame + sizeof(fd_eth_hdr_t);
     842          12 :     uchar * gre_hdr           = outer_iphdr + sizeof(fd_ip4_hdr_t);
     843          12 :     uchar * inner_iphdr       = gre_hdr + sizeof(fd_gre_hdr_t);
     844             : 
     845             :     /* outer hdr + gre hdr + inner net_tot_len */
     846          12 :     ushort  outer_net_tot_len = (ushort)( sizeof(fd_ip4_hdr_t) + sizeof(fd_gre_hdr_t) + fd_ushort_bswap( ( (fd_ip4_hdr_t *)inner_iphdr )->net_tot_len ) );
     847             : 
     848             :     /* Construct outer ip header */
     849          12 :     fd_ip4_hdr_t ip4_outer = (fd_ip4_hdr_t) {
     850          12 :       .verihl       = FD_IP4_VERIHL( 4,5 ),
     851          12 :       .tos          = 0,
     852          12 :       .net_tot_len  = fd_ushort_bswap( outer_net_tot_len ),
     853          12 :       .net_id       = 0,
     854          12 :       .net_frag_off = fd_ushort_bswap( FD_IP4_HDR_FRAG_OFF_DF ),
     855          12 :       .ttl          = 64,
     856          12 :       .protocol     = FD_IP4_HDR_PROTOCOL_GRE,
     857          12 :       .check        = 0,
     858          12 :       .saddr        = ctx->tx_op.gre_outer_src_ip,
     859          12 :       .daddr        = ctx->tx_op.gre_outer_dst_ip,
     860          12 :     };
     861          12 :     ip4_outer.check = fd_ip4_hdr_check_fast( &ip4_outer );
     862          12 :     FD_STORE( fd_ip4_hdr_t, outer_iphdr, ip4_outer );
     863             : 
     864             :     /* Construct gre header */
     865          12 :     fd_gre_hdr_t gre_hdr_ = {
     866          12 :       .flags_version = FD_GRE_HDR_FLG_VER_BASIC,
     867          12 :       .protocol      = fd_ushort_bswap( FD_ETH_HDR_TYPE_IP )
     868          12 :     };
     869          12 :     FD_STORE( fd_gre_hdr_t, gre_hdr, gre_hdr_ );
     870             : 
     871          12 :     iphdr   = inner_iphdr;
     872          12 :     sz      = sizeof(fd_eth_hdr_t) + outer_net_tot_len;
     873          12 :     xsk_idx = 0;
     874          12 :   }
     875             : 
     876             :   /* Construct (inner) ip header */
     877          18 :   uint   ihl       = FD_IP4_GET_LEN( *(fd_ip4_hdr_t *)iphdr );
     878          18 :   uint   ver       = FD_IP4_GET_VERSION( *(fd_ip4_hdr_t *)iphdr );
     879          18 :   uint   ip4_saddr = FD_LOAD( uint, iphdr+12 );
     880          18 :   ushort ethertype = FD_LOAD( ushort, frame+12 );
     881             : 
     882          18 :   if( FD_UNLIKELY( ethertype!=fd_ushort_bswap( FD_ETH_HDR_TYPE_IP ) ) ) {
     883           0 :     FD_LOG_CRIT(( "in link %lu attempted to send packet with invalid ethertype %04x",
     884           0 :                   in_idx, fd_ushort_bswap( ethertype ) ));
     885           0 :   }
     886             : 
     887          18 :   if( ver!=0x4 ) {
     888           0 :     ctx->metrics.tx_route_fail_cnt++; // Not an IPv4 packet. drop
     889           0 :     return;
     890           0 :   }
     891             : 
     892          18 :   if( ip4_saddr==0 ) {
     893          18 :     if( FD_UNLIKELY( ctx->tx_op.src_ip==0 ||
     894          18 :                      ihl<sizeof(fd_ip4_hdr_t) ||
     895          18 :                      (sizeof(fd_eth_hdr_t)+ihl)>sz ) ) {
     896             :       /* Outgoing IPv4 packet with unknown src IP or invalid IHL */
     897             :       /* FIXME should select first IPv4 address of device table here */
     898           0 :       ctx->metrics.tx_route_fail_cnt++;
     899           0 :       return;
     900           0 :     }
     901             :     /* Recompute checksum after changing header */
     902          18 :     FD_STORE( uint,   iphdr+12, ctx->tx_op.src_ip );
     903          18 :     FD_STORE( ushort, iphdr+10, 0 );
     904          18 :     FD_STORE( ushort, iphdr+10, fd_ip4_hdr_check( iphdr ) );
     905          18 :   }
     906             : 
     907             :   /* Submit packet TX job
     908             : 
     909             :      Invariant for ring_tx: prod-cons<length
     910             :      (This invariant breaks if any other packet is sent over this ring
     911             :      between before_frag and this point, e.g. send_arp_probe.) */
     912             : 
     913          18 :   fd_xsk_t      * xsk     = &ctx->xsk[ xsk_idx ];
     914          18 :   fd_xdp_ring_t * tx_ring = &xsk->ring_tx;
     915          18 :   uint            tx_seq  = tx_ring->cached_prod;
     916          18 :   uint            tx_mask = tx_ring->depth - 1U;
     917          18 :   xsk->ring_tx.packet_ring[ tx_seq&tx_mask ] = (struct xdp_desc) {
     918          18 :     .addr    = (ulong)frame - (ulong)ctx->umem,
     919          18 :     .len     = (uint)sz,
     920          18 :     .options = 0
     921          18 :   };
     922             : 
     923             :   /* Frame is now owned by kernel. Clear tx_op. */
     924          18 :   ctx->tx_op.frame = NULL;
     925             : 
     926             :   /* Register newly enqueued packet */
     927          18 :   tx_ring->cached_prod = tx_seq+1U;
     928          18 :   ctx->metrics.tx_submit_cnt++;
     929          18 :   ctx->metrics.tx_bytes_total += sz;
     930          18 :   if( ctx->tx_op.use_gre ) ctx->metrics.tx_gre_cnt++;
     931          18 :   fd_net_flusher_inc( ctx->tx_flusher+xsk_idx, fd_tickcount() );
     932          18 : }
     933             : 
     934             : /* net_rx_packet is called when a new Ethernet frame is available.
     935             :    Attempts to copy out the frame to a downstream tile. */
     936             : 
     937             : static void
     938             : net_rx_packet( fd_net_ctx_t * ctx,
     939             :                ulong          umem_off,
     940             :                ulong          sz,
     941          27 :                uint *         freed_chunk ) {
     942             : 
     943          27 :   if( FD_UNLIKELY( sz<sizeof(fd_eth_hdr_t)+sizeof(fd_ip4_hdr_t)+sizeof(fd_udp_hdr_t) ) ) {
     944           0 :     FD_DTRACE_PROBE( net_tile_err_rx_undersz );
     945           0 :     ctx->metrics.rx_undersz_cnt++;
     946           0 :     return;
     947           0 :   }
     948             : 
     949          27 :   uchar        * packet     = (uchar *)ctx->umem + umem_off;
     950          27 :   uchar const  * packet_end = packet + sz;
     951          27 :   fd_ip4_hdr_t * iphdr      = (fd_ip4_hdr_t *)(packet + sizeof(fd_eth_hdr_t));
     952             : 
     953          27 :   if( FD_UNLIKELY( ((fd_eth_hdr_t *)packet)->net_type!=fd_ushort_bswap( FD_ETH_HDR_TYPE_IP ) ) ) return;
     954             : 
     955          27 :   int is_packet_gre = 0;
     956             :   /* Discard the GRE overhead (outer iphdr and gre hdr) */
     957          27 :   if( iphdr->protocol == FD_IP4_HDR_PROTOCOL_GRE ) {
     958          15 :     if( FD_UNLIKELY( !ctx->gre_tunnel_ip[0] ) ) { /* if the first entry is 0, they all are */
     959           0 :       ctx->metrics.rx_gre_ignored_cnt++;
     960           0 :       return;
     961           0 :     }
     962          15 :     ulong gre_ipver = FD_IP4_GET_VERSION( *iphdr );
     963          15 :     ulong gre_iplen = FD_IP4_GET_LEN( *iphdr );
     964          15 :     if( FD_UNLIKELY( gre_ipver!=0x4 || gre_iplen<20 ) ) {
     965           0 :       FD_DTRACE_PROBE( net_tile_err_rx_noip );
     966           0 :       ctx->metrics.rx_gre_inv_pkt_cnt++; /* drop IPv6 packets */
     967           0 :       return;
     968           0 :     }
     969             : 
     970          15 :     int found = 0;
     971          75 :     for( ulong i=0UL; i<MAX_GRE_CNT; i++ ) found |= (iphdr->saddr==ctx->gre_tunnel_ip[i]);
     972          15 :     if( FD_UNLIKELY( (!found) | (iphdr->saddr==0U) ) ) {
     973           3 :       ctx->metrics.rx_src_addr_invalid_cnt++;
     974           3 :       return;
     975           3 :     }
     976             : 
     977          12 :     ulong overhead = gre_iplen + sizeof(fd_gre_hdr_t);
     978          12 :     if( FD_UNLIKELY( (uchar *)iphdr+overhead+sizeof(fd_ip4_hdr_t)>packet_end ) ) {
     979           0 :       FD_DTRACE_PROBE( net_tile_err_rx_undersz );
     980           0 :       ctx->metrics.rx_undersz_cnt++;  /* inner ip4 header invalid */
     981           0 :       return;
     982           0 :     }
     983             : 
     984             :     /* The new iphdr is where the inner iphdr was. Copy over the eth_hdr */
     985          12 :     iphdr              = (fd_ip4_hdr_t *)((uchar *)iphdr + overhead);
     986          12 :     uchar * new_packet = (uchar *)iphdr - sizeof(fd_eth_hdr_t);
     987          12 :     fd_memcpy( new_packet, packet, sizeof(fd_eth_hdr_t) );
     988          12 :     sz                 -= overhead;
     989          12 :     packet             = new_packet;
     990          12 :     umem_off           = (ulong)( packet - (uchar *)ctx->umem );
     991          12 :     is_packet_gre      = 1;
     992          12 :   }
     993             : 
     994             :   /* Translate packet to UMEM frame index */
     995          24 :   ulong chunk       = ctx->umem_chunk0 + (umem_off>>FD_CHUNK_LG_SZ);
     996          24 :   ulong ctl         = umem_off & 0x3fUL;
     997             : 
     998             :   /* Filter for UDP/IPv4 packets. */
     999          24 :   ulong ipver = FD_IP4_GET_VERSION( *iphdr );
    1000          24 :   ulong iplen = FD_IP4_GET_LEN    ( *iphdr );
    1001          24 :   if( FD_UNLIKELY( ipver!=0x4 || iplen<20 ||
    1002          24 :                    iphdr->protocol!=FD_IP4_HDR_PROTOCOL_UDP ) ) {
    1003           0 :     FD_DTRACE_PROBE( net_tile_err_rx_noip );
    1004           0 :     ctx->metrics.rx_undersz_cnt++; /* drop IPv6 packets */
    1005           0 :     return;
    1006           0 :   }
    1007             : 
    1008          24 :   uchar const * udp = (uchar *)iphdr + iplen;
    1009          24 :   if( FD_UNLIKELY( udp+sizeof(fd_udp_hdr_t) > packet_end ) ) {
    1010           0 :     FD_DTRACE_PROBE( net_tile_err_rx_undersz );
    1011           0 :     ctx->metrics.rx_undersz_cnt++;
    1012           0 :     return;
    1013           0 :   }
    1014             : 
    1015          24 :   fd_udp_hdr_t const * udp_hdr = (fd_udp_hdr_t const *)udp;
    1016          24 :   ulong        const   udp_sz  = fd_ushort_bswap( udp_hdr->net_len );
    1017          24 :   if( FD_UNLIKELY( (udp_sz<sizeof(fd_udp_hdr_t)) | (udp+udp_sz>packet_end) ) ) {
    1018           6 :     FD_DTRACE_PROBE( net_tile_err_rx_undersz );
    1019           6 :     ctx->metrics.rx_undersz_cnt++;
    1020           6 :     return;
    1021           6 :   }
    1022             : 
    1023             :   /* Extract IP dest addr and UDP src/dest port */
    1024          18 :   uint   ip_srcaddr   =  iphdr->saddr;
    1025          18 :   ushort udp_srcport  =  fd_ushort_bswap( udp_hdr->net_sport );
    1026          18 :   ushort udp_dstport  =  fd_ushort_bswap( udp_hdr->net_dport );
    1027             : 
    1028          18 :   if( FD_UNLIKELY( fd_ip4_addr_is_mcast( ip_srcaddr ) ) ) {
    1029           0 :     ctx->metrics.rx_src_addr_invalid_cnt++;
    1030           0 :     return;
    1031           0 :   }
    1032             : 
    1033          18 :   FD_DTRACE_PROBE_4( net_tile_pkt_rx, ip_srcaddr, udp_srcport, udp_dstport, sz );
    1034             : 
    1035             :   /* Route packet to downstream tile */
    1036          18 :   ushort proto;
    1037          18 :   fd_net_out_ctx_t * out;
    1038          18 :   if(      FD_UNLIKELY( udp_dstport==ctx->shred_listen_port ) ) {
    1039          18 :     proto = DST_PROTO_SHRED;
    1040          18 :     out = ctx->shred_out;
    1041          18 :   } else if( FD_UNLIKELY( udp_dstport==ctx->quic_transaction_listen_port ) ) {
    1042           0 :     proto = DST_PROTO_TPU_QUIC;
    1043           0 :     out = ctx->quic_out;
    1044           0 :   } else if( FD_UNLIKELY( udp_dstport==ctx->legacy_transaction_listen_port ) ) {
    1045           0 :     proto = DST_PROTO_TPU_UDP;
    1046           0 :     out = ctx->quic_out;
    1047           0 :   } else if( FD_UNLIKELY( udp_dstport==ctx->gossip_listen_port ) ) {
    1048           0 :     proto = DST_PROTO_GOSSIP;
    1049           0 :     out = ctx->gossvf_out;
    1050           0 :   } else if( FD_UNLIKELY( udp_dstport==ctx->repair_client_listen_port ) ) {
    1051           0 :     proto = DST_PROTO_REPAIR;
    1052           0 :     if( FD_UNLIKELY( sz == REPAIR_PING_SZ ) ) out = ctx->repair_out; /* ping-pong */
    1053           0 :     else                                      out = ctx->shred_out;
    1054           0 :   } else if( FD_UNLIKELY( udp_dstport==ctx->repair_serve_listen_port ) ) {
    1055           0 :     if( FD_UNLIKELY( !ctx->rserve_enabled ) ) return;
    1056           0 :     proto = DST_PROTO_RSERVE;
    1057           0 :     out = ctx->rserve_out;
    1058           0 :   } else if( FD_UNLIKELY( udp_dstport==ctx->txsend_src_port ) ) {
    1059           0 :     proto = DST_PROTO_SEND;
    1060           0 :     out = ctx->txsend_out;
    1061           0 :   } else {
    1062           0 :     FD_LOG_ERR(( "Firedancer received a UDP packet on port %hu which was not expected. "
    1063           0 :                   "Only the following ports should be configured to forward packets: "
    1064           0 :                   "%hu, %hu, %hu, %hu, %hu, %hu (excluding any 0 ports, which can be ignored)."
    1065           0 :                   "Please report this error to Firedancer maintainers.",
    1066           0 :                   udp_dstport,
    1067           0 :                   ctx->shred_listen_port,
    1068           0 :                   ctx->quic_transaction_listen_port,
    1069           0 :                   ctx->legacy_transaction_listen_port,
    1070           0 :                   ctx->gossip_listen_port,
    1071           0 :                   ctx->repair_client_listen_port,
    1072           0 :                   ctx->repair_serve_listen_port ));
    1073           0 :   }
    1074             : 
    1075             :   /* tile can decide how to partition based on src ip addr and src port */
    1076          18 :   ulong sig              = fd_disco_netmux_sig( ip_srcaddr, udp_srcport, ip_srcaddr, proto, 14UL+8UL+iplen );
    1077             : 
    1078             :   /* Peek the mline for an old frame */
    1079          18 :   fd_frag_meta_t * mline = out->mcache + fd_mcache_line_idx( out->seq, out->depth );
    1080          18 :   *freed_chunk           = mline->chunk;
    1081             : 
    1082             :   /* Overwrite the mline with the new frame */
    1083          18 :   ulong tspub            = (ulong)fd_frag_meta_ts_comp( fd_tickcount() );
    1084          18 : # if FD_HAS_AVX
    1085          18 :   fd_mcache_publish_avx( out->mcache, out->depth, out->seq, sig, chunk, sz, ctl, 0, tspub );
    1086             : # else
    1087             :   fd_mcache_publish( out->mcache, out->depth, out->seq, sig, chunk, sz, ctl, 0, tspub );
    1088             : # endif
    1089             : 
    1090             :   /* Wind up for the next iteration */
    1091          18 :   out->seq               = fd_seq_inc( out->seq, 1UL );
    1092             : 
    1093          18 :   if( is_packet_gre ) ctx->metrics.rx_gre_cnt++;
    1094          18 :   ctx->metrics.rx_pkt_cnt++;
    1095          18 :   ctx->metrics.rx_bytes_total += sz;
    1096          18 : }
    1097             : 
    1098             : /* net_comp_event is called when an XDP TX frame is free again. */
    1099             : 
    1100             : static void
    1101             : net_comp_event( fd_net_ctx_t * ctx,
    1102             :                 fd_xsk_t *     xsk,
    1103           0 :                 uint           comp_seq ) {
    1104             : 
    1105             :   /* Locate the incoming frame */
    1106             : 
    1107           0 :   fd_xdp_ring_t * comp_ring  = &xsk->ring_cr;
    1108           0 :   uint            comp_mask  = comp_ring->depth - 1U;
    1109           0 :   ulong           frame      = FD_VOLATILE_CONST( comp_ring->frame_ring[ comp_seq&comp_mask ] );
    1110           0 :   ulong const     frame_mask = FD_NET_MTU - 1UL;
    1111           0 :   FD_STATIC_ASSERT( FD_ULONG_IS_POW2( FD_NET_MTU ), "FD_NET_MTU must be a power of two" );
    1112           0 :   if( FD_UNLIKELY( frame+FD_NET_MTU > ctx->umem_sz ) ) {
    1113           0 :     FD_LOG_ERR(( "Bounds check failed: frame=0x%lx umem_sz=0x%lx",
    1114           0 :                  frame, (ulong)ctx->umem_sz ));
    1115           0 :   }
    1116             : 
    1117             :   /* Check if we have space to return the freed frame */
    1118             : 
    1119           0 :   fd_net_free_ring_t * free      = &ctx->free_tx;
    1120           0 :   ulong                free_prod = free->prod;
    1121           0 :   ulong                free_mask = free->depth - 1UL;
    1122           0 :   ulong                free_cons = free->cons;
    1123           0 :   long                 free_cnt = fd_seq_diff( free_prod, free_cons );
    1124           0 :   FD_TEST( free_prod >= free_cons );
    1125           0 :   if( FD_UNLIKELY( free_cnt>=(long)free->depth ) ) return; /* blocked */
    1126             : 
    1127           0 :   free->queue[ free_prod&free_mask ] = (ulong)ctx->umem + (frame & (~frame_mask));
    1128           0 :   free->prod = fd_seq_inc( free_prod, 1UL );
    1129             : 
    1130             :   /* Wind up for next iteration */
    1131             : 
    1132           0 :   comp_ring->cached_cons = comp_seq+1U;
    1133           0 :   ctx->metrics.tx_complete_cnt++;
    1134           0 : }
    1135             : 
    1136             : /* net_rx_event is called when a new XDP RX frame is available.  Calls
    1137             :    net_rx_packet, then returns the packet back to the kernel via the fill
    1138             :    ring.  */
    1139             : 
    1140             : static void
    1141             : net_rx_event( fd_net_ctx_t * ctx,
    1142             :               fd_xsk_t *     xsk,
    1143          27 :               uint           rx_seq ) {
    1144             :   /* Locate the incoming frame */
    1145             : 
    1146          27 :   fd_xdp_ring_t * rx_ring = &xsk->ring_rx;
    1147          27 :   uint            rx_mask = rx_ring->depth - 1U;
    1148          27 :   struct xdp_desc frame   = FD_VOLATILE_CONST( rx_ring->packet_ring[ rx_seq&rx_mask ] );
    1149             : 
    1150          27 :   if( FD_UNLIKELY( frame.len>FD_NET_MTU ) )
    1151           0 :     FD_LOG_ERR(( "received a UDP packet with a too large payload (%u)", frame.len ));
    1152             : 
    1153             :   /* Check if we have space in the fill ring to free the frame */
    1154             : 
    1155          27 :   fd_xdp_ring_t * fill_ring  = &xsk->ring_fr;
    1156          27 :   if( FD_UNLIKELY( fd_xdp_ring_full( fill_ring ) ) ) {
    1157           0 :     ctx->metrics.rx_fill_blocked_cnt++;
    1158           0 :     return; /* blocked */
    1159           0 :   }
    1160             : 
    1161             :   /* Pass it to the receive handler */
    1162             : 
    1163          27 :   uint freed_chunk = (uint)( ctx->umem_chunk0 + (frame.addr>>FD_CHUNK_LG_SZ) );
    1164          27 :   net_rx_packet( ctx, frame.addr, frame.len, &freed_chunk );
    1165          27 :   FD_COMPILER_MFENCE();
    1166          27 :   rx_ring->cached_cons = rx_seq+1U;
    1167             : 
    1168             :   /* Every RX operation returns one frame to the FILL ring.  If the
    1169             :      packet was forwarded to a downstream ring, the newly shadowed frame
    1170             :      is returned.  Otherwise, the frame just received is returned. */
    1171             : 
    1172          27 :   if( FD_UNLIKELY( ( freed_chunk < ctx->umem_chunk0 ) |
    1173          27 :                     ( freed_chunk > ctx->umem_wmark ) ) ) {
    1174           0 :     FD_LOG_CRIT(( "mcache corruption detected: chunk=%u chunk0=%u wmark=%u",
    1175           0 :                   freed_chunk, ctx->umem_chunk0, ctx->umem_wmark ));
    1176           0 :   }
    1177             : 
    1178          27 :   FD_STATIC_ASSERT( FD_ULONG_IS_POW2( FD_NET_MTU ), "FD_NET_MTU must be a power of two" );
    1179          27 :   uint  fill_prod  = fill_ring->cached_prod;
    1180          27 :   uint  fill_mask  = (fill_ring->depth)-1U;
    1181          27 :   ulong frame_mask = FD_NET_MTU - 1UL;
    1182          27 :   ulong freed_off  = (freed_chunk - ctx->umem_chunk0)<<FD_CHUNK_LG_SZ;
    1183          27 :   fill_ring->frame_ring[ fill_prod&fill_mask ] = freed_off & (~frame_mask);
    1184          27 :   fill_ring->cached_prod = fill_prod+1U;
    1185          27 : }
    1186             : 
    1187             : static void
    1188             : before_credit_softirq( fd_net_ctx_t *      ctx,
    1189             :                        int *               charge_busy,
    1190             :                        uint                rr_idx,
    1191          27 :                        fd_xsk_t *          rr_xsk ) {
    1192             : 
    1193          27 :   net_tx_periodic_wakeup( ctx, rr_idx, fd_tickcount(), charge_busy );
    1194             : 
    1195             :   /* Fire RX event if we have RX desc avail */
    1196          27 :   if( !fd_xdp_ring_empty( &rr_xsk->ring_rx, FD_XDP_RING_ROLE_CONS ) ) {
    1197          27 :     *charge_busy = 1;
    1198          27 :     net_rx_event( ctx, rr_xsk, rr_xsk->ring_rx.cached_cons );
    1199          27 :   } else {
    1200           0 :     net_rx_wakeup( ctx, rr_xsk, charge_busy );
    1201             : 
    1202             :     /* Iterate onto the next NAPI queue. */
    1203           0 :     ctx->rr_idx++;
    1204           0 :     ctx->rr_idx = fd_uint_if( ctx->rr_idx>=ctx->xsk_cnt, 0, ctx->rr_idx );
    1205           0 :   }
    1206          27 : }
    1207             : 
    1208             : static int
    1209             : net_prefbusy_poll_ready( fd_xsk_t *         rr_xsk,
    1210             :                          fd_net_flusher_t * flusher,
    1211           0 :                          long               now ) {
    1212             : 
    1213           0 :   if( FD_LIKELY( now < ( flusher->prefbusy_last_poll_ticks + flusher->prefbusy_min_interval_ticks ) ) ) return 0;
    1214           0 :   if( FD_UNLIKELY( now > ( flusher->prefbusy_last_poll_ticks + flusher->prefbusy_stall_timeout_ticks ) ) ) return 1;
    1215             : 
    1216           0 :   int rx_empty = fd_xdp_ring_empty( &rr_xsk->ring_rx, FD_XDP_RING_ROLE_CONS );
    1217             : 
    1218           0 :   return rx_empty;
    1219           0 : }
    1220             : 
    1221             : static void
    1222             : net_prefbusy_poll_flush( fd_net_flusher_t * flusher,
    1223           0 :                          long               now ) {
    1224           0 :   flusher->prefbusy_last_poll_ticks = now;
    1225           0 : }
    1226             : 
    1227             : static void
    1228             : before_credit_prefbusy( fd_net_ctx_t *      ctx,
    1229             :                         int *               charge_busy,
    1230             :                         uint                rr_idx,
    1231           0 :                         fd_xsk_t *          rr_xsk ) {
    1232             : 
    1233           0 :   fd_net_flusher_t * flusher = ctx->tx_flusher+rr_idx;
    1234           0 :   if( FD_UNLIKELY( net_prefbusy_poll_ready( rr_xsk, flusher, fd_tickcount() ) ) ) {
    1235             :     /* NAPI needs to be polled to process new TX from
    1236             :        Firedancer's net tile and process new RX from the NIC. */
    1237             : 
    1238           0 :     FD_VOLATILE( *rr_xsk->ring_tx.prod ) = rr_xsk->ring_tx.cached_prod; /* write-back local copies to fseqs */
    1239           0 :     FD_VOLATILE( *rr_xsk->ring_cr.cons ) = rr_xsk->ring_cr.cached_cons;
    1240           0 :     FD_VOLATILE( *rr_xsk->ring_rx.cons ) = rr_xsk->ring_rx.cached_cons;
    1241           0 :     FD_VOLATILE( *rr_xsk->ring_fr.prod ) = rr_xsk->ring_fr.cached_prod;
    1242             : 
    1243           0 :     if( FD_UNLIKELY( -1==sendto( rr_xsk->xsk_fd, NULL, 0, MSG_DONTWAIT, NULL, 0 ) ) ) {
    1244           0 :       if( FD_UNLIKELY( net_is_fatal_xdp_error( errno ) ) ) {
    1245           0 :         FD_LOG_ERR(( "xsk sendto failed xsk_fd=%d (%i-%s)", rr_xsk->xsk_fd, errno, fd_io_strerror( errno ) ));
    1246           0 :       }
    1247           0 :       if( FD_UNLIKELY( errno!=EAGAIN ) ) {
    1248           0 :         long ts = fd_log_wallclock();
    1249           0 :         if( ts > rr_xsk->log_suppress_until_ns ) {
    1250           0 :           FD_LOG_WARNING(( "xsk sendto failed xsk_fd=%d (%i-%s)", rr_xsk->xsk_fd, errno, fd_io_strerror( errno ) ));
    1251           0 :           rr_xsk->log_suppress_until_ns = ts + (long)1e9;
    1252           0 :         }
    1253           0 :       }
    1254           0 :     }
    1255             :     /* Since xsk sendmsg in prefbusy mode drives both rx and tx, both are incremented */
    1256           0 :     ctx->metrics.xsk_tx_wakeup_cnt++;
    1257           0 :     ctx->metrics.xsk_rx_wakeup_cnt++;
    1258             : 
    1259           0 :     net_prefbusy_poll_flush( flusher, fd_tickcount() );
    1260           0 :   }
    1261             : 
    1262             :   /* Process new RX from xsk ring if there is any. */
    1263           0 :   if( !fd_xdp_ring_empty( &rr_xsk->ring_rx, FD_XDP_RING_ROLE_CONS ) ) {
    1264           0 :     *charge_busy = 1;
    1265           0 :     net_rx_event( ctx, rr_xsk, rr_xsk->ring_rx.cached_cons );
    1266           0 :   }
    1267             :   /* Iterate onto the next NAPI queue. */
    1268           0 :   ctx->rr_idx++;
    1269           0 :   ctx->rr_idx = fd_uint_if( ctx->rr_idx>=ctx->xsk_cnt, 0, ctx->rr_idx );
    1270           0 : }
    1271             : 
    1272             : /* before_credit is called every loop iteration. */
    1273             : 
    1274             : static void
    1275             : before_credit( fd_net_ctx_t *      ctx,
    1276             :                fd_stem_context_t * stem,
    1277          27 :                int *               charge_busy ) {
    1278          27 :   (void)stem;
    1279             :   /* A previous send attempt was overrun.  A corrupt copy of the packet was
    1280             :      placed into an XDP frame, but the frame was not yet submitted to the
    1281             :      TX ring.  Return the tx buffer to the free list. */
    1282             : 
    1283          27 :   if( ctx->tx_op.frame ) {
    1284           0 :     *charge_busy = 1;
    1285           0 :     fd_net_free_ring_t * free      = &ctx->free_tx;
    1286           0 :     ulong                alloc_seq = free->prod;
    1287           0 :     free->queue[ alloc_seq % free->depth ] = (ulong)ctx->tx_op.frame;
    1288           0 :     free->prod = fd_seq_inc( alloc_seq, 1UL );
    1289           0 :     ctx->tx_op.frame = NULL;
    1290           0 :   }
    1291             : 
    1292             :   /* Check if new packets are available or if TX frames are free again
    1293             :      (Round-robin through sockets) */
    1294             : 
    1295          27 :   uint       rr_idx = ctx->rr_idx;
    1296          27 :   fd_xsk_t * rr_xsk = &ctx->xsk[ rr_idx ];
    1297             : 
    1298          27 :   if( FD_LIKELY( !rr_xsk->prefbusy_poll_enabled ) ) {
    1299             :     /* Default poll mode which relies on irqs and wakeups */
    1300          27 :     before_credit_softirq( ctx, charge_busy, rr_idx, rr_xsk );
    1301          27 :   } else {
    1302           0 :     before_credit_prefbusy( ctx, charge_busy, rr_idx, rr_xsk );
    1303           0 :   }
    1304             : 
    1305             :   /* Fire comp event if we have comp desc avail */
    1306          27 :   if( !fd_xdp_ring_empty( &rr_xsk->ring_cr, FD_XDP_RING_ROLE_CONS ) ) {
    1307           0 :     *charge_busy = 1;
    1308           0 :     net_comp_event( ctx, rr_xsk, rr_xsk->ring_cr.cached_cons );
    1309           0 :   }
    1310          27 : }
    1311             : 
    1312             : /* net_xsk_bootstrap assigns UMEM frames to the FILL ring. */
    1313             : 
    1314             : static ulong
    1315             : net_xsk_bootstrap( fd_net_ctx_t * ctx,
    1316             :                    uint           xsk_idx,
    1317           0 :                    ulong          frame_off ) {
    1318           0 :   fd_xsk_t * xsk = &ctx->xsk[ xsk_idx ];
    1319             : 
    1320           0 :   ulong const frame_sz  = FD_NET_MTU;
    1321           0 :   ulong const fr_depth  = ctx->xsk[ xsk_idx ].ring_fr.depth/2UL;
    1322             : 
    1323           0 :   fd_xdp_ring_t * fill      = &xsk->ring_fr;
    1324           0 :   uint            fill_prod = fill->cached_prod;
    1325           0 :   for( ulong j=0UL; j<fr_depth; j++ ) {
    1326           0 :     fill->frame_ring[ j ] = frame_off;
    1327           0 :     frame_off += frame_sz;
    1328           0 :   }
    1329           0 :   FD_VOLATILE( *fill->prod ) = fill->cached_prod = fill_prod + (uint)fr_depth;
    1330             : 
    1331           0 :   return frame_off;
    1332           0 : }
    1333             : 
    1334             : /* FIXME source MAC address from netlnk tile instead */
    1335             : 
    1336             : static void
    1337             : interface_addrs( const char * interface,
    1338             :                  uchar *      mac,
    1339           0 :                  uint *       ip4_addr ) {
    1340           0 :   int fd = socket( AF_INET, SOCK_DGRAM, 0 );
    1341           0 :   struct ifreq ifr;
    1342           0 :   ifr.ifr_addr.sa_family = AF_INET;
    1343             : 
    1344           0 :   strncpy( ifr.ifr_name, interface, IFNAMSIZ );
    1345           0 :   if( FD_UNLIKELY( ioctl( fd, SIOCGIFHWADDR, &ifr ) ) )
    1346           0 :     FD_LOG_ERR(( "could not get MAC address of interface `%s`: (%i-%s)", interface, errno, fd_io_strerror( errno ) ));
    1347           0 :   fd_memcpy( mac, ifr.ifr_hwaddr.sa_data, 6 );
    1348             : 
    1349           0 :   if( FD_UNLIKELY( ioctl( fd, SIOCGIFADDR, &ifr ) ) )
    1350           0 :     FD_LOG_ERR(( "could not get IP address of interface `%s`: (%i-%s)", interface, errno, fd_io_strerror( errno ) ));
    1351           0 :   *ip4_addr = ((struct sockaddr_in *)fd_type_pun( &ifr.ifr_addr ))->sin_addr.s_addr;
    1352             : 
    1353           0 :   if( FD_UNLIKELY( close(fd) ) )
    1354           0 :     FD_LOG_ERR(( "could not close socket (%i-%s)", errno, fd_io_strerror( errno ) ));
    1355           0 : }
    1356             : 
    1357             : /* privileged_init does the following initialization steps:
    1358             : 
    1359             :    - Create an AF_XDP socket
    1360             :    - Map XDP metadata rings
    1361             :    - Register UMEM data region with socket
    1362             :    - Insert AF_XDP socket into xsk_map
    1363             : 
    1364             :    Net tile 0 also runs fd_xdp_install and repeats the above step for
    1365             :    the loopback device.  (Unless the main interface is already loopback)
    1366             : 
    1367             :    Kernel object references:
    1368             : 
    1369             :      BPF_LINK file descriptor
    1370             :       |
    1371             :       +-> XDP program installation on NIC
    1372             :       |    |
    1373             :       |    +-> XDP program <-- BPF_PROG file descriptor (prog_fd)
    1374             :       |
    1375             :       +-> XSKMAP object <-- BPF_MAP file descriptor (xsk_map) */
    1376             : 
    1377             : FD_FN_UNUSED static void
    1378             : privileged_init( fd_topo_t const *      topo,
    1379           0 :                  fd_topo_tile_t const * tile ) {
    1380           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    1381             : 
    1382           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    1383           0 :   fd_net_ctx_t * ctx     = FD_SCRATCH_ALLOC_APPEND( l, alignof(fd_net_ctx_t), sizeof(fd_net_ctx_t) );
    1384           0 :   ulong *        free_tx = FD_SCRATCH_ALLOC_APPEND( l, alignof(ulong), tile->xdp.free_ring_depth * sizeof(ulong) );;
    1385             : 
    1386           0 :   fd_memset( ctx, 0, sizeof(fd_net_ctx_t) );
    1387             : 
    1388           0 :   interface_addrs( tile->xdp.if_virt, ctx->src_mac_addr, &ctx->default_address );
    1389           0 :   ctx->if_virt = if_nametoindex( tile->xdp.if_virt ); FD_TEST( ctx->if_virt );
    1390             : 
    1391             :   /* Load up dcache containing UMEM */
    1392             : 
    1393           0 :   void * const dcache_mem          = fd_topo_obj_laddr( topo, tile->net.umem_dcache_obj_id );
    1394           0 :   void * const umem                = fd_dcache_join( dcache_mem );
    1395           0 :   ulong  const umem_dcache_data_sz = fd_dcache_data_sz( umem );
    1396           0 :   ulong  const umem_frame_sz       = 2048UL;
    1397           0 :   ulong  const umem_sz             = fd_ulong_align_dn( umem_dcache_data_sz, umem_frame_sz );
    1398             : 
    1399             :   /* Derive chunk bounds */
    1400             : 
    1401           0 :   void * const umem_base   = fd_wksp_containing( dcache_mem );
    1402           0 :   ulong  const umem_chunk0 = ( (ulong)umem - (ulong)umem_base )>>FD_CHUNK_LG_SZ;
    1403           0 :   ulong  const umem_wmark  = umem_chunk0 + ( ( umem_sz-umem_frame_sz )>>FD_CHUNK_LG_SZ );
    1404             : 
    1405           0 :   if( FD_UNLIKELY( umem_chunk0>UINT_MAX || umem_wmark>UINT_MAX || umem_chunk0>umem_wmark ) ) {
    1406           0 :     FD_LOG_ERR(( "Calculated invalid UMEM bounds [%lu,%lu]", umem_chunk0, umem_wmark ));
    1407           0 :   }
    1408             : 
    1409           0 :   if( FD_UNLIKELY( !umem_base ) ) FD_LOG_ERR(( "UMEM dcache is not in a workspace" ));
    1410             : 
    1411           0 :   ctx->umem        = umem;
    1412           0 :   ctx->umem_sz     = umem_sz;
    1413           0 :   ctx->umem_chunk0 = (uint)umem_chunk0;
    1414           0 :   ctx->umem_wmark  = (uint)umem_wmark;
    1415             : 
    1416           0 :   ctx->free_tx.queue = free_tx;
    1417           0 :   ctx->free_tx.depth = tile->xdp.xdp_tx_queue_size;
    1418             : 
    1419             :   /* Create and install XSKs */
    1420             : 
    1421           0 :   uint if_phys_if_idx = if_nametoindex( tile->xdp.if_phys );
    1422           0 :   if( FD_UNLIKELY( !if_phys_if_idx ) ) FD_LOG_ERR(( "if_nametoindex(%s) failed", tile->xdp.if_phys ));
    1423             : 
    1424           0 :   fd_xsk_params_t params0 = {
    1425           0 :     .if_idx      = if_phys_if_idx,
    1426           0 :     .if_queue_id = tile->xdp.if_queue,
    1427             : 
    1428             :     /* Some kernels produce EOPNOTSUP errors on sendto calls when
    1429             :        starting up without either XDP_ZEROCOPY or XDP_COPY
    1430             :        (e.g. 5.14.0-503.23.1.el9_5 with i40e) */
    1431           0 :     .bind_flags  = tile->xdp.zero_copy ? XDP_ZEROCOPY : XDP_COPY,
    1432             : 
    1433           0 :     .prefbusy_time_budget_micros = PREFBUSY_TIME_BUDGET_MICROS,
    1434             : 
    1435           0 :     .prefbusy_rx_budget = PREFBUSY_RX_BUDGET,
    1436             : 
    1437           0 :     .fr_depth  = tile->xdp.xdp_rx_queue_size*2,
    1438           0 :     .rx_depth  = tile->xdp.xdp_rx_queue_size,
    1439           0 :     .cr_depth  = tile->xdp.xdp_tx_queue_size,
    1440           0 :     .tx_depth  = tile->xdp.xdp_tx_queue_size,
    1441             : 
    1442           0 :     .umem_addr = umem,
    1443           0 :     .frame_sz  = umem_frame_sz,
    1444           0 :     .umem_sz   = umem_sz,
    1445             : 
    1446           0 :     .core_dump = tile->xdp.xsk_core_dump,
    1447           0 :   };
    1448             : 
    1449           0 :   fd_cstr_ncpy( params0.poll_mode, tile->xdp.poll_mode, sizeof(params0.poll_mode) );
    1450             : 
    1451             :   /* Re-derive XDP file descriptors */
    1452             : 
    1453           0 :   fd_xdp_fds_t xdp_fds[ FD_TOPO_XDP_FDS_MAX ];
    1454           0 :   uint         xdp_fds_cnt = FD_TOPO_XDP_FDS_MAX;
    1455           0 :   fd_topo_install_xdp( topo, xdp_fds, &xdp_fds_cnt, 0U, /* dry_run */ 1 );
    1456             : 
    1457           0 :   int xsk_map_fd = -1;
    1458           0 :   for( uint i=0U; i<xdp_fds_cnt; i++ ) {
    1459           0 :     if( xdp_fds[ i ].if_idx==if_phys_if_idx ) {
    1460           0 :       xsk_map_fd              = xdp_fds[ i ].xsk_map_fd;
    1461           0 :       ctx->prog_link_fds[ 0 ] = xdp_fds[ i ].prog_link_fd;
    1462           0 :       xdp_fds[ i ].prog_link_fd = -1; /* mark as used */
    1463           0 :       break;
    1464           0 :     }
    1465           0 :   }
    1466           0 :   FD_TEST( xsk_map_fd>=0 );
    1467             : 
    1468             :   /* Init XSK */
    1469           0 :   if( FD_UNLIKELY( !fd_xsk_init( &ctx->xsk[ 0 ], &params0 ) ) )       FD_LOG_ERR(( "failed to bind xsk for net tile %lu", tile->kind_id ));
    1470           0 :   if( FD_UNLIKELY( !fd_xsk_activate( &ctx->xsk[ 0 ], xsk_map_fd ) ) ) FD_LOG_ERR(( "failed to activate xsk for net tile %lu", tile->kind_id ));
    1471           0 :   ctx->xsk_cnt = 1;
    1472             : 
    1473             :   /* Networking tile at index 0 also binds to loopback (only queue 0 available on lo) */
    1474             : 
    1475           0 :   if( FD_UNLIKELY( strcmp( tile->xdp.if_virt, "lo" ) && !tile->kind_id ) ) {
    1476           0 :     ctx->xsk_cnt = 2;
    1477             : 
    1478           0 :     uint lo_idx = if_nametoindex( "lo" );
    1479           0 :     if( FD_UNLIKELY( !lo_idx ) ) FD_LOG_ERR(( "if_nametoindex(lo) failed" ));
    1480             : 
    1481           0 :     int lo_xsk_map_fd = -1;
    1482           0 :     for( uint i=0U; i<xdp_fds_cnt; i++ ) {
    1483           0 :       if( xdp_fds[ i ].if_idx==lo_idx ) {
    1484           0 :         lo_xsk_map_fd           = xdp_fds[ i ].xsk_map_fd;
    1485           0 :         ctx->prog_link_fds[ 1 ] = xdp_fds[ i ].prog_link_fd;
    1486           0 :         xdp_fds[ i ].prog_link_fd = -1; /* mark as used */
    1487           0 :         break;
    1488           0 :       }
    1489           0 :     }
    1490           0 :     FD_TEST( lo_xsk_map_fd>=0 );
    1491             : 
    1492             :     /* init xsk 1 */
    1493           0 :     fd_xsk_params_t params1 = params0;
    1494           0 :     params1.if_idx      = lo_idx; /* probably always 1 */
    1495           0 :     params1.if_queue_id = 0;
    1496           0 :     params1.bind_flags  = 0;
    1497           0 :     if( FD_UNLIKELY( !fd_xsk_init( &ctx->xsk[ 1 ], &params1 ) ) )          FD_LOG_ERR(( "failed to bind lo_xsk" ));
    1498           0 :     if( FD_UNLIKELY( !fd_xsk_activate( &ctx->xsk[ 1 ], lo_xsk_map_fd ) ) ) FD_LOG_ERR(( "failed to activate lo_xsk" ));
    1499           0 :   }
    1500             : 
    1501             :   /* Close unused XDP fds */
    1502             : 
    1503           0 :   if( FD_UNLIKELY( fd_sandbox_gettid()==fd_sandbox_getpid() ) ) {
    1504             :     /* Kind of gross.. in single threaded mode we don't want to close the xsk_map_fd
    1505             :        since it's shared with other net tiles.  Just check for that by seeing if we
    1506             :        are the only thread in the process. */
    1507           0 :     for( uint i=0U; i<xdp_fds_cnt; i++ ) {
    1508           0 :       if( -1==close( xdp_fds[ i ].xsk_map_fd ) ) {
    1509           0 :         FD_LOG_ERR(( "close(%d) failed (%d-%s)", xsk_map_fd, errno, fd_io_strerror( errno ) ));
    1510           0 :       }
    1511           0 :       if( xdp_fds[ i ].prog_link_fd>0 &&
    1512           0 :           -1==close( xdp_fds[ i ].prog_link_fd ) ) {
    1513           0 :         FD_LOG_ERR(( "close(%d) failed (%d-%s)", xsk_map_fd, errno, fd_io_strerror( errno ) ));
    1514           0 :       }
    1515           0 :     }
    1516           0 :   }
    1517             : 
    1518           0 :   double tick_per_ns = fd_tempo_tick_per_ns( NULL );
    1519           0 :   ctx->xdp_stats_interval_ticks = (long)( FD_XDP_STATS_INTERVAL_NS * tick_per_ns );
    1520             : 
    1521           0 :   ulong scratch_top = FD_SCRATCH_ALLOC_FINI( l, scratch_align() );
    1522           0 :   if( FD_UNLIKELY( scratch_top > (ulong)scratch + scratch_footprint( tile ) ) )
    1523           0 :     FD_LOG_ERR(( "scratch overflow %lu %lu %lu", scratch_top - (ulong)scratch - scratch_footprint( tile ), scratch_top, (ulong)scratch + scratch_footprint( tile ) ));
    1524           0 : }
    1525             : 
    1526             : static void
    1527             : init_device_table( fd_net_ctx_t * ctx,
    1528             :                    void *         netdev_tbl_shm,
    1529           3 :                    void *         netdev_tbl_local ) {
    1530           3 :   FD_TEST( fd_netdev_tbl_join( &ctx->netdev_shared, netdev_tbl_shm ) );
    1531           3 :   FD_TEST( fd_netdev_tbl_new( netdev_tbl_local, NETDEV_MAX, BOND_MASTER_MAX ) );
    1532           3 :   FD_TEST( fd_netdev_tbl_join( &ctx->netdev_tbl, netdev_tbl_local ) );
    1533           3 : }
    1534             : 
    1535             : FD_FN_UNUSED static void
    1536             : unprivileged_init( fd_topo_t const *      topo,
    1537           0 :                    fd_topo_tile_t const * tile ) {
    1538           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    1539             : 
    1540           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    1541           0 :   fd_net_ctx_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof(fd_net_ctx_t), sizeof(fd_net_ctx_t) );
    1542           0 :   FD_TEST( ctx->xsk_cnt!=0 );
    1543           0 :   FD_TEST( ctx->free_tx.queue!=NULL );
    1544           0 :   (void)FD_SCRATCH_ALLOC_APPEND( l, alignof(ulong), tile->xdp.free_ring_depth * sizeof(ulong) );
    1545           0 :   void * netdev_tbl_local = FD_SCRATCH_ALLOC_APPEND( l, fd_netdev_tbl_align(), fd_netdev_tbl_footprint( NETDEV_MAX, BOND_MASTER_MAX ) );
    1546             : 
    1547           0 :   ctx->net_tile_id  = (uint)tile->kind_id;
    1548           0 :   ctx->net_tile_cnt = (uint)fd_topo_tile_name_cnt( topo, tile->name );
    1549             : 
    1550           0 :   ctx->bind_address                   = tile->net.bind_address;
    1551           0 :   ctx->shred_listen_port              = tile->net.shred_listen_port;
    1552           0 :   ctx->quic_transaction_listen_port   = tile->net.quic_transaction_listen_port;
    1553           0 :   ctx->legacy_transaction_listen_port = tile->net.legacy_transaction_listen_port;
    1554           0 :   ctx->gossip_listen_port             = tile->net.gossip_listen_port;
    1555           0 :   ctx->repair_client_listen_port      = tile->net.repair_client_listen_port;
    1556           0 :   ctx->repair_serve_listen_port       = tile->net.repair_serve_listen_port;
    1557           0 :   ctx->txsend_src_port                = tile->net.txsend_src_port;
    1558             : 
    1559             :   /* Put a bound on chunks we read from the input, to make sure they
    1560             :      are within in the data region of the workspace. */
    1561             : 
    1562           0 :   if( FD_UNLIKELY( !tile->in_cnt ) ) FD_LOG_ERR(( "net tile in link cnt is zero" ));
    1563           0 :   if( FD_UNLIKELY( tile->in_cnt>MAX_NET_INS ) ) FD_LOG_ERR(( "net tile in link cnt %lu exceeds MAX_NET_INS %lu", tile->in_cnt, MAX_NET_INS ));
    1564           0 :   FD_TEST( tile->in_cnt<=32 );
    1565           0 :   for( ulong i=0UL; i<tile->in_cnt; i++ ) {
    1566           0 :     fd_topo_link_t const * link = &topo->links[ tile->in_link_id[ i ] ];
    1567           0 :     if( FD_UNLIKELY( link->mtu!=FD_NET_MTU ) ) FD_LOG_ERR(( "net tile in link %s does not have a normal MTU", link->name ));
    1568             : 
    1569           0 :     ctx->in[ i ].mem    = topo->workspaces[ topo->objs[ link->dcache_obj_id ].wksp_id ].wksp;
    1570           0 :     ctx->in[ i ].chunk0 = fd_dcache_compact_chunk0( ctx->in[ i ].mem, link->dcache );
    1571           0 :     ctx->in[ i ].wmark  = fd_dcache_compact_wmark( ctx->in[ i ].mem, link->dcache, link->mtu );
    1572           0 :   }
    1573             : 
    1574           0 :   ctx->rserve_enabled = 0;
    1575           0 :   for( ulong i = 0; i < tile->out_cnt; i++ ) {
    1576           0 :     fd_topo_link_t const * out_link = &topo->links[ tile->out_link_id[ i  ] ];
    1577           0 :     if( strcmp( out_link->name, "net_quic" ) == 0 ) {
    1578           0 :       fd_topo_link_t const * quic_out = out_link;
    1579           0 :       ctx->quic_out->mcache = quic_out->mcache;
    1580           0 :       ctx->quic_out->sync   = fd_mcache_seq_laddr( ctx->quic_out->mcache );
    1581           0 :       ctx->quic_out->depth  = fd_mcache_depth( ctx->quic_out->mcache );
    1582           0 :       ctx->quic_out->seq    = fd_mcache_seq_query( ctx->quic_out->sync );
    1583           0 :     } else if( strcmp( out_link->name, "net_shred" ) == 0 ) {
    1584           0 :       fd_topo_link_t const * shred_out = out_link;
    1585           0 :       ctx->shred_out->mcache = shred_out->mcache;
    1586           0 :       ctx->shred_out->sync   = fd_mcache_seq_laddr( ctx->shred_out->mcache );
    1587           0 :       ctx->shred_out->depth  = fd_mcache_depth( ctx->shred_out->mcache );
    1588           0 :       ctx->shred_out->seq    = fd_mcache_seq_query( ctx->shred_out->sync );
    1589           0 :     } else if( strcmp( out_link->name, "net_gossvf" ) == 0 ) {
    1590           0 :       fd_topo_link_t const * gossip_out = out_link;
    1591           0 :       ctx->gossvf_out->mcache = gossip_out->mcache;
    1592           0 :       ctx->gossvf_out->sync   = fd_mcache_seq_laddr( ctx->gossvf_out->mcache );
    1593           0 :       ctx->gossvf_out->depth  = fd_mcache_depth( ctx->gossvf_out->mcache );
    1594           0 :       ctx->gossvf_out->seq    = fd_mcache_seq_query( ctx->gossvf_out->sync );
    1595           0 :     } else if( strcmp( out_link->name, "net_repair" ) == 0 ) {
    1596           0 :       fd_topo_link_t const * repair_out = out_link;
    1597           0 :       ctx->repair_out->mcache = repair_out->mcache;
    1598           0 :       ctx->repair_out->sync   = fd_mcache_seq_laddr( ctx->repair_out->mcache );
    1599           0 :       ctx->repair_out->depth  = fd_mcache_depth( ctx->repair_out->mcache );
    1600           0 :       ctx->repair_out->seq    = fd_mcache_seq_query( ctx->repair_out->sync );
    1601           0 :     } else if( strcmp( out_link->name, "net_netlnk" ) == 0 ) {
    1602           0 :       fd_topo_link_t const * netlink_out = out_link;
    1603           0 :       ctx->neigh4_solicit->mcache = netlink_out->mcache;
    1604           0 :       ctx->neigh4_solicit->depth  = fd_mcache_depth( ctx->neigh4_solicit->mcache );
    1605           0 :       ctx->neigh4_solicit->seq    = fd_mcache_seq_query( fd_mcache_seq_laddr( ctx->neigh4_solicit->mcache ) );
    1606           0 :     } else if( strcmp( out_link->name, "net_txsend" ) == 0 ) {
    1607           0 :       fd_topo_link_t const * txsend_out = out_link;
    1608           0 :       ctx->txsend_out->mcache = txsend_out->mcache;
    1609           0 :       ctx->txsend_out->sync   = fd_mcache_seq_laddr( ctx->txsend_out->mcache );
    1610           0 :       ctx->txsend_out->depth  = fd_mcache_depth( ctx->txsend_out->mcache );
    1611           0 :       ctx->txsend_out->seq    = fd_mcache_seq_query( ctx->txsend_out->sync );
    1612           0 :     } else if( strcmp( out_link->name, "net_rserve" ) == 0 ) {
    1613           0 :       fd_topo_link_t const * rserve_out = out_link;
    1614           0 :       ctx->rserve_out->mcache = rserve_out->mcache;
    1615           0 :       ctx->rserve_out->sync   = fd_mcache_seq_laddr( ctx->rserve_out->mcache );
    1616           0 :       ctx->rserve_out->depth  = fd_mcache_depth( ctx->rserve_out->mcache );
    1617           0 :       ctx->rserve_out->seq    = fd_mcache_seq_query( ctx->rserve_out->sync );
    1618           0 :       ctx->rserve_enabled     = 1;
    1619           0 :     } else {
    1620           0 :       FD_LOG_ERR(( "unrecognized out link `%s`", out_link->name ));
    1621           0 :     }
    1622           0 :   }
    1623             : 
    1624             :   /* Check if any of the tiles we set a listen port for do not have an outlink. */
    1625           0 :   if( FD_UNLIKELY( ctx->shred_listen_port!=0 && ctx->shred_out->mcache==NULL ) ) {
    1626           0 :     FD_LOG_ERR(( "shred listen port set but no out link was found" ));
    1627           0 :   } else if( FD_UNLIKELY( ctx->quic_transaction_listen_port!=0 && ctx->quic_out->mcache==NULL ) ) {
    1628           0 :     FD_LOG_ERR(( "quic transaction listen port set but no out link was found" ));
    1629           0 :   } else if( FD_UNLIKELY( ctx->legacy_transaction_listen_port!=0 && ctx->quic_out->mcache==NULL ) ) {
    1630           0 :     FD_LOG_ERR(( "legacy transaction listen port set but no out link was found" ));
    1631           0 :   } else if( FD_UNLIKELY( ctx->gossip_listen_port!=0 && ctx->gossvf_out->mcache==NULL ) ) {
    1632           0 :     FD_LOG_ERR(( "gossip listen port set but no out link was found" ));
    1633           0 :   } else if( FD_UNLIKELY( ctx->repair_client_listen_port!=0 && ctx->repair_out->mcache==NULL ) ) {
    1634           0 :     FD_LOG_ERR(( "repair intake port set but no out link was found" ));
    1635           0 :   } else if( FD_UNLIKELY( ctx->repair_serve_listen_port!=0 && ctx->repair_out->mcache==NULL ) ) {
    1636           0 :     FD_LOG_ERR(( "repair serve listen port set but no out link was found" ));
    1637           0 :   } else if( FD_UNLIKELY( ctx->neigh4_solicit->mcache==NULL ) ) {
    1638           0 :     FD_LOG_ERR(( "netlink request link not found" ));
    1639           0 :   } else if( FD_UNLIKELY( ctx->txsend_src_port!=0 && ctx->txsend_out->mcache==NULL ) ) {
    1640           0 :     FD_LOG_ERR(( "txsend listen port set but no out link was found" ));
    1641           0 :   }
    1642             : 
    1643           0 :   for( uint j=0U; j<2U; j++ ) {
    1644           0 :     ctx->tx_flusher[ j ].pending_wmark         = (ulong)( (double)tile->xdp.xdp_tx_queue_size * 0.7 );
    1645           0 :     ctx->tx_flusher[ j ].tail_flush_backoff    = (long)( (double)tile->xdp.tx_flush_timeout_ns * fd_tempo_tick_per_ns( NULL ) );
    1646           0 :     ctx->tx_flusher[ j ].next_tail_flush_ticks = LONG_MAX;
    1647             : 
    1648           0 :     ctx->tx_flusher[ j ].prefbusy_last_poll_ticks     = 0L;
    1649           0 :     ctx->tx_flusher[ j ].prefbusy_min_interval_ticks  = (long)( PREFBUSY_MIN_INTERVAL_NS * fd_tempo_tick_per_ns( NULL ) );
    1650           0 :     ctx->tx_flusher[ j ].prefbusy_stall_timeout_ticks = (long)( PREFBUSY_STALL_TIMEOUT_NS * fd_tempo_tick_per_ns( NULL ) );
    1651           0 :   }
    1652             : 
    1653             :   /* Join netbase objects */
    1654           0 :   FD_TEST( fd_fib4_join( ctx->fib_local, fd_topo_obj_laddr( topo, tile->xdp.fib4_local_obj_id ) ) );
    1655           0 :   FD_TEST( fd_fib4_join( ctx->fib_main, fd_topo_obj_laddr( topo, tile->xdp.fib4_main_obj_id  ) ) );
    1656             : 
    1657           0 :   ulong neigh4_obj_id = tile->xdp.neigh4_obj_id;
    1658           0 :   ulong ele_max   = fd_pod_queryf_ulong( topo->props, ULONG_MAX, "obj.%lu.ele_max",   neigh4_obj_id );
    1659           0 :   ulong probe_max = fd_pod_queryf_ulong( topo->props, ULONG_MAX, "obj.%lu.probe_max", neigh4_obj_id );
    1660           0 :   ulong seed      = fd_pod_queryf_ulong( topo->props, ULONG_MAX, "obj.%lu.seed",      neigh4_obj_id );
    1661           0 :   if( FD_UNLIKELY( (ele_max==ULONG_MAX) | (probe_max==ULONG_MAX) | (seed==ULONG_MAX) ) )
    1662           0 :     FD_LOG_ERR(( "neigh4 hmap properties not set" ));
    1663           0 :   if( FD_UNLIKELY( !fd_neigh4_hmap_join(
    1664           0 :       ctx->neigh4,
    1665           0 :       fd_topo_obj_laddr( topo, neigh4_obj_id ),
    1666           0 :       ele_max,
    1667           0 :       probe_max,
    1668           0 :       seed ) ) ) {
    1669           0 :     FD_LOG_ERR(( "fd_neigh4_hmap_join failed" ));
    1670           0 :   }
    1671             : 
    1672           0 :   init_device_table( ctx, fd_topo_obj_laddr( topo, tile->xdp.netdev_tbl_obj_id ), netdev_tbl_local );
    1673             : 
    1674             :   /* Initialize TX free ring */
    1675             : 
    1676           0 :   ulong const frame_sz  = 2048UL;
    1677           0 :   ulong       frame_off = 0UL;
    1678           0 :   ulong const tx_depth  = ctx->free_tx.depth;
    1679           0 :   for( ulong j=0; j<tx_depth; j++ ) {
    1680           0 :     ctx->free_tx.queue[ j ] = (ulong)ctx->umem + frame_off;
    1681           0 :     frame_off += frame_sz;
    1682           0 :   }
    1683           0 :   ctx->free_tx.prod = tx_depth;
    1684             : 
    1685             :   /* Initialize RX mcache chunks */
    1686             : 
    1687           0 :   for( ulong i=0UL; i<(tile->out_cnt); i++ ) {
    1688           0 :     fd_topo_link_t const * out_link = &topo->links[ tile->out_link_id[ i  ] ];
    1689           0 :     fd_frag_meta_t * mcache = out_link->mcache;
    1690           0 :     for( ulong j=0UL; j<fd_mcache_depth( mcache ); j++ ) {
    1691           0 :       mcache[ j ].chunk = (uint)( ctx->umem_chunk0 + (frame_off>>FD_CHUNK_LG_SZ) );
    1692           0 :       frame_off += frame_sz;
    1693           0 :     }
    1694           0 :   }
    1695             : 
    1696             :   /* Initialize FILL ring */
    1697             : 
    1698           0 :   int _charge_busy = 0;
    1699           0 :   for( uint j=0U; j<ctx->xsk_cnt; j++ ) {
    1700           0 :     frame_off = net_xsk_bootstrap( ctx, j, frame_off );
    1701           0 :     net_rx_wakeup( ctx, &ctx->xsk[ j ], &_charge_busy );
    1702           0 :     net_tx_wakeup( ctx, &ctx->xsk[ j ], &_charge_busy );
    1703           0 :   }
    1704             : 
    1705           0 :   if( FD_UNLIKELY( frame_off > ctx->umem_sz ) ) {
    1706           0 :     FD_LOG_ERR(( "UMEM is too small" ));
    1707           0 :   }
    1708           0 : }
    1709             : 
    1710             : FD_FN_UNUSED static ulong
    1711             : populate_allowed_seccomp( fd_topo_t const *      topo,
    1712             :                           fd_topo_tile_t const * tile,
    1713             :                           ulong                  out_cnt,
    1714           0 :                           struct sock_filter *   out ) {
    1715           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    1716           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    1717           0 :   fd_net_ctx_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof( fd_net_ctx_t ), sizeof( fd_net_ctx_t ) );
    1718             : 
    1719             :   /* A bit of a hack, if there is no loopback XSK for this tile, we still need to pass
    1720             :      two "allow" FD arguments to the net policy, so we just make them both the same. */
    1721           0 :   int allow_fd2 = ctx->xsk_cnt>1UL ? ctx->xsk[ 1 ].xsk_fd : ctx->xsk[ 0 ].xsk_fd;
    1722           0 :   FD_TEST( ctx->xsk[ 0 ].xsk_fd >= 0 && allow_fd2 >= 0 );
    1723             : 
    1724           0 :   populate_sock_filter_policy_fd_xdp_tile( out_cnt, out, (uint)fd_log_private_logfile_fd(), (uint)ctx->xsk[ 0 ].xsk_fd, (uint)allow_fd2 );
    1725           0 :   return sock_filter_policy_fd_xdp_tile_instr_cnt;
    1726           0 : }
    1727             : 
    1728             : FD_FN_UNUSED static ulong
    1729             : populate_allowed_fds( fd_topo_t const *      topo,
    1730             :                       fd_topo_tile_t const * tile,
    1731             :                       ulong                  out_fds_cnt,
    1732           0 :                       int *                  out_fds ) {
    1733           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    1734           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    1735           0 :   fd_net_ctx_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof( fd_net_ctx_t ), sizeof( fd_net_ctx_t ) );
    1736             : 
    1737           0 :   if( FD_UNLIKELY( out_fds_cnt<6UL ) ) FD_LOG_ERR(( "out_fds_cnt %lu", out_fds_cnt ));
    1738             : 
    1739           0 :   ulong out_cnt = 0UL;
    1740             : 
    1741           0 :   out_fds[ out_cnt++ ] = 2; /* stderr */
    1742           0 :   if( FD_LIKELY( -1!=fd_log_private_logfile_fd() ) )
    1743           0 :     out_fds[ out_cnt++ ] = fd_log_private_logfile_fd(); /* logfile */
    1744             : 
    1745           0 :                                       out_fds[ out_cnt++ ] = ctx->xsk[ 0 ].xsk_fd;
    1746           0 :                                       out_fds[ out_cnt++ ] = ctx->prog_link_fds[ 0 ];
    1747           0 :   if( FD_LIKELY( ctx->xsk_cnt>1UL ) ) out_fds[ out_cnt++ ] = ctx->xsk[ 1 ].xsk_fd;
    1748           0 :   if( FD_LIKELY( ctx->xsk_cnt>1UL ) ) out_fds[ out_cnt++ ] = ctx->prog_link_fds[ 1 ];
    1749           0 :   return out_cnt;
    1750           0 : }
    1751             : 
    1752           0 : #define STEM_BURST (1UL)
    1753           0 : #define STEM_LAZY ((ulong)30e3) /* 30 us */
    1754             : 
    1755           0 : #define STEM_CALLBACK_CONTEXT_TYPE  fd_net_ctx_t
    1756           0 : #define STEM_CALLBACK_CONTEXT_ALIGN alignof(fd_net_ctx_t)
    1757             : 
    1758           0 : #define STEM_CALLBACK_METRICS_WRITE       metrics_write
    1759           0 : #define STEM_CALLBACK_DURING_HOUSEKEEPING during_housekeeping
    1760           0 : #define STEM_CALLBACK_BEFORE_CREDIT       before_credit
    1761           0 : #define STEM_CALLBACK_BEFORE_FRAG         before_frag
    1762           0 : #define STEM_CALLBACK_DURING_FRAG         during_frag
    1763           0 : #define STEM_CALLBACK_AFTER_FRAG          after_frag
    1764             : 
    1765             : #include "../../stem/fd_stem.c"
    1766             : 
    1767             : #ifndef FD_TILE_TEST
    1768             : fd_topo_run_tile_t fd_tile_net = {
    1769             :   .name                     = "net",
    1770             :   .populate_allowed_seccomp = populate_allowed_seccomp,
    1771             :   .populate_allowed_fds     = populate_allowed_fds,
    1772             :   .scratch_align            = scratch_align,
    1773             :   .scratch_footprint        = scratch_footprint,
    1774             :   .privileged_init          = privileged_init,
    1775             :   .unprivileged_init        = unprivileged_init,
    1776             :   .run                      = stem_run,
    1777             : };
    1778             : #endif

Generated by: LCOV version 1.14