aboutsummaryrefslogtreecommitdiffstats
path: root/src/vnet/bfd/bfd_main.h
blob: 0bdcfb876224115efdf79b531be1bcc5bbc2524a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/*
 * Copyright (c) 2011-2016 Cisco and/or its affiliates.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @file
 * @brief BFD global declarations
 */
#ifndef __included_bfd_main_h__
#define __included_bfd_main_h__

#include <vnet/vnet.h>
#include <vnet/bfd/bfd_protocol.h>
#include <vnet/bfd/bfd_udp.h>
#include <vlib/log.h>
#include <vppinfra/os.h>
#include <vppinfra/tw_timer_1t_3w_1024sl_ov.h>

#define foreach_bfd_mode(F) \
  F (asynchronous)          \
  F (demand)

typedef enum
{
#define F(x) BFD_MODE_##x,
  foreach_bfd_mode (F)
#undef F
} bfd_mode_e;

typedef struct
{
  /** global configuration key ID */
  u32 conf_key_id;

  /** keeps track of how many sessions reference this key */
  u32 use_count;

  /**
   * key data directly usable for bfd purposes - already padded with zeroes
   * (so we don't need the actual length)
   */
  u8 key[20];

  /** authentication type for this key */
  bfd_auth_type_e auth_type;
} bfd_auth_key_t;

#define foreach_bfd_poll_state(F) \
  F (NOT_NEEDED)                  \
  F (NEEDED)                      \
  F (IN_PROGRESS)                 \
  F (IN_PROGRESS_AND_QUEUED)

typedef enum
{
#define F(x) BFD_POLL_##x,
  foreach_bfd_poll_state (F)
#undef F
} bfd_poll_state_e;

/**
 * hop types
 */
#define foreach_bfd_hop(F)                     \
  F (SINGLE, "single")                         \
  F (MULTI,  "multi")                          \

typedef enum
{
#define F(sym, str) BFD_HOP_TYPE_##sym,
  foreach_bfd_hop (F)
#undef F
} bfd_hop_type_e;

typedef struct bfd_session_s
{
  /** index in bfd_main.sessions pool */
  u32 bs_idx;

  /** session state */
  bfd_state_e local_state;

  /** remote session state */
  bfd_state_e remote_state;

  /** BFD hop type */
  bfd_hop_type_e hop_type;

  /** local diagnostics */
  bfd_diag_code_e local_diag;

  /** remote diagnostics */
  bfd_diag_code_e remote_diag;

  /** local discriminator */
  u32 local_discr;

  /** remote discriminator */
  u32 remote_discr;

  /** configured desired min tx interval (microseconds) */
  u32 config_desired_min_tx_usec;

  /** configured desired min tx interval (nsec) */
  u64 config_desired_min_tx_nsec;

  /** effective desired min tx interval (nsec) */
  u64 effective_desired_min_tx_nsec;

  /** configured required min rx interval (microseconds) */
  u32 config_required_min_rx_usec;

  /** configured required min rx interval (nsec) */
  u64 config_required_min_rx_nsec;

  /** effective required min rx interval (nsec) */
  u64 effective_required_min_rx_nsec;

  /** remote min rx interval (microseconds) */
  u64 remote_min_rx_usec;

  /** remote min rx interval (nsec) */
  u64 remote_min_rx_nsec;

  /** remote min echo rx interval (microseconds) */
  u64 remote_min_echo_rx_usec;

  /** remote min echo rx interval (nsec) */
  u64 remote_min_echo_rx_nsec;

  /** remote desired min tx interval (nsec) */
  u64 remote_desired_min_tx_nsec;

  /** configured detect multiplier */
  u8 local_detect_mult;

  /** 1 if remote system sets demand mode, 0 otherwise */
  u8 remote_demand;

  /** remote detect multiplier */
  u8 remote_detect_mult;

  /** 1 is echo function is active, 0 otherwise */
  u8 echo;

  /** next event time in nsec for this session (0 if no event) */
  u64 event_time_nsec;

  /** timing wheel internal id used to manipulate timer (if set) */
  u32 tw_id;

  /** transmit interval */
  u64 transmit_interval_nsec;

  /** next time at which to transmit a packet */
  u64 tx_timeout_nsec;

  /** timestamp of last packet transmitted */
  u64 last_tx_nsec;

  /** timestamp of last packet received */
  u64 last_rx_nsec;

  /** transmit interval for echo packets */
  u64 echo_transmit_interval_nsec;

  /** next time at which to transmit echo packet */
  u64 echo_tx_timeout_nsec;

  /** timestamp of last echo packet transmitted */
  u64 echo_last_tx_nsec;

  /** timestamp of last echo packet received */
  u64 echo_last_rx_nsec;

  /** secret used for calculating/checking checksum of echo packets */
  u32 echo_secret;

  /** detection time */
  u64 detection_time_nsec;

  /** state info regarding poll sequence */
  bfd_poll_state_e poll_state;

  /**
   * helper for delayed poll sequence - marks either start of running poll
   * sequence or timeout, after which we can start the next poll sequnce
   */
  u64 poll_state_start_or_timeout_nsec;

  /** authentication information */
  struct
  {
    /** current key in use */
    bfd_auth_key_t *curr_key;

    /**
     * set to next key to use if delayed switch is enabled - in that case
     * the key is switched when first incoming packet is signed with next_key
     */
    bfd_auth_key_t *next_key;

    /** sequence number incremented occasionally or always (if meticulous) */
    u32 local_seq_number;

    /** remote sequence number */
    u32 remote_seq_number;

    /** set to 1 if remote sequence number is known */
    u8 remote_seq_number_known;

    /** current key ID sent out in bfd packet */
    u8 curr_bfd_key_id;

    /** key ID to use when switched to next_key */
    u8 next_bfd_key_id;

    /**
     * set to 1 if delayed action is pending, which might be activation
     * of authentication, change of key or deactivation
     */
    u8 is_delayed;
  } auth;

  /** transport type for this session */
  bfd_transport_e transport;

  /** union of transport-specific data */
  union
  {
    bfd_udp_session_t udp;
  };
} bfd_session_t;

