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 #include <fcntl.h>
17 #include <stddef.h>
18 #include <sys/mman.h>
19 #include <sys/stat.h>
20 #include <unistd.h>
21
22 #include "tensorflow/lite/allocation.h"
23 #include "tensorflow/lite/core/api/error_reporter.h"
24
25 namespace tflite {
26
MMAPAllocation(const char * filename,ErrorReporter * error_reporter)27 MMAPAllocation::MMAPAllocation(const char* filename,
28 ErrorReporter* error_reporter)
29 : Allocation(error_reporter, Allocation::Type::kMMap),
30 mmapped_buffer_(MAP_FAILED) {
31 mmap_fd_ = open(filename, O_RDONLY);
32 if (mmap_fd_ == -1) {
33 error_reporter_->Report("Could not open '%s'.", filename);
34 return;
35 }
36 struct stat sb;
37 fstat(mmap_fd_, &sb);
38 buffer_size_bytes_ = sb.st_size;
39 mmapped_buffer_ =
40 mmap(nullptr, buffer_size_bytes_, PROT_READ, MAP_SHARED, mmap_fd_, 0);
41 if (mmapped_buffer_ == MAP_FAILED) {
42 error_reporter_->Report("Mmap of '%s' failed.", filename);
43 return;
44 }
45 }
46
~MMAPAllocation()47 MMAPAllocation::~MMAPAllocation() {
48 if (valid()) {
49 munmap(const_cast<void*>(mmapped_buffer_), buffer_size_bytes_);
50 }
51 if (mmap_fd_ != -1) close(mmap_fd_);
52 }
53
base() const54 const void* MMAPAllocation::base() const { return mmapped_buffer_; }
55
bytes() const56 size_t MMAPAllocation::bytes() const { return buffer_size_bytes_; }
57
valid() const58 bool MMAPAllocation::valid() const { return mmapped_buffer_ != MAP_FAILED; }
59
IsSupported()60 bool MMAPAllocation::IsSupported() { return true; }
61
62 } // namespace tflite
63