Use membarrier in TLRefCount
[folly.git] / folly / experimental / AsymmetricMemoryBarrier.cpp
1 /*
2  * Copyright 2016 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 "AsymmetricMemoryBarrier.h"
18
19 #include <folly/Exception.h>
20 #include <folly/Indestructible.h>
21 #include <folly/portability/SysMembarrier.h>
22 #include <folly/portability/SysMman.h>
23 #include <mutex>
24
25 namespace folly {
26
27 namespace {
28
29 struct DummyPageCreator {
30   DummyPageCreator() {
31     get();
32   }
33
34   static void* get() {
35     static auto ptr =
36         kIsLinux && !detail::sysMembarrierAvailable() ? create() : nullptr;
37     return ptr;
38   }
39
40  private:
41   static void* create() {
42     auto ptr = mmap(nullptr, 1, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
43     checkUnixError(reinterpret_cast<uintptr_t>(ptr), "mmap");
44
45     // Lock the memory so it can't get paged out. If it gets paged out, changing
46     // its protection won't accomplish anything.
47     auto r = mlock(ptr, 1);
48     checkUnixError(r, "mlock");
49
50     return ptr;
51   }
52 };
53
54 // Make sure dummy page is always initialized before shutdown
55 DummyPageCreator dummyPageCreator;
56
57 void mprotectMembarrier() {
58   auto dummyPage = dummyPageCreator.get();
59
60   // This function is required to be safe to call on shutdown,
61   // so we must leak the mutex.
62   static Indestructible<std::mutex> mprotectMutex;
63   std::lock_guard<std::mutex> lg(*mprotectMutex);
64
65   int r = 0;
66   r = mprotect(dummyPage, 1, PROT_READ | PROT_WRITE);
67   checkUnixError(r, "mprotect");
68
69   r = mprotect(dummyPage, 1, PROT_READ);
70   checkUnixError(r, "mprotect");
71 }
72 }
73
74 void asymmetricHeavyBarrier() {
75   if (kIsLinux) {
76     static const bool useSysMembarrier = detail::sysMembarrierAvailable();
77     if (useSysMembarrier) {
78       auto r = detail::sysMembarrier();
79       checkUnixError(r, "membarrier");
80     } else {
81       mprotectMembarrier();
82     }
83   } else {
84     std::atomic_thread_fence(std::memory_order_seq_cst);
85   }
86 }
87 }