blob: dc53a37402aabca6844479d6d91e4eef6239509d [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));
Tyler Chatow582c6c72021-07-16 13:45:07 -070039
40// Declare tc_malloc weak so we can check if it exists.
41void *tc_malloc(size_t size) __attribute__((weak));
42
43void *__libc_malloc(size_t size);
44void __libc_free(void *ptr);
Tyler Chatowbf0609c2021-07-31 16:13:27 -070045} // extern "C"
Austin Schuh62288252020-11-18 23:26:04 -080046
Alex Perrycb7da4b2019-08-28 19:35:56 -070047namespace FLAG__namespace_do_not_use_directly_use_DECLARE_double_instead {
48extern double FLAGS_tcmalloc_release_rate __attribute__((weak));
49}
50using FLAG__namespace_do_not_use_directly_use_DECLARE_double_instead::
51 FLAGS_tcmalloc_release_rate;
52
53namespace aos {
54namespace logging {
55namespace internal {
56
57// Implemented in aos/logging/context.cc.
58void ReloadThreadName() __attribute__((weak));
59
60} // namespace internal
61} // namespace logging
62
63namespace {
64
Austin Schuh27553152020-11-18 21:26:37 -080065enum class SetLimitForRoot { kYes, kNo };
James Kuszmaulb4874eb2020-01-18 17:50:35 -080066
Austin Schuh27553152020-11-18 21:26:37 -080067enum class AllowSoftLimitDecrease { kYes, kNo };
James Kuszmaulb4874eb2020-01-18 17:50:35 -080068
69void SetSoftRLimit(
70 int resource, rlim64_t soft, SetLimitForRoot set_for_root,
Austin Schuh27553152020-11-18 21:26:37 -080071 std::string_view help_string,
James Kuszmaulb4874eb2020-01-18 17:50:35 -080072 AllowSoftLimitDecrease allow_decrease = AllowSoftLimitDecrease::kYes) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070073 bool am_root = getuid() == 0;
James Kuszmaulb4874eb2020-01-18 17:50:35 -080074 if (set_for_root == SetLimitForRoot::kYes || !am_root) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070075 struct rlimit64 rlim;
76 PCHECK(getrlimit64(resource, &rlim) == 0)
Brian Silverman6a54ff32020-04-28 16:41:39 -070077 << ": getting limit for " << resource;
Alex Perrycb7da4b2019-08-28 19:35:56 -070078
James Kuszmaulb4874eb2020-01-18 17:50:35 -080079 if (allow_decrease == AllowSoftLimitDecrease::kYes) {
80 rlim.rlim_cur = soft;
81 } else {
82 rlim.rlim_cur = std::max(rlim.rlim_cur, soft);
83 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070084 rlim.rlim_max = ::std::max(rlim.rlim_max, soft);
85
86 PCHECK(setrlimit64(resource, &rlim) == 0)
Brian Silverman6a54ff32020-04-28 16:41:39 -070087 << ": changing limit for " << resource << " to " << rlim.rlim_cur
Austin Schuh27553152020-11-18 21:26:37 -080088 << " with max of " << rlim.rlim_max << help_string;
Alex Perrycb7da4b2019-08-28 19:35:56 -070089 }
90}
91
92} // namespace
93
94void LockAllMemory() {
Austin Schuhcc6070c2020-10-10 20:25:56 -070095 CheckNotRealtime();
Alex Perrycb7da4b2019-08-28 19:35:56 -070096 // Allow locking as much as we want into RAM.
Austin Schuh27553152020-11-18 21:26:37 -080097 SetSoftRLimit(RLIMIT_MEMLOCK, RLIM_INFINITY, SetLimitForRoot::kNo,
98 "use --skip_locking_memory to not lock memory.");
Alex Perrycb7da4b2019-08-28 19:35:56 -070099
100 WriteCoreDumps();
Austin Schuh27553152020-11-18 21:26:37 -0800101 PCHECK(mlockall(MCL_CURRENT | MCL_FUTURE) == 0)
102 << ": Failed to lock memory, use --skip_locking_memory to bypass this. "
103 "Bypassing will impact RT performance.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700104
Brian Silverman4dbbcce2020-09-18 15:27:38 -0700105#if !__has_feature(address_sanitizer) && !__has_feature(memory_sanitizer)
Alex Perrycb7da4b2019-08-28 19:35:56 -0700106 // Don't give freed memory back to the OS.
107 CHECK_EQ(1, mallopt(M_TRIM_THRESHOLD, -1));
108 // Don't use mmap for large malloc chunks.
109 CHECK_EQ(1, mallopt(M_MMAP_MAX, 0));
Austin Schuh85faf672020-09-10 22:58:46 -0700110#endif
Alex Perrycb7da4b2019-08-28 19:35:56 -0700111
112 if (&FLAGS_tcmalloc_release_rate) {
113 // Tell tcmalloc not to return memory.
114 FLAGS_tcmalloc_release_rate = 0.0;
115 }
116
117 // Forces the memory pages for all the stack space that we're ever going to
118 // use to be loaded into memory (so it can be locked there).
119 uint8_t data[4096 * 8];
120 // Not 0 because linux might optimize that to a 0-filled page.
121 memset(data, 1, sizeof(data));
Austin Schuh27553152020-11-18 21:26:37 -0800122 __asm__ __volatile__("" ::"m"(data));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700123
124 static const size_t kHeapPreallocSize = 512 * 1024;
125 char *const heap_data = static_cast<char *>(malloc(kHeapPreallocSize));
126 memset(heap_data, 1, kHeapPreallocSize);
Austin Schuh27553152020-11-18 21:26:37 -0800127 __asm__ __volatile__("" ::"m"(heap_data));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700128 free(heap_data);
129}
130
131void InitRT() {
Austin Schuh27553152020-11-18 21:26:37 -0800132 if (FLAGS_skip_locking_memory) {
133 LOG(WARNING) << "Ignoring request to lock all memory due to "
134 "--skip_locking_memory.";
135 return;
136 }
137
Austin Schuhcc6070c2020-10-10 20:25:56 -0700138 CheckNotRealtime();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700139 LockAllMemory();
140
Austin Schuh27553152020-11-18 21:26:37 -0800141 if (FLAGS_skip_realtime_scheduler) {
142 return;
143 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700144 // Only let rt processes run for 3 seconds straight.
Austin Schuh27553152020-11-18 21:26:37 -0800145 SetSoftRLimit(
146 RLIMIT_RTTIME, 3000000, SetLimitForRoot::kYes,
147 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
148 "warning.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700149
150 // Allow rt processes up to priority 40.
Austin Schuh27553152020-11-18 21:26:37 -0800151 SetSoftRLimit(
152 RLIMIT_RTPRIO, 40, SetLimitForRoot::kNo,
153 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
154 "warning.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700155}
156
157void UnsetCurrentThreadRealtimePriority() {
158 struct sched_param param;
159 param.sched_priority = 0;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700160 PCHECK(sched_setscheduler(0, SCHED_OTHER, &param) == 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -0700161 MarkRealtime(false);
Brian Silverman6a54ff32020-04-28 16:41:39 -0700162}
163
164void SetCurrentThreadAffinity(const cpu_set_t &cpuset) {
165 PCHECK(sched_setaffinity(0, sizeof(cpuset), &cpuset) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700166}
167
James Kuszmaul57c2baa2020-01-19 14:52:52 -0800168void SetCurrentThreadName(const std::string_view name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700169 CHECK_LE(name.size(), 16u) << ": thread name '" << name << "' too long";
170 VLOG(1) << "This thread is changing to '" << name << "'";
James Kuszmaul57c2baa2020-01-19 14:52:52 -0800171 std::string string_name(name);
Brian Silverman6a54ff32020-04-28 16:41:39 -0700172 PCHECK(prctl(PR_SET_NAME, string_name.c_str()) == 0)
173 << ": changing name to " << string_name;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700174 if (&logging::internal::ReloadThreadName != nullptr) {
175 logging::internal::ReloadThreadName();
176 }
177}
178
179void SetCurrentThreadRealtimePriority(int priority) {
Austin Schuh27553152020-11-18 21:26:37 -0800180 if (FLAGS_skip_realtime_scheduler) {
181 LOG(WARNING) << "Ignoring request to switch to the RT scheduler due to "
182 "--skip_realtime_scheduler.";
183 return;
184 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700185 // Make sure we will only be allowed to run for 3 seconds straight.
Austin Schuh27553152020-11-18 21:26:37 -0800186 SetSoftRLimit(
187 RLIMIT_RTTIME, 3000000, SetLimitForRoot::kYes,
188 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
189 "warning.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700190
Brian Silvermanb3826f52020-07-02 19:41:18 -0700191 // Raise our soft rlimit if necessary.
Austin Schuh27553152020-11-18 21:26:37 -0800192 SetSoftRLimit(
193 RLIMIT_RTPRIO, priority, SetLimitForRoot::kNo,
194 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
195 "warning.",
196 AllowSoftLimitDecrease::kNo);
Brian Silvermanb3826f52020-07-02 19:41:18 -0700197
Alex Perrycb7da4b2019-08-28 19:35:56 -0700198 struct sched_param param;
199 param.sched_priority = priority;
Austin Schuhcc6070c2020-10-10 20:25:56 -0700200 MarkRealtime(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700201 PCHECK(sched_setscheduler(0, SCHED_FIFO, &param) == 0)
Austin Schuh27553152020-11-18 21:26:37 -0800202 << ": changing to SCHED_FIFO with " << priority
203 << ", if you want to bypass this check for testing, use "
204 "--skip_realtime_scheduler";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700205}
206
207void WriteCoreDumps() {
208 // Do create core files of unlimited size.
Austin Schuh27553152020-11-18 21:26:37 -0800209 SetSoftRLimit(RLIMIT_CORE, RLIM_INFINITY, SetLimitForRoot::kYes, "");
James Kuszmaulb4874eb2020-01-18 17:50:35 -0800210}
211
212void ExpandStackSize() {
Austin Schuh27553152020-11-18 21:26:37 -0800213 SetSoftRLimit(RLIMIT_STACK, 1000000, SetLimitForRoot::kYes, "",
James Kuszmaulb4874eb2020-01-18 17:50:35 -0800214 AllowSoftLimitDecrease::kNo);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700215}
216
Austin Schuhcc6070c2020-10-10 20:25:56 -0700217namespace {
Austin Schuhf239e332021-07-30 15:27:26 -0700218// Bool to track if malloc hooks have failed to be configured.
219bool has_malloc_hook = true;
Austin Schuhcc6070c2020-10-10 20:25:56 -0700220AOS_THREAD_LOCAL bool is_realtime = false;
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700221} // namespace
Austin Schuhcc6070c2020-10-10 20:25:56 -0700222
223bool MarkRealtime(bool realtime) {
Austin Schuhf239e332021-07-30 15:27:26 -0700224 if (realtime) {
225 // For some applications (generally tools built for the host in Bazel), we
226 // don't have malloc hooks available, but we also don't go realtime. Delay
227 // complaining in that case until we try to go RT and it matters.
228 CHECK(has_malloc_hook)
229 << ": Failed to register required malloc hooks before going realtime. "
230 "Disable --die_on_malloc to continue.";
231 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700232 const bool prior = is_realtime;
233 is_realtime = realtime;
234 return prior;
235}
236
237void CheckRealtime() { CHECK(is_realtime); }
238
239void CheckNotRealtime() { CHECK(!is_realtime); }
240
241ScopedRealtimeRestorer::ScopedRealtimeRestorer() : prior_(is_realtime) {}
242
Austin Schuh62288252020-11-18 23:26:04 -0800243void NewHook(const void *ptr, size_t size) {
244 if (is_realtime) {
245 is_realtime = false;
246 RAW_LOG(FATAL, "Malloced %p -> %zu bytes", ptr, size);
247 }
248}
249
250void DeleteHook(const void *ptr) {
Austin Schuhf239e332021-07-30 15:27:26 -0700251 // It is legal to call free(nullptr) unconditionally and assume that it won't
252 // do anything. Eigen does this. So, if we are RT, ignore any of these
253 // calls.
254 if (is_realtime && ptr != nullptr) {
Austin Schuh62288252020-11-18 23:26:04 -0800255 is_realtime = false;
256 RAW_LOG(FATAL, "Delete Hook %p", ptr);
257 }
258}
259
Tyler Chatow582c6c72021-07-16 13:45:07 -0700260extern "C" {
261
262// malloc hooks for libc. Tcmalloc will replace everything it finds (malloc,
263// __libc_malloc, etc.), so we need its specific hook above as well.
264void *aos_malloc_hook(size_t size) {
265 if (FLAGS_die_on_malloc && aos::is_realtime) {
266 aos::is_realtime = false;
267 RAW_LOG(FATAL, "Malloced %zu bytes", size);
268 return nullptr;
269 } else {
270 return __libc_malloc(size);
271 }
272}
273
274void aos_free_hook(void *ptr) {
275 if (FLAGS_die_on_malloc && aos::is_realtime && ptr != nullptr) {
276 aos::is_realtime = false;
277 RAW_LOG(FATAL, "Deleted %p", ptr);
278 } else {
279 __libc_free(ptr);
280 }
281}
282
283void *malloc(size_t size) __attribute__((weak, alias("aos_malloc_hook")));
284void free(void *ptr) __attribute__((weak, alias("aos_free_hook")));
285
286}
287
Austin Schuh62288252020-11-18 23:26:04 -0800288void RegisterMallocHook() {
289 if (FLAGS_die_on_malloc) {
Tyler Chatow582c6c72021-07-16 13:45:07 -0700290 // tcmalloc redefines __libc_malloc, so use this as a feature test.
291 if (&__libc_malloc == &tc_malloc) {
292 RAW_LOG(INFO, "Hooking tcmalloc for die_on_malloc");
293 if (&MallocHook_AddNewHook != nullptr) {
294 CHECK(MallocHook_AddNewHook(&NewHook));
295 } else {
296 has_malloc_hook = false;
297 }
298 if (&MallocHook_AddDeleteHook != nullptr) {
299 CHECK(MallocHook_AddDeleteHook(&DeleteHook));
300 } else {
301 has_malloc_hook = false;
302 }
Austin Schuh62288252020-11-18 23:26:04 -0800303 } else {
Tyler Chatow582c6c72021-07-16 13:45:07 -0700304 RAW_LOG(INFO, "Replacing glibc malloc");
305 if (&malloc != &aos_malloc_hook) {
306 has_malloc_hook = false;
307 }
308 if (&free != &aos_free_hook) {
309 has_malloc_hook = false;
310 }
Austin Schuh62288252020-11-18 23:26:04 -0800311 }
312 }
313}
314
Alex Perrycb7da4b2019-08-28 19:35:56 -0700315} // namespace aos