memory_manager.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. * Copyright 2011-2017 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. #pragma once
  17. #include "device/device.h"
  18. #include "util/util_map.h"
  19. #include "util/util_vector.h"
  20. #include "util/util_string.h"
  21. #include "clew.h"
  22. CCL_NAMESPACE_BEGIN
  23. class OpenCLDevice;
  24. class MemoryManager {
  25. public:
  26. static const int NUM_DEVICE_BUFFERS = 8;
  27. struct BufferDescriptor {
  28. uint device_buffer;
  29. cl_ulong offset;
  30. };
  31. private:
  32. struct DeviceBuffer;
  33. struct Allocation {
  34. device_memory *mem;
  35. DeviceBuffer *device_buffer;
  36. size_t size; /* Size of actual allocation, may be larger than requested. */
  37. BufferDescriptor desc;
  38. bool needs_copy_to_device;
  39. Allocation() : mem(NULL), device_buffer(NULL), size(0), needs_copy_to_device(false)
  40. {
  41. }
  42. };
  43. struct DeviceBuffer {
  44. device_only_memory<uchar> *buffer;
  45. vector<Allocation *> allocations;
  46. size_t size; /* Size of all allocations. */
  47. DeviceBuffer() : buffer(NULL), size(0)
  48. {
  49. }
  50. ~DeviceBuffer()
  51. {
  52. delete buffer;
  53. buffer = NULL;
  54. }
  55. void add_allocation(Allocation &allocation);
  56. void update_device_memory(OpenCLDevice *device);
  57. void free(OpenCLDevice *device);
  58. };
  59. OpenCLDevice *device;
  60. DeviceBuffer device_buffers[NUM_DEVICE_BUFFERS];
  61. typedef unordered_map<string, Allocation> AllocationsMap;
  62. AllocationsMap allocations;
  63. bool need_update;
  64. DeviceBuffer *smallest_device_buffer();
  65. public:
  66. MemoryManager(OpenCLDevice *device);
  67. void free(); /* Free all memory. */
  68. void alloc(const char *name, device_memory &mem);
  69. bool free(device_memory &mem);
  70. BufferDescriptor get_descriptor(string name);
  71. void update_device_memory();
  72. void set_kernel_arg_buffers(cl_kernel kernel, cl_uint *narg);
  73. };
  74. CCL_NAMESPACE_END