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