Initial commit of vpp code.
[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 int vl_map_shmem (char *region_name, int is_vlib)
196 {
197     svm_map_region_args_t *a = 0;
198     svm_region_t *vlib_rp, *root_rp;
199     void *oldheap;
200     vl_shmem_hdr_t *shmem_hdr=0;
201     api_main_t *am = &api_main;
202     int i;
203     struct timespec ts, tsrem;
204
205     if (is_vlib == 0)
206         svm_region_init();
207
208     vec_validate (a, 0);
209
210     a->name = region_name;
211     a->size = 16<<20;
212     a->flags = SVM_FLAGS_MHEAP;
213
214     vlib_rp = svm_region_find_or_create (a);
215     
216     vec_free (a);
217
218     if (vlib_rp == 0)
219         return (-2);
220
221     pthread_mutex_lock (&vlib_rp->mutex);
222     /* Has someone else set up the shared-memory variable table? */
223     if (vlib_rp->user_ctx) {
224         am->shmem_hdr = (void *) vlib_rp->user_ctx;
225         am->our_pid = getpid();
226         if (is_vlib) {
227             unix_shared_memory_queue_t *q;
228             uword old_msg;
229             /* 
230              * application restart. Reset cached pids, API message
231              * rings, list of clients; otherwise, various things
232              * fail. (e.g. queue non-empty notification) 
233              */
234
235             /* ghosts keep the region from disappearing properly */
236             svm_client_scan_this_region_nolock(vlib_rp);
237             am->shmem_hdr->application_restarts++;
238             q = am->shmem_hdr->vl_input_queue;
239             am->shmem_hdr->vl_pid = getpid();
240             q->consumer_pid = am->shmem_hdr->vl_pid;
241             /* Drain the input queue, freeing msgs */
242             for (i = 0; i < 10; i++) {
243                 if (pthread_mutex_trylock (&q->mutex) == 0) {
244                     pthread_mutex_unlock (&q->mutex);
245                     goto mutex_ok;
246                 }
247                 ts.tv_sec = 0;
248                 ts.tv_nsec = 10000*1000;  /* 10 ms */
249                 while (nanosleep(&ts, &tsrem) < 0)
250                     ts = tsrem;
251             }
252             /* Mutex buggered, "fix" it */
253             memset (&q->mutex, 0, sizeof (q->mutex));
254             clib_warning ("forcibly release main input queue mutex");
255
256         mutex_ok:
257             am->vlib_rp = vlib_rp;
258             while (unix_shared_memory_queue_sub (q, 
259                                                  (u8 *)&old_msg, 
260                                                  1 /* nowait */) 
261                    != -2 /* queue underflow */) {
262                 vl_msg_api_free_nolock ((void *)old_msg);
263                 am->shmem_hdr->restart_reclaims++;
264             }
265             pthread_mutex_unlock (&vlib_rp->mutex);
266             root_rp = svm_get_root_rp();
267             ASSERT(root_rp);
268             /* Clean up the root region client list */
269             pthread_mutex_lock (&root_rp->mutex);
270             svm_client_scan_this_region_nolock (root_rp);
271             pthread_mutex_unlock (&root_rp->mutex);
272         } else {
273             pthread_mutex_unlock (&vlib_rp->mutex);
274             /* 
275              * Make sure the vlib app is really there...
276              * Wait up to 100 seconds... 
277              */
278             for (i = 0; i < 10000; i++) {
279                 /* Yup, it's there, off we go... */
280                 if (kill (am->shmem_hdr->vl_pid, 0) >= 0)
281                     break;
282
283                 ts.tv_sec = 0;
284                 ts.tv_nsec = 10000*1000;  /* 10 ms */
285                 while (nanosleep(&ts, &tsrem) < 0)
286                     ts = tsrem;
287             }
288         }
289
290         am->vlib_rp = vlib_rp;
291         vec_add1(am->mapped_shmem_regions, vlib_rp);
292         return 0;
293     }
294     /* Clients simply have to wait... */
295     if (!is_vlib) {
296         pthread_mutex_unlock (&vlib_rp->mutex);
297
298         /* Wait up to 100 seconds... */
299         for (i = 0; i < 10000; i++) {
300             ts.tv_sec = 0;
301             ts.tv_nsec = 10000*1000;  /* 10 ms */
302             while (nanosleep(&ts, &tsrem) < 0)
303                 ts = tsrem;
304             if (vlib_rp->user_ctx)
305                 goto ready;
306         }
307         /* Clean up and leave... */
308         svm_region_unmap (vlib_rp);
309         clib_warning ("region init fail");
310         return (-2);
311
312     ready:
313         am->shmem_hdr = (void *)vlib_rp->user_ctx;
314         am->our_pid = getpid();
315         am->vlib_rp = vlib_rp;
316         vec_add1(am->mapped_shmem_regions, vlib_rp);
317         return 0;
318     }
319
320     /* Nope, it's our problem... */
321
322     oldheap = svm_push_data_heap (vlib_rp);
323
324     vec_validate(shmem_hdr, 0);
325     shmem_hdr->version = VL_SHM_VERSION;
326
327     /* vlib main input queue */
328     shmem_hdr->vl_input_queue = 
329         unix_shared_memory_queue_init (1024, sizeof (uword), getpid(),
330                                        am->vlib_signal);
331
332     /* Set up the msg ring allocator */
333 #define _(sz,n)                                                 \
334     do {                                                        \
335         ring_alloc_t _rp;                                       \
336         _rp.rp = unix_shared_memory_queue_init ((n), (sz), 0, 0); \
337         _rp.size = (sz);                                        \
338         _rp.nitems = n;                                         \
339         _rp.hits = 0;                                           \
340         _rp.misses = 0;                                         \
341         vec_add1(shmem_hdr->vl_rings, _rp);                     \
342     } while (0);
343
344     foreach_vl_aring_size;
345 #undef _
346
347 #define _(sz,n)                                                 \
348     do {                                                        \
349         ring_alloc_t _rp;                                       \
350         _rp.rp = unix_shared_memory_queue_init ((n), (sz), 0, 0); \
351         _rp.size = (sz);                                        \
352         _rp.nitems = n;                                         \
353         _rp.hits = 0;                                           \
354         _rp.misses = 0;                                         \
355         vec_add1(shmem_hdr->client_rings, _rp);                 \
356     } while (0);
357
358     foreach_clnt_aring_size;
359 #undef _
360
361     am->shmem_hdr = shmem_hdr;
362     am->vlib_rp = vlib_rp;
363     am->our_pid = getpid();
364     if (is_vlib)
365         am->shmem_hdr->vl_pid = am->our_pid;
366     
367     svm_pop_heap (oldheap);
368
369     /* 
370      * After absolutely everything that a client might see is set up,
371      * declare the shmem region valid
372      */
373     vlib_rp->user_ctx = shmem_hdr;
374
375     pthread_mutex_unlock (&vlib_rp->mutex);
376     vec_add1(am->mapped_shmem_regions, vlib_rp);
377     return 0;
378 }
379
380 void vl_register_mapped_shmem_region(svm_region_t *rp)
381 {
382     api_main_t *am = &api_main;
383
384     vec_add1(am->mapped_shmem_regions, rp);
385 }
386
387 void vl_unmap_shmem (void)
388 {
389     svm_region_t *rp;
390     int i;
391     api_main_t *am = &api_main;
392
393     if (! svm_get_root_rp())
394       return;
395
396     for (i = 0; i < vec_len(am->mapped_shmem_regions); i++) {
397         rp = am->mapped_shmem_regions[i];
398         svm_region_unmap (rp);
399     }
400
401     vec_free(am->mapped_shmem_regions);
402     am->shmem_hdr = 0;
403
404     svm_region_exit ();
405     /* $$$ more careful cleanup, valgrind run... */
406     vec_free (am->msg_handlers);
407     vec_free (am->msg_endian_handlers);
408     vec_free (am->msg_print_handlers);
409 }
410
411 void vl_msg_api_send_shmem (unix_shared_memory_queue_t *q, u8 *elem)
412 {
413     api_main_t *am = &api_main;
414     uword *trace = (uword *)elem;
415
416     if (am->tx_trace && am->tx_trace->enabled)
417         vl_msg_api_trace(am, am->tx_trace, (void *)trace[0]);
418
419     (void)unix_shared_memory_queue_add(q, elem, 0 /* nowait */);
420 }
421
422 void vl_msg_api_send_shmem_nolock (unix_shared_memory_queue_t *q, u8 *elem)
423 {
424     api_main_t *am = &api_main;
425     uword *trace = (uword *)elem;
426
427     if (am->tx_trace && am->tx_trace->enabled)
428         vl_msg_api_trace(am, am->tx_trace, (void *)trace[0]);
429
430     (void)unix_shared_memory_queue_add_nolock (q, elem);
431 }
432
433 static void vl_api_memclnt_create_reply_t_handler (
434     vl_api_memclnt_create_reply_t *mp)
435 {
436     api_main_t *am = &api_main;
437     int rv;
438
439     am->my_client_index = mp->index;
440     am->my_registration = (vl_api_registration_t *)(uword)
441         mp->handle;
442
443     rv = ntohl(mp->response);
444
445     if (rv < 0)
446         clib_warning ("WARNING: API mismatch detected");
447 }        
448
449 void vl_client_add_api_signatures (vl_api_memclnt_create_t *mp) 
450     __attribute__((weak));
451
452 void vl_client_add_api_signatures (vl_api_memclnt_create_t *mp) 
453 {
454     int i;
455
456     for (i = 0; i < ARRAY_LEN(mp->api_versions); i++)
457         mp->api_versions[i] = 0;
458 }
459
460 int vl_client_connect (char *name, int ctx_quota, int input_queue_size)
461 {
462     svm_region_t *svm;
463     vl_api_memclnt_create_t *mp;
464     vl_api_memclnt_create_reply_t *rp;
465     unix_shared_memory_queue_t *vl_input_queue;
466     vl_shmem_hdr_t *shmem_hdr;
467     int rv=0;
468     void *oldheap;
469     api_main_t *am = &api_main;
470
471     if (am->my_registration) {
472         clib_warning ("client %s already connected...", name);
473         return -1;
474     }
475
476     if (am->vlib_rp == 0) {
477         clib_warning ("am->vlib_rp NULL");
478         return -1;
479     }
480
481     svm = am->vlib_rp;
482     shmem_hdr = am->shmem_hdr;
483
484     if (shmem_hdr == 0 || shmem_hdr->vl_input_queue == 0) {
485         clib_warning ("shmem_hdr / input queue NULL");
486         return -1;
487     }
488
489     pthread_mutex_lock (&svm->mutex);
490     oldheap = svm_push_data_heap(svm);
491     vl_input_queue = 
492         unix_shared_memory_queue_init (input_queue_size, sizeof(uword), 
493                                        getpid(), 0);
494     pthread_mutex_unlock(&svm->mutex);
495     svm_pop_heap (oldheap);
496
497     am->my_client_index = ~0;
498     am->my_registration = 0;
499     am->vl_input_queue = vl_input_queue;
500
501     mp = vl_msg_api_alloc(sizeof(vl_api_memclnt_create_t));
502     memset(mp, 0, sizeof (*mp));
503     mp->_vl_msg_id = ntohs(VL_API_MEMCLNT_CREATE);
504     mp->ctx_quota = ctx_quota;
505     mp->input_queue = (uword)vl_input_queue;
506     strncpy ((char *) mp->name, name, sizeof(mp->name)-1);
507
508     vl_client_add_api_signatures(mp);
509     
510     vl_msg_api_send_shmem (shmem_hdr->vl_input_queue, (u8 *)&mp);
511
512     while (1) {
513         int qstatus;
514         struct timespec ts, tsrem;
515         int i;
516
517         /* Wait up to 10 seconds */
518         for (i = 0; i < 1000; i++) {
519             qstatus = unix_shared_memory_queue_sub (vl_input_queue, (u8 *)&rp, 
520                                                     1 /* nowait */);
521             if (qstatus == 0)
522                 goto read_one_msg;
523             ts.tv_sec = 0;
524             ts.tv_nsec = 10000*1000;  /* 10 ms */
525             while (nanosleep(&ts, &tsrem) < 0)
526                 ts = tsrem;
527         }
528         /* Timeout... */
529         clib_warning ("memclnt_create_reply timeout");
530         return -1;
531
532     read_one_msg:
533         if (ntohs(rp->_vl_msg_id) != VL_API_MEMCLNT_CREATE_REPLY) {
534             clib_warning ("unexpected reply: id %d", ntohs(rp->_vl_msg_id));
535             continue;
536         }
537         rv = clib_net_to_host_u32(rp->response);
538
539         vl_msg_api_handler((void *)rp);
540         break;
541     }
542     return (rv);
543 }
544
545 static void vl_api_memclnt_delete_reply_t_handler (
546     vl_api_memclnt_delete_reply_t *mp)
547 {
548     void *oldheap;
549     api_main_t *am = &api_main;
550
551     pthread_mutex_lock (&am->vlib_rp->mutex);
552     oldheap = svm_push_data_heap(am->vlib_rp);
553     unix_shared_memory_queue_free (am->vl_input_queue);
554     pthread_mutex_unlock (&am->vlib_rp->mutex);
555     svm_pop_heap (oldheap);
556
557     am->my_client_index = ~0;
558     am->my_registration = 0;
559     am->vl_input_queue = 0;
560 }        
561
562 void vl_client_disconnect (void)
563 {
564     vl_api_memclnt_delete_t *mp;
565     vl_api_memclnt_delete_reply_t *rp;
566     unix_shared_memory_queue_t *vl_input_queue;
567     vl_shmem_hdr_t *shmem_hdr;
568     time_t begin;
569     api_main_t *am = &api_main;
570     
571     ASSERT(am->vlib_rp);
572     shmem_hdr = am->shmem_hdr;
573     ASSERT(shmem_hdr && shmem_hdr->vl_input_queue);
574
575     vl_input_queue = am->vl_input_queue;
576
577     mp = vl_msg_api_alloc(sizeof(vl_api_memclnt_delete_t));
578     memset(mp, 0, sizeof (*mp));
579     mp->_vl_msg_id = ntohs(VL_API_MEMCLNT_DELETE);
580     mp->index = am->my_client_index;
581     mp->handle = (uword) am->my_registration;
582
583     vl_msg_api_send_shmem (shmem_hdr->vl_input_queue, (u8 *)&mp);
584
585     /* 
586      * Have to be careful here, in case the client is disconnecting
587      * because e.g. the vlib process died, or is unresponsive.
588      */
589     
590     begin = time (0);
591     while (1) {
592         time_t now;
593
594         now = time (0);
595
596         if (now >= (begin + 2)) {
597             clib_warning ("peer unresponsive, give up");
598             am->my_client_index = ~0;
599             am->my_registration = 0;
600             am->shmem_hdr = 0;
601             break;
602         }
603         if (unix_shared_memory_queue_sub (vl_input_queue, (u8 *)&rp, 1) < 0)
604             continue;
605         
606         /* drain the queue */
607         if (ntohs(rp->_vl_msg_id) != VL_API_MEMCLNT_DELETE_REPLY) {
608             vl_msg_api_handler ((void *)rp);
609             continue;
610         }
611         vl_msg_api_handler((void *)rp);
612         break;
613     }
614 }
615
616 static inline vl_api_registration_t 
617 *vl_api_client_index_to_registration_internal (u32 handle)
618 {
619     vl_api_registration_t **regpp;
620     vl_api_registration_t *regp;
621     api_main_t *am = &api_main;
622     u32 index;
623
624     index = vl_msg_api_handle_get_index (handle);
625     if ((am->shmem_hdr->application_restarts & VL_API_EPOCH_MASK)
626         != vl_msg_api_handle_get_epoch (handle)) {
627         vl_msg_api_increment_missing_client_counter();
628         return 0;
629     }
630
631     regpp = am->vl_clients + index;
632
633     if (pool_is_free(am->vl_clients, regpp)) {
634         vl_msg_api_increment_missing_client_counter();
635         return 0;
636     }
637     regp = *regpp;
638     return (regp);
639 }
640
641 vl_api_registration_t *vl_api_client_index_to_registration (u32 index)
642 {
643     return (vl_api_client_index_to_registration_internal (index));
644 }
645
646 unix_shared_memory_queue_t *vl_api_client_index_to_input_queue (u32 index)
647 {
648     vl_api_registration_t *regp;
649
650     regp = vl_api_client_index_to_registration_internal (index);
651     if (!regp)
652         return 0;
653     return (regp->vl_input_queue);
654 }
655
656 #define foreach_api_client_msg                  \
657 _(MEMCLNT_CREATE_REPLY, memclnt_create_reply)   \
658 _(MEMCLNT_DELETE_REPLY, memclnt_delete_reply)
659
660 int vl_client_api_map (char *region_name)
661 {
662     int rv;
663
664     if ((rv = vl_map_shmem (region_name, 0 /* is_vlib */)) < 0) {
665         return rv;
666     }
667
668 #define _(N,n)                                                          \
669     vl_msg_api_set_handlers(VL_API_##N, 0 /* name */,                   \
670                            vl_api_##n##_t_handler,                      \
671                            0/* cleanup */, 0/* endian */, 0/* print */, \
672                            sizeof(vl_api_##n##_t), 1); 
673     foreach_api_client_msg;
674 #undef _
675     return 0;
676 }
677
678 void vl_client_api_unmap (void)
679 {
680     vl_unmap_shmem();
681 }