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