LCOV - code coverage report
Current view: top level - disco/pack - fd_pack_tile.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 0 807 0.0 %
Date: 2026-11-11 12:40:43 Functions: 0 20 0.0 %

          Line data    Source code
       1             : #include "../tiles.h"
       2             : 
       3             : #include <linux/futex.h>
       4             : #include "generated/fd_pack_tile_seccomp.h"
       5             : 
       6             : #include "../../util/pod/fd_pod_format.h"
       7             : #include "../../discof/replay/fd_replay_tile.h" // layering violation
       8             : #include "../fd_txn_m.h"
       9             : #include "../keyguard/fd_keyload.h"
      10             : #include "../keyguard/fd_keyswitch.h"
      11             : #include "../keyguard/fd_keyguard.h"
      12             : #include "../keyguard/fd_keyguard_client.h"
      13             : #include "../metrics/fd_metrics.h"
      14             : #include "../pack/fd_pack.h"
      15             : #include "../pack/fd_pack_cost.h"
      16             : #include "../pack/fd_pack_pacing.h"
      17             : #include "../fd_clock_tile.h"
      18             : 
      19             : #include <string.h>
      20             : 
      21             : /* fd_pack is responsible for taking verified transactions, and
      22             :    arranging them into "microblocks" (groups) of transactions to
      23             :    be executed serially.  It can try to do clever things so that
      24             :    multiple microblocks can execute in parallel, if they don't
      25             :    write to the same accounts. */
      26             : 
      27           0 : #define IN_KIND_RESOLV       (0UL)
      28           0 : #define IN_KIND_EXECLE       (2UL)
      29           0 : #define IN_KIND_SIGN         (3UL)
      30           0 : #define IN_KIND_REPLAY       (4UL)
      31             : 
      32             : /* Minimum time between microblocks per execle.  Zero disables pacing. */
      33           0 : #define MICROBLOCK_DURATION_NS  (0L)
      34             : 
      35             : /* There are 151 accepted blockhashes.  The execle tile does the final
      36             :    check, but making this as precise as possible limits spam.  When we
      37             :    aren't leader, we don't have much information about what replay is
      38             :    doing, but we still want to be able to expire transactions before we
      39             :    become leader, so we snoop on the block heights of the recent
      40             :    blockhashes of transactions coming from resolv.  There's a small
      41             :    possibility that these are on a different fork than the one we become
      42             :    leader for, so we might not want to be fully strict until becoming
      43             :    leader, but having to delete a bunch of expired transactions lead to
      44             :    a 100us delay in sending out the first shred. */
      45           0 : #define TRANSACTION_LIFETIME_SLOTS 151UL
      46             : 
      47             : /* Time is normally a long, but pack expects a ulong.  Add -LONG_MIN to
      48             :    the time values so that LONG_MIN maps to 0, LONG_MAX maps to
      49             :    ULONG_MAX, and everything in between maps linearly with a slope of 1.
      50             :    Just subtracting LONG_MIN results in signed integer overflow, which
      51             :    is U.B. */
      52             : #define TIME_OFFSET 0x8000000000000000UL
      53             : FD_STATIC_ASSERT( (ulong)LONG_MIN+TIME_OFFSET==0UL,       time_offset );
      54             : FD_STATIC_ASSERT( (ulong)LONG_MAX+TIME_OFFSET==ULONG_MAX, time_offset );
      55             : 
      56             : /* 1.6 M cost units, enough for 1 max size transaction */
      57             : const ulong CUS_PER_MICROBLOCK = 1600000UL;
      58             : 
      59           0 : #define EFFECTIVE_TXN_PER_MICROBLOCK 1UL
      60             : 
      61             : 
      62             : 
      63             : /* Sync with src/app/shared/fd_config.c */
      64           0 : #define FD_PACK_STRATEGY_PERF     0
      65           0 : #define FD_PACK_STRATEGY_BALANCED 1
      66           0 : #define FD_PACK_STRATEGY_AUCTION  2
      67             : 
      68             : static char const * const schedule_strategy_strings[3] = { "PRF", "BAL", "AUC" };
      69             : 
      70             : /* Overview of how the "auction" strategy works:
      71             : 
      72             :    In the perf and balanced strategies, as soon as a transaction
      73             :    arrives it becomes eligible for scheduling. The auction strategy
      74             :    runs periodic batch "auctions". Transactions that arrive during the
      75             :    period when the auction is running are not immediately eligible for
      76             :    scheduling. These become eligible for scheduling when the auction
      77             :    ends. The exception is bundles, which are immediately eligible for
      78             :    scheduling regardless of whether an auction is running or not.
      79             : 
      80             :    Therefore, pack can be in one of 3 states:
      81             :    - 1) No auction running. New transactions that arrive are added to
      82             :         the pending/penalty treaps, but are not eligible for scheduling
      83             :         until the start of the next auction.
      84             :    - 2) Auction running. New transactions that arrive are added to the
      85             :         next_auction treap, which means they are not eligible for
      86             :         scheduling. Transactions in the pending/penalty treaps at the
      87             :         time of the auction starting are eligible for scheduling
      88             :         throughout the auction.
      89             :    - 3) The final 10ms of the leader rotation. All transactions are
      90             :         eligible for scheduling immediately.
      91             : 
      92             :    Each auction is limited to its proportional fraction of the blocks
      93             :    total CU limit. auction_cu_limit is the total block CU limit cost
      94             :    that the current auction cannot exceed. This is the fraction of the
      95             :    slot time (leader_slot_end_tick-leader_slot_start_tick) that will
      96             :    have elapsed when the auction ends (now+auction_interval_tick)
      97             :    multiplied by the total block CU limit (slot_max_cost).
      98             : 
      99             :    Auctions are run back to back, every 50ms (auction_interval_tick).
     100             :    auction_next_tick is the tick at which the next auction is due to
     101             :    start. This is set to start of the current auction +
     102             :    auction_interval_tick. Note that bundles adjust this value, to
     103             :    try and synchronize the start of the auction with a "burst" of
     104             :    bundles. This is because bundles typically arrive in bursts, and we
     105             :    want the pack auctions to coincide with the auctions held in the
     106             :    bundle engine. Therefore, each bundle arrival sets
     107             :    auction_next_tick to 5ms after that bundle arrived, so that the
     108             :    auction starts once the current bundle burst has ended. The
     109             :    following limits apply:
     110             :    - auction_next_tick can't be less than 40ms after the previous
     111             :      attempt (auction_last_attempt_tick + auction_spacing_tick). This
     112             :      is so that a short pause within a bundle burst does not trigger
     113             :      a new auction.
     114             :    - auction_next_tick can't be later than 50ms after the previous
     115             :      attempt (auction_last_attempt_tick + auction_interval_tick).
     116             : 
     117             :    Pack moves between the states as such:
     118             :    - An auction begins when we are leader, and all of the following are
     119             :      true:
     120             :      - The current tick (now) >= auction_next_tick
     121             :      - The current tick (now)  < auction_final_start_tick
     122             :      - The current block cost is less than the auction CU limit
     123             :        (auction_cu_limit). If the auction has exceeded the limit the
     124             :        attempt is cancelled, and tried again at the next
     125             :        auction_next_tick.
     126             :      Starting an auction means:
     127             :      - New transactions are held in next_auction and are not eligible
     128             :        for scheduling until the start of the next auction.
     129             :      - Transactions already in the pending/penalty treaps become
     130             :        eligible for scheduling.
     131             :    - An auction ends when we are leader, and one of the following is
     132             :      true:
     133             :      - The next auction is due (now>=auction_next_tick)
     134             :      - The current block cost has exceeded the auction CU limit
     135             :        (auction_cu_limit)
     136             :      - We are in the last 10ms of the leader rotation
     137             :        (now>=auction_final_start_tick)
     138             :      - The block ends for any other reason
     139             :      Ending an auction means:
     140             :      - Every transaction held in next_auction is moved into the
     141             :        penalty/pending treaps. New transactions are added to the
     142             :        penalty/pending treaps.
     143             :      - Transactions in the pending/penalty treaps are no longer eligible
     144             :        for scheduling, until the start of the next auction - unless
     145             :        we are in the final 10ms of the rotation.
     146             : 
     147             :    Note that none of the above applies to bundles, which are eligible
     148             :    for scheduling as soon as they arrive, on all execle tiles. */
     149             : 
     150             : /* FD_PACK_AUCTION_BUNDLE_END_GAP_NS is the amount of time for which,
     151             :    if we receive no bundles, we consider the bundle burst to be over. We
     152             :    start auctions after not observing any bundles for
     153             :    FD_PACK_AUCTION_BUNDLE_END_GAP_NS. This synchronizes the start of
     154             :    the auction with the end of the bundle burst. */
     155           0 : #define FD_PACK_AUCTION_BUNDLE_END_GAP_NS ( 5000000L)
     156             : 
     157             : /* FD_PACK_AUCTION_SPACING_NS is the minimum time gap between auctions.
     158             :    40ms was chosen so that a bundle burst with a short pause in the
     159             :    middle doesn't start two auctions. */
     160           0 : #define FD_PACK_AUCTION_SPACING_NS        (40000000L)
     161             : 
     162             : /* FD_PACK_AUCTION_INTERVAL_NS is the maximum time between auctions.
     163             :    This was chosen so that no transaction is ineligible for scheduling
     164             :    for more than 50ms. */
     165           0 : #define FD_PACK_AUCTION_INTERVAL_NS       (50000000L)
     166             : 
     167             : /* FD_PACK_AUCTION_FINAL_NS is the length of time before the end of the
     168             :    last slot of the leader rotation that we do not hold incoming
     169             :    transactions. This is so that all incoming transactions have a
     170             :    chance of being scheduled. */
     171           0 : #define FD_PACK_AUCTION_FINAL_NS          (10000000L)
     172             : 
     173             : 
     174             : typedef struct {
     175             :   fd_acct_addr_t commission_pubkey[1];
     176             :   ulong          commission;
     177             : } block_builder_info_t;
     178             : 
     179             : typedef struct {
     180             :   long time;
     181             :   ulong sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_CNT ];
     182             : } fd_pack_sched_results_snap_t;
     183             : 
     184             : typedef struct {
     185             :   fd_wksp_t * mem;
     186             :   ulong       chunk0;
     187             :   ulong       wmark;
     188             : } fd_pack_in_ctx_t;
     189             : 
     190             : typedef struct {
     191             :   fd_wksp_t * mem;
     192             :   ulong       chunk0;
     193             :   ulong       wmark;
     194             :   ulong       chunk;
     195             :   ulong       out_idx;
     196             : } fd_pack_out_ctx_t;
     197             : 
     198             : typedef struct {
     199             :   fd_pack_t *  pack;
     200             :   fd_txn_e_t * cur_spot;
     201             :   int          is_bundle; /* is the current transaction a bundle */
     202             : 
     203             :   uchar executed_txn_sig[ 64UL ];
     204             :   uchar txn_committed;
     205             : 
     206             :   /* One of the FD_PACK_STRATEGY_* values defined above */
     207             :   int      strategy;
     208             : 
     209             :   /* The value passed to fd_pack_new, etc. */
     210             :   ulong    max_pending_transactions;
     211             : 
     212             :   /* The leader slot we are currently packing for, or ULONG_MAX if we
     213             :      are not the leader. */
     214             :   ulong  leader_slot;
     215             :   ulong        leader_bank_idx;
     216             :   ulong        leader_bank_seq;
     217             : 
     218             :   /* The block height of the last slot for which we became leader */
     219             :   ulong        block_height;
     220             : 
     221             :   fd_became_leader_t _became_leader[1];
     222             : 
     223             :   /* The number of microblocks we have packed for the current leader
     224             :      slot.  Will always be <= slot_max_microblocks.  We must track
     225             :      this so that when we are done we can tell the PoH tile how many
     226             :      microblocks to expect in the slot. */
     227             :   ulong slot_microblock_cnt;
     228             : 
     229             :   /* Counter which increments when we've finished packing for a slot */
     230             :   uint pack_idx;
     231             : 
     232             :   ulong pack_txn_cnt; /* total num transactions packed since startup */
     233             : 
     234             :   long  slot_pack_start_ns;  /* wallclock ns production began for leader_slot */
     235             :   ulong slot_bundle_txn_cnt; /* bundled txns scheduled into leader_slot */
     236             : 
     237             :   /* The maximum number of microblocks that can be packed in this slot.
     238             :      Provided by the PoH tile when we become leader.*/
     239             :   ulong slot_max_microblocks;
     240             : 
     241             :   /* Cap (in bytes) of the amount of transaction data we produce in each
     242             :      block to avoid hitting the shred limits.  See where this is set for
     243             :      more explanation. */
     244             :   ulong slot_max_data;
     245             : 
     246             :   /* Consensus critical slot cost limits. */
     247             :   struct {
     248             :     ulong slot_max_cost;
     249             :     ulong slot_max_write_cost_per_acct;
     250             :     ulong slot_max_allocated_data_per_block;
     251             :     ulong slot_max_data_shreds;
     252             :   } limits;
     253             :   ulong bench_max_shreds_per_block; /* [development.bench], floors the leader's slot_max_data_shreds */
     254             : 
     255             :   /* If drain_execle is non-zero, then the pack tile must wait until all
     256             :      execle are idle before scheduling any more microblocks.  This is
     257             :      primarily helpful in irregular leader transitions, e.g. while being
     258             :      leader for slot N, we switch forks to a slot M (!=N+1) in which we
     259             :      are also leader.  We don't want to execute microblocks for
     260             :      different slots concurrently. */
     261             :   int drain_execle;
     262             : 
     263             :   fd_rng_t * rng;
     264             : 
     265             :   uint  rng_seed;
     266             :   ulong rng_idx;
     267             : 
     268             :   /* The end wallclock time of the leader slot we are currently packing
     269             :      for, if we are currently packing for a slot.*/
     270             :   long slot_end_ns;
     271             : 
     272             :   /* The batch auction bookkeeping state.
     273             :      leader_slot_start_tick:    the start tick of the leader slot
     274             :      leader_slot_end_tick:      the end tick of the leader slot
     275             :      auction_start_tick:        the tick when the current auction started
     276             :      auction_last_attempt_tick: the tick when we last started or skipped an auction
     277             :      auction_next_tick:         the tick when the next auction is due to be attempted
     278             :      auction_cu_limit:          the total number of CUs within a block at which the auction must stop (for pacing)
     279             :      auction_final_start_tick:  the tick at which the last auction in the rotation should end, to give any held transactions a chance to execute */
     280             :   long  leader_slot_start_tick;
     281             :   long  leader_slot_end_tick;
     282             :   long  auction_start_tick;
     283             :   long  auction_last_attempt_tick;
     284             :   long  auction_next_tick;
     285             :   long  auction_final_start_tick;
     286             :   ulong auction_cu_limit;
     287             : 
     288             :   /* The FD_PACK_AUCTION_*_NS constants, in ticks */
     289             :   long  auction_bundle_end_gap_tick;
     290             :   long  auction_spacing_tick;
     291             :   long  auction_interval_tick;
     292             : 
     293             :   /* pacer is used for pacing CUs through the slot, i.e. deciding when
     294             :      to schedule a microblock given the number of CUs that have been
     295             :      consumed so far.  It is an opaque pacing object, initialized when
     296             :      the pack tile is packing a slot. */
     297             :   fd_pack_pacing_t pacer[1];
     298             : 
     299             :   fd_clock_tile_t  clock[1];
     300             : 
     301             :   /* last_successful_insert stores the tickcount of the last
     302             :      successful transaction insert. */
     303             :   long last_successful_insert;
     304             : 
     305             :   /* highest_observed_block_height stores the highest block height we've
     306             :      seen from any transaction coming from the resolv tile.  When this
     307             :      increases, we expire old transactions. */
     308             :   ulong highest_observed_block_height;
     309             : 
     310             :   /* microblock_duration_ns scaled to be in ticks instead of nanoseconds */
     311             :   ulong microblock_duration_ticks;
     312             : 
     313             :   fd_pack_in_ctx_t in[ FD_TOPO_MAX_TILE_IN_LINKS ];
     314             :   int              in_kind[ FD_TOPO_MAX_TILE_IN_LINKS ];
     315             : 
     316             :   ulong    execle_cnt;
     317             :   ulong    execle_idle_bitset; /* bit i is 1 if we've observed *execle_current[i]==execle_expect[i] */
     318             :   int      poll_cursor; /* in [0, execle_cnt), the next execle to poll */
     319             :   int      use_consumed_cus;
     320             :   long     skip_cnt;
     321             :   ulong *  execle_current[ FD_PACK_MAX_EXECLE_TILES ];
     322             :   ulong    execle_expect[ FD_PACK_MAX_EXECLE_TILES  ];
     323             :   /* execle_ready_at[x] means don't check execle x until tickcount is at
     324             :      least execle_ready_at[x]. */
     325             :   long     execle_ready_at[ FD_PACK_MAX_EXECLE_TILES  ];
     326             : 
     327             :   fd_pack_out_ctx_t execle_out[ FD_PACK_MAX_EXECLE_TILES ];
     328             :   fd_pack_out_ctx_t poh_out;
     329             : 
     330             :   ulong      insert_result[ FD_PACK_INSERT_RETVAL_CNT ];
     331             :   fd_histf_t schedule_duration[ 1 ];
     332             :   fd_histf_t no_sched_duration[ 1 ];
     333             :   fd_histf_t insert_duration  [ 1 ];
     334             :   fd_histf_t complete_duration[ 1 ];
     335             : 
     336             :   ulong      auction_started;
     337             :   ulong      auction_cancelled;
     338             :   ulong      auction_ended    [ FD_METRICS_ENUM_PACK_AUCTION_END_REASON_CNT   ];
     339             :   fd_histf_t auction_duration [ 1 ];
     340             : 
     341             :   struct {
     342             :     uint metric_state;
     343             :     long metric_state_begin;
     344             :     long metric_timing[ 16 ];
     345             :   };
     346             : 
     347             :   /* last_sched_metrics is a snapshot of the schedule outcome counters
     348             :      during the last schedule which included at least one successful
     349             :      outcome. */
     350             :   fd_pack_sched_results_snap_t last_sched_metrics[ 1 ];
     351             : 
     352             :     /* last_sched_metrics is a snapshot of the schedule outcome counters
     353             :        at the last start-of-leader-block event. */
     354             :   fd_pack_sched_results_snap_t start_block_sched_metrics[ 1 ];
     355             : 
     356             :   struct {
     357             :     ulong id;
     358             :     ulong txn_cnt;
     359             :     ulong txn_received;
     360             :     ulong min_blockhash_height;
     361             :     fd_txn_e_t * _txn[ FD_PACK_MAX_TXN_PER_BUNDLE ];
     362             :     fd_txn_e_t * const * bundle; /* points to _txn when non-NULL */
     363             :   } current_bundle[1];
     364             : 
     365             :   block_builder_info_t blk_engine_cfg[1];
     366             : 
     367             :   struct {
     368             :     int                   enabled;
     369             :     int                   ib_inserted; /* in this slot */
     370             :     fd_acct_addr_t        vote_pubkey[1];
     371             :     fd_acct_addr_t        identity_pubkey[1];
     372             :     fd_bundle_crank_gen_t gen[1];
     373             :     fd_acct_addr_t        tip_receiver_owner[1];
     374             :     ulong                 epoch;
     375             :     fd_bundle_crank_tip_payment_config_t prev_config[1]; /* as of start of slot, then updated */
     376             :     uchar                 recent_blockhash[32];
     377             :     fd_ed25519_sig_t      last_sig[1];
     378             : 
     379             :     fd_keyswitch_t *      keyswitch;
     380             :     fd_keyguard_client_t  keyguard_client[1];
     381             : 
     382             :     ulong                 metrics[4];
     383             :   } crank[1];
     384             : 
     385             : 
     386             :   /* Used between during_frag and after_frag */
     387             :   ulong pending_rebate_sz;
     388             :   union{ fd_pack_rebate_t rebate[1]; uchar footprint[USHORT_MAX]; } rebate[1];
     389             : } fd_pack_ctx_t;
     390             : 
     391           0 : #define BUNDLE_META_SZ 40UL
     392             : FD_STATIC_ASSERT( sizeof(block_builder_info_t)==BUNDLE_META_SZ, blk_engine_cfg );
     393             : 
     394           0 : #define FD_PACK_METRIC_STATE_TRANSACTIONS 0
     395           0 : #define FD_PACK_METRIC_STATE_EXECLES      1
     396           0 : #define FD_PACK_METRIC_STATE_LEADER       2
     397           0 : #define FD_PACK_METRIC_STATE_MICROBLOCKS  3
     398             : 
     399             : /* Updates one component of the metric state.  If the state has changed,
     400             :    records the change.  effective_as_of may be earlier than the last
     401             :    update in the same callback, which credits nothing. */
     402             : static inline void
     403             : update_metric_state( fd_pack_ctx_t * ctx,
     404             :                      long            effective_as_of,
     405             :                      int             type,
     406           0 :                      int             status ) {
     407           0 :   uint current_state = fd_uint_insert_bit( ctx->metric_state, type, status );
     408           0 :   if( FD_UNLIKELY( current_state!=ctx->metric_state ) ) {
     409           0 :     ctx->metric_timing[ ctx->metric_state ] += fd_long_max( effective_as_of-ctx->metric_state_begin, 0L );
     410           0 :     ctx->metric_state_begin = fd_long_max( effective_as_of, ctx->metric_state_begin );
     411           0 :     ctx->metric_state = current_state;
     412           0 :   }
     413           0 : }
     414             : 
     415             : static inline void
     416           0 : remove_ib( fd_pack_ctx_t * ctx ) {
     417             :   /* It's likely the initializer bundle is long scheduled, but we want to
     418             :      try deleting it just in case. */
     419           0 :   if( FD_UNLIKELY( ctx->crank->enabled & ctx->crank->ib_inserted ) ) {
     420           0 :     ulong deleted = fd_pack_delete_transaction( ctx->pack, (fd_ed25519_sig_t const *)ctx->crank->last_sig );
     421           0 :     FD_MCNT_INC( PACK, TXN_EVICTED, deleted );
     422           0 :   }
     423           0 :   ctx->crank->ib_inserted = 0;
     424           0 : }
     425             : 
     426             : 
     427             : FD_FN_CONST static inline ulong
     428           0 : scratch_align( void ) {
     429           0 :   return 4096UL;
     430           0 : }
     431             : 
     432             : FD_FN_PURE static inline ulong
     433           0 : scratch_footprint( fd_topo_tile_t const * tile ) {
     434           0 :   fd_pack_limits_t limits[1] = {{
     435           0 :     .max_cost_per_block           = tile->pack.max_cost_per_block,
     436           0 :     .max_write_cost_per_acct      = FD_PACK_MAX_WRITE_COST_PER_ACCT_UPPER_BOUND,
     437           0 :     .max_data_bytes_per_block     = FD_PACK_MAX_DATA_PER_BLOCK*(tile->pack.max_shreds_per_block/FD_SHRED_BLK_MAX),
     438           0 :     .max_txn_per_microblock       = EFFECTIVE_TXN_PER_MICROBLOCK,
     439           0 :     .max_microblocks_per_block    = (ulong)UINT_MAX, /* Limit not known yet */
     440           0 :     .max_allocated_data_per_block = FD_PACK_MAX_ALLOCATED_DATA_PER_BLOCK,
     441           0 :   }};
     442             : 
     443           0 :   ulong l = FD_LAYOUT_INIT;
     444           0 :   l = FD_LAYOUT_APPEND( l, alignof( fd_pack_ctx_t ), sizeof( fd_pack_ctx_t )                                   );
     445           0 :   l = FD_LAYOUT_APPEND( l, fd_rng_align(),           fd_rng_footprint()                                        );
     446           0 :   l = FD_LAYOUT_APPEND( l, fd_pack_align(),          fd_pack_footprint( tile->pack.max_pending_transactions,
     447           0 :                                                                         BUNDLE_META_SZ,
     448           0 :                                                                         tile->pack.execle_tile_count,
     449           0 :                                                                         limits                               ) );
     450           0 :   return FD_LAYOUT_FINI( l, scratch_align() );
     451           0 : }
     452             : 
     453             : static inline void
     454             : log_end_block_metrics( fd_pack_ctx_t * ctx,
     455             :                        long            now,
     456             :                        char const    * reason,
     457           0 :                        ulong           cus_consumed_in_block ) {
     458           0 : #define DELTA( m ) (fd_metrics_tl[ MIDX(COUNTER, PACK, TXN_SCHEDULE_ATTEMPTED_##m) ] - ctx->last_sched_metrics->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_##m##_IDX ])
     459           0 : #define AVAIL( m ) (fd_metrics_tl[ MIDX(GAUGE, PACK, TXN_PENDING_USED_##m) ])
     460           0 :     FD_LOG_INFO(( "pack_end_block(slot=%lu,%s,%lx,ticks_since_last_schedule=%ld,reasons=%lu,%lu,%lu,%lu,%lu,%lu,%lu,%lu;remaining=%lu+%lu+%lu+%lu;smallest=%lu;cus=%lu->%lu)",
     461           0 :           ctx->leader_slot, reason, ctx->execle_idle_bitset, now-ctx->last_sched_metrics->time,
     462           0 :           DELTA( TAKEN ), DELTA( CU_LIMIT ), DELTA( CONFLICT_FAST ), DELTA( BYTE_LIMIT ), DELTA( ALLOC_LIMIT ), DELTA( WRITE_COST ), DELTA( CONFLICT_SLOW ), DELTA( WRITE_COST_DEFERRED ),
     463           0 :           AVAIL(REGULAR), AVAIL(VOTE), AVAIL(BUNDLE), AVAIL(CONFLICTING),
     464           0 :           (fd_metrics_tl[ MIDX(GAUGE, PACK, TXN_PENDING_SMALLEST_COST) ]),
     465           0 :           (cus_consumed_in_block),
     466           0 :           (fd_metrics_tl[ MIDX(GAUGE, PACK, BLOCK_COST) ])
     467           0 :     ));
     468           0 : #undef AVAIL
     469           0 : #undef DELTA
     470           0 : }
     471             : 
     472             : static inline void
     473           0 : get_done_packing( fd_pack_ctx_t * ctx, fd_done_packing_t * done_packing, int reason ) {
     474           0 :   fd_pack_metrics_write( ctx->pack );
     475             : 
     476           0 :   done_packing->microblocks_in_slot = ctx->slot_microblock_cnt;
     477           0 :   done_packing->end_slot_reason = reason;
     478           0 :   fd_pack_get_block_limits( ctx->pack, done_packing->limits_usage, done_packing->limits );
     479             : 
     480           0 : #define DELTA( mem, m ) (fd_metrics_tl[ MIDX(COUNTER, PACK, TXN_SCHEDULE_ATTEMPTED_##m) ] - ctx->mem->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_##m##_IDX ])
     481           0 :     done_packing->block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_TAKEN_IDX               ] = DELTA( start_block_sched_metrics, TAKEN               );
     482           0 :     done_packing->block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_CU_LIMIT_IDX            ] = DELTA( start_block_sched_metrics, CU_LIMIT            );
     483           0 :     done_packing->block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_CONFLICT_FAST_IDX       ] = DELTA( start_block_sched_metrics, CONFLICT_FAST       );
     484           0 :     done_packing->block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_BYTE_LIMIT_IDX          ] = DELTA( start_block_sched_metrics, BYTE_LIMIT          );
     485           0 :     done_packing->block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_ALLOC_LIMIT_IDX         ] = DELTA( start_block_sched_metrics, ALLOC_LIMIT         );
     486           0 :     done_packing->block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_WRITE_COST_IDX          ] = DELTA( start_block_sched_metrics, WRITE_COST          );
     487           0 :     done_packing->block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_CONFLICT_SLOW_IDX       ] = DELTA( start_block_sched_metrics, CONFLICT_SLOW       );
     488           0 :     done_packing->block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_WRITE_COST_DEFERRED_IDX ] = DELTA( start_block_sched_metrics, WRITE_COST_DEFERRED );
     489             : 
     490           0 :     done_packing->end_block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_TAKEN_IDX               ] = DELTA( last_sched_metrics, TAKEN               );
     491           0 :     done_packing->end_block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_CU_LIMIT_IDX            ] = DELTA( last_sched_metrics, CU_LIMIT            );
     492           0 :     done_packing->end_block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_CONFLICT_FAST_IDX       ] = DELTA( last_sched_metrics, CONFLICT_FAST       );
     493           0 :     done_packing->end_block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_BYTE_LIMIT_IDX          ] = DELTA( last_sched_metrics, BYTE_LIMIT          );
     494           0 :     done_packing->end_block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_ALLOC_LIMIT_IDX         ] = DELTA( last_sched_metrics, ALLOC_LIMIT         );
     495           0 :     done_packing->end_block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_WRITE_COST_IDX          ] = DELTA( last_sched_metrics, WRITE_COST          );
     496           0 :     done_packing->end_block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_CONFLICT_SLOW_IDX       ] = DELTA( last_sched_metrics, CONFLICT_SLOW       );
     497           0 :     done_packing->end_block_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_WRITE_COST_DEFERRED_IDX ] = DELTA( last_sched_metrics, WRITE_COST_DEFERRED );
     498           0 : #undef DELTA
     499             : 
     500           0 :   fd_pack_get_pending_smallest( ctx->pack, done_packing->pending_smallest );
     501             : 
     502           0 :   done_packing->bundle_txn_count = ctx->slot_bundle_txn_cnt;
     503           0 :   done_packing->pack_start_ns    = ctx->slot_pack_start_ns;
     504           0 :   done_packing->pack_end_ns      = fd_clock_tile_now( ctx->clock );
     505           0 : }
     506             : 
     507             : static inline void
     508           0 : metrics_write( fd_pack_ctx_t * ctx ) {
     509           0 :   long now = fd_tickcount();
     510           0 :   ctx->metric_timing[ ctx->metric_state ] += fd_long_max( now-ctx->metric_state_begin, 0L );
     511           0 :   ctx->metric_state_begin = fd_long_max( now, ctx->metric_state_begin );
     512             : 
     513           0 :   FD_MCNT_ENUM_COPY( PACK, TXN_INSERT_ATTEMPTED,          ctx->insert_result  );
     514           0 :   FD_MCNT_ENUM_COPY( PACK, SCHEDULE_REGIME_DURATION_NANOS,        ((ulong*)ctx->metric_timing) );
     515           0 :   FD_MCNT_ENUM_COPY( PACK, BUNDLE_CRANK_ATTEMPTED,           ctx->crank->metrics );
     516           0 :   FD_MHIST_COPY( PACK, MICROBLOCK_SCHEDULE_DURATION_NANOS, ctx->schedule_duration );
     517           0 :   FD_MHIST_COPY( PACK, MICROBLOCK_SCHEDULE_EMPTY_DURATION_NANOS, ctx->no_sched_duration );
     518           0 :   FD_MHIST_COPY( PACK, TXN_INSERT_DURATION_NANOS,            ctx->insert_duration   );
     519           0 :   FD_MHIST_COPY( PACK, MICROBLOCK_COMPLETE_DURATION_NANOS,   ctx->complete_duration );
     520           0 :   FD_MCNT_SET      ( PACK, AUCTION_STARTED,        ctx->auction_started   );
     521           0 :   FD_MCNT_SET      ( PACK, AUCTION_CANCELLED,      ctx->auction_cancelled );
     522           0 :   FD_MCNT_ENUM_COPY( PACK, AUCTION_ENDED,          ctx->auction_ended     );
     523           0 :   FD_MHIST_COPY    ( PACK, AUCTION_DURATION_NANOS, ctx->auction_duration  );
     524             : 
     525           0 :   fd_pack_metrics_write( ctx->pack );
     526           0 : }
     527             : 
     528             : static inline void
     529           0 : during_housekeeping( fd_pack_ctx_t * ctx ) {
     530           0 :   if( FD_UNLIKELY( fd_clock_tile_recal_due( ctx->clock ) ) ) {
     531           0 :     fd_clock_tile_recal( ctx->clock );
     532           0 :   }
     533             : 
     534           0 :   if( FD_UNLIKELY( ctx->crank->enabled && fd_keyswitch_state_query( ctx->crank->keyswitch )==FD_KEYSWITCH_STATE_SWITCH_PENDING ) ) {
     535           0 :     fd_memcpy( ctx->crank->identity_pubkey, ctx->crank->keyswitch->bytes, 32UL );
     536           0 :     fd_keyswitch_state( ctx->crank->keyswitch, FD_KEYSWITCH_STATE_COMPLETED );
     537           0 :   }
     538           0 : }
     539             : 
     540             : static inline void
     541             : before_credit( fd_pack_ctx_t *     ctx,
     542             :                fd_stem_context_t * stem,
     543           0 :                int *               charge_busy ) {
     544           0 :   (void)stem;
     545             : 
     546           0 :   if( FD_UNLIKELY( (ctx->cur_spot!=NULL) & !ctx->is_bundle ) ) {
     547           0 :     *charge_busy = 1;
     548             : 
     549             :     /* If we were overrun while processing a frag from an in, then
     550             :        cur_spot is left dangling and not cleaned up, so clean it up here
     551             :        (by returning the slot to the pool of free slots).  If the last
     552             :        transaction was a bundle, then we don't want to return it.  When
     553             :        we try to process the first transaction in the next bundle, we'll
     554             :        see we never got the full bundle and cancel the whole last
     555             :        bundle, returning all the storage to the pool. */
     556           0 :     fd_pack_insert_txn_cancel( ctx->pack, ctx->cur_spot );
     557           0 :     ctx->cur_spot = NULL;
     558           0 :   }
     559           0 : }
     560             : 
     561             : static inline int
     562           0 : prevent_park( fd_pack_ctx_t * ctx ) {
     563             :   /* skip_cnt counts loop iterations, not time, never park through it */
     564           0 :   return ctx->skip_cnt>0L;
     565           0 : }
     566             : 
     567             : static inline void
     568             : auction_end( fd_pack_ctx_t * ctx,
     569             :              long            now_tick,
     570           0 :              ulong           reason ) {
     571           0 :   if( !fd_pack_auction_running( ctx->pack ) ) return;
     572           0 :   ctx->auction_ended[ reason ]++;
     573           0 :   fd_histf_sample( ctx->auction_duration, (ulong)fd_long_max( now_tick-ctx->auction_start_tick, 0L ) );
     574           0 :   fd_pack_auction_end( ctx->pack );
     575           0 : }
     576             : 
     577             : static inline void
     578             : auction_begin( fd_pack_ctx_t * ctx,
     579           0 :                long            now_tick ) {
     580           0 :   ctx->auction_last_attempt_tick = now_tick;
     581           0 :   ctx->auction_next_tick         = now_tick+ctx->auction_interval_tick;
     582             : 
     583           0 :   long  span    = fd_long_max( ctx->leader_slot_end_tick-ctx->leader_slot_start_tick, 1L );
     584           0 :   long  elapsed = fd_long_min( fd_long_max( now_tick+ctx->auction_interval_tick-ctx->leader_slot_start_tick, 0L ), span );
     585           0 :   ulong limit   = (ulong)( (double)ctx->limits.slot_max_cost*(double)elapsed/(double)span );
     586           0 :   if( FD_UNLIKELY( fd_pack_current_block_cost( ctx->pack )>=limit ) ) {
     587           0 :     ctx->auction_cancelled++;
     588           0 :     return;
     589           0 :   }
     590             : 
     591           0 :   ctx->auction_started++;
     592           0 :   ctx->auction_start_tick = now_tick;
     593           0 :   ctx->auction_cu_limit   = limit;
     594           0 :   fd_pack_auction_begin( ctx->pack );
     595           0 : }
     596             : 
     597             : static inline long
     598           0 : next_deadline( fd_pack_ctx_t * ctx ) {
     599           0 :   if( FD_LIKELY( ctx->leader_slot==ULONG_MAX ) ) return LONG_MAX;
     600           0 :   long now      = fd_tickcount();
     601           0 :   long deadline = fd_clock_tile_wallclock_to_tickcount( ctx->clock, ctx->slot_end_ns );
     602           0 :   if( ctx->strategy==FD_PACK_STRATEGY_AUCTION ) {
     603           0 :     if( now<ctx->auction_final_start_tick ) {
     604           0 :       deadline = fd_long_min( deadline, fd_long_min( ctx->auction_next_tick, ctx->auction_final_start_tick ) );
     605           0 :     }
     606           0 :     return deadline;
     607           0 :   }
     608           0 :   ulong enabled = fd_ulong_min( fd_pack_pacing_enabled_bank_cnt( ctx->pacer, now ), ctx->execle_cnt );
     609           0 :   if( FD_UNLIKELY( enabled>=ctx->execle_cnt ) ) return deadline;
     610           0 :   return fd_long_min( deadline, fd_pack_pacing_next_enable( ctx->pacer, enabled ) );
     611           0 : }
     612             : 
     613             : static inline void
     614             : after_credit( fd_pack_ctx_t *     ctx,
     615             :               fd_stem_context_t * stem,
     616             :               int *               opt_poll_in FD_PARAM_UNUSED,
     617           0 :               int *               charge_busy ) {
     618           0 :   if( FD_UNLIKELY( (ctx->skip_cnt--)>0L ) ) return; /* It would take ages for this to hit LONG_MIN */
     619             : 
     620           0 :   long now = fd_tickcount();
     621             : 
     622           0 :   ulong execle_cnt = ctx->execle_cnt;
     623             : 
     624           0 :   int pacing_execle_cnt = (int)fd_ulong_min( fd_pack_pacing_enabled_bank_cnt( ctx->pacer, now ), execle_cnt );
     625             : 
     626             :   /* If any execle are busy, check one of the busy ones see if it is
     627             :      still busy. */
     628           0 :   if( FD_LIKELY( ctx->execle_idle_bitset!=fd_ulong_mask_lsb( (int)execle_cnt ) ) ) {
     629           0 :     int   poll_cursor = ctx->poll_cursor;
     630           0 :     ulong busy_bitset = (~ctx->execle_idle_bitset) & fd_ulong_mask_lsb( (int)execle_cnt );
     631             : 
     632             :     /* Suppose execle_cnt is 4 and idle_bitset looks something like this
     633             :        (pretending it's a uchar):
     634             :                 0000 1001
     635             :                        ^ busy cursor is 1
     636             :        Then busy_bitset is
     637             :                 0000 0110
     638             :        Rotate it right by 2 bits
     639             :                 1000 0001
     640             :        Find lsb returns 0, so busy cursor remains 2, and we poll
     641             :        execle 2.
     642             : 
     643             :        If instead idle_bitset were
     644             :                 0000 1110
     645             :                        ^
     646             :        The rotated version would be
     647             :                 0100 0000
     648             :        Find lsb will return 6, so busy cursor would be set to 0, and
     649             :        we'd poll execle 0, which is the right one. */
     650           0 :     poll_cursor++;
     651           0 :     poll_cursor = (poll_cursor + fd_ulong_find_lsb( fd_ulong_rotate_right( busy_bitset, (poll_cursor&63) ) )) & 63;
     652             : 
     653           0 :     if( FD_UNLIKELY(
     654             :         /* if microblock duration is 0, bypass the execle_ready_at check
     655             :            to avoid a potential cache miss.  Can't use an ifdef here
     656             :            because FD_UNLIKELY is a macro, but the compiler should
     657             :            eliminate the check easily. */
     658           0 :         ( (MICROBLOCK_DURATION_NS==0L) || (ctx->execle_ready_at[poll_cursor]<now) ) &&
     659           0 :         (fd_fseq_query( ctx->execle_current[poll_cursor] )==ctx->execle_expect[poll_cursor]) ) ) {
     660           0 :       *charge_busy = 1;
     661           0 :       ctx->execle_idle_bitset |= 1UL<<poll_cursor;
     662             : 
     663           0 :       long complete_duration = -fd_tickcount();
     664           0 :       int completed = fd_pack_microblock_complete( ctx->pack, (ulong)poll_cursor );
     665           0 :       complete_duration      += fd_tickcount();
     666           0 :       if( FD_LIKELY( completed ) ) fd_histf_sample( ctx->complete_duration, (ulong)complete_duration );
     667           0 :     }
     668             : 
     669           0 :     ctx->poll_cursor = poll_cursor;
     670           0 :   }
     671             : 
     672             : 
     673             :   /* If we time out on our slot, then stop being leader. */
     674           0 :   if( FD_UNLIKELY( ctx->leader_slot!=ULONG_MAX &&
     675           0 :                    fd_clock_tile_tickcount_to_wallclock( ctx->clock, now )>=ctx->slot_end_ns ) ) {
     676           0 :     *charge_busy = 1;
     677             : 
     678           0 :     fd_done_packing_t * done_packing = fd_chunk_to_laddr( ctx->poh_out.mem, ctx->poh_out.chunk );
     679           0 :     get_done_packing( ctx, done_packing, FD_PACK_END_SLOT_REASON_TIME ); /* needs to be called before fd_pack_end_block */
     680           0 :     log_end_block_metrics( ctx, now, "time", done_packing->limits_usage->block_cost ); /* reads gauges fd_pack_end_block resets */
     681           0 :     fd_pack_end_block( ctx->pack );
     682           0 :     fd_pack_get_top_writers( ctx->pack, done_packing->limits_usage->top_writers ); /* needs to be called after fd_pack_end_block */
     683             : 
     684           0 :     metrics_write( ctx );
     685           0 :     fd_stem_publish( stem, ctx->poh_out.out_idx, fd_disco_execle_sig( ctx->leader_slot, ctx->pack_idx ), ctx->poh_out.chunk, sizeof(fd_done_packing_t), 0UL, 0UL, fd_frag_meta_ts_comp( fd_tickcount() ) );
     686           0 :     ctx->poh_out.chunk = fd_dcache_compact_next( ctx->poh_out.chunk, sizeof(fd_done_packing_t), ctx->poh_out.chunk0, ctx->poh_out.wmark );
     687           0 :     ctx->pack_idx++;
     688             : 
     689           0 :     auction_end( ctx, now, FD_METRICS_ENUM_PACK_AUCTION_END_REASON_V_SLOT_END_IDX );
     690           0 :     ctx->drain_execle        = 1;
     691           0 :     ctx->leader_slot         = ULONG_MAX;
     692           0 :     ctx->slot_microblock_cnt = 0UL;
     693           0 :     remove_ib( ctx );
     694             : 
     695           0 :     update_metric_state( ctx, now, FD_PACK_METRIC_STATE_LEADER,       0 );
     696           0 :     update_metric_state( ctx, now, FD_PACK_METRIC_STATE_EXECLES,      0 );
     697           0 :     update_metric_state( ctx, now, FD_PACK_METRIC_STATE_MICROBLOCKS,  0 );
     698           0 :     return;
     699           0 :   }
     700             : 
     701             :   /* Am I in drain mode?  If so, check if I can exit it */
     702           0 :   if( FD_UNLIKELY( ctx->drain_execle ) ) {
     703           0 :     if( FD_LIKELY( ctx->execle_idle_bitset==fd_ulong_mask_lsb( (int)execle_cnt ) ) ) {
     704           0 :       ctx->drain_execle = 0;
     705             : 
     706             :       /* Notify consumers of pack_poh (e.g. the GUI) that execle are
     707             :          drained by sending a FD_PACK_MSG_DONE_DRAINING sig. */
     708           0 :       fd_stem_publish( stem, ctx->poh_out.out_idx, FD_PACK_MSG_DONE_DRAINING, 0UL, 0UL, 0UL, 0UL, fd_frag_meta_ts_comp( fd_tickcount() ) );
     709           0 :       *charge_busy = 1;
     710           0 :       return;
     711           0 :     } else {
     712           0 :       return;
     713           0 :     }
     714           0 :   }
     715             : 
     716             :   /* Am I leader? */
     717           0 :   if( FD_UNLIKELY( ctx->leader_slot==ULONG_MAX ) ) {
     718           0 :     return;
     719           0 :   }
     720             : 
     721           0 :   if( ctx->strategy==FD_PACK_STRATEGY_AUCTION ) {
     722           0 :     if( now>=ctx->auction_final_start_tick ) {
     723           0 :       auction_end( ctx, now, FD_METRICS_ENUM_PACK_AUCTION_END_REASON_V_FINAL_IDX );
     724           0 :     } else if( now>=ctx->auction_next_tick ) {
     725             :       /* End the current auction, if one is running. This will flush
     726             :          all transactions held in next_auction. */
     727           0 :       auction_end( ctx, now, FD_METRICS_ENUM_PACK_AUCTION_END_REASON_V_RESTARTED_IDX );
     728             :       /* Start the new auction, holding any new transactions in
     729             :          next_auction. */
     730           0 :       auction_begin( ctx, now );
     731           0 :     }
     732           0 :   }
     733             : 
     734             :   /* Have I sent the max allowed microblocks? Nothing to do. */
     735           0 :   if( FD_UNLIKELY( ctx->slot_microblock_cnt>=ctx->slot_max_microblocks ) ) return;
     736             : 
     737           0 :   int any_ready     = 0;
     738           0 :   int any_scheduled = 0;
     739             : 
     740           0 :   *charge_busy = 1;
     741             : 
     742           0 :   if( FD_LIKELY( ctx->crank->enabled ) ) {
     743           0 :     block_builder_info_t const * top_meta = fd_pack_peek_bundle_meta( ctx->pack );
     744           0 :     if( FD_UNLIKELY( top_meta ) ) {
     745             :       /* Have bundles, in a reasonable state to crank. */
     746             : 
     747           0 :       fd_txn_e_t * _bundle[ 1UL ];
     748           0 :       fd_txn_e_t * const * bundle = fd_pack_insert_bundle_init( ctx->pack, _bundle, 1UL );
     749             : 
     750           0 :       ulong txn_sz = fd_bundle_crank_generate( ctx->crank->gen, ctx->crank->prev_config, top_meta->commission_pubkey,
     751           0 :           ctx->crank->identity_pubkey, ctx->crank->tip_receiver_owner, ctx->crank->epoch, top_meta->commission,
     752           0 :           bundle[0]->txnp->payload, TXN( bundle[0]->txnp ) );
     753             : 
     754           0 :       if( FD_LIKELY( txn_sz==0UL ) ) { /* Everything in good shape! */
     755           0 :         fd_pack_insert_bundle_cancel( ctx->pack, bundle, 1UL );
     756           0 :         fd_pack_set_initializer_bundles_ready( ctx->pack );
     757           0 :         ctx->crank->metrics[ 0 ]++; /* BUNDLE_CRANK_ATTEMPTED_UP_TO_DATE */
     758           0 :       }
     759           0 :       else if( FD_LIKELY( txn_sz<ULONG_MAX ) ) {
     760           0 :         bundle[0]->txnp->payload_sz  = (ushort)txn_sz;
     761           0 :         bundle[0]->txnp->source_tpu  = FD_TXN_M_TPU_SOURCE_BUNDLE;
     762           0 :         bundle[0]->txnp->source_ipv4 = 0; /* not applicable */
     763           0 :         bundle[0]->txnp->scheduler_arrival_time_nanos = fd_clock_tile_now( ctx->clock );
     764           0 :         bundle[0]->txnp->first_seen_nanos = bundle[0]->txnp->scheduler_arrival_time_nanos;
     765           0 :         memcpy( bundle[0]->txnp->payload+TXN(bundle[0]->txnp)->recent_blockhash_off, ctx->crank->recent_blockhash, 32UL );
     766             : 
     767           0 :         fd_keyguard_client_sign( ctx->crank->keyguard_client, bundle[0]->txnp->payload+1UL,
     768           0 :             bundle[0]->txnp->payload+65UL, txn_sz-65UL, FD_KEYGUARD_SIGN_TYPE_ED25519 );
     769             : 
     770           0 :         memcpy( ctx->crank->last_sig, bundle[0]->txnp->payload+1UL, 64UL );
     771             : 
     772           0 :         ctx->crank->ib_inserted = 1;
     773           0 :         ulong deleted;
     774           0 :         int retval = fd_pack_insert_bundle_fini( ctx->pack, bundle, 1UL, ctx->block_height-1UL, 1, NULL, &deleted );
     775           0 :         FD_MCNT_INC( PACK, TXN_EVICTED, deleted );
     776           0 :         ctx->insert_result[ retval + FD_PACK_INSERT_RETVAL_OFF ]++;
     777           0 :         if( FD_UNLIKELY( retval<0 ) ) {
     778           0 :           ctx->crank->metrics[ 3 ]++; /* BUNDLE_CRANK_ATTEMPTED_INSERTION_FAILED */
     779           0 :           FD_LOG_WARNING(( "inserting initializer bundle returned %i", retval ));
     780           0 :         } else {
     781             :           /* Update the cached copy of the on-chain state.  This seems a
     782             :              little dangerous, since we're updating it as if the bundle
     783             :              succeeded without knowing if that's true, but here's why
     784             :              it's safe:
     785             : 
     786             :              Until the initializer bundle is scheduled, peek_bundle_meta
     787             :              returns NULL because the top bundle is an initializer.  Once
     788             :              scheduled, [Pending] state keeps it NULL until the rebate.
     789             : 
     790             :              Then, if the initializer bundle failed, we'll go into
     791             :              [Failed] IB state until the end of the block, which will
     792             :              cause top_meta to remain NULL so we don't read these values
     793             :              again.
     794             : 
     795             :              Otherwise, the initializer bundle succeeded, which means
     796             :              that these are the right values to use. */
     797           0 :           fd_bundle_crank_apply( ctx->crank->gen, ctx->crank->prev_config, top_meta->commission_pubkey,
     798           0 :                                  ctx->crank->tip_receiver_owner, ctx->crank->epoch, top_meta->commission );
     799           0 :           ctx->crank->metrics[ 1 ]++; /* BUNDLE_CRANK_ATTEMPTED_INSERTED */
     800           0 :         }
     801           0 :       } else {
     802             :         /* Already logged a warning in this case */
     803           0 :         fd_pack_insert_bundle_cancel( ctx->pack, bundle, 1UL );
     804           0 :         ctx->crank->metrics[ 2 ]++; /* BUNDLE_CRANK_ATTEMPTED_CREATION_FAILED */
     805           0 :       }
     806           0 :     }
     807           0 :   }
     808             : 
     809             :   /* Try to schedule the next microblock. */
     810           0 :   if( FD_LIKELY( ctx->execle_idle_bitset ) ) { /* Optimize for schedule */
     811           0 :     any_ready = 1;
     812             : 
     813           0 :     int i = fd_ulong_find_lsb( ctx->execle_idle_bitset );
     814             : 
     815           0 :     int flags;
     816             : 
     817           0 :     switch( ctx->strategy ) {
     818           0 :       default:
     819           0 :       case FD_PACK_STRATEGY_PERF:
     820           0 :         flags = FD_PACK_SCHEDULE_BUNDLE | FD_PACK_SCHEDULE_TXN;
     821           0 :         break;
     822           0 :       case FD_PACK_STRATEGY_BALANCED:
     823             :         /* It doesn't really make much sense to pace bundles, because
     824             :            they get scheduled in FIFO order.  However, we keep pacing
     825             :            for normal transactions (votes included).  For example, if
     826             :            pacing_execle_cnt is 0, then pack won't schedule normal
     827             :            transactions to any execle tile. */
     828           0 :         flags = fd_int_if( i==0,                FD_PACK_SCHEDULE_BUNDLE, 0 )
     829           0 :               | fd_int_if( i<pacing_execle_cnt, FD_PACK_SCHEDULE_TXN,    0 );
     830           0 :         break;
     831           0 :       case FD_PACK_STRATEGY_AUCTION: {
     832           0 :         int allow = fd_pack_auction_running( ctx->pack ) | (now>=ctx->auction_final_start_tick);
     833           0 :         flags     = FD_PACK_SCHEDULE_BUNDLE | fd_int_if( allow, FD_PACK_SCHEDULE_TXN, 0 );
     834           0 :         break;
     835           0 :       }
     836           0 :     }
     837             : 
     838           0 :     fd_pack_out_ctx_t * execle_out = &ctx->execle_out[ i ];
     839           0 :     fd_txn_e_t * microblock_dst = fd_chunk_to_laddr( execle_out->mem, execle_out->chunk );
     840           0 :     long schedule_duration = -fd_tickcount();
     841           0 :     ulong schedule_cnt = fd_pack_schedule_next_microblock( ctx->pack, CUS_PER_MICROBLOCK, (ulong)i, flags, microblock_dst );
     842           0 :     schedule_duration      += fd_tickcount();
     843           0 :     fd_histf_sample( (schedule_cnt>0UL) ? ctx->schedule_duration : ctx->no_sched_duration, (ulong)schedule_duration );
     844             : 
     845           0 :     if( fd_pack_auction_running( ctx->pack ) ) {
     846             :       /* End the auction early if we have reached the CU limit. */
     847           0 :       if( fd_pack_current_block_cost( ctx->pack )>=ctx->auction_cu_limit ) {
     848           0 :         auction_end( ctx, now, FD_METRICS_ENUM_PACK_AUCTION_END_REASON_V_LIMIT_IDX );
     849           0 :       }
     850           0 :     }
     851             : 
     852           0 :     if( FD_LIKELY( schedule_cnt ) ) {
     853           0 :       any_scheduled = 1;
     854           0 :       long  now2   = fd_tickcount();
     855           0 :       ulong tsorig = (ulong)fd_frag_meta_ts_comp( now  ); /* A bound on when we observed execle was idle */
     856           0 :       ulong tspub  = (ulong)fd_frag_meta_ts_comp( now2 );
     857           0 :       ulong chunk  = execle_out->chunk;
     858           0 :       ulong msg_sz = schedule_cnt*sizeof(fd_txn_e_t);
     859           0 :       fd_microblock_execle_trailer_t * trailer = (fd_microblock_execle_trailer_t*)(microblock_dst+schedule_cnt);
     860           0 :       trailer->bank_idx = ctx->leader_bank_idx;
     861           0 :       trailer->bank_seq = ctx->leader_bank_seq;
     862           0 :       trailer->microblock_idx = ctx->slot_microblock_cnt;
     863           0 :       trailer->pack_idx = ctx->pack_idx;
     864           0 :       trailer->pack_txn_idx = ctx->pack_txn_cnt;
     865           0 :       trailer->is_bundle = !!(microblock_dst->txnp->flags & FD_TXN_P_FLAGS_BUNDLE);
     866             : 
     867             :       /* When sending MAX_TXN_PER_MICROBLOCK transactions as fd_txn_e_t
     868             :          to execle, there must be room for the trailer at the end. */
     869           0 :       FD_STATIC_ASSERT( MAX_TXN_PER_MICROBLOCK*sizeof(fd_txn_e_t)+sizeof(fd_microblock_execle_trailer_t)<=MAX_MICROBLOCK_SZ, pack_execle_mtu );
     870             : 
     871           0 :       ulong sig = fd_disco_poh_sig( ctx->leader_slot, POH_PKT_TYPE_MICROBLOCK, (ulong)i );
     872           0 :       ctx->execle_expect[ i ] = fd_stem_publish( stem, execle_out->out_idx, sig, chunk, msg_sz+sizeof(fd_microblock_execle_trailer_t), 0UL, tsorig, tspub );
     873           0 :       ctx->execle_ready_at[i] = now2 + (long)ctx->microblock_duration_ticks;
     874           0 :       execle_out->chunk = fd_dcache_compact_next( execle_out->chunk, msg_sz+sizeof(fd_microblock_execle_trailer_t), execle_out->chunk0, execle_out->wmark );
     875           0 :       ctx->slot_microblock_cnt += fd_ulong_if( trailer->is_bundle, schedule_cnt, 1UL );
     876           0 :       ctx->pack_idx += fd_uint_if( trailer->is_bundle, (uint)schedule_cnt, 1U );
     877           0 :       ctx->pack_txn_cnt += schedule_cnt;
     878           0 :       ctx->slot_bundle_txn_cnt += fd_ulong_if( trailer->is_bundle, schedule_cnt, 0UL );
     879             : 
     880           0 :       ctx->execle_idle_bitset = fd_ulong_pop_lsb( ctx->execle_idle_bitset );
     881           0 :       ctx->skip_cnt           = (long)schedule_cnt * fd_long_if( ctx->use_consumed_cus, (long)execle_cnt/2L, 1L );
     882           0 :       fd_pack_pacing_update_consumed_cus( ctx->pacer, fd_pack_current_block_cost( ctx->pack ), now2 );
     883             : 
     884           0 :       ctx->last_sched_metrics->time = now2;
     885           0 :       fd_pack_get_sched_metrics( ctx->pack, ctx->last_sched_metrics->sched_results );
     886             : 
     887             :       /* If we're using CU rebates, then we have one in for each execle
     888             :          in addition to the two normal ones.  We want to skip schedule
     889             :          attempts for (execle_cnt + 1) link polls after a successful
     890             :          schedule attempt. */
     891           0 :       fd_long_store_if( ctx->use_consumed_cus, &(ctx->skip_cnt), (long)(ctx->execle_cnt + 1) );
     892           0 :     }
     893           0 :   }
     894             : 
     895           0 :   update_metric_state( ctx, now, FD_PACK_METRIC_STATE_EXECLES,     any_ready     );
     896           0 :   update_metric_state( ctx, now, FD_PACK_METRIC_STATE_MICROBLOCKS, any_scheduled );
     897           0 :   now = fd_tickcount();
     898           0 :   update_metric_state( ctx, now, FD_PACK_METRIC_STATE_TRANSACTIONS, fd_pack_avail_txn_cnt( ctx->pack )>0 );
     899             : 
     900             :   /* Did we send the maximum allowed microblocks? Then end the slot. */
     901           0 :   if( FD_UNLIKELY( ctx->slot_microblock_cnt==ctx->slot_max_microblocks )) {
     902           0 :     *charge_busy = 1;
     903             : 
     904           0 :     update_metric_state( ctx, now, FD_PACK_METRIC_STATE_LEADER,       0 );
     905           0 :     update_metric_state( ctx, now, FD_PACK_METRIC_STATE_EXECLES,      0 );
     906           0 :     update_metric_state( ctx, now, FD_PACK_METRIC_STATE_MICROBLOCKS,  0 );
     907             :     /* The pack object also does this accounting and increases this
     908             :        metric, but we end the slot early so won't see it unless we also
     909             :        increment it here. */
     910           0 :     FD_MCNT_INC( PACK, BLOCK_MICROBLOCK_LIMIT_REACHED, 1UL );
     911             : 
     912           0 :     fd_done_packing_t * done_packing = fd_chunk_to_laddr( ctx->poh_out.mem, ctx->poh_out.chunk );
     913           0 :     get_done_packing( ctx, done_packing, FD_PACK_END_SLOT_REASON_MICROBLOCK );
     914           0 :     log_end_block_metrics( ctx, now, "microblock", done_packing->limits_usage->block_cost );
     915           0 :     fd_pack_end_block( ctx->pack );
     916           0 :     fd_pack_get_top_writers( ctx->pack, done_packing->limits_usage->top_writers );
     917             : 
     918           0 :     metrics_write( ctx ); /* final for the slot before poh ends it */
     919           0 :     fd_stem_publish( stem, ctx->poh_out.out_idx, fd_disco_execle_sig( ctx->leader_slot, ctx->pack_idx ), ctx->poh_out.chunk, sizeof(fd_done_packing_t), 0UL, 0UL, fd_frag_meta_ts_comp( fd_tickcount() ) );
     920           0 :     ctx->poh_out.chunk = fd_dcache_compact_next( ctx->poh_out.chunk, sizeof(fd_done_packing_t), ctx->poh_out.chunk0, ctx->poh_out.wmark );
     921           0 :     ctx->pack_idx++;
     922             : 
     923           0 :     auction_end( ctx, now, FD_METRICS_ENUM_PACK_AUCTION_END_REASON_V_SLOT_END_IDX );
     924           0 :     ctx->drain_execle        = 1;
     925           0 :     ctx->leader_slot         = ULONG_MAX;
     926           0 :     ctx->slot_microblock_cnt = 0UL;
     927           0 :     remove_ib( ctx );
     928             : 
     929           0 :     return;
     930           0 :   }
     931           0 : }
     932             : 
     933             : 
     934             : /* At this point, we have started receiving frag seq with details in
     935             :     mline at time now.  Speculatively process it here. */
     936             : 
     937             : static inline void
     938             : during_frag( fd_pack_ctx_t * ctx,
     939             :              ulong           in_idx,
     940             :              ulong           seq FD_PARAM_UNUSED,
     941             :              ulong           sig,
     942             :              ulong           chunk,
     943             :              ulong           sz,
     944           0 :              ulong           ctl FD_PARAM_UNUSED ) {
     945             : 
     946           0 :   uchar const * dcache_entry = fd_chunk_to_laddr_const( ctx->in[ in_idx ].mem, chunk );
     947             : 
     948           0 :   switch( ctx->in_kind[ in_idx ] ) {
     949           0 :   case IN_KIND_REPLAY: {
     950           0 :     if( FD_LIKELY( sig==REPLAY_SIG_TXN_EXECUTED ) ) {
     951           0 :       fd_replay_txn_executed_t const * txn_executed = fd_type_pun_const( dcache_entry );
     952           0 :       ctx->txn_committed = !!txn_executed->is_committable;
     953           0 :       if( FD_UNLIKELY( !txn_executed->is_committable ) ) return;
     954           0 :       memcpy( ctx->executed_txn_sig, fd_txn_get_signatures( TXN(txn_executed->txn), txn_executed->txn->payload ), FD_TXN_SIGNATURE_SZ );
     955           0 :       return;
     956           0 :     }
     957           0 :     if( FD_LIKELY( sig!=REPLAY_SIG_BECAME_LEADER ) ) return;
     958             : 
     959             :     /* There was a leader transition.  Handle it. */
     960           0 :     if( FD_UNLIKELY( chunk<ctx->in[ in_idx ].chunk0 || chunk>ctx->in[ in_idx ].wmark || sz!=sizeof(fd_became_leader_t) ) )
     961           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 ));
     962             : 
     963           0 :     fd_memcpy( ctx->_became_leader, dcache_entry, sizeof(fd_became_leader_t) );
     964           0 :     return;
     965           0 :   }
     966           0 :   case IN_KIND_EXECLE: {
     967           0 :     FD_TEST( ctx->use_consumed_cus );
     968             :       /* For a previous slot */
     969           0 :     if( FD_UNLIKELY( sig!=ctx->leader_slot ) ) return;
     970             : 
     971           0 :     if( FD_UNLIKELY( chunk<ctx->in[ in_idx ].chunk0 || chunk>ctx->in[ in_idx ].wmark || sz<FD_PACK_REBATE_MIN_SZ
     972           0 :           || sz>FD_PACK_REBATE_MAX_SZ ) )
     973           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 ));
     974             : 
     975           0 :     ctx->pending_rebate_sz = sz;
     976           0 :     fd_memcpy( ctx->rebate, dcache_entry, sz );
     977           0 :     return;
     978           0 :   }
     979           0 :   case IN_KIND_RESOLV: {
     980           0 :     if( FD_UNLIKELY( chunk<ctx->in[ in_idx ].chunk0 || chunk>ctx->in[ in_idx ].wmark || sz>FD_TPU_RESOLVED_MTU ) )
     981           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 ));
     982             : 
     983           0 :     fd_txn_m_t * txnm = (fd_txn_m_t *)dcache_entry;
     984           0 :     ulong payload_sz  = txnm->payload_sz;
     985           0 :     ulong txn_t_sz    = txnm->txn_t_sz;
     986           0 :     uint  source_ipv4 = txnm->source_ipv4;
     987           0 :     uchar source_tpu  = txnm->source_tpu;
     988           0 :     FD_TEST( payload_sz<=FD_TPU_MTU    );
     989           0 :     FD_TEST( txn_t_sz  <=FD_TXN_MAX_SZ );
     990           0 :     fd_txn_t * txn  = fd_txn_m_txn_t( txnm );
     991             : 
     992           0 :     ulong addr_table_sz = 32UL*txn->addr_table_adtl_cnt;
     993           0 :     FD_TEST( addr_table_sz<=32UL*FD_TXN_ACCT_ADDR_MAX );
     994             : 
     995           0 :     if( FD_UNLIKELY( (ctx->leader_slot==ULONG_MAX) & (sig>ctx->highest_observed_block_height) ) ) {
     996             :       /* Using the resolv tile's knowledge of the current block height
     997             :          is a bit of a hack, since we don't get any info if there are no
     998             :          transactions and we're not leader.  We're actually in exactly
     999             :          the case where that's okay though.  The point of calling
    1000             :          expire_before long before we become leader is so that we don't
    1001             :          drop new but low-fee-paying transactions when pack is clogged
    1002             :          with expired but high-fee-paying transactions.  That can only
    1003             :          happen if we are getting transactions.
    1004             : 
    1005             :          FIXME: this should use rooted slots instead. */
    1006           0 :       ctx->highest_observed_block_height = sig;
    1007           0 :       ulong exp_cnt = fd_pack_expire_before( ctx->pack, fd_ulong_max( ctx->highest_observed_block_height, TRANSACTION_LIFETIME_SLOTS )-TRANSACTION_LIFETIME_SLOTS );
    1008           0 :       FD_MCNT_INC( PACK, TXN_DROPPED_EXPIRED, exp_cnt );
    1009           0 :     }
    1010             : 
    1011             : 
    1012           0 :     ulong bundle_id = txnm->block_engine.bundle_id;
    1013           0 :     if( FD_UNLIKELY( bundle_id ) ) {
    1014           0 :       ctx->is_bundle = 1;
    1015           0 :       if( FD_LIKELY( bundle_id!=ctx->current_bundle->id ) ) {
    1016           0 :         if( FD_UNLIKELY( ctx->current_bundle->bundle ) ) {
    1017           0 :           FD_MCNT_INC( PACK, TXN_DROPPED_PARTIAL_BUNDLE, ctx->current_bundle->txn_received );
    1018           0 :           fd_pack_insert_bundle_cancel( ctx->pack, ctx->current_bundle->bundle, ctx->current_bundle->txn_cnt );
    1019           0 :         }
    1020           0 :         ctx->current_bundle->id                   = bundle_id;
    1021           0 :         ctx->current_bundle->txn_cnt              = txnm->block_engine.bundle_txn_cnt;
    1022           0 :         ctx->current_bundle->min_blockhash_height = ULONG_MAX;
    1023           0 :         ctx->current_bundle->txn_received         = 0UL;
    1024             : 
    1025           0 :         if( FD_UNLIKELY( ctx->current_bundle->txn_cnt==0UL ) ) {
    1026           0 :           FD_MCNT_INC( PACK, TXN_DROPPED_PARTIAL_BUNDLE, 1UL );
    1027           0 :           ctx->current_bundle->id = 0UL;
    1028           0 :           return;
    1029           0 :         }
    1030           0 :         ctx->blk_engine_cfg->commission = txnm->block_engine.commission;
    1031           0 :         memcpy( ctx->blk_engine_cfg->commission_pubkey->b, txnm->block_engine.commission_pubkey, 32UL );
    1032             : 
    1033           0 :         ctx->current_bundle->bundle = fd_pack_insert_bundle_init( ctx->pack, ctx->current_bundle->_txn, ctx->current_bundle->txn_cnt );
    1034           0 :       }
    1035           0 :       ctx->cur_spot                             = ctx->current_bundle->bundle[ ctx->current_bundle->txn_received ];
    1036           0 :       int is_nonce = fd_disco_tpu_is_durable_nonce( txn, fd_txn_m_payload( txnm ) );
    1037             :       /* If it's a nonce transaction, we don't want to include the slot
    1038             :          of the nonce in the min calculation, so we use the highest
    1039             :          block height we know about, which might be block_height if
    1040             :          we've been leader for a while in a row. */
    1041           0 :       ulong block_height_to_use = fd_ulong_if( is_nonce, fd_ulong_max( ctx->block_height, ctx->highest_observed_block_height ), sig );
    1042           0 :       ctx->current_bundle->min_blockhash_height = fd_ulong_min( ctx->current_bundle->min_blockhash_height, block_height_to_use );
    1043           0 :     } else {
    1044           0 :       ctx->is_bundle = 0;
    1045           0 :       ctx->cur_spot = fd_pack_insert_txn_init( ctx->pack );
    1046           0 :     }
    1047             : 
    1048             :     /* We get transactions from the resolv tile.
    1049             :        The transactions should have been parsed and verified. */
    1050           0 :     FD_MCNT_INC( PACK, TXN_RX, 1UL );
    1051             : 
    1052           0 :     fd_memcpy( ctx->cur_spot->txnp->payload, fd_txn_m_payload( txnm ), payload_sz    );
    1053           0 :     fd_memcpy( TXN(ctx->cur_spot->txnp),     txn,                      txn_t_sz      );
    1054           0 :     fd_memcpy( ctx->cur_spot->alt_accts,     fd_txn_m_alut( txnm ),    addr_table_sz );
    1055           0 :     ctx->cur_spot->txnp->scheduler_arrival_time_nanos = fd_clock_tile_now( ctx->clock );
    1056           0 :     ctx->cur_spot->txnp->first_seen_nanos = txnm->first_seen_nanos;
    1057           0 :     ctx->cur_spot->txnp->payload_sz  = (ushort)payload_sz;
    1058           0 :     ctx->cur_spot->txnp->source_ipv4 = source_ipv4;
    1059           0 :     ctx->cur_spot->txnp->source_tpu  = source_tpu;
    1060             : 
    1061           0 :     break;
    1062           0 :   }
    1063           0 :   }
    1064           0 : }
    1065             : 
    1066             : 
    1067             : /* After the transaction has been fully received, and we know we were
    1068             :    not overrun while reading it, insert it into pack. */
    1069             : 
    1070             : static inline void
    1071             : after_frag( fd_pack_ctx_t *     ctx,
    1072             :             ulong               in_idx,
    1073             :             ulong               seq,
    1074             :             ulong               sig,
    1075             :             ulong               sz,
    1076             :             ulong               tsorig,
    1077             :             ulong               tspub,
    1078           0 :             fd_stem_context_t * stem ) {
    1079           0 :   (void)seq;
    1080           0 :   (void)sz;
    1081           0 :   (void)tsorig;
    1082           0 :   (void)tspub;
    1083           0 :   (void)stem;
    1084             : 
    1085           0 :   long now = fd_tickcount();
    1086             : 
    1087           0 :   ulong leader_slot = ULONG_MAX;
    1088           0 :   switch( ctx->in_kind[ in_idx ] ) {
    1089           0 :     case IN_KIND_REPLAY:
    1090           0 :       if( FD_LIKELY( sig==REPLAY_SIG_TXN_EXECUTED && ctx->txn_committed ) ) {
    1091           0 :         ulong deleted = fd_pack_delete_transaction( ctx->pack, fd_type_pun( ctx->executed_txn_sig ) );
    1092           0 :         FD_MCNT_INC( PACK, TXN_DROPPED_ALREADY_EXECUTED, deleted );
    1093           0 :         update_metric_state( ctx, now, FD_PACK_METRIC_STATE_TRANSACTIONS, fd_pack_avail_txn_cnt( ctx->pack )>0 );
    1094           0 :       }
    1095           0 :       if( FD_UNLIKELY( sig!=REPLAY_SIG_BECAME_LEADER ) ) return;
    1096           0 :       leader_slot = ctx->_became_leader->slot;
    1097             : 
    1098           0 :       ctx->start_block_sched_metrics->time = now;
    1099           0 :       fd_pack_get_sched_metrics( ctx->pack, ctx->start_block_sched_metrics->sched_results );
    1100           0 :       break;
    1101           0 :     default:
    1102           0 :       break;
    1103           0 :   }
    1104             : 
    1105           0 :   switch( ctx->in_kind[ in_idx ] ) {
    1106           0 :   case IN_KIND_REPLAY: {
    1107           0 :     long now_ticks = fd_tickcount();
    1108           0 :     long now_ns    = fd_log_wallclock();
    1109             : 
    1110             :     /* Replay sends the next became leader only once the previous leader
    1111             :        slot ended, which pack's done packing starts. */
    1112           0 :     if( FD_UNLIKELY( ctx->leader_slot!=ULONG_MAX ) ) FD_LOG_CRIT(( "invariant violation: became leader for slot %lu while packing for slot %lu", leader_slot, ctx->leader_slot ));
    1113           0 :     ctx->leader_slot = leader_slot;
    1114           0 :     ulong slots_left = 3UL - (leader_slot%4UL);
    1115           0 :     long  slot_ns    = (long)( ctx->_became_leader->ticks_per_slot*ctx->_became_leader->tick_duration_ns );
    1116           0 :     fd_pack_set_rotation_end_ns( ctx->pack, ctx->_became_leader->slot_end_ns + (long)slots_left*slot_ns );
    1117           0 :     ctx->block_height = ctx->_became_leader->block_height;
    1118             : 
    1119           0 :     ctx->slot_pack_start_ns  = now_ns;
    1120           0 :     ctx->slot_bundle_txn_cnt = 0UL;
    1121             : 
    1122           0 :     ulong exp_cnt = fd_pack_expire_before( ctx->pack, fd_ulong_max( ctx->block_height, TRANSACTION_LIFETIME_SLOTS )-TRANSACTION_LIFETIME_SLOTS );
    1123           0 :     FD_MCNT_INC( PACK, TXN_DROPPED_EXPIRED, exp_cnt );
    1124             : 
    1125           0 :     ctx->leader_bank_idx      = ctx->_became_leader->bank_idx;
    1126           0 :     ctx->leader_bank_seq      = ctx->_became_leader->bank_seq;
    1127           0 :     ctx->slot_max_microblocks = ctx->_became_leader->max_microblocks_in_slot;
    1128             : 
    1129             :     /* Cap pack's entry bytes at the worst case: how many entry bytes
    1130             :        fit in max_shred_idx given our shredding.  We fill a batch until
    1131             :        the next microblock would not fit in two FEC sets, then pad out
    1132             :        that batch.  An Alpenglow block has no tick entries besides the
    1133             :        closing alpentick, which the end of block reserve covers. */
    1134           0 :     ulong shreds            = fd_ulong_max( ctx->_became_leader->limits.slot_max_data_shreds, ctx->bench_max_shreds_per_block );
    1135           0 :     ulong max_microblock_sz = sizeof(fd_entry_batch_header_t) + EFFECTIVE_TXN_PER_MICROBLOCK*FD_TPU_MTU;
    1136           0 :     ulong base_max_data     = fd_shred_batch_pack_data_max( shreds, max_microblock_sz );
    1137           0 :     FD_TEST( base_max_data );
    1138           0 :     ctx->slot_max_data        = base_max_data;
    1139             : 
    1140           0 :     ctx->limits.slot_max_cost                     = ctx->_became_leader->limits.slot_max_cost;
    1141           0 :     ctx->limits.slot_max_write_cost_per_acct      = ctx->_became_leader->limits.slot_max_write_cost_per_acct;
    1142           0 :     ctx->limits.slot_max_allocated_data_per_block = ctx->_became_leader->limits.slot_max_allocated_data_per_block;
    1143           0 :     ctx->limits.slot_max_data_shreds              = shreds;
    1144             : 
    1145           0 :     double tick_per_ns = ctx->clock->epoch->w;
    1146           0 :     long end_ticks = now_ticks + (long)((double)fd_long_max( ctx->_became_leader->slot_end_ns - now_ns, 1L )*tick_per_ns);
    1147             :     /* We may still get overrun, but then we'll never use this and just
    1148             :        reinitialize it the next time when we actually become leader. */
    1149           0 :     fd_pack_pacing_init( ctx->pacer, now_ticks, end_ticks, (float)tick_per_ns, ctx->limits.slot_max_cost );
    1150             : 
    1151           0 :     if( FD_UNLIKELY( ctx->crank->enabled ) ) {
    1152             :       /* If we get overrun, we'll just never use these values, but the
    1153             :          old values aren't really useful either. */
    1154           0 :       ctx->crank->epoch = ctx->_became_leader->epoch;
    1155           0 :       *(ctx->crank->prev_config) = *(ctx->_became_leader->bundle->config);
    1156           0 :       memcpy( ctx->crank->recent_blockhash,   ctx->_became_leader->bundle->last_blockhash,     32UL );
    1157           0 :       memcpy( ctx->crank->tip_receiver_owner, ctx->_became_leader->bundle->tip_receiver_owner, 32UL );
    1158           0 :     }
    1159             : 
    1160           0 :     FD_LOG_INFO(( "pack_became_leader(slot=%lu,ends_at=%ld)", ctx->leader_slot, ctx->_became_leader->slot_end_ns ));
    1161             : 
    1162           0 :     update_metric_state( ctx, fd_tickcount(), FD_PACK_METRIC_STATE_LEADER, 1 );
    1163             : 
    1164             :     /* If there is currently an auction running from a previous slot, end it. */
    1165           0 :     auction_end( ctx, now_ticks, FD_METRICS_ENUM_PACK_AUCTION_END_REASON_V_SLOT_END_IDX );
    1166             : 
    1167           0 :     ctx->slot_end_ns                   = ctx->_became_leader->slot_end_ns;
    1168           0 :     ctx->leader_slot_start_tick        = now_ticks + (long)((double)( ctx->_became_leader->slot_start_ns - now_ns )*tick_per_ns);
    1169           0 :     ctx->leader_slot_end_tick          = end_ticks;
    1170           0 :     ctx->auction_final_start_tick      = fd_long_if( ctx->leader_slot%4UL==3UL,
    1171           0 :                                                      end_ticks-(long)(tick_per_ns*(double)FD_PACK_AUCTION_FINAL_NS), LONG_MAX );
    1172           0 :     ctx->auction_last_attempt_tick     = now_ticks - ctx->auction_interval_tick;
    1173           0 :     ctx->auction_next_tick             = now_ticks;
    1174           0 :     fd_pack_limits_t limits[ 1 ];
    1175           0 :     limits->max_cost_per_block = ctx->limits.slot_max_cost;
    1176           0 :     limits->max_data_bytes_per_block = ctx->slot_max_data;
    1177           0 :     limits->max_microblocks_per_block = ctx->slot_max_microblocks;
    1178           0 :     limits->max_write_cost_per_acct = ctx->limits.slot_max_write_cost_per_acct;
    1179           0 :     limits->max_txn_per_microblock = ULONG_MAX; /* unused */
    1180           0 :     limits->max_allocated_data_per_block = ctx->limits.slot_max_allocated_data_per_block;
    1181           0 :     fd_pack_set_block_limits( ctx->pack, limits );
    1182           0 :     fd_pack_pacing_update_consumed_cus( ctx->pacer, fd_pack_current_block_cost( ctx->pack ), now );
    1183             : 
    1184           0 :     break;
    1185           0 :   }
    1186           0 :   case IN_KIND_EXECLE: {
    1187             :     /* For a previous slot */
    1188           0 :     if( FD_UNLIKELY( sig!=ctx->leader_slot ) ) return;
    1189             : 
    1190           0 :     fd_pack_rebate_cus( ctx->pack, ctx->rebate->rebate );
    1191           0 :     if( FD_UNLIKELY( ctx->rebate->rebate->ib_result<0 ) ) FD_LOG_WARNING(( "initializer bundle failed in leader slot %lu; no bundles until the slot ends", ctx->leader_slot ));
    1192           0 :     ctx->pending_rebate_sz = 0UL;
    1193           0 :     fd_pack_pacing_update_consumed_cus( ctx->pacer, fd_pack_current_block_cost( ctx->pack ), now );
    1194           0 :     break;
    1195           0 :   }
    1196           0 :   case IN_KIND_RESOLV: {
    1197             :     /* Normal transaction case */
    1198           0 :     if( FD_UNLIKELY( ctx->is_bundle ) ) {
    1199           0 :       if( FD_UNLIKELY( ctx->current_bundle->txn_cnt==0UL ) ) return;
    1200           0 :       if( FD_UNLIKELY( ++(ctx->current_bundle->txn_received)==ctx->current_bundle->txn_cnt ) ) {
    1201           0 :         ulong deleted;
    1202           0 :         long insert_duration = -fd_tickcount();
    1203           0 :         int result = fd_pack_insert_bundle_fini( ctx->pack, ctx->current_bundle->bundle, ctx->current_bundle->txn_cnt, ctx->current_bundle->min_blockhash_height, 0, ctx->blk_engine_cfg, &deleted );
    1204           0 :         insert_duration       += fd_tickcount();
    1205           0 :         long burst             = fd_long_max( now+ctx->auction_bundle_end_gap_tick, ctx->auction_last_attempt_tick+ctx->auction_spacing_tick );
    1206           0 :         long fallback          = ctx->auction_last_attempt_tick+ctx->auction_interval_tick;
    1207           0 :         ctx->auction_next_tick = fd_long_min( burst, fallback );
    1208           0 :         FD_MCNT_INC( PACK, TXN_EVICTED, deleted );
    1209           0 :         ctx->insert_result[ result + FD_PACK_INSERT_RETVAL_OFF ] += ctx->current_bundle->txn_received;
    1210           0 :         fd_histf_sample( ctx->insert_duration, (ulong)insert_duration );
    1211           0 :         ctx->current_bundle->bundle = NULL;
    1212           0 :       }
    1213           0 :     } else {
    1214           0 :       ulong blockhash_height = sig;
    1215           0 :       ulong deleted;
    1216           0 :       long insert_duration = -fd_tickcount();
    1217           0 :       int result = fd_pack_insert_txn_fini( ctx->pack, ctx->cur_spot, blockhash_height, &deleted );
    1218           0 :       insert_duration      += fd_tickcount();
    1219           0 :       FD_MCNT_INC( PACK, TXN_EVICTED, deleted );
    1220           0 :       ctx->insert_result[ result + FD_PACK_INSERT_RETVAL_OFF ]++;
    1221           0 :       fd_histf_sample( ctx->insert_duration, (ulong)insert_duration );
    1222           0 :       if( FD_LIKELY( result>=0 ) ) ctx->last_successful_insert = now;
    1223           0 :     }
    1224             : 
    1225           0 :     ctx->cur_spot = NULL;
    1226           0 :     break;
    1227           0 :   }
    1228           0 :   }
    1229             : 
    1230           0 :   update_metric_state( ctx, now, FD_PACK_METRIC_STATE_TRANSACTIONS, fd_pack_avail_txn_cnt( ctx->pack )>0 );
    1231           0 : }
    1232             : 
    1233             : static void
    1234             : privileged_init( fd_topo_t const *      topo,
    1235           0 :                  fd_topo_tile_t const * tile ) {
    1236           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    1237             : 
    1238           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    1239           0 :   fd_pack_ctx_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof( fd_pack_ctx_t ), sizeof( fd_pack_ctx_t ) );
    1240             : 
    1241           0 :   if( FD_UNLIKELY( !fd_rng_secure( &ctx->rng_seed, sizeof(uint) ) ) ) {
    1242           0 :     FD_LOG_CRIT(( "fd_rng_secure failed" ));
    1243           0 :   }
    1244           0 :   if( FD_UNLIKELY( !fd_rng_secure( &ctx->rng_idx, sizeof(ulong) ) ) ) {
    1245           0 :     FD_LOG_CRIT(( "fd_rng_secure failed" ));
    1246           0 :   }
    1247             : 
    1248           0 :   if( FD_LIKELY( !tile->pack.bundle.enabled ) ) return;
    1249           0 :   if( FD_UNLIKELY( !tile->pack.bundle.vote_account_path[0] ) ) {
    1250           0 :     FD_LOG_WARNING(( "Disabling bundle crank because no vote account was specified" ));
    1251           0 :     return;
    1252           0 :   }
    1253             : 
    1254           0 :   if( FD_UNLIKELY( !strcmp( tile->pack.bundle.identity_key_path, "" ) ) )
    1255           0 :     FD_LOG_ERR(( "identity_key_path not set" ));
    1256             : 
    1257           0 :   const uchar * identity_key = fd_keyload_load( tile->pack.bundle.identity_key_path, /* pubkey only: */ 1 );
    1258           0 :   fd_memcpy( ctx->crank->identity_pubkey->b, identity_key, 32UL );
    1259             : 
    1260           0 :   if( FD_UNLIKELY( !fd_base58_decode_32( tile->pack.bundle.vote_account_path, ctx->crank->vote_pubkey->b ) ) ) {
    1261           0 :     const uchar * vote_key = fd_keyload_load( tile->pack.bundle.vote_account_path, /* pubkey only: */ 1 );
    1262           0 :     fd_memcpy( ctx->crank->vote_pubkey->b, vote_key, 32UL );
    1263           0 :   }
    1264           0 : }
    1265             : 
    1266             : static void
    1267             : unprivileged_init( fd_topo_t const *      topo,
    1268           0 :                    fd_topo_tile_t const * tile ) {
    1269           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    1270             : 
    1271           0 :   if( FD_UNLIKELY( tile->pack.max_pending_transactions >= USHORT_MAX-10UL ) ) FD_LOG_ERR(( "pack tile supports up to %lu pending transactions", USHORT_MAX-11UL ));
    1272             : 
    1273           0 :   fd_pack_limits_t limits_upper[1] = {{
    1274           0 :     .max_cost_per_block           = tile->pack.max_cost_per_block,
    1275           0 :     .max_write_cost_per_acct      = FD_PACK_MAX_WRITE_COST_PER_ACCT_UPPER_BOUND,
    1276           0 :     .max_data_bytes_per_block     = FD_PACK_MAX_DATA_PER_BLOCK*(tile->pack.max_shreds_per_block/FD_SHRED_BLK_MAX),
    1277           0 :     .max_txn_per_microblock       = EFFECTIVE_TXN_PER_MICROBLOCK,
    1278           0 :     .max_microblocks_per_block    = (ulong)UINT_MAX, /* Limit not known yet */
    1279           0 :     .max_allocated_data_per_block = FD_PACK_MAX_ALLOCATED_DATA_PER_BLOCK,
    1280           0 :   }};
    1281             : 
    1282           0 :   ulong pack_footprint = fd_pack_footprint( tile->pack.max_pending_transactions, BUNDLE_META_SZ, tile->pack.execle_tile_count, limits_upper );
    1283             : 
    1284           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    1285           0 :   fd_pack_ctx_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof( fd_pack_ctx_t ), sizeof( fd_pack_ctx_t ) );
    1286           0 :   fd_rng_t *      rng = fd_rng_join( fd_rng_new( FD_SCRATCH_ALLOC_APPEND( l, fd_rng_align(), fd_rng_footprint() ), ctx->rng_seed, ctx->rng_idx ) );
    1287           0 :   if( FD_UNLIKELY( !rng ) ) FD_LOG_ERR(( "fd_rng_new failed" ));
    1288             : 
    1289           0 :   fd_pack_limits_t limits_lower[1] = {{
    1290           0 :     .max_cost_per_block           = FD_PACK_MAX_COST_PER_BLOCK_LOWER_BOUND, /* replaced by the chain's at become-leader */
    1291           0 :     .max_write_cost_per_acct      = FD_PACK_MAX_WRITE_COST_PER_ACCT_LOWER_BOUND,
    1292           0 :     .max_data_bytes_per_block     = FD_PACK_MAX_DATA_PER_BLOCK*(tile->pack.max_shreds_per_block/FD_SHRED_BLK_MAX),
    1293           0 :     .max_txn_per_microblock       = EFFECTIVE_TXN_PER_MICROBLOCK,
    1294           0 :     .max_microblocks_per_block    = (ulong)UINT_MAX, /* Limit not known yet */
    1295           0 :     .max_allocated_data_per_block = FD_PACK_MAX_ALLOCATED_DATA_PER_BLOCK,
    1296           0 :   }};
    1297             : 
    1298           0 :   ctx->pack = fd_pack_join( fd_pack_new( FD_SCRATCH_ALLOC_APPEND( l, fd_pack_align(), pack_footprint ),
    1299           0 :                                          tile->pack.max_pending_transactions, BUNDLE_META_SZ, tile->pack.execle_tile_count,
    1300           0 :                                          limits_upper,
    1301           0 :                                          fd_type_pun_const( tile->pack.acct_blocklist ), tile->pack.acct_blocklist_cnt,
    1302           0 :                                          rng ) );
    1303           0 :   if( FD_UNLIKELY( !ctx->pack ) ) FD_LOG_ERR(( "fd_pack_new failed" ));
    1304             : 
    1305           0 :   fd_pack_set_block_limits( ctx->pack, limits_lower );
    1306             : 
    1307           0 :   ulong in_max = sizeof(ctx->in)/sizeof(ctx->in[0]);
    1308           0 :   if( FD_UNLIKELY( tile->in_cnt>in_max ) )
    1309           0 :     FD_LOG_ERR(( "Too many input links (%lu>%lu) to pack tile", tile->in_cnt, in_max ));
    1310           0 :   FD_TEST( in_max==sizeof(ctx->in_kind)/sizeof(ctx->in_kind[0]) );
    1311           0 :   for( ulong i=0UL; i<tile->in_cnt; i++ ) {
    1312           0 :     fd_topo_link_t const * link = &topo->links[ tile->in_link_id[ i ] ];
    1313             : 
    1314           0 :     if( FD_LIKELY(      !strcmp( link->name, "resolv_pack"  ) ) ) ctx->in_kind[ i ] = IN_KIND_RESOLV;
    1315           0 :     else if( FD_LIKELY( !strcmp( link->name, "execle_pack"  ) ) ) ctx->in_kind[ i ] = IN_KIND_EXECLE;
    1316           0 :     else if( FD_LIKELY( !strcmp( link->name, "sign_pack"    ) ) ) ctx->in_kind[ i ] = IN_KIND_SIGN;
    1317           0 :     else if( FD_LIKELY( !strcmp( link->name, "replay_out"   ) ) ) ctx->in_kind[ i ] = IN_KIND_REPLAY;
    1318           0 :     else FD_LOG_ERR(( "pack tile has unexpected input link %lu %s", i, link->name ));
    1319           0 :   }
    1320             : 
    1321           0 :   if( FD_UNLIKELY( tile->pack.execle_tile_count>FD_PACK_MAX_EXECLE_TILES ) ) FD_LOG_ERR(( "pack tile connects to too many execle tiles" ));
    1322             : 
    1323           0 :   FD_TEST( (tile->pack.schedule_strategy>=0) & (tile->pack.schedule_strategy<=FD_PACK_STRATEGY_AUCTION) );
    1324             : 
    1325           0 :   ctx->crank->enabled = tile->pack.bundle.enabled;
    1326           0 :   if( FD_UNLIKELY( tile->pack.bundle.enabled ) ) {
    1327           0 :     if( FD_UNLIKELY( !fd_bundle_crank_gen_init( ctx->crank->gen, (fd_acct_addr_t const *)tile->pack.bundle.tip_distribution_program_addr,
    1328           0 :             (fd_acct_addr_t const *)tile->pack.bundle.tip_payment_program_addr,
    1329           0 :             (fd_acct_addr_t const *)ctx->crank->vote_pubkey->b,
    1330           0 :             (fd_acct_addr_t const *)tile->pack.bundle.tip_distribution_authority,
    1331           0 :             schedule_strategy_strings[ tile->pack.schedule_strategy ],
    1332           0 :             tile->pack.bundle.commission_bps ) ) ) {
    1333           0 :       FD_LOG_ERR(( "constructing bundle generator failed" ));
    1334           0 :     }
    1335             : 
    1336           0 :     ulong sign_in_idx  = fd_topo_find_tile_in_link ( topo, tile, "sign_pack", tile->kind_id );
    1337           0 :     ulong sign_out_idx = fd_topo_find_tile_out_link( topo, tile, "pack_sign", tile->kind_id );
    1338           0 :     FD_TEST( sign_in_idx!=ULONG_MAX );
    1339           0 :     fd_topo_link_t const * sign_in = &topo->links[ tile->in_link_id[ sign_in_idx ] ];
    1340           0 :     fd_topo_link_t const * sign_out = &topo->links[ tile->out_link_id[ sign_out_idx ] ];
    1341             : 
    1342           0 :     fd_sleep_t * sleep = NULL;
    1343           0 :     if( FD_UNLIKELY( topo->sleep_obj_id!=ULONG_MAX ) ) {
    1344           0 :       sleep = fd_sleep_join( fd_topo_obj_laddr( topo, topo->sleep_obj_id ) );
    1345           0 :       FD_TEST( sleep );
    1346           0 :     }
    1347             : 
    1348           0 :     if( FD_UNLIKELY( !fd_keyguard_client_join( fd_keyguard_client_new( ctx->crank->keyguard_client,
    1349           0 :             sign_out->mcache,
    1350           0 :             sign_out->dcache,
    1351           0 :             sign_in->mcache,
    1352           0 :             sign_in->dcache,
    1353           0 :             sign_out->mtu,
    1354           0 :             sign_in->mtu,
    1355           0 :             sleep,
    1356           0 :             sign_out->id,
    1357           0 :             fd_topo_find_link_consumer( topo, sign_out ) ) ) ) ) {
    1358           0 :       FD_LOG_ERR(( "failed to construct keyguard" ));
    1359           0 :     }
    1360             :     /* Initialize enough of the prev config that it produces a
    1361             :        transaction */
    1362           0 :     ctx->crank->prev_config->discriminator       = 0x82ccfa1ee0aa0c9bUL;
    1363           0 :     ctx->crank->prev_config->tip_receiver->b[1]  = 1;
    1364           0 :     ctx->crank->prev_config->block_builder->b[2] = 1;
    1365             : 
    1366           0 :     memset( ctx->crank->tip_receiver_owner, '\0', 32UL );
    1367           0 :     memset( ctx->crank->recent_blockhash,   '\0', 32UL );
    1368           0 :     memset( ctx->crank->last_sig,           '\0', 64UL );
    1369           0 :     ctx->crank->ib_inserted    = 0;
    1370           0 :     ctx->crank->epoch          = 0UL;
    1371           0 :     ctx->crank->keyswitch = fd_keyswitch_join( fd_topo_obj_laddr( topo, tile->id_keyswitch_obj_id ) );
    1372           0 :     FD_TEST( ctx->crank->keyswitch );
    1373           0 :   } else {
    1374           0 :     memset( ctx->crank, '\0', sizeof(ctx->crank) );
    1375           0 :   }
    1376             : 
    1377             : 
    1378           0 :   ctx->cur_spot                      = NULL;
    1379           0 :   ctx->is_bundle                     = 0;
    1380           0 :   ctx->strategy                      = tile->pack.schedule_strategy;
    1381           0 :   ctx->max_pending_transactions      = tile->pack.max_pending_transactions;
    1382           0 :   ctx->leader_slot                   = ULONG_MAX;
    1383           0 :   ctx->block_height                  = 0UL;
    1384           0 :   ctx->auction_last_attempt_tick     = 0L;
    1385           0 :   ctx->auction_next_tick             = LONG_MAX;
    1386           0 :   ctx->auction_final_start_tick      = LONG_MAX;
    1387           0 :   ctx->leader_bank_idx               = ULONG_MAX;
    1388           0 :   ctx->leader_bank_seq               = ULONG_MAX;
    1389           0 :   ctx->pack_idx                      = 0UL;
    1390           0 :   ctx->slot_microblock_cnt           = 0UL;
    1391           0 :   ctx->pack_txn_cnt                  = 0UL;
    1392           0 :   ctx->slot_max_microblocks          = 0UL;
    1393           0 :   ctx->slot_max_data                 = 0UL;
    1394           0 :   ctx->drain_execle                  = 0;
    1395           0 :   ctx->rng                           = rng;
    1396           0 :   fd_clock_tile_init( ctx->clock );
    1397           0 :   double tick_per_ns                 = ctx->clock->epoch->w;
    1398           0 :   ctx->last_successful_insert        = 0L;
    1399           0 :   ctx->highest_observed_block_height = 0UL;
    1400           0 :   ctx->microblock_duration_ticks     = (ulong)(tick_per_ns*(double)MICROBLOCK_DURATION_NS  + 0.5);
    1401           0 :   ctx->auction_bundle_end_gap_tick   = (long)(tick_per_ns*(double)FD_PACK_AUCTION_BUNDLE_END_GAP_NS);
    1402           0 :   ctx->auction_spacing_tick          = (long)(tick_per_ns*(double)FD_PACK_AUCTION_SPACING_NS);
    1403           0 :   ctx->auction_interval_tick         = (long)(tick_per_ns*(double)FD_PACK_AUCTION_INTERVAL_NS);
    1404           0 :   ctx->use_consumed_cus              = tile->pack.use_consumed_cus;
    1405           0 :   ctx->bench_max_shreds_per_block    = tile->pack.bench_max_shreds_per_block;
    1406           0 :   ctx->crank->enabled                = tile->pack.bundle.enabled;
    1407             : 
    1408           0 :   ctx->limits.slot_max_cost                = limits_lower->max_cost_per_block;
    1409           0 :   ctx->limits.slot_max_write_cost_per_acct = limits_lower->max_write_cost_per_acct;
    1410             : 
    1411           0 :   ctx->execle_cnt       = tile->pack.execle_tile_count;
    1412           0 :   ctx->poll_cursor      = 0;
    1413           0 :   ctx->skip_cnt         = 0L;
    1414           0 :   ctx->execle_idle_bitset = fd_ulong_mask_lsb( (int)tile->pack.execle_tile_count );
    1415           0 :   for( ulong i=0UL; i<tile->pack.execle_tile_count; i++ ) {
    1416           0 :     ulong busy_obj_id = fd_pod_queryf_ulong( topo->props, ULONG_MAX, "execle_busy.%lu", i );
    1417           0 :     FD_TEST( busy_obj_id!=ULONG_MAX );
    1418           0 :     ctx->execle_current[ i ] = fd_fseq_join( fd_topo_obj_laddr( topo, busy_obj_id ) );
    1419           0 :     ctx->execle_expect[ i ] = ULONG_MAX;
    1420           0 :     if( FD_UNLIKELY( !ctx->execle_current[ i ] ) ) FD_LOG_ERR(( "execle tile %lu has no busy flag", i ));
    1421           0 :     ctx->execle_ready_at[ i ] = 0L;
    1422           0 :     FD_TEST( ULONG_MAX==fd_fseq_query( ctx->execle_current[ i ] ) );
    1423           0 :   }
    1424             : 
    1425           0 :   for( ulong i=0UL; i<tile->in_cnt; i++ ) {
    1426           0 :     fd_topo_link_t const * link = &topo->links[ tile->in_link_id[ i ] ];
    1427           0 :     fd_topo_wksp_t const * link_wksp = &topo->workspaces[ topo->objs[ link->dcache_obj_id ].wksp_id ];
    1428             : 
    1429           0 :     ctx->in[ i ].mem    = link_wksp->wksp;
    1430           0 :     ctx->in[ i ].chunk0 = fd_dcache_compact_chunk0( ctx->in[ i ].mem, link->dcache );
    1431           0 :     ctx->in[ i ].wmark  = fd_dcache_compact_wmark ( ctx->in[ i ].mem, link->dcache, link->mtu );
    1432           0 :   }
    1433             : 
    1434           0 :   char const * execle_out_name = fd_topo_find_tile_out_link( topo, tile, "pack_execle", 0UL )!=ULONG_MAX ? "pack_execle" : "pack_bank";
    1435           0 :   for( ulong i=0UL; i<ctx->execle_cnt; i++ ) {
    1436           0 :     fd_pack_out_ctx_t * out = &ctx->execle_out[ i ];
    1437           0 :     out->out_idx = fd_topo_find_tile_out_link( topo, tile, execle_out_name, i );
    1438           0 :     FD_TEST( out->out_idx!=ULONG_MAX );
    1439           0 :     fd_topo_link_t const * link = &topo->links[ tile->out_link_id[ out->out_idx ] ];
    1440           0 :     out->mem    = topo->workspaces[ topo->objs[ link->dcache_obj_id ].wksp_id ].wksp;
    1441           0 :     out->chunk0 = fd_dcache_compact_chunk0( out->mem, link->dcache );
    1442           0 :     out->wmark  = fd_dcache_compact_wmark ( out->mem, link->dcache, link->mtu );
    1443           0 :     out->chunk  = out->chunk0;
    1444           0 :   }
    1445             : 
    1446           0 :   ctx->poh_out.out_idx = fd_topo_find_tile_out_link( topo, tile, "pack_poh", 0UL );
    1447           0 :   FD_TEST( ctx->poh_out.out_idx!=ULONG_MAX );
    1448           0 :   fd_topo_link_t const * poh_out_link = &topo->links[ tile->out_link_id[ ctx->poh_out.out_idx ] ];
    1449           0 :   ctx->poh_out.mem    = topo->workspaces[ topo->objs[ poh_out_link->dcache_obj_id ].wksp_id ].wksp;
    1450           0 :   ctx->poh_out.chunk0 = fd_dcache_compact_chunk0( ctx->poh_out.mem, poh_out_link->dcache );
    1451           0 :   ctx->poh_out.wmark  = fd_dcache_compact_wmark ( ctx->poh_out.mem, poh_out_link->dcache, poh_out_link->mtu );
    1452           0 :   ctx->poh_out.chunk  = ctx->poh_out.chunk0;
    1453             : 
    1454             :   /* Initialize metrics storage */
    1455           0 :   memset( ctx->insert_result, '\0', FD_PACK_INSERT_RETVAL_CNT * sizeof(ulong) );
    1456           0 :   fd_histf_join( fd_metrics_histf_new_ns( ctx->schedule_duration, FD_MHIST_EDGES_NS( PACK, MICROBLOCK_SCHEDULE_DURATION_NANOS ) ) );
    1457           0 :   fd_histf_join( fd_metrics_histf_new_ns( ctx->no_sched_duration, FD_MHIST_EDGES_NS( PACK, MICROBLOCK_SCHEDULE_EMPTY_DURATION_NANOS ) ) );
    1458           0 :   fd_histf_join( fd_metrics_histf_new_ns( ctx->insert_duration,   FD_MHIST_EDGES_NS( PACK, TXN_INSERT_DURATION_NANOS ) ) );
    1459           0 :   fd_histf_join( fd_metrics_histf_new_ns( ctx->complete_duration, FD_MHIST_EDGES_NS( PACK, MICROBLOCK_COMPLETE_DURATION_NANOS ) ) );
    1460           0 :   ctx->auction_started   = 0UL;
    1461           0 :   ctx->auction_cancelled = 0UL;
    1462           0 :   memset( ctx->auction_ended,   0, sizeof(ctx->auction_ended)   );
    1463           0 :   fd_histf_join( fd_metrics_histf_new_ns( ctx->auction_duration,  FD_MHIST_EDGES_NS( PACK, AUCTION_DURATION_NANOS ) ) );
    1464           0 :   ctx->metric_state = 0;
    1465           0 :   ctx->metric_state_begin = fd_tickcount();
    1466           0 :   memset( ctx->metric_timing,             '\0', 16*sizeof(long)                        );
    1467           0 :   memset( ctx->current_bundle,            '\0', sizeof(ctx->current_bundle)            );
    1468           0 :   memset( ctx->blk_engine_cfg,            '\0', sizeof(ctx->blk_engine_cfg)            );
    1469           0 :   memset( ctx->last_sched_metrics,        '\0', sizeof(ctx->last_sched_metrics)        );
    1470           0 :   memset( ctx->start_block_sched_metrics, '\0', sizeof(ctx->start_block_sched_metrics) );
    1471           0 :   memset( ctx->crank->metrics,            '\0', sizeof(ctx->crank->metrics)            );
    1472             : 
    1473           0 :   FD_LOG_INFO(( "packing microblocks of at most %lu transactions to %lu execle tiles using strategy %i", EFFECTIVE_TXN_PER_MICROBLOCK, tile->pack.execle_tile_count, ctx->strategy ));
    1474             : 
    1475           0 :   ulong scratch_top = FD_SCRATCH_ALLOC_FINI( l, scratch_align() );
    1476           0 :   if( FD_UNLIKELY( scratch_top > (ulong)scratch + scratch_footprint( tile ) ) )
    1477           0 :     FD_LOG_ERR(( "scratch overflow %lu %lu %lu", scratch_top - (ulong)scratch - scratch_footprint( tile ), scratch_top, (ulong)scratch + scratch_footprint( tile ) ));
    1478           0 : }
    1479             : 
    1480             : static ulong
    1481             : populate_allowed_seccomp( fd_topo_t const *      topo,
    1482             :                           fd_topo_tile_t const * tile,
    1483             :                           ulong                  out_cnt,
    1484           0 :                           struct sock_filter *   out ) {
    1485           0 :   (void)topo;
    1486           0 :   (void)tile;
    1487             : 
    1488           0 :   populate_sock_filter_policy_fd_pack_tile( out_cnt, out, (uint)fd_log_private_logfile_fd() );
    1489           0 :   return sock_filter_policy_fd_pack_tile_instr_cnt;
    1490           0 : }
    1491             : 
    1492             : static ulong
    1493             : populate_allowed_fds( fd_topo_t const *      topo,
    1494             :                       fd_topo_tile_t const * tile,
    1495             :                       ulong                  out_fds_cnt,
    1496           0 :                       int *                  out_fds ) {
    1497           0 :   (void)topo;
    1498           0 :   (void)tile;
    1499             : 
    1500           0 :   if( FD_UNLIKELY( out_fds_cnt<2UL ) ) FD_LOG_ERR(( "out_fds_cnt %lu", out_fds_cnt ));
    1501             : 
    1502           0 :   ulong out_cnt = 0UL;
    1503           0 :   out_fds[ out_cnt++ ] = 2; /* stderr */
    1504           0 :   if( FD_LIKELY( -1!=fd_log_private_logfile_fd() ) )
    1505           0 :     out_fds[ out_cnt++ ] = fd_log_private_logfile_fd(); /* logfile */
    1506           0 :   return out_cnt;
    1507           0 : }
    1508             : 
    1509             : /* Pack can publish a frag in the following scenarios:
    1510             : 
    1511             :    after_credit:
    1512             :      A. TIMED_OUT. Sets ctx->leader_slot=ULONG_MAX. return.
    1513             :      B. DONE_DRAINING. *after* DONE_PACKING. return.
    1514             :      C. SCHEDULE_MB. *doesn't* return.
    1515             :      D. EXHAUST_MICROBLOCKS. Sets ctx->leader_slot=ULONG_MAX. return.
    1516             :    after_frag:
    1517             :          E. ABANDONED. Requires ctx->leader_slot!=ULONG_MAX
    1518             : 
    1519             :      It isn't possible to get a burst of 3, but a burst of 2 is possible
    1520             :      in these situations.
    1521             : 
    1522             :      B -> E
    1523             :      C -> E
    1524             :      C -> D
    1525             :  */
    1526           0 : #define STEM_BURST (2UL)
    1527             : 
    1528           0 : #define STEM_LAZY  (128L*3000L)
    1529             : 
    1530           0 : #define STEM_CALLBACK_CONTEXT_TYPE  fd_pack_ctx_t
    1531           0 : #define STEM_CALLBACK_CONTEXT_ALIGN alignof(fd_pack_ctx_t)
    1532             : 
    1533           0 : #define STEM_CALLBACK_DURING_HOUSEKEEPING during_housekeeping
    1534             : #define STEM_CALLBACK_PREVENT_PARK        prevent_park
    1535           0 : #define STEM_CALLBACK_NEXT_DEADLINE       next_deadline
    1536           0 : #define STEM_CALLBACK_BEFORE_CREDIT       before_credit
    1537           0 : #define STEM_CALLBACK_AFTER_CREDIT        after_credit
    1538           0 : #define STEM_CALLBACK_DURING_FRAG         during_frag
    1539           0 : #define STEM_CALLBACK_AFTER_FRAG          after_frag
    1540           0 : #define STEM_CALLBACK_METRICS_WRITE       metrics_write
    1541             : 
    1542             : #include "../stem/fd_stem.c"
    1543             : 
    1544             : fd_topo_run_tile_t fd_tile_pack = {
    1545             :   .name                     = "pack",
    1546             :   .populate_allowed_seccomp = populate_allowed_seccomp,
    1547             :   .populate_allowed_fds     = populate_allowed_fds,
    1548             :   .scratch_align            = scratch_align,
    1549             :   .scratch_footprint        = scratch_footprint,
    1550             :   .privileged_init          = privileged_init,
    1551             :   .unprivileged_init        = unprivileged_init,
    1552             :   .run                      = stem_run,
    1553             : };

Generated by: LCOV version 1.14