okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0221-sycl: a Linux SYCL (Intel Arc) engine package recipe and feed entry, --version without GPU access, RUNPATH $ORIGIN; Arc PCs get an engine from the feed23b3dfc2c

main
37.0 KiB986 linesraw
1//==---- memory_internal.hpp ---------------------*- C++ -*----------------==//
2//
3// Copyright (C) Intel Corporation
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5// See https://llvm.org/LICENSE.txt for license information.
6//
7//===---------------------------------------------------------------------===//
8
9#ifndef __DPCT_DETAIL_MEMORY_DETAIL_HPP__
10#define __DPCT_DETAIL_MEMORY_DETAIL_HPP__
11
12namespace dpct {
13
14#ifdef SYCL_EXT_ONEAPI_BINDLESS_IMAGES
15namespace experimental {
16namespace detail {
17static sycl::event dpct_memcpy(const image_mem_wrapper *src,
18                               const sycl::id<3> &src_id,
19                               const size_t src_x_offest_byte,
20                               pitched_data &dest, const sycl::id<3> &dest_id,
21                               const size_t dest_x_offest_byte,
22                               const sycl::range<3> &size,
23                               const size_t copy_x_size_byte, sycl::queue q);
24static sycl::event
25dpct_memcpy(const pitched_data src, const sycl::id<3> &src_id,
26            const size_t src_x_offest_byte, image_mem_wrapper *dest,
27            const sycl::id<3> &dest_id, const size_t dest_x_offest_byte,
28            const sycl::range<3> &size, const size_t copy_x_size_byte,
29            sycl::queue q);
30static sycl::event
31dpct_memcpy(const image_mem_wrapper *src, const sycl::id<3> &src_id,
32            const size_t src_x_offest_byte, image_mem_wrapper *dest,
33            const sycl::id<3> &dest_id, const size_t dest_x_offest_byte,
34            const sycl::range<3> &size, const size_t copy_x_size_byte,
35            sycl::queue q);
36} // namespace detail
37} // namespace experimental
38
39#endif // !SYCL_EXT_ONEAPI_BINDLESS_IMAGES
40
41class image_matrix;
42
43namespace detail {
44static pitched_data to_pitched_data(image_matrix *image);
45
46class mem_mgr {
47  mem_mgr() {
48    // Reserved address space, no real memory allocation happens here.
49#if defined(__linux__)
50    mapped_address_space =
51        (byte_t *)mmap(nullptr, mapped_region_size, PROT_NONE,
52                       MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
53#elif defined(_WIN64)
54    mapped_address_space = (byte_t *)VirtualAlloc(
55        NULL,               // NULL specified as the base address parameter
56        mapped_region_size, // Size of allocation
57        MEM_RESERVE,        // Allocate reserved pages
58        PAGE_NOACCESS);     // Protection = no access
59#else
60#error "Only support Windows and Linux."
61#endif
62    next_free = mapped_address_space;
63  };
64
65public:
66  using buffer_id_t = int;
67
68  struct allocation {
69    buffer_t buffer;
70    byte_t *alloc_ptr;
71    size_t size;
72  };
73
74  ~mem_mgr() {
75#if defined(__linux__)
76    munmap(mapped_address_space, mapped_region_size);
77#elif defined(_WIN64)
78    VirtualFree(mapped_address_space, 0, MEM_RELEASE);
79#else
80#error "Only support Windows and Linux."
81#endif
82  };
83
84  mem_mgr(const mem_mgr &) = delete;
85  mem_mgr &operator=(const mem_mgr &) = delete;
86  mem_mgr(mem_mgr &&) = delete;
87  mem_mgr &operator=(mem_mgr &&) = delete;
88
89  /// Allocate
90  void *mem_alloc(size_t size) {
91    if (!size)
92      return nullptr;
93    std::lock_guard<std::mutex> lock(m_mutex);
94    if (next_free + size > mapped_address_space + mapped_region_size) {
95      throw std::runtime_error(
96          "dpct_malloc: out of memory for virtual memory pool");
97    }
98    // Allocation
99    sycl::range<1> r(size);
100    buffer_t buf(r);
101    allocation A{buf, next_free, size};
102    // Map allocation to device pointer
103    void *result = next_free;
104    m_map.emplace(next_free + size, A);
105    // Update pointer to the next free space.
106    next_free += (size + extra_padding + alignment - 1) & ~(alignment - 1);
107
108    return result;
109  }
110
111  /// Deallocate
112  void mem_free(const void *ptr) {
113    if (!ptr)
114      return;
115    std::lock_guard<std::mutex> lock(m_mutex);
116    auto it = get_map_iterator(ptr);
117    m_map.erase(it);
118  }
119
120  /// map: device pointer -> allocation(buffer, alloc_ptr, size)
121  allocation translate_ptr(const void *ptr) {
122    std::lock_guard<std::mutex> lock(m_mutex);
123    auto it = get_map_iterator(ptr);
124    return it->second;
125  }
126
127  void *get_base_addr(const void *ptr) {
128    allocation alloc = translate_ptr(ptr);
129    return alloc.alloc_ptr;
130  }
131
132  /// Check if the pointer represents device pointer or not.
133  bool is_device_ptr(const void *ptr) const {
134    std::lock_guard<std::mutex> lock(m_mutex);
135    return (mapped_address_space <= ptr) &&
136           (ptr < mapped_address_space + mapped_region_size);
137  }
138
139  /// Returns the instance of memory manager singleton.
140  static mem_mgr &instance() {
141    static mem_mgr m;
142    return m;
143  }
144
145private:
146  std::map<byte_t *, allocation> m_map;
147  mutable std::mutex m_mutex;
148  byte_t *mapped_address_space;
149  byte_t *next_free;
150  const size_t mapped_region_size = 128ull * 1024 * 1024 * 1024;
151  const size_t alignment = 256;
152  /// This padding may be defined to some positive value to debug
153  /// out of bound accesses.
154  const size_t extra_padding = 0;
155
156  std::map<byte_t *, allocation>::iterator get_map_iterator(const void *ptr) {
157    auto it = m_map.upper_bound((byte_t *)ptr);
158    if (it == m_map.end()) {
159      // Not a virtual pointer.
160      throw std::runtime_error("can not get buffer from non-virtual pointer");
161    }
162    const allocation &alloc = it->second;
163    if (ptr < alloc.alloc_ptr) {
164      // Out of bound.
165      // This may happen if there's a gap between allocations due to alignment
166      // or extra padding and pointer points to this gap.
167      throw std::runtime_error("invalid virtual pointer");
168    }
169    return it;
170  }
171};
172
173template <class T, memory_region Memory, size_t Dimension> class accessor;
174template <memory_region Memory, class T = byte_t> class memory_traits {
175public:
176  static constexpr sycl::access::target target = sycl::access::target::device;
177  static constexpr sycl::access_mode mode = (Memory == constant)
178                                                ? sycl::access_mode::read
179                                                : sycl::access_mode::read_write;
180  static constexpr size_t type_size = sizeof(T);
181  using value_t = typename std::remove_cv<T>::type;
182  template <size_t Dimension = 1>
183  using accessor_t = typename std::conditional<
184      Memory == local, sycl::local_accessor<value_t, Dimension>,
185      sycl::accessor<T, Dimension, mode, target>>::type;
186  using pointer_t = T *;
187};
188
189static inline void *dpct_malloc(size_t size, sycl::queue &q) {
190#ifdef DPCT_USM_LEVEL_NONE
191  return mem_mgr::instance().mem_alloc(size * sizeof(byte_t));
192#else
193  return sycl::malloc_device(size, q.get_device(), q.get_context());
194#endif // DPCT_USM_LEVEL_NONE
195}
196
197#define PITCH_DEFAULT_ALIGN(x) (((x) + 31) & ~(0x1F))
198static inline void *dpct_malloc(size_t &pitch, size_t x, size_t y, size_t z,
199                                sycl::queue &q) {
200  pitch = PITCH_DEFAULT_ALIGN(x);
201  return dpct_malloc(pitch * y * z, q);
202}
203
204/**
205 * @brief Sets \p value to the first \p size elements starting from \p dev_ptr
206 * in \p q.
207 * @tparam valueT The type of the element to be set.
208 * @param [in] q The queue in which the operation is done.
209 * @param [in] dev_ptr Pointer to the virtual device memory address.
210 * @param [in] value The value to be set.
211 * @param [in] size Number of elements to be set to the value.
212 * @return An event representing the memset operation.
213 */
214template <typename valueT>
215static inline sycl::event dpct_memset(sycl::queue &q, void *dev_ptr,
216                                      valueT value, size_t size) {
217#ifdef DPCT_USM_LEVEL_NONE
218  auto &mm = mem_mgr::instance();
219  assert(mm.is_device_ptr(dev_ptr));
220  auto alloc = mm.translate_ptr(dev_ptr);
221  size_t offset = (valueT *)dev_ptr - (valueT *)alloc.alloc_ptr;
222
223  return q.submit([&](sycl::handler &cgh) {
224    auto r = sycl::range<1>(size);
225    auto o = sycl::id<1>(offset);
226    auto new_buffer = alloc.buffer.reinterpret<valueT>(
227        sycl::range<1>(alloc.size / sizeof(valueT)));
228    sycl::accessor<valueT, 1, sycl::access_mode::write,
229                   sycl::access::target::device>
230        acc(new_buffer, cgh, r, o);
231    cgh.fill(acc, value);
232  });
233#else
234  return q.fill(dev_ptr, value, size);
235#endif // DPCT_USM_LEVEL_NONE
236}
237
238/**
239 * @brief Sets \p value to the 3D memory region pointed by \p data in \p q.
240 * @tparam valueT The type of the element to be set.
241 * @param [in] q The queue in which the operation is done.
242 * @param [in] data Pointer to the pitched device memory region.
243 * @param [in] value The value to be set.
244 * @param [in] size 3D memory region by number of elements.
245 * @return An event list representing the memset operations.
246 */
247template <typename valueT>
248static inline std::vector<sycl::event>
249dpct_memset(sycl::queue &q, dpct::pitched_data data, valueT value,
250            sycl::range<3> size) {
251  std::vector<sycl::event> event_list;
252  size_t slice = data.get_pitch() * data.get_y();
253  unsigned char *data_surface = (unsigned char *)data.get_data_ptr();
254  for (size_t z = 0; z < size.get(2); ++z) {
255    unsigned char *data_ptr = data_surface;
256    for (size_t y = 0; y < size.get(1); ++y) {
257      event_list.push_back(dpct_memset(q, data_ptr, value, size.get(0)));
258      data_ptr += data.get_pitch();
259    }
260    data_surface += slice;
261  }
262  return event_list;
263}
264
265/**
266 * @brief Sets \p val to the pitched 2D memory region pointed by \p ptr in \p q.
267 * @tparam valueT The type of the element to be set.
268 * @param [in] q The queue in which the operation is done.
269 * @param [in] ptr Pointer to the virtual device memory.
270 * @param [in] pitch The pitch size by number of elements, including padding.
271 * @param [in] val The value to be set.
272 * @param [in] x The width of memory region by number of elements.
273 * @param [in] y The height of memory region by number of elements.
274 * @return An event list representing the memset operations.
275 */
276template <typename valueT>
277static inline std::vector<sycl::event> dpct_memset(sycl::queue &q, void *ptr,
278                                                   size_t pitch, valueT val,
279                                                   size_t x, size_t y) {
280  return dpct_memset(q, pitched_data(ptr, pitch, x, 1), val,
281                     sycl::range<3>(x, y, 1));
282}
283
284enum class pointer_access_attribute {
285  host_only = 0,
286  device_only,
287  host_device,
288  end
289};
290
291static pointer_access_attribute get_pointer_attribute(sycl::queue &q,
292                                                      const void *ptr) {
293#ifdef DPCT_USM_LEVEL_NONE
294  return mem_mgr::instance().is_device_ptr(ptr)
295             ? pointer_access_attribute::device_only
296             : pointer_access_attribute::host_only;
297#else
298  switch (sycl::get_pointer_type(ptr, q.get_context())) {
299  case sycl::usm::alloc::unknown:
300    return pointer_access_attribute::host_only;
301  case sycl::usm::alloc::device:
302    return pointer_access_attribute::device_only;
303  case sycl::usm::alloc::shared:
304  case sycl::usm::alloc::host:
305    return pointer_access_attribute::host_device;
306  }
307#endif
308}
309
310static memcpy_direction deduce_memcpy_direction(sycl::queue &q, void *to_ptr,
311                                                const void *from_ptr,
312                                                memcpy_direction dir) {
313  switch (dir) {
314  case memcpy_direction::host_to_host:
315  case memcpy_direction::host_to_device:
316  case memcpy_direction::device_to_host:
317  case memcpy_direction::device_to_device:
318    return dir;
319  case memcpy_direction::automatic: {
320    // table[to_attribute][from_attribute]
321    static const memcpy_direction
322        direction_table[static_cast<unsigned>(pointer_access_attribute::end)]
323                       [static_cast<unsigned>(pointer_access_attribute::end)] =
324                           {{memcpy_direction::host_to_host,
325                             memcpy_direction::device_to_host,
326                             memcpy_direction::host_to_host},
327                            {memcpy_direction::host_to_device,
328                             memcpy_direction::device_to_device,
329                             memcpy_direction::device_to_device},
330                            {memcpy_direction::host_to_host,
331                             memcpy_direction::device_to_device,
332                             memcpy_direction::device_to_device}};
333    return direction_table[static_cast<unsigned>(get_pointer_attribute(
334        q, to_ptr))][static_cast<unsigned>(get_pointer_attribute(q, from_ptr))];
335  }
336  default:
337    throw std::runtime_error("dpct_memcpy: invalid direction value");
338  }
339}
340
341static sycl::event
342dpct_memcpy(sycl::queue &q, void *to_ptr, const void *from_ptr, size_t size,
343            memcpy_direction direction,
344            const std::vector<sycl::event> &dep_events = {}) {
345  if (!size)
346    return sycl::event{};
347#ifdef DPCT_USM_LEVEL_NONE
348  auto &mm = mem_mgr::instance();
349  auto real_direction = deduce_memcpy_direction(q, to_ptr, from_ptr, direction);
350
351  switch (real_direction) {
352  case host_to_host:
353    return q.submit([&](sycl::handler &cgh) {
354      cgh.depends_on(dep_events);
355      cgh.host_task([=] { std::memcpy(to_ptr, from_ptr, size); });
356    });
357  case host_to_device: {
358    auto alloc = mm.translate_ptr(to_ptr);
359    size_t offset = (byte_t *)to_ptr - alloc.alloc_ptr;
360    return q.submit([&](sycl::handler &cgh) {
361      cgh.depends_on(dep_events);
362      auto r = sycl::range<1>(size);
363      auto o = sycl::id<1>(offset);
364      sycl::accessor<byte_t, 1, sycl::access_mode::write,
365                     sycl::access::target::device>
366          acc(alloc.buffer, cgh, r, o);
367      cgh.copy(from_ptr, acc);
368    });
369  }
370  case device_to_host: {
371    auto alloc = mm.translate_ptr(from_ptr);
372    size_t offset = (byte_t *)from_ptr - alloc.alloc_ptr;
373    return q.submit([&](sycl::handler &cgh) {
374      cgh.depends_on(dep_events);
375      auto r = sycl::range<1>(size);
376      auto o = sycl::id<1>(offset);
377      sycl::accessor<byte_t, 1, sycl::access_mode::read,
378                     sycl::access::target::device>
379          acc(alloc.buffer, cgh, r, o);
380      cgh.copy(acc, to_ptr);
381    });
382  }
383  case device_to_device: {
384    auto to_alloc = mm.translate_ptr(to_ptr);
385    auto from_alloc = mm.translate_ptr(from_ptr);
386    size_t to_offset = (byte_t *)to_ptr - to_alloc.alloc_ptr;
387    size_t from_offset = (byte_t *)from_ptr - from_alloc.alloc_ptr;
388    return q.submit([&](sycl::handler &cgh) {
389      cgh.depends_on(dep_events);
390      auto r = sycl::range<1>(size);
391      auto to_o = sycl::id<1>(to_offset);
392      auto from_o = sycl::id<1>(from_offset);
393      sycl::accessor<byte_t, 1, sycl::access_mode::write,
394                     sycl::access::target::device>
395          to_acc(to_alloc.buffer, cgh, r, to_o);
396      sycl::accessor<byte_t, 1, sycl::access_mode::read,
397                     sycl::access::target::device>
398          from_acc(from_alloc.buffer, cgh, r, from_o);
399      cgh.copy(from_acc, to_acc);
400    });
401  }
402  default:
403    throw std::runtime_error("dpct_memcpy: invalid direction value");
404  }
405#else
406  return q.memcpy(to_ptr, from_ptr, size, dep_events);
407#endif // DPCT_USM_LEVEL_NONE
408}
409
410// Get actual copy range and make sure it will not exceed range.
411static inline size_t get_copy_range(sycl::range<3> size, size_t slice,
412                                    size_t pitch) {
413  return slice * (size.get(2) - 1) + pitch * (size.get(1) - 1) + size.get(0);
414}
415
416static inline size_t get_offset(sycl::id<3> id, size_t slice, size_t pitch) {
417  return slice * id.get(2) + pitch * id.get(1) + id.get(0);
418}
419
420// RAII for host pointer
421class host_buffer {
422  void *_buf;
423  size_t _size;
424  sycl::queue &_q;
425  const std::vector<sycl::event> &_deps; // free operation depends
426
427public:
428  host_buffer(size_t size, sycl::queue &q, const std::vector<sycl::event> &deps)
429      : _buf(std::malloc(size)), _size(size), _q(q), _deps(deps) {}
430  void *get_ptr() const { return _buf; }
431  size_t get_size() const { return _size; }
432  ~host_buffer() {
433    if (_buf) {
434      _q.submit([&](sycl::handler &cgh) {
435        cgh.depends_on(_deps);
436        cgh.host_task([buf = _buf] { std::free(buf); });
437      });
438    }
439  }
440};
441
442static sycl::event dpct_memcpy(sycl::queue &q, void *to_ptr, int to_dev_id,
443                               const void *from_ptr, int from_dev_id,
444                               size_t size) {
445  if (to_dev_id == from_dev_id)
446    return dpct_memcpy(q, to_ptr, from_ptr, size,
447                       memcpy_direction::device_to_device);
448  // Now, different device have different context, and memcpy API cannot copy
449  // data between different context. So we need use host buffer to copy the data
450  // between devices.
451  std::vector<sycl::event> event_list;
452  host_buffer buf(size, q, event_list);
453  auto copy_events = dpct_memcpy(q, buf.get_ptr(), from_ptr, size,
454                                 memcpy_direction::device_to_host);
455  event_list.push_back(dpct::detail::dpct_memcpy(
456      q, to_ptr, buf.get_ptr(), size, memcpy_direction::host_to_device,
457      {copy_events}));
458  return event_list[0];
459}
460
461static inline std::vector<sycl::event>
462dpct_memcpy(sycl::queue &q, void *to_ptr, const void *from_ptr,
463            sycl::range<3> to_range, sycl::range<3> from_range,
464            sycl::id<3> to_id, sycl::id<3> from_id, sycl::range<3> size,
465            memcpy_direction direction,
466            const std::vector<sycl::event> &dep_events);
467
468static inline void copy_to_device_via_host_buffer(
469    sycl::queue &q, const sycl::range<3> &size, unsigned char *to_surface,
470    const sycl::range<3> &to_range, const unsigned char *from_surface,
471    const sycl::range<3> &from_range, std::vector<sycl::event> &event_list,
472    memcpy_direction direction,
473    const std::vector<sycl::event> &dep_events = {}) {
474  assert(direction == device_to_host || direction == host_to_host);
475  size_t to_slice = to_range.get(1) * to_range.get(0);
476  host_buffer buf(get_copy_range(size, to_slice, to_range.get(0)), q,
477                  event_list);
478  std::vector<sycl::event> host_events;
479  size_t size_slice = size.get(1) * size.get(0);
480  if (to_slice == size_slice) {
481    // Copy host data to a temp host buffer with the shape of target.
482    host_events =
483        dpct_memcpy(q, buf.get_ptr(), from_surface, to_range, from_range,
484                    sycl::id<3>(0, 0, 0), sycl::id<3>(0, 0, 0), size, direction,
485                    dep_events);
486  } else {
487    // Copy host data to a temp host buffer with the shape of target.
488    host_events =
489        dpct_memcpy(q, buf.get_ptr(), from_surface, to_range, from_range,
490                    sycl::id<3>(0, 0, 0), sycl::id<3>(0, 0, 0), size, direction,
491                    // If has padding data, not sure whether it is useless. So
492                    // fill temp buffer with it.
493                    std::vector<sycl::event>{dpct_memcpy(
494                        q, buf.get_ptr(), to_surface, buf.get_size(),
495                        device_to_host, dep_events)});
496  }
497  // Copy from temp host buffer to device with only one submit.
498  event_list.push_back(dpct_memcpy(q, to_surface, buf.get_ptr(), buf.get_size(),
499                                   host_to_device, host_events));
500}
501
502/// copy 3D matrix specified by \p size from 3D matrix specified by \p from_ptr
503/// and \p from_range to another specified by \p to_ptr and \p to_range.
504static inline std::vector<sycl::event>
505dpct_memcpy(sycl::queue &q, void *to_ptr, const void *from_ptr,
506            sycl::range<3> to_range, sycl::range<3> from_range,
507            sycl::id<3> to_id, sycl::id<3> from_id, sycl::range<3> size,
508            memcpy_direction direction,
509            const std::vector<sycl::event> &dep_events = {}) {
510  std::vector<sycl::event> event_list;
511
512  size_t to_slice = to_range.get(1) * to_range.get(0),
513         from_slice = from_range.get(1) * from_range.get(0);
514  unsigned char *to_surface =
515      (unsigned char *)to_ptr + get_offset(to_id, to_slice, to_range.get(0));
516  const unsigned char *from_surface =
517      (const unsigned char *)from_ptr +
518      get_offset(from_id, from_slice, from_range.get(0));
519
520  if (to_slice == from_slice && to_slice == size.get(1) * size.get(0)) {
521    return {dpct_memcpy(q, to_surface, from_surface, to_slice * size.get(2),
522                        direction, dep_events)};
523  }
524  direction = deduce_memcpy_direction(q, to_ptr, from_ptr, direction);
525  size_t size_slice = size.get(1) * size.get(0);
526  switch (direction) {
527  case host_to_host:
528    for (size_t z = 0; z < size.get(2); ++z) {
529      unsigned char *to_ptr = to_surface;
530      const unsigned char *from_ptr = from_surface;
531      if (to_range.get(0) == from_range.get(0) &&
532          to_range.get(0) == size.get(0)) {
533        event_list.push_back(dpct_memcpy(q, to_ptr, from_ptr, size_slice,
534                                         direction, dep_events));
535      } else {
536        for (size_t y = 0; y < size.get(1); ++y) {
537          event_list.push_back(dpct_memcpy(q, to_ptr, from_ptr, size.get(0),
538                                           direction, dep_events));
539          to_ptr += to_range.get(0);
540          from_ptr += from_range.get(0);
541        }
542      }
543      to_surface += to_slice;
544      from_surface += from_slice;
545    }
546    break;
547  case host_to_device: {
548    copy_to_device_via_host_buffer(q, size, to_surface, to_range, from_surface,
549                                   from_range, event_list, host_to_host,
550                                   dep_events);
551    break;
552  }
553  case device_to_host: {
554    host_buffer buf(get_copy_range(size, from_slice, from_range.get(0)), q,
555                    event_list);
556    // Copy from host temp buffer to host target with reshaping.
557    event_list = dpct_memcpy(
558        q, to_surface, buf.get_ptr(), to_range, from_range,
559        sycl::id<3>(0, 0, 0), sycl::id<3>(0, 0, 0), size, host_to_host,
560        // Copy from device to temp host buffer with only one submit.
561        std::vector<sycl::event>{dpct_memcpy(q, buf.get_ptr(), from_surface,
562                                             buf.get_size(), device_to_host,
563                                             dep_events)});
564    break;
565  }
566  case device_to_device:
567#ifdef DPCT_USM_LEVEL_NONE
568  {
569    auto &mm = mem_mgr::instance();
570    auto to_alloc = mm.translate_ptr(to_surface);
571    auto from_alloc = mm.translate_ptr(from_surface);
572    size_t to_offset = (byte_t *)to_surface - to_alloc.alloc_ptr;
573    size_t from_offset = (byte_t *)from_surface - from_alloc.alloc_ptr;
574    event_list.push_back(q.submit([&](sycl::handler &cgh) {
575      cgh.depends_on(dep_events);
576      auto to_o = sycl::id<1>(to_offset);
577      auto from_o = sycl::id<1>(from_offset);
578      sycl::accessor<byte_t, 1, sycl::access_mode::write,
579                     sycl::access::target::device>
580          to_acc(to_alloc.buffer, cgh,
581                 get_copy_range(size, to_slice, to_range.get(0)), to_o);
582      sycl::accessor<byte_t, 1, sycl::access_mode::read,
583                     sycl::access::target::device>
584          from_acc(from_alloc.buffer, cgh,
585                   get_copy_range(size, from_slice, from_range.get(0)), from_o);
586      cgh.parallel_for<class dpct_memcpy_3d_detail_usmnone>(
587          size, [=](sycl::id<3> id) {
588            to_acc[get_offset(id, to_slice, to_range.get(0))] =
589                from_acc[get_offset(id, from_slice, from_range.get(0))];
590          });
591    }));
592  }
593#else
594    event_list.push_back(q.submit([&](sycl::handler &cgh) {
595      cgh.depends_on(dep_events);
596      cgh.parallel_for<class dpct_memcpy_3d_detail>(size, [=](sycl::id<3> id) {
597        to_surface[get_offset(id, to_slice, to_range.get(0))] =
598            from_surface[get_offset(id, from_slice, from_range.get(0))];
599      });
600    }));
601#endif
602  break;
603  default:
604    throw std::runtime_error("dpct_memcpy: invalid direction value");
605  }
606  return event_list;
607}
608
609/// memcpy 2D/3D matrix specified by pitched_data.
610static inline std::vector<sycl::event>
611dpct_memcpy(sycl::queue &q, pitched_data to, sycl::id<3> to_id,
612            pitched_data from, sycl::id<3> from_id, sycl::range<3> size,
613            memcpy_direction direction = automatic) {
614  return dpct_memcpy(q, to.get_data_ptr(), from.get_data_ptr(),
615                     sycl::range<3>(to.get_pitch(), to.get_y(), 1),
616                     sycl::range<3>(from.get_pitch(), from.get_y(), 1), to_id,
617                     from_id, size, direction);
618}
619
620/// memcpy 2D/3D matrix between different devices.
621static inline std::vector<sycl::event>
622dpct_memcpy(sycl::queue &q, pitched_data to, sycl::id<3> to_id, int to_dev_id,
623            pitched_data from, sycl::id<3> from_id, int from_dev_id,
624            sycl::range<3> size) {
625  if (to_dev_id == from_dev_id)
626    return dpct_memcpy(q, to, to_id, from, from_id, size,
627                       memcpy_direction::device_to_device);
628  std::vector<sycl::event> event_list;
629  const auto to_range = sycl::range<3>(to.get_pitch(), to.get_y(), 1),
630             from_range = sycl::range<3>(from.get_pitch(), from.get_y(), 1);
631  const size_t to_slice = to_range.get(1) * to_range.get(0),
632               from_slice = from_range.get(1) * from_range.get(0);
633  unsigned char *to_surface = (unsigned char *)to.get_data_ptr() +
634                              get_offset(to_id, to_slice, to_range.get(0));
635  const unsigned char *from_surface =
636      (const unsigned char *)from.get_data_ptr() +
637      get_offset(from_id, from_slice, from_range.get(0));
638  copy_to_device_via_host_buffer(q, size, to_surface, to_range, from_surface,
639                                 from_range, event_list, device_to_host);
640  return event_list;
641}
642
643/// memcpy 2D matrix with pitch.
644static inline std::vector<sycl::event>
645dpct_memcpy(sycl::queue &q, void *to_ptr, const void *from_ptr, size_t to_pitch,
646            size_t from_pitch, size_t x, size_t y,
647            memcpy_direction direction = automatic) {
648  return dpct_memcpy(q, to_ptr, from_ptr, sycl::range<3>(to_pitch, y, 1),
649                     sycl::range<3>(from_pitch, y, 1), sycl::id<3>(0, 0, 0),
650                     sycl::id<3>(0, 0, 0), sycl::range<3>(x, y, 1), direction);
651}
652
653static inline std::vector<sycl::event>
654dpct_memcpy(sycl::queue &q, const memcpy_parameter &param) {
655  auto to = param.to.pitched;
656  auto from = param.from.pitched;
657#ifdef SYCL_EXT_ONEAPI_BINDLESS_IMAGES
658  if (param.to.image_bindless != nullptr &&
659      param.from.image_bindless != nullptr) {
660    return {experimental::detail::dpct_memcpy(
661        param.from.image_bindless, param.from.pos, param.from.pos_x_in_bytes,
662        param.to.image_bindless, param.to.pos, param.to.pos_x_in_bytes,
663        param.size, param.size_x_in_bytes, q)};
664  } else if (param.to.image_bindless != nullptr) {
665    return {experimental::detail::dpct_memcpy(
666        from, param.from.pos, param.from.pos_x_in_bytes,
667        param.to.image_bindless, param.to.pos, param.to.pos_x_in_bytes,
668        param.size, param.size_x_in_bytes, q)};
669  } else if (param.from.image_bindless != nullptr) {
670    return {experimental::detail::dpct_memcpy(
671        param.from.image_bindless, param.from.pos, param.from.pos_x_in_bytes,
672        to, param.to.pos, param.to.pos_x_in_bytes, param.size,
673        param.size_x_in_bytes, q)};
674  }
675#endif
676  auto size = param.size;
677  auto to_pos = param.to.pos;
678  auto from_pos = param.from.pos;
679  // If the src and dest are not bindless image, the x can be set to XInByte.
680  if (param.size_x_in_bytes != 0) {
681    size[0] = param.size_x_in_bytes;
682  }
683  if (param.to.pos_x_in_bytes != 0) {
684    to_pos[0] = param.to.pos_x_in_bytes;
685  }
686  if (param.from.pos_x_in_bytes != 0) {
687    from_pos[0] = param.from.pos_x_in_bytes;
688  }
689  if (param.to.image != nullptr) {
690    to = to_pitched_data(param.to.image);
691  }
692  if (param.from.image != nullptr) {
693    from = to_pitched_data(param.from.image);
694  }
695  if (deduce_memcpy_direction(q, to.get_data_ptr(), from.get_data_ptr(),
696                              param.direction) == device_to_device)
697    return dpct_memcpy(q, to, to_pos, param.to.dev_id, from, from_pos,
698                       param.from.dev_id, size);
699  return dpct_memcpy(q, to, to_pos, from, from_pos, size, param.direction);
700}
701
702namespace deprecated {
703
704template <typename T, sycl::usm::alloc AllocKind> class usm_allocator {
705private:
706  using Alloc = sycl::usm_allocator<T, AllocKind>;
707  Alloc _impl;
708
709public:
710  using value_type = typename std::allocator_traits<Alloc>::value_type;
711  using pointer = typename std::allocator_traits<Alloc>::pointer;
712  using const_pointer = typename std::allocator_traits<Alloc>::const_pointer;
713  using void_pointer = typename std::allocator_traits<Alloc>::void_pointer;
714  using const_void_pointer =
715      typename std::allocator_traits<Alloc>::const_void_pointer;
716  using reference = typename std::allocator_traits<Alloc>::value_type &;
717  using const_reference =
718      const typename std::allocator_traits<Alloc>::value_type &;
719  using difference_type =
720      typename std::allocator_traits<Alloc>::difference_type;
721  using size_type = typename std::allocator_traits<Alloc>::size_type;
722  using propagate_on_container_copy_assignment = typename std::allocator_traits<
723      Alloc>::propagate_on_container_copy_assignment;
724  using propagate_on_container_move_assignment = typename std::allocator_traits<
725      Alloc>::propagate_on_container_move_assignment;
726  using propagate_on_container_swap =
727      typename std::allocator_traits<Alloc>::propagate_on_container_swap;
728  using is_always_equal =
729      typename std::allocator_traits<Alloc>::is_always_equal;
730
731  template <typename U> struct rebind {
732    typedef usm_allocator<U, AllocKind> other;
733  };
734
735  usm_allocator() : _impl(dpct::get_default_queue()) {}
736  usm_allocator(sycl::queue &q) : _impl(q) {}
737  ~usm_allocator() {}
738  usm_allocator(const usm_allocator &other) : _impl(other._impl) {}
739  usm_allocator(usm_allocator &&other) : _impl(std::move(other._impl)) {}
740  pointer address(reference r) { return &r; }
741  const_pointer address(const_reference r) { return &r; }
742  pointer allocate(size_type cnt, const_void_pointer hint = nullptr) {
743    return std::allocator_traits<Alloc>::allocate(_impl, cnt, hint);
744  }
745  void deallocate(pointer p, size_type cnt) {
746    std::allocator_traits<Alloc>::deallocate(_impl, p, cnt);
747  }
748  size_type max_size() const {
749    return std::allocator_traits<Alloc>::max_size(_impl);
750  }
751  bool operator==(const usm_allocator &other) const {
752    return _impl == other._impl;
753  }
754  bool operator!=(const usm_allocator &other) const {
755    return _impl != other._impl;
756  }
757};
758
759} // namespace deprecated
760
761inline void dpct_free(void *ptr, const sycl::queue &q) {
762  if (ptr) {
763#ifdef DPCT_USM_LEVEL_NONE
764    detail::mem_mgr::instance().mem_free(ptr);
765#else
766    sycl::free(ptr, q.get_context());
767#endif // DPCT_USM_LEVEL_NONE
768  }
769}
770
771inline sycl::event async_dpct_free(const std::vector<void *> &pointers,
772                                   const std::vector<sycl::event> &events,
773                                   sycl::queue q) {
774  return q.submit([&](sycl::handler &cgh) {
775    cgh.depends_on(events);
776    cgh.host_task([=] {
777      for (auto p : pointers)
778        if (p) {
779          detail::dpct_free(p, q);
780        }
781    });
782  });
783}
784
785/// Device variable with address space of shared, global or constant.
786template <class T, memory_region Memory, size_t Dimension> class device_memory {
787public:
788  using accessor_t =
789      typename detail::memory_traits<Memory, T>::template accessor_t<Dimension>;
790  using value_t = typename detail::memory_traits<Memory, T>::value_t;
791  using dpct_accessor_t = dpct::accessor<T, Memory, Dimension>;
792
793  device_memory() : device_memory(sycl::range<Dimension>(1)) {}
794
795  /// Constructor of 1-D array with initializer list
796  device_memory(const sycl::range<Dimension> &in_range,
797                std::initializer_list<value_t> &&init_list)
798      : device_memory(in_range) {
799    assert(init_list.size() <= in_range.size());
800    _host_ptr = (value_t *)std::malloc(_size);
801    std::memset(_host_ptr, 0, _size);
802    std::memcpy(_host_ptr, init_list.begin(), init_list.size() * sizeof(T));
803  }
804
805  /// Constructor of 2-D array with initializer list
806  template <size_t D = Dimension>
807  device_memory(
808      const typename std::enable_if<D == 2, sycl::range<2>>::type &in_range,
809      std::initializer_list<std::initializer_list<value_t>> &&init_list)
810      : device_memory(in_range) {
811    assert(init_list.size() <= in_range[0]);
812    _host_ptr = (value_t *)std::malloc(_size);
813    std::memset(_host_ptr, 0, _size);
814    auto tmp_data = _host_ptr;
815    for (auto sub_list : init_list) {
816      assert(sub_list.size() <= in_range[1]);
817      std::memcpy(tmp_data, sub_list.begin(), sub_list.size() * sizeof(T));
818      tmp_data += in_range[1];
819    }
820  }
821
822  /// Constructor with range
823  device_memory(const sycl::range<Dimension> &range_in)
824      : _size(range_in.size() * sizeof(T)), _range(range_in), _reference(false),
825        _host_ptr(nullptr) {
826    static_assert((Memory == global) || (Memory == constant) ||
827                      (Memory == shared),
828                  "device memory region should be global, constant or shared");
829    // Strata: the pointer table, mem_mgr and dev_mgr are made at the first get_ptr_impl() (sycl/tools/fixups.py)
830  }
831
832  /// Constructor with range
833  template <class... Args>
834  device_memory(Args... Arguments)
835      : device_memory(sycl::range<Dimension>(Arguments...)) {}
836
837  ~device_memory() {
838    if (!_reference) {
839      for (unsigned i = 0; i < _device_ptrs.size(); ++i) {
840        if (auto ptr = _device_ptrs[i])
841          dpct::dpct_free(ptr, get_device(i).default_queue());
842      }
843    }
844    if (_host_ptr)
845      std::free(_host_ptr);
846  }
847
848  /// Allocate memory with default queue, and init memory if has initial value.
849  void init() { init(dpct::get_default_queue()); }
850  /// Allocate memory with specified queue, and init memory if has initial
851  /// value.
852  void init(sycl::queue &q) { (void)get_ptr_impl(q); }
853
854  /// The variable is assigned to a device pointer.
855#ifndef DPCT_USM_LEVLE_NONE
856  [[deprecated]]
857#endif
858  void
859  assign(value_t *src, size_t size) {
860    this->~device_memory();
861    new (this) device_memory(src, size);
862  }
863
864  /// Get memory pointer of the memory object, which is virtual pointer when
865  /// usm is not used, and device pointer when usm is used.
866  value_t *get_ptr() { return get_ptr(get_default_queue()); }
867  /// Get memory pointer of the memory object, which is virtual pointer when
868  /// usm is not used, and device pointer when usm is used.
869  value_t *get_ptr(sycl::queue &q) { return get_ptr_impl(q); }
870
871  /// Get the device memory object size in bytes.
872  size_t get_size() { return _size; }
873
874  template <size_t D = Dimension>
875  typename std::enable_if<D == 1, T>::type &operator[](size_t index) {
876    auto ptr = get_ptr();
877#ifdef DPCT_USM_LEVEL_NONE
878    return dpct::get_buffer<typename std::enable_if<D == 1, T>::type>(ptr)
879        .get_host_access(sycl::read_write)[index];
880#else
881    return ptr[index];
882#endif // DPCT_USM_LEVEL_NONE
883  }
884
885#ifdef DPCT_USM_LEVEL_NONE
886  /// Get sycl::accessor for the device memory object when usm is not used.
887  accessor_t get_access(sycl::handler &cgh) {
888    return get_buffer(_device_ptrs.front())
889        .template reinterpret<T, Dimension>(_range)
890        .template get_access<detail::memory_traits<Memory, T>::mode,
891                             detail::memory_traits<Memory, T>::target>(cgh);
892  }
893#else
894  /// Get dpct::accessor with dimension info for the device memory object
895  /// when usm is used and dimension is greater than 1.
896  template <size_t D = Dimension>
897  typename std::enable_if<D != 1, dpct_accessor_t>::type
898  get_access(sycl::handler &cgh) {
899    return dpct_accessor_t((T *)_device_ptrs.front(), _range);
900  }
901#endif // DPCT_USM_LEVEL_NONE
902
903private:
904  device_memory(value_t *memory_ptr, size_t size)
905      : _size(size), _range(size / sizeof(T)), _reference(true),
906        _device_ptrs(get_ptrs_size(), memory_ptr) {}
907
908  value_t *allocate_device(sycl::queue &q) {
909    _q = q;
910#ifndef DPCT_USM_LEVEL_NONE
911    if (Memory == shared) {
912      return (value_t *)sycl::malloc_shared(_size, q.get_device(),
913                                            q.get_context());
914    }
915#ifdef SYCL_EXT_ONEAPI_USM_DEVICE_READ_ONLY
916    if (Memory == constant) {
917      return (value_t *)sycl::malloc_device(
918          _size, q.get_device(), q.get_context(),
919          sycl::ext::oneapi::property::usm::device_read_only());
920    }
921#endif
922#endif
923    return (value_t *)detail::dpct_malloc(_size, q);
924  }
925
926  value_t *get_ptr_impl(sycl::queue &q) {
927    if (_device_ptrs.empty()) {
928      detail::mem_mgr::instance();
929      dev_mgr::instance();
930      _device_ptrs.assign(get_ptrs_size(), nullptr);
931    }
932#ifdef DPCT_USM_LEVEL_NONE
933    auto &ptr = _device_ptrs.front();
934#else
935    auto &ptr = _device_ptrs[get_device_id(q.get_device())];
936#endif
937    if (ptr || !_size)
938      return ptr;
939    ptr = allocate_device(q);
940    if (_host_ptr)
941      detail::dpct_memcpy(q, ptr, _host_ptr, _size, host_to_device);
942    return ptr;
943  }
944
945  static size_t get_ptrs_size() {
946#ifdef DPCT_USM_LEVEL_NONE
947    return 1;
948#else
949    return device_count();
950#endif
951  }
952
953  size_t _size;
954  sycl::range<Dimension> _range;
955  bool _reference;
956  value_t *_host_ptr;
957  std::vector<value_t *> _device_ptrs;
958  std::optional<sycl::queue> _q;   // Strata: a default-built sycl::queue picks a device (sycl/tools/fixups.py)
959};
960template <class T, memory_region Memory>
961class device_memory<T, Memory, 0> : public device_memory<T, Memory, 1> {
962public:
963  using base = device_memory<T, Memory, 1>;
964  using value_t = typename base::value_t;
965  using accessor_t =
966      typename detail::memory_traits<Memory, T>::template accessor_t<0>;
967
968  /// Constructor with initial value.
969  device_memory(const value_t &val) : base(sycl::range<1>(1), {val}) {}
970
971  /// Default constructor
972  device_memory() : base(1) {}
973
974#ifdef DPCT_USM_LEVEL_NONE
975  /// Get sycl::accessor for the device memory object when usm is not used.
976  accessor_t get_access(sycl::handler &cgh) {
977    auto buf = get_buffer(base::get_ptr())
978                   .template reinterpret<T, 1>(sycl::range<1>(1));
979    return accessor_t(buf, cgh);
980  }
981#endif // DPCT_USM_LEVEL_NONE
982};
983
984} // namespace detail
985} // namespace dpct
986#endif //! __DPCT_DETAIL_MEMORY_DETAIL_HPP__