FieldAllocator.h 11.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//======================================================================================================================
//
//  This file is part of waLBerla. waLBerla is free software: you can 
//  redistribute it and/or modify it under the terms of the GNU General Public
//  License as published by the Free Software Foundation, either version 3 of 
//  the License, or (at your option) any later version.
//  
//  waLBerla is distributed in the hope that it will be useful, but WITHOUT 
//  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
//  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License 
//  for more details.
//  
//  You should have received a copy of the GNU General Public License along
//  with waLBerla (see COPYING.txt). If not, see <http://www.gnu.org/licenses/>.
//
//! \file FieldAllocator.h
//! \ingroup field
//! \author Martin Bauer <martin.bauer@fau.de>
//! \brief Allocation Strategies for Fields
//
//======================================================================================================================

#pragma once

#include "AlignedMalloc.h"
#include "core/debug/Debug.h"
#include "field/CMakeDefs.h"

#include <map>
#include <new>


namespace walberla {
namespace field {


   //*******************************************************************************************************************
   /*! Allocation Strategy base class for fields
   *
   * \ingroup field
   *
   * The base class handles reference counting, and has purely virtual member functions
   * that have to be implemented by concrete strategy.
   */
   //*******************************************************************************************************************
   template<typename T>
   class FieldAllocator
   {
      public:

51
52
         virtual ~FieldAllocator() = default;

53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
         /**
          * \brief Allocate memory for a field of given sizes and initializes reference counter with one
          *
          * \param size*       The size of the field. size0*size1*size2*size*3 is the minimum amount of
          *                    memory that has to be allocated. size0 is the size of the outermost (slowest)
          *                    coordinate, size3 the size of the fastest.
          *
          * \param allocSize*  Output parameters. The actual size of the allocation may be bigger. Here
          *                    allocSize can be bigger than size if alignment >0. There is no allocSize0,
          *                    since extra allocations (padding) for the outer coordinate do not make sense.
          */
         T * allocate (  uint_t size0, uint_t size1, uint_t size2, uint_t size3,
                         uint_t & allocSize1, uint_t & allocSize2, uint_t & allocSize3)
         {
            T * mem = allocateMemory(size0,size1,size2,size3,allocSize1,allocSize2,allocSize3);
            #ifdef WALBERLA_THREAD_SAFE_FIELD_ALLOCATION
            #ifdef _OPENMP
            #pragma omp critical( walberla_field_allocator_refcount )
            #endif
            #endif
            {
               WALBERLA_ASSERT( referenceCounts_.find(mem) == referenceCounts_.end() || referenceCounts_[mem] == 0 );
               referenceCounts_[mem] = 1;
            }
            return mem;
         }


         virtual void setInnerGhostLayerSize( uint_t /*innerGhostLayerSize*/ ) {}

         /**
          * \brief Allocate memory of the given size
          *
          * This is used by the field when a memory portion of the same size as an already allocated
          * region (for example in clone() )
          */
         T * allocate ( uint_t allocSize )
         {
            T * mem = allocateMemory( allocSize );
            
            #ifdef WALBERLA_THREAD_SAFE_FIELD_ALLOCATION
            #ifdef _OPENMP
            #pragma omp critical( walberla_field_allocator_refcount )
            #endif
            #endif
            {
               WALBERLA_ASSERT( referenceCounts_.find(mem) == referenceCounts_.end() || referenceCounts_[mem] == 0 );
               referenceCounts_[mem] = 1;
            }
            return mem;
         }

         /**
          * \brief Increments the reference count for the given pointer
          *
          * \param allocatedPointer a pointer that was returned by the allocate function
          *
          * The reference counter is the number of field objects that currently use the allocated
          * memory region
          */
         void incrementReferenceCount( T * mem )
         {
            #ifdef WALBERLA_THREAD_SAFE_FIELD_ALLOCATION
            #ifdef _OPENMP
            #pragma omp critical( walberla_field_allocator_refcount )
            #endif
            #endif
            {
               WALBERLA_ASSERT( referenceCounts_.find(mem) != referenceCounts_.end() );
               WALBERLA_ASSERT_GREATER( referenceCounts_[mem], 0 );
               referenceCounts_[mem]++;
            }
         }


         /**
          * \brief Decrements the reference count for the given pointer
          *
          * \param allocatedPointer a pointer that was returned by the allocate function
          *
          * A memory region is freed only when the reference count is zero.
          * \return true if memory was freed,
          *         false if some other field still uses the memory
          */
         bool decrementReferenceCount( T * mem )
         {
            bool memoryFreed = false;
            
            uint_t refCount = 0;

            #ifdef WALBERLA_THREAD_SAFE_FIELD_ALLOCATION
            #ifdef _OPENMP
            #pragma omp critical( walberla_field_allocator_refcount )
            #endif
            #endif
            {
               WALBERLA_ASSERT( referenceCounts_.find(mem) != referenceCounts_.end() );
               WALBERLA_ASSERT_GREATER( referenceCounts_[mem], 0 );

               refCount = --referenceCounts_[mem];
            }

            if( refCount == 0 ) {
               deallocate( mem );
               memoryFreed = true;
            }
            
            return memoryFreed;
         }


