VCluster.hpp 30.7 KB
Newer Older
incardon's avatar
incardon committed
1 2 3
#ifndef VCLUSTER
#define VCLUSTER

4
#include "config.h"
incardon's avatar
incardon committed
5
#include <mpi.h>
6
#include "MPI_wrapper/MPI_util.hpp"
incardon's avatar
incardon committed
7 8
#include "VCluster_object.hpp"
#include "Vector/map_vector.hpp"
9 10 11
#include "MPI_wrapper/MPI_IallreduceW.hpp"
#include "MPI_wrapper/MPI_IrecvW.hpp"
#include "MPI_wrapper/MPI_IsendW.hpp"
incardon's avatar
incardon committed
12
#include "MPI_wrapper/MPI_IAllGather.hpp"
incardon's avatar
incardon committed
13
#include <exception>
14
#include "Vector/map_vector.hpp"
15 16
#ifdef DEBUG
#include "util/check_no_pointers.hpp"
17
#include "util/util_debug.hpp"
18
#endif
incardon's avatar
incardon committed
19
#include "util/Vcluster_log.hpp"
incardon's avatar
incardon committed
20 21 22

#define MSG_LENGTH 1024
#define MSG_SEND_RECV 1025
23
#define SEND_SPARSE 4096
incardon's avatar
incardon committed
24 25 26
#define NONE 1
#define NEED_ALL_SIZE 2

27 28
#define SERIVCE_MESSAGE_TAG 16384
#define SEND_RECV_BASE 8192
incardon's avatar
incardon committed
29
#define GATHER_BASE 24576
incardon's avatar
incardon committed
30

Pietro Incardona's avatar
Pietro Incardona committed
31
// number of vcluster instances
incardon's avatar
incardon committed
32
extern size_t n_vcluster;
Pietro Incardona's avatar
Pietro Incardona committed
33
// Global MPI initialization
incardon's avatar
incardon committed
34 35
extern bool global_mpi_init;

incardon's avatar
incardon committed
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
///////////////////// Post functions /////////////

template<typename T> void assign(T * ptr1, T * ptr2)
{
	*ptr1 = *ptr2;
};

//////////////////////////////////////////////////

// temporal buffer for reductions
union red
{
	char c;
	unsigned char uc;
	short s;
	unsigned short us;
	int i;
	unsigned int ui;
	float f;
	double d;
};

/*! \brief Virtual Cluster exception
 *
 * This a a class that signal an exception on MPI_WaitAll
 *
 */

class exec_exception: public std::exception
{
  virtual const char* what() const throw()
  {
    return "One or more request has failed or reported an error";
  }
};

72
/*! \brief This class virtualize the cluster of PC as a set of processes that communicate
incardon's avatar
incardon committed
73
 *
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
 * At the moment it is an MPI-like interface, with a more type aware, and simple, interface.
 *  It also give some more complex communication functionalities like **Dynamic Sparse Data Exchange**
 *
 * Actually VCluster expose a Computation driven parallelism (MPI-like), with a plan of extending to
 * communication driven parallelism
 *
 * * In computation driven parallelism, the program compute than communicate to the other processors
 *
 * * In a communication driven parallelism, (Charm++ or HPX), the program receive messages, this receiving
 *   messages trigger computation
 *
 * ### An example of sending and receive plain buffers
 * \snippet VCluster_unit_test_util.hpp Send and receive plain buffer data
 * ### An example of sending vectors of primitives with (T=float,double,lont int,...)
 * \snippet VCluster_unit_test_util.hpp Sending and receiving primitives
 * ### An example of sending vectors of complexes object
 * \snippet VCluster_unit_test_util.hpp Send and receive vectors of complex
 * ### An example of gathering numbers from all processors
 * \snippet VCluster_unit_test_util.hpp allGather numbers
incardon's avatar
incardon committed
93 94 95 96 97
 *
 */

class Vcluster
{
incardon's avatar
incardon committed
98 99
	Vcluster_log log;

100 101 102
	//! NBX has a potential pitfall that must be addressed,
	//! NBX Send all the messages and probe for incoming messages,
	//! if there is an incoming message it receive it producing
103
	//! an acknowledge notification on the sending processor.
104 105 106 107 108 109
	//! When all the sends has been acknowledged, the processor call the MPI_Ibarrier
	//! when all the processors call MPI_Ibarrier all send has been received.
	//! While the processors are waiting for the MPI_Ibarrier to complete, all processors
	//! are still probing for incoming message, Unfortunately some processor
	//! can quit the MPI_Ibarrier before others and this mean that some
	//! processor can exit the probing status before others, these processors can in theory
110 111 112 113
	//! start new communications while the other processor are still in probing status producing
	//! a wrong send/recv association to
	//! resolve this problem an incremental NBX_cnt is used as message TAG to distinguish that the
	//! messages come from other send or subsequent NBX procedures
incardon's avatar
incardon committed
114
	size_t NBX_cnt;
115

incardon's avatar
incardon committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
	// temporal vector used for meta-communication
	// ( or meta-data before the real communication )
	openfpm::vector<size_t> proc_com;

	// vector that contain the scatter map (it is basically an array of one)
	openfpm::vector<int> map_scatter;

