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 gboolean _wapi_shm_disabled = TRUE;
50 noshm_semaphores_init (void)
54 for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++)
55 mono_mutex_init (&noshm_sems [i], NULL);
59 noshm_sem_lock (int sem)
63 DEBUGLOG ("%s: locking nosem %d", __func__, sem);
65 ret = mono_mutex_lock (&noshm_sems[sem]);
71 noshm_sem_trylock (int sem)
75 DEBUGLOG ("%s: trying to lock nosem %d", __func__, sem);
77 ret = mono_mutex_trylock (&noshm_sems[sem]);
83 noshm_sem_unlock (int sem)
87 DEBUGLOG ("%s: unlocking nosem %d", __func__, sem);
89 ret = mono_mutex_unlock (&noshm_sems[sem]);
94 #ifdef DISABLE_SHARED_HANDLES
96 _wapi_shm_semaphores_init (void)
98 noshm_semaphores_init ();
102 _wapi_shm_semaphores_remove (void)
108 _wapi_shm_sem_lock (int sem)
110 return noshm_sem_lock (sem);
114 _wapi_shm_sem_trylock (int sem)
116 return noshm_sem_trylock (sem);
120 _wapi_shm_sem_unlock (int sem)
122 return noshm_sem_unlock (sem);
126 _wapi_shm_attach (_wapi_shm_t type)
132 return g_malloc0 (sizeof(struct _WapiHandleSharedLayout));
134 case WAPI_SHM_FILESHARE:
135 return g_malloc0 (sizeof(struct _WapiFileShareLayout));
138 g_error ("Invalid type in _wapi_shm_attach ()");
144 * Use POSIX shared memory if possible, it is simpler, and it has the advantage that
145 * writes to the shared area does not need to be written to disk, avoiding spinning up
146 * the disk every x secs on laptops.
153 _wapi_shm_base_name (_wapi_shm_t type)
156 gchar machine_name[256];
157 const gchar *fake_name;
164 ubuf.machine[0] = '\0';
165 ubuf.sysname[0] = '\0';
167 g_strdelimit (ubuf.sysname, "/", '_');
168 g_strdelimit (ubuf.machine, "/", '_');
171 fake_name = g_getenv ("MONO_SHARED_HOSTNAME");
172 if (fake_name == NULL) {
173 if (gethostname(machine_name, sizeof(machine_name)) != 0)
174 machine_name[0] = '\0';
176 len = MIN (strlen (fake_name), sizeof (machine_name) - 1);
177 strncpy (machine_name, fake_name, len);
178 machine_name [len] = '\0';
183 name = g_strdup_printf ("shared_data-%s-%s-%s-%d-%d-%d",
184 machine_name, ubuf.sysname,
186 (int) sizeof(struct _WapiHandleShared),
187 _WAPI_HANDLE_VERSION, 0);
190 case WAPI_SHM_FILESHARE:
191 name = g_strdup_printf ("shared_fileshare-%s-%s-%s-%d-%d-%d",
192 machine_name, ubuf.sysname,
194 (int) sizeof(struct _WapiFileShare),
195 _WAPI_HANDLE_VERSION, 0);
204 static gchar *_wapi_shm_shm_name (_wapi_shm_t type)
206 char *base_name = _wapi_shm_base_name (type);
208 /* Also add the uid to avoid permission problems */
209 char *res = g_strdup_printf ("/mono-shared-%d-%s", getuid (), base_name);
217 _wapi_shm_open (const char *filename, int size)
221 fd = shm_open (filename, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP);
223 /* Maybe /dev/shm is not mounted */
225 if (ftruncate (fd, size) != 0) {
226 perror ("_wapi_shm_open (): ftruncate ()");
227 g_assert_not_reached ();
236 _wapi_shm_file (_wapi_shm_t type)
238 static gchar file[_POSIX_PATH_MAX];
239 gchar *name = NULL, *filename, *wapi_dir;
241 name = _wapi_shm_base_name (type);
243 /* I don't know how nfs affects mmap. If mmap() of files on
244 * nfs mounts breaks, then there should be an option to set
247 wapi_dir = getenv ("MONO_SHARED_DIR");
248 if (wapi_dir == NULL) {
249 filename = g_build_filename (g_get_home_dir (), ".wapi", name,
252 filename = g_build_filename (wapi_dir, ".wapi", name, NULL);
256 g_snprintf (file, _POSIX_PATH_MAX, "%s", filename);
263 _wapi_shm_file_open (const gchar *filename, guint32 wanted_size)
268 gboolean created = FALSE;
272 /* No need to check if the dir already exists or check
273 * mkdir() errors, because on any error the open() call will
274 * report the problem.
276 dir = g_path_get_dirname (filename);
284 } else if (tries > 5) {
285 /* Break out of a loop */
289 /* Make sure future processes can open the shared data files */
290 oldmask = umask (066);
292 /* No O_CREAT yet, because we need to initialise the file if
293 * we have to create it.
295 fd = open (filename, O_RDWR, 0600);
298 if (fd == -1 && errno == ENOENT) {
299 /* OK, its up to us to create it. O_EXCL to avoid a
300 * race condition where two processes can
301 * simultaneously try and create the file
303 oldmask = umask (066);
304 fd = open (filename, O_CREAT|O_EXCL|O_RDWR, 0600);
307 if (fd == -1 && errno == EEXIST) {
308 /* It's possible that the file was created in
309 * between finding it didn't exist, and trying
310 * to create it. Just try opening it again
313 } else if (fd == -1) {
314 g_critical ("%s: shared file [%s] open error: %s",
315 __func__, filename, g_strerror (errno));
318 /* We created the file, so we need to expand
321 * (wanted_size-1, because we're about to
322 * write the other byte to actually expand the
325 if (lseek (fd, wanted_size-1, SEEK_SET) == -1) {
326 g_critical ("%s: shared file [%s] lseek error: %s", __func__, filename, g_strerror (errno));
333 ret = write (fd, "", 1);
334 } while (ret == -1 && errno == EINTR);
337 g_critical ("%s: shared file [%s] write error: %s", __func__, filename, g_strerror (errno));
345 /* The contents of the file is set to all
346 * zero, because it is opened up with lseek,
347 * so we don't need to do any more
348 * initialisation here
351 } else if (fd == -1) {
352 g_critical ("%s: shared file [%s] open error: %s", __func__,
353 filename, g_strerror (errno));
357 /* Use stat to find the file size (instead of hard coding it)
358 * because we can expand the file later if needed (for more
359 * handles or scratch space.)
361 if (fstat (fd, &statbuf) == -1) {
362 g_critical ("%s: fstat error: %s", __func__,
364 if (created == TRUE) {
371 if (statbuf.st_size < wanted_size) {
373 if (created == TRUE) {
374 g_critical ("%s: shared file [%s] is not big enough! (found %ld, need %d bytes)", __func__, filename, (long)statbuf.st_size, wanted_size);
378 /* We didn't create it, so just try opening it again */
379 _wapi_handle_spin (100);
388 check_disabled (void)
390 static gboolean env_checked;
393 if (g_getenv ("MONO_ENABLE_SHM"))
394 _wapi_shm_disabled = FALSE;
398 return _wapi_shm_disabled;
403 * @success: Was it a success
405 * Attach to the shared memory file or create it if it did not exist.
406 * Returns the memory area the file was mmapped to.
409 _wapi_shm_attach (_wapi_shm_t type)
414 gchar *filename = _wapi_shm_file (type), *shm_name;
419 size = sizeof(struct _WapiHandleSharedLayout);
422 case WAPI_SHM_FILESHARE:
423 size = sizeof(struct _WapiFileShareLayout);
426 g_error ("Invalid type in _wapi_shm_attach ()");
430 if (check_disabled ()) {
431 return g_malloc0 (size);
435 shm_name = _wapi_shm_shm_name (type);
436 fd = _wapi_shm_open (shm_name, size);
442 /* Fall back to files if POSIX shm fails (for example, because /dev/shm is not mounted */
444 fd = _wapi_shm_file_open (filename, size);
446 g_critical ("%s: shared file [%s] open error", __func__,
451 if (fstat (fd, &statbuf)==-1) {
452 g_critical ("%s: fstat error: %s", __func__,
458 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
460 if (shm_seg == MAP_FAILED) {
461 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
463 if (shm_seg == MAP_FAILED) {
464 g_critical ("%s: mmap error: %s", __func__, g_strerror (errno));
475 shm_semaphores_init (void)
480 struct _WapiHandleSharedLayout *tmp_shared;
485 * Yet more barmy API - this union is a well-defined parameter
486 * in a syscall, yet I still have to define it here as it
487 * doesn't appear in a header
491 struct semid_ds *buf;
494 ushort def_vals[_WAPI_SHARED_SEM_COUNT];
498 for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++) {
503 * Process count must start at '0' - the 1 for all the others
504 * sets the semaphore to "unlocked"
506 def_vals[_WAPI_SHARED_SEM_PROCESS_COUNT] = 0;
508 defs.array = def_vals;
511 *Temporarily attach the shared data so we can read the
512 * semaphore key. We release this mapping and attach again
513 * after getting the semaphores to avoid a race condition
514 * where a terminating process can delete the shared files
515 * between a new process attaching the file and getting access
516 * to the semaphores (which increments the process count,
517 * preventing destruction of the shared data...)
519 tmp_shared = _wapi_shm_attach (WAPI_SHM_DATA);
520 g_assert (tmp_shared != NULL);
523 ftmp=_wapi_shm_shm_name (WAPI_SHM_DATA);
524 filename = g_build_filename ("/dev/shm", ftmp, NULL);
525 g_assert (filename!=NULL);
526 key = ftok (filename, 'M');
530 key = ftok ( _wapi_shm_file (WAPI_SHM_DATA), 'M');
535 oldkey = tmp_shared->sem_key;
538 DEBUGLOG ("%s: Creating with new key (0x%x)", __func__, key);
541 * The while loop attempts to make some sense of the
542 * bonkers 'think of a random number' method of
543 * picking a key without collision with other
546 while ((_wapi_sem_id = semget (key, _WAPI_SHARED_SEM_COUNT,
547 IPC_CREAT | IPC_EXCL | 0600)) == -1) {
548 if (errno == ENOMEM) {
549 g_error ("%s: semget error: %s", __func__,
551 } else if (errno == ENOSPC) {
552 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));
553 } else if (errno != EEXIST) {
555 g_warning ("%s: semget error: %s key 0x%x - trying again", __func__,
556 g_strerror (errno), key);
560 DEBUGLOG ("%s: Got (%s), trying with new key (0x%x)", __func__, g_strerror (errno), key);
563 * Got a semaphore array, so initialise it and install
564 * the key into the shared memory
567 if (semctl (_wapi_sem_id, 0, SETALL, defs) == -1) {
569 g_warning ("%s: semctl init error: %s - trying again", __func__, g_strerror (errno));
572 * Something went horribly wrong, so try
573 * getting a new set from scratch
575 semctl (_wapi_sem_id, 0, IPC_RMID);
579 if (InterlockedCompareExchange (&tmp_shared->sem_key,
582 * Someone else created one and installed the
583 * key while we were working, so delete the
584 * array we created and fall through to the
585 * 'key already known' case.
587 semctl (_wapi_sem_id, 0, IPC_RMID);
588 oldkey = tmp_shared->sem_key;
591 * We've installed this semaphore set's key into
598 DEBUGLOG ("%s: Trying with old key 0x%x", __func__, oldkey);
600 _wapi_sem_id = semget (oldkey, _WAPI_SHARED_SEM_COUNT, 0600);
601 if (_wapi_sem_id == -1) {
603 g_warning ("%s: semget error opening old key 0x%x (%s) - trying again",
604 __func__, oldkey,g_strerror (errno));
607 * Someone must have deleted the semaphore set, so
608 * blow away the bad key and try again
610 InterlockedCompareExchange (&tmp_shared->sem_key, 0, oldkey);
616 /* Increment the usage count of this semaphore set */
617 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
618 g_assert (thr_ret == 0);
620 DEBUGLOG ("%s: Incrementing the process count (%d)", __func__, _wapi_getpid ());
623 * We only ever _unlock_ this semaphore, letting the kernel
624 * restore (ie decrement) this unlock when this process exits.
625 * We lock another semaphore around it so we can serialise
626 * access when we're testing the value of this semaphore when
627 * we exit cleanly, so we can delete the whole semaphore set.
629 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT);
631 DEBUGLOG ("%s: Process count is now %d (%d)", __func__, semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT, GETVAL), _wapi_getpid ());
633 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
635 if (_wapi_shm_disabled)
638 munmap (tmp_shared, sizeof(struct _WapiHandleSharedLayout));
642 shm_semaphores_remove (void)
648 DEBUGLOG ("%s: Checking process count (%d)", __func__, _wapi_getpid ());
650 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
651 g_assert (thr_ret == 0);
653 proc_count = semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT,
656 g_assert (proc_count > 0);
657 if (proc_count == 1) {
659 * Just us, so blow away the semaphores and the shared
662 DEBUGLOG ("%s: Removing semaphores! (%d)", __func__, _wapi_getpid ());
664 semctl (_wapi_sem_id, 0, IPC_RMID);
666 shm_name = _wapi_shm_shm_name (WAPI_SHM_DATA);
667 shm_unlink (shm_name);
670 shm_name = _wapi_shm_shm_name (WAPI_SHM_FILESHARE);
671 shm_unlink (shm_name);
674 unlink (_wapi_shm_file (WAPI_SHM_DATA));
675 unlink (_wapi_shm_file (WAPI_SHM_FILESHARE));
678 * "else" clause, because there's no point unlocking
679 * the semaphore if we've just blown it away...
681 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
686 shm_sem_lock (int sem)
691 DEBUGLOG ("%s: locking sem %d", __func__, sem);
695 ops.sem_flg = SEM_UNDO;
699 ret = semop (_wapi_sem_id, &ops, 1);
700 } while (ret == -1 && errno == EINTR);
704 * EINVAL covers the case when the semaphore was
705 * deleted before we started the semop
707 if (errno == EIDRM || errno == EINVAL) {
709 * Someone blew away this semaphore set, so
710 * get a new one and try again
712 DEBUGLOG ("%s: Reinitialising the semaphores!", __func__);
714 _wapi_shm_semaphores_init ();
718 /* Turn this into a pthreads-style return value */
722 DEBUGLOG ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
728 shm_sem_trylock (int sem)
733 DEBUGLOG ("%s: trying to lock sem %d", __func__, sem);
737 ops.sem_flg = IPC_NOWAIT | SEM_UNDO;
741 ret = semop (_wapi_sem_id, &ops, 1);
742 } while (ret == -1 && errno == EINTR);
746 * EINVAL covers the case when the semaphore was
747 * deleted before we started the semop
749 if (errno == EIDRM || errno == EINVAL) {
751 * Someone blew away this semaphore set, so
752 * get a new one and try again
754 DEBUGLOG ("%s: Reinitialising the semaphores!", __func__);
756 _wapi_shm_semaphores_init ();
760 /* Turn this into a pthreads-style return value */
765 /* But pthreads uses this code instead */
769 DEBUGLOG ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
775 shm_sem_unlock (int sem)
780 DEBUGLOG ("%s: unlocking sem %d", __func__, sem);
784 ops.sem_flg = SEM_UNDO;
788 ret = semop (_wapi_sem_id, &ops, 1);
789 } while (ret == -1 && errno == EINTR);
792 /* EINVAL covers the case when the semaphore was
793 * deleted before we started the semop
795 if (errno == EIDRM || errno == EINVAL) {
796 /* Someone blew away this semaphore set, so
797 * get a new one and try again (we can't just
798 * assume that the semaphore is now unlocked)
800 DEBUGLOG ("%s: Reinitialising the semaphores!", __func__);
802 _wapi_shm_semaphores_init ();
806 /* Turn this into a pthreads-style return value */
810 DEBUGLOG ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
816 _wapi_shm_semaphores_init (void)
818 if (check_disabled ())
819 noshm_semaphores_init ();
821 shm_semaphores_init ();
825 _wapi_shm_semaphores_remove (void)
827 if (!_wapi_shm_disabled)
828 shm_semaphores_remove ();
832 _wapi_shm_sem_lock (int sem)
834 if (_wapi_shm_disabled)
835 return noshm_sem_lock (sem);
837 return shm_sem_lock (sem);
841 _wapi_shm_sem_trylock (int sem)
843 if (_wapi_shm_disabled)
844 return noshm_sem_trylock (sem);
846 return shm_sem_trylock (sem);
850 _wapi_shm_sem_unlock (int sem)
852 if (_wapi_shm_disabled)
853 return noshm_sem_unlock (sem);
855 return shm_sem_unlock (sem);
857 #endif /* !DISABLE_SHARED_HANDLES */