Blame view

src/agents-splitgo-mpi.c 64.9 KB
965dadaa   Salvador Abreu   initial commit fr...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <pthread.h>

#include <mpi.h>

#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <errno.h>
#include <semaphore.h>

#include <assert.h>

#include "fdc_int.h"
#include "variables.h"
#include "values.h"
#include "store.h"
#include "splitting.h"
#include "bound.h"

eef94371   Vasco Pedro   Update to PaCCS v...
20
21
#ifndef COMPACT_DOMAINS
#error "only works with COMPACT_DOMAINS"
965dadaa   Salvador Abreu   initial commit fr...
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#endif

#if !defined(PACK_PROBLEM) || !defined(USE_STORE)
#error "must PACK_PROBLEM and USE_STORE"
#endif

/* sizes are taken from the MPI-2 standard */
#if UNIT_BITS == 64
   /* some MPI implementations, such as New Madeleine's, don't have
      MPI_UNSIGNED_LONG_LONG */
#  ifndef MPI_UNSIGNED_LONG_LONG
#    ifndef MPI_LONG_LONG
#      warning "neither MPI_UNSIGNED_LONG_LONG nor MPI_LONG_LONG are defined"
#    endif

#    define MPI_DOMAIN_TYPE MPI_LONG_LONG
#  else
#    define MPI_DOMAIN_TYPE MPI_UNSIGNED_LONG_LONG
#  endif
#elif UNIT_BITS == 32
#  define MPI_DOMAIN_TYPE MPI_UNSIGNED_LONG
#else
#  error "don't know which MPI type to use for MPI_DOMAIN_TYPE"
#endif

#define MAX_AGENTS 1024

a2ec137b   Vasco Pedro   updated to PaCCS ...
49
// number of workers to use
965dadaa   Salvador Abreu   initial commit fr...
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
int fd__workers = -1;

// events within the main loop
#define EV_INT_SUCCESS	0x001	  // an agent found a solution
#define EV_INT_FAIL	0x002	  // an agent exhausted its search space
#define EV_EXT_SUCCESS	0x010	  // another process found a solution
#define EV_EXT_REQ_WORK	0x020	  // another process exhausted its search space
#define EV_EXT_NO_WORK	0x040	  // there is no work to give to another process
#define EV_EXT_STORE	0x080	  // this process received more work
#define EV_EXT_FAIL	0x100	  // there is no more work available
#define EV_EXT_DONE	0x200	  // the search has succeeded and should stop
#define EV_EXT_QUIT	0x300	  // no more work is available for sharing
#define EV_EXT_READY	0x600	  // process has no work and nothing pending

#define EV_EXT_BOUND	0x500	  // best value of the objective function

#define EV_INT_COUNT	0x004	  // solutions count from an agent
#define EV_EXT_COUNT	0x400	  // solutions count from a process

#define EV_EXT_REQ_SHARE 0x030	  // a process couldn't find work
#define EV_EXT_NO_SHARE	0x050	  // a process has no work to share

#define EV_INT_TIMEOUT	0x008	  // some timeout

#define WAIT_NORM 1000000L // pause between event probes (1ms)
#define WAIT_TOUT  250000L // pause between event probes on a deadline (0.25ms)

#define FEED1_TIMEOUT 20 // ms to wait for the reply to the 1st request for work
#define FEED2_TIMEOUT 10 // ms to wait for the reply to the 2nd request for work
#define POLL_TIMEOUT  10 // ms to wait for the reply to a poll for work

#define millisleep(ms) do {						\
			 struct timespec ts = { 0, ms * 1000000 };	\
			 nanosleep(&ts, NULL);				\
		       } while (0)

#ifdef STATS_MSGS
static unsigned long _fd_msgs_received = 0, _fd_msgs_sent = 0;

static int _fd_MPI_Recv(void *b, int c, MPI_Datatype d, int s, int t,
			MPI_Comm w, MPI_Status *x)
{
  ++_fd_msgs_received;

  return MPI_Recv(b, c, d, s, t, w, x);
}
#define MPI_Recv _fd_MPI_Recv

static int _fd_MPI_Send(void *b, int c, MPI_Datatype d, int s, int t,
			MPI_Comm w)
{
  ++_fd_msgs_sent;

  return MPI_Send(b, c, d, s, t, w);
}
#define MPI_Send _fd_MPI_Send

static int _fd_MPI_Isend(void *b, int c, MPI_Datatype d, int s, int t,
			 MPI_Comm w, MPI_Request *r)
{
  ++_fd_msgs_sent;

  return MPI_Isend(b, c, d, s, t, w, r);
}
#define MPI_Isend _fd_MPI_Isend

static int _fd_MPI_Ssend(void *b, int c, MPI_Datatype d, int s, int t,
			 MPI_Comm w)
{
  ++_fd_msgs_sent;

  return MPI_Ssend(b, c, d, s, t, w);
}
#define MPI_Ssend _fd_MPI_Ssend

static int _fd_MPI_Issend(void *b, int c, MPI_Datatype d, int s, int t,
			  MPI_Comm w, MPI_Request *r)
{
  ++_fd_msgs_sent;

  return MPI_Issend(b, c, d, s, t, w, r);
}
#define MPI_Issend _fd_MPI_Issend

void _fd_statistics_msgs()
{
  extern int tid;

  _fd_output("[%d] messages: %lu sent, %lu received\n", tid, _fd_msgs_sent,
	     _fd_msgs_received);
eef94371   Vasco Pedro   Update to PaCCS v...
140
}
965dadaa   Salvador Abreu   initial commit fr...
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#else /* STATS_MSGS */
#define _fd_statistics_msgs() ((void) 0)
#endif /* STATS_MSGS */


static fd_int *_fd_copies[MAX_AGENTS];
static _fd_store _fd_agents_stores[MAX_AGENTS];
static _fd_store _fd_processes_stores[MAX_AGENTS]; // XXX: MAX_AGENTS!?
						   // only needed by process 0

// used to deliver the id of the agent
static int successful;

// used to signal the main thread that an agent has found a solution
// XXX: could be done through a (shared) variable?
static pthread_mutex_t success_mutex = PTHREAD_MUTEX_INITIALIZER;
static sem_t ready_semaphore, notify_semaphore;
// used when optimising, to release an agent after checking its solution
static sem_t resume_semaphore;
#if STEAL_WORK >= 2
// where agents will wait for more work
static pthread_mutex_t continue_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t continue_cond = PTHREAD_COND_INITIALIZER;
#endif

// number of agents which will actually run (depends on the splitting)
static int agents_to_run;

extern unsigned long long _fd_count_solutions(fd_int[], int);

// used to accumulate the number of solutions found (when counting solutions)
static unsigned long long total_solutions = 0;

// record issued MPI requests, so they can be cleaned up before
// calling MPI_Finalize
// XXX: this list should be checked once in a while, otherwise it will
//      keep growing as the program runs
static fd_list pending_requests;

int tid;	// team ID // XXX: only used outside _fd_dsolve() for debugging

static void _fd_copy_problem(int n)
{
#ifndef PACK_PROBLEM
  int i, v;

  for (i = 0; i < n; ++i)
    {
      _fd_copies[i] = calloc(fd_variables_count, sizeof(fd_int)); // XXX: NULL?

      for (v = 0; v < fd_variables_count; ++v)
	_fd_copies[i][v] = _fd_var_copy(_fd_variables[v]);

      _fd_import_constraints(_fd_copies[i]);
    }
#else /* PACK_PROBLEM */
  int i;

  for (i = 0; i < n; ++i)
    _fd_copies[i] = _fd_variables; // XXX
#endif /* PACK_PROBLEM */
}

// XXX: turn the variables' domains into ``indexes'' into the store
static void _fd_despicable_hack(int n)
{
  store = _fd_agents_stores[n];
}

int _fd_agent(int n)
{
  if (!_fd_counting_solutions)
    {
      int result;
      struct timeval ti, tis, to, tos;

      _fd_debug("[%d.%d] agent starting\n", tid, n);

eef94371   Vasco Pedro   Update to PaCCS v...
219
      gettimeofday(&ti, NULL);
965dadaa   Salvador Abreu   initial commit fr...
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242

      _fd_despicable_hack(n);

      memcpy(_fd_variables, _fd_copies[n], fd_variables_count * sizeof(fd_int));

      // make sure agents release the mutexes they hold when cancelled
      pthread_cleanup_push((void (*)(void *)) pthread_mutex_unlock,
			   &success_mutex);
#if STEAL_WORK >= 2
      pthread_cleanup_push((void (*)(void *)) pthread_mutex_unlock,
			   &continue_mutex);
#endif

      do {
	gettimeofday(&tis, NULL);

	result = _fd_dsearch(_fd_copies[n], n);

	gettimeofday(&to, NULL);
	timersub(&to, &tis, &tos);
	timersub(&to, &ti, &to);
	_fd_debug("[%d.%d] took %d.%06ds (%d.%06ds)\n", tid, n,
		  tos.tv_sec, tos.tv_usec, to.tv_sec, to.tv_usec);
eef94371   Vasco Pedro   Update to PaCCS v...
243

965dadaa   Salvador Abreu   initial commit fr...
244
245
246
247
	while (result == FD_OK)
	  {
	    _fd_debug("[%d.%d] agent was successful\n", tid, n);

eef94371   Vasco Pedro   Update to PaCCS v...
248
	    // ensure that only one agent signals its success
965dadaa   Salvador Abreu   initial commit fr...
249
250
251
252
	    // XXX: only good (?) if only looking for the 1st solution
	    pthread_mutex_lock(&success_mutex);
	    _fd_debug("[%d.%d] acquired success mutex\n", tid, n);

eef94371   Vasco Pedro   Update to PaCCS v...
253
	    // tell the main thread that this agent is done
965dadaa   Salvador Abreu   initial commit fr...
254
255
256
257
258
259
260
261
262
263
264
	    if (sem_wait(&ready_semaphore))
	      perror("sem_wait (ready)");

	    successful = n;

	    if (sem_post(&notify_semaphore))
	      perror("sem_post");

	    pthread_mutex_unlock(&success_mutex);
	    _fd_debug("[%d.%d] released success mutex\n", tid, n);

eef94371   Vasco Pedro   Update to PaCCS v...
265
	    if (!_fd_optimising)
965dadaa   Salvador Abreu   initial commit fr...
266
267
268
269
270
271
	      break;

	    if (sem_wait(&resume_semaphore))
	      perror("sem_post (resume)");
	    _fd_debug("[%d.%d] resuming, new bound is %d\n", tid, n, _fd_bound_value());

eef94371   Vasco Pedro   Update to PaCCS v...
272
	    // find the next solution
965dadaa   Salvador Abreu   initial commit fr...
273
274
275
276
277
278
279
280
281
	    gettimeofday(&tis, NULL);

	    result = _fd_dsearch_again(_fd_copies[n]);

	    gettimeofday(&to, NULL);
	    timersub(&to, &tis, &tos);
	    timersub(&to, &ti, &to);
	    _fd_debug("[%d.%d] took %d.%06ds (%d.%06ds)\n", tid, n,
		      tos.tv_sec, tos.tv_usec, to.tv_sec, to.tv_usec);
eef94371   Vasco Pedro   Update to PaCCS v...
282
	  }
965dadaa   Salvador Abreu   initial commit fr...
283
284
285
286
287
288
289
290

	// XXX: only interested in the 1st solution, for now
	if (!_fd_optimising && result == FD_OK)
	  break;

	// eventually, the agent will fail to find a solution
	_fd_debug("[%d.%d] agent was unsuccessful\n", tid, n);

eef94371   Vasco Pedro   Update to PaCCS v...
291
	// tell the main thread that this agent is done
965dadaa   Salvador Abreu   initial commit fr...
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
	if (sem_wait(&ready_semaphore))
	  perror("sem_wait (ready)");

	successful = -n - 1;	// negative agent number means failure

#if STEAL_WORK >= 2
	pthread_mutex_lock(&continue_mutex);
#endif

	if (sem_post(&notify_semaphore))
	  perror("sem_post");

#if STEAL_WORK >= 2
	do {
	  // wait for more work
	  _fd_debug("[%d.%d] waiting for more work\n", tid, n);
	  pthread_cond_wait(&continue_cond, &continue_mutex);
eef94371   Vasco Pedro   Update to PaCCS v...
309
	} while(n >= agents_to_run);
965dadaa   Salvador Abreu   initial commit fr...
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329

	if (pthread_mutex_unlock(&continue_mutex))
	  perror("pthread_mutex_unlock");
#endif
      } while (STEAL_WORK >= 2);

#if STEAL_WORK >= 2
      pthread_cleanup_pop(0);
#endif
      pthread_cleanup_pop(0);

      return result;
    }
  else /* _fd_counting_solutions != 0 */
    {
      unsigned long long solutions;
      struct timeval ti, tis, to, tos;

      _fd_debug("[%d.%d] agent starting\n", tid, n);

eef94371   Vasco Pedro   Update to PaCCS v...
330
      gettimeofday(&ti, NULL);
965dadaa   Salvador Abreu   initial commit fr...
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350

      _fd_despicable_hack(n);

      memcpy(_fd_variables, _fd_copies[n], fd_variables_count * sizeof(fd_int));

#if STEAL_WORK >= 2
      pthread_cleanup_push((void (*)(void *)) pthread_mutex_unlock,
			   &continue_mutex);
#endif

      do {
	gettimeofday(&tis, NULL);

	solutions = _fd_count_solutions(_fd_copies[n], n);

	gettimeofday(&to, NULL);
	timersub(&to, &tis, &tos);
	timersub(&to, &ti, &to);
	_fd_debug("[%d.%d] took %d.%06ds (%d.%06ds)\n", tid, n,
		  tos.tv_sec, tos.tv_usec, to.tv_sec, to.tv_usec);
eef94371   Vasco Pedro   Update to PaCCS v...
351

965dadaa   Salvador Abreu   initial commit fr...
352
353
	_fd_debug("[%d.%d] found %llu solutions\n", tid, n, solutions);

eef94371   Vasco Pedro   Update to PaCCS v...
354
	// tell the main thread that this agent is done
965dadaa   Salvador Abreu   initial commit fr...
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
	if (sem_wait(&ready_semaphore))
	  perror("sem_wait (ready)");

	successful = n;

	// and update the solutions' running total
	total_solutions += solutions;

#if STEAL_WORK >= 2
	pthread_mutex_lock(&continue_mutex);
#endif

	if (sem_post(&notify_semaphore))
	  perror("sem_post");

#if STEAL_WORK >= 2
	do {
	  // wait for more work
	  _fd_debug("[%d.%d] waiting for more work\n", tid, n);
	  pthread_cond_wait(&continue_cond, &continue_mutex);
eef94371   Vasco Pedro   Update to PaCCS v...
375
	} while (n >= agents_to_run);
965dadaa   Salvador Abreu   initial commit fr...
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410

	if (pthread_mutex_unlock(&continue_mutex))
	  perror("pthread_mutex_unlock");
#endif /* STEAL_WORK >= 2 */
      } while (STEAL_WORK >= 2);

#if STEAL_WORK >= 2
      pthread_cleanup_pop(0);
#endif

      return 0;
    }
}

