MemoryMapping changes: automatically detect huge pages, no more WritableMemoryMapping
[folly.git] / folly / experimental / io / HugePages.cpp
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "folly/experimental/io/HugePages.h"
18
19 #include <sys/stat.h>
20 #include <sys/types.h>
21 #include <fcntl.h>
22
23 #include <cctype>
24 #include <cstring>
25
26 #include <algorithm>
27 #include <stdexcept>
28 #include <system_error>
29
30 #include <boost/noncopyable.hpp>
31 #include <boost/regex.hpp>
32
33 #include <glog/logging.h>
34
35 #include "folly/Conv.h"
36 #include "folly/Format.h"
37 #include "folly/Range.h"
38 #include "folly/ScopeGuard.h"
39 #include "folly/String.h"
40
41 #include "folly/gen/Base.h"
42 #include "folly/gen/File.h"
43 #include "folly/gen/String.h"
44
45 namespace folly {
46
47 namespace {
48
49 // Get the default huge page size
50 size_t getDefaultHugePageSize() {
51   // We need to parse /proc/meminfo
52   static const boost::regex regex(R"!(Hugepagesize:\s*(\d+)\s*kB)!");
53   size_t pageSize = 0;
54   boost::cmatch match;
55
56   bool error = gen::byLine("/proc/meminfo") |
57     [&] (StringPiece line) -> bool {
58       if (boost::regex_match(line.begin(), line.end(), match, regex)) {
59         StringPiece numStr(line.begin() + match.position(1), match.length(1));
60         pageSize = to<size_t>(numStr) * 1024;  // in KiB
61         return false;  // stop
62       }
63       return true;
64     };
65
66   if (error) {
67     throw std::runtime_error("Can't find default huge page size");
68   }
69   return pageSize;
70 }
71
72 // Get raw huge page sizes (without mount points, they'll be filled later)
73 HugePageSizeVec readRawHugePageSizes() {
74   // We need to parse file names from /sys/kernel/mm/hugepages
75   static const boost::regex regex(R"!(hugepages-(\d+)kB)!");
76   boost::smatch match;
77   HugePageSizeVec vec;
78   fs::path path("/sys/kernel/mm/hugepages");
79   for (fs::directory_iterator it(path); it != fs::directory_iterator(); ++it) {
80     std::string filename(it->path().filename().native());
81     if (boost::regex_match(filename, match, regex)) {
82       StringPiece numStr(filename.data() + match.position(1), match.length(1));
83       vec.emplace_back(to<size_t>(numStr) * 1024);
84     }
85   }
86   return vec;
87 }
88
89 // Parse the value of a pagesize mount option
90 // Format: number, optional K/M/G/T suffix, trailing junk allowed
91 size_t parsePageSizeValue(StringPiece value) {
92   static const boost::regex regex(R"!((\d+)([kmgt])?.*)!", boost::regex::icase);
93   boost::cmatch match;
94   if (!boost::regex_match(value.begin(), value.end(), match, regex)) {
95     throw std::runtime_error("Invalid pagesize option");
96   }
97   char c = '\0';
98   if (match.length(2) != 0) {
99     c = tolower(value[match.position(2)]);
100   }
101   StringPiece numStr(value.data() + match.position(1), match.length(1));
102   size_t size = to<size_t>(numStr);
103   switch (c) {
104   case 't': size *= 1024;
105   case 'g': size *= 1024;
106   case 'm': size *= 1024;
107   case 'k': size *= 1024;
108   }
109   return size;
110 }
111
112 /**
113  * Get list of supported huge page sizes and their mount points, if
114  * hugetlbfs file systems are mounted for those sizes.
115  */
116 HugePageSizeVec readHugePageSizes() {
117   HugePageSizeVec sizeVec = readRawHugePageSizes();
118   if (sizeVec.empty()) {
119     return sizeVec;  // nothing to do
120   }
121   std::sort(sizeVec.begin(), sizeVec.end());
122
123   size_t defaultHugePageSize = getDefaultHugePageSize();
124
125   struct PageSizeLess {
126     bool operator()(const HugePageSize& a, size_t b) const {
127       return a.size < b;
128     }
129     bool operator()(size_t a, const HugePageSize& b) const {
130       return a < b.size;
131     }
132   };
133
134   // Read and parse /proc/mounts
135   std::vector<StringPiece> parts;
136   std::vector<StringPiece> options;
137
138   gen::byLine("/proc/mounts") | gen::eachAs<StringPiece>() |
139     [&](StringPiece line) {
140       parts.clear();
141       split(" ", line, parts);
142       // device path fstype options uid gid
143       if (parts.size() != 6) {
144         throw std::runtime_error("Invalid /proc/mounts line");
145       }
146       if (parts[2] != "hugetlbfs") {
147         return;  // we only care about hugetlbfs
148       }
149
150       options.clear();
151       split(",", parts[3], options);
152       size_t pageSize = defaultHugePageSize;
153       // Search for the "pagesize" option, which must have a value
154       for (auto& option : options) {
155         // key=value
156         const char* p = static_cast<const char*>(
157             memchr(option.data(), '=', option.size()));
158         if (!p) {
159           continue;
160         }
161         if (StringPiece(option.data(), p) != "pagesize") {
162           continue;
163         }
164         pageSize = parsePageSizeValue(StringPiece(p + 1, option.end()));
165         break;
166       }
167
168       auto pos = std::lower_bound(sizeVec.begin(), sizeVec.end(), pageSize,
169                                   PageSizeLess());
170       if (pos == sizeVec.end() || pos->size != pageSize) {
171         throw std::runtime_error("Mount page size not found");
172       }
173       if (pos->mountPoint.empty()) {
174         // Store mount point
175         pos->mountPoint = fs::canonical(fs::path(parts[1].begin(),
176                                                  parts[1].end()));
177
178         struct stat st;
179         checkUnixError(stat(pos->mountPoint.c_str(), &st),
180                        "stat hugepage mountpoint failed");
181         pos->device = st.st_dev;
182       }
183     };
184
185   return sizeVec;
186 }
187
188 }  // namespace
189
190 const HugePageSizeVec& getHugePageSizes() {
191   static HugePageSizeVec sizes = readHugePageSizes();
192   return sizes;
193 }
194
195 const HugePageSize* getHugePageSize(size_t size) {
196   // Linear search is just fine.
197   for (auto& p : getHugePageSizes()) {
198     if (p.mountPoint.empty()) {
199       continue;
200     }
201     if (size == 0 || size == p.size) {
202       return &p;
203     }
204   }
205   return nullptr;
206 }
207
208 const HugePageSize* getHugePageSizeForDevice(dev_t device) {
209   // Linear search is just fine.
210   for (auto& p : getHugePageSizes()) {
211     if (p.mountPoint.empty()) {
212       continue;
213     }
214     if (device == p.device) {
215       return &p;
216     }
217   }
218   return nullptr;
219 }
220
221 }  // namespace folly