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>
24 #ifdef HAVE_SYS_UTSNAME_H
25 #include <sys/utsname.h>
28 #include <mono/io-layer/wapi.h>
29 #include <mono/io-layer/wapi-private.h>
30 #include <mono/io-layer/shared.h>
31 #include <mono/io-layer/handles-private.h>
34 * Use POSIX shared memory if possible, it is simpler, and it has the advantage that
35 * writes to the shared area does not need to be written to disk, avoiding spinning up
36 * the disk every x secs on laptops.
44 #ifdef DISABLE_SHARED_HANDLES
45 gboolean _wapi_shm_disabled
= TRUE
;
47 gboolean _wapi_shm_disabled
= FALSE
;
51 _wapi_shm_base_name (_wapi_shm_t type
)
54 gchar machine_name
[256];
55 const gchar
*fake_name
;
62 ubuf
.machine
[0] = '\0';
63 ubuf
.sysname
[0] = '\0';
65 g_strdelimit (ubuf
.sysname
, "/", '_');
66 g_strdelimit (ubuf
.machine
, "/", '_');
69 fake_name
= g_getenv ("MONO_SHARED_HOSTNAME");
70 if (fake_name
== NULL
) {
71 if (gethostname(machine_name
, sizeof(machine_name
)) != 0)
72 machine_name
[0] = '\0';
74 len
= MIN (strlen (fake_name
), sizeof (machine_name
) - 1);
75 strncpy (machine_name
, fake_name
, len
);
76 machine_name
[len
] = '\0';
81 name
= g_strdup_printf ("shared_data-%s-%s-%s-%d-%d-%d",
82 machine_name
, ubuf
.sysname
,
84 (int) sizeof(struct _WapiHandleShared
),
85 _WAPI_HANDLE_VERSION
, 0);
88 case WAPI_SHM_FILESHARE
:
89 name
= g_strdup_printf ("shared_fileshare-%s-%s-%s-%d-%d-%d",
90 machine_name
, ubuf
.sysname
,
92 (int) sizeof(struct _WapiFileShare
),
93 _WAPI_HANDLE_VERSION
, 0);
102 static gchar
*_wapi_shm_shm_name (_wapi_shm_t type
)
104 char *base_name
= _wapi_shm_base_name (type
);
106 /* Also add the uid to avoid permission problems */
107 return g_strdup_printf ("/mono-shared-%d-%s", getuid (), base_name
);
111 _wapi_shm_open (const char *filename
, int size
)
115 fd
= shm_open (filename
, O_CREAT
|O_RDWR
, S_IRUSR
|S_IWUSR
|S_IRGRP
);
117 /* Maybe /dev/shm is not mounted */
119 if (ftruncate (fd
, size
) != 0) {
120 perror ("_wapi_shm_open (): ftruncate ()");
121 g_assert_not_reached ();
129 static gchar
*_wapi_shm_file (_wapi_shm_t type
)
131 static gchar file
[_POSIX_PATH_MAX
];
132 gchar
*name
= NULL
, *filename
, *dir
, *wapi_dir
;
134 name
= _wapi_shm_base_name (type
);
136 /* I don't know how nfs affects mmap. If mmap() of files on
137 * nfs mounts breaks, then there should be an option to set
140 wapi_dir
= getenv ("MONO_SHARED_DIR");
141 if (wapi_dir
== NULL
) {
142 filename
= g_build_filename (g_get_home_dir (), ".wapi", name
,
145 filename
= g_build_filename (wapi_dir
, ".wapi", name
, NULL
);
149 g_snprintf (file
, _POSIX_PATH_MAX
, "%s", filename
);
152 /* No need to check if the dir already exists or check
153 * mkdir() errors, because on any error the open() call will
154 * report the problem.
156 dir
= g_path_get_dirname (file
);
163 static int _wapi_shm_file_open (const gchar
*filename
, guint32 wanted_size
)
168 gboolean created
= FALSE
;
175 } else if (tries
> 5) {
176 /* Break out of a loop */
180 /* Make sure future processes can open the shared data files */
181 oldmask
= umask (066);
183 /* No O_CREAT yet, because we need to initialise the file if
184 * we have to create it.
186 fd
= open (filename
, O_RDWR
, 0600);
189 if (fd
== -1 && errno
== ENOENT
) {
190 /* OK, its up to us to create it. O_EXCL to avoid a
191 * race condition where two processes can
192 * simultaneously try and create the file
194 oldmask
= umask (066);
195 fd
= open (filename
, O_CREAT
|O_EXCL
|O_RDWR
, 0600);
198 if (fd
== -1 && errno
== EEXIST
) {
199 /* It's possible that the file was created in
200 * between finding it didn't exist, and trying
201 * to create it. Just try opening it again
204 } else if (fd
== -1) {
205 g_critical ("%s: shared file [%s] open error: %s",
206 __func__
, filename
, g_strerror (errno
));
209 /* We created the file, so we need to expand
212 * (wanted_size-1, because we're about to
213 * write the other byte to actually expand the
216 if (lseek (fd
, wanted_size
-1, SEEK_SET
) == -1) {
217 g_critical ("%s: shared file [%s] lseek error: %s", __func__
, filename
, g_strerror (errno
));
224 ret
= write (fd
, "", 1);
225 } while (ret
== -1 && errno
== EINTR
);
228 g_critical ("%s: shared file [%s] write error: %s", __func__
, filename
, g_strerror (errno
));
236 /* The contents of the file is set to all
237 * zero, because it is opened up with lseek,
238 * so we don't need to do any more
239 * initialisation here
242 } else if (fd
== -1) {
243 g_critical ("%s: shared file [%s] open error: %s", __func__
,
244 filename
, g_strerror (errno
));
248 /* Use stat to find the file size (instead of hard coding it)
249 * because we can expand the file later if needed (for more
250 * handles or scratch space.)
252 if (fstat (fd
, &statbuf
) == -1) {
253 g_critical ("%s: fstat error: %s", __func__
,
255 if (created
== TRUE
) {
262 if (statbuf
.st_size
< wanted_size
) {
264 if (created
== TRUE
) {
265 g_critical ("%s: shared file [%s] is not big enough! (found %ld, need %d bytes)", __func__
, filename
, (long)statbuf
.st_size
, wanted_size
);
269 /* We didn't create it, so just try opening it again */
270 _wapi_handle_spin (100);
278 static gboolean
check_disabled (void)
280 if (_wapi_shm_disabled
|| g_getenv ("MONO_DISABLE_SHM")) {
281 const char* val
= g_getenv ("MONO_DISABLE_SHM");
282 if (val
== NULL
|| *val
== '1' || *val
== 'y' || *val
== 'Y') {
283 _wapi_shm_disabled
= TRUE
;
287 return(_wapi_shm_disabled
);
292 * @success: Was it a success
294 * Attach to the shared memory file or create it if it did not exist.
295 * Returns the memory area the file was mmapped to.
297 gpointer
_wapi_shm_attach (_wapi_shm_t type
)
302 gchar
*filename
= _wapi_shm_file (type
);
307 size
= sizeof(struct _WapiHandleSharedLayout
);
310 case WAPI_SHM_FILESHARE
:
311 size
= sizeof(struct _WapiFileShareLayout
);
314 g_error ("Invalid type in _wapi_shm_attach ()");
318 if (check_disabled ()) {
319 return g_malloc0 (size
);
323 fd
= _wapi_shm_open (_wapi_shm_shm_name (type
), size
);
328 /* Fall back to files if POSIX shm fails (for example, because /dev/shm is not mounted */
330 fd
= _wapi_shm_file_open (filename
, size
);
332 g_critical ("%s: shared file [%s] open error", __func__
,
337 if (fstat (fd
, &statbuf
)==-1) {
338 g_critical ("%s: fstat error: %s", __func__
,
344 shm_seg
= mmap (NULL
, statbuf
.st_size
, PROT_READ
|PROT_WRITE
,
346 if (shm_seg
== MAP_FAILED
) {
347 shm_seg
= mmap (NULL
, statbuf
.st_size
, PROT_READ
|PROT_WRITE
,
349 if (shm_seg
== MAP_FAILED
) {
350 g_critical ("%s: mmap error: %s", __func__
, g_strerror (errno
));
360 static void shm_semaphores_init (void)
365 struct _WapiHandleSharedLayout
*tmp_shared
;
367 /* Yet more barmy API - this union is a well-defined parameter
368 * in a syscall, yet I still have to define it here as it
369 * doesn't appear in a header
373 struct semid_ds
*buf
;
376 ushort def_vals
[_WAPI_SHARED_SEM_COUNT
];
380 for (i
= 0; i
< _WAPI_SHARED_SEM_COUNT
; i
++) {
384 /* Process count must start at '0' - the 1 for all the others
385 * sets the semaphore to "unlocked"
387 def_vals
[_WAPI_SHARED_SEM_PROCESS_COUNT
] = 0;
389 defs
.array
= def_vals
;
391 /* Temporarily attach the shared data so we can read the
392 * semaphore key. We release this mapping and attach again
393 * after getting the semaphores to avoid a race condition
394 * where a terminating process can delete the shared files
395 * between a new process attaching the file and getting access
396 * to the semaphores (which increments the process count,
397 * preventing destruction of the shared data...)
399 tmp_shared
= _wapi_shm_attach (WAPI_SHM_DATA
);
400 g_assert (tmp_shared
!= NULL
);
402 key
= ftok (_wapi_shm_file (WAPI_SHM_DATA
), 'M');
406 oldkey
= tmp_shared
->sem_key
;
410 g_message ("%s: Creating with new key (0x%x)", __func__
, key
);
413 /* The while loop attempts to make some sense of the
414 * bonkers 'think of a random number' method of
415 * picking a key without collision with other
418 while ((_wapi_sem_id
= semget (key
, _WAPI_SHARED_SEM_COUNT
,
419 IPC_CREAT
| IPC_EXCL
| 0600)) == -1) {
420 if (errno
== ENOMEM
) {
421 g_error ("%s: semget error: %s", __func__
,
423 } else if (errno
== ENOSPC
) {
424 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
));
425 } else if (errno
!= EEXIST
) {
427 g_warning ("%s: semget error: %s key 0x%x - trying again", __func__
,
428 g_strerror (errno
), key
);
433 g_message ("%s: Got (%s), trying with new key (0x%x)",
434 __func__
, g_strerror (errno
), key
);
437 /* Got a semaphore array, so initialise it and install
438 * the key into the shared memory
441 if (semctl (_wapi_sem_id
, 0, SETALL
, defs
) == -1) {
443 g_warning ("%s: semctl init error: %s - trying again", __func__
, g_strerror (errno
));
445 /* Something went horribly wrong, so try
446 * getting a new set from scratch
448 semctl (_wapi_sem_id
, 0, IPC_RMID
);
452 if (InterlockedCompareExchange (&tmp_shared
->sem_key
,
454 /* Someone else created one and installed the
455 * key while we were working, so delete the
456 * array we created and fall through to the
457 * 'key already known' case.
459 semctl (_wapi_sem_id
, 0, IPC_RMID
);
460 oldkey
= tmp_shared
->sem_key
;
462 /* We've installed this semaphore set's key into
470 g_message ("%s: Trying with old key 0x%x", __func__
, oldkey
);
473 _wapi_sem_id
= semget (oldkey
, _WAPI_SHARED_SEM_COUNT
, 0600);
474 if (_wapi_sem_id
== -1) {
476 g_warning ("%s: semget error opening old key 0x%x (%s) - trying again",
477 __func__
, oldkey
,g_strerror (errno
));
479 /* Someone must have deleted the semaphore set, so
480 * blow away the bad key and try again
482 InterlockedCompareExchange (&tmp_shared
->sem_key
, 0, oldkey
);
488 /* Increment the usage count of this semaphore set */
489 thr_ret
= _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK
);
490 g_assert (thr_ret
== 0);
493 g_message ("%s: Incrementing the process count (%d)", __func__
, _wapi_getpid ());
496 /* We only ever _unlock_ this semaphore, letting the kernel
497 * restore (ie decrement) this unlock when this process exits.
498 * We lock another semaphore around it so we can serialise
499 * access when we're testing the value of this semaphore when
500 * we exit cleanly, so we can delete the whole semaphore set.
502 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT
);
505 g_message ("%s: Process count is now %d (%d)", __func__
, semctl (_wapi_sem_id
, _WAPI_SHARED_SEM_PROCESS_COUNT
, GETVAL
), _wapi_getpid ());
508 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK
);
510 if (_wapi_shm_disabled
)
513 munmap (tmp_shared
, sizeof(struct _WapiHandleSharedLayout
));
516 static mono_mutex_t noshm_sems
[_WAPI_SHARED_SEM_COUNT
];
518 static void noshm_semaphores_init (void)
522 for (i
= 0; i
< _WAPI_SHARED_SEM_COUNT
; i
++) {
523 mono_mutex_init (&noshm_sems
[i
], NULL
);
527 static void shm_semaphores_remove (void)
533 g_message ("%s: Checking process count (%d)", __func__
,
537 thr_ret
= _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK
);
538 g_assert (thr_ret
== 0);
540 proc_count
= semctl (_wapi_sem_id
, _WAPI_SHARED_SEM_PROCESS_COUNT
,
543 g_assert (proc_count
> 0);
544 if (proc_count
== 1) {
545 /* Just us, so blow away the semaphores and the shared
549 g_message ("%s: Removing semaphores! (%d)", __func__
,
553 semctl (_wapi_sem_id
, 0, IPC_RMID
);
555 shm_unlink (_wapi_shm_shm_name (WAPI_SHM_DATA
));
556 shm_unlink (_wapi_shm_shm_name (WAPI_SHM_FILESHARE
));
558 unlink (_wapi_shm_file (WAPI_SHM_DATA
));
559 unlink (_wapi_shm_file (WAPI_SHM_FILESHARE
));
561 /* "else" clause, because there's no point unlocking
562 * the semaphore if we've just blown it away...
564 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK
);
568 static void noshm_semaphores_remove (void)
570 /* No need to do anything */
573 static int shm_sem_lock (int sem
)
579 g_message ("%s: locking sem %d", __func__
, sem
);
584 ops
.sem_flg
= SEM_UNDO
;
588 ret
= semop (_wapi_sem_id
, &ops
, 1);
589 } while (ret
== -1 && errno
== EINTR
);
592 /* EINVAL covers the case when the semaphore was
593 * deleted before we started the semop
595 if (errno
== EIDRM
|| errno
== EINVAL
) {
596 /* Someone blew away this semaphore set, so
597 * get a new one and try again
600 g_message ("%s: Reinitialising the semaphores!",
604 _wapi_shm_semaphores_init ();
608 /* Turn this into a pthreads-style return value */
613 g_message ("%s: returning %d (%s)", __func__
, ret
, g_strerror (ret
));
619 static int noshm_sem_lock (int sem
)
624 g_message ("%s: locking nosem %d", __func__
, sem
);
627 ret
= mono_mutex_lock (&noshm_sems
[sem
]);
632 static int shm_sem_trylock (int sem
)
638 g_message ("%s: trying to lock sem %d", __func__
, sem
);
643 ops
.sem_flg
= IPC_NOWAIT
| SEM_UNDO
;
647 ret
= semop (_wapi_sem_id
, &ops
, 1);
648 } while (ret
== -1 && errno
== EINTR
);
651 /* EINVAL covers the case when the semaphore was
652 * deleted before we started the semop
654 if (errno
== EIDRM
|| errno
== EINVAL
) {
655 /* Someone blew away this semaphore set, so
656 * get a new one and try again
659 g_message ("%s: Reinitialising the semaphores!",
663 _wapi_shm_semaphores_init ();
667 /* Turn this into a pthreads-style return value */
672 /* But pthreads uses this code instead */
677 g_message ("%s: returning %d (%s)", __func__
, ret
, g_strerror (ret
));
683 static int noshm_sem_trylock (int sem
)
688 g_message ("%s: trying to lock nosem %d", __func__
, sem
);
691 ret
= mono_mutex_trylock (&noshm_sems
[sem
]);
696 static int shm_sem_unlock (int sem
)
702 g_message ("%s: unlocking sem %d", __func__
, sem
);
707 ops
.sem_flg
= SEM_UNDO
;
711 ret
= semop (_wapi_sem_id
, &ops
, 1);
712 } while (ret
== -1 && errno
== EINTR
);
715 /* EINVAL covers the case when the semaphore was
716 * deleted before we started the semop
718 if (errno
== EIDRM
|| errno
== EINVAL
) {
719 /* Someone blew away this semaphore set, so
720 * get a new one and try again (we can't just
721 * assume that the semaphore is now unlocked)
724 g_message ("%s: Reinitialising the semaphores!",
728 _wapi_shm_semaphores_init ();
732 /* Turn this into a pthreads-style return value */
737 g_message ("%s: returning %d (%s)", __func__
, ret
, g_strerror (ret
));
743 static int noshm_sem_unlock (int sem
)
748 g_message ("%s: unlocking nosem %d", __func__
, sem
);
751 ret
= mono_mutex_unlock (&noshm_sems
[sem
]);
756 void _wapi_shm_semaphores_init (void)
758 if (check_disabled ()) {
759 noshm_semaphores_init ();
761 shm_semaphores_init ();
765 void _wapi_shm_semaphores_remove (void)
767 if (_wapi_shm_disabled
) {
768 noshm_semaphores_remove ();
770 shm_semaphores_remove ();
774 int _wapi_shm_sem_lock (int sem
)
776 if (_wapi_shm_disabled
) {
777 return(noshm_sem_lock (sem
));
779 return(shm_sem_lock (sem
));
783 int _wapi_shm_sem_trylock (int sem
)
785 if (_wapi_shm_disabled
) {
786 return(noshm_sem_trylock (sem
));
788 return(shm_sem_trylock (sem
));
792 int _wapi_shm_sem_unlock (int sem
)
794 if (_wapi_shm_disabled
) {
795 return(noshm_sem_unlock (sem
));
797 return(shm_sem_unlock (sem
));