vhost: CLI delete interface by name
[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 void
1046 vl_api_trace_print_file_cmd (vlib_main_t * vm, u32 first, u32 last,
1047                              u8 * filename)
1048 {
1049   FILE *fp;
1050   static vl_api_trace_t *tp = 0;
1051   int endian_swap = 0;
1052   u32 i;
1053   u16 msg_id;
1054   static u8 *msg_buf = 0;
1055   void (*endian_fp) (void *);
1056   u8 *(*print_fp) (void *, void *);
1057   int size;
1058   api_main_t *am = &api_main;
1059
1060   /*
1061    * On-demand: allocate enough space for the largest message
1062    */
1063   if (msg_buf == 0)
1064     {
1065       vec_validate (tp, 0);
1066       int max_size = 0;
1067       for (i = 0; i < vec_len (am->api_trace_cfg); i++)
1068         {
1069           if (am->api_trace_cfg[i].size > max_size)
1070             max_size = am->api_trace_cfg[i].size;
1071         }
1072       /* round size to a multiple of the cache-line size */
1073       max_size = (max_size + (CLIB_CACHE_LINE_BYTES - 1)) &
1074         (~(CLIB_CACHE_LINE_BYTES - 1));
1075       vec_validate (msg_buf, max_size - 1);
1076     }
1077
1078   fp = fopen ((char *) filename, "r");
1079
1080   if (fp == NULL)
1081     {
1082       vlib_cli_output (vm, "Couldn't open %s\n", filename);
1083       return;
1084     }
1085
1086   /* first, fish the header record from the file */
1087
1088   if (fread (tp, sizeof (*tp), 1, fp) != 1)
1089     {
1090       fclose (fp);
1091       vlib_cli_output (vm, "Header read error\n");
1092       return;
1093     }
1094
1095   /* Endian swap required? */
1096   if (clib_arch_is_big_endian != tp->endian)
1097     {
1098       endian_swap = 1;
1099     }
1100
1101   for (i = 0; i <= last; i++)
1102     {
1103       /* First 2 bytes are the message type */
1104       if (fread (&msg_id, sizeof (u16), 1, fp) != 1)
1105         {
1106           break;
1107         }
1108       msg_id = ntohs (msg_id);
1109
1110       if (fseek (fp, -2, SEEK_CUR) < 0)
1111         {
1112           vlib_cli_output (vm, "fseek failed, %s", strerror (errno));
1113           fclose (fp);
1114           return;
1115         }
1116
1117       /* Mild sanity check */
1118       if (msg_id >= vec_len (am->msg_handlers))
1119         {
1120           fclose (fp);
1121           vlib_cli_output (vm, "msg_id %d out of bounds\n", msg_id);
1122           return;
1123         }
1124
1125       size = am->api_trace_cfg[msg_id].size;
1126
1127       if (fread (msg_buf, size, 1, fp) != 1)
1128         {
1129           fclose (fp);
1130           vlib_cli_output (vm, "read error on %s\n", filename);
1131           return;
1132         }
1133
1134       if (i < first)
1135         continue;
1136
1137       if (endian_swap)
1138         {
1139           endian_fp = am->msg_endian_handlers[msg_id];
1140           (*endian_fp) (msg_buf);
1141         }
1142
1143       vlib_cli_output (vm, "[%d]: %s\n", i, am->msg_names[msg_id]);
1144
1145       print_fp = (void *) am->msg_print_handlers[msg_id];
1146       (*print_fp) (msg_buf, vm);
1147       vlib_cli_output (vm, "-------------\n");
1148     }
1149   fclose (fp);
1150 }
1151
1152 static clib_error_t *
1153 vl_api_trace_command (vlib_main_t * vm,
1154                       unformat_input_t * input, vlib_cli_command_t * cli_cmd)
1155 {
1156   u32 nitems = 1024;
1157   vl_api_trace_which_t which = VL_API_TRACE_RX;
1158   u8 *filename;
1159   u32 first = 0;
1160   u32 last = ~0;
1161   api_main_t *am = &api_main;
1162
1163   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1164     {
1165       if (unformat (input, "rx nitems %u", &nitems) || unformat (input, "rx"))
1166         goto configure;
1167       else if (unformat (input, "tx nitems %u", &nitems)
1168                || unformat (input, "tx"))
1169         {
1170           which = VL_API_TRACE_RX;
1171           goto configure;
1172         }
1173       else if (unformat (input, "on rx"))
1174         {
1175           vl_msg_api_trace_onoff (am, VL_API_TRACE_RX, 1);
1176         }
1177       else if (unformat (input, "on tx"))
1178         {
1179           vl_msg_api_trace_onoff (am, VL_API_TRACE_TX, 1);
1180         }
1181       else if (unformat (input, "on"))
1182         {
1183           vl_msg_api_trace_onoff (am, VL_API_TRACE_RX, 1);
1184         }
1185       else if (unformat (input, "off"))
1186         {
1187           vl_msg_api_trace_onoff (am, VL_API_TRACE_RX, 0);
1188           vl_msg_api_trace_onoff (am, VL_API_TRACE_TX, 0);
1189         }
1190       else if (unformat (input, "free"))
1191         {
1192           vl_msg_api_trace_onoff (am, VL_API_TRACE_RX, 0);
1193           vl_msg_api_trace_onoff (am, VL_API_TRACE_TX, 0);
1194           vl_msg_api_trace_free (am, VL_API_TRACE_RX);
1195           vl_msg_api_trace_free (am, VL_API_TRACE_TX);
1196         }
1197       else if (unformat (input, "print %s from %d to %d", &filename,
1198                          &first, &last)
1199                || unformat (input, "print %s", &filename))
1200         {
1201           goto print;
1202         }
1203       else if (unformat (input, "debug on"))
1204         {
1205           am->msg_print_flag = 1;
1206         }
1207       else if (unformat (input, "debug off"))
1208         {
1209           am->msg_print_flag = 0;
1210         }
1211       else
1212         return clib_error_return (0, "unknown input `%U'",
1213                                   format_unformat_error, input);
1214     }
1215   return 0;
1216
1217 print:
1218   vl_api_trace_print_file_cmd (vm, first, last, filename);
1219   goto out;
1220
1221 configure:
1222   if (vl_msg_api_trace_configure (am, which, nitems))
1223     {
1224       vlib_cli_output (vm, "warning: trace configure error (%d, %d)",
1225                        which, nitems);
1226     }
1227
1228 out:
1229   return 0;
1230 }
1231
1232 /* *INDENT-OFF* */
1233 VLIB_CLI_COMMAND (trace, static) = {
1234     .path = "set api-trace",
1235     .short_help = "API trace",
1236     .function = vl_api_trace_command,
1237 };
1238 /* *INDENT-ON* */
1239
1240 clib_error_t *
1241 vlibmemory_init (vlib_main_t * vm)
1242 {
1243   api_main_t *am = &api_main;
1244   svm_map_region_args_t _a, *a = &_a;
1245
1246   memset (a, 0, sizeof (*a));
1247   a->root_path = am->root_path;
1248   a->name = SVM_GLOBAL_REGION_NAME;
1249   a->baseva = (am->global_baseva != 0) ?
1250     am->global_baseva : SVM_GLOBAL_REGION_BASEVA;
1251   a->size = (am->global_size != 0) ? am->global_size : SVM_GLOBAL_REGION_SIZE;
1252   a->flags = SVM_FLAGS_NODATA;
1253   a->uid = am->api_uid;
1254   a->gid = am->api_gid;
1255   a->pvt_heap_size =
1256     (am->global_pvt_heap_size !=
1257      0) ? am->global_pvt_heap_size : SVM_PVT_MHEAP_SIZE;
1258
1259   svm_region_init_args (a);
1260   return 0;
1261 }
1262
1263 VLIB_INIT_FUNCTION (vlibmemory_init);
1264
1265 void
1266 vl_set_memory_region_name (char *name)
1267 {
1268   api_main_t *am = &api_main;
1269
1270   am->region_name = name;
1271 }
1272
1273 static int
1274 range_compare (vl_api_msg_range_t * a0, vl_api_msg_range_t * a1)
1275 {
1276   int len0, len1, clen;
1277
1278   len0 = vec_len (a0->name);
1279   len1 = vec_len (a1->name);
1280   clen = len0 < len1 ? len0 : len1;
1281   return (strncmp ((char *) a0->name, (char *) a1->name, clen));
1282 }
1283
1284 static u8 *
1285 format_api_msg_range (u8 * s, va_list * args)
1286 {
1287   vl_api_msg_range_t *rp = va_arg (*args, vl_api_msg_range_t *);
1288
1289   if (rp == 0)
1290     s = format (s, "%-20s%9s%9s", "Name", "First-ID", "Last-ID");
1291   else
1292     s = format (s, "%-20s%9d%9d", rp->name, rp->first_msg_id,
1293                 rp->last_msg_id);
1294
1295   return s;
1296 }
1297
1298 static clib_error_t *
1299 vl_api_show_plugin_command (vlib_main_t * vm,
1300                             unformat_input_t * input,
1301                             vlib_cli_command_t * cli_cmd)
1302 {
1303   api_main_t *am = &api_main;
1304   vl_api_msg_range_t *rp = 0;
1305   int i;
1306
1307   if (vec_len (am->msg_ranges) == 0)
1308     {
1309       vlib_cli_output (vm, "No plugin API message ranges configured...");
1310       return 0;
1311     }
1312
1313   rp = vec_dup (am->msg_ranges);
1314
1315   vec_sort_with_function (rp, range_compare);
1316
1317   vlib_cli_output (vm, "Plugin API message ID ranges...\n");
1318   vlib_cli_output (vm, "%U", format_api_msg_range, 0 /* header */ );
1319
1320   for (i = 0; i < vec_len (rp); i++)
1321     vlib_cli_output (vm, "%U", format_api_msg_range, rp + i);
1322
1323   return 0;
1324 }
1325
1326 /* *INDENT-OFF* */
1327 VLIB_CLI_COMMAND (cli_show_api_plugin_command, static) = {
1328     .path = "show api plugin",
1329     .short_help = "show api plugin",
1330     .function = vl_api_show_plugin_command,
1331 };
1332 /* *INDENT-ON* */
1333
1334 static void
1335 vl_api_rpc_call_t_handler (vl_api_rpc_call_t * mp)
1336 {
1337   vl_api_rpc_reply_t *rmp;
1338   int (*fp) (void *);
1339   i32 rv = 0;
1340   vlib_main_t *vm = vlib_get_main ();
1341
1342   if (mp->function == 0)
1343     {
1344       rv = -1;
1345       clib_warning ("rpc NULL function pointer");
1346     }
1347
1348   else
1349     {
1350       if (mp->need_barrier_sync)
1351         vlib_worker_thread_barrier_sync (vm);
1352
1353       fp = uword_to_pointer (mp->function, int (*)(void *));
1354       rv = fp (mp->data);
1355
1356       if (mp->need_barrier_sync)
1357         vlib_worker_thread_barrier_release (vm);
1358     }
1359
1360   if (mp->send_reply)
1361     {
1362       unix_shared_memory_queue_t *q =
1363         vl_api_client_index_to_input_queue (mp->client_index);
1364       if (q)
1365         {
1366           rmp = vl_msg_api_alloc_as_if_client (sizeof (*rmp));
1367           rmp->_vl_msg_id = ntohs (VL_API_RPC_REPLY);
1368           rmp->context = mp->context;
1369           rmp->retval = rv;
1370           vl_msg_api_send_shmem (q, (u8 *) & rmp);
1371         }
1372     }
1373   if (mp->multicast)
1374     {
1375       clib_warning ("multicast not yet implemented...");
1376     }
1377 }
1378
1379 static void
1380 vl_api_rpc_reply_t_handler (vl_api_rpc_reply_t * mp)
1381 {
1382   clib_warning ("unimplemented");
1383 }
1384
1385 void
1386 vl_api_rpc_call_main_thread (void *fp, u8 * data, u32 data_length)
1387 {
1388   vl_api_rpc_call_t *mp;
1389   api_main_t *am = &api_main;
1390   vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
1391   unix_shared_memory_queue_t *q;
1392
1393   /* Main thread: call the function directly */
1394   if (os_get_cpu_number () == 0)
1395     {
1396       vlib_main_t *vm = vlib_get_main ();
1397       void (*call_fp) (void *);
1398
1399       vlib_worker_thread_barrier_sync (vm);
1400
1401       call_fp = fp;
1402       call_fp (data);
1403
1404       vlib_worker_thread_barrier_release (vm);
1405       return;
1406     }
1407
1408   /* Any other thread, actually do an RPC call... */
1409   mp = vl_msg_api_alloc_as_if_client (sizeof (*mp) + data_length);
1410
1411   memset (mp, 0, sizeof (*mp));
1412   clib_memcpy (mp->data, data, data_length);
1413   mp->_vl_msg_id = ntohs (VL_API_RPC_CALL);
1414   mp->function = pointer_to_uword (fp);
1415   mp->need_barrier_sync = 1;
1416
1417   /*
1418    * Use the "normal" control-plane mechanism for the main thread.
1419    * Well, almost. if the main input queue is full, we cannot
1420    * block. Otherwise, we can expect a barrier sync timeout.
1421    */
1422   q = shmem_hdr->vl_input_queue;
1423
1424   while (pthread_mutex_trylock (&q->mutex))
1425     vlib_worker_thread_barrier_check ();
1426
1427   while (PREDICT_FALSE (unix_shared_memory_queue_is_full (q)))
1428     {
1429       pthread_mutex_unlock (&q->mutex);
1430       vlib_worker_thread_barrier_check ();
1431       while (pthread_mutex_trylock (&q->mutex))
1432         vlib_worker_thread_barrier_check ();
1433     }
1434
1435   vl_msg_api_send_shmem_nolock (q, (u8 *) & mp);
1436
1437   pthread_mutex_unlock (&q->mutex);
1438 }
1439
1440 #define foreach_rpc_api_msg                     \
1441 _(RPC_CALL,rpc_call)                            \
1442 _(RPC_REPLY,rpc_reply)
1443
1444 static clib_error_t *
1445 rpc_api_hookup (vlib_main_t * vm)
1446 {
1447 #define _(N,n)                                                  \
1448     vl_msg_api_set_handlers(VL_API_##N, #n,                     \
1449                            vl_api_##n##_t_handler,              \
1450                            vl_noop_handler,                     \
1451                            vl_noop_handler,                     \
1452                            vl_api_##n##_t_print,                \
1453                            sizeof(vl_api_##n##_t), 0 /* do not trace */);
1454   foreach_rpc_api_msg;
1455 #undef _
1456   return 0;
1457 }
1458
1459 VLIB_API_INIT_FUNCTION (rpc_api_hookup);
1460
1461 /*
1462  * fd.io coding-style-patch-verification: ON
1463  *
1464  * Local Variables:
1465  * eval: (c-set-style "gnu")
1466  * End:
1467  */