/**
 * listener events
 */
#define foreach_bfd_listen_event(F)            \
  F (CREATE, "sesion-created")                 \
  F (UPDATE, "session-updated")                \
  F (DELETE, "session-deleted")

typedef enum
{
#define F(sym, str) BFD_LISTEN_EVENT_##sym,
  foreach_bfd_listen_event (F)
#undef F
} bfd_listen_event_e;

/**
 * session nitification call back function type
 */
typedef void (*bfd_notify_fn_t) (bfd_listen_event_e, const bfd_session_t *);

typedef struct
{
  /** lock to protect data structures */
  clib_spinlock_t lock;
  int lock_recursion_count;
  uword owner_thread_index;

  /** Number of event wakeup RPCs in flight. Should be 0 or 1 */
  int bfd_process_wakeup_events_in_flight;

  /** The timestamp of last wakeup event being sent */
  u64 bfd_process_wakeup_event_start_nsec;

  /** The time it took the last wakeup event to make it to handling */
  u64 bfd_process_wakeup_event_delay_nsec;

  /** When the bfd process is supposed to wake up next */
  u64 bfd_process_next_wakeup_nsec;

  /** pool of bfd sessions context data */
  bfd_session_t *sessions;

  /** timing wheel for scheduling timeouts */
    TWT (tw_timer_wheel) wheel;

  /** hashmap - bfd session by discriminator */
  u32 *session_by_disc;

  /** background process node index */
  u32 bfd_process_node_index;

  /** convenience variables */
  vlib_main_t *vlib_main;
  vnet_main_t *vnet_main;

  /** how many nanoseconds is one timing wheel tick */
  u64 nsec_per_tw_tick;

  /** default desired min tx in nsec */
  u64 default_desired_min_tx_nsec;

  /** minimum required min rx while echo function is active - nsec */
  u64 min_required_min_rx_while_echo_nsec;

  /** for generating random numbers */
  u32 random_seed;

  /** pool of authentication keys */
  bfd_auth_key_t *auth_keys;

  /** hashmap - index in pool auth_keys by conf_key_id */
  u32 *auth_key_by_conf_key_id;

  /** vector of callback notification functions */
  bfd_notify_fn_t *listeners;

  /** log class */
  vlib_log_class_t log_class;

  u16 msg_id_base;
} bfd_main_t;

extern bfd_main_t bfd_main;

/** Packet counters */
#define foreach_bfd_error(F)               \
  F (NONE, "good bfd packets (processed)") \
  F (BAD, "invalid bfd packets")           \
  F (DISABLED, "bfd packets received on disabled interfaces")

typedef enum
{
#define F(sym, str) BFD_ERROR_##sym,
  foreach_bfd_error (F)
#undef F
    BFD_N_ERROR,
} bfd_error_t;

