Teuchos - Trilinos Tools Package  Version of the Day
Teuchos_DefaultMpiComm.hpp
1 // @HEADER
2 // ***********************************************************************
3 //
4 // Teuchos: Common Tools Package
5 // Copyright (2004) Sandia Corporation
6 //
7 // Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive
8 // license for use of this work by or on behalf of the U.S. Government.
9 //
10 // Redistribution and use in source and binary forms, with or without
11 // modification, are permitted provided that the following conditions are
12 // met:
13 //
14 // 1. Redistributions of source code must retain the above copyright
15 // notice, this list of conditions and the following disclaimer.
16 //
17 // 2. Redistributions in binary form must reproduce the above copyright
18 // notice, this list of conditions and the following disclaimer in the
19 // documentation and/or other materials provided with the distribution.
20 //
21 // 3. Neither the name of the Corporation nor the names of the
22 // contributors may be used to endorse or promote products derived from
23 // this software without specific prior written permission.
24 //
25 // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY
26 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
28 // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE
29 // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
30 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
31 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
32 // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
34 // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
35 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 //
37 // Questions? Contact Michael A. Heroux (maherou@sandia.gov)
38 //
39 // ***********************************************************************
40 // @HEADER
41 
42 #ifndef TEUCHOS_MPI_COMM_HPP
43 #define TEUCHOS_MPI_COMM_HPP
44 
45 
46 #include "Teuchos_Comm.hpp"
47 #include "Teuchos_CommUtilities.hpp"
49 #include "Teuchos_OpaqueWrapper.hpp"
50 #include "Teuchos_MpiReductionOpSetter.hpp"
51 #include "Teuchos_SerializationTraitsHelpers.hpp"
52 #include "Teuchos_Workspace.hpp"
54 #include "Teuchos_as.hpp"
55 #include "Teuchos_Assert.hpp"
56 #include "mpi.h"
57 #include <iterator>
58 
59 // This must be defined globally for the whole program!
60 //#define TEUCHOS_MPI_COMM_DUMP
61 
62 
63 #ifdef TEUCHOS_MPI_COMM_DUMP
64 # include "Teuchos_VerboseObject.hpp"
65 #endif
66 
67 
68 namespace Teuchos {
69 
71 std::string
72 mpiErrorCodeToString (const int err);
73 
74 namespace details {
88  void safeCommFree (MPI_Comm* comm);
89 
94  int setCommErrhandler (MPI_Comm comm, MPI_Errhandler handler);
95 
96 } // namespace details
97 
98 #ifdef TEUCHOS_MPI_COMM_DUMP
99 template<typename Ordinal, typename T>
100 void dumpBuffer(
101  const std::string &funcName, const std::string &buffName
102  ,const Ordinal bytes, const T buff[]
103  )
104 {
107  Teuchos::OSTab tab(out);
108  *out
109  << "\n" << funcName << "::" << buffName << ":\n";
110  tab.incrTab();
111  for( Ordinal i = 0; i < bytes; ++i ) {
112  *out << buffName << "[" << i << "] = '" << buff[i] << "'\n";
113  }
114  *out << "\n";
115 }
116 #endif // TEUCHOS_MPI_COMM_DUMP
117 
118 
130 template<class OrdinalType>
131 class MpiCommStatus : public CommStatus<OrdinalType> {
132 public:
133  MpiCommStatus (MPI_Status status) : status_ (status) {}
134 
136  virtual ~MpiCommStatus() {}
137 
139  OrdinalType getSourceRank () { return status_.MPI_SOURCE; }
140 
142  OrdinalType getTag () { return status_.MPI_TAG; }
143 
145  OrdinalType getError () { return status_.MPI_ERROR; }
146 
147 private:
149  MpiCommStatus ();
150 
152  MPI_Status status_;
153 };
154 
158 template<class OrdinalType>
160 mpiCommStatus (MPI_Status rawMpiStatus)
161 {
162  return rcp (new MpiCommStatus<OrdinalType> (rawMpiStatus));
163 }
164 
165 
181 template<class OrdinalType>
182 class MpiCommRequestBase : public CommRequest<OrdinalType> {
183 public:
186  rawMpiRequest_ (MPI_REQUEST_NULL)
187  {}
188 
190  MpiCommRequestBase (MPI_Request rawMpiRequest) :
191  rawMpiRequest_ (rawMpiRequest)
192  {}
193 
201  MPI_Request releaseRawMpiRequest()
202  {
203  MPI_Request tmp_rawMpiRequest = rawMpiRequest_;
204  rawMpiRequest_ = MPI_REQUEST_NULL;
205  return tmp_rawMpiRequest;
206  }
207 
209  bool isNull() const {
210  return rawMpiRequest_ == MPI_REQUEST_NULL;
211  }
212 
219  MPI_Status rawMpiStatus;
220  // Whether this function satisfies the strong exception guarantee
221  // depends on whether MPI_Wait modifies its input request on error.
222  const int err = MPI_Wait (&rawMpiRequest_, &rawMpiStatus);
224  err != MPI_SUCCESS, std::runtime_error,
225  "Teuchos: MPI_Wait() failed with error \""
226  << mpiErrorCodeToString (err));
227  // MPI_Wait sets the MPI_Request to MPI_REQUEST_NULL on success.
228  return mpiCommStatus<OrdinalType> (rawMpiStatus);
229  }
230 
236  if (rawMpiRequest_ == MPI_REQUEST_NULL) {
237  return null;
238  }
239  else {
240  int err = MPI_Cancel (&rawMpiRequest_);
242  err != MPI_SUCCESS, std::runtime_error,
243  "Teuchos: MPI_Cancel failed with the following error: "
244  << mpiErrorCodeToString (err));
245 
246  // Wait on the request. If successful, MPI_Wait will set the
247  // MPI_Request to MPI_REQUEST_NULL. The returned status may
248  // still be useful; for example, one may call MPI_Test_cancelled
249  // to test an MPI_Status from a nonblocking send.
250  MPI_Status status;
251  err = MPI_Wait (&rawMpiRequest_, &status);
252  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
253  "Teuchos::MpiCommStatus::cancel: MPI_Wait failed with the following "
254  "error: " << mpiErrorCodeToString (err));
255  return mpiCommStatus<OrdinalType> (status);
256  }
257  }
258 
260  virtual ~MpiCommRequestBase () {
261  if (rawMpiRequest_ != MPI_REQUEST_NULL) {
262  // We're in a destructor, so don't throw errors. However, if
263  // MPI_Cancel fails, it's probably a bad idea to call MPI_Wait.
264  const int err = MPI_Cancel (&rawMpiRequest_);
265  if (err == MPI_SUCCESS) {
266  // The MPI_Cancel succeeded. Now wait on the request. Ignore
267  // any reported error, since we can't do anything about those
268  // in the destructor (other than kill the program). If
269  // successful, MPI_Wait will set the MPI_Request to
270  // MPI_REQUEST_NULL. We ignore the returned MPI_Status, since
271  // if the user let the request fall out of scope, she must not
272  // care about the status.
273  //
274  // mfh 21 Oct 2012: The MPI standard requires completing a
275  // canceled request by calling a function like MPI_Wait,
276  // MPI_Test, or MPI_Request_free. MPI_Wait on a canceled
277  // request behaves like a local operation (it does not
278  // communicate or block waiting for communication). One could
279  // also call MPI_Request_free instead of MPI_Wait, but
280  // MPI_Request_free is intended more for persistent requests
281  // (created with functions like MPI_Recv_init).
282  (void) MPI_Wait (&rawMpiRequest_, MPI_STATUS_IGNORE);
283  }
284  }
285  }
286 
287 private:
289  MPI_Request rawMpiRequest_;
290 };
291 
292 
308 template<class OrdinalType>
309 class MpiCommRequest : public MpiCommRequestBase<OrdinalType> {
310 public:
313  MpiCommRequestBase<OrdinalType> (MPI_REQUEST_NULL),
314  numBytes_ (0)
315  {}
316 
318  MpiCommRequest (MPI_Request rawMpiRequest,
319  const ArrayView<char>::size_type numBytesInMessage) :
320  MpiCommRequestBase<OrdinalType> (rawMpiRequest),
321  numBytes_ (numBytesInMessage)
322  {}
323 
330  return numBytes_;
331  }
332 
334  virtual ~MpiCommRequest () {}
335 
336 private:
338  ArrayView<char>::size_type numBytes_;
339 };
340 
349 template<class OrdinalType>
351 mpiCommRequest (MPI_Request rawMpiRequest,
352  const ArrayView<char>::size_type numBytes)
353 {
354  return rcp (new MpiCommRequest<OrdinalType> (rawMpiRequest, numBytes));
355 }
356 
372 template<typename Ordinal>
373 class MpiComm : public Comm<Ordinal> {
374 public:
375 
377 
378 
399  explicit MpiComm (MPI_Comm rawMpiComm);
400 
415  MpiComm(
416  const RCP<const OpaqueWrapper<MPI_Comm> > &rawMpiComm
417  );
418 
435  MpiComm(const MpiComm<Ordinal>& other);
436 
439  {return rawMpiComm_;}
440 
459  void setErrorHandler (const RCP<const OpaqueWrapper<MPI_Errhandler> >& errHandler);
460 
462 
464 
465 
467  virtual int getRank() const;
469  virtual int getSize() const;
471  virtual void barrier() const;
473  virtual void broadcast(
474  const int rootRank, const Ordinal bytes, char buffer[]
475  ) const;
477  virtual void
478  gather (const Ordinal sendBytes, const char sendBuffer[],
479  const Ordinal recvBytes, char recvBuffer[],
480  const int root) const;
482  virtual void gatherAll(
483  const Ordinal sendBytes, const char sendBuffer[]
484  ,const Ordinal recvBytes, char recvBuffer[]
485  ) const;
487  virtual void reduceAll(
488  const ValueTypeReductionOp<Ordinal,char> &reductOp
489  ,const Ordinal bytes, const char sendBuffer[], char globalReducts[]
490  ) const;
492  virtual void reduceAllAndScatter(
493  const ValueTypeReductionOp<Ordinal,char> &reductOp
494  ,const Ordinal sendBytes, const char sendBuffer[]
495  ,const Ordinal recvCounts[], char myGlobalReducts[]
496  ) const;
498  virtual void scan(
499  const ValueTypeReductionOp<Ordinal,char> &reductOp
500  ,const Ordinal bytes, const char sendBuffer[], char scanReducts[]
501  ) const;
503  virtual void send(
504  const Ordinal bytes, const char sendBuffer[], const int destRank
505  ) const;
507  virtual void
508  send (const Ordinal bytes,
509  const char sendBuffer[],
510  const int destRank,
511  const int tag) const;
513  virtual void ssend(
514  const Ordinal bytes, const char sendBuffer[], const int destRank
515  ) const;
517  virtual void
518  ssend (const Ordinal bytes,
519  const char sendBuffer[],
520  const int destRank,
521  const int tag) const;
523  virtual int receive(
524  const int sourceRank, const Ordinal bytes, char recvBuffer[]
525  ) const;
527  virtual void readySend(
528  const ArrayView<const char> &sendBuffer,
529  const int destRank
530  ) const;
532  virtual void
533  readySend (const Ordinal bytes,
534  const char sendBuffer[],
535  const int destRank,
536  const int tag) const;
538  virtual RCP<CommRequest<Ordinal> > isend(
539  const ArrayView<const char> &sendBuffer,
540  const int destRank
541  ) const;
543  virtual RCP<CommRequest<Ordinal> >
544  isend (const ArrayView<const char> &sendBuffer,
545  const int destRank,
546  const int tag) const;
549  const ArrayView<char> &Buffer,
550  const int sourceRank
551  ) const;
553  virtual RCP<CommRequest<Ordinal> >
554  ireceive (const ArrayView<char> &Buffer,
555  const int sourceRank,
556  const int tag) const;
558  virtual void waitAll(
559  const ArrayView<RCP<CommRequest<Ordinal> > > &requests
560  ) const;
562  virtual void
563  waitAll (const ArrayView<RCP<CommRequest<Ordinal> > >& requests,
564  const ArrayView<RCP<CommStatus<Ordinal> > >& statuses) const;
566  virtual RCP<CommStatus<Ordinal> >
567  wait (const Ptr<RCP<CommRequest<Ordinal> > >& request) const;
569  virtual RCP< Comm<Ordinal> > duplicate() const;
571  virtual RCP< Comm<Ordinal> > split(const int color, const int key) const;
573  virtual RCP< Comm<Ordinal> > createSubcommunicator(
574  const ArrayView<const int>& ranks) const;
576 
578 
579 
581  std::string description() const;
582 
584 
585  // These should be private but the PGI compiler requires them be public
586 
587  static int const minTag_ = 26000; // These came from Teuchos::MpiComm???
588  static int const maxTag_ = 26099; // ""
589 
595  int getTag () const { return tag_; }
596 
597 private:
598 
599  // Set internal data members once the rawMpiComm_ data member is valid.
600  void setupMembersFromComm();
601  static int tagCounter_;
602 
610  RCP<const OpaqueWrapper<MPI_Comm> > rawMpiComm_;
611 
613  int rank_;
614 
616  int size_;
617 
625  int tag_;
626 
628  RCP<const OpaqueWrapper<MPI_Errhandler> > customErrorHandler_;
629 
630  void assertRank(const int rank, const std::string &rankName) const;
631 
632  // Not defined and not to be called!
633  MpiComm();
634 
635 #ifdef TEUCHOS_MPI_COMM_DUMP
636 public:
637  static bool show_dump;
638 #endif // TEUCHOS_MPI_COMM_DUMP
639 
640 };
641 
642 
656 template<typename Ordinal>
658 createMpiComm(
659  const RCP<const OpaqueWrapper<MPI_Comm> > &rawMpiComm
660  );
661 
662 
663 // ////////////////////////
664 // Implementations
665 
666 
667 // Static members
668 
669 
670 template<typename Ordinal>
672 
673 
674 // Constructors
675 
676 
677 template<typename Ordinal>
679  const RCP<const OpaqueWrapper<MPI_Comm> > &rawMpiComm
680  )
681 {
682  TEUCHOS_TEST_FOR_EXCEPTION(rawMpiComm.get()==NULL, std::invalid_argument,
683  "Teuchos::MpiComm constructor: The input RCP is null.");
684  TEUCHOS_TEST_FOR_EXCEPTION(*rawMpiComm == MPI_COMM_NULL,
685  std::invalid_argument, "Teuchos::MpiComm constructor: The given MPI_Comm "
686  "is MPI_COMM_NULL.");
687  rawMpiComm_ = rawMpiComm;
688 
689  // FIXME (mfh 26 Mar 2012) The following is a bit wicked in that it
690  // changes the behavior of existing applications that use MpiComm,
691  // without warning. I've chosen to do it because I can't figure out
692  // any other way to help me debug MPI_Waitall failures on some (but
693  // not all) of the testing platforms. The problem is that MPI's
694  // default error handler is MPI_ERRORS_ARE_FATAL, which immediately
695  // aborts on error without returning an error code from the MPI
696  // function. Also, the testing platforms' MPI implementations'
697  // diagnostics are not giving me useful information. Thus, I'm
698  // setting the default error handler to MPI_ERRORS_RETURN, so that
699  // MPI_Waitall will return an error code.
700  //
701  // Note that all MpiComm methods check error codes returned by MPI
702  // functions, and throw an exception if the code is not MPI_SUCCESS.
703  // Thus, this change in behavior will only affect your program in
704  // the following case: You call a function f() in the try block of a
705  // try-catch, and expect f() to throw an exception (generally
706  // std::runtime_error) in a particular case not related to MpiComm,
707  // but MpiComm throws the exception instead. It's probably a bad
708  // idea for you to do this, because MpiComm might very well throw
709  // exceptions for things like invalid arguments.
710  const bool makeMpiErrorsReturn = true;
711  if (makeMpiErrorsReturn) {
713  rcp (new OpaqueWrapper<MPI_Errhandler> (MPI_ERRORS_RETURN));
714  setErrorHandler (errHandler);
715  }
716 
717  setupMembersFromComm();
718 }
719 
720 
721 template<typename Ordinal>
722 MpiComm<Ordinal>::MpiComm (MPI_Comm rawMpiComm)
723 {
724  TEUCHOS_TEST_FOR_EXCEPTION(rawMpiComm == MPI_COMM_NULL,
725  std::invalid_argument, "Teuchos::MpiComm constructor: The given MPI_Comm "
726  "is MPI_COMM_NULL.");
727  // We don't supply a "free" function here, since this version of the
728  // constructor makes the caller responsible for freeing rawMpiComm
729  // after use if necessary.
730  rawMpiComm_ = opaqueWrapper<MPI_Comm> (rawMpiComm);
731 
732  // FIXME (mfh 26 Mar 2012) The following is a bit wicked in that it
733  // changes the behavior of existing applications that use MpiComm,
734  // without warning. I've chosen to do it because I can't figure out
735  // any other way to help me debug MPI_Waitall failures on some (but
736  // not all) of the testing platforms. The problem is that MPI's
737  // default error handler is MPI_ERRORS_ARE_FATAL, which immediately
738  // aborts on error without returning an error code from the MPI
739  // function. Also, the testing platforms' MPI implementations'
740  // diagnostics are not giving me useful information. Thus, I'm
741  // setting the default error handler to MPI_ERRORS_RETURN, so that
742  // MPI_Waitall will return an error code.
743  //
744  // Note that all MpiComm methods check error codes returned by MPI
745  // functions, and throw an exception if the code is not MPI_SUCCESS.
746  // Thus, this change in behavior will only affect your program in
747  // the following case: You call a function f() in the try block of a
748  // try-catch, and expect f() to throw an exception (generally
749  // std::runtime_error) in a particular case not related to MpiComm,
750  // but MpiComm throws the exception instead. It's probably a bad
751  // idea for you to do this, because MpiComm might very well throw
752  // exceptions for things like invalid arguments.
753  const bool makeMpiErrorsReturn = true;
754  if (makeMpiErrorsReturn) {
756  rcp (new OpaqueWrapper<MPI_Errhandler> (MPI_ERRORS_RETURN));
757  setErrorHandler (errHandler);
758  }
759 
760  setupMembersFromComm();
761 }
762 
763 
764 template<typename Ordinal>
766  rawMpiComm_ (opaqueWrapper<MPI_Comm> (MPI_COMM_NULL)) // <- This will be set below
767 {
768  // These are logic errors, since they violate MpiComm's invariants.
769  RCP<const OpaqueWrapper<MPI_Comm> > origCommPtr = other.getRawMpiComm ();
770  TEUCHOS_TEST_FOR_EXCEPTION(origCommPtr == null, std::logic_error,
771  "Teuchos::MpiComm copy constructor: "
772  "The input's getRawMpiComm() method returns null.");
773  MPI_Comm origComm = *origCommPtr;
774  TEUCHOS_TEST_FOR_EXCEPTION(origComm == MPI_COMM_NULL, std::logic_error,
775  "Teuchos::MpiComm copy constructor: "
776  "The input's raw MPI_Comm is MPI_COMM_NULL.");
777 
778  // mfh 19 Oct 2012: Don't change the behavior of MpiComm's copy
779  // constructor for now. Later, we'll switch to the version that
780  // calls MPI_Comm_dup. For now, we just copy other's handle over.
781  // Note that the new MpiComm's tag is still different than the input
782  // MpiComm's tag. See Bug 5740.
783  if (true) {
784  rawMpiComm_ = origCommPtr;
785  }
786  else { // false (not run)
787  MPI_Comm newComm;
788  const int err = MPI_Comm_dup (origComm, &newComm);
789  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
790  "Teuchos::MpiComm copy constructor: MPI_Comm_dup failed with "
791  "the following error: " << mpiErrorCodeToString (err));
792  // No side effects until after everything has succeeded.
793  rawMpiComm_ = opaqueWrapper (newComm, details::safeCommFree);
794  }
795 
796  setupMembersFromComm();
797 }
798 
799 
800 template<typename Ordinal>
802 {
803  MPI_Comm_size(*rawMpiComm_, &size_);
804  MPI_Comm_rank(*rawMpiComm_, &rank_);
805  // Set the default tag to make unique across all communicators
806  if (tagCounter_ > maxTag_) {
807  tagCounter_ = minTag_;
808  }
809  tag_ = tagCounter_++;
810  // Must ensure the same tag is used on all processes!
811  MPI_Bcast(&tag_, 1, MPI_INT, 0, *rawMpiComm_);
812 }
813 
814 
815 template<typename Ordinal>
816 void
819 {
820  if (! is_null (errHandler)) {
821  const int err = details::setCommErrhandler (*getRawMpiComm (), *errHandler);
822  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
823  "Teuchos::MpiComm: Setting the MPI_Comm's error handler failed with "
824  "error \"" << mpiErrorCodeToString (err) << "\".");
825  }
826  // Wait to set this until the end, in case setting the error handler
827  // doesn't succeed.
828  customErrorHandler_ = errHandler;
829 }
830 
831 
832 
833 // Overridden from Comm
834 
835 
836 template<typename Ordinal>
838 {
839  return rank_;
840 }
841 
842 
843 template<typename Ordinal>
845 {
846  return size_;
847 }
848 
849 
850 template<typename Ordinal>
852 {
853  TEUCHOS_COMM_TIME_MONITOR(
854  "Teuchos::MpiComm<"<<OrdinalTraits<Ordinal>::name()<<">::barrier()"
855  );
856  const int err = MPI_Barrier(*rawMpiComm_);
857  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
858  "Teuchos::MpiComm::barrier: MPI_Barrier failed with error \""
859  << mpiErrorCodeToString (err) << "\".");
860 }
861 
862 
863 template<typename Ordinal>
865  const int rootRank, const Ordinal bytes, char buffer[]
866  ) const
867 {
868  TEUCHOS_COMM_TIME_MONITOR(
869  "Teuchos::MpiComm<"<<OrdinalTraits<Ordinal>::name()<<">::broadcast(...)"
870  );
871  const int err = MPI_Bcast(buffer,bytes,MPI_CHAR,rootRank,*rawMpiComm_);
872  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
873  "Teuchos::MpiComm::broadcast: MPI_Bcast failed with error \""
874  << mpiErrorCodeToString (err) << "\".");
875 }
876 
877 
878 template<typename Ordinal>
880  const Ordinal sendBytes, const char sendBuffer[],
881  const Ordinal recvBytes, char recvBuffer[]
882  ) const
883 {
884  TEUCHOS_COMM_TIME_MONITOR(
885  "Teuchos::MpiComm<"<<OrdinalTraits<Ordinal>::name()<<">::gatherAll(...)"
886  );
887  TEUCHOS_ASSERT_EQUALITY((sendBytes*size_), recvBytes );
888  const int err =
889  MPI_Allgather (const_cast<char *>(sendBuffer), sendBytes, MPI_CHAR,
890  recvBuffer, sendBytes, MPI_CHAR, *rawMpiComm_);
891  // NOTE: 'sendBytes' is being sent above for the MPI arg recvcount (which is
892  // very confusing in the MPI documentation) for MPI_Allgether(...).
893 
894  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
895  "Teuchos::MpiComm::gatherAll: MPI_Allgather failed with error \""
896  << mpiErrorCodeToString (err) << "\".");
897 }
898 
899 
900 template<typename Ordinal>
901 void
902 MpiComm<Ordinal>::gather (const Ordinal sendBytes,
903  const char sendBuffer[],
904  const Ordinal recvBytes,
905  char recvBuffer[],
906  const int root) const
907 {
908  TEUCHOS_COMM_TIME_MONITOR(
909  "Teuchos::MpiComm<"<<OrdinalTraits<Ordinal>::name()<<">::gather(...)"
910  );
911  const int err =
912  MPI_Gather (const_cast<char *> (sendBuffer), sendBytes, MPI_CHAR,
913  recvBuffer, sendBytes, MPI_CHAR, root, *rawMpiComm_);
914  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
915  "Teuchos::MpiComm::gather: MPI_Gather failed with error \""
916  << mpiErrorCodeToString (err) << "\".");
917 }
918 
919 
920 template<typename Ordinal>
921 void
924  const Ordinal bytes,
925  const char sendBuffer[],
926  char globalReducts[]) const
927 {
928  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::reduceAll(...)" );
929 
930  MpiReductionOpSetter op(mpiReductionOp(rcp(&reductOp,false)));
931  MPI_Datatype char_block;
932 
933  // TODO (mfh 26 Mar 2012) Check returned error codes of the MPI
934  // custom datatype functions.
935  MPI_Type_contiguous(bytes, MPI_CHAR, &char_block);
936  MPI_Type_commit(&char_block);
937 
938  const int err =
939  MPI_Allreduce (const_cast<char*>(sendBuffer), globalReducts, 1, char_block,
940  op.mpi_op(), *rawMpiComm_);
941  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
942  "Teuchos::MpiComm::reduceAll (custom op): MPI_Allreduce failed with error \""
943  << mpiErrorCodeToString (err) << "\".");
944 
945  // TODO (mfh 26 Mar 2012) Check returned error codes of the MPI
946  // custom datatype functions.
947  MPI_Type_free(&char_block);
948 }
949 
950 
951 template<typename Ordinal>
953  const ValueTypeReductionOp<Ordinal,char> &reductOp
954  ,const Ordinal sendBytes, const char sendBuffer[]
955  ,const Ordinal recvCounts[], char myGlobalReducts[]
956  ) const
957 {
958 
959  (void)sendBytes; // Ignore if not in debug mode
960 
961  TEUCHOS_COMM_TIME_MONITOR(
962  "Teuchos::MpiComm<"<<OrdinalTraits<Ordinal>::name()<<">::reduceAllAndScatter(...)"
963  );
964 
965 #ifdef TEUCHOS_DEBUG
966  Ordinal sumRecvBytes = 0;
967  for( Ordinal i = 0; i < size_; ++i ) {
968  sumRecvBytes += recvCounts[i];
969  }
970  TEUCHOS_TEST_FOR_EXCEPT(!(sumRecvBytes==sendBytes));
971 #endif // TEUCHOS_DEBUG
972 
973 #ifdef TEUCHOS_MPI_COMM_DUMP
974  if(show_dump) {
975  dumpBuffer<Ordinal,char>(
976  "Teuchos::MpiComm<Ordinal>::reduceAllAndScatter(...)",
977  "sendBuffer", sendBytes, sendBuffer );
978  dumpBuffer<Ordinal,Ordinal>(
979  "Teuchos::MpiComm<Ordinal>::reduceAllAndScatter(...)",
980  "recvCounts", as<Ordinal>(size_), recvCounts );
981  dumpBuffer<Ordinal,char>(
982  "Teuchos::MpiComm<Ordinal>::reduceAllAndScatter(...)",
983  "myGlobalReducts", as<char>(recvCounts[rank_]), myGlobalReducts );
984  }
985 #endif // TEUCHOS_MPI_COMM_DUMP
986 
987  // Create a new recvCount[] if Ordinal!=int
989  const bool Ordinal_is_int = typeid(int)==typeid(Ordinal);
990  Workspace<int> ws_int_recvCounts(wss,Ordinal_is_int?0:size_);
991  const int *int_recvCounts = 0;
992  if(Ordinal_is_int) {
993  int_recvCounts = reinterpret_cast<const int*>(recvCounts);
994  // Note: We must do an reinterpet cast since this must
995  // compile even if it is not executed. I could implement
996  // code that would not need to do this using template
997  // conditionals but I don't want to bother.
998  }
999  else {
1000  std::copy(recvCounts, recvCounts+size_, &ws_int_recvCounts[0]);
1001  int_recvCounts = &ws_int_recvCounts[0];
1002  }
1003 
1004  // Perform the operation
1005  MpiReductionOpSetter op(mpiReductionOp(rcp(&reductOp, false)));
1006 
1007  const int err = MPI_Reduce_scatter(
1008  const_cast<char*>(sendBuffer), myGlobalReducts,
1009  const_cast<int*>(int_recvCounts),
1010  MPI_CHAR,
1011  op.mpi_op(),
1012  *rawMpiComm_
1013  );
1014  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
1015  "Teuchos::MpiComm::reduceAllAndScatter: MPI_Reduce_scatter failed with "
1016  "error \"" << mpiErrorCodeToString (err) << "\".");
1017 }
1018 
1019 
1020 template<typename Ordinal>
1022  const ValueTypeReductionOp<Ordinal,char> &reductOp
1023  ,const Ordinal bytes, const char sendBuffer[], char scanReducts[]
1024  ) const
1025 {
1026  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::scan(...)" );
1027 
1028  MpiReductionOpSetter op(mpiReductionOp(rcp(&reductOp,false)));
1029  const int err =
1030  MPI_Scan (const_cast<char*>(sendBuffer), scanReducts, bytes, MPI_CHAR,
1031  op.mpi_op(), *rawMpiComm_);
1032  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
1033  "Teuchos::MpiComm::scan: MPI_Scan() failed with error \""
1034  << mpiErrorCodeToString (err) << "\".");
1035 }
1036 
1037 
1038 template<typename Ordinal>
1039 void
1040 MpiComm<Ordinal>::send (const Ordinal bytes,
1041  const char sendBuffer[],
1042  const int destRank) const
1043 {
1044  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::send(...)" );
1045 
1046 #ifdef TEUCHOS_MPI_COMM_DUMP
1047  if(show_dump) {
1048  dumpBuffer<Ordinal,char>(
1049  "Teuchos::MpiComm<Ordinal>::send(...)"
1050  ,"sendBuffer", bytes, sendBuffer
1051  );
1052  }
1053 #endif // TEUCHOS_MPI_COMM_DUMP
1054 
1055  const int err = MPI_Send (const_cast<char*>(sendBuffer), bytes, MPI_CHAR,
1056  destRank, tag_, *rawMpiComm_);
1057  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
1058  "Teuchos::MpiComm::send: MPI_Send() failed with error \""
1059  << mpiErrorCodeToString (err) << "\".");
1060 }
1061 
1062 
1063 template<typename Ordinal>
1064 void
1065 MpiComm<Ordinal>::send (const Ordinal bytes,
1066  const char sendBuffer[],
1067  const int destRank,
1068  const int tag) const
1069 {
1070  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::send(...)" );
1071  const int err = MPI_Send (const_cast<char*> (sendBuffer), bytes, MPI_CHAR,
1072  destRank, tag, *rawMpiComm_);
1073  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
1074  "Teuchos::MpiComm::send: MPI_Send() failed with error \""
1075  << mpiErrorCodeToString (err) << "\".");
1076 }
1077 
1078 
1079 template<typename Ordinal>
1080 void
1081 MpiComm<Ordinal>::ssend (const Ordinal bytes,
1082  const char sendBuffer[],
1083  const int destRank) const
1084 {
1085  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::ssend(...)" );
1086 
1087 #ifdef TEUCHOS_MPI_COMM_DUMP
1088  if(show_dump) {
1089  dumpBuffer<Ordinal,char>(
1090  "Teuchos::MpiComm<Ordinal>::send(...)"
1091  ,"sendBuffer", bytes, sendBuffer
1092  );
1093  }
1094 #endif // TEUCHOS_MPI_COMM_DUMP
1095 
1096  const int err = MPI_Ssend (const_cast<char*>(sendBuffer), bytes, MPI_CHAR,
1097  destRank, tag_, *rawMpiComm_);
1098  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
1099  "Teuchos::MpiComm::send: MPI_Ssend() failed with error \""
1100  << mpiErrorCodeToString (err) << "\".");
1101 }
1102 
1103 template<typename Ordinal>
1104 void
1105 MpiComm<Ordinal>::ssend (const Ordinal bytes,
1106  const char sendBuffer[],
1107  const int destRank,
1108  const int tag) const
1109 {
1110  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::ssend(...)" );
1111  const int err =
1112  MPI_Ssend (const_cast<char*>(sendBuffer), bytes, MPI_CHAR,
1113  destRank, tag, *rawMpiComm_);
1114  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
1115  "Teuchos::MpiComm::send: MPI_Ssend() failed with error \""
1116  << mpiErrorCodeToString (err) << "\".");
1117 }
1118 
1119 template<typename Ordinal>
1121  const ArrayView<const char> &sendBuffer,
1122  const int destRank
1123  ) const
1124 {
1125  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::readySend" );
1126 
1127 #ifdef TEUCHOS_MPI_COMM_DUMP
1128  if(show_dump) {
1129  dumpBuffer<Ordinal,char>(
1130  "Teuchos::MpiComm<Ordinal>::readySend(...)"
1131  ,"sendBuffer", bytes, sendBuffer
1132  );
1133  }
1134 #endif // TEUCHOS_MPI_COMM_DUMP
1135 
1136  const int err =
1137  MPI_Rsend (const_cast<char*>(sendBuffer.getRawPtr()), sendBuffer.size(),
1138  MPI_CHAR, destRank, tag_, *rawMpiComm_);
1139  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
1140  "Teuchos::MpiComm::readySend: MPI_Rsend() failed with error \""
1141  << mpiErrorCodeToString (err) << "\".");
1142 }
1143 
1144 
1145 template<typename Ordinal>
1146 void MpiComm<Ordinal>::
1147 readySend (const Ordinal bytes,
1148  const char sendBuffer[],
1149  const int destRank,
1150  const int tag) const
1151 {
1152  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::readySend" );
1153  const int err =
1154  MPI_Rsend (const_cast<char*> (sendBuffer), bytes,
1155  MPI_CHAR, destRank, tag, *rawMpiComm_);
1156  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
1157  "Teuchos::MpiComm::readySend: MPI_Rsend() failed with error \""
1158  << mpiErrorCodeToString (err) << "\".");
1159 }
1160 
1161 
1162 template<typename Ordinal>
1163 int
1164 MpiComm<Ordinal>::receive (const int sourceRank,
1165  const Ordinal bytes,
1166  char recvBuffer[]) const
1167 {
1168  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::receive(...)" );
1169 
1170  // A negative source rank indicates MPI_ANY_SOURCE, namely that we
1171  // will take an incoming message from any process, as long as the
1172  // tag matches.
1173  const int theSrcRank = (sourceRank < 0) ? MPI_ANY_SOURCE : sourceRank;
1174 
1175  MPI_Status status;
1176  const int err = MPI_Recv (recvBuffer, bytes, MPI_CHAR, theSrcRank, tag_,
1177  *rawMpiComm_, &status);
1178  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
1179  "Teuchos::MpiComm::receive: MPI_Recv() failed with error \""
1180  << mpiErrorCodeToString (err) << "\".");
1181 
1182 #ifdef TEUCHOS_MPI_COMM_DUMP
1183  if (show_dump) {
1184  dumpBuffer<Ordinal,char> ("Teuchos::MpiComm<Ordinal>::receive(...)",
1185  "recvBuffer", bytes, recvBuffer);
1186  }
1187 #endif // TEUCHOS_MPI_COMM_DUMP
1188 
1189  // Returning the source rank is useful in the MPI_ANY_SOURCE case.
1190  return status.MPI_SOURCE;
1191 }
1192 
1193 
1194 template<typename Ordinal>
1197  const int destRank) const
1198 {
1199  using Teuchos::as;
1200  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::isend(...)" );
1201 
1202  MPI_Request rawMpiRequest = MPI_REQUEST_NULL;
1203  const int err =
1204  MPI_Isend (const_cast<char*> (sendBuffer.getRawPtr ()),
1205  as<Ordinal> (sendBuffer.size ()), MPI_CHAR,
1206  destRank, tag_, *rawMpiComm_, &rawMpiRequest);
1207  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
1208  "Teuchos::MpiComm::isend: MPI_Isend() failed with error \""
1209  << mpiErrorCodeToString (err) << "\".");
1210 
1211  return mpiCommRequest<Ordinal> (rawMpiRequest, sendBuffer.size ());
1212 }
1213 
1214 
1215 template<typename Ordinal>
1218 isend (const ArrayView<const char> &sendBuffer,
1219  const int destRank,
1220  const int tag) const
1221 {
1222  using Teuchos::as;
1223  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::isend(...)" );
1224 
1225  MPI_Request rawMpiRequest = MPI_REQUEST_NULL;
1226  const int err =
1227  MPI_Isend (const_cast<char*> (sendBuffer.getRawPtr ()),
1228  as<Ordinal> (sendBuffer.size ()), MPI_CHAR,
1229  destRank, tag, *rawMpiComm_, &rawMpiRequest);
1230  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
1231  "Teuchos::MpiComm::isend: MPI_Isend() failed with error \""
1232  << mpiErrorCodeToString (err) << "\".");
1233 
1234  return mpiCommRequest<Ordinal> (rawMpiRequest, sendBuffer.size ());
1235 }
1236 
1237 
1238 template<typename Ordinal>
1241  const int sourceRank) const
1242 {
1243  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::ireceive(...)" );
1244 
1245  // A negative source rank indicates MPI_ANY_SOURCE, namely that we
1246  // will take an incoming message from any process, as long as the
1247  // tag matches.
1248  const int theSrcRank = (sourceRank < 0) ? MPI_ANY_SOURCE : sourceRank;
1249 
1250  MPI_Request rawMpiRequest = MPI_REQUEST_NULL;
1251  const int err =
1252  MPI_Irecv (const_cast<char*>(recvBuffer.getRawPtr()), recvBuffer.size(),
1253  MPI_CHAR, theSrcRank, tag_, *rawMpiComm_, &rawMpiRequest);
1254  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
1255  "Teuchos::MpiComm::ireceive: MPI_Irecv() failed with error \""
1256  << mpiErrorCodeToString (err) << "\".");
1257 
1258  return mpiCommRequest<Ordinal> (rawMpiRequest, recvBuffer.size());
1259 }
1260 
1261 template<typename Ordinal>
1264  const int sourceRank,
1265  const int tag) const
1266 {
1267  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::ireceive(...)" );
1268 
1269  // A negative source rank indicates MPI_ANY_SOURCE, namely that we
1270  // will take an incoming message from any process, as long as the
1271  // tag matches.
1272  const int theSrcRank = (sourceRank < 0) ? MPI_ANY_SOURCE : sourceRank;
1273 
1274  MPI_Request rawMpiRequest = MPI_REQUEST_NULL;
1275  const int err =
1276  MPI_Irecv (const_cast<char*> (recvBuffer.getRawPtr ()), recvBuffer.size (),
1277  MPI_CHAR, theSrcRank, tag, *rawMpiComm_, &rawMpiRequest);
1278  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error,
1279  "Teuchos::MpiComm::ireceive: MPI_Irecv() failed with error \""
1280  << mpiErrorCodeToString (err) << "\".");
1281 
1282  return mpiCommRequest<Ordinal> (rawMpiRequest, recvBuffer.size ());
1283 }
1284 
1285 namespace {
1286  // Called by the two-argument MpiComm::waitAll() variant.
1287  template<typename Ordinal>
1288  void
1289  waitAllImpl (const ArrayView<RCP<CommRequest<Ordinal> > >& requests,
1290  const ArrayView<MPI_Status>& rawMpiStatuses)
1291  {
1292  typedef typename ArrayView<RCP<CommRequest<Ordinal> > >::size_type size_type;
1293  const size_type count = requests.size();
1294  // waitAllImpl() is not meant to be called by users, so it's a bug
1295  // for the two views to have different lengths.
1296  TEUCHOS_TEST_FOR_EXCEPTION(rawMpiStatuses.size() != count,
1297  std::logic_error, "Teuchos::MpiComm's waitAllImpl: rawMpiStatus.size() = "
1298  << rawMpiStatuses.size() << " != requests.size() = " << requests.size()
1299  << ". Please report this bug to the Tpetra developers.");
1300  if (count == 0) {
1301  return; // No requests on which to wait
1302  }
1303 
1304  // MpiComm wraps MPI and can't expose any MPI structs or opaque
1305  // objects. Thus, we have to unpack requests into a separate array.
1306  // If that's too slow, then your code should just call into MPI
1307  // directly.
1308  //
1309  // Pull out the raw MPI requests from the wrapped requests.
1310  // MPI_Waitall should not fail if a request is MPI_REQUEST_NULL, but
1311  // we keep track just to inform the user.
1312  bool someNullRequests = false;
1313  Array<MPI_Request> rawMpiRequests (count, MPI_REQUEST_NULL);
1314  for (int i = 0; i < count; ++i) {
1315  RCP<CommRequest<Ordinal> > request = requests[i];
1316  if (! is_null (request)) {
1317  RCP<MpiCommRequestBase<Ordinal> > mpiRequest =
1318  rcp_dynamic_cast<MpiCommRequestBase<Ordinal> > (request);
1319  // releaseRawMpiRequest() sets the MpiCommRequest's raw
1320  // MPI_Request to MPI_REQUEST_NULL. This makes waitAll() not
1321  // satisfy the strong exception guarantee. That's OK because
1322  // MPI_Waitall() doesn't promise that it satisfies the strong
1323  // exception guarantee, and we would rather conservatively
1324  // invalidate the handles than leave dangling requests around
1325  // and risk users trying to wait on the same request twice.
1326  rawMpiRequests[i] = mpiRequest->releaseRawMpiRequest();
1327  }
1328  else { // Null requests map to MPI_REQUEST_NULL
1329  rawMpiRequests[i] = MPI_REQUEST_NULL;
1330  someNullRequests = true;
1331  }
1332  }
1333 
1334  // This is the part where we've finally peeled off the wrapper and
1335  // we can now interact with MPI directly.
1336  //
1337  // One option in the one-argument version of waitAll() is to ignore
1338  // the statuses completely. MPI lets you pass in the named constant
1339  // MPI_STATUSES_IGNORE for the MPI_Status array output argument in
1340  // MPI_Waitall(), which would tell MPI not to bother with the
1341  // statuses. However, we want the statuses because we can use them
1342  // for detailed error diagnostics in case something goes wrong.
1343  const int err = MPI_Waitall (count, rawMpiRequests.getRawPtr(),
1344  rawMpiStatuses.getRawPtr());
1345 
1346  // In MPI_Waitall(), an error indicates that one or more requests
1347  // failed. In that case, there could be requests that completed
1348  // (their MPI_Status' error field is MPI_SUCCESS), and other
1349  // requests that have not completed yet but have not necessarily
1350  // failed (MPI_PENDING). We make no attempt here to wait on the
1351  // pending requests. It doesn't make sense for us to do so, because
1352  // in general Teuchos::Comm doesn't attempt to provide robust
1353  // recovery from failed messages.
1354  if (err != MPI_SUCCESS) {
1355  if (err == MPI_ERR_IN_STATUS) {
1356  //
1357  // When MPI_Waitall returns MPI_ERR_IN_STATUS (a standard error
1358  // class), it's telling us to check the error codes in the
1359  // returned statuses. In that case, we do so and generate a
1360  // detailed exception message.
1361  //
1362  // Figure out which of the requests failed.
1363  Array<std::pair<size_type, int> > errorLocationsAndCodes;
1364  for (size_type k = 0; k < rawMpiStatuses.size(); ++k) {
1365  const int curErr = rawMpiStatuses[k].MPI_ERROR;
1366  if (curErr != MPI_SUCCESS) {
1367  errorLocationsAndCodes.push_back (std::make_pair (k, curErr));
1368  }
1369  }
1370  const size_type numErrs = errorLocationsAndCodes.size();
1371  if (numErrs > 0) {
1372  // There was at least one error. Assemble a detailed
1373  // exception message reporting which requests failed,
1374  // their error codes, and their source
1375  std::ostringstream os;
1376  os << "Teuchos::MpiComm::waitAll: MPI_Waitall() failed with error \""
1377  << mpiErrorCodeToString (err) << "\". Of the " << count
1378  << " total request" << (count != 1 ? "s" : "") << ", " << numErrs
1379  << " failed. Here are the indices of the failed requests, and the "
1380  "error codes extracted from their returned MPI_Status objects:"
1381  << std::endl;
1382  for (size_type k = 0; k < numErrs; ++k) {
1383  const size_type errInd = errorLocationsAndCodes[k].first;
1384  os << "Request " << errInd << ": MPI_ERROR = "
1385  << mpiErrorCodeToString (rawMpiStatuses[errInd].MPI_ERROR)
1386  << std::endl;
1387  }
1388  if (someNullRequests) {
1389  os << " On input to MPI_Waitall, there was at least one MPI_"
1390  "Request that was MPI_REQUEST_NULL. MPI_Waitall should not "
1391  "normally fail in that case, but we thought we should let you know "
1392  "regardless.";
1393  }
1394  TEUCHOS_TEST_FOR_EXCEPTION(true, std::runtime_error, os.str());
1395  }
1396  // If there were no actual errors in the returned statuses,
1397  // well, then I guess everything is OK. Just keep going.
1398  }
1399  else {
1400  std::ostringstream os;
1401  os << "Teuchos::MpiComm::waitAll: MPI_Waitall() failed with error \""
1402  << mpiErrorCodeToString (err) << "\".";
1403  if (someNullRequests) {
1404  os << " On input to MPI_Waitall, there was at least one MPI_Request "
1405  "that was MPI_REQUEST_NULL. MPI_Waitall should not normally fail in "
1406  "that case, but we thought we should let you know regardless.";
1407  }
1408  TEUCHOS_TEST_FOR_EXCEPTION(true, std::runtime_error, os.str());
1409  }
1410  }
1411 
1412  // Invalidate the input array of requests by setting all entries
1413  // to null.
1414  std::fill (requests.begin(), requests.end(), null);
1415  }
1416 
1417 
1418 
1419  // Called by the one-argument MpiComm::waitAll() variant.
1420  template<typename Ordinal>
1421  void
1422  waitAllImpl (const ArrayView<RCP<CommRequest<Ordinal> > >& requests)
1423  {
1424  typedef typename ArrayView<RCP<CommRequest<Ordinal> > >::size_type size_type;
1425  const size_type count = requests.size ();
1426  if (count == 0) {
1427  return; // No requests on which to wait
1428  }
1429 
1430  // MpiComm wraps MPI and can't expose any MPI structs or opaque
1431  // objects. Thus, we have to unpack requests into a separate
1432  // array. If that's too slow, then your code should just call
1433  // into MPI directly.
1434  //
1435  // Pull out the raw MPI requests from the wrapped requests.
1436  // MPI_Waitall should not fail if a request is MPI_REQUEST_NULL,
1437  // but we keep track just to inform the user.
1438  bool someNullRequests = false;
1439  Array<MPI_Request> rawMpiRequests (count, MPI_REQUEST_NULL);
1440  for (int i = 0; i < count; ++i) {
1441  RCP<CommRequest<Ordinal> > request = requests[i];
1442  if (! request.is_null ()) {
1443  RCP<MpiCommRequestBase<Ordinal> > mpiRequest =
1444  rcp_dynamic_cast<MpiCommRequestBase<Ordinal> > (request);
1445  // releaseRawMpiRequest() sets the MpiCommRequest's raw
1446  // MPI_Request to MPI_REQUEST_NULL. This makes waitAll() not
1447  // satisfy the strong exception guarantee. That's OK because
1448  // MPI_Waitall() doesn't promise that it satisfies the strong
1449  // exception guarantee, and we would rather conservatively
1450  // invalidate the handles than leave dangling requests around
1451  // and risk users trying to wait on the same request twice.
1452  rawMpiRequests[i] = mpiRequest->releaseRawMpiRequest ();
1453  }
1454  else { // Null requests map to MPI_REQUEST_NULL
1455  rawMpiRequests[i] = MPI_REQUEST_NULL;
1456  someNullRequests = true;
1457  }
1458  }
1459 
1460  // This is the part where we've finally peeled off the wrapper and
1461  // we can now interact with MPI directly.
1462  //
1463  // MPI lets us pass in the named constant MPI_STATUSES_IGNORE for
1464  // the MPI_Status array output argument in MPI_Waitall(), which
1465  // tells MPI not to bother writing out the statuses.
1466  const int err = MPI_Waitall (count, rawMpiRequests.getRawPtr(),
1467  MPI_STATUSES_IGNORE);
1468 
1469  // In MPI_Waitall(), an error indicates that one or more requests
1470  // failed. In that case, there could be requests that completed
1471  // (their MPI_Status' error field is MPI_SUCCESS), and other
1472  // requests that have not completed yet but have not necessarily
1473  // failed (MPI_PENDING). We make no attempt here to wait on the
1474  // pending requests. It doesn't make sense for us to do so,
1475  // because in general Teuchos::Comm doesn't attempt to provide
1476  // robust recovery from failed messages.
1477  if (err != MPI_SUCCESS) {
1478  std::ostringstream os;
1479  os << "Teuchos::MpiComm::waitAll: MPI_Waitall() failed with error \""
1480  << mpiErrorCodeToString (err) << "\".";
1481  if (someNullRequests) {
1482  os << std::endl << "On input to MPI_Waitall, there was at least one "
1483  "MPI_Request that was MPI_REQUEST_NULL. MPI_Waitall should not "
1484  "normally fail in that case, but we thought we should let you know "
1485  "regardless.";
1486  }
1487  TEUCHOS_TEST_FOR_EXCEPTION(true, std::runtime_error, os.str());
1488  }
1489 
1490  // Invalidate the input array of requests by setting all entries
1491  // to null. We delay this until the end, since some
1492  // implementations of CommRequest might hold the only reference to
1493  // the communication buffer, and we don't want that to go away
1494  // until we've waited on the communication operation.
1495  std::fill (requests.begin(), requests.end(), null);
1496  }
1497 
1498 } // namespace (anonymous)
1499 
1500 
1501 
1502 template<typename Ordinal>
1503 void
1505 waitAll (const ArrayView<RCP<CommRequest<Ordinal> > >& requests) const
1506 {
1507  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::waitAll(requests)" );
1508  // Call the one-argument version of waitAllImpl, to avoid overhead
1509  // of handling statuses (which the user didn't want anyway).
1510  waitAllImpl<Ordinal> (requests);
1511 }
1512 
1513 
1514 template<typename Ordinal>
1515 void
1518  const ArrayView<RCP<CommStatus<Ordinal> > >& statuses) const
1519 {
1520  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::waitAll(requests, statuses)" );
1521 
1522  typedef typename ArrayView<RCP<CommRequest<Ordinal> > >::size_type size_type;
1523  const size_type count = requests.size();
1524 
1525  TEUCHOS_TEST_FOR_EXCEPTION(count != statuses.size(),
1526  std::invalid_argument, "Teuchos::MpiComm::waitAll: requests.size() = "
1527  << count << " != statuses.size() = " << statuses.size() << ".");
1528 
1529  Array<MPI_Status> rawMpiStatuses (count);
1530  waitAllImpl<Ordinal> (requests, rawMpiStatuses());
1531 
1532  // Repackage the raw MPI_Status structs into the wrappers.
1533  for (size_type i = 0; i < count; ++i) {
1534  statuses[i] = mpiCommStatus<Ordinal> (rawMpiStatuses[i]);
1535  }
1536 }
1537 
1538 
1539 template<typename Ordinal>
1542 {
1543  TEUCHOS_COMM_TIME_MONITOR( "Teuchos::MpiComm::wait(...)" );
1544 
1545  if (is_null (*request)) {
1546  return null; // Nothing to wait on ...
1547  }
1548  else {
1549  RCP<CommStatus<Ordinal> > status = (*request)->wait ();
1550  // mfh 22 Oct 2012: The unit tests expect waiting on the
1551  // CommRequest to invalidate it by setting it to null.
1552  *request = null;
1553  return status;
1554  }
1555 }
1556 
1557 template<typename Ordinal>
1560 {
1561  MPI_Comm origRawComm = *rawMpiComm_;
1562  MPI_Comm newRawComm = MPI_COMM_NULL;
1563  const int err = MPI_Comm_dup (origRawComm, &newRawComm);
1564  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::runtime_error, "Teuchos"
1565  "::MpiComm::duplicate: MPI_Comm_dup failed with the following error: "
1566  << mpiErrorCodeToString (err));
1567 
1568  // Wrap the raw communicator, and pass the (const) wrapped
1569  // communicator to MpiComm's constructor. We created the raw comm,
1570  // so we have to supply a function that frees it after use.
1571  RCP<OpaqueWrapper<MPI_Comm> > wrapped = opaqueWrapper<MPI_Comm> (newRawComm, details::safeCommFree);
1572  RCP<MpiComm<Ordinal> > newComm (new MpiComm<Ordinal> (wrapped.getConst ()));
1573  return rcp_implicit_cast<Comm<Ordinal> > (newComm);
1574 }
1575 
1576 
1577 template<typename Ordinal>
1579 MpiComm<Ordinal>::split(const int color, const int key) const
1580 {
1581  MPI_Comm newComm;
1582  const int splitReturn =
1583  MPI_Comm_split (*rawMpiComm_,
1584  color < 0 ? MPI_UNDEFINED : color,
1585  key,
1586  &newComm);
1588  splitReturn != MPI_SUCCESS,
1589  std::logic_error,
1590  "Teuchos::MpiComm::split: Failed to create communicator with color "
1591  << color << "and key " << key << ". MPI_Comm_split failed with error \""
1592  << mpiErrorCodeToString (splitReturn) << "\".");
1593  if (newComm == MPI_COMM_NULL) {
1594  return RCP< Comm<Ordinal> >();
1595  } else {
1596  return rcp(new MpiComm<Ordinal>(
1597  rcp_implicit_cast<const OpaqueWrapper<MPI_Comm> >(
1598  opaqueWrapper(newComm,MPI_Comm_free))));
1599  }
1600 }
1601 
1602 
1603 template<typename Ordinal>
1606 {
1607  int err = MPI_SUCCESS; // For error codes returned by MPI functions
1608 
1609  // Get the group that this communicator is in.
1610  MPI_Group thisGroup;
1611  err = MPI_Comm_group (*rawMpiComm_, &thisGroup);
1612  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::logic_error,
1613  "Failed to obtain the current communicator's group. "
1614  "MPI_Comm_group failed with error \""
1615  << mpiErrorCodeToString (err) << "\".");
1616 
1617  // Create a new group with the specified members.
1618  MPI_Group newGroup;
1619  // It's rude to cast away const, but MPI functions demand it.
1620  //
1621  // NOTE (mfh 14 Aug 2012) Please don't ask for &ranks[0] unless you
1622  // know that ranks.size() > 0. That's why I'm using getRawPtr().
1623  err = MPI_Group_incl (thisGroup, ranks.size(),
1624  const_cast<int*> (ranks.getRawPtr ()), &newGroup);
1625  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::logic_error,
1626  "Failed to create subgroup. MPI_Group_incl failed with error \""
1627  << mpiErrorCodeToString (err) << "\".");
1628 
1629  // Create a new communicator from the new group.
1630  MPI_Comm newComm;
1631  try {
1632  err = MPI_Comm_create (*rawMpiComm_, newGroup, &newComm);
1633  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::logic_error,
1634  "Failed to create subcommunicator. MPI_Comm_create failed with error \""
1635  << mpiErrorCodeToString (err) << "\".");
1636  } catch (...) {
1637  // Attempt to free the new group before rethrowing. If
1638  // successful, this will prevent a memory leak due to the "lost"
1639  // group that was allocated successfully above. Since we're
1640  // throwing std::logic_error anyway, we can only promise
1641  // best-effort recovery; thus, we don't check the error code.
1642  (void) MPI_Group_free (&newGroup);
1643  (void) MPI_Group_free (&thisGroup);
1644  throw;
1645  }
1646 
1647  // We don't need the group any more, so free it.
1648  err = MPI_Group_free (&newGroup);
1649  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::logic_error,
1650  "Failed to free subgroup. MPI_Group_free failed with error \""
1651  << mpiErrorCodeToString (err) << "\".");
1652  err = MPI_Group_free (&thisGroup);
1653  TEUCHOS_TEST_FOR_EXCEPTION(err != MPI_SUCCESS, std::logic_error,
1654  "Failed to free subgroup. MPI_Group_free failed with error \""
1655  << mpiErrorCodeToString (err) << "\".");
1656 
1657  if (newComm == MPI_COMM_NULL) {
1658  return RCP<Comm<Ordinal> > ();
1659  } else {
1660  using Teuchos::details::safeCommFree;
1661  typedef OpaqueWrapper<MPI_Comm> ow_type;
1662  RCP<const ow_type> wrapper =
1663  rcp_implicit_cast<const ow_type> (opaqueWrapper (newComm, safeCommFree));
1664  return rcp (new MpiComm<Ordinal> (wrapper));
1665  }
1666 }
1667 
1668 
1669 // Overridden from Describable
1670 
1671 
1672 template<typename Ordinal>
1674 {
1675  std::ostringstream oss;
1676  oss
1677  << typeName(*this)
1678  << "{"
1679  << "size="<<size_
1680  << ",rank="<<rank_
1681  << ",rawMpiComm="<<static_cast<MPI_Comm>(*rawMpiComm_)
1682  <<"}";
1683  return oss.str();
1684 }
1685 
1686 
1687 #ifdef TEUCHOS_MPI_COMM_DUMP
1688 template<typename Ordinal>
1689 bool MpiComm<Ordinal>::show_dump = false;
1690 #endif
1691 
1692 
1693 // private
1694 
1695 
1696 template<typename Ordinal>
1697 void MpiComm<Ordinal>::assertRank(const int rank, const std::string &rankName) const
1698 {
1700  ! ( 0 <= rank && rank < size_ ), std::logic_error
1701  ,"Error, "<<rankName<<" = " << rank << " is not < 0 or is not"
1702  " in the range [0,"<<size_-1<<"]!"
1703  );
1704 }
1705 
1706 
1707 } // namespace Teuchos
1708 
1709 
1710 template<typename Ordinal>
1712 Teuchos::createMpiComm(
1713  const RCP<const OpaqueWrapper<MPI_Comm> > &rawMpiComm
1714  )
1715 {
1716  if( rawMpiComm.get()!=NULL && *rawMpiComm != MPI_COMM_NULL )
1717  return rcp(new MpiComm<Ordinal>(rawMpiComm));
1718  return Teuchos::null;
1719 }
1720 
1721 
1722 #endif // TEUCHOS_MPI_COMM_HPP
virtual void ssend(const Ordinal bytes, const char sendBuffer[], const int destRank) const
virtual RCP< Comm< Ordinal > > duplicate() const
RCP< const T > getConst() const
Return an RCP<const T> version of *this.
RCP< CommStatus< OrdinalType > > wait()
Wait on this communication request to complete.
virtual int getRank() const
virtual int receive(const int sourceRank, const Ordinal bytes, char recvBuffer[]) const
RCP< CommStatus< OrdinalType > > cancel()
Cancel the communication request, and return its status.
bool is_null(const boost::shared_ptr< T > &p)
Returns true if p.get()==NULL.
RCP< const MpiReductionOp< Ordinal > > mpiReductionOp(const RCP< const ValueTypeReductionOp< Ordinal, char > > &reductOp)
Create an MpiReductionOp object given an ReductionOp object.
Templated class for workspace creation.
MPI-specific implementation of CommStatus.
virtual void gather(const Ordinal sendBytes, const char sendBuffer[], const Ordinal recvBytes, char recvBuffer[], const int root) const
Gather values from all processes to the root process.
virtual RCP< CommStatus< Ordinal > > wait(const Ptr< RCP< CommRequest< Ordinal > > > &request) const
#define TEUCHOS_TEST_FOR_EXCEPTION(throw_exception_test, Exception, msg)
Macro for throwing an exception with breakpointing to ease debugging.
virtual void broadcast(const int rootRank, const Ordinal bytes, char buffer[]) const
size_type size() const
The total number of items in the managed array.
int rank(const Comm< Ordinal > &comm)
Get the process rank.
MpiCommRequest(MPI_Request rawMpiRequest, const ArrayView< char >::size_type numBytesInMessage)
Constructor (from a raw MPI_Request).
virtual ~MpiCommRequest()
Destructor; cancels the request if it is still pending.
virtual void gatherAll(const Ordinal sendBytes, const char sendBuffer[], const Ordinal recvBytes, char recvBuffer[]) const
T * getRawPtr()
Return a raw pointer to beginning of array or NULL if unsized.
std::string description() const
int getTag() const
The current tag.
Tabbing class for helping to create formated, indented output for a basic_FancyOStream object...
RCP< const OpaqueWrapper< MPI_Comm > > getRawMpiComm() const
Return the embedded wrapped opaque MPI_Comm object.
virtual RCP< CommRequest< Ordinal > > isend(const ArrayView< const char > &sendBuffer, const int destRank) const
OrdinalType getSourceRank()
The source rank that sent the message.
virtual ~MpiCommRequestBase()
Destructor; cancels the request if it is still pending.
Base class MPI implementation of CommRequest.
virtual ~MpiCommStatus()
Destructor (declared virtual for memory safety)
virtual RCP< Comm< Ordinal > > createSubcommunicator(const ArrayView< const int > &ranks) const
MPI_Request releaseRawMpiRequest()
Return and relinquish ownership of the raw MPI_Request.
TEUCHOS_DEPRECATED RCP< T > rcp(T *p, Dealloc_T dealloc, bool owns_mem)
Deprecated.
bool isNull() const
Whether the raw MPI_Request is MPI_REQUEST_NULL.
void setErrorHandler(const RCP< const OpaqueWrapper< MPI_Errhandler > > &errHandler)
Set the MPI error handler for this communicator.
Teuchos implementation details.
Utility class for setting an MPI-compatible reduction object and using it to create an MPI_Op object...
TEUCHOS_DEPRECATED void scan(const Comm< Ordinal > &comm, const EReductionType reductType, const Packet &send, Packet *scanReduct)
Deprecated.
std::string mpiErrorCodeToString(const int err)
Human-readable string version of the given MPI error code.
MPI implementation of CommRequest.
virtual void readySend(const ArrayView< const char > &sendBuffer, const int destRank) const
virtual void waitAll(const ArrayView< RCP< CommRequest< Ordinal > > > &requests) const
static RCP< FancyOStream > getDefaultOStream()
Get the default output stream object.
This structure defines some basic traits for the ordinal field type.
TEUCHOS_DEPRECATED void reduceAll(const Comm< Ordinal > &comm, const EReductionType reductType, const Packet &send, Packet *globalReduct)
Deprecated .
Encapsulation of the result of a receive (blocking or nonblocking).
void send(const Packet sendBuffer[], const Ordinal count, const int destRank, const int tag, const Comm< Ordinal > &comm)
Variant of send() that takes a tag (and restores the correct order of arguments). ...
virtual void send(const Ordinal bytes, const char sendBuffer[], const int destRank) const
Workspace encapsulation class.
T * getRawPtr() const
Return a raw pointer to beginning of array or NULL if unsized.
MPI_Op mpi_op() const
Return the created MPI_Op reduction object that can be used by MPI.
RCP< CommRequest< Ordinal > > ireceive(const ArrayRCP< Packet > &recvBuffer, const int sourceRank, const int tag, const Comm< Ordinal > &comm)
Variant of ireceive that takes a tag argument (and restores the correct order of arguments).
virtual void reduceAllAndScatter(const ValueTypeReductionOp< Ordinal, char > &reductOp, const Ordinal sendBytes, const char sendBuffer[], const Ordinal recvCounts[], char myGlobalReducts[]) const
OrdinalType getError()
The error code of the received message.
MpiCommRequestBase(MPI_Request rawMpiRequest)
Constructor (from a raw MPI_Request).
MpiCommRequestBase()
Default constructor.
virtual void barrier() const
Abstract interface for distributed-memory communication.
void push_back(const value_type &x)
Nonowning array view.
Defines basic traits for the ordinal field type.
The Teuchos namespace contains all of the classes, structs and enums used by Teuchos, as well as a number of utility routines.
virtual RCP< CommRequest< Ordinal > > ireceive(const ArrayView< char > &Buffer, const int sourceRank) const
MpiCommRequest()
Default constructor.
size_type size() const
TypeTo as(const TypeFrom &t)
Convert from one value type to another.
Definition: Teuchos_as.hpp:287
void ssend(const Packet sendBuffer[], const Ordinal count, const int destRank, const int tag, const Comm< Ordinal > &comm)
Variant of ssend() that takes a tag (and restores the correct order of arguments).
ArrayView< char >::size_type numBytes() const
Number of bytes in the nonblocking send or receive request.
virtual RCP< Comm< Ordinal > > split(const int color, const int key) const
OrdinalType getTag()
The tag of the received message.
Smart reference counting pointer class for automatic garbage collection.
virtual int getSize() const
virtual void scan(const ValueTypeReductionOp< Ordinal, char > &reductOp, const Ordinal bytes, const char sendBuffer[], char scanReducts[]) const
Encapsulation of a pending nonblocking communication operation.
#define TEUCHOS_ASSERT_EQUALITY(val1, val2)
This macro is checks that to numbers are equal and if not then throws an exception with a good error ...
virtual void reduceAll(const ValueTypeReductionOp< Ordinal, char > &reductOp, const Ordinal bytes, const char sendBuffer[], char globalReducts[]) const
Implementation of Comm that uses MPI for communication.
Defines basic traits returning the name of a type in a portable and readable way. ...
Definition of Teuchos::as, for conversions between types.
void readySend(const Packet sendBuffer[], const Ordinal count, const int destRank, const int tag, const Comm< Ordinal > &comm)
Variant of readySend() that accepts a message tag.
#define TEUCHOS_TEST_FOR_EXCEPT(throw_exception_test)
This macro is designed to be a short version of TEUCHOS_TEST_FOR_EXCEPTION() that is easier to call...
Simple wrapper class for raw pointers to single objects where no persisting relationship exists...
TEUCHOSCORE_LIB_DLL_EXPORT Teuchos::RCP< WorkspaceStore > get_default_workspace_store()
Get the global workspace object set by set_default_workspace_store().
std::string typeName(const T &t)
Template function for returning the concrete type name of a passed-in object.
Memory-safe templated array class that encapsulates std::vector.
bool is_null() const
Returns true if the underlying pointer is null.