1 /* Copyright 2018 The TensorFlow Authors. All Rights Reserved. 2 3 Licensed under the Apache License, Version 2.0 (the "License"); 4 you may not use this file except in compliance with the License. 5 You may obtain a copy of the License at 6 7 http://www.apache.org/licenses/LICENSE-2.0 8 9 Unless required by applicable law or agreed to in writing, software 10 distributed under the License is distributed on an "AS IS" BASIS, 11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 See the License for the specific language governing permissions and 13 limitations under the License. 14 ==============================================================================*/ 15 16 #ifndef TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_HOST_ALLOCATOR_H_ 17 #define TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_HOST_ALLOCATOR_H_ 18 19 #include "tensorflow/core/framework/allocator.h" 20 #include "tensorflow/core/platform/macros.h" 21 #include "tensorflow/core/platform/stream_executor.h" 22 23 namespace tensorflow { 24 // Allocator for pinned CPU RAM that is made known to GPU for the 25 // purpose of efficient DMA with a GPU. 26 class GpuHostAllocator : public SubAllocator { 27 public: 28 // Note: stream_exec cannot be null. GpuHostAllocator(se::StreamExecutor * stream_exec,int numa_node,const std::vector<Visitor> & alloc_visitors,const std::vector<Visitor> & free_visitors)29 explicit GpuHostAllocator(se::StreamExecutor* stream_exec, int numa_node, 30 const std::vector<Visitor>& alloc_visitors, 31 const std::vector<Visitor>& free_visitors) 32 : SubAllocator(alloc_visitors, free_visitors), 33 stream_exec_(stream_exec), 34 numa_node_(numa_node) { 35 CHECK(stream_exec_ != nullptr); 36 } ~GpuHostAllocator()37 ~GpuHostAllocator() override {} 38 Alloc(size_t alignment,size_t num_bytes)39 void* Alloc(size_t alignment, size_t num_bytes) override { 40 void* ptr = nullptr; 41 if (num_bytes > 0) { 42 ptr = stream_exec_->HostMemoryAllocate(num_bytes); 43 if (ptr == nullptr) { 44 LOG(WARNING) << "could not allocate pinned host memory of size: " 45 << num_bytes; 46 return ptr; 47 } 48 VisitAlloc(ptr, numa_node_, num_bytes); 49 } 50 return ptr; 51 } 52 Free(void * ptr,size_t num_bytes)53 void Free(void* ptr, size_t num_bytes) override { 54 if (ptr != nullptr) { 55 VisitFree(ptr, numa_node_, num_bytes); 56 stream_exec_->HostMemoryDeallocate(ptr); 57 } 58 } 59 60 private: 61 se::StreamExecutor* stream_exec_; // not owned, non-null 62 const int numa_node_; 63 64 TF_DISALLOW_COPY_AND_ASSIGN(GpuHostAllocator); 65 }; 66 67 } // namespace tensorflow 68 #endif // TENSORFLOW_CORE_COMMON_RUNTIME_GPU_GPU_HOST_ALLOCATOR_H_ 69