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