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 static gchar *_wapi_shm_file (_wapi_shm_t type)
34 static gchar file[_POSIX_PATH_MAX];
35 gchar *name = NULL, *filename, *dir, *wapi_dir;
36 gchar machine_name[256];
37 const gchar *fake_name;
44 ubuf.machine[0] = '\0';
45 ubuf.sysname[0] = '\0';
47 g_strdelimit (ubuf.sysname, "/", '_');
48 g_strdelimit (ubuf.machine, "/", '_');
51 fake_name = g_getenv ("MONO_SHARED_HOSTNAME");
52 if (fake_name == NULL) {
53 if (gethostname(machine_name, sizeof(machine_name)) != 0)
54 machine_name[0] = '\0';
56 len = MIN (strlen (fake_name), sizeof (machine_name) - 1);
57 strncpy (machine_name, fake_name, len);
58 machine_name [len] = '\0';
63 name = g_strdup_printf ("shared_data-%s-%s-%s-%d-%d-%d",
64 machine_name, ubuf.sysname,
66 (int) sizeof(struct _WapiHandleShared),
67 _WAPI_HANDLE_VERSION, 0);
70 case WAPI_SHM_FILESHARE:
71 name = g_strdup_printf ("shared_fileshare-%s-%s-%s-%d-%d-%d",
72 machine_name, ubuf.sysname,
74 (int) sizeof(struct _WapiFileShare),
75 _WAPI_HANDLE_VERSION, 0);
79 /* I don't know how nfs affects mmap. If mmap() of files on
80 * nfs mounts breaks, then there should be an option to set
83 wapi_dir = getenv ("MONO_SHARED_DIR");
84 if (wapi_dir == NULL) {
85 filename = g_build_filename (g_get_home_dir (), ".wapi", name,
88 filename = g_build_filename (wapi_dir, ".wapi", name, NULL);
92 g_snprintf (file, _POSIX_PATH_MAX, "%s", filename);
95 /* No need to check if the dir already exists or check
96 * mkdir() errors, because on any error the open() call will
99 dir = g_path_get_dirname (file);
106 static int _wapi_shm_file_open (const gchar *filename, guint32 wanted_size)
111 gboolean created = FALSE;
117 } else if (tries > 5) {
118 /* Break out of a loop */
122 /* No O_CREAT yet, because we need to initialise the file if
123 * we have to create it.
125 fd = open (filename, O_RDWR, 0600);
126 if (fd == -1 && errno == ENOENT) {
127 /* OK, its up to us to create it. O_EXCL to avoid a
128 * race condition where two processes can
129 * simultaneously try and create the file
131 fd = open (filename, O_CREAT|O_EXCL|O_RDWR, 0600);
132 if (fd == -1 && errno == EEXIST) {
133 /* It's possible that the file was created in
134 * between finding it didn't exist, and trying
135 * to create it. Just try opening it again
138 } else if (fd == -1) {
139 g_critical ("%s: shared file [%s] open error: %s",
140 __func__, filename, g_strerror (errno));
143 /* We created the file, so we need to expand
146 * (wanted_size-1, because we're about to
147 * write the other byte to actually expand the
150 if (lseek (fd, wanted_size-1, SEEK_SET) == -1) {
151 g_critical ("%s: shared file [%s] lseek error: %s", __func__, filename, g_strerror (errno));
158 ret = write (fd, "", 1);
159 } while (ret == -1 && errno == EINTR);
162 g_critical ("%s: shared file [%s] write error: %s", __func__, filename, g_strerror (errno));
170 /* The contents of the file is set to all
171 * zero, because it is opened up with lseek,
172 * so we don't need to do any more
173 * initialisation here
176 } else if (fd == -1) {
177 g_critical ("%s: shared file [%s] open error: %s", __func__,
178 filename, g_strerror (errno));
182 /* Use stat to find the file size (instead of hard coding it)
183 * because we can expand the file later if needed (for more
184 * handles or scratch space.)
186 if (fstat (fd, &statbuf) == -1) {
187 g_critical ("%s: fstat error: %s", __func__,
189 if (created == TRUE) {
196 if (statbuf.st_size < wanted_size) {
198 if (created == TRUE) {
199 #ifdef HAVE_LARGE_FILE_SUPPORT
200 /* Keep gcc quiet... */
201 g_critical ("%s: shared file [%s] is not big enough! (found %lld, need %d bytes)", __func__, filename, statbuf.st_size, wanted_size);
203 g_critical ("%s: shared file [%s] is not big enough! (found %ld, need %d bytes)", __func__, filename, statbuf.st_size, wanted_size);
208 /* We didn't create it, so just try opening it again */
209 _wapi_handle_spin (100);
217 static gboolean wapi_shm_disabled = 0;
221 * @success: Was it a success
223 * Attach to the shared memory file or create it if it did not exist.
224 * Returns the memory area the file was mmapped to.
226 gpointer _wapi_shm_attach (_wapi_shm_t type)
231 gchar *filename=_wapi_shm_file (type);
236 size = sizeof(struct _WapiHandleSharedLayout);
239 case WAPI_SHM_FILESHARE:
240 size = sizeof(struct _WapiFileShareLayout);
243 g_error ("Invalid type in _wapi_shm_attach ()");
247 if (g_getenv ("MONO_DISABLE_SHM")) {
248 const char* val = g_getenv ("MONO_DISABLE_SHM");
249 if (*val == '1' || *val == 'y' || *val == 'Y') {
250 wapi_shm_disabled = TRUE;
251 return g_malloc0 (size);
255 fd = _wapi_shm_file_open (filename, size);
257 g_critical ("%s: shared file [%s] open error", __func__,
262 if (fstat (fd, &statbuf)==-1) {
263 g_critical ("%s: fstat error: %s", __func__,
269 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
271 if (shm_seg == MAP_FAILED) {
272 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
274 if (shm_seg == MAP_FAILED) {
275 g_critical ("%s: mmap error: %s", __func__, g_strerror (errno));
285 void _wapi_shm_semaphores_init ()
290 struct _WapiHandleSharedLayout *tmp_shared;
292 /* Yet more barmy API - this union is a well-defined parameter
293 * in a syscall, yet I still have to define it here as it
294 * doesn't appear in a header
298 struct semid_ds *buf;
301 ushort def_vals[_WAPI_SHARED_SEM_COUNT];
305 for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++) {
309 /* Process count must start at '0' - the 1 for all the others
310 * sets the semaphore to "unlocked"
312 def_vals[_WAPI_SHARED_SEM_PROCESS_COUNT] = 0;
314 defs.array = def_vals;
316 /* Temporarily attach the shared data so we can read the
317 * semaphore key. We release this mapping and attach again
318 * after getting the semaphores to avoid a race condition
319 * where a terminating process can delete the shared files
320 * between a new process attaching the file and getting access
321 * to the semaphores (which increments the process count,
322 * preventing destruction of the shared data...)
324 tmp_shared = _wapi_shm_attach (WAPI_SHM_DATA);
325 g_assert (tmp_shared != NULL);
327 key = ftok (_wapi_shm_file (WAPI_SHM_DATA), 'M');
331 oldkey = tmp_shared->sem_key;
335 g_message ("%s: Creating with new key (0x%x)", __func__, key);
338 /* The while loop attempts to make some sense of the
339 * bonkers 'think of a random number' method of
340 * picking a key without collision with other
343 while ((_wapi_sem_id = semget (key, _WAPI_SHARED_SEM_COUNT,
344 IPC_CREAT | IPC_EXCL | 0600)) == -1) {
345 if (errno == ENOMEM) {
346 g_error ("%s: semget error: %s", __func__,
348 } else if (errno == ENOSPC) {
349 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));
350 } else if (errno != EEXIST) {
352 g_warning ("%s: semget error: %s key 0x%x - trying again", __func__,
353 g_strerror (errno), key);
358 g_message ("%s: Got (%s), trying with new key (0x%x)",
359 __func__, g_strerror (errno), key);
362 /* Got a semaphore array, so initialise it and install
363 * the key into the shared memory
366 if (semctl (_wapi_sem_id, 0, SETALL, defs) == -1) {
368 g_warning ("%s: semctl init error: %s - trying again", __func__, g_strerror (errno));
370 /* Something went horribly wrong, so try
371 * getting a new set from scratch
373 semctl (_wapi_sem_id, 0, IPC_RMID);
377 if (InterlockedCompareExchange (&tmp_shared->sem_key,
379 /* Someone else created one and installed the
380 * key while we were working, so delete the
381 * array we created and fall through to the
382 * 'key already known' case.
384 semctl (_wapi_sem_id, 0, IPC_RMID);
385 oldkey = tmp_shared->sem_key;
387 /* We've installed this semaphore set's key into
395 g_message ("%s: Trying with old key 0x%x", __func__, oldkey);
398 _wapi_sem_id = semget (oldkey, _WAPI_SHARED_SEM_COUNT, 0600);
399 if (_wapi_sem_id == -1) {
401 g_warning ("%s: semget error opening old key 0x%x (%s) - trying again",
402 __func__, oldkey,g_strerror (errno));
404 /* Someone must have deleted the semaphore set, so
405 * blow away the bad key and try again
407 InterlockedCompareExchange (&tmp_shared->sem_key, 0, oldkey);
413 /* Increment the usage count of this semaphore set */
414 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
415 g_assert (thr_ret == 0);
418 g_message ("%s: Incrementing the process count (%d)", __func__, _wapi_getpid ());
421 /* We only ever _unlock_ this semaphore, letting the kernel
422 * restore (ie decrement) this unlock when this process exits.
423 * We lock another semaphore around it so we can serialise
424 * access when we're testing the value of this semaphore when
425 * we exit cleanly, so we can delete the whole semaphore set.
427 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT);
430 g_message ("%s: Process count is now %d (%d)", __func__, semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT, GETVAL), _wapi_getpid ());
433 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
435 if (wapi_shm_disabled)
438 munmap (tmp_shared, sizeof(struct _WapiHandleSharedLayout));
441 void _wapi_shm_semaphores_remove (void)
447 g_message ("%s: Checking process count (%d)", __func__,
451 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
452 g_assert (thr_ret == 0);
454 proc_count = semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT,
457 g_assert (proc_count > 0);
458 if (proc_count == 1) {
459 /* Just us, so blow away the semaphores and the shared
463 g_message ("%s: Removing semaphores! (%d)", __func__,
467 semctl (_wapi_sem_id, 0, IPC_RMID);
468 unlink (_wapi_shm_file (WAPI_SHM_DATA));
469 unlink (_wapi_shm_file (WAPI_SHM_FILESHARE));
471 /* "else" clause, because there's no point unlocking
472 * the semaphore if we've just blown it away...
474 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
478 int _wapi_shm_sem_lock (int sem)
484 g_message ("%s: locking sem %d", __func__, sem);
489 ops.sem_flg = SEM_UNDO;
493 ret = semop (_wapi_sem_id, &ops, 1);
494 } while (ret == -1 && errno == EINTR);
497 /* EINVAL covers the case when the semaphore was
498 * deleted before we started the semop
500 if (errno == EIDRM || errno == EINVAL) {
501 /* Someone blew away this semaphore set, so
502 * get a new one and try again
505 g_message ("%s: Reinitialising the semaphores!",
509 _wapi_shm_semaphores_init ();
513 /* Turn this into a pthreads-style return value */
518 g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
524 int _wapi_shm_sem_trylock (int sem)
530 g_message ("%s: trying to lock sem %d", __func__, sem);
535 ops.sem_flg = IPC_NOWAIT | SEM_UNDO;
539 ret = semop (_wapi_sem_id, &ops, 1);
540 } while (ret == -1 && errno == EINTR);
543 /* EINVAL covers the case when the semaphore was
544 * deleted before we started the semop
546 if (errno == EIDRM || errno == EINVAL) {
547 /* Someone blew away this semaphore set, so
548 * get a new one and try again
551 g_message ("%s: Reinitialising the semaphores!",
555 _wapi_shm_semaphores_init ();
559 /* Turn this into a pthreads-style return value */
564 /* But pthreads uses this code instead */
569 g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
575 int _wapi_shm_sem_unlock (int sem)
581 g_message ("%s: unlocking sem %d", __func__, sem);
586 ops.sem_flg = SEM_UNDO;
590 ret = semop (_wapi_sem_id, &ops, 1);
591 } while (ret == -1 && errno == EINTR);
594 /* EINVAL covers the case when the semaphore was
595 * deleted before we started the semop
597 if (errno == EIDRM || errno == EINVAL) {
598 /* Someone blew away this semaphore set, so
599 * get a new one and try again (we can't just
600 * assume that the semaphore is now unlocked)
603 g_message ("%s: Reinitialising the semaphores!",
607 _wapi_shm_semaphores_init ();
611 /* Turn this into a pthreads-style return value */
616 g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));