	// vector of MPI requests
	openfpm::vector<MPI_Request> req;

	// vector of MPI status
	openfpm::vector<MPI_Status> stat;

	// vector of functions to execute after all the request has been performed
	std::vector<int> post_exe;

	// Object array


	// Single objects

	// number of processes
	int size;
	// actual rank
	int rank;

	// number of processing unit per process
	int numPE = 1;

	/* This buffer is a temporal buffer for reductions
	 *
	 * MPI_Iallreduce does not accept recv and send buffer to be the same
	 * r is used to overcome this problem (is given as second parameter)
	 * after the execution the data is copied back
	 *
	 */
	std::vector<red> r;

154 155 156 157 158 159 160 161 162 163 164 165 166 167
	// vector of pointers of send buffers
	openfpm::vector<void *> ptr_send;

	// vector of the size of send buffers
	openfpm::vector<size_t> sz_send;

	// sending map
	openfpm::vector<size_t> map;

	// barrier request
	MPI_Request bar_req;
	// barrier status
	MPI_Status bar_stat;

incardon's avatar
incardon committed
168 169 170 171 172
public:

	// Finalize the MPI program
	~Vcluster()
	{
Pietro Incardona's avatar
Pietro Incardona committed
173 174 175
#ifdef SE_CLASS2
		check_delete(this);
#endif
Pietro Incardona's avatar
Pietro Incardona committed
176
		n_vcluster--;
incardon's avatar
incardon committed
177 178

		// if there are no other vcluster instances finalize
Pietro Incardona's avatar
Pietro Incardona committed
179 180
		if (n_vcluster == 0)
		{
181 182 183 184
			int already_finalised;

			MPI_Finalized(&already_finalised);
			if (!already_finalised)
Pietro Incardona's avatar
Pietro Incardona committed
185
			{
186 187 188 189
				if (MPI_Finalize() != 0)
				{
					std::cerr << __FILE__ << ":" << __LINE__  << " MPI_Finalize FAILED \n";
				}
Pietro Incardona's avatar
Pietro Incardona committed
190
			}
Pietro Incardona's avatar
Pietro Incardona committed
191
		}
incardon's avatar
incardon committed
192 193
	}

194 195 196 197 198 199
	/*! \brief Virtual cluster constructor
	 *
	 * \param argc pointer to arguments counts passed to the program
	 * \param argv pointer to arguments vector passed to the program
	 *
	 */
incardon's avatar
incardon committed
200
	Vcluster(int *argc, char ***argv)
incardon's avatar
incardon committed
201
	:NBX_cnt(0)
incardon's avatar
incardon committed
202
	{
Pietro Incardona's avatar
Pietro Incardona committed
203 204 205 206
#ifdef SE_CLASS2
		check_new(this,8,VCLUSTER_EVENT,PRJ_VCLUSTER);
#endif

Pietro Incardona's avatar
Pietro Incardona committed
207
		n_vcluster++;
incardon's avatar
incardon committed
208

209 210 211
		int already_initialised;
		MPI_Initialized(&already_initialised);

incardon's avatar
incardon committed
212
		// Check if MPI is already initialized
213
		if (!already_initialised)
incardon's avatar
incardon committed
214
		{
incardon's avatar
incardon committed
215

incardon's avatar
incardon committed
216 217
			MPI_Init(argc,argv);
		}
incardon's avatar
incardon committed
218

219 220
		// Get the total number of process
		// and the rank of this process
incardon's avatar
incardon committed
221 222 223 224

		MPI_Comm_size(MPI_COMM_WORLD, &size);
		MPI_Comm_rank(MPI_COMM_WORLD, &rank);

225
#ifdef SE_CLASS2
incardon's avatar
incardon committed
226 227 228
			process_v_cl = rank;
#endif

229
		// create and fill map scatter with one
incardon's avatar
incardon committed
230 231 232 233 234 235
		map_scatter.resize(size);

		for (size_t i = 0 ; i < map_scatter.size() ; i++)
		{
			map_scatter.get(i) = 1;
		}
incardon's avatar
incardon committed
236 237 238

		// open the log file
		log.openLog(rank);
239 240 241 242

		// Initialize bar_req
		bar_req = MPI_Request();
		bar_stat = MPI_Status();
incardon's avatar
incardon committed
243 244
	}

245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
#ifdef DEBUG

