dpdk: Add support for Mellanox ConnectX-4 devices
[vpp.git] / vlib-api / vlibmemory / memory_vlib.c
1 /*
2  *------------------------------------------------------------------
3  * memory_vlib.c
4  *
5  * Copyright (c) 2009 Cisco and/or its affiliates.
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at:
9  *
10  *     http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *------------------------------------------------------------------
18  */
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <sys/types.h>
25 #include <signal.h>
26 #include <pthread.h>
27 #include <vppinfra/vec.h>
28 #include <vppinfra/hash.h>
29 #include <vppinfra/pool.h>
30 #include <vppinfra/format.h>
31 #include <vppinfra/byte_order.h>
32 #include <vppinfra/elog.h>
33 #include <stdarg.h>
34 #include <vlib/vlib.h>
35 #include <vlib/unix/unix.h>
36 #include <vlibapi/api.h>
37 #include <vlibmemory/api.h>
38
39 #define TRACE_VLIB_MEMORY_QUEUE 0
40
41 #include <vlibmemory/vl_memory_msg_enum.h>      /* enumerate all vlib messages */
42
43 #define vl_typedefs             /* define message structures */
44 #include <vlibmemory/vl_memory_api_h.h>
45 #undef vl_typedefs
46
47 /* instantiate all the print functions we know about */
48 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
49 #define vl_printfun
50 #include <vlibmemory/vl_memory_api_h.h>
51 #undef vl_printfun
52
53 static inline void *
54 vl_api_memclnt_create_t_print (vl_api_memclnt_create_t * a, void *handle)
55 {
56   vl_print (handle, "vl_api_memclnt_create_t:\n");
57   vl_print (handle, "name: %s\n", a->name);
58   vl_print (handle, "input_queue: 0x%wx\n", a->input_queue);
59   vl_print (handle, "context: %u\n", (unsigned) a->context);
60   vl_print (handle, "ctx_quota: %ld\n", (long) a->ctx_quota);
61   return handle;
62 }
63
64 static inline void *
65 vl_api_memclnt_delete_t_print (vl_api_memclnt_delete_t * a, void *handle)
66 {
67   vl_print (handle, "vl_api_memclnt_delete_t:\n");
68   vl_print (handle, "index: %u\n", (unsigned) a->index);
69   vl_print (handle, "handle: 0x%wx\n", a->handle);
70   return handle;
71 }
72
73 /* instantiate all the endian swap functions we know about */
74 #define vl_endianfun
75 #include <vlibmemory/vl_memory_api_h.h>
76 #undef vl_endianfun
77
78 void vl_socket_api_send (vl_api_registration_t * rp, u8 * elem)
79   __attribute__ ((weak));
80
81 void
82 vl_socket_api_send (vl_api_registration_t * rp, u8 * elem)
83 {
84   static int count;
85
86   if (count++ < 5)
87     clib_warning ("need to link against -lvlibsocket, msg not sent!");
88 }
89
90 void
91 vl_msg_api_send (vl_api_registration_t * rp, u8 * elem)
92 {
93   if (PREDICT_FALSE (rp->registration_type > REGISTRATION_TYPE_SHMEM))
94     {
95       vl_socket_api_send (rp, elem);
96     }
97   else
98     {
99       vl_msg_api_send_shmem (rp->vl_input_queue, elem);
100     }
101 }
102
103 u8 *
104 vl_api_serialize_message_table (api_main_t * am, u8 * vector)
105 {
106   serialize_main_t _sm, *sm = &_sm;
107   hash_pair_t *hp;
108   u32 nmsg = hash_elts (am->msg_index_by_name_and_crc);
109
110   serialize_open_vector (sm, vector);
111
112   /* serialize the count */
113   serialize_integer (sm, nmsg, sizeof (u32));
114
115   hash_foreach_pair (hp, am->msg_index_by_name_and_crc, (
116                                                           {
117                                                           serialize_likely_small_unsigned_integer
118                                                           (sm, hp->value[0]);
119                                                           serialize_cstring
120                                                           (sm,
121                                                            (char *) hp->key);
122                                                           }));
123
124   return serialize_close_vector (sm);
125 }
126
127 /*
128  * vl_api_memclnt_create_t_handler
129  */
130 void
131 vl_api_memclnt_create_t_handler (vl_api_memclnt_create_t * mp)
132 {
133   vl_api_registration_t **regpp;
134   vl_api_registration_t *regp;
135   vl_api_memclnt_create_reply_t *rp;
136   svm_region_t *svm;
137   unix_shared_memory_queue_t *q;
138   int rv = 0;
139   void *oldheap;
140   api_main_t *am = &api_main;
141   u8 *serialized_message_table = 0;
142
143   /*
144    * This is tortured. Maintain a vlib-address-space private
145    * pool of client registrations. We use the shared-memory virtual
146    * address of client structure as a handle, to allow direct
147    * manipulation of context quota vbls from the client library.
148    *
149    * This scheme causes trouble w/ API message trace replay, since
150    * some random VA from clib_mem_alloc() certainly won't
151    * occur in the Linux sim. The (very) few places
152    * that care need to use the pool index.
153    *
154    * Putting the registration object(s) into a pool in shared memory and
155    * using the pool index as a handle seems like a great idea.
156    * Unfortunately, each and every reference to that pool would need
157    * to be protected by a mutex:
158    *
159    *     Client                      VLIB
160    *     ------                      ----
161    *     convert pool index to
162    *     pointer.
163    *     <deschedule>
164    *                                 expand pool
165    *                                 <deschedule>
166    *     kaboom!
167    */
168
169   pool_get (am->vl_clients, regpp);
170
171   svm = am->vlib_rp;
172
173   if (am->serialized_message_table_in_shmem == 0)
174     serialized_message_table = vl_api_serialize_message_table (am, 0);
175
176   pthread_mutex_lock (&svm->mutex);
177   oldheap = svm_push_data_heap (svm);
178   *regpp = clib_mem_alloc (sizeof (vl_api_registration_t));
179
180   regp = *regpp;
181   memset (regp, 0, sizeof (*regp));
182   regp->registration_type = REGISTRATION_TYPE_SHMEM;
183   regp->vl_api_registration_pool_index = regpp - am->vl_clients;
184
185   q = regp->vl_input_queue = (unix_shared_memory_queue_t *) (uword)
186     mp->input_queue;
187
188   regp->name = format (0, "%s", mp->name);
189   vec_add1 (regp->name, 0);
190   if (serialized_message_table)
191     am->serialized_message_table_in_shmem =
192       vec_dup (serialized_message_table);
193
194   pthread_mutex_unlock (&svm->mutex);
195   svm_pop_heap (oldheap);
196
197   vec_free (serialized_message_table);
198
199   rp = vl_msg_api_alloc (sizeof (*rp));
200   rp->_vl_msg_id = ntohs (VL_API_MEMCLNT_CREATE_REPLY);
201   rp->handle = (uword) regp;
202   rp->index = vl_msg_api_handle_from_index_and_epoch
203     (regp->vl_api_registration_pool_index,
204      am->shmem_hdr->application_restarts);
205   rp->context = mp->context;
206   rp->response = ntohl (rv);
207   rp->message_table = (u64) am->serialized_message_table_in_shmem;
208
209   vl_msg_api_send_shmem (q, (u8 *) & rp);
210 }
211
212 /* Application callback to clean up leftover registrations from this client */
213 int vl_api_memclnt_delete_callback (u32 client_index) __attribute__ ((weak));
214
215 int
216 vl_api_memclnt_delete_callback (u32 client_index)
217 {
218   return 0;
219 }
220
221 /*
222  * vl_api_memclnt_delete_t_handler
223  */
224 void
225 vl_api_memclnt_delete_t_handler (vl_api_memclnt_delete_t * mp)
226 {
227   vl_api_registration_t **regpp;
228   vl_api_registration_t *regp;
229   vl_api_memclnt_delete_reply_t *rp;
230   svm_region_t *svm;
231   void *oldheap;
232   api_main_t *am = &api_main;
233   u32 handle, client_index, epoch;
234
235   handle = mp->index;
236
237   if (vl_api_memclnt_delete_callback (handle))
238     return;
239
240   epoch = vl_msg_api_handle_get_epoch (handle);
241   client_index = vl_msg_api_handle_get_index (handle);
242
243   if (epoch != (am->shmem_hdr->application_restarts & VL_API_EPOCH_MASK))
244     {
245       clib_warning
246         ("Stale clnt delete index %d old epoch %d cur epoch %d",
247          client_index, epoch,
248          (am->shmem_hdr->application_restarts & VL_API_EPOCH_MASK));
249       return;
250     }
251
252   regpp = am->vl_clients + client_index;
253
254   if (!pool_is_free (am->vl_clients, regpp))
255     {
256       regp = *regpp;
257       svm = am->vlib_rp;
258
259       /* $$$ check the input queue for e.g. punted sf's */
260
261       rp = vl_msg_api_alloc (sizeof (*rp));
262       rp->_vl_msg_id = ntohs (VL_API_MEMCLNT_DELETE_REPLY);
263       rp->handle = mp->handle;
264       rp->response = 1;
265
266       vl_msg_api_send_shmem (regp->vl_input_queue, (u8 *) & rp);
267
268       if (client_index != regp->vl_api_registration_pool_index)
269         {
270           clib_warning ("mismatch client_index %d pool_index %d",
271                         client_index, regp->vl_api_registration_pool_index);
272           vl_msg_api_free (rp);
273           return;
274         }
275
276       /* No dangling references, please */
277       *regpp = 0;
278
279       pool_put_index (am->vl_clients, regp->vl_api_registration_pool_index);
280
281       pthread_mutex_lock (&svm->mutex);
282       oldheap = svm_push_data_heap (svm);
283       /* Poison the old registration */
284       memset (regp, 0xF1, sizeof (*regp));
285       clib_mem_free (regp);
286       pthread_mutex_unlock (&svm->mutex);
287       svm_pop_heap (oldheap);
288     }
289   else
290     {
291       clib_warning ("unknown client ID %d", mp->index);
292     }
293 }
294
295 void
296 vl_api_get_first_msg_id_t_handler (vl_api_get_first_msg_id_t * mp)
297 {
298   vl_api_get_first_msg_id_reply_t *rmp;
299   unix_shared_memory_queue_t *q;
300   uword *p;
301   api_main_t *am = &api_main;
302   vl_api_msg_range_t *rp;
303   u8 name[64];
304   u16 first_msg_id = ~0;
305   int rv = -7;                  /* VNET_API_ERROR_INVALID_VALUE */
306
307   q = vl_api_client_index_to_input_queue (mp->client_index);
308   if (!q)
309     return;
310
311   if (am->msg_range_by_name == 0)
312     goto out;
313
314   strncpy ((char *) name, (char *) mp->name, ARRAY_LEN (name) - 1);
315
316   p = hash_get_mem (am->msg_range_by_name, name);
317   if (p == 0)
318     goto out;
319
320   rp = vec_elt_at_index (am->msg_ranges, p[0]);
321
322   first_msg_id = rp->first_msg_id;
323   rv = 0;
324
325 out:
326
327   rmp = vl_msg_api_alloc (sizeof (*rmp));
328   rmp->_vl_msg_id = ntohs (VL_API_GET_FIRST_MSG_ID_REPLY);
329   rmp->context = mp->context;
330   rmp->retval = ntohl (rv);
331   rmp->first_msg_id = ntohs (first_msg_id);
332   vl_msg_api_send_shmem (q, (u8 *) & rmp);
333 }
334
335 #define foreach_vlib_api_msg                    \
336 _(MEMCLNT_CREATE, memclnt_create)               \
337 _(MEMCLNT_DELETE, memclnt_delete)               \
338 _(GET_FIRST_MSG_ID, get_first_msg_id)
339
340 /*
341  * vl_api_init
342  */
343 static int
344 memory_api_init (char *region_name)
345 {
346   int rv;
347   vl_msg_api_msg_config_t cfg;
348   vl_msg_api_msg_config_t *c = &cfg;
349
350   if ((rv = vl_map_shmem (region_name, 1 /* is_vlib */ )) < 0)
351     return rv;
352
353 #define _(N,n) do {                                             \
354     c->id = VL_API_##N;                                         \
355     c->name = #n;                                               \
356     c->handler = vl_api_##n##_t_handler;                        \
357     c->cleanup = vl_noop_handler;                               \
358     c->endian = vl_api_##n##_t_endian;                          \
359     c->print = vl_api_##n##_t_print;                            \
360     c->size = sizeof(vl_api_##n##_t);                           \
361     c->traced = 1; /* trace, so these msgs print */             \
362     c->replay = 0; /* don't replay client create/delete msgs */ \
363     vl_msg_api_config(c);} while (0);
364
365   foreach_vlib_api_msg;
366 #undef _
367
368   return 0;
369 }
370
371 #define foreach_histogram_bucket                \
372 _(400)                                          \
373 _(200)                                          \
374 _(100)                                          \
375 _(10)
376
377 typedef enum
378 {
379 #define _(n) SLEEP_##n##_US,
380   foreach_histogram_bucket
381 #undef _
382     SLEEP_N_BUCKETS,
383 } histogram_index_t;
384
385 static u64 vector_rate_histogram[SLEEP_N_BUCKETS];
386
387 static void memclnt_queue_callback (vlib_main_t * vm);
388
389 static uword
390 memclnt_process (vlib_main_t * vm,
391                  vlib_node_runtime_t * node, vlib_frame_t * f)
392 {
393   uword mp;
394   vl_shmem_hdr_t *shm;
395   unix_shared_memory_queue_t *q;
396   clib_error_t *e;
397   int rv;
398   api_main_t *am = &api_main;
399   f64 dead_client_scan_time;
400   f64 sleep_time, start_time;
401   f64 vector_rate;
402
403   vlib_set_queue_signal_callback (vm, memclnt_queue_callback);
404
405   if ((rv = memory_api_init (am->region_name)) < 0)
406     {
407       clib_warning ("memory_api_init returned %d, wait for godot...", rv);
408       vlib_process_suspend (vm, 1e70);
409     }
410
411   shm = am->shmem_hdr;
412   ASSERT (shm);
413   q = shm->vl_input_queue;
414   ASSERT (q);
415
416   e = vlib_call_init_exit_functions
417     (vm, vm->api_init_function_registrations, 1 /* call_once */ );
418   if (e)
419     clib_error_report (e);
420
421   sleep_time = 20.0;
422   dead_client_scan_time = vlib_time_now (vm) + 20.0;
423
424   /* $$$ pay attention to frame size, control CPU usage */
425   while (1)
426     {
427       uword event_type __attribute__ ((unused));
428       i8 *headp;
429       int need_broadcast;
430
431       /*
432        * There's a reason for checking the queue before
433        * sleeping. If the vlib application crashes, it's entirely
434        * possible for a client to enqueue a connect request
435        * during the process restart interval.
436        *
437        * Unless some force of physics causes the new incarnation
438        * of the application to process the request, the client will
439        * sit and wait for Godot...
440        */
441       vector_rate = vlib_last_vector_length_per_node (vm);
442       start_time = vlib_time_now (vm);
443       while (1)
444         {
445           pthread_mutex_lock (&q->mutex);
446           if (q->cursize == 0)
447             {
448               vm->api_queue_nonempty = 0;
449               pthread_mutex_unlock (&q->mutex);
450
451               if (TRACE_VLIB_MEMORY_QUEUE)
452                 {
453                   /* *INDENT-OFF* */
454                   ELOG_TYPE_DECLARE (e) =
455                     {
456                       .format = "q-underflow: len %d",
457                       .format_args = "i4",
458                     };
459                   /* *INDENT-ON* */
460                   struct
461                   {
462                     u32 len;
463                   } *ed;
464                   ed = ELOG_DATA (&vm->elog_main, e);
465                   ed->len = 0;
466                 }
467               sleep_time = 20.0;
468               break;
469             }
470
471           headp = (i8 *) (q->data + sizeof (uword) * q->head);
472           clib_memcpy (&mp, headp, sizeof (uword));
473
474           q->head++;
475           need_broadcast = (q->cursize == q->maxsize / 2);
476           q->cursize--;
477
478           if (PREDICT_FALSE (q->head == q->maxsize))
479             q->head = 0;
480           pthread_mutex_unlock (&q->mutex);
481           if (need_broadcast)
482             (void) pthread_cond_broadcast (&q->condvar);
483
484           vl_msg_api_handler_with_vm_node (am, (void *) mp, vm, node);
485
486           /* Allow no more than 10us without a pause */
487           if (vlib_time_now (vm) > start_time + 10e-6)
488             {
489               int index = SLEEP_400_US;
490               if (vector_rate > 40.0)
491                 sleep_time = 400e-6;
492               else if (vector_rate > 20.0)
493                 {
494                   index = SLEEP_200_US;
495                   sleep_time = 200e-6;
496                 }
497               else if (vector_rate >= 1.0)
498                 {
499                   index = SLEEP_100_US;
500                   sleep_time = 100e-6;
501                 }
502               else
503                 {
504                   index = SLEEP_10_US;
505                   sleep_time = 10e-6;
506                 }
507               vector_rate_histogram[index] += 1;
508               break;
509             }
510         }
511
512       event_type = vlib_process_wait_for_event_or_clock (vm, sleep_time);
513       vm->queue_signal_pending = 0;
514       vlib_process_get_events (vm, 0 /* event_data */ );
515
516       if (vlib_time_now (vm) > dead_client_scan_time)
517         {
518           vl_api_registration_t **regpp;
519           vl_api_registration_t *regp;
520           unix_shared_memory_queue_t *q;
521           static u32 *dead_indices;
522           static u32 *confused_indices;
523
524           vec_reset_length (dead_indices);
525           vec_reset_length (confused_indices);
526
527           /* *INDENT-OFF* */
528           pool_foreach (regpp, am->vl_clients,
529           ({
530             regp = *regpp;
531             if (regp)
532               {
533                 q = regp->vl_input_queue;
534                 if (kill (q->consumer_pid, 0) < 0)
535                   {
536                     vec_add1(dead_indices, regpp - am->vl_clients);
537                   }
538               }
539             else
540               {
541                 clib_warning ("NULL client registration index %d",
542                               regpp - am->vl_clients);
543                 vec_add1 (confused_indices, regpp - am->vl_clients);
544               }
545           }));
546           /* *INDENT-ON* */
547           /* This should "never happen," but if it does, fix it... */
548           if (PREDICT_FALSE (vec_len (confused_indices) > 0))
549             {
550               int i;
551               for (i = 0; i < vec_len (confused_indices); i++)
552                 {
553                   pool_put_index (am->vl_clients, confused_indices[i]);
554                 }
555             }
556
557           if (PREDICT_FALSE (vec_len (dead_indices) > 0))
558             {
559               int i;
560               svm_region_t *svm;
561               void *oldheap;
562
563               /* Allow the application to clean up its registrations */
564               for (i = 0; i < vec_len (dead_indices); i++)
565                 {
566                   regpp = pool_elt_at_index (am->vl_clients, dead_indices[i]);
567                   if (regpp)
568                     {
569                       u32 handle;
570
571                       handle = vl_msg_api_handle_from_index_and_epoch
572                         (dead_indices[i], shm->application_restarts);
573                       (void) vl_api_memclnt_delete_callback (handle);
574                     }
575                 }
576
577               svm = am->vlib_rp;
578               pthread_mutex_lock (&svm->mutex);
579               oldheap = svm_push_data_heap (svm);
580
581               for (i = 0; i < vec_len (dead_indices); i++)
582                 {
583                   regpp = pool_elt_at_index (am->vl_clients, dead_indices[i]);
584                   if (regpp)
585                     {
586                       /* Poison the old registration */
587                       memset (*regpp, 0xF3, sizeof (**regpp));
588                       clib_mem_free (*regpp);
589                       /* no dangling references, please */
590                       *regpp = 0;
591                     }
592                   else
593                     {
594                       svm_pop_heap (oldheap);
595                       clib_warning ("Duplicate free, client index %d",
596                                     regpp - am->vl_clients);
597                       oldheap = svm_push_data_heap (svm);
598                     }
599                 }
600
601               svm_client_scan_this_region_nolock (am->vlib_rp);
602
603               pthread_mutex_unlock (&svm->mutex);
604               svm_pop_heap (oldheap);
605               for (i = 0; i < vec_len (dead_indices); i++)
606                 pool_put_index (am->vl_clients, dead_indices[i]);
607             }
608
609           dead_client_scan_time = vlib_time_now (vm) + 20.0;
610         }
611
612       if (TRACE_VLIB_MEMORY_QUEUE)
613         {
614           /* *INDENT-OFF* */
615           ELOG_TYPE_DECLARE (e) = {
616             .format = "q-awake: len %d",
617             .format_args = "i4",
618           };
619           /* *INDENT-ON* */
620           struct
621           {
622             u32 len;
623           } *ed;
624           ed = ELOG_DATA (&vm->elog_main, e);
625           ed->len = q->cursize;
626         }
627     }
628
629   return 0;
630 }
631
632 static clib_error_t *
633 vl_api_show_histogram_command (vlib_main_t * vm,
634                                unformat_input_t * input,
635                                vlib_cli_command_t * cli_cmd)
636 {
637   u64 total_counts = 0;
638   int i;
639
640   for (i = 0; i < SLEEP_N_BUCKETS; i++)
641     {
642       total_counts += vector_rate_histogram[i];
643     }
644
645   if (total_counts == 0)
646     {
647       vlib_cli_output (vm, "No control-plane activity.");
648       return 0;
649     }
650
651 #define _(n)                                                    \
652     do {                                                        \
653         f64 percent;                                            \
654         percent = ((f64) vector_rate_histogram[SLEEP_##n##_US]) \
655             / (f64) total_counts;                               \
656         percent *= 100.0;                                       \
657         vlib_cli_output (vm, "Sleep %3d us: %llu, %.2f%%",n,    \
658                          vector_rate_histogram[SLEEP_##n##_US], \
659                          percent);                              \
660     } while (0);
661   foreach_histogram_bucket;
662 #undef _
663
664   return 0;
665 }
666
667 /* *INDENT-OFF* */
668 VLIB_CLI_COMMAND (cli_show_api_histogram_command, static) = {
669     .path = "show api histogram",
670     .short_help = "show api histogram",
671     .function = vl_api_show_histogram_command,
672 };
673 /* *INDENT-ON* */
674
675 static clib_error_t *
676 vl_api_clear_histogram_command (vlib_main_t * vm,
677                                 unformat_input_t * input,
678                                 vlib_cli_command_t * cli_cmd)
679 {
680   int i;
681
682   for (i = 0; i < SLEEP_N_BUCKETS; i++)
683     vector_rate_histogram[i] = 0;
684   return 0;
685 }
686
687 /* *INDENT-OFF* */
688 VLIB_CLI_COMMAND (cli_clear_api_histogram_command, static) = {
689     .path = "clear api histogram",
690     .short_help = "clear api histogram",
691     .function = vl_api_clear_histogram_command,
692 };
693 /* *INDENT-ON* */
694
695
696 /* *INDENT-OFF* */
697 VLIB_REGISTER_NODE (memclnt_node,static) = {
698     .function = memclnt_process,
699     .type = VLIB_NODE_TYPE_PROCESS,
700     .name = "api-rx-from-ring",
701     .state = VLIB_NODE_STATE_DISABLED,
702 };
703 /* *INDENT-ON* */
704
705 static void
706 memclnt_queue_callback (vlib_main_t * vm)
707 {
708   static volatile int *cursizep;
709
710   if (PREDICT_FALSE (cursizep == 0))
711     {
712       api_main_t *am = &api_main;
713       vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
714       unix_shared_memory_queue_t *q;
715
716       if (shmem_hdr == 0)
717         return;
718
719       q = shmem_hdr->vl_input_queue;
720       if (q == 0)
721         return;
722       cursizep = &q->cursize;
723     }
724
725   if (*cursizep >= 1)
726     {
727       vm->queue_signal_pending = 1;
728       vm->api_queue_nonempty = 1;
729       vlib_process_signal_event (vm, memclnt_node.index,
730                                  /* event_type */ 0, /* event_data */ 0);
731     }
732 }
733
734 void
735 vl_enable_disable_memory_api (vlib_main_t * vm, int enable)
736 {
737   vlib_node_set_state (vm, memclnt_node.index,
738                        (enable
739                         ? VLIB_NODE_STATE_POLLING
740                         : VLIB_NODE_STATE_DISABLED));
741 }
742
743 static uword
744 api_rx_from_node (vlib_main_t * vm,
745                   vlib_node_runtime_t * node, vlib_frame_t * frame)
746 {
747   uword n_packets = frame->n_vectors;
748   uword n_left_from;
749   u32 *from;
750   static u8 *long_msg;
751
752   vec_validate (long_msg, 4095);
753   n_left_from = frame->n_vectors;
754   from = vlib_frame_args (frame);
755
756   while (n_left_from > 0)
757     {
758       u32 bi0;
759       vlib_buffer_t *b0;
760       void *msg;
761       uword msg_len;
762
763       bi0 = from[0];
764       b0 = vlib_get_buffer (vm, bi0);
765       from += 1;
766       n_left_from -= 1;
767
768       msg = b0->data + b0->current_data;
769       msg_len = b0->current_length;
770       if (b0->flags & VLIB_BUFFER_NEXT_PRESENT)
771         {
772           ASSERT (long_msg != 0);
773           _vec_len (long_msg) = 0;
774           vec_add (long_msg, msg, msg_len);
775           while (b0->flags & VLIB_BUFFER_NEXT_PRESENT)
776             {
777               b0 = vlib_get_buffer (vm, b0->next_buffer);
778               msg = b0->data + b0->current_data;
779               msg_len = b0->current_length;
780               vec_add (long_msg, msg, msg_len);
781             }
782           msg = long_msg;
783         }
784       vl_msg_api_handler_no_trace_no_free (msg);
785     }
786
787   /* Free what we've been given. */
788   vlib_buffer_free (vm, vlib_frame_args (frame), n_packets);
789
790   return n_packets;
791 }
792
793 /* *INDENT-OFF* */
794 VLIB_REGISTER_NODE (api_rx_from_node_node,static) = {
795     .function = api_rx_from_node,
796     .type = VLIB_NODE_TYPE_INTERNAL,
797     .vector_size = 4,
798     .name = "api-rx-from-node",
799 };
800 /* *INDENT-ON* */
801
802 static clib_error_t *
803 setup_memclnt_exit (vlib_main_t * vm)
804 {
805   atexit (vl_unmap_shmem);
806   return 0;
807 }
808
809 VLIB_INIT_FUNCTION (setup_memclnt_exit);
810
811
812 static clib_error_t *
813 vl_api_ring_command (vlib_main_t * vm,
814                      unformat_input_t * input, vlib_cli_command_t * cli_cmd)
815 {
816   int i;
817   ring_alloc_t *ap;
818   vl_shmem_hdr_t *shmem_hdr;
819   api_main_t *am = &api_main;
820
821   shmem_hdr = am->shmem_hdr;
822
823   if (shmem_hdr == 0)
824     {
825       vlib_cli_output (vm, "Shared memory segment not initialized...\n");
826       return 0;
827     }
828
829   vlib_cli_output (vm, "%8s %8s %8s %8s %8s\n",
830                    "Owner", "Size", "Nitems", "Hits", "Misses");
831
832   ap = shmem_hdr->vl_rings;
833
834   for (i = 0; i < vec_len (shmem_hdr->vl_rings); i++)
835     {
836       vlib_cli_output (vm, "%8s %8d %8d %8d %8d\n",
837                        "vlib", ap->size, ap->nitems, ap->hits, ap->misses);
838       ap++;
839     }
840
841   ap = shmem_hdr->client_rings;
842
843   for (i = 0; i < vec_len (shmem_hdr->client_rings); i++)
844     {
845       vlib_cli_output (vm, "%8s %8d %8d %8d %8d\n",
846                        "clnt", ap->size, ap->nitems, ap->hits, ap->misses);
847       ap++;
848     }
849
850   vlib_cli_output (vm, "%d ring miss fallback allocations\n",
851                    am->ring_misses);
852
853   vlib_cli_output (vm, "%d application restarts, %d reclaimed msgs\n",
854                    shmem_hdr->application_restarts,
855                    shmem_hdr->restart_reclaims);
856   return 0;
857 }
858
859 void dump_socket_clients (vlib_main_t * vm, api_main_t * am)
860   __attribute__ ((weak));
861
862 void
863 dump_socket_clients (vlib_main_t * vm, api_main_t * am)
864 {
865 }
866
867 static clib_error_t *
868 vl_api_client_command (vlib_main_t * vm,
869                        unformat_input_t * input, vlib_cli_command_t * cli_cmd)
870 {
871   vl_api_registration_t **regpp, *regp;
872   unix_shared_memory_queue_t *q;
873   char *health;
874   api_main_t *am = &api_main;
875   u32 *confused_indices = 0;
876
877   if (!pool_elts (am->vl_clients))
878     goto socket_clients;
879   vlib_cli_output (vm, "Shared memory clients");
880   vlib_cli_output (vm, "%16s %8s %14s %18s %s",
881                    "Name", "PID", "Queue Length", "Queue VA", "Health");
882
883   /* *INDENT-OFF* */
884   pool_foreach (regpp, am->vl_clients,
885   ({
886     regp = *regpp;
887
888     if (regp)
889       {
890         q = regp->vl_input_queue;
891         if (kill (q->consumer_pid, 0) < 0)
892           {
893             health = "DEAD";
894           }
895         else
896           {
897             health = "alive";
898           }
899         vlib_cli_output (vm, "%16s %8d %14d 0x%016llx %s\n",
900                          regp->name, q->consumer_pid, q->cursize,
901                          q, health);
902       }
903     else
904       {
905         clib_warning ("NULL client registration index %d",
906                       regpp - am->vl_clients);
907         vec_add1 (confused_indices, regpp - am->vl_clients);
908       }
909   }));
910   /* *INDENT-ON* */
911
912   /* This should "never happen," but if it does, fix it... */
913   if (PREDICT_FALSE (vec_len (confused_indices) > 0))
914     {
915       int i;
916       for (i = 0; i < vec_len (confused_indices); i++)
917         {
918           pool_put_index (am->vl_clients, confused_indices[i]);
919         }
920     }
921   vec_free (confused_indices);
922
923   if (am->missing_clients)
924     vlib_cli_output (vm, "%u messages with missing clients",
925                      am->missing_clients);
926 socket_clients:
927   dump_socket_clients (vm, am);
928
929   return 0;
930 }
931
932 static clib_error_t *
933 vl_api_status_command (vlib_main_t * vm,
934                        unformat_input_t * input, vlib_cli_command_t * cli_cmd)
935 {
936   api_main_t *am = &api_main;
937
938   // check if rx_trace and tx_trace are not null pointers
939
940   if (am->rx_trace == 0)
941     {
942       vlib_cli_output (vm, "RX Trace disabled\n");
943     }
944   else
945     {
946       if (am->rx_trace->enabled == 0)
947         vlib_cli_output (vm, "RX Trace disabled\n");
948       else
949         vlib_cli_output (vm, "RX Trace enabled\n");
950     }
951
952   if (am->tx_trace == 0)
953     {
954       vlib_cli_output (vm, "TX Trace disabled\n");
955     }
956   else
957     {
958       if (am->tx_trace->enabled == 0)
959         vlib_cli_output (vm, "TX Trace disabled\n");
960       else
961         vlib_cli_output (vm, "TX Trace enabled\n");
962     }
963
964   return 0;
965 }
966
967 /* *INDENT-OFF* */
968 VLIB_CLI_COMMAND (cli_show_api_command, static) = {
969     .path = "show api",
970     .short_help = "Show API information",
971 };
972 /* *INDENT-ON* */
973
974 /* *INDENT-OFF* */
975 VLIB_CLI_COMMAND (cli_show_api_ring_command, static) = {
976     .path = "show api ring-stats",
977     .short_help = "Message ring statistics",
978     .function = vl_api_ring_command,
979 };
980 /* *INDENT-ON* */
981
982 /* *INDENT-OFF* */
983 VLIB_CLI_COMMAND (cli_show_api_clients_command, static) = {
984     .path = "show api clients",
985     .short_help = "Client information",
986     .function = vl_api_client_command,
987 };
988 /* *INDENT-ON* */
989
990 /* *INDENT-OFF* */
991 VLIB_CLI_COMMAND (cli_show_api_status_command, static) = {
992     .path = "show api status",
993     .short_help = "Show API trace status",
994     .function = vl_api_status_command,
995 };
996 /* *INDENT-ON* */
997
998 static clib_error_t *
999 vl_api_message_table_command (vlib_main_t * vm,
1000                               unformat_input_t * input,
1001                               vlib_cli_command_t * cli_cmd)
1002 {
1003   api_main_t *am = &api_main;
1004   int i;
1005   int verbose = 0;
1006
1007   if (unformat (input, "verbose"))
1008     verbose = 1;
1009
1010
1011   if (verbose == 0)
1012     vlib_cli_output (vm, "%-4s %s", "ID", "Name");
1013   else
1014     vlib_cli_output (vm, "%-4s %-40s %6s %7s", "ID", "Name", "Bounce",
1015                      "MP-safe");
1016
1017   for (i = 1; i < vec_len (am->msg_names); i++)
1018     {
1019       if (verbose == 0)
1020         {
1021           vlib_cli_output (vm, "%-4d %s", i,
1022                            am->msg_names[i] ? am->msg_names[i] :
1023                            "  [no handler]");
1024         }
1025       else
1026         {
1027           vlib_cli_output (vm, "%-4d %-40s %6d %7d", i,
1028                            am->msg_names[i] ? am->msg_names[i] :
1029                            "  [no handler]", am->message_bounce[i],
1030                            am->is_mp_safe[i]);
1031         }
1032     }
1033
1034   return 0;
1035 }
1036
1037 /* *INDENT-OFF* */
1038 VLIB_CLI_COMMAND (cli_show_api_message_table_command, static) = {
1039     .path = "show api message-table",
1040     .short_help = "Message Table",
1041     .function = vl_api_message_table_command,
1042 };
1043 /* *INDENT-ON* */
1044
1045 static clib_error_t *
1046 vl_api_trace_command (vlib_main_t * vm,
1047                       unformat_input_t * input, vlib_cli_command_t * cli_cmd)
1048 {
1049   u32 nitems = 1024;
1050   vl_api_trace_which_t which = VL_API_TRACE_RX;
1051   api_main_t *am = &api_main;
1052
1053   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1054     {
1055       if (unformat (input, "rx nitems %u", &nitems) || unformat (input, "rx"))
1056         goto configure;
1057       else if (unformat (input, "tx nitems %u", &nitems)
1058                || unformat (input, "tx"))
1059         {
1060           which = VL_API_TRACE_RX;
1061           goto configure;
1062         }
1063       else if (unformat (input, "on rx"))
1064         {
1065           vl_msg_api_trace_onoff (am, VL_API_TRACE_RX, 1);
1066         }
1067       else if (unformat (input, "on tx"))
1068         {
1069           vl_msg_api_trace_onoff (am, VL_API_TRACE_TX, 1);
1070         }
1071       else if (unformat (input, "on"))
1072         {
1073           vl_msg_api_trace_onoff (am, VL_API_TRACE_RX, 1);
1074         }
1075       else if (unformat (input, "off"))
1076         {
1077           vl_msg_api_trace_onoff (am, VL_API_TRACE_RX, 0);
1078           vl_msg_api_trace_onoff (am, VL_API_TRACE_TX, 0);
1079         }
1080       else if (unformat (input, "free"))
1081         {
1082           vl_msg_api_trace_onoff (am, VL_API_TRACE_RX, 0);
1083           vl_msg_api_trace_onoff (am, VL_API_TRACE_TX, 0);
1084           vl_msg_api_trace_free (am, VL_API_TRACE_RX);
1085           vl_msg_api_trace_free (am, VL_API_TRACE_TX);
1086         }
1087       else if (unformat (input, "debug on"))
1088         {
1089           am->msg_print_flag = 1;
1090         }
1091       else if (unformat (input, "debug off"))
1092         {
1093           am->msg_print_flag = 0;
1094         }
1095       else
1096         return clib_error_return (0, "unknown input `%U'",
1097                                   format_unformat_error, input);
1098     }
1099   return 0;
1100
1101 configure:
1102   if (vl_msg_api_trace_configure (am, which, nitems))
1103     {
1104       vlib_cli_output (vm, "warning: trace configure error (%d, %d)",
1105                        which, nitems);
1106     }
1107
1108   return 0;
1109 }
1110
1111 /* *INDENT-OFF* */
1112 VLIB_CLI_COMMAND (trace, static) = {
1113     .path = "set api-trace",
1114     .short_help = "API trace",
1115     .function = vl_api_trace_command,
1116 };
1117 /* *INDENT-ON* */
1118
1119 clib_error_t *
1120 vlibmemory_init (vlib_main_t * vm)
1121 {
1122   api_main_t *am = &api_main;
1123   svm_map_region_args_t _a, *a = &_a;
1124
1125   memset (a, 0, sizeof (*a));
1126   a->root_path = am->root_path;
1127   a->name = SVM_GLOBAL_REGION_NAME;
1128   a->baseva = (am->global_baseva != 0) ?
1129     am->global_baseva : SVM_GLOBAL_REGION_BASEVA;
1130   a->size = (am->global_size != 0) ? am->global_size : SVM_GLOBAL_REGION_SIZE;
1131   a->flags = SVM_FLAGS_NODATA;
1132   a->uid = am->api_uid;
1133   a->gid = am->api_gid;
1134   a->pvt_heap_size =
1135     (am->global_pvt_heap_size !=
1136      0) ? am->global_pvt_heap_size : SVM_PVT_MHEAP_SIZE;
1137
1138   svm_region_init_args (a);
1139   return 0;
1140 }
1141
1142 VLIB_INIT_FUNCTION (vlibmemory_init);
1143
1144 void
1145 vl_set_memory_region_name (char *name)
1146 {
1147   api_main_t *am = &api_main;
1148
1149   am->region_name = name;
1150 }
1151
1152 static int
1153 range_compare (vl_api_msg_range_t * a0, vl_api_msg_range_t * a1)
1154 {
1155   int len0, len1, clen;
1156
1157   len0 = vec_len (a0->name);
1158   len1 = vec_len (a1->name);
1159   clen = len0 < len1 ? len0 : len1;
1160   return (strncmp ((char *) a0->name, (char *) a1->name, clen));
1161 }
1162
1163 static u8 *
1164 format_api_msg_range (u8 * s, va_list * args)
1165 {
1166   vl_api_msg_range_t *rp = va_arg (*args, vl_api_msg_range_t *);
1167
1168   if (rp == 0)
1169     s = format (s, "%-20s%9s%9s", "Name", "First-ID", "Last-ID");
1170   else
1171     s = format (s, "%-20s%9d%9d", rp->name, rp->first_msg_id,
1172                 rp->last_msg_id);
1173
1174   return s;
1175 }
1176
1177 static clib_error_t *
1178 vl_api_show_plugin_command (vlib_main_t * vm,
1179                             unformat_input_t * input,
1180                             vlib_cli_command_t * cli_cmd)
1181 {
1182   api_main_t *am = &api_main;
1183   vl_api_msg_range_t *rp = 0;
1184   int i;
1185
1186   if (vec_len (am->msg_ranges) == 0)
1187     {
1188       vlib_cli_output (vm, "No plugin API message ranges configured...");
1189       return 0;
1190     }
1191
1192   rp = vec_dup (am->msg_ranges);
1193
1194   vec_sort_with_function (rp, range_compare);
1195
1196   vlib_cli_output (vm, "Plugin API message ID ranges...\n");
1197   vlib_cli_output (vm, "%U", format_api_msg_range, 0 /* header */ );
1198
1199   for (i = 0; i < vec_len (rp); i++)
1200     vlib_cli_output (vm, "%U", format_api_msg_range, rp + i);
1201
1202   return 0;
1203 }
1204
1205 /* *INDENT-OFF* */
1206 VLIB_CLI_COMMAND (cli_show_api_plugin_command, static) = {
1207     .path = "show api plugin",
1208     .short_help = "show api plugin",
1209     .function = vl_api_show_plugin_command,
1210 };
1211 /* *INDENT-ON* */
1212
1213 static void
1214 vl_api_rpc_call_t_handler (vl_api_rpc_call_t * mp)
1215 {
1216   vl_api_rpc_reply_t *rmp;
1217   int (*fp) (void *);
1218   i32 rv = 0;
1219   vlib_main_t *vm = vlib_get_main ();
1220
1221   if (mp->function == 0)
1222     {
1223       rv = -1;
1224       clib_warning ("rpc NULL function pointer");
1225     }
1226
1227   else
1228     {
1229       if (mp->need_barrier_sync)
1230         vlib_worker_thread_barrier_sync (vm);
1231
1232       fp = uword_to_pointer (mp->function, int (*)(void *));
1233       rv = fp (mp->data);
1234
1235       if (mp->need_barrier_sync)
1236         vlib_worker_thread_barrier_release (vm);
1237     }
1238
1239   if (mp->send_reply)
1240     {
1241       unix_shared_memory_queue_t *q =
1242         vl_api_client_index_to_input_queue (mp->client_index);
1243       if (q)
1244         {
1245           rmp = vl_msg_api_alloc_as_if_client (sizeof (*rmp));
1246           rmp->_vl_msg_id = ntohs (VL_API_RPC_REPLY);
1247           rmp->context = mp->context;
1248           rmp->retval = rv;
1249           vl_msg_api_send_shmem (q, (u8 *) & rmp);
1250         }
1251     }
1252   if (mp->multicast)
1253     {
1254       clib_warning ("multicast not yet implemented...");
1255     }
1256 }
1257
1258 static void
1259 vl_api_rpc_reply_t_handler (vl_api_rpc_reply_t * mp)
1260 {
1261   clib_warning ("unimplemented");
1262 }
1263
1264 void
1265 vl_api_rpc_call_main_thread (void *fp, u8 * data, u32 data_length)
1266 {
1267   vl_api_rpc_call_t *mp;
1268   api_main_t *am = &api_main;
1269   vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
1270   unix_shared_memory_queue_t *q;
1271
1272   /* Main thread: call the function directly */
1273   if (os_get_cpu_number () == 0)
1274     {
1275       vlib_main_t *vm = vlib_get_main ();
1276       void (*call_fp) (void *);
1277
1278       vlib_worker_thread_barrier_sync (vm);
1279
1280       call_fp = fp;
1281       call_fp (data);
1282
1283       vlib_worker_thread_barrier_release (vm);
1284       return;
1285     }
1286
1287   /* Any other thread, actually do an RPC call... */
1288   mp = vl_msg_api_alloc_as_if_client (sizeof (*mp) + data_length);
1289
1290   memset (mp, 0, sizeof (*mp));
1291   clib_memcpy (mp->data, data, data_length);
1292   mp->_vl_msg_id = ntohs (VL_API_RPC_CALL);
1293   mp->function = pointer_to_uword (fp);
1294   mp->need_barrier_sync = 1;
1295
1296   /*
1297    * Use the "normal" control-plane mechanism for the main thread.
1298    * Well, almost. if the main input queue is full, we cannot
1299    * block. Otherwise, we can expect a barrier sync timeout.
1300    */
1301   q = shmem_hdr->vl_input_queue;
1302
1303   while (pthread_mutex_trylock (&q->mutex))
1304     vlib_worker_thread_barrier_check ();
1305
1306   while (PREDICT_FALSE (unix_shared_memory_queue_is_full (q)))
1307     {
1308       pthread_mutex_unlock (&q->mutex);
1309       vlib_worker_thread_barrier_check ();
1310       while (pthread_mutex_trylock (&q->mutex))
1311         vlib_worker_thread_barrier_check ();
1312     }
1313
1314   vl_msg_api_send_shmem_nolock (q, (u8 *) & mp);
1315
1316   pthread_mutex_unlock (&q->mutex);
1317 }
1318
1319 #define foreach_rpc_api_msg                     \
1320 _(RPC_CALL,rpc_call)                            \
1321 _(RPC_REPLY,rpc_reply)
1322
1323 static clib_error_t *
1324 rpc_api_hookup (vlib_main_t * vm)
1325 {
1326 #define _(N,n)                                                  \
1327     vl_msg_api_set_handlers(VL_API_##N, #n,                     \
1328                            vl_api_##n##_t_handler,              \
1329                            vl_noop_handler,                     \
1330                            vl_noop_handler,                     \
1331                            vl_api_##n##_t_print,                \
1332                            sizeof(vl_api_##n##_t), 0 /* do not trace */);
1333   foreach_rpc_api_msg;
1334 #undef _
1335   return 0;
1336 }
1337
1338 VLIB_API_INIT_FUNCTION (rpc_api_hookup);
1339
1340 /*
1341  * fd.io coding-style-patch-verification: ON
1342  *
1343  * Local Variables:
1344  * eval: (c-set-style "gnu")
1345  * End:
1346  */