Nektar++
Loading...
Searching...
No Matches
MemoryRegion.hpp
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: MemoryRegion.hpp
4//
5// For more information, please see: http://www.nektar.info
6//
7// The MIT License
8//
9// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
10// Department of Aeronautics, Imperial College London (UK), and Scientific
11// Computing and Imaging Institute, University of Utah (USA).
12//
13// Permission is hereby granted, free of charge, to any person obtaining a
14// copy of this software and associated documentation files (the "Software"),
15// to deal in the Software without restriction, including without limitation
16// the rights to use, copy, modify, merge, publish, distribute, sublicense,
17// and/or sell copies of the Software, and to permit persons to whom the
18// Software is furnished to do so, subject to the following conditions:
19//
20// The above copyright notice and this permission notice shall be included
21// in all copies or substantial portions of the Software.
22//
23// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
26// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
28// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
29// DEALINGS IN THE SOFTWARE.
30//
31// Description:
32//
33///////////////////////////////////////////////////////////////////////////////
34
35#pragma once
36
40
41namespace Nektar
42{
43
44/**
45 * @brief Possible states for Field data.
46 *
47 * These identify the mathematical representation of the field data. The two
48 * main states are *Phys*, representing the field at the quadrature points,
49 * and *Coeff*, representing the field in terms of its spectral/hp element
50 * basis coefficients.
51 */
52enum class FieldState
53{
54 Phys,
55 Coeff
56};
57
58template <FieldState TFieldState> std::string FieldStateToString(void)
59{
60 if constexpr (TFieldState == FieldState::Coeff)
61 {
62 return "Coeff";
63 }
64 else if constexpr (TFieldState == FieldState::Phys)
65 {
66 return "Phys";
67 }
68}
69
70// Memory access qualifier
72{
73};
75{
76};
78{
79};
80
81} // namespace Nektar
82
84{
85
86template <typename TData, FieldState TState> class Field;
87
88// Use by NekDataWarehouse.hpp
90{
91};
92
93/**
94 * @brief A MemoryRegion represents a memory region
95 * @tparam TData The data type representation used by the MemoryRegion.
96 */
97template <typename TData> class MemoryRegion : public MemoryRegionBase
98{
99 template <typename TDataField, FieldState TState> friend class Field;
100
101public:
102 MemoryRegion() = default;
103
104 /**
105 * @brief Constructor methods - create a new memory region.
106 *
107 * @param name - name
108 * @param size - size of memory
109 * @param memAllocType - [ eHostPageable, eHostPinned, eDeviceMemoryPool,
110 * eHostPinnedDeviceMemoryPool]
111 * @param alignment - memory alignment
112 */
113 MemoryRegion(const std::string name, const size_t size,
114 const MemAllocType &memAllocType = eHostPageable,
115 const size_t alignment = NektarSpaces::host_memory_alignment)
116 {
117 m_instantiated = true;
118 m_host_owned = true;
119 m_device_owned = true;
120 m_host_valid = false;
121 m_device_valid = false;
122 m_host = nullptr;
123 m_host_aligned = nullptr;
124 m_device = nullptr;
125
126 m_size = size;
127 m_alignment = alignment;
128 m_name = name;
129 m_memAllocType = memAllocType;
130 }
131
132 /**
133 * @brief Constructor methods - create a new memory region.
134 *
135 * @param size - size of memory
136 * @param memAllocType - [ eHostPageable, eHostPinned, eDeviceMemoryPool,
137 * eHostPinnedDeviceMemoryPool]
138 * @param alignment - memory alignment
139 */
140 MemoryRegion(const size_t size,
141 const MemAllocType &memAllocType = eHostPageable,
142 const size_t alignment = NektarSpaces::host_memory_alignment)
143 : MemoryRegion<TData>("", size, memAllocType, alignment)
144 {
145 }
146
147 /**
148 * @brief Constructor methods - move from another MemoryRegion
149 *
150 * @param rhs - MemoryRegion to move from
151 */
159 {
160 rhs.m_instantiated = false;
161 rhs.m_host_owned = true;
162 rhs.m_device_owned = true;
163 rhs.m_host_valid = false;
164 rhs.m_device_valid = false;
165 rhs.m_host = nullptr;
166 rhs.m_host_aligned = nullptr;
167 rhs.m_device = nullptr;
168 rhs.m_size = 0;
169 rhs.m_alignment = NektarSpaces::host_memory_alignment;
170 rhs.m_name = "";
171 rhs.m_memAllocType = eHostPageable;
172 }
173
174 /**
175 * @brief Destructor method.
176 *
177 */
179 {
181 }
182
183 /**
184 * @brief Constructor methods - No copy methods
185 *
186 */
187 MemoryRegion(const MemoryRegion &) = delete;
189
190 /**
191 * @brief Move assignment operator.
192 *
193 * @param rhs - MemoryRegion to move from
194 *
195 * @return - MemoryRegion&
196 */
198 {
199 if (this == &rhs)
200 {
201 return *this;
202 }
203
204 // The storage this region already owns is released before it takes
205 // over the storage of rhs; overwriting the pointers alone would leak
206 // it.
208
209 m_instantiated = rhs.m_instantiated;
210 m_host_owned = rhs.m_host_owned;
211 m_device_owned = rhs.m_device_owned;
212 m_host_valid = rhs.m_host_valid;
213 m_device_valid = rhs.m_device_valid;
214 m_host = rhs.m_host;
215 m_host_aligned = rhs.m_host_aligned;
216 m_device = rhs.m_device;
217 m_size = rhs.m_size;
218 m_alignment = rhs.m_alignment;
219 m_name = rhs.m_name;
220 m_memAllocType = rhs.m_memAllocType;
221
222 rhs.m_instantiated = false;
223 rhs.m_host_owned = true;
224 rhs.m_device_owned = true;
225 rhs.m_host_valid = false;
226 rhs.m_device_valid = false;
227 rhs.m_host = nullptr;
228 rhs.m_host_aligned = nullptr;
229 rhs.m_device = nullptr;
230 rhs.m_size = 0;
231 rhs.m_alignment = NektarSpaces::host_memory_alignment;
232 rhs.m_name = "";
233 rhs.m_memAllocType = eHostPageable;
234
235 return *this;
236 }
237
238 /**
239 * @brief Get the pointer to the host/device memory.
240 *
241 * @return - TData*
242 */
243 template <typename MemSpace, typename MemAccess>
245 [[maybe_unused]] const unsigned int streamID = 0)
246 {
247 if (!m_instantiated)
248 {
250 "MemoryRegion::GetPtr - Object has not been "
251 "instantiated by custom constructor.");
252 }
253
254 if constexpr (std::is_same_v<MemSpace, NektarSpaces::HostSpace>)
255 {
256 // The API returns an error message if the data has not been
257 // previously initialized by using a WriteOnly memory access. Memory
258 // transfer occurs if the data in the host memory space was marked
259 // as invalid. A constant pointer is returned by the API and the
260 // data in the host memory space is now marked as valid. The
261 // data in the device memory space remain valid.
262 if constexpr (std::is_same_v<MemAccess, ReadOnly>)
263 {
264 if (!m_host_aligned && !m_device && m_size > 0)
265 {
266 // Throw an error.
268 "MemoryRegion::GetPtr - attempt to access host "
269 "memory (" +
270 m_name + ") without it being allocated.");
271 }
272
274 {
276 "MemoryRegion::GetPtr - attempt to get a host "
277 "pointer (" +
278 m_name + ") before the data is initialized.");
279 }
280
281 DeviceToHostCopy(streamID); // Move to host if necessary
282
283 m_host_valid = true;
284
285 return m_host_aligned;
286 }
287 // Memory is allocated and marked as initialized, if not yet
288 // allocated. No memory transfer occurs and a non-constant pointer
289 // is returned by the API. The data in the host memory space is
290 // now marked as valid, while the data in the device memory space
291 // is marked as invalid.
292 else if constexpr (std::is_same_v<MemAccess, WriteOnly>)
293 {
294 // Allocate host memory, if not yet allocated.
295 if (!m_host_aligned)
296 {
298 {
299 // Add extra bytes for alignment provision.
300 size_t aligned_bytes_size =
301 m_size * sizeof(TData) + m_alignment;
302 hostMallocPinned(&m_host, aligned_bytes_size);
303 if ((size_t)m_host % m_alignment)
304 {
305 // Get aligned memory pointer by offsetting
306 // non-aligned pinned memory.
308 (TData *)((size_t)m_host + m_alignment -
309 (size_t)m_host % m_alignment);
310 }
311 else
312 {
314 }
315 }
316 else if (m_memAllocType == eHostPageable)
317 {
318 hostMalloc(&m_host, m_size * sizeof(TData),
321 }
322
323 // Initialize memory to zero.
324 std::memset((void *)m_host_aligned, 0,
325 m_size * sizeof(TData));
326 }
327
328 m_host_valid = true;
329 m_device_valid = false;
330
331 return m_host_aligned;
332 }
333 // The API returns an error message if the data have not been
334 // previously initialized by using a WriteOnly memory access. Memory
335 // transfer occurs if the data on the host memory space was
336 // marked as invalid and a non-constant pointer is returned by the
337 // API. The data in the host memory space is now marked as
338 // valid, while the data in the device memory space is marked as
339 // invalid.
340 else if constexpr (std::is_same_v<MemAccess, ReadWrite>)
341 {
342 if (!m_host_aligned && !m_device && m_size > 0)
343 {
344 // Throw an error.
345 NEKERROR(
347 "MemoryRegion::GetPtr - attempt to access host data (" +
348 m_name + ") without it being allocated.");
349 }
350
352 {
354 "MemoryRegion::GetPtr - attempt to get a host "
355 "pointer (" +
356 m_name + ") before the data is initialized.");
357 }
358
359 DeviceToHostCopy(streamID); // Move to host if necessary
360
361 m_host_valid = true;
362 m_device_valid = false;
363
364 return m_host_aligned;
365 }
366 }
367 else if constexpr (std::is_same_v<MemSpace, NektarSpaces::DeviceSpace>)
368 {
369 // The API returns an error message if the data has not been
370 // previously initialized by using a WriteOnly memory access. Memory
371 // transfer occurs if the data in the device memory space was marked
372 // as invalid. A constant pointer is returned by the API and the
373 // data in the device memory space is now marked as valid. The
374 // data in the host memory space remain valid.
375 if constexpr (std::is_same_v<MemAccess, ReadOnly>)
376 {
377 if (!m_host_aligned && !m_device && m_size > 0)
378 {
379 // Throw an error.
381 "MemoryRegion::GetPtr - attempt to access device "
382 "memory (" +
383 m_name + ") without it being allocated.");
384 }
385
387 {
389 "MemoryRegion::GetPtr - attempt to get a host "
390 "pointer (" +
391 m_name + ") before the data is initialized.");
392 }
393
394 HostToDeviceCopy(streamID); // Move to device if necessary
395
396 m_device_valid = true;
397
398 return m_device;
399 }
400 // Memory is allocated and marked as initialized, if not yet
401 // allocated. No memory transfer occurs and a non-constant pointer
402 // is returned by the API. The data in the device memory space is
403 // now marked as valid, while the data in the host memory space
404 // is marked as invalid.
405 else if constexpr (std::is_same_v<MemAccess, WriteOnly>)
406 {
407 // Allocate device memory, if not yet allocated.
408 if (!m_device)
409 {
410 deviceMalloc(&m_device, m_size * sizeof(TData), streamID,
412
413 // Initialize memory to zero.
414 deviceMemset(m_device, 0, m_size * sizeof(TData), streamID);
415 }
416
417 m_host_valid = false;
418 m_device_valid = true;
419
420 return m_device;
421 }
422 // The API returns an error message if the data have not been
423 // previously initialized by using a WriteOnly memory access. Memory
424 // transfer occurs if the data on the device memory space was
425 // marked as invalid and a non-constant pointer is returned by the
426 // API. The data in the device memory space is now marked as
427 // valid, while the data in the host memory space is marked as
428 // invalid.
429 else if constexpr (std::is_same_v<MemAccess, ReadWrite>)
430 {
431 if (!m_host_aligned && !m_device && m_size > 0)
432 {
433 // Throw an error.
435 "MemoryRegion::GetPtr - attempt to access device "
436 "memory (" +
437 m_name + ") without it being allocated.");
438 }
439
441 {
443 "MemoryRegion::GetPtr - attempt to get a host "
444 "pointer (" +
445 m_name + ") before the data is initialized.");
446 }
447
448 HostToDeviceCopy(streamID); // Move to device if necessary
449
450 m_host_valid = false;
451 m_device_valid = true;
452
453 return m_device;
454 }
455 }
456
457 return nullptr;
458 }
459
460 /**
461 * @brief Static templated creation method. This method creates a
462 * new MemoryRegion that copies data from a std::vector
463 *
464 * @param name - name of the memory region
465 * @param array - std::vector to copy from
466 * @param memAllocType - [ eHostPageable, eHostPinned, eDeviceMemoryPool,
467 * eHostPinnedDeviceMemoryPool]
468 * @param alignment - Memory alignment to use.
469 *
470 * @return MemoryRegion<TData>
471 */
472 template <typename MemSpace, typename TDataIn,
473 class Alloc = std::allocator<TDataIn>>
475 const std::string name, std::vector<TDataIn, Alloc> const &array,
476 const unsigned int streamID = 0,
477 const MemAllocType &memAllocType = eHostPageable,
478 const size_t alignment = NektarSpaces::host_memory_alignment)
479 {
480 auto mr =
481 MemoryRegion<TData>(name, array.size(), memAllocType, alignment);
482 mr.template CopyFromHostPtr<MemSpace>(array.data(), array.size(), 0,
483 streamID);
484 return mr;
485 }
486
487 /**
488 * @brief Static templated creation method. This method creates a
489 * new MemoryRegion that copies data from a std::vector
490 *
491 * @param array - std::vector to copy from
492 * @param memAllocType - [ eHostPageable, eHostPinned, eDeviceMemoryPool,
493 * eHostPinnedDeviceMemoryPool]
494 * @param alignment - Memory alignment to use.
495 *
496 * @return MemoryRegion<TData>
497 */
498 template <typename MemSpace, typename TDataIn,
499 class Alloc = std::allocator<TDataIn>>
501 std::vector<TDataIn, Alloc> const &array,
502 const unsigned int streamID = 0,
503 const MemAllocType &memAllocType = eHostPageable,
504 const size_t alignment = NektarSpaces::host_memory_alignment)
505 {
506 return MemoryRegion<TData>::template FromVector<MemSpace, TDataIn>(
507 "", array, streamID, memAllocType, alignment);
508 }
509
510 /**
511 * @brief Static templated creation method. This method creates a
512 * new MemoryRegion that copies data from a
513 * Nektar::Array<Nektar::OneD, TDataIn>
514 *
515 * @param name - name of the memory region
516 * @param array - Nektar::Array to copy from
517 * @param memAllocType - [ eHostPageable, eHostPinned, eDeviceMemoryPool,
518 * eHostPinnedDeviceMemoryPool]
519 * @param alignment - Memory alignment to use.
520 *
521 * @return MemoryRegion<TData>
522 */
523 template <typename MemSpace, typename TDataIn>
525 const std::string name,
527 const unsigned int streamID = 0,
528 const MemAllocType &memAllocType = eHostPageable,
529 const size_t alignment = NektarSpaces::host_memory_alignment)
530 {
531 auto mr =
532 MemoryRegion<TData>(name, array.size(), memAllocType, alignment);
533 mr.template CopyFromHostPtr<MemSpace>(array.data(), array.size(), 0,
534 streamID);
535 return mr;
536 }
537
538 /**
539 * @brief Static templated creation method. This method creates a
540 * new MemoryRegion that copies data from an Nektar::Array
541 *
542 * @param array - Nektar::Array to copy from
543 * @param memAllocType - [ eHostPageable, eHostPinned, eDeviceMemoryPool,
544 * eHostPinnedDeviceMemoryPool]
545 * @param alignment - Memory alignment to use.
546 *
547 * @return MemoryRegion<TData>
548 */
549 template <typename MemSpace, typename TDataIn>
552 const unsigned int streamID = 0,
553 const MemAllocType &memAllocType = eHostPageable,
554 const size_t alignment = NektarSpaces::host_memory_alignment)
555 {
556 return MemoryRegion<TData>::template FromArray<MemSpace, TDataIn>(
557 "", array, streamID, memAllocType, alignment);
558 }
559
560 /**
561 * @brief initialize the storage memory.
562 *
563 * @param val - value to set
564 * @param count - number of values
565 * @param offset - offset to m_host_aligned pointer
566 */
567 template <typename MemSpace>
568 void Initialize(const TData val, const size_t count = 0,
569 const size_t offset = 0, const unsigned int streamID = 0)
570 {
571 if (!m_instantiated)
572 {
574 "MemoryRegion::Initialize - Object has not been "
575 "instantiated by custom constructor.");
576 }
577
578 if (std::is_same_v<MemSpace, NektarSpaces::HostSpace>)
579 {
580 // Allocate host memory, if not yet allocated.
581 if (!m_host_aligned)
582 {
584 {
585 // Add extra bytes for alignment provision.
586 size_t aligned_bytes_size =
587 m_size * sizeof(TData) + m_alignment;
588 hostMallocPinned(&m_host, aligned_bytes_size);
589 if ((size_t)m_host % m_alignment)
590 {
591 // Get aligned memory pointer by offsetting non-aligned
592 // pinned memory.
594 (TData *)((size_t)m_host + m_alignment -
595 (size_t)m_host % m_alignment);
596 }
597 else
598 {
600 }
601 }
602 else if (m_memAllocType == eHostPageable)
603 {
604 hostMalloc(&m_host, m_size * sizeof(TData), m_alignment);
606 }
607
608 // Initialize memory to zero.
609 std::memset((void *)m_host_aligned, 0, m_size * sizeof(TData));
610 }
611
612 auto size = (count == 0) ? m_size : count;
613
614 TData *dst = m_host_aligned + offset;
615
616 // Initialize memory to val.
617 if constexpr (std::is_floating_point_v<TData> ||
618 std::is_integral_v<TData>)
619 {
620 // Zero value.
621 if (val == TData(0))
622 {
623 std::memset(dst, 0, size * sizeof(TData));
624 }
625 // Nonzero value.
626 else
627 {
628 std::fill(dst, dst + size, val);
629 }
630 }
631 else
632 {
633 std::fill(dst, dst + size, val);
634 }
635
636 m_host_valid = true;
637 m_device_valid = false;
638 }
639 else if (std::is_same_v<MemSpace, NektarSpaces::DeviceSpace>)
640 {
641 // Allocate device memory, if not yet allocated.
642 if (!m_device)
643 {
644 deviceMalloc(&m_device, m_size * sizeof(TData), streamID,
646
647 // Initialize memory to zero.
648 deviceMemset(m_device, 0, m_size * sizeof(TData), streamID);
649 }
650
651 auto size = (count == 0) ? m_size : count;
652
653 TData *dst = m_device + offset;
654
655 // Initialize memory to val.
656 if constexpr (std::is_floating_point_v<TData> ||
657 std::is_integral_v<TData>)
658 {
659 // Zero value.
660 if (val == TData(0))
661 {
662 deviceMemset(dst, 0, size * sizeof(TData), streamID);
663 }
664 // Nonzero value.
665 else
666 {
667 deviceFill(dst, val, size, streamID);
668 }
669 }
670 else
671 {
672 deviceFill(dst, val, size, streamID);
673 }
674
675 m_host_valid = false;
676 m_device_valid = true;
677 }
678 }
679
680 /**
681 * @brief Copy data from one region to another region.
682 *
683 * @param rhs - MemoryRegion to copy from
684 */
685 template <typename MemSpace>
687 [[maybe_unused]] const unsigned int streamID = 0)
688 {
689 if (this->size() != rhs.size())
690 {
691 std::stringstream msg;
692
693 msg << "MemoryRegion::Copy - "
694 << "Memory size mismatch between (" << rhs.GetName()
695 << ") and (" << this->GetName() << ").";
697 }
698
699 auto dst = this->template GetPtr<MemSpace, WriteOnly>();
700 auto src = rhs.template GetPtr<MemSpace, ReadOnly>();
701 if constexpr (std::is_same_v<MemSpace, NektarSpaces::HostSpace>)
702 {
703 std::copy(src, src + this->size(), dst);
704 }
705 else if constexpr (std::is_same_v<MemSpace, NektarSpaces::DeviceSpace>)
706 {
707 deviceMemcpy<eDeviceToDevice>(
708 dst, src, this->size() * sizeof(TData), streamID);
709 }
710 }
711
712 /**
713 * @brief Templated copy method. This method copies data from a
714 * std::vector
715 *
716 * @param array - std::vector to copy from
717 *
718 */
719 template <typename MemSpace, typename TDataIn,
720 class Alloc = std::allocator<TDataIn>>
721 void CopyVector(const std::vector<TDataIn, Alloc> &array,
722 const unsigned int streamID = 0)
723 {
724 if (this->size() != array.size())
725 {
726 std::stringstream msg;
727
728 msg << "MemoryRegion::CopyVector - "
729 << "Memory size mismatch between (std::vector) and ("
730 << this->GetName() << ").";
732 }
733
734 this->CopyFromHostPtr<MemSpace>(array.data(), array.size(), 0,
735 streamID);
736 }
737
738 /**
739 * @brief Templated copy method. This method copies data from a
740 * Nektar::Array<Nektar::OneD, TDataIn>
741 *
742 * @param array - Nektar::Array to copy from
743 *
744 */
745 template <typename MemSpace, typename TDataIn>
747 const unsigned int streamID = 0)
748 {
749 if (this->size() != array.size())
750 {
751 std::stringstream msg;
752
753 msg << "MemoryRegion::CopyArray - "
754 << "Memory size mismatch between (Nektar::array) and ("
755 << this->GetName() << ").";
757 }
758
759 this->CopyFromHostPtr<MemSpace>(array.data(), array.size(), 0,
760 streamID);
761 }
762
763 /**
764 * @brief Copy data to a std:vector.
765 *
766 * @return std::vector<TDataOut>
767 */
768 template <typename TDataOut = TData, class Alloc = std::allocator<TDataOut>>
769 std::vector<TDataOut, Alloc> ToVector()
770 {
771 if (!m_instantiated)
772 {
774 "MemoryRegion::ToVector - Object has not been "
775 "instantiated by custom constructor.");
776 }
777
778 if constexpr (std::is_same_v<TDataOut, TData>)
779 {
780 auto ptr =
781 this->template GetPtr<NektarSpaces::HostSpace, ReadOnly>();
782 return std::vector<TDataOut, Alloc>(ptr, ptr + m_size);
783 }
784 else
785 {
786 std::vector<TDataOut, Alloc> vector(m_size);
787
788 // Copy the data from the input field.
789 auto ptr =
790 this->template GetPtr<NektarSpaces::HostSpace, ReadOnly>();
791 auto vecPtr = vector.data();
792
793 std::copy(ptr, ptr + m_size, vecPtr);
794
795 return vector;
796 }
797 }
798
799 /**
800 * @brief Copy data to a Nektar::Array
801 *
802 * @return Array<Nektar::OneD, TDataOut>
803 */
804 template <typename TDataOut = TData>
806 {
807 if (!m_instantiated)
808 {
810 "MemoryRegion::ToArray - Object has not been instantiated "
811 "by custom constructor.");
812 }
813
814 if constexpr (std::is_same_v<TDataOut, TData>)
815 {
817 m_size,
818 this->template GetPtr<NektarSpaces::HostSpace, ReadOnly>());
819 }
820 else
821 {
823
824 // Copy the data from the input field.
825 auto ptr =
826 this->template GetPtr<NektarSpaces::HostSpace, ReadOnly>();
827 auto arrPtr = array.data();
828
829 std::copy(ptr, ptr + m_size, arrPtr);
830
831 return array;
832 }
833 }
834
835 /**
836 * @brief Get the storage memory alignment.
837 *
838 * @return - size_t
839 */
840 size_t GetAlignment() const
841 {
842 if (!m_instantiated)
843 {
845 "MemoryRegion::GetAlignment - Object has not been "
846 "instantiated by custom constructor.");
847 }
848
849 return m_alignment;
850 }
851
852 /**
853 * @brief Get the storage size
854 *
855 * @return - size_t
856 */
857 size_t size() const
858 {
859 return m_size;
860 }
861
862 /**
863 * @brief Get the storage name.
864 *
865 */
866 std::string GetName() const
867 {
868 if (!m_instantiated)
869 {
871 "MemoryRegion::GetName - Object has not been instantiated "
872 "by custom constructor.");
873 }
874
875 return m_name;
876 }
877
878 typedef TData value_type;
879
880private:
881 /**
882 * @brief Free the host and device storage this region owns and return it
883 * to the default, uninstantiated state.
884 *
885 * Storage set from outside with SetHostStorage() or SetDeviceStorage() is
886 * not owned and is left alone.
887 */
889 {
891 {
892 const unsigned int streamID = 0;
893 deviceFree(m_device, m_size * sizeof(TData), streamID,
895 nekStreamSynchronize(streamID);
896 }
897
898 if (m_host && m_host_owned)
899 {
901 {
903 }
904 else if (m_memAllocType == eHostPageable)
905 {
907 }
908 }
909
910 m_instantiated = false;
911 m_host_owned = true;
912 m_device_owned = true;
913 m_host_valid = false;
914 m_device_valid = false;
915 m_host = nullptr;
916 m_host_aligned = nullptr;
917 m_device = nullptr;
918 m_size = 0;
920 m_name = "";
922 }
923
924 /**
925 * @brief Templated copy method.
926 *
927 * @param src - pointer data type TDataIn to copy from
928 * @param size - number of element of type TDataIn to copy
929 * @param offset - offset to m_host_aligned pointer
930 */
931 template <typename MemSpace, typename TDataIn>
932 void CopyFromHostPtr(const TDataIn *src, const size_t size,
933 const size_t offset = 0,
934 const unsigned int streamID = 0)
935 {
936 if (std::is_same_v<MemSpace, NektarSpaces::HostSpace>)
937 {
938 // Allocate host memory, if not yet allocated.
939 if (!m_host_aligned)
940 {
942 {
943 // Add extra bytes for alignment provision.
944 size_t aligned_bytes_size =
945 m_size * sizeof(TData) + m_alignment;
946 hostMallocPinned(&m_host, aligned_bytes_size);
947 if ((size_t)m_host % m_alignment)
948 {
949 // Get aligned memory pointer by offsetting non-aligned
950 // pinned memory.
952 (TData *)((size_t)m_host + m_alignment -
953 (size_t)m_host % m_alignment);
954 }
955 else
956 {
958 }
959 }
960 else if (m_memAllocType == eHostPageable)
961 {
962 hostMalloc(&m_host, m_size * sizeof(TData), m_alignment);
964 }
965
966 // Initialize memory to zero.
967 std::memset((void *)m_host_aligned, 0, m_size * sizeof(TData));
968 }
969
970 TData *dst = m_host_aligned + offset;
971
972 // Copy to host memory.
973 if constexpr (std::is_same_v<TDataIn, TData>)
974 {
975 std::memcpy(dst, src, size * sizeof(TData));
976 }
977 else
978 {
979 std::vector<TData> tmp(size);
980 std::copy(src, src + size, tmp.data());
981 std::memcpy(dst, tmp.data(), size * sizeof(TData));
982 }
983
984 m_host_valid = true;
985 m_device_valid = false;
986 }
987 else if (std::is_same_v<MemSpace, NektarSpaces::DeviceSpace>)
988 {
989 // Allocate device memory, if not yet allocated.
990 if (!m_device)
991 {
992 deviceMalloc(&m_device, m_size * sizeof(TData), streamID,
994
995 // Allocate device memory, if not yet allocated.
996 deviceMemset(m_device, 0, m_size * sizeof(TData), streamID);
997 }
998
999 TData *dst = m_device + offset;
1000
1001 // Copy to device memory.
1002 if constexpr (std::is_same_v<TDataIn, TData>)
1003 {
1004 deviceMemcpy<eHostToDevice>(dst, src, size * sizeof(TData),
1005 streamID);
1006 }
1007 else
1008 {
1009 std::vector<TData> tmp(size);
1010 std::copy(src, src + size, tmp.data());
1011 deviceMemcpy<eHostToDevice>(dst, tmp.data(),
1012 size * sizeof(TData), streamID);
1013 }
1014 m_host_valid = false;
1015 m_device_valid = true;
1016
1017 // Synchronize stream to avoid host memory going out of scope before
1018 // memory copy is complete.
1019 nekStreamSynchronize(streamID);
1020 }
1021 }
1022
1023 /**
1024 * @brief Perform a host to device copy.
1025 *
1026 */
1027 void HostToDeviceCopy(const unsigned int streamID)
1028 {
1029 if (!m_device_valid)
1030 {
1031 if (!m_host_aligned && m_size > 0)
1032 {
1034 "MemoryRegion::HostToDeviceCopy - attempt to transfer "
1035 "data from the host (" +
1036 m_name +
1037 ") without any valid host memory allocated.");
1038 }
1039
1040 // Allocate device memory, if not yet allocated.
1041 if (!m_device)
1042 {
1043 deviceMalloc(&m_device, m_size * sizeof(TData), streamID,
1045 }
1046
1047 // Make sure the host data is valid. It might not be.
1048 if (m_host_valid)
1049 {
1050 deviceMemcpy<eHostToDevice>(m_device, m_host_aligned,
1051 m_size * sizeof(TData), streamID);
1052 }
1053 else
1054 {
1055 // Throw an error.
1057 "MemoryRegion::HostToDeviceCopy - attempt to transfer "
1058 "data (" +
1059 m_name +
1060 ") to the device without any valid host data.");
1061 }
1062 }
1063 }
1064
1065 /**
1066 * @brief Perform a device to host copy.
1067 *
1068 */
1069 void DeviceToHostCopy(const unsigned int streamID)
1070 {
1071 if (!m_host_valid)
1072 {
1073 if (!m_device && m_size > 0)
1074 {
1076 "MemoryRegion::DeviceToHostCopy - attempt to transfer "
1077 "data from the device (" +
1078 m_name +
1079 ") without any valid device memory allocated.");
1080 }
1081
1082 // Allocate host memory, if not yet allocated.
1083 if (!m_host_aligned)
1084 {
1086 {
1087 // Add extra bytes for alignment provision.
1088 size_t aligned_bytes_size =
1089 m_size * sizeof(TData) + m_alignment;
1090 hostMallocPinned(&m_host, aligned_bytes_size);
1091 if ((size_t)m_host % m_alignment)
1092 {
1093 // Get aligned memory pointer by offsetting non-aligned
1094 // pinned memory.
1096 (TData *)((size_t)m_host + m_alignment -
1097 (size_t)m_host % m_alignment);
1098 }
1099 else
1100 {
1102 }
1103 }
1104 else if (m_memAllocType == eHostPageable)
1105 {
1106 hostMalloc(&m_host, m_size * sizeof(TData), m_alignment);
1108 }
1109 }
1110
1111 // Make sure the device data is valid. It might not be.
1112 if (m_device_valid)
1113 {
1114 deviceMemcpy<eDeviceToHost>(m_host_aligned, m_device,
1115 m_size * sizeof(TData), streamID);
1116 }
1117 else
1118 {
1119 // Throw an error.
1121 "MemoryRegion::DeviceToHostCopy - attempt to transfer "
1122 "data (" +
1123 m_name +
1124 ") to the host without any valid device data.");
1125 }
1126 }
1127 }
1128
1129 /**
1130 * @brief Initialize host pointer for an existing (external) pointer.
1131 * Specialized function used in Field.h to allocate a contiguous host memory
1132 * accross all MemoryRegion objects from a Field object. This function
1133 * should not be otherwise used.
1134 *
1135 * @param src - source pointer from Field
1136 *
1137 * Note: It is the user responsability to guarantee that src has the proper
1138 * alignment.
1139 */
1140 void SetHostStorage(TData *src)
1141 {
1142 if (m_host)
1143 {
1144 // Throw an error.
1146 "MemoryRegion::SetHostStorage - Host storage has already "
1147 "been allocated");
1148 }
1149
1150 m_host = src;
1151 m_host_aligned = src;
1152 m_host_owned = false;
1153 }
1154
1155 /**
1156 * @brief Initialize device pointer for an existing (external) pointer.
1157 * Specialized function used in Field.h to allocate a contiguous device
1158 * memory accross all MemoryRegion objects from a Field object. This
1159 * function should not be otherwise used.
1160 *
1161 * @param src - source pointer from Field
1162 *
1163 */
1164 void SetDeviceStorage(TData *src)
1165 {
1166 if (m_device)
1167 {
1168 // Throw an error.
1169 NEKERROR(
1171 "MemoryRegion::SetDeviceStorage - Device storage has already "
1172 "been allocated");
1173 }
1174
1175 m_device = src;
1176 m_device_owned = false;
1177 }
1178
1179 // Member variables:
1180 bool m_instantiated = false; ///< Flag indicating if the current object has
1181 ///< been instantiated.
1182 bool m_host_owned = true; ///< Flag indicating if the host pointer is owned
1183 ///< by the current object.
1184 bool m_device_owned = true; ///< Flag indicating if the device pointer is
1185 ///< owned by the current object.
1186 bool m_host_valid = false; ///< Flag indicating if the host data is valid.
1187 bool m_device_valid = false; ///< Flag indicating if the device data is
1188 ///< valid.
1189 TData *m_host = nullptr; ///< Host memory pointer.
1190 TData *m_host_aligned = nullptr; ///< Host (aligned) memory pointer.
1191 TData *m_device = nullptr; ///< Device memory pointer.
1192 size_t m_size = 0; ///< Storage size (number of elements).
1194
1195 std::string m_name{""}; ///< Name to identify the current object.
1197 eHostPageable}; ///< Host memory allocation type
1198 ///< ( eHostPageable, eHostPinned, eDeviceMemoryPool,
1199 ///< eHostPinnedDeviceMemoryPool).
1200};
1201
1202} // namespace Nektar::LibUtilities
#define NEKERROR(type, msg)
Assert Level 0 – Fundamental assert which is used whether in FULLDEBUG, DEBUG or OPT compilation mode...
A Field represents expansion data to be operated on.
A MemoryRegion represents a memory region.
TData * m_host_aligned
Host (aligned) memory pointer.
static MemoryRegion< TData > FromArray(const std::string name, Nektar::Array< Nektar::OneD, TDataIn > const &array, const unsigned int streamID=0, const MemAllocType &memAllocType=eHostPageable, const size_t alignment=NektarSpaces::host_memory_alignment)
Static templated creation method. This method creates a new MemoryRegion that copies data from a Nekt...
void SetDeviceStorage(TData *src)
Initialize device pointer for an existing (external) pointer. Specialized function used in Field....
static MemoryRegion< TData > FromVector(const std::string name, std::vector< TDataIn, Alloc > const &array, const unsigned int streamID=0, const MemAllocType &memAllocType=eHostPageable, const size_t alignment=NektarSpaces::host_memory_alignment)
Static templated creation method. This method creates a new MemoryRegion that copies data from a std:...
MemoryRegion(const MemoryRegion &)=delete
Constructor methods - No copy methods.
void SetHostStorage(TData *src)
Initialize host pointer for an existing (external) pointer. Specialized function used in Field....
std::string GetName() const
Get the storage name.
const_if< std::is_same_v< MemAccess, ReadOnly >, TData >::type * GetPtr(const unsigned int streamID=0)
Get the pointer to the host/device memory.
bool m_host_owned
Flag indicating if the host pointer is owned by the current object.
size_t size() const
Get the storage size.
TData * m_host
Host memory pointer.
void DeviceToHostCopy(const unsigned int streamID)
Perform a device to host copy.
size_t GetAlignment() const
Get the storage memory alignment.
void CopyArray(const Nektar::Array< Nektar::OneD, TDataIn > &array, const unsigned int streamID=0)
Templated copy method. This method copies data from a Nektar::Array<Nektar::OneD, TDataIn>
bool m_host_valid
Flag indicating if the host data is valid.
MemoryRegion(const size_t size, const MemAllocType &memAllocType=eHostPageable, const size_t alignment=NektarSpaces::host_memory_alignment)
Constructor methods - create a new memory region.
MemoryRegion & operator=(MemoryRegion &&rhs)
Move assignment operator.
Nektar::Array< Nektar::OneD, TDataOut > ToArray()
Copy data to a Nektar::Array.
std::vector< TDataOut, Alloc > ToVector()
Copy data to a std:vector.
size_t m_size
Storage size (number of elements).
MemoryRegion & operator=(const MemoryRegion &)=delete
static MemoryRegion< TData > FromArray(Nektar::Array< Nektar::OneD, TDataIn > const &array, const unsigned int streamID=0, const MemAllocType &memAllocType=eHostPageable, const size_t alignment=NektarSpaces::host_memory_alignment)
Static templated creation method. This method creates a new MemoryRegion that copies data from an Nek...
void ReleaseStorage()
Free the host and device storage this region owns and return it to the default, uninstantiated state.
MemoryRegion(MemoryRegion &&rhs)
Constructor methods - move from another MemoryRegion.
bool m_instantiated
Flag indicating if the current object has been instantiated.
void CopyVector(const std::vector< TDataIn, Alloc > &array, const unsigned int streamID=0)
Templated copy method. This method copies data from a std::vector.
MemoryRegion(const std::string name, const size_t size, const MemAllocType &memAllocType=eHostPageable, const size_t alignment=NektarSpaces::host_memory_alignment)
Constructor methods - create a new memory region.
MemAllocType m_memAllocType
Host memory allocation type ( eHostPageable, eHostPinned, eDeviceMemoryPool, eHostPinnedDeviceMemoryP...
void HostToDeviceCopy(const unsigned int streamID)
Perform a host to device copy.
void Copy(MemoryRegion &rhs, const unsigned int streamID=0)
Copy data from one region to another region.
static MemoryRegion< TData > FromVector(std::vector< TDataIn, Alloc > const &array, const unsigned int streamID=0, const MemAllocType &memAllocType=eHostPageable, const size_t alignment=NektarSpaces::host_memory_alignment)
Static templated creation method. This method creates a new MemoryRegion that copies data from a std:...
std::string m_name
Name to identify the current object.
bool m_device_valid
Flag indicating if the device data is valid.
bool m_device_owned
Flag indicating if the device pointer is owned by the current object.
TData * m_device
Device memory pointer.
void Initialize(const TData val, const size_t count=0, const size_t offset=0, const unsigned int streamID=0)
initialize the storage memory.
void CopyFromHostPtr(const TDataIn *src, const size_t size, const size_t offset=0, const unsigned int streamID=0)
Templated copy method.
static constexpr size_t host_memory_alignment
Definition Backends.hpp:178
void deviceFree(TData *src, const size_t size, const unsigned int streamID, const MemAllocType memAllocType=eHostPageable)
void hostFreePinned(TData *src)
void hostFree(TData *src, const size_t alignment)
void deviceMemset(TData *dst, const int val, const size_t size, const unsigned int streamID)
static void nekStreamSynchronize(const unsigned int streamID)
Definition Backends.hpp:428
void deviceMalloc(TData **src, const size_t size, const unsigned int streamID, const MemAllocType memAllocType=eHostPageable)
@ eHostPageable
void deviceFill(TData *dst, const TData val, const size_t size, const unsigned int streamID)
void hostMallocPinned(TData **src, const size_t size)
FieldState
Possible states for Field data.
std::string FieldStateToString(void)
void hostMalloc(TData **src, const size_t size, const size_t alignment)