static void clock_add(struct timespec *ts, long delta)
{
  clock_gettime(CLOCK_REALTIME, ts);

  ts->tv_nsec += delta;

  if (ts->tv_nsec >= 1000000000L)
    {
      ts->tv_sec += ts->tv_nsec / 1000000000L;
      ts->tv_nsec %= 1000000000L;
    }
}

/* send TO a dataless message (non-blocking) */
static void _fd_send(int to, int tag)
{
  MPI_Request mpi_request = MPI_REQUEST_NULL;

  if (MPI_Isend(NULL, 0, MPI_CHAR, to, tag, MPI_COMM_WORLD, &mpi_request))
    _fd_fatal("MPI_Isend failed");
}
eef94371   Vasco Pedro   Update to PaCCS v...
411

965dadaa   Salvador Abreu   initial commit fr...
412
413
414
415
416
417
418
419
/* send TO a message with data (non-blocking) */
static void _fd_send_data(int to, int tag, void *buf, int n, MPI_Datatype type)
{
  MPI_Request mpi_request = MPI_REQUEST_NULL;

  if (MPI_Isend(buf, n, type, to, tag, MPI_COMM_WORLD, &mpi_request))
    _fd_fatal("MPI_Isend failed");
}
eef94371   Vasco Pedro   Update to PaCCS v...
420

965dadaa   Salvador Abreu   initial commit fr...
421
422
423
424
425
426
427
428
429
430
431
#if STEAL_WORK >= 2
/* send TO a message with data and keep the record of the REQUEST */
static void _fd_ssend_data(int to, int tag, void *buf, int n, MPI_Datatype type,
			   MPI_Request *request)
{
  if (request)
    {
#ifndef MAD_MPI
      if (MPI_Issend(buf, n, type, to, tag, MPI_COMM_WORLD, request))
	_fd_fatal("MPI_Issend failed");

eef94371   Vasco Pedro   Update to PaCCS v...
432
#if 0
965dadaa   Salvador Abreu   initial commit fr...
433
434
435
436
437
      {
	int mpi_flag;

	_fd_debug("[%d] MPI_Test = %d\n", tid,
		  MPI_Test(request, &mpi_flag, MPI_STATUS_IGNORE));
eef94371   Vasco Pedro   Update to PaCCS v...
438

965dadaa   Salvador Abreu   initial commit fr...
439
440
441
	if (mpi_flag)
	  _fd_debug("[%d] send completed\n", tid);
	else
eef94371   Vasco Pedro   Update to PaCCS v...
442
	  _fd_debug("[%d] send didn't complete yet\n", tid);
965dadaa   Salvador Abreu   initial commit fr...
443
      }
eef94371   Vasco Pedro   Update to PaCCS v...
444
#endif
965dadaa   Salvador Abreu   initial commit fr...
445
446
447
448
449
450
#else /* MAD_MPI */
      // XXX: NMAD doesn't have MPI_Issend
      // XXX: no record of the sending is left
      if (MPI_Ssend(buf, n, type, to, tag, MPI_COMM_WORLD))
	_fd_fatal("MPI_Send failed");

eef94371   Vasco Pedro   Update to PaCCS v...
451
      *request = MPI_REQUEST_NULL;
965dadaa   Salvador Abreu   initial commit fr...
452
453
454
455
456
457
458
459
460
#endif /* MAD_MPI */
    }
  else
    {
      MPI_Request mpi_request = MPI_REQUEST_NULL;

      if (MPI_Isend(buf, n, type, to, tag, MPI_COMM_WORLD, &mpi_request))
	_fd_fatal("MPI_Isend failed");
    }
eef94371   Vasco Pedro   Update to PaCCS v...
461
}
965dadaa   Salvador Abreu   initial commit fr...
462
463
464
465
466
467
468
469
470
#endif /* STEAL_WORK >= 2 */

static void fd__send_empty_store(int to, int tag, _fd_store buffer,
				 MPI_Request *request)
{
  if (MPI_Isend(buffer, 0, MPI_DOMAIN_TYPE,
		to, tag, MPI_COMM_WORLD, request))
    _fd_fatal("MPI_Isend failed");
}
eef94371   Vasco Pedro   Update to PaCCS v...
471

965dadaa   Salvador Abreu   initial commit fr...
472
473
474
475
476
477
478
479
480
481
482
483
484
485
static void _fd_send_store(int to, int tag, _fd_store buffer,
			   MPI_Request *request, bool synchronous)
{
  if (synchronous)
    {
      _fd_ssend_data(to, tag, buffer, fd_variables_count * DOMAIN_WORDS,
		     MPI_DOMAIN_TYPE, request);
    }
  else
    {
      if (MPI_Isend(buffer, fd_variables_count * DOMAIN_WORDS, MPI_DOMAIN_TYPE,
		    to, tag, MPI_COMM_WORLD, request))
	_fd_fatal("MPI_Isend failed");
    }
eef94371   Vasco Pedro   Update to PaCCS v...
486
}
965dadaa   Salvador Abreu   initial commit fr...
487
488
489
490
491
492
493
494
495
496

static int _fd_recv_store(int from, int tag, _fd_store buffer)
{
  MPI_Status status;
  int count;

  if (MPI_Recv(buffer, fd_variables_count * DOMAIN_WORDS, MPI_DOMAIN_TYPE,
	       from, tag, MPI_COMM_WORLD, &status))
    _fd_fatal("MPI_Recv failed");

eef94371   Vasco Pedro   Update to PaCCS v...
497
  MPI_Get_count(&status, MPI_DOMAIN_TYPE, &count);
965dadaa   Salvador Abreu   initial commit fr...
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515

  return count;
}

static void _fd_broadcast(int msg, int processes, int from)
{
#if 0
  MPI_Request *mpi_request /* = MPI_REQUEST_NULL*/;
  int i;

  for (i = 0; i < processes; ++i)
    if (i != from)
      {
	mpi_request = malloc(sizeof(MPI_Request));

	if (MPI_Isend(NULL, 0, MPI_CHAR, i, msg, MPI_COMM_WORLD, mpi_request))
	  _fd_fatal("MPI_Isend failed");

eef94371   Vasco Pedro   Update to PaCCS v...
516
	fd_list_append(pending_requests, mpi_request);
965dadaa   Salvador Abreu   initial commit fr...
517
518
519
520
521
522
523
524
525
526
      }
#else
  MPI_Request mpi_request = MPI_REQUEST_NULL;
  int i;

  for (i = 0; i < processes; ++i)
    if (i != from)
      if (MPI_Isend(NULL, 0, MPI_CHAR, i, msg, MPI_COMM_WORLD, &mpi_request))
	_fd_fatal("MPI_Isend failed");
#endif
eef94371   Vasco Pedro   Update to PaCCS v...
527
}
965dadaa   Salvador Abreu   initial commit fr...
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564

static void _fd_broadcast_data(int msg, void *buf, int n, MPI_Datatype type,
			       int processes, int from)
{
  int i;

  for (i = 0; i < processes; ++i)
    if (i != from)
      _fd_send_data(i, msg, buf, n, type);
}

#ifdef GET_SIGNAL
#include <signal.h>
void sig_handler(int sig)
{
  printf("******** caught signal %d ********\n", sig);
}

struct sigaction old_actions[_NSIG];
struct sigaction new_action = { sig_handler, 0, 0, NULL };
#endif

static bool _fd_probe_external(int tag, char *name, int *source, bool consume)
{
  MPI_Status mpi_status;
  int mpi_flag;
  int s;

  s = MPI_Iprobe(MPI_ANY_SOURCE, tag, MPI_COMM_WORLD, &mpi_flag, &mpi_status);

#if 0
  // XXX: what the heck is the return value supposed to mean?
  if (s)
    {
      char es[1024]; int _;
      _fd_debug("MPI_Iprobe %s returned %d\n", name, s);
      MPI_Error_string(s, es, &_);
eef94371   Vasco Pedro   Update to PaCCS v...
565
      _fd_debug("%s\n", es);
965dadaa   Salvador Abreu   initial commit fr...
566
    }
eef94371   Vasco Pedro   Update to PaCCS v...
567
#endif
965dadaa   Salvador Abreu   initial commit fr...
568
569
570
571
572
573
574

  if (mpi_flag)
    {
      *source = mpi_status.MPI_SOURCE;

      _fd_debug("[%d] got %s from %d\n", tid, name, *source);

eef94371   Vasco Pedro   Update to PaCCS v...
575
      // consume message
965dadaa   Salvador Abreu   initial commit fr...
576
577
578
579
580
      if (consume)
	if (MPI_Recv(NULL, 0, MPI_CHAR, mpi_status.MPI_SOURCE, tag,
		     MPI_COMM_WORLD, &mpi_status))
	  _fd_fatal("MPI_Recv failed");

eef94371   Vasco Pedro   Update to PaCCS v...
581
      return true;
965dadaa   Salvador Abreu   initial commit fr...
582
583
584
585
586
587
588
589
590
591
592
593
594
    }

  return false;
}

