874f6a1350b5617239d4223e18dc36c0e08f7093
[vpp.git] / src / vlib / main.c
1 /*
2  * Copyright (c) 2015 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 /*
16  * main.c: main vector processing loop
17  *
18  * Copyright (c) 2008 Eliot Dresselhaus
19  *
20  * Permission is hereby granted, free of charge, to any person obtaining
21  * a copy of this software and associated documentation files (the
22  * "Software"), to deal in the Software without restriction, including
23  * without limitation the rights to use, copy, modify, merge, publish,
24  * distribute, sublicense, and/or sell copies of the Software, and to
25  * permit persons to whom the Software is furnished to do so, subject to
26  * the following conditions:
27  *
28  * The above copyright notice and this permission notice shall be
29  * included in all copies or substantial portions of the Software.
30  *
31  *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
32  *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33  *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
34  *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
35  *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
36  *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
37  *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38  */
39
40 #include <math.h>
41 #include <vppinfra/format.h>
42 #include <vlib/vlib.h>
43 #include <vlib/threads.h>
44 #include <vlib/stats/stats.h>
45 #include <vppinfra/tw_timer_1t_3w_1024sl_ov.h>
46
47 #include <vlib/unix/unix.h>
48
49 #define VLIB_FRAME_MAGIC (0xabadc0ed)
50
51 always_inline u32 *
52 vlib_frame_find_magic (vlib_frame_t * f, vlib_node_t * node)
53 {
54   return (void *) f + node->magic_offset;
55 }
56
57 static vlib_frame_t *
58 vlib_frame_alloc_to_node (vlib_main_t * vm, u32 to_node_index,
59                           u32 frame_flags)
60 {
61   vlib_node_main_t *nm = &vm->node_main;
62   vlib_frame_size_t *fs;
63   vlib_node_t *to_node;
64   vlib_frame_t *f;
65   u32 l, n;
66
67   ASSERT (vm == vlib_get_main ());
68
69   to_node = vlib_get_node (vm, to_node_index);
70
71   vec_validate (nm->frame_sizes, to_node->frame_size_index);
72   fs = vec_elt_at_index (nm->frame_sizes, to_node->frame_size_index);
73
74   if (fs->frame_size == 0)
75     fs->frame_size = to_node->frame_size;
76   else
77     ASSERT (fs->frame_size == to_node->frame_size);
78
79   n = fs->frame_size;
80   if ((l = vec_len (fs->free_frames)) > 0)
81     {
82       /* Allocate from end of free list. */
83       f = fs->free_frames[l - 1];
84       _vec_len (fs->free_frames) = l - 1;
85     }
86   else
87     {
88       f = clib_mem_alloc_aligned_no_fail (n, CLIB_CACHE_LINE_BYTES);
89     }
90
91   /* Poison frame when debugging. */
92   if (CLIB_DEBUG > 0)
93     clib_memset_u8 (f, 0xfe, n);
94
95   /* Insert magic number. */
96   {
97     u32 *magic;
98
99     magic = vlib_frame_find_magic (f, to_node);
100     *magic = VLIB_FRAME_MAGIC;
101   }
102
103   f->frame_flags = VLIB_FRAME_IS_ALLOCATED | frame_flags;
104   f->n_vectors = 0;
105   f->scalar_offset = to_node->scalar_offset;
106   f->vector_offset = to_node->vector_offset;
107   f->aux_offset = to_node->aux_offset;
108   f->flags = 0;
109
110   fs->n_alloc_frames += 1;
111
112   return f;
113 }
114
115 /* Allocate a frame for from FROM_NODE to TO_NODE via TO_NEXT_INDEX.
116    Returns frame index. */
117 static vlib_frame_t *
118 vlib_frame_alloc (vlib_main_t * vm, vlib_node_runtime_t * from_node_runtime,
119                   u32 to_next_index)
120 {
121   vlib_node_t *from_node;
122
123   from_node = vlib_get_node (vm, from_node_runtime->node_index);
124   ASSERT (to_next_index < vec_len (from_node->next_nodes));
125
126   return vlib_frame_alloc_to_node (vm, from_node->next_nodes[to_next_index],
127                                    /* frame_flags */ 0);
128 }
129
130 vlib_frame_t *
131 vlib_get_frame_to_node (vlib_main_t * vm, u32 to_node_index)
132 {
133   vlib_frame_t *f = vlib_frame_alloc_to_node (vm, to_node_index,
134                                               /* frame_flags */
135                                               VLIB_FRAME_FREE_AFTER_DISPATCH);
136   return vlib_get_frame (vm, f);
137 }
138
139 static inline void
140 vlib_validate_frame_indices (vlib_frame_t * f)
141 {
142   if (CLIB_DEBUG > 0)
143     {
144       int i;
145       u32 *from = vlib_frame_vector_args (f);
146
147       /* Check for bad buffer index values */
148       for (i = 0; i < f->n_vectors; i++)
149         {
150           if (from[i] == 0)
151             {
152               clib_warning ("BUG: buffer index 0 at index %d", i);
153               ASSERT (0);
154             }
155           else if (from[i] == 0xfefefefe)
156             {
157               clib_warning ("BUG: frame poison pattern at index %d", i);
158               ASSERT (0);
159             }
160         }
161     }
162 }
163
164 void
165 vlib_put_frame_to_node (vlib_main_t * vm, u32 to_node_index, vlib_frame_t * f)
166 {
167   vlib_pending_frame_t *p;
168   vlib_node_t *to_node;
169
170   if (f->n_vectors == 0)
171     return;
172
173   ASSERT (vm == vlib_get_main ());
174
175   vlib_validate_frame_indices (f);
176
177   to_node = vlib_get_node (vm, to_node_index);
178
179   vec_add2 (vm->node_main.pending_frames, p, 1);
180
181   f->frame_flags |= VLIB_FRAME_PENDING;
182   p->frame = vlib_get_frame (vm, f);
183   p->node_runtime_index = to_node->runtime_index;
184   p->next_frame_index = VLIB_PENDING_FRAME_NO_NEXT_FRAME;
185 }
186
187 /* Free given frame. */
188 void
189 vlib_frame_free (vlib_main_t * vm, vlib_node_runtime_t * r, vlib_frame_t * f)
190 {
191   vlib_node_main_t *nm = &vm->node_main;
192   vlib_node_t *node;
193   vlib_frame_size_t *fs;
194
195   ASSERT (vm == vlib_get_main ());
196   ASSERT (f->frame_flags & VLIB_FRAME_IS_ALLOCATED);
197
198   node = vlib_get_node (vm, r->node_index);
199   fs = vec_elt_at_index (nm->frame_sizes, node->frame_size_index);
200
201   ASSERT (f->frame_flags & VLIB_FRAME_IS_ALLOCATED);
202
203   /* No next frames may point to freed frame. */
204   if (CLIB_DEBUG > 0)
205     {
206       vlib_next_frame_t *nf;
207       vec_foreach (nf, vm->node_main.next_frames) ASSERT (nf->frame != f);
208     }
209
210   f->frame_flags &= ~(VLIB_FRAME_IS_ALLOCATED | VLIB_FRAME_NO_APPEND);
211
212   vec_add1 (fs->free_frames, f);
213   ASSERT (fs->n_alloc_frames > 0);
214   fs->n_alloc_frames -= 1;
215 }
216
217 static clib_error_t *
218 show_frame_stats (vlib_main_t * vm,
219                   unformat_input_t * input, vlib_cli_command_t * cmd)
220 {
221   vlib_frame_size_t *fs;
222
223   vlib_cli_output (vm, "%=8s%=6s%=12s%=12s", "Thread", "Size", "# Alloc",
224                    "# Free");
225   foreach_vlib_main ()
226     {
227       vlib_node_main_t *nm = &this_vlib_main->node_main;
228       vec_foreach (fs, nm->frame_sizes)
229         {
230           u32 n_alloc = fs->n_alloc_frames;
231           u32 n_free = vec_len (fs->free_frames);
232
233           if (n_alloc + n_free > 0)
234             vlib_cli_output (vm, "%=8d%=6d%=12d%=12d",
235                              this_vlib_main->thread_index, fs->frame_size,
236                              n_alloc, n_free);
237         }
238     }
239
240   return 0;
241 }
242
243 /* *INDENT-OFF* */
244 VLIB_CLI_COMMAND (show_frame_stats_cli, static) = {
245   .path = "show vlib frame-allocation",
246   .short_help = "Show node dispatch frame statistics",
247   .function = show_frame_stats,
248 };
249 /* *INDENT-ON* */
250
251 /* Change ownership of enqueue rights to given next node. */
252 static void
253 vlib_next_frame_change_ownership (vlib_main_t * vm,
254                                   vlib_node_runtime_t * node_runtime,
255                                   u32 next_index)
256 {
257   vlib_node_main_t *nm = &vm->node_main;
258   vlib_next_frame_t *next_frame;
259   vlib_node_t *node, *next_node;
260
261   node = vec_elt (nm->nodes, node_runtime->node_index);
262
263   /* Only internal & input nodes are allowed to call other nodes. */
264   ASSERT (node->type == VLIB_NODE_TYPE_INTERNAL
265           || node->type == VLIB_NODE_TYPE_INPUT
266           || node->type == VLIB_NODE_TYPE_PROCESS);
267
268   ASSERT (vec_len (node->next_nodes) == node_runtime->n_next_nodes);
269
270   next_frame =
271     vlib_node_runtime_get_next_frame (vm, node_runtime, next_index);
272   next_node = vec_elt (nm->nodes, node->next_nodes[next_index]);
273
274   if (next_node->owner_node_index != VLIB_INVALID_NODE_INDEX)
275     {
276       /* Get frame from previous owner. */
277       vlib_next_frame_t *owner_next_frame;
278       vlib_next_frame_t tmp;
279
280       owner_next_frame =
281         vlib_node_get_next_frame (vm,
282                                   next_node->owner_node_index,
283                                   next_node->owner_next_index);
284
285       /* Swap target next frame with owner's. */
286       tmp = owner_next_frame[0];
287       owner_next_frame[0] = next_frame[0];
288       next_frame[0] = tmp;
289
290       /*
291        * If next_frame is already pending, we have to track down
292        * all pending frames and fix their next_frame_index fields.
293        */
294       if (next_frame->flags & VLIB_FRAME_PENDING)
295         {
296           vlib_pending_frame_t *p;
297           if (next_frame->frame != NULL)
298             {
299               vec_foreach (p, nm->pending_frames)
300               {
301                 if (p->frame == next_frame->frame)
302                   {
303                     p->next_frame_index =
304                       next_frame - vm->node_main.next_frames;
305                   }
306               }
307             }
308         }
309     }
310   else
311     {
312       /* No previous owner. Take ownership. */
313       next_frame->flags |= VLIB_FRAME_OWNER;
314     }
315
316   /* Record new owner. */
317   next_node->owner_node_index = node->index;
318   next_node->owner_next_index = next_index;
319
320   /* Now we should be owner. */
321   ASSERT (next_frame->flags & VLIB_FRAME_OWNER);
322 }
323
324 /* Make sure that magic number is still there.
325    Otherwise, it is likely that caller has overrun frame arguments. */
326 always_inline void
327 validate_frame_magic (vlib_main_t * vm,
328                       vlib_frame_t * f, vlib_node_t * n, uword next_index)
329 {
330   vlib_node_t *next_node = vlib_get_node (vm, n->next_nodes[next_index]);
331   u32 *magic = vlib_frame_find_magic (f, next_node);
332   ASSERT (VLIB_FRAME_MAGIC == magic[0]);
333 }
334
335 vlib_frame_t *
336 vlib_get_next_frame_internal (vlib_main_t * vm,
337                               vlib_node_runtime_t * node,
338                               u32 next_index, u32 allocate_new_next_frame)
339 {
340   vlib_frame_t *f;
341   vlib_next_frame_t *nf;
342   u32 n_used;
343
344   nf = vlib_node_runtime_get_next_frame (vm, node, next_index);
345
346   /* Make sure this next frame owns right to enqueue to destination frame. */
347   if (PREDICT_FALSE (!(nf->flags & VLIB_FRAME_OWNER)))
348     vlib_next_frame_change_ownership (vm, node, next_index);
349
350   /* ??? Don't need valid flag: can use frame_index == ~0 */
351   if (PREDICT_FALSE (!(nf->flags & VLIB_FRAME_IS_ALLOCATED)))
352     {
353       nf->frame = vlib_frame_alloc (vm, node, next_index);
354       nf->flags |= VLIB_FRAME_IS_ALLOCATED;
355     }
356
357   f = nf->frame;
358
359   /* Has frame been removed from pending vector (e.g. finished dispatching)?
360      If so we can reuse frame. */
361   if ((nf->flags & VLIB_FRAME_PENDING)
362       && !(f->frame_flags & VLIB_FRAME_PENDING))
363     {
364       nf->flags &= ~VLIB_FRAME_PENDING;
365       f->n_vectors = 0;
366       f->flags = 0;
367     }
368
369   /* Allocate new frame if current one is marked as no-append or
370      it is already full. */
371   n_used = f->n_vectors;
372   if (n_used >= VLIB_FRAME_SIZE || (allocate_new_next_frame && n_used > 0) ||
373       (f->frame_flags & VLIB_FRAME_NO_APPEND))
374     {
375       /* Old frame may need to be freed after dispatch, since we'll have
376          two redundant frames from node -> next node. */
377       if (!(nf->flags & VLIB_FRAME_NO_FREE_AFTER_DISPATCH))
378         {
379           vlib_frame_t *f_old = vlib_get_frame (vm, nf->frame);
380           f_old->frame_flags |= VLIB_FRAME_FREE_AFTER_DISPATCH;
381         }
382
383       /* Allocate new frame to replace full one. */
384       f = nf->frame = vlib_frame_alloc (vm, node, next_index);
385       n_used = f->n_vectors;
386     }
387
388   /* Should have free vectors in frame now. */
389   ASSERT (n_used < VLIB_FRAME_SIZE);
390
391   if (CLIB_DEBUG > 0)
392     {
393       validate_frame_magic (vm, f,
394                             vlib_get_node (vm, node->node_index), next_index);
395     }
396
397   return f;
398 }
399
400 static void
401 vlib_put_next_frame_validate (vlib_main_t * vm,
402                               vlib_node_runtime_t * rt,
403                               u32 next_index, u32 n_vectors_left)
404 {
405   vlib_node_main_t *nm = &vm->node_main;
406   vlib_next_frame_t *nf;
407   vlib_frame_t *f;
408   vlib_node_runtime_t *next_rt;
409   vlib_node_t *next_node;
410   u32 n_before, n_after;
411
412   nf = vlib_node_runtime_get_next_frame (vm, rt, next_index);
413   f = vlib_get_frame (vm, nf->frame);
414
415   ASSERT (n_vectors_left <= VLIB_FRAME_SIZE);
416
417   vlib_validate_frame_indices (f);
418
419   n_after = VLIB_FRAME_SIZE - n_vectors_left;
420   n_before = f->n_vectors;
421
422   ASSERT (n_after >= n_before);
423
424   next_rt = vec_elt_at_index (nm->nodes_by_type[VLIB_NODE_TYPE_INTERNAL],
425                               nf->node_runtime_index);
426   next_node = vlib_get_node (vm, next_rt->node_index);
427   if (n_after > 0 && next_node->validate_frame)
428     {
429       u8 *msg = next_node->validate_frame (vm, rt, f);
430       if (msg)
431         {
432           clib_warning ("%v", msg);
433           ASSERT (0);
434         }
435       vec_free (msg);
436     }
437 }
438
439 void
440 vlib_put_next_frame (vlib_main_t * vm,
441                      vlib_node_runtime_t * r,
442                      u32 next_index, u32 n_vectors_left)
443 {
444   vlib_node_main_t *nm = &vm->node_main;
445   vlib_next_frame_t *nf;
446   vlib_frame_t *f;
447   u32 n_vectors_in_frame;
448
449   if (CLIB_DEBUG > 0)
450     vlib_put_next_frame_validate (vm, r, next_index, n_vectors_left);
451
452   nf = vlib_node_runtime_get_next_frame (vm, r, next_index);
453   f = vlib_get_frame (vm, nf->frame);
454
455   /* Make sure that magic number is still there.  Otherwise, caller
456      has overrun frame meta data. */
457   if (CLIB_DEBUG > 0)
458     {
459       vlib_node_t *node = vlib_get_node (vm, r->node_index);
460       validate_frame_magic (vm, f, node, next_index);
461     }
462
463   /* Convert # of vectors left -> number of vectors there. */
464   ASSERT (n_vectors_left <= VLIB_FRAME_SIZE);
465   n_vectors_in_frame = VLIB_FRAME_SIZE - n_vectors_left;
466
467   f->n_vectors = n_vectors_in_frame;
468
469   /* If vectors were added to frame, add to pending vector. */
470   if (PREDICT_TRUE (n_vectors_in_frame > 0))
471     {
472       vlib_pending_frame_t *p;
473       u32 v0, v1;
474
475       r->cached_next_index = next_index;
476
477       if (!(f->frame_flags & VLIB_FRAME_PENDING))
478         {
479           __attribute__ ((unused)) vlib_node_t *node;
480           vlib_node_t *next_node;
481           vlib_node_runtime_t *next_runtime;
482
483           node = vlib_get_node (vm, r->node_index);
484           next_node = vlib_get_next_node (vm, r->node_index, next_index);
485           next_runtime = vlib_node_get_runtime (vm, next_node->index);
486
487           vec_add2 (nm->pending_frames, p, 1);
488
489           p->frame = nf->frame;
490           p->node_runtime_index = nf->node_runtime_index;
491           p->next_frame_index = nf - nm->next_frames;
492           nf->flags |= VLIB_FRAME_PENDING;
493           f->frame_flags |= VLIB_FRAME_PENDING;
494
495           /*
496            * If we're going to dispatch this frame on another thread,
497            * force allocation of a new frame. Otherwise, we create
498            * a dangling frame reference. Each thread has its own copy of
499            * the next_frames vector.
500            */
501           if (0 && r->thread_index != next_runtime->thread_index)
502             {
503               nf->frame = NULL;
504               nf->flags &= ~(VLIB_FRAME_PENDING | VLIB_FRAME_IS_ALLOCATED);
505             }
506         }
507
508       /* Copy trace flag from next_frame and from runtime. */
509       nf->flags |=
510         (nf->flags & VLIB_NODE_FLAG_TRACE) | (r->
511                                               flags & VLIB_NODE_FLAG_TRACE);
512
513       v0 = nf->vectors_since_last_overflow;
514       v1 = v0 + n_vectors_in_frame;
515       nf->vectors_since_last_overflow = v1;
516       if (PREDICT_FALSE (v1 < v0))
517         {
518           vlib_node_t *node = vlib_get_node (vm, r->node_index);
519           vec_elt (node->n_vectors_by_next_node, next_index) += v0;
520         }
521     }
522 }
523
524 /* Sync up runtime (32 bit counters) and main node stats (64 bit counters). */
525 void
526 vlib_node_runtime_sync_stats_node (vlib_node_t *n, vlib_node_runtime_t *r,
527                                    uword n_calls, uword n_vectors,
528                                    uword n_clocks)
529 {
530   n->stats_total.calls += n_calls + r->calls_since_last_overflow;
531   n->stats_total.vectors += n_vectors + r->vectors_since_last_overflow;
532   n->stats_total.clocks += n_clocks + r->clocks_since_last_overflow;
533   n->stats_total.max_clock = r->max_clock;
534   n->stats_total.max_clock_n = r->max_clock_n;
535
536   r->calls_since_last_overflow = 0;
537   r->vectors_since_last_overflow = 0;
538   r->clocks_since_last_overflow = 0;
539 }
540
541 void
542 vlib_node_runtime_sync_stats (vlib_main_t *vm, vlib_node_runtime_t *r,
543                               uword n_calls, uword n_vectors, uword n_clocks)
544 {
545   vlib_node_t *n = vlib_get_node (vm, r->node_index);
546   vlib_node_runtime_sync_stats_node (n, r, n_calls, n_vectors, n_clocks);
547 }
548
549 always_inline void __attribute__ ((unused))
550 vlib_process_sync_stats (vlib_main_t * vm,
551                          vlib_process_t * p,
552                          uword n_calls, uword n_vectors, uword n_clocks)
553 {
554   vlib_node_runtime_t *rt = &p->node_runtime;
555   vlib_node_t *n = vlib_get_node (vm, rt->node_index);
556   vlib_node_runtime_sync_stats (vm, rt, n_calls, n_vectors, n_clocks);
557   n->stats_total.suspends += p->n_suspends;
558   p->n_suspends = 0;
559 }
560
561 void
562 vlib_node_sync_stats (vlib_main_t * vm, vlib_node_t * n)
563 {
564   vlib_node_runtime_t *rt;
565
566   if (n->type == VLIB_NODE_TYPE_PROCESS)
567     {
568       /* Nothing to do for PROCESS nodes except in main thread */
569       if (vm != vlib_get_first_main ())
570         return;
571
572       vlib_process_t *p = vlib_get_process_from_node (vm, n);
573       n->stats_total.suspends += p->n_suspends;
574       p->n_suspends = 0;
575       rt = &p->node_runtime;
576     }
577   else
578     rt =
579       vec_elt_at_index (vm->node_main.nodes_by_type[n->type],
580                         n->runtime_index);
581
582   vlib_node_runtime_sync_stats (vm, rt, 0, 0, 0);
583
584   /* Sync up runtime next frame vector counters with main node structure. */
585   {
586     vlib_next_frame_t *nf;
587     uword i;
588     for (i = 0; i < rt->n_next_nodes; i++)
589       {
590         nf = vlib_node_runtime_get_next_frame (vm, rt, i);
591         vec_elt (n->n_vectors_by_next_node, i) +=
592           nf->vectors_since_last_overflow;
593         nf->vectors_since_last_overflow = 0;
594       }
595   }
596 }
597
598 always_inline u32
599 vlib_node_runtime_update_stats (vlib_main_t * vm,
600                                 vlib_node_runtime_t * node,
601                                 uword n_calls,
602                                 uword n_vectors, uword n_clocks)
603 {
604   u32 ca0, ca1, v0, v1, cl0, cl1, r;
605
606   cl0 = cl1 = node->clocks_since_last_overflow;
607   ca0 = ca1 = node->calls_since_last_overflow;
608   v0 = v1 = node->vectors_since_last_overflow;
609
610   ca1 = ca0 + n_calls;
611   v1 = v0 + n_vectors;
612   cl1 = cl0 + n_clocks;
613
614   node->calls_since_last_overflow = ca1;
615   node->clocks_since_last_overflow = cl1;
616   node->vectors_since_last_overflow = v1;
617
618   node->max_clock_n = node->max_clock > n_clocks ?
619     node->max_clock_n : n_vectors;
620   node->max_clock = node->max_clock > n_clocks ? node->max_clock : n_clocks;
621
622   r = vlib_node_runtime_update_main_loop_vector_stats (vm, node, n_vectors);
623
624   if (PREDICT_FALSE (ca1 < ca0 || v1 < v0 || cl1 < cl0))
625     {
626       node->calls_since_last_overflow = ca0;
627       node->clocks_since_last_overflow = cl0;
628       node->vectors_since_last_overflow = v0;
629
630       vlib_node_runtime_sync_stats (vm, node, n_calls, n_vectors, n_clocks);
631     }
632
633   return r;
634 }
635
636 always_inline void
637 vlib_process_update_stats (vlib_main_t * vm,
638                            vlib_process_t * p,
639                            uword n_calls, uword n_vectors, uword n_clocks)
640 {
641   vlib_node_runtime_update_stats (vm, &p->node_runtime,
642                                   n_calls, n_vectors, n_clocks);
643 }
644
645 static clib_error_t *
646 vlib_cli_elog_clear (vlib_main_t * vm,
647                      unformat_input_t * input, vlib_cli_command_t * cmd)
648 {
649   elog_reset_buffer (&vlib_global_main.elog_main);
650   return 0;
651 }
652
653 /* *INDENT-OFF* */
654 VLIB_CLI_COMMAND (elog_clear_cli, static) = {
655   .path = "event-logger clear",
656   .short_help = "Clear the event log",
657   .function = vlib_cli_elog_clear,
658 };
659 /* *INDENT-ON* */
660
661 #ifdef CLIB_UNIX
662 static clib_error_t *
663 elog_save_buffer (vlib_main_t * vm,
664                   unformat_input_t * input, vlib_cli_command_t * cmd)
665 {
666   elog_main_t *em = &vlib_global_main.elog_main;
667   char *file, *chroot_file;
668   clib_error_t *error = 0;
669
670   if (!unformat (input, "%s", &file))
671     {
672       vlib_cli_output (vm, "expected file name, got `%U'",
673                        format_unformat_error, input);
674       return 0;
675     }
676
677   /* It's fairly hard to get "../oopsie" through unformat; just in case */
678   if (strstr (file, "..") || index (file, '/'))
679     {
680       vlib_cli_output (vm, "illegal characters in filename '%s'", file);
681       return 0;
682     }
683
684   chroot_file = (char *) format (0, "/tmp/%s%c", file, 0);
685
686   vec_free (file);
687
688   vlib_cli_output (vm, "Saving %wd of %wd events to %s",
689                    elog_n_events_in_buffer (em),
690                    elog_buffer_capacity (em), chroot_file);
691
692   vlib_worker_thread_barrier_sync (vm);
693   error = elog_write_file (em, chroot_file, 1 /* flush ring */ );
694   vlib_worker_thread_barrier_release (vm);
695   vec_free (chroot_file);
696   return error;
697 }
698
699 void
700 vlib_post_mortem_dump (void)
701 {
702   vlib_global_main_t *vgm = vlib_get_global_main ();
703
704   for (int i = 0; i < vec_len (vgm->post_mortem_callbacks); i++)
705     (vgm->post_mortem_callbacks[i]) ();
706 }
707
708 /* *INDENT-OFF* */
709 VLIB_CLI_COMMAND (elog_save_cli, static) = {
710   .path = "event-logger save",
711   .short_help = "event-logger save <filename> (saves log in /tmp/<filename>)",
712   .function = elog_save_buffer,
713 };
714 /* *INDENT-ON* */
715
716 static clib_error_t *
717 elog_stop (vlib_main_t * vm,
718            unformat_input_t * input, vlib_cli_command_t * cmd)
719 {
720   elog_main_t *em = &vlib_global_main.elog_main;
721
722   em->n_total_events_disable_limit = em->n_total_events;
723
724   vlib_cli_output (vm, "Stopped the event logger...");
725   return 0;
726 }
727
728 /* *INDENT-OFF* */
729 VLIB_CLI_COMMAND (elog_stop_cli, static) = {
730   .path = "event-logger stop",
731   .short_help = "Stop the event-logger",
732   .function = elog_stop,
733 };
734 /* *INDENT-ON* */
735
736 static clib_error_t *
737 elog_restart (vlib_main_t * vm,
738               unformat_input_t * input, vlib_cli_command_t * cmd)
739 {
740   elog_main_t *em = &vlib_global_main.elog_main;
741
742   em->n_total_events_disable_limit = ~0;
743
744   vlib_cli_output (vm, "Restarted the event logger...");
745   return 0;
746 }
747
748 /* *INDENT-OFF* */
749 VLIB_CLI_COMMAND (elog_restart_cli, static) = {
750   .path = "event-logger restart",
751   .short_help = "Restart the event-logger",
752   .function = elog_restart,
753 };
754 /* *INDENT-ON* */
755
756 static clib_error_t *
757 elog_resize_command_fn (vlib_main_t * vm,
758                         unformat_input_t * input, vlib_cli_command_t * cmd)
759 {
760   elog_main_t *em = &vlib_global_main.elog_main;
761   u32 tmp;
762
763   /* Stop the parade */
764   elog_reset_buffer (em);
765
766   if (unformat (input, "%d", &tmp))
767     {
768       elog_alloc (em, tmp);
769       em->n_total_events_disable_limit = ~0;
770     }
771   else
772     return clib_error_return (0, "Must specify how many events in the ring");
773
774   vlib_cli_output (vm, "Resized ring and restarted the event logger...");
775   return 0;
776 }
777
778 /* *INDENT-OFF* */
779 VLIB_CLI_COMMAND (elog_resize_cli, static) = {
780   .path = "event-logger resize",
781   .short_help = "event-logger resize <nnn>",
782   .function = elog_resize_command_fn,
783 };
784 /* *INDENT-ON* */
785
786 #endif /* CLIB_UNIX */
787
788 static void
789 elog_show_buffer_internal (vlib_main_t * vm, u32 n_events_to_show)
790 {
791   elog_main_t *em = &vlib_global_main.elog_main;
792   elog_event_t *e, *es;
793   f64 dt;
794
795   /* Show events in VLIB time since log clock starts after VLIB clock. */
796   dt = (em->init_time.cpu - vm->clib_time.init_cpu_time)
797     * vm->clib_time.seconds_per_clock;
798
799   es = elog_peek_events (em);
800   vlib_cli_output (vm, "%d of %d events in buffer, logger %s", vec_len (es),
801                    em->event_ring_size,
802                    em->n_total_events < em->n_total_events_disable_limit ?
803                    "running" : "stopped");
804   vec_foreach (e, es)
805   {
806     vlib_cli_output (vm, "%18.9f: %U",
807                      e->time + dt, format_elog_event, em, e);
808     n_events_to_show--;
809     if (n_events_to_show == 0)
810       break;
811   }
812   vec_free (es);
813
814 }
815
816 static clib_error_t *
817 elog_show_buffer (vlib_main_t * vm,
818                   unformat_input_t * input, vlib_cli_command_t * cmd)
819 {
820   u32 n_events_to_show;
821   clib_error_t *error = 0;
822
823   n_events_to_show = 250;
824   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
825     {
826       if (unformat (input, "%d", &n_events_to_show))
827         ;
828       else if (unformat (input, "all"))
829         n_events_to_show = ~0;
830       else
831         return unformat_parse_error (input);
832     }
833   elog_show_buffer_internal (vm, n_events_to_show);
834   return error;
835 }
836
837 /* *INDENT-OFF* */
838 VLIB_CLI_COMMAND (elog_show_cli, static) = {
839   .path = "show event-logger",
840   .short_help = "Show event logger info",
841   .function = elog_show_buffer,
842 };
843 /* *INDENT-ON* */
844
845 void
846 vlib_gdb_show_event_log (void)
847 {
848   elog_show_buffer_internal (vlib_get_main (), (u32) ~ 0);
849 }
850
851 static inline void
852 vlib_elog_main_loop_event (vlib_main_t * vm,
853                            u32 node_index,
854                            u64 time, u32 n_vectors, u32 is_return)
855 {
856   vlib_main_t *evm = vlib_get_first_main ();
857   elog_main_t *em = vlib_get_elog_main ();
858   int enabled = evm->elog_trace_graph_dispatch |
859     evm->elog_trace_graph_circuit;
860
861   if (PREDICT_FALSE (enabled && n_vectors))
862     {
863       if (PREDICT_FALSE (!elog_is_enabled (em)))
864         {
865           evm->elog_trace_graph_dispatch = 0;
866           evm->elog_trace_graph_circuit = 0;
867           return;
868         }
869       if (PREDICT_TRUE
870           (evm->elog_trace_graph_dispatch ||
871            (evm->elog_trace_graph_circuit &&
872             node_index == evm->elog_trace_graph_circuit_node_index)))
873         {
874           elog_track (em,
875                       /* event type */
876                       vec_elt_at_index (is_return
877                                         ? evm->node_return_elog_event_types
878                                         : evm->node_call_elog_event_types,
879                                         node_index),
880                       /* track */
881                       (vm->thread_index ?
882                        &vlib_worker_threads[vm->thread_index].elog_track
883                        : &em->default_track),
884                       /* data to log */ n_vectors);
885         }
886     }
887 }
888
889 static inline void
890 add_trajectory_trace (vlib_buffer_t * b, u32 node_index)
891 {
892 #if VLIB_BUFFER_TRACE_TRAJECTORY > 0
893   if (PREDICT_FALSE (b->trajectory_nb >= VLIB_BUFFER_TRACE_TRAJECTORY_MAX))
894     return;
895   b->trajectory_trace[b->trajectory_nb] = node_index;
896   b->trajectory_nb++;
897 #endif
898 }
899
900 static_always_inline u64
901 dispatch_node (vlib_main_t * vm,
902                vlib_node_runtime_t * node,
903                vlib_node_type_t type,
904                vlib_node_state_t dispatch_state,
905                vlib_frame_t * frame, u64 last_time_stamp)
906 {
907   uword n, v;
908   u64 t;
909   vlib_node_main_t *nm = &vm->node_main;
910   vlib_next_frame_t *nf;
911
912   if (CLIB_DEBUG > 0)
913     {
914       vlib_node_t *n = vlib_get_node (vm, node->node_index);
915       ASSERT (n->type == type);
916     }
917
918   /* Only non-internal nodes may be disabled. */
919   if (type != VLIB_NODE_TYPE_INTERNAL && node->state != dispatch_state)
920     {
921       ASSERT (type != VLIB_NODE_TYPE_INTERNAL);
922       return last_time_stamp;
923     }
924
925   if ((type == VLIB_NODE_TYPE_PRE_INPUT || type == VLIB_NODE_TYPE_INPUT)
926       && dispatch_state != VLIB_NODE_STATE_INTERRUPT)
927     {
928       u32 c = node->input_main_loops_per_call;
929       /* Only call node when count reaches zero. */
930       if (c)
931         {
932           node->input_main_loops_per_call = c - 1;
933           return last_time_stamp;
934         }
935     }
936
937   /* Speculatively prefetch next frames. */
938   if (node->n_next_nodes > 0)
939     {
940       nf = vec_elt_at_index (nm->next_frames, node->next_frame_index);
941       CLIB_PREFETCH (nf, 4 * sizeof (nf[0]), WRITE);
942     }
943
944   vm->cpu_time_last_node_dispatch = last_time_stamp;
945
946   vlib_elog_main_loop_event (vm, node->node_index,
947                              last_time_stamp, frame ? frame->n_vectors : 0,
948                              /* is_after */ 0);
949
950   vlib_node_runtime_perf_counter (vm, node, frame, 0, last_time_stamp,
951                                   VLIB_NODE_RUNTIME_PERF_BEFORE);
952
953   /*
954    * Turn this on if you run into
955    * "bad monkey" contexts, and you want to know exactly
956    * which nodes they've visited... See ixge.c...
957    */
958   if (VLIB_BUFFER_TRACE_TRAJECTORY && frame)
959     {
960       int i;
961       u32 *from;
962       from = vlib_frame_vector_args (frame);
963       for (i = 0; i < frame->n_vectors; i++)
964         {
965           vlib_buffer_t *b = vlib_get_buffer (vm, from[i]);
966           add_trajectory_trace (b, node->node_index);
967         }
968       if (PREDICT_TRUE (vm->dispatch_wrapper_fn == 0))
969         n = node->function (vm, node, frame);
970       else
971         n = vm->dispatch_wrapper_fn (vm, node, frame);
972     }
973   else
974     {
975       if (PREDICT_TRUE (vm->dispatch_wrapper_fn == 0))
976         n = node->function (vm, node, frame);
977       else
978         n = vm->dispatch_wrapper_fn (vm, node, frame);
979     }
980
981   t = clib_cpu_time_now ();
982
983   vlib_node_runtime_perf_counter (vm, node, frame, n, t,
984                                   VLIB_NODE_RUNTIME_PERF_AFTER);
985
986   vlib_elog_main_loop_event (vm, node->node_index, t, n, 1 /* is_after */ );
987
988   vm->main_loop_vectors_processed += n;
989   vm->main_loop_nodes_processed += n > 0;
990
991   v = vlib_node_runtime_update_stats (vm, node,
992                                       /* n_calls */ 1,
993                                       /* n_vectors */ n,
994                                       /* n_clocks */ t - last_time_stamp);
995
996   /* When in adaptive mode and vector rate crosses threshold switch to
997      polling mode and vice versa. */
998   if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_ADAPTIVE_MODE))
999     {
1000       /* *INDENT-OFF* */
1001       ELOG_TYPE_DECLARE (e) =
1002         {
1003           .function = (char *) __FUNCTION__,
1004           .format = "%s vector length %d, switching to %s",
1005           .format_args = "T4i4t4",
1006           .n_enum_strings = 2,
1007           .enum_strings = {
1008             "interrupt", "polling",
1009           },
1010         };
1011       /* *INDENT-ON* */
1012       struct
1013       {
1014         u32 node_name, vector_length, is_polling;
1015       } *ed;
1016
1017       if ((dispatch_state == VLIB_NODE_STATE_INTERRUPT
1018            && v >= nm->polling_threshold_vector_length) &&
1019           !(node->flags &
1020             VLIB_NODE_FLAG_SWITCH_FROM_INTERRUPT_TO_POLLING_MODE))
1021         {
1022           vlib_node_t *n = vlib_get_node (vm, node->node_index);
1023           n->state = VLIB_NODE_STATE_POLLING;
1024           node->state = VLIB_NODE_STATE_POLLING;
1025           node->flags &=
1026             ~VLIB_NODE_FLAG_SWITCH_FROM_POLLING_TO_INTERRUPT_MODE;
1027           node->flags |= VLIB_NODE_FLAG_SWITCH_FROM_INTERRUPT_TO_POLLING_MODE;
1028           nm->input_node_counts_by_state[VLIB_NODE_STATE_INTERRUPT] -= 1;
1029           nm->input_node_counts_by_state[VLIB_NODE_STATE_POLLING] += 1;
1030
1031           if (PREDICT_FALSE (
1032                 vlib_get_first_main ()->elog_trace_graph_dispatch))
1033             {
1034               vlib_worker_thread_t *w = vlib_worker_threads
1035                 + vm->thread_index;
1036
1037               ed = ELOG_TRACK_DATA (&vlib_global_main.elog_main, e,
1038                                     w->elog_track);
1039               ed->node_name = n->name_elog_string;
1040               ed->vector_length = v;
1041               ed->is_polling = 1;
1042             }
1043         }
1044       else if (dispatch_state == VLIB_NODE_STATE_POLLING
1045                && v <= nm->interrupt_threshold_vector_length)
1046         {
1047           vlib_node_t *n = vlib_get_node (vm, node->node_index);
1048           if (node->flags &
1049               VLIB_NODE_FLAG_SWITCH_FROM_POLLING_TO_INTERRUPT_MODE)
1050             {
1051               /* Switch to interrupt mode after dispatch in polling one more time.
1052                  This allows driver to re-enable interrupts. */
1053               n->state = VLIB_NODE_STATE_INTERRUPT;
1054               node->state = VLIB_NODE_STATE_INTERRUPT;
1055               node->flags &=
1056                 ~VLIB_NODE_FLAG_SWITCH_FROM_INTERRUPT_TO_POLLING_MODE;
1057               nm->input_node_counts_by_state[VLIB_NODE_STATE_POLLING] -= 1;
1058               nm->input_node_counts_by_state[VLIB_NODE_STATE_INTERRUPT] += 1;
1059
1060             }
1061           else
1062             {
1063               vlib_worker_thread_t *w = vlib_worker_threads
1064                 + vm->thread_index;
1065               node->flags |=
1066                 VLIB_NODE_FLAG_SWITCH_FROM_POLLING_TO_INTERRUPT_MODE;
1067               if (PREDICT_FALSE (
1068                     vlib_get_first_main ()->elog_trace_graph_dispatch))
1069                 {
1070                   ed = ELOG_TRACK_DATA (&vlib_global_main.elog_main, e,
1071                                         w->elog_track);
1072                   ed->node_name = n->name_elog_string;
1073                   ed->vector_length = v;
1074                   ed->is_polling = 0;
1075                 }
1076             }
1077         }
1078     }
1079
1080   return t;
1081 }
1082
1083 static u64
1084 dispatch_pending_node (vlib_main_t * vm, uword pending_frame_index,
1085                        u64 last_time_stamp)
1086 {
1087   vlib_node_main_t *nm = &vm->node_main;
1088   vlib_frame_t *f;
1089   vlib_next_frame_t *nf, nf_placeholder;
1090   vlib_node_runtime_t *n;
1091   vlib_frame_t *restore_frame;
1092   vlib_pending_frame_t *p;
1093
1094   /* See comment below about dangling references to nm->pending_frames */
1095   p = nm->pending_frames + pending_frame_index;
1096
1097   n = vec_elt_at_index (nm->nodes_by_type[VLIB_NODE_TYPE_INTERNAL],
1098                         p->node_runtime_index);
1099
1100   f = vlib_get_frame (vm, p->frame);
1101   if (p->next_frame_index == VLIB_PENDING_FRAME_NO_NEXT_FRAME)
1102     {
1103       /* No next frame: so use placeholder on stack. */
1104       nf = &nf_placeholder;
1105       nf->flags = f->frame_flags & VLIB_NODE_FLAG_TRACE;
1106       nf->frame = NULL;
1107     }
1108   else
1109     nf = vec_elt_at_index (nm->next_frames, p->next_frame_index);
1110
1111   ASSERT (f->frame_flags & VLIB_FRAME_IS_ALLOCATED);
1112
1113   /* Force allocation of new frame while current frame is being
1114      dispatched. */
1115   restore_frame = NULL;
1116   if (nf->frame == p->frame)
1117     {
1118       nf->frame = NULL;
1119       nf->flags &= ~VLIB_FRAME_IS_ALLOCATED;
1120       if (!(n->flags & VLIB_NODE_FLAG_FRAME_NO_FREE_AFTER_DISPATCH))
1121         restore_frame = p->frame;
1122     }
1123
1124   /* Frame must be pending. */
1125   ASSERT (f->frame_flags & VLIB_FRAME_PENDING);
1126   ASSERT (f->n_vectors > 0);
1127
1128   /* Copy trace flag from next frame to node.
1129      Trace flag indicates that at least one vector in the dispatched
1130      frame is traced. */
1131   n->flags &= ~VLIB_NODE_FLAG_TRACE;
1132   n->flags |= (nf->flags & VLIB_FRAME_TRACE) ? VLIB_NODE_FLAG_TRACE : 0;
1133   nf->flags &= ~VLIB_FRAME_TRACE;
1134
1135   last_time_stamp = dispatch_node (vm, n,
1136                                    VLIB_NODE_TYPE_INTERNAL,
1137                                    VLIB_NODE_STATE_POLLING,
1138                                    f, last_time_stamp);
1139   /* Internal node vector-rate accounting, for summary stats */
1140   vm->internal_node_vectors += f->n_vectors;
1141   vm->internal_node_calls++;
1142   vm->internal_node_last_vectors_per_main_loop =
1143     (f->n_vectors > vm->internal_node_last_vectors_per_main_loop) ?
1144     f->n_vectors : vm->internal_node_last_vectors_per_main_loop;
1145
1146   f->frame_flags &= ~(VLIB_FRAME_PENDING | VLIB_FRAME_NO_APPEND);
1147
1148   /* Frame is ready to be used again, so restore it. */
1149   if (restore_frame != NULL)
1150     {
1151       /*
1152        * We musn't restore a frame that is flagged to be freed. This
1153        * shouldn't happen since frames to be freed post dispatch are
1154        * those used when the to-node frame becomes full i.e. they form a
1155        * sort of queue of frames to a single node. If we get here then
1156        * the to-node frame and the pending frame *were* the same, and so
1157        * we removed the to-node frame.  Therefore this frame is no
1158        * longer part of the queue for that node and hence it cannot be
1159        * it's overspill.
1160        */
1161       ASSERT (!(f->frame_flags & VLIB_FRAME_FREE_AFTER_DISPATCH));
1162
1163       /*
1164        * NB: dispatching node n can result in the creation and scheduling
1165        * of new frames, and hence in the reallocation of nm->pending_frames.
1166        * Recompute p, or no supper. This was broken for more than 10 years.
1167        */
1168       p = nm->pending_frames + pending_frame_index;
1169
1170       /*
1171        * p->next_frame_index can change during node dispatch if node
1172        * function decides to change graph hook up.
1173        */
1174       nf = vec_elt_at_index (nm->next_frames, p->next_frame_index);
1175       nf->flags |= VLIB_FRAME_IS_ALLOCATED;
1176
1177       if (NULL == nf->frame)
1178         {
1179           /* no new frame has been assigned to this node, use the saved one */
1180           nf->frame = restore_frame;
1181           f->n_vectors = 0;
1182         }
1183       else
1184         {
1185           /* The node has gained a frame, implying packets from the current frame
1186              were re-queued to this same node. we don't need the saved one
1187              anymore */
1188           vlib_frame_free (vm, n, f);
1189         }
1190     }
1191   else
1192     {
1193       if (f->frame_flags & VLIB_FRAME_FREE_AFTER_DISPATCH)
1194         {
1195           ASSERT (!(n->flags & VLIB_NODE_FLAG_FRAME_NO_FREE_AFTER_DISPATCH));
1196           vlib_frame_free (vm, n, f);
1197         }
1198     }
1199
1200   return last_time_stamp;
1201 }
1202
1203 always_inline uword
1204 vlib_process_stack_is_valid (vlib_process_t * p)
1205 {
1206   return p->stack[0] == VLIB_PROCESS_STACK_MAGIC;
1207 }
1208
1209 typedef struct
1210 {
1211   vlib_main_t *vm;
1212   vlib_process_t *process;
1213   vlib_frame_t *frame;
1214 } vlib_process_bootstrap_args_t;
1215
1216 /* Called in process stack. */
1217 static uword
1218 vlib_process_bootstrap (uword _a)
1219 {
1220   vlib_process_bootstrap_args_t *a;
1221   vlib_main_t *vm;
1222   vlib_node_runtime_t *node;
1223   vlib_frame_t *f;
1224   vlib_process_t *p;
1225   uword n;
1226
1227   a = uword_to_pointer (_a, vlib_process_bootstrap_args_t *);
1228
1229   vm = a->vm;
1230   p = a->process;
1231   vlib_process_finish_switch_stack (vm);
1232
1233   f = a->frame;
1234   node = &p->node_runtime;
1235
1236   n = node->function (vm, node, f);
1237
1238   ASSERT (vlib_process_stack_is_valid (p));
1239
1240   vlib_process_start_switch_stack (vm, 0);
1241   clib_longjmp (&p->return_longjmp, n);
1242
1243   return n;
1244 }
1245
1246 /* Called in main stack. */
1247 static_always_inline uword
1248 vlib_process_startup (vlib_main_t * vm, vlib_process_t * p, vlib_frame_t * f)
1249 {
1250   vlib_process_bootstrap_args_t a;
1251   uword r;
1252
1253   a.vm = vm;
1254   a.process = p;
1255   a.frame = f;
1256
1257   r = clib_setjmp (&p->return_longjmp, VLIB_PROCESS_RETURN_LONGJMP_RETURN);
1258   if (r == VLIB_PROCESS_RETURN_LONGJMP_RETURN)
1259     {
1260       vlib_process_start_switch_stack (vm, p);
1261       r = clib_calljmp (vlib_process_bootstrap, pointer_to_uword (&a),
1262                         (void *) p->stack + (1 << p->log2_n_stack_bytes));
1263     }
1264   else
1265     vlib_process_finish_switch_stack (vm);
1266
1267   return r;
1268 }
1269
1270 static_always_inline uword
1271 vlib_process_resume (vlib_main_t * vm, vlib_process_t * p)
1272 {
1273   uword r;
1274   p->flags &= ~(VLIB_PROCESS_IS_SUSPENDED_WAITING_FOR_CLOCK
1275                 | VLIB_PROCESS_IS_SUSPENDED_WAITING_FOR_EVENT
1276                 | VLIB_PROCESS_RESUME_PENDING);
1277   r = clib_setjmp (&p->return_longjmp, VLIB_PROCESS_RETURN_LONGJMP_RETURN);
1278   if (r == VLIB_PROCESS_RETURN_LONGJMP_RETURN)
1279     {
1280       vlib_process_start_switch_stack (vm, p);
1281       clib_longjmp (&p->resume_longjmp, VLIB_PROCESS_RESUME_LONGJMP_RESUME);
1282     }
1283   else
1284     vlib_process_finish_switch_stack (vm);
1285   return r;
1286 }
1287
1288 static u64
1289 dispatch_process (vlib_main_t * vm,
1290                   vlib_process_t * p, vlib_frame_t * f, u64 last_time_stamp)
1291 {
1292   vlib_node_main_t *nm = &vm->node_main;
1293   vlib_node_runtime_t *node_runtime = &p->node_runtime;
1294   vlib_node_t *node = vlib_get_node (vm, node_runtime->node_index);
1295   u32 old_process_index;
1296   u64 t;
1297   uword n_vectors, is_suspend;
1298
1299   if (node->state != VLIB_NODE_STATE_POLLING
1300       || (p->flags & (VLIB_PROCESS_IS_SUSPENDED_WAITING_FOR_CLOCK
1301                       | VLIB_PROCESS_IS_SUSPENDED_WAITING_FOR_EVENT)))
1302     return last_time_stamp;
1303
1304   p->flags |= VLIB_PROCESS_IS_RUNNING;
1305
1306   t = last_time_stamp;
1307   vlib_elog_main_loop_event (vm, node_runtime->node_index, t,
1308                              f ? f->n_vectors : 0, /* is_after */ 0);
1309
1310   /* Save away current process for suspend. */
1311   old_process_index = nm->current_process_index;
1312   nm->current_process_index = node->runtime_index;
1313
1314   vlib_node_runtime_perf_counter (vm, node_runtime, f, 0, last_time_stamp,
1315                                   VLIB_NODE_RUNTIME_PERF_BEFORE);
1316
1317   n_vectors = vlib_process_startup (vm, p, f);
1318
1319   nm->current_process_index = old_process_index;
1320
1321   ASSERT (n_vectors != VLIB_PROCESS_RETURN_LONGJMP_RETURN);
1322   is_suspend = n_vectors == VLIB_PROCESS_RETURN_LONGJMP_SUSPEND;
1323   if (is_suspend)
1324     {
1325       vlib_pending_frame_t *pf;
1326
1327       n_vectors = 0;
1328       pool_get (nm->suspended_process_frames, pf);
1329       pf->node_runtime_index = node->runtime_index;
1330       pf->frame = f;
1331       pf->next_frame_index = ~0;
1332
1333       p->n_suspends += 1;
1334       p->suspended_process_frame_index = pf - nm->suspended_process_frames;
1335
1336       if (p->flags & VLIB_PROCESS_IS_SUSPENDED_WAITING_FOR_CLOCK)
1337         {
1338           TWT (tw_timer_wheel) * tw =
1339             (TWT (tw_timer_wheel) *) nm->timing_wheel;
1340           p->stop_timer_handle =
1341             TW (tw_timer_start) (tw,
1342                                  vlib_timing_wheel_data_set_suspended_process
1343                                  (node->runtime_index) /* [sic] pool idex */ ,
1344                                  0 /* timer_id */ ,
1345                                  p->resume_clock_interval);
1346         }
1347     }
1348   else
1349     p->flags &= ~VLIB_PROCESS_IS_RUNNING;
1350
1351   t = clib_cpu_time_now ();
1352
1353   vlib_elog_main_loop_event (vm, node_runtime->node_index, t, is_suspend,
1354                              /* is_after */ 1);
1355
1356   vlib_node_runtime_perf_counter (vm, node_runtime, f, n_vectors, t,
1357                                   VLIB_NODE_RUNTIME_PERF_AFTER);
1358
1359   vlib_process_update_stats (vm, p,
1360                              /* n_calls */ !is_suspend,
1361                              /* n_vectors */ n_vectors,
1362                              /* n_clocks */ t - last_time_stamp);
1363
1364   return t;
1365 }
1366
1367 void
1368 vlib_start_process (vlib_main_t * vm, uword process_index)
1369 {
1370   vlib_node_main_t *nm = &vm->node_main;
1371   vlib_process_t *p = vec_elt (nm->processes, process_index);
1372   dispatch_process (vm, p, /* frame */ 0, /* cpu_time_now */ 0);
1373 }
1374
1375 static u64
1376 dispatch_suspended_process (vlib_main_t * vm,
1377                             uword process_index, u64 last_time_stamp)
1378 {
1379   vlib_node_main_t *nm = &vm->node_main;
1380   vlib_node_runtime_t *node_runtime;
1381   vlib_node_t *node;
1382   vlib_frame_t *f;
1383   vlib_process_t *p;
1384   vlib_pending_frame_t *pf;
1385   u64 t, n_vectors, is_suspend;
1386
1387   t = last_time_stamp;
1388
1389   p = vec_elt (nm->processes, process_index);
1390   if (PREDICT_FALSE (!(p->flags & VLIB_PROCESS_IS_RUNNING)))
1391     return last_time_stamp;
1392
1393   ASSERT (p->flags & (VLIB_PROCESS_IS_SUSPENDED_WAITING_FOR_CLOCK
1394                       | VLIB_PROCESS_IS_SUSPENDED_WAITING_FOR_EVENT));
1395
1396   pf = pool_elt_at_index (nm->suspended_process_frames,
1397                           p->suspended_process_frame_index);
1398
1399   node_runtime = &p->node_runtime;
1400   node = vlib_get_node (vm, node_runtime->node_index);
1401   f = pf->frame;
1402
1403   vlib_elog_main_loop_event (vm, node_runtime->node_index, t,
1404                              f ? f->n_vectors : 0, /* is_after */ 0);
1405
1406   /* Save away current process for suspend. */
1407   nm->current_process_index = node->runtime_index;
1408
1409   vlib_node_runtime_perf_counter (vm, node_runtime, f, 0, last_time_stamp,
1410                                   VLIB_NODE_RUNTIME_PERF_BEFORE);
1411
1412   n_vectors = vlib_process_resume (vm, p);
1413   t = clib_cpu_time_now ();
1414
1415   nm->current_process_index = ~0;
1416
1417   is_suspend = n_vectors == VLIB_PROCESS_RETURN_LONGJMP_SUSPEND;
1418   if (is_suspend)
1419     {
1420       /* Suspend it again. */
1421       n_vectors = 0;
1422       p->n_suspends += 1;
1423       if (p->flags & VLIB_PROCESS_IS_SUSPENDED_WAITING_FOR_CLOCK)
1424         {
1425           p->stop_timer_handle =
1426             TW (tw_timer_start) ((TWT (tw_timer_wheel) *) nm->timing_wheel,
1427                                  vlib_timing_wheel_data_set_suspended_process
1428                                  (node->runtime_index) /* [sic] pool idex */ ,
1429                                  0 /* timer_id */ ,
1430                                  p->resume_clock_interval);
1431         }
1432     }
1433   else
1434     {
1435       p->flags &= ~VLIB_PROCESS_IS_RUNNING;
1436       pool_put_index (nm->suspended_process_frames,
1437                       p->suspended_process_frame_index);
1438       p->suspended_process_frame_index = ~0;
1439     }
1440
1441   t = clib_cpu_time_now ();
1442   vlib_elog_main_loop_event (vm, node_runtime->node_index, t, !is_suspend,
1443                              /* is_after */ 1);
1444
1445   vlib_node_runtime_perf_counter (vm, node_runtime, f, n_vectors, t,
1446                                   VLIB_NODE_RUNTIME_PERF_AFTER);
1447
1448   vlib_process_update_stats (vm, p,
1449                              /* n_calls */ !is_suspend,
1450                              /* n_vectors */ n_vectors,
1451                              /* n_clocks */ t - last_time_stamp);
1452
1453   return t;
1454 }
1455
1456 void vl_api_send_pending_rpc_requests (vlib_main_t *) __attribute__ ((weak));
1457 void
1458 vl_api_send_pending_rpc_requests (vlib_main_t * vm)
1459 {
1460 }
1461
1462 static_always_inline void
1463 vlib_main_or_worker_loop (vlib_main_t * vm, int is_main)
1464 {
1465   vlib_node_main_t *nm = &vm->node_main;
1466   vlib_thread_main_t *tm = vlib_get_thread_main ();
1467   uword i;
1468   u64 cpu_time_now;
1469   f64 now;
1470   vlib_frame_queue_main_t *fqm;
1471   u32 frame_queue_check_counter = 0;
1472
1473   /* Initialize pending node vector. */
1474   if (is_main)
1475     {
1476       vec_resize (nm->pending_frames, 32);
1477       _vec_len (nm->pending_frames) = 0;
1478     }
1479
1480   /* Mark time of main loop start. */
1481   if (is_main)
1482     {
1483       cpu_time_now = vm->clib_time.last_cpu_time;
1484       vm->cpu_time_main_loop_start = cpu_time_now;
1485     }
1486   else
1487     cpu_time_now = clib_cpu_time_now ();
1488
1489   /* Pre-allocate interupt runtime indices and lock. */
1490   vec_alloc_aligned (nm->pending_interrupts, 1, CLIB_CACHE_LINE_BYTES);
1491
1492   /* Pre-allocate expired nodes. */
1493   if (!nm->polling_threshold_vector_length)
1494     nm->polling_threshold_vector_length = 10;
1495   if (!nm->interrupt_threshold_vector_length)
1496     nm->interrupt_threshold_vector_length = 5;
1497
1498   vm->cpu_id = clib_get_current_cpu_id ();
1499   vm->numa_node = clib_get_current_numa_node ();
1500   os_set_numa_index (vm->numa_node);
1501
1502   /* Start all processes. */
1503   if (is_main)
1504     {
1505       uword i;
1506
1507       /*
1508        * Perform an initial barrier sync. Pays no attention to
1509        * the barrier sync hold-down timer scheme, which won't work
1510        * at this point in time.
1511        */
1512       vlib_worker_thread_initial_barrier_sync_and_release (vm);
1513
1514       nm->current_process_index = ~0;
1515       for (i = 0; i < vec_len (nm->processes); i++)
1516         cpu_time_now = dispatch_process (vm, nm->processes[i], /* frame */ 0,
1517                                          cpu_time_now);
1518     }
1519
1520   while (1)
1521     {
1522       vlib_node_runtime_t *n;
1523
1524       if (PREDICT_FALSE (_vec_len (vm->pending_rpc_requests) > 0))
1525         {
1526           if (!is_main)
1527             vl_api_send_pending_rpc_requests (vm);
1528         }
1529
1530       if (!is_main)
1531         vlib_worker_thread_barrier_check ();
1532
1533       if (PREDICT_FALSE (vm->check_frame_queues + frame_queue_check_counter))
1534         {
1535           u32 processed = 0;
1536           vlib_frame_queue_dequeue_fn_t *fn =
1537             vlib_buffer_func_main.frame_queue_dequeue_fn;
1538
1539           if (vm->check_frame_queues)
1540             {
1541               frame_queue_check_counter = 100;
1542               vm->check_frame_queues = 0;
1543             }
1544
1545           vec_foreach (fqm, tm->frame_queue_mains)
1546             processed += (fn) (vm, fqm);
1547
1548           /* No handoff queue work found? */
1549           if (processed)
1550             frame_queue_check_counter = 100;
1551           else
1552             frame_queue_check_counter--;
1553         }
1554
1555       if (PREDICT_FALSE (vec_len (vm->worker_thread_main_loop_callbacks)))
1556         clib_call_callbacks (vm->worker_thread_main_loop_callbacks, vm,
1557                              cpu_time_now);
1558
1559       /* Process pre-input nodes. */
1560       cpu_time_now = clib_cpu_time_now ();
1561       vec_foreach (n, nm->nodes_by_type[VLIB_NODE_TYPE_PRE_INPUT])
1562         cpu_time_now = dispatch_node (vm, n,
1563                                       VLIB_NODE_TYPE_PRE_INPUT,
1564                                       VLIB_NODE_STATE_POLLING,
1565                                       /* frame */ 0,
1566                                       cpu_time_now);
1567
1568       /* Next process input nodes. */
1569       vec_foreach (n, nm->nodes_by_type[VLIB_NODE_TYPE_INPUT])
1570         cpu_time_now = dispatch_node (vm, n,
1571                                       VLIB_NODE_TYPE_INPUT,
1572                                       VLIB_NODE_STATE_POLLING,
1573                                       /* frame */ 0,
1574                                       cpu_time_now);
1575
1576       if (PREDICT_TRUE (is_main && vm->queue_signal_pending == 0))
1577         vm->queue_signal_callback (vm);
1578
1579       if (__atomic_load_n (nm->pending_interrupts, __ATOMIC_ACQUIRE))
1580         {
1581           int int_num = -1;
1582           *nm->pending_interrupts = 0;
1583
1584           while ((int_num =
1585                     clib_interrupt_get_next (nm->interrupts, int_num)) != -1)
1586             {
1587               vlib_node_runtime_t *n;
1588               clib_interrupt_clear (nm->interrupts, int_num);
1589               n = vec_elt_at_index (nm->nodes_by_type[VLIB_NODE_TYPE_INPUT],
1590                                     int_num);
1591               cpu_time_now = dispatch_node (vm, n, VLIB_NODE_TYPE_INPUT,
1592                                             VLIB_NODE_STATE_INTERRUPT,
1593                                             /* frame */ 0, cpu_time_now);
1594             }
1595         }
1596
1597       /* Input nodes may have added work to the pending vector.
1598          Process pending vector until there is nothing left.
1599          All pending vectors will be processed from input -> output. */
1600       for (i = 0; i < _vec_len (nm->pending_frames); i++)
1601         cpu_time_now = dispatch_pending_node (vm, i, cpu_time_now);
1602       /* Reset pending vector for next iteration. */
1603       _vec_len (nm->pending_frames) = 0;
1604
1605       if (is_main)
1606         {
1607           /* *INDENT-OFF* */
1608           ELOG_TYPE_DECLARE (es) =
1609             {
1610               .format = "process tw start",
1611               .format_args = "",
1612             };
1613           ELOG_TYPE_DECLARE (ee) =
1614             {
1615               .format = "process tw end: %d",
1616               .format_args = "i4",
1617             };
1618           /* *INDENT-ON* */
1619
1620           struct
1621           {
1622             int nready_procs;
1623           } *ed;
1624
1625           /* Check if process nodes have expired from timing wheel. */
1626           ASSERT (nm->data_from_advancing_timing_wheel != 0);
1627
1628           if (PREDICT_FALSE (vm->elog_trace_graph_dispatch))
1629             ed = ELOG_DATA (&vlib_global_main.elog_main, es);
1630
1631           nm->data_from_advancing_timing_wheel =
1632             TW (tw_timer_expire_timers_vec)
1633             ((TWT (tw_timer_wheel) *) nm->timing_wheel, vlib_time_now (vm),
1634              nm->data_from_advancing_timing_wheel);
1635
1636           ASSERT (nm->data_from_advancing_timing_wheel != 0);
1637
1638           if (PREDICT_FALSE (vm->elog_trace_graph_dispatch))
1639             {
1640               ed = ELOG_DATA (&vlib_global_main.elog_main, ee);
1641               ed->nready_procs =
1642                 _vec_len (nm->data_from_advancing_timing_wheel);
1643             }
1644
1645           if (PREDICT_FALSE
1646               (_vec_len (nm->data_from_advancing_timing_wheel) > 0))
1647             {
1648               uword i;
1649
1650               for (i = 0; i < _vec_len (nm->data_from_advancing_timing_wheel);
1651                    i++)
1652                 {
1653                   u32 d = nm->data_from_advancing_timing_wheel[i];
1654                   u32 di = vlib_timing_wheel_data_get_index (d);
1655
1656                   if (vlib_timing_wheel_data_is_timed_event (d))
1657                     {
1658                       vlib_signal_timed_event_data_t *te =
1659                         pool_elt_at_index (nm->signal_timed_event_data_pool,
1660                                            di);
1661                       vlib_node_t *n =
1662                         vlib_get_node (vm, te->process_node_index);
1663                       vlib_process_t *p =
1664                         vec_elt (nm->processes, n->runtime_index);
1665                       void *data;
1666                       data =
1667                         vlib_process_signal_event_helper (nm, n, p,
1668                                                           te->event_type_index,
1669                                                           te->n_data_elts,
1670                                                           te->n_data_elt_bytes);
1671                       if (te->n_data_bytes < sizeof (te->inline_event_data))
1672                         clib_memcpy_fast (data, te->inline_event_data,
1673                                           te->n_data_bytes);
1674                       else
1675                         {
1676                           clib_memcpy_fast (data, te->event_data_as_vector,
1677                                             te->n_data_bytes);
1678                           vec_free (te->event_data_as_vector);
1679                         }
1680                       pool_put (nm->signal_timed_event_data_pool, te);
1681                     }
1682                   else
1683                     {
1684                       cpu_time_now = clib_cpu_time_now ();
1685                       cpu_time_now =
1686                         dispatch_suspended_process (vm, di, cpu_time_now);
1687                     }
1688                 }
1689               _vec_len (nm->data_from_advancing_timing_wheel) = 0;
1690             }
1691         }
1692       vlib_increment_main_loop_counter (vm);
1693       /* Record time stamp in case there are no enabled nodes and above
1694          calls do not update time stamp. */
1695       cpu_time_now = clib_cpu_time_now ();
1696       vm->loops_this_reporting_interval++;
1697       now = clib_time_now_internal (&vm->clib_time, cpu_time_now);
1698       /* Time to update loops_per_second? */
1699       if (PREDICT_FALSE (now >= vm->loop_interval_end))
1700         {
1701           /* Next sample ends in 20ms */
1702           if (vm->loop_interval_start)
1703             {
1704               f64 this_loops_per_second;
1705
1706               this_loops_per_second =
1707                 ((f64) vm->loops_this_reporting_interval) / (now -
1708                                                              vm->loop_interval_start);
1709
1710               vm->loops_per_second =
1711                 vm->loops_per_second * vm->damping_constant +
1712                 (1.0 - vm->damping_constant) * this_loops_per_second;
1713               if (vm->loops_per_second != 0.0)
1714                 vm->seconds_per_loop = 1.0 / vm->loops_per_second;
1715               else
1716                 vm->seconds_per_loop = 0.0;
1717             }
1718           /* New interval starts now, and ends in 20ms */
1719           vm->loop_interval_start = now;
1720           vm->loop_interval_end = now + 2e-4;
1721           vm->loops_this_reporting_interval = 0;
1722         }
1723     }
1724 }
1725
1726 static void
1727 vlib_main_loop (vlib_main_t * vm)
1728 {
1729   vlib_main_or_worker_loop (vm, /* is_main */ 1);
1730 }
1731
1732 void
1733 vlib_worker_loop (vlib_main_t * vm)
1734 {
1735   vlib_main_or_worker_loop (vm, /* is_main */ 0);
1736 }
1737
1738 vlib_global_main_t vlib_global_main;
1739
1740 void
1741 vlib_add_del_post_mortem_callback (void *cb, int is_add)
1742 {
1743   vlib_global_main_t *vgm = vlib_get_global_main ();
1744   int i;
1745
1746   if (is_add == 0)
1747     {
1748       for (i = vec_len (vgm->post_mortem_callbacks) - 1; i >= 0; i--)
1749         if (vgm->post_mortem_callbacks[i] == cb)
1750           vec_del1 (vgm->post_mortem_callbacks, i);
1751       return;
1752     }
1753
1754   for (i = 0; i < vec_len (vgm->post_mortem_callbacks); i++)
1755     if (vgm->post_mortem_callbacks[i] == cb)
1756       return;
1757   vec_add1 (vgm->post_mortem_callbacks, cb);
1758 }
1759
1760 static void
1761 elog_post_mortem_dump (void)
1762 {
1763   elog_main_t *em = vlib_get_elog_main ();
1764
1765   u8 *filename;
1766   clib_error_t *error;
1767
1768   filename = format (0, "/tmp/elog_post_mortem.%d%c", getpid (), 0);
1769   error = elog_write_file (em, (char *) filename, 1 /* flush ring */);
1770   if (error)
1771     clib_error_report (error);
1772   /*
1773    * We're in the middle of crashing. Don't try to free the filename.
1774    */
1775 }
1776
1777 static clib_error_t *
1778 vlib_main_configure (vlib_main_t * vm, unformat_input_t * input)
1779 {
1780   vlib_global_main_t *vgm = vlib_get_global_main ();
1781   int turn_on_mem_trace = 0;
1782
1783   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1784     {
1785       if (unformat (input, "memory-trace"))
1786         turn_on_mem_trace = 1;
1787
1788       else if (unformat (input, "elog-events %d",
1789                          &vgm->configured_elog_ring_size))
1790         vgm->configured_elog_ring_size =
1791           1 << max_log2 (vgm->configured_elog_ring_size);
1792       else if (unformat (input, "elog-post-mortem-dump"))
1793         vlib_add_del_post_mortem_callback (elog_post_mortem_dump,
1794                                            /* is_add */ 1);
1795       else if (unformat (input, "buffer-alloc-success-rate %f",
1796                          &vm->buffer_alloc_success_rate))
1797         {
1798           if (VLIB_BUFFER_ALLOC_FAULT_INJECTOR == 0)
1799             return clib_error_return
1800               (0, "Buffer fault injection not configured");
1801         }
1802       else if (unformat (input, "buffer-alloc-success-seed %u",
1803                          &vm->buffer_alloc_success_seed))
1804         {
1805           if (VLIB_BUFFER_ALLOC_FAULT_INJECTOR == 0)
1806             return clib_error_return
1807               (0, "Buffer fault injection not configured");
1808         }
1809       else
1810         return unformat_parse_error (input);
1811     }
1812
1813   unformat_free (input);
1814
1815   /* Enable memory trace as early as possible. */
1816   if (turn_on_mem_trace)
1817     clib_mem_trace (1);
1818
1819   return 0;
1820 }
1821
1822 VLIB_EARLY_CONFIG_FUNCTION (vlib_main_configure, "vlib");
1823
1824 static void
1825 placeholder_queue_signal_callback (vlib_main_t * vm)
1826 {
1827 }
1828
1829 #define foreach_weak_reference_stub             \
1830 _(vpe_api_init)                                 \
1831 _(vlibmemory_init)                              \
1832 _(map_api_segment_init)
1833
1834 #define _(name)                                                 \
1835 clib_error_t *name (vlib_main_t *vm) __attribute__((weak));     \
1836 clib_error_t *name (vlib_main_t *vm) { return 0; }
1837 foreach_weak_reference_stub;
1838 #undef _
1839
1840 void vl_api_set_elog_main (elog_main_t * m) __attribute__ ((weak));
1841 void
1842 vl_api_set_elog_main (elog_main_t * m)
1843 {
1844   clib_warning ("STUB");
1845 }
1846
1847 int vl_api_set_elog_trace_api_messages (int enable) __attribute__ ((weak));
1848 int
1849 vl_api_set_elog_trace_api_messages (int enable)
1850 {
1851   clib_warning ("STUB");
1852   return 0;
1853 }
1854
1855 int vl_api_get_elog_trace_api_messages (void) __attribute__ ((weak));
1856 int
1857 vl_api_get_elog_trace_api_messages (void)
1858 {
1859   clib_warning ("STUB");
1860   return 0;
1861 }
1862
1863 /* Main function. */
1864 int
1865 vlib_main (vlib_main_t * volatile vm, unformat_input_t * input)
1866 {
1867   vlib_global_main_t *vgm = vlib_get_global_main ();
1868   clib_error_t *volatile error;
1869   vlib_node_main_t *nm = &vm->node_main;
1870
1871   vm->queue_signal_callback = placeholder_queue_signal_callback;
1872
1873   /* Reconfigure event log which is enabled very early */
1874   if (vgm->configured_elog_ring_size &&
1875       vgm->configured_elog_ring_size != vgm->elog_main.event_ring_size)
1876     elog_resize (&vgm->elog_main, vgm->configured_elog_ring_size);
1877   vl_api_set_elog_main (vlib_get_elog_main ());
1878   (void) vl_api_set_elog_trace_api_messages (1);
1879
1880   /* Default name. */
1881   if (!vgm->name)
1882     vgm->name = "VLIB";
1883
1884   if ((error = vlib_physmem_init (vm)))
1885     {
1886       clib_error_report (error);
1887       goto done;
1888     }
1889
1890   if ((error = vlib_log_init (vm)))
1891     {
1892       clib_error_report (error);
1893       goto done;
1894     }
1895
1896   if ((error = vlib_stats_init (vm)))
1897     {
1898       clib_error_report (error);
1899       goto done;
1900     }
1901
1902   if ((error = vlib_buffer_main_init (vm)))
1903     {
1904       clib_error_report (error);
1905       goto done;
1906     }
1907
1908   if ((error = vlib_thread_init (vm)))
1909     {
1910       clib_error_report (error);
1911       goto done;
1912     }
1913
1914   /* Register node ifunction variants */
1915   vlib_register_all_node_march_variants (vm);
1916
1917   /* Register static nodes so that init functions may use them. */
1918   vlib_register_all_static_nodes (vm);
1919
1920   /* Set seed for random number generator.
1921      Allow user to specify seed to make random sequence deterministic. */
1922   if (!unformat (input, "seed %wd", &vm->random_seed))
1923     vm->random_seed = clib_cpu_time_now ();
1924   clib_random_buffer_init (&vm->random_buffer, vm->random_seed);
1925
1926   /* Initialize node graph. */
1927   if ((error = vlib_node_main_init (vm)))
1928     {
1929       /* Arrange for graph hook up error to not be fatal when debugging. */
1930       if (CLIB_DEBUG > 0)
1931         clib_error_report (error);
1932       else
1933         goto done;
1934     }
1935
1936   /* Direct call / weak reference, for vlib standalone use-cases */
1937   if ((error = vpe_api_init (vm)))
1938     {
1939       clib_error_report (error);
1940       goto done;
1941     }
1942
1943   if ((error = vlibmemory_init (vm)))
1944     {
1945       clib_error_report (error);
1946       goto done;
1947     }
1948
1949   if ((error = map_api_segment_init (vm)))
1950     {
1951       clib_error_report (error);
1952       goto done;
1953     }
1954
1955   /* See unix/main.c; most likely already set up */
1956   if (vgm->init_functions_called == 0)
1957     vgm->init_functions_called = hash_create (0, /* value bytes */ 0);
1958   if ((error = vlib_call_all_init_functions (vm)))
1959     goto done;
1960
1961   nm->timing_wheel = clib_mem_alloc_aligned (sizeof (TWT (tw_timer_wheel)),
1962                                              CLIB_CACHE_LINE_BYTES);
1963
1964   vec_validate (nm->data_from_advancing_timing_wheel, 10);
1965   _vec_len (nm->data_from_advancing_timing_wheel) = 0;
1966
1967   /* Create the process timing wheel */
1968   TW (tw_timer_wheel_init) ((TWT (tw_timer_wheel) *) nm->timing_wheel,
1969                             0 /* no callback */ ,
1970                             10e-6 /* timer period 10us */ ,
1971                             ~0 /* max expirations per call */ );
1972
1973   vec_validate (vm->pending_rpc_requests, 0);
1974   _vec_len (vm->pending_rpc_requests) = 0;
1975   vec_validate (vm->processing_rpc_requests, 0);
1976   _vec_len (vm->processing_rpc_requests) = 0;
1977
1978   /* Default params for the buffer allocator fault injector, if configured */
1979   if (VLIB_BUFFER_ALLOC_FAULT_INJECTOR > 0)
1980     {
1981       vm->buffer_alloc_success_seed = 0xdeaddabe;
1982       vm->buffer_alloc_success_rate = 0.80;
1983     }
1984
1985   if ((error = vlib_call_all_config_functions (vm, input, 0 /* is_early */ )))
1986     goto done;
1987
1988   /*
1989    * Use exponential smoothing, with a half-life of 1 second
1990    * reported_rate(t) = reported_rate(t-1) * K + rate(t)*(1-K)
1991    *
1992    * Sample every 20ms, aka 50 samples per second
1993    * K = exp (-1.0/20.0);
1994    * K = 0.95
1995    */
1996   vm->damping_constant = exp (-1.0 / 20.0);
1997
1998   /* Sort per-thread init functions before we start threads */
1999   vlib_sort_init_exit_functions (&vgm->worker_init_function_registrations);
2000
2001   /* Call all main loop enter functions. */
2002   {
2003     clib_error_t *sub_error;
2004     sub_error = vlib_call_all_main_loop_enter_functions (vm);
2005     if (sub_error)
2006       clib_error_report (sub_error);
2007   }
2008
2009   switch (clib_setjmp (&vm->main_loop_exit, VLIB_MAIN_LOOP_EXIT_NONE))
2010     {
2011     case VLIB_MAIN_LOOP_EXIT_NONE:
2012       vm->main_loop_exit_set = 1;
2013       break;
2014
2015     case VLIB_MAIN_LOOP_EXIT_CLI:
2016       goto done;
2017
2018     default:
2019       error = vm->main_loop_error;
2020       goto done;
2021     }
2022
2023   vlib_main_loop (vm);
2024
2025 done:
2026   vlib_worker_thread_barrier_sync (vm);
2027   /* Call all exit functions. */
2028   {
2029     clib_error_t *sub_error;
2030     sub_error = vlib_call_all_main_loop_exit_functions (vm);
2031     if (sub_error)
2032       clib_error_report (sub_error);
2033   }
2034   vlib_worker_thread_barrier_release (vm);
2035
2036   if (error)
2037     clib_error_report (error);
2038
2039   return vm->main_loop_exit_status;
2040 }
2041
2042 vlib_main_t *
2043 vlib_get_main_not_inline (void)
2044 {
2045   return vlib_get_main ();
2046 }
2047
2048 elog_main_t *
2049 vlib_get_elog_main_not_inline ()
2050 {
2051   return &vlib_global_main.elog_main;
2052 }
2053
2054 void
2055 vlib_exit_with_status (vlib_main_t *vm, int status)
2056 {
2057   vm->main_loop_exit_status = status;
2058   __atomic_store_n (&vm->main_loop_exit_now, 1, __ATOMIC_RELEASE);
2059 }
2060
2061 /*
2062  * fd.io coding-style-patch-verification: ON
2063  *
2064  * Local Variables:
2065  * eval: (c-set-style "gnu")
2066  * End:
2067  */