api: multiple connections per process
[vpp.git] / src / vlibmemory / memory_api.c
1 /*
2  *------------------------------------------------------------------
3  * Copyright (c) 2018 Cisco and/or its affiliates.
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *------------------------------------------------------------------
16  */
17 #include <signal.h>
18
19 #include <vlib/vlib.h>
20 #include <vlibapi/api.h>
21 #include <vlibmemory/api.h>
22 #include <vlibmemory/memory_api.h>
23
24 #include <vlibmemory/vl_memory_msg_enum.h>      /* enumerate all vlib messages */
25
26 #define vl_typedefs             /* define message structures */
27 #include <vlibmemory/vl_memory_api_h.h>
28 #undef vl_typedefs
29
30 /* instantiate all the print functions we know about */
31 #define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
32 #define vl_printfun
33 #include <vlibmemory/vl_memory_api_h.h>
34 #undef vl_printfun
35
36 /* instantiate all the endian swap functions we know about */
37 #define vl_endianfun
38 #include <vlibmemory/vl_memory_api_h.h>
39 #undef vl_endianfun
40
41 static inline void *
42 vl_api_memclnt_create_t_print (vl_api_memclnt_create_t * a, void *handle)
43 {
44   vl_print (handle, "vl_api_memclnt_create_t:\n");
45   vl_print (handle, "name: %s\n", a->name);
46   vl_print (handle, "input_queue: 0x%wx\n", a->input_queue);
47   vl_print (handle, "context: %u\n", (unsigned) a->context);
48   vl_print (handle, "ctx_quota: %ld\n", (long) a->ctx_quota);
49   return handle;
50 }
51
52 static inline void *
53 vl_api_memclnt_delete_t_print (vl_api_memclnt_delete_t * a, void *handle)
54 {
55   vl_print (handle, "vl_api_memclnt_delete_t:\n");
56   vl_print (handle, "index: %u\n", (unsigned) a->index);
57   vl_print (handle, "handle: 0x%wx\n", a->handle);
58   return handle;
59 }
60
61 volatile int **vl_api_queue_cursizes;
62
63 static void
64 memclnt_queue_callback (vlib_main_t * vm)
65 {
66   int i;
67   api_main_t *am = vlibapi_get_main ();
68
69   if (PREDICT_FALSE (vec_len (vl_api_queue_cursizes) !=
70                      1 + vec_len (am->vlib_private_rps)))
71     {
72       vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
73       svm_queue_t *q;
74
75       if (shmem_hdr == 0)
76         return;
77
78       q = shmem_hdr->vl_input_queue;
79       if (q == 0)
80         return;
81
82       vec_add1 (vl_api_queue_cursizes, &q->cursize);
83
84       for (i = 0; i < vec_len (am->vlib_private_rps); i++)
85         {
86           svm_region_t *vlib_rp = am->vlib_private_rps[i];
87
88           shmem_hdr = (void *) vlib_rp->user_ctx;
89           q = shmem_hdr->vl_input_queue;
90           vec_add1 (vl_api_queue_cursizes, &q->cursize);
91         }
92     }
93
94   for (i = 0; i < vec_len (vl_api_queue_cursizes); i++)
95     {
96       if (*vl_api_queue_cursizes[i])
97         {
98           vm->queue_signal_pending = 1;
99           vm->api_queue_nonempty = 1;
100           vlib_process_signal_event (vm, vl_api_clnt_node.index,
101                                      /* event_type */ QUEUE_SIGNAL_EVENT,
102                                      /* event_data */ 0);
103           break;
104         }
105     }
106   if (vec_len (vm->pending_rpc_requests))
107     {
108       vm->queue_signal_pending = 1;
109       vm->api_queue_nonempty = 1;
110       vlib_process_signal_event (vm, vl_api_clnt_node.index,
111                                  /* event_type */ QUEUE_SIGNAL_EVENT,
112                                  /* event_data */ 0);
113     }
114 }
115
116 /*
117  * vl_api_memclnt_create_internal
118  */
119 u32
120 vl_api_memclnt_create_internal (char *name, svm_queue_t * q)
121 {
122   vl_api_registration_t **regpp;
123   vl_api_registration_t *regp;
124   svm_region_t *svm;
125   void *oldheap;
126   api_main_t *am = vlibapi_get_main ();
127
128   ASSERT (vlib_get_thread_index () == 0);
129   pool_get (am->vl_clients, regpp);
130
131   svm = am->vlib_rp;
132
133   pthread_mutex_lock (&svm->mutex);
134   oldheap = svm_push_data_heap (svm);
135   *regpp = clib_mem_alloc (sizeof (vl_api_registration_t));
136
137   regp = *regpp;
138   clib_memset (regp, 0, sizeof (*regp));
139   regp->registration_type = REGISTRATION_TYPE_SHMEM;
140   regp->vl_api_registration_pool_index = regpp - am->vl_clients;
141   regp->vlib_rp = svm;
142   regp->shmem_hdr = am->shmem_hdr;
143
144   regp->vl_input_queue = q;
145   regp->name = format (0, "%s%c", name, 0);
146
147   pthread_mutex_unlock (&svm->mutex);
148   svm_pop_heap (oldheap);
149   return vl_msg_api_handle_from_index_and_epoch
150     (regp->vl_api_registration_pool_index,
151      am->shmem_hdr->application_restarts);
152 }
153
154 /*
155  * vl_api_memclnt_create_t_handler
156  */
157 void
158 vl_api_memclnt_create_t_handler (vl_api_memclnt_create_t * mp)
159 {
160   vl_api_registration_t **regpp;
161   vl_api_registration_t *regp;
162   vl_api_memclnt_create_reply_t *rp;
163   svm_region_t *svm;
164   svm_queue_t *q;
165   int rv = 0;
166   void *oldheap;
167   api_main_t *am = vlibapi_get_main ();
168   u8 *msg_table;
169
170   /*
171    * This is tortured. Maintain a vlib-address-space private
172    * pool of client registrations. We use the shared-memory virtual
173    * address of client structure as a handle, to allow direct
174    * manipulation of context quota vbls from the client library.
175    *
176    * This scheme causes trouble w/ API message trace replay, since
177    * some random VA from clib_mem_alloc() certainly won't
178    * occur in the Linux sim. The (very) few places
179    * that care need to use the pool index.
180    *
181    * Putting the registration object(s) into a pool in shared memory and
182    * using the pool index as a handle seems like a great idea.
183    * Unfortunately, each and every reference to that pool would need
184    * to be protected by a mutex:
185    *
186    *     Client                      VLIB
187    *     ------                      ----
188    *     convert pool index to
189    *     pointer.
190    *     <deschedule>
191    *                                 expand pool
192    *                                 <deschedule>
193    *     kaboom!
194    */
195
196   pool_get (am->vl_clients, regpp);
197
198   svm = am->vlib_rp;
199
200   pthread_mutex_lock (&svm->mutex);
201   oldheap = svm_push_data_heap (svm);
202   *regpp = clib_mem_alloc (sizeof (vl_api_registration_t));
203
204   regp = *regpp;
205   clib_memset (regp, 0, sizeof (*regp));
206   regp->registration_type = REGISTRATION_TYPE_SHMEM;
207   regp->vl_api_registration_pool_index = regpp - am->vl_clients;
208   regp->vlib_rp = svm;
209   regp->shmem_hdr = am->shmem_hdr;
210   regp->clib_file_index = am->shmem_hdr->clib_file_index;
211
212   q = regp->vl_input_queue = (svm_queue_t *) (uword) mp->input_queue;
213   VL_MSG_API_SVM_QUEUE_UNPOISON (q);
214
215   regp->name = format (0, "%s", mp->name);
216   vec_add1 (regp->name, 0);
217
218   if (am->serialized_message_table_in_shmem == 0)
219     am->serialized_message_table_in_shmem =
220       vl_api_serialize_message_table (am, 0);
221
222   if (am->vlib_rp != am->vlib_primary_rp)
223     msg_table = vl_api_serialize_message_table (am, 0);
224   else
225     msg_table = am->serialized_message_table_in_shmem;
226
227   pthread_mutex_unlock (&svm->mutex);
228   svm_pop_heap (oldheap);
229
230   rp = vl_msg_api_alloc (sizeof (*rp));
231   rp->_vl_msg_id = ntohs (VL_API_MEMCLNT_CREATE_REPLY);
232   rp->handle = (uword) regp;
233   rp->index = vl_msg_api_handle_from_index_and_epoch
234     (regp->vl_api_registration_pool_index,
235      am->shmem_hdr->application_restarts);
236   rp->context = mp->context;
237   rp->response = ntohl (rv);
238   rp->message_table = pointer_to_uword (msg_table);
239
240   vl_msg_api_send_shmem (q, (u8 *) & rp);
241 }
242
243 int
244 vl_api_call_reaper_functions (u32 client_index)
245 {
246   clib_error_t *error = 0;
247   _vl_msg_api_function_list_elt_t *i;
248
249   i = vlibapi_get_main ()->reaper_function_registrations;
250   while (i)
251     {
252       error = i->f (client_index);
253       if (error)
254         clib_error_report (error);
255       i = i->next_init_function;
256     }
257   return 0;
258 }
259
260 /*
261  * vl_api_memclnt_delete_t_handler
262  */
263 void
264 vl_api_memclnt_delete_t_handler (vl_api_memclnt_delete_t * mp)
265 {
266   vl_api_registration_t **regpp;
267   vl_api_registration_t *regp;
268   vl_api_memclnt_delete_reply_t *rp;
269   svm_region_t *svm;
270   void *oldheap;
271   api_main_t *am = vlibapi_get_main ();
272   u32 handle, client_index, epoch;
273
274   handle = mp->index;
275
276   if (vl_api_call_reaper_functions (handle))
277     return;
278
279   epoch = vl_msg_api_handle_get_epoch (handle);
280   client_index = vl_msg_api_handle_get_index (handle);
281
282   if (epoch != (am->shmem_hdr->application_restarts & VL_API_EPOCH_MASK))
283     {
284       clib_warning
285         ("Stale clnt delete index %d old epoch %d cur epoch %d",
286          client_index, epoch,
287          (am->shmem_hdr->application_restarts & VL_API_EPOCH_MASK));
288       return;
289     }
290
291   regpp = pool_elt_at_index (am->vl_clients, client_index);
292
293   if (!pool_is_free (am->vl_clients, regpp))
294     {
295       int i;
296       regp = *regpp;
297       svm = am->vlib_rp;
298       int private_registration = 0;
299
300       /* Send reply unless client asked us to do the cleanup */
301       if (!mp->do_cleanup)
302         {
303           /*
304            * Note: the API message handling path will set am->vlib_rp
305            * as appropriate for pairwise / private memory segments
306            */
307           rp = vl_msg_api_alloc (sizeof (*rp));
308           rp->_vl_msg_id = ntohs (VL_API_MEMCLNT_DELETE_REPLY);
309           rp->handle = mp->handle;
310           rp->response = 1;
311
312           vl_msg_api_send_shmem (regp->vl_input_queue, (u8 *) & rp);
313           if (client_index != regp->vl_api_registration_pool_index)
314             {
315               clib_warning ("mismatch client_index %d pool_index %d",
316                             client_index,
317                             regp->vl_api_registration_pool_index);
318               vl_msg_api_free (rp);
319               return;
320             }
321         }
322
323       /* No dangling references, please */
324       *regpp = 0;
325
326       /* For horizontal scaling, add a hash table... */
327       for (i = 0; i < vec_len (am->vlib_private_rps); i++)
328         {
329           /* Is this a pairwise / private API segment? */
330           if (am->vlib_private_rps[i] == svm)
331             {
332               /* Note: account for the memfd header page */
333               uword virtual_base = svm->virtual_base - MMAP_PAGESIZE;
334               uword virtual_size = svm->virtual_size + MMAP_PAGESIZE;
335
336               /*
337                * Kill the registration pool element before we make
338                * the index vanish forever
339                */
340               pool_put_index (am->vl_clients,
341                               regp->vl_api_registration_pool_index);
342
343               vec_delete (am->vlib_private_rps, 1, i);
344               /* Kill it, accounting for the memfd header page */
345               if (munmap ((void *) virtual_base, virtual_size) < 0)
346                 clib_unix_warning ("munmap");
347               /* Reset the queue-length-address cache */
348               vec_reset_length (vl_api_queue_cursizes);
349               private_registration = 1;
350               break;
351             }
352         }
353
354       if (private_registration == 0)
355         {
356           pool_put_index (am->vl_clients,
357                           regp->vl_api_registration_pool_index);
358           pthread_mutex_lock (&svm->mutex);
359           oldheap = svm_push_data_heap (svm);
360           if (mp->do_cleanup)
361             svm_queue_free (regp->vl_input_queue);
362           vec_free (regp->name);
363           /* Poison the old registration */
364           clib_memset (regp, 0xF1, sizeof (*regp));
365           clib_mem_free (regp);
366           pthread_mutex_unlock (&svm->mutex);
367           svm_pop_heap (oldheap);
368           /*
369            * These messages must be freed manually, since they're set up
370            * as "bounce" messages. In the private_registration == 1 case,
371            * we kill the shared-memory segment which contains the message
372            * with munmap.
373            */
374           vl_msg_api_free (mp);
375         }
376     }
377   else
378     {
379       clib_warning ("unknown client ID %d", mp->index);
380     }
381 }
382
383 /**
384  * client answered a ping, stave off the grim reaper...
385  */
386 void
387   vl_api_memclnt_keepalive_reply_t_handler
388   (vl_api_memclnt_keepalive_reply_t * mp)
389 {
390   vl_api_registration_t *regp;
391   vlib_main_t *vm = vlib_get_main ();
392
393   regp = vl_api_client_index_to_registration (mp->context);
394   if (regp)
395     {
396       regp->last_heard = vlib_time_now (vm);
397       regp->unanswered_pings = 0;
398     }
399   else
400     clib_warning ("BUG: anonymous memclnt_keepalive_reply");
401 }
402
403 /**
404  * We can send ourselves these messages if someone uses the
405  * builtin binary api test tool...
406  */
407 static void
408 vl_api_memclnt_keepalive_t_handler (vl_api_memclnt_keepalive_t * mp)
409 {
410   vl_api_memclnt_keepalive_reply_t *rmp;
411   api_main_t *am;
412   vl_shmem_hdr_t *shmem_hdr;
413
414   am = vlibapi_get_main ();
415   shmem_hdr = am->shmem_hdr;
416
417   rmp = vl_msg_api_alloc_as_if_client (sizeof (*rmp));
418   clib_memset (rmp, 0, sizeof (*rmp));
419   rmp->_vl_msg_id = ntohs (VL_API_MEMCLNT_KEEPALIVE_REPLY);
420   rmp->context = mp->context;
421   vl_msg_api_send_shmem (shmem_hdr->vl_input_queue, (u8 *) & rmp);
422 }
423
424 /*
425  * To avoid filling the API trace buffer with boring messages,
426  * don't trace memclnt_keepalive[_reply] msgs
427  */
428
429 #define foreach_vlib_api_msg                            \
430 _(MEMCLNT_CREATE, memclnt_create, 1)                    \
431 _(MEMCLNT_DELETE, memclnt_delete, 1)                    \
432 _(MEMCLNT_KEEPALIVE, memclnt_keepalive, 0)              \
433 _(MEMCLNT_KEEPALIVE_REPLY, memclnt_keepalive_reply, 0)
434
435 /*
436  * memory_api_init
437  */
438 int
439 vl_mem_api_init (const char *region_name)
440 {
441   int rv;
442   api_main_t *am = vlibapi_get_main ();
443   vl_msg_api_msg_config_t cfg;
444   vl_msg_api_msg_config_t *c = &cfg;
445   vl_shmem_hdr_t *shm;
446   vlib_main_t *vm = vlib_get_main ();
447
448   clib_memset (c, 0, sizeof (*c));
449
450   if ((rv = vl_map_shmem (region_name, 1 /* is_vlib */ )) < 0)
451     return rv;
452
453 #define _(N,n,t) do {                                            \
454     c->id = VL_API_##N;                                         \
455     c->name = #n;                                               \
456     c->handler = vl_api_##n##_t_handler;                        \
457     c->cleanup = vl_noop_handler;                               \
458     c->endian = vl_api_##n##_t_endian;                          \
459     c->print = vl_api_##n##_t_print;                            \
460     c->size = sizeof(vl_api_##n##_t);                           \
461     c->traced = t; /* trace, so these msgs print */             \
462     c->replay = 0; /* don't replay client create/delete msgs */ \
463     c->message_bounce = 0; /* don't bounce this message */      \
464     vl_msg_api_config(c);} while (0);
465
466   foreach_vlib_api_msg;
467 #undef _
468
469   /*
470    * special-case freeing of memclnt_delete messages, so we can
471    * simply munmap pairwise / private API segments...
472    */
473   am->message_bounce[VL_API_MEMCLNT_DELETE] = 1;
474   am->is_mp_safe[VL_API_MEMCLNT_KEEPALIVE_REPLY] = 1;
475   am->is_mp_safe[VL_API_MEMCLNT_KEEPALIVE] = 1;
476
477   vlib_set_queue_signal_callback (vm, memclnt_queue_callback);
478
479   shm = am->shmem_hdr;
480   ASSERT (shm && shm->vl_input_queue);
481
482   /* Make a note so we can always find the primary region easily */
483   am->vlib_primary_rp = am->vlib_rp;
484
485   return 0;
486 }
487
488 clib_error_t *
489 map_api_segment_init (vlib_main_t * vm)
490 {
491   api_main_t *am = vlibapi_get_main ();
492   int rv;
493
494   if ((rv = vl_mem_api_init (am->region_name)) < 0)
495     {
496       return clib_error_return (0, "vl_mem_api_init (%s) failed",
497                                 am->region_name);
498     }
499   return 0;
500 }
501
502 static void
503 send_memclnt_keepalive (vl_api_registration_t * regp, f64 now)
504 {
505   vl_api_memclnt_keepalive_t *mp;
506   svm_queue_t *q;
507   api_main_t *am = vlibapi_get_main ();
508
509   q = regp->vl_input_queue;
510
511   /*
512    * If the queue head is moving, assume that the client is processing
513    * messages and skip the ping. This heuristic may fail if the queue
514    * is in the same position as last time, net of wrapping; in which
515    * case, the client will receive a keepalive.
516    */
517   if (regp->last_queue_head != q->head)
518     {
519       regp->last_heard = now;
520       regp->unanswered_pings = 0;
521       regp->last_queue_head = q->head;
522       return;
523     }
524
525   /*
526    * push/pop shared memory segment, so this routine
527    * will work with "normal" as well as "private segment"
528    * memory clients..
529    */
530
531   mp = vl_mem_api_alloc_as_if_client_w_reg (regp, sizeof (*mp));
532   clib_memset (mp, 0, sizeof (*mp));
533   mp->_vl_msg_id = clib_host_to_net_u16 (VL_API_MEMCLNT_KEEPALIVE);
534   mp->context = mp->client_index =
535     vl_msg_api_handle_from_index_and_epoch
536     (regp->vl_api_registration_pool_index,
537      am->shmem_hdr->application_restarts);
538
539   regp->unanswered_pings++;
540
541   /* Failure-to-send due to a stuffed queue is absolutely expected */
542   if (svm_queue_add (q, (u8 *) & mp, 1 /* nowait */ ))
543     vl_msg_api_free_w_region (regp->vlib_rp, mp);
544 }
545
546 static void
547 vl_mem_send_client_keepalive_w_reg (api_main_t * am, f64 now,
548                                     vl_api_registration_t ** regpp,
549                                     u32 ** dead_indices,
550                                     u32 ** confused_indices)
551 {
552   vl_api_registration_t *regp = *regpp;
553   if (regp)
554     {
555       /* If we haven't heard from this client recently... */
556       if (regp->last_heard < (now - 10.0))
557         {
558           if (regp->unanswered_pings == 2)
559             {
560               svm_queue_t *q;
561               q = regp->vl_input_queue;
562               if (kill (q->consumer_pid, 0) >= 0)
563                 {
564                   clib_warning ("REAPER: lazy binary API client '%s'",
565                                 regp->name);
566                   regp->unanswered_pings = 0;
567                   regp->last_heard = now;
568                 }
569               else
570                 {
571                   clib_warning ("REAPER: binary API client '%s' died",
572                                 regp->name);
573                   vec_add1 (*dead_indices, regpp - am->vl_clients);
574                 }
575             }
576           else
577             send_memclnt_keepalive (regp, now);
578         }
579       else
580         regp->unanswered_pings = 0;
581     }
582   else
583     {
584       clib_warning ("NULL client registration index %d",
585                     regpp - am->vl_clients);
586       vec_add1 (*confused_indices, regpp - am->vl_clients);
587     }
588 }
589
590 void
591 vl_mem_api_dead_client_scan (api_main_t * am, vl_shmem_hdr_t * shm, f64 now)
592 {
593   vl_api_registration_t **regpp;
594   static u32 *dead_indices;
595   static u32 *confused_indices;
596
597   vec_reset_length (dead_indices);
598   vec_reset_length (confused_indices);
599
600   /* *INDENT-OFF* */
601   pool_foreach (regpp, am->vl_clients, ({
602       vl_mem_send_client_keepalive_w_reg (am, now, regpp, &dead_indices,
603                                           &confused_indices);
604   }));
605   /* *INDENT-ON* */
606
607   /* This should "never happen," but if it does, fix it... */
608   if (PREDICT_FALSE (vec_len (confused_indices) > 0))
609     {
610       int i;
611       for (i = 0; i < vec_len (confused_indices); i++)
612         {
613           pool_put_index (am->vl_clients, confused_indices[i]);
614         }
615     }
616
617   if (PREDICT_FALSE (vec_len (dead_indices) > 0))
618     {
619       int i;
620       svm_region_t *svm;
621       void *oldheap;
622
623       /* Allow the application to clean up its registrations */
624       for (i = 0; i < vec_len (dead_indices); i++)
625         {
626           regpp = pool_elt_at_index (am->vl_clients, dead_indices[i]);
627           if (regpp)
628             {
629               u32 handle;
630
631               handle = vl_msg_api_handle_from_index_and_epoch
632                 (dead_indices[i], shm->application_restarts);
633               (void) vl_api_call_reaper_functions (handle);
634             }
635         }
636
637       svm = am->vlib_rp;
638       pthread_mutex_lock (&svm->mutex);
639       oldheap = svm_push_data_heap (svm);
640
641       for (i = 0; i < vec_len (dead_indices); i++)
642         {
643           regpp = pool_elt_at_index (am->vl_clients, dead_indices[i]);
644           if (regpp)
645             {
646               /* Is this a pairwise SVM segment? */
647               if ((*regpp)->vlib_rp != svm)
648                 {
649                   int i;
650                   svm_region_t *dead_rp = (*regpp)->vlib_rp;
651                   /* Note: account for the memfd header page */
652                   uword virtual_base = dead_rp->virtual_base - MMAP_PAGESIZE;
653                   uword virtual_size = dead_rp->virtual_size + MMAP_PAGESIZE;
654
655                   /* For horizontal scaling, add a hash table... */
656                   for (i = 0; i < vec_len (am->vlib_private_rps); i++)
657                     if (am->vlib_private_rps[i] == dead_rp)
658                       {
659                         vec_delete (am->vlib_private_rps, 1, i);
660                         goto found;
661                       }
662                   svm_pop_heap (oldheap);
663                   clib_warning ("private rp %llx AWOL", dead_rp);
664                   oldheap = svm_push_data_heap (svm);
665
666                 found:
667                   /* Kill it, accounting for the memfd header page */
668                   svm_pop_heap (oldheap);
669                   if (munmap ((void *) virtual_base, virtual_size) < 0)
670                     clib_unix_warning ("munmap");
671                   /* Reset the queue-length-address cache */
672                   vec_reset_length (vl_api_queue_cursizes);
673                   oldheap = svm_push_data_heap (svm);
674                 }
675               else
676                 {
677                   /* Poison the old registration */
678                   clib_memset (*regpp, 0xF3, sizeof (**regpp));
679                   clib_mem_free (*regpp);
680                 }
681               /* no dangling references, please */
682               *regpp = 0;
683             }
684           else
685             {
686               svm_pop_heap (oldheap);
687               clib_warning ("Duplicate free, client index %d",
688                             regpp - am->vl_clients);
689               oldheap = svm_push_data_heap (svm);
690             }
691         }
692
693       svm_client_scan_this_region_nolock (am->vlib_rp);
694
695       pthread_mutex_unlock (&svm->mutex);
696       svm_pop_heap (oldheap);
697       for (i = 0; i < vec_len (dead_indices); i++)
698         pool_put_index (am->vl_clients, dead_indices[i]);
699     }
700 }
701
702 static inline int
703 void_mem_api_handle_msg_i (api_main_t * am, svm_region_t * vlib_rp,
704                            vlib_main_t * vm, vlib_node_runtime_t * node,
705                            u8 is_private)
706 {
707   svm_queue_t *q;
708   uword mp;
709
710   q = ((vl_shmem_hdr_t *) (void *) vlib_rp->user_ctx)->vl_input_queue;
711
712   if (!svm_queue_sub2 (q, (u8 *) & mp))
713     {
714       VL_MSG_API_UNPOISON ((void *) mp);
715       vl_msg_api_handler_with_vm_node (am, vlib_rp, (void *) mp, vm, node,
716                                        is_private);
717       return 0;
718     }
719   return -1;
720 }
721
722 int
723 vl_mem_api_handle_msg_main (vlib_main_t * vm, vlib_node_runtime_t * node)
724 {
725   api_main_t *am = vlibapi_get_main ();
726   return void_mem_api_handle_msg_i (am, am->vlib_rp, vm, node,
727                                     0 /* is_private */ );
728 }
729
730 int
731 vl_mem_api_handle_rpc (vlib_main_t * vm, vlib_node_runtime_t * node)
732 {
733   api_main_t *am = vlibapi_get_main ();
734   int i;
735   uword *tmp, mp;
736
737   /*
738    * Swap pending and processing vectors, then process the RPCs
739    * Avoid deadlock conditions by construction.
740    */
741   clib_spinlock_lock_if_init (&vm->pending_rpc_lock);
742   tmp = vm->processing_rpc_requests;
743   vec_reset_length (tmp);
744   vm->processing_rpc_requests = vm->pending_rpc_requests;
745   vm->pending_rpc_requests = tmp;
746   clib_spinlock_unlock_if_init (&vm->pending_rpc_lock);
747
748   /*
749    * RPCs are used to reflect function calls to thread 0
750    * when the underlying code is not thread-safe.
751    *
752    * Grabbing the thread barrier across a set of RPCs
753    * greatly increases efficiency, and avoids
754    * running afoul of the barrier sync holddown timer.
755    * The barrier sync code supports recursive locking.
756    *
757    * We really need to rewrite RPC-based code...
758    */
759   if (PREDICT_TRUE (vec_len (vm->processing_rpc_requests)))
760     {
761       vl_msg_api_barrier_sync ();
762       for (i = 0; i < vec_len (vm->processing_rpc_requests); i++)
763         {
764           mp = vm->processing_rpc_requests[i];
765           vl_msg_api_handler_with_vm_node (am, am->vlib_rp, (void *) mp, vm,
766                                            node, 0 /* is_private */ );
767         }
768       vl_msg_api_barrier_release ();
769     }
770
771   return 0;
772 }
773
774 int
775 vl_mem_api_handle_msg_private (vlib_main_t * vm, vlib_node_runtime_t * node,
776                                u32 reg_index)
777 {
778   api_main_t *am = vlibapi_get_main ();
779
780   return void_mem_api_handle_msg_i (am, am->vlib_private_rps[reg_index], vm,
781                                     node, 1 /* is_private */ );
782 }
783
784 vl_api_registration_t *
785 vl_mem_api_client_index_to_registration (u32 handle)
786 {
787   vl_api_registration_t **regpp;
788   vl_api_registration_t *regp;
789   api_main_t *am = vlibapi_get_main ();
790   vl_shmem_hdr_t *shmem_hdr;
791   u32 index;
792
793   index = vl_msg_api_handle_get_index (handle);
794   regpp = am->vl_clients + index;
795
796   if (pool_is_free (am->vl_clients, regpp))
797     {
798       vl_msg_api_increment_missing_client_counter ();
799       return 0;
800     }
801   regp = *regpp;
802
803   shmem_hdr = (vl_shmem_hdr_t *) regp->shmem_hdr;
804   if (!vl_msg_api_handle_is_valid (handle, shmem_hdr->application_restarts))
805     {
806       vl_msg_api_increment_missing_client_counter ();
807       return 0;
808     }
809
810   return (regp);
811 }
812
813 svm_queue_t *
814 vl_api_client_index_to_input_queue (u32 index)
815 {
816   vl_api_registration_t *regp;
817   api_main_t *am = vlibapi_get_main ();
818
819   /* Special case: vlib trying to send itself a message */
820   if (index == (u32) ~ 0)
821     return (am->shmem_hdr->vl_input_queue);
822
823   regp = vl_mem_api_client_index_to_registration (index);
824   if (!regp)
825     return 0;
826   return (regp->vl_input_queue);
827 }
828
829 static clib_error_t *
830 setup_memclnt_exit (vlib_main_t * vm)
831 {
832   atexit (vl_unmap_shmem);
833   return 0;
834 }
835
836 VLIB_INIT_FUNCTION (setup_memclnt_exit);
837
838 u8 *
839 format_api_message_rings (u8 * s, va_list * args)
840 {
841   api_main_t *am = va_arg (*args, api_main_t *);
842   vl_shmem_hdr_t *shmem_hdr = va_arg (*args, vl_shmem_hdr_t *);
843   int main_segment = va_arg (*args, int);
844   ring_alloc_t *ap;
845   int i;
846
847   if (shmem_hdr == 0)
848     return format (s, "%8s %8s %8s %8s %8s\n",
849                    "Owner", "Size", "Nitems", "Hits", "Misses");
850
851   ap = shmem_hdr->vl_rings;
852
853   for (i = 0; i < vec_len (shmem_hdr->vl_rings); i++)
854     {
855       s = format (s, "%8s %8d %8d %8d %8d\n",
856                   "vlib", ap->size, ap->nitems, ap->hits, ap->misses);
857       ap++;
858     }
859
860   ap = shmem_hdr->client_rings;
861
862   for (i = 0; i < vec_len (shmem_hdr->client_rings); i++)
863     {
864       s = format (s, "%8s %8d %8d %8d %8d\n",
865                   "clnt", ap->size, ap->nitems, ap->hits, ap->misses);
866       ap++;
867     }
868
869   if (main_segment)
870     {
871       s = format (s, "%d ring miss fallback allocations\n", am->ring_misses);
872       s = format
873         (s,
874          "%d application restarts, %d reclaimed msgs, %d garbage collects\n",
875          shmem_hdr->application_restarts, shmem_hdr->restart_reclaims,
876          shmem_hdr->garbage_collects);
877     }
878   return s;
879 }
880
881 static clib_error_t *
882 vl_api_ring_command (vlib_main_t * vm,
883                      unformat_input_t * input, vlib_cli_command_t * cli_cmd)
884 {
885   int i;
886   vl_shmem_hdr_t *shmem_hdr;
887   api_main_t *am = vlibapi_get_main ();
888
889   /* First, dump the primary region rings.. */
890
891   if (am->vlib_primary_rp == 0 || am->vlib_primary_rp->user_ctx == 0)
892     {
893       vlib_cli_output (vm, "Shared memory segment not initialized...\n");
894       return 0;
895     }
896
897   shmem_hdr = (void *) am->vlib_primary_rp->user_ctx;
898
899   vlib_cli_output (vm, "Main API segment rings:");
900
901   vlib_cli_output (vm, "%U", format_api_message_rings, am,
902                    0 /* print header */ , 0 /* notused */ );
903
904   vlib_cli_output (vm, "%U", format_api_message_rings, am,
905                    shmem_hdr, 1 /* main segment */ );
906
907   for (i = 0; i < vec_len (am->vlib_private_rps); i++)
908     {
909       svm_region_t *vlib_rp = am->vlib_private_rps[i];
910       shmem_hdr = (void *) vlib_rp->user_ctx;
911       vl_api_registration_t **regpp;
912       vl_api_registration_t *regp = 0;
913
914       /* For horizontal scaling, add a hash table... */
915       /* *INDENT-OFF* */
916       pool_foreach (regpp, am->vl_clients,
917       ({
918         regp = *regpp;
919         if (regp && regp->vlib_rp == vlib_rp)
920           {
921             vlib_cli_output (vm, "%s segment rings:", regp->name);
922             goto found;
923           }
924       }));
925       vlib_cli_output (vm, "regp %llx not found?", regp);
926       continue;
927       /* *INDENT-ON* */
928     found:
929       vlib_cli_output (vm, "%U", format_api_message_rings, am,
930                        0 /* print header */ , 0 /* notused */ );
931       vlib_cli_output (vm, "%U", format_api_message_rings, am,
932                        shmem_hdr, 0 /* main segment */ );
933     }
934
935   return 0;
936 }
937
938 /*?
939  * Display binary api message allocation ring statistics
940 ?*/
941 /* *INDENT-OFF* */
942 VLIB_CLI_COMMAND (cli_show_api_ring_command, static) =
943 {
944   .path = "show api ring-stats",
945   .short_help = "Message ring statistics",
946   .function = vl_api_ring_command,
947 };
948 /* *INDENT-ON* */
949
950 clib_error_t *
951 vlibmemory_init (vlib_main_t * vm)
952 {
953   api_main_t *am = vlibapi_get_main ();
954   svm_map_region_args_t _a, *a = &_a;
955   u8 *remove_path1, *remove_path2;
956   void vlibsocket_reference (void);
957
958   vlibsocket_reference ();
959
960   /*
961    * By popular request / to avoid support fires, remove any old api segment
962    * files Right Here.
963    */
964   if (am->root_path == 0)
965     {
966       remove_path1 = format (0, "/dev/shm/global_vm%c", 0);
967       remove_path2 = format (0, "/dev/shm/vpe-api%c", 0);
968     }
969   else
970     {
971       remove_path1 = format (0, "/dev/shm/%s-global_vm%c", am->root_path, 0);
972       remove_path2 = format (0, "/dev/shm/%s-vpe-api%c", am->root_path, 0);
973     }
974
975   (void) unlink ((char *) remove_path1);
976   (void) unlink ((char *) remove_path2);
977
978   vec_free (remove_path1);
979   vec_free (remove_path2);
980
981   clib_memset (a, 0, sizeof (*a));
982   a->root_path = am->root_path;
983   a->name = SVM_GLOBAL_REGION_NAME;
984   a->baseva = (am->global_baseva != 0) ?
985     am->global_baseva : +svm_get_global_region_base_va ();
986   a->size = (am->global_size != 0) ? am->global_size : SVM_GLOBAL_REGION_SIZE;
987   a->flags = SVM_FLAGS_NODATA;
988   a->uid = am->api_uid;
989   a->gid = am->api_gid;
990   a->pvt_heap_size =
991     (am->global_pvt_heap_size !=
992      0) ? am->global_pvt_heap_size : SVM_PVT_MHEAP_SIZE;
993
994   svm_region_init_args (a);
995
996   return 0;
997 }
998
999 void
1000 vl_set_memory_region_name (const char *name)
1001 {
1002   api_main_t *am = vlibapi_get_main ();
1003   am->region_name = name;
1004 }
1005
1006 /*
1007  * fd.io coding-style-patch-verification: ON
1008  *
1009  * Local Variables:
1010  * eval: (c-set-style "gnu")
1011  * End:
1012  */