blob: 1e10457a84da3621b490d07b8bde6dfd2c4ac6ec [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
James Kuszmaula791b762023-07-13 14:56:21 -070021#include "aos/uuid.h"
Philipp Schrader790cb542023-07-05 21:06:52 -070022
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 {
Stephan Pleinesf63bde82024-01-13 15:59:33 -080056
57namespace logging::internal {
Alex Perrycb7da4b2019-08-28 19:35:56 -070058
59// Implemented in aos/logging/context.cc.
60void ReloadThreadName() __attribute__((weak));
61
Stephan Pleinesf63bde82024-01-13 15:59:33 -080062} // namespace logging::internal
Alex Perrycb7da4b2019-08-28 19:35:56 -070063
64namespace {
65
Austin Schuh27553152020-11-18 21:26:37 -080066enum class SetLimitForRoot { kYes, kNo };
James Kuszmaulb4874eb2020-01-18 17:50:35 -080067
Austin Schuh27553152020-11-18 21:26:37 -080068enum class AllowSoftLimitDecrease { kYes, kNo };
James Kuszmaulb4874eb2020-01-18 17:50:35 -080069
70void SetSoftRLimit(
71 int resource, rlim64_t soft, SetLimitForRoot set_for_root,
Austin Schuh27553152020-11-18 21:26:37 -080072 std::string_view help_string,
James Kuszmaulb4874eb2020-01-18 17:50:35 -080073 AllowSoftLimitDecrease allow_decrease = AllowSoftLimitDecrease::kYes) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070074 bool am_root = getuid() == 0;
James Kuszmaulb4874eb2020-01-18 17:50:35 -080075 if (set_for_root == SetLimitForRoot::kYes || !am_root) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070076 struct rlimit64 rlim;
77 PCHECK(getrlimit64(resource, &rlim) == 0)
Brian Silverman6a54ff32020-04-28 16:41:39 -070078 << ": getting limit for " << resource;
Alex Perrycb7da4b2019-08-28 19:35:56 -070079
James Kuszmaulb4874eb2020-01-18 17:50:35 -080080 if (allow_decrease == AllowSoftLimitDecrease::kYes) {
81 rlim.rlim_cur = soft;
82 } else {
83 rlim.rlim_cur = std::max(rlim.rlim_cur, soft);
84 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070085 rlim.rlim_max = ::std::max(rlim.rlim_max, soft);
86
87 PCHECK(setrlimit64(resource, &rlim) == 0)
Brian Silverman6a54ff32020-04-28 16:41:39 -070088 << ": changing limit for " << resource << " to " << rlim.rlim_cur
Austin Schuh27553152020-11-18 21:26:37 -080089 << " with max of " << rlim.rlim_max << help_string;
Alex Perrycb7da4b2019-08-28 19:35:56 -070090 }
91}
92
93} // namespace
94
95void LockAllMemory() {
Austin Schuhcc6070c2020-10-10 20:25:56 -070096 CheckNotRealtime();
Alex Perrycb7da4b2019-08-28 19:35:56 -070097 // Allow locking as much as we want into RAM.
Austin Schuh27553152020-11-18 21:26:37 -080098 SetSoftRLimit(RLIMIT_MEMLOCK, RLIM_INFINITY, SetLimitForRoot::kNo,
99 "use --skip_locking_memory to not lock memory.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700100
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
Philipp Schrader36d77932024-02-01 18:31:19 -0800164std::ostream &operator<<(std::ostream &stream, const cpu_set_t &cpuset) {
165 stream << "{CPUs ";
166 bool first_found = false;
167 for (int i = 0; i < CPU_SETSIZE; ++i) {
168 if (CPU_ISSET(i, &cpuset)) {
169 if (first_found) {
170 stream << ", ";
171 }
172 stream << i;
173 first_found = true;
174 }
175 }
176 stream << "}";
177 return stream;
178}
179
Brian Silverman6a54ff32020-04-28 16:41:39 -0700180void SetCurrentThreadAffinity(const cpu_set_t &cpuset) {
Philipp Schrader36d77932024-02-01 18:31:19 -0800181 PCHECK(sched_setaffinity(0, sizeof(cpuset), &cpuset) == 0) << cpuset;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700182}
183
James Kuszmaul57c2baa2020-01-19 14:52:52 -0800184void SetCurrentThreadName(const std::string_view name) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700185 CHECK_LE(name.size(), 16u) << ": thread name '" << name << "' too long";
186 VLOG(1) << "This thread is changing to '" << name << "'";
James Kuszmaul57c2baa2020-01-19 14:52:52 -0800187 std::string string_name(name);
Brian Silverman6a54ff32020-04-28 16:41:39 -0700188 PCHECK(prctl(PR_SET_NAME, string_name.c_str()) == 0)
189 << ": changing name to " << string_name;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700190 if (&logging::internal::ReloadThreadName != nullptr) {
191 logging::internal::ReloadThreadName();
192 }
193}
194
Austin Schuhde973292021-10-12 18:09:49 -0700195cpu_set_t GetCurrentThreadAffinity() {
196 cpu_set_t result;
197 PCHECK(sched_getaffinity(0, sizeof(result), &result) == 0);
198 return result;
199}
200
Alex Perrycb7da4b2019-08-28 19:35:56 -0700201void SetCurrentThreadRealtimePriority(int priority) {
James Kuszmaula791b762023-07-13 14:56:21 -0700202 // Ensure that we won't get expensive reads of /dev/random when the realtime
203 // scheduler is running.
204 UUID::Random();
205
Austin Schuh27553152020-11-18 21:26:37 -0800206 if (FLAGS_skip_realtime_scheduler) {
207 LOG(WARNING) << "Ignoring request to switch to the RT scheduler due to "
208 "--skip_realtime_scheduler.";
209 return;
210 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700211 // Make sure we will only be allowed to run for 3 seconds straight.
Austin Schuh27553152020-11-18 21:26:37 -0800212 SetSoftRLimit(
213 RLIMIT_RTTIME, 3000000, SetLimitForRoot::kYes,
214 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
215 "warning.");
Alex Perrycb7da4b2019-08-28 19:35:56 -0700216
Brian Silvermanb3826f52020-07-02 19:41:18 -0700217 // Raise our soft rlimit if necessary.
Austin Schuh27553152020-11-18 21:26:37 -0800218 SetSoftRLimit(
219 RLIMIT_RTPRIO, priority, SetLimitForRoot::kNo,
220 ", use --skip_realtime_scheduler to stay non-rt and bypass this "
221 "warning.",
222 AllowSoftLimitDecrease::kNo);
Brian Silvermanb3826f52020-07-02 19:41:18 -0700223
Alex Perrycb7da4b2019-08-28 19:35:56 -0700224 struct sched_param param;
225 param.sched_priority = priority;
Austin Schuhcc6070c2020-10-10 20:25:56 -0700226 MarkRealtime(true);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700227 PCHECK(sched_setscheduler(0, SCHED_FIFO, &param) == 0)
Austin Schuh27553152020-11-18 21:26:37 -0800228 << ": changing to SCHED_FIFO with " << priority
229 << ", if you want to bypass this check for testing, use "
230 "--skip_realtime_scheduler";
Alex Perrycb7da4b2019-08-28 19:35:56 -0700231}
232
233void WriteCoreDumps() {
234 // Do create core files of unlimited size.
Austin Schuh27553152020-11-18 21:26:37 -0800235 SetSoftRLimit(RLIMIT_CORE, RLIM_INFINITY, SetLimitForRoot::kYes, "");
James Kuszmaulb4874eb2020-01-18 17:50:35 -0800236}
237
238void ExpandStackSize() {
Austin Schuh27553152020-11-18 21:26:37 -0800239 SetSoftRLimit(RLIMIT_STACK, 1000000, SetLimitForRoot::kYes, "",
James Kuszmaulb4874eb2020-01-18 17:50:35 -0800240 AllowSoftLimitDecrease::kNo);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700241}
242
Austin Schuhcc6070c2020-10-10 20:25:56 -0700243namespace {
Austin Schuhf239e332021-07-30 15:27:26 -0700244// Bool to track if malloc hooks have failed to be configured.
245bool has_malloc_hook = true;
Austin Schuhf7bfb652023-08-25 14:22:50 -0700246thread_local bool is_realtime = false;
Tyler Chatowbf0609c2021-07-31 16:13:27 -0700247} // namespace
Austin Schuhcc6070c2020-10-10 20:25:56 -0700248
249bool MarkRealtime(bool realtime) {
Austin Schuhf239e332021-07-30 15:27:26 -0700250 if (realtime) {
251 // For some applications (generally tools built for the host in Bazel), we
252 // don't have malloc hooks available, but we also don't go realtime. Delay
253 // complaining in that case until we try to go RT and it matters.
Victor Valenciab009bfc2022-09-30 13:30:11 -0700254#if !__has_feature(address_sanitizer) && !__has_feature(memory_sanitizer)
Austin Schuhf239e332021-07-30 15:27:26 -0700255 CHECK(has_malloc_hook)
256 << ": Failed to register required malloc hooks before going realtime. "
257 "Disable --die_on_malloc to continue.";
Victor Valenciab009bfc2022-09-30 13:30:11 -0700258#endif
Austin Schuhf239e332021-07-30 15:27:26 -0700259 }
Austin Schuhcc6070c2020-10-10 20:25:56 -0700260 const bool prior = is_realtime;
261 is_realtime = realtime;
262 return prior;
263}
264
265void CheckRealtime() { CHECK(is_realtime); }
266
267void CheckNotRealtime() { CHECK(!is_realtime); }
268
269ScopedRealtimeRestorer::ScopedRealtimeRestorer() : prior_(is_realtime) {}
270
Austin Schuh62288252020-11-18 23:26:04 -0800271void NewHook(const void *ptr, size_t size) {
272 if (is_realtime) {
273 is_realtime = false;
274 RAW_LOG(FATAL, "Malloced %p -> %zu bytes", ptr, size);
275 }
276}
277
278void DeleteHook(const void *ptr) {
Austin Schuhf239e332021-07-30 15:27:26 -0700279 // It is legal to call free(nullptr) unconditionally and assume that it won't
280 // do anything. Eigen does this. So, if we are RT, ignore any of these
281 // calls.
282 if (is_realtime && ptr != nullptr) {
Austin Schuh62288252020-11-18 23:26:04 -0800283 is_realtime = false;
284 RAW_LOG(FATAL, "Delete Hook %p", ptr);
285 }
286}
287
Tyler Chatow582c6c72021-07-16 13:45:07 -0700288extern "C" {
289
290// malloc hooks for libc. Tcmalloc will replace everything it finds (malloc,
291// __libc_malloc, etc.), so we need its specific hook above as well.
292void *aos_malloc_hook(size_t size) {
293 if (FLAGS_die_on_malloc && aos::is_realtime) {
294 aos::is_realtime = false;
295 RAW_LOG(FATAL, "Malloced %zu bytes", size);
296 return nullptr;
297 } else {
298 return __libc_malloc(size);
299 }
300}
301
302void aos_free_hook(void *ptr) {
303 if (FLAGS_die_on_malloc && aos::is_realtime && ptr != nullptr) {
304 aos::is_realtime = false;
305 RAW_LOG(FATAL, "Deleted %p", ptr);
306 } else {
307 __libc_free(ptr);
308 }
309}
310
311void *malloc(size_t size) __attribute__((weak, alias("aos_malloc_hook")));
312void free(void *ptr) __attribute__((weak, alias("aos_free_hook")));
Tyler Chatow582c6c72021-07-16 13:45:07 -0700313}
314
Austin Schuh77f3f222022-06-10 16:49:21 -0700315void FatalUnsetRealtimePriority() {
Austin Schuh4737ad62022-12-30 14:47:03 -0800316 int saved_errno = errno;
Austin Schuh77f3f222022-06-10 16:49:21 -0700317 // Drop our priority first. We are about to do lots of work to undo
318 // everything, don't get overly clever.
319 struct sched_param param;
Austin Schuh4737ad62022-12-30 14:47:03 -0800320 param.sched_priority = 0;
Austin Schuh77f3f222022-06-10 16:49:21 -0700321 sched_setscheduler(0, SCHED_OTHER, &param);
322
323 is_realtime = false;
324
325 // Put all sub-tasks back to non-rt priority too.
326 DIR *dirp = opendir("/proc/self/task");
327 if (dirp) {
328 struct dirent *directory_entry;
329 while ((directory_entry = readdir(dirp)) != NULL) {
330 int thread_id = std::atoi(directory_entry->d_name);
331
332 // ignore . and .. which are zeroes for some reason
333 if (thread_id != 0) {
334 struct sched_param param;
Austin Schuh4737ad62022-12-30 14:47:03 -0800335 param.sched_priority = 0;
Austin Schuh77f3f222022-06-10 16:49:21 -0700336 sched_setscheduler(thread_id, SCHED_OTHER, &param);
337 }
338 }
339 closedir(dirp);
340 }
Austin Schuh4737ad62022-12-30 14:47:03 -0800341 errno = saved_errno;
Austin Schuh77f3f222022-06-10 16:49:21 -0700342}
343
Austin Schuh62288252020-11-18 23:26:04 -0800344void RegisterMallocHook() {
345 if (FLAGS_die_on_malloc) {
Tyler Chatow582c6c72021-07-16 13:45:07 -0700346 // tcmalloc redefines __libc_malloc, so use this as a feature test.
347 if (&__libc_malloc == &tc_malloc) {
James Kuszmaul4af7fa62023-08-05 13:33:22 -0700348 if (VLOG_IS_ON(1)) {
349 RAW_LOG(INFO, "Hooking tcmalloc for die_on_malloc");
350 }
Tyler Chatow582c6c72021-07-16 13:45:07 -0700351 if (&MallocHook_AddNewHook != nullptr) {
352 CHECK(MallocHook_AddNewHook(&NewHook));
353 } else {
354 has_malloc_hook = false;
355 }
356 if (&MallocHook_AddDeleteHook != nullptr) {
357 CHECK(MallocHook_AddDeleteHook(&DeleteHook));
358 } else {
359 has_malloc_hook = false;
360 }
Austin Schuh62288252020-11-18 23:26:04 -0800361 } else {
Austin Schuh6d8afc02023-05-28 13:27:42 -0700362 if (VLOG_IS_ON(1)) {
363 RAW_LOG(INFO, "Replacing glibc malloc");
364 }
Tyler Chatow582c6c72021-07-16 13:45:07 -0700365 if (&malloc != &aos_malloc_hook) {
366 has_malloc_hook = false;
367 }
368 if (&free != &aos_free_hook) {
369 has_malloc_hook = false;
370 }
Austin Schuh62288252020-11-18 23:26:04 -0800371 }
372 }
373}
374
Alex Perrycb7da4b2019-08-28 19:35:56 -0700375} // namespace aos