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