psi.c 43 KB

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