Fix T41328: Saving a copy changes lib paths
[blender-staging.git] / intern / cycles / device / device_cuda.cpp
1 /*
2  * Copyright 2011-2013 Blender Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License
15  */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20
21 #include "device.h"
22 #include "device_intern.h"
23
24 #include "buffers.h"
25
26 #include "cuew.h"
27 #include "util_debug.h"
28 #include "util_map.h"
29 #include "util_opengl.h"
30 #include "util_path.h"
31 #include "util_system.h"
32 #include "util_types.h"
33 #include "util_time.h"
34
35 CCL_NAMESPACE_BEGIN
36
37 class CUDADevice : public Device
38 {
39 public:
40         DedicatedTaskPool task_pool;
41         CUdevice cuDevice;
42         CUcontext cuContext;
43         CUmodule cuModule;
44         map<device_ptr, bool> tex_interp_map;
45         int cuDevId;
46         int cuDevArchitecture;
47         bool first_error;
48         bool use_texture_storage;
49
50         struct PixelMem {
51                 GLuint cuPBO;
52                 CUgraphicsResource cuPBOresource;
53                 GLuint cuTexId;
54                 int w, h;
55         };
56
57         map<device_ptr, PixelMem> pixel_mem_map;
58
59         CUdeviceptr cuda_device_ptr(device_ptr mem)
60         {
61                 return (CUdeviceptr)mem;
62         }
63
64         static bool have_precompiled_kernels()
65         {
66                 string cubins_path = path_get("lib");
67                 return path_exists(cubins_path);
68         }
69
70 /*#ifdef NDEBUG
71 #define cuda_abort()
72 #else
73 #define cuda_abort() abort()
74 #endif*/
75         void cuda_error_documentation()
76         {
77                 if(first_error) {
78                         fprintf(stderr, "\nRefer to the Cycles GPU rendering documentation for possible solutions:\n");
79                         fprintf(stderr, "http://wiki.blender.org/index.php/Doc:2.6/Manual/Render/Cycles/GPU_Rendering\n\n");
80                         first_error = false;
81                 }
82         }
83
84 #define cuda_assert(stmt) \
85         { \
86                 CUresult result = stmt; \
87                 \
88                 if(result != CUDA_SUCCESS) { \
89                         string message = string_printf("CUDA error: %s in %s", cuewErrorString(result), #stmt); \
90                         if(error_msg == "") \
91                                 error_msg = message; \
92                         fprintf(stderr, "%s\n", message.c_str()); \
93                         /*cuda_abort();*/ \
94                         cuda_error_documentation(); \
95                 } \
96         } (void)0
97
98         bool cuda_error_(CUresult result, const string& stmt)
99         {
100                 if(result == CUDA_SUCCESS)
101                         return false;
102
103                 string message = string_printf("CUDA error at %s: %s", stmt.c_str(), cuewErrorString(result));
104                 if(error_msg == "")
105                         error_msg = message;
106                 fprintf(stderr, "%s\n", message.c_str());
107                 cuda_error_documentation();
108                 return true;
109         }
110
111 #define cuda_error(stmt) cuda_error_(stmt, #stmt)
112
113         void cuda_error_message(const string& message)
114         {
115                 if(error_msg == "")
116                         error_msg = message;
117                 fprintf(stderr, "%s\n", message.c_str());
118                 cuda_error_documentation();
119         }
120
121         void cuda_push_context()
122         {
123                 cuda_assert(cuCtxSetCurrent(cuContext));
124         }
125
126         void cuda_pop_context()
127         {
128                 cuda_assert(cuCtxSetCurrent(NULL));
129         }
130
131         CUDADevice(DeviceInfo& info, Stats &stats, bool background_)
132         : Device(info, stats, background_)
133         {
134                 first_error = true;
135                 background = background_;
136                 use_texture_storage = true;
137
138                 cuDevId = info.num;
139                 cuDevice = 0;
140                 cuContext = 0;
141
142                 /* intialize */
143                 if(cuda_error(cuInit(0)))
144                         return;
145
146                 /* setup device and context */
147                 if(cuda_error(cuDeviceGet(&cuDevice, cuDevId)))
148                         return;
149
150                 CUresult result;
151
152                 if(background) {
153                         result = cuCtxCreate(&cuContext, 0, cuDevice);
154                 }
155                 else {
156                         result = cuGLCtxCreate(&cuContext, 0, cuDevice);
157
158                         if(result != CUDA_SUCCESS) {
159                                 result = cuCtxCreate(&cuContext, 0, cuDevice);
160                                 background = true;
161                         }
162                 }
163
164                 if(cuda_error_(result, "cuCtxCreate"))
165                         return;
166
167                 int major, minor;
168                 cuDeviceComputeCapability(&major, &minor, cuDevId);
169                 cuDevArchitecture = major*100 + minor*10;
170
171                 /* In order to use full 6GB of memory on Titan cards, use arrays instead
172                  * of textures. On earlier cards this seems slower, but on Titan it is
173                  * actually slightly faster in tests. */
174                 use_texture_storage = (cuDevArchitecture < 300);
175
176                 cuda_pop_context();
177         }
178
179         ~CUDADevice()
180         {
181                 task_pool.stop();
182
183                 cuda_assert(cuCtxDestroy(cuContext));
184         }
185
186         bool support_device(bool experimental)
187         {
188                 int major, minor;
189                 cuDeviceComputeCapability(&major, &minor, cuDevId);
190                 
191                 /* We only support sm_20 and above */
192                 if(major < 2) {
193                         cuda_error_message(string_printf("CUDA device supported only with compute capability 2.0 or up, found %d.%d.", major, minor));
194                         return false;
195                 }
196                 
197                 return true;
198         }
199
200         string compile_kernel()
201         {
202                 /* compute cubin name */
203                 int major, minor;
204                 cuDeviceComputeCapability(&major, &minor, cuDevId);
205
206                 /* attempt to use kernel provided with blender */
207                 string cubin = path_get(string_printf("lib/kernel_sm_%d%d.cubin", major, minor));
208                 if(path_exists(cubin))
209                         return cubin;
210
211                 /* not found, try to use locally compiled kernel */
212                 string kernel_path = path_get("kernel");
213                 string md5 = path_files_md5_hash(kernel_path);
214
215                 cubin = string_printf("cycles_kernel_sm%d%d_%s.cubin", major, minor, md5.c_str());
216                 cubin = path_user_get(path_join("cache", cubin));
217
218                 /* if exists already, use it */
219                 if(path_exists(cubin))
220                         return cubin;
221
222 #ifdef _WIN32
223                 if(have_precompiled_kernels()) {
224                         if(major < 2)
225                                 cuda_error_message(string_printf("CUDA device requires compute capability 2.0 or up, found %d.%d. Your GPU is not supported.", major, minor));
226                         else
227                                 cuda_error_message(string_printf("CUDA binary kernel for this graphics card compute capability (%d.%d) not found.", major, minor));
228                         return "";
229                 }
230 #endif
231
232                 /* if not, find CUDA compiler */
233                 const char *nvcc = cuewCompilerPath();
234
235                 if(nvcc == NULL) {
236                         cuda_error_message("CUDA nvcc compiler not found. Install CUDA toolkit in default location.");
237                         return "";
238                 }
239
240                 int cuda_version = cuewCompilerVersion();
241
242                 if(cuda_version == 0) {
243                         cuda_error_message("CUDA nvcc compiler version could not be parsed.");
244                         return "";
245                 }
246                 if(cuda_version < 50) {
247                         printf("Unsupported CUDA version %d.%d detected, you need CUDA 6.0.\n", cuda_version/10, cuda_version%10);
248                         return "";
249                 }
250                 else if(cuda_version != 60)
251                         printf("CUDA version %d.%d detected, build may succeed but only CUDA 6.0 is officially supported.\n", cuda_version/10, cuda_version%10);
252
253                 /* compile */
254                 string kernel = path_join(kernel_path, "kernel.cu");
255                 string include = kernel_path;
256                 const int machine = system_cpu_bits();
257
258                 double starttime = time_dt();
259                 printf("Compiling CUDA kernel ...\n");
260
261                 path_create_directories(cubin);
262
263                 string command = string_printf("\"%s\" -arch=sm_%d%d -m%d --cubin \"%s\" "
264                         "-o \"%s\" --ptxas-options=\"-v\" -I\"%s\" -DNVCC -D__KERNEL_CUDA_VERSION__=%d",
265                         nvcc, major, minor, machine, kernel.c_str(), cubin.c_str(), include.c_str(), cuda_version);
266
267                 printf("%s\n", command.c_str());
268
269                 if(system(command.c_str()) == -1) {
270                         cuda_error_message("Failed to execute compilation command, see console for details.");
271                         return "";
272                 }
273
274                 /* verify if compilation succeeded */
275                 if(!path_exists(cubin)) {
276                         cuda_error_message("CUDA kernel compilation failed, see console for details.");
277                         return "";
278                 }
279
280                 printf("Kernel compilation finished in %.2lfs.\n", time_dt() - starttime);
281
282                 return cubin;
283         }
284
285         bool load_kernels(bool experimental)
286         {
287                 /* check if cuda init succeeded */
288                 if(cuContext == 0)
289                         return false;
290                 
291                 /* check if GPU is supported */
292                 if(!support_device(experimental))
293                         return false;
294
295                 /* get kernel */
296                 string cubin = compile_kernel();
297
298                 if(cubin == "")
299                         return false;
300
301                 /* open module */
302                 cuda_push_context();
303
304                 string cubin_data;
305                 CUresult result;
306
307                 if (path_read_text(cubin, cubin_data))
308                         result = cuModuleLoadData(&cuModule, cubin_data.c_str());
309                 else
310                         result = CUDA_ERROR_FILE_NOT_FOUND;
311
312                 if(cuda_error_(result, "cuModuleLoad"))
313                         cuda_error_message(string_printf("Failed loading CUDA kernel %s.", cubin.c_str()));
314
315                 cuda_pop_context();
316
317                 return (result == CUDA_SUCCESS);
318         }
319
320         void mem_alloc(device_memory& mem, MemoryType type)
321         {
322                 cuda_push_context();
323                 CUdeviceptr device_pointer;
324                 size_t size = mem.memory_size();
325                 cuda_assert(cuMemAlloc(&device_pointer, size));
326                 mem.device_pointer = (device_ptr)device_pointer;
327                 stats.mem_alloc(size);
328                 cuda_pop_context();
329         }
330
331         void mem_copy_to(device_memory& mem)
332         {
333                 cuda_push_context();
334                 if(mem.device_pointer)
335                         cuda_assert(cuMemcpyHtoD(cuda_device_ptr(mem.device_pointer), (void*)mem.data_pointer, mem.memory_size()));
336                 cuda_pop_context();
337         }
338
339         void mem_copy_from(device_memory& mem, int y, int w, int h, int elem)
340         {
341                 size_t offset = elem*y*w;
342                 size_t size = elem*w*h;
343
344                 cuda_push_context();
345                 if(mem.device_pointer) {
346                         cuda_assert(cuMemcpyDtoH((uchar*)mem.data_pointer + offset,
347                                                  (CUdeviceptr)((uchar*)mem.device_pointer + offset), size));
348                 }
349                 else {
350                         memset((char*)mem.data_pointer + offset, 0, size);
351                 }
352                 cuda_pop_context();
353         }
354
355         void mem_zero(device_memory& mem)
356         {
357                 memset((void*)mem.data_pointer, 0, mem.memory_size());
358
359                 cuda_push_context();
360                 if(mem.device_pointer)
361                         cuda_assert(cuMemsetD8(cuda_device_ptr(mem.device_pointer), 0, mem.memory_size()));
362                 cuda_pop_context();
363         }
364
365         void mem_free(device_memory& mem)
366         {
367                 if(mem.device_pointer) {
368                         cuda_push_context();
369                         cuda_assert(cuMemFree(cuda_device_ptr(mem.device_pointer)));
370                         cuda_pop_context();
371
372                         mem.device_pointer = 0;
373
374                         stats.mem_free(mem.memory_size());
375                 }
376         }
377
378         void const_copy_to(const char *name, void *host, size_t size)
379         {
380                 CUdeviceptr mem;
381                 size_t bytes;
382
383                 cuda_push_context();
384                 cuda_assert(cuModuleGetGlobal(&mem, &bytes, cuModule, name));
385                 //assert(bytes == size);
386                 cuda_assert(cuMemcpyHtoD(mem, host, size));
387                 cuda_pop_context();
388         }
389
390         void tex_alloc(const char *name, device_memory& mem, InterpolationType interpolation, bool periodic)
391         {
392                 /* todo: support 3D textures, only CPU for now */
393
394                 /* determine format */
395                 CUarray_format_enum format;
396                 size_t dsize = datatype_size(mem.data_type);
397                 size_t size = mem.memory_size();
398                 bool use_texture = (interpolation != INTERPOLATION_NONE) || use_texture_storage;
399
400                 if(use_texture) {
401
402                         switch(mem.data_type) {
403                                 case TYPE_UCHAR: format = CU_AD_FORMAT_UNSIGNED_INT8; break;
404                                 case TYPE_UINT: format = CU_AD_FORMAT_UNSIGNED_INT32; break;
405                                 case TYPE_INT: format = CU_AD_FORMAT_SIGNED_INT32; break;
406                                 case TYPE_FLOAT: format = CU_AD_FORMAT_FLOAT; break;
407                                 default: assert(0); return;
408                         }
409
410                         CUtexref texref = NULL;
411
412                         cuda_push_context();
413                         cuda_assert(cuModuleGetTexRef(&texref, cuModule, name));
414
415                         if(!texref) {
416                                 cuda_pop_context();
417                                 return;
418                         }
419
420                         if(interpolation != INTERPOLATION_NONE) {
421                                 CUarray handle = NULL;
422                                 CUDA_ARRAY_DESCRIPTOR desc;
423
424                                 desc.Width = mem.data_width;
425                                 desc.Height = mem.data_height;
426                                 desc.Format = format;
427                                 desc.NumChannels = mem.data_elements;
428
429                                 cuda_assert(cuArrayCreate(&handle, &desc));
430
431                                 if(!handle) {
432                                         cuda_pop_context();
433                                         return;
434                                 }
435
436                                 if(mem.data_height > 1) {
437                                         CUDA_MEMCPY2D param;
438                                         memset(&param, 0, sizeof(param));
439                                         param.dstMemoryType = CU_MEMORYTYPE_ARRAY;
440                                         param.dstArray = handle;
441                                         param.srcMemoryType = CU_MEMORYTYPE_HOST;
442                                         param.srcHost = (void*)mem.data_pointer;
443                                         param.srcPitch = mem.data_width*dsize*mem.data_elements;
444                                         param.WidthInBytes = param.srcPitch;
445                                         param.Height = mem.data_height;
446
447                                         cuda_assert(cuMemcpy2D(&param));
448                                 }
449                                 else
450                                         cuda_assert(cuMemcpyHtoA(handle, 0, (void*)mem.data_pointer, size));
451
452                                 cuda_assert(cuTexRefSetArray(texref, handle, CU_TRSA_OVERRIDE_FORMAT));
453
454                                 if(interpolation == INTERPOLATION_CLOSEST) {
455                                         cuda_assert(cuTexRefSetFilterMode(texref, CU_TR_FILTER_MODE_POINT));
456                                 }
457                                 else if (interpolation == INTERPOLATION_LINEAR) {
458                                         cuda_assert(cuTexRefSetFilterMode(texref, CU_TR_FILTER_MODE_LINEAR));
459                                 }
460                                 else {/* CUBIC and SMART are unsupported for CUDA */
461                                         cuda_assert(cuTexRefSetFilterMode(texref, CU_TR_FILTER_MODE_LINEAR));
462                                 }
463                                 cuda_assert(cuTexRefSetFlags(texref, CU_TRSF_NORMALIZED_COORDINATES));
464
465                                 mem.device_pointer = (device_ptr)handle;
466
467                                 stats.mem_alloc(size);
468                         }
469                         else {
470                                 cuda_pop_context();
471
472                                 mem_alloc(mem, MEM_READ_ONLY);
473                                 mem_copy_to(mem);
474
475                                 cuda_push_context();
476
477                                 cuda_assert(cuTexRefSetAddress(NULL, texref, cuda_device_ptr(mem.device_pointer), size));
478                                 cuda_assert(cuTexRefSetFilterMode(texref, CU_TR_FILTER_MODE_POINT));
479                                 cuda_assert(cuTexRefSetFlags(texref, CU_TRSF_READ_AS_INTEGER));
480                         }
481
482                         if(periodic) {
483                                 cuda_assert(cuTexRefSetAddressMode(texref, 0, CU_TR_ADDRESS_MODE_WRAP));
484                                 cuda_assert(cuTexRefSetAddressMode(texref, 1, CU_TR_ADDRESS_MODE_WRAP));
485                         }
486                         else {
487                                 cuda_assert(cuTexRefSetAddressMode(texref, 0, CU_TR_ADDRESS_MODE_CLAMP));
488                                 cuda_assert(cuTexRefSetAddressMode(texref, 1, CU_TR_ADDRESS_MODE_CLAMP));
489                         }
490                         cuda_assert(cuTexRefSetFormat(texref, format, mem.data_elements));
491
492                         cuda_pop_context();
493                 }
494                 else {
495                         mem_alloc(mem, MEM_READ_ONLY);
496                         mem_copy_to(mem);
497
498                         cuda_push_context();
499
500                         CUdeviceptr cumem;
501                         size_t cubytes;
502
503                         cuda_assert(cuModuleGetGlobal(&cumem, &cubytes, cuModule, name));
504
505                         if(cubytes == 8) {
506                                 /* 64 bit device pointer */
507                                 uint64_t ptr = mem.device_pointer;
508                                 cuda_assert(cuMemcpyHtoD(cumem, (void*)&ptr, cubytes));
509                         }
510                         else {
511                                 /* 32 bit device pointer */
512                                 uint32_t ptr = (uint32_t)mem.device_pointer;
513                                 cuda_assert(cuMemcpyHtoD(cumem, (void*)&ptr, cubytes));
514                         }
515
516                         cuda_pop_context();
517                 }
518
519                 tex_interp_map[mem.device_pointer] = (interpolation != INTERPOLATION_NONE);
520         }
521
522         void tex_free(device_memory& mem)
523         {
524                 if(mem.device_pointer) {
525                         if(tex_interp_map[mem.device_pointer]) {
526                                 cuda_push_context();
527                                 cuArrayDestroy((CUarray)mem.device_pointer);
528                                 cuda_pop_context();
529
530                                 tex_interp_map.erase(tex_interp_map.find(mem.device_pointer));
531                                 mem.device_pointer = 0;
532
533                                 stats.mem_free(mem.memory_size());
534                         }
535                         else {
536                                 tex_interp_map.erase(tex_interp_map.find(mem.device_pointer));
537                                 mem_free(mem);
538                         }
539                 }
540         }
541
542         void path_trace(RenderTile& rtile, int sample, bool branched)
543         {
544                 if(have_error())
545                         return;
546
547                 cuda_push_context();
548
549                 CUfunction cuPathTrace;
550                 CUdeviceptr d_buffer = cuda_device_ptr(rtile.buffer);
551                 CUdeviceptr d_rng_state = cuda_device_ptr(rtile.rng_state);
552
553                 /* get kernel function */
554                 if(branched) {
555                         cuda_assert(cuModuleGetFunction(&cuPathTrace, cuModule, "kernel_cuda_branched_path_trace"));
556                 }
557                 else {
558                         cuda_assert(cuModuleGetFunction(&cuPathTrace, cuModule, "kernel_cuda_path_trace"));
559                 }
560
561                 if(have_error())
562                         return;
563
564                 /* pass in parameters */
565                 void *args[] = {&d_buffer,
566                                                  &d_rng_state,
567                                                  &sample,
568                                                  &rtile.x,
569                                                  &rtile.y,
570                                                  &rtile.w,
571                                                  &rtile.h,
572                                                  &rtile.offset,
573                                                  &rtile.stride};
574
575                 /* launch kernel */
576                 int threads_per_block;
577                 cuda_assert(cuFuncGetAttribute(&threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, cuPathTrace));
578
579                 /*int num_registers;
580                 cuda_assert(cuFuncGetAttribute(&num_registers, CU_FUNC_ATTRIBUTE_NUM_REGS, cuPathTrace));
581
582                 printf("threads_per_block %d\n", threads_per_block);
583                 printf("num_registers %d\n", num_registers);*/
584
585                 int xthreads = (int)sqrt((float)threads_per_block);
586                 int ythreads = (int)sqrt((float)threads_per_block);
587                 int xblocks = (rtile.w + xthreads - 1)/xthreads;
588                 int yblocks = (rtile.h + ythreads - 1)/ythreads;
589
590                 cuda_assert(cuFuncSetCacheConfig(cuPathTrace, CU_FUNC_CACHE_PREFER_L1));
591
592                 cuda_assert(cuLaunchKernel(cuPathTrace,
593                                                                    xblocks , yblocks, 1, /* blocks */
594                                                                    xthreads, ythreads, 1, /* threads */
595                                                                    0, 0, args, 0));
596
597                 cuda_assert(cuCtxSynchronize());
598
599                 cuda_pop_context();
600         }
601
602         void film_convert(DeviceTask& task, device_ptr buffer, device_ptr rgba_byte, device_ptr rgba_half)
603         {
604                 if(have_error())
605                         return;
606
607                 cuda_push_context();
608
609                 CUfunction cuFilmConvert;
610                 CUdeviceptr d_rgba = map_pixels((rgba_byte)? rgba_byte: rgba_half);
611                 CUdeviceptr d_buffer = cuda_device_ptr(buffer);
612
613                 /* get kernel function */
614                 if(rgba_half) {
615                         cuda_assert(cuModuleGetFunction(&cuFilmConvert, cuModule, "kernel_cuda_convert_to_half_float"));
616                 }
617                 else {
618                         cuda_assert(cuModuleGetFunction(&cuFilmConvert, cuModule, "kernel_cuda_convert_to_byte"));
619                 }
620
621
622                 float sample_scale = 1.0f/(task.sample + 1);
623
624                 /* pass in parameters */
625                 void *args[] = {&d_rgba,
626                                                  &d_buffer,
627                                                  &sample_scale,
628                                                  &task.x,
629                                                  &task.y,
630                                                  &task.w,
631                                                  &task.h,
632                                                  &task.offset,
633                                                  &task.stride};
634
635                 /* launch kernel */
636                 int threads_per_block;
637                 cuda_assert(cuFuncGetAttribute(&threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, cuFilmConvert));
638
639                 int xthreads = (int)sqrt((float)threads_per_block);
640                 int ythreads = (int)sqrt((float)threads_per_block);
641                 int xblocks = (task.w + xthreads - 1)/xthreads;
642                 int yblocks = (task.h + ythreads - 1)/ythreads;
643
644                 cuda_assert(cuFuncSetCacheConfig(cuFilmConvert, CU_FUNC_CACHE_PREFER_L1));
645
646                 cuda_assert(cuLaunchKernel(cuFilmConvert,
647                                                                    xblocks , yblocks, 1, /* blocks */
648                                                                    xthreads, ythreads, 1, /* threads */
649                                                                    0, 0, args, 0));
650
651                 unmap_pixels((rgba_byte)? rgba_byte: rgba_half);
652
653                 cuda_pop_context();
654         }
655
656         void shader(DeviceTask& task)
657         {
658                 if(have_error())
659                         return;
660
661                 cuda_push_context();
662
663                 CUfunction cuShader;
664                 CUdeviceptr d_input = cuda_device_ptr(task.shader_input);
665                 CUdeviceptr d_output = cuda_device_ptr(task.shader_output);
666
667                 /* get kernel function */
668                 if(task.shader_eval_type >= SHADER_EVAL_BAKE) {
669                         cuda_assert(cuModuleGetFunction(&cuShader, cuModule, "kernel_cuda_bake"));
670                 }
671                 else {
672                         cuda_assert(cuModuleGetFunction(&cuShader, cuModule, "kernel_cuda_shader"));
673                 }
674
675                 /* do tasks in smaller chunks, so we can cancel it */
676                 const int shader_chunk_size = 65536;
677                 const int start = task.shader_x;
678                 const int end = task.shader_x + task.shader_w;
679
680                 bool canceled = false;
681                 for(int sample = 0; sample < task.num_samples && !canceled; sample++) {
682                         for(int shader_x = start; shader_x < end; shader_x += shader_chunk_size) {
683                                 int shader_w = min(shader_chunk_size, end - shader_x);
684
685                                 /* pass in parameters */
686                                 void *args[] = {&d_input,
687                                                                  &d_output,
688                                                                  &task.shader_eval_type,
689                                                                  &shader_x,
690                                                                  &shader_w,
691                                                                  &sample};
692
693                                 /* launch kernel */
694                                 int threads_per_block;
695                                 cuda_assert(cuFuncGetAttribute(&threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, cuShader));
696
697                                 int xblocks = (shader_w + threads_per_block - 1)/threads_per_block;
698
699                                 cuda_assert(cuFuncSetCacheConfig(cuShader, CU_FUNC_CACHE_PREFER_L1));
700                                 cuda_assert(cuLaunchKernel(cuShader,
701                                                                                    xblocks , 1, 1, /* blocks */
702                                                                                    threads_per_block, 1, 1, /* threads */
703                                                                                    0, 0, args, 0));
704
705                                 cuda_assert(cuCtxSynchronize());
706
707                                 if(task.get_cancel()) {
708                                         canceled = false;
709                                         break;
710                                 }
711                         }
712
713                         task.update_progress(NULL);
714                 }
715
716                 cuda_pop_context();
717         }
718
719         CUdeviceptr map_pixels(device_ptr mem)
720         {
721                 if(!background) {
722                         PixelMem pmem = pixel_mem_map[mem];
723                         CUdeviceptr buffer;
724                         
725                         size_t bytes;
726                         cuda_assert(cuGraphicsMapResources(1, &pmem.cuPBOresource, 0));
727                         cuda_assert(cuGraphicsResourceGetMappedPointer(&buffer, &bytes, pmem.cuPBOresource));
728                         
729                         return buffer;
730                 }
731
732                 return cuda_device_ptr(mem);
733         }
734
735         void unmap_pixels(device_ptr mem)
736         {
737                 if(!background) {
738                         PixelMem pmem = pixel_mem_map[mem];
739
740                         cuda_assert(cuGraphicsUnmapResources(1, &pmem.cuPBOresource, 0));
741                 }
742         }
743
744         void pixels_alloc(device_memory& mem)
745         {
746                 if(!background) {
747                         PixelMem pmem;
748
749                         pmem.w = mem.data_width;
750                         pmem.h = mem.data_height;
751
752                         cuda_push_context();
753
754                         glGenBuffers(1, &pmem.cuPBO);
755                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pmem.cuPBO);
756                         if(mem.data_type == TYPE_HALF)
757                                 glBufferData(GL_PIXEL_UNPACK_BUFFER, pmem.w*pmem.h*sizeof(GLhalf)*4, NULL, GL_DYNAMIC_DRAW);
758                         else
759                                 glBufferData(GL_PIXEL_UNPACK_BUFFER, pmem.w*pmem.h*sizeof(uint8_t)*4, NULL, GL_DYNAMIC_DRAW);
760                         
761                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
762                         
763                         glGenTextures(1, &pmem.cuTexId);
764                         glBindTexture(GL_TEXTURE_2D, pmem.cuTexId);
765                         if(mem.data_type == TYPE_HALF)
766                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, pmem.w, pmem.h, 0, GL_RGBA, GL_HALF_FLOAT, NULL);
767                         else
768                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pmem.w, pmem.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
769                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
770                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
771                         glBindTexture(GL_TEXTURE_2D, 0);
772                         
773                         CUresult result = cuGraphicsGLRegisterBuffer(&pmem.cuPBOresource, pmem.cuPBO, CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE);
774
775                         if(result == CUDA_SUCCESS) {
776                                 cuda_pop_context();
777
778                                 mem.device_pointer = pmem.cuTexId;
779                                 pixel_mem_map[mem.device_pointer] = pmem;
780
781                                 stats.mem_alloc(mem.memory_size());
782
783                                 return;
784                         }
785                         else {
786                                 /* failed to register buffer, fallback to no interop */
787                                 glDeleteBuffers(1, &pmem.cuPBO);
788                                 glDeleteTextures(1, &pmem.cuTexId);
789
790                                 cuda_pop_context();
791
792                                 background = true;
793                         }
794                 }
795
796                 Device::pixels_alloc(mem);
797         }
798
799         void pixels_copy_from(device_memory& mem, int y, int w, int h)
800         {
801                 if(!background) {
802                         PixelMem pmem = pixel_mem_map[mem.device_pointer];
803
804                         cuda_push_context();
805
806                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pmem.cuPBO);
807                         uchar *pixels = (uchar*)glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_ONLY);
808                         size_t offset = sizeof(uchar)*4*y*w;
809                         memcpy((uchar*)mem.data_pointer + offset, pixels + offset, sizeof(uchar)*4*w*h);
810                         glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
811                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
812
813                         cuda_pop_context();
814
815                         return;
816                 }
817
818                 Device::pixels_copy_from(mem, y, w, h);
819         }
820
821         void pixels_free(device_memory& mem)
822         {
823                 if(mem.device_pointer) {
824                         if(!background) {
825                                 PixelMem pmem = pixel_mem_map[mem.device_pointer];
826
827                                 cuda_push_context();
828
829                                 cuda_assert(cuGraphicsUnregisterResource(pmem.cuPBOresource));
830                                 glDeleteBuffers(1, &pmem.cuPBO);
831                                 glDeleteTextures(1, &pmem.cuTexId);
832
833                                 cuda_pop_context();
834
835                                 pixel_mem_map.erase(pixel_mem_map.find(mem.device_pointer));
836                                 mem.device_pointer = 0;
837
838                                 stats.mem_free(mem.memory_size());
839
840                                 return;
841                         }
842
843                         Device::pixels_free(mem);
844                 }
845         }
846
847         void draw_pixels(device_memory& mem, int y, int w, int h, int dy, int width, int height, bool transparent,
848                 const DeviceDrawParams &draw_params)
849         {
850                 if(!background) {
851                         PixelMem pmem = pixel_mem_map[mem.device_pointer];
852
853                         cuda_push_context();
854
855                         /* for multi devices, this assumes the inefficient method that we allocate
856                          * all pixels on the device even though we only render to a subset */
857                         size_t offset = 4*y*w;
858
859                         if(mem.data_type == TYPE_HALF)
860                                 offset *= sizeof(GLhalf);
861                         else
862                                 offset *= sizeof(uint8_t);
863
864                         glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pmem.cuPBO);
865                         glBindTexture(GL_TEXTURE_2D, pmem.cuTexId);
866                         if(mem.data_type == TYPE_HALF)
867                                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_HALF_FLOAT, (void*)offset);
868                         else
869                                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, (void*)offset);
870                         glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0);
871                         
872                         glEnable(GL_TEXTURE_2D);
873                         
874                         if(transparent) {
875                                 glEnable(GL_BLEND);
876                                 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
877                         }
878
879                         glColor3f(1.0f, 1.0f, 1.0f);
880
881                         if(draw_params.bind_display_space_shader_cb) {
882                                 draw_params.bind_display_space_shader_cb();
883                         }
884
885                         glPushMatrix();
886                         glTranslatef(0.0f, (float)dy, 0.0f);
887                                 
888                         glBegin(GL_QUADS);
889                         
890                         glTexCoord2f(0.0f, 0.0f);
891                         glVertex2f(0.0f, 0.0f);
892                         glTexCoord2f((float)w/(float)pmem.w, 0.0f);
893                         glVertex2f((float)width, 0.0f);
894                         glTexCoord2f((float)w/(float)pmem.w, (float)h/(float)pmem.h);
895                         glVertex2f((float)width, (float)height);
896                         glTexCoord2f(0.0f, (float)h/(float)pmem.h);
897                         glVertex2f(0.0f, (float)height);
898
899                         glEnd();
900
901                         glPopMatrix();
902
903                         if(draw_params.unbind_display_space_shader_cb) {
904                                 draw_params.unbind_display_space_shader_cb();
905                         }
906
907                         if(transparent)
908                                 glDisable(GL_BLEND);
909                         
910                         glBindTexture(GL_TEXTURE_2D, 0);
911                         glDisable(GL_TEXTURE_2D);
912
913                         cuda_pop_context();
914
915                         return;
916                 }
917
918                 Device::draw_pixels(mem, y, w, h, dy, width, height, transparent, draw_params);
919         }
920
921         void thread_run(DeviceTask *task)
922         {
923                 if(task->type == DeviceTask::PATH_TRACE) {
924                         RenderTile tile;
925                         
926                         bool branched = task->integrator_branched;
927                         
928                         /* keep rendering tiles until done */
929                         while(task->acquire_tile(this, tile)) {
930                                 int start_sample = tile.start_sample;
931                                 int end_sample = tile.start_sample + tile.num_samples;
932
933                                 for(int sample = start_sample; sample < end_sample; sample++) {
934                                         if (task->get_cancel()) {
935                                                 if(task->need_finish_queue == false)
936                                                         break;
937                                         }
938
939                                         path_trace(tile, sample, branched);
940
941                                         tile.sample = sample + 1;
942
943                                         task->update_progress(&tile);
944                                 }
945
946                                 task->release_tile(tile);
947                         }
948                 }
949                 else if(task->type == DeviceTask::SHADER) {
950                         shader(*task);
951
952                         cuda_push_context();
953                         cuda_assert(cuCtxSynchronize());
954                         cuda_pop_context();
955                 }
956         }
957
958         class CUDADeviceTask : public DeviceTask {
959         public:
960                 CUDADeviceTask(CUDADevice *device, DeviceTask& task)
961                 : DeviceTask(task)
962                 {
963                         run = function_bind(&CUDADevice::thread_run, device, this);
964                 }
965         };
966
967         int get_split_task_count(DeviceTask& task)
968         {
969                 return 1;
970         }
971
972         void task_add(DeviceTask& task)
973         {
974                 if(task.type == DeviceTask::FILM_CONVERT) {
975                         /* must be done in main thread due to opengl access */
976                         film_convert(task, task.buffer, task.rgba_byte, task.rgba_half);
977
978                         cuda_push_context();
979                         cuda_assert(cuCtxSynchronize());
980                         cuda_pop_context();
981                 }
982                 else {
983                         task_pool.push(new CUDADeviceTask(this, task));
984                 }
985         }
986
987         void task_wait()
988         {
989                 task_pool.wait();
990         }
991
992         void task_cancel()
993         {
994                 task_pool.cancel();
995         }
996 };
997
998 bool device_cuda_init(void)
999 {
1000         static bool initialized = false;
1001         static bool result = false;
1002
1003         if (initialized)
1004                 return result;
1005
1006         initialized = true;
1007
1008         if (cuewInit() == CUEW_SUCCESS) {
1009                 if(CUDADevice::have_precompiled_kernels())
1010                         result = true;
1011 #ifndef _WIN32
1012                 else if(cuewCompilerPath() != NULL)
1013                         result = true;
1014 #endif
1015         }
1016
1017         return result;
1018 }
1019
1020 Device *device_cuda_create(DeviceInfo& info, Stats &stats, bool background)
1021 {
1022         return new CUDADevice(info, stats, background);
1023 }
1024
1025 void device_cuda_info(vector<DeviceInfo>& devices)
1026 {
1027         CUresult result;
1028         int count = 0;
1029
1030         result = cuInit(0);
1031         if(result != CUDA_SUCCESS) {
1032                 if(result != CUDA_ERROR_NO_DEVICE)
1033                         fprintf(stderr, "CUDA cuInit: %s\n", cuewErrorString(result));
1034                 return;
1035         }
1036
1037         result = cuDeviceGetCount(&count);
1038         if(result != CUDA_SUCCESS) {
1039                 fprintf(stderr, "CUDA cuDeviceGetCount: %s\n", cuewErrorString(result));
1040                 return;
1041         }
1042         
1043         vector<DeviceInfo> display_devices;
1044         
1045         for(int num = 0; num < count; num++) {
1046                 char name[256];
1047                 int attr;
1048                 
1049                 if(cuDeviceGetName(name, 256, num) != CUDA_SUCCESS)
1050                         continue;
1051
1052                 DeviceInfo info;
1053
1054                 info.type = DEVICE_CUDA;
1055                 info.description = string(name);
1056                 info.id = string_printf("CUDA_%d", num);
1057                 info.num = num;
1058
1059                 int major, minor;
1060                 cuDeviceComputeCapability(&major, &minor, num);
1061                 info.advanced_shading = (major >= 2);
1062                 info.extended_images = (major >= 3);
1063                 info.pack_images = false;
1064
1065                 /* if device has a kernel timeout, assume it is used for display */
1066                 if(cuDeviceGetAttribute(&attr, CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT, num) == CUDA_SUCCESS && attr == 1) {
1067                         info.display_device = true;
1068                         display_devices.push_back(info);
1069                 }
1070                 else
1071                         devices.push_back(info);
1072         }
1073
1074         if(!display_devices.empty())
1075                 devices.insert(devices.end(), display_devices.begin(), display_devices.end());
1076 }
1077
1078 CCL_NAMESPACE_END
1079