Add support for AArch32
[vpp.git] / vlib / vlib / threads.c
1 /*
2  * Copyright (c) 2015 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #define _GNU_SOURCE
16 #include <sched.h>
17
18 #include <signal.h>
19 #include <math.h>
20 #include <vppinfra/format.h>
21 #include <vlib/vlib.h>
22
23 #include <vlib/threads.h>
24 #include <vlib/unix/cj.h>
25
26
27 #if DPDK==1
28 #include <rte_config.h>
29 #include <rte_common.h>
30 #include <rte_eal.h>
31 #include <rte_launch.h>
32 #include <rte_lcore.h>
33 #endif
34 DECLARE_CJ_GLOBAL_LOG;
35
36 #define FRAME_QUEUE_NELTS 32
37
38
39 #if DPDK==1
40 /*
41  *  Weak definitions of DPDK symbols used in this file.
42  *  Needed for linking test programs without DPDK libs.
43  */
44 unsigned __thread      __attribute__((weak)) RTE_PER_LCORE(_lcore_id);
45 struct lcore_config    __attribute__((weak)) lcore_config[];
46 unsigned               __attribute__((weak)) rte_socket_id();
47 int                    __attribute__((weak)) rte_eal_remote_launch();
48 #endif
49 u32 vl(void *p)
50 {
51   return vec_len (p);
52 }
53
54 void debug_hex_bytes (u8 *s, u32 n)
55 {
56     fformat (stderr, "%U\n", format_hex_bytes, s, n);
57 }
58
59 vlib_thread_main_t vlib_thread_main;
60
61 uword
62 os_get_cpu_number (void)
63 {
64   void * sp;
65   uword n;
66   u32 len;
67
68   len = vec_len (vlib_thread_stacks);
69   if (len == 0)
70     return 0;
71
72   /* Get any old stack address. */
73   sp = &sp;
74
75   n = ((uword)sp - (uword)vlib_thread_stacks[0])
76       >> VLIB_LOG2_THREAD_STACK_SIZE;
77
78   /* "processes" have their own stacks, and they always run in thread 0 */
79   n = n >= len ? 0 : n;
80
81   return n;
82 }
83
84 void
85 vlib_set_thread_name (char *name)
86 {
87   int pthread_setname_np (pthread_t __target_thread, const char *__name);
88   pthread_t thread = pthread_self();
89
90   if (thread) 
91     pthread_setname_np(thread, name);
92 }
93
94 static int sort_registrations_by_no_clone  (void *a0, void * a1)
95
96   vlib_thread_registration_t ** tr0 = a0;
97   vlib_thread_registration_t ** tr1 = a1;
98
99   return ((i32)((*tr0)->no_data_structure_clone) 
100           - ((i32)((*tr1)->no_data_structure_clone)));
101 }
102
103 static uword *
104 vlib_sysfs_list_to_bitmap(char * filename)
105 {
106   FILE *fp;
107   uword *r = 0;
108
109   fp = fopen (filename, "r");
110
111   if (fp != NULL)
112     {
113       u8 * buffer = 0;
114       vec_validate (buffer, 256-1);
115       if (fgets ((char *)buffer, 256, fp))
116         {
117           unformat_input_t in;
118           unformat_init_string (&in, (char *) buffer, strlen ((char *) buffer));
119           unformat(&in, "%U", unformat_bitmap_list, &r);
120           unformat_free (&in);
121         }
122       vec_free(buffer);
123       fclose(fp);
124     }
125   return r;
126 }
127
128
129 /* Called early in the init sequence */
130
131 clib_error_t *
132 vlib_thread_init (vlib_main_t * vm)
133 {
134   vlib_thread_main_t * tm = &vlib_thread_main;
135   vlib_worker_thread_t * w;
136   vlib_thread_registration_t * tr;
137   u32 n_vlib_mains = 1;
138   u32 first_index = 1;
139   u32 i;
140   uword * avail_cpu;
141
142   /* get bitmaps of active cpu cores and sockets */
143   tm->cpu_core_bitmap =
144     vlib_sysfs_list_to_bitmap("/sys/devices/system/cpu/online");
145   tm->cpu_socket_bitmap =
146     vlib_sysfs_list_to_bitmap("/sys/devices/system/node/online");
147
148   avail_cpu = clib_bitmap_dup(tm->cpu_core_bitmap);
149
150   /* skip cores */
151   for (i=0; i < tm->skip_cores; i++)
152     {
153       uword c = clib_bitmap_first_set(avail_cpu);
154       if (c == ~0)
155         return clib_error_return (0, "no available cpus to skip");
156
157       avail_cpu = clib_bitmap_set(avail_cpu, c, 0);
158     }
159
160   /* grab cpu for main thread */
161   if (!tm->main_lcore)
162     {
163       tm->main_lcore = clib_bitmap_first_set(avail_cpu);
164       if (tm->main_lcore == (u8) ~0)
165         return clib_error_return (0, "no available cpus to be used for the"
166                                   " main thread");
167     }
168   else
169     {
170       if (clib_bitmap_get(avail_cpu, tm->main_lcore) == 0)
171         return clib_error_return (0, "cpu %u is not available to be used"
172                                   " for the main thread", tm->main_lcore);
173     }
174   avail_cpu = clib_bitmap_set(avail_cpu, tm->main_lcore, 0);
175
176   /* assume that there is socket 0 only if there is no data from sysfs */
177   if (!tm->cpu_socket_bitmap)
178     tm->cpu_socket_bitmap = clib_bitmap_set(0, 0, 1);
179
180   /* pin main thread to main_lcore  */
181 #if DPDK==0
182   {
183      cpu_set_t cpuset;
184      CPU_ZERO(&cpuset);
185      CPU_SET(tm->main_lcore, &cpuset);
186      pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
187   }
188 #endif
189
190   /* as many threads as stacks... */
191   vec_validate_aligned (vlib_worker_threads, vec_len(vlib_thread_stacks)-1,
192                         CLIB_CACHE_LINE_BYTES);
193
194   /* Preallocate thread 0 */
195   _vec_len(vlib_worker_threads) = 1;
196   w = vlib_worker_threads;
197   w->thread_mheap = clib_mem_get_heap();
198   w->thread_stack = vlib_thread_stacks[0];
199   w->dpdk_lcore_id = -1;
200   w->lwp = syscall(SYS_gettid);
201   tm->n_vlib_mains = 1;
202
203   /* assign threads to cores and set n_vlib_mains */
204   tr = tm->next;
205
206   while (tr)
207     {
208       vec_add1 (tm->registrations, tr);
209       tr = tr->next;
210     }
211
212   vec_sort_with_function
213     (tm->registrations, sort_registrations_by_no_clone);
214
215   for (i = 0; i < vec_len (tm->registrations); i++)
216     {
217       int j;
218       tr = tm->registrations[i];
219       tr->first_index = first_index;
220       first_index += tr->count;
221       n_vlib_mains += (tr->no_data_structure_clone == 0) ? tr->count : 0;
222
223       /* construct coremask */
224       if (tr->use_pthreads || !tr->count)
225         continue;
226
227       if (tr->coremask)
228         {
229           uword c;
230           clib_bitmap_foreach (c, tr->coremask, ({
231             if (clib_bitmap_get(avail_cpu, c) == 0)
232               return clib_error_return (0, "cpu %u is not available to be used"
233                                         " for the '%s' thread",c, tr->name);
234
235             avail_cpu = clib_bitmap_set(avail_cpu, c, 0);
236           }));
237
238         }
239       else
240         {
241           for (j=0; j < tr->count; j++)
242             {
243               uword c = clib_bitmap_first_set(avail_cpu);
244               if (c == ~0)
245               return clib_error_return (0, "no available cpus to be used for"
246                                         " the '%s' thread", tr->name);
247
248               avail_cpu = clib_bitmap_set(avail_cpu, c, 0);
249               tr->coremask = clib_bitmap_set(tr->coremask, c, 1);
250             }
251         }
252     }
253
254   clib_bitmap_free(avail_cpu);
255
256   tm->n_vlib_mains = n_vlib_mains;
257
258   vec_validate_aligned (vlib_worker_threads, first_index-1,
259                         CLIB_CACHE_LINE_BYTES);
260
261
262   tm->efd.enabled = VLIB_EFD_DISABLED;
263   tm->efd.queue_hi_thresh = ((VLIB_EFD_DEF_WORKER_HI_THRESH_PCT *
264                               FRAME_QUEUE_NELTS)/100);
265   return 0;
266 }
267
268 vlib_worker_thread_t *
269 vlib_alloc_thread (vlib_main_t * vm)
270 {
271   vlib_worker_thread_t * w;
272
273   if (vec_len(vlib_worker_threads) >= vec_len (vlib_thread_stacks))
274     {
275       clib_warning ("out of worker threads... Quitting...");
276       exit(1);
277     }
278   vec_add2 (vlib_worker_threads, w, 1);
279   w->thread_stack = vlib_thread_stacks[w - vlib_worker_threads];
280   return w;
281 }
282
283 vlib_frame_queue_t * vlib_frame_queue_alloc (int nelts)
284 {
285   vlib_frame_queue_t * fq;
286
287   fq = clib_mem_alloc_aligned(sizeof (*fq), CLIB_CACHE_LINE_BYTES);
288   memset (fq, 0, sizeof (*fq));
289   fq->nelts = nelts;
290   fq->vector_threshold = 128; // packets
291   vec_validate_aligned (fq->elts, nelts-1, CLIB_CACHE_LINE_BYTES);
292
293   if (1)
294   {
295     if (((uword)&fq->tail) & (CLIB_CACHE_LINE_BYTES - 1))
296       fformat(stderr, "WARNING: fq->tail unaligned\n");
297     if (((uword)&fq->head) & (CLIB_CACHE_LINE_BYTES - 1))
298       fformat(stderr, "WARNING: fq->head unaligned\n");
299     if (((uword)fq->elts) & (CLIB_CACHE_LINE_BYTES - 1))
300       fformat(stderr, "WARNING: fq->elts unaligned\n");
301     
302     if (sizeof (fq->elts[0]) % CLIB_CACHE_LINE_BYTES)
303       fformat(stderr, "WARNING: fq->elts[0] size %d\n", 
304               sizeof (fq->elts[0]));
305     if (nelts & (nelts -1))
306       {
307         fformat (stderr, "FATAL: nelts MUST be a power of 2\n");
308         abort();
309       }
310   }
311   
312   return (fq);
313 }
314
315 void vl_msg_api_handler_no_free (void *) __attribute__ ((weak));
316 void vl_msg_api_handler_no_free (void *v) { }
317
318 /* Turned off, save as reference material... */
319 #if 0
320 static inline int vlib_frame_queue_dequeue_internal (int thread_id, 
321                                                       vlib_main_t *vm, 
322                                                       vlib_node_main_t *nm)
323 {
324   vlib_frame_queue_t *fq = vlib_frame_queues[thread_id];
325   vlib_frame_queue_elt_t *elt;
326   vlib_frame_t *f;
327   vlib_pending_frame_t *p;
328   vlib_node_runtime_t *r;
329   u32 node_runtime_index;
330   int msg_type;
331   u64 before;
332   int processed = 0;
333   
334   ASSERT(vm == vlib_mains[thread_id]);
335
336   while (1)
337     {
338       if (fq->head == fq->tail)
339         return processed;
340
341       elt = fq->elts + ((fq->head+1) & (fq->nelts-1));
342
343       if (!elt->valid)
344         return processed;
345
346       before = clib_cpu_time_now();
347
348       f = elt->frame;
349       node_runtime_index = elt->node_runtime_index;
350       msg_type = elt->msg_type;
351
352       switch (msg_type)
353         {
354         case VLIB_FRAME_QUEUE_ELT_FREE_BUFFERS:
355           vlib_buffer_free (vm, vlib_frame_vector_args (f), f->n_vectors);
356           /* note fallthrough... */
357         case VLIB_FRAME_QUEUE_ELT_FREE_FRAME:
358           r = vec_elt_at_index (nm->nodes_by_type[VLIB_NODE_TYPE_INTERNAL], 
359                                 node_runtime_index);
360           vlib_frame_free (vm, r, f);
361           break;
362         case VLIB_FRAME_QUEUE_ELT_DISPATCH_FRAME:
363           vec_add2 (vm->node_main.pending_frames, p, 1);
364           f->flags |= (VLIB_FRAME_PENDING | VLIB_FRAME_FREE_AFTER_DISPATCH);
365           p->node_runtime_index = elt->node_runtime_index;
366           p->frame_index = vlib_frame_index (vm, f);
367           p->next_frame_index = VLIB_PENDING_FRAME_NO_NEXT_FRAME;
368           fq->dequeue_vectors += (u64) f->n_vectors;
369           break;
370         case VLIB_FRAME_QUEUE_ELT_API_MSG:
371           vl_msg_api_handler_no_free (f);
372           break;
373         default:
374           clib_warning ("bogus frame queue message, type %d", msg_type);
375           break;
376         }
377       elt->valid = 0;
378       fq->dequeues++;
379       fq->dequeue_ticks += clib_cpu_time_now() - before;
380       CLIB_MEMORY_BARRIER();
381       fq->head++;
382       processed++;
383     }
384   ASSERT(0);
385   return processed;
386 }
387
388 int vlib_frame_queue_dequeue (int thread_id, 
389                                vlib_main_t *vm, 
390                                vlib_node_main_t *nm)
391 {
392   return vlib_frame_queue_dequeue_internal (thread_id, vm, nm);
393 }
394
395 int vlib_frame_queue_enqueue (vlib_main_t *vm, u32 node_runtime_index,
396                               u32 frame_queue_index, vlib_frame_t *frame,
397                               vlib_frame_queue_msg_type_t type)
398 {
399   vlib_frame_queue_t *fq = vlib_frame_queues[frame_queue_index];
400   vlib_frame_queue_elt_t *elt;
401   u32 save_count;
402   u64 new_tail;
403   u64 before = clib_cpu_time_now();
404   
405   ASSERT (fq);
406
407   new_tail = __sync_add_and_fetch (&fq->tail, 1);
408
409   /* Wait until a ring slot is available */
410   while (new_tail >= fq->head + fq->nelts)
411     {
412       f64 b4 = vlib_time_now_ticks (vm, before);
413       vlib_worker_thread_barrier_check (vm, b4);
414       /* Bad idea. Dequeue -> enqueue -> dequeue -> trouble */
415       // vlib_frame_queue_dequeue (vm->cpu_index, vm, nm);
416     }
417
418   elt = fq->elts + (new_tail & (fq->nelts-1));
419
420   /* this would be very bad... */
421   while (elt->valid) 
422     {
423     }
424
425   /* Once we enqueue the frame, frame->n_vectors is owned elsewhere... */
426   save_count = frame->n_vectors;
427
428   elt->frame = frame;
429   elt->node_runtime_index = node_runtime_index;
430   elt->msg_type = type;
431   CLIB_MEMORY_BARRIER();
432   elt->valid = 1;
433
434   return save_count;
435 }
436 #endif /* 0 */
437
438 /* To be called by vlib worker threads upon startup */
439 void vlib_worker_thread_init (vlib_worker_thread_t * w)
440 {
441   vlib_thread_main_t *tm = vlib_get_thread_main();
442   
443   /* worker threads wants no signals. */
444   {
445     sigset_t s;
446     sigfillset (&s);
447     pthread_sigmask (SIG_SETMASK, &s, 0);
448   }
449
450   clib_mem_set_heap (w->thread_mheap);
451
452   if (vec_len(tm->thread_prefix) && w->registration->short_name)
453     {
454       w->name = format(0, "%v_%s_%d%c", tm->thread_prefix,
455                                         w->registration->short_name,
456                                         w->instance_id,
457                                         '\0');
458       vlib_set_thread_name((char *)w->name);
459     }
460
461   if (!w->registration->use_pthreads)
462     {
463
464       /* Initial barrier sync, for both worker and i/o threads */
465       clib_smp_atomic_add (vlib_worker_threads->workers_at_barrier, 1);
466
467       while (*vlib_worker_threads->wait_at_barrier)
468           ;
469
470       clib_smp_atomic_add (vlib_worker_threads->workers_at_barrier, -1);
471     }
472 }
473
474 void *vlib_worker_thread_bootstrap_fn (void *arg)
475 {
476   void *rv;
477   vlib_worker_thread_t *w = arg;
478   
479   w->lwp = syscall(SYS_gettid);
480   w->dpdk_lcore_id = -1;
481 #if DPDK==1
482   if (w->registration && !w->registration->use_pthreads &&
483       rte_socket_id) /* do we really have dpdk linked */
484     {
485       unsigned lcore = rte_lcore_id();
486       lcore = lcore < RTE_MAX_LCORE ? lcore : -1;
487       w->dpdk_lcore_id = lcore;
488     }
489 #endif
490
491   rv = (void *) clib_calljmp 
492       ((uword (*)(uword)) w->thread_function, 
493        (uword) arg, w->thread_stack + VLIB_THREAD_STACK_SIZE);
494   /* NOTREACHED, we hope */
495   return rv;
496 }
497
498 static int
499 vlib_launch_thread (void *fp, vlib_worker_thread_t *w, unsigned lcore_id)
500 {
501   void *(*fp_arg)(void *) = fp;
502
503 #if DPDK==1
504   if (!w->registration->use_pthreads)
505     if (rte_eal_remote_launch) /* do we have dpdk linked */
506       return rte_eal_remote_launch (fp, (void *)w, lcore_id);
507     else
508       return -1;
509   else
510 #endif
511   {
512     int ret;
513     pthread_t worker;
514     cpu_set_t cpuset;
515     CPU_ZERO(&cpuset);
516     CPU_SET(lcore_id, &cpuset);
517
518     ret = pthread_create (&worker, NULL /* attr */, fp_arg, (void *)w);
519     if(ret == 0)
520         return pthread_setaffinity_np(worker, sizeof(cpu_set_t), &cpuset);
521     else
522         return ret;
523   }
524 }
525
526 static clib_error_t * start_workers (vlib_main_t * vm)
527 {
528   int i, j;
529   vlib_worker_thread_t *w;
530   vlib_main_t *vm_clone;
531   void *oldheap;
532   vlib_frame_queue_t *fq;
533   vlib_thread_main_t * tm = &vlib_thread_main;
534   vlib_thread_registration_t * tr; 
535   vlib_node_runtime_t * rt;
536   u32 n_vlib_mains = tm->n_vlib_mains;
537   u32 worker_thread_index;
538
539   vec_reset_length (vlib_worker_threads);
540
541   /* Set up the main thread */
542   vec_add2_aligned (vlib_worker_threads, w, 1, CLIB_CACHE_LINE_BYTES);
543   w->elog_track.name = "main thread";
544   elog_track_register (&vm->elog_main, &w->elog_track);
545
546   if (vec_len(tm->thread_prefix))
547     {
548       w->name = format(0, "%v_main%c", tm->thread_prefix, '\0');
549       vlib_set_thread_name((char *)w->name);
550     }
551
552 #if DPDK==1
553   w->dpdk_lcore_id = -1;
554   if (rte_socket_id) /* do we really have dpdk linked */
555     {
556       unsigned lcore = rte_lcore_id();
557       w->dpdk_lcore_id = lcore < RTE_MAX_LCORE ? lcore : -1;;
558     }
559 #endif
560
561   if (n_vlib_mains > 1)
562     {
563       u8 * heap = clib_mem_get_per_cpu_heap();
564       mheap_t * h = mheap_header (heap);
565       
566       /* make the main heap thread-safe */
567       h->flags |= MHEAP_FLAG_THREAD_SAFE;
568       
569       /* Make the event-log MP-safe */
570       vm->elog_main.lock = 
571         clib_mem_alloc_aligned (CLIB_CACHE_LINE_BYTES, 
572                                 CLIB_CACHE_LINE_BYTES);
573   
574       vm->elog_main.lock[0] = 0;
575
576       vec_validate (vlib_mains, tm->n_vlib_mains - 1);
577       _vec_len (vlib_mains) = 0;
578       vec_add1 (vlib_mains, vm);
579
580       vec_validate (vlib_frame_queues, tm->n_vlib_mains - 1);
581       _vec_len (vlib_frame_queues) = 0;
582       fq = vlib_frame_queue_alloc (FRAME_QUEUE_NELTS);
583       vec_add1 (vlib_frame_queues, fq);
584
585       vlib_worker_threads->wait_at_barrier = 
586         clib_mem_alloc_aligned (sizeof (u32), CLIB_CACHE_LINE_BYTES);
587       vlib_worker_threads->workers_at_barrier =
588         clib_mem_alloc_aligned (sizeof (u32), CLIB_CACHE_LINE_BYTES);
589
590       /* Ask for an initial barrier sync */
591       *vlib_worker_threads->workers_at_barrier = 0;
592       *vlib_worker_threads->wait_at_barrier = 1;
593
594       worker_thread_index = 1;
595
596       for (i = 0; i < vec_len(tm->registrations); i++)
597         {
598           vlib_node_main_t *nm, *nm_clone;
599           vlib_buffer_main_t *bm_clone;
600           vlib_buffer_free_list_t *fl_clone, *fl_orig;
601           vlib_buffer_free_list_t *orig_freelist_pool;
602           int k;
603
604           tr = tm->registrations[i];
605
606           if (tr->count == 0)
607             continue;
608
609           for (k = 0; k < tr->count; k++)
610           {
611             vec_add2 (vlib_worker_threads, w, 1);
612             /* 
613              * Share the main heap which is now thread-safe.
614              *
615              * To allocate separate heaps, code:
616              * mheap_alloc (0 / * use VM * /, tr->mheap_size);
617              */
618             w->thread_mheap = heap;
619             w->thread_stack = vlib_thread_stacks[w - vlib_worker_threads];
620             w->thread_function = tr->function;
621             w->thread_function_arg = w;
622             w->instance_id = k;
623             w->registration = tr; 
624             
625             w->elog_track.name = 
626                 (char *) format (0, "%s %d", tr->name, k+1);
627             vec_add1 (w->elog_track.name, 0);
628             elog_track_register (&vm->elog_main, &w->elog_track);
629             
630             if (tr->no_data_structure_clone)
631               continue;
632
633             /* Allocate "to-worker-N" frame queue */
634             fq = vlib_frame_queue_alloc (FRAME_QUEUE_NELTS);
635             vec_validate (vlib_frame_queues, worker_thread_index);
636             vlib_frame_queues[worker_thread_index] = fq;
637
638             /* Fork vlib_global_main et al. Look for bugs here */
639             oldheap = clib_mem_set_heap (w->thread_mheap);
640
641             vm_clone = clib_mem_alloc (sizeof (*vm_clone));
642             memcpy (vm_clone, vlib_mains[0], sizeof (*vm_clone));
643
644             vm_clone->cpu_index = worker_thread_index;
645             vm_clone->heap_base = w->thread_mheap;
646             vm_clone->mbuf_alloc_list = 0;
647             memset (&vm_clone->random_buffer, 0, sizeof (vm_clone->random_buffer));
648
649             nm = &vlib_mains[0]->node_main;
650             nm_clone = &vm_clone->node_main;
651             /* fork next frames array, preserving node runtime indices */
652             nm_clone->next_frames = vec_dup (nm->next_frames);
653             for (j = 0; j < vec_len (nm_clone->next_frames); j++)
654               {
655                 vlib_next_frame_t *nf = &nm_clone->next_frames[j];
656                 u32 save_node_runtime_index;
657                 u32 save_flags;
658
659                 save_node_runtime_index = nf->node_runtime_index;
660                 save_flags = nf->flags & VLIB_FRAME_NO_FREE_AFTER_DISPATCH;
661                 vlib_next_frame_init (nf);
662                 nf->node_runtime_index = save_node_runtime_index;
663                 nf->flags = save_flags;
664               }
665
666             /* fork the frame dispatch queue */
667             nm_clone->pending_frames = 0;
668             vec_validate (nm_clone->pending_frames, 10); /* $$$$$?????? */
669             _vec_len (nm_clone->pending_frames) = 0;
670
671             /* fork nodes */
672             nm_clone->nodes = 0;
673             for (j = 0; j < vec_len (nm->nodes); j++) 
674               {
675                 vlib_node_t *n;
676                 n = clib_mem_alloc_no_fail (sizeof(*n));
677                 memcpy (n, nm->nodes[j], sizeof (*n));
678                 /* none of the copied nodes have enqueue rights given out */
679                 n->owner_node_index = VLIB_INVALID_NODE_INDEX;
680                 memset (&n->stats_total, 0, sizeof (n->stats_total));
681                 memset (&n->stats_last_clear, 0, sizeof (n->stats_last_clear));
682                 vec_add1 (nm_clone->nodes, n);
683               }
684             nm_clone->nodes_by_type[VLIB_NODE_TYPE_INTERNAL] =
685               vec_dup (nm->nodes_by_type[VLIB_NODE_TYPE_INTERNAL]);
686
687             nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT] =
688               vec_dup (nm->nodes_by_type[VLIB_NODE_TYPE_INPUT]);
689             vec_foreach(rt, nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT])
690               rt->cpu_index = vm_clone->cpu_index;
691
692             nm_clone->processes = vec_dup (nm->processes);
693
694             /* zap the (per worker) frame freelists, etc */
695             nm_clone->frame_sizes = 0;
696             nm_clone->frame_size_hash = 0;
697
698             /* Packet trace buffers are guaranteed to be empty, nothing to do here */
699
700             clib_mem_set_heap (oldheap);
701             vec_add1 (vlib_mains, vm_clone);
702
703             vm_clone->error_main.counters =
704               vec_dup(vlib_mains[0]->error_main.counters);
705             vm_clone->error_main.counters_last_clear =
706               vec_dup(vlib_mains[0]->error_main.counters_last_clear);
707
708             /* Fork the vlib_buffer_main_t free lists, etc. */
709             bm_clone = vec_dup (vm_clone->buffer_main);
710             vm_clone->buffer_main = bm_clone;
711
712             orig_freelist_pool = bm_clone->buffer_free_list_pool;
713             bm_clone->buffer_free_list_pool = 0;
714
715             pool_foreach (fl_orig, orig_freelist_pool,
716                           ({
717                             pool_get_aligned (bm_clone->buffer_free_list_pool, 
718                                               fl_clone, CLIB_CACHE_LINE_BYTES);
719                             ASSERT (fl_orig - orig_freelist_pool 
720                                     == fl_clone - bm_clone->buffer_free_list_pool);
721
722                             fl_clone[0] = fl_orig[0];
723                             fl_clone->aligned_buffers = 0;
724                             fl_clone->unaligned_buffers = 0;
725                             fl_clone->n_alloc = 0;
726                           }));
727
728             worker_thread_index++;
729           }
730         }
731     }
732   else
733     {
734       /* only have non-data-structure copy threads to create... */
735       for (i = 0; i < vec_len(tm->registrations); i++)
736         {
737           tr = tm->registrations[i];
738
739           for (j = 0; j < tr->count; j++)
740             {
741               vec_add2 (vlib_worker_threads, w, 1);
742               w->thread_mheap = mheap_alloc (0 /* use VM */, tr->mheap_size);
743               w->thread_stack = vlib_thread_stacks[w - vlib_worker_threads];
744               w->thread_function = tr->function;
745               w->thread_function_arg = w;
746               w->instance_id = j;
747               w->elog_track.name = 
748                   (char *) format (0, "%s %d", tr->name, j+1);
749               w->registration = tr;
750               vec_add1 (w->elog_track.name, 0);
751               elog_track_register (&vm->elog_main, &w->elog_track);
752             }
753         }
754     }
755
756   worker_thread_index = 1;
757
758   for (i = 0; i < vec_len (tm->registrations); i++)
759     {
760       int j;
761
762       tr = tm->registrations[i];
763
764       if (tr->use_pthreads || tm->use_pthreads)
765         {
766           for (j = 0; j < tr->count; j++)
767             {
768               w = vlib_worker_threads + worker_thread_index++;
769               if (vlib_launch_thread (vlib_worker_thread_bootstrap_fn, w, 0) < 0)
770                 clib_warning ("Couldn't start '%s' pthread ", tr->name);
771             }
772         }
773       else
774         {
775             uword c;
776             clib_bitmap_foreach (c, tr->coremask, ({
777               w = vlib_worker_threads + worker_thread_index++;
778               if (vlib_launch_thread (vlib_worker_thread_bootstrap_fn, w, c) < 0)
779                 clib_warning ("Couldn't start DPDK lcore %d", c);
780
781             }));
782         }
783     }
784   vlib_worker_thread_barrier_sync(vm);
785   vlib_worker_thread_barrier_release(vm);
786   return 0;
787 }
788
789 VLIB_MAIN_LOOP_ENTER_FUNCTION (start_workers);
790
791 void vlib_worker_thread_node_runtime_update(void)
792 {
793   int i, j;
794   vlib_worker_thread_t *w;
795   vlib_main_t *vm;
796   vlib_node_main_t *nm, *nm_clone;
797   vlib_node_t ** old_nodes_clone;
798   vlib_main_t *vm_clone;
799   vlib_node_runtime_t * rt, * old_rt;
800   void *oldheap;
801   never_inline void
802     vlib_node_runtime_sync_stats (vlib_main_t * vm,
803                                   vlib_node_runtime_t * r,
804                                   uword n_calls,
805                                   uword n_vectors,
806                                   uword n_clocks);
807   
808   ASSERT (os_get_cpu_number() == 0);
809
810   if (vec_len (vlib_mains) == 0)
811     return;
812
813   vm = vlib_mains[0];
814   nm = &vm->node_main;
815
816   ASSERT (os_get_cpu_number() == 0);
817   ASSERT (*vlib_worker_threads->wait_at_barrier == 1);
818
819   /* 
820    * Scrape all runtime stats, so we don't lose node runtime(s) with
821    * pending counts, or throw away worker / io thread counts.
822    */
823   for (j = 0; j < vec_len (nm->nodes); j++) 
824     {
825       vlib_node_t * n;
826       n = nm->nodes[j];
827       vlib_node_sync_stats (vm, n);
828     }
829
830   for (i = 1; i < vec_len (vlib_mains); i++)
831     {
832       vlib_node_t * n;
833       
834       vm_clone = vlib_mains[i];
835       nm_clone = &vm_clone->node_main;
836
837       for (j = 0; j < vec_len (nm_clone->nodes); j++) 
838         {
839           n = nm_clone->nodes[j];
840
841           rt = vlib_node_get_runtime (vm_clone, n->index);
842           vlib_node_runtime_sync_stats (vm_clone, rt, 0, 0, 0);
843         }
844     }
845
846   for (i = 1; i < vec_len (vlib_mains); i++)
847     {
848       vlib_node_runtime_t * rt;
849       w = vlib_worker_threads + i;
850       oldheap = clib_mem_set_heap (w->thread_mheap);
851
852       vm_clone = vlib_mains[i];
853
854       /* Re-clone error heap */
855       u64 * old_counters = vm_clone->error_main.counters;
856       u64 * old_counters_all_clear = vm_clone->error_main.counters_last_clear;
857       memcpy (&vm_clone->error_main, &vm->error_main, sizeof (vm->error_main));
858       j = vec_len(vm->error_main.counters) - 1;
859       vec_validate_aligned(old_counters, j, CLIB_CACHE_LINE_BYTES);
860       vec_validate_aligned(old_counters_all_clear, j, CLIB_CACHE_LINE_BYTES);
861       vm_clone->error_main.counters = old_counters;
862       vm_clone->error_main.counters_last_clear = old_counters_all_clear;
863
864       nm_clone = &vm_clone->node_main;
865       vec_free (nm_clone->next_frames);
866       nm_clone->next_frames = vec_dup (nm->next_frames);
867
868       for (j = 0; j < vec_len (nm_clone->next_frames); j++)
869         {
870           vlib_next_frame_t *nf = &nm_clone->next_frames[j];
871           u32 save_node_runtime_index;
872           u32 save_flags;
873
874           save_node_runtime_index = nf->node_runtime_index;
875           save_flags = nf->flags & VLIB_FRAME_NO_FREE_AFTER_DISPATCH;
876           vlib_next_frame_init (nf);
877           nf->node_runtime_index = save_node_runtime_index;
878           nf->flags = save_flags;
879         }
880
881       old_nodes_clone = nm_clone->nodes;
882       nm_clone->nodes = 0;
883
884       /* re-fork nodes */
885       for (j = 0; j < vec_len (nm->nodes); j++) {
886         vlib_node_t *old_n_clone;
887         vlib_node_t *new_n, *new_n_clone;
888
889         new_n = nm->nodes[j];
890         old_n_clone = old_nodes_clone[j];
891
892         new_n_clone = clib_mem_alloc_no_fail (sizeof(*new_n_clone));
893         memcpy (new_n_clone, new_n, sizeof (*new_n));
894         /* none of the copied nodes have enqueue rights given out */
895         new_n_clone->owner_node_index = VLIB_INVALID_NODE_INDEX;
896
897         if (j >= vec_len (old_nodes_clone))
898           {
899             /* new node, set to zero */
900             memset (&new_n_clone->stats_total, 0, 
901                     sizeof (new_n_clone->stats_total));
902             memset (&new_n_clone->stats_last_clear, 0, 
903                     sizeof (new_n_clone->stats_last_clear));
904           }
905         else
906           {
907             /* Copy stats if the old data is valid */
908             memcpy (&new_n_clone->stats_total, 
909                     &old_n_clone->stats_total,
910                     sizeof (new_n_clone->stats_total));
911             memcpy (&new_n_clone->stats_last_clear, 
912                     &old_n_clone->stats_last_clear,
913                     sizeof (new_n_clone->stats_last_clear));
914
915             /* keep previous node state */
916             new_n_clone->state = old_n_clone->state;
917           }
918         vec_add1 (nm_clone->nodes, new_n_clone);
919       }
920       /* Free the old node clone */
921       for (j = 0; j < vec_len(old_nodes_clone); j++)
922         clib_mem_free (old_nodes_clone[j]);
923       vec_free (old_nodes_clone);
924       
925       vec_free (nm_clone->nodes_by_type[VLIB_NODE_TYPE_INTERNAL]);
926
927       nm_clone->nodes_by_type[VLIB_NODE_TYPE_INTERNAL] =
928           vec_dup (nm->nodes_by_type[VLIB_NODE_TYPE_INTERNAL]);
929
930       /* clone input node runtime */
931       old_rt = nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT];
932
933       nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT] =
934         vec_dup (nm->nodes_by_type[VLIB_NODE_TYPE_INPUT]);
935
936       vec_foreach(rt, nm_clone->nodes_by_type[VLIB_NODE_TYPE_INPUT])
937         {
938           rt->cpu_index = vm_clone->cpu_index;
939         }
940
941       for (j=0; j < vec_len(old_rt); j++)
942         {
943           rt = vlib_node_get_runtime (vm_clone, old_rt[j].node_index);
944           rt->state = old_rt[j].state;
945         }
946
947       vec_free(old_rt);
948
949       nm_clone->processes = vec_dup (nm->processes);
950
951       clib_mem_set_heap (oldheap);
952
953       // vnet_main_fork_fixup (i);
954     }
955 }
956
957 static clib_error_t *
958 cpu_config (vlib_main_t * vm, unformat_input_t * input)
959 {
960   vlib_thread_registration_t *tr;
961   uword * p;
962   vlib_thread_main_t * tm = &vlib_thread_main;
963   u8 * name;
964   u64 coremask;
965   uword * bitmap;
966   u32 count;
967
968   tm->thread_registrations_by_name = hash_create_string (0, sizeof (uword));
969   tm->n_thread_stacks = 1;      /* account for main thread */
970
971   tr = tm->next;
972
973   while (tr)
974     {
975       hash_set_mem (tm->thread_registrations_by_name, tr->name, (uword)tr);
976       tr = tr->next;
977     }
978
979   while (unformat_check_input(input) != UNFORMAT_END_OF_INPUT)
980     {
981       if (unformat (input, "main-thread-io"))
982         tm->main_thread_is_io_node = 1;
983       else if (unformat (input, "use-pthreads"))
984         tm->use_pthreads = 1;
985       else if (unformat (input, "thread-prefix %v", &tm->thread_prefix))
986           ;
987       else if (unformat (input, "main-core %u", &tm->main_lcore))
988           ;
989       else if (unformat (input, "skip-cores %u", &tm->skip_cores))
990           ;
991       else if (unformat (input, "coremask-%s %llx", &name, &coremask))
992         {
993           p = hash_get_mem (tm->thread_registrations_by_name, name);
994           if (p == 0)
995             return clib_error_return (0, "no such thread type '%s'", name);
996
997           tr = (vlib_thread_registration_t *)p[0];
998
999           if  (tr->use_pthreads)
1000             return clib_error_return (0, "coremask cannot be set for '%s' threads",
1001                                       name);
1002
1003           tr->coremask = clib_bitmap_set_multiple 
1004             (tr->coremask, 0, coremask, BITS(coremask));
1005           tr->count = clib_bitmap_count_set_bits (tr->coremask);
1006         }
1007       else if (unformat (input, "corelist-%s %U", &name, unformat_bitmap_list,
1008                &bitmap))
1009         {
1010           p = hash_get_mem (tm->thread_registrations_by_name, name);
1011           if (p == 0)
1012             return clib_error_return (0, "no such thread type '%s'", name);
1013
1014           tr = (vlib_thread_registration_t *)p[0];
1015
1016           if  (tr->use_pthreads)
1017             return clib_error_return (0, "corelist cannot be set for '%s' threads",
1018                                       name);
1019
1020           tr->coremask = bitmap;
1021           tr->count = clib_bitmap_count_set_bits (tr->coremask);
1022         }
1023       else if (unformat (input, "%s %u", &name, &count))
1024         {
1025           p = hash_get_mem (tm->thread_registrations_by_name, name);
1026           if (p == 0)
1027               return clib_error_return (0, "no such thread type '%s'", name);
1028                                         
1029           tr = (vlib_thread_registration_t *)p[0];
1030           if (tr->fixed_count)
1031             return clib_error_return 
1032               (0, "number of %s threads not configurable", tr->name);
1033           tr->count = count;
1034         }
1035       else 
1036         break;
1037     }
1038
1039   tr = tm->next;
1040
1041   if (!tm->thread_prefix)
1042     tm->thread_prefix = format(0, "vpp");
1043
1044   while (tr)
1045     {
1046       tm->n_thread_stacks += tr->count;
1047       tm->n_pthreads += tr->count * tr->use_pthreads;
1048       tm->n_eal_threads += tr->count * (tr->use_pthreads == 0);
1049       tr = tr->next;
1050     }
1051
1052   return 0;
1053 }
1054
1055 VLIB_EARLY_CONFIG_FUNCTION (cpu_config, "cpu");
1056
1057 #if !defined (__x86_64__) && !defined (__aarch64__) && !defined (__powerpc64__) && !defined(__arm__)
1058 void __sync_fetch_and_add_8 (void)
1059 {
1060   fformat(stderr, "%s called\n", __FUNCTION__);
1061   abort();
1062 }
1063 void __sync_add_and_fetch_8 (void)
1064 {
1065   fformat(stderr, "%s called\n", __FUNCTION__);
1066   abort();
1067 }
1068 #endif
1069
1070 void vnet_main_fixup (vlib_fork_fixup_t which) __attribute__ ((weak));
1071 void vnet_main_fixup (vlib_fork_fixup_t which) { }
1072
1073 void vlib_worker_thread_fork_fixup (vlib_fork_fixup_t which)
1074 {
1075   vlib_main_t * vm = vlib_get_main();
1076
1077   if (vlib_mains == 0)
1078     return;
1079
1080   ASSERT(os_get_cpu_number() == 0);
1081   vlib_worker_thread_barrier_sync(vm);
1082
1083   switch (which)
1084     {
1085     case VLIB_WORKER_THREAD_FORK_FIXUP_NEW_SW_IF_INDEX:
1086       vnet_main_fixup (VLIB_WORKER_THREAD_FORK_FIXUP_NEW_SW_IF_INDEX);
1087       break;
1088
1089     default:
1090       ASSERT(0);
1091     }
1092   vlib_worker_thread_barrier_release(vm);
1093 }
1094
1095 void vlib_worker_thread_barrier_sync(vlib_main_t *vm)
1096 {
1097   f64 deadline;
1098   u32 count;
1099   
1100   if (!vlib_mains)
1101       return;
1102
1103   count = vec_len (vlib_mains) - 1;
1104
1105   /* Tolerate recursive calls */
1106   if (++vlib_worker_threads[0].recursion_level > 1)
1107       return;
1108
1109   vlib_worker_threads[0].barrier_sync_count++;
1110
1111   ASSERT (os_get_cpu_number() == 0);
1112
1113   deadline = vlib_time_now (vm) + BARRIER_SYNC_TIMEOUT;
1114
1115   *vlib_worker_threads->wait_at_barrier = 1;
1116   while (*vlib_worker_threads->workers_at_barrier != count)
1117     {
1118       if (vlib_time_now(vm) > deadline)
1119         {
1120           fformat(stderr, "%s: worker thread deadlock\n", __FUNCTION__);
1121           os_panic();
1122         }
1123     }
1124 }
1125
1126 void vlib_worker_thread_barrier_release(vlib_main_t * vm)
1127 {
1128   f64 deadline;
1129
1130   if (!vlib_mains)
1131       return;
1132
1133   if (--vlib_worker_threads[0].recursion_level > 0)
1134     return;
1135
1136   deadline = vlib_time_now (vm) + BARRIER_SYNC_TIMEOUT;
1137
1138   *vlib_worker_threads->wait_at_barrier = 0;
1139
1140   while (*vlib_worker_threads->workers_at_barrier > 0)
1141     {
1142       if (vlib_time_now(vm) > deadline)
1143         {
1144           fformat(stderr, "%s: worker thread deadlock\n", __FUNCTION__);
1145           os_panic();
1146         }
1147     }
1148 }
1149
1150 static clib_error_t *
1151 show_threads_fn (vlib_main_t * vm,
1152        unformat_input_t * input,
1153        vlib_cli_command_t * cmd)
1154 {
1155   vlib_worker_thread_t * w;
1156   int i;
1157
1158   vlib_cli_output (vm, "%-7s%-20s%-12s%-8s%-7s%-7s%-7s%-10s",
1159                    "ID", "Name", "Type", "LWP",
1160                    "lcore", "Core", "Socket", "State");
1161
1162 #if !defined(__powerpc64__)
1163   for (i = 0; i < vec_len(vlib_worker_threads); i++)
1164     {
1165       w = vlib_worker_threads + i;
1166       u8 * line = NULL;
1167
1168       line = format(line, "%-7d%-20s%-12s%-8d",
1169                     i,
1170                     w->name ? w->name : (u8 *) "",
1171                     w->registration ? w->registration->name : "",
1172                     w->lwp);
1173
1174 #if DPDK==1
1175       int lcore = w->dpdk_lcore_id;
1176       if (lcore > -1)
1177         {
1178           line = format(line, "%-7u%-7u%-7u",
1179                         lcore,
1180                         lcore_config[lcore].core_id,
1181                         lcore_config[lcore].socket_id);
1182
1183           switch(lcore_config[lcore].state)
1184             {
1185               case WAIT:
1186                 line = format(line, "wait");
1187                 break;
1188               case RUNNING:
1189                 line = format(line, "running");
1190                 break;
1191               case FINISHED:
1192                 line = format(line, "finished");
1193                 break;
1194               default:
1195                 line = format(line, "unknown");
1196             }
1197         }
1198 #endif
1199       vlib_cli_output(vm, "%v", line);
1200       vec_free(line);
1201     }
1202 #endif
1203
1204   return 0;
1205 }
1206
1207
1208 VLIB_CLI_COMMAND (show_threads_command, static) = {
1209   .path = "show threads",
1210   .short_help = "Show threads",
1211   .function = show_threads_fn,
1212 };