/** bfd packet trace capture */
typedef struct
{
  u32 len;
  u8 data[400];
} bfd_input_trace_t;

typedef enum
{
  BFD_EVENT_RESCHEDULE = 1,
  BFD_EVENT_NEW_SESSION,
  BFD_EVENT_CONFIG_CHANGED,
} bfd_process_event_e;

/* *INDENT-OFF* */
/** echo packet structure */
typedef CLIB_PACKED (struct {
  /** local discriminator */
  u32 discriminator;
  /** expire time of this packet - nsec */
  u64 expire_time_nsec;
  /** checksum - based on discriminator, local secret and expire time */
  u64 checksum;
}) bfd_echo_pkt_t;
/* *INDENT-ON* */

static inline void
bfd_lock (bfd_main_t * bm)
{
  uword my_thread_index = __os_thread_index;

  if (bm->owner_thread_index == my_thread_index
      && bm->lock_recursion_count > 0)
    {
      bm->lock_recursion_count++;
      return;
    }

  clib_spinlock_lock_if_init (&bm->lock);
  bm->lock_recursion_count = 1;
  bm->owner_thread_index = my_thread_index;
}

static inline void
bfd_unlock (bfd_main_t * bm)
{
  uword my_thread_index = __os_thread_index;
  ASSERT (bm->owner_thread_index == my_thread_index);

  if (bm->lock_recursion_count > 1)
    {
      bm->lock_recursion_count--;
      return;
    }
  bm->lock_recursion_count = 0;
  bm->owner_thread_index = ~0;
  clib_spinlock_unlock_if_init (&bm->lock);
}

static inline void
bfd_lock_check (bfd_main_t * bm)
{
  if (PREDICT_FALSE (bm->lock_recursion_count < 1))
    clib_warning ("lock check failure");
}

u8 *bfd_input_format_trace (u8 * s, va_list * args);
bfd_session_t *bfd_get_session (bfd_main_t * bm, bfd_transport_e t);
void bfd_put_session (bfd_main_t * bm, bfd_session_t * bs);
bfd_session_t *bfd_find_session_by_idx (bfd_main_t * bm, uword bs_idx);
bfd_session_t *bfd_find_session_by_disc (bfd_main_t * bm, u32 disc);
void bfd_session_start (bfd_main_t * bm, bfd_session_t * bs);
void bfd_consume_pkt (vlib_main_t * vm, bfd_main_t * bm,
		      const bfd_pkt_t * bfd, u32 bs_idx);
int bfd_consume_echo_pkt (vlib_main_t * vm, bfd_main_t * bm,
			  vlib_buffer_t * b);
int bfd_verify_pkt_common (const bfd_pkt_t * pkt);
int bfd_verify_pkt_auth (vlib_main_t * vm, const bfd_pkt_t * pkt,
			 u16 pkt_size, bfd_session_t * bs);
void bfd_event (bfd_main_t * bm, bfd_session_t * bs);
void bfd_init_final_control_frame (vlib_main_t * vm, vlib_buffer_t * b,
				   bfd_main_t * bm, bfd_session_t * bs,
				   int is_local);
u8 *format_bfd_session (u8 * s, va_list * args);
u8 *format_bfd_session_brief (u8 * s, va_list * args);
u8 *format_bfd_auth_key (u8 * s, va_list * args);
void bfd_session_set_flags (vlib_main_t * vm, bfd_session_t * bs,
			    u8 admin_up_down);
unsigned bfd_auth_type_supported (bfd_auth_type_e auth_type);
vnet_api_error_t bfd_auth_activate (bfd_session_t * bs, u32 conf_key_id,
				    u8 bfd_key_id, u8 is_delayed);
vnet_api_error_t bfd_auth_deactivate (bfd_session_t * bs, u8 is_delayed);
vnet_api_error_t bfd_session_set_params (bfd_main_t * bm, bfd_session_t * bs,
					 u32 desired_min_tx_usec,
					 u32 required_min_rx_usec,
					 u8 detect_mult);

u32 bfd_nsec_to_usec (u64 nsec);
const char *bfd_poll_state_string (bfd_poll_state_e state);

#define USEC_PER_MS (1000LL)
#define MSEC_PER_SEC (1000LL)
#define NSEC_PER_USEC (1000LL)
#define USEC_PER_SEC (MSEC_PER_SEC * USEC_PER_MS)
#define NSEC_PER_SEC (NSEC_PER_USEC * USEC_PER_SEC)
#define SEC_PER_NSEC ((f64)1/NSEC_PER_SEC)

