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