-
Notifications
You must be signed in to change notification settings - Fork 1
/
cuda_cuda - Kopie.c
2499 lines (2281 loc) · 117 KB
/
cuda_cuda - Kopie.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
/************************* CudaMat ******************************************
* Copyright (C) 2008-2009 by Rainer Heintzmann *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; Version 2 of the License. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************
Compile with:
Windows:
mex cuda_cuda.c cudaArith.obj -Ic:\\CUDA\include\ -Lc:\\CUDA\lib64\ -lcublas -lcufft -lcudart
Windows 64 bit:
No Cula:
mex cuda_cuda.c cudaArith.obj -DNOCULA "-IC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.2\include" "-IC:\Program Files\CULA\R14\include" "-LC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.2\lib\x64" -lcublas -lcufft -lcudart
Cula:
mex cuda_cuda.c cudaArith.obj "-IC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.2\include" "-IC:\Program Files\CULA\R14\include" "-LC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.2\lib\x64" "-LC:\Program Files\CULA\R14\lib64" -lcublas -lcufft -lcudart -lcula_core -lcula_lapack
Linux:
mex -Dnocula cuda_cuda.c cudaArith.o -I/usr/local/cuda/include -L/usr/local/cuda/lib64 -lcublas -lcufft -lcudart -v
or Linux including CULA support:
mex cuda_cuda.c cudaArith.o -I/usr/local/cuda/include -I/usr/local/cula/include -L/usr/local/cuda/lib64 -L/usr/local/cula/lib64 -lcublas -lcufft -lcudart -lcula
*/
/*
This is a mex file to perform a number of operations using cuda on graphic cards.
* The sytax is always cuda_cuda('operation',arg1, arg2) whereas arg2 can be empty.
'alloc' convert a matlab single into a cuda object which is stored on the graphics card. Returns integer reference to cuda object.
*/
#include "mex.h"
#include "cufft.h"
#include "cuda_runtime.h"
#include "cublas.h"
#define externC
#include "cudaArith.h"
#include "matrix.h"
#include "stdio.h"
#include "string.h"
#include "cufft.h"
#ifndef NOCULA
// #include "culadevice.h" // Only for old Cula releases
#include "cula.h" // Later releases such as R14
#include "cula_device.h" // Later releases such as R14
#endif
// #define DEBUG
// #define UseHeap // if defined the heap allocation and recycling is used. Otherwise normal allocation and free is used
#define AllocBlas // use the cublasAlloc and free functions instead of cudaMalloc and cudaFree
#define MAX_ARRAYS 65738 // maximum number of arrays simultaneously on card
#ifdef UseHeap
#define MAX_HEAP 5 // size of the heap of arrays to recycle
#endif
#define CHECK_CUDAREF(p) {if ((((double) (int) p) != p) || (p < 0) || (p >= MAX_ARRAYS)) \
mexErrMsgTxt("cuda: Reference must be an integer between 0 and max_array\n");}
#define CHECK_CUDASIZES(ref1,ref2) {if (cuda_array_dim[ref1] != cuda_array_dim[ref2]) mexErrMsgTxt("cuda: Arrays have different dimensionalities\n"); \
int d; for (d=0;d< cuda_array_dim[ref1]) if (cuda_array_size[ref1][d] != cuda_array_size[ref2][d])\
mexErrMsgTxt("cuda: Array sizes must be equal in all dimensions\n");}
#ifdef DEBUG
#define Dbg_printf(arg) printf(arg)
#define Dbg_printf2(arg1,arg2) printf(arg1,arg2)
#define Dbg_printf3(arg1,arg2,arg3) printf(arg1,arg2,arg3)
#define Dbg_printf4(arg1,arg2,arg3,arg4) printf(arg1,arg2,arg3,arg4)
#define Dbg_printf5(arg1,arg2,arg3,arg4,arg5) printf(arg1,arg2,arg3,arg4,arg5)
#else
#define Dbg_printf(arg)
#define Dbg_printf2(arg1,arg2)
#define Dbg_printf3(arg1,arg2,arg3)
#define Dbg_printf4(arg1,arg2,arg3,arg4)
#define Dbg_printf5(arg1,arg2,arg3,arg4,arg5)
#endif
// ----------------- Macros of code snippets, defining common ways of calling Cuda ---------
#define CallCUDA_BinaryFkt(FktName,AllocFkt) \
const char *ret=0; \
if (nrhs != 3) mexErrMsgTxt("cuda: " #FktName "needs three arguments\n"); \
if (isComplexType(getCudaRefNum(prhs[1])) && isComplexType(getCudaRefNum(prhs[2]))) { \
Dbg_printf("cuda: complex array " #FktName " complex array\n"); \
ret=CUDAcarr_##FktName##_carr(getCudaRef(prhs[1]),getCudaRef(prhs[2]),AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); } \
else if (isComplexType(getCudaRefNum(prhs[1]))) { \
Dbg_printf("cuda: complex array " #FktName " float array\n"); \
ret=CUDAcarr_##FktName##_arr(getCudaRef(prhs[1]),getCudaRef(prhs[2]),AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); } \
else if (isComplexType(getCudaRefNum(prhs[2]))) { \
Dbg_printf("cuda: float array " #FktName " complex array\n"); \
ret=CUDAarr_##FktName##_carr(getCudaRef(prhs[1]),getCudaRef(prhs[2]),AllocFkt(prhs[2]),getTotalSizeFromRef(prhs[1])); }\
else { \
Dbg_printf("cuda: array " #FktName " array\n"); \
ret=CUDAarr_##FktName##_arr(getCudaRef(prhs[1]),getCudaRef(prhs[2]),AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); }\
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("cuda error " #FktName ": Bailing out");} \
// ----------------- for calling with array and constant ---------
#define CallCUDA_UnaryFktConst(FktName,AllocFkt) \
const char *ret=0; \
int ref; \
if (nrhs != 3) mexErrMsgTxt("cuda: " #FktName "_alpha needs three arguments\n"); \
ref=getCudaRefNum(prhs[1]); \
if (mxIsComplex(prhs[2])) { \
double myreal = mxGetScalar(prhs[2]); \
double myimag = * ((double *) (mxGetPi(prhs[2]))); \
if (isComplexType(ref)) { \
Dbg_printf("cuda: complex array " #FktName " complex-const\n"); \
ret=CUDAcarr_##FktName##_const(getCudaRef(prhs[1]),(float) myreal,(float) myimag,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} else { \
int tmp=cuda_array_type[ref]; float * narr=AllocFkt(prhs[1]);cuda_array_type[ref]=tmp; cuda_array_type[ref]=scomplex; \
Dbg_printf("cuda: float array " #FktName " complex-const\n"); \
ret=CUDAarr_##FktName##_Cconst(getCudaRef(prhs[1]),(float) myreal,(float) myimag,narr,getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} \
} else { \
double alpha = mxGetScalar(prhs[2]); \
if (isComplexType(ref)) { \
Dbg_printf("cuda: complex array " #FktName " real-const\n"); \
ret=CUDAcarr_##FktName##_const(getCudaRef(prhs[1]),(float) alpha,0.0,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} else { \
Dbg_printf("cuda: float array " #FktName " real-const\n"); \
ret=CUDAarr_##FktName##_const(getCudaRef(prhs[1]),(float) alpha,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} \
}
// ----------------- for calling with array and constant but in Reverse order---------
#define CallCUDA_UnaryFktConstR(FktName,AllocFkt) \
const char *ret=0; \
int ref; \
if (nrhs != 3) mexErrMsgTxt("cuda: " #FktName "_alpha needs three arguments\n"); \
ref=getCudaRefNum(prhs[1]); \
if (mxIsComplex(prhs[2])) { \
double myreal = mxGetScalar(prhs[2]); \
double myimag = * ((double *) (mxGetPi(prhs[2]))); \
if (isComplexType(ref)) { \
Dbg_printf("cuda: complex array " #FktName " complex-const\n"); \
ret=CUDAconst_##FktName##_carr(getCudaRef(prhs[1]),(float) myreal,(float) myimag,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} else { \
int tmp=cuda_array_type[ref]; float * narr=AllocFkt(prhs[1]);cuda_array_type[ref]=tmp; cuda_array_type[ref]=scomplex; \
Dbg_printf("cuda: float array " #FktName " complex-const\n"); \
ret=CUDACconst_##FktName##_arr(getCudaRef(prhs[1]),(float) myreal,(float) myimag,narr,getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} \
} else { \
double alpha = mxGetScalar(prhs[2]); \
if (isComplexType(ref)) { \
Dbg_printf("cuda: complex array " #FktName " real-const\n"); \
ret=CUDAconst_##FktName##_carr(getCudaRef(prhs[1]),(float) alpha,0.0,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} else { \
Dbg_printf("cuda: float array " #FktName " real-const\n"); \
ret=CUDAconst_##FktName##_arr(getCudaRef(prhs[1]),(float) alpha,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} \
}
// --------- The ones below are FOR REAL-VALUED Functions only --- (e.g. comparison operations) ----------
#define CallCUDA_BinaryHRealFkt(FktName,AllocFkt) \
const char *ret=0; \
if (nrhs != 3) mexErrMsgTxt("cuda: " #FktName "needs three arguments\n"); \
if (isComplexType(getCudaRefNum(prhs[1])) && isComplexType(getCudaRefNum(prhs[2]))) { \
mexErrMsgTxt("cuda: Function \"" #FktName "\" is defined only for real argument data.\n");} \
else if (isComplexType(getCudaRefNum(prhs[1]))) { \
Dbg_printf("cuda: complex array " #FktName " float array\n"); \
ret=CUDAcarr_##FktName##_arr(getCudaRef(prhs[1]),getCudaRef(prhs[2]),AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); } \
else if (isComplexType(getCudaRefNum(prhs[2]))) { \
mexErrMsgTxt("cuda: Function \"" #FktName "\" is defined only for real argument data.\n");} \
else { \
Dbg_printf("cuda: array " #FktName " array\n"); \
ret=CUDAarr_##FktName##_arr(getCudaRef(prhs[1]),getCudaRef(prhs[2]),AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); }\
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("cuda error " #FktName ": Bailing out");} \
// --------- The ones below are FOR REAL-VALUED Functions only --- (e.g. comparison operations) ----------
#define CallCUDA_BinaryRealFkt(FktName,AllocFkt) \
const char *ret=0; \
if (nrhs != 3) mexErrMsgTxt("cuda: " #FktName "needs three arguments\n"); \
if (isComplexType(getCudaRefNum(prhs[1])) || isComplexType(getCudaRefNum(prhs[2]))) \
mexErrMsgTxt("cuda: Function \"" #FktName "\" is defined only for real valued data.\n"); \
else { \
Dbg_printf("cuda: array " #FktName " array\n"); \
ret=CUDAarr_##FktName##_arr(getCudaRef(prhs[1]),getCudaRef(prhs[2]),AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); }\
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("cuda error " #FktName ": Bailing out");}
// ----------------- for calling with array and constant ---------
#define CallCUDA_UnaryRealFktConst(FktName,AllocFkt) \
const char *ret=0; \
if (nrhs != 3) mexErrMsgTxt("cuda: " #FktName "_alpha needs three arguments\n"); \
if (mxIsComplex(prhs[2])) { \
mexErrMsgTxt("cuda: Function \"" #FktName "\" is defined only for real valued data.\n"); \
} else { \
double alpha = mxGetScalar(prhs[2]); \
if (isComplexType(getCudaRefNum(prhs[1]))) { \
mexErrMsgTxt("cuda: Function \"" #FktName "\" is defined only for real valued data.\n"); \
} else { \
Dbg_printf("cuda: float array " #FktName " real-const\n"); \
ret=CUDAarr_##FktName##_const(getCudaRef(prhs[1]),(float) alpha,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
} \
} \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("cuda error " #FktName ": Bailing out");}
// ----------------- for calling with array and constant but in Reverse order (e.g. for alpha / array) ---------
#define CallCUDA_UnaryRealFktConstR(FktName,AllocFkt) \
const char *ret=0; \
if (nrhs != 3) mexErrMsgTxt("cuda: " #FktName "_alpha needs three arguments\n"); \
if (mxIsComplex(prhs[2])) { \
mexErrMsgTxt("cuda: Function \"" #FktName "\" is defined only for real valued data.\n"); \
} else { \
double alpha = mxGetScalar(prhs[2]); \
if (isComplexType(getCudaRefNum(prhs[1]))) { \
mexErrMsgTxt("cuda: Function \"" #FktName "\" is defined only for real valued data.\n"); \
} else { \
Dbg_printf("cuda: float array " #FktName " real-const\n"); \
ret=CUDAconst_##FktName##_arr(getCudaRef(prhs[1]),(float) alpha,AllocFkt(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("cuda error " #FktName ": Bailing out");} \
} \
}
// ----------------- Unary function for real valued data only ------AllocCommand determines whether the result type is that same, complex or real ----------
#define CallCUDA_UnaryRealFkt(FktName,AllocCommand) \
const char *ret=0; \
if (nrhs != 2) mexErrMsgTxt("cuda: " #FktName " needs three arguments\n"); \
if (isComplexType(getCudaRefNum(prhs[1]))) { \
mexErrMsgTxt("cuda error " #FktName ": Tried to apply to complex valued data."); \
ret="Error " #FktName ": Tried to apply to complex valued data."; \
} else { \
Dbg_printf("cuda: float array " #FktName "\n"); \
ret=CUDA##FktName##_arr(getCudaRef(prhs[1]),AllocCommand(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("cuda error " #FktName ": Bailing out");} \
}
// ----------------- Unary function ------AllocCommand determines whether the result type is that same, complex or real ----------
#define CallCUDA_UnaryFkt(FktName,AllocCommand) \
const char *ret=0; \
if (nrhs != 2) mexErrMsgTxt("cuda: " #FktName " needs three arguments\n"); \
if (isComplexType(getCudaRefNum(prhs[1]))) { \
Dbg_printf("cuda: complex array " #FktName "\n"); \
ret=CUDA##FktName##_carr(getCudaRef(prhs[1]),AllocCommand(prhs[1]),getTotalSizeFromRef(prhs[1])); \
} else { \
Dbg_printf("cuda: float array " #FktName "\n"); \
ret=CUDA##FktName##_arr(getCudaRef(prhs[1]),AllocCommand(prhs[1]),getTotalSizeFromRef(prhs[1])); \
if (ret!=(const char *) cudaSuccess) { printf("cuda " #FktName ": %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("cuda error " #FktName ": Bailing out");} \
}
static const char * ERROR_NAMES[]={
"SUCCESS",
"INVALID_PLAN",
"ALLOC_FAILED",
"INVALID_TYPE",
"INVALID_VALUE",
"INTERNAL_ERROR",
"EXEC_FAILED",
"SETUP_FAILED",
// "SHOWDOWN_FAILED",
"INVALID_SIZE",
"" // needed to stop the search
};
enum CUDA_TYPE {
single,
int16,
// fftSingle,
fftHalfSComplex,
scomplex
};
static const char * CUDA_TYPE_NAMES[]={
"single",
"int16",
// "fftSingle",
"fftHalfSComplex",
"scomplex",
"" // needed to stop the search
};
static int CUDA_TYPE_SIZE[]={
sizeof(float),
2,
// sizeof(float),
sizeof(cufftComplex),
sizeof(cufftComplex)
};
static int CUDA_MATLAB_CLASS[]={
mxSINGLE_CLASS,
mxINT16_CLASS,
// mxSINGLE_CLASS,
mxSINGLE_CLASS,
mxSINGLE_CLASS
};
static float * cuda_arrays[MAX_ARRAYS]; // static array of cuda arrays
static cufftHandle cuda_FFTplan[MAX_ARRAYS]; // stores fft plans (when needed)
static int cuda_array_dim[MAX_ARRAYS]; // type tags see CUDA_TYPE definitions above
static int * cuda_array_size[MAX_ARRAYS]; // dynamically allocated
static int cuda_array_origFTsize[MAX_ARRAYS]; // for storing the original data size, when doing FFTs
static float cuda_array_FTscale[MAX_ARRAYS]; // to do the maginitude correction
static int cuda_array_type[MAX_ARRAYS]; // type tags see CUDA_TYPE definitions above
static int free_array=0; // next number of array to fill
static int cuda_curr_arrays=0;
static int cuda_initialized=0;
// static int sizes[100];
// static int dims=0,totalsize=0;
static float * pOne=0, * pZero=0;
static int ignoreDelete=0; // Needed to avoid delete (or copyiing the whole array) after subassign
static int ignoreRef=-1; // Needed to avoid delete (or copyiing the whole array) after subassign
static void * fastMem=0, * fastMemI=0;
static const int fastMemSize=1024; // number of byte for fast transfer
#ifdef UseHeap
static void * mem_heap[MAX_HEAP]; // memory which can be reused if size matches
static int memsize_heap[MAX_HEAP]; // sizes in bytes
static int mem_heap_pos=0;
static int mem_heap_allocated=0;
#endif
/**************************************************************************/
/* MATLAB stores complex numbers in separate arrays for the real and
imaginary parts. The following functions take the data in
this format and pack it into a complex work array, or
unpack it, respectively.
We are using cufftComplex defined in cufft.h to handle complex on Windows and Linux
*/
#ifndef NOCULA
void checkCULAStatus(char * text, culaStatus status)
{
if(!status)
return;
if(status == culaArgumentError)
printf("%s: Invalid value for parameter %d\n", text,culaGetErrorInfo());
else if(status == culaDataError)
printf("%s: Data error (%d)\n", text,culaGetErrorInfo());
else if(status == culaBlasError)
printf("%s: Blas error (%d)\n", text,culaGetErrorInfo());
else if(status == culaRuntimeError)
printf("%s: Runtime error (%d)\n", text,culaGetErrorInfo());
else
printf("%s: %s\n", text,culaGetStatusString(status));
mexErrMsgTxt("CULA Error: Bailing out\n");
// culaShutdown();
}
#endif
void checkCudaError(char * text, cudaError_t err)
{
if(!err)
return;
printf("%s: %s\n", text, cudaGetErrorString(err));
mexErrMsgTxt("CULA Error: Bailing out\n");
}
// returns array size in 3D coordinates (expanding with ones)
void get3DSize(int ref, int * mysize) {
int d;
for (d=0;d<3;d++)
if (d< cuda_array_dim[ref])
mysize[d]=cuda_array_size[ref][d];
else
mysize[d]=1;
}
int getCudaRefNum(const mxArray * arg) {
double cudaref;
if (! mxIsDouble(arg))
mexErrMsgTxt("cuda: Obtaining reference number. Number must be a double");
cudaref = mxGetScalar(arg);
/* printf("cuda: get ref %g, next free array %d\n",cudaref,free_array); */
CHECK_CUDAREF(cudaref);
if (cuda_array_size[(int) cudaref] == 0)
mexErrMsgTxt("cuda: Trying to access non-existing cuda reference.");
return (int) cudaref;
}
bool isComplexType(int ref) {
return (cuda_array_type[ref] >= fftHalfSComplex);
}
int getTotalSize(int dim,const int * sizevec) {
int totalsize=1,d;
for (d=0;d<dim;d++)
totalsize *= sizevec[d];
Dbg_printf2("Totalsize = %d\n",totalsize);
return totalsize;
}
int getTotalSizeFromRefNum(int pos) {
return getTotalSize(cuda_array_dim[pos],cuda_array_size[pos]);
}
int getTotalSizeFromRef(const mxArray * arg) {
return getTotalSizeFromRefNum(getCudaRefNum(arg));
}
int getTotalFloatSizeFromRef(const mxArray * arg) { // sizes in floating point numbers
int ref=getCudaRefNum(arg);
if (isComplexType(ref)) // this is a complex datatyp
return getTotalSizeFromRefNum(ref)*2;
else
return getTotalSizeFromRefNum(ref);
}
float * MemAlloc(int mysize) { // returns an array from the heap or a fresh array
#ifdef UseHeap
int p;
for (p=0;p<MAX_HEAP;p++)
if (mysize == memsize_heap[p])
{
memsize_heap[p]=0;
Dbg_printf2("Array allocated from heap %d\n",p);
float * tmp=(float *) mem_heap[p];
mem_heap[p]=0;
mem_heap_allocated--;
return tmp;
}
Dbg_printf2("No matching size in heap\n",mysize);
#endif
float * p_cuda_data; float ** pp_cuda_data= & p_cuda_data;
int custatus;
#ifdef AllocBlas
custatus = cublasAlloc((mysize+3)/sizeof(float), sizeof(float), (void**) pp_cuda_data);
if (custatus != CUBLAS_STATUS_SUCCESS) {
mexErrMsgTxt("cuda: Device memory allocation error (on card)\n");
return 0;
}
#else
custatus=cudaMalloc((void **) pp_cuda_data, mysize);
if (custatus!=cudaSuccess) { printf("cuda Malloc: %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("Bailing out");}
#endif
Dbg_printf2("Allocated %d bytes\n",mysize);
return p_cuda_data;
}
void MemFree(int ref) {
#ifdef UseHeap
int totalsize=getTotalSizeFromRefNum(ref) * sizeof(float);
int similarCnt=0;
int p;
for (p=0;p<MAX_HEAP;p++)
{
if (memsize_heap[p] == 0)
{
mem_heap[p]=(void *) cuda_arrays[ref];
memsize_heap[p]=totalsize;
cuda_arrays[ref]=0;
Dbg_printf3("Array reference %d stored to heap place %d\n",ref,p);
mem_heap_allocated++;
return;
}
if (totalsize == memsize_heap[p])
similarCnt++;
}
if (similarCnt > (int) sqrt(MAX_HEAP+1)) // enough of these there already
{
#endif
#ifdef AllocBlas
cublasFree(cuda_arrays[ref]);
#else
int custatus=cudaFree(cuda_arrays[ref]);
if (custatus!=cudaSuccess) { printf("cuda Free: %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("Bailing out");}
#endif
cuda_arrays[ref]=0;
#ifdef UseHeap
Dbg_printf2("Array reference %d freed entirely as already in heap\n",ref);
}
else // we need to free another one and keep this one
{
#ifdef AllocBlas
cublasFree(mem_heap[mem_heap_pos]);
#else
custatus=cudaFree(mem_heap[mem_heap_pos]);
if (custatus!=cudaSuccess) { printf("cuda Free: %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("Bailing out");}
#endif
mem_heap[mem_heap_pos]=(void *) cuda_arrays[ref];
memsize_heap[p]=totalsize;
cuda_arrays[ref]=0;
Dbg_printf3("Array reference %d kept but a different array %d freed from heap\n",ref,mem_heap_pos);
mem_heap_pos = (mem_heap_pos+1) % MAX_HEAP; // next time free a different one
}
#endif
}
int MatlabTypeFromCuda(int ref) { /// returns the Matlab class for the specified datatype
return CUDA_MATLAB_CLASS[cuda_array_type[ref]];
}
int MatlabRealCpxFromCuda(int ref) { // returns a specifier to indicate whether this is real or complex valued data in Matlab
if (!isComplexType(ref))
return mxREAL;
else
return mxCOMPLEX;
}
int cudaTypeFromArg(const char * MatlabString) {
int i;
/* Copy the string data from prhs[0] into a C string */
Dbg_printf2("cuda: type to allocate is %s\n",MatlabString);
// printf("cuda: Number of CUDA_TYPENAMES is %d\n",sizeof(CUDA_TYPE_NAMES));
// return 0;
for (i=0;CUDA_TYPE_NAMES[i][0] != 0;i++)
if (strcmp(MatlabString,CUDA_TYPE_NAMES[i])==0)
{
return i;
}
mexErrMsgTxt("cuda: Unknown type!\n");
return -1;
}
int updataFreeArray() { // looks for the next free position to store and array
int howmany=0;
int pos=free_array;
for(;cuda_array_size[pos] != 0;pos=(pos+1)%MAX_ARRAYS)
{ howmany++;
if (howmany > MAX_ARRAYS+1) {
printf("cuda: MAX_ARRAYS is %d\n",MAX_ARRAYS);
mexErrMsgTxt("cuda: Maximum number of allocatable arrays reached!\n");
return -1;
}
}
free_array=pos;
return free_array;
}
float * getCudaRef(const mxArray * arg) {
return cuda_arrays[getCudaRefNum(arg)];
}
void ReduceToHalfComplex(int pos) {
cuda_array_origFTsize[pos] = cuda_array_size[pos][0]; // needs to be stored to recover it when doing inverse FTs
cuda_array_size[pos][0] = ((int) ((cuda_array_size[pos][0]) / 2)) +1; // reduce size accordingly for half complex values
}
void ExpandToFullReal(int pos) {
cuda_array_size[pos][0] = cuda_array_origFTsize[pos]; // restore size for real space
}
void swapMatlabSize(int * mysize, int dims) {
int tmp=mysize[0];
if (dims>1)
{mysize[0]=mysize[1];mysize[1]=tmp;} // the bad matlab problem with x and y dimensions
}
void cudaCopySizeVec(int pos, const int * sizevec,int dims) { // copies a matlab sizevector to the array
double FTscale = 1.0;
int d;
cuda_array_size[pos]=calloc(dims,sizeof(cuda_array_size[0][0]));
for (d=0;d<dims;d++) {
cuda_array_size[pos][d]=sizevec[d]; // copy sizes
FTscale *= sizevec[d];
}
//swapMatlabSize(cuda_array_size[pos],dims);
cuda_array_FTscale[pos]=(float) (1.0/sqrt(FTscale));
cuda_array_dim[pos]=dims;
Dbg_printf2("CopySizeVec of %d dimensional vector\n",dims);
}
void cudaCopySizeVecD(int pos, const double * sizevec,int dims) { // copies a matlab sizevector to the array
double FTscale = 1.0;
int d;
cuda_array_size[pos]=calloc(dims,sizeof(cuda_array_size[0][0]));
for (d=0;d<dims;d++) {
cuda_array_size[pos][d]=(int) sizevec[d]; // copy sizes
FTscale *= sizevec[d];
}
//swapMatlabSize(cuda_array_size[pos],dims);
cuda_array_FTscale[pos]=(float) (1.0/sqrt(FTscale));
cuda_array_dim[pos]=dims;
Dbg_printf2("CopySizeVecD of %d dimensional vector\n",dims);
}
float * cudaAllocDetailed(int dims, const int * sizevec, int cuda_type) { // make a new array
float * p_cuda_data; // float ** pp_cuda_data=& p_cuda_data;
int pos=updataFreeArray(),ts;
cudaCopySizeVec(pos,sizevec,dims);
cuda_array_type[pos]=cuda_type;
ts=getTotalSize(dims,cuda_array_size[pos]);
if (ts>0) {
p_cuda_data=MemAlloc(ts*CUDA_TYPE_SIZE[cuda_type]);
//int custatus = cublasAlloc(ts, CUDA_TYPE_SIZE[cuda_type], (void**) pp_cuda_data);
//if (custatus != CUBLAS_STATUS_SUCCESS) {
// mexErrMsgTxt("cuda: Device memory allocation error (on card)\n");
// return 0;
//}
}
else p_cuda_data=0;
//if (cuda_type==fftHalfSComplex)
// cuda_array_size[pos][dims-1] = sizevec[dims-1]; // restore to the original value. Just the allocation needs to be bigger
cuda_arrays[pos]=p_cuda_data; // save it in the array
cuda_curr_arrays++;
Dbg_printf3("constructed cuda array nr %d of %d dimensions\n",pos,dims);
return p_cuda_data;
}
float * cudaAlloc(const mxArray * arg) { // make a new array with same properties as other array
int ref=getCudaRefNum(arg);
//swapMatlabSize(cuda_array_size[ref],cuda_array_dim[ref]); // pretend this is a matlab array until allocation is done
float * ret=cudaAllocDetailed(cuda_array_dim[ref], cuda_array_size[ref], cuda_array_type[ref]);
//swapMatlabSize(cuda_array_size[ref],cuda_array_dim[ref]); // swap back
cuda_array_origFTsize[free_array]=cuda_array_origFTsize[ref]; // needs to be copied when creating another HalfFourier array
cuda_array_FTscale[free_array]=cuda_array_FTscale[ref]; // to do the maginitude correction
cuda_array_type[free_array]=cuda_array_type[ref]; // type tags see CUDA_TYPE definitions above
return ret;
}
float * cudaAllocReal(const mxArray * arg) { // make a new array with same properties as other array, but ignores Complex and makes it Real
int ref=getCudaRefNum(arg);
//swapMatlabSize(cuda_array_size[ref],cuda_array_dim[ref]); // pretend this is a matlab array until allocation is done
float * ret=cudaAllocDetailed(cuda_array_dim[ref], cuda_array_size[ref], single);
//swapMatlabSize(cuda_array_size[ref],cuda_array_dim[ref]); // swap back
cuda_array_origFTsize[free_array]=cuda_array_origFTsize[ref]; // needs to be copied when creating another HalfFourier array
cuda_array_FTscale[free_array]=cuda_array_FTscale[ref]; // to do the maginitude correction
cuda_array_type[free_array]=single; // type tags see CUDA_TYPE definitions above
return ret;
}
float * cudaAllocComplex(const mxArray * arg) { // make a new array with same properties as other array, but ignores type and makes it Complex
int ref=getCudaRefNum(arg);
//swapMatlabSize(cuda_array_size[ref],cuda_array_dim[ref]); // pretend this is a matlab array until allocation is done
float * ret=cudaAllocDetailed(cuda_array_dim[ref], cuda_array_size[ref], scomplex);
//swapMatlabSize(cuda_array_size[ref],cuda_array_dim[ref]); // swap back
cuda_array_origFTsize[free_array]=cuda_array_origFTsize[ref]; // needs to be copied when creating another HalfFourier array
cuda_array_FTscale[free_array]=cuda_array_FTscale[ref]; // to do the maginitude correction
cuda_array_type[free_array]=scomplex; // type tags see CUDA_TYPE definitions above
return ret;
}
float * getMatlabFloatArray(const mxArray * arg, int * nd) {
(* nd) = mxGetNumberOfDimensions(arg);
// int * sz = mxGetDimensions(arg);
if (*nd > 0) {
/* Pointer for the real part of the input */
return (float *) mxGetData(arg);
}
mexErrMsgTxt("cuda: getMatlabFloatArray; data is zero dimensional\n");
return 0;
}
float * cudaPut(const mxArray * arg) { // copies Matlab array into cuda
int dims = mxGetNumberOfDimensions(arg);
const int * sizevec = mxGetDimensions(arg);
int ts;
int cuda_type = -1;
float * p_cuda_data=0;
const char * TypeName=mxGetClassName(arg);
Dbg_printf2("cudaPut Classname=%s\n",mxGetClassName(arg));
if (! mxIsSingle(arg))
mexErrMsgTxt("cuda: Datatype for cuda arrays needs to be single precision, or single precision complex\n");
ts=getTotalSize(dims,sizevec);
if (CUDAmaxSize() < ts)
mexErrMsgTxt("cuda: Array too big for available number of threads\n");
if (mxIsComplex(arg))
cuda_type = cudaTypeFromArg("scomplex");
else
cuda_type=cudaTypeFromArg(TypeName); // "single" Typename
if (mxIsComplex(arg))
{
p_cuda_data = cudaAllocDetailed(dims,sizevec,cuda_type);
/* Pointer for the real part of the input */
if (ts > 0) {
float * pr= (float *) mxGetPr(arg);
float * pi= (float *) mxGetPi(arg);
int custatus=cudaMemcpy2D(p_cuda_data, sizeof(float)*2,pr, sizeof(float), sizeof(float), ts, cudaMemcpyHostToDevice);
if (custatus!=cudaSuccess) { printf("cuda Memcpy2D: %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("Bailing out");}
//int custatus = cublasSetVector(ts, sizeof(pr[0]), pr, 1, p_cuda_data, 2);
//if (custatus != CUBLAS_STATUS_SUCCESS) {mexErrMsgTxt("cuda: Device access error (write C to cuda)\n");return 0;}
custatus=cudaMemcpy2D(p_cuda_data+1, sizeof(float)*2,pi, sizeof(float), sizeof(float), ts, cudaMemcpyHostToDevice);
if (custatus!=cudaSuccess) { printf("cuda Memcpy2D: %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("Bailing out");}
//custatus = cublasSetVector(getTotalSize(dims,sizevec), sizeof(pi[0]), pi, 1, p_cuda_data+1, 2);
//if (custatus != CUBLAS_STATUS_SUCCESS) {mexErrMsgTxt("cuda: Device access error (write C to cuda)\n");return 0;}
Dbg_printf("cuda: copied Complex data to device\n");
}
}
else
{
int nd;
/* Initialize the device matrices with the host matrices */
p_cuda_data = cudaAllocDetailed(dims,sizevec,cuda_type);
if (ts > 0) {
float * p_matlab_data = getMatlabFloatArray(arg, & nd);
int custatus=cudaMemcpy(p_cuda_data, p_matlab_data, sizeof(p_matlab_data[0])*ts, cudaMemcpyHostToDevice);
if (custatus!=cudaSuccess) { printf("cuda Memcpy: %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("Bailing out");}
//int custatus = cublasSetVector(ts, sizeof(p_matlab_data[0]), p_matlab_data, 1, p_cuda_data, 1);
//if (custatus != CUBLAS_STATUS_SUCCESS) {mexErrMsgTxt("cuda: Memcpy Device access error (write C to cuda)\n");return 0;}
Dbg_printf("cuda: copied Float data to device\n");
}
}
return p_cuda_data;
}
float * cudaPutVal(float value) { // writes a single value into a cuda array
float * p_cuda_data;
int custatus;
p_cuda_data=MemAlloc(sizeof(float));
/* Initialize the device matrices with the host matrices */
custatus=cudaMemcpy(p_cuda_data, &value, sizeof(value), cudaMemcpyHostToDevice);
if (custatus!=cudaSuccess) { printf("cuda Memcpy: %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("Bailing out");}
// custatus = cublasSetVector(1, sizeof(value), & value, 1, p_cuda_data, 1);
//if (custatus != CUBLAS_STATUS_SUCCESS) {
// mexErrMsgTxt("cuda: Device access error (write C value to cuda)\n");
// return 0;
//}
return p_cuda_data;
}
void cudaSetSize(const mxArray * arg, const mxArray * sizes) { // overwrites current sizes with new sizes
int pos=getCudaRefNum(arg);
// int sd = mxGetNumberOfDimensions(sizes);
const int * sv = mxGetDimensions(sizes);
int dims = sv[1];
const double * sizevec = mxGetPr(sizes);
if (cuda_array_size[pos] != 0)
{ free(cuda_array_size[pos]); cuda_array_size[pos]=0;}
cudaCopySizeVecD(pos,sizevec,dims);
return;
}
mxArray * cudaGetSize(const mxArray * arg) { // returns a vector with sizes
int ref=getCudaRefNum(arg);
mxArray * ret = mxCreateNumericMatrix(1, cuda_array_dim[ref], mxDOUBLE_CLASS, mxREAL);
double * ar = mxGetPr(ret); // pointer to real part of array
int d, dims=cuda_array_dim[ref];
//swapMatlabSize(cuda_array_size[ref],dims);
for (d=0;d<dims;d++)
ar[d] = cuda_array_size[ref][d];
//swapMatlabSize(cuda_array_size[ref],dims);
return ret;
}
mxArray * cudaGet(const mxArray * arg) { // from device to host
int ref=getCudaRefNum(arg);
//int cuda_type=cuda_array_type[ref];
//int dims=cuda_array_dim[ref];
//int saveddim=cuda_array_size[ref][dims-1];
//if (cuda_type==fftHalfSComplex)
// cuda_array_size[ref][dims-1] = ((int) saveddim)/2+1; // restore to the original value. Just the allocation needs to be bigger
mxArray * ret = 0;
double * ar =0;
double * ai=0;
int custatus;
/* Copy result back to host */
// cudaMemcpy( ar, getCudaRef(arg), getTypeSize(arg)*getTotalSizeFromRef(arg), cudaMemcpyDeviceToHost);
int totalsize=getTotalSizeFromRef(arg); // size in floating point values
Dbg_printf2("Memcpy totalsize in bytes: %d\n",sizeof(float)*totalsize);
if (totalsize*sizeof(float) < fastMemSize)
ar=(double *) fastMem;
else {
ret=mxCreateNumericArray(cuda_array_dim[ref], cuda_array_size[ref], MatlabTypeFromCuda(ref), MatlabRealCpxFromCuda(ref));
ar=mxGetPr(ret); // pointer to real part of array
}
if (MatlabRealCpxFromCuda(ref) == mxCOMPLEX)
{
/* Copy result back to host */
// cudaMemcpy( input_single, rhs_complex_d, sizeof(cufftComplex)*N*M*P, cudaMemcpyDeviceToHost);
//int custate=cudaMemcpy( ar, getCudaRef(arg), sizeof(cufftComplex)*N*M*P, cudaMemcpyDeviceToHost);
//if (custatus != cudaSucecss) {mexErrMsgTxt("cuda: Device access error (read real-part cuda to C)\n");return 0;}
//custatus = cublasGetVector(getTotalSizeFromRef(arg), CUDA_TYPE_SIZE[cuda_array_type[ref]], getCudaRef(arg), 1, ar, 1);
custatus=cudaMemcpy2D( ar, sizeof(float),getCudaRef(arg), sizeof(float)*2, sizeof(float), totalsize, cudaMemcpyDeviceToHost);
if (custatus!=cudaSuccess) { printf("cuda Get Memcpy2D: %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("Bailing out");}
if (totalsize*sizeof(float) < fastMemSize)
ai=(double *) fastMemI;
else
ai = mxGetPi(ret);
custatus=cudaMemcpy2D( ai, sizeof(float),getCudaRef(arg)+1, sizeof(float)*2, sizeof(float), totalsize, cudaMemcpyDeviceToHost);
if (custatus!=cudaSuccess) { printf("cuda Get Memcpy2D: %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("Bailing out");}
//custatus = cublasGetVector(totalsize, sizeof(float), getCudaRef(arg), 2, ar, 1);
//custatus = cublasGetVector(totalsize, sizeof(float), getCudaRef(arg)+1, 2, ai, 1);
//if (custatus != CUBLAS_STATUS_SUCCESS) {mexErrMsgTxt("cuda: Device access error (real-part cuda to C)\n");return 0;}
}
else
{
custatus=cudaMemcpy(ar, getCudaRef(arg), CUDA_TYPE_SIZE[cuda_array_type[ref]]*totalsize, cudaMemcpyDeviceToHost);
if (custatus!=cudaSuccess) { printf("cuda Get Memcpy2D: %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("Bailing out");}
//custatus = cublasGetVector(getTotalSizeFromRef(arg), CUDA_TYPE_SIZE[cuda_array_type[ref]], getCudaRef(arg), 1, ar, 1);
//if (custatus != CUBLAS_STATUS_SUCCESS) {mexErrMsgTxt("cuda: Device access error (cuda to C)\n");return 0;}
}
//if (cuda_type==fftHalfSComplex)
// cuda_array_size[ref][dims-1] = ((int) saveddim)/2+1; // restore to the original value. Just the allocation needs to be bigger
if (totalsize*sizeof(float) < fastMemSize) {
if (totalsize==1 && (MatlabRealCpxFromCuda(ref) != mxCOMPLEX))
ret = mxCreateDoubleScalar((double)((float *)fastMem)[0]);
else {
ret=mxCreateNumericArray(cuda_array_dim[ref], cuda_array_size[ref], MatlabTypeFromCuda(ref), MatlabRealCpxFromCuda(ref));
memcpy(mxGetPr(ret),fastMem,totalsize*sizeof(float));
if (MatlabRealCpxFromCuda(ref) == mxCOMPLEX)
memcpy(mxGetPi(ret),fastMemI,totalsize*sizeof(float));
}
}
Dbg_printf4("cuda: Got type %s sizeX %d sizeY %d\n",CUDA_TYPE_NAMES[cuda_array_type[ref]],cuda_array_size[ref][0],cuda_array_size[ref][1]);
return ret;
}
void cudaDelete(int cudaref) {
float * myref=cuda_arrays[cudaref];
if (cuda_array_size[cudaref] == 0)
mexErrMsgTxt("cuda: Attempt to delete non-existing reference\n");
if (myref != 0)
{
MemFree(cudaref);
// cudaFree(myref);
// cublasFree(myref);
cuda_arrays[cudaref]=0;
}
free(cuda_array_size[cudaref]); // free size information
cuda_array_size[cudaref]=0;
cuda_array_dim[cudaref]=0;
if (cuda_FFTplan[cudaref] != 0)
cufftDestroy(cuda_FFTplan[cudaref]); // delete the current plan (if exists)
cuda_FFTplan[cudaref]=0;
cuda_curr_arrays=cuda_curr_arrays-1; // reduce number of arrays by one
//free_array=cudaref; // to keep the array indices low
Dbg_printf2("cuda: deleted object reference %d\n",cudaref);
}
float * cloneArray(const mxArray * arg) {
float * myref= getCudaRef(arg);
float * newp=cudaAlloc(arg);
Dbg_printf2("copying array, total size = %d \n",getTotalFloatSizeFromRef(arg));
cublasScopy(getTotalFloatSizeFromRef(arg), myref, 1, newp, 1);
if (cublasGetError() != CUBLAS_STATUS_SUCCESS) {mexErrMsgTxt("cuda: Device access error (cloneArray)\n");return 0;}
return newp;
}
float * copyToCpx(const mxArray * arg) { // creates an array from real and upcasts it to complex
int ref=getCudaRefNum(arg);
float * myref= getCudaRef(arg),* newp;
if (cuda_array_type[ref] != single)
mexErrMsgTxt("cuda: Upcasting to complex. Type needs to be single\n");
cuda_array_type[ref]=scomplex; // only temporary for allocation below
newp=cudaAlloc(arg);
cuda_array_type[ref]=single; // reset
Dbg_printf2("copying array to Cpx, total size = %d \n",getTotalFloatSizeFromRef(arg));
cublasScopy(getTotalFloatSizeFromRef(arg), myref, 1, newp, 2); // just copy the real parts
cublasScopy(getTotalFloatSizeFromRef(arg), pZero, 0, newp+1, 2); // just copy the real parts
if (cublasGetError() != CUBLAS_STATUS_SUCCESS) {mexErrMsgTxt("cuda: Device access error (cloneArray)\n");return 0;}
return newp;
}
void CreateFFTPlan(int ref) {
cufftResult status=0;
if (cuda_FFTplan[ref] != 0)
{
cufftDestroy(cuda_FFTplan[ref]); // for now. Later: keep this plan and have one for forward and one for backward direction
// return 0;
}
//if (cuda_array_type[ref] == single)
//{
// cuda_array_type[ref] = fftSingle;
//}
/* Create plan for CUDA FFT */
// printf("FFT Error codes: %d, %d, %d, %d, %d ,%d ,%d, %d, %d, %d\n",CUFFT_SUCCESS,CUFFT_INVALID_PLAN,CUFFT_ALLOC_FAILED,CUFFT_INVALID_TYPE,CUFFT_INVALID_VALUE,CUFFT_INTERNAL_ERROR, CUFFT_EXEC_FAILED, CUFFT_SETUP_FAILED, 0, CUFFT_INVALID_SIZE);
if (cuda_array_dim[ref] == 1) {
Dbg_printf3("creating 1D-plan with sizes : %d of type %s\n",cuda_array_size[ref][0],CUDA_TYPE_NAMES[cuda_array_type[ref]]);
if (cuda_array_type[ref] == single)
status=cufftPlan1d(&cuda_FFTplan[ref], cuda_array_size[ref][0],CUFFT_R2C,1);
else if (cuda_array_type[ref] == fftHalfSComplex)
status=cufftPlan1d(&cuda_FFTplan[ref], cuda_array_origFTsize[ref],CUFFT_C2R,1);
else if (cuda_array_type[ref] == scomplex)
status=cufftPlan1d(&cuda_FFTplan[ref], cuda_array_size[ref][0],CUFFT_C2C,1);
else
mexErrMsgTxt("cuda: Datatype unsuitable for FFT\n");
}
else if (cuda_array_dim[ref] == 2 || (cuda_array_dim[ref] > 2 && cuda_array_size[ref][2] == 1)) {
Dbg_printf4("creating 2D-plan with sizes : %dx%d of type %s\n",cuda_array_size[ref][0],cuda_array_size[ref][1],CUDA_TYPE_NAMES[cuda_array_type[ref]]);
if (cuda_array_type[ref] == single)
status=cufftPlan2d(&cuda_FFTplan[ref], cuda_array_size[ref][1], cuda_array_size[ref][0], CUFFT_R2C);
else if (cuda_array_type[ref] == fftHalfSComplex)
status=cufftPlan2d(&cuda_FFTplan[ref], cuda_array_size[ref][1], cuda_array_origFTsize[ref], CUFFT_C2R);
else if (cuda_array_type[ref] == scomplex)
status=cufftPlan2d(&cuda_FFTplan[ref], cuda_array_size[ref][1], cuda_array_size[ref][0], CUFFT_C2C);
else
mexErrMsgTxt("cuda: Datatype unsuitable for FFT\n");
}
else if (cuda_array_dim[ref] > 2) {
Dbg_printf5("creating 3D-plan with sizes : %dx%dx%d of type %s\n",cuda_array_size[ref][0],cuda_array_size[ref][1],cuda_array_size[ref][2],CUDA_TYPE_NAMES[cuda_array_type[ref]]);
if (cuda_array_type[ref] == single)
status=cufftPlan3d(&cuda_FFTplan[ref], cuda_array_size[ref][2], cuda_array_size[ref][1], cuda_array_size[ref][0], CUFFT_R2C);
else if (cuda_array_type[ref] == fftHalfSComplex)
status=cufftPlan3d(&cuda_FFTplan[ref], cuda_array_size[ref][2], cuda_array_size[ref][1], cuda_array_size[ref][0], CUFFT_C2R);
else if (cuda_array_type[ref] == scomplex)
status=cufftPlan3d(&cuda_FFTplan[ref], cuda_array_size[ref][2], cuda_array_size[ref][1], cuda_array_size[ref][0], CUFFT_C2C);
else
mexErrMsgTxt("cuda: Datatype unsuitable for FFT\n");
}
if (status != CUFFT_SUCCESS) {printf("Error : %s",ERROR_NAMES[status]);mexErrMsgTxt("cuda: Error FFT Plan creation failed\n");return;}
}
/**************************************************************************/
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])
{
cublasStatus custatus;
//float * p_matlab_data1=0, * p_cuda_data1=0;
//float * p_matlab_data2=0, * p_cuda_data2=0;
//double cudaref1,cudaref2; // will be converted to in on usage
char *command;
size_t buflen;
//int mstatus;
if (mxIsChar(prhs[0]) != 1)
mexErrMsgTxt("Input 1 must be a string.");
if (mxGetM(prhs[0]) != 1)
mexErrMsgTxt("Input 1 must be a row vector.");
/* Get the length of the input string. */
buflen = (mxGetM(prhs[0]) * mxGetN(prhs[0])) + 1;
/* Allocate memory for input and output strings. */
command = (char*) mxCalloc(buflen, sizeof(char));
/* Copy the string data from prhs[0] into a C string */
mxGetString(prhs[0], command, (int) buflen);
if (!cuda_initialized) {
custatus = cublasInit();
if (custatus != CUBLAS_STATUS_SUCCESS) {
mexErrMsgTxt("cuda: CUBLAS initialization error\n");
return;
}
printf("initializing cuda\n");
pOne=cudaPutVal(1.0f);
pZero=cudaPutVal(0.0f);
custatus = cudaMallocHost(& fastMem, fastMemSize); // for fast copy operations
if (custatus!=cudaSuccess) { printf("cuda init MallocHost: %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("Bailing out");}
custatus = cudaMallocHost(& fastMemI, fastMemSize); // for fast copy operations
if (custatus!=cudaSuccess) { printf("cuda init MallocHost: %s\n",cudaGetErrorString(cudaGetLastError())); mexErrMsgTxt("Bailing out");}
#ifndef NOCULA
{
culaStatus s;
s=culaInitialize();
checkCULAStatus("Cula initialization",s);
}
#endif