psi.c 46 KB

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