Declare variables as external
[vpp.git] / vlib / vlib / threads.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 #define _GNU_SOURCE
16
17 #include <signal.h>
18 #include <math.h>
19 #include <vppinfra/format.h>
20 #include <vlib/vlib.h>
21
22 #include <vlib/threads.h>
23 #include <vlib/unix/cj.h>
24
25
26 #if DPDK==1
27 #include <rte_config.h>
28 #include <rte_common.h>
29 #include <rte_eal.h>
30 #include <rte_launch.h>
31 #include <rte_lcore.h>
32 #endif
33 DECLARE_CJ_GLOBAL_LOG;
34
35 #define FRAME_QUEUE_NELTS 32
36
37
38 #if DPDK==1
39 /*
40  *  Weak definitions of DPDK symbols used in this file.
41  *  Needed for linking test programs without DPDK libs.
42  */
43 unsigned __thread __attribute__ ((weak)) RTE_PER_LCORE (_lcore_id);
44 struct lcore_config __attribute__ ((weak)) lcore_config[];
45 unsigned __attribute__ ((weak)) rte_socket_id ();
46 int __attribute__ ((weak)) rte_eal_remote_launch ();
47 #endif
48 u32
49 vl (void *p)
50 {
51   return vec_len (p);
52 }
53
54 vlib_worker_thread_t *vlib_worker_threads;
55 vlib_thread_main_t vlib_thread_main;
56
57 uword
58 os_get_cpu_number (void)
59 {
60   void *sp;
61   uword n;
62   u32 len;
63
64   len = vec_len (vlib_thread_stacks);
65   if (len == 0)
66     return 0;
67
68   /* Get any old stack address. */
69   sp = &sp;
70
71   n = ((uword) sp - (uword) vlib_thread_stacks[0])
72     >> VLIB_LOG2_THREAD_STACK_SIZE;
73
74   /* "processes" have their own stacks, and they always run in thread 0 */
75   n = n >= len ? 0 : n;
76
77   return n;
78 }
79
80 uword
81 os_get_ncpus (void)
82 {
83   u32 len;
84
85   len = vec_len (vlib_thread_stacks);
86   if (len == 0)
87     return 1;
88   else
89     return len;
90 }
91
92 void
93 vlib_set_thread_name (char *name)
94 {
95   int pthread_setname_np (pthread_t __target_thread, const char *__name);
96   int rv;
97   pthread_t thread = pthread_self ();
98
99   if (thread)
100     {
101       rv = pthread_setname_np (thread, name);
102       if (rv)
103         clib_warning ("pthread_setname_np returned %d", rv);
104     }
105 }
106
107 static int
108 sort_registrations_by_no_clone (void *a0, void *a1)
109 {
110   vlib_thread_registration_t **tr0 = a0;
111   vlib_thread_registration_t **tr1 = a1;
112
113   return ((i32) ((*tr0)->no_data_structure_clone)
114           - ((i32) ((*tr1)->no_data_structure_clone)));
115 }
116
117 static uword *
118 vlib_sysfs_list_to_bitmap (char *filename)
119 {
120   FILE *fp;
121   uword *r = 0;
122
123   fp = fopen (filename, "r");
124
125   if (fp != NULL)
126     {
127       u8 *buffer = 0;
128       vec_validate (buffer, 256 - 1);
129       if (fgets ((char *) buffer, 256, fp))
130         {
131           unformat_input_t in;
132           unformat_init_string (&in, (char *) buffer,
133                                 strlen ((char *) buffer));
134           if (unformat (&in, "%U", unformat_bitmap_list, &r) != 1)
135             clib_warning ("unformat_bitmap_list failed");
136           unformat_free (&in);
137         }
138       vec_free (buffer);
139       fclose (fp);
140     }
141   return r;
142 }
143
144
145 /* Called early in the init sequence */
146
147 clib_error_t *
148 vlib_thread_init (vlib_main_t * vm)
149 {
150   vlib_thread_main_t *tm = &vlib_thread_main;
151   vlib_worker_thread_t *w;
152   vlib_thread_registration_t *tr;
153   u32 n_vlib_mains = 1;
154   u32 first_index = 1;
155   u32 i;
156   uword *avail_cpu;
157
158   /* get bitmaps of active cpu cores and sockets */
159   tm->cpu_core_bitmap =
160     vlib_sysfs_list_to_bitmap ("/sys/devices/system/cpu/online");
161   tm->cpu_socket_bitmap =
162     vlib_sysfs_list_to_bitmap ("/sys/devices/system/node/online");
163
164   avail_cpu = clib_bitmap_dup (tm->cpu_core_bitmap);
165
166   /* skip cores */
167   for (i = 0; i < tm->skip_cores; i++)
168     {
169       uword c = clib_bitmap_first_set (avail_cpu);
170       if (c == ~0)
171         return clib_error_return (0, "no available cpus to skip");
172
173       avail_cpu = clib_bitmap_set (avail_cpu, c, 0);
174     }
175
176   /* grab cpu for main thread */
177   if (!tm->main_lcore)
178     {
179       tm->main_lcore = clib_bitmap_first_set (avail_cpu);
180       if (tm->main_lcore == (u8) ~ 0)
181         return clib_error_return (0, "no available cpus to be used for the"
182                                   " main thread");
183     }
184   else
185     {
186       if (clib_bitmap_get (avail_cpu, tm->main_lcore) == 0)
187         return clib_error_return (0, "cpu %u is not available to be used"
188                                   " for the main thread", tm->main_lcore);
189     }
190   avail_cpu = clib_bitmap_set (avail_cpu, tm->main_lcore, 0);
191
192   /* assume that there is socket 0 only if there is no data from sysfs */
193   if (!tm->cpu_socket_bitmap)
194     tm->cpu_socket_bitmap = clib_bitmap_set (0, 0, 1);
195
196   /* pin main thread to main_lcore  */
197 #if DPDK==0
198   {
199     cpu_set_t cpuset;
200     CPU_ZERO (&cpuset);
201     CPU_SET (tm->main_lcore, &cpuset);
202     pthread_setaffinity_np (pthread_self (), sizeof (cpu_set_t), &cpuset);
203   }
204 #endif
205
206   /* as many threads as stacks... */
207   vec_validate_aligned (vlib_worker_threads, vec_len (vlib_thread_stacks) - 1,
208                         CLIB_CACHE_LINE_BYTES);
209
210   /* Preallocate thread 0 */
211   _vec_len (vlib_worker_threads) = 1;
212   w = vlib_worker_threads;
213   w->thread_mheap = clib_mem_get_heap ();
214   w->thread_stack = vlib_thread_stacks[0];
215   w->lcore_id = tm->main_lcore;
216   w->lwp = syscall (SYS_gettid);
217   w->thread_id = pthread_self ();
218   tm->n_vlib_mains = 1;
219
220   if (tm->sched_policy != ~0)
221     {
222       struct sched_param sched_param;
223       if (!sched_getparam (w->lwp, &sched_param))
224         {
225           if (tm->sched_priority != ~0)
226             sched_param.sched_priority = tm->sched_priority;
227           sched_setscheduler (w->lwp, tm->sched_policy, &sched_param);
228         }
229     }
230
231   /* assign threads to cores and set n_vlib_mains */
232   tr = tm->next;
233
234   while (tr)
235     {
236       vec_add1 (tm->registrations, tr);
237       tr = tr->next;
238     }
239
240   vec_sort_with_function (tm->registrations, sort_registrations_by_no_clone);
241
242   for (i = 0; i < vec_len (tm->registrations); i++)
243     {
244       int j;
245       tr = tm->registrations[i];
246       tr->first_index = first_index;
247       first_index += tr->count;
248       n_vlib_mains += (tr->no_data_structure_clone == 0) ? tr->count : 0;
249
250       /* construct coremask */
251       if (tr->use_pthreads || !tr->count)
252         continue;
253
254       if (tr->coremask)
255         {
256           uword c;
257           /* *INDENT-OFF* */
258           clib_bitmap_foreach (c, tr->coremask, ({
259             if (clib_bitmap_get(avail_cpu, c) == 0)
260               return clib_error_return (0, "cpu %u is not available to be used"
261                                         " for the '%s' thread",c, tr->name);
262
263             avail_cpu = clib_bitmap_set(avail_cpu, c, 0);
264           }));
265 /* *INDENT-ON* */
266
267         }
268       else
269         {
270           for (j = 0; j < tr->count; j++)
271             {
272               uword c = clib_bitmap_first_set (avail_cpu);
273               if (c == ~0)
274                 return clib_error_return (0,
275                                           "no available cpus to be used for"
276                                           " the '%s' thread", tr->name);
277
278               avail_cpu = clib_bitmap_set (avail_cpu, c, 0);
279               tr->coremask = clib_bitmap_set (tr->coremask, c, 1);
280             }
281         }
282     }
283
284   clib_bitmap_free (avail_cpu);
285
286   tm->n_vlib_mains = n_vlib_mains;
287
288   vec_validate_aligned (vlib_worker_threads, first_index - 1,
289                         CLIB_CACHE_LINE_BYTES);
290
291   return 0;
292 }
293
294 vlib_worker_thread_t *
295 vlib_alloc_thread (vlib_main_t * vm)
296 {
297   vlib_worker_thread_t *w;
298
299   if (vec_len (vlib_worker_threads) >= vec_len (vlib_thread_stacks))
300     {
301       clib_warning ("out of worker threads... Quitting...");
302       exit (1);
303     }
304   vec_add2 (vlib_worker_threads, w, 1);
305   w->thread_stack = vlib_thread_stacks[w - vlib_worker_threads];
306   return w;
307 }
308
309 vlib_frame_queue_t *
310 vlib_frame_queue_alloc (int nelts)
311 {
312   vlib_frame_queue_t *fq;
313
314   fq = clib_mem_alloc_aligned (sizeof (*fq), CLIB_CACHE_LINE_BYTES);
315   memset (fq, 0, sizeof (*fq));
316   fq->nelts = nelts;
317   fq->vector_threshold = 128;   // packets
318   vec_validate_aligned (fq->elts, nelts - 1, CLIB_CACHE_LINE_BYTES);
319
320   if (1)
321     {
322       if (((uword) & fq->tail) & (CLIB_CACHE_LINE_BYTES - 1))
323         fformat (stderr, "WARNING: fq->tail unaligned\n");
324       if (((uword) & fq->head) & (CLIB_CACHE_LINE_BYTES - 1))
325         fformat (stderr, "WARNING: fq->head unaligned\n");
326       if (((uword) fq->elts) & (CLIB_CACHE_LINE_BYTES - 1))
327         fformat (stderr, "WARNING: fq->elts unaligned\n");
328
329       if (sizeof (fq->elts[0]) % CLIB_CACHE_LINE_BYTES)
330         fformat (stderr, "WARNING: fq->elts[0] size %d\n",
331                  sizeof (fq->elts[0]));
332       if (nelts & (nelts - 1))
333         {
334           fformat (stderr, "FATAL: nelts MUST be a power of 2\n");
335           abort ();
336         }
337     }
338
339   return (fq);
340 }
341
342 void vl_msg_api_handler_no_free (void *) __attribute__ ((weak));
343 void
344 vl_msg_api_handler_no_free (void *v)
345 {
346 }
347
348 /* Turned off, save as reference material... */
349 #if 0
350 static inline int
351 vlib_frame_queue_dequeue_internal (int thread_id,
352                                    vlib_main_t * vm, vlib_node_main_t * nm)
353 {
354   vlib_frame_queue_t *fq = vlib_frame_queues[thread_id];
355   vlib_frame_queue_elt_t *elt;
356   vlib_frame_t *f;
357   vlib_pending_frame_t *p;
358   vlib_node_runtime_t *r;
359   u32 node_runtime_index;
360   int msg_type;
361   u64 before;
362   int processed = 0;
363
364   ASSERT (vm == vlib_mains[thread_id]);
365
366   while (1)
367     {
368       if (fq->head == fq->tail)
369         return processed;
370
371       elt = fq->elts + ((fq->head + 1) & (fq->nelts - 1));
372
373       if (!elt->valid)
374         return processed;
375
376       before = clib_cpu_time_now ();
377
378       f = elt->frame;
379       node_runtime_index = elt->node_runtime_index;
380       msg_type = elt->msg_type;
381
382       switch (msg_type)
383         {
384         case VLIB_FRAME_QUEUE_ELT_FREE_BUFFERS:
385           vlib_buffer_free (vm, vlib_frame_vector_args (f), f->n_vectors);
386           /* note fallthrough... */
387         case VLIB_FRAME_QUEUE_ELT_FREE_FRAME:
388           r = vec_elt_at_index (nm->nodes_by_type[VLIB_NODE_TYPE_INTERNAL],
389                                 node_runtime_index);
390           vlib_frame_free (vm, r, f);
391           break;
392         case VLIB_FRAME_QUEUE_ELT_DISPATCH_FRAME:
393           vec_add2 (vm->node_main.pending_frames, p, 1);
394           f->flags |= (VLIB_FRAME_PENDING | VLIB_FRAME_FREE_AFTER_DISPATCH);
395           p->node_runtime_index = elt->node_runtime_index;
396           p->frame_index = vlib_frame_index (vm, f);
397           p->next_frame_index = VLIB_PENDING_FRAME_NO_NEXT_FRAME;
398           fq->dequeue_vectors += (u64) f->n_vectors;
399           break;
400         case VLIB_FRAME_QUEUE_ELT_API_MSG:
401           vl_msg_api_handler_no_free (f);
402           break;
403         default:
404           clib_warning ("bogus frame queue message, type %d", msg_type);
405           break;
406         }
407       elt->valid = 0;
408       fq->dequeues++;
409       fq->dequeue_ticks += clib_cpu_time_now () - before;
410       CLIB_MEMORY_BARRIER ();
411       fq->head++;
412       processed++;
413     }
414   ASSERT (0);
415   return processed;
416 }
417
418 int
419 vlib_frame_queue_dequeue (int thread_id,
420                           vlib_main_t * vm, vlib_node_main_t * nm)
421 {
422   return vlib_frame_queue_dequeue_internal (thread_id, vm, nm);
423 }
424
425 int
426 vlib_frame_queue_enqueue (vlib_main_t * vm, u32 node_runtime_index,
427                           u32 frame_queue_index, vlib_frame_t * frame,
428                           vlib_frame_queue_msg_type_t type)
429 {
430   vlib_frame_queue_t *fq = vlib_frame_queues[frame_queue_index];
431   vlib_frame_queue_elt_t *elt;
432   u32 save_count;
433   u64 new_tail;
434   u64 before = clib_cpu_time_now ();
435
436   ASSERT (fq);
437
438   new_tail = __sync_add_and_fetch (&fq->tail, 1);
439
440   /* Wait until a ring slot is available */
441   while (new_tail >= fq->head + fq->nelts)
442     {
443       f64 b4 = vlib_time_now_ticks (vm, before);
444       vlib_worker_thread_barrier_check (vm, b4);
445       /* Bad idea. Dequeue -> enqueue -> dequeue -> trouble */
446       // vlib_frame_queue_dequeue (vm->cpu_index, vm, nm);
447     }
448
449   elt = fq->elts + (new_tail & (fq->nelts - 1));
450
451   /* this would be very bad... */
452   while (elt->valid)
453     {
454     }
455
456   /* Once we enqueue the frame, frame->n_vectors is owned elsewhere... */
457   save_count = frame->n_vectors;
458
459   elt->frame = frame;
460   elt->node_runtime_index = node_runtime_index;
461   elt->msg_type = type;
462   CLIB_MEMORY_BARRIER ();
463   elt->valid = 1;
464
465   return save_count;
466 }
467 #endif /* 0 */
468
469 /* To be called by vlib worker threads upon startup */
470 void
471 vlib_worker_thread_init (vlib_worker_thread_t * w)
472 {
473   vlib_thread_main_t *tm = vlib_get_thread_main ();
474
475   /* worker threads wants no signals. */
476   {
477     sigset_t s;
478     sigfillset (&s);
479     pthread_sigmask (SIG_SETMASK, &s, 0);
480   }
481
482   clib_mem_set_heap (w->thread_mheap);
483
484   if (vec_len (tm->thread_prefix) && w->registration->short_name)
485     {
486       w->name = format (0, "%v_%s_%d%c", tm->thread_prefix,
487                         w->registration->short_name, w->instance_id, '\0');
488       vlib_set_thread_name ((char *) w->name);
489     }
490
491   if (!w->registration->use_pthreads)
492     {
493
494       /* Initial barrier sync, for both worker and i/o threads */
495       clib_smp_atomic_add (vlib_worker_threads->workers_at_barrier, 1);
496
497       while (*vlib_worker_threads->wait_at_barrier)
498         ;
499
500       clib_smp_atomic_add (vlib_worker_threads->workers_at_barrier, -1);
501     }
502 }
503
504 void *
505 vlib_worker_thread_bootstrap_fn (void *arg)
506 {
507   void *rv;
508   vlib_worker_thread_t *w = arg;
509
510   w->lwp = syscall (SYS_gettid);
511   w->thread_id = pthread_self ();
512
513   rv = (void *) clib_calljmp
514     ((uword (*)(uword)) w->thread_function,
515      (uword) arg, w->thread_stack + VLIB_THREAD_STACK_SIZE);
516   /* NOTREACHED, we hope */
517   return rv;
518 }
519
520 static int
521 vlib_launch_thread (void *fp, vlib_worker_thread_t * w, unsigned lcore_id)
522 {
523   void *(*fp_arg) (void *) = fp;
524
525   w->lcore_id = lcore_id;
526 #if DPDK==1
527   if (!w->registration->use_pthreads)
528     if (rte_eal_remote_launch)  /* do we have dpdk linked */
529       return rte_eal_remote_launch (fp, (void *) w, lcore_id);
530     else
531       return -1;
532   else
533 #endif
534     {
535       int ret;
536       pthread_t worker;
537       cpu_set_t cpuset;
538       CPU_ZERO (&cpuset);
539       CPU_SET (lcore_id, &cpuset);
540
541       ret = pthread_create (&worker, NULL /* attr */ , fp_arg, (void *) w);
542       if (ret == 0)
543         return pthread_setaffinity_np (worker, sizeof (cpu_set_t), &cpuset);
544       else
545         return ret;
546     }
547 }
548
549 static clib_error_t *
550 start_workers (vlib_main_t * vm)
551 {
552   int i, j;
553   vlib_worker_thread_t *w;
554   vlib_main_t *vm_clone;
555   void *oldheap;
556   vlib_thread_main_t *tm = &vlib_thread_main;
557   vlib_thread_registration_t *tr;
558   vlib_node_runtime_t *rt;
559   u32 n_vlib_mains = tm->n_vlib_mains;
560   u32 worker_thread_index;
561   u8 *main_heap = clib_mem_get_per_cpu_heap ();
562   mheap_t *main_heap_header = mheap_header (main_heap);
563
564   vec_reset_length (vlib_worker_threads);
565
566   /* Set up the main thread */
567   vec_add2_aligned (vlib_worker_threads, w, 1, CLIB_CACHE_LINE_BYTES);
568   w->elog_track.name = "main thread";
569   elog_track_register (&vm->elog_main, &w->elog_track);
570
571   if (vec_len (tm->thread_prefix))
572     {
573       w->name = format (0, "%v_main%c", tm->thread_prefix, '\0');
574       vlib_set_thread_name ((char *) w->name);
575     }
576
577   /*
578    * Truth of the matter: we always use at least two
579    * threads. So, make the main heap thread-safe
580    * and make the event log thread-safe.
581    */
582   main_heap_header->flags |= MHEAP_FLAG_THREAD_SAFE;
583   vm->elog_main.lock =
584     clib_mem_alloc_aligned (CLIB_CACHE_LINE_BYTES, CLIB_CACHE_LINE_BYTES);
585   vm->elog_main.lock[0] = 0;
586
587   if (n_vlib_mains > 1)
588     {
589       vec_validate (vlib_mains, tm->n_vlib_mains - 1);
590       _vec_len (vlib_mains) = 0;
591       vec_add1 (vlib_mains, vm);
592
593       vlib_worker_threads->wait_at_barrier =
594         clib_mem_alloc_aligned (sizeof (u32), CLIB_CACHE_LINE_BYTES);
595       vlib_worker_threads->workers_at_barrier =
596         clib_mem_alloc_aligned (sizeof (u32), CLIB_CACHE_LINE_BYTES);
597
598       /* Ask for an initial barrier sync */
599       *vlib_worker_threads->workers_at_barrier = 0;
600       *vlib_worker_threads->wait_at_barrier = 1;
601
602       worker_thread_index = 1;
603
604       for (i = 0; i < vec_len (tm->registrations); i++)
605         {
606           vlib_node_main_t *nm, *nm_clone;
607           vlib_buffer_main_t *bm_clone;
608           vlib_buffer_free_list_t *fl_clone, *fl_orig;
609           vlib_buffer_free_list_t *orig_freelist_pool;
610           int k;
611
612           tr = tm->registrations[i];
613
614           if (tr->count == 0)
615             continue;
616
617           for (k = 0; k < tr->count; k++)
618             {
619               vec_add2 (vlib_worker_threads, w, 1);
620               if (tr->mheap_size)
621                 w->thread_mheap =
622                   mheap_alloc (0 /* use VM */ , tr->mheap_size);
623               else
624                 w->thread_mheap = main_heap;
625               w->thread_stack = vlib_thread_stacks[w - vlib_worker_threads];
626               w->thread_function = tr->function;
627               w->thread_function_arg = w;
628               w->instance_id = k;
629               w->registration = tr;
630
631               w->elog_track.name =
632                 (char *) format (0, "%s %d", tr->name, k + 1);
633               vec_add1 (w->elog_track.name, 0);
634               elog_track_register (&vm->elog_main, &w->elog_track);
635
636               if (tr->no_data_structure_clone)
637                 continue;
638
639               /* Fork vlib_global_main et al. Look for bugs here */
640               oldheap = clib_mem_set_heap (w->thread_mheap);
641
642               vm_clone = clib_mem_alloc (sizeof (*vm_clone));
643               clib_memcpy (vm_clone, vlib_mains[0], sizeof (*vm_clone));
644
645               vm_clone->cpu_index = worker_thread_index;
646               vm_clone->heap_base = w->thread_mheap;
647               vm_clone->mbuf_alloc_list = 0;
648               memset (&vm_clone->random_buffer, 0,
649                       sizeof (vm_clone->random_buffer));
650
651               nm = &vlib_mains[0]->node_main;
652               nm_clone = &vm_clone->node_main;
653               /* fork next frames array, preserving node runtime indices */
654               nm_clone->next_frames = vec_dup (nm->next_frames);
655               for (j = 0; j < vec_len (nm_clone->next_frames); j++)
656                 {
657                   vlib_next_frame_t *nf = &nm_clone->next_frames[j];
658                   u32 save_node_runtime_index;
659                   u32 save_flags;
660
661                   save_node_runtime_index = nf->node_runtime_index;
662                   save_flags = nf->flags & VLIB_FRAME_NO_FREE_AFTER_DISPATCH;
663                   vlib_next_frame_init (nf);
664                   nf->node_runtime_index = save_node_runtime_index;
665                   nf->flags = save_flags;
666                 }
667
668               /* fork the frame dispatch queue */
669               nm_clone->pending_frames = 0;
670               vec_validate (nm_clone->pending_frames, 10);      /* $$$$$?????? */
671               _vec_len (nm_clone->pending_frames) = 0;
672
673               /* fork nodes */
674               nm_clone->nodes = 0;
675               for (j = 0; j < vec_len (nm->nodes); j++)
676                 {
677                   vlib_node_t *n;
678                   n = clib_mem_alloc_no_fail (sizeof (*n));
679                   clib_memcpy (n, nm->nodes[j], sizeof (*n));
680                   /* none of the copied nodes have enqueue rights given out */
681                   n->owner_node_index = VLIB_INVALID_NODE_INDEX;
682                   memset (&n->stats_total, 0, sizeof (n->stats_total));
683                   memset (&n->stats_last_clear, 0,
684                           sizeof (n->stats_last_clear));
685                   vec_add1 (nm_clone->nodes, n);
686                 }
687               nm_clone->nodes_by_type[VLIB_NODE_TYPE_INTERNAL] =
688                 vec_dup (nm->nodes_by_type[VLIB_NODE_TYPE_INTERNAL]);
689
690               nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT] =
691                 vec_dup (nm->nodes_by_type[VLIB_NODE_TYPE_INPUT]);
692               vec_foreach (rt, nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT])
693                 rt->cpu_index = vm_clone->cpu_index;
694
695               nm_clone->processes = vec_dup (nm->processes);
696
697               /* zap the (per worker) frame freelists, etc */
698               nm_clone->frame_sizes = 0;
699               nm_clone->frame_size_hash = 0;
700
701               /* Packet trace buffers are guaranteed to be empty, nothing to do here */
702
703               clib_mem_set_heap (oldheap);
704               vec_add1 (vlib_mains, vm_clone);
705
706               vm_clone->error_main.counters =
707                 vec_dup (vlib_mains[0]->error_main.counters);
708               vm_clone->error_main.counters_last_clear =
709                 vec_dup (vlib_mains[0]->error_main.counters_last_clear);
710
711               /* Fork the vlib_buffer_main_t free lists, etc. */
712               bm_clone = vec_dup (vm_clone->buffer_main);
713               vm_clone->buffer_main = bm_clone;
714
715               orig_freelist_pool = bm_clone->buffer_free_list_pool;
716               bm_clone->buffer_free_list_pool = 0;
717
718             /* *INDENT-OFF* */
719             pool_foreach (fl_orig, orig_freelist_pool,
720                           ({
721                             pool_get_aligned (bm_clone->buffer_free_list_pool,
722                                               fl_clone, CLIB_CACHE_LINE_BYTES);
723                             ASSERT (fl_orig - orig_freelist_pool
724                                     == fl_clone - bm_clone->buffer_free_list_pool);
725
726                             fl_clone[0] = fl_orig[0];
727                             fl_clone->aligned_buffers = 0;
728                             fl_clone->unaligned_buffers = 0;
729                             fl_clone->n_alloc = 0;
730                           }));
731 /* *INDENT-ON* */
732
733               worker_thread_index++;
734             }
735         }
736     }
737   else
738     {
739       /* only have non-data-structure copy threads to create... */
740       for (i = 0; i < vec_len (tm->registrations); i++)
741         {
742           tr = tm->registrations[i];
743
744           for (j = 0; j < tr->count; j++)
745             {
746               vec_add2 (vlib_worker_threads, w, 1);
747               if (tr->mheap_size)
748                 w->thread_mheap =
749                   mheap_alloc (0 /* use VM */ , tr->mheap_size);
750               else
751                 w->thread_mheap = main_heap;
752               w->thread_stack = vlib_thread_stacks[w - vlib_worker_threads];
753               w->thread_function = tr->function;
754               w->thread_function_arg = w;
755               w->instance_id = j;
756               w->elog_track.name =
757                 (char *) format (0, "%s %d", tr->name, j + 1);
758               w->registration = tr;
759               vec_add1 (w->elog_track.name, 0);
760               elog_track_register (&vm->elog_main, &w->elog_track);
761             }
762         }
763     }
764
765   worker_thread_index = 1;
766
767   for (i = 0; i < vec_len (tm->registrations); i++)
768     {
769       int j;
770
771       tr = tm->registrations[i];
772
773       if (tr->use_pthreads || tm->use_pthreads)
774         {
775           for (j = 0; j < tr->count; j++)
776             {
777               w = vlib_worker_threads + worker_thread_index++;
778               if (vlib_launch_thread (vlib_worker_thread_bootstrap_fn, w, 0) <
779                   0)
780                 clib_warning ("Couldn't start '%s' pthread ", tr->name);
781             }
782         }
783       else
784         {
785           uword c;
786             /* *INDENT-OFF* */
787             clib_bitmap_foreach (c, tr->coremask, ({
788               w = vlib_worker_threads + worker_thread_index++;
789               if (vlib_launch_thread (vlib_worker_thread_bootstrap_fn, w, c) < 0)
790                 clib_warning ("Couldn't start DPDK lcore %d", c);
791
792             }));
793 /* *INDENT-ON* */
794         }
795     }
796   vlib_worker_thread_barrier_sync (vm);
797   vlib_worker_thread_barrier_release (vm);
798   return 0;
799 }
800
801 VLIB_MAIN_LOOP_ENTER_FUNCTION (start_workers);
802
803 void
804 vlib_worker_thread_node_runtime_update (void)
805 {
806   int i, j;
807   vlib_worker_thread_t *w;
808   vlib_main_t *vm;
809   vlib_node_main_t *nm, *nm_clone;
810   vlib_node_t **old_nodes_clone;
811   vlib_main_t *vm_clone;
812   vlib_node_runtime_t *rt, *old_rt;
813   void *oldheap;
814   never_inline void
815     vlib_node_runtime_sync_stats (vlib_main_t * vm,
816                                   vlib_node_runtime_t * r,
817                                   uword n_calls,
818                                   uword n_vectors, uword n_clocks);
819
820   ASSERT (os_get_cpu_number () == 0);
821
822   if (vec_len (vlib_mains) == 0)
823     return;
824
825   vm = vlib_mains[0];
826   nm = &vm->node_main;
827
828   ASSERT (os_get_cpu_number () == 0);
829   ASSERT (*vlib_worker_threads->wait_at_barrier == 1);
830
831   /*
832    * Scrape all runtime stats, so we don't lose node runtime(s) with
833    * pending counts, or throw away worker / io thread counts.
834    */
835   for (j = 0; j < vec_len (nm->nodes); j++)
836     {
837       vlib_node_t *n;
838       n = nm->nodes[j];
839       vlib_node_sync_stats (vm, n);
840     }
841
842   for (i = 1; i < vec_len (vlib_mains); i++)
843     {
844       vlib_node_t *n;
845
846       vm_clone = vlib_mains[i];
847       nm_clone = &vm_clone->node_main;
848
849       for (j = 0; j < vec_len (nm_clone->nodes); j++)
850         {
851           n = nm_clone->nodes[j];
852
853           rt = vlib_node_get_runtime (vm_clone, n->index);
854           vlib_node_runtime_sync_stats (vm_clone, rt, 0, 0, 0);
855         }
856     }
857
858   for (i = 1; i < vec_len (vlib_mains); i++)
859     {
860       vlib_node_runtime_t *rt;
861       w = vlib_worker_threads + i;
862       oldheap = clib_mem_set_heap (w->thread_mheap);
863
864       vm_clone = vlib_mains[i];
865
866       /* Re-clone error heap */
867       u64 *old_counters = vm_clone->error_main.counters;
868       u64 *old_counters_all_clear = vm_clone->error_main.counters_last_clear;
869       clib_memcpy (&vm_clone->error_main, &vm->error_main,
870                    sizeof (vm->error_main));
871       j = vec_len (vm->error_main.counters) - 1;
872       vec_validate_aligned (old_counters, j, CLIB_CACHE_LINE_BYTES);
873       vec_validate_aligned (old_counters_all_clear, j, CLIB_CACHE_LINE_BYTES);
874       vm_clone->error_main.counters = old_counters;
875       vm_clone->error_main.counters_last_clear = old_counters_all_clear;
876
877       nm_clone = &vm_clone->node_main;
878       vec_free (nm_clone->next_frames);
879       nm_clone->next_frames = vec_dup (nm->next_frames);
880
881       for (j = 0; j < vec_len (nm_clone->next_frames); j++)
882         {
883           vlib_next_frame_t *nf = &nm_clone->next_frames[j];
884           u32 save_node_runtime_index;
885           u32 save_flags;
886
887           save_node_runtime_index = nf->node_runtime_index;
888           save_flags = nf->flags & VLIB_FRAME_NO_FREE_AFTER_DISPATCH;
889           vlib_next_frame_init (nf);
890           nf->node_runtime_index = save_node_runtime_index;
891           nf->flags = save_flags;
892         }
893
894       old_nodes_clone = nm_clone->nodes;
895       nm_clone->nodes = 0;
896
897       /* re-fork nodes */
898       for (j = 0; j < vec_len (nm->nodes); j++)
899         {
900           vlib_node_t *old_n_clone;
901           vlib_node_t *new_n, *new_n_clone;
902
903           new_n = nm->nodes[j];
904           old_n_clone = old_nodes_clone[j];
905
906           new_n_clone = clib_mem_alloc_no_fail (sizeof (*new_n_clone));
907           clib_memcpy (new_n_clone, new_n, sizeof (*new_n));
908           /* none of the copied nodes have enqueue rights given out */
909           new_n_clone->owner_node_index = VLIB_INVALID_NODE_INDEX;
910
911           if (j >= vec_len (old_nodes_clone))
912             {
913               /* new node, set to zero */
914               memset (&new_n_clone->stats_total, 0,
915                       sizeof (new_n_clone->stats_total));
916               memset (&new_n_clone->stats_last_clear, 0,
917                       sizeof (new_n_clone->stats_last_clear));
918             }
919           else
920             {
921               /* Copy stats if the old data is valid */
922               clib_memcpy (&new_n_clone->stats_total,
923                            &old_n_clone->stats_total,
924                            sizeof (new_n_clone->stats_total));
925               clib_memcpy (&new_n_clone->stats_last_clear,
926                            &old_n_clone->stats_last_clear,
927                            sizeof (new_n_clone->stats_last_clear));
928
929               /* keep previous node state */
930               new_n_clone->state = old_n_clone->state;
931             }
932           vec_add1 (nm_clone->nodes, new_n_clone);
933         }
934       /* Free the old node clone */
935       for (j = 0; j < vec_len (old_nodes_clone); j++)
936         clib_mem_free (old_nodes_clone[j]);
937       vec_free (old_nodes_clone);
938
939       vec_free (nm_clone->nodes_by_type[VLIB_NODE_TYPE_INTERNAL]);
940
941       nm_clone->nodes_by_type[VLIB_NODE_TYPE_INTERNAL] =
942         vec_dup (nm->nodes_by_type[VLIB_NODE_TYPE_INTERNAL]);
943
944       /* clone input node runtime */
945       old_rt = nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT];
946
947       nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT] =
948         vec_dup (nm->nodes_by_type[VLIB_NODE_TYPE_INPUT]);
949
950       vec_foreach (rt, nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT])
951       {
952         rt->cpu_index = vm_clone->cpu_index;
953       }
954
955       for (j = 0; j < vec_len (old_rt); j++)
956         {
957           rt = vlib_node_get_runtime (vm_clone, old_rt[j].node_index);
958           rt->state = old_rt[j].state;
959         }
960
961       vec_free (old_rt);
962
963       nm_clone->processes = vec_dup (nm->processes);
964
965       clib_mem_set_heap (oldheap);
966
967       // vnet_main_fork_fixup (i);
968     }
969 }
970
971 u32
972 unformat_sched_policy (unformat_input_t * input, va_list * args)
973 {
974   u32 *r = va_arg (*args, u32 *);
975
976   if (0);
977 #define _(v,f,s) else if (unformat (input, s)) *r = SCHED_POLICY_##f;
978   foreach_sched_policy
979 #undef _
980     else
981     return 0;
982   return 1;
983 }
984
985 static clib_error_t *
986 cpu_config (vlib_main_t * vm, unformat_input_t * input)
987 {
988   vlib_thread_registration_t *tr;
989   uword *p;
990   vlib_thread_main_t *tm = &vlib_thread_main;
991   u8 *name;
992   u64 coremask;
993   uword *bitmap;
994   u32 count;
995
996   tm->thread_registrations_by_name = hash_create_string (0, sizeof (uword));
997
998   tm->n_thread_stacks = 1;      /* account for main thread */
999   tm->sched_policy = ~0;
1000   tm->sched_priority = ~0;
1001
1002   tr = tm->next;
1003
1004   while (tr)
1005     {
1006       hash_set_mem (tm->thread_registrations_by_name, tr->name, (uword) tr);
1007       tr = tr->next;
1008     }
1009
1010   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1011     {
1012       if (unformat (input, "use-pthreads"))
1013         tm->use_pthreads = 1;
1014       else if (unformat (input, "thread-prefix %v", &tm->thread_prefix))
1015         ;
1016       else if (unformat (input, "main-core %u", &tm->main_lcore))
1017         ;
1018       else if (unformat (input, "skip-cores %u", &tm->skip_cores))
1019         ;
1020       else if (unformat (input, "coremask-%s %llx", &name, &coremask))
1021         {
1022           p = hash_get_mem (tm->thread_registrations_by_name, name);
1023           if (p == 0)
1024             return clib_error_return (0, "no such thread type '%s'", name);
1025
1026           tr = (vlib_thread_registration_t *) p[0];
1027
1028           if (tr->use_pthreads)
1029             return clib_error_return (0,
1030                                       "coremask cannot be set for '%s' threads",
1031                                       name);
1032
1033           tr->coremask = clib_bitmap_set_multiple
1034             (tr->coremask, 0, coremask, BITS (coremask));
1035           tr->count = clib_bitmap_count_set_bits (tr->coremask);
1036         }
1037       else if (unformat (input, "corelist-%s %U", &name, unformat_bitmap_list,
1038                          &bitmap))
1039         {
1040           p = hash_get_mem (tm->thread_registrations_by_name, name);
1041           if (p == 0)
1042             return clib_error_return (0, "no such thread type '%s'", name);
1043
1044           tr = (vlib_thread_registration_t *) p[0];
1045
1046           if (tr->use_pthreads)
1047             return clib_error_return (0,
1048                                       "corelist cannot be set for '%s' threads",
1049                                       name);
1050
1051           tr->coremask = bitmap;
1052           tr->count = clib_bitmap_count_set_bits (tr->coremask);
1053         }
1054       else
1055         if (unformat
1056             (input, "scheduler-policy %U", unformat_sched_policy,
1057              &tm->sched_policy))
1058         ;
1059       else if (unformat (input, "scheduler-priority %u", &tm->sched_priority))
1060         ;
1061       else if (unformat (input, "%s %u", &name, &count))
1062         {
1063           p = hash_get_mem (tm->thread_registrations_by_name, name);
1064           if (p == 0)
1065             return clib_error_return (0, "no such thread type 3 '%s'", name);
1066
1067           tr = (vlib_thread_registration_t *) p[0];
1068           if (tr->fixed_count)
1069             return clib_error_return
1070               (0, "number of %s threads not configurable", tr->name);
1071           tr->count = count;
1072         }
1073       else
1074         break;
1075     }
1076
1077   if (tm->sched_priority != ~0)
1078     {
1079       if (tm->sched_policy == SCHED_FIFO || tm->sched_policy == SCHED_RR)
1080         {
1081           u32 prio_max = sched_get_priority_max (tm->sched_policy);
1082           u32 prio_min = sched_get_priority_min (tm->sched_policy);
1083           if (tm->sched_priority > prio_max)
1084             tm->sched_priority = prio_max;
1085           if (tm->sched_priority < prio_min)
1086             tm->sched_priority = prio_min;
1087         }
1088       else
1089         {
1090           return clib_error_return
1091             (0,
1092              "scheduling priority (%d) is not allowed for `normal` scheduling policy",
1093              tm->sched_priority);
1094         }
1095     }
1096   tr = tm->next;
1097
1098   if (!tm->thread_prefix)
1099     tm->thread_prefix = format (0, "vpp");
1100
1101   while (tr)
1102     {
1103       tm->n_thread_stacks += tr->count;
1104       tm->n_pthreads += tr->count * tr->use_pthreads;
1105       tm->n_eal_threads += tr->count * (tr->use_pthreads == 0);
1106       tr = tr->next;
1107     }
1108
1109   return 0;
1110 }
1111
1112 VLIB_EARLY_CONFIG_FUNCTION (cpu_config, "cpu");
1113
1114 #if !defined (__x86_64__) && !defined (__aarch64__) && !defined (__powerpc64__) && !defined(__arm__)
1115 void
1116 __sync_fetch_and_add_8 (void)
1117 {
1118   fformat (stderr, "%s called\n", __FUNCTION__);
1119   abort ();
1120 }
1121
1122 void
1123 __sync_add_and_fetch_8 (void)
1124 {
1125   fformat (stderr, "%s called\n", __FUNCTION__);
1126   abort ();
1127 }
1128 #endif
1129
1130 void vnet_main_fixup (vlib_fork_fixup_t which) __attribute__ ((weak));
1131 void
1132 vnet_main_fixup (vlib_fork_fixup_t which)
1133 {
1134 }
1135
1136 void
1137 vlib_worker_thread_fork_fixup (vlib_fork_fixup_t which)
1138 {
1139   vlib_main_t *vm = vlib_get_main ();
1140
1141   if (vlib_mains == 0)
1142     return;
1143
1144   ASSERT (os_get_cpu_number () == 0);
1145   vlib_worker_thread_barrier_sync (vm);
1146
1147   switch (which)
1148     {
1149     case VLIB_WORKER_THREAD_FORK_FIXUP_NEW_SW_IF_INDEX:
1150       vnet_main_fixup (VLIB_WORKER_THREAD_FORK_FIXUP_NEW_SW_IF_INDEX);
1151       break;
1152
1153     default:
1154       ASSERT (0);
1155     }
1156   vlib_worker_thread_barrier_release (vm);
1157 }
1158
1159 void
1160 vlib_worker_thread_barrier_sync (vlib_main_t * vm)
1161 {
1162   f64 deadline;
1163   u32 count;
1164
1165   if (!vlib_mains)
1166     return;
1167
1168   count = vec_len (vlib_mains) - 1;
1169
1170   /* Tolerate recursive calls */
1171   if (++vlib_worker_threads[0].recursion_level > 1)
1172     return;
1173
1174   vlib_worker_threads[0].barrier_sync_count++;
1175
1176   ASSERT (os_get_cpu_number () == 0);
1177
1178   deadline = vlib_time_now (vm) + BARRIER_SYNC_TIMEOUT;
1179
1180   *vlib_worker_threads->wait_at_barrier = 1;
1181   while (*vlib_worker_threads->workers_at_barrier != count)
1182     {
1183       if (vlib_time_now (vm) > deadline)
1184         {
1185           fformat (stderr, "%s: worker thread deadlock\n", __FUNCTION__);
1186           os_panic ();
1187         }
1188     }
1189 }
1190
1191 void
1192 vlib_worker_thread_barrier_release (vlib_main_t * vm)
1193 {
1194   f64 deadline;
1195
1196   if (!vlib_mains)
1197     return;
1198
1199   if (--vlib_worker_threads[0].recursion_level > 0)
1200     return;
1201
1202   deadline = vlib_time_now (vm) + BARRIER_SYNC_TIMEOUT;
1203
1204   *vlib_worker_threads->wait_at_barrier = 0;
1205
1206   while (*vlib_worker_threads->workers_at_barrier > 0)
1207     {
1208       if (vlib_time_now (vm) > deadline)
1209         {
1210           fformat (stderr, "%s: worker thread deadlock\n", __FUNCTION__);
1211           os_panic ();
1212         }
1213     }
1214 }
1215
1216 /*
1217  * Check the frame queue to see if any frames are available.
1218  * If so, pull the packets off the frames and put them to
1219  * the handoff node.
1220  */
1221 static inline int
1222 vlib_frame_queue_dequeue_internal (vlib_main_t * vm,
1223                                    vlib_frame_queue_main_t * fqm)
1224 {
1225   u32 thread_id = vm->cpu_index;
1226   vlib_frame_queue_t *fq = fqm->vlib_frame_queues[thread_id];
1227   vlib_frame_queue_elt_t *elt;
1228   u32 *from, *to;
1229   vlib_frame_t *f;
1230   int msg_type;
1231   int processed = 0;
1232   u32 n_left_to_node;
1233   u32 vectors = 0;
1234
1235   ASSERT (fq);
1236   ASSERT (vm == vlib_mains[thread_id]);
1237
1238   if (PREDICT_FALSE (fqm->node_index == ~0))
1239     return 0;
1240   /*
1241    * Gather trace data for frame queues
1242    */
1243   if (PREDICT_FALSE (fq->trace))
1244     {
1245       frame_queue_trace_t *fqt;
1246       frame_queue_nelt_counter_t *fqh;
1247       u32 elix;
1248
1249       fqt = &fqm->frame_queue_traces[thread_id];
1250
1251       fqt->nelts = fq->nelts;
1252       fqt->head = fq->head;
1253       fqt->head_hint = fq->head_hint;
1254       fqt->tail = fq->tail;
1255       fqt->threshold = fq->vector_threshold;
1256       fqt->n_in_use = fqt->tail - fqt->head;
1257       if (fqt->n_in_use >= fqt->nelts)
1258         {
1259           // if beyond max then use max
1260           fqt->n_in_use = fqt->nelts - 1;
1261         }
1262
1263       /* Record the number of elements in use in the histogram */
1264       fqh = &fqm->frame_queue_histogram[thread_id];
1265       fqh->count[fqt->n_in_use]++;
1266
1267       /* Record a snapshot of the elements in use */
1268       for (elix = 0; elix < fqt->nelts; elix++)
1269         {
1270           elt = fq->elts + ((fq->head + 1 + elix) & (fq->nelts - 1));
1271           if (1 || elt->valid)
1272             {
1273               fqt->n_vectors[elix] = elt->n_vectors;
1274             }
1275         }
1276       fqt->written = 1;
1277     }
1278
1279   while (1)
1280     {
1281       if (fq->head == fq->tail)
1282         {
1283           fq->head_hint = fq->head;
1284           return processed;
1285         }
1286
1287       elt = fq->elts + ((fq->head + 1) & (fq->nelts - 1));
1288
1289       if (!elt->valid)
1290         {
1291           fq->head_hint = fq->head;
1292           return processed;
1293         }
1294
1295       from = elt->buffer_index;
1296       msg_type = elt->msg_type;
1297
1298       ASSERT (msg_type == VLIB_FRAME_QUEUE_ELT_DISPATCH_FRAME);
1299       ASSERT (elt->n_vectors <= VLIB_FRAME_SIZE);
1300
1301       f = vlib_get_frame_to_node (vm, fqm->node_index);
1302
1303       to = vlib_frame_vector_args (f);
1304
1305       n_left_to_node = elt->n_vectors;
1306
1307       while (n_left_to_node >= 4)
1308         {
1309           to[0] = from[0];
1310           to[1] = from[1];
1311           to[2] = from[2];
1312           to[3] = from[3];
1313           to += 4;
1314           from += 4;
1315           n_left_to_node -= 4;
1316         }
1317
1318       while (n_left_to_node > 0)
1319         {
1320           to[0] = from[0];
1321           to++;
1322           from++;
1323           n_left_to_node--;
1324         }
1325
1326       vectors += elt->n_vectors;
1327       f->n_vectors = elt->n_vectors;
1328       vlib_put_frame_to_node (vm, fqm->node_index, f);
1329
1330       elt->valid = 0;
1331       elt->n_vectors = 0;
1332       elt->msg_type = 0xfefefefe;
1333       CLIB_MEMORY_BARRIER ();
1334       fq->head++;
1335       processed++;
1336
1337       /*
1338        * Limit the number of packets pushed into the graph
1339        */
1340       if (vectors >= fq->vector_threshold)
1341         {
1342           fq->head_hint = fq->head;
1343           return processed;
1344         }
1345     }
1346   ASSERT (0);
1347   return processed;
1348 }
1349
1350 static_always_inline void
1351 vlib_worker_thread_internal (vlib_main_t * vm)
1352 {
1353   vlib_node_main_t *nm = &vm->node_main;
1354   vlib_thread_main_t *tm = vlib_get_thread_main ();
1355   u64 cpu_time_now = clib_cpu_time_now ();
1356   vlib_frame_queue_main_t *fqm;
1357
1358   vec_alloc (nm->pending_interrupt_node_runtime_indices, 32);
1359
1360   while (1)
1361     {
1362       vlib_worker_thread_barrier_check ();
1363
1364       vec_foreach (fqm, tm->frame_queue_mains)
1365         vlib_frame_queue_dequeue_internal (vm, fqm);
1366
1367       vlib_node_runtime_t *n;
1368       vec_foreach (n, nm->nodes_by_type[VLIB_NODE_TYPE_INPUT])
1369       {
1370         cpu_time_now = dispatch_node (vm, n, VLIB_NODE_TYPE_INPUT,
1371                                       VLIB_NODE_STATE_POLLING, /* frame */ 0,
1372                                       cpu_time_now);
1373       }
1374
1375       /* Next handle interrupts. */
1376       {
1377         uword l = _vec_len (nm->pending_interrupt_node_runtime_indices);
1378         uword i;
1379         if (l > 0)
1380           {
1381             _vec_len (nm->pending_interrupt_node_runtime_indices) = 0;
1382             for (i = 0; i < l; i++)
1383               {
1384                 n = vec_elt_at_index (nm->nodes_by_type[VLIB_NODE_TYPE_INPUT],
1385                                       nm->
1386                                       pending_interrupt_node_runtime_indices
1387                                       [i]);
1388                 cpu_time_now =
1389                   dispatch_node (vm, n, VLIB_NODE_TYPE_INPUT,
1390                                  VLIB_NODE_STATE_INTERRUPT,
1391                                  /* frame */ 0,
1392                                  cpu_time_now);
1393               }
1394           }
1395       }
1396
1397       if (_vec_len (nm->pending_frames))
1398         {
1399           int i;
1400           cpu_time_now = clib_cpu_time_now ();
1401           for (i = 0; i < _vec_len (nm->pending_frames); i++)
1402             {
1403               vlib_pending_frame_t *p;
1404
1405               p = nm->pending_frames + i;
1406
1407               cpu_time_now = dispatch_pending_node (vm, p, cpu_time_now);
1408             }
1409           _vec_len (nm->pending_frames) = 0;
1410         }
1411       vlib_increment_main_loop_counter (vm);
1412
1413       /* Record time stamp in case there are no enabled nodes and above
1414          calls do not update time stamp. */
1415       cpu_time_now = clib_cpu_time_now ();
1416     }
1417 }
1418
1419 void
1420 vlib_worker_thread_fn (void *arg)
1421 {
1422   vlib_worker_thread_t *w = (vlib_worker_thread_t *) arg;
1423   vlib_main_t *vm = vlib_get_main ();
1424
1425   ASSERT (vm->cpu_index == os_get_cpu_number ());
1426
1427   vlib_worker_thread_init (w);
1428   clib_time_init (&vm->clib_time);
1429   clib_mem_set_heap (w->thread_mheap);
1430
1431 #if DPDK > 0
1432   /* Wait until the dpdk init sequence is complete */
1433   vlib_thread_main_t *tm = vlib_get_thread_main ();
1434   while (tm->worker_thread_release == 0)
1435     vlib_worker_thread_barrier_check ();
1436 #endif
1437
1438   vlib_worker_thread_internal (vm);
1439 }
1440
1441 /* *INDENT-OFF* */
1442 VLIB_REGISTER_THREAD (worker_thread_reg, static) = {
1443   .name = "workers",
1444   .short_name = "wk",
1445   .function = vlib_worker_thread_fn,
1446 };
1447 /* *INDENT-ON* */
1448
1449 u32
1450 vlib_frame_queue_main_init (u32 node_index, u32 frame_queue_nelts)
1451 {
1452   vlib_thread_main_t *tm = vlib_get_thread_main ();
1453   vlib_frame_queue_main_t *fqm;
1454   vlib_frame_queue_t *fq;
1455   int i;
1456
1457   if (frame_queue_nelts == 0)
1458     frame_queue_nelts = FRAME_QUEUE_NELTS;
1459
1460   vec_add2 (tm->frame_queue_mains, fqm, 1);
1461
1462   fqm->node_index = node_index;
1463
1464   vec_validate (fqm->vlib_frame_queues, tm->n_vlib_mains - 1);
1465   _vec_len (fqm->vlib_frame_queues) = 0;
1466   for (i = 0; i < tm->n_vlib_mains; i++)
1467     {
1468       fq = vlib_frame_queue_alloc (frame_queue_nelts);
1469       vec_add1 (fqm->vlib_frame_queues, fq);
1470     }
1471
1472   return (fqm - tm->frame_queue_mains);
1473 }
1474
1475 clib_error_t *
1476 threads_init (vlib_main_t * vm)
1477 {
1478   return 0;
1479 }
1480
1481 VLIB_INIT_FUNCTION (threads_init);
1482
1483 /*
1484  * fd.io coding-style-patch-verification: ON
1485  *
1486  * Local Variables:
1487  * eval: (c-set-style "gnu")
1488  * End:
1489  */