Cycles: Add option to directly link against CUDA libraries
[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 <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20
21 #include "device.h"
22 #include "device_intern.h"
23
24 #include "buffers.h"
25
26 #ifdef WITH_CUDA_DYNLOAD
27 #  include "cuew.h"
28 #else
29 #  include "util_opengl.h"
30 #  include <cuda.h>
31 #  include <cudaGL.h>
32 #endif
33 #include "util_debug.h"
34 #include "util_logging.h"
35 #include "util_map.h"
36 #include "util_md5.h"
37 #include "util_opengl.h"
38 #include "util_path.h"
39 #include "util_string.h"
40 #include "util_system.h"
41 #include "util_types.h"
42 #include "util_time.h"
43
44 /* use feature-adaptive kernel compilation.
45  * Requires CUDA toolkit to be installed and currently only works on Linux.
46  */
47 /* #define KERNEL_USE_ADAPTIVE */
48
49 CCL_NAMESPACE_BEGIN
50
51 #ifndef WITH_CUDA_DYNLOAD
52
53 /* Transparently implement some functions, so majority of the file does not need
54  * to worry about difference between dynamically loaded and linked CUDA at all.
55  */
56
57 namespace {
58
59 const char *cuewErrorString(CUresult result)
60 {
61         /* We can only give error code here without major code duplication, that
62          * should be enough since dynamic loading is only being disabled by folks
63          * who knows what they're doing anyway.
64          *
65          * NOTE: Avoid call from several threads.
66          */
67         static string error;
68         error = string_printf("%d", result);
69         return error.c_str();
70 }
71
72 const char *cuewCompilerPath(void)
73 {
74         return CYCLES_CUDA_NVCC_EXECUTABLE;
75 }
76
77 int cuewCompilerVersion(void)
78 {
79         return (CUDA_VERSION / 100) + (CUDA_VERSION % 100 / 10);
80 }
81
82 }  /* namespace */
83 #endif  /* WITH_CUDA_DYNLOAD */
84
85 class CUDADevice : public Device
86 {
87 public:
88         DedicatedTaskPool task_pool;
89         CUdevice cuDevice;
90         CUcontext cuContext;
91         CUmodule cuModule;
92         map<device_ptr, bool> tex_interp_map;
93         int cuDevId;
94         int cuDevArchitecture;
95         bool first_error;
96         bool use_texture_storage;
97
98         struct PixelMem {
99                 GLuint cuPBO;
100                 CUgraphicsResource cuPBOresource;
101                 GLuint cuTexId;
102                 int w, h;
103         };
104
105         map<device_ptr, PixelMem> pixel_mem_map;
106
107         CUdeviceptr cuda_device_ptr(device_ptr mem)
108         {
109                 return (CUdeviceptr)mem;
110         }
111
112         static bool have_precompiled_kernels()
113         {
114                 string cubins_path = path_get("lib");
115                 return path_exists(cubins_path);
116         }
117
118 /*#ifdef NDEBUG
119 #define cuda_abort()
120 #else
121 #define cuda_abort() abort()
122 #endif*/
123         void cuda_error_documentation()
124         {
125                 if(first_error) {
126                         fprintf(stderr, "\nRefer to the Cycles GPU rendering documentation for possible solutions:\n");
127                         fprintf(stderr, "http://www.blender.org/manual/render/cycles/gpu_rendering.html\n\n");
128                         first_error = false;
129                 }
130         }
131
132 #define cuda_assert(stmt) \
133         { \
134                 CUresult result = stmt; \
135                 \
136                 if(result != CUDA_SUCCESS) { \
137                         string message = string_printf("CUDA error: %s in %s", cuewErrorString(result), #stmt); \
138                         if(error_msg == "") \
139                                 error_msg = message; \
140                         fprintf(stderr, "%s\n", message.c_str()); \
141                         /*cuda_abort();*/ \
142                         cuda_error_documentation(); \
143                 } \
144         } (void)0
145
146         bool cuda_error_(CUresult result, const string& stmt)
147         {
148                 if(result == CUDA_SUCCESS)
149                         return false;
150
151                 string message = string_printf("CUDA error at %s: %s", stmt.c_str(), cuewErrorString(result));
152                 if(error_msg == "")
153                         error_msg = message;
154                 fprintf(stderr, "%s\n", message.c_str());
155                 cuda_error_documentation();
156                 return true;
157         }
158
159 #define cuda_error(stmt) cuda_error_(stmt, #stmt)
160
161         void cuda_error_message(const string& message)
162         {
163                 if(error_msg == "")
164                         error_msg = message;
165                 fprintf(stderr, "%s\n", message.c_str());
166                 cuda_error_documentation();
167         }
168
169         void cuda_push_context()
170         {
171                 cuda_assert(cuCtxSetCurrent(cuContext));
172         }
173
174         void cuda_pop_context()
175         {
176                 cuda_assert(cuCtxSetCurrent(NULL));
177         }
178
179         CUDADevice(DeviceInfo& info, Stats &stats, bool background_)
180         : Device(info, stats, background_)
181         {
182                 first_error = true;
183                 background = background_;
184                 use_texture_storage = true;
185
186                 cuDevId = info.num;
187                 cuDevice = 0;
188                 cuContext = 0;
189
190                 /* intialize */
191                 if(cuda_error(cuInit(0)))
192                         return;
193
194                 /* setup device and context */
195                 if(cuda_error(cuDeviceGet(&cuDevice, cuDevId)))
196                         return;
197
198                 CUresult result;
199
200                 if(background) {
201                         result = cuCtxCreate(&cuContext, 0, cuDevice);
202                 }
203                 else {
204                         result = cuGLCtxCreate(&cuContext, 0, cuDevice);
205
206                         if(result != CUDA_SUCCESS) {
207                                 result = cuCtxCreate(&cuContext, 0, cuDevice);
208                                 background = true;
209                         }
210                 }
211
212                 if(cuda_error_(result, "cuCtxCreate"))
213                         return;
214
215                 int major, minor;
216                 cuDeviceComputeCapability(&major, &minor, cuDevId);
217                 cuDevArchitecture = major*100 + minor*10;
218
219                 /* In order to use full 6GB of memory on Titan cards, use arrays instead
220                  * of textures. On earlier cards this seems slower, but on Titan it is
221                  * actually slightly faster in tests. */
222                 use_texture_storage = (cuDevArchitecture < 300);
223
224                 cuda_pop_context();
225         }
226
227         ~CUDADevice()
228         {
229                 task_pool.stop();
230
231                 cuda_assert(cuCtxDestroy(cuContext));
232         }
233
234         bool support_device(const DeviceRequestedFeatures& /*requested_features*/)
235         {
236                 int major, minor;
237                 cuDeviceComputeCapability(&major, &minor, cuDevId);
238
239                 /* We only support sm_20 and above */
240                 if(major < 2) {
241                         cuda_error_message(string_printf("CUDA device supported only with compute capability 2.0 or up, found %d.%d.", major, minor));
242                         return false;
243                 }
244
245                 return true;
246         }
247
248         string compile_kernel(const DeviceRequestedFeatures& requested_features)
249         {
250                 /* compute cubin name */
251                 int major, minor;
252                 cuDeviceComputeCapability(&major, &minor, cuDevId);
253                 string cubin;
254
255                 /* attempt to use kernel provided with blender */
256                 if(requested_features.experimental)
257                         cubin = path_get(string_printf("lib/kernel_experimental_sm_%d%d.cubin", major, minor));
258                 else
259                         cubin = path_get(string_printf("lib/kernel_sm_%d%d.cubin", major, minor));
260                 VLOG(1) << "Testing for pre-compiled kernel " << cubin;
261                 if(path_exists(cubin)) {
262                         VLOG(1) << "Using precompiled kernel";
263                         return cubin;
264                 }
265
266                 /* not found, try to use locally compiled kernel */
267                 string kernel_path = path_get("kernel");
268                 string md5 = path_files_md5_hash(kernel_path);
269
270 #ifdef KERNEL_USE_ADAPTIVE
271                 string feature_build_options = requested_features.get_build_options();
272                 string device_md5 = util_md5_string(feature_build_options);
273                 cubin = string_printf("cycles_kernel_%s_sm%d%d_%s.cubin",
274                                       device_md5.c_str(),
275                                       major, minor,
276                                       md5.c_str());
277 #else
278                 if(requested_features.experimental)
279                         cubin = string_printf("cycles_kernel_experimental_sm%d%d_%s.cubin", major, minor, md5.c_str());
280                 else
281                         cubin = string_printf("cycles_kernel_sm%d%d_%s.cubin", major, minor, md5.c_str());
282 #endif
283
284                 cubin = path_user_get(path_join("cache", cubin));
285                 VLOG(1) << "Testing for locally compiled kernel " << cubin;
286                 /* if exists already, use it */
287                 if(path_exists(cubin)) {
288                         VLOG(1) << "Using locally compiled kernel";
289                         return cubin;
290                 }
291
292 #ifdef _WIN32
293                 if(have_precompiled_kernels()) {
294                         if(major < 2)
295                                 cuda_error_message(string_printf("CUDA device requires compute capability 2.0 or up, found %d.%d. Your GPU is not supported.", major, minor));
296                         else
297                                 cuda_error_message(string_printf("CUDA binary kernel for this graphics card compute capability (%d.%d) not found.", major, minor));
298                         return "";
299                 }
300 #endif
301
302                 /* if not, find CUDA compiler */
303                 const char *nvcc = cuewCompilerPath();
304
305                 if(nvcc == NULL) {
306                         cuda_error_message("CUDA nvcc compiler not found. Install CUDA toolkit in default location.");
307                         return "";
308                 }
309
310                 int cuda_version = cuewCompilerVersion();
311                 VLOG(1) << "Found nvcc " << nvcc << ", CUDA version " << cuda_version;
312
313                 if(cuda_version == 0) {
314                         cuda_error_message("CUDA nvcc compiler version could not be parsed.");
315                         return "";
316                 }
317                 if(cuda_version < 60) {
318                         printf("Unsupported CUDA version %d.%d detected, you need CUDA 6.5.\n", cuda_version/10, cuda_version%10);
319                         return "";
320                 }
321                 else if(cuda_version != 65)
322                         printf("CUDA version %d.%d detected, build may succeed but only CUDA 6.5 is officially supported.\n", cuda_version/10, cuda_version%10);
323
324                 /* compile */
325                 string kernel = path_join(kernel_path, path_join("kernels", path_join("cuda", "kernel.cu")));
326                 string include = kernel_path;
327                 const int machine = system_cpu_bits();
328
329                 double starttime = time_dt();
330                 printf("Compiling CUDA kernel ...\n");
331
332                 path_create_directories(cubin);
333
334                 string command = string_printf("\"%s\" -arch=sm_%d%d -m%d --cubin \"%s\" "
335                         "-o \"%s\" --ptxas-options=\"-v\" --use_fast_math -I\"%s\" "
336                         "-DNVCC -D__KERNEL_CUDA_VERSION__=%d",
337                         nvcc, major, minor, machine, kernel.c_str(), cubin.c_str(), include.c_str(), cuda_version);
338
339 #ifdef KERNEL_USE_ADAPTIVE
340                 command += " " + feature_build_options;
341 #else
342                 if(requested_features.experimental) {
343                         command += " -D__KERNEL_EXPERIMENTAL__";
344                 }
345 #endif
346
347                 const char* extra_cflags = getenv("CYCLES_CUDA_EXTRA_CFLAGS");
348                 if(extra_cflags) {
349                         command += string(" ") + string(extra_cflags);
350                 }
351
352 #ifdef WITH_CYCLES_DEBUG
353                 command += " -D__KERNEL_DEBUG__";
354 #endif
355
356                 printf("%s\n", command.c_str());
357
358                 if(system(command.c_str()) == -1) {
359                         cuda_error_message("Failed to execute compilation command, see console for details.");
360                         return "";
361                 }
362
363                 /* verify if compilation succeeded */
364                 if(!path_exists(cubin)) {
365                         cuda_error_message("CUDA kernel compilation failed, see console for details.");
366                         return "";
367                 }
368
369                 printf("Kernel compilation finished in %.2lfs.\n", time_dt() - starttime);
370
371                 return cubin;
372         }
373
374         bool load_kernels(const DeviceRequestedFeatures& requested_features)
375         {
376                 /* check if cuda init succeeded */
377                 if(cuContext == 0)
378                         return false;
379
380                 /* check if GPU is supported */
381                 if(!support_device(requested_features))
382                         return false;
383
384                 /* get kernel */
385                 string cubin = compile_kernel(requested_features);
386
387                 if(cubin == "")
388                         return false;
389
390                 /* open module */
391                 cuda_push_context();
392
393                 string cubin_data;
394                 CUresult result;
395
396                 if(path_read_text(cubin, cubin_data))
397                         result = cuModuleLoadData(&cuModule, cubin_data.c_str());
398                 else
399                         result = CUDA_ERROR_FILE_NOT_FOUND;
400
401                 if(cuda_error_(result, "cuModuleLoad"))
402                         cuda_error_message(string_printf("Failed loading CUDA kernel %s.", cubin.c_str()));
403
404                 cuda_pop_context();
405
406                 return (result == CUDA_SUCCESS);
407         }
408
409         void mem_alloc(device_memory& mem, MemoryType /*type*/)
410         {
411                 cuda_push_context();
412                 CUdeviceptr device_pointer;
413                 size_t size = mem.memory_size();
414                 cuda_assert(cuMemAlloc(&device_pointer, size));
415                 mem.device_pointer = (device_ptr)device_pointer;
416                 mem.device_size = size;
417                 stats.mem_alloc(size);
418                 cuda_pop_context();
419         }
420
421         void mem_copy_to(device_memory& mem)
422         {
423                 cuda_push_context();
424                 if(mem.device_pointer)
425                         cuda_assert(cuMemcpyHtoD(cuda_device_ptr(mem.device_pointer), (void*)mem.data_pointer, mem.memory_size()));
426                 cuda_pop_context();
427         }
428
429         void mem_copy_from(device_memory& mem, int y, int w, int h, int elem)
430         {
431                 size_t offset = elem*y*w;
432                 size_t size = elem*w*h;
433
434                 cuda_push_context();
435                 if(mem.device_pointer) {
436                         cuda_assert(cuMemcpyDtoH((uchar*)mem.data_pointer + offset,
437                                                  (CUdeviceptr)(mem.device_pointer + offset), size));
438                 }
439                 else {
440                         memset((char*)mem.data_pointer + offset, 0, size);
441                 }
442                 cuda_pop_context();
443         }
444
445         void mem_zero(device_memory& mem)
446         {
447                 memset((void*)mem.data_pointer, 0, mem.memory_size());
448
449                 cuda_push_context();
450                 if(mem.device_pointer)
451                         cuda_assert(cuMemsetD8(cuda_device_ptr(mem.device_pointer), 0, mem.memory_size()));
452                 cuda_pop_context();
453         }
454
455         void mem_free(device_memory& mem)
456         {
457                 if(mem.device_pointer) {
458                         cuda_push_context();
459                         cuda_assert(cuMemFree(cuda_device_ptr(mem.device_pointer)));
460                         cuda_pop_context();
461
462                         mem.device_pointer = 0;
463
464                         stats.mem_free(mem.device_size);
465                         mem.device_size = 0;
466                 }
467         }
468
469         void const_copy_to(const char *name, void *host, size_t size)
470         {
471                 CUdeviceptr mem;
472                 size_t bytes;
473
474                 cuda_push_context();
475                 cuda_assert(cuModuleGetGlobal(&mem, &bytes, cuModule, name));
476                 //assert(bytes == size);
477                 cuda_assert(cuMemcpyHtoD(mem, host, size));
478                 cuda_pop_context();
479         }
480
481         void tex_alloc(const char *name,
482                        device_memory& mem,
483                        InterpolationType interpolation,
484                        ExtensionType extension)
485         {
486                 /* todo: support 3D textures, only CPU for now */
487                 VLOG(1) << "Texture allocate: " << name << ", " << mem.memory_size() << " bytes.";
488
489                 /* determine format */
490                 CUarray_format_enum format;
491                 size_t dsize = datatype_size(mem.data_type);
492                 size_t size = mem.memory_size();
493                 bool use_texture = (interpolation != INTERPOLATION_NONE) || use_texture_storage;
494
495                 if(use_texture) {
496
497                         switch(mem.data_type) {
498                                 case TYPE_UCHAR: format = CU_AD_FORMAT_UNSIGNED_INT8; break;
499                                 case TYPE_UINT: format = CU_AD_FORMAT_UNSIGNED_INT32; break;
500                                 case TYPE_INT: format = CU_AD_FORMAT_SIGNED_INT32; break;
501                                 case TYPE_FLOAT: format = CU_AD_FORMAT_FLOAT; break;
502                                 default: assert(0); return;
503                         }
504
505                         CUtexref texref = NULL;
506
507                         cuda_push_context();
508                         cuda_assert(cuModuleGetTexRef(&texref, cuModule, name));
509
510                         if(!texref) {
511                                 cuda_pop_context();
512                                 return;
513                         }
514
515                         if(interpolation != INTERPOLATION_NONE) {
516                                 CUarray handle = NULL;
517                                 CUDA_ARRAY_DESCRIPTOR desc;
518
519                                 desc.Width = mem.data_width;
520                                 desc.Height = mem.data_height;
521                                 desc.Format = format;
522                                 desc.NumChannels = mem.data_elements;
523
524                                 cuda_assert(cuArrayCreate(&handle, &desc));
525
526                                 if(!handle) {
527                                         cuda_pop_context();
528                                         return;
529                                 }
530
531                                 if(mem.data_height > 1) {
532                                         CUDA_MEMCPY2D param;
533                                         memset(&param, 0, sizeof(param));
534                                         param.dstMemoryType = CU_MEMORYTYPE_ARRAY;
535                                         param.dstArray = handle;
536                                         param.srcMemoryType = CU_MEMORYTYPE_HOST;
537                                         param.srcHost = (void*)mem.data_pointer;
538                                         param.srcPitch = mem.data_width*dsize*mem.data_elements;
539                                         param.WidthInBytes = param.srcPitch;
540                                         param.Height = mem.data_height;
541
542                                         cuda_assert(cuMemcpy2D(&param));
543                                 }
544                                 else
545                                         cuda_assert(cuMemcpyHtoA(handle, 0, (void*)mem.data_pointer, size));
546
547                                 cuda_assert(cuTexRefSetArray(texref, handle, CU_TRSA_OVERRIDE_FORMAT));
548
549                                 if(interpolation == INTERPOLATION_CLOSEST) {
550                                         cuda_assert(cuTexRefSetFilterMode(texref, CU_TR_FILTER_MODE_POINT));
551                                 }
552                                 else if(interpolation == INTERPOLATION_LINEAR) {
553                                         cuda_assert(cuTexRefSetFilterMode(texref, CU_TR_FILTER_MODE_LINEAR));
554                                 }
555                                 else {/* CUBIC and SMART are unsupported for CUDA */
556                                         cuda_assert(cuTexRefSetFilterMode(texref, CU_TR_FILTER_MODE_LINEAR));
557                                 }
558                                 cuda_assert(cuTexRefSetFlags(texref, CU_TRSF_NORMALIZED_COORDINATES));
559
560                                 mem.device_pointer = (device_ptr)handle;
561                                 mem.device_size = size;
562
563                                 stats.mem_alloc(size);
564                         }
565                         else {
566                                 cuda_pop_context();
567
568                                 mem_alloc(mem, MEM_READ_ONLY);
569                                 mem_copy_to(mem);
570
571                                 cuda_push_context();
572
573                                 cuda_assert(cuTexRefSetAddress(NULL, texref, cuda_device_ptr(mem.device_pointer), size));
574                                 cuda_assert(cuTexRefSetFilterMode(texref, CU_TR_FILTER_MODE_POINT));
575                                 cuda_assert(cuTexRefSetFlags(texref, CU_TRSF_READ_AS_INTEGER));
576                         }
577
578                         switch(extension) {
579                                 case EXTENSION_REPEAT:
580                                         cuda_assert(cuTexRefSetAddressMode(texref, 0, CU_TR_ADDRESS_MODE_WRAP));
581                                         cuda_assert(cuTexRefSetAddressMode(texref, 1, CU_TR_ADDRESS_MODE_WRAP));
582                                         break;
583                                 case EXTENSION_EXTEND:
584                                         cuda_assert(cuTexRefSetAddressMode(texref, 0, CU_TR_ADDRESS_MODE_CLAMP));
585                                         cuda_assert(cuTexRefSetAddressMode(texref, 1, CU_TR_ADDRESS_MODE_CLAMP));
586                                         break;
587                                 case EXTENSION_CLIP:
588                                         cuda_assert(cuTexRefSetAddressMode(texref, 0, CU_TR_ADDRESS_MODE_BORDER));
589                                         cuda_assert(cuTexRefSetAddressMode(texref, 1, CU_TR_ADDRESS_MODE_BORDER));
590                                         break;
591                         }
592                         cuda_assert(cuTexRefSetFormat(texref, format, mem.data_elements));
593
594                         cuda_pop_context();
595                 }
596                 else {
597                         mem_alloc(mem, MEM_READ_ONLY);
598                         mem_copy_to(mem);
599
600                         cuda_push_context();
601
602                         CUdeviceptr cumem;
603                         size_t cubytes;
604
605                         cuda_assert(cuModuleGetGlobal(&cumem, &cubytes, cuModule, name));
606
607                         if(cubytes == 8) {
608                                 /* 64 bit device pointer */
609                                 uint64_t ptr = mem.device_pointer;
610                                 cuda_assert(cuMemcpyHtoD(cumem, (void*)&ptr, cubytes));
611                         }
612                         else {
613                                 /* 32 bit device pointer */
614                                 uint32_t ptr = (uint32_t)mem.device_pointer;
615                                 cuda_assert(cuMemcpyHtoD(cumem, (void*)&ptr, cubytes));
616                         }
617
618                         cuda_pop_context();
619                 }
620
621                 tex_interp_map[mem.device_pointer] = (interpolation != INTERPOLATION_NONE);
622         }
623
624         void tex_free(device_memory& mem)
625         {
626                 if(mem.device_pointer) {
627                         if(tex_interp_map[mem.device_pointer]) {
628                                 cuda_push_context();
629                                 cuArrayDestroy((CUarray)mem.device_pointer);
630                                 cuda_pop_context();
631
632                                 tex_interp_map.erase(tex_interp_map.find(mem.device_pointer));
633                                 mem.device_pointer = 0;
634
635                                 stats.mem_free(mem.device_size);
636                                 mem.device_size = 0;
637                         }
638                         else {
639                                 tex_interp_map.erase(tex_interp_map.find(mem.device_pointer));
640                                 mem_free(mem);
641                         }
642                 }
643         }
644
645         void path_trace(RenderTile& rtile, int sample, bool branched)
646         {
647                 if(have_error())
648                         return;
649
650                 cuda_push_context();
651
652                 CUfunction cuPathTrace;
653                 CUdeviceptr d_buffer = cuda_device_ptr(rtile.buffer);
654                 CUdeviceptr d_rng_state = cuda_device_ptr(rtile.rng_state);
655
656                 /* get kernel function */
657                 if(branched) {
658                         cuda_assert(cuModuleGetFunction(&cuPathTrace, cuModule, "kernel_cuda_branched_path_trace"));
659                 }
660                 else {
661                         cuda_assert(cuModuleGetFunction(&cuPathTrace, cuModule, "kernel_cuda_path_trace"));
662                 }
663
664                 if(have_error())
665                         return;
666
667                 /* pass in parameters */
668                 void *args[] = {&d_buffer,
669                                                  &d_rng_state,
670                                                  &sample,
671                                                  &rtile.x,
672                                                  &rtile.y,
673                                                  &rtile.w,
674                                                  &rtile.h,
675                                                  &rtile.offset,
676                                                  &rtile.stride};
677
678                 /* launch kernel */
679                 int threads_per_block;
680                 cuda_assert(cuFuncGetAttribute(&threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, cuPathTrace));
681
682                 /*int num_registers;
683                 cuda_assert(cuFuncGetAttribute(&num_registers, CU_FUNC_ATTRIBUTE_NUM_REGS, cuPathTrace));
684
685                 printf("threads_per_block %d\n", threads_per_block);
686                 printf("num_registers %d\n", num_registers);*/
687
688                 int xthreads = (int)sqrt((float)threads_per_block);
689                 int ythreads = (int)sqrt((float)threads_per_block);
690                 int xblocks = (rtile.w + xthreads - 1)/xthreads;
691                 int yblocks = (rtile.h + ythreads - 1)/ythreads;
692
693                 cuda_assert(cuFuncSetCacheConfig(cuPathTrace, CU_FUNC_CACHE_PREFER_L1));
694
695                 cuda_assert(cuLaunchKernel(cuPathTrace,
696                                                                    xblocks , yblocks, 1, /* blocks */
697                                                                    xthreads, ythreads, 1, /* threads */
698                                                                    0, 0, args, 0));
699
700                 cuda_assert(cuCtxSynchronize());
701
702                 cuda_pop_context();
703         }
704
705         void film_convert(DeviceTask& task, device_ptr buffer, device_ptr rgba_byte, device_ptr rgba_half)
706         {
707                 if(have_error())
708                         return;
709
710                 cuda_push_context();
711
712                 CUfunction cuFilmConvert;
713                 CUdeviceptr d_rgba = map_pixels((rgba_byte)? rgba_byte: rgba_half);
714                 CUdeviceptr d_buffer = cuda_device_ptr(buffer);
715
716                 /* get kernel function */
717                 if(rgba_half) {
718                         cuda_assert(cuModuleGetFunction(&cuFilmConvert, cuModule, "kernel_cuda_convert_to_half_float"));
719                 }
720                 else {
721                         cuda_assert(cuModuleGetFunction(&cuFilmConvert, cuModule, "kernel_cuda_convert_to_byte"));
722                 }
723
724
725                 float sample_scale = 1.0f/(task.sample + 1);
726
727                 /* pass in parameters */
728                 void *args[] = {&d_rgba,
729                                                  &d_buffer,
730                                                  &sample_scale,
731                                                  &task.x,
732                                                  &task.y,
733                                                  &task.w,
734                                                  &task.h,
735                                                  &task.offset,
736                                                  &task.stride};
737
738                 /* launch kernel */
739                 int threads_per_block;
740                 cuda_assert(cuFuncGetAttribute(&threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, cuFilmConvert));
741
742                 int xthreads = (int)sqrt((float)threads_per_block);
743                 int ythreads = (int)sqrt((float)threads_per_block);
744                 int xblocks = (task.w + xthreads - 1)/xthreads;
745                 int yblocks = (task.h + ythreads - 1)/ythreads;
746
747                 cuda_assert(cuFuncSetCacheConfig(cuFilmConvert, CU_FUNC_CACHE_PREFER_L1));
748
749                 cuda_assert(cuLaunchKernel(cuFilmConvert,
750                                                                    xblocks , yblocks, 1, /* blocks */
751                                                                    xthreads, ythreads, 1, /* threads */
752                                                                    0, 0, args, 0));
753
754                 unmap_pixels((rgba_byte)? rgba_byte: rgba_half);
755
756                 cuda_pop_context();
757         }
758
759         void shader(DeviceTask& task)
760         {
761                 if(have_error())
762                         return;
763
764                 cuda_push_context();
765
766                 CUfunction cuShader;
767                 CUdeviceptr d_input = cuda_device_ptr(task.shader_input);
768                 CUdeviceptr d_output = cuda_device_ptr(task.shader_output);
769                 CUdeviceptr d_output_luma = cuda_device_ptr(task.shader_output_luma);
770
771                 /* get kernel function */
772                 if(task.shader_eval_type >= SHADER_EVAL_BAKE) {
773                         cuda_assert(cuModuleGetFunction(&cuShader, cuModule, "kernel_cuda_bake"));
774                 }
775                 else {
776                         cuda_assert(cuModuleGetFunction(&cuShader, cuModule, "kernel_cuda_shader"));
777                 }
778
779                 /* do tasks in smaller chunks, so we can cancel it */
780                 const int shader_chunk_size = 65536;
781                 const int start = task.shader_x;
782                 const int end = task.shader_x + task.shader_w;
783                 int offset = task.offset;
784
785                 bool canceled = false;
786                 for(int sample = 0; sample < task.num_samples && !canceled; sample++) {
787                         for(int shader_x = start; shader_x < end; shader_x += shader_chunk_size) {
788                                 int shader_w = min(shader_chunk_size, end - shader_x);
789
790                                 /* pass in parameters */
791                                 void *args[8];
792                                 int arg = 0;
793                                 args[arg++] = &d_input;
794                                 args[arg++] = &d_output;
795                                 if(task.shader_eval_type < SHADER_EVAL_BAKE) {
796                                         args[arg++] = &d_output_luma;
797                                 }
798                                 args[arg++] = &task.shader_eval_type;
799                                 args[arg++] = &shader_x;
800                                 args[arg++] = &shader_w;
801                                 args[arg++] = &offset;
802                                 args[arg++] = &sample;
803
804                                 /* launch kernel */
805                                 int threads_per_block;
806                                 cuda_assert(cuFuncGetAttribute(&threads_per_block, CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, cuShader));
807
808                                 int xblocks = (shader_w + threads_per_block - 1)/threads_per_block;
809
810                                 cuda_assert(cuFuncSetCacheConfig(cuShader, CU_FUNC_CACHE_PREFER_L1));
811                                 cuda_assert(cuLaunchKernel(cuShader,
812                                                                                    xblocks , 1, 1, /* blocks */
813                                                                                    threads_per_block, 1, 1, /* threads */
814                                                                                    0, 0, args, 0));
815
816                                 cuda_assert(cuCtxSynchronize());
817
818                                 if(task.get_cancel()) {
819                                         canceled = false;
820                                         break;
821                                 }
822                         }
823
824                         task.update_progress(NULL);
825                 }
826
827                 cuda_pop_context();
828         }
829
830         CUdeviceptr map_pixels(device_ptr mem)
831         {
832                 if(!background) {
833                         PixelMem pmem = pixel_mem_map[mem];
834                         CUdeviceptr buffer;
835                         
836                         size_t bytes;
837                         cuda_assert(cuGraphicsMapResources(1, &pmem.cuPBOresource, 0));
838                         cuda_assert(cuGraphicsResourceGetMappedPointer(&buffer, &bytes, pmem.cuPBOresource));
839                         
840                         return buffer;
841                 }
842
843                 return cuda_device_ptr(mem);
844         }
845
846         void unmap_pixels(device_ptr mem)
847         {
848                 if(!background) {
849                         PixelMem pmem = pixel_mem_map[mem];
850
851                         cuda_assert(cuGraphicsUnmapResources(1, &pmem.cuPBOresource, 0));
852                 }
853         }
854
855         void pixels_alloc(device_memory& mem)
856         {
857                 if(!background) {
858                         PixelMem pmem;
859
860                         pmem.w = mem.data_width;
861                         pmem.h = mem.data_height;
862
863                         cuda_push_context();
864
865                         glGenBuffers(1, &pmem.cuPBO);
866                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pmem.cuPBO);
867                         if(mem.data_type == TYPE_HALF)
868                                 glBufferData(GL_PIXEL_UNPACK_BUFFER, pmem.w*pmem.h*sizeof(GLhalf)*4, NULL, GL_DYNAMIC_DRAW);
869                         else
870                                 glBufferData(GL_PIXEL_UNPACK_BUFFER, pmem.w*pmem.h*sizeof(uint8_t)*4, NULL, GL_DYNAMIC_DRAW);
871                         
872                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
873                         
874                         glGenTextures(1, &pmem.cuTexId);
875                         glBindTexture(GL_TEXTURE_2D, pmem.cuTexId);
876                         if(mem.data_type == TYPE_HALF)
877                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, pmem.w, pmem.h, 0, GL_RGBA, GL_HALF_FLOAT, NULL);
878                         else
879                                 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, pmem.w, pmem.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
880                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
881                         glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
882                         glBindTexture(GL_TEXTURE_2D, 0);
883                         
884                         CUresult result = cuGraphicsGLRegisterBuffer(&pmem.cuPBOresource, pmem.cuPBO, CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE);
885
886                         if(result == CUDA_SUCCESS) {
887                                 cuda_pop_context();
888
889                                 mem.device_pointer = pmem.cuTexId;
890                                 pixel_mem_map[mem.device_pointer] = pmem;
891
892                                 mem.device_size = mem.memory_size();
893                                 stats.mem_alloc(mem.device_size);
894
895                                 return;
896                         }
897                         else {
898                                 /* failed to register buffer, fallback to no interop */
899                                 glDeleteBuffers(1, &pmem.cuPBO);
900                                 glDeleteTextures(1, &pmem.cuTexId);
901
902                                 cuda_pop_context();
903
904                                 background = true;
905                         }
906                 }
907
908                 Device::pixels_alloc(mem);
909         }
910
911         void pixels_copy_from(device_memory& mem, int y, int w, int h)
912         {
913                 if(!background) {
914                         PixelMem pmem = pixel_mem_map[mem.device_pointer];
915
916                         cuda_push_context();
917
918                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pmem.cuPBO);
919                         uchar *pixels = (uchar*)glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_READ_ONLY);
920                         size_t offset = sizeof(uchar)*4*y*w;
921                         memcpy((uchar*)mem.data_pointer + offset, pixels + offset, sizeof(uchar)*4*w*h);
922                         glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
923                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
924
925                         cuda_pop_context();
926
927                         return;
928                 }
929
930                 Device::pixels_copy_from(mem, y, w, h);
931         }
932
933         void pixels_free(device_memory& mem)
934         {
935                 if(mem.device_pointer) {
936                         if(!background) {
937                                 PixelMem pmem = pixel_mem_map[mem.device_pointer];
938
939                                 cuda_push_context();
940
941                                 cuda_assert(cuGraphicsUnregisterResource(pmem.cuPBOresource));
942                                 glDeleteBuffers(1, &pmem.cuPBO);
943                                 glDeleteTextures(1, &pmem.cuTexId);
944
945                                 cuda_pop_context();
946
947                                 pixel_mem_map.erase(pixel_mem_map.find(mem.device_pointer));
948                                 mem.device_pointer = 0;
949
950                                 stats.mem_free(mem.device_size);
951                                 mem.device_size = 0;
952
953                                 return;
954                         }
955
956                         Device::pixels_free(mem);
957                 }
958         }
959
960         void draw_pixels(device_memory& mem, int y, int w, int h, int dx, int dy, int width, int height, bool transparent,
961                 const DeviceDrawParams &draw_params)
962         {
963                 if(!background) {
964                         PixelMem pmem = pixel_mem_map[mem.device_pointer];
965                         float *vpointer;
966
967                         cuda_push_context();
968
969                         /* for multi devices, this assumes the inefficient method that we allocate
970                          * all pixels on the device even though we only render to a subset */
971                         size_t offset = 4*y*w;
972
973                         if(mem.data_type == TYPE_HALF)
974                                 offset *= sizeof(GLhalf);
975                         else
976                                 offset *= sizeof(uint8_t);
977
978                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pmem.cuPBO);
979                         glBindTexture(GL_TEXTURE_2D, pmem.cuTexId);
980                         if(mem.data_type == TYPE_HALF)
981                                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_HALF_FLOAT, (void*)offset);
982                         else
983                                 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, (void*)offset);
984                         glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
985                         
986                         glEnable(GL_TEXTURE_2D);
987                         
988                         if(transparent) {
989                                 glEnable(GL_BLEND);
990                                 glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
991                         }
992
993                         glColor3f(1.0f, 1.0f, 1.0f);
994
995                         if(draw_params.bind_display_space_shader_cb) {
996                                 draw_params.bind_display_space_shader_cb();
997                         }
998
999                         if(!vertex_buffer)
1000                                 glGenBuffers(1, &vertex_buffer);
1001
1002                         glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
1003                         /* invalidate old contents - avoids stalling if buffer is still waiting in queue to be rendered */
1004                         glBufferData(GL_ARRAY_BUFFER, 16 * sizeof(float), NULL, GL_STREAM_DRAW);
1005
1006                         vpointer = (float *)glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
1007
1008                         if(vpointer) {
1009                                 /* texture coordinate - vertex pair */
1010                                 vpointer[0] = 0.0f;
1011                                 vpointer[1] = 0.0f;
1012                                 vpointer[2] = dx;
1013                                 vpointer[3] = dy;
1014
1015                                 vpointer[4] = (float)w/(float)pmem.w;
1016                                 vpointer[5] = 0.0f;
1017                                 vpointer[6] = (float)width + dx;
1018                                 vpointer[7] = dy;
1019
1020                                 vpointer[8] = (float)w/(float)pmem.w;
1021                                 vpointer[9] = (float)h/(float)pmem.h;
1022                                 vpointer[10] = (float)width + dx;
1023                                 vpointer[11] = (float)height + dy;
1024
1025                                 vpointer[12] = 0.0f;
1026                                 vpointer[13] = (float)h/(float)pmem.h;
1027                                 vpointer[14] = dx;
1028                                 vpointer[15] = (float)height + dy;
1029
1030                                 glUnmapBuffer(GL_ARRAY_BUFFER);
1031                         }
1032
1033                         glTexCoordPointer(2, GL_FLOAT, 4 * sizeof(float), 0);
1034                         glVertexPointer(2, GL_FLOAT, 4 * sizeof(float), (char *)NULL + 2 * sizeof(float));
1035
1036                         glEnableClientState(GL_VERTEX_ARRAY);
1037                         glEnableClientState(GL_TEXTURE_COORD_ARRAY);
1038
1039                         glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1040
1041                         glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1042                         glDisableClientState(GL_VERTEX_ARRAY);
1043
1044                         glBindBuffer(GL_ARRAY_BUFFER, 0);
1045
1046                         if(draw_params.unbind_display_space_shader_cb) {
1047                                 draw_params.unbind_display_space_shader_cb();
1048                         }
1049
1050                         if(transparent)
1051                                 glDisable(GL_BLEND);
1052                         
1053                         glBindTexture(GL_TEXTURE_2D, 0);
1054                         glDisable(GL_TEXTURE_2D);
1055
1056                         cuda_pop_context();
1057
1058                         return;
1059                 }
1060
1061                 Device::draw_pixels(mem, y, w, h, dx, dy, width, height, transparent, draw_params);
1062         }
1063
1064         void thread_run(DeviceTask *task)
1065         {
1066                 if(task->type == DeviceTask::PATH_TRACE) {
1067                         RenderTile tile;
1068                         
1069                         bool branched = task->integrator_branched;
1070                         
1071                         /* keep rendering tiles until done */
1072                         while(task->acquire_tile(this, tile)) {
1073                                 int start_sample = tile.start_sample;
1074                                 int end_sample = tile.start_sample + tile.num_samples;
1075
1076                                 for(int sample = start_sample; sample < end_sample; sample++) {
1077                                         if(task->get_cancel()) {
1078                                                 if(task->need_finish_queue == false)
1079                                                         break;
1080                                         }
1081
1082                                         path_trace(tile, sample, branched);
1083
1084                                         tile.sample = sample + 1;
1085
1086                                         task->update_progress(&tile);
1087                                 }
1088
1089                                 task->release_tile(tile);
1090                         }
1091                 }
1092                 else if(task->type == DeviceTask::SHADER) {
1093                         shader(*task);
1094
1095                         cuda_push_context();
1096                         cuda_assert(cuCtxSynchronize());
1097                         cuda_pop_context();
1098                 }
1099         }
1100
1101         class CUDADeviceTask : public DeviceTask {
1102         public:
1103                 CUDADeviceTask(CUDADevice *device, DeviceTask& task)
1104                 : DeviceTask(task)
1105                 {
1106                         run = function_bind(&CUDADevice::thread_run, device, this);
1107                 }
1108         };
1109
1110         int get_split_task_count(DeviceTask& /*task*/)
1111         {
1112                 return 1;
1113         }
1114
1115         void task_add(DeviceTask& task)
1116         {
1117                 if(task.type == DeviceTask::FILM_CONVERT) {
1118                         /* must be done in main thread due to opengl access */
1119                         film_convert(task, task.buffer, task.rgba_byte, task.rgba_half);
1120
1121                         cuda_push_context();
1122                         cuda_assert(cuCtxSynchronize());
1123                         cuda_pop_context();
1124                 }
1125                 else {
1126                         task_pool.push(new CUDADeviceTask(this, task));
1127                 }
1128         }
1129
1130         void task_wait()
1131         {
1132                 task_pool.wait();
1133         }
1134
1135         void task_cancel()
1136         {
1137                 task_pool.cancel();
1138         }
1139 };
1140
1141 bool device_cuda_init(void)
1142 {
1143 #ifdef WITH_CUDA_DYNLOAD
1144         static bool initialized = false;
1145         static bool result = false;
1146
1147         if(initialized)
1148                 return result;
1149
1150         initialized = true;
1151         int cuew_result = cuewInit();
1152         if(cuew_result == CUEW_SUCCESS) {
1153                 VLOG(1) << "CUEW initialization succeeded";
1154                 if(CUDADevice::have_precompiled_kernels()) {
1155                         VLOG(1) << "Found precompiled  kernels";
1156                         result = true;
1157                 }
1158 #ifndef _WIN32
1159                 else if(cuewCompilerPath() != NULL) {
1160                         VLOG(1) << "Found CUDA compiled " << cuewCompilerPath();
1161                         result = true;
1162                 }
1163                 else {
1164                         VLOG(1) << "Neither precompiled kernels nor CUDA compiler wad found,"
1165                                 << " unable to use CUDA";
1166                 }
1167 #endif
1168         }
1169         else {
1170                 VLOG(1) << "CUEW initialization failed: "
1171                         << ((cuew_result == CUEW_ERROR_ATEXIT_FAILED)
1172                             ? "Error setting up atexit() handler"
1173                             : "Error opening the library");
1174         }
1175
1176         return result;
1177 #else  /* WITH_CUDA_DYNLOAD */
1178         return true;
1179 #endif /* WITH_CUDA_DYNLOAD */
1180 }
1181
1182 Device *device_cuda_create(DeviceInfo& info, Stats &stats, bool background)
1183 {
1184         return new CUDADevice(info, stats, background);
1185 }
1186
1187 void device_cuda_info(vector<DeviceInfo>& devices)
1188 {
1189         CUresult result;
1190         int count = 0;
1191
1192         result = cuInit(0);
1193         if(result != CUDA_SUCCESS) {
1194                 if(result != CUDA_ERROR_NO_DEVICE)
1195                         fprintf(stderr, "CUDA cuInit: %s\n", cuewErrorString(result));
1196                 return;
1197         }
1198
1199         result = cuDeviceGetCount(&count);
1200         if(result != CUDA_SUCCESS) {
1201                 fprintf(stderr, "CUDA cuDeviceGetCount: %s\n", cuewErrorString(result));
1202                 return;
1203         }
1204         
1205         vector<DeviceInfo> display_devices;
1206
1207         for(int num = 0; num < count; num++) {
1208                 char name[256];
1209                 int attr;
1210
1211                 if(cuDeviceGetName(name, 256, num) != CUDA_SUCCESS)
1212                         continue;
1213
1214                 int major, minor;
1215                 cuDeviceComputeCapability(&major, &minor, num);
1216                 if(major < 2) {
1217                         continue;
1218                 }
1219
1220                 DeviceInfo info;
1221
1222                 info.type = DEVICE_CUDA;
1223                 info.description = string(name);
1224                 info.id = string_printf("CUDA_%d", num);
1225                 info.num = num;
1226
1227                 info.advanced_shading = (major >= 2);
1228                 info.extended_images = (major >= 3);
1229                 info.pack_images = false;
1230
1231                 /* if device has a kernel timeout, assume it is used for display */
1232                 if(cuDeviceGetAttribute(&attr, CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT, num) == CUDA_SUCCESS && attr == 1) {
1233                         info.display_device = true;
1234                         display_devices.push_back(info);
1235                 }
1236                 else
1237                         devices.push_back(info);
1238         }
1239
1240         if(!display_devices.empty())
1241                 devices.insert(devices.end(), display_devices.begin(), display_devices.end());
1242 }
1243
1244 string device_cuda_capabilities(void)
1245 {
1246         CUresult result = cuInit(0);
1247         if(result != CUDA_SUCCESS) {
1248                 if(result != CUDA_ERROR_NO_DEVICE) {
1249                         return string("Error initializing CUDA: ") + cuewErrorString(result);
1250                 }
1251                 return "No CUDA device found\n";
1252         }
1253
1254         int count;
1255         result = cuDeviceGetCount(&count);
1256         if(result != CUDA_SUCCESS) {
1257                 return string("Error getting devices: ") + cuewErrorString(result);
1258         }
1259
1260         string capabilities = "";
1261         for(int num = 0; num < count; num++) {
1262                 char name[256];
1263                 if(cuDeviceGetName(name, 256, num) != CUDA_SUCCESS) {
1264                         continue;
1265                 }
1266                 capabilities += string("\t") + name + "\n";
1267                 int value;
1268 #define GET_ATTR(attr) \
1269                 { \
1270                         if(cuDeviceGetAttribute(&value, \
1271                                                 CU_DEVICE_ATTRIBUTE_##attr, \
1272                                                 num) == CUDA_SUCCESS) \
1273                         { \
1274                                 capabilities += string_printf("\t\tCU_DEVICE_ATTRIBUTE_" #attr "\t\t\t%d\n", \
1275                                                               value); \
1276                         } \
1277                 } (void)0
1278                 /* TODO(sergey): Strip all attributes which are not useful for us
1279                  * or does not depend on the driver.
1280                  */
1281                 GET_ATTR(MAX_THREADS_PER_BLOCK);
1282                 GET_ATTR(MAX_BLOCK_DIM_X);
1283                 GET_ATTR(MAX_BLOCK_DIM_Y);
1284                 GET_ATTR(MAX_BLOCK_DIM_Z);
1285                 GET_ATTR(MAX_GRID_DIM_X);
1286                 GET_ATTR(MAX_GRID_DIM_Y);
1287                 GET_ATTR(MAX_GRID_DIM_Z);
1288                 GET_ATTR(MAX_SHARED_MEMORY_PER_BLOCK);
1289                 GET_ATTR(SHARED_MEMORY_PER_BLOCK);
1290                 GET_ATTR(TOTAL_CONSTANT_MEMORY);
1291                 GET_ATTR(WARP_SIZE);
1292                 GET_ATTR(MAX_PITCH);
1293                 GET_ATTR(MAX_REGISTERS_PER_BLOCK);
1294                 GET_ATTR(REGISTERS_PER_BLOCK);
1295                 GET_ATTR(CLOCK_RATE);
1296                 GET_ATTR(TEXTURE_ALIGNMENT);
1297                 GET_ATTR(GPU_OVERLAP);
1298                 GET_ATTR(MULTIPROCESSOR_COUNT);
1299                 GET_ATTR(KERNEL_EXEC_TIMEOUT);
1300                 GET_ATTR(INTEGRATED);
1301                 GET_ATTR(CAN_MAP_HOST_MEMORY);
1302                 GET_ATTR(COMPUTE_MODE);
1303                 GET_ATTR(MAXIMUM_TEXTURE1D_WIDTH);
1304                 GET_ATTR(MAXIMUM_TEXTURE2D_WIDTH);
1305                 GET_ATTR(MAXIMUM_TEXTURE2D_HEIGHT);
1306                 GET_ATTR(MAXIMUM_TEXTURE3D_WIDTH);
1307                 GET_ATTR(MAXIMUM_TEXTURE3D_HEIGHT);
1308                 GET_ATTR(MAXIMUM_TEXTURE3D_DEPTH);
1309                 GET_ATTR(MAXIMUM_TEXTURE2D_LAYERED_WIDTH);
1310                 GET_ATTR(MAXIMUM_TEXTURE2D_LAYERED_HEIGHT);
1311                 GET_ATTR(MAXIMUM_TEXTURE2D_LAYERED_LAYERS);
1312                 GET_ATTR(MAXIMUM_TEXTURE2D_ARRAY_WIDTH);
1313                 GET_ATTR(MAXIMUM_TEXTURE2D_ARRAY_HEIGHT);
1314                 GET_ATTR(MAXIMUM_TEXTURE2D_ARRAY_NUMSLICES);
1315                 GET_ATTR(SURFACE_ALIGNMENT);
1316                 GET_ATTR(CONCURRENT_KERNELS);
1317                 GET_ATTR(ECC_ENABLED);
1318                 GET_ATTR(TCC_DRIVER);
1319                 GET_ATTR(MEMORY_CLOCK_RATE);
1320                 GET_ATTR(GLOBAL_MEMORY_BUS_WIDTH);
1321                 GET_ATTR(L2_CACHE_SIZE);
1322                 GET_ATTR(MAX_THREADS_PER_MULTIPROCESSOR);
1323                 GET_ATTR(ASYNC_ENGINE_COUNT);
1324                 GET_ATTR(UNIFIED_ADDRESSING);
1325                 GET_ATTR(MAXIMUM_TEXTURE1D_LAYERED_WIDTH);
1326                 GET_ATTR(MAXIMUM_TEXTURE1D_LAYERED_LAYERS);
1327                 GET_ATTR(CAN_TEX2D_GATHER);
1328                 GET_ATTR(MAXIMUM_TEXTURE2D_GATHER_WIDTH);
1329                 GET_ATTR(MAXIMUM_TEXTURE2D_GATHER_HEIGHT);
1330                 GET_ATTR(MAXIMUM_TEXTURE3D_WIDTH_ALTERNATE);
1331                 GET_ATTR(MAXIMUM_TEXTURE3D_HEIGHT_ALTERNATE);
1332                 GET_ATTR(MAXIMUM_TEXTURE3D_DEPTH_ALTERNATE);
1333                 GET_ATTR(TEXTURE_PITCH_ALIGNMENT);
1334                 GET_ATTR(MAXIMUM_TEXTURECUBEMAP_WIDTH);
1335                 GET_ATTR(MAXIMUM_TEXTURECUBEMAP_LAYERED_WIDTH);
1336                 GET_ATTR(MAXIMUM_TEXTURECUBEMAP_LAYERED_LAYERS);
1337                 GET_ATTR(MAXIMUM_SURFACE1D_WIDTH);
1338                 GET_ATTR(MAXIMUM_SURFACE2D_WIDTH);
1339                 GET_ATTR(MAXIMUM_SURFACE2D_HEIGHT);
1340                 GET_ATTR(MAXIMUM_SURFACE3D_WIDTH);
1341                 GET_ATTR(MAXIMUM_SURFACE3D_HEIGHT);
1342                 GET_ATTR(MAXIMUM_SURFACE3D_DEPTH);
1343                 GET_ATTR(MAXIMUM_SURFACE1D_LAYERED_WIDTH);
1344                 GET_ATTR(MAXIMUM_SURFACE1D_LAYERED_LAYERS);
1345                 GET_ATTR(MAXIMUM_SURFACE2D_LAYERED_WIDTH);
1346                 GET_ATTR(MAXIMUM_SURFACE2D_LAYERED_HEIGHT);
1347                 GET_ATTR(MAXIMUM_SURFACE2D_LAYERED_LAYERS);
1348                 GET_ATTR(MAXIMUM_SURFACECUBEMAP_WIDTH);
1349                 GET_ATTR(MAXIMUM_SURFACECUBEMAP_LAYERED_WIDTH);
1350                 GET_ATTR(MAXIMUM_SURFACECUBEMAP_LAYERED_LAYERS);
1351                 GET_ATTR(MAXIMUM_TEXTURE1D_LINEAR_WIDTH);
1352                 GET_ATTR(MAXIMUM_TEXTURE2D_LINEAR_WIDTH);
1353                 GET_ATTR(MAXIMUM_TEXTURE2D_LINEAR_HEIGHT);
1354                 GET_ATTR(MAXIMUM_TEXTURE2D_LINEAR_PITCH);
1355                 GET_ATTR(MAXIMUM_TEXTURE2D_MIPMAPPED_WIDTH);
1356                 GET_ATTR(MAXIMUM_TEXTURE2D_MIPMAPPED_HEIGHT);
1357                 GET_ATTR(COMPUTE_CAPABILITY_MAJOR);
1358                 GET_ATTR(COMPUTE_CAPABILITY_MINOR);
1359                 GET_ATTR(MAXIMUM_TEXTURE1D_MIPMAPPED_WIDTH);
1360                 GET_ATTR(STREAM_PRIORITIES_SUPPORTED);
1361                 GET_ATTR(GLOBAL_L1_CACHE_SUPPORTED);
1362                 GET_ATTR(LOCAL_L1_CACHE_SUPPORTED);
1363                 GET_ATTR(MAX_SHARED_MEMORY_PER_MULTIPROCESSOR);
1364                 GET_ATTR(MAX_REGISTERS_PER_MULTIPROCESSOR);
1365                 GET_ATTR(MANAGED_MEMORY);
1366                 GET_ATTR(MULTI_GPU_BOARD);
1367                 GET_ATTR(MULTI_GPU_BOARD_GROUP_ID);
1368 #undef GET_ATTR
1369                 capabilities += "\n";
1370         }
1371
1372         return capabilities;
1373 }
1374
1375 CCL_NAMESPACE_END