1use crate::cpuset::CpuSet;
6use crate::finding::{Finding, HotSet, Role, Severity};
7use crate::host::{Host, ReadError};
8use crate::platform::{Arch, Platform};
9
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum Thread {
13 Current,
15 Task(u32),
18}
19
20impl Thread {
21 pub(crate) fn file(self, name: &str) -> String {
22 match self {
23 Self::Current => format!("/proc/thread-self/{name}"),
24 Self::Task(tid) => format!("/proc/self/task/{tid}/{name}"),
25 }
26 }
27}
28
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31#[non_exhaustive]
32pub enum SchedPolicy {
33 Other,
35 Fifo,
37 RoundRobin,
39 Batch,
41 Idle,
43 Deadline,
45 Unrecognised(u32),
47}
48
49impl SchedPolicy {
50 const fn from_number(n: u32) -> Self {
51 match n {
52 0 => Self::Other,
53 1 => Self::Fifo,
54 2 => Self::RoundRobin,
55 3 => Self::Batch,
56 5 => Self::Idle,
57 6 => Self::Deadline,
58 other => Self::Unrecognised(other),
59 }
60 }
61
62 #[must_use]
64 pub fn name(self) -> String {
65 match self {
66 Self::Other => "SCHED_OTHER".to_owned(),
67 Self::Fifo => "SCHED_FIFO".to_owned(),
68 Self::RoundRobin => "SCHED_RR".to_owned(),
69 Self::Batch => "SCHED_BATCH".to_owned(),
70 Self::Idle => "SCHED_IDLE".to_owned(),
71 Self::Deadline => "SCHED_DEADLINE".to_owned(),
72 Self::Unrecognised(n) => format!("policy {n}"),
73 }
74 }
75}
76
77pub fn thread_policy(host: &Host, thread: Thread) -> Result<SchedPolicy, ReadError> {
83 let path = thread.file("stat");
84 let text = host.read(&path)?;
85 let malformed = |detail| ReadError::Malformed {
86 path: path.clone(),
87 detail,
88 };
89 let (_, after_comm) = text
90 .rsplit_once(')')
91 .ok_or_else(|| malformed("no command name"))?;
92 let policy = after_comm
94 .split_whitespace()
95 .nth(41 - 3)
96 .ok_or_else(|| malformed("fewer fields than a stat line has"))?;
97 let n: u32 = policy
98 .parse()
99 .map_err(|_| malformed("policy not a number"))?;
100 Ok(SchedPolicy::from_number(n))
101}
102
103pub fn thread_affinity(host: &Host, thread: Thread) -> Result<CpuSet, ReadError> {
108 let path = thread.file("status");
109 let text = host.read(&path)?;
110 let list = text
111 .lines()
112 .find_map(|l| l.strip_prefix("Cpus_allowed_list:"))
113 .ok_or_else(|| ReadError::Malformed {
114 path: path.clone(),
115 detail: "no Cpus_allowed_list line",
116 })?;
117 CpuSet::parse_list(list).map_err(|e| ReadError::cpus(&path, e))
118}
119
120pub fn isolated_cpus(host: &Host) -> Result<CpuSet, ReadError> {
130 let boot = host.read_cpu_list("/sys/devices/system/cpu/isolated")?;
131 let partitions = host
132 .read_cpu_list("/sys/fs/cgroup/cpuset.cpus.isolated")
133 .unwrap_or_default();
134 Ok(boot.union(&partitions))
135}
136
137pub fn spare(host: &Host, busy: &CpuSet) -> Option<CpuSet> {
139 host.read_cpu_list("/sys/devices/system/cpu/online")
140 .map(|online| online.difference(busy))
141 .ok()
142 .filter(|s| !s.is_empty())
143}
144
145pub fn housekeeping(host: &Host, busy: &CpuSet) -> String {
148 spare(host, busy).map_or_else(|| "<housekeeping CPUs>".to_owned(), |s| s.to_string())
149}
150
151const T1_EVIDENCE: &str = "Linux \
152 Documentation/timers/no_hz.rst and admin-guide/kernel-parameters.txt (isolcpus, nohz_full, \
153 rcu_nocbs, irqaffinity)";
154
155struct T1<'a> {
157 cpus: &'a HotSet,
158 spinning: CpuSet,
159 tickless: CpuSet,
163 all: String,
165 target: CpuSet,
168 hk: String,
169 boot: String,
170}
171
172impl T1<'_> {
173 const fn finding(message: String) -> Finding {
174 Finding::found("T1", Severity::Warn, T1_EVIDENCE, message)
175 }
176
177 fn unknown(message: String, e: &ReadError) -> Finding {
178 Finding::unknown("T1", Severity::Warn, T1_EVIDENCE, message, e)
179 }
180
181 fn domain(&self, isolated: &Result<CpuSet, ReadError>, out: &mut Vec<Finding>) {
182 let isolated = match isolated {
183 Ok(i) => i,
184 Err(e) => {
185 out.push(Self::unknown(
186 format!("cannot tell whether {} are isolated", self.all),
187 e,
188 ));
189 return;
190 }
191 };
192 for cpu in self.spinning.difference(isolated).iter() {
193 out.push(Self::finding(format!(
194 "{} is not isolated: the scheduler balances other tasks onto it, and \
195 each one pauses the loop. Fix: {}",
196 self.cpus.describe(cpu),
197 self.boot
198 )));
199 }
200 }
201
202 fn nohz(&self, nohz: &Result<Option<CpuSet>, ReadError>, out: &mut Vec<Finding>) {
203 let nohz = match nohz {
204 Ok(n) => n,
205 Err(e) => {
206 out.push(Self::unknown(
207 format!("cannot tell whether {} are nohz_full", self.all),
208 e,
209 ));
210 return;
211 }
212 };
213 let (missing, kernel, fix) = nohz.as_ref().map_or_else(
214 || {
215 (
216 self.tickless.clone(),
217 "this kernel has no NO_HZ_FULL (no /sys/devices/system/cpu/nohz_full), so ",
218 format!(
219 "use a kernel built with CONFIG_NO_HZ_FULL=y and {}",
220 self.boot
221 ),
222 )
223 },
224 |n| (self.tickless.difference(n), "", self.boot.clone()),
225 );
226 for cpu in missing.iter() {
227 out.push(Self::finding(format!(
228 "{} is not nohz_full: {kernel}its scheduler tick keeps firing, CONFIG_HZ times a \
229 second, and each local-timer interrupt pauses the loop; isolcpus alone leaves \
230 it on. Fix: {fix}",
231 self.cpus.describe(cpu)
232 )));
233 }
234 }
235
236 fn ok(&self, nohz: &Result<Option<CpuSet>, ReadError>) -> Finding {
238 let ticking = match nohz {
239 Ok(Some(n)) => self.spinning.difference(n),
240 Ok(None) => self.spinning.clone(),
241 Err(_) => CpuSet::new(),
242 };
243 let message = if ticking.is_empty() {
244 format!(
245 "{}: isolated, nohz_full and outside default_smp_affinity",
246 self.all
247 )
248 } else {
249 format!(
250 "{}: isolated and outside default_smp_affinity; nohz_full but for {}, which \
251 holds only the SQPOLL thread (not asked there; not measured)",
252 self.all,
253 self.cpus.describe_all(&ticking)
254 )
255 };
256 Finding::ok("T1", Severity::Warn, T1_EVIDENCE, message)
257 }
258
259 fn default_affinity(&self, host: &Host, out: &mut Vec<Finding>) {
260 let path = "/proc/irq/default_smp_affinity";
261 let mask = match host
262 .read(path)
263 .and_then(|t| CpuSet::parse_mask(&t).map_err(|e| ReadError::cpus(path, e)))
264 {
265 Ok(m) => m,
266 Err(e) => {
267 out.push(Self::unknown(
268 format!(
269 "cannot tell whether {} are outside the default IRQ affinity",
270 self.all
271 ),
272 &e,
273 ));
274 return;
275 }
276 };
277 let in_mask = self.spinning.intersection(&mask);
278 if in_mask.is_empty() {
279 return;
280 }
281 let hk_mask = spare(host, &self.target)
282 .map_or_else(|| "<housekeeping mask>".to_owned(), |s| s.to_mask());
283 out.push(Self::finding(format!(
284 "{} {} in /proc/irq/default_smp_affinity ({}): interrupts set up from now on may be \
285 placed there. Fix: `echo {hk_mask} > /proc/irq/default_smp_affinity`, or boot with \
286 `irqaffinity={}`",
287 self.cpus.describe_all(&in_mask),
288 if in_mask.len() == 1 { "is" } else { "are" },
289 mask.to_mask(),
290 self.hk
291 )));
292 }
293}
294
295#[must_use]
304pub fn t1_isolation(host: &Host, cpus: &HotSet) -> Vec<Finding> {
305 let spinning = cpus.spinning();
306 if spinning.is_empty() {
307 return vec![Finding::ok(
308 "T1",
309 Severity::Warn,
310 T1_EVIDENCE,
311 "no busy-spinning CPU to check".to_owned(),
312 )];
313 }
314 let isolated = isolated_cpus(host);
315 let nohz_path = "/sys/devices/system/cpu/nohz_full";
316 let nohz = host.read_optional(nohz_path).and_then(|t| {
317 t.map(|t| CpuSet::parse_list(&t).map_err(|e| ReadError::cpus(nohz_path, e)))
318 .transpose()
319 });
320 let none = CpuSet::new();
321 let target = spinning
322 .union(isolated.as_ref().unwrap_or(&none))
323 .union(nohz.as_ref().ok().and_then(Option::as_ref).unwrap_or(&none));
324 let hk = housekeeping(host, &target);
325 let boot = format!(
326 "boot with `isolcpus=nohz,domain,managed_irq,{target} nohz_full={target} \
327 rcu_nocbs={target} irqaffinity={hk}`"
328 );
329 let tickless = cpus
330 .iter()
331 .filter(|h| h.role.spins() && h.role != Role::SqPoll)
332 .map(|h| h.cpu)
333 .collect();
334 let t1 = T1 {
335 cpus,
336 all: cpus.describe_all(&spinning),
337 spinning,
338 tickless,
339 target,
340 hk,
341 boot,
342 };
343 let mut out = Vec::new();
344 t1.domain(&isolated, &mut out);
345 t1.nohz(&nohz, &mut out);
346 t1.default_affinity(host, &mut out);
347 if out.is_empty() {
348 out.push(t1.ok(&nohz));
349 }
350 out
351}
352
353const T7_EVIDENCE: &str = "Linux Documentation/scheduler/sched-rt-group.rst; not measured here";
354
355#[must_use]
358pub fn t7_sched_policy(host: &Host, thread: Thread, role: Role) -> Finding {
359 let id = "T7";
360 let sev = Severity::Warn;
361 let who = format!("the {} thread", role.name());
362 match thread_policy(host, thread) {
363 Ok(p @ (SchedPolicy::Fifo | SchedPolicy::RoundRobin)) => {
364 let throttle = match host.read_i64("/proc/sys/kernel/sched_rt_runtime_us") {
365 Ok(-1) => " (RT throttling is off here, sched_rt_runtime_us -1: nothing else gets \
366 that CPU)"
367 .to_owned(),
368 Ok(us) => {
369 let period = host
370 .read_i64("/proc/sys/kernel/sched_rt_period_us")
371 .map_or_else(|_| "its period".to_owned(), |p| format!("{p} µs"));
372 format!(" (sched_rt_runtime_us {us} of {period})")
373 }
374 Err(_) => String::new(),
375 };
376 Finding::found(
377 id,
378 sev,
379 T7_EVIDENCE,
380 format!(
381 "{who} runs {}: RT throttling can take the CPU away{throttle}; its latency \
382 effect is not measured here. Fix: run it SCHED_OTHER on an isolated CPU \
383 (`chrt --other -p 0 <tid>`)",
384 p.name()
385 ),
386 )
387 }
388 Ok(p) => Finding::ok(id, sev, T7_EVIDENCE, format!("{who} runs {}", p.name())),
389 Err(e) => Finding::unknown(
390 id,
391 sev,
392 T7_EVIDENCE,
393 format!("cannot tell {who}'s scheduling policy"),
394 e,
395 ),
396 }
397}
398
399const T8_EVIDENCE: &str = "SMT siblings share one core's execution units; a busy sibling and two \
400 threads on one CPU are not measured here";
401
402struct T8<'a> {
404 cpus: &'a HotSet,
405 isolated: Result<CpuSet, ReadError>,
406 pairs: Vec<(u32, u32)>,
407 smt: bool,
408 out: Vec<Finding>,
409}
410
411impl T8<'_> {
412 fn push(&mut self, severity: Severity, message: String) {
413 self.out
414 .push(Finding::found("T8", severity, T8_EVIDENCE, message));
415 }
416
417 fn same_cpu(&mut self, cpu: u32) {
419 let roles: Vec<&str> = self
420 .cpus
421 .roles(cpu)
422 .into_iter()
423 .filter(|r| r.spins())
424 .map(Role::name)
425 .collect();
426 if roles.len() > 1 {
427 self.push(
428 Severity::Warn,
429 format!(
430 "the {} are both on CPU {cpu}: two busy threads take turns on one CPU, so each \
431 waits for the other's time slice (not measured here). Fix: pin them to separate \
432 cores",
433 roles.join(" and ")
434 ),
435 );
436 }
437 }
438
439 fn sibling(&mut self, cpu: u32, s: u32) {
441 self.smt = true;
442 let roles = self.cpus.roles(s);
443 let busy = busy_on(self.cpus, s);
444 let (me, them) = (self.cpus.describe(cpu), self.cpus.describe(s));
445 if busy {
446 let pair = (cpu.min(s), cpu.max(s));
447 if self.pairs.contains(&pair) {
448 return;
449 }
450 self.pairs.push(pair);
451 if sqpoll_with_loop(self.cpus, cpu, s) {
452 return;
453 }
454 self.push(
455 Severity::Warn,
456 format!(
457 "{} and {} are hyperthreads of one core: two busy threads share its execution \
458 units. Fix: pin them to separate cores",
459 self.cpus.describe(pair.0),
460 self.cpus.describe(pair.1)
461 ),
462 );
463 } else if roles.contains(&Role::Housekeeping) {
464 self.push(
465 Severity::Info,
466 format!(
467 "{me} shares its core with {them}: what runs there takes the core's execution \
468 units from it (not measured here). Fix: \
469 keep CPU {s} idle, or give it a core of its own"
470 ),
471 );
472 } else {
473 match &self.isolated {
474 Ok(iso) if iso.contains(s) => {}
475 Ok(_) => self.push(
476 Severity::Info,
477 format!(
478 "{me} shares its core with CPU {s}, which is not isolated: other tasks run \
479 there and take the core's execution units from it (not measured \
480 here). Fix: isolate CPU {s} and leave it \
481 idle"
482 ),
483 ),
484 Err(e) => {
485 let f = Finding::unknown(
486 "T8",
487 Severity::Warn,
488 T8_EVIDENCE,
489 format!("cannot tell whether CPU {s}, {me}'s SMT sibling, is isolated"),
490 e,
491 );
492 self.out.push(f);
493 }
494 }
495 }
496 }
497}
498
499#[must_use]
509pub fn t8_smt_siblings(host: &Host, cpus: &HotSet) -> Vec<Finding> {
510 let spinning = cpus.spinning();
511 let mut t8 = T8 {
512 cpus,
513 isolated: isolated_cpus(host),
514 pairs: Vec::new(),
515 smt: false,
516 out: Vec::new(),
517 };
518 for cpu in spinning.iter() {
519 t8.same_cpu(cpu);
520 let path = format!("/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list");
521 match host.read_cpu_list(&path) {
522 Ok(siblings) => {
523 for s in siblings.iter().filter(|s| *s != cpu) {
524 t8.sibling(cpu, s);
525 }
526 }
527 Err(e) => t8.out.push(Finding::unknown(
528 "T8",
529 Severity::Warn,
530 T8_EVIDENCE,
531 format!("cannot tell {}'s SMT siblings", cpus.describe(cpu)),
532 e,
533 )),
534 }
535 }
536 if t8.out.is_empty() {
537 let all = cpus.describe_all(&spinning);
538 let message = if spinning.is_empty() {
539 "no busy-spinning CPU to check".to_owned()
540 } else if t8.smt {
541 format!("{all}: no other busy thread on their cores, and their siblings are isolated")
542 } else if Platform::detect(host).is_graviton() {
543 format!("{all}: one thread per core (Graviton has no SMT)")
544 } else {
545 format!("{all}: one thread per core (no SMT sibling)")
546 };
547 t8.out
548 .push(Finding::ok("T8", Severity::Warn, T8_EVIDENCE, message));
549 }
550 t8.out
551}
552
553pub fn busy_on(cpus: &HotSet, cpu: u32) -> bool {
556 cpus.roles(cpu)
557 .iter()
558 .any(|r| r.spins() || matches!(r, Role::Conductor | Role::EalLcore))
559}
560
561pub fn sqpoll_with_loop(cpus: &HotSet, a: u32, b: u32) -> bool {
564 let (ra, rb) = (cpus.roles(a), cpus.roles(b));
565 (ra.contains(&Role::Loop) && rb.contains(&Role::SqPoll) && !rb.contains(&Role::Loop))
566 || (rb.contains(&Role::Loop) && ra.contains(&Role::SqPoll) && !ra.contains(&Role::Loop))
567}
568
569const T10_EVIDENCE: &str = "AWS instance-optimize-cpu and instance-specify-cpu-options (CpuOptions ThreadsPerCore); \
570 kernel-parameters.txt (nosmt); ABI/testing/sysfs-devices-system-cpu (smt/active, smt/control)";
571
572fn smt_active(host: &Host) -> Result<bool, ReadError> {
575 if let Ok(line) = host.read_line("/sys/devices/system/cpu/smt/active") {
576 return match line.trim() {
577 "1" => Ok(true),
578 "0" => Ok(false),
579 _ => Err(ReadError::Malformed {
580 path: "/sys/devices/system/cpu/smt/active".to_owned(),
581 detail: "smt/active is neither 0 nor 1",
582 }),
583 };
584 }
585 let online = host.read_cpu_list("/sys/devices/system/cpu/online")?;
586 let mut saw_one = false;
587 for cpu in online.iter() {
588 let path = format!("/sys/devices/system/cpu/cpu{cpu}/topology/thread_siblings_list");
589 match host.read_cpu_list(&path) {
590 Ok(siblings) => {
591 saw_one = true;
592 if siblings.len() > 1 {
593 return Ok(true);
594 }
595 }
596 Err(ReadError::Io { .. }) => {}
597 Err(e) => return Err(e),
598 }
599 }
600 if saw_one {
601 Ok(false)
602 } else {
603 Err(ReadError::Malformed {
604 path: "/sys/devices/system/cpu".to_owned(),
605 detail: "no smt/active and no thread_siblings_list to fall back on",
606 })
607 }
608}
609
610#[must_use]
616pub fn t10_smt_on(host: &Host) -> Finding {
617 let id = "T10";
618 let sev = Severity::Warn;
619 let platform = Platform::detect(host);
620 if platform.is_graviton() || platform.arch == Arch::Aarch64 {
621 return Finding::ok(
622 id,
623 sev,
624 T10_EVIDENCE,
625 if platform.is_graviton() {
626 "Graviton: one vCPU is one physical core (no SMT)".to_owned()
627 } else {
628 "arm64: one vCPU is one physical core (no SMT)".to_owned()
629 },
630 );
631 }
632 match smt_active(host) {
633 Ok(false) => Finding::ok(
634 id,
635 sev,
636 T10_EVIDENCE,
637 "SMT is off: one vCPU is one physical core".to_owned(),
638 ),
639 Ok(true) => Finding::found(
640 id,
641 sev,
642 T10_EVIDENCE,
643 "SMT is on: on x86 a Kubernetes `cpu: 2` is one physical core, not two, and a busy \
644 sibling slows the loop: the two share the core's execution units (not measured \
645 here). Turn SMT off on the NODE. EKS/EC2: launch template \
646 `\"CpuOptions\": {\"CoreCount\": <the type's cores>, \"ThreadsPerCore\": 1}` (not \
647 possible on bare metal, or on T2, C7a, M7a, R7a, Apple silicon Mac \
648 or Graviton). Self-managed: \
649 boot with `nosmt` (`nosmt=force` cannot be undone at runtime), or `echo off > \
650 /sys/devices/system/cpu/smt/control` before the kubelet starts, then delete its \
651 cpu_manager_state so it re-pins. Or an instance type without SMT: \
652 one vCPU is one physical core"
653 .to_owned(),
654 ),
655 Err(e) => Finding::unknown(
656 id,
657 sev,
658 T10_EVIDENCE,
659 "cannot tell whether SMT is active on this host".to_owned(),
660 e,
661 ),
662 }
663}