1 //  Copyright (c) 2011-present, Facebook, Inc.  All rights reserved.
2 //  This source code is licensed under both the GPLv2 (found in the
3 //  COPYING file in the root directory) and Apache 2.0 License
4 //  (found in the LICENSE.Apache file in the root directory).
5 //
6 // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
7 // Use of this source code is governed by a BSD-style license that can be
8 // found in the LICENSE file. See the AUTHORS file for names of contributors.
9 //
10 // Abstract interface for allocating memory in blocks. This memory is freed
11 // when the allocator object is destroyed. See the Arena class for more info.
12 
13 #pragma once
14 #include <cerrno>
15 #include <cstddef>
16 #include "rocksdb/write_buffer_manager.h"
17 
18 namespace ROCKSDB_NAMESPACE {
19 
20 class Logger;
21 
22 class Allocator {
23  public:
~Allocator()24   virtual ~Allocator() {}
25 
26   virtual char* Allocate(size_t bytes) = 0;
27   virtual char* AllocateAligned(size_t bytes, size_t huge_page_size = 0,
28                                 Logger* logger = nullptr) = 0;
29 
30   virtual size_t BlockSize() const = 0;
31 };
32 
33 class AllocTracker {
34  public:
35   explicit AllocTracker(WriteBufferManager* write_buffer_manager);
36   // No copying allowed
37   AllocTracker(const AllocTracker&) = delete;
38   void operator=(const AllocTracker&) = delete;
39 
40   ~AllocTracker();
41   void Allocate(size_t bytes);
42   // Call when we're finished allocating memory so we can free it from
43   // the write buffer's limit.
44   void DoneAllocating();
45 
46   void FreeMem();
47 
is_freed()48   bool is_freed() const { return write_buffer_manager_ == nullptr || freed_; }
49 
50  private:
51   WriteBufferManager* write_buffer_manager_;
52   std::atomic<size_t> bytes_allocated_;
53   bool done_allocating_;
54   bool freed_;
55 };
56 
57 }  // namespace ROCKSDB_NAMESPACE
58