	/*! \brief Check for wrong types
	 *
	 * In general we do not know if a type T make sense to be sent or not, but if it has pointer
	 * inside it does not. This function check if the basic type T has a method called noPointers,
	 * This function in general notify if T has internally pointers. If T has pointer an error
	 * is printed, is T does not have the method a WARNING is printed
	 *
	 * \tparam T type to check
	 *
	 */
	template<typename T> void checkType()
	{
		// if T is a primitive like int, long int, float, double, ... make sense
		// (pointers, l-references and r-references are not fundamentals)
		if (std::is_fundamental<T>::value == true)
			return;

		// if it is a pointer make no sense
		if (std::is_pointer<T>::value == true)
			std::cerr << "Error: " << __FILE__ << ":" << __LINE__ << " the type " << demangle(typeid(T).name()) << " is a pointer, sending pointers values has no sense\n";

		// if it is an l-value reference make no send
		if (std::is_lvalue_reference<T>::value == true)
			std::cerr << "Error: " << __FILE__ << ":" << __LINE__ << " the type " << demangle(typeid(T).name()) << " is a pointer, sending pointers values has no sense\n";

		// if it is an r-value reference make no send
		if (std::is_rvalue_reference<T>::value == true)
			std::cerr << "Error: " << __FILE__ << ":" << __LINE__ << " the type " << demangle(typeid(T).name()) << " is a pointer, sending pointers values has no sense\n";

		// ... if not, check that T has a method called noPointers
		switch (check_no_pointers<T>::value())
		{
			case PNP::UNKNOWN:
			{
incardon's avatar
incardon committed
281
				std::cerr << "Warning: " << __FILE__ << ":" << __LINE__ << " impossible to check the type " << demangle(typeid(T).name()) << " please consider to add a static method \"static bool noPointers()\" \n" ;
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
				break;
			}
			case PNP::POINTERS:
			{
				std::cerr << "Error: " << __FILE__ << ":" << __LINE__ << " the type " << demangle(typeid(T).name()) << " has pointers inside, sending pointers values has no sense\n";
				break;
			}
			default:
			{

			}
		}
	}

#endif

incardon's avatar
incardon committed
298 299 300 301 302 303 304 305 306 307 308 309
	//! Get the total number of processing units
	size_t getProcessingUnits()
	{
		return size*numPE;
	}

