forked from UCBerkeleySETI/rawspec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rawspec_gpu.cu
1988 lines (1782 loc) · 71.9 KB
/
rawspec_gpu.cu
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
#include "rawspec.h"
#include "rawspec_version.h"
// --- #include <stdint.h> Issue #43
#include <cuda.h> // Issue #43
#include <cufft.h>
#include <cufftXt.h>
#include "cufft_error_name.h"
#define NO_PLAN ((cufftHandle)-1)
#define NO_STREAM ((cudaStream_t)-1)
#define LOAD_TEXTURE_WIDTH_POWER 15
#define LOAD_TEXTURE_WIDTH_MASK (unsigned int)((1<<LOAD_TEXTURE_WIDTH_POWER)-1)
#define MIN(a,b) ((a < b) ? (a) : (b))
#define PRINT_CUDA_ERRMSG(error) \
fprintf(stderr, "got error %s at %s:%d\n", \
cudaGetErrorName(error), \
__FILE__, __LINE__); fflush(stderr)
#define PRINT_CUFFT_ERRMSG(error) \
fprintf(stderr, "got error %s at %s:%d\n", \
cufftGetErrorName(error), \
__FILE__, __LINE__); fflush(stderr)
// Stream callback data structure
typedef struct {
rawspec_context * ctx;
int output_product;
} dump_cb_data_t;
// In full-Stokes mode (Npolout == -4) or full-pol mode (Npolout == 4), the
// CuFFT store callbacks are different depending on whether it is for pol0 or
// pol1:
//
// For full-Stokes mode, the store_callback_pol0_iquv function stores the
// voltage data into the first half of the 2x-sized FFT output buffer and
// accummulates (i.e. adds) the pol0 power into the first two quarters (I and
// Q) of the 4x-sized power buffer.
//
// For full-Stokes mode, the store_callback_pol1_iquv function accumulates
// (i.e. adds) the pol1 power into the first quarter of the 4x-sized power
// buffer (I), negatively accumulates (i.e. subtracts) the pol1 power into the
// second quarter of the 4x-sized power buffer (Q), reads the corresponding
// pol0 voltage from the first half of the 2x-sized FFT output buffer, and
// accumulates the complex pol0-pol1 power in the third (U) and fourth (V)
// quarters of the 4x-sized power buffer.
//
// For full-pol mode, the store_callback_pol0 function stores the voltage data
// into the first half of the 2x-sized FFT output buffer and accummulates the
// pol0 power into the first quarter of the 4x-sized power buffer.
//
// For full-pol mode, the store_callback_pol1 function accumulates the pol1
// power into the second quarter of the 4x-sized power buffer, reads the
// corresponding pol0 voltage from the first half of the 2x-sized FFT output
// buffer, accumulates the complex pol0-pol1 power in the third (real) and
// fourth (imaginary) quarters of the 4x-sized power buffer.
//
// We use a "store_cb_data_t" structure to pass device pointers to the
// various buffers involved.
typedef struct {
cufftComplex * fft_out_pol0;
float * pwr_buf_p00_i;
float * pwr_buf_p11_q;
float * pwr_buf_p01_re_u;
float * pwr_buf_p01_im_v;
} store_cb_data_t;
// GPU context structure
typedef struct {
// Device pointer to FFT input buffer
char * d_fft_in;
// Device pointer to complex4 expansion LUT
char2 * d_comp4_exp_LUT;
// Device pointer to intermediary buffer for expansion of complex4 samples
char * d_blk_expansion_buf;
// Device pointer to FFT output buffer
cufftComplex * d_fft_out;
// Array of device pointers to power buffers (sized for Nbc)
float * d_pwr_out[MAX_OUTPUTS];
// Array of device pointers to power buffers (sized for Nc if Ni > 1)
float * d_prev_pwr_out_cache[MAX_OUTPUTS];
// Array of device pointers to incoherent-sum buffers
float * d_ics_out[MAX_OUTPUTS];
float * d_Aws;
// Array of handles to FFT plans.
// Each output product gets a pair of plans (one for each pol).
cufftHandle plan[MAX_OUTPUTS][2];
// Array of device pointers to store_cb_data_t structures
// (one per output product)
store_cb_data_t *d_scb_data[MAX_OUTPUTS];
// Device pointer to work area (shared by all plans!)
void * d_work_area;
// Size of work area
size_t work_size;
// Array of Ns values (number of specta (FFTs) per input buffer for Nt)
unsigned int Nss[MAX_OUTPUTS];
// Compute stream (as opposed to a "copy stream")
cudaStream_t compute_stream;
// Array of grids for accumulate kernel
dim3 grid[MAX_OUTPUTS];
// Array of number of threads to use per block for accumulate kernel
int nthreads[MAX_OUTPUTS];
// Array of Ni values (number of input buffers per dump)
unsigned int Nis[MAX_OUTPUTS];
// A count of the number of input buffers processed
unsigned int inbuf_count;
// Array of dump_cb_data_t structures for dump callback
dump_cb_data_t dump_cb_data[MAX_OUTPUTS];
// CUDA Texture Object used to convert from integer to floating point
cudaTextureObject_t tex_obj;
// CUDA Texture Object used to convert from complex4bit byte data to complex8bit short data
cudaTextureObject_t comp4_exp_tex_obj;
// Flag indicating that the caller is managing the input block buffers
// Non-zero when caller is managing (i.e. allocating and freeing) the
// buffers; zero when we are.
int caller_managed;
// This is a commonly used value to stride between channels within GUPPI input-buffers,
// the dimensionality of which is [channel (slowest), time, polarisation (fastest)]:
// (ctx->Ntpb * ctx->Np * 2 /*complex*/ * ctx->Nbps)/8
size_t guppi_channel_stride;
} rawspec_gpu_context;
// Device-side texture object declaration
__device__ cudaTextureObject_t d_tex_obj;
__device__ cudaTextureObject_t d_comp4_exp_tex_obj;
// The load_callback gets the input value through the texture memory to achieve
// a "for free" mapping of 8-bit integer values into 32-bit float values.
__device__ cufftComplex load_callback(void *p_v_in,
size_t offset,
void *p_v_user,
void *p_v_shared)
{
cufftComplex c;
// p_v_in is input buffer (cast to cufftComplex*) plus polarization offset.
// p_v_user is input buffer. offset is complex element offset from start of
// input buffer, but does not include any polarization offset so we compute
// the polarization offset by subtracting p_v_user from p_v_in and add it to
// offset.
offset += (cufftComplex *)p_v_in - (cufftComplex *)p_v_user;
c.x = tex2D<float>(d_tex_obj, ((2*offset ) & LOAD_TEXTURE_WIDTH_MASK), (( offset ) >> (LOAD_TEXTURE_WIDTH_POWER-1)));
c.y = tex2D<float>(d_tex_obj, ((2*offset+1) & LOAD_TEXTURE_WIDTH_MASK), ((2*offset+1) >> LOAD_TEXTURE_WIDTH_POWER));
return c;
}
// For total-power-only mode (Npolout == 1), the store_callback just needs to
// accumulate the power into the one and only power buffer. It doesn't matter
// if it's for pol0 or pol1 since they all get added together eventually.
__device__ void store_callback(void *p_v_out,
size_t offset,
cufftComplex element,
void *p_v_user,
void *p_v_shared)
{
float pwr = element.x * element.x + element.y * element.y;
((float *)p_v_user)[offset] += pwr;
}
// For complex-only mode (Npolout == 2), the store_callback_complex just needs to
// accumulate the elements into the power buffer. Pol0 is stored across the first half.
__device__ void store_callback_pol0_complex(void *p_v_out,
size_t offset,
cufftComplex element,
void *p_v_user,
void *p_v_shared)
{
store_cb_data_t * d_scb_data = (store_cb_data_t *)p_v_user;
d_scb_data->pwr_buf_p00_i[2*offset] += element.x;
d_scb_data->pwr_buf_p00_i[2*offset + 1] += element.y;
}
// For complex-only mode (Npolout == 2), the store_callback_complex just needs to
// accumulate the elements into the power buffer. Pol1 is stored across the second half.
__device__ void store_callback_pol1_complex(void *p_v_out,
size_t offset,
cufftComplex element,
void *p_v_user,
void *p_v_shared)
{
store_cb_data_t * d_scb_data = (store_cb_data_t *)p_v_user;
d_scb_data->pwr_buf_p11_q[2*offset] += element.x;
d_scb_data->pwr_buf_p11_q[2*offset + 1] += element.y;
}
// For full-Stokes mode, the store_callback_pol0_iquv function stores the
// voltage data into the first half of the 2x-sized FFT output buffer and
// accummulates (i.e. adds) the pol0 power into the first two quarters (I and
// Q) of the 4x-sized power buffer.
__device__ void store_callback_pol0_iquv(void *p_v_out,
size_t offset,
cufftComplex p0,
void *p_v_user,
void *p_v_shared)
{
store_cb_data_t * d_scb_data = (store_cb_data_t *)p_v_user;
float pwr = p0.x * p0.x + p0.y * p0.y;
d_scb_data->pwr_buf_p00_i[offset] += pwr;
d_scb_data->pwr_buf_p11_q[offset] += pwr;
d_scb_data->fft_out_pol0[offset] = p0;
}
// For full-Stokes mode, the store_callback_pol1_iquv function accumulates
// (i.e. adds) the pol1 power into the first quarter of the 4x-sized power
// buffer (I), negatively accumulates (i.e. subtracts) the pol1 power into the
// second quarter of the 4x-sized power buffer (Q), reads the corresponding
// pol0 voltage from the first half of the 2x-sized FFT output buffer, and
// accumulates the complex pol0-pol1 power in the third (U) and fourth (V)
// quarters of the 4x-sized power buffer.
__device__ void store_callback_pol1_iquv(void *p_v_out,
size_t offset,
cufftComplex p1,
void *p_v_user,
void *p_v_shared)
{
store_cb_data_t * d_scb_data = (store_cb_data_t *)p_v_user;
float pwr = p1.x * p1.x + p1.y * p1.y;
d_scb_data->pwr_buf_p00_i[offset] += pwr;
d_scb_data->pwr_buf_p11_q[offset] -= pwr;
cufftComplex p0 = d_scb_data->fft_out_pol0[offset];
// TODO Verify sign and factor-of-two scaling for U and V
d_scb_data->pwr_buf_p01_re_u[offset] += p0.x * p1.x + p0.y * p1.y;
d_scb_data->pwr_buf_p01_im_v[offset] += p0.y * p1.x - p0.x * p1.y;
}
// Conjugated form of store_callback_pol1_iquv().
__device__ void store_callback_pol1_iquv_conj(void *p_v_out,
size_t offset,
cufftComplex p1,
void *p_v_user,
void *p_v_shared)
{
store_cb_data_t * d_scb_data = (store_cb_data_t *)p_v_user;
float pwr = p1.x * p1.x + p1.y * p1.y;
d_scb_data->pwr_buf_p00_i[offset] += pwr;
d_scb_data->pwr_buf_p11_q[offset] -= pwr;
cufftComplex p0 = d_scb_data->fft_out_pol0[offset];
// TODO Verify sign and factor-of-two scaling for U and V
d_scb_data->pwr_buf_p01_re_u[offset] += p0.x * p1.x + p0.y * p1.y;
d_scb_data->pwr_buf_p01_im_v[offset] -= p0.y * p1.x - p0.x * p1.y;
}
// For full-pol mode, the store_callback_pol0 function stores the voltage data
// into the first half of the 2x-sized FFT output buffer and accummulates the
// pol0 power into the first quarter of the 4x-sized power buffer.
__device__ void store_callback_pol0(void *p_v_out,
size_t offset,
cufftComplex p0,
void *p_v_user,
void *p_v_shared)
{
store_cb_data_t * d_scb_data = (store_cb_data_t *)p_v_user;
float pwr = p0.x * p0.x + p0.y * p0.y;
d_scb_data->pwr_buf_p00_i[offset] += pwr;
d_scb_data->fft_out_pol0[offset] = p0;
}
// For full-pol mode, the store_callback_pol1 function accumulates the pol1
// power into the second quarter of the 4x-sized power buffer, reads the
// corresponding pol0 voltage from the first half of the 2x-sized FFT output
// buffer, accumulates the complex pol0-pol1 power in the third (real) and
// fourth (imaginary) quarters of the 4x-sized power buffer.
__device__ void store_callback_pol1(void *p_v_out,
size_t offset,
cufftComplex p1,
void *p_v_user,
void *p_v_shared)
{
store_cb_data_t * d_scb_data = (store_cb_data_t *)p_v_user;
float pwr = p1.x * p1.x + p1.y * p1.y;
d_scb_data->pwr_buf_p11_q[offset] += pwr;
cufftComplex p0 = d_scb_data->fft_out_pol0[offset];
d_scb_data->pwr_buf_p01_re_u[offset] += p0.x * p1.x + p0.y * p1.y;
d_scb_data->pwr_buf_p01_im_v[offset] += p0.y * p1.x - p0.x * p1.y;
}
// conjugated form of store_callback_pol1().
__device__ void store_callback_pol1_conj(void *p_v_out,
size_t offset,
cufftComplex p1,
void *p_v_user,
void *p_v_shared)
{
store_cb_data_t * d_scb_data = (store_cb_data_t *)p_v_user;
float pwr = p1.x * p1.x + p1.y * p1.y;
d_scb_data->pwr_buf_p11_q[offset] += pwr;
cufftComplex p0 = d_scb_data->fft_out_pol0[offset];
d_scb_data->pwr_buf_p01_re_u[offset] += p0.x * p1.x + p0.y * p1.y;
d_scb_data->pwr_buf_p01_im_v[offset] -= p0.y * p1.x - p0.x * p1.y;
}
__device__ cufftCallbackLoadC d_cufft_load_callback = load_callback;
__device__ cufftCallbackStoreC d_cufft_store_callback = store_callback;
__device__ cufftCallbackStoreC d_cufft_store_callback_complex_pol0 = store_callback_pol0_complex;
__device__ cufftCallbackStoreC d_cufft_store_callback_complex_pol1 = store_callback_pol1_complex;
__device__ cufftCallbackStoreC d_cufft_store_callback_pol0 = store_callback_pol0;
__device__ cufftCallbackStoreC d_cufft_store_callback_pol1 = store_callback_pol1;
__device__ cufftCallbackStoreC d_cufft_store_callback_pol1_conj = store_callback_pol1_conj;
__device__ cufftCallbackStoreC d_cufft_store_callback_pol0_iquv = store_callback_pol0_iquv;
__device__ cufftCallbackStoreC d_cufft_store_callback_pol1_iquv = store_callback_pol1_iquv;
__device__ cufftCallbackStoreC d_cufft_store_callback_pol1_iquv_conj = store_callback_pol1_iquv_conj;
#define MAX_THREADS (1024)
// mem2dAccumMoveFloat kernel
// Adds the source float to the respective destination float,
// then sets the source float 0.0.
//
// Expectation of blockDim, with 1 thread each:
// grid.x = width;
// grid.y = height;
// grid.z = complexity_factor;
// All pitches are in units of float
__global__ void mem2dAccumMoveFloat(float* dst, size_t dpitch, float* src, size_t spitch)
{
float* src_offst = src + blockIdx.z + blockDim.z*(blockDim.x*blockIdx.y*spitch + blockIdx.x);
dst[blockIdx.z + blockDim.z*(blockDim.x*blockIdx.y*dpitch + blockIdx.x)] += *src_offst;
*src_offst = 0.0;
}
// Accumulate kernel
__global__ void accumulate(float * pwr_buf, unsigned int Na, size_t xpitch, size_t ypitch, size_t zpitch)
{
unsigned int i;
// TODO Add check for past end of spectrum
off_t offset0 = blockIdx.z * zpitch
+ blockIdx.y * ypitch
+ blockIdx.x * MAX_THREADS
+ threadIdx.x;
off_t offset = offset0;
float sum = pwr_buf[offset];
for(i=1; i<Na; i++) {
offset += xpitch;
sum += pwr_buf[offset];
}
pwr_buf[offset0] = sum;
}
// Incoherent summation kernel (across antenna)
__global__ void incoherent_sum(float * pwr_buf, float * incoh_buf, float * ant_weights, unsigned int Nant, size_t Nt,
size_t ant_pitch, size_t chan_pitch, size_t pol_pitch, size_t spectra_pitch,
size_t chan_out_pitch, size_t pol_out_pitch, size_t spectra_out_pitch
)
{
const size_t coarse_chan_idx = (blockIdx.x* blockDim.x + threadIdx.x)/Nt;
const size_t fine_chan_idx = (blockIdx.x* blockDim.x + threadIdx.x)%Nt;
off_t offset_pwr = blockIdx.z * spectra_pitch
+ blockIdx.y * pol_pitch
+ coarse_chan_idx * chan_pitch + fine_chan_idx;
const off_t offset_ics = blockIdx.z * spectra_out_pitch
+ blockIdx.y * pol_out_pitch
+ coarse_chan_idx * chan_out_pitch + fine_chan_idx + (fine_chan_idx < (Nt+1)/2 ? Nt/2 : -Nt/2);
for(unsigned int i=0; i<Nant; i++) {
incoh_buf[offset_ics] += ant_weights[i] * pwr_buf[offset_pwr];
offset_pwr += ant_pitch;
}
}
__global__ void complex4_expansion(char2 *lut){
// The right shifts (>> 4) aren't perfectly necessary, as
// with out them a scaling factor is introduced. They are kept
// however, as the LUT only computes this 256 times, all in parallel,
// and so no real speed gains are to be had.
lut[blockIdx.x] = make_char2( ((char)(blockIdx.x&0xf0))>>4, // Real component
((char)((blockIdx.x&0x0f)<<4)) >> 4 // Imag component
);
}
// 4bit Expansion kernel
// Takes the half full blocks of the gpu_ctx->d_blk_expansion_buf buffer and expands
// each complex4 byte. The transferal mimics the cudaMemcpy2D of
// rawspec_copy_blocks_to_gpu:
// The src order is [time, channel, blocks] (fastest --> slowest)
// The dst order is [time, blocks, channels] (fastest --> slowest)
//
// Expectation of blockDim, with ctx->Np threads each:
// grid.x = ctx->Ntpb;
// grid.y = ctx->Nc;
// grid.z = num_blocks;
__global__ void copy_expand_complex4(char *comp8_dst, char *comp4_src, size_t num_blocks,
size_t block_pitch, size_t channel_pitch)
{
char* comp8_dst_offset = comp8_dst + 2*(blockIdx.y*num_blocks*channel_pitch +
blockIdx.z*channel_pitch +
blockIdx.x*blockDim.x + threadIdx.x);
const char2 comp8 = tex1Dfetch<char2>(d_comp4_exp_tex_obj, (unsigned char) (comp4_src[blockIdx.z*block_pitch +
blockIdx.y*channel_pitch +
blockIdx.x*blockDim.x + threadIdx.x]));
comp8_dst_offset[0] = comp8.x;
comp8_dst_offset[1] = comp8.y;
}
// Stream callback function that is called right before an output product's GPU
// power buffer has been copied to the host power buffer.
static void CUDART_CB pre_dump_stream_callback(cudaStream_t stream,
cudaError_t status,
void *data)
{
dump_cb_data_t * dump_cb_data = (dump_cb_data_t *)data;
if(dump_cb_data->ctx->dump_callback) {
dump_cb_data->ctx->dump_callback(dump_cb_data->ctx,
dump_cb_data->output_product,
RAWSPEC_CALLBACK_PRE_DUMP);
}
}
// Stream callback function that is called right after an output product's GPU
// power buffer has been copied to the host power buffer.
static void CUDART_CB post_dump_stream_callback(cudaStream_t stream,
cudaError_t status,
void *data)
{
dump_cb_data_t * dump_cb_data = (dump_cb_data_t *)data;
if(dump_cb_data->ctx->dump_callback) {
dump_cb_data->ctx->dump_callback(dump_cb_data->ctx,
dump_cb_data->output_product,
RAWSPEC_CALLBACK_POST_DUMP);
}
}
// This stringification trick is from "info cpp"
// See https://gcc.gnu.org/onlinedocs/gcc-4.8.5/cpp/Stringification.html
#define STRINGIFY1(s) #s
#define STRINGIFY(s) STRINGIFY1(s)
// librawspec version string
static const char librawspec_version[] = STRINGIFY(RAWSPEC_VERSION);
// cuFFT version string
static const char cufft_version[] =
#ifdef CUFFT_VER_MAJOR
STRINGIFY(CUFFT_VER_MAJOR)
#ifdef CUFFT_VER_MINOR
"." STRINGIFY(CUFFT_VER_MINOR)
#ifdef CUFFT_VER_PATCH
"." STRINGIFY(CUFFT_VER_PATCH)
#ifdef CUFFT_VER_BUILD
"." STRINGIFY(CUFFT_VER_BUILD)
#endif // CUFFT_VER_BUILD
#endif // CUFFT_VER_PATCH
#endif // CUFFT_VER_MINOR
#else
" unknown/old"
#endif // CUFFT_VER_MAJOR
;
// Returns a pointer to a string containing the librawspec version
const char * get_librawspec_version()
{
return librawspec_version;
}
// Returns a pointer to a string containing the cuFFT version
const char * get_cufft_version()
{
return cufft_version;
}
// Sets ctx->Ntmax.
// Allocates host and device buffers based on the ctx->N values.
// Allocates and sets the ctx->gpu_ctx field.
// Creates CuFFT plans.
// Creates streams.
// Returns 0 on success, non-zero on error.
int rawspec_initialize(rawspec_context * ctx)
{
int i;
int p;
// A simple bool-flag for now, but could rather hold expansion ratio
// ^^ would require appropriate changes in rawspec.c (see expand4bps_to8bps)
char NbpsIsExpanded = 0;
uint64_t buf_size;
size_t work_size = 0;
store_cb_data_t h_scb_data;
cudaError_t cuda_rc;
cufftResult cufft_rc;
cudaResourceDesc res_desc;
cudaTextureDesc tex_desc;
int texture_attribute_maximum;
// Host copies of cufft callback pointers
cufftCallbackLoadC h_cufft_load_callback;
cufftCallbackStoreC h_cufft_store_callback;
cufftCallbackStoreC h_cufft_store_callback_complex_pols[2];
cufftCallbackStoreC h_cufft_store_callback_pols[2];
cufftCallbackStoreC h_cufft_store_callback_iquv[2];
// Validate No
if(ctx->No == 0 || ctx->No > MAX_OUTPUTS) {
fprintf(stderr, "output products must be in range [1..%d], not %d\n",
MAX_OUTPUTS, ctx->No);
fflush(stderr);
return 1;
}
// Validate Np
if(ctx->Np == 0 || ctx->Np > 2) {
fprintf(stderr,
"number of polarizations must be in range [1..2], not %d\n", ctx->Np);
fflush(stderr);
return 1;
}
// Validate/set Npolout values
for(i=0; i<ctx->No; i++) {
switch(ctx->Npolout[i]) {
case -4:
case 4:
if(ctx->Np != 2) {
ctx->Npolout[i] = 1;
}
break;
case -2:
case -1:
ctx->complex_output = 1;
ctx->Npolout[i] = abs(ctx->Npolout[i]);
break;
default:
ctx->Npolout[i] = 1;
}
}
ctx->complex_output = min(ctx->complex_output, 1);
// Validate Ntpb
if(ctx->Ntpb == 0) {
fprintf(stderr, "number of time samples per block cannot be zero\n");
fflush(stderr);
return 1;
}
// Validate Nbps.
// Nbps==0 silently defaults to 8 for backwards compatibility with pre-Nbps versions.
// Valid values for Nbps are 4, 8, or 16.
// Any other value results in an error message to stderr and return code of 1 (failure).
// NbpsIsExpanded = 1 (true) if Nbps==4 else 0 (false).
if(ctx->Nbps == 0)
ctx->Nbps = 8;
if(ctx->Nbps != 4 && ctx->Nbps != 8 && ctx->Nbps != 16) {
fprintf(stderr, "Number of bits per sample in raw header must be 4, 0/8, or 16\n");
fprintf(stderr, "Observed a value of %d\n", ctx->Nbps);
fflush(stderr);
return 1;
}
NbpsIsExpanded = ctx->Nbps == 4;
if(ctx->Nbps == 4)
ctx->Nbps = 8;
// Determine Ntmax (and validate Nts)
ctx->Ntmax = 0;
for(i=0; i<ctx->No; i++) {
if(ctx->Nts[i] == 0) {
fprintf(stderr, "Nts[%d] cannot be 0\n", i);
fflush(stderr);
return 1;
}
if(ctx->Ntmax < ctx->Nts[i]) {
ctx->Ntmax = ctx->Nts[i];
}
}
// Validate that all Nts are factors of Ntmax. This constraint helps
// simplify input buffer management.
for(i=0; i<ctx->No; i++) {
if(ctx->Ntmax % ctx->Nts[i] != 0) {
fprintf(stderr, "Nts[%d] (%u) is not a factor of Ntmax (%u)\n",
i, ctx->Nts[i], ctx->Ntmax);
fflush(stderr);
return 1;
}
}
// Validate/calculate Nb
// If ctx->Nb is given by caller (i.e. is non-zero)
if(ctx->Nb != 0) {
// Validate that Ntmax is a factor of (Nb * Ntpb)
if((ctx->Nb * ctx->Ntpb) % ctx->Ntmax != 0) {
fprintf(stderr,
"Ntmax (%u) is not a factor of Nb*Ntpb (%u * %u = %u)\n",
ctx->Ntmax, ctx->Nb, ctx->Ntpb, ctx->Nb*ctx->Ntpb);
fflush(stderr);
return 1;
}
} else {
// Calculate Nb
// If Ntmax is less than one block
if(ctx->Ntmax < ctx->Ntpb) {
// Validate that Ntmax is a factor of Ntpb
if(ctx->Ntpb % ctx->Ntmax != 0) {
fprintf(stderr, "Ntmax (%u) is not a factor of Ntpb (%u)\n",
ctx->Ntmax, ctx->Ntpb);
fflush(stderr);
return 1;
}
ctx->Nb = 1;
} else {
// Validate that Ntpb is factor of Ntmax
if(ctx->Ntmax % ctx->Ntpb != 0) {
fprintf(stderr, "Ntpb (%u) is not a factor of Nmax (%u)\n",
ctx->Ntpb, ctx->Ntmax);
fflush(stderr);
return 1;
}
ctx->Nb = ctx->Ntmax / ctx->Ntpb;
}
}
// Ensure Nb_host is non-zero when host input buffers are caller managed
if(ctx->Nb_host == 0 && ctx->h_blkbufs) {
fprintf(stderr,
"Must specify number of host input blocks when caller-managed\n");
fflush(stderr);
return 1;
} else if(ctx->Nb_host == 0) {
ctx->Nb_host = ctx->Nb;
}
// Validate Nas
for(i=0; i < ctx->No; i++) {
if(ctx->Nas[i] == 0) {
fprintf(stderr, "Nas[%d] cannot be 0\n", i);
fflush(stderr);
return 1;
}
// If mulitple integrations per input buffer
if(ctx->Nts[i]*ctx->Nas[i] < ctx->Nb*ctx->Ntpb) {
// Must have integer integrations per input buffer
if((ctx->Nb * ctx->Ntpb) % (ctx->Nts[i] * ctx->Nas[i]) != 0) {
fprintf(stderr,
"Nts[%d] * Nas[%d] (%u * %u) must divide Nb * Ntpb (%u * %u)\n",
i, i, ctx->Nts[i], ctx->Nas[i], ctx->Nb, ctx->Ntpb);
fflush(stderr);
return 1;
}
} else {
// Must have integer input buffers per integration
if((ctx->Nts[i] * ctx->Nas[i]) % (ctx->Nb * ctx->Ntpb) != 0) {
fprintf(stderr,
"Nb * Ntpb (%u * %u) must divide Nts[%d] * Nas[%d] (%u * %u)\n",
ctx->Nb, ctx->Ntpb, i, i, ctx->Nts[i], ctx->Nas[i]);
fflush(stderr);
return 1;
}
}
}
ctx->Nant = ctx->Nant <= 0 ? 1 : ctx->Nant;
// Setup batched-channel parametners
if(ctx->Nbc == 0) { // Disable channel-batching
ctx->Nbc = ctx->Nc;
}
else{ // Enabled channel-batching
if(ctx->Nbc <= 1) { // Auto channel-batching
if(ctx->Nant > 1){
ctx->Nbc = ctx->Nc/ctx->Nant;
}
else{ // find largest Nc factor <= 10
for(i = 1; i <= 10; i++){
if(ctx->Nc%i == 0){
ctx->Nbc = ctx->Nc/i;
}
}
}
}
if(ctx->Nc%ctx->Nbc != 0) { // inappropriate batches, probably Manual channel-batching
fprintf(stderr, "%d channels cannot be factorised to batches of %d\n",
ctx->Nc, ctx->Nbc
);
return 1;
}
printf("Batching %d channels into %d batches of %d.\n", ctx->Nc, ctx->Nc/ctx->Nbc, ctx->Nbc);
}
// Null out all pointers
// TODO Add support for client managed host buffers
for(i=0; i < MAX_OUTPUTS; i++) {
ctx->h_pwrbuf[i] = NULL;
ctx->h_icsbuf[i] = NULL;
}
ctx->gpu_ctx = NULL;
// Set CUDA device (validates gpu_index)
cuda_rc = cudaSetDevice(ctx->gpu_index);
if(cuda_rc != cudaSuccess) {
PRINT_CUDA_ERRMSG(cuda_rc);
// TODO return distinct error code
return 1;
}
// Allocate GPU context
rawspec_gpu_context * gpu_ctx = (rawspec_gpu_context *)malloc(sizeof(rawspec_gpu_context));
if(!gpu_ctx) {
fprintf(stderr, "unable to allocate %lu bytes for rawspec GPU context\n",
sizeof(rawspec_gpu_context));
fflush(stderr);
rawspec_cleanup(ctx);
return 1;
}
// Store pointer to gpu_ctx in ctx
ctx->gpu_ctx = gpu_ctx;
// NULL out pointers (and invalidate plans)
gpu_ctx->d_fft_in = NULL;
gpu_ctx->d_comp4_exp_LUT = NULL;
gpu_ctx->d_blk_expansion_buf = NULL;
gpu_ctx->d_fft_out = NULL;
gpu_ctx->d_work_area = NULL;
gpu_ctx->work_size = 0;
gpu_ctx->compute_stream = NO_STREAM;
for(i=0; i<MAX_OUTPUTS; i++) {
gpu_ctx->d_pwr_out[i] = NULL;
gpu_ctx->d_prev_pwr_out_cache[i] = NULL;
gpu_ctx->d_scb_data[i] = NULL;
gpu_ctx->plan[i][0] = NO_PLAN;
gpu_ctx->plan[i][1] = NO_PLAN;
gpu_ctx->dump_cb_data[i].ctx = ctx;
gpu_ctx->dump_cb_data[i].output_product = i;
}
// Initialize inbuf_count
gpu_ctx->inbuf_count = 0;
if(!ctx->h_blkbufs) {
// Remember that we (not the caller) are managing these buffers
// (i.e. we will need to free them when cleaning up).
gpu_ctx->caller_managed = 0;
// Alllocate host input block buffers
ctx->h_blkbufs = (char **)malloc(ctx->Nb_host * sizeof(char *));
for(i=0; i < ctx->Nb_host; i++) {
// Block buffer can use write combining
cuda_rc = cudaHostAlloc(&ctx->h_blkbufs[i],
ctx->Ntpb * ctx->Np * ctx->Nc * 2 /*complex*/ * (ctx->Nbps/8),
cudaHostAllocWriteCombined);
if(cuda_rc != cudaSuccess) {
PRINT_CUDA_ERRMSG(cuda_rc);
rawspec_cleanup(ctx);
return 1;
}
}
} else {
// Remember that the caller is managing these buffers
// (i.e. we will only need to unregister them when cleaning up).
gpu_ctx->caller_managed = 1;
// Register these buffers with CUDA. It is the caller's responsibility to
// ensure that the blocks meet memory alignment requirements, etc.
for(i=0; i < ctx->Nb_host; i++) {
cuda_rc = cudaHostRegister(ctx->h_blkbufs[i],
ctx->Ntpb * ctx->Np * ctx->Nc * 2 /*complex*/ * (ctx->Nbps/8),
cudaHostRegisterDefault);
if(cuda_rc != cudaSuccess) {
PRINT_CUDA_ERRMSG(cuda_rc);
rawspec_cleanup(ctx);
return 1;
}
}
}
// Calculate Ns and allocate host power output buffers
for(i=0; i < ctx->No; i++) {
// Ns[i] is number of specta (FFTs) per coarse channel for one input buffer
// for Nt[i] points per spectra.
gpu_ctx->Nss[i] = (ctx->Nb * ctx->Ntpb) / ctx->Nts[i];
// Calculate number of spectra per dump
ctx->Nds[i] = gpu_ctx->Nss[i] / ctx->Nas[i];
if(ctx->Nds[i] == 0) {
ctx->Nds[i] = 1;
}
// Calculate number of input buffers per dump
gpu_ctx->Nis[i] = ctx->Nas[i] / gpu_ctx->Nss[i];
if(gpu_ctx->Nis[i] == 0) {
gpu_ctx->Nis[i] = 1;
}
// Calculate grid dimensions
gpu_ctx->nthreads[i] = ctx->Nts[i];
gpu_ctx->nthreads[i] *= 1 + ctx->complex_output;
gpu_ctx->grid[i].x = (gpu_ctx->nthreads[i] + MAX_THREADS - 1) / MAX_THREADS;
gpu_ctx->grid[i].y = ctx->Nds[i];
gpu_ctx->grid[i].z = ctx->Nbc;
// Calculate number of threads per block
gpu_ctx->nthreads[i] = MIN(gpu_ctx->nthreads[i], MAX_THREADS);
// Host buffer needs to accommodate the number of integrations that will be
// dumped at one time (Nd).
ctx->h_pwrbuf_size[i] = abs(ctx->Npolout[i]) *
ctx->Nds[i]*ctx->Nts[i]*ctx->Nc*sizeof(float);
ctx->h_pwrbuf_size[i] *= 1 + ctx->complex_output; // complex-output conditional double
printf("FFT Host dump buffer[%d] size == %lu\n", i, ctx->h_pwrbuf_size[i]);
#ifdef VERBOSE_ALLOC
printf("FFT Host dump buffer[%d] size == %lu\n", i, ctx->h_pwrbuf_size[i]);
#endif
cuda_rc = cudaHostAlloc(&ctx->h_pwrbuf[i], ctx->h_pwrbuf_size[i],
cudaHostAllocDefault);
if(cuda_rc != cudaSuccess) {
PRINT_CUDA_ERRMSG(cuda_rc);
rawspec_cleanup(ctx);
return 1;
}
if(ctx->incoherently_sum == 1){// TODO validate that Nant > 1
cuda_rc = cudaHostAlloc(&ctx->h_icsbuf[i], ctx->h_pwrbuf_size[i]/ctx->Nant,
cudaHostAllocDefault);
if(cuda_rc != cudaSuccess) {
PRINT_CUDA_ERRMSG(cuda_rc);
rawspec_cleanup(ctx);
return 1;
}
}
}
gpu_ctx->guppi_channel_stride = (ctx->Ntpb * ctx->Np * 2 /*complex*/ * ctx->Nbps)/8;
// Allocate buffers
// FFT input buffer
// The input buffer is padded to the next multiple of 1<<LOAD_TEXTURE_WIDTH_POWER
// to facilitate 2D texture lookups by treating the input buffer as a 2D array
// that is 1<<LOAD_TEXTURE_WIDTH_POWER wide.
buf_size = ctx->Nb*ctx->Nc*gpu_ctx->guppi_channel_stride;
if((buf_size & LOAD_TEXTURE_WIDTH_MASK) != 0) {
// Round up to next multiple of 64KB
buf_size = (buf_size & ~LOAD_TEXTURE_WIDTH_MASK) + 1<<LOAD_TEXTURE_WIDTH_POWER;
}
#ifdef VERBOSE_ALLOC
printf("FFT input buffer size == %lu\n", buf_size);
#endif
cuda_rc = cudaMalloc(&gpu_ctx->d_fft_in, buf_size);
if(cuda_rc != cudaSuccess) {
PRINT_CUDA_ERRMSG(cuda_rc);
rawspec_cleanup(ctx);
return 1;
}
cudaDeviceGetAttribute(&texture_attribute_maximum, cudaDevAttrMaxTexture2DLinearWidth, ctx->gpu_index);
if(texture_attribute_maximum < 1<<LOAD_TEXTURE_WIDTH_POWER){
fprintf(stderr, "Maximum 2D texture width: %d.\n", texture_attribute_maximum);
fprintf(stderr, "\tThe static load-texture-width of 1<<LOAD_TEXTURE_WIDTH_POWER exceeds this: %d\n", 1<<LOAD_TEXTURE_WIDTH_POWER);
fprintf(stderr, "\tExpect a CUDA raised failure!\n");
}
cudaDeviceGetAttribute(&texture_attribute_maximum, cudaDevAttrMaxTexture2DLinearHeight, ctx->gpu_index);
if(texture_attribute_maximum < buf_size>>LOAD_TEXTURE_WIDTH_POWER){
fprintf(stderr, "Maximum 2D texture height: %d.\n", texture_attribute_maximum);
fprintf(stderr, "\tThe load-texture-height of `buf_size (%lu)>>(%d) LOAD_TEXTURE_WIDTH_POWER` exceeds this: %lu\n", buf_size, LOAD_TEXTURE_WIDTH_POWER, buf_size>>LOAD_TEXTURE_WIDTH_POWER);
fprintf(stderr, "\tExpect a CUDA raised failure!\n");
cudaDeviceGetAttribute(&texture_attribute_maximum, cudaDevAttrMaxTexture2DLinearWidth, ctx->gpu_index);
if(texture_attribute_maximum > 1<<LOAD_TEXTURE_WIDTH_POWER){
fprintf(stderr, "\tLOAD_TEXTURE_WIDTH_POWER could be increased to %d (at most) to possibly circumvent this issued\n", 31 - __builtin_clz(texture_attribute_maximum));
}
}
cudaDeviceGetAttribute(&texture_attribute_maximum, cudaDevAttrMaxTexture2DLinearPitch, ctx->gpu_index);
if(texture_attribute_maximum < (1<<LOAD_TEXTURE_WIDTH_POWER) * (ctx->Nbps/8)){
fprintf(stderr, "Maximum 2D texture pitch: %d.\n", texture_attribute_maximum);
fprintf(stderr, "\tThe load-texture-pitch of (1<<LOAD_TEXTURE_WIDTH_POWER) * (ctx->Nbps/8) exceeds this: %d\n", (1<<LOAD_TEXTURE_WIDTH_POWER) * (ctx->Nbps/8));
fprintf(stderr, "\tExpect a CUDA raised failure!\n");
}
fflush(stderr);
// Create texture object for device input buffer
// res_desc describes input resource
// Width is 32K elements, height is buf_size/32K elements, pitch is 32K elements
memset(&res_desc, 0, sizeof(res_desc));
res_desc.resType = cudaResourceTypePitch2D;
res_desc.res.pitch2D.devPtr = gpu_ctx->d_fft_in;
res_desc.res.pitch2D.desc.f = cudaChannelFormatKindSigned;
res_desc.res.pitch2D.desc.x = ctx->Nbps; // bits per sample
res_desc.res.pitch2D.width = 1<<LOAD_TEXTURE_WIDTH_POWER; // elements
res_desc.res.pitch2D.height = buf_size>>LOAD_TEXTURE_WIDTH_POWER; // elements
res_desc.res.pitch2D.pitchInBytes = (1<<LOAD_TEXTURE_WIDTH_POWER) * (ctx->Nbps/8); // bytes!
// tex_desc describes texture mapping
memset(&tex_desc, 0, sizeof(tex_desc));
#if 0 // These settings are not used in online examples involved cudaReadModeNormalizedFloat
// Not sure whether address_mode matters for cudaReadModeNormalizedFloat
tex_desc.address_mode[0] = cudaAddressModeClamp;
tex_desc.address_mode[1] = cudaAddressModeClamp;
tex_desc.address_mode[2] = cudaAddressModeClamp;
// Not sure whether filter_mode matters for cudaReadModeNormalizedFloat
tex_desc.filter_mode = cudaFilterModePoint;
#endif // 0
tex_desc.readMode = cudaReadModeNormalizedFloat;
cuda_rc = cudaCreateTextureObject(&gpu_ctx->tex_obj,
&res_desc, &tex_desc, NULL);
if(cuda_rc != cudaSuccess) {
PRINT_CUDA_ERRMSG(cuda_rc);
rawspec_cleanup(ctx);
return 1;
}
// Copy texture object to device
cuda_rc = cudaMemcpyToSymbol(d_tex_obj,
&gpu_ctx->tex_obj,
sizeof(cudaTextureObject_t));
if(cuda_rc != cudaSuccess) {
PRINT_CUDA_ERRMSG(cuda_rc);
rawspec_cleanup(ctx);
return 1;
}
if(NbpsIsExpanded){
#ifdef VERBOSE_ALLOC
printf("NBITS expansion buffer size == %lu\n", buf_size/2);
#endif
cuda_rc = cudaMalloc(&gpu_ctx->d_blk_expansion_buf, buf_size/2);
if(cuda_rc != cudaSuccess) {
PRINT_CUDA_ERRMSG(cuda_rc);
rawspec_cleanup(ctx);
return 1;
}
#ifdef VERBOSE_ALLOC
printf("Complex4 expansion LUT size == %lu\n", 256*sizeof(char2));
#endif
cuda_rc = cudaMalloc(&gpu_ctx->d_comp4_exp_LUT, 256*sizeof(char2));
if(cuda_rc != cudaSuccess) {
PRINT_CUDA_ERRMSG(cuda_rc);
rawspec_cleanup(ctx);
return 1;
}
complex4_expansion<<<256,1>>>(gpu_ctx->d_comp4_exp_LUT);
memset(&res_desc, 0, sizeof(res_desc));
res_desc.resType = cudaResourceTypeLinear;
res_desc.res.linear.devPtr = gpu_ctx->d_comp4_exp_LUT;
res_desc.res.linear.desc.f = cudaChannelFormatKindSigned;
res_desc.res.linear.desc.x = 8; // bits per channel
res_desc.res.linear.desc.y = 8; // bits per channel
res_desc.res.linear.sizeInBytes = 256*sizeof(char2);
memset(&tex_desc, 0, sizeof(tex_desc));
tex_desc.readMode = cudaReadModeElementType;
cuda_rc = cudaCreateTextureObject(&gpu_ctx->comp4_exp_tex_obj,
&res_desc, &tex_desc, NULL);
if(cuda_rc != cudaSuccess) {
PRINT_CUDA_ERRMSG(cuda_rc);
rawspec_cleanup(ctx);
return 1;
}
cuda_rc = cudaMemcpyToSymbol(d_comp4_exp_tex_obj,
&gpu_ctx->comp4_exp_tex_obj,
sizeof(cudaTextureObject_t));
if(cuda_rc != cudaSuccess) {
PRINT_CUDA_ERRMSG(cuda_rc);
rawspec_cleanup(ctx);
return 1;
}
}
// FFT output buffer
buf_size = ctx->Nb*ctx->Ntpb*ctx->Nbc*sizeof(cufftComplex);
// If any output product is full-pol then we need to double output buffer
for(i=0; i < ctx->No; i++) {
if(abs(ctx->Npolout[i]) == 4) {
buf_size *= 2;
break;
}
}
#ifdef VERBOSE_ALLOC
printf("FFT output buffer size == %lu\n", buf_size);
#endif
cuda_rc = cudaMalloc(&gpu_ctx->d_fft_out, buf_size);
if(cuda_rc != cudaSuccess) {
PRINT_CUDA_ERRMSG(cuda_rc);
rawspec_cleanup(ctx);
return 1;
}
// For each output product
for(i=0; i < ctx->No; i++) {
// Power output buffer
buf_size = abs(ctx->Npolout[i]) * ctx->Nb*ctx->Ntpb*ctx->Nbc*sizeof(float);