static int _fd_get_event(int running, int *source, int *timeout)
{
  struct timespec ts;
  double tin, tmout = 0;
  int event;

  _fd_debug("[%d] getting next event\n", tid);

eef94371   Vasco Pedro   Update to PaCCS v...
595
  if (timeout && *timeout)
965dadaa   Salvador Abreu   initial commit fr...
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
    {
      tin = MPI_Wtime();
      tmout = tin + *timeout / 1000.0;	// timeout comes in milliseconds
    }

  for (;;)
    {
      // see if any of the agents has anything to say
      if (running > 0)
	{
	  if (sem_trywait(&notify_semaphore))
	    {
	      if (errno == EAGAIN)
		; //_fd_debug("[%d] notify semaphore is busy\n", tid);
	      else
eef94371   Vasco Pedro   Update to PaCCS v...
611
		perror("sem_trywait (notify)");
965dadaa   Salvador Abreu   initial commit fr...
612
613
614
615
616
617
	    }
	  else
	    {
	      // got something from one of the agents
	      _fd_debug("[%d] got something from an agent\n", tid);

eef94371   Vasco Pedro   Update to PaCCS v...
618
	      if (!_fd_counting_solutions)
965dadaa   Salvador Abreu   initial commit fr...
619
620
621
622
623
624
625
626
		{
		  int s = successful;

		  if (sem_post(&ready_semaphore))
		    perror("sem_post");

		  _fd_debug("[%d] got an answer from %s%d\n", tid,
			    s == -1 ? "-" : "", s + (s < 0));
eef94371   Vasco Pedro   Update to PaCCS v...
627

965dadaa   Salvador Abreu   initial commit fr...
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
		  if (s >= 0)
		    {
		      *source = s;

		      event = EV_INT_SUCCESS;
		      break;
		    }

		  *source = -(s + 1);

		  return EV_INT_FAIL;
		}
	      else /* _fd_counting_solutions != 0 */
		{
		  *source = successful;

		  if (sem_post(&ready_semaphore))
		    perror("sem_post");

		  event = EV_INT_COUNT;
		  break;
		}
	    }
	}

#ifndef MAD_MPI
      {
	MPI_Status mpi_status;
	int mpi_flag;
	bool consume = true;
	char *name;

	MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &mpi_flag,
		   &mpi_status);

	if (mpi_flag)
	  {
	    *source = mpi_status.MPI_SOURCE;

	    switch (mpi_status.MPI_TAG)
	      {
	      case FD_MSG_SOLUTION:
		name = "FD_MSG_SOLUTION";
		consume = false;
		event = EV_EXT_SUCCESS;
		break;
	      case FD_MSG_FAIL:
		name = "FD_MSG_FAIL";
		event = EV_EXT_FAIL;
		break;
	      case FD_MSG_DONE:
		name = "FD_MSG_DONE";
		event = EV_EXT_DONE;
		break;
	      case FD_MSG_BOUND:
		name = "FD_MSG_BOUND";
		consume = false;
		event = EV_EXT_BOUND;
		break;
	      case FD_MSG_COUNT:
		name = "FD_MSG_COUNT";
		consume = false;
		event = EV_EXT_COUNT;
		break;
	      case FD_MSG_STORE:
		name = "FD_MSG_STORE";
		consume = false;
		event = EV_EXT_STORE;
		break;
	      case FD_MSG_FEED_ME:
		name = "FD_MSG_FEED_ME";
		event = EV_EXT_REQ_WORK;
		break;
	      case FD_MSG_NO_WORK:
		name = "FD_MSG_NO_WORK";
		event = EV_EXT_NO_WORK;
		break;
	      case FD_MSG_NO_SHARE:
		name = "FD_MSG_NO_SHARE";
		event = EV_EXT_NO_SHARE;
		break;
	      case FD_MSG_SHARE:
		name = "FD_MSG_SHARE";
		event = EV_EXT_REQ_SHARE;
		break;
	      case FD_MSG_QUIT:
		name = "FD_MSG_QUIT";
		event = EV_EXT_QUIT;
		break;
	      case FD_MSG_READY:
		name = "FD_MSG_READY";
		event = EV_EXT_READY;
		break;
	      default:
		_fd_debug("[%d] unknown tag %d\n", tid, mpi_status.MPI_TAG);
		_fd_fatal("unknown tag in message");
eef94371   Vasco Pedro   Update to PaCCS v...
724
725
	      }

965dadaa   Salvador Abreu   initial commit fr...
726
727
	    _fd_debug("[%d] got %s from %d\n", tid, name, *source);

eef94371   Vasco Pedro   Update to PaCCS v...
728
	    // consume message
965dadaa   Salvador Abreu   initial commit fr...
729
730
731
732
733
	    if (consume)
	      if (MPI_Recv(NULL, 0, MPI_CHAR, mpi_status.MPI_SOURCE,
			   mpi_status.MPI_TAG, MPI_COMM_WORLD, &mpi_status))
		_fd_fatal("MPI_Recv failed");

eef94371   Vasco Pedro   Update to PaCCS v...
734
	    break;
965dadaa   Salvador Abreu   initial commit fr...
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
	  }
      }
#else /* MAD_MPI */
      // XXX: New Madeleine doesn't implement MPI_*probe(..., MPI_ANY_TAG, ...)

      if (_fd_probe_external(FD_MSG_SOLUTION, "FD_MSG_SOLUTION", source, false))
	{
	  event = EV_EXT_SUCCESS;
	  break;
	}

      if (_fd_probe_external(FD_MSG_BOUND, "FD_MSG_BOUND", source, false))
	{
	  event = EV_EXT_BOUND;
	  break;
	}

      if (_fd_probe_external(FD_MSG_QUIT, "FD_MSG_QUIT", source, true))
	{
	  event = EV_EXT_QUIT;
	  break;
	}

      if (_fd_probe_external(FD_MSG_NO_WORK, "FD_MSG_NO_WORK", source, true))
	{
	  event = EV_EXT_NO_WORK;
	  break;
	}

      if (_fd_probe_external(FD_MSG_STORE, "FD_MSG_STORE", source, false))
	{
	  event = EV_EXT_STORE;
	  break;
	}

      if (_fd_probe_external(FD_MSG_SHARE, "FD_MSG_SHARE", source, true))
	{
	  event = EV_EXT_REQ_SHARE;
	  break;
	}

      if (_fd_probe_external(FD_MSG_NO_SHARE, "FD_MSG_NO_SHARE", source, true))
	{
	  event = EV_EXT_NO_SHARE;
	  break;
	}

      /*
	must be checked for after FD_MSG_STORE: if the `supplier'
	sends an FD_MSG_STORE, then finishes its work and sends an
	FD_MSG_FEED_ME and the checks are reversed, the latter will be
	ignored (since this is not yet the supplier) and the solver
	will not halt (XXX: only if not polling?)
      */
      if (_fd_probe_external(FD_MSG_FEED_ME, "FD_MSG_FEED_ME", source, true))
	{
	  event = EV_EXT_REQ_WORK;
	  break;
	}

      if (_fd_probe_external(FD_MSG_FAIL, "FD_MSG_FAIL", source, true))
	{
	  event = EV_EXT_FAIL;
	  break;
	}

      // XXX: only processes with rank != 0 shall receive DONE
      if (_fd_probe_external(FD_MSG_DONE, "FD_MSG_DONE", source, true))
	{
	  event = EV_EXT_DONE;
	  break;
	}

      if (_fd_probe_external(FD_MSG_READY, "FD_MSG_READY", source, true))
	{
	  event = EV_EXT_READY;
	  break;
	}

      if (_fd_counting_solutions)
	// XXX: only the process with rank 0 shall receive COUNTs
	if (_fd_probe_external(FD_MSG_COUNT, "FD_MSG_COUNT", source, false))
	  {
	    event = EV_EXT_COUNT;
	    break;
	  }
#endif /* MAD_MPI */

      if (tmout && MPI_Wtime() >= tmout)
	{
	  *timeout = 0;

	  return EV_INT_TIMEOUT;
	}

      if (tmout)
	{
	  struct timespec ts = { 0, WAIT_TOUT };

	  nanosleep(&ts, NULL);
	}
      else
	{
	  struct timespec ts = { 0, WAIT_NORM };

	  nanosleep(&ts, NULL);
	}
    }

  if (tmout)
    {
      *timeout = (int) ((tmout - MPI_Wtime()) * 1000.0 + 0.5);
      if (*timeout < 1)
	*timeout = 1;
    }

  return event;
}

static void _fd_flush_events(int procno)
{
  MPI_Status mpi_status;
  int mpi_flag;
  int got_one;
  MPI_Request *mpi_request;

  // check the status of MPI pending requests
  while (mpi_request = fd_list_remove(pending_requests))
    {
      if (MPI_Test(mpi_request, &mpi_flag, MPI_STATUS_IGNORE))
	_fd_debug("[%d] MPI_Test failed\n", procno);

eef94371   Vasco Pedro   Update to PaCCS v...
867
      if (!mpi_flag)
965dadaa   Salvador Abreu   initial commit fr...
868
869
870
871
	{
#if 0	// this is probably the solution just sent, not cancelling it
	  _fd_debug("[%d] cancelling request\n", procno);

eef94371   Vasco Pedro   Update to PaCCS v...
872
	  if (MPI_Cancel(mpi_request))
965dadaa   Salvador Abreu   initial commit fr...
873
874
	    _fd_debug("[%d] MPI_Cancel failed\n", procno);

eef94371   Vasco Pedro   Update to PaCCS v...
875
	  _fd_debug("[%d] waiting for cancellation completion\n", procno);
965dadaa   Salvador Abreu   initial commit fr...
876

eef94371   Vasco Pedro   Update to PaCCS v...
877
	  if (MPI_Wait(mpi_request, MPI_STATUS_IGNORE))
965dadaa   Salvador Abreu   initial commit fr...
878
879
	    _fd_debug("[%d] MPI_Wait failed\n", procno);
#else
eef94371   Vasco Pedro   Update to PaCCS v...
880
	  _fd_debug("[%d] found a not completed request\n", procno);
965dadaa   Salvador Abreu   initial commit fr...
881
#endif
eef94371   Vasco Pedro   Update to PaCCS v...
882
	}
965dadaa   Salvador Abreu   initial commit fr...
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915

      free(mpi_request);
    }

  fd_list_dispose(pending_requests);

#ifndef MAD_MPI
  // XXX: should be cancelled at the sending site?

  // consume pending incoming communications
  for (;;)
    {
      int source;
      char *name;
      MPI_Datatype type = MPI_CHAR;
      int count = 0;

      MPI_Iprobe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &mpi_flag,
		 &mpi_status);

      if (!mpi_flag)	// nothing to do if no incoming message is found
	break;

      source = mpi_status.MPI_SOURCE;

      switch (mpi_status.MPI_TAG)
	{
	case FD_MSG_SOLUTION:
	  name = "FD_MSG_SOLUTION";
	  type = MPI_DOMAIN_TYPE;
	  count = fd_variables_count * DOMAIN_WORDS;
	  _fd_error("[%d] dropping %s from %d\n", tid, name, source);
	  break;
eef94371   Vasco Pedro   Update to PaCCS v...
916
	case FD_MSG_FAIL:
965dadaa   Salvador Abreu   initial commit fr...
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
	  name = "FD_MSG_FAIL";
	  break;
	case FD_MSG_DONE:
	  name = "FD_MSG_DONE";
	  break;
	case FD_MSG_BOUND:
	  name = "FD_MSG_BOUND";
	  type = MPI_INT;
	  count = 1;
	  break;
	case FD_MSG_COUNT:
	  name = "FD_MSG_COUNT";
	  type = MPI_LONG_LONG;
	  count = 1;
	  _fd_error("[%d] dropping %s from %d\n", tid, name, source);
	  break;
eef94371   Vasco Pedro   Update to PaCCS v...
933
	case FD_MSG_STORE:
965dadaa   Salvador Abreu   initial commit fr...
934
935
936
937
938
	  name = "FD_MSG_STORE";
	  type = MPI_DOMAIN_TYPE;
	  count = fd_variables_count * DOMAIN_WORDS;
	  _fd_error("[%d] *** dropping %s from %d\n", tid, name, source);
	  break;
eef94371   Vasco Pedro   Update to PaCCS v...
939
	case FD_MSG_FEED_ME:
965dadaa   Salvador Abreu   initial commit fr...
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
	  name = "FD_MSG_FEED_ME";
	  break;
	case FD_MSG_NO_WORK:
	  name = "FD_MSG_NO_WORK";
	  break;
	case FD_MSG_NO_SHARE:
	  name = "FD_MSG_NO_SHARE";
	  break;
	case FD_MSG_SHARE:
	  name = "FD_MSG_SHARE";
	  break;
	case FD_MSG_QUIT:
	  name = "FD_MSG_QUIT";
	  break;
	case FD_MSG_READY:
	  name = "FD_MSG_READY";
	  break;
	default:
	  _fd_debug("[%d] unknown tag %d\n", tid, mpi_status.MPI_TAG);
	  _fd_fatal("unknown tag in message");
eef94371   Vasco Pedro   Update to PaCCS v...
960
961
	}

965dadaa   Salvador Abreu   initial commit fr...
962
963
      _fd_debug("[%d] dropping %s from %d\n", tid, name, source);

eef94371   Vasco Pedro   Update to PaCCS v...
964
      // consume message
965dadaa   Salvador Abreu   initial commit fr...
965
966
967
968
969
970
971
      {
	char *buffer = alloca(fd_variables_count * sizeof(*store));

	if (MPI_Recv(buffer, count, type, source, mpi_status.MPI_TAG,
		     MPI_COMM_WORLD, MPI_STATUS_IGNORE))
	  _fd_error("[%d] MPI_Recv failed (dropping %s)\n", tid, name);
      }
eef94371   Vasco Pedro   Update to PaCCS v...
972
    }
965dadaa   Salvador Abreu   initial commit fr...
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
#else /* MAD_MPI */
  // XXX: New Madeleine doesn't implement MPI_*probe(..., MPI_ANY_TAG, ...)
