xref: /petsc/src/sys/objects/device/impls/cupm/cupmcontext.hpp (revision fbf9dbe564678ed6eff1806adbc4c4f01b9743f4)
1 #ifndef PETSCDEVICECONTEXTCUPM_HPP
2 #define PETSCDEVICECONTEXTCUPM_HPP
3 
4 #include <petsc/private/deviceimpl.h>
5 #include <petsc/private/cupmsolverinterface.hpp>
6 #include <petsc/private/logimpl.h>
7 
8 #include <petsc/private/cpp/array.hpp>
9 
10 #include "../segmentedmempool.hpp"
11 #include "cupmallocator.hpp"
12 #include "cupmstream.hpp"
13 #include "cupmevent.hpp"
14 
15 namespace Petsc
16 {
17 
18 namespace device
19 {
20 
21 namespace cupm
22 {
23 
24 namespace impl
25 {
26 
27 template <DeviceType T>
28 class DeviceContext : SolverInterface<T> {
29 public:
30   PETSC_CUPMSOLVER_INHERIT_INTERFACE_TYPEDEFS_USING(T);
31 
32 private:
33   template <typename H, std::size_t>
34   struct HandleTag {
35     using type = H;
36   };
37 
38   using stream_tag = HandleTag<cupmStream_t, 0>;
39   using blas_tag   = HandleTag<cupmBlasHandle_t, 1>;
40   using solver_tag = HandleTag<cupmSolverHandle_t, 2>;
41 
42   using stream_type = CUPMStream<T>;
43   using event_type  = CUPMEvent<T>;
44 
45 public:
46   // This is the canonical PETSc "impls" struct that normally resides in a standalone impls
47   // header, but since we are using the power of templates it must be declared part of
48   // this class to have easy access the same typedefs. Technically one can make a
49   // templated struct outside the class but it's more code for the same result.
50   struct PetscDeviceContext_IMPLS : memory::PoolAllocated<PetscDeviceContext_IMPLS> {
51     stream_type stream{};
52     cupmEvent_t event{};
53     cupmEvent_t begin{}; // timer-only
54     cupmEvent_t end{};   // timer-only
55 #if PetscDefined(USE_DEBUG)
56     PetscBool timerInUse{};
57 #endif
58     cupmBlasHandle_t   blas{};
59     cupmSolverHandle_t solver{};
60 
61     constexpr PetscDeviceContext_IMPLS() noexcept = default;
62 
63     PETSC_NODISCARD const cupmStream_t &get(stream_tag) const noexcept { return this->stream.get_stream(); }
64 
65     PETSC_NODISCARD const cupmBlasHandle_t &get(blas_tag) const noexcept { return this->blas; }
66 
67     PETSC_NODISCARD const cupmSolverHandle_t &get(solver_tag) const noexcept { return this->solver; }
68   };
69 
70 private:
71   static bool initialized_;
72 
73   static std::array<cupmBlasHandle_t, PETSC_DEVICE_MAX_DEVICES>   blashandles_;
74   static std::array<cupmSolverHandle_t, PETSC_DEVICE_MAX_DEVICES> solverhandles_;
75 
76   PETSC_NODISCARD static constexpr PetscDeviceContext_IMPLS *impls_cast_(PetscDeviceContext ptr) noexcept { return static_cast<PetscDeviceContext_IMPLS *>(ptr->data); }
77 
78   PETSC_NODISCARD static constexpr CUPMEvent<T> *event_cast_(PetscEvent event) noexcept { return static_cast<CUPMEvent<T> *>(event->data); }
79 
80   PETSC_NODISCARD static PetscLogEvent CUPMBLAS_HANDLE_CREATE() noexcept { return T == DeviceType::CUDA ? CUBLAS_HANDLE_CREATE : HIPBLAS_HANDLE_CREATE; }
81 
82   PETSC_NODISCARD static PetscLogEvent CUPMSOLVER_HANDLE_CREATE() noexcept { return T == DeviceType::CUDA ? CUSOLVER_HANDLE_CREATE : HIPSOLVER_HANDLE_CREATE; }
83 
84   // this exists purely to satisfy the compiler so the tag-based dispatch works for the other
85   // handles
86   static PetscErrorCode initialize_handle_(stream_tag, PetscDeviceContext) noexcept { return PETSC_SUCCESS; }
87 
88   static PetscErrorCode initialize_handle_(blas_tag, PetscDeviceContext dctx) noexcept
89   {
90     const auto dci    = impls_cast_(dctx);
91     auto      &handle = blashandles_[dctx->device->deviceId];
92 
93     PetscFunctionBegin;
94     if (!handle) {
95       PetscLogEvent event;
96 
97       PetscCall(PetscLogPauseCurrentEvent_Internal(&event));
98       PetscCall(PetscLogEventBegin(CUPMBLAS_HANDLE_CREATE(), 0, 0, 0, 0));
99       for (auto i = 0; i < 3; ++i) {
100         const auto cberr = cupmBlasCreate(handle.ptr_to());
101         if (PetscLikely(cberr == CUPMBLAS_STATUS_SUCCESS)) break;
102         if (PetscUnlikely(cberr != CUPMBLAS_STATUS_ALLOC_FAILED) && (cberr != CUPMBLAS_STATUS_NOT_INITIALIZED)) PetscCallCUPMBLAS(cberr);
103         if (i != 2) {
104           PetscCall(PetscSleep(3));
105           continue;
106         }
107         PetscCheck(cberr == CUPMBLAS_STATUS_SUCCESS, PETSC_COMM_SELF, PETSC_ERR_GPU_RESOURCE, "Unable to initialize %s", cupmBlasName());
108       }
109       PetscCall(PetscLogEventEnd(CUPMBLAS_HANDLE_CREATE(), 0, 0, 0, 0));
110       PetscCall(PetscLogEventResume_Internal(event));
111     }
112     PetscCallCUPMBLAS(cupmBlasSetStream(handle, dci->stream.get_stream()));
113     dci->blas = handle;
114     PetscFunctionReturn(PETSC_SUCCESS);
115   }
116 
117   static PetscErrorCode initialize_handle_(solver_tag, PetscDeviceContext dctx) noexcept
118   {
119     const auto dci    = impls_cast_(dctx);
120     auto      &handle = solverhandles_[dctx->device->deviceId];
121 
122     PetscFunctionBegin;
123     if (!handle) {
124       PetscLogEvent event;
125 
126       PetscCall(PetscLogPauseCurrentEvent_Internal(&event));
127       PetscCall(PetscLogEventBegin(CUPMSOLVER_HANDLE_CREATE(), 0, 0, 0, 0));
128       for (auto i = 0; i < 3; ++i) {
129         const auto cerr = cupmSolverCreate(&handle);
130         if (PetscLikely(cerr == CUPMSOLVER_STATUS_SUCCESS)) break;
131         if ((cerr != CUPMSOLVER_STATUS_NOT_INITIALIZED) && (cerr != CUPMSOLVER_STATUS_ALLOC_FAILED)) PetscCallCUPMSOLVER(cerr);
132         if (i < 2) {
133           PetscCall(PetscSleep(3));
134           continue;
135         }
136         PetscCheck(cerr == CUPMSOLVER_STATUS_SUCCESS, PETSC_COMM_SELF, PETSC_ERR_GPU_RESOURCE, "Unable to initialize %s", cupmSolverName());
137       }
138       PetscCall(PetscLogEventEnd(CUPMSOLVER_HANDLE_CREATE(), 0, 0, 0, 0));
139       PetscCall(PetscLogEventResume_Internal(event));
140     }
141     PetscCallCUPMSOLVER(cupmSolverSetStream(handle, dci->stream.get_stream()));
142     dci->solver = handle;
143     PetscFunctionReturn(PETSC_SUCCESS);
144   }
145 
146   static PetscErrorCode check_current_device_(PetscDeviceContext dctxl, PetscDeviceContext dctxr) noexcept
147   {
148     const auto devidl = dctxl->device->deviceId, devidr = dctxr->device->deviceId;
149 
150     PetscFunctionBegin;
151     PetscCheck(devidl == devidr, PETSC_COMM_SELF, PETSC_ERR_GPU, "Device contexts must be on the same device; dctx A (id %" PetscInt64_FMT " device id %" PetscInt_FMT ") dctx B (id %" PetscInt64_FMT " device id %" PetscInt_FMT ")",
152                PetscObjectCast(dctxl)->id, devidl, PetscObjectCast(dctxr)->id, devidr);
153     PetscCall(PetscDeviceCheckDeviceCount_Internal(devidl));
154     PetscCall(PetscDeviceCheckDeviceCount_Internal(devidr));
155     PetscCallCUPM(cupmSetDevice(static_cast<int>(devidl)));
156     PetscFunctionReturn(PETSC_SUCCESS);
157   }
158 
159   static PetscErrorCode check_current_device_(PetscDeviceContext dctx) noexcept { return check_current_device_(dctx, dctx); }
160 
161   static PetscErrorCode finalize_() noexcept
162   {
163     PetscFunctionBegin;
164     for (auto &&handle : blashandles_) {
165       if (handle) {
166         PetscCallCUPMBLAS(cupmBlasDestroy(handle));
167         handle = nullptr;
168       }
169     }
170 
171     for (auto &&handle : solverhandles_) {
172       if (handle) {
173         PetscCallCUPMSOLVER(cupmSolverDestroy(handle));
174         handle = nullptr;
175       }
176     }
177     initialized_ = false;
178     PetscFunctionReturn(PETSC_SUCCESS);
179   }
180 
181   template <typename Allocator, typename PoolType = ::Petsc::memory::SegmentedMemoryPool<typename Allocator::value_type, stream_type, Allocator, 256 * sizeof(PetscScalar)>>
182   PETSC_NODISCARD static PoolType &default_pool_() noexcept
183   {
184     static PoolType pool;
185     return pool;
186   }
187 
188   static PetscErrorCode check_memtype_(PetscMemType mtype, const char mess[]) noexcept
189   {
190     PetscFunctionBegin;
191     PetscCheck(PetscMemTypeHost(mtype) || (mtype == PETSC_MEMTYPE_DEVICE) || (mtype == PETSC_MEMTYPE_CUPM()), PETSC_COMM_SELF, PETSC_ERR_SUP, "%s device context can only handle %s (pinned) host or device memory", cupmName(), mess);
192     PetscFunctionReturn(PETSC_SUCCESS);
193   }
194 
195 public:
196   // All of these functions MUST be static in order to be callable from C, otherwise they
197   // get the implicit 'this' pointer tacked on
198   static PetscErrorCode destroy(PetscDeviceContext) noexcept;
199   static PetscErrorCode changeStreamType(PetscDeviceContext, PetscStreamType) noexcept;
200   static PetscErrorCode setUp(PetscDeviceContext) noexcept;
201   static PetscErrorCode query(PetscDeviceContext, PetscBool *) noexcept;
202   static PetscErrorCode waitForContext(PetscDeviceContext, PetscDeviceContext) noexcept;
203   static PetscErrorCode synchronize(PetscDeviceContext) noexcept;
204   template <typename Handle_t>
205   static PetscErrorCode getHandle(PetscDeviceContext, void *) noexcept;
206   template <typename Handle_t>
207   static PetscErrorCode getHandlePtr(PetscDeviceContext, void **) noexcept;
208   static PetscErrorCode beginTimer(PetscDeviceContext) noexcept;
209   static PetscErrorCode endTimer(PetscDeviceContext, PetscLogDouble *) noexcept;
210   static PetscErrorCode memAlloc(PetscDeviceContext, PetscBool, PetscMemType, std::size_t, std::size_t, void **) noexcept;
211   static PetscErrorCode memFree(PetscDeviceContext, PetscMemType, void **) noexcept;
212   static PetscErrorCode memCopy(PetscDeviceContext, void *PETSC_RESTRICT, const void *PETSC_RESTRICT, std::size_t, PetscDeviceCopyMode) noexcept;
213   static PetscErrorCode memSet(PetscDeviceContext, PetscMemType, void *, PetscInt, std::size_t) noexcept;
214   static PetscErrorCode createEvent(PetscDeviceContext, PetscEvent) noexcept;
215   static PetscErrorCode recordEvent(PetscDeviceContext, PetscEvent) noexcept;
216   static PetscErrorCode waitForEvent(PetscDeviceContext, PetscEvent) noexcept;
217 
218   // not a PetscDeviceContext method, this registers the class
219   static PetscErrorCode initialize(PetscDevice) noexcept;
220 
221   // clang-format off
222   static constexpr _DeviceContextOps ops = {
223     PetscDesignatedInitializer(destroy, destroy),
224     PetscDesignatedInitializer(changestreamtype, changeStreamType),
225     PetscDesignatedInitializer(setup, setUp),
226     PetscDesignatedInitializer(query, query),
227     PetscDesignatedInitializer(waitforcontext, waitForContext),
228     PetscDesignatedInitializer(synchronize, synchronize),
229     PetscDesignatedInitializer(getblashandle, getHandle<blas_tag>),
230     PetscDesignatedInitializer(getsolverhandle, getHandle<solver_tag>),
231     PetscDesignatedInitializer(getstreamhandle, getHandlePtr<stream_tag>),
232     PetscDesignatedInitializer(begintimer, beginTimer),
233     PetscDesignatedInitializer(endtimer, endTimer),
234     PetscDesignatedInitializer(memalloc, memAlloc),
235     PetscDesignatedInitializer(memfree, memFree),
236     PetscDesignatedInitializer(memcopy, memCopy),
237     PetscDesignatedInitializer(memset, memSet),
238     PetscDesignatedInitializer(createevent, createEvent),
239     PetscDesignatedInitializer(recordevent, recordEvent),
240     PetscDesignatedInitializer(waitforevent, waitForEvent)
241   };
242   // clang-format on
243 };
244 
245 // not a PetscDeviceContext method, this initializes the CLASS
246 template <DeviceType T>
247 inline PetscErrorCode DeviceContext<T>::initialize(PetscDevice device) noexcept
248 {
249   PetscFunctionBegin;
250   if (PetscUnlikely(!initialized_)) {
251     uint64_t      threshold = UINT64_MAX;
252     cupmMemPool_t mempool;
253 
254     initialized_ = true;
255     PetscCallCUPM(cupmDeviceGetMemPool(&mempool, static_cast<int>(device->deviceId)));
256     PetscCallCUPM(cupmMemPoolSetAttribute(mempool, cupmMemPoolAttrReleaseThreshold, &threshold));
257     blashandles_.fill(nullptr);
258     solverhandles_.fill(nullptr);
259     PetscCall(PetscRegisterFinalize(finalize_));
260   }
261   PetscFunctionReturn(PETSC_SUCCESS);
262 }
263 
264 template <DeviceType T>
265 inline PetscErrorCode DeviceContext<T>::destroy(PetscDeviceContext dctx) noexcept
266 {
267   PetscFunctionBegin;
268   if (const auto dci = impls_cast_(dctx)) {
269     PetscCall(dci->stream.destroy());
270     if (dci->event) PetscCall(cupm_fast_event_pool<T>().deallocate(&dci->event));
271     if (dci->begin) PetscCallCUPM(cupmEventDestroy(dci->begin));
272     if (dci->end) PetscCallCUPM(cupmEventDestroy(dci->end));
273     delete dci;
274     dctx->data = nullptr;
275   }
276   PetscFunctionReturn(PETSC_SUCCESS);
277 }
278 
279 template <DeviceType T>
280 inline PetscErrorCode DeviceContext<T>::changeStreamType(PetscDeviceContext dctx, PETSC_UNUSED PetscStreamType stype) noexcept
281 {
282   const auto dci = impls_cast_(dctx);
283 
284   PetscFunctionBegin;
285   PetscCall(dci->stream.destroy());
286   // set these to null so they aren't usable until setup is called again
287   dci->blas   = nullptr;
288   dci->solver = nullptr;
289   PetscFunctionReturn(PETSC_SUCCESS);
290 }
291 
292 template <DeviceType T>
293 inline PetscErrorCode DeviceContext<T>::setUp(PetscDeviceContext dctx) noexcept
294 {
295   const auto dci   = impls_cast_(dctx);
296   auto      &event = dci->event;
297 
298   PetscFunctionBegin;
299   PetscCall(check_current_device_(dctx));
300   PetscCall(dci->stream.change_type(dctx->streamType));
301   if (!event) PetscCall(cupm_fast_event_pool<T>().allocate(&event));
302 #if PetscDefined(USE_DEBUG)
303   dci->timerInUse = PETSC_FALSE;
304 #endif
305   PetscFunctionReturn(PETSC_SUCCESS);
306 }
307 
308 template <DeviceType T>
309 inline PetscErrorCode DeviceContext<T>::query(PetscDeviceContext dctx, PetscBool *idle) noexcept
310 {
311   PetscFunctionBegin;
312   PetscCall(check_current_device_(dctx));
313   switch (auto cerr = cupmStreamQuery(impls_cast_(dctx)->stream.get_stream())) {
314   case cupmSuccess:
315     *idle = PETSC_TRUE;
316     break;
317   case cupmErrorNotReady:
318     *idle = PETSC_FALSE;
319     // reset the error
320     cerr = cupmGetLastError();
321     static_cast<void>(cerr);
322     break;
323   default:
324     PetscCallCUPM(cerr);
325     PetscUnreachable();
326   }
327   PetscFunctionReturn(PETSC_SUCCESS);
328 }
329 
330 template <DeviceType T>
331 inline PetscErrorCode DeviceContext<T>::waitForContext(PetscDeviceContext dctxa, PetscDeviceContext dctxb) noexcept
332 {
333   const auto dcib  = impls_cast_(dctxb);
334   const auto event = dcib->event;
335 
336   PetscFunctionBegin;
337   PetscCall(check_current_device_(dctxa, dctxb));
338   PetscCallCUPM(cupmEventRecord(event, dcib->stream.get_stream()));
339   PetscCallCUPM(cupmStreamWaitEvent(impls_cast_(dctxa)->stream.get_stream(), event, 0));
340   PetscFunctionReturn(PETSC_SUCCESS);
341 }
342 
343 template <DeviceType T>
344 inline PetscErrorCode DeviceContext<T>::synchronize(PetscDeviceContext dctx) noexcept
345 {
346   auto idle = PETSC_TRUE;
347 
348   PetscFunctionBegin;
349   PetscCall(query(dctx, &idle));
350   if (!idle) PetscCallCUPM(cupmStreamSynchronize(impls_cast_(dctx)->stream.get_stream()));
351   PetscFunctionReturn(PETSC_SUCCESS);
352 }
353 
354 template <DeviceType T>
355 template <typename handle_t>
356 inline PetscErrorCode DeviceContext<T>::getHandle(PetscDeviceContext dctx, void *handle) noexcept
357 {
358   PetscFunctionBegin;
359   PetscCall(initialize_handle_(handle_t{}, dctx));
360   *static_cast<typename handle_t::type *>(handle) = impls_cast_(dctx)->get(handle_t{});
361   PetscFunctionReturn(PETSC_SUCCESS);
362 }
363 
364 template <DeviceType T>
365 template <typename handle_t>
366 inline PetscErrorCode DeviceContext<T>::getHandlePtr(PetscDeviceContext dctx, void **handle) noexcept
367 {
368   using handle_type = typename handle_t::type;
369 
370   PetscFunctionBegin;
371   PetscCall(initialize_handle_(handle_t{}, dctx));
372   *reinterpret_cast<handle_type **>(handle) = const_cast<handle_type *>(std::addressof(impls_cast_(dctx)->get(handle_t{})));
373   PetscFunctionReturn(PETSC_SUCCESS);
374 }
375 
376 template <DeviceType T>
377 inline PetscErrorCode DeviceContext<T>::beginTimer(PetscDeviceContext dctx) noexcept
378 {
379   const auto dci = impls_cast_(dctx);
380 
381   PetscFunctionBegin;
382   PetscCall(check_current_device_(dctx));
383 #if PetscDefined(USE_DEBUG)
384   PetscCheck(!dci->timerInUse, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Forgot to call PetscLogGpuTimeEnd()?");
385   dci->timerInUse = PETSC_TRUE;
386 #endif
387   if (!dci->begin) {
388     PetscAssert(!dci->end, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Don't have a 'begin' event, but somehow have an end event");
389     PetscCallCUPM(cupmEventCreate(&dci->begin));
390     PetscCallCUPM(cupmEventCreate(&dci->end));
391   }
392   PetscCallCUPM(cupmEventRecord(dci->begin, dci->stream.get_stream()));
393   PetscFunctionReturn(PETSC_SUCCESS);
394 }
395 
396 template <DeviceType T>
397 inline PetscErrorCode DeviceContext<T>::endTimer(PetscDeviceContext dctx, PetscLogDouble *elapsed) noexcept
398 {
399   float      gtime;
400   const auto dci = impls_cast_(dctx);
401   const auto end = dci->end;
402 
403   PetscFunctionBegin;
404   PetscCall(check_current_device_(dctx));
405 #if PetscDefined(USE_DEBUG)
406   PetscCheck(dci->timerInUse, PETSC_COMM_SELF, PETSC_ERR_PLIB, "Forgot to call PetscLogGpuTimeBegin()?");
407   dci->timerInUse = PETSC_FALSE;
408 #endif
409   PetscCallCUPM(cupmEventRecord(end, dci->stream.get_stream()));
410   PetscCallCUPM(cupmEventSynchronize(end));
411   PetscCallCUPM(cupmEventElapsedTime(&gtime, dci->begin, end));
412   *elapsed = static_cast<util::remove_pointer_t<decltype(elapsed)>>(gtime);
413   PetscFunctionReturn(PETSC_SUCCESS);
414 }
415 
416 template <DeviceType T>
417 inline PetscErrorCode DeviceContext<T>::memAlloc(PetscDeviceContext dctx, PetscBool clear, PetscMemType mtype, std::size_t n, std::size_t alignment, void **dest) noexcept
418 {
419   const auto &stream = impls_cast_(dctx)->stream;
420 
421   PetscFunctionBegin;
422   PetscCall(check_current_device_(dctx));
423   PetscCall(check_memtype_(mtype, "allocating"));
424   if (PetscMemTypeHost(mtype)) {
425     PetscCall(default_pool_<HostAllocator<T>>().allocate(n, reinterpret_cast<char **>(dest), &stream, alignment));
426   } else {
427     PetscCall(default_pool_<DeviceAllocator<T>>().allocate(n, reinterpret_cast<char **>(dest), &stream, alignment));
428   }
429   if (clear) PetscCallCUPM(cupmMemsetAsync(*dest, 0, n, stream.get_stream()));
430   PetscFunctionReturn(PETSC_SUCCESS);
431 }
432 
433 template <DeviceType T>
434 inline PetscErrorCode DeviceContext<T>::memFree(PetscDeviceContext dctx, PetscMemType mtype, void **ptr) noexcept
435 {
436   const auto &stream = impls_cast_(dctx)->stream;
437 
438   PetscFunctionBegin;
439   PetscCall(check_current_device_(dctx));
440   PetscCall(check_memtype_(mtype, "freeing"));
441   if (!*ptr) PetscFunctionReturn(PETSC_SUCCESS);
442   if (PetscMemTypeHost(mtype)) {
443     PetscCall(default_pool_<HostAllocator<T>>().deallocate(reinterpret_cast<char **>(ptr), &stream));
444     // if ptr exists still exists the pool didn't own it
445     if (*ptr) {
446       auto registered = PETSC_FALSE, managed = PETSC_FALSE;
447 
448       PetscCall(PetscCUPMGetMemType(*ptr, nullptr, &registered, &managed));
449       if (registered) {
450         PetscCallCUPM(cupmFreeHost(*ptr));
451       } else if (managed) {
452         PetscCallCUPM(cupmFreeAsync(*ptr, stream.get_stream()));
453       }
454     }
455   } else {
456     PetscCall(default_pool_<DeviceAllocator<T>>().deallocate(reinterpret_cast<char **>(ptr), &stream));
457     // if ptr still exists the pool didn't own it
458     if (*ptr) PetscCallCUPM(cupmFreeAsync(*ptr, stream.get_stream()));
459   }
460   PetscFunctionReturn(PETSC_SUCCESS);
461 }
462 
463 template <DeviceType T>
464 inline PetscErrorCode DeviceContext<T>::memCopy(PetscDeviceContext dctx, void *PETSC_RESTRICT dest, const void *PETSC_RESTRICT src, std::size_t n, PetscDeviceCopyMode mode) noexcept
465 {
466   const auto stream = impls_cast_(dctx)->stream.get_stream();
467 
468   PetscFunctionBegin;
469   // can't use PetscCUPMMemcpyAsync here since we don't know sizeof(*src)...
470   if (mode == PETSC_DEVICE_COPY_HTOH) {
471     const auto cerr = cupmStreamQuery(stream);
472 
473     // yes this is faster
474     if (cerr == cupmSuccess) {
475       PetscCall(PetscMemcpy(dest, src, n));
476       PetscFunctionReturn(PETSC_SUCCESS);
477     } else if (cerr == cupmErrorNotReady) {
478       auto PETSC_UNUSED unused = cupmGetLastError();
479 
480       static_cast<void>(unused);
481     } else {
482       PetscCallCUPM(cerr);
483     }
484   }
485   PetscCallCUPM(cupmMemcpyAsync(dest, src, n, PetscDeviceCopyModeToCUPMMemcpyKind(mode), stream));
486   PetscFunctionReturn(PETSC_SUCCESS);
487 }
488 
489 template <DeviceType T>
490 inline PetscErrorCode DeviceContext<T>::memSet(PetscDeviceContext dctx, PetscMemType mtype, void *ptr, PetscInt v, std::size_t n) noexcept
491 {
492   PetscFunctionBegin;
493   PetscCall(check_current_device_(dctx));
494   PetscCall(check_memtype_(mtype, "zeroing"));
495   PetscCallCUPM(cupmMemsetAsync(ptr, static_cast<int>(v), n, impls_cast_(dctx)->stream.get_stream()));
496   PetscFunctionReturn(PETSC_SUCCESS);
497 }
498 
499 template <DeviceType T>
500 inline PetscErrorCode DeviceContext<T>::createEvent(PetscDeviceContext, PetscEvent event) noexcept
501 {
502   PetscFunctionBegin;
503   PetscCallCXX(event->data = new event_type());
504   event->destroy = [](PetscEvent event) {
505     PetscFunctionBegin;
506     delete event_cast_(event);
507     event->data = nullptr;
508     PetscFunctionReturn(PETSC_SUCCESS);
509   };
510   PetscFunctionReturn(PETSC_SUCCESS);
511 }
512 
513 template <DeviceType T>
514 inline PetscErrorCode DeviceContext<T>::recordEvent(PetscDeviceContext dctx, PetscEvent event) noexcept
515 {
516   PetscFunctionBegin;
517   PetscCall(impls_cast_(dctx)->stream.record_event(*event_cast_(event)));
518   PetscFunctionReturn(PETSC_SUCCESS);
519 }
520 
521 template <DeviceType T>
522 inline PetscErrorCode DeviceContext<T>::waitForEvent(PetscDeviceContext dctx, PetscEvent event) noexcept
523 {
524   PetscFunctionBegin;
525   PetscCall(impls_cast_(dctx)->stream.wait_for_event(*event_cast_(event)));
526   PetscFunctionReturn(PETSC_SUCCESS);
527 }
528 
529 // initialize the static member variables
530 template <DeviceType T>
531 bool DeviceContext<T>::initialized_ = false;
532 
533 template <DeviceType T>
534 std::array<typename DeviceContext<T>::cupmBlasHandle_t, PETSC_DEVICE_MAX_DEVICES> DeviceContext<T>::blashandles_ = {};
535 
536 template <DeviceType T>
537 std::array<typename DeviceContext<T>::cupmSolverHandle_t, PETSC_DEVICE_MAX_DEVICES> DeviceContext<T>::solverhandles_ = {};
538 
539 template <DeviceType T>
540 constexpr _DeviceContextOps DeviceContext<T>::ops;
541 
542 } // namespace impl
543 
544 // shorten this one up a bit (and instantiate the templates)
545 using CUPMContextCuda = impl::DeviceContext<DeviceType::CUDA>;
546 using CUPMContextHip  = impl::DeviceContext<DeviceType::HIP>;
547 
548 // shorthand for what is an EXTREMELY long name
549 #define PetscDeviceContext_(IMPLS) ::Petsc::device::cupm::impl::DeviceContext<::Petsc::device::cupm::DeviceType::IMPLS>::PetscDeviceContext_IMPLS
550 
551 } // namespace cupm
552 
553 } // namespace device
554 
555 } // namespace Petsc
556 
557 #endif // PETSCDEVICECONTEXTCUDA_HPP
558