2 * shared.c: Shared memory handling, and daemon launching
5 * Dick Porter (dick@ximian.com)
7 * (C) 2002-2006 Novell, Inc.
17 #include <sys/types.h>
23 #include <sys/utsname.h>
25 #include <mono/io-layer/wapi.h>
26 #include <mono/io-layer/wapi-private.h>
27 #include <mono/io-layer/shared.h>
28 #include <mono/io-layer/handles-private.h>
32 #ifdef DISABLE_SHARED_HANDLES
33 gboolean _wapi_shm_disabled = TRUE;
35 gboolean _wapi_shm_disabled = FALSE;
38 static gchar *_wapi_shm_file (_wapi_shm_t type)
40 static gchar file[_POSIX_PATH_MAX];
41 gchar *name = NULL, *filename, *dir, *wapi_dir;
42 gchar machine_name[256];
43 const gchar *fake_name;
50 ubuf.machine[0] = '\0';
51 ubuf.sysname[0] = '\0';
53 g_strdelimit (ubuf.sysname, "/", '_');
54 g_strdelimit (ubuf.machine, "/", '_');
57 fake_name = g_getenv ("MONO_SHARED_HOSTNAME");
58 if (fake_name == NULL) {
59 if (gethostname(machine_name, sizeof(machine_name)) != 0)
60 machine_name[0] = '\0';
62 len = MIN (strlen (fake_name), sizeof (machine_name) - 1);
63 strncpy (machine_name, fake_name, len);
64 machine_name [len] = '\0';
69 name = g_strdup_printf ("shared_data-%s-%s-%s-%d-%d-%d",
70 machine_name, ubuf.sysname,
72 (int) sizeof(struct _WapiHandleShared),
73 _WAPI_HANDLE_VERSION, 0);
76 case WAPI_SHM_FILESHARE:
77 name = g_strdup_printf ("shared_fileshare-%s-%s-%s-%d-%d-%d",
78 machine_name, ubuf.sysname,
80 (int) sizeof(struct _WapiFileShare),
81 _WAPI_HANDLE_VERSION, 0);
85 /* I don't know how nfs affects mmap. If mmap() of files on
86 * nfs mounts breaks, then there should be an option to set
89 wapi_dir = getenv ("MONO_SHARED_DIR");
90 if (wapi_dir == NULL) {
91 filename = g_build_filename (g_get_home_dir (), ".wapi", name,
94 filename = g_build_filename (wapi_dir, ".wapi", name, NULL);
98 g_snprintf (file, _POSIX_PATH_MAX, "%s", filename);
101 /* No need to check if the dir already exists or check
102 * mkdir() errors, because on any error the open() call will
103 * report the problem.
105 dir = g_path_get_dirname (file);
112 static int _wapi_shm_file_open (const gchar *filename, guint32 wanted_size)
117 gboolean created = FALSE;
123 } else if (tries > 5) {
124 /* Break out of a loop */
128 /* No O_CREAT yet, because we need to initialise the file if
129 * we have to create it.
131 fd = open (filename, O_RDWR, 0600);
132 if (fd == -1 && errno == ENOENT) {
133 /* OK, its up to us to create it. O_EXCL to avoid a
134 * race condition where two processes can
135 * simultaneously try and create the file
137 fd = open (filename, O_CREAT|O_EXCL|O_RDWR, 0600);
138 if (fd == -1 && errno == EEXIST) {
139 /* It's possible that the file was created in
140 * between finding it didn't exist, and trying
141 * to create it. Just try opening it again
144 } else if (fd == -1) {
145 g_critical ("%s: shared file [%s] open error: %s",
146 __func__, filename, g_strerror (errno));
149 /* We created the file, so we need to expand
152 * (wanted_size-1, because we're about to
153 * write the other byte to actually expand the
156 if (lseek (fd, wanted_size-1, SEEK_SET) == -1) {
157 g_critical ("%s: shared file [%s] lseek error: %s", __func__, filename, g_strerror (errno));
164 ret = write (fd, "", 1);
165 } while (ret == -1 && errno == EINTR);
168 g_critical ("%s: shared file [%s] write error: %s", __func__, filename, g_strerror (errno));
176 /* The contents of the file is set to all
177 * zero, because it is opened up with lseek,
178 * so we don't need to do any more
179 * initialisation here
182 } else if (fd == -1) {
183 g_critical ("%s: shared file [%s] open error: %s", __func__,
184 filename, g_strerror (errno));
188 /* Use stat to find the file size (instead of hard coding it)
189 * because we can expand the file later if needed (for more
190 * handles or scratch space.)
192 if (fstat (fd, &statbuf) == -1) {
193 g_critical ("%s: fstat error: %s", __func__,
195 if (created == TRUE) {
202 if (statbuf.st_size < wanted_size) {
204 if (created == TRUE) {
205 #ifdef HAVE_LARGE_FILE_SUPPORT
206 /* Keep gcc quiet... */
207 g_critical ("%s: shared file [%s] is not big enough! (found %lld, need %d bytes)", __func__, filename, statbuf.st_size, wanted_size);
209 g_critical ("%s: shared file [%s] is not big enough! (found %ld, need %d bytes)", __func__, filename, statbuf.st_size, wanted_size);
214 /* We didn't create it, so just try opening it again */
215 _wapi_handle_spin (100);
223 static gboolean check_disabled (void)
225 if (_wapi_shm_disabled || g_getenv ("MONO_DISABLE_SHM")) {
226 const char* val = g_getenv ("MONO_DISABLE_SHM");
227 if (val == NULL || *val == '1' || *val == 'y' || *val == 'Y') {
228 _wapi_shm_disabled = TRUE;
232 return(_wapi_shm_disabled);
237 * @success: Was it a success
239 * Attach to the shared memory file or create it if it did not exist.
240 * Returns the memory area the file was mmapped to.
242 gpointer _wapi_shm_attach (_wapi_shm_t type)
247 gchar *filename=_wapi_shm_file (type);
252 size = sizeof(struct _WapiHandleSharedLayout);
255 case WAPI_SHM_FILESHARE:
256 size = sizeof(struct _WapiFileShareLayout);
259 g_error ("Invalid type in _wapi_shm_attach ()");
263 if (check_disabled ()) {
264 return g_malloc0 (size);
267 fd = _wapi_shm_file_open (filename, size);
269 g_critical ("%s: shared file [%s] open error", __func__,
274 if (fstat (fd, &statbuf)==-1) {
275 g_critical ("%s: fstat error: %s", __func__,
281 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
283 if (shm_seg == MAP_FAILED) {
284 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
286 if (shm_seg == MAP_FAILED) {
287 g_critical ("%s: mmap error: %s", __func__, g_strerror (errno));
297 static void shm_semaphores_init (void)
302 struct _WapiHandleSharedLayout *tmp_shared;
304 /* Yet more barmy API - this union is a well-defined parameter
305 * in a syscall, yet I still have to define it here as it
306 * doesn't appear in a header
310 struct semid_ds *buf;
313 ushort def_vals[_WAPI_SHARED_SEM_COUNT];
317 for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++) {
321 /* Process count must start at '0' - the 1 for all the others
322 * sets the semaphore to "unlocked"
324 def_vals[_WAPI_SHARED_SEM_PROCESS_COUNT] = 0;
326 defs.array = def_vals;
328 /* Temporarily attach the shared data so we can read the
329 * semaphore key. We release this mapping and attach again
330 * after getting the semaphores to avoid a race condition
331 * where a terminating process can delete the shared files
332 * between a new process attaching the file and getting access
333 * to the semaphores (which increments the process count,
334 * preventing destruction of the shared data...)
336 tmp_shared = _wapi_shm_attach (WAPI_SHM_DATA);
337 g_assert (tmp_shared != NULL);
339 key = ftok (_wapi_shm_file (WAPI_SHM_DATA), 'M');
343 oldkey = tmp_shared->sem_key;
347 g_message ("%s: Creating with new key (0x%x)", __func__, key);
350 /* The while loop attempts to make some sense of the
351 * bonkers 'think of a random number' method of
352 * picking a key without collision with other
355 while ((_wapi_sem_id = semget (key, _WAPI_SHARED_SEM_COUNT,
356 IPC_CREAT | IPC_EXCL | 0600)) == -1) {
357 if (errno == ENOMEM) {
358 g_error ("%s: semget error: %s", __func__,
360 } else if (errno == ENOSPC) {
361 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));
362 } else if (errno != EEXIST) {
364 g_warning ("%s: semget error: %s key 0x%x - trying again", __func__,
365 g_strerror (errno), key);
370 g_message ("%s: Got (%s), trying with new key (0x%x)",
371 __func__, g_strerror (errno), key);
374 /* Got a semaphore array, so initialise it and install
375 * the key into the shared memory
378 if (semctl (_wapi_sem_id, 0, SETALL, defs) == -1) {
380 g_warning ("%s: semctl init error: %s - trying again", __func__, g_strerror (errno));
382 /* Something went horribly wrong, so try
383 * getting a new set from scratch
385 semctl (_wapi_sem_id, 0, IPC_RMID);
389 if (InterlockedCompareExchange (&tmp_shared->sem_key,
391 /* Someone else created one and installed the
392 * key while we were working, so delete the
393 * array we created and fall through to the
394 * 'key already known' case.
396 semctl (_wapi_sem_id, 0, IPC_RMID);
397 oldkey = tmp_shared->sem_key;
399 /* We've installed this semaphore set's key into
407 g_message ("%s: Trying with old key 0x%x", __func__, oldkey);
410 _wapi_sem_id = semget (oldkey, _WAPI_SHARED_SEM_COUNT, 0600);
411 if (_wapi_sem_id == -1) {
413 g_warning ("%s: semget error opening old key 0x%x (%s) - trying again",
414 __func__, oldkey,g_strerror (errno));
416 /* Someone must have deleted the semaphore set, so
417 * blow away the bad key and try again
419 InterlockedCompareExchange (&tmp_shared->sem_key, 0, oldkey);
425 /* Increment the usage count of this semaphore set */
426 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
427 g_assert (thr_ret == 0);
430 g_message ("%s: Incrementing the process count (%d)", __func__, _wapi_getpid ());
433 /* We only ever _unlock_ this semaphore, letting the kernel
434 * restore (ie decrement) this unlock when this process exits.
435 * We lock another semaphore around it so we can serialise
436 * access when we're testing the value of this semaphore when
437 * we exit cleanly, so we can delete the whole semaphore set.
439 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT);
442 g_message ("%s: Process count is now %d (%d)", __func__, semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT, GETVAL), _wapi_getpid ());
445 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
447 if (_wapi_shm_disabled)
450 munmap (tmp_shared, sizeof(struct _WapiHandleSharedLayout));
453 static mono_mutex_t noshm_sems[_WAPI_SHARED_SEM_COUNT] = {MONO_MUTEX_INITIALIZER};
455 static void noshm_semaphores_init (void)
457 /* No need to do anything */
460 static void shm_semaphores_remove (void)
466 g_message ("%s: Checking process count (%d)", __func__,
470 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
471 g_assert (thr_ret == 0);
473 proc_count = semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT,
476 g_assert (proc_count > 0);
477 if (proc_count == 1) {
478 /* Just us, so blow away the semaphores and the shared
482 g_message ("%s: Removing semaphores! (%d)", __func__,
486 semctl (_wapi_sem_id, 0, IPC_RMID);
487 unlink (_wapi_shm_file (WAPI_SHM_DATA));
488 unlink (_wapi_shm_file (WAPI_SHM_FILESHARE));
490 /* "else" clause, because there's no point unlocking
491 * the semaphore if we've just blown it away...
493 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
497 static void noshm_semaphores_remove (void)
499 /* No need to do anything */
502 static int shm_sem_lock (int sem)
508 g_message ("%s: locking sem %d", __func__, sem);
513 ops.sem_flg = SEM_UNDO;
517 ret = semop (_wapi_sem_id, &ops, 1);
518 } while (ret == -1 && errno == EINTR);
521 /* EINVAL covers the case when the semaphore was
522 * deleted before we started the semop
524 if (errno == EIDRM || errno == EINVAL) {
525 /* Someone blew away this semaphore set, so
526 * get a new one and try again
529 g_message ("%s: Reinitialising the semaphores!",
533 _wapi_shm_semaphores_init ();
537 /* Turn this into a pthreads-style return value */
542 g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
548 static int noshm_sem_lock (int sem)
553 g_message ("%s: locking nosem %d", __func__, sem);
556 ret = mono_mutex_lock (&noshm_sems[sem]);
561 static int shm_sem_trylock (int sem)
567 g_message ("%s: trying to lock sem %d", __func__, sem);
572 ops.sem_flg = IPC_NOWAIT | SEM_UNDO;
576 ret = semop (_wapi_sem_id, &ops, 1);
577 } while (ret == -1 && errno == EINTR);
580 /* EINVAL covers the case when the semaphore was
581 * deleted before we started the semop
583 if (errno == EIDRM || errno == EINVAL) {
584 /* Someone blew away this semaphore set, so
585 * get a new one and try again
588 g_message ("%s: Reinitialising the semaphores!",
592 _wapi_shm_semaphores_init ();
596 /* Turn this into a pthreads-style return value */
601 /* But pthreads uses this code instead */
606 g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
612 static int noshm_sem_trylock (int sem)
617 g_message ("%s: trying to lock nosem %d", __func__, sem);
620 ret = mono_mutex_trylock (&noshm_sems[sem]);
625 static int shm_sem_unlock (int sem)
631 g_message ("%s: unlocking sem %d", __func__, sem);
636 ops.sem_flg = SEM_UNDO;
640 ret = semop (_wapi_sem_id, &ops, 1);
641 } while (ret == -1 && errno == EINTR);
644 /* EINVAL covers the case when the semaphore was
645 * deleted before we started the semop
647 if (errno == EIDRM || errno == EINVAL) {
648 /* Someone blew away this semaphore set, so
649 * get a new one and try again (we can't just
650 * assume that the semaphore is now unlocked)
653 g_message ("%s: Reinitialising the semaphores!",
657 _wapi_shm_semaphores_init ();
661 /* Turn this into a pthreads-style return value */
666 g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
672 static int noshm_sem_unlock (int sem)
677 g_message ("%s: unlocking nosem %d", __func__, sem);
680 ret = mono_mutex_unlock (&noshm_sems[sem]);
685 void _wapi_shm_semaphores_init (void)
687 if (check_disabled ()) {
688 noshm_semaphores_init ();
690 shm_semaphores_init ();
694 void _wapi_shm_semaphores_remove (void)
696 if (_wapi_shm_disabled) {
697 noshm_semaphores_remove ();
699 shm_semaphores_remove ();
703 int _wapi_shm_sem_lock (int sem)
705 if (_wapi_shm_disabled) {
706 return(noshm_sem_lock (sem));
708 return(shm_sem_lock (sem));
712 int _wapi_shm_sem_trylock (int sem)
714 if (_wapi_shm_disabled) {
715 return(noshm_sem_trylock (sem));
717 return(shm_sem_trylock (sem));
721 int _wapi_shm_sem_unlock (int sem)
723 if (_wapi_shm_disabled) {
724 return(noshm_sem_unlock (sem));
726 return(shm_sem_unlock (sem));