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];
48 noshm_semaphores_init (void)
52 for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++)
53 mono_mutex_init (&noshm_sems [i], NULL);
57 noshm_sem_lock (int sem)
61 DEBUGLOG ("%s: locking nosem %d", __func__, sem);
63 ret = mono_mutex_lock (&noshm_sems[sem]);
69 noshm_sem_trylock (int sem)
73 DEBUGLOG ("%s: trying to lock nosem %d", __func__, sem);
75 ret = mono_mutex_trylock (&noshm_sems[sem]);
81 noshm_sem_unlock (int sem)
85 DEBUGLOG ("%s: unlocking nosem %d", __func__, sem);
87 ret = mono_mutex_unlock (&noshm_sems[sem]);
92 #ifdef DISABLE_SHARED_HANDLES
94 _wapi_shm_semaphores_init (void)
96 noshm_semaphores_init ();
100 _wapi_shm_semaphores_remove (void)
106 _wapi_shm_sem_lock (int sem)
108 return noshm_sem_lock (sem);
112 _wapi_shm_sem_trylock (int sem)
114 return noshm_sem_trylock (sem);
118 _wapi_shm_sem_unlock (int sem)
120 return noshm_sem_unlock (sem);
124 * Use POSIX shared memory if possible, it is simpler, and it has the advantage that
125 * writes to the shared area does not need to be written to disk, avoiding spinning up
126 * the disk every x secs on laptops.
132 #ifdef DISABLE_SHARED_HANDLES
133 gboolean _wapi_shm_disabled = TRUE;
135 gboolean _wapi_shm_disabled = FALSE;
139 _wapi_shm_base_name (_wapi_shm_t type)
142 gchar machine_name[256];
143 const gchar *fake_name;
150 ubuf.machine[0] = '\0';
151 ubuf.sysname[0] = '\0';
153 g_strdelimit (ubuf.sysname, "/", '_');
154 g_strdelimit (ubuf.machine, "/", '_');
157 fake_name = g_getenv ("MONO_SHARED_HOSTNAME");
158 if (fake_name == NULL) {
159 if (gethostname(machine_name, sizeof(machine_name)) != 0)
160 machine_name[0] = '\0';
162 len = MIN (strlen (fake_name), sizeof (machine_name) - 1);
163 strncpy (machine_name, fake_name, len);
164 machine_name [len] = '\0';
169 name = g_strdup_printf ("shared_data-%s-%s-%s-%d-%d-%d",
170 machine_name, ubuf.sysname,
172 (int) sizeof(struct _WapiHandleShared),
173 _WAPI_HANDLE_VERSION, 0);
176 case WAPI_SHM_FILESHARE:
177 name = g_strdup_printf ("shared_fileshare-%s-%s-%s-%d-%d-%d",
178 machine_name, ubuf.sysname,
180 (int) sizeof(struct _WapiFileShare),
181 _WAPI_HANDLE_VERSION, 0);
190 static gchar *_wapi_shm_shm_name (_wapi_shm_t type)
192 char *base_name = _wapi_shm_base_name (type);
194 /* Also add the uid to avoid permission problems */
195 char *res = g_strdup_printf ("/mono-shared-%d-%s", getuid (), base_name);
203 _wapi_shm_open (const char *filename, int size)
207 fd = shm_open (filename, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP);
209 /* Maybe /dev/shm is not mounted */
211 if (ftruncate (fd, size) != 0) {
212 perror ("_wapi_shm_open (): ftruncate ()");
213 g_assert_not_reached ();
222 _wapi_shm_file (_wapi_shm_t type)
224 static gchar file[_POSIX_PATH_MAX];
225 gchar *name = NULL, *filename, *dir, *wapi_dir;
227 name = _wapi_shm_base_name (type);
229 /* I don't know how nfs affects mmap. If mmap() of files on
230 * nfs mounts breaks, then there should be an option to set
233 wapi_dir = getenv ("MONO_SHARED_DIR");
234 if (wapi_dir == NULL) {
235 filename = g_build_filename (g_get_home_dir (), ".wapi", name,
238 filename = g_build_filename (wapi_dir, ".wapi", name, NULL);
242 g_snprintf (file, _POSIX_PATH_MAX, "%s", filename);
245 /* No need to check if the dir already exists or check
246 * mkdir() errors, because on any error the open() call will
247 * report the problem.
249 dir = g_path_get_dirname (file);
257 _wapi_shm_file_open (const gchar *filename, guint32 wanted_size)
262 gboolean created = FALSE;
269 } else if (tries > 5) {
270 /* Break out of a loop */
274 /* Make sure future processes can open the shared data files */
275 oldmask = umask (066);
277 /* No O_CREAT yet, because we need to initialise the file if
278 * we have to create it.
280 fd = open (filename, O_RDWR, 0600);
283 if (fd == -1 && errno == ENOENT) {
284 /* OK, its up to us to create it. O_EXCL to avoid a
285 * race condition where two processes can
286 * simultaneously try and create the file
288 oldmask = umask (066);
289 fd = open (filename, O_CREAT|O_EXCL|O_RDWR, 0600);
292 if (fd == -1 && errno == EEXIST) {
293 /* It's possible that the file was created in
294 * between finding it didn't exist, and trying
295 * to create it. Just try opening it again
298 } else if (fd == -1) {
299 g_critical ("%s: shared file [%s] open error: %s",
300 __func__, filename, g_strerror (errno));
303 /* We created the file, so we need to expand
306 * (wanted_size-1, because we're about to
307 * write the other byte to actually expand the
310 if (lseek (fd, wanted_size-1, SEEK_SET) == -1) {
311 g_critical ("%s: shared file [%s] lseek error: %s", __func__, filename, g_strerror (errno));
318 ret = write (fd, "", 1);
319 } while (ret == -1 && errno == EINTR);
322 g_critical ("%s: shared file [%s] write error: %s", __func__, filename, g_strerror (errno));
330 /* The contents of the file is set to all
331 * zero, because it is opened up with lseek,
332 * so we don't need to do any more
333 * initialisation here
336 } else if (fd == -1) {
337 g_critical ("%s: shared file [%s] open error: %s", __func__,
338 filename, g_strerror (errno));
342 /* Use stat to find the file size (instead of hard coding it)
343 * because we can expand the file later if needed (for more
344 * handles or scratch space.)
346 if (fstat (fd, &statbuf) == -1) {
347 g_critical ("%s: fstat error: %s", __func__,
349 if (created == TRUE) {
356 if (statbuf.st_size < wanted_size) {
358 if (created == TRUE) {
359 g_critical ("%s: shared file [%s] is not big enough! (found %ld, need %d bytes)", __func__, filename, (long)statbuf.st_size, wanted_size);
363 /* We didn't create it, so just try opening it again */
364 _wapi_handle_spin (100);
373 check_disabled (void)
375 if (_wapi_shm_disabled || g_getenv ("MONO_DISABLE_SHM")) {
376 const char* val = g_getenv ("MONO_DISABLE_SHM");
377 if (val == NULL || *val == '1' || *val == 'y' || *val == 'Y') {
378 _wapi_shm_disabled = TRUE;
382 return _wapi_shm_disabled;
387 * @success: Was it a success
389 * Attach to the shared memory file or create it if it did not exist.
390 * Returns the memory area the file was mmapped to.
393 _wapi_shm_attach (_wapi_shm_t type)
398 gchar *filename = _wapi_shm_file (type), *shm_name;
403 size = sizeof(struct _WapiHandleSharedLayout);
406 case WAPI_SHM_FILESHARE:
407 size = sizeof(struct _WapiFileShareLayout);
410 g_error ("Invalid type in _wapi_shm_attach ()");
414 if (check_disabled ()) {
415 return g_malloc0 (size);
419 shm_name = _wapi_shm_shm_name (type);
420 fd = _wapi_shm_open (shm_name, size);
426 /* Fall back to files if POSIX shm fails (for example, because /dev/shm is not mounted */
428 fd = _wapi_shm_file_open (filename, size);
430 g_critical ("%s: shared file [%s] open error", __func__,
435 if (fstat (fd, &statbuf)==-1) {
436 g_critical ("%s: fstat error: %s", __func__,
442 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
444 if (shm_seg == MAP_FAILED) {
445 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
447 if (shm_seg == MAP_FAILED) {
448 g_critical ("%s: mmap error: %s", __func__, g_strerror (errno));
459 shm_semaphores_init (void)
464 struct _WapiHandleSharedLayout *tmp_shared;
467 * Yet more barmy API - this union is a well-defined parameter
468 * in a syscall, yet I still have to define it here as it
469 * doesn't appear in a header
473 struct semid_ds *buf;
476 ushort def_vals[_WAPI_SHARED_SEM_COUNT];
480 for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++) {
485 * Process count must start at '0' - the 1 for all the others
486 * sets the semaphore to "unlocked"
488 def_vals[_WAPI_SHARED_SEM_PROCESS_COUNT] = 0;
490 defs.array = def_vals;
493 *Temporarily attach the shared data so we can read the
494 * semaphore key. We release this mapping and attach again
495 * after getting the semaphores to avoid a race condition
496 * where a terminating process can delete the shared files
497 * between a new process attaching the file and getting access
498 * to the semaphores (which increments the process count,
499 * preventing destruction of the shared data...)
501 tmp_shared = _wapi_shm_attach (WAPI_SHM_DATA);
502 g_assert (tmp_shared != NULL);
504 key = ftok (_wapi_shm_file (WAPI_SHM_DATA), 'M');
508 oldkey = tmp_shared->sem_key;
511 DEBUGLOG ("%s: Creating with new key (0x%x)", __func__, key);
514 * The while loop attempts to make some sense of the
515 * bonkers 'think of a random number' method of
516 * picking a key without collision with other
519 while ((_wapi_sem_id = semget (key, _WAPI_SHARED_SEM_COUNT,
520 IPC_CREAT | IPC_EXCL | 0600)) == -1) {
521 if (errno == ENOMEM) {
522 g_error ("%s: semget error: %s", __func__,
524 } else if (errno == ENOSPC) {
525 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));
526 } else if (errno != EEXIST) {
528 g_warning ("%s: semget error: %s key 0x%x - trying again", __func__,
529 g_strerror (errno), key);
533 DEBUGLOG ("%s: Got (%s), trying with new key (0x%x)", __func__, g_strerror (errno), key);
536 * Got a semaphore array, so initialise it and install
537 * the key into the shared memory
540 if (semctl (_wapi_sem_id, 0, SETALL, defs) == -1) {
542 g_warning ("%s: semctl init error: %s - trying again", __func__, g_strerror (errno));
545 * Something went horribly wrong, so try
546 * getting a new set from scratch
548 semctl (_wapi_sem_id, 0, IPC_RMID);
552 if (InterlockedCompareExchange (&tmp_shared->sem_key,
555 * Someone else created one and installed the
556 * key while we were working, so delete the
557 * array we created and fall through to the
558 * 'key already known' case.
560 semctl (_wapi_sem_id, 0, IPC_RMID);
561 oldkey = tmp_shared->sem_key;
564 * We've installed this semaphore set's key into
571 DEBUGLOG ("%s: Trying with old key 0x%x", __func__, oldkey);
573 _wapi_sem_id = semget (oldkey, _WAPI_SHARED_SEM_COUNT, 0600);
574 if (_wapi_sem_id == -1) {
576 g_warning ("%s: semget error opening old key 0x%x (%s) - trying again",
577 __func__, oldkey,g_strerror (errno));
580 * Someone must have deleted the semaphore set, so
581 * blow away the bad key and try again
583 InterlockedCompareExchange (&tmp_shared->sem_key, 0, oldkey);
589 /* Increment the usage count of this semaphore set */
590 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
591 g_assert (thr_ret == 0);
593 DEBUGLOG ("%s: Incrementing the process count (%d)", __func__, _wapi_getpid ());
596 * We only ever _unlock_ this semaphore, letting the kernel
597 * restore (ie decrement) this unlock when this process exits.
598 * We lock another semaphore around it so we can serialise
599 * access when we're testing the value of this semaphore when
600 * we exit cleanly, so we can delete the whole semaphore set.
602 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT);
604 DEBUGLOG ("%s: Process count is now %d (%d)", __func__, semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT, GETVAL), _wapi_getpid ());
606 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
608 if (_wapi_shm_disabled)
611 munmap (tmp_shared, sizeof(struct _WapiHandleSharedLayout));
615 shm_semaphores_remove (void)
621 DEBUGLOG ("%s: Checking process count (%d)", __func__, _wapi_getpid ());
623 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
624 g_assert (thr_ret == 0);
626 proc_count = semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT,
629 g_assert (proc_count > 0);
630 if (proc_count == 1) {
632 * Just us, so blow away the semaphores and the shared
635 DEBUGLOG ("%s: Removing semaphores! (%d)", __func__, _wapi_getpid ());
637 semctl (_wapi_sem_id, 0, IPC_RMID);
639 shm_name = _wapi_shm_shm_name (WAPI_SHM_DATA);
640 shm_unlink (shm_name);
643 shm_name = _wapi_shm_shm_name (WAPI_SHM_FILESHARE);
644 shm_unlink (shm_name);
647 unlink (_wapi_shm_file (WAPI_SHM_DATA));
648 unlink (_wapi_shm_file (WAPI_SHM_FILESHARE));
651 * "else" clause, because there's no point unlocking
652 * the semaphore if we've just blown it away...
654 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
659 shm_sem_lock (int sem)
664 DEBUGLOG ("%s: locking sem %d", __func__, sem);
668 ops.sem_flg = SEM_UNDO;
672 ret = semop (_wapi_sem_id, &ops, 1);
673 } while (ret == -1 && errno == EINTR);
677 * EINVAL covers the case when the semaphore was
678 * deleted before we started the semop
680 if (errno == EIDRM || errno == EINVAL) {
682 * Someone blew away this semaphore set, so
683 * get a new one and try again
685 DEBUGLOG ("%s: Reinitialising the semaphores!", __func__);
687 _wapi_shm_semaphores_init ();
691 /* Turn this into a pthreads-style return value */
695 DEBUGLOG ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
701 shm_sem_trylock (int sem)
706 DEBUGLOG ("%s: trying to lock sem %d", __func__, sem);
710 ops.sem_flg = IPC_NOWAIT | SEM_UNDO;
714 ret = semop (_wapi_sem_id, &ops, 1);
715 } while (ret == -1 && errno == EINTR);
719 * EINVAL covers the case when the semaphore was
720 * deleted before we started the semop
722 if (errno == EIDRM || errno == EINVAL) {
724 * Someone blew away this semaphore set, so
725 * get a new one and try again
727 DEBUGLOG ("%s: Reinitialising the semaphores!", __func__);
729 _wapi_shm_semaphores_init ();
733 /* Turn this into a pthreads-style return value */
738 /* But pthreads uses this code instead */
742 DEBUGLOG ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
748 shm_sem_unlock (int sem)
753 DEBUGLOG ("%s: unlocking sem %d", __func__, sem);
757 ops.sem_flg = SEM_UNDO;
761 ret = semop (_wapi_sem_id, &ops, 1);
762 } while (ret == -1 && errno == EINTR);
765 /* EINVAL covers the case when the semaphore was
766 * deleted before we started the semop
768 if (errno == EIDRM || errno == EINVAL) {
769 /* Someone blew away this semaphore set, so
770 * get a new one and try again (we can't just
771 * assume that the semaphore is now unlocked)
773 DEBUGLOG ("%s: Reinitialising the semaphores!", __func__);
775 _wapi_shm_semaphores_init ();
779 /* Turn this into a pthreads-style return value */
783 DEBUGLOG ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
789 _wapi_shm_semaphores_init (void)
791 if (check_disabled ())
792 noshm_semaphores_init ();
794 shm_semaphores_init ();
798 _wapi_shm_semaphores_remove (void)
800 if (!_wapi_shm_disabled)
801 shm_semaphores_remove ();
805 _wapi_shm_sem_lock (int sem)
807 if (_wapi_shm_disabled)
808 return noshm_sem_lock (sem);
810 return shm_sem_lock (sem);
814 _wapi_shm_sem_trylock (int sem)
816 if (_wapi_shm_disabled)
817 return noshm_sem_trylock (sem);
819 return shm_sem_trylock (sem);
823 _wapi_shm_sem_unlock (int sem)
825 if (_wapi_shm_disabled)
826 return noshm_sem_unlock (sem);
828 return shm_sem_unlock (sem);
830 #endif /* !DISABLE_SHARED_HANDLES */