buddy_allocator.h 2.3 KB
Newer Older
L
liaogang 已提交
1 2
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

3 4 5
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at
L
liaogang 已提交
6

7
   http://www.apache.org/licenses/LICENSE-2.0
L
liaogang 已提交
8

9 10 11 12 13
   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. */
L
liaogang 已提交
14 15 16 17 18

#pragma once

#include "paddle/memory/detail/system_allocator.h"

L
liaogang 已提交
19
#include <mutex>
L
liaogang 已提交
20
#include <vector>
L
liaogang 已提交
21

L
liaogang 已提交
22 23 24 25 26
namespace paddle {
namespace memory {
namespace detail {

class BuddyAllocator {
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
 public:
  BuddyAllocator(size_t pool_size, size_t max_pools,
                 SystemAllocator* system_allocator);
  ~BuddyAllocator();

  void* Alloc(size_t size);
  void Free(void*);
  size_t Used();

 private:
  struct Block {
    size_t size_;
    Block* left_;   // left buddy
    Block* right_;  // right buddy
  };

  // Initially, there is only one pool.  If a Alloc founds not enough
  // memory from that pool, and there has not been max_num_pools_,
  // create a new pool by calling system_allocator_.Alloc(pool_size_).
  std::vector<void*> pools_;

  size_t pool_size_;      // the size of each pool;
  size_t max_num_pools_;  // the size of all pools;
L
liaogang 已提交
50

51
  SystemAllocator* system_allocator_;
L
liaogang 已提交
52

53
  std::mutex mutex_;
L
liaogang 已提交
54

55 56 57
  // Disable copy and assignment.
  BuddyAllocator(const BuddyAllocator&) = delete;
  BuddyAllocator& operator=(const BuddyAllocator&) = delete;
L
liaogang 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
};

BuddyAllocator<CPUAllocator>* GetCPUBuddyAllocator() {
  static BuddyAllocator<CPUAllocator>* a = nullptr;
  if (a == nullptr) {
    a = new BuddyAllocator<CPUAllocator>();
  }
  return a;
}

#ifndef PADDLE_ONLY_CPU  // The following code are for CUDA.

BuddyAllocator<GPUAllocator>* GetGPUBuddyAllocator(int gpu_id) {
  static BuddyAllocator<GPUAllocator>** as = NULL;
  if (as == NULL) {
73
    int gpu_num = platform::GetDeviceCount();
L
liaogang 已提交
74 75
    as = new BuddyAllocator<GPUAllocator>*[gpu_num];
    for (int gpu = 0; gpu < gpu_num; gpu++) {
76
      as[gpu] = new BuddyAllocator<GPUAllocator>();
L
liaogang 已提交
77 78 79 80 81
    }
  }
  return as[gpu_id];
}

82
#endif  // PADDLE_ONLY_CPU
L
liaogang 已提交
83 84 85 86

}  // namespace detail
}  // namespace memory
}  // namespace paddle