vlib: flush rpcs on worker sync
[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 <vppinfra/time_range.h>
21 #include <vppinfra/interrupt.h>
22 #include <vppinfra/linux/sysfs.h>
23 #include <vlib/vlib.h>
24
25 #include <vlib/threads.h>
26
27 #include <vlib/stats/stats.h>
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 /*
39  * Barrier tracing can be enabled on a normal build to collect information
40  * on barrier use, including timings and call stacks.  Deliberately not
41  * keyed off CLIB_DEBUG, because that can add significant overhead which
42  * imapacts observed timings.
43  */
44
45 static inline void
46 barrier_trace_sync (f64 t_entry, f64 t_open, f64 t_closed)
47 {
48   if (!vlib_worker_threads->barrier_elog_enabled)
49     return;
50
51   ELOG_TYPE_DECLARE (e) = {
52     .format = "bar-trace-%s-#%d",
53     .format_args = "T4i4",
54   };
55
56   struct
57   {
58     u32 caller, count, t_entry, t_open, t_closed;
59   } *ed = 0;
60
61   ed = ELOG_DATA (&vlib_global_main.elog_main, e);
62   ed->count = (int) vlib_worker_threads[0].barrier_sync_count;
63   ed->caller = elog_string (&vlib_global_main.elog_main,
64                             (char *) vlib_worker_threads[0].barrier_caller);
65   ed->t_entry = (int) (1000000.0 * t_entry);
66   ed->t_open = (int) (1000000.0 * t_open);
67   ed->t_closed = (int) (1000000.0 * t_closed);
68 }
69
70 static inline void
71 barrier_trace_sync_rec (f64 t_entry)
72 {
73   if (!vlib_worker_threads->barrier_elog_enabled)
74     return;
75
76   ELOG_TYPE_DECLARE (e) = {
77     .format = "bar-syncrec-%s-#%d",
78     .format_args = "T4i4",
79   };
80
81   struct
82   {
83     u32 caller, depth;
84   } *ed = 0;
85
86   ed = ELOG_DATA (&vlib_global_main.elog_main, e);
87   ed->depth = (int) vlib_worker_threads[0].recursion_level - 1;
88   ed->caller = elog_string (&vlib_global_main.elog_main,
89                             (char *) vlib_worker_threads[0].barrier_caller);
90 }
91
92 static inline void
93 barrier_trace_release_rec (f64 t_entry)
94 {
95   if (!vlib_worker_threads->barrier_elog_enabled)
96     return;
97
98   ELOG_TYPE_DECLARE (e) = {
99     .format = "bar-relrrec-#%d",
100     .format_args = "i4",
101   };
102
103   struct
104   {
105     u32 depth;
106   } *ed = 0;
107
108   ed = ELOG_DATA (&vlib_global_main.elog_main, e);
109   ed->depth = (int) vlib_worker_threads[0].recursion_level;
110 }
111
112 static inline void
113 barrier_trace_release (f64 t_entry, f64 t_closed_total, f64 t_update_main)
114 {
115   if (!vlib_worker_threads->barrier_elog_enabled)
116     return;
117
118   ELOG_TYPE_DECLARE (e) = {
119     .format = "bar-rel-#%d-e%d-u%d-t%d",
120     .format_args = "i4i4i4i4",
121   };
122
123   struct
124   {
125     u32 count, t_entry, t_update_main, t_closed_total;
126   } *ed = 0;
127
128   ed = ELOG_DATA (&vlib_global_main.elog_main, e);
129   ed->t_entry = (int) (1000000.0 * t_entry);
130   ed->t_update_main = (int) (1000000.0 * t_update_main);
131   ed->t_closed_total = (int) (1000000.0 * t_closed_total);
132   ed->count = (int) vlib_worker_threads[0].barrier_sync_count;
133
134   /* Reset context for next trace */
135   vlib_worker_threads[0].barrier_context = NULL;
136 }
137
138 uword
139 os_get_nthreads (void)
140 {
141   return vec_len (vlib_thread_stacks);
142 }
143
144 void
145 vlib_set_thread_name (char *name)
146 {
147   int pthread_setname_np (pthread_t __target_thread, const char *__name);
148   int rv;
149   pthread_t thread = pthread_self ();
150
151   if (thread)
152     {
153       rv = pthread_setname_np (thread, name);
154       if (rv)
155         clib_warning ("pthread_setname_np returned %d", rv);
156     }
157 }
158
159 static int
160 sort_registrations_by_no_clone (void *a0, void *a1)
161 {
162   vlib_thread_registration_t **tr0 = a0;
163   vlib_thread_registration_t **tr1 = a1;
164
165   return ((i32) ((*tr0)->no_data_structure_clone)
166           - ((i32) ((*tr1)->no_data_structure_clone)));
167 }
168
169
170 /* Called early in the init sequence */
171
172 clib_error_t *
173 vlib_thread_init (vlib_main_t * vm)
174 {
175   vlib_thread_main_t *tm = &vlib_thread_main;
176   vlib_worker_thread_t *w;
177   vlib_thread_registration_t *tr;
178   u32 n_vlib_mains = 1;
179   u32 first_index = 1;
180   u32 i;
181   uword *avail_cpu;
182   u32 stats_num_worker_threads_dir_index;
183
184   stats_num_worker_threads_dir_index =
185     vlib_stats_add_gauge ("/sys/num_worker_threads");
186   ASSERT (stats_num_worker_threads_dir_index != ~0);
187
188   /* get bitmaps of active cpu cores and sockets */
189   tm->cpu_core_bitmap =
190     clib_sysfs_list_to_bitmap ("/sys/devices/system/cpu/online");
191   tm->cpu_socket_bitmap =
192     clib_sysfs_list_to_bitmap ("/sys/devices/system/node/online");
193
194   avail_cpu = clib_bitmap_dup (tm->cpu_core_bitmap);
195
196   /* skip cores */
197   for (i = 0; i < tm->skip_cores; i++)
198     {
199       uword c = clib_bitmap_first_set (avail_cpu);
200       if (c == ~0)
201         return clib_error_return (0, "no available cpus to skip");
202
203       avail_cpu = clib_bitmap_set (avail_cpu, c, 0);
204     }
205
206   /* grab cpu for main thread */
207   if (tm->main_lcore != ~0)
208     {
209       if (clib_bitmap_get (avail_cpu, tm->main_lcore) == 0)
210         return clib_error_return (0, "cpu %u is not available to be used"
211                                   " for the main thread", tm->main_lcore);
212       avail_cpu = clib_bitmap_set (avail_cpu, tm->main_lcore, 0);
213     }
214
215   /* assume that there is socket 0 only if there is no data from sysfs */
216   if (!tm->cpu_socket_bitmap)
217     tm->cpu_socket_bitmap = clib_bitmap_set (0, 0, 1);
218
219   /* pin main thread to main_lcore  */
220   if (tm->main_lcore != ~0)
221     {
222       cpu_set_t cpuset;
223       CPU_ZERO (&cpuset);
224       CPU_SET (tm->main_lcore, &cpuset);
225       if (pthread_setaffinity_np (pthread_self (), sizeof (cpu_set_t),
226                                   &cpuset))
227         {
228           return clib_error_return (0, "could not pin main thread to cpu %u",
229                                     tm->main_lcore);
230         }
231     }
232
233   /* Set up thread 0 */
234   vec_validate_aligned (vlib_worker_threads, 0, CLIB_CACHE_LINE_BYTES);
235   vec_set_len (vlib_worker_threads, 1);
236   w = vlib_worker_threads;
237   w->thread_mheap = clib_mem_get_heap ();
238   w->thread_stack = vlib_thread_stacks[0];
239   w->cpu_id = tm->main_lcore;
240   w->lwp = syscall (SYS_gettid);
241   w->thread_id = pthread_self ();
242   tm->n_vlib_mains = 1;
243
244   vlib_get_thread_core_numa (w, w->cpu_id);
245
246   if (tm->sched_policy != ~0)
247     {
248       struct sched_param sched_param;
249       if (!sched_getparam (w->lwp, &sched_param))
250         {
251           if (tm->sched_priority != ~0)
252             sched_param.sched_priority = tm->sched_priority;
253           sched_setscheduler (w->lwp, tm->sched_policy, &sched_param);
254         }
255     }
256
257   /* assign threads to cores and set n_vlib_mains */
258   tr = tm->next;
259
260   while (tr)
261     {
262       vec_add1 (tm->registrations, tr);
263       tr = tr->next;
264     }
265
266   vec_sort_with_function (tm->registrations, sort_registrations_by_no_clone);
267
268   for (i = 0; i < vec_len (tm->registrations); i++)
269     {
270       int j;
271       tr = tm->registrations[i];
272       tr->first_index = first_index;
273       first_index += tr->count;
274       n_vlib_mains += (tr->no_data_structure_clone == 0) ? tr->count : 0;
275
276       /* construct coremask */
277       if (tr->use_pthreads || !tr->count)
278         continue;
279
280       if (tr->coremask)
281         {
282           uword c;
283           /* *INDENT-OFF* */
284           clib_bitmap_foreach (c, tr->coremask)  {
285             if (clib_bitmap_get(avail_cpu, c) == 0)
286               return clib_error_return (0, "cpu %u is not available to be used"
287                                         " for the '%s' thread",c, tr->name);
288
289             avail_cpu = clib_bitmap_set(avail_cpu, c, 0);
290           }
291           /* *INDENT-ON* */
292         }
293       else
294         {
295           for (j = 0; j < tr->count; j++)
296             {
297               /* Do not use CPU 0 by default - leave it to the host and IRQs */
298               uword avail_c0 = clib_bitmap_get (avail_cpu, 0);
299               avail_cpu = clib_bitmap_set (avail_cpu, 0, 0);
300
301               uword c = clib_bitmap_first_set (avail_cpu);
302               /* Use CPU 0 as a last resort */
303               if (c == ~0 && avail_c0)
304                 {
305                   c = 0;
306                   avail_c0 = 0;
307                 }
308
309               if (c == ~0)
310                 return clib_error_return (0,
311                                           "no available cpus to be used for"
312                                           " the '%s' thread #%u",
313                                           tr->name, tr->count);
314
315               avail_cpu = clib_bitmap_set (avail_cpu, 0, avail_c0);
316               avail_cpu = clib_bitmap_set (avail_cpu, c, 0);
317               tr->coremask = clib_bitmap_set (tr->coremask, c, 1);
318             }
319         }
320     }
321
322   clib_bitmap_free (avail_cpu);
323
324   tm->n_vlib_mains = n_vlib_mains;
325   vlib_stats_set_gauge (stats_num_worker_threads_dir_index, n_vlib_mains - 1);
326
327   /*
328    * Allocate the remaining worker threads, and thread stack vector slots
329    * from now on, calls to os_get_nthreads() will return the correct
330    * answer.
331    */
332   vec_validate_aligned (vlib_worker_threads, first_index - 1,
333                         CLIB_CACHE_LINE_BYTES);
334   vec_validate (vlib_thread_stacks, vec_len (vlib_worker_threads) - 1);
335   return 0;
336 }
337
338 vlib_frame_queue_t *
339 vlib_frame_queue_alloc (int nelts)
340 {
341   vlib_frame_queue_t *fq;
342
343   fq = clib_mem_alloc_aligned (sizeof (*fq), CLIB_CACHE_LINE_BYTES);
344   clib_memset (fq, 0, sizeof (*fq));
345   fq->nelts = nelts;
346   fq->vector_threshold = 2 * VLIB_FRAME_SIZE;
347   vec_validate_aligned (fq->elts, nelts - 1, CLIB_CACHE_LINE_BYTES);
348
349   if (nelts & (nelts - 1))
350     {
351       fformat (stderr, "FATAL: nelts MUST be a power of 2\n");
352       abort ();
353     }
354
355   return (fq);
356 }
357
358 void vl_msg_api_handler_no_free (void *) __attribute__ ((weak));
359 void
360 vl_msg_api_handler_no_free (void *v)
361 {
362 }
363
364 /* To be called by vlib worker threads upon startup */
365 void
366 vlib_worker_thread_init (vlib_worker_thread_t * w)
367 {
368   vlib_thread_main_t *tm = vlib_get_thread_main ();
369
370   /*
371    * Note: disabling signals in worker threads as follows
372    * prevents the api post-mortem dump scheme from working
373    * {
374    *    sigset_t s;
375    *    sigfillset (&s);
376    *    pthread_sigmask (SIG_SETMASK, &s, 0);
377    *  }
378    */
379
380   clib_mem_set_heap (w->thread_mheap);
381
382   if (vec_len (tm->thread_prefix) && w->registration->short_name)
383     {
384       w->name = format (0, "%v_%s_%d%c", tm->thread_prefix,
385                         w->registration->short_name, w->instance_id, '\0');
386       vlib_set_thread_name ((char *) w->name);
387     }
388
389   if (!w->registration->use_pthreads)
390     {
391
392       /* Initial barrier sync, for both worker and i/o threads */
393       clib_atomic_fetch_add (vlib_worker_threads->workers_at_barrier, 1);
394
395       while (*vlib_worker_threads->wait_at_barrier)
396         ;
397
398       clib_atomic_fetch_add (vlib_worker_threads->workers_at_barrier, -1);
399     }
400 }
401
402 void *
403 vlib_worker_thread_bootstrap_fn (void *arg)
404 {
405   vlib_worker_thread_t *w = arg;
406
407   w->lwp = syscall (SYS_gettid);
408   w->thread_id = pthread_self ();
409
410   __os_thread_index = w - vlib_worker_threads;
411
412   if (CLIB_DEBUG > 0)
413     {
414       void *frame_addr = __builtin_frame_address (0);
415       if (frame_addr < (void *) w->thread_stack ||
416           frame_addr > (void *) w->thread_stack + VLIB_THREAD_STACK_SIZE)
417         {
418           /* heap is not set yet */
419           fprintf (stderr, "thread stack is not set properly\n");
420           exit (1);
421         }
422     }
423
424   w->thread_function (arg);
425
426   return 0;
427 }
428
429 void
430 vlib_get_thread_core_numa (vlib_worker_thread_t * w, unsigned cpu_id)
431 {
432   const char *sys_cpu_path = "/sys/devices/system/cpu/cpu";
433   const char *sys_node_path = "/sys/devices/system/node/node";
434   clib_bitmap_t *nbmp = 0, *cbmp = 0;
435   u32 node;
436   u8 *p = 0;
437   int core_id = -1, numa_id = -1;
438
439   p = format (p, "%s%u/topology/core_id%c", sys_cpu_path, cpu_id, 0);
440   clib_sysfs_read ((char *) p, "%d", &core_id);
441   vec_reset_length (p);
442
443   /* *INDENT-OFF* */
444   clib_sysfs_read ("/sys/devices/system/node/online", "%U",
445         unformat_bitmap_list, &nbmp);
446   clib_bitmap_foreach (node, nbmp)  {
447     p = format (p, "%s%u/cpulist%c", sys_node_path, node, 0);
448     clib_sysfs_read ((char *) p, "%U", unformat_bitmap_list, &cbmp);
449     if (clib_bitmap_get (cbmp, cpu_id))
450       numa_id = node;
451     vec_reset_length (cbmp);
452     vec_reset_length (p);
453   }
454   /* *INDENT-ON* */
455   vec_free (nbmp);
456   vec_free (cbmp);
457   vec_free (p);
458
459   w->core_id = core_id;
460   w->numa_id = numa_id;
461 }
462
463 static clib_error_t *
464 vlib_launch_thread_int (void *fp, vlib_worker_thread_t * w, unsigned cpu_id)
465 {
466   clib_mem_main_t *mm = &clib_mem_main;
467   vlib_thread_main_t *tm = &vlib_thread_main;
468   pthread_t worker;
469   pthread_attr_t attr;
470   cpu_set_t cpuset;
471   void *(*fp_arg) (void *) = fp;
472   void *numa_heap;
473
474   w->cpu_id = cpu_id;
475   vlib_get_thread_core_numa (w, cpu_id);
476
477   /* Set up NUMA-bound heap if indicated */
478   if (mm->per_numa_mheaps[w->numa_id] == 0)
479     {
480       /* If the user requested a NUMA heap, create it... */
481       if (tm->numa_heap_size)
482         {
483           clib_mem_set_numa_affinity (w->numa_id, 1 /* force */ );
484           numa_heap = clib_mem_create_heap (0 /* DIY */ , tm->numa_heap_size,
485                                             1 /* is_locked */ ,
486                                             "numa %u heap", w->numa_id);
487           clib_mem_set_default_numa_affinity ();
488           mm->per_numa_mheaps[w->numa_id] = numa_heap;
489         }
490       else
491         {
492           /* Or, use the main heap */
493           mm->per_numa_mheaps[w->numa_id] = w->thread_mheap;
494         }
495     }
496
497       CPU_ZERO (&cpuset);
498       CPU_SET (cpu_id, &cpuset);
499
500       if (pthread_attr_init (&attr))
501         return clib_error_return_unix (0, "pthread_attr_init");
502
503       if (pthread_attr_setstack (&attr, w->thread_stack,
504                                  VLIB_THREAD_STACK_SIZE))
505         return clib_error_return_unix (0, "pthread_attr_setstack");
506
507       if (pthread_create (&worker, &attr, fp_arg, (void *) w))
508         return clib_error_return_unix (0, "pthread_create");
509
510       if (pthread_setaffinity_np (worker, sizeof (cpu_set_t), &cpuset))
511         return clib_error_return_unix (0, "pthread_setaffinity_np");
512
513       if (pthread_attr_destroy (&attr))
514         return clib_error_return_unix (0, "pthread_attr_destroy");
515
516       return 0;
517 }
518
519 static clib_error_t *
520 start_workers (vlib_main_t * vm)
521 {
522   vlib_global_main_t *vgm = vlib_get_global_main ();
523   vlib_main_t *fvm = vlib_get_first_main ();
524   int i, j;
525   vlib_worker_thread_t *w;
526   vlib_main_t *vm_clone;
527   void *oldheap;
528   vlib_thread_main_t *tm = &vlib_thread_main;
529   vlib_thread_registration_t *tr;
530   vlib_node_runtime_t *rt;
531   u32 n_vlib_mains = tm->n_vlib_mains;
532   u32 worker_thread_index;
533   u32 stats_err_entry_index = fvm->error_main.stats_err_entry_index;
534   clib_mem_heap_t *main_heap = clib_mem_get_per_cpu_heap ();
535   vlib_stats_register_mem_heap (main_heap);
536
537   vec_reset_length (vlib_worker_threads);
538
539   /* Set up the main thread */
540   vec_add2_aligned (vlib_worker_threads, w, 1, CLIB_CACHE_LINE_BYTES);
541   w->elog_track.name = "main thread";
542   elog_track_register (vlib_get_elog_main (), &w->elog_track);
543
544   if (vec_len (tm->thread_prefix))
545     {
546       w->name = format (0, "%v_main%c", tm->thread_prefix, '\0');
547       vlib_set_thread_name ((char *) w->name);
548     }
549
550   vgm->elog_main.lock =
551     clib_mem_alloc_aligned (CLIB_CACHE_LINE_BYTES, CLIB_CACHE_LINE_BYTES);
552   vgm->elog_main.lock[0] = 0;
553
554   clib_callback_data_init (&vm->vlib_node_runtime_perf_callbacks,
555                            &vm->worker_thread_main_loop_callback_lock);
556
557   vec_validate_aligned (vgm->vlib_mains, n_vlib_mains - 1,
558                         CLIB_CACHE_LINE_BYTES);
559   vec_set_len (vgm->vlib_mains, 0);
560   vec_add1_aligned (vgm->vlib_mains, vm, CLIB_CACHE_LINE_BYTES);
561
562   if (n_vlib_mains > 1)
563     {
564       vlib_worker_threads->wait_at_barrier =
565         clib_mem_alloc_aligned (sizeof (u32), CLIB_CACHE_LINE_BYTES);
566       vlib_worker_threads->workers_at_barrier =
567         clib_mem_alloc_aligned (sizeof (u32), CLIB_CACHE_LINE_BYTES);
568
569       vlib_worker_threads->node_reforks_required =
570         clib_mem_alloc_aligned (sizeof (u32), CLIB_CACHE_LINE_BYTES);
571
572       /* We'll need the rpc vector lock... */
573       clib_spinlock_init (&vm->pending_rpc_lock);
574
575       /* Ask for an initial barrier sync */
576       *vlib_worker_threads->workers_at_barrier = 0;
577       *vlib_worker_threads->wait_at_barrier = 1;
578
579       /* Without update or refork */
580       *vlib_worker_threads->node_reforks_required = 0;
581       vgm->need_vlib_worker_thread_node_runtime_update = 0;
582
583       /* init timing */
584       vm->barrier_epoch = 0;
585       vm->barrier_no_close_before = 0;
586
587       worker_thread_index = 1;
588       clib_spinlock_init (&vm->worker_thread_main_loop_callback_lock);
589
590       for (i = 0; i < vec_len (tm->registrations); i++)
591         {
592           vlib_node_main_t *nm, *nm_clone;
593           int k;
594
595           tr = tm->registrations[i];
596
597           if (tr->count == 0)
598             continue;
599
600           for (k = 0; k < tr->count; k++)
601             {
602               vlib_node_t *n;
603               u64 **c;
604
605               vec_add2 (vlib_worker_threads, w, 1);
606               /* Currently unused, may not really work */
607               if (tr->mheap_size)
608                 w->thread_mheap = clib_mem_create_heap (0, tr->mheap_size,
609                                                         /* unlocked */ 0,
610                                                         "%s%d heap",
611                                                         tr->name, k);
612               else
613                 w->thread_mheap = main_heap;
614
615               w->thread_stack =
616                 vlib_thread_stack_init (w - vlib_worker_threads);
617               w->thread_function = tr->function;
618               w->thread_function_arg = w;
619               w->instance_id = k;
620               w->registration = tr;
621
622               w->elog_track.name =
623                 (char *) format (0, "%s %d", tr->name, k + 1);
624               vec_add1 (w->elog_track.name, 0);
625               elog_track_register (vlib_get_elog_main (), &w->elog_track);
626
627               if (tr->no_data_structure_clone)
628                 continue;
629
630               /* Fork vlib_global_main et al. Look for bugs here */
631               oldheap = clib_mem_set_heap (w->thread_mheap);
632
633               vm_clone = clib_mem_alloc_aligned (sizeof (*vm_clone),
634                                                  CLIB_CACHE_LINE_BYTES);
635               clib_memcpy (vm_clone, vlib_get_first_main (),
636                            sizeof (*vm_clone));
637
638               vm_clone->thread_index = worker_thread_index;
639               vm_clone->pending_rpc_requests = 0;
640               vec_validate (vm_clone->pending_rpc_requests, 0);
641               vec_set_len (vm_clone->pending_rpc_requests, 0);
642               clib_memset (&vm_clone->random_buffer, 0,
643                            sizeof (vm_clone->random_buffer));
644               clib_spinlock_init
645                 (&vm_clone->worker_thread_main_loop_callback_lock);
646               clib_callback_data_init
647                 (&vm_clone->vlib_node_runtime_perf_callbacks,
648                  &vm_clone->worker_thread_main_loop_callback_lock);
649
650               nm = &vlib_get_first_main ()->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_aligned (nm->next_frames,
654                                                        CLIB_CACHE_LINE_BYTES);
655               for (j = 0; j < vec_len (nm_clone->next_frames); j++)
656                 {
657                   vlib_next_frame_t *nf = &nm_clone->next_frames[j];
658                   u32 save_node_runtime_index;
659                   u32 save_flags;
660
661                   save_node_runtime_index = nf->node_runtime_index;
662                   save_flags = nf->flags & VLIB_FRAME_NO_FREE_AFTER_DISPATCH;
663                   vlib_next_frame_init (nf);
664                   nf->node_runtime_index = save_node_runtime_index;
665                   nf->flags = save_flags;
666                 }
667
668               /* fork the frame dispatch queue */
669               nm_clone->pending_frames = 0;
670               vec_validate (nm_clone->pending_frames, 10);
671               vec_set_len (nm_clone->pending_frames, 0);
672
673               /* fork nodes */
674               nm_clone->nodes = 0;
675
676               /* Allocate all nodes in single block for speed */
677               n = clib_mem_alloc_no_fail (vec_len (nm->nodes) * sizeof (*n));
678
679               for (j = 0; j < vec_len (nm->nodes); j++)
680                 {
681                   clib_memcpy (n, nm->nodes[j], sizeof (*n));
682                   /* none of the copied nodes have enqueue rights given out */
683                   n->owner_node_index = VLIB_INVALID_NODE_INDEX;
684                   clib_memset (&n->stats_total, 0, sizeof (n->stats_total));
685                   clib_memset (&n->stats_last_clear, 0,
686                                sizeof (n->stats_last_clear));
687                   vec_add1 (nm_clone->nodes, n);
688                   n++;
689                 }
690               nm_clone->nodes_by_type[VLIB_NODE_TYPE_INTERNAL] =
691                 vec_dup_aligned (nm->nodes_by_type[VLIB_NODE_TYPE_INTERNAL],
692                                  CLIB_CACHE_LINE_BYTES);
693               vec_foreach (rt,
694                            nm_clone->nodes_by_type[VLIB_NODE_TYPE_INTERNAL])
695               {
696                 vlib_node_t *n = vlib_get_node (vm, rt->node_index);
697                 /* copy initial runtime_data from node */
698                 if (n->runtime_data && n->runtime_data_bytes > 0)
699                   clib_memcpy (rt->runtime_data, n->runtime_data,
700                                clib_min (VLIB_NODE_RUNTIME_DATA_SIZE,
701                                          n->runtime_data_bytes));
702               }
703
704               nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT] =
705                 vec_dup_aligned (nm->nodes_by_type[VLIB_NODE_TYPE_INPUT],
706                                  CLIB_CACHE_LINE_BYTES);
707               clib_interrupt_init (
708                 &nm_clone->input_node_interrupts,
709                 vec_len (nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT]));
710               clib_interrupt_init (
711                 &nm_clone->pre_input_node_interrupts,
712                 vec_len (nm_clone->nodes_by_type[VLIB_NODE_TYPE_PRE_INPUT]));
713               vec_foreach (rt, nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT])
714               {
715                 vlib_node_t *n = vlib_get_node (vm, rt->node_index);
716                 /* copy initial runtime_data from node */
717                 if (n->runtime_data && n->runtime_data_bytes > 0)
718                   clib_memcpy (rt->runtime_data, n->runtime_data,
719                                clib_min (VLIB_NODE_RUNTIME_DATA_SIZE,
720                                          n->runtime_data_bytes));
721               }
722
723               nm_clone->nodes_by_type[VLIB_NODE_TYPE_PRE_INPUT] =
724                 vec_dup_aligned (nm->nodes_by_type[VLIB_NODE_TYPE_PRE_INPUT],
725                                  CLIB_CACHE_LINE_BYTES);
726               vec_foreach (rt,
727                            nm_clone->nodes_by_type[VLIB_NODE_TYPE_PRE_INPUT])
728               {
729                 vlib_node_t *n = vlib_get_node (vm, rt->node_index);
730                 /* copy initial runtime_data from node */
731                 if (n->runtime_data && n->runtime_data_bytes > 0)
732                   clib_memcpy (rt->runtime_data, n->runtime_data,
733                                clib_min (VLIB_NODE_RUNTIME_DATA_SIZE,
734                                          n->runtime_data_bytes));
735               }
736
737               nm_clone->processes = vec_dup_aligned (nm->processes,
738                                                      CLIB_CACHE_LINE_BYTES);
739
740               /* Create per-thread frame freelist */
741               nm_clone->frame_sizes = 0;
742               nm_clone->node_by_error = nm->node_by_error;
743
744               /* Packet trace buffers are guaranteed to be empty, nothing to do here */
745
746               clib_mem_set_heap (oldheap);
747               vec_add1_aligned (vgm->vlib_mains, vm_clone,
748                                 CLIB_CACHE_LINE_BYTES);
749
750               /* Switch to the stats segment ... */
751               vlib_stats_validate (stats_err_entry_index, worker_thread_index,
752                                    vec_len (fvm->error_main.counters) - 1);
753               c = vlib_stats_get_entry_data_pointer (stats_err_entry_index);
754               vm_clone->error_main.counters = c[worker_thread_index];
755
756               vm_clone->error_main.counters_last_clear = vec_dup_aligned (
757                 vlib_get_first_main ()->error_main.counters_last_clear,
758                 CLIB_CACHE_LINE_BYTES);
759
760               worker_thread_index++;
761             }
762         }
763     }
764   else
765     {
766       /* only have non-data-structure copy threads to create... */
767       for (i = 0; i < vec_len (tm->registrations); i++)
768         {
769           tr = tm->registrations[i];
770
771           for (j = 0; j < tr->count; j++)
772             {
773               vec_add2 (vlib_worker_threads, w, 1);
774               if (tr->mheap_size)
775                 {
776                   w->thread_mheap = clib_mem_create_heap (0, tr->mheap_size,
777                                                           /* locked */ 0,
778                                                           "%s%d heap",
779                                                           tr->name, j);
780                 }
781               else
782                 w->thread_mheap = main_heap;
783               w->thread_stack =
784                 vlib_thread_stack_init (w - vlib_worker_threads);
785               w->thread_function = tr->function;
786               w->thread_function_arg = w;
787               w->instance_id = j;
788               w->elog_track.name =
789                 (char *) format (0, "%s %d", tr->name, j + 1);
790               w->registration = tr;
791               vec_add1 (w->elog_track.name, 0);
792               elog_track_register (vlib_get_elog_main (), &w->elog_track);
793             }
794         }
795     }
796
797   worker_thread_index = 1;
798
799   for (i = 0; i < vec_len (tm->registrations); i++)
800     {
801       clib_error_t *err;
802       int j;
803
804       tr = tm->registrations[i];
805
806       if (tr->use_pthreads || tm->use_pthreads)
807         {
808           for (j = 0; j < tr->count; j++)
809             {
810
811               w = vlib_worker_threads + worker_thread_index++;
812               err = vlib_launch_thread_int (vlib_worker_thread_bootstrap_fn,
813                                             w, 0);
814               if (err)
815                 clib_unix_error ("%U, thread %s init on cpu %d failed",
816                                  format_clib_error, err, tr->name, 0);
817             }
818         }
819       else
820         {
821           uword c;
822           clib_bitmap_foreach (c, tr->coremask)  {
823             w = vlib_worker_threads + worker_thread_index++;
824             err = vlib_launch_thread_int (vlib_worker_thread_bootstrap_fn,
825                                           w, c);
826             if (err)
827               clib_unix_error ("%U, thread %s init on cpu %d failed",
828                                format_clib_error, err, tr->name, c);
829             }
830         }
831     }
832   vlib_worker_thread_barrier_sync (vm);
833   {
834     clib_error_t *err;
835     err = vlib_call_init_exit_functions (
836       vm, &vgm->num_workers_change_function_registrations, 1 /* call_once */,
837       1 /* is_global */);
838     if (err)
839       clib_error_report (err);
840   }
841   vlib_worker_thread_barrier_release (vm);
842   return 0;
843 }
844
845 VLIB_MAIN_LOOP_ENTER_FUNCTION (start_workers);
846
847
848 static inline void
849 worker_thread_node_runtime_update_internal (void)
850 {
851   int i, j;
852   vlib_main_t *vm;
853   vlib_node_main_t *nm, *nm_clone;
854   vlib_main_t *vm_clone;
855   vlib_node_runtime_t *rt;
856
857   ASSERT (vlib_get_thread_index () == 0);
858
859   vm = vlib_get_first_main ();
860   nm = &vm->node_main;
861
862   ASSERT (*vlib_worker_threads->wait_at_barrier == 1);
863
864   /*
865    * Scrape all runtime stats, so we don't lose node runtime(s) with
866    * pending counts, or throw away worker / io thread counts.
867    */
868   for (j = 0; j < vec_len (nm->nodes); j++)
869     {
870       vlib_node_t *n;
871       n = nm->nodes[j];
872       vlib_node_sync_stats (vm, n);
873     }
874
875   for (i = 1; i < vlib_get_n_threads (); i++)
876     {
877       vlib_node_t *n;
878
879       vm_clone = vlib_get_main_by_index (i);
880       nm_clone = &vm_clone->node_main;
881
882       for (j = 0; j < vec_len (nm_clone->nodes); j++)
883         {
884           n = nm_clone->nodes[j];
885
886           rt = vlib_node_get_runtime (vm_clone, n->index);
887           vlib_node_runtime_sync_stats (vm_clone, rt, 0, 0, 0);
888         }
889     }
890
891   /* Per-worker clone rebuilds are now done on each thread */
892 }
893
894
895 void
896 vlib_worker_thread_node_refork (void)
897 {
898   vlib_main_t *vm, *vm_clone;
899   vlib_node_main_t *nm, *nm_clone;
900   vlib_node_t **old_nodes_clone;
901   vlib_node_runtime_t *rt, *old_rt;
902   u64 **c;
903
904   vlib_node_t *new_n_clone;
905
906   int j;
907
908   vm = vlib_get_first_main ();
909   nm = &vm->node_main;
910   vm_clone = vlib_get_main ();
911   nm_clone = &vm_clone->node_main;
912
913   /* Re-clone error heap */
914   u64 *old_counters_all_clear = vm_clone->error_main.counters_last_clear;
915
916   clib_memcpy_fast (&vm_clone->error_main, &vm->error_main,
917                     sizeof (vm->error_main));
918   j = vec_len (vm->error_main.counters) - 1;
919
920   c = vlib_stats_get_entry_data_pointer (vm->error_main.stats_err_entry_index);
921   vm_clone->error_main.counters = c[vm_clone->thread_index];
922
923   vec_validate_aligned (old_counters_all_clear, j, CLIB_CACHE_LINE_BYTES);
924   vm_clone->error_main.counters_last_clear = old_counters_all_clear;
925
926   for (j = 0; j < vec_len (nm_clone->next_frames); j++)
927     {
928       vlib_next_frame_t *nf = &nm_clone->next_frames[j];
929       if ((nf->flags & VLIB_FRAME_IS_ALLOCATED) && nf->frame != NULL)
930         {
931           vlib_frame_t *f = nf->frame;
932           nf->frame = NULL;
933           vlib_frame_free (vm_clone, f);
934         }
935     }
936
937   vec_free (nm_clone->next_frames);
938   nm_clone->next_frames = vec_dup_aligned (nm->next_frames,
939                                            CLIB_CACHE_LINE_BYTES);
940
941   for (j = 0; j < vec_len (nm_clone->next_frames); j++)
942     {
943       vlib_next_frame_t *nf = &nm_clone->next_frames[j];
944       u32 save_node_runtime_index;
945       u32 save_flags;
946
947       save_node_runtime_index = nf->node_runtime_index;
948       save_flags = nf->flags & VLIB_FRAME_NO_FREE_AFTER_DISPATCH;
949       vlib_next_frame_init (nf);
950       nf->node_runtime_index = save_node_runtime_index;
951       nf->flags = save_flags;
952     }
953
954   old_nodes_clone = nm_clone->nodes;
955   nm_clone->nodes = 0;
956
957   /* re-fork nodes */
958
959   /* Allocate all nodes in single block for speed */
960   new_n_clone =
961     clib_mem_alloc_no_fail (vec_len (nm->nodes) * sizeof (*new_n_clone));
962   for (j = 0; j < vec_len (nm->nodes); j++)
963     {
964       vlib_node_t *new_n = nm->nodes[j];
965
966       clib_memcpy_fast (new_n_clone, new_n, sizeof (*new_n));
967       /* none of the copied nodes have enqueue rights given out */
968       new_n_clone->owner_node_index = VLIB_INVALID_NODE_INDEX;
969
970       if (j >= vec_len (old_nodes_clone))
971         {
972           /* new node, set to zero */
973           clib_memset (&new_n_clone->stats_total, 0,
974                        sizeof (new_n_clone->stats_total));
975           clib_memset (&new_n_clone->stats_last_clear, 0,
976                        sizeof (new_n_clone->stats_last_clear));
977         }
978       else
979         {
980           vlib_node_t *old_n_clone = old_nodes_clone[j];
981           /* Copy stats if the old data is valid */
982           clib_memcpy_fast (&new_n_clone->stats_total,
983                             &old_n_clone->stats_total,
984                             sizeof (new_n_clone->stats_total));
985           clib_memcpy_fast (&new_n_clone->stats_last_clear,
986                             &old_n_clone->stats_last_clear,
987                             sizeof (new_n_clone->stats_last_clear));
988
989           /* keep previous node state */
990           new_n_clone->state = old_n_clone->state;
991           new_n_clone->flags = old_n_clone->flags;
992         }
993       vec_add1 (nm_clone->nodes, new_n_clone);
994       new_n_clone++;
995     }
996   /* Free the old node clones */
997   clib_mem_free (old_nodes_clone[0]);
998
999   vec_free (old_nodes_clone);
1000
1001
1002   /* re-clone internal nodes */
1003   old_rt = nm_clone->nodes_by_type[VLIB_NODE_TYPE_INTERNAL];
1004   nm_clone->nodes_by_type[VLIB_NODE_TYPE_INTERNAL] =
1005     vec_dup_aligned (nm->nodes_by_type[VLIB_NODE_TYPE_INTERNAL],
1006                      CLIB_CACHE_LINE_BYTES);
1007
1008   vec_foreach (rt, nm_clone->nodes_by_type[VLIB_NODE_TYPE_INTERNAL])
1009   {
1010     vlib_node_t *n = vlib_get_node (vm, rt->node_index);
1011     /* copy runtime_data, will be overwritten later for existing rt */
1012     if (n->runtime_data && n->runtime_data_bytes > 0)
1013       clib_memcpy_fast (rt->runtime_data, n->runtime_data,
1014                         clib_min (VLIB_NODE_RUNTIME_DATA_SIZE,
1015                                   n->runtime_data_bytes));
1016   }
1017
1018   for (j = 0; j < vec_len (old_rt); j++)
1019     {
1020       rt = vlib_node_get_runtime (vm_clone, old_rt[j].node_index);
1021       rt->state = old_rt[j].state;
1022       rt->flags = old_rt[j].flags;
1023       clib_memcpy_fast (rt->runtime_data, old_rt[j].runtime_data,
1024                         VLIB_NODE_RUNTIME_DATA_SIZE);
1025     }
1026
1027   vec_free (old_rt);
1028
1029   /* re-clone input nodes */
1030   old_rt = nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT];
1031   nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT] =
1032     vec_dup_aligned (nm->nodes_by_type[VLIB_NODE_TYPE_INPUT],
1033                      CLIB_CACHE_LINE_BYTES);
1034   clib_interrupt_resize (
1035     &nm_clone->input_node_interrupts,
1036     vec_len (nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT]));
1037   clib_interrupt_resize (
1038     &nm_clone->pre_input_node_interrupts,
1039     vec_len (nm_clone->nodes_by_type[VLIB_NODE_TYPE_PRE_INPUT]));
1040
1041   vec_foreach (rt, nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT])
1042   {
1043     vlib_node_t *n = vlib_get_node (vm, rt->node_index);
1044     /* copy runtime_data, will be overwritten later for existing rt */
1045     if (n->runtime_data && n->runtime_data_bytes > 0)
1046       clib_memcpy_fast (rt->runtime_data, n->runtime_data,
1047                         clib_min (VLIB_NODE_RUNTIME_DATA_SIZE,
1048                                   n->runtime_data_bytes));
1049   }
1050
1051   for (j = 0; j < vec_len (old_rt); j++)
1052     {
1053       rt = vlib_node_get_runtime (vm_clone, old_rt[j].node_index);
1054       rt->state = old_rt[j].state;
1055       rt->flags = old_rt[j].flags;
1056       clib_memcpy_fast (rt->runtime_data, old_rt[j].runtime_data,
1057                         VLIB_NODE_RUNTIME_DATA_SIZE);
1058     }
1059
1060   vec_free (old_rt);
1061
1062   /* re-clone pre-input nodes */
1063   old_rt = nm_clone->nodes_by_type[VLIB_NODE_TYPE_PRE_INPUT];
1064   nm_clone->nodes_by_type[VLIB_NODE_TYPE_PRE_INPUT] =
1065     vec_dup_aligned (nm->nodes_by_type[VLIB_NODE_TYPE_PRE_INPUT],
1066                      CLIB_CACHE_LINE_BYTES);
1067
1068   vec_foreach (rt, nm_clone->nodes_by_type[VLIB_NODE_TYPE_PRE_INPUT])
1069   {
1070     vlib_node_t *n = vlib_get_node (vm, rt->node_index);
1071     /* copy runtime_data, will be overwritten later for existing rt */
1072     if (n->runtime_data && n->runtime_data_bytes > 0)
1073       clib_memcpy_fast (rt->runtime_data, n->runtime_data,
1074                         clib_min (VLIB_NODE_RUNTIME_DATA_SIZE,
1075                                   n->runtime_data_bytes));
1076   }
1077
1078   for (j = 0; j < vec_len (old_rt); j++)
1079     {
1080       rt = vlib_node_get_runtime (vm_clone, old_rt[j].node_index);
1081       rt->state = old_rt[j].state;
1082       rt->flags = old_rt[j].flags;
1083       clib_memcpy_fast (rt->runtime_data, old_rt[j].runtime_data,
1084                         VLIB_NODE_RUNTIME_DATA_SIZE);
1085     }
1086
1087   vec_free (old_rt);
1088
1089   vec_free (nm_clone->processes);
1090   nm_clone->processes = vec_dup_aligned (nm->processes,
1091                                          CLIB_CACHE_LINE_BYTES);
1092   nm_clone->node_by_error = nm->node_by_error;
1093 }
1094
1095 void
1096 vlib_worker_thread_node_runtime_update (void)
1097 {
1098   /*
1099    * Make a note that we need to do a node runtime update
1100    * prior to releasing the barrier.
1101    */
1102   vlib_global_main.need_vlib_worker_thread_node_runtime_update = 1;
1103 }
1104
1105 u32
1106 unformat_sched_policy (unformat_input_t * input, va_list * args)
1107 {
1108   u32 *r = va_arg (*args, u32 *);
1109
1110   if (0);
1111 #define _(v,f,s) else if (unformat (input, s)) *r = SCHED_POLICY_##f;
1112   foreach_sched_policy
1113 #undef _
1114     else
1115     return 0;
1116   return 1;
1117 }
1118
1119 static clib_error_t *
1120 cpu_config (vlib_main_t * vm, unformat_input_t * input)
1121 {
1122   vlib_thread_registration_t *tr;
1123   uword *p;
1124   vlib_thread_main_t *tm = &vlib_thread_main;
1125   u8 *name;
1126   uword *bitmap;
1127   u32 count;
1128
1129   tm->thread_registrations_by_name = hash_create_string (0, sizeof (uword));
1130
1131   tm->n_thread_stacks = 1;      /* account for main thread */
1132   tm->sched_policy = ~0;
1133   tm->sched_priority = ~0;
1134   tm->main_lcore = ~0;
1135
1136   tr = tm->next;
1137
1138   while (tr)
1139     {
1140       hash_set_mem (tm->thread_registrations_by_name, tr->name, (uword) tr);
1141       tr = tr->next;
1142     }
1143
1144   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1145     {
1146       if (unformat (input, "use-pthreads"))
1147         tm->use_pthreads = 1;
1148       else if (unformat (input, "thread-prefix %v", &tm->thread_prefix))
1149         ;
1150       else if (unformat (input, "main-core %u", &tm->main_lcore))
1151         ;
1152       else if (unformat (input, "skip-cores %u", &tm->skip_cores))
1153         ;
1154       else if (unformat (input, "numa-heap-size %U",
1155                          unformat_memory_size, &tm->numa_heap_size))
1156         ;
1157       else if (unformat (input, "coremask-%s %U", &name,
1158                          unformat_bitmap_mask, &bitmap) ||
1159                unformat (input, "corelist-%s %U", &name,
1160                          unformat_bitmap_list, &bitmap))
1161         {
1162           p = hash_get_mem (tm->thread_registrations_by_name, name);
1163           if (p == 0)
1164             return clib_error_return (0, "no such thread type '%s'", name);
1165
1166           tr = (vlib_thread_registration_t *) p[0];
1167
1168           if (tr->use_pthreads)
1169             return clib_error_return (0,
1170                                       "corelist cannot be set for '%s' threads",
1171                                       name);
1172           if (tr->count)
1173             return clib_error_return
1174               (0, "core placement of '%s' threads is already configured",
1175                name);
1176
1177           tr->coremask = bitmap;
1178           tr->count = clib_bitmap_count_set_bits (tr->coremask);
1179         }
1180       else
1181         if (unformat
1182             (input, "scheduler-policy %U", unformat_sched_policy,
1183              &tm->sched_policy))
1184         ;
1185       else if (unformat (input, "scheduler-priority %u", &tm->sched_priority))
1186         ;
1187       else if (unformat (input, "%s %u", &name, &count))
1188         {
1189           p = hash_get_mem (tm->thread_registrations_by_name, name);
1190           if (p == 0)
1191             return clib_error_return (0, "no such thread type 3 '%s'", name);
1192
1193           tr = (vlib_thread_registration_t *) p[0];
1194
1195           if (tr->fixed_count)
1196             return clib_error_return
1197               (0, "number of '%s' threads not configurable", name);
1198           if (tr->count)
1199             return clib_error_return
1200               (0, "number of '%s' threads is already configured", name);
1201
1202           tr->count = count;
1203         }
1204       else
1205         break;
1206     }
1207
1208   if (tm->sched_priority != ~0)
1209     {
1210       if (tm->sched_policy == SCHED_FIFO || tm->sched_policy == SCHED_RR)
1211         {
1212           u32 prio_max = sched_get_priority_max (tm->sched_policy);
1213           u32 prio_min = sched_get_priority_min (tm->sched_policy);
1214           if (tm->sched_priority > prio_max)
1215             tm->sched_priority = prio_max;
1216           if (tm->sched_priority < prio_min)
1217             tm->sched_priority = prio_min;
1218         }
1219       else
1220         {
1221           return clib_error_return
1222             (0,
1223              "scheduling priority (%d) is not allowed for `normal` scheduling policy",
1224              tm->sched_priority);
1225         }
1226     }
1227   tr = tm->next;
1228
1229   if (!tm->thread_prefix)
1230     tm->thread_prefix = format (0, "vpp");
1231
1232   while (tr)
1233     {
1234       tm->n_thread_stacks += tr->count;
1235       tm->n_pthreads += tr->count * tr->use_pthreads;
1236       tm->n_threads += tr->count * (tr->use_pthreads == 0);
1237       tr = tr->next;
1238     }
1239
1240   return 0;
1241 }
1242
1243 VLIB_EARLY_CONFIG_FUNCTION (cpu_config, "cpu");
1244
1245   /*
1246    * Enforce minimum open time to minimize packet loss due to Rx overflow,
1247    * based on a test based heuristic that barrier should be open for at least
1248    * 3 time as long as it is closed (with an upper bound of 1ms because by that
1249    *  point it is probably too late to make a difference)
1250    */
1251
1252 #ifndef BARRIER_MINIMUM_OPEN_LIMIT
1253 #define BARRIER_MINIMUM_OPEN_LIMIT 0.001
1254 #endif
1255
1256 #ifndef BARRIER_MINIMUM_OPEN_FACTOR
1257 #define BARRIER_MINIMUM_OPEN_FACTOR 3
1258 #endif
1259
1260 void
1261 vlib_worker_thread_initial_barrier_sync_and_release (vlib_main_t * vm)
1262 {
1263   f64 deadline;
1264   f64 now = vlib_time_now (vm);
1265   u32 count = vlib_get_n_threads () - 1;
1266
1267   /* No worker threads? */
1268   if (count == 0)
1269     return;
1270
1271   deadline = now + BARRIER_SYNC_TIMEOUT;
1272   *vlib_worker_threads->wait_at_barrier = 1;
1273   while (*vlib_worker_threads->workers_at_barrier != count)
1274     {
1275       if ((now = vlib_time_now (vm)) > deadline)
1276         {
1277           fformat (stderr, "%s: worker thread deadlock\n", __FUNCTION__);
1278           os_panic ();
1279         }
1280       CLIB_PAUSE ();
1281     }
1282   *vlib_worker_threads->wait_at_barrier = 0;
1283 }
1284
1285 /**
1286  * Return true if the wroker thread barrier is held
1287  */
1288 u8
1289 vlib_worker_thread_barrier_held (void)
1290 {
1291   if (vlib_get_n_threads () < 2)
1292     return (1);
1293
1294   return (*vlib_worker_threads->wait_at_barrier == 1);
1295 }
1296
1297 void
1298 vlib_worker_thread_barrier_sync_int (vlib_main_t * vm, const char *func_name)
1299 {
1300   f64 deadline;
1301   f64 now;
1302   f64 t_entry;
1303   f64 t_open;
1304   f64 t_closed;
1305   f64 max_vector_rate;
1306   u32 count;
1307   int i;
1308
1309   if (vlib_get_n_threads () < 2)
1310     return;
1311
1312   ASSERT (vlib_get_thread_index () == 0);
1313
1314   vlib_worker_threads[0].barrier_caller = func_name;
1315   count = vlib_get_n_threads () - 1;
1316
1317   /* Record entry relative to last close */
1318   now = vlib_time_now (vm);
1319   t_entry = now - vm->barrier_epoch;
1320
1321   /* Tolerate recursive calls */
1322   if (++vlib_worker_threads[0].recursion_level > 1)
1323     {
1324       barrier_trace_sync_rec (t_entry);
1325       return;
1326     }
1327
1328   if (PREDICT_FALSE (vec_len (vm->barrier_perf_callbacks) != 0))
1329     clib_call_callbacks (vm->barrier_perf_callbacks, vm,
1330                          vm->clib_time.last_cpu_time, 0 /* enter */ );
1331
1332   /*
1333    * Need data to decide if we're working hard enough to honor
1334    * the barrier hold-down timer.
1335    */
1336   max_vector_rate = 0.0;
1337   for (i = 1; i < vlib_get_n_threads (); i++)
1338     {
1339       vlib_main_t *ovm = vlib_get_main_by_index (i);
1340       max_vector_rate = clib_max (max_vector_rate,
1341                                   (f64) vlib_last_vectors_per_main_loop (ovm));
1342     }
1343
1344   vlib_worker_threads[0].barrier_sync_count++;
1345
1346   /* Enforce minimum barrier open time to minimize packet loss */
1347   ASSERT (vm->barrier_no_close_before <= (now + BARRIER_MINIMUM_OPEN_LIMIT));
1348
1349   /*
1350    * If any worker thread seems busy, which we define
1351    * as a vector rate above 10, we enforce the barrier hold-down timer
1352    */
1353   if (max_vector_rate > 10.0)
1354     {
1355       while (1)
1356         {
1357           now = vlib_time_now (vm);
1358           /* Barrier hold-down timer expired? */
1359           if (now >= vm->barrier_no_close_before)
1360             break;
1361           if ((vm->barrier_no_close_before - now)
1362               > (2.0 * BARRIER_MINIMUM_OPEN_LIMIT))
1363             {
1364               clib_warning
1365                 ("clock change: would have waited for %.4f seconds",
1366                  (vm->barrier_no_close_before - now));
1367               break;
1368             }
1369         }
1370     }
1371   /* Record time of closure */
1372   t_open = now - vm->barrier_epoch;
1373   vm->barrier_epoch = now;
1374
1375   deadline = now + BARRIER_SYNC_TIMEOUT;
1376
1377   *vlib_worker_threads->wait_at_barrier = 1;
1378   while (*vlib_worker_threads->workers_at_barrier != count)
1379     {
1380       if ((now = vlib_time_now (vm)) > deadline)
1381         {
1382           fformat (stderr, "%s: worker thread deadlock\n", __FUNCTION__);
1383           os_panic ();
1384         }
1385     }
1386
1387   t_closed = now - vm->barrier_epoch;
1388
1389   barrier_trace_sync (t_entry, t_open, t_closed);
1390
1391 }
1392
1393 void
1394 vlib_worker_thread_barrier_release (vlib_main_t * vm)
1395 {
1396   vlib_global_main_t *vgm = vlib_get_global_main ();
1397   f64 deadline;
1398   f64 now;
1399   f64 minimum_open;
1400   f64 t_entry;
1401   f64 t_closed_total;
1402   f64 t_update_main = 0.0;
1403   int refork_needed = 0;
1404
1405   if (vlib_get_n_threads () < 2)
1406     return;
1407
1408   ASSERT (vlib_get_thread_index () == 0);
1409
1410
1411   now = vlib_time_now (vm);
1412   t_entry = now - vm->barrier_epoch;
1413
1414   if (--vlib_worker_threads[0].recursion_level > 0)
1415     {
1416       barrier_trace_release_rec (t_entry);
1417       return;
1418     }
1419
1420   /* Update (all) node runtimes before releasing the barrier, if needed */
1421   if (vgm->need_vlib_worker_thread_node_runtime_update)
1422     {
1423       /*
1424        * Lock stat segment here, so we's safe when
1425        * rebuilding the stat segment node clones from the
1426        * stat thread...
1427        */
1428       vlib_stats_segment_lock ();
1429
1430       /* Do stats elements on main thread */
1431       worker_thread_node_runtime_update_internal ();
1432       vgm->need_vlib_worker_thread_node_runtime_update = 0;
1433
1434       /* Do per thread rebuilds in parallel */
1435       refork_needed = 1;
1436       clib_atomic_fetch_add (vlib_worker_threads->node_reforks_required,
1437                              (vlib_get_n_threads () - 1));
1438       now = vlib_time_now (vm);
1439       t_update_main = now - vm->barrier_epoch;
1440     }
1441
1442   deadline = now + BARRIER_SYNC_TIMEOUT;
1443
1444   /*
1445    * Note when we let go of the barrier.
1446    * Workers can use this to derive a reasonably accurate
1447    * time offset. See vlib_time_now(...)
1448    */
1449   vm->time_last_barrier_release = vlib_time_now (vm);
1450   CLIB_MEMORY_STORE_BARRIER ();
1451
1452   *vlib_worker_threads->wait_at_barrier = 0;
1453
1454   while (*vlib_worker_threads->workers_at_barrier > 0)
1455     {
1456       if ((now = vlib_time_now (vm)) > deadline)
1457         {
1458           fformat (stderr, "%s: worker thread deadlock\n", __FUNCTION__);
1459           os_panic ();
1460         }
1461     }
1462
1463   /* Wait for reforks before continuing */
1464   if (refork_needed)
1465     {
1466       now = vlib_time_now (vm);
1467
1468       deadline = now + BARRIER_SYNC_TIMEOUT;
1469
1470       while (*vlib_worker_threads->node_reforks_required > 0)
1471         {
1472           if ((now = vlib_time_now (vm)) > deadline)
1473             {
1474               fformat (stderr, "%s: worker thread refork deadlock\n",
1475                        __FUNCTION__);
1476               os_panic ();
1477             }
1478         }
1479       vlib_stats_segment_unlock ();
1480     }
1481
1482   t_closed_total = now - vm->barrier_epoch;
1483
1484   minimum_open = t_closed_total * BARRIER_MINIMUM_OPEN_FACTOR;
1485
1486   if (minimum_open > BARRIER_MINIMUM_OPEN_LIMIT)
1487     {
1488       minimum_open = BARRIER_MINIMUM_OPEN_LIMIT;
1489     }
1490
1491   vm->barrier_no_close_before = now + minimum_open;
1492
1493   /* Record barrier epoch (used to enforce minimum open time) */
1494   vm->barrier_epoch = now;
1495
1496   barrier_trace_release (t_entry, t_closed_total, t_update_main);
1497
1498   if (PREDICT_FALSE (vec_len (vm->barrier_perf_callbacks) != 0))
1499     clib_call_callbacks (vm->barrier_perf_callbacks, vm,
1500                          vm->clib_time.last_cpu_time, 1 /* leave */ );
1501 }
1502
1503 static void
1504 vlib_worker_sync_rpc (void *args)
1505 {
1506   ASSERT (vlib_thread_is_main_w_barrier ());
1507   vlib_worker_threads->wait_before_barrier = 0;
1508 }
1509
1510 void
1511 vlib_workers_sync (void)
1512 {
1513   if (PREDICT_FALSE (!vlib_num_workers ()))
1514     return;
1515
1516   if (!(*vlib_worker_threads->wait_at_barrier) &&
1517       !clib_atomic_swap_rel_n (&vlib_worker_threads->wait_before_barrier, 1))
1518     {
1519       u32 thread_index = vlib_get_thread_index ();
1520       vlib_rpc_call_main_thread (vlib_worker_sync_rpc, (u8 *) &thread_index,
1521                                  sizeof (thread_index));
1522       vlib_worker_flush_pending_rpc_requests (vlib_get_main ());
1523     }
1524
1525   /* Wait until main thread asks for barrier */
1526   while (!(*vlib_worker_threads->wait_at_barrier))
1527     ;
1528
1529   /* Stop before barrier and make sure all threads are either
1530    * at worker barrier or the barrier before it */
1531   clib_atomic_fetch_add (&vlib_worker_threads->workers_before_barrier, 1);
1532   while (vlib_num_workers () > (*vlib_worker_threads->workers_at_barrier +
1533                                 vlib_worker_threads->workers_before_barrier))
1534     ;
1535 }
1536
1537 void
1538 vlib_workers_continue (void)
1539 {
1540   if (PREDICT_FALSE (!vlib_num_workers ()))
1541     return;
1542
1543   clib_atomic_fetch_add (&vlib_worker_threads->done_work_before_barrier, 1);
1544
1545   /* Wait until all workers are done with work before barrier */
1546   while (vlib_worker_threads->done_work_before_barrier <
1547          vlib_worker_threads->workers_before_barrier)
1548     ;
1549
1550   clib_atomic_fetch_add (&vlib_worker_threads->done_work_before_barrier, -1);
1551   clib_atomic_fetch_add (&vlib_worker_threads->workers_before_barrier, -1);
1552 }
1553
1554 /**
1555  * Wait until each of the workers has been once around the track
1556  */
1557 void
1558 vlib_worker_wait_one_loop (void)
1559 {
1560   vlib_global_main_t *vgm = vlib_get_global_main ();
1561   ASSERT (vlib_get_thread_index () == 0);
1562
1563   if (vlib_get_n_threads () < 2)
1564     return;
1565
1566   if (vlib_worker_thread_barrier_held ())
1567     return;
1568
1569   u32 *counts = 0;
1570   u32 ii;
1571
1572   vec_validate (counts, vlib_get_n_threads () - 1);
1573
1574   /* record the current loop counts */
1575   vec_foreach_index (ii, vgm->vlib_mains)
1576     counts[ii] = vgm->vlib_mains[ii]->main_loop_count;
1577
1578   /* spin until each changes, apart from the main thread, or we'd be
1579    * a while */
1580   for (ii = 1; ii < vec_len (counts); ii++)
1581     {
1582       while (counts[ii] == vgm->vlib_mains[ii]->main_loop_count)
1583         CLIB_PAUSE ();
1584     }
1585
1586   vec_free (counts);
1587   return;
1588 }
1589
1590 void
1591 vlib_worker_flush_pending_rpc_requests (vlib_main_t *vm)
1592 {
1593   vlib_main_t *vm_global = vlib_get_first_main ();
1594
1595   ASSERT (vm != vm_global);
1596
1597   clib_spinlock_lock_if_init (&vm_global->pending_rpc_lock);
1598   vec_append (vm_global->pending_rpc_requests, vm->pending_rpc_requests);
1599   vec_reset_length (vm->pending_rpc_requests);
1600   clib_spinlock_unlock_if_init (&vm_global->pending_rpc_lock);
1601 }
1602
1603 void
1604 vlib_worker_thread_fn (void *arg)
1605 {
1606   vlib_global_main_t *vgm = vlib_get_global_main ();
1607   vlib_worker_thread_t *w = (vlib_worker_thread_t *) arg;
1608   vlib_main_t *vm = vlib_get_main ();
1609   clib_error_t *e;
1610
1611   ASSERT (vm->thread_index == vlib_get_thread_index ());
1612
1613   vlib_worker_thread_init (w);
1614   clib_time_init (&vm->clib_time);
1615   clib_mem_set_heap (w->thread_mheap);
1616
1617   vm->worker_init_functions_called = hash_create (0, 0);
1618
1619   e = vlib_call_init_exit_functions_no_sort (
1620     vm, &vgm->worker_init_function_registrations, 1 /* call_once */,
1621     0 /* is_global */);
1622   if (e)
1623     clib_error_report (e);
1624
1625   vlib_worker_loop (vm);
1626 }
1627
1628 /* *INDENT-OFF* */
1629 VLIB_REGISTER_THREAD (worker_thread_reg, static) = {
1630   .name = "workers",
1631   .short_name = "wk",
1632   .function = vlib_worker_thread_fn,
1633 };
1634 /* *INDENT-ON* */
1635
1636 extern clib_march_fn_registration
1637   *vlib_frame_queue_dequeue_with_aux_fn_march_fn_registrations;
1638 extern clib_march_fn_registration
1639   *vlib_frame_queue_dequeue_fn_march_fn_registrations;
1640 u32
1641 vlib_frame_queue_main_init (u32 node_index, u32 frame_queue_nelts)
1642 {
1643   vlib_thread_main_t *tm = vlib_get_thread_main ();
1644   vlib_main_t *vm = vlib_get_main ();
1645   vlib_frame_queue_main_t *fqm;
1646   vlib_frame_queue_t *fq;
1647   vlib_node_t *node;
1648   int i;
1649   u32 num_threads;
1650
1651   if (frame_queue_nelts == 0)
1652     frame_queue_nelts = FRAME_QUEUE_MAX_NELTS;
1653
1654   num_threads = 1 /* main thread */  + tm->n_threads;
1655   ASSERT (frame_queue_nelts >= 8 + num_threads);
1656
1657   vec_add2 (tm->frame_queue_mains, fqm, 1);
1658
1659   node = vlib_get_node (vm, fqm->node_index);
1660   ASSERT (node);
1661   if (node->aux_offset)
1662     {
1663       fqm->frame_queue_dequeue_fn =
1664         CLIB_MARCH_FN_VOID_POINTER (vlib_frame_queue_dequeue_with_aux_fn);
1665     }
1666   else
1667     {
1668       fqm->frame_queue_dequeue_fn =
1669         CLIB_MARCH_FN_VOID_POINTER (vlib_frame_queue_dequeue_fn);
1670     }
1671
1672   fqm->node_index = node_index;
1673   fqm->frame_queue_nelts = frame_queue_nelts;
1674
1675   vec_validate (fqm->vlib_frame_queues, tm->n_vlib_mains - 1);
1676   vec_set_len (fqm->vlib_frame_queues, 0);
1677   for (i = 0; i < tm->n_vlib_mains; i++)
1678     {
1679       fq = vlib_frame_queue_alloc (frame_queue_nelts);
1680       vec_add1 (fqm->vlib_frame_queues, fq);
1681     }
1682
1683   return (fqm - tm->frame_queue_mains);
1684 }
1685
1686 void
1687 vlib_process_signal_event_mt_helper (vlib_process_signal_event_mt_args_t *
1688                                      args)
1689 {
1690   ASSERT (vlib_get_thread_index () == 0);
1691   vlib_process_signal_event (vlib_get_main (), args->node_index,
1692                              args->type_opaque, args->data);
1693 }
1694
1695 void *rpc_call_main_thread_cb_fn;
1696
1697 void
1698 vlib_rpc_call_main_thread (void *callback, u8 * args, u32 arg_size)
1699 {
1700   if (rpc_call_main_thread_cb_fn)
1701     {
1702       void (*fp) (void *, u8 *, u32) = rpc_call_main_thread_cb_fn;
1703       (*fp) (callback, args, arg_size);
1704     }
1705   else
1706     clib_warning ("BUG: rpc_call_main_thread_cb_fn NULL!");
1707 }
1708
1709 clib_error_t *
1710 threads_init (vlib_main_t * vm)
1711 {
1712   const vlib_thread_main_t *tm = vlib_get_thread_main ();
1713
1714   if (tm->main_lcore == ~0 && tm->n_vlib_mains > 1)
1715     return clib_error_return (0, "Configuration error, a main core must "
1716                                  "be specified when using worker threads");
1717
1718   return 0;
1719 }
1720
1721 VLIB_INIT_FUNCTION (threads_init);
1722
1723 static clib_error_t *
1724 show_clock_command_fn (vlib_main_t * vm,
1725                        unformat_input_t * input, vlib_cli_command_t * cmd)
1726 {
1727   int verbose = 0;
1728   clib_timebase_t _tb, *tb = &_tb;
1729
1730   (void) unformat (input, "verbose %=", &verbose, 1);
1731
1732   clib_timebase_init (tb, 0 /* GMT */ , CLIB_TIMEBASE_DAYLIGHT_NONE,
1733                       &vm->clib_time);
1734
1735   vlib_cli_output (vm, "%U, %U GMT", format_clib_time, &vm->clib_time,
1736                    verbose, format_clib_timebase_time,
1737                    clib_timebase_now (tb));
1738
1739   vlib_cli_output (vm, "Time last barrier release %.9f",
1740                    vm->time_last_barrier_release);
1741
1742   foreach_vlib_main ()
1743     {
1744       vlib_cli_output (vm, "%d: %U", this_vlib_main->thread_index,
1745                        format_clib_time, &this_vlib_main->clib_time, verbose);
1746
1747       vlib_cli_output (vm, "Thread %d offset %.9f error %.9f",
1748                        this_vlib_main->thread_index,
1749                        this_vlib_main->time_offset,
1750                        vm->time_last_barrier_release -
1751                          this_vlib_main->time_last_barrier_release);
1752     }
1753   return 0;
1754 }
1755
1756 /* *INDENT-OFF* */
1757 VLIB_CLI_COMMAND (f_command, static) =
1758 {
1759   .path = "show clock",
1760   .short_help = "show clock",
1761   .function = show_clock_command_fn,
1762 };
1763 /* *INDENT-ON* */
1764
1765 vlib_thread_main_t *
1766 vlib_get_thread_main_not_inline (void)
1767 {
1768   return vlib_get_thread_main ();
1769 }
1770
1771 /*
1772  * fd.io coding-style-patch-verification: ON
1773  *
1774  * Local Variables:
1775  * eval: (c-set-style "gnu")
1776  * End:
1777  */