api: refactor vlibmemory
[vpp.git] / src / vlibmemory / memory_client.c
1 /*
2  *------------------------------------------------------------------
3  * memory_client.c - API message handling, client code.
4  *
5  * Copyright (c) 2010 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 <setjmp.h>
21
22 #include <svm/svm.h>
23 #include <vppinfra/serialize.h>
24 #include <vppinfra/hash.h>
25 #include <vlibmemory/memory_client.h>
26
27 /* A hack. vl_client_get_first_plugin_msg_id depends on it */
28 #include <vlibmemory/socket_client.h>
29
30 #include <vlibmemory/vl_memory_msg_enum.h>
31
32 #define vl_typedefs             /* define message structures */
33 #include <vlibmemory/vl_memory_api_h.h>
34 #undef vl_typedefs
35
36 #define vl_endianfun            /* define message structures */
37 #include <vlibmemory/vl_memory_api_h.h>
38 #undef vl_endianfun
39
40 /* instantiate all the print functions we know about */
41 #define vl_print(handle, ...) clib_warning (__VA_ARGS__)
42 #define vl_printfun
43 #include <vlibmemory/vl_memory_api_h.h>
44 #undef vl_printfun
45
46 typedef struct
47 {
48   u8 rx_thread_jmpbuf_valid;
49   u8 connected_to_vlib;
50   jmp_buf rx_thread_jmpbuf;
51   pthread_t rx_thread_handle;
52   /* Plugin message base lookup scheme */
53   volatile u8 first_msg_id_reply_ready;
54   u16 first_msg_id_reply;
55 } memory_client_main_t;
56
57 memory_client_main_t memory_client_main;
58
59 static void *
60 rx_thread_fn (void *arg)
61 {
62   svm_queue_t *q;
63   memory_client_main_t *mm = &memory_client_main;
64   api_main_t *am = &api_main;
65   int i;
66
67   q = am->vl_input_queue;
68
69   /* So we can make the rx thread terminate cleanly */
70   if (setjmp (mm->rx_thread_jmpbuf) == 0)
71     {
72       mm->rx_thread_jmpbuf_valid = 1;
73       /*
74        * Find an unused slot in the per-cpu-mheaps array,
75        * and grab it for this thread. We need to be able to
76        * push/pop the thread heap without affecting other thread(s).
77        */
78       if (__os_thread_index == 0)
79         {
80           for (i = 0; i < ARRAY_LEN (clib_per_cpu_mheaps); i++)
81             {
82               if (clib_per_cpu_mheaps[i] == 0)
83                 {
84                   /* Copy the main thread mheap pointer */
85                   clib_per_cpu_mheaps[i] = clib_per_cpu_mheaps[0];
86                   __os_thread_index = i;
87                   break;
88                 }
89             }
90           ASSERT (__os_thread_index > 0);
91         }
92       while (1)
93         vl_msg_api_queue_handler (q);
94     }
95   pthread_exit (0);
96 }
97
98 static void
99 vl_api_rx_thread_exit_t_handler (vl_api_rx_thread_exit_t * mp)
100 {
101   memory_client_main_t *mm = &memory_client_main;
102   vl_msg_api_free (mp);
103   longjmp (mm->rx_thread_jmpbuf, 1);
104 }
105
106 static void
107 vl_api_memclnt_create_reply_t_handler (vl_api_memclnt_create_reply_t * mp)
108 {
109   serialize_main_t _sm, *sm = &_sm;
110   api_main_t *am = &api_main;
111   u8 *tblv;
112   u32 nmsgs;
113   int i;
114   u8 *name_and_crc;
115   u32 msg_index;
116
117   am->my_client_index = mp->index;
118   am->my_registration = (vl_api_registration_t *) (uword) mp->handle;
119
120   /* Clean out any previous hash table (unlikely) */
121   if (am->msg_index_by_name_and_crc)
122     {
123       int i;
124       u8 **keys = 0;
125       hash_pair_t *hp;
126       /* *INDENT-OFF* */
127       hash_foreach_pair (hp, am->msg_index_by_name_and_crc,
128       ({
129         vec_add1 (keys, (u8 *) hp->key);
130       }));
131       /* *INDENT-ON* */
132       for (i = 0; i < vec_len (keys); i++)
133         vec_free (keys[i]);
134       vec_free (keys);
135     }
136
137   am->msg_index_by_name_and_crc = hash_create_string (0, sizeof (uword));
138
139   /* Recreate the vnet-side API message handler table */
140   tblv = uword_to_pointer (mp->message_table, u8 *);
141   unserialize_open_data (sm, tblv, vec_len (tblv));
142   unserialize_integer (sm, &nmsgs, sizeof (u32));
143
144   for (i = 0; i < nmsgs; i++)
145     {
146       msg_index = unserialize_likely_small_unsigned_integer (sm);
147       unserialize_cstring (sm, (char **) &name_and_crc);
148       hash_set_mem (am->msg_index_by_name_and_crc, name_and_crc, msg_index);
149     }
150 }
151
152 static void
153 noop_handler (void *notused)
154 {
155 }
156
157 int
158 vl_client_connect (const char *name, int ctx_quota, int input_queue_size)
159 {
160   svm_region_t *svm;
161   vl_api_memclnt_create_t *mp;
162   vl_api_memclnt_create_reply_t *rp;
163   svm_queue_t *vl_input_queue;
164   vl_shmem_hdr_t *shmem_hdr;
165   int rv = 0;
166   void *oldheap;
167   api_main_t *am = &api_main;
168
169   if (am->my_registration)
170     {
171       clib_warning ("client %s already connected...", name);
172       return -1;
173     }
174
175   if (am->vlib_rp == 0)
176     {
177       clib_warning ("am->vlib_rp NULL");
178       return -1;
179     }
180
181   svm = am->vlib_rp;
182   shmem_hdr = am->shmem_hdr;
183
184   if (shmem_hdr == 0 || shmem_hdr->vl_input_queue == 0)
185     {
186       clib_warning ("shmem_hdr / input queue NULL");
187       return -1;
188     }
189
190   pthread_mutex_lock (&svm->mutex);
191   oldheap = svm_push_data_heap (svm);
192   vl_input_queue =
193     svm_queue_init (input_queue_size, sizeof (uword), getpid (), 0);
194   pthread_mutex_unlock (&svm->mutex);
195   svm_pop_heap (oldheap);
196
197   am->my_client_index = ~0;
198   am->my_registration = 0;
199   am->vl_input_queue = vl_input_queue;
200
201   mp = vl_msg_api_alloc (sizeof (vl_api_memclnt_create_t));
202   memset (mp, 0, sizeof (*mp));
203   mp->_vl_msg_id = ntohs (VL_API_MEMCLNT_CREATE);
204   mp->ctx_quota = ctx_quota;
205   mp->input_queue = (uword) vl_input_queue;
206   strncpy ((char *) mp->name, name, sizeof (mp->name) - 1);
207
208   vl_msg_api_send_shmem (shmem_hdr->vl_input_queue, (u8 *) & mp);
209
210   while (1)
211     {
212       int qstatus;
213       struct timespec ts, tsrem;
214       int i;
215
216       /* Wait up to 10 seconds */
217       for (i = 0; i < 1000; i++)
218         {
219           qstatus = svm_queue_sub (vl_input_queue, (u8 *) & rp,
220                                    1 /* nowait */ );
221           if (qstatus == 0)
222             goto read_one_msg;
223           ts.tv_sec = 0;
224           ts.tv_nsec = 10000 * 1000;    /* 10 ms */
225           while (nanosleep (&ts, &tsrem) < 0)
226             ts = tsrem;
227         }
228       /* Timeout... */
229       clib_warning ("memclnt_create_reply timeout");
230       return -1;
231
232     read_one_msg:
233       if (ntohs (rp->_vl_msg_id) != VL_API_MEMCLNT_CREATE_REPLY)
234         {
235           clib_warning ("unexpected reply: id %d", ntohs (rp->_vl_msg_id));
236           continue;
237         }
238       rv = clib_net_to_host_u32 (rp->response);
239
240       vl_msg_api_handler ((void *) rp);
241       break;
242     }
243   return (rv);
244 }
245
246 static void
247 vl_api_memclnt_delete_reply_t_handler (vl_api_memclnt_delete_reply_t * mp)
248 {
249   void *oldheap;
250   api_main_t *am = &api_main;
251
252   pthread_mutex_lock (&am->vlib_rp->mutex);
253   oldheap = svm_push_data_heap (am->vlib_rp);
254   svm_queue_free (am->vl_input_queue);
255   pthread_mutex_unlock (&am->vlib_rp->mutex);
256   svm_pop_heap (oldheap);
257
258   am->my_client_index = ~0;
259   am->my_registration = 0;
260   am->vl_input_queue = 0;
261 }
262
263 void
264 vl_client_disconnect (void)
265 {
266   vl_api_memclnt_delete_t *mp;
267   vl_api_memclnt_delete_reply_t *rp;
268   svm_queue_t *vl_input_queue;
269   vl_shmem_hdr_t *shmem_hdr;
270   time_t begin;
271   api_main_t *am = &api_main;
272
273   ASSERT (am->vlib_rp);
274   shmem_hdr = am->shmem_hdr;
275   ASSERT (shmem_hdr && shmem_hdr->vl_input_queue);
276
277   vl_input_queue = am->vl_input_queue;
278
279   mp = vl_msg_api_alloc (sizeof (vl_api_memclnt_delete_t));
280   memset (mp, 0, sizeof (*mp));
281   mp->_vl_msg_id = ntohs (VL_API_MEMCLNT_DELETE);
282   mp->index = am->my_client_index;
283   mp->handle = (uword) am->my_registration;
284
285   vl_msg_api_send_shmem (shmem_hdr->vl_input_queue, (u8 *) & mp);
286
287   /*
288    * Have to be careful here, in case the client is disconnecting
289    * because e.g. the vlib process died, or is unresponsive.
290    */
291
292   begin = time (0);
293   while (1)
294     {
295       time_t now;
296
297       now = time (0);
298
299       if (now >= (begin + 2))
300         {
301           clib_warning ("peer unresponsive, give up");
302           am->my_client_index = ~0;
303           am->my_registration = 0;
304           am->shmem_hdr = 0;
305           break;
306         }
307       if (svm_queue_sub (vl_input_queue, (u8 *) & rp, 1) < 0)
308         continue;
309
310       /* drain the queue */
311       if (ntohs (rp->_vl_msg_id) != VL_API_MEMCLNT_DELETE_REPLY)
312         {
313           clib_warning ("queue drain: %d", ntohs (rp->_vl_msg_id));
314           vl_msg_api_handler ((void *) rp);
315           continue;
316         }
317       vl_msg_api_handler ((void *) rp);
318       break;
319     }
320 }
321
322 /**
323  * Stave off the binary API dead client reaper
324  * Only sent to inactive clients
325  */
326 static void
327 vl_api_memclnt_keepalive_t_handler (vl_api_memclnt_keepalive_t * mp)
328 {
329   vl_api_memclnt_keepalive_reply_t *rmp;
330   api_main_t *am;
331   vl_shmem_hdr_t *shmem_hdr;
332
333   am = &api_main;
334   shmem_hdr = am->shmem_hdr;
335
336   rmp = vl_msg_api_alloc_as_if_client (sizeof (*rmp));
337   memset (rmp, 0, sizeof (*rmp));
338   rmp->_vl_msg_id = ntohs (VL_API_MEMCLNT_KEEPALIVE_REPLY);
339   rmp->context = mp->context;
340   vl_msg_api_send_shmem (shmem_hdr->vl_input_queue, (u8 *) & rmp);
341 }
342
343 #define foreach_api_msg                         \
344 _(RX_THREAD_EXIT, rx_thread_exit)               \
345 _(MEMCLNT_CREATE_REPLY, memclnt_create_reply)   \
346 _(MEMCLNT_DELETE_REPLY, memclnt_delete_reply)   \
347 _(MEMCLNT_KEEPALIVE, memclnt_keepalive)
348
349 void
350 vl_client_install_client_message_handlers (void)
351 {
352
353 #define _(N,n)                                                  \
354     vl_msg_api_set_handlers(VL_API_##N, #n,                     \
355                             vl_api_##n##_t_handler,             \
356                             noop_handler,                       \
357                             vl_api_##n##_t_endian,              \
358                             vl_api_##n##_t_print,               \
359                             sizeof(vl_api_##n##_t), 1);
360   foreach_api_msg;
361 #undef _
362 }
363
364
365 int
366 vl_client_api_map (const char *region_name)
367 {
368   int rv;
369
370   if ((rv = vl_map_shmem (region_name, 0 /* is_vlib */ )) < 0)
371     return rv;
372
373   vl_client_install_client_message_handlers ();
374   return 0;
375 }
376
377 void
378 vl_client_api_unmap (void)
379 {
380   vl_unmap_shmem ();
381 }
382
383 static int
384 connect_to_vlib_internal (const char *svm_name,
385                           const char *client_name,
386                           int rx_queue_size, int want_pthread, int do_map)
387 {
388   int rv = 0;
389   memory_client_main_t *mm = &memory_client_main;
390
391   if (do_map && (rv = vl_client_api_map (svm_name)))
392     {
393       clib_warning ("vl_client_api map rv %d", rv);
394       return rv;
395     }
396
397   if (vl_client_connect (client_name, 0 /* punt quota */ ,
398                          rx_queue_size /* input queue */ ) < 0)
399     {
400       vl_client_api_unmap ();
401       return -1;
402     }
403
404   /* Start the rx queue thread */
405
406   if (want_pthread)
407     {
408       rv = pthread_create (&mm->rx_thread_handle,
409                            NULL /*attr */ , rx_thread_fn, 0);
410       if (rv)
411         clib_warning ("pthread_create returned %d", rv);
412     }
413
414   mm->connected_to_vlib = 1;
415   return 0;
416 }
417
418 int
419 vl_client_connect_to_vlib (const char *svm_name,
420                            const char *client_name, int rx_queue_size)
421 {
422   return connect_to_vlib_internal (svm_name, client_name, rx_queue_size,
423                                    1 /* want pthread */ ,
424                                    1 /* do map */ );
425 }
426
427 int
428 vl_client_connect_to_vlib_no_rx_pthread (const char *svm_name,
429                                          const char *client_name,
430                                          int rx_queue_size)
431 {
432   return connect_to_vlib_internal (svm_name, client_name, rx_queue_size,
433                                    0 /* want pthread */ ,
434                                    1 /* do map */ );
435 }
436
437 int
438 vl_client_connect_to_vlib_no_map (const char *svm_name,
439                                   const char *client_name, int rx_queue_size)
440 {
441   return connect_to_vlib_internal (svm_name, client_name, rx_queue_size,
442                                    1 /* want pthread */ ,
443                                    0 /* dont map */ );
444 }
445
446 void
447 vl_client_disconnect_from_vlib (void)
448 {
449   memory_client_main_t *mm = &memory_client_main;
450   api_main_t *am = &api_main;
451   uword junk;
452
453   if (mm->rx_thread_jmpbuf_valid)
454     {
455       vl_api_rx_thread_exit_t *ep;
456       ep = vl_msg_api_alloc (sizeof (*ep));
457       ep->_vl_msg_id = ntohs (VL_API_RX_THREAD_EXIT);
458       vl_msg_api_send_shmem (am->vl_input_queue, (u8 *) & ep);
459       pthread_join (mm->rx_thread_handle, (void **) &junk);
460     }
461   if (mm->connected_to_vlib)
462     {
463       vl_client_disconnect ();
464       vl_client_api_unmap ();
465     }
466   memset (mm, 0, sizeof (*mm));
467 }
468
469 static void vl_api_get_first_msg_id_reply_t_handler
470   (vl_api_get_first_msg_id_reply_t * mp)
471 {
472   memory_client_main_t *mm = &memory_client_main;
473   i32 retval = ntohl (mp->retval);
474
475   mm->first_msg_id_reply = (retval >= 0) ? ntohs (mp->first_msg_id) : ~0;
476   mm->first_msg_id_reply_ready = 1;
477 }
478
479 u16
480 vl_client_get_first_plugin_msg_id (const char *plugin_name)
481 {
482   vl_api_get_first_msg_id_t *mp;
483   api_main_t *am = &api_main;
484   memory_client_main_t *mm = &memory_client_main;
485   f64 timeout;
486   void *old_handler;
487   clib_time_t clib_time;
488   u16 rv = ~0;
489
490   if (strlen (plugin_name) + 1 > sizeof (mp->name))
491     return (rv);
492
493   memset (&clib_time, 0, sizeof (clib_time));
494   clib_time_init (&clib_time);
495
496   /* Push this plugin's first_msg_id_reply handler */
497   old_handler = am->msg_handlers[VL_API_GET_FIRST_MSG_ID_REPLY];
498   am->msg_handlers[VL_API_GET_FIRST_MSG_ID_REPLY] = (void *)
499     vl_api_get_first_msg_id_reply_t_handler;
500
501   /* Ask the data-plane for the message-ID base of the indicated plugin */
502   mm->first_msg_id_reply_ready = 0;
503
504   /* Not using shm client */
505   if (!am->my_registration)
506     {
507       mp = vl_socket_client_msg_alloc (sizeof (*mp));
508       memset (mp, 0, sizeof (*mp));
509       mp->_vl_msg_id = ntohs (VL_API_GET_FIRST_MSG_ID);
510       mp->client_index = am->my_client_index;
511       strncpy ((char *) mp->name, plugin_name, sizeof (mp->name) - 1);
512
513       if (vl_socket_client_write () <= 0)
514         goto sock_err;
515       if (vl_socket_client_read (1))
516         goto sock_err;
517
518       if (mm->first_msg_id_reply_ready == 1)
519         {
520           rv = mm->first_msg_id_reply;
521           goto result;
522         }
523
524     sock_err:
525       /* Restore old handler */
526       am->msg_handlers[VL_API_GET_FIRST_MSG_ID_REPLY] = old_handler;
527
528       return -1;
529     }
530   else
531     {
532       mp = vl_msg_api_alloc (sizeof (*mp));
533       memset (mp, 0, sizeof (*mp));
534       mp->_vl_msg_id = ntohs (VL_API_GET_FIRST_MSG_ID);
535       mp->client_index = am->my_client_index;
536       strncpy ((char *) mp->name, plugin_name, sizeof (mp->name) - 1);
537
538       vl_msg_api_send_shmem (am->shmem_hdr->vl_input_queue, (u8 *) & mp);
539
540       /* Synchronously wait for the answer */
541       timeout = clib_time_now (&clib_time) + 1.0;
542       while (clib_time_now (&clib_time) < timeout)
543         {
544           if (mm->first_msg_id_reply_ready == 1)
545             {
546               rv = mm->first_msg_id_reply;
547               goto result;
548             }
549         }
550       /* Restore old handler */
551       am->msg_handlers[VL_API_GET_FIRST_MSG_ID_REPLY] = old_handler;
552
553       return rv;
554     }
555
556 result:
557
558   /* Restore the old handler */
559   am->msg_handlers[VL_API_GET_FIRST_MSG_ID_REPLY] = old_handler;
560
561   if (rv == (u16) ~ 0)
562     clib_warning ("plugin '%s' not registered", plugin_name);
563
564   return rv;
565 }
566
567 /*
568  * fd.io coding-style-patch-verification: ON
569  *
570  * Local Variables:
571  * eval: (c-set-style "gnu")
572  * End:
573  */