sched/walt: Accounting for number of irqs pending on each core
[firefly-linux-kernel-4.4.55.git] / kernel / sched / walt.c
1 /*
2  * Copyright (c) 2016, The Linux Foundation. All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 and
6  * only version 2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  *
14  * Window Assisted Load Tracking (WALT) implementation credits:
15  * Srivatsa Vaddagiri, Steve Muckle, Syed Rameez Mustafa, Joonwoo Park,
16  * Pavan Kumar Kondeti, Olav Haugan
17  *
18  * 2016-03-06: Integration with EAS/refactoring by Vikram Mulukutla
19  *             and Todd Kjos
20  */
21
22 #include <linux/syscore_ops.h>
23 #include <linux/cpufreq.h>
24 #include <trace/events/sched.h>
25 #include "sched.h"
26 #include "walt.h"
27
28 #define WINDOW_STATS_RECENT             0
29 #define WINDOW_STATS_MAX                1
30 #define WINDOW_STATS_MAX_RECENT_AVG     2
31 #define WINDOW_STATS_AVG                3
32 #define WINDOW_STATS_INVALID_POLICY     4
33
34 #define EXITING_TASK_MARKER     0xdeaddead
35
36 static __read_mostly unsigned int walt_ravg_hist_size = 5;
37 static __read_mostly unsigned int walt_window_stats_policy =
38         WINDOW_STATS_MAX_RECENT_AVG;
39 static __read_mostly unsigned int walt_account_wait_time = 1;
40 static __read_mostly unsigned int walt_freq_account_wait_time = 0;
41 static __read_mostly unsigned int walt_io_is_busy = 0;
42
43 unsigned int sysctl_sched_walt_init_task_load_pct = 15;
44
45 /* 1 -> use PELT based load stats, 0 -> use window-based load stats */
46 unsigned int __read_mostly walt_disabled = 0;
47
48 static unsigned int max_possible_efficiency = 1024;
49 static unsigned int min_possible_efficiency = 1024;
50
51 /*
52  * Maximum possible frequency across all cpus. Task demand and cpu
53  * capacity (cpu_power) metrics are scaled in reference to it.
54  */
55 static unsigned int max_possible_freq = 1;
56
57 /*
58  * Minimum possible max_freq across all cpus. This will be same as
59  * max_possible_freq on homogeneous systems and could be different from
60  * max_possible_freq on heterogenous systems. min_max_freq is used to derive
61  * capacity (cpu_power) of cpus.
62  */
63 static unsigned int min_max_freq = 1;
64
65 static unsigned int max_capacity = 1024;
66 static unsigned int min_capacity = 1024;
67 static unsigned int max_load_scale_factor = 1024;
68 static unsigned int max_possible_capacity = 1024;
69
70 /* Mask of all CPUs that have  max_possible_capacity */
71 static cpumask_t mpc_mask = CPU_MASK_ALL;
72
73 /* Window size (in ns) */
74 __read_mostly unsigned int walt_ravg_window = 20000000;
75
76 /* Min window size (in ns) = 10ms */
77 #define MIN_SCHED_RAVG_WINDOW 10000000
78
79 /* Max window size (in ns) = 1s */
80 #define MAX_SCHED_RAVG_WINDOW 1000000000
81
82 static unsigned int sync_cpu;
83 static ktime_t ktime_last;
84 static bool walt_ktime_suspended;
85
86 static unsigned int task_load(struct task_struct *p)
87 {
88         return p->ravg.demand;
89 }
90
91 void
92 walt_inc_cumulative_runnable_avg(struct rq *rq,
93                                  struct task_struct *p)
94 {
95         rq->cumulative_runnable_avg += p->ravg.demand;
96 }
97
98 void
99 walt_dec_cumulative_runnable_avg(struct rq *rq,
100                                  struct task_struct *p)
101 {
102         rq->cumulative_runnable_avg -= p->ravg.demand;
103         BUG_ON((s64)rq->cumulative_runnable_avg < 0);
104 }
105
106 static void
107 fixup_cumulative_runnable_avg(struct rq *rq,
108                               struct task_struct *p, s64 task_load_delta)
109 {
110         rq->cumulative_runnable_avg += task_load_delta;
111         if ((s64)rq->cumulative_runnable_avg < 0)
112                 panic("cra less than zero: tld: %lld, task_load(p) = %u\n",
113                         task_load_delta, task_load(p));
114 }
115
116 u64 walt_ktime_clock(void)
117 {
118         if (unlikely(walt_ktime_suspended))
119                 return ktime_to_ns(ktime_last);
120         return ktime_get_ns();
121 }
122
123 static void walt_resume(void)
124 {
125         walt_ktime_suspended = false;
126 }
127
128 static int walt_suspend(void)
129 {
130         ktime_last = ktime_get();
131         walt_ktime_suspended = true;
132         return 0;
133 }
134
135 static struct syscore_ops walt_syscore_ops = {
136         .resume = walt_resume,
137         .suspend = walt_suspend
138 };
139
140 static int __init walt_init_ops(void)
141 {
142         register_syscore_ops(&walt_syscore_ops);
143         return 0;
144 }
145 late_initcall(walt_init_ops);
146
147 void walt_inc_cfs_cumulative_runnable_avg(struct cfs_rq *cfs_rq,
148                 struct task_struct *p)
149 {
150         cfs_rq->cumulative_runnable_avg += p->ravg.demand;
151 }
152
153 void walt_dec_cfs_cumulative_runnable_avg(struct cfs_rq *cfs_rq,
154                 struct task_struct *p)
155 {
156         cfs_rq->cumulative_runnable_avg -= p->ravg.demand;
157 }
158
159 static int exiting_task(struct task_struct *p)
160 {
161         if (p->flags & PF_EXITING) {
162                 if (p->ravg.sum_history[0] != EXITING_TASK_MARKER) {
163                         p->ravg.sum_history[0] = EXITING_TASK_MARKER;
164                 }
165                 return 1;
166         }
167         return 0;
168 }
169
170 static int __init set_walt_ravg_window(char *str)
171 {
172         get_option(&str, &walt_ravg_window);
173
174         walt_disabled = (walt_ravg_window < MIN_SCHED_RAVG_WINDOW ||
175                                 walt_ravg_window > MAX_SCHED_RAVG_WINDOW);
176         return 0;
177 }
178
179 early_param("walt_ravg_window", set_walt_ravg_window);
180
181 static void
182 update_window_start(struct rq *rq, u64 wallclock)
183 {
184         s64 delta;
185         int nr_windows;
186
187         delta = wallclock - rq->window_start;
188         BUG_ON(delta < 0);
189         if (delta < walt_ravg_window)
190                 return;
191
192         nr_windows = div64_u64(delta, walt_ravg_window);
193         rq->window_start += (u64)nr_windows * (u64)walt_ravg_window;
194 }
195
196 static u64 scale_exec_time(u64 delta, struct rq *rq)
197 {
198         unsigned int cur_freq = rq->cur_freq;
199         int sf;
200
201         if (unlikely(cur_freq > max_possible_freq))
202                 cur_freq = rq->max_possible_freq;
203
204         /* round up div64 */
205         delta = div64_u64(delta * cur_freq + max_possible_freq - 1,
206                           max_possible_freq);
207
208         sf = DIV_ROUND_UP(rq->efficiency * 1024, max_possible_efficiency);
209
210         delta *= sf;
211         delta >>= 10;
212
213         return delta;
214 }
215
216 static int cpu_is_waiting_on_io(struct rq *rq)
217 {
218         if (!walt_io_is_busy)
219                 return 0;
220
221         return atomic_read(&rq->nr_iowait);
222 }
223
224 void walt_account_irqtime(int cpu, struct task_struct *curr,
225                                  u64 delta, u64 wallclock)
226 {
227         struct rq *rq = cpu_rq(cpu);
228         unsigned long flags, nr_windows;
229         u64 cur_jiffies_ts;
230
231         raw_spin_lock_irqsave(&rq->lock, flags);
232
233         /*
234          * cputime (wallclock) uses sched_clock so use the same here for
235          * consistency.
236          */
237         delta += sched_clock() - wallclock;
238         cur_jiffies_ts = get_jiffies_64();
239
240         if (is_idle_task(curr))
241                 walt_update_task_ravg(curr, rq, IRQ_UPDATE, walt_ktime_clock(),
242                                  delta);
243
244         nr_windows = cur_jiffies_ts - rq->irqload_ts;
245
246         if (nr_windows) {
247                 if (nr_windows < 10) {
248                         /* Decay CPU's irqload by 3/4 for each window. */
249                         rq->avg_irqload *= (3 * nr_windows);
250                         rq->avg_irqload = div64_u64(rq->avg_irqload,
251                                                     4 * nr_windows);
252                 } else {
253                         rq->avg_irqload = 0;
254                 }
255                 rq->avg_irqload += rq->cur_irqload;
256                 rq->cur_irqload = 0;
257         }
258
259         rq->cur_irqload += delta;
260         rq->irqload_ts = cur_jiffies_ts;
261         raw_spin_unlock_irqrestore(&rq->lock, flags);
262 }
263
264
265 #define WALT_HIGH_IRQ_TIMEOUT 3
266
267 u64 walt_irqload(int cpu) {
268         struct rq *rq = cpu_rq(cpu);
269         s64 delta;
270         delta = get_jiffies_64() - rq->irqload_ts;
271
272         /*
273          * Current context can be preempted by irq and rq->irqload_ts can be
274          * updated by irq context so that delta can be negative.
275          * But this is okay and we can safely return as this means there
276          * was recent irq occurrence.
277          */
278
279         if (delta < WALT_HIGH_IRQ_TIMEOUT)
280                 return rq->avg_irqload;
281         else
282                 return 0;
283 }
284
285 int walt_cpu_high_irqload(int cpu) {
286         return walt_irqload(cpu) >= sysctl_sched_walt_cpu_high_irqload;
287 }
288
289 static int account_busy_for_cpu_time(struct rq *rq, struct task_struct *p,
290                                      u64 irqtime, int event)
291 {
292         if (is_idle_task(p)) {
293                 /* TASK_WAKE && TASK_MIGRATE is not possible on idle task! */
294                 if (event == PICK_NEXT_TASK)
295                         return 0;
296
297                 /* PUT_PREV_TASK, TASK_UPDATE && IRQ_UPDATE are left */
298                 return irqtime || cpu_is_waiting_on_io(rq);
299         }
300
301         if (event == TASK_WAKE)
302                 return 0;
303
304         if (event == PUT_PREV_TASK || event == IRQ_UPDATE ||
305                                          event == TASK_UPDATE)
306                 return 1;
307
308         /* Only TASK_MIGRATE && PICK_NEXT_TASK left */
309         return walt_freq_account_wait_time;
310 }
311
312 /*
313  * Account cpu activity in its busy time counters (rq->curr/prev_runnable_sum)
314  */
315 static void update_cpu_busy_time(struct task_struct *p, struct rq *rq,
316              int event, u64 wallclock, u64 irqtime)
317 {
318         int new_window, nr_full_windows = 0;
319         int p_is_curr_task = (p == rq->curr);
320         u64 mark_start = p->ravg.mark_start;
321         u64 window_start = rq->window_start;
322         u32 window_size = walt_ravg_window;
323         u64 delta;
324
325         new_window = mark_start < window_start;
326         if (new_window) {
327                 nr_full_windows = div64_u64((window_start - mark_start),
328                                                 window_size);
329                 if (p->ravg.active_windows < USHRT_MAX)
330                         p->ravg.active_windows++;
331         }
332
333         /* Handle per-task window rollover. We don't care about the idle
334          * task or exiting tasks. */
335         if (new_window && !is_idle_task(p) && !exiting_task(p)) {
336                 u32 curr_window = 0;
337
338                 if (!nr_full_windows)
339                         curr_window = p->ravg.curr_window;
340
341                 p->ravg.prev_window = curr_window;
342                 p->ravg.curr_window = 0;
343         }
344
345         if (!account_busy_for_cpu_time(rq, p, irqtime, event)) {
346                 /* account_busy_for_cpu_time() = 0, so no update to the
347                  * task's current window needs to be made. This could be
348                  * for example
349                  *
350                  *   - a wakeup event on a task within the current
351                  *     window (!new_window below, no action required),
352                  *   - switching to a new task from idle (PICK_NEXT_TASK)
353                  *     in a new window where irqtime is 0 and we aren't
354                  *     waiting on IO */
355
356                 if (!new_window)
357                         return;
358
359                 /* A new window has started. The RQ demand must be rolled
360                  * over if p is the current task. */
361                 if (p_is_curr_task) {
362                         u64 prev_sum = 0;
363
364                         /* p is either idle task or an exiting task */
365                         if (!nr_full_windows) {
366                                 prev_sum = rq->curr_runnable_sum;
367                         }
368
369                         rq->prev_runnable_sum = prev_sum;
370                         rq->curr_runnable_sum = 0;
371                 }
372
373                 return;
374         }
375
376         if (!new_window) {
377                 /* account_busy_for_cpu_time() = 1 so busy time needs
378                  * to be accounted to the current window. No rollover
379                  * since we didn't start a new window. An example of this is
380                  * when a task starts execution and then sleeps within the
381                  * same window. */
382
383                 if (!irqtime || !is_idle_task(p) || cpu_is_waiting_on_io(rq))
384                         delta = wallclock - mark_start;
385                 else
386                         delta = irqtime;
387                 delta = scale_exec_time(delta, rq);
388                 rq->curr_runnable_sum += delta;
389                 if (!is_idle_task(p) && !exiting_task(p))
390                         p->ravg.curr_window += delta;
391
392                 return;
393         }
394
395         if (!p_is_curr_task) {
396                 /* account_busy_for_cpu_time() = 1 so busy time needs
397                  * to be accounted to the current window. A new window
398                  * has also started, but p is not the current task, so the
399                  * window is not rolled over - just split up and account
400                  * as necessary into curr and prev. The window is only
401                  * rolled over when a new window is processed for the current
402                  * task.
403                  *
404                  * Irqtime can't be accounted by a task that isn't the
405                  * currently running task. */
406
407                 if (!nr_full_windows) {
408                         /* A full window hasn't elapsed, account partial
409                          * contribution to previous completed window. */
410                         delta = scale_exec_time(window_start - mark_start, rq);
411                         if (!exiting_task(p))
412                                 p->ravg.prev_window += delta;
413                 } else {
414                         /* Since at least one full window has elapsed,
415                          * the contribution to the previous window is the
416                          * full window (window_size). */
417                         delta = scale_exec_time(window_size, rq);
418                         if (!exiting_task(p))
419                                 p->ravg.prev_window = delta;
420                 }
421                 rq->prev_runnable_sum += delta;
422
423                 /* Account piece of busy time in the current window. */
424                 delta = scale_exec_time(wallclock - window_start, rq);
425                 rq->curr_runnable_sum += delta;
426                 if (!exiting_task(p))
427                         p->ravg.curr_window = delta;
428
429                 return;
430         }
431
432         if (!irqtime || !is_idle_task(p) || cpu_is_waiting_on_io(rq)) {
433                 /* account_busy_for_cpu_time() = 1 so busy time needs
434                  * to be accounted to the current window. A new window
435                  * has started and p is the current task so rollover is
436                  * needed. If any of these three above conditions are true
437                  * then this busy time can't be accounted as irqtime.
438                  *
439                  * Busy time for the idle task or exiting tasks need not
440                  * be accounted.
441                  *
442                  * An example of this would be a task that starts execution
443                  * and then sleeps once a new window has begun. */
444
445                 if (!nr_full_windows) {
446                         /* A full window hasn't elapsed, account partial
447                          * contribution to previous completed window. */
448                         delta = scale_exec_time(window_start - mark_start, rq);
449                         if (!is_idle_task(p) && !exiting_task(p))
450                                 p->ravg.prev_window += delta;
451
452                         delta += rq->curr_runnable_sum;
453                 } else {
454                         /* Since at least one full window has elapsed,
455                          * the contribution to the previous window is the
456                          * full window (window_size). */
457                         delta = scale_exec_time(window_size, rq);
458                         if (!is_idle_task(p) && !exiting_task(p))
459                                 p->ravg.prev_window = delta;
460
461                 }
462                 /*
463                  * Rollover for normal runnable sum is done here by overwriting
464                  * the values in prev_runnable_sum and curr_runnable_sum.
465                  * Rollover for new task runnable sum has completed by previous
466                  * if-else statement.
467                  */
468                 rq->prev_runnable_sum = delta;
469
470                 /* Account piece of busy time in the current window. */
471                 delta = scale_exec_time(wallclock - window_start, rq);
472                 rq->curr_runnable_sum = delta;
473                 if (!is_idle_task(p) && !exiting_task(p))
474                         p->ravg.curr_window = delta;
475
476                 return;
477         }
478
479         if (irqtime) {
480                 /* account_busy_for_cpu_time() = 1 so busy time needs
481                  * to be accounted to the current window. A new window
482                  * has started and p is the current task so rollover is
483                  * needed. The current task must be the idle task because
484                  * irqtime is not accounted for any other task.
485                  *
486                  * Irqtime will be accounted each time we process IRQ activity
487                  * after a period of idleness, so we know the IRQ busy time
488                  * started at wallclock - irqtime. */
489
490                 BUG_ON(!is_idle_task(p));
491                 mark_start = wallclock - irqtime;
492
493                 /* Roll window over. If IRQ busy time was just in the current
494                  * window then that is all that need be accounted. */
495                 rq->prev_runnable_sum = rq->curr_runnable_sum;
496                 if (mark_start > window_start) {
497                         rq->curr_runnable_sum = scale_exec_time(irqtime, rq);
498                         return;
499                 }
500
501                 /* The IRQ busy time spanned multiple windows. Process the
502                  * busy time preceding the current window start first. */
503                 delta = window_start - mark_start;
504                 if (delta > window_size)
505                         delta = window_size;
506                 delta = scale_exec_time(delta, rq);
507                 rq->prev_runnable_sum += delta;
508
509                 /* Process the remaining IRQ busy time in the current window. */
510                 delta = wallclock - window_start;
511                 rq->curr_runnable_sum = scale_exec_time(delta, rq);
512
513                 return;
514         }
515
516         BUG();
517 }
518
519 static int account_busy_for_task_demand(struct task_struct *p, int event)
520 {
521         /* No need to bother updating task demand for exiting tasks
522          * or the idle task. */
523         if (exiting_task(p) || is_idle_task(p))
524                 return 0;
525
526         /* When a task is waking up it is completing a segment of non-busy
527          * time. Likewise, if wait time is not treated as busy time, then
528          * when a task begins to run or is migrated, it is not running and
529          * is completing a segment of non-busy time. */
530         if (event == TASK_WAKE || (!walt_account_wait_time &&
531                          (event == PICK_NEXT_TASK || event == TASK_MIGRATE)))
532                 return 0;
533
534         return 1;
535 }
536
537 /*
538  * Called when new window is starting for a task, to record cpu usage over
539  * recently concluded window(s). Normally 'samples' should be 1. It can be > 1
540  * when, say, a real-time task runs without preemption for several windows at a
541  * stretch.
542  */
543 static void update_history(struct rq *rq, struct task_struct *p,
544                          u32 runtime, int samples, int event)
545 {
546         u32 *hist = &p->ravg.sum_history[0];
547         int ridx, widx;
548         u32 max = 0, avg, demand;
549         u64 sum = 0;
550
551         /* Ignore windows where task had no activity */
552         if (!runtime || is_idle_task(p) || exiting_task(p) || !samples)
553                         goto done;
554
555         /* Push new 'runtime' value onto stack */
556         widx = walt_ravg_hist_size - 1;
557         ridx = widx - samples;
558         for (; ridx >= 0; --widx, --ridx) {
559                 hist[widx] = hist[ridx];
560                 sum += hist[widx];
561                 if (hist[widx] > max)
562                         max = hist[widx];
563         }
564
565         for (widx = 0; widx < samples && widx < walt_ravg_hist_size; widx++) {
566                 hist[widx] = runtime;
567                 sum += hist[widx];
568                 if (hist[widx] > max)
569                         max = hist[widx];
570         }
571
572         p->ravg.sum = 0;
573
574         if (walt_window_stats_policy == WINDOW_STATS_RECENT) {
575                 demand = runtime;
576         } else if (walt_window_stats_policy == WINDOW_STATS_MAX) {
577                 demand = max;
578         } else {
579                 avg = div64_u64(sum, walt_ravg_hist_size);
580                 if (walt_window_stats_policy == WINDOW_STATS_AVG)
581                         demand = avg;
582                 else
583                         demand = max(avg, runtime);
584         }
585
586         /*
587          * A throttled deadline sched class task gets dequeued without
588          * changing p->on_rq. Since the dequeue decrements hmp stats
589          * avoid decrementing it here again.
590          */
591         if (task_on_rq_queued(p) && (!task_has_dl_policy(p) ||
592                                                 !p->dl.dl_throttled))
593                 fixup_cumulative_runnable_avg(rq, p, demand);
594
595         p->ravg.demand = demand;
596
597 done:
598         trace_walt_update_history(rq, p, runtime, samples, event);
599         return;
600 }
601
602 static void add_to_task_demand(struct rq *rq, struct task_struct *p,
603                                 u64 delta)
604 {
605         delta = scale_exec_time(delta, rq);
606         p->ravg.sum += delta;
607         if (unlikely(p->ravg.sum > walt_ravg_window))
608                 p->ravg.sum = walt_ravg_window;
609 }
610
611 /*
612  * Account cpu demand of task and/or update task's cpu demand history
613  *
614  * ms = p->ravg.mark_start;
615  * wc = wallclock
616  * ws = rq->window_start
617  *
618  * Three possibilities:
619  *
620  *      a) Task event is contained within one window.
621  *              window_start < mark_start < wallclock
622  *
623  *              ws   ms  wc
624  *              |    |   |
625  *              V    V   V
626  *              |---------------|
627  *
628  *      In this case, p->ravg.sum is updated *iff* event is appropriate
629  *      (ex: event == PUT_PREV_TASK)
630  *
631  *      b) Task event spans two windows.
632  *              mark_start < window_start < wallclock
633  *
634  *              ms   ws   wc
635  *              |    |    |
636  *              V    V    V
637  *              -----|-------------------
638  *
639  *      In this case, p->ravg.sum is updated with (ws - ms) *iff* event
640  *      is appropriate, then a new window sample is recorded followed
641  *      by p->ravg.sum being set to (wc - ws) *iff* event is appropriate.
642  *
643  *      c) Task event spans more than two windows.
644  *
645  *              ms ws_tmp                          ws  wc
646  *              |  |                               |   |
647  *              V  V                               V   V
648  *              ---|-------|-------|-------|-------|------
649  *                 |                               |
650  *                 |<------ nr_full_windows ------>|
651  *
652  *      In this case, p->ravg.sum is updated with (ws_tmp - ms) first *iff*
653  *      event is appropriate, window sample of p->ravg.sum is recorded,
654  *      'nr_full_window' samples of window_size is also recorded *iff*
655  *      event is appropriate and finally p->ravg.sum is set to (wc - ws)
656  *      *iff* event is appropriate.
657  *
658  * IMPORTANT : Leave p->ravg.mark_start unchanged, as update_cpu_busy_time()
659  * depends on it!
660  */
661 static void update_task_demand(struct task_struct *p, struct rq *rq,
662              int event, u64 wallclock)
663 {
664         u64 mark_start = p->ravg.mark_start;
665         u64 delta, window_start = rq->window_start;
666         int new_window, nr_full_windows;
667         u32 window_size = walt_ravg_window;
668
669         new_window = mark_start < window_start;
670         if (!account_busy_for_task_demand(p, event)) {
671                 if (new_window)
672                         /* If the time accounted isn't being accounted as
673                          * busy time, and a new window started, only the
674                          * previous window need be closed out with the
675                          * pre-existing demand. Multiple windows may have
676                          * elapsed, but since empty windows are dropped,
677                          * it is not necessary to account those. */
678                         update_history(rq, p, p->ravg.sum, 1, event);
679                 return;
680         }
681
682         if (!new_window) {
683                 /* The simple case - busy time contained within the existing
684                  * window. */
685                 add_to_task_demand(rq, p, wallclock - mark_start);
686                 return;
687         }
688
689         /* Busy time spans at least two windows. Temporarily rewind
690          * window_start to first window boundary after mark_start. */
691         delta = window_start - mark_start;
692         nr_full_windows = div64_u64(delta, window_size);
693         window_start -= (u64)nr_full_windows * (u64)window_size;
694
695         /* Process (window_start - mark_start) first */
696         add_to_task_demand(rq, p, window_start - mark_start);
697
698         /* Push new sample(s) into task's demand history */
699         update_history(rq, p, p->ravg.sum, 1, event);
700         if (nr_full_windows)
701                 update_history(rq, p, scale_exec_time(window_size, rq),
702                                nr_full_windows, event);
703
704         /* Roll window_start back to current to process any remainder
705          * in current window. */
706         window_start += (u64)nr_full_windows * (u64)window_size;
707
708         /* Process (wallclock - window_start) next */
709         mark_start = window_start;
710         add_to_task_demand(rq, p, wallclock - mark_start);
711 }
712
713 /* Reflect task activity on its demand and cpu's busy time statistics */
714 void walt_update_task_ravg(struct task_struct *p, struct rq *rq,
715              int event, u64 wallclock, u64 irqtime)
716 {
717         if (walt_disabled || !rq->window_start)
718                 return;
719
720         lockdep_assert_held(&rq->lock);
721
722         update_window_start(rq, wallclock);
723
724         if (!p->ravg.mark_start)
725                 goto done;
726
727         update_task_demand(p, rq, event, wallclock);
728         update_cpu_busy_time(p, rq, event, wallclock, irqtime);
729
730 done:
731         trace_walt_update_task_ravg(p, rq, event, wallclock, irqtime);
732
733         p->ravg.mark_start = wallclock;
734 }
735
736 unsigned long __weak arch_get_cpu_efficiency(int cpu)
737 {
738         return SCHED_LOAD_SCALE;
739 }
740
741 void walt_init_cpu_efficiency(void)
742 {
743         int i, efficiency;
744         unsigned int max = 0, min = UINT_MAX;
745
746         for_each_possible_cpu(i) {
747                 efficiency = arch_get_cpu_efficiency(i);
748                 cpu_rq(i)->efficiency = efficiency;
749
750                 if (efficiency > max)
751                         max = efficiency;
752                 if (efficiency < min)
753                         min = efficiency;
754         }
755
756         if (max)
757                 max_possible_efficiency = max;
758
759         if (min)
760                 min_possible_efficiency = min;
761 }
762
763 static void reset_task_stats(struct task_struct *p)
764 {
765         u32 sum = 0;
766
767         if (exiting_task(p))
768                 sum = EXITING_TASK_MARKER;
769
770         memset(&p->ravg, 0, sizeof(struct ravg));
771         /* Retain EXITING_TASK marker */
772         p->ravg.sum_history[0] = sum;
773 }
774
775 void walt_mark_task_starting(struct task_struct *p)
776 {
777         u64 wallclock;
778         struct rq *rq = task_rq(p);
779
780         if (!rq->window_start) {
781                 reset_task_stats(p);
782                 return;
783         }
784
785         wallclock = walt_ktime_clock();
786         p->ravg.mark_start = wallclock;
787 }
788
789 void walt_set_window_start(struct rq *rq)
790 {
791         int cpu = cpu_of(rq);
792         struct rq *sync_rq = cpu_rq(sync_cpu);
793
794         if (rq->window_start)
795                 return;
796
797         if (cpu == sync_cpu) {
798                 rq->window_start = walt_ktime_clock();
799         } else {
800                 raw_spin_unlock(&rq->lock);
801                 double_rq_lock(rq, sync_rq);
802                 rq->window_start = cpu_rq(sync_cpu)->window_start;
803                 rq->curr_runnable_sum = rq->prev_runnable_sum = 0;
804                 raw_spin_unlock(&sync_rq->lock);
805         }
806
807         rq->curr->ravg.mark_start = rq->window_start;
808 }
809
810 void walt_migrate_sync_cpu(int cpu)
811 {
812         if (cpu == sync_cpu)
813                 sync_cpu = smp_processor_id();
814 }
815
816 void walt_fixup_busy_time(struct task_struct *p, int new_cpu)
817 {
818         struct rq *src_rq = task_rq(p);
819         struct rq *dest_rq = cpu_rq(new_cpu);
820         u64 wallclock;
821
822         if (!p->on_rq && p->state != TASK_WAKING)
823                 return;
824
825         if (exiting_task(p)) {
826                 return;
827         }
828
829         if (p->state == TASK_WAKING)
830                 double_rq_lock(src_rq, dest_rq);
831
832         wallclock = walt_ktime_clock();
833
834         walt_update_task_ravg(task_rq(p)->curr, task_rq(p),
835                         TASK_UPDATE, wallclock, 0);
836         walt_update_task_ravg(dest_rq->curr, dest_rq,
837                         TASK_UPDATE, wallclock, 0);
838
839         walt_update_task_ravg(p, task_rq(p), TASK_MIGRATE, wallclock, 0);
840
841         if (p->ravg.curr_window) {
842                 src_rq->curr_runnable_sum -= p->ravg.curr_window;
843                 dest_rq->curr_runnable_sum += p->ravg.curr_window;
844         }
845
846         if (p->ravg.prev_window) {
847                 src_rq->prev_runnable_sum -= p->ravg.prev_window;
848                 dest_rq->prev_runnable_sum += p->ravg.prev_window;
849         }
850
851         if ((s64)src_rq->prev_runnable_sum < 0) {
852                 src_rq->prev_runnable_sum = 0;
853                 WARN_ON(1);
854         }
855         if ((s64)src_rq->curr_runnable_sum < 0) {
856                 src_rq->curr_runnable_sum = 0;
857                 WARN_ON(1);
858         }
859
860         trace_walt_migration_update_sum(src_rq, p);
861         trace_walt_migration_update_sum(dest_rq, p);
862
863         if (p->state == TASK_WAKING)
864                 double_rq_unlock(src_rq, dest_rq);
865 }
866
867 /* Keep track of max/min capacity possible across CPUs "currently" */
868 static void __update_min_max_capacity(void)
869 {
870         int i;
871         int max = 0, min = INT_MAX;
872
873         for_each_online_cpu(i) {
874                 if (cpu_rq(i)->capacity > max)
875                         max = cpu_rq(i)->capacity;
876                 if (cpu_rq(i)->capacity < min)
877                         min = cpu_rq(i)->capacity;
878         }
879
880         max_capacity = max;
881         min_capacity = min;
882 }
883
884 static void update_min_max_capacity(void)
885 {
886         unsigned long flags;
887         int i;
888
889         local_irq_save(flags);
890         for_each_possible_cpu(i)
891                 raw_spin_lock(&cpu_rq(i)->lock);
892
893         __update_min_max_capacity();
894
895         for_each_possible_cpu(i)
896                 raw_spin_unlock(&cpu_rq(i)->lock);
897         local_irq_restore(flags);
898 }
899
900 /*
901  * Return 'capacity' of a cpu in reference to "least" efficient cpu, such that
902  * least efficient cpu gets capacity of 1024
903  */
904 static unsigned long capacity_scale_cpu_efficiency(int cpu)
905 {
906         return (1024 * cpu_rq(cpu)->efficiency) / min_possible_efficiency;
907 }
908
909 /*
910  * Return 'capacity' of a cpu in reference to cpu with lowest max_freq
911  * (min_max_freq), such that one with lowest max_freq gets capacity of 1024.
912  */
913 static unsigned long capacity_scale_cpu_freq(int cpu)
914 {
915         return (1024 * cpu_rq(cpu)->max_freq) / min_max_freq;
916 }
917
918 /*
919  * Return load_scale_factor of a cpu in reference to "most" efficient cpu, so
920  * that "most" efficient cpu gets a load_scale_factor of 1
921  */
922 static unsigned long load_scale_cpu_efficiency(int cpu)
923 {
924         return DIV_ROUND_UP(1024 * max_possible_efficiency,
925                             cpu_rq(cpu)->efficiency);
926 }
927
928 /*
929  * Return load_scale_factor of a cpu in reference to cpu with best max_freq
930  * (max_possible_freq), so that one with best max_freq gets a load_scale_factor
931  * of 1.
932  */
933 static unsigned long load_scale_cpu_freq(int cpu)
934 {
935         return DIV_ROUND_UP(1024 * max_possible_freq, cpu_rq(cpu)->max_freq);
936 }
937
938 static int compute_capacity(int cpu)
939 {
940         int capacity = 1024;
941
942         capacity *= capacity_scale_cpu_efficiency(cpu);
943         capacity >>= 10;
944
945         capacity *= capacity_scale_cpu_freq(cpu);
946         capacity >>= 10;
947
948         return capacity;
949 }
950
951 static int compute_load_scale_factor(int cpu)
952 {
953         int load_scale = 1024;
954
955         /*
956          * load_scale_factor accounts for the fact that task load
957          * is in reference to "best" performing cpu. Task's load will need to be
958          * scaled (up) by a factor to determine suitability to be placed on a
959          * (little) cpu.
960          */
961         load_scale *= load_scale_cpu_efficiency(cpu);
962         load_scale >>= 10;
963
964         load_scale *= load_scale_cpu_freq(cpu);
965         load_scale >>= 10;
966
967         return load_scale;
968 }
969
970 static int cpufreq_notifier_policy(struct notifier_block *nb,
971                 unsigned long val, void *data)
972 {
973         struct cpufreq_policy *policy = (struct cpufreq_policy *)data;
974         int i, update_max = 0;
975         u64 highest_mpc = 0, highest_mplsf = 0;
976         const struct cpumask *cpus = policy->related_cpus;
977         unsigned int orig_min_max_freq = min_max_freq;
978         unsigned int orig_max_possible_freq = max_possible_freq;
979         /* Initialized to policy->max in case policy->related_cpus is empty! */
980         unsigned int orig_max_freq = policy->max;
981
982         if (val != CPUFREQ_NOTIFY && val != CPUFREQ_REMOVE_POLICY &&
983                                                 val != CPUFREQ_CREATE_POLICY)
984                 return 0;
985
986         if (val == CPUFREQ_REMOVE_POLICY || val == CPUFREQ_CREATE_POLICY) {
987                 update_min_max_capacity();
988                 return 0;
989         }
990
991         for_each_cpu(i, policy->related_cpus) {
992                 cpumask_copy(&cpu_rq(i)->freq_domain_cpumask,
993                              policy->related_cpus);
994                 orig_max_freq = cpu_rq(i)->max_freq;
995                 cpu_rq(i)->min_freq = policy->min;
996                 cpu_rq(i)->max_freq = policy->max;
997                 cpu_rq(i)->cur_freq = policy->cur;
998                 cpu_rq(i)->max_possible_freq = policy->cpuinfo.max_freq;
999         }
1000
1001         max_possible_freq = max(max_possible_freq, policy->cpuinfo.max_freq);
1002         if (min_max_freq == 1)
1003                 min_max_freq = UINT_MAX;
1004         min_max_freq = min(min_max_freq, policy->cpuinfo.max_freq);
1005         BUG_ON(!min_max_freq);
1006         BUG_ON(!policy->max);
1007
1008         /* Changes to policy other than max_freq don't require any updates */
1009         if (orig_max_freq == policy->max)
1010                 return 0;
1011
1012         /*
1013          * A changed min_max_freq or max_possible_freq (possible during bootup)
1014          * needs to trigger re-computation of load_scale_factor and capacity for
1015          * all possible cpus (even those offline). It also needs to trigger
1016          * re-computation of nr_big_task count on all online cpus.
1017          *
1018          * A changed rq->max_freq otoh needs to trigger re-computation of
1019          * load_scale_factor and capacity for just the cluster of cpus involved.
1020          * Since small task definition depends on max_load_scale_factor, a
1021          * changed load_scale_factor of one cluster could influence
1022          * classification of tasks in another cluster. Hence a changed
1023          * rq->max_freq will need to trigger re-computation of nr_big_task
1024          * count on all online cpus.
1025          *
1026          * While it should be sufficient for nr_big_tasks to be
1027          * re-computed for only online cpus, we have inadequate context
1028          * information here (in policy notifier) with regard to hotplug-safety
1029          * context in which notification is issued. As a result, we can't use
1030          * get_online_cpus() here, as it can lead to deadlock. Until cpufreq is
1031          * fixed up to issue notification always in hotplug-safe context,
1032          * re-compute nr_big_task for all possible cpus.
1033          */
1034
1035         if (orig_min_max_freq != min_max_freq ||
1036                 orig_max_possible_freq != max_possible_freq) {
1037                         cpus = cpu_possible_mask;
1038                         update_max = 1;
1039         }
1040
1041         /*
1042          * Changed load_scale_factor can trigger reclassification of tasks as
1043          * big or small. Make this change "atomic" so that tasks are accounted
1044          * properly due to changed load_scale_factor
1045          */
1046         for_each_cpu(i, cpus) {
1047                 struct rq *rq = cpu_rq(i);
1048
1049                 rq->capacity = compute_capacity(i);
1050                 rq->load_scale_factor = compute_load_scale_factor(i);
1051
1052                 if (update_max) {
1053                         u64 mpc, mplsf;
1054
1055                         mpc = div_u64(((u64) rq->capacity) *
1056                                 rq->max_possible_freq, rq->max_freq);
1057                         rq->max_possible_capacity = (int) mpc;
1058
1059                         mplsf = div_u64(((u64) rq->load_scale_factor) *
1060                                 rq->max_possible_freq, rq->max_freq);
1061
1062                         if (mpc > highest_mpc) {
1063                                 highest_mpc = mpc;
1064                                 cpumask_clear(&mpc_mask);
1065                                 cpumask_set_cpu(i, &mpc_mask);
1066                         } else if (mpc == highest_mpc) {
1067                                 cpumask_set_cpu(i, &mpc_mask);
1068                         }
1069
1070                         if (mplsf > highest_mplsf)
1071                                 highest_mplsf = mplsf;
1072                 }
1073         }
1074
1075         if (update_max) {
1076                 max_possible_capacity = highest_mpc;
1077                 max_load_scale_factor = highest_mplsf;
1078         }
1079
1080         __update_min_max_capacity();
1081
1082         return 0;
1083 }
1084
1085 static int cpufreq_notifier_trans(struct notifier_block *nb,
1086                 unsigned long val, void *data)
1087 {
1088         struct cpufreq_freqs *freq = (struct cpufreq_freqs *)data;
1089         unsigned int cpu = freq->cpu, new_freq = freq->new;
1090         unsigned long flags;
1091         int i;
1092
1093         if (val != CPUFREQ_POSTCHANGE)
1094                 return 0;
1095
1096         BUG_ON(!new_freq);
1097
1098         if (cpu_rq(cpu)->cur_freq == new_freq)
1099                 return 0;
1100
1101         for_each_cpu(i, &cpu_rq(cpu)->freq_domain_cpumask) {
1102                 struct rq *rq = cpu_rq(i);
1103
1104                 raw_spin_lock_irqsave(&rq->lock, flags);
1105                 walt_update_task_ravg(rq->curr, rq, TASK_UPDATE,
1106                                       walt_ktime_clock(), 0);
1107                 rq->cur_freq = new_freq;
1108                 raw_spin_unlock_irqrestore(&rq->lock, flags);
1109         }
1110
1111         return 0;
1112 }
1113
1114 static struct notifier_block notifier_policy_block = {
1115         .notifier_call = cpufreq_notifier_policy
1116 };
1117
1118 static struct notifier_block notifier_trans_block = {
1119         .notifier_call = cpufreq_notifier_trans
1120 };
1121
1122 static int register_sched_callback(void)
1123 {
1124         int ret;
1125
1126         ret = cpufreq_register_notifier(&notifier_policy_block,
1127                                                 CPUFREQ_POLICY_NOTIFIER);
1128
1129         if (!ret)
1130                 ret = cpufreq_register_notifier(&notifier_trans_block,
1131                                                 CPUFREQ_TRANSITION_NOTIFIER);
1132
1133         return 0;
1134 }
1135
1136 /*
1137  * cpufreq callbacks can be registered at core_initcall or later time.
1138  * Any registration done prior to that is "forgotten" by cpufreq. See
1139  * initialization of variable init_cpufreq_transition_notifier_list_called
1140  * for further information.
1141  */
1142 core_initcall(register_sched_callback);
1143
1144 void walt_init_new_task_load(struct task_struct *p)
1145 {
1146         int i;
1147         u32 init_load_windows =
1148                         div64_u64((u64)sysctl_sched_walt_init_task_load_pct *
1149                           (u64)walt_ravg_window, 100);
1150         u32 init_load_pct = current->init_load_pct;
1151
1152         p->init_load_pct = 0;
1153         memset(&p->ravg, 0, sizeof(struct ravg));
1154
1155         if (init_load_pct) {
1156                 init_load_windows = div64_u64((u64)init_load_pct *
1157                           (u64)walt_ravg_window, 100);
1158         }
1159
1160         p->ravg.demand = init_load_windows;
1161         for (i = 0; i < RAVG_HIST_SIZE_MAX; ++i)
1162                 p->ravg.sum_history[i] = init_load_windows;
1163 }