	//! Get the process unit id
	size_t getProcessUnitID()
	{
		return rank;
	}

310
	/*! \brief Sum the numbers across all processors and get the result
incardon's avatar
incardon committed
311 312 313 314 315
	 *
	 * \param num to reduce, input and output
	 *
	 */

316
	template<typename T> void sum(T & num)
incardon's avatar
incardon committed
317
	{
318 319 320 321
#ifdef DEBUG
		checkType<T>();
#endif

incardon's avatar
incardon committed
322 323 324 325 326 327 328 329 330
		// reduce over MPI

		// Create one request
		req.add();

		// reduce
		MPI_IallreduceW<T>::reduce(num,MPI_SUM,req.last());
	}

331
	/*! \brief Get the maximum number across all processors (or reduction with infinity norm)
incardon's avatar
incardon committed
332 333 334 335 336 337
	 *
	 * \param num to reduce
	 *
	 */
	template<typename T> void max(T & num)
	{
338 339 340
#ifdef DEBUG
		checkType<T>();
#endif
incardon's avatar
incardon committed
341 342 343 344 345 346 347 348 349
		// reduce over MPI

		// Create one request
		req.add();

		// reduce
		MPI_IallreduceW<T>::reduce(num,MPI_MAX,req.last());
	}

Pietro Incardona's avatar
Pietro Incardona committed
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 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
	/*! \brief Send and receive multiple messages
	 *
	 * It send multiple messages to a set of processors the and receive
	 * multiple messages from another set of processors, all the processor must call this
	 * function, NBX is more performant than PCX with more processors (1000+)
	 *
	 * suppose the following situation the calling processor want to communicate
	 * * 2 vector of 100 integers to processor 1
	 * * 1 vector of 50 integers to processor 6
	 * * 1 vector of 48 integers to processor 7
	 * * 1 vector of 70 integers to processor 8
	 *
	 * \param prc list of processors you should communicate with [1,1,6,7,8]
	 *
	 * \param v vector containing the data to send [v=vector<vector<int>>, v.size()=4, T=vector<int>], T at the moment
	 *          is only tested for vectors of 0 or more generic elements (without pointers)
	 *
	 * \param msg_alloc This is a call-back with the purpose to allocate space
	 *        for the incoming messages and give back a valid pointer, supposing that this call-back has been triggered by
	 *        the processor of id 5 that want to communicate with me a message of size 100 byte the call-back will have
	 *        the following 6 parameters
	 *        in the call-back in order:
	 *        * message size required to receive the message (100)
	 *        * total message size to receive from all the processors (NBX does not provide this information)
	 *        * the total number of processor want to communicate with you (NBX does not provide this information)
	 *        * processor id (5)
	 *        * ri request id (it is an id that goes from 0 to total_p, and is incremented
	 *           every time message_alloc is called)
	 *        * void pointer, parameter for additional data to pass to the call-back
	 *
	 * \param opt options, only NONE supported
	 *
	 */
	template<typename T> void sendrecvMultipleMessagesNBX(openfpm::vector< size_t > & prc, openfpm::vector< T * > & data, void * (* msg_alloc)(size_t,size_t,size_t,size_t,size_t,void *), void * ptr_arg, long int opt=NONE)
	{
#ifdef DEBUG
		checkType<typename T::value_type>();
#endif
		// resize the pointer list
		ptr_send.resize(prc.size());
		sz_send.resize(prc.size());

		for (size_t i = 0 ; i < prc.size() ; i++)
		{
			ptr_send.get(i) = data.get(i)->getPointer();
			sz_send.get(i) = data.get(i)->size() * sizeof(typename T::value_type);
		}

		sendrecvMultipleMessagesNBX(prc.size(),(size_t *)sz_send.getPointer(),(size_t *)prc.getPointer(),(void **)ptr_send.getPointer(),msg_alloc,ptr_arg,opt);
	}

401
	/*! \brief Send and receive multiple messages
402
	 *
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
	 * It send multiple messages to a set of processors the and receive
	 * multiple messages from another set of processors, all the processor must call this
	 * function, NBX is more performant than PCX with more processors (1000+)
	 *
	 * suppose the following situation the calling processor want to communicate
	 * * 2 vector of 100 integers to processor 1
	 * * 1 vector of 50 integers to processor 6
	 * * 1 vector of 48 integers to processor 7
	 * * 1 vector of 70 integers to processor 8
	 *
	 * \param prc list of processors you should communicate with [1,1,6,7,8]
	 *
	 * \param v vector containing the data to send [v=vector<vector<int>>, v.size()=4, T=vector<int>], T at the moment
	 *          is only tested for vectors of 0 or more generic elements (without pointers)
	 *
	 * \param msg_alloc This is a call-back with the purpose to allocate space
	 *        for the incoming messages and give back a valid pointer, supposing that this call-back has been triggered by
	 *        the processor of id 5 that want to communicate with me a message of size 100 byte the call-back will have
	 *        the following 6 parameters
	 *        in the call-back in order:
	 *        * message size required to receive the message (100)
	 *        * total message size to receive from all the processors (NBX does not provide this information)
	 *        * the total number of processor want to communicate with you (NBX does not provide this information)
	 *        * processor id (5)
	 *        * ri request id (it is an id that goes from 0 to total_p, and is incremented
428
	 *           every time message_alloc is called)
429
	 *        * void pointer, parameter for additional data to pass to the call-back
430
	 *
431
	 * \param opt options, only NONE supported
432 433 434 435
	 *
	 */
	template<typename T> void sendrecvMultipleMessagesNBX(openfpm::vector< size_t > & prc, openfpm::vector< T > & data, void * (* msg_alloc)(size_t,size_t,size_t,size_t,size_t,void *), void * ptr_arg, long int opt=NONE)
	{
436 437 438
#ifdef DEBUG
		checkType<typename T::value_type>();
#endif
439 440 441 442 443 444 445 446 447 448 449 450 451
		// resize the pointer list
		ptr_send.resize(prc.size());
		sz_send.resize(prc.size());

		for (size_t i = 0 ; i < prc.size() ; i++)
		{
			ptr_send.get(i) = data.get(i).getPointer();
			sz_send.get(i) = data.get(i).size() * sizeof(typename T::value_type);
		}

		sendrecvMultipleMessagesNBX(prc.size(),(size_t *)sz_send.getPointer(),(size_t *)prc.getPointer(),(void **)ptr_send.getPointer(),msg_alloc,ptr_arg,opt);
	}

incardon's avatar
incardon committed
452 453
	/*! \brief Send and receive multiple messages
	 *
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
	 * It sends multiple messages to a set of processors and receives
	 * multiple messages from another set of processors, all the processor must call this
	 * function, NBX is more performant than PCX with more processors (1000+)
	 *
	 * suppose the following situation the calling processor want to communicate
	 * * 2 vector of 100 integers to processor 1
	 * * 1 vector of 50 integers to processor 6
	 * * 1 vector of 48 integers to processor 7
	 * * 1 vector of 70 integers to processor 8
	 *
	 * \param prc list of processors you should communicate with [1,1,6,7,8]
	 *
	 * \param v vector containing the data to send [v=vector<vector<int>>, v.size()=4, T=vector<int>], T at the moment
	 *          is only tested for vectors of 0 or more generic elements (without pointers)
	 *
	 * \param msg_alloc This is a call-back with the purpose to allocate space
	 *        for the incoming messages and give back a valid pointer, supposing that this call-back has been triggered by
	 *        the processor of id 5 that want to communicate with me a message of size 100 byte the call-back will have
	 *        the following 6 parameters
	 *        in the call-back in order:
	 *        * message size required to receive the message [100]
	 *        * total message size to receive from all the processors (NBX does not provide this information)
	 *        * the total number of processor want to communicate with you (NBX does not provide this information)
	 *        * processor id [5]
	 *        * ri request id (it is an id that goes from 0 to total_p, and is incremented
479
	 *           every time message_alloc is called)
480
	 *        * void pointer, parameter for additional data to pass to the call-back
incardon's avatar
incardon committed
481
	 *
482
	 * \param opt options, only NONE supported
incardon's avatar
incardon committed
483 484
	 *
	 */
485
	template<typename T> void sendrecvMultipleMessagesPCX(openfpm::vector< size_t > & prc, openfpm::vector< T > & data, void * (* msg_alloc)(size_t,size_t,size_t,size_t,size_t,void *), void * ptr_arg, long int opt=NONE)
incardon's avatar
incardon committed
486
	{
487 488 489
#ifdef DEBUG
		checkType<typename T::value_type>();
#endif
incardon's avatar
incardon committed
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
		// resize map with the number of processors
		map.resize(size);

		// reset the sending buffer
		map.fill(0);

		// create sending map
		for (size_t i = 0 ; i < prc.size() ; i++)
		{map.get(prc.get(i)) = 1;}

		// resize the pointer list
		ptr_send.resize(prc.size());
		sz_send.resize(prc.size());

		for (size_t i = 0 ; i < prc.size() ; i++)
		{
			ptr_send.get(i) = data.get(i).getPointer();
			sz_send.get(i) = data.get(i).size() * sizeof(typename T::value_type);
		}

510 511 512
		sendrecvMultipleMessagesPCX(prc.size(),(size_t *)map.getPointer(),(size_t *)sz_send.getPointer(),(size_t *)prc.getPointer(),(void **)ptr_send.getPointer(),msg_alloc,ptr_arg,opt);
	}

513
	/*! \brief Send and receive multiple messages
514
	 *
515 516 517
	 * It send multiple messages to a set of processors the and receive
	 * multiple messages from another set of processors, all the processor must call this
	 * function, NBX is more performant than PCX with more processors (1000+)
518
	 *
519 520 521 522 523
	 * suppose the following situation the calling processor want to communicate
	 * * 2 messages of size 100 byte to processor 1
	 * * 1 message of size 50 byte to processor 6
	 * * 1 message of size 48 byte to processor 7
	 * * 1 message of size 70 byte to processor 8
524
	 *
525
	 * \param n_send number of send for this processor [4]
526 527
	 *
	 * \param prc list of processor with which it should communicate
528
	 *        [1,1,6,7,8]
529
	 *
530 531 532 533
	 * \param sz the array contain the size of the message for each processor
	 *        (zeros must not be presents) [100,100,50,48,70]
	 *
	 * \param ptr array that contain the pointers to the message to send
534 535
	 *
	 * \param msg_alloc This is a call-back with the purpose of allocate space
536 537 538
	 *        for the incoming message and give back a valid pointer, supposing that this call-back has been triggered by
	 *        the processor of id 5 that want to communicate with me a message of size 100 byte the call-back will have
	 *        the following 6 parameters
539
	 *        in the call-back are in order:
540 541 542 543 544
	 *        * message size required to receive the message [100]
	 *        * total message size to receive from all the processors (NBX does not provide this information)
	 *        * the total number of processor want to communicate with you (NBX does not provide this information)
	 *        * processor id [5]
	 *        * ri request id (it is an id that goes from 0 to total_p, and is incremented
545
	 *           every time message_alloc is called)
546
	 *        * void pointer, parameter for additional data to pass to the call-back
547 548 549 550 551 552
	 *
	 * \param opt options, NONE (ignored in this moment)
	 *
	 */
	void sendrecvMultipleMessagesNBX(size_t n_send , size_t sz[], size_t prc[] , void * ptr[], void * (* msg_alloc)(size_t,size_t,size_t,size_t,size_t,void *), void * ptr_arg, long int opt)
	{
553 554 555 556 557
		if (stat.size() != 0 || req.size() != 0)
			std::cerr << "Error: " << __FILE__ << ":" << __LINE__ << " this function must be called when no other requests are in progress \n";


		stat.clear();
558 559 560 561 562
		req.clear();
		// Do MPI_Issend

		for (size_t i = 0 ; i < n_send ; i++)
		{
incardon's avatar
incardon committed
563 564 565
			if (sz[i] != 0)
			{
				req.add();
566 567 568 569 570

#ifdef SE_CLASS2
				check_valid(ptr[i],sz[i]);
#endif

571
				MPI_SAFE_CALL(MPI_Issend(ptr[i], sz[i], MPI_BYTE, prc[i], SEND_SPARSE + NBX_cnt, MPI_COMM_WORLD,&req.last()));
incardon's avatar
incardon committed
572
				log.logSend(prc[i]);
incardon's avatar
incardon committed
573
			}
574 575 576 577 578 579 580
		}

		size_t rid = 0;
		int flag = false;

		bool reached_bar_req = false;

incardon's avatar
incardon committed
581 582
		log.start(10);

583 584 585
		// Wait that all the send are acknowledge
		do
		{
incardon's avatar
incardon committed
586

587 588 589 590 591
			// flag that notify that this processor reach the barrier
			// Barrier request

			MPI_Status stat_t;
			int stat = false;
592
			MPI_SAFE_CALL(MPI_Iprobe(MPI_ANY_SOURCE,SEND_SPARSE + NBX_cnt,MPI_COMM_WORLD,&stat,&stat_t));
593

594
			// If I have an incoming message and is related to this NBX communication
595 596 597 598 599 600 601 602 603
			if (stat == true)
			{
				// Get the message size
				int msize;
				MPI_SAFE_CALL(MPI_Get_count(&stat_t,MPI_BYTE,&msize));

				// Get the pointer to receive the message
				void * ptr = msg_alloc(msize,0,0,stat_t.MPI_SOURCE,rid,ptr_arg);

incardon's avatar
incardon committed
604 605 606
				// Log the receiving request
				log.logRecv(stat_t);

607 608
				rid++;

609 610 611 612
				// Check the pointer
#ifdef SE_CLASS2
				check_valid(ptr,msize);
#endif
613
				MPI_SAFE_CALL(MPI_Recv(ptr,msize,MPI_BYTE,stat_t.MPI_SOURCE,SEND_SPARSE+NBX_cnt,MPI_COMM_WORLD,&stat_t));
614 615 616 617

#ifdef SE_CLASS2
				check_valid(ptr,msize);
#endif
618 619 620 621 622 623 624
			}

			// Check the status of all the MPI_issend and call the barrier if finished

			if (reached_bar_req == false)
			{
				int flag = false;
incardon's avatar
incardon committed
625 626 627 628
				if (req.size() != 0)
				{MPI_SAFE_CALL(MPI_Testall(req.size(),&req.get(0),&flag,MPI_STATUSES_IGNORE));}
				else
					flag = true;
629 630 631 632 633 634

				// If all send has been completed
				if (flag == true)
				{MPI_SAFE_CALL(MPI_Ibarrier(MPI_COMM_WORLD,&bar_req));reached_bar_req = true;}
			}

incardon's avatar
incardon committed
635
			// Check if all processor reached the async barrier
636
			if (reached_bar_req)
incardon's avatar
incardon committed
637
			{MPI_SAFE_CALL(MPI_Test(&bar_req,&flag,&bar_stat))};
incardon's avatar
incardon committed
638 639

			// produce a report if communication get stuck
incardon's avatar
incardon committed
640
			log.NBXreport(NBX_cnt,req,reached_bar_req,bar_stat);
incardon's avatar
incardon committed
641

642 643 644 645 646 647
		} while (flag == false);

		// Remove the executed request

		req.clear();
		stat.clear();
incardon's avatar
incardon committed
648
		log.clear();
649 650 651

		// Circular counter
		NBX_cnt = (NBX_cnt + 1) % 1024;
incardon's avatar
incardon committed
652 653 654 655
	}

