LCOV - code coverage report
Current view: top level - disco/net/xdp - fd_xdp_tile.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 0 697 0.0 %
Date: 2026-11-11 12:40:43 Functions: 0 63 0.0 %

          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             : #include "../fd_net_tile_private.h"
       7             : 
       8             : #include <errno.h>
       9             : #include <fcntl.h>
      10             : #include <net/if.h>
      11             : #include <netinet/in.h>
      12             : #include <sys/socket.h> /* MSG_DONTWAIT needed before importing the net seccomp filter */
      13             : #include <linux/if_xdp.h>
      14             : #include <sys/epoll.h>
      15             : 
      16             : #include "../../metrics/fd_metrics.h"
      17             : #include "../../netlink/fd_netlink_tile.h" /* neigh4_solicit */
      18             : #include "../../waker/fd_waker.h"
      19             : #include "../../topo/fd_topo.h"
      20             : 
      21             : #include "../../../waltz/ip/fd_fib4.h"
      22             : #include "../../../waltz/ip/fd_iproute.h"
      23             : #include "../../../waltz/neigh/fd_neigh4_map.h"
      24             : #include "../../../waltz/mib/fd_netdev_tbl.h"
      25             : #include "../../../waltz/xdp/fd_xdp_redirect_user.h" /* fd_xsk_activate */
      26             : #include "../../../waltz/xdp/fd_xsk.h"
      27             : #include "../../../util/log/fd_dtrace.h"
      28             : #include "../../../util/net/fd_eth.h"
      29             : #include "../../../util/net/fd_ip4.h"
      30             : #include "../../../util/net/fd_gre.h"
      31             : #include "../../../util/pod/fd_pod_format.h"
      32             : 
      33             : #include <unistd.h>
      34             : #include <linux/if.h> /* struct ifreq */
      35             : #include <sys/ioctl.h>
      36             : #include <linux/if_arp.h>
      37             : #include <linux/rtnetlink.h>
      38             : #include <linux/futex.h>
      39             : 
      40             : #define FD_SOCKADDR_IN_SZ sizeof(struct sockaddr_in)
      41             : #include "generated/fd_xdp_tile_seccomp.h"
      42             : 
      43             : 
      44             : /* FD_XDP_STATS_INTERVAL_NS controls the XDP stats refresh interval.
      45             :    This should be lower than the interval at which the metrics tile
      46             :    collects metrics. */
      47             : 
      48           0 : #define FD_XDP_STATS_INTERVAL_NS (11e6) /* 11ms */
      49             : 
      50             : /* XSK_IDX_{MAIN,LO} are the hardcoded XSK indices in ctx->xsk[ ... ].
      51             :    Only net tile 0 has XSK_IDX_LO, all net tiles have XSK_IDX_MAIN. */
      52             : 
      53           0 : #define XSK_IDX_MAIN 0
      54           0 : #define XSK_IDX_LO   1
      55             : 
      56             : /* XSK 'busy_poll_usecs' value (max amount of time
      57             :    spent spinning in a NAPI poll before returning back to
      58             :    userspace if the processing budget hasn't already ran out).
      59             : 
      60             :    64us chosen based on napibusy configuration tested and
      61             :    shown in https://lwn.net/Articles/997491/ Linux patch
      62             :    cover letter.  Chosen over fullbusy since for Firedancer
      63             :    the values of fullbusy are unnecessarily high and could
      64             :    cause some extra latency to regular non-Firedancer traffic.*/
      65           0 : #define PREFBUSY_TIME_BUDGET_MICROS (64L)
      66             : 
      67             : /* PREFBUSY_RX_BUDGET is the NAPI RX processing budget (max num RX
      68             :    packets that the NIC driver can move from the hw rings into the
      69             :    XSK rings per poll).
      70             : 
      71             :    Default RX budget used by NIC drivers is 64, therefore
      72             :    it is safest to use 64 in prefbusy polling.  Also reduces
      73             :    TX starvation risks as the TX budget set by the NIC driver
      74             :    is also generally 64. */
      75           0 : #define PREFBUSY_RX_BUDGET (64L)
      76             : 
      77             : /* Min time between each prefbusy poll.  Necessary to avoid a no RX
      78             :    scenario livelocking TX with overly frequent sendto calls, given
      79             :    prefbusy polls whenever the RX queue is empty.
      80             : 
      81             :    Value chosen based on experimentation on ixgbe, mlx5 and i40e as well
      82             :    as on varying CPUs and clock speeds.  Too low -> lower max TX
      83             :    throughput when RX is very low.  Too high -> lower max RX and TX throughput. */
      84           0 : #define PREFBUSY_MIN_INTERVAL_NS (5e3) /* 5us */
      85             : 
      86             : /* Max time since last prefbusy poll before a prefbusy poll is
      87             :    forced (has been read that polling can sometimes resolve a stall).
      88             : 
      89             :    Exact value again not particularly important as this is just extra
      90             :    protection against stalls which have not been observed in testing but
      91             :    are still good to protect against since there is no cost to doing so.
      92             : 
      93             :    Value of 150us chosen since it is easily large enough to not interfere
      94             :    with standard prefbusy runtime unless there is a serious problem. */
      95           0 : #define PREFBUSY_STALL_TIMEOUT_NS (150e3) /* 150us */
      96             : 
      97             : /* fd_net_flusher_t controls the pacing of XDP sendto calls for flushing
      98             :    TX batches.  In the 'wakeup' XDP mode, no TX occurs unless the net
      99             :    tile wakes up the kernel periodically using the sendto() syscall.
     100             :    If sendto() is called too frequently, time is wasted on context
     101             :    switches.  If sendto() is called not often enough, packets are
     102             :    delayed or dropped.  sendto() calls make almost no guarantees how
     103             :    much packets are sent out, nor do they indicate when the kernel
     104             :    finishes a wakeup call (asynchronously dispatched).  The net tile
     105             :    thus uses a myriad of flush triggers that were tested for best
     106             :    performance. */
     107             : 
     108             : struct fd_net_flusher {
     109             : 
     110             :   /* Packets that were enqueued after the last sendto() wakeup are
     111             :      considered "pending".  If there are more than pending_wmark packets
     112             :      pending, a wakeup is dispatched.  Thus, this dispatch trigger is
     113             :      proportional to packet rate, but does not trigger if I/O is seldom. */
     114             :   ulong pending_cnt;
     115             :   ulong pending_wmark;
     116             : 
     117             :   /* Sometimes, packets are not flushed out even after a sendto()
     118             :      wakeup.  This can result in the tail of a burst getting delayed or
     119             :      overrun.  If more than tail_flush_backoff ticks pass since the last
     120             :      sendto() wakeup and there are still unacknowledged packets in the
     121             :      TX ring, issues another wakeup. Only used by "softirq" poll mode. */
     122             :   long next_tail_flush_ticks;
     123             :   long tail_flush_backoff;
     124             : 
     125             :   /* When the most recent prefbusy poll was. */
     126             :   long prefbusy_last_poll_ticks;
     127             :   /* Min time between each prefbusy poll. */
     128             :   long prefbusy_min_interval_ticks;
     129             :   /* Max time since last prefbusy poll before a prefbusy poll is
     130             :      forced (has been read that polling can sometimes resolve a stall). */
     131             :   long prefbusy_stall_timeout_ticks;
     132             : };
     133             : 
     134             : typedef struct fd_net_flusher fd_net_flusher_t;
     135             : 
     136             : FD_PROTOTYPES_BEGIN
     137             : 
     138             : /* fd_net_flusher_inc marks a new packet as enqueued. */
     139             : 
     140             : static inline void
     141             : fd_net_flusher_inc( fd_net_flusher_t * flusher,
     142           0 :                     long               now ) {
     143           0 :   flusher->pending_cnt++;
     144           0 :   long next_flush = now + flusher->tail_flush_backoff;
     145           0 :   flusher->next_tail_flush_ticks = fd_long_min( flusher->next_tail_flush_ticks, next_flush );
     146           0 : }
     147             : 
     148             : /* fd_net_flusher_check returns 1 if a sendto() wakeup should be issued
     149             :    immediately.  now is a recent fd_tickcount() value.
     150             :    If tx_ring_empty!=0 then the kernel is caught up with the net tile
     151             :    on the XDP TX ring.  (Otherwise, the kernel is behind the net tile) */
     152             : 
     153             : static inline int
     154             : fd_net_flusher_check( fd_net_flusher_t * flusher,
     155             :                       long               now,
     156           0 :                       int                tx_ring_empty ) {
     157           0 :   int flush_level   = flusher->pending_cnt >= flusher->pending_wmark;
     158           0 :   int flush_timeout = now >= flusher->next_tail_flush_ticks;
     159           0 :   int flush         = flush_level || flush_timeout;
     160           0 :   if( !flush ) return 0;
     161           0 :   if( FD_UNLIKELY( tx_ring_empty ) ) {
     162             :     /* Flush requested but caught up */
     163           0 :     flusher->pending_cnt           = 0UL;
     164           0 :     flusher->next_tail_flush_ticks = LONG_MAX;
     165           0 :     return 0;
     166           0 :   }
     167           0 :   return 1;
     168           0 : }
     169             : 
     170             : /* fd_net_flusher_wakeup signals a sendto() wakeup was done.  now is a
     171             :    recent fd_tickcount() value. */
     172             : 
     173             : static inline void
     174             : fd_net_flusher_wakeup( fd_net_flusher_t * flusher,
     175           0 :                        long               now ) {
     176           0 :   flusher->pending_cnt           = 0UL;
     177           0 :   flusher->next_tail_flush_ticks = now + flusher->tail_flush_backoff;
     178           0 : }
     179             : 
     180             : FD_PROTOTYPES_END
     181             : 
     182             : /* fd_net_free_ring is a FIFO queue that stores pointers to free XDP TX
     183             :    frames. */
     184             : 
     185             : struct fd_net_free_ring {
     186             :   ulong   prod;
     187             :   ulong   cons;
     188             :   ulong   depth;
     189             :   ulong * queue;
     190             : };
     191             : typedef struct fd_net_free_ring fd_net_free_ring_t;
     192             : 
     193             : typedef struct {
     194             :   fd_net_tile_t net;
     195             : 
     196             :   /* An "XSK" is an AF_XDP socket */
     197             :   uint     xsk_cnt;
     198             :   fd_xsk_t xsk[ 2 ];
     199             :   int      prog_link_fds[ 2 ];
     200             : 
     201             :   /* UMEM frame region within dcache */
     202             :   void *   umem;    /* Start of UMEM */
     203             :   ulong    umem_sz; /* Size  of UMEM */
     204             : 
     205             :   /* Details pertaining to an inflight send op */
     206             :   struct {
     207             :     uint   xsk_idx;
     208             :     void * frame;
     209             :   } tx_op;
     210             : 
     211             :   /* Round-robin cycle service operations */
     212             :   uint rr_idx;
     213             : 
     214             :   /* Ring tracking free packet buffers */
     215             :   fd_net_free_ring_t free_tx;
     216             : 
     217             :   uchar src_mac_addr[6];
     218             : 
     219             :   /* XDP stats refresh timer */
     220             :   long xdp_stats_interval_ticks;
     221             :   long next_xdp_stats_refresh;
     222             : 
     223             :   /* TX flush timers */
     224             :   fd_net_flusher_t tx_flusher[2]; /* one per XSK */
     225             :   ulong   waker_client_idx;
     226             :   ulong * waker_fseq;
     227             : 
     228             :   ulong netdev_seq; /* netdev_shared seqlock value of the net.router.netdev_tbl copy */
     229             : 
     230             :   struct {
     231             :     ulong rx_fill_blocked_cnt;
     232             :     long  rx_busy_cnt;
     233             :     long  rx_idle_cnt;
     234             : 
     235             :     ulong tx_submit_cnt;
     236             :     ulong tx_full_fail_cnt;
     237             :     long  tx_busy_cnt;
     238             :     long  tx_idle_cnt;
     239             : 
     240             :     ulong xsk_tx_wakeup_cnt;
     241             :     ulong xsk_rx_wakeup_cnt;
     242             :   } metrics;
     243             : } fd_net_ctx_t;
     244             : 
     245             : fd_fib4_t *
     246             : fd_xdp_tile_fib4_join( fd_fib4_t *            out,
     247             :                        fd_topo_t const *      topo,
     248             :                        fd_topo_tile_t const * tile,
     249           0 :                        int                    main_table ) {
     250           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
     251           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
     252           0 :   (void)FD_SCRATCH_ALLOC_APPEND( l, alignof(fd_net_ctx_t), sizeof(fd_net_ctx_t) );
     253           0 :   (void)FD_SCRATCH_ALLOC_APPEND( l, alignof(ulong), tile->xdp.free_ring_depth*sizeof(ulong) );
     254           0 :   (void)FD_SCRATCH_ALLOC_APPEND( l, fd_netdev_tbl_align(), fd_netdev_tbl_footprint( NETDEV_MAX, BOND_MASTER_MAX ) );
     255           0 :   void * local_mem = FD_SCRATCH_ALLOC_APPEND( l, fd_fib4_align(), fd_fib4_footprint( tile->xdp.route_max, tile->xdp.route_peer_max ) );
     256           0 :   void * main_mem  = FD_SCRATCH_ALLOC_APPEND( l, fd_fib4_align(), fd_fib4_footprint( tile->xdp.route_max, tile->xdp.route_peer_max ) );
     257           0 :   return fd_fib4_join( out, main_table ? main_mem : local_mem );
     258           0 : }
     259             : 
     260             : FD_FN_CONST static inline ulong
     261           0 : scratch_align( void ) {
     262           0 :   return 4096UL;
     263           0 : }
     264             : 
     265             : FD_FN_PURE static inline ulong
     266           0 : scratch_footprint( fd_topo_tile_t const * tile ) {
     267           0 :   ulong l = FD_LAYOUT_INIT;
     268           0 :   l = FD_LAYOUT_APPEND( l, alignof(fd_net_ctx_t), sizeof(fd_net_ctx_t)                      );
     269           0 :   l = FD_LAYOUT_APPEND( l, alignof(ulong),        tile->xdp.free_ring_depth * sizeof(ulong) );
     270           0 :   l = FD_LAYOUT_APPEND( l, fd_netdev_tbl_align(), fd_netdev_tbl_footprint( NETDEV_MAX, BOND_MASTER_MAX ) );
     271           0 :   for( ulong i=0UL; i<2UL; i++ ) l = FD_LAYOUT_APPEND( l, fd_fib4_align(), fd_fib4_footprint( tile->xdp.route_max, tile->xdp.route_peer_max ) );
     272           0 :   return FD_LAYOUT_FINI( l, scratch_align() );
     273           0 : }
     274             : 
     275             : static void
     276           0 : metrics_write( fd_net_ctx_t * ctx ) {
     277           0 :   FD_MCNT_SET(   NET, PKT_RX,                ctx->net.metrics.rx_pkt_cnt         );
     278           0 :   FD_MCNT_SET(   NET, PKT_RX_BYTES,          ctx->net.metrics.rx_bytes_total     );
     279           0 :   FD_MCNT_ENUM_COPY( NET, PKT_RX_DROPPED,  ctx->net.metrics.rx_drop_cnt        );
     280           0 :   FD_MCNT_SET(   NET, GRE_PKT_RX,            ctx->net.metrics.rx_gre_cnt         );
     281           0 :   FD_MCNT_SET(   NET, VLAN_PKT_RX,           ctx->net.metrics.rx_vlan_cnt        );
     282           0 :   FD_MCNT_SET(   NET, RX_FILL_RING_STALLED,  ctx->metrics.rx_fill_blocked_cnt    );
     283           0 :   FD_MGAUGE_SET( NET, RX_BUFFER_USED, (ulong)fd_long_max( ctx->metrics.rx_busy_cnt, 0L ) );
     284           0 :   FD_MGAUGE_SET( NET, RX_BUFFER_FREE, (ulong)fd_long_max( ctx->metrics.rx_idle_cnt, 0L ) );
     285           0 :   FD_MGAUGE_SET( NET, TX_BUFFER_USED, (ulong)fd_long_max( ctx->metrics.tx_busy_cnt, 0L ) );
     286           0 :   FD_MGAUGE_SET( NET, TX_BUFFER_FREE, (ulong)fd_long_max( ctx->metrics.tx_idle_cnt, 0L ) );
     287             : 
     288           0 :   FD_MCNT_SET( NET, PKT_TX_SUBMITTED,        ctx->metrics.tx_submit_cnt         );
     289           0 :   FD_MCNT_SET( NET, PKT_TX_COMPLETED,        ctx->net.metrics.tx_pkt_cnt        );
     290           0 :   FD_MCNT_SET( NET, PKT_TX_SUBMITTED_BYTES,  ctx->net.metrics.tx_bytes_total    );
     291           0 :   ctx->net.metrics.tx_drop_cnt[ FD_METRICS_ENUM_PKT_TX_DROP_REASON_V_RING_FULL_IDX ] = ctx->metrics.tx_full_fail_cnt;
     292           0 :   FD_MCNT_ENUM_COPY( NET, PKT_TX_DROPPED,          ctx->net.metrics.tx_drop_cnt             );
     293           0 :   FD_MCNT_ENUM_COPY( NET, PKT_TX_ROUTED,           ctx->net.metrics.tx_route_result_cnt     );
     294           0 :   FD_MCNT_ENUM_COPY( NET, PKT_TX_SLOW_PATH_ROUTED, ctx->net.metrics.tx_slow_path_reason_cnt );
     295             : 
     296           0 :   FD_MCNT_SET( NET, XSK_SYSCALL_TX,          ctx->metrics.xsk_tx_wakeup_cnt );
     297           0 :   FD_MCNT_SET( NET, XSK_SYSCALL_RX,          ctx->metrics.xsk_rx_wakeup_cnt );
     298             : 
     299           0 :   FD_MCNT_SET( NET, GRE_PKT_TX_SUBMITTED,       ctx->net.metrics.tx_gre_cnt              );
     300           0 :   FD_MCNT_SET( NET, PKT_TX_SLOW_PATH_SUBMITTED, ctx->net.metrics.tx_slow_path_submit_cnt );
     301             :   /* fd_fib4_cnt includes the synthetic throw route at index zero. */
     302           0 :   FD_MGAUGE_SET( NET, ROUTE_COUNT_LOCAL, fd_ulong_sat_sub( fd_fib4_cnt( ctx->net.router.fib_local ), 1UL ) );
     303           0 :   FD_MGAUGE_SET( NET, ROUTE_COUNT_MAIN,  fd_ulong_sat_sub( fd_fib4_cnt( ctx->net.router.fib_main  ), 1UL ) );
     304           0 : }
     305             : 
     306             : struct xdp_statistics_v0 {
     307             :   __u64 rx_dropped; /* Dropped for other reasons */
     308             :   __u64 rx_invalid_descs; /* Dropped due to invalid descriptor */
     309             :   __u64 tx_invalid_descs; /* Dropped due to invalid descriptor */
     310             : };
     311             : 
     312             : struct xdp_statistics_v1 {
     313             :   __u64 rx_dropped; /* Dropped for other reasons */
     314             :   __u64 rx_invalid_descs; /* Dropped due to invalid descriptor */
     315             :   __u64 tx_invalid_descs; /* Dropped due to invalid descriptor */
     316             :   __u64 rx_ring_full; /* Dropped due to rx ring being full */
     317             :   __u64 rx_fill_ring_empty_descs; /* Failed to retrieve item from fill ring */
     318             :   __u64 tx_ring_empty_descs; /* Failed to retrieve item from tx ring */
     319             : };
     320             : 
     321             : static void
     322           0 : poll_xdp_statistics( fd_net_ctx_t * ctx ) {
     323           0 :   struct xdp_statistics_v1 stats = {0};
     324           0 :   ulong xsk_cnt = ctx->xsk_cnt;
     325           0 :   for( ulong j=0UL; j<xsk_cnt; j++ ) {
     326           0 :     struct xdp_statistics_v1 sub_stats = {0};
     327           0 :     uint optlen = (uint)sizeof(struct xdp_statistics_v1);
     328           0 :     if( FD_UNLIKELY( -1==getsockopt( ctx->xsk[ j ].xsk_fd, SOL_XDP, XDP_STATISTICS, &sub_stats, &optlen ) ) )
     329           0 :       FD_LOG_ERR(( "getsockopt(SOL_XDP, XDP_STATISTICS) failed: %s", strerror( errno ) ));
     330           0 :     if( FD_UNLIKELY( optlen!=sizeof(struct xdp_statistics_v0) &&
     331           0 :                      optlen!=sizeof(struct xdp_statistics_v1) ) ) {
     332           0 :       FD_LOG_ERR(( "getsockopt(SOL_XDP, XDP_STATISTICS) returned unexpected size %u", optlen ));
     333           0 :     }
     334           0 :     stats.rx_dropped               += sub_stats.rx_dropped;
     335           0 :     stats.rx_invalid_descs         += sub_stats.rx_invalid_descs;
     336           0 :     stats.tx_invalid_descs         += sub_stats.tx_invalid_descs;
     337           0 :     stats.rx_ring_full             += sub_stats.rx_ring_full;
     338           0 :     stats.rx_fill_ring_empty_descs += sub_stats.rx_fill_ring_empty_descs;
     339           0 :     stats.tx_ring_empty_descs      += sub_stats.tx_ring_empty_descs;
     340           0 :   }
     341             : 
     342           0 :   FD_MCNT_SET( NET, XDP_RX_OTHER_DROPPED,                 stats.rx_dropped               );
     343           0 :   FD_MCNT_SET( NET, XDP_RX_INVALID_DESCRIPTOR_DROPPED,    stats.rx_invalid_descs         );
     344           0 :   FD_MCNT_SET( NET, XDP_TX_INVALID_DESCRIPTOR_DROPPED,    stats.tx_invalid_descs         );
     345           0 :   FD_MCNT_SET( NET, XDP_RX_RING_FULL_DROPPED,             stats.rx_ring_full             );
     346           0 :   FD_MCNT_SET( NET, XDP_RX_FILL_RING_EMPTY,               stats.rx_fill_ring_empty_descs );
     347           0 :   FD_MCNT_SET( NET, XDP_TX_RING_EMPTY,                    stats.tx_ring_empty_descs      );
     348           0 : }
     349             : 
     350             : /* net_is_fatal_xdp_error returns 1 if the given errno returned by an
     351             :    XDP API indicates a non-recoverable error code.  The net tile should
     352             :    crash if it sees such an error so the problem does not go undetected.
     353             :    Otherwise, returns 0. */
     354             : 
     355             : static int
     356           0 : net_is_fatal_xdp_error( int err ) {
     357           0 :   return err==ESOCKTNOSUPPORT || err==EOPNOTSUPP || err==EINVAL ||
     358           0 :          err==EPERM;
     359           0 : }
     360             : 
     361             : /* net_tx_ready returns 1 if we can submit a job to this TX ring, and 0 otherwise.
     362             :    Reasons for block include:
     363             :    - No TX buffer is available (free ring empty)
     364             :    - TX ring is full
     365             : 
     366             :    tx_ring: pointer to the XDP TX ring
     367             :    free_ring: pointer to the free TX ring */
     368             : 
     369             : static int
     370             : net_tx_ready( fd_xdp_ring_t *      tx_ring,
     371           0 :               fd_net_free_ring_t * free_ring ) {
     372           0 :   if( FD_UNLIKELY( free_ring->prod == free_ring->cons ) ) return 0; /* drop - no free buffers */
     373           0 :   if( FD_UNLIKELY( fd_xdp_ring_full( tx_ring ) ) )        return 0; /* drop - tx ring full */
     374           0 :   return 1;
     375           0 : }
     376             : 
     377             : /* net_rx_wakeup triggers xsk_recvmsg to run in the kernel.  Needs to be
     378             :    called periodically in order to receive packets. */
     379             : 
     380             : static void
     381             : net_rx_wakeup( fd_net_ctx_t * ctx,
     382             :                fd_xsk_t *     xsk,
     383           0 :                int *          charge_busy ) {
     384             :   /* write-back local copies to fseqs */
     385           0 :   __atomic_store_n( xsk->ring_rx.cons, xsk->ring_rx.cached_cons, __ATOMIC_RELEASE );
     386           0 :   __atomic_store_n( xsk->ring_fr.prod, xsk->ring_fr.cached_prod, __ATOMIC_RELEASE );
     387           0 :   if( !fd_xsk_rx_need_wakeup( xsk ) ) return;
     388           0 :   *charge_busy = 1;
     389           0 :   struct msghdr _ignored[ 1 ] = { 0 };
     390           0 :   if( FD_UNLIKELY( -1==recvmsg( xsk->xsk_fd, _ignored, MSG_DONTWAIT ) ) ) {
     391           0 :     if( FD_UNLIKELY( net_is_fatal_xdp_error( errno ) ) ) {
     392           0 :       FD_LOG_ERR(( "xsk recvmsg failed xsk_fd=%d (%i-%s)", xsk->xsk_fd, errno, fd_io_strerror( errno ) ));
     393           0 :     }
     394           0 :     if( FD_UNLIKELY( errno!=EAGAIN ) ) {
     395           0 :       long ts = fd_log_wallclock();
     396           0 :       if( ts > xsk->log_suppress_until_ns ) {
     397           0 :         FD_LOG_WARNING(( "xsk recvmsg failed xsk_fd=%d (%i-%s)", xsk->xsk_fd, errno, fd_io_strerror( errno ) ));
     398           0 :         xsk->log_suppress_until_ns = ts + (long)1e9;
     399           0 :       }
     400           0 :     }
     401           0 :   }
     402           0 :   ctx->metrics.xsk_rx_wakeup_cnt++;
     403           0 : }
     404             : 
     405             : /* net_tx_wakeup triggers xsk_sendmsg to run in the kernel.  Needs to be
     406             :    called periodically in order to transmit packets. Should only be called
     407             :    if there are unconsumed packets in Tx ring. */
     408             : 
     409             : static void
     410             : net_tx_wakeup( fd_net_ctx_t * ctx,
     411             :                fd_xsk_t *     xsk,
     412           0 :                int *          charge_busy ) {
     413             :   /* write-back local copies to fseqs */
     414           0 :   __atomic_store_n( xsk->ring_tx.prod, xsk->ring_tx.cached_prod, __ATOMIC_RELEASE );
     415           0 :   __atomic_store_n( xsk->ring_cr.cons, xsk->ring_cr.cached_cons, __ATOMIC_RELEASE );
     416           0 :   if( !fd_xsk_tx_need_wakeup( xsk ) ) return;
     417           0 :   *charge_busy = 1;
     418           0 :   if( FD_UNLIKELY( -1==sendto( xsk->xsk_fd, NULL, 0, MSG_DONTWAIT, NULL, 0 ) ) ) {
     419           0 :     if( FD_UNLIKELY( net_is_fatal_xdp_error( errno ) ) ) {
     420           0 :       FD_LOG_ERR(( "xsk sendto failed xsk_fd=%d (%i-%s)", xsk->xsk_fd, errno, fd_io_strerror( errno ) ));
     421           0 :     }
     422           0 :     if( FD_UNLIKELY( errno!=EAGAIN ) ) {
     423           0 :       long ts = fd_log_wallclock();
     424           0 :       if( ts > xsk->log_suppress_until_ns ) {
     425           0 :         FD_LOG_WARNING(( "xsk sendto failed xsk_fd=%d (%i-%s)", xsk->xsk_fd, errno, fd_io_strerror( errno ) ));
     426           0 :         xsk->log_suppress_until_ns = ts + (long)1e9;
     427           0 :       }
     428           0 :     }
     429           0 :   }
     430           0 :   ctx->metrics.xsk_tx_wakeup_cnt++;
     431           0 : }
     432             : 
     433             : /* net_tx_periodic_wakeup does a timer based xsk_sendmsg wakeup. */
     434             : 
     435             : static inline int
     436             : net_tx_periodic_wakeup( fd_net_ctx_t * ctx,
     437             :                         uint           xsk_idx,
     438             :                         long           now,
     439           0 :                         int *          charge_busy ) {
     440           0 :   fd_xdp_ring_t * tx_ring        = &ctx->xsk[ xsk_idx ].ring_tx;
     441           0 :   int             tx_ring_empty  = fd_xdp_ring_empty( tx_ring, FD_XDP_RING_ROLE_PROD );
     442           0 :   if( fd_net_flusher_check( ctx->tx_flusher+xsk_idx, now, tx_ring_empty ) ) {
     443           0 :     net_tx_wakeup( ctx, &ctx->xsk[ xsk_idx ], charge_busy );
     444           0 :     fd_net_flusher_wakeup( ctx->tx_flusher+xsk_idx, now );
     445           0 :   }
     446           0 :   return 0;
     447           0 : }
     448             : 
     449             : static void
     450           0 : during_housekeeping( fd_net_ctx_t * ctx ) {
     451           0 :   long now = fd_tickcount();
     452           0 :   if( FD_UNLIKELY( fd_netdev_tbl_refresh( &ctx->net.router.netdev_tbl, &ctx->net.router.netdev_shared, &ctx->netdev_seq ) ) ) {
     453           0 :     fd_net_gre_tunnels_refresh( &ctx->net, &ctx->net.router.netdev_tbl );
     454           0 :   }
     455             : 
     456           0 :   ctx->metrics.rx_busy_cnt = 0UL;
     457           0 :   ctx->metrics.rx_idle_cnt = 0UL;
     458           0 :   ctx->metrics.tx_idle_cnt = fd_seq_diff( ctx->free_tx.prod, ctx->free_tx.cons );
     459           0 :   ctx->metrics.tx_busy_cnt = (long)ctx->free_tx.depth - ctx->metrics.tx_idle_cnt;
     460           0 :   for( uint j=0U; j<ctx->xsk_cnt; j++ ) {
     461           0 :     fd_xsk_t * xsk = &ctx->xsk[ j ];
     462           0 :     FD_COMPILER_MFENCE();
     463             :     /* Write back local copies to fseqs that we own */
     464           0 :     __atomic_store_n( xsk->ring_fr.prod, xsk->ring_fr.cached_prod, __ATOMIC_RELEASE );
     465           0 :     __atomic_store_n( xsk->ring_rx.cons, xsk->ring_rx.cached_cons, __ATOMIC_RELEASE );
     466           0 :     __atomic_store_n( xsk->ring_tx.prod, xsk->ring_tx.cached_prod, __ATOMIC_RELEASE );
     467           0 :     __atomic_store_n( xsk->ring_cr.cons, xsk->ring_cr.cached_cons, __ATOMIC_RELEASE );
     468             : 
     469             :     /* Refresh kernel-owned seq numbers for accurate stats */
     470           0 :     xsk->ring_fr.cached_cons = __atomic_load_n( xsk->ring_fr.cons, __ATOMIC_ACQUIRE );
     471           0 :     xsk->ring_rx.cached_prod = __atomic_load_n( xsk->ring_rx.prod, __ATOMIC_ACQUIRE );
     472           0 :     xsk->ring_tx.cached_cons = __atomic_load_n( xsk->ring_tx.cons, __ATOMIC_ACQUIRE );
     473           0 :     xsk->ring_cr.cached_prod = __atomic_load_n( xsk->ring_cr.prod, __ATOMIC_ACQUIRE );
     474             : 
     475           0 :     FD_COMPILER_MFENCE();
     476           0 :     ctx->metrics.rx_busy_cnt += (long)(int)( xsk->ring_rx.cached_prod - xsk->ring_rx.cached_cons );
     477           0 :     ctx->metrics.rx_idle_cnt += (long)(int)( xsk->ring_fr.cached_prod - xsk->ring_fr.cached_cons );
     478           0 :   }
     479             : 
     480           0 :   if( now > ctx->next_xdp_stats_refresh ) {
     481           0 :     ctx->next_xdp_stats_refresh = now + ctx->xdp_stats_interval_ticks;
     482           0 :     poll_xdp_statistics( ctx );
     483           0 :   }
     484           0 : }
     485             : 
     486             : 
     487             : /* before_frag is called when a new metadata descriptor for a TX job is
     488             :    found.  This callback determines whether this net tile is responsible
     489             :    for the TX job.  If so, it prepares the TX op for the during_frag and
     490             :    after_frag callbacks. */
     491             : 
     492             : static inline int
     493             : before_frag( fd_net_ctx_t * ctx,
     494             :              ulong          in_idx,
     495             :              ulong          seq,
     496           0 :              ulong          sig ) {
     497           0 :   (void)seq;
     498             : 
     499             :   /* Short circuit TX logic for route updates */
     500           0 :   if( FD_UNLIKELY( ctx->net.in_kind[ in_idx ]==FD_NET_IN_KIND_IPROUTE ) ) return 0;
     501             : 
     502           0 :   if( !fd_net_tx_select( &ctx->net, sig ) ) return 1;
     503             : 
     504           0 :   fd_net_tx_route_t * route = &ctx->net.tx_route;
     505           0 :   uint xsk_idx = route->use_loopback && route->if_idx!=ctx->net.router.if_virt ? XSK_IDX_LO : XSK_IDX_MAIN;
     506           0 :   ctx->tx_op.xsk_idx = xsk_idx;
     507             : 
     508           0 :   if( FD_UNLIKELY( xsk_idx>=ctx->xsk_cnt ) ) {
     509             :     /* Packet does not route to an XDP interface, so send it on net.sock */
     510           0 :     ctx->net.metrics.tx_slow_path_reason_cnt[ FD_METRICS_ENUM_PKT_TX_SLOW_PATH_REASON_V_UNSUPPORTED_INTERFACE_IDX ]++;
     511           0 :     route->routing_failure = 1;
     512           0 :     xsk_idx                = XSK_IDX_MAIN;
     513           0 :     ctx->tx_op.xsk_idx     = XSK_IDX_MAIN;
     514           0 :   }
     515             : 
     516             :   /* Skip if TX is blocked */
     517           0 :   fd_xsk_t *           xsk  = &ctx->xsk[ xsk_idx ];
     518           0 :   fd_net_free_ring_t * free = &ctx->free_tx;
     519           0 :   if( FD_UNLIKELY( !net_tx_ready( &xsk->ring_tx, free ) ) ) {
     520           0 :     ctx->metrics.tx_full_fail_cnt++;
     521           0 :     return 1;
     522           0 :   }
     523             : 
     524             :   /* Allocate buffer for receive */
     525           0 :   ulong                alloc_seq = free->cons;
     526           0 :   void *               frame     = (void *)free->queue[ alloc_seq & (free->depth-1UL) ];
     527           0 :   free->cons = fd_seq_inc( alloc_seq, 1UL );
     528             : 
     529           0 :   ctx->tx_op.frame = frame;
     530           0 :   fd_net_tx_route_result_increment( &ctx->net );
     531             : 
     532           0 :   return 0; /* continue */
     533           0 : }
     534             : 
     535             : /* during_frag stages route updates or copies an outgoing packet. */
     536             : 
     537             : static inline void
     538             : during_frag( fd_net_ctx_t * ctx,
     539             :              ulong          in_idx,
     540             :              ulong          seq FD_PARAM_UNUSED,
     541             :              ulong          sig FD_PARAM_UNUSED,
     542             :              ulong          chunk,
     543             :              ulong          sz,
     544           0 :              ulong          ctl FD_PARAM_UNUSED ) {
     545           0 :   fd_net_in_frag_validate( &ctx->net, in_idx, chunk, sz );
     546             : 
     547           0 :   if( FD_UNLIKELY( fd_net_iproute_msg_stage( &ctx->net, in_idx, chunk, sz ) ) ) return;
     548             : 
     549           0 :   void * frame = ctx->tx_op.frame;
     550           0 :   if( FD_UNLIKELY( (ulong)frame < (ulong)ctx->umem ) )
     551           0 :     FD_LOG_ERR(( "frame %p out of bounds (below %p)", frame, (void *)ctx->umem ));
     552           0 :   ulong umem_off = (ulong)frame - (ulong)ctx->umem;
     553           0 :   if( FD_UNLIKELY( (ulong)umem_off > (ulong)ctx->umem_sz ) )
     554           0 :     FD_LOG_ERR(( "frame %p out of bounds (beyond %p)", frame, (void *)ctx->umem_sz ));
     555             : 
     556             :   /* Speculatively copy frame into buffer from in link */
     557           0 :   fd_net_tx_pkt_cpy( &ctx->net, ctx->tx_op.frame, chunk, sz, in_idx );
     558           0 : }
     559             : 
     560             : /* after_frag is called when the during_frag memcpy was _not_ overrun. */
     561             : 
     562             : static void
     563             : after_frag( fd_net_ctx_t *      ctx,
     564             :             ulong               in_idx,
     565             :             ulong               seq,
     566             :             ulong               sig,
     567             :             ulong               sz,
     568             :             ulong               tsorig,
     569             :             ulong               tspub,
     570           0 :             fd_stem_context_t * stem ) {
     571           0 :   (void)seq; (void)sig; (void)tsorig; (void)tspub; (void)stem;
     572             : 
     573           0 :   if( FD_UNLIKELY( ctx->net.in_kind[ in_idx ]==FD_NET_IN_KIND_IPROUTE ) ) {
     574           0 :     fd_iproute_msg_t const * msg = &ctx->net.iproute_msg;
     575           0 :     if( msg->op==FD_IPROUTE_OP_FLUSH ) {
     576           0 :       fd_fib4_clear( ctx->net.router.fib_local );
     577           0 :       fd_fib4_clear( ctx->net.router.fib_main );
     578           0 :       return;
     579           0 :     }
     580           0 :     fd_fib4_t * fib;
     581           0 :     if( msg->table_id==RT_TABLE_LOCAL ) fib = ctx->net.router.fib_local;
     582           0 :     else if( msg->table_id==RT_TABLE_MAIN ) fib = ctx->net.router.fib_main;
     583           0 :     else return;
     584           0 :     if( msg->op==FD_IPROUTE_OP_UPSERT && FD_UNLIKELY( !fd_fib4_insert( fib, msg->dst_addr, msg->prefix, msg->prio, &msg->hop ) ) ) {
     585           0 :       FD_LOG_WARNING(( "route update dropped: route table full (increase [tiles.netlink].max_routes or [tiles.netlink].max_peer_routes)" ));
     586           0 :       if( FD_UNLIKELY( ctx->net.kind_id==0UL ) ) {
     587           0 :         fd_stem_publish( stem, ctx->net.router.netlnk_out_idx, FD_NETLINK_ROUTE4_SYNC_SIG, 0UL, 0UL, 0UL, 0UL, fd_frag_meta_ts_comp( fd_tickcount() ) );
     588           0 :       }
     589           0 :     }
     590           0 :     else if( msg->op==FD_IPROUTE_OP_DELETE ) fd_fib4_remove( fib, msg->dst_addr, msg->prefix, msg->prio );
     591           0 :     return;
     592           0 :   }
     593             : 
     594             :   /* Current send operation */
     595             : 
     596           0 :   uchar * frame   = ctx->tx_op.frame;
     597           0 :   uint    xsk_idx = ctx->tx_op.xsk_idx;
     598             : 
     599           0 :   if( FD_UNLIKELY( !fd_net_tx_pkt_prep( &ctx->net, frame, &sz, in_idx ) ) ) return;
     600             : 
     601             :   /* Packets that failed userland routing are sent on net.sock starting
     602             :      at the IPv4 header, and the kernel builds the L2 header.  The send
     603             :      is synchronous, so the frame goes straight back to free_tx, and a
     604             :      sent packet is counted as both submitted and completed (there is
     605             :      no XSK completion event for it). */
     606           0 :   if( FD_UNLIKELY( ctx->net.tx_route.routing_failure ) ) {
     607           0 :     int                  ok       = fd_net_tx_sock_send( &ctx->net, frame, sz );
     608           0 :     fd_net_free_ring_t * free     = &ctx->free_tx;
     609           0 :     ulong                free_idx = free->prod & (free->depth-1UL);
     610           0 :     free->queue[ free_idx ] = (ulong)frame;
     611           0 :     free->prod              = fd_seq_inc( free->prod, 1UL );
     612           0 :     ctx->tx_op.frame        = NULL;
     613           0 :     if( FD_LIKELY( ok ) ) {
     614           0 :       ctx->metrics.tx_submit_cnt++;
     615           0 :       ctx->net.metrics.tx_pkt_cnt++;
     616           0 :       ctx->net.metrics.tx_bytes_total += sz;
     617           0 :       ctx->net.metrics.tx_gre_cnt     += (ulong)ctx->net.tx_route.use_gre;
     618           0 :     }
     619           0 :     return;
     620           0 :   }
     621             : 
     622             :   /* Submit packet TX job
     623             : 
     624             :      Invariant for ring_tx: prod-cons<length
     625             :      (This invariant breaks if any other packet is sent over this ring
     626             :      between before_frag and this point.) */
     627             : 
     628           0 :   fd_xsk_t      * xsk     = &ctx->xsk[ xsk_idx ];
     629           0 :   fd_xdp_ring_t * tx_ring = &xsk->ring_tx;
     630           0 :   uint            tx_seq  = tx_ring->cached_prod;
     631           0 :   uint            tx_mask = tx_ring->depth - 1U;
     632           0 :   xsk->ring_tx.packet_ring[ tx_seq&tx_mask ] = (struct xdp_desc) {
     633           0 :     .addr    = (ulong)frame - (ulong)ctx->umem,
     634           0 :     .len     = (uint)sz,
     635           0 :     .options = 0
     636           0 :   };
     637             : 
     638             :   /* Frame is now owned by kernel. Clear tx_op. */
     639           0 :   ctx->tx_op.frame = NULL;
     640             : 
     641             :   /* Register newly enqueued packet */
     642           0 :   tx_ring->cached_prod = tx_seq+1U;
     643           0 :   ctx->metrics.tx_submit_cnt++;
     644           0 :   ctx->net.metrics.tx_bytes_total += sz;
     645           0 :   if( ctx->net.tx_route.use_gre ) ctx->net.metrics.tx_gre_cnt++;
     646           0 :   fd_net_flusher_inc( ctx->tx_flusher+xsk_idx, fd_tickcount() );
     647           0 : }
     648             : 
     649             : /* net_comp_event is called when an XDP TX frame is free again. */
     650             : 
     651             : static void
     652             : net_comp_event( fd_net_ctx_t * ctx,
     653             :                 fd_xsk_t *     xsk,
     654           0 :                 uint           comp_seq ) {
     655             : 
     656             :   /* Locate the incoming frame */
     657             : 
     658           0 :   fd_xdp_ring_t * comp_ring  = &xsk->ring_cr;
     659           0 :   uint            comp_mask  = comp_ring->depth - 1U;
     660           0 :   ulong           frame      = FD_VOLATILE_CONST( comp_ring->frame_ring[ comp_seq&comp_mask ] );
     661           0 :   ulong const     frame_mask = FD_NET_MTU - 1UL;
     662           0 :   FD_STATIC_ASSERT( FD_ULONG_IS_POW2( FD_NET_MTU ), "FD_NET_MTU must be a power of two" );
     663           0 :   if( FD_UNLIKELY( frame+FD_NET_MTU > ctx->umem_sz ) ) {
     664           0 :     FD_LOG_ERR(( "Bounds check failed: frame=0x%lx umem_sz=0x%lx",
     665           0 :                  frame, (ulong)ctx->umem_sz ));
     666           0 :   }
     667             : 
     668             :   /* Check if we have space to return the freed frame */
     669             : 
     670           0 :   fd_net_free_ring_t * free      = &ctx->free_tx;
     671           0 :   ulong                free_prod = free->prod;
     672           0 :   ulong                free_mask = free->depth - 1UL;
     673           0 :   ulong                free_cons = free->cons;
     674           0 :   long                 free_cnt = fd_seq_diff( free_prod, free_cons );
     675           0 :   FD_TEST( free_prod >= free_cons );
     676           0 :   if( FD_UNLIKELY( free_cnt>=(long)free->depth ) ) return; /* blocked */
     677             : 
     678           0 :   free->queue[ free_prod&free_mask ] = (ulong)ctx->umem + (frame & (~frame_mask));
     679           0 :   free->prod = fd_seq_inc( free_prod, 1UL );
     680             : 
     681             :   /* Wind up for next iteration */
     682             : 
     683           0 :   comp_ring->cached_cons = comp_seq+1U;
     684           0 :   ctx->net.metrics.tx_pkt_cnt++;
     685           0 : }
     686             : 
     687             : static int
     688           0 : prevent_park( fd_net_ctx_t * ctx ) {
     689           0 :   for( uint i=0U; i<ctx->xsk_cnt; i++ ) {
     690           0 :     fd_xsk_t * xsk = &ctx->xsk[ i ];
     691           0 :     if( FD_UNLIKELY( xsk->prefbusy_poll_enabled ) ) return 1;
     692           0 :     if( FD_UNLIKELY( !fd_xdp_ring_empty( &xsk->ring_rx, FD_XDP_RING_ROLE_CONS ) ) ) return 1;
     693           0 :     if( FD_UNLIKELY( !fd_xdp_ring_empty( &xsk->ring_cr, FD_XDP_RING_ROLE_CONS ) ) ) return 1;
     694           0 :     if( FD_UNLIKELY( ctx->tx_flusher[ i ].pending_cnt ) ) return 1;
     695           0 :     if( FD_UNLIKELY( !fd_xdp_ring_empty( &xsk->ring_tx, FD_XDP_RING_ROLE_PROD ) ) ) return 1; /* the flusher paces the kicks */
     696           0 :   }
     697           0 :   return 0;
     698           0 : }
     699             : 
     700             : /* net_rx_event is called when a new XDP RX frame is available.  Calls
     701             :    fd_net_rx_pkt, then returns the packet back to the kernel via the fill
     702             :    ring.  */
     703             : 
     704             : static void
     705             : net_rx_event( fd_net_ctx_t *      ctx,
     706             :               fd_stem_context_t * stem,
     707             :               fd_xsk_t *          xsk,
     708           0 :               uint                rx_seq ) {
     709             :   /* Locate the incoming frame */
     710             : 
     711           0 :   fd_xdp_ring_t * rx_ring = &xsk->ring_rx;
     712           0 :   uint            rx_mask = rx_ring->depth - 1U;
     713           0 :   struct xdp_desc frame   = FD_VOLATILE_CONST( rx_ring->packet_ring[ rx_seq&rx_mask ] );
     714             : 
     715           0 :   if( FD_UNLIKELY( frame.len>FD_NET_MTU ) )
     716           0 :     FD_LOG_ERR(( "received a UDP packet with a too large payload (%u)", frame.len ));
     717             : 
     718             :   /* Check if we have space in the fill ring to free the frame */
     719             : 
     720           0 :   fd_xdp_ring_t * fill_ring  = &xsk->ring_fr;
     721           0 :   if( FD_UNLIKELY( fd_xdp_ring_full( fill_ring ) ) ) {
     722           0 :     ctx->metrics.rx_fill_blocked_cnt++;
     723           0 :     return; /* blocked */
     724           0 :   }
     725             : 
     726             :   /* Pass it to the receive handler */
     727             : 
     728           0 :   ulong const chunk = ctx->net.pkt_buf_chunk0 + (frame.addr >> FD_CHUNK_LG_SZ);
     729           0 :   ulong const tspub = (ulong)fd_frag_meta_ts_comp( fd_tickcount() );
     730           0 :   ulong       freed_chunk;
     731           0 :   fd_net_rx_pkt( &ctx->net, stem, chunk, frame.addr & (FD_CHUNK_SZ-1UL), frame.len, tspub, &freed_chunk, NULL );
     732             : 
     733           0 :   FD_COMPILER_MFENCE();
     734           0 :   rx_ring->cached_cons = rx_seq+1U;
     735             : 
     736             :   /* Every RX operation returns one frame to the FILL ring.  If the
     737             :      packet was forwarded to a downstream ring, the newly shadowed frame
     738             :      is returned.  Otherwise, the frame just received is returned. */
     739             : 
     740           0 :   FD_STATIC_ASSERT( FD_ULONG_IS_POW2( FD_NET_MTU ), "FD_NET_MTU must be a power of two" );
     741             :   /* Packets can start partway into a UMEM frame, so align down to
     742             :      the frame start. */
     743           0 :   ulong const frame_sz_chunks = FD_NET_MTU>>FD_CHUNK_LG_SZ;
     744           0 :   freed_chunk = ctx->net.pkt_buf_chunk0 + fd_ulong_align_dn( freed_chunk-ctx->net.pkt_buf_chunk0, frame_sz_chunks );
     745           0 :   if( FD_UNLIKELY( freed_chunk<ctx->net.pkt_buf_chunk0 || freed_chunk>ctx->net.pkt_buf_wmark ) ) {
     746           0 :     FD_LOG_CRIT(( "mcache corruption detected: buffer chunk %lu out of bounds [%lu,%lu]",
     747           0 :                   freed_chunk, ctx->net.pkt_buf_chunk0, ctx->net.pkt_buf_wmark ));
     748           0 :   }
     749           0 :   ulong const freed_off = (freed_chunk-ctx->net.pkt_buf_chunk0)<<FD_CHUNK_LG_SZ;
     750             : 
     751           0 :   uint fill_prod = fill_ring->cached_prod;
     752           0 :   uint fill_mask = (fill_ring->depth)-1U;
     753           0 :   fill_ring->frame_ring[ fill_prod&fill_mask ] = freed_off;
     754           0 :   fill_ring->cached_prod = fill_prod+1U;
     755           0 : }
     756             : 
     757             : static void
     758             : before_credit_softirq( fd_net_ctx_t *      ctx,
     759             :                        fd_stem_context_t * stem,
     760             :                        int *               charge_busy,
     761             :                        uint                rr_idx,
     762           0 :                        fd_xsk_t *          rr_xsk ) {
     763             : 
     764           0 :   net_tx_periodic_wakeup( ctx, rr_idx, fd_tickcount(), charge_busy );
     765             : 
     766             :   /* Fire RX event if we have RX desc avail */
     767           0 :   if( !fd_xdp_ring_empty( &rr_xsk->ring_rx, FD_XDP_RING_ROLE_CONS ) ) {
     768           0 :     *charge_busy = 1;
     769           0 :     net_rx_event( ctx, stem, rr_xsk, rr_xsk->ring_rx.cached_cons );
     770           0 :   } else {
     771           0 :     net_rx_wakeup( ctx, rr_xsk, charge_busy );
     772             : 
     773             :     /* Iterate onto the next NAPI queue. */
     774           0 :     ctx->rr_idx++;
     775           0 :     ctx->rr_idx = fd_uint_if( ctx->rr_idx>=ctx->xsk_cnt, 0, ctx->rr_idx );
     776           0 :   }
     777           0 : }
     778             : 
     779             : static int
     780             : net_prefbusy_poll_ready( fd_xsk_t *         rr_xsk,
     781             :                          fd_net_flusher_t * flusher,
     782           0 :                          long               now ) {
     783             : 
     784           0 :   if( FD_LIKELY( now < ( flusher->prefbusy_last_poll_ticks + flusher->prefbusy_min_interval_ticks ) ) ) return 0;
     785           0 :   if( FD_UNLIKELY( now > ( flusher->prefbusy_last_poll_ticks + flusher->prefbusy_stall_timeout_ticks ) ) ) return 1;
     786             : 
     787           0 :   int rx_empty = fd_xdp_ring_empty( &rr_xsk->ring_rx, FD_XDP_RING_ROLE_CONS );
     788             : 
     789           0 :   return rx_empty;
     790           0 : }
     791             : 
     792             : static void
     793             : net_prefbusy_poll_flush( fd_net_flusher_t * flusher,
     794           0 :                          long               now ) {
     795           0 :   flusher->prefbusy_last_poll_ticks = now;
     796           0 : }
     797             : 
     798             : static void
     799             : before_credit_prefbusy( fd_net_ctx_t *      ctx,
     800             :                         fd_stem_context_t * stem,
     801             :                         int *               charge_busy,
     802             :                         uint                rr_idx,
     803           0 :                         fd_xsk_t *          rr_xsk ) {
     804             : 
     805           0 :   fd_net_flusher_t * flusher = ctx->tx_flusher+rr_idx;
     806           0 :   if( FD_UNLIKELY( net_prefbusy_poll_ready( rr_xsk, flusher, fd_tickcount() ) ) ) {
     807             :     /* NAPI needs to be polled to process new TX from
     808             :        Firedancer's net tile and process new RX from the NIC. */
     809             : 
     810             :     /* write-back local copies to fseqs */
     811           0 :     __atomic_store_n( rr_xsk->ring_tx.prod, rr_xsk->ring_tx.cached_prod, __ATOMIC_RELEASE );
     812           0 :     __atomic_store_n( rr_xsk->ring_cr.cons, rr_xsk->ring_cr.cached_cons, __ATOMIC_RELEASE );
     813           0 :     __atomic_store_n( rr_xsk->ring_rx.cons, rr_xsk->ring_rx.cached_cons, __ATOMIC_RELEASE );
     814           0 :     __atomic_store_n( rr_xsk->ring_fr.prod, rr_xsk->ring_fr.cached_prod, __ATOMIC_RELEASE );
     815             : 
     816           0 :     if( FD_UNLIKELY( -1==sendto( rr_xsk->xsk_fd, NULL, 0, MSG_DONTWAIT, NULL, 0 ) ) ) {
     817           0 :       if( FD_UNLIKELY( net_is_fatal_xdp_error( errno ) ) ) {
     818           0 :         FD_LOG_ERR(( "xsk sendto failed xsk_fd=%d (%i-%s)", rr_xsk->xsk_fd, errno, fd_io_strerror( errno ) ));
     819           0 :       }
     820           0 :       if( FD_UNLIKELY( errno!=EAGAIN ) ) {
     821           0 :         long ts = fd_log_wallclock();
     822           0 :         if( ts > rr_xsk->log_suppress_until_ns ) {
     823           0 :           FD_LOG_WARNING(( "xsk sendto failed xsk_fd=%d (%i-%s)", rr_xsk->xsk_fd, errno, fd_io_strerror( errno ) ));
     824           0 :           rr_xsk->log_suppress_until_ns = ts + (long)1e9;
     825           0 :         }
     826           0 :       }
     827           0 :     }
     828             :     /* Since xsk sendmsg in prefbusy mode drives both rx and tx, both are incremented */
     829           0 :     ctx->metrics.xsk_tx_wakeup_cnt++;
     830           0 :     ctx->metrics.xsk_rx_wakeup_cnt++;
     831             : 
     832           0 :     net_prefbusy_poll_flush( flusher, fd_tickcount() );
     833           0 :   }
     834             : 
     835             :   /* Process new RX from xsk ring if there is any. */
     836           0 :   if( !fd_xdp_ring_empty( &rr_xsk->ring_rx, FD_XDP_RING_ROLE_CONS ) ) {
     837           0 :     *charge_busy = 1;
     838           0 :     net_rx_event( ctx, stem, rr_xsk, rr_xsk->ring_rx.cached_cons );
     839           0 :   }
     840             :   /* Iterate onto the next NAPI queue. */
     841           0 :   ctx->rr_idx++;
     842           0 :   ctx->rr_idx = fd_uint_if( ctx->rr_idx>=ctx->xsk_cnt, 0, ctx->rr_idx );
     843           0 : }
     844             : 
     845             : static void
     846             : before_credit( fd_net_ctx_t *      ctx,
     847             :                fd_stem_context_t * stem,
     848           0 :                int *               charge_busy ) {
     849           0 :   fd_net_router_solicit( &ctx->net.router, stem );
     850             : 
     851             :   /* A previous send attempt was overrun.  A corrupt copy of the packet was
     852             :      placed into an XDP frame, but the frame was not yet submitted to the
     853             :      TX ring.  Return the tx buffer to the free list. */
     854             : 
     855           0 :   if( ctx->tx_op.frame ) {
     856           0 :     *charge_busy = 1;
     857           0 :     fd_net_free_ring_t * free      = &ctx->free_tx;
     858           0 :     ulong                alloc_seq = free->prod;
     859           0 :     free->queue[ alloc_seq & (free->depth-1UL) ] = (ulong)ctx->tx_op.frame;
     860           0 :     free->prod = fd_seq_inc( alloc_seq, 1UL );
     861           0 :     ctx->tx_op.frame = NULL;
     862           0 :   }
     863             : 
     864             :   /* Check if new packets are available or if TX frames are free again
     865             :      (Round-robin through sockets) */
     866             : 
     867           0 :   uint       rr_idx = ctx->rr_idx;
     868           0 :   fd_xsk_t * rr_xsk = &ctx->xsk[ rr_idx ];
     869             : 
     870           0 :   if( FD_LIKELY( !rr_xsk->prefbusy_poll_enabled ) ) {
     871             :     /* Default poll mode which relies on irqs and wakeups */
     872           0 :     before_credit_softirq( ctx, stem, charge_busy, rr_idx, rr_xsk );
     873           0 :   } else {
     874           0 :     before_credit_prefbusy( ctx, stem, charge_busy, rr_idx, rr_xsk );
     875           0 :   }
     876             : 
     877             :   /* Fire comp event if we have comp desc avail */
     878           0 :   if( !fd_xdp_ring_empty( &rr_xsk->ring_cr, FD_XDP_RING_ROLE_CONS ) ) {
     879           0 :     *charge_busy = 1;
     880           0 :     net_comp_event( ctx, rr_xsk, rr_xsk->ring_cr.cached_cons );
     881           0 :   }
     882             : 
     883           0 :   if( FD_UNLIKELY( ctx->waker_fseq && fd_fseq_query( ctx->waker_fseq )==1UL ) ) {
     884           0 :     for( uint i=0U; i<ctx->xsk_cnt; i++ ) {
     885           0 :       if( FD_UNLIKELY( !fd_xdp_ring_empty( &ctx->xsk[ i ].ring_rx, FD_XDP_RING_ROLE_CONS ) ) ) return;
     886           0 :       if( FD_UNLIKELY( !fd_xdp_ring_empty( &ctx->xsk[ i ].ring_cr, FD_XDP_RING_ROLE_CONS ) ) ) return;
     887           0 :     }
     888           0 :     fd_fseq_update( ctx->waker_fseq, 0UL );
     889           0 :     fd_waker_client_rearm( ctx->waker_client_idx );
     890           0 :   }
     891           0 : }
     892             : 
     893             : /* net_xsk_bootstrap assigns UMEM frames to the FILL ring. */
     894             : 
     895             : static ulong
     896             : net_xsk_bootstrap( fd_net_ctx_t * ctx,
     897             :                    uint           xsk_idx,
     898           0 :                    ulong          frame_off ) {
     899           0 :   fd_xsk_t * xsk = &ctx->xsk[ xsk_idx ];
     900             : 
     901           0 :   ulong const frame_sz  = FD_NET_MTU;
     902           0 :   ulong const fr_depth  = ctx->xsk[ xsk_idx ].ring_fr.depth/2UL;
     903             : 
     904           0 :   fd_xdp_ring_t * fill      = &xsk->ring_fr;
     905           0 :   uint            fill_prod = fill->cached_prod;
     906           0 :   for( ulong j=0UL; j<fr_depth; j++ ) {
     907           0 :     fill->frame_ring[ j ] = frame_off;
     908           0 :     frame_off += frame_sz;
     909           0 :   }
     910           0 :   fill->cached_prod = fill_prod + (uint)fr_depth;
     911           0 :   __atomic_store_n( fill->prod, fill->cached_prod, __ATOMIC_RELEASE );
     912             : 
     913           0 :   return frame_off;
     914           0 : }
     915             : 
     916             : /* FIXME source MAC address from netlnk tile instead */
     917             : 
     918             : static void
     919             : interface_addrs( const char * interface,
     920             :                  uchar *      mac,
     921           0 :                  uint *       ip4_addr ) {
     922           0 :   int fd = socket( AF_INET, SOCK_DGRAM, 0 );
     923           0 :   struct ifreq ifr;
     924           0 :   ifr.ifr_addr.sa_family = AF_INET;
     925             : 
     926           0 :   strncpy( ifr.ifr_name, interface, IFNAMSIZ );
     927           0 :   if( FD_UNLIKELY( ioctl( fd, SIOCGIFHWADDR, &ifr ) ) )
     928           0 :     FD_LOG_ERR(( "could not get MAC address of interface `%s`: (%i-%s)", interface, errno, fd_io_strerror( errno ) ));
     929           0 :   fd_memcpy( mac, ifr.ifr_hwaddr.sa_data, 6 );
     930             : 
     931           0 :   if( FD_UNLIKELY( ioctl( fd, SIOCGIFADDR, &ifr ) ) )
     932           0 :     FD_LOG_ERR(( "could not get IP address of interface `%s`: (%i-%s)", interface, errno, fd_io_strerror( errno ) ));
     933           0 :   *ip4_addr = ((struct sockaddr_in *)fd_type_pun( &ifr.ifr_addr ))->sin_addr.s_addr;
     934             : 
     935           0 :   if( FD_UNLIKELY( close(fd) ) )
     936           0 :     FD_LOG_ERR(( "could not close socket (%i-%s)", errno, fd_io_strerror( errno ) ));
     937           0 : }
     938             : 
     939             : /* privileged_init does the following initialization steps:
     940             : 
     941             :    - Create an AF_XDP socket
     942             :    - Map XDP metadata rings
     943             :    - Register UMEM data region with socket
     944             :    - Insert AF_XDP socket into xsk_map
     945             : 
     946             :    Net tile 0 repeats these steps for the loopback device, unless the
     947             :    main interface is already loopback.  XDP programs are installed before
     948             :    tiles start.
     949             : 
     950             :    Kernel object references:
     951             : 
     952             :      BPF_LINK file descriptor
     953             :       |
     954             :       +-> XDP program installation on NIC
     955             :       |    |
     956             :       |    +-> XDP program <-- BPF_PROG file descriptor (prog_fd)
     957             :       |
     958             :       +-> XSKMAP object <-- BPF_MAP file descriptor (xsk_map) */
     959             : 
     960             : FD_FN_UNUSED static void
     961             : privileged_init( fd_topo_t const *      topo,
     962           0 :                  fd_topo_tile_t const * tile ) {
     963           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
     964             : 
     965           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
     966           0 :   fd_net_ctx_t * ctx     = FD_SCRATCH_ALLOC_APPEND( l, alignof(fd_net_ctx_t), sizeof(fd_net_ctx_t) );
     967           0 :   ulong *        free_tx = FD_SCRATCH_ALLOC_APPEND( l, alignof(ulong), tile->xdp.free_ring_depth * sizeof(ulong) );;
     968             : 
     969           0 :   fd_memset( ctx, 0, sizeof(fd_net_ctx_t) );
     970             : 
     971           0 :   interface_addrs( tile->xdp.if_virt, ctx->src_mac_addr, &ctx->net.router.default_address );
     972           0 :   ctx->net.router.if_virt = if_nametoindex( tile->xdp.if_virt ); FD_TEST( ctx->net.router.if_virt );
     973             : 
     974             :   /* Load up dcache containing UMEM */
     975             : 
     976           0 :   void * const dcache_mem          = fd_topo_obj_laddr( topo, tile->net.umem_dcache_obj_id );
     977           0 :   void * const umem                = fd_dcache_join( dcache_mem );
     978           0 :   ulong  const umem_dcache_data_sz = fd_dcache_data_sz( umem );
     979           0 :   ulong  const umem_frame_sz       = 2048UL;
     980           0 :   ulong  const umem_sz             = fd_ulong_align_dn( umem_dcache_data_sz, umem_frame_sz );
     981             : 
     982             :   /* Derive chunk bounds */
     983             : 
     984           0 :   void * const umem_base   = fd_wksp_containing( dcache_mem );
     985           0 :   ulong  const umem_chunk0 = ( (ulong)umem - (ulong)umem_base )>>FD_CHUNK_LG_SZ;
     986           0 :   ulong  const umem_wmark  = umem_chunk0 + ( ( umem_sz-umem_frame_sz )>>FD_CHUNK_LG_SZ );
     987             : 
     988           0 :   if( FD_UNLIKELY( umem_chunk0>UINT_MAX || umem_wmark>UINT_MAX || umem_chunk0>umem_wmark ) ) {
     989           0 :     FD_LOG_ERR(( "Calculated invalid UMEM bounds [%lu,%lu]", umem_chunk0, umem_wmark ));
     990           0 :   }
     991             : 
     992           0 :   if( FD_UNLIKELY( !umem_base ) ) FD_LOG_ERR(( "UMEM dcache is not in a workspace" ));
     993             : 
     994           0 :   ctx->umem                 = umem;
     995           0 :   ctx->umem_sz              = umem_sz;
     996           0 :   ctx->net.pkt_buf_wksp_base = umem_base;
     997           0 :   ctx->net.pkt_buf_chunk0    = umem_chunk0;
     998           0 :   ctx->net.pkt_buf_wmark     = umem_wmark;
     999             : 
    1000           0 :   ctx->free_tx.queue = free_tx;
    1001           0 :   ctx->free_tx.depth = tile->xdp.free_ring_depth;
    1002             : 
    1003             :   /* Firedancer requires the ring be a power of two. */
    1004           0 :   FD_TEST( fd_ulong_is_pow2( tile->xdp.free_ring_depth ) );
    1005             : 
    1006             :   /* Create and install XSKs */
    1007             : 
    1008           0 :   uint if_phys_if_idx = if_nametoindex( tile->xdp.if_phys );
    1009           0 :   if( FD_UNLIKELY( !if_phys_if_idx ) ) FD_LOG_ERR(( "if_nametoindex(%s) failed", tile->xdp.if_phys ));
    1010             : 
    1011           0 :   fd_xsk_params_t params0 = {
    1012           0 :     .if_idx      = if_phys_if_idx,
    1013           0 :     .if_queue_id = tile->xdp.if_queue,
    1014             : 
    1015             :     /* Some kernels produce EOPNOTSUP errors on sendto calls when
    1016             :        starting up without either XDP_ZEROCOPY or XDP_COPY
    1017             :        (e.g. 5.14.0-503.23.1.el9_5 with i40e) */
    1018           0 :     .bind_flags  = tile->xdp.zero_copy ? XDP_ZEROCOPY : XDP_COPY,
    1019             : 
    1020           0 :     .prefbusy_time_budget_micros = PREFBUSY_TIME_BUDGET_MICROS,
    1021             : 
    1022           0 :     .prefbusy_rx_budget = PREFBUSY_RX_BUDGET,
    1023             : 
    1024           0 :     .fr_depth  = tile->xdp.xdp_rx_queue_size*2,
    1025           0 :     .rx_depth  = tile->xdp.xdp_rx_queue_size,
    1026           0 :     .cr_depth  = tile->xdp.xdp_tx_queue_size,
    1027           0 :     .tx_depth  = tile->xdp.xdp_tx_queue_size,
    1028             : 
    1029           0 :     .umem_addr = umem,
    1030           0 :     .frame_sz  = umem_frame_sz,
    1031           0 :     .umem_sz   = umem_sz,
    1032           0 :   };
    1033             : 
    1034           0 :   fd_cstr_ncpy( params0.poll_mode, tile->xdp.poll_mode, sizeof(params0.poll_mode) );
    1035             : 
    1036             :   /* Re-derive XDP file descriptors */
    1037             : 
    1038           0 :   fd_xdp_fds_t xdp_fds[ FD_TOPO_XDP_FDS_MAX ];
    1039           0 :   uint         xdp_fds_cnt = FD_TOPO_XDP_FDS_MAX;
    1040           0 :   fd_topo_install_xdp( topo, xdp_fds, &xdp_fds_cnt, 0U, /* dry_run */ 1 );
    1041             : 
    1042           0 :   int xsk_map_fd = -1;
    1043           0 :   for( uint i=0U; i<xdp_fds_cnt; i++ ) {
    1044           0 :     if( xdp_fds[ i ].if_idx==if_phys_if_idx ) {
    1045           0 :       xsk_map_fd              = xdp_fds[ i ].xsk_map_fd;
    1046           0 :       ctx->prog_link_fds[ 0 ] = xdp_fds[ i ].prog_link_fd;
    1047           0 :       xdp_fds[ i ].prog_link_fd = -1; /* mark as used */
    1048           0 :       break;
    1049           0 :     }
    1050           0 :   }
    1051           0 :   FD_TEST( xsk_map_fd>=0 );
    1052             : 
    1053             :   /* Init XSK */
    1054           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 ));
    1055           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 ));
    1056           0 :   ctx->xsk_cnt = 1;
    1057             : 
    1058             :   /* Networking tile at index 0 also binds to loopback (only queue 0 available on lo) */
    1059             : 
    1060           0 :   if( FD_UNLIKELY( strcmp( tile->xdp.if_virt, "lo" ) && !tile->kind_id ) ) {
    1061           0 :     ctx->xsk_cnt = 2;
    1062             : 
    1063           0 :     uint lo_idx = if_nametoindex( "lo" );
    1064           0 :     if( FD_UNLIKELY( !lo_idx ) ) FD_LOG_ERR(( "if_nametoindex(lo) failed" ));
    1065             : 
    1066           0 :     int lo_xsk_map_fd = -1;
    1067           0 :     for( uint i=0U; i<xdp_fds_cnt; i++ ) {
    1068           0 :       if( xdp_fds[ i ].if_idx==lo_idx ) {
    1069           0 :         lo_xsk_map_fd           = xdp_fds[ i ].xsk_map_fd;
    1070           0 :         ctx->prog_link_fds[ 1 ] = xdp_fds[ i ].prog_link_fd;
    1071           0 :         xdp_fds[ i ].prog_link_fd = -1; /* mark as used */
    1072           0 :         break;
    1073           0 :       }
    1074           0 :     }
    1075           0 :     FD_TEST( lo_xsk_map_fd>=0 );
    1076             : 
    1077             :     /* init xsk 1 */
    1078           0 :     fd_xsk_params_t params1 = params0;
    1079           0 :     params1.if_idx      = lo_idx; /* probably always 1 */
    1080           0 :     params1.if_queue_id = 0;
    1081           0 :     params1.bind_flags  = 0;
    1082           0 :     if( FD_UNLIKELY( !fd_xsk_init( &ctx->xsk[ 1 ], &params1 ) ) )          FD_LOG_ERR(( "failed to bind lo_xsk" ));
    1083           0 :     if( FD_UNLIKELY( !fd_xsk_activate( &ctx->xsk[ 1 ], lo_xsk_map_fd ) ) ) FD_LOG_ERR(( "failed to activate lo_xsk" ));
    1084           0 :   }
    1085             : 
    1086             :   /* Close unused XDP fds */
    1087             : 
    1088           0 :   if( FD_UNLIKELY( fd_sandbox_gettid()==fd_sandbox_getpid() ) ) {
    1089             :     /* Kind of gross.. in single threaded mode we don't want to close the xsk_map_fd
    1090             :        since it's shared with other net tiles.  Just check for that by seeing if we
    1091             :        are the only thread in the process. */
    1092           0 :     for( uint i=0U; i<xdp_fds_cnt; i++ ) {
    1093           0 :       if( -1==close( xdp_fds[ i ].xsk_map_fd ) ) {
    1094           0 :         FD_LOG_ERR(( "close(%d) failed (%d-%s)", xsk_map_fd, errno, fd_io_strerror( errno ) ));
    1095           0 :       }
    1096           0 :       if( xdp_fds[ i ].prog_link_fd>0 &&
    1097           0 :           -1==close( xdp_fds[ i ].prog_link_fd ) ) {
    1098           0 :         FD_LOG_ERR(( "close(%d) failed (%d-%s)", xsk_map_fd, errno, fd_io_strerror( errno ) ));
    1099           0 :       }
    1100           0 :     }
    1101           0 :   }
    1102             : 
    1103           0 :   ctx->waker_client_idx = tile->waker_client_idx;
    1104           0 :   if( FD_UNLIKELY( topo->sleep_obj_id!=ULONG_MAX ) ) {
    1105           0 :     FD_TEST( ctx->waker_client_idx!=ULONG_MAX );
    1106           0 :     for( uint i=0U; i<ctx->xsk_cnt; i++ ) {
    1107           0 :       struct epoll_event ev = { .events = EPOLLIN, .data.fd = ctx->xsk[ i ].xsk_fd };
    1108           0 :       if( FD_UNLIKELY( -1==epoll_ctl( FD_WAKER_INNER_FD( ctx->waker_client_idx ), EPOLL_CTL_ADD, ctx->xsk[ i ].xsk_fd, &ev ) ) )
    1109           0 :         FD_LOG_ERR(( "epoll_ctl(ADD,xsk_fd) failed (%i-%s)", errno, fd_io_strerror( errno ) ));
    1110           0 :     }
    1111           0 :   }
    1112             : 
    1113           0 :   double tick_per_ns = fd_tempo_tick_per_ns( NULL );
    1114           0 :   ctx->xdp_stats_interval_ticks = (long)( FD_XDP_STATS_INTERVAL_NS * tick_per_ns );
    1115             : 
    1116           0 :   ulong scratch_top = FD_SCRATCH_ALLOC_FINI( l, scratch_align() );
    1117           0 :   if( FD_UNLIKELY( scratch_top > (ulong)scratch + scratch_footprint( tile ) ) )
    1118           0 :     FD_LOG_ERR(( "scratch overflow %lu %lu %lu", scratch_top - (ulong)scratch - scratch_footprint( tile ), scratch_top, (ulong)scratch + scratch_footprint( tile ) ));
    1119             : 
    1120           0 :   if( FD_UNLIKELY( !fd_net_sock_init( &ctx->net.sock ) ) ) {
    1121           0 :     FD_LOG_ERR(( "fd_net_sock_init failed (%i-%s)", errno, fd_io_strerror( errno ) ));
    1122           0 :   }
    1123           0 : }
    1124             : 
    1125             : static void
    1126             : init_device_table( fd_net_ctx_t * ctx,
    1127             :                    void *         netdev_tbl_shm,
    1128           0 :                    void *         netdev_tbl_local ) {
    1129           0 :   FD_TEST( fd_netdev_tbl_join( &ctx->net.router.netdev_shared, netdev_tbl_shm ) );
    1130           0 :   FD_TEST( fd_netdev_tbl_new( netdev_tbl_local, NETDEV_MAX, BOND_MASTER_MAX ) );
    1131           0 :   FD_TEST( fd_netdev_tbl_join( &ctx->net.router.netdev_tbl, netdev_tbl_local ) );
    1132           0 :   ctx->netdev_seq = fd_netdev_tbl_copy( &ctx->net.router.netdev_tbl, &ctx->net.router.netdev_shared );
    1133           0 :   fd_net_gre_tunnels_refresh( &ctx->net, &ctx->net.router.netdev_tbl );
    1134           0 : }
    1135             : 
    1136             : FD_FN_UNUSED static void
    1137             : unprivileged_init( fd_topo_t const *      topo,
    1138           0 :                    fd_topo_tile_t const * tile ) {
    1139           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    1140             : 
    1141           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    1142           0 :   fd_net_ctx_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof(fd_net_ctx_t), sizeof(fd_net_ctx_t) );
    1143           0 :   FD_TEST( ctx->xsk_cnt!=0 );
    1144           0 :   FD_TEST( ctx->free_tx.queue!=NULL );
    1145           0 :   (void)FD_SCRATCH_ALLOC_APPEND( l, alignof(ulong), tile->xdp.free_ring_depth * sizeof(ulong) );
    1146           0 :   void * netdev_tbl_local = FD_SCRATCH_ALLOC_APPEND( l, fd_netdev_tbl_align(), fd_netdev_tbl_footprint( NETDEV_MAX, BOND_MASTER_MAX ) );
    1147           0 :   void * fib_local_mem    = FD_SCRATCH_ALLOC_APPEND( l, fd_fib4_align(),       fd_fib4_footprint( tile->xdp.route_max, tile->xdp.route_peer_max ) );
    1148           0 :   void * fib_main_mem     = FD_SCRATCH_ALLOC_APPEND( l, fd_fib4_align(),       fd_fib4_footprint( tile->xdp.route_max, tile->xdp.route_peer_max ) );
    1149           0 :   FD_TEST( fd_fib4_join( ctx->net.router.fib_local, fd_fib4_new( fib_local_mem, tile->xdp.route_max, tile->xdp.route_peer_max, tile->xdp.route_peer_seed ) ) );
    1150           0 :   FD_TEST( fd_fib4_join( ctx->net.router.fib_main,  fd_fib4_new( fib_main_mem,  tile->xdp.route_max, tile->xdp.route_peer_max, tile->xdp.route_peer_seed ) ) );
    1151             : 
    1152           0 :   ctx->net.kind_id  = tile->kind_id;
    1153           0 :   ctx->net.tile_cnt = fd_topo_tile_name_cnt( topo, tile->name );
    1154             : 
    1155           0 :   ctx->net.bind_address = tile->net.bind_address;
    1156             : 
    1157             :   /* Put a bound on chunks we read from the input, to make sure they
    1158             :      are within in the data region of the workspace. */
    1159             : 
    1160           0 :   if( FD_UNLIKELY( !tile->in_cnt ) ) FD_LOG_ERR(( "net tile in link cnt is zero" ));
    1161           0 :   if( FD_UNLIKELY( tile->in_cnt>FD_NET_IN_MAX ) ) FD_LOG_ERR(( "net tile in link cnt %lu exceeds FD_NET_IN_MAX %lu", tile->in_cnt, FD_NET_IN_MAX ));
    1162           0 :   FD_TEST( tile->in_cnt<=32 );
    1163           0 :   for( ulong i=0UL; i<tile->in_cnt; i++ ) {
    1164           0 :     fd_topo_link_t const * link = &topo->links[ tile->in_link_id[ i ] ];
    1165           0 :     if( !strcmp( link->name, "iproute_out" ) ) ctx->net.in_kind[i] = FD_NET_IN_KIND_IPROUTE;
    1166           0 :     else {
    1167           0 :       ctx->net.in_kind[i] = FD_NET_IN_KIND_TX;
    1168           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 ));
    1169           0 :     }
    1170             : 
    1171           0 :     ctx->net.in_dcache_ctx[ i ].wksp_base = topo->workspaces[ topo->objs[ link->dcache_obj_id ].wksp_id ].wksp;
    1172           0 :     ctx->net.in_dcache_ctx[ i ].chunk0    = fd_dcache_compact_chunk0( ctx->net.in_dcache_ctx[ i ].wksp_base, link->dcache );
    1173           0 :     ctx->net.in_dcache_ctx[ i ].wmark     = fd_dcache_compact_wmark( ctx->net.in_dcache_ctx[ i ].wksp_base, link->dcache, link->mtu );
    1174           0 :   }
    1175             : 
    1176           0 :   fd_net_rx_dests_init( &ctx->net, topo, tile );
    1177             : 
    1178           0 :   ctx->net.router.netlnk_out_idx = fd_topo_find_tile_out_link( topo, tile, "net_netlnk", tile->kind_id );
    1179           0 :   if( FD_UNLIKELY( ctx->net.router.netlnk_out_idx==ULONG_MAX ) ) FD_LOG_ERR(( "netlink request link not found" ));
    1180           0 :   ctx->net.router.solicit_ip = 0U;
    1181             : 
    1182           0 :   ctx->waker_fseq = NULL;
    1183           0 :   if( FD_UNLIKELY( tile->is_waker_client ) ) {
    1184           0 :     ctx->waker_fseq = fd_fseq_join( fd_topo_obj_laddr( topo, tile->waker_fseq_obj_id ) );
    1185           0 :     FD_TEST( ctx->waker_fseq );
    1186           0 :   }
    1187             : 
    1188           0 :   for( uint j=0U; j<2U; j++ ) {
    1189           0 :     ctx->tx_flusher[ j ].pending_wmark         = (ulong)( (double)tile->xdp.xdp_tx_queue_size * 0.7 );
    1190           0 :     ctx->tx_flusher[ j ].tail_flush_backoff    = (long)( (double)tile->xdp.tx_flush_timeout_ns * fd_tempo_tick_per_ns( NULL ) );
    1191           0 :     ctx->tx_flusher[ j ].next_tail_flush_ticks = LONG_MAX;
    1192             : 
    1193           0 :     ctx->tx_flusher[ j ].prefbusy_last_poll_ticks     = 0L;
    1194           0 :     ctx->tx_flusher[ j ].prefbusy_min_interval_ticks  = (long)( PREFBUSY_MIN_INTERVAL_NS * fd_tempo_tick_per_ns( NULL ) );
    1195           0 :     ctx->tx_flusher[ j ].prefbusy_stall_timeout_ticks = (long)( PREFBUSY_STALL_TIMEOUT_NS * fd_tempo_tick_per_ns( NULL ) );
    1196           0 :   }
    1197             : 
    1198           0 :   ulong neigh4_obj_id = tile->xdp.neigh4_obj_id;
    1199           0 :   ulong ele_max   = fd_pod_queryf_ulong( topo->props, ULONG_MAX, "obj.%lu.ele_max",   neigh4_obj_id );
    1200           0 :   ulong probe_max = fd_pod_queryf_ulong( topo->props, ULONG_MAX, "obj.%lu.probe_max", neigh4_obj_id );
    1201           0 :   ulong seed      = fd_pod_queryf_ulong( topo->props, ULONG_MAX, "obj.%lu.seed",      neigh4_obj_id );
    1202           0 :   if( FD_UNLIKELY( (ele_max==ULONG_MAX) | (probe_max==ULONG_MAX) | (seed==ULONG_MAX) ) )
    1203           0 :     FD_LOG_ERR(( "neigh4 hmap properties not set" ));
    1204           0 :   if( FD_UNLIKELY( !fd_neigh4_hmap_join(
    1205           0 :       ctx->net.router.neigh4,
    1206           0 :       fd_topo_obj_laddr( topo, neigh4_obj_id ),
    1207           0 :       ele_max,
    1208           0 :       probe_max,
    1209           0 :       seed ) ) ) {
    1210           0 :     FD_LOG_ERR(( "fd_neigh4_hmap_join failed" ));
    1211           0 :   }
    1212             : 
    1213           0 :   init_device_table( ctx, fd_topo_obj_laddr( topo, tile->xdp.netdev_tbl_obj_id ), netdev_tbl_local );
    1214             : 
    1215             :   /* Initialize TX free ring */
    1216             : 
    1217           0 :   ulong const frame_sz  = 2048UL;
    1218           0 :   ulong       frame_off = 0UL;
    1219           0 :   ulong const tx_depth  = ctx->free_tx.depth;
    1220           0 :   for( ulong j=0; j<tx_depth; j++ ) {
    1221           0 :     ctx->free_tx.queue[ j ] = (ulong)ctx->umem + frame_off;
    1222           0 :     frame_off += frame_sz;
    1223           0 :   }
    1224           0 :   ctx->free_tx.prod = tx_depth;
    1225             : 
    1226             :   /* Initialize RX mcache chunks */
    1227             : 
    1228           0 :   for( ulong i=0UL; i<(tile->out_cnt); i++ ) {
    1229           0 :     fd_topo_link_t const * out_link = &topo->links[ tile->out_link_id[ i  ] ];
    1230           0 :     fd_frag_meta_t * mcache = out_link->mcache;
    1231           0 :     for( ulong j=0UL; j<fd_mcache_depth( mcache ); j++ ) {
    1232           0 :       mcache[ j ].chunk = (uint)( ctx->net.pkt_buf_chunk0 + (frame_off>>FD_CHUNK_LG_SZ) );
    1233           0 :       frame_off += frame_sz;
    1234           0 :     }
    1235           0 :   }
    1236             : 
    1237             :   /* Initialize FILL ring */
    1238             : 
    1239           0 :   int _charge_busy = 0;
    1240           0 :   for( uint j=0U; j<ctx->xsk_cnt; j++ ) {
    1241           0 :     frame_off = net_xsk_bootstrap( ctx, j, frame_off );
    1242           0 :     net_rx_wakeup( ctx, &ctx->xsk[ j ], &_charge_busy );
    1243           0 :     net_tx_wakeup( ctx, &ctx->xsk[ j ], &_charge_busy );
    1244           0 :   }
    1245             : 
    1246           0 :   if( FD_UNLIKELY( frame_off > ctx->umem_sz ) ) {
    1247           0 :     FD_LOG_ERR(( "UMEM is too small" ));
    1248           0 :   }
    1249           0 : }
    1250             : 
    1251             : FD_FN_UNUSED static ulong
    1252             : populate_allowed_seccomp( fd_topo_t const *      topo,
    1253             :                           fd_topo_tile_t const * tile,
    1254             :                           ulong                  out_cnt,
    1255           0 :                           struct sock_filter *   out ) {
    1256           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    1257           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    1258           0 :   fd_net_ctx_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof( fd_net_ctx_t ), sizeof( fd_net_ctx_t ) );
    1259             : 
    1260             :   /* A bit of a hack, if there is no loopback XSK for this tile, we still need to pass
    1261             :      two "allow" FD arguments to the net policy, so we just make them both the same. */
    1262           0 :   int allow_fd2 = ctx->xsk_cnt>1UL ? ctx->xsk[ 1 ].xsk_fd : ctx->xsk[ 0 ].xsk_fd;
    1263           0 :   FD_TEST( ctx->xsk[ 0 ].xsk_fd >= 0 && allow_fd2 >= 0 && ctx->net.sock.sock >= 0 );
    1264             : 
    1265             :   /* not a waker client in performance mode: no fd matches, epoll_ctl denied */
    1266           0 :   uint epoll_inner_fd = tile->is_waker_client ? (uint)FD_WAKER_INNER_FD( tile->waker_client_idx ) : (uint)-1;
    1267           0 :   uint epoll_outer_fd = tile->is_waker_client ? (uint)FD_WAKER_OUTER_FD : (uint)-1;
    1268           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,
    1269           0 :                                            (uint)ctx->net.sock.sock, epoll_inner_fd, epoll_outer_fd );
    1270           0 :   return sock_filter_policy_fd_xdp_tile_instr_cnt;
    1271           0 : }
    1272             : 
    1273             : FD_FN_UNUSED static ulong
    1274             : populate_allowed_fds( fd_topo_t const *      topo,
    1275             :                       fd_topo_tile_t const * tile,
    1276             :                       ulong                  out_fds_cnt,
    1277           0 :                       int *                  out_fds ) {
    1278           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    1279           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    1280           0 :   fd_net_ctx_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof( fd_net_ctx_t ), sizeof( fd_net_ctx_t ) );
    1281             : 
    1282           0 :   if( FD_UNLIKELY( out_fds_cnt<9UL ) ) FD_LOG_ERR(( "out_fds_cnt %lu", out_fds_cnt ));
    1283             : 
    1284           0 :   ulong out_cnt = 0UL;
    1285             : 
    1286           0 :   out_fds[ out_cnt++ ] = 2; /* stderr */
    1287           0 :   if( FD_LIKELY( -1!=fd_log_private_logfile_fd() ) )
    1288           0 :     out_fds[ out_cnt++ ] = fd_log_private_logfile_fd(); /* logfile */
    1289             : 
    1290           0 :                                       out_fds[ out_cnt++ ] = ctx->xsk[ 0 ].xsk_fd;
    1291           0 :                                       out_fds[ out_cnt++ ] = ctx->prog_link_fds[ 0 ];
    1292           0 :                                       out_fds[ out_cnt++ ] = ctx->net.sock.sock; /* routing fallback socket */
    1293           0 :   if( FD_LIKELY( ctx->xsk_cnt>1UL ) ) out_fds[ out_cnt++ ] = ctx->xsk[ 1 ].xsk_fd;
    1294           0 :   if( FD_LIKELY( ctx->xsk_cnt>1UL ) ) out_fds[ out_cnt++ ] = ctx->prog_link_fds[ 1 ];
    1295           0 :   if( FD_UNLIKELY( tile->is_waker_client ) ) {
    1296           0 :     out_fds[ out_cnt++ ] = FD_WAKER_OUTER_FD;                           /* waker outer epoll fd (rearm) */
    1297           0 :     out_fds[ out_cnt++ ] = FD_WAKER_INNER_FD( tile->waker_client_idx ); /* waker inner epoll fd */
    1298           0 :   }
    1299           0 :   return out_cnt;
    1300           0 : }
    1301             : 
    1302           0 : #define STEM_BURST (1UL)
    1303           0 : #define STEM_LAZY ((ulong)30e3) /* 30 us */
    1304             : 
    1305           0 : #define STEM_CALLBACK_CONTEXT_TYPE  fd_net_ctx_t
    1306           0 : #define STEM_CALLBACK_CONTEXT_ALIGN alignof(fd_net_ctx_t)
    1307             : 
    1308           0 : #define STEM_CALLBACK_METRICS_WRITE       metrics_write
    1309           0 : #define STEM_CALLBACK_DURING_HOUSEKEEPING during_housekeeping
    1310             : #define STEM_CALLBACK_PREVENT_PARK        prevent_park
    1311           0 : #define STEM_CALLBACK_BEFORE_CREDIT       before_credit
    1312           0 : #define STEM_CALLBACK_BEFORE_FRAG         before_frag
    1313           0 : #define STEM_CALLBACK_DURING_FRAG         during_frag
    1314           0 : #define STEM_CALLBACK_AFTER_FRAG          after_frag
    1315             : 
    1316             : #include "../../stem/fd_stem.c"
    1317             : 
    1318             : #ifndef FD_TILE_TEST
    1319             : fd_topo_run_tile_t fd_tile_net = {
    1320             :   .name                     = "net",
    1321             :   .populate_allowed_seccomp = populate_allowed_seccomp,
    1322             :   .populate_allowed_fds     = populate_allowed_fds,
    1323             :   .scratch_align            = scratch_align,
    1324             :   .scratch_footprint        = scratch_footprint,
    1325             :   .privileged_init          = privileged_init,
    1326             :   .unprivileged_init        = unprivileged_init,
    1327             :   .run                      = stem_run,
    1328             : };
    1329             : #endif

Generated by: LCOV version 1.14