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