Cycles: Remove unneeded include statements
[blender-staging.git] / intern / cycles / device / opencl / opencl_split.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 #ifdef WITH_OPENCL
18
19 #include "device/opencl/opencl.h"
20
21 #include "render/buffers.h"
22
23 #include "kernel/kernel_types.h"
24 #include "kernel/split/kernel_split_data_types.h"
25
26 #include "device/device_split_kernel.h"
27
28 #include "util/util_algorithm.h"
29 #include "util/util_debug.h"
30 #include "util/util_logging.h"
31 #include "util/util_md5.h"
32 #include "util/util_path.h"
33 #include "util/util_time.h"
34
35 CCL_NAMESPACE_BEGIN
36
37 class OpenCLSplitKernel;
38
39 namespace {
40
41 /* Copy dummy KernelGlobals related to OpenCL from kernel_globals.h to
42  * fetch its size.
43  */
44 typedef struct KernelGlobalsDummy {
45         ccl_constant KernelData *data;
46         ccl_global char *buffers[8];
47
48 #define KERNEL_TEX(type, name) \
49         TextureInfo name;
50 #  include "kernel/kernel_textures.h"
51 #undef KERNEL_TEX
52         SplitData split_data;
53         SplitParams split_param_data;
54 } KernelGlobalsDummy;
55
56 }  // namespace
57
58 static string get_build_options(OpenCLDeviceBase *device, const DeviceRequestedFeatures& requested_features)
59 {
60         string build_options = "-D__SPLIT_KERNEL__ ";
61         build_options += requested_features.get_build_options();
62
63         /* Set compute device build option. */
64         cl_device_type device_type;
65         OpenCLInfo::get_device_type(device->cdDevice, &device_type, &device->ciErr);
66         assert(device->ciErr == CL_SUCCESS);
67         if(device_type == CL_DEVICE_TYPE_GPU) {
68                 build_options += " -D__COMPUTE_DEVICE_GPU__";
69         }
70
71         return build_options;
72 }
73
74 /* OpenCLDeviceSplitKernel's declaration/definition. */
75 class OpenCLDeviceSplitKernel : public OpenCLDeviceBase
76 {
77 public:
78         DeviceSplitKernel *split_kernel;
79         OpenCLProgram program_data_init;
80         OpenCLProgram program_state_buffer_size;
81
82         OpenCLDeviceSplitKernel(DeviceInfo& info, Stats &stats, bool background_);
83
84         ~OpenCLDeviceSplitKernel()
85         {
86                 task_pool.stop();
87
88                 /* Release kernels */
89                 program_data_init.release();
90
91                 delete split_kernel;
92         }
93
94         virtual bool show_samples() const {
95                 return true;
96         }
97
98         virtual bool load_kernels(const DeviceRequestedFeatures& requested_features,
99                                   vector<OpenCLDeviceBase::OpenCLProgram*> &programs)
100         {
101                 bool single_program = OpenCLInfo::use_single_program();
102                 program_data_init = OpenCLDeviceBase::OpenCLProgram(this,
103                                                   single_program ? "split" : "split_data_init",
104                                                   single_program ? "kernel_split.cl" : "kernel_data_init.cl",
105                                                   get_build_options(this, requested_features));
106
107                 program_data_init.add_kernel(ustring("path_trace_data_init"));
108                 programs.push_back(&program_data_init);
109
110                 program_state_buffer_size = OpenCLDeviceBase::OpenCLProgram(this,
111                                                   single_program ? "split" : "split_state_buffer_size",
112                                                   single_program ? "kernel_split.cl" : "kernel_state_buffer_size.cl",
113                                                   get_build_options(this, requested_features));
114                 program_state_buffer_size.add_kernel(ustring("path_trace_state_buffer_size"));
115                 programs.push_back(&program_state_buffer_size);
116
117                 return split_kernel->load_kernels(requested_features);
118         }
119
120         void thread_run(DeviceTask *task)
121         {
122                 flush_texture_buffers();
123
124                 if(task->type == DeviceTask::FILM_CONVERT) {
125                         film_convert(*task, task->buffer, task->rgba_byte, task->rgba_half);
126                 }
127                 else if(task->type == DeviceTask::SHADER) {
128                         shader(*task);
129                 }
130                 else if(task->type == DeviceTask::RENDER) {
131                         RenderTile tile;
132                         DenoisingTask denoising(this);
133
134                         /* Allocate buffer for kernel globals */
135                         device_only_memory<KernelGlobalsDummy> kgbuffer(this, "kernel_globals");
136                         kgbuffer.alloc_to_device(1);
137
138                         /* Keep rendering tiles until done. */
139                         while(task->acquire_tile(this, tile)) {
140                                 if(tile.task == RenderTile::PATH_TRACE) {
141                                         assert(tile.task == RenderTile::PATH_TRACE);
142                                         scoped_timer timer(&tile.buffers->render_time);
143
144                                         split_kernel->path_trace(task,
145                                                                  tile,
146                                                                  kgbuffer,
147                                                                  *const_mem_map["__data"]);
148
149                                         /* Complete kernel execution before release tile. */
150                                         /* This helps in multi-device render;
151                                          * The device that reaches the critical-section function
152                                          * release_tile waits (stalling other devices from entering
153                                          * release_tile) for all kernels to complete. If device1 (a
154                                          * slow-render device) reaches release_tile first then it would
155                                          * stall device2 (a fast-render device) from proceeding to render
156                                          * next tile.
157                                          */
158                                         clFinish(cqCommandQueue);
159                                 }
160                                 else if(tile.task == RenderTile::DENOISE) {
161                                         tile.sample = tile.start_sample + tile.num_samples;
162                                         denoise(tile, denoising, *task);
163                                         task->update_progress(&tile, tile.w*tile.h);
164                                 }
165
166                                 task->release_tile(tile);
167                         }
168
169                         kgbuffer.free();
170                 }
171         }
172
173         bool is_split_kernel()
174         {
175                 return true;
176         }
177
178 protected:
179         /* ** Those guys are for workign around some compiler-specific bugs ** */
180
181         string build_options_for_base_program(
182                 const DeviceRequestedFeatures& requested_features)
183         {
184                 return requested_features.get_build_options();
185         }
186
187         friend class OpenCLSplitKernel;
188         friend class OpenCLSplitKernelFunction;
189 };
190
191 struct CachedSplitMemory {
192         int id;
193         device_memory *split_data;
194         device_memory *ray_state;
195         device_memory *queue_index;
196         device_memory *use_queues_flag;
197         device_memory *work_pools;
198         device_ptr *buffer;
199 };
200
201 class OpenCLSplitKernelFunction : public SplitKernelFunction {
202 public:
203         OpenCLDeviceSplitKernel* device;
204         OpenCLDeviceBase::OpenCLProgram program;
205         CachedSplitMemory& cached_memory;
206         int cached_id;
207
208         OpenCLSplitKernelFunction(OpenCLDeviceSplitKernel* device, CachedSplitMemory& cached_memory) :
209                         device(device), cached_memory(cached_memory), cached_id(cached_memory.id-1)
210         {
211         }
212
213         ~OpenCLSplitKernelFunction()
214         {
215                 program.release();
216         }
217
218         virtual bool enqueue(const KernelDimensions& dim, device_memory& kg, device_memory& data)
219         {
220                 if(cached_id != cached_memory.id) {
221                         cl_uint start_arg_index =
222                                 device->kernel_set_args(program(),
223                                                     0,
224                                                     kg,
225                                                     data,
226                                                     *cached_memory.split_data,
227                                                     *cached_memory.ray_state);
228
229                                 device->set_kernel_arg_buffers(program(), &start_arg_index);
230
231                         start_arg_index +=
232                                 device->kernel_set_args(program(),
233                                                     start_arg_index,
234                                                     *cached_memory.queue_index,
235                                                     *cached_memory.use_queues_flag,
236                                                     *cached_memory.work_pools,
237                                                     *cached_memory.buffer);
238
239                         cached_id = cached_memory.id;
240                 }
241
242                 device->ciErr = clEnqueueNDRangeKernel(device->cqCommandQueue,
243                                                        program(),
244                                                        2,
245                                                        NULL,
246                                                        dim.global_size,
247                                                        dim.local_size,
248                                                        0,
249                                                        NULL,
250                                                        NULL);
251
252                 device->opencl_assert_err(device->ciErr, "clEnqueueNDRangeKernel");
253
254                 if(device->ciErr != CL_SUCCESS) {
255                         string message = string_printf("OpenCL error: %s in clEnqueueNDRangeKernel()",
256                                                        clewErrorString(device->ciErr));
257                         device->opencl_error(message);
258                         return false;
259                 }
260
261                 return true;
262         }
263 };
264
265 class OpenCLSplitKernel : public DeviceSplitKernel {
266         OpenCLDeviceSplitKernel *device;
267         CachedSplitMemory cached_memory;
268 public:
269         explicit OpenCLSplitKernel(OpenCLDeviceSplitKernel *device) : DeviceSplitKernel(device), device(device) {
270         }
271
272         virtual SplitKernelFunction* get_split_kernel_function(const string& kernel_name,
273                                                                const DeviceRequestedFeatures& requested_features)
274         {
275                 OpenCLSplitKernelFunction* kernel = new OpenCLSplitKernelFunction(device, cached_memory);
276
277                 bool single_program = OpenCLInfo::use_single_program();
278                 kernel->program =
279                         OpenCLDeviceBase::OpenCLProgram(device,
280                                                         single_program ? "split" : "split_" + kernel_name,
281                                                         single_program ? "kernel_split.cl" : "kernel_" + kernel_name + ".cl",
282                                                         get_build_options(device, requested_features));
283
284                 kernel->program.add_kernel(ustring("path_trace_" + kernel_name));
285                 kernel->program.load();
286
287                 if(!kernel->program.is_loaded()) {
288                         delete kernel;
289                         return NULL;
290                 }
291
292                 return kernel;
293         }
294
295         virtual uint64_t state_buffer_size(device_memory& kg, device_memory& data, size_t num_threads)
296         {
297                 device_vector<uint64_t> size_buffer(device, "size_buffer", MEM_READ_WRITE);
298                 size_buffer.alloc(1);
299                 size_buffer.zero_to_device();
300
301                 uint threads = num_threads;
302                 device->kernel_set_args(device->program_state_buffer_size(), 0, kg, data, threads, size_buffer);
303
304                 size_t global_size = 64;
305                 device->ciErr = clEnqueueNDRangeKernel(device->cqCommandQueue,
306                                                device->program_state_buffer_size(),
307                                                1,
308                                                NULL,
309                                                &global_size,
310                                                NULL,
311                                                0,
312                                                NULL,
313                                                NULL);
314
315                 device->opencl_assert_err(device->ciErr, "clEnqueueNDRangeKernel");
316
317                 size_buffer.copy_from_device(0, 1, 1);
318                 size_t size = size_buffer[0];
319                 size_buffer.free();
320
321                 if(device->ciErr != CL_SUCCESS) {
322                         string message = string_printf("OpenCL error: %s in clEnqueueNDRangeKernel()",
323                                                        clewErrorString(device->ciErr));
324                         device->opencl_error(message);
325                         return 0;
326                 }
327
328                 return size;
329         }
330
331         virtual bool enqueue_split_kernel_data_init(const KernelDimensions& dim,
332                                                     RenderTile& rtile,
333                                                     int num_global_elements,
334                                                     device_memory& kernel_globals,
335                                                     device_memory& kernel_data,
336                                                     device_memory& split_data,
337                                                     device_memory& ray_state,
338                                                     device_memory& queue_index,
339                                                     device_memory& use_queues_flag,
340                                                     device_memory& work_pool_wgs
341                                                     )
342         {
343                 cl_int dQueue_size = dim.global_size[0] * dim.global_size[1];
344
345                 /* Set the range of samples to be processed for every ray in
346                  * path-regeneration logic.
347                  */
348                 cl_int start_sample = rtile.start_sample;
349                 cl_int end_sample = rtile.start_sample + rtile.num_samples;
350
351                 cl_uint start_arg_index =
352                         device->kernel_set_args(device->program_data_init(),
353                                         0,
354                                         kernel_globals,
355                                         kernel_data,
356                                         split_data,
357                                         num_global_elements,
358                                         ray_state);
359
360                         device->set_kernel_arg_buffers(device->program_data_init(), &start_arg_index);
361
362                 start_arg_index +=
363                         device->kernel_set_args(device->program_data_init(),
364                                         start_arg_index,
365                                         start_sample,
366                                         end_sample,
367                                         rtile.x,
368                                         rtile.y,
369                                         rtile.w,
370                                         rtile.h,
371                                         rtile.offset,
372                                         rtile.stride,
373                                         queue_index,
374                                         dQueue_size,
375                                         use_queues_flag,
376                                         work_pool_wgs,
377                                         rtile.num_samples,
378                                         rtile.buffer);
379
380                 /* Enqueue ckPathTraceKernel_data_init kernel. */
381                 device->ciErr = clEnqueueNDRangeKernel(device->cqCommandQueue,
382                                                device->program_data_init(),
383                                                2,
384                                                NULL,
385                                                dim.global_size,
386                                                dim.local_size,
387                                                0,
388                                                NULL,
389                                                NULL);
390
391                 device->opencl_assert_err(device->ciErr, "clEnqueueNDRangeKernel");
392
393                 if(device->ciErr != CL_SUCCESS) {
394                         string message = string_printf("OpenCL error: %s in clEnqueueNDRangeKernel()",
395                                                        clewErrorString(device->ciErr));
396                         device->opencl_error(message);
397                         return false;
398                 }
399
400                 cached_memory.split_data = &split_data;
401                 cached_memory.ray_state = &ray_state;
402                 cached_memory.queue_index = &queue_index;
403                 cached_memory.use_queues_flag = &use_queues_flag;
404                 cached_memory.work_pools = &work_pool_wgs;
405                 cached_memory.buffer = &rtile.buffer;
406                 cached_memory.id++;
407
408                 return true;
409         }
410
411         virtual int2 split_kernel_local_size()
412         {
413                 return make_int2(64, 1);
414         }
415
416         virtual int2 split_kernel_global_size(device_memory& kg, device_memory& data, DeviceTask * /*task*/)
417         {
418                 cl_device_type type = OpenCLInfo::get_device_type(device->cdDevice);
419                 /* Use small global size on CPU devices as it seems to be much faster. */
420                 if(type == CL_DEVICE_TYPE_CPU) {
421                         VLOG(1) << "Global size: (64, 64).";
422                         return make_int2(64, 64);
423                 }
424
425                 cl_ulong max_buffer_size;
426                 clGetDeviceInfo(device->cdDevice, CL_DEVICE_MAX_MEM_ALLOC_SIZE, sizeof(cl_ulong), &max_buffer_size, NULL);
427
428                 if(DebugFlags().opencl.mem_limit) {
429                         max_buffer_size = min(max_buffer_size,
430                                               cl_ulong(DebugFlags().opencl.mem_limit - device->stats.mem_used));
431                 }
432
433                 VLOG(1) << "Maximum device allocation size: "
434                         << string_human_readable_number(max_buffer_size) << " bytes. ("
435                         << string_human_readable_size(max_buffer_size) << ").";
436
437                 /* Limit to 2gb, as we shouldn't need more than that and some devices may support much more. */
438                 max_buffer_size = min(max_buffer_size / 2, (cl_ulong)2l*1024*1024*1024);
439
440                 size_t num_elements = max_elements_for_max_buffer_size(kg, data, max_buffer_size);
441                 int2 global_size = make_int2(max(round_down((int)sqrt(num_elements), 64), 64), (int)sqrt(num_elements));
442                 VLOG(1) << "Global size: " << global_size << ".";
443                 return global_size;
444         }
445 };
446
447 OpenCLDeviceSplitKernel::OpenCLDeviceSplitKernel(DeviceInfo& info, Stats &stats, bool background_)
448 : OpenCLDeviceBase(info, stats, background_)
449 {
450         split_kernel = new OpenCLSplitKernel(this);
451
452         background = background_;
453 }
454
455 Device *opencl_create_split_device(DeviceInfo& info, Stats& stats, bool background)
456 {
457         return new OpenCLDeviceSplitKernel(info, stats, background);
458 }
459
460 CCL_NAMESPACE_END
461
462 #endif /* WITH_OPENCL */