/** timing wheel tick-rate, 1ms should be good enough */
#define BFD_TW_TPS (MSEC_PER_SEC)

/** default, slow transmission interval for BFD packets, per spec at least 1s */
#define BFD_DEFAULT_DESIRED_MIN_TX_USEC USEC_PER_SEC

/**
 * minimum required min rx set locally when echo function is used, per spec
 * should be set to at least 1s
 */
#define BFD_REQUIRED_MIN_RX_USEC_WHILE_ECHO USEC_PER_SEC

/**
 * Register a callback function to receive session notifications.
 */
void bfd_register_listener (bfd_notify_fn_t fn);

#endif /* __included_bfd_main_h__ */

/*
 * fd.io coding-style-patch-verification: ON
 *
 * Local Variables:
 * eval: (c-set-style "gnu")
 * End:
 */
< TW_SLOTS_PER_RING); interval -= (((u64) glacier_ring_offset) << (2 * TW_RING_SHIFT)); #endif #if TW_TIMER_WHEELS > 1 slow_ring_offset = interval >> TW_RING_SHIFT; ASSERT ((u64) slow_ring_offset < TW_SLOTS_PER_RING); interval -= (((u64) slow_ring_offset) << TW_RING_SHIFT); #endif fast_ring_offset = interval & TW_RING_MASK; /* * Account for the current wheel positions(s) * This is made slightly complicated by the fact that the current * index vector will contain (TW_SLOTS_PER_RING, ...) when * the actual position is (0, ...) */ fast_ring_offset += tw->current_index[TW_TIMER_RING_FAST] & TW_RING_MASK; #if TW_TIMER_WHEELS > 1 carry = fast_ring_offset >= TW_SLOTS_PER_RING ? 1 : 0; fast_ring_offset %= TW_SLOTS_PER_RING; slow_ring_offset += (tw->current_index[TW_TIMER_RING_SLOW] & TW_RING_MASK) + carry; carry = slow_ring_offset >= TW_SLOTS_PER_RING ? 1 : 0; slow_ring_offset %= TW_SLOTS_PER_RING; #endif #if TW_TIMER_WHEELS > 2 glacier_ring_offset += (tw->current_index[TW_TIMER_RING_GLACIER] & TW_RING_MASK) + carry; glacier_ring_offset %= TW_SLOTS_PER_RING; #endif #if TW_TIMER_WHEELS > 2 if (glacier_ring_offset != (tw->current_index[TW_TIMER_RING_GLACIER] & TW_RING_MASK)) { /* We'll need slow and fast ring offsets later */ t->slow_ring_offset = slow_ring_offset; t->fast_ring_offset = fast_ring_offset; ts = &tw->w[TW_TIMER_RING_GLACIER][glacier_ring_offset]; timer_addhead (tw->timers, ts->head_index, t - tw->timers); #if TW_START_STOP_TRACE_SIZE > 0 TW (tw_timer_trace) (tw, timer_id, user_id, t - tw->timers); #endif return; } #endif #if TW_TIMER_WHEELS > 1 /* Timer expires more than 51.2 seconds from now? */ if (slow_ring_offset != (tw->current_index[TW_TIMER_RING_SLOW] & TW_RING_MASK)) { /* We'll need the fast ring offset later... */ t->fast_ring_offset = fast_ring_offset; ts = &tw->w[TW_TIMER_RING_SLOW][slow_ring_offset]; timer_addhead (tw->timers, ts->head_index, t - tw->timers); #if TW_START_STOP_TRACE_SIZE > 0 TW (tw_timer_trace) (tw, timer_id, user_id, t - tw->timers); #endif return; } #else fast_ring_offset %= TW_SLOTS_PER_RING; #endif /* Timer expires less than one fast-ring revolution from now */ ts = &tw->w[TW_TIMER_RING_FAST][fast_ring_offset]; timer_addhead (tw->timers, ts->head_index, t - tw->timers); #if TW_FAST_WHEEL_BITMAP tw->fast_slot_bitmap = clib_bitmap_set (tw->fast_slot_bitmap, fast_ring_offset, 1); #endif #if TW_START_STOP_TRACE_SIZE > 0 TW (tw_timer_trace) (tw, timer_id, user_id, t - tw->timers); #endif } /** * @brief Start a Tw Timer * @param tw_timer_wheel_t * tw timer wheel object pointer * @param u32 user_id user defined timer id, presumably for a tw session * @param u32 timer_id app-specific timer ID. 4 bits. * @param u64 interval timer interval in ticks * @returns handle needed to cancel the timer */ u32 TW (tw_timer_start) (TWT (tw_timer_wheel) * tw, u32 user_id, u32 timer_id, u64 interval) { TWT (tw_timer) * t; ASSERT (interval); pool_get (tw->timers, t); clib_memset (t, 0xff, sizeof (*t)); t->user_handle = TW (make_internal_timer_handle) (user_id, timer_id); timer_add (tw, t, interval); return t - tw->timers; } #if TW_TIMER_SCAN_FOR_HANDLE > 0 int TW (scan_for_handle) (TWT (tw_timer_wheel) * tw, u32 handle) { int i, j; tw_timer_wheel_slot_t *ts; TWT (tw_timer) * t, *head; u32 next_index; int rv = 0; for (i = 0; i < TW_TIMER_WHEELS; i++) { for (j = 0; j < TW_SLOTS_PER_RING; j++) { ts = &tw->w[i][j]; head = pool_elt_at_index (tw->timers, ts->head_index); next_index = head->next; while (next_index != ts->head_index) { t = pool_elt_at_index (tw->timers, next_index); if (next_index == handle) { clib_warning ("handle %d found in ring %d slot %d", handle, i, j); clib_warning ("user handle 0x%x", t->user_handle); rv = 1; } next_index = t->next; } } } return rv; } #endif /* TW_TIMER_SCAN_FOR_HANDLE */ /** * @brief Stop a tw timer * @param tw_timer_wheel_t * tw timer wheel object pointer * @param u32 handle timer cancellation returned by tw_timer_start */ void TW (tw_timer_stop) (TWT (tw_timer_wheel) * tw, u32 handle) { TWT (tw_timer) * t; #if TW_TIMER_ALLOW_DUPLICATE_STOP /* * A vlib process may have its timer expire, and receive * an event before the expiration is processed. * That results in a duplicate tw_timer_stop. */ if (pool_is_free_index (tw->timers, handle)) return; #endif #if TW_START_STOP_TRACE_SIZE > 0 TW (tw_timer_trace) (tw, ~0, ~0, handle); #endif t = pool_elt_at_index (tw->timers, handle); /* in case of idiotic handle (e.g. passing a listhead index) */ ASSERT (t->user_handle != ~0); timer_remove (tw->timers, t); pool_put_index (tw->timers, handle); } int TW (tw_timer_handle_is_free) (TWT (tw_timer_wheel) * tw, u32 handle) { return pool_is_free_index (tw->timers, handle); } /** * @brief Update a tw timer * @param tw_timer_wheel_t * tw timer wheel object pointer * @param u32 handle timer returned by tw_timer_start * @param u32 interval timer interval in ticks */ void TW (tw_timer_update) (TWT (tw_timer_wheel) * tw, u32 handle, u64 interval) { TWT (tw_timer) * t; t = pool_elt_at_index (tw->timers, handle); timer_remove (tw->timers, t); timer_add (tw, t, interval); } /** * @brief Initialize a tw timer wheel template instance * @param tw_timer_wheel_t * tw timer wheel object pointer * @param void * expired_timer_callback. Passed a u32 * vector of * expired timer handles. The callback is optional. * @param f64 timer_interval_in_seconds */ void TW (tw_timer_wheel_init) (TWT (tw_timer_wheel) * tw, void *expired_timer_callback, f64 timer_interval_in_seconds, u32 max_expirations) { int ring, slot; tw_timer_wheel_slot_t *ts; TWT (tw_timer) * t; clib_memset (tw, 0, sizeof (*tw)); tw->expired_timer_callback = expired_timer_callback; tw->max_expirations = max_expirations; if (timer_interval_in_seconds == 0.0) { clib_warning ("timer interval is zero"); abort (); } tw->timer_interval = timer_interval_in_seconds; tw->ticks_per_second = 1.0 / timer_interval_in_seconds; tw->first_expires_tick = ~0ULL; vec_validate (tw->expired_timer_handles, 0); _vec_len (tw->expired_timer_handles) = 0; for (ring = 0; ring < TW_TIMER_WHEELS; ring++) { for (slot = 0; slot < TW_SLOTS_PER_RING; slot++) { ts = &tw->w[ring][slot]; pool_get (tw->timers, t); clib_memset (t, 0xff, sizeof (*t)); t->next = t->prev = t - tw->timers; ts->head_index = t - tw->timers; } } #if TW_OVERFLOW_VECTOR > 0 ts = &tw->overflow; pool_get (tw->timers, t); clib_memset (t, 0xff, sizeof (*t)); t->next = t->prev = t - tw->timers; ts->head_index = t - tw->timers; #endif } /** * @brief Free a tw timer wheel template instance * @param tw_timer_wheel_t * tw timer wheel object pointer */ void TW (tw_timer_wheel_free) (TWT (tw_timer_wheel) * tw) { int i, j; tw_timer_wheel_slot_t *ts; TWT (tw_timer) * head, *t; u32 next_index; for (i = 0; i < TW_TIMER_WHEELS; i++) { for (j = 0; j < TW_SLOTS_PER_RING; j++) { ts = &tw->w[i][j]; head = pool_elt_at_index (tw->timers, ts->head_index); next_index = head->next; while (next_index != ts->head_index) { t = pool_elt_at_index (tw->timers, next_index); next_index = t->next; pool_put (tw->timers, t); } pool_put (tw->timers, head); } } #if TW_OVERFLOW_VECVOR > 0 ts = &tw->overflow; head = pool_elt_at_index (tw->timers, ts->head_index); next_index = head->next; while (next_index != ts->head_index) { t = pool_elt_at_index (tw->timers, next_index); next_index = t->next; pool_put (tw->timers, t); } pool_put (tw->timers, head); #endif clib_memset (tw, 0, sizeof (*tw)); } /** * @brief Advance a tw timer wheel. Calls the expired timer callback * as needed. This routine should be called once every timer_interval seconds * @param tw_timer_wheel_t * tw timer wheel template instance pointer * @param f64 now the current time, e.g. from vlib_time_now(vm) * @returns u32 * vector of expired user handles */ static inline u32 * TW (tw_timer_expire_timers_internal) (TWT (tw_timer_wheel) * tw, f64 now, u32 * callback_vector_arg) { u32 nticks, i; tw_timer_wheel_slot_t *ts; TWT (tw_timer) * t, *head; u32 *callback_vector; u32 fast_wheel_index; u32 next_index; u32 slow_wheel_index __attribute__ ((unused)); u32 glacier_wheel_index __attribute__ ((unused)); /* Shouldn't happen */ if (PREDICT_FALSE (now < tw->next_run_time)) return callback_vector_arg; /* Number of ticks which have occurred */ nticks = tw->ticks_per_second * (now - tw->last_run_time); if (nticks == 0) return callback_vector_arg; /* Remember when we ran, compute next runtime */ tw->next_run_time = (now + tw->timer_interval); if (callback_vector_arg == 0) { _vec_len (tw->expired_timer_handles) = 0; callback_vector = tw->expired_timer_handles; } else callback_vector = callback_vector_arg; for (i = 0; i < nticks; i++) { fast_wheel_index = tw->current_index[TW_TIMER_RING_FAST]; if (TW_TIMER_WHEELS > 1) slow_wheel_index = tw->current_index[TW_TIMER_RING_SLOW]; if (TW_TIMER_WHEELS > 2) glacier_wheel_index = tw->current_index[TW_TIMER_RING_GLACIER]; #if TW_OVERFLOW_VECTOR > 0 /* Triple odometer-click? Process the overflow vector... */ if (PREDICT_FALSE (fast_wheel_index == TW_SLOTS_PER_RING && slow_wheel_index == TW_SLOTS_PER_RING && glacier_wheel_index == TW_SLOTS_PER_RING)) { u64 interval; u32 new_glacier_ring_offset, new_slow_ring_offset; u32 new_fast_ring_offset; ts = &tw->overflow; head = pool_elt_at_index (tw->timers, ts->head_index); next_index = head->next; /* Make slot empty */ head->next = head->prev = ts->head_index; /* traverse slot, place timers wherever they go */ while (next_index != head - tw->timers) { t = pool_elt_at_index (tw->timers, next_index); next_index = t->next; /* Remove from the overflow vector (hammer) */ t->next = t->prev = ~0; ASSERT (t->expiration_time >= tw->current_tick); interval = t->expiration_time - tw->current_tick; /* Right back onto the overflow vector? */ if (interval >= (1 << (3 * TW_RING_SHIFT))) { ts = &tw->overflow; timer_addhead (tw->timers, ts->head_index, t - tw->timers); continue; } /* Compute ring offsets */ new_glacier_ring_offset = interval >> (2 * TW_RING_SHIFT); interval -= (new_glacier_ring_offset << (2 * TW_RING_SHIFT)); /* Note: the wheels are at (0,0,0), no add-with-carry needed */ new_slow_ring_offset = interval >> TW_RING_SHIFT; interval -= (new_slow_ring_offset << TW_RING_SHIFT); new_fast_ring_offset = interval & TW_RING_MASK; t->slow_ring_offset = new_slow_ring_offset; t->fast_ring_offset = new_fast_ring_offset; /* Timer expires Right Now */ if (PREDICT_FALSE (t->slow_ring_offset == 0 && t->fast_ring_offset == 0 && new_glacier_ring_offset == 0)) { vec_add1 (callback_vector, t->user_handle); #if TW_START_STOP_TRACE_SIZE > 0 TW (tw_timer_trace) (tw, 0xfe, t->user_handle, t - tw->timers); #endif pool_put (tw->timers, t); } /* Timer moves to the glacier ring */ else if (new_glacier_ring_offset) { ts = &tw->w[TW_TIMER_RING_GLACIER][new_glacier_ring_offset]; timer_addhead (tw->timers, ts->head_index, t - tw->timers); } /* Timer moves to the slow ring */ else if (t->slow_ring_offset) { /* Add to slow ring */ ts = &tw->w[TW_TIMER_RING_SLOW][t->slow_ring_offset]; timer_addhead (tw->timers, ts->head_index, t - tw->timers); } /* Timer timer moves to the fast ring */ else { ts = &tw->w[TW_TIMER_RING_FAST][t->fast_ring_offset]; timer_addhead (tw->timers, ts->head_index, t - tw->timers); #if TW_FAST_WHEEL_BITMAP tw->fast_slot_bitmap = clib_bitmap_set (tw->fast_slot_bitmap, t->fast_ring_offset, 1); #endif } } } #endif #if TW_TIMER_WHEELS > 2 /* * Double odometer-click? Process one slot in the glacier ring... */ if (PREDICT_FALSE (fast_wheel_index == TW_SLOTS_PER_RING && slow_wheel_index == TW_SLOTS_PER_RING)) { glacier_wheel_index %= TW_SLOTS_PER_RING; ts = &tw->w[TW_TIMER_RING_GLACIER][glacier_wheel_index]; head = pool_elt_at_index (tw->timers, ts->head_index); next_index = head->next; /* Make slot empty */ head->next = head->prev = ts->head_index; /* traverse slot, deal timers into slow ring */ while (next_index != head - tw->timers) { t = pool_elt_at_index (tw->timers, next_index); next_index = t->next; /* Remove from glacier ring slot (hammer) */ t->next = t->prev = ~0; /* Timer expires Right Now */ if (PREDICT_FALSE (t->slow_ring_offset == 0 && t->fast_ring_offset == 0)) { vec_add1 (callback_vector, t->user_handle); #if TW_START_STOP_TRACE_SIZE > 0 TW (tw_timer_trace) (tw, 0xfe, t->user_handle, t - tw->timers); #endif pool_put (tw->timers, t); } /* Timer expires during slow-wheel tick 0 */ else if (PREDICT_FALSE (t->slow_ring_offset == 0)) { ts = &tw->w[TW_TIMER_RING_FAST][t->fast_ring_offset]; timer_addhead (tw->timers, ts->head_index, t - tw->timers); #if TW_FAST_WHEEL_BITMAP tw->fast_slot_bitmap = clib_bitmap_set (tw->fast_slot_bitmap, t->fast_ring_offset, 1); #endif } else /* typical case */ { /* Add to slow ring */ ts = &tw->w[TW_TIMER_RING_SLOW][t->slow_ring_offset]; timer_addhead (tw->timers, ts->head_index, t - tw->timers); } } } #endif #if TW_TIMER_WHEELS > 1 /* * Single odometer-click? Process a slot in the slow ring, */ if (PREDICT_FALSE (fast_wheel_index == TW_SLOTS_PER_RING)) { slow_wheel_index %= TW_SLOTS_PER_RING; ts = &tw->w[TW_TIMER_RING_SLOW][slow_wheel_index]; head = pool_elt_at_index (tw->timers, ts->head_index); next_index = head->next; /* Make slot empty */ head->next = head->prev = ts->head_index; /* traverse slot, deal timers into fast ring */ while (next_index != head - tw->timers) { t = pool_elt_at_index (tw->timers, next_index); next_index = t->next; /* Remove from sloe ring slot (hammer) */ t->next = t->prev = ~0; /* Timer expires Right Now */ if (PREDICT_FALSE (t->fast_ring_offset == 0)) { vec_add1 (callback_vector, t->user_handle); #if TW_START_STOP_TRACE_SIZE > 0 TW (tw_timer_trace) (tw, 0xfe, t->user_handle, t - tw->timers); #endif pool_put (tw->timers, t); } else /* typical case */ { /* Add to fast ring */ ts = &tw->w[TW_TIMER_RING_FAST][t->fast_ring_offset]; timer_addhead (tw->timers, ts->head_index, t - tw->timers); #if TW_FAST_WHEEL_BITMAP tw->fast_slot_bitmap = clib_bitmap_set (tw->fast_slot_bitmap, t->fast_ring_offset, 1); #endif } } } #endif /* Handle the fast ring */ fast_wheel_index %= TW_SLOTS_PER_RING; ts = &tw->w[TW_TIMER_RING_FAST][fast_wheel_index]; head = pool_elt_at_index (tw->timers, ts->head_index); next_index = head->next; /* Make slot empty */ head->next = head->prev = ts->head_index; /* Construct vector of expired timer handles to give the user */ while (next_index != ts->head_index) { t = pool_elt_at_index (tw->timers, next_index); next_index = t->next; vec_add1 (callback_vector, t->user_handle); #if TW_START_STOP_TRACE_SIZE > 0 TW (tw_timer_trace) (tw, 0xfe, t->user_handle, t - tw->timers); #endif pool_put (tw->timers, t); } /* If any timers expired, tell the user */ if (callback_vector_arg == 0 && vec_len (callback_vector)) { /* The callback is optional. We return the u32 * handle vector */ if (tw->expired_timer_callback) { tw->expired_timer_callback (callback_vector); vec_reset_length (callback_vector); } tw->expired_timer_handles = callback_vector; } #if TW_FAST_WHEEL_BITMAP tw->fast_slot_bitmap = clib_bitmap_set (tw->fast_slot_bitmap, fast_wheel_index, 0); #endif tw->current_tick++; fast_wheel_index++; tw->current_index[TW_TIMER_RING_FAST] = fast_wheel_index; #if TW_TIMER_WHEELS > 1 if (PREDICT_FALSE (fast_wheel_index == TW_SLOTS_PER_RING)) slow_wheel_index++; tw->current_index[TW_TIMER_RING_SLOW] = slow_wheel_index; #endif #if TW_TIMER_WHEELS > 2 if (PREDICT_FALSE (slow_wheel_index == TW_SLOTS_PER_RING)) glacier_wheel_index++; tw->current_index[TW_TIMER_RING_GLACIER] = glacier_wheel_index; #endif if (vec_len (callback_vector) >= tw->max_expirations) break; } if (callback_vector_arg == 0) tw->expired_timer_handles = callback_vector; tw->last_run_time += i * tw->timer_interval; return callback_vector; } u32 *TW (tw_timer_expire_timers) (TWT (tw_timer_wheel) * tw, f64 now) { return TW (tw_timer_expire_timers_internal) (tw, now, 0 /* no vector */ ); } u32 *TW (tw_timer_expire_timers_vec) (TWT (tw_timer_wheel) * tw, f64 now, u32 * vec) { return TW (tw_timer_expire_timers_internal) (tw, now, vec); } #if TW_FAST_WHEEL_BITMAP /** Returns an approximation to the first timer expiration in * timer-ticks from "now". To avoid wasting an unjustifiable * amount of time on the problem, we maintain an approximate fast-wheel slot * occupancy bitmap. We don't worry about clearing fast wheel bits * when timers are removed from fast wheel slots. */ u32 TW (tw_timer_first_expires_in_ticks) (TWT (tw_timer_wheel) * tw) { u32 first_expiring_index, fast_ring_index; i32 delta; if (clib_bitmap_is_zero (tw->fast_slot_bitmap)) return TW_SLOTS_PER_RING; fast_ring_index = tw->current_index[TW_TIMER_RING_FAST]; if (fast_ring_index == TW_SLOTS_PER_RING) fast_ring_index = 0; first_expiring_index = clib_bitmap_next_set (tw->fast_slot_bitmap, fast_ring_index); if (first_expiring_index == ~0 && fast_ring_index != 0) first_expiring_index = clib_bitmap_first_set (tw->fast_slot_bitmap); ASSERT (first_expiring_index != ~0); delta = (i32) first_expiring_index - (i32) fast_ring_index; if (delta < 0) delta += TW_SLOTS_PER_RING; ASSERT (delta >= 0); return (u32) delta; } #endif /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */