svm: calc base address on AArch64 based on autodetected VA space size
[vpp.git] / src / svm / svm.c
1 /*
2  *------------------------------------------------------------------
3  * svm.c - shared VM allocation, mmap(...MAP_FIXED...)
4  * library
5  *
6  * Copyright (c) 2009 Cisco and/or its affiliates.
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at:
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *------------------------------------------------------------------
19  */
20
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <sys/types.h>
24 #include <sys/mman.h>
25 #include <sys/stat.h>
26 #include <netinet/in.h>
27 #include <signal.h>
28 #include <pthread.h>
29 #include <unistd.h>
30 #include <time.h>
31 #include <fcntl.h>
32 #include <string.h>
33 #include <vppinfra/clib.h>
34 #include <vppinfra/vec.h>
35 #include <vppinfra/hash.h>
36 #include <vppinfra/bitmap.h>
37 #include <vppinfra/fifo.h>
38 #include <vppinfra/time.h>
39 #include <vppinfra/mheap.h>
40 #include <vppinfra/heap.h>
41 #include <vppinfra/pool.h>
42 #include <vppinfra/format.h>
43
44 #include "svm.h"
45
46 static svm_region_t *root_rp;
47 static int root_rp_refcount;
48
49 #define MAXLOCK 2
50 static pthread_mutex_t *mutexes_held[MAXLOCK];
51 static int nheld;
52
53 svm_region_t *
54 svm_get_root_rp (void)
55 {
56   return root_rp;
57 }
58
59 #define MUTEX_DEBUG
60
61 u64
62 svm_get_global_region_base_va ()
63 {
64 #if __aarch64__
65   /* On AArch64 VA space can have different size, from 36 to 48 bits.
66      Here we are trying to detect VA bits by parsing /proc/self/maps
67      address ranges */
68   int fd;
69   unformat_input_t input;
70   u64 start, end = 0;
71   u8 bits = 0;
72
73   if ((fd = open ("/proc/self/maps", 0)) < 0)
74     clib_unix_error ("open '/proc/self/maps'");
75
76   unformat_init_clib_file (&input, fd);
77   while (unformat_check_input (&input) != UNFORMAT_END_OF_INPUT)
78     {
79       unformat (&input, "%llx-%llx", &start, &end);
80       unformat_skip_line (&input);
81     }
82   unformat_free (&input);
83   close (fd);
84
85   count_leading_zeros (bits, end);
86   bits = 64 - (bits + 1);
87   if (bits >= 36 && bits <= 48)
88     return ((1ul << bits) / 4) - (2 * SVM_GLOBAL_REGION_SIZE);
89   else
90     clib_unix_error ("unexpected va bits '%u'", bits);
91 #endif
92
93   /* default value */
94   return 0x30000000;
95 }
96
97 static void
98 region_lock (svm_region_t * rp, int tag)
99 {
100   pthread_mutex_lock (&rp->mutex);
101 #ifdef MUTEX_DEBUG
102   rp->mutex_owner_pid = getpid ();
103   rp->mutex_owner_tag = tag;
104 #endif
105   ASSERT (nheld < MAXLOCK);
106   /*
107    * Keep score of held mutexes so we can try to exit
108    * cleanly if the world comes to an end at the worst possible
109    * moment
110    */
111   mutexes_held[nheld++] = &rp->mutex;
112 }
113
114 static void
115 region_unlock (svm_region_t * rp)
116 {
117   int i, j;
118 #ifdef MUTEX_DEBUG
119   rp->mutex_owner_pid = 0;
120   rp->mutex_owner_tag = 0;
121 #endif
122
123   for (i = nheld - 1; i >= 0; i--)
124     {
125       if (mutexes_held[i] == &rp->mutex)
126         {
127           for (j = i; j < MAXLOCK - 1; j++)
128             mutexes_held[j] = mutexes_held[j + 1];
129           nheld--;
130           goto found;
131         }
132     }
133   ASSERT (0);
134
135 found:
136   CLIB_MEMORY_BARRIER ();
137   pthread_mutex_unlock (&rp->mutex);
138 }
139
140
141 static u8 *
142 format_svm_flags (u8 * s, va_list * args)
143 {
144   uword f = va_arg (*args, uword);
145
146   if (f & SVM_FLAGS_MHEAP)
147     s = format (s, "MHEAP ");
148   if (f & SVM_FLAGS_FILE)
149     s = format (s, "FILE ");
150   if (f & SVM_FLAGS_NODATA)
151     s = format (s, "NODATA ");
152   if (f & SVM_FLAGS_NEED_DATA_INIT)
153     s = format (s, "INIT ");
154
155   return (s);
156 }
157
158 static u8 *
159 format_svm_size (u8 * s, va_list * args)
160 {
161   uword size = va_arg (*args, uword);
162
163   if (size >= (1 << 20))
164     {
165       s = format (s, "(%d mb)", size >> 20);
166     }
167   else if (size >= (1 << 10))
168     {
169       s = format (s, "(%d kb)", size >> 10);
170     }
171   else
172     {
173       s = format (s, "(%d bytes)", size);
174     }
175   return (s);
176 }
177
178 u8 *
179 format_svm_region (u8 * s, va_list * args)
180 {
181   svm_region_t *rp = va_arg (*args, svm_region_t *);
182   int verbose = va_arg (*args, int);
183   int i;
184   uword lo, hi;
185
186   s = format (s, "%s: base va 0x%x size 0x%x %U\n",
187               rp->region_name, rp->virtual_base,
188               rp->virtual_size, format_svm_size, rp->virtual_size);
189   s = format (s, "  user_ctx 0x%x, bitmap_size %d\n",
190               rp->user_ctx, rp->bitmap_size);
191
192   if (verbose)
193     {
194       s = format (s, "  flags: 0x%x %U\n", rp->flags,
195                   format_svm_flags, rp->flags);
196       s = format (s,
197                   "  region_heap 0x%x data_base 0x%x data_heap 0x%x\n",
198                   rp->region_heap, rp->data_base, rp->data_heap);
199     }
200
201   s = format (s, "  %d clients, pids: ", vec_len (rp->client_pids));
202
203   for (i = 0; i < vec_len (rp->client_pids); i++)
204     s = format (s, "%d ", rp->client_pids[i]);
205
206   s = format (s, "\n");
207
208   if (verbose)
209     {
210       lo = hi = ~0;
211
212       s = format (s, "  VM in use: ");
213
214       for (i = 0; i < rp->bitmap_size; i++)
215         {
216           if (clib_bitmap_get_no_check (rp->bitmap, i) != 0)
217             {
218               if (lo == ~0)
219                 {
220                   hi = lo = rp->virtual_base + i * MMAP_PAGESIZE;
221                 }
222               else
223                 {
224                   hi = rp->virtual_base + i * MMAP_PAGESIZE;
225                 }
226             }
227           else
228             {
229               if (lo != ~0)
230                 {
231                   hi = rp->virtual_base + i * MMAP_PAGESIZE - 1;
232                   s = format (s, "   0x%x - 0x%x (%dk)\n", lo, hi,
233                               (hi - lo) >> 10);
234                   lo = hi = ~0;
235                 }
236             }
237         }
238       s = format (s, "  rgn heap stats: %U", format_mheap,
239                   rp->region_heap, 0);
240       if ((rp->flags & SVM_FLAGS_MHEAP) && rp->data_heap)
241         {
242           s = format (s, "\n  data heap stats: %U", format_mheap,
243                       rp->data_heap, 1);
244         }
245       s = format (s, "\n");
246     }
247
248   return (s);
249 }
250
251 /*
252  * rnd_pagesize
253  * Round to a pagesize multiple, presumably 4k works
254  */
255 static u64
256 rnd_pagesize (u64 size)
257 {
258   u64 rv;
259
260   rv = (size + (MMAP_PAGESIZE - 1)) & ~(MMAP_PAGESIZE - 1);
261   return (rv);
262 }
263
264 /*
265  * svm_data_region_setup
266  */
267 static int
268 svm_data_region_create (svm_map_region_args_t * a, svm_region_t * rp)
269 {
270   int fd;
271   u8 junk = 0;
272   uword map_size;
273
274   map_size = rp->virtual_size - (MMAP_PAGESIZE +
275                                  (a->pvt_heap_size ? a->pvt_heap_size :
276                                   SVM_PVT_MHEAP_SIZE));
277
278   if (a->flags & SVM_FLAGS_FILE)
279     {
280       struct stat statb;
281
282       fd = open (a->backing_file, O_RDWR | O_CREAT, 0777);
283
284       if (fd < 0)
285         {
286           clib_unix_warning ("open");
287           return -1;
288         }
289
290       if (fstat (fd, &statb) < 0)
291         {
292           clib_unix_warning ("fstat");
293           close (fd);
294           return -2;
295         }
296
297       if (statb.st_mode & S_IFREG)
298         {
299           if (statb.st_size == 0)
300             {
301               if (lseek (fd, map_size, SEEK_SET) == (off_t) - 1)
302                 {
303                   clib_unix_warning ("seek region size");
304                   close (fd);
305                   return -3;
306                 }
307               if (write (fd, &junk, 1) != 1)
308                 {
309                   clib_unix_warning ("set region size");
310                   close (fd);
311                   return -3;
312                 }
313             }
314           else
315             {
316               map_size = rnd_pagesize (statb.st_size);
317             }
318         }
319       else
320         {
321           map_size = a->backing_mmap_size;
322         }
323
324       ASSERT (map_size <= rp->virtual_size -
325               (MMAP_PAGESIZE + SVM_PVT_MHEAP_SIZE));
326
327       if (mmap (rp->data_base, map_size, PROT_READ | PROT_WRITE,
328                 MAP_SHARED | MAP_FIXED, fd, 0) == MAP_FAILED)
329         {
330           clib_unix_warning ("mmap");
331           close (fd);
332           return -3;
333         }
334       close (fd);
335       rp->backing_file = (char *) format (0, "%s\0", a->backing_file);
336       rp->flags |= SVM_FLAGS_FILE;
337     }
338
339   if (a->flags & SVM_FLAGS_MHEAP)
340     {
341       rp->data_heap =
342         mheap_alloc_with_flags ((void *) (rp->data_base), map_size,
343                                 MHEAP_FLAG_DISABLE_VM);
344       rp->flags |= SVM_FLAGS_MHEAP;
345     }
346   return 0;
347 }
348
349 static int
350 svm_data_region_map (svm_map_region_args_t * a, svm_region_t * rp)
351 {
352   int fd;
353   u8 junk = 0;
354   uword map_size;
355   struct stat statb;
356
357   map_size = rp->virtual_size -
358     (MMAP_PAGESIZE
359      + (a->pvt_heap_size ? a->pvt_heap_size : SVM_PVT_MHEAP_SIZE));
360
361   if (a->flags & SVM_FLAGS_FILE)
362     {
363
364       fd = open (a->backing_file, O_RDWR, 0777);
365
366       if (fd < 0)
367         {
368           clib_unix_warning ("open");
369           return -1;
370         }
371
372       if (fstat (fd, &statb) < 0)
373         {
374           clib_unix_warning ("fstat");
375           close (fd);
376           return -2;
377         }
378
379       if (statb.st_mode & S_IFREG)
380         {
381           if (statb.st_size == 0)
382             {
383               if (lseek (fd, map_size, SEEK_SET) == (off_t) - 1)
384                 {
385                   clib_unix_warning ("seek region size");
386                   close (fd);
387                   return -3;
388                 }
389               if (write (fd, &junk, 1) != 1)
390                 {
391                   clib_unix_warning ("set region size");
392                   close (fd);
393                   return -3;
394                 }
395             }
396           else
397             {
398               map_size = rnd_pagesize (statb.st_size);
399             }
400         }
401       else
402         {
403           map_size = a->backing_mmap_size;
404         }
405
406       ASSERT (map_size <= rp->virtual_size
407               - (MMAP_PAGESIZE
408                  +
409                  (a->pvt_heap_size ? a->pvt_heap_size : SVM_PVT_MHEAP_SIZE)));
410
411       if (mmap (rp->data_base, map_size, PROT_READ | PROT_WRITE,
412                 MAP_SHARED | MAP_FIXED, fd, 0) == MAP_FAILED)
413         {
414           clib_unix_warning ("mmap");
415           close (fd);
416           return -3;
417         }
418       close (fd);
419     }
420   return 0;
421 }
422
423 u8 *
424 shm_name_from_svm_map_region_args (svm_map_region_args_t * a)
425 {
426   u8 *path;
427   u8 *shm_name;
428   u8 *split_point;
429   u8 *mkdir_arg = 0;
430   int root_path_offset = 0;
431   int name_offset = 0;
432
433   if (a->root_path)
434     {
435       /* Tolerate present or absent slashes */
436       if (a->root_path[0] == '/')
437         root_path_offset++;
438
439       /* create the root_path under /dev/shm
440          iterate through path creating directories */
441
442       path = format (0, "/dev/shm/%s%c", &a->root_path[root_path_offset], 0);
443       split_point = path + 1;
444       vec_add1 (mkdir_arg, '-');
445
446       while (*split_point)
447         {
448           while (*split_point && *split_point != '/')
449             {
450               vec_add1 (mkdir_arg, *split_point);
451               split_point++;
452             }
453           vec_add1 (mkdir_arg, 0);
454
455           /* ready to descend another level */
456           mkdir_arg[vec_len (mkdir_arg) - 1] = '-';
457           split_point++;
458         }
459       vec_free (mkdir_arg);
460       vec_free (path);
461
462       if (a->name[0] == '/')
463         name_offset = 1;
464
465       shm_name = format (0, "/%s-%s%c", &a->root_path[root_path_offset],
466                          &a->name[name_offset], 0);
467     }
468   else
469     shm_name = format (0, "%s%c", a->name, 0);
470   return (shm_name);
471 }
472
473 void
474 svm_region_init_mapped_region (svm_map_region_args_t * a, svm_region_t * rp)
475 {
476   pthread_mutexattr_t attr;
477   pthread_condattr_t cattr;
478   int nbits, words, bit;
479   int overhead_space;
480   void *oldheap;
481   uword data_base;
482   ASSERT (rp);
483   int rv;
484
485   memset (rp, 0, sizeof (*rp));
486
487   if (pthread_mutexattr_init (&attr))
488     clib_unix_warning ("mutexattr_init");
489
490   if (pthread_mutexattr_setpshared (&attr, PTHREAD_PROCESS_SHARED))
491     clib_unix_warning ("mutexattr_setpshared");
492
493   if (pthread_mutex_init (&rp->mutex, &attr))
494     clib_unix_warning ("mutex_init");
495
496   if (pthread_mutexattr_destroy (&attr))
497     clib_unix_warning ("mutexattr_destroy");
498
499   if (pthread_condattr_init (&cattr))
500     clib_unix_warning ("condattr_init");
501
502   if (pthread_condattr_setpshared (&cattr, PTHREAD_PROCESS_SHARED))
503     clib_unix_warning ("condattr_setpshared");
504
505   if (pthread_cond_init (&rp->condvar, &cattr))
506     clib_unix_warning ("cond_init");
507
508   if (pthread_condattr_destroy (&cattr))
509     clib_unix_warning ("condattr_destroy");
510
511   region_lock (rp, 1);
512
513   rp->virtual_base = a->baseva;
514   rp->virtual_size = a->size;
515
516   rp->region_heap =
517     mheap_alloc_with_flags (uword_to_pointer
518                             (a->baseva + MMAP_PAGESIZE, void *),
519                             (a->pvt_heap_size !=
520                              0) ? a->pvt_heap_size : SVM_PVT_MHEAP_SIZE,
521                             MHEAP_FLAG_DISABLE_VM);
522   oldheap = svm_push_pvt_heap (rp);
523
524   rp->region_name = (char *) format (0, "%s%c", a->name, 0);
525   vec_add1 (rp->client_pids, getpid ());
526
527   nbits = rp->virtual_size / MMAP_PAGESIZE;
528
529   ASSERT (nbits > 0);
530   rp->bitmap_size = nbits;
531   words = (nbits + BITS (uword) - 1) / BITS (uword);
532   vec_validate (rp->bitmap, words - 1);
533
534   overhead_space = MMAP_PAGESIZE /* header */  +
535     ((a->pvt_heap_size != 0) ? a->pvt_heap_size : SVM_PVT_MHEAP_SIZE);
536
537   bit = 0;
538   data_base = (uword) rp->virtual_base;
539
540   if (a->flags & SVM_FLAGS_NODATA)
541     rp->flags |= SVM_FLAGS_NEED_DATA_INIT;
542
543   do
544     {
545       clib_bitmap_set_no_check (rp->bitmap, bit, 1);
546       bit++;
547       overhead_space -= MMAP_PAGESIZE;
548       data_base += MMAP_PAGESIZE;
549     }
550   while (overhead_space > 0);
551
552   rp->data_base = (void *) data_base;
553
554   /*
555    * Note: although the POSIX spec guarantees that only one
556    * process enters this block, we have to play games
557    * to hold off clients until e.g. the mutex is ready
558    */
559   rp->version = SVM_VERSION;
560
561   /* setup the data portion of the region */
562
563   rv = svm_data_region_create (a, rp);
564   if (rv)
565     {
566       clib_warning ("data_region_create: %d", rv);
567     }
568
569   region_unlock (rp);
570
571   svm_pop_heap (oldheap);
572 }
573
574 /*
575  * svm_map_region
576  */
577 void *
578 svm_map_region (svm_map_region_args_t * a)
579 {
580   int svm_fd;
581   svm_region_t *rp;
582   int deadman = 0;
583   u8 junk = 0;
584   void *oldheap;
585   int rv;
586   int pid_holding_region_lock;
587   u8 *shm_name;
588   int dead_region_recovery = 0;
589   int time_left;
590   struct stat stat;
591   struct timespec ts, tsrem;
592
593   ASSERT ((a->size & ~(MMAP_PAGESIZE - 1)) == a->size);
594   ASSERT (a->name);
595
596   shm_name = shm_name_from_svm_map_region_args (a);
597
598   if (CLIB_DEBUG > 1)
599     clib_warning ("[%d] map region %s: shm_open (%s)",
600                   getpid (), a->name, shm_name);
601
602   svm_fd = shm_open ((char *) shm_name, O_RDWR | O_CREAT | O_EXCL, 0777);
603
604   if (svm_fd >= 0)
605     {
606       if (fchmod (svm_fd, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) < 0)
607         clib_unix_warning ("segment chmod");
608       /* This turns out to fail harmlessly if the client starts first */
609       if (fchown (svm_fd, a->uid, a->gid) < 0)
610         clib_unix_warning ("segment chown [ok if client starts first]");
611
612       vec_free (shm_name);
613
614       if (lseek (svm_fd, a->size, SEEK_SET) == (off_t) - 1)
615         {
616           clib_warning ("seek region size");
617           close (svm_fd);
618           return (0);
619         }
620       if (write (svm_fd, &junk, 1) != 1)
621         {
622           clib_warning ("set region size");
623           close (svm_fd);
624           return (0);
625         }
626
627       rp = mmap (uword_to_pointer (a->baseva, void *), a->size,
628                  PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, svm_fd, 0);
629
630       if (rp == (svm_region_t *) MAP_FAILED)
631         {
632           clib_unix_warning ("mmap create");
633           close (svm_fd);
634           return (0);
635         }
636       close (svm_fd);
637
638       svm_region_init_mapped_region (a, rp);
639
640       return ((void *) rp);
641     }
642   else
643     {
644       svm_fd = shm_open ((char *) shm_name, O_RDWR, 0777);
645
646       vec_free (shm_name);
647
648       if (svm_fd < 0)
649         {
650           perror ("svm_region_map(mmap open)");
651           return (0);
652         }
653
654       time_left = 20;
655       while (1)
656         {
657           if (0 != fstat (svm_fd, &stat))
658             {
659               clib_warning ("fstat failed: %d", errno);
660               close (svm_fd);
661               return (0);
662             }
663           if (stat.st_size > 0)
664             {
665               break;
666             }
667           if (0 == time_left)
668             {
669               clib_warning ("waiting for resize of shm file timed out");
670               close (svm_fd);
671               return (0);
672             }
673           ts.tv_sec = 0;
674           ts.tv_nsec = 100000000;
675           while (nanosleep (&ts, &tsrem) < 0)
676             ts = tsrem;
677           time_left--;
678         }
679
680       rp = mmap (0, MMAP_PAGESIZE,
681                  PROT_READ | PROT_WRITE, MAP_SHARED, svm_fd, 0);
682
683       if (rp == (svm_region_t *) MAP_FAILED)
684         {
685           close (svm_fd);
686           clib_warning ("mmap");
687           return (0);
688         }
689       /*
690        * We lost the footrace to create this region; make sure
691        * the winner has crossed the finish line.
692        */
693       while (rp->version == 0 && deadman++ < 5)
694         {
695           sleep (1);
696         }
697
698       /*
699        * <bleep>-ed?
700        */
701       if (rp->version == 0)
702         {
703           clib_warning ("rp->version %d not %d", rp->version, SVM_VERSION);
704           close (svm_fd);
705           munmap (rp, a->size);
706           return (0);
707         }
708       /* Remap now that the region has been placed */
709       a->baseva = rp->virtual_base;
710       a->size = rp->virtual_size;
711       munmap (rp, MMAP_PAGESIZE);
712
713       rp = (void *) mmap (uword_to_pointer (a->baseva, void *), a->size,
714                           PROT_READ | PROT_WRITE,
715                           MAP_SHARED | MAP_FIXED, svm_fd, 0);
716       if ((uword) rp == (uword) MAP_FAILED)
717         {
718           clib_unix_warning ("mmap");
719           close (svm_fd);
720           return (0);
721         }
722
723       if ((uword) rp != rp->virtual_base)
724         {
725           clib_warning ("mmap botch");
726         }
727
728       /*
729        * Try to fix the region mutex if it is held by
730        * a dead process
731        */
732       pid_holding_region_lock = rp->mutex_owner_pid;
733       if (pid_holding_region_lock && kill (pid_holding_region_lock, 0) < 0)
734         {
735           clib_warning
736             ("region %s mutex held by dead pid %d, tag %d, force unlock",
737              rp->region_name, pid_holding_region_lock, rp->mutex_owner_tag);
738           /* owner pid is nonexistent */
739           rp->mutex.__data.__owner = 0;
740           rp->mutex.__data.__lock = 0;
741           dead_region_recovery = 1;
742         }
743
744       if (dead_region_recovery)
745         clib_warning ("recovery: attempt to re-lock region");
746
747       region_lock (rp, 2);
748       oldheap = svm_push_pvt_heap (rp);
749       vec_add1 (rp->client_pids, getpid ());
750
751       if (dead_region_recovery)
752         clib_warning ("recovery: attempt svm_data_region_map");
753
754       rv = svm_data_region_map (a, rp);
755       if (rv)
756         {
757           clib_warning ("data_region_map: %d", rv);
758         }
759
760       if (dead_region_recovery)
761         clib_warning ("unlock and continue");
762
763       region_unlock (rp);
764
765       svm_pop_heap (oldheap);
766
767       return ((void *) rp);
768
769     }
770   return 0;                     /* NOTREACHED */
771 }
772
773 static void
774 svm_mutex_cleanup (void)
775 {
776   int i;
777   for (i = 0; i < nheld; i++)
778     {
779       pthread_mutex_unlock (mutexes_held[i]);
780     }
781 }
782
783 static int
784 svm_region_init_internal (svm_map_region_args_t * a)
785 {
786   svm_region_t *rp;
787   u64 ticks = clib_cpu_time_now ();
788   uword randomize_baseva;
789
790   /* guard against klutz calls */
791   if (root_rp)
792     return -1;
793
794   root_rp_refcount++;
795
796   atexit (svm_mutex_cleanup);
797
798   /* Randomize the shared-VM base at init time */
799   if (MMAP_PAGESIZE <= (4 << 10))
800     randomize_baseva = (ticks & 15) * MMAP_PAGESIZE;
801   else
802     randomize_baseva = (ticks & 3) * MMAP_PAGESIZE;
803
804   a->baseva += randomize_baseva;
805
806   rp = svm_map_region (a);
807   if (!rp)
808     return -1;
809
810   region_lock (rp, 3);
811
812   /* Set up the main region data structures */
813   if (rp->flags & SVM_FLAGS_NEED_DATA_INIT)
814     {
815       svm_main_region_t *mp = 0;
816       void *oldheap;
817
818       rp->flags &= ~(SVM_FLAGS_NEED_DATA_INIT);
819
820       oldheap = svm_push_pvt_heap (rp);
821       vec_validate (mp, 0);
822       mp->name_hash = hash_create_string (0, sizeof (uword));
823       mp->root_path = a->root_path ? format (0, "%s%c", a->root_path, 0) : 0;
824       mp->uid = a->uid;
825       mp->gid = a->gid;
826       rp->data_base = mp;
827       svm_pop_heap (oldheap);
828     }
829   region_unlock (rp);
830   root_rp = rp;
831
832   return 0;
833 }
834
835 void
836 svm_region_init (void)
837 {
838   svm_map_region_args_t _a, *a = &_a;
839
840   memset (a, 0, sizeof (*a));
841   a->root_path = 0;
842   a->name = SVM_GLOBAL_REGION_NAME;
843   a->baseva = svm_get_global_region_base_va ();
844   a->size = SVM_GLOBAL_REGION_SIZE;
845   a->flags = SVM_FLAGS_NODATA;
846   a->uid = 0;
847   a->gid = 0;
848
849   svm_region_init_internal (a);
850 }
851
852 int
853 svm_region_init_chroot (const char *root_path)
854 {
855   svm_map_region_args_t _a, *a = &_a;
856
857   memset (a, 0, sizeof (*a));
858   a->root_path = root_path;
859   a->name = SVM_GLOBAL_REGION_NAME;
860   a->baseva = svm_get_global_region_base_va ();
861   a->size = SVM_GLOBAL_REGION_SIZE;
862   a->flags = SVM_FLAGS_NODATA;
863   a->uid = 0;
864   a->gid = 0;
865
866   return svm_region_init_internal (a);
867 }
868
869 void
870 svm_region_init_chroot_uid_gid (const char *root_path, int uid, int gid)
871 {
872   svm_map_region_args_t _a, *a = &_a;
873
874   memset (a, 0, sizeof (*a));
875   a->root_path = root_path;
876   a->name = SVM_GLOBAL_REGION_NAME;
877   a->baseva = svm_get_global_region_base_va ();
878   a->size = SVM_GLOBAL_REGION_SIZE;
879   a->flags = SVM_FLAGS_NODATA;
880   a->uid = uid;
881   a->gid = gid;
882
883   svm_region_init_internal (a);
884 }
885
886 void
887 svm_region_init_args (svm_map_region_args_t * a)
888 {
889   svm_region_init_internal (a);
890 }
891
892 void *
893 svm_region_find_or_create (svm_map_region_args_t * a)
894 {
895   svm_main_region_t *mp;
896   svm_region_t *rp;
897   uword need_nbits;
898   int index, i;
899   void *oldheap;
900   uword *p;
901   u8 *name;
902   svm_subregion_t *subp;
903
904   ASSERT (root_rp);
905
906   a->size += MMAP_PAGESIZE +
907     ((a->pvt_heap_size != 0) ? a->pvt_heap_size : SVM_PVT_MHEAP_SIZE);
908   a->size = rnd_pagesize (a->size);
909
910   region_lock (root_rp, 4);
911   oldheap = svm_push_pvt_heap (root_rp);
912   mp = root_rp->data_base;
913
914   ASSERT (mp);
915
916   /* Map the named region from the correct chroot environment */
917   if (a->root_path == NULL)
918     a->root_path = (char *) mp->root_path;
919
920   /*
921    * See if this region is already known. If it is, we're
922    * almost done...
923    */
924   p = hash_get_mem (mp->name_hash, a->name);
925
926   if (p)
927     {
928       rp = svm_map_region (a);
929       region_unlock (root_rp);
930       svm_pop_heap (oldheap);
931       return rp;
932     }
933
934   /* Create the region. */
935   ASSERT ((a->size & ~(MMAP_PAGESIZE - 1)) == a->size);
936
937   need_nbits = a->size / MMAP_PAGESIZE;
938
939   index = 1;                    /* $$$ fixme, figure out how many bit to really skip */
940
941   /*
942    * Scan the virtual space allocation bitmap, looking for a large
943    * enough chunk
944    */
945   do
946     {
947       if (clib_bitmap_get_no_check (root_rp->bitmap, index) == 0)
948         {
949           for (i = 0; i < (need_nbits - 1); i++)
950             {
951               if (clib_bitmap_get_no_check (root_rp->bitmap, index + i) == 1)
952                 {
953                   index = index + i;
954                   goto next;
955                 }
956             }
957           break;
958         }
959       index++;
960     next:;
961     }
962   while (index < root_rp->bitmap_size);
963
964   /* Completely out of VM? */
965   if (index >= root_rp->bitmap_size)
966     {
967       clib_warning ("region %s: not enough VM to allocate 0x%llx (%lld)",
968                     root_rp->region_name, a->size, a->size);
969       svm_pop_heap (oldheap);
970       region_unlock (root_rp);
971       return 0;
972     }
973
974   /*
975    * Mark virtual space allocated
976    */
977 #if CLIB_DEBUG > 1
978   clib_warning ("set %d bits at index %d", need_nbits, index);
979 #endif
980
981   for (i = 0; i < need_nbits; i++)
982     {
983       clib_bitmap_set_no_check (root_rp->bitmap, index + i, 1);
984     }
985
986   /* Place this region where it goes... */
987   a->baseva = root_rp->virtual_base + index * MMAP_PAGESIZE;
988
989   rp = svm_map_region (a);
990
991   pool_get (mp->subregions, subp);
992   name = format (0, "%s%c", a->name, 0);
993   subp->subregion_name = name;
994
995   hash_set_mem (mp->name_hash, name, subp - mp->subregions);
996
997   svm_pop_heap (oldheap);
998
999   region_unlock (root_rp);
1000
1001   return (rp);
1002 }
1003
1004 void
1005 svm_region_unlink (svm_region_t * rp)
1006 {
1007   svm_map_region_args_t _a, *a = &_a;
1008   svm_main_region_t *mp;
1009   u8 *shm_name;
1010
1011   ASSERT (root_rp);
1012   ASSERT (rp);
1013   ASSERT (vec_c_string_is_terminated (rp->region_name));
1014
1015   mp = root_rp->data_base;
1016   ASSERT (mp);
1017
1018   a->root_path = (char *) mp->root_path;
1019   a->name = rp->region_name;
1020   shm_name = shm_name_from_svm_map_region_args (a);
1021   if (CLIB_DEBUG > 1)
1022     clib_warning ("[%d] shm_unlink (%s)", getpid (), shm_name);
1023   shm_unlink ((const char *) shm_name);
1024   vec_free (shm_name);
1025 }
1026
1027 /*
1028  * svm_region_unmap
1029  *
1030  * Let go of the indicated region. If the calling process
1031  * is the last customer, throw it away completely.
1032  * The root region mutex guarantees atomicity with respect to
1033  * a new region client showing up at the wrong moment.
1034  */
1035 void
1036 svm_region_unmap (void *rp_arg)
1037 {
1038   int i, mypid = getpid ();
1039   int nclients_left;
1040   void *oldheap;
1041   uword virtual_base, virtual_size;
1042   svm_region_t *rp = rp_arg;
1043   char *name;
1044
1045   /*
1046    * If we take a signal while holding one or more shared-memory
1047    * mutexes, we may end up back here from an otherwise
1048    * benign exit handler. Bail out to avoid a recursive
1049    * mutex screw-up.
1050    */
1051   if (nheld)
1052     return;
1053
1054   ASSERT (rp);
1055   ASSERT (root_rp);
1056
1057   if (CLIB_DEBUG > 1)
1058     clib_warning ("[%d] unmap region %s", getpid (), rp->region_name);
1059
1060   region_lock (root_rp, 5);
1061   region_lock (rp, 6);
1062
1063   oldheap = svm_push_pvt_heap (rp);     /* nb vec_delete() in the loop */
1064
1065   /* Remove the caller from the list of mappers */
1066   for (i = 0; i < vec_len (rp->client_pids); i++)
1067     {
1068       if (rp->client_pids[i] == mypid)
1069         {
1070           vec_delete (rp->client_pids, 1, i);
1071           goto found;
1072         }
1073     }
1074   clib_warning ("pid %d AWOL", mypid);
1075
1076 found:
1077
1078   svm_pop_heap (oldheap);
1079
1080   nclients_left = vec_len (rp->client_pids);
1081   virtual_base = rp->virtual_base;
1082   virtual_size = rp->virtual_size;
1083
1084   if (nclients_left == 0)
1085     {
1086       int index, nbits, i;
1087       svm_main_region_t *mp;
1088       uword *p;
1089       svm_subregion_t *subp;
1090
1091       /* Kill the region, last guy on his way out */
1092
1093       oldheap = svm_push_pvt_heap (root_rp);
1094       name = vec_dup (rp->region_name);
1095
1096       virtual_base = rp->virtual_base;
1097       virtual_size = rp->virtual_size;
1098
1099       /* Figure out which bits to clear in the root region bitmap */
1100       index = (virtual_base - root_rp->virtual_base) / MMAP_PAGESIZE;
1101
1102       nbits = (virtual_size + MMAP_PAGESIZE - 1) / MMAP_PAGESIZE;
1103
1104 #if CLIB_DEBUG > 1
1105       clib_warning ("clear %d bits at index %d", nbits, index);
1106 #endif
1107       /* Give back the allocated VM */
1108       for (i = 0; i < nbits; i++)
1109         {
1110           clib_bitmap_set_no_check (root_rp->bitmap, index + i, 0);
1111         }
1112
1113       mp = root_rp->data_base;
1114
1115       p = hash_get_mem (mp->name_hash, name);
1116
1117       /* Better never happen ... */
1118       if (p == NULL)
1119         {
1120           region_unlock (rp);
1121           region_unlock (root_rp);
1122           svm_pop_heap (oldheap);
1123           clib_warning ("Region name '%s' not found?", name);
1124           return;
1125         }
1126
1127       /* Remove from the root region subregion pool */
1128       subp = mp->subregions + p[0];
1129       pool_put (mp->subregions, subp);
1130
1131       hash_unset_mem (mp->name_hash, name);
1132
1133       vec_free (name);
1134
1135       region_unlock (rp);
1136       svm_region_unlink (rp);
1137       munmap ((void *) virtual_base, virtual_size);
1138       region_unlock (root_rp);
1139       svm_pop_heap (oldheap);
1140       return;
1141     }
1142
1143   region_unlock (rp);
1144   region_unlock (root_rp);
1145
1146   munmap ((void *) virtual_base, virtual_size);
1147 }
1148
1149 /*
1150  * svm_region_exit
1151  */
1152 void
1153 svm_region_exit ()
1154 {
1155   void *oldheap;
1156   int i, mypid = getpid ();
1157   uword virtual_base, virtual_size;
1158
1159   /* It felt so nice we did it twice... */
1160   if (root_rp == 0)
1161     return;
1162
1163   if (--root_rp_refcount > 0)
1164     return;
1165
1166   /*
1167    * If we take a signal while holding one or more shared-memory
1168    * mutexes, we may end up back here from an otherwise
1169    * benign exit handler. Bail out to avoid a recursive
1170    * mutex screw-up.
1171    */
1172   if (nheld)
1173     return;
1174
1175   region_lock (root_rp, 7);
1176   oldheap = svm_push_pvt_heap (root_rp);
1177
1178   virtual_base = root_rp->virtual_base;
1179   virtual_size = root_rp->virtual_size;
1180
1181   for (i = 0; i < vec_len (root_rp->client_pids); i++)
1182     {
1183       if (root_rp->client_pids[i] == mypid)
1184         {
1185           vec_delete (root_rp->client_pids, 1, i);
1186           goto found;
1187         }
1188     }
1189   clib_warning ("pid %d AWOL", mypid);
1190
1191 found:
1192
1193   if (vec_len (root_rp->client_pids) == 0)
1194     svm_region_unlink (root_rp);
1195
1196   region_unlock (root_rp);
1197   svm_pop_heap (oldheap);
1198
1199   root_rp = 0;
1200   munmap ((void *) virtual_base, virtual_size);
1201 }
1202
1203 void
1204 svm_client_scan_this_region_nolock (svm_region_t * rp)
1205 {
1206   int j;
1207   int mypid = getpid ();
1208   void *oldheap;
1209
1210   for (j = 0; j < vec_len (rp->client_pids); j++)
1211     {
1212       if (mypid == rp->client_pids[j])
1213         continue;
1214       if (rp->client_pids[j] && (kill (rp->client_pids[j], 0) < 0))
1215         {
1216           clib_warning ("%s: cleanup ghost pid %d",
1217                         rp->region_name, rp->client_pids[j]);
1218           /* nb: client vec in rp->region_heap */
1219           oldheap = svm_push_pvt_heap (rp);
1220           vec_delete (rp->client_pids, 1, j);
1221           j--;
1222           svm_pop_heap (oldheap);
1223         }
1224     }
1225 }
1226
1227
1228 /*
1229  * Scan svm regions for dead clients
1230  */
1231 void
1232 svm_client_scan (const char *root_path)
1233 {
1234   int i, j;
1235   svm_main_region_t *mp;
1236   svm_map_region_args_t *a = 0;
1237   svm_region_t *root_rp;
1238   svm_region_t *rp;
1239   svm_subregion_t *subp;
1240   u8 *name = 0;
1241   u8 **svm_names = 0;
1242   void *oldheap;
1243   int mypid = getpid ();
1244
1245   vec_validate (a, 0);
1246
1247   svm_region_init_chroot (root_path);
1248
1249   root_rp = svm_get_root_rp ();
1250
1251   pthread_mutex_lock (&root_rp->mutex);
1252
1253   mp = root_rp->data_base;
1254
1255   for (j = 0; j < vec_len (root_rp->client_pids); j++)
1256     {
1257       if (mypid == root_rp->client_pids[j])
1258         continue;
1259       if (root_rp->client_pids[j] && (kill (root_rp->client_pids[j], 0) < 0))
1260         {
1261           clib_warning ("%s: cleanup ghost pid %d",
1262                         root_rp->region_name, root_rp->client_pids[j]);
1263           /* nb: client vec in root_rp->region_heap */
1264           oldheap = svm_push_pvt_heap (root_rp);
1265           vec_delete (root_rp->client_pids, 1, j);
1266           j--;
1267           svm_pop_heap (oldheap);
1268         }
1269     }
1270
1271   /*
1272    * Snapshoot names, can't hold root rp mutex across
1273    * find_or_create.
1274    */
1275   /* *INDENT-OFF* */
1276   pool_foreach (subp, mp->subregions, ({
1277         name = vec_dup (subp->subregion_name);
1278         vec_add1(svm_names, name);
1279       }));
1280   /* *INDENT-ON* */
1281
1282   pthread_mutex_unlock (&root_rp->mutex);
1283
1284   for (i = 0; i < vec_len (svm_names); i++)
1285     {
1286       vec_validate (a, 0);
1287       a->root_path = root_path;
1288       a->name = (char *) svm_names[i];
1289       rp = svm_region_find_or_create (a);
1290       if (rp)
1291         {
1292           pthread_mutex_lock (&rp->mutex);
1293
1294           svm_client_scan_this_region_nolock (rp);
1295
1296           pthread_mutex_unlock (&rp->mutex);
1297           svm_region_unmap (rp);
1298           vec_free (svm_names[i]);
1299         }
1300       vec_free (a);
1301     }
1302   vec_free (svm_names);
1303
1304   svm_region_exit ();
1305
1306   vec_free (a);
1307 }
1308
1309 /*
1310  * fd.io coding-style-patch-verification: ON
1311  *
1312  * Local Variables:
1313  * eval: (c-set-style "gnu")
1314  * End:
1315  */