1da9d22234ed410eafa09c3d84cb48415d6b0153
[vpp.git] / src / vlib / threads.h
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 #ifndef included_vlib_threads_h
16 #define included_vlib_threads_h
17
18 #include <vlib/main.h>
19 #include <vppinfra/callback.h>
20 #include <linux/sched.h>
21
22 void vlib_set_thread_name (char *name);
23
24 /* arg is actually a vlib__thread_t * */
25 typedef void (vlib_thread_function_t) (void *arg);
26
27 typedef struct vlib_thread_registration_
28 {
29   /* constructor generated list of thread registrations */
30   struct vlib_thread_registration_ *next;
31
32   /* config parameters */
33   char *name;
34   char *short_name;
35   vlib_thread_function_t *function;
36   uword mheap_size;
37   int fixed_count;
38   u32 count;
39   int no_data_structure_clone;
40   u32 frame_queue_nelts;
41
42   /* All threads of this type run on pthreads */
43   int use_pthreads;
44   u32 first_index;
45   uword *coremask;
46 } vlib_thread_registration_t;
47
48 /*
49  * Frames have their cpu / vlib_main_t index in the low-order N bits
50  * Make VLIB_MAX_CPUS a power-of-two, please...
51  */
52
53 #ifndef VLIB_MAX_CPUS
54 #define VLIB_MAX_CPUS 256
55 #endif
56
57 #if VLIB_MAX_CPUS > CLIB_MAX_MHEAPS
58 #error Please increase number of per-cpu mheaps
59 #endif
60
61 #define VLIB_CPU_MASK (VLIB_MAX_CPUS - 1)       /* 0x3f, max */
62 #define VLIB_OFFSET_MASK (~VLIB_CPU_MASK)
63
64 #define VLIB_LOG2_THREAD_STACK_SIZE (21)
65 #define VLIB_THREAD_STACK_SIZE (1<<VLIB_LOG2_THREAD_STACK_SIZE)
66
67 typedef enum
68 {
69   VLIB_FRAME_QUEUE_ELT_DISPATCH_FRAME,
70 } vlib_frame_queue_msg_type_t;
71
72 typedef struct
73 {
74   CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);
75   volatile u32 valid;
76   u32 msg_type;
77   u32 n_vectors;
78   u32 last_n_vectors;
79
80   /* 256 * 4 = 1024 bytes, even mult of cache line size */
81   u32 buffer_index[VLIB_FRAME_SIZE];
82 }
83 vlib_frame_queue_elt_t;
84
85 typedef struct
86 {
87   /* First cache line */
88   CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);
89   volatile u32 *wait_at_barrier;
90   volatile u32 *workers_at_barrier;
91
92   /* Second Cache Line */
93     CLIB_CACHE_LINE_ALIGN_MARK (cacheline1);
94   void *thread_mheap;
95   u8 *thread_stack;
96   void (*thread_function) (void *);
97   void *thread_function_arg;
98   i64 recursion_level;
99   elog_track_t elog_track;
100   u32 instance_id;
101   vlib_thread_registration_t *registration;
102   u8 *name;
103   u64 barrier_sync_count;
104   u8 barrier_elog_enabled;
105   const char *barrier_caller;
106   const char *barrier_context;
107   volatile u32 *node_reforks_required;
108
109   long lwp;
110   int cpu_id;
111   int core_id;
112   int numa_id;
113   pthread_t thread_id;
114 } vlib_worker_thread_t;
115
116 extern vlib_worker_thread_t *vlib_worker_threads;
117
118 typedef struct
119 {
120   /* enqueue side */
121   CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);
122   volatile u64 tail;
123   u64 enqueues;
124   u64 enqueue_ticks;
125   u64 enqueue_vectors;
126   u32 enqueue_full_events;
127
128   /* dequeue side */
129     CLIB_CACHE_LINE_ALIGN_MARK (cacheline1);
130   volatile u64 head;
131   u64 dequeues;
132   u64 dequeue_ticks;
133   u64 dequeue_vectors;
134   u64 trace;
135   u64 vector_threshold;
136
137   /* dequeue hint to enqueue side */
138     CLIB_CACHE_LINE_ALIGN_MARK (cacheline2);
139   volatile u64 head_hint;
140
141   /* read-only, constant, shared */
142     CLIB_CACHE_LINE_ALIGN_MARK (cacheline3);
143   vlib_frame_queue_elt_t *elts;
144   u32 nelts;
145 }
146 vlib_frame_queue_t;
147
148 typedef struct
149 {
150   vlib_frame_queue_elt_t **handoff_queue_elt_by_thread_index;
151   vlib_frame_queue_t **congested_handoff_queue_by_thread_index;
152 } vlib_frame_queue_per_thread_data_t;
153
154 typedef struct
155 {
156   u32 node_index;
157   u32 frame_queue_nelts;
158   u32 queue_hi_thresh;
159
160   vlib_frame_queue_t **vlib_frame_queues;
161   vlib_frame_queue_per_thread_data_t *per_thread_data;
162
163   /* for frame queue tracing */
164   frame_queue_trace_t *frame_queue_traces;
165   frame_queue_nelt_counter_t *frame_queue_histogram;
166 } vlib_frame_queue_main_t;
167
168 typedef struct
169 {
170   uword node_index;
171   uword type_opaque;
172   uword data;
173 } vlib_process_signal_event_mt_args_t;
174
175 /* Called early, in thread 0's context */
176 clib_error_t *vlib_thread_init (vlib_main_t * vm);
177
178 int vlib_frame_queue_enqueue (vlib_main_t * vm, u32 node_runtime_index,
179                               u32 frame_queue_index, vlib_frame_t * frame,
180                               vlib_frame_queue_msg_type_t type);
181
182 int
183 vlib_frame_queue_dequeue (vlib_main_t * vm, vlib_frame_queue_main_t * fqm);
184
185 void vlib_worker_thread_node_runtime_update (void);
186
187 void vlib_create_worker_threads (vlib_main_t * vm, int n,
188                                  void (*thread_function) (void *));
189
190 void vlib_worker_thread_init (vlib_worker_thread_t * w);
191 u32 vlib_frame_queue_main_init (u32 node_index, u32 frame_queue_nelts);
192
193 /* Check for a barrier sync request every 30ms */
194 #define BARRIER_SYNC_DELAY (0.030000)
195
196 #if CLIB_DEBUG > 0
197 /* long barrier timeout, for gdb... */
198 #define BARRIER_SYNC_TIMEOUT (600.1)
199 #else
200 #define BARRIER_SYNC_TIMEOUT (1.0)
201 #endif
202
203 #define vlib_worker_thread_barrier_sync(X) {vlib_worker_thread_barrier_sync_int(X, __FUNCTION__);}
204
205 void vlib_worker_thread_barrier_sync_int (vlib_main_t * vm,
206                                           const char *func_name);
207 void vlib_worker_thread_barrier_release (vlib_main_t * vm);
208 u8 vlib_worker_thread_barrier_held (void);
209 void vlib_worker_thread_initial_barrier_sync_and_release (vlib_main_t * vm);
210 void vlib_worker_thread_node_refork (void);
211 /**
212  * Wait until each of the workers has been once around the track
213  */
214 void vlib_worker_wait_one_loop (void);
215
216 static_always_inline uword
217 vlib_get_thread_index (void)
218 {
219   return __os_thread_index;
220 }
221
222 always_inline void
223 vlib_smp_unsafe_warning (void)
224 {
225   if (CLIB_DEBUG > 0)
226     {
227       if (vlib_get_thread_index ())
228         fformat (stderr, "%s: SMP unsafe warning...\n", __FUNCTION__);
229     }
230 }
231
232 always_inline int
233 __foreach_vlib_main_helper (vlib_main_t *ii, vlib_main_t **p)
234 {
235   vlib_main_t *vm;
236   u32 index = ii - (vlib_main_t *) 0;
237
238   if (index >= vec_len (vlib_global_main.vlib_mains))
239     return 0;
240
241   *p = vm = vlib_global_main.vlib_mains[index];
242   ASSERT (index == 0 || vm->parked_at_barrier == 1);
243   return 1;
244 }
245
246 #define foreach_vlib_main()                                                   \
247   for (vlib_main_t *ii = 0, *this_vlib_main;                                  \
248        __foreach_vlib_main_helper (ii, &this_vlib_main); ii++)                \
249     if (this_vlib_main)
250
251 #define foreach_sched_policy \
252   _(SCHED_OTHER, OTHER, "other") \
253   _(SCHED_BATCH, BATCH, "batch") \
254   _(SCHED_IDLE, IDLE, "idle")   \
255   _(SCHED_FIFO, FIFO, "fifo")   \
256   _(SCHED_RR, RR, "rr")
257
258 typedef enum
259 {
260 #define _(v,f,s) SCHED_POLICY_##f = v,
261   foreach_sched_policy
262 #undef _
263     SCHED_POLICY_N,
264 } sched_policy_t;
265
266 typedef struct
267 {
268   clib_error_t *(*vlib_launch_thread_cb) (void *fp, vlib_worker_thread_t * w,
269                                           unsigned cpu_id);
270   clib_error_t *(*vlib_thread_set_lcore_cb) (u32 thread, u16 cpu);
271 } vlib_thread_callbacks_t;
272
273 typedef struct
274 {
275   /* Link list of registrations, built by constructors */
276   vlib_thread_registration_t *next;
277
278   /* Vector of registrations, w/ non-data-structure clones at the top */
279   vlib_thread_registration_t **registrations;
280
281   uword *thread_registrations_by_name;
282
283   vlib_worker_thread_t *worker_threads;
284
285   /*
286    * Launch all threads as pthreads,
287    * not eal_rte_launch (strict affinity) threads
288    */
289   int use_pthreads;
290
291   /* Number of vlib_main / vnet_main clones */
292   u32 n_vlib_mains;
293
294   /* Number of thread stacks to create */
295   u32 n_thread_stacks;
296
297   /* Number of pthreads */
298   u32 n_pthreads;
299
300   /* Number of threads */
301   u32 n_threads;
302
303   /* Number of cores to skip, must match the core mask */
304   u32 skip_cores;
305
306   /* Thread prefix name */
307   u8 *thread_prefix;
308
309   /* main thread lcore */
310   u32 main_lcore;
311
312   /* Bitmap of available CPU cores */
313   uword *cpu_core_bitmap;
314
315   /* Bitmap of available CPU sockets (NUMA nodes) */
316   uword *cpu_socket_bitmap;
317
318   /* Worker handoff queues */
319   vlib_frame_queue_main_t *frame_queue_mains;
320
321   /* worker thread initialization barrier */
322   volatile u32 worker_thread_release;
323
324   /* scheduling policy */
325   u32 sched_policy;
326
327   /* scheduling policy priority */
328   u32 sched_priority;
329
330   /* callbacks */
331   vlib_thread_callbacks_t cb;
332   int extern_thread_mgmt;
333
334   /* NUMA-bound heap size */
335   uword numa_heap_size;
336
337 } vlib_thread_main_t;
338
339 extern vlib_thread_main_t vlib_thread_main;
340
341 #include <vlib/global_funcs.h>
342
343 #define VLIB_REGISTER_THREAD(x,...)                     \
344   __VA_ARGS__ vlib_thread_registration_t x;             \
345 static void __vlib_add_thread_registration_##x (void)   \
346   __attribute__((__constructor__)) ;                    \
347 static void __vlib_add_thread_registration_##x (void)   \
348 {                                                       \
349   vlib_thread_main_t * tm = &vlib_thread_main;          \
350   x.next = tm->next;                                    \
351   tm->next = &x;                                        \
352 }                                                       \
353 static void __vlib_rm_thread_registration_##x (void)    \
354   __attribute__((__destructor__)) ;                     \
355 static void __vlib_rm_thread_registration_##x (void)    \
356 {                                                       \
357   vlib_thread_main_t * tm = &vlib_thread_main;          \
358   VLIB_REMOVE_FROM_LINKED_LIST (tm->next, &x, next);    \
359 }                                                       \
360 __VA_ARGS__ vlib_thread_registration_t x
361
362 always_inline u32
363 vlib_num_workers ()
364 {
365   return vlib_thread_main.n_vlib_mains - 1;
366 }
367
368 always_inline u32
369 vlib_get_worker_thread_index (u32 worker_index)
370 {
371   return worker_index + 1;
372 }
373
374 always_inline u32
375 vlib_get_worker_index (u32 thread_index)
376 {
377   return thread_index - 1;
378 }
379
380 always_inline u32
381 vlib_get_current_worker_index ()
382 {
383   return vlib_get_thread_index () - 1;
384 }
385
386 static inline void
387 vlib_worker_thread_barrier_check (void)
388 {
389   if (PREDICT_FALSE (*vlib_worker_threads->wait_at_barrier))
390     {
391       vlib_global_main_t *vgm = vlib_get_global_main ();
392       vlib_main_t *vm = vlib_get_main ();
393       u32 thread_index = vm->thread_index;
394       f64 t = vlib_time_now (vm);
395
396       if (PREDICT_FALSE (vec_len (vm->barrier_perf_callbacks) != 0))
397         clib_call_callbacks (vm->barrier_perf_callbacks, vm,
398                              vm->clib_time.last_cpu_time, 0 /* enter */ );
399
400       if (PREDICT_FALSE (vlib_worker_threads->barrier_elog_enabled))
401         {
402           vlib_worker_thread_t *w = vlib_worker_threads + thread_index;
403           /* *INDENT-OFF* */
404           ELOG_TYPE_DECLARE (e) = {
405             .format = "barrier-wait-thread-%d",
406             .format_args = "i4",
407           };
408           /* *INDENT-ON* */
409
410           struct
411           {
412             u32 thread_index;
413           } __clib_packed *ed;
414
415           ed = ELOG_TRACK_DATA (&vlib_global_main.elog_main, e, w->elog_track);
416           ed->thread_index = thread_index;
417         }
418
419       if (CLIB_DEBUG > 0)
420         {
421           vm = vlib_get_main ();
422           vm->parked_at_barrier = 1;
423         }
424       clib_atomic_fetch_add (vlib_worker_threads->workers_at_barrier, 1);
425       while (*vlib_worker_threads->wait_at_barrier)
426         ;
427
428       /*
429        * Recompute the offset from thread-0 time.
430        * Note that vlib_time_now adds vm->time_offset, so
431        * clear it first. Save the resulting idea of "now", to
432        * see how well we're doing. See show_clock_command_fn(...)
433        */
434       {
435         f64 now;
436         vm->time_offset = 0.0;
437         now = vlib_time_now (vm);
438         vm->time_offset = vgm->vlib_mains[0]->time_last_barrier_release - now;
439         vm->time_last_barrier_release = vlib_time_now (vm);
440       }
441
442       if (CLIB_DEBUG > 0)
443         vm->parked_at_barrier = 0;
444       clib_atomic_fetch_add (vlib_worker_threads->workers_at_barrier, -1);
445
446       if (PREDICT_FALSE (*vlib_worker_threads->node_reforks_required))
447         {
448           if (PREDICT_FALSE (vlib_worker_threads->barrier_elog_enabled))
449             {
450               t = vlib_time_now (vm) - t;
451               vlib_worker_thread_t *w = vlib_worker_threads + thread_index;
452               /* *INDENT-OFF* */
453               ELOG_TYPE_DECLARE (e) = {
454                 .format = "barrier-refork-thread-%d",
455                 .format_args = "i4",
456               };
457               /* *INDENT-ON* */
458
459               struct
460               {
461                 u32 thread_index;
462               } __clib_packed *ed;
463
464               ed = ELOG_TRACK_DATA (&vlib_global_main.elog_main, e,
465                                     w->elog_track);
466               ed->thread_index = thread_index;
467             }
468
469           vlib_worker_thread_node_refork ();
470           clib_atomic_fetch_add (vlib_worker_threads->node_reforks_required,
471                                  -1);
472           while (*vlib_worker_threads->node_reforks_required)
473             ;
474         }
475       if (PREDICT_FALSE (vlib_worker_threads->barrier_elog_enabled))
476         {
477           t = vlib_time_now (vm) - t;
478           vlib_worker_thread_t *w = vlib_worker_threads + thread_index;
479           /* *INDENT-OFF* */
480           ELOG_TYPE_DECLARE (e) = {
481             .format = "barrier-released-thread-%d: %dus",
482             .format_args = "i4i4",
483           };
484           /* *INDENT-ON* */
485
486           struct
487           {
488             u32 thread_index;
489             u32 duration;
490           } __clib_packed *ed;
491
492           ed = ELOG_TRACK_DATA (&vlib_global_main.elog_main, e, w->elog_track);
493           ed->thread_index = thread_index;
494           ed->duration = (int) (1000000.0 * t);
495         }
496
497       if (PREDICT_FALSE (vec_len (vm->barrier_perf_callbacks) != 0))
498         clib_call_callbacks (vm->barrier_perf_callbacks, vm,
499                              vm->clib_time.last_cpu_time, 1 /* leave */ );
500     }
501 }
502
503 always_inline vlib_main_t *
504 vlib_get_worker_vlib_main (u32 worker_index)
505 {
506   vlib_main_t *vm;
507   vlib_thread_main_t *tm = &vlib_thread_main;
508   ASSERT (worker_index < tm->n_vlib_mains - 1);
509   vm = vlib_get_main_by_index (worker_index + 1);
510   ASSERT (vm);
511   return vm;
512 }
513
514 static inline u8
515 vlib_thread_is_main_w_barrier (void)
516 {
517   return (!vlib_num_workers ()
518           || ((vlib_get_thread_index () == 0
519                && vlib_worker_threads->wait_at_barrier[0])));
520 }
521
522 static inline void
523 vlib_put_frame_queue_elt (vlib_frame_queue_elt_t * hf)
524 {
525   CLIB_MEMORY_BARRIER ();
526   hf->valid = 1;
527 }
528
529 static inline vlib_frame_queue_elt_t *
530 vlib_get_frame_queue_elt (u32 frame_queue_index, u32 index)
531 {
532   vlib_frame_queue_t *fq;
533   vlib_frame_queue_elt_t *elt;
534   vlib_thread_main_t *tm = &vlib_thread_main;
535   vlib_frame_queue_main_t *fqm =
536     vec_elt_at_index (tm->frame_queue_mains, frame_queue_index);
537   u64 new_tail;
538
539   fq = fqm->vlib_frame_queues[index];
540   ASSERT (fq);
541
542   new_tail = clib_atomic_add_fetch (&fq->tail, 1);
543
544   /* Wait until a ring slot is available */
545   while (new_tail >= fq->head_hint + fq->nelts)
546     vlib_worker_thread_barrier_check ();
547
548   elt = fq->elts + (new_tail & (fq->nelts - 1));
549
550   /* this would be very bad... */
551   while (elt->valid)
552     ;
553
554   elt->msg_type = VLIB_FRAME_QUEUE_ELT_DISPATCH_FRAME;
555   elt->last_n_vectors = elt->n_vectors = 0;
556
557   return elt;
558 }
559
560 static inline vlib_frame_queue_t *
561 is_vlib_frame_queue_congested (u32 frame_queue_index,
562                                u32 index,
563                                u32 queue_hi_thresh,
564                                vlib_frame_queue_t **
565                                handoff_queue_by_worker_index)
566 {
567   vlib_frame_queue_t *fq;
568   vlib_thread_main_t *tm = &vlib_thread_main;
569   vlib_frame_queue_main_t *fqm =
570     vec_elt_at_index (tm->frame_queue_mains, frame_queue_index);
571
572   fq = handoff_queue_by_worker_index[index];
573   if (fq != (vlib_frame_queue_t *) (~0))
574     return fq;
575
576   fq = fqm->vlib_frame_queues[index];
577   ASSERT (fq);
578
579   if (PREDICT_FALSE (fq->tail >= (fq->head_hint + queue_hi_thresh)))
580     {
581       /* a valid entry in the array will indicate the queue has reached
582        * the specified threshold and is congested
583        */
584       handoff_queue_by_worker_index[index] = fq;
585       fq->enqueue_full_events++;
586       return fq;
587     }
588
589   return NULL;
590 }
591
592 static inline vlib_frame_queue_elt_t *
593 vlib_get_worker_handoff_queue_elt (u32 frame_queue_index,
594                                    u32 vlib_worker_index,
595                                    vlib_frame_queue_elt_t **
596                                    handoff_queue_elt_by_worker_index)
597 {
598   vlib_frame_queue_elt_t *elt;
599
600   if (handoff_queue_elt_by_worker_index[vlib_worker_index])
601     return handoff_queue_elt_by_worker_index[vlib_worker_index];
602
603   elt = vlib_get_frame_queue_elt (frame_queue_index, vlib_worker_index);
604
605   handoff_queue_elt_by_worker_index[vlib_worker_index] = elt;
606
607   return elt;
608 }
609
610 u8 *vlib_thread_stack_init (uword thread_index);
611 int vlib_thread_cb_register (struct vlib_main_t *vm,
612                              vlib_thread_callbacks_t * cb);
613 extern void *rpc_call_main_thread_cb_fn;
614
615 void
616 vlib_process_signal_event_mt_helper (vlib_process_signal_event_mt_args_t *
617                                      args);
618 void vlib_rpc_call_main_thread (void *function, u8 * args, u32 size);
619 void vlib_get_thread_core_numa (vlib_worker_thread_t * w, unsigned cpu_id);
620 vlib_thread_main_t *vlib_get_thread_main_not_inline (void);
621
622 #endif /* included_vlib_threads_h */
623
624 /*
625  * fd.io coding-style-patch-verification: ON
626  *
627  * Local Variables:
628  * eval: (c-set-style "gnu")
629  * End:
630  */