-
Notifications
You must be signed in to change notification settings - Fork 27
/
my_cuda_rt.h
1256 lines (988 loc) · 39.3 KB
/
my_cuda_rt.h
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
#ifndef _MY_CUDA_H_
#define _MY_CUDA_H_
#include <cmath>
//#include <sys/time.h>
#if defined(_WIN32) && !defined(_WIN64)
//Only use this on 32bit Windows builds
#include <typeinfo.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <fstream>
#include <cassert>
#include <vector>
#include <cuda_runtime.h>
#include <vector_functions.h>
#include <iostream>
//Some easy to use typedefs
typedef float4 real4;
typedef float real;
#define make_real4 make_float4
typedef unsigned int uint;
using namespace std;
#define cl_mem void*
# define CU_SAFE_CALL_KERNEL( call , kernel ) CU_SAFE_CALL(call);
// This will output the proper CUDA error strings in the event that a CUDA host call returns an error
#define CU_SAFE_CALL(err) __checkCudaErrors (err, __FILE__, __LINE__)
inline void __checkCudaErrors(cudaError err, const char *file, const int line )
{
if(cudaSuccess != err)
{
fprintf(stderr, "%s(%i) : CUDA Runtime API error %d: %s.\n",file, line, (int)err, cudaGetErrorString( err ) );
exit(-1);
}
}
// This will output the proper error string when calling cudaGetLastError
#define getLastCudaError(msg) __getLastCudaError (msg, __FILE__, __LINE__)
inline void __getLastCudaError(const char *errorMessage, const char *file, const int line )
{
cudaError_t err = cudaGetLastError();
if (cudaSuccess != err)
{
fprintf(stderr, "%s(%i) : getLastCudaError() CUDA error : %s : (%d) %s.\n",
file, line, errorMessage, (int)err, cudaGetErrorString( err ) );
exit(-1);
}
}
// end of CUDA Helper Functions
//OpenCL to CUDA macro / functions
__inline__ cudaError_t clFinish(int param)
{
#if CUDART_VERSION >= 4000
return cudaDeviceSynchronize();
#else
return cudaThreadSynchronize();
#endif
}
static int getNumberOfCUDADevices()
{
// Get number of devices supporting CUDA
int temp = 0;
CU_SAFE_CALL(cudaGetDeviceCount(&temp));
return temp;
}
namespace my_dev {
class context {
protected:
size_t dev;
int ciDeviceCount;
int ciErrNum;
bool hContext_flag;
bool hInit_flag;
bool logfile_flag;
bool disable_timing;
ofstream *logFile;
int logID; //Unique ID to every log line
//Events:
cudaEvent_t start, stop;
//Compute capabilty, important for default compilation mode
int ccMajor;
int ccMinor;
int defaultComputeMode;
public:
int multiProcessorCount; //Required to configure parts of the code
context() {
hContext_flag = false;
hInit_flag = false;
logfile_flag = false;
disable_timing = false;
hInit_flag = true;
}
~context() {
if (hContext_flag )
{
}
}
int getComputeCapability() const { return 100 * ccMajor + 10 * ccMinor; }
int create(std::ofstream &log, bool disableTiming = false)
{
disable_timing = disableTiming;
logfile_flag = true;
logFile = &log;
logID = 0;
return create(disable_timing);
}
int create(bool disableT = false) {
assert(hInit_flag);
disable_timing = disableT;
printf("Creating CUDA context \n");
// Get number of devices supporting CUDA
ciDeviceCount = 0;
CU_SAFE_CALL(cudaGetDeviceCount(&ciDeviceCount));
printf("Found %d suitable devices: \n",ciDeviceCount);
for(int i=0; i < ciDeviceCount; i++)
{
cudaDeviceProp deviceProp;
cudaGetDeviceProperties(&deviceProp, i);
printf(" %d: %s\n",i, deviceProp.name);
}
return ciDeviceCount;
}
void createQueue(size_t dev = 0, int ctxCreateFlags = 0)
{
//use CU_CTX_MAP_HOST as flag for zero-copy memory
//Here we finally create and assign the context to a device
assert(!hContext_flag);
assert(hInit_flag);
this->dev = dev;
assert((int)dev < ciDeviceCount);
printf("Trying to use device: %d ...", (int)dev);
//Faster and async kernel launches when using large size arrays of local memory
//ctxCreateFlags |= CU_CTX_LMEM_RESIZE_TO_MAX;
//Create the context for this device handle
//CU_SAFE_CALL(cuCtxCreate(&hContext, ctxCreateFlags, hDevice));
int res = cudaSetDevice((int)dev);
if(res != cudaSuccess)
{
printf("failed (error #: %d), now trying all devices starting at 0 \n", res);
for(int i=0; i < ciDeviceCount; i++)
{
printf("Trying device: %d ...", i);
if(cudaSetDevice(i) != cudaSuccess)
{
printf("failed!\n");
if(i+1 == ciDeviceCount)
{
printf("All devices failed, exit! \n");
exit(0);
}
}
else
{
printf("success! \n");
this->dev = i;
break;
}
}
}
else
{
printf("success!\n");
}
cudaDeviceProp deviceProp;
CU_SAFE_CALL(cudaGetDeviceProperties(&deviceProp, (int)dev));
//Get the number of multiprocessors of the device
multiProcessorCount = deviceProp.multiProcessorCount;
ccMajor = deviceProp.major;
ccMinor = deviceProp.minor;
hContext_flag = true;
}
void startTiming(cudaStream_t stream=0)
{
if(disable_timing) return;
int eventflags = cudaEventDefault;
CU_SAFE_CALL(cudaEventCreateWithFlags(&start, eventflags));
CU_SAFE_CALL(cudaEventCreateWithFlags(&stop, eventflags));
CU_SAFE_CALL(cudaEventRecord(start, stream));
}
//Text and ID to be printed with the log message on screen / in the file
void stopTiming(const char *text, int type = -1, cudaStream_t stream=0)
{
if(disable_timing) return;
CU_SAFE_CALL(cudaEventRecord(stop, stream));
CU_SAFE_CALL(cudaEventSynchronize(stop));
float time;
CU_SAFE_CALL(cudaEventElapsedTime(&time, start, stop));
CU_SAFE_CALL(cudaEventDestroy(start));
CU_SAFE_CALL(cudaEventDestroy(stop));
printf("%s took:\t%f\t millisecond\n", text, time);
if(logfile_flag)
{
(*logFile) << logID++ << "\t" << type << "\t" << text << "\t" << time << endl;
}
}
/////////////
//Kept for compatability
int get_command_queue() {return 0;}
//////////
};
////////////////////////////////////////
//Class to handle streams / queues
class dev_stream
{
private:
cudaStream_t stream;
public:
dev_stream(unsigned int flags = 0)
{
createStream(flags);
}
void createStream(unsigned int flags = 0)
{
CU_SAFE_CALL(cudaStreamCreate(&stream));
}
void destroyStream()
{
CU_SAFE_CALL(cudaStreamDestroy(stream));
}
void sync()
{
CU_SAFE_CALL(cudaStreamSynchronize(stream));
}
bool isFinished()
{
cudaError_t res = cudaStreamQuery(stream);
if(res == cudaSuccess) return true;
if(res == cudaErrorNotReady) return false;
//Some other result
CU_SAFE_CALL(res);
return false;
}
cudaStream_t s()
{
return stream;
}
~dev_stream() {
destroyStream();
}
};
///////////////////////
class base_mem
{
public:
//Memory usage counters
static long long currentMemUsage;
static long long maxMemUsage;
void increaseMemUsage(int bytes)
{
currentMemUsage += bytes;
if(currentMemUsage > maxMemUsage)
maxMemUsage = currentMemUsage;
}
void decreaseMemUsage(int bytes)
{
currentMemUsage -= bytes;
}
static void printMemUsage()
{
printf("Current usage: %lld bytes ( %lld MB) \n", currentMemUsage, currentMemUsage / (1024*1024));
printf("Maximum usage: %lld bytes ( %lld MB) \n", maxMemUsage, maxMemUsage / (1024*1024));
size_t free, total;
cudaMemGetInfo(&free, &total);
printf("Build-in usage: free: %ld bytes ( %ld MB , total: %ld) \n", free, free / (1024*1024), total / (1024*1024));
}
static long long getMaxMemUsage()
{
return maxMemUsage;
}
};
template<class T>
class dev_mem : base_mem {
protected:
typedef struct textureInfo
{
const struct textureReference *texture;
int texOffset; //The possible extra offset when using textures and combined memory
int texSize;
} textureInfo;
vector<textureInfo> textures;
int size;
T *hDeviceMem;
T *host_ptr;
void *DeviceMemPtr;
void *tempDeviceMemPtr;
bool pinned_mem, context_flag, flags;
bool hDeviceMem_flag;
bool childMemory; //Indicates that this is a shared buffer that will be freed by a parent
void cuda_free() {
if(childMemory) //Only free if we are NOT a child
{
return;
}
// assert(context_flag);
if (hDeviceMem_flag)
{
assert(size > 0);
CU_SAFE_CALL(cudaFree(hDeviceMem));
decreaseMemUsage(size*sizeof(T));
if(pinned_mem){
CU_SAFE_CALL(cudaFreeHost((void*)host_ptr));}
else{
free(host_ptr);}
hDeviceMem_flag = false;
}
} //cuda_free
public:
///////// Constructors
dev_mem() {
size = 0;
pinned_mem = false;
hDeviceMem_flag = false;
context_flag = false;
host_ptr = NULL;
childMemory = false;
}
dev_mem(class context &c) {
size = 0;
pinned_mem = false;
context_flag = false;
hDeviceMem_flag = false;
host_ptr = NULL;
childMemory = false;
setContext(c);
}
//CUDA has no memory flags like opencl
//so just put it to 0 and keep function format same for
//compatability
dev_mem(class context &c, int n, bool zero = false,
int flags = 0, bool pinned = false) {
context_flag = false;
childMemory = false;
hDeviceMem_flag = false;
pinned_mem = pinned;
size = 0;
setContext(c);
if (zero) this->ccalloc(n, pinned, flags);
else this->cmalloc(n, pinned, flags);
}
// dev_mem(class context &c, std::vector<T> data,
// int flags = 0, bool pinned = false) {
// context_flag = false;
// hDeviceMem_flag = false;
// childMemory = false;
// pinned_mem = pinned;
// size = 0;
// setContext(c);
// this->cmalloc(data, flags);
// }
void free_mem()
{
cuda_free();
}
//////// Destructor
~dev_mem() {
cuda_free();
}
///////////
void setContext(class context &c) {
context_flag = true;
}
///////////
//Get the reference of memory allocated by another piece of memory
void cmalloc_copy(bool pinned, bool flags, void *cudaMem,
void* ParentHost_ptr, int offset, int n,
int allignOffset)
{
assert(context_flag);
this->pinned_mem = pinned;
this->flags = flags;
this->childMemory = true;
size = n;
//Dont forget to add the allignment values
//The following line has a bug, it first casts and then adds offset*sizeof ELEMENTS
//host_ptr = (T*)ParentHost_ptr + allignOffset*sizeof(uint);
//This line correctly increases the memory location with number of bytes before casting
host_ptr = (T*) ((char*)ParentHost_ptr + allignOffset*sizeof(uint));
#if 0 /* egaburov: to fix void* pointer arithmetic warrning . */
// hDeviceMem = (T*)(cudaMem + offset*sizeof(uint) + allignOffset*sizeof(uint));
#else
/* jbedorf: fixed so address is correct, casting before adding gives a different
* result. So divide by size of object */
hDeviceMem = (T*)cudaMem + ((offset*sizeof(uint) + allignOffset*sizeof(uint)) / sizeof(T));
//hDeviceMem = (T*)cudaMem + offset*sizeof(uint) + allignOffset*sizeof(uint);
#endif
DeviceMemPtr = (void*)(size_t)(hDeviceMem);
hDeviceMem_flag = true;
}
void cmalloc(int n, bool pinned = false, int flags = 0)
{
assert(context_flag);
// assert(!hDeviceMem_flag);
this->pinned_mem = pinned;
this->flags = (flags == 0) ? false : true;
if (size > 0) cuda_free();
size = n;
if(pinned_mem){
CU_SAFE_CALL(cudaMallocHost((T**)&host_ptr, size*sizeof(T)));}
else{
host_ptr = (T*)malloc(size*sizeof(T));}
CU_SAFE_CALL(cudaMalloc((T**)&hDeviceMem, size*sizeof(T)));
increaseMemUsage(size*sizeof(T));
DeviceMemPtr = (void*)(size_t)hDeviceMem;
hDeviceMem_flag = true;
}
void ccalloc(int n, bool pinned = false, int flags = 0) {
assert(context_flag);
// assert(!hDeviceMem_flag);
this->pinned_mem = pinned;
this->flags = (flags == 0) ? false : true;
if (size > 0) cuda_free();
size = n;
if(pinned_mem)
cudaMallocHost((T**)&host_ptr, size*sizeof(T));
else
host_ptr = (T*)calloc(size, sizeof(T));
CU_SAFE_CALL(cudaMalloc((T**)&hDeviceMem, size*sizeof(T)));
CU_SAFE_CALL(cudaMemset((void*)hDeviceMem, 0, size*sizeof(T)));
increaseMemUsage(size*sizeof(T));
DeviceMemPtr = (void*)(size_t)hDeviceMem;
hDeviceMem_flag = true;
}
//Set reduce to false to not reduce the size, to speed up pinned memory buffers
void cresize(int n, bool reduce = true)
{
if(size == n) //No need if we are already at the correct size
return;
if(size > n && reduce == false) //Do not make the memory size smaller
{
return;
}
// d2h(); //Get datafrom the device
if(pinned_mem)
{
//No realloc function so do it by hand
T *tmp_ptr;
CU_SAFE_CALL(cudaMallocHost((T**)&tmp_ptr, n*sizeof(T)));
//Copy old content to newly allocated mem
int tmpSize = min(size,n);
//Copy the old data to the new pointer and free the old location
memcpy (((void*) tmp_ptr), ((void*) host_ptr), tmpSize*sizeof(T));
CU_SAFE_CALL(cudaFreeHost((void*)host_ptr));
host_ptr = tmp_ptr;
}
else
{
//Resizes the current array
//New size is smaller, don't do anything with the allocated memory
host_ptr = (T*)realloc(host_ptr, n*sizeof(T));
}
//This version compared to the commented out one above, first allocates
//new memory and then copies the old one in the new one and free's the old one
T *hDeviceMemNew;
CU_SAFE_CALL(cudaMalloc((T**)&hDeviceMemNew, n*sizeof(T)));
increaseMemUsage(n*sizeof(T));
int nToCopy = min(size, n); //Do not copy more than we have memory
CU_SAFE_CALL(cudaMemcpy(hDeviceMemNew, hDeviceMem, nToCopy*sizeof(T), cudaMemcpyDeviceToDevice ));
//Now free the old memory
CU_SAFE_CALL(cudaFree(hDeviceMem));
decreaseMemUsage(size*sizeof(T));
hDeviceMem = hDeviceMemNew;
DeviceMemPtr = (void*)(size_t)hDeviceMem;
size = n;
//Rebind the textures
for(unsigned int i = 0; i < textures.size(); i++)
{
//Sometimes textures are only bound to a part of the total memory
//So check this
cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<T>();
if(textures[i].texOffset < 0)
{
CU_SAFE_CALL(cudaBindTexture (0, textures[i].texture, hDeviceMem,
&channelDesc, n*sizeof(T)));
}
else
{
void * tempPtr = a(textures[i].texOffset);
CU_SAFE_CALL(cudaBindTexture (0, textures[i].texture, tempPtr,
&channelDesc, sizeof(T)*textures[i].texSize));
}
}
}
//Set the memory to zero
void zeroMem()
{
assert(context_flag);
assert(hDeviceMem_flag);
memset(host_ptr, 0, size*sizeof(T));
CU_SAFE_CALL(cudaMemset((void*)hDeviceMem, 0, size*sizeof(T)));
}
///////////
//////////////
void d2h(bool OCL_BLOCKING = true, cudaStream_t stream = 0) {
assert(context_flag);
assert(hDeviceMem_flag);
assert(size > 0);
if(OCL_BLOCKING)
{
CU_SAFE_CALL(cudaMemcpy(&host_ptr[0], hDeviceMem, size*sizeof(T), cudaMemcpyDeviceToHost));
}
else
{
//Async copy, ONLY works for page-locked memory therefore default parameter
//is blocking.
assert(pinned_mem);
CU_SAFE_CALL(cudaMemcpyAsync(&host_ptr[0], hDeviceMem, size*sizeof(T),cudaMemcpyDeviceToHost, stream));
}
}
//D2h that only copies a certain number of items to the host
void d2h(int number, bool OCL_BLOCKING = true, cudaStream_t stream = 0) {
assert(context_flag);
assert(hDeviceMem_flag);
if(number == 0) return;
assert(size > 0);
if(OCL_BLOCKING)
{
CU_SAFE_CALL(cudaMemcpy(&host_ptr[0], hDeviceMem, number*sizeof(T),cudaMemcpyDeviceToHost));
}
else
{
//Async copy, ONLY works for page-locked memory therefore default parameter
//is blocking.
assert(pinned_mem);
CU_SAFE_CALL(cudaMemcpyAsync(&host_ptr[0], hDeviceMem, number*sizeof(T),cudaMemcpyDeviceToHost, stream));
}
}
void h2d(bool OCL_BLOCKING = true, cudaStream_t stream = 0) {
assert(context_flag);
assert(hDeviceMem_flag);
assert(size > 0);
//if (flags & CL_MEM_USE_HOST_PTR == 0) return;
if(OCL_BLOCKING)
{
CU_SAFE_CALL(cudaMemcpy(hDeviceMem, &host_ptr[0], size*sizeof(T),cudaMemcpyHostToDevice ));
}
else
{
//Async copy, ONLY works for page-locked memory therefore default parameter
//is blocking.
assert(pinned_mem);
CU_SAFE_CALL(cudaMemcpyAsync(hDeviceMem, host_ptr, size*sizeof(T),cudaMemcpyHostToDevice , stream));
}
}
//D2h that only copies a certain number of items to the host
void h2d(int number, bool OCL_BLOCKING = true, cudaStream_t stream = 0) {
assert(context_flag);
assert(hDeviceMem_flag);
assert(size > 0);
if(number == 0) return;
if(OCL_BLOCKING)
{
CU_SAFE_CALL(cudaMemcpy(hDeviceMem, &host_ptr[0], number*sizeof(T),cudaMemcpyHostToDevice));
}
else
{
//Async copy, ONLY works for page-locked memory therefore default parameter
//is blocking.
assert(pinned_mem);
CU_SAFE_CALL(cudaMemcpyAsync(hDeviceMem, host_ptr, number*sizeof(T),cudaMemcpyHostToDevice, stream));
}
}
//JB: Modified this so that it copies a device buffer to an other device
//buffer, and the host buffer to the other host buffer
void copy(dev_mem &src_buffer, int n, bool OCL_BLOCKING = true) {
assert(context_flag);
assert(hDeviceMem_flag);
if (size < n) {
cuda_free();
cmalloc(n, flags);
size = n;
printf("Resize in copy \n");
}
//Copy on the device
CU_SAFE_CALL(cudaMemcpy(hDeviceMem, src_buffer.d(), n*sizeof(T), cudaMemcpyDeviceToDevice));
//Copy on the host
memcpy (((void*) &host_ptr[0]), ((void*) &src_buffer[0]), n*sizeof(T));
}
/////////
T& operator[] (int i){ return host_ptr[i]; }
void * get_devMem() {return (void*)hDeviceMem;}
void* d() {return (void*)hDeviceMem;}
T* raw_p() {return hDeviceMem;}
void* p() {return &hDeviceMem;}
void* a(int offset)
{
//Calculate the new memory offset
//This fails because pointer is of type T and not of type void :-)
//return (void*)(size_t)(hDeviceMem + offset*sizeof(T));
//This works
return (void*)(size_t)(hDeviceMem + offset);
}
//Add a texture reference to the memory object
int addTexture(const struct textureReference *texref, int offset, int texSize)
{
textureInfo temp;
temp.texture = texref;
temp.texOffset = offset;
temp.texSize = texSize;
textures.push_back(temp);
return (int)(textures.size()-1);
}
int get_size(){return size;}
bool get_pinned(){return pinned_mem;}
bool get_flags(){return flags;}
}; // end of class dev_mem
////////////////////
class kernel {
protected:
char *hKernelFilename;
char *hKernelName;
vector<size_t> hGlobalWork;
vector<size_t> hLocalWork;
vector<void*> argumentList;
vector<int> argumentOffset;
//Kernel argument stuff
#define MAXKERNELARGUMENTS 128
typedef struct kernelArg
{
int alignment; //Alignment of the variable type
int sizeoftyp; //Size of the variable type
void* ptr; //The pointer to the memory
int size; //The number of elements (incase of shared memory)
const struct textureReference *texture; //If the arguments is a texture
cudaChannelFormatDesc channelDesc;
int texOffset; //The possible extra offset when using textures and combined memory
int texSize;
int texIdx;
#if 1 /* egaburov/harrism: to remove various uninitialized use warnings */
kernelArg() :
alignment(0), sizeoftyp(0), ptr(0), size(0), texture(0),
channelDesc(cudaCreateChannelDesc(0, 0, 0, 0, cudaChannelFormatKindNone)),
texOffset(0), texSize(0), texIdx(0) {}
#endif
} kernelArg;
std::vector<kernelArg> kernelArguments;
bool context_flag;
bool kernel_flag;
bool program_flag;
bool work_flag;
size_t sharedMemorySize;
int paramOffset;
public:
kernel() {
hKernelName = (char*)malloc(256);
hKernelFilename = (char*)malloc(1024);
hGlobalWork.clear();
hLocalWork.clear();
context_flag = false;
kernel_flag = false;
program_flag = false;
work_flag = false;
sharedMemorySize = 0;
paramOffset = 0;
//Kernel argument stuff
kernelArguments.resize(MAXKERNELARGUMENTS);
kernelArg argTemp;
argTemp.alignment = -1; argTemp.sizeoftyp = -1;
argTemp.ptr = NULL; argTemp.size = -1;
argTemp.texIdx = -1; argTemp.texOffset = 0;
kernelArguments.assign(MAXKERNELARGUMENTS, argTemp);
}
~kernel() {
free(hKernelName);
free(hKernelFilename);
}
kernel(class context &c) {
hKernelName = (char*)malloc(256);
hKernelFilename = (char*)malloc(1024);
hGlobalWork.clear();
hLocalWork.clear();
context_flag = false;
kernel_flag = false;
program_flag = false;
work_flag = false;
//Kernel argument stuff
kernelArguments.resize(MAXKERNELARGUMENTS);
kernelArg argTemp;
argTemp.alignment = -1; argTemp.sizeoftyp = -1;
argTemp.ptr = NULL; argTemp.size = -1;
argTemp.texIdx = -1; argTemp.texOffset = 0;
kernelArguments.assign(MAXKERNELARGUMENTS, argTemp);
sharedMemorySize = 0;
paramOffset = 0;
setContext(c);
}
////////////
void setContext(class context &c) {
assert(!context_flag);
context_flag = true;
}
////////////
void load_source(const char *fileName, string &ptx_source)
{
//Keep for compatability
}
void load_source(const char *kernel_name, const char *subfolder,
const char *compilerOptions = "",
int maxrregcount = -1,
int architecture = 0) {
assert(context_flag);
assert(!program_flag);
//In runtime kept for compatability
//In cuda version we assume that the code is already compiled into ptx
//so that the file loaded/specified is in fact a PTX file
sprintf(hKernelFilename, "%s%s", subfolder, kernel_name);
printf("Loading source: %s ...", hKernelFilename);
printf("done!\n");
program_flag = true;
}
void create(const char *kernel_name) {
//In runtime kept for compatability
assert(program_flag);
assert(!kernel_flag);
sprintf(hKernelName, kernel_name,"");
printf("%s \n", kernel_name);
kernel_flag = true;
}
void computeSharedMemorySize()
{
//We need to know size of shared memory before we set the arguments
//so a quick look to only compute the shared memory size
sharedMemorySize = 0;
//Loop over all set arguments and set them
for(int i=0; i < MAXKERNELARGUMENTS; i++)
{
//First of all check if this argument has to be set or that we've finished already
if(kernelArguments[i].size == -1)
continue;
//Now, check if this is a shared memory argument
if(kernelArguments[i].ptr == NULL && kernelArguments[i].size > 1)
{
//Increase the shared memory size
sharedMemorySize += (size_t) (kernelArguments[i].size*kernelArguments[i].sizeoftyp);
}
}//end for
}
//NVIDIA macro
#define ALIGN_UP(offset, alignment) (offset) = ((offset) + (alignment) - 1) & ~((alignment) -1)
void completeArguments()
{
//Reset the parameter offset and amount of shared memory
paramOffset = 0;
sharedMemorySize = 0;
//Loop over all set arguments and set them
for(int i=0; i < MAXKERNELARGUMENTS; i++)
{
//First of all check if this argument has to be set or that we've finished already
if(kernelArguments[i].size == -1)
continue;
if(kernelArguments[i].size == -2)
{
//This is a texture
cudaChannelFormatDesc channelDesc = kernelArguments[i].channelDesc;
CU_SAFE_CALL(cudaBindTexture(0, kernelArguments[i].texture,
kernelArguments[i].ptr,
&channelDesc,
kernelArguments[i].texSize));
continue;
}
//Now, check if this is a shared memory argument
if(kernelArguments[i].ptr == NULL && kernelArguments[i].size > 1)
{
//Increase the shared memory size
sharedMemorySize += (size_t) (kernelArguments[i].size*kernelArguments[i].sizeoftyp);
}
else
{
//This is an actual argument that we have to set
ALIGN_UP(paramOffset, kernelArguments[i].alignment);
CU_SAFE_CALL(cudaSetupArgument(kernelArguments[i].ptr, kernelArguments[i].sizeoftyp, paramOffset));
paramOffset += kernelArguments[i].sizeoftyp;
} //end if
}//end for
}//end completeArguments
//'size' is used for dynamic shared memory
//Cuda does not have a function like clSetKernelArg
//therefore we keep track of a vector with arguments
//that will be processed when we launch the kernel
template<class T>
void set_arg(unsigned int arg, void* ptr, int size = 1) {
assert(kernel_flag);
//TODO have to check / think about if we want size default initialised
//to 1 or to zero
kernelArg tempArg;