Code refactor: use device_only_memory and device_vector in more places.
[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 <climits>
18 #include <limits.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22
23 #include "device/device.h"
24 #include "device/device_denoising.h"
25 #include "device/device_intern.h"
26 #include "device/device_split_kernel.h"
27
28 #include "render/buffers.h"
29
30 #include "kernel/filter/filter_defines.h"
31
32 #ifdef WITH_CUDA_DYNLOAD
33 #  include "cuew.h"
34 #else
35 #  include "util/util_opengl.h"
36 #  include <cuda.h>
37 #  include <cudaGL.h>
38 #endif
39 #include "util/util_debug.h"
40 #include "util/util_logging.h"
41 #include "util/util_map.h"
42 #include "util/util_md5.h"
43 #include "util/util_opengl.h"
44 #include "util/util_path.h"
45 #include "util/util_string.h"
46 #include "util/util_system.h"
47 #include "util/util_types.h"
48 #include "util/util_time.h"
49
50 #include "kernel/split/kernel_split_data_types.h"
51
52 CCL_NAMESPACE_BEGIN
53
54 #ifndef WITH_CUDA_DYNLOAD
55
56 /* Transparently implement some functions, so majority of the file does not need
57  * to worry about difference between dynamically loaded and linked CUDA at all.
58  */
59
60 namespace {
61
62 const char *cuewErrorString(CUresult result)
63 {
64         /* We can only give error code here without major code duplication, that
65          * should be enough since dynamic loading is only being disabled by folks
66          * who knows what they're doing anyway.
67          *
68          * NOTE: Avoid call from several threads.
69          */
70         static string error;
71         error = string_printf("%d", result);
72         return error.c_str();
73 }
74
75 const char *cuewCompilerPath(void)
76 {
77         return CYCLES_CUDA_NVCC_EXECUTABLE;
78 }
79
80 int cuewCompilerVersion(void)
81 {
82         return (CUDA_VERSION / 100) + (CUDA_VERSION % 100 / 10);
83 }
84
85 }  /* namespace */
86 #endif  /* WITH_CUDA_DYNLOAD */
87
88 class CUDADevice;
89
90 class CUDASplitKernel : public DeviceSplitKernel {
91         CUDADevice *device;
92 public:
93         explicit CUDASplitKernel(CUDADevice *device);
94
95         virtual uint64_t state_buffer_size(device_memory& kg, device_memory& data, size_t num_threads);
96
97         virtual bool enqueue_split_kernel_data_init(const KernelDimensions& dim,
98                                                     RenderTile& rtile,
99                                                     int num_global_elements,
100                                                     device_memory& kernel_globals,
101                                                     device_memory& kernel_data_,
102                                                     device_memory& split_data,
103                                                     device_memory& ray_state,
104                                                     device_memory& queue_index,
105                                                     device_memory& use_queues_flag,
106                                                     device_memory& work_pool_wgs);
107
108         virtual SplitKernelFunction* get_split_kernel_function(const string& kernel_name,
109                                                                const DeviceRequestedFeatures&);
110         virtual int2 split_kernel_local_size();
111         virtual int2 split_kernel_global_size(device_memory& kg, device_memory& data, DeviceTask *task);
112 };
113
114 /* Utility to push/pop CUDA context. */
115 class CUDAContextScope {
116 public:
117         CUDAContextScope(CUDADevice *device);
118         ~CUDAContextScope();
119
120 private:
121         CUDADevice *device;
122 };
123
124 class CUDADevice : public Device
125 {
126 public:
127         DedicatedTaskPool task_pool;
128         CUdevice cuDevice;
129         CUcontext cuContext;
130         CUmodule cuModule, cuFilterModule;
131         map<device_ptr, bool> tex_interp_map;
132         map<device_ptr, CUtexObject> tex_bindless_map;
133         int cuDevId;
134         int cuDevArchitecture;
135         bool first_error;
136         CUDASplitKernel *split_kernel;
137
138         struct PixelMem {
139                 GLuint cuPBO;
140                 CUgraphicsResource cuPBOresource;
141                 GLuint cuTexId;
142                 int w, h;
143         };
144
145         map<device_ptr, PixelMem> pixel_mem_map;
146
147         /* Bindless Textures */
148         device_vector<TextureInfo> texture_info;
149         bool need_texture_info;
150
151         CUdeviceptr cuda_device_ptr(device_ptr mem)
152         {
153                 return (CUdeviceptr)mem;
154         }
155
156         static bool have_precompiled_kernels()
157         {
158                 string cubins_path = path_get("lib");
159                 return path_exists(cubins_path);
160         }
161
162         virtual bool show_samples() const
163         {
164                 /* The CUDADevice only processes one tile at a time, so showing samples is fine. */
165                 return true;
166         }
167
168 /*#ifdef NDEBUG
169 #define cuda_abort()
170 #else
171 #define cuda_abort() abort()
172 #endif*/
173         void cuda_error_documentation()
174         {
175                 if(first_error) {
176                         fprintf(stderr, "\nRefer to the Cycles GPU rendering documentation for possible solutions:\n");
177                         fprintf(stderr, "https://docs.blender.org/manual/en/dev/render/cycles/gpu_rendering.html\n\n");
178                         first_error = false;
179                 }
180         }
181
182 #define cuda_assert(stmt) \
183         { \
184                 CUresult result = stmt; \
185                 \
186                 if(result != CUDA_SUCCESS) { \
187                         string message = string_printf("CUDA error: %s in %s, line %d", cuewErrorString(result), #stmt, __LINE__); \
188                         if(error_msg == "") \
189                                 error_msg = message; \
190                         fprintf(stderr, "%s\n", message.c_str()); \
191                         /*cuda_abort();*/ \
192                         cuda_error_documentation(); \
193                 } \
194         } (void)0
195
196         bool cuda_error_(CUresult result, const string& stmt)
197         {
198                 if(result == CUDA_SUCCESS)
199                         return false;
200
201                 string message = string_printf("CUDA error at %s: %s", stmt.c_str(), cuewErrorString(result));
202                 if(error_msg == "")
203                         error_msg = message;
204                 fprintf(stderr, "%s\n", message.c_str());
205                 cuda_error_documentation();
206                 return true;
207         }
208
209 #define cuda_error(stmt) cuda_error_(stmt, #stmt)
210
211         void cuda_error_message(const string& message)
212         {
213                 if(error_msg == "")
214                         error_msg = message;
215                 fprintf(stderr, "%s\n", message.c_str());
216                 cuda_error_documentation();
217         }
218
219         CUDADevice(DeviceInfo& info, Stats &stats, bool background_)
220         : Device(info, stats, background_),
221           texture_info(this, "__texture_info")
222         {
223                 first_error = true;
224                 background = background_;
225
226                 cuDevId = info.num;
227                 cuDevice = 0;
228                 cuContext = 0;
229
230                 cuModule = 0;
231                 cuFilterModule = 0;
232
233                 split_kernel = NULL;
234
235                 need_texture_info = false;
236
237                 /* intialize */
238                 if(cuda_error(cuInit(0)))
239                         return;
240
241                 /* setup device and context */
242                 if(cuda_error(cuDeviceGet(&cuDevice, cuDevId)))
243                         return;
244
245                 CUresult result;
246
247                 if(background) {
248                         result = cuCtxCreate(&cuContext, 0, cuDevice);
249                 }
250                 else {
251                         result = cuGLCtxCreate(&cuContext, 0, cuDevice);
252
253                         if(result != CUDA_SUCCESS) {
254                                 result = cuCtxCreate(&cuContext, 0, cuDevice);
255                                 background = true;
256                         }
257                 }
258
259                 if(cuda_error_(result, "cuCtxCreate"))
260                         return;
261
262                 int major, minor;
263                 cuDeviceGetAttribute(&major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, cuDevId);
264                 cuDeviceGetAttribute(&minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, cuDevId);
265                 cuDevArchitecture = major*100 + minor*10;
266
267                 /* Pop context set by cuCtxCreate. */
268                 cuCtxPopCurrent(NULL);
269         }
270
271         ~CUDADevice()
272         {
273                 task_pool.stop();
274
275                 delete split_kernel;
276
277                 if(info.has_bindless_textures) {
278                         tex_free(texture_info);
279                 }
280
281                 cuda_assert(cuCtxDestroy(cuContext));
282         }
283
284         bool support_device(const DeviceRequestedFeatures& /*requested_features*/)
285         {
286                 int major, minor;
287                 cuDeviceGetAttribute(&major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, cuDevId);
288                 cuDeviceGetAttribute(&minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, cuDevId);
289
290                 /* We only support sm_20 and above */
291                 if(major < 2) {
292                         cuda_error_message(string_printf("CUDA device supported only with compute capability 2.0 or up, found %d.%d.", major, minor));
293                         return false;
294                 }
295
296                 return true;
297         }
298
299         bool use_adaptive_compilation()
300         {
301                 return DebugFlags().cuda.adaptive_compile;
302         }
303
304         bool use_split_kernel()
305         {
306                 return DebugFlags().cuda.split_kernel;
307         }
308
309         /* Common NVCC flags which stays the same regardless of shading model,
310          * kernel sources md5 and only depends on compiler or compilation settings.
311          */
312         string compile_kernel_get_common_cflags(
313                 const DeviceRequestedFeatures& requested_features,
314                 bool filter=false, bool split=false)
315         {
316                 const int cuda_version = cuewCompilerVersion();
317                 const int machine = system_cpu_bits();
318                 const string source_path = path_get("source");
319                 const string include_path = source_path;
320                 string cflags = string_printf("-m%d "
321                                               "--ptxas-options=\"-v\" "
322                                               "--use_fast_math "
323                                               "-DNVCC "
324                                               "-D__KERNEL_CUDA_VERSION__=%d "
325                                                "-I\"%s\"",
326                                               machine,
327                                               cuda_version,
328                                               include_path.c_str());
329                 if(!filter && use_adaptive_compilation()) {
330                         cflags += " " + requested_features.get_build_options();
331                 }
332                 const char *extra_cflags = getenv("CYCLES_CUDA_EXTRA_CFLAGS");
333                 if(extra_cflags) {
334                         cflags += string(" ") + string(extra_cflags);
335                 }
336 #ifdef WITH_CYCLES_DEBUG
337                 cflags += " -D__KERNEL_DEBUG__";
338 #endif
339
340                 if(split) {
341                         cflags += " -D__SPLIT__";
342                 }
343
344                 return cflags;
345         }
346
347         bool compile_check_compiler() {
348                 const char *nvcc = cuewCompilerPath();
349                 if(nvcc == NULL) {
350                         cuda_error_message("CUDA nvcc compiler not found. "
351                                            "Install CUDA toolkit in default location.");
352                         return false;
353                 }
354                 const int cuda_version = cuewCompilerVersion();
355                 VLOG(1) << "Found nvcc " << nvcc
356                         << ", CUDA version " << cuda_version
357                         << ".";
358                 const int major = cuda_version / 10, minor = cuda_version & 10;
359                 if(cuda_version == 0) {
360                         cuda_error_message("CUDA nvcc compiler version could not be parsed.");
361                         return false;
362                 }
363                 if(cuda_version < 80) {
364                         printf("Unsupported CUDA version %d.%d detected, "
365                                "you need CUDA 8.0 or newer.\n",
366                                major, minor);
367                         return false;
368                 }
369                 else if(cuda_version != 80) {
370                         printf("CUDA version %d.%d detected, build may succeed but only "
371                                "CUDA 8.0 is officially supported.\n",
372                                major, minor);
373                 }
374                 return true;
375         }
376
377         string compile_kernel(const DeviceRequestedFeatures& requested_features,
378                               bool filter=false, bool split=false)
379         {
380                 const char *name, *source;
381                 if(filter) {
382                         name = "filter";
383                         source = "filter.cu";
384                 }
385                 else if(split) {
386                         name = "kernel_split";
387                         source = "kernel_split.cu";
388                 }
389                 else {
390                         name = "kernel";
391                         source = "kernel.cu";
392                 }
393                 /* Compute cubin name. */
394                 int major, minor;
395                 cuDeviceGetAttribute(&major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, cuDevId);
396                 cuDeviceGetAttribute(&minor, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, cuDevId);
397
398                 /* Attempt to use kernel provided with Blender. */
399                 if(!use_adaptive_compilation()) {
400                         const string cubin = path_get(string_printf("lib/%s_sm_%d%d.cubin",
401                                                                     name, major, minor));
402                         VLOG(1) << "Testing for pre-compiled kernel " << cubin << ".";
403                         if(path_exists(cubin)) {
404                                 VLOG(1) << "Using precompiled kernel.";
405                                 return cubin;
406                         }
407                 }
408
409                 const string common_cflags =
410                         compile_kernel_get_common_cflags(requested_features, filter, split);
411
412                 /* Try to use locally compiled kernel. */
413                 const string source_path = path_get("source");
414                 const string kernel_md5 = path_files_md5_hash(source_path);
415
416                 /* We include cflags into md5 so changing cuda toolkit or changing other
417                  * compiler command line arguments makes sure cubin gets re-built.
418                  */
419                 const string cubin_md5 = util_md5_string(kernel_md5 + common_cflags);
420
421                 const string cubin_file = string_printf("cycles_%s_sm%d%d_%s.cubin",
422                                                         name, major, minor,
423                                                         cubin_md5.c_str());
424                 const string cubin = path_cache_get(path_join("kernels", cubin_file));
425                 VLOG(1) << "Testing for locally compiled kernel " << cubin << ".";
426                 if(path_exists(cubin)) {
427                         VLOG(1) << "Using locally compiled kernel.";
428                         return cubin;
429                 }
430
431 #ifdef _WIN32
432                 if(have_precompiled_kernels()) {
433                         if(major < 2) {
434                                 cuda_error_message(string_printf(
435                                         "CUDA device requires compute capability 2.0 or up, "
436                                         "found %d.%d. Your GPU is not supported.",
437                                         major, minor));
438                         }
439                         else {
440                                 cuda_error_message(string_printf(
441                                         "CUDA binary kernel for this graphics card compute "
442                                         "capability (%d.%d) not found.",
443                                         major, minor));
444                         }
445                         return "";
446                 }
447 #endif
448
449                 /* Compile. */
450                 if(!compile_check_compiler()) {
451                         return "";
452                 }
453                 const char *nvcc = cuewCompilerPath();
454                 const string kernel = path_join(
455                         path_join(source_path, "kernel"),
456                         path_join("kernels",
457                                   path_join("cuda", source)));
458                 double starttime = time_dt();
459                 printf("Compiling CUDA kernel ...\n");
460
461                 path_create_directories(cubin);
462
463                 string command = string_printf("\"%s\" "
464                                                "-arch=sm_%d%d "
465                                                "--cubin \"%s\" "
466                                                "-o \"%s\" "
467                                                "%s ",
468                                                nvcc,
469                                                major, minor,
470                                                kernel.c_str(),
471                                                cubin.c_str(),
472                                                common_cflags.c_str());
473
474                 printf("%s\n", command.c_str());
475
476                 if(system(command.c_str()) == -1) {
477                         cuda_error_message("Failed to execute compilation command, "
478                                            "see console for details.");
479                         return "";
480                 }
481
482                 /* Verify if compilation succeeded */
483                 if(!path_exists(cubin)) {
484                         cuda_error_message("CUDA kernel compilation failed, "
485                                            "see console for details.");
486                         return "";
487                 }
488
489                 printf("Kernel compilation finished in %.2lfs.\n", time_dt() - starttime);
490
491                 return cubin;
492         }
493
494         bool load_kernels(const DeviceRequestedFeatures& requested_features)
495         {
496                 /* TODO(sergey): Support kernels re-load for CUDA devices.
497                  *
498                  * Currently re-loading kernel will invalidate memory pointers,
499                  * causing problems in cuCtxSynchronize.
500                  */
501                 if(cuFilterModule && cuModule) {
502                         VLOG(1) << "Skipping kernel reload, not currently supported.";
503                         return true;
504                 }
505
506                 /* check if cuda init succeeded */
507                 if(cuContext == 0)
508                         return false;
509
510                 /* check if GPU is supported */
511                 if(!support_device(requested_features))
512                         return false;
513
514                 /* get kernel */
515                 string cubin = compile_kernel(requested_features, false, use_split_kernel());
516                 if(cubin == "")
517                         return false;
518
519                 string filter_cubin = compile_kernel(requested_features, true, false);
520                 if(filter_cubin == "")
521                         return false;
522
523                 /* open module */
524                 CUDAContextScope scope(this);
525
526                 string cubin_data;
527                 CUresult result;
528
529                 if(path_read_text(cubin, cubin_data))
530                         result = cuModuleLoadData(&cuModule, cubin_data.c_str());
531                 else
532                         result = CUDA_ERROR_FILE_NOT_FOUND;
533
534                 if(cuda_error_(result, "cuModuleLoad"))
535                         cuda_error_message(string_printf("Failed loading CUDA kernel %s.", cubin.c_str()));
536
537                 if(path_read_text(filter_cubin, cubin_data))
538                         result = cuModuleLoadData(&cuFilterModule, cubin_data.c_str());
539                 else
540                         result = CUDA_ERROR_FILE_NOT_FOUND;
541
542                 if(cuda_error_(result, "cuModuleLoad"))
543                         cuda_error_message(string_printf("Failed loading CUDA kernel %s.", filter_cubin.c_str()));
544
545                 return (result == CUDA_SUCCESS);
546         }
547
548         void load_texture_info()
549         {
550                 if(info.has_bindless_textures && need_texture_info) {
551                         tex_free(texture_info);
552                         tex_alloc(texture_info);
553                         need_texture_info = false;
554                 }
555         }
556
557         void mem_alloc(device_memory& mem)
558         {
559                 CUDAContextScope scope(this);
560
561                 if(mem.name) {
562                         VLOG(1) << "Buffer allocate: " << mem.name << ", "
563                                 << string_human_readable_number(mem.memory_size()) << " bytes. ("
564                                 << string_human_readable_size(mem.memory_size()) << ")";
565                 }
566
567                 CUdeviceptr device_pointer;
568                 size_t size = mem.memory_size();
569                 cuda_assert(cuMemAlloc(&device_pointer, size));
570                 mem.device_pointer = (device_ptr)device_pointer;
571                 mem.device_size = size;
572                 stats.mem_alloc(size);
573         }
574
575         void mem_copy_to(device_memory& mem)
576         {
577                 CUDAContextScope scope(this);
578
579                 if(mem.device_pointer)
580                         cuda_assert(cuMemcpyHtoD(cuda_device_ptr(mem.device_pointer), (void*)mem.data_pointer, mem.memory_size()));
581         }
582
583         void mem_copy_from(device_memory& mem, int y, int w, int h, int elem)
584         {
585                 CUDAContextScope scope(this);
586                 size_t offset = elem*y*w;
587                 size_t size = elem*w*h;
588
589                 if(mem.device_pointer) {
590                         cuda_assert(cuMemcpyDtoH((uchar*)mem.data_pointer + offset,
591                                                  (CUdeviceptr)(mem.device_pointer + offset), size));
592                 }
593                 else {
594                         memset((char*)mem.data_pointer + offset, 0, size);
595                 }
596         }
597
598         void mem_zero(device_memory& mem)
599         {
600                 if(mem.data_pointer) {
601                         memset((void*)mem.data_pointer, 0, mem.memory_size());
602                 }
603
604                 if(mem.device_pointer) {
605                         CUDAContextScope scope(this);
606                         cuda_assert(cuMemsetD8(cuda_device_ptr(mem.device_pointer), 0, mem.memory_size()));
607                 }
608         }
609
610         void mem_free(device_memory& mem)
611         {
612                 if(mem.device_pointer) {
613                         CUDAContextScope scope(this);
614                         cuda_assert(cuMemFree(cuda_device_ptr(mem.device_pointer)));
615
616                         mem.device_pointer = 0;
617
618                         stats.mem_free(mem.device_size);
619                         mem.device_size = 0;
620                 }
621         }
622
623         virtual device_ptr mem_alloc_sub_ptr(device_memory& mem, int offset, int /*size*/)
624         {
625                 return (device_ptr) (((char*) mem.device_pointer) + mem.memory_elements_size(offset));
626         }
627
628         void const_copy_to(const char *name, void *host, size_t size)
629         {
630                 CUDAContextScope scope(this);
631                 CUdeviceptr mem;
632                 size_t bytes;
633
634                 cuda_assert(cuModuleGetGlobal(&mem, &bytes, cuModule, name));
635                 //assert(bytes == size);
636                 cuda_assert(cuMemcpyHtoD(mem, host, size));
637         }
638
639         void tex_alloc(device_memory& mem)
640         {
641                 CUDAContextScope scope(this);
642
643                 VLOG(1) << "Texture allocate: " << mem.name << ", "
644                         << string_human_readable_number(mem.memory_size()) << " bytes. ("
645                         << string_human_readable_size(mem.memory_size()) << ")";
646
647                 /* Check if we are on sm_30 or above, for bindless textures. */
648                 bool has_bindless_textures = info.has_bindless_textures;
649
650                 /* General variables for both architectures */
651                 string bind_name = mem.name;
652                 size_t dsize = datatype_size(mem.data_type);
653                 size_t size = mem.memory_size();
654
655                 CUaddress_mode address_mode = CU_TR_ADDRESS_MODE_WRAP;
656                 switch(mem.extension) {
657                         case EXTENSION_REPEAT:
658                                 address_mode = CU_TR_ADDRESS_MODE_WRAP;
659                                 break;
660                         case EXTENSION_EXTEND:
661                                 address_mode = CU_TR_ADDRESS_MODE_CLAMP;
662                                 break;
663                         case EXTENSION_CLIP:
664                                 address_mode = CU_TR_ADDRESS_MODE_BORDER;
665                                 break;
666                         default:
667                                 assert(0);
668                                 break;
669                 }
670
671                 CUfilter_mode filter_mode;
672                 if(mem.interpolation == INTERPOLATION_CLOSEST) {
673                         filter_mode = CU_TR_FILTER_MODE_POINT;
674                 }
675                 else {
676                         filter_mode = CU_TR_FILTER_MODE_LINEAR;
677                 }
678
679                 /* General variables for Fermi */
680                 CUtexref texref = NULL;
681
682                 if(!has_bindless_textures && mem.interpolation != INTERPOLATION_NONE) {
683                         if(mem.data_depth > 1) {
684                                 /* Kernel uses different bind names for 2d and 3d float textures,
685                                  * so we have to adjust couple of things here.
686                                  */
687                                 vector<string> tokens;
688                                 string_split(tokens, mem.name, "_");
689                                 bind_name = string_printf("__tex_image_%s_3d_%s",
690                                                           tokens[2].c_str(),
691                                                           tokens[3].c_str());
692                         }
693
694                         cuda_assert(cuModuleGetTexRef(&texref, cuModule, bind_name.c_str()));
695
696                         if(!texref) {
697                                 return;
698                         }
699                 }
700
701                 if(mem.interpolation == INTERPOLATION_NONE) {
702                         /* Data Storage */
703                         mem_alloc(mem);
704                         mem_copy_to(mem);
705
706                         CUdeviceptr cumem;
707                         size_t cubytes;
708
709                         cuda_assert(cuModuleGetGlobal(&cumem, &cubytes, cuModule, bind_name.c_str()));
710
711                         if(cubytes == 8) {
712                                 /* 64 bit device pointer */
713                                 uint64_t ptr = mem.device_pointer;
714                                 cuda_assert(cuMemcpyHtoD(cumem, (void*)&ptr, cubytes));
715                         }
716                         else {
717                                 /* 32 bit device pointer */
718                                 uint32_t ptr = (uint32_t)mem.device_pointer;
719                                 cuda_assert(cuMemcpyHtoD(cumem, (void*)&ptr, cubytes));
720                         }
721                 }
722                 else {
723                         /* Texture Storage */
724                         CUarray handle = NULL;
725
726                         CUarray_format_enum format;
727                         switch(mem.data_type) {
728                                 case TYPE_UCHAR: format = CU_AD_FORMAT_UNSIGNED_INT8; break;
729                                 case TYPE_UINT: format = CU_AD_FORMAT_UNSIGNED_INT32; break;
730                                 case TYPE_INT: format = CU_AD_FORMAT_SIGNED_INT32; break;
731                                 case TYPE_FLOAT: format = CU_AD_FORMAT_FLOAT; break;
732                                 case TYPE_HALF: format = CU_AD_FORMAT_HALF; break;
733                                 default: assert(0); return;
734                         }
735
736                         if(mem.data_depth > 1) {
737                                 CUDA_ARRAY3D_DESCRIPTOR desc;
738
739                                 desc.Width = mem.data_width;
740                                 desc.Height = mem.data_height;
741                                 desc.Depth = mem.data_depth;
742                                 desc.Format = format;
743                                 desc.NumChannels = mem.data_elements;
744                                 desc.Flags = 0;
745
746                                 cuda_assert(cuArray3DCreate(&handle, &desc));
747                         }
748                         else {
749                                 CUDA_ARRAY_DESCRIPTOR desc;
750
751                                 desc.Width = mem.data_width;
752                                 desc.Height = mem.data_height;
753                                 desc.Format = format;
754                                 desc.NumChannels = mem.data_elements;
755
756                                 cuda_assert(cuArrayCreate(&handle, &desc));
757                         }
758
759                         if(!handle) {
760                                 return;
761                         }
762
763                         /* Allocate 3D, 2D or 1D memory */
764                         if(mem.data_depth > 1) {
765                                 CUDA_MEMCPY3D param;
766                                 memset(&param, 0, sizeof(param));
767                                 param.dstMemoryType = CU_MEMORYTYPE_ARRAY;
768                                 param.dstArray = handle;
769                                 param.srcMemoryType = CU_MEMORYTYPE_HOST;
770                                 param.srcHost = (void*)mem.data_pointer;
771                                 param.srcPitch = mem.data_width*dsize*mem.data_elements;
772                                 param.WidthInBytes = param.srcPitch;
773                                 param.Height = mem.data_height;
774                                 param.Depth = mem.data_depth;
775
776                                 cuda_assert(cuMemcpy3D(&param));
777                         }
778                         else if(mem.data_height > 1) {
779                                 CUDA_MEMCPY2D param;
780                                 memset(&param, 0, sizeof(param));
781                                 param.dstMemoryType = CU_MEMORYTYPE_ARRAY;
782                                 param.dstArray = handle;
783                                 param.srcMemoryType = CU_MEMORYTYPE_HOST;
784                                 param.srcHost = (void*)mem.data_pointer;
785                                 param.srcPitch = mem.data_width*dsize*mem.data_elements;
786                                 param.WidthInBytes = param.srcPitch;
787                                 param.Height = mem.data_height;
788
789                                 cuda_assert(cuMemcpy2D(&param));
790                         }
791                         else
792                                 cuda_assert(cuMemcpyHtoA(handle, 0, (void*)mem.data_pointer, size));
793
794                         /* Fermi and Kepler */
795                         mem.device_pointer = (device_ptr)handle;
796                         mem.device_size = size;
797
798                         stats.mem_alloc(size);
799
800                         if(has_bindless_textures) {
801                                 /* Bindless Textures - Kepler */
802                                 int flat_slot = 0;
803                                 if(string_startswith(mem.name, "__tex_image")) {
804                                         int pos =  string(mem.name).rfind("_");
805                                         flat_slot = atoi(mem.name + pos + 1);
806                                 }
807                                 else {
808                                         assert(0);
809                                 }
810
811                                 CUDA_RESOURCE_DESC resDesc;
812                                 memset(&resDesc, 0, sizeof(resDesc));
813                                 resDesc.resType = CU_RESOURCE_TYPE_ARRAY;
814                                 resDesc.res.array.hArray = handle;
815                                 resDesc.flags = 0;
816
817                                 CUDA_TEXTURE_DESC texDesc;
818                                 memset(&texDesc, 0, sizeof(texDesc));
819                                 texDesc.addressMode[0] = address_mode;
820                                 texDesc.addressMode[1] = address_mode;
821                                 texDesc.addressMode[2] = address_mode;
822                                 texDesc.filterMode = filter_mode;
823                                 texDesc.flags = CU_TRSF_NORMALIZED_COORDINATES;
824
825                                 CUtexObject tex = 0;
826                                 cuda_assert(cuTexObjectCreate(&tex, &resDesc, &texDesc, NULL));
827
828                                 /* Safety check */
829                                 if((uint)tex > UINT_MAX) {
830                                         assert(0);
831                                 }
832
833                                 /* Resize once */
834                                 if(flat_slot >= texture_info.size()) {
835                                         /* Allocate some slots in advance, to reduce amount
836                                          * of re-allocations. */
837                                         texture_info.resize(flat_slot + 128);
838                                 }
839
840                                 /* Set Mapping and tag that we need to (re-)upload to device */
841                                 TextureInfo& info = texture_info[flat_slot];
842                                 info.data = (uint64_t)tex;
843                                 info.cl_buffer = 0;
844                                 info.interpolation = mem.interpolation;
845                                 info.extension = mem.extension;
846                                 info.width = mem.data_width;
847                                 info.height = mem.data_height;
848                                 info.depth = mem.data_depth;
849
850                                 tex_bindless_map[mem.device_pointer] = tex;
851                                 need_texture_info = true;
852                         }
853                         else {
854                                 /* Regular Textures - Fermi */
855                                 cuda_assert(cuTexRefSetArray(texref, handle, CU_TRSA_OVERRIDE_FORMAT));
856                                 cuda_assert(cuTexRefSetFilterMode(texref, filter_mode));
857                                 cuda_assert(cuTexRefSetFlags(texref, CU_TRSF_NORMALIZED_COORDINATES));
858
859                                 cuda_assert(cuTexRefSetAddressMode(texref, 0, address_mode));
860                                 cuda_assert(cuTexRefSetAddressMode(texref, 1, address_mode));
861                                 if(mem.data_depth > 1) {
862                                         cuda_assert(cuTexRefSetAddressMode(texref, 2, address_mode));
863                                 }
864
865                                 cuda_assert(cuTexRefSetFormat(texref, format, mem.data_elements));
866                         }
867                 }
868
869                 /* Fermi and Kepler */
870                 tex_interp_map[mem.device_pointer] = (mem.interpolation != INTERPOLATION_NONE);
871         }
872
873         void tex_free(device_memory& mem)
874         {
875                 if(mem.device_pointer) {
876                         if(tex_interp_map[mem.device_pointer]) {
877                                 CUDAContextScope scope(this);
878                                 cuArrayDestroy((CUarray)mem.device_pointer);
879
880                                 /* Free CUtexObject (Bindless Textures) */
881                                 if(info.has_bindless_textures && tex_bindless_map[mem.device_pointer]) {
882                                         CUtexObject tex = tex_bindless_map[mem.device_pointer];
883                                         cuTexObjectDestroy(tex);
884                                 }
885
886                                 tex_interp_map.erase(tex_interp_map.find(mem.device_pointer));
887                                 mem.device_pointer = 0;
888
889                                 stats.mem_free(mem.device_size);
890                                 mem.device_size = 0;
891                         }
892                         else {
893                                 tex_interp_map.erase(tex_interp_map.find(mem.device_pointer));
894                                 mem_free(mem);
895                         }
896                 }
897         }
898
899         bool denoising_set_tiles(device_ptr *buffers, DenoisingTask *task)
900         {
901                 mem_alloc(task->tiles_mem);
902
903                 TilesInfo *tiles = (TilesInfo*) task->tiles_mem.data_pointer;
904                 for(int i = 0; i < 9; i++) {
905                         tiles->buffers[i] = buffers[i];
906                 }
907
908                 mem_copy_to(task->tiles_mem);
909
910                 return !have_error();
911         }
912
913 #define CUDA_GET_BLOCKSIZE(func, w, h)                                                                          \
914                         int threads_per_block;                                                                              \
915                         cuda_assert(cuFuncGetAttribute(&threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, func)); \
916                         int threads = (int)sqrt((float)threads_per_block);                                                  \
917                         int xblocks = ((w) + threads - 1)/threads;                                                          \
918                         int yblocks = ((h) + threads - 1)/threads;
919
920 #define CUDA_LAUNCH_KERNEL(func, args)                      \
921                         cuda_assert(cuLaunchKernel(func,                \
922                                                    xblocks, yblocks, 1, \
923                                                    threads, threads, 1, \
924                                                    0, 0, args, 0));
925
926         bool denoising_non_local_means(device_ptr image_ptr, device_ptr guide_ptr, device_ptr variance_ptr, device_ptr out_ptr,
927                                        DenoisingTask *task)
928         {
929                 if(have_error())
930                         return false;
931
932                 CUDAContextScope scope(this);
933
934                 int4 rect = task->rect;
935                 int w = align_up(rect.z-rect.x, 4);
936                 int h = rect.w-rect.y;
937                 int r = task->nlm_state.r;
938                 int f = task->nlm_state.f;
939                 float a = task->nlm_state.a;
940                 float k_2 = task->nlm_state.k_2;
941
942                 CUdeviceptr difference     = task->nlm_state.temporary_1_ptr;
943                 CUdeviceptr blurDifference = task->nlm_state.temporary_2_ptr;
944                 CUdeviceptr weightAccum    = task->nlm_state.temporary_3_ptr;
945
946                 cuda_assert(cuMemsetD8(weightAccum, 0, sizeof(float)*w*h));
947                 cuda_assert(cuMemsetD8(out_ptr, 0, sizeof(float)*w*h));
948
949                 CUfunction cuNLMCalcDifference, cuNLMBlur, cuNLMCalcWeight, cuNLMUpdateOutput, cuNLMNormalize;
950                 cuda_assert(cuModuleGetFunction(&cuNLMCalcDifference, cuFilterModule, "kernel_cuda_filter_nlm_calc_difference"));
951                 cuda_assert(cuModuleGetFunction(&cuNLMBlur,           cuFilterModule, "kernel_cuda_filter_nlm_blur"));
952                 cuda_assert(cuModuleGetFunction(&cuNLMCalcWeight,     cuFilterModule, "kernel_cuda_filter_nlm_calc_weight"));
953                 cuda_assert(cuModuleGetFunction(&cuNLMUpdateOutput,   cuFilterModule, "kernel_cuda_filter_nlm_update_output"));
954                 cuda_assert(cuModuleGetFunction(&cuNLMNormalize,      cuFilterModule, "kernel_cuda_filter_nlm_normalize"));
955
956                 cuda_assert(cuFuncSetCacheConfig(cuNLMCalcDifference, CU_FUNC_CACHE_PREFER_L1));
957                 cuda_assert(cuFuncSetCacheConfig(cuNLMBlur,           CU_FUNC_CACHE_PREFER_L1));
958                 cuda_assert(cuFuncSetCacheConfig(cuNLMCalcWeight,     CU_FUNC_CACHE_PREFER_L1));
959                 cuda_assert(cuFuncSetCacheConfig(cuNLMUpdateOutput,   CU_FUNC_CACHE_PREFER_L1));
960                 cuda_assert(cuFuncSetCacheConfig(cuNLMNormalize,      CU_FUNC_CACHE_PREFER_L1));
961
962                 CUDA_GET_BLOCKSIZE(cuNLMCalcDifference, rect.z-rect.x, rect.w-rect.y);
963
964                 int dx, dy;
965                 int4 local_rect;
966                 int channel_offset = 0;
967                 void *calc_difference_args[] = {&dx, &dy, &guide_ptr, &variance_ptr, &difference, &local_rect, &w, &channel_offset, &a, &k_2};
968                 void *blur_args[]            = {&difference, &blurDifference, &local_rect, &w, &f};
969                 void *calc_weight_args[]     = {&blurDifference, &difference, &local_rect, &w, &f};
970                 void *update_output_args[]   = {&dx, &dy, &blurDifference, &image_ptr, &out_ptr, &weightAccum, &local_rect, &w, &f};
971
972                 for(int i = 0; i < (2*r+1)*(2*r+1); i++) {
973                         dy = i / (2*r+1) - r;
974                         dx = i % (2*r+1) - r;
975                         local_rect = make_int4(max(0, -dx), max(0, -dy), rect.z-rect.x - max(0, dx), rect.w-rect.y - max(0, dy));
976
977                         CUDA_LAUNCH_KERNEL(cuNLMCalcDifference, calc_difference_args);
978                         CUDA_LAUNCH_KERNEL(cuNLMBlur, blur_args);
979                         CUDA_LAUNCH_KERNEL(cuNLMCalcWeight, calc_weight_args);
980                         CUDA_LAUNCH_KERNEL(cuNLMBlur, blur_args);
981                         CUDA_LAUNCH_KERNEL(cuNLMUpdateOutput, update_output_args);
982                 }
983
984                 local_rect = make_int4(0, 0, rect.z-rect.x, rect.w-rect.y);
985                 void *normalize_args[] = {&out_ptr, &weightAccum, &local_rect, &w};
986                 CUDA_LAUNCH_KERNEL(cuNLMNormalize, normalize_args);
987                 cuda_assert(cuCtxSynchronize());
988
989                 return !have_error();
990         }
991
992         bool denoising_construct_transform(DenoisingTask *task)
993         {
994                 if(have_error())
995                         return false;
996
997                 CUDAContextScope scope(this);
998
999                 CUfunction cuFilterConstructTransform;
1000                 cuda_assert(cuModuleGetFunction(&cuFilterConstructTransform, cuFilterModule, "kernel_cuda_filter_construct_transform"));
1001                 cuda_assert(cuFuncSetCacheConfig(cuFilterConstructTransform, CU_FUNC_CACHE_PREFER_SHARED));
1002                 CUDA_GET_BLOCKSIZE(cuFilterConstructTransform,
1003                                    task->storage.w,
1004                                    task->storage.h);
1005
1006                 void *args[] = {&task->buffer.mem.device_pointer,
1007                                 &task->storage.transform.device_pointer,
1008                                 &task->storage.rank.device_pointer,
1009                                 &task->filter_area,
1010                                 &task->rect,
1011                                 &task->radius,
1012                                 &task->pca_threshold,
1013                                 &task->buffer.pass_stride};
1014                 CUDA_LAUNCH_KERNEL(cuFilterConstructTransform, args);
1015                 cuda_assert(cuCtxSynchronize());
1016
1017                 return !have_error();
1018         }
1019
1020         bool denoising_reconstruct(device_ptr color_ptr,
1021                                    device_ptr color_variance_ptr,
1022                                    device_ptr output_ptr,
1023                                    DenoisingTask *task)
1024         {
1025                 if(have_error())
1026                         return false;
1027
1028                 CUDAContextScope scope(this);
1029
1030                 mem_zero(task->storage.XtWX);
1031                 mem_zero(task->storage.XtWY);
1032
1033                 CUfunction cuNLMCalcDifference, cuNLMBlur, cuNLMCalcWeight, cuNLMConstructGramian, cuFinalize;
1034                 cuda_assert(cuModuleGetFunction(&cuNLMCalcDifference,   cuFilterModule, "kernel_cuda_filter_nlm_calc_difference"));
1035                 cuda_assert(cuModuleGetFunction(&cuNLMBlur,             cuFilterModule, "kernel_cuda_filter_nlm_blur"));
1036                 cuda_assert(cuModuleGetFunction(&cuNLMCalcWeight,       cuFilterModule, "kernel_cuda_filter_nlm_calc_weight"));
1037                 cuda_assert(cuModuleGetFunction(&cuNLMConstructGramian, cuFilterModule, "kernel_cuda_filter_nlm_construct_gramian"));
1038                 cuda_assert(cuModuleGetFunction(&cuFinalize,            cuFilterModule, "kernel_cuda_filter_finalize"));
1039
1040                 cuda_assert(cuFuncSetCacheConfig(cuNLMCalcDifference,   CU_FUNC_CACHE_PREFER_L1));
1041                 cuda_assert(cuFuncSetCacheConfig(cuNLMBlur,             CU_FUNC_CACHE_PREFER_L1));
1042                 cuda_assert(cuFuncSetCacheConfig(cuNLMCalcWeight,       CU_FUNC_CACHE_PREFER_L1));
1043                 cuda_assert(cuFuncSetCacheConfig(cuNLMConstructGramian, CU_FUNC_CACHE_PREFER_SHARED));
1044                 cuda_assert(cuFuncSetCacheConfig(cuFinalize,            CU_FUNC_CACHE_PREFER_L1));
1045
1046                 CUDA_GET_BLOCKSIZE(cuNLMCalcDifference,
1047                                    task->reconstruction_state.source_w,
1048                                    task->reconstruction_state.source_h);
1049
1050                 CUdeviceptr difference     = task->reconstruction_state.temporary_1_ptr;
1051                 CUdeviceptr blurDifference = task->reconstruction_state.temporary_2_ptr;
1052
1053                 int r = task->radius;
1054                 int f = 4;
1055                 float a = 1.0f;
1056                 for(int i = 0; i < (2*r+1)*(2*r+1); i++) {
1057                         int dy = i / (2*r+1) - r;
1058                         int dx = i % (2*r+1) - r;
1059
1060                         int local_rect[4] = {max(0, -dx), max(0, -dy),
1061                                              task->reconstruction_state.source_w - max(0, dx),
1062                                              task->reconstruction_state.source_h - max(0, dy)};
1063
1064                         void *calc_difference_args[] = {&dx, &dy,
1065                                                         &color_ptr,
1066                                                         &color_variance_ptr,
1067                                                         &difference,
1068                                                         &local_rect,
1069                                                         &task->buffer.w,
1070                                                         &task->buffer.pass_stride,
1071                                                         &a,
1072                                                         &task->nlm_k_2};
1073                         CUDA_LAUNCH_KERNEL(cuNLMCalcDifference, calc_difference_args);
1074
1075                         void *blur_args[] = {&difference,
1076                                              &blurDifference,
1077                                              &local_rect,
1078                                              &task->buffer.w,
1079                                              &f};
1080                         CUDA_LAUNCH_KERNEL(cuNLMBlur, blur_args);
1081
1082                         void *calc_weight_args[] = {&blurDifference,
1083                                                     &difference,
1084                                                     &local_rect,
1085                                                     &task->buffer.w,
1086                                                     &f};
1087                         CUDA_LAUNCH_KERNEL(cuNLMCalcWeight, calc_weight_args);
1088
1089                         /* Reuse previous arguments. */
1090                         CUDA_LAUNCH_KERNEL(cuNLMBlur, blur_args);
1091
1092                         void *construct_gramian_args[] = {&dx, &dy,
1093                                                           &blurDifference,
1094                                                           &task->buffer.mem.device_pointer,
1095                                                           &task->storage.transform.device_pointer,
1096                                                           &task->storage.rank.device_pointer,
1097                                                           &task->storage.XtWX.device_pointer,
1098                                                           &task->storage.XtWY.device_pointer,
1099                                                           &local_rect,
1100                                                           &task->reconstruction_state.filter_rect,
1101                                                           &task->buffer.w,
1102                                                           &task->buffer.h,
1103                                                           &f,
1104                                                       &task->buffer.pass_stride};
1105                         CUDA_LAUNCH_KERNEL(cuNLMConstructGramian, construct_gramian_args);
1106                 }
1107
1108                 void *finalize_args[] = {&task->buffer.w,
1109                                          &task->buffer.h,
1110                                          &output_ptr,
1111                                                  &task->storage.rank.device_pointer,
1112                                                  &task->storage.XtWX.device_pointer,
1113                                                  &task->storage.XtWY.device_pointer,
1114                                                  &task->filter_area,
1115                                                  &task->reconstruction_state.buffer_params.x,
1116                                                  &task->render_buffer.samples};
1117                 CUDA_LAUNCH_KERNEL(cuFinalize, finalize_args);
1118                 cuda_assert(cuCtxSynchronize());
1119
1120                 return !have_error();
1121         }
1122
1123         bool denoising_combine_halves(device_ptr a_ptr, device_ptr b_ptr,
1124                                       device_ptr mean_ptr, device_ptr variance_ptr,
1125                                       int r, int4 rect, DenoisingTask *task)
1126         {
1127                 if(have_error())
1128                         return false;
1129
1130                 CUDAContextScope scope(this);
1131
1132                 CUfunction cuFilterCombineHalves;
1133                 cuda_assert(cuModuleGetFunction(&cuFilterCombineHalves, cuFilterModule, "kernel_cuda_filter_combine_halves"));
1134                 cuda_assert(cuFuncSetCacheConfig(cuFilterCombineHalves, CU_FUNC_CACHE_PREFER_L1));
1135                 CUDA_GET_BLOCKSIZE(cuFilterCombineHalves,
1136                                    task->rect.z-task->rect.x,
1137                                    task->rect.w-task->rect.y);
1138
1139                 void *args[] = {&mean_ptr,
1140                                 &variance_ptr,
1141                                 &a_ptr,
1142                                 &b_ptr,
1143                                 &rect,
1144                                 &r};
1145                 CUDA_LAUNCH_KERNEL(cuFilterCombineHalves, args);
1146                 cuda_assert(cuCtxSynchronize());
1147
1148                 return !have_error();
1149         }
1150
1151         bool denoising_divide_shadow(device_ptr a_ptr, device_ptr b_ptr,
1152                                      device_ptr sample_variance_ptr, device_ptr sv_variance_ptr,
1153                                      device_ptr buffer_variance_ptr, DenoisingTask *task)
1154         {
1155                 if(have_error())
1156                         return false;
1157
1158                 CUDAContextScope scope(this);
1159
1160                 CUfunction cuFilterDivideShadow;
1161                 cuda_assert(cuModuleGetFunction(&cuFilterDivideShadow, cuFilterModule, "kernel_cuda_filter_divide_shadow"));
1162                 cuda_assert(cuFuncSetCacheConfig(cuFilterDivideShadow, CU_FUNC_CACHE_PREFER_L1));
1163                 CUDA_GET_BLOCKSIZE(cuFilterDivideShadow,
1164                                    task->rect.z-task->rect.x,
1165                                    task->rect.w-task->rect.y);
1166
1167                 void *args[] = {&task->render_buffer.samples,
1168                                 &task->tiles_mem.device_pointer,
1169                                 &a_ptr,
1170                                 &b_ptr,
1171                                 &sample_variance_ptr,
1172                                 &sv_variance_ptr,
1173                                 &buffer_variance_ptr,
1174                                 &task->rect,
1175                                 &task->render_buffer.pass_stride,
1176                                 &task->render_buffer.denoising_data_offset};
1177                 CUDA_LAUNCH_KERNEL(cuFilterDivideShadow, args);
1178                 cuda_assert(cuCtxSynchronize());
1179
1180                 return !have_error();
1181         }
1182
1183         bool denoising_get_feature(int mean_offset,
1184                                    int variance_offset,
1185                                    device_ptr mean_ptr,
1186                                    device_ptr variance_ptr,
1187                                    DenoisingTask *task)
1188         {
1189                 if(have_error())
1190                         return false;
1191
1192                 CUDAContextScope scope(this);
1193
1194                 CUfunction cuFilterGetFeature;
1195                 cuda_assert(cuModuleGetFunction(&cuFilterGetFeature, cuFilterModule, "kernel_cuda_filter_get_feature"));
1196                 cuda_assert(cuFuncSetCacheConfig(cuFilterGetFeature, CU_FUNC_CACHE_PREFER_L1));
1197                 CUDA_GET_BLOCKSIZE(cuFilterGetFeature,
1198                                    task->rect.z-task->rect.x,
1199                                    task->rect.w-task->rect.y);
1200
1201                 void *args[] = {&task->render_buffer.samples,
1202                                 &task->tiles_mem.device_pointer,
1203                                         &mean_offset,
1204                                         &variance_offset,
1205                                 &mean_ptr,
1206                                 &variance_ptr,
1207                                 &task->rect,
1208                                 &task->render_buffer.pass_stride,
1209                                 &task->render_buffer.denoising_data_offset};
1210                 CUDA_LAUNCH_KERNEL(cuFilterGetFeature, args);
1211                 cuda_assert(cuCtxSynchronize());
1212
1213                 return !have_error();
1214         }
1215
1216         bool denoising_detect_outliers(device_ptr image_ptr,
1217                                        device_ptr variance_ptr,
1218                                        device_ptr depth_ptr,
1219                                        device_ptr output_ptr,
1220                                        DenoisingTask *task)
1221         {
1222                 if(have_error())
1223                         return false;
1224
1225                 CUDAContextScope scope(this);
1226
1227                 CUfunction cuFilterDetectOutliers;
1228                 cuda_assert(cuModuleGetFunction(&cuFilterDetectOutliers, cuFilterModule, "kernel_cuda_filter_detect_outliers"));
1229                 cuda_assert(cuFuncSetCacheConfig(cuFilterDetectOutliers, CU_FUNC_CACHE_PREFER_L1));
1230                 CUDA_GET_BLOCKSIZE(cuFilterDetectOutliers,
1231                                    task->rect.z-task->rect.x,
1232                                    task->rect.w-task->rect.y);
1233
1234                 void *args[] = {&image_ptr,
1235                                 &variance_ptr,
1236                                 &depth_ptr,
1237                                 &output_ptr,
1238                                 &task->rect,
1239                                 &task->buffer.pass_stride};
1240
1241                 CUDA_LAUNCH_KERNEL(cuFilterDetectOutliers, args);
1242                 cuda_assert(cuCtxSynchronize());
1243
1244                 return !have_error();
1245         }
1246
1247         void denoise(RenderTile &rtile, const DeviceTask &task)
1248         {
1249                 DenoisingTask denoising(this);
1250
1251                 denoising.functions.construct_transform = function_bind(&CUDADevice::denoising_construct_transform, this, &denoising);
1252                 denoising.functions.reconstruct = function_bind(&CUDADevice::denoising_reconstruct, this, _1, _2, _3, &denoising);
1253                 denoising.functions.divide_shadow = function_bind(&CUDADevice::denoising_divide_shadow, this, _1, _2, _3, _4, _5, &denoising);
1254                 denoising.functions.non_local_means = function_bind(&CUDADevice::denoising_non_local_means, this, _1, _2, _3, _4, &denoising);
1255                 denoising.functions.combine_halves = function_bind(&CUDADevice::denoising_combine_halves, this, _1, _2, _3, _4, _5, _6, &denoising);
1256                 denoising.functions.get_feature = function_bind(&CUDADevice::denoising_get_feature, this, _1, _2, _3, _4, &denoising);
1257                 denoising.functions.detect_outliers = function_bind(&CUDADevice::denoising_detect_outliers, this, _1, _2, _3, _4, &denoising);
1258                 denoising.functions.set_tiles = function_bind(&CUDADevice::denoising_set_tiles, this, _1, &denoising);
1259
1260                 denoising.filter_area = make_int4(rtile.x, rtile.y, rtile.w, rtile.h);
1261                 denoising.render_buffer.samples = rtile.sample;
1262
1263                 RenderTile rtiles[9];
1264                 rtiles[4] = rtile;
1265                 task.map_neighbor_tiles(rtiles, this);
1266                 denoising.tiles_from_rendertiles(rtiles);
1267
1268                 denoising.init_from_devicetask(task);
1269
1270                 denoising.run_denoising();
1271
1272                 task.unmap_neighbor_tiles(rtiles, this);
1273         }
1274
1275         void path_trace(DeviceTask& task, RenderTile& rtile)
1276         {
1277                 if(have_error())
1278                         return;
1279
1280                 CUDAContextScope scope(this);
1281                 CUfunction cuPathTrace;
1282
1283                 /* Get kernel function. */
1284                 if(task.integrator_branched) {
1285                         cuda_assert(cuModuleGetFunction(&cuPathTrace, cuModule, "kernel_cuda_branched_path_trace"));
1286                 }
1287                 else {
1288                         cuda_assert(cuModuleGetFunction(&cuPathTrace, cuModule, "kernel_cuda_path_trace"));
1289                 }
1290
1291                 if(have_error()) {
1292                         return;
1293                 }
1294
1295                 cuda_assert(cuFuncSetCacheConfig(cuPathTrace, CU_FUNC_CACHE_PREFER_L1));
1296
1297                 /* Allocate work tile. */
1298                 device_vector<WorkTile> work_tiles(this, "work_tiles", MEM_READ_ONLY);
1299                 work_tiles.resize(1);
1300
1301                 WorkTile *wtile = work_tiles.get_data();
1302                 wtile->x = rtile.x;
1303                 wtile->y = rtile.y;
1304                 wtile->w = rtile.w;
1305                 wtile->h = rtile.h;
1306                 wtile->offset = rtile.offset;
1307                 wtile->stride = rtile.stride;
1308                 wtile->buffer = (float*)cuda_device_ptr(rtile.buffer);
1309                 mem_alloc(work_tiles);
1310
1311                 CUdeviceptr d_work_tiles = cuda_device_ptr(work_tiles.device_pointer);
1312
1313                 /* Prepare work size. More step samples render faster, but for now we
1314                  * remain conservative for GPUs connected to a display to avoid driver
1315                  * timeouts and display freezing. */
1316                 int min_blocks, num_threads_per_block;
1317                 cuda_assert(cuOccupancyMaxPotentialBlockSize(&min_blocks, &num_threads_per_block, cuPathTrace, NULL, 0, 0));
1318                 if(!info.display_device) {
1319                         min_blocks *= 8;
1320                 }
1321
1322                 uint step_samples = divide_up(min_blocks * num_threads_per_block, wtile->w * wtile->h);;
1323
1324                 /* Render all samples. */
1325                 int start_sample = rtile.start_sample;
1326                 int end_sample = rtile.start_sample + rtile.num_samples;
1327
1328                 for(int sample = start_sample; sample < end_sample; sample += step_samples) {
1329                         /* Setup and copy work tile to device. */
1330                         wtile->start_sample = sample;
1331                         wtile->num_samples = min(step_samples, end_sample - sample);;
1332                         mem_copy_to(work_tiles);
1333
1334                         uint total_work_size = wtile->w * wtile->h * wtile->num_samples;
1335                         uint num_blocks = divide_up(total_work_size, num_threads_per_block);
1336
1337                         /* Launch kernel. */
1338                         void *args[] = {&d_work_tiles,
1339                                         &total_work_size};
1340
1341                         cuda_assert(cuLaunchKernel(cuPathTrace,
1342                                                    num_blocks, 1, 1,
1343                                                    num_threads_per_block, 1, 1,
1344                                                    0, 0, args, 0));
1345
1346                         cuda_assert(cuCtxSynchronize());
1347
1348                         /* Update progress. */
1349                         rtile.sample = sample + wtile->num_samples;
1350                         task.update_progress(&rtile, rtile.w*rtile.h*wtile->num_samples);
1351
1352                         if(task.get_cancel()) {
1353                                 if(task.need_finish_queue == false)
1354                                         break;
1355                         }
1356                 }
1357
1358                 mem_free(work_tiles);
1359         }
1360
1361         void film_convert(DeviceTask& task, device_ptr buffer, device_ptr rgba_byte, device_ptr rgba_half)
1362         {
1363                 if(have_error())
1364                         return;
1365
1366                 CUDAContextScope scope(this);
1367
1368                 CUfunction cuFilmConvert;
1369                 CUdeviceptr d_rgba = map_pixels((rgba_byte)? rgba_byte: rgba_half);
1370                 CUdeviceptr d_buffer = cuda_device_ptr(buffer);
1371
1372                 /* get kernel function */
1373                 if(rgba_half) {
1374                         cuda_assert(cuModuleGetFunction(&cuFilmConvert, cuModule, "kernel_cuda_convert_to_half_float"));
1375                 }
1376                 else {
1377                         cuda_assert(cuModuleGetFunction(&cuFilmConvert, cuModule, "kernel_cuda_convert_to_byte"));
1378                 }
1379
1380
1381                 float sample_scale = 1.0f/(task.sample + 1);
1382
1383                 /* pass in parameters */
1384                 void *args[] = {&d_rgba,
1385                                 &d_buffer,
1386                                 &sample_scale,
1387                                 &task.x,
1388                                 &task.y,
1389                                 &task.w,
1390                                 &task.h,
1391                                 &task.offset,
1392                                 &task.stride};
1393
1394                 /* launch kernel */
1395                 int threads_per_block;
1396                 cuda_assert(cuFuncGetAttribute(&threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, cuFilmConvert));
1397
1398                 int xthreads = (int)sqrt(threads_per_block);
1399                 int ythreads = (int)sqrt(threads_per_block);
1400                 int xblocks = (task.w + xthreads - 1)/xthreads;
1401                 int yblocks = (task.h + ythreads - 1)/ythreads;
1402
1403                 cuda_assert(cuFuncSetCacheConfig(cuFilmConvert, CU_FUNC_CACHE_PREFER_L1));
1404
1405                 cuda_assert(cuLaunchKernel(cuFilmConvert,
1406                                            xblocks , yblocks, 1, /* blocks */
1407                                            xthreads, ythreads, 1, /* threads */
1408                                            0, 0, args, 0));
1409
1410                 unmap_pixels((rgba_byte)? rgba_byte: rgba_half);
1411         }
1412
1413         void shader(DeviceTask& task)
1414         {
1415                 if(have_error())
1416                         return;
1417
1418                 CUDAContextScope scope(this);
1419
1420                 CUfunction cuShader;
1421                 CUdeviceptr d_input = cuda_device_ptr(task.shader_input);
1422                 CUdeviceptr d_output = cuda_device_ptr(task.shader_output);
1423
1424                 /* get kernel function */
1425                 if(task.shader_eval_type >= SHADER_EVAL_BAKE) {
1426                         cuda_assert(cuModuleGetFunction(&cuShader, cuModule, "kernel_cuda_bake"));
1427                 }
1428                 else if(task.shader_eval_type == SHADER_EVAL_DISPLACE) {
1429                         cuda_assert(cuModuleGetFunction(&cuShader, cuModule, "kernel_cuda_displace"));
1430                 }
1431                 else {
1432                         cuda_assert(cuModuleGetFunction(&cuShader, cuModule, "kernel_cuda_background"));
1433                 }
1434
1435                 /* do tasks in smaller chunks, so we can cancel it */
1436                 const int shader_chunk_size = 65536;
1437                 const int start = task.shader_x;
1438                 const int end = task.shader_x + task.shader_w;
1439                 int offset = task.offset;
1440
1441                 bool canceled = false;
1442                 for(int sample = 0; sample < task.num_samples && !canceled; sample++) {
1443                         for(int shader_x = start; shader_x < end; shader_x += shader_chunk_size) {
1444                                 int shader_w = min(shader_chunk_size, end - shader_x);
1445
1446                                 /* pass in parameters */
1447                                 void *args[8];
1448                                 int arg = 0;
1449                                 args[arg++] = &d_input;
1450                                 args[arg++] = &d_output;
1451                                 args[arg++] = &task.shader_eval_type;
1452                                 if(task.shader_eval_type >= SHADER_EVAL_BAKE) {
1453                                         args[arg++] = &task.shader_filter;
1454                                 }
1455                                 args[arg++] = &shader_x;
1456                                 args[arg++] = &shader_w;
1457                                 args[arg++] = &offset;
1458                                 args[arg++] = &sample;
1459
1460                                 /* launch kernel */
1461                                 int threads_per_block;
1462                                 cuda_assert(cuFuncGetAttribute(&threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, cuShader));
1463
1464                                 int xblocks = (shader_w + threads_per_block - 1)/threads_per_block;
1465
1466                                 cuda_assert(cuFuncSetCacheConfig(cuShader, CU_FUNC_CACHE_PREFER_L1));
1467                                 cuda_assert(cuLaunchKernel(cuShader,
1468                                                            xblocks , 1, 1, /* blocks */
1469                                                            threads_per_block, 1, 1, /* threads */
1470                                                            0, 0, args, 0));
1471
1472                                 cuda_assert(cuCtxSynchronize());
1473
1474                                 if(task.get_cancel()) {
1475                                         canceled = true;
1476                                         break;
1477                                 }
1478                         }
1479
1480                         task.update_progress(NULL);
1481                 }
1482         }
1483
1484         CUdeviceptr map_pixels(device_ptr mem)
1485         {
1486                 if(!background) {
1487                         PixelMem pmem = pixel_mem_map[mem];
1488                         CUdeviceptr buffer;
1489
1490                         size_t bytes;
1491                         cuda_assert(cuGraphicsMapResources(1, &pmem.cuPBOresource, 0));
1492                         cuda_assert(cuGraphicsResourceGetMappedPointer(&buffer, &bytes, pmem.cuPBOresource));
1493
1494                         return buffer;
1495                 }
1496
1497                 return cuda_device_ptr(mem);
1498         }
1499
1500         void unmap_pixels(device_ptr mem)
1501         {
1502                 if(!background) {
1503                         PixelMem pmem = pixel_mem_map[mem];
1504
1505                         cuda_assert(cuGraphicsUnmapResources(1, &pmem.cuPBOresource, 0));
1506                 }
1507         }
1508
1509         void pixels_alloc(device_memory& mem)
1510         {
1511                 if(!background) {
1512                         PixelMem pmem;
1513
1514                         pmem.w = mem.data_width;
1515                         pmem.h = mem.data_height;
1516
1517                         CUDAContextScope scope(this);
1518
1519                         glGenBuffers(1, &pmem.cuPBO);
1520                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pmem.cuPBO);
1521                         if(mem.data_type == TYPE_HALF)
1522                                 glBufferData(GL_PIXEL_UNPACK_BUFFER, pmem.w*pmem.h*sizeof(GLhalf)*4, NULL, GL_DYNAMIC_DRAW);
1523                         else
1524                                 glBufferData(GL_PIXEL_UNPACK_BUFFER, pmem.w*pmem.h*sizeof(uint8_t)*4, NULL, GL_DYNAMIC_DRAW);
1525
1526                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1527
1528                         glGenTextures(1, &pmem.cuTexId);
1529                         glBindTexture(GL_TEXTURE_2D, pmem.cuTexId);
1530                         if(mem.data_type == TYPE_HALF)
1531                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, pmem.w, pmem.h, 0, GL_RGBA, GL_HALF_FLOAT, NULL);
1532                         else
1533                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, pmem.w, pmem.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
1534                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
1535                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
1536                         glBindTexture(GL_TEXTURE_2D, 0);
1537
1538                         CUresult result = cuGraphicsGLRegisterBuffer(&pmem.cuPBOresource, pmem.cuPBO, CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE);
1539
1540                         if(result == CUDA_SUCCESS) {
1541                                 mem.device_pointer = pmem.cuTexId;
1542                                 pixel_mem_map[mem.device_pointer] = pmem;
1543
1544                                 mem.device_size = mem.memory_size();
1545                                 stats.mem_alloc(mem.device_size);
1546
1547                                 return;
1548                         }
1549                         else {
1550                                 /* failed to register buffer, fallback to no interop */
1551                                 glDeleteBuffers(1, &pmem.cuPBO);
1552                                 glDeleteTextures(1, &pmem.cuTexId);
1553
1554                                 background = true;
1555                         }
1556                 }
1557
1558                 Device::pixels_alloc(mem);
1559         }
1560
1561         void pixels_copy_from(device_memory& mem, int y, int w, int h)
1562         {
1563                 if(!background) {
1564                         PixelMem pmem = pixel_mem_map[mem.device_pointer];
1565
1566                         CUDAContextScope scope(this);
1567
1568                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pmem.cuPBO);
1569                         uchar *pixels = (uchar*)glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_ONLY);
1570                         size_t offset = sizeof(uchar)*4*y*w;
1571                         memcpy((uchar*)mem.data_pointer + offset, pixels + offset, sizeof(uchar)*4*w*h);
1572                         glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
1573                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1574
1575                         return;
1576                 }
1577
1578                 Device::pixels_copy_from(mem, y, w, h);
1579         }
1580
1581         void pixels_free(device_memory& mem)
1582         {
1583                 if(mem.device_pointer) {
1584                         if(!background) {
1585                                 PixelMem pmem = pixel_mem_map[mem.device_pointer];
1586
1587                                 CUDAContextScope scope(this);
1588
1589                                 cuda_assert(cuGraphicsUnregisterResource(pmem.cuPBOresource));
1590                                 glDeleteBuffers(1, &pmem.cuPBO);
1591                                 glDeleteTextures(1, &pmem.cuTexId);
1592
1593                                 pixel_mem_map.erase(pixel_mem_map.find(mem.device_pointer));
1594                                 mem.device_pointer = 0;
1595
1596                                 stats.mem_free(mem.device_size);
1597                                 mem.device_size = 0;
1598
1599                                 return;
1600                         }
1601
1602                         Device::pixels_free(mem);
1603                 }
1604         }
1605
1606         void draw_pixels(device_memory& mem, int y, int w, int h, int dx, int dy, int width, int height, bool transparent,
1607                 const DeviceDrawParams &draw_params)
1608         {
1609                 if(!background) {
1610                         PixelMem pmem = pixel_mem_map[mem.device_pointer];
1611                         float *vpointer;
1612
1613                         CUDAContextScope scope(this);
1614
1615                         /* for multi devices, this assumes the inefficient method that we allocate
1616                          * all pixels on the device even though we only render to a subset */
1617                         size_t offset = 4*y*w;
1618
1619                         if(mem.data_type == TYPE_HALF)
1620                                 offset *= sizeof(GLhalf);
1621                         else
1622                                 offset *= sizeof(uint8_t);
1623
1624                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pmem.cuPBO);
1625                         glBindTexture(GL_TEXTURE_2D, pmem.cuTexId);
1626                         if(mem.data_type == TYPE_HALF)
1627                                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_HALF_FLOAT, (void*)offset);
1628                         else
1629                                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, (void*)offset);
1630                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
1631
1632                         glEnable(GL_TEXTURE_2D);
1633
1634                         if(transparent) {
1635                                 glEnable(GL_BLEND);
1636                                 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
1637                         }
1638
1639                         glColor3f(1.0f, 1.0f, 1.0f);
1640
1641                         if(draw_params.bind_display_space_shader_cb) {
1642                                 draw_params.bind_display_space_shader_cb();
1643                         }
1644
1645                         if(!vertex_buffer)
1646                                 glGenBuffers(1, &vertex_buffer);
1647
1648                         glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
1649                         /* invalidate old contents - avoids stalling if buffer is still waiting in queue to be rendered */
1650                         glBufferData(GL_ARRAY_BUFFER, 16 * sizeof(float), NULL, GL_STREAM_DRAW);
1651
1652                         vpointer = (float *)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
1653
1654                         if(vpointer) {
1655                                 /* texture coordinate - vertex pair */
1656                                 vpointer[0] = 0.0f;
1657                                 vpointer[1] = 0.0f;
1658                                 vpointer[2] = dx;
1659                                 vpointer[3] = dy;
1660
1661                                 vpointer[4] = (float)w/(float)pmem.w;
1662                                 vpointer[5] = 0.0f;
1663                                 vpointer[6] = (float)width + dx;
1664                                 vpointer[7] = dy;
1665
1666                                 vpointer[8] = (float)w/(float)pmem.w;
1667                                 vpointer[9] = (float)h/(float)pmem.h;
1668                                 vpointer[10] = (float)width + dx;
1669                                 vpointer[11] = (float)height + dy;
1670
1671                                 vpointer[12] = 0.0f;
1672                                 vpointer[13] = (float)h/(float)pmem.h;
1673                                 vpointer[14] = dx;
1674                                 vpointer[15] = (float)height + dy;
1675
1676                                 glUnmapBuffer(GL_ARRAY_BUFFER);
1677                         }
1678
1679                         glTexCoordPointer(2, GL_FLOAT, 4 * sizeof(float), 0);
1680                         glVertexPointer(2, GL_FLOAT, 4 * sizeof(float), (char *)NULL + 2 * sizeof(float));
1681
1682                         glEnableClientState(GL_VERTEX_ARRAY);
1683                         glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1684
1685                         glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1686
1687                         glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1688                         glDisableClientState(GL_VERTEX_ARRAY);
1689
1690                         glBindBuffer(GL_ARRAY_BUFFER, 0);
1691
1692                         if(draw_params.unbind_display_space_shader_cb) {
1693                                 draw_params.unbind_display_space_shader_cb();
1694                         }
1695
1696                         if(transparent)
1697                                 glDisable(GL_BLEND);
1698
1699                         glBindTexture(GL_TEXTURE_2D, 0);
1700                         glDisable(GL_TEXTURE_2D);
1701
1702                         return;
1703                 }
1704
1705                 Device::draw_pixels(mem, y, w, h, dx, dy, width, height, transparent, draw_params);
1706         }
1707
1708         void thread_run(DeviceTask *task)
1709         {
1710                 CUDAContextScope scope(this);
1711
1712                 if(task->type == DeviceTask::RENDER) {
1713                         RenderTile tile;
1714
1715                         DeviceRequestedFeatures requested_features;
1716                         if(use_split_kernel()) {
1717                                 if(!use_adaptive_compilation()) {
1718                                         requested_features.max_closure = 64;
1719                                 }
1720
1721                                 if(split_kernel == NULL) {
1722                                         split_kernel = new CUDASplitKernel(this);
1723                                         split_kernel->load_kernels(requested_features);
1724                                 }
1725                         }
1726
1727                         /* keep rendering tiles until done */
1728                         while(task->acquire_tile(this, tile)) {
1729                                 if(tile.task == RenderTile::PATH_TRACE) {
1730                                         if(use_split_kernel()) {
1731                                                 device_only_memory<uchar> void_buffer(this, "void_buffer");
1732                                                 split_kernel->path_trace(task, tile, void_buffer, void_buffer);
1733                                         }
1734                                         else {
1735                                                 path_trace(*task, tile);
1736                                         }
1737                                 }
1738                                 else if(tile.task == RenderTile::DENOISE) {
1739                                         tile.sample = tile.start_sample + tile.num_samples;
1740
1741                                         denoise(tile, *task);
1742
1743                                         task->update_progress(&tile, tile.w*tile.h);
1744                                 }
1745
1746                                 task->release_tile(tile);
1747
1748                                 if(task->get_cancel()) {
1749                                         if(task->need_finish_queue == false)
1750                                                 break;
1751                                 }
1752                         }
1753                 }
1754                 else if(task->type == DeviceTask::SHADER) {
1755                         shader(*task);
1756
1757                         cuda_assert(cuCtxSynchronize());
1758                 }
1759         }
1760
1761         class CUDADeviceTask : public DeviceTask {
1762         public:
1763                 CUDADeviceTask(CUDADevice *device, DeviceTask& task)
1764                 : DeviceTask(task)
1765                 {
1766                         run = function_bind(&CUDADevice::thread_run, device, this);
1767                 }
1768         };
1769
1770         int get_split_task_count(DeviceTask& /*task*/)
1771         {
1772                 return 1;
1773         }
1774
1775         void task_add(DeviceTask& task)
1776         {
1777                 CUDAContextScope scope(this);
1778
1779                 /* Load texture info. */
1780                 load_texture_info();
1781
1782                 if(task.type == DeviceTask::FILM_CONVERT) {
1783                         /* must be done in main thread due to opengl access */
1784                         film_convert(task, task.buffer, task.rgba_byte, task.rgba_half);
1785                         cuda_assert(cuCtxSynchronize());
1786                 }
1787                 else {
1788                         task_pool.push(new CUDADeviceTask(this, task));
1789                 }
1790         }
1791
1792         void task_wait()
1793         {
1794                 task_pool.wait();
1795         }
1796
1797         void task_cancel()
1798         {
1799                 task_pool.cancel();
1800         }
1801
1802         friend class CUDASplitKernelFunction;
1803         friend class CUDASplitKernel;
1804         friend class CUDAContextScope;
1805 };
1806
1807 /* redefine the cuda_assert macro so it can be used outside of the CUDADevice class
1808  * now that the definition of that class is complete
1809  */
1810 #undef cuda_assert
1811 #define cuda_assert(stmt) \
1812         { \
1813                 CUresult result = stmt; \
1814                 \
1815                 if(result != CUDA_SUCCESS) { \
1816                         string message = string_printf("CUDA error: %s in %s", cuewErrorString(result), #stmt); \
1817                         if(device->error_msg == "") \
1818                                 device->error_msg = message; \
1819                         fprintf(stderr, "%s\n", message.c_str()); \
1820                         /*cuda_abort();*/ \
1821                         device->cuda_error_documentation(); \
1822                 } \
1823         } (void)0
1824
1825
1826 /* CUDA context scope. */
1827
1828 CUDAContextScope::CUDAContextScope(CUDADevice *device)
1829 : device(device)
1830 {
1831         cuda_assert(cuCtxPushCurrent(device->cuContext));
1832 }
1833
1834 CUDAContextScope::~CUDAContextScope()
1835 {
1836         cuda_assert(cuCtxPopCurrent(NULL));
1837 }
1838
1839 /* split kernel */
1840
1841 class CUDASplitKernelFunction : public SplitKernelFunction{
1842         CUDADevice* device;
1843         CUfunction func;
1844 public:
1845         CUDASplitKernelFunction(CUDADevice *device, CUfunction func) : device(device), func(func) {}
1846
1847         /* enqueue the kernel, returns false if there is an error */
1848         bool enqueue(const KernelDimensions &dim, device_memory &/*kg*/, device_memory &/*data*/)
1849         {
1850                 return enqueue(dim, NULL);
1851         }
1852
1853         /* enqueue the kernel, returns false if there is an error */
1854         bool enqueue(const KernelDimensions &dim, void *args[])
1855         {
1856                 if(device->have_error())
1857                         return false;
1858
1859                 CUDAContextScope scope(device);
1860
1861                 /* we ignore dim.local_size for now, as this is faster */
1862                 int threads_per_block;
1863                 cuda_assert(cuFuncGetAttribute(&threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, func));
1864
1865                 int xblocks = (dim.global_size[0]*dim.global_size[1] + threads_per_block - 1)/threads_per_block;
1866
1867                 cuda_assert(cuFuncSetCacheConfig(func, CU_FUNC_CACHE_PREFER_L1));
1868
1869                 cuda_assert(cuLaunchKernel(func,
1870                                            xblocks, 1, 1, /* blocks */
1871                                            threads_per_block, 1, 1, /* threads */
1872                                            0, 0, args, 0));
1873
1874                 return !device->have_error();
1875         }
1876 };
1877
1878 CUDASplitKernel::CUDASplitKernel(CUDADevice *device) : DeviceSplitKernel(device), device(device)
1879 {
1880 }
1881
1882 uint64_t CUDASplitKernel::state_buffer_size(device_memory& /*kg*/, device_memory& /*data*/, size_t num_threads)
1883 {
1884         CUDAContextScope scope(device);
1885
1886         device_vector<uint64_t> size_buffer(device, "size_buffer", MEM_READ_WRITE);
1887         size_buffer.resize(1);
1888         device->mem_alloc(size_buffer);
1889
1890         uint threads = num_threads;
1891         CUdeviceptr d_size = device->cuda_device_ptr(size_buffer.device_pointer);
1892
1893         struct args_t {
1894                 uint* num_threads;
1895                 CUdeviceptr* size;
1896         };
1897
1898         args_t args = {
1899                 &threads,
1900                 &d_size
1901         };
1902
1903         CUfunction state_buffer_size;
1904         cuda_assert(cuModuleGetFunction(&state_buffer_size, device->cuModule, "kernel_cuda_state_buffer_size"));
1905
1906         cuda_assert(cuLaunchKernel(state_buffer_size,
1907                                    1, 1, 1,
1908                                    1, 1, 1,
1909                                    0, 0, (void**)&args, 0));
1910
1911         device->mem_copy_from(size_buffer, 0, 1, 1, sizeof(uint64_t));
1912         size_t size = size_buffer[0];
1913         device->mem_free(size_buffer);
1914
1915         return size;
1916 }
1917
1918 bool CUDASplitKernel::enqueue_split_kernel_data_init(const KernelDimensions& dim,
1919                                     RenderTile& rtile,
1920                                     int num_global_elements,
1921                                     device_memory& /*kernel_globals*/,
1922                                     device_memory& /*kernel_data*/,
1923                                     device_memory& split_data,
1924                                     device_memory& ray_state,
1925                                     device_memory& queue_index,
1926                                     device_memory& use_queues_flag,
1927                                     device_memory& work_pool_wgs)
1928 {
1929         CUDAContextScope scope(device);
1930
1931         CUdeviceptr d_split_data = device->cuda_device_ptr(split_data.device_pointer);
1932         CUdeviceptr d_ray_state = device->cuda_device_ptr(ray_state.device_pointer);
1933         CUdeviceptr d_queue_index = device->cuda_device_ptr(queue_index.device_pointer);
1934         CUdeviceptr d_use_queues_flag = device->cuda_device_ptr(use_queues_flag.device_pointer);
1935         CUdeviceptr d_work_pool_wgs = device->cuda_device_ptr(work_pool_wgs.device_pointer);
1936
1937         CUdeviceptr d_buffer = device->cuda_device_ptr(rtile.buffer);
1938
1939         int end_sample = rtile.start_sample + rtile.num_samples;
1940         int queue_size = dim.global_size[0] * dim.global_size[1];
1941
1942         struct args_t {
1943                 CUdeviceptr* split_data_buffer;
1944                 int* num_elements;
1945                 CUdeviceptr* ray_state;
1946                 int* start_sample;
1947                 int* end_sample;
1948                 int* sx;
1949                 int* sy;
1950                 int* sw;
1951                 int* sh;
1952                 int* offset;
1953                 int* stride;
1954                 CUdeviceptr* queue_index;
1955                 int* queuesize;
1956                 CUdeviceptr* use_queues_flag;
1957                 CUdeviceptr* work_pool_wgs;
1958                 int* num_samples;
1959                 CUdeviceptr* buffer;
1960         };
1961
1962         args_t args = {
1963                 &d_split_data,
1964                 &num_global_elements,
1965                 &d_ray_state,
1966                 &rtile.start_sample,
1967                 &end_sample,
1968                 &rtile.x,
1969                 &rtile.y,
1970                 &rtile.w,
1971                 &rtile.h,
1972                 &rtile.offset,
1973                 &rtile.stride,
1974                 &d_queue_index,
1975                 &queue_size,
1976                 &d_use_queues_flag,
1977                 &d_work_pool_wgs,
1978                 &rtile.num_samples,
1979                 &d_buffer
1980         };
1981
1982         CUfunction data_init;
1983         cuda_assert(cuModuleGetFunction(&data_init, device->cuModule, "kernel_cuda_path_trace_data_init"));
1984         if(device->have_error()) {
1985                 return false;
1986         }
1987
1988         CUDASplitKernelFunction(device, data_init).enqueue(dim, (void**)&args);
1989
1990         return !device->have_error();
1991 }
1992
1993 SplitKernelFunction* CUDASplitKernel::get_split_kernel_function(const string& kernel_name,
1994                                                                 const DeviceRequestedFeatures&)
1995 {
1996         CUDAContextScope scope(device);
1997         CUfunction func;
1998
1999         cuda_assert(cuModuleGetFunction(&func, device->cuModule, (string("kernel_cuda_") + kernel_name).data()));
2000         if(device->have_error()) {
2001                 device->cuda_error_message(string_printf("kernel \"kernel_cuda_%s\" not found in module", kernel_name.data()));
2002                 return NULL;
2003         }
2004
2005         return new CUDASplitKernelFunction(device, func);
2006 }
2007
2008 int2 CUDASplitKernel::split_kernel_local_size()
2009 {
2010         return make_int2(32, 1);
2011 }
2012
2013 int2 CUDASplitKernel::split_kernel_global_size(device_memory& kg, device_memory& data, DeviceTask * /*task*/)
2014 {
2015         CUDAContextScope scope(device);
2016         size_t free;
2017         size_t total;
2018
2019         cuda_assert(cuMemGetInfo(&free, &total));
2020
2021         VLOG(1) << "Maximum device allocation size: "
2022                 << string_human_readable_number(free) << " bytes. ("
2023                 << string_human_readable_size(free) << ").";
2024
2025         size_t num_elements = max_elements_for_max_buffer_size(kg, data, free / 2);
2026         size_t side = round_down((int)sqrt(num_elements), 32);
2027         int2 global_size = make_int2(side, round_down(num_elements / side, 16));
2028         VLOG(1) << "Global size: " << global_size << ".";
2029         return global_size;
2030 }
2031
2032 bool device_cuda_init(void)
2033 {
2034 #ifdef WITH_CUDA_DYNLOAD
2035         static bool initialized = false;
2036         static bool result = false;
2037
2038         if(initialized)
2039                 return result;
2040
2041         initialized = true;
2042         int cuew_result = cuewInit();
2043         if(cuew_result == CUEW_SUCCESS) {
2044                 VLOG(1) << "CUEW initialization succeeded";
2045                 if(CUDADevice::have_precompiled_kernels()) {
2046                         VLOG(1) << "Found precompiled kernels";
2047                         result = true;
2048                 }
2049 #ifndef _WIN32
2050                 else if(cuewCompilerPath() != NULL) {
2051                         VLOG(1) << "Found CUDA compiler " << cuewCompilerPath();
2052                         result = true;
2053                 }
2054                 else {
2055                         VLOG(1) << "Neither precompiled kernels nor CUDA compiler wad found,"
2056                                 << " unable to use CUDA";
2057                 }
2058 #endif
2059         }
2060         else {
2061                 VLOG(1) << "CUEW initialization failed: "
2062                         << ((cuew_result == CUEW_ERROR_ATEXIT_FAILED)
2063                             ? "Error setting up atexit() handler"
2064                             : "Error opening the library");
2065         }
2066
2067         return result;
2068 #else  /* WITH_CUDA_DYNLOAD */
2069         return true;
2070 #endif /* WITH_CUDA_DYNLOAD */
2071 }
2072
2073 Device *device_cuda_create(DeviceInfo& info, Stats &stats, bool background)
2074 {
2075         return new CUDADevice(info, stats, background);
2076 }
2077
2078 static CUresult device_cuda_safe_init()
2079 {
2080 #ifdef _WIN32
2081         __try {
2082                 return cuInit(0);
2083         }
2084         __except(EXCEPTION_EXECUTE_HANDLER) {
2085                 /* Ignore crashes inside the CUDA driver and hope we can
2086                  * survive even with corrupted CUDA installs. */
2087                 fprintf(stderr, "Cycles CUDA: driver crashed, continuing without CUDA.\n");
2088         }
2089
2090         return CUDA_ERROR_NO_DEVICE;
2091 #else
2092         return cuInit(0);
2093 #endif
2094 }
2095
2096 void device_cuda_info(vector<DeviceInfo>& devices)
2097 {
2098         CUresult result = device_cuda_safe_init();
2099         if(result != CUDA_SUCCESS) {
2100                 if(result != CUDA_ERROR_NO_DEVICE)
2101                         fprintf(stderr, "CUDA cuInit: %s\n", cuewErrorString(result));
2102                 return;
2103         }
2104
2105         int count = 0;
2106         result = cuDeviceGetCount(&count);
2107         if(result != CUDA_SUCCESS) {
2108                 fprintf(stderr, "CUDA cuDeviceGetCount: %s\n", cuewErrorString(result));
2109                 return;
2110         }
2111
2112         vector<DeviceInfo> display_devices;
2113
2114         for(int num = 0; num < count; num++) {
2115                 char name[256];
2116
2117                 result = cuDeviceGetName(name, 256, num);
2118                 if(result != CUDA_SUCCESS) {
2119                         fprintf(stderr, "CUDA cuDeviceGetName: %s\n", cuewErrorString(result));
2120                         continue;
2121                 }
2122
2123                 int major;
2124                 cuDeviceGetAttribute(&major, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, num);
2125                 if(major < 2) {
2126                         VLOG(1) << "Ignoring device \"" << name
2127                                 << "\", compute capability is too low.";
2128                         continue;
2129                 }
2130
2131                 DeviceInfo info;
2132
2133                 info.type = DEVICE_CUDA;
2134                 info.description = string(name);
2135                 info.num = num;
2136
2137                 info.advanced_shading = (major >= 2);
2138                 info.has_bindless_textures = (major >= 3);
2139                 info.has_volume_decoupled = false;
2140                 info.has_qbvh = false;
2141
2142                 int pci_location[3] = {0, 0, 0};
2143                 cuDeviceGetAttribute(&pci_location[0], CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID, num);
2144                 cuDeviceGetAttribute(&pci_location[1], CU_DEVICE_ATTRIBUTE_PCI_BUS_ID, num);
2145                 cuDeviceGetAttribute(&pci_location[2], CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID, num);
2146                 info.id = string_printf("CUDA_%s_%04x:%02x:%02x",
2147                                         name,
2148                                         (unsigned int)pci_location[0],
2149                                         (unsigned int)pci_location[1],
2150                                         (unsigned int)pci_location[2]);
2151
2152                 /* If device has a kernel timeout and no compute preemption, we assume
2153                  * it is connected to a display and will freeze the display while doing
2154                  * computations. */
2155                 int timeout_attr = 0, preempt_attr = 0;
2156                 cuDeviceGetAttribute(&timeout_attr, CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT, num);
2157                 cuDeviceGetAttribute(&preempt_attr, CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED, num);
2158
2159                 if(timeout_attr && !preempt_attr) {
2160                         VLOG(1) << "Device is recognized as display.";
2161                         info.description += " (Display)";
2162                         info.display_device = true;
2163                         display_devices.push_back(info);
2164                 }
2165                 else {
2166                         devices.push_back(info);
2167                 }
2168                 VLOG(1) << "Added device \"" << name << "\" with id \"" << info.id << "\".";
2169         }
2170
2171         if(!display_devices.empty())
2172                 devices.insert(devices.end(), display_devices.begin(), display_devices.end());
2173 }
2174
2175 string device_cuda_capabilities(void)
2176 {
2177         CUresult result = device_cuda_safe_init();
2178         if(result != CUDA_SUCCESS) {
2179                 if(result != CUDA_ERROR_NO_DEVICE) {
2180                         return string("Error initializing CUDA: ") + cuewErrorString(result);
2181                 }
2182                 return "No CUDA device found\n";
2183         }
2184
2185         int count;
2186         result = cuDeviceGetCount(&count);
2187         if(result != CUDA_SUCCESS) {
2188                 return string("Error getting devices: ") + cuewErrorString(result);
2189         }
2190
2191         string capabilities = "";
2192         for(int num = 0; num < count; num++) {
2193                 char name[256];
2194                 if(cuDeviceGetName(name, 256, num) != CUDA_SUCCESS) {
2195                         continue;
2196                 }
2197                 capabilities += string("\t") + name + "\n";
2198                 int value;
2199 #define GET_ATTR(attr) \
2200                 { \
2201                         if(cuDeviceGetAttribute(&value, \
2202                                                 CU_DEVICE_ATTRIBUTE_##attr, \
2203                                                 num) == CUDA_SUCCESS) \
2204                         { \
2205                                 capabilities += string_printf("\t\tCU_DEVICE_ATTRIBUTE_" #attr "\t\t\t%d\n", \
2206                                                               value); \
2207                         } \
2208                 } (void)0
2209                 /* TODO(sergey): Strip all attributes which are not useful for us
2210                  * or does not depend on the driver.
2211                  */
2212                 GET_ATTR(MAX_THREADS_PER_BLOCK);
2213                 GET_ATTR(MAX_BLOCK_DIM_X);
2214                 GET_ATTR(MAX_BLOCK_DIM_Y);
2215                 GET_ATTR(MAX_BLOCK_DIM_Z);
2216                 GET_ATTR(MAX_GRID_DIM_X);
2217                 GET_ATTR(MAX_GRID_DIM_Y);
2218                 GET_ATTR(MAX_GRID_DIM_Z);
2219                 GET_ATTR(MAX_SHARED_MEMORY_PER_BLOCK);
2220                 GET_ATTR(SHARED_MEMORY_PER_BLOCK);
2221                 GET_ATTR(TOTAL_CONSTANT_MEMORY);
2222                 GET_ATTR(WARP_SIZE);
2223                 GET_ATTR(MAX_PITCH);
2224                 GET_ATTR(MAX_REGISTERS_PER_BLOCK);
2225                 GET_ATTR(REGISTERS_PER_BLOCK);
2226                 GET_ATTR(CLOCK_RATE);
2227                 GET_ATTR(TEXTURE_ALIGNMENT);
2228                 GET_ATTR(GPU_OVERLAP);
2229                 GET_ATTR(MULTIPROCESSOR_COUNT);
2230                 GET_ATTR(KERNEL_EXEC_TIMEOUT);
2231                 GET_ATTR(INTEGRATED);
2232                 GET_ATTR(CAN_MAP_HOST_MEMORY);
2233                 GET_ATTR(COMPUTE_MODE);
2234                 GET_ATTR(MAXIMUM_TEXTURE1D_WIDTH);
2235                 GET_ATTR(MAXIMUM_TEXTURE2D_WIDTH);
2236                 GET_ATTR(MAXIMUM_TEXTURE2D_HEIGHT);
2237                 GET_ATTR(MAXIMUM_TEXTURE3D_WIDTH);
2238                 GET_ATTR(MAXIMUM_TEXTURE3D_HEIGHT);
2239                 GET_ATTR(MAXIMUM_TEXTURE3D_DEPTH);
2240                 GET_ATTR(MAXIMUM_TEXTURE2D_LAYERED_WIDTH);
2241                 GET_ATTR(MAXIMUM_TEXTURE2D_LAYERED_HEIGHT);
2242                 GET_ATTR(MAXIMUM_TEXTURE2D_LAYERED_LAYERS);
2243                 GET_ATTR(MAXIMUM_TEXTURE2D_ARRAY_WIDTH);
2244                 GET_ATTR(MAXIMUM_TEXTURE2D_ARRAY_HEIGHT);
2245                 GET_ATTR(MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES);
2246                 GET_ATTR(SURFACE_ALIGNMENT);
2247                 GET_ATTR(CONCURRENT_KERNELS);
2248                 GET_ATTR(ECC_ENABLED);
2249                 GET_ATTR(TCC_DRIVER);
2250                 GET_ATTR(MEMORY_CLOCK_RATE);
2251                 GET_ATTR(GLOBAL_MEMORY_BUS_WIDTH);
2252                 GET_ATTR(L2_CACHE_SIZE);
2253                 GET_ATTR(MAX_THREADS_PER_MULTIPROCESSOR);
2254                 GET_ATTR(ASYNC_ENGINE_COUNT);
2255                 GET_ATTR(UNIFIED_ADDRESSING);
2256                 GET_ATTR(MAXIMUM_TEXTURE1D_LAYERED_WIDTH);
2257                 GET_ATTR(MAXIMUM_TEXTURE1D_LAYERED_LAYERS);
2258                 GET_ATTR(CAN_TEX2D_GATHER);
2259                 GET_ATTR(MAXIMUM_TEXTURE2D_GATHER_WIDTH);
2260                 GET_ATTR(MAXIMUM_TEXTURE2D_GATHER_HEIGHT);
2261                 GET_ATTR(MAXIMUM_TEXTURE3D_WIDTH_ALTERNATE);
2262                 GET_ATTR(MAXIMUM_TEXTURE3D_HEIGHT_ALTERNATE);
2263                 GET_ATTR(MAXIMUM_TEXTURE3D_DEPTH_ALTERNATE);
2264                 GET_ATTR(TEXTURE_PITCH_ALIGNMENT);
2265                 GET_ATTR(MAXIMUM_TEXTURECUBEMAP_WIDTH);
2266                 GET_ATTR(MAXIMUM_TEXTURECUBEMAP_LAYERED_WIDTH);
2267                 GET_ATTR(MAXIMUM_TEXTURECUBEMAP_LAYERED_LAYERS);
2268                 GET_ATTR(MAXIMUM_SURFACE1D_WIDTH);
2269                 GET_ATTR(MAXIMUM_SURFACE2D_WIDTH);
2270                 GET_ATTR(MAXIMUM_SURFACE2D_HEIGHT);
2271                 GET_ATTR(MAXIMUM_SURFACE3D_WIDTH);
2272                 GET_ATTR(MAXIMUM_SURFACE3D_HEIGHT);
2273                 GET_ATTR(MAXIMUM_SURFACE3D_DEPTH);
2274                 GET_ATTR(MAXIMUM_SURFACE1D_LAYERED_WIDTH);
2275                 GET_ATTR(MAXIMUM_SURFACE1D_LAYERED_LAYERS);
2276                 GET_ATTR(MAXIMUM_SURFACE2D_LAYERED_WIDTH);
2277                 GET_ATTR(MAXIMUM_SURFACE2D_LAYERED_HEIGHT);
2278                 GET_ATTR(MAXIMUM_SURFACE2D_LAYERED_LAYERS);
2279                 GET_ATTR(MAXIMUM_SURFACECUBEMAP_WIDTH);
2280                 GET_ATTR(MAXIMUM_SURFACECUBEMAP_LAYERED_WIDTH);
2281                 GET_ATTR(MAXIMUM_SURFACECUBEMAP_LAYERED_LAYERS);
2282                 GET_ATTR(MAXIMUM_TEXTURE1D_LINEAR_WIDTH);
2283                 GET_ATTR(MAXIMUM_TEXTURE2D_LINEAR_WIDTH);
2284                 GET_ATTR(MAXIMUM_TEXTURE2D_LINEAR_HEIGHT);
2285                 GET_ATTR(MAXIMUM_TEXTURE2D_LINEAR_PITCH);
2286                 GET_ATTR(MAXIMUM_TEXTURE2D_MIPMAPPED_WIDTH);
2287                 GET_ATTR(MAXIMUM_TEXTURE2D_MIPMAPPED_HEIGHT);
2288                 GET_ATTR(COMPUTE_CAPABILITY_MAJOR);
2289                 GET_ATTR(COMPUTE_CAPABILITY_MINOR);
2290                 GET_ATTR(MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH);
2291                 GET_ATTR(STREAM_PRIORITIES_SUPPORTED);
2292                 GET_ATTR(GLOBAL_L1_CACHE_SUPPORTED);
2293                 GET_ATTR(LOCAL_L1_CACHE_SUPPORTED);
2294                 GET_ATTR(MAX_SHARED_MEMORY_PER_MULTIPROCESSOR);
2295                 GET_ATTR(MAX_REGISTERS_PER_MULTIPROCESSOR);
2296                 GET_ATTR(MANAGED_MEMORY);
2297                 GET_ATTR(MULTI_GPU_BOARD);
2298                 GET_ATTR(MULTI_GPU_BOARD_GROUP_ID);
2299 #undef GET_ATTR
2300                 capabilities += "\n";
2301         }
2302
2303         return capabilities;
2304 }
2305
2306 CCL_NAMESPACE_END