blob: 14849a4bc2c874652a40041f322c03116c36e57f [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#include "aos/realtime.h"
2
Austin Schuh77f3f222022-06-10 16:49:21 -07003#include <dirent.h>
Austin Schuhcc6070c2020-10-10 20:25:56 -07004#include <malloc.h>
5#include <sched.h>
Alex Perrycb7da4b2019-08-28 19:35:56 -07006#include <sys/mman.h>
Austin Schuhcc6070c2020-10-10 20:25:56 -07007#include <sys/prctl.h>
Alex Perrycb7da4b2019-08-28 19:35:56 -07008#include <sys/resource.h>
9#include <sys/types.h>
10#include <unistd.h>
Alex Perrycb7da4b2019-08-28 19:35:56 -070011
Tyler Chatowbf0609c2021-07-31 16:13:27 -070012#include <cerrno>
13#include <cstdint>
14#include <cstdio>
15#include <cstdlib>
16#include <cstring>
17
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
Philipp Schrader790cb542023-07-05 21:06:52 -070021#include "aos/thread_local.h"
22
Austin Schuh62288252020-11-18 23:26:04 -080023DEFINE_bool(
Austin Schuhbd938202023-05-16 22:42:11 -070024 die_on_malloc, true,
Austin Schuh62288252020-11-18 23:26:04 -080025 "If true, die when the application allocates memory in a RT section.");
Austin Schuh27553152020-11-18 21:26:37 -080026DEFINE_bool(skip_realtime_scheduler, false,
27 "If true, skip changing the scheduler. Pretend that we changed "
28 "the scheduler instead.");
29DEFINE_bool(skip_locking_memory, false,
30 "If true, skip locking memory. Pretend that we did it instead.");
31
Austin Schuh62288252020-11-18 23:26:04 -080032extern "C" {
Tyler Chatowbf0609c2021-07-31 16:13:27 -070033typedef void (*MallocHook_NewHook)(const void *ptr, size_t size);
Austin Schuh62288252020-11-18 23:26:04 -080034int MallocHook_AddNewHook(MallocHook_NewHook hook) __attribute__((weak));
35int MallocHook_RemoveNewHook(MallocHook_NewHook hook) __attribute__((weak));
36
Tyler Chatowbf0609c2021-07-31 16:13:27 -070037typedef void (*MallocHook_DeleteHook)(const void *ptr);
Austin Schuh62288252020-11-18 23:26:04 -080038int MallocHook_AddDeleteHook(MallocHook_DeleteHook hook) __attribute__((weak));
Tyler Chatowbf0609c2021-07-31 16:13:27 -070039int MallocHook_RemoveDeleteHook(MallocHook_DeleteHook hook)
40 __attribute__((weak));
Tyler Chatow582c6c72021-07-16 13:45:07 -070041
42// Declare tc_malloc weak so we can check if it exists.
43void *tc_malloc(size_t size) __attribute__((weak));
44
45void *__libc_malloc(size_t size);
46void __libc_free(void *ptr);
Tyler Chatowbf0609c2021-07-31 16:13:27 -070047} // extern "C"
Austin Schuh62288252020-11-18 23:26:04 -080048
Alex Perrycb7da4b2019-08-28 19:35:56 -070049namespace FLAG__namespace_do_not_use_directly_use_DECLARE_double_instead {
50extern double FLAGS_tcmalloc_release_rate __attribute__((weak));
51}
52using FLAG__namespace_do_not_use_directly_use_DECLARE_double_instead::
53 FLAGS_tcmalloc_release_rate;
54
55namespace aos {
56namespace logging {
57namespace internal {
58
59// Implemented in aos/logging/context.cc.
60void ReloadThreadName() __attribute__((weak));
61
62} // namespace internal
63} // namespace logging
64
65namespace {
66
Austin Schuh27553152020-11-18 21:26:37 -080067enum class SetLimitForRoot { kYes, kNo };
James Kuszmaulb4874eb2020-01-18 17:50:35 -080068
Austin Schuh27553152020-11-18 21:26:37 -080069enum class AllowSoftLimitDecrease { kYes, kNo };
James Kuszmaulb4874eb2020-01-18 17:50:35 -080070
71void SetSoftRLimit(
72 int resource, rlim64_t soft, SetLimitForRoot set_for_root,
Austin Schuh27553152020-11-18 21:26:37 -080073 std::string_view help_string,
James Kuszmaulb4874eb2020-01-18 17:50:35 -080074 AllowSoftLimitDecrease allow_decrease = AllowSoftLimitDecrease::kYes) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070075 bool am_root = getuid() == 0;
James Kuszmaulb4874eb2020-01-18 17:50:35 -080076 if (set_for_root == SetLimitForRoot::kYes || !am_root) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070077 struct rlimit64 rlim;
78 PCHECK(getrlimit64(resource, &rlim) == 0)
Brian Silverman6a54ff32020-04-28 16:41:39 -070079 << ": getting limit for " << resource;
Alex Perrycb7da4b2019-08-28 19:35:56 -070080
James Kuszmaulb4874eb2020-01-18 17:50:35 -080081 if (allow_decrease == AllowSoftLimitDecrease::kYes) {
82 rlim.rlim_cur = soft;
83 } else {
84 rlim.rlim_cur = std::max(rlim.rlim_cur, soft);
85 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070086 rlim.rlim_max = ::std::max(rlim.rlim_max, soft);
87
88 PCHECK(setrlimit64(resource, &rlim) == 0)
Brian Silverman6a54ff32020-04-28 16:41:39 -070089 << ": changing limit for " << resource << " to " << rlim.rlim_cur
Austin Schuh27553152020-11-18 21:26:37 -080090 << " with max of " << rlim.rlim_max << help_string;
Alex Perrycb7da4b2019-08-28 19:35:56 -070091 }
92}
93
94} // namespace
95
96void LockAllMemory() {
Austin Schuhcc6070c2020-10-10 20:25:56 -070097 CheckNotRealtime();
Alex Perrycb7da4b2019-08-28 19:35:56 -070098 // Allow locking as much as we want into RAM.
Austin Schuh27553152020-11-18 21:26:37 -080099 SetSoftRLimit(RLIMIT_MEMLOCK, RLIM_INFINITY, SetLimitForRoot::kNo,
100 "use --skip_locking_memory to not lock memory.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700101
Austin Schuh27553152020-11-18 21:26:37 -0800102 PCHECK(mlockall(MCL_CURRENT | MCL_FUTURE) == 0)
103 << ": Failed to lock memory, use --skip_locking_memory to bypass this. "
104 "Bypassing will impact RT performance.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700105
Brian Silverman4dbbcce2020-09-18 15:27:38 -0700106#if !__has_feature(address_sanitizer) && !__has_feature(memory_sanitizer)
Alex Perrycb7da4b2019-08-28 19:35:56 -0700107 // Don't give freed memory back to the OS.
108 CHECK_EQ(1, mallopt(M_TRIM_THRESHOLD, -1));
109 // Don't use mmap for large malloc chunks.
110 CHECK_EQ(1, mallopt(M_MMAP_MAX, 0));
Austin Schuh85faf672020-09-10 22:58:46 -0700111#endif
Alex Perrycb7da4b2019-08-28 19:35:56 -0700112
113 if (&FLAGS_tcmalloc_release_rate) {
114 // Tell tcmalloc not to return memory.
115 FLAGS_tcmalloc_release_rate = 0.0;
116 }
117
118 // Forces the memory pages for all the stack space that we're ever going to
119 // use to be loaded into memory (so it can be locked there).
120 uint8_t data[4096 * 8];
121 // Not 0 because linux might optimize that to a 0-filled page.
122 memset(data, 1, sizeof(data));
Austin Schuh27553152020-11-18 21:26:37 -0800123 __asm__ __volatile__("" ::"m"(data));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700124
125 static const size_t kHeapPreallocSize = 512 * 1024;
126 char *const heap_data = static_cast<char *>(malloc(kHeapPreallocSize));
127 memset(heap_data, 1, kHeapPreallocSize);
Austin Schuh27553152020-11-18 21:26:37 -0800128 __asm__ __volatile__("" ::"m"(heap_data));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700129 free(heap_data);
130}
131
132void InitRT() {
Austin Schuh27553152020-11-18 21:26:37 -0800133 if (FLAGS_skip_locking_memory) {
134 LOG(WARNING) << "Ignoring request to lock all memory due to "
135 "--skip_locking_memory.";
136 return;
137 }
138
Austin Schuhcc6070c2020-10-10 20:25:56 -0700139 CheckNotRealtime();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700140 LockAllMemory();
141
Austin Schuh27553152020-11-18 21:26:37 -0800142 if (FLAGS_skip_realtime_scheduler) {
143 return;
144 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700145 // Only let rt processes run for 3 seconds straight.
Austin Schuh27553152020-11-18 21:26:37 -0800146 SetSoftRLimit(
147 RLIMIT_RTTIME, 3000000, SetLimitForRoot::kYes,
148 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
149 "warning.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700150
151 // Allow rt processes up to priority 40.
Austin Schuh27553152020-11-18 21:26:37 -0800152 SetSoftRLimit(
153 RLIMIT_RTPRIO, 40, SetLimitForRoot::kNo,
154 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
155 "warning.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700156}
157
158void UnsetCurrentThreadRealtimePriority() {
159 struct sched_param param;
160 param.sched_priority = 0;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700161 PCHECK(sched_setscheduler(0, SCHED_OTHER, &param) == 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -0700162 MarkRealtime(false);
Brian Silverman6a54ff32020-04-28 16:41:39 -0700163}
164
165void SetCurrentThreadAffinity(const cpu_set_t &cpuset) {
166 PCHECK(sched_setaffinity(0, sizeof(cpuset), &cpuset) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700167}
168
James Kuszmaul57c2baa2020-01-19 14:52:52 -0800169void SetCurrentThreadName(const std::string_view name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700170 CHECK_LE(name.size(), 16u) << ": thread name '" << name << "' too long";
171 VLOG(1) << "This thread is changing to '" << name << "'";
James Kuszmaul57c2baa2020-01-19 14:52:52 -0800172 std::string string_name(name);
Brian Silverman6a54ff32020-04-28 16:41:39 -0700173 PCHECK(prctl(PR_SET_NAME, string_name.c_str()) == 0)
174 << ": changing name to " << string_name;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700175 if (&logging::internal::ReloadThreadName != nullptr) {
176 logging::internal::ReloadThreadName();
177 }
178}
179
Austin Schuhde973292021-10-12 18:09:49 -0700180cpu_set_t GetCurrentThreadAffinity() {
181 cpu_set_t result;
182 PCHECK(sched_getaffinity(0, sizeof(result), &result) == 0);
183 return result;
184}
185
Alex Perrycb7da4b2019-08-28 19:35:56 -0700186void SetCurrentThreadRealtimePriority(int priority) {
Austin Schuh27553152020-11-18 21:26:37 -0800187 if (FLAGS_skip_realtime_scheduler) {
188 LOG(WARNING) << "Ignoring request to switch to the RT scheduler due to "
189 "--skip_realtime_scheduler.";
190 return;
191 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700192 // Make sure we will only be allowed to run for 3 seconds straight.
Austin Schuh27553152020-11-18 21:26:37 -0800193 SetSoftRLimit(
194 RLIMIT_RTTIME, 3000000, SetLimitForRoot::kYes,
195 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
196 "warning.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700197
Brian Silvermanb3826f52020-07-02 19:41:18 -0700198 // Raise our soft rlimit if necessary.
Austin Schuh27553152020-11-18 21:26:37 -0800199 SetSoftRLimit(
200 RLIMIT_RTPRIO, priority, SetLimitForRoot::kNo,
201 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
202 "warning.",
203 AllowSoftLimitDecrease::kNo);
Brian Silvermanb3826f52020-07-02 19:41:18 -0700204
Alex Perrycb7da4b2019-08-28 19:35:56 -0700205 struct sched_param param;
206 param.sched_priority = priority;
Austin Schuhcc6070c2020-10-10 20:25:56 -0700207 MarkRealtime(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700208 PCHECK(sched_setscheduler(0, SCHED_FIFO, &param) == 0)
Austin Schuh27553152020-11-18 21:26:37 -0800209 << ": changing to SCHED_FIFO with " << priority
210 << ", if you want to bypass this check for testing, use "
211 "--skip_realtime_scheduler";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700212}
213
214void WriteCoreDumps() {
215 // Do create core files of unlimited size.
Austin Schuh27553152020-11-18 21:26:37 -0800216 SetSoftRLimit(RLIMIT_CORE, RLIM_INFINITY, SetLimitForRoot::kYes, "");
James Kuszmaulb4874eb2020-01-18 17:50:35 -0800217}
218
219void ExpandStackSize() {
Austin Schuh27553152020-11-18 21:26:37 -0800220 SetSoftRLimit(RLIMIT_STACK, 1000000, SetLimitForRoot::kYes, "",
James Kuszmaulb4874eb2020-01-18 17:50:35 -0800221 AllowSoftLimitDecrease::kNo);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700222}
223
Austin Schuhcc6070c2020-10-10 20:25:56 -0700224namespace {
Austin Schuhf239e332021-07-30 15:27:26 -0700225// Bool to track if malloc hooks have failed to be configured.
226bool has_malloc_hook = true;
Austin Schuhcc6070c2020-10-10 20:25:56 -0700227AOS_THREAD_LOCAL bool is_realtime = false;
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700228} // namespace
Austin Schuhcc6070c2020-10-10 20:25:56 -0700229
230bool MarkRealtime(bool realtime) {
Austin Schuhf239e332021-07-30 15:27:26 -0700231 if (realtime) {
232 // For some applications (generally tools built for the host in Bazel), we
233 // don't have malloc hooks available, but we also don't go realtime. Delay
234 // complaining in that case until we try to go RT and it matters.
Victor Valenciab009bfc2022-09-30 13:30:11 -0700235#if !__has_feature(address_sanitizer) && !__has_feature(memory_sanitizer)
Austin Schuhf239e332021-07-30 15:27:26 -0700236 CHECK(has_malloc_hook)
237 << ": Failed to register required malloc hooks before going realtime. "
238 "Disable --die_on_malloc to continue.";
Victor Valenciab009bfc2022-09-30 13:30:11 -0700239#endif
Austin Schuhf239e332021-07-30 15:27:26 -0700240 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700241 const bool prior = is_realtime;
242 is_realtime = realtime;
243 return prior;
244}
245
246void CheckRealtime() { CHECK(is_realtime); }
247
248void CheckNotRealtime() { CHECK(!is_realtime); }
249
250ScopedRealtimeRestorer::ScopedRealtimeRestorer() : prior_(is_realtime) {}
251
Austin Schuh62288252020-11-18 23:26:04 -0800252void NewHook(const void *ptr, size_t size) {
253 if (is_realtime) {
254 is_realtime = false;
255 RAW_LOG(FATAL, "Malloced %p -> %zu bytes", ptr, size);
256 }
257}
258
259void DeleteHook(const void *ptr) {
Austin Schuhf239e332021-07-30 15:27:26 -0700260 // It is legal to call free(nullptr) unconditionally and assume that it won't
261 // do anything. Eigen does this. So, if we are RT, ignore any of these
262 // calls.
263 if (is_realtime && ptr != nullptr) {
Austin Schuh62288252020-11-18 23:26:04 -0800264 is_realtime = false;
265 RAW_LOG(FATAL, "Delete Hook %p", ptr);
266 }
267}
268
Tyler Chatow582c6c72021-07-16 13:45:07 -0700269extern "C" {
270
271// malloc hooks for libc. Tcmalloc will replace everything it finds (malloc,
272// __libc_malloc, etc.), so we need its specific hook above as well.
273void *aos_malloc_hook(size_t size) {
274 if (FLAGS_die_on_malloc && aos::is_realtime) {
275 aos::is_realtime = false;
276 RAW_LOG(FATAL, "Malloced %zu bytes", size);
277 return nullptr;
278 } else {
279 return __libc_malloc(size);
280 }
281}
282
283void aos_free_hook(void *ptr) {
284 if (FLAGS_die_on_malloc && aos::is_realtime && ptr != nullptr) {
285 aos::is_realtime = false;
286 RAW_LOG(FATAL, "Deleted %p", ptr);
287 } else {
288 __libc_free(ptr);
289 }
290}
291
292void *malloc(size_t size) __attribute__((weak, alias("aos_malloc_hook")));
293void free(void *ptr) __attribute__((weak, alias("aos_free_hook")));
Tyler Chatow582c6c72021-07-16 13:45:07 -0700294}
295
Austin Schuh77f3f222022-06-10 16:49:21 -0700296void FatalUnsetRealtimePriority() {
Austin Schuh4737ad62022-12-30 14:47:03 -0800297 int saved_errno = errno;
Austin Schuh77f3f222022-06-10 16:49:21 -0700298 // Drop our priority first. We are about to do lots of work to undo
299 // everything, don't get overly clever.
300 struct sched_param param;
Austin Schuh4737ad62022-12-30 14:47:03 -0800301 param.sched_priority = 0;
Austin Schuh77f3f222022-06-10 16:49:21 -0700302 sched_setscheduler(0, SCHED_OTHER, &param);
303
304 is_realtime = false;
305
306 // Put all sub-tasks back to non-rt priority too.
307 DIR *dirp = opendir("/proc/self/task");
308 if (dirp) {
309 struct dirent *directory_entry;
310 while ((directory_entry = readdir(dirp)) != NULL) {
311 int thread_id = std::atoi(directory_entry->d_name);
312
313 // ignore . and .. which are zeroes for some reason
314 if (thread_id != 0) {
315 struct sched_param param;
Austin Schuh4737ad62022-12-30 14:47:03 -0800316 param.sched_priority = 0;
Austin Schuh77f3f222022-06-10 16:49:21 -0700317 sched_setscheduler(thread_id, SCHED_OTHER, &param);
318 }
319 }
320 closedir(dirp);
321 }
Austin Schuh4737ad62022-12-30 14:47:03 -0800322 errno = saved_errno;
Austin Schuh77f3f222022-06-10 16:49:21 -0700323}
324
Austin Schuh62288252020-11-18 23:26:04 -0800325void RegisterMallocHook() {
326 if (FLAGS_die_on_malloc) {
Tyler Chatow582c6c72021-07-16 13:45:07 -0700327 // tcmalloc redefines __libc_malloc, so use this as a feature test.
328 if (&__libc_malloc == &tc_malloc) {
329 RAW_LOG(INFO, "Hooking tcmalloc for die_on_malloc");
330 if (&MallocHook_AddNewHook != nullptr) {
331 CHECK(MallocHook_AddNewHook(&NewHook));
332 } else {
333 has_malloc_hook = false;
334 }
335 if (&MallocHook_AddDeleteHook != nullptr) {
336 CHECK(MallocHook_AddDeleteHook(&DeleteHook));
337 } else {
338 has_malloc_hook = false;
339 }
Austin Schuh62288252020-11-18 23:26:04 -0800340 } else {
Austin Schuh6d8afc02023-05-28 13:27:42 -0700341 if (VLOG_IS_ON(1)) {
342 RAW_LOG(INFO, "Replacing glibc malloc");
343 }
Tyler Chatow582c6c72021-07-16 13:45:07 -0700344 if (&malloc != &aos_malloc_hook) {
345 has_malloc_hook = false;
346 }
347 if (&free != &aos_free_hook) {
348 has_malloc_hook = false;
349 }
Austin Schuh62288252020-11-18 23:26:04 -0800350 }
351 }
352}
353
Alex Perrycb7da4b2019-08-28 19:35:56 -0700354} // namespace aos