blob: 8b34adac72ffdb90660783e203e5a846bd6212ab [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"
James Kuszmaula791b762023-07-13 14:56:21 -070022#include "aos/uuid.h"
Philipp Schrader790cb542023-07-05 21:06:52 -070023
Austin Schuh62288252020-11-18 23:26:04 -080024DEFINE_bool(
Austin Schuhbd938202023-05-16 22:42:11 -070025 die_on_malloc, true,
Austin Schuh62288252020-11-18 23:26:04 -080026 "If true, die when the application allocates memory in a RT section.");
Austin Schuh27553152020-11-18 21:26:37 -080027DEFINE_bool(skip_realtime_scheduler, false,
28 "If true, skip changing the scheduler. Pretend that we changed "
29 "the scheduler instead.");
30DEFINE_bool(skip_locking_memory, false,
31 "If true, skip locking memory. Pretend that we did it instead.");
32
Austin Schuh62288252020-11-18 23:26:04 -080033extern "C" {
Tyler Chatowbf0609c2021-07-31 16:13:27 -070034typedef void (*MallocHook_NewHook)(const void *ptr, size_t size);
Austin Schuh62288252020-11-18 23:26:04 -080035int MallocHook_AddNewHook(MallocHook_NewHook hook) __attribute__((weak));
36int MallocHook_RemoveNewHook(MallocHook_NewHook hook) __attribute__((weak));
37
Tyler Chatowbf0609c2021-07-31 16:13:27 -070038typedef void (*MallocHook_DeleteHook)(const void *ptr);
Austin Schuh62288252020-11-18 23:26:04 -080039int MallocHook_AddDeleteHook(MallocHook_DeleteHook hook) __attribute__((weak));
Tyler Chatowbf0609c2021-07-31 16:13:27 -070040int MallocHook_RemoveDeleteHook(MallocHook_DeleteHook hook)
41 __attribute__((weak));
Tyler Chatow582c6c72021-07-16 13:45:07 -070042
43// Declare tc_malloc weak so we can check if it exists.
44void *tc_malloc(size_t size) __attribute__((weak));
45
46void *__libc_malloc(size_t size);
47void __libc_free(void *ptr);
Tyler Chatowbf0609c2021-07-31 16:13:27 -070048} // extern "C"
Austin Schuh62288252020-11-18 23:26:04 -080049
Alex Perrycb7da4b2019-08-28 19:35:56 -070050namespace FLAG__namespace_do_not_use_directly_use_DECLARE_double_instead {
51extern double FLAGS_tcmalloc_release_rate __attribute__((weak));
52}
53using FLAG__namespace_do_not_use_directly_use_DECLARE_double_instead::
54 FLAGS_tcmalloc_release_rate;
55
56namespace aos {
57namespace logging {
58namespace internal {
59
60// Implemented in aos/logging/context.cc.
61void ReloadThreadName() __attribute__((weak));
62
63} // namespace internal
64} // namespace logging
65
66namespace {
67
Austin Schuh27553152020-11-18 21:26:37 -080068enum class SetLimitForRoot { kYes, kNo };
James Kuszmaulb4874eb2020-01-18 17:50:35 -080069
Austin Schuh27553152020-11-18 21:26:37 -080070enum class AllowSoftLimitDecrease { kYes, kNo };
James Kuszmaulb4874eb2020-01-18 17:50:35 -080071
72void SetSoftRLimit(
73 int resource, rlim64_t soft, SetLimitForRoot set_for_root,
Austin Schuh27553152020-11-18 21:26:37 -080074 std::string_view help_string,
James Kuszmaulb4874eb2020-01-18 17:50:35 -080075 AllowSoftLimitDecrease allow_decrease = AllowSoftLimitDecrease::kYes) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070076 bool am_root = getuid() == 0;
James Kuszmaulb4874eb2020-01-18 17:50:35 -080077 if (set_for_root == SetLimitForRoot::kYes || !am_root) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070078 struct rlimit64 rlim;
79 PCHECK(getrlimit64(resource, &rlim) == 0)
Brian Silverman6a54ff32020-04-28 16:41:39 -070080 << ": getting limit for " << resource;
Alex Perrycb7da4b2019-08-28 19:35:56 -070081
James Kuszmaulb4874eb2020-01-18 17:50:35 -080082 if (allow_decrease == AllowSoftLimitDecrease::kYes) {
83 rlim.rlim_cur = soft;
84 } else {
85 rlim.rlim_cur = std::max(rlim.rlim_cur, soft);
86 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070087 rlim.rlim_max = ::std::max(rlim.rlim_max, soft);
88
89 PCHECK(setrlimit64(resource, &rlim) == 0)
Brian Silverman6a54ff32020-04-28 16:41:39 -070090 << ": changing limit for " << resource << " to " << rlim.rlim_cur
Austin Schuh27553152020-11-18 21:26:37 -080091 << " with max of " << rlim.rlim_max << help_string;
Alex Perrycb7da4b2019-08-28 19:35:56 -070092 }
93}
94
95} // namespace
96
97void LockAllMemory() {
Austin Schuhcc6070c2020-10-10 20:25:56 -070098 CheckNotRealtime();
Alex Perrycb7da4b2019-08-28 19:35:56 -070099 // Allow locking as much as we want into RAM.
Austin Schuh27553152020-11-18 21:26:37 -0800100 SetSoftRLimit(RLIMIT_MEMLOCK, RLIM_INFINITY, SetLimitForRoot::kNo,
101 "use --skip_locking_memory to not lock memory.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700102
Austin Schuh27553152020-11-18 21:26:37 -0800103 PCHECK(mlockall(MCL_CURRENT | MCL_FUTURE) == 0)
104 << ": Failed to lock memory, use --skip_locking_memory to bypass this. "
105 "Bypassing will impact RT performance.";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700106
Brian Silverman4dbbcce2020-09-18 15:27:38 -0700107#if !__has_feature(address_sanitizer) && !__has_feature(memory_sanitizer)
Alex Perrycb7da4b2019-08-28 19:35:56 -0700108 // Don't give freed memory back to the OS.
109 CHECK_EQ(1, mallopt(M_TRIM_THRESHOLD, -1));
110 // Don't use mmap for large malloc chunks.
111 CHECK_EQ(1, mallopt(M_MMAP_MAX, 0));
Austin Schuh85faf672020-09-10 22:58:46 -0700112#endif
Alex Perrycb7da4b2019-08-28 19:35:56 -0700113
114 if (&FLAGS_tcmalloc_release_rate) {
115 // Tell tcmalloc not to return memory.
116 FLAGS_tcmalloc_release_rate = 0.0;
117 }
118
119 // Forces the memory pages for all the stack space that we're ever going to
120 // use to be loaded into memory (so it can be locked there).
121 uint8_t data[4096 * 8];
122 // Not 0 because linux might optimize that to a 0-filled page.
123 memset(data, 1, sizeof(data));
Austin Schuh27553152020-11-18 21:26:37 -0800124 __asm__ __volatile__("" ::"m"(data));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700125
126 static const size_t kHeapPreallocSize = 512 * 1024;
127 char *const heap_data = static_cast<char *>(malloc(kHeapPreallocSize));
128 memset(heap_data, 1, kHeapPreallocSize);
Austin Schuh27553152020-11-18 21:26:37 -0800129 __asm__ __volatile__("" ::"m"(heap_data));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700130 free(heap_data);
131}
132
133void InitRT() {
Austin Schuh27553152020-11-18 21:26:37 -0800134 if (FLAGS_skip_locking_memory) {
135 LOG(WARNING) << "Ignoring request to lock all memory due to "
136 "--skip_locking_memory.";
137 return;
138 }
139
Austin Schuhcc6070c2020-10-10 20:25:56 -0700140 CheckNotRealtime();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700141 LockAllMemory();
142
Austin Schuh27553152020-11-18 21:26:37 -0800143 if (FLAGS_skip_realtime_scheduler) {
144 return;
145 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700146 // Only let rt processes run for 3 seconds straight.
Austin Schuh27553152020-11-18 21:26:37 -0800147 SetSoftRLimit(
148 RLIMIT_RTTIME, 3000000, SetLimitForRoot::kYes,
149 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
150 "warning.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700151
152 // Allow rt processes up to priority 40.
Austin Schuh27553152020-11-18 21:26:37 -0800153 SetSoftRLimit(
154 RLIMIT_RTPRIO, 40, SetLimitForRoot::kNo,
155 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
156 "warning.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700157}
158
159void UnsetCurrentThreadRealtimePriority() {
160 struct sched_param param;
161 param.sched_priority = 0;
Brian Silverman6a54ff32020-04-28 16:41:39 -0700162 PCHECK(sched_setscheduler(0, SCHED_OTHER, &param) == 0);
Austin Schuhcc6070c2020-10-10 20:25:56 -0700163 MarkRealtime(false);
Brian Silverman6a54ff32020-04-28 16:41:39 -0700164}
165
166void SetCurrentThreadAffinity(const cpu_set_t &cpuset) {
167 PCHECK(sched_setaffinity(0, sizeof(cpuset), &cpuset) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700168}
169
James Kuszmaul57c2baa2020-01-19 14:52:52 -0800170void SetCurrentThreadName(const std::string_view name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700171 CHECK_LE(name.size(), 16u) << ": thread name '" << name << "' too long";
172 VLOG(1) << "This thread is changing to '" << name << "'";
James Kuszmaul57c2baa2020-01-19 14:52:52 -0800173 std::string string_name(name);
Brian Silverman6a54ff32020-04-28 16:41:39 -0700174 PCHECK(prctl(PR_SET_NAME, string_name.c_str()) == 0)
175 << ": changing name to " << string_name;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700176 if (&logging::internal::ReloadThreadName != nullptr) {
177 logging::internal::ReloadThreadName();
178 }
179}
180
Austin Schuhde973292021-10-12 18:09:49 -0700181cpu_set_t GetCurrentThreadAffinity() {
182 cpu_set_t result;
183 PCHECK(sched_getaffinity(0, sizeof(result), &result) == 0);
184 return result;
185}
186
Alex Perrycb7da4b2019-08-28 19:35:56 -0700187void SetCurrentThreadRealtimePriority(int priority) {
James Kuszmaula791b762023-07-13 14:56:21 -0700188 // Ensure that we won't get expensive reads of /dev/random when the realtime
189 // scheduler is running.
190 UUID::Random();
191
Austin Schuh27553152020-11-18 21:26:37 -0800192 if (FLAGS_skip_realtime_scheduler) {
193 LOG(WARNING) << "Ignoring request to switch to the RT scheduler due to "
194 "--skip_realtime_scheduler.";
195 return;
196 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700197 // Make sure we will only be allowed to run for 3 seconds straight.
Austin Schuh27553152020-11-18 21:26:37 -0800198 SetSoftRLimit(
199 RLIMIT_RTTIME, 3000000, SetLimitForRoot::kYes,
200 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
201 "warning.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700202
Brian Silvermanb3826f52020-07-02 19:41:18 -0700203 // Raise our soft rlimit if necessary.
Austin Schuh27553152020-11-18 21:26:37 -0800204 SetSoftRLimit(
205 RLIMIT_RTPRIO, priority, SetLimitForRoot::kNo,
206 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
207 "warning.",
208 AllowSoftLimitDecrease::kNo);
Brian Silvermanb3826f52020-07-02 19:41:18 -0700209
Alex Perrycb7da4b2019-08-28 19:35:56 -0700210 struct sched_param param;
211 param.sched_priority = priority;
Austin Schuhcc6070c2020-10-10 20:25:56 -0700212 MarkRealtime(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700213 PCHECK(sched_setscheduler(0, SCHED_FIFO, &param) == 0)
Austin Schuh27553152020-11-18 21:26:37 -0800214 << ": changing to SCHED_FIFO with " << priority
215 << ", if you want to bypass this check for testing, use "
216 "--skip_realtime_scheduler";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700217}
218
219void WriteCoreDumps() {
220 // Do create core files of unlimited size.
Austin Schuh27553152020-11-18 21:26:37 -0800221 SetSoftRLimit(RLIMIT_CORE, RLIM_INFINITY, SetLimitForRoot::kYes, "");
James Kuszmaulb4874eb2020-01-18 17:50:35 -0800222}
223
224void ExpandStackSize() {
Austin Schuh27553152020-11-18 21:26:37 -0800225 SetSoftRLimit(RLIMIT_STACK, 1000000, SetLimitForRoot::kYes, "",
James Kuszmaulb4874eb2020-01-18 17:50:35 -0800226 AllowSoftLimitDecrease::kNo);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700227}
228
Austin Schuhcc6070c2020-10-10 20:25:56 -0700229namespace {
Austin Schuhf239e332021-07-30 15:27:26 -0700230// Bool to track if malloc hooks have failed to be configured.
231bool has_malloc_hook = true;
Austin Schuhcc6070c2020-10-10 20:25:56 -0700232AOS_THREAD_LOCAL bool is_realtime = false;
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700233} // namespace
Austin Schuhcc6070c2020-10-10 20:25:56 -0700234
235bool MarkRealtime(bool realtime) {
Austin Schuhf239e332021-07-30 15:27:26 -0700236 if (realtime) {
237 // For some applications (generally tools built for the host in Bazel), we
238 // don't have malloc hooks available, but we also don't go realtime. Delay
239 // complaining in that case until we try to go RT and it matters.
Victor Valenciab009bfc2022-09-30 13:30:11 -0700240#if !__has_feature(address_sanitizer) && !__has_feature(memory_sanitizer)
Austin Schuhf239e332021-07-30 15:27:26 -0700241 CHECK(has_malloc_hook)
242 << ": Failed to register required malloc hooks before going realtime. "
243 "Disable --die_on_malloc to continue.";
Victor Valenciab009bfc2022-09-30 13:30:11 -0700244#endif
Austin Schuhf239e332021-07-30 15:27:26 -0700245 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700246 const bool prior = is_realtime;
247 is_realtime = realtime;
248 return prior;
249}
250
251void CheckRealtime() { CHECK(is_realtime); }
252
253void CheckNotRealtime() { CHECK(!is_realtime); }
254
255ScopedRealtimeRestorer::ScopedRealtimeRestorer() : prior_(is_realtime) {}
256
Austin Schuh62288252020-11-18 23:26:04 -0800257void NewHook(const void *ptr, size_t size) {
258 if (is_realtime) {
259 is_realtime = false;
260 RAW_LOG(FATAL, "Malloced %p -> %zu bytes", ptr, size);
261 }
262}
263
264void DeleteHook(const void *ptr) {
Austin Schuhf239e332021-07-30 15:27:26 -0700265 // It is legal to call free(nullptr) unconditionally and assume that it won't
266 // do anything. Eigen does this. So, if we are RT, ignore any of these
267 // calls.
268 if (is_realtime && ptr != nullptr) {
Austin Schuh62288252020-11-18 23:26:04 -0800269 is_realtime = false;
270 RAW_LOG(FATAL, "Delete Hook %p", ptr);
271 }
272}
273
Tyler Chatow582c6c72021-07-16 13:45:07 -0700274extern "C" {
275
276// malloc hooks for libc. Tcmalloc will replace everything it finds (malloc,
277// __libc_malloc, etc.), so we need its specific hook above as well.
278void *aos_malloc_hook(size_t size) {
279 if (FLAGS_die_on_malloc && aos::is_realtime) {
280 aos::is_realtime = false;
281 RAW_LOG(FATAL, "Malloced %zu bytes", size);
282 return nullptr;
283 } else {
284 return __libc_malloc(size);
285 }
286}
287
288void aos_free_hook(void *ptr) {
289 if (FLAGS_die_on_malloc && aos::is_realtime && ptr != nullptr) {
290 aos::is_realtime = false;
291 RAW_LOG(FATAL, "Deleted %p", ptr);
292 } else {
293 __libc_free(ptr);
294 }
295}
296
297void *malloc(size_t size) __attribute__((weak, alias("aos_malloc_hook")));
298void free(void *ptr) __attribute__((weak, alias("aos_free_hook")));
Tyler Chatow582c6c72021-07-16 13:45:07 -0700299}
300
Austin Schuh77f3f222022-06-10 16:49:21 -0700301void FatalUnsetRealtimePriority() {
Austin Schuh4737ad62022-12-30 14:47:03 -0800302 int saved_errno = errno;
Austin Schuh77f3f222022-06-10 16:49:21 -0700303 // Drop our priority first. We are about to do lots of work to undo
304 // everything, don't get overly clever.
305 struct sched_param param;
Austin Schuh4737ad62022-12-30 14:47:03 -0800306 param.sched_priority = 0;
Austin Schuh77f3f222022-06-10 16:49:21 -0700307 sched_setscheduler(0, SCHED_OTHER, &param);
308
309 is_realtime = false;
310
311 // Put all sub-tasks back to non-rt priority too.
312 DIR *dirp = opendir("/proc/self/task");
313 if (dirp) {
314 struct dirent *directory_entry;
315 while ((directory_entry = readdir(dirp)) != NULL) {
316 int thread_id = std::atoi(directory_entry->d_name);
317
318 // ignore . and .. which are zeroes for some reason
319 if (thread_id != 0) {
320 struct sched_param param;
Austin Schuh4737ad62022-12-30 14:47:03 -0800321 param.sched_priority = 0;
Austin Schuh77f3f222022-06-10 16:49:21 -0700322 sched_setscheduler(thread_id, SCHED_OTHER, &param);
323 }
324 }
325 closedir(dirp);
326 }
Austin Schuh4737ad62022-12-30 14:47:03 -0800327 errno = saved_errno;
Austin Schuh77f3f222022-06-10 16:49:21 -0700328}
329
Austin Schuh62288252020-11-18 23:26:04 -0800330void RegisterMallocHook() {
331 if (FLAGS_die_on_malloc) {
Tyler Chatow582c6c72021-07-16 13:45:07 -0700332 // tcmalloc redefines __libc_malloc, so use this as a feature test.
333 if (&__libc_malloc == &tc_malloc) {
334 RAW_LOG(INFO, "Hooking tcmalloc for die_on_malloc");
335 if (&MallocHook_AddNewHook != nullptr) {
336 CHECK(MallocHook_AddNewHook(&NewHook));
337 } else {
338 has_malloc_hook = false;
339 }
340 if (&MallocHook_AddDeleteHook != nullptr) {
341 CHECK(MallocHook_AddDeleteHook(&DeleteHook));
342 } else {
343 has_malloc_hook = false;
344 }
Austin Schuh62288252020-11-18 23:26:04 -0800345 } else {
Austin Schuh6d8afc02023-05-28 13:27:42 -0700346 if (VLOG_IS_ON(1)) {
347 RAW_LOG(INFO, "Replacing glibc malloc");
348 }
Tyler Chatow582c6c72021-07-16 13:45:07 -0700349 if (&malloc != &aos_malloc_hook) {
350 has_malloc_hook = false;
351 }
352 if (&free != &aos_free_hook) {
353 has_malloc_hook = false;
354 }
Austin Schuh62288252020-11-18 23:26:04 -0800355 }
356 }
357}
358
Alex Perrycb7da4b2019-08-28 19:35:56 -0700359} // namespace aos