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