Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Do not pass a pointer to dynar where a pointer to sem is expected...
[simgrid.git] / src / simix / smx_synchro.c
1 /* Copyright (c) 2007, 2008, 2009, 2010. The SimGrid Team.
2  * All rights reserved.                                                     */
3
4 /* This program is free software; you can redistribute it and/or modify it
5  * under the terms of the license (GNU LGPL) which comes with this package. */
6
7 #include "private.h"
8 #include "xbt/log.h"
9
10
11 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(simix_synchro, simix,
12                                 "Logging specific to SIMIX (synchronization)");
13
14
15 /****************************** Synchronization *******************************/
16
17 /*********************************** Mutex ************************************/
18
19 /**
20  * \brief Initialize a mutex.
21  *
22  * Allocs and creates the data for the mutex. It have to be called before the utilisation of the mutex.
23  * \return A mutex
24  */
25 smx_mutex_t SIMIX_mutex_init()
26 {
27   smx_mutex_t m = xbt_new0(s_smx_mutex_t, 1);
28   s_smx_process_t p;            /* useful to initialize sleeping swag */
29   /* structures initialization */
30   m->refcount = 0;
31   m->sleeping = xbt_swag_new(xbt_swag_offset(p, synchro_hookup));
32   return m;
33 }
34
35 /**
36  * \brief Locks a mutex.
37  *
38  * Tries to lock a mutex, if the mutex isn't used yet, the process can continue its execution, else it'll be blocked here. You have to call #SIMIX_mutex_unlock to free the mutex.
39  * \param mutex The mutex
40  */
41 void SIMIX_mutex_lock(smx_mutex_t mutex)
42 {
43   smx_process_t self = SIMIX_process_self();
44   xbt_assert0((mutex != NULL), "Invalid parameters");
45
46
47   if (mutex->refcount) {
48     /* somebody using the mutex, block */
49     xbt_swag_insert(self, mutex->sleeping);
50     self->mutex = mutex;
51     /* wait for some process make the unlock and wake up me from mutex->sleeping */
52     SIMIX_process_yield();
53     self->mutex = NULL;
54
55     /* verify if the process was suspended */
56     while (self->suspended) {
57       SIMIX_process_yield();
58     }
59
60     mutex->refcount = 1;
61   } else {
62     /* mutex free */
63     mutex->refcount = 1;
64   }
65   return;
66 }
67
68 /**
69  * \brief Tries to lock a mutex.
70  *
71  * Tries to lock a mutex, return 1 if the mutex is free, 0 else. This function does not block the process if the mutex is used.
72  * \param mutex The mutex
73  * \return 1 - mutex free, 0 - mutex used
74  */
75 XBT_INLINE int SIMIX_mutex_trylock(smx_mutex_t mutex)
76 {
77   xbt_assert0((mutex != NULL), "Invalid parameters");
78
79   if (mutex->refcount)
80     return 0;
81   else {
82     mutex->refcount = 1;
83     return 1;
84   }
85 }
86
87 /**
88  * \brief Unlocks a mutex.
89  *
90  * Unlocks the mutex and wakes up a process blocked on it. If there are no process sleeping, only sets the mutex as free.
91  * \param mutex The mutex
92  */
93 void SIMIX_mutex_unlock(smx_mutex_t mutex)
94 {
95   smx_process_t p;              /*process to wake up */
96
97   xbt_assert0((mutex != NULL), "Invalid parameters");
98
99   if (xbt_swag_size(mutex->sleeping) > 0) {
100     p = xbt_swag_extract(mutex->sleeping);
101     mutex->refcount = 0;
102     xbt_swag_insert(p, simix_global->process_to_run);
103   } else {
104     /* nobody to wake up */
105     mutex->refcount = 0;
106   }
107   return;
108 }
109
110 /**
111  * \brief Destroys a mutex.
112  *
113  * Destroys and frees the mutex's memory. 
114  * \param mutex A mutex
115  */
116 XBT_INLINE void SIMIX_mutex_destroy(smx_mutex_t mutex)
117 {
118   if (mutex == NULL)
119     return;
120   else {
121     xbt_swag_free(mutex->sleeping);
122     xbt_free(mutex);
123     return;
124   }
125 }
126
127 /******************************** Conditional *********************************/
128
129 /**
130  * \brief Initialize a condition.
131  *
132  * Allocates and creates the data for the condition.
133  * It have to be called before the use of the condition.
134  * \return A condition
135  */
136 smx_cond_t SIMIX_cond_init()
137 {
138   smx_cond_t cond = xbt_new0(s_smx_cond_t, 1);
139   s_smx_process_t p;
140
141   cond->sleeping = xbt_swag_new(xbt_swag_offset(p, synchro_hookup));
142   cond->actions = xbt_fifo_new();
143   cond->mutex = NULL;
144   return cond;
145 }
146
147 /**
148  * \brief Signalizes a condition.
149  *
150  * Signalizes a condition and wakes up a sleeping process. If there are no process sleeping, no action is done.
151  * \param cond A condition
152  */
153 void SIMIX_cond_signal(smx_cond_t cond)
154 {
155   smx_process_t proc = NULL;
156   DEBUG1("Signal condition %p", cond);
157   xbt_assert0((cond != NULL), "Invalid parameters");
158
159
160   if (xbt_swag_size(cond->sleeping) >= 1) {
161     proc = xbt_swag_extract(cond->sleeping);
162     xbt_swag_insert(proc, simix_global->process_to_run);
163   }
164
165   return;
166 }
167
168 /**
169  * \brief Waits on a condition.
170  *
171  * Blocks a process until the signal is called. This functions frees the mutex associated and locks it after its execution.
172  * \param cond A condition
173  * \param mutex A mutex
174  */
175 void SIMIX_cond_wait(smx_cond_t cond, smx_mutex_t mutex)
176 {
177   smx_action_t act_sleep;
178
179   DEBUG1("Wait condition %p", cond);
180
181   /* If there is a mutex unlock it */
182   if (mutex != NULL) {
183     cond->mutex = mutex;
184     SIMIX_mutex_unlock(mutex);
185   }
186
187   /* Always create an action null in case there is a host failure */
188   act_sleep = SIMIX_action_sleep(SIMIX_host_self(), -1);
189   SIMIX_action_set_name(act_sleep, bprintf("Wait condition %p", cond));
190   SIMIX_process_self()->waiting_action = act_sleep;
191   SIMIX_register_action_to_condition(act_sleep, cond);
192   __SIMIX_cond_wait(cond);
193   SIMIX_process_self()->waiting_action = NULL;
194   SIMIX_unregister_action_to_condition(act_sleep, cond);
195   SIMIX_action_destroy(act_sleep);
196
197   /* get the mutex again if necessary */
198   if (mutex != NULL)
199     SIMIX_mutex_lock(cond->mutex);
200
201   return;
202 }
203
204 XBT_INLINE xbt_fifo_t SIMIX_cond_get_actions(smx_cond_t cond)
205 {
206   xbt_assert0((cond != NULL), "Invalid parameters");
207   return cond->actions;
208 }
209
210 void __SIMIX_cond_wait(smx_cond_t cond)
211 {
212   smx_process_t self = SIMIX_process_self();
213   xbt_assert0((cond != NULL), "Invalid parameters");
214
215   /* process status */
216
217   self->cond = cond;
218   xbt_swag_insert(self, cond->sleeping);
219   SIMIX_process_yield();
220   self->cond = NULL;
221   while (self->suspended) {
222     SIMIX_process_yield();
223   }
224   return;
225 }
226
227 /**
228  * \brief Waits on a condition with timeout.
229  *
230  * Same behavior of #SIMIX_cond_wait, but waits a maximum time and throws an timeout_error if it happens.
231  * \param cond A condition
232  * \param mutex A mutex
233  * \param max_duration Timeout time
234  */
235 void SIMIX_cond_wait_timeout(smx_cond_t cond, smx_mutex_t mutex,
236                              double max_duration)
237 {
238   smx_action_t act_sleep;
239
240   DEBUG1("Timed wait condition %p", cond);
241
242   /* If there is a mutex unlock it */
243   if (mutex != NULL) {
244     cond->mutex = mutex;
245     SIMIX_mutex_unlock(mutex);
246   }
247
248   if (max_duration >= 0) {
249     act_sleep = SIMIX_action_sleep(SIMIX_host_self(), max_duration);
250     SIMIX_action_set_name(act_sleep,
251                           bprintf
252                           ("Timed wait condition %p (max_duration:%f)",
253                            cond, max_duration));
254     SIMIX_register_action_to_condition(act_sleep, cond);
255     SIMIX_process_self()->waiting_action = act_sleep;
256     __SIMIX_cond_wait(cond);
257     SIMIX_process_self()->waiting_action = NULL;
258     SIMIX_unregister_action_to_condition(act_sleep, cond);
259     if (SIMIX_action_get_state(act_sleep) == SURF_ACTION_DONE) {
260       SIMIX_action_destroy(act_sleep);
261       THROW1(timeout_error, 0, "Condition timeout after %f", max_duration);
262     } else {
263       SIMIX_action_destroy(act_sleep);
264     }
265
266   } else
267     SIMIX_cond_wait(cond, NULL);
268
269   /* get the mutex again if necessary */
270   if (mutex != NULL)
271     SIMIX_mutex_lock(cond->mutex);
272 }
273
274 /**
275  * \brief Broadcasts a condition.
276  *
277  * Signalizes a condition and wakes up ALL sleping process. If there are no process sleeping, no action is done.
278  * \param cond A condition
279  */
280 void SIMIX_cond_broadcast(smx_cond_t cond)
281 {
282   smx_process_t proc = NULL;
283   smx_process_t proc_next = NULL;
284
285   xbt_assert0((cond != NULL), "Invalid parameters");
286
287   DEBUG1("Broadcast condition %p", cond);
288   xbt_swag_foreach_safe(proc, proc_next, cond->sleeping) {
289     xbt_swag_remove(proc, cond->sleeping);
290     xbt_swag_insert(proc, simix_global->process_to_run);
291   }
292 }
293
294 /**
295  * \brief Destroys a contidion.
296  *
297  * Destroys and frees the condition's memory. 
298  * \param cond A condition
299  */
300 void SIMIX_cond_destroy(smx_cond_t cond)
301 {
302   DEBUG1("Destroy condition %p", cond);
303   if (cond == NULL)
304     return;
305   else {
306     xbt_fifo_item_t item = NULL;
307     smx_action_t action = NULL;
308
309     xbt_assert0(xbt_swag_size(cond->sleeping) == 0,
310                 "Cannot destroy conditional since someone is still using it");
311     xbt_swag_free(cond->sleeping);
312
313     DEBUG1("%d actions registered", xbt_fifo_size(cond->actions));
314     __SIMIX_cond_display_actions(cond);
315     xbt_fifo_foreach(cond->actions, item, action, smx_action_t) {
316       SIMIX_unregister_action_to_condition(action, cond);
317     }
318     __SIMIX_cond_display_actions(cond);
319
320     xbt_fifo_free(cond->actions);
321     xbt_free(cond);
322     return;
323   }
324 }
325
326 void SIMIX_cond_display_info(smx_cond_t cond)
327 {
328   if (cond == NULL)
329     return;
330   else {
331     smx_process_t process = NULL;
332
333     INFO0("Blocked process on this condition:");
334     xbt_swag_foreach(process, cond->sleeping) {
335       INFO2("\t %s running on host %s", process->name,
336             process->smx_host->name);
337     }
338   }
339 }
340
341 /* ************************** Semaphores ************************************** */
342 #define SMX_SEM_NOLIMIT 99999
343 /** @brief Initialize a semaphore */
344 smx_sem_t SIMIX_sem_init(int capacity)
345 {
346   smx_sem_t sem = xbt_new0(s_smx_sem_t, 1);
347
348   sem->sleeping = xbt_fifo_new();
349   sem->actions = xbt_fifo_new();
350   sem->capacity = capacity;
351   return sem;
352 }
353
354 /** @brief Destroys a semaphore */
355 void SIMIX_sem_destroy(smx_sem_t sem)
356 {
357   smx_action_t action = NULL;
358   DEBUG1("Destroy semaphore %p", sem);
359   if (sem == NULL)
360     return;
361
362   xbt_assert0(xbt_fifo_size(sem->sleeping) == 0,
363               "Cannot destroy semaphore since someone is still using it");
364   xbt_fifo_free(sem->sleeping);
365
366   DEBUG1("%d actions registered", xbt_fifo_size(sem->actions));
367   while ((action = xbt_fifo_pop(sem->actions)))
368     SIMIX_unregister_action_to_semaphore(action, sem);
369
370   xbt_fifo_free(sem->actions);
371   xbt_free(sem);
372 }
373
374 /** @brief release the semaphore
375  *
376  * The first locked process on this semaphore is unlocked.
377  * If no one was blocked, the semaphore capacity is increased by 1.
378  * */
379 void SIMIX_sem_release(smx_sem_t sem)
380 {
381   smx_process_t proc;
382
383   if (sem->capacity != SMX_SEM_NOLIMIT) {
384     sem->capacity++;
385   }
386   DEBUG1("Sem release semaphore %p", sem);
387   if ((proc = xbt_fifo_shift(sem->sleeping)) != NULL) {
388     xbt_swag_insert(proc, simix_global->process_to_run);
389   }
390 }
391
392 /** @brief make sure the semaphore will never be blocking again
393  *
394  * This function is not really in the semaphore spirit. It makes
395  * sure that the semaphore will never be blocking anymore.
396  *
397  * Releasing and acquiring the semaphore after calling this
398  * function is a noop. Such "broken" semaphores are useful to
399  * implement something between condition variables (with broadcast)
400  * and semaphore (with memory). It's like a semaphore signaled for ever.
401  *
402  * There is no way to reset the semaphore to a more regular state afterward.
403  * */
404 void SIMIX_sem_release_forever(smx_sem_t sem)
405 {
406   smx_process_t proc;
407
408   sem->capacity = SMX_SEM_NOLIMIT;
409   DEBUG1("Broadcast semaphore %p", sem);
410   while ((proc = xbt_fifo_shift(sem->sleeping)) != NULL) {
411     xbt_swag_insert(proc, simix_global->process_to_run);
412   }
413 }
414
415 /**
416  * \brief Low level wait on a semaphore
417  *
418  * This function does not test the capacity of the semaphore and direcly locks
419  * the calling process on the semaphore (until someone call SIMIX_sem_release()
420  * on this semaphore). Do not call this function if you did not attach any action
421  * to this semaphore to be awaken. Note also that you may miss host failure if you
422  * do not attach a dummy action beforehand. SIMIX_sem_acquire does all these
423  * things for you so you it may be preferable to use.
424  */
425 void SIMIX_sem_block_onto(smx_sem_t sem)
426 {
427   smx_process_t self = SIMIX_process_self();
428
429   /* process status */
430   self->sem = sem;
431   xbt_fifo_push(sem->sleeping, self);
432   SIMIX_process_yield();
433   self->sem = NULL;
434   while (self->suspended)
435     SIMIX_process_yield();
436 }
437
438 /** @brief Returns true if acquiring this semaphore would block */
439 XBT_INLINE int SIMIX_sem_would_block(smx_sem_t sem)
440 {
441   return (sem->capacity <= 0);
442 }
443
444 /** @brief Returns the current capacity of the semaphore
445  *
446  * If it's negative, that's the amount of processes locked on the semaphore
447  */
448 int SIMIX_sem_get_capacity(smx_sem_t sem)
449 {
450   return sem->capacity;
451 }
452
453 /**
454  * \brief Waits on a semaphore
455  *
456  * If the capacity>0, decrease the capacity.
457  *
458  * If capacity==0, locks the current process
459  * until someone call SIMIX_sem_release() on this semaphore
460  */
461 void SIMIX_sem_acquire(smx_sem_t sem)
462 {
463   SIMIX_sem_acquire_timeout(sem, -1);
464 }
465
466 /**
467  * \brief Tries to acquire a semaphore before a timeout
468  *
469  * Same behavior of #SIMIX_sem_acquire, but waits a maximum time and throws an timeout_error if it happens.
470  */
471 void SIMIX_sem_acquire_timeout(smx_sem_t sem, double max_duration)
472 {
473   smx_action_t act_sleep;
474
475   DEBUG2("Wait semaphore %p (timeout:%f)", sem, max_duration);
476
477   if (sem->capacity == SMX_SEM_NOLIMIT) {
478     DEBUG1("semaphore %p wide open", sem);
479     return;                     /* don't even decrease it if wide open */
480   }
481
482   /* If capacity sufficient, decrease it */
483   if (sem->capacity > 0) {
484     DEBUG1("semaphore %p has enough capacity", sem);
485     sem->capacity--;
486     return;
487   }
488
489   /* Always create an action null in case there is a host failure */
490   act_sleep = SIMIX_action_sleep(SIMIX_host_self(), max_duration);
491   SIMIX_action_set_name(act_sleep,
492                         bprintf("Locked in semaphore %p (max_duration:%f)",
493                                 sem, max_duration));
494   SIMIX_process_self()->waiting_action = act_sleep;
495   SIMIX_register_action_to_semaphore(act_sleep, sem);
496   SIMIX_sem_block_onto(sem);
497   SIMIX_process_self()->waiting_action = NULL;
498   SIMIX_unregister_action_to_semaphore(act_sleep, sem);
499   if (max_duration >= 0
500       && SIMIX_action_get_state(act_sleep) == SURF_ACTION_DONE) {
501     SIMIX_action_destroy(act_sleep);
502     THROW1(timeout_error, 0, "Semaphore acquire timeouted after %f",
503            max_duration);
504   } else {
505     if (sem->capacity != SMX_SEM_NOLIMIT) {
506       /* Take the released token */
507       sem->capacity--;
508     }
509     SIMIX_action_destroy(act_sleep);
510   }
511   DEBUG1("End of Wait on semaphore %p", sem);
512 }
513
514 /**
515  * \brief Blocks on a set of semaphore
516  *
517  * If any of the semaphores has some more capacity, it gets decreased.
518  * If not, blocks until the capacity of one of the semaphores becomes more friendly.
519  *
520  * \return the rank in the dynar of the semaphore which just got locked from the set
521  */
522 unsigned int SIMIX_sem_acquire_any(xbt_dynar_t sems)
523 {
524   smx_sem_t sem;
525   unsigned int counter, result = -1;
526   smx_action_t act_sleep;
527   smx_process_t self = SIMIX_process_self();
528
529   xbt_assert0(xbt_dynar_length(sems),
530               "I refuse to commit sucide by locking on an **empty** set of semaphores!!");
531   DEBUG2("Wait on semaphore set %p (containing %ld semaphores)", sems,
532          xbt_dynar_length(sems));
533
534   xbt_dynar_foreach(sems, counter, sem) {
535     if (!SIMIX_sem_would_block(sem)) {
536       DEBUG1("Semaphore %p wouldn't block; get it without waiting", sem);
537       SIMIX_sem_acquire(sem);
538       return counter;
539     }
540   }
541
542   /* Always create an action null in case there is a host failure */
543   act_sleep = SIMIX_action_sleep(SIMIX_host_self(), -1);
544   SIMIX_action_set_name(act_sleep, bprintf("Locked in semaphore %p", sem));
545   self->waiting_action = act_sleep;
546   SIMIX_register_action_to_semaphore(act_sleep,
547                                      xbt_dynar_get_as(sems, 0, smx_sem_t));
548
549   /* Get listed as member of all the provided semaphores */
550   self->sem = xbt_dynar_getfirst_as(sems, smx_sem_t);
551   xbt_dynar_foreach(sems, counter, sem) {
552     xbt_fifo_push(sem->sleeping, self);
553   }
554   SIMIX_process_yield();
555   self->sem = NULL;
556   while (self->suspended)
557     SIMIX_process_yield();
558
559   /* at least one of the semaphore unsuspended us -- great, let's search the first one (and get out of the others) */
560   xbt_dynar_foreach(sems, counter, sem) {
561     if (!xbt_fifo_remove(sem->sleeping, self) && result == -1) {
562       if (sem->capacity != SMX_SEM_NOLIMIT) {
563         /* Take the released token */
564         sem->capacity--;
565       }
566       result = counter;
567     }
568   }
569   xbt_assert0(result != -1, "Cannot find which semaphore unlocked me!");
570
571   /* Destroy the waiting action */
572   self->waiting_action = NULL;
573   SIMIX_unregister_action_to_semaphore(act_sleep,
574                                        xbt_dynar_get_as(sems, 0,
575                                                         smx_sem_t));
576   SIMIX_action_destroy(act_sleep);
577   return result;
578 }