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