//#ifdef MAD_MPI
//  // XXX: otherwise, assume they will be cancelled at the sending site

  // consume pending incoming communications
  do
    {
      got_one = 0;

      MPI_Iprobe(MPI_ANY_SOURCE, FD_MSG_SOLUTION, MPI_COMM_WORLD, &mpi_flag, &mpi_status);

      if (mpi_flag)
	{
	  _fd_store null = alloca(fd_variables_count * sizeof(*null));

	  _fd_debug("[%d] dropping FD_MSG_SOLUTION from %d\n", procno, mpi_status.MPI_SOURCE);

eef94371   Vasco Pedro   Update to PaCCS v...
991
	  _fd_recv_store(mpi_status.MPI_SOURCE, FD_MSG_SOLUTION, null);
965dadaa   Salvador Abreu   initial commit fr...
992
993
994
995
996
997
998
999
1000
1001

	  got_one++;
	}

      MPI_Iprobe(MPI_ANY_SOURCE, FD_MSG_FEED_ME, MPI_COMM_WORLD, &mpi_flag, &mpi_status);

      if (mpi_flag)
	{
	  _fd_debug("[%d] dropping FD_MSG_FEED_ME from %d\n", procno, mpi_status.MPI_SOURCE);

eef94371   Vasco Pedro   Update to PaCCS v...
1002
	  // consume message
965dadaa   Salvador Abreu   initial commit fr...
1003
1004
1005
1006
	  if (MPI_Recv(NULL, 0, MPI_CHAR, mpi_status.MPI_SOURCE, FD_MSG_FEED_ME,
		       MPI_COMM_WORLD, &mpi_status))
	    _fd_fatal("MPI_Recv failed");

eef94371   Vasco Pedro   Update to PaCCS v...
1007
	  got_one++;
965dadaa   Salvador Abreu   initial commit fr...
1008
1009
1010
1011
1012
1013
1014
1015
	}

      MPI_Iprobe(MPI_ANY_SOURCE, FD_MSG_NO_WORK, MPI_COMM_WORLD, &mpi_flag, &mpi_status);

      if (mpi_flag)
	{
	  _fd_debug("[%d] dropping FD_MSG_NO_WORK from %d\n", procno, mpi_status.MPI_SOURCE);

eef94371   Vasco Pedro   Update to PaCCS v...
1016
	  // consume message
965dadaa   Salvador Abreu   initial commit fr...
1017
1018
1019
1020
	  if (MPI_Recv(NULL, 0, MPI_CHAR, mpi_status.MPI_SOURCE, FD_MSG_NO_WORK,
		       MPI_COMM_WORLD, &mpi_status))
	    _fd_fatal("MPI_Recv failed");

eef94371   Vasco Pedro   Update to PaCCS v...
1021
	  got_one++;
965dadaa   Salvador Abreu   initial commit fr...
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
	}

      MPI_Iprobe(MPI_ANY_SOURCE, FD_MSG_STORE, MPI_COMM_WORLD, &mpi_flag, &mpi_status);

      if (mpi_flag)
	{
	  _fd_store null = alloca(fd_variables_count * sizeof(*null));

	  _fd_debug("[%d] dropping FD_MSG_STORE from %d\n", procno, mpi_status.MPI_SOURCE);

eef94371   Vasco Pedro   Update to PaCCS v...
1032
	  _fd_recv_store(mpi_status.MPI_SOURCE, FD_MSG_STORE, null);
965dadaa   Salvador Abreu   initial commit fr...
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042

	  got_one++;
	}

      MPI_Iprobe(MPI_ANY_SOURCE, FD_MSG_FAIL, MPI_COMM_WORLD, &mpi_flag, &mpi_status);

      if (mpi_flag)
	{
	  _fd_debug("[%d] dropping FD_MSG_FAIL from %d\n", procno, mpi_status.MPI_SOURCE);

eef94371   Vasco Pedro   Update to PaCCS v...
1043
	  // consume message
965dadaa   Salvador Abreu   initial commit fr...
1044
1045
1046
1047
	  if (MPI_Recv(NULL, 0, MPI_CHAR, mpi_status.MPI_SOURCE, FD_MSG_FAIL,
		       MPI_COMM_WORLD, &mpi_status))
	    _fd_fatal("MPI_Recv failed");

eef94371   Vasco Pedro   Update to PaCCS v...
1048
	  got_one++;
965dadaa   Salvador Abreu   initial commit fr...
1049
1050
1051
1052
1053
1054
1055
1056
	}

      MPI_Iprobe(MPI_ANY_SOURCE, FD_MSG_DONE, MPI_COMM_WORLD, &mpi_flag, &mpi_status);

      if (mpi_flag)
	{
	  _fd_debug("[%d] dropping FD_MSG_DONE from %d\n", procno, mpi_status.MPI_SOURCE);

eef94371   Vasco Pedro   Update to PaCCS v...
1057
	  // consume message
965dadaa   Salvador Abreu   initial commit fr...
1058
1059
1060
1061
	  if (MPI_Recv(NULL, 0, MPI_CHAR, mpi_status.MPI_SOURCE, FD_MSG_DONE,
		       MPI_COMM_WORLD, &mpi_status))
	    _fd_fatal("MPI_Recv failed");

eef94371   Vasco Pedro   Update to PaCCS v...
1062
	  got_one++;
965dadaa   Salvador Abreu   initial commit fr...
1063
1064
1065
1066
1067
1068
1069
1070
	}

      MPI_Iprobe(MPI_ANY_SOURCE, FD_MSG_SHARE, MPI_COMM_WORLD, &mpi_flag, &mpi_status);

      if (mpi_flag)
	{
	  _fd_debug("[%d] dropping FD_MSG_SHARE from %d\n", procno, mpi_status.MPI_SOURCE);

eef94371   Vasco Pedro   Update to PaCCS v...
1071
	  // consume message
965dadaa   Salvador Abreu   initial commit fr...
1072
1073
1074
1075
	  if (MPI_Recv(NULL, 0, MPI_CHAR, mpi_status.MPI_SOURCE, FD_MSG_SHARE,
		       MPI_COMM_WORLD, &mpi_status))
	    _fd_fatal("MPI_Recv failed");

eef94371   Vasco Pedro   Update to PaCCS v...
1076
	  got_one++;
965dadaa   Salvador Abreu   initial commit fr...
1077
1078
1079
1080
1081
1082
1083
1084
	}

      MPI_Iprobe(MPI_ANY_SOURCE, FD_MSG_NO_SHARE, MPI_COMM_WORLD, &mpi_flag, &mpi_status);

      if (mpi_flag)
	{
	  _fd_debug("[%d] dropping FD_MSG_NO_SHARE from %d\n", procno, mpi_status.MPI_SOURCE);

eef94371   Vasco Pedro   Update to PaCCS v...
1085
	  // consume message
965dadaa   Salvador Abreu   initial commit fr...
1086
1087
1088
1089
	  if (MPI_Recv(NULL, 0, MPI_CHAR, mpi_status.MPI_SOURCE, FD_MSG_NO_SHARE,
		       MPI_COMM_WORLD, &mpi_status))
	    _fd_fatal("MPI_Recv failed");

eef94371   Vasco Pedro   Update to PaCCS v...
1090
	  got_one++;
965dadaa   Salvador Abreu   initial commit fr...
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
	}
    }
  while (got_one);
#endif /* MAD_MPI */
}

void _fd_cleanup_mpi_state(int process)
{
//  if (!_fd_counting_solutions)
    {
      // this rendez-vous ensures that no stop message is cancelled before
      // a still running process has a chance to see it
      // XXX: New Madeleine can't cope with messages en route
#if 0 //#ifndef MAD_MPI
      _fd_debug("[%d] setting up barrier 1\n", process);
      if (MPI_Barrier(MPI_COMM_WORLD))
eef94371   Vasco Pedro   Update to PaCCS v...
1107
	_fd_error("[%d] MPI_Barrier failed\n", process);
965dadaa   Salvador Abreu   initial commit fr...
1108
      else
eef94371   Vasco Pedro   Update to PaCCS v...
1109
	_fd_debug("[%d] leaving barrier 1\n", process);
965dadaa   Salvador Abreu   initial commit fr...
1110
#endif
eef94371   Vasco Pedro   Update to PaCCS v...
1111

965dadaa   Salvador Abreu   initial commit fr...
1112
1113
1114
1115
1116
      _fd_flush_events(process);

#if 0
      _fd_debug("[%d] setting up barrier 2\n", process);
      if (MPI_Barrier(MPI_COMM_WORLD))
eef94371   Vasco Pedro   Update to PaCCS v...
1117
	_fd_error("[%d] MPI_Barrier failed\n", process);
965dadaa   Salvador Abreu   initial commit fr...
1118
      else
eef94371   Vasco Pedro   Update to PaCCS v...
1119
	_fd_debug("[%d] leaving barrier 2\n", process);
965dadaa   Salvador Abreu   initial commit fr...
1120
#endif
eef94371   Vasco Pedro   Update to PaCCS v...
1121
    }
965dadaa   Salvador Abreu   initial commit fr...
1122
1123
1124
1125
1126

  _fd_statistics_msgs();

  _fd_debug("[%d] calling MPI_Finalize\n", process);
  if (MPI_Finalize())
eef94371   Vasco Pedro   Update to PaCCS v...
1127
    _fd_error("[%d] MPI_Finalize failed\n", process);
965dadaa   Salvador Abreu   initial commit fr...
1128
  else
eef94371   Vasco Pedro   Update to PaCCS v...
1129
    _fd_debug("[%d] returned from MPI_Finalize\n", process);
965dadaa   Salvador Abreu   initial commit fr...
1130
}
eef94371   Vasco Pedro   Update to PaCCS v...
1131

965dadaa   Salvador Abreu   initial commit fr...
1132
1133
1134
1135
1136
1137
static void _fd_exit_process(int process)
{
  _fd_cleanup_mpi_state(process);

  _fd_debug("[%d] exiting\n", process);

eef94371   Vasco Pedro   Update to PaCCS v...
1138
  exit(0);
965dadaa   Salvador Abreu   initial commit fr...
1139
1140
1141
1142
1143
1144
}

void _fd_search_space_sizes(_fd_store stores[], int n)
{
#ifndef FAST
  double s;
eef94371   Vasco Pedro   Update to PaCCS v...
1145
  int i, v;
965dadaa   Salvador Abreu   initial commit fr...
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159

  // when there are no agents, just return
  if (*stores == NULL)
    return;

  for (i = 0; i < n; ++i)
    {
      s = 1;

      for (v = 0; v < fd__label_vars_count; ++v)
	s *= _fd_val_size(SVALUE(stores[i][fd__label_vars[v]->index]));

      _fd_debug("[%d] search space %d size is %g\n", tid, i, s);
    }
eef94371   Vasco Pedro   Update to PaCCS v...
1160
#endif /* FAST */
965dadaa   Salvador Abreu   initial commit fr...
1161
}
eef94371   Vasco Pedro   Update to PaCCS v...
1162

965dadaa   Salvador Abreu   initial commit fr...
1163
1164
1165
1166
static void count_singletons(_fd_store store)
{
#ifndef FAST
  int i, n;
eef94371   Vasco Pedro   Update to PaCCS v...
1167

965dadaa   Salvador Abreu   initial commit fr...
1168
1169
1170
1171
1172
1173
1174
1175
  n = 0;

  for (i = 0; i < fd_variables_count; ++i)
    if (_fd_val_single(SVALUE(store[i]), NULL))
      ++n;

  _fd_debug("[%d] store has %d/%d/%d singletons\n", tid, n,
	    fd__label_vars_count, fd_variables_count);
eef94371   Vasco Pedro   Update to PaCCS v...
1176
#endif
965dadaa   Salvador Abreu   initial commit fr...
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
}

#if STEAL_WORK >= 2
static int _fd_restart_agents(int tid, int nagents)
{
  int parts;

  // split the store among the agents
  parts = fd__split_problem(nagents, _fd_agents_stores, fd__split_team_problem_f);

  if (parts < nagents)
    _fd_debug("[%d] WARNING: store only good for %d agents (out of %d)\n",
	      tid, parts, nagents);
eef94371   Vasco Pedro   Update to PaCCS v...
1190

965dadaa   Salvador Abreu   initial commit fr...
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
  agents_to_run = parts;

  // reset the pool
  _fd_init_store_depository(agents_to_run);

  // give the agents the go-ahead
  if (pthread_mutex_lock(&continue_mutex))
    perror("pthread_mutex_lock");
  pthread_cond_broadcast(&continue_cond);
  if (pthread_mutex_unlock(&continue_mutex))
    perror("pthread_mutex_unlock");

  _fd_debug("[%d] told waiting agents to proceed\n", tid);

eef94371   Vasco Pedro   Update to PaCCS v...
1205
  return parts;
965dadaa   Salvador Abreu   initial commit fr...
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
}

#ifndef ROUND_ROBIN_POLL

#define _fd_start_polling(x) _fd_poll_next(processes, x)

static int _fd_poll_next(int last, int skip)
{
  int poll;

  poll = last - 1;

  // skip over both self and the ex-supplier (if it is not process 0)
  while (poll == tid || poll == skip && skip != 0)
    --poll;

  if (poll >= 0)
    {
      // send a forceful request for work
      _fd_debug("[%d] polling %d\n", tid, poll);
      _fd_send(poll, FD_MSG_SHARE);
eef94371   Vasco Pedro   Update to PaCCS v...
1227
    }
965dadaa   Salvador Abreu   initial commit fr...
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265

  return poll;
}
#else /* ROUND_ROBIN_POLL */

#define _fd_start_polling(x) _fd_poll_rr(true, processes, x)
#define _fd_poll_next(l, x) _fd_poll_rr(false, l, x)

static int _fd_poll_rr(bool starting, int np_or_last, int skip)
{
  static int processes = 0;
  static int tried, last_polled;
  int poll;
  int i;

  if (starting)
    {
      tried = 0;

      if (processes == 0)
	{
	  processes = np_or_last;
	  last_polled = tid;
	}
    }

  poll = (last_polled + 1) % processes;

  // skip over both the ex-supplier and self
  for (; tried < processes && (poll == tid || poll == skip); ++tried)
    poll = (poll + 1) % processes;

  if (tried == processes)
    return -1;

  // send a forceful request for work
  _fd_debug("[%d] polling %d\n", tid, poll);
  _fd_send(poll, FD_MSG_SHARE);
eef94371   Vasco Pedro   Update to PaCCS v...
1266

965dadaa   Salvador Abreu   initial commit fr...
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
  last_polled = poll;

  return poll;
}
#endif /* ROUND_ROBIN_POLL */

