• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Simple CPU accounting cgroup controller
4  */
5 #include <linux/cpufreq_times.h>
6 #include "sched.h"
7 #include <trace/hooks/sched.h>
8 
9 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
10 
11 /*
12  * There are no locks covering percpu hardirq/softirq time.
13  * They are only modified in vtime_account, on corresponding CPU
14  * with interrupts disabled. So, writes are safe.
15  * They are read and saved off onto struct rq in update_rq_clock().
16  * This may result in other CPU reading this CPU's irq time and can
17  * race with irq/vtime_account on this CPU. We would either get old
18  * or new value with a side effect of accounting a slice of irq time to wrong
19  * task when irq is in progress while we read rq->clock. That is a worthy
20  * compromise in place of having locks on each irq in account_system_time.
21  */
22 DEFINE_PER_CPU(struct irqtime, cpu_irqtime);
23 EXPORT_PER_CPU_SYMBOL_GPL(cpu_irqtime);
24 
25 static int sched_clock_irqtime;
26 
enable_sched_clock_irqtime(void)27 void enable_sched_clock_irqtime(void)
28 {
29 	sched_clock_irqtime = 1;
30 }
31 
disable_sched_clock_irqtime(void)32 void disable_sched_clock_irqtime(void)
33 {
34 	sched_clock_irqtime = 0;
35 }
36 
irqtime_account_delta(struct irqtime * irqtime,u64 delta,enum cpu_usage_stat idx)37 static void irqtime_account_delta(struct irqtime *irqtime, u64 delta,
38 				  enum cpu_usage_stat idx)
39 {
40 	u64 *cpustat = kcpustat_this_cpu->cpustat;
41 
42 	u64_stats_update_begin(&irqtime->sync);
43 	cpustat[idx] += delta;
44 	irqtime->total += delta;
45 	irqtime->tick_delta += delta;
46 	u64_stats_update_end(&irqtime->sync);
47 }
48 
49 /*
50  * Called before incrementing preempt_count on {soft,}irq_enter
51  * and before decrementing preempt_count on {soft,}irq_exit.
52  */
irqtime_account_irq(struct task_struct * curr)53 void irqtime_account_irq(struct task_struct *curr)
54 {
55 	struct irqtime *irqtime = this_cpu_ptr(&cpu_irqtime);
56 	s64 delta;
57 	int cpu;
58 
59 	if (!sched_clock_irqtime)
60 		return;
61 
62 	cpu = smp_processor_id();
63 	delta = sched_clock_cpu(cpu) - irqtime->irq_start_time;
64 	irqtime->irq_start_time += delta;
65 
66 	/*
67 	 * We do not account for softirq time from ksoftirqd here.
68 	 * We want to continue accounting softirq time to ksoftirqd thread
69 	 * in that case, so as not to confuse scheduler with a special task
70 	 * that do not consume any time, but still wants to run.
71 	 */
72 	if (hardirq_count())
73 		irqtime_account_delta(irqtime, delta, CPUTIME_IRQ);
74 	else if (in_serving_softirq() && curr != this_cpu_ksoftirqd())
75 		irqtime_account_delta(irqtime, delta, CPUTIME_SOFTIRQ);
76 }
77 EXPORT_SYMBOL_GPL(irqtime_account_irq);
78 
irqtime_tick_accounted(u64 maxtime)79 static u64 irqtime_tick_accounted(u64 maxtime)
80 {
81 	struct irqtime *irqtime = this_cpu_ptr(&cpu_irqtime);
82 	u64 delta;
83 
84 	delta = min(irqtime->tick_delta, maxtime);
85 	irqtime->tick_delta -= delta;
86 
87 	return delta;
88 }
89 
90 #else /* CONFIG_IRQ_TIME_ACCOUNTING */
91 
92 #define sched_clock_irqtime	(0)
93 
irqtime_tick_accounted(u64 dummy)94 static u64 irqtime_tick_accounted(u64 dummy)
95 {
96 	return 0;
97 }
98 
99 #endif /* !CONFIG_IRQ_TIME_ACCOUNTING */
100 
task_group_account_field(struct task_struct * p,int index,u64 tmp)101 static inline void task_group_account_field(struct task_struct *p, int index,
102 					    u64 tmp)
103 {
104 	/*
105 	 * Since all updates are sure to touch the root cgroup, we
106 	 * get ourselves ahead and touch it first. If the root cgroup
107 	 * is the only cgroup, then nothing else should be necessary.
108 	 *
109 	 */
110 	__this_cpu_add(kernel_cpustat.cpustat[index], tmp);
111 
112 	cgroup_account_cputime_field(p, index, tmp);
113 }
114 
115 /*
116  * Account user CPU time to a process.
117  * @p: the process that the CPU time gets accounted to
118  * @cputime: the CPU time spent in user space since the last update
119  */
account_user_time(struct task_struct * p,u64 cputime)120 void account_user_time(struct task_struct *p, u64 cputime)
121 {
122 	int index;
123 
124 	/* Add user time to process. */
125 	p->utime += cputime;
126 	account_group_user_time(p, cputime);
127 
128 	index = (task_nice(p) > 0) ? CPUTIME_NICE : CPUTIME_USER;
129 
130 	/* Add user time to cpustat. */
131 	task_group_account_field(p, index, cputime);
132 
133 	/* Account for user time used */
134 	acct_account_cputime(p);
135 
136 	/* Account power usage for user time */
137 	cpufreq_acct_update_power(p, cputime);
138 }
139 
140 /*
141  * Account guest CPU time to a process.
142  * @p: the process that the CPU time gets accounted to
143  * @cputime: the CPU time spent in virtual machine since the last update
144  */
account_guest_time(struct task_struct * p,u64 cputime)145 void account_guest_time(struct task_struct *p, u64 cputime)
146 {
147 	u64 *cpustat = kcpustat_this_cpu->cpustat;
148 
149 	/* Add guest time to process. */
150 	p->utime += cputime;
151 	account_group_user_time(p, cputime);
152 	p->gtime += cputime;
153 
154 	/* Add guest time to cpustat. */
155 	if (task_nice(p) > 0) {
156 		task_group_account_field(p, CPUTIME_NICE, cputime);
157 		cpustat[CPUTIME_GUEST_NICE] += cputime;
158 	} else {
159 		task_group_account_field(p, CPUTIME_USER, cputime);
160 		cpustat[CPUTIME_GUEST] += cputime;
161 	}
162 }
163 
164 /*
165  * Account system CPU time to a process and desired cpustat field
166  * @p: the process that the CPU time gets accounted to
167  * @cputime: the CPU time spent in kernel space since the last update
168  * @index: pointer to cpustat field that has to be updated
169  */
account_system_index_time(struct task_struct * p,u64 cputime,enum cpu_usage_stat index)170 void account_system_index_time(struct task_struct *p,
171 			       u64 cputime, enum cpu_usage_stat index)
172 {
173 	/* Add system time to process. */
174 	p->stime += cputime;
175 	account_group_system_time(p, cputime);
176 
177 	/* Add system time to cpustat. */
178 	task_group_account_field(p, index, cputime);
179 
180 	/* Account for system time used */
181 	acct_account_cputime(p);
182 
183 	/* Account power usage for system time */
184 	cpufreq_acct_update_power(p, cputime);
185 }
186 
187 /*
188  * Account system CPU time to a process.
189  * @p: the process that the CPU time gets accounted to
190  * @hardirq_offset: the offset to subtract from hardirq_count()
191  * @cputime: the CPU time spent in kernel space since the last update
192  */
account_system_time(struct task_struct * p,int hardirq_offset,u64 cputime)193 void account_system_time(struct task_struct *p, int hardirq_offset, u64 cputime)
194 {
195 	int index;
196 
197 	if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
198 		account_guest_time(p, cputime);
199 		return;
200 	}
201 
202 	if (hardirq_count() - hardirq_offset)
203 		index = CPUTIME_IRQ;
204 	else if (in_serving_softirq())
205 		index = CPUTIME_SOFTIRQ;
206 	else
207 		index = CPUTIME_SYSTEM;
208 
209 	account_system_index_time(p, cputime, index);
210 }
211 
212 /*
213  * Account for involuntary wait time.
214  * @cputime: the CPU time spent in involuntary wait
215  */
account_steal_time(u64 cputime)216 void account_steal_time(u64 cputime)
217 {
218 	u64 *cpustat = kcpustat_this_cpu->cpustat;
219 
220 	cpustat[CPUTIME_STEAL] += cputime;
221 }
222 
223 /*
224  * Account for idle time.
225  * @cputime: the CPU time spent in idle wait
226  */
account_idle_time(u64 cputime)227 void account_idle_time(u64 cputime)
228 {
229 	u64 *cpustat = kcpustat_this_cpu->cpustat;
230 	struct rq *rq = this_rq();
231 
232 	if (atomic_read(&rq->nr_iowait) > 0)
233 		cpustat[CPUTIME_IOWAIT] += cputime;
234 	else
235 		cpustat[CPUTIME_IDLE] += cputime;
236 }
237 
238 /*
239  * When a guest is interrupted for a longer amount of time, missed clock
240  * ticks are not redelivered later. Due to that, this function may on
241  * occasion account more time than the calling functions think elapsed.
242  */
steal_account_process_time(u64 maxtime)243 static __always_inline u64 steal_account_process_time(u64 maxtime)
244 {
245 #ifdef CONFIG_PARAVIRT
246 	if (static_key_false(&paravirt_steal_enabled)) {
247 		u64 steal;
248 
249 		steal = paravirt_steal_clock(smp_processor_id());
250 		steal -= this_rq()->prev_steal_time;
251 		steal = min(steal, maxtime);
252 		account_steal_time(steal);
253 		this_rq()->prev_steal_time += steal;
254 
255 		return steal;
256 	}
257 #endif
258 	return 0;
259 }
260 
261 /*
262  * Account how much elapsed time was spent in steal, irq, or softirq time.
263  */
account_other_time(u64 max)264 static inline u64 account_other_time(u64 max)
265 {
266 	u64 accounted;
267 
268 	lockdep_assert_irqs_disabled();
269 
270 	accounted = steal_account_process_time(max);
271 
272 	if (accounted < max)
273 		accounted += irqtime_tick_accounted(max - accounted);
274 
275 	return accounted;
276 }
277 
278 #ifdef CONFIG_64BIT
read_sum_exec_runtime(struct task_struct * t)279 static inline u64 read_sum_exec_runtime(struct task_struct *t)
280 {
281 	return t->se.sum_exec_runtime;
282 }
283 #else
read_sum_exec_runtime(struct task_struct * t)284 static u64 read_sum_exec_runtime(struct task_struct *t)
285 {
286 	u64 ns;
287 	struct rq_flags rf;
288 	struct rq *rq;
289 
290 	rq = task_rq_lock(t, &rf);
291 	ns = t->se.sum_exec_runtime;
292 	task_rq_unlock(rq, t, &rf);
293 
294 	return ns;
295 }
296 #endif
297 
298 /*
299  * Accumulate raw cputime values of dead tasks (sig->[us]time) and live
300  * tasks (sum on group iteration) belonging to @tsk's group.
301  */
thread_group_cputime(struct task_struct * tsk,struct task_cputime * times)302 void thread_group_cputime(struct task_struct *tsk, struct task_cputime *times)
303 {
304 	struct signal_struct *sig = tsk->signal;
305 	u64 utime, stime;
306 	struct task_struct *t;
307 	unsigned int seq, nextseq;
308 	unsigned long flags;
309 
310 	/*
311 	 * Update current task runtime to account pending time since last
312 	 * scheduler action or thread_group_cputime() call. This thread group
313 	 * might have other running tasks on different CPUs, but updating
314 	 * their runtime can affect syscall performance, so we skip account
315 	 * those pending times and rely only on values updated on tick or
316 	 * other scheduler action.
317 	 */
318 	if (same_thread_group(current, tsk))
319 		(void) task_sched_runtime(current);
320 
321 	rcu_read_lock();
322 	/* Attempt a lockless read on the first round. */
323 	nextseq = 0;
324 	do {
325 		seq = nextseq;
326 		flags = read_seqbegin_or_lock_irqsave(&sig->stats_lock, &seq);
327 		times->utime = sig->utime;
328 		times->stime = sig->stime;
329 		times->sum_exec_runtime = sig->sum_sched_runtime;
330 
331 		for_each_thread(tsk, t) {
332 			task_cputime(t, &utime, &stime);
333 			times->utime += utime;
334 			times->stime += stime;
335 			times->sum_exec_runtime += read_sum_exec_runtime(t);
336 		}
337 		/* If lockless access failed, take the lock. */
338 		nextseq = 1;
339 	} while (need_seqretry(&sig->stats_lock, seq));
340 	done_seqretry_irqrestore(&sig->stats_lock, seq, flags);
341 	rcu_read_unlock();
342 }
343 
344 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
345 /*
346  * Account a tick to a process and cpustat
347  * @p: the process that the CPU time gets accounted to
348  * @user_tick: is the tick from userspace
349  * @rq: the pointer to rq
350  *
351  * Tick demultiplexing follows the order
352  * - pending hardirq update
353  * - pending softirq update
354  * - user_time
355  * - idle_time
356  * - system time
357  *   - check for guest_time
358  *   - else account as system_time
359  *
360  * Check for hardirq is done both for system and user time as there is
361  * no timer going off while we are on hardirq and hence we may never get an
362  * opportunity to update it solely in system time.
363  * p->stime and friends are only updated on system time and not on irq
364  * softirq as those do not count in task exec_runtime any more.
365  */
irqtime_account_process_tick(struct task_struct * p,int user_tick,int ticks)366 static void irqtime_account_process_tick(struct task_struct *p, int user_tick,
367 					 int ticks)
368 {
369 	u64 other, cputime = TICK_NSEC * ticks;
370 
371 	/*
372 	 * When returning from idle, many ticks can get accounted at
373 	 * once, including some ticks of steal, irq, and softirq time.
374 	 * Subtract those ticks from the amount of time accounted to
375 	 * idle, or potentially user or system time. Due to rounding,
376 	 * other time can exceed ticks occasionally.
377 	 */
378 	other = account_other_time(ULONG_MAX);
379 	if (other >= cputime)
380 		return;
381 
382 	cputime -= other;
383 
384 	if (this_cpu_ksoftirqd() == p) {
385 		/*
386 		 * ksoftirqd time do not get accounted in cpu_softirq_time.
387 		 * So, we have to handle it separately here.
388 		 * Also, p->stime needs to be updated for ksoftirqd.
389 		 */
390 		account_system_index_time(p, cputime, CPUTIME_SOFTIRQ);
391 	} else if (user_tick) {
392 		account_user_time(p, cputime);
393 	} else if (p == this_rq()->idle) {
394 		account_idle_time(cputime);
395 	} else if (p->flags & PF_VCPU) { /* System time or guest time */
396 		account_guest_time(p, cputime);
397 	} else {
398 		account_system_index_time(p, cputime, CPUTIME_SYSTEM);
399 	}
400 	trace_android_vh_irqtime_account_process_tick(p, this_rq(), user_tick, ticks);
401 }
402 
irqtime_account_idle_ticks(int ticks)403 static void irqtime_account_idle_ticks(int ticks)
404 {
405 	irqtime_account_process_tick(current, 0, ticks);
406 }
407 #else /* CONFIG_IRQ_TIME_ACCOUNTING */
irqtime_account_idle_ticks(int ticks)408 static inline void irqtime_account_idle_ticks(int ticks) { }
irqtime_account_process_tick(struct task_struct * p,int user_tick,int nr_ticks)409 static inline void irqtime_account_process_tick(struct task_struct *p, int user_tick,
410 						int nr_ticks) { }
411 #endif /* CONFIG_IRQ_TIME_ACCOUNTING */
412 
413 /*
414  * Use precise platform statistics if available:
415  */
416 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
417 
418 # ifndef __ARCH_HAS_VTIME_TASK_SWITCH
vtime_task_switch(struct task_struct * prev)419 void vtime_task_switch(struct task_struct *prev)
420 {
421 	if (is_idle_task(prev))
422 		vtime_account_idle(prev);
423 	else
424 		vtime_account_kernel(prev);
425 
426 	vtime_flush(prev);
427 	arch_vtime_task_switch(prev);
428 }
429 # endif
430 
431 /*
432  * Archs that account the whole time spent in the idle task
433  * (outside irq) as idle time can rely on this and just implement
434  * vtime_account_kernel() and vtime_account_idle(). Archs that
435  * have other meaning of the idle time (s390 only includes the
436  * time spent by the CPU when it's in low power mode) must override
437  * vtime_account().
438  */
439 #ifndef __ARCH_HAS_VTIME_ACCOUNT
vtime_account_irq_enter(struct task_struct * tsk)440 void vtime_account_irq_enter(struct task_struct *tsk)
441 {
442 	if (!in_interrupt() && is_idle_task(tsk))
443 		vtime_account_idle(tsk);
444 	else
445 		vtime_account_kernel(tsk);
446 }
447 EXPORT_SYMBOL_GPL(vtime_account_irq_enter);
448 #endif /* __ARCH_HAS_VTIME_ACCOUNT */
449 
cputime_adjust(struct task_cputime * curr,struct prev_cputime * prev,u64 * ut,u64 * st)450 void cputime_adjust(struct task_cputime *curr, struct prev_cputime *prev,
451 		    u64 *ut, u64 *st)
452 {
453 	*ut = curr->utime;
454 	*st = curr->stime;
455 }
456 
task_cputime_adjusted(struct task_struct * p,u64 * ut,u64 * st)457 void task_cputime_adjusted(struct task_struct *p, u64 *ut, u64 *st)
458 {
459 	*ut = p->utime;
460 	*st = p->stime;
461 }
462 EXPORT_SYMBOL_GPL(task_cputime_adjusted);
463 
thread_group_cputime_adjusted(struct task_struct * p,u64 * ut,u64 * st)464 void thread_group_cputime_adjusted(struct task_struct *p, u64 *ut, u64 *st)
465 {
466 	struct task_cputime cputime;
467 
468 	thread_group_cputime(p, &cputime);
469 
470 	*ut = cputime.utime;
471 	*st = cputime.stime;
472 }
473 EXPORT_SYMBOL_GPL(thread_group_cputime_adjusted);
474 
475 #else /* !CONFIG_VIRT_CPU_ACCOUNTING_NATIVE: */
476 
477 /*
478  * Account a single tick of CPU time.
479  * @p: the process that the CPU time gets accounted to
480  * @user_tick: indicates if the tick is a user or a system tick
481  */
account_process_tick(struct task_struct * p,int user_tick)482 void account_process_tick(struct task_struct *p, int user_tick)
483 {
484 	u64 cputime, steal;
485 
486 	if (vtime_accounting_enabled_this_cpu())
487 		return;
488 	trace_android_vh_account_task_time(p, this_rq(), user_tick);
489 
490 	if (sched_clock_irqtime) {
491 		irqtime_account_process_tick(p, user_tick, 1);
492 		return;
493 	}
494 
495 	cputime = TICK_NSEC;
496 	steal = steal_account_process_time(ULONG_MAX);
497 
498 	if (steal >= cputime)
499 		return;
500 
501 	cputime -= steal;
502 
503 	if (user_tick)
504 		account_user_time(p, cputime);
505 	else if ((p != this_rq()->idle) || (irq_count() != HARDIRQ_OFFSET))
506 		account_system_time(p, HARDIRQ_OFFSET, cputime);
507 	else
508 		account_idle_time(cputime);
509 }
510 
511 /*
512  * Account multiple ticks of idle time.
513  * @ticks: number of stolen ticks
514  */
account_idle_ticks(unsigned long ticks)515 void account_idle_ticks(unsigned long ticks)
516 {
517 	u64 cputime, steal;
518 
519 	if (sched_clock_irqtime) {
520 		irqtime_account_idle_ticks(ticks);
521 		return;
522 	}
523 
524 	cputime = ticks * TICK_NSEC;
525 	steal = steal_account_process_time(ULONG_MAX);
526 
527 	if (steal >= cputime)
528 		return;
529 
530 	cputime -= steal;
531 	account_idle_time(cputime);
532 }
533 
534 /*
535  * Adjust tick based cputime random precision against scheduler runtime
536  * accounting.
537  *
538  * Tick based cputime accounting depend on random scheduling timeslices of a
539  * task to be interrupted or not by the timer.  Depending on these
540  * circumstances, the number of these interrupts may be over or
541  * under-optimistic, matching the real user and system cputime with a variable
542  * precision.
543  *
544  * Fix this by scaling these tick based values against the total runtime
545  * accounted by the CFS scheduler.
546  *
547  * This code provides the following guarantees:
548  *
549  *   stime + utime == rtime
550  *   stime_i+1 >= stime_i, utime_i+1 >= utime_i
551  *
552  * Assuming that rtime_i+1 >= rtime_i.
553  */
cputime_adjust(struct task_cputime * curr,struct prev_cputime * prev,u64 * ut,u64 * st)554 void cputime_adjust(struct task_cputime *curr, struct prev_cputime *prev,
555 		    u64 *ut, u64 *st)
556 {
557 	u64 rtime, stime, utime;
558 	unsigned long flags;
559 
560 	/* Serialize concurrent callers such that we can honour our guarantees */
561 	raw_spin_lock_irqsave(&prev->lock, flags);
562 	rtime = curr->sum_exec_runtime;
563 
564 	/*
565 	 * This is possible under two circumstances:
566 	 *  - rtime isn't monotonic after all (a bug);
567 	 *  - we got reordered by the lock.
568 	 *
569 	 * In both cases this acts as a filter such that the rest of the code
570 	 * can assume it is monotonic regardless of anything else.
571 	 */
572 	if (prev->stime + prev->utime >= rtime)
573 		goto out;
574 
575 	stime = curr->stime;
576 	utime = curr->utime;
577 
578 	/*
579 	 * If either stime or utime are 0, assume all runtime is userspace.
580 	 * Once a task gets some ticks, the monotonicy code at 'update:'
581 	 * will ensure things converge to the observed ratio.
582 	 */
583 	if (stime == 0) {
584 		utime = rtime;
585 		goto update;
586 	}
587 
588 	if (utime == 0) {
589 		stime = rtime;
590 		goto update;
591 	}
592 
593 	stime = mul_u64_u64_div_u64(stime, rtime, stime + utime);
594 
595 update:
596 	/*
597 	 * Make sure stime doesn't go backwards; this preserves monotonicity
598 	 * for utime because rtime is monotonic.
599 	 *
600 	 *  utime_i+1 = rtime_i+1 - stime_i
601 	 *            = rtime_i+1 - (rtime_i - utime_i)
602 	 *            = (rtime_i+1 - rtime_i) + utime_i
603 	 *            >= utime_i
604 	 */
605 	if (stime < prev->stime)
606 		stime = prev->stime;
607 	utime = rtime - stime;
608 
609 	/*
610 	 * Make sure utime doesn't go backwards; this still preserves
611 	 * monotonicity for stime, analogous argument to above.
612 	 */
613 	if (utime < prev->utime) {
614 		utime = prev->utime;
615 		stime = rtime - utime;
616 	}
617 
618 	prev->stime = stime;
619 	prev->utime = utime;
620 out:
621 	*ut = prev->utime;
622 	*st = prev->stime;
623 	raw_spin_unlock_irqrestore(&prev->lock, flags);
624 }
625 
task_cputime_adjusted(struct task_struct * p,u64 * ut,u64 * st)626 void task_cputime_adjusted(struct task_struct *p, u64 *ut, u64 *st)
627 {
628 	struct task_cputime cputime = {
629 		.sum_exec_runtime = p->se.sum_exec_runtime,
630 	};
631 
632 	task_cputime(p, &cputime.utime, &cputime.stime);
633 	cputime_adjust(&cputime, &p->prev_cputime, ut, st);
634 }
635 EXPORT_SYMBOL_GPL(task_cputime_adjusted);
636 
thread_group_cputime_adjusted(struct task_struct * p,u64 * ut,u64 * st)637 void thread_group_cputime_adjusted(struct task_struct *p, u64 *ut, u64 *st)
638 {
639 	struct task_cputime cputime;
640 
641 	thread_group_cputime(p, &cputime);
642 	cputime_adjust(&cputime, &p->signal->prev_cputime, ut, st);
643 }
644 EXPORT_SYMBOL_GPL(thread_group_cputime_adjusted);
645 
646 #endif /* !CONFIG_VIRT_CPU_ACCOUNTING_NATIVE */
647 
648 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
vtime_delta(struct vtime * vtime)649 static u64 vtime_delta(struct vtime *vtime)
650 {
651 	unsigned long long clock;
652 
653 	clock = sched_clock();
654 	if (clock < vtime->starttime)
655 		return 0;
656 
657 	return clock - vtime->starttime;
658 }
659 
get_vtime_delta(struct vtime * vtime)660 static u64 get_vtime_delta(struct vtime *vtime)
661 {
662 	u64 delta = vtime_delta(vtime);
663 	u64 other;
664 
665 	/*
666 	 * Unlike tick based timing, vtime based timing never has lost
667 	 * ticks, and no need for steal time accounting to make up for
668 	 * lost ticks. Vtime accounts a rounded version of actual
669 	 * elapsed time. Limit account_other_time to prevent rounding
670 	 * errors from causing elapsed vtime to go negative.
671 	 */
672 	other = account_other_time(delta);
673 	WARN_ON_ONCE(vtime->state == VTIME_INACTIVE);
674 	vtime->starttime += delta;
675 
676 	return delta - other;
677 }
678 
vtime_account_system(struct task_struct * tsk,struct vtime * vtime)679 static void vtime_account_system(struct task_struct *tsk,
680 				 struct vtime *vtime)
681 {
682 	vtime->stime += get_vtime_delta(vtime);
683 	if (vtime->stime >= TICK_NSEC) {
684 		account_system_time(tsk, irq_count(), vtime->stime);
685 		vtime->stime = 0;
686 	}
687 }
688 
vtime_account_guest(struct task_struct * tsk,struct vtime * vtime)689 static void vtime_account_guest(struct task_struct *tsk,
690 				struct vtime *vtime)
691 {
692 	vtime->gtime += get_vtime_delta(vtime);
693 	if (vtime->gtime >= TICK_NSEC) {
694 		account_guest_time(tsk, vtime->gtime);
695 		vtime->gtime = 0;
696 	}
697 }
698 
__vtime_account_kernel(struct task_struct * tsk,struct vtime * vtime)699 static void __vtime_account_kernel(struct task_struct *tsk,
700 				   struct vtime *vtime)
701 {
702 	/* We might have scheduled out from guest path */
703 	if (vtime->state == VTIME_GUEST)
704 		vtime_account_guest(tsk, vtime);
705 	else
706 		vtime_account_system(tsk, vtime);
707 }
708 
vtime_account_kernel(struct task_struct * tsk)709 void vtime_account_kernel(struct task_struct *tsk)
710 {
711 	struct vtime *vtime = &tsk->vtime;
712 
713 	if (!vtime_delta(vtime))
714 		return;
715 
716 	write_seqcount_begin(&vtime->seqcount);
717 	__vtime_account_kernel(tsk, vtime);
718 	write_seqcount_end(&vtime->seqcount);
719 }
720 
vtime_user_enter(struct task_struct * tsk)721 void vtime_user_enter(struct task_struct *tsk)
722 {
723 	struct vtime *vtime = &tsk->vtime;
724 
725 	write_seqcount_begin(&vtime->seqcount);
726 	vtime_account_system(tsk, vtime);
727 	vtime->state = VTIME_USER;
728 	write_seqcount_end(&vtime->seqcount);
729 }
730 
vtime_user_exit(struct task_struct * tsk)731 void vtime_user_exit(struct task_struct *tsk)
732 {
733 	struct vtime *vtime = &tsk->vtime;
734 
735 	write_seqcount_begin(&vtime->seqcount);
736 	vtime->utime += get_vtime_delta(vtime);
737 	if (vtime->utime >= TICK_NSEC) {
738 		account_user_time(tsk, vtime->utime);
739 		vtime->utime = 0;
740 	}
741 	vtime->state = VTIME_SYS;
742 	write_seqcount_end(&vtime->seqcount);
743 }
744 
vtime_guest_enter(struct task_struct * tsk)745 void vtime_guest_enter(struct task_struct *tsk)
746 {
747 	struct vtime *vtime = &tsk->vtime;
748 	/*
749 	 * The flags must be updated under the lock with
750 	 * the vtime_starttime flush and update.
751 	 * That enforces a right ordering and update sequence
752 	 * synchronization against the reader (task_gtime())
753 	 * that can thus safely catch up with a tickless delta.
754 	 */
755 	write_seqcount_begin(&vtime->seqcount);
756 	vtime_account_system(tsk, vtime);
757 	tsk->flags |= PF_VCPU;
758 	vtime->state = VTIME_GUEST;
759 	write_seqcount_end(&vtime->seqcount);
760 }
761 EXPORT_SYMBOL_GPL(vtime_guest_enter);
762 
vtime_guest_exit(struct task_struct * tsk)763 void vtime_guest_exit(struct task_struct *tsk)
764 {
765 	struct vtime *vtime = &tsk->vtime;
766 
767 	write_seqcount_begin(&vtime->seqcount);
768 	vtime_account_guest(tsk, vtime);
769 	tsk->flags &= ~PF_VCPU;
770 	vtime->state = VTIME_SYS;
771 	write_seqcount_end(&vtime->seqcount);
772 }
773 EXPORT_SYMBOL_GPL(vtime_guest_exit);
774 
vtime_account_idle(struct task_struct * tsk)775 void vtime_account_idle(struct task_struct *tsk)
776 {
777 	account_idle_time(get_vtime_delta(&tsk->vtime));
778 }
779 
vtime_task_switch_generic(struct task_struct * prev)780 void vtime_task_switch_generic(struct task_struct *prev)
781 {
782 	struct vtime *vtime = &prev->vtime;
783 
784 	write_seqcount_begin(&vtime->seqcount);
785 	if (vtime->state == VTIME_IDLE)
786 		vtime_account_idle(prev);
787 	else
788 		__vtime_account_kernel(prev, vtime);
789 	vtime->state = VTIME_INACTIVE;
790 	vtime->cpu = -1;
791 	write_seqcount_end(&vtime->seqcount);
792 
793 	vtime = &current->vtime;
794 
795 	write_seqcount_begin(&vtime->seqcount);
796 	if (is_idle_task(current))
797 		vtime->state = VTIME_IDLE;
798 	else if (current->flags & PF_VCPU)
799 		vtime->state = VTIME_GUEST;
800 	else
801 		vtime->state = VTIME_SYS;
802 	vtime->starttime = sched_clock();
803 	vtime->cpu = smp_processor_id();
804 	write_seqcount_end(&vtime->seqcount);
805 }
806 
vtime_init_idle(struct task_struct * t,int cpu)807 void vtime_init_idle(struct task_struct *t, int cpu)
808 {
809 	struct vtime *vtime = &t->vtime;
810 	unsigned long flags;
811 
812 	local_irq_save(flags);
813 	write_seqcount_begin(&vtime->seqcount);
814 	vtime->state = VTIME_IDLE;
815 	vtime->starttime = sched_clock();
816 	vtime->cpu = cpu;
817 	write_seqcount_end(&vtime->seqcount);
818 	local_irq_restore(flags);
819 }
820 
task_gtime(struct task_struct * t)821 u64 task_gtime(struct task_struct *t)
822 {
823 	struct vtime *vtime = &t->vtime;
824 	unsigned int seq;
825 	u64 gtime;
826 
827 	if (!vtime_accounting_enabled())
828 		return t->gtime;
829 
830 	do {
831 		seq = read_seqcount_begin(&vtime->seqcount);
832 
833 		gtime = t->gtime;
834 		if (vtime->state == VTIME_GUEST)
835 			gtime += vtime->gtime + vtime_delta(vtime);
836 
837 	} while (read_seqcount_retry(&vtime->seqcount, seq));
838 
839 	return gtime;
840 }
841 
842 /*
843  * Fetch cputime raw values from fields of task_struct and
844  * add up the pending nohz execution time since the last
845  * cputime snapshot.
846  */
task_cputime(struct task_struct * t,u64 * utime,u64 * stime)847 void task_cputime(struct task_struct *t, u64 *utime, u64 *stime)
848 {
849 	struct vtime *vtime = &t->vtime;
850 	unsigned int seq;
851 	u64 delta;
852 
853 	if (!vtime_accounting_enabled()) {
854 		*utime = t->utime;
855 		*stime = t->stime;
856 		return;
857 	}
858 
859 	do {
860 		seq = read_seqcount_begin(&vtime->seqcount);
861 
862 		*utime = t->utime;
863 		*stime = t->stime;
864 
865 		/* Task is sleeping or idle, nothing to add */
866 		if (vtime->state < VTIME_SYS)
867 			continue;
868 
869 		delta = vtime_delta(vtime);
870 
871 		/*
872 		 * Task runs either in user (including guest) or kernel space,
873 		 * add pending nohz time to the right place.
874 		 */
875 		if (vtime->state == VTIME_SYS)
876 			*stime += vtime->stime + delta;
877 		else
878 			*utime += vtime->utime + delta;
879 	} while (read_seqcount_retry(&vtime->seqcount, seq));
880 }
881 
vtime_state_fetch(struct vtime * vtime,int cpu)882 static int vtime_state_fetch(struct vtime *vtime, int cpu)
883 {
884 	int state = READ_ONCE(vtime->state);
885 
886 	/*
887 	 * We raced against a context switch, fetch the
888 	 * kcpustat task again.
889 	 */
890 	if (vtime->cpu != cpu && vtime->cpu != -1)
891 		return -EAGAIN;
892 
893 	/*
894 	 * Two possible things here:
895 	 * 1) We are seeing the scheduling out task (prev) or any past one.
896 	 * 2) We are seeing the scheduling in task (next) but it hasn't
897 	 *    passed though vtime_task_switch() yet so the pending
898 	 *    cputime of the prev task may not be flushed yet.
899 	 *
900 	 * Case 1) is ok but 2) is not. So wait for a safe VTIME state.
901 	 */
902 	if (state == VTIME_INACTIVE)
903 		return -EAGAIN;
904 
905 	return state;
906 }
907 
kcpustat_user_vtime(struct vtime * vtime)908 static u64 kcpustat_user_vtime(struct vtime *vtime)
909 {
910 	if (vtime->state == VTIME_USER)
911 		return vtime->utime + vtime_delta(vtime);
912 	else if (vtime->state == VTIME_GUEST)
913 		return vtime->gtime + vtime_delta(vtime);
914 	return 0;
915 }
916 
kcpustat_field_vtime(u64 * cpustat,struct task_struct * tsk,enum cpu_usage_stat usage,int cpu,u64 * val)917 static int kcpustat_field_vtime(u64 *cpustat,
918 				struct task_struct *tsk,
919 				enum cpu_usage_stat usage,
920 				int cpu, u64 *val)
921 {
922 	struct vtime *vtime = &tsk->vtime;
923 	unsigned int seq;
924 
925 	do {
926 		int state;
927 
928 		seq = read_seqcount_begin(&vtime->seqcount);
929 
930 		state = vtime_state_fetch(vtime, cpu);
931 		if (state < 0)
932 			return state;
933 
934 		*val = cpustat[usage];
935 
936 		/*
937 		 * Nice VS unnice cputime accounting may be inaccurate if
938 		 * the nice value has changed since the last vtime update.
939 		 * But proper fix would involve interrupting target on nice
940 		 * updates which is a no go on nohz_full (although the scheduler
941 		 * may still interrupt the target if rescheduling is needed...)
942 		 */
943 		switch (usage) {
944 		case CPUTIME_SYSTEM:
945 			if (state == VTIME_SYS)
946 				*val += vtime->stime + vtime_delta(vtime);
947 			break;
948 		case CPUTIME_USER:
949 			if (task_nice(tsk) <= 0)
950 				*val += kcpustat_user_vtime(vtime);
951 			break;
952 		case CPUTIME_NICE:
953 			if (task_nice(tsk) > 0)
954 				*val += kcpustat_user_vtime(vtime);
955 			break;
956 		case CPUTIME_GUEST:
957 			if (state == VTIME_GUEST && task_nice(tsk) <= 0)
958 				*val += vtime->gtime + vtime_delta(vtime);
959 			break;
960 		case CPUTIME_GUEST_NICE:
961 			if (state == VTIME_GUEST && task_nice(tsk) > 0)
962 				*val += vtime->gtime + vtime_delta(vtime);
963 			break;
964 		default:
965 			break;
966 		}
967 	} while (read_seqcount_retry(&vtime->seqcount, seq));
968 
969 	return 0;
970 }
971 
kcpustat_field(struct kernel_cpustat * kcpustat,enum cpu_usage_stat usage,int cpu)972 u64 kcpustat_field(struct kernel_cpustat *kcpustat,
973 		   enum cpu_usage_stat usage, int cpu)
974 {
975 	u64 *cpustat = kcpustat->cpustat;
976 	u64 val = cpustat[usage];
977 	struct rq *rq;
978 	int err;
979 
980 	if (!vtime_accounting_enabled_cpu(cpu))
981 		return val;
982 
983 	rq = cpu_rq(cpu);
984 
985 	for (;;) {
986 		struct task_struct *curr;
987 
988 		rcu_read_lock();
989 		curr = rcu_dereference(rq->curr);
990 		if (WARN_ON_ONCE(!curr)) {
991 			rcu_read_unlock();
992 			return cpustat[usage];
993 		}
994 
995 		err = kcpustat_field_vtime(cpustat, curr, usage, cpu, &val);
996 		rcu_read_unlock();
997 
998 		if (!err)
999 			return val;
1000 
1001 		cpu_relax();
1002 	}
1003 }
1004 EXPORT_SYMBOL_GPL(kcpustat_field);
1005 
kcpustat_cpu_fetch_vtime(struct kernel_cpustat * dst,const struct kernel_cpustat * src,struct task_struct * tsk,int cpu)1006 static int kcpustat_cpu_fetch_vtime(struct kernel_cpustat *dst,
1007 				    const struct kernel_cpustat *src,
1008 				    struct task_struct *tsk, int cpu)
1009 {
1010 	struct vtime *vtime = &tsk->vtime;
1011 	unsigned int seq;
1012 
1013 	do {
1014 		u64 *cpustat;
1015 		u64 delta;
1016 		int state;
1017 
1018 		seq = read_seqcount_begin(&vtime->seqcount);
1019 
1020 		state = vtime_state_fetch(vtime, cpu);
1021 		if (state < 0)
1022 			return state;
1023 
1024 		*dst = *src;
1025 		cpustat = dst->cpustat;
1026 
1027 		/* Task is sleeping, dead or idle, nothing to add */
1028 		if (state < VTIME_SYS)
1029 			continue;
1030 
1031 		delta = vtime_delta(vtime);
1032 
1033 		/*
1034 		 * Task runs either in user (including guest) or kernel space,
1035 		 * add pending nohz time to the right place.
1036 		 */
1037 		if (state == VTIME_SYS) {
1038 			cpustat[CPUTIME_SYSTEM] += vtime->stime + delta;
1039 		} else if (state == VTIME_USER) {
1040 			if (task_nice(tsk) > 0)
1041 				cpustat[CPUTIME_NICE] += vtime->utime + delta;
1042 			else
1043 				cpustat[CPUTIME_USER] += vtime->utime + delta;
1044 		} else {
1045 			WARN_ON_ONCE(state != VTIME_GUEST);
1046 			if (task_nice(tsk) > 0) {
1047 				cpustat[CPUTIME_GUEST_NICE] += vtime->gtime + delta;
1048 				cpustat[CPUTIME_NICE] += vtime->gtime + delta;
1049 			} else {
1050 				cpustat[CPUTIME_GUEST] += vtime->gtime + delta;
1051 				cpustat[CPUTIME_USER] += vtime->gtime + delta;
1052 			}
1053 		}
1054 	} while (read_seqcount_retry(&vtime->seqcount, seq));
1055 
1056 	return 0;
1057 }
1058 
kcpustat_cpu_fetch(struct kernel_cpustat * dst,int cpu)1059 void kcpustat_cpu_fetch(struct kernel_cpustat *dst, int cpu)
1060 {
1061 	const struct kernel_cpustat *src = &kcpustat_cpu(cpu);
1062 	struct rq *rq;
1063 	int err;
1064 
1065 	if (!vtime_accounting_enabled_cpu(cpu)) {
1066 		*dst = *src;
1067 		return;
1068 	}
1069 
1070 	rq = cpu_rq(cpu);
1071 
1072 	for (;;) {
1073 		struct task_struct *curr;
1074 
1075 		rcu_read_lock();
1076 		curr = rcu_dereference(rq->curr);
1077 		if (WARN_ON_ONCE(!curr)) {
1078 			rcu_read_unlock();
1079 			*dst = *src;
1080 			return;
1081 		}
1082 
1083 		err = kcpustat_cpu_fetch_vtime(dst, src, curr, cpu);
1084 		rcu_read_unlock();
1085 
1086 		if (!err)
1087 			return;
1088 
1089 		cpu_relax();
1090 	}
1091 }
1092 EXPORT_SYMBOL_GPL(kcpustat_cpu_fetch);
1093 
1094 #endif /* CONFIG_VIRT_CPU_ACCOUNTING_GEN */
1095