1ce36986474c6de258672ffa6e8e4af96e23b04a
[folly.git] / folly / experimental / io / HugePageUtil.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 <sys/mman.h>
18 #include <sys/types.h>
19 #include <sys/stat.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <unistd.h>
23
24 #include <iostream>
25 #include <stdexcept>
26 #include <system_error>
27
28 #include <gflags/gflags.h>
29
30 #include "folly/File.h"
31 #include "folly/Format.h"
32 #include "folly/MemoryMapping.h"
33 #include "folly/Portability.h"
34 #include "folly/Range.h"
35 #include "folly/ScopeGuard.h"
36 #include "folly/experimental/io/HugePages.h"
37
38 DEFINE_bool(cp, false, "Copy file");
39
40 using namespace folly;
41
42 namespace {
43
44 FOLLY_NORETURN void usage(const char* name);
45
46 void usage(const char* name) {
47   std::cerr << folly::format(
48       "Usage: {0}\n"
49       "         list all huge page sizes and their mount points\n"
50       "       {0} -cp <src_file> <dest_nameprefix>\n"
51       "         copy src_file to a huge page file\n",
52       name);
53   exit(1);
54 }
55
56 void copy(const char* srcFile, const char* dest) {
57   fs::path destPath(dest);
58   if (!destPath.is_absolute()) {
59     auto hp = getHugePageSize();
60     CHECK(hp) << "no huge pages available";
61     destPath = fs::canonical_parent(destPath, hp->mountPoint);
62   }
63
64   mmapFileCopy(srcFile, destPath.c_str());
65 }
66
67 void list() {
68   for (const auto& p : getHugePageSizes()) {
69     std::cout << p.size << " " << p.mountPoint << "\n";
70   }
71 }
72
73 }  // namespace
74
75
76 int main(int argc, char *argv[]) {
77   google::ParseCommandLineFlags(&argc, &argv, true);
78   if (FLAGS_cp) {
79     if (argc != 3) usage(argv[0]);
80     copy(argv[1], argv[2]);
81   } else {
82     if (argc != 1) usage(argv[0]);
83     list();
84   }
85   return 0;
86 }
87