-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_tclmpi.c
3098 lines (2743 loc) · 121 KB
/
_tclmpi.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
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
401
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*! \file _tclmpi.c
* \brief This file contains the C code with the Tcl MPI wrappers. */
/* TclMPI - A Tcl Interface to MPI */
/*! \page copyright Copyright and License for TclMPI
*
* Copyright (c) 2012,2016,2017,2018,2019,2020,2021 Axel Kohlmeyer <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the author of this software nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Axel Kohlmeyer
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <mpi.h>
#include <tcl.h>
#include <stdio.h>
#include <string.h>
/*! \page userguide TclMPI User's Guide
*
* This page describes Tcl bindings for MPI. This package provides a
* shared object that can be loaded into a Tcl interpreter to provide
* additional commands that act as an interface to an underlying MPI
* implementation. This allows to run Tcl scripts in parallel via
* mpirun or mpiexec similar to C, C++ or Fortran programs and
* communicate via wrappers to MPI function call.
*
* The original motivation for writing this package was to complement a
* Tcl wrapper for the LAMMPS molecular dynamics simulation software,
* but also allow using the VMD molecular visualization and analysis
* package in parallel without having to recompile VMD and using an
* API that is convenient to people that already know how to program
* parallel programs with MPI in C, C++ or Fortran.
* It has since been adopted to provide an MPI wrapper for
* the OpenSees software: https://github.com/ambaker1/OpenSeesMPI
*
* \section binaries Pre-compiled Binary Packages
*
* While it is usually expected that MPI based parallel applications
* are compiled from source code using the target machine's local
* MPI implementation, that is not always convenient or necessary.
* This applies for example to the Windows platform or Linux
* distributions where mechanisms are in place to check that are
* pre-requisites are installed and binaries are compatible.
* The TclMPI homepage has links to available binaries and information
* about how to install them as they become available.
*
* \section compile Compilation
*
* The package currently consist of a single C source file which usually
* will be compiled for dynamic linkage, but can also be compiled into a
* new Tcl interpreter with TclMPI included (required on some platforms
* that require static linkage) and a Tcl script file.
* In addition the package contains some examples, a simple unit test
* harness (implemented in Tcl) and a set of tests to be run with either
* one MPI rank (test01, test02) or two MPI ranks (test03, test04).
*
* The build system uses CMake (version 3.16 or later) and has been
* confirmed to work on Linux, macOS, and Windows using a variety of
* C compilers (GNU, Clang, Intel, PGI, MSVC). You need to have both,
* Tcl and MPI installed including their respective development support
* packages (sometimes called SDK). The MPI library has to be at least
* MPI-2 standard compliant and the Tcl version should be 8.6 or later.
* When compiled for a dynamically loaded shared object (DSO) or DLL
* file, the MPI library has to be compiled and linked with support for
* building shared libraries as well.
*
* To configure and build TclMPI you need to run CMake the usual way,
* in a console window with with:
\code{.sh}
cmake -B build-folder -S .
cmake --build build-folder
cmake --install build-folder
\endcode
* There are a few settings that can be used to adjust what is compiled
* and installed and where. The following settings are supported:
* - BUILD_TCLMPI_SHELL Build a `tclmpish` executable as extended Tcl shell (default: on)
* - ENABLE_TCL_STUBS Use the Tcl stubs mechanism (default: on, requires Tcl 8.6 or later)
* - CMAKE_INSTALL_PREFIX Path to installation location prefix (default: (platform specific))
* - BUILD_TESTING Enable unit testing (default: on)
* - DOWNLOAD_MPICH4WIN Download MPICH2-1.4.1 headers and link library (default: off,
* only supported when cross-compiling on Linux for Windows)
*
* To change settings from the defaults append `-D<SETTING>=<VALUE>` to
* the `cmake` command line and replace `<SETTING>` and `<VALUE>` accordingly
* or you may use the `ccmake` text mode UI or `cmake-gui`.
*
* \section gendocs Building the Documentation
*
* Documentation in HTML and PDF format is extracted from the sources
* using doxygen, if available. The build of the HTML format
* documentation is requested with
\code{.sh}
cmake --build build-folder --target html
\endcode
* The documentation will be in folder `build-folder/html`. To
* generate the PDF documentation, PDFLaTeX and several LaTeX
* style packages need to be installed. This is requested using
\code{.sh}
cmake --build build-folder --target pdf
\endcode
* and the resulting documentation will be in `build-folder/tclmpi_docs.pdf`.
*
* \section install Installation
*
* To install the TclMPI package you can use
\code{.sh}
cmake --build build-folder --target install
\endcode
* which should by default install the compiled shared object and the
* associated two Tcl files into a subfolder of `<CMAKE_INSTALL_PREFIX>/tcl8.6`.
* The default value of CMAKE_INSTALL_PREFIX is system specific, but it can
* changed with `-D CMAKE_INSTALL_PREFIX=/some/path` when configuring
* with CMake, then the installation will be into the corresponding location.
*
* To tell Tcl where to find the package, you need to either set or expand
* the TCLLIBPATH environment variable to the folder into which you have
* installed the files or place
* `auto_path [concat /usr/local/tcl8.6/ $auto_path]` at the beginning
* of your Tcl script or in your `.tclshrc` file (or .vmdrc or similar).
* Then you should be able to load the TclMPI wrappers on demand by using
* the command `package require tclmpi`.
*
* For the extended Tcl shell `tclmpish`, the `_tclmpi.so` file is not used
* and instead `tclmpish` already includes the coresponding code and needs
* to be run instead of `tclsh`. For that you may append the `bin` folder
* of the installation tree to your PATH environment variable. In case
* of using the custom Tcl shell, the startup script would be called
* `.tclmpishrc` instead of `.tclshrc`.
*
* \section devel Software Development and Bug Reports
*
* The TclMPI code is maintained using git for source code management,
* and the project is hosted on github at
* https://github.com/akohlmey/tclmpi From there you can download
* snapshots of the development and releases, clone the repository to
* follow development, or work on your own branches after forking
* it. Bug reports and feature requests should also be filed on github
* at through the issue tracker at:
* https://github.com/akohlmey/tclmpi/issues.
*
* \section examples Example Programs
* The following section provides some simple examples using TclMPI
* to recreate some common MPI example programs in Tcl.
*
* \subsection hello Hello World
* This is the TclMPI version of "hello world".
* \code {.tcl}
#!/usr/bin/env tclsh
package require tclmpi 1.2
# initialize MPI
::tclmpi::init
# get size of communicator and rank of process
set comm tclmpi::comm_world
set size [::tclmpi::comm_size $comm]
set rank [::tclmpi::comm_rank $comm]
puts "hello world, this is rank $rank of $size"
# shut down MPI
::tclmpi::finalize
exit 0
* \endcode
*
* \subsection mypi Computation of Pi
* This script uses TclMPI to compute the value of Pi from
* numerical quadrature of the integral:
\f[
\pi = \int^1_0 {\frac{4}{1 + x^2}} dx
\f]
* \code {.tcl}
#!/usr/bin/env tclsh
package require tclmpi 1.2
# initialize MPI
::tclmpi::init
set comm tclmpi::comm_world
set size [::tclmpi::comm_size $comm]
set rank [::tclmpi::comm_rank $comm]
set master 0
set num [lindex $argv 0]
# make sure all processes have the same interval parameter
set num [::tclmpi::bcast $num ::tclmpi::int $master $comm]
# run parallel calculation
set h [expr {1.0/$num}]
set sum 0.0
for {set i $rank} {$i < $num} {incr i $size} {
set sum [expr {$sum + 4.0/(1.0 + ($h*($i+0.5))**2)}]
}
set mypi [expr {$h * $sum}]
# combine and print results
set mypi [::tclmpi::allreduce $mypi tclmpi::double \
tclmpi::sum $comm]
if {$rank == $master} {
set rel [expr {abs(($mypi - 3.14159265358979)/3.14159265358979)}]
puts "result: $mypi. relative error: $rel"
}
# shut down MPI
::tclmpi::finalize
exit 0
* \endcode
*
* \subsection distsum Distributed Sum
* This is a small example version that distributes a data set
* and computes the sum across all elements in parallel.
*
* \code {.tcl}
#!/usr/bin/env tclsh
package require tclmpi 1.2
# data summation helper function
proc sum {data} {
set sum 0
foreach d $data {
set sum [expr {$sum + $d}]
}
return $sum
}
::tclmpi::init
set comm $tclmpi::comm_world
set mpi_sum $tclmpi::sum
set mpi_double $tclmpi::double
set mpi_int $tclmpi::int
set size [::tclmpi::comm_size $comm]
set rank [::tclmpi::comm_rank $comm]
set master 0
# The master creates the list of data
#
set dataSize 1000000
set data {}
if { $comm == $master } {
set mysum 0
for { set i 0 } { $i < $dataSize } { incr i } {
lappend data $i
}
}
# add padding, so the number of data elements is divisible
# by the number of processors as required by tclmpi::scatter
set needpad [expr {$dataSize % $size}]
set numpad [expr {$needpad ? ($size - $needpad) : 0}]
if { [comm_rank $comm] == $master } {
for {set i 0} {$i < $numpad} {incr i} {
lappend data 0
}
}
set blocksz [expr {($dataSize + $numpad)/ $size}]
# distribute data and do the summation on each node
# the sum the result across all nodes. Note: the data
# is integer, but we need to do the full sum in double
# precison to avoid overflows.
set mydata [::tclmpi::scatter $data $mpi_int $master $comm]
set sum [::tclmpi::allreduce [sum $mydata] $mpi_double $mpi_sum $comm]
if { $comm == $master } {
puts "Distributed sum: $sum"
}
::tclmpi::finalize
* \endcode
*
* \section tclapi TclMPI Tcl command reference
* All TclMPI Tcl commands are placed into the \ref tclmpi namespace.
*/
/*! \page devguide TclMPI Developer's Guide
*
* This document explains the implementation of the Tcl bindings
* for MPI implemented in TclMPI. The following sections will
* document how and which MPI functions are mapped to Tcl and
* what design choices were made in the process.
*
* \section design Overall Design and Differences to the MPI C-bindings
*
* To be consistent with typical Tcl conventions, all commands and constants
* are in lower case and prefixed with tclmpi, so that clashes with existing
* programs are reduced.
*
* The overall philosophy of the bindings
* is to make the API similar to the MPI one (e.g. maintain the order of
* arguments), but don't stick to it slavishly and do things the Tcl way
* wherever justified. Convenience and simplicity take precedence over
* performance. If performance matters that much, one would write the entire
* code in C/C++ or Fortran and not in Tcl. The biggest visible change is that
* for sending data around, receive buffers will be automatically set up
* to handle the entire message. Thus the typical "count" arguments of the
* C/C++ or Fortran bindings for MPI is not required, and the received data
* will be the return value of the corresponding command. This is consistent
* with the automatic memory management in Tcl, but this convenience and
* consistency will affect performance and semantics. For example calls
* to tclmpi::bcast will be converted into *two* calls to MPI_Bcast();
* the first will broadcast the size of the data set being sent (so that
* sufficiently sized buffers can be allocated) and then the second call
* will finally send the data for real. Similarly, tclmpi::recv will be
* converted into calling MPI_Probe() and then MPI_Recv() for the purpose
* of determining the amount of temporary storage required. The second call
* will also use the MPI_SOURCE and MPI_TAG flags from the MPI_Status object
* created for MPI_Probe() to make certain, the correct data is received.
*
* Things get even more complicated with with non-blocking receives. Since
* we need to know the size of the message to receive, a non-blocking receive
* can only be posted, if the corresponding send is already pending. This is
* being determined by calling MPI_Iprobe() and when this shows no (matching)
* pending message, the parameters for the receive will be cached and the
* then MPI_Probe() followed by MPI_Recv() will be called as part of
* tclmpi::wait. The blocking/non-blocking behavior of the Tcl script
* should be very close to the corresponding C bindings, but probably not
* as efficient.
*
* \section naming Naming Conventions
* All functions that are new Tcl commands follow the MPI naming
* conventions, but using TclMPI_ as prefix instead of MPI_.
* The corresponding Tcl commands are placed in the tclmpi namespace
* and all lower case. Example: \ref TclMPI_Init() is the wrapper for
* MPI_Init() and is provided as command tclmpi::init.
* Defines and constants from the MPI header file are represented in
* TclMPI as plain strings, all lowercase and with a tclmpi:: prefix.
* Thus MPI_COMM_WORLD becomes tclmpi::comm_world and MPI_INT becomes
* tclmpi::int.
* Functions that are internal to the plugin as well as static variables
* are prefixed with all lower case, i.e. tclmpi_. Those functions have
* to be declared static.
*
* All string constants are also declared as namespace variables,
* e.g. $tclmpi::comm_world, so that shortcut notations are possible
* as shown in the following example:
* \code {.tcl}
namespace upvar tclmpi comm_world comm
namespace upvar tclmpi int mpi_int
* \endcode
*
* \section Internal TclMPI Support Functions
* Several MPI entities like communicators, requests, status objects
* cannot be represented directly in Tcl. For TclMPI they need to be
* mapped to something else, for example a string that will uniquely
* identify this entity and then it will be translated into the real
* object it represents with the help of the following support functions.
*
* \subsection tclcomm Mapping MPI Communicators
* MPI communicators are represented in TclMPI by strings of the form
* "tclmpi::comm%d", with "%d" being replaced by a unique integer.
* In addition, a few string constants are mapped to the default
* communicators that are defined in MPI. These are tclmpi::comm_world,
* tclmpi::comm_self, and tclmpi::comm_null, which represent
* MPI_COMM_WORLD, MPI_COMM_SELF, and MPI_COMM_NULL, respectively.
*
* Internally the map is maintained in a simple linked list which
* is initialized with the three default communicators when the plugin
* is loaded and where new communicators are added at the end as needed.
* The functions \ref mpi2tcl_comm and \ref tcl2mpi_comm are then used
* to translate from one representation to the other while
* \ref tclmpi_add_comm will append a new structure containing the
* communicator to the list.
* Correspondingly \ref tclmpi_del_comm will remove a communicator entry
* from the lest, based on its Tcl string representation.
*
* \subsection tclreq Mapping MPI Requests
* MPI requests are represented in TclMPI by strings of the form
* "tclmpi::req%d", with "%d" being replaced by a unique integer.
* Internally this map is maintained in a simple linked list to which
* new requests are appended and from which completed requests are
* removed as needed.
* The function \ref tclmpi_find_req is used to locate a specific request
* and its associated data from its string label. In addition,
* \ref tclmpi_add_req will append a new request to the list, and
* \ref tclmpi_del_req will remove (completed) requests.
*
* \subsection tcldata Mapping Data Types
* The helper function \ref tclmpi_datatype is used to convert string
* constants representing specific data types into integer constants
* for convenient branching. Data types in TclMPI are somewhat different
* from MPI data types to match better the spirit of Tcl scripting.
*
* \subsection tclerr Common Error Message Processing
* There is a significant redundancy in checking for and reporting
* error conditions. For this purpose, several support functions
* exist.
*
* \ref tclmpi_errcheck verifies if calls to the MPI library were
* successful and if not, generates a formatted error message that
* is appended to the current result list.
*
* \ref tclmpi_commcheck verifies if a communicator argument was
* using a valid Tcl representation and if not, generates a
* formatted error message that is appended to the current result list.
*
* \ref tclmpi_typecheck test if a type argument was using a valid
* Tcl representation and if not, generates a formatted error message
* that is appended to the current result list.
*
* \section tcltest TclMPI Tcl Test Harness command reference
* TclMPI includes a simple unit test harness written in (of course) Tcl.
* The corresponding commands are placed into the \ref tclmpi_test namespace.
* Check out the files in the `tests` folders for examples.
*/
/* We require MPI-2 */
#if !defined(MPI_VERSION) || (MPI_VERSION < 2)
#error TclMPI needs at least MPI-2
#endif
/*! \defgroup supportfn Support functions and data structures
* @{
*/
/*! Linked list entry type for managing MPI communicators */
typedef struct tclmpi_comm tclmpi_comm_t;
/*! Linked list entry to map MPI communicators to strings. */
struct tclmpi_comm {
const char *label; /*!< String representing the communicator in Tcl */
MPI_Comm comm; /*!< MPI communicator corresponding of this entry */
int valid; /*!< Non-zero if communicator is valid */
tclmpi_comm_t *next; /*!< Pointer to next element in linked list */
};
/*! First element of the communicator map list */
static tclmpi_comm_t *first_comm = NULL;
/*! Last element of the communicator map list */
static tclmpi_comm_t *last_comm = NULL;
/*! Communicator counter. Incremented to get unique strings */
static int tclmpi_comm_cntr = 0;
/*! Size of stringbuffer for tclmpi labels */
#define TCLMPI_LABEL_SIZE 32
/*! Additional global communicator to detect unlisted communicators */
static MPI_Comm MPI_COMM_INVALID;
/*! Translate an MPI communicator to its Tcl label.
* \param comm an MPI communicator
* \return the corresponding string label or NULL.
*
* This function will search through the linked list of known communicators
* until it finds the (first) match and then returns the string label to
* the calling function. If a NULL is returned, the communicator does not
* yet exist in the linked list.
*/
static const char *mpi2tcl_comm(MPI_Comm comm)
{
tclmpi_comm_t *next;
next = first_comm;
while (next) {
if (comm == next->comm) {
if (next->valid != 0) {
return next->label;
} else {
return NULL;
}
} else {
next = next->next;
}
}
return NULL;
}
/*! Translate a Tcl communicator label into the MPI communicator it represents.
* \param label the Tcl name for the communicator
* \return the matching MPI communicator or MPI_COMM_INVALID
*
* This function will search through the linked list of known communicators
* until it finds the (first) match and then returns the string label to
* the calling function. If a NULL is returned, the communicator does not
* yet exist in the linked list.
*/
static MPI_Comm tcl2mpi_comm(const char *label)
{
tclmpi_comm_t *next;
next = first_comm;
while (next) {
if (strcmp(next->label, label) == 0) {
if (next->valid != 0) {
return next->comm;
} else {
return MPI_COMM_INVALID;
}
} else {
next = next->next;
}
}
return MPI_COMM_INVALID;
}
/*! Add an MPI communicator to the linked list of communicators, if needed.
* \param comm an MPI communicator
* \return the corresponding string label or NULL.
*
* This function will first call mpi2tcl_comm in order to see, if the
* communicator handed in, is already listed and return that communicators
* Tcl label string. If it is not yet lists, a new entry is added to the
* linked list and a new label of the format "tclmpi::comm%d" assigned.
* The (global/static) variable tclmpi_comm_cntr is incremented every time
* to make the communicator label unique.
*/
static const char *tclmpi_add_comm(MPI_Comm comm)
{
tclmpi_comm_t *next;
char *label;
const char *oldlabel;
oldlabel = mpi2tcl_comm(comm);
if (oldlabel != NULL) return oldlabel;
next = (tclmpi_comm_t *)Tcl_Alloc(sizeof(tclmpi_comm_t));
next->next = NULL;
next->comm = comm;
next->valid = 1;
label = (char *)Tcl_Alloc(TCLMPI_LABEL_SIZE);
snprintf(label, TCLMPI_LABEL_SIZE, "tclmpi::comm%d", tclmpi_comm_cntr);
next->label = label;
++tclmpi_comm_cntr;
last_comm->next = next;
last_comm = next;
return next->label;
}
/*! Remove an MPI communicator from the linked list of communicators
* \param label the Tcl name for the communicator
* \return TCL_OK if deletion was successful, else TCL_ERROR
*
* This function will find the entry in the linked list that matches
* the Tcl label string, remove it and free the associated resources.
*/
static int tclmpi_del_comm(const char *label)
{
tclmpi_comm_t *next, *prev;
prev = first_comm;
if (prev->next != NULL)
next = prev->next;
else
return TCL_ERROR;
while (next) {
if (strcmp(label, next->label) == 0) {
prev->next = next->next;
Tcl_Free((char *)next->label);
Tcl_Free((char *)next);
return TCL_OK;
}
prev = next;
next = next->next;
}
return TCL_ERROR;
}
/*! Data type for maxloc/minloc reductions with a double and an integer */
typedef struct tclmpi_dblint tclmpi_dblint_t;
/*! Represent a double/integer pair */
struct tclmpi_dblint {
double d; /*!< double data value */
int i; /*!< location data */
};
/*! Data type for maxloc/minloc reductions with two integers */
typedef struct tclmpi_intint tclmpi_intint_t;
/*! Represent an integer/integer pair */
struct tclmpi_intint {
int i1; /*!< integer data value */
int i2; /*!< location data */
};
/* some symbolic constants. some have multiple uses. */
#define TCLMPI_TOZERO -4 /*!< convert problematic data items to zero */
#define TCLMPI_ABORT -3 /*!< abort on problems */
#define TCLMPI_ERROR -2 /*!< flag problems as Tcl errors */
#define TCLMPI_INVALID -1 /*!< not ready to handle data */
#define TCLMPI_NONE 0 /*!< no data type assigned */
#define TCLMPI_AUTO 1 /*!< the tcl native data type (string) */
#define TCLMPI_INT 2 /*!< data type for integers */
#define TCLMPI_INT_INT 3 /*!< data type for pairs of integers */
#define TCLMPI_DOUBLE 4 /*!< floating point data type */
#define TCLMPI_DOUBLE_INT 5 /*!< data type for double/integer pair */
/*! Translate TclMPI strings to MPI constants for reductions
* \param opstr string constant describing the operator
* \param op pointer to location for storing the MPI constant
* \return TCL_OK if the string was recognized else TCL_ERROR
*
* This is a convenience function to consistently convert
* TclMPI string constants representing reduction operators
* to their corresponding MPI counterparts.
*/
static int tclmpi_get_op(const char *opstr, MPI_Op *op)
{
if (op == NULL) return TCL_ERROR;
if (strcmp(opstr, "tclmpi::max") == 0)
*op = MPI_MAX;
else if (strcmp(opstr, "tclmpi::min") == 0)
*op = MPI_MIN;
else if (strcmp(opstr, "tclmpi::sum") == 0)
*op = MPI_SUM;
else if (strcmp(opstr, "tclmpi::prod") == 0)
*op = MPI_PROD;
else if (strcmp(opstr, "tclmpi::land") == 0)
*op = MPI_LAND;
else if (strcmp(opstr, "tclmpi::band") == 0)
*op = MPI_BAND;
else if (strcmp(opstr, "tclmpi::lor") == 0)
*op = MPI_LOR;
else if (strcmp(opstr, "tclmpi::bor") == 0)
*op = MPI_BOR;
else if (strcmp(opstr, "tclmpi::lxor") == 0)
*op = MPI_LXOR;
else if (strcmp(opstr, "tclmpi::bxor") == 0)
*op = MPI_BXOR;
else if (strcmp(opstr, "tclmpi::maxloc") == 0)
*op = MPI_MAXLOC;
else if (strcmp(opstr, "tclmpi::minloc") == 0)
*op = MPI_MINLOC;
else
return TCL_ERROR;
return TCL_OK;
}
/* translate MPI requests to Tcl strings and back "tclmpi::req%d" */
/*! Linked list entry type for managing MPI requests */
typedef struct tclmpi_req tclmpi_req_t;
/*! Linked list entry to map MPI requests to "tclmpi::req%d" strings. */
struct tclmpi_req {
const char *label; /*!< identifier of this request */
void *data; /*!< pointer to send or receive data buffer */
int len; /*!< size of data block */
int type; /*!< data type of send data */
int source; /*!< source rank of non-blocking receive */
int tag; /*!< tag selector of non-blocking receive */
MPI_Request *req; /*!< pointer MPI request handle generated by MPI */
MPI_Comm comm; /*!< communicator for non-blocking receive */
tclmpi_req_t *next; /*!< pointer to next struct */
};
/*! First element of the list of generated requests */
static tclmpi_req_t *first_req = NULL;
/*! Request counter. Incremented to get unique strings */
static int tclmpi_req_cntr = 0;
/*! Selects what to do when a data element in a list cannot
* be successfully converted to the desired data type.
* Default is to throw a Tcl error. */
static int tclmpi_conv_handler = TCLMPI_ERROR;
/*! Data conversion with with error handling
* \param type Tcl data type for calling Tcl_Get<Type>FromObj()
* \param in pointer to input object for conversion
* \param out pointer to output storage for conversion
* \param assign target to assign a zero to for TCLMPI_TOZERO
*
* This macro enables consistent handling of data conversions.
* It also queries the tclmpi_conv_handler variable to jump to
* the selected conversion error behavior. For TCLMPI_ERROR
* (the default) a Tcl error is raised and TclMPI returns to
* the calling function. For TCLMPI_ABORT and error message
* is written to stderr and parallel execution on the current
* communicator is terminated via MPI_Abort(). For TCLMPI_TOZERO
* the error is silently ignored and the data element handed
* in as assign parameter is set to zero. */
#define TCLMPI_CONV_CHECK(type, in, out, assign) \
if (Tcl_Get##type##FromObj(interp, in, out) != TCL_OK) { \
if (tclmpi_conv_handler == TCLMPI_TOZERO) { \
Tcl_ResetResult(interp); \
assign = 0; \
} else if (tclmpi_conv_handler == TCLMPI_ABORT) { \
fprintf(stderr, "Error on data element %d: %s\n", i, Tcl_GetStringResult(interp)); \
MPI_Abort(comm, i); \
} else { \
return TCL_ERROR; \
} \
}
/*! Allocate and add an entry to the request map linked list
* \return the corresponding string label or NULL.
*
* This function will allocate and initialize a new linked list entry
* for the translation between MPI requests and their string
* representation passed to Tcl scripts. The assigned label of the
* for "tclmpi::req%d" will be returned. The (global/static) variable
* tclmpi_req_cntr is incremented every time to make the communicator
* label unique.
*/
static const char *tclmpi_add_req()
{
tclmpi_req_t *next;
char *label;
next = (tclmpi_req_t *)Tcl_Alloc(sizeof(tclmpi_req_t));
if (next == NULL) return NULL;
memset(next, 0, sizeof(tclmpi_req_t));
next->req = (MPI_Request *)Tcl_Alloc(sizeof(MPI_Request));
if (next->req == NULL) {
Tcl_Free((char *)next);
return NULL;
}
label = (char *)Tcl_Alloc(TCLMPI_LABEL_SIZE);
if (label == NULL) {
Tcl_Free((char *)next->req);
Tcl_Free((char *)next);
return NULL;
}
snprintf(label, TCLMPI_LABEL_SIZE, "tclmpi::req%d", tclmpi_req_cntr);
next->label = label;
next->type = TCLMPI_NONE;
next->len = TCLMPI_INVALID;
++tclmpi_req_cntr;
if (first_req == NULL) {
first_req = next;
} else {
tclmpi_req_t *req;
req = first_req;
while (req->next) req = req->next;
req->next = next;
}
return next->label;
}
/*! translate Tcl representation of an MPI request to request itself.
* \param label the Tcl name for the communicator
* \return a pointer to the matching tclmpi_req_t structure
*
* This function will search through the linked list of known MPI requests
* until it finds the (first) match and then returns a pointer to this data.
* If NULL is returned, the communicator does not exist in the linked list.
*/
static tclmpi_req_t *tclmpi_find_req(const char *label)
{
tclmpi_req_t *req;
req = first_req;
while (req) {
if (strcmp(req->label, label) == 0)
return req;
else
req = req->next;
}
return NULL;
}
/*! remove tclmpi_req_t entry from the request linked list
* \param req a pointer to the request in question
* \return TCL_OK on succes, TCL_ERROR on failure
*
* This function will search through the linked list of known MPI requests
* until it finds the (first) match and then will remove it from the linked
* and free the allocated storage.
* If TCL_ERROR is returned, the request did not exist in the linked list.
*/
static int tclmpi_del_req(tclmpi_req_t *req)
{
if (req == NULL) return TCL_ERROR;
if (req == first_req) {
first_req = req->next;
return TCL_OK;
} else {
tclmpi_req_t *prev = first_req;
while (prev->next) {
if (prev->next == req) {
prev->next = prev->next->next;
Tcl_Free((char *)req->label);
Tcl_Free((char *)req->req);
Tcl_Free((char *)req);
return TCL_OK;
}
prev = prev->next;
}
}
return TCL_ERROR;
}
/*! convert a string describing a data type to a numeric representation */
static int tclmpi_datatype(const char *type)
{
if (strcmp(type, "tclmpi::int") == 0)
return TCLMPI_INT;
else if (strcmp(type, "tclmpi::double") == 0)
return TCLMPI_DOUBLE;
else if (strcmp(type, "tclmpi::dblint") == 0)
return TCLMPI_DOUBLE_INT;
else if (strcmp(type, "tclmpi::intint") == 0)
return TCLMPI_INT_INT;
else if (strcmp(type, "tclmpi::auto") == 0)
return TCLMPI_AUTO;
else
return TCLMPI_NONE;
}
/*! buffer for error messages. */
static char tclmpi_errmsg[MPI_MAX_ERROR_STRING];
/*! convert MPI error code to Tcl error error message and append to result
* \param interp current Tcl interpreter
* \param ierr MPI error number. return value of an MPI call.
* \param obj Tcl object representing the current command name
* \return TCL_OK if the "error" is MPI_SUCCESS or TCL_ERROR
*
* This is a convenience wrapper that will use MPI_Error_string() to
* convert any error code returned from MPI function calls to the
* respective error class and that into a string. This string is
* appended to the Tcl result vector of the current command. Should be
* called after each MPI call. Since we change error handlers on all
* communicators to not result in fatal errors, we have to generate Tcl
* errors instead (which can be caught).
*/
static int tclmpi_errcheck(Tcl_Interp *interp, int ierr, Tcl_Obj *obj)
{
if (ierr != MPI_SUCCESS) {
int len, eclass;
MPI_Error_class(ierr, &eclass);
MPI_Error_string(eclass, tclmpi_errmsg, &len);
Tcl_AppendResult(interp, Tcl_GetString(obj), ": ", tclmpi_errmsg, NULL);
return TCL_ERROR;
} else
return TCL_OK;
}
/*! convenience function to report an unknown communicator as Tcl error
* \param interp current Tcl interpreter
* \param comm MPI communicator
* \param obj0 Tcl object representing the current command name
* \param obj1 Tcl object representing the communicator as Tcl name
* \return TCL_ERROR if the communicator is MPI_COMM_INVALID or TCL_OK
*/
static int tclmpi_commcheck(Tcl_Interp *interp, MPI_Comm comm, Tcl_Obj *obj0, Tcl_Obj *obj1)
{
if (comm == MPI_COMM_INVALID) {
Tcl_AppendResult(interp, Tcl_GetString(obj0), ": unknown communicator: ", Tcl_GetString(obj1), NULL);
return TCL_ERROR;
} else
return TCL_OK;
}
/*! convenience function to report an unknown data type as Tcl error
* \param interp current Tcl interpreter
* \param type TclMPI data type
* \param obj0 Tcl object representing the current command name
* \param obj1 Tcl object representing the data type as Tcl name
* \return TCL_ERROR if the communicator is TCLMPI_NONE or TCL_OK
*/
static int tclmpi_typecheck(Tcl_Interp *interp, int type, Tcl_Obj *obj0, Tcl_Obj *obj1)
{
if (type == TCLMPI_NONE) {
Tcl_AppendResult(interp, Tcl_GetString(obj0), ": invalid data type: ", Tcl_GetString(obj1), NULL);
return TCL_ERROR;
} else
return TCL_OK;
}
/*!
* @}
*/
/*!
* \defgroup wrappers TclMPI wrapper functions
* @{
*/
/*! wrapper for MPI_Initialized()
* \return TCL_OK or TCL_ERROR
*
* This function checks whether the MPI environment has been initialized.
*/
int TclMPI_Initialized(ClientData nodata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
{
Tcl_Obj *result;
int tclmpi_init_done;
if (objc != 1) {
Tcl_WrongNumArgs(interp, 1, objv, NULL);
return TCL_ERROR;
}
MPI_Initialized(&tclmpi_init_done);
result = Tcl_NewIntObj(tclmpi_init_done);
Tcl_SetObjResult(interp, result);
return TCL_OK;
}
/*! wrapper for MPI_Finalized()
* \return TCL_OK or TCL_ERROR
*
* This function checks whether the MPI environment has been shut down.
*/
int TclMPI_Finalized(ClientData nodata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
{
Tcl_Obj *result;
int tclmpi_init_done;
if (objc != 1) {
Tcl_WrongNumArgs(interp, 1, objv, NULL);
return TCL_ERROR;
}
MPI_Finalized(&tclmpi_init_done);
result = Tcl_NewIntObj(tclmpi_init_done);
Tcl_SetObjResult(interp, result);
return TCL_OK;
}
/*! wrapper for MPI_Init()
* \param nodata ignored
* \param interp current Tcl interpreter
* \param objc number of argument objects
* \param objv list of argument object
* \return TCL_OK or TCL_ERROR
*
* This function does a little more work than just calling MPI_Init().
* First of it tries to detect whether MPI_Init() has been called before
* (from Tcl) and then creates a (catchable) Tcl error instead of an
* (uncatchable) MPI error. It will also try to pass the argument vector
* to the script from the Tcl generated 'argv' array to the underlying
* MPI_Init() call and reset argv as needed.
*/
int TclMPI_Init(ClientData nodata, Tcl_Interp *interp, int objc, Tcl_Obj *const objv[])
{
Tcl_Obj *result, *argobj, **args;
int argc, narg, i, ierr, tlevel;
int tclmpi_init_done;
char **argv;
if (objc != 1) {
Tcl_WrongNumArgs(interp, 1, objv, NULL);
return TCL_ERROR;
}
/* convert "command line arguments" back to standard C stuff. */
argobj = Tcl_GetVar2Ex(interp, "argv", NULL, TCL_GLOBAL_ONLY);
Tcl_ListObjGetElements(interp, argobj, &narg, &args);
argv = (char **)Tcl_Alloc((narg + 1) * sizeof(char *));
for (argc = 1; argc <= narg; ++argc) {
Tcl_IncrRefCount(args[argc - 1]);
argv[argc] = Tcl_GetString(args[argc - 1]);
}
argobj = Tcl_GetVar2Ex(interp, "argv0", NULL, TCL_GLOBAL_ONLY);
Tcl_IncrRefCount(argobj);
argv[0] = Tcl_GetString(argobj);
MPI_Initialized(&tclmpi_init_done);
if (tclmpi_init_done != 0) {
Tcl_AppendResult(interp, "Calling ", Tcl_GetString(objv[0]), " multiple times is erroneous.", NULL);
return TCL_ERROR;
}
ierr = MPI_Init_thread(&argc, &argv, MPI_THREAD_SINGLE, &tlevel);
if (tclmpi_errcheck(interp, ierr, objv[0]) != TCL_OK) return TCL_ERROR;
/* change default error handler, so we can convert
MPI errors into 'catch'able Tcl errors */
MPI_Comm_set_errhandler(MPI_COMM_WORLD, MPI_ERRORS_RETURN);
/* build new argv list */
result = Tcl_NewListObj(0, NULL);
for (i = 1; i < argc; ++i) { Tcl_ListObjAppendElement(interp, result, Tcl_NewStringObj(argv[i], -1)); }
for (i = 0; i < narg; ++i) Tcl_DecrRefCount(args[i]);