	/*! \brief Send and receive multiple messages
	 *
656 657 658
	 * It send multiple messages to a set of processors the and receive
	 * multiple messages from another set of processors, all the processor must call this
	 * function, NBX is more performant than PCX with more processors (1000+)
incardon's avatar
incardon committed
659
	 *
660 661 662 663 664
	 * suppose the following situation the calling processor want to communicate
	 * * 2 messages of size 100 byte to processor 1
	 * * 1 message of size 50 byte to processor 6
	 * * 1 message of size 48 byte to processor 7
	 * * 1 message of size 70 byte to processor 8
incardon's avatar
incardon committed
665
	 *
666
	 * \param n_send number of send for this processor [4]
incardon's avatar
incardon committed
667
	 *
668 669
	 * \param prc list of processor with which it should communicate
	 *        [1,1,6,7,8]
incardon's avatar
incardon committed
670
	 *
671 672 673
	 * \param map array containing an array of the number of messages for
	 *        each processor the colling processor want to communicate
	 *        [0 2 0 0 0 0 1 1 1]
incardon's avatar
incardon committed
674
	 *
675 676
	 * \param sz the array contain the size of the message for each processor
	 *        (zeros must not be presents) [100,100,50,48,70]
incardon's avatar
incardon committed
677
	 *
678
	 * \param ptr array that contain the pointers to the message to send
incardon's avatar
incardon committed
679 680
	 *
	 * \param msg_alloc This is a call-back with the purpose of allocate space
681 682 683 684 685 686 687 688 689 690 691
	 *        for the incoming message and give back a valid pointer, supposing that this call-back has been triggered by
	 *        the processor of id 5 that want to communicate with me a message of size 100 byte the call-back will have
	 *        the following 6 parameters
	 *        in the call-back are in order:
	 *        * message size required to receive the message [100]
	 *        * total message size to receive from all the processors
	 *        * the total number of processor want to communicate with the calling processor
	 *        * processor id [5]
	 *        * ri request id (it is an id that goes from 0 to total_p, and is incremented
	 *           every time message_alloc is called)
	 *        * void pointer, parameter for additional data to pass to the call-back
incardon's avatar
incardon committed
692
	 *
693
	 * \param opt options, NONE (ignored in this moment)
incardon's avatar
incardon committed
694 695
	 *
	 */
696
	void sendrecvMultipleMessagesPCX(size_t n_send, size_t * map, size_t sz[], size_t prc[] , void * ptr[], void * (* msg_alloc)(size_t,size_t,size_t,size_t,size_t,void *), void * ptr_arg, long int opt)
incardon's avatar
incardon committed
697
	{
698 699 700 701
		if (stat.size() != 0 || req.size() != 0)
			std::cerr << "Error: " << __FILE__ << ":" << __LINE__ << " this function must be called when no other requests are in progress \n";

		stat.clear();
incardon's avatar
incardon committed
702
		req.clear();
703

incardon's avatar
incardon committed
704
		req.add();
incardon's avatar
incardon committed
705
		stat.add();
incardon's avatar
incardon committed
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738

		proc_com.resize(1);

		MPI_SAFE_CALL(MPI_Ireduce_scatter(map,&proc_com.get(0),&map_scatter.get(0),MPI_UNSIGNED_LONG,MPI_SUM,MPI_COMM_WORLD,&req.last()));
		MPI_SAFE_CALL(MPI_Waitall(req.size(),&req.get(0),&stat.get(0)));

		// Remove the executed request

		req.clear();
		stat.clear();

		// Allocate the temporal buffer to store the message size for each processor

		size_t n_proc_com = proc_com.get(0);
		proc_com.resize(n_proc_com * 2);

		// queue n_proc_com MPI_Irecv with source ANY_SOURCE to get
		// the message length from each processor and
		//  send the message length to each processor

		for (size_t i = 0 ; i < n_proc_com ; i++)
		{
			req.add();
			MPI_SAFE_CALL(MPI_Irecv(&proc_com.get(i),1,MPI_UNSIGNED_LONG,MPI_ANY_SOURCE,MSG_LENGTH,MPI_COMM_WORLD,&req.last()));
		}

		for (size_t i = 0 ; i < n_send ; i++)
		{
			req.add();
			MPI_SAFE_CALL(MPI_Isend(&sz[i],1,MPI_UNSIGNED_LONG,prc[i],MSG_LENGTH,MPI_COMM_WORLD,&req.last()));
		}

		stat.resize(req.size());
739
		if (req.size() != 0) {MPI_SAFE_CALL(MPI_Waitall(req.size(),&req.get(0),&stat.get(0)));}
incardon's avatar
incardon committed
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

		// Use proc_com to get the processor id that try to communicate

		for (size_t i = 0 ; i < n_proc_com ; i++)
		{
			proc_com.get(n_proc_com+i) = stat.get(i).MPI_SOURCE;
		}

		// Remove the executed request

		req.clear();
		stat.clear();

		// Calculate the total size of the message

		size_t total_msg = 0;

		for (size_t i = 0 ; i < n_proc_com ; i++)
		{
			total_msg += proc_com.get(i);
		}

		// Receive the message

		for (size_t i = 0 ; i < n_proc_com ; i++)
		{
incardon's avatar
incardon committed
766
			void * ptr = msg_alloc(proc_com.get(i),total_msg,n_proc_com,proc_com.get(n_proc_com+i),i,ptr_arg);
incardon's avatar
incardon committed
767 768

			req.add();
769 770 771 772 773

#ifdef SE_CLASS2
				check_valid(ptr,proc_com.get(i));
#endif

incardon's avatar
incardon committed
774 775 776 777 778 779 780 781
			MPI_SAFE_CALL(MPI_Irecv(ptr,proc_com.get(i),MPI_BYTE,proc_com.get(i+n_proc_com),MSG_SEND_RECV,MPI_COMM_WORLD,&req.last()));
		}

		// Send all the messages this processor must send

		for (size_t i = 0 ; i < n_send ; i++)
		{
			req.add();
782 783 784 785 786

#ifdef SE_CLASS2
			check_valid(ptr[i],sz[i]);
#endif

incardon's avatar
incardon committed
787 788 789 790
			MPI_SAFE_CALL(MPI_Isend(ptr[i],sz[i],MPI_BYTE,prc[i],MSG_SEND_RECV,MPI_COMM_WORLD,&req.last()));
		}

		stat.resize(req.size());
791
		if (req.size() != 0) {MPI_SAFE_CALL(MPI_Waitall(req.size(),&req.get(0),&stat.get(0)));}
incardon's avatar
incardon committed
792 793 794 795 796 797

		// Remove the executed request
		req.clear();
		stat.clear();
	}

798 799 800 801 802 803
	/*! \brief Send data to a processor
	 *
	 * \warning In order to avoid deadlock every send must be coupled with a recv
	 *          in case you want to send data without knowledge from the other side
	 *          consider to use sendRecvMultipleMessages
	 *
incardon's avatar
incardon committed
804 805 806 807 808 809 810 811 812 813 814 815
	 * \warning operation is asynchronous execute must be called to ensure they are executed
	 *
	 * \see sendRecvMultipleMessages
	 *
	 * \param proc processor id
	 * \param tag id
	 * \param mem buffer with the data to send
	 * \param sz size
	 *
	 * \return true if succeed false otherwise
	 *
	 */
816
	bool send(size_t proc, size_t tag, const void * mem, size_t sz)
incardon's avatar
incardon committed
817 818 819 820 821 822 823 824 825 826 827 828
	{
		// send over MPI

		// Create one request
		req.add();

		// send
		MPI_IsendWB::send(proc,SEND_RECV_BASE + tag,mem,sz,req.last());

		return true;
	}

incardon's avatar
incardon committed
829

incardon's avatar
incardon committed
830 831 832 833 834 835 836
	/*! \brief Send data to a processor
	 *
	 * \warning In order to avoid deadlock every send must be coupled with a recv
	 *          in case you want to send data without knowledge from the other side
	 *          consider to use sendRecvMultipleMessages
	 *
	 * \warning operation is asynchronous execute must be called to ensure they are executed
837 838 839 840 841 842 843
	 *
	 * \see sendRecvMultipleMessages
	 *
	 * \param proc processor id
	 * \param tag id
	 * \param v buffer to send
	 *
844 845
	 * \return true if succeed false otherwise
	 *
846
	 */
847
	template<typename T, typename Mem, typename gr> bool send(size_t proc, size_t tag, openfpm::vector<T,Mem,gr> & v)
848 849 850 851 852 853 854 855 856 857
	{
#ifdef DEBUG
		checkType<T>();
#endif

		// send over MPI

		// Create one request
		req.add();

858
		// send
859
		MPI_IsendW<T,Mem,gr>::send(proc,SEND_RECV_BASE + tag,v,req.last());
860 861

		return true;
862 863 864 865 866 867
	}

