blob: 8b6bb2a8c46166b404c642e663ee8a339783d7e4 [file] [log] [blame]
Austin Schuh608514f2022-12-30 15:51:30 -08001#include <linux/securebits.h>
2#include <pwd.h>
3#include <sys/prctl.h>
Austin Schuha63163e2023-02-24 16:18:18 -08004#include <sys/resource.h>
Austin Schuh608514f2022-12-30 15:51:30 -08005#include <sys/types.h>
6
Philipp Schrader790cb542023-07-05 21:06:52 -07007#include "gflags/gflags.h"
8
Austin Schuh608514f2022-12-30 15:51:30 -08009#include "aos/events/shm_event_loop.h"
10#include "aos/init.h"
11#include "aos/starter/irq_affinity_lib.h"
12#include "aos/starter/kthread_generated.h"
13#include "aos/util/top.h"
Austin Schuh608514f2022-12-30 15:51:30 -080014
15DEFINE_string(config, "aos_config.json", "File path of aos configuration");
16
17DEFINE_string(user, "",
18 "Starter runs as though this user ran a SUID binary if set.");
Alexander Yeee61cac32023-02-11 19:40:40 -080019DEFINE_string(irq_config, "rockpi_config.json",
20 "File path of rockpi configuration");
Austin Schuh608514f2022-12-30 15:51:30 -080021
22namespace aos {
23
24cpu_set_t AffinityFromFlatbuffer(const flatbuffers::Vector<uint8_t> *v) {
25 cpu_set_t affinity;
26 CPU_ZERO(&affinity);
27 if (v == nullptr) {
28 for (int i = 0; i < CPU_SETSIZE; ++i) {
29 CPU_SET(i, &affinity);
30 }
31 } else {
32 for (uint8_t cpu : *v) {
33 CPU_SET(cpu, &affinity);
34 }
35 }
36 return affinity;
37}
38
39// Class to hold the configuration for an IRQ.
40struct ParsedIrqConfig {
41 std::string name;
42 cpu_set_t affinity;
43
44 void ConfigureIrq(int interrupt_number) const {
45 const std::string affinity_filename =
46 absl::StrCat("/proc/irq/", interrupt_number, "/smp_affinity");
47 const std::string contents = util::ReadFileToStringOrDie(affinity_filename);
48
49 std::string new_contents = std::string(contents.size() - 1, '0');
50
51 // Contents will be a padded string which is the size of the number of
52 // IRQs.
53 CHECK(!(CPU_SETSIZE & 0xf));
54 for (size_t i = 0; i < CPU_SETSIZE; i += 4) {
55 if (i / 4 >= new_contents.size()) {
56 break;
57 }
58 uint8_t byte = 0;
59 if (CPU_ISSET(i + 0, &affinity)) {
60 byte |= 1;
61 }
62 if (CPU_ISSET(i + 1, &affinity)) {
63 byte |= 2;
64 }
65 if (CPU_ISSET(i + 2, &affinity)) {
66 byte |= 4;
67 }
68 if (CPU_ISSET(i + 3, &affinity)) {
69 byte |= 8;
70 }
71 if (byte < 10) {
72 new_contents[new_contents.size() - 1 - i / 4] = '0' + byte;
73 } else {
74 new_contents[new_contents.size() - 1 - i / 4] = 'a' + (byte - 10);
75 }
76 }
77
78 if (contents != new_contents) {
79 util::WriteStringToFileOrDie(affinity_filename, new_contents);
80 }
81 }
82};
83
84// Class to hold the configuration for a kthread.
85struct ParsedKThreadConfig {
86 bool full_match = false;
87 std::string prefix;
88 std::string postfix;
89 starter::Scheduler scheduler;
90 int priority;
Austin Schuha63163e2023-02-24 16:18:18 -080091 std::optional<int> nice;
Austin Schuh608514f2022-12-30 15:51:30 -080092 cpu_set_t affinity;
93
94 bool Matches(std::string_view candidate) const {
95 if (full_match) {
96 return candidate == prefix;
97 } else {
98 if (candidate.size() < prefix.size() + postfix.size()) {
99 return false;
100 }
101 if (candidate.substr(0, prefix.size()) != prefix) {
102 return false;
103 }
104 if (candidate.substr(candidate.size() - postfix.size(), postfix.size()) !=
105 postfix) {
106 return false;
107 }
108 return true;
109 }
110 }
111
112 void ConfigurePid(pid_t pid) const {
Austin Schuha63163e2023-02-24 16:18:18 -0800113 struct sched_param param;
114 param.sched_priority = priority;
115 int new_scheduler;
116 switch (scheduler) {
117 case starter::Scheduler::SCHEDULER_OTHER:
118 new_scheduler = SCHED_OTHER;
119 break;
120 case starter::Scheduler::SCHEDULER_RR:
121 new_scheduler = SCHED_RR;
122 break;
123 case starter::Scheduler::SCHEDULER_FIFO:
124 new_scheduler = SCHED_FIFO;
125 break;
126 default:
127 LOG(FATAL) << "Unknown scheduler";
Austin Schuh608514f2022-12-30 15:51:30 -0800128 }
Austin Schuha63163e2023-02-24 16:18:18 -0800129 PCHECK(sched_setscheduler(pid, new_scheduler, &param) == 0);
130
131 if (scheduler == starter::Scheduler::SCHEDULER_OTHER && nice.has_value()) {
132 PCHECK(setpriority(PRIO_PROCESS, pid, *nice) == 0)
133 << ": Failed to set priority";
134 }
135
Austin Schuh608514f2022-12-30 15:51:30 -0800136 PCHECK(sched_setaffinity(pid, sizeof(affinity), &affinity) == 0);
137 }
138};
139
140// TODO(austin): Clean this up a bit, and maybe we can add some tests.
141class IrqAffinity {
142 public:
143 IrqAffinity(
144 EventLoop *event_loop,
145 const aos::FlatbufferDetachedBuffer<aos::starter::IrqAffinityConfig>
146 &irq_affinity_config)
147 : top_(event_loop) {
148 if (irq_affinity_config.message().has_kthreads()) {
Austin Schuh4ec20622023-03-11 15:11:50 -0800149 PopulateThreads(irq_affinity_config.message().kthreads(), &kthreads_);
150 }
151 if (irq_affinity_config.message().has_threads()) {
152 PopulateThreads(irq_affinity_config.message().threads(), &threads_);
Austin Schuh608514f2022-12-30 15:51:30 -0800153 }
154
155 if (irq_affinity_config.message().has_irqs()) {
156 irqs_.reserve(irq_affinity_config.message().irqs()->size());
157 for (const starter::IrqConfig *irq_config :
158 *irq_affinity_config.message().irqs()) {
159 CHECK(irq_config->has_name()) << ": Name required";
160 LOG(INFO) << "IRQ " << aos::FlatbufferToJson(irq_config);
161 irqs_.push_back(ParsedIrqConfig{
162 .name = irq_config->name()->str(),
163 .affinity = AffinityFromFlatbuffer(irq_config->affinity()),
164 });
165 }
166 }
167
168 top_.set_track_top_processes(true);
169 top_.set_on_reading_update([this]() {
170 for (const std::pair<const pid_t, util::Top::ProcessReadings> &reading :
171 top_.readings()) {
172 if (reading.second.kthread) {
173 for (const ParsedKThreadConfig &match : kthreads_) {
174 if (match.Matches(reading.second.name)) {
175 match.ConfigurePid(reading.first);
176 break;
177 }
178 }
Austin Schuh4ec20622023-03-11 15:11:50 -0800179 } else {
180 for (const ParsedKThreadConfig &match : threads_) {
181 if (match.Matches(reading.second.name)) {
182 match.ConfigurePid(reading.first);
183 break;
184 }
185 }
Austin Schuh608514f2022-12-30 15:51:30 -0800186 }
187 }
188
189 interrupts_status_.Update();
190
191 for (const InterruptsStatus::InterruptState &state :
192 interrupts_status_.states()) {
193 for (const ParsedIrqConfig &match : irqs_) {
194 bool matched = false;
195 for (const std::string &action : state.actions) {
196 if (match.name == action) {
197 matched = true;
198 break;
199 }
200 }
201 if (matched) {
202 match.ConfigureIrq(state.interrupt_number);
203 }
204 }
205 }
206 });
207 }
208
209 private:
Austin Schuh4ec20622023-03-11 15:11:50 -0800210 void PopulateThreads(
211 const flatbuffers::Vector<flatbuffers::Offset<starter::KthreadConfig>>
212 *threads_config,
213 std::vector<ParsedKThreadConfig> *threads) {
214 threads->reserve(threads_config->size());
215 for (const starter::KthreadConfig *kthread_config : *threads_config) {
216 LOG(INFO) << "Kthread " << aos::FlatbufferToJson(kthread_config);
217 CHECK(kthread_config->has_name()) << ": Name required";
218 const size_t star_position =
219 kthread_config->name()->string_view().find('*');
220 const bool has_star = star_position != std::string_view::npos;
221
222 threads->push_back(ParsedKThreadConfig{
223 .full_match = !has_star,
224 .prefix = std::string(
225 !has_star ? kthread_config->name()->string_view()
226 : kthread_config->name()->string_view().substr(
227 0, star_position)),
228 .postfix = std::string(
229 !has_star ? ""
230 : kthread_config->name()->string_view().substr(
231 star_position + 1)),
232 .scheduler = kthread_config->scheduler(),
233 .priority = kthread_config->priority(),
234 .nice = kthread_config->nice(),
235 .affinity = AffinityFromFlatbuffer(kthread_config->affinity()),
236 });
237 }
238 }
239
Austin Schuh608514f2022-12-30 15:51:30 -0800240 util::Top top_;
241
242 // TODO(austin): Publish message with everything in it.
243 // TODO(austin): Make Top report out affinity + priority + scheduler for
244 // posterity.
245
246 std::vector<ParsedKThreadConfig> kthreads_;
Austin Schuh4ec20622023-03-11 15:11:50 -0800247 std::vector<ParsedKThreadConfig> threads_;
Austin Schuh608514f2022-12-30 15:51:30 -0800248 std::vector<ParsedIrqConfig> irqs_;
249
250 InterruptsStatus interrupts_status_;
251};
252
253} // namespace aos
254
255int main(int argc, char **argv) {
256 aos::InitGoogle(&argc, &argv);
257
258 if (!FLAGS_user.empty()) {
259 // Maintain root permissions as we switch to become the user so we can
260 // actually manipulate priorities.
261 PCHECK(prctl(PR_SET_SECUREBITS, SECBIT_NO_SETUID_FIXUP | SECBIT_NOROOT) ==
262 0);
263
264 uid_t uid;
265 uid_t gid;
266 {
267 struct passwd *user_data = getpwnam(FLAGS_user.c_str());
268 if (user_data != nullptr) {
269 uid = user_data->pw_uid;
270 gid = user_data->pw_gid;
271 } else {
272 LOG(FATAL) << "Could not find user " << FLAGS_user;
273 return 1;
274 }
275 }
276 // Change the real and effective IDs to the user we're running as. The
277 // effective IDs mean files we access (like shared memory) will happen as
278 // that user. The real IDs allow child processes with an different effective
279 // ID to still participate in signal sending/receiving.
280 constexpr int kUnchanged = -1;
281 if (setresgid(/* ruid */ gid, /* euid */ gid,
282 /* suid */ kUnchanged) != 0) {
283 PLOG(FATAL) << "Failed to change GID to " << FLAGS_user;
284 }
285
286 if (setresuid(/* ruid */ uid, /* euid */ uid,
287 /* suid */ kUnchanged) != 0) {
288 PLOG(FATAL) << "Failed to change UID to " << FLAGS_user;
289 }
290 }
291
292 aos::FlatbufferDetachedBuffer<aos::Configuration> config =
293 aos::configuration::ReadConfig(FLAGS_config);
294
Austin Schuh608514f2022-12-30 15:51:30 -0800295 aos::FlatbufferDetachedBuffer<aos::starter::IrqAffinityConfig>
296 irq_affinity_config =
Alexander Yeee61cac32023-02-11 19:40:40 -0800297 aos::JsonFileToFlatbuffer<aos::starter::IrqAffinityConfig>(
298 FLAGS_irq_config);
Austin Schuh608514f2022-12-30 15:51:30 -0800299
300 aos::ShmEventLoop shm_event_loop(&config.message());
301
302 aos::IrqAffinity irq_affinity(&shm_event_loop, irq_affinity_config);
303
304 shm_event_loop.Run();
305
306 return 0;
307}