         uint_t referenceCount ( T * mem ) const
         {
            uint_t refCount = 0;
            #ifdef WALBERLA_THREAD_SAFE_FIELD_ALLOCATION
            #ifdef _OPENMP
            #pragma omp critical( walberla_field_allocator_refcount )
            #endif
            #endif
            {
               WALBERLA_ASSERT( referenceCounts_.find(mem) != referenceCounts_.end()  );
               refCount = referenceCounts_[mem];
            }
            
            return refCount;
         }

      protected:
         /**
          * \brief Same as allocated, without handling of reference counter
          */
         virtual T * allocateMemory (  uint_t size0, uint_t size1, uint_t size2, uint_t size3,
                                       uint_t & allocSize1, uint_t & allocSize2, uint_t & allocSize3 ) = 0;


         /**
          * \brief Same as allocated, without handling of reference counter
          */
         virtual T * allocateMemory ( uint_t size ) = 0;

         /**
          * \brief Deallocates memory that has been allocated using allocate()
          *
          * \param values      Return value of allocate function()
          */
         virtual void deallocate( T *& values ) = 0;

      private:
         static std::map<T*, uint_t> referenceCounts_;

   };

   template<typename T>
   std::map<T*, uint_t> FieldAllocator<T>::referenceCounts_ = std::map<T*,uint_t>();



   /****************************************************************************************************************//**
   * Aligned Allocation strategy for Fields
   *
   * \ingroup field
   *
   * Template parameters:
   *  - T          type that is stored in field
   *  - alignment  the beginning of each row of the field is placed such that the memory
   *               address 'a' of each row fulfills: a % alignment == 0
   *               alignment has to be a power of 2
   ********************************************************************************************************************/
   template <typename T, uint_t alignment>
   class AllocateAligned : public FieldAllocator<T>
   {

      protected:

         virtual T * allocateMemory (  uint_t size0, uint_t size1, uint_t size2, uint_t size3,
                                       uint_t & allocSize1, uint_t & allocSize2, uint_t & allocSize3)
         {
            allocSize1=size1;
            allocSize2=size2;
            allocSize3=size3;
            uint_t lineLength = size3 * static_cast<uint_t>( sizeof(T) );
            if(lineLength % alignment !=0 )
               allocSize3 = ((lineLength + alignment) / alignment ) * (alignment / sizeof(T));

            WALBERLA_ASSERT_GREATER_EQUAL( allocSize3, size3 );
            WALBERLA_ASSERT_EQUAL( (allocSize3 * sizeof(T)) % alignment, 0 );

            return allocateMemory ( size0 * allocSize1 * allocSize2 * allocSize3 );
         }

         virtual T * allocateMemory (  uint_t size )
         {
            void * ptr = aligned_malloc_with_offset(size * sizeof(T), alignment, offset_ % alignment );
            if(!ptr)
               throw std::bad_alloc();

            // placement new
            new (ptr) T[ size ];

            T * ret = reinterpret_cast<T*>( ptr );

            #ifdef _OPENMP
            #pragma omp critical( walberla_field_aligned_allocator_nrOfElements )
            #endif
            {
               nrOfElements_[ret] = size;
            }
            return ret;
         }

         virtual void setInnerGhostLayerSize( uint_t innerGhostLayerSize ) {
            offset_ = sizeof(T) * innerGhostLayerSize;
         }

         virtual void deallocate(T *& values )
         {
            WALBERLA_ASSERT ( nrOfElements_.find(values) != nrOfElements_.end() );

            size_t nrOfValues = 0;

            #ifdef _OPENMP
            #pragma omp critical( walberla_field_aligned_allocator_nrOfElements )
            #endif
            {
               nrOfValues = nrOfElements_[values];
            }

            for( uint_t i = 0; i < nrOfValues; ++i )
               values[i].~T();

            #ifdef _OPENMP
            #pragma omp critical( walberla_field_aligned_allocator_nrOfElements )
            #endif
            {
               nrOfElements_.erase( values );
            }

            aligned_free(values);
         }

293
294
         static_assert(alignment > 0, "Use StdFieldAlloc");
         static_assert(!(alignment & (alignment - 1)) , "Alignment has to be power of 2");
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341

      private:
         /// Nr of elements per allocated pointer has to be stored to call the destructor on each element
         static std::map<T*, uint_t> nrOfElements_;

         uint_t offset_;
   };
   template <typename T, uint_t alignment>
   std::map<T*,uint_t> AllocateAligned<T,alignment>::nrOfElements_ = std::map<T*,uint_t>();



   /****************************************************************************************************************//**
   *  Allocator without alignment using new and delete[]
   *
   * \ingroup field
   *
   ********************************************************************************************************************/
   template <typename T>
   class StdFieldAlloc : public FieldAllocator<T>
   {
      public:
         virtual T * allocateMemory (  uint_t size0, uint_t size1, uint_t size2, uint_t size3,
                                       uint_t & allocSize1, uint_t & allocSize2, uint_t & allocSize3)
         {
            allocSize1=size1;
            allocSize2=size2;
            allocSize3=size3;
            return new T[size0*size1*size2*size3];
         }

         virtual T * allocateMemory ( uint_t size )
         {
            return new T[size];
         }

         virtual void deallocate(T *& values) {
            delete[] values;
            values = 0;
         }
   };


} // namespace field
} // namespace walberla