-
Notifications
You must be signed in to change notification settings - Fork 5
/
codegen_c_udgram.py
1427 lines (1335 loc) · 69.2 KB
/
codegen_c_udgram.py
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
########################################################################
#
# Code generation module for the coNCePTuaL language:
# C + Unix-domain (i.e., local) sockets
#
# By Scott Pakin <[email protected]>
#
# ----------------------------------------------------------------------
#
#
# Copyright (C) 2003, Triad National Security, LLC
# All rights reserved.
#
# Copyright (2003). Triad National Security, LLC. This software
# was produced under U.S. Government contract 89233218CNA000001 for
# Los Alamos National Laboratory (LANL), which is operated by Los
# Alamos National Security, LLC (Triad) for the U.S. Department
# of Energy. The U.S. Government has rights to use, reproduce,
# and distribute this software. NEITHER THE GOVERNMENT NOR TRIAD
# MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY
# FOR THE USE OF THIS SOFTWARE. If software is modified to produce
# derivative works, such modified software should be clearly marked,
# so as not to confuse it with the version available from LANL.
#
# Additionally, 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 Triad National Security, LLC, Los Alamos
# National Laboratory, the U.S. Government, 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 TRIAD 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 TRIAD OR CONTRIBUTORS 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.
#
#
########################################################################
import codegen_c_generic
from ncptl_config import ncptl_config
class NCPTL_CodeGen(codegen_c_generic.NCPTL_CodeGen):
def __init__(self, options=None):
"Initialize the C + Unix sockets code generation module."
codegen_c_generic.NCPTL_CodeGen.__init__(self, options)
self.backend_name = "c_udgram"
self.backend_desc = "C + Unix-domain datagram sockets"
# Add a command-line option to the generated code to enable a
# user to specify the number of tasks.
self.base_global_parameters.append(("NCPTL_TYPE_INT",
"var_num_tasks",
"tasks",
"T",
"Number of tasks to use",
"1"))
# We don't have our own command-line options but we handle
# --help, nevertheless.
for arg in range(0, len(options)):
if options[arg] == "--help":
# Output a help message.
self.show_help()
raise SystemExit, 0
# ---------------------------- #
# Backend-specific helper code #
# ---------------------------- #
def code_reject_nonzero_tag(self, struct, statement):
"Check for a nonzero tag and abort if one is found."
return ["if (%s.tag != 0%s)" % (struct, self.ncptl_int_suffix),
'ncptl_fatal ("The %s backend does not support nonzero tags in %s statements");' % (self.backend_name, statement)]
# ----------- #
# Header code #
# ----------- #
def code_specify_include_files_POST(self, localvars):
"Specify extra header files needed by the c_udgram backend."
includefiles = [
"#include <errno.h>",
"#include <signal.h>",
"#include <sys/socket.h>",
"#include <sys/un.h>",
"#include <sys/ioctl.h>",
"#include <sys/wait.h>"]
if ncptl_config.has_key("HAVE_SYS_SELECT_H"):
self.push("#include <sys/select.h>", includefiles)
return includefiles
def code_define_macros_POST(self, localvars):
"Define some macros to simplify the generated C code."
# Define a filename template to use for our sockets.
definition = [
"/* Define a filename template for this program's sockets. */",
'#define SOCKET_TEMPLATE "c_udgram_XXXXXX"',
""]
# Define a CONC_SYSTEM_ERROR macro that invokes ncptl_fatal()
# with a description or the number of the most recent system
# error. We use strerror() if configure detected it.
# Otherwise, we use sys_errlist[] if configure detected that.
# Otherwise, we simply use errno.
definition.extend([
'/* Define a wrapper for ncptl_fatal() after a system call failure. */',
'#define CONC_SYSTEM_ERROR(MSG) \\',
' do { \\'])
if ncptl_config.has_key("HAVE_STRERROR"):
definition.extend([
' if (strerror(errno)) \\',
' ncptl_fatal (MSG " (%s, errno=%d)", strerror(errno), errno); \\',
' else \\',
' ncptl_fatal (MSG " (errno=%d)", errno); \\'])
elif ncptl_config.has_key("HAVE_DECL_SYS_ERRLIST"):
definition.extend([
' if (errno < sys_nerr) \\',
' ncptl_fatal (MSG " (%s)", sys_errlist[errno]); \\',
' else \\',
' ncptl_fatal (MSG " (errno=%d)", errno); \\'])
else:
definition.extend([
' ncptl_fatal (MSG " (errno=%d)", errno); \\'])
definition.extend([
' } \\',
' while (0)',
''])
# Define a CONC_SET_BLOCKING macro that sets a socket to
# either blocking or nonblocking, as desired.
definition.extend([
"/* Define a macro that sets or resets a socket's blocking state. */",
'#define CONC_SET_BLOCKING(CSTATE, PEER, BLOCKING) \\',
' do { \\',
' int nonblocking = 1 - (BLOCKING); \\',
' if (ioctl ((CSTATE)->channels[PEER], FIONBIO, &nonblocking) == -1) \\',
' CONC_SYSTEM_ERROR ("Failed to toggle a socket\'s blocking state"); \\',
' } \\',
' while (0)'])
return definition
def code_declare_datatypes_POST(self, localvars):
"Declare additional types needed by the c_udgram backend."
newtypes = []
self.pushmany([
"/* Declare a type that encapsulates much of the communication state. */",
"typedef struct {"],
stack=newtypes)
self.code_declare_var(type="int *", name="channels",
comment="Socket connections to each other task",
stack=newtypes)
self.code_declare_var(type="NCPTL_QUEUE **", name="blockedsendQ",
comment="Queue of events corresponding to blocked sends to each destination",
stack=newtypes)
self.code_declare_var(type="NCPTL_QUEUE **", name="blockedrecvQ",
comment="Queue of events corresponding to blocked receives from each source",
stack=newtypes)
self.code_declare_var(type="int", name="sendsblocked",
comment="0=all blockedsendQ[] are empty; 1=nonempty",
stack=newtypes)
self.code_declare_var(type="int", name="recvsblocked",
comment="0=all blockedrecvQ[] are empty; 1=nonempty",
stack=newtypes)
self.pushmany([
"} COMMSTATE;",
"",
"/* Create symbolic names for each set of communication state we plan to use. */",
"typedef enum {",
"COMMSTATE_PT2PT, /* State for point-to-point communication */",
"COMMSTATE_COLL, /* State for collective communication */",
"NUMCHANNELSETS /* Sentinel describing the number of entries in COMMSTATE_TYPES */",
"} COMMSTATE_TYPES;"],
newtypes)
return newtypes
def code_declare_globals_EXTRA(self, localvars):
"Declare additional C global variables needed by the c_udgram backend."
newvars = []
self.code_declare_var(type="COMMSTATE", name="commstate",
arraysize="NUMCHANNELSETS",
comment="Communication state for multiple independent channels",
stack=newvars)
self.code_declare_var(type="int", name="abnormal_exit", rhs="1",
comment="1=exit handler invoked after an abnormal exit; 0=invoked after a normal one",
stack=newvars)
self.code_declare_var(name="maxpacketlen",
comment="Maximum message length that can be transmitted whole",
stack=newvars)
self.code_declare_var(type="NCPTL_QUEUE *", name="alltasksQ",
comment="List of 0, ..., var_num_tasks-1 for all-task synchronization",
stack=newvars)
# Make all declarations static.
static_newvars = []
for var in newvars:
static_newvars.append("static " + var)
return static_newvars
def code_def_init_decls_POST(self, localvars):
"""
Declare C variables needed by code_define_functions_INIT_COMM_3,
code_def_init_msg_mem_PRE, and code_def_init_misc_EXTRA.
"""
newvars = []
self.code_declare_var(type="int", name="cset",
comment="Index into commstate[]",
stack=newvars)
self.code_declare_var(name="taskID", comment="Loop over all task IDs",
stack=newvars)
self.code_declare_var(type="struct sockaddr_un ***", name="socketinfo",
comment="Socket information (e.g., filename) for every socket in channels[][][]",
stack=newvars)
self.code_declare_var(type="char", name="maxpacketlen_str",
arraysize="50", comment="String equivalent of maxpacketlen",
stack=newvars)
return newvars
# --------------------------- #
# Helper-function definitions #
# --------------------------- #
def code_define_functions_PRE(self, localvars):
"Define some point-to-point and collective communication functions."
msgfuncs = []
uses_send = self.events_used.has_key("EV_SEND")
uses_asend = self.events_used.has_key("EV_ASEND")
uses_recv = self.events_used.has_key("EV_RECV")
uses_arecv = self.events_used.has_key("EV_ARECV")
uses_sync = self.events_used.has_key("EV_SYNC")
uses_mcast = self.events_used.has_key("EV_MCAST")
uses_wait = self.events_used.has_key("EV_WAIT")
uses_etime = self.events_used.has_key("EV_ETIME")
uses_reduce = self.events_used.has_key("EV_REDUCE")
# State all function dependencies.
uses_sync = 1 # Currently required by conc_finalize().
if uses_etime:
uses_send = 1
uses_recv = 1
if uses_sync or uses_mcast:
uses_asend = 1
uses_recv = 1
uses_wait = 1
if uses_reduce:
uses_send = 1
uses_arecv = 1
uses_wait = 1
# Define a wrapper for send() with automatic error checking. */
self.pushmany([
"/* Attempt to send data. Abort on error. Return 1 on success,",
" * 0 if the send blocked. */",
"static inline int conc_send_packet (COMMSTATE *cstate, int dest, void *buffer, int packetsize)",
"{"],
stack=msgfuncs)
self.code_declare_var(type="int", name="bytessent",
comment="Number of bytes actually sent",
stack=msgfuncs)
self.pushmany([
"do",
"bytessent = send (cstate->channels[dest], buffer, (size_t) packetsize, 0);",
"while (bytessent == -1 && errno == EINTR);",
"if (bytessent == -1)",
"if (errno == EAGAIN)",
"return 0; /* send() blocked. */",
"else",
'CONC_SYSTEM_ERROR ("Failed to send a message");',
"else",
" /* send() did not block. */",
"if (bytessent != packetsize)",
'ncptl_fatal ("Expected to send %d bytes but actually sent %d bytes",',
"packetsize, bytessent);",
"return 1;",
"}",
""],
stack=msgfuncs)
# Define a wrapper for recv() with automatic error checking.
self.pushmany([
"/* Attempt to send data. Abort on error. Return 1 on success,",
" * 0 if the send blocked. */",
"static inline int conc_receive_packet (COMMSTATE *cstate, int source, void *buffer, int packetsize)",
"{"],
stack=msgfuncs)
self.code_declare_var(type="int", name="bytesreceived",
comment="Number of bytes actually received",
stack=msgfuncs)
self.pushmany([
"do",
"bytesreceived = recv (cstate->channels[source],",
"buffer, packetsize, MSG_WAITALL|MSG_TRUNC);",
"while (bytesreceived == -1 && errno == EINTR);",
"if (bytesreceived == -1)",
"if (errno == EAGAIN)",
"return 0; /* recv() blocked. */",
"else",
'CONC_SYSTEM_ERROR ("Failed to receive a message");',
"else",
" /* recv() did not block. */",
"if (bytesreceived != packetsize)",
'ncptl_fatal ("Expected to receive %d bytes but actually received %d bytes",',
"packetsize, bytesreceived);",
"return 1;",
"}",
""],
stack=msgfuncs)
# Define a function that determines the maximum socket size.
self.pushmany([
"/* Binary search for the largest valid packet length. */",
"static ncptl_int conc_find_max_packet_len (COMMSTATE *cstate)",
"{",],
stack=msgfuncs)
self.code_declare_var(type="int", name="maxsize",
comment="Maximum valid message size",
stack=msgfuncs)
self.code_declare_var(type="int", name="delta",
comment="Change in message size to try next",
stack=msgfuncs)
self.code_declare_var(type="socklen_t", name="intsize", rhs="sizeof(int)",
comment="Number of bytes in maxsize",
stack=msgfuncs)
self.code_declare_var(type="char *", name="msgbuffer",
comment="Buffer used for sending and receiving",
stack=msgfuncs)
self.code_declare_var(type="int", name="bytessent",
comment="Number of bytes actually sent",
stack=msgfuncs)
self.code_declare_var(type="int", name="bytesreceived",
comment="Number of bytes actually received",
stack=msgfuncs)
self.pushmany([
"CONC_SET_BLOCKING (cstate, physrank, 1);",
"if (getsockopt (cstate->channels[physrank], SOL_SOCKET, SO_SNDBUF, &maxsize, &intsize) == -1 ||",
"!maxsize)",
'CONC_SYSTEM_ERROR ("Failed to get a socket parameter");',
"msgbuffer = (char *) ncptl_malloc (maxsize, 0);",
"",
"for (delta=maxsize/2; delta; delta/=2) {",
"do",
"bytessent =",
"send (cstate->channels[physrank], msgbuffer, (size_t) maxsize, 0);",
"while (bytessent == -1 && errno == EINTR);",
"if (bytessent != -1) {",
"do",
"bytesreceived = recv (cstate->channels[physrank], msgbuffer,",
"(size_t) maxsize, MSG_WAITALL | MSG_TRUNC);",
"while (bytesreceived == -1 && errno == EINTR);",
"if (bytesreceived != (int) maxsize)",
'ncptl_fatal ("Expected to receive %d bytes but actually received %d bytes",',
"maxsize, bytesreceived);",
"maxsize += delta;",
"}",
"else",
"maxsize -= delta;",
"}",
"ncptl_free (msgbuffer);",
"CONC_SET_BLOCKING (cstate, physrank, 0);",
"return (maxsize/sizeof(ncptl_int))*sizeof(ncptl_int) - 1;",
"}"],
stack=msgfuncs)
# Define a wait-one function.
if uses_wait:
self.pushmany([
" /* Wait until a specific send/receive request completes.",
" * ASSUMPTION: target_req has not yet completed. */",
"static inline void conc_wait_one (COMMSTATE *cstate, void *target_req)",
"{"],
stack=msgfuncs)
self.code_declare_var(type="struct timeval", name="polltime",
comment="Time structure corresponding to a minimal poll time",
stack=msgfuncs)
self.pushmany([
"",
" /* Alternately complete receives and sends until target_req",
" * is satisfied. */",
"while (1) {"],
stack=msgfuncs)
self.code_declare_var(name="task_ofs",
comment="Offset from our task ID",
stack=msgfuncs)
self.pushmany([
"",
" /* Process each task ID in turn, starting from our own. */",
"for (task_ofs=0; task_ofs<var_num_tasks; task_ofs++) {"],
stack=msgfuncs)
for type, name, rhs, comment in [
("ncptl_int", "taskID", "(physrank+task_ofs) % var_num_tasks", "Task ID to process"),
("ncptl_int", "pendingsends", "ncptl_queue_length (cstate->blockedsendQ[taskID])", "Number of blocked sends"),
("ncptl_int", "pendingrecvs", "ncptl_queue_length (cstate->blockedrecvQ[taskID])", "Number of blocked receives"),
("int", "making_progress", None, "1=a packet was sent/received; 0=we idled")]:
self.code_declare_var(type=type, name=name, rhs=rhs,
comment=comment, stack=msgfuncs)
self.pushmany([
"",
" /* Keep sending from task taskID and/or receiving from task",
" * taskID until we can no longer do so. */",
"making_progress = pendingrecvs || pendingsends;",
"while (making_progress) {"],
stack=msgfuncs)
for type, name, rhs, comment in [
("int", "recvfd", "0", "File descriptor for a receive channel"),
("int", "sendfd", "0", "File descriptor for a send channel"),
("fd_set", "firstrecv", None, "Set containing either recvfd or nothing"),
("fd_set", "firstsend", None, "Set containing either sendfd or nothing"),
("int", "last_fd", "-1", "1 + highest-numbered descriptor on which to select()"),
("CONC_RECV_EVENT *", "recvev", "NULL", "List of blockedrecvQ's contents"),
("CONC_SEND_EVENT *", "sendev", "NULL", "List of blockedsendQ's contents"),
("int", "recv_available", None, "1=recv() won't block; 0=it will"),
("int", "send_available", None, "1=send() won't block; 0=it will")]:
self.code_declare_var(type=type, name=name, rhs=rhs,
comment=comment, stack=msgfuncs)
self.pushmany([
"",
"FD_ZERO (&firstrecv);",
"if (pendingrecvs) {",
"recvev = ncptl_queue_contents (cstate->blockedrecvQ[taskID], 0);",
"recvfd = cstate->channels[recvev->source];",
"FD_SET(recvfd, &firstrecv);",
"last_fd = recvfd>last_fd ? recvfd : last_fd;",
"}",
"FD_ZERO (&firstsend);",
"if (pendingsends) {",
"sendev = ncptl_queue_contents (cstate->blockedsendQ[taskID], 0);",
"sendfd = cstate->channels[sendev->dest];",
"FD_SET(sendfd, &firstsend);",
"last_fd = sendfd>last_fd ? sendfd : last_fd;",
"}",
"polltime.tv_sec = 0;",
"polltime.tv_usec = 1; /* Setting to 0 tends to hog the CPU. */",
"select (last_fd+1, &firstrecv, &firstsend, NULL, &polltime);",
"send_available = sendfd && FD_ISSET(sendfd, &firstsend);",
"recv_available = recvfd && FD_ISSET(recvfd, &firstrecv);",
"if (!send_available && !recv_available)",
" /* Give up if we're blocked on both the send and receive sides. */",
"break;",
"making_progress = 0; /* Assume no progress. */",
"",
" /* Process a pending receive, if any. */",
"if (pendingrecvs && recv_available) {"],
stack=msgfuncs)
self.code_declare_var(type="int", name="packetsize",
rhs="(int) (recvev->size>maxpacketlen ? maxpacketlen : recvev->size)",
comment="Number of bytes to receive per call",
stack=msgfuncs)
self.pushmany([
"",
"if (conc_receive_packet (cstate, recvev->source, recvev->buffer, packetsize)) {",
" /* The receive went through. */",
"making_progress = 1;",
"recvev->buffer = (void *) ((char *)recvev->buffer + packetsize);",
"recvev->size -= packetsize;",
"if (!recvev->size) {",
" /* We received a complete message. */",
"(void) ncptl_queue_pop (cstate->blockedrecvQ[taskID]);",
"if (!--pendingrecvs)",
"ncptl_queue_empty (cstate->blockedrecvQ[taskID]);",
"if (recvev == target_req)",
" /* We finished the one message we care about. */",
"return;",
"}",
"}",
"}",
"",
" /* Process a pending send, if any. */",
"if (pendingsends && send_available) {",
"int packetsize = (int) (sendev->size>maxpacketlen ? maxpacketlen : sendev->size); /* Number of bytes to send per call */",
"if (conc_send_packet (cstate, sendev->dest, sendev->buffer, packetsize)) {",
" /* The send went through. */",
"making_progress = 1;",
"sendev->buffer = (void *) ((char *) sendev->buffer + packetsize);",
"sendev->size -= packetsize;",
"if (!sendev->size) {",
" /* We sent a complete message. */",
"(void) ncptl_queue_pop (cstate->blockedsendQ[taskID]);",
"if (!--pendingsends)",
"ncptl_queue_empty (cstate->blockedsendQ[taskID]);",
"if (sendev == target_req)",
" /* We finished the one message we care about. */",
"return;",
"}",
"}",
"}",
"}",
"}",
"}",
"}"],
stack=msgfuncs)
# Define a wait-all function.
if uses_wait:
self.pushmany([
"/* Wait until all of our blocked sends and receives complete. */",
"static inline void conc_wait_all (COMMSTATE *cstate)",
"{"],
stack=msgfuncs)
self.code_declare_var(name="taskID", comment="Loop over all task IDs",
stack=msgfuncs)
self.pushmany([
"",
" /* Ensure we have something to do. */",
"if (!cstate->sendsblocked && !cstate->recvsblocked)",
"return;",
"",
" /* Await completion from each task in turn -- not very efficient",
" * but we expect var_num_tasks to be small. */",
"for (taskID=0; taskID<var_num_tasks; taskID++) {"],
stack=msgfuncs)
self.code_declare_var(name="pendingsends", comment="Number of blocked sends",
stack=msgfuncs)
self.code_declare_var(name="pendingrecvs", comment="Number of blocked receives",
stack=msgfuncs)
self.pushmany([
"",
" /* Wait for the final send to complete. */",
"pendingsends = ncptl_queue_length (cstate->blockedsendQ[taskID]);",
"if (pendingsends) {"],
stack=msgfuncs)
self.code_declare_var(type="CONC_SEND_EVENT *", name="lastsend",
comment="Task taskID's final pending send",
stack=msgfuncs)
self.pushmany([
"",
"lastsend = (CONC_SEND_EVENT *) ncptl_queue_contents (cstate->blockedsendQ[taskID], 0);",
"lastsend += pendingsends - 1;",
"conc_wait_one (cstate, (void *) lastsend);",
"}",
"",
" /* Wait for the final receive to complete. */",
"pendingrecvs = ncptl_queue_length (cstate->blockedrecvQ[taskID]);",
"if (pendingrecvs) {"],
stack=msgfuncs)
self.code_declare_var(type="CONC_RECV_EVENT *", name="lastrecv",
comment="Task taskID's final pending receive",
stack=msgfuncs)
self.pushmany([
"",
"lastrecv = (CONC_RECV_EVENT *) ncptl_queue_contents (cstate->blockedrecvQ[taskID], 0);",
"lastrecv += pendingrecvs - 1;",
"conc_wait_one (cstate, (void *) lastrecv); /* Wait for the final receive */",
"}",
"}",
"",
" /* Enable send/receive functions to proceed. */",
"cstate->sendsblocked = 0;",
"cstate->recvsblocked = 0;",
"}"],
stack=msgfuncs)
# Define a synchronous send function.
if uses_send:
self.pushmany([
"/* Enqueue a message on a given channel and block until it completes. */",
"static inline void conc_send_msg (COMMSTATE *cstate, CONC_SEND_EVENT *sendev)",
"{"],
stack=msgfuncs)
self.code_declare_var(type="CONC_SEND_EVENT *", name="sendev_copy",
comment="Mutable copy of sendev",
stack=msgfuncs)
self.pushmany([
"cstate->sendsblocked = 1;",
"sendev_copy = (CONC_SEND_EVENT *) ncptl_queue_push (cstate->blockedsendQ[sendev->dest], (void *) sendev);",
"sendev_copy->buffer = (void *) ((char *)sendev_copy->buffer + sendev_copy->bufferofs);",
"conc_wait_one (cstate, sendev_copy);",
"}"],
stack=msgfuncs)
# Define a synchronous receive function.
if uses_recv:
self.pushmany([
"/* Post a receive and block until it completes. */",
"static inline void conc_recv_msg (COMMSTATE *cstate, CONC_RECV_EVENT *recvev)",
"{"],
stack=msgfuncs)
self.code_declare_var(type="CONC_RECV_EVENT *", name="recvev_copy",
comment="Mutable copy of recvev",
stack=msgfuncs)
self.pushmany([
"cstate->recvsblocked = 1;",
"recvev_copy = (CONC_RECV_EVENT *) ncptl_queue_push (cstate->blockedrecvQ[recvev->source], (void *) recvev);",
"recvev_copy->buffer = (void *) ((char *)recvev_copy->buffer + recvev_copy->bufferofs);",
"conc_wait_one (cstate, recvev_copy);",
"}"],
stack=msgfuncs)
# Define an asynchronous send function.
if uses_asend:
self.pushmany([
"/* Enqueue a message on a given channel (nonblocking). */",
"static inline void conc_asend_msg (COMMSTATE *cstate, CONC_SEND_EVENT *sendev)",
"{"],
stack=msgfuncs)
self.code_declare_var(type="CONC_SEND_EVENT *", name="sendev_copy",
comment="Mutable copy of sendev",
stack=msgfuncs)
self.pushmany([
"cstate->sendsblocked = 1;",
"sendev_copy = (CONC_SEND_EVENT *) ncptl_queue_push (cstate->blockedsendQ[sendev->dest], (void *) sendev);",
"sendev_copy->buffer = (void *) ((char *)sendev_copy->buffer + sendev_copy->bufferofs);",
"}"],
stack=msgfuncs)
# Define an asynchronous receive function.
if uses_arecv:
self.pushmany([
"/* Enqueue a receive request on a given channel (nonblocking). */",
"static inline void conc_arecv_msg (COMMSTATE *cstate, CONC_RECV_EVENT *recvev)",
"{"],
stack=msgfuncs)
self.code_declare_var(type="CONC_RECV_EVENT *", name="recvev_copy",
comment="Mutable copy of recvev",
stack=msgfuncs)
self.pushmany([
"cstate->recvsblocked = 1;",
"recvev_copy = (CONC_RECV_EVENT *) ncptl_queue_push (cstate->blockedrecvQ[recvev->source], (void *) recvev);",
"recvev_copy->buffer = (void *) ((char *)recvev_copy->buffer + recvev_copy->bufferofs);",
"}"],
stack=msgfuncs)
# Define a synchronization function.
if uses_sync:
self.pushmany([
"/* Barrier-synchronize a list of tasks using a butterfly pattern. */",
"static inline void conc_synchronize (COMMSTATE *cstate, int *peerlist, ncptl_int maxrank, ncptl_int syncrank)",
"{"],
stack=msgfuncs)
for type, name, comment in [
("ncptl_int", "stage", "Current stage of the butterfly pattern"),
("CONC_SEND_EVENT", "sendev", "Send event to pass to conc_asend_msg()"),
("CONC_RECV_EVENT", "recvev", "Receive event to pass to conc_recv_msg()"),
("ncptl_int", "dummybuffer", "Dummy message buffer")]:
self.code_declare_var(type=type, name=name, comment=comment,
stack=msgfuncs)
# For each peer with a Hamming distance of 1 from us,
# perform a nonblocking send followed by a blocking
# receive.
self.pushmany([
"",
"memset ((void *)&sendev, 0, sizeof(CONC_SEND_EVENT));",
"memset ((void *)&recvev, 0, sizeof(CONC_RECV_EVENT));",
"for (stage=ncptl_func_bits(maxrank)-1; stage>=0; stage--) {"],
stack=msgfuncs)
self.code_declare_var(name="peernum",
rhs="syncrank ^ (1<<stage)",
comment="Offset into peerlist[] of our current peer",
stack=msgfuncs)
self.pushmany([
"if (peernum <= maxrank) {",
"sendev.dest = peerlist[peernum];",
"sendev.buffer = (void *) &dummybuffer;",
"conc_asend_msg (cstate, &sendev);",
"recvev.source = peerlist[peernum];",
"recvev.buffer = (void *) &dummybuffer;",
"conc_recv_msg (cstate, &recvev);",
"conc_wait_all (cstate);",
"}",
"}",
"}"],
stack=msgfuncs)
# Define a multicast function.
if uses_mcast:
self.pushmany([
"/* Multicast data from a single source to a set of destinations. */",
"static void conc_multicast (COMMSTATE *cstate, CONC_MCAST_EVENT *mcast_ev)",
"{"],
stack=msgfuncs)
self.code_declare_var(name="mcastrank",
rhs="mcast_ev->mcastrank",
comment="This task's rank in the multicast",
stack=msgfuncs)
self.code_declare_var(type="int *", name="peerlist",
rhs="(int *) ncptl_queue_contents(mcast_ev->peerqueue, 0)",
comment="List of our peers' physical task numbers",
stack=msgfuncs)
self.code_declare_var(name="maxrank",
rhs="ncptl_queue_length(mcast_ev->peerqueue) - 1",
comment="Number of tasks involved in the multicast",
stack=msgfuncs)
self.code_declare_var(type="CONC_SEND_EVENT", name="sendev",
comment="Send event to pass to conc_asend_msg()",
stack=msgfuncs)
self.code_declare_var(type="CONC_RECV_EVENT", name="recvev",
comment="Receive event to pass to conc_recv_msg()",
stack=msgfuncs)
self.pushmany([
"",
" /* Multicast data in a binary-tree pattern. */",
"memset ((void *)&sendev, 0, sizeof(CONC_SEND_EVENT));",
"sendev.size = mcast_ev->size;"],
stack=msgfuncs)
for field in ["alignment", "buffernum", "bufferofs", "misaligned",
"touching", "verification", "buffer"]:
self.push("sendev.%s = mcast_ev->%s;" % (field, field), msgfuncs)
self.pushmany([
"memset ((void *)&recvev, 0, sizeof(CONC_RECV_EVENT));",
"recvev.size = mcast_ev->size;"],
stack=msgfuncs)
for field in ["alignment", "buffernum", "bufferofs", "misaligned",
"touching", "verification", "buffer"]:
self.push("recvev.%s = mcast_ev->%s;" % (field, field), msgfuncs)
self.pushmany([
"if (mcastrank > 0) {",
" /* Receive synchronously from our parent. */",
"recvev.source = peerlist[(mcastrank-1)/2];",
"conc_recv_msg (cstate, &recvev);",
"}",
"if ((mcastrank+1)*2-1 <= maxrank) {",
" /* Send asynchronously to our left child. */",
"sendev.dest = peerlist[(mcastrank+1)*2 - 1];",
"conc_asend_msg (cstate, &sendev);",
"if ((mcastrank+1)*2 <= maxrank) {",
" /* Send asynchronously to our right child. */",
"sendev.dest = peerlist[(mcastrank+1)*2];",
"conc_asend_msg (cstate, &sendev);",
"}",
"",
" /* Wait for all of our pending sends to complete. */",
"conc_wait_all (cstate);",
"}",
"}"],
stack=msgfuncs)
# Define a reduction function.
if uses_reduce:
self.pushmany([
"/* Reduce data from one set of tasks to another set. */",
"static inline void conc_reduce (COMMSTATE *cstate, CONC_REDUCE_EVENT *reduce_ev)",
"{"],
stack=msgfuncs)
self.push(" /* Implement all forms of reduction as a reduce-to-one followed by an optional multicast. */", msgfuncs)
self.code_declare_var(name="sendrank",
rhs="reduce_ev->sendrank",
comment="This task's rank in the reduction step",
stack=msgfuncs)
self.code_declare_var(name="recvrank",
rhs="reduce_ev->recvrank",
comment="This task's rank in the multicast step",
stack=msgfuncs)
self.code_declare_var(name="msgsize",
rhs="reduce_ev->numitems * reduce_ev->itemsize",
comment="The number of bytes in the reduction message",
stack=msgfuncs)
self.code_declare_var(type="ncptl_int *", name="send_peerlist",
rhs="(ncptl_int *) ncptl_queue_contents(reduce_ev->all_senders, 0)",
comment="List of our reduction peers' physical task numbers",
stack=msgfuncs)
self.code_declare_var(type="ncptl_int *", name="recv_peerlist",
rhs="(ncptl_int *) ncptl_queue_contents(reduce_ev->all_receivers, 0)",
comment="List of our multicast peers' physical task numbers",
stack=msgfuncs)
self.code_declare_var(name="num_send_peers",
rhs="ncptl_queue_length(reduce_ev->all_senders)",
comment="Number of tasks involved in the reduction step",
stack=msgfuncs)
self.code_declare_var(name="num_recv_peers",
rhs="ncptl_queue_length(reduce_ev->all_receivers)",
comment="Number of tasks involved in the multicast step",
stack=msgfuncs)
self.code_declare_var(type="CONC_SEND_EVENT", name="sendev",
comment="Send event to pass to conc_asend_msg()",
stack=msgfuncs)
self.code_declare_var(type="CONC_RECV_EVENT", name="recvev",
comment="Receive event to pass to conc_recv_msg()",
stack=msgfuncs)
self.pushmany([
"",
" /* Implement a reduction tree to reduce a value to the first sender. */",
"memset ((void *)&sendev, 0, sizeof(CONC_SEND_EVENT));",
"sendev.size = msgsize;"],
stack=msgfuncs)
for field in ["alignment", "buffernum", "bufferofs", "misaligned",
"touching", "buffer"]:
self.push("sendev.%s = reduce_ev->%s;" % (field, field), msgfuncs)
self.pushmany([
"memset ((void *)&recvev, 0, sizeof(CONC_RECV_EVENT));",
"recvev.size = msgsize;"],
stack=msgfuncs)
for field in ["alignment", "buffernum", "bufferofs", "misaligned",
"touching", "buffer"]:
self.push("recvev.%s = reduce_ev->%s;" % (field, field), msgfuncs)
self.pushmany([
"if (reduce_ev->sending) {",
" /* Receive asynchronously from our children. */",
"if ((sendrank+1)*2-1 < num_send_peers) {",
"recvev.source = send_peerlist[(sendrank+1)*2-1];",
"conc_arecv_msg (cstate, &recvev);",
"if ((sendrank+1)*2 < num_send_peers) {",
"recvev.source = send_peerlist[(sendrank+1)*2];",
"conc_arecv_msg (cstate, &recvev);",
"}",
"conc_wait_all (cstate);",
"}",
"",
" /* Send synchronously to our parent. */",
"if (sendrank > 0) {",
"sendev.dest = send_peerlist[(sendrank-1)/2];",
"conc_send_msg (cstate, &sendev);",
"}",
"else {",
" /* The root of the reduction sends to the root of the multicast. */",
"if (send_peerlist[0] != recv_peerlist[0]) {",
"sendev.dest = recv_peerlist[0];",
"conc_send_msg (cstate, &sendev);",
"}"
"}"
"}"],
stack=msgfuncs)
self.pushmany([
"",
" /* Implement a multicast tree to multicast from the first receiver. */",
"if (reduce_ev->receiving) {",
"if (recvrank == 0 && send_peerlist[0] != recv_peerlist[0]) {",
" /* The root of the multicast receives from the root of the reduction. */",
"recvev.source = send_peerlist[0];",
"conc_recv_msg (cstate, &recvev);",
"}",
"",
"if (recvrank > 0) {",
" /* Receive synchronously from our parent. */",
"recvev.source = recv_peerlist[(recvrank-1)/2];",
"conc_recv_msg (cstate, &recvev);",
"}",
"if ((recvrank+1)*2-1 < num_recv_peers) {",
" /* Send asynchronously to our left child. */",
"sendev.dest = recv_peerlist[(recvrank+1)*2 - 1];",
"conc_asend_msg (cstate, &sendev);",
"if ((recvrank+1)*2 < num_recv_peers) {",
" /* Send asynchronously to our right child. */",
"sendev.dest = recv_peerlist[(recvrank+1)*2];",
"conc_asend_msg (cstate, &sendev);",
"}",
"",
" /* Wait for any blocked sends to complete. */",
"conc_wait_all (cstate);",
"}",
"}",
"}"],
stack=msgfuncs)
# Return the list of function definitions.
return msgfuncs
# -------------- #
# Initialization #
# -------------- #
def code_define_functions_INIT_COMM_1(self, localvars):
"Define extra initialization to be performed after ncptl_init()."
return [
" /* Prevent exiting children from killing their parent. */",
"ncptl_permit_signal(SIGCHLD);"]
def code_def_init_cmd_line_PRE_PARSE(self, localvars):
"Toggle the abnormal_exit flag."
return ['abnormal_exit = 0; /* Let "--help" exit normally. */']
def code_def_init_cmd_line_POST_PARSE(self, localvars):
"Toggle the abnormal_exit flag."
return ['abnormal_exit = 1;']
def code_define_functions_INIT_COMM_3(self, localvars):
"Generate code to initialize the c_udgram backend."
initcode = []
# Create a unique name for every socket we plan to use.
self.pushmany([
" /* Create names for all of the sockets every task will need. */",
"socketinfo = (struct sockaddr_un ***) ncptl_malloc (NUMCHANNELSETS*sizeof (struct sockaddr_un **), 0);",
"for (cset=0; cset<NUMCHANNELSETS; cset++) {"],
stack=initcode)
self.code_declare_var(name="src", comment="Source task ID",
stack=initcode)
self.code_declare_var(name="dest", comment="Destination task ID",
stack=initcode)
self.pushmany([
"socketinfo[cset] = (struct sockaddr_un **) ncptl_malloc (var_num_tasks*sizeof (struct sockaddr_un *), 0);",
"for (dest = 0; dest < var_num_tasks; dest++) {",
"socketinfo[cset][dest] = (struct sockaddr_un *) ncptl_malloc (var_num_tasks*sizeof (struct sockaddr_un), 0);",
"for (src = 0; src < var_num_tasks; src++) {"],
stack=initcode)
self.code_declare_var(type="int", name="tempfd",
comment="File descriptor returned by mkstemp() (not used)",
stack=initcode)
self.pushmany([
"socketinfo[cset][dest][src].sun_family = AF_UNIX;",
"strcpy (socketinfo[cset][dest][src].sun_path, SOCKET_TEMPLATE);",
"if ((tempfd=mkstemp(socketinfo[cset][dest][src].sun_path)) == -1)",
'CONC_SYSTEM_ERROR ("Failed to create a unique filename");',
"if (close (tempfd) == -1)",
'CONC_SYSTEM_ERROR ("Failed to close an open file");',
"}",
"}",
"}",
""],
stack=initcode)
# Spawn child tasks.
self.pushmany([
" /* Spawn var_num_tasks-1 processes (one per task excluding the master). */",
"physrank = 0;",
"if (setpgid (0, 0) == -1)",
'CONC_SYSTEM_ERROR ("Failed to start a new process group");',
"for (i=1; i<var_num_tasks; i++) {",
" /* Spawn a child task and assign it a virtual task ID. While",
" * this could be done in a tree pattern instead of linearly,",
" * we expect var_num_tasks to be small; plus, a simple mapping",
" * from PIDs to tasks may help debug deadlocks and other",
" * problems. */"],
stack=initcode)
self.code_declare_var(type="int", name="newpid",
comment="0=child; other=parent",
stack=initcode)
self.pushmany([
"if ((newpid=fork()) == -1)",
'CONC_SYSTEM_ERROR ("Failed to spawn a child process");',
"else",
"if (!newpid) {",
" /* Child */",
"physrank = (ncptl_int) i;",
"break;",
"}",
"}",
""],
stack=initcode)
# Create and bind socket connections to every other task.
self.pushmany([
" /* Create and bind sockets for inter-task communication. */",
"for (cset=0; cset<NUMCHANNELSETS; cset++) {"],
stack=initcode)
self.code_declare_var(type="COMMSTATE *", name="cstate",
rhs="&commstate[cset]", comment="Current channel set",
stack=initcode)
self.pushmany([
"cstate->channels = (int *) ncptl_malloc (var_num_tasks*sizeof (int), 0);",
"for (taskID=0; taskID<var_num_tasks; taskID++) {",
"if ((cstate->channels[taskID] = socket (PF_UNIX, SOCK_DGRAM, 0)) == -1)",
'CONC_SYSTEM_ERROR ("Socket creation failed");',
"if (unlink (socketinfo[cset][physrank][taskID].sun_path) == -1)",
'CONC_SYSTEM_ERROR ("File deletion failed");',
"if (bind (cstate->channels[taskID],",
"(const struct sockaddr *) &socketinfo[cset][physrank][taskID],",
"SUN_LEN (&socketinfo[cset][physrank][taskID])) == -1)",
'CONC_SYSTEM_ERROR ("Failed to bind a socket");',
"}",
"}",
""],
stack=initcode)
# Connect all of the sockets we created.
self.pushmany([
" /* Connect to each of our peers in turn. */",
"for (cset=0; cset<NUMCHANNELSETS; cset++) {"],
stack=initcode)
self.code_declare_var(type="COMMSTATE *", name="cstate",
rhs="&commstate[cset]", comment="Current channel set",
stack=initcode)
self.pushmany([
"for (taskID=0; taskID<var_num_tasks; taskID++) {",
" /* Keep trying to connect until the socket we want",
" * to connect to exists and is, in fact, a socket. */",
"while (connect (cstate->channels[taskID],",
"(const struct sockaddr *) &socketinfo[cset][taskID][physrank],",
"SUN_LEN (&socketinfo[cset][taskID][physrank])) == -1) {",
"if (errno!=ECONNREFUSED && errno!=ENOENT)",
'CONC_SYSTEM_ERROR ("Failed to connect a socket");',
"usleep (1000);",
"}",
"",
" /* Now that we're connected, put the socket in nonblocking mode. */",
"CONC_SET_BLOCKING (cstate, taskID, 0);",