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);
219 * @success: Was it a success
221 * Attach to the shared memory file or create it if it did not exist.
222 * Returns the memory area the file was mmapped to.
224 gpointer _wapi_shm_attach (_wapi_shm_t type)
229 gchar *filename=_wapi_shm_file (type);
234 size = sizeof(struct _WapiHandleSharedLayout);
237 case WAPI_SHM_FILESHARE:
238 size = sizeof(struct _WapiFileShareLayout);
242 fd = _wapi_shm_file_open (filename, size);
244 g_critical ("%s: shared file [%s] open error", __func__,
249 if (fstat (fd, &statbuf)==-1) {
250 g_critical ("%s: fstat error: %s", __func__,
256 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
258 if (shm_seg == MAP_FAILED) {
259 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
261 if (shm_seg == MAP_FAILED) {
262 g_critical ("%s: mmap error: %s", __func__, g_strerror (errno));
272 void _wapi_shm_semaphores_init ()
277 struct _WapiHandleSharedLayout *tmp_shared;
279 /* Yet more barmy API - this union is a well-defined parameter
280 * in a syscall, yet I still have to define it here as it
281 * doesn't appear in a header
285 struct semid_ds *buf;
288 ushort def_vals[_WAPI_SHARED_SEM_COUNT];
292 for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++) {
296 /* Process count must start at '0' - the 1 for all the others
297 * sets the semaphore to "unlocked"
299 def_vals[_WAPI_SHARED_SEM_PROCESS_COUNT] = 0;
301 defs.array = def_vals;
303 /* Temporarily attach the shared data so we can read the
304 * semaphore key. We release this mapping and attach again
305 * after getting the semaphores to avoid a race condition
306 * where a terminating process can delete the shared files
307 * between a new process attaching the file and getting access
308 * to the semaphores (which increments the process count,
309 * preventing destruction of the shared data...)
311 tmp_shared = _wapi_shm_attach (WAPI_SHM_DATA);
312 g_assert (tmp_shared != NULL);
314 key = ftok (_wapi_shm_file (WAPI_SHM_DATA), 'M');
318 oldkey = tmp_shared->sem_key;
322 g_message ("%s: Creating with new key (0x%x)", __func__, key);
325 /* The while loop attempts to make some sense of the
326 * bonkers 'think of a random number' method of
327 * picking a key without collision with other
330 while ((_wapi_sem_id = semget (key, _WAPI_SHARED_SEM_COUNT,
331 IPC_CREAT | IPC_EXCL | 0600)) == -1) {
332 if (errno == ENOMEM) {
333 g_error ("%s: semget error: %s", __func__,
335 } else if (errno == ENOSPC) {
336 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));
337 } else if (errno != EEXIST) {
339 g_warning ("%s: semget error: %s key 0x%x - trying again", __func__,
340 g_strerror (errno), key);
345 g_message ("%s: Got (%s), trying with new key (0x%x)",
346 __func__, g_strerror (errno), key);
349 /* Got a semaphore array, so initialise it and install
350 * the key into the shared memory
353 if (semctl (_wapi_sem_id, 0, SETALL, defs) == -1) {
355 g_warning ("%s: semctl init error: %s - trying again", __func__, g_strerror (errno));
357 /* Something went horribly wrong, so try
358 * getting a new set from scratch
360 semctl (_wapi_sem_id, 0, IPC_RMID);
364 if (InterlockedCompareExchange (&tmp_shared->sem_key,
366 /* Someone else created one and installed the
367 * key while we were working, so delete the
368 * array we created and fall through to the
369 * 'key already known' case.
371 semctl (_wapi_sem_id, 0, IPC_RMID);
372 oldkey = tmp_shared->sem_key;
374 /* We've installed this semaphore set's key into
382 g_message ("%s: Trying with old key 0x%x", __func__, oldkey);
385 _wapi_sem_id = semget (oldkey, _WAPI_SHARED_SEM_COUNT, 0600);
386 if (_wapi_sem_id == -1) {
388 g_warning ("%s: semget error opening old key 0x%x (%s) - trying again",
389 __func__, oldkey,g_strerror (errno));
391 /* Someone must have deleted the semaphore set, so
392 * blow away the bad key and try again
394 InterlockedCompareExchange (&tmp_shared->sem_key, 0, oldkey);
400 /* Increment the usage count of this semaphore set */
401 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
402 g_assert (thr_ret == 0);
405 g_message ("%s: Incrementing the process count (%d)", __func__, _wapi_getpid ());
408 /* We only ever _unlock_ this semaphore, letting the kernel
409 * restore (ie decrement) this unlock when this process exits.
410 * We lock another semaphore around it so we can serialise
411 * access when we're testing the value of this semaphore when
412 * we exit cleanly, so we can delete the whole semaphore set.
414 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT);
417 g_message ("%s: Process count is now %d (%d)", __func__, semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT, GETVAL), _wapi_getpid ());
420 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
422 munmap (tmp_shared, sizeof(struct _WapiHandleSharedLayout));
425 void _wapi_shm_semaphores_remove (void)
431 g_message ("%s: Checking process count (%d)", __func__,
435 thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
436 g_assert (thr_ret == 0);
438 proc_count = semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT,
441 g_assert (proc_count > 0);
442 if (proc_count == 1) {
443 /* Just us, so blow away the semaphores and the shared
447 g_message ("%s: Removing semaphores! (%d)", __func__,
451 semctl (_wapi_sem_id, 0, IPC_RMID);
452 unlink (_wapi_shm_file (WAPI_SHM_DATA));
453 unlink (_wapi_shm_file (WAPI_SHM_FILESHARE));
455 /* "else" clause, because there's no point unlocking
456 * the semaphore if we've just blown it away...
458 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
462 int _wapi_shm_sem_lock (int sem)
468 g_message ("%s: locking sem %d", __func__, sem);
473 ops.sem_flg = SEM_UNDO;
477 ret = semop (_wapi_sem_id, &ops, 1);
478 } while (ret == -1 && errno == EINTR);
481 /* EINVAL covers the case when the semaphore was
482 * deleted before we started the semop
484 if (errno == EIDRM || errno == EINVAL) {
485 /* Someone blew away this semaphore set, so
486 * get a new one and try again
489 g_message ("%s: Reinitialising the semaphores!",
493 _wapi_shm_semaphores_init ();
497 /* Turn this into a pthreads-style return value */
502 g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
508 int _wapi_shm_sem_trylock (int sem)
514 g_message ("%s: trying to lock sem %d", __func__, sem);
519 ops.sem_flg = IPC_NOWAIT | SEM_UNDO;
523 ret = semop (_wapi_sem_id, &ops, 1);
524 } while (ret == -1 && errno == EINTR);
527 /* EINVAL covers the case when the semaphore was
528 * deleted before we started the semop
530 if (errno == EIDRM || errno == EINVAL) {
531 /* Someone blew away this semaphore set, so
532 * get a new one and try again
535 g_message ("%s: Reinitialising the semaphores!",
539 _wapi_shm_semaphores_init ();
543 /* Turn this into a pthreads-style return value */
548 /* But pthreads uses this code instead */
553 g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
559 int _wapi_shm_sem_unlock (int sem)
565 g_message ("%s: unlocking sem %d", __func__, sem);
570 ops.sem_flg = SEM_UNDO;
574 ret = semop (_wapi_sem_id, &ops, 1);
575 } while (ret == -1 && errno == EINTR);
578 /* EINVAL covers the case when the semaphore was
579 * deleted before we started the semop
581 if (errno == EIDRM || errno == EINVAL) {
582 /* Someone blew away this semaphore set, so
583 * get a new one and try again (we can't just
584 * assume that the semaphore is now unlocked)
587 g_message ("%s: Reinitialising the semaphores!",
591 _wapi_shm_semaphores_init ();
595 /* Turn this into a pthreads-style return value */
600 g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));