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