aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/core/common_runtime/scoped_allocator.cc
blob: a26672b79dab87d66ac98a8436cc7e2df7473677 (plain)
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
51
52
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
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

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

    http://www.apache.org/licenses/LICENSE-2.0

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.
==============================================================================*/
#include "tensorflow/core/common_runtime/scoped_allocator.h"
#include "tensorflow/core/common_runtime/scoped_allocator_mgr.h"

namespace tensorflow {

ScopedAllocator::ScopedAllocator(const Tensor& backing_tensor, int32 scope_id,
                                 const string& name,
                                 const gtl::ArraySlice<Field>& fields,
                                 int32 expected_call_count,
                                 ScopedAllocatorContainer* container)
    : backing_tensor_(backing_tensor),
      tbuf_(backing_tensor_.buf_),
      id_(scope_id),
      name_(name),
      container_(container),
      fields_(fields.begin(), fields.end()),
      expected_call_count_(expected_call_count),
      live_alloc_count_(0) {
  // Hold this until all aliases have been deallocated.
  tbuf_->Ref();
  // Hold this until all expected_calls have been made.
  container->Ref();
  CHECK_GE(tbuf_->size(), fields.back().offset + fields.back().bytes);
}

ScopedAllocator::~ScopedAllocator() {
  mutex_lock l(mu_);
  VLOG(1) << "~ScopedAllocator " << this << " tbuf_ " << tbuf_ << " data "
          << static_cast<void*>(tbuf_->data());
  // In the absence of incomplete graph execution situations
  // (interruption by error status or control flow branch crossing
  // ScopedAllocation region) we expect expected_call_count_ == 0 at
  // exit.
  if (VLOG_IS_ON(1)) {
    if (expected_call_count_ > 0)
      VLOG(1) << "expected_call_count_ = " << expected_call_count_
              << " at deallocation";
  }
  if (tbuf_) tbuf_->Unref();
}

void* ScopedAllocator::AllocateRaw(int32 field_index, size_t num_bytes) {
  VLOG(1) << "ScopedAllocator index " << id_ << " AllocateRaw "
          << "field " << field_index << " num_bytes " << num_bytes;
  mutex_lock l(mu_);
  if (expected_call_count_ <= 0) {
    LOG(ERROR) << "Scoped allocator " << name_
               << " could not satisfy request for " << num_bytes
               << " bytes, expected uses exhausted. ";
    return nullptr;
  }

  int32_t num_fields = static_cast<int32>(fields_.size());
  if (field_index >= num_fields) {
    LOG(ERROR) << "ScopedAllocator " << name_
               << " received unexpected field number " << field_index;
    return nullptr;
  }

  const Field& f = fields_[field_index];
  if (num_bytes != f.bytes) {
    LOG(ERROR) << "ScopedAllocator " << name_ << " got request for "
               << num_bytes << " bytes from field " << field_index
               << " which has precalculated size " << f.bytes << " and offset "
               << f.offset;
    return nullptr;
  }

  void* ptr = static_cast<void*>((tbuf_->template base<char>() + f.offset));

  ++live_alloc_count_;
  --expected_call_count_;
  if (0 == expected_call_count_) {
    for (auto& f : fields_) {
      container_->Drop(f.scope_id, this);
    }
    container_->Drop(id_, this);
    container_->Unref();
    container_ = nullptr;
  }
  VLOG(1) << "AllocateRaw returning " << ptr;
  return ptr;
}

void ScopedAllocator::DeallocateRaw(void* p) {
  CHECK(VerifyPointer(p));

  bool dead = false;
  {
    mutex_lock l(mu_);
    CHECK_GT(live_alloc_count_, 0);
    if (0 == --live_alloc_count_) {
      if (0 == expected_call_count_) {
        dead = true;
      }
    }
  }
  if (dead) {
    delete this;
  }
}

bool ScopedAllocator::VerifyPointer(const void* p) {
  void* base = tbuf_->data();
  CHECK_GE(p, base);
  for (auto& f : fields_) {
    void* f_ptr = static_cast<void*>(static_cast<char*>(base) + f.offset);
    if (f_ptr == p) {
      return true;
      break;
    }
  }
  VLOG(1) << "ScopedAllocator index " << id_ << " VerifyPointer for p=" << p
          << " failed.";
  return false;
}

bool ScopedAllocator::VerifyTensor(const Tensor* t) {
  return VerifyPointer(t->buf_->data());
}

ScopedAllocatorInstance::ScopedAllocatorInstance(ScopedAllocator* sa,
                                                 int32 field_index)
    : scoped_allocator_(sa),
      field_index_(field_index),
      allocated_(false),
      deallocated_(false),
      in_table_(true) {
  VLOG(1) << "new ScopedAllocatorInstance " << this << " on SA " << sa
          << " field_index " << field_index;
}

void ScopedAllocatorInstance::DropFromTable() {
  bool del = false;
  {
    mutex_lock l(mu_);
    CHECK(in_table_);
    in_table_ = false;
    VLOG(2) << "ScopedAllocatorInstance::DropFromTable " << this
            << " allocated_ " << allocated_ << " deallocated_ " << deallocated_
            << " in_table_ " << in_table_;
    // Single use is complete when it is allocated and deallocated.
    // This check prevents a race between Allocating the tensor slice and
    // Dropping it from the parent container's table.
    if (allocated_ && deallocated_) {
      del = true;
    }
  }
  if (del) delete this;
}

void* ScopedAllocatorInstance::AllocateRaw(size_t alignment, size_t num_bytes) {
  void* ptr = scoped_allocator_->AllocateRaw(field_index_, num_bytes);
  {
    mutex_lock l(mu_);
    if (nullptr == ptr) {
      VLOG(2) << "ScopedAllocatorInstance::AllocateRaw " << this
              << " call to underlying ScopedAllocator unsuccessful,"
              << " allocated_ " << allocated_ << " deallocated_ "
              << deallocated_ << " in_table_ " << in_table_
              << " returning nullptr.";
    } else {
      allocated_ = true;
      VLOG(2) << "ScopedAllocatorInstance::AllocateRaw " << this
              << " allocated_ " << allocated_ << " deallocated_ "
              << deallocated_ << " in_table_ " << in_table_
              << " returning ptr = " << ptr;
    }
  }
  return ptr;
}

void ScopedAllocatorInstance::DeallocateRaw(void* p) {
  scoped_allocator_->DeallocateRaw(p);
  bool del = false;
  {
    mutex_lock l(mu_);
    CHECK(allocated_);
    deallocated_ = true;
    VLOG(2) << "ScopedAllocatorInstance::DeallocateRaw " << this
            << " allocated_ " << allocated_ << " deallocated_ " << deallocated_
            << " in_table_ " << in_table_;
    // Single use is now complete, but only delete this instance when it is
    // no longer in a ScopedAllocatorContainer's table.
    if (!in_table_) {
      del = true;
    }
  }
  if (del) delete this;
}

string ScopedAllocatorInstance::Name() {
  return strings::StrCat(scoped_allocator_->name(), "_field_", field_index_);
}

}  // namespace tensorflow