api: refactor vlibmemory
[vpp.git] / src / 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 <stddef.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <signal.h>
28
29 #include <vppinfra/format.h>
30 #include <vppinfra/byte_order.h>
31 #include <vppinfra/error.h>
32 #include <svm/queue.h>
33 #include <vlib/vlib.h>
34 #include <vlib/unix/unix.h>
35 #include <vlibmemory/memory_api.h>
36 #include <vlibmemory/vl_memory_msg_enum.h>
37
38 #define vl_typedefs
39 #include <vlibmemory/vl_memory_api_h.h>
40 #undef vl_typedefs
41
42 #define DEBUG_MESSAGE_BUFFER_OVERRUN 0
43
44 static inline void *
45 vl_msg_api_alloc_internal (int nbytes, int pool, int may_return_null)
46 {
47   int i;
48   msgbuf_t *rv;
49   ring_alloc_t *ap;
50   svm_queue_t *q;
51   void *oldheap;
52   vl_shmem_hdr_t *shmem_hdr;
53   api_main_t *am = &api_main;
54
55   shmem_hdr = am->shmem_hdr;
56
57 #if DEBUG_MESSAGE_BUFFER_OVERRUN > 0
58   nbytes += 4;
59 #endif
60
61   ASSERT (pool == 0 || vlib_get_thread_index () == 0);
62
63   if (shmem_hdr == 0)
64     {
65       clib_warning ("shared memory header NULL");
66       return 0;
67     }
68
69   /* account for the msgbuf_t header */
70   nbytes += sizeof (msgbuf_t);
71
72   if (shmem_hdr->vl_rings == 0)
73     {
74       clib_warning ("vl_rings NULL");
75       ASSERT (0);
76       abort ();
77     }
78
79   if (shmem_hdr->client_rings == 0)
80     {
81       clib_warning ("client_rings NULL");
82       ASSERT (0);
83       abort ();
84     }
85
86   ap = pool ? shmem_hdr->vl_rings : shmem_hdr->client_rings;
87   for (i = 0; i < vec_len (ap); i++)
88     {
89       /* Too big? */
90       if (nbytes > ap[i].size)
91         {
92           continue;
93         }
94
95       q = ap[i].rp;
96       if (pool == 0)
97         {
98           pthread_mutex_lock (&q->mutex);
99         }
100       rv = (msgbuf_t *) (&q->data[0] + q->head * q->elsize);
101       /*
102        * Is this item still in use?
103        */
104       if (rv->q)
105         {
106           u32 now = (u32) time (0);
107
108           if (PREDICT_TRUE (rv->gc_mark_timestamp == 0))
109             rv->gc_mark_timestamp = now;
110           else
111             {
112               if (now - rv->gc_mark_timestamp > 10)
113                 {
114                   if (CLIB_DEBUG > 0)
115                     {
116                       u16 *msg_idp, msg_id;
117                       clib_warning
118                         ("garbage collect pool %d ring %d index %d", pool, i,
119                          q->head);
120                       msg_idp = (u16 *) (rv->data);
121                       msg_id = clib_net_to_host_u16 (*msg_idp);
122                       if (msg_id < vec_len (api_main.msg_names))
123                         clib_warning ("msg id %d name %s", (u32) msg_id,
124                                       api_main.msg_names[msg_id]);
125                     }
126                   shmem_hdr->garbage_collects++;
127                   goto collected;
128                 }
129             }
130
131
132           /* yes, loser; try next larger pool */
133           ap[i].misses++;
134           if (pool == 0)
135             pthread_mutex_unlock (&q->mutex);
136           continue;
137         }
138     collected:
139
140       /* OK, we have a winner */
141       ap[i].hits++;
142       /*
143        * Remember the source queue, although we
144        * don't need to know the queue to free the item.
145        */
146       rv->q = q;
147       rv->gc_mark_timestamp = 0;
148       q->head++;
149       if (q->head == q->maxsize)
150         q->head = 0;
151
152       if (pool == 0)
153         pthread_mutex_unlock (&q->mutex);
154       goto out;
155     }
156
157   /*
158    * Request too big, or head element of all size-compatible rings
159    * still in use. Fall back to shared-memory malloc.
160    */
161   am->ring_misses++;
162
163   pthread_mutex_lock (&am->vlib_rp->mutex);
164   oldheap = svm_push_data_heap (am->vlib_rp);
165   if (may_return_null)
166     {
167       rv = clib_mem_alloc_or_null (nbytes);
168       if (PREDICT_FALSE (rv == 0))
169         {
170           svm_pop_heap (oldheap);
171           pthread_mutex_unlock (&am->vlib_rp->mutex);
172           return 0;
173         }
174     }
175   else
176     rv = clib_mem_alloc (nbytes);
177
178   rv->q = 0;
179   svm_pop_heap (oldheap);
180   pthread_mutex_unlock (&am->vlib_rp->mutex);
181
182 out:
183 #if DEBUG_MESSAGE_BUFFER_OVERRUN > 0
184   {
185     nbytes -= 4;
186     u32 *overrun;
187     overrun = (u32 *) (rv->data + nbytes - sizeof (msgbuf_t));
188     *overrun = 0x1badbabe;
189   }
190 #endif
191   rv->data_len = htonl (nbytes - sizeof (msgbuf_t));
192
193   return (rv->data);
194 }
195
196 void *
197 vl_msg_api_alloc (int nbytes)
198 {
199   int pool;
200   api_main_t *am = &api_main;
201   vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
202
203   /*
204    * Clients use pool-0, vlib proc uses pool 1
205    */
206   pool = (am->our_pid == shmem_hdr->vl_pid);
207   return vl_msg_api_alloc_internal (nbytes, pool, 0 /* may_return_null */ );
208 }
209
210 void *
211 vl_msg_api_alloc_or_null (int nbytes)
212 {
213   int pool;
214   api_main_t *am = &api_main;
215   vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
216
217   pool = (am->our_pid == shmem_hdr->vl_pid);
218   return vl_msg_api_alloc_internal (nbytes, pool, 1 /* may_return_null */ );
219 }
220
221 void *
222 vl_msg_api_alloc_as_if_client (int nbytes)
223 {
224   return vl_msg_api_alloc_internal (nbytes, 0, 0 /* may_return_null */ );
225 }
226
227 void *
228 vl_msg_api_alloc_as_if_client_or_null (int nbytes)
229 {
230   return vl_msg_api_alloc_internal (nbytes, 0, 1 /* may_return_null */ );
231 }
232
233 void
234 vl_msg_api_free (void *a)
235 {
236   msgbuf_t *rv;
237   void *oldheap;
238   api_main_t *am = &api_main;
239
240   rv = (msgbuf_t *) (((u8 *) a) - offsetof (msgbuf_t, data));
241
242   /*
243    * Here's the beauty of the scheme.  Only one proc/thread has
244    * control of a given message buffer. To free a buffer, we just clear the
245    * queue field, and leave. No locks, no hits, no errors...
246    */
247   if (rv->q)
248     {
249       rv->q = 0;
250       rv->gc_mark_timestamp = 0;
251 #if DEBUG_MESSAGE_BUFFER_OVERRUN > 0
252       {
253         u32 *overrun;
254         overrun = (u32 *) (rv->data + ntohl (rv->data_len));
255         ASSERT (*overrun == 0x1badbabe);
256       }
257 #endif
258       return;
259     }
260
261   pthread_mutex_lock (&am->vlib_rp->mutex);
262   oldheap = svm_push_data_heap (am->vlib_rp);
263
264 #if DEBUG_MESSAGE_BUFFER_OVERRUN > 0
265   {
266     u32 *overrun;
267     overrun = (u32 *) (rv->data + ntohl (rv->data_len));
268     ASSERT (*overrun == 0x1badbabe);
269   }
270 #endif
271
272   clib_mem_free (rv);
273   svm_pop_heap (oldheap);
274   pthread_mutex_unlock (&am->vlib_rp->mutex);
275 }
276
277 static void
278 vl_msg_api_free_nolock (void *a)
279 {
280   msgbuf_t *rv;
281   void *oldheap;
282   api_main_t *am = &api_main;
283
284   rv = (msgbuf_t *) (((u8 *) a) - offsetof (msgbuf_t, data));
285   /*
286    * Here's the beauty of the scheme.  Only one proc/thread has
287    * control of a given message buffer. To free a buffer, we just clear the
288    * queue field, and leave. No locks, no hits, no errors...
289    */
290   if (rv->q)
291     {
292       rv->q = 0;
293       return;
294     }
295
296   oldheap = svm_push_data_heap (am->vlib_rp);
297   clib_mem_free (rv);
298   svm_pop_heap (oldheap);
299 }
300
301 void
302 vl_set_memory_root_path (const char *name)
303 {
304   api_main_t *am = &api_main;
305
306   am->root_path = name;
307 }
308
309 void
310 vl_set_memory_uid (int uid)
311 {
312   api_main_t *am = &api_main;
313
314   am->api_uid = uid;
315 }
316
317 void
318 vl_set_memory_gid (int gid)
319 {
320   api_main_t *am = &api_main;
321
322   am->api_gid = gid;
323 }
324
325 void
326 vl_set_global_memory_baseva (u64 baseva)
327 {
328   api_main_t *am = &api_main;
329
330   am->global_baseva = baseva;
331 }
332
333 void
334 vl_set_global_memory_size (u64 size)
335 {
336   api_main_t *am = &api_main;
337
338   am->global_size = size;
339 }
340
341 void
342 vl_set_api_memory_size (u64 size)
343 {
344   api_main_t *am = &api_main;
345
346   am->api_size = size;
347 }
348
349 void
350 vl_set_global_pvt_heap_size (u64 size)
351 {
352   api_main_t *am = &api_main;
353
354   am->global_pvt_heap_size = size;
355 }
356
357 void
358 vl_set_api_pvt_heap_size (u64 size)
359 {
360   api_main_t *am = &api_main;
361
362   am->api_pvt_heap_size = size;
363 }
364
365 static void
366 vl_api_default_mem_config (vl_shmem_hdr_t * shmem_hdr)
367 {
368   api_main_t *am = &api_main;
369   u32 vlib_input_queue_length;
370
371   /* vlib main input queue */
372   vlib_input_queue_length = 1024;
373   if (am->vlib_input_queue_length)
374     vlib_input_queue_length = am->vlib_input_queue_length;
375
376   shmem_hdr->vl_input_queue =
377     svm_queue_init (vlib_input_queue_length, sizeof (uword),
378                     getpid (), am->vlib_signal);
379
380 #define _(sz,n)                                                 \
381     do {                                                        \
382         ring_alloc_t _rp;                                       \
383         _rp.rp = svm_queue_init ((n), (sz), 0, 0); \
384         _rp.size = (sz);                                        \
385         _rp.nitems = n;                                         \
386         _rp.hits = 0;                                           \
387         _rp.misses = 0;                                         \
388         vec_add1(shmem_hdr->vl_rings, _rp);                     \
389     } while (0);
390
391   foreach_vl_aring_size;
392 #undef _
393
394 #define _(sz,n)                                                 \
395     do {                                                        \
396         ring_alloc_t _rp;                                       \
397         _rp.rp = svm_queue_init ((n), (sz), 0, 0); \
398         _rp.size = (sz);                                        \
399         _rp.nitems = n;                                         \
400         _rp.hits = 0;                                           \
401         _rp.misses = 0;                                         \
402         vec_add1(shmem_hdr->client_rings, _rp);                 \
403     } while (0);
404
405   foreach_clnt_aring_size;
406 #undef _
407 }
408
409 void
410 vl_api_mem_config (vl_shmem_hdr_t * hdr, vl_api_shm_elem_config_t * config)
411 {
412   api_main_t *am = &api_main;
413   vl_api_shm_elem_config_t *c;
414   ring_alloc_t *rp;
415   u32 size;
416
417   if (!config)
418     {
419       vl_api_default_mem_config (hdr);
420       return;
421     }
422
423   vec_foreach (c, config)
424   {
425     switch (c->type)
426       {
427       case VL_API_QUEUE:
428         hdr->vl_input_queue = svm_queue_init (c->count,
429                                               c->size,
430                                               getpid (), am->vlib_signal);
431         continue;
432       case VL_API_VLIB_RING:
433         vec_add2 (hdr->vl_rings, rp, 1);
434         break;
435       case VL_API_CLIENT_RING:
436         vec_add2 (hdr->client_rings, rp, 1);
437         break;
438       default:
439         clib_warning ("unknown config type: %d", c->type);
440         continue;
441       }
442
443     size = sizeof (ring_alloc_t) + c->size;
444     rp->rp = svm_queue_init (c->count, size, 0, 0);
445     rp->size = size;
446     rp->nitems = c->count;
447     rp->hits = 0;
448     rp->misses = 0;
449   }
450 }
451
452 void
453 vl_init_shmem (svm_region_t * vlib_rp, vl_api_shm_elem_config_t * config,
454                int is_vlib, int is_private_region)
455 {
456   api_main_t *am = &api_main;
457   vl_shmem_hdr_t *shmem_hdr = 0;
458   void *oldheap;
459   ASSERT (vlib_rp);
460
461   /* $$$$ need private region config parameters */
462
463   oldheap = svm_push_data_heap (vlib_rp);
464
465   vec_validate (shmem_hdr, 0);
466   shmem_hdr->version = VL_SHM_VERSION;
467
468   /* Set up the queue and msg ring allocator */
469   vl_api_mem_config (shmem_hdr, config);
470
471   if (is_private_region == 0)
472     {
473       am->shmem_hdr = shmem_hdr;
474       am->vlib_rp = vlib_rp;
475       am->our_pid = getpid ();
476       if (is_vlib)
477         am->shmem_hdr->vl_pid = am->our_pid;
478     }
479   else
480     shmem_hdr->vl_pid = am->our_pid;
481
482   svm_pop_heap (oldheap);
483
484   /*
485    * After absolutely everything that a client might see is set up,
486    * declare the shmem region valid
487    */
488   vlib_rp->user_ctx = shmem_hdr;
489
490   pthread_mutex_unlock (&vlib_rp->mutex);
491 }
492
493 int
494 vl_map_shmem (const char *region_name, int is_vlib)
495 {
496   svm_map_region_args_t _a, *a = &_a;
497   svm_region_t *vlib_rp, *root_rp;
498   api_main_t *am = &api_main;
499   int i, rv;
500   struct timespec ts, tsrem;
501   char *vpe_api_region_suffix = "-vpe-api";
502
503   memset (a, 0, sizeof (*a));
504
505   if (strstr (region_name, vpe_api_region_suffix))
506     {
507       u8 *root_path = format (0, "%s", region_name);
508       _vec_len (root_path) = (vec_len (root_path) -
509                               strlen (vpe_api_region_suffix));
510       vec_terminate_c_string (root_path);
511       a->root_path = (const char *) root_path;
512       am->root_path = (const char *) root_path;
513     }
514
515   if (is_vlib == 0)
516     {
517       rv = svm_region_init_chroot (am->root_path);
518       if (rv)
519         return rv;
520     }
521
522   if (a->root_path != NULL)
523     {
524       a->name = "/vpe-api";
525     }
526   else
527     a->name = region_name;
528   a->size = am->api_size ? am->api_size : (16 << 20);
529   a->flags = SVM_FLAGS_MHEAP;
530   a->uid = am->api_uid;
531   a->gid = am->api_gid;
532   a->pvt_heap_size = am->api_pvt_heap_size;
533
534   vlib_rp = svm_region_find_or_create (a);
535
536   if (vlib_rp == 0)
537     return (-2);
538
539   pthread_mutex_lock (&vlib_rp->mutex);
540   /* Has someone else set up the shared-memory variable table? */
541   if (vlib_rp->user_ctx)
542     {
543       am->shmem_hdr = (void *) vlib_rp->user_ctx;
544       am->our_pid = getpid ();
545       if (is_vlib)
546         {
547           svm_queue_t *q;
548           uword old_msg;
549           /*
550            * application restart. Reset cached pids, API message
551            * rings, list of clients; otherwise, various things
552            * fail. (e.g. queue non-empty notification)
553            */
554
555           /* ghosts keep the region from disappearing properly */
556           svm_client_scan_this_region_nolock (vlib_rp);
557           am->shmem_hdr->application_restarts++;
558           q = am->shmem_hdr->vl_input_queue;
559           am->shmem_hdr->vl_pid = getpid ();
560           q->consumer_pid = am->shmem_hdr->vl_pid;
561           /* Drain the input queue, freeing msgs */
562           for (i = 0; i < 10; i++)
563             {
564               if (pthread_mutex_trylock (&q->mutex) == 0)
565                 {
566                   pthread_mutex_unlock (&q->mutex);
567                   goto mutex_ok;
568                 }
569               ts.tv_sec = 0;
570               ts.tv_nsec = 10000 * 1000;        /* 10 ms */
571               while (nanosleep (&ts, &tsrem) < 0)
572                 ts = tsrem;
573             }
574           /* Mutex buggered, "fix" it */
575           memset (&q->mutex, 0, sizeof (q->mutex));
576           clib_warning ("forcibly release main input queue mutex");
577
578         mutex_ok:
579           am->vlib_rp = vlib_rp;
580           while (svm_queue_sub (q, (u8 *) & old_msg, 1 /* nowait */ )
581                  != -2 /* queue underflow */ )
582             {
583               vl_msg_api_free_nolock ((void *) old_msg);
584               am->shmem_hdr->restart_reclaims++;
585             }
586           pthread_mutex_unlock (&vlib_rp->mutex);
587           root_rp = svm_get_root_rp ();
588           ASSERT (root_rp);
589           /* Clean up the root region client list */
590           pthread_mutex_lock (&root_rp->mutex);
591           svm_client_scan_this_region_nolock (root_rp);
592           pthread_mutex_unlock (&root_rp->mutex);
593         }
594       else
595         {
596           pthread_mutex_unlock (&vlib_rp->mutex);
597         }
598       am->vlib_rp = vlib_rp;
599       vec_add1 (am->mapped_shmem_regions, vlib_rp);
600       return 0;
601     }
602   /* Clients simply have to wait... */
603   if (!is_vlib)
604     {
605       pthread_mutex_unlock (&vlib_rp->mutex);
606
607       /* Wait up to 100 seconds... */
608       for (i = 0; i < 10000; i++)
609         {
610           ts.tv_sec = 0;
611           ts.tv_nsec = 10000 * 1000;    /* 10 ms */
612           while (nanosleep (&ts, &tsrem) < 0)
613             ts = tsrem;
614           if (vlib_rp->user_ctx)
615             goto ready;
616         }
617       /* Clean up and leave... */
618       svm_region_unmap (vlib_rp);
619       clib_warning ("region init fail");
620       return (-2);
621
622     ready:
623       am->shmem_hdr = (void *) vlib_rp->user_ctx;
624       am->our_pid = getpid ();
625       am->vlib_rp = vlib_rp;
626       vec_add1 (am->mapped_shmem_regions, vlib_rp);
627       return 0;
628     }
629
630   /* Nope, it's our problem... */
631   vl_init_shmem (vlib_rp, 0 /* default config */ , 1 /* is vlib */ ,
632                  0 /* is_private_region */ );
633
634   vec_add1 (am->mapped_shmem_regions, vlib_rp);
635   return 0;
636 }
637
638 void
639 vl_register_mapped_shmem_region (svm_region_t * rp)
640 {
641   api_main_t *am = &api_main;
642
643   vec_add1 (am->mapped_shmem_regions, rp);
644 }
645
646 void
647 vl_unmap_shmem (void)
648 {
649   svm_region_t *rp;
650   int i;
651   api_main_t *am = &api_main;
652
653   if (!svm_get_root_rp ())
654     return;
655
656   for (i = 0; i < vec_len (am->mapped_shmem_regions); i++)
657     {
658       rp = am->mapped_shmem_regions[i];
659       svm_region_unmap (rp);
660     }
661
662   vec_free (am->mapped_shmem_regions);
663   am->shmem_hdr = 0;
664
665   svm_region_exit ();
666   /* $$$ more careful cleanup, valgrind run... */
667   vec_free (am->msg_handlers);
668   vec_free (am->msg_endian_handlers);
669   vec_free (am->msg_print_handlers);
670 }
671
672 void
673 vl_msg_api_send_shmem (svm_queue_t * q, u8 * elem)
674 {
675   api_main_t *am = &api_main;
676   uword *trace = (uword *) elem;
677
678   if (am->tx_trace && am->tx_trace->enabled)
679     vl_msg_api_trace (am, am->tx_trace, (void *) trace[0]);
680
681   (void) svm_queue_add (q, elem, 0 /* nowait */ );
682 }
683
684 void
685 vl_msg_api_send_shmem_nolock (svm_queue_t * q, u8 * elem)
686 {
687   api_main_t *am = &api_main;
688   uword *trace = (uword *) elem;
689
690   if (am->tx_trace && am->tx_trace->enabled)
691     vl_msg_api_trace (am, am->tx_trace, (void *) trace[0]);
692
693   (void) svm_queue_add_nolock (q, elem);
694 }
695
696 /*
697  * fd.io coding-style-patch-verification: ON
698  *
699  * Local Variables:
700  * eval: (c-set-style "gnu")
701  * End:
702  */