psi.c 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Pressure stall information for CPU, memory and IO
  4. *
  5. * Copyright (c) 2018 Facebook, Inc.
  6. * Author: Johannes Weiner <hannes@cmpxchg.org>
  7. *
  8. * Polling support by Suren Baghdasaryan <surenb@google.com>
  9. * Copyright (c) 2018 Google, Inc.
  10. *
  11. * When CPU, memory and IO are contended, tasks experience delays that
  12. * reduce throughput and introduce latencies into the workload. Memory
  13. * and IO contention, in addition, can cause a full loss of forward
  14. * progress in which the CPU goes idle.
  15. *
  16. * This code aggregates individual task delays into resource pressure
  17. * metrics that indicate problems with both workload health and
  18. * resource utilization.
  19. *
  20. * Model
  21. *
  22. * The time in which a task can execute on a CPU is our baseline for
  23. * productivity. Pressure expresses the amount of time in which this
  24. * potential cannot be realized due to resource contention.
  25. *
  26. * This concept of productivity has two components: the workload and
  27. * the CPU. To measure the impact of pressure on both, we define two
  28. * contention states for a resource: SOME and FULL.
  29. *
  30. * In the SOME state of a given resource, one or more tasks are
  31. * delayed on that resource. This affects the workload's ability to
  32. * perform work, but the CPU may still be executing other tasks.
  33. *
  34. * In the FULL state of a given resource, all non-idle tasks are
  35. * delayed on that resource such that nobody is advancing and the CPU
  36. * goes idle. This leaves both workload and CPU unproductive.
  37. *
  38. * SOME = nr_delayed_tasks != 0
  39. * FULL = nr_delayed_tasks != 0 && nr_productive_tasks == 0
  40. *
  41. * What it means for a task to be productive is defined differently
  42. * for each resource. For IO, productive means a running task. For
  43. * memory, productive means a running task that isn't a reclaimer. For
  44. * CPU, productive means an on-CPU task.
  45. *
  46. * Naturally, the FULL state doesn't exist for the CPU resource at the
  47. * system level, but exist at the cgroup level. At the cgroup level,
  48. * FULL means all non-idle tasks in the cgroup are delayed on the CPU
  49. * resource which is being used by others outside of the cgroup or
  50. * throttled by the cgroup cpu.max configuration.
  51. *
  52. * The percentage of wall clock time spent in those compound stall
  53. * states gives pressure numbers between 0 and 100 for each resource,
  54. * where the SOME percentage indicates workload slowdowns and the FULL
  55. * percentage indicates reduced CPU utilization:
  56. *
  57. * %SOME = time(SOME) / period
  58. * %FULL = time(FULL) / period
  59. *
  60. * Multiple CPUs
  61. *
  62. * The more tasks and available CPUs there are, the more work can be
  63. * performed concurrently. This means that the potential that can go
  64. * unrealized due to resource contention *also* scales with non-idle
  65. * tasks and CPUs.
  66. *
  67. * Consider a scenario where 257 number crunching tasks are trying to
  68. * run concurrently on 256 CPUs. If we simply aggregated the task
  69. * states, we would have to conclude a CPU SOME pressure number of
  70. * 100%, since *somebody* is waiting on a runqueue at all
  71. * times. However, that is clearly not the amount of contention the
  72. * workload is experiencing: only one out of 256 possible execution
  73. * threads will be contended at any given time, or about 0.4%.
  74. *
  75. * Conversely, consider a scenario of 4 tasks and 4 CPUs where at any
  76. * given time *one* of the tasks is delayed due to a lack of memory.
  77. * Again, looking purely at the task state would yield a memory FULL
  78. * pressure number of 0%, since *somebody* is always making forward
  79. * progress. But again this wouldn't capture the amount of execution
  80. * potential lost, which is 1 out of 4 CPUs, or 25%.
  81. *
  82. * To calculate wasted potential (pressure) with multiple processors,
  83. * we have to base our calculation on the number of non-idle tasks in
  84. * conjunction with the number of available CPUs, which is the number
  85. * of potential execution threads. SOME becomes then the proportion of
  86. * delayed tasks to possible threads, and FULL is the share of possible
  87. * threads that are unproductive due to delays:
  88. *
  89. * threads = min(nr_nonidle_tasks, nr_cpus)
  90. * SOME = min(nr_delayed_tasks / threads, 1)
  91. * FULL = (threads - min(nr_productive_tasks, threads)) / threads
  92. *
  93. * For the 257 number crunchers on 256 CPUs, this yields:
  94. *
  95. * threads = min(257, 256)
  96. * SOME = min(1 / 256, 1) = 0.4%
  97. * FULL = (256 - min(256, 256)) / 256 = 0%
  98. *
  99. * For the 1 out of 4 memory-delayed tasks, this yields:
  100. *
  101. * threads = min(4, 4)
  102. * SOME = min(1 / 4, 1) = 25%
  103. * FULL = (4 - min(3, 4)) / 4 = 25%
  104. *
  105. * [ Substitute nr_cpus with 1, and you can see that it's a natural
  106. * extension of the single-CPU model. ]
  107. *
  108. * Implementation
  109. *
  110. * To assess the precise time spent in each such state, we would have
  111. * to freeze the system on task changes and start/stop the state
  112. * clocks accordingly. Obviously that doesn't scale in practice.
  113. *
  114. * Because the scheduler aims to distribute the compute load evenly
  115. * among the available CPUs, we can track task state locally to each
  116. * CPU and, at much lower frequency, extrapolate the global state for
  117. * the cumulative stall times and the running averages.
  118. *
  119. * For each runqueue, we track:
  120. *
  121. * tSOME[cpu] = time(nr_delayed_tasks[cpu] != 0)
  122. * tFULL[cpu] = time(nr_delayed_tasks[cpu] && !nr_productive_tasks[cpu])
  123. * tNONIDLE[cpu] = time(nr_nonidle_tasks[cpu] != 0)
  124. *
  125. * and then periodically aggregate:
  126. *
  127. * tNONIDLE = sum(tNONIDLE[i])
  128. *
  129. * tSOME = sum(tSOME[i] * tNONIDLE[i]) / tNONIDLE
  130. * tFULL = sum(tFULL[i] * tNONIDLE[i]) / tNONIDLE
  131. *
  132. * %SOME = tSOME / period
  133. * %FULL = tFULL / period
  134. *
  135. * This gives us an approximation of pressure that is practical
  136. * cost-wise, yet way more sensitive and accurate than periodic
  137. * sampling of the aggregate task states would be.
  138. */
  139. static int psi_bug __read_mostly;
  140. DEFINE_STATIC_KEY_FALSE(psi_disabled);
  141. static DEFINE_STATIC_KEY_TRUE(psi_cgroups_enabled);
  142. #ifdef CONFIG_PSI_DEFAULT_DISABLED
  143. static bool psi_enable;
  144. #else
  145. static bool psi_enable = true;
  146. #endif
  147. static int __init setup_psi(char *str)
  148. {
  149. return kstrtobool(str, &psi_enable) == 0;
  150. }
  151. __setup("psi=", setup_psi);
  152. /* Running averages - we need to be higher-res than loadavg */
  153. #define PSI_FREQ (2*HZ+1) /* 2 sec intervals */
  154. #define EXP_10s 1677 /* 1/exp(2s/10s) as fixed-point */
  155. #define EXP_60s 1981 /* 1/exp(2s/60s) */
  156. #define EXP_300s 2034 /* 1/exp(2s/300s) */
  157. /* PSI trigger definitions */
  158. #define WINDOW_MAX_US 10000000 /* Max window size is 10s */
  159. #define UPDATES_PER_WINDOW 10 /* 10 updates per window */
  160. /* Sampling frequency in nanoseconds */
  161. static u64 psi_period __read_mostly;
  162. /* System-level pressure and stall tracking */
  163. static DEFINE_PER_CPU(struct psi_group_cpu, system_group_pcpu);
  164. struct psi_group psi_system = {
  165. .pcpu = &system_group_pcpu,
  166. };
  167. static void psi_avgs_work(struct work_struct *work);
  168. static void poll_timer_fn(struct timer_list *t);
  169. static void group_init(struct psi_group *group)
  170. {
  171. int cpu;
  172. group->enabled = true;
  173. for_each_possible_cpu(cpu)
  174. seqcount_init(&per_cpu_ptr(group->pcpu, cpu)->seq);
  175. group->avg_last_update = sched_clock();
  176. group->avg_next_update = group->avg_last_update + psi_period;
  177. mutex_init(&group->avgs_lock);
  178. /* Init avg trigger-related members */
  179. INIT_LIST_HEAD(&group->avg_triggers);
  180. memset(group->avg_nr_triggers, 0, sizeof(group->avg_nr_triggers));
  181. INIT_DELAYED_WORK(&group->avgs_work, psi_avgs_work);
  182. /* Init rtpoll trigger-related members */
  183. atomic_set(&group->rtpoll_scheduled, 0);
  184. mutex_init(&group->rtpoll_trigger_lock);
  185. INIT_LIST_HEAD(&group->rtpoll_triggers);
  186. group->rtpoll_min_period = U32_MAX;
  187. group->rtpoll_next_update = ULLONG_MAX;
  188. init_waitqueue_head(&group->rtpoll_wait);
  189. timer_setup(&group->rtpoll_timer, poll_timer_fn, 0);
  190. rcu_assign_pointer(group->rtpoll_task, NULL);
  191. }
  192. void __init psi_init(void)
  193. {
  194. if (!psi_enable) {
  195. static_branch_enable(&psi_disabled);
  196. static_branch_disable(&psi_cgroups_enabled);
  197. return;
  198. }
  199. if (!cgroup_psi_enabled())
  200. static_branch_disable(&psi_cgroups_enabled);
  201. psi_period = jiffies_to_nsecs(PSI_FREQ);
  202. group_init(&psi_system);
  203. }
  204. static u32 test_states(unsigned int *tasks, u32 state_mask)
  205. {
  206. const bool oncpu = state_mask & PSI_ONCPU;
  207. if (tasks[NR_IOWAIT]) {
  208. state_mask |= BIT(PSI_IO_SOME);
  209. if (!tasks[NR_RUNNING])
  210. state_mask |= BIT(PSI_IO_FULL);
  211. }
  212. if (tasks[NR_MEMSTALL]) {
  213. state_mask |= BIT(PSI_MEM_SOME);
  214. if (tasks[NR_RUNNING] == tasks[NR_MEMSTALL_RUNNING])
  215. state_mask |= BIT(PSI_MEM_FULL);
  216. }
  217. if (tasks[NR_RUNNING] > oncpu)
  218. state_mask |= BIT(PSI_CPU_SOME);
  219. if (tasks[NR_RUNNING] && !oncpu)
  220. state_mask |= BIT(PSI_CPU_FULL);
  221. if (tasks[NR_IOWAIT] || tasks[NR_MEMSTALL] || tasks[NR_RUNNING])
  222. state_mask |= BIT(PSI_NONIDLE);
  223. return state_mask;
  224. }
  225. static void get_recent_times(struct psi_group *group, int cpu,
  226. enum psi_aggregators aggregator, u32 *times,
  227. u32 *pchanged_states)
  228. {
  229. struct psi_group_cpu *groupc = per_cpu_ptr(group->pcpu, cpu);
  230. int current_cpu = raw_smp_processor_id();
  231. unsigned int tasks[NR_PSI_TASK_COUNTS];
  232. u64 now, state_start;
  233. enum psi_states s;
  234. unsigned int seq;
  235. u32 state_mask;
  236. *pchanged_states = 0;
  237. /* Snapshot a coherent view of the CPU state */
  238. do {
  239. seq = read_seqcount_begin(&groupc->seq);
  240. now = cpu_clock(cpu);
  241. memcpy(times, groupc->times, sizeof(groupc->times));
  242. state_mask = groupc->state_mask;
  243. state_start = groupc->state_start;
  244. if (cpu == current_cpu)
  245. memcpy(tasks, groupc->tasks, sizeof(groupc->tasks));
  246. } while (read_seqcount_retry(&groupc->seq, seq));
  247. /* Calculate state time deltas against the previous snapshot */
  248. for (s = 0; s < NR_PSI_STATES; s++) {
  249. u32 delta;
  250. /*
  251. * In addition to already concluded states, we also
  252. * incorporate currently active states on the CPU,
  253. * since states may last for many sampling periods.
  254. *
  255. * This way we keep our delta sampling buckets small
  256. * (u32) and our reported pressure close to what's
  257. * actually happening.
  258. */
  259. if (state_mask & (1 << s))
  260. times[s] += now - state_start;
  261. delta = times[s] - groupc->times_prev[aggregator][s];
  262. groupc->times_prev[aggregator][s] = times[s];
  263. times[s] = delta;
  264. if (delta)
  265. *pchanged_states |= (1 << s);
  266. }
  267. /*
  268. * When collect_percpu_times() from the avgs_work, we don't want to
  269. * re-arm avgs_work when all CPUs are IDLE. But the current CPU running
  270. * this avgs_work is never IDLE, cause avgs_work can't be shut off.
  271. * So for the current CPU, we need to re-arm avgs_work only when
  272. * (NR_RUNNING > 1 || NR_IOWAIT > 0 || NR_MEMSTALL > 0), for other CPUs
  273. * we can just check PSI_NONIDLE delta.
  274. */
  275. if (current_work() == &group->avgs_work.work) {
  276. bool reschedule;
  277. if (cpu == current_cpu)
  278. reschedule = tasks[NR_RUNNING] +
  279. tasks[NR_IOWAIT] +
  280. tasks[NR_MEMSTALL] > 1;
  281. else
  282. reschedule = *pchanged_states & (1 << PSI_NONIDLE);
  283. if (reschedule)
  284. *pchanged_states |= PSI_STATE_RESCHEDULE;
  285. }
  286. }
  287. static void calc_avgs(unsigned long avg[3], int missed_periods,
  288. u64 time, u64 period)
  289. {
  290. unsigned long pct;
  291. /* Fill in zeroes for periods of no activity */
  292. if (missed_periods) {
  293. avg[0] = calc_load_n(avg[0], EXP_10s, 0, missed_periods);
  294. avg[1] = calc_load_n(avg[1], EXP_60s, 0, missed_periods);
  295. avg[2] = calc_load_n(avg[2], EXP_300s, 0, missed_periods);
  296. }
  297. /* Sample the most recent active period */
  298. pct = div_u64(time * 100, period);
  299. pct *= FIXED_1;
  300. avg[0] = calc_load(avg[0], EXP_10s, pct);
  301. avg[1] = calc_load(avg[1], EXP_60s, pct);
  302. avg[2] = calc_load(avg[2], EXP_300s, pct);
  303. }
  304. static void collect_percpu_times(struct psi_group *group,
  305. enum psi_aggregators aggregator,
  306. u32 *pchanged_states)
  307. {
  308. u64 deltas[NR_PSI_STATES - 1] = { 0, };
  309. unsigned long nonidle_total = 0;
  310. u32 changed_states = 0;
  311. int cpu;
  312. int s;
  313. /*
  314. * Collect the per-cpu time buckets and average them into a
  315. * single time sample that is normalized to wall clock time.
  316. *
  317. * For averaging, each CPU is weighted by its non-idle time in
  318. * the sampling period. This eliminates artifacts from uneven
  319. * loading, or even entirely idle CPUs.
  320. */
  321. for_each_possible_cpu(cpu) {
  322. u32 times[NR_PSI_STATES];
  323. u32 nonidle;
  324. u32 cpu_changed_states;
  325. get_recent_times(group, cpu, aggregator, times,
  326. &cpu_changed_states);
  327. changed_states |= cpu_changed_states;
  328. nonidle = nsecs_to_jiffies(times[PSI_NONIDLE]);
  329. nonidle_total += nonidle;
  330. for (s = 0; s < PSI_NONIDLE; s++)
  331. deltas[s] += (u64)times[s] * nonidle;
  332. }
  333. /*
  334. * Integrate the sample into the running statistics that are
  335. * reported to userspace: the cumulative stall times and the
  336. * decaying averages.
  337. *
  338. * Pressure percentages are sampled at PSI_FREQ. We might be
  339. * called more often when the user polls more frequently than
  340. * that; we might be called less often when there is no task
  341. * activity, thus no data, and clock ticks are sporadic. The
  342. * below handles both.
  343. */
  344. /* total= */
  345. for (s = 0; s < NR_PSI_STATES - 1; s++)
  346. group->total[aggregator][s] +=
  347. div_u64(deltas[s], max(nonidle_total, 1UL));
  348. if (pchanged_states)
  349. *pchanged_states = changed_states;
  350. }
  351. /* Trigger tracking window manipulations */
  352. static void window_reset(struct psi_window *win, u64 now, u64 value,
  353. u64 prev_growth)
  354. {
  355. win->start_time = now;
  356. win->start_value = value;
  357. win->prev_growth = prev_growth;
  358. }
  359. /*
  360. * PSI growth tracking window update and growth calculation routine.
  361. *
  362. * This approximates a sliding tracking window by interpolating
  363. * partially elapsed windows using historical growth data from the
  364. * previous intervals. This minimizes memory requirements (by not storing
  365. * all the intermediate values in the previous window) and simplifies
  366. * the calculations. It works well because PSI signal changes only in
  367. * positive direction and over relatively small window sizes the growth
  368. * is close to linear.
  369. */
  370. static u64 window_update(struct psi_window *win, u64 now, u64 value)
  371. {
  372. u64 elapsed;
  373. u64 growth;
  374. elapsed = now - win->start_time;
  375. growth = value - win->start_value;
  376. /*
  377. * After each tracking window passes win->start_value and
  378. * win->start_time get reset and win->prev_growth stores
  379. * the average per-window growth of the previous window.
  380. * win->prev_growth is then used to interpolate additional
  381. * growth from the previous window assuming it was linear.
  382. */
  383. if (elapsed > win->size)
  384. window_reset(win, now, value, growth);
  385. else {
  386. u32 remaining;
  387. remaining = win->size - elapsed;
  388. growth += div64_u64(win->prev_growth * remaining, win->size);
  389. }
  390. return growth;
  391. }
  392. static void update_triggers(struct psi_group *group, u64 now,
  393. enum psi_aggregators aggregator)
  394. {
  395. struct psi_trigger *t;
  396. u64 *total = group->total[aggregator];
  397. struct list_head *triggers;
  398. u64 *aggregator_total;
  399. if (aggregator == PSI_AVGS) {
  400. triggers = &group->avg_triggers;
  401. aggregator_total = group->avg_total;
  402. } else {
  403. triggers = &group->rtpoll_triggers;
  404. aggregator_total = group->rtpoll_total;
  405. }
  406. /*
  407. * On subsequent updates, calculate growth deltas and let
  408. * watchers know when their specified thresholds are exceeded.
  409. */
  410. list_for_each_entry(t, triggers, node) {
  411. u64 growth;
  412. bool new_stall;
  413. new_stall = aggregator_total[t->state] != total[t->state];
  414. /* Check for stall activity or a previous threshold breach */
  415. if (!new_stall && !t->pending_event)
  416. continue;
  417. /*
  418. * Check for new stall activity, as well as deferred
  419. * events that occurred in the last window after the
  420. * trigger had already fired (we want to ratelimit
  421. * events without dropping any).
  422. */
  423. if (new_stall) {
  424. /* Calculate growth since last update */
  425. growth = window_update(&t->win, now, total[t->state]);
  426. if (!t->pending_event) {
  427. if (growth < t->threshold)
  428. continue;
  429. t->pending_event = true;
  430. }
  431. }
  432. /* Limit event signaling to once per window */
  433. if (now < t->last_event_time + t->win.size)
  434. continue;
  435. /* Generate an event */
  436. if (cmpxchg(&t->event, 0, 1) == 0) {
  437. if (t->of)
  438. kernfs_notify(t->of->kn);
  439. else
  440. wake_up_interruptible(&t->event_wait);
  441. }
  442. t->last_event_time = now;
  443. /* Reset threshold breach flag once event got generated */
  444. t->pending_event = false;
  445. }
  446. }
  447. static u64 update_averages(struct psi_group *group, u64 now)
  448. {
  449. unsigned long missed_periods = 0;
  450. u64 expires, period;
  451. u64 avg_next_update;
  452. int s;
  453. /* avgX= */
  454. expires = group->avg_next_update;
  455. if (now - expires >= psi_period)
  456. missed_periods = div_u64(now - expires, psi_period);
  457. /*
  458. * The periodic clock tick can get delayed for various
  459. * reasons, especially on loaded systems. To avoid clock
  460. * drift, we schedule the clock in fixed psi_period intervals.
  461. * But the deltas we sample out of the per-cpu buckets above
  462. * are based on the actual time elapsing between clock ticks.
  463. */
  464. avg_next_update = expires + ((1 + missed_periods) * psi_period);
  465. period = now - (group->avg_last_update + (missed_periods * psi_period));
  466. group->avg_last_update = now;
  467. for (s = 0; s < NR_PSI_STATES - 1; s++) {
  468. u32 sample;
  469. sample = group->total[PSI_AVGS][s] - group->avg_total[s];
  470. /*
  471. * Due to the lockless sampling of the time buckets,
  472. * recorded time deltas can slip into the next period,
  473. * which under full pressure can result in samples in
  474. * excess of the period length.
  475. *
  476. * We don't want to report non-sensical pressures in
  477. * excess of 100%, nor do we want to drop such events
  478. * on the floor. Instead we punt any overage into the
  479. * future until pressure subsides. By doing this we
  480. * don't underreport the occurring pressure curve, we
  481. * just report it delayed by one period length.
  482. *
  483. * The error isn't cumulative. As soon as another
  484. * delta slips from a period P to P+1, by definition
  485. * it frees up its time T in P.
  486. */
  487. if (sample > period)
  488. sample = period;
  489. group->avg_total[s] += sample;
  490. calc_avgs(group->avg[s], missed_periods, sample, period);
  491. }
  492. return avg_next_update;
  493. }
  494. static void psi_avgs_work(struct work_struct *work)
  495. {
  496. struct delayed_work *dwork;
  497. struct psi_group *group;
  498. u32 changed_states;
  499. u64 now;
  500. dwork = to_delayed_work(work);
  501. group = container_of(dwork, struct psi_group, avgs_work);
  502. mutex_lock(&group->avgs_lock);
  503. now = sched_clock();
  504. collect_percpu_times(group, PSI_AVGS, &changed_states);
  505. /*
  506. * If there is task activity, periodically fold the per-cpu
  507. * times and feed samples into the running averages. If things
  508. * are idle and there is no data to process, stop the clock.
  509. * Once restarted, we'll catch up the running averages in one
  510. * go - see calc_avgs() and missed_periods.
  511. */
  512. if (now >= group->avg_next_update) {
  513. update_triggers(group, now, PSI_AVGS);
  514. group->avg_next_update = update_averages(group, now);
  515. }
  516. if (changed_states & PSI_STATE_RESCHEDULE) {
  517. schedule_delayed_work(dwork, nsecs_to_jiffies(
  518. group->avg_next_update - now) + 1);
  519. }
  520. mutex_unlock(&group->avgs_lock);
  521. }
  522. static void init_rtpoll_triggers(struct psi_group *group, u64 now)
  523. {
  524. struct psi_trigger *t;
  525. list_for_each_entry(t, &group->rtpoll_triggers, node)
  526. window_reset(&t->win, now,
  527. group->total[PSI_POLL][t->state], 0);
  528. memcpy(group->rtpoll_total, group->total[PSI_POLL],
  529. sizeof(group->rtpoll_total));
  530. group->rtpoll_next_update = now + group->rtpoll_min_period;
  531. }
  532. /* Schedule rtpolling if it's not already scheduled or forced. */
  533. static void psi_schedule_rtpoll_work(struct psi_group *group, unsigned long delay,
  534. bool force)
  535. {
  536. struct task_struct *task;
  537. /*
  538. * atomic_xchg should be called even when !force to provide a
  539. * full memory barrier (see the comment inside psi_rtpoll_work).
  540. */
  541. if (atomic_xchg(&group->rtpoll_scheduled, 1) && !force)
  542. return;
  543. rcu_read_lock();
  544. task = rcu_dereference(group->rtpoll_task);
  545. /*
  546. * kworker might be NULL in case psi_trigger_destroy races with
  547. * psi_task_change (hotpath) which can't use locks
  548. */
  549. if (likely(task))
  550. mod_timer(&group->rtpoll_timer, jiffies + delay);
  551. else
  552. atomic_set(&group->rtpoll_scheduled, 0);
  553. rcu_read_unlock();
  554. }
  555. static void psi_rtpoll_work(struct psi_group *group)
  556. {
  557. bool force_reschedule = false;
  558. u32 changed_states;
  559. u64 now;
  560. mutex_lock(&group->rtpoll_trigger_lock);
  561. now = sched_clock();
  562. if (now > group->rtpoll_until) {
  563. /*
  564. * We are either about to start or might stop rtpolling if no
  565. * state change was recorded. Resetting rtpoll_scheduled leaves
  566. * a small window for psi_group_change to sneak in and schedule
  567. * an immediate rtpoll_work before we get to rescheduling. One
  568. * potential extra wakeup at the end of the rtpolling window
  569. * should be negligible and rtpoll_next_update still keeps
  570. * updates correctly on schedule.
  571. */
  572. atomic_set(&group->rtpoll_scheduled, 0);
  573. /*
  574. * A task change can race with the rtpoll worker that is supposed to
  575. * report on it. To avoid missing events, ensure ordering between
  576. * rtpoll_scheduled and the task state accesses, such that if the
  577. * rtpoll worker misses the state update, the task change is
  578. * guaranteed to reschedule the rtpoll worker:
  579. *
  580. * rtpoll worker:
  581. * atomic_set(rtpoll_scheduled, 0)
  582. * smp_mb()
  583. * LOAD states
  584. *
  585. * task change:
  586. * STORE states
  587. * if atomic_xchg(rtpoll_scheduled, 1) == 0:
  588. * schedule rtpoll worker
  589. *
  590. * The atomic_xchg() implies a full barrier.
  591. */
  592. smp_mb();
  593. } else {
  594. /* The rtpolling window is not over, keep rescheduling */
  595. force_reschedule = true;
  596. }
  597. collect_percpu_times(group, PSI_POLL, &changed_states);
  598. if (changed_states & group->rtpoll_states) {
  599. /* Initialize trigger windows when entering rtpolling mode */
  600. if (now > group->rtpoll_until)
  601. init_rtpoll_triggers(group, now);
  602. /*
  603. * Keep the monitor active for at least the duration of the
  604. * minimum tracking window as long as monitor states are
  605. * changing.
  606. */
  607. group->rtpoll_until = now +
  608. group->rtpoll_min_period * UPDATES_PER_WINDOW;
  609. }
  610. if (now > group->rtpoll_until) {
  611. group->rtpoll_next_update = ULLONG_MAX;
  612. goto out;
  613. }
  614. if (now >= group->rtpoll_next_update) {
  615. if (changed_states & group->rtpoll_states) {
  616. update_triggers(group, now, PSI_POLL);
  617. memcpy(group->rtpoll_total, group->total[PSI_POLL],
  618. sizeof(group->rtpoll_total));
  619. }
  620. group->rtpoll_next_update = now + group->rtpoll_min_period;
  621. }
  622. psi_schedule_rtpoll_work(group,
  623. nsecs_to_jiffies(group->rtpoll_next_update - now) + 1,
  624. force_reschedule);
  625. out:
  626. mutex_unlock(&group->rtpoll_trigger_lock);
  627. }
  628. static int psi_rtpoll_worker(void *data)
  629. {
  630. struct psi_group *group = (struct psi_group *)data;
  631. sched_set_fifo_low(current);
  632. while (true) {
  633. wait_event_interruptible(group->rtpoll_wait,
  634. atomic_cmpxchg(&group->rtpoll_wakeup, 1, 0) ||
  635. kthread_should_stop());
  636. if (kthread_should_stop())
  637. break;
  638. psi_rtpoll_work(group);
  639. }
  640. return 0;
  641. }
  642. static void poll_timer_fn(struct timer_list *t)
  643. {
  644. struct psi_group *group = from_timer(group, t, rtpoll_timer);
  645. atomic_set(&group->rtpoll_wakeup, 1);
  646. wake_up_interruptible(&group->rtpoll_wait);
  647. }
  648. static void record_times(struct psi_group_cpu *groupc, u64 now)
  649. {
  650. u32 delta;
  651. delta = now - groupc->state_start;
  652. groupc->state_start = now;
  653. if (groupc->state_mask & (1 << PSI_IO_SOME)) {
  654. groupc->times[PSI_IO_SOME] += delta;
  655. if (groupc->state_mask & (1 << PSI_IO_FULL))
  656. groupc->times[PSI_IO_FULL] += delta;
  657. }
  658. if (groupc->state_mask & (1 << PSI_MEM_SOME)) {
  659. groupc->times[PSI_MEM_SOME] += delta;
  660. if (groupc->state_mask & (1 << PSI_MEM_FULL))
  661. groupc->times[PSI_MEM_FULL] += delta;
  662. }
  663. if (groupc->state_mask & (1 << PSI_CPU_SOME)) {
  664. groupc->times[PSI_CPU_SOME] += delta;
  665. if (groupc->state_mask & (1 << PSI_CPU_FULL))
  666. groupc->times[PSI_CPU_FULL] += delta;
  667. }
  668. if (groupc->state_mask & (1 << PSI_NONIDLE))
  669. groupc->times[PSI_NONIDLE] += delta;
  670. }
  671. static void psi_group_change(struct psi_group *group, int cpu,
  672. unsigned int clear, unsigned int set,
  673. bool wake_clock)
  674. {
  675. struct psi_group_cpu *groupc;
  676. unsigned int t, m;
  677. u32 state_mask;
  678. u64 now;
  679. lockdep_assert_rq_held(cpu_rq(cpu));
  680. groupc = per_cpu_ptr(group->pcpu, cpu);
  681. /*
  682. * First we update the task counts according to the state
  683. * change requested through the @clear and @set bits.
  684. *
  685. * Then if the cgroup PSI stats accounting enabled, we
  686. * assess the aggregate resource states this CPU's tasks
  687. * have been in since the last change, and account any
  688. * SOME and FULL time these may have resulted in.
  689. */
  690. write_seqcount_begin(&groupc->seq);
  691. now = cpu_clock(cpu);
  692. /*
  693. * Start with TSK_ONCPU, which doesn't have a corresponding
  694. * task count - it's just a boolean flag directly encoded in
  695. * the state mask. Clear, set, or carry the current state if
  696. * no changes are requested.
  697. */
  698. if (unlikely(clear & TSK_ONCPU)) {
  699. state_mask = 0;
  700. clear &= ~TSK_ONCPU;
  701. } else if (unlikely(set & TSK_ONCPU)) {
  702. state_mask = PSI_ONCPU;
  703. set &= ~TSK_ONCPU;
  704. } else {
  705. state_mask = groupc->state_mask & PSI_ONCPU;
  706. }
  707. /*
  708. * The rest of the state mask is calculated based on the task
  709. * counts. Update those first, then construct the mask.
  710. */
  711. for (t = 0, m = clear; m; m &= ~(1 << t), t++) {
  712. if (!(m & (1 << t)))
  713. continue;
  714. if (groupc->tasks[t]) {
  715. groupc->tasks[t]--;
  716. } else if (!psi_bug) {
  717. printk_deferred(KERN_ERR "psi: task underflow! cpu=%d t=%d tasks=[%u %u %u %u] clear=%x set=%x\n",
  718. cpu, t, groupc->tasks[0],
  719. groupc->tasks[1], groupc->tasks[2],
  720. groupc->tasks[3], clear, set);
  721. psi_bug = 1;
  722. }
  723. }
  724. for (t = 0; set; set &= ~(1 << t), t++)
  725. if (set & (1 << t))
  726. groupc->tasks[t]++;
  727. if (!group->enabled) {
  728. /*
  729. * On the first group change after disabling PSI, conclude
  730. * the current state and flush its time. This is unlikely
  731. * to matter to the user, but aggregation (get_recent_times)
  732. * may have already incorporated the live state into times_prev;
  733. * avoid a delta sample underflow when PSI is later re-enabled.
  734. */
  735. if (unlikely(groupc->state_mask & (1 << PSI_NONIDLE)))
  736. record_times(groupc, now);
  737. groupc->state_mask = state_mask;
  738. write_seqcount_end(&groupc->seq);
  739. return;
  740. }
  741. state_mask = test_states(groupc->tasks, state_mask);
  742. /*
  743. * Since we care about lost potential, a memstall is FULL
  744. * when there are no other working tasks, but also when
  745. * the CPU is actively reclaiming and nothing productive
  746. * could run even if it were runnable. So when the current
  747. * task in a cgroup is in_memstall, the corresponding groupc
  748. * on that cpu is in PSI_MEM_FULL state.
  749. */
  750. if (unlikely((state_mask & PSI_ONCPU) && cpu_curr(cpu)->in_memstall))
  751. state_mask |= (1 << PSI_MEM_FULL);
  752. record_times(groupc, now);
  753. groupc->state_mask = state_mask;
  754. write_seqcount_end(&groupc->seq);
  755. if (state_mask & group->rtpoll_states)
  756. psi_schedule_rtpoll_work(group, 1, false);
  757. if (wake_clock && !delayed_work_pending(&group->avgs_work))
  758. schedule_delayed_work(&group->avgs_work, PSI_FREQ);
  759. }
  760. static inline struct psi_group *task_psi_group(struct task_struct *task)
  761. {
  762. #ifdef CONFIG_CGROUPS
  763. if (static_branch_likely(&psi_cgroups_enabled))
  764. return cgroup_psi(task_dfl_cgroup(task));
  765. #endif
  766. return &psi_system;
  767. }
  768. static void psi_flags_change(struct task_struct *task, int clear, int set)
  769. {
  770. if (((task->psi_flags & set) ||
  771. (task->psi_flags & clear) != clear) &&
  772. !psi_bug) {
  773. printk_deferred(KERN_ERR "psi: inconsistent task state! task=%d:%s cpu=%d psi_flags=%x clear=%x set=%x\n",
  774. task->pid, task->comm, task_cpu(task),
  775. task->psi_flags, clear, set);
  776. psi_bug = 1;
  777. }
  778. task->psi_flags &= ~clear;
  779. task->psi_flags |= set;
  780. }
  781. void psi_task_change(struct task_struct *task, int clear, int set)
  782. {
  783. int cpu = task_cpu(task);
  784. struct psi_group *group;
  785. if (!task->pid)
  786. return;
  787. psi_flags_change(task, clear, set);
  788. group = task_psi_group(task);
  789. do {
  790. psi_group_change(group, cpu, clear, set, true);
  791. } while ((group = group->parent));
  792. }
  793. void psi_task_switch(struct task_struct *prev, struct task_struct *next,
  794. bool sleep)
  795. {
  796. struct psi_group *group, *common = NULL;
  797. int cpu = task_cpu(prev);
  798. if (next->pid) {
  799. psi_flags_change(next, 0, TSK_ONCPU);
  800. /*
  801. * Set TSK_ONCPU on @next's cgroups. If @next shares any
  802. * ancestors with @prev, those will already have @prev's
  803. * TSK_ONCPU bit set, and we can stop the iteration there.
  804. */
  805. group = task_psi_group(next);
  806. do {
  807. if (per_cpu_ptr(group->pcpu, cpu)->state_mask &
  808. PSI_ONCPU) {
  809. common = group;
  810. break;
  811. }
  812. psi_group_change(group, cpu, 0, TSK_ONCPU, true);
  813. } while ((group = group->parent));
  814. }
  815. if (prev->pid) {
  816. int clear = TSK_ONCPU, set = 0;
  817. bool wake_clock = true;
  818. /*
  819. * When we're going to sleep, psi_dequeue() lets us
  820. * handle TSK_RUNNING, TSK_MEMSTALL_RUNNING and
  821. * TSK_IOWAIT here, where we can combine it with
  822. * TSK_ONCPU and save walking common ancestors twice.
  823. */
  824. if (sleep) {
  825. clear |= TSK_RUNNING;
  826. if (prev->in_memstall)
  827. clear |= TSK_MEMSTALL_RUNNING;
  828. if (prev->in_iowait)
  829. set |= TSK_IOWAIT;
  830. /*
  831. * Periodic aggregation shuts off if there is a period of no
  832. * task changes, so we wake it back up if necessary. However,
  833. * don't do this if the task change is the aggregation worker
  834. * itself going to sleep, or we'll ping-pong forever.
  835. */
  836. if (unlikely((prev->flags & PF_WQ_WORKER) &&
  837. wq_worker_last_func(prev) == psi_avgs_work))
  838. wake_clock = false;
  839. }
  840. psi_flags_change(prev, clear, set);
  841. group = task_psi_group(prev);
  842. do {
  843. if (group == common)
  844. break;
  845. psi_group_change(group, cpu, clear, set, wake_clock);
  846. } while ((group = group->parent));
  847. /*
  848. * TSK_ONCPU is handled up to the common ancestor. If there are
  849. * any other differences between the two tasks (e.g. prev goes
  850. * to sleep, or only one task is memstall), finish propagating
  851. * those differences all the way up to the root.
  852. */
  853. if ((prev->psi_flags ^ next->psi_flags) & ~TSK_ONCPU) {
  854. clear &= ~TSK_ONCPU;
  855. for (; group; group = group->parent)
  856. psi_group_change(group, cpu, clear, set, wake_clock);
  857. }
  858. }
  859. }
  860. #ifdef CONFIG_IRQ_TIME_ACCOUNTING
  861. void psi_account_irqtime(struct rq *rq, struct task_struct *curr, struct task_struct *prev)
  862. {
  863. int cpu = task_cpu(curr);
  864. struct psi_group *group;
  865. struct psi_group_cpu *groupc;
  866. s64 delta;
  867. u64 irq;
  868. if (static_branch_likely(&psi_disabled))
  869. return;
  870. if (!curr->pid)
  871. return;
  872. lockdep_assert_rq_held(rq);
  873. group = task_psi_group(curr);
  874. if (prev && task_psi_group(prev) == group)
  875. return;
  876. irq = irq_time_read(cpu);
  877. delta = (s64)(irq - rq->psi_irq_time);
  878. if (delta < 0)
  879. return;
  880. rq->psi_irq_time = irq;
  881. do {
  882. u64 now;
  883. if (!group->enabled)
  884. continue;
  885. groupc = per_cpu_ptr(group->pcpu, cpu);
  886. write_seqcount_begin(&groupc->seq);
  887. now = cpu_clock(cpu);
  888. record_times(groupc, now);
  889. groupc->times[PSI_IRQ_FULL] += delta;
  890. write_seqcount_end(&groupc->seq);
  891. if (group->rtpoll_states & (1 << PSI_IRQ_FULL))
  892. psi_schedule_rtpoll_work(group, 1, false);
  893. } while ((group = group->parent));
  894. }
  895. #endif
  896. /**
  897. * psi_memstall_enter - mark the beginning of a memory stall section
  898. * @flags: flags to handle nested sections
  899. *
  900. * Marks the calling task as being stalled due to a lack of memory,
  901. * such as waiting for a refault or performing reclaim.
  902. */
  903. void psi_memstall_enter(unsigned long *flags)
  904. {
  905. struct rq_flags rf;
  906. struct rq *rq;
  907. if (static_branch_likely(&psi_disabled))
  908. return;
  909. *flags = current->in_memstall;
  910. if (*flags)
  911. return;
  912. /*
  913. * in_memstall setting & accounting needs to be atomic wrt
  914. * changes to the task's scheduling state, otherwise we can
  915. * race with CPU migration.
  916. */
  917. rq = this_rq_lock_irq(&rf);
  918. current->in_memstall = 1;
  919. psi_task_change(current, 0, TSK_MEMSTALL | TSK_MEMSTALL_RUNNING);
  920. rq_unlock_irq(rq, &rf);
  921. }
  922. EXPORT_SYMBOL_GPL(psi_memstall_enter);
  923. /**
  924. * psi_memstall_leave - mark the end of an memory stall section
  925. * @flags: flags to handle nested memdelay sections
  926. *
  927. * Marks the calling task as no longer stalled due to lack of memory.
  928. */
  929. void psi_memstall_leave(unsigned long *flags)
  930. {
  931. struct rq_flags rf;
  932. struct rq *rq;
  933. if (static_branch_likely(&psi_disabled))
  934. return;
  935. if (*flags)
  936. return;
  937. /*
  938. * in_memstall clearing & accounting needs to be atomic wrt
  939. * changes to the task's scheduling state, otherwise we could
  940. * race with CPU migration.
  941. */
  942. rq = this_rq_lock_irq(&rf);
  943. current->in_memstall = 0;
  944. psi_task_change(current, TSK_MEMSTALL | TSK_MEMSTALL_RUNNING, 0);
  945. rq_unlock_irq(rq, &rf);
  946. }
  947. EXPORT_SYMBOL_GPL(psi_memstall_leave);
  948. #ifdef CONFIG_CGROUPS
  949. int psi_cgroup_alloc(struct cgroup *cgroup)
  950. {
  951. if (!static_branch_likely(&psi_cgroups_enabled))
  952. return 0;
  953. cgroup->psi = kzalloc(sizeof(struct psi_group), GFP_KERNEL);
  954. if (!cgroup->psi)
  955. return -ENOMEM;
  956. cgroup->psi->pcpu = alloc_percpu(struct psi_group_cpu);
  957. if (!cgroup->psi->pcpu) {
  958. kfree(cgroup->psi);
  959. return -ENOMEM;
  960. }
  961. group_init(cgroup->psi);
  962. cgroup->psi->parent = cgroup_psi(cgroup_parent(cgroup));
  963. return 0;
  964. }
  965. void psi_cgroup_free(struct cgroup *cgroup)
  966. {
  967. if (!static_branch_likely(&psi_cgroups_enabled))
  968. return;
  969. cancel_delayed_work_sync(&cgroup->psi->avgs_work);
  970. free_percpu(cgroup->psi->pcpu);
  971. /* All triggers must be removed by now */
  972. WARN_ONCE(cgroup->psi->rtpoll_states, "psi: trigger leak\n");
  973. kfree(cgroup->psi);
  974. }
  975. /**
  976. * cgroup_move_task - move task to a different cgroup
  977. * @task: the task
  978. * @to: the target css_set
  979. *
  980. * Move task to a new cgroup and safely migrate its associated stall
  981. * state between the different groups.
  982. *
  983. * This function acquires the task's rq lock to lock out concurrent
  984. * changes to the task's scheduling state and - in case the task is
  985. * running - concurrent changes to its stall state.
  986. */
  987. void cgroup_move_task(struct task_struct *task, struct css_set *to)
  988. {
  989. unsigned int task_flags;
  990. struct rq_flags rf;
  991. struct rq *rq;
  992. if (!static_branch_likely(&psi_cgroups_enabled)) {
  993. /*
  994. * Lame to do this here, but the scheduler cannot be locked
  995. * from the outside, so we move cgroups from inside sched/.
  996. */
  997. rcu_assign_pointer(task->cgroups, to);
  998. return;
  999. }
  1000. rq = task_rq_lock(task, &rf);
  1001. /*
  1002. * We may race with schedule() dropping the rq lock between
  1003. * deactivating prev and switching to next. Because the psi
  1004. * updates from the deactivation are deferred to the switch
  1005. * callback to save cgroup tree updates, the task's scheduling
  1006. * state here is not coherent with its psi state:
  1007. *
  1008. * schedule() cgroup_move_task()
  1009. * rq_lock()
  1010. * deactivate_task()
  1011. * p->on_rq = 0
  1012. * psi_dequeue() // defers TSK_RUNNING & TSK_IOWAIT updates
  1013. * pick_next_task()
  1014. * rq_unlock()
  1015. * rq_lock()
  1016. * psi_task_change() // old cgroup
  1017. * task->cgroups = to
  1018. * psi_task_change() // new cgroup
  1019. * rq_unlock()
  1020. * rq_lock()
  1021. * psi_sched_switch() // does deferred updates in new cgroup
  1022. *
  1023. * Don't rely on the scheduling state. Use psi_flags instead.
  1024. */
  1025. task_flags = task->psi_flags;
  1026. if (task_flags)
  1027. psi_task_change(task, task_flags, 0);
  1028. /* See comment above */
  1029. rcu_assign_pointer(task->cgroups, to);
  1030. if (task_flags)
  1031. psi_task_change(task, 0, task_flags);
  1032. task_rq_unlock(rq, task, &rf);
  1033. }
  1034. void psi_cgroup_restart(struct psi_group *group)
  1035. {
  1036. int cpu;
  1037. /*
  1038. * After we disable psi_group->enabled, we don't actually
  1039. * stop percpu tasks accounting in each psi_group_cpu,
  1040. * instead only stop test_states() loop, record_times()
  1041. * and averaging worker, see psi_group_change() for details.
  1042. *
  1043. * When disable cgroup PSI, this function has nothing to sync
  1044. * since cgroup pressure files are hidden and percpu psi_group_cpu
  1045. * would see !psi_group->enabled and only do task accounting.
  1046. *
  1047. * When re-enable cgroup PSI, this function use psi_group_change()
  1048. * to get correct state mask from test_states() loop on tasks[],
  1049. * and restart groupc->state_start from now, use .clear = .set = 0
  1050. * here since no task status really changed.
  1051. */
  1052. if (!group->enabled)
  1053. return;
  1054. for_each_possible_cpu(cpu) {
  1055. struct rq *rq = cpu_rq(cpu);
  1056. struct rq_flags rf;
  1057. rq_lock_irq(rq, &rf);
  1058. psi_group_change(group, cpu, 0, 0, true);
  1059. rq_unlock_irq(rq, &rf);
  1060. }
  1061. }
  1062. #endif /* CONFIG_CGROUPS */
  1063. int psi_show(struct seq_file *m, struct psi_group *group, enum psi_res res)
  1064. {
  1065. bool only_full = false;
  1066. int full;
  1067. u64 now;
  1068. if (static_branch_likely(&psi_disabled))
  1069. return -EOPNOTSUPP;
  1070. /* Update averages before reporting them */
  1071. mutex_lock(&group->avgs_lock);
  1072. now = sched_clock();
  1073. collect_percpu_times(group, PSI_AVGS, NULL);
  1074. if (now >= group->avg_next_update)
  1075. group->avg_next_update = update_averages(group, now);
  1076. mutex_unlock(&group->avgs_lock);
  1077. #ifdef CONFIG_IRQ_TIME_ACCOUNTING
  1078. only_full = res == PSI_IRQ;
  1079. #endif
  1080. for (full = 0; full < 2 - only_full; full++) {
  1081. unsigned long avg[3] = { 0, };
  1082. u64 total = 0;
  1083. int w;
  1084. /* CPU FULL is undefined at the system level */
  1085. if (!(group == &psi_system && res == PSI_CPU && full)) {
  1086. for (w = 0; w < 3; w++)
  1087. avg[w] = group->avg[res * 2 + full][w];
  1088. total = div_u64(group->total[PSI_AVGS][res * 2 + full],
  1089. NSEC_PER_USEC);
  1090. }
  1091. seq_printf(m, "%s avg10=%lu.%02lu avg60=%lu.%02lu avg300=%lu.%02lu total=%llu\n",
  1092. full || only_full ? "full" : "some",
  1093. LOAD_INT(avg[0]), LOAD_FRAC(avg[0]),
  1094. LOAD_INT(avg[1]), LOAD_FRAC(avg[1]),
  1095. LOAD_INT(avg[2]), LOAD_FRAC(avg[2]),
  1096. total);
  1097. }
  1098. return 0;
  1099. }
  1100. struct psi_trigger *psi_trigger_create(struct psi_group *group, char *buf,
  1101. enum psi_res res, struct file *file,
  1102. struct kernfs_open_file *of)
  1103. {
  1104. struct psi_trigger *t;
  1105. enum psi_states state;
  1106. u32 threshold_us;
  1107. bool privileged;
  1108. u32 window_us;
  1109. if (static_branch_likely(&psi_disabled))
  1110. return ERR_PTR(-EOPNOTSUPP);
  1111. /*
  1112. * Checking the privilege here on file->f_cred implies that a privileged user
  1113. * could open the file and delegate the write to an unprivileged one.
  1114. */
  1115. privileged = cap_raised(file->f_cred->cap_effective, CAP_SYS_RESOURCE);
  1116. if (sscanf(buf, "some %u %u", &threshold_us, &window_us) == 2)
  1117. state = PSI_IO_SOME + res * 2;
  1118. else if (sscanf(buf, "full %u %u", &threshold_us, &window_us) == 2)
  1119. state = PSI_IO_FULL + res * 2;
  1120. else
  1121. return ERR_PTR(-EINVAL);
  1122. #ifdef CONFIG_IRQ_TIME_ACCOUNTING
  1123. if (res == PSI_IRQ && --state != PSI_IRQ_FULL)
  1124. return ERR_PTR(-EINVAL);
  1125. #endif
  1126. if (state >= PSI_NONIDLE)
  1127. return ERR_PTR(-EINVAL);
  1128. if (window_us == 0 || window_us > WINDOW_MAX_US)
  1129. return ERR_PTR(-EINVAL);
  1130. /*
  1131. * Unprivileged users can only use 2s windows so that averages aggregation
  1132. * work is used, and no RT threads need to be spawned.
  1133. */
  1134. if (!privileged && window_us % 2000000)
  1135. return ERR_PTR(-EINVAL);
  1136. /* Check threshold */
  1137. if (threshold_us == 0 || threshold_us > window_us)
  1138. return ERR_PTR(-EINVAL);
  1139. t = kmalloc(sizeof(*t), GFP_KERNEL);
  1140. if (!t)
  1141. return ERR_PTR(-ENOMEM);
  1142. t->group = group;
  1143. t->state = state;
  1144. t->threshold = threshold_us * NSEC_PER_USEC;
  1145. t->win.size = window_us * NSEC_PER_USEC;
  1146. window_reset(&t->win, sched_clock(),
  1147. group->total[PSI_POLL][t->state], 0);
  1148. t->event = 0;
  1149. t->last_event_time = 0;
  1150. t->of = of;
  1151. if (!of)
  1152. init_waitqueue_head(&t->event_wait);
  1153. t->pending_event = false;
  1154. t->aggregator = privileged ? PSI_POLL : PSI_AVGS;
  1155. if (privileged) {
  1156. mutex_lock(&group->rtpoll_trigger_lock);
  1157. if (!rcu_access_pointer(group->rtpoll_task)) {
  1158. struct task_struct *task;
  1159. task = kthread_create(psi_rtpoll_worker, group, "psimon");
  1160. if (IS_ERR(task)) {
  1161. kfree(t);
  1162. mutex_unlock(&group->rtpoll_trigger_lock);
  1163. return ERR_CAST(task);
  1164. }
  1165. atomic_set(&group->rtpoll_wakeup, 0);
  1166. wake_up_process(task);
  1167. rcu_assign_pointer(group->rtpoll_task, task);
  1168. }
  1169. list_add(&t->node, &group->rtpoll_triggers);
  1170. group->rtpoll_min_period = min(group->rtpoll_min_period,
  1171. div_u64(t->win.size, UPDATES_PER_WINDOW));
  1172. group->rtpoll_nr_triggers[t->state]++;
  1173. group->rtpoll_states |= (1 << t->state);
  1174. mutex_unlock(&group->rtpoll_trigger_lock);
  1175. } else {
  1176. mutex_lock(&group->avgs_lock);
  1177. list_add(&t->node, &group->avg_triggers);
  1178. group->avg_nr_triggers[t->state]++;
  1179. mutex_unlock(&group->avgs_lock);
  1180. }
  1181. return t;
  1182. }
  1183. void psi_trigger_destroy(struct psi_trigger *t)
  1184. {
  1185. struct psi_group *group;
  1186. struct task_struct *task_to_destroy = NULL;
  1187. /*
  1188. * We do not check psi_disabled since it might have been disabled after
  1189. * the trigger got created.
  1190. */
  1191. if (!t)
  1192. return;
  1193. group = t->group;
  1194. /*
  1195. * Wakeup waiters to stop polling and clear the queue to prevent it from
  1196. * being accessed later. Can happen if cgroup is deleted from under a
  1197. * polling process.
  1198. */
  1199. if (t->of)
  1200. kernfs_notify(t->of->kn);
  1201. else
  1202. wake_up_interruptible(&t->event_wait);
  1203. if (t->aggregator == PSI_AVGS) {
  1204. mutex_lock(&group->avgs_lock);
  1205. if (!list_empty(&t->node)) {
  1206. list_del(&t->node);
  1207. group->avg_nr_triggers[t->state]--;
  1208. }
  1209. mutex_unlock(&group->avgs_lock);
  1210. } else {
  1211. mutex_lock(&group->rtpoll_trigger_lock);
  1212. if (!list_empty(&t->node)) {
  1213. struct psi_trigger *tmp;
  1214. u64 period = ULLONG_MAX;
  1215. list_del(&t->node);
  1216. group->rtpoll_nr_triggers[t->state]--;
  1217. if (!group->rtpoll_nr_triggers[t->state])
  1218. group->rtpoll_states &= ~(1 << t->state);
  1219. /*
  1220. * Reset min update period for the remaining triggers
  1221. * iff the destroying trigger had the min window size.
  1222. */
  1223. if (group->rtpoll_min_period == div_u64(t->win.size, UPDATES_PER_WINDOW)) {
  1224. list_for_each_entry(tmp, &group->rtpoll_triggers, node)
  1225. period = min(period, div_u64(tmp->win.size,
  1226. UPDATES_PER_WINDOW));
  1227. group->rtpoll_min_period = period;
  1228. }
  1229. /* Destroy rtpoll_task when the last trigger is destroyed */
  1230. if (group->rtpoll_states == 0) {
  1231. group->rtpoll_until = 0;
  1232. task_to_destroy = rcu_dereference_protected(
  1233. group->rtpoll_task,
  1234. lockdep_is_held(&group->rtpoll_trigger_lock));
  1235. rcu_assign_pointer(group->rtpoll_task, NULL);
  1236. del_timer(&group->rtpoll_timer);
  1237. }
  1238. }
  1239. mutex_unlock(&group->rtpoll_trigger_lock);
  1240. }
  1241. /*
  1242. * Wait for psi_schedule_rtpoll_work RCU to complete its read-side
  1243. * critical section before destroying the trigger and optionally the
  1244. * rtpoll_task.
  1245. */
  1246. synchronize_rcu();
  1247. /*
  1248. * Stop kthread 'psimon' after releasing rtpoll_trigger_lock to prevent
  1249. * a deadlock while waiting for psi_rtpoll_work to acquire
  1250. * rtpoll_trigger_lock
  1251. */
  1252. if (task_to_destroy) {
  1253. /*
  1254. * After the RCU grace period has expired, the worker
  1255. * can no longer be found through group->rtpoll_task.
  1256. */
  1257. kthread_stop(task_to_destroy);
  1258. atomic_set(&group->rtpoll_scheduled, 0);
  1259. }
  1260. kfree(t);
  1261. }
  1262. __poll_t psi_trigger_poll(void **trigger_ptr,
  1263. struct file *file, poll_table *wait)
  1264. {
  1265. __poll_t ret = DEFAULT_POLLMASK;
  1266. struct psi_trigger *t;
  1267. if (static_branch_likely(&psi_disabled))
  1268. return DEFAULT_POLLMASK | EPOLLERR | EPOLLPRI;
  1269. t = smp_load_acquire(trigger_ptr);
  1270. if (!t)
  1271. return DEFAULT_POLLMASK | EPOLLERR | EPOLLPRI;
  1272. if (t->of)
  1273. kernfs_generic_poll(t->of, wait);
  1274. else
  1275. poll_wait(file, &t->event_wait, wait);
  1276. if (cmpxchg(&t->event, 1, 0) == 1)
  1277. ret |= EPOLLPRI;
  1278. return ret;
  1279. }
  1280. #ifdef CONFIG_PROC_FS
  1281. static int psi_io_show(struct seq_file *m, void *v)
  1282. {
  1283. return psi_show(m, &psi_system, PSI_IO);
  1284. }
  1285. static int psi_memory_show(struct seq_file *m, void *v)
  1286. {
  1287. return psi_show(m, &psi_system, PSI_MEM);
  1288. }
  1289. static int psi_cpu_show(struct seq_file *m, void *v)
  1290. {
  1291. return psi_show(m, &psi_system, PSI_CPU);
  1292. }
  1293. static int psi_io_open(struct inode *inode, struct file *file)
  1294. {
  1295. return single_open(file, psi_io_show, NULL);
  1296. }
  1297. static int psi_memory_open(struct inode *inode, struct file *file)
  1298. {
  1299. return single_open(file, psi_memory_show, NULL);
  1300. }
  1301. static int psi_cpu_open(struct inode *inode, struct file *file)
  1302. {
  1303. return single_open(file, psi_cpu_show, NULL);
  1304. }
  1305. static ssize_t psi_write(struct file *file, const char __user *user_buf,
  1306. size_t nbytes, enum psi_res res)
  1307. {
  1308. char buf[32];
  1309. size_t buf_size;
  1310. struct seq_file *seq;
  1311. struct psi_trigger *new;
  1312. if (static_branch_likely(&psi_disabled))
  1313. return -EOPNOTSUPP;
  1314. if (!nbytes)
  1315. return -EINVAL;
  1316. buf_size = min(nbytes, sizeof(buf));
  1317. if (copy_from_user(buf, user_buf, buf_size))
  1318. return -EFAULT;
  1319. buf[buf_size - 1] = '\0';
  1320. seq = file->private_data;
  1321. /* Take seq->lock to protect seq->private from concurrent writes */
  1322. mutex_lock(&seq->lock);
  1323. /* Allow only one trigger per file descriptor */
  1324. if (seq->private) {
  1325. mutex_unlock(&seq->lock);
  1326. return -EBUSY;
  1327. }
  1328. new = psi_trigger_create(&psi_system, buf, res, file, NULL);
  1329. if (IS_ERR(new)) {
  1330. mutex_unlock(&seq->lock);
  1331. return PTR_ERR(new);
  1332. }
  1333. smp_store_release(&seq->private, new);
  1334. mutex_unlock(&seq->lock);
  1335. return nbytes;
  1336. }
  1337. static ssize_t psi_io_write(struct file *file, const char __user *user_buf,
  1338. size_t nbytes, loff_t *ppos)
  1339. {
  1340. return psi_write(file, user_buf, nbytes, PSI_IO);
  1341. }
  1342. static ssize_t psi_memory_write(struct file *file, const char __user *user_buf,
  1343. size_t nbytes, loff_t *ppos)
  1344. {
  1345. return psi_write(file, user_buf, nbytes, PSI_MEM);
  1346. }
  1347. static ssize_t psi_cpu_write(struct file *file, const char __user *user_buf,
  1348. size_t nbytes, loff_t *ppos)
  1349. {
  1350. return psi_write(file, user_buf, nbytes, PSI_CPU);
  1351. }
  1352. static __poll_t psi_fop_poll(struct file *file, poll_table *wait)
  1353. {
  1354. struct seq_file *seq = file->private_data;
  1355. return psi_trigger_poll(&seq->private, file, wait);
  1356. }
  1357. static int psi_fop_release(struct inode *inode, struct file *file)
  1358. {
  1359. struct seq_file *seq = file->private_data;
  1360. psi_trigger_destroy(seq->private);
  1361. return single_release(inode, file);
  1362. }
  1363. static const struct proc_ops psi_io_proc_ops = {
  1364. .proc_open = psi_io_open,
  1365. .proc_read = seq_read,
  1366. .proc_lseek = seq_lseek,
  1367. .proc_write = psi_io_write,
  1368. .proc_poll = psi_fop_poll,
  1369. .proc_release = psi_fop_release,
  1370. };
  1371. static const struct proc_ops psi_memory_proc_ops = {
  1372. .proc_open = psi_memory_open,
  1373. .proc_read = seq_read,
  1374. .proc_lseek = seq_lseek,
  1375. .proc_write = psi_memory_write,
  1376. .proc_poll = psi_fop_poll,
  1377. .proc_release = psi_fop_release,
  1378. };
  1379. static const struct proc_ops psi_cpu_proc_ops = {
  1380. .proc_open = psi_cpu_open,
  1381. .proc_read = seq_read,
  1382. .proc_lseek = seq_lseek,
  1383. .proc_write = psi_cpu_write,
  1384. .proc_poll = psi_fop_poll,
  1385. .proc_release = psi_fop_release,
  1386. };
  1387. #ifdef CONFIG_IRQ_TIME_ACCOUNTING
  1388. static int psi_irq_show(struct seq_file *m, void *v)
  1389. {
  1390. return psi_show(m, &psi_system, PSI_IRQ);
  1391. }
  1392. static int psi_irq_open(struct inode *inode, struct file *file)
  1393. {
  1394. return single_open(file, psi_irq_show, NULL);
  1395. }
  1396. static ssize_t psi_irq_write(struct file *file, const char __user *user_buf,
  1397. size_t nbytes, loff_t *ppos)
  1398. {
  1399. return psi_write(file, user_buf, nbytes, PSI_IRQ);
  1400. }
  1401. static const struct proc_ops psi_irq_proc_ops = {
  1402. .proc_open = psi_irq_open,
  1403. .proc_read = seq_read,
  1404. .proc_lseek = seq_lseek,
  1405. .proc_write = psi_irq_write,
  1406. .proc_poll = psi_fop_poll,
  1407. .proc_release = psi_fop_release,
  1408. };
  1409. #endif
  1410. static int __init psi_proc_init(void)
  1411. {
  1412. if (psi_enable) {
  1413. proc_mkdir("pressure", NULL);
  1414. proc_create("pressure/io", 0666, NULL, &psi_io_proc_ops);
  1415. proc_create("pressure/memory", 0666, NULL, &psi_memory_proc_ops);
  1416. proc_create("pressure/cpu", 0666, NULL, &psi_cpu_proc_ops);
  1417. #ifdef CONFIG_IRQ_TIME_ACCOUNTING
  1418. proc_create("pressure/irq", 0666, NULL, &psi_irq_proc_ops);
  1419. #endif
  1420. }
  1421. return 0;
  1422. }
  1423. module_init(psi_proc_init);
  1424. #endif /* CONFIG_PROC_FS */