2 * shared.c: Shared memory handling, and daemon launching
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2006 Novell, Inc.
15 #include <sys/types.h>
21 #if defined(HAVE_SYS_SEM_H) && !(defined(__native_client__) && defined(__GLIBC__))
24 # define DISABLE_SHARED_HANDLES
27 #ifndef DISABLE_SHARED_HANDLES
28 # include <sys/mman.h>
30 # ifdef HAVE_SYS_UTSNAME_H
31 # include <sys/utsname.h>
35 #include <mono/io-layer/wapi.h>
36 #include <mono/io-layer/wapi-private.h>
37 #include <mono/io-layer/shared.h>
38 #include <mono/io-layer/handles-private.h>
41 //#define DEBUGLOG(...) g_message(__VA_ARGS__);
43 // Semaphores used when no-shared-memory use is in use
45 static mono_mutex_t noshm_sems[_WAPI_SHARED_SEM_COUNT];
47 gboolean _wapi_shm_disabled = TRUE;
49 static gpointer wapi_storage [16];
52 noshm_semaphores_init (void)
56 for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++)
57 mono_mutex_init (&noshm_sems [i]);
61 noshm_sem_lock (int sem)
65 DEBUGLOG ("%s: locking nosem %d", __func__, sem);
67 ret = mono_mutex_lock (&noshm_sems[sem]);
73 noshm_sem_trylock (int sem)
77 DEBUGLOG ("%s: trying to lock nosem %d", __func__, sem);
79 ret = mono_mutex_trylock (&noshm_sems[sem]);
85 noshm_sem_unlock (int sem)
89 DEBUGLOG ("%s: unlocking nosem %d", __func__, sem);
91 ret = mono_mutex_unlock (&noshm_sems[sem]);
96 #ifdef DISABLE_SHARED_HANDLES
98 _wapi_shm_semaphores_init (void)
100 noshm_semaphores_init ();
104 _wapi_shm_semaphores_remove (void)
110 _wapi_shm_sem_lock (int sem)
112 return noshm_sem_lock (sem);
116 _wapi_shm_sem_trylock (int sem)
118 return noshm_sem_trylock (sem);
122 _wapi_shm_sem_unlock (int sem)
124 return noshm_sem_unlock (sem);
128 _wapi_shm_attach (_wapi_shm_t type)
134 res = g_malloc0 (sizeof(struct _WapiHandleSharedLayout));
136 case WAPI_SHM_FILESHARE:
137 res = g_malloc0 (sizeof(struct _WapiFileShareLayout));
140 g_error ("Invalid type in _wapi_shm_attach ()");
144 wapi_storage [type] = res;
149 _wapi_shm_detach (_wapi_shm_t type)
151 g_free (wapi_storage [type]);
155 _wapi_shm_enabled (void)
162 * Use POSIX shared memory if possible, it is simpler, and it has the advantage that
163 * writes to the shared area does not need to be written to disk, avoiding spinning up
164 * the disk every x secs on laptops.
171 _wapi_shm_base_name (_wapi_shm_t type)
174 gchar machine_name[256];
175 const gchar *fake_name;
182 ubuf.machine[0] = '\0';
183 ubuf.sysname[0] = '\0';
185 g_strdelimit (ubuf.sysname, "/", '_');
186 g_strdelimit (ubuf.machine, "/", '_');
189 fake_name = g_getenv ("MONO_SHARED_HOSTNAME");
190 if (fake_name == NULL) {
191 if (gethostname(machine_name, sizeof(machine_name)) != 0)
192 machine_name[0] = '\0';
194 len = MIN (strlen (fake_name), sizeof (machine_name) - 1);
195 strncpy (machine_name, fake_name, len);
196 machine_name [len] = '\0';
201 name = g_strdup_printf ("shared_data-%s-%s-%s-%d-%d-%d",
202 machine_name, ubuf.sysname,
204 (int) sizeof(struct _WapiHandleShared),
205 _WAPI_HANDLE_VERSION, 0);
208 case WAPI_SHM_FILESHARE:
209 name = g_strdup_printf ("shared_fileshare-%s-%s-%s-%d-%d-%d",
210 machine_name, ubuf.sysname,
212 (int) sizeof(struct _WapiFileShare),
213 _WAPI_HANDLE_VERSION, 0);
222 static gchar *_wapi_shm_shm_name (_wapi_shm_t type)
224 char *base_name = _wapi_shm_base_name (type);
226 /* Also add the uid to avoid permission problems */
227 char *res = g_strdup_printf ("/mono-shared-%d-%s", getuid (), base_name);
235 _wapi_shm_open (const char *filename, int size)
239 fd = shm_open (filename, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP);
241 /* Maybe /dev/shm is not mounted */
243 if (ftruncate (fd, size) != 0) {
244 perror ("_wapi_shm_open (): ftruncate ()");
245 g_assert_not_reached ();
254 _wapi_shm_file (_wapi_shm_t type)
256 static gchar file[_POSIX_PATH_MAX];
257 gchar *name = NULL, *filename;
258 const gchar *wapi_dir;
260 name = _wapi_shm_base_name (type);
262 /* I don't know how nfs affects mmap. If mmap() of files on
263 * nfs mounts breaks, then there should be an option to set
266 wapi_dir = g_getenv ("MONO_SHARED_DIR");
267 if (wapi_dir == NULL) {
268 filename = g_build_filename (g_get_home_dir (), ".wapi", name,
271 filename = g_build_filename (wapi_dir, ".wapi", name, NULL);
275 g_snprintf (file, _POSIX_PATH_MAX, "%s", filename);
282 _wapi_shm_file_open (const gchar *filename, guint32 wanted_size)
287 gboolean created = FALSE;
291 /* No need to check if the dir already exists or check
292 * mkdir() errors, because on any error the open() call will
293 * report the problem.
295 dir = g_path_get_dirname (filename);
303 } else if (tries > 5) {
304 /* Break out of a loop */
308 /* Make sure future processes can open the shared data files */
309 oldmask = umask (066);
311 /* No O_CREAT yet, because we need to initialise the file if
312 * we have to create it.
314 fd = open (filename, O_RDWR, 0600);
317 if (fd == -1 && errno == ENOENT) {
318 /* OK, its up to us to create it. O_EXCL to avoid a
319 * race condition where two processes can
320 * simultaneously try and create the file
322 oldmask = umask (066);
323 fd = open (filename, O_CREAT|O_EXCL|O_RDWR, 0600);
326 if (fd == -1 && errno == EEXIST) {
327 /* It's possible that the file was created in
328 * between finding it didn't exist, and trying
329 * to create it. Just try opening it again
332 } else if (fd == -1) {
333 g_critical ("%s: shared file [%s] open error: %s",
334 __func__, filename, g_strerror (errno));
337 /* We created the file, so we need to expand
340 * (wanted_size-1, because we're about to
341 * write the other byte to actually expand the
344 if (lseek (fd, wanted_size-1, SEEK_SET) == -1) {
345 g_critical ("%s: shared file [%s] lseek error: %s", __func__, filename, g_strerror (errno));
352 ret = write (fd, "", 1);
353 } while (ret == -1 && errno == EINTR);
356 g_critical ("%s: shared file [%s] write error: %s", __func__, filename, g_strerror (errno));
364 /* The contents of the file is set to all
365 * zero, because it is opened up with lseek,
366 * so we don't need to do any more
367 * initialisation here
370 } else if (fd == -1) {
371 g_critical ("%s: shared file [%s] open error: %s", __func__,
372 filename, g_strerror (errno));
376 /* Use stat to find the file size (instead of hard coding it)
377 * because we can expand the file later if needed (for more
378 * handles or scratch space.)
380 if (fstat (fd, &statbuf) == -1) {
381 g_critical ("%s: fstat error: %s", __func__,
383 if (created == TRUE) {
390 if (statbuf.st_size < wanted_size) {
392 if (created == TRUE) {
393 g_critical ("%s: shared file [%s] is not big enough! (found %ld, need %d bytes)", __func__, filename, (long)statbuf.st_size, wanted_size);
397 /* We didn't create it, so just try opening it again */
398 _wapi_handle_spin (100);
407 _wapi_shm_enabled (void)
409 static gboolean env_checked;
412 if (g_getenv ("MONO_ENABLE_SHM"))
413 _wapi_shm_disabled = FALSE;
417 return !_wapi_shm_disabled;
422 * @success: Was it a success
424 * Attach to the shared memory file or create it if it did not exist.
425 * Returns the memory area the file was mmapped to.
428 _wapi_shm_attach (_wapi_shm_t type)
433 gchar *filename = _wapi_shm_file (type), *shm_name;
438 size = sizeof(struct _WapiHandleSharedLayout);
441 case WAPI_SHM_FILESHARE:
442 size = sizeof(struct _WapiFileShareLayout);
445 g_error ("Invalid type in _wapi_shm_attach ()");
449 if (!_wapi_shm_enabled ()) {
450 wapi_storage [type] = g_malloc0 (size);
451 return wapi_storage [type];
455 shm_name = _wapi_shm_shm_name (type);
456 fd = _wapi_shm_open (shm_name, size);
462 /* Fall back to files if POSIX shm fails (for example, because /dev/shm is not mounted */
464 fd = _wapi_shm_file_open (filename, size);
466 g_critical ("%s: shared file [%s] open error", __func__,
471 if (fstat (fd, &statbuf)==-1) {
472 g_critical ("%s: fstat error: %s", __func__,
478 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
480 if (shm_seg == MAP_FAILED) {
481 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
483 if (shm_seg == MAP_FAILED) {
484 g_critical ("%s: mmap error: %s", __func__, g_strerror (errno));
495 _wapi_shm_detach (_wapi_shm_t type)
497 if (!_wapi_shm_enabled ())
498 g_free (wapi_storage [type]);
502 shm_semaphores_init (void)
507 struct _WapiHandleSharedLayout *tmp_shared;
512 * Yet more barmy API - this union is a well-defined parameter
513 * in a syscall, yet I still have to define it here as it
514 * doesn't appear in a header
518 struct semid_ds *buf;
521 ushort def_vals[_WAPI_SHARED_SEM_COUNT];
525 for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++) {
530 * Process count must start at '0' - the 1 for all the others
531 * sets the semaphore to "unlocked"
533 def_vals[_WAPI_SHARED_SEM_PROCESS_COUNT] = 0;
535 defs.array = def_vals;
538 *Temporarily attach the shared data so we can read the
539 * semaphore key. We release this mapping and attach again
540 * after getting the semaphores to avoid a race condition
541 * where a terminating process can delete the shared files
542 * between a new process attaching the file and getting access
543 * to the semaphores (which increments the process count,
544 * preventing destruction of the shared data...)
546 tmp_shared = _wapi_shm_attach (WAPI_SHM_DATA);
547 g_assert (tmp_shared != NULL);
550 ftmp=_wapi_shm_shm_name (WAPI_SHM_DATA);
551 filename = g_build_filename ("/dev/shm", ftmp, NULL);
552 g_assert (filename!=NULL);
553 key = ftok (filename, 'M');
557 key = ftok ( _wapi_shm_file (WAPI_SHM_DATA), 'M');
562 oldkey = tmp_shared->sem_key;
565 DEBUGLOG ("%s: Creating with new key (0x%x)", __func__, key);
568 * The while loop attempts to make some sense of the
569 * bonkers 'think of a random number' method of
570 * picking a key without collision with other
573 while ((_wapi_sem_id = semget (key, _WAPI_SHARED_SEM_COUNT,
574 IPC_CREAT | IPC_EXCL | 0600)) == -1) {
575 if (errno == ENOMEM) {
576 g_error ("%s: semget error: %s", __func__,
578 } else if (errno == ENOSPC) {
579 g_error ("%s: semget error: %s. Try deleting some semaphores with ipcs and ipcrm\nor increase the maximum number of semaphore in the system.", __func__, g_strerror (errno));
580 } else if (errno != EEXIST) {
582 g_warning ("%s: semget error: %s key 0x%x - trying again", __func__,
583 g_strerror (errno), key);
587 DEBUGLOG ("%s: Got (%s), trying with new key (0x%x)", __func__, g_strerror (errno), key);
590 * Got a semaphore array, so initialise it and install
591 * the key into the shared memory
594 if (semctl (_wapi_sem_id, 0, SETALL, defs) == -1) {
596 g_warning ("%s: semctl init error: %s - trying again", __func__, g_strerror (errno));
599 * Something went horribly wrong, so try
600 * getting a new set from scratch
602 semctl (_wapi_sem_id, 0, IPC_RMID);
606 if (InterlockedCompareExchange (&tmp_shared->sem_key,
609 * Someone else created one and installed the
610 * key while we were working, so delete the
611 * array we created and fall through to the
612 * 'key already known' case.
614 semctl (_wapi_sem_id, 0, IPC_RMID);
615 oldkey = tmp_shared->sem_key;
618 * We've installed this semaphore set's key into
625 DEBUGLOG ("%s: Trying with old key 0x%x", __func__, oldkey);
627 _wapi_sem_id = semget (oldkey, _WAPI_SHARED_SEM_COUNT, 0600);
628 if (_wapi_sem_id == -1) {
630 g_warning ("%s: semget error opening old key 0x%x (%s) - trying again",
631 __func__, oldkey,g_strerror (errno));
634 * Someone must have deleted the semaphore set, so
635 * blow away the bad key and try again
637 InterlockedCompareExchange (&tmp_shared->sem_key, 0, oldkey);
643 /* Increment the usage count of this semaphore set */
644 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
645 g_assert (thr_ret == 0);
647 DEBUGLOG ("%s: Incrementing the process count (%d)", __func__, _wapi_getpid ());
650 * We only ever _unlock_ this semaphore, letting the kernel
651 * restore (ie decrement) this unlock when this process exits.
652 * We lock another semaphore around it so we can serialise
653 * access when we're testing the value of this semaphore when
654 * we exit cleanly, so we can delete the whole semaphore set.
656 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT);
658 DEBUGLOG ("%s: Process count is now %d (%d)", __func__, semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT, GETVAL), _wapi_getpid ());
660 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
662 if (_wapi_shm_disabled)
665 munmap (tmp_shared, sizeof(struct _WapiHandleSharedLayout));
669 shm_semaphores_remove (void)
675 DEBUGLOG ("%s: Checking process count (%d)", __func__, _wapi_getpid ());
677 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
678 g_assert (thr_ret == 0);
680 proc_count = semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT,
683 g_assert (proc_count > 0);
684 if (proc_count == 1) {
686 * Just us, so blow away the semaphores and the shared
689 DEBUGLOG ("%s: Removing semaphores! (%d)", __func__, _wapi_getpid ());
691 semctl (_wapi_sem_id, 0, IPC_RMID);
693 shm_name = _wapi_shm_shm_name (WAPI_SHM_DATA);
694 shm_unlink (shm_name);
697 shm_name = _wapi_shm_shm_name (WAPI_SHM_FILESHARE);
698 shm_unlink (shm_name);
701 unlink (_wapi_shm_file (WAPI_SHM_DATA));
702 unlink (_wapi_shm_file (WAPI_SHM_FILESHARE));
705 * "else" clause, because there's no point unlocking
706 * the semaphore if we've just blown it away...
708 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
713 shm_sem_lock (int sem)
718 DEBUGLOG ("%s: locking sem %d", __func__, sem);
722 ops.sem_flg = SEM_UNDO;
726 ret = semop (_wapi_sem_id, &ops, 1);
727 } while (ret == -1 && errno == EINTR);
731 * EINVAL covers the case when the semaphore was
732 * deleted before we started the semop
734 if (errno == EIDRM || errno == EINVAL) {
736 * Someone blew away this semaphore set, so
737 * get a new one and try again
739 DEBUGLOG ("%s: Reinitialising the semaphores!", __func__);
741 _wapi_shm_semaphores_init ();
745 /* Turn this into a pthreads-style return value */
749 DEBUGLOG ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
755 shm_sem_trylock (int sem)
760 DEBUGLOG ("%s: trying to lock sem %d", __func__, sem);
764 ops.sem_flg = IPC_NOWAIT | SEM_UNDO;
768 ret = semop (_wapi_sem_id, &ops, 1);
769 } while (ret == -1 && errno == EINTR);
773 * EINVAL covers the case when the semaphore was
774 * deleted before we started the semop
776 if (errno == EIDRM || errno == EINVAL) {
778 * Someone blew away this semaphore set, so
779 * get a new one and try again
781 DEBUGLOG ("%s: Reinitialising the semaphores!", __func__);
783 _wapi_shm_semaphores_init ();
787 /* Turn this into a pthreads-style return value */
792 /* But pthreads uses this code instead */
796 DEBUGLOG ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
802 shm_sem_unlock (int sem)
807 DEBUGLOG ("%s: unlocking sem %d", __func__, sem);
811 ops.sem_flg = SEM_UNDO;
815 ret = semop (_wapi_sem_id, &ops, 1);
816 } while (ret == -1 && errno == EINTR);
819 /* EINVAL covers the case when the semaphore was
820 * deleted before we started the semop
822 if (errno == EIDRM || errno == EINVAL) {
823 /* Someone blew away this semaphore set, so
824 * get a new one and try again (we can't just
825 * assume that the semaphore is now unlocked)
827 DEBUGLOG ("%s: Reinitialising the semaphores!", __func__);
829 _wapi_shm_semaphores_init ();
833 /* Turn this into a pthreads-style return value */
837 DEBUGLOG ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
843 _wapi_shm_semaphores_init (void)
845 if (!_wapi_shm_enabled ())
846 noshm_semaphores_init ();
848 shm_semaphores_init ();
852 _wapi_shm_semaphores_remove (void)
854 if (!_wapi_shm_disabled)
855 shm_semaphores_remove ();
859 _wapi_shm_sem_lock (int sem)
861 if (_wapi_shm_disabled)
862 return noshm_sem_lock (sem);
864 return shm_sem_lock (sem);
868 _wapi_shm_sem_trylock (int sem)
870 if (_wapi_shm_disabled)
871 return noshm_sem_trylock (sem);
873 return shm_sem_trylock (sem);
877 _wapi_shm_sem_unlock (int sem)
879 if (_wapi_shm_disabled)
880 return noshm_sem_unlock (sem);
882 return shm_sem_unlock (sem);
884 #endif /* !DISABLE_SHARED_HANDLES */