2006-06-14 Dick Porter <dick@ximian.com>
[mono.git] / mono / io-layer / shared.c
1 /*
2  * shared.c:  Shared memory handling, and daemon launching
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *
7  * (C) 2002-2006 Novell, Inc.
8  */
9
10
11 #include <config.h>
12 #include <glib.h>
13 #include <stdio.h>
14 #include <fcntl.h>
15 #include <unistd.h>
16 #include <sys/mman.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <errno.h>
20 #include <string.h>
21 #include <sys/ipc.h>
22 #include <sys/sem.h>
23 #include <sys/utsname.h>
24
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>
29
30 #undef DEBUG
31
32 static gchar *_wapi_shm_file (_wapi_shm_t type)
33 {
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;
38         struct utsname ubuf;
39         int ret;
40         int len;
41         
42         ret = uname (&ubuf);
43         if (ret == -1) {
44                 ubuf.machine[0] = '\0';
45                 ubuf.sysname[0] = '\0';
46         }
47
48         fake_name = g_getenv ("MONO_SHARED_HOSTNAME");
49         if (fake_name == NULL) {
50                 if (gethostname(machine_name, sizeof(machine_name)) != 0)
51                         machine_name[0] = '\0';
52         } else {
53                 len = MIN (strlen (fake_name), sizeof (machine_name) - 1);
54                 strncpy (machine_name, fake_name, len);
55                 machine_name [len] = '\0';
56         }
57         
58         switch (type) {
59         case WAPI_SHM_DATA:
60                 name = g_strdup_printf ("shared_data-%s-%s-%s-%d-%d-%d",
61                                         machine_name, ubuf.sysname,
62                                         ubuf.machine,
63                                         (int) sizeof(struct _WapiHandleShared),
64                                         _WAPI_HANDLE_VERSION, 0);
65                 break;
66                 
67         case WAPI_SHM_FILESHARE:
68                 name = g_strdup_printf ("shared_fileshare-%s-%s-%s-%d-%d-%d",
69                                         machine_name, ubuf.sysname,
70                                         ubuf.machine,
71                                         (int) sizeof(struct _WapiFileShare),
72                                         _WAPI_HANDLE_VERSION, 0);
73                 break;
74         }
75
76         /* I don't know how nfs affects mmap.  If mmap() of files on
77          * nfs mounts breaks, then there should be an option to set
78          * the directory.
79          */
80         wapi_dir = getenv ("MONO_SHARED_DIR");
81         if (wapi_dir == NULL) {
82                 filename = g_build_filename (g_get_home_dir (), ".wapi", name,
83                                              NULL);
84         } else {
85                 filename = g_build_filename (wapi_dir, ".wapi", name, NULL);
86         }
87         g_free (name);
88
89         g_snprintf (file, _POSIX_PATH_MAX, "%s", filename);
90         g_free (filename);
91                 
92         /* No need to check if the dir already exists or check
93          * mkdir() errors, because on any error the open() call will
94          * report the problem.
95          */
96         dir = g_path_get_dirname (file);
97         mkdir (dir, 0755);
98         g_free (dir);
99         
100         return(file);
101 }
102
103 static int _wapi_shm_file_open (const gchar *filename, guint32 wanted_size)
104 {
105         int fd;
106         struct stat statbuf;
107         int ret, tries = 0;
108         gboolean created = FALSE;
109         
110 try_again:
111         if (tries++ > 10) {
112                 /* Just give up */
113                 return (-1);
114         } else if (tries > 5) {
115                 /* Break out of a loop */
116                 unlink (filename);
117         }
118         
119         /* No O_CREAT yet, because we need to initialise the file if
120          * we have to create it.
121          */
122         fd = open (filename, O_RDWR, 0600);
123         if (fd == -1 && errno == ENOENT) {
124                 /* OK, its up to us to create it.  O_EXCL to avoid a
125                  * race condition where two processes can
126                  * simultaneously try and create the file
127                  */
128                 fd = open (filename, O_CREAT|O_EXCL|O_RDWR, 0600);
129                 if (fd == -1 && errno == EEXIST) {
130                         /* It's possible that the file was created in
131                          * between finding it didn't exist, and trying
132                          * to create it.  Just try opening it again
133                          */
134                         goto try_again;
135                 } else if (fd == -1) {
136                         g_critical ("%s: shared file [%s] open error: %s",
137                                     __func__, filename, g_strerror (errno));
138                         return(-1);
139                 } else {
140                         /* We created the file, so we need to expand
141                          * the file.
142                          *
143                          * (wanted_size-1, because we're about to
144                          * write the other byte to actually expand the
145                          * file.)
146                          */
147                         if (lseek (fd, wanted_size-1, SEEK_SET) == -1) {
148                                 g_critical ("%s: shared file [%s] lseek error: %s", __func__, filename, g_strerror (errno));
149                                 close (fd);
150                                 unlink (filename);
151                                 return(-1);
152                         }
153                         
154                         do {
155                                 ret = write (fd, "", 1);
156                         } while (ret == -1 && errno == EINTR);
157                                 
158                         if (ret == -1) {
159                                 g_critical ("%s: shared file [%s] write error: %s", __func__, filename, g_strerror (errno));
160                                 close (fd);
161                                 unlink (filename);
162                                 return(-1);
163                         }
164                         
165                         created = TRUE;
166
167                         /* The contents of the file is set to all
168                          * zero, because it is opened up with lseek,
169                          * so we don't need to do any more
170                          * initialisation here
171                          */
172                 }
173         } else if (fd == -1) {
174                 g_critical ("%s: shared file [%s] open error: %s", __func__,
175                             filename, g_strerror (errno));
176                 return(-1);
177         }
178         
179         /* Use stat to find the file size (instead of hard coding it)
180          * because we can expand the file later if needed (for more
181          * handles or scratch space.)
182          */
183         if (fstat (fd, &statbuf) == -1) {
184                 g_critical ("%s: fstat error: %s", __func__,
185                             g_strerror (errno));
186                 if (created == TRUE) {
187                         unlink (filename);
188                 }
189                 close (fd);
190                 return(-1);
191         }
192
193         if (statbuf.st_size < wanted_size) {
194                 close (fd);
195                 if (created == TRUE) {
196 #ifdef HAVE_LARGE_FILE_SUPPORT
197                         /* Keep gcc quiet... */
198                         g_critical ("%s: shared file [%s] is not big enough! (found %lld, need %d bytes)", __func__, filename, statbuf.st_size, wanted_size);
199 #else
200                         g_critical ("%s: shared file [%s] is not big enough! (found %ld, need %d bytes)", __func__, filename, statbuf.st_size, wanted_size);
201 #endif
202                         unlink (filename);
203                         return(-1);
204                 } else {
205                         /* We didn't create it, so just try opening it again */
206                         _wapi_handle_spin (100);
207                         goto try_again;
208                 }
209         }
210         
211         return(fd);
212 }
213
214 /*
215  * _wapi_shm_attach:
216  * @success: Was it a success
217  *
218  * Attach to the shared memory file or create it if it did not exist.
219  * Returns the memory area the file was mmapped to.
220  */
221 gpointer _wapi_shm_attach (_wapi_shm_t type)
222 {
223         gpointer shm_seg;
224         int fd;
225         struct stat statbuf;
226         gchar *filename=_wapi_shm_file (type);
227         guint32 size;
228         
229         switch(type) {
230         case WAPI_SHM_DATA:
231                 size = sizeof(struct _WapiHandleSharedLayout);
232                 break;
233                 
234         case WAPI_SHM_FILESHARE:
235                 size = sizeof(struct _WapiFileShareLayout);
236                 break;
237         }
238         
239         fd = _wapi_shm_file_open (filename, size);
240         if (fd == -1) {
241                 g_critical ("%s: shared file [%s] open error", __func__,
242                             filename);
243                 return(NULL);
244         }
245         
246         if (fstat (fd, &statbuf)==-1) {
247                 g_critical ("%s: fstat error: %s", __func__,
248                             g_strerror (errno));
249                 close (fd);
250                 return(NULL);
251         }
252         
253         shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
254                         MAP_SHARED, fd, 0);
255         if (shm_seg == MAP_FAILED) {
256                 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
257                         MAP_PRIVATE, fd, 0);
258                 if (shm_seg == MAP_FAILED) {
259                         g_critical ("%s: mmap error: %s", __func__, g_strerror (errno));
260                         close (fd);
261                         return(NULL);
262                 }
263         }
264                 
265         close (fd);
266         return(shm_seg);
267 }
268
269 void _wapi_shm_semaphores_init ()
270 {
271         key_t key;
272         key_t oldkey;
273         int thr_ret;
274         struct _WapiHandleSharedLayout *tmp_shared;
275         
276         /* Yet more barmy API - this union is a well-defined parameter
277          * in a syscall, yet I still have to define it here as it
278          * doesn't appear in a header
279          */
280         union semun {
281                 int val;
282                 struct semid_ds *buf;
283                 ushort *array;
284         } defs;
285         ushort def_vals[_WAPI_SHARED_SEM_COUNT];
286         int i;
287         int retries = 0;
288         
289         for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++) {
290                 def_vals[i] = 1;
291         }
292 #ifdef NEXT_VERSION_INC
293         /* Process count must start at '0' - the 1 for all the others
294          * sets the semaphore to "unlocked"
295          */
296         def_vals[_WAPI_SHARED_SEM_PROCESS_COUNT] = 0;
297 #endif
298         
299         defs.array = def_vals;
300         
301         /* Temporarily attach the shared data so we can read the
302          * semaphore key.  We release this mapping and attach again
303          * after getting the semaphores to avoid a race condition
304          * where a terminating process can delete the shared files
305          * between a new process attaching the file and getting access
306          * to the semaphores (which increments the process count,
307          * preventing destruction of the shared data...)
308          */
309         tmp_shared = _wapi_shm_attach (WAPI_SHM_DATA);
310         g_assert (tmp_shared != NULL);
311         
312         key = ftok (_wapi_shm_file (WAPI_SHM_DATA), 'M');
313
314 again:
315         retries++;
316         oldkey = tmp_shared->sem_key;
317
318         if (oldkey == 0) {
319 #ifdef DEBUG
320                 g_message ("%s: Creating with new key (0x%x)", __func__, key);
321 #endif
322
323                 /* The while loop attempts to make some sense of the
324                  * bonkers 'think of a random number' method of
325                  * picking a key without collision with other
326                  * applications
327                  */
328                 while ((_wapi_sem_id = semget (key, _WAPI_SHARED_SEM_COUNT,
329                                                IPC_CREAT | IPC_EXCL | 0600)) == -1) {
330                         if (errno == ENOMEM) {
331                                 g_critical ("%s: semget error: %s", __func__,
332                                             g_strerror (errno));
333                         } else if (errno == ENOSPC) {
334                                 g_critical ("%s: semget error: %s.  Try deleting some semaphores with ipcs and ipcrm", __func__, g_strerror (errno));
335                         } else if (errno != EEXIST) {
336                                 if (retries > 3)
337                                         g_warning ("%s: semget error: %s key 0x%x - trying again", __func__,
338                                                         g_strerror (errno), key);
339                         }
340                         
341                         key++;
342 #ifdef DEBUG
343                         g_message ("%s: Got (%s), trying with new key (0x%x)",
344                                    __func__, g_strerror (errno), key);
345 #endif
346                 }
347                 /* Got a semaphore array, so initialise it and install
348                  * the key into the shared memory
349                  */
350                 
351                 if (semctl (_wapi_sem_id, 0, SETALL, defs) == -1) {
352                         if (retries > 3)
353                                 g_warning ("%s: semctl init error: %s - trying again", __func__, g_strerror (errno));
354
355                         /* Something went horribly wrong, so try
356                          * getting a new set from scratch
357                          */
358                         semctl (_wapi_sem_id, 0, IPC_RMID);
359                         goto again;
360                 }
361
362                 if (InterlockedCompareExchange (&tmp_shared->sem_key,
363                                                 key, 0) != 0) {
364                         /* Someone else created one and installed the
365                          * key while we were working, so delete the
366                          * array we created and fall through to the
367                          * 'key already known' case.
368                          */
369                         semctl (_wapi_sem_id, 0, IPC_RMID);
370                         oldkey = tmp_shared->sem_key;
371                 } else {
372                         /* We've installed this semaphore set's key into
373                          * the shared memory
374                          */
375                         goto done;
376                 }
377         }
378         
379 #ifdef DEBUG
380         g_message ("%s: Trying with old key 0x%x", __func__, oldkey);
381 #endif
382
383         _wapi_sem_id = semget (oldkey, _WAPI_SHARED_SEM_COUNT, 0600);
384         if (_wapi_sem_id == -1) {
385                 if (retries > 3)
386                         g_warning ("%s: semget error opening old key 0x%x (%s) - trying again",
387                                         __func__, oldkey,g_strerror (errno));
388
389                 /* Someone must have deleted the semaphore set, so
390                  * blow away the bad key and try again
391                  */
392                 InterlockedCompareExchange (&tmp_shared->sem_key, 0, oldkey);
393                 
394                 goto again;
395         }
396
397   done:
398         /* Increment the usage count of this semaphore set */
399         thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
400         g_assert (thr_ret == 0);
401         
402 #ifdef DEBUG
403         g_message ("%s: Incrementing the process count (%d)", __func__, _wapi_getpid ());
404 #endif
405
406         /* We only ever _unlock_ this semaphore, letting the kernel
407          * restore (ie decrement) this unlock when this process exits.
408          * We lock another semaphore around it so we can serialise
409          * access when we're testing the value of this semaphore when
410          * we exit cleanly, so we can delete the whole semaphore set.
411          */
412         _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT);
413
414 #ifdef DEBUG
415         g_message ("%s: Process count is now %d (%d)", __func__, semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT, GETVAL), _wapi_getpid ());
416 #endif
417         
418         _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
419
420         munmap (tmp_shared, sizeof(struct _WapiHandleSharedLayout));
421 }
422
423 void _wapi_shm_semaphores_remove (void)
424 {
425         int thr_ret;
426         int proc_count;
427         
428 #ifdef DEBUG
429         g_message ("%s: Checking process count (%d)", __func__,
430                    _wapi_getpid ());
431 #endif
432         
433         thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
434         g_assert (thr_ret == 0);
435         
436         proc_count = semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT,
437                              GETVAL);
438 #ifdef NEXT_VERSION_INC
439         g_assert (proc_count > 0);
440         if (proc_count == 1) {
441 #else
442         /* Compatibility - the semaphore was initialised to '1' (which
443          * normally means 'unlocked'.  Instead of fixing that right
444          * now, which would mean a shared file version increment, just
445          * cope with the value starting too high for now.  Fix this
446          * next time I have to change the file version.
447          */
448         g_assert (proc_count > 1);
449         if (proc_count == 2) {
450 #endif
451                 /* Just us, so blow away the semaphores and the shared
452                  * files
453                  */
454 #ifdef DEBUG
455                 g_message ("%s: Removing semaphores! (%d)", __func__,
456                            _wapi_getpid ());
457 #endif
458
459                 semctl (_wapi_sem_id, 0, IPC_RMID);
460                 unlink (_wapi_shm_file (WAPI_SHM_DATA));
461                 unlink (_wapi_shm_file (WAPI_SHM_FILESHARE));
462         } else {
463                 /* "else" clause, because there's no point unlocking
464                  * the semaphore if we've just blown it away...
465                  */
466                 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
467         }
468 }
469
470 int _wapi_shm_sem_lock (int sem)
471 {
472         struct sembuf ops;
473         int ret;
474         
475 #ifdef DEBUG
476         g_message ("%s: locking sem %d", __func__, sem);
477 #endif
478
479         ops.sem_num = sem;
480         ops.sem_op = -1;
481         ops.sem_flg = SEM_UNDO;
482         
483   retry:
484         do {
485                 ret = semop (_wapi_sem_id, &ops, 1);
486         } while (ret == -1 && errno == EINTR);
487
488         if (ret == -1) {
489                 /* EINVAL covers the case when the semaphore was
490                  * deleted before we started the semop
491                  */
492                 if (errno == EIDRM || errno == EINVAL) {
493                         /* Someone blew away this semaphore set, so
494                          * get a new one and try again
495                          */
496 #ifdef DEBUG
497                         g_message ("%s: Reinitialising the semaphores!",
498                                    __func__);
499 #endif
500
501                         _wapi_shm_semaphores_init ();
502                         goto retry;
503                 }
504                 
505                 /* Turn this into a pthreads-style return value */
506                 ret = errno;
507         }
508         
509 #ifdef DEBUG
510         g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
511 #endif
512         
513         return(ret);
514 }
515
516 int _wapi_shm_sem_trylock (int sem)
517 {
518         struct sembuf ops;
519         int ret;
520         
521 #ifdef DEBUG
522         g_message ("%s: trying to lock sem %d", __func__, sem);
523 #endif
524         
525         ops.sem_num = sem;
526         ops.sem_op = -1;
527         ops.sem_flg = IPC_NOWAIT | SEM_UNDO;
528         
529   retry:
530         do {
531                 ret = semop (_wapi_sem_id, &ops, 1);
532         } while (ret == -1 && errno == EINTR);
533
534         if (ret == -1) {
535                 /* EINVAL covers the case when the semaphore was
536                  * deleted before we started the semop
537                  */
538                 if (errno == EIDRM || errno == EINVAL) {
539                         /* Someone blew away this semaphore set, so
540                          * get a new one and try again
541                          */
542 #ifdef DEBUG
543                         g_message ("%s: Reinitialising the semaphores!",
544                                    __func__);
545 #endif
546
547                         _wapi_shm_semaphores_init ();
548                         goto retry;
549                 }
550                 
551                 /* Turn this into a pthreads-style return value */
552                 ret = errno;
553         }
554         
555         if (ret == EAGAIN) {
556                 /* But pthreads uses this code instead */
557                 ret = EBUSY;
558         }
559         
560 #ifdef DEBUG
561         g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
562 #endif
563         
564         return(ret);
565 }
566
567 int _wapi_shm_sem_unlock (int sem)
568 {
569         struct sembuf ops;
570         int ret;
571         
572 #ifdef DEBUG
573         g_message ("%s: unlocking sem %d", __func__, sem);
574 #endif
575         
576         ops.sem_num = sem;
577         ops.sem_op = 1;
578         ops.sem_flg = SEM_UNDO;
579         
580   retry:
581         do {
582                 ret = semop (_wapi_sem_id, &ops, 1);
583         } while (ret == -1 && errno == EINTR);
584
585         if (ret == -1) {
586                 /* EINVAL covers the case when the semaphore was
587                  * deleted before we started the semop
588                  */
589                 if (errno == EIDRM || errno == EINVAL) {
590                         /* Someone blew away this semaphore set, so
591                          * get a new one and try again (we can't just
592                          * assume that the semaphore is now unlocked)
593                          */
594 #ifdef DEBUG
595                         g_message ("%s: Reinitialising the semaphores!",
596                                    __func__);
597 #endif
598
599                         _wapi_shm_semaphores_init ();
600                         goto retry;
601                 }
602                 
603                 /* Turn this into a pthreads-style return value */
604                 ret = errno;
605         }
606         
607 #ifdef DEBUG
608         g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
609 #endif
610
611         return(ret);
612 }
613