	/*! \brief Recv data from a processor
	 *
	 * \warning In order to avoid deadlock every recv must be coupled with a send
	 *          in case you want to send data without knowledge from the other side
868
	 *          consider to use sendrecvMultipleMessagesPCX or sendrecvMultipleMessagesNBX
869
	 *
incardon's avatar
incardon committed
870
	 * \warning operation is asynchronous execute must be called to ensure they are executed
871
	 *
872
	 * \see sendrecvMultipleMessagesPCX sendrecvMultipleMessagesNBX
873 874 875 876
	 *
	 * \param proc processor id
	 * \param tag id
	 * \param v buffer to send
incardon's avatar
incardon committed
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
	 * \param sz size of the buffer
	 *
	 * \return true if succeed false otherwise
	 *
	 */
	bool recv(size_t proc, size_t tag, void * v, size_t sz)
	{
		// recv over MPI

		// Create one request
		req.add();

		// receive
		MPI_IrecvWB::recv(proc,SEND_RECV_BASE + tag,v,sz,req.last());

		return true;
	}

incardon's avatar
incardon committed
895 896 897 898
    /*! \brief Recv data from a processor
     *
     * \warning In order to avoid deadlock every recv must be coupled with a send
     *          in case you want to send data without knowledge from the other side
899
     *          consider to use sendrecvMultipleMessagesPCX sendrecvMultipleMessagesNBX
incardon's avatar
incardon committed
900 901 902
     *
     * \warning operation is asynchronous execute must be called to ensure they are executed
     *
903
     * \see sendrecvMultipleMessagesPCX sendrecvMultipleMessagesNBX
incardon's avatar
incardon committed
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929
     *
     * \param proc processor id
     * \param tag id
     * \param v vector to send
     *
     * \return true if succeed false otherwise
     *
     */
    template<typename T, typename Mem, typename gr> bool recv(size_t proc, size_t tag, openfpm::vector<T,Mem,gr> & v)
    {
#ifdef DEBUG
            checkType<T>();
#endif

            // recv over MPI

            // Create one request
            req.add();

            // receive
            MPI_IrecvW<T>::recv(proc,SEND_RECV_BASE + tag,v,req.last());

            return true;
    }

