blob: cd9ea436e347527f2b67fc500e451f76cde5a36c [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#include "aos/realtime.h"
2
Austin Schuhcc6070c2020-10-10 20:25:56 -07003#include <malloc.h>
4#include <sched.h>
Alex Perrycb7da4b2019-08-28 19:35:56 -07005#include <sys/mman.h>
Austin Schuhcc6070c2020-10-10 20:25:56 -07006#include <sys/prctl.h>
Alex Perrycb7da4b2019-08-28 19:35:56 -07007#include <sys/resource.h>
8#include <sys/types.h>
9#include <unistd.h>
Alex Perrycb7da4b2019-08-28 19:35:56 -070010
Tyler Chatowbf0609c2021-07-31 16:13:27 -070011#include <cerrno>
12#include <cstdint>
13#include <cstdio>
14#include <cstdlib>
15#include <cstring>
16
Austin Schuhcc6070c2020-10-10 20:25:56 -070017#include "aos/thread_local.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070018#include "glog/logging.h"
Austin Schuh62288252020-11-18 23:26:04 -080019#include "glog/raw_logging.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070020
Austin Schuh62288252020-11-18 23:26:04 -080021DEFINE_bool(
22 die_on_malloc, false,
23 "If true, die when the application allocates memory in a RT section.");
Austin Schuh27553152020-11-18 21:26:37 -080024DEFINE_bool(skip_realtime_scheduler, false,
25 "If true, skip changing the scheduler. Pretend that we changed "
26 "the scheduler instead.");
27DEFINE_bool(skip_locking_memory, false,
28 "If true, skip locking memory. Pretend that we did it instead.");
29
Austin Schuh62288252020-11-18 23:26:04 -080030extern "C" {
Tyler Chatowbf0609c2021-07-31 16:13:27 -070031typedef void (*MallocHook_NewHook)(const void *ptr, size_t size);
Austin Schuh62288252020-11-18 23:26:04 -080032int MallocHook_AddNewHook(MallocHook_NewHook hook) __attribute__((weak));
33int MallocHook_RemoveNewHook(MallocHook_NewHook hook) __attribute__((weak));
34
Tyler Chatowbf0609c2021-07-31 16:13:27 -070035typedef void (*MallocHook_DeleteHook)(const void *ptr);
Austin Schuh62288252020-11-18 23:26:04 -080036int MallocHook_AddDeleteHook(MallocHook_DeleteHook hook) __attribute__((weak));
Tyler Chatowbf0609c2021-07-31 16:13:27 -070037int MallocHook_RemoveDeleteHook(MallocHook_DeleteHook hook)
38 __attribute__((weak));
39} // extern "C"
Austin Schuh62288252020-11-18 23:26:04 -080040
Alex Perrycb7da4b2019-08-28 19:35:56 -070041namespace FLAG__namespace_do_not_use_directly_use_DECLARE_double_instead {
42extern double FLAGS_tcmalloc_release_rate __attribute__((weak));
43}
44using FLAG__namespace_do_not_use_directly_use_DECLARE_double_instead::
45 FLAGS_tcmalloc_release_rate;
46
47namespace aos {
48namespace logging {
49namespace internal {
50
51// Implemented in aos/logging/context.cc.
52void ReloadThreadName() __attribute__((weak));
53
54} // namespace internal
55} // namespace logging
56
57namespace {
58
Austin Schuh27553152020-11-18 21:26:37 -080059enum class SetLimitForRoot { kYes, kNo };
James Kuszmaulb4874eb2020-01-18 17:50:35 -080060
Austin Schuh27553152020-11-18 21:26:37 -080061enum class AllowSoftLimitDecrease { kYes, kNo };
James Kuszmaulb4874eb2020-01-18 17:50:35 -080062
63void SetSoftRLimit(
64 int resource, rlim64_t soft, SetLimitForRoot set_for_root,
Austin Schuh27553152020-11-18 21:26:37 -080065 std::string_view help_string,
James Kuszmaulb4874eb2020-01-18 17:50:35 -080066 AllowSoftLimitDecrease allow_decrease = AllowSoftLimitDecrease::kYes) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070067 bool am_root = getuid() == 0;
James Kuszmaulb4874eb2020-01-18 17:50:35 -080068 if (set_for_root == SetLimitForRoot::kYes || !am_root) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070069 struct rlimit64 rlim;
70 PCHECK(getrlimit64(resource, &rlim) == 0)
Brian Silverman6a54ff32020-04-28 16:41:39 -070071 << ": getting limit for " << resource;
Alex Perrycb7da4b2019-08-28 19:35:56 -070072
James Kuszmaulb4874eb2020-01-18 17:50:35 -080073 if (allow_decrease == AllowSoftLimitDecrease::kYes) {
74 rlim.rlim_cur = soft;
75 } else {
76 rlim.rlim_cur = std::max(rlim.rlim_cur, soft);
77 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070078 rlim.rlim_max = ::std::max(rlim.rlim_max, soft);
79
80 PCHECK(setrlimit64(resource, &rlim) == 0)
Brian Silverman6a54ff32020-04-28 16:41:39 -070081 << ": changing limit for " << resource << " to " << rlim.rlim_cur
Austin Schuh27553152020-11-18 21:26:37 -080082 << " with max of " << rlim.rlim_max << help_string;
Alex Perrycb7da4b2019-08-28 19:35:56 -070083 }
84}
85
86} // namespace
87
88void LockAllMemory() {
Austin Schuhcc6070c2020-10-10 20:25:56 -070089 CheckNotRealtime();
Alex Perrycb7da4b2019-08-28 19:35:56 -070090 // Allow locking as much as we want into RAM.
Austin Schuh27553152020-11-18 21:26:37 -080091 SetSoftRLimit(RLIMIT_MEMLOCK, RLIM_INFINITY, SetLimitForRoot::kNo,
92 "use --skip_locking_memory to not lock memory.");
Alex Perrycb7da4b2019-08-28 19:35:56 -070093
94 WriteCoreDumps();
Austin Schuh27553152020-11-18 21:26:37 -080095 PCHECK(mlockall(MCL_CURRENT | MCL_FUTURE) == 0)
96 << ": Failed to lock memory, use --skip_locking_memory to bypass this. "
97 "Bypassing will impact RT performance.";
Alex Perrycb7da4b2019-08-28 19:35:56 -070098
Brian Silverman4dbbcce2020-09-18 15:27:38 -070099#if !__has_feature(address_sanitizer) && !__has_feature(memory_sanitizer)
Alex Perrycb7da4b2019-08-28 19:35:56 -0700100 // Don't give freed memory back to the OS.
101 CHECK_EQ(1, mallopt(M_TRIM_THRESHOLD, -1));
102 // Don't use mmap for large malloc chunks.
103 CHECK_EQ(1, mallopt(M_MMAP_MAX, 0));
Austin Schuh85faf672020-09-10 22:58:46 -0700104#endif
Alex Perrycb7da4b2019-08-28 19:35:56 -0700105
106 if (&FLAGS_tcmalloc_release_rate) {
107 // Tell tcmalloc not to return memory.
108 FLAGS_tcmalloc_release_rate = 0.0;
109 }
110
111 // Forces the memory pages for all the stack space that we're ever going to
112 // use to be loaded into memory (so it can be locked there).
113 uint8_t data[4096 * 8];
114 // Not 0 because linux might optimize that to a 0-filled page.
115 memset(data, 1, sizeof(data));
Austin Schuh27553152020-11-18 21:26:37 -0800116 __asm__ __volatile__("" ::"m"(data));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700117
118 static const size_t kHeapPreallocSize = 512 * 1024;
119 char *const heap_data = static_cast<char *>(malloc(kHeapPreallocSize));
120 memset(heap_data, 1, kHeapPreallocSize);
Austin Schuh27553152020-11-18 21:26:37 -0800121 __asm__ __volatile__("" ::"m"(heap_data));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700122 free(heap_data);
123}
124
125void InitRT() {
Austin Schuh27553152020-11-18 21:26:37 -0800126 if (FLAGS_skip_locking_memory) {
127 LOG(WARNING) << "Ignoring request to lock all memory due to "
128 "--skip_locking_memory.";
129 return;
130 }
131
Austin Schuhcc6070c2020-10-10 20:25:56 -0700132 CheckNotRealtime();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700133 LockAllMemory();
134
Austin Schuh27553152020-11-18 21:26:37 -0800135 if (FLAGS_skip_realtime_scheduler) {
136 return;
137 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700138 // Only let rt processes run for 3 seconds straight.
Austin Schuh27553152020-11-18 21:26:37 -0800139 SetSoftRLimit(
140 RLIMIT_RTTIME, 3000000, SetLimitForRoot::kYes,
141 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
142 "warning.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700143
144 // Allow rt processes up to priority 40.
Austin Schuh27553152020-11-18 21:26:37 -0800145 SetSoftRLimit(
146 RLIMIT_RTPRIO, 40, SetLimitForRoot::kNo,
147 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
148 "warning.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700149}
150
151void UnsetCurrentThreadRealtimePriority() {
152 struct sched_param param;
153 param.sched_priority = 0;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700154 PCHECK(sched_setscheduler(0, SCHED_OTHER, &param) == 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -0700155 MarkRealtime(false);
Brian Silverman6a54ff32020-04-28 16:41:39 -0700156}
157
158void SetCurrentThreadAffinity(const cpu_set_t &cpuset) {
159 PCHECK(sched_setaffinity(0, sizeof(cpuset), &cpuset) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700160}
161
James Kuszmaul57c2baa2020-01-19 14:52:52 -0800162void SetCurrentThreadName(const std::string_view name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700163 CHECK_LE(name.size(), 16u) << ": thread name '" << name << "' too long";
164 VLOG(1) << "This thread is changing to '" << name << "'";
James Kuszmaul57c2baa2020-01-19 14:52:52 -0800165 std::string string_name(name);
Brian Silverman6a54ff32020-04-28 16:41:39 -0700166 PCHECK(prctl(PR_SET_NAME, string_name.c_str()) == 0)
167 << ": changing name to " << string_name;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700168 if (&logging::internal::ReloadThreadName != nullptr) {
169 logging::internal::ReloadThreadName();
170 }
171}
172
173void SetCurrentThreadRealtimePriority(int priority) {
Austin Schuh27553152020-11-18 21:26:37 -0800174 if (FLAGS_skip_realtime_scheduler) {
175 LOG(WARNING) << "Ignoring request to switch to the RT scheduler due to "
176 "--skip_realtime_scheduler.";
177 return;
178 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700179 // Make sure we will only be allowed to run for 3 seconds straight.
Austin Schuh27553152020-11-18 21:26:37 -0800180 SetSoftRLimit(
181 RLIMIT_RTTIME, 3000000, SetLimitForRoot::kYes,
182 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
183 "warning.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700184
Brian Silvermanb3826f52020-07-02 19:41:18 -0700185 // Raise our soft rlimit if necessary.
Austin Schuh27553152020-11-18 21:26:37 -0800186 SetSoftRLimit(
187 RLIMIT_RTPRIO, priority, SetLimitForRoot::kNo,
188 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
189 "warning.",
190 AllowSoftLimitDecrease::kNo);
Brian Silvermanb3826f52020-07-02 19:41:18 -0700191
Alex Perrycb7da4b2019-08-28 19:35:56 -0700192 struct sched_param param;
193 param.sched_priority = priority;
Austin Schuhcc6070c2020-10-10 20:25:56 -0700194 MarkRealtime(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700195 PCHECK(sched_setscheduler(0, SCHED_FIFO, &param) == 0)
Austin Schuh27553152020-11-18 21:26:37 -0800196 << ": changing to SCHED_FIFO with " << priority
197 << ", if you want to bypass this check for testing, use "
198 "--skip_realtime_scheduler";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700199}
200
201void WriteCoreDumps() {
202 // Do create core files of unlimited size.
Austin Schuh27553152020-11-18 21:26:37 -0800203 SetSoftRLimit(RLIMIT_CORE, RLIM_INFINITY, SetLimitForRoot::kYes, "");
James Kuszmaulb4874eb2020-01-18 17:50:35 -0800204}
205
206void ExpandStackSize() {
Austin Schuh27553152020-11-18 21:26:37 -0800207 SetSoftRLimit(RLIMIT_STACK, 1000000, SetLimitForRoot::kYes, "",
James Kuszmaulb4874eb2020-01-18 17:50:35 -0800208 AllowSoftLimitDecrease::kNo);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700209}
210
Austin Schuhcc6070c2020-10-10 20:25:56 -0700211namespace {
Austin Schuhf239e332021-07-30 15:27:26 -0700212// Bool to track if malloc hooks have failed to be configured.
213bool has_malloc_hook = true;
Austin Schuhcc6070c2020-10-10 20:25:56 -0700214AOS_THREAD_LOCAL bool is_realtime = false;
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700215} // namespace
Austin Schuhcc6070c2020-10-10 20:25:56 -0700216
217bool MarkRealtime(bool realtime) {
Austin Schuhf239e332021-07-30 15:27:26 -0700218 if (realtime) {
219 // For some applications (generally tools built for the host in Bazel), we
220 // don't have malloc hooks available, but we also don't go realtime. Delay
221 // complaining in that case until we try to go RT and it matters.
222 CHECK(has_malloc_hook)
223 << ": Failed to register required malloc hooks before going realtime. "
224 "Disable --die_on_malloc to continue.";
225 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700226 const bool prior = is_realtime;
227 is_realtime = realtime;
228 return prior;
229}
230
231void CheckRealtime() { CHECK(is_realtime); }
232
233void CheckNotRealtime() { CHECK(!is_realtime); }
234
235ScopedRealtimeRestorer::ScopedRealtimeRestorer() : prior_(is_realtime) {}
236
Austin Schuh62288252020-11-18 23:26:04 -0800237void NewHook(const void *ptr, size_t size) {
238 if (is_realtime) {
239 is_realtime = false;
240 RAW_LOG(FATAL, "Malloced %p -> %zu bytes", ptr, size);
241 }
242}
243
244void DeleteHook(const void *ptr) {
Austin Schuhf239e332021-07-30 15:27:26 -0700245 // It is legal to call free(nullptr) unconditionally and assume that it won't
246 // do anything. Eigen does this. So, if we are RT, ignore any of these
247 // calls.
248 if (is_realtime && ptr != nullptr) {
Austin Schuh62288252020-11-18 23:26:04 -0800249 is_realtime = false;
250 RAW_LOG(FATAL, "Delete Hook %p", ptr);
251 }
252}
253
254void RegisterMallocHook() {
255 if (FLAGS_die_on_malloc) {
256 if (&MallocHook_AddNewHook != nullptr) {
257 CHECK(MallocHook_AddNewHook(&NewHook));
258 } else {
Austin Schuhf239e332021-07-30 15:27:26 -0700259 has_malloc_hook = false;
Austin Schuh62288252020-11-18 23:26:04 -0800260 }
261 if (&MallocHook_AddDeleteHook != nullptr) {
262 CHECK(MallocHook_AddDeleteHook(&DeleteHook));
263 } else {
Austin Schuhf239e332021-07-30 15:27:26 -0700264 has_malloc_hook = false;
Austin Schuh62288252020-11-18 23:26:04 -0800265 }
266 }
267}
268
Alex Perrycb7da4b2019-08-28 19:35:56 -0700269} // namespace aos