ecd5cff733976e8401ed20d1ce91d9f0aef3733f
[vpp.git] / vlib-api / vlibmemory / memory_shared.c
1 /* 
2  *------------------------------------------------------------------
3  * memclnt_shared.c - API message handling, common code for both clients
4  * and the vlib process itself.
5  * 
6  *
7  * Copyright (c) 2009 Cisco and/or its affiliates.
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at:
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *------------------------------------------------------------------
20  */
21
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <signal.h>
27 #include <vppinfra/format.h>
28 #include <vppinfra/byte_order.h>
29 #include <vppinfra/error.h>
30 #include <vlib/vlib.h>
31 #include <vlib/unix/unix.h>
32 #include <vlibmemory/api.h>
33 #include <vlibmemory/unix_shared_memory_queue.h>
34
35 #include <vlibmemory/vl_memory_msg_enum.h>   
36
37 #define vl_typedefs 
38 #include <vlibmemory/vl_memory_api_h.h>
39 #undef vl_typedefs
40
41 typedef struct msgbuf_ {
42     unix_shared_memory_queue_t *q;
43     u8 data[0];
44 } msgbuf_t;
45
46 static inline void *vl_msg_api_alloc_internal(int nbytes, int pool)
47 {
48     int i;
49     msgbuf_t *rv;
50     ring_alloc_t *ap;
51     unix_shared_memory_queue_t *q;
52     void *oldheap;
53     vl_shmem_hdr_t *shmem_hdr;
54     api_main_t *am = &api_main;
55
56     shmem_hdr = am->shmem_hdr;
57
58     if (shmem_hdr == 0) {
59         clib_warning ("shared memory header NULL");
60         return 0;
61     }
62
63     /* account for the msgbuf_t header*/
64     nbytes += sizeof(msgbuf_t);
65
66     if (shmem_hdr->vl_rings == 0) {
67         clib_warning ("vl_rings NULL");
68         return 0;
69     }
70
71     if (shmem_hdr->client_rings == 0) {
72         clib_warning ("client_rings NULL");
73         return 0;
74     }
75
76     ap = pool ? shmem_hdr->vl_rings : shmem_hdr->client_rings;
77     for (i = 0; i < vec_len (ap); i++) {
78         /* Too big? */
79         if (nbytes > ap[i].size) {
80             continue;
81         }
82
83         q = ap[i].rp;
84         if (pool == 0) {
85             pthread_mutex_lock(&q->mutex);
86         }
87         rv = (msgbuf_t *) (&q->data[0] + q->head*q->elsize);
88         /*
89          * Is this item still in use? 
90          */
91         if (rv->q) {
92             /* yes, loser; try next larger pool */
93             ap[i].misses++;
94             if (pool == 0)
95                 pthread_mutex_unlock(&q->mutex);
96             continue;
97         }
98         /* OK, we have a winner */
99         ap[i].hits++;
100         /*
101          * Remember the source queue, although we
102          * don't need to know the queue to free the item.
103          */
104         rv->q = q;
105         q->head++;
106         if (q->head == q->maxsize)
107             q->head = 0;
108                 
109         if (pool == 0)
110             pthread_mutex_unlock(&q->mutex);
111         goto out;
112     }
113
114     /*
115      * Request too big, or head element of all size-compatible rings
116      * still in use. Fall back to shared-memory malloc.
117      */
118     am->ring_misses++;
119
120     pthread_mutex_lock (&am->vlib_rp->mutex);
121     oldheap = svm_push_data_heap (am->vlib_rp);
122     rv = clib_mem_alloc(nbytes + sizeof(msgbuf_t));
123     rv->q = 0;
124     svm_pop_heap (oldheap);
125     pthread_mutex_unlock (&am->vlib_rp->mutex);
126
127  out:
128     return(rv->data);
129 }
130
131 void *vl_msg_api_alloc (int nbytes)
132 {
133     int pool;
134     api_main_t *am = &api_main;
135     vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
136
137     /*
138      * Clients use pool-0, vlib proc uses pool 1
139      */
140     pool = (am->our_pid == shmem_hdr->vl_pid);
141     return vl_msg_api_alloc_internal (nbytes, pool);
142 }
143
144 void *vl_msg_api_alloc_as_if_client (int nbytes)
145 {
146     return vl_msg_api_alloc_internal (nbytes, 0);
147 }
148
149 void vl_msg_api_free(void *a)
150 {
151     msgbuf_t *rv;
152     void *oldheap;
153     api_main_t *am = &api_main;
154     
155     rv = (msgbuf_t *)(((u8 *)a) - sizeof(*rv));
156     /*
157      * Here's the beauty of the scheme.  Only one proc/thread has
158      * control of a given message buffer. To free a buffer, we just clear the 
159      * queue field, and leave. No locks, no hits, no errors...
160      */
161     if (rv->q) {
162         rv->q = 0;
163         return;
164     }
165
166     pthread_mutex_lock (&am->vlib_rp->mutex);
167     oldheap = svm_push_data_heap (am->vlib_rp);
168     clib_mem_free (rv);
169     svm_pop_heap (oldheap);
170     pthread_mutex_unlock (&am->vlib_rp->mutex);
171 }
172
173 static void vl_msg_api_free_nolock (void *a)
174 {
175     msgbuf_t *rv;
176     void *oldheap;
177     api_main_t *am = &api_main;
178     
179     rv = (msgbuf_t *)(((u8 *)a) - sizeof(*rv));
180     /*
181      * Here's the beauty of the scheme.  Only one proc/thread has
182      * control of a given message buffer. To free a buffer, we just clear the 
183      * queue field, and leave. No locks, no hits, no errors...
184      */
185     if (rv->q) {
186         rv->q = 0;
187         return;
188     }
189
190     oldheap = svm_push_data_heap (am->vlib_rp);
191     clib_mem_free (rv);
192     svm_pop_heap (oldheap);
193 }
194
195 void vl_set_memory_root_path (char *name)
196 {
197     api_main_t *am = &api_main;
198
199     am->root_path = name;
200 }
201
202 int vl_map_shmem (char *region_name, int is_vlib)
203 {
204     svm_map_region_args_t *a = 0;
205     svm_region_t *vlib_rp, *root_rp;
206     void *oldheap;
207     vl_shmem_hdr_t *shmem_hdr=0;
208     api_main_t *am = &api_main;
209     int i;
210     struct timespec ts, tsrem;
211
212     if (is_vlib == 0)
213         svm_region_init_chroot(am->root_path);
214
215     vec_validate (a, 0);
216
217     a->name = region_name;
218     a->size = 16<<20;
219     a->flags = SVM_FLAGS_MHEAP;
220
221     vlib_rp = svm_region_find_or_create (a);
222     
223     vec_free (a);
224
225     if (vlib_rp == 0)
226         return (-2);
227
228     pthread_mutex_lock (&vlib_rp->mutex);
229     /* Has someone else set up the shared-memory variable table? */
230     if (vlib_rp->user_ctx) {
231         am->shmem_hdr = (void *) vlib_rp->user_ctx;
232         am->our_pid = getpid();
233         if (is_vlib) {
234             unix_shared_memory_queue_t *q;
235             uword old_msg;
236             /* 
237              * application restart. Reset cached pids, API message
238              * rings, list of clients; otherwise, various things
239              * fail. (e.g. queue non-empty notification) 
240              */
241
242             /* ghosts keep the region from disappearing properly */
243             svm_client_scan_this_region_nolock(vlib_rp);
244             am->shmem_hdr->application_restarts++;
245             q = am->shmem_hdr->vl_input_queue;
246             am->shmem_hdr->vl_pid = getpid();
247             q->consumer_pid = am->shmem_hdr->vl_pid;
248             /* Drain the input queue, freeing msgs */
249             for (i = 0; i < 10; i++) {
250                 if (pthread_mutex_trylock (&q->mutex) == 0) {
251                     pthread_mutex_unlock (&q->mutex);
252                     goto mutex_ok;
253                 }
254                 ts.tv_sec = 0;
255                 ts.tv_nsec = 10000*1000;  /* 10 ms */
256                 while (nanosleep(&ts, &tsrem) < 0)
257                     ts = tsrem;
258             }
259             /* Mutex buggered, "fix" it */
260             memset (&q->mutex, 0, sizeof (q->mutex));
261             clib_warning ("forcibly release main input queue mutex");
262
263         mutex_ok:
264             am->vlib_rp = vlib_rp;
265             while (unix_shared_memory_queue_sub (q, 
266                                                  (u8 *)&old_msg, 
267                                                  1 /* nowait */) 
268                    != -2 /* queue underflow */) {
269                 vl_msg_api_free_nolock ((void *)old_msg);
270                 am->shmem_hdr->restart_reclaims++;
271             }
272             pthread_mutex_unlock (&vlib_rp->mutex);
273             root_rp = svm_get_root_rp();
274             ASSERT(root_rp);
275             /* Clean up the root region client list */
276             pthread_mutex_lock (&root_rp->mutex);
277             svm_client_scan_this_region_nolock (root_rp);
278             pthread_mutex_unlock (&root_rp->mutex);
279         } else {
280             pthread_mutex_unlock (&vlib_rp->mutex);
281             /* 
282              * Make sure the vlib app is really there...
283              * Wait up to 100 seconds... 
284              */
285             for (i = 0; i < 10000; i++) {
286                 /* Yup, it's there, off we go... */
287                 if (kill (am->shmem_hdr->vl_pid, 0) >= 0)
288                     break;
289
290                 ts.tv_sec = 0;
291                 ts.tv_nsec = 10000*1000;  /* 10 ms */
292                 while (nanosleep(&ts, &tsrem) < 0)
293                     ts = tsrem;
294             }
295         }
296
297         am->vlib_rp = vlib_rp;
298         vec_add1(am->mapped_shmem_regions, vlib_rp);
299         return 0;
300     }
301     /* Clients simply have to wait... */
302     if (!is_vlib) {
303         pthread_mutex_unlock (&vlib_rp->mutex);
304
305         /* Wait up to 100 seconds... */
306         for (i = 0; i < 10000; i++) {
307             ts.tv_sec = 0;
308             ts.tv_nsec = 10000*1000;  /* 10 ms */
309             while (nanosleep(&ts, &tsrem) < 0)
310                 ts = tsrem;
311             if (vlib_rp->user_ctx)
312                 goto ready;
313         }
314         /* Clean up and leave... */
315         svm_region_unmap (vlib_rp);
316         clib_warning ("region init fail");
317         return (-2);
318
319     ready:
320         am->shmem_hdr = (void *)vlib_rp->user_ctx;
321         am->our_pid = getpid();
322         am->vlib_rp = vlib_rp;
323         vec_add1(am->mapped_shmem_regions, vlib_rp);
324         return 0;
325     }
326
327     /* Nope, it's our problem... */
328
329     oldheap = svm_push_data_heap (vlib_rp);
330
331     vec_validate(shmem_hdr, 0);
332     shmem_hdr->version = VL_SHM_VERSION;
333
334     /* vlib main input queue */
335     shmem_hdr->vl_input_queue = 
336         unix_shared_memory_queue_init (1024, sizeof (uword), getpid(),
337                                        am->vlib_signal);
338
339     /* Set up the msg ring allocator */
340 #define _(sz,n)                                                 \
341     do {                                                        \
342         ring_alloc_t _rp;                                       \
343         _rp.rp = unix_shared_memory_queue_init ((n), (sz), 0, 0); \
344         _rp.size = (sz);                                        \
345         _rp.nitems = n;                                         \
346         _rp.hits = 0;                                           \
347         _rp.misses = 0;                                         \
348         vec_add1(shmem_hdr->vl_rings, _rp);                     \
349     } while (0);
350
351     foreach_vl_aring_size;
352 #undef _
353
354 #define _(sz,n)                                                 \
355     do {                                                        \
356         ring_alloc_t _rp;                                       \
357         _rp.rp = unix_shared_memory_queue_init ((n), (sz), 0, 0); \
358         _rp.size = (sz);                                        \
359         _rp.nitems = n;                                         \
360         _rp.hits = 0;                                           \
361         _rp.misses = 0;                                         \
362         vec_add1(shmem_hdr->client_rings, _rp);                 \
363     } while (0);
364
365     foreach_clnt_aring_size;
366 #undef _
367
368     am->shmem_hdr = shmem_hdr;
369     am->vlib_rp = vlib_rp;
370     am->our_pid = getpid();
371     if (is_vlib)
372         am->shmem_hdr->vl_pid = am->our_pid;
373     
374     svm_pop_heap (oldheap);
375
376     /* 
377      * After absolutely everything that a client might see is set up,
378      * declare the shmem region valid
379      */
380     vlib_rp->user_ctx = shmem_hdr;
381
382     pthread_mutex_unlock (&vlib_rp->mutex);
383     vec_add1(am->mapped_shmem_regions, vlib_rp);
384     return 0;
385 }
386
387 void vl_register_mapped_shmem_region(svm_region_t *rp)
388 {
389     api_main_t *am = &api_main;
390
391     vec_add1(am->mapped_shmem_regions, rp);
392 }
393
394 void vl_unmap_shmem (void)
395 {
396     svm_region_t *rp;
397     int i;
398     api_main_t *am = &api_main;
399
400     if (! svm_get_root_rp())
401       return;
402
403     for (i = 0; i < vec_len(am->mapped_shmem_regions); i++) {
404         rp = am->mapped_shmem_regions[i];
405         svm_region_unmap (rp);
406     }
407
408     vec_free(am->mapped_shmem_regions);
409     am->shmem_hdr = 0;
410
411     svm_region_exit ();
412     /* $$$ more careful cleanup, valgrind run... */
413     vec_free (am->msg_handlers);
414     vec_free (am->msg_endian_handlers);
415     vec_free (am->msg_print_handlers);
416 }
417
418 void vl_msg_api_send_shmem (unix_shared_memory_queue_t *q, u8 *elem)
419 {
420     api_main_t *am = &api_main;
421     uword *trace = (uword *)elem;
422
423     if (am->tx_trace && am->tx_trace->enabled)
424         vl_msg_api_trace(am, am->tx_trace, (void *)trace[0]);
425
426     (void)unix_shared_memory_queue_add(q, elem, 0 /* nowait */);
427 }
428
429 void vl_msg_api_send_shmem_nolock (unix_shared_memory_queue_t *q, u8 *elem)
430 {
431     api_main_t *am = &api_main;
432     uword *trace = (uword *)elem;
433
434     if (am->tx_trace && am->tx_trace->enabled)
435         vl_msg_api_trace(am, am->tx_trace, (void *)trace[0]);
436
437     (void)unix_shared_memory_queue_add_nolock (q, elem);
438 }
439
440 static void vl_api_memclnt_create_reply_t_handler (
441     vl_api_memclnt_create_reply_t *mp)
442 {
443     api_main_t *am = &api_main;
444     int rv;
445
446     am->my_client_index = mp->index;
447     am->my_registration = (vl_api_registration_t *)(uword)
448         mp->handle;
449
450     rv = ntohl(mp->response);
451
452     if (rv < 0)
453         clib_warning ("WARNING: API mismatch detected");
454 }        
455
456 void vl_client_add_api_signatures (vl_api_memclnt_create_t *mp) 
457     __attribute__((weak));
458
459 void vl_client_add_api_signatures (vl_api_memclnt_create_t *mp) 
460 {
461     int i;
462
463     for (i = 0; i < ARRAY_LEN(mp->api_versions); i++)
464         mp->api_versions[i] = 0;
465 }
466
467 int vl_client_connect (char *name, int ctx_quota, int input_queue_size)
468 {
469     svm_region_t *svm;
470     vl_api_memclnt_create_t *mp;
471     vl_api_memclnt_create_reply_t *rp;
472     unix_shared_memory_queue_t *vl_input_queue;
473     vl_shmem_hdr_t *shmem_hdr;
474     int rv=0;
475     void *oldheap;
476     api_main_t *am = &api_main;
477
478     if (am->my_registration) {
479         clib_warning ("client %s already connected...", name);
480         return -1;
481     }
482
483     if (am->vlib_rp == 0) {
484         clib_warning ("am->vlib_rp NULL");
485         return -1;
486     }
487
488     svm = am->vlib_rp;
489     shmem_hdr = am->shmem_hdr;
490
491     if (shmem_hdr == 0 || shmem_hdr->vl_input_queue == 0) {
492         clib_warning ("shmem_hdr / input queue NULL");
493         return -1;
494     }
495
496     pthread_mutex_lock (&svm->mutex);
497     oldheap = svm_push_data_heap(svm);
498     vl_input_queue = 
499         unix_shared_memory_queue_init (input_queue_size, sizeof(uword), 
500                                        getpid(), 0);
501     pthread_mutex_unlock(&svm->mutex);
502     svm_pop_heap (oldheap);
503
504     am->my_client_index = ~0;
505     am->my_registration = 0;
506     am->vl_input_queue = vl_input_queue;
507
508     mp = vl_msg_api_alloc(sizeof(vl_api_memclnt_create_t));
509     memset(mp, 0, sizeof (*mp));
510     mp->_vl_msg_id = ntohs(VL_API_MEMCLNT_CREATE);
511     mp->ctx_quota = ctx_quota;
512     mp->input_queue = (uword)vl_input_queue;
513     strncpy ((char *) mp->name, name, sizeof(mp->name)-1);
514
515     vl_client_add_api_signatures(mp);
516     
517     vl_msg_api_send_shmem (shmem_hdr->vl_input_queue, (u8 *)&mp);
518
519     while (1) {
520         int qstatus;
521         struct timespec ts, tsrem;
522         int i;
523
524         /* Wait up to 10 seconds */
525         for (i = 0; i < 1000; i++) {
526             qstatus = unix_shared_memory_queue_sub (vl_input_queue, (u8 *)&rp, 
527                                                     1 /* nowait */);
528             if (qstatus == 0)
529                 goto read_one_msg;
530             ts.tv_sec = 0;
531             ts.tv_nsec = 10000*1000;  /* 10 ms */
532             while (nanosleep(&ts, &tsrem) < 0)
533                 ts = tsrem;
534         }
535         /* Timeout... */
536         clib_warning ("memclnt_create_reply timeout");
537         return -1;
538
539     read_one_msg:
540         if (ntohs(rp->_vl_msg_id) != VL_API_MEMCLNT_CREATE_REPLY) {
541             clib_warning ("unexpected reply: id %d", ntohs(rp->_vl_msg_id));
542             continue;
543         }
544         rv = clib_net_to_host_u32(rp->response);
545
546         vl_msg_api_handler((void *)rp);
547         break;
548     }
549     return (rv);
550 }
551
552 static void vl_api_memclnt_delete_reply_t_handler (
553     vl_api_memclnt_delete_reply_t *mp)
554 {
555     void *oldheap;
556     api_main_t *am = &api_main;
557
558     pthread_mutex_lock (&am->vlib_rp->mutex);
559     oldheap = svm_push_data_heap(am->vlib_rp);
560     unix_shared_memory_queue_free (am->vl_input_queue);
561     pthread_mutex_unlock (&am->vlib_rp->mutex);
562     svm_pop_heap (oldheap);
563
564     am->my_client_index = ~0;
565     am->my_registration = 0;
566     am->vl_input_queue = 0;
567 }        
568
569 void vl_client_disconnect (void)
570 {
571     vl_api_memclnt_delete_t *mp;
572     vl_api_memclnt_delete_reply_t *rp;
573     unix_shared_memory_queue_t *vl_input_queue;
574     vl_shmem_hdr_t *shmem_hdr;
575     time_t begin;
576     api_main_t *am = &api_main;
577     
578     ASSERT(am->vlib_rp);
579     shmem_hdr = am->shmem_hdr;
580     ASSERT(shmem_hdr && shmem_hdr->vl_input_queue);
581
582     vl_input_queue = am->vl_input_queue;
583
584     mp = vl_msg_api_alloc(sizeof(vl_api_memclnt_delete_t));
585     memset(mp, 0, sizeof (*mp));
586     mp->_vl_msg_id = ntohs(VL_API_MEMCLNT_DELETE);
587     mp->index = am->my_client_index;
588     mp->handle = (uword) am->my_registration;
589
590     vl_msg_api_send_shmem (shmem_hdr->vl_input_queue, (u8 *)&mp);
591
592     /* 
593      * Have to be careful here, in case the client is disconnecting
594      * because e.g. the vlib process died, or is unresponsive.
595      */
596     
597     begin = time (0);
598     while (1) {
599         time_t now;
600
601         now = time (0);
602
603         if (now >= (begin + 2)) {
604             clib_warning ("peer unresponsive, give up");
605             am->my_client_index = ~0;
606             am->my_registration = 0;
607             am->shmem_hdr = 0;
608             break;
609         }
610         if (unix_shared_memory_queue_sub (vl_input_queue, (u8 *)&rp, 1) < 0)
611             continue;
612         
613         /* drain the queue */
614         if (ntohs(rp->_vl_msg_id) != VL_API_MEMCLNT_DELETE_REPLY) {
615             vl_msg_api_handler ((void *)rp);
616             continue;
617         }
618         vl_msg_api_handler((void *)rp);
619         break;
620     }
621 }
622
623 static inline vl_api_registration_t 
624 *vl_api_client_index_to_registration_internal (u32 handle)
625 {
626     vl_api_registration_t **regpp;
627     vl_api_registration_t *regp;
628     api_main_t *am = &api_main;
629     u32 index;
630
631     index = vl_msg_api_handle_get_index (handle);
632     if ((am->shmem_hdr->application_restarts & VL_API_EPOCH_MASK)
633         != vl_msg_api_handle_get_epoch (handle)) {
634         vl_msg_api_increment_missing_client_counter();
635         return 0;
636     }
637
638     regpp = am->vl_clients + index;
639
640     if (pool_is_free(am->vl_clients, regpp)) {
641         vl_msg_api_increment_missing_client_counter();
642         return 0;
643     }
644     regp = *regpp;
645     return (regp);
646 }
647
648 vl_api_registration_t *vl_api_client_index_to_registration (u32 index)
649 {
650     return (vl_api_client_index_to_registration_internal (index));
651 }
652
653 unix_shared_memory_queue_t *vl_api_client_index_to_input_queue (u32 index)
654 {
655     vl_api_registration_t *regp;
656
657     regp = vl_api_client_index_to_registration_internal (index);
658     if (!regp)
659         return 0;
660     return (regp->vl_input_queue);
661 }
662
663 #define foreach_api_client_msg                  \
664 _(MEMCLNT_CREATE_REPLY, memclnt_create_reply)   \
665 _(MEMCLNT_DELETE_REPLY, memclnt_delete_reply)
666
667 int vl_client_api_map (char *region_name)
668 {
669     int rv;
670
671     if ((rv = vl_map_shmem (region_name, 0 /* is_vlib */)) < 0) {
672         return rv;
673     }
674
675 #define _(N,n)                                                          \
676     vl_msg_api_set_handlers(VL_API_##N, 0 /* name */,                   \
677                            vl_api_##n##_t_handler,                      \
678                            0/* cleanup */, 0/* endian */, 0/* print */, \
679                            sizeof(vl_api_##n##_t), 1); 
680     foreach_api_client_msg;
681 #undef _
682     return 0;
683 }
684
685 void vl_client_api_unmap (void)
686 {
687     vl_unmap_shmem();
688 }