// try to share work with PEER, return true on success
// XXX: side-effect: when true is returned, the process will cease to
//      be the supplier
static bool _fd_share_work(int peer, MPI_Request *request, fd_list saved_stores,
			   bool polled)
{
  _fd_store saved;
  int mpi_flag;

  // test whether a previously sent store has yet to be received
  if (MPI_Test(request, &mpi_flag, MPI_STATUS_IGNORE))
    perror("MPI_Test");

  if (!mpi_flag)
    {
      // the previous send has not completed
      _fd_debug("[%d] there's a store in transit to %d\n", tid, peer);

eef94371   Vasco Pedro   Update to PaCCS v...
1291
      /* despite MPI_Test() having failed, the store may already have
965dadaa   Salvador Abreu   initial commit fr...
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
	 been received and processed; since process 0 must receive or
	 give an answer, otherwise there's a risk of deadlock, we'll
	 force one when it is involved */

      if (peer != 0 && tid != 0)
	return true;

      if (MPI_Wait(request, MPI_STATUS_IGNORE))
	perror("MPI_Wait");
    }

  // see if there's a saved store which can be sent
  if (saved = fd_list_remove(saved_stores))
    {
      memcpy(_fd_processes_stores[peer], saved,
	     fd_variables_count * sizeof(*saved));

      _fd_debug("[%d] sending store (saved) to %d\n", tid, peer);
      _fd_send_store(peer, FD_MSG_STORE, _fd_processes_stores[peer], request,
eef94371   Vasco Pedro   Update to PaCCS v...
1311
		     true);
965dadaa   Salvador Abreu   initial commit fr...
1312
1313
1314
1315
1316
1317
1318
1319

      free(saved);

      return true;
    }

#ifndef INDEX_IN_POOL
  if (_fd_steal_store(_fd_processes_stores[peer], -1, 0))
965dadaa   Salvador Abreu   initial commit fr...
1320
#else
965dadaa   Salvador Abreu   initial commit fr...
1321
  if (_fd_steal_store(_fd_processes_stores[peer], NULL, -1, 0))
eef94371   Vasco Pedro   Update to PaCCS v...
1322
#endif
965dadaa   Salvador Abreu   initial commit fr...
1323
1324
1325
1326
1327
1328
1329
1330
1331
    {
      _fd_debug("[%d] sending store to %d\n", tid, peer);
      _fd_send_store(peer, FD_MSG_STORE, _fd_processes_stores[peer], request,
		     true);

      return true;
    }

  // tell the requester that there is no work available
eef94371   Vasco Pedro   Update to PaCCS v...
1332
  if (polled)
965dadaa   Salvador Abreu   initial commit fr...
1333
1334
1335
1336
    {
      _fd_debug("[%d] no work to share with %d\n", tid, peer);
      _fd_send(peer, FD_MSG_NO_SHARE);
    }
eef94371   Vasco Pedro   Update to PaCCS v...
1337
  else
965dadaa   Salvador Abreu   initial commit fr...
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
    {
      _fd_debug("[%d] can't find work requested by %d\n", tid, peer);
      _fd_send(peer, FD_MSG_NO_WORK);
    }

  return false;
}

/* Process PEER has polled last resort process 0 for work unsuccessfully,
   and (probably) has become idle. If all remaining processes are idle,
   stop them. */
#define mark_process_idle(peer)						     \
	do								     \
	  {								     \
	    int _p = peer;						     \
									     \
	    if (!process_idle[_p])					     \
	      {								     \
eef94371   Vasco Pedro   Update to PaCCS v...
1356
		/* record polling process as idle */			     \
965dadaa   Salvador Abreu   initial commit fr...
1357
1358
1359
1360
1361
		gettimeofday(&to, NULL); timersub(&to, &ti, &to);	     \
		_fd_debug("[%d] %d idled after %d.%06ds\n", tid, _p,	     \
			   to.tv_sec, to.tv_usec);			     \
									     \
		process_idle[_p] = true;				     \
eef94371   Vasco Pedro   Update to PaCCS v...
1362
		if (++idle_processes == live_procs - 1)			     \
965dadaa   Salvador Abreu   initial commit fr...
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
		  {							     \
		    _fd_debug("[%d] sending 2nd quit\n", tid);		     \
									     \
		    _fd_broadcast(FD_MSG_QUIT, processes, tid);		     \
		  }							     \
	      }								     \
	  }								     \
	while (0)
#endif /* STEAL_WORK >= 2 */