	/*! \brief Gather the data from all processors
930 931
	 *
	 * send a primitive data T receive the same primitive T from all the other processors
incardon's avatar
incardon committed
932 933 934
	 *
	 * \warning operation is asynchronous execute must be called to ensure they are executed
	 *
935
	 * \param v vector to receive (automaticaly resized)
incardon's avatar
incardon committed
936
	 * \param send data to send
937
	 *
938 939
	 * \return true if succeed false otherwise
	 *
940
	 */
incardon's avatar
incardon committed
941
	template<typename T, typename Mem, typename gr> bool allGather(T & send, openfpm::vector<T,Mem,gr> & v)
942 943 944 945 946 947 948 949
	{
#ifdef DEBUG
		checkType<T>();
#endif

		// Create one request
		req.add();

incardon's avatar
incardon committed
950 951 952
		// Number of processors
		v.resize(getProcessingUnits());

953
		// gather
incardon's avatar
incardon committed
954
		MPI_IAllGatherW<T>::gather(&send,1,v.getPointer(),1,req.last());
955 956

		return true;
957 958 959
	}

	/*! \brief Execute all the requests
incardon's avatar
incardon committed
960 961 962 963 964 965
	 *
	 */
	void execute()
	{
		int err = 0;

966 967 968 969
		// if req == 0 return
		if (req.size() == 0)
			return;

incardon's avatar
incardon committed
970
		// Wait for all the requests
971
		stat.resize(req.size());
incardon's avatar
incardon committed
972 973 974 975 976 977
		err = MPI_Waitall(req.size(),&req.get(0),&stat.get(0));

		// MPI error get the message and abort MPI
		if (err != MPI_SUCCESS)
			MPI_Abort(MPI_COMM_WORLD,1);

978
		// Remove executed request and status
incardon's avatar
incardon committed
979 980 981
		req.clear();
		stat.clear();
	}
982 983


incardon's avatar
incardon committed
984 985
};

Pietro Incardona's avatar
Pietro Incardona committed
986
// Function to initialize the global VCluster //
incardon's avatar
incardon committed
987 988 989

extern Vcluster * global_v_cluster;

Pietro Incardona's avatar
Pietro Incardona committed
990 991 992 993 994 995 996

/*! \brief Initialize a global instance of Runtime Virtual Cluster Machine
 *
 * Initialize a global instance of Runtime Virtual Cluster Machine
 *
 */

Pietro Incardona's avatar
Pietro Incardona committed
997
static inline void init_global_v_cluster(int *argc, char ***argv)
Pietro Incardona's avatar
Pietro Incardona committed
998 999 1000 1001 1002
{
	if (global_v_cluster == NULL)
		global_v_cluster = new Vcluster(argc,argv);
}

Pietro Incardona's avatar
Pietro Incardona committed
1003
static inline void delete_global_v_cluster()
Pietro Incardona's avatar
Pietro Incardona committed
1004 1005 1006 1007
{
	delete global_v_cluster;
}

incardon's avatar
incardon committed
1008 1009
#endif