HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
CE_Context.h
Go to the documentation of this file.
1 /*
2  * PROPRIETARY INFORMATION. This software is proprietary to
3  * Side Effects Software Inc., and is not to be reproduced,
4  * transmitted, or disclosed in any way without written permission.
5  *
6  * NAME: CE_Context.h ( CE Library, C++)
7  *
8  * COMMENTS: Compute Engine Contexts.
9  */
10 
11 #ifndef __CE_Context__
12 #define __CE_Context__
13 
14 #include "CE_API.h"
15 #include "CE_Tracing.h"
16 #include "CE_Error.h"
17 
18 #include <UT/UT_Array.h>
19 #include <UT/UT_Error.h>
20 #include <UT/UT_Lock.h>
21 #include <UT/UT_Map.h>
22 #include <UT/UT_NonCopyable.h>
23 #include <UT/UT_StringMap.h>
24 #include <UT/UT_UniquePtr.h>
25 #include <SYS/SYS_Types.h>
26 #include <SYS/SYS_Handle.h>
27 #include <iosfwd>
28 
29 class CE_MemoryPool;
30 class UT_MemoryResource;
31 
32 typedef void (*CE_ErrorCB)(const char *errmsg, UT_ErrorSeverity severity,
33  void *data);
34 
36 {
37 public:
40 
42 
43  virtual void rebindOGLBuffer( uint buf_obj ) = 0;
44  virtual void unbindOGLBuffer() = 0;
45  virtual bool isBinded() = 0;
46 };
47 
48 /// An OpenCL buffer that is backed by a external memory. External memory is accessed
49 /// through a platform specific memory handle.
50 /// Requires the OpenCL driver implements the following extensions:
51 /// cl_khr_external_memory
52 /// cl_khr_external_memory_opaque_fd (only on Linux and possibly Mac)
53 /// cl_khr_external_memory_win32 (only on Windows)
54 class CE_API CE_ExternalBuffer : public cl::Buffer
55 {
56 public:
58  const cl::Context &context,
60  ::size_t size,
61  SYS_Handle handle,
62  cl_int *err = nullptr);
63 
64  CE_ExternalBuffer() : cl::Buffer() {}
65 };
66 /// An OpenCL image that is backed by external memory, similar to
67 /// CE_ExternalBuffer.
69 {
70 public:
72  const cl::Context &context,
74  const cl_image_format *format,
75  const cl_image_desc *desc,
76  SYS_Handle handle,
77  cl_int *err = nullptr);
78 
79  CE_ExternalImage() : cl::Image() {}
80 };
81 
82 #ifndef CL_UUID_SIZE_KHR
83 #define CL_UUID_SIZE_KHR 16
84 #endif
85 
86 /// CE_Context encapsulates the OpenCL context and provides various convenience
87 /// functions for loading kernel programs and allocating GPU memory.
89 {
90 public:
91  CE_Context();
92  virtual ~CE_Context();
93 
95 
96  /// Returns a pointer to the singleton CE_Context object. This function
97  /// attempts to initialize OpenCL if it has not yet been.
98  /// gl_shared should be true if the context will be expected to interoperate
99  /// with the OpenGL context. If both gl_shared and shared_fallback are true,
100  /// then the function will try to make an unshared context in case the
101  /// shared context fails to create.
102  static CE_Context *getContext(bool gl_shared = true,
103  bool shared_fallback = true);
104  /// Returns true if interoperability between CL and GL is possible.
105  static bool isGLSharingPossible();
106 
107  /// Returns the underlying cl::Context object.
108  cl::Context getCLContext() const {return myContext;}
109 
110  /// Returns the cl::Queue object that is used to enqueue OpenCL kernels
111  /// and memory transfers.
112  cl::CommandQueue getQueue() const {return myQueue;}
113 
114  /// Returns the OpenCL Device object.
115  cl::Device getDevice() const {return myDevice;}
116 
117  ceTraceCtx getTraceContext() const {return myTraceCtx;}
118 
119  // Write OpenCL Device info to the supplied buffer.
120  static void getInfo(const cl::Device &device, UT_WorkBuffer &buffer );
121  static void getExtendedInfo(const cl::Device &device, UT_WorkBuffer &buffer );
122 
123  // Write info for all available OpenCL platforms to the supplied buffer.
124  static void getAllPlatformsInfo(UT_WorkBuffer &buffer);
125 
126  /// Get the suggested global and local ranges for the given 1-D kernel over
127  /// the specified number of items.
128  void get1DRanges(const cl::Kernel &k, size_t items,
129  cl::NDRange &g, cl::NDRange &l);
130 
131  /// Get the suggested global and local ranges for a reduction for the
132  /// given 1-D kernel over the specified number of items.
133  void getReductionRanges(const cl::Kernel &k, size_t items, size_t accumsize,
134  cl::NDRange &global_range, cl::NDRange &local_range,
135  uint &groupsize, uint &ngroups) const;
136 
137  /// Get the maximum workgroup size for the given kernel.
138  size_t getMaxWorkgroupSize(const cl::Kernel &k);
139  /// Get the array of maximum work items along each dimension supported by the
140  /// compute device.
141  std::vector<size_t> getMaxWorkItemSizes();
142 
143  /// Round up a provided group size to a larger clean one as some
144  /// driers die with prime-based groups sizes.
145  /// Less than 1024 is raised to next power of 2, greater is to a multiple
146  /// of 1024.
147  static size_t roundUpGroupSize(size_t gsize);
148 
149  /// Loads the OpenCL program specified by progname. This functions searches
150  /// for the file in the HOUDINI_OCL_PATH environment variable. Any compile-
151  /// time options can be passed in the options parameter. If the program
152  /// load succeeds, the progname will be cached, using the progrname and
153  /// options strings together as a hash value lookup. In this way the same
154  /// OpenCL program can be loaded several times with different compile-time
155  /// flags.
156  cl::Program loadProgram(const char *progname,
157  const char *options = nullptr,
158  bool recompile = false);
159 
160  /// Like loadProgram() except it creates a program from code directly.
161  /// `progname` should be provided where possible so that errors are easier
162  /// to find.
163  cl::Program compileProgram(const char *progtext,
164  const char *options = nullptr,
165  bool recompile = false,
166  const char *progname = nullptr);
167 
168  /// Create an OpenCL kernel named kernelname from the program specified by
169  /// progname. For some types of devices these kernels will be cached, as
170  /// kernels can be expensive to create. This is the recommended method
171  /// for creating kernels.
172  cl::Kernel loadKernel(const cl::Program &prog, const UT_StringRef &kernelname);
173  cl::Kernel loadKernel(const char *progname, const UT_StringRef &kernelname,
174  const char *options = nullptr)
175  { return loadKernel(loadProgram(progname, options), kernelname); }
176 
177  /// Returns whether the CE_Context has been successfully initialized.
178  bool isValid() const {return myIsValid;}
179 
180  /// Returns whether the singleton CE_Context has been initialized yet. This
181  /// can be used to test whether OpenCL has been initialized without calling
182  /// getContext and forcing an attempt at initialization.
183  static bool isInitialized(bool gl_shared=false);
184 
185  /// Returns true if the OpenCL device is running on the CPU.
186  bool isCPU() const;
187 
188  /// Returns true if the OpenCL device supports double precision.
189  bool hasDoubleSupport() const {return mySupportsDouble;}
190  /// Returns true if the OpenCL device supports writing to 3D image objects.
191  bool has3DImageWriteSupport() const {return mySupports3DImageWrites;}
192 
193  /// Block until any outstanding kernel or memory transfers on the main
194  /// CommandQueue have executed. If sweep_pool is true, the context's
195  /// CE_MemoryPool will sweep for any buffers that were in use when their
196  /// CE_Grid's went out of scope, but that were still active in kernels.
197  void finish(bool sweep_pool=true);
198 
199  /// Allocate a buffer of specified size on the CE_Device.
200  /// use_pool= true, attempts to use the underlying CE_MemoryPool to possibly return
201  /// an already allocated, unused buffer.
202  /// read=true, creates a buffer that is readable inside kernels.
203  /// write=true, creates a buffer that is writable inside kernels.
204  /// ogl_bind, specifies an OGL buffer to bind to.
205  cl::Buffer allocBuffer(int64 size, bool use_pool=true, bool read=true, bool write=true, uint32 ogl_bind=SYS_UINT32_MAX);
206 
207  /// Release the specified buffer, possibly to the CE_MemoryPool.
208  void releaseBuffer(cl::Buffer &&buf, bool use_pool=true);
209 
210  /// Read the specified number of bytes from the buffer.
211  void readBuffer(const cl::Buffer &buf, size_t size, void *p, bool blocking = true, size_t offset = 0);
212 
213  /// Write the specified number of bytes to the buffer.
214  void writeBuffer(const cl::Buffer &buf, size_t size, const void *p, bool blocking = true, size_t offset = 0);
215 
216  /// Copy the specified amount of data from source buffer to destination
217  /// buffer.
218  void copyBuffer(const cl::Buffer &src, const cl::Buffer &dst, size_t size,
219  size_t src_offset = 0, size_t dst_offset = 0);
220 
221  /// Copy data from the source buffer into the specified region of the
222  /// destination image.
223  void copyBufferToImage(const cl::Buffer &src, const cl::Image &dst,
224  const cl::size_t<3>& dst_origin,
225  const cl::size_t<3>& dst_region,
226  size_t src_offset = 0);
227 
228  /// Copy data from the specified region of the source image to the
229  /// destination buffer.
230  void copyImageToBuffer(const cl::Image &src, const cl::Buffer &dst,
231  const cl::size_t<3>& src_origin,
232  const cl::size_t<3>& src_region,
233  size_t dst_offset = 0);
234 
235  /// Enqueue the kernel over the provided ranges.
236  void enqueueKernel(const cl::Kernel &kernel, const cl::NDRange &global, const cl::NDRange &local);
237 
238  /// Keep a map buffer to bind at render time
239  /// The first time a CL::Buffer is created it can be registered to rebing to a OGL vertex buffer at drawing time.
240  /// The uint returned by the register call can be attached to a detail attribute and the drawing code can convert
241  /// the CL Buffer to a CL BufferGL.
242  uint32 registerDelayedOGLBindBuffer(CE_DelayedOGLBindBuffer* buffer);
243  void unregisterDelayedOGLBindBuffer(uint32 id);
244  CE_DelayedOGLBindBuffer* lookupDelayedOGLBindBuffer( uint id );
245 
246  /// Returns true if the context supports querying for device and driver
247  /// UUIDs that are unique across APIs (allowing for example, to match Vulkan
248  /// device selection). This requires the cl_khr_device_uuid extension.
249  bool supportsUUID();
250  /// Writes the OpenCL device UUID. Check that supportsUUID() returns true
251  /// before trying to query the UUID.
252  void getDeviceUUID(cl_uchar (&uuid)[CL_UUID_SIZE_KHR]);
253  /// Writes the OpenCL driver UUID. Check that supportsUUID() returns true
254  /// before trying to query the UUID.
255  void getDriverUUID(cl_uchar (&uuid)[CL_UUID_SIZE_KHR]);
256 
257  /// Returns true if the context supports the creation of buffers backed by
258  /// external memory. Mainly for use in sharing buffers with Vulkan.
259  bool supportsExternalMemory();
260 
261  /// Create a buffer backed by external memory. The handle will be the reference
262  /// to the actual memory object, and its lifetime is externally managed. The
263  /// memory might be owned by another GPU API, such as Vulkan. In those cases,
264  /// that handle can be obtained by a call to
265  /// vkGetMemoryFdKHR or vkGetMemoryWin32HandleKHR
266  /// This requires a few extensions to be available. Check that the context
267  /// supports these by calling CE_Context::supportsExternalMemory first.
268  CE_ExternalBuffer createExternalMemoryBuffer(SYS_Handle handle, int64_t size, bool read=true, bool write=true);
269 
270  CE_ExternalImage createExternalImage(SYS_Handle handle,
271  const cl_image_format& format,
272  const cl_image_desc& image_desc,
273  bool read = true, bool write = true);
274 
275  /// Clear the CE_MemoryPool object.
276  void clearMemoryPool();
277 
278  /// Sweep the memory pool for in use buffers. We call this on every finish
279  /// call as well, but if we have a large sequence of operations that use
280  /// temporary buffers without a finish, it's a good idea to call this directly
281  /// occasionally.
282  void sweepInUseMemory();
283 
284  /// Return a pointer to pinned (page-locked) host memory. On some devices
285  /// (Nvidia), using this type of memory for the PCI/E host/device transfers
286  /// can double the throughput. Will return NULL if the memory can't be
287  /// allocated, or if the device is not a GPU.
288  fpreal32 *getPinnedBuffer(int64 size);
289 
290  cl::Buffer getXNoiseData();
291 
292  /// Standard error reporting for OpenCL exceptions. They should generally
293  /// take the form:
294  /// @code
295  /// try
296  /// {
297  /// OpenCL calls...
298  /// }
299  /// catch(cl::Error &err)
300  /// {
301  /// CE_Context::reportError(err);
302  /// ///cleanup
303  /// }
304  /// @endcode
305  /// This will not capture delayed errors, however. Instead
306  /// you will need to add a callback to intercept them.
307  static void reportError(const cl::Error &err);
308  static void outputErrorMessage(const char *err_msg);
309  static void setErrorCB(CE_ErrorCB callback, void *data);
310  static void outputWarningMessage(const char *err_msg);
311 
312  static void initMainSharedGLContext( int devicetype, void* context, void* display, const cl_uchar (&uuid)[16]);
313  static bool useHalfNormalDelayedBindBuffer();
314 
315  /// Marks that an operation has run out of memory, allowing us
316  /// to report elsewhere.
317  void setOutOfMemoryFailure(bool hasfailed = true) { myOutOfMemoryFailure = true; }
318  bool hasOutOfMemoryFailureHappened() const { return myOutOfMemoryFailure; }
319 
320  /// Combination of environment variable, but overriden to be false by known buggy drivers
321  static bool shouldUseOCLOGLInterop();
322 
323  /// This structure holds a device name, vendor, device number, and drive version with respect to
324  /// its vendor platform.
326  {
330  int number;
332  };
333  /// Get the vector of available devices of the given type.
334  static void getDevices(UT_Array<DeviceDescriptor>&, cl_device_type t);
335 
336  /// Get an index to the preferred/default device for the specified device
337  /// type and the list of available devices.
338  static int getDefaultDevice(
340 
341  /// Returns true if environment variables are set that override preferences.
342  static bool isEnvironmentOverride();
343 
344  // Queries the device by calling clGetDeviceInfo, but returning false and setting
345  // result to zero for unknown flags or flags that are disabled with environment
346  // variables.
347  template <class T>
348  static bool getDeviceInfoRestricted(cl_device_id device, cl_uint flag, T &result);
349 
350  /// Queries the current device give the specified flag using clGetDeviceInfo,
351  /// used by ocldeviceinfo EXPR function. Returns false for unrecognized flag.
352  bool getDeviceInfo(const char *flag, fpreal &result);
353 
354  /// This function returns the total size of addressable compute memory for
355  /// the current device.
356  size_t getAddressableMemory() const;
357 
358  /// Report memory usage
359  void reportUsage(std::ostream &os) const;
360 
361  /// Requests the specified amount of memory to be freed from the OpenCL
362  /// device and returns the amount actually freed.
363  int64 requestMemoryFromResource(int64 amount);
364  /// Returns the memory resource object for the OpenCL device. All objects
365  /// that use OpenCL memory should ideally be registered as clients for this
366  /// resource. NOTE: this only exists if the context is valid!
368  {
369  return myMemResource;
370  }
371 
372 private:
373  UT_UniquePtr<cl::Program> doCompileProgram(
374  const char *progname,
375  const char *progtext,
376  const char *options,
377  bool recompile);
378 
379  /// Initialize the context for the given device.
380  void init(cl::Context &context, cl::Device &device, bool gl_shared);
381 
382  /// Releases the pinned, page-locked memory buffer.
383  void releasePinnedBuffer();
384 
385 
386  cl::Context myContext;
387  cl::CommandQueue myQueue;
388  cl::CommandQueue myDeviceQueue;
389  ceTraceCtx myTraceCtx;
390  cl::Device myDevice;
391  bool myIsValid;
392  bool mySupportsDouble;
393  bool mySupports3DImageWrites;
394  cl::Buffer myXNoiseData;
395  UT_Lock myXNoiseLock;
396 
397  // Indirection to avoid changing reference counts when caches resize/rehash.
398  using ProgramUPtr = UT_UniquePtr<cl::Program>;
399  using KernelUPtr = UT_UniquePtr<cl::Kernel>;
400 
401  struct KernelInfo
402  {
404  UT_Array<KernelUPtr> kernels;
405  };
406 
407  UT_StringMap<ProgramUPtr> myProgramTable;
409  UT_Lock myKernelCacheLock;
410 
411  UT_UniquePtr<CE_MemoryPool> myMemPool;
412  UT_MemoryResource *myMemResource;
413 
414  // The pinned buffer is unique to the main thread.
415  cl::Buffer myPinnedBuffer;
416  fpreal32 *myPinnedData;
417 
418  bool myOutOfMemoryFailure;
419 
420  UT_Map<uint32,CE_DelayedOGLBindBuffer*> myDelayedOGLBindBuffers;
421 
422  static void* theGLContext;
423  static void* theGLDisplay;
424  static int theGLDeviceType;
425  static char theGLDeviceUUID[16];
426 };
427 
428 /// NOTE: this function will retry if it fails on allocation failure, after
429 /// freeing some memory.
431 ce_enqueueKernel(const cl::CommandQueue& queue, const cl::Kernel &kernel,
432  const cl::NDRange &offset, const cl::NDRange &global, const cl::NDRange &local,
433  const std::vector<cl::Event>* events,
434  cl::Event* event);
435 
436 #endif
#define CE_API
Definition: CE_API.h:13
struct _cl_device_id * cl_device_id
Definition: cl.h:30
uint32_t cl_uint
Definition: cl_platform.h:261
bool has3DImageWriteSupport() const
Returns true if the OpenCL device supports writing to 3D image objects.
Definition: CE_Context.h:191
GLenum GLuint GLenum GLsizei const GLchar * buf
Definition: glcorearb.h:2540
GLbitfield flags
Definition: glcorearb.h:1596
cl::Device getDevice() const
Returns the OpenCL Device object.
Definition: CE_Context.h:115
Unsorted map container.
Definition: UT_Map.h:114
*get result *(waiting if necessary)*A common idiom is to fire a bunch of sub tasks at the and then *wait for them to all complete We provide a helper class
Definition: thread.h:632
void
Definition: png.h:1083
GLboolean * data
Definition: glcorearb.h:131
GLboolean GLboolean g
Definition: glcorearb.h:1222
UT_StringHolder platformVendor
Definition: CE_Context.h:329
UT_ErrorSeverity
Definition: UT_Error.h:25
int32_t cl_int
Definition: cl_platform.h:260
uint8_t cl_uchar
Definition: cl_platform.h:257
ceTraceCtx getTraceContext() const
Definition: CE_Context.h:117
CE_API cl_int ce_enqueueKernel(const cl::CommandQueue &queue, const cl::Kernel &kernel, const cl::NDRange &offset, const cl::NDRange &global, const cl::NDRange &local, const std::vector< cl::Event > *events, cl::Event *event)
**But if you need a result
Definition: thread.h:622
virtual ~CE_DelayedOGLBindBuffer()
Definition: CE_Context.h:39
Definition: Image.h:45
float fpreal32
Definition: SYS_Types.h:200
void * ceTraceCtx
Definition: CE_Tracing.h:58
GLuint buffer
Definition: glcorearb.h:660
cl::CommandQueue getQueue() const
Definition: CE_Context.h:112
#define CL_UUID_SIZE_KHR
Definition: CE_Context.h:83
std::unique_ptr< T, Deleter > UT_UniquePtr
A smart pointer for unique ownership of dynamically allocated objects.
Definition: UT_UniquePtr.h:39
struct _cl_event * event
Definition: glcorearb.h:2961
Event interface for cl_event.
Definition: cl.hpp:1647
bool isValid() const
Returns whether the CE_Context has been successfully initialized.
Definition: CE_Context.h:178
UT_StringHolder driverVersion
Definition: CE_Context.h:331
GLintptr offset
Definition: glcorearb.h:665
cl_bitfield cl_device_type
Definition: cl.h:42
GLuint writeBuffer
Definition: glcorearb.h:2674
GLint GLint GLsizei GLint GLenum format
Definition: glcorearb.h:108
#define UT_NON_COPYABLE(CLASS)
Define deleted copy constructor and assignment operator inside a class.
*get result *(waiting if necessary)*A common idiom is to fire a bunch of sub tasks at the queue
Definition: thread.h:632
long long int64
Definition: SYS_Types.h:116
void setOutOfMemoryFailure(bool hasfailed=true)
Definition: CE_Context.h:317
GLenum GLenum severity
Definition: glcorearb.h:2539
GLuint const GLchar * name
Definition: glcorearb.h:786
#define SYS_UINT32_MAX
Definition: SYS_Types.h:172
GLdouble t
Definition: glad.h:2397
GLsizeiptr size
Definition: glcorearb.h:664
GLenum GLenum dst
Definition: glcorearb.h:1793
CommandQueue interface for cl_command_queue.
Definition: cl.hpp:2852
cl_int getInfo(Func f, cl_uint name, T *param)
Definition: cl.hpp:1030
cl::Kernel loadKernel(const char *progname, const UT_StringRef &kernelname, const char *options=nullptr)
Definition: CE_Context.h:173
fpreal64 fpreal
Definition: SYS_Types.h:283
UT_MemoryResource * getMemoryResource() const
Definition: CE_Context.h:367
Base class interface for all images.
Definition: cl.hpp:2098
unsigned int uint32
Definition: SYS_Types.h:40
Memory buffer interface.
Definition: cl.hpp:1867
NDRange interface.
Definition: cl.hpp:2466
void(* CE_ErrorCB)(const char *errmsg, UT_ErrorSeverity severity, void *data)
Definition: CE_Context.h:32
Kernel interface that implements cl_kernel.
Definition: cl.hpp:2544
cl::Context getCLContext() const
Returns the underlying cl::Context object.
Definition: CE_Context.h:108
Device interface for cl_device_id.
Definition: cl.hpp:1265
bool hasDoubleSupport() const
Returns true if the OpenCL device supports double precision.
Definition: CE_Context.h:189
Program interface that implements cl_program.
Definition: cl.hpp:2649
bool hasOutOfMemoryFailureHappened() const
Definition: CE_Context.h:318
unsigned int uint
Definition: SYS_Types.h:45
cl_bitfield cl_mem_flags
Definition: cl.h:66
Definition: format.h:1821
GLenum src
Definition: glcorearb.h:1793