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