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>
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 #ifdef DISABLE_SHARED_HANDLES
48 gboolean _wapi_shm_disabled = TRUE;
50 gboolean _wapi_shm_disabled = FALSE;
54 noshm_semaphores_init (void)
58 for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++)
59 mono_mutex_init (&noshm_sems [i], NULL);
63 noshm_sem_lock (int sem)
67 DEBUGLOG ("%s: locking nosem %d", __func__, sem);
69 ret = mono_mutex_lock (&noshm_sems[sem]);
75 noshm_sem_trylock (int sem)
79 DEBUGLOG ("%s: trying to lock nosem %d", __func__, sem);
81 ret = mono_mutex_trylock (&noshm_sems[sem]);
87 noshm_sem_unlock (int sem)
91 DEBUGLOG ("%s: unlocking nosem %d", __func__, sem);
93 ret = mono_mutex_unlock (&noshm_sems[sem]);
98 #ifdef DISABLE_SHARED_HANDLES
100 _wapi_shm_semaphores_init (void)
102 noshm_semaphores_init ();
106 _wapi_shm_semaphores_remove (void)
112 _wapi_shm_sem_lock (int sem)
114 return noshm_sem_lock (sem);
118 _wapi_shm_sem_trylock (int sem)
120 return noshm_sem_trylock (sem);
124 _wapi_shm_sem_unlock (int sem)
126 return noshm_sem_unlock (sem);
130 _wapi_shm_attach (_wapi_shm_t type)
136 return g_malloc0 (sizeof(struct _WapiHandleSharedLayout));
138 case WAPI_SHM_FILESHARE:
139 return g_malloc0 (sizeof(struct _WapiFileShareLayout));
142 g_error ("Invalid type in _wapi_shm_attach ()");
148 * Use POSIX shared memory if possible, it is simpler, and it has the advantage that
149 * writes to the shared area does not need to be written to disk, avoiding spinning up
150 * the disk every x secs on laptops.
157 _wapi_shm_base_name (_wapi_shm_t type)
160 gchar machine_name[256];
161 const gchar *fake_name;
168 ubuf.machine[0] = '\0';
169 ubuf.sysname[0] = '\0';
171 g_strdelimit (ubuf.sysname, "/", '_');
172 g_strdelimit (ubuf.machine, "/", '_');
175 fake_name = g_getenv ("MONO_SHARED_HOSTNAME");
176 if (fake_name == NULL) {
177 if (gethostname(machine_name, sizeof(machine_name)) != 0)
178 machine_name[0] = '\0';
180 len = MIN (strlen (fake_name), sizeof (machine_name) - 1);
181 strncpy (machine_name, fake_name, len);
182 machine_name [len] = '\0';
187 name = g_strdup_printf ("shared_data-%s-%s-%s-%d-%d-%d",
188 machine_name, ubuf.sysname,
190 (int) sizeof(struct _WapiHandleShared),
191 _WAPI_HANDLE_VERSION, 0);
194 case WAPI_SHM_FILESHARE:
195 name = g_strdup_printf ("shared_fileshare-%s-%s-%s-%d-%d-%d",
196 machine_name, ubuf.sysname,
198 (int) sizeof(struct _WapiFileShare),
199 _WAPI_HANDLE_VERSION, 0);
208 static gchar *_wapi_shm_shm_name (_wapi_shm_t type)
210 char *base_name = _wapi_shm_base_name (type);
212 /* Also add the uid to avoid permission problems */
213 char *res = g_strdup_printf ("/mono-shared-%d-%s", getuid (), base_name);
221 _wapi_shm_open (const char *filename, int size)
225 fd = shm_open (filename, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP);
227 /* Maybe /dev/shm is not mounted */
229 if (ftruncate (fd, size) != 0) {
230 perror ("_wapi_shm_open (): ftruncate ()");
231 g_assert_not_reached ();
240 _wapi_shm_file (_wapi_shm_t type)
242 static gchar file[_POSIX_PATH_MAX];
243 gchar *name = NULL, *filename, *wapi_dir;
245 name = _wapi_shm_base_name (type);
247 /* I don't know how nfs affects mmap. If mmap() of files on
248 * nfs mounts breaks, then there should be an option to set
251 wapi_dir = getenv ("MONO_SHARED_DIR");
252 if (wapi_dir == NULL) {
253 filename = g_build_filename (g_get_home_dir (), ".wapi", name,
256 filename = g_build_filename (wapi_dir, ".wapi", name, NULL);
260 g_snprintf (file, _POSIX_PATH_MAX, "%s", filename);
267 _wapi_shm_file_open (const gchar *filename, guint32 wanted_size)
272 gboolean created = FALSE;
276 /* No need to check if the dir already exists or check
277 * mkdir() errors, because on any error the open() call will
278 * report the problem.
280 dir = g_path_get_dirname (filename);
288 } else if (tries > 5) {
289 /* Break out of a loop */
293 /* Make sure future processes can open the shared data files */
294 oldmask = umask (066);
296 /* No O_CREAT yet, because we need to initialise the file if
297 * we have to create it.
299 fd = open (filename, O_RDWR, 0600);
302 if (fd == -1 && errno == ENOENT) {
303 /* OK, its up to us to create it. O_EXCL to avoid a
304 * race condition where two processes can
305 * simultaneously try and create the file
307 oldmask = umask (066);
308 fd = open (filename, O_CREAT|O_EXCL|O_RDWR, 0600);
311 if (fd == -1 && errno == EEXIST) {
312 /* It's possible that the file was created in
313 * between finding it didn't exist, and trying
314 * to create it. Just try opening it again
317 } else if (fd == -1) {
318 g_critical ("%s: shared file [%s] open error: %s",
319 __func__, filename, g_strerror (errno));
322 /* We created the file, so we need to expand
325 * (wanted_size-1, because we're about to
326 * write the other byte to actually expand the
329 if (lseek (fd, wanted_size-1, SEEK_SET) == -1) {
330 g_critical ("%s: shared file [%s] lseek error: %s", __func__, filename, g_strerror (errno));
337 ret = write (fd, "", 1);
338 } while (ret == -1 && errno == EINTR);
341 g_critical ("%s: shared file [%s] write error: %s", __func__, filename, g_strerror (errno));
349 /* The contents of the file is set to all
350 * zero, because it is opened up with lseek,
351 * so we don't need to do any more
352 * initialisation here
355 } else if (fd == -1) {
356 g_critical ("%s: shared file [%s] open error: %s", __func__,
357 filename, g_strerror (errno));
361 /* Use stat to find the file size (instead of hard coding it)
362 * because we can expand the file later if needed (for more
363 * handles or scratch space.)
365 if (fstat (fd, &statbuf) == -1) {
366 g_critical ("%s: fstat error: %s", __func__,
368 if (created == TRUE) {
375 if (statbuf.st_size < wanted_size) {
377 if (created == TRUE) {
378 g_critical ("%s: shared file [%s] is not big enough! (found %ld, need %d bytes)", __func__, filename, (long)statbuf.st_size, wanted_size);
382 /* We didn't create it, so just try opening it again */
383 _wapi_handle_spin (100);
392 check_disabled (void)
394 if (_wapi_shm_disabled || g_getenv ("MONO_DISABLE_SHM")) {
395 const char* val = g_getenv ("MONO_DISABLE_SHM");
396 if (val == NULL || *val == '1' || *val == 'y' || *val == 'Y') {
397 _wapi_shm_disabled = TRUE;
401 return _wapi_shm_disabled;
406 * @success: Was it a success
408 * Attach to the shared memory file or create it if it did not exist.
409 * Returns the memory area the file was mmapped to.
412 _wapi_shm_attach (_wapi_shm_t type)
417 gchar *filename = _wapi_shm_file (type), *shm_name;
422 size = sizeof(struct _WapiHandleSharedLayout);
425 case WAPI_SHM_FILESHARE:
426 size = sizeof(struct _WapiFileShareLayout);
429 g_error ("Invalid type in _wapi_shm_attach ()");
433 if (check_disabled ()) {
434 return g_malloc0 (size);
438 shm_name = _wapi_shm_shm_name (type);
439 fd = _wapi_shm_open (shm_name, size);
445 /* Fall back to files if POSIX shm fails (for example, because /dev/shm is not mounted */
447 fd = _wapi_shm_file_open (filename, size);
449 g_critical ("%s: shared file [%s] open error", __func__,
454 if (fstat (fd, &statbuf)==-1) {
455 g_critical ("%s: fstat error: %s", __func__,
461 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
463 if (shm_seg == MAP_FAILED) {
464 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
466 if (shm_seg == MAP_FAILED) {
467 g_critical ("%s: mmap error: %s", __func__, g_strerror (errno));
478 shm_semaphores_init (void)
483 struct _WapiHandleSharedLayout *tmp_shared;
488 * Yet more barmy API - this union is a well-defined parameter
489 * in a syscall, yet I still have to define it here as it
490 * doesn't appear in a header
494 struct semid_ds *buf;
497 ushort def_vals[_WAPI_SHARED_SEM_COUNT];
501 for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++) {
506 * Process count must start at '0' - the 1 for all the others
507 * sets the semaphore to "unlocked"
509 def_vals[_WAPI_SHARED_SEM_PROCESS_COUNT] = 0;
511 defs.array = def_vals;
514 *Temporarily attach the shared data so we can read the
515 * semaphore key. We release this mapping and attach again
516 * after getting the semaphores to avoid a race condition
517 * where a terminating process can delete the shared files
518 * between a new process attaching the file and getting access
519 * to the semaphores (which increments the process count,
520 * preventing destruction of the shared data...)
522 tmp_shared = _wapi_shm_attach (WAPI_SHM_DATA);
523 g_assert (tmp_shared != NULL);
526 ftmp=_wapi_shm_shm_name (WAPI_SHM_DATA);
527 filename = g_build_filename ("/dev/shm", ftmp, NULL);
528 g_assert (filename!=NULL);
529 key = ftok (filename, 'M');
533 key = ftok ( _wapi_shm_file (WAPI_SHM_DATA), 'M');
538 oldkey = tmp_shared->sem_key;
541 DEBUGLOG ("%s: Creating with new key (0x%x)", __func__, key);
544 * The while loop attempts to make some sense of the
545 * bonkers 'think of a random number' method of
546 * picking a key without collision with other
549 while ((_wapi_sem_id = semget (key, _WAPI_SHARED_SEM_COUNT,
550 IPC_CREAT | IPC_EXCL | 0600)) == -1) {
551 if (errno == ENOMEM) {
552 g_error ("%s: semget error: %s", __func__,
554 } else if (errno == ENOSPC) {
555 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));
556 } else if (errno != EEXIST) {
558 g_warning ("%s: semget error: %s key 0x%x - trying again", __func__,
559 g_strerror (errno), key);
563 DEBUGLOG ("%s: Got (%s), trying with new key (0x%x)", __func__, g_strerror (errno), key);
566 * Got a semaphore array, so initialise it and install
567 * the key into the shared memory
570 if (semctl (_wapi_sem_id, 0, SETALL, defs) == -1) {
572 g_warning ("%s: semctl init error: %s - trying again", __func__, g_strerror (errno));
575 * Something went horribly wrong, so try
576 * getting a new set from scratch
578 semctl (_wapi_sem_id, 0, IPC_RMID);
582 if (InterlockedCompareExchange (&tmp_shared->sem_key,
585 * Someone else created one and installed the
586 * key while we were working, so delete the
587 * array we created and fall through to the
588 * 'key already known' case.
590 semctl (_wapi_sem_id, 0, IPC_RMID);
591 oldkey = tmp_shared->sem_key;
594 * We've installed this semaphore set's key into
601 DEBUGLOG ("%s: Trying with old key 0x%x", __func__, oldkey);
603 _wapi_sem_id = semget (oldkey, _WAPI_SHARED_SEM_COUNT, 0600);
604 if (_wapi_sem_id == -1) {
606 g_warning ("%s: semget error opening old key 0x%x (%s) - trying again",
607 __func__, oldkey,g_strerror (errno));
610 * Someone must have deleted the semaphore set, so
611 * blow away the bad key and try again
613 InterlockedCompareExchange (&tmp_shared->sem_key, 0, oldkey);
619 /* Increment the usage count of this semaphore set */
620 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
621 g_assert (thr_ret == 0);
623 DEBUGLOG ("%s: Incrementing the process count (%d)", __func__, _wapi_getpid ());
626 * We only ever _unlock_ this semaphore, letting the kernel
627 * restore (ie decrement) this unlock when this process exits.
628 * We lock another semaphore around it so we can serialise
629 * access when we're testing the value of this semaphore when
630 * we exit cleanly, so we can delete the whole semaphore set.
632 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT);
634 DEBUGLOG ("%s: Process count is now %d (%d)", __func__, semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT, GETVAL), _wapi_getpid ());
636 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
638 if (_wapi_shm_disabled)
641 munmap (tmp_shared, sizeof(struct _WapiHandleSharedLayout));
645 shm_semaphores_remove (void)
651 DEBUGLOG ("%s: Checking process count (%d)", __func__, _wapi_getpid ());
653 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
654 g_assert (thr_ret == 0);
656 proc_count = semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT,
659 g_assert (proc_count > 0);
660 if (proc_count == 1) {
662 * Just us, so blow away the semaphores and the shared
665 DEBUGLOG ("%s: Removing semaphores! (%d)", __func__, _wapi_getpid ());
667 semctl (_wapi_sem_id, 0, IPC_RMID);
669 shm_name = _wapi_shm_shm_name (WAPI_SHM_DATA);
670 shm_unlink (shm_name);
673 shm_name = _wapi_shm_shm_name (WAPI_SHM_FILESHARE);
674 shm_unlink (shm_name);
677 unlink (_wapi_shm_file (WAPI_SHM_DATA));
678 unlink (_wapi_shm_file (WAPI_SHM_FILESHARE));
681 * "else" clause, because there's no point unlocking
682 * the semaphore if we've just blown it away...
684 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
689 shm_sem_lock (int sem)
694 DEBUGLOG ("%s: locking sem %d", __func__, sem);
698 ops.sem_flg = SEM_UNDO;
702 ret = semop (_wapi_sem_id, &ops, 1);
703 } while (ret == -1 && errno == EINTR);
707 * EINVAL covers the case when the semaphore was
708 * deleted before we started the semop
710 if (errno == EIDRM || errno == EINVAL) {
712 * Someone blew away this semaphore set, so
713 * get a new one and try again
715 DEBUGLOG ("%s: Reinitialising the semaphores!", __func__);
717 _wapi_shm_semaphores_init ();
721 /* Turn this into a pthreads-style return value */
725 DEBUGLOG ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
731 shm_sem_trylock (int sem)
736 DEBUGLOG ("%s: trying to lock sem %d", __func__, sem);
740 ops.sem_flg = IPC_NOWAIT | SEM_UNDO;
744 ret = semop (_wapi_sem_id, &ops, 1);
745 } while (ret == -1 && errno == EINTR);
749 * EINVAL covers the case when the semaphore was
750 * deleted before we started the semop
752 if (errno == EIDRM || errno == EINVAL) {
754 * Someone blew away this semaphore set, so
755 * get a new one and try again
757 DEBUGLOG ("%s: Reinitialising the semaphores!", __func__);
759 _wapi_shm_semaphores_init ();
763 /* Turn this into a pthreads-style return value */
768 /* But pthreads uses this code instead */
772 DEBUGLOG ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
778 shm_sem_unlock (int sem)
783 DEBUGLOG ("%s: unlocking sem %d", __func__, sem);
787 ops.sem_flg = SEM_UNDO;
791 ret = semop (_wapi_sem_id, &ops, 1);
792 } while (ret == -1 && errno == EINTR);
795 /* EINVAL covers the case when the semaphore was
796 * deleted before we started the semop
798 if (errno == EIDRM || errno == EINVAL) {
799 /* Someone blew away this semaphore set, so
800 * get a new one and try again (we can't just
801 * assume that the semaphore is now unlocked)
803 DEBUGLOG ("%s: Reinitialising the semaphores!", __func__);
805 _wapi_shm_semaphores_init ();
809 /* Turn this into a pthreads-style return value */
813 DEBUGLOG ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
819 _wapi_shm_semaphores_init (void)
821 if (check_disabled ())
822 noshm_semaphores_init ();
824 shm_semaphores_init ();
828 _wapi_shm_semaphores_remove (void)
830 if (!_wapi_shm_disabled)
831 shm_semaphores_remove ();
835 _wapi_shm_sem_lock (int sem)
837 if (_wapi_shm_disabled)
838 return noshm_sem_lock (sem);
840 return shm_sem_lock (sem);
844 _wapi_shm_sem_trylock (int sem)
846 if (_wapi_shm_disabled)
847 return noshm_sem_trylock (sem);
849 return shm_sem_trylock (sem);
853 _wapi_shm_sem_unlock (int sem)
855 if (_wapi_shm_disabled)
856 return noshm_sem_unlock (sem);
858 return shm_sem_unlock (sem);
860 #endif /* !DISABLE_SHARED_HANDLES */