int _fd_dsolve()
{
  pthread_t threads[MAX_AGENTS];
  int nagents = 4, started, running, peer;
  int status = FD_NOSOLUTION;
  int parts;
  int i;
  struct timeval ti, to, ts = { 0, 0 };
  char *s;
  int processes, live_procs;
#if STEAL_WORK >= 2
  bool *process_idle;		// processes who have polled process 0
  int idle_processes = 0;
  bool quitting = false;
  MPI_Request *stores_pending;	// to trace the reception of a store
  int supplier;
#endif
  MPI_Status mpi_status;
  int done, stopped;
  _fd_store solution;
  bool have_solution = false;
  int bound;

  unsigned long long external_solutions = 0; // other processes' solutions count

  fd_int *local_variables = _fd_variables;
  _fd_store local_store = store;

  gettimeofday(&ti, NULL);
eef94371   Vasco Pedro   Update to PaCCS v...
1402

965dadaa   Salvador Abreu   initial commit fr...
1403
  if (MPI_Comm_rank(MPI_COMM_WORLD, &tid))
eef94371   Vasco Pedro   Update to PaCCS v...
1404
    _fd_fatal("MPI_Comm_rank failed\n");
965dadaa   Salvador Abreu   initial commit fr...
1405
1406
1407
1408

  _fd_debug("I'm MPI rank %d\n", tid);

  {
eef94371   Vasco Pedro   Update to PaCCS v...
1409
1410
    char host[512];

965dadaa   Salvador Abreu   initial commit fr...
1411
1412
1413
    gethostname(host, sizeof(host));
    _fd_debug("[%d] process %d at %s\n", tid, getpid(), host);
  }
eef94371   Vasco Pedro   Update to PaCCS v...
1414

965dadaa   Salvador Abreu   initial commit fr...
1415
  if (MPI_Comm_size(MPI_COMM_WORLD, &processes))
eef94371   Vasco Pedro   Update to PaCCS v...
1416
    _fd_fatal("MPI_Comm_size failed\n");
965dadaa   Salvador Abreu   initial commit fr...
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441

  _fd_debug("[%d] There are %d of us\n", tid, processes);

  pending_requests = fd_list_new();

#if STEAL_WORK >= 2
  stores_pending = calloc(processes, sizeof(*stores_pending)); // XXX: NULL
  for (i = 0; i < processes; ++i)
    stores_pending[i] = MPI_REQUEST_NULL;

  // the last process is the one which can supply work to the others
  supplier = tid == processes - 1;

  process_idle = alloca(processes * sizeof(*process_idle));
  memset(process_idle, 0, processes * sizeof(*process_idle));
#endif

  if (fd__workers == -1 && (s = getenv("FDC_AGENTS")))
    fd__workers = atoi(s);

  if (fd__workers != -1)
    {
      nagents = fd__workers;

      if (nagents < 0)
a2ec137b   Vasco Pedro   updated to PaCCS ...
1442
	{
965dadaa   Salvador Abreu   initial commit fr...
1443
1444
1445
1446
	  nagents = 0;
	  fd__info("[%d] using %d workers\n", tid, nagents);
	}
      else if (nagents > MAX_AGENTS)
a2ec137b   Vasco Pedro   updated to PaCCS ...
1447
	{
965dadaa   Salvador Abreu   initial commit fr...
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
	  nagents = MAX_AGENTS;
	  fd__info("[%d] limiting workers to %d\n", tid, nagents);
	}
    }

  // allocate stores for all the processes, in case one needs to borrow
  // work from this one
  for (i = 0; i < processes; ++i)
    _fd_processes_stores[i] = calloc(fd_variables_count, sizeof(*store)); // XXX: NULL

  fd__setup_label_vars();

  if (tid == 0)
    {
      // code for the controlling process

      MPI_Request mpi_request = MPI_REQUEST_NULL;

#ifdef FILTER_DOMAINS
      // XXX: *must* revise as the splitting proceeds!
      if (_fd_filter_domains() == FD_NOSOLUTION)
	return FD_NOSOLUTION;
#endif

      // do an initial partition among all the processes
      // XXX: check if processes <= MAX_AGENTS ('cause of _fd_processes_stores)
      parts = fd__split_problem(processes, _fd_processes_stores, fd__split_problem_f);
eef94371   Vasco Pedro   Update to PaCCS v...
1475
      _fd_search_space_sizes(_fd_processes_stores, parts);
965dadaa   Salvador Abreu   initial commit fr...
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
      if (parts < processes)
	_fd_error("WARNING: work enough for %d processes only\n", parts);

      // now send the resulting parts to the other processes
      // XXX: could each have done what this did and now pick its share?
      for (i = 1; i < parts; ++i)
	_fd_send_store(i, FD_MSG_STORE, _fd_processes_stores[i], &mpi_request,
		       false);

      for (i = parts; i < processes; ++i)
	fd__send_empty_store(i, FD_MSG_STORE, _fd_processes_stores[i], &mpi_request);

      processes = parts;

      // install our part of the search space
      memcpy(store, _fd_processes_stores[0], fd_variables_count * sizeof(*store));
    }
  else
    {
eef94371   Vasco Pedro   Update to PaCCS v...
1495
      // code for the remaining processes
965dadaa   Salvador Abreu   initial commit fr...
1496
1497
1498
1499

      _fd_debug("[%d] waiting for initial store\n", tid);

      // retrieve the domains assigned to the process
eef94371   Vasco Pedro   Update to PaCCS v...
1500
      if (!_fd_recv_store(0, FD_MSG_STORE, store))
965dadaa   Salvador Abreu   initial commit fr...
1501
1502
1503
1504
      	{
	  _fd_debug("[%d] empty initial store\n", tid);

	  _fd_exit_process(tid);
eef94371   Vasco Pedro   Update to PaCCS v...
1505
	}
965dadaa   Salvador Abreu   initial commit fr...
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530

      _fd_debug("[%d] received initial store\n", tid);
    }

#if FILTER_DOMAINS > 1
  // XXX: *must* revise as the splitting proceeds!
  if (_fd_filter_domains() == FD_NOSOLUTION)
    return FD_NOSOLUTION;	      // XXX: should try to obtain a new store
#endif

  // now, get on with the search
  _fd_copy_problem(nagents);

  // allocate space to keep a solution
  if (_fd_optimising)
    solution = calloc(fd_variables_count, sizeof(*solution)); // XXX: NULL?
  else
    solution = store;

  // create agents' stores
  for (i = 0; i < nagents; ++i)
    _fd_agents_stores[i] = calloc(fd_variables_count, sizeof(*store)); // XXX: NULL

  parts = fd__split_problem(nagents, _fd_agents_stores, fd__split_team_problem_f);

eef94371   Vasco Pedro   Update to PaCCS v...
1531
  if (parts < nagents)
965dadaa   Salvador Abreu   initial commit fr...
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
    {
      _fd_debug("[%d] reducing to %d agents!\n", tid, parts);

      nagents = parts;
    }

  // XXX: pretend there are stores for every agent (should always happen)
  agents_to_run = nagents;

  _fd_search_space_sizes(_fd_agents_stores, parts);

eef94371   Vasco Pedro   Update to PaCCS v...
1543
  gettimeofday(&to, NULL);
965dadaa   Salvador Abreu   initial commit fr...
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
  timersub(&to, &ti, &to);
  _fd_debug("[%d] setup took %d.%06ds\n", tid, to.tv_sec, to.tv_usec);

#if 0
  for (i = 0; i < nagents; ++i)
    _fd_cprint2(_fd_copies[i]);

  return FD_NOSOLUTION;
#endif

  if (nagents > 0)
    {
      int timeout = 0;
#if STEAL_WORK >= 2
      int timeouts;
      int ex_supplier, polling;
      fd_list saved_stores = fd_list_new();
      _fd_message waiting_on;
      bool ready = false;	// true means no pending communications
#ifdef ASK_EARLY
      bool waiting_for_work = false;
      bool getting_work_failed = false;
#endif
#endif

      _fd_init_store_depository(nagents);

      if (sem_init(&ready_semaphore, 0, 1))
	perror("sem_init (ready)");
      if (sem_init(&notify_semaphore, 0, 0))
	perror("sem_init (notify)");
      if (_fd_optimising && sem_init(&resume_semaphore, 0, 0))
	  perror("sem_init (resume)");

      for (i = started = 0; i < nagents; ++i)
	{
	  long l = i; // XXX: avoid a gcc warning

	  pthread_create(&threads[i], NULL, (void *) _fd_agent, (void *) l);

	  started++;

	  // don't start any more agents if one has already succeeded
	  if (!_fd_counting_solutions && !_fd_optimising)
	    {
	      if (pthread_mutex_trylock(&success_mutex) == 0)
		pthread_mutex_unlock(&success_mutex);
	      else
		break;
	    }
eef94371   Vasco Pedro   Update to PaCCS v...
1594
	}
965dadaa   Salvador Abreu   initial commit fr...
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607

      _fd_debug("[%d] main thread waiting\n", tid);

      running = started;
      live_procs = processes;
      done = stopped = 0;

      do
	{
	  int event = _fd_get_event(running, &peer, &timeout);

	  switch (event)
	    {
eef94371   Vasco Pedro   Update to PaCCS v...
1608
#if STEAL_WORK >= 2
965dadaa   Salvador Abreu   initial commit fr...
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
	    case EV_INT_TIMEOUT:
	      _fd_debug("[%d] timed out waiting for event\n", tid);

	      switch (waiting_on)
		{
		case FD_MSG_ANY:
		  done = 1;
		  break;
		case FD_MSG_FEED_ME:
		  // no work sharing after having been told to stop
		  if (quitting || ready)
		    break;

		  if (timeouts++)
		    {
		      if (tid != 0 || live_procs > 1)
			{
			  polling = _fd_start_polling(ex_supplier = tid);

			  waiting_on = FD_MSG_SHARE;
			  if (polling == 0)
			    timeout = 0;	// last resort polling
			  else
			    timeout = POLL_TIMEOUT;
			}
		      else
#ifndef ASK_EARLY
			done = 1;
#else
			done = running == 0;

		      waiting_for_work = false;
		      getting_work_failed = true;
#endif
		    }
		  else
eef94371   Vasco Pedro   Update to PaCCS v...
1645
		    {
965dadaa   Salvador Abreu   initial commit fr...
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
		      // resend request for work
		      _fd_debug("[%d] re-asking for work\n", tid);
		      _fd_broadcast(FD_MSG_FEED_ME, processes, tid);

		      timeout = FEED2_TIMEOUT;
		    }
		  break;
		case FD_MSG_SHARE:
		  // no work sharing after having been told to stop
		  if (quitting || ready)
		    break;

		  // the last polled process must have stopped
		  // try the next one
		  if ((polling = _fd_poll_next(polling, ex_supplier)) >= 0)
		    {
		      if (polling == 0)
			timeout = 0;		// last resort polling
		      else
			timeout = POLL_TIMEOUT;	// reset timeout
		    }
		  else
		    {
		      // no additional work could be found

		      done = tid != 0 || live_procs == 1;

#ifdef ASK_EARLY
		      done = done && running == 0;
		      waiting_for_work = false;
		      getting_work_failed = true;
#endif

		      if (tid == 0)
			{
			  // XXX: ???
			  // become the supplier, to answer further requests
			  // for work, even if negatively
			  supplier = 1;
			}
		    }

eef94371   Vasco Pedro   Update to PaCCS v...
1688
1689
		  break;
		default:
965dadaa   Salvador Abreu   initial commit fr...
1690
1691
1692
1693
1694
1695
1696
1697
		  _fd_debug("[%d] unknown timeout: %d\n", tid, waiting_on);
		  _fd_fatal("unknown timeout reason");
		}

	      break;
#endif /* STEAL_WORK >= 2 */

	    /* first solution internal events (from the workers) */
eef94371   Vasco Pedro   Update to PaCCS v...
1698

965dadaa   Salvador Abreu   initial commit fr...
1699
1700
1701
1702
1703
1704
1705
1706
	    case EV_INT_SUCCESS:
	      _fd_debug("[%d] using agent %d's results\n", tid, peer);

	      assert(!_fd_counting_solutions);

	      if (_fd_optimising)
		{
		  // check and update bound
eef94371   Vasco Pedro   Update to PaCCS v...
1707
		  if (!_fd_bound_check_set(_fd_agents_stores[peer]))
965dadaa   Salvador Abreu   initial commit fr...
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
		    {
		      _fd_debug("[%d] invalid solution, releasing %d\n", tid, peer);
		      if (sem_post(&resume_semaphore))
			perror("sem_post (resume)");

		      break;
		    }

		  gettimeofday(&ts, NULL);

		  // save solution
		  memcpy(solution, _fd_agents_stores[peer],
			 fd_variables_count * sizeof(*solution));
eef94371   Vasco Pedro   Update to PaCCS v...
1721

965dadaa   Salvador Abreu   initial commit fr...
1722
1723
1724
		  // release agent
		  _fd_debug("[%d] releasing agent %d\n", tid, peer);
		  if (sem_post(&resume_semaphore))
eef94371   Vasco Pedro   Update to PaCCS v...
1725
		    perror("sem_post (resume)");
965dadaa   Salvador Abreu   initial commit fr...
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746

		  _fd_debug("[%d] bound updated to %d\n", tid, _fd_bound_value());

		  // broadcast new bound
		  bound = _fd_bound_value();
		  _fd_broadcast_data(FD_MSG_BOUND, &bound, 1, MPI_INT,
				     processes, tid);

		  status = FD_OK;
		  have_solution = true;

		  break;
		}

	      status = FD_OK;

	      memcpy(store, _fd_agents_stores[peer],
		     fd_variables_count * sizeof(*store));

	      done = 1;

eef94371   Vasco Pedro   Update to PaCCS v...
1747
	      break;
965dadaa   Salvador Abreu   initial commit fr...
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
	    case EV_INT_FAIL:
	      _fd_debug("[%d] agent %d found no solution\n", tid, peer);

	      assert(!_fd_counting_solutions);

	      running--;

#if STEAL_WORK < 2
	      done = running == 0 && (tid != 0 || live_procs == 1);
#else /* STEAL_WORK < 2 */
#ifdef ASK_EARLY
	      if (running == agents_to_run - 1)
		{
		  // the first agent halted and the other agents must
		  // be stopping soon; try to get work before they do

		  // no need if we already have a store saved up
		  if (fd_list_empty(saved_stores))
		    {
		      // ask the other processes for more work, unless this
		      // is the rank 0 process and all others have finished
		      if (tid != 0 || live_procs > 1)
			{
eef94371   Vasco Pedro   Update to PaCCS v...
1771
			  if (!supplier)
965dadaa   Salvador Abreu   initial commit fr...
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
			    {
			      _fd_debug("[%d] asking for work\n", tid);
			      _fd_broadcast(FD_MSG_FEED_ME, processes, tid);

			      waiting_on = FD_MSG_FEED_ME;
			      timeout = FEED1_TIMEOUT;
			      timeouts = 0;
			    }
			  else
			    {
			      // poll the other processes for work
			      polling = _fd_start_polling(ex_supplier = tid);

			      waiting_on = FD_MSG_SHARE;
			      if (polling == 0)
				timeout = 0;		// last resort polling
			      else
				timeout = POLL_TIMEOUT;	// set timeout
			    }

			  waiting_for_work = true;
			}
		    }
		}
#endif /* ASK_EARLY */

	      if (running == 0)
		{
		  _fd_store saved;

		  // see if there's some store saved up
eef94371   Vasco Pedro   Update to PaCCS v...
1803
		  if (saved = fd_list_remove(saved_stores))
965dadaa   Salvador Abreu   initial commit fr...
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
		    {
		      _fd_debug("[%d] using saved store\n", tid);

		      memcpy(store, saved,
			     fd_variables_count * sizeof(*saved));

		      count_singletons(store);

		      // restart the agents
		      running = _fd_restart_agents(tid, nagents);

		      free(saved);
		    }
#ifdef ASK_EARLY
		  else if (waiting_for_work)
		    {
		      // we're already trying to get work, let's
		      // wait and see how that fans out

		      break;
		    }
		  else if (getting_work_failed)
		    {
		      // if we already have tried to get work and
		      // failed, it's no use doing it again

		      done = tid != 0 || live_procs == 1;

		      break;
		    }
#endif /* ASK_EARLY */
		  else if (quitting || ready)
		    done = quitting && (tid != 0 || live_procs == 1);
		  else if (tid != 0 || live_procs > 1)
		    {
		      // there is at least one other process still running
		      if (!supplier)
eef94371   Vasco Pedro   Update to PaCCS v...
1841
			{
965dadaa   Salvador Abreu   initial commit fr...
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
			  // ask the other processes for more work
			  _fd_debug("[%d] asking for work\n", tid);
			  _fd_broadcast(FD_MSG_FEED_ME, processes, tid);

			  waiting_on = FD_MSG_FEED_ME;
			  timeout = FEED1_TIMEOUT;
			  timeouts = 0;
			}
		      else
			{
			  // poll the other processes for work
			  polling = _fd_start_polling(ex_supplier = tid);

			  waiting_on = FD_MSG_SHARE;
			  if (polling == 0)
			    timeout = 0;		// last resort polling
			  else
			    timeout = POLL_TIMEOUT;	// set timeout
			}

#ifdef ASK_EARLY
		      waiting_for_work = true;
#endif
		    }
		  else
		    done = 1;
		}
#endif /* STEAL_WORK < 2 */

	      break;

	    /* first solution external events (from the other processes) */
eef94371   Vasco Pedro   Update to PaCCS v...
1874

965dadaa   Salvador Abreu   initial commit fr...
1875
1876
1877
1878
1879
	    case EV_EXT_SUCCESS:
	      _fd_debug("[%d] received a solution from %d\n", tid, peer);

	      assert(!_fd_counting_solutions);

eef94371   Vasco Pedro   Update to PaCCS v...
1880
	      _fd_recv_store(peer, FD_MSG_SOLUTION, store);
965dadaa   Salvador Abreu   initial commit fr...
1881
1882
1883

	      _fd_debug("[%d] using process %d's results\n", tid, peer);

eef94371   Vasco Pedro   Update to PaCCS v...
1884
1885
	      gettimeofday(&to, NULL);
	      timersub(&to, &ti, &to);
965dadaa   Salvador Abreu   initial commit fr...
1886
1887
1888
1889
1890
1891
1892
#if defined(STATS_PROCS) || !defined(FAST)
	      fd__info("[%d] process %d took %d.%06ds\n", tid, peer, to.tv_sec, to.tv_usec);
#endif

	      if (_fd_optimising)
		{
		  // see if it is the better solution
eef94371   Vasco Pedro   Update to PaCCS v...
1893
		  if (!have_solution || _fd_better_solution(store, solution))
965dadaa   Salvador Abreu   initial commit fr...
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
		    {
		      _fd_debug("[%d] process %d solution is better\n", tid, peer);

		      memcpy(solution, store,
			     fd_variables_count * sizeof(*store));

		      status = FD_OK;
		      have_solution = true;
		      ts.tv_sec = 0;

		      // XXX: could update the current bound
		    }

		  live_procs--;
		  done = live_procs == 1 && running == 0;

		  break;
		}

	      status = FD_OK;

	      done = 1;

eef94371   Vasco Pedro   Update to PaCCS v...
1917
	      break;
965dadaa   Salvador Abreu   initial commit fr...
1918
1919
1920
1921
1922
	    case EV_EXT_FAIL:
	      _fd_debug("[%d] process %d found no solution\n", tid, peer);

	      assert(!_fd_counting_solutions);

eef94371   Vasco Pedro   Update to PaCCS v...
1923
1924
	      gettimeofday(&to, NULL);
	      timersub(&to, &ti, &to);
965dadaa   Salvador Abreu   initial commit fr...
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
#if defined(STATS_PROCS) || !defined(FAST)
	      fd__info("[%d] process %d took %d.%06ds\n", tid, peer, to.tv_sec, to.tv_usec);
#endif

	      live_procs--;

#if STEAL_WORK >= 2
	      // become the supplier, so further requests for work will
	      // be answered
	      // XXX: some requests for work may get lost
	      // XXX: side effect: this process *will* try to supply work
	      supplier = 1;
#endif

	      done = running == 0 && live_procs == 1;
#ifdef ASK_EARLY
	      done = done && !waiting_for_work;
#endif

eef94371   Vasco Pedro   Update to PaCCS v...
1944
	      break;
965dadaa   Salvador Abreu   initial commit fr...
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
	    case EV_EXT_DONE:
	      _fd_debug("[%d] process %d told me to stop\n", tid, peer);

	      assert(!_fd_counting_solutions);

	      done = stopped = 1;

	      break;

	    /* optimisation external events (from the other processes) */
eef94371   Vasco Pedro   Update to PaCCS v...
1955

965dadaa   Salvador Abreu   initial commit fr...
1956
1957
1958
1959
1960
1961
1962
1963
	    case EV_EXT_BOUND:
	      _fd_debug("[%d] received new bound from %d\n", tid, peer);

	      assert(!_fd_counting_solutions && _fd_optimising);

	      {
		int bound;

eef94371   Vasco Pedro   Update to PaCCS v...
1964
		if (MPI_Recv(&bound, 1, MPI_INT, peer, FD_MSG_BOUND,
965dadaa   Salvador Abreu   initial commit fr...
1965
1966
1967
1968
			     MPI_COMM_WORLD, &mpi_status))
		  _fd_fatal("MPI_Recv failed");

		// try to set new bound
eef94371   Vasco Pedro   Update to PaCCS v...
1969
		if (_fd_set_bound(bound))
965dadaa   Salvador Abreu   initial commit fr...
1970
1971
1972
1973
		  {
		    _fd_debug("[%d] new bound is %d\n", tid, bound);

		    // bound has been reset, invalidate previous solution
eef94371   Vasco Pedro   Update to PaCCS v...
1974
		    if (have_solution && !_fd_bound_check(solution))
965dadaa   Salvador Abreu   initial commit fr...
1975
1976
1977
1978
1979
1980
		      {
			_fd_debug("[%d] invalidating current solution\n", tid);

			status = FD_NOSOLUTION;
			have_solution = false;
		      }
eef94371   Vasco Pedro   Update to PaCCS v...
1981
		  }
965dadaa   Salvador Abreu   initial commit fr...
1982
1983
1984
1985
1986
1987
1988
		else
		  _fd_debug("[%d] invalid bound %d\n", tid, bound);
	      }

	      break;

	    /* counting solutions internal events (from the workers) */
eef94371   Vasco Pedro   Update to PaCCS v...
1989

965dadaa   Salvador Abreu   initial commit fr...
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
	    case EV_INT_COUNT:
	      _fd_debug("[%d] agent %d is done\n", tid, peer);

	      assert(_fd_counting_solutions);

	      running--;

#if STEAL_WORK < 2
	      done = running == 0 && (tid != 0 || live_procs == 1);
#else /* STEAL_WORK < 2 */
#ifdef ASK_EARLY
	      if (running == agents_to_run - 1)
		{
		  // the first agent halted and the other agents must
		  // be stopping soon; try to get work before they do

		  // no need if we already have a store saved up
		  if (fd_list_empty(saved_stores))
		    {
		      // ask the other processes for more work, unless this
		      // is the rank 0 process and all others have finished
		      if (tid != 0 || live_procs > 1)
			{
eef94371   Vasco Pedro   Update to PaCCS v...
2013
			  if (!supplier)
965dadaa   Salvador Abreu   initial commit fr...
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
			    {
			      _fd_debug("[%d] asking for work\n", tid);
			      _fd_broadcast(FD_MSG_FEED_ME, processes, tid);

			      waiting_on = FD_MSG_FEED_ME;
			      timeout = FEED1_TIMEOUT;
			      timeouts = 0;
			    }
			  else
			    {
			      // poll the other processes for work
			      polling = _fd_start_polling(ex_supplier = tid);

			      waiting_on = FD_MSG_SHARE;
			      if (polling == 0)
				timeout = 0;		// last resort polling
			      else
				timeout = POLL_TIMEOUT;	// set timeout
			    }

			  waiting_for_work = true;
			}
		    }
		}
#endif /* ASK_EARLY */

	      if (running == 0)
		{
		  _fd_store saved;

		  // see if there's some store saved up
eef94371   Vasco Pedro   Update to PaCCS v...
2045
		  if (saved = fd_list_remove(saved_stores))
965dadaa   Salvador Abreu   initial commit fr...
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
		    {
		      _fd_debug("[%d] using saved store\n", tid);

		      memcpy(store, saved,
			     fd_variables_count * sizeof(*saved));

		      count_singletons(store);

		      // restart the agents
		      running = _fd_restart_agents(tid, nagents);

		      free(saved);
		    }
#ifdef ASK_EARLY
		  else if (waiting_for_work)
		    {
		      // we're already trying to get work, let's
		      // wait and see how that fans out

		      break;
		    }
		  else if (getting_work_failed)
		    {
		      // if we already have tried to get work and
		      // failed, it's no use doing it again

		      done = tid != 0 || live_procs == 1;

		      break;
		    }
#endif /* ASK_EARLY */
		  else if (quitting || ready)
		    done = quitting && (tid != 0 || live_procs == 1);
		  else if (tid != 0 || live_procs > 1)
		    {
		      // there is at least one other process still running
		      if (!supplier)
eef94371   Vasco Pedro   Update to PaCCS v...
2083
			{
965dadaa   Salvador Abreu   initial commit fr...
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
			  // ask the other processes for more work
			  _fd_debug("[%d] asking for work\n", tid);
			  _fd_broadcast(FD_MSG_FEED_ME, processes, tid);

			  waiting_on = FD_MSG_FEED_ME;
			  timeout = FEED1_TIMEOUT;
			  timeouts = 0;
			}
		      else
			{
			  // poll the other processes for work
			  polling = _fd_start_polling(ex_supplier = tid);

			  waiting_on = FD_MSG_SHARE;
			  if (polling == 0)
			    timeout = 0;		// last resort polling
			  else
			    timeout = POLL_TIMEOUT;	// set timeout
			}

#ifdef ASK_EARLY
		      waiting_for_work = true;
#endif
		    }
		  else
		    done = 1;
		}
#endif /* STEAL_WORK < 2 */

	      break;

	    /* counting solutions external events (from the other processes) */
eef94371   Vasco Pedro   Update to PaCCS v...
2116

965dadaa   Salvador Abreu   initial commit fr...
2117
2118
2119
2120
2121
2122
2123
2124
	    case EV_EXT_COUNT:
	      _fd_debug("[%d] receiving count from %d\n", tid, peer);

	      assert(_fd_counting_solutions);

	      {
		unsigned long long ull;

eef94371   Vasco Pedro   Update to PaCCS v...
2125
		if (MPI_Recv(&ull, 1, MPI_LONG_LONG, peer, FD_MSG_COUNT,
965dadaa   Salvador Abreu   initial commit fr...
2126
2127
2128
			     MPI_COMM_WORLD, &mpi_status))
		  _fd_fatal("MPI_Recv failed");

eef94371   Vasco Pedro   Update to PaCCS v...
2129
		external_solutions += ull;
965dadaa   Salvador Abreu   initial commit fr...
2130
2131
2132
2133

		_fd_debug("[%d] process %d found %llu solutions\n", tid, peer, ull);
	      }

eef94371   Vasco Pedro   Update to PaCCS v...
2134
2135
	      gettimeofday(&to, NULL);
	      timersub(&to, &ti, &to);
965dadaa   Salvador Abreu   initial commit fr...
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
#if defined(STATS_PROCS) || !defined(FAST)
	      fd__info("[%d] process %d took %d.%06ds\n", tid, peer, to.tv_sec, to.tv_usec);
#endif

	      live_procs--;

#if STEAL_WORK >= 2
	      // become the supplier, so further requests for work will
	      // be answered
	      // XXX: some requests for work may get lost
	      // XXX: side effect: this process *will* try to supply work
	      supplier = 1;
#endif

	      done = running == 0 && live_procs == 1;
#ifdef ASK_EARLY
	      done = done && !waiting_for_work;
#endif

	      break;
#if STEAL_WORK >= 2

	    /* work stealing events (external) */
eef94371   Vasco Pedro   Update to PaCCS v...
2159

965dadaa   Salvador Abreu   initial commit fr...
2160
	    case EV_EXT_STORE:
eef94371   Vasco Pedro   Update to PaCCS v...
2161
	      _fd_debug("[%d] process %d sent a store\n", tid, peer);
965dadaa   Salvador Abreu   initial commit fr...
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198

if (waiting_on == FD_MSG_ANY) _fd_debug("[%d] recovered store\n", tid);

	      if (running == 0)
		{
		  // retrieve the store
		  _fd_recv_store(peer, FD_MSG_STORE, store);

		  // restart the agents
		  running = _fd_restart_agents(tid, nagents);

		  count_singletons(store);
		}
	      else
		{
		  // save the store just received for later
		  _fd_store new = calloc(fd_variables_count, sizeof(*new)); // XXX: NULL

		  // retrieve the store
		  _fd_recv_store(peer, FD_MSG_STORE, new);

		  fd_list_append(saved_stores, new);
		}

	      // this process becomes the supplier of work
	      // XXX: between the moment the store was sent and now
	      //      some requests for work may have been lost
	      supplier = !ready || tid == 0;

	      // cancel timeout
	      timeout = 0;
	      waiting_on = FD_MSG_NONE;

#ifdef ASK_EARLY
	      waiting_for_work = false;
#endif

eef94371   Vasco Pedro   Update to PaCCS v...
2199
	      break;
965dadaa   Salvador Abreu   initial commit fr...
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
	    case EV_EXT_REQ_WORK:
	      _fd_debug("[%d] process %d wants more work\n", tid, peer);

	      if (supplier)
		{
		  if (quitting || ready)
		    {
		      _fd_send(peer, FD_MSG_NO_WORK);

		      break;
		    }

		  if (_fd_share_work(peer, stores_pending + peer,
				     saved_stores, false))
		    supplier = 0;
		}

eef94371   Vasco Pedro   Update to PaCCS v...
2217
	      break;
965dadaa   Salvador Abreu   initial commit fr...
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
	    case EV_EXT_NO_WORK:
	      _fd_debug("[%d] process %d can't supply work\n", tid, peer);

	      // no work sharing after having been told to stop
	      if (quitting || ready)
		break;

	      // if the message is not expected, just ignore it
#ifndef ASK_EARLY
	      if (running > 0 || waiting_on != FD_MSG_FEED_ME)
#else
	      if (!waiting_for_work || waiting_on != FD_MSG_FEED_ME)
#endif
		break;

	      // poll the other processes for work
	      if ((polling = _fd_start_polling(ex_supplier = peer)) >= 0)
		{
		  waiting_on = FD_MSG_SHARE;
		  if (polling == 0)
		    timeout = 0;		// last resort polling
		  else
		    timeout = POLL_TIMEOUT;	// set timeout
		}
	      else
		{
		  // no additional work could be found
		  if (tid != 0)
#ifndef ASK_EARLY
		    done = 1;
#else
		    done = running == 0;
#endif
		  else
		    {
		      // become the supplier, to answer further requests
		      // for work, even if negatively
		      supplier = 1;

		      done = running == 0 && live_procs == 1;
		    }

		  // cancel timeout
		  timeout = 0;

#ifdef ASK_EARLY
		  waiting_for_work = false;
		  getting_work_failed = true;
#endif
		}

eef94371   Vasco Pedro   Update to PaCCS v...
2269
	      break;
965dadaa   Salvador Abreu   initial commit fr...
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
	    case EV_EXT_NO_SHARE:
	      _fd_debug("[%d] process %d can't share work\n", tid, peer);

	      // no work sharing after having been told to stop
	      if (quitting || ready)
		break;

	      // if the message is not expected, just ignore it
#ifndef ASK_EARLY
	      if (running > 0 || waiting_on != FD_MSG_SHARE)
#else
	      if (!waiting_for_work || waiting_on != FD_MSG_SHARE)
#endif
		break;

eef94371   Vasco Pedro   Update to PaCCS v...
2285
	      if (peer != polling)
965dadaa   Salvador Abreu   initial commit fr...
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
		{
		  _fd_debug("[%d] polling %d but got answer from %d\n",
			    tid, polling, peer);

		  // belated answer, ignore
		  break;
		}

	      // try the next process
	      if ((polling = _fd_poll_next(polling, ex_supplier)) >= 0)
		{
		  if (polling == 0)
		    timeout = 0;		// last resort polling
		  else
		    timeout = POLL_TIMEOUT;	// reset timeout
		}
	      else
		{
		  // no additional work could be found
		  if (tid != 0)
#ifndef ASK_EARLY
		    {
		      quitting = true;
		      done = 1;
		    }
#else
		    done = running == 0;
#endif
		  else
		    {
		      // become the supplier, to answer further requests
		      // for work, even if negatively
		      supplier = 1;

		      done = running == 0 && live_procs == 1;
		    }

		  // cancel timeout
		  timeout = 0;

#ifdef ASK_EARLY
		  waiting_for_work = false;
		  getting_work_failed = true;
#endif
		}

eef94371   Vasco Pedro   Update to PaCCS v...
2332
	      break;
965dadaa   Salvador Abreu   initial commit fr...
2333
2334
2335
2336
2337
2338
	    case EV_EXT_REQ_SHARE:
	      _fd_debug("[%d] process %d really wants work\n", tid, peer);

	      // if we're idle, there's nothing to share
	      if (running == 0 || quitting || ready) // XXX: could be < nagents
		{
eef94371   Vasco Pedro   Update to PaCCS v...
2339
		  // notify the asking process that there really isn't
965dadaa   Salvador Abreu   initial commit fr...
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
		  // work to be shared
		  _fd_debug("[%d] no work to share with %d\n", tid, peer);
		  _fd_send(peer, FD_MSG_NO_SHARE);

		  break;
		}

	      // see if there is work to share
	      if (_fd_share_work(peer, stores_pending + peer, saved_stores,
				 true))
		supplier = 0;

	      break;
eef94371   Vasco Pedro   Update to PaCCS v...
2353
	    case EV_EXT_READY:
965dadaa   Salvador Abreu   initial commit fr...
2354
2355
2356
2357
2358
2359
	      // peer has no work and no outgoing communications pending
	      _fd_debug("[%d] %d is done\n", tid, peer);

	      assert(tid == 0);

	      mark_process_idle(peer);
eef94371   Vasco Pedro   Update to PaCCS v...
2360

965dadaa   Salvador Abreu   initial commit fr...
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
	      // XXX: in mark_process_idle()
	      //_fd_debug("[%d] sending 2nd quit\n", tid);
	      //_fd_broadcast(FD_MSG_QUIT, processes, tid);

	      //done = running == 0 && live_procs == 1;

	      // become the supplier, to answer further requests
	      // for work, even if negatively
	      supplier = 1;

	      break;
eef94371   Vasco Pedro   Update to PaCCS v...
2372
	    case EV_EXT_QUIT:
965dadaa   Salvador Abreu   initial commit fr...
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
	      // possibilities for finding work have been exhausted
	      _fd_debug("[%d] %d told me to stop\n", tid, peer);

	      assert(tid != 0);

	      quitting = true;

	      done = running == 0 && ready;

	      if (done)
		waiting_on = FD_MSG_NONE;

	      break;
eef94371   Vasco Pedro   Update to PaCCS v...
2386
2387
#endif /* STEAL_WORK >= 2 */
	    default:
965dadaa   Salvador Abreu   initial commit fr...
2388
2389
2390
	      _fd_debug("[%d] unknown event in main loop: %d\n", tid, event);
	      _fd_fatal("unknown event in main loop");
	    }
eef94371   Vasco Pedro   Update to PaCCS v...
2391

965dadaa   Salvador Abreu   initial commit fr...
2392
2393
2394
2395
2396
2397
2398
2399
2400
#if STEAL_WORK >= 2
if (done) _fd_debug("[%d] done (quitting = %d, ready = %d, timeout = %d)\n", tid, quitting, ready, timeout);

	  // if it is important that the full search space is explored,
	  // make an extra effort for receiving messages that may have
	  // been delayed
	  if (done && waiting_on != FD_MSG_ANY &&
	      (_fd_counting_solutions ||
	       _fd_optimising ||
eef94371   Vasco Pedro   Update to PaCCS v...
2401
	       status != FD_OK && !stopped))
965dadaa   Salvador Abreu   initial commit fr...
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
	    {
	      _fd_debug("[%d] checking for any event before leaving\n", tid);

	      done = 0;
	      waiting_on = FD_MSG_ANY;
	      timeout = 1;

	      continue;
	    }

#ifdef MPICH2
#  define _count count
#  define _cancelled cancelled
#elif OPEN_MPI && OMPI_MAJOR_VERSION == 1 && OMPI_MINOR_VERSION > 4
#  define _count _ucount
#endif

	  // try to ensure that no store sent to another process is
	  // lost, which may happen when the process it was addressed
	  // to stopped before receiving it
	  // this applies when optimising or counting all solutions,
	  // and when looking for the first solution and none has yet
	  // been found

	  if (done && !ready && (status != FD_OK && !stopped || _fd_optimising))
	    {
	      bool cancel_pending = false;

	      for (i = 0; i < processes; ++i)
		{
		  int tries = 3;
		  MPI_Status mpi_status = { 99, 99, 99, 99, 99 };
		  int mpi_flag;

		  if (MPI_Test(stores_pending + i, &mpi_flag, &mpi_status))
		    perror("MPI_Test");

eef94371   Vasco Pedro   Update to PaCCS v...
2439
		  if (!mpi_flag)	// request hasn't completed
965dadaa   Salvador Abreu   initial commit fr...
2440
2441
2442
2443
2444
2445
		    {
		      _fd_debug("[%d] recovering outstanding store to %d\n",
				tid, i);

		      // try cancelling the send (or the cancel?)
		      if (MPI_Cancel(stores_pending + i))
eef94371   Vasco Pedro   Update to PaCCS v...
2446
			perror("MPI_Cancel");
965dadaa   Salvador Abreu   initial commit fr...
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457

		      _fd_debug("[%d] cancelled request\n", tid);

		      // allow the cancel some time to complete
		      do
			{
			  if (MPI_Test(stores_pending + i, &mpi_flag,
				       &mpi_status))
			    perror("MPI_Test");

			  if (mpi_flag)
eef94371   Vasco Pedro   Update to PaCCS v...
2458
			    break;
965dadaa   Salvador Abreu   initial commit fr...
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469

			  _fd_debug("[%d] cancelling store to %d didn't complete\n",
				    tid, i);

			  if (--tries == 0)
			    break;

			  millisleep(5);
			}
		      while (!mpi_flag);

eef94371   Vasco Pedro   Update to PaCCS v...
2470
		      if (!mpi_flag)  // cancel didn't complete, give up for now
965dadaa   Salvador Abreu   initial commit fr...
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
			{
			  _fd_debug("[%d] giving up cancelling store to %i for now\n",
				    tid, i);

			  // if no store is cancelled, will have to wait
			  // for this cancellation to complete; in the
			  // meantime, will check the incoming messages
			  done = 0;
			  timeout = 1;
			  waiting_on = FD_MSG_ANY;

			  continue;
eef94371   Vasco Pedro   Update to PaCCS v...
2483
			}
965dadaa   Salvador Abreu   initial commit fr...
2484
2485
2486
2487
2488
2489
2490
2491

		      _fd_debug("[%d] status = (%d, %d, %d, %d, %d)\n", tid,
				mpi_status.MPI_SOURCE, mpi_status.MPI_TAG,
				mpi_status.MPI_ERROR, mpi_status._count,
				mpi_status._cancelled);

		      MPI_Test_cancelled(&mpi_status, &mpi_flag);

eef94371   Vasco Pedro   Update to PaCCS v...
2492
		      if (!mpi_flag)
965dadaa   Salvador Abreu   initial commit fr...
2493
2494
2495
2496
			{
			  _fd_debug("[%d] cancel did not succeed\n", tid);

			  continue;
eef94371   Vasco Pedro   Update to PaCCS v...
2497
			}
965dadaa   Salvador Abreu   initial commit fr...
2498
2499
2500
2501
2502
2503
2504
2505
2506

		      _fd_debug("[%d] cancel succeeded\n", tid);
		    }
		  else
		    {
		      // this request may already have been cancelled
		      MPI_Test_cancelled(&mpi_status, &mpi_flag);

		      if (!mpi_flag)
eef94371   Vasco Pedro   Update to PaCCS v...
2507
			continue;	// the send has completed
965dadaa   Salvador Abreu   initial commit fr...
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533

		      _fd_debug("[%d] previously cancelled store to %d\n",
				  tid, i);
		    }

		  assert(stores_pending[i] == MPI_REQUEST_NULL);

		  // recover the store
		  memcpy(store, _fd_processes_stores[i],
			 fd_variables_count * sizeof(*store));

		  count_singletons(store);

		  // and restart
		  running = _fd_restart_agents(tid, nagents);

		  done = 0;

		  // cancel timeout
		  timeout = 0;

		  break;
		}

	      if (done)	// no store was cancelled
		{
eef94371   Vasco Pedro   Update to PaCCS v...
2534
		  if (tid != 0)
965dadaa   Salvador Abreu   initial commit fr...
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
		    {
		      _fd_debug("[%d] ready to leave\n", tid);

		      _fd_send(0, FD_MSG_READY);

		      // cease to be the supplier
		      supplier = 0;
		    }

		  done = tid == 0 && live_procs == 1;
		  timeout = 0;
		  ready = true;
		  quitting = false;
		}
	    }

#ifdef MPICH2
#  undef _count
#  undef _cancelled
#elif OPEN_MPI && OMPI_MAJOR_VERSION == 1 && OMPI_MINOR_VERSION > 4
#  undef _count
#endif
#endif /* STEAL_WORK >= 2 */
	}
      while (!done);

      if (!_fd_counting_solutions)
	{
	  // send word that this process is done
	  if (tid == 0)
	    {
	      // stop the other processes
eef94371   Vasco Pedro   Update to PaCCS v...
2567
	      if (live_procs > 1)
965dadaa   Salvador Abreu   initial commit fr...
2568
2569
2570
		{
		  _fd_debug("[%d] stopping all processes\n", tid);
		  _fd_broadcast(FD_MSG_DONE, processes, tid);
eef94371   Vasco Pedro   Update to PaCCS v...
2571
		}
965dadaa   Salvador Abreu   initial commit fr...
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
	      else
		_fd_debug("[%d] all other processes already stopped\n", tid);

	      if (_fd_optimising && status == FD_OK)
		{
		  assert(have_solution);

		  memcpy(store, solution, fd_variables_count * sizeof(*store));

		  if (ts.tv_sec)
eef94371   Vasco Pedro   Update to PaCCS v...
2582
		    {
965dadaa   Salvador Abreu   initial commit fr...
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
		      timersub(&ts, &ti, &ts);
		      _fd_debug("[%d] time to solution was %d.%06ds\n", tid,
				ts.tv_sec, ts.tv_usec);
		    }
		}
	    }
	  else if (!stopped)
	    {
	      MPI_Request mpi_request;

	      if (status == FD_OK)
		{
eef94371   Vasco Pedro   Update to PaCCS v...
2595
		  MPI_Request *mpi_request = malloc(sizeof(MPI_Request));
965dadaa   Salvador Abreu   initial commit fr...
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605

		  _fd_debug("[%d] sending solution\n", tid);

		  if (_fd_optimising)
		    assert(have_solution);

		  _fd_send_store(0, FD_MSG_SOLUTION, solution, mpi_request,
				 false);

		  if (ts.tv_sec)
eef94371   Vasco Pedro   Update to PaCCS v...
2606
		    {
965dadaa   Salvador Abreu   initial commit fr...
2607
2608
2609
2610
2611
2612
2613
		      timersub(&ts, &ti, &ts);
		      _fd_debug("[%d] time to solution was %d.%06ds\n", tid,
				ts.tv_sec, ts.tv_usec);
		    }

		  fd_list_append(pending_requests, mpi_request);
		}
eef94371   Vasco Pedro   Update to PaCCS v...
2614
	      else
965dadaa   Salvador Abreu   initial commit fr...
2615
2616
2617
2618
2619
		{
		  _fd_debug("[%d] sending failure notice\n", tid);
		  _fd_send(0, FD_MSG_FAIL);
		}
	    }
eef94371   Vasco Pedro   Update to PaCCS v...
2620

965dadaa   Salvador Abreu   initial commit fr...
2621
2622
2623
2624
2625
	  // stop all the agents
	  _fd_debug("[%d] stopping agents\n", tid);
	  for (i = 0; i < started; ++i)
	    {
	      int s;
eef94371   Vasco Pedro   Update to PaCCS v...
2626

965dadaa   Salvador Abreu   initial commit fr...
2627
2628
2629
2630
2631
2632
2633
2634
	      if ((s = pthread_cancel(threads[i])) && s != ESRCH)
		_fd_debug("[%d] error cancelling thread %d = %d\n", tid, i, s);
	    }

	  // make sure all agents have stopped before exiting
	  if (!_fd_optimising && (status == FD_OK || stopped))
	    for (i = 0; i < started; ++i)
	      {
eef94371   Vasco Pedro   Update to PaCCS v...
2635
		int s;
965dadaa   Salvador Abreu   initial commit fr...
2636

eef94371   Vasco Pedro   Update to PaCCS v...
2637
		_fd_debug("[%d] joining agent %d\n", tid, i);
965dadaa   Salvador Abreu   initial commit fr...
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
		if ((s = pthread_join(threads[i], NULL)) && s != ESRCH)
		  _fd_debug("[%d] error joining thread %d = %d\n", tid, i, s);
	      }

#if STEAL_WORK >= 2
	  fd_list_dispose_deep(saved_stores, free);
#endif /* STEAL_WORK >= 2 */
	}
      else /* _fd_counting_solutions != 0 */
	{
	  // send solutions count to the rank 0 process, telling it that we
	  // are done
	  if (tid != 0)
	    _fd_send_data(0, FD_MSG_COUNT, &total_solutions, 1, MPI_LONG_LONG);

eef94371   Vasco Pedro   Update to PaCCS v...
2653
#if STEAL_WORK >= 2
965dadaa   Salvador Abreu   initial commit fr...
2654
2655
2656
2657
2658
	  // stop all the agents, which are waiting for work
	  _fd_debug("[%d] stopping agents\n", tid);
	  for (i = 0; i < started; ++i)
	    {
	      int s;
eef94371   Vasco Pedro   Update to PaCCS v...
2659

965dadaa   Salvador Abreu   initial commit fr...
2660
2661
2662
2663
2664
2665
2666
	      if ((s = pthread_cancel(threads[i])) && s != ESRCH)
		_fd_debug("[%d] error cancelling thread %d = %d\n", tid, i, s);
	    }

	  // make sure all agents have stopped before exiting
	  for (i = 0; i < started; ++i)
	    {
eef94371   Vasco Pedro   Update to PaCCS v...
2667
	      int s;
965dadaa   Salvador Abreu   initial commit fr...
2668

eef94371   Vasco Pedro   Update to PaCCS v...
2669
	      _fd_debug("[%d] joining agent %d\n", tid, i);
965dadaa   Salvador Abreu   initial commit fr...
2670
2671
2672
	      if ((s = pthread_join(threads[i], NULL)) && s != ESRCH)
		_fd_debug("[%d] error joining thread %d = %d\n", tid, i, s);
	    }
eef94371   Vasco Pedro   Update to PaCCS v...
2673

965dadaa   Salvador Abreu   initial commit fr...
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
	  if (!fd_list_empty(saved_stores))
	    _fd_fatal("saved_stores not empty on exit");

	  fd_list_dispose(saved_stores);
#endif /* STEAL_WORK >= 2 */
	}

      _fd_statistics_steal();
    }
  else /* agents == 0 */
    {
      _fd_agents_stores[0] = store;

      _fd_init_store_depository(1);

      if (!_fd_counting_solutions)
	status = _fd_dsearch(_fd_variables, 0);
      else
	total_solutions = _fd_count_solutions(_fd_variables, 0);

      store = _fd_agents_stores[0]; // restore its value so it can be freed
    }

  if (tid != 0)
    _fd_exit_process(tid);

eef94371   Vasco Pedro   Update to PaCCS v...
2700
  if (_fd_counting_solutions)
965dadaa   Salvador Abreu   initial commit fr...
2701
2702
2703
2704
2705
2706
    {
      _fd_output("found %llu solutions\n", total_solutions + external_solutions); // XXX

      status = FD_NOSOLUTION; // XXX
    }

eef94371   Vasco Pedro   Update to PaCCS v...
2707
2708
  gettimeofday(&to, NULL);
  timersub(&to, &ti, &to);
965dadaa   Salvador Abreu   initial commit fr...
2709
2710
2711
2712
#if defined(STATS_PROCS) || !defined(FAST)
  fd__info("process %d took %d.%06ds\n", tid, to.tv_sec, to.tv_usec);
#endif