Thu Mar 8 19:42:17 CET 2007 Paolo Molaro <lupus@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         } else {
47                 g_strdelimit (ubuf.sysname, "/", '_');
48                 g_strdelimit (ubuf.machine, "/", '_');
49         }
50
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';
55         } else {
56                 len = MIN (strlen (fake_name), sizeof (machine_name) - 1);
57                 strncpy (machine_name, fake_name, len);
58                 machine_name [len] = '\0';
59         }
60         
61         switch (type) {
62         case WAPI_SHM_DATA:
63                 name = g_strdup_printf ("shared_data-%s-%s-%s-%d-%d-%d",
64                                         machine_name, ubuf.sysname,
65                                         ubuf.machine,
66                                         (int) sizeof(struct _WapiHandleShared),
67                                         _WAPI_HANDLE_VERSION, 0);
68                 break;
69                 
70         case WAPI_SHM_FILESHARE:
71                 name = g_strdup_printf ("shared_fileshare-%s-%s-%s-%d-%d-%d",
72                                         machine_name, ubuf.sysname,
73                                         ubuf.machine,
74                                         (int) sizeof(struct _WapiFileShare),
75                                         _WAPI_HANDLE_VERSION, 0);
76                 break;
77         }
78
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
81          * the directory.
82          */
83         wapi_dir = getenv ("MONO_SHARED_DIR");
84         if (wapi_dir == NULL) {
85                 filename = g_build_filename (g_get_home_dir (), ".wapi", name,
86                                              NULL);
87         } else {
88                 filename = g_build_filename (wapi_dir, ".wapi", name, NULL);
89         }
90         g_free (name);
91
92         g_snprintf (file, _POSIX_PATH_MAX, "%s", filename);
93         g_free (filename);
94                 
95         /* No need to check if the dir already exists or check
96          * mkdir() errors, because on any error the open() call will
97          * report the problem.
98          */
99         dir = g_path_get_dirname (file);
100         mkdir (dir, 0755);
101         g_free (dir);
102         
103         return(file);
104 }
105
106 static int _wapi_shm_file_open (const gchar *filename, guint32 wanted_size)
107 {
108         int fd;
109         struct stat statbuf;
110         int ret, tries = 0;
111         gboolean created = FALSE;
112         
113 try_again:
114         if (tries++ > 10) {
115                 /* Just give up */
116                 return (-1);
117         } else if (tries > 5) {
118                 /* Break out of a loop */
119                 unlink (filename);
120         }
121         
122         /* No O_CREAT yet, because we need to initialise the file if
123          * we have to create it.
124          */
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
130                  */
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
136                          */
137                         goto try_again;
138                 } else if (fd == -1) {
139                         g_critical ("%s: shared file [%s] open error: %s",
140                                     __func__, filename, g_strerror (errno));
141                         return(-1);
142                 } else {
143                         /* We created the file, so we need to expand
144                          * the file.
145                          *
146                          * (wanted_size-1, because we're about to
147                          * write the other byte to actually expand the
148                          * file.)
149                          */
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));
152                                 close (fd);
153                                 unlink (filename);
154                                 return(-1);
155                         }
156                         
157                         do {
158                                 ret = write (fd, "", 1);
159                         } while (ret == -1 && errno == EINTR);
160                                 
161                         if (ret == -1) {
162                                 g_critical ("%s: shared file [%s] write error: %s", __func__, filename, g_strerror (errno));
163                                 close (fd);
164                                 unlink (filename);
165                                 return(-1);
166                         }
167                         
168                         created = TRUE;
169
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
174                          */
175                 }
176         } else if (fd == -1) {
177                 g_critical ("%s: shared file [%s] open error: %s", __func__,
178                             filename, g_strerror (errno));
179                 return(-1);
180         }
181         
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.)
185          */
186         if (fstat (fd, &statbuf) == -1) {
187                 g_critical ("%s: fstat error: %s", __func__,
188                             g_strerror (errno));
189                 if (created == TRUE) {
190                         unlink (filename);
191                 }
192                 close (fd);
193                 return(-1);
194         }
195
196         if (statbuf.st_size < wanted_size) {
197                 close (fd);
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);
202 #else
203                         g_critical ("%s: shared file [%s] is not big enough! (found %ld, need %d bytes)", __func__, filename, statbuf.st_size, wanted_size);
204 #endif
205                         unlink (filename);
206                         return(-1);
207                 } else {
208                         /* We didn't create it, so just try opening it again */
209                         _wapi_handle_spin (100);
210                         goto try_again;
211                 }
212         }
213         
214         return(fd);
215 }
216
217 static gboolean wapi_shm_disabled = 0;
218
219 /*
220  * _wapi_shm_attach:
221  * @success: Was it a success
222  *
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.
225  */
226 gpointer _wapi_shm_attach (_wapi_shm_t type)
227 {
228         gpointer shm_seg;
229         int fd;
230         struct stat statbuf;
231         gchar *filename=_wapi_shm_file (type);
232         guint32 size;
233         
234         switch(type) {
235         case WAPI_SHM_DATA:
236                 size = sizeof(struct _WapiHandleSharedLayout);
237                 break;
238                 
239         case WAPI_SHM_FILESHARE:
240                 size = sizeof(struct _WapiFileShareLayout);
241                 break;
242         default:
243                 g_error ("Invalid type in _wapi_shm_attach ()");
244                 return NULL;
245         }
246
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);
252                 }
253         }
254
255         fd = _wapi_shm_file_open (filename, size);
256         if (fd == -1) {
257                 g_critical ("%s: shared file [%s] open error", __func__,
258                             filename);
259                 return(NULL);
260         }
261         
262         if (fstat (fd, &statbuf)==-1) {
263                 g_critical ("%s: fstat error: %s", __func__,
264                             g_strerror (errno));
265                 close (fd);
266                 return(NULL);
267         }
268         
269         shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
270                         MAP_SHARED, fd, 0);
271         if (shm_seg == MAP_FAILED) {
272                 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
273                         MAP_PRIVATE, fd, 0);
274                 if (shm_seg == MAP_FAILED) {
275                         g_critical ("%s: mmap error: %s", __func__, g_strerror (errno));
276                         close (fd);
277                         return(NULL);
278                 }
279         }
280                 
281         close (fd);
282         return(shm_seg);
283 }
284
285 void _wapi_shm_semaphores_init ()
286 {
287         key_t key;
288         key_t oldkey;
289         int thr_ret;
290         struct _WapiHandleSharedLayout *tmp_shared;
291         
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
295          */
296         union semun {
297                 int val;
298                 struct semid_ds *buf;
299                 ushort *array;
300         } defs;
301         ushort def_vals[_WAPI_SHARED_SEM_COUNT];
302         int i;
303         int retries = 0;
304         
305         for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++) {
306                 def_vals[i] = 1;
307         }
308
309         /* Process count must start at '0' - the 1 for all the others
310          * sets the semaphore to "unlocked"
311          */
312         def_vals[_WAPI_SHARED_SEM_PROCESS_COUNT] = 0;
313         
314         defs.array = def_vals;
315         
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...)
323          */
324         tmp_shared = _wapi_shm_attach (WAPI_SHM_DATA);
325         g_assert (tmp_shared != NULL);
326         
327         key = ftok (_wapi_shm_file (WAPI_SHM_DATA), 'M');
328
329 again:
330         retries++;
331         oldkey = tmp_shared->sem_key;
332
333         if (oldkey == 0) {
334 #ifdef DEBUG
335                 g_message ("%s: Creating with new key (0x%x)", __func__, key);
336 #endif
337
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
341                  * applications
342                  */
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__,
347                                             g_strerror (errno));
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) {
351                                 if (retries > 3)
352                                         g_warning ("%s: semget error: %s key 0x%x - trying again", __func__,
353                                                         g_strerror (errno), key);
354                         }
355                         
356                         key++;
357 #ifdef DEBUG
358                         g_message ("%s: Got (%s), trying with new key (0x%x)",
359                                    __func__, g_strerror (errno), key);
360 #endif
361                 }
362                 /* Got a semaphore array, so initialise it and install
363                  * the key into the shared memory
364                  */
365                 
366                 if (semctl (_wapi_sem_id, 0, SETALL, defs) == -1) {
367                         if (retries > 3)
368                                 g_warning ("%s: semctl init error: %s - trying again", __func__, g_strerror (errno));
369
370                         /* Something went horribly wrong, so try
371                          * getting a new set from scratch
372                          */
373                         semctl (_wapi_sem_id, 0, IPC_RMID);
374                         goto again;
375                 }
376
377                 if (InterlockedCompareExchange (&tmp_shared->sem_key,
378                                                 key, 0) != 0) {
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.
383                          */
384                         semctl (_wapi_sem_id, 0, IPC_RMID);
385                         oldkey = tmp_shared->sem_key;
386                 } else {
387                         /* We've installed this semaphore set's key into
388                          * the shared memory
389                          */
390                         goto done;
391                 }
392         }
393         
394 #ifdef DEBUG
395         g_message ("%s: Trying with old key 0x%x", __func__, oldkey);
396 #endif
397
398         _wapi_sem_id = semget (oldkey, _WAPI_SHARED_SEM_COUNT, 0600);
399         if (_wapi_sem_id == -1) {
400                 if (retries > 3)
401                         g_warning ("%s: semget error opening old key 0x%x (%s) - trying again",
402                                         __func__, oldkey,g_strerror (errno));
403
404                 /* Someone must have deleted the semaphore set, so
405                  * blow away the bad key and try again
406                  */
407                 InterlockedCompareExchange (&tmp_shared->sem_key, 0, oldkey);
408                 
409                 goto again;
410         }
411
412   done:
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);
416         
417 #ifdef DEBUG
418         g_message ("%s: Incrementing the process count (%d)", __func__, _wapi_getpid ());
419 #endif
420
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.
426          */
427         _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT);
428
429 #ifdef DEBUG
430         g_message ("%s: Process count is now %d (%d)", __func__, semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT, GETVAL), _wapi_getpid ());
431 #endif
432         
433         _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
434
435         if (wapi_shm_disabled)
436                 g_free (tmp_shared);
437         else
438                 munmap (tmp_shared, sizeof(struct _WapiHandleSharedLayout));
439 }
440
441 void _wapi_shm_semaphores_remove (void)
442 {
443         int thr_ret;
444         int proc_count;
445         
446 #ifdef DEBUG
447         g_message ("%s: Checking process count (%d)", __func__,
448                    _wapi_getpid ());
449 #endif
450         
451         thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
452         g_assert (thr_ret == 0);
453         
454         proc_count = semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT,
455                              GETVAL);
456
457         g_assert (proc_count > 0);
458         if (proc_count == 1) {
459                 /* Just us, so blow away the semaphores and the shared
460                  * files
461                  */
462 #ifdef DEBUG
463                 g_message ("%s: Removing semaphores! (%d)", __func__,
464                            _wapi_getpid ());
465 #endif
466
467                 semctl (_wapi_sem_id, 0, IPC_RMID);
468                 unlink (_wapi_shm_file (WAPI_SHM_DATA));
469                 unlink (_wapi_shm_file (WAPI_SHM_FILESHARE));
470         } else {
471                 /* "else" clause, because there's no point unlocking
472                  * the semaphore if we've just blown it away...
473                  */
474                 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
475         }
476 }
477
478 int _wapi_shm_sem_lock (int sem)
479 {
480         struct sembuf ops;
481         int ret;
482         
483 #ifdef DEBUG
484         g_message ("%s: locking sem %d", __func__, sem);
485 #endif
486
487         ops.sem_num = sem;
488         ops.sem_op = -1;
489         ops.sem_flg = SEM_UNDO;
490         
491   retry:
492         do {
493                 ret = semop (_wapi_sem_id, &ops, 1);
494         } while (ret == -1 && errno == EINTR);
495
496         if (ret == -1) {
497                 /* EINVAL covers the case when the semaphore was
498                  * deleted before we started the semop
499                  */
500                 if (errno == EIDRM || errno == EINVAL) {
501                         /* Someone blew away this semaphore set, so
502                          * get a new one and try again
503                          */
504 #ifdef DEBUG
505                         g_message ("%s: Reinitialising the semaphores!",
506                                    __func__);
507 #endif
508
509                         _wapi_shm_semaphores_init ();
510                         goto retry;
511                 }
512                 
513                 /* Turn this into a pthreads-style return value */
514                 ret = errno;
515         }
516         
517 #ifdef DEBUG
518         g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
519 #endif
520         
521         return(ret);
522 }
523
524 int _wapi_shm_sem_trylock (int sem)
525 {
526         struct sembuf ops;
527         int ret;
528         
529 #ifdef DEBUG
530         g_message ("%s: trying to lock sem %d", __func__, sem);
531 #endif
532         
533         ops.sem_num = sem;
534         ops.sem_op = -1;
535         ops.sem_flg = IPC_NOWAIT | SEM_UNDO;
536         
537   retry:
538         do {
539                 ret = semop (_wapi_sem_id, &ops, 1);
540         } while (ret == -1 && errno == EINTR);
541
542         if (ret == -1) {
543                 /* EINVAL covers the case when the semaphore was
544                  * deleted before we started the semop
545                  */
546                 if (errno == EIDRM || errno == EINVAL) {
547                         /* Someone blew away this semaphore set, so
548                          * get a new one and try again
549                          */
550 #ifdef DEBUG
551                         g_message ("%s: Reinitialising the semaphores!",
552                                    __func__);
553 #endif
554
555                         _wapi_shm_semaphores_init ();
556                         goto retry;
557                 }
558                 
559                 /* Turn this into a pthreads-style return value */
560                 ret = errno;
561         }
562         
563         if (ret == EAGAIN) {
564                 /* But pthreads uses this code instead */
565                 ret = EBUSY;
566         }
567         
568 #ifdef DEBUG
569         g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
570 #endif
571         
572         return(ret);
573 }
574
575 int _wapi_shm_sem_unlock (int sem)
576 {
577         struct sembuf ops;
578         int ret;
579         
580 #ifdef DEBUG
581         g_message ("%s: unlocking sem %d", __func__, sem);
582 #endif
583         
584         ops.sem_num = sem;
585         ops.sem_op = 1;
586         ops.sem_flg = SEM_UNDO;
587         
588   retry:
589         do {
590                 ret = semop (_wapi_sem_id, &ops, 1);
591         } while (ret == -1 && errno == EINTR);
592
593         if (ret == -1) {
594                 /* EINVAL covers the case when the semaphore was
595                  * deleted before we started the semop
596                  */
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)
601                          */
602 #ifdef DEBUG
603                         g_message ("%s: Reinitialising the semaphores!",
604                                    __func__);
605 #endif
606
607                         _wapi_shm_semaphores_init ();
608                         goto retry;
609                 }
610                 
611                 /* Turn this into a pthreads-style return value */
612                 ret = errno;
613         }
614         
615 #ifdef DEBUG
616         g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
617 #endif
618
619         return(ret);
620 }
621