aboutsummaryrefslogtreecommitdiffstats
path: root/kernel
diff options
context:
space:
mode:
authorJonathan Herman <hermanjl@cs.unc.edu>2013-01-22 10:38:37 -0500
committerJonathan Herman <hermanjl@cs.unc.edu>2013-01-22 10:38:37 -0500
commitfcc9d2e5a6c89d22b8b773a64fb4ad21ac318446 (patch)
treea57612d1888735a2ec7972891b68c1ac5ec8faea /kernel
parent8dea78da5cee153b8af9c07a2745f6c55057fe12 (diff)
Added missing tegra files.HEADmaster
Diffstat (limited to 'kernel')
-rw-r--r--kernel/pm_qos_params.c526
-rw-r--r--kernel/power/consoleearlysuspend.c78
-rw-r--r--kernel/power/earlysuspend.c187
-rw-r--r--kernel/power/fbearlysuspend.c153
-rw-r--r--kernel/power/suspend_time.c111
-rw-r--r--kernel/power/userwakelock.c219
-rw-r--r--kernel/sched.c9443
-rw-r--r--kernel/sched_autogroup.c275
-rw-r--r--kernel/sched_autogroup.h42
-rw-r--r--kernel/sched_clock.c350
-rw-r--r--kernel/sched_cpupri.c204
-rw-r--r--kernel/sched_cpupri.h37
-rw-r--r--kernel/sched_debug.c508
-rw-r--r--kernel/sched_fair.c4346
-rw-r--r--kernel/sched_features.h74
-rw-r--r--kernel/sched_idletask.c97
-rw-r--r--kernel/sched_rt.c1866
-rw-r--r--kernel/sched_stats.h336
-rw-r--r--kernel/sched_stoptask.c104
-rw-r--r--kernel/sysctl_check.c160
-rw-r--r--kernel/time/timecompare.c193
-rw-r--r--kernel/trace/trace_workqueue.c300
-rw-r--r--kernel/trace/tracedump.c682
-rw-r--r--kernel/trace/tracelevel.c142
24 files changed, 20433 insertions, 0 deletions
diff --git a/kernel/pm_qos_params.c b/kernel/pm_qos_params.c
new file mode 100644
index 00000000000..82da7ac3b1f
--- /dev/null
+++ b/kernel/pm_qos_params.c
@@ -0,0 +1,526 @@
1/*
2 * This module exposes the interface to kernel space for specifying
3 * QoS dependencies. It provides infrastructure for registration of:
4 *
5 * Dependents on a QoS value : register requests
6 * Watchers of QoS value : get notified when target QoS value changes
7 *
8 * This QoS design is best effort based. Dependents register their QoS needs.
9 * Watchers register to keep track of the current QoS needs of the system.
10 *
11 * There are 3 basic classes of QoS parameter: latency, timeout, throughput
12 * each have defined units:
13 * latency: usec
14 * timeout: usec <-- currently not used.
15 * throughput: kbs (kilo byte / sec)
16 *
17 * There are lists of pm_qos_objects each one wrapping requests, notifiers
18 *
19 * User mode requests on a QOS parameter register themselves to the
20 * subsystem by opening the device node /dev/... and writing there request to
21 * the node. As long as the process holds a file handle open to the node the
22 * client continues to be accounted for. Upon file release the usermode
23 * request is removed and a new qos target is computed. This way when the
24 * request that the application has is cleaned up when closes the file
25 * pointer or exits the pm_qos_object will get an opportunity to clean up.
26 *
27 * Mark Gross <mgross@linux.intel.com>
28 */
29
30/*#define DEBUG*/
31
32#include <linux/pm_qos_params.h>
33#include <linux/sched.h>
34#include <linux/spinlock.h>
35#include <linux/slab.h>
36#include <linux/time.h>
37#include <linux/fs.h>
38#include <linux/device.h>
39#include <linux/miscdevice.h>
40#include <linux/string.h>
41#include <linux/platform_device.h>
42#include <linux/init.h>
43#include <linux/kernel.h>
44
45#include <linux/uaccess.h>
46
47/*
48 * locking rule: all changes to requests or notifiers lists
49 * or pm_qos_object list and pm_qos_objects need to happen with pm_qos_lock
50 * held, taken with _irqsave. One lock to rule them all
51 */
52enum pm_qos_type {
53 PM_QOS_MAX, /* return the largest value */
54 PM_QOS_MIN /* return the smallest value */
55};
56
57/*
58 * Note: The lockless read path depends on the CPU accessing
59 * target_value atomically. Atomic access is only guaranteed on all CPU
60 * types linux supports for 32 bit quantites
61 */
62struct pm_qos_object {
63 struct plist_head requests;
64 struct blocking_notifier_head *notifiers;
65 struct miscdevice pm_qos_power_miscdev;
66 char *name;
67 s32 target_value; /* Do not change to 64 bit */
68 s32 default_value;
69 enum pm_qos_type type;
70};
71
72static DEFINE_SPINLOCK(pm_qos_lock);
73
74static struct pm_qos_object null_pm_qos;
75static BLOCKING_NOTIFIER_HEAD(cpu_dma_lat_notifier);
76static struct pm_qos_object cpu_dma_pm_qos = {
77 .requests = PLIST_HEAD_INIT(cpu_dma_pm_qos.requests),
78 .notifiers = &cpu_dma_lat_notifier,
79 .name = "cpu_dma_latency",
80 .target_value = PM_QOS_CPU_DMA_LAT_DEFAULT_VALUE,
81 .default_value = PM_QOS_CPU_DMA_LAT_DEFAULT_VALUE,
82 .type = PM_QOS_MIN,
83};
84
85static BLOCKING_NOTIFIER_HEAD(network_lat_notifier);
86static struct pm_qos_object network_lat_pm_qos = {
87 .requests = PLIST_HEAD_INIT(network_lat_pm_qos.requests),
88 .notifiers = &network_lat_notifier,
89 .name = "network_latency",
90 .target_value = PM_QOS_NETWORK_LAT_DEFAULT_VALUE,
91 .default_value = PM_QOS_NETWORK_LAT_DEFAULT_VALUE,
92 .type = PM_QOS_MIN
93};
94
95
96static BLOCKING_NOTIFIER_HEAD(network_throughput_notifier);
97static struct pm_qos_object network_throughput_pm_qos = {
98 .requests = PLIST_HEAD_INIT(network_throughput_pm_qos.requests),
99 .notifiers = &network_throughput_notifier,
100 .name = "network_throughput",
101 .target_value = PM_QOS_NETWORK_THROUGHPUT_DEFAULT_VALUE,
102 .default_value = PM_QOS_NETWORK_THROUGHPUT_DEFAULT_VALUE,
103 .type = PM_QOS_MAX,
104};
105
106
107static BLOCKING_NOTIFIER_HEAD(min_online_cpus_notifier);
108static struct pm_qos_object min_online_cpus_pm_qos = {
109 .requests = PLIST_HEAD_INIT(min_online_cpus_pm_qos.requests),
110 .notifiers = &min_online_cpus_notifier,
111 .name = "min_online_cpus",
112 .target_value = PM_QOS_MIN_ONLINE_CPUS_DEFAULT_VALUE,
113 .default_value = PM_QOS_MIN_ONLINE_CPUS_DEFAULT_VALUE,
114 .type = PM_QOS_MAX,
115};
116
117
118static BLOCKING_NOTIFIER_HEAD(max_online_cpus_notifier);
119static struct pm_qos_object max_online_cpus_pm_qos = {
120 .requests = PLIST_HEAD_INIT(max_online_cpus_pm_qos.requests),
121 .notifiers = &max_online_cpus_notifier,
122 .name = "max_online_cpus",
123 .target_value = PM_QOS_MAX_ONLINE_CPUS_DEFAULT_VALUE,
124 .default_value = PM_QOS_MAX_ONLINE_CPUS_DEFAULT_VALUE,
125 .type = PM_QOS_MIN,
126};
127
128
129static BLOCKING_NOTIFIER_HEAD(cpu_freq_min_notifier);
130static struct pm_qos_object cpu_freq_min_pm_qos = {
131 .requests = PLIST_HEAD_INIT(cpu_freq_min_pm_qos.requests),
132 .notifiers = &cpu_freq_min_notifier,
133 .name = "cpu_freq_min",
134 .target_value = PM_QOS_CPU_FREQ_MIN_DEFAULT_VALUE,
135 .default_value = PM_QOS_CPU_FREQ_MIN_DEFAULT_VALUE,
136 .type = PM_QOS_MAX,
137};
138
139
140static BLOCKING_NOTIFIER_HEAD(cpu_freq_max_notifier);
141static struct pm_qos_object cpu_freq_max_pm_qos = {
142 .requests = PLIST_HEAD_INIT(cpu_freq_max_pm_qos.requests),
143 .notifiers = &cpu_freq_max_notifier,
144 .name = "cpu_freq_max",
145 .target_value = PM_QOS_CPU_FREQ_MAX_DEFAULT_VALUE,
146 .default_value = PM_QOS_CPU_FREQ_MAX_DEFAULT_VALUE,
147 .type = PM_QOS_MIN,
148};
149
150
151static struct pm_qos_object *pm_qos_array[] = {
152 &null_pm_qos,
153 &cpu_dma_pm_qos,
154 &network_lat_pm_qos,
155 &network_throughput_pm_qos,
156 &min_online_cpus_pm_qos,
157 &max_online_cpus_pm_qos,
158 &cpu_freq_min_pm_qos,
159 &cpu_freq_max_pm_qos
160};
161
162static ssize_t pm_qos_power_write(struct file *filp, const char __user *buf,
163 size_t count, loff_t *f_pos);
164static ssize_t pm_qos_power_read(struct file *filp, char __user *buf,
165 size_t count, loff_t *f_pos);
166static int pm_qos_power_open(struct inode *inode, struct file *filp);
167static int pm_qos_power_release(struct inode *inode, struct file *filp);
168
169static const struct file_operations pm_qos_power_fops = {
170 .write = pm_qos_power_write,
171 .read = pm_qos_power_read,
172 .open = pm_qos_power_open,
173 .release = pm_qos_power_release,
174 .llseek = noop_llseek,
175};
176
177/* unlocked internal variant */
178static inline int pm_qos_get_value(struct pm_qos_object *o)
179{
180 if (plist_head_empty(&o->requests))
181 return o->default_value;
182
183 switch (o->type) {
184 case PM_QOS_MIN:
185 return plist_first(&o->requests)->prio;
186
187 case PM_QOS_MAX:
188 return plist_last(&o->requests)->prio;
189
190 default:
191 /* runtime check for not using enum */
192 BUG();
193 }
194}
195
196static inline s32 pm_qos_read_value(struct pm_qos_object *o)
197{
198 return o->target_value;
199}
200
201static inline void pm_qos_set_value(struct pm_qos_object *o, s32 value)
202{
203 o->target_value = value;
204}
205
206static void update_target(struct pm_qos_object *o, struct plist_node *node,
207 int del, int value)
208{
209 unsigned long flags;
210 int prev_value, curr_value;
211
212 spin_lock_irqsave(&pm_qos_lock, flags);
213 prev_value = pm_qos_get_value(o);
214 /* PM_QOS_DEFAULT_VALUE is a signal that the value is unchanged */
215 if (value != PM_QOS_DEFAULT_VALUE) {
216 /*
217 * to change the list, we atomically remove, reinit
218 * with new value and add, then see if the extremal
219 * changed
220 */
221 plist_del(node, &o->requests);
222 plist_node_init(node, value);
223 plist_add(node, &o->requests);
224 } else if (del) {
225 plist_del(node, &o->requests);
226 } else {
227 plist_add(node, &o->requests);
228 }
229 curr_value = pm_qos_get_value(o);
230 pm_qos_set_value(o, curr_value);
231 spin_unlock_irqrestore(&pm_qos_lock, flags);
232
233 if (prev_value != curr_value)
234 blocking_notifier_call_chain(o->notifiers,
235 (unsigned long)curr_value,
236 NULL);
237}
238
239static int register_pm_qos_misc(struct pm_qos_object *qos)
240{
241 qos->pm_qos_power_miscdev.minor = MISC_DYNAMIC_MINOR;
242 qos->pm_qos_power_miscdev.name = qos->name;
243 qos->pm_qos_power_miscdev.fops = &pm_qos_power_fops;
244
245 return misc_register(&qos->pm_qos_power_miscdev);
246}
247
248static int find_pm_qos_object_by_minor(int minor)
249{
250 int pm_qos_class;
251
252 for (pm_qos_class = 0;
253 pm_qos_class < PM_QOS_NUM_CLASSES; pm_qos_class++) {
254 if (minor ==
255 pm_qos_array[pm_qos_class]->pm_qos_power_miscdev.minor)
256 return pm_qos_class;
257 }
258 return -1;
259}
260
261/**
262 * pm_qos_request - returns current system wide qos expectation
263 * @pm_qos_class: identification of which qos value is requested
264 *
265 * This function returns the current target value.
266 */
267int pm_qos_request(int pm_qos_class)
268{
269 return pm_qos_read_value(pm_qos_array[pm_qos_class]);
270}
271EXPORT_SYMBOL_GPL(pm_qos_request);
272
273int pm_qos_request_active(struct pm_qos_request_list *req)
274{
275 return req->pm_qos_class != 0;
276}
277EXPORT_SYMBOL_GPL(pm_qos_request_active);
278
279/**
280 * pm_qos_add_request - inserts new qos request into the list
281 * @dep: pointer to a preallocated handle
282 * @pm_qos_class: identifies which list of qos request to use
283 * @value: defines the qos request
284 *
285 * This function inserts a new entry in the pm_qos_class list of requested qos
286 * performance characteristics. It recomputes the aggregate QoS expectations
287 * for the pm_qos_class of parameters and initializes the pm_qos_request_list
288 * handle. Caller needs to save this handle for later use in updates and
289 * removal.
290 */
291
292void pm_qos_add_request(struct pm_qos_request_list *dep,
293 int pm_qos_class, s32 value)
294{
295 struct pm_qos_object *o = pm_qos_array[pm_qos_class];
296 int new_value;
297
298 if (pm_qos_request_active(dep)) {
299 WARN(1, KERN_ERR "pm_qos_add_request() called for already added request\n");
300 return;
301 }
302 if (value == PM_QOS_DEFAULT_VALUE)
303 new_value = o->default_value;
304 else
305 new_value = value;
306 plist_node_init(&dep->list, new_value);
307 dep->pm_qos_class = pm_qos_class;
308 update_target(o, &dep->list, 0, PM_QOS_DEFAULT_VALUE);
309}
310EXPORT_SYMBOL_GPL(pm_qos_add_request);
311
312/**
313 * pm_qos_update_request - modifies an existing qos request
314 * @pm_qos_req : handle to list element holding a pm_qos request to use
315 * @value: defines the qos request
316 *
317 * Updates an existing qos request for the pm_qos_class of parameters along
318 * with updating the target pm_qos_class value.
319 *
320 * Attempts are made to make this code callable on hot code paths.
321 */
322void pm_qos_update_request(struct pm_qos_request_list *pm_qos_req,
323 s32 new_value)
324{
325 s32 temp;
326 struct pm_qos_object *o;
327
328 if (!pm_qos_req) /*guard against callers passing in null */
329 return;
330
331 if (!pm_qos_request_active(pm_qos_req)) {
332 WARN(1, KERN_ERR "pm_qos_update_request() called for unknown object\n");
333 return;
334 }
335
336 o = pm_qos_array[pm_qos_req->pm_qos_class];
337
338 if (new_value == PM_QOS_DEFAULT_VALUE)
339 temp = o->default_value;
340 else
341 temp = new_value;
342
343 if (temp != pm_qos_req->list.prio)
344 update_target(o, &pm_qos_req->list, 0, temp);
345}
346EXPORT_SYMBOL_GPL(pm_qos_update_request);
347
348/**
349 * pm_qos_remove_request - modifies an existing qos request
350 * @pm_qos_req: handle to request list element
351 *
352 * Will remove pm qos request from the list of requests and
353 * recompute the current target value for the pm_qos_class. Call this
354 * on slow code paths.
355 */
356void pm_qos_remove_request(struct pm_qos_request_list *pm_qos_req)
357{
358 struct pm_qos_object *o;
359
360 if (pm_qos_req == NULL)
361 return;
362 /* silent return to keep pcm code cleaner */
363
364 if (!pm_qos_request_active(pm_qos_req)) {
365 WARN(1, KERN_ERR "pm_qos_remove_request() called for unknown object\n");
366 return;
367 }
368
369 o = pm_qos_array[pm_qos_req->pm_qos_class];
370 update_target(o, &pm_qos_req->list, 1, PM_QOS_DEFAULT_VALUE);
371 memset(pm_qos_req, 0, sizeof(*pm_qos_req));
372}
373EXPORT_SYMBOL_GPL(pm_qos_remove_request);
374
375/**
376 * pm_qos_add_notifier - sets notification entry for changes to target value
377 * @pm_qos_class: identifies which qos target changes should be notified.
378 * @notifier: notifier block managed by caller.
379 *
380 * will register the notifier into a notification chain that gets called
381 * upon changes to the pm_qos_class target value.
382 */
383int pm_qos_add_notifier(int pm_qos_class, struct notifier_block *notifier)
384{
385 int retval;
386
387 retval = blocking_notifier_chain_register(
388 pm_qos_array[pm_qos_class]->notifiers, notifier);
389
390 return retval;
391}
392EXPORT_SYMBOL_GPL(pm_qos_add_notifier);
393
394/**
395 * pm_qos_remove_notifier - deletes notification entry from chain.
396 * @pm_qos_class: identifies which qos target changes are notified.
397 * @notifier: notifier block to be removed.
398 *
399 * will remove the notifier from the notification chain that gets called
400 * upon changes to the pm_qos_class target value.
401 */
402int pm_qos_remove_notifier(int pm_qos_class, struct notifier_block *notifier)
403{
404 int retval;
405
406 retval = blocking_notifier_chain_unregister(
407 pm_qos_array[pm_qos_class]->notifiers, notifier);
408
409 return retval;
410}
411EXPORT_SYMBOL_GPL(pm_qos_remove_notifier);
412
413static int pm_qos_power_open(struct inode *inode, struct file *filp)
414{
415 long pm_qos_class;
416
417 pm_qos_class = find_pm_qos_object_by_minor(iminor(inode));
418 if (pm_qos_class >= 0) {
419 struct pm_qos_request_list *req = kzalloc(sizeof(*req), GFP_KERNEL);
420 if (!req)
421 return -ENOMEM;
422
423 pm_qos_add_request(req, pm_qos_class, PM_QOS_DEFAULT_VALUE);
424 filp->private_data = req;
425
426 if (filp->private_data)
427 return 0;
428 }
429 return -EPERM;
430}
431
432static int pm_qos_power_release(struct inode *inode, struct file *filp)
433{
434 struct pm_qos_request_list *req;
435
436 req = filp->private_data;
437 pm_qos_remove_request(req);
438 kfree(req);
439
440 return 0;
441}
442
443
444static ssize_t pm_qos_power_read(struct file *filp, char __user *buf,
445 size_t count, loff_t *f_pos)
446{
447 s32 value;
448 unsigned long flags;
449 struct pm_qos_object *o;
450 struct pm_qos_request_list *pm_qos_req = filp->private_data;
451
452 if (!pm_qos_req)
453 return -EINVAL;
454 if (!pm_qos_request_active(pm_qos_req))
455 return -EINVAL;
456
457 o = pm_qos_array[pm_qos_req->pm_qos_class];
458 spin_lock_irqsave(&pm_qos_lock, flags);
459 value = pm_qos_get_value(o);
460 spin_unlock_irqrestore(&pm_qos_lock, flags);
461
462 return simple_read_from_buffer(buf, count, f_pos, &value, sizeof(s32));
463}
464
465static ssize_t pm_qos_power_write(struct file *filp, const char __user *buf,
466 size_t count, loff_t *f_pos)
467{
468 s32 value;
469 struct pm_qos_request_list *pm_qos_req;
470
471 if (count == sizeof(s32)) {
472 if (copy_from_user(&value, buf, sizeof(s32)))
473 return -EFAULT;
474 } else if (count <= 11) { /* ASCII perhaps? */
475 char ascii_value[11];
476 unsigned long int ulval;
477 int ret;
478
479 if (copy_from_user(ascii_value, buf, count))
480 return -EFAULT;
481
482 if (count > 10) {
483 if (ascii_value[10] == '\n')
484 ascii_value[10] = '\0';
485 else
486 return -EINVAL;
487 } else {
488 ascii_value[count] = '\0';
489 }
490 ret = strict_strtoul(ascii_value, 16, &ulval);
491 if (ret) {
492 pr_debug("%s, 0x%lx, 0x%x\n", ascii_value, ulval, ret);
493 return -EINVAL;
494 }
495 value = (s32)lower_32_bits(ulval);
496 } else {
497 return -EINVAL;
498 }
499
500 pm_qos_req = filp->private_data;
501 pm_qos_update_request(pm_qos_req, value);
502
503 return count;
504}
505
506
507static int __init pm_qos_power_init(void)
508{
509 int ret = 0;
510 int i;
511
512 BUILD_BUG_ON(ARRAY_SIZE(pm_qos_array) != PM_QOS_NUM_CLASSES);
513
514 for (i = 1; i < PM_QOS_NUM_CLASSES; i++) {
515 ret = register_pm_qos_misc(pm_qos_array[i]);
516 if (ret < 0) {
517 printk(KERN_ERR "pm_qos_param: %s setup failed\n",
518 pm_qos_array[i]->name);
519 return ret;
520 }
521 }
522
523 return ret;
524}
525
526late_initcall(pm_qos_power_init);
diff --git a/kernel/power/consoleearlysuspend.c b/kernel/power/consoleearlysuspend.c
new file mode 100644
index 00000000000..a3edcb26738
--- /dev/null
+++ b/kernel/power/consoleearlysuspend.c
@@ -0,0 +1,78 @@
1/* kernel/power/consoleearlysuspend.c
2 *
3 * Copyright (C) 2005-2008 Google, Inc.
4 *
5 * This software is licensed under the terms of the GNU General Public
6 * License version 2, as published by the Free Software Foundation, and
7 * may be copied, distributed, and modified under those terms.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 */
15
16#include <linux/console.h>
17#include <linux/earlysuspend.h>
18#include <linux/kbd_kern.h>
19#include <linux/module.h>
20#include <linux/vt_kern.h>
21#include <linux/wait.h>
22
23#define EARLY_SUSPEND_CONSOLE (MAX_NR_CONSOLES-1)
24
25static int orig_fgconsole;
26static void console_early_suspend(struct early_suspend *h)
27{
28 acquire_console_sem();
29 orig_fgconsole = fg_console;
30 if (vc_allocate(EARLY_SUSPEND_CONSOLE))
31 goto err;
32 if (set_console(EARLY_SUSPEND_CONSOLE))
33 goto err;
34 release_console_sem();
35
36 if (vt_waitactive(EARLY_SUSPEND_CONSOLE + 1))
37 pr_warning("console_early_suspend: Can't switch VCs.\n");
38 return;
39err:
40 pr_warning("console_early_suspend: Can't set console\n");
41 release_console_sem();
42}
43
44static void console_late_resume(struct early_suspend *h)
45{
46 int ret;
47 acquire_console_sem();
48 ret = set_console(orig_fgconsole);
49 release_console_sem();
50 if (ret) {
51 pr_warning("console_late_resume: Can't set console.\n");
52 return;
53 }
54
55 if (vt_waitactive(orig_fgconsole + 1))
56 pr_warning("console_late_resume: Can't switch VCs.\n");
57}
58
59static struct early_suspend console_early_suspend_desc = {
60 .level = EARLY_SUSPEND_LEVEL_STOP_DRAWING,
61 .suspend = console_early_suspend,
62 .resume = console_late_resume,
63};
64
65static int __init console_early_suspend_init(void)
66{
67 register_early_suspend(&console_early_suspend_desc);
68 return 0;
69}
70
71static void __exit console_early_suspend_exit(void)
72{
73 unregister_early_suspend(&console_early_suspend_desc);
74}
75
76module_init(console_early_suspend_init);
77module_exit(console_early_suspend_exit);
78
diff --git a/kernel/power/earlysuspend.c b/kernel/power/earlysuspend.c
new file mode 100644
index 00000000000..b15f02eba45
--- /dev/null
+++ b/kernel/power/earlysuspend.c
@@ -0,0 +1,187 @@
1/* kernel/power/earlysuspend.c
2 *
3 * Copyright (C) 2005-2008 Google, Inc.
4 *
5 * This software is licensed under the terms of the GNU General Public
6 * License version 2, as published by the Free Software Foundation, and
7 * may be copied, distributed, and modified under those terms.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 */
15
16#include <linux/earlysuspend.h>
17#include <linux/module.h>
18#include <linux/mutex.h>
19#include <linux/rtc.h>
20#include <linux/syscalls.h> /* sys_sync */
21#include <linux/wakelock.h>
22#include <linux/workqueue.h>
23
24#include "power.h"
25
26enum {
27 DEBUG_USER_STATE = 1U << 0,
28 DEBUG_SUSPEND = 1U << 2,
29 DEBUG_VERBOSE = 1U << 3,
30};
31static int debug_mask = DEBUG_USER_STATE;
32module_param_named(debug_mask, debug_mask, int, S_IRUGO | S_IWUSR | S_IWGRP);
33
34static DEFINE_MUTEX(early_suspend_lock);
35static LIST_HEAD(early_suspend_handlers);
36static void early_suspend(struct work_struct *work);
37static void late_resume(struct work_struct *work);
38static DECLARE_WORK(early_suspend_work, early_suspend);
39static DECLARE_WORK(late_resume_work, late_resume);
40static DEFINE_SPINLOCK(state_lock);
41enum {
42 SUSPEND_REQUESTED = 0x1,
43 SUSPENDED = 0x2,
44 SUSPEND_REQUESTED_AND_SUSPENDED = SUSPEND_REQUESTED | SUSPENDED,
45};
46static int state;
47
48void register_early_suspend(struct early_suspend *handler)
49{
50 struct list_head *pos;
51
52 mutex_lock(&early_suspend_lock);
53 list_for_each(pos, &early_suspend_handlers) {
54 struct early_suspend *e;
55 e = list_entry(pos, struct early_suspend, link);
56 if (e->level > handler->level)
57 break;
58 }
59 list_add_tail(&handler->link, pos);
60 if ((state & SUSPENDED) && handler->suspend)
61 handler->suspend(handler);
62 mutex_unlock(&early_suspend_lock);
63}
64EXPORT_SYMBOL(register_early_suspend);
65
66void unregister_early_suspend(struct early_suspend *handler)
67{
68 mutex_lock(&early_suspend_lock);
69 list_del(&handler->link);
70 mutex_unlock(&early_suspend_lock);
71}
72EXPORT_SYMBOL(unregister_early_suspend);
73
74static void early_suspend(struct work_struct *work)
75{
76 struct early_suspend *pos;
77 unsigned long irqflags;
78 int abort = 0;
79
80 mutex_lock(&early_suspend_lock);
81 spin_lock_irqsave(&state_lock, irqflags);
82 if (state == SUSPEND_REQUESTED)
83 state |= SUSPENDED;
84 else
85 abort = 1;
86 spin_unlock_irqrestore(&state_lock, irqflags);
87
88 if (abort) {
89 if (debug_mask & DEBUG_SUSPEND)
90 pr_info("early_suspend: abort, state %d\n", state);
91 mutex_unlock(&early_suspend_lock);
92 goto abort;
93 }
94
95 if (debug_mask & DEBUG_SUSPEND)
96 pr_info("early_suspend: call handlers\n");
97 list_for_each_entry(pos, &early_suspend_handlers, link) {
98 if (pos->suspend != NULL) {
99 if (debug_mask & DEBUG_VERBOSE)
100 pr_info("early_suspend: calling %pf\n", pos->suspend);
101 pos->suspend(pos);
102 }
103 }
104 mutex_unlock(&early_suspend_lock);
105
106 if (debug_mask & DEBUG_SUSPEND)
107 pr_info("early_suspend: sync\n");
108
109 sys_sync();
110abort:
111 spin_lock_irqsave(&state_lock, irqflags);
112 if (state == SUSPEND_REQUESTED_AND_SUSPENDED)
113 wake_unlock(&main_wake_lock);
114 spin_unlock_irqrestore(&state_lock, irqflags);
115}
116
117static void late_resume(struct work_struct *work)
118{
119 struct early_suspend *pos;
120 unsigned long irqflags;
121 int abort = 0;
122
123 mutex_lock(&early_suspend_lock);
124 spin_lock_irqsave(&state_lock, irqflags);
125 if (state == SUSPENDED)
126 state &= ~SUSPENDED;
127 else
128 abort = 1;
129 spin_unlock_irqrestore(&state_lock, irqflags);
130
131 if (abort) {
132 if (debug_mask & DEBUG_SUSPEND)
133 pr_info("late_resume: abort, state %d\n", state);
134 goto abort;
135 }
136 if (debug_mask & DEBUG_SUSPEND)
137 pr_info("late_resume: call handlers\n");
138 list_for_each_entry_reverse(pos, &early_suspend_handlers, link) {
139 if (pos->resume != NULL) {
140 if (debug_mask & DEBUG_VERBOSE)
141 pr_info("late_resume: calling %pf\n", pos->resume);
142
143 pos->resume(pos);
144 }
145 }
146 if (debug_mask & DEBUG_SUSPEND)
147 pr_info("late_resume: done\n");
148abort:
149 mutex_unlock(&early_suspend_lock);
150}
151
152void request_suspend_state(suspend_state_t new_state)
153{
154 unsigned long irqflags;
155 int old_sleep;
156
157 spin_lock_irqsave(&state_lock, irqflags);
158 old_sleep = state & SUSPEND_REQUESTED;
159 if (debug_mask & DEBUG_USER_STATE) {
160 struct timespec ts;
161 struct rtc_time tm;
162 getnstimeofday(&ts);
163 rtc_time_to_tm(ts.tv_sec, &tm);
164 pr_info("request_suspend_state: %s (%d->%d) at %lld "
165 "(%d-%02d-%02d %02d:%02d:%02d.%09lu UTC)\n",
166 new_state != PM_SUSPEND_ON ? "sleep" : "wakeup",
167 requested_suspend_state, new_state,
168 ktime_to_ns(ktime_get()),
169 tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
170 tm.tm_hour, tm.tm_min, tm.tm_sec, ts.tv_nsec);
171 }
172 if (!old_sleep && new_state != PM_SUSPEND_ON) {
173 state |= SUSPEND_REQUESTED;
174 queue_work(suspend_work_queue, &early_suspend_work);
175 } else if (old_sleep && new_state == PM_SUSPEND_ON) {
176 state &= ~SUSPEND_REQUESTED;
177 wake_lock(&main_wake_lock);
178 queue_work(suspend_work_queue, &late_resume_work);
179 }
180 requested_suspend_state = new_state;
181 spin_unlock_irqrestore(&state_lock, irqflags);
182}
183
184suspend_state_t get_suspend_state(void)
185{
186 return requested_suspend_state;
187}
diff --git a/kernel/power/fbearlysuspend.c b/kernel/power/fbearlysuspend.c
new file mode 100644
index 00000000000..15137650149
--- /dev/null
+++ b/kernel/power/fbearlysuspend.c
@@ -0,0 +1,153 @@
1/* kernel/power/fbearlysuspend.c
2 *
3 * Copyright (C) 2005-2008 Google, Inc.
4 *
5 * This software is licensed under the terms of the GNU General Public
6 * License version 2, as published by the Free Software Foundation, and
7 * may be copied, distributed, and modified under those terms.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 */
15
16#include <linux/earlysuspend.h>
17#include <linux/module.h>
18#include <linux/wait.h>
19
20#include "power.h"
21
22static wait_queue_head_t fb_state_wq;
23static DEFINE_SPINLOCK(fb_state_lock);
24static enum {
25 FB_STATE_STOPPED_DRAWING,
26 FB_STATE_REQUEST_STOP_DRAWING,
27 FB_STATE_DRAWING_OK,
28} fb_state;
29
30/* tell userspace to stop drawing, wait for it to stop */
31static void stop_drawing_early_suspend(struct early_suspend *h)
32{
33 int ret;
34 unsigned long irq_flags;
35
36 spin_lock_irqsave(&fb_state_lock, irq_flags);
37 fb_state = FB_STATE_REQUEST_STOP_DRAWING;
38 spin_unlock_irqrestore(&fb_state_lock, irq_flags);
39
40 wake_up_all(&fb_state_wq);
41 ret = wait_event_timeout(fb_state_wq,
42 fb_state == FB_STATE_STOPPED_DRAWING,
43 HZ);
44 if (unlikely(fb_state != FB_STATE_STOPPED_DRAWING))
45 pr_warning("stop_drawing_early_suspend: timeout waiting for "
46 "userspace to stop drawing\n");
47}
48
49/* tell userspace to start drawing */
50static void start_drawing_late_resume(struct early_suspend *h)
51{
52 unsigned long irq_flags;
53
54 spin_lock_irqsave(&fb_state_lock, irq_flags);
55 fb_state = FB_STATE_DRAWING_OK;
56 spin_unlock_irqrestore(&fb_state_lock, irq_flags);
57 wake_up(&fb_state_wq);
58}
59
60static struct early_suspend stop_drawing_early_suspend_desc = {
61 .level = EARLY_SUSPEND_LEVEL_STOP_DRAWING,
62 .suspend = stop_drawing_early_suspend,
63 .resume = start_drawing_late_resume,
64};
65
66static ssize_t wait_for_fb_sleep_show(struct kobject *kobj,
67 struct kobj_attribute *attr, char *buf)
68{
69 char *s = buf;
70 int ret;
71
72 ret = wait_event_interruptible(fb_state_wq,
73 fb_state != FB_STATE_DRAWING_OK);
74 if (ret && fb_state == FB_STATE_DRAWING_OK)
75 return ret;
76 else
77 s += sprintf(buf, "sleeping");
78 return s - buf;
79}
80
81static ssize_t wait_for_fb_wake_show(struct kobject *kobj,
82 struct kobj_attribute *attr, char *buf)
83{
84 char *s = buf;
85 int ret;
86 unsigned long irq_flags;
87
88 spin_lock_irqsave(&fb_state_lock, irq_flags);
89 if (fb_state == FB_STATE_REQUEST_STOP_DRAWING) {
90 fb_state = FB_STATE_STOPPED_DRAWING;
91 wake_up(&fb_state_wq);
92 }
93 spin_unlock_irqrestore(&fb_state_lock, irq_flags);
94
95 ret = wait_event_interruptible(fb_state_wq,
96 fb_state == FB_STATE_DRAWING_OK);
97 if (ret && fb_state != FB_STATE_DRAWING_OK)
98 return ret;
99 else
100 s += sprintf(buf, "awake");
101
102 return s - buf;
103}
104
105#define power_ro_attr(_name) \
106static struct kobj_attribute _name##_attr = { \
107 .attr = { \
108 .name = __stringify(_name), \
109 .mode = 0444, \
110 }, \
111 .show = _name##_show, \
112 .store = NULL, \
113}
114
115power_ro_attr(wait_for_fb_sleep);
116power_ro_attr(wait_for_fb_wake);
117
118static struct attribute *g[] = {
119 &wait_for_fb_sleep_attr.attr,
120 &wait_for_fb_wake_attr.attr,
121 NULL,
122};
123
124static struct attribute_group attr_group = {
125 .attrs = g,
126};
127
128static int __init android_power_init(void)
129{
130 int ret;
131
132 init_waitqueue_head(&fb_state_wq);
133 fb_state = FB_STATE_DRAWING_OK;
134
135 ret = sysfs_create_group(power_kobj, &attr_group);
136 if (ret) {
137 pr_err("android_power_init: sysfs_create_group failed\n");
138 return ret;
139 }
140
141 register_early_suspend(&stop_drawing_early_suspend_desc);
142 return 0;
143}
144
145static void __exit android_power_exit(void)
146{
147 unregister_early_suspend(&stop_drawing_early_suspend_desc);
148 sysfs_remove_group(power_kobj, &attr_group);
149}
150
151module_init(android_power_init);
152module_exit(android_power_exit);
153
diff --git a/kernel/power/suspend_time.c b/kernel/power/suspend_time.c
new file mode 100644
index 00000000000..d2a65da9f22
--- /dev/null
+++ b/kernel/power/suspend_time.c
@@ -0,0 +1,111 @@
1/*
2 * debugfs file to track time spent in suspend
3 *
4 * Copyright (c) 2011, Google, Inc.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14 * more details.
15 */
16
17#include <linux/debugfs.h>
18#include <linux/err.h>
19#include <linux/init.h>
20#include <linux/kernel.h>
21#include <linux/seq_file.h>
22#include <linux/syscore_ops.h>
23#include <linux/time.h>
24
25static struct timespec suspend_time_before;
26static unsigned int time_in_suspend_bins[32];
27
28#ifdef CONFIG_DEBUG_FS
29static int suspend_time_debug_show(struct seq_file *s, void *data)
30{
31 int bin;
32 seq_printf(s, "time (secs) count\n");
33 seq_printf(s, "------------------\n");
34 for (bin = 0; bin < 32; bin++) {
35 if (time_in_suspend_bins[bin] == 0)
36 continue;
37 seq_printf(s, "%4d - %4d %4u\n",
38 bin ? 1 << (bin - 1) : 0, 1 << bin,
39 time_in_suspend_bins[bin]);
40 }
41 return 0;
42}
43
44static int suspend_time_debug_open(struct inode *inode, struct file *file)
45{
46 return single_open(file, suspend_time_debug_show, NULL);
47}
48
49static const struct file_operations suspend_time_debug_fops = {
50 .open = suspend_time_debug_open,
51 .read = seq_read,
52 .llseek = seq_lseek,
53 .release = single_release,
54};
55
56static int __init suspend_time_debug_init(void)
57{
58 struct dentry *d;
59
60 d = debugfs_create_file("suspend_time", 0755, NULL, NULL,
61 &suspend_time_debug_fops);
62 if (!d) {
63 pr_err("Failed to create suspend_time debug file\n");
64 return -ENOMEM;
65 }
66
67 return 0;
68}
69
70late_initcall(suspend_time_debug_init);
71#endif
72
73static int suspend_time_syscore_suspend(void)
74{
75 read_persistent_clock(&suspend_time_before);
76
77 return 0;
78}
79
80static void suspend_time_syscore_resume(void)
81{
82 struct timespec after;
83
84 read_persistent_clock(&after);
85
86 after = timespec_sub(after, suspend_time_before);
87
88 time_in_suspend_bins[fls(after.tv_sec)]++;
89
90 pr_info("Suspended for %lu.%03lu seconds\n", after.tv_sec,
91 after.tv_nsec / NSEC_PER_MSEC);
92}
93
94static struct syscore_ops suspend_time_syscore_ops = {
95 .suspend = suspend_time_syscore_suspend,
96 .resume = suspend_time_syscore_resume,
97};
98
99static int suspend_time_syscore_init(void)
100{
101 register_syscore_ops(&suspend_time_syscore_ops);
102
103 return 0;
104}
105
106static void suspend_time_syscore_exit(void)
107{
108 unregister_syscore_ops(&suspend_time_syscore_ops);
109}
110module_init(suspend_time_syscore_init);
111module_exit(suspend_time_syscore_exit);
diff --git a/kernel/power/userwakelock.c b/kernel/power/userwakelock.c
new file mode 100644
index 00000000000..a28a8db4146
--- /dev/null
+++ b/kernel/power/userwakelock.c
@@ -0,0 +1,219 @@
1/* kernel/power/userwakelock.c
2 *
3 * Copyright (C) 2005-2008 Google, Inc.
4 *
5 * This software is licensed under the terms of the GNU General Public
6 * License version 2, as published by the Free Software Foundation, and
7 * may be copied, distributed, and modified under those terms.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 */
15
16#include <linux/ctype.h>
17#include <linux/module.h>
18#include <linux/wakelock.h>
19#include <linux/slab.h>
20
21#include "power.h"
22
23enum {
24 DEBUG_FAILURE = BIT(0),
25 DEBUG_ERROR = BIT(1),
26 DEBUG_NEW = BIT(2),
27 DEBUG_ACCESS = BIT(3),
28 DEBUG_LOOKUP = BIT(4),
29};
30static int debug_mask = DEBUG_FAILURE;
31module_param_named(debug_mask, debug_mask, int, S_IRUGO | S_IWUSR | S_IWGRP);
32
33static DEFINE_MUTEX(tree_lock);
34
35struct user_wake_lock {
36 struct rb_node node;
37 struct wake_lock wake_lock;
38 char name[0];
39};
40struct rb_root user_wake_locks;
41
42static struct user_wake_lock *lookup_wake_lock_name(
43 const char *buf, int allocate, long *timeoutptr)
44{
45 struct rb_node **p = &user_wake_locks.rb_node;
46 struct rb_node *parent = NULL;
47 struct user_wake_lock *l;
48 int diff;
49 u64 timeout;
50 int name_len;
51 const char *arg;
52
53 /* Find length of lock name and start of optional timeout string */
54 arg = buf;
55 while (*arg && !isspace(*arg))
56 arg++;
57 name_len = arg - buf;
58 if (!name_len)
59 goto bad_arg;
60 while (isspace(*arg))
61 arg++;
62
63 /* Process timeout string */
64 if (timeoutptr && *arg) {
65 timeout = simple_strtoull(arg, (char **)&arg, 0);
66 while (isspace(*arg))
67 arg++;
68 if (*arg)
69 goto bad_arg;
70 /* convert timeout from nanoseconds to jiffies > 0 */
71 timeout += (NSEC_PER_SEC / HZ) - 1;
72 do_div(timeout, (NSEC_PER_SEC / HZ));
73 if (timeout <= 0)
74 timeout = 1;
75 *timeoutptr = timeout;
76 } else if (*arg)
77 goto bad_arg;
78 else if (timeoutptr)
79 *timeoutptr = 0;
80
81 /* Lookup wake lock in rbtree */
82 while (*p) {
83 parent = *p;
84 l = rb_entry(parent, struct user_wake_lock, node);
85 diff = strncmp(buf, l->name, name_len);
86 if (!diff && l->name[name_len])
87 diff = -1;
88 if (debug_mask & DEBUG_ERROR)
89 pr_info("lookup_wake_lock_name: compare %.*s %s %d\n",
90 name_len, buf, l->name, diff);
91
92 if (diff < 0)
93 p = &(*p)->rb_left;
94 else if (diff > 0)
95 p = &(*p)->rb_right;
96 else
97 return l;
98 }
99
100 /* Allocate and add new wakelock to rbtree */
101 if (!allocate) {
102 if (debug_mask & DEBUG_ERROR)
103 pr_info("lookup_wake_lock_name: %.*s not found\n",
104 name_len, buf);
105 return ERR_PTR(-EINVAL);
106 }
107 l = kzalloc(sizeof(*l) + name_len + 1, GFP_KERNEL);
108 if (l == NULL) {
109 if (debug_mask & DEBUG_FAILURE)
110 pr_err("lookup_wake_lock_name: failed to allocate "
111 "memory for %.*s\n", name_len, buf);
112 return ERR_PTR(-ENOMEM);
113 }
114 memcpy(l->name, buf, name_len);
115 if (debug_mask & DEBUG_NEW)
116 pr_info("lookup_wake_lock_name: new wake lock %s\n", l->name);
117 wake_lock_init(&l->wake_lock, WAKE_LOCK_SUSPEND, l->name);
118 rb_link_node(&l->node, parent, p);
119 rb_insert_color(&l->node, &user_wake_locks);
120 return l;
121
122bad_arg:
123 if (debug_mask & DEBUG_ERROR)
124 pr_info("lookup_wake_lock_name: wake lock, %.*s, bad arg, %s\n",
125 name_len, buf, arg);
126 return ERR_PTR(-EINVAL);
127}
128
129ssize_t wake_lock_show(
130 struct kobject *kobj, struct kobj_attribute *attr, char *buf)
131{
132 char *s = buf;
133 char *end = buf + PAGE_SIZE;
134 struct rb_node *n;
135 struct user_wake_lock *l;
136
137 mutex_lock(&tree_lock);
138
139 for (n = rb_first(&user_wake_locks); n != NULL; n = rb_next(n)) {
140 l = rb_entry(n, struct user_wake_lock, node);
141 if (wake_lock_active(&l->wake_lock))
142 s += scnprintf(s, end - s, "%s ", l->name);
143 }
144 s += scnprintf(s, end - s, "\n");
145
146 mutex_unlock(&tree_lock);
147 return (s - buf);
148}
149
150ssize_t wake_lock_store(
151 struct kobject *kobj, struct kobj_attribute *attr,
152 const char *buf, size_t n)
153{
154 long timeout;
155 struct user_wake_lock *l;
156
157 mutex_lock(&tree_lock);
158 l = lookup_wake_lock_name(buf, 1, &timeout);
159 if (IS_ERR(l)) {
160 n = PTR_ERR(l);
161 goto bad_name;
162 }
163
164 if (debug_mask & DEBUG_ACCESS)
165 pr_info("wake_lock_store: %s, timeout %ld\n", l->name, timeout);
166
167 if (timeout)
168 wake_lock_timeout(&l->wake_lock, timeout);
169 else
170 wake_lock(&l->wake_lock);
171bad_name:
172 mutex_unlock(&tree_lock);
173 return n;
174}
175
176
177ssize_t wake_unlock_show(
178 struct kobject *kobj, struct kobj_attribute *attr, char *buf)
179{
180 char *s = buf;
181 char *end = buf + PAGE_SIZE;
182 struct rb_node *n;
183 struct user_wake_lock *l;
184
185 mutex_lock(&tree_lock);
186
187 for (n = rb_first(&user_wake_locks); n != NULL; n = rb_next(n)) {
188 l = rb_entry(n, struct user_wake_lock, node);
189 if (!wake_lock_active(&l->wake_lock))
190 s += scnprintf(s, end - s, "%s ", l->name);
191 }
192 s += scnprintf(s, end - s, "\n");
193
194 mutex_unlock(&tree_lock);
195 return (s - buf);
196}
197
198ssize_t wake_unlock_store(
199 struct kobject *kobj, struct kobj_attribute *attr,
200 const char *buf, size_t n)
201{
202 struct user_wake_lock *l;
203
204 mutex_lock(&tree_lock);
205 l = lookup_wake_lock_name(buf, 0, NULL);
206 if (IS_ERR(l)) {
207 n = PTR_ERR(l);
208 goto not_found;
209 }
210
211 if (debug_mask & DEBUG_ACCESS)
212 pr_info("wake_unlock_store: %s\n", l->name);
213
214 wake_unlock(&l->wake_lock);
215not_found:
216 mutex_unlock(&tree_lock);
217 return n;
218}
219
diff --git a/kernel/sched.c b/kernel/sched.c
new file mode 100644
index 00000000000..f6cf5cbc64b
--- /dev/null
+++ b/kernel/sched.c
@@ -0,0 +1,9443 @@
1/*
2 * kernel/sched.c
3 *
4 * Kernel scheduler and related syscalls
5 *
6 * Copyright (C) 1991-2002 Linus Torvalds
7 *
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
11 * by Andrea Arcangeli
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
19 * 2007-04-15 Work begun on replacing all interactivity tuning with a
20 * fair scheduling design by Con Kolivas.
21 * 2007-05-05 Load balancing (smp-nice) and other improvements
22 * by Peter Williams
23 * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
24 * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
25 * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
26 * Thomas Gleixner, Mike Kravetz
27 */
28
29#include <linux/mm.h>
30#include <linux/module.h>
31#include <linux/nmi.h>
32#include <linux/init.h>
33#include <linux/uaccess.h>
34#include <linux/highmem.h>
35#include <asm/mmu_context.h>
36#include <linux/interrupt.h>
37#include <linux/capability.h>
38#include <linux/completion.h>
39#include <linux/kernel_stat.h>
40#include <linux/debug_locks.h>
41#include <linux/perf_event.h>
42#include <linux/security.h>
43#include <linux/notifier.h>
44#include <linux/profile.h>
45#include <linux/freezer.h>
46#include <linux/vmalloc.h>
47#include <linux/blkdev.h>
48#include <linux/delay.h>
49#include <linux/pid_namespace.h>
50#include <linux/smp.h>
51#include <linux/threads.h>
52#include <linux/timer.h>
53#include <linux/rcupdate.h>
54#include <linux/cpu.h>
55#include <linux/cpuset.h>
56#include <linux/percpu.h>
57#include <linux/proc_fs.h>
58#include <linux/seq_file.h>
59#include <linux/stop_machine.h>
60#include <linux/sysctl.h>
61#include <linux/syscalls.h>
62#include <linux/times.h>
63#include <linux/tsacct_kern.h>
64#include <linux/kprobes.h>
65#include <linux/delayacct.h>
66#include <linux/unistd.h>
67#include <linux/pagemap.h>
68#include <linux/hrtimer.h>
69#include <linux/tick.h>
70#include <linux/debugfs.h>
71#include <linux/ctype.h>
72#include <linux/ftrace.h>
73#include <linux/slab.h>
74#include <linux/cpuacct.h>
75
76#include <asm/tlb.h>
77#include <asm/irq_regs.h>
78#include <asm/mutex.h>
79#ifdef CONFIG_PARAVIRT
80#include <asm/paravirt.h>
81#endif
82
83#include "sched_cpupri.h"
84#include "workqueue_sched.h"
85#include "sched_autogroup.h"
86
87#define CREATE_TRACE_POINTS
88#include <trace/events/sched.h>
89
90/*
91 * Convert user-nice values [ -20 ... 0 ... 19 ]
92 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
93 * and back.
94 */
95#define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
96#define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
97#define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
98
99/*
100 * 'User priority' is the nice value converted to something we
101 * can work with better when scaling various scheduler parameters,
102 * it's a [ 0 ... 39 ] range.
103 */
104#define USER_PRIO(p) ((p)-MAX_RT_PRIO)
105#define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
106#define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
107
108/*
109 * Helpers for converting nanosecond timing to jiffy resolution
110 */
111#define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
112
113#define NICE_0_LOAD SCHED_LOAD_SCALE
114#define NICE_0_SHIFT SCHED_LOAD_SHIFT
115
116/*
117 * These are the 'tuning knobs' of the scheduler:
118 *
119 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
120 * Timeslices get refilled after they expire.
121 */
122#define DEF_TIMESLICE (100 * HZ / 1000)
123
124/*
125 * single value that denotes runtime == period, ie unlimited time.
126 */
127#define RUNTIME_INF ((u64)~0ULL)
128
129static inline int rt_policy(int policy)
130{
131 if (policy == SCHED_FIFO || policy == SCHED_RR)
132 return 1;
133 return 0;
134}
135
136static inline int task_has_rt_policy(struct task_struct *p)
137{
138 return rt_policy(p->policy);
139}
140
141/*
142 * This is the priority-queue data structure of the RT scheduling class:
143 */
144struct rt_prio_array {
145 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
146 struct list_head queue[MAX_RT_PRIO];
147};
148
149struct rt_bandwidth {
150 /* nests inside the rq lock: */
151 raw_spinlock_t rt_runtime_lock;
152 ktime_t rt_period;
153 u64 rt_runtime;
154 struct hrtimer rt_period_timer;
155};
156
157static struct rt_bandwidth def_rt_bandwidth;
158
159static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
160
161static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
162{
163 struct rt_bandwidth *rt_b =
164 container_of(timer, struct rt_bandwidth, rt_period_timer);
165 ktime_t now;
166 int overrun;
167 int idle = 0;
168
169 for (;;) {
170 now = hrtimer_cb_get_time(timer);
171 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
172
173 if (!overrun)
174 break;
175
176 idle = do_sched_rt_period_timer(rt_b, overrun);
177 }
178
179 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
180}
181
182static
183void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
184{
185 rt_b->rt_period = ns_to_ktime(period);
186 rt_b->rt_runtime = runtime;
187
188 raw_spin_lock_init(&rt_b->rt_runtime_lock);
189
190 hrtimer_init(&rt_b->rt_period_timer,
191 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
192 rt_b->rt_period_timer.function = sched_rt_period_timer;
193}
194
195static inline int rt_bandwidth_enabled(void)
196{
197 return sysctl_sched_rt_runtime >= 0;
198}
199
200static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
201{
202 ktime_t now;
203
204 if (!rt_bandwidth_enabled() || rt_b->rt_runtime == RUNTIME_INF)
205 return;
206
207 if (hrtimer_active(&rt_b->rt_period_timer))
208 return;
209
210 raw_spin_lock(&rt_b->rt_runtime_lock);
211 for (;;) {
212 unsigned long delta;
213 ktime_t soft, hard;
214
215 if (hrtimer_active(&rt_b->rt_period_timer))
216 break;
217
218 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
219 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
220
221 soft = hrtimer_get_softexpires(&rt_b->rt_period_timer);
222 hard = hrtimer_get_expires(&rt_b->rt_period_timer);
223 delta = ktime_to_ns(ktime_sub(hard, soft));
224 __hrtimer_start_range_ns(&rt_b->rt_period_timer, soft, delta,
225 HRTIMER_MODE_ABS_PINNED, 0);
226 }
227 raw_spin_unlock(&rt_b->rt_runtime_lock);
228}
229
230#ifdef CONFIG_RT_GROUP_SCHED
231static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
232{
233 hrtimer_cancel(&rt_b->rt_period_timer);
234}
235#endif
236
237/*
238 * sched_domains_mutex serializes calls to init_sched_domains,
239 * detach_destroy_domains and partition_sched_domains.
240 */
241static DEFINE_MUTEX(sched_domains_mutex);
242
243#ifdef CONFIG_CGROUP_SCHED
244
245#include <linux/cgroup.h>
246
247struct cfs_rq;
248
249static LIST_HEAD(task_groups);
250
251/* task group related information */
252struct task_group {
253 struct cgroup_subsys_state css;
254
255#ifdef CONFIG_FAIR_GROUP_SCHED
256 /* schedulable entities of this group on each cpu */
257 struct sched_entity **se;
258 /* runqueue "owned" by this group on each cpu */
259 struct cfs_rq **cfs_rq;
260 unsigned long shares;
261
262 atomic_t load_weight;
263#endif
264
265#ifdef CONFIG_RT_GROUP_SCHED
266 struct sched_rt_entity **rt_se;
267 struct rt_rq **rt_rq;
268
269 struct rt_bandwidth rt_bandwidth;
270#endif
271
272 struct rcu_head rcu;
273 struct list_head list;
274
275 struct task_group *parent;
276 struct list_head siblings;
277 struct list_head children;
278
279#ifdef CONFIG_SCHED_AUTOGROUP
280 struct autogroup *autogroup;
281#endif
282};
283
284/* task_group_lock serializes the addition/removal of task groups */
285static DEFINE_SPINLOCK(task_group_lock);
286
287#ifdef CONFIG_FAIR_GROUP_SCHED
288
289# define ROOT_TASK_GROUP_LOAD NICE_0_LOAD
290
291/*
292 * A weight of 0 or 1 can cause arithmetics problems.
293 * A weight of a cfs_rq is the sum of weights of which entities
294 * are queued on this cfs_rq, so a weight of a entity should not be
295 * too large, so as the shares value of a task group.
296 * (The default weight is 1024 - so there's no practical
297 * limitation from this.)
298 */
299#define MIN_SHARES (1UL << 1)
300#define MAX_SHARES (1UL << 18)
301
302static int root_task_group_load = ROOT_TASK_GROUP_LOAD;
303#endif
304
305/* Default task group.
306 * Every task in system belong to this group at bootup.
307 */
308struct task_group root_task_group;
309
310#endif /* CONFIG_CGROUP_SCHED */
311
312/* CFS-related fields in a runqueue */
313struct cfs_rq {
314 struct load_weight load;
315 unsigned long nr_running;
316
317 u64 exec_clock;
318 u64 min_vruntime;
319#ifndef CONFIG_64BIT
320 u64 min_vruntime_copy;
321#endif
322
323 struct rb_root tasks_timeline;
324 struct rb_node *rb_leftmost;
325
326 struct list_head tasks;
327 struct list_head *balance_iterator;
328
329 /*
330 * 'curr' points to currently running entity on this cfs_rq.
331 * It is set to NULL otherwise (i.e when none are currently running).
332 */
333 struct sched_entity *curr, *next, *last, *skip;
334
335#ifdef CONFIG_SCHED_DEBUG
336 unsigned int nr_spread_over;
337#endif
338
339#ifdef CONFIG_FAIR_GROUP_SCHED
340 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
341
342 /*
343 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
344 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
345 * (like users, containers etc.)
346 *
347 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
348 * list is used during load balance.
349 */
350 int on_list;
351 struct list_head leaf_cfs_rq_list;
352 struct task_group *tg; /* group that "owns" this runqueue */
353
354#ifdef CONFIG_SMP
355 /*
356 * the part of load.weight contributed by tasks
357 */
358 unsigned long task_weight;
359
360 /*
361 * h_load = weight * f(tg)
362 *
363 * Where f(tg) is the recursive weight fraction assigned to
364 * this group.
365 */
366 unsigned long h_load;
367
368 /*
369 * Maintaining per-cpu shares distribution for group scheduling
370 *
371 * load_stamp is the last time we updated the load average
372 * load_last is the last time we updated the load average and saw load
373 * load_unacc_exec_time is currently unaccounted execution time
374 */
375 u64 load_avg;
376 u64 load_period;
377 u64 load_stamp, load_last, load_unacc_exec_time;
378
379 unsigned long load_contribution;
380#endif
381#endif
382};
383
384/* Real-Time classes' related field in a runqueue: */
385struct rt_rq {
386 struct rt_prio_array active;
387 unsigned long rt_nr_running;
388#if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
389 struct {
390 int curr; /* highest queued rt task prio */
391#ifdef CONFIG_SMP
392 int next; /* next highest */
393#endif
394 } highest_prio;
395#endif
396#ifdef CONFIG_SMP
397 unsigned long rt_nr_migratory;
398 unsigned long rt_nr_total;
399 int overloaded;
400 struct plist_head pushable_tasks;
401#endif
402 int rt_throttled;
403 u64 rt_time;
404 u64 rt_runtime;
405 /* Nests inside the rq lock: */
406 raw_spinlock_t rt_runtime_lock;
407
408#ifdef CONFIG_RT_GROUP_SCHED
409 unsigned long rt_nr_boosted;
410
411 struct rq *rq;
412 struct list_head leaf_rt_rq_list;
413 struct task_group *tg;
414#endif
415};
416
417#ifdef CONFIG_SMP
418
419/*
420 * We add the notion of a root-domain which will be used to define per-domain
421 * variables. Each exclusive cpuset essentially defines an island domain by
422 * fully partitioning the member cpus from any other cpuset. Whenever a new
423 * exclusive cpuset is created, we also create and attach a new root-domain
424 * object.
425 *
426 */
427struct root_domain {
428 atomic_t refcount;
429 atomic_t rto_count;
430 struct rcu_head rcu;
431 cpumask_var_t span;
432 cpumask_var_t online;
433
434 /*
435 * The "RT overload" flag: it gets set if a CPU has more than
436 * one runnable RT task.
437 */
438 cpumask_var_t rto_mask;
439 struct cpupri cpupri;
440};
441
442/*
443 * By default the system creates a single root-domain with all cpus as
444 * members (mimicking the global state we have today).
445 */
446static struct root_domain def_root_domain;
447
448#endif /* CONFIG_SMP */
449
450/*
451 * This is the main, per-CPU runqueue data structure.
452 *
453 * Locking rule: those places that want to lock multiple runqueues
454 * (such as the load balancing or the thread migration code), lock
455 * acquire operations must be ordered by ascending &runqueue.
456 */
457struct rq {
458 /* runqueue lock: */
459 raw_spinlock_t lock;
460
461 /*
462 * nr_running and cpu_load should be in the same cacheline because
463 * remote CPUs use both these fields when doing load calculation.
464 */
465 unsigned long nr_running;
466 #define CPU_LOAD_IDX_MAX 5
467 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
468 unsigned long last_load_update_tick;
469#ifdef CONFIG_NO_HZ
470 u64 nohz_stamp;
471 unsigned char nohz_balance_kick;
472#endif
473 int skip_clock_update;
474
475 /* capture load from *all* tasks on this cpu: */
476 struct load_weight load;
477 unsigned long nr_load_updates;
478 u64 nr_switches;
479
480 struct cfs_rq cfs;
481 struct rt_rq rt;
482
483#ifdef CONFIG_FAIR_GROUP_SCHED
484 /* list of leaf cfs_rq on this cpu: */
485 struct list_head leaf_cfs_rq_list;
486#endif
487#ifdef CONFIG_RT_GROUP_SCHED
488 struct list_head leaf_rt_rq_list;
489#endif
490
491 /*
492 * This is part of a global counter where only the total sum
493 * over all CPUs matters. A task can increase this counter on
494 * one CPU and if it got migrated afterwards it may decrease
495 * it on another CPU. Always updated under the runqueue lock:
496 */
497 unsigned long nr_uninterruptible;
498
499 struct task_struct *curr, *idle, *stop;
500 unsigned long next_balance;
501 struct mm_struct *prev_mm;
502
503 u64 clock;
504 u64 clock_task;
505
506 atomic_t nr_iowait;
507
508#ifdef CONFIG_SMP
509 struct root_domain *rd;
510 struct sched_domain *sd;
511
512 unsigned long cpu_power;
513
514 unsigned char idle_at_tick;
515 /* For active balancing */
516 int post_schedule;
517 int active_balance;
518 int push_cpu;
519 struct cpu_stop_work active_balance_work;
520 /* cpu of this runqueue: */
521 int cpu;
522 int online;
523
524 unsigned long avg_load_per_task;
525
526 u64 rt_avg;
527 u64 age_stamp;
528 u64 idle_stamp;
529 u64 avg_idle;
530#endif
531
532#ifdef CONFIG_IRQ_TIME_ACCOUNTING
533 u64 prev_irq_time;
534#endif
535#ifdef CONFIG_PARAVIRT
536 u64 prev_steal_time;
537#endif
538#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
539 u64 prev_steal_time_rq;
540#endif
541
542 /* calc_load related fields */
543 unsigned long calc_load_update;
544 long calc_load_active;
545
546#ifdef CONFIG_SCHED_HRTICK
547#ifdef CONFIG_SMP
548 int hrtick_csd_pending;
549 struct call_single_data hrtick_csd;
550#endif
551 struct hrtimer hrtick_timer;
552#endif
553
554#ifdef CONFIG_SCHEDSTATS
555 /* latency stats */
556 struct sched_info rq_sched_info;
557 unsigned long long rq_cpu_time;
558 /* could above be rq->cfs_rq.exec_clock + rq->rt_rq.rt_runtime ? */
559
560 /* sys_sched_yield() stats */
561 unsigned int yld_count;
562
563 /* schedule() stats */
564 unsigned int sched_switch;
565 unsigned int sched_count;
566 unsigned int sched_goidle;
567
568 /* try_to_wake_up() stats */
569 unsigned int ttwu_count;
570 unsigned int ttwu_local;
571#endif
572
573#ifdef CONFIG_SMP
574 struct task_struct *wake_list;
575#endif
576};
577
578static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
579
580
581static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags);
582
583static inline int cpu_of(struct rq *rq)
584{
585#ifdef CONFIG_SMP
586 return rq->cpu;
587#else
588 return 0;
589#endif
590}
591
592#define rcu_dereference_check_sched_domain(p) \
593 rcu_dereference_check((p), \
594 lockdep_is_held(&sched_domains_mutex))
595
596/*
597 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
598 * See detach_destroy_domains: synchronize_sched for details.
599 *
600 * The domain tree of any CPU may only be accessed from within
601 * preempt-disabled sections.
602 */
603#define for_each_domain(cpu, __sd) \
604 for (__sd = rcu_dereference_check_sched_domain(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
605
606#define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
607#define this_rq() (&__get_cpu_var(runqueues))
608#define task_rq(p) cpu_rq(task_cpu(p))
609#define cpu_curr(cpu) (cpu_rq(cpu)->curr)
610#define raw_rq() (&__raw_get_cpu_var(runqueues))
611
612#ifdef CONFIG_CGROUP_SCHED
613
614/*
615 * Return the group to which this tasks belongs.
616 *
617 * We use task_subsys_state_check() and extend the RCU verification with
618 * pi->lock and rq->lock because cpu_cgroup_attach() holds those locks for each
619 * task it moves into the cgroup. Therefore by holding either of those locks,
620 * we pin the task to the current cgroup.
621 */
622static inline struct task_group *task_group(struct task_struct *p)
623{
624 struct task_group *tg;
625 struct cgroup_subsys_state *css;
626
627 css = task_subsys_state_check(p, cpu_cgroup_subsys_id,
628 lockdep_is_held(&p->pi_lock) ||
629 lockdep_is_held(&task_rq(p)->lock));
630 tg = container_of(css, struct task_group, css);
631
632 return autogroup_task_group(p, tg);
633}
634
635/* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
636static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
637{
638#ifdef CONFIG_FAIR_GROUP_SCHED
639 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
640 p->se.parent = task_group(p)->se[cpu];
641#endif
642
643#ifdef CONFIG_RT_GROUP_SCHED
644 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
645 p->rt.parent = task_group(p)->rt_se[cpu];
646#endif
647}
648
649#else /* CONFIG_CGROUP_SCHED */
650
651static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
652static inline struct task_group *task_group(struct task_struct *p)
653{
654 return NULL;
655}
656
657#endif /* CONFIG_CGROUP_SCHED */
658
659static void update_rq_clock_task(struct rq *rq, s64 delta);
660
661static void update_rq_clock(struct rq *rq)
662{
663 s64 delta;
664
665 if (rq->skip_clock_update > 0)
666 return;
667
668 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
669 rq->clock += delta;
670 update_rq_clock_task(rq, delta);
671}
672
673/*
674 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
675 */
676#ifdef CONFIG_SCHED_DEBUG
677# define const_debug __read_mostly
678#else
679# define const_debug static const
680#endif
681
682/**
683 * runqueue_is_locked - Returns true if the current cpu runqueue is locked
684 * @cpu: the processor in question.
685 *
686 * This interface allows printk to be called with the runqueue lock
687 * held and know whether or not it is OK to wake up the klogd.
688 */
689int runqueue_is_locked(int cpu)
690{
691 return raw_spin_is_locked(&cpu_rq(cpu)->lock);
692}
693
694/*
695 * Debugging: various feature bits
696 */
697
698#define SCHED_FEAT(name, enabled) \
699 __SCHED_FEAT_##name ,
700
701enum {
702#include "sched_features.h"
703};
704
705#undef SCHED_FEAT
706
707#define SCHED_FEAT(name, enabled) \
708 (1UL << __SCHED_FEAT_##name) * enabled |
709
710const_debug unsigned int sysctl_sched_features =
711#include "sched_features.h"
712 0;
713
714#undef SCHED_FEAT
715
716#ifdef CONFIG_SCHED_DEBUG
717#define SCHED_FEAT(name, enabled) \
718 #name ,
719
720static __read_mostly char *sched_feat_names[] = {
721#include "sched_features.h"
722 NULL
723};
724
725#undef SCHED_FEAT
726
727static int sched_feat_show(struct seq_file *m, void *v)
728{
729 int i;
730
731 for (i = 0; sched_feat_names[i]; i++) {
732 if (!(sysctl_sched_features & (1UL << i)))
733 seq_puts(m, "NO_");
734 seq_printf(m, "%s ", sched_feat_names[i]);
735 }
736 seq_puts(m, "\n");
737
738 return 0;
739}
740
741static ssize_t
742sched_feat_write(struct file *filp, const char __user *ubuf,
743 size_t cnt, loff_t *ppos)
744{
745 char buf[64];
746 char *cmp;
747 int neg = 0;
748 int i;
749
750 if (cnt > 63)
751 cnt = 63;
752
753 if (copy_from_user(&buf, ubuf, cnt))
754 return -EFAULT;
755
756 buf[cnt] = 0;
757 cmp = strstrip(buf);
758
759 if (strncmp(cmp, "NO_", 3) == 0) {
760 neg = 1;
761 cmp += 3;
762 }
763
764 for (i = 0; sched_feat_names[i]; i++) {
765 if (strcmp(cmp, sched_feat_names[i]) == 0) {
766 if (neg)
767 sysctl_sched_features &= ~(1UL << i);
768 else
769 sysctl_sched_features |= (1UL << i);
770 break;
771 }
772 }
773
774 if (!sched_feat_names[i])
775 return -EINVAL;
776
777 *ppos += cnt;
778
779 return cnt;
780}
781
782static int sched_feat_open(struct inode *inode, struct file *filp)
783{
784 return single_open(filp, sched_feat_show, NULL);
785}
786
787static const struct file_operations sched_feat_fops = {
788 .open = sched_feat_open,
789 .write = sched_feat_write,
790 .read = seq_read,
791 .llseek = seq_lseek,
792 .release = single_release,
793};
794
795static __init int sched_init_debug(void)
796{
797 debugfs_create_file("sched_features", 0644, NULL, NULL,
798 &sched_feat_fops);
799
800 return 0;
801}
802late_initcall(sched_init_debug);
803
804#endif
805
806#define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
807
808/*
809 * Number of tasks to iterate in a single balance run.
810 * Limited because this is done with IRQs disabled.
811 */
812const_debug unsigned int sysctl_sched_nr_migrate = 32;
813
814/*
815 * period over which we average the RT time consumption, measured
816 * in ms.
817 *
818 * default: 1s
819 */
820const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
821
822/*
823 * period over which we measure -rt task cpu usage in us.
824 * default: 1s
825 */
826unsigned int sysctl_sched_rt_period = 1000000;
827
828static __read_mostly int scheduler_running;
829
830/*
831 * part of the period that we allow rt tasks to run in us.
832 * default: 0.95s
833 */
834int sysctl_sched_rt_runtime = 950000;
835
836static inline u64 global_rt_period(void)
837{
838 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
839}
840
841static inline u64 global_rt_runtime(void)
842{
843 if (sysctl_sched_rt_runtime < 0)
844 return RUNTIME_INF;
845
846 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
847}
848
849#ifndef prepare_arch_switch
850# define prepare_arch_switch(next) do { } while (0)
851#endif
852#ifndef finish_arch_switch
853# define finish_arch_switch(prev) do { } while (0)
854#endif
855
856static inline int task_current(struct rq *rq, struct task_struct *p)
857{
858 return rq->curr == p;
859}
860
861static inline int task_running(struct rq *rq, struct task_struct *p)
862{
863#ifdef CONFIG_SMP
864 return p->on_cpu;
865#else
866 return task_current(rq, p);
867#endif
868}
869
870#ifndef __ARCH_WANT_UNLOCKED_CTXSW
871static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
872{
873#ifdef CONFIG_SMP
874 /*
875 * We can optimise this out completely for !SMP, because the
876 * SMP rebalancing from interrupt is the only thing that cares
877 * here.
878 */
879 next->on_cpu = 1;
880#endif
881}
882
883static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
884{
885#ifdef CONFIG_SMP
886 /*
887 * After ->on_cpu is cleared, the task can be moved to a different CPU.
888 * We must ensure this doesn't happen until the switch is completely
889 * finished.
890 */
891 smp_wmb();
892 prev->on_cpu = 0;
893#endif
894#ifdef CONFIG_DEBUG_SPINLOCK
895 /* this is a valid case when another task releases the spinlock */
896 rq->lock.owner = current;
897#endif
898 /*
899 * If we are tracking spinlock dependencies then we have to
900 * fix up the runqueue lock - which gets 'carried over' from
901 * prev into current:
902 */
903 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
904
905 raw_spin_unlock_irq(&rq->lock);
906}
907
908#else /* __ARCH_WANT_UNLOCKED_CTXSW */
909static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
910{
911#ifdef CONFIG_SMP
912 /*
913 * We can optimise this out completely for !SMP, because the
914 * SMP rebalancing from interrupt is the only thing that cares
915 * here.
916 */
917 next->on_cpu = 1;
918#endif
919#ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
920 raw_spin_unlock_irq(&rq->lock);
921#else
922 raw_spin_unlock(&rq->lock);
923#endif
924}
925
926static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
927{
928#ifdef CONFIG_SMP
929 /*
930 * After ->on_cpu is cleared, the task can be moved to a different CPU.
931 * We must ensure this doesn't happen until the switch is completely
932 * finished.
933 */
934 smp_wmb();
935 prev->on_cpu = 0;
936#endif
937#ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
938 local_irq_enable();
939#endif
940}
941#endif /* __ARCH_WANT_UNLOCKED_CTXSW */
942
943/*
944 * __task_rq_lock - lock the rq @p resides on.
945 */
946static inline struct rq *__task_rq_lock(struct task_struct *p)
947 __acquires(rq->lock)
948{
949 struct rq *rq;
950
951 lockdep_assert_held(&p->pi_lock);
952
953 for (;;) {
954 rq = task_rq(p);
955 raw_spin_lock(&rq->lock);
956 if (likely(rq == task_rq(p)))
957 return rq;
958 raw_spin_unlock(&rq->lock);
959 }
960}
961
962/*
963 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
964 */
965static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
966 __acquires(p->pi_lock)
967 __acquires(rq->lock)
968{
969 struct rq *rq;
970
971 for (;;) {
972 raw_spin_lock_irqsave(&p->pi_lock, *flags);
973 rq = task_rq(p);
974 raw_spin_lock(&rq->lock);
975 if (likely(rq == task_rq(p)))
976 return rq;
977 raw_spin_unlock(&rq->lock);
978 raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
979 }
980}
981
982static void __task_rq_unlock(struct rq *rq)
983 __releases(rq->lock)
984{
985 raw_spin_unlock(&rq->lock);
986}
987
988static inline void
989task_rq_unlock(struct rq *rq, struct task_struct *p, unsigned long *flags)
990 __releases(rq->lock)
991 __releases(p->pi_lock)
992{
993 raw_spin_unlock(&rq->lock);
994 raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
995}
996
997/*
998 * this_rq_lock - lock this runqueue and disable interrupts.
999 */
1000static struct rq *this_rq_lock(void)
1001 __acquires(rq->lock)
1002{
1003 struct rq *rq;
1004
1005 local_irq_disable();
1006 rq = this_rq();
1007 raw_spin_lock(&rq->lock);
1008
1009 return rq;
1010}
1011
1012#ifdef CONFIG_SCHED_HRTICK
1013/*
1014 * Use HR-timers to deliver accurate preemption points.
1015 *
1016 * Its all a bit involved since we cannot program an hrt while holding the
1017 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1018 * reschedule event.
1019 *
1020 * When we get rescheduled we reprogram the hrtick_timer outside of the
1021 * rq->lock.
1022 */
1023
1024/*
1025 * Use hrtick when:
1026 * - enabled by features
1027 * - hrtimer is actually high res
1028 */
1029static inline int hrtick_enabled(struct rq *rq)
1030{
1031 if (!sched_feat(HRTICK))
1032 return 0;
1033 if (!cpu_active(cpu_of(rq)))
1034 return 0;
1035 return hrtimer_is_hres_active(&rq->hrtick_timer);
1036}
1037
1038static void hrtick_clear(struct rq *rq)
1039{
1040 if (hrtimer_active(&rq->hrtick_timer))
1041 hrtimer_cancel(&rq->hrtick_timer);
1042}
1043
1044/*
1045 * High-resolution timer tick.
1046 * Runs from hardirq context with interrupts disabled.
1047 */
1048static enum hrtimer_restart hrtick(struct hrtimer *timer)
1049{
1050 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1051
1052 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1053
1054 raw_spin_lock(&rq->lock);
1055 update_rq_clock(rq);
1056 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1057 raw_spin_unlock(&rq->lock);
1058
1059 return HRTIMER_NORESTART;
1060}
1061
1062#ifdef CONFIG_SMP
1063/*
1064 * called from hardirq (IPI) context
1065 */
1066static void __hrtick_start(void *arg)
1067{
1068 struct rq *rq = arg;
1069
1070 raw_spin_lock(&rq->lock);
1071 hrtimer_restart(&rq->hrtick_timer);
1072 rq->hrtick_csd_pending = 0;
1073 raw_spin_unlock(&rq->lock);
1074}
1075
1076/*
1077 * Called to set the hrtick timer state.
1078 *
1079 * called with rq->lock held and irqs disabled
1080 */
1081static void hrtick_start(struct rq *rq, u64 delay)
1082{
1083 struct hrtimer *timer = &rq->hrtick_timer;
1084 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
1085
1086 hrtimer_set_expires(timer, time);
1087
1088 if (rq == this_rq()) {
1089 hrtimer_restart(timer);
1090 } else if (!rq->hrtick_csd_pending) {
1091 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
1092 rq->hrtick_csd_pending = 1;
1093 }
1094}
1095
1096static int
1097hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1098{
1099 int cpu = (int)(long)hcpu;
1100
1101 switch (action) {
1102 case CPU_UP_CANCELED:
1103 case CPU_UP_CANCELED_FROZEN:
1104 case CPU_DOWN_PREPARE:
1105 case CPU_DOWN_PREPARE_FROZEN:
1106 case CPU_DEAD:
1107 case CPU_DEAD_FROZEN:
1108 hrtick_clear(cpu_rq(cpu));
1109 return NOTIFY_OK;
1110 }
1111
1112 return NOTIFY_DONE;
1113}
1114
1115static __init void init_hrtick(void)
1116{
1117 hotcpu_notifier(hotplug_hrtick, 0);
1118}
1119#else
1120/*
1121 * Called to set the hrtick timer state.
1122 *
1123 * called with rq->lock held and irqs disabled
1124 */
1125static void hrtick_start(struct rq *rq, u64 delay)
1126{
1127 __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
1128 HRTIMER_MODE_REL_PINNED, 0);
1129}
1130
1131static inline void init_hrtick(void)
1132{
1133}
1134#endif /* CONFIG_SMP */
1135
1136static void init_rq_hrtick(struct rq *rq)
1137{
1138#ifdef CONFIG_SMP
1139 rq->hrtick_csd_pending = 0;
1140
1141 rq->hrtick_csd.flags = 0;
1142 rq->hrtick_csd.func = __hrtick_start;
1143 rq->hrtick_csd.info = rq;
1144#endif
1145
1146 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1147 rq->hrtick_timer.function = hrtick;
1148}
1149#else /* CONFIG_SCHED_HRTICK */
1150static inline void hrtick_clear(struct rq *rq)
1151{
1152}
1153
1154static inline void init_rq_hrtick(struct rq *rq)
1155{
1156}
1157
1158static inline void init_hrtick(void)
1159{
1160}
1161#endif /* CONFIG_SCHED_HRTICK */
1162
1163/*
1164 * resched_task - mark a task 'to be rescheduled now'.
1165 *
1166 * On UP this means the setting of the need_resched flag, on SMP it
1167 * might also involve a cross-CPU call to trigger the scheduler on
1168 * the target CPU.
1169 */
1170#ifdef CONFIG_SMP
1171
1172#ifndef tsk_is_polling
1173#define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1174#endif
1175
1176static void resched_task(struct task_struct *p)
1177{
1178 int cpu;
1179
1180 assert_raw_spin_locked(&task_rq(p)->lock);
1181
1182 if (test_tsk_need_resched(p))
1183 return;
1184
1185 set_tsk_need_resched(p);
1186
1187 cpu = task_cpu(p);
1188 if (cpu == smp_processor_id())
1189 return;
1190
1191 /* NEED_RESCHED must be visible before we test polling */
1192 smp_mb();
1193 if (!tsk_is_polling(p))
1194 smp_send_reschedule(cpu);
1195}
1196
1197static void resched_cpu(int cpu)
1198{
1199 struct rq *rq = cpu_rq(cpu);
1200 unsigned long flags;
1201
1202 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
1203 return;
1204 resched_task(cpu_curr(cpu));
1205 raw_spin_unlock_irqrestore(&rq->lock, flags);
1206}
1207
1208#ifdef CONFIG_NO_HZ
1209/*
1210 * In the semi idle case, use the nearest busy cpu for migrating timers
1211 * from an idle cpu. This is good for power-savings.
1212 *
1213 * We don't do similar optimization for completely idle system, as
1214 * selecting an idle cpu will add more delays to the timers than intended
1215 * (as that cpu's timer base may not be uptodate wrt jiffies etc).
1216 */
1217int get_nohz_timer_target(void)
1218{
1219 int cpu = smp_processor_id();
1220 int i;
1221 struct sched_domain *sd;
1222
1223 rcu_read_lock();
1224 for_each_domain(cpu, sd) {
1225 for_each_cpu(i, sched_domain_span(sd)) {
1226 if (!idle_cpu(i)) {
1227 cpu = i;
1228 goto unlock;
1229 }
1230 }
1231 }
1232unlock:
1233 rcu_read_unlock();
1234 return cpu;
1235}
1236/*
1237 * When add_timer_on() enqueues a timer into the timer wheel of an
1238 * idle CPU then this timer might expire before the next timer event
1239 * which is scheduled to wake up that CPU. In case of a completely
1240 * idle system the next event might even be infinite time into the
1241 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1242 * leaves the inner idle loop so the newly added timer is taken into
1243 * account when the CPU goes back to idle and evaluates the timer
1244 * wheel for the next timer event.
1245 */
1246void wake_up_idle_cpu(int cpu)
1247{
1248 struct rq *rq = cpu_rq(cpu);
1249
1250 if (cpu == smp_processor_id())
1251 return;
1252
1253 /*
1254 * This is safe, as this function is called with the timer
1255 * wheel base lock of (cpu) held. When the CPU is on the way
1256 * to idle and has not yet set rq->curr to idle then it will
1257 * be serialized on the timer wheel base lock and take the new
1258 * timer into account automatically.
1259 */
1260 if (rq->curr != rq->idle)
1261 return;
1262
1263 /*
1264 * We can set TIF_RESCHED on the idle task of the other CPU
1265 * lockless. The worst case is that the other CPU runs the
1266 * idle task through an additional NOOP schedule()
1267 */
1268 set_tsk_need_resched(rq->idle);
1269
1270 /* NEED_RESCHED must be visible before we test polling */
1271 smp_mb();
1272 if (!tsk_is_polling(rq->idle))
1273 smp_send_reschedule(cpu);
1274}
1275
1276#endif /* CONFIG_NO_HZ */
1277
1278static u64 sched_avg_period(void)
1279{
1280 return (u64)sysctl_sched_time_avg * NSEC_PER_MSEC / 2;
1281}
1282
1283static void sched_avg_update(struct rq *rq)
1284{
1285 s64 period = sched_avg_period();
1286
1287 while ((s64)(rq->clock - rq->age_stamp) > period) {
1288 /*
1289 * Inline assembly required to prevent the compiler
1290 * optimising this loop into a divmod call.
1291 * See __iter_div_u64_rem() for another example of this.
1292 */
1293 asm("" : "+rm" (rq->age_stamp));
1294 rq->age_stamp += period;
1295 rq->rt_avg /= 2;
1296 }
1297}
1298
1299static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1300{
1301 rq->rt_avg += rt_delta;
1302 sched_avg_update(rq);
1303}
1304
1305#else /* !CONFIG_SMP */
1306static void resched_task(struct task_struct *p)
1307{
1308 assert_raw_spin_locked(&task_rq(p)->lock);
1309 set_tsk_need_resched(p);
1310}
1311
1312static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1313{
1314}
1315
1316static void sched_avg_update(struct rq *rq)
1317{
1318}
1319#endif /* CONFIG_SMP */
1320
1321#if BITS_PER_LONG == 32
1322# define WMULT_CONST (~0UL)
1323#else
1324# define WMULT_CONST (1UL << 32)
1325#endif
1326
1327#define WMULT_SHIFT 32
1328
1329/*
1330 * Shift right and round:
1331 */
1332#define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1333
1334/*
1335 * delta *= weight / lw
1336 */
1337static unsigned long
1338calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1339 struct load_weight *lw)
1340{
1341 u64 tmp;
1342
1343 /*
1344 * weight can be less than 2^SCHED_LOAD_RESOLUTION for task group sched
1345 * entities since MIN_SHARES = 2. Treat weight as 1 if less than
1346 * 2^SCHED_LOAD_RESOLUTION.
1347 */
1348 if (likely(weight > (1UL << SCHED_LOAD_RESOLUTION)))
1349 tmp = (u64)delta_exec * scale_load_down(weight);
1350 else
1351 tmp = (u64)delta_exec;
1352
1353 if (!lw->inv_weight) {
1354 unsigned long w = scale_load_down(lw->weight);
1355
1356 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
1357 lw->inv_weight = 1;
1358 else if (unlikely(!w))
1359 lw->inv_weight = WMULT_CONST;
1360 else
1361 lw->inv_weight = WMULT_CONST / w;
1362 }
1363
1364 /*
1365 * Check whether we'd overflow the 64-bit multiplication:
1366 */
1367 if (unlikely(tmp > WMULT_CONST))
1368 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1369 WMULT_SHIFT/2);
1370 else
1371 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1372
1373 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1374}
1375
1376static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1377{
1378 lw->weight += inc;
1379 lw->inv_weight = 0;
1380}
1381
1382static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1383{
1384 lw->weight -= dec;
1385 lw->inv_weight = 0;
1386}
1387
1388static inline void update_load_set(struct load_weight *lw, unsigned long w)
1389{
1390 lw->weight = w;
1391 lw->inv_weight = 0;
1392}
1393
1394/*
1395 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1396 * of tasks with abnormal "nice" values across CPUs the contribution that
1397 * each task makes to its run queue's load is weighted according to its
1398 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1399 * scaled version of the new time slice allocation that they receive on time
1400 * slice expiry etc.
1401 */
1402
1403#define WEIGHT_IDLEPRIO 3
1404#define WMULT_IDLEPRIO 1431655765
1405
1406/*
1407 * Nice levels are multiplicative, with a gentle 10% change for every
1408 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1409 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1410 * that remained on nice 0.
1411 *
1412 * The "10% effect" is relative and cumulative: from _any_ nice level,
1413 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1414 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1415 * If a task goes up by ~10% and another task goes down by ~10% then
1416 * the relative distance between them is ~25%.)
1417 */
1418static const int prio_to_weight[40] = {
1419 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1420 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1421 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1422 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1423 /* 0 */ 1024, 820, 655, 526, 423,
1424 /* 5 */ 335, 272, 215, 172, 137,
1425 /* 10 */ 110, 87, 70, 56, 45,
1426 /* 15 */ 36, 29, 23, 18, 15,
1427};
1428
1429/*
1430 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1431 *
1432 * In cases where the weight does not change often, we can use the
1433 * precalculated inverse to speed up arithmetics by turning divisions
1434 * into multiplications:
1435 */
1436static const u32 prio_to_wmult[40] = {
1437 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1438 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1439 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1440 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1441 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1442 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1443 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1444 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1445};
1446
1447/* Time spent by the tasks of the cpu accounting group executing in ... */
1448enum cpuacct_stat_index {
1449 CPUACCT_STAT_USER, /* ... user mode */
1450 CPUACCT_STAT_SYSTEM, /* ... kernel mode */
1451
1452 CPUACCT_STAT_NSTATS,
1453};
1454
1455#ifdef CONFIG_CGROUP_CPUACCT
1456static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1457static void cpuacct_update_stats(struct task_struct *tsk,
1458 enum cpuacct_stat_index idx, cputime_t val);
1459#else
1460static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1461static inline void cpuacct_update_stats(struct task_struct *tsk,
1462 enum cpuacct_stat_index idx, cputime_t val) {}
1463#endif
1464
1465static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1466{
1467 update_load_add(&rq->load, load);
1468}
1469
1470static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1471{
1472 update_load_sub(&rq->load, load);
1473}
1474
1475#if (defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)) || defined(CONFIG_RT_GROUP_SCHED)
1476typedef int (*tg_visitor)(struct task_group *, void *);
1477
1478/*
1479 * Iterate the full tree, calling @down when first entering a node and @up when
1480 * leaving it for the final time.
1481 */
1482static int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
1483{
1484 struct task_group *parent, *child;
1485 int ret;
1486
1487 rcu_read_lock();
1488 parent = &root_task_group;
1489down:
1490 ret = (*down)(parent, data);
1491 if (ret)
1492 goto out_unlock;
1493 list_for_each_entry_rcu(child, &parent->children, siblings) {
1494 parent = child;
1495 goto down;
1496
1497up:
1498 continue;
1499 }
1500 ret = (*up)(parent, data);
1501 if (ret)
1502 goto out_unlock;
1503
1504 child = parent;
1505 parent = parent->parent;
1506 if (parent)
1507 goto up;
1508out_unlock:
1509 rcu_read_unlock();
1510
1511 return ret;
1512}
1513
1514static int tg_nop(struct task_group *tg, void *data)
1515{
1516 return 0;
1517}
1518#endif
1519
1520#ifdef CONFIG_SMP
1521/* Used instead of source_load when we know the type == 0 */
1522static unsigned long weighted_cpuload(const int cpu)
1523{
1524 return cpu_rq(cpu)->load.weight;
1525}
1526
1527/*
1528 * Return a low guess at the load of a migration-source cpu weighted
1529 * according to the scheduling class and "nice" value.
1530 *
1531 * We want to under-estimate the load of migration sources, to
1532 * balance conservatively.
1533 */
1534static unsigned long source_load(int cpu, int type)
1535{
1536 struct rq *rq = cpu_rq(cpu);
1537 unsigned long total = weighted_cpuload(cpu);
1538
1539 if (type == 0 || !sched_feat(LB_BIAS))
1540 return total;
1541
1542 return min(rq->cpu_load[type-1], total);
1543}
1544
1545/*
1546 * Return a high guess at the load of a migration-target cpu weighted
1547 * according to the scheduling class and "nice" value.
1548 */
1549static unsigned long target_load(int cpu, int type)
1550{
1551 struct rq *rq = cpu_rq(cpu);
1552 unsigned long total = weighted_cpuload(cpu);
1553
1554 if (type == 0 || !sched_feat(LB_BIAS))
1555 return total;
1556
1557 return max(rq->cpu_load[type-1], total);
1558}
1559
1560static unsigned long power_of(int cpu)
1561{
1562 return cpu_rq(cpu)->cpu_power;
1563}
1564
1565static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1566
1567static unsigned long cpu_avg_load_per_task(int cpu)
1568{
1569 struct rq *rq = cpu_rq(cpu);
1570 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
1571
1572 if (nr_running)
1573 rq->avg_load_per_task = rq->load.weight / nr_running;
1574 else
1575 rq->avg_load_per_task = 0;
1576
1577 return rq->avg_load_per_task;
1578}
1579
1580#ifdef CONFIG_PREEMPT
1581
1582static void double_rq_lock(struct rq *rq1, struct rq *rq2);
1583
1584/*
1585 * fair double_lock_balance: Safely acquires both rq->locks in a fair
1586 * way at the expense of forcing extra atomic operations in all
1587 * invocations. This assures that the double_lock is acquired using the
1588 * same underlying policy as the spinlock_t on this architecture, which
1589 * reduces latency compared to the unfair variant below. However, it
1590 * also adds more overhead and therefore may reduce throughput.
1591 */
1592static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1593 __releases(this_rq->lock)
1594 __acquires(busiest->lock)
1595 __acquires(this_rq->lock)
1596{
1597 raw_spin_unlock(&this_rq->lock);
1598 double_rq_lock(this_rq, busiest);
1599
1600 return 1;
1601}
1602
1603#else
1604/*
1605 * Unfair double_lock_balance: Optimizes throughput at the expense of
1606 * latency by eliminating extra atomic operations when the locks are
1607 * already in proper order on entry. This favors lower cpu-ids and will
1608 * grant the double lock to lower cpus over higher ids under contention,
1609 * regardless of entry order into the function.
1610 */
1611static int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1612 __releases(this_rq->lock)
1613 __acquires(busiest->lock)
1614 __acquires(this_rq->lock)
1615{
1616 int ret = 0;
1617
1618 if (unlikely(!raw_spin_trylock(&busiest->lock))) {
1619 if (busiest < this_rq) {
1620 raw_spin_unlock(&this_rq->lock);
1621 raw_spin_lock(&busiest->lock);
1622 raw_spin_lock_nested(&this_rq->lock,
1623 SINGLE_DEPTH_NESTING);
1624 ret = 1;
1625 } else
1626 raw_spin_lock_nested(&busiest->lock,
1627 SINGLE_DEPTH_NESTING);
1628 }
1629 return ret;
1630}
1631
1632#endif /* CONFIG_PREEMPT */
1633
1634/*
1635 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1636 */
1637static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
1638{
1639 if (unlikely(!irqs_disabled())) {
1640 /* printk() doesn't work good under rq->lock */
1641 raw_spin_unlock(&this_rq->lock);
1642 BUG_ON(1);
1643 }
1644
1645 return _double_lock_balance(this_rq, busiest);
1646}
1647
1648static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
1649 __releases(busiest->lock)
1650{
1651 raw_spin_unlock(&busiest->lock);
1652 lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_);
1653}
1654
1655/*
1656 * double_rq_lock - safely lock two runqueues
1657 *
1658 * Note this does not disable interrupts like task_rq_lock,
1659 * you need to do so manually before calling.
1660 */
1661static void double_rq_lock(struct rq *rq1, struct rq *rq2)
1662 __acquires(rq1->lock)
1663 __acquires(rq2->lock)
1664{
1665 BUG_ON(!irqs_disabled());
1666 if (rq1 == rq2) {
1667 raw_spin_lock(&rq1->lock);
1668 __acquire(rq2->lock); /* Fake it out ;) */
1669 } else {
1670 if (rq1 < rq2) {
1671 raw_spin_lock(&rq1->lock);
1672 raw_spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING);
1673 } else {
1674 raw_spin_lock(&rq2->lock);
1675 raw_spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING);
1676 }
1677 }
1678}
1679
1680/*
1681 * double_rq_unlock - safely unlock two runqueues
1682 *
1683 * Note this does not restore interrupts like task_rq_unlock,
1684 * you need to do so manually after calling.
1685 */
1686static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
1687 __releases(rq1->lock)
1688 __releases(rq2->lock)
1689{
1690 raw_spin_unlock(&rq1->lock);
1691 if (rq1 != rq2)
1692 raw_spin_unlock(&rq2->lock);
1693 else
1694 __release(rq2->lock);
1695}
1696
1697#else /* CONFIG_SMP */
1698
1699/*
1700 * double_rq_lock - safely lock two runqueues
1701 *
1702 * Note this does not disable interrupts like task_rq_lock,
1703 * you need to do so manually before calling.
1704 */
1705static void double_rq_lock(struct rq *rq1, struct rq *rq2)
1706 __acquires(rq1->lock)
1707 __acquires(rq2->lock)
1708{
1709 BUG_ON(!irqs_disabled());
1710 BUG_ON(rq1 != rq2);
1711 raw_spin_lock(&rq1->lock);
1712 __acquire(rq2->lock); /* Fake it out ;) */
1713}
1714
1715/*
1716 * double_rq_unlock - safely unlock two runqueues
1717 *
1718 * Note this does not restore interrupts like task_rq_unlock,
1719 * you need to do so manually after calling.
1720 */
1721static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
1722 __releases(rq1->lock)
1723 __releases(rq2->lock)
1724{
1725 BUG_ON(rq1 != rq2);
1726 raw_spin_unlock(&rq1->lock);
1727 __release(rq2->lock);
1728}
1729
1730#endif
1731
1732static void calc_load_account_idle(struct rq *this_rq);
1733static void update_sysctl(void);
1734static int get_update_sysctl_factor(void);
1735static void update_cpu_load(struct rq *this_rq);
1736
1737static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1738{
1739 set_task_rq(p, cpu);
1740#ifdef CONFIG_SMP
1741 /*
1742 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1743 * successfuly executed on another CPU. We must ensure that updates of
1744 * per-task data have been completed by this moment.
1745 */
1746 smp_wmb();
1747 task_thread_info(p)->cpu = cpu;
1748#endif
1749}
1750
1751static const struct sched_class rt_sched_class;
1752
1753#define sched_class_highest (&stop_sched_class)
1754#define for_each_class(class) \
1755 for (class = sched_class_highest; class; class = class->next)
1756
1757#include "sched_stats.h"
1758
1759static void inc_nr_running(struct rq *rq)
1760{
1761 rq->nr_running++;
1762}
1763
1764static void dec_nr_running(struct rq *rq)
1765{
1766 rq->nr_running--;
1767}
1768
1769static void set_load_weight(struct task_struct *p)
1770{
1771 int prio = p->static_prio - MAX_RT_PRIO;
1772 struct load_weight *load = &p->se.load;
1773
1774 /*
1775 * SCHED_IDLE tasks get minimal weight:
1776 */
1777 if (p->policy == SCHED_IDLE) {
1778 load->weight = scale_load(WEIGHT_IDLEPRIO);
1779 load->inv_weight = WMULT_IDLEPRIO;
1780 return;
1781 }
1782
1783 load->weight = scale_load(prio_to_weight[prio]);
1784 load->inv_weight = prio_to_wmult[prio];
1785}
1786
1787static void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
1788{
1789 update_rq_clock(rq);
1790 sched_info_queued(p);
1791 p->sched_class->enqueue_task(rq, p, flags);
1792}
1793
1794static void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
1795{
1796 update_rq_clock(rq);
1797 sched_info_dequeued(p);
1798 p->sched_class->dequeue_task(rq, p, flags);
1799}
1800
1801/*
1802 * activate_task - move a task to the runqueue.
1803 */
1804static void activate_task(struct rq *rq, struct task_struct *p, int flags)
1805{
1806 if (task_contributes_to_load(p))
1807 rq->nr_uninterruptible--;
1808
1809 enqueue_task(rq, p, flags);
1810 inc_nr_running(rq);
1811}
1812
1813/*
1814 * deactivate_task - remove a task from the runqueue.
1815 */
1816static void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
1817{
1818 if (task_contributes_to_load(p))
1819 rq->nr_uninterruptible++;
1820
1821 dequeue_task(rq, p, flags);
1822 dec_nr_running(rq);
1823}
1824
1825#ifdef CONFIG_IRQ_TIME_ACCOUNTING
1826
1827/*
1828 * There are no locks covering percpu hardirq/softirq time.
1829 * They are only modified in account_system_vtime, on corresponding CPU
1830 * with interrupts disabled. So, writes are safe.
1831 * They are read and saved off onto struct rq in update_rq_clock().
1832 * This may result in other CPU reading this CPU's irq time and can
1833 * race with irq/account_system_vtime on this CPU. We would either get old
1834 * or new value with a side effect of accounting a slice of irq time to wrong
1835 * task when irq is in progress while we read rq->clock. That is a worthy
1836 * compromise in place of having locks on each irq in account_system_time.
1837 */
1838static DEFINE_PER_CPU(u64, cpu_hardirq_time);
1839static DEFINE_PER_CPU(u64, cpu_softirq_time);
1840
1841static DEFINE_PER_CPU(u64, irq_start_time);
1842static int sched_clock_irqtime;
1843
1844void enable_sched_clock_irqtime(void)
1845{
1846 sched_clock_irqtime = 1;
1847}
1848
1849void disable_sched_clock_irqtime(void)
1850{
1851 sched_clock_irqtime = 0;
1852}
1853
1854#ifndef CONFIG_64BIT
1855static DEFINE_PER_CPU(seqcount_t, irq_time_seq);
1856
1857static inline void irq_time_write_begin(void)
1858{
1859 __this_cpu_inc(irq_time_seq.sequence);
1860 smp_wmb();
1861}
1862
1863static inline void irq_time_write_end(void)
1864{
1865 smp_wmb();
1866 __this_cpu_inc(irq_time_seq.sequence);
1867}
1868
1869static inline u64 irq_time_read(int cpu)
1870{
1871 u64 irq_time;
1872 unsigned seq;
1873
1874 do {
1875 seq = read_seqcount_begin(&per_cpu(irq_time_seq, cpu));
1876 irq_time = per_cpu(cpu_softirq_time, cpu) +
1877 per_cpu(cpu_hardirq_time, cpu);
1878 } while (read_seqcount_retry(&per_cpu(irq_time_seq, cpu), seq));
1879
1880 return irq_time;
1881}
1882#else /* CONFIG_64BIT */
1883static inline void irq_time_write_begin(void)
1884{
1885}
1886
1887static inline void irq_time_write_end(void)
1888{
1889}
1890
1891static inline u64 irq_time_read(int cpu)
1892{
1893 return per_cpu(cpu_softirq_time, cpu) + per_cpu(cpu_hardirq_time, cpu);
1894}
1895#endif /* CONFIG_64BIT */
1896
1897/*
1898 * Called before incrementing preempt_count on {soft,}irq_enter
1899 * and before decrementing preempt_count on {soft,}irq_exit.
1900 */
1901void account_system_vtime(struct task_struct *curr)
1902{
1903 unsigned long flags;
1904 s64 delta;
1905 int cpu;
1906
1907 if (!sched_clock_irqtime)
1908 return;
1909
1910 local_irq_save(flags);
1911
1912 cpu = smp_processor_id();
1913 delta = sched_clock_cpu(cpu) - __this_cpu_read(irq_start_time);
1914 __this_cpu_add(irq_start_time, delta);
1915
1916 irq_time_write_begin();
1917 /*
1918 * We do not account for softirq time from ksoftirqd here.
1919 * We want to continue accounting softirq time to ksoftirqd thread
1920 * in that case, so as not to confuse scheduler with a special task
1921 * that do not consume any time, but still wants to run.
1922 */
1923 if (hardirq_count())
1924 __this_cpu_add(cpu_hardirq_time, delta);
1925 else if (in_serving_softirq() && curr != this_cpu_ksoftirqd())
1926 __this_cpu_add(cpu_softirq_time, delta);
1927
1928 irq_time_write_end();
1929 local_irq_restore(flags);
1930}
1931EXPORT_SYMBOL_GPL(account_system_vtime);
1932
1933#endif /* CONFIG_IRQ_TIME_ACCOUNTING */
1934
1935#ifdef CONFIG_PARAVIRT
1936static inline u64 steal_ticks(u64 steal)
1937{
1938 if (unlikely(steal > NSEC_PER_SEC))
1939 return div_u64(steal, TICK_NSEC);
1940
1941 return __iter_div_u64_rem(steal, TICK_NSEC, &steal);
1942}
1943#endif
1944
1945static void update_rq_clock_task(struct rq *rq, s64 delta)
1946{
1947/*
1948 * In theory, the compile should just see 0 here, and optimize out the call
1949 * to sched_rt_avg_update. But I don't trust it...
1950 */
1951#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
1952 s64 steal = 0, irq_delta = 0;
1953#endif
1954#ifdef CONFIG_IRQ_TIME_ACCOUNTING
1955 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
1956
1957 /*
1958 * Since irq_time is only updated on {soft,}irq_exit, we might run into
1959 * this case when a previous update_rq_clock() happened inside a
1960 * {soft,}irq region.
1961 *
1962 * When this happens, we stop ->clock_task and only update the
1963 * prev_irq_time stamp to account for the part that fit, so that a next
1964 * update will consume the rest. This ensures ->clock_task is
1965 * monotonic.
1966 *
1967 * It does however cause some slight miss-attribution of {soft,}irq
1968 * time, a more accurate solution would be to update the irq_time using
1969 * the current rq->clock timestamp, except that would require using
1970 * atomic ops.
1971 */
1972 if (irq_delta > delta)
1973 irq_delta = delta;
1974
1975 rq->prev_irq_time += irq_delta;
1976 delta -= irq_delta;
1977#endif
1978#ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
1979 if (static_branch((&paravirt_steal_rq_enabled))) {
1980 u64 st;
1981
1982 steal = paravirt_steal_clock(cpu_of(rq));
1983 steal -= rq->prev_steal_time_rq;
1984
1985 if (unlikely(steal > delta))
1986 steal = delta;
1987
1988 st = steal_ticks(steal);
1989 steal = st * TICK_NSEC;
1990
1991 rq->prev_steal_time_rq += steal;
1992
1993 delta -= steal;
1994 }
1995#endif
1996
1997 rq->clock_task += delta;
1998
1999#if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
2000 if ((irq_delta + steal) && sched_feat(NONTASK_POWER))
2001 sched_rt_avg_update(rq, irq_delta + steal);
2002#endif
2003}
2004
2005#ifdef CONFIG_IRQ_TIME_ACCOUNTING
2006static int irqtime_account_hi_update(void)
2007{
2008 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2009 unsigned long flags;
2010 u64 latest_ns;
2011 int ret = 0;
2012
2013 local_irq_save(flags);
2014 latest_ns = this_cpu_read(cpu_hardirq_time);
2015 if (cputime64_gt(nsecs_to_cputime64(latest_ns), cpustat->irq))
2016 ret = 1;
2017 local_irq_restore(flags);
2018 return ret;
2019}
2020
2021static int irqtime_account_si_update(void)
2022{
2023 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2024 unsigned long flags;
2025 u64 latest_ns;
2026 int ret = 0;
2027
2028 local_irq_save(flags);
2029 latest_ns = this_cpu_read(cpu_softirq_time);
2030 if (cputime64_gt(nsecs_to_cputime64(latest_ns), cpustat->softirq))
2031 ret = 1;
2032 local_irq_restore(flags);
2033 return ret;
2034}
2035
2036#else /* CONFIG_IRQ_TIME_ACCOUNTING */
2037
2038#define sched_clock_irqtime (0)
2039
2040#endif
2041
2042#include "sched_idletask.c"
2043#include "sched_fair.c"
2044#include "sched_rt.c"
2045#include "sched_autogroup.c"
2046#include "sched_stoptask.c"
2047#ifdef CONFIG_SCHED_DEBUG
2048# include "sched_debug.c"
2049#endif
2050
2051void sched_set_stop_task(int cpu, struct task_struct *stop)
2052{
2053 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
2054 struct task_struct *old_stop = cpu_rq(cpu)->stop;
2055
2056 if (stop) {
2057 /*
2058 * Make it appear like a SCHED_FIFO task, its something
2059 * userspace knows about and won't get confused about.
2060 *
2061 * Also, it will make PI more or less work without too
2062 * much confusion -- but then, stop work should not
2063 * rely on PI working anyway.
2064 */
2065 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
2066
2067 stop->sched_class = &stop_sched_class;
2068 }
2069
2070 cpu_rq(cpu)->stop = stop;
2071
2072 if (old_stop) {
2073 /*
2074 * Reset it back to a normal scheduling class so that
2075 * it can die in pieces.
2076 */
2077 old_stop->sched_class = &rt_sched_class;
2078 }
2079}
2080
2081/*
2082 * __normal_prio - return the priority that is based on the static prio
2083 */
2084static inline int __normal_prio(struct task_struct *p)
2085{
2086 return p->static_prio;
2087}
2088
2089/*
2090 * Calculate the expected normal priority: i.e. priority
2091 * without taking RT-inheritance into account. Might be
2092 * boosted by interactivity modifiers. Changes upon fork,
2093 * setprio syscalls, and whenever the interactivity
2094 * estimator recalculates.
2095 */
2096static inline int normal_prio(struct task_struct *p)
2097{
2098 int prio;
2099
2100 if (task_has_rt_policy(p))
2101 prio = MAX_RT_PRIO-1 - p->rt_priority;
2102 else
2103 prio = __normal_prio(p);
2104 return prio;
2105}
2106
2107/*
2108 * Calculate the current priority, i.e. the priority
2109 * taken into account by the scheduler. This value might
2110 * be boosted by RT tasks, or might be boosted by
2111 * interactivity modifiers. Will be RT if the task got
2112 * RT-boosted. If not then it returns p->normal_prio.
2113 */
2114static int effective_prio(struct task_struct *p)
2115{
2116 p->normal_prio = normal_prio(p);
2117 /*
2118 * If we are RT tasks or we were boosted to RT priority,
2119 * keep the priority unchanged. Otherwise, update priority
2120 * to the normal priority:
2121 */
2122 if (!rt_prio(p->prio))
2123 return p->normal_prio;
2124 return p->prio;
2125}
2126
2127/**
2128 * task_curr - is this task currently executing on a CPU?
2129 * @p: the task in question.
2130 */
2131inline int task_curr(const struct task_struct *p)
2132{
2133 return cpu_curr(task_cpu(p)) == p;
2134}
2135
2136static inline void check_class_changed(struct rq *rq, struct task_struct *p,
2137 const struct sched_class *prev_class,
2138 int oldprio)
2139{
2140 if (prev_class != p->sched_class) {
2141 if (prev_class->switched_from)
2142 prev_class->switched_from(rq, p);
2143 p->sched_class->switched_to(rq, p);
2144 } else if (oldprio != p->prio)
2145 p->sched_class->prio_changed(rq, p, oldprio);
2146}
2147
2148static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
2149{
2150 const struct sched_class *class;
2151
2152 if (p->sched_class == rq->curr->sched_class) {
2153 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
2154 } else {
2155 for_each_class(class) {
2156 if (class == rq->curr->sched_class)
2157 break;
2158 if (class == p->sched_class) {
2159 resched_task(rq->curr);
2160 break;
2161 }
2162 }
2163 }
2164
2165 /*
2166 * A queue event has occurred, and we're going to schedule. In
2167 * this case, we can save a useless back to back clock update.
2168 */
2169 if (rq->curr->on_rq && test_tsk_need_resched(rq->curr))
2170 rq->skip_clock_update = 1;
2171}
2172
2173#ifdef CONFIG_SMP
2174/*
2175 * Is this task likely cache-hot:
2176 */
2177static int
2178task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2179{
2180 s64 delta;
2181
2182 if (p->sched_class != &fair_sched_class)
2183 return 0;
2184
2185 if (unlikely(p->policy == SCHED_IDLE))
2186 return 0;
2187
2188 /*
2189 * Buddy candidates are cache hot:
2190 */
2191 if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
2192 (&p->se == cfs_rq_of(&p->se)->next ||
2193 &p->se == cfs_rq_of(&p->se)->last))
2194 return 1;
2195
2196 if (sysctl_sched_migration_cost == -1)
2197 return 1;
2198 if (sysctl_sched_migration_cost == 0)
2199 return 0;
2200
2201 delta = now - p->se.exec_start;
2202
2203 return delta < (s64)sysctl_sched_migration_cost;
2204}
2205
2206void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2207{
2208#ifdef CONFIG_SCHED_DEBUG
2209 /*
2210 * We should never call set_task_cpu() on a blocked task,
2211 * ttwu() will sort out the placement.
2212 */
2213 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
2214 !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE));
2215
2216#ifdef CONFIG_LOCKDEP
2217 /*
2218 * The caller should hold either p->pi_lock or rq->lock, when changing
2219 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
2220 *
2221 * sched_move_task() holds both and thus holding either pins the cgroup,
2222 * see set_task_rq().
2223 *
2224 * Furthermore, all task_rq users should acquire both locks, see
2225 * task_rq_lock().
2226 */
2227 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
2228 lockdep_is_held(&task_rq(p)->lock)));
2229#endif
2230#endif
2231
2232 trace_sched_migrate_task(p, new_cpu);
2233
2234 if (task_cpu(p) != new_cpu) {
2235 p->se.nr_migrations++;
2236 perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, NULL, 0);
2237 }
2238
2239 __set_task_cpu(p, new_cpu);
2240}
2241
2242struct migration_arg {
2243 struct task_struct *task;
2244 int dest_cpu;
2245};
2246
2247static int migration_cpu_stop(void *data);
2248
2249/*
2250 * wait_task_inactive - wait for a thread to unschedule.
2251 *
2252 * If @match_state is nonzero, it's the @p->state value just checked and
2253 * not expected to change. If it changes, i.e. @p might have woken up,
2254 * then return zero. When we succeed in waiting for @p to be off its CPU,
2255 * we return a positive number (its total switch count). If a second call
2256 * a short while later returns the same number, the caller can be sure that
2257 * @p has remained unscheduled the whole time.
2258 *
2259 * The caller must ensure that the task *will* unschedule sometime soon,
2260 * else this function might spin for a *long* time. This function can't
2261 * be called with interrupts off, or it may introduce deadlock with
2262 * smp_call_function() if an IPI is sent by the same process we are
2263 * waiting to become inactive.
2264 */
2265unsigned long wait_task_inactive(struct task_struct *p, long match_state)
2266{
2267 unsigned long flags;
2268 int running, on_rq;
2269 unsigned long ncsw;
2270 struct rq *rq;
2271
2272 for (;;) {
2273 /*
2274 * We do the initial early heuristics without holding
2275 * any task-queue locks at all. We'll only try to get
2276 * the runqueue lock when things look like they will
2277 * work out!
2278 */
2279 rq = task_rq(p);
2280
2281 /*
2282 * If the task is actively running on another CPU
2283 * still, just relax and busy-wait without holding
2284 * any locks.
2285 *
2286 * NOTE! Since we don't hold any locks, it's not
2287 * even sure that "rq" stays as the right runqueue!
2288 * But we don't care, since "task_running()" will
2289 * return false if the runqueue has changed and p
2290 * is actually now running somewhere else!
2291 */
2292 while (task_running(rq, p)) {
2293 if (match_state && unlikely(p->state != match_state))
2294 return 0;
2295 cpu_relax();
2296 }
2297
2298 /*
2299 * Ok, time to look more closely! We need the rq
2300 * lock now, to be *sure*. If we're wrong, we'll
2301 * just go back and repeat.
2302 */
2303 rq = task_rq_lock(p, &flags);
2304 trace_sched_wait_task(p);
2305 running = task_running(rq, p);
2306 on_rq = p->on_rq;
2307 ncsw = 0;
2308 if (!match_state || p->state == match_state)
2309 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2310 task_rq_unlock(rq, p, &flags);
2311
2312 /*
2313 * If it changed from the expected state, bail out now.
2314 */
2315 if (unlikely(!ncsw))
2316 break;
2317
2318 /*
2319 * Was it really running after all now that we
2320 * checked with the proper locks actually held?
2321 *
2322 * Oops. Go back and try again..
2323 */
2324 if (unlikely(running)) {
2325 cpu_relax();
2326 continue;
2327 }
2328
2329 /*
2330 * It's not enough that it's not actively running,
2331 * it must be off the runqueue _entirely_, and not
2332 * preempted!
2333 *
2334 * So if it was still runnable (but just not actively
2335 * running right now), it's preempted, and we should
2336 * yield - it could be a while.
2337 */
2338 if (unlikely(on_rq)) {
2339 ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
2340
2341 set_current_state(TASK_UNINTERRUPTIBLE);
2342 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
2343 continue;
2344 }
2345
2346 /*
2347 * Ahh, all good. It wasn't running, and it wasn't
2348 * runnable, which means that it will never become
2349 * running in the future either. We're all done!
2350 */
2351 break;
2352 }
2353
2354 return ncsw;
2355}
2356
2357/***
2358 * kick_process - kick a running thread to enter/exit the kernel
2359 * @p: the to-be-kicked thread
2360 *
2361 * Cause a process which is running on another CPU to enter
2362 * kernel-mode, without any delay. (to get signals handled.)
2363 *
2364 * NOTE: this function doesn't have to take the runqueue lock,
2365 * because all it wants to ensure is that the remote task enters
2366 * the kernel. If the IPI races and the task has been migrated
2367 * to another CPU then no harm is done and the purpose has been
2368 * achieved as well.
2369 */
2370void kick_process(struct task_struct *p)
2371{
2372 int cpu;
2373
2374 preempt_disable();
2375 cpu = task_cpu(p);
2376 if ((cpu != smp_processor_id()) && task_curr(p))
2377 smp_send_reschedule(cpu);
2378 preempt_enable();
2379}
2380EXPORT_SYMBOL_GPL(kick_process);
2381#endif /* CONFIG_SMP */
2382
2383#ifdef CONFIG_SMP
2384/*
2385 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
2386 */
2387static int select_fallback_rq(int cpu, struct task_struct *p)
2388{
2389 int dest_cpu;
2390 const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(cpu));
2391
2392 /* Look for allowed, online CPU in same node. */
2393 for_each_cpu_and(dest_cpu, nodemask, cpu_active_mask)
2394 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
2395 return dest_cpu;
2396
2397 /* Any allowed, online CPU? */
2398 dest_cpu = cpumask_any_and(&p->cpus_allowed, cpu_active_mask);
2399 if (dest_cpu < nr_cpu_ids)
2400 return dest_cpu;
2401
2402 /* No more Mr. Nice Guy. */
2403 dest_cpu = cpuset_cpus_allowed_fallback(p);
2404 /*
2405 * Don't tell them about moving exiting tasks or
2406 * kernel threads (both mm NULL), since they never
2407 * leave kernel.
2408 */
2409 if (p->mm && printk_ratelimit()) {
2410 printk(KERN_INFO "process %d (%s) no longer affine to cpu%d\n",
2411 task_pid_nr(p), p->comm, cpu);
2412 }
2413
2414 return dest_cpu;
2415}
2416
2417/*
2418 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
2419 */
2420static inline
2421int select_task_rq(struct task_struct *p, int sd_flags, int wake_flags)
2422{
2423 int cpu = p->sched_class->select_task_rq(p, sd_flags, wake_flags);
2424
2425 /*
2426 * In order not to call set_task_cpu() on a blocking task we need
2427 * to rely on ttwu() to place the task on a valid ->cpus_allowed
2428 * cpu.
2429 *
2430 * Since this is common to all placement strategies, this lives here.
2431 *
2432 * [ this allows ->select_task() to simply return task_cpu(p) and
2433 * not worry about this generic constraint ]
2434 */
2435 if (unlikely(!cpumask_test_cpu(cpu, &p->cpus_allowed) ||
2436 !cpu_online(cpu)))
2437 cpu = select_fallback_rq(task_cpu(p), p);
2438
2439 return cpu;
2440}
2441
2442static void update_avg(u64 *avg, u64 sample)
2443{
2444 s64 diff = sample - *avg;
2445 *avg += diff >> 3;
2446}
2447#endif
2448
2449static void
2450ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
2451{
2452#ifdef CONFIG_SCHEDSTATS
2453 struct rq *rq = this_rq();
2454
2455#ifdef CONFIG_SMP
2456 int this_cpu = smp_processor_id();
2457
2458 if (cpu == this_cpu) {
2459 schedstat_inc(rq, ttwu_local);
2460 schedstat_inc(p, se.statistics.nr_wakeups_local);
2461 } else {
2462 struct sched_domain *sd;
2463
2464 schedstat_inc(p, se.statistics.nr_wakeups_remote);
2465 rcu_read_lock();
2466 for_each_domain(this_cpu, sd) {
2467 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2468 schedstat_inc(sd, ttwu_wake_remote);
2469 break;
2470 }
2471 }
2472 rcu_read_unlock();
2473 }
2474
2475 if (wake_flags & WF_MIGRATED)
2476 schedstat_inc(p, se.statistics.nr_wakeups_migrate);
2477
2478#endif /* CONFIG_SMP */
2479
2480 schedstat_inc(rq, ttwu_count);
2481 schedstat_inc(p, se.statistics.nr_wakeups);
2482
2483 if (wake_flags & WF_SYNC)
2484 schedstat_inc(p, se.statistics.nr_wakeups_sync);
2485
2486#endif /* CONFIG_SCHEDSTATS */
2487}
2488
2489static void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
2490{
2491 activate_task(rq, p, en_flags);
2492 p->on_rq = 1;
2493
2494 /* if a worker is waking up, notify workqueue */
2495 if (p->flags & PF_WQ_WORKER)
2496 wq_worker_waking_up(p, cpu_of(rq));
2497}
2498
2499/*
2500 * Mark the task runnable and perform wakeup-preemption.
2501 */
2502static void
2503ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
2504{
2505 trace_sched_wakeup(p, true);
2506 check_preempt_curr(rq, p, wake_flags);
2507
2508 p->state = TASK_RUNNING;
2509#ifdef CONFIG_SMP
2510 if (p->sched_class->task_woken)
2511 p->sched_class->task_woken(rq, p);
2512
2513 if (rq->idle_stamp) {
2514 u64 delta = rq->clock - rq->idle_stamp;
2515 u64 max = 2*sysctl_sched_migration_cost;
2516
2517 if (delta > max)
2518 rq->avg_idle = max;
2519 else
2520 update_avg(&rq->avg_idle, delta);
2521 rq->idle_stamp = 0;
2522 }
2523#endif
2524}
2525
2526static void
2527ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags)
2528{
2529#ifdef CONFIG_SMP
2530 if (p->sched_contributes_to_load)
2531 rq->nr_uninterruptible--;
2532#endif
2533
2534 ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING);
2535 ttwu_do_wakeup(rq, p, wake_flags);
2536}
2537
2538/*
2539 * Called in case the task @p isn't fully descheduled from its runqueue,
2540 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
2541 * since all we need to do is flip p->state to TASK_RUNNING, since
2542 * the task is still ->on_rq.
2543 */
2544static int ttwu_remote(struct task_struct *p, int wake_flags)
2545{
2546 struct rq *rq;
2547 int ret = 0;
2548
2549 rq = __task_rq_lock(p);
2550 if (p->on_rq) {
2551 ttwu_do_wakeup(rq, p, wake_flags);
2552 ret = 1;
2553 }
2554 __task_rq_unlock(rq);
2555
2556 return ret;
2557}
2558
2559#ifdef CONFIG_SMP
2560static void sched_ttwu_do_pending(struct task_struct *list)
2561{
2562 struct rq *rq = this_rq();
2563
2564 raw_spin_lock(&rq->lock);
2565
2566 while (list) {
2567 struct task_struct *p = list;
2568 list = list->wake_entry;
2569 ttwu_do_activate(rq, p, 0);
2570 }
2571
2572 raw_spin_unlock(&rq->lock);
2573}
2574
2575#ifdef CONFIG_HOTPLUG_CPU
2576
2577static void sched_ttwu_pending(void)
2578{
2579 struct rq *rq = this_rq();
2580 struct task_struct *list = xchg(&rq->wake_list, NULL);
2581
2582 if (!list)
2583 return;
2584
2585 sched_ttwu_do_pending(list);
2586}
2587
2588#endif /* CONFIG_HOTPLUG_CPU */
2589
2590void scheduler_ipi(void)
2591{
2592 struct rq *rq = this_rq();
2593 struct task_struct *list = xchg(&rq->wake_list, NULL);
2594
2595 if (!list)
2596 return;
2597
2598 /*
2599 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
2600 * traditionally all their work was done from the interrupt return
2601 * path. Now that we actually do some work, we need to make sure
2602 * we do call them.
2603 *
2604 * Some archs already do call them, luckily irq_enter/exit nest
2605 * properly.
2606 *
2607 * Arguably we should visit all archs and update all handlers,
2608 * however a fair share of IPIs are still resched only so this would
2609 * somewhat pessimize the simple resched case.
2610 */
2611 irq_enter();
2612 sched_ttwu_do_pending(list);
2613 irq_exit();
2614}
2615
2616static void ttwu_queue_remote(struct task_struct *p, int cpu)
2617{
2618 struct rq *rq = cpu_rq(cpu);
2619 struct task_struct *next = rq->wake_list;
2620
2621 for (;;) {
2622 struct task_struct *old = next;
2623
2624 p->wake_entry = next;
2625 next = cmpxchg(&rq->wake_list, old, p);
2626 if (next == old)
2627 break;
2628 }
2629
2630 if (!next)
2631 smp_send_reschedule(cpu);
2632}
2633
2634#ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2635static int ttwu_activate_remote(struct task_struct *p, int wake_flags)
2636{
2637 struct rq *rq;
2638 int ret = 0;
2639
2640 rq = __task_rq_lock(p);
2641 if (p->on_cpu) {
2642 ttwu_activate(rq, p, ENQUEUE_WAKEUP);
2643 ttwu_do_wakeup(rq, p, wake_flags);
2644 ret = 1;
2645 }
2646 __task_rq_unlock(rq);
2647
2648 return ret;
2649
2650}
2651#endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
2652#endif /* CONFIG_SMP */
2653
2654static void ttwu_queue(struct task_struct *p, int cpu)
2655{
2656 struct rq *rq = cpu_rq(cpu);
2657
2658#if defined(CONFIG_SMP)
2659 if (sched_feat(TTWU_QUEUE) && cpu != smp_processor_id()) {
2660 sched_clock_cpu(cpu); /* sync clocks x-cpu */
2661 ttwu_queue_remote(p, cpu);
2662 return;
2663 }
2664#endif
2665
2666 raw_spin_lock(&rq->lock);
2667 ttwu_do_activate(rq, p, 0);
2668 raw_spin_unlock(&rq->lock);
2669}
2670
2671/**
2672 * try_to_wake_up - wake up a thread
2673 * @p: the thread to be awakened
2674 * @state: the mask of task states that can be woken
2675 * @wake_flags: wake modifier flags (WF_*)
2676 *
2677 * Put it on the run-queue if it's not already there. The "current"
2678 * thread is always on the run-queue (except when the actual
2679 * re-schedule is in progress), and as such you're allowed to do
2680 * the simpler "current->state = TASK_RUNNING" to mark yourself
2681 * runnable without the overhead of this.
2682 *
2683 * Returns %true if @p was woken up, %false if it was already running
2684 * or @state didn't match @p's state.
2685 */
2686static int
2687try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
2688{
2689 unsigned long flags;
2690 int cpu, success = 0;
2691
2692 smp_wmb();
2693 raw_spin_lock_irqsave(&p->pi_lock, flags);
2694 if (!(p->state & state))
2695 goto out;
2696
2697 success = 1; /* we're going to change ->state */
2698 cpu = task_cpu(p);
2699
2700 if (p->on_rq && ttwu_remote(p, wake_flags))
2701 goto stat;
2702
2703#ifdef CONFIG_SMP
2704 /*
2705 * If the owning (remote) cpu is still in the middle of schedule() with
2706 * this task as prev, wait until its done referencing the task.
2707 */
2708 while (p->on_cpu) {
2709#ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2710 /*
2711 * In case the architecture enables interrupts in
2712 * context_switch(), we cannot busy wait, since that
2713 * would lead to deadlocks when an interrupt hits and
2714 * tries to wake up @prev. So bail and do a complete
2715 * remote wakeup.
2716 */
2717 if (ttwu_activate_remote(p, wake_flags))
2718 goto stat;
2719#else
2720 cpu_relax();
2721#endif
2722 }
2723 /*
2724 * Pairs with the smp_wmb() in finish_lock_switch().
2725 */
2726 smp_rmb();
2727
2728 p->sched_contributes_to_load = !!task_contributes_to_load(p);
2729 p->state = TASK_WAKING;
2730
2731 if (p->sched_class->task_waking)
2732 p->sched_class->task_waking(p);
2733
2734 cpu = select_task_rq(p, SD_BALANCE_WAKE, wake_flags);
2735 if (task_cpu(p) != cpu) {
2736 wake_flags |= WF_MIGRATED;
2737 set_task_cpu(p, cpu);
2738 }
2739#endif /* CONFIG_SMP */
2740
2741 ttwu_queue(p, cpu);
2742stat:
2743 ttwu_stat(p, cpu, wake_flags);
2744out:
2745 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2746
2747 return success;
2748}
2749
2750/**
2751 * try_to_wake_up_local - try to wake up a local task with rq lock held
2752 * @p: the thread to be awakened
2753 *
2754 * Put @p on the run-queue if it's not already there. The caller must
2755 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2756 * the current task.
2757 */
2758static void try_to_wake_up_local(struct task_struct *p)
2759{
2760 struct rq *rq = task_rq(p);
2761
2762 BUG_ON(rq != this_rq());
2763 BUG_ON(p == current);
2764 lockdep_assert_held(&rq->lock);
2765
2766 if (!raw_spin_trylock(&p->pi_lock)) {
2767 raw_spin_unlock(&rq->lock);
2768 raw_spin_lock(&p->pi_lock);
2769 raw_spin_lock(&rq->lock);
2770 }
2771
2772 if (!(p->state & TASK_NORMAL))
2773 goto out;
2774
2775 if (!p->on_rq)
2776 ttwu_activate(rq, p, ENQUEUE_WAKEUP);
2777
2778 ttwu_do_wakeup(rq, p, 0);
2779 ttwu_stat(p, smp_processor_id(), 0);
2780out:
2781 raw_spin_unlock(&p->pi_lock);
2782}
2783
2784/**
2785 * wake_up_process - Wake up a specific process
2786 * @p: The process to be woken up.
2787 *
2788 * Attempt to wake up the nominated process and move it to the set of runnable
2789 * processes. Returns 1 if the process was woken up, 0 if it was already
2790 * running.
2791 *
2792 * It may be assumed that this function implies a write memory barrier before
2793 * changing the task state if and only if any tasks are woken up.
2794 */
2795int wake_up_process(struct task_struct *p)
2796{
2797 return try_to_wake_up(p, TASK_ALL, 0);
2798}
2799EXPORT_SYMBOL(wake_up_process);
2800
2801int wake_up_state(struct task_struct *p, unsigned int state)
2802{
2803 return try_to_wake_up(p, state, 0);
2804}
2805
2806/*
2807 * Perform scheduler related setup for a newly forked process p.
2808 * p is forked by current.
2809 *
2810 * __sched_fork() is basic setup used by init_idle() too:
2811 */
2812static void __sched_fork(struct task_struct *p)
2813{
2814 p->on_rq = 0;
2815
2816 p->se.on_rq = 0;
2817 p->se.exec_start = 0;
2818 p->se.sum_exec_runtime = 0;
2819 p->se.prev_sum_exec_runtime = 0;
2820 p->se.nr_migrations = 0;
2821 p->se.vruntime = 0;
2822 INIT_LIST_HEAD(&p->se.group_node);
2823
2824#ifdef CONFIG_SCHEDSTATS
2825 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2826#endif
2827
2828 INIT_LIST_HEAD(&p->rt.run_list);
2829
2830#ifdef CONFIG_PREEMPT_NOTIFIERS
2831 INIT_HLIST_HEAD(&p->preempt_notifiers);
2832#endif
2833}
2834
2835/*
2836 * fork()/clone()-time setup:
2837 */
2838void sched_fork(struct task_struct *p)
2839{
2840 unsigned long flags;
2841 int cpu = get_cpu();
2842
2843 __sched_fork(p);
2844 /*
2845 * We mark the process as running here. This guarantees that
2846 * nobody will actually run it, and a signal or other external
2847 * event cannot wake it up and insert it on the runqueue either.
2848 */
2849 p->state = TASK_RUNNING;
2850
2851 /*
2852 * Revert to default priority/policy on fork if requested.
2853 */
2854 if (unlikely(p->sched_reset_on_fork)) {
2855 if (p->policy == SCHED_FIFO || p->policy == SCHED_RR) {
2856 p->policy = SCHED_NORMAL;
2857 p->normal_prio = p->static_prio;
2858 }
2859
2860 if (PRIO_TO_NICE(p->static_prio) < 0) {
2861 p->static_prio = NICE_TO_PRIO(0);
2862 p->normal_prio = p->static_prio;
2863 set_load_weight(p);
2864 }
2865
2866 /*
2867 * We don't need the reset flag anymore after the fork. It has
2868 * fulfilled its duty:
2869 */
2870 p->sched_reset_on_fork = 0;
2871 }
2872
2873 /*
2874 * Make sure we do not leak PI boosting priority to the child.
2875 */
2876 p->prio = current->normal_prio;
2877
2878 if (!rt_prio(p->prio))
2879 p->sched_class = &fair_sched_class;
2880
2881 if (p->sched_class->task_fork)
2882 p->sched_class->task_fork(p);
2883
2884 /*
2885 * The child is not yet in the pid-hash so no cgroup attach races,
2886 * and the cgroup is pinned to this child due to cgroup_fork()
2887 * is ran before sched_fork().
2888 *
2889 * Silence PROVE_RCU.
2890 */
2891 raw_spin_lock_irqsave(&p->pi_lock, flags);
2892 set_task_cpu(p, cpu);
2893 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2894
2895#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2896 if (likely(sched_info_on()))
2897 memset(&p->sched_info, 0, sizeof(p->sched_info));
2898#endif
2899#if defined(CONFIG_SMP)
2900 p->on_cpu = 0;
2901#endif
2902#ifdef CONFIG_PREEMPT_COUNT
2903 /* Want to start with kernel preemption disabled. */
2904 task_thread_info(p)->preempt_count = 1;
2905#endif
2906#ifdef CONFIG_SMP
2907 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2908#endif
2909
2910 put_cpu();
2911}
2912
2913/*
2914 * wake_up_new_task - wake up a newly created task for the first time.
2915 *
2916 * This function will do some initial scheduler statistics housekeeping
2917 * that must be done for every newly created context, then puts the task
2918 * on the runqueue and wakes it.
2919 */
2920void wake_up_new_task(struct task_struct *p)
2921{
2922 unsigned long flags;
2923 struct rq *rq;
2924
2925 raw_spin_lock_irqsave(&p->pi_lock, flags);
2926#ifdef CONFIG_SMP
2927 /*
2928 * Fork balancing, do it here and not earlier because:
2929 * - cpus_allowed can change in the fork path
2930 * - any previously selected cpu might disappear through hotplug
2931 */
2932 set_task_cpu(p, select_task_rq(p, SD_BALANCE_FORK, 0));
2933#endif
2934
2935 rq = __task_rq_lock(p);
2936 activate_task(rq, p, 0);
2937 p->on_rq = 1;
2938 trace_sched_wakeup_new(p, true);
2939 check_preempt_curr(rq, p, WF_FORK);
2940#ifdef CONFIG_SMP
2941 if (p->sched_class->task_woken)
2942 p->sched_class->task_woken(rq, p);
2943#endif
2944 task_rq_unlock(rq, p, &flags);
2945}
2946
2947#ifdef CONFIG_PREEMPT_NOTIFIERS
2948
2949/**
2950 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2951 * @notifier: notifier struct to register
2952 */
2953void preempt_notifier_register(struct preempt_notifier *notifier)
2954{
2955 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2956}
2957EXPORT_SYMBOL_GPL(preempt_notifier_register);
2958
2959/**
2960 * preempt_notifier_unregister - no longer interested in preemption notifications
2961 * @notifier: notifier struct to unregister
2962 *
2963 * This is safe to call from within a preemption notifier.
2964 */
2965void preempt_notifier_unregister(struct preempt_notifier *notifier)
2966{
2967 hlist_del(&notifier->link);
2968}
2969EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2970
2971static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2972{
2973 struct preempt_notifier *notifier;
2974 struct hlist_node *node;
2975
2976 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2977 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2978}
2979
2980static void
2981fire_sched_out_preempt_notifiers(struct task_struct *curr,
2982 struct task_struct *next)
2983{
2984 struct preempt_notifier *notifier;
2985 struct hlist_node *node;
2986
2987 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2988 notifier->ops->sched_out(notifier, next);
2989}
2990
2991#else /* !CONFIG_PREEMPT_NOTIFIERS */
2992
2993static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2994{
2995}
2996
2997static void
2998fire_sched_out_preempt_notifiers(struct task_struct *curr,
2999 struct task_struct *next)
3000{
3001}
3002
3003#endif /* CONFIG_PREEMPT_NOTIFIERS */
3004
3005/**
3006 * prepare_task_switch - prepare to switch tasks
3007 * @rq: the runqueue preparing to switch
3008 * @prev: the current task that is being switched out
3009 * @next: the task we are going to switch to.
3010 *
3011 * This is called with the rq lock held and interrupts off. It must
3012 * be paired with a subsequent finish_task_switch after the context
3013 * switch.
3014 *
3015 * prepare_task_switch sets up locking and calls architecture specific
3016 * hooks.
3017 */
3018static inline void
3019prepare_task_switch(struct rq *rq, struct task_struct *prev,
3020 struct task_struct *next)
3021{
3022 sched_info_switch(prev, next);
3023 perf_event_task_sched_out(prev, next);
3024 fire_sched_out_preempt_notifiers(prev, next);
3025 prepare_lock_switch(rq, next);
3026 prepare_arch_switch(next);
3027 trace_sched_switch(prev, next);
3028}
3029
3030/**
3031 * finish_task_switch - clean up after a task-switch
3032 * @rq: runqueue associated with task-switch
3033 * @prev: the thread we just switched away from.
3034 *
3035 * finish_task_switch must be called after the context switch, paired
3036 * with a prepare_task_switch call before the context switch.
3037 * finish_task_switch will reconcile locking set up by prepare_task_switch,
3038 * and do any other architecture-specific cleanup actions.
3039 *
3040 * Note that we may have delayed dropping an mm in context_switch(). If
3041 * so, we finish that here outside of the runqueue lock. (Doing it
3042 * with the lock held can cause deadlocks; see schedule() for
3043 * details.)
3044 */
3045static void finish_task_switch(struct rq *rq, struct task_struct *prev)
3046 __releases(rq->lock)
3047{
3048 struct mm_struct *mm = rq->prev_mm;
3049 long prev_state;
3050
3051 rq->prev_mm = NULL;
3052
3053 /*
3054 * A task struct has one reference for the use as "current".
3055 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
3056 * schedule one last time. The schedule call will never return, and
3057 * the scheduled task must drop that reference.
3058 * The test for TASK_DEAD must occur while the runqueue locks are
3059 * still held, otherwise prev could be scheduled on another cpu, die
3060 * there before we look at prev->state, and then the reference would
3061 * be dropped twice.
3062 * Manfred Spraul <manfred@colorfullife.com>
3063 */
3064 prev_state = prev->state;
3065 finish_arch_switch(prev);
3066#ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
3067 local_irq_disable();
3068#endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
3069 perf_event_task_sched_in(prev, current);
3070#ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
3071 local_irq_enable();
3072#endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
3073 finish_lock_switch(rq, prev);
3074
3075 fire_sched_in_preempt_notifiers(current);
3076 if (mm)
3077 mmdrop(mm);
3078 if (unlikely(prev_state == TASK_DEAD)) {
3079 /*
3080 * Remove function-return probe instances associated with this
3081 * task and put them back on the free list.
3082 */
3083 kprobe_flush_task(prev);
3084 put_task_struct(prev);
3085 }
3086}
3087
3088#ifdef CONFIG_SMP
3089
3090/* assumes rq->lock is held */
3091static inline void pre_schedule(struct rq *rq, struct task_struct *prev)
3092{
3093 if (prev->sched_class->pre_schedule)
3094 prev->sched_class->pre_schedule(rq, prev);
3095}
3096
3097/* rq->lock is NOT held, but preemption is disabled */
3098static inline void post_schedule(struct rq *rq)
3099{
3100 if (rq->post_schedule) {
3101 unsigned long flags;
3102
3103 raw_spin_lock_irqsave(&rq->lock, flags);
3104 if (rq->curr->sched_class->post_schedule)
3105 rq->curr->sched_class->post_schedule(rq);
3106 raw_spin_unlock_irqrestore(&rq->lock, flags);
3107
3108 rq->post_schedule = 0;
3109 }
3110}
3111
3112#else
3113
3114static inline void pre_schedule(struct rq *rq, struct task_struct *p)
3115{
3116}
3117
3118static inline void post_schedule(struct rq *rq)
3119{
3120}
3121
3122#endif
3123
3124/**
3125 * schedule_tail - first thing a freshly forked thread must call.
3126 * @prev: the thread we just switched away from.
3127 */
3128asmlinkage void schedule_tail(struct task_struct *prev)
3129 __releases(rq->lock)
3130{
3131 struct rq *rq = this_rq();
3132
3133 finish_task_switch(rq, prev);
3134
3135 /*
3136 * FIXME: do we need to worry about rq being invalidated by the
3137 * task_switch?
3138 */
3139 post_schedule(rq);
3140
3141#ifdef __ARCH_WANT_UNLOCKED_CTXSW
3142 /* In this case, finish_task_switch does not reenable preemption */
3143 preempt_enable();
3144#endif
3145 if (current->set_child_tid)
3146 put_user(task_pid_vnr(current), current->set_child_tid);
3147}
3148
3149/*
3150 * context_switch - switch to the new MM and the new
3151 * thread's register state.
3152 */
3153static inline void
3154context_switch(struct rq *rq, struct task_struct *prev,
3155 struct task_struct *next)
3156{
3157 struct mm_struct *mm, *oldmm;
3158
3159 prepare_task_switch(rq, prev, next);
3160
3161 mm = next->mm;
3162 oldmm = prev->active_mm;
3163 /*
3164 * For paravirt, this is coupled with an exit in switch_to to
3165 * combine the page table reload and the switch backend into
3166 * one hypercall.
3167 */
3168 arch_start_context_switch(prev);
3169
3170 if (!mm) {
3171 next->active_mm = oldmm;
3172 atomic_inc(&oldmm->mm_count);
3173 enter_lazy_tlb(oldmm, next);
3174 } else
3175 switch_mm(oldmm, mm, next);
3176
3177 if (!prev->mm) {
3178 prev->active_mm = NULL;
3179 rq->prev_mm = oldmm;
3180 }
3181 /*
3182 * Since the runqueue lock will be released by the next
3183 * task (which is an invalid locking op but in the case
3184 * of the scheduler it's an obvious special-case), so we
3185 * do an early lockdep release here:
3186 */
3187#ifndef __ARCH_WANT_UNLOCKED_CTXSW
3188 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
3189#endif
3190
3191 /* Here we just switch the register state and the stack. */
3192 switch_to(prev, next, prev);
3193
3194 barrier();
3195 /*
3196 * this_rq must be evaluated again because prev may have moved
3197 * CPUs since it called schedule(), thus the 'rq' on its stack
3198 * frame will be invalid.
3199 */
3200 finish_task_switch(this_rq(), prev);
3201}
3202
3203/*
3204 * nr_running, nr_uninterruptible and nr_context_switches:
3205 *
3206 * externally visible scheduler statistics: current number of runnable
3207 * threads, current number of uninterruptible-sleeping threads, total
3208 * number of context switches performed since bootup.
3209 */
3210unsigned long nr_running(void)
3211{
3212 unsigned long i, sum = 0;
3213
3214 for_each_online_cpu(i)
3215 sum += cpu_rq(i)->nr_running;
3216
3217 return sum;
3218}
3219
3220unsigned long nr_uninterruptible(void)
3221{
3222 unsigned long i, sum = 0;
3223
3224 for_each_possible_cpu(i)
3225 sum += cpu_rq(i)->nr_uninterruptible;
3226
3227 /*
3228 * Since we read the counters lockless, it might be slightly
3229 * inaccurate. Do not allow it to go below zero though:
3230 */
3231 if (unlikely((long)sum < 0))
3232 sum = 0;
3233
3234 return sum;
3235}
3236
3237unsigned long long nr_context_switches(void)
3238{
3239 int i;
3240 unsigned long long sum = 0;
3241
3242 for_each_possible_cpu(i)
3243 sum += cpu_rq(i)->nr_switches;
3244
3245 return sum;
3246}
3247
3248unsigned long nr_iowait(void)
3249{
3250 unsigned long i, sum = 0;
3251
3252 for_each_possible_cpu(i)
3253 sum += atomic_read(&cpu_rq(i)->nr_iowait);
3254
3255 return sum;
3256}
3257
3258unsigned long nr_iowait_cpu(int cpu)
3259{
3260 struct rq *this = cpu_rq(cpu);
3261 return atomic_read(&this->nr_iowait);
3262}
3263
3264unsigned long this_cpu_load(void)
3265{
3266 struct rq *this = this_rq();
3267 return this->cpu_load[0];
3268}
3269
3270
3271/* Variables and functions for calc_load */
3272static atomic_long_t calc_load_tasks;
3273static unsigned long calc_load_update;
3274unsigned long avenrun[3];
3275EXPORT_SYMBOL(avenrun);
3276
3277static long calc_load_fold_active(struct rq *this_rq)
3278{
3279 long nr_active, delta = 0;
3280
3281 nr_active = this_rq->nr_running;
3282 nr_active += (long) this_rq->nr_uninterruptible;
3283
3284 if (nr_active != this_rq->calc_load_active) {
3285 delta = nr_active - this_rq->calc_load_active;
3286 this_rq->calc_load_active = nr_active;
3287 }
3288
3289 return delta;
3290}
3291
3292static unsigned long
3293calc_load(unsigned long load, unsigned long exp, unsigned long active)
3294{
3295 load *= exp;
3296 load += active * (FIXED_1 - exp);
3297 load += 1UL << (FSHIFT - 1);
3298 return load >> FSHIFT;
3299}
3300
3301#ifdef CONFIG_NO_HZ
3302/*
3303 * For NO_HZ we delay the active fold to the next LOAD_FREQ update.
3304 *
3305 * When making the ILB scale, we should try to pull this in as well.
3306 */
3307static atomic_long_t calc_load_tasks_idle;
3308
3309static void calc_load_account_idle(struct rq *this_rq)
3310{
3311 long delta;
3312
3313 delta = calc_load_fold_active(this_rq);
3314 if (delta)
3315 atomic_long_add(delta, &calc_load_tasks_idle);
3316}
3317
3318static long calc_load_fold_idle(void)
3319{
3320 long delta = 0;
3321
3322 /*
3323 * Its got a race, we don't care...
3324 */
3325 if (atomic_long_read(&calc_load_tasks_idle))
3326 delta = atomic_long_xchg(&calc_load_tasks_idle, 0);
3327
3328 return delta;
3329}
3330
3331/**
3332 * fixed_power_int - compute: x^n, in O(log n) time
3333 *
3334 * @x: base of the power
3335 * @frac_bits: fractional bits of @x
3336 * @n: power to raise @x to.
3337 *
3338 * By exploiting the relation between the definition of the natural power
3339 * function: x^n := x*x*...*x (x multiplied by itself for n times), and
3340 * the binary encoding of numbers used by computers: n := \Sum n_i * 2^i,
3341 * (where: n_i \elem {0, 1}, the binary vector representing n),
3342 * we find: x^n := x^(\Sum n_i * 2^i) := \Prod x^(n_i * 2^i), which is
3343 * of course trivially computable in O(log_2 n), the length of our binary
3344 * vector.
3345 */
3346static unsigned long
3347fixed_power_int(unsigned long x, unsigned int frac_bits, unsigned int n)
3348{
3349 unsigned long result = 1UL << frac_bits;
3350
3351 if (n) for (;;) {
3352 if (n & 1) {
3353 result *= x;
3354 result += 1UL << (frac_bits - 1);
3355 result >>= frac_bits;
3356 }
3357 n >>= 1;
3358 if (!n)
3359 break;
3360 x *= x;
3361 x += 1UL << (frac_bits - 1);
3362 x >>= frac_bits;
3363 }
3364
3365 return result;
3366}
3367
3368/*
3369 * a1 = a0 * e + a * (1 - e)
3370 *
3371 * a2 = a1 * e + a * (1 - e)
3372 * = (a0 * e + a * (1 - e)) * e + a * (1 - e)
3373 * = a0 * e^2 + a * (1 - e) * (1 + e)
3374 *
3375 * a3 = a2 * e + a * (1 - e)
3376 * = (a0 * e^2 + a * (1 - e) * (1 + e)) * e + a * (1 - e)
3377 * = a0 * e^3 + a * (1 - e) * (1 + e + e^2)
3378 *
3379 * ...
3380 *
3381 * an = a0 * e^n + a * (1 - e) * (1 + e + ... + e^n-1) [1]
3382 * = a0 * e^n + a * (1 - e) * (1 - e^n)/(1 - e)
3383 * = a0 * e^n + a * (1 - e^n)
3384 *
3385 * [1] application of the geometric series:
3386 *
3387 * n 1 - x^(n+1)
3388 * S_n := \Sum x^i = -------------
3389 * i=0 1 - x
3390 */
3391static unsigned long
3392calc_load_n(unsigned long load, unsigned long exp,
3393 unsigned long active, unsigned int n)
3394{
3395
3396 return calc_load(load, fixed_power_int(exp, FSHIFT, n), active);
3397}
3398
3399/*
3400 * NO_HZ can leave us missing all per-cpu ticks calling
3401 * calc_load_account_active(), but since an idle CPU folds its delta into
3402 * calc_load_tasks_idle per calc_load_account_idle(), all we need to do is fold
3403 * in the pending idle delta if our idle period crossed a load cycle boundary.
3404 *
3405 * Once we've updated the global active value, we need to apply the exponential
3406 * weights adjusted to the number of cycles missed.
3407 */
3408static void calc_global_nohz(unsigned long ticks)
3409{
3410 long delta, active, n;
3411
3412 if (time_before(jiffies, calc_load_update))
3413 return;
3414
3415 /*
3416 * If we crossed a calc_load_update boundary, make sure to fold
3417 * any pending idle changes, the respective CPUs might have
3418 * missed the tick driven calc_load_account_active() update
3419 * due to NO_HZ.
3420 */
3421 delta = calc_load_fold_idle();
3422 if (delta)
3423 atomic_long_add(delta, &calc_load_tasks);
3424
3425 /*
3426 * If we were idle for multiple load cycles, apply them.
3427 */
3428 if (ticks >= LOAD_FREQ) {
3429 n = ticks / LOAD_FREQ;
3430
3431 active = atomic_long_read(&calc_load_tasks);
3432 active = active > 0 ? active * FIXED_1 : 0;
3433
3434 avenrun[0] = calc_load_n(avenrun[0], EXP_1, active, n);
3435 avenrun[1] = calc_load_n(avenrun[1], EXP_5, active, n);
3436 avenrun[2] = calc_load_n(avenrun[2], EXP_15, active, n);
3437
3438 calc_load_update += n * LOAD_FREQ;
3439 }
3440
3441 /*
3442 * Its possible the remainder of the above division also crosses
3443 * a LOAD_FREQ period, the regular check in calc_global_load()
3444 * which comes after this will take care of that.
3445 *
3446 * Consider us being 11 ticks before a cycle completion, and us
3447 * sleeping for 4*LOAD_FREQ + 22 ticks, then the above code will
3448 * age us 4 cycles, and the test in calc_global_load() will
3449 * pick up the final one.
3450 */
3451}
3452#else
3453static void calc_load_account_idle(struct rq *this_rq)
3454{
3455}
3456
3457static inline long calc_load_fold_idle(void)
3458{
3459 return 0;
3460}
3461
3462static void calc_global_nohz(unsigned long ticks)
3463{
3464}
3465#endif
3466
3467/**
3468 * get_avenrun - get the load average array
3469 * @loads: pointer to dest load array
3470 * @offset: offset to add
3471 * @shift: shift count to shift the result left
3472 *
3473 * These values are estimates at best, so no need for locking.
3474 */
3475void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
3476{
3477 loads[0] = (avenrun[0] + offset) << shift;
3478 loads[1] = (avenrun[1] + offset) << shift;
3479 loads[2] = (avenrun[2] + offset) << shift;
3480}
3481
3482/*
3483 * calc_load - update the avenrun load estimates 10 ticks after the
3484 * CPUs have updated calc_load_tasks.
3485 */
3486void calc_global_load(unsigned long ticks)
3487{
3488 long active;
3489
3490 calc_global_nohz(ticks);
3491
3492 if (time_before(jiffies, calc_load_update + 10))
3493 return;
3494
3495 active = atomic_long_read(&calc_load_tasks);
3496 active = active > 0 ? active * FIXED_1 : 0;
3497
3498 avenrun[0] = calc_load(avenrun[0], EXP_1, active);
3499 avenrun[1] = calc_load(avenrun[1], EXP_5, active);
3500 avenrun[2] = calc_load(avenrun[2], EXP_15, active);
3501
3502 calc_load_update += LOAD_FREQ;
3503}
3504
3505/*
3506 * Called from update_cpu_load() to periodically update this CPU's
3507 * active count.
3508 */
3509static void calc_load_account_active(struct rq *this_rq)
3510{
3511 long delta;
3512
3513 if (time_before(jiffies, this_rq->calc_load_update))
3514 return;
3515
3516 delta = calc_load_fold_active(this_rq);
3517 delta += calc_load_fold_idle();
3518 if (delta)
3519 atomic_long_add(delta, &calc_load_tasks);
3520
3521 this_rq->calc_load_update += LOAD_FREQ;
3522}
3523
3524/*
3525 * The exact cpuload at various idx values, calculated at every tick would be
3526 * load = (2^idx - 1) / 2^idx * load + 1 / 2^idx * cur_load
3527 *
3528 * If a cpu misses updates for n-1 ticks (as it was idle) and update gets called
3529 * on nth tick when cpu may be busy, then we have:
3530 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
3531 * load = (2^idx - 1) / 2^idx) * load + 1 / 2^idx * cur_load
3532 *
3533 * decay_load_missed() below does efficient calculation of
3534 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
3535 * avoiding 0..n-1 loop doing load = ((2^idx - 1) / 2^idx) * load
3536 *
3537 * The calculation is approximated on a 128 point scale.
3538 * degrade_zero_ticks is the number of ticks after which load at any
3539 * particular idx is approximated to be zero.
3540 * degrade_factor is a precomputed table, a row for each load idx.
3541 * Each column corresponds to degradation factor for a power of two ticks,
3542 * based on 128 point scale.
3543 * Example:
3544 * row 2, col 3 (=12) says that the degradation at load idx 2 after
3545 * 8 ticks is 12/128 (which is an approximation of exact factor 3^8/4^8).
3546 *
3547 * With this power of 2 load factors, we can degrade the load n times
3548 * by looking at 1 bits in n and doing as many mult/shift instead of
3549 * n mult/shifts needed by the exact degradation.
3550 */
3551#define DEGRADE_SHIFT 7
3552static const unsigned char
3553 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
3554static const unsigned char
3555 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
3556 {0, 0, 0, 0, 0, 0, 0, 0},
3557 {64, 32, 8, 0, 0, 0, 0, 0},
3558 {96, 72, 40, 12, 1, 0, 0},
3559 {112, 98, 75, 43, 15, 1, 0},
3560 {120, 112, 98, 76, 45, 16, 2} };
3561
3562/*
3563 * Update cpu_load for any missed ticks, due to tickless idle. The backlog
3564 * would be when CPU is idle and so we just decay the old load without
3565 * adding any new load.
3566 */
3567static unsigned long
3568decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
3569{
3570 int j = 0;
3571
3572 if (!missed_updates)
3573 return load;
3574
3575 if (missed_updates >= degrade_zero_ticks[idx])
3576 return 0;
3577
3578 if (idx == 1)
3579 return load >> missed_updates;
3580
3581 while (missed_updates) {
3582 if (missed_updates % 2)
3583 load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
3584
3585 missed_updates >>= 1;
3586 j++;
3587 }
3588 return load;
3589}
3590
3591/*
3592 * Update rq->cpu_load[] statistics. This function is usually called every
3593 * scheduler tick (TICK_NSEC). With tickless idle this will not be called
3594 * every tick. We fix it up based on jiffies.
3595 */
3596static void update_cpu_load(struct rq *this_rq)
3597{
3598 unsigned long this_load = this_rq->load.weight;
3599 unsigned long curr_jiffies = jiffies;
3600 unsigned long pending_updates;
3601 int i, scale;
3602
3603 this_rq->nr_load_updates++;
3604
3605 /* Avoid repeated calls on same jiffy, when moving in and out of idle */
3606 if (curr_jiffies == this_rq->last_load_update_tick)
3607 return;
3608
3609 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
3610 this_rq->last_load_update_tick = curr_jiffies;
3611
3612 /* Update our load: */
3613 this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
3614 for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
3615 unsigned long old_load, new_load;
3616
3617 /* scale is effectively 1 << i now, and >> i divides by scale */
3618
3619 old_load = this_rq->cpu_load[i];
3620 old_load = decay_load_missed(old_load, pending_updates - 1, i);
3621 new_load = this_load;
3622 /*
3623 * Round up the averaging division if load is increasing. This
3624 * prevents us from getting stuck on 9 if the load is 10, for
3625 * example.
3626 */
3627 if (new_load > old_load)
3628 new_load += scale - 1;
3629
3630 this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
3631 }
3632
3633 sched_avg_update(this_rq);
3634}
3635
3636static void update_cpu_load_active(struct rq *this_rq)
3637{
3638 update_cpu_load(this_rq);
3639
3640 calc_load_account_active(this_rq);
3641}
3642
3643#ifdef CONFIG_SMP
3644
3645/*
3646 * sched_exec - execve() is a valuable balancing opportunity, because at
3647 * this point the task has the smallest effective memory and cache footprint.
3648 */
3649void sched_exec(void)
3650{
3651 struct task_struct *p = current;
3652 unsigned long flags;
3653 int dest_cpu;
3654
3655 raw_spin_lock_irqsave(&p->pi_lock, flags);
3656 dest_cpu = p->sched_class->select_task_rq(p, SD_BALANCE_EXEC, 0);
3657 if (dest_cpu == smp_processor_id())
3658 goto unlock;
3659
3660 if (likely(cpu_active(dest_cpu))) {
3661 struct migration_arg arg = { p, dest_cpu };
3662
3663 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3664 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
3665 return;
3666 }
3667unlock:
3668 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3669}
3670
3671#endif
3672
3673DEFINE_PER_CPU(struct kernel_stat, kstat);
3674
3675EXPORT_PER_CPU_SYMBOL(kstat);
3676
3677/*
3678 * Return any ns on the sched_clock that have not yet been accounted in
3679 * @p in case that task is currently running.
3680 *
3681 * Called with task_rq_lock() held on @rq.
3682 */
3683static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
3684{
3685 u64 ns = 0;
3686
3687 if (task_current(rq, p)) {
3688 update_rq_clock(rq);
3689 ns = rq->clock_task - p->se.exec_start;
3690 if ((s64)ns < 0)
3691 ns = 0;
3692 }
3693
3694 return ns;
3695}
3696
3697unsigned long long task_delta_exec(struct task_struct *p)
3698{
3699 unsigned long flags;
3700 struct rq *rq;
3701 u64 ns = 0;
3702
3703 rq = task_rq_lock(p, &flags);
3704 ns = do_task_delta_exec(p, rq);
3705 task_rq_unlock(rq, p, &flags);
3706
3707 return ns;
3708}
3709
3710/*
3711 * Return accounted runtime for the task.
3712 * In case the task is currently running, return the runtime plus current's
3713 * pending runtime that have not been accounted yet.
3714 */
3715unsigned long long task_sched_runtime(struct task_struct *p)
3716{
3717 unsigned long flags;
3718 struct rq *rq;
3719 u64 ns = 0;
3720
3721 rq = task_rq_lock(p, &flags);
3722 ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
3723 task_rq_unlock(rq, p, &flags);
3724
3725 return ns;
3726}
3727
3728/*
3729 * Account user cpu time to a process.
3730 * @p: the process that the cpu time gets accounted to
3731 * @cputime: the cpu time spent in user space since the last update
3732 * @cputime_scaled: cputime scaled by cpu frequency
3733 */
3734void account_user_time(struct task_struct *p, cputime_t cputime,
3735 cputime_t cputime_scaled)
3736{
3737 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3738 cputime64_t tmp;
3739
3740 /* Add user time to process. */
3741 p->utime = cputime_add(p->utime, cputime);
3742 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
3743 account_group_user_time(p, cputime);
3744
3745 /* Add user time to cpustat. */
3746 tmp = cputime_to_cputime64(cputime);
3747 if (TASK_NICE(p) > 0)
3748 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3749 else
3750 cpustat->user = cputime64_add(cpustat->user, tmp);
3751
3752 cpuacct_update_stats(p, CPUACCT_STAT_USER, cputime);
3753 /* Account for user time used */
3754 acct_update_integrals(p);
3755}
3756
3757/*
3758 * Account guest cpu time to a process.
3759 * @p: the process that the cpu time gets accounted to
3760 * @cputime: the cpu time spent in virtual machine since the last update
3761 * @cputime_scaled: cputime scaled by cpu frequency
3762 */
3763static void account_guest_time(struct task_struct *p, cputime_t cputime,
3764 cputime_t cputime_scaled)
3765{
3766 cputime64_t tmp;
3767 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3768
3769 tmp = cputime_to_cputime64(cputime);
3770
3771 /* Add guest time to process. */
3772 p->utime = cputime_add(p->utime, cputime);
3773 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
3774 account_group_user_time(p, cputime);
3775 p->gtime = cputime_add(p->gtime, cputime);
3776
3777 /* Add guest time to cpustat. */
3778 if (TASK_NICE(p) > 0) {
3779 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3780 cpustat->guest_nice = cputime64_add(cpustat->guest_nice, tmp);
3781 } else {
3782 cpustat->user = cputime64_add(cpustat->user, tmp);
3783 cpustat->guest = cputime64_add(cpustat->guest, tmp);
3784 }
3785}
3786
3787/*
3788 * Account system cpu time to a process and desired cpustat field
3789 * @p: the process that the cpu time gets accounted to
3790 * @cputime: the cpu time spent in kernel space since the last update
3791 * @cputime_scaled: cputime scaled by cpu frequency
3792 * @target_cputime64: pointer to cpustat field that has to be updated
3793 */
3794static inline
3795void __account_system_time(struct task_struct *p, cputime_t cputime,
3796 cputime_t cputime_scaled, cputime64_t *target_cputime64)
3797{
3798 cputime64_t tmp = cputime_to_cputime64(cputime);
3799
3800 /* Add system time to process. */
3801 p->stime = cputime_add(p->stime, cputime);
3802 p->stimescaled = cputime_add(p->stimescaled, cputime_scaled);
3803 account_group_system_time(p, cputime);
3804
3805 /* Add system time to cpustat. */
3806 *target_cputime64 = cputime64_add(*target_cputime64, tmp);
3807 cpuacct_update_stats(p, CPUACCT_STAT_SYSTEM, cputime);
3808
3809 /* Account for system time used */
3810 acct_update_integrals(p);
3811}
3812
3813/*
3814 * Account system cpu time to a process.
3815 * @p: the process that the cpu time gets accounted to
3816 * @hardirq_offset: the offset to subtract from hardirq_count()
3817 * @cputime: the cpu time spent in kernel space since the last update
3818 * @cputime_scaled: cputime scaled by cpu frequency
3819 */
3820void account_system_time(struct task_struct *p, int hardirq_offset,
3821 cputime_t cputime, cputime_t cputime_scaled)
3822{
3823 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3824 cputime64_t *target_cputime64;
3825
3826 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
3827 account_guest_time(p, cputime, cputime_scaled);
3828 return;
3829 }
3830
3831 if (hardirq_count() - hardirq_offset)
3832 target_cputime64 = &cpustat->irq;
3833 else if (in_serving_softirq())
3834 target_cputime64 = &cpustat->softirq;
3835 else
3836 target_cputime64 = &cpustat->system;
3837
3838 __account_system_time(p, cputime, cputime_scaled, target_cputime64);
3839}
3840
3841/*
3842 * Account for involuntary wait time.
3843 * @cputime: the cpu time spent in involuntary wait
3844 */
3845void account_steal_time(cputime_t cputime)
3846{
3847 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3848 cputime64_t cputime64 = cputime_to_cputime64(cputime);
3849
3850 cpustat->steal = cputime64_add(cpustat->steal, cputime64);
3851}
3852
3853/*
3854 * Account for idle time.
3855 * @cputime: the cpu time spent in idle wait
3856 */
3857void account_idle_time(cputime_t cputime)
3858{
3859 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3860 cputime64_t cputime64 = cputime_to_cputime64(cputime);
3861 struct rq *rq = this_rq();
3862
3863 if (atomic_read(&rq->nr_iowait) > 0)
3864 cpustat->iowait = cputime64_add(cpustat->iowait, cputime64);
3865 else
3866 cpustat->idle = cputime64_add(cpustat->idle, cputime64);
3867}
3868
3869static __always_inline bool steal_account_process_tick(void)
3870{
3871#ifdef CONFIG_PARAVIRT
3872 if (static_branch(&paravirt_steal_enabled)) {
3873 u64 steal, st = 0;
3874
3875 steal = paravirt_steal_clock(smp_processor_id());
3876 steal -= this_rq()->prev_steal_time;
3877
3878 st = steal_ticks(steal);
3879 this_rq()->prev_steal_time += st * TICK_NSEC;
3880
3881 account_steal_time(st);
3882 return st;
3883 }
3884#endif
3885 return false;
3886}
3887
3888#ifndef CONFIG_VIRT_CPU_ACCOUNTING
3889
3890#ifdef CONFIG_IRQ_TIME_ACCOUNTING
3891/*
3892 * Account a tick to a process and cpustat
3893 * @p: the process that the cpu time gets accounted to
3894 * @user_tick: is the tick from userspace
3895 * @rq: the pointer to rq
3896 *
3897 * Tick demultiplexing follows the order
3898 * - pending hardirq update
3899 * - pending softirq update
3900 * - user_time
3901 * - idle_time
3902 * - system time
3903 * - check for guest_time
3904 * - else account as system_time
3905 *
3906 * Check for hardirq is done both for system and user time as there is
3907 * no timer going off while we are on hardirq and hence we may never get an
3908 * opportunity to update it solely in system time.
3909 * p->stime and friends are only updated on system time and not on irq
3910 * softirq as those do not count in task exec_runtime any more.
3911 */
3912static void irqtime_account_process_tick(struct task_struct *p, int user_tick,
3913 struct rq *rq)
3914{
3915 cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy);
3916 cputime64_t tmp = cputime_to_cputime64(cputime_one_jiffy);
3917 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3918
3919 if (steal_account_process_tick())
3920 return;
3921
3922 if (irqtime_account_hi_update()) {
3923 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3924 } else if (irqtime_account_si_update()) {
3925 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3926 } else if (this_cpu_ksoftirqd() == p) {
3927 /*
3928 * ksoftirqd time do not get accounted in cpu_softirq_time.
3929 * So, we have to handle it separately here.
3930 * Also, p->stime needs to be updated for ksoftirqd.
3931 */
3932 __account_system_time(p, cputime_one_jiffy, one_jiffy_scaled,
3933 &cpustat->softirq);
3934 } else if (user_tick) {
3935 account_user_time(p, cputime_one_jiffy, one_jiffy_scaled);
3936 } else if (p == rq->idle) {
3937 account_idle_time(cputime_one_jiffy);
3938 } else if (p->flags & PF_VCPU) { /* System time or guest time */
3939 account_guest_time(p, cputime_one_jiffy, one_jiffy_scaled);
3940 } else {
3941 __account_system_time(p, cputime_one_jiffy, one_jiffy_scaled,
3942 &cpustat->system);
3943 }
3944}
3945
3946static void irqtime_account_idle_ticks(int ticks)
3947{
3948 int i;
3949 struct rq *rq = this_rq();
3950
3951 for (i = 0; i < ticks; i++)
3952 irqtime_account_process_tick(current, 0, rq);
3953}
3954#else /* CONFIG_IRQ_TIME_ACCOUNTING */
3955static void irqtime_account_idle_ticks(int ticks) {}
3956static void irqtime_account_process_tick(struct task_struct *p, int user_tick,
3957 struct rq *rq) {}
3958#endif /* CONFIG_IRQ_TIME_ACCOUNTING */
3959
3960/*
3961 * Account a single tick of cpu time.
3962 * @p: the process that the cpu time gets accounted to
3963 * @user_tick: indicates if the tick is a user or a system tick
3964 */
3965void account_process_tick(struct task_struct *p, int user_tick)
3966{
3967 cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy);
3968 struct rq *rq = this_rq();
3969
3970 if (sched_clock_irqtime) {
3971 irqtime_account_process_tick(p, user_tick, rq);
3972 return;
3973 }
3974
3975 if (steal_account_process_tick())
3976 return;
3977
3978 if (user_tick)
3979 account_user_time(p, cputime_one_jiffy, one_jiffy_scaled);
3980 else if ((p != rq->idle) || (irq_count() != HARDIRQ_OFFSET))
3981 account_system_time(p, HARDIRQ_OFFSET, cputime_one_jiffy,
3982 one_jiffy_scaled);
3983 else
3984 account_idle_time(cputime_one_jiffy);
3985}
3986
3987/*
3988 * Account multiple ticks of steal time.
3989 * @p: the process from which the cpu time has been stolen
3990 * @ticks: number of stolen ticks
3991 */
3992void account_steal_ticks(unsigned long ticks)
3993{
3994 account_steal_time(jiffies_to_cputime(ticks));
3995}
3996
3997/*
3998 * Account multiple ticks of idle time.
3999 * @ticks: number of stolen ticks
4000 */
4001void account_idle_ticks(unsigned long ticks)
4002{
4003
4004 if (sched_clock_irqtime) {
4005 irqtime_account_idle_ticks(ticks);
4006 return;
4007 }
4008
4009 account_idle_time(jiffies_to_cputime(ticks));
4010}
4011
4012#endif
4013
4014/*
4015 * Use precise platform statistics if available:
4016 */
4017#ifdef CONFIG_VIRT_CPU_ACCOUNTING
4018void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
4019{
4020 *ut = p->utime;
4021 *st = p->stime;
4022}
4023
4024void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
4025{
4026 struct task_cputime cputime;
4027
4028 thread_group_cputime(p, &cputime);
4029
4030 *ut = cputime.utime;
4031 *st = cputime.stime;
4032}
4033#else
4034
4035#ifndef nsecs_to_cputime
4036# define nsecs_to_cputime(__nsecs) nsecs_to_jiffies(__nsecs)
4037#endif
4038
4039void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
4040{
4041 cputime_t rtime, utime = p->utime, total = cputime_add(utime, p->stime);
4042
4043 /*
4044 * Use CFS's precise accounting:
4045 */
4046 rtime = nsecs_to_cputime(p->se.sum_exec_runtime);
4047
4048 if (total) {
4049 u64 temp = rtime;
4050
4051 temp *= utime;
4052 do_div(temp, total);
4053 utime = (cputime_t)temp;
4054 } else
4055 utime = rtime;
4056
4057 /*
4058 * Compare with previous values, to keep monotonicity:
4059 */
4060 p->prev_utime = max(p->prev_utime, utime);
4061 p->prev_stime = max(p->prev_stime, cputime_sub(rtime, p->prev_utime));
4062
4063 *ut = p->prev_utime;
4064 *st = p->prev_stime;
4065}
4066
4067/*
4068 * Must be called with siglock held.
4069 */
4070void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
4071{
4072 struct signal_struct *sig = p->signal;
4073 struct task_cputime cputime;
4074 cputime_t rtime, utime, total;
4075
4076 thread_group_cputime(p, &cputime);
4077
4078 total = cputime_add(cputime.utime, cputime.stime);
4079 rtime = nsecs_to_cputime(cputime.sum_exec_runtime);
4080
4081 if (total) {
4082 u64 temp = rtime;
4083
4084 temp *= cputime.utime;
4085 do_div(temp, total);
4086 utime = (cputime_t)temp;
4087 } else
4088 utime = rtime;
4089
4090 sig->prev_utime = max(sig->prev_utime, utime);
4091 sig->prev_stime = max(sig->prev_stime,
4092 cputime_sub(rtime, sig->prev_utime));
4093
4094 *ut = sig->prev_utime;
4095 *st = sig->prev_stime;
4096}
4097#endif
4098
4099/*
4100 * This function gets called by the timer code, with HZ frequency.
4101 * We call it with interrupts disabled.
4102 */
4103void scheduler_tick(void)
4104{
4105 int cpu = smp_processor_id();
4106 struct rq *rq = cpu_rq(cpu);
4107 struct task_struct *curr = rq->curr;
4108
4109 sched_clock_tick();
4110
4111 raw_spin_lock(&rq->lock);
4112 update_rq_clock(rq);
4113 update_cpu_load_active(rq);
4114 curr->sched_class->task_tick(rq, curr, 0);
4115 raw_spin_unlock(&rq->lock);
4116
4117 perf_event_task_tick();
4118
4119#ifdef CONFIG_SMP
4120 rq->idle_at_tick = idle_cpu(cpu);
4121 trigger_load_balance(rq, cpu);
4122#endif
4123}
4124
4125notrace unsigned long get_parent_ip(unsigned long addr)
4126{
4127 if (in_lock_functions(addr)) {
4128 addr = CALLER_ADDR2;
4129 if (in_lock_functions(addr))
4130 addr = CALLER_ADDR3;
4131 }
4132 return addr;
4133}
4134
4135#if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
4136 defined(CONFIG_PREEMPT_TRACER))
4137
4138void __kprobes add_preempt_count(int val)
4139{
4140#ifdef CONFIG_DEBUG_PREEMPT
4141 /*
4142 * Underflow?
4143 */
4144 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4145 return;
4146#endif
4147 preempt_count() += val;
4148#ifdef CONFIG_DEBUG_PREEMPT
4149 /*
4150 * Spinlock count overflowing soon?
4151 */
4152 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4153 PREEMPT_MASK - 10);
4154#endif
4155 if (preempt_count() == val)
4156 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4157}
4158EXPORT_SYMBOL(add_preempt_count);
4159
4160void __kprobes sub_preempt_count(int val)
4161{
4162#ifdef CONFIG_DEBUG_PREEMPT
4163 /*
4164 * Underflow?
4165 */
4166 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
4167 return;
4168 /*
4169 * Is the spinlock portion underflowing?
4170 */
4171 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4172 !(preempt_count() & PREEMPT_MASK)))
4173 return;
4174#endif
4175
4176 if (preempt_count() == val)
4177 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
4178 preempt_count() -= val;
4179}
4180EXPORT_SYMBOL(sub_preempt_count);
4181
4182#endif
4183
4184/*
4185 * Print scheduling while atomic bug:
4186 */
4187static noinline void __schedule_bug(struct task_struct *prev)
4188{
4189 struct pt_regs *regs = get_irq_regs();
4190
4191 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4192 prev->comm, prev->pid, preempt_count());
4193
4194 debug_show_held_locks(prev);
4195 print_modules();
4196 if (irqs_disabled())
4197 print_irqtrace_events(prev);
4198
4199 if (regs)
4200 show_regs(regs);
4201 else
4202 dump_stack();
4203}
4204
4205/*
4206 * Various schedule()-time debugging checks and statistics:
4207 */
4208static inline void schedule_debug(struct task_struct *prev)
4209{
4210 /*
4211 * Test if we are atomic. Since do_exit() needs to call into
4212 * schedule() atomically, we ignore that path for now.
4213 * Otherwise, whine if we are scheduling when we should not be.
4214 */
4215 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
4216 __schedule_bug(prev);
4217
4218 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4219
4220 schedstat_inc(this_rq(), sched_count);
4221}
4222
4223static void put_prev_task(struct rq *rq, struct task_struct *prev)
4224{
4225 if (prev->on_rq || rq->skip_clock_update < 0)
4226 update_rq_clock(rq);
4227 prev->sched_class->put_prev_task(rq, prev);
4228}
4229
4230/*
4231 * Pick up the highest-prio task:
4232 */
4233static inline struct task_struct *
4234pick_next_task(struct rq *rq)
4235{
4236 const struct sched_class *class;
4237 struct task_struct *p;
4238
4239 /*
4240 * Optimization: we know that if all tasks are in
4241 * the fair class we can call that function directly:
4242 */
4243 if (likely(rq->nr_running == rq->cfs.nr_running)) {
4244 p = fair_sched_class.pick_next_task(rq);
4245 if (likely(p))
4246 return p;
4247 }
4248
4249 for_each_class(class) {
4250 p = class->pick_next_task(rq);
4251 if (p)
4252 return p;
4253 }
4254
4255 BUG(); /* the idle class will always have a runnable task */
4256}
4257
4258/*
4259 * __schedule() is the main scheduler function.
4260 */
4261static void __sched __schedule(void)
4262{
4263 struct task_struct *prev, *next;
4264 unsigned long *switch_count;
4265 struct rq *rq;
4266 int cpu;
4267
4268need_resched:
4269 preempt_disable();
4270 cpu = smp_processor_id();
4271 rq = cpu_rq(cpu);
4272 rcu_note_context_switch(cpu);
4273 prev = rq->curr;
4274
4275 schedule_debug(prev);
4276
4277 if (sched_feat(HRTICK))
4278 hrtick_clear(rq);
4279
4280 raw_spin_lock_irq(&rq->lock);
4281
4282 switch_count = &prev->nivcsw;
4283 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4284 if (unlikely(signal_pending_state(prev->state, prev))) {
4285 prev->state = TASK_RUNNING;
4286 } else {
4287 deactivate_task(rq, prev, DEQUEUE_SLEEP);
4288 prev->on_rq = 0;
4289
4290 /*
4291 * If a worker went to sleep, notify and ask workqueue
4292 * whether it wants to wake up a task to maintain
4293 * concurrency.
4294 */
4295 if (prev->flags & PF_WQ_WORKER) {
4296 struct task_struct *to_wakeup;
4297
4298 to_wakeup = wq_worker_sleeping(prev, cpu);
4299 if (to_wakeup)
4300 try_to_wake_up_local(to_wakeup);
4301 }
4302 }
4303 switch_count = &prev->nvcsw;
4304 }
4305
4306 pre_schedule(rq, prev);
4307
4308 if (unlikely(!rq->nr_running))
4309 idle_balance(cpu, rq);
4310
4311 put_prev_task(rq, prev);
4312 next = pick_next_task(rq);
4313 clear_tsk_need_resched(prev);
4314 rq->skip_clock_update = 0;
4315
4316 if (likely(prev != next)) {
4317 rq->nr_switches++;
4318 rq->curr = next;
4319 ++*switch_count;
4320
4321 context_switch(rq, prev, next); /* unlocks the rq */
4322 /*
4323 * The context switch have flipped the stack from under us
4324 * and restored the local variables which were saved when
4325 * this task called schedule() in the past. prev == current
4326 * is still correct, but it can be moved to another cpu/rq.
4327 */
4328 cpu = smp_processor_id();
4329 rq = cpu_rq(cpu);
4330 } else
4331 raw_spin_unlock_irq(&rq->lock);
4332
4333 post_schedule(rq);
4334
4335 preempt_enable_no_resched();
4336 if (need_resched())
4337 goto need_resched;
4338}
4339
4340static inline void sched_submit_work(struct task_struct *tsk)
4341{
4342 if (!tsk->state)
4343 return;
4344 /*
4345 * If we are going to sleep and we have plugged IO queued,
4346 * make sure to submit it to avoid deadlocks.
4347 */
4348 if (blk_needs_flush_plug(tsk))
4349 blk_schedule_flush_plug(tsk);
4350}
4351
4352asmlinkage void __sched schedule(void)
4353{
4354 struct task_struct *tsk = current;
4355
4356 sched_submit_work(tsk);
4357 __schedule();
4358}
4359EXPORT_SYMBOL(schedule);
4360
4361#ifdef CONFIG_MUTEX_SPIN_ON_OWNER
4362
4363static inline bool owner_running(struct mutex *lock, struct task_struct *owner)
4364{
4365 if (lock->owner != owner)
4366 return false;
4367
4368 /*
4369 * Ensure we emit the owner->on_cpu, dereference _after_ checking
4370 * lock->owner still matches owner, if that fails, owner might
4371 * point to free()d memory, if it still matches, the rcu_read_lock()
4372 * ensures the memory stays valid.
4373 */
4374 barrier();
4375
4376 return owner->on_cpu;
4377}
4378
4379/*
4380 * Look out! "owner" is an entirely speculative pointer
4381 * access and not reliable.
4382 */
4383int mutex_spin_on_owner(struct mutex *lock, struct task_struct *owner)
4384{
4385 if (!sched_feat(OWNER_SPIN))
4386 return 0;
4387
4388 rcu_read_lock();
4389 while (owner_running(lock, owner)) {
4390 if (need_resched())
4391 break;
4392
4393 arch_mutex_cpu_relax();
4394 }
4395 rcu_read_unlock();
4396
4397 /*
4398 * We break out the loop above on need_resched() and when the
4399 * owner changed, which is a sign for heavy contention. Return
4400 * success only when lock->owner is NULL.
4401 */
4402 return lock->owner == NULL;
4403}
4404#endif
4405
4406#ifdef CONFIG_PREEMPT
4407/*
4408 * this is the entry point to schedule() from in-kernel preemption
4409 * off of preempt_enable. Kernel preemptions off return from interrupt
4410 * occur there and call schedule directly.
4411 */
4412asmlinkage void __sched notrace preempt_schedule(void)
4413{
4414 struct thread_info *ti = current_thread_info();
4415
4416 /*
4417 * If there is a non-zero preempt_count or interrupts are disabled,
4418 * we do not want to preempt the current task. Just return..
4419 */
4420 if (likely(ti->preempt_count || irqs_disabled()))
4421 return;
4422
4423 do {
4424 add_preempt_count_notrace(PREEMPT_ACTIVE);
4425 __schedule();
4426 sub_preempt_count_notrace(PREEMPT_ACTIVE);
4427
4428 /*
4429 * Check again in case we missed a preemption opportunity
4430 * between schedule and now.
4431 */
4432 barrier();
4433 } while (need_resched());
4434}
4435EXPORT_SYMBOL(preempt_schedule);
4436
4437/*
4438 * this is the entry point to schedule() from kernel preemption
4439 * off of irq context.
4440 * Note, that this is called and return with irqs disabled. This will
4441 * protect us against recursive calling from irq.
4442 */
4443asmlinkage void __sched preempt_schedule_irq(void)
4444{
4445 struct thread_info *ti = current_thread_info();
4446
4447 /* Catch callers which need to be fixed */
4448 BUG_ON(ti->preempt_count || !irqs_disabled());
4449
4450 do {
4451 add_preempt_count(PREEMPT_ACTIVE);
4452 local_irq_enable();
4453 __schedule();
4454 local_irq_disable();
4455 sub_preempt_count(PREEMPT_ACTIVE);
4456
4457 /*
4458 * Check again in case we missed a preemption opportunity
4459 * between schedule and now.
4460 */
4461 barrier();
4462 } while (need_resched());
4463}
4464
4465#endif /* CONFIG_PREEMPT */
4466
4467int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
4468 void *key)
4469{
4470 return try_to_wake_up(curr->private, mode, wake_flags);
4471}
4472EXPORT_SYMBOL(default_wake_function);
4473
4474/*
4475 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4476 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4477 * number) then we wake all the non-exclusive tasks and one exclusive task.
4478 *
4479 * There are circumstances in which we can try to wake a task which has already
4480 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4481 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4482 */
4483static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4484 int nr_exclusive, int wake_flags, void *key)
4485{
4486 wait_queue_t *curr, *next;
4487
4488 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4489 unsigned flags = curr->flags;
4490
4491 if (curr->func(curr, mode, wake_flags, key) &&
4492 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4493 break;
4494 }
4495}
4496
4497/**
4498 * __wake_up - wake up threads blocked on a waitqueue.
4499 * @q: the waitqueue
4500 * @mode: which threads
4501 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4502 * @key: is directly passed to the wakeup function
4503 *
4504 * It may be assumed that this function implies a write memory barrier before
4505 * changing the task state if and only if any tasks are woken up.
4506 */
4507void __wake_up(wait_queue_head_t *q, unsigned int mode,
4508 int nr_exclusive, void *key)
4509{
4510 unsigned long flags;
4511
4512 spin_lock_irqsave(&q->lock, flags);
4513 __wake_up_common(q, mode, nr_exclusive, 0, key);
4514 spin_unlock_irqrestore(&q->lock, flags);
4515}
4516EXPORT_SYMBOL(__wake_up);
4517
4518/*
4519 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4520 */
4521void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4522{
4523 __wake_up_common(q, mode, 1, 0, NULL);
4524}
4525EXPORT_SYMBOL_GPL(__wake_up_locked);
4526
4527void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
4528{
4529 __wake_up_common(q, mode, 1, 0, key);
4530}
4531EXPORT_SYMBOL_GPL(__wake_up_locked_key);
4532
4533/**
4534 * __wake_up_sync_key - wake up threads blocked on a waitqueue.
4535 * @q: the waitqueue
4536 * @mode: which threads
4537 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4538 * @key: opaque value to be passed to wakeup targets
4539 *
4540 * The sync wakeup differs that the waker knows that it will schedule
4541 * away soon, so while the target thread will be woken up, it will not
4542 * be migrated to another CPU - ie. the two threads are 'synchronized'
4543 * with each other. This can prevent needless bouncing between CPUs.
4544 *
4545 * On UP it can prevent extra preemption.
4546 *
4547 * It may be assumed that this function implies a write memory barrier before
4548 * changing the task state if and only if any tasks are woken up.
4549 */
4550void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
4551 int nr_exclusive, void *key)
4552{
4553 unsigned long flags;
4554 int wake_flags = WF_SYNC;
4555
4556 if (unlikely(!q))
4557 return;
4558
4559 if (unlikely(!nr_exclusive))
4560 wake_flags = 0;
4561
4562 spin_lock_irqsave(&q->lock, flags);
4563 __wake_up_common(q, mode, nr_exclusive, wake_flags, key);
4564 spin_unlock_irqrestore(&q->lock, flags);
4565}
4566EXPORT_SYMBOL_GPL(__wake_up_sync_key);
4567
4568/*
4569 * __wake_up_sync - see __wake_up_sync_key()
4570 */
4571void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4572{
4573 __wake_up_sync_key(q, mode, nr_exclusive, NULL);
4574}
4575EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4576
4577/**
4578 * complete: - signals a single thread waiting on this completion
4579 * @x: holds the state of this particular completion
4580 *
4581 * This will wake up a single thread waiting on this completion. Threads will be
4582 * awakened in the same order in which they were queued.
4583 *
4584 * See also complete_all(), wait_for_completion() and related routines.
4585 *
4586 * It may be assumed that this function implies a write memory barrier before
4587 * changing the task state if and only if any tasks are woken up.
4588 */
4589void complete(struct completion *x)
4590{
4591 unsigned long flags;
4592
4593 spin_lock_irqsave(&x->wait.lock, flags);
4594 x->done++;
4595 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4596 spin_unlock_irqrestore(&x->wait.lock, flags);
4597}
4598EXPORT_SYMBOL(complete);
4599
4600/**
4601 * complete_all: - signals all threads waiting on this completion
4602 * @x: holds the state of this particular completion
4603 *
4604 * This will wake up all threads waiting on this particular completion event.
4605 *
4606 * It may be assumed that this function implies a write memory barrier before
4607 * changing the task state if and only if any tasks are woken up.
4608 */
4609void complete_all(struct completion *x)
4610{
4611 unsigned long flags;
4612
4613 spin_lock_irqsave(&x->wait.lock, flags);
4614 x->done += UINT_MAX/2;
4615 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4616 spin_unlock_irqrestore(&x->wait.lock, flags);
4617}
4618EXPORT_SYMBOL(complete_all);
4619
4620static inline long __sched
4621do_wait_for_common(struct completion *x, long timeout, int state)
4622{
4623 if (!x->done) {
4624 DECLARE_WAITQUEUE(wait, current);
4625
4626 __add_wait_queue_tail_exclusive(&x->wait, &wait);
4627 do {
4628 if (signal_pending_state(state, current)) {
4629 timeout = -ERESTARTSYS;
4630 break;
4631 }
4632 __set_current_state(state);
4633 spin_unlock_irq(&x->wait.lock);
4634 timeout = schedule_timeout(timeout);
4635 spin_lock_irq(&x->wait.lock);
4636 } while (!x->done && timeout);
4637 __remove_wait_queue(&x->wait, &wait);
4638 if (!x->done)
4639 return timeout;
4640 }
4641 x->done--;
4642 return timeout ?: 1;
4643}
4644
4645static long __sched
4646wait_for_common(struct completion *x, long timeout, int state)
4647{
4648 might_sleep();
4649
4650 spin_lock_irq(&x->wait.lock);
4651 timeout = do_wait_for_common(x, timeout, state);
4652 spin_unlock_irq(&x->wait.lock);
4653 return timeout;
4654}
4655
4656/**
4657 * wait_for_completion: - waits for completion of a task
4658 * @x: holds the state of this particular completion
4659 *
4660 * This waits to be signaled for completion of a specific task. It is NOT
4661 * interruptible and there is no timeout.
4662 *
4663 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
4664 * and interrupt capability. Also see complete().
4665 */
4666void __sched wait_for_completion(struct completion *x)
4667{
4668 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4669}
4670EXPORT_SYMBOL(wait_for_completion);
4671
4672/**
4673 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
4674 * @x: holds the state of this particular completion
4675 * @timeout: timeout value in jiffies
4676 *
4677 * This waits for either a completion of a specific task to be signaled or for a
4678 * specified timeout to expire. The timeout is in jiffies. It is not
4679 * interruptible.
4680 */
4681unsigned long __sched
4682wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4683{
4684 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4685}
4686EXPORT_SYMBOL(wait_for_completion_timeout);
4687
4688/**
4689 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
4690 * @x: holds the state of this particular completion
4691 *
4692 * This waits for completion of a specific task to be signaled. It is
4693 * interruptible.
4694 */
4695int __sched wait_for_completion_interruptible(struct completion *x)
4696{
4697 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4698 if (t == -ERESTARTSYS)
4699 return t;
4700 return 0;
4701}
4702EXPORT_SYMBOL(wait_for_completion_interruptible);
4703
4704/**
4705 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
4706 * @x: holds the state of this particular completion
4707 * @timeout: timeout value in jiffies
4708 *
4709 * This waits for either a completion of a specific task to be signaled or for a
4710 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
4711 */
4712long __sched
4713wait_for_completion_interruptible_timeout(struct completion *x,
4714 unsigned long timeout)
4715{
4716 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4717}
4718EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4719
4720/**
4721 * wait_for_completion_killable: - waits for completion of a task (killable)
4722 * @x: holds the state of this particular completion
4723 *
4724 * This waits to be signaled for completion of a specific task. It can be
4725 * interrupted by a kill signal.
4726 */
4727int __sched wait_for_completion_killable(struct completion *x)
4728{
4729 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4730 if (t == -ERESTARTSYS)
4731 return t;
4732 return 0;
4733}
4734EXPORT_SYMBOL(wait_for_completion_killable);
4735
4736/**
4737 * wait_for_completion_killable_timeout: - waits for completion of a task (w/(to,killable))
4738 * @x: holds the state of this particular completion
4739 * @timeout: timeout value in jiffies
4740 *
4741 * This waits for either a completion of a specific task to be
4742 * signaled or for a specified timeout to expire. It can be
4743 * interrupted by a kill signal. The timeout is in jiffies.
4744 */
4745long __sched
4746wait_for_completion_killable_timeout(struct completion *x,
4747 unsigned long timeout)
4748{
4749 return wait_for_common(x, timeout, TASK_KILLABLE);
4750}
4751EXPORT_SYMBOL(wait_for_completion_killable_timeout);
4752
4753/**
4754 * try_wait_for_completion - try to decrement a completion without blocking
4755 * @x: completion structure
4756 *
4757 * Returns: 0 if a decrement cannot be done without blocking
4758 * 1 if a decrement succeeded.
4759 *
4760 * If a completion is being used as a counting completion,
4761 * attempt to decrement the counter without blocking. This
4762 * enables us to avoid waiting if the resource the completion
4763 * is protecting is not available.
4764 */
4765bool try_wait_for_completion(struct completion *x)
4766{
4767 unsigned long flags;
4768 int ret = 1;
4769
4770 spin_lock_irqsave(&x->wait.lock, flags);
4771 if (!x->done)
4772 ret = 0;
4773 else
4774 x->done--;
4775 spin_unlock_irqrestore(&x->wait.lock, flags);
4776 return ret;
4777}
4778EXPORT_SYMBOL(try_wait_for_completion);
4779
4780/**
4781 * completion_done - Test to see if a completion has any waiters
4782 * @x: completion structure
4783 *
4784 * Returns: 0 if there are waiters (wait_for_completion() in progress)
4785 * 1 if there are no waiters.
4786 *
4787 */
4788bool completion_done(struct completion *x)
4789{
4790 unsigned long flags;
4791 int ret = 1;
4792
4793 spin_lock_irqsave(&x->wait.lock, flags);
4794 if (!x->done)
4795 ret = 0;
4796 spin_unlock_irqrestore(&x->wait.lock, flags);
4797 return ret;
4798}
4799EXPORT_SYMBOL(completion_done);
4800
4801static long __sched
4802sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4803{
4804 unsigned long flags;
4805 wait_queue_t wait;
4806
4807 init_waitqueue_entry(&wait, current);
4808
4809 __set_current_state(state);
4810
4811 spin_lock_irqsave(&q->lock, flags);
4812 __add_wait_queue(q, &wait);
4813 spin_unlock(&q->lock);
4814 timeout = schedule_timeout(timeout);
4815 spin_lock_irq(&q->lock);
4816 __remove_wait_queue(q, &wait);
4817 spin_unlock_irqrestore(&q->lock, flags);
4818
4819 return timeout;
4820}
4821
4822void __sched interruptible_sleep_on(wait_queue_head_t *q)
4823{
4824 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4825}
4826EXPORT_SYMBOL(interruptible_sleep_on);
4827
4828long __sched
4829interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4830{
4831 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4832}
4833EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4834
4835void __sched sleep_on(wait_queue_head_t *q)
4836{
4837 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4838}
4839EXPORT_SYMBOL(sleep_on);
4840
4841long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4842{
4843 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4844}
4845EXPORT_SYMBOL(sleep_on_timeout);
4846
4847#ifdef CONFIG_RT_MUTEXES
4848
4849/*
4850 * rt_mutex_setprio - set the current priority of a task
4851 * @p: task
4852 * @prio: prio value (kernel-internal form)
4853 *
4854 * This function changes the 'effective' priority of a task. It does
4855 * not touch ->normal_prio like __setscheduler().
4856 *
4857 * Used by the rt_mutex code to implement priority inheritance logic.
4858 */
4859void rt_mutex_setprio(struct task_struct *p, int prio)
4860{
4861 int oldprio, on_rq, running;
4862 struct rq *rq;
4863 const struct sched_class *prev_class;
4864
4865 BUG_ON(prio < 0 || prio > MAX_PRIO);
4866
4867 rq = __task_rq_lock(p);
4868
4869 trace_sched_pi_setprio(p, prio);
4870 oldprio = p->prio;
4871 prev_class = p->sched_class;
4872 on_rq = p->on_rq;
4873 running = task_current(rq, p);
4874 if (on_rq)
4875 dequeue_task(rq, p, 0);
4876 if (running)
4877 p->sched_class->put_prev_task(rq, p);
4878
4879 if (rt_prio(prio))
4880 p->sched_class = &rt_sched_class;
4881 else
4882 p->sched_class = &fair_sched_class;
4883
4884 p->prio = prio;
4885
4886 if (running)
4887 p->sched_class->set_curr_task(rq);
4888 if (on_rq)
4889 enqueue_task(rq, p, oldprio < prio ? ENQUEUE_HEAD : 0);
4890
4891 check_class_changed(rq, p, prev_class, oldprio);
4892 __task_rq_unlock(rq);
4893}
4894
4895#endif
4896
4897void set_user_nice(struct task_struct *p, long nice)
4898{
4899 int old_prio, delta, on_rq;
4900 unsigned long flags;
4901 struct rq *rq;
4902
4903 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4904 return;
4905 /*
4906 * We have to be careful, if called from sys_setpriority(),
4907 * the task might be in the middle of scheduling on another CPU.
4908 */
4909 rq = task_rq_lock(p, &flags);
4910 /*
4911 * The RT priorities are set via sched_setscheduler(), but we still
4912 * allow the 'normal' nice value to be set - but as expected
4913 * it wont have any effect on scheduling until the task is
4914 * SCHED_FIFO/SCHED_RR:
4915 */
4916 if (task_has_rt_policy(p)) {
4917 p->static_prio = NICE_TO_PRIO(nice);
4918 goto out_unlock;
4919 }
4920 on_rq = p->on_rq;
4921 if (on_rq)
4922 dequeue_task(rq, p, 0);
4923
4924 p->static_prio = NICE_TO_PRIO(nice);
4925 set_load_weight(p);
4926 old_prio = p->prio;
4927 p->prio = effective_prio(p);
4928 delta = p->prio - old_prio;
4929
4930 if (on_rq) {
4931 enqueue_task(rq, p, 0);
4932 /*
4933 * If the task increased its priority or is running and
4934 * lowered its priority, then reschedule its CPU:
4935 */
4936 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4937 resched_task(rq->curr);
4938 }
4939out_unlock:
4940 task_rq_unlock(rq, p, &flags);
4941}
4942EXPORT_SYMBOL(set_user_nice);
4943
4944/*
4945 * can_nice - check if a task can reduce its nice value
4946 * @p: task
4947 * @nice: nice value
4948 */
4949int can_nice(const struct task_struct *p, const int nice)
4950{
4951 /* convert nice value [19,-20] to rlimit style value [1,40] */
4952 int nice_rlim = 20 - nice;
4953
4954 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
4955 capable(CAP_SYS_NICE));
4956}
4957
4958#ifdef __ARCH_WANT_SYS_NICE
4959
4960/*
4961 * sys_nice - change the priority of the current process.
4962 * @increment: priority increment
4963 *
4964 * sys_setpriority is a more generic, but much slower function that
4965 * does similar things.
4966 */
4967SYSCALL_DEFINE1(nice, int, increment)
4968{
4969 long nice, retval;
4970
4971 /*
4972 * Setpriority might change our priority at the same moment.
4973 * We don't have to worry. Conceptually one call occurs first
4974 * and we have a single winner.
4975 */
4976 if (increment < -40)
4977 increment = -40;
4978 if (increment > 40)
4979 increment = 40;
4980
4981 nice = TASK_NICE(current) + increment;
4982 if (nice < -20)
4983 nice = -20;
4984 if (nice > 19)
4985 nice = 19;
4986
4987 if (increment < 0 && !can_nice(current, nice))
4988 return -EPERM;
4989
4990 retval = security_task_setnice(current, nice);
4991 if (retval)
4992 return retval;
4993
4994 set_user_nice(current, nice);
4995 return 0;
4996}
4997
4998#endif
4999
5000/**
5001 * task_prio - return the priority value of a given task.
5002 * @p: the task in question.
5003 *
5004 * This is the priority value as seen by users in /proc.
5005 * RT tasks are offset by -200. Normal tasks are centered
5006 * around 0, value goes from -16 to +15.
5007 */
5008int task_prio(const struct task_struct *p)
5009{
5010 return p->prio - MAX_RT_PRIO;
5011}
5012
5013/**
5014 * task_nice - return the nice value of a given task.
5015 * @p: the task in question.
5016 */
5017int task_nice(const struct task_struct *p)
5018{
5019 return TASK_NICE(p);
5020}
5021EXPORT_SYMBOL(task_nice);
5022
5023/**
5024 * idle_cpu - is a given cpu idle currently?
5025 * @cpu: the processor in question.
5026 */
5027int idle_cpu(int cpu)
5028{
5029 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
5030}
5031
5032/**
5033 * idle_task - return the idle task for a given cpu.
5034 * @cpu: the processor in question.
5035 */
5036struct task_struct *idle_task(int cpu)
5037{
5038 return cpu_rq(cpu)->idle;
5039}
5040
5041/**
5042 * find_process_by_pid - find a process with a matching PID value.
5043 * @pid: the pid in question.
5044 */
5045static struct task_struct *find_process_by_pid(pid_t pid)
5046{
5047 return pid ? find_task_by_vpid(pid) : current;
5048}
5049
5050/* Actually do priority change: must hold rq lock. */
5051static void
5052__setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
5053{
5054 p->policy = policy;
5055 p->rt_priority = prio;
5056 p->normal_prio = normal_prio(p);
5057 /* we are holding p->pi_lock already */
5058 p->prio = rt_mutex_getprio(p);
5059 if (rt_prio(p->prio))
5060 p->sched_class = &rt_sched_class;
5061 else
5062 p->sched_class = &fair_sched_class;
5063 set_load_weight(p);
5064}
5065
5066/*
5067 * check the target process has a UID that matches the current process's
5068 */
5069static bool check_same_owner(struct task_struct *p)
5070{
5071 const struct cred *cred = current_cred(), *pcred;
5072 bool match;
5073
5074 rcu_read_lock();
5075 pcred = __task_cred(p);
5076 if (cred->user->user_ns == pcred->user->user_ns)
5077 match = (cred->euid == pcred->euid ||
5078 cred->euid == pcred->uid);
5079 else
5080 match = false;
5081 rcu_read_unlock();
5082 return match;
5083}
5084
5085static int __sched_setscheduler(struct task_struct *p, int policy,
5086 const struct sched_param *param, bool user)
5087{
5088 int retval, oldprio, oldpolicy = -1, on_rq, running;
5089 unsigned long flags;
5090 const struct sched_class *prev_class;
5091 struct rq *rq;
5092 int reset_on_fork;
5093
5094 /* may grab non-irq protected spin_locks */
5095 BUG_ON(in_interrupt());
5096recheck:
5097 /* double check policy once rq lock held */
5098 if (policy < 0) {
5099 reset_on_fork = p->sched_reset_on_fork;
5100 policy = oldpolicy = p->policy;
5101 } else {
5102 reset_on_fork = !!(policy & SCHED_RESET_ON_FORK);
5103 policy &= ~SCHED_RESET_ON_FORK;
5104
5105 if (policy != SCHED_FIFO && policy != SCHED_RR &&
5106 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
5107 policy != SCHED_IDLE)
5108 return -EINVAL;
5109 }
5110
5111 /*
5112 * Valid priorities for SCHED_FIFO and SCHED_RR are
5113 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5114 * SCHED_BATCH and SCHED_IDLE is 0.
5115 */
5116 if (param->sched_priority < 0 ||
5117 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
5118 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
5119 return -EINVAL;
5120 if (rt_policy(policy) != (param->sched_priority != 0))
5121 return -EINVAL;
5122
5123 /*
5124 * Allow unprivileged RT tasks to decrease priority:
5125 */
5126 if (user && !capable(CAP_SYS_NICE)) {
5127 if (rt_policy(policy)) {
5128 unsigned long rlim_rtprio =
5129 task_rlimit(p, RLIMIT_RTPRIO);
5130
5131 /* can't set/change the rt policy */
5132 if (policy != p->policy && !rlim_rtprio)
5133 return -EPERM;
5134
5135 /* can't increase priority */
5136 if (param->sched_priority > p->rt_priority &&
5137 param->sched_priority > rlim_rtprio)
5138 return -EPERM;
5139 }
5140
5141 /*
5142 * Treat SCHED_IDLE as nice 20. Only allow a switch to
5143 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
5144 */
5145 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) {
5146 if (!can_nice(p, TASK_NICE(p)))
5147 return -EPERM;
5148 }
5149
5150 /* can't change other user's priorities */
5151 if (!check_same_owner(p))
5152 return -EPERM;
5153
5154 /* Normal users shall not reset the sched_reset_on_fork flag */
5155 if (p->sched_reset_on_fork && !reset_on_fork)
5156 return -EPERM;
5157 }
5158
5159 if (user) {
5160 retval = security_task_setscheduler(p);
5161 if (retval)
5162 return retval;
5163 }
5164
5165 /*
5166 * make sure no PI-waiters arrive (or leave) while we are
5167 * changing the priority of the task:
5168 *
5169 * To be able to change p->policy safely, the appropriate
5170 * runqueue lock must be held.
5171 */
5172 rq = task_rq_lock(p, &flags);
5173
5174 /*
5175 * Changing the policy of the stop threads its a very bad idea
5176 */
5177 if (p == rq->stop) {
5178 task_rq_unlock(rq, p, &flags);
5179 return -EINVAL;
5180 }
5181
5182 /*
5183 * If not changing anything there's no need to proceed further:
5184 */
5185 if (unlikely(policy == p->policy && (!rt_policy(policy) ||
5186 param->sched_priority == p->rt_priority))) {
5187
5188 __task_rq_unlock(rq);
5189 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5190 return 0;
5191 }
5192
5193#ifdef CONFIG_RT_GROUP_SCHED
5194 if (user) {
5195 /*
5196 * Do not allow realtime tasks into groups that have no runtime
5197 * assigned.
5198 */
5199 if (rt_bandwidth_enabled() && rt_policy(policy) &&
5200 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
5201 !task_group_is_autogroup(task_group(p))) {
5202 task_rq_unlock(rq, p, &flags);
5203 return -EPERM;
5204 }
5205 }
5206#endif
5207
5208 /* recheck policy now with rq lock held */
5209 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5210 policy = oldpolicy = -1;
5211 task_rq_unlock(rq, p, &flags);
5212 goto recheck;
5213 }
5214 on_rq = p->on_rq;
5215 running = task_current(rq, p);
5216 if (on_rq)
5217 deactivate_task(rq, p, 0);
5218 if (running)
5219 p->sched_class->put_prev_task(rq, p);
5220
5221 p->sched_reset_on_fork = reset_on_fork;
5222
5223 oldprio = p->prio;
5224 prev_class = p->sched_class;
5225 __setscheduler(rq, p, policy, param->sched_priority);
5226
5227 if (running)
5228 p->sched_class->set_curr_task(rq);
5229 if (on_rq)
5230 activate_task(rq, p, 0);
5231
5232 check_class_changed(rq, p, prev_class, oldprio);
5233 task_rq_unlock(rq, p, &flags);
5234
5235 rt_mutex_adjust_pi(p);
5236
5237 return 0;
5238}
5239
5240/**
5241 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5242 * @p: the task in question.
5243 * @policy: new policy.
5244 * @param: structure containing the new RT priority.
5245 *
5246 * NOTE that the task may be already dead.
5247 */
5248int sched_setscheduler(struct task_struct *p, int policy,
5249 const struct sched_param *param)
5250{
5251 return __sched_setscheduler(p, policy, param, true);
5252}
5253EXPORT_SYMBOL_GPL(sched_setscheduler);
5254
5255/**
5256 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
5257 * @p: the task in question.
5258 * @policy: new policy.
5259 * @param: structure containing the new RT priority.
5260 *
5261 * Just like sched_setscheduler, only don't bother checking if the
5262 * current context has permission. For example, this is needed in
5263 * stop_machine(): we create temporary high priority worker threads,
5264 * but our caller might not have that capability.
5265 */
5266int sched_setscheduler_nocheck(struct task_struct *p, int policy,
5267 const struct sched_param *param)
5268{
5269 return __sched_setscheduler(p, policy, param, false);
5270}
5271
5272static int
5273do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5274{
5275 struct sched_param lparam;
5276 struct task_struct *p;
5277 int retval;
5278
5279 if (!param || pid < 0)
5280 return -EINVAL;
5281 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5282 return -EFAULT;
5283
5284 rcu_read_lock();
5285 retval = -ESRCH;
5286 p = find_process_by_pid(pid);
5287 if (p != NULL)
5288 retval = sched_setscheduler(p, policy, &lparam);
5289 rcu_read_unlock();
5290
5291 return retval;
5292}
5293
5294/**
5295 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5296 * @pid: the pid in question.
5297 * @policy: new policy.
5298 * @param: structure containing the new RT priority.
5299 */
5300SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
5301 struct sched_param __user *, param)
5302{
5303 /* negative values for policy are not valid */
5304 if (policy < 0)
5305 return -EINVAL;
5306
5307 return do_sched_setscheduler(pid, policy, param);
5308}
5309
5310/**
5311 * sys_sched_setparam - set/change the RT priority of a thread
5312 * @pid: the pid in question.
5313 * @param: structure containing the new RT priority.
5314 */
5315SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
5316{
5317 return do_sched_setscheduler(pid, -1, param);
5318}
5319
5320/**
5321 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5322 * @pid: the pid in question.
5323 */
5324SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
5325{
5326 struct task_struct *p;
5327 int retval;
5328
5329 if (pid < 0)
5330 return -EINVAL;
5331
5332 retval = -ESRCH;
5333 rcu_read_lock();
5334 p = find_process_by_pid(pid);
5335 if (p) {
5336 retval = security_task_getscheduler(p);
5337 if (!retval)
5338 retval = p->policy
5339 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
5340 }
5341 rcu_read_unlock();
5342 return retval;
5343}
5344
5345/**
5346 * sys_sched_getparam - get the RT priority of a thread
5347 * @pid: the pid in question.
5348 * @param: structure containing the RT priority.
5349 */
5350SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
5351{
5352 struct sched_param lp;
5353 struct task_struct *p;
5354 int retval;
5355
5356 if (!param || pid < 0)
5357 return -EINVAL;
5358
5359 rcu_read_lock();
5360 p = find_process_by_pid(pid);
5361 retval = -ESRCH;
5362 if (!p)
5363 goto out_unlock;
5364
5365 retval = security_task_getscheduler(p);
5366 if (retval)
5367 goto out_unlock;
5368
5369 lp.sched_priority = p->rt_priority;
5370 rcu_read_unlock();
5371
5372 /*
5373 * This one might sleep, we cannot do it with a spinlock held ...
5374 */
5375 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
5376
5377 return retval;
5378
5379out_unlock:
5380 rcu_read_unlock();
5381 return retval;
5382}
5383
5384long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
5385{
5386 cpumask_var_t cpus_allowed, new_mask;
5387 struct task_struct *p;
5388 int retval;
5389
5390 get_online_cpus();
5391 rcu_read_lock();
5392
5393 p = find_process_by_pid(pid);
5394 if (!p) {
5395 rcu_read_unlock();
5396 put_online_cpus();
5397 return -ESRCH;
5398 }
5399
5400 /* Prevent p going away */
5401 get_task_struct(p);
5402 rcu_read_unlock();
5403
5404 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
5405 retval = -ENOMEM;
5406 goto out_put_task;
5407 }
5408 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
5409 retval = -ENOMEM;
5410 goto out_free_cpus_allowed;
5411 }
5412 retval = -EPERM;
5413 if (!check_same_owner(p) && !task_ns_capable(p, CAP_SYS_NICE))
5414 goto out_unlock;
5415
5416 retval = security_task_setscheduler(p);
5417 if (retval)
5418 goto out_unlock;
5419
5420 cpuset_cpus_allowed(p, cpus_allowed);
5421 cpumask_and(new_mask, in_mask, cpus_allowed);
5422again:
5423 retval = set_cpus_allowed_ptr(p, new_mask);
5424
5425 if (!retval) {
5426 cpuset_cpus_allowed(p, cpus_allowed);
5427 if (!cpumask_subset(new_mask, cpus_allowed)) {
5428 /*
5429 * We must have raced with a concurrent cpuset
5430 * update. Just reset the cpus_allowed to the
5431 * cpuset's cpus_allowed
5432 */
5433 cpumask_copy(new_mask, cpus_allowed);
5434 goto again;
5435 }
5436 }
5437out_unlock:
5438 free_cpumask_var(new_mask);
5439out_free_cpus_allowed:
5440 free_cpumask_var(cpus_allowed);
5441out_put_task:
5442 put_task_struct(p);
5443 put_online_cpus();
5444 return retval;
5445}
5446
5447static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5448 struct cpumask *new_mask)
5449{
5450 if (len < cpumask_size())
5451 cpumask_clear(new_mask);
5452 else if (len > cpumask_size())
5453 len = cpumask_size();
5454
5455 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5456}
5457
5458/**
5459 * sys_sched_setaffinity - set the cpu affinity of a process
5460 * @pid: pid of the process
5461 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5462 * @user_mask_ptr: user-space pointer to the new cpu mask
5463 */
5464SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
5465 unsigned long __user *, user_mask_ptr)
5466{
5467 cpumask_var_t new_mask;
5468 int retval;
5469
5470 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
5471 return -ENOMEM;
5472
5473 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
5474 if (retval == 0)
5475 retval = sched_setaffinity(pid, new_mask);
5476 free_cpumask_var(new_mask);
5477 return retval;
5478}
5479
5480long sched_getaffinity(pid_t pid, struct cpumask *mask)
5481{
5482 struct task_struct *p;
5483 unsigned long flags;
5484 int retval;
5485
5486 get_online_cpus();
5487 rcu_read_lock();
5488
5489 retval = -ESRCH;
5490 p = find_process_by_pid(pid);
5491 if (!p)
5492 goto out_unlock;
5493
5494 retval = security_task_getscheduler(p);
5495 if (retval)
5496 goto out_unlock;
5497
5498 raw_spin_lock_irqsave(&p->pi_lock, flags);
5499 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
5500 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
5501
5502out_unlock:
5503 rcu_read_unlock();
5504 put_online_cpus();
5505
5506 return retval;
5507}
5508
5509/**
5510 * sys_sched_getaffinity - get the cpu affinity of a process
5511 * @pid: pid of the process
5512 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5513 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5514 */
5515SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
5516 unsigned long __user *, user_mask_ptr)
5517{
5518 int ret;
5519 cpumask_var_t mask;
5520
5521 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
5522 return -EINVAL;
5523 if (len & (sizeof(unsigned long)-1))
5524 return -EINVAL;
5525
5526 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
5527 return -ENOMEM;
5528
5529 ret = sched_getaffinity(pid, mask);
5530 if (ret == 0) {
5531 size_t retlen = min_t(size_t, len, cpumask_size());
5532
5533 if (copy_to_user(user_mask_ptr, mask, retlen))
5534 ret = -EFAULT;
5535 else
5536 ret = retlen;
5537 }
5538 free_cpumask_var(mask);
5539
5540 return ret;
5541}
5542
5543/**
5544 * sys_sched_yield - yield the current processor to other threads.
5545 *
5546 * This function yields the current CPU to other tasks. If there are no
5547 * other threads running on this CPU then this function will return.
5548 */
5549SYSCALL_DEFINE0(sched_yield)
5550{
5551 struct rq *rq = this_rq_lock();
5552
5553 schedstat_inc(rq, yld_count);
5554 current->sched_class->yield_task(rq);
5555
5556 /*
5557 * Since we are going to call schedule() anyway, there's
5558 * no need to preempt or enable interrupts:
5559 */
5560 __release(rq->lock);
5561 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5562 do_raw_spin_unlock(&rq->lock);
5563 preempt_enable_no_resched();
5564
5565 schedule();
5566
5567 return 0;
5568}
5569
5570static inline int should_resched(void)
5571{
5572 return need_resched() && !(preempt_count() & PREEMPT_ACTIVE);
5573}
5574
5575static void __cond_resched(void)
5576{
5577 add_preempt_count(PREEMPT_ACTIVE);
5578 __schedule();
5579 sub_preempt_count(PREEMPT_ACTIVE);
5580}
5581
5582int __sched _cond_resched(void)
5583{
5584 if (should_resched()) {
5585 __cond_resched();
5586 return 1;
5587 }
5588 return 0;
5589}
5590EXPORT_SYMBOL(_cond_resched);
5591
5592/*
5593 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
5594 * call schedule, and on return reacquire the lock.
5595 *
5596 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5597 * operations here to prevent schedule() from being called twice (once via
5598 * spin_unlock(), once by hand).
5599 */
5600int __cond_resched_lock(spinlock_t *lock)
5601{
5602 int resched = should_resched();
5603 int ret = 0;
5604
5605 lockdep_assert_held(lock);
5606
5607 if (spin_needbreak(lock) || resched) {
5608 spin_unlock(lock);
5609 if (resched)
5610 __cond_resched();
5611 else
5612 cpu_relax();
5613 ret = 1;
5614 spin_lock(lock);
5615 }
5616 return ret;
5617}
5618EXPORT_SYMBOL(__cond_resched_lock);
5619
5620int __sched __cond_resched_softirq(void)
5621{
5622 BUG_ON(!in_softirq());
5623
5624 if (should_resched()) {
5625 local_bh_enable();
5626 __cond_resched();
5627 local_bh_disable();
5628 return 1;
5629 }
5630 return 0;
5631}
5632EXPORT_SYMBOL(__cond_resched_softirq);
5633
5634/**
5635 * yield - yield the current processor to other threads.
5636 *
5637 * This is a shortcut for kernel-space yielding - it marks the
5638 * thread runnable and calls sys_sched_yield().
5639 */
5640void __sched yield(void)
5641{
5642 set_current_state(TASK_RUNNING);
5643 sys_sched_yield();
5644}
5645EXPORT_SYMBOL(yield);
5646
5647/**
5648 * yield_to - yield the current processor to another thread in
5649 * your thread group, or accelerate that thread toward the
5650 * processor it's on.
5651 * @p: target task
5652 * @preempt: whether task preemption is allowed or not
5653 *
5654 * It's the caller's job to ensure that the target task struct
5655 * can't go away on us before we can do any checks.
5656 *
5657 * Returns true if we indeed boosted the target task.
5658 */
5659bool __sched yield_to(struct task_struct *p, bool preempt)
5660{
5661 struct task_struct *curr = current;
5662 struct rq *rq, *p_rq;
5663 unsigned long flags;
5664 bool yielded = 0;
5665
5666 local_irq_save(flags);
5667 rq = this_rq();
5668
5669again:
5670 p_rq = task_rq(p);
5671 double_rq_lock(rq, p_rq);
5672 while (task_rq(p) != p_rq) {
5673 double_rq_unlock(rq, p_rq);
5674 goto again;
5675 }
5676
5677 if (!curr->sched_class->yield_to_task)
5678 goto out;
5679
5680 if (curr->sched_class != p->sched_class)
5681 goto out;
5682
5683 if (task_running(p_rq, p) || p->state)
5684 goto out;
5685
5686 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
5687 if (yielded) {
5688 schedstat_inc(rq, yld_count);
5689 /*
5690 * Make p's CPU reschedule; pick_next_entity takes care of
5691 * fairness.
5692 */
5693 if (preempt && rq != p_rq)
5694 resched_task(p_rq->curr);
5695 }
5696
5697out:
5698 double_rq_unlock(rq, p_rq);
5699 local_irq_restore(flags);
5700
5701 if (yielded)
5702 schedule();
5703
5704 return yielded;
5705}
5706EXPORT_SYMBOL_GPL(yield_to);
5707
5708/*
5709 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5710 * that process accounting knows that this is a task in IO wait state.
5711 */
5712void __sched io_schedule(void)
5713{
5714 struct rq *rq = raw_rq();
5715
5716 delayacct_blkio_start();
5717 atomic_inc(&rq->nr_iowait);
5718 blk_flush_plug(current);
5719 current->in_iowait = 1;
5720 schedule();
5721 current->in_iowait = 0;
5722 atomic_dec(&rq->nr_iowait);
5723 delayacct_blkio_end();
5724}
5725EXPORT_SYMBOL(io_schedule);
5726
5727long __sched io_schedule_timeout(long timeout)
5728{
5729 struct rq *rq = raw_rq();
5730 long ret;
5731
5732 delayacct_blkio_start();
5733 atomic_inc(&rq->nr_iowait);
5734 blk_flush_plug(current);
5735 current->in_iowait = 1;
5736 ret = schedule_timeout(timeout);
5737 current->in_iowait = 0;
5738 atomic_dec(&rq->nr_iowait);
5739 delayacct_blkio_end();
5740 return ret;
5741}
5742
5743/**
5744 * sys_sched_get_priority_max - return maximum RT priority.
5745 * @policy: scheduling class.
5746 *
5747 * this syscall returns the maximum rt_priority that can be used
5748 * by a given scheduling class.
5749 */
5750SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5751{
5752 int ret = -EINVAL;
5753
5754 switch (policy) {
5755 case SCHED_FIFO:
5756 case SCHED_RR:
5757 ret = MAX_USER_RT_PRIO-1;
5758 break;
5759 case SCHED_NORMAL:
5760 case SCHED_BATCH:
5761 case SCHED_IDLE:
5762 ret = 0;
5763 break;
5764 }
5765 return ret;
5766}
5767
5768/**
5769 * sys_sched_get_priority_min - return minimum RT priority.
5770 * @policy: scheduling class.
5771 *
5772 * this syscall returns the minimum rt_priority that can be used
5773 * by a given scheduling class.
5774 */
5775SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5776{
5777 int ret = -EINVAL;
5778
5779 switch (policy) {
5780 case SCHED_FIFO:
5781 case SCHED_RR:
5782 ret = 1;
5783 break;
5784 case SCHED_NORMAL:
5785 case SCHED_BATCH:
5786 case SCHED_IDLE:
5787 ret = 0;
5788 }
5789 return ret;
5790}
5791
5792/**
5793 * sys_sched_rr_get_interval - return the default timeslice of a process.
5794 * @pid: pid of the process.
5795 * @interval: userspace pointer to the timeslice value.
5796 *
5797 * this syscall writes the default timeslice value of a given process
5798 * into the user-space timespec buffer. A value of '0' means infinity.
5799 */
5800SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5801 struct timespec __user *, interval)
5802{
5803 struct task_struct *p;
5804 unsigned int time_slice;
5805 unsigned long flags;
5806 struct rq *rq;
5807 int retval;
5808 struct timespec t;
5809
5810 if (pid < 0)
5811 return -EINVAL;
5812
5813 retval = -ESRCH;
5814 rcu_read_lock();
5815 p = find_process_by_pid(pid);
5816 if (!p)
5817 goto out_unlock;
5818
5819 retval = security_task_getscheduler(p);
5820 if (retval)
5821 goto out_unlock;
5822
5823 rq = task_rq_lock(p, &flags);
5824 time_slice = p->sched_class->get_rr_interval(rq, p);
5825 task_rq_unlock(rq, p, &flags);
5826
5827 rcu_read_unlock();
5828 jiffies_to_timespec(time_slice, &t);
5829 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5830 return retval;
5831
5832out_unlock:
5833 rcu_read_unlock();
5834 return retval;
5835}
5836
5837static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5838
5839void sched_show_task(struct task_struct *p)
5840{
5841 unsigned long free = 0;
5842 unsigned state;
5843
5844 state = p->state ? __ffs(p->state) + 1 : 0;
5845 printk(KERN_INFO "%-15.15s %c", p->comm,
5846 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5847#if BITS_PER_LONG == 32
5848 if (state == TASK_RUNNING)
5849 printk(KERN_CONT " running ");
5850 else
5851 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5852#else
5853 if (state == TASK_RUNNING)
5854 printk(KERN_CONT " running task ");
5855 else
5856 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5857#endif
5858#ifdef CONFIG_DEBUG_STACK_USAGE
5859 free = stack_not_used(p);
5860#endif
5861 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5862 task_pid_nr(p), task_pid_nr(p->real_parent),
5863 (unsigned long)task_thread_info(p)->flags);
5864
5865 show_stack(p, NULL);
5866}
5867
5868void show_state_filter(unsigned long state_filter)
5869{
5870 struct task_struct *g, *p;
5871
5872#if BITS_PER_LONG == 32
5873 printk(KERN_INFO
5874 " task PC stack pid father\n");
5875#else
5876 printk(KERN_INFO
5877 " task PC stack pid father\n");
5878#endif
5879 read_lock(&tasklist_lock);
5880 do_each_thread(g, p) {
5881 /*
5882 * reset the NMI-timeout, listing all files on a slow
5883 * console might take a lot of time:
5884 */
5885 touch_nmi_watchdog();
5886 if (!state_filter || (p->state & state_filter))
5887 sched_show_task(p);
5888 } while_each_thread(g, p);
5889
5890 touch_all_softlockup_watchdogs();
5891
5892#ifdef CONFIG_SCHED_DEBUG
5893 sysrq_sched_debug_show();
5894#endif
5895 read_unlock(&tasklist_lock);
5896 /*
5897 * Only show locks if all tasks are dumped:
5898 */
5899 if (!state_filter)
5900 debug_show_all_locks();
5901}
5902
5903void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5904{
5905 idle->sched_class = &idle_sched_class;
5906}
5907
5908/**
5909 * init_idle - set up an idle thread for a given CPU
5910 * @idle: task in question
5911 * @cpu: cpu the idle task belongs to
5912 *
5913 * NOTE: this function does not set the idle thread's NEED_RESCHED
5914 * flag, to make booting more robust.
5915 */
5916void __cpuinit init_idle(struct task_struct *idle, int cpu)
5917{
5918 struct rq *rq = cpu_rq(cpu);
5919 unsigned long flags;
5920
5921 raw_spin_lock_irqsave(&rq->lock, flags);
5922
5923 __sched_fork(idle);
5924 idle->state = TASK_RUNNING;
5925 idle->se.exec_start = sched_clock();
5926
5927 do_set_cpus_allowed(idle, cpumask_of(cpu));
5928 /*
5929 * We're having a chicken and egg problem, even though we are
5930 * holding rq->lock, the cpu isn't yet set to this cpu so the
5931 * lockdep check in task_group() will fail.
5932 *
5933 * Similar case to sched_fork(). / Alternatively we could
5934 * use task_rq_lock() here and obtain the other rq->lock.
5935 *
5936 * Silence PROVE_RCU
5937 */
5938 rcu_read_lock();
5939 __set_task_cpu(idle, cpu);
5940 rcu_read_unlock();
5941
5942 rq->curr = rq->idle = idle;
5943#if defined(CONFIG_SMP)
5944 idle->on_cpu = 1;
5945#endif
5946 raw_spin_unlock_irqrestore(&rq->lock, flags);
5947
5948 /* Set the preempt count _outside_ the spinlocks! */
5949 task_thread_info(idle)->preempt_count = 0;
5950
5951 /*
5952 * The idle tasks have their own, simple scheduling class:
5953 */
5954 idle->sched_class = &idle_sched_class;
5955 ftrace_graph_init_idle_task(idle, cpu);
5956}
5957
5958/*
5959 * In a system that switches off the HZ timer nohz_cpu_mask
5960 * indicates which cpus entered this state. This is used
5961 * in the rcu update to wait only for active cpus. For system
5962 * which do not switch off the HZ timer nohz_cpu_mask should
5963 * always be CPU_BITS_NONE.
5964 */
5965cpumask_var_t nohz_cpu_mask;
5966
5967/*
5968 * Increase the granularity value when there are more CPUs,
5969 * because with more CPUs the 'effective latency' as visible
5970 * to users decreases. But the relationship is not linear,
5971 * so pick a second-best guess by going with the log2 of the
5972 * number of CPUs.
5973 *
5974 * This idea comes from the SD scheduler of Con Kolivas:
5975 */
5976static int get_update_sysctl_factor(void)
5977{
5978 unsigned int cpus = min_t(int, num_online_cpus(), 8);
5979 unsigned int factor;
5980
5981 switch (sysctl_sched_tunable_scaling) {
5982 case SCHED_TUNABLESCALING_NONE:
5983 factor = 1;
5984 break;
5985 case SCHED_TUNABLESCALING_LINEAR:
5986 factor = cpus;
5987 break;
5988 case SCHED_TUNABLESCALING_LOG:
5989 default:
5990 factor = 1 + ilog2(cpus);
5991 break;
5992 }
5993
5994 return factor;
5995}
5996
5997static void update_sysctl(void)
5998{
5999 unsigned int factor = get_update_sysctl_factor();
6000
6001#define SET_SYSCTL(name) \
6002 (sysctl_##name = (factor) * normalized_sysctl_##name)
6003 SET_SYSCTL(sched_min_granularity);
6004 SET_SYSCTL(sched_latency);
6005 SET_SYSCTL(sched_wakeup_granularity);
6006#undef SET_SYSCTL
6007}
6008
6009static inline void sched_init_granularity(void)
6010{
6011 update_sysctl();
6012}
6013
6014#ifdef CONFIG_SMP
6015void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
6016{
6017 if (p->sched_class && p->sched_class->set_cpus_allowed)
6018 p->sched_class->set_cpus_allowed(p, new_mask);
6019 else {
6020 cpumask_copy(&p->cpus_allowed, new_mask);
6021 p->rt.nr_cpus_allowed = cpumask_weight(new_mask);
6022 }
6023}
6024
6025/*
6026 * This is how migration works:
6027 *
6028 * 1) we invoke migration_cpu_stop() on the target CPU using
6029 * stop_one_cpu().
6030 * 2) stopper starts to run (implicitly forcing the migrated thread
6031 * off the CPU)
6032 * 3) it checks whether the migrated task is still in the wrong runqueue.
6033 * 4) if it's in the wrong runqueue then the migration thread removes
6034 * it and puts it into the right queue.
6035 * 5) stopper completes and stop_one_cpu() returns and the migration
6036 * is done.
6037 */
6038
6039/*
6040 * Change a given task's CPU affinity. Migrate the thread to a
6041 * proper CPU and schedule it away if the CPU it's executing on
6042 * is removed from the allowed bitmask.
6043 *
6044 * NOTE: the caller must have a valid reference to the task, the
6045 * task must not exit() & deallocate itself prematurely. The
6046 * call is not atomic; no spinlocks may be held.
6047 */
6048int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
6049{
6050 unsigned long flags;
6051 struct rq *rq;
6052 unsigned int dest_cpu;
6053 int ret = 0;
6054
6055 rq = task_rq_lock(p, &flags);
6056
6057 if (cpumask_equal(&p->cpus_allowed, new_mask))
6058 goto out;
6059
6060 if (!cpumask_intersects(new_mask, cpu_active_mask)) {
6061 ret = -EINVAL;
6062 goto out;
6063 }
6064
6065 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current)) {
6066 ret = -EINVAL;
6067 goto out;
6068 }
6069
6070 do_set_cpus_allowed(p, new_mask);
6071
6072 /* Can the task run on the task's current CPU? If so, we're done */
6073 if (cpumask_test_cpu(task_cpu(p), new_mask))
6074 goto out;
6075
6076 dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
6077 if (p->on_rq) {
6078 struct migration_arg arg = { p, dest_cpu };
6079 /* Need help from migration thread: drop lock and wait. */
6080 task_rq_unlock(rq, p, &flags);
6081 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
6082 tlb_migrate_finish(p->mm);
6083 return 0;
6084 }
6085out:
6086 task_rq_unlock(rq, p, &flags);
6087
6088 return ret;
6089}
6090EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
6091
6092/*
6093 * Move (not current) task off this cpu, onto dest cpu. We're doing
6094 * this because either it can't run here any more (set_cpus_allowed()
6095 * away from this CPU, or CPU going down), or because we're
6096 * attempting to rebalance this task on exec (sched_exec).
6097 *
6098 * So we race with normal scheduler movements, but that's OK, as long
6099 * as the task is no longer on this CPU.
6100 *
6101 * Returns non-zero if task was successfully migrated.
6102 */
6103static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
6104{
6105 struct rq *rq_dest, *rq_src;
6106 int ret = 0;
6107
6108 if (unlikely(!cpu_active(dest_cpu)))
6109 return ret;
6110
6111 rq_src = cpu_rq(src_cpu);
6112 rq_dest = cpu_rq(dest_cpu);
6113
6114 raw_spin_lock(&p->pi_lock);
6115 double_rq_lock(rq_src, rq_dest);
6116 /* Already moved. */
6117 if (task_cpu(p) != src_cpu)
6118 goto done;
6119 /* Affinity changed (again). */
6120 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
6121 goto fail;
6122
6123 /*
6124 * If we're not on a rq, the next wake-up will ensure we're
6125 * placed properly.
6126 */
6127 if (p->on_rq) {
6128 deactivate_task(rq_src, p, 0);
6129 set_task_cpu(p, dest_cpu);
6130 activate_task(rq_dest, p, 0);
6131 check_preempt_curr(rq_dest, p, 0);
6132 }
6133done:
6134 ret = 1;
6135fail:
6136 double_rq_unlock(rq_src, rq_dest);
6137 raw_spin_unlock(&p->pi_lock);
6138 return ret;
6139}
6140
6141/*
6142 * migration_cpu_stop - this will be executed by a highprio stopper thread
6143 * and performs thread migration by bumping thread off CPU then
6144 * 'pushing' onto another runqueue.
6145 */
6146static int migration_cpu_stop(void *data)
6147{
6148 struct migration_arg *arg = data;
6149
6150 /*
6151 * The original target cpu might have gone down and we might
6152 * be on another cpu but it doesn't matter.
6153 */
6154 local_irq_disable();
6155 __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu);
6156 local_irq_enable();
6157 return 0;
6158}
6159
6160#ifdef CONFIG_HOTPLUG_CPU
6161
6162/*
6163 * Ensures that the idle task is using init_mm right before its cpu goes
6164 * offline.
6165 */
6166void idle_task_exit(void)
6167{
6168 struct mm_struct *mm = current->active_mm;
6169
6170 BUG_ON(cpu_online(smp_processor_id()));
6171
6172 if (mm != &init_mm)
6173 switch_mm(mm, &init_mm, current);
6174 mmdrop(mm);
6175}
6176
6177/*
6178 * While a dead CPU has no uninterruptible tasks queued at this point,
6179 * it might still have a nonzero ->nr_uninterruptible counter, because
6180 * for performance reasons the counter is not stricly tracking tasks to
6181 * their home CPUs. So we just add the counter to another CPU's counter,
6182 * to keep the global sum constant after CPU-down:
6183 */
6184static void migrate_nr_uninterruptible(struct rq *rq_src)
6185{
6186 struct rq *rq_dest = cpu_rq(cpumask_any(cpu_active_mask));
6187
6188 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
6189 rq_src->nr_uninterruptible = 0;
6190}
6191
6192/*
6193 * remove the tasks which were accounted by rq from calc_load_tasks.
6194 */
6195static void calc_global_load_remove(struct rq *rq)
6196{
6197 atomic_long_sub(rq->calc_load_active, &calc_load_tasks);
6198 rq->calc_load_active = 0;
6199}
6200
6201/*
6202 * Migrate all tasks from the rq, sleeping tasks will be migrated by
6203 * try_to_wake_up()->select_task_rq().
6204 *
6205 * Called with rq->lock held even though we'er in stop_machine() and
6206 * there's no concurrency possible, we hold the required locks anyway
6207 * because of lock validation efforts.
6208 */
6209static void migrate_tasks(unsigned int dead_cpu)
6210{
6211 struct rq *rq = cpu_rq(dead_cpu);
6212 struct task_struct *next, *stop = rq->stop;
6213 int dest_cpu;
6214
6215 /*
6216 * Fudge the rq selection such that the below task selection loop
6217 * doesn't get stuck on the currently eligible stop task.
6218 *
6219 * We're currently inside stop_machine() and the rq is either stuck
6220 * in the stop_machine_cpu_stop() loop, or we're executing this code,
6221 * either way we should never end up calling schedule() until we're
6222 * done here.
6223 */
6224 rq->stop = NULL;
6225
6226 for ( ; ; ) {
6227 /*
6228 * There's this thread running, bail when that's the only
6229 * remaining thread.
6230 */
6231 if (rq->nr_running == 1)
6232 break;
6233
6234 next = pick_next_task(rq);
6235 BUG_ON(!next);
6236 next->sched_class->put_prev_task(rq, next);
6237
6238 /* Find suitable destination for @next, with force if needed. */
6239 dest_cpu = select_fallback_rq(dead_cpu, next);
6240 raw_spin_unlock(&rq->lock);
6241
6242 __migrate_task(next, dead_cpu, dest_cpu);
6243
6244 raw_spin_lock(&rq->lock);
6245 }
6246
6247 rq->stop = stop;
6248}
6249
6250#endif /* CONFIG_HOTPLUG_CPU */
6251
6252#if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6253
6254static struct ctl_table sd_ctl_dir[] = {
6255 {
6256 .procname = "sched_domain",
6257 .mode = 0555,
6258 },
6259 {}
6260};
6261
6262static struct ctl_table sd_ctl_root[] = {
6263 {
6264 .procname = "kernel",
6265 .mode = 0555,
6266 .child = sd_ctl_dir,
6267 },
6268 {}
6269};
6270
6271static struct ctl_table *sd_alloc_ctl_entry(int n)
6272{
6273 struct ctl_table *entry =
6274 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
6275
6276 return entry;
6277}
6278
6279static void sd_free_ctl_entry(struct ctl_table **tablep)
6280{
6281 struct ctl_table *entry;
6282
6283 /*
6284 * In the intermediate directories, both the child directory and
6285 * procname are dynamically allocated and could fail but the mode
6286 * will always be set. In the lowest directory the names are
6287 * static strings and all have proc handlers.
6288 */
6289 for (entry = *tablep; entry->mode; entry++) {
6290 if (entry->child)
6291 sd_free_ctl_entry(&entry->child);
6292 if (entry->proc_handler == NULL)
6293 kfree(entry->procname);
6294 }
6295
6296 kfree(*tablep);
6297 *tablep = NULL;
6298}
6299
6300static void
6301set_table_entry(struct ctl_table *entry,
6302 const char *procname, void *data, int maxlen,
6303 mode_t mode, proc_handler *proc_handler)
6304{
6305 entry->procname = procname;
6306 entry->data = data;
6307 entry->maxlen = maxlen;
6308 entry->mode = mode;
6309 entry->proc_handler = proc_handler;
6310}
6311
6312static struct ctl_table *
6313sd_alloc_ctl_domain_table(struct sched_domain *sd)
6314{
6315 struct ctl_table *table = sd_alloc_ctl_entry(13);
6316
6317 if (table == NULL)
6318 return NULL;
6319
6320 set_table_entry(&table[0], "min_interval", &sd->min_interval,
6321 sizeof(long), 0644, proc_doulongvec_minmax);
6322 set_table_entry(&table[1], "max_interval", &sd->max_interval,
6323 sizeof(long), 0644, proc_doulongvec_minmax);
6324 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
6325 sizeof(int), 0644, proc_dointvec_minmax);
6326 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
6327 sizeof(int), 0644, proc_dointvec_minmax);
6328 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
6329 sizeof(int), 0644, proc_dointvec_minmax);
6330 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
6331 sizeof(int), 0644, proc_dointvec_minmax);
6332 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
6333 sizeof(int), 0644, proc_dointvec_minmax);
6334 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
6335 sizeof(int), 0644, proc_dointvec_minmax);
6336 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
6337 sizeof(int), 0644, proc_dointvec_minmax);
6338 set_table_entry(&table[9], "cache_nice_tries",
6339 &sd->cache_nice_tries,
6340 sizeof(int), 0644, proc_dointvec_minmax);
6341 set_table_entry(&table[10], "flags", &sd->flags,
6342 sizeof(int), 0644, proc_dointvec_minmax);
6343 set_table_entry(&table[11], "name", sd->name,
6344 CORENAME_MAX_SIZE, 0444, proc_dostring);
6345 /* &table[12] is terminator */
6346
6347 return table;
6348}
6349
6350static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
6351{
6352 struct ctl_table *entry, *table;
6353 struct sched_domain *sd;
6354 int domain_num = 0, i;
6355 char buf[32];
6356
6357 for_each_domain(cpu, sd)
6358 domain_num++;
6359 entry = table = sd_alloc_ctl_entry(domain_num + 1);
6360 if (table == NULL)
6361 return NULL;
6362
6363 i = 0;
6364 for_each_domain(cpu, sd) {
6365 snprintf(buf, 32, "domain%d", i);
6366 entry->procname = kstrdup(buf, GFP_KERNEL);
6367 entry->mode = 0555;
6368 entry->child = sd_alloc_ctl_domain_table(sd);
6369 entry++;
6370 i++;
6371 }
6372 return table;
6373}
6374
6375static struct ctl_table_header *sd_sysctl_header;
6376static void register_sched_domain_sysctl(void)
6377{
6378 int i, cpu_num = num_possible_cpus();
6379 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
6380 char buf[32];
6381
6382 WARN_ON(sd_ctl_dir[0].child);
6383 sd_ctl_dir[0].child = entry;
6384
6385 if (entry == NULL)
6386 return;
6387
6388 for_each_possible_cpu(i) {
6389 snprintf(buf, 32, "cpu%d", i);
6390 entry->procname = kstrdup(buf, GFP_KERNEL);
6391 entry->mode = 0555;
6392 entry->child = sd_alloc_ctl_cpu_table(i);
6393 entry++;
6394 }
6395
6396 WARN_ON(sd_sysctl_header);
6397 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
6398}
6399
6400/* may be called multiple times per register */
6401static void unregister_sched_domain_sysctl(void)
6402{
6403 if (sd_sysctl_header)
6404 unregister_sysctl_table(sd_sysctl_header);
6405 sd_sysctl_header = NULL;
6406 if (sd_ctl_dir[0].child)
6407 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6408}
6409#else
6410static void register_sched_domain_sysctl(void)
6411{
6412}
6413static void unregister_sched_domain_sysctl(void)
6414{
6415}
6416#endif
6417
6418static void set_rq_online(struct rq *rq)
6419{
6420 if (!rq->online) {
6421 const struct sched_class *class;
6422
6423 cpumask_set_cpu(rq->cpu, rq->rd->online);
6424 rq->online = 1;
6425
6426 for_each_class(class) {
6427 if (class->rq_online)
6428 class->rq_online(rq);
6429 }
6430 }
6431}
6432
6433static void set_rq_offline(struct rq *rq)
6434{
6435 if (rq->online) {
6436 const struct sched_class *class;
6437
6438 for_each_class(class) {
6439 if (class->rq_offline)
6440 class->rq_offline(rq);
6441 }
6442
6443 cpumask_clear_cpu(rq->cpu, rq->rd->online);
6444 rq->online = 0;
6445 }
6446}
6447
6448/*
6449 * migration_call - callback that gets triggered when a CPU is added.
6450 * Here we can start up the necessary migration thread for the new CPU.
6451 */
6452static int __cpuinit
6453migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6454{
6455 int cpu = (long)hcpu;
6456 unsigned long flags;
6457 struct rq *rq = cpu_rq(cpu);
6458
6459 switch (action & ~CPU_TASKS_FROZEN) {
6460
6461 case CPU_UP_PREPARE:
6462 rq->calc_load_update = calc_load_update;
6463 break;
6464
6465 case CPU_ONLINE:
6466 /* Update our root-domain */
6467 raw_spin_lock_irqsave(&rq->lock, flags);
6468 if (rq->rd) {
6469 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
6470
6471 set_rq_online(rq);
6472 }
6473 raw_spin_unlock_irqrestore(&rq->lock, flags);
6474 break;
6475
6476#ifdef CONFIG_HOTPLUG_CPU
6477 case CPU_DYING:
6478 sched_ttwu_pending();
6479 /* Update our root-domain */
6480 raw_spin_lock_irqsave(&rq->lock, flags);
6481 if (rq->rd) {
6482 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
6483 set_rq_offline(rq);
6484 }
6485 migrate_tasks(cpu);
6486 BUG_ON(rq->nr_running != 1); /* the migration thread */
6487 raw_spin_unlock_irqrestore(&rq->lock, flags);
6488
6489 migrate_nr_uninterruptible(rq);
6490 calc_global_load_remove(rq);
6491 break;
6492#endif
6493 }
6494
6495 update_max_interval();
6496
6497 return NOTIFY_OK;
6498}
6499
6500/*
6501 * Register at high priority so that task migration (migrate_all_tasks)
6502 * happens before everything else. This has to be lower priority than
6503 * the notifier in the perf_event subsystem, though.
6504 */
6505static struct notifier_block __cpuinitdata migration_notifier = {
6506 .notifier_call = migration_call,
6507 .priority = CPU_PRI_MIGRATION,
6508};
6509
6510static int __cpuinit sched_cpu_active(struct notifier_block *nfb,
6511 unsigned long action, void *hcpu)
6512{
6513 switch (action & ~CPU_TASKS_FROZEN) {
6514 case CPU_STARTING:
6515 case CPU_DOWN_FAILED:
6516 set_cpu_active((long)hcpu, true);
6517 return NOTIFY_OK;
6518 default:
6519 return NOTIFY_DONE;
6520 }
6521}
6522
6523static int __cpuinit sched_cpu_inactive(struct notifier_block *nfb,
6524 unsigned long action, void *hcpu)
6525{
6526 switch (action & ~CPU_TASKS_FROZEN) {
6527 case CPU_DOWN_PREPARE:
6528 set_cpu_active((long)hcpu, false);
6529 return NOTIFY_OK;
6530 default:
6531 return NOTIFY_DONE;
6532 }
6533}
6534
6535static int __init migration_init(void)
6536{
6537 void *cpu = (void *)(long)smp_processor_id();
6538 int err;
6539
6540 /* Initialize migration for the boot CPU */
6541 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6542 BUG_ON(err == NOTIFY_BAD);
6543 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6544 register_cpu_notifier(&migration_notifier);
6545
6546 /* Register cpu active notifiers */
6547 cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
6548 cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
6549
6550 return 0;
6551}
6552early_initcall(migration_init);
6553#endif
6554
6555#ifdef CONFIG_SMP
6556
6557static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
6558
6559#ifdef CONFIG_SCHED_DEBUG
6560
6561static __read_mostly int sched_domain_debug_enabled;
6562
6563static int __init sched_domain_debug_setup(char *str)
6564{
6565 sched_domain_debug_enabled = 1;
6566
6567 return 0;
6568}
6569early_param("sched_debug", sched_domain_debug_setup);
6570
6571static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6572 struct cpumask *groupmask)
6573{
6574 struct sched_group *group = sd->groups;
6575 char str[256];
6576
6577 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
6578 cpumask_clear(groupmask);
6579
6580 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6581
6582 if (!(sd->flags & SD_LOAD_BALANCE)) {
6583 printk("does not load-balance\n");
6584 if (sd->parent)
6585 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6586 " has parent");
6587 return -1;
6588 }
6589
6590 printk(KERN_CONT "span %s level %s\n", str, sd->name);
6591
6592 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
6593 printk(KERN_ERR "ERROR: domain->span does not contain "
6594 "CPU%d\n", cpu);
6595 }
6596 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
6597 printk(KERN_ERR "ERROR: domain->groups does not contain"
6598 " CPU%d\n", cpu);
6599 }
6600
6601 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6602 do {
6603 if (!group) {
6604 printk("\n");
6605 printk(KERN_ERR "ERROR: group is NULL\n");
6606 break;
6607 }
6608
6609 if (!group->sgp->power) {
6610 printk(KERN_CONT "\n");
6611 printk(KERN_ERR "ERROR: domain->cpu_power not "
6612 "set\n");
6613 break;
6614 }
6615
6616 if (!cpumask_weight(sched_group_cpus(group))) {
6617 printk(KERN_CONT "\n");
6618 printk(KERN_ERR "ERROR: empty group\n");
6619 break;
6620 }
6621
6622 if (cpumask_intersects(groupmask, sched_group_cpus(group))) {
6623 printk(KERN_CONT "\n");
6624 printk(KERN_ERR "ERROR: repeated CPUs\n");
6625 break;
6626 }
6627
6628 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
6629
6630 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
6631
6632 printk(KERN_CONT " %s", str);
6633 if (group->sgp->power != SCHED_POWER_SCALE) {
6634 printk(KERN_CONT " (cpu_power = %d)",
6635 group->sgp->power);
6636 }
6637
6638 group = group->next;
6639 } while (group != sd->groups);
6640 printk(KERN_CONT "\n");
6641
6642 if (!cpumask_equal(sched_domain_span(sd), groupmask))
6643 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6644
6645 if (sd->parent &&
6646 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
6647 printk(KERN_ERR "ERROR: parent span is not a superset "
6648 "of domain->span\n");
6649 return 0;
6650}
6651
6652static void sched_domain_debug(struct sched_domain *sd, int cpu)
6653{
6654 int level = 0;
6655
6656 if (!sched_domain_debug_enabled)
6657 return;
6658
6659 if (!sd) {
6660 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6661 return;
6662 }
6663
6664 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6665
6666 for (;;) {
6667 if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
6668 break;
6669 level++;
6670 sd = sd->parent;
6671 if (!sd)
6672 break;
6673 }
6674}
6675#else /* !CONFIG_SCHED_DEBUG */
6676# define sched_domain_debug(sd, cpu) do { } while (0)
6677#endif /* CONFIG_SCHED_DEBUG */
6678
6679static int sd_degenerate(struct sched_domain *sd)
6680{
6681 if (cpumask_weight(sched_domain_span(sd)) == 1)
6682 return 1;
6683
6684 /* Following flags need at least 2 groups */
6685 if (sd->flags & (SD_LOAD_BALANCE |
6686 SD_BALANCE_NEWIDLE |
6687 SD_BALANCE_FORK |
6688 SD_BALANCE_EXEC |
6689 SD_SHARE_CPUPOWER |
6690 SD_SHARE_PKG_RESOURCES)) {
6691 if (sd->groups != sd->groups->next)
6692 return 0;
6693 }
6694
6695 /* Following flags don't use groups */
6696 if (sd->flags & (SD_WAKE_AFFINE))
6697 return 0;
6698
6699 return 1;
6700}
6701
6702static int
6703sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6704{
6705 unsigned long cflags = sd->flags, pflags = parent->flags;
6706
6707 if (sd_degenerate(parent))
6708 return 1;
6709
6710 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
6711 return 0;
6712
6713 /* Flags needing groups don't count if only 1 group in parent */
6714 if (parent->groups == parent->groups->next) {
6715 pflags &= ~(SD_LOAD_BALANCE |
6716 SD_BALANCE_NEWIDLE |
6717 SD_BALANCE_FORK |
6718 SD_BALANCE_EXEC |
6719 SD_SHARE_CPUPOWER |
6720 SD_SHARE_PKG_RESOURCES);
6721 if (nr_node_ids == 1)
6722 pflags &= ~SD_SERIALIZE;
6723 }
6724 if (~cflags & pflags)
6725 return 0;
6726
6727 return 1;
6728}
6729
6730static void free_rootdomain(struct rcu_head *rcu)
6731{
6732 struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
6733
6734 cpupri_cleanup(&rd->cpupri);
6735 free_cpumask_var(rd->rto_mask);
6736 free_cpumask_var(rd->online);
6737 free_cpumask_var(rd->span);
6738 kfree(rd);
6739}
6740
6741static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6742{
6743 struct root_domain *old_rd = NULL;
6744 unsigned long flags;
6745
6746 raw_spin_lock_irqsave(&rq->lock, flags);
6747
6748 if (rq->rd) {
6749 old_rd = rq->rd;
6750
6751 if (cpumask_test_cpu(rq->cpu, old_rd->online))
6752 set_rq_offline(rq);
6753
6754 cpumask_clear_cpu(rq->cpu, old_rd->span);
6755
6756 /*
6757 * If we dont want to free the old_rt yet then
6758 * set old_rd to NULL to skip the freeing later
6759 * in this function:
6760 */
6761 if (!atomic_dec_and_test(&old_rd->refcount))
6762 old_rd = NULL;
6763 }
6764
6765 atomic_inc(&rd->refcount);
6766 rq->rd = rd;
6767
6768 cpumask_set_cpu(rq->cpu, rd->span);
6769 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
6770 set_rq_online(rq);
6771
6772 raw_spin_unlock_irqrestore(&rq->lock, flags);
6773
6774 if (old_rd)
6775 call_rcu_sched(&old_rd->rcu, free_rootdomain);
6776}
6777
6778static int init_rootdomain(struct root_domain *rd)
6779{
6780 memset(rd, 0, sizeof(*rd));
6781
6782 if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
6783 goto out;
6784 if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
6785 goto free_span;
6786 if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
6787 goto free_online;
6788
6789 if (cpupri_init(&rd->cpupri) != 0)
6790 goto free_rto_mask;
6791 return 0;
6792
6793free_rto_mask:
6794 free_cpumask_var(rd->rto_mask);
6795free_online:
6796 free_cpumask_var(rd->online);
6797free_span:
6798 free_cpumask_var(rd->span);
6799out:
6800 return -ENOMEM;
6801}
6802
6803static void init_defrootdomain(void)
6804{
6805 init_rootdomain(&def_root_domain);
6806
6807 atomic_set(&def_root_domain.refcount, 1);
6808}
6809
6810static struct root_domain *alloc_rootdomain(void)
6811{
6812 struct root_domain *rd;
6813
6814 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6815 if (!rd)
6816 return NULL;
6817
6818 if (init_rootdomain(rd) != 0) {
6819 kfree(rd);
6820 return NULL;
6821 }
6822
6823 return rd;
6824}
6825
6826static void free_sched_groups(struct sched_group *sg, int free_sgp)
6827{
6828 struct sched_group *tmp, *first;
6829
6830 if (!sg)
6831 return;
6832
6833 first = sg;
6834 do {
6835 tmp = sg->next;
6836
6837 if (free_sgp && atomic_dec_and_test(&sg->sgp->ref))
6838 kfree(sg->sgp);
6839
6840 kfree(sg);
6841 sg = tmp;
6842 } while (sg != first);
6843}
6844
6845static void free_sched_domain(struct rcu_head *rcu)
6846{
6847 struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
6848
6849 /*
6850 * If its an overlapping domain it has private groups, iterate and
6851 * nuke them all.
6852 */
6853 if (sd->flags & SD_OVERLAP) {
6854 free_sched_groups(sd->groups, 1);
6855 } else if (atomic_dec_and_test(&sd->groups->ref)) {
6856 kfree(sd->groups->sgp);
6857 kfree(sd->groups);
6858 }
6859 kfree(sd);
6860}
6861
6862static void destroy_sched_domain(struct sched_domain *sd, int cpu)
6863{
6864 call_rcu(&sd->rcu, free_sched_domain);
6865}
6866
6867static void destroy_sched_domains(struct sched_domain *sd, int cpu)
6868{
6869 for (; sd; sd = sd->parent)
6870 destroy_sched_domain(sd, cpu);
6871}
6872
6873/*
6874 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6875 * hold the hotplug lock.
6876 */
6877static void
6878cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6879{
6880 struct rq *rq = cpu_rq(cpu);
6881 struct sched_domain *tmp;
6882
6883 /* Remove the sched domains which do not contribute to scheduling. */
6884 for (tmp = sd; tmp; ) {
6885 struct sched_domain *parent = tmp->parent;
6886 if (!parent)
6887 break;
6888
6889 if (sd_parent_degenerate(tmp, parent)) {
6890 tmp->parent = parent->parent;
6891 if (parent->parent)
6892 parent->parent->child = tmp;
6893 destroy_sched_domain(parent, cpu);
6894 } else
6895 tmp = tmp->parent;
6896 }
6897
6898 if (sd && sd_degenerate(sd)) {
6899 tmp = sd;
6900 sd = sd->parent;
6901 destroy_sched_domain(tmp, cpu);
6902 if (sd)
6903 sd->child = NULL;
6904 }
6905
6906 sched_domain_debug(sd, cpu);
6907
6908 rq_attach_root(rq, rd);
6909 tmp = rq->sd;
6910 rcu_assign_pointer(rq->sd, sd);
6911 destroy_sched_domains(tmp, cpu);
6912}
6913
6914/* cpus with isolated domains */
6915static cpumask_var_t cpu_isolated_map;
6916
6917/* Setup the mask of cpus configured for isolated domains */
6918static int __init isolated_cpu_setup(char *str)
6919{
6920 alloc_bootmem_cpumask_var(&cpu_isolated_map);
6921 cpulist_parse(str, cpu_isolated_map);
6922 return 1;
6923}
6924
6925__setup("isolcpus=", isolated_cpu_setup);
6926
6927#define SD_NODES_PER_DOMAIN 16
6928
6929#ifdef CONFIG_NUMA
6930
6931/**
6932 * find_next_best_node - find the next node to include in a sched_domain
6933 * @node: node whose sched_domain we're building
6934 * @used_nodes: nodes already in the sched_domain
6935 *
6936 * Find the next node to include in a given scheduling domain. Simply
6937 * finds the closest node not already in the @used_nodes map.
6938 *
6939 * Should use nodemask_t.
6940 */
6941static int find_next_best_node(int node, nodemask_t *used_nodes)
6942{
6943 int i, n, val, min_val, best_node = -1;
6944
6945 min_val = INT_MAX;
6946
6947 for (i = 0; i < nr_node_ids; i++) {
6948 /* Start at @node */
6949 n = (node + i) % nr_node_ids;
6950
6951 if (!nr_cpus_node(n))
6952 continue;
6953
6954 /* Skip already used nodes */
6955 if (node_isset(n, *used_nodes))
6956 continue;
6957
6958 /* Simple min distance search */
6959 val = node_distance(node, n);
6960
6961 if (val < min_val) {
6962 min_val = val;
6963 best_node = n;
6964 }
6965 }
6966
6967 if (best_node != -1)
6968 node_set(best_node, *used_nodes);
6969 return best_node;
6970}
6971
6972/**
6973 * sched_domain_node_span - get a cpumask for a node's sched_domain
6974 * @node: node whose cpumask we're constructing
6975 * @span: resulting cpumask
6976 *
6977 * Given a node, construct a good cpumask for its sched_domain to span. It
6978 * should be one that prevents unnecessary balancing, but also spreads tasks
6979 * out optimally.
6980 */
6981static void sched_domain_node_span(int node, struct cpumask *span)
6982{
6983 nodemask_t used_nodes;
6984 int i;
6985
6986 cpumask_clear(span);
6987 nodes_clear(used_nodes);
6988
6989 cpumask_or(span, span, cpumask_of_node(node));
6990 node_set(node, used_nodes);
6991
6992 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6993 int next_node = find_next_best_node(node, &used_nodes);
6994 if (next_node < 0)
6995 break;
6996 cpumask_or(span, span, cpumask_of_node(next_node));
6997 }
6998}
6999
7000static const struct cpumask *cpu_node_mask(int cpu)
7001{
7002 lockdep_assert_held(&sched_domains_mutex);
7003
7004 sched_domain_node_span(cpu_to_node(cpu), sched_domains_tmpmask);
7005
7006 return sched_domains_tmpmask;
7007}
7008
7009static const struct cpumask *cpu_allnodes_mask(int cpu)
7010{
7011 return cpu_possible_mask;
7012}
7013#endif /* CONFIG_NUMA */
7014
7015static const struct cpumask *cpu_cpu_mask(int cpu)
7016{
7017 return cpumask_of_node(cpu_to_node(cpu));
7018}
7019
7020int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
7021
7022struct sd_data {
7023 struct sched_domain **__percpu sd;
7024 struct sched_group **__percpu sg;
7025 struct sched_group_power **__percpu sgp;
7026};
7027
7028struct s_data {
7029 struct sched_domain ** __percpu sd;
7030 struct root_domain *rd;
7031};
7032
7033enum s_alloc {
7034 sa_rootdomain,
7035 sa_sd,
7036 sa_sd_storage,
7037 sa_none,
7038};
7039
7040struct sched_domain_topology_level;
7041
7042typedef struct sched_domain *(*sched_domain_init_f)(struct sched_domain_topology_level *tl, int cpu);
7043typedef const struct cpumask *(*sched_domain_mask_f)(int cpu);
7044
7045#define SDTL_OVERLAP 0x01
7046
7047struct sched_domain_topology_level {
7048 sched_domain_init_f init;
7049 sched_domain_mask_f mask;
7050 int flags;
7051 struct sd_data data;
7052};
7053
7054static int
7055build_overlap_sched_groups(struct sched_domain *sd, int cpu)
7056{
7057 struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
7058 const struct cpumask *span = sched_domain_span(sd);
7059 struct cpumask *covered = sched_domains_tmpmask;
7060 struct sd_data *sdd = sd->private;
7061 struct sched_domain *child;
7062 int i;
7063
7064 cpumask_clear(covered);
7065
7066 for_each_cpu(i, span) {
7067 struct cpumask *sg_span;
7068
7069 if (cpumask_test_cpu(i, covered))
7070 continue;
7071
7072 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
7073 GFP_KERNEL, cpu_to_node(i));
7074
7075 if (!sg)
7076 goto fail;
7077
7078 sg_span = sched_group_cpus(sg);
7079
7080 child = *per_cpu_ptr(sdd->sd, i);
7081 if (child->child) {
7082 child = child->child;
7083 cpumask_copy(sg_span, sched_domain_span(child));
7084 } else
7085 cpumask_set_cpu(i, sg_span);
7086
7087 cpumask_or(covered, covered, sg_span);
7088
7089 sg->sgp = *per_cpu_ptr(sdd->sgp, cpumask_first(sg_span));
7090 atomic_inc(&sg->sgp->ref);
7091
7092 if (cpumask_test_cpu(cpu, sg_span))
7093 groups = sg;
7094
7095 if (!first)
7096 first = sg;
7097 if (last)
7098 last->next = sg;
7099 last = sg;
7100 last->next = first;
7101 }
7102 sd->groups = groups;
7103
7104 return 0;
7105
7106fail:
7107 free_sched_groups(first, 0);
7108
7109 return -ENOMEM;
7110}
7111
7112static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
7113{
7114 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
7115 struct sched_domain *child = sd->child;
7116
7117 if (child)
7118 cpu = cpumask_first(sched_domain_span(child));
7119
7120 if (sg) {
7121 *sg = *per_cpu_ptr(sdd->sg, cpu);
7122 (*sg)->sgp = *per_cpu_ptr(sdd->sgp, cpu);
7123 atomic_set(&(*sg)->sgp->ref, 1); /* for claim_allocations */
7124 }
7125
7126 return cpu;
7127}
7128
7129/*
7130 * build_sched_groups will build a circular linked list of the groups
7131 * covered by the given span, and will set each group's ->cpumask correctly,
7132 * and ->cpu_power to 0.
7133 *
7134 * Assumes the sched_domain tree is fully constructed
7135 */
7136static int
7137build_sched_groups(struct sched_domain *sd, int cpu)
7138{
7139 struct sched_group *first = NULL, *last = NULL;
7140 struct sd_data *sdd = sd->private;
7141 const struct cpumask *span = sched_domain_span(sd);
7142 struct cpumask *covered;
7143 int i;
7144
7145 get_group(cpu, sdd, &sd->groups);
7146 atomic_inc(&sd->groups->ref);
7147
7148 if (cpu != cpumask_first(sched_domain_span(sd)))
7149 return 0;
7150
7151 lockdep_assert_held(&sched_domains_mutex);
7152 covered = sched_domains_tmpmask;
7153
7154 cpumask_clear(covered);
7155
7156 for_each_cpu(i, span) {
7157 struct sched_group *sg;
7158 int group = get_group(i, sdd, &sg);
7159 int j;
7160
7161 if (cpumask_test_cpu(i, covered))
7162 continue;
7163
7164 cpumask_clear(sched_group_cpus(sg));
7165 sg->sgp->power = 0;
7166
7167 for_each_cpu(j, span) {
7168 if (get_group(j, sdd, NULL) != group)
7169 continue;
7170
7171 cpumask_set_cpu(j, covered);
7172 cpumask_set_cpu(j, sched_group_cpus(sg));
7173 }
7174
7175 if (!first)
7176 first = sg;
7177 if (last)
7178 last->next = sg;
7179 last = sg;
7180 }
7181 last->next = first;
7182
7183 return 0;
7184}
7185
7186/*
7187 * Initialize sched groups cpu_power.
7188 *
7189 * cpu_power indicates the capacity of sched group, which is used while
7190 * distributing the load between different sched groups in a sched domain.
7191 * Typically cpu_power for all the groups in a sched domain will be same unless
7192 * there are asymmetries in the topology. If there are asymmetries, group
7193 * having more cpu_power will pickup more load compared to the group having
7194 * less cpu_power.
7195 */
7196static void init_sched_groups_power(int cpu, struct sched_domain *sd)
7197{
7198 struct sched_group *sg = sd->groups;
7199
7200 WARN_ON(!sd || !sg);
7201
7202 do {
7203 sg->group_weight = cpumask_weight(sched_group_cpus(sg));
7204 sg = sg->next;
7205 } while (sg != sd->groups);
7206
7207 if (cpu != group_first_cpu(sg))
7208 return;
7209
7210 update_group_power(sd, cpu);
7211}
7212
7213/*
7214 * Initializers for schedule domains
7215 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
7216 */
7217
7218#ifdef CONFIG_SCHED_DEBUG
7219# define SD_INIT_NAME(sd, type) sd->name = #type
7220#else
7221# define SD_INIT_NAME(sd, type) do { } while (0)
7222#endif
7223
7224#define SD_INIT_FUNC(type) \
7225static noinline struct sched_domain * \
7226sd_init_##type(struct sched_domain_topology_level *tl, int cpu) \
7227{ \
7228 struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu); \
7229 *sd = SD_##type##_INIT; \
7230 SD_INIT_NAME(sd, type); \
7231 sd->private = &tl->data; \
7232 return sd; \
7233}
7234
7235SD_INIT_FUNC(CPU)
7236#ifdef CONFIG_NUMA
7237 SD_INIT_FUNC(ALLNODES)
7238 SD_INIT_FUNC(NODE)
7239#endif
7240#ifdef CONFIG_SCHED_SMT
7241 SD_INIT_FUNC(SIBLING)
7242#endif
7243#ifdef CONFIG_SCHED_MC
7244 SD_INIT_FUNC(MC)
7245#endif
7246#ifdef CONFIG_SCHED_BOOK
7247 SD_INIT_FUNC(BOOK)
7248#endif
7249
7250static int default_relax_domain_level = -1;
7251int sched_domain_level_max;
7252
7253static int __init setup_relax_domain_level(char *str)
7254{
7255 unsigned long val;
7256
7257 val = simple_strtoul(str, NULL, 0);
7258 if (val < sched_domain_level_max)
7259 default_relax_domain_level = val;
7260
7261 return 1;
7262}
7263__setup("relax_domain_level=", setup_relax_domain_level);
7264
7265static void set_domain_attribute(struct sched_domain *sd,
7266 struct sched_domain_attr *attr)
7267{
7268 int request;
7269
7270 if (!attr || attr->relax_domain_level < 0) {
7271 if (default_relax_domain_level < 0)
7272 return;
7273 else
7274 request = default_relax_domain_level;
7275 } else
7276 request = attr->relax_domain_level;
7277 if (request < sd->level) {
7278 /* turn off idle balance on this domain */
7279 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
7280 } else {
7281 /* turn on idle balance on this domain */
7282 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
7283 }
7284}
7285
7286static void __sdt_free(const struct cpumask *cpu_map);
7287static int __sdt_alloc(const struct cpumask *cpu_map);
7288
7289static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
7290 const struct cpumask *cpu_map)
7291{
7292 switch (what) {
7293 case sa_rootdomain:
7294 if (!atomic_read(&d->rd->refcount))
7295 free_rootdomain(&d->rd->rcu); /* fall through */
7296 case sa_sd:
7297 free_percpu(d->sd); /* fall through */
7298 case sa_sd_storage:
7299 __sdt_free(cpu_map); /* fall through */
7300 case sa_none:
7301 break;
7302 }
7303}
7304
7305static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
7306 const struct cpumask *cpu_map)
7307{
7308 memset(d, 0, sizeof(*d));
7309
7310 if (__sdt_alloc(cpu_map))
7311 return sa_sd_storage;
7312 d->sd = alloc_percpu(struct sched_domain *);
7313 if (!d->sd)
7314 return sa_sd_storage;
7315 d->rd = alloc_rootdomain();
7316 if (!d->rd)
7317 return sa_sd;
7318 return sa_rootdomain;
7319}
7320
7321/*
7322 * NULL the sd_data elements we've used to build the sched_domain and
7323 * sched_group structure so that the subsequent __free_domain_allocs()
7324 * will not free the data we're using.
7325 */
7326static void claim_allocations(int cpu, struct sched_domain *sd)
7327{
7328 struct sd_data *sdd = sd->private;
7329
7330 WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
7331 *per_cpu_ptr(sdd->sd, cpu) = NULL;
7332
7333 if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
7334 *per_cpu_ptr(sdd->sg, cpu) = NULL;
7335
7336 if (atomic_read(&(*per_cpu_ptr(sdd->sgp, cpu))->ref))
7337 *per_cpu_ptr(sdd->sgp, cpu) = NULL;
7338}
7339
7340#ifdef CONFIG_SCHED_SMT
7341static const struct cpumask *cpu_smt_mask(int cpu)
7342{
7343 return topology_thread_cpumask(cpu);
7344}
7345#endif
7346
7347/*
7348 * Topology list, bottom-up.
7349 */
7350static struct sched_domain_topology_level default_topology[] = {
7351#ifdef CONFIG_SCHED_SMT
7352 { sd_init_SIBLING, cpu_smt_mask, },
7353#endif
7354#ifdef CONFIG_SCHED_MC
7355 { sd_init_MC, cpu_coregroup_mask, },
7356#endif
7357#ifdef CONFIG_SCHED_BOOK
7358 { sd_init_BOOK, cpu_book_mask, },
7359#endif
7360 { sd_init_CPU, cpu_cpu_mask, },
7361#ifdef CONFIG_NUMA
7362 { sd_init_NODE, cpu_node_mask, SDTL_OVERLAP, },
7363 { sd_init_ALLNODES, cpu_allnodes_mask, },
7364#endif
7365 { NULL, },
7366};
7367
7368static struct sched_domain_topology_level *sched_domain_topology = default_topology;
7369
7370static int __sdt_alloc(const struct cpumask *cpu_map)
7371{
7372 struct sched_domain_topology_level *tl;
7373 int j;
7374
7375 for (tl = sched_domain_topology; tl->init; tl++) {
7376 struct sd_data *sdd = &tl->data;
7377
7378 sdd->sd = alloc_percpu(struct sched_domain *);
7379 if (!sdd->sd)
7380 return -ENOMEM;
7381
7382 sdd->sg = alloc_percpu(struct sched_group *);
7383 if (!sdd->sg)
7384 return -ENOMEM;
7385
7386 sdd->sgp = alloc_percpu(struct sched_group_power *);
7387 if (!sdd->sgp)
7388 return -ENOMEM;
7389
7390 for_each_cpu(j, cpu_map) {
7391 struct sched_domain *sd;
7392 struct sched_group *sg;
7393 struct sched_group_power *sgp;
7394
7395 sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
7396 GFP_KERNEL, cpu_to_node(j));
7397 if (!sd)
7398 return -ENOMEM;
7399
7400 *per_cpu_ptr(sdd->sd, j) = sd;
7401
7402 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
7403 GFP_KERNEL, cpu_to_node(j));
7404 if (!sg)
7405 return -ENOMEM;
7406
7407 *per_cpu_ptr(sdd->sg, j) = sg;
7408
7409 sgp = kzalloc_node(sizeof(struct sched_group_power),
7410 GFP_KERNEL, cpu_to_node(j));
7411 if (!sgp)
7412 return -ENOMEM;
7413
7414 *per_cpu_ptr(sdd->sgp, j) = sgp;
7415 }
7416 }
7417
7418 return 0;
7419}
7420
7421static void __sdt_free(const struct cpumask *cpu_map)
7422{
7423 struct sched_domain_topology_level *tl;
7424 int j;
7425
7426 for (tl = sched_domain_topology; tl->init; tl++) {
7427 struct sd_data *sdd = &tl->data;
7428
7429 for_each_cpu(j, cpu_map) {
7430 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, j);
7431 if (sd && (sd->flags & SD_OVERLAP))
7432 free_sched_groups(sd->groups, 0);
7433 kfree(*per_cpu_ptr(sdd->sd, j));
7434 kfree(*per_cpu_ptr(sdd->sg, j));
7435 kfree(*per_cpu_ptr(sdd->sgp, j));
7436 }
7437 free_percpu(sdd->sd);
7438 free_percpu(sdd->sg);
7439 free_percpu(sdd->sgp);
7440 }
7441}
7442
7443struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
7444 struct s_data *d, const struct cpumask *cpu_map,
7445 struct sched_domain_attr *attr, struct sched_domain *child,
7446 int cpu)
7447{
7448 struct sched_domain *sd = tl->init(tl, cpu);
7449 if (!sd)
7450 return child;
7451
7452 set_domain_attribute(sd, attr);
7453 cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
7454 if (child) {
7455 sd->level = child->level + 1;
7456 sched_domain_level_max = max(sched_domain_level_max, sd->level);
7457 child->parent = sd;
7458 }
7459 sd->child = child;
7460
7461 return sd;
7462}
7463
7464/*
7465 * Build sched domains for a given set of cpus and attach the sched domains
7466 * to the individual cpus
7467 */
7468static int build_sched_domains(const struct cpumask *cpu_map,
7469 struct sched_domain_attr *attr)
7470{
7471 enum s_alloc alloc_state = sa_none;
7472 struct sched_domain *sd;
7473 struct s_data d;
7474 int i, ret = -ENOMEM;
7475
7476 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
7477 if (alloc_state != sa_rootdomain)
7478 goto error;
7479
7480 /* Set up domains for cpus specified by the cpu_map. */
7481 for_each_cpu(i, cpu_map) {
7482 struct sched_domain_topology_level *tl;
7483
7484 sd = NULL;
7485 for (tl = sched_domain_topology; tl->init; tl++) {
7486 sd = build_sched_domain(tl, &d, cpu_map, attr, sd, i);
7487 if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
7488 sd->flags |= SD_OVERLAP;
7489 if (cpumask_equal(cpu_map, sched_domain_span(sd)))
7490 break;
7491 }
7492
7493 while (sd->child)
7494 sd = sd->child;
7495
7496 *per_cpu_ptr(d.sd, i) = sd;
7497 }
7498
7499 /* Build the groups for the domains */
7500 for_each_cpu(i, cpu_map) {
7501 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
7502 sd->span_weight = cpumask_weight(sched_domain_span(sd));
7503 if (sd->flags & SD_OVERLAP) {
7504 if (build_overlap_sched_groups(sd, i))
7505 goto error;
7506 } else {
7507 if (build_sched_groups(sd, i))
7508 goto error;
7509 }
7510 }
7511 }
7512
7513 /* Calculate CPU power for physical packages and nodes */
7514 for (i = nr_cpumask_bits-1; i >= 0; i--) {
7515 if (!cpumask_test_cpu(i, cpu_map))
7516 continue;
7517
7518 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
7519 claim_allocations(i, sd);
7520 init_sched_groups_power(i, sd);
7521 }
7522 }
7523
7524 /* Attach the domains */
7525 rcu_read_lock();
7526 for_each_cpu(i, cpu_map) {
7527 sd = *per_cpu_ptr(d.sd, i);
7528 cpu_attach_domain(sd, d.rd, i);
7529 }
7530 rcu_read_unlock();
7531
7532 ret = 0;
7533error:
7534 __free_domain_allocs(&d, alloc_state, cpu_map);
7535 return ret;
7536}
7537
7538static cpumask_var_t *doms_cur; /* current sched domains */
7539static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7540static struct sched_domain_attr *dattr_cur;
7541 /* attribues of custom domains in 'doms_cur' */
7542
7543/*
7544 * Special case: If a kmalloc of a doms_cur partition (array of
7545 * cpumask) fails, then fallback to a single sched domain,
7546 * as determined by the single cpumask fallback_doms.
7547 */
7548static cpumask_var_t fallback_doms;
7549
7550/*
7551 * arch_update_cpu_topology lets virtualized architectures update the
7552 * cpu core maps. It is supposed to return 1 if the topology changed
7553 * or 0 if it stayed the same.
7554 */
7555int __attribute__((weak)) arch_update_cpu_topology(void)
7556{
7557 return 0;
7558}
7559
7560cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
7561{
7562 int i;
7563 cpumask_var_t *doms;
7564
7565 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
7566 if (!doms)
7567 return NULL;
7568 for (i = 0; i < ndoms; i++) {
7569 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
7570 free_sched_domains(doms, i);
7571 return NULL;
7572 }
7573 }
7574 return doms;
7575}
7576
7577void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
7578{
7579 unsigned int i;
7580 for (i = 0; i < ndoms; i++)
7581 free_cpumask_var(doms[i]);
7582 kfree(doms);
7583}
7584
7585/*
7586 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7587 * For now this just excludes isolated cpus, but could be used to
7588 * exclude other special cases in the future.
7589 */
7590static int init_sched_domains(const struct cpumask *cpu_map)
7591{
7592 int err;
7593
7594 arch_update_cpu_topology();
7595 ndoms_cur = 1;
7596 doms_cur = alloc_sched_domains(ndoms_cur);
7597 if (!doms_cur)
7598 doms_cur = &fallback_doms;
7599 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
7600 dattr_cur = NULL;
7601 err = build_sched_domains(doms_cur[0], NULL);
7602 register_sched_domain_sysctl();
7603
7604 return err;
7605}
7606
7607/*
7608 * Detach sched domains from a group of cpus specified in cpu_map
7609 * These cpus will now be attached to the NULL domain
7610 */
7611static void detach_destroy_domains(const struct cpumask *cpu_map)
7612{
7613 int i;
7614
7615 rcu_read_lock();
7616 for_each_cpu(i, cpu_map)
7617 cpu_attach_domain(NULL, &def_root_domain, i);
7618 rcu_read_unlock();
7619}
7620
7621/* handle null as "default" */
7622static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7623 struct sched_domain_attr *new, int idx_new)
7624{
7625 struct sched_domain_attr tmp;
7626
7627 /* fast path */
7628 if (!new && !cur)
7629 return 1;
7630
7631 tmp = SD_ATTR_INIT;
7632 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7633 new ? (new + idx_new) : &tmp,
7634 sizeof(struct sched_domain_attr));
7635}
7636
7637/*
7638 * Partition sched domains as specified by the 'ndoms_new'
7639 * cpumasks in the array doms_new[] of cpumasks. This compares
7640 * doms_new[] to the current sched domain partitioning, doms_cur[].
7641 * It destroys each deleted domain and builds each new domain.
7642 *
7643 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
7644 * The masks don't intersect (don't overlap.) We should setup one
7645 * sched domain for each mask. CPUs not in any of the cpumasks will
7646 * not be load balanced. If the same cpumask appears both in the
7647 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7648 * it as it is.
7649 *
7650 * The passed in 'doms_new' should be allocated using
7651 * alloc_sched_domains. This routine takes ownership of it and will
7652 * free_sched_domains it when done with it. If the caller failed the
7653 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
7654 * and partition_sched_domains() will fallback to the single partition
7655 * 'fallback_doms', it also forces the domains to be rebuilt.
7656 *
7657 * If doms_new == NULL it will be replaced with cpu_online_mask.
7658 * ndoms_new == 0 is a special case for destroying existing domains,
7659 * and it will not create the default domain.
7660 *
7661 * Call with hotplug lock held
7662 */
7663void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
7664 struct sched_domain_attr *dattr_new)
7665{
7666 int i, j, n;
7667 int new_topology;
7668
7669 mutex_lock(&sched_domains_mutex);
7670
7671 /* always unregister in case we don't destroy any domains */
7672 unregister_sched_domain_sysctl();
7673
7674 /* Let architecture update cpu core mappings. */
7675 new_topology = arch_update_cpu_topology();
7676
7677 n = doms_new ? ndoms_new : 0;
7678
7679 /* Destroy deleted domains */
7680 for (i = 0; i < ndoms_cur; i++) {
7681 for (j = 0; j < n && !new_topology; j++) {
7682 if (cpumask_equal(doms_cur[i], doms_new[j])
7683 && dattrs_equal(dattr_cur, i, dattr_new, j))
7684 goto match1;
7685 }
7686 /* no match - a current sched domain not in new doms_new[] */
7687 detach_destroy_domains(doms_cur[i]);
7688match1:
7689 ;
7690 }
7691
7692 if (doms_new == NULL) {
7693 ndoms_cur = 0;
7694 doms_new = &fallback_doms;
7695 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
7696 WARN_ON_ONCE(dattr_new);
7697 }
7698
7699 /* Build new domains */
7700 for (i = 0; i < ndoms_new; i++) {
7701 for (j = 0; j < ndoms_cur && !new_topology; j++) {
7702 if (cpumask_equal(doms_new[i], doms_cur[j])
7703 && dattrs_equal(dattr_new, i, dattr_cur, j))
7704 goto match2;
7705 }
7706 /* no match - add a new doms_new */
7707 build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
7708match2:
7709 ;
7710 }
7711
7712 /* Remember the new sched domains */
7713 if (doms_cur != &fallback_doms)
7714 free_sched_domains(doms_cur, ndoms_cur);
7715 kfree(dattr_cur); /* kfree(NULL) is safe */
7716 doms_cur = doms_new;
7717 dattr_cur = dattr_new;
7718 ndoms_cur = ndoms_new;
7719
7720 register_sched_domain_sysctl();
7721
7722 mutex_unlock(&sched_domains_mutex);
7723}
7724
7725#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7726static void reinit_sched_domains(void)
7727{
7728 get_online_cpus();
7729
7730 /* Destroy domains first to force the rebuild */
7731 partition_sched_domains(0, NULL, NULL);
7732
7733 rebuild_sched_domains();
7734 put_online_cpus();
7735}
7736
7737static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7738{
7739 unsigned int level = 0;
7740
7741 if (sscanf(buf, "%u", &level) != 1)
7742 return -EINVAL;
7743
7744 /*
7745 * level is always be positive so don't check for
7746 * level < POWERSAVINGS_BALANCE_NONE which is 0
7747 * What happens on 0 or 1 byte write,
7748 * need to check for count as well?
7749 */
7750
7751 if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS)
7752 return -EINVAL;
7753
7754 if (smt)
7755 sched_smt_power_savings = level;
7756 else
7757 sched_mc_power_savings = level;
7758
7759 reinit_sched_domains();
7760
7761 return count;
7762}
7763
7764#ifdef CONFIG_SCHED_MC
7765static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
7766 struct sysdev_class_attribute *attr,
7767 char *page)
7768{
7769 return sprintf(page, "%u\n", sched_mc_power_savings);
7770}
7771static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
7772 struct sysdev_class_attribute *attr,
7773 const char *buf, size_t count)
7774{
7775 return sched_power_savings_store(buf, count, 0);
7776}
7777static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
7778 sched_mc_power_savings_show,
7779 sched_mc_power_savings_store);
7780#endif
7781
7782#ifdef CONFIG_SCHED_SMT
7783static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
7784 struct sysdev_class_attribute *attr,
7785 char *page)
7786{
7787 return sprintf(page, "%u\n", sched_smt_power_savings);
7788}
7789static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
7790 struct sysdev_class_attribute *attr,
7791 const char *buf, size_t count)
7792{
7793 return sched_power_savings_store(buf, count, 1);
7794}
7795static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
7796 sched_smt_power_savings_show,
7797 sched_smt_power_savings_store);
7798#endif
7799
7800int __init sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7801{
7802 int err = 0;
7803
7804#ifdef CONFIG_SCHED_SMT
7805 if (smt_capable())
7806 err = sysfs_create_file(&cls->kset.kobj,
7807 &attr_sched_smt_power_savings.attr);
7808#endif
7809#ifdef CONFIG_SCHED_MC
7810 if (!err && mc_capable())
7811 err = sysfs_create_file(&cls->kset.kobj,
7812 &attr_sched_mc_power_savings.attr);
7813#endif
7814 return err;
7815}
7816#endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
7817
7818/*
7819 * Update cpusets according to cpu_active mask. If cpusets are
7820 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7821 * around partition_sched_domains().
7822 */
7823static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
7824 void *hcpu)
7825{
7826 switch (action & ~CPU_TASKS_FROZEN) {
7827 case CPU_ONLINE:
7828 case CPU_DOWN_FAILED:
7829 cpuset_update_active_cpus();
7830 return NOTIFY_OK;
7831 default:
7832 return NOTIFY_DONE;
7833 }
7834}
7835
7836static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
7837 void *hcpu)
7838{
7839 switch (action & ~CPU_TASKS_FROZEN) {
7840 case CPU_DOWN_PREPARE:
7841 cpuset_update_active_cpus();
7842 return NOTIFY_OK;
7843 default:
7844 return NOTIFY_DONE;
7845 }
7846}
7847
7848static int update_runtime(struct notifier_block *nfb,
7849 unsigned long action, void *hcpu)
7850{
7851 int cpu = (int)(long)hcpu;
7852
7853 switch (action) {
7854 case CPU_DOWN_PREPARE:
7855 case CPU_DOWN_PREPARE_FROZEN:
7856 disable_runtime(cpu_rq(cpu));
7857 return NOTIFY_OK;
7858
7859 case CPU_DOWN_FAILED:
7860 case CPU_DOWN_FAILED_FROZEN:
7861 case CPU_ONLINE:
7862 case CPU_ONLINE_FROZEN:
7863 enable_runtime(cpu_rq(cpu));
7864 return NOTIFY_OK;
7865
7866 default:
7867 return NOTIFY_DONE;
7868 }
7869}
7870
7871void __init sched_init_smp(void)
7872{
7873 cpumask_var_t non_isolated_cpus;
7874
7875 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
7876 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
7877
7878 get_online_cpus();
7879 mutex_lock(&sched_domains_mutex);
7880 init_sched_domains(cpu_active_mask);
7881 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
7882 if (cpumask_empty(non_isolated_cpus))
7883 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
7884 mutex_unlock(&sched_domains_mutex);
7885 put_online_cpus();
7886
7887 hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
7888 hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
7889
7890 /* RT runtime code needs to handle some hotplug events */
7891 hotcpu_notifier(update_runtime, 0);
7892
7893 init_hrtick();
7894
7895 /* Move init over to a non-isolated CPU */
7896 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
7897 BUG();
7898 sched_init_granularity();
7899 free_cpumask_var(non_isolated_cpus);
7900
7901 init_sched_rt_class();
7902}
7903#else
7904void __init sched_init_smp(void)
7905{
7906 sched_init_granularity();
7907}
7908#endif /* CONFIG_SMP */
7909
7910const_debug unsigned int sysctl_timer_migration = 1;
7911
7912int in_sched_functions(unsigned long addr)
7913{
7914 return in_lock_functions(addr) ||
7915 (addr >= (unsigned long)__sched_text_start
7916 && addr < (unsigned long)__sched_text_end);
7917}
7918
7919static void init_cfs_rq(struct cfs_rq *cfs_rq)
7920{
7921 cfs_rq->tasks_timeline = RB_ROOT;
7922 INIT_LIST_HEAD(&cfs_rq->tasks);
7923 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7924#ifndef CONFIG_64BIT
7925 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
7926#endif
7927}
7928
7929static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7930{
7931 struct rt_prio_array *array;
7932 int i;
7933
7934 array = &rt_rq->active;
7935 for (i = 0; i < MAX_RT_PRIO; i++) {
7936 INIT_LIST_HEAD(array->queue + i);
7937 __clear_bit(i, array->bitmap);
7938 }
7939 /* delimiter for bitsearch: */
7940 __set_bit(MAX_RT_PRIO, array->bitmap);
7941
7942#if defined CONFIG_SMP
7943 rt_rq->highest_prio.curr = MAX_RT_PRIO;
7944 rt_rq->highest_prio.next = MAX_RT_PRIO;
7945 rt_rq->rt_nr_migratory = 0;
7946 rt_rq->overloaded = 0;
7947 plist_head_init(&rt_rq->pushable_tasks);
7948#endif
7949
7950 rt_rq->rt_time = 0;
7951 rt_rq->rt_throttled = 0;
7952 rt_rq->rt_runtime = 0;
7953 raw_spin_lock_init(&rt_rq->rt_runtime_lock);
7954}
7955
7956#ifdef CONFIG_FAIR_GROUP_SCHED
7957static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
7958 struct sched_entity *se, int cpu,
7959 struct sched_entity *parent)
7960{
7961 struct rq *rq = cpu_rq(cpu);
7962
7963 cfs_rq->tg = tg;
7964 cfs_rq->rq = rq;
7965#ifdef CONFIG_SMP
7966 /* allow initial update_cfs_load() to truncate */
7967 cfs_rq->load_stamp = 1;
7968#endif
7969
7970 tg->cfs_rq[cpu] = cfs_rq;
7971 tg->se[cpu] = se;
7972
7973 /* se could be NULL for root_task_group */
7974 if (!se)
7975 return;
7976
7977 if (!parent)
7978 se->cfs_rq = &rq->cfs;
7979 else
7980 se->cfs_rq = parent->my_q;
7981
7982 se->my_q = cfs_rq;
7983 update_load_set(&se->load, 0);
7984 se->parent = parent;
7985}
7986#endif
7987
7988#ifdef CONFIG_RT_GROUP_SCHED
7989static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
7990 struct sched_rt_entity *rt_se, int cpu,
7991 struct sched_rt_entity *parent)
7992{
7993 struct rq *rq = cpu_rq(cpu);
7994
7995 rt_rq->highest_prio.curr = MAX_RT_PRIO;
7996 rt_rq->rt_nr_boosted = 0;
7997 rt_rq->rq = rq;
7998 rt_rq->tg = tg;
7999
8000 tg->rt_rq[cpu] = rt_rq;
8001 tg->rt_se[cpu] = rt_se;
8002
8003 if (!rt_se)
8004 return;
8005
8006 if (!parent)
8007 rt_se->rt_rq = &rq->rt;
8008 else
8009 rt_se->rt_rq = parent->my_q;
8010
8011 rt_se->my_q = rt_rq;
8012 rt_se->parent = parent;
8013 INIT_LIST_HEAD(&rt_se->run_list);
8014}
8015#endif
8016
8017void __init sched_init(void)
8018{
8019 int i, j;
8020 unsigned long alloc_size = 0, ptr;
8021
8022#ifdef CONFIG_FAIR_GROUP_SCHED
8023 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8024#endif
8025#ifdef CONFIG_RT_GROUP_SCHED
8026 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8027#endif
8028#ifdef CONFIG_CPUMASK_OFFSTACK
8029 alloc_size += num_possible_cpus() * cpumask_size();
8030#endif
8031 if (alloc_size) {
8032 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
8033
8034#ifdef CONFIG_FAIR_GROUP_SCHED
8035 root_task_group.se = (struct sched_entity **)ptr;
8036 ptr += nr_cpu_ids * sizeof(void **);
8037
8038 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
8039 ptr += nr_cpu_ids * sizeof(void **);
8040
8041#endif /* CONFIG_FAIR_GROUP_SCHED */
8042#ifdef CONFIG_RT_GROUP_SCHED
8043 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
8044 ptr += nr_cpu_ids * sizeof(void **);
8045
8046 root_task_group.rt_rq = (struct rt_rq **)ptr;
8047 ptr += nr_cpu_ids * sizeof(void **);
8048
8049#endif /* CONFIG_RT_GROUP_SCHED */
8050#ifdef CONFIG_CPUMASK_OFFSTACK
8051 for_each_possible_cpu(i) {
8052 per_cpu(load_balance_tmpmask, i) = (void *)ptr;
8053 ptr += cpumask_size();
8054 }
8055#endif /* CONFIG_CPUMASK_OFFSTACK */
8056 }
8057
8058#ifdef CONFIG_SMP
8059 init_defrootdomain();
8060#endif
8061
8062 init_rt_bandwidth(&def_rt_bandwidth,
8063 global_rt_period(), global_rt_runtime());
8064
8065#ifdef CONFIG_RT_GROUP_SCHED
8066 init_rt_bandwidth(&root_task_group.rt_bandwidth,
8067 global_rt_period(), global_rt_runtime());
8068#endif /* CONFIG_RT_GROUP_SCHED */
8069
8070#ifdef CONFIG_CGROUP_SCHED
8071 list_add(&root_task_group.list, &task_groups);
8072 INIT_LIST_HEAD(&root_task_group.children);
8073 autogroup_init(&init_task);
8074#endif /* CONFIG_CGROUP_SCHED */
8075
8076 for_each_possible_cpu(i) {
8077 struct rq *rq;
8078
8079 rq = cpu_rq(i);
8080 raw_spin_lock_init(&rq->lock);
8081 rq->nr_running = 0;
8082 rq->calc_load_active = 0;
8083 rq->calc_load_update = jiffies + LOAD_FREQ;
8084 init_cfs_rq(&rq->cfs);
8085 init_rt_rq(&rq->rt, rq);
8086#ifdef CONFIG_FAIR_GROUP_SCHED
8087 root_task_group.shares = root_task_group_load;
8088 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
8089 /*
8090 * How much cpu bandwidth does root_task_group get?
8091 *
8092 * In case of task-groups formed thr' the cgroup filesystem, it
8093 * gets 100% of the cpu resources in the system. This overall
8094 * system cpu resource is divided among the tasks of
8095 * root_task_group and its child task-groups in a fair manner,
8096 * based on each entity's (task or task-group's) weight
8097 * (se->load.weight).
8098 *
8099 * In other words, if root_task_group has 10 tasks of weight
8100 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8101 * then A0's share of the cpu resource is:
8102 *
8103 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8104 *
8105 * We achieve this by letting root_task_group's tasks sit
8106 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
8107 */
8108 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
8109#endif /* CONFIG_FAIR_GROUP_SCHED */
8110
8111 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
8112#ifdef CONFIG_RT_GROUP_SCHED
8113 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
8114 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
8115#endif
8116
8117 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
8118 rq->cpu_load[j] = 0;
8119
8120 rq->last_load_update_tick = jiffies;
8121
8122#ifdef CONFIG_SMP
8123 rq->sd = NULL;
8124 rq->rd = NULL;
8125 rq->cpu_power = SCHED_POWER_SCALE;
8126 rq->post_schedule = 0;
8127 rq->active_balance = 0;
8128 rq->next_balance = jiffies;
8129 rq->push_cpu = 0;
8130 rq->cpu = i;
8131 rq->online = 0;
8132 rq->idle_stamp = 0;
8133 rq->avg_idle = 2*sysctl_sched_migration_cost;
8134 rq_attach_root(rq, &def_root_domain);
8135#ifdef CONFIG_NO_HZ
8136 rq->nohz_balance_kick = 0;
8137 init_sched_softirq_csd(&per_cpu(remote_sched_softirq_cb, i));
8138#endif
8139#endif
8140 init_rq_hrtick(rq);
8141 atomic_set(&rq->nr_iowait, 0);
8142 }
8143
8144 set_load_weight(&init_task);
8145
8146#ifdef CONFIG_PREEMPT_NOTIFIERS
8147 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
8148#endif
8149
8150#ifdef CONFIG_SMP
8151 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
8152#endif
8153
8154#ifdef CONFIG_RT_MUTEXES
8155 plist_head_init(&init_task.pi_waiters);
8156#endif
8157
8158 /*
8159 * The boot idle thread does lazy MMU switching as well:
8160 */
8161 atomic_inc(&init_mm.mm_count);
8162 enter_lazy_tlb(&init_mm, current);
8163
8164 /*
8165 * Make us the idle thread. Technically, schedule() should not be
8166 * called from this thread, however somewhere below it might be,
8167 * but because we are the idle thread, we just pick up running again
8168 * when this runqueue becomes "idle".
8169 */
8170 init_idle(current, smp_processor_id());
8171
8172 calc_load_update = jiffies + LOAD_FREQ;
8173
8174 /*
8175 * During early bootup we pretend to be a normal task:
8176 */
8177 current->sched_class = &fair_sched_class;
8178
8179 /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
8180 zalloc_cpumask_var(&nohz_cpu_mask, GFP_NOWAIT);
8181#ifdef CONFIG_SMP
8182 zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
8183#ifdef CONFIG_NO_HZ
8184 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
8185 alloc_cpumask_var(&nohz.grp_idle_mask, GFP_NOWAIT);
8186 atomic_set(&nohz.load_balancer, nr_cpu_ids);
8187 atomic_set(&nohz.first_pick_cpu, nr_cpu_ids);
8188 atomic_set(&nohz.second_pick_cpu, nr_cpu_ids);
8189 nohz.next_balance = jiffies;
8190#endif
8191 /* May be allocated at isolcpus cmdline parse time */
8192 if (cpu_isolated_map == NULL)
8193 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
8194#endif /* SMP */
8195
8196 scheduler_running = 1;
8197}
8198
8199#ifdef CONFIG_DEBUG_ATOMIC_SLEEP
8200static inline int preempt_count_equals(int preempt_offset)
8201{
8202 int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
8203
8204 return (nested == preempt_offset);
8205}
8206
8207static int __might_sleep_init_called;
8208int __init __might_sleep_init(void)
8209{
8210 __might_sleep_init_called = 1;
8211 return 0;
8212}
8213early_initcall(__might_sleep_init);
8214
8215void __might_sleep(const char *file, int line, int preempt_offset)
8216{
8217 static unsigned long prev_jiffy; /* ratelimiting */
8218
8219 if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) ||
8220 oops_in_progress)
8221 return;
8222 if (system_state != SYSTEM_RUNNING &&
8223 (!__might_sleep_init_called || system_state != SYSTEM_BOOTING))
8224 return;
8225 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8226 return;
8227 prev_jiffy = jiffies;
8228
8229 printk(KERN_ERR
8230 "BUG: sleeping function called from invalid context at %s:%d\n",
8231 file, line);
8232 printk(KERN_ERR
8233 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
8234 in_atomic(), irqs_disabled(),
8235 current->pid, current->comm);
8236
8237 debug_show_held_locks(current);
8238 if (irqs_disabled())
8239 print_irqtrace_events(current);
8240 dump_stack();
8241}
8242EXPORT_SYMBOL(__might_sleep);
8243#endif
8244
8245#ifdef CONFIG_MAGIC_SYSRQ
8246static void normalize_task(struct rq *rq, struct task_struct *p)
8247{
8248 const struct sched_class *prev_class = p->sched_class;
8249 int old_prio = p->prio;
8250 int on_rq;
8251
8252 on_rq = p->on_rq;
8253 if (on_rq)
8254 deactivate_task(rq, p, 0);
8255 __setscheduler(rq, p, SCHED_NORMAL, 0);
8256 if (on_rq) {
8257 activate_task(rq, p, 0);
8258 resched_task(rq->curr);
8259 }
8260
8261 check_class_changed(rq, p, prev_class, old_prio);
8262}
8263
8264void normalize_rt_tasks(void)
8265{
8266 struct task_struct *g, *p;
8267 unsigned long flags;
8268 struct rq *rq;
8269
8270 read_lock_irqsave(&tasklist_lock, flags);
8271 do_each_thread(g, p) {
8272 /*
8273 * Only normalize user tasks:
8274 */
8275 if (!p->mm)
8276 continue;
8277
8278 p->se.exec_start = 0;
8279#ifdef CONFIG_SCHEDSTATS
8280 p->se.statistics.wait_start = 0;
8281 p->se.statistics.sleep_start = 0;
8282 p->se.statistics.block_start = 0;
8283#endif
8284
8285 if (!rt_task(p)) {
8286 /*
8287 * Renice negative nice level userspace
8288 * tasks back to 0:
8289 */
8290 if (TASK_NICE(p) < 0 && p->mm)
8291 set_user_nice(p, 0);
8292 continue;
8293 }
8294
8295 raw_spin_lock(&p->pi_lock);
8296 rq = __task_rq_lock(p);
8297
8298 normalize_task(rq, p);
8299
8300 __task_rq_unlock(rq);
8301 raw_spin_unlock(&p->pi_lock);
8302 } while_each_thread(g, p);
8303
8304 read_unlock_irqrestore(&tasklist_lock, flags);
8305}
8306
8307#endif /* CONFIG_MAGIC_SYSRQ */
8308
8309#if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
8310/*
8311 * These functions are only useful for the IA64 MCA handling, or kdb.
8312 *
8313 * They can only be called when the whole system has been
8314 * stopped - every CPU needs to be quiescent, and no scheduling
8315 * activity can take place. Using them for anything else would
8316 * be a serious bug, and as a result, they aren't even visible
8317 * under any other configuration.
8318 */
8319
8320/**
8321 * curr_task - return the current task for a given cpu.
8322 * @cpu: the processor in question.
8323 *
8324 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8325 */
8326struct task_struct *curr_task(int cpu)
8327{
8328 return cpu_curr(cpu);
8329}
8330
8331#endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
8332
8333#ifdef CONFIG_IA64
8334/**
8335 * set_curr_task - set the current task for a given cpu.
8336 * @cpu: the processor in question.
8337 * @p: the task pointer to set.
8338 *
8339 * Description: This function must only be used when non-maskable interrupts
8340 * are serviced on a separate stack. It allows the architecture to switch the
8341 * notion of the current task on a cpu in a non-blocking manner. This function
8342 * must be called with all CPU's synchronized, and interrupts disabled, the
8343 * and caller must save the original value of the current task (see
8344 * curr_task() above) and restore that value before reenabling interrupts and
8345 * re-starting the system.
8346 *
8347 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8348 */
8349void set_curr_task(int cpu, struct task_struct *p)
8350{
8351 cpu_curr(cpu) = p;
8352}
8353
8354#endif
8355
8356#ifdef CONFIG_FAIR_GROUP_SCHED
8357static void free_fair_sched_group(struct task_group *tg)
8358{
8359 int i;
8360
8361 for_each_possible_cpu(i) {
8362 if (tg->cfs_rq)
8363 kfree(tg->cfs_rq[i]);
8364 if (tg->se)
8365 kfree(tg->se[i]);
8366 }
8367
8368 kfree(tg->cfs_rq);
8369 kfree(tg->se);
8370}
8371
8372static
8373int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8374{
8375 struct cfs_rq *cfs_rq;
8376 struct sched_entity *se;
8377 int i;
8378
8379 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8380 if (!tg->cfs_rq)
8381 goto err;
8382 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8383 if (!tg->se)
8384 goto err;
8385
8386 tg->shares = NICE_0_LOAD;
8387
8388 for_each_possible_cpu(i) {
8389 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
8390 GFP_KERNEL, cpu_to_node(i));
8391 if (!cfs_rq)
8392 goto err;
8393
8394 se = kzalloc_node(sizeof(struct sched_entity),
8395 GFP_KERNEL, cpu_to_node(i));
8396 if (!se)
8397 goto err_free_rq;
8398
8399 init_cfs_rq(cfs_rq);
8400 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
8401 }
8402
8403 return 1;
8404
8405err_free_rq:
8406 kfree(cfs_rq);
8407err:
8408 return 0;
8409}
8410
8411static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8412{
8413 struct rq *rq = cpu_rq(cpu);
8414 unsigned long flags;
8415
8416 /*
8417 * Only empty task groups can be destroyed; so we can speculatively
8418 * check on_list without danger of it being re-added.
8419 */
8420 if (!tg->cfs_rq[cpu]->on_list)
8421 return;
8422
8423 raw_spin_lock_irqsave(&rq->lock, flags);
8424 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
8425 raw_spin_unlock_irqrestore(&rq->lock, flags);
8426}
8427#else /* !CONFIG_FAIR_GROUP_SCHED */
8428static inline void free_fair_sched_group(struct task_group *tg)
8429{
8430}
8431
8432static inline
8433int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8434{
8435 return 1;
8436}
8437
8438static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8439{
8440}
8441#endif /* CONFIG_FAIR_GROUP_SCHED */
8442
8443#ifdef CONFIG_RT_GROUP_SCHED
8444static void free_rt_sched_group(struct task_group *tg)
8445{
8446 int i;
8447
8448 if (tg->rt_se)
8449 destroy_rt_bandwidth(&tg->rt_bandwidth);
8450
8451 for_each_possible_cpu(i) {
8452 if (tg->rt_rq)
8453 kfree(tg->rt_rq[i]);
8454 if (tg->rt_se)
8455 kfree(tg->rt_se[i]);
8456 }
8457
8458 kfree(tg->rt_rq);
8459 kfree(tg->rt_se);
8460}
8461
8462static
8463int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8464{
8465 struct rt_rq *rt_rq;
8466 struct sched_rt_entity *rt_se;
8467 int i;
8468
8469 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8470 if (!tg->rt_rq)
8471 goto err;
8472 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8473 if (!tg->rt_se)
8474 goto err;
8475
8476 init_rt_bandwidth(&tg->rt_bandwidth,
8477 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8478
8479 for_each_possible_cpu(i) {
8480 rt_rq = kzalloc_node(sizeof(struct rt_rq),
8481 GFP_KERNEL, cpu_to_node(i));
8482 if (!rt_rq)
8483 goto err;
8484
8485 rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
8486 GFP_KERNEL, cpu_to_node(i));
8487 if (!rt_se)
8488 goto err_free_rq;
8489
8490 init_rt_rq(rt_rq, cpu_rq(i));
8491 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
8492 init_tg_rt_entry(tg, rt_rq, rt_se, i, parent->rt_se[i]);
8493 }
8494
8495 return 1;
8496
8497err_free_rq:
8498 kfree(rt_rq);
8499err:
8500 return 0;
8501}
8502#else /* !CONFIG_RT_GROUP_SCHED */
8503static inline void free_rt_sched_group(struct task_group *tg)
8504{
8505}
8506
8507static inline
8508int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8509{
8510 return 1;
8511}
8512#endif /* CONFIG_RT_GROUP_SCHED */
8513
8514#ifdef CONFIG_CGROUP_SCHED
8515static void free_sched_group(struct task_group *tg)
8516{
8517 free_fair_sched_group(tg);
8518 free_rt_sched_group(tg);
8519 autogroup_free(tg);
8520 kfree(tg);
8521}
8522
8523/* allocate runqueue etc for a new task group */
8524struct task_group *sched_create_group(struct task_group *parent)
8525{
8526 struct task_group *tg;
8527 unsigned long flags;
8528
8529 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8530 if (!tg)
8531 return ERR_PTR(-ENOMEM);
8532
8533 if (!alloc_fair_sched_group(tg, parent))
8534 goto err;
8535
8536 if (!alloc_rt_sched_group(tg, parent))
8537 goto err;
8538
8539 spin_lock_irqsave(&task_group_lock, flags);
8540 list_add_rcu(&tg->list, &task_groups);
8541
8542 WARN_ON(!parent); /* root should already exist */
8543
8544 tg->parent = parent;
8545 INIT_LIST_HEAD(&tg->children);
8546 list_add_rcu(&tg->siblings, &parent->children);
8547 spin_unlock_irqrestore(&task_group_lock, flags);
8548
8549 return tg;
8550
8551err:
8552 free_sched_group(tg);
8553 return ERR_PTR(-ENOMEM);
8554}
8555
8556/* rcu callback to free various structures associated with a task group */
8557static void free_sched_group_rcu(struct rcu_head *rhp)
8558{
8559 /* now it should be safe to free those cfs_rqs */
8560 free_sched_group(container_of(rhp, struct task_group, rcu));
8561}
8562
8563/* Destroy runqueue etc associated with a task group */
8564void sched_destroy_group(struct task_group *tg)
8565{
8566 unsigned long flags;
8567 int i;
8568
8569 /* end participation in shares distribution */
8570 for_each_possible_cpu(i)
8571 unregister_fair_sched_group(tg, i);
8572
8573 spin_lock_irqsave(&task_group_lock, flags);
8574 list_del_rcu(&tg->list);
8575 list_del_rcu(&tg->siblings);
8576 spin_unlock_irqrestore(&task_group_lock, flags);
8577
8578 /* wait for possible concurrent references to cfs_rqs complete */
8579 call_rcu(&tg->rcu, free_sched_group_rcu);
8580}
8581
8582/* change task's runqueue when it moves between groups.
8583 * The caller of this function should have put the task in its new group
8584 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8585 * reflect its new group.
8586 */
8587void sched_move_task(struct task_struct *tsk)
8588{
8589 int on_rq, running;
8590 unsigned long flags;
8591 struct rq *rq;
8592
8593 rq = task_rq_lock(tsk, &flags);
8594
8595 running = task_current(rq, tsk);
8596 on_rq = tsk->on_rq;
8597
8598 if (on_rq)
8599 dequeue_task(rq, tsk, 0);
8600 if (unlikely(running))
8601 tsk->sched_class->put_prev_task(rq, tsk);
8602
8603#ifdef CONFIG_FAIR_GROUP_SCHED
8604 if (tsk->sched_class->task_move_group)
8605 tsk->sched_class->task_move_group(tsk, on_rq);
8606 else
8607#endif
8608 set_task_rq(tsk, task_cpu(tsk));
8609
8610 if (unlikely(running))
8611 tsk->sched_class->set_curr_task(rq);
8612 if (on_rq)
8613 enqueue_task(rq, tsk, 0);
8614
8615 task_rq_unlock(rq, tsk, &flags);
8616}
8617#endif /* CONFIG_CGROUP_SCHED */
8618
8619#ifdef CONFIG_FAIR_GROUP_SCHED
8620static DEFINE_MUTEX(shares_mutex);
8621
8622int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8623{
8624 int i;
8625 unsigned long flags;
8626
8627 /*
8628 * We can't change the weight of the root cgroup.
8629 */
8630 if (!tg->se[0])
8631 return -EINVAL;
8632
8633 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
8634
8635 mutex_lock(&shares_mutex);
8636 if (tg->shares == shares)
8637 goto done;
8638
8639 tg->shares = shares;
8640 for_each_possible_cpu(i) {
8641 struct rq *rq = cpu_rq(i);
8642 struct sched_entity *se;
8643
8644 se = tg->se[i];
8645 /* Propagate contribution to hierarchy */
8646 raw_spin_lock_irqsave(&rq->lock, flags);
8647 for_each_sched_entity(se)
8648 update_cfs_shares(group_cfs_rq(se));
8649 raw_spin_unlock_irqrestore(&rq->lock, flags);
8650 }
8651
8652done:
8653 mutex_unlock(&shares_mutex);
8654 return 0;
8655}
8656
8657unsigned long sched_group_shares(struct task_group *tg)
8658{
8659 return tg->shares;
8660}
8661#endif
8662
8663#ifdef CONFIG_RT_GROUP_SCHED
8664/*
8665 * Ensure that the real time constraints are schedulable.
8666 */
8667static DEFINE_MUTEX(rt_constraints_mutex);
8668
8669static unsigned long to_ratio(u64 period, u64 runtime)
8670{
8671 if (runtime == RUNTIME_INF)
8672 return 1ULL << 20;
8673
8674 return div64_u64(runtime << 20, period);
8675}
8676
8677/* Must be called with tasklist_lock held */
8678static inline int tg_has_rt_tasks(struct task_group *tg)
8679{
8680 struct task_struct *g, *p;
8681
8682 do_each_thread(g, p) {
8683 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8684 return 1;
8685 } while_each_thread(g, p);
8686
8687 return 0;
8688}
8689
8690struct rt_schedulable_data {
8691 struct task_group *tg;
8692 u64 rt_period;
8693 u64 rt_runtime;
8694};
8695
8696static int tg_schedulable(struct task_group *tg, void *data)
8697{
8698 struct rt_schedulable_data *d = data;
8699 struct task_group *child;
8700 unsigned long total, sum = 0;
8701 u64 period, runtime;
8702
8703 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8704 runtime = tg->rt_bandwidth.rt_runtime;
8705
8706 if (tg == d->tg) {
8707 period = d->rt_period;
8708 runtime = d->rt_runtime;
8709 }
8710
8711 /*
8712 * Cannot have more runtime than the period.
8713 */
8714 if (runtime > period && runtime != RUNTIME_INF)
8715 return -EINVAL;
8716
8717 /*
8718 * Ensure we don't starve existing RT tasks.
8719 */
8720 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
8721 return -EBUSY;
8722
8723 total = to_ratio(period, runtime);
8724
8725 /*
8726 * Nobody can have more than the global setting allows.
8727 */
8728 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
8729 return -EINVAL;
8730
8731 /*
8732 * The sum of our children's runtime should not exceed our own.
8733 */
8734 list_for_each_entry_rcu(child, &tg->children, siblings) {
8735 period = ktime_to_ns(child->rt_bandwidth.rt_period);
8736 runtime = child->rt_bandwidth.rt_runtime;
8737
8738 if (child == d->tg) {
8739 period = d->rt_period;
8740 runtime = d->rt_runtime;
8741 }
8742
8743 sum += to_ratio(period, runtime);
8744 }
8745
8746 if (sum > total)
8747 return -EINVAL;
8748
8749 return 0;
8750}
8751
8752static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8753{
8754 struct rt_schedulable_data data = {
8755 .tg = tg,
8756 .rt_period = period,
8757 .rt_runtime = runtime,
8758 };
8759
8760 return walk_tg_tree(tg_schedulable, tg_nop, &data);
8761}
8762
8763static int tg_set_bandwidth(struct task_group *tg,
8764 u64 rt_period, u64 rt_runtime)
8765{
8766 int i, err = 0;
8767
8768 mutex_lock(&rt_constraints_mutex);
8769 read_lock(&tasklist_lock);
8770 err = __rt_schedulable(tg, rt_period, rt_runtime);
8771 if (err)
8772 goto unlock;
8773
8774 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8775 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8776 tg->rt_bandwidth.rt_runtime = rt_runtime;
8777
8778 for_each_possible_cpu(i) {
8779 struct rt_rq *rt_rq = tg->rt_rq[i];
8780
8781 raw_spin_lock(&rt_rq->rt_runtime_lock);
8782 rt_rq->rt_runtime = rt_runtime;
8783 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8784 }
8785 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8786unlock:
8787 read_unlock(&tasklist_lock);
8788 mutex_unlock(&rt_constraints_mutex);
8789
8790 return err;
8791}
8792
8793int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8794{
8795 u64 rt_runtime, rt_period;
8796
8797 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8798 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8799 if (rt_runtime_us < 0)
8800 rt_runtime = RUNTIME_INF;
8801
8802 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8803}
8804
8805long sched_group_rt_runtime(struct task_group *tg)
8806{
8807 u64 rt_runtime_us;
8808
8809 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8810 return -1;
8811
8812 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8813 do_div(rt_runtime_us, NSEC_PER_USEC);
8814 return rt_runtime_us;
8815}
8816
8817int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8818{
8819 u64 rt_runtime, rt_period;
8820
8821 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8822 rt_runtime = tg->rt_bandwidth.rt_runtime;
8823
8824 if (rt_period == 0)
8825 return -EINVAL;
8826
8827 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8828}
8829
8830long sched_group_rt_period(struct task_group *tg)
8831{
8832 u64 rt_period_us;
8833
8834 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8835 do_div(rt_period_us, NSEC_PER_USEC);
8836 return rt_period_us;
8837}
8838
8839static int sched_rt_global_constraints(void)
8840{
8841 u64 runtime, period;
8842 int ret = 0;
8843
8844 if (sysctl_sched_rt_period <= 0)
8845 return -EINVAL;
8846
8847 runtime = global_rt_runtime();
8848 period = global_rt_period();
8849
8850 /*
8851 * Sanity check on the sysctl variables.
8852 */
8853 if (runtime > period && runtime != RUNTIME_INF)
8854 return -EINVAL;
8855
8856 mutex_lock(&rt_constraints_mutex);
8857 read_lock(&tasklist_lock);
8858 ret = __rt_schedulable(NULL, 0, 0);
8859 read_unlock(&tasklist_lock);
8860 mutex_unlock(&rt_constraints_mutex);
8861
8862 return ret;
8863}
8864
8865int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
8866{
8867 /* Don't accept realtime tasks when there is no way for them to run */
8868 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
8869 return 0;
8870
8871 return 1;
8872}
8873
8874#else /* !CONFIG_RT_GROUP_SCHED */
8875static int sched_rt_global_constraints(void)
8876{
8877 unsigned long flags;
8878 int i;
8879
8880 if (sysctl_sched_rt_period <= 0)
8881 return -EINVAL;
8882
8883 /*
8884 * There's always some RT tasks in the root group
8885 * -- migration, kstopmachine etc..
8886 */
8887 if (sysctl_sched_rt_runtime == 0)
8888 return -EBUSY;
8889
8890 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8891 for_each_possible_cpu(i) {
8892 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8893
8894 raw_spin_lock(&rt_rq->rt_runtime_lock);
8895 rt_rq->rt_runtime = global_rt_runtime();
8896 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8897 }
8898 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8899
8900 return 0;
8901}
8902#endif /* CONFIG_RT_GROUP_SCHED */
8903
8904int sched_rt_handler(struct ctl_table *table, int write,
8905 void __user *buffer, size_t *lenp,
8906 loff_t *ppos)
8907{
8908 int ret;
8909 int old_period, old_runtime;
8910 static DEFINE_MUTEX(mutex);
8911
8912 mutex_lock(&mutex);
8913 old_period = sysctl_sched_rt_period;
8914 old_runtime = sysctl_sched_rt_runtime;
8915
8916 ret = proc_dointvec(table, write, buffer, lenp, ppos);
8917
8918 if (!ret && write) {
8919 ret = sched_rt_global_constraints();
8920 if (ret) {
8921 sysctl_sched_rt_period = old_period;
8922 sysctl_sched_rt_runtime = old_runtime;
8923 } else {
8924 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8925 def_rt_bandwidth.rt_period =
8926 ns_to_ktime(global_rt_period());
8927 }
8928 }
8929 mutex_unlock(&mutex);
8930
8931 return ret;
8932}
8933
8934#ifdef CONFIG_CGROUP_SCHED
8935
8936/* return corresponding task_group object of a cgroup */
8937static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
8938{
8939 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8940 struct task_group, css);
8941}
8942
8943static struct cgroup_subsys_state *
8944cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
8945{
8946 struct task_group *tg, *parent;
8947
8948 if (!cgrp->parent) {
8949 /* This is early initialization for the top cgroup */
8950 return &root_task_group.css;
8951 }
8952
8953 parent = cgroup_tg(cgrp->parent);
8954 tg = sched_create_group(parent);
8955 if (IS_ERR(tg))
8956 return ERR_PTR(-ENOMEM);
8957
8958 return &tg->css;
8959}
8960
8961static void
8962cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8963{
8964 struct task_group *tg = cgroup_tg(cgrp);
8965
8966 sched_destroy_group(tg);
8967}
8968
8969static int
8970cpu_cgroup_allow_attach(struct cgroup *cgrp, struct task_struct *tsk)
8971{
8972 const struct cred *cred = current_cred(), *tcred;
8973
8974 tcred = __task_cred(tsk);
8975
8976 if ((current != tsk) && !capable(CAP_SYS_NICE) &&
8977 cred->euid != tcred->uid && cred->euid != tcred->suid)
8978 return -EACCES;
8979
8980 return 0;
8981}
8982
8983static int
8984cpu_cgroup_can_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
8985{
8986#ifdef CONFIG_RT_GROUP_SCHED
8987 if (!sched_rt_can_attach(cgroup_tg(cgrp), tsk))
8988 return -EINVAL;
8989#else
8990 /* We don't support RT-tasks being in separate groups */
8991 if (tsk->sched_class != &fair_sched_class)
8992 return -EINVAL;
8993#endif
8994 return 0;
8995}
8996
8997static void
8998cpu_cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
8999{
9000 sched_move_task(tsk);
9001}
9002
9003static void
9004cpu_cgroup_exit(struct cgroup_subsys *ss, struct cgroup *cgrp,
9005 struct cgroup *old_cgrp, struct task_struct *task)
9006{
9007 /*
9008 * cgroup_exit() is called in the copy_process() failure path.
9009 * Ignore this case since the task hasn't ran yet, this avoids
9010 * trying to poke a half freed task state from generic code.
9011 */
9012 if (!(task->flags & PF_EXITING))
9013 return;
9014
9015 sched_move_task(task);
9016}
9017
9018#ifdef CONFIG_FAIR_GROUP_SCHED
9019static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
9020 u64 shareval)
9021{
9022 return sched_group_set_shares(cgroup_tg(cgrp), scale_load(shareval));
9023}
9024
9025static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
9026{
9027 struct task_group *tg = cgroup_tg(cgrp);
9028
9029 return (u64) scale_load_down(tg->shares);
9030}
9031#endif /* CONFIG_FAIR_GROUP_SCHED */
9032
9033#ifdef CONFIG_RT_GROUP_SCHED
9034static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
9035 s64 val)
9036{
9037 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
9038}
9039
9040static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
9041{
9042 return sched_group_rt_runtime(cgroup_tg(cgrp));
9043}
9044
9045static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9046 u64 rt_period_us)
9047{
9048 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
9049}
9050
9051static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
9052{
9053 return sched_group_rt_period(cgroup_tg(cgrp));
9054}
9055#endif /* CONFIG_RT_GROUP_SCHED */
9056
9057static struct cftype cpu_files[] = {
9058#ifdef CONFIG_FAIR_GROUP_SCHED
9059 {
9060 .name = "shares",
9061 .read_u64 = cpu_shares_read_u64,
9062 .write_u64 = cpu_shares_write_u64,
9063 },
9064#endif
9065#ifdef CONFIG_RT_GROUP_SCHED
9066 {
9067 .name = "rt_runtime_us",
9068 .read_s64 = cpu_rt_runtime_read,
9069 .write_s64 = cpu_rt_runtime_write,
9070 },
9071 {
9072 .name = "rt_period_us",
9073 .read_u64 = cpu_rt_period_read_uint,
9074 .write_u64 = cpu_rt_period_write_uint,
9075 },
9076#endif
9077};
9078
9079static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
9080{
9081 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
9082}
9083
9084struct cgroup_subsys cpu_cgroup_subsys = {
9085 .name = "cpu",
9086 .create = cpu_cgroup_create,
9087 .destroy = cpu_cgroup_destroy,
9088 .allow_attach = cpu_cgroup_allow_attach,
9089 .can_attach_task = cpu_cgroup_can_attach_task,
9090 .attach_task = cpu_cgroup_attach_task,
9091 .exit = cpu_cgroup_exit,
9092 .populate = cpu_cgroup_populate,
9093 .subsys_id = cpu_cgroup_subsys_id,
9094 .early_init = 1,
9095};
9096
9097#endif /* CONFIG_CGROUP_SCHED */
9098
9099#ifdef CONFIG_CGROUP_CPUACCT
9100
9101/*
9102 * CPU accounting code for task groups.
9103 *
9104 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9105 * (balbir@in.ibm.com).
9106 */
9107
9108/* track cpu usage of a group of tasks and its child groups */
9109struct cpuacct {
9110 struct cgroup_subsys_state css;
9111 /* cpuusage holds pointer to a u64-type object on every cpu */
9112 u64 __percpu *cpuusage;
9113 struct percpu_counter cpustat[CPUACCT_STAT_NSTATS];
9114 struct cpuacct *parent;
9115 struct cpuacct_charge_calls *cpufreq_fn;
9116 void *cpuacct_data;
9117};
9118
9119static struct cpuacct *cpuacct_root;
9120
9121/* Default calls for cpufreq accounting */
9122static struct cpuacct_charge_calls *cpuacct_cpufreq;
9123int cpuacct_register_cpufreq(struct cpuacct_charge_calls *fn)
9124{
9125 cpuacct_cpufreq = fn;
9126
9127 /*
9128 * Root node is created before platform can register callbacks,
9129 * initalize here.
9130 */
9131 if (cpuacct_root && fn) {
9132 cpuacct_root->cpufreq_fn = fn;
9133 if (fn->init)
9134 fn->init(&cpuacct_root->cpuacct_data);
9135 }
9136 return 0;
9137}
9138
9139struct cgroup_subsys cpuacct_subsys;
9140
9141/* return cpu accounting group corresponding to this container */
9142static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
9143{
9144 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
9145 struct cpuacct, css);
9146}
9147
9148/* return cpu accounting group to which this task belongs */
9149static inline struct cpuacct *task_ca(struct task_struct *tsk)
9150{
9151 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
9152 struct cpuacct, css);
9153}
9154
9155/* create a new cpu accounting group */
9156static struct cgroup_subsys_state *cpuacct_create(
9157 struct cgroup_subsys *ss, struct cgroup *cgrp)
9158{
9159 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
9160 int i;
9161
9162 if (!ca)
9163 goto out;
9164
9165 ca->cpuusage = alloc_percpu(u64);
9166 if (!ca->cpuusage)
9167 goto out_free_ca;
9168
9169 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
9170 if (percpu_counter_init(&ca->cpustat[i], 0))
9171 goto out_free_counters;
9172
9173 ca->cpufreq_fn = cpuacct_cpufreq;
9174
9175 /* If available, have platform code initalize cpu frequency table */
9176 if (ca->cpufreq_fn && ca->cpufreq_fn->init)
9177 ca->cpufreq_fn->init(&ca->cpuacct_data);
9178
9179 if (cgrp->parent)
9180 ca->parent = cgroup_ca(cgrp->parent);
9181 else
9182 cpuacct_root = ca;
9183
9184 return &ca->css;
9185
9186out_free_counters:
9187 while (--i >= 0)
9188 percpu_counter_destroy(&ca->cpustat[i]);
9189 free_percpu(ca->cpuusage);
9190out_free_ca:
9191 kfree(ca);
9192out:
9193 return ERR_PTR(-ENOMEM);
9194}
9195
9196/* destroy an existing cpu accounting group */
9197static void
9198cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9199{
9200 struct cpuacct *ca = cgroup_ca(cgrp);
9201 int i;
9202
9203 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
9204 percpu_counter_destroy(&ca->cpustat[i]);
9205 free_percpu(ca->cpuusage);
9206 kfree(ca);
9207}
9208
9209static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
9210{
9211 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
9212 u64 data;
9213
9214#ifndef CONFIG_64BIT
9215 /*
9216 * Take rq->lock to make 64-bit read safe on 32-bit platforms.
9217 */
9218 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
9219 data = *cpuusage;
9220 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
9221#else
9222 data = *cpuusage;
9223#endif
9224
9225 return data;
9226}
9227
9228static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
9229{
9230 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
9231
9232#ifndef CONFIG_64BIT
9233 /*
9234 * Take rq->lock to make 64-bit write safe on 32-bit platforms.
9235 */
9236 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
9237 *cpuusage = val;
9238 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
9239#else
9240 *cpuusage = val;
9241#endif
9242}
9243
9244/* return total cpu usage (in nanoseconds) of a group */
9245static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
9246{
9247 struct cpuacct *ca = cgroup_ca(cgrp);
9248 u64 totalcpuusage = 0;
9249 int i;
9250
9251 for_each_present_cpu(i)
9252 totalcpuusage += cpuacct_cpuusage_read(ca, i);
9253
9254 return totalcpuusage;
9255}
9256
9257static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
9258 u64 reset)
9259{
9260 struct cpuacct *ca = cgroup_ca(cgrp);
9261 int err = 0;
9262 int i;
9263
9264 if (reset) {
9265 err = -EINVAL;
9266 goto out;
9267 }
9268
9269 for_each_present_cpu(i)
9270 cpuacct_cpuusage_write(ca, i, 0);
9271
9272out:
9273 return err;
9274}
9275
9276static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
9277 struct seq_file *m)
9278{
9279 struct cpuacct *ca = cgroup_ca(cgroup);
9280 u64 percpu;
9281 int i;
9282
9283 for_each_present_cpu(i) {
9284 percpu = cpuacct_cpuusage_read(ca, i);
9285 seq_printf(m, "%llu ", (unsigned long long) percpu);
9286 }
9287 seq_printf(m, "\n");
9288 return 0;
9289}
9290
9291static const char *cpuacct_stat_desc[] = {
9292 [CPUACCT_STAT_USER] = "user",
9293 [CPUACCT_STAT_SYSTEM] = "system",
9294};
9295
9296static int cpuacct_stats_show(struct cgroup *cgrp, struct cftype *cft,
9297 struct cgroup_map_cb *cb)
9298{
9299 struct cpuacct *ca = cgroup_ca(cgrp);
9300 int i;
9301
9302 for (i = 0; i < CPUACCT_STAT_NSTATS; i++) {
9303 s64 val = percpu_counter_read(&ca->cpustat[i]);
9304 val = cputime64_to_clock_t(val);
9305 cb->fill(cb, cpuacct_stat_desc[i], val);
9306 }
9307 return 0;
9308}
9309
9310static int cpuacct_cpufreq_show(struct cgroup *cgrp, struct cftype *cft,
9311 struct cgroup_map_cb *cb)
9312{
9313 struct cpuacct *ca = cgroup_ca(cgrp);
9314 if (ca->cpufreq_fn && ca->cpufreq_fn->cpufreq_show)
9315 ca->cpufreq_fn->cpufreq_show(ca->cpuacct_data, cb);
9316
9317 return 0;
9318}
9319
9320/* return total cpu power usage (milliWatt second) of a group */
9321static u64 cpuacct_powerusage_read(struct cgroup *cgrp, struct cftype *cft)
9322{
9323 int i;
9324 struct cpuacct *ca = cgroup_ca(cgrp);
9325 u64 totalpower = 0;
9326
9327 if (ca->cpufreq_fn && ca->cpufreq_fn->power_usage)
9328 for_each_present_cpu(i) {
9329 totalpower += ca->cpufreq_fn->power_usage(
9330 ca->cpuacct_data);
9331 }
9332
9333 return totalpower;
9334}
9335
9336static struct cftype files[] = {
9337 {
9338 .name = "usage",
9339 .read_u64 = cpuusage_read,
9340 .write_u64 = cpuusage_write,
9341 },
9342 {
9343 .name = "usage_percpu",
9344 .read_seq_string = cpuacct_percpu_seq_read,
9345 },
9346 {
9347 .name = "stat",
9348 .read_map = cpuacct_stats_show,
9349 },
9350 {
9351 .name = "cpufreq",
9352 .read_map = cpuacct_cpufreq_show,
9353 },
9354 {
9355 .name = "power",
9356 .read_u64 = cpuacct_powerusage_read
9357 },
9358};
9359
9360static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
9361{
9362 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
9363}
9364
9365/*
9366 * charge this task's execution time to its accounting group.
9367 *
9368 * called with rq->lock held.
9369 */
9370static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
9371{
9372 struct cpuacct *ca;
9373 int cpu;
9374
9375 if (unlikely(!cpuacct_subsys.active))
9376 return;
9377
9378 cpu = task_cpu(tsk);
9379
9380 rcu_read_lock();
9381
9382 ca = task_ca(tsk);
9383
9384 for (; ca; ca = ca->parent) {
9385 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
9386 *cpuusage += cputime;
9387
9388 /* Call back into platform code to account for CPU speeds */
9389 if (ca->cpufreq_fn && ca->cpufreq_fn->charge)
9390 ca->cpufreq_fn->charge(ca->cpuacct_data, cputime, cpu);
9391 }
9392
9393 rcu_read_unlock();
9394}
9395
9396/*
9397 * When CONFIG_VIRT_CPU_ACCOUNTING is enabled one jiffy can be very large
9398 * in cputime_t units. As a result, cpuacct_update_stats calls
9399 * percpu_counter_add with values large enough to always overflow the
9400 * per cpu batch limit causing bad SMP scalability.
9401 *
9402 * To fix this we scale percpu_counter_batch by cputime_one_jiffy so we
9403 * batch the same amount of time with CONFIG_VIRT_CPU_ACCOUNTING disabled
9404 * and enabled. We cap it at INT_MAX which is the largest allowed batch value.
9405 */
9406#ifdef CONFIG_SMP
9407#define CPUACCT_BATCH \
9408 min_t(long, percpu_counter_batch * cputime_one_jiffy, INT_MAX)
9409#else
9410#define CPUACCT_BATCH 0
9411#endif
9412
9413/*
9414 * Charge the system/user time to the task's accounting group.
9415 */
9416static void cpuacct_update_stats(struct task_struct *tsk,
9417 enum cpuacct_stat_index idx, cputime_t val)
9418{
9419 struct cpuacct *ca;
9420 int batch = CPUACCT_BATCH;
9421
9422 if (unlikely(!cpuacct_subsys.active))
9423 return;
9424
9425 rcu_read_lock();
9426 ca = task_ca(tsk);
9427
9428 do {
9429 __percpu_counter_add(&ca->cpustat[idx], val, batch);
9430 ca = ca->parent;
9431 } while (ca);
9432 rcu_read_unlock();
9433}
9434
9435struct cgroup_subsys cpuacct_subsys = {
9436 .name = "cpuacct",
9437 .create = cpuacct_create,
9438 .destroy = cpuacct_destroy,
9439 .populate = cpuacct_populate,
9440 .subsys_id = cpuacct_subsys_id,
9441};
9442#endif /* CONFIG_CGROUP_CPUACCT */
9443
diff --git a/kernel/sched_autogroup.c b/kernel/sched_autogroup.c
new file mode 100644
index 00000000000..429242f3c48
--- /dev/null
+++ b/kernel/sched_autogroup.c
@@ -0,0 +1,275 @@
1#ifdef CONFIG_SCHED_AUTOGROUP
2
3#include <linux/proc_fs.h>
4#include <linux/seq_file.h>
5#include <linux/kallsyms.h>
6#include <linux/utsname.h>
7
8unsigned int __read_mostly sysctl_sched_autogroup_enabled = 1;
9static struct autogroup autogroup_default;
10static atomic_t autogroup_seq_nr;
11
12static void __init autogroup_init(struct task_struct *init_task)
13{
14 autogroup_default.tg = &root_task_group;
15 kref_init(&autogroup_default.kref);
16 init_rwsem(&autogroup_default.lock);
17 init_task->signal->autogroup = &autogroup_default;
18}
19
20static inline void autogroup_free(struct task_group *tg)
21{
22 kfree(tg->autogroup);
23}
24
25static inline void autogroup_destroy(struct kref *kref)
26{
27 struct autogroup *ag = container_of(kref, struct autogroup, kref);
28
29#ifdef CONFIG_RT_GROUP_SCHED
30 /* We've redirected RT tasks to the root task group... */
31 ag->tg->rt_se = NULL;
32 ag->tg->rt_rq = NULL;
33#endif
34 sched_destroy_group(ag->tg);
35}
36
37static inline void autogroup_kref_put(struct autogroup *ag)
38{
39 kref_put(&ag->kref, autogroup_destroy);
40}
41
42static inline struct autogroup *autogroup_kref_get(struct autogroup *ag)
43{
44 kref_get(&ag->kref);
45 return ag;
46}
47
48static inline struct autogroup *autogroup_task_get(struct task_struct *p)
49{
50 struct autogroup *ag;
51 unsigned long flags;
52
53 if (!lock_task_sighand(p, &flags))
54 return autogroup_kref_get(&autogroup_default);
55
56 ag = autogroup_kref_get(p->signal->autogroup);
57 unlock_task_sighand(p, &flags);
58
59 return ag;
60}
61
62#ifdef CONFIG_RT_GROUP_SCHED
63static void free_rt_sched_group(struct task_group *tg);
64#endif
65
66static inline struct autogroup *autogroup_create(void)
67{
68 struct autogroup *ag = kzalloc(sizeof(*ag), GFP_KERNEL);
69 struct task_group *tg;
70
71 if (!ag)
72 goto out_fail;
73
74 tg = sched_create_group(&root_task_group);
75
76 if (IS_ERR(tg))
77 goto out_free;
78
79 kref_init(&ag->kref);
80 init_rwsem(&ag->lock);
81 ag->id = atomic_inc_return(&autogroup_seq_nr);
82 ag->tg = tg;
83#ifdef CONFIG_RT_GROUP_SCHED
84 /*
85 * Autogroup RT tasks are redirected to the root task group
86 * so we don't have to move tasks around upon policy change,
87 * or flail around trying to allocate bandwidth on the fly.
88 * A bandwidth exception in __sched_setscheduler() allows
89 * the policy change to proceed. Thereafter, task_group()
90 * returns &root_task_group, so zero bandwidth is required.
91 */
92 free_rt_sched_group(tg);
93 tg->rt_se = root_task_group.rt_se;
94 tg->rt_rq = root_task_group.rt_rq;
95#endif
96 tg->autogroup = ag;
97
98 return ag;
99
100out_free:
101 kfree(ag);
102out_fail:
103 if (printk_ratelimit()) {
104 printk(KERN_WARNING "autogroup_create: %s failure.\n",
105 ag ? "sched_create_group()" : "kmalloc()");
106 }
107
108 return autogroup_kref_get(&autogroup_default);
109}
110
111static inline bool
112task_wants_autogroup(struct task_struct *p, struct task_group *tg)
113{
114 if (tg != &root_task_group)
115 return false;
116
117 if (p->sched_class != &fair_sched_class)
118 return false;
119
120 /*
121 * We can only assume the task group can't go away on us if
122 * autogroup_move_group() can see us on ->thread_group list.
123 */
124 if (p->flags & PF_EXITING)
125 return false;
126
127 return true;
128}
129
130static inline bool task_group_is_autogroup(struct task_group *tg)
131{
132 return !!tg->autogroup;
133}
134
135static inline struct task_group *
136autogroup_task_group(struct task_struct *p, struct task_group *tg)
137{
138 int enabled = ACCESS_ONCE(sysctl_sched_autogroup_enabled);
139
140 if (enabled && task_wants_autogroup(p, tg))
141 return p->signal->autogroup->tg;
142
143 return tg;
144}
145
146static void
147autogroup_move_group(struct task_struct *p, struct autogroup *ag)
148{
149 struct autogroup *prev;
150 struct task_struct *t;
151 unsigned long flags;
152
153 BUG_ON(!lock_task_sighand(p, &flags));
154
155 prev = p->signal->autogroup;
156 if (prev == ag) {
157 unlock_task_sighand(p, &flags);
158 return;
159 }
160
161 p->signal->autogroup = autogroup_kref_get(ag);
162
163 if (!ACCESS_ONCE(sysctl_sched_autogroup_enabled))
164 goto out;
165
166 t = p;
167 do {
168 sched_move_task(t);
169 } while_each_thread(p, t);
170
171out:
172 unlock_task_sighand(p, &flags);
173 autogroup_kref_put(prev);
174}
175
176/* Allocates GFP_KERNEL, cannot be called under any spinlock */
177void sched_autogroup_create_attach(struct task_struct *p)
178{
179 struct autogroup *ag = autogroup_create();
180
181 autogroup_move_group(p, ag);
182 /* drop extra reference added by autogroup_create() */
183 autogroup_kref_put(ag);
184}
185EXPORT_SYMBOL(sched_autogroup_create_attach);
186
187/* Cannot be called under siglock. Currently has no users */
188void sched_autogroup_detach(struct task_struct *p)
189{
190 autogroup_move_group(p, &autogroup_default);
191}
192EXPORT_SYMBOL(sched_autogroup_detach);
193
194void sched_autogroup_fork(struct signal_struct *sig)
195{
196 sig->autogroup = autogroup_task_get(current);
197}
198
199void sched_autogroup_exit(struct signal_struct *sig)
200{
201 autogroup_kref_put(sig->autogroup);
202}
203
204static int __init setup_autogroup(char *str)
205{
206 sysctl_sched_autogroup_enabled = 0;
207
208 return 1;
209}
210
211__setup("noautogroup", setup_autogroup);
212
213#ifdef CONFIG_PROC_FS
214
215int proc_sched_autogroup_set_nice(struct task_struct *p, int *nice)
216{
217 static unsigned long next = INITIAL_JIFFIES;
218 struct autogroup *ag;
219 int err;
220
221 if (*nice < -20 || *nice > 19)
222 return -EINVAL;
223
224 err = security_task_setnice(current, *nice);
225 if (err)
226 return err;
227
228 if (*nice < 0 && !can_nice(current, *nice))
229 return -EPERM;
230
231 /* this is a heavy operation taking global locks.. */
232 if (!capable(CAP_SYS_ADMIN) && time_before(jiffies, next))
233 return -EAGAIN;
234
235 next = HZ / 10 + jiffies;
236 ag = autogroup_task_get(p);
237
238 down_write(&ag->lock);
239 err = sched_group_set_shares(ag->tg, prio_to_weight[*nice + 20]);
240 if (!err)
241 ag->nice = *nice;
242 up_write(&ag->lock);
243
244 autogroup_kref_put(ag);
245
246 return err;
247}
248
249void proc_sched_autogroup_show_task(struct task_struct *p, struct seq_file *m)
250{
251 struct autogroup *ag = autogroup_task_get(p);
252
253 if (!task_group_is_autogroup(ag->tg))
254 goto out;
255
256 down_read(&ag->lock);
257 seq_printf(m, "/autogroup-%ld nice %d\n", ag->id, ag->nice);
258 up_read(&ag->lock);
259
260out:
261 autogroup_kref_put(ag);
262}
263#endif /* CONFIG_PROC_FS */
264
265#ifdef CONFIG_SCHED_DEBUG
266static inline int autogroup_path(struct task_group *tg, char *buf, int buflen)
267{
268 if (!task_group_is_autogroup(tg))
269 return 0;
270
271 return snprintf(buf, buflen, "%s-%ld", "/autogroup", tg->autogroup->id);
272}
273#endif /* CONFIG_SCHED_DEBUG */
274
275#endif /* CONFIG_SCHED_AUTOGROUP */
diff --git a/kernel/sched_autogroup.h b/kernel/sched_autogroup.h
new file mode 100644
index 00000000000..c2f0e7248dc
--- /dev/null
+++ b/kernel/sched_autogroup.h
@@ -0,0 +1,42 @@
1#ifdef CONFIG_SCHED_AUTOGROUP
2
3struct autogroup {
4 /*
5 * reference doesn't mean how many thread attach to this
6 * autogroup now. It just stands for the number of task
7 * could use this autogroup.
8 */
9 struct kref kref;
10 struct task_group *tg;
11 struct rw_semaphore lock;
12 unsigned long id;
13 int nice;
14};
15
16static inline bool task_group_is_autogroup(struct task_group *tg);
17static inline struct task_group *
18autogroup_task_group(struct task_struct *p, struct task_group *tg);
19
20#else /* !CONFIG_SCHED_AUTOGROUP */
21
22static inline void autogroup_init(struct task_struct *init_task) { }
23static inline void autogroup_free(struct task_group *tg) { }
24static inline bool task_group_is_autogroup(struct task_group *tg)
25{
26 return 0;
27}
28
29static inline struct task_group *
30autogroup_task_group(struct task_struct *p, struct task_group *tg)
31{
32 return tg;
33}
34
35#ifdef CONFIG_SCHED_DEBUG
36static inline int autogroup_path(struct task_group *tg, char *buf, int buflen)
37{
38 return 0;
39}
40#endif
41
42#endif /* CONFIG_SCHED_AUTOGROUP */
diff --git a/kernel/sched_clock.c b/kernel/sched_clock.c
new file mode 100644
index 00000000000..9d8af0b3fb6
--- /dev/null
+++ b/kernel/sched_clock.c
@@ -0,0 +1,350 @@
1/*
2 * sched_clock for unstable cpu clocks
3 *
4 * Copyright (C) 2008 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
5 *
6 * Updates and enhancements:
7 * Copyright (C) 2008 Red Hat, Inc. Steven Rostedt <srostedt@redhat.com>
8 *
9 * Based on code by:
10 * Ingo Molnar <mingo@redhat.com>
11 * Guillaume Chazarain <guichaz@gmail.com>
12 *
13 *
14 * What:
15 *
16 * cpu_clock(i) provides a fast (execution time) high resolution
17 * clock with bounded drift between CPUs. The value of cpu_clock(i)
18 * is monotonic for constant i. The timestamp returned is in nanoseconds.
19 *
20 * ######################### BIG FAT WARNING ##########################
21 * # when comparing cpu_clock(i) to cpu_clock(j) for i != j, time can #
22 * # go backwards !! #
23 * ####################################################################
24 *
25 * There is no strict promise about the base, although it tends to start
26 * at 0 on boot (but people really shouldn't rely on that).
27 *
28 * cpu_clock(i) -- can be used from any context, including NMI.
29 * sched_clock_cpu(i) -- must be used with local IRQs disabled (implied by NMI)
30 * local_clock() -- is cpu_clock() on the current cpu.
31 *
32 * How:
33 *
34 * The implementation either uses sched_clock() when
35 * !CONFIG_HAVE_UNSTABLE_SCHED_CLOCK, which means in that case the
36 * sched_clock() is assumed to provide these properties (mostly it means
37 * the architecture provides a globally synchronized highres time source).
38 *
39 * Otherwise it tries to create a semi stable clock from a mixture of other
40 * clocks, including:
41 *
42 * - GTOD (clock monotomic)
43 * - sched_clock()
44 * - explicit idle events
45 *
46 * We use GTOD as base and use sched_clock() deltas to improve resolution. The
47 * deltas are filtered to provide monotonicity and keeping it within an
48 * expected window.
49 *
50 * Furthermore, explicit sleep and wakeup hooks allow us to account for time
51 * that is otherwise invisible (TSC gets stopped).
52 *
53 *
54 * Notes:
55 *
56 * The !IRQ-safetly of sched_clock() and sched_clock_cpu() comes from things
57 * like cpufreq interrupts that can change the base clock (TSC) multiplier
58 * and cause funny jumps in time -- although the filtering provided by
59 * sched_clock_cpu() should mitigate serious artifacts we cannot rely on it
60 * in general since for !CONFIG_HAVE_UNSTABLE_SCHED_CLOCK we fully rely on
61 * sched_clock().
62 */
63#include <linux/spinlock.h>
64#include <linux/hardirq.h>
65#include <linux/module.h>
66#include <linux/percpu.h>
67#include <linux/ktime.h>
68#include <linux/sched.h>
69
70/*
71 * Scheduler clock - returns current time in nanosec units.
72 * This is default implementation.
73 * Architectures and sub-architectures can override this.
74 */
75unsigned long long __attribute__((weak)) sched_clock(void)
76{
77 return (unsigned long long)(jiffies - INITIAL_JIFFIES)
78 * (NSEC_PER_SEC / HZ);
79}
80EXPORT_SYMBOL_GPL(sched_clock);
81
82__read_mostly int sched_clock_running;
83
84#ifdef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK
85__read_mostly int sched_clock_stable;
86
87struct sched_clock_data {
88 u64 tick_raw;
89 u64 tick_gtod;
90 u64 clock;
91};
92
93static DEFINE_PER_CPU_SHARED_ALIGNED(struct sched_clock_data, sched_clock_data);
94
95static inline struct sched_clock_data *this_scd(void)
96{
97 return &__get_cpu_var(sched_clock_data);
98}
99
100static inline struct sched_clock_data *cpu_sdc(int cpu)
101{
102 return &per_cpu(sched_clock_data, cpu);
103}
104
105void sched_clock_init(void)
106{
107 u64 ktime_now = ktime_to_ns(ktime_get());
108 int cpu;
109
110 for_each_possible_cpu(cpu) {
111 struct sched_clock_data *scd = cpu_sdc(cpu);
112
113 scd->tick_raw = 0;
114 scd->tick_gtod = ktime_now;
115 scd->clock = ktime_now;
116 }
117
118 sched_clock_running = 1;
119}
120
121/*
122 * min, max except they take wrapping into account
123 */
124
125static inline u64 wrap_min(u64 x, u64 y)
126{
127 return (s64)(x - y) < 0 ? x : y;
128}
129
130static inline u64 wrap_max(u64 x, u64 y)
131{
132 return (s64)(x - y) > 0 ? x : y;
133}
134
135/*
136 * update the percpu scd from the raw @now value
137 *
138 * - filter out backward motion
139 * - use the GTOD tick value to create a window to filter crazy TSC values
140 */
141static u64 sched_clock_local(struct sched_clock_data *scd)
142{
143 u64 now, clock, old_clock, min_clock, max_clock;
144 s64 delta;
145
146again:
147 now = sched_clock();
148 delta = now - scd->tick_raw;
149 if (unlikely(delta < 0))
150 delta = 0;
151
152 old_clock = scd->clock;
153
154 /*
155 * scd->clock = clamp(scd->tick_gtod + delta,
156 * max(scd->tick_gtod, scd->clock),
157 * scd->tick_gtod + TICK_NSEC);
158 */
159
160 clock = scd->tick_gtod + delta;
161 min_clock = wrap_max(scd->tick_gtod, old_clock);
162 max_clock = wrap_max(old_clock, scd->tick_gtod + TICK_NSEC);
163
164 clock = wrap_max(clock, min_clock);
165 clock = wrap_min(clock, max_clock);
166
167 if (cmpxchg64(&scd->clock, old_clock, clock) != old_clock)
168 goto again;
169
170 return clock;
171}
172
173static u64 sched_clock_remote(struct sched_clock_data *scd)
174{
175 struct sched_clock_data *my_scd = this_scd();
176 u64 this_clock, remote_clock;
177 u64 *ptr, old_val, val;
178
179 sched_clock_local(my_scd);
180again:
181 this_clock = my_scd->clock;
182 remote_clock = scd->clock;
183
184 /*
185 * Use the opportunity that we have both locks
186 * taken to couple the two clocks: we take the
187 * larger time as the latest time for both
188 * runqueues. (this creates monotonic movement)
189 */
190 if (likely((s64)(remote_clock - this_clock) < 0)) {
191 ptr = &scd->clock;
192 old_val = remote_clock;
193 val = this_clock;
194 } else {
195 /*
196 * Should be rare, but possible:
197 */
198 ptr = &my_scd->clock;
199 old_val = this_clock;
200 val = remote_clock;
201 }
202
203 if (cmpxchg64(ptr, old_val, val) != old_val)
204 goto again;
205
206 return val;
207}
208
209/*
210 * Similar to cpu_clock(), but requires local IRQs to be disabled.
211 *
212 * See cpu_clock().
213 */
214u64 sched_clock_cpu(int cpu)
215{
216 struct sched_clock_data *scd;
217 u64 clock;
218
219 WARN_ON_ONCE(!irqs_disabled());
220
221 if (sched_clock_stable)
222 return sched_clock();
223
224 if (unlikely(!sched_clock_running))
225 return 0ull;
226
227 scd = cpu_sdc(cpu);
228
229 if (cpu != smp_processor_id())
230 clock = sched_clock_remote(scd);
231 else
232 clock = sched_clock_local(scd);
233
234 return clock;
235}
236
237void sched_clock_tick(void)
238{
239 struct sched_clock_data *scd;
240 u64 now, now_gtod;
241
242 if (sched_clock_stable)
243 return;
244
245 if (unlikely(!sched_clock_running))
246 return;
247
248 WARN_ON_ONCE(!irqs_disabled());
249
250 scd = this_scd();
251 now_gtod = ktime_to_ns(ktime_get());
252 now = sched_clock();
253
254 scd->tick_raw = now;
255 scd->tick_gtod = now_gtod;
256 sched_clock_local(scd);
257}
258
259/*
260 * We are going deep-idle (irqs are disabled):
261 */
262void sched_clock_idle_sleep_event(void)
263{
264 sched_clock_cpu(smp_processor_id());
265}
266EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
267
268/*
269 * We just idled delta nanoseconds (called with irqs disabled):
270 */
271void sched_clock_idle_wakeup_event(u64 delta_ns)
272{
273 if (timekeeping_suspended)
274 return;
275
276 sched_clock_tick();
277 touch_softlockup_watchdog();
278}
279EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
280
281/*
282 * As outlined at the top, provides a fast, high resolution, nanosecond
283 * time source that is monotonic per cpu argument and has bounded drift
284 * between cpus.
285 *
286 * ######################### BIG FAT WARNING ##########################
287 * # when comparing cpu_clock(i) to cpu_clock(j) for i != j, time can #
288 * # go backwards !! #
289 * ####################################################################
290 */
291u64 cpu_clock(int cpu)
292{
293 u64 clock;
294 unsigned long flags;
295
296 local_irq_save(flags);
297 clock = sched_clock_cpu(cpu);
298 local_irq_restore(flags);
299
300 return clock;
301}
302
303/*
304 * Similar to cpu_clock() for the current cpu. Time will only be observed
305 * to be monotonic if care is taken to only compare timestampt taken on the
306 * same CPU.
307 *
308 * See cpu_clock().
309 */
310u64 local_clock(void)
311{
312 u64 clock;
313 unsigned long flags;
314
315 local_irq_save(flags);
316 clock = sched_clock_cpu(smp_processor_id());
317 local_irq_restore(flags);
318
319 return clock;
320}
321
322#else /* CONFIG_HAVE_UNSTABLE_SCHED_CLOCK */
323
324void sched_clock_init(void)
325{
326 sched_clock_running = 1;
327}
328
329u64 sched_clock_cpu(int cpu)
330{
331 if (unlikely(!sched_clock_running))
332 return 0;
333
334 return sched_clock();
335}
336
337u64 cpu_clock(int cpu)
338{
339 return sched_clock_cpu(cpu);
340}
341
342u64 local_clock(void)
343{
344 return sched_clock_cpu(0);
345}
346
347#endif /* CONFIG_HAVE_UNSTABLE_SCHED_CLOCK */
348
349EXPORT_SYMBOL_GPL(cpu_clock);
350EXPORT_SYMBOL_GPL(local_clock);
diff --git a/kernel/sched_cpupri.c b/kernel/sched_cpupri.c
new file mode 100644
index 00000000000..2722dc1b413
--- /dev/null
+++ b/kernel/sched_cpupri.c
@@ -0,0 +1,204 @@
1/*
2 * kernel/sched_cpupri.c
3 *
4 * CPU priority management
5 *
6 * Copyright (C) 2007-2008 Novell
7 *
8 * Author: Gregory Haskins <ghaskins@novell.com>
9 *
10 * This code tracks the priority of each CPU so that global migration
11 * decisions are easy to calculate. Each CPU can be in a state as follows:
12 *
13 * (INVALID), IDLE, NORMAL, RT1, ... RT99
14 *
15 * going from the lowest priority to the highest. CPUs in the INVALID state
16 * are not eligible for routing. The system maintains this state with
17 * a 2 dimensional bitmap (the first for priority class, the second for cpus
18 * in that class). Therefore a typical application without affinity
19 * restrictions can find a suitable CPU with O(1) complexity (e.g. two bit
20 * searches). For tasks with affinity restrictions, the algorithm has a
21 * worst case complexity of O(min(102, nr_domcpus)), though the scenario that
22 * yields the worst case search is fairly contrived.
23 *
24 * This program is free software; you can redistribute it and/or
25 * modify it under the terms of the GNU General Public License
26 * as published by the Free Software Foundation; version 2
27 * of the License.
28 */
29
30#include <linux/gfp.h>
31#include "sched_cpupri.h"
32
33/* Convert between a 140 based task->prio, and our 102 based cpupri */
34static int convert_prio(int prio)
35{
36 int cpupri;
37
38 if (prio == CPUPRI_INVALID)
39 cpupri = CPUPRI_INVALID;
40 else if (prio == MAX_PRIO)
41 cpupri = CPUPRI_IDLE;
42 else if (prio >= MAX_RT_PRIO)
43 cpupri = CPUPRI_NORMAL;
44 else
45 cpupri = MAX_RT_PRIO - prio + 1;
46
47 return cpupri;
48}
49
50#define for_each_cpupri_active(array, idx) \
51 for_each_set_bit(idx, array, CPUPRI_NR_PRIORITIES)
52
53/**
54 * cpupri_find - find the best (lowest-pri) CPU in the system
55 * @cp: The cpupri context
56 * @p: The task
57 * @lowest_mask: A mask to fill in with selected CPUs (or NULL)
58 *
59 * Note: This function returns the recommended CPUs as calculated during the
60 * current invocation. By the time the call returns, the CPUs may have in
61 * fact changed priorities any number of times. While not ideal, it is not
62 * an issue of correctness since the normal rebalancer logic will correct
63 * any discrepancies created by racing against the uncertainty of the current
64 * priority configuration.
65 *
66 * Returns: (int)bool - CPUs were found
67 */
68int cpupri_find(struct cpupri *cp, struct task_struct *p,
69 struct cpumask *lowest_mask)
70{
71 int idx = 0;
72 int task_pri = convert_prio(p->prio);
73
74 for_each_cpupri_active(cp->pri_active, idx) {
75 struct cpupri_vec *vec = &cp->pri_to_cpu[idx];
76
77 if (idx >= task_pri)
78 break;
79
80 if (cpumask_any_and(&p->cpus_allowed, vec->mask) >= nr_cpu_ids)
81 continue;
82
83 if (lowest_mask) {
84 cpumask_and(lowest_mask, &p->cpus_allowed, vec->mask);
85
86 /*
87 * We have to ensure that we have at least one bit
88 * still set in the array, since the map could have
89 * been concurrently emptied between the first and
90 * second reads of vec->mask. If we hit this
91 * condition, simply act as though we never hit this
92 * priority level and continue on.
93 */
94 if (cpumask_any(lowest_mask) >= nr_cpu_ids)
95 continue;
96 }
97
98 return 1;
99 }
100
101 return 0;
102}
103
104/**
105 * cpupri_set - update the cpu priority setting
106 * @cp: The cpupri context
107 * @cpu: The target cpu
108 * @pri: The priority (INVALID-RT99) to assign to this CPU
109 *
110 * Note: Assumes cpu_rq(cpu)->lock is locked
111 *
112 * Returns: (void)
113 */
114void cpupri_set(struct cpupri *cp, int cpu, int newpri)
115{
116 int *currpri = &cp->cpu_to_pri[cpu];
117 int oldpri = *currpri;
118 unsigned long flags;
119
120 newpri = convert_prio(newpri);
121
122 BUG_ON(newpri >= CPUPRI_NR_PRIORITIES);
123
124 if (newpri == oldpri)
125 return;
126
127 /*
128 * If the cpu was currently mapped to a different value, we
129 * need to map it to the new value then remove the old value.
130 * Note, we must add the new value first, otherwise we risk the
131 * cpu being cleared from pri_active, and this cpu could be
132 * missed for a push or pull.
133 */
134 if (likely(newpri != CPUPRI_INVALID)) {
135 struct cpupri_vec *vec = &cp->pri_to_cpu[newpri];
136
137 raw_spin_lock_irqsave(&vec->lock, flags);
138
139 cpumask_set_cpu(cpu, vec->mask);
140 vec->count++;
141 if (vec->count == 1)
142 set_bit(newpri, cp->pri_active);
143
144 raw_spin_unlock_irqrestore(&vec->lock, flags);
145 }
146 if (likely(oldpri != CPUPRI_INVALID)) {
147 struct cpupri_vec *vec = &cp->pri_to_cpu[oldpri];
148
149 raw_spin_lock_irqsave(&vec->lock, flags);
150
151 vec->count--;
152 if (!vec->count)
153 clear_bit(oldpri, cp->pri_active);
154 cpumask_clear_cpu(cpu, vec->mask);
155
156 raw_spin_unlock_irqrestore(&vec->lock, flags);
157 }
158
159 *currpri = newpri;
160}
161
162/**
163 * cpupri_init - initialize the cpupri structure
164 * @cp: The cpupri context
165 * @bootmem: true if allocations need to use bootmem
166 *
167 * Returns: -ENOMEM if memory fails.
168 */
169int cpupri_init(struct cpupri *cp)
170{
171 int i;
172
173 memset(cp, 0, sizeof(*cp));
174
175 for (i = 0; i < CPUPRI_NR_PRIORITIES; i++) {
176 struct cpupri_vec *vec = &cp->pri_to_cpu[i];
177
178 raw_spin_lock_init(&vec->lock);
179 vec->count = 0;
180 if (!zalloc_cpumask_var(&vec->mask, GFP_KERNEL))
181 goto cleanup;
182 }
183
184 for_each_possible_cpu(i)
185 cp->cpu_to_pri[i] = CPUPRI_INVALID;
186 return 0;
187
188cleanup:
189 for (i--; i >= 0; i--)
190 free_cpumask_var(cp->pri_to_cpu[i].mask);
191 return -ENOMEM;
192}
193
194/**
195 * cpupri_cleanup - clean up the cpupri structure
196 * @cp: The cpupri context
197 */
198void cpupri_cleanup(struct cpupri *cp)
199{
200 int i;
201
202 for (i = 0; i < CPUPRI_NR_PRIORITIES; i++)
203 free_cpumask_var(cp->pri_to_cpu[i].mask);
204}
diff --git a/kernel/sched_cpupri.h b/kernel/sched_cpupri.h
new file mode 100644
index 00000000000..9fc7d386fea
--- /dev/null
+++ b/kernel/sched_cpupri.h
@@ -0,0 +1,37 @@
1#ifndef _LINUX_CPUPRI_H
2#define _LINUX_CPUPRI_H
3
4#include <linux/sched.h>
5
6#define CPUPRI_NR_PRIORITIES (MAX_RT_PRIO + 2)
7#define CPUPRI_NR_PRI_WORDS BITS_TO_LONGS(CPUPRI_NR_PRIORITIES)
8
9#define CPUPRI_INVALID -1
10#define CPUPRI_IDLE 0
11#define CPUPRI_NORMAL 1
12/* values 2-101 are RT priorities 0-99 */
13
14struct cpupri_vec {
15 raw_spinlock_t lock;
16 int count;
17 cpumask_var_t mask;
18};
19
20struct cpupri {
21 struct cpupri_vec pri_to_cpu[CPUPRI_NR_PRIORITIES];
22 long pri_active[CPUPRI_NR_PRI_WORDS];
23 int cpu_to_pri[NR_CPUS];
24};
25
26#ifdef CONFIG_SMP
27int cpupri_find(struct cpupri *cp,
28 struct task_struct *p, struct cpumask *lowest_mask);
29void cpupri_set(struct cpupri *cp, int cpu, int pri);
30int cpupri_init(struct cpupri *cp);
31void cpupri_cleanup(struct cpupri *cp);
32#else
33#define cpupri_set(cp, cpu, pri) do { } while (0)
34#define cpupri_init() do { } while (0)
35#endif
36
37#endif /* _LINUX_CPUPRI_H */
diff --git a/kernel/sched_debug.c b/kernel/sched_debug.c
new file mode 100644
index 00000000000..a6710a112b4
--- /dev/null
+++ b/kernel/sched_debug.c
@@ -0,0 +1,508 @@
1/*
2 * kernel/time/sched_debug.c
3 *
4 * Print the CFS rbtree
5 *
6 * Copyright(C) 2007, Red Hat, Inc., Ingo Molnar
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License version 2 as
10 * published by the Free Software Foundation.
11 */
12
13#include <linux/proc_fs.h>
14#include <linux/sched.h>
15#include <linux/seq_file.h>
16#include <linux/kallsyms.h>
17#include <linux/utsname.h>
18
19static DEFINE_SPINLOCK(sched_debug_lock);
20
21/*
22 * This allows printing both to /proc/sched_debug and
23 * to the console
24 */
25#define SEQ_printf(m, x...) \
26 do { \
27 if (m) \
28 seq_printf(m, x); \
29 else \
30 printk(x); \
31 } while (0)
32
33/*
34 * Ease the printing of nsec fields:
35 */
36static long long nsec_high(unsigned long long nsec)
37{
38 if ((long long)nsec < 0) {
39 nsec = -nsec;
40 do_div(nsec, 1000000);
41 return -nsec;
42 }
43 do_div(nsec, 1000000);
44
45 return nsec;
46}
47
48static unsigned long nsec_low(unsigned long long nsec)
49{
50 if ((long long)nsec < 0)
51 nsec = -nsec;
52
53 return do_div(nsec, 1000000);
54}
55
56#define SPLIT_NS(x) nsec_high(x), nsec_low(x)
57
58#ifdef CONFIG_FAIR_GROUP_SCHED
59static void print_cfs_group_stats(struct seq_file *m, int cpu, struct task_group *tg)
60{
61 struct sched_entity *se = tg->se[cpu];
62 if (!se)
63 return;
64
65#define P(F) \
66 SEQ_printf(m, " .%-30s: %lld\n", #F, (long long)F)
67#define PN(F) \
68 SEQ_printf(m, " .%-30s: %lld.%06ld\n", #F, SPLIT_NS((long long)F))
69
70 PN(se->exec_start);
71 PN(se->vruntime);
72 PN(se->sum_exec_runtime);
73#ifdef CONFIG_SCHEDSTATS
74 PN(se->statistics.wait_start);
75 PN(se->statistics.sleep_start);
76 PN(se->statistics.block_start);
77 PN(se->statistics.sleep_max);
78 PN(se->statistics.block_max);
79 PN(se->statistics.exec_max);
80 PN(se->statistics.slice_max);
81 PN(se->statistics.wait_max);
82 PN(se->statistics.wait_sum);
83 P(se->statistics.wait_count);
84#endif
85 P(se->load.weight);
86#undef PN
87#undef P
88}
89#endif
90
91#ifdef CONFIG_CGROUP_SCHED
92static char group_path[PATH_MAX];
93
94static char *task_group_path(struct task_group *tg)
95{
96 if (autogroup_path(tg, group_path, PATH_MAX))
97 return group_path;
98
99 /*
100 * May be NULL if the underlying cgroup isn't fully-created yet
101 */
102 if (!tg->css.cgroup) {
103 group_path[0] = '\0';
104 return group_path;
105 }
106 cgroup_path(tg->css.cgroup, group_path, PATH_MAX);
107 return group_path;
108}
109#endif
110
111static void
112print_task(struct seq_file *m, struct rq *rq, struct task_struct *p)
113{
114 if (rq->curr == p)
115 SEQ_printf(m, "R");
116 else
117 SEQ_printf(m, " ");
118
119 SEQ_printf(m, "%15s %5d %9Ld.%06ld %9Ld %5d ",
120 p->comm, p->pid,
121 SPLIT_NS(p->se.vruntime),
122 (long long)(p->nvcsw + p->nivcsw),
123 p->prio);
124#ifdef CONFIG_SCHEDSTATS
125 SEQ_printf(m, "%9Ld.%06ld %9Ld.%06ld %9Ld.%06ld",
126 SPLIT_NS(p->se.vruntime),
127 SPLIT_NS(p->se.sum_exec_runtime),
128 SPLIT_NS(p->se.statistics.sum_sleep_runtime));
129#else
130 SEQ_printf(m, "%15Ld %15Ld %15Ld.%06ld %15Ld.%06ld %15Ld.%06ld",
131 0LL, 0LL, 0LL, 0L, 0LL, 0L, 0LL, 0L);
132#endif
133#ifdef CONFIG_CGROUP_SCHED
134 SEQ_printf(m, " %s", task_group_path(task_group(p)));
135#endif
136
137 SEQ_printf(m, "\n");
138}
139
140static void print_rq(struct seq_file *m, struct rq *rq, int rq_cpu)
141{
142 struct task_struct *g, *p;
143 unsigned long flags;
144
145 SEQ_printf(m,
146 "\nrunnable tasks:\n"
147 " task PID tree-key switches prio"
148 " exec-runtime sum-exec sum-sleep\n"
149 "------------------------------------------------------"
150 "----------------------------------------------------\n");
151
152 read_lock_irqsave(&tasklist_lock, flags);
153
154 do_each_thread(g, p) {
155 if (!p->on_rq || task_cpu(p) != rq_cpu)
156 continue;
157
158 print_task(m, rq, p);
159 } while_each_thread(g, p);
160
161 read_unlock_irqrestore(&tasklist_lock, flags);
162}
163
164void print_cfs_rq(struct seq_file *m, int cpu, struct cfs_rq *cfs_rq)
165{
166 s64 MIN_vruntime = -1, min_vruntime, max_vruntime = -1,
167 spread, rq0_min_vruntime, spread0;
168 struct rq *rq = cpu_rq(cpu);
169 struct sched_entity *last;
170 unsigned long flags;
171
172#ifdef CONFIG_FAIR_GROUP_SCHED
173 SEQ_printf(m, "\ncfs_rq[%d]:%s\n", cpu, task_group_path(cfs_rq->tg));
174#else
175 SEQ_printf(m, "\ncfs_rq[%d]:\n", cpu);
176#endif
177 SEQ_printf(m, " .%-30s: %Ld.%06ld\n", "exec_clock",
178 SPLIT_NS(cfs_rq->exec_clock));
179
180 raw_spin_lock_irqsave(&rq->lock, flags);
181 if (cfs_rq->rb_leftmost)
182 MIN_vruntime = (__pick_first_entity(cfs_rq))->vruntime;
183 last = __pick_last_entity(cfs_rq);
184 if (last)
185 max_vruntime = last->vruntime;
186 min_vruntime = cfs_rq->min_vruntime;
187 rq0_min_vruntime = cpu_rq(0)->cfs.min_vruntime;
188 raw_spin_unlock_irqrestore(&rq->lock, flags);
189 SEQ_printf(m, " .%-30s: %Ld.%06ld\n", "MIN_vruntime",
190 SPLIT_NS(MIN_vruntime));
191 SEQ_printf(m, " .%-30s: %Ld.%06ld\n", "min_vruntime",
192 SPLIT_NS(min_vruntime));
193 SEQ_printf(m, " .%-30s: %Ld.%06ld\n", "max_vruntime",
194 SPLIT_NS(max_vruntime));
195 spread = max_vruntime - MIN_vruntime;
196 SEQ_printf(m, " .%-30s: %Ld.%06ld\n", "spread",
197 SPLIT_NS(spread));
198 spread0 = min_vruntime - rq0_min_vruntime;
199 SEQ_printf(m, " .%-30s: %Ld.%06ld\n", "spread0",
200 SPLIT_NS(spread0));
201 SEQ_printf(m, " .%-30s: %d\n", "nr_spread_over",
202 cfs_rq->nr_spread_over);
203 SEQ_printf(m, " .%-30s: %ld\n", "nr_running", cfs_rq->nr_running);
204 SEQ_printf(m, " .%-30s: %ld\n", "load", cfs_rq->load.weight);
205#ifdef CONFIG_FAIR_GROUP_SCHED
206#ifdef CONFIG_SMP
207 SEQ_printf(m, " .%-30s: %Ld.%06ld\n", "load_avg",
208 SPLIT_NS(cfs_rq->load_avg));
209 SEQ_printf(m, " .%-30s: %Ld.%06ld\n", "load_period",
210 SPLIT_NS(cfs_rq->load_period));
211 SEQ_printf(m, " .%-30s: %ld\n", "load_contrib",
212 cfs_rq->load_contribution);
213 SEQ_printf(m, " .%-30s: %d\n", "load_tg",
214 atomic_read(&cfs_rq->tg->load_weight));
215#endif
216
217 print_cfs_group_stats(m, cpu, cfs_rq->tg);
218#endif
219}
220
221void print_rt_rq(struct seq_file *m, int cpu, struct rt_rq *rt_rq)
222{
223#ifdef CONFIG_RT_GROUP_SCHED
224 SEQ_printf(m, "\nrt_rq[%d]:%s\n", cpu, task_group_path(rt_rq->tg));
225#else
226 SEQ_printf(m, "\nrt_rq[%d]:\n", cpu);
227#endif
228
229#define P(x) \
230 SEQ_printf(m, " .%-30s: %Ld\n", #x, (long long)(rt_rq->x))
231#define PN(x) \
232 SEQ_printf(m, " .%-30s: %Ld.%06ld\n", #x, SPLIT_NS(rt_rq->x))
233
234 P(rt_nr_running);
235 P(rt_throttled);
236 PN(rt_time);
237 PN(rt_runtime);
238
239#undef PN
240#undef P
241}
242
243extern __read_mostly int sched_clock_running;
244
245static void print_cpu(struct seq_file *m, int cpu)
246{
247 struct rq *rq = cpu_rq(cpu);
248 unsigned long flags;
249
250#ifdef CONFIG_X86
251 {
252 unsigned int freq = cpu_khz ? : 1;
253
254 SEQ_printf(m, "\ncpu#%d, %u.%03u MHz\n",
255 cpu, freq / 1000, (freq % 1000));
256 }
257#else
258 SEQ_printf(m, "\ncpu#%d\n", cpu);
259#endif
260
261#define P(x) \
262 SEQ_printf(m, " .%-30s: %Ld\n", #x, (long long)(rq->x))
263#define PN(x) \
264 SEQ_printf(m, " .%-30s: %Ld.%06ld\n", #x, SPLIT_NS(rq->x))
265
266 P(nr_running);
267 SEQ_printf(m, " .%-30s: %lu\n", "load",
268 rq->load.weight);
269 P(nr_switches);
270 P(nr_load_updates);
271 P(nr_uninterruptible);
272 PN(next_balance);
273 P(curr->pid);
274 PN(clock);
275 P(cpu_load[0]);
276 P(cpu_load[1]);
277 P(cpu_load[2]);
278 P(cpu_load[3]);
279 P(cpu_load[4]);
280#undef P
281#undef PN
282
283#ifdef CONFIG_SCHEDSTATS
284#define P(n) SEQ_printf(m, " .%-30s: %d\n", #n, rq->n);
285#define P64(n) SEQ_printf(m, " .%-30s: %Ld\n", #n, rq->n);
286
287 P(yld_count);
288
289 P(sched_switch);
290 P(sched_count);
291 P(sched_goidle);
292#ifdef CONFIG_SMP
293 P64(avg_idle);
294#endif
295
296 P(ttwu_count);
297 P(ttwu_local);
298
299#undef P
300#undef P64
301#endif
302 spin_lock_irqsave(&sched_debug_lock, flags);
303 print_cfs_stats(m, cpu);
304 print_rt_stats(m, cpu);
305
306 rcu_read_lock();
307 print_rq(m, rq, cpu);
308 rcu_read_unlock();
309 spin_unlock_irqrestore(&sched_debug_lock, flags);
310}
311
312static const char *sched_tunable_scaling_names[] = {
313 "none",
314 "logaritmic",
315 "linear"
316};
317
318static int sched_debug_show(struct seq_file *m, void *v)
319{
320 u64 ktime, sched_clk, cpu_clk;
321 unsigned long flags;
322 int cpu;
323
324 local_irq_save(flags);
325 ktime = ktime_to_ns(ktime_get());
326 sched_clk = sched_clock();
327 cpu_clk = local_clock();
328 local_irq_restore(flags);
329
330 SEQ_printf(m, "Sched Debug Version: v0.10, %s %.*s\n",
331 init_utsname()->release,
332 (int)strcspn(init_utsname()->version, " "),
333 init_utsname()->version);
334
335#define P(x) \
336 SEQ_printf(m, "%-40s: %Ld\n", #x, (long long)(x))
337#define PN(x) \
338 SEQ_printf(m, "%-40s: %Ld.%06ld\n", #x, SPLIT_NS(x))
339 PN(ktime);
340 PN(sched_clk);
341 PN(cpu_clk);
342 P(jiffies);
343#ifdef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK
344 P(sched_clock_stable);
345#endif
346#undef PN
347#undef P
348
349 SEQ_printf(m, "\n");
350 SEQ_printf(m, "sysctl_sched\n");
351
352#define P(x) \
353 SEQ_printf(m, " .%-40s: %Ld\n", #x, (long long)(x))
354#define PN(x) \
355 SEQ_printf(m, " .%-40s: %Ld.%06ld\n", #x, SPLIT_NS(x))
356 PN(sysctl_sched_latency);
357 PN(sysctl_sched_min_granularity);
358 PN(sysctl_sched_wakeup_granularity);
359 P(sysctl_sched_child_runs_first);
360 P(sysctl_sched_features);
361#undef PN
362#undef P
363
364 SEQ_printf(m, " .%-40s: %d (%s)\n", "sysctl_sched_tunable_scaling",
365 sysctl_sched_tunable_scaling,
366 sched_tunable_scaling_names[sysctl_sched_tunable_scaling]);
367
368 for_each_online_cpu(cpu)
369 print_cpu(m, cpu);
370
371 SEQ_printf(m, "\n");
372
373 return 0;
374}
375
376static void sysrq_sched_debug_show(void)
377{
378 sched_debug_show(NULL, NULL);
379}
380
381static int sched_debug_open(struct inode *inode, struct file *filp)
382{
383 return single_open(filp, sched_debug_show, NULL);
384}
385
386static const struct file_operations sched_debug_fops = {
387 .open = sched_debug_open,
388 .read = seq_read,
389 .llseek = seq_lseek,
390 .release = single_release,
391};
392
393static int __init init_sched_debug_procfs(void)
394{
395 struct proc_dir_entry *pe;
396
397 pe = proc_create("sched_debug", 0444, NULL, &sched_debug_fops);
398 if (!pe)
399 return -ENOMEM;
400 return 0;
401}
402
403__initcall(init_sched_debug_procfs);
404
405void proc_sched_show_task(struct task_struct *p, struct seq_file *m)
406{
407 unsigned long nr_switches;
408
409 SEQ_printf(m, "%s (%d, #threads: %d)\n", p->comm, p->pid,
410 get_nr_threads(p));
411 SEQ_printf(m,
412 "---------------------------------------------------------\n");
413#define __P(F) \
414 SEQ_printf(m, "%-35s:%21Ld\n", #F, (long long)F)
415#define P(F) \
416 SEQ_printf(m, "%-35s:%21Ld\n", #F, (long long)p->F)
417#define __PN(F) \
418 SEQ_printf(m, "%-35s:%14Ld.%06ld\n", #F, SPLIT_NS((long long)F))
419#define PN(F) \
420 SEQ_printf(m, "%-35s:%14Ld.%06ld\n", #F, SPLIT_NS((long long)p->F))
421
422 PN(se.exec_start);
423 PN(se.vruntime);
424 PN(se.sum_exec_runtime);
425
426 nr_switches = p->nvcsw + p->nivcsw;
427
428#ifdef CONFIG_SCHEDSTATS
429 PN(se.statistics.wait_start);
430 PN(se.statistics.sleep_start);
431 PN(se.statistics.block_start);
432 PN(se.statistics.sleep_max);
433 PN(se.statistics.block_max);
434 PN(se.statistics.exec_max);
435 PN(se.statistics.slice_max);
436 PN(se.statistics.wait_max);
437 PN(se.statistics.wait_sum);
438 P(se.statistics.wait_count);
439 PN(se.statistics.iowait_sum);
440 P(se.statistics.iowait_count);
441 P(se.nr_migrations);
442 P(se.statistics.nr_migrations_cold);
443 P(se.statistics.nr_failed_migrations_affine);
444 P(se.statistics.nr_failed_migrations_running);
445 P(se.statistics.nr_failed_migrations_hot);
446 P(se.statistics.nr_forced_migrations);
447 P(se.statistics.nr_wakeups);
448 P(se.statistics.nr_wakeups_sync);
449 P(se.statistics.nr_wakeups_migrate);
450 P(se.statistics.nr_wakeups_local);
451 P(se.statistics.nr_wakeups_remote);
452 P(se.statistics.nr_wakeups_affine);
453 P(se.statistics.nr_wakeups_affine_attempts);
454 P(se.statistics.nr_wakeups_passive);
455 P(se.statistics.nr_wakeups_idle);
456
457 {
458 u64 avg_atom, avg_per_cpu;
459
460 avg_atom = p->se.sum_exec_runtime;
461 if (nr_switches)
462 do_div(avg_atom, nr_switches);
463 else
464 avg_atom = -1LL;
465
466 avg_per_cpu = p->se.sum_exec_runtime;
467 if (p->se.nr_migrations) {
468 avg_per_cpu = div64_u64(avg_per_cpu,
469 p->se.nr_migrations);
470 } else {
471 avg_per_cpu = -1LL;
472 }
473
474 __PN(avg_atom);
475 __PN(avg_per_cpu);
476 }
477#endif
478 __P(nr_switches);
479 SEQ_printf(m, "%-35s:%21Ld\n",
480 "nr_voluntary_switches", (long long)p->nvcsw);
481 SEQ_printf(m, "%-35s:%21Ld\n",
482 "nr_involuntary_switches", (long long)p->nivcsw);
483
484 P(se.load.weight);
485 P(policy);
486 P(prio);
487#undef PN
488#undef __PN
489#undef P
490#undef __P
491
492 {
493 unsigned int this_cpu = raw_smp_processor_id();
494 u64 t0, t1;
495
496 t0 = cpu_clock(this_cpu);
497 t1 = cpu_clock(this_cpu);
498 SEQ_printf(m, "%-35s:%21Ld\n",
499 "clock-delta", (long long)(t1-t0));
500 }
501}
502
503void proc_sched_set_task(struct task_struct *p)
504{
505#ifdef CONFIG_SCHEDSTATS
506 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
507#endif
508}
diff --git a/kernel/sched_fair.c b/kernel/sched_fair.c
new file mode 100644
index 00000000000..bc8ee999381
--- /dev/null
+++ b/kernel/sched_fair.c
@@ -0,0 +1,4346 @@
1/*
2 * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
3 *
4 * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
5 *
6 * Interactivity improvements by Mike Galbraith
7 * (C) 2007 Mike Galbraith <efault@gmx.de>
8 *
9 * Various enhancements by Dmitry Adamushko.
10 * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
11 *
12 * Group scheduling enhancements by Srivatsa Vaddagiri
13 * Copyright IBM Corporation, 2007
14 * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
15 *
16 * Scaled math optimizations by Thomas Gleixner
17 * Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
18 *
19 * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
20 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
21 */
22
23#include <linux/latencytop.h>
24#include <linux/sched.h>
25#include <linux/cpumask.h>
26
27/*
28 * Targeted preemption latency for CPU-bound tasks:
29 * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
30 *
31 * NOTE: this latency value is not the same as the concept of
32 * 'timeslice length' - timeslices in CFS are of variable length
33 * and have no persistent notion like in traditional, time-slice
34 * based scheduling concepts.
35 *
36 * (to see the precise effective timeslice length of your workload,
37 * run vmstat and monitor the context-switches (cs) field)
38 */
39unsigned int sysctl_sched_latency = 6000000ULL;
40unsigned int normalized_sysctl_sched_latency = 6000000ULL;
41
42/*
43 * The initial- and re-scaling of tunables is configurable
44 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
45 *
46 * Options are:
47 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
48 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
49 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
50 */
51enum sched_tunable_scaling sysctl_sched_tunable_scaling
52 = SCHED_TUNABLESCALING_LOG;
53
54/*
55 * Minimal preemption granularity for CPU-bound tasks:
56 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
57 */
58unsigned int sysctl_sched_min_granularity = 750000ULL;
59unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
60
61/*
62 * is kept at sysctl_sched_latency / sysctl_sched_min_granularity
63 */
64static unsigned int sched_nr_latency = 8;
65
66/*
67 * After fork, child runs first. If set to 0 (default) then
68 * parent will (try to) run first.
69 */
70unsigned int sysctl_sched_child_runs_first __read_mostly;
71
72/*
73 * SCHED_OTHER wake-up granularity.
74 * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
75 *
76 * This option delays the preemption effects of decoupled workloads
77 * and reduces their over-scheduling. Synchronous workloads will still
78 * have immediate wakeup/sleep latencies.
79 */
80unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
81unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
82
83const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
84
85/*
86 * The exponential sliding window over which load is averaged for shares
87 * distribution.
88 * (default: 10msec)
89 */
90unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL;
91
92static const struct sched_class fair_sched_class;
93
94/**************************************************************
95 * CFS operations on generic schedulable entities:
96 */
97
98#ifdef CONFIG_FAIR_GROUP_SCHED
99
100/* cpu runqueue to which this cfs_rq is attached */
101static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
102{
103 return cfs_rq->rq;
104}
105
106/* An entity is a task if it doesn't "own" a runqueue */
107#define entity_is_task(se) (!se->my_q)
108
109static inline struct task_struct *task_of(struct sched_entity *se)
110{
111#ifdef CONFIG_SCHED_DEBUG
112 WARN_ON_ONCE(!entity_is_task(se));
113#endif
114 return container_of(se, struct task_struct, se);
115}
116
117/* Walk up scheduling entities hierarchy */
118#define for_each_sched_entity(se) \
119 for (; se; se = se->parent)
120
121static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
122{
123 return p->se.cfs_rq;
124}
125
126/* runqueue on which this entity is (to be) queued */
127static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
128{
129 return se->cfs_rq;
130}
131
132/* runqueue "owned" by this group */
133static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
134{
135 return grp->my_q;
136}
137
138static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
139{
140 if (!cfs_rq->on_list) {
141 /*
142 * Ensure we either appear before our parent (if already
143 * enqueued) or force our parent to appear after us when it is
144 * enqueued. The fact that we always enqueue bottom-up
145 * reduces this to two cases.
146 */
147 if (cfs_rq->tg->parent &&
148 cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) {
149 list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
150 &rq_of(cfs_rq)->leaf_cfs_rq_list);
151 } else {
152 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
153 &rq_of(cfs_rq)->leaf_cfs_rq_list);
154 }
155
156 cfs_rq->on_list = 1;
157 }
158}
159
160static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
161{
162 if (cfs_rq->on_list) {
163 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
164 cfs_rq->on_list = 0;
165 }
166}
167
168/* Iterate thr' all leaf cfs_rq's on a runqueue */
169#define for_each_leaf_cfs_rq(rq, cfs_rq) \
170 list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
171
172/* Do the two (enqueued) entities belong to the same group ? */
173static inline int
174is_same_group(struct sched_entity *se, struct sched_entity *pse)
175{
176 if (se->cfs_rq == pse->cfs_rq)
177 return 1;
178
179 return 0;
180}
181
182static inline struct sched_entity *parent_entity(struct sched_entity *se)
183{
184 return se->parent;
185}
186
187/* return depth at which a sched entity is present in the hierarchy */
188static inline int depth_se(struct sched_entity *se)
189{
190 int depth = 0;
191
192 for_each_sched_entity(se)
193 depth++;
194
195 return depth;
196}
197
198static void
199find_matching_se(struct sched_entity **se, struct sched_entity **pse)
200{
201 int se_depth, pse_depth;
202
203 /*
204 * preemption test can be made between sibling entities who are in the
205 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
206 * both tasks until we find their ancestors who are siblings of common
207 * parent.
208 */
209
210 /* First walk up until both entities are at same depth */
211 se_depth = depth_se(*se);
212 pse_depth = depth_se(*pse);
213
214 while (se_depth > pse_depth) {
215 se_depth--;
216 *se = parent_entity(*se);
217 }
218
219 while (pse_depth > se_depth) {
220 pse_depth--;
221 *pse = parent_entity(*pse);
222 }
223
224 while (!is_same_group(*se, *pse)) {
225 *se = parent_entity(*se);
226 *pse = parent_entity(*pse);
227 }
228}
229
230#else /* !CONFIG_FAIR_GROUP_SCHED */
231
232static inline struct task_struct *task_of(struct sched_entity *se)
233{
234 return container_of(se, struct task_struct, se);
235}
236
237static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
238{
239 return container_of(cfs_rq, struct rq, cfs);
240}
241
242#define entity_is_task(se) 1
243
244#define for_each_sched_entity(se) \
245 for (; se; se = NULL)
246
247static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
248{
249 return &task_rq(p)->cfs;
250}
251
252static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
253{
254 struct task_struct *p = task_of(se);
255 struct rq *rq = task_rq(p);
256
257 return &rq->cfs;
258}
259
260/* runqueue "owned" by this group */
261static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
262{
263 return NULL;
264}
265
266static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
267{
268}
269
270static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
271{
272}
273
274#define for_each_leaf_cfs_rq(rq, cfs_rq) \
275 for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
276
277static inline int
278is_same_group(struct sched_entity *se, struct sched_entity *pse)
279{
280 return 1;
281}
282
283static inline struct sched_entity *parent_entity(struct sched_entity *se)
284{
285 return NULL;
286}
287
288static inline void
289find_matching_se(struct sched_entity **se, struct sched_entity **pse)
290{
291}
292
293#endif /* CONFIG_FAIR_GROUP_SCHED */
294
295
296/**************************************************************
297 * Scheduling class tree data structure manipulation methods:
298 */
299
300static inline u64 max_vruntime(u64 min_vruntime, u64 vruntime)
301{
302 s64 delta = (s64)(vruntime - min_vruntime);
303 if (delta > 0)
304 min_vruntime = vruntime;
305
306 return min_vruntime;
307}
308
309static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
310{
311 s64 delta = (s64)(vruntime - min_vruntime);
312 if (delta < 0)
313 min_vruntime = vruntime;
314
315 return min_vruntime;
316}
317
318static inline int entity_before(struct sched_entity *a,
319 struct sched_entity *b)
320{
321 return (s64)(a->vruntime - b->vruntime) < 0;
322}
323
324static void update_min_vruntime(struct cfs_rq *cfs_rq)
325{
326 u64 vruntime = cfs_rq->min_vruntime;
327
328 if (cfs_rq->curr)
329 vruntime = cfs_rq->curr->vruntime;
330
331 if (cfs_rq->rb_leftmost) {
332 struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
333 struct sched_entity,
334 run_node);
335
336 if (!cfs_rq->curr)
337 vruntime = se->vruntime;
338 else
339 vruntime = min_vruntime(vruntime, se->vruntime);
340 }
341
342 cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
343#ifndef CONFIG_64BIT
344 smp_wmb();
345 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
346#endif
347}
348
349/*
350 * Enqueue an entity into the rb-tree:
351 */
352static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
353{
354 struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
355 struct rb_node *parent = NULL;
356 struct sched_entity *entry;
357 int leftmost = 1;
358
359 /*
360 * Find the right place in the rbtree:
361 */
362 while (*link) {
363 parent = *link;
364 entry = rb_entry(parent, struct sched_entity, run_node);
365 /*
366 * We dont care about collisions. Nodes with
367 * the same key stay together.
368 */
369 if (entity_before(se, entry)) {
370 link = &parent->rb_left;
371 } else {
372 link = &parent->rb_right;
373 leftmost = 0;
374 }
375 }
376
377 /*
378 * Maintain a cache of leftmost tree entries (it is frequently
379 * used):
380 */
381 if (leftmost)
382 cfs_rq->rb_leftmost = &se->run_node;
383
384 rb_link_node(&se->run_node, parent, link);
385 rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
386}
387
388static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
389{
390 if (cfs_rq->rb_leftmost == &se->run_node) {
391 struct rb_node *next_node;
392
393 next_node = rb_next(&se->run_node);
394 cfs_rq->rb_leftmost = next_node;
395 }
396
397 rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
398}
399
400static struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
401{
402 struct rb_node *left = cfs_rq->rb_leftmost;
403
404 if (!left)
405 return NULL;
406
407 return rb_entry(left, struct sched_entity, run_node);
408}
409
410static struct sched_entity *__pick_next_entity(struct sched_entity *se)
411{
412 struct rb_node *next = rb_next(&se->run_node);
413
414 if (!next)
415 return NULL;
416
417 return rb_entry(next, struct sched_entity, run_node);
418}
419
420#ifdef CONFIG_SCHED_DEBUG
421static struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
422{
423 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline);
424
425 if (!last)
426 return NULL;
427
428 return rb_entry(last, struct sched_entity, run_node);
429}
430
431/**************************************************************
432 * Scheduling class statistics methods:
433 */
434
435int sched_proc_update_handler(struct ctl_table *table, int write,
436 void __user *buffer, size_t *lenp,
437 loff_t *ppos)
438{
439 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
440 int factor = get_update_sysctl_factor();
441
442 if (ret || !write)
443 return ret;
444
445 sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
446 sysctl_sched_min_granularity);
447
448#define WRT_SYSCTL(name) \
449 (normalized_sysctl_##name = sysctl_##name / (factor))
450 WRT_SYSCTL(sched_min_granularity);
451 WRT_SYSCTL(sched_latency);
452 WRT_SYSCTL(sched_wakeup_granularity);
453#undef WRT_SYSCTL
454
455 return 0;
456}
457#endif
458
459/*
460 * delta /= w
461 */
462static inline unsigned long
463calc_delta_fair(unsigned long delta, struct sched_entity *se)
464{
465 if (unlikely(se->load.weight != NICE_0_LOAD))
466 delta = calc_delta_mine(delta, NICE_0_LOAD, &se->load);
467
468 return delta;
469}
470
471/*
472 * The idea is to set a period in which each task runs once.
473 *
474 * When there are too many tasks (sysctl_sched_nr_latency) we have to stretch
475 * this period because otherwise the slices get too small.
476 *
477 * p = (nr <= nl) ? l : l*nr/nl
478 */
479static u64 __sched_period(unsigned long nr_running)
480{
481 u64 period = sysctl_sched_latency;
482 unsigned long nr_latency = sched_nr_latency;
483
484 if (unlikely(nr_running > nr_latency)) {
485 period = sysctl_sched_min_granularity;
486 period *= nr_running;
487 }
488
489 return period;
490}
491
492/*
493 * We calculate the wall-time slice from the period by taking a part
494 * proportional to the weight.
495 *
496 * s = p*P[w/rw]
497 */
498static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
499{
500 u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
501
502 for_each_sched_entity(se) {
503 struct load_weight *load;
504 struct load_weight lw;
505
506 cfs_rq = cfs_rq_of(se);
507 load = &cfs_rq->load;
508
509 if (unlikely(!se->on_rq)) {
510 lw = cfs_rq->load;
511
512 update_load_add(&lw, se->load.weight);
513 load = &lw;
514 }
515 slice = calc_delta_mine(slice, se->load.weight, load);
516 }
517 return slice;
518}
519
520/*
521 * We calculate the vruntime slice of a to be inserted task
522 *
523 * vs = s/w
524 */
525static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
526{
527 return calc_delta_fair(sched_slice(cfs_rq, se), se);
528}
529
530static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update);
531static void update_cfs_shares(struct cfs_rq *cfs_rq);
532
533/*
534 * Update the current task's runtime statistics. Skip current tasks that
535 * are not in our scheduling class.
536 */
537static inline void
538__update_curr(struct cfs_rq *cfs_rq, struct sched_entity *curr,
539 unsigned long delta_exec)
540{
541 unsigned long delta_exec_weighted;
542
543 schedstat_set(curr->statistics.exec_max,
544 max((u64)delta_exec, curr->statistics.exec_max));
545
546 curr->sum_exec_runtime += delta_exec;
547 schedstat_add(cfs_rq, exec_clock, delta_exec);
548 delta_exec_weighted = calc_delta_fair(delta_exec, curr);
549
550 curr->vruntime += delta_exec_weighted;
551 update_min_vruntime(cfs_rq);
552
553#if defined CONFIG_SMP && defined CONFIG_FAIR_GROUP_SCHED
554 cfs_rq->load_unacc_exec_time += delta_exec;
555#endif
556}
557
558static void update_curr(struct cfs_rq *cfs_rq)
559{
560 struct sched_entity *curr = cfs_rq->curr;
561 u64 now = rq_of(cfs_rq)->clock_task;
562 unsigned long delta_exec;
563
564 if (unlikely(!curr))
565 return;
566
567 /*
568 * Get the amount of time the current task was running
569 * since the last time we changed load (this cannot
570 * overflow on 32 bits):
571 */
572 delta_exec = (unsigned long)(now - curr->exec_start);
573 if (!delta_exec)
574 return;
575
576 __update_curr(cfs_rq, curr, delta_exec);
577 curr->exec_start = now;
578
579 if (entity_is_task(curr)) {
580 struct task_struct *curtask = task_of(curr);
581
582 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
583 cpuacct_charge(curtask, delta_exec);
584 account_group_exec_runtime(curtask, delta_exec);
585 }
586}
587
588static inline void
589update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
590{
591 schedstat_set(se->statistics.wait_start, rq_of(cfs_rq)->clock);
592}
593
594/*
595 * Task is being enqueued - update stats:
596 */
597static void update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
598{
599 /*
600 * Are we enqueueing a waiting task? (for current tasks
601 * a dequeue/enqueue event is a NOP)
602 */
603 if (se != cfs_rq->curr)
604 update_stats_wait_start(cfs_rq, se);
605}
606
607static void
608update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
609{
610 schedstat_set(se->statistics.wait_max, max(se->statistics.wait_max,
611 rq_of(cfs_rq)->clock - se->statistics.wait_start));
612 schedstat_set(se->statistics.wait_count, se->statistics.wait_count + 1);
613 schedstat_set(se->statistics.wait_sum, se->statistics.wait_sum +
614 rq_of(cfs_rq)->clock - se->statistics.wait_start);
615#ifdef CONFIG_SCHEDSTATS
616 if (entity_is_task(se)) {
617 trace_sched_stat_wait(task_of(se),
618 rq_of(cfs_rq)->clock - se->statistics.wait_start);
619 }
620#endif
621 schedstat_set(se->statistics.wait_start, 0);
622}
623
624static inline void
625update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
626{
627 /*
628 * Mark the end of the wait period if dequeueing a
629 * waiting task:
630 */
631 if (se != cfs_rq->curr)
632 update_stats_wait_end(cfs_rq, se);
633}
634
635/*
636 * We are picking a new current task - update its stats:
637 */
638static inline void
639update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
640{
641 /*
642 * We are starting a new run period:
643 */
644 se->exec_start = rq_of(cfs_rq)->clock_task;
645}
646
647/**************************************************
648 * Scheduling class queueing methods:
649 */
650
651#if defined CONFIG_SMP && defined CONFIG_FAIR_GROUP_SCHED
652static void
653add_cfs_task_weight(struct cfs_rq *cfs_rq, unsigned long weight)
654{
655 cfs_rq->task_weight += weight;
656}
657#else
658static inline void
659add_cfs_task_weight(struct cfs_rq *cfs_rq, unsigned long weight)
660{
661}
662#endif
663
664static void
665account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
666{
667 update_load_add(&cfs_rq->load, se->load.weight);
668 if (!parent_entity(se))
669 inc_cpu_load(rq_of(cfs_rq), se->load.weight);
670 if (entity_is_task(se)) {
671 add_cfs_task_weight(cfs_rq, se->load.weight);
672 list_add(&se->group_node, &cfs_rq->tasks);
673 }
674 cfs_rq->nr_running++;
675}
676
677static void
678account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
679{
680 update_load_sub(&cfs_rq->load, se->load.weight);
681 if (!parent_entity(se))
682 dec_cpu_load(rq_of(cfs_rq), se->load.weight);
683 if (entity_is_task(se)) {
684 add_cfs_task_weight(cfs_rq, -se->load.weight);
685 list_del_init(&se->group_node);
686 }
687 cfs_rq->nr_running--;
688}
689
690#ifdef CONFIG_FAIR_GROUP_SCHED
691# ifdef CONFIG_SMP
692static void update_cfs_rq_load_contribution(struct cfs_rq *cfs_rq,
693 int global_update)
694{
695 struct task_group *tg = cfs_rq->tg;
696 long load_avg;
697
698 load_avg = div64_u64(cfs_rq->load_avg, cfs_rq->load_period+1);
699 load_avg -= cfs_rq->load_contribution;
700
701 if (global_update || abs(load_avg) > cfs_rq->load_contribution / 8) {
702 atomic_add(load_avg, &tg->load_weight);
703 cfs_rq->load_contribution += load_avg;
704 }
705}
706
707static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
708{
709 u64 period = sysctl_sched_shares_window;
710 u64 now, delta;
711 unsigned long load = cfs_rq->load.weight;
712
713 if (cfs_rq->tg == &root_task_group)
714 return;
715
716 now = rq_of(cfs_rq)->clock_task;
717 delta = now - cfs_rq->load_stamp;
718
719 /* truncate load history at 4 idle periods */
720 if (cfs_rq->load_stamp > cfs_rq->load_last &&
721 now - cfs_rq->load_last > 4 * period) {
722 cfs_rq->load_period = 0;
723 cfs_rq->load_avg = 0;
724 delta = period - 1;
725 }
726
727 cfs_rq->load_stamp = now;
728 cfs_rq->load_unacc_exec_time = 0;
729 cfs_rq->load_period += delta;
730 if (load) {
731 cfs_rq->load_last = now;
732 cfs_rq->load_avg += delta * load;
733 }
734
735 /* consider updating load contribution on each fold or truncate */
736 if (global_update || cfs_rq->load_period > period
737 || !cfs_rq->load_period)
738 update_cfs_rq_load_contribution(cfs_rq, global_update);
739
740 while (cfs_rq->load_period > period) {
741 /*
742 * Inline assembly required to prevent the compiler
743 * optimising this loop into a divmod call.
744 * See __iter_div_u64_rem() for another example of this.
745 */
746 asm("" : "+rm" (cfs_rq->load_period));
747 cfs_rq->load_period /= 2;
748 cfs_rq->load_avg /= 2;
749 }
750
751 if (!cfs_rq->curr && !cfs_rq->nr_running && !cfs_rq->load_avg)
752 list_del_leaf_cfs_rq(cfs_rq);
753}
754
755static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
756{
757 long load_weight, load, shares;
758
759 load = cfs_rq->load.weight;
760
761 load_weight = atomic_read(&tg->load_weight);
762 load_weight += load;
763 load_weight -= cfs_rq->load_contribution;
764
765 shares = (tg->shares * load);
766 if (load_weight)
767 shares /= load_weight;
768
769 if (shares < MIN_SHARES)
770 shares = MIN_SHARES;
771 if (shares > tg->shares)
772 shares = tg->shares;
773
774 return shares;
775}
776
777static void update_entity_shares_tick(struct cfs_rq *cfs_rq)
778{
779 if (cfs_rq->load_unacc_exec_time > sysctl_sched_shares_window) {
780 update_cfs_load(cfs_rq, 0);
781 update_cfs_shares(cfs_rq);
782 }
783}
784# else /* CONFIG_SMP */
785static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
786{
787}
788
789static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
790{
791 return tg->shares;
792}
793
794static inline void update_entity_shares_tick(struct cfs_rq *cfs_rq)
795{
796}
797# endif /* CONFIG_SMP */
798static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
799 unsigned long weight)
800{
801 if (se->on_rq) {
802 /* commit outstanding execution time */
803 if (cfs_rq->curr == se)
804 update_curr(cfs_rq);
805 account_entity_dequeue(cfs_rq, se);
806 }
807
808 update_load_set(&se->load, weight);
809
810 if (se->on_rq)
811 account_entity_enqueue(cfs_rq, se);
812}
813
814static void update_cfs_shares(struct cfs_rq *cfs_rq)
815{
816 struct task_group *tg;
817 struct sched_entity *se;
818 long shares;
819
820 tg = cfs_rq->tg;
821 se = tg->se[cpu_of(rq_of(cfs_rq))];
822 if (!se)
823 return;
824#ifndef CONFIG_SMP
825 if (likely(se->load.weight == tg->shares))
826 return;
827#endif
828 shares = calc_cfs_shares(cfs_rq, tg);
829
830 reweight_entity(cfs_rq_of(se), se, shares);
831}
832#else /* CONFIG_FAIR_GROUP_SCHED */
833static void update_cfs_load(struct cfs_rq *cfs_rq, int global_update)
834{
835}
836
837static inline void update_cfs_shares(struct cfs_rq *cfs_rq)
838{
839}
840
841static inline void update_entity_shares_tick(struct cfs_rq *cfs_rq)
842{
843}
844#endif /* CONFIG_FAIR_GROUP_SCHED */
845
846static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
847{
848#ifdef CONFIG_SCHEDSTATS
849 struct task_struct *tsk = NULL;
850
851 if (entity_is_task(se))
852 tsk = task_of(se);
853
854 if (se->statistics.sleep_start) {
855 u64 delta = rq_of(cfs_rq)->clock - se->statistics.sleep_start;
856
857 if ((s64)delta < 0)
858 delta = 0;
859
860 if (unlikely(delta > se->statistics.sleep_max))
861 se->statistics.sleep_max = delta;
862
863 se->statistics.sleep_start = 0;
864 se->statistics.sum_sleep_runtime += delta;
865
866 if (tsk) {
867 account_scheduler_latency(tsk, delta >> 10, 1);
868 trace_sched_stat_sleep(tsk, delta);
869 }
870 }
871 if (se->statistics.block_start) {
872 u64 delta = rq_of(cfs_rq)->clock - se->statistics.block_start;
873
874 if ((s64)delta < 0)
875 delta = 0;
876
877 if (unlikely(delta > se->statistics.block_max))
878 se->statistics.block_max = delta;
879
880 se->statistics.block_start = 0;
881 se->statistics.sum_sleep_runtime += delta;
882
883 if (tsk) {
884 if (tsk->in_iowait) {
885 se->statistics.iowait_sum += delta;
886 se->statistics.iowait_count++;
887 trace_sched_stat_iowait(tsk, delta);
888 }
889
890 /*
891 * Blocking time is in units of nanosecs, so shift by
892 * 20 to get a milliseconds-range estimation of the
893 * amount of time that the task spent sleeping:
894 */
895 if (unlikely(prof_on == SLEEP_PROFILING)) {
896 profile_hits(SLEEP_PROFILING,
897 (void *)get_wchan(tsk),
898 delta >> 20);
899 }
900 account_scheduler_latency(tsk, delta >> 10, 0);
901 }
902 }
903#endif
904}
905
906static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
907{
908#ifdef CONFIG_SCHED_DEBUG
909 s64 d = se->vruntime - cfs_rq->min_vruntime;
910
911 if (d < 0)
912 d = -d;
913
914 if (d > 3*sysctl_sched_latency)
915 schedstat_inc(cfs_rq, nr_spread_over);
916#endif
917}
918
919static void
920place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
921{
922 u64 vruntime = cfs_rq->min_vruntime;
923
924 /*
925 * The 'current' period is already promised to the current tasks,
926 * however the extra weight of the new task will slow them down a
927 * little, place the new task so that it fits in the slot that
928 * stays open at the end.
929 */
930 if (initial && sched_feat(START_DEBIT))
931 vruntime += sched_vslice(cfs_rq, se);
932
933 /* sleeps up to a single latency don't count. */
934 if (!initial) {
935 unsigned long thresh = sysctl_sched_latency;
936
937 /*
938 * Halve their sleep time's effect, to allow
939 * for a gentler effect of sleepers:
940 */
941 if (sched_feat(GENTLE_FAIR_SLEEPERS))
942 thresh >>= 1;
943
944 vruntime -= thresh;
945 }
946
947 /* ensure we never gain time by being placed backwards. */
948 vruntime = max_vruntime(se->vruntime, vruntime);
949
950 se->vruntime = vruntime;
951}
952
953static void
954enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
955{
956 /*
957 * Update the normalized vruntime before updating min_vruntime
958 * through callig update_curr().
959 */
960 if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
961 se->vruntime += cfs_rq->min_vruntime;
962
963 /*
964 * Update run-time statistics of the 'current'.
965 */
966 update_curr(cfs_rq);
967 update_cfs_load(cfs_rq, 0);
968 account_entity_enqueue(cfs_rq, se);
969 update_cfs_shares(cfs_rq);
970
971 if (flags & ENQUEUE_WAKEUP) {
972 place_entity(cfs_rq, se, 0);
973 enqueue_sleeper(cfs_rq, se);
974 }
975
976 update_stats_enqueue(cfs_rq, se);
977 check_spread(cfs_rq, se);
978 if (se != cfs_rq->curr)
979 __enqueue_entity(cfs_rq, se);
980 se->on_rq = 1;
981
982 if (cfs_rq->nr_running == 1)
983 list_add_leaf_cfs_rq(cfs_rq);
984}
985
986static void __clear_buddies_last(struct sched_entity *se)
987{
988 for_each_sched_entity(se) {
989 struct cfs_rq *cfs_rq = cfs_rq_of(se);
990 if (cfs_rq->last == se)
991 cfs_rq->last = NULL;
992 else
993 break;
994 }
995}
996
997static void __clear_buddies_next(struct sched_entity *se)
998{
999 for_each_sched_entity(se) {
1000 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1001 if (cfs_rq->next == se)
1002 cfs_rq->next = NULL;
1003 else
1004 break;
1005 }
1006}
1007
1008static void __clear_buddies_skip(struct sched_entity *se)
1009{
1010 for_each_sched_entity(se) {
1011 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1012 if (cfs_rq->skip == se)
1013 cfs_rq->skip = NULL;
1014 else
1015 break;
1016 }
1017}
1018
1019static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
1020{
1021 if (cfs_rq->last == se)
1022 __clear_buddies_last(se);
1023
1024 if (cfs_rq->next == se)
1025 __clear_buddies_next(se);
1026
1027 if (cfs_rq->skip == se)
1028 __clear_buddies_skip(se);
1029}
1030
1031static void
1032dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
1033{
1034 /*
1035 * Update run-time statistics of the 'current'.
1036 */
1037 update_curr(cfs_rq);
1038
1039 update_stats_dequeue(cfs_rq, se);
1040 if (flags & DEQUEUE_SLEEP) {
1041#ifdef CONFIG_SCHEDSTATS
1042 if (entity_is_task(se)) {
1043 struct task_struct *tsk = task_of(se);
1044
1045 if (tsk->state & TASK_INTERRUPTIBLE)
1046 se->statistics.sleep_start = rq_of(cfs_rq)->clock;
1047 if (tsk->state & TASK_UNINTERRUPTIBLE)
1048 se->statistics.block_start = rq_of(cfs_rq)->clock;
1049 }
1050#endif
1051 }
1052
1053 clear_buddies(cfs_rq, se);
1054
1055 if (se != cfs_rq->curr)
1056 __dequeue_entity(cfs_rq, se);
1057 se->on_rq = 0;
1058 update_cfs_load(cfs_rq, 0);
1059 account_entity_dequeue(cfs_rq, se);
1060
1061 /*
1062 * Normalize the entity after updating the min_vruntime because the
1063 * update can refer to the ->curr item and we need to reflect this
1064 * movement in our normalized position.
1065 */
1066 if (!(flags & DEQUEUE_SLEEP))
1067 se->vruntime -= cfs_rq->min_vruntime;
1068
1069 update_min_vruntime(cfs_rq);
1070 update_cfs_shares(cfs_rq);
1071}
1072
1073/*
1074 * Preempt the current task with a newly woken task if needed:
1075 */
1076static void
1077check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
1078{
1079 unsigned long ideal_runtime, delta_exec;
1080
1081 ideal_runtime = sched_slice(cfs_rq, curr);
1082 delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
1083 if (delta_exec > ideal_runtime) {
1084 resched_task(rq_of(cfs_rq)->curr);
1085 /*
1086 * The current task ran long enough, ensure it doesn't get
1087 * re-elected due to buddy favours.
1088 */
1089 clear_buddies(cfs_rq, curr);
1090 return;
1091 }
1092
1093 /*
1094 * Ensure that a task that missed wakeup preemption by a
1095 * narrow margin doesn't have to wait for a full slice.
1096 * This also mitigates buddy induced latencies under load.
1097 */
1098 if (!sched_feat(WAKEUP_PREEMPT))
1099 return;
1100
1101 if (delta_exec < sysctl_sched_min_granularity)
1102 return;
1103
1104 if (cfs_rq->nr_running > 1) {
1105 struct sched_entity *se = __pick_first_entity(cfs_rq);
1106 s64 delta = curr->vruntime - se->vruntime;
1107
1108 if (delta < 0)
1109 return;
1110
1111 if (delta > ideal_runtime)
1112 resched_task(rq_of(cfs_rq)->curr);
1113 }
1114}
1115
1116static void
1117set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
1118{
1119 /* 'current' is not kept within the tree. */
1120 if (se->on_rq) {
1121 /*
1122 * Any task has to be enqueued before it get to execute on
1123 * a CPU. So account for the time it spent waiting on the
1124 * runqueue.
1125 */
1126 update_stats_wait_end(cfs_rq, se);
1127 __dequeue_entity(cfs_rq, se);
1128 }
1129
1130 update_stats_curr_start(cfs_rq, se);
1131 cfs_rq->curr = se;
1132#ifdef CONFIG_SCHEDSTATS
1133 /*
1134 * Track our maximum slice length, if the CPU's load is at
1135 * least twice that of our own weight (i.e. dont track it
1136 * when there are only lesser-weight tasks around):
1137 */
1138 if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
1139 se->statistics.slice_max = max(se->statistics.slice_max,
1140 se->sum_exec_runtime - se->prev_sum_exec_runtime);
1141 }
1142#endif
1143 se->prev_sum_exec_runtime = se->sum_exec_runtime;
1144}
1145
1146static int
1147wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
1148
1149/*
1150 * Pick the next process, keeping these things in mind, in this order:
1151 * 1) keep things fair between processes/task groups
1152 * 2) pick the "next" process, since someone really wants that to run
1153 * 3) pick the "last" process, for cache locality
1154 * 4) do not run the "skip" process, if something else is available
1155 */
1156static struct sched_entity *pick_next_entity(struct cfs_rq *cfs_rq)
1157{
1158 struct sched_entity *se = __pick_first_entity(cfs_rq);
1159 struct sched_entity *left = se;
1160
1161 /*
1162 * Avoid running the skip buddy, if running something else can
1163 * be done without getting too unfair.
1164 */
1165 if (cfs_rq->skip == se) {
1166 struct sched_entity *second = __pick_next_entity(se);
1167 if (second && wakeup_preempt_entity(second, left) < 1)
1168 se = second;
1169 }
1170
1171 /*
1172 * Prefer last buddy, try to return the CPU to a preempted task.
1173 */
1174 if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
1175 se = cfs_rq->last;
1176
1177 /*
1178 * Someone really wants this to run. If it's not unfair, run it.
1179 */
1180 if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
1181 se = cfs_rq->next;
1182
1183 clear_buddies(cfs_rq, se);
1184
1185 return se;
1186}
1187
1188static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
1189{
1190 /*
1191 * If still on the runqueue then deactivate_task()
1192 * was not called and update_curr() has to be done:
1193 */
1194 if (prev->on_rq)
1195 update_curr(cfs_rq);
1196
1197 check_spread(cfs_rq, prev);
1198 if (prev->on_rq) {
1199 update_stats_wait_start(cfs_rq, prev);
1200 /* Put 'current' back into the tree. */
1201 __enqueue_entity(cfs_rq, prev);
1202 }
1203 cfs_rq->curr = NULL;
1204}
1205
1206static void
1207entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
1208{
1209 /*
1210 * Update run-time statistics of the 'current'.
1211 */
1212 update_curr(cfs_rq);
1213
1214 /*
1215 * Update share accounting for long-running entities.
1216 */
1217 update_entity_shares_tick(cfs_rq);
1218
1219#ifdef CONFIG_SCHED_HRTICK
1220 /*
1221 * queued ticks are scheduled to match the slice, so don't bother
1222 * validating it and just reschedule.
1223 */
1224 if (queued) {
1225 resched_task(rq_of(cfs_rq)->curr);
1226 return;
1227 }
1228 /*
1229 * don't let the period tick interfere with the hrtick preemption
1230 */
1231 if (!sched_feat(DOUBLE_TICK) &&
1232 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
1233 return;
1234#endif
1235
1236 if (cfs_rq->nr_running > 1 || !sched_feat(WAKEUP_PREEMPT))
1237 check_preempt_tick(cfs_rq, curr);
1238}
1239
1240/**************************************************
1241 * CFS operations on tasks:
1242 */
1243
1244#ifdef CONFIG_SCHED_HRTICK
1245static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
1246{
1247 struct sched_entity *se = &p->se;
1248 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1249
1250 WARN_ON(task_rq(p) != rq);
1251
1252 if (hrtick_enabled(rq) && cfs_rq->nr_running > 1) {
1253 u64 slice = sched_slice(cfs_rq, se);
1254 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
1255 s64 delta = slice - ran;
1256
1257 if (delta < 0) {
1258 if (rq->curr == p)
1259 resched_task(p);
1260 return;
1261 }
1262
1263 /*
1264 * Don't schedule slices shorter than 10000ns, that just
1265 * doesn't make sense. Rely on vruntime for fairness.
1266 */
1267 if (rq->curr != p)
1268 delta = max_t(s64, 10000LL, delta);
1269
1270 hrtick_start(rq, delta);
1271 }
1272}
1273
1274/*
1275 * called from enqueue/dequeue and updates the hrtick when the
1276 * current task is from our class and nr_running is low enough
1277 * to matter.
1278 */
1279static void hrtick_update(struct rq *rq)
1280{
1281 struct task_struct *curr = rq->curr;
1282
1283 if (curr->sched_class != &fair_sched_class)
1284 return;
1285
1286 if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
1287 hrtick_start_fair(rq, curr);
1288}
1289#else /* !CONFIG_SCHED_HRTICK */
1290static inline void
1291hrtick_start_fair(struct rq *rq, struct task_struct *p)
1292{
1293}
1294
1295static inline void hrtick_update(struct rq *rq)
1296{
1297}
1298#endif
1299
1300/*
1301 * The enqueue_task method is called before nr_running is
1302 * increased. Here we update the fair scheduling stats and
1303 * then put the task into the rbtree:
1304 */
1305static void
1306enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
1307{
1308 struct cfs_rq *cfs_rq;
1309 struct sched_entity *se = &p->se;
1310
1311 for_each_sched_entity(se) {
1312 if (se->on_rq)
1313 break;
1314 cfs_rq = cfs_rq_of(se);
1315 enqueue_entity(cfs_rq, se, flags);
1316 flags = ENQUEUE_WAKEUP;
1317 }
1318
1319 for_each_sched_entity(se) {
1320 cfs_rq = cfs_rq_of(se);
1321
1322 update_cfs_load(cfs_rq, 0);
1323 update_cfs_shares(cfs_rq);
1324 }
1325
1326 hrtick_update(rq);
1327}
1328
1329static void set_next_buddy(struct sched_entity *se);
1330
1331/*
1332 * The dequeue_task method is called before nr_running is
1333 * decreased. We remove the task from the rbtree and
1334 * update the fair scheduling stats:
1335 */
1336static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
1337{
1338 struct cfs_rq *cfs_rq;
1339 struct sched_entity *se = &p->se;
1340 int task_sleep = flags & DEQUEUE_SLEEP;
1341
1342 for_each_sched_entity(se) {
1343 cfs_rq = cfs_rq_of(se);
1344 dequeue_entity(cfs_rq, se, flags);
1345
1346 /* Don't dequeue parent if it has other entities besides us */
1347 if (cfs_rq->load.weight) {
1348 /*
1349 * Bias pick_next to pick a task from this cfs_rq, as
1350 * p is sleeping when it is within its sched_slice.
1351 */
1352 if (task_sleep && parent_entity(se))
1353 set_next_buddy(parent_entity(se));
1354
1355 /* avoid re-evaluating load for this entity */
1356 se = parent_entity(se);
1357 break;
1358 }
1359 flags |= DEQUEUE_SLEEP;
1360 }
1361
1362 for_each_sched_entity(se) {
1363 cfs_rq = cfs_rq_of(se);
1364
1365 update_cfs_load(cfs_rq, 0);
1366 update_cfs_shares(cfs_rq);
1367 }
1368
1369 hrtick_update(rq);
1370}
1371
1372#ifdef CONFIG_SMP
1373
1374static void task_waking_fair(struct task_struct *p)
1375{
1376 struct sched_entity *se = &p->se;
1377 struct cfs_rq *cfs_rq = cfs_rq_of(se);
1378 u64 min_vruntime;
1379
1380#ifndef CONFIG_64BIT
1381 u64 min_vruntime_copy;
1382
1383 do {
1384 min_vruntime_copy = cfs_rq->min_vruntime_copy;
1385 smp_rmb();
1386 min_vruntime = cfs_rq->min_vruntime;
1387 } while (min_vruntime != min_vruntime_copy);
1388#else
1389 min_vruntime = cfs_rq->min_vruntime;
1390#endif
1391
1392 se->vruntime -= min_vruntime;
1393}
1394
1395#ifdef CONFIG_FAIR_GROUP_SCHED
1396/*
1397 * effective_load() calculates the load change as seen from the root_task_group
1398 *
1399 * Adding load to a group doesn't make a group heavier, but can cause movement
1400 * of group shares between cpus. Assuming the shares were perfectly aligned one
1401 * can calculate the shift in shares.
1402 */
1403static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
1404{
1405 struct sched_entity *se = tg->se[cpu];
1406
1407 if (!tg->parent)
1408 return wl;
1409
1410 for_each_sched_entity(se) {
1411 long lw, w;
1412
1413 tg = se->my_q->tg;
1414 w = se->my_q->load.weight;
1415
1416 /* use this cpu's instantaneous contribution */
1417 lw = atomic_read(&tg->load_weight);
1418 lw -= se->my_q->load_contribution;
1419 lw += w + wg;
1420
1421 wl += w;
1422
1423 if (lw > 0 && wl < lw)
1424 wl = (wl * tg->shares) / lw;
1425 else
1426 wl = tg->shares;
1427
1428 /* zero point is MIN_SHARES */
1429 if (wl < MIN_SHARES)
1430 wl = MIN_SHARES;
1431 wl -= se->load.weight;
1432 wg = 0;
1433 }
1434
1435 return wl;
1436}
1437
1438#else
1439
1440static inline unsigned long effective_load(struct task_group *tg, int cpu,
1441 unsigned long wl, unsigned long wg)
1442{
1443 return wl;
1444}
1445
1446#endif
1447
1448static int wake_affine(struct sched_domain *sd, struct task_struct *p, int sync)
1449{
1450 s64 this_load, load;
1451 int idx, this_cpu, prev_cpu;
1452 unsigned long tl_per_task;
1453 struct task_group *tg;
1454 unsigned long weight;
1455 int balanced;
1456
1457 idx = sd->wake_idx;
1458 this_cpu = smp_processor_id();
1459 prev_cpu = task_cpu(p);
1460 load = source_load(prev_cpu, idx);
1461 this_load = target_load(this_cpu, idx);
1462
1463 /*
1464 * If sync wakeup then subtract the (maximum possible)
1465 * effect of the currently running task from the load
1466 * of the current CPU:
1467 */
1468 if (sync) {
1469 tg = task_group(current);
1470 weight = current->se.load.weight;
1471
1472 this_load += effective_load(tg, this_cpu, -weight, -weight);
1473 load += effective_load(tg, prev_cpu, 0, -weight);
1474 }
1475
1476 tg = task_group(p);
1477 weight = p->se.load.weight;
1478
1479 /*
1480 * In low-load situations, where prev_cpu is idle and this_cpu is idle
1481 * due to the sync cause above having dropped this_load to 0, we'll
1482 * always have an imbalance, but there's really nothing you can do
1483 * about that, so that's good too.
1484 *
1485 * Otherwise check if either cpus are near enough in load to allow this
1486 * task to be woken on this_cpu.
1487 */
1488 if (this_load > 0) {
1489 s64 this_eff_load, prev_eff_load;
1490
1491 this_eff_load = 100;
1492 this_eff_load *= power_of(prev_cpu);
1493 this_eff_load *= this_load +
1494 effective_load(tg, this_cpu, weight, weight);
1495
1496 prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
1497 prev_eff_load *= power_of(this_cpu);
1498 prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
1499
1500 balanced = this_eff_load <= prev_eff_load;
1501 } else
1502 balanced = true;
1503
1504 /*
1505 * If the currently running task will sleep within
1506 * a reasonable amount of time then attract this newly
1507 * woken task:
1508 */
1509 if (sync && balanced)
1510 return 1;
1511
1512 schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
1513 tl_per_task = cpu_avg_load_per_task(this_cpu);
1514
1515 if (balanced ||
1516 (this_load <= load &&
1517 this_load + target_load(prev_cpu, idx) <= tl_per_task)) {
1518 /*
1519 * This domain has SD_WAKE_AFFINE and
1520 * p is cache cold in this domain, and
1521 * there is no bad imbalance.
1522 */
1523 schedstat_inc(sd, ttwu_move_affine);
1524 schedstat_inc(p, se.statistics.nr_wakeups_affine);
1525
1526 return 1;
1527 }
1528 return 0;
1529}
1530
1531/*
1532 * find_idlest_group finds and returns the least busy CPU group within the
1533 * domain.
1534 */
1535static struct sched_group *
1536find_idlest_group(struct sched_domain *sd, struct task_struct *p,
1537 int this_cpu, int load_idx)
1538{
1539 struct sched_group *idlest = NULL, *group = sd->groups;
1540 unsigned long min_load = ULONG_MAX, this_load = 0;
1541 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1542
1543 do {
1544 unsigned long load, avg_load;
1545 int local_group;
1546 int i;
1547
1548 /* Skip over this group if it has no CPUs allowed */
1549 if (!cpumask_intersects(sched_group_cpus(group),
1550 &p->cpus_allowed))
1551 continue;
1552
1553 local_group = cpumask_test_cpu(this_cpu,
1554 sched_group_cpus(group));
1555
1556 /* Tally up the load of all CPUs in the group */
1557 avg_load = 0;
1558
1559 for_each_cpu(i, sched_group_cpus(group)) {
1560 /* Bias balancing toward cpus of our domain */
1561 if (local_group)
1562 load = source_load(i, load_idx);
1563 else
1564 load = target_load(i, load_idx);
1565
1566 avg_load += load;
1567 }
1568
1569 /* Adjust by relative CPU power of the group */
1570 avg_load = (avg_load * SCHED_POWER_SCALE) / group->sgp->power;
1571
1572 if (local_group) {
1573 this_load = avg_load;
1574 } else if (avg_load < min_load) {
1575 min_load = avg_load;
1576 idlest = group;
1577 }
1578 } while (group = group->next, group != sd->groups);
1579
1580 if (!idlest || 100*this_load < imbalance*min_load)
1581 return NULL;
1582 return idlest;
1583}
1584
1585/*
1586 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1587 */
1588static int
1589find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1590{
1591 unsigned long load, min_load = ULONG_MAX;
1592 int idlest = -1;
1593 int i;
1594
1595 /* Traverse only the allowed CPUs */
1596 for_each_cpu_and(i, sched_group_cpus(group), &p->cpus_allowed) {
1597 load = weighted_cpuload(i);
1598
1599 if (load < min_load || (load == min_load && i == this_cpu)) {
1600 min_load = load;
1601 idlest = i;
1602 }
1603 }
1604
1605 return idlest;
1606}
1607
1608/*
1609 * Try and locate an idle CPU in the sched_domain.
1610 */
1611static int select_idle_sibling(struct task_struct *p, int target)
1612{
1613 int cpu = smp_processor_id();
1614 int prev_cpu = task_cpu(p);
1615 struct sched_domain *sd;
1616 int i;
1617
1618 /*
1619 * If the task is going to be woken-up on this cpu and if it is
1620 * already idle, then it is the right target.
1621 */
1622 if (target == cpu && idle_cpu(cpu))
1623 return cpu;
1624
1625 /*
1626 * If the task is going to be woken-up on the cpu where it previously
1627 * ran and if it is currently idle, then it the right target.
1628 */
1629 if (target == prev_cpu && idle_cpu(prev_cpu))
1630 return prev_cpu;
1631
1632 /*
1633 * Otherwise, iterate the domains and find an elegible idle cpu.
1634 */
1635 rcu_read_lock();
1636 for_each_domain(target, sd) {
1637 if (!(sd->flags & SD_SHARE_PKG_RESOURCES))
1638 break;
1639
1640 for_each_cpu_and(i, sched_domain_span(sd), &p->cpus_allowed) {
1641 if (idle_cpu(i)) {
1642 target = i;
1643 break;
1644 }
1645 }
1646
1647 /*
1648 * Lets stop looking for an idle sibling when we reached
1649 * the domain that spans the current cpu and prev_cpu.
1650 */
1651 if (cpumask_test_cpu(cpu, sched_domain_span(sd)) &&
1652 cpumask_test_cpu(prev_cpu, sched_domain_span(sd)))
1653 break;
1654 }
1655 rcu_read_unlock();
1656
1657 return target;
1658}
1659
1660/*
1661 * sched_balance_self: balance the current task (running on cpu) in domains
1662 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1663 * SD_BALANCE_EXEC.
1664 *
1665 * Balance, ie. select the least loaded group.
1666 *
1667 * Returns the target CPU number, or the same CPU if no balancing is needed.
1668 *
1669 * preempt must be disabled.
1670 */
1671static int
1672select_task_rq_fair(struct task_struct *p, int sd_flag, int wake_flags)
1673{
1674 struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
1675 int cpu = smp_processor_id();
1676 int prev_cpu = task_cpu(p);
1677 int new_cpu = cpu;
1678 int want_affine = 0;
1679 int want_sd = 1;
1680 int sync = wake_flags & WF_SYNC;
1681
1682 if (sd_flag & SD_BALANCE_WAKE) {
1683 if (cpumask_test_cpu(cpu, &p->cpus_allowed))
1684 want_affine = 1;
1685 new_cpu = prev_cpu;
1686 }
1687
1688 rcu_read_lock();
1689 for_each_domain(cpu, tmp) {
1690 if (!(tmp->flags & SD_LOAD_BALANCE))
1691 continue;
1692
1693 /*
1694 * If power savings logic is enabled for a domain, see if we
1695 * are not overloaded, if so, don't balance wider.
1696 */
1697 if (tmp->flags & (SD_POWERSAVINGS_BALANCE|SD_PREFER_LOCAL)) {
1698 unsigned long power = 0;
1699 unsigned long nr_running = 0;
1700 unsigned long capacity;
1701 int i;
1702
1703 for_each_cpu(i, sched_domain_span(tmp)) {
1704 power += power_of(i);
1705 nr_running += cpu_rq(i)->cfs.nr_running;
1706 }
1707
1708 capacity = DIV_ROUND_CLOSEST(power, SCHED_POWER_SCALE);
1709
1710 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1711 nr_running /= 2;
1712
1713 if (nr_running < capacity)
1714 want_sd = 0;
1715 }
1716
1717 /*
1718 * If both cpu and prev_cpu are part of this domain,
1719 * cpu is a valid SD_WAKE_AFFINE target.
1720 */
1721 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
1722 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
1723 affine_sd = tmp;
1724 want_affine = 0;
1725 }
1726
1727 if (!want_sd && !want_affine)
1728 break;
1729
1730 if (!(tmp->flags & sd_flag))
1731 continue;
1732
1733 if (want_sd)
1734 sd = tmp;
1735 }
1736
1737 if (affine_sd) {
1738 if (cpu == prev_cpu || wake_affine(affine_sd, p, sync))
1739 prev_cpu = cpu;
1740
1741 new_cpu = select_idle_sibling(p, prev_cpu);
1742 goto unlock;
1743 }
1744
1745 while (sd) {
1746 int load_idx = sd->forkexec_idx;
1747 struct sched_group *group;
1748 int weight;
1749
1750 if (!(sd->flags & sd_flag)) {
1751 sd = sd->child;
1752 continue;
1753 }
1754
1755 if (sd_flag & SD_BALANCE_WAKE)
1756 load_idx = sd->wake_idx;
1757
1758 group = find_idlest_group(sd, p, cpu, load_idx);
1759 if (!group) {
1760 sd = sd->child;
1761 continue;
1762 }
1763
1764 new_cpu = find_idlest_cpu(group, p, cpu);
1765 if (new_cpu == -1 || new_cpu == cpu) {
1766 /* Now try balancing at a lower domain level of cpu */
1767 sd = sd->child;
1768 continue;
1769 }
1770
1771 /* Now try balancing at a lower domain level of new_cpu */
1772 cpu = new_cpu;
1773 weight = sd->span_weight;
1774 sd = NULL;
1775 for_each_domain(cpu, tmp) {
1776 if (weight <= tmp->span_weight)
1777 break;
1778 if (tmp->flags & sd_flag)
1779 sd = tmp;
1780 }
1781 /* while loop will break here if sd == NULL */
1782 }
1783unlock:
1784 rcu_read_unlock();
1785
1786 return new_cpu;
1787}
1788#endif /* CONFIG_SMP */
1789
1790static unsigned long
1791wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
1792{
1793 unsigned long gran = sysctl_sched_wakeup_granularity;
1794
1795 /*
1796 * Since its curr running now, convert the gran from real-time
1797 * to virtual-time in his units.
1798 *
1799 * By using 'se' instead of 'curr' we penalize light tasks, so
1800 * they get preempted easier. That is, if 'se' < 'curr' then
1801 * the resulting gran will be larger, therefore penalizing the
1802 * lighter, if otoh 'se' > 'curr' then the resulting gran will
1803 * be smaller, again penalizing the lighter task.
1804 *
1805 * This is especially important for buddies when the leftmost
1806 * task is higher priority than the buddy.
1807 */
1808 return calc_delta_fair(gran, se);
1809}
1810
1811/*
1812 * Should 'se' preempt 'curr'.
1813 *
1814 * |s1
1815 * |s2
1816 * |s3
1817 * g
1818 * |<--->|c
1819 *
1820 * w(c, s1) = -1
1821 * w(c, s2) = 0
1822 * w(c, s3) = 1
1823 *
1824 */
1825static int
1826wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
1827{
1828 s64 gran, vdiff = curr->vruntime - se->vruntime;
1829
1830 if (vdiff <= 0)
1831 return -1;
1832
1833 gran = wakeup_gran(curr, se);
1834 if (vdiff > gran)
1835 return 1;
1836
1837 return 0;
1838}
1839
1840static void set_last_buddy(struct sched_entity *se)
1841{
1842 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
1843 return;
1844
1845 for_each_sched_entity(se)
1846 cfs_rq_of(se)->last = se;
1847}
1848
1849static void set_next_buddy(struct sched_entity *se)
1850{
1851 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
1852 return;
1853
1854 for_each_sched_entity(se)
1855 cfs_rq_of(se)->next = se;
1856}
1857
1858static void set_skip_buddy(struct sched_entity *se)
1859{
1860 for_each_sched_entity(se)
1861 cfs_rq_of(se)->skip = se;
1862}
1863
1864/*
1865 * Preempt the current task with a newly woken task if needed:
1866 */
1867static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
1868{
1869 struct task_struct *curr = rq->curr;
1870 struct sched_entity *se = &curr->se, *pse = &p->se;
1871 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
1872 int scale = cfs_rq->nr_running >= sched_nr_latency;
1873 int next_buddy_marked = 0;
1874
1875 if (unlikely(se == pse))
1876 return;
1877
1878 if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
1879 set_next_buddy(pse);
1880 next_buddy_marked = 1;
1881 }
1882
1883 /*
1884 * We can come here with TIF_NEED_RESCHED already set from new task
1885 * wake up path.
1886 */
1887 if (test_tsk_need_resched(curr))
1888 return;
1889
1890 /* Idle tasks are by definition preempted by non-idle tasks. */
1891 if (unlikely(curr->policy == SCHED_IDLE) &&
1892 likely(p->policy != SCHED_IDLE))
1893 goto preempt;
1894
1895 /*
1896 * Batch and idle tasks do not preempt non-idle tasks (their preemption
1897 * is driven by the tick):
1898 */
1899 if (unlikely(p->policy != SCHED_NORMAL))
1900 return;
1901
1902
1903 if (!sched_feat(WAKEUP_PREEMPT))
1904 return;
1905
1906 find_matching_se(&se, &pse);
1907 update_curr(cfs_rq_of(se));
1908 BUG_ON(!pse);
1909 if (wakeup_preempt_entity(se, pse) == 1) {
1910 /*
1911 * Bias pick_next to pick the sched entity that is
1912 * triggering this preemption.
1913 */
1914 if (!next_buddy_marked)
1915 set_next_buddy(pse);
1916 goto preempt;
1917 }
1918
1919 return;
1920
1921preempt:
1922 resched_task(curr);
1923 /*
1924 * Only set the backward buddy when the current task is still
1925 * on the rq. This can happen when a wakeup gets interleaved
1926 * with schedule on the ->pre_schedule() or idle_balance()
1927 * point, either of which can * drop the rq lock.
1928 *
1929 * Also, during early boot the idle thread is in the fair class,
1930 * for obvious reasons its a bad idea to schedule back to it.
1931 */
1932 if (unlikely(!se->on_rq || curr == rq->idle))
1933 return;
1934
1935 if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
1936 set_last_buddy(se);
1937}
1938
1939static struct task_struct *pick_next_task_fair(struct rq *rq)
1940{
1941 struct task_struct *p;
1942 struct cfs_rq *cfs_rq = &rq->cfs;
1943 struct sched_entity *se;
1944
1945 if (!cfs_rq->nr_running)
1946 return NULL;
1947
1948 do {
1949 se = pick_next_entity(cfs_rq);
1950 set_next_entity(cfs_rq, se);
1951 cfs_rq = group_cfs_rq(se);
1952 } while (cfs_rq);
1953
1954 p = task_of(se);
1955 hrtick_start_fair(rq, p);
1956
1957 return p;
1958}
1959
1960/*
1961 * Account for a descheduled task:
1962 */
1963static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
1964{
1965 struct sched_entity *se = &prev->se;
1966 struct cfs_rq *cfs_rq;
1967
1968 for_each_sched_entity(se) {
1969 cfs_rq = cfs_rq_of(se);
1970 put_prev_entity(cfs_rq, se);
1971 }
1972}
1973
1974/*
1975 * sched_yield() is very simple
1976 *
1977 * The magic of dealing with the ->skip buddy is in pick_next_entity.
1978 */
1979static void yield_task_fair(struct rq *rq)
1980{
1981 struct task_struct *curr = rq->curr;
1982 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
1983 struct sched_entity *se = &curr->se;
1984
1985 /*
1986 * Are we the only task in the tree?
1987 */
1988 if (unlikely(rq->nr_running == 1))
1989 return;
1990
1991 clear_buddies(cfs_rq, se);
1992
1993 if (curr->policy != SCHED_BATCH) {
1994 update_rq_clock(rq);
1995 /*
1996 * Update run-time statistics of the 'current'.
1997 */
1998 update_curr(cfs_rq);
1999 }
2000
2001 set_skip_buddy(se);
2002}
2003
2004static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
2005{
2006 struct sched_entity *se = &p->se;
2007
2008 if (!se->on_rq)
2009 return false;
2010
2011 /* Tell the scheduler that we'd really like pse to run next. */
2012 set_next_buddy(se);
2013
2014 yield_task_fair(rq);
2015
2016 return true;
2017}
2018
2019#ifdef CONFIG_SMP
2020/**************************************************
2021 * Fair scheduling class load-balancing methods:
2022 */
2023
2024/*
2025 * pull_task - move a task from a remote runqueue to the local runqueue.
2026 * Both runqueues must be locked.
2027 */
2028static void pull_task(struct rq *src_rq, struct task_struct *p,
2029 struct rq *this_rq, int this_cpu)
2030{
2031 deactivate_task(src_rq, p, 0);
2032 set_task_cpu(p, this_cpu);
2033 activate_task(this_rq, p, 0);
2034 check_preempt_curr(this_rq, p, 0);
2035}
2036
2037/*
2038 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2039 */
2040static
2041int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2042 struct sched_domain *sd, enum cpu_idle_type idle,
2043 int *all_pinned)
2044{
2045 int tsk_cache_hot = 0;
2046 /*
2047 * We do not migrate tasks that are:
2048 * 1) running (obviously), or
2049 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2050 * 3) are cache-hot on their current CPU.
2051 */
2052 if (!cpumask_test_cpu(this_cpu, &p->cpus_allowed)) {
2053 schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
2054 return 0;
2055 }
2056 *all_pinned = 0;
2057
2058 if (task_running(rq, p)) {
2059 schedstat_inc(p, se.statistics.nr_failed_migrations_running);
2060 return 0;
2061 }
2062
2063 /*
2064 * Aggressive migration if:
2065 * 1) task is cache cold, or
2066 * 2) too many balance attempts have failed.
2067 */
2068
2069 tsk_cache_hot = task_hot(p, rq->clock_task, sd);
2070 if (!tsk_cache_hot ||
2071 sd->nr_balance_failed > sd->cache_nice_tries) {
2072#ifdef CONFIG_SCHEDSTATS
2073 if (tsk_cache_hot) {
2074 schedstat_inc(sd, lb_hot_gained[idle]);
2075 schedstat_inc(p, se.statistics.nr_forced_migrations);
2076 }
2077#endif
2078 return 1;
2079 }
2080
2081 if (tsk_cache_hot) {
2082 schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
2083 return 0;
2084 }
2085 return 1;
2086}
2087
2088/*
2089 * move_one_task tries to move exactly one task from busiest to this_rq, as
2090 * part of active balancing operations within "domain".
2091 * Returns 1 if successful and 0 otherwise.
2092 *
2093 * Called with both runqueues locked.
2094 */
2095static int
2096move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2097 struct sched_domain *sd, enum cpu_idle_type idle)
2098{
2099 struct task_struct *p, *n;
2100 struct cfs_rq *cfs_rq;
2101 int pinned = 0;
2102
2103 for_each_leaf_cfs_rq(busiest, cfs_rq) {
2104 list_for_each_entry_safe(p, n, &cfs_rq->tasks, se.group_node) {
2105
2106 if (!can_migrate_task(p, busiest, this_cpu,
2107 sd, idle, &pinned))
2108 continue;
2109
2110 pull_task(busiest, p, this_rq, this_cpu);
2111 /*
2112 * Right now, this is only the second place pull_task()
2113 * is called, so we can safely collect pull_task()
2114 * stats here rather than inside pull_task().
2115 */
2116 schedstat_inc(sd, lb_gained[idle]);
2117 return 1;
2118 }
2119 }
2120
2121 return 0;
2122}
2123
2124static unsigned long
2125balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2126 unsigned long max_load_move, struct sched_domain *sd,
2127 enum cpu_idle_type idle, int *all_pinned,
2128 struct cfs_rq *busiest_cfs_rq)
2129{
2130 int loops = 0, pulled = 0;
2131 long rem_load_move = max_load_move;
2132 struct task_struct *p, *n;
2133
2134 if (max_load_move == 0)
2135 goto out;
2136
2137 list_for_each_entry_safe(p, n, &busiest_cfs_rq->tasks, se.group_node) {
2138 if (loops++ > sysctl_sched_nr_migrate)
2139 break;
2140
2141 if ((p->se.load.weight >> 1) > rem_load_move ||
2142 !can_migrate_task(p, busiest, this_cpu, sd, idle,
2143 all_pinned))
2144 continue;
2145
2146 pull_task(busiest, p, this_rq, this_cpu);
2147 pulled++;
2148 rem_load_move -= p->se.load.weight;
2149
2150#ifdef CONFIG_PREEMPT
2151 /*
2152 * NEWIDLE balancing is a source of latency, so preemptible
2153 * kernels will stop after the first task is pulled to minimize
2154 * the critical section.
2155 */
2156 if (idle == CPU_NEWLY_IDLE)
2157 break;
2158#endif
2159
2160 /*
2161 * We only want to steal up to the prescribed amount of
2162 * weighted load.
2163 */
2164 if (rem_load_move <= 0)
2165 break;
2166 }
2167out:
2168 /*
2169 * Right now, this is one of only two places pull_task() is called,
2170 * so we can safely collect pull_task() stats here rather than
2171 * inside pull_task().
2172 */
2173 schedstat_add(sd, lb_gained[idle], pulled);
2174
2175 return max_load_move - rem_load_move;
2176}
2177
2178#ifdef CONFIG_FAIR_GROUP_SCHED
2179/*
2180 * update tg->load_weight by folding this cpu's load_avg
2181 */
2182static int update_shares_cpu(struct task_group *tg, int cpu)
2183{
2184 struct cfs_rq *cfs_rq;
2185 unsigned long flags;
2186 struct rq *rq;
2187
2188 if (!tg->se[cpu])
2189 return 0;
2190
2191 rq = cpu_rq(cpu);
2192 cfs_rq = tg->cfs_rq[cpu];
2193
2194 raw_spin_lock_irqsave(&rq->lock, flags);
2195
2196 update_rq_clock(rq);
2197 update_cfs_load(cfs_rq, 1);
2198
2199 /*
2200 * We need to update shares after updating tg->load_weight in
2201 * order to adjust the weight of groups with long running tasks.
2202 */
2203 update_cfs_shares(cfs_rq);
2204
2205 raw_spin_unlock_irqrestore(&rq->lock, flags);
2206
2207 return 0;
2208}
2209
2210static void update_shares(int cpu)
2211{
2212 struct cfs_rq *cfs_rq;
2213 struct rq *rq = cpu_rq(cpu);
2214
2215 rcu_read_lock();
2216 /*
2217 * Iterates the task_group tree in a bottom up fashion, see
2218 * list_add_leaf_cfs_rq() for details.
2219 */
2220 for_each_leaf_cfs_rq(rq, cfs_rq)
2221 update_shares_cpu(cfs_rq->tg, cpu);
2222 rcu_read_unlock();
2223}
2224
2225/*
2226 * Compute the cpu's hierarchical load factor for each task group.
2227 * This needs to be done in a top-down fashion because the load of a child
2228 * group is a fraction of its parents load.
2229 */
2230static int tg_load_down(struct task_group *tg, void *data)
2231{
2232 unsigned long load;
2233 long cpu = (long)data;
2234
2235 if (!tg->parent) {
2236 load = cpu_rq(cpu)->load.weight;
2237 } else {
2238 load = tg->parent->cfs_rq[cpu]->h_load;
2239 load *= tg->se[cpu]->load.weight;
2240 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
2241 }
2242
2243 tg->cfs_rq[cpu]->h_load = load;
2244
2245 return 0;
2246}
2247
2248static void update_h_load(long cpu)
2249{
2250 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
2251}
2252
2253static unsigned long
2254load_balance_fair(struct rq *this_rq, int this_cpu, struct rq *busiest,
2255 unsigned long max_load_move,
2256 struct sched_domain *sd, enum cpu_idle_type idle,
2257 int *all_pinned)
2258{
2259 long rem_load_move = max_load_move;
2260 struct cfs_rq *busiest_cfs_rq;
2261
2262 rcu_read_lock();
2263 update_h_load(cpu_of(busiest));
2264
2265 for_each_leaf_cfs_rq(busiest, busiest_cfs_rq) {
2266 unsigned long busiest_h_load = busiest_cfs_rq->h_load;
2267 unsigned long busiest_weight = busiest_cfs_rq->load.weight;
2268 u64 rem_load, moved_load;
2269
2270 /*
2271 * empty group
2272 */
2273 if (!busiest_cfs_rq->task_weight)
2274 continue;
2275
2276 rem_load = (u64)rem_load_move * busiest_weight;
2277 rem_load = div_u64(rem_load, busiest_h_load + 1);
2278
2279 moved_load = balance_tasks(this_rq, this_cpu, busiest,
2280 rem_load, sd, idle, all_pinned,
2281 busiest_cfs_rq);
2282
2283 if (!moved_load)
2284 continue;
2285
2286 moved_load *= busiest_h_load;
2287 moved_load = div_u64(moved_load, busiest_weight + 1);
2288
2289 rem_load_move -= moved_load;
2290 if (rem_load_move < 0)
2291 break;
2292 }
2293 rcu_read_unlock();
2294
2295 return max_load_move - rem_load_move;
2296}
2297#else
2298static inline void update_shares(int cpu)
2299{
2300}
2301
2302static unsigned long
2303load_balance_fair(struct rq *this_rq, int this_cpu, struct rq *busiest,
2304 unsigned long max_load_move,
2305 struct sched_domain *sd, enum cpu_idle_type idle,
2306 int *all_pinned)
2307{
2308 return balance_tasks(this_rq, this_cpu, busiest,
2309 max_load_move, sd, idle, all_pinned,
2310 &busiest->cfs);
2311}
2312#endif
2313
2314/*
2315 * move_tasks tries to move up to max_load_move weighted load from busiest to
2316 * this_rq, as part of a balancing operation within domain "sd".
2317 * Returns 1 if successful and 0 otherwise.
2318 *
2319 * Called with both runqueues locked.
2320 */
2321static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2322 unsigned long max_load_move,
2323 struct sched_domain *sd, enum cpu_idle_type idle,
2324 int *all_pinned)
2325{
2326 unsigned long total_load_moved = 0, load_moved;
2327
2328 do {
2329 load_moved = load_balance_fair(this_rq, this_cpu, busiest,
2330 max_load_move - total_load_moved,
2331 sd, idle, all_pinned);
2332
2333 total_load_moved += load_moved;
2334
2335#ifdef CONFIG_PREEMPT
2336 /*
2337 * NEWIDLE balancing is a source of latency, so preemptible
2338 * kernels will stop after the first task is pulled to minimize
2339 * the critical section.
2340 */
2341 if (idle == CPU_NEWLY_IDLE && this_rq->nr_running)
2342 break;
2343
2344 if (raw_spin_is_contended(&this_rq->lock) ||
2345 raw_spin_is_contended(&busiest->lock))
2346 break;
2347#endif
2348 } while (load_moved && max_load_move > total_load_moved);
2349
2350 return total_load_moved > 0;
2351}
2352
2353/********** Helpers for find_busiest_group ************************/
2354/*
2355 * sd_lb_stats - Structure to store the statistics of a sched_domain
2356 * during load balancing.
2357 */
2358struct sd_lb_stats {
2359 struct sched_group *busiest; /* Busiest group in this sd */
2360 struct sched_group *this; /* Local group in this sd */
2361 unsigned long total_load; /* Total load of all groups in sd */
2362 unsigned long total_pwr; /* Total power of all groups in sd */
2363 unsigned long avg_load; /* Average load across all groups in sd */
2364
2365 /** Statistics of this group */
2366 unsigned long this_load;
2367 unsigned long this_load_per_task;
2368 unsigned long this_nr_running;
2369 unsigned long this_has_capacity;
2370 unsigned int this_idle_cpus;
2371
2372 /* Statistics of the busiest group */
2373 unsigned int busiest_idle_cpus;
2374 unsigned long max_load;
2375 unsigned long busiest_load_per_task;
2376 unsigned long busiest_nr_running;
2377 unsigned long busiest_group_capacity;
2378 unsigned long busiest_has_capacity;
2379 unsigned int busiest_group_weight;
2380
2381 int group_imb; /* Is there imbalance in this sd */
2382#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2383 int power_savings_balance; /* Is powersave balance needed for this sd */
2384 struct sched_group *group_min; /* Least loaded group in sd */
2385 struct sched_group *group_leader; /* Group which relieves group_min */
2386 unsigned long min_load_per_task; /* load_per_task in group_min */
2387 unsigned long leader_nr_running; /* Nr running of group_leader */
2388 unsigned long min_nr_running; /* Nr running of group_min */
2389#endif
2390};
2391
2392/*
2393 * sg_lb_stats - stats of a sched_group required for load_balancing
2394 */
2395struct sg_lb_stats {
2396 unsigned long avg_load; /*Avg load across the CPUs of the group */
2397 unsigned long group_load; /* Total load over the CPUs of the group */
2398 unsigned long sum_nr_running; /* Nr tasks running in the group */
2399 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
2400 unsigned long group_capacity;
2401 unsigned long idle_cpus;
2402 unsigned long group_weight;
2403 int group_imb; /* Is there an imbalance in the group ? */
2404 int group_has_capacity; /* Is there extra capacity in the group? */
2405};
2406
2407/**
2408 * group_first_cpu - Returns the first cpu in the cpumask of a sched_group.
2409 * @group: The group whose first cpu is to be returned.
2410 */
2411static inline unsigned int group_first_cpu(struct sched_group *group)
2412{
2413 return cpumask_first(sched_group_cpus(group));
2414}
2415
2416/**
2417 * get_sd_load_idx - Obtain the load index for a given sched domain.
2418 * @sd: The sched_domain whose load_idx is to be obtained.
2419 * @idle: The Idle status of the CPU for whose sd load_icx is obtained.
2420 */
2421static inline int get_sd_load_idx(struct sched_domain *sd,
2422 enum cpu_idle_type idle)
2423{
2424 int load_idx;
2425
2426 switch (idle) {
2427 case CPU_NOT_IDLE:
2428 load_idx = sd->busy_idx;
2429 break;
2430
2431 case CPU_NEWLY_IDLE:
2432 load_idx = sd->newidle_idx;
2433 break;
2434 default:
2435 load_idx = sd->idle_idx;
2436 break;
2437 }
2438
2439 return load_idx;
2440}
2441
2442
2443#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2444/**
2445 * init_sd_power_savings_stats - Initialize power savings statistics for
2446 * the given sched_domain, during load balancing.
2447 *
2448 * @sd: Sched domain whose power-savings statistics are to be initialized.
2449 * @sds: Variable containing the statistics for sd.
2450 * @idle: Idle status of the CPU at which we're performing load-balancing.
2451 */
2452static inline void init_sd_power_savings_stats(struct sched_domain *sd,
2453 struct sd_lb_stats *sds, enum cpu_idle_type idle)
2454{
2455 /*
2456 * Busy processors will not participate in power savings
2457 * balance.
2458 */
2459 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
2460 sds->power_savings_balance = 0;
2461 else {
2462 sds->power_savings_balance = 1;
2463 sds->min_nr_running = ULONG_MAX;
2464 sds->leader_nr_running = 0;
2465 }
2466}
2467
2468/**
2469 * update_sd_power_savings_stats - Update the power saving stats for a
2470 * sched_domain while performing load balancing.
2471 *
2472 * @group: sched_group belonging to the sched_domain under consideration.
2473 * @sds: Variable containing the statistics of the sched_domain
2474 * @local_group: Does group contain the CPU for which we're performing
2475 * load balancing ?
2476 * @sgs: Variable containing the statistics of the group.
2477 */
2478static inline void update_sd_power_savings_stats(struct sched_group *group,
2479 struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
2480{
2481
2482 if (!sds->power_savings_balance)
2483 return;
2484
2485 /*
2486 * If the local group is idle or completely loaded
2487 * no need to do power savings balance at this domain
2488 */
2489 if (local_group && (sds->this_nr_running >= sgs->group_capacity ||
2490 !sds->this_nr_running))
2491 sds->power_savings_balance = 0;
2492
2493 /*
2494 * If a group is already running at full capacity or idle,
2495 * don't include that group in power savings calculations
2496 */
2497 if (!sds->power_savings_balance ||
2498 sgs->sum_nr_running >= sgs->group_capacity ||
2499 !sgs->sum_nr_running)
2500 return;
2501
2502 /*
2503 * Calculate the group which has the least non-idle load.
2504 * This is the group from where we need to pick up the load
2505 * for saving power
2506 */
2507 if ((sgs->sum_nr_running < sds->min_nr_running) ||
2508 (sgs->sum_nr_running == sds->min_nr_running &&
2509 group_first_cpu(group) > group_first_cpu(sds->group_min))) {
2510 sds->group_min = group;
2511 sds->min_nr_running = sgs->sum_nr_running;
2512 sds->min_load_per_task = sgs->sum_weighted_load /
2513 sgs->sum_nr_running;
2514 }
2515
2516 /*
2517 * Calculate the group which is almost near its
2518 * capacity but still has some space to pick up some load
2519 * from other group and save more power
2520 */
2521 if (sgs->sum_nr_running + 1 > sgs->group_capacity)
2522 return;
2523
2524 if (sgs->sum_nr_running > sds->leader_nr_running ||
2525 (sgs->sum_nr_running == sds->leader_nr_running &&
2526 group_first_cpu(group) < group_first_cpu(sds->group_leader))) {
2527 sds->group_leader = group;
2528 sds->leader_nr_running = sgs->sum_nr_running;
2529 }
2530}
2531
2532/**
2533 * check_power_save_busiest_group - see if there is potential for some power-savings balance
2534 * @sds: Variable containing the statistics of the sched_domain
2535 * under consideration.
2536 * @this_cpu: Cpu at which we're currently performing load-balancing.
2537 * @imbalance: Variable to store the imbalance.
2538 *
2539 * Description:
2540 * Check if we have potential to perform some power-savings balance.
2541 * If yes, set the busiest group to be the least loaded group in the
2542 * sched_domain, so that it's CPUs can be put to idle.
2543 *
2544 * Returns 1 if there is potential to perform power-savings balance.
2545 * Else returns 0.
2546 */
2547static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
2548 int this_cpu, unsigned long *imbalance)
2549{
2550 if (!sds->power_savings_balance)
2551 return 0;
2552
2553 if (sds->this != sds->group_leader ||
2554 sds->group_leader == sds->group_min)
2555 return 0;
2556
2557 *imbalance = sds->min_load_per_task;
2558 sds->busiest = sds->group_min;
2559
2560 return 1;
2561
2562}
2563#else /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
2564static inline void init_sd_power_savings_stats(struct sched_domain *sd,
2565 struct sd_lb_stats *sds, enum cpu_idle_type idle)
2566{
2567 return;
2568}
2569
2570static inline void update_sd_power_savings_stats(struct sched_group *group,
2571 struct sd_lb_stats *sds, int local_group, struct sg_lb_stats *sgs)
2572{
2573 return;
2574}
2575
2576static inline int check_power_save_busiest_group(struct sd_lb_stats *sds,
2577 int this_cpu, unsigned long *imbalance)
2578{
2579 return 0;
2580}
2581#endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
2582
2583
2584unsigned long default_scale_freq_power(struct sched_domain *sd, int cpu)
2585{
2586 return SCHED_POWER_SCALE;
2587}
2588
2589unsigned long __weak arch_scale_freq_power(struct sched_domain *sd, int cpu)
2590{
2591 return default_scale_freq_power(sd, cpu);
2592}
2593
2594unsigned long default_scale_smt_power(struct sched_domain *sd, int cpu)
2595{
2596 unsigned long weight = sd->span_weight;
2597 unsigned long smt_gain = sd->smt_gain;
2598
2599 smt_gain /= weight;
2600
2601 return smt_gain;
2602}
2603
2604unsigned long __weak arch_scale_smt_power(struct sched_domain *sd, int cpu)
2605{
2606 return default_scale_smt_power(sd, cpu);
2607}
2608
2609unsigned long scale_rt_power(int cpu)
2610{
2611 struct rq *rq = cpu_rq(cpu);
2612 u64 total, available;
2613
2614 total = sched_avg_period() + (rq->clock - rq->age_stamp);
2615
2616 if (unlikely(total < rq->rt_avg)) {
2617 /* Ensures that power won't end up being negative */
2618 available = 0;
2619 } else {
2620 available = total - rq->rt_avg;
2621 }
2622
2623 if (unlikely((s64)total < SCHED_POWER_SCALE))
2624 total = SCHED_POWER_SCALE;
2625
2626 total >>= SCHED_POWER_SHIFT;
2627
2628 return div_u64(available, total);
2629}
2630
2631static void update_cpu_power(struct sched_domain *sd, int cpu)
2632{
2633 unsigned long weight = sd->span_weight;
2634 unsigned long power = SCHED_POWER_SCALE;
2635 struct sched_group *sdg = sd->groups;
2636
2637 if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
2638 if (sched_feat(ARCH_POWER))
2639 power *= arch_scale_smt_power(sd, cpu);
2640 else
2641 power *= default_scale_smt_power(sd, cpu);
2642
2643 power >>= SCHED_POWER_SHIFT;
2644 }
2645
2646 sdg->sgp->power_orig = power;
2647
2648 if (sched_feat(ARCH_POWER))
2649 power *= arch_scale_freq_power(sd, cpu);
2650 else
2651 power *= default_scale_freq_power(sd, cpu);
2652
2653 power >>= SCHED_POWER_SHIFT;
2654
2655 power *= scale_rt_power(cpu);
2656 power >>= SCHED_POWER_SHIFT;
2657
2658 if (!power)
2659 power = 1;
2660
2661 cpu_rq(cpu)->cpu_power = power;
2662 sdg->sgp->power = power;
2663}
2664
2665static void update_group_power(struct sched_domain *sd, int cpu)
2666{
2667 struct sched_domain *child = sd->child;
2668 struct sched_group *group, *sdg = sd->groups;
2669 unsigned long power;
2670
2671 if (!child) {
2672 update_cpu_power(sd, cpu);
2673 return;
2674 }
2675
2676 power = 0;
2677
2678 group = child->groups;
2679 do {
2680 power += group->sgp->power;
2681 group = group->next;
2682 } while (group != child->groups);
2683
2684 sdg->sgp->power = power;
2685}
2686
2687/*
2688 * Try and fix up capacity for tiny siblings, this is needed when
2689 * things like SD_ASYM_PACKING need f_b_g to select another sibling
2690 * which on its own isn't powerful enough.
2691 *
2692 * See update_sd_pick_busiest() and check_asym_packing().
2693 */
2694static inline int
2695fix_small_capacity(struct sched_domain *sd, struct sched_group *group)
2696{
2697 /*
2698 * Only siblings can have significantly less than SCHED_POWER_SCALE
2699 */
2700 if (!(sd->flags & SD_SHARE_CPUPOWER))
2701 return 0;
2702
2703 /*
2704 * If ~90% of the cpu_power is still there, we're good.
2705 */
2706 if (group->sgp->power * 32 > group->sgp->power_orig * 29)
2707 return 1;
2708
2709 return 0;
2710}
2711
2712/**
2713 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
2714 * @sd: The sched_domain whose statistics are to be updated.
2715 * @group: sched_group whose statistics are to be updated.
2716 * @this_cpu: Cpu for which load balance is currently performed.
2717 * @idle: Idle status of this_cpu
2718 * @load_idx: Load index of sched_domain of this_cpu for load calc.
2719 * @local_group: Does group contain this_cpu.
2720 * @cpus: Set of cpus considered for load balancing.
2721 * @balance: Should we balance.
2722 * @sgs: variable to hold the statistics for this group.
2723 */
2724static inline void update_sg_lb_stats(struct sched_domain *sd,
2725 struct sched_group *group, int this_cpu,
2726 enum cpu_idle_type idle, int load_idx,
2727 int local_group, const struct cpumask *cpus,
2728 int *balance, struct sg_lb_stats *sgs)
2729{
2730 unsigned long load, max_cpu_load, min_cpu_load, max_nr_running;
2731 int i;
2732 unsigned int balance_cpu = -1, first_idle_cpu = 0;
2733 unsigned long avg_load_per_task = 0;
2734
2735 if (local_group)
2736 balance_cpu = group_first_cpu(group);
2737
2738 /* Tally up the load of all CPUs in the group */
2739 max_cpu_load = 0;
2740 min_cpu_load = ~0UL;
2741 max_nr_running = 0;
2742
2743 for_each_cpu_and(i, sched_group_cpus(group), cpus) {
2744 struct rq *rq = cpu_rq(i);
2745
2746 /* Bias balancing toward cpus of our domain */
2747 if (local_group) {
2748 if (idle_cpu(i) && !first_idle_cpu) {
2749 first_idle_cpu = 1;
2750 balance_cpu = i;
2751 }
2752
2753 load = target_load(i, load_idx);
2754 } else {
2755 load = source_load(i, load_idx);
2756 if (load > max_cpu_load) {
2757 max_cpu_load = load;
2758 max_nr_running = rq->nr_running;
2759 }
2760 if (min_cpu_load > load)
2761 min_cpu_load = load;
2762 }
2763
2764 sgs->group_load += load;
2765 sgs->sum_nr_running += rq->nr_running;
2766 sgs->sum_weighted_load += weighted_cpuload(i);
2767 if (idle_cpu(i))
2768 sgs->idle_cpus++;
2769 }
2770
2771 /*
2772 * First idle cpu or the first cpu(busiest) in this sched group
2773 * is eligible for doing load balancing at this and above
2774 * domains. In the newly idle case, we will allow all the cpu's
2775 * to do the newly idle load balance.
2776 */
2777 if (idle != CPU_NEWLY_IDLE && local_group) {
2778 if (balance_cpu != this_cpu) {
2779 *balance = 0;
2780 return;
2781 }
2782 update_group_power(sd, this_cpu);
2783 }
2784
2785 /* Adjust by relative CPU power of the group */
2786 sgs->avg_load = (sgs->group_load*SCHED_POWER_SCALE) / group->sgp->power;
2787
2788 /*
2789 * Consider the group unbalanced when the imbalance is larger
2790 * than the average weight of a task.
2791 *
2792 * APZ: with cgroup the avg task weight can vary wildly and
2793 * might not be a suitable number - should we keep a
2794 * normalized nr_running number somewhere that negates
2795 * the hierarchy?
2796 */
2797 if (sgs->sum_nr_running)
2798 avg_load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
2799
2800 if ((max_cpu_load - min_cpu_load) >= avg_load_per_task && max_nr_running > 1)
2801 sgs->group_imb = 1;
2802
2803 sgs->group_capacity = DIV_ROUND_CLOSEST(group->sgp->power,
2804 SCHED_POWER_SCALE);
2805 if (!sgs->group_capacity)
2806 sgs->group_capacity = fix_small_capacity(sd, group);
2807 sgs->group_weight = group->group_weight;
2808
2809 if (sgs->group_capacity > sgs->sum_nr_running)
2810 sgs->group_has_capacity = 1;
2811}
2812
2813/**
2814 * update_sd_pick_busiest - return 1 on busiest group
2815 * @sd: sched_domain whose statistics are to be checked
2816 * @sds: sched_domain statistics
2817 * @sg: sched_group candidate to be checked for being the busiest
2818 * @sgs: sched_group statistics
2819 * @this_cpu: the current cpu
2820 *
2821 * Determine if @sg is a busier group than the previously selected
2822 * busiest group.
2823 */
2824static bool update_sd_pick_busiest(struct sched_domain *sd,
2825 struct sd_lb_stats *sds,
2826 struct sched_group *sg,
2827 struct sg_lb_stats *sgs,
2828 int this_cpu)
2829{
2830 if (sgs->avg_load <= sds->max_load)
2831 return false;
2832
2833 if (sgs->sum_nr_running > sgs->group_capacity)
2834 return true;
2835
2836 if (sgs->group_imb)
2837 return true;
2838
2839 /*
2840 * ASYM_PACKING needs to move all the work to the lowest
2841 * numbered CPUs in the group, therefore mark all groups
2842 * higher than ourself as busy.
2843 */
2844 if ((sd->flags & SD_ASYM_PACKING) && sgs->sum_nr_running &&
2845 this_cpu < group_first_cpu(sg)) {
2846 if (!sds->busiest)
2847 return true;
2848
2849 if (group_first_cpu(sds->busiest) > group_first_cpu(sg))
2850 return true;
2851 }
2852
2853 return false;
2854}
2855
2856/**
2857 * update_sd_lb_stats - Update sched_group's statistics for load balancing.
2858 * @sd: sched_domain whose statistics are to be updated.
2859 * @this_cpu: Cpu for which load balance is currently performed.
2860 * @idle: Idle status of this_cpu
2861 * @cpus: Set of cpus considered for load balancing.
2862 * @balance: Should we balance.
2863 * @sds: variable to hold the statistics for this sched_domain.
2864 */
2865static inline void update_sd_lb_stats(struct sched_domain *sd, int this_cpu,
2866 enum cpu_idle_type idle, const struct cpumask *cpus,
2867 int *balance, struct sd_lb_stats *sds)
2868{
2869 struct sched_domain *child = sd->child;
2870 struct sched_group *sg = sd->groups;
2871 struct sg_lb_stats sgs;
2872 int load_idx, prefer_sibling = 0;
2873
2874 if (child && child->flags & SD_PREFER_SIBLING)
2875 prefer_sibling = 1;
2876
2877 init_sd_power_savings_stats(sd, sds, idle);
2878 load_idx = get_sd_load_idx(sd, idle);
2879
2880 do {
2881 int local_group;
2882
2883 local_group = cpumask_test_cpu(this_cpu, sched_group_cpus(sg));
2884 memset(&sgs, 0, sizeof(sgs));
2885 update_sg_lb_stats(sd, sg, this_cpu, idle, load_idx,
2886 local_group, cpus, balance, &sgs);
2887
2888 if (local_group && !(*balance))
2889 return;
2890
2891 sds->total_load += sgs.group_load;
2892 sds->total_pwr += sg->sgp->power;
2893
2894 /*
2895 * In case the child domain prefers tasks go to siblings
2896 * first, lower the sg capacity to one so that we'll try
2897 * and move all the excess tasks away. We lower the capacity
2898 * of a group only if the local group has the capacity to fit
2899 * these excess tasks, i.e. nr_running < group_capacity. The
2900 * extra check prevents the case where you always pull from the
2901 * heaviest group when it is already under-utilized (possible
2902 * with a large weight task outweighs the tasks on the system).
2903 */
2904 if (prefer_sibling && !local_group && sds->this_has_capacity)
2905 sgs.group_capacity = min(sgs.group_capacity, 1UL);
2906
2907 if (local_group) {
2908 sds->this_load = sgs.avg_load;
2909 sds->this = sg;
2910 sds->this_nr_running = sgs.sum_nr_running;
2911 sds->this_load_per_task = sgs.sum_weighted_load;
2912 sds->this_has_capacity = sgs.group_has_capacity;
2913 sds->this_idle_cpus = sgs.idle_cpus;
2914 } else if (update_sd_pick_busiest(sd, sds, sg, &sgs, this_cpu)) {
2915 sds->max_load = sgs.avg_load;
2916 sds->busiest = sg;
2917 sds->busiest_nr_running = sgs.sum_nr_running;
2918 sds->busiest_idle_cpus = sgs.idle_cpus;
2919 sds->busiest_group_capacity = sgs.group_capacity;
2920 sds->busiest_load_per_task = sgs.sum_weighted_load;
2921 sds->busiest_has_capacity = sgs.group_has_capacity;
2922 sds->busiest_group_weight = sgs.group_weight;
2923 sds->group_imb = sgs.group_imb;
2924 }
2925
2926 update_sd_power_savings_stats(sg, sds, local_group, &sgs);
2927 sg = sg->next;
2928 } while (sg != sd->groups);
2929}
2930
2931int __weak arch_sd_sibling_asym_packing(void)
2932{
2933 return 0*SD_ASYM_PACKING;
2934}
2935
2936/**
2937 * check_asym_packing - Check to see if the group is packed into the
2938 * sched doman.
2939 *
2940 * This is primarily intended to used at the sibling level. Some
2941 * cores like POWER7 prefer to use lower numbered SMT threads. In the
2942 * case of POWER7, it can move to lower SMT modes only when higher
2943 * threads are idle. When in lower SMT modes, the threads will
2944 * perform better since they share less core resources. Hence when we
2945 * have idle threads, we want them to be the higher ones.
2946 *
2947 * This packing function is run on idle threads. It checks to see if
2948 * the busiest CPU in this domain (core in the P7 case) has a higher
2949 * CPU number than the packing function is being run on. Here we are
2950 * assuming lower CPU number will be equivalent to lower a SMT thread
2951 * number.
2952 *
2953 * Returns 1 when packing is required and a task should be moved to
2954 * this CPU. The amount of the imbalance is returned in *imbalance.
2955 *
2956 * @sd: The sched_domain whose packing is to be checked.
2957 * @sds: Statistics of the sched_domain which is to be packed
2958 * @this_cpu: The cpu at whose sched_domain we're performing load-balance.
2959 * @imbalance: returns amount of imbalanced due to packing.
2960 */
2961static int check_asym_packing(struct sched_domain *sd,
2962 struct sd_lb_stats *sds,
2963 int this_cpu, unsigned long *imbalance)
2964{
2965 int busiest_cpu;
2966
2967 if (!(sd->flags & SD_ASYM_PACKING))
2968 return 0;
2969
2970 if (!sds->busiest)
2971 return 0;
2972
2973 busiest_cpu = group_first_cpu(sds->busiest);
2974 if (this_cpu > busiest_cpu)
2975 return 0;
2976
2977 *imbalance = DIV_ROUND_CLOSEST(sds->max_load * sds->busiest->sgp->power,
2978 SCHED_POWER_SCALE);
2979 return 1;
2980}
2981
2982/**
2983 * fix_small_imbalance - Calculate the minor imbalance that exists
2984 * amongst the groups of a sched_domain, during
2985 * load balancing.
2986 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
2987 * @this_cpu: The cpu at whose sched_domain we're performing load-balance.
2988 * @imbalance: Variable to store the imbalance.
2989 */
2990static inline void fix_small_imbalance(struct sd_lb_stats *sds,
2991 int this_cpu, unsigned long *imbalance)
2992{
2993 unsigned long tmp, pwr_now = 0, pwr_move = 0;
2994 unsigned int imbn = 2;
2995 unsigned long scaled_busy_load_per_task;
2996
2997 if (sds->this_nr_running) {
2998 sds->this_load_per_task /= sds->this_nr_running;
2999 if (sds->busiest_load_per_task >
3000 sds->this_load_per_task)
3001 imbn = 1;
3002 } else
3003 sds->this_load_per_task =
3004 cpu_avg_load_per_task(this_cpu);
3005
3006 scaled_busy_load_per_task = sds->busiest_load_per_task
3007 * SCHED_POWER_SCALE;
3008 scaled_busy_load_per_task /= sds->busiest->sgp->power;
3009
3010 if (sds->max_load - sds->this_load + scaled_busy_load_per_task >=
3011 (scaled_busy_load_per_task * imbn)) {
3012 *imbalance = sds->busiest_load_per_task;
3013 return;
3014 }
3015
3016 /*
3017 * OK, we don't have enough imbalance to justify moving tasks,
3018 * however we may be able to increase total CPU power used by
3019 * moving them.
3020 */
3021
3022 pwr_now += sds->busiest->sgp->power *
3023 min(sds->busiest_load_per_task, sds->max_load);
3024 pwr_now += sds->this->sgp->power *
3025 min(sds->this_load_per_task, sds->this_load);
3026 pwr_now /= SCHED_POWER_SCALE;
3027
3028 /* Amount of load we'd subtract */
3029 tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
3030 sds->busiest->sgp->power;
3031 if (sds->max_load > tmp)
3032 pwr_move += sds->busiest->sgp->power *
3033 min(sds->busiest_load_per_task, sds->max_load - tmp);
3034
3035 /* Amount of load we'd add */
3036 if (sds->max_load * sds->busiest->sgp->power <
3037 sds->busiest_load_per_task * SCHED_POWER_SCALE)
3038 tmp = (sds->max_load * sds->busiest->sgp->power) /
3039 sds->this->sgp->power;
3040 else
3041 tmp = (sds->busiest_load_per_task * SCHED_POWER_SCALE) /
3042 sds->this->sgp->power;
3043 pwr_move += sds->this->sgp->power *
3044 min(sds->this_load_per_task, sds->this_load + tmp);
3045 pwr_move /= SCHED_POWER_SCALE;
3046
3047 /* Move if we gain throughput */
3048 if (pwr_move > pwr_now)
3049 *imbalance = sds->busiest_load_per_task;
3050}
3051
3052/**
3053 * calculate_imbalance - Calculate the amount of imbalance present within the
3054 * groups of a given sched_domain during load balance.
3055 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
3056 * @this_cpu: Cpu for which currently load balance is being performed.
3057 * @imbalance: The variable to store the imbalance.
3058 */
3059static inline void calculate_imbalance(struct sd_lb_stats *sds, int this_cpu,
3060 unsigned long *imbalance)
3061{
3062 unsigned long max_pull, load_above_capacity = ~0UL;
3063
3064 sds->busiest_load_per_task /= sds->busiest_nr_running;
3065 if (sds->group_imb) {
3066 sds->busiest_load_per_task =
3067 min(sds->busiest_load_per_task, sds->avg_load);
3068 }
3069
3070 /*
3071 * In the presence of smp nice balancing, certain scenarios can have
3072 * max load less than avg load(as we skip the groups at or below
3073 * its cpu_power, while calculating max_load..)
3074 */
3075 if (sds->max_load < sds->avg_load) {
3076 *imbalance = 0;
3077 return fix_small_imbalance(sds, this_cpu, imbalance);
3078 }
3079
3080 if (!sds->group_imb) {
3081 /*
3082 * Don't want to pull so many tasks that a group would go idle.
3083 */
3084 load_above_capacity = (sds->busiest_nr_running -
3085 sds->busiest_group_capacity);
3086
3087 load_above_capacity *= (SCHED_LOAD_SCALE * SCHED_POWER_SCALE);
3088
3089 load_above_capacity /= sds->busiest->sgp->power;
3090 }
3091
3092 /*
3093 * We're trying to get all the cpus to the average_load, so we don't
3094 * want to push ourselves above the average load, nor do we wish to
3095 * reduce the max loaded cpu below the average load. At the same time,
3096 * we also don't want to reduce the group load below the group capacity
3097 * (so that we can implement power-savings policies etc). Thus we look
3098 * for the minimum possible imbalance.
3099 * Be careful of negative numbers as they'll appear as very large values
3100 * with unsigned longs.
3101 */
3102 max_pull = min(sds->max_load - sds->avg_load, load_above_capacity);
3103
3104 /* How much load to actually move to equalise the imbalance */
3105 *imbalance = min(max_pull * sds->busiest->sgp->power,
3106 (sds->avg_load - sds->this_load) * sds->this->sgp->power)
3107 / SCHED_POWER_SCALE;
3108
3109 /*
3110 * if *imbalance is less than the average load per runnable task
3111 * there is no guarantee that any tasks will be moved so we'll have
3112 * a think about bumping its value to force at least one task to be
3113 * moved
3114 */
3115 if (*imbalance < sds->busiest_load_per_task)
3116 return fix_small_imbalance(sds, this_cpu, imbalance);
3117
3118}
3119
3120/******* find_busiest_group() helpers end here *********************/
3121
3122/**
3123 * find_busiest_group - Returns the busiest group within the sched_domain
3124 * if there is an imbalance. If there isn't an imbalance, and
3125 * the user has opted for power-savings, it returns a group whose
3126 * CPUs can be put to idle by rebalancing those tasks elsewhere, if
3127 * such a group exists.
3128 *
3129 * Also calculates the amount of weighted load which should be moved
3130 * to restore balance.
3131 *
3132 * @sd: The sched_domain whose busiest group is to be returned.
3133 * @this_cpu: The cpu for which load balancing is currently being performed.
3134 * @imbalance: Variable which stores amount of weighted load which should
3135 * be moved to restore balance/put a group to idle.
3136 * @idle: The idle status of this_cpu.
3137 * @cpus: The set of CPUs under consideration for load-balancing.
3138 * @balance: Pointer to a variable indicating if this_cpu
3139 * is the appropriate cpu to perform load balancing at this_level.
3140 *
3141 * Returns: - the busiest group if imbalance exists.
3142 * - If no imbalance and user has opted for power-savings balance,
3143 * return the least loaded group whose CPUs can be
3144 * put to idle by rebalancing its tasks onto our group.
3145 */
3146static struct sched_group *
3147find_busiest_group(struct sched_domain *sd, int this_cpu,
3148 unsigned long *imbalance, enum cpu_idle_type idle,
3149 const struct cpumask *cpus, int *balance)
3150{
3151 struct sd_lb_stats sds;
3152
3153 memset(&sds, 0, sizeof(sds));
3154
3155 /*
3156 * Compute the various statistics relavent for load balancing at
3157 * this level.
3158 */
3159 update_sd_lb_stats(sd, this_cpu, idle, cpus, balance, &sds);
3160
3161 /*
3162 * this_cpu is not the appropriate cpu to perform load balancing at
3163 * this level.
3164 */
3165 if (!(*balance))
3166 goto ret;
3167
3168 if ((idle == CPU_IDLE || idle == CPU_NEWLY_IDLE) &&
3169 check_asym_packing(sd, &sds, this_cpu, imbalance))
3170 return sds.busiest;
3171
3172 /* There is no busy sibling group to pull tasks from */
3173 if (!sds.busiest || sds.busiest_nr_running == 0)
3174 goto out_balanced;
3175
3176 sds.avg_load = (SCHED_POWER_SCALE * sds.total_load) / sds.total_pwr;
3177
3178 /*
3179 * If the busiest group is imbalanced the below checks don't
3180 * work because they assumes all things are equal, which typically
3181 * isn't true due to cpus_allowed constraints and the like.
3182 */
3183 if (sds.group_imb)
3184 goto force_balance;
3185
3186 /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
3187 if (idle == CPU_NEWLY_IDLE && sds.this_has_capacity &&
3188 !sds.busiest_has_capacity)
3189 goto force_balance;
3190
3191 /*
3192 * If the local group is more busy than the selected busiest group
3193 * don't try and pull any tasks.
3194 */
3195 if (sds.this_load >= sds.max_load)
3196 goto out_balanced;
3197
3198 /*
3199 * Don't pull any tasks if this group is already above the domain
3200 * average load.
3201 */
3202 if (sds.this_load >= sds.avg_load)
3203 goto out_balanced;
3204
3205 if (idle == CPU_IDLE) {
3206 /*
3207 * This cpu is idle. If the busiest group load doesn't
3208 * have more tasks than the number of available cpu's and
3209 * there is no imbalance between this and busiest group
3210 * wrt to idle cpu's, it is balanced.
3211 */
3212 if ((sds.this_idle_cpus <= sds.busiest_idle_cpus + 1) &&
3213 sds.busiest_nr_running <= sds.busiest_group_weight)
3214 goto out_balanced;
3215 } else {
3216 /*
3217 * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
3218 * imbalance_pct to be conservative.
3219 */
3220 if (100 * sds.max_load <= sd->imbalance_pct * sds.this_load)
3221 goto out_balanced;
3222 }
3223
3224force_balance:
3225 /* Looks like there is an imbalance. Compute it */
3226 calculate_imbalance(&sds, this_cpu, imbalance);
3227 return sds.busiest;
3228
3229out_balanced:
3230 /*
3231 * There is no obvious imbalance. But check if we can do some balancing
3232 * to save power.
3233 */
3234 if (check_power_save_busiest_group(&sds, this_cpu, imbalance))
3235 return sds.busiest;
3236ret:
3237 *imbalance = 0;
3238 return NULL;
3239}
3240
3241/*
3242 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3243 */
3244static struct rq *
3245find_busiest_queue(struct sched_domain *sd, struct sched_group *group,
3246 enum cpu_idle_type idle, unsigned long imbalance,
3247 const struct cpumask *cpus)
3248{
3249 struct rq *busiest = NULL, *rq;
3250 unsigned long max_load = 0;
3251 int i;
3252
3253 for_each_cpu(i, sched_group_cpus(group)) {
3254 unsigned long power = power_of(i);
3255 unsigned long capacity = DIV_ROUND_CLOSEST(power,
3256 SCHED_POWER_SCALE);
3257 unsigned long wl;
3258
3259 if (!capacity)
3260 capacity = fix_small_capacity(sd, group);
3261
3262 if (!cpumask_test_cpu(i, cpus))
3263 continue;
3264
3265 rq = cpu_rq(i);
3266 wl = weighted_cpuload(i);
3267
3268 /*
3269 * When comparing with imbalance, use weighted_cpuload()
3270 * which is not scaled with the cpu power.
3271 */
3272 if (capacity && rq->nr_running == 1 && wl > imbalance)
3273 continue;
3274
3275 /*
3276 * For the load comparisons with the other cpu's, consider
3277 * the weighted_cpuload() scaled with the cpu power, so that
3278 * the load can be moved away from the cpu that is potentially
3279 * running at a lower capacity.
3280 */
3281 wl = (wl * SCHED_POWER_SCALE) / power;
3282
3283 if (wl > max_load) {
3284 max_load = wl;
3285 busiest = rq;
3286 }
3287 }
3288
3289 return busiest;
3290}
3291
3292/*
3293 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3294 * so long as it is large enough.
3295 */
3296#define MAX_PINNED_INTERVAL 512
3297
3298/* Working cpumask for load_balance and load_balance_newidle. */
3299static DEFINE_PER_CPU(cpumask_var_t, load_balance_tmpmask);
3300
3301static int need_active_balance(struct sched_domain *sd, int idle,
3302 int busiest_cpu, int this_cpu)
3303{
3304 if (idle == CPU_NEWLY_IDLE) {
3305
3306 /*
3307 * ASYM_PACKING needs to force migrate tasks from busy but
3308 * higher numbered CPUs in order to pack all tasks in the
3309 * lowest numbered CPUs.
3310 */
3311 if ((sd->flags & SD_ASYM_PACKING) && busiest_cpu > this_cpu)
3312 return 1;
3313
3314 /*
3315 * The only task running in a non-idle cpu can be moved to this
3316 * cpu in an attempt to completely freeup the other CPU
3317 * package.
3318 *
3319 * The package power saving logic comes from
3320 * find_busiest_group(). If there are no imbalance, then
3321 * f_b_g() will return NULL. However when sched_mc={1,2} then
3322 * f_b_g() will select a group from which a running task may be
3323 * pulled to this cpu in order to make the other package idle.
3324 * If there is no opportunity to make a package idle and if
3325 * there are no imbalance, then f_b_g() will return NULL and no
3326 * action will be taken in load_balance_newidle().
3327 *
3328 * Under normal task pull operation due to imbalance, there
3329 * will be more than one task in the source run queue and
3330 * move_tasks() will succeed. ld_moved will be true and this
3331 * active balance code will not be triggered.
3332 */
3333 if (sched_mc_power_savings < POWERSAVINGS_BALANCE_WAKEUP)
3334 return 0;
3335 }
3336
3337 return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
3338}
3339
3340static int active_load_balance_cpu_stop(void *data);
3341
3342/*
3343 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3344 * tasks if there is an imbalance.
3345 */
3346static int load_balance(int this_cpu, struct rq *this_rq,
3347 struct sched_domain *sd, enum cpu_idle_type idle,
3348 int *balance)
3349{
3350 int ld_moved, all_pinned = 0, active_balance = 0;
3351 struct sched_group *group;
3352 unsigned long imbalance;
3353 struct rq *busiest;
3354 unsigned long flags;
3355 struct cpumask *cpus = __get_cpu_var(load_balance_tmpmask);
3356
3357 cpumask_copy(cpus, cpu_active_mask);
3358
3359 schedstat_inc(sd, lb_count[idle]);
3360
3361redo:
3362 group = find_busiest_group(sd, this_cpu, &imbalance, idle,
3363 cpus, balance);
3364
3365 if (*balance == 0)
3366 goto out_balanced;
3367
3368 if (!group) {
3369 schedstat_inc(sd, lb_nobusyg[idle]);
3370 goto out_balanced;
3371 }
3372
3373 busiest = find_busiest_queue(sd, group, idle, imbalance, cpus);
3374 if (!busiest) {
3375 schedstat_inc(sd, lb_nobusyq[idle]);
3376 goto out_balanced;
3377 }
3378
3379 BUG_ON(busiest == this_rq);
3380
3381 schedstat_add(sd, lb_imbalance[idle], imbalance);
3382
3383 ld_moved = 0;
3384 if (busiest->nr_running > 1) {
3385 /*
3386 * Attempt to move tasks. If find_busiest_group has found
3387 * an imbalance but busiest->nr_running <= 1, the group is
3388 * still unbalanced. ld_moved simply stays zero, so it is
3389 * correctly treated as an imbalance.
3390 */
3391 all_pinned = 1;
3392 local_irq_save(flags);
3393 double_rq_lock(this_rq, busiest);
3394 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3395 imbalance, sd, idle, &all_pinned);
3396 double_rq_unlock(this_rq, busiest);
3397 local_irq_restore(flags);
3398
3399 /*
3400 * some other cpu did the load balance for us.
3401 */
3402 if (ld_moved && this_cpu != smp_processor_id())
3403 resched_cpu(this_cpu);
3404
3405 /* All tasks on this runqueue were pinned by CPU affinity */
3406 if (unlikely(all_pinned)) {
3407 cpumask_clear_cpu(cpu_of(busiest), cpus);
3408 if (!cpumask_empty(cpus))
3409 goto redo;
3410 goto out_balanced;
3411 }
3412 }
3413
3414 if (!ld_moved) {
3415 schedstat_inc(sd, lb_failed[idle]);
3416 /*
3417 * Increment the failure counter only on periodic balance.
3418 * We do not want newidle balance, which can be very
3419 * frequent, pollute the failure counter causing
3420 * excessive cache_hot migrations and active balances.
3421 */
3422 if (idle != CPU_NEWLY_IDLE)
3423 sd->nr_balance_failed++;
3424
3425 if (need_active_balance(sd, idle, cpu_of(busiest), this_cpu)) {
3426 raw_spin_lock_irqsave(&busiest->lock, flags);
3427
3428 /* don't kick the active_load_balance_cpu_stop,
3429 * if the curr task on busiest cpu can't be
3430 * moved to this_cpu
3431 */
3432 if (!cpumask_test_cpu(this_cpu,
3433 &busiest->curr->cpus_allowed)) {
3434 raw_spin_unlock_irqrestore(&busiest->lock,
3435 flags);
3436 all_pinned = 1;
3437 goto out_one_pinned;
3438 }
3439
3440 /*
3441 * ->active_balance synchronizes accesses to
3442 * ->active_balance_work. Once set, it's cleared
3443 * only after active load balance is finished.
3444 */
3445 if (!busiest->active_balance) {
3446 busiest->active_balance = 1;
3447 busiest->push_cpu = this_cpu;
3448 active_balance = 1;
3449 }
3450 raw_spin_unlock_irqrestore(&busiest->lock, flags);
3451
3452 if (active_balance)
3453 stop_one_cpu_nowait(cpu_of(busiest),
3454 active_load_balance_cpu_stop, busiest,
3455 &busiest->active_balance_work);
3456
3457 /*
3458 * We've kicked active balancing, reset the failure
3459 * counter.
3460 */
3461 sd->nr_balance_failed = sd->cache_nice_tries+1;
3462 }
3463 } else
3464 sd->nr_balance_failed = 0;
3465
3466 if (likely(!active_balance)) {
3467 /* We were unbalanced, so reset the balancing interval */
3468 sd->balance_interval = sd->min_interval;
3469 } else {
3470 /*
3471 * If we've begun active balancing, start to back off. This
3472 * case may not be covered by the all_pinned logic if there
3473 * is only 1 task on the busy runqueue (because we don't call
3474 * move_tasks).
3475 */
3476 if (sd->balance_interval < sd->max_interval)
3477 sd->balance_interval *= 2;
3478 }
3479
3480 goto out;
3481
3482out_balanced:
3483 schedstat_inc(sd, lb_balanced[idle]);
3484
3485 sd->nr_balance_failed = 0;
3486
3487out_one_pinned:
3488 /* tune up the balancing interval */
3489 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3490 (sd->balance_interval < sd->max_interval))
3491 sd->balance_interval *= 2;
3492
3493 ld_moved = 0;
3494out:
3495 return ld_moved;
3496}
3497
3498/*
3499 * idle_balance is called by schedule() if this_cpu is about to become
3500 * idle. Attempts to pull tasks from other CPUs.
3501 */
3502static void idle_balance(int this_cpu, struct rq *this_rq)
3503{
3504 struct sched_domain *sd;
3505 int pulled_task = 0;
3506 unsigned long next_balance = jiffies + HZ;
3507
3508 this_rq->idle_stamp = this_rq->clock;
3509
3510 if (this_rq->avg_idle < sysctl_sched_migration_cost)
3511 return;
3512
3513 /*
3514 * Drop the rq->lock, but keep IRQ/preempt disabled.
3515 */
3516 raw_spin_unlock(&this_rq->lock);
3517
3518 update_shares(this_cpu);
3519 rcu_read_lock();
3520 for_each_domain(this_cpu, sd) {
3521 unsigned long interval;
3522 int balance = 1;
3523
3524 if (!(sd->flags & SD_LOAD_BALANCE))
3525 continue;
3526
3527 if (sd->flags & SD_BALANCE_NEWIDLE) {
3528 /* If we've pulled tasks over stop searching: */
3529 pulled_task = load_balance(this_cpu, this_rq,
3530 sd, CPU_NEWLY_IDLE, &balance);
3531 }
3532
3533 interval = msecs_to_jiffies(sd->balance_interval);
3534 if (time_after(next_balance, sd->last_balance + interval))
3535 next_balance = sd->last_balance + interval;
3536 if (pulled_task) {
3537 this_rq->idle_stamp = 0;
3538 break;
3539 }
3540 }
3541 rcu_read_unlock();
3542
3543 raw_spin_lock(&this_rq->lock);
3544
3545 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3546 /*
3547 * We are going idle. next_balance may be set based on
3548 * a busy processor. So reset next_balance.
3549 */
3550 this_rq->next_balance = next_balance;
3551 }
3552}
3553
3554/*
3555 * active_load_balance_cpu_stop is run by cpu stopper. It pushes
3556 * running tasks off the busiest CPU onto idle CPUs. It requires at
3557 * least 1 task to be running on each physical CPU where possible, and
3558 * avoids physical / logical imbalances.
3559 */
3560static int active_load_balance_cpu_stop(void *data)
3561{
3562 struct rq *busiest_rq = data;
3563 int busiest_cpu = cpu_of(busiest_rq);
3564 int target_cpu = busiest_rq->push_cpu;
3565 struct rq *target_rq = cpu_rq(target_cpu);
3566 struct sched_domain *sd;
3567
3568 raw_spin_lock_irq(&busiest_rq->lock);
3569
3570 /* make sure the requested cpu hasn't gone down in the meantime */
3571 if (unlikely(busiest_cpu != smp_processor_id() ||
3572 !busiest_rq->active_balance))
3573 goto out_unlock;
3574
3575 /* Is there any task to move? */
3576 if (busiest_rq->nr_running <= 1)
3577 goto out_unlock;
3578
3579 /*
3580 * This condition is "impossible", if it occurs
3581 * we need to fix it. Originally reported by
3582 * Bjorn Helgaas on a 128-cpu setup.
3583 */
3584 BUG_ON(busiest_rq == target_rq);
3585
3586 /* move a task from busiest_rq to target_rq */
3587 double_lock_balance(busiest_rq, target_rq);
3588
3589 /* Search for an sd spanning us and the target CPU. */
3590 rcu_read_lock();
3591 for_each_domain(target_cpu, sd) {
3592 if ((sd->flags & SD_LOAD_BALANCE) &&
3593 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
3594 break;
3595 }
3596
3597 if (likely(sd)) {
3598 schedstat_inc(sd, alb_count);
3599
3600 if (move_one_task(target_rq, target_cpu, busiest_rq,
3601 sd, CPU_IDLE))
3602 schedstat_inc(sd, alb_pushed);
3603 else
3604 schedstat_inc(sd, alb_failed);
3605 }
3606 rcu_read_unlock();
3607 double_unlock_balance(busiest_rq, target_rq);
3608out_unlock:
3609 busiest_rq->active_balance = 0;
3610 raw_spin_unlock_irq(&busiest_rq->lock);
3611 return 0;
3612}
3613
3614#ifdef CONFIG_NO_HZ
3615
3616static DEFINE_PER_CPU(struct call_single_data, remote_sched_softirq_cb);
3617
3618static void trigger_sched_softirq(void *data)
3619{
3620 raise_softirq_irqoff(SCHED_SOFTIRQ);
3621}
3622
3623static inline void init_sched_softirq_csd(struct call_single_data *csd)
3624{
3625 csd->func = trigger_sched_softirq;
3626 csd->info = NULL;
3627 csd->flags = 0;
3628 csd->priv = 0;
3629}
3630
3631/*
3632 * idle load balancing details
3633 * - One of the idle CPUs nominates itself as idle load_balancer, while
3634 * entering idle.
3635 * - This idle load balancer CPU will also go into tickless mode when
3636 * it is idle, just like all other idle CPUs
3637 * - When one of the busy CPUs notice that there may be an idle rebalancing
3638 * needed, they will kick the idle load balancer, which then does idle
3639 * load balancing for all the idle CPUs.
3640 */
3641static struct {
3642 atomic_t load_balancer;
3643 atomic_t first_pick_cpu;
3644 atomic_t second_pick_cpu;
3645 cpumask_var_t idle_cpus_mask;
3646 cpumask_var_t grp_idle_mask;
3647 unsigned long next_balance; /* in jiffy units */
3648} nohz ____cacheline_aligned;
3649
3650int get_nohz_load_balancer(void)
3651{
3652 return atomic_read(&nohz.load_balancer);
3653}
3654
3655#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3656/**
3657 * lowest_flag_domain - Return lowest sched_domain containing flag.
3658 * @cpu: The cpu whose lowest level of sched domain is to
3659 * be returned.
3660 * @flag: The flag to check for the lowest sched_domain
3661 * for the given cpu.
3662 *
3663 * Returns the lowest sched_domain of a cpu which contains the given flag.
3664 */
3665static inline struct sched_domain *lowest_flag_domain(int cpu, int flag)
3666{
3667 struct sched_domain *sd;
3668
3669 for_each_domain(cpu, sd)
3670 if (sd && (sd->flags & flag))
3671 break;
3672
3673 return sd;
3674}
3675
3676/**
3677 * for_each_flag_domain - Iterates over sched_domains containing the flag.
3678 * @cpu: The cpu whose domains we're iterating over.
3679 * @sd: variable holding the value of the power_savings_sd
3680 * for cpu.
3681 * @flag: The flag to filter the sched_domains to be iterated.
3682 *
3683 * Iterates over all the scheduler domains for a given cpu that has the 'flag'
3684 * set, starting from the lowest sched_domain to the highest.
3685 */
3686#define for_each_flag_domain(cpu, sd, flag) \
3687 for (sd = lowest_flag_domain(cpu, flag); \
3688 (sd && (sd->flags & flag)); sd = sd->parent)
3689
3690/**
3691 * is_semi_idle_group - Checks if the given sched_group is semi-idle.
3692 * @ilb_group: group to be checked for semi-idleness
3693 *
3694 * Returns: 1 if the group is semi-idle. 0 otherwise.
3695 *
3696 * We define a sched_group to be semi idle if it has atleast one idle-CPU
3697 * and atleast one non-idle CPU. This helper function checks if the given
3698 * sched_group is semi-idle or not.
3699 */
3700static inline int is_semi_idle_group(struct sched_group *ilb_group)
3701{
3702 cpumask_and(nohz.grp_idle_mask, nohz.idle_cpus_mask,
3703 sched_group_cpus(ilb_group));
3704
3705 /*
3706 * A sched_group is semi-idle when it has atleast one busy cpu
3707 * and atleast one idle cpu.
3708 */
3709 if (cpumask_empty(nohz.grp_idle_mask))
3710 return 0;
3711
3712 if (cpumask_equal(nohz.grp_idle_mask, sched_group_cpus(ilb_group)))
3713 return 0;
3714
3715 return 1;
3716}
3717/**
3718 * find_new_ilb - Finds the optimum idle load balancer for nomination.
3719 * @cpu: The cpu which is nominating a new idle_load_balancer.
3720 *
3721 * Returns: Returns the id of the idle load balancer if it exists,
3722 * Else, returns >= nr_cpu_ids.
3723 *
3724 * This algorithm picks the idle load balancer such that it belongs to a
3725 * semi-idle powersavings sched_domain. The idea is to try and avoid
3726 * completely idle packages/cores just for the purpose of idle load balancing
3727 * when there are other idle cpu's which are better suited for that job.
3728 */
3729static int find_new_ilb(int cpu)
3730{
3731 struct sched_domain *sd;
3732 struct sched_group *ilb_group;
3733 int ilb = nr_cpu_ids;
3734
3735 /*
3736 * Have idle load balancer selection from semi-idle packages only
3737 * when power-aware load balancing is enabled
3738 */
3739 if (!(sched_smt_power_savings || sched_mc_power_savings))
3740 goto out_done;
3741
3742 /*
3743 * Optimize for the case when we have no idle CPUs or only one
3744 * idle CPU. Don't walk the sched_domain hierarchy in such cases
3745 */
3746 if (cpumask_weight(nohz.idle_cpus_mask) < 2)
3747 goto out_done;
3748
3749 rcu_read_lock();
3750 for_each_flag_domain(cpu, sd, SD_POWERSAVINGS_BALANCE) {
3751 ilb_group = sd->groups;
3752
3753 do {
3754 if (is_semi_idle_group(ilb_group)) {
3755 ilb = cpumask_first(nohz.grp_idle_mask);
3756 goto unlock;
3757 }
3758
3759 ilb_group = ilb_group->next;
3760
3761 } while (ilb_group != sd->groups);
3762 }
3763unlock:
3764 rcu_read_unlock();
3765
3766out_done:
3767 return ilb;
3768}
3769#else /* (CONFIG_SCHED_MC || CONFIG_SCHED_SMT) */
3770static inline int find_new_ilb(int call_cpu)
3771{
3772 return nr_cpu_ids;
3773}
3774#endif
3775
3776/*
3777 * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
3778 * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
3779 * CPU (if there is one).
3780 */
3781static void nohz_balancer_kick(int cpu)
3782{
3783 int ilb_cpu;
3784
3785 nohz.next_balance++;
3786
3787 ilb_cpu = get_nohz_load_balancer();
3788
3789 if (ilb_cpu >= nr_cpu_ids) {
3790 ilb_cpu = cpumask_first(nohz.idle_cpus_mask);
3791 if (ilb_cpu >= nr_cpu_ids)
3792 return;
3793 }
3794
3795 if (!cpu_rq(ilb_cpu)->nohz_balance_kick) {
3796 struct call_single_data *cp;
3797
3798 cpu_rq(ilb_cpu)->nohz_balance_kick = 1;
3799 cp = &per_cpu(remote_sched_softirq_cb, cpu);
3800 __smp_call_function_single(ilb_cpu, cp, 0);
3801 }
3802 return;
3803}
3804
3805/*
3806 * This routine will try to nominate the ilb (idle load balancing)
3807 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3808 * load balancing on behalf of all those cpus.
3809 *
3810 * When the ilb owner becomes busy, we will not have new ilb owner until some
3811 * idle CPU wakes up and goes back to idle or some busy CPU tries to kick
3812 * idle load balancing by kicking one of the idle CPUs.
3813 *
3814 * Ticks are stopped for the ilb owner as well, with busy CPU kicking this
3815 * ilb owner CPU in future (when there is a need for idle load balancing on
3816 * behalf of all idle CPUs).
3817 */
3818void select_nohz_load_balancer(int stop_tick)
3819{
3820 int cpu = smp_processor_id();
3821
3822 if (stop_tick) {
3823 if (!cpu_active(cpu)) {
3824 if (atomic_read(&nohz.load_balancer) != cpu)
3825 return;
3826
3827 /*
3828 * If we are going offline and still the leader,
3829 * give up!
3830 */
3831 if (atomic_cmpxchg(&nohz.load_balancer, cpu,
3832 nr_cpu_ids) != cpu)
3833 BUG();
3834
3835 return;
3836 }
3837
3838 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
3839
3840 if (atomic_read(&nohz.first_pick_cpu) == cpu)
3841 atomic_cmpxchg(&nohz.first_pick_cpu, cpu, nr_cpu_ids);
3842 if (atomic_read(&nohz.second_pick_cpu) == cpu)
3843 atomic_cmpxchg(&nohz.second_pick_cpu, cpu, nr_cpu_ids);
3844
3845 if (atomic_read(&nohz.load_balancer) >= nr_cpu_ids) {
3846 int new_ilb;
3847
3848 /* make me the ilb owner */
3849 if (atomic_cmpxchg(&nohz.load_balancer, nr_cpu_ids,
3850 cpu) != nr_cpu_ids)
3851 return;
3852
3853 /*
3854 * Check to see if there is a more power-efficient
3855 * ilb.
3856 */
3857 new_ilb = find_new_ilb(cpu);
3858 if (new_ilb < nr_cpu_ids && new_ilb != cpu) {
3859 atomic_set(&nohz.load_balancer, nr_cpu_ids);
3860 resched_cpu(new_ilb);
3861 return;
3862 }
3863 return;
3864 }
3865 } else {
3866 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask))
3867 return;
3868
3869 cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
3870
3871 if (atomic_read(&nohz.load_balancer) == cpu)
3872 if (atomic_cmpxchg(&nohz.load_balancer, cpu,
3873 nr_cpu_ids) != cpu)
3874 BUG();
3875 }
3876 return;
3877}
3878#endif
3879
3880static DEFINE_SPINLOCK(balancing);
3881
3882static unsigned long __read_mostly max_load_balance_interval = HZ/10;
3883
3884/*
3885 * Scale the max load_balance interval with the number of CPUs in the system.
3886 * This trades load-balance latency on larger machines for less cross talk.
3887 */
3888static void update_max_interval(void)
3889{
3890 max_load_balance_interval = HZ*num_online_cpus()/10;
3891}
3892
3893/*
3894 * It checks each scheduling domain to see if it is due to be balanced,
3895 * and initiates a balancing operation if so.
3896 *
3897 * Balancing parameters are set up in arch_init_sched_domains.
3898 */
3899static void rebalance_domains(int cpu, enum cpu_idle_type idle)
3900{
3901 int balance = 1;
3902 struct rq *rq = cpu_rq(cpu);
3903 unsigned long interval;
3904 struct sched_domain *sd;
3905 /* Earliest time when we have to do rebalance again */
3906 unsigned long next_balance = jiffies + 60*HZ;
3907 int update_next_balance = 0;
3908 int need_serialize;
3909
3910 update_shares(cpu);
3911
3912 rcu_read_lock();
3913 for_each_domain(cpu, sd) {
3914 if (!(sd->flags & SD_LOAD_BALANCE))
3915 continue;
3916
3917 interval = sd->balance_interval;
3918 if (idle != CPU_IDLE)
3919 interval *= sd->busy_factor;
3920
3921 /* scale ms to jiffies */
3922 interval = msecs_to_jiffies(interval);
3923 interval = clamp(interval, 1UL, max_load_balance_interval);
3924
3925 need_serialize = sd->flags & SD_SERIALIZE;
3926
3927 if (need_serialize) {
3928 if (!spin_trylock(&balancing))
3929 goto out;
3930 }
3931
3932 if (time_after_eq(jiffies, sd->last_balance + interval)) {
3933 if (load_balance(cpu, rq, sd, idle, &balance)) {
3934 /*
3935 * We've pulled tasks over so either we're no
3936 * longer idle.
3937 */
3938 idle = CPU_NOT_IDLE;
3939 }
3940 sd->last_balance = jiffies;
3941 }
3942 if (need_serialize)
3943 spin_unlock(&balancing);
3944out:
3945 if (time_after(next_balance, sd->last_balance + interval)) {
3946 next_balance = sd->last_balance + interval;
3947 update_next_balance = 1;
3948 }
3949
3950 /*
3951 * Stop the load balance at this level. There is another
3952 * CPU in our sched group which is doing load balancing more
3953 * actively.
3954 */
3955 if (!balance)
3956 break;
3957 }
3958 rcu_read_unlock();
3959
3960 /*
3961 * next_balance will be updated only when there is a need.
3962 * When the cpu is attached to null domain for ex, it will not be
3963 * updated.
3964 */
3965 if (likely(update_next_balance))
3966 rq->next_balance = next_balance;
3967}
3968
3969#ifdef CONFIG_NO_HZ
3970/*
3971 * In CONFIG_NO_HZ case, the idle balance kickee will do the
3972 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3973 */
3974static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle)
3975{
3976 struct rq *this_rq = cpu_rq(this_cpu);
3977 struct rq *rq;
3978 int balance_cpu;
3979
3980 if (idle != CPU_IDLE || !this_rq->nohz_balance_kick)
3981 return;
3982
3983 for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
3984 if (balance_cpu == this_cpu)
3985 continue;
3986
3987 /*
3988 * If this cpu gets work to do, stop the load balancing
3989 * work being done for other cpus. Next load
3990 * balancing owner will pick it up.
3991 */
3992 if (need_resched()) {
3993 this_rq->nohz_balance_kick = 0;
3994 break;
3995 }
3996
3997 raw_spin_lock_irq(&this_rq->lock);
3998 update_rq_clock(this_rq);
3999 update_cpu_load(this_rq);
4000 raw_spin_unlock_irq(&this_rq->lock);
4001
4002 rebalance_domains(balance_cpu, CPU_IDLE);
4003
4004 rq = cpu_rq(balance_cpu);
4005 if (time_after(this_rq->next_balance, rq->next_balance))
4006 this_rq->next_balance = rq->next_balance;
4007 }
4008 nohz.next_balance = this_rq->next_balance;
4009 this_rq->nohz_balance_kick = 0;
4010}
4011
4012/*
4013 * Current heuristic for kicking the idle load balancer
4014 * - first_pick_cpu is the one of the busy CPUs. It will kick
4015 * idle load balancer when it has more than one process active. This
4016 * eliminates the need for idle load balancing altogether when we have
4017 * only one running process in the system (common case).
4018 * - If there are more than one busy CPU, idle load balancer may have
4019 * to run for active_load_balance to happen (i.e., two busy CPUs are
4020 * SMT or core siblings and can run better if they move to different
4021 * physical CPUs). So, second_pick_cpu is the second of the busy CPUs
4022 * which will kick idle load balancer as soon as it has any load.
4023 */
4024static inline int nohz_kick_needed(struct rq *rq, int cpu)
4025{
4026 unsigned long now = jiffies;
4027 int ret;
4028 int first_pick_cpu, second_pick_cpu;
4029
4030 if (time_before(now, nohz.next_balance))
4031 return 0;
4032
4033 if (rq->idle_at_tick)
4034 return 0;
4035
4036 first_pick_cpu = atomic_read(&nohz.first_pick_cpu);
4037 second_pick_cpu = atomic_read(&nohz.second_pick_cpu);
4038
4039 if (first_pick_cpu < nr_cpu_ids && first_pick_cpu != cpu &&
4040 second_pick_cpu < nr_cpu_ids && second_pick_cpu != cpu)
4041 return 0;
4042
4043 ret = atomic_cmpxchg(&nohz.first_pick_cpu, nr_cpu_ids, cpu);
4044 if (ret == nr_cpu_ids || ret == cpu) {
4045 atomic_cmpxchg(&nohz.second_pick_cpu, cpu, nr_cpu_ids);
4046 if (rq->nr_running > 1)
4047 return 1;
4048 } else {
4049 ret = atomic_cmpxchg(&nohz.second_pick_cpu, nr_cpu_ids, cpu);
4050 if (ret == nr_cpu_ids || ret == cpu) {
4051 if (rq->nr_running)
4052 return 1;
4053 }
4054 }
4055 return 0;
4056}
4057#else
4058static void nohz_idle_balance(int this_cpu, enum cpu_idle_type idle) { }
4059#endif
4060
4061/*
4062 * run_rebalance_domains is triggered when needed from the scheduler tick.
4063 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
4064 */
4065static void run_rebalance_domains(struct softirq_action *h)
4066{
4067 int this_cpu = smp_processor_id();
4068 struct rq *this_rq = cpu_rq(this_cpu);
4069 enum cpu_idle_type idle = this_rq->idle_at_tick ?
4070 CPU_IDLE : CPU_NOT_IDLE;
4071
4072 rebalance_domains(this_cpu, idle);
4073
4074 /*
4075 * If this cpu has a pending nohz_balance_kick, then do the
4076 * balancing on behalf of the other idle cpus whose ticks are
4077 * stopped.
4078 */
4079 nohz_idle_balance(this_cpu, idle);
4080}
4081
4082static inline int on_null_domain(int cpu)
4083{
4084 return !rcu_dereference_sched(cpu_rq(cpu)->sd);
4085}
4086
4087/*
4088 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4089 */
4090static inline void trigger_load_balance(struct rq *rq, int cpu)
4091{
4092 /* Don't need to rebalance while attached to NULL domain */
4093 if (time_after_eq(jiffies, rq->next_balance) &&
4094 likely(!on_null_domain(cpu)))
4095 raise_softirq(SCHED_SOFTIRQ);
4096#ifdef CONFIG_NO_HZ
4097 else if (nohz_kick_needed(rq, cpu) && likely(!on_null_domain(cpu)))
4098 nohz_balancer_kick(cpu);
4099#endif
4100}
4101
4102static void rq_online_fair(struct rq *rq)
4103{
4104 update_sysctl();
4105}
4106
4107static void rq_offline_fair(struct rq *rq)
4108{
4109 update_sysctl();
4110}
4111
4112#else /* CONFIG_SMP */
4113
4114/*
4115 * on UP we do not need to balance between CPUs:
4116 */
4117static inline void idle_balance(int cpu, struct rq *rq)
4118{
4119}
4120
4121#endif /* CONFIG_SMP */
4122
4123/*
4124 * scheduler tick hitting a task of our scheduling class:
4125 */
4126static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
4127{
4128 struct cfs_rq *cfs_rq;
4129 struct sched_entity *se = &curr->se;
4130
4131 for_each_sched_entity(se) {
4132 cfs_rq = cfs_rq_of(se);
4133 entity_tick(cfs_rq, se, queued);
4134 }
4135}
4136
4137/*
4138 * called on fork with the child task as argument from the parent's context
4139 * - child not yet on the tasklist
4140 * - preemption disabled
4141 */
4142static void task_fork_fair(struct task_struct *p)
4143{
4144 struct cfs_rq *cfs_rq = task_cfs_rq(current);
4145 struct sched_entity *se = &p->se, *curr = cfs_rq->curr;
4146 int this_cpu = smp_processor_id();
4147 struct rq *rq = this_rq();
4148 unsigned long flags;
4149
4150 raw_spin_lock_irqsave(&rq->lock, flags);
4151
4152 update_rq_clock(rq);
4153
4154 if (unlikely(task_cpu(p) != this_cpu)) {
4155 rcu_read_lock();
4156 __set_task_cpu(p, this_cpu);
4157 rcu_read_unlock();
4158 }
4159
4160 update_curr(cfs_rq);
4161
4162 if (curr)
4163 se->vruntime = curr->vruntime;
4164 place_entity(cfs_rq, se, 1);
4165
4166 if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
4167 /*
4168 * Upon rescheduling, sched_class::put_prev_task() will place
4169 * 'current' within the tree based on its new key value.
4170 */
4171 swap(curr->vruntime, se->vruntime);
4172 resched_task(rq->curr);
4173 }
4174
4175 se->vruntime -= cfs_rq->min_vruntime;
4176
4177 raw_spin_unlock_irqrestore(&rq->lock, flags);
4178}
4179
4180/*
4181 * Priority of the task has changed. Check to see if we preempt
4182 * the current task.
4183 */
4184static void
4185prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
4186{
4187 if (!p->se.on_rq)
4188 return;
4189
4190 /*
4191 * Reschedule if we are currently running on this runqueue and
4192 * our priority decreased, or if we are not currently running on
4193 * this runqueue and our priority is higher than the current's
4194 */
4195 if (rq->curr == p) {
4196 if (p->prio > oldprio)
4197 resched_task(rq->curr);
4198 } else
4199 check_preempt_curr(rq, p, 0);
4200}
4201
4202static void switched_from_fair(struct rq *rq, struct task_struct *p)
4203{
4204 struct sched_entity *se = &p->se;
4205 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4206
4207 /*
4208 * Ensure the task's vruntime is normalized, so that when its
4209 * switched back to the fair class the enqueue_entity(.flags=0) will
4210 * do the right thing.
4211 *
4212 * If it was on_rq, then the dequeue_entity(.flags=0) will already
4213 * have normalized the vruntime, if it was !on_rq, then only when
4214 * the task is sleeping will it still have non-normalized vruntime.
4215 */
4216 if (!se->on_rq && p->state != TASK_RUNNING) {
4217 /*
4218 * Fix up our vruntime so that the current sleep doesn't
4219 * cause 'unlimited' sleep bonus.
4220 */
4221 place_entity(cfs_rq, se, 0);
4222 se->vruntime -= cfs_rq->min_vruntime;
4223 }
4224}
4225
4226/*
4227 * We switched to the sched_fair class.
4228 */
4229static void switched_to_fair(struct rq *rq, struct task_struct *p)
4230{
4231 if (!p->se.on_rq)
4232 return;
4233
4234 /*
4235 * We were most likely switched from sched_rt, so
4236 * kick off the schedule if running, otherwise just see
4237 * if we can still preempt the current task.
4238 */
4239 if (rq->curr == p)
4240 resched_task(rq->curr);
4241 else
4242 check_preempt_curr(rq, p, 0);
4243}
4244
4245/* Account for a task changing its policy or group.
4246 *
4247 * This routine is mostly called to set cfs_rq->curr field when a task
4248 * migrates between groups/classes.
4249 */
4250static void set_curr_task_fair(struct rq *rq)
4251{
4252 struct sched_entity *se = &rq->curr->se;
4253
4254 for_each_sched_entity(se)
4255 set_next_entity(cfs_rq_of(se), se);
4256}
4257
4258#ifdef CONFIG_FAIR_GROUP_SCHED
4259static void task_move_group_fair(struct task_struct *p, int on_rq)
4260{
4261 /*
4262 * If the task was not on the rq at the time of this cgroup movement
4263 * it must have been asleep, sleeping tasks keep their ->vruntime
4264 * absolute on their old rq until wakeup (needed for the fair sleeper
4265 * bonus in place_entity()).
4266 *
4267 * If it was on the rq, we've just 'preempted' it, which does convert
4268 * ->vruntime to a relative base.
4269 *
4270 * Make sure both cases convert their relative position when migrating
4271 * to another cgroup's rq. This does somewhat interfere with the
4272 * fair sleeper stuff for the first placement, but who cares.
4273 */
4274 if (!on_rq)
4275 p->se.vruntime -= cfs_rq_of(&p->se)->min_vruntime;
4276 set_task_rq(p, task_cpu(p));
4277 if (!on_rq)
4278 p->se.vruntime += cfs_rq_of(&p->se)->min_vruntime;
4279}
4280#endif
4281
4282static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
4283{
4284 struct sched_entity *se = &task->se;
4285 unsigned int rr_interval = 0;
4286
4287 /*
4288 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
4289 * idle runqueue:
4290 */
4291 if (rq->cfs.load.weight)
4292 rr_interval = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
4293
4294 return rr_interval;
4295}
4296
4297/*
4298 * All the scheduling class methods:
4299 */
4300static const struct sched_class fair_sched_class = {
4301 .next = &idle_sched_class,
4302 .enqueue_task = enqueue_task_fair,
4303 .dequeue_task = dequeue_task_fair,
4304 .yield_task = yield_task_fair,
4305 .yield_to_task = yield_to_task_fair,
4306
4307 .check_preempt_curr = check_preempt_wakeup,
4308
4309 .pick_next_task = pick_next_task_fair,
4310 .put_prev_task = put_prev_task_fair,
4311
4312#ifdef CONFIG_SMP
4313 .select_task_rq = select_task_rq_fair,
4314
4315 .rq_online = rq_online_fair,
4316 .rq_offline = rq_offline_fair,
4317
4318 .task_waking = task_waking_fair,
4319#endif
4320
4321 .set_curr_task = set_curr_task_fair,
4322 .task_tick = task_tick_fair,
4323 .task_fork = task_fork_fair,
4324
4325 .prio_changed = prio_changed_fair,
4326 .switched_from = switched_from_fair,
4327 .switched_to = switched_to_fair,
4328
4329 .get_rr_interval = get_rr_interval_fair,
4330
4331#ifdef CONFIG_FAIR_GROUP_SCHED
4332 .task_move_group = task_move_group_fair,
4333#endif
4334};
4335
4336#ifdef CONFIG_SCHED_DEBUG
4337static void print_cfs_stats(struct seq_file *m, int cpu)
4338{
4339 struct cfs_rq *cfs_rq;
4340
4341 rcu_read_lock();
4342 for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
4343 print_cfs_rq(m, cpu, cfs_rq);
4344 rcu_read_unlock();
4345}
4346#endif
diff --git a/kernel/sched_features.h b/kernel/sched_features.h
new file mode 100644
index 00000000000..2e74677cb04
--- /dev/null
+++ b/kernel/sched_features.h
@@ -0,0 +1,74 @@
1/*
2 * Only give sleepers 50% of their service deficit. This allows
3 * them to run sooner, but does not allow tons of sleepers to
4 * rip the spread apart.
5 */
6SCHED_FEAT(GENTLE_FAIR_SLEEPERS, 1)
7
8/*
9 * Place new tasks ahead so that they do not starve already running
10 * tasks
11 */
12SCHED_FEAT(START_DEBIT, 1)
13
14/*
15 * Should wakeups try to preempt running tasks.
16 */
17SCHED_FEAT(WAKEUP_PREEMPT, 1)
18
19/*
20 * Based on load and program behaviour, see if it makes sense to place
21 * a newly woken task on the same cpu as the task that woke it --
22 * improve cache locality. Typically used with SYNC wakeups as
23 * generated by pipes and the like, see also SYNC_WAKEUPS.
24 */
25SCHED_FEAT(AFFINE_WAKEUPS, 1)
26
27/*
28 * Prefer to schedule the task we woke last (assuming it failed
29 * wakeup-preemption), since its likely going to consume data we
30 * touched, increases cache locality.
31 */
32SCHED_FEAT(NEXT_BUDDY, 0)
33
34/*
35 * Prefer to schedule the task that ran last (when we did
36 * wake-preempt) as that likely will touch the same data, increases
37 * cache locality.
38 */
39SCHED_FEAT(LAST_BUDDY, 1)
40
41/*
42 * Consider buddies to be cache hot, decreases the likelyness of a
43 * cache buddy being migrated away, increases cache locality.
44 */
45SCHED_FEAT(CACHE_HOT_BUDDY, 1)
46
47/*
48 * Use arch dependent cpu power functions
49 */
50SCHED_FEAT(ARCH_POWER, 0)
51
52SCHED_FEAT(HRTICK, 0)
53SCHED_FEAT(DOUBLE_TICK, 0)
54SCHED_FEAT(LB_BIAS, 1)
55
56/*
57 * Spin-wait on mutex acquisition when the mutex owner is running on
58 * another cpu -- assumes that when the owner is running, it will soon
59 * release the lock. Decreases scheduling overhead.
60 */
61SCHED_FEAT(OWNER_SPIN, 1)
62
63/*
64 * Decrement CPU power based on time not spent running tasks
65 */
66SCHED_FEAT(NONTASK_POWER, 1)
67
68/*
69 * Queue remote wakeups on the target CPU and process them
70 * using the scheduler IPI. Reduces rq->lock contention/bounces.
71 */
72SCHED_FEAT(TTWU_QUEUE, 1)
73
74SCHED_FEAT(FORCE_SD_OVERLAP, 0)
diff --git a/kernel/sched_idletask.c b/kernel/sched_idletask.c
new file mode 100644
index 00000000000..0a51882534e
--- /dev/null
+++ b/kernel/sched_idletask.c
@@ -0,0 +1,97 @@
1/*
2 * idle-task scheduling class.
3 *
4 * (NOTE: these are not related to SCHED_IDLE tasks which are
5 * handled in sched_fair.c)
6 */
7
8#ifdef CONFIG_SMP
9static int
10select_task_rq_idle(struct task_struct *p, int sd_flag, int flags)
11{
12 return task_cpu(p); /* IDLE tasks as never migrated */
13}
14#endif /* CONFIG_SMP */
15/*
16 * Idle tasks are unconditionally rescheduled:
17 */
18static void check_preempt_curr_idle(struct rq *rq, struct task_struct *p, int flags)
19{
20 resched_task(rq->idle);
21}
22
23static struct task_struct *pick_next_task_idle(struct rq *rq)
24{
25 schedstat_inc(rq, sched_goidle);
26 calc_load_account_idle(rq);
27 return rq->idle;
28}
29
30/*
31 * It is not legal to sleep in the idle task - print a warning
32 * message if some code attempts to do it:
33 */
34static void
35dequeue_task_idle(struct rq *rq, struct task_struct *p, int flags)
36{
37 raw_spin_unlock_irq(&rq->lock);
38 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
39 dump_stack();
40 raw_spin_lock_irq(&rq->lock);
41}
42
43static void put_prev_task_idle(struct rq *rq, struct task_struct *prev)
44{
45}
46
47static void task_tick_idle(struct rq *rq, struct task_struct *curr, int queued)
48{
49}
50
51static void set_curr_task_idle(struct rq *rq)
52{
53}
54
55static void switched_to_idle(struct rq *rq, struct task_struct *p)
56{
57 BUG();
58}
59
60static void
61prio_changed_idle(struct rq *rq, struct task_struct *p, int oldprio)
62{
63 BUG();
64}
65
66static unsigned int get_rr_interval_idle(struct rq *rq, struct task_struct *task)
67{
68 return 0;
69}
70
71/*
72 * Simple, special scheduling class for the per-CPU idle tasks:
73 */
74static const struct sched_class idle_sched_class = {
75 /* .next is NULL */
76 /* no enqueue/yield_task for idle tasks */
77
78 /* dequeue is not valid, we print a debug message there: */
79 .dequeue_task = dequeue_task_idle,
80
81 .check_preempt_curr = check_preempt_curr_idle,
82
83 .pick_next_task = pick_next_task_idle,
84 .put_prev_task = put_prev_task_idle,
85
86#ifdef CONFIG_SMP
87 .select_task_rq = select_task_rq_idle,
88#endif
89
90 .set_curr_task = set_curr_task_idle,
91 .task_tick = task_tick_idle,
92
93 .get_rr_interval = get_rr_interval_idle,
94
95 .prio_changed = prio_changed_idle,
96 .switched_to = switched_to_idle,
97};
diff --git a/kernel/sched_rt.c b/kernel/sched_rt.c
new file mode 100644
index 00000000000..af1177858be
--- /dev/null
+++ b/kernel/sched_rt.c
@@ -0,0 +1,1866 @@
1/*
2 * Real-Time Scheduling Class (mapped to the SCHED_FIFO and SCHED_RR
3 * policies)
4 */
5
6#ifdef CONFIG_RT_GROUP_SCHED
7
8#define rt_entity_is_task(rt_se) (!(rt_se)->my_q)
9
10static inline struct task_struct *rt_task_of(struct sched_rt_entity *rt_se)
11{
12#ifdef CONFIG_SCHED_DEBUG
13 WARN_ON_ONCE(!rt_entity_is_task(rt_se));
14#endif
15 return container_of(rt_se, struct task_struct, rt);
16}
17
18static inline struct rq *rq_of_rt_rq(struct rt_rq *rt_rq)
19{
20 return rt_rq->rq;
21}
22
23static inline struct rt_rq *rt_rq_of_se(struct sched_rt_entity *rt_se)
24{
25 return rt_se->rt_rq;
26}
27
28#else /* CONFIG_RT_GROUP_SCHED */
29
30#define rt_entity_is_task(rt_se) (1)
31
32static inline struct task_struct *rt_task_of(struct sched_rt_entity *rt_se)
33{
34 return container_of(rt_se, struct task_struct, rt);
35}
36
37static inline struct rq *rq_of_rt_rq(struct rt_rq *rt_rq)
38{
39 return container_of(rt_rq, struct rq, rt);
40}
41
42static inline struct rt_rq *rt_rq_of_se(struct sched_rt_entity *rt_se)
43{
44 struct task_struct *p = rt_task_of(rt_se);
45 struct rq *rq = task_rq(p);
46
47 return &rq->rt;
48}
49
50#endif /* CONFIG_RT_GROUP_SCHED */
51
52#ifdef CONFIG_SMP
53
54static inline int rt_overloaded(struct rq *rq)
55{
56 return atomic_read(&rq->rd->rto_count);
57}
58
59static inline void rt_set_overload(struct rq *rq)
60{
61 if (!rq->online)
62 return;
63
64 cpumask_set_cpu(rq->cpu, rq->rd->rto_mask);
65 /*
66 * Make sure the mask is visible before we set
67 * the overload count. That is checked to determine
68 * if we should look at the mask. It would be a shame
69 * if we looked at the mask, but the mask was not
70 * updated yet.
71 */
72 wmb();
73 atomic_inc(&rq->rd->rto_count);
74}
75
76static inline void rt_clear_overload(struct rq *rq)
77{
78 if (!rq->online)
79 return;
80
81 /* the order here really doesn't matter */
82 atomic_dec(&rq->rd->rto_count);
83 cpumask_clear_cpu(rq->cpu, rq->rd->rto_mask);
84}
85
86static void update_rt_migration(struct rt_rq *rt_rq)
87{
88 if (rt_rq->rt_nr_migratory && rt_rq->rt_nr_total > 1) {
89 if (!rt_rq->overloaded) {
90 rt_set_overload(rq_of_rt_rq(rt_rq));
91 rt_rq->overloaded = 1;
92 }
93 } else if (rt_rq->overloaded) {
94 rt_clear_overload(rq_of_rt_rq(rt_rq));
95 rt_rq->overloaded = 0;
96 }
97}
98
99static void inc_rt_migration(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
100{
101 if (!rt_entity_is_task(rt_se))
102 return;
103
104 rt_rq = &rq_of_rt_rq(rt_rq)->rt;
105
106 rt_rq->rt_nr_total++;
107 if (rt_se->nr_cpus_allowed > 1)
108 rt_rq->rt_nr_migratory++;
109
110 update_rt_migration(rt_rq);
111}
112
113static void dec_rt_migration(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
114{
115 if (!rt_entity_is_task(rt_se))
116 return;
117
118 rt_rq = &rq_of_rt_rq(rt_rq)->rt;
119
120 rt_rq->rt_nr_total--;
121 if (rt_se->nr_cpus_allowed > 1)
122 rt_rq->rt_nr_migratory--;
123
124 update_rt_migration(rt_rq);
125}
126
127static void enqueue_pushable_task(struct rq *rq, struct task_struct *p)
128{
129 plist_del(&p->pushable_tasks, &rq->rt.pushable_tasks);
130 plist_node_init(&p->pushable_tasks, p->prio);
131 plist_add(&p->pushable_tasks, &rq->rt.pushable_tasks);
132}
133
134static void dequeue_pushable_task(struct rq *rq, struct task_struct *p)
135{
136 plist_del(&p->pushable_tasks, &rq->rt.pushable_tasks);
137}
138
139static inline int has_pushable_tasks(struct rq *rq)
140{
141 return !plist_head_empty(&rq->rt.pushable_tasks);
142}
143
144#else
145
146static inline void enqueue_pushable_task(struct rq *rq, struct task_struct *p)
147{
148}
149
150static inline void dequeue_pushable_task(struct rq *rq, struct task_struct *p)
151{
152}
153
154static inline
155void inc_rt_migration(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
156{
157}
158
159static inline
160void dec_rt_migration(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
161{
162}
163
164#endif /* CONFIG_SMP */
165
166static inline int on_rt_rq(struct sched_rt_entity *rt_se)
167{
168 return !list_empty(&rt_se->run_list);
169}
170
171#ifdef CONFIG_RT_GROUP_SCHED
172
173static inline u64 sched_rt_runtime(struct rt_rq *rt_rq)
174{
175 if (!rt_rq->tg)
176 return RUNTIME_INF;
177
178 return rt_rq->rt_runtime;
179}
180
181static inline u64 sched_rt_period(struct rt_rq *rt_rq)
182{
183 return ktime_to_ns(rt_rq->tg->rt_bandwidth.rt_period);
184}
185
186typedef struct task_group *rt_rq_iter_t;
187
188static inline struct task_group *next_task_group(struct task_group *tg)
189{
190 do {
191 tg = list_entry_rcu(tg->list.next,
192 typeof(struct task_group), list);
193 } while (&tg->list != &task_groups && task_group_is_autogroup(tg));
194
195 if (&tg->list == &task_groups)
196 tg = NULL;
197
198 return tg;
199}
200
201#define for_each_rt_rq(rt_rq, iter, rq) \
202 for (iter = container_of(&task_groups, typeof(*iter), list); \
203 (iter = next_task_group(iter)) && \
204 (rt_rq = iter->rt_rq[cpu_of(rq)]);)
205
206static inline void list_add_leaf_rt_rq(struct rt_rq *rt_rq)
207{
208 list_add_rcu(&rt_rq->leaf_rt_rq_list,
209 &rq_of_rt_rq(rt_rq)->leaf_rt_rq_list);
210}
211
212static inline void list_del_leaf_rt_rq(struct rt_rq *rt_rq)
213{
214 list_del_rcu(&rt_rq->leaf_rt_rq_list);
215}
216
217#define for_each_leaf_rt_rq(rt_rq, rq) \
218 list_for_each_entry_rcu(rt_rq, &rq->leaf_rt_rq_list, leaf_rt_rq_list)
219
220#define for_each_sched_rt_entity(rt_se) \
221 for (; rt_se; rt_se = rt_se->parent)
222
223static inline struct rt_rq *group_rt_rq(struct sched_rt_entity *rt_se)
224{
225 return rt_se->my_q;
226}
227
228static void enqueue_rt_entity(struct sched_rt_entity *rt_se, bool head);
229static void dequeue_rt_entity(struct sched_rt_entity *rt_se);
230
231static void sched_rt_rq_enqueue(struct rt_rq *rt_rq)
232{
233 struct task_struct *curr = rq_of_rt_rq(rt_rq)->curr;
234 struct sched_rt_entity *rt_se;
235
236 int cpu = cpu_of(rq_of_rt_rq(rt_rq));
237
238 rt_se = rt_rq->tg->rt_se[cpu];
239
240 if (rt_rq->rt_nr_running) {
241 if (rt_se && !on_rt_rq(rt_se))
242 enqueue_rt_entity(rt_se, false);
243 if (rt_rq->highest_prio.curr < curr->prio)
244 resched_task(curr);
245 }
246}
247
248static void sched_rt_rq_dequeue(struct rt_rq *rt_rq)
249{
250 struct sched_rt_entity *rt_se;
251 int cpu = cpu_of(rq_of_rt_rq(rt_rq));
252
253 rt_se = rt_rq->tg->rt_se[cpu];
254
255 if (rt_se && on_rt_rq(rt_se))
256 dequeue_rt_entity(rt_se);
257}
258
259static inline int rt_rq_throttled(struct rt_rq *rt_rq)
260{
261 return rt_rq->rt_throttled && !rt_rq->rt_nr_boosted;
262}
263
264static int rt_se_boosted(struct sched_rt_entity *rt_se)
265{
266 struct rt_rq *rt_rq = group_rt_rq(rt_se);
267 struct task_struct *p;
268
269 if (rt_rq)
270 return !!rt_rq->rt_nr_boosted;
271
272 p = rt_task_of(rt_se);
273 return p->prio != p->normal_prio;
274}
275
276#ifdef CONFIG_SMP
277static inline const struct cpumask *sched_rt_period_mask(void)
278{
279 return cpu_rq(smp_processor_id())->rd->span;
280}
281#else
282static inline const struct cpumask *sched_rt_period_mask(void)
283{
284 return cpu_online_mask;
285}
286#endif
287
288static inline
289struct rt_rq *sched_rt_period_rt_rq(struct rt_bandwidth *rt_b, int cpu)
290{
291 return container_of(rt_b, struct task_group, rt_bandwidth)->rt_rq[cpu];
292}
293
294static inline struct rt_bandwidth *sched_rt_bandwidth(struct rt_rq *rt_rq)
295{
296 return &rt_rq->tg->rt_bandwidth;
297}
298
299#else /* !CONFIG_RT_GROUP_SCHED */
300
301static inline u64 sched_rt_runtime(struct rt_rq *rt_rq)
302{
303 return rt_rq->rt_runtime;
304}
305
306static inline u64 sched_rt_period(struct rt_rq *rt_rq)
307{
308 return ktime_to_ns(def_rt_bandwidth.rt_period);
309}
310
311typedef struct rt_rq *rt_rq_iter_t;
312
313#define for_each_rt_rq(rt_rq, iter, rq) \
314 for ((void) iter, rt_rq = &rq->rt; rt_rq; rt_rq = NULL)
315
316static inline void list_add_leaf_rt_rq(struct rt_rq *rt_rq)
317{
318}
319
320static inline void list_del_leaf_rt_rq(struct rt_rq *rt_rq)
321{
322}
323
324#define for_each_leaf_rt_rq(rt_rq, rq) \
325 for (rt_rq = &rq->rt; rt_rq; rt_rq = NULL)
326
327#define for_each_sched_rt_entity(rt_se) \
328 for (; rt_se; rt_se = NULL)
329
330static inline struct rt_rq *group_rt_rq(struct sched_rt_entity *rt_se)
331{
332 return NULL;
333}
334
335static inline void sched_rt_rq_enqueue(struct rt_rq *rt_rq)
336{
337 if (rt_rq->rt_nr_running)
338 resched_task(rq_of_rt_rq(rt_rq)->curr);
339}
340
341static inline void sched_rt_rq_dequeue(struct rt_rq *rt_rq)
342{
343}
344
345static inline int rt_rq_throttled(struct rt_rq *rt_rq)
346{
347 return rt_rq->rt_throttled;
348}
349
350static inline const struct cpumask *sched_rt_period_mask(void)
351{
352 return cpu_online_mask;
353}
354
355static inline
356struct rt_rq *sched_rt_period_rt_rq(struct rt_bandwidth *rt_b, int cpu)
357{
358 return &cpu_rq(cpu)->rt;
359}
360
361static inline struct rt_bandwidth *sched_rt_bandwidth(struct rt_rq *rt_rq)
362{
363 return &def_rt_bandwidth;
364}
365
366#endif /* CONFIG_RT_GROUP_SCHED */
367
368#ifdef CONFIG_SMP
369/*
370 * We ran out of runtime, see if we can borrow some from our neighbours.
371 */
372static int do_balance_runtime(struct rt_rq *rt_rq)
373{
374 struct rt_bandwidth *rt_b = sched_rt_bandwidth(rt_rq);
375 struct root_domain *rd = cpu_rq(smp_processor_id())->rd;
376 int i, weight, more = 0;
377 u64 rt_period;
378
379 weight = cpumask_weight(rd->span);
380
381 raw_spin_lock(&rt_b->rt_runtime_lock);
382 rt_period = ktime_to_ns(rt_b->rt_period);
383 for_each_cpu(i, rd->span) {
384 struct rt_rq *iter = sched_rt_period_rt_rq(rt_b, i);
385 s64 diff;
386
387 if (iter == rt_rq)
388 continue;
389
390 raw_spin_lock(&iter->rt_runtime_lock);
391 /*
392 * Either all rqs have inf runtime and there's nothing to steal
393 * or __disable_runtime() below sets a specific rq to inf to
394 * indicate its been disabled and disalow stealing.
395 */
396 if (iter->rt_runtime == RUNTIME_INF)
397 goto next;
398
399 /*
400 * From runqueues with spare time, take 1/n part of their
401 * spare time, but no more than our period.
402 */
403 diff = iter->rt_runtime - iter->rt_time;
404 if (diff > 0) {
405 diff = div_u64((u64)diff, weight);
406 if (rt_rq->rt_runtime + diff > rt_period)
407 diff = rt_period - rt_rq->rt_runtime;
408 iter->rt_runtime -= diff;
409 rt_rq->rt_runtime += diff;
410 more = 1;
411 if (rt_rq->rt_runtime == rt_period) {
412 raw_spin_unlock(&iter->rt_runtime_lock);
413 break;
414 }
415 }
416next:
417 raw_spin_unlock(&iter->rt_runtime_lock);
418 }
419 raw_spin_unlock(&rt_b->rt_runtime_lock);
420
421 return more;
422}
423
424/*
425 * Ensure this RQ takes back all the runtime it lend to its neighbours.
426 */
427static void __disable_runtime(struct rq *rq)
428{
429 struct root_domain *rd = rq->rd;
430 rt_rq_iter_t iter;
431 struct rt_rq *rt_rq;
432
433 if (unlikely(!scheduler_running))
434 return;
435
436 for_each_rt_rq(rt_rq, iter, rq) {
437 struct rt_bandwidth *rt_b = sched_rt_bandwidth(rt_rq);
438 s64 want;
439 int i;
440
441 raw_spin_lock(&rt_b->rt_runtime_lock);
442 raw_spin_lock(&rt_rq->rt_runtime_lock);
443 /*
444 * Either we're all inf and nobody needs to borrow, or we're
445 * already disabled and thus have nothing to do, or we have
446 * exactly the right amount of runtime to take out.
447 */
448 if (rt_rq->rt_runtime == RUNTIME_INF ||
449 rt_rq->rt_runtime == rt_b->rt_runtime)
450 goto balanced;
451 raw_spin_unlock(&rt_rq->rt_runtime_lock);
452
453 /*
454 * Calculate the difference between what we started out with
455 * and what we current have, that's the amount of runtime
456 * we lend and now have to reclaim.
457 */
458 want = rt_b->rt_runtime - rt_rq->rt_runtime;
459
460 /*
461 * Greedy reclaim, take back as much as we can.
462 */
463 for_each_cpu(i, rd->span) {
464 struct rt_rq *iter = sched_rt_period_rt_rq(rt_b, i);
465 s64 diff;
466
467 /*
468 * Can't reclaim from ourselves or disabled runqueues.
469 */
470 if (iter == rt_rq || iter->rt_runtime == RUNTIME_INF)
471 continue;
472
473 raw_spin_lock(&iter->rt_runtime_lock);
474 if (want > 0) {
475 diff = min_t(s64, iter->rt_runtime, want);
476 iter->rt_runtime -= diff;
477 want -= diff;
478 } else {
479 iter->rt_runtime -= want;
480 want -= want;
481 }
482 raw_spin_unlock(&iter->rt_runtime_lock);
483
484 if (!want)
485 break;
486 }
487
488 raw_spin_lock(&rt_rq->rt_runtime_lock);
489 /*
490 * We cannot be left wanting - that would mean some runtime
491 * leaked out of the system.
492 */
493 BUG_ON(want);
494balanced:
495 /*
496 * Disable all the borrow logic by pretending we have inf
497 * runtime - in which case borrowing doesn't make sense.
498 */
499 rt_rq->rt_runtime = RUNTIME_INF;
500 raw_spin_unlock(&rt_rq->rt_runtime_lock);
501 raw_spin_unlock(&rt_b->rt_runtime_lock);
502 }
503}
504
505static void disable_runtime(struct rq *rq)
506{
507 unsigned long flags;
508
509 raw_spin_lock_irqsave(&rq->lock, flags);
510 __disable_runtime(rq);
511 raw_spin_unlock_irqrestore(&rq->lock, flags);
512}
513
514static void __enable_runtime(struct rq *rq)
515{
516 rt_rq_iter_t iter;
517 struct rt_rq *rt_rq;
518
519 if (unlikely(!scheduler_running))
520 return;
521
522 /*
523 * Reset each runqueue's bandwidth settings
524 */
525 for_each_rt_rq(rt_rq, iter, rq) {
526 struct rt_bandwidth *rt_b = sched_rt_bandwidth(rt_rq);
527
528 raw_spin_lock(&rt_b->rt_runtime_lock);
529 raw_spin_lock(&rt_rq->rt_runtime_lock);
530 rt_rq->rt_runtime = rt_b->rt_runtime;
531 rt_rq->rt_time = 0;
532 rt_rq->rt_throttled = 0;
533 raw_spin_unlock(&rt_rq->rt_runtime_lock);
534 raw_spin_unlock(&rt_b->rt_runtime_lock);
535 }
536}
537
538static void enable_runtime(struct rq *rq)
539{
540 unsigned long flags;
541
542 raw_spin_lock_irqsave(&rq->lock, flags);
543 __enable_runtime(rq);
544 raw_spin_unlock_irqrestore(&rq->lock, flags);
545}
546
547static int balance_runtime(struct rt_rq *rt_rq)
548{
549 int more = 0;
550
551 if (rt_rq->rt_time > rt_rq->rt_runtime) {
552 raw_spin_unlock(&rt_rq->rt_runtime_lock);
553 more = do_balance_runtime(rt_rq);
554 raw_spin_lock(&rt_rq->rt_runtime_lock);
555 }
556
557 return more;
558}
559#else /* !CONFIG_SMP */
560static inline int balance_runtime(struct rt_rq *rt_rq)
561{
562 return 0;
563}
564#endif /* CONFIG_SMP */
565
566static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun)
567{
568 int i, idle = 1;
569 const struct cpumask *span;
570
571 if (!rt_bandwidth_enabled() || rt_b->rt_runtime == RUNTIME_INF)
572 return 1;
573
574 span = sched_rt_period_mask();
575 for_each_cpu(i, span) {
576 int enqueue = 0;
577 struct rt_rq *rt_rq = sched_rt_period_rt_rq(rt_b, i);
578 struct rq *rq = rq_of_rt_rq(rt_rq);
579
580 raw_spin_lock(&rq->lock);
581 if (rt_rq->rt_time) {
582 u64 runtime;
583
584 raw_spin_lock(&rt_rq->rt_runtime_lock);
585 if (rt_rq->rt_throttled)
586 balance_runtime(rt_rq);
587 runtime = rt_rq->rt_runtime;
588 rt_rq->rt_time -= min(rt_rq->rt_time, overrun*runtime);
589 if (rt_rq->rt_throttled && rt_rq->rt_time < runtime) {
590 rt_rq->rt_throttled = 0;
591 enqueue = 1;
592
593 /*
594 * Force a clock update if the CPU was idle,
595 * lest wakeup -> unthrottle time accumulate.
596 */
597 if (rt_rq->rt_nr_running && rq->curr == rq->idle)
598 rq->skip_clock_update = -1;
599 }
600 if (rt_rq->rt_time || rt_rq->rt_nr_running)
601 idle = 0;
602 raw_spin_unlock(&rt_rq->rt_runtime_lock);
603 } else if (rt_rq->rt_nr_running) {
604 idle = 0;
605 if (!rt_rq_throttled(rt_rq))
606 enqueue = 1;
607 }
608
609 if (enqueue)
610 sched_rt_rq_enqueue(rt_rq);
611 raw_spin_unlock(&rq->lock);
612 }
613
614 return idle;
615}
616
617static inline int rt_se_prio(struct sched_rt_entity *rt_se)
618{
619#ifdef CONFIG_RT_GROUP_SCHED
620 struct rt_rq *rt_rq = group_rt_rq(rt_se);
621
622 if (rt_rq)
623 return rt_rq->highest_prio.curr;
624#endif
625
626 return rt_task_of(rt_se)->prio;
627}
628
629static int sched_rt_runtime_exceeded(struct rt_rq *rt_rq)
630{
631 u64 runtime = sched_rt_runtime(rt_rq);
632
633 if (rt_rq->rt_throttled)
634 return rt_rq_throttled(rt_rq);
635
636 if (sched_rt_runtime(rt_rq) >= sched_rt_period(rt_rq))
637 return 0;
638
639 balance_runtime(rt_rq);
640 runtime = sched_rt_runtime(rt_rq);
641 if (runtime == RUNTIME_INF)
642 return 0;
643
644 if (rt_rq->rt_time > runtime) {
645 rt_rq->rt_throttled = 1;
646 if (rt_rq_throttled(rt_rq)) {
647 sched_rt_rq_dequeue(rt_rq);
648 return 1;
649 }
650 }
651
652 return 0;
653}
654
655/*
656 * Update the current task's runtime statistics. Skip current tasks that
657 * are not in our scheduling class.
658 */
659static void update_curr_rt(struct rq *rq)
660{
661 struct task_struct *curr = rq->curr;
662 struct sched_rt_entity *rt_se = &curr->rt;
663 struct rt_rq *rt_rq = rt_rq_of_se(rt_se);
664 u64 delta_exec;
665
666 if (curr->sched_class != &rt_sched_class)
667 return;
668
669 delta_exec = rq->clock_task - curr->se.exec_start;
670 if (unlikely((s64)delta_exec < 0))
671 delta_exec = 0;
672
673 schedstat_set(curr->se.statistics.exec_max, max(curr->se.statistics.exec_max, delta_exec));
674
675 curr->se.sum_exec_runtime += delta_exec;
676 account_group_exec_runtime(curr, delta_exec);
677
678 curr->se.exec_start = rq->clock_task;
679 cpuacct_charge(curr, delta_exec);
680
681 sched_rt_avg_update(rq, delta_exec);
682
683 if (!rt_bandwidth_enabled())
684 return;
685
686 for_each_sched_rt_entity(rt_se) {
687 rt_rq = rt_rq_of_se(rt_se);
688
689 if (sched_rt_runtime(rt_rq) != RUNTIME_INF) {
690 raw_spin_lock(&rt_rq->rt_runtime_lock);
691 rt_rq->rt_time += delta_exec;
692 if (sched_rt_runtime_exceeded(rt_rq))
693 resched_task(curr);
694 raw_spin_unlock(&rt_rq->rt_runtime_lock);
695 }
696 }
697}
698
699#if defined CONFIG_SMP
700
701static struct task_struct *pick_next_highest_task_rt(struct rq *rq, int cpu);
702
703static inline int next_prio(struct rq *rq)
704{
705 struct task_struct *next = pick_next_highest_task_rt(rq, rq->cpu);
706
707 if (next && rt_prio(next->prio))
708 return next->prio;
709 else
710 return MAX_RT_PRIO;
711}
712
713static void
714inc_rt_prio_smp(struct rt_rq *rt_rq, int prio, int prev_prio)
715{
716 struct rq *rq = rq_of_rt_rq(rt_rq);
717
718 if (prio < prev_prio) {
719
720 /*
721 * If the new task is higher in priority than anything on the
722 * run-queue, we know that the previous high becomes our
723 * next-highest.
724 */
725 rt_rq->highest_prio.next = prev_prio;
726
727 if (rq->online)
728 cpupri_set(&rq->rd->cpupri, rq->cpu, prio);
729
730 } else if (prio == rt_rq->highest_prio.curr)
731 /*
732 * If the next task is equal in priority to the highest on
733 * the run-queue, then we implicitly know that the next highest
734 * task cannot be any lower than current
735 */
736 rt_rq->highest_prio.next = prio;
737 else if (prio < rt_rq->highest_prio.next)
738 /*
739 * Otherwise, we need to recompute next-highest
740 */
741 rt_rq->highest_prio.next = next_prio(rq);
742}
743
744static void
745dec_rt_prio_smp(struct rt_rq *rt_rq, int prio, int prev_prio)
746{
747 struct rq *rq = rq_of_rt_rq(rt_rq);
748
749 if (rt_rq->rt_nr_running && (prio <= rt_rq->highest_prio.next))
750 rt_rq->highest_prio.next = next_prio(rq);
751
752 if (rq->online && rt_rq->highest_prio.curr != prev_prio)
753 cpupri_set(&rq->rd->cpupri, rq->cpu, rt_rq->highest_prio.curr);
754}
755
756#else /* CONFIG_SMP */
757
758static inline
759void inc_rt_prio_smp(struct rt_rq *rt_rq, int prio, int prev_prio) {}
760static inline
761void dec_rt_prio_smp(struct rt_rq *rt_rq, int prio, int prev_prio) {}
762
763#endif /* CONFIG_SMP */
764
765#if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
766static void
767inc_rt_prio(struct rt_rq *rt_rq, int prio)
768{
769 int prev_prio = rt_rq->highest_prio.curr;
770
771 if (prio < prev_prio)
772 rt_rq->highest_prio.curr = prio;
773
774 inc_rt_prio_smp(rt_rq, prio, prev_prio);
775}
776
777static void
778dec_rt_prio(struct rt_rq *rt_rq, int prio)
779{
780 int prev_prio = rt_rq->highest_prio.curr;
781
782 if (rt_rq->rt_nr_running) {
783
784 WARN_ON(prio < prev_prio);
785
786 /*
787 * This may have been our highest task, and therefore
788 * we may have some recomputation to do
789 */
790 if (prio == prev_prio) {
791 struct rt_prio_array *array = &rt_rq->active;
792
793 rt_rq->highest_prio.curr =
794 sched_find_first_bit(array->bitmap);
795 }
796
797 } else
798 rt_rq->highest_prio.curr = MAX_RT_PRIO;
799
800 dec_rt_prio_smp(rt_rq, prio, prev_prio);
801}
802
803#else
804
805static inline void inc_rt_prio(struct rt_rq *rt_rq, int prio) {}
806static inline void dec_rt_prio(struct rt_rq *rt_rq, int prio) {}
807
808#endif /* CONFIG_SMP || CONFIG_RT_GROUP_SCHED */
809
810#ifdef CONFIG_RT_GROUP_SCHED
811
812static void
813inc_rt_group(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
814{
815 if (rt_se_boosted(rt_se))
816 rt_rq->rt_nr_boosted++;
817
818 if (rt_rq->tg)
819 start_rt_bandwidth(&rt_rq->tg->rt_bandwidth);
820}
821
822static void
823dec_rt_group(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
824{
825 if (rt_se_boosted(rt_se))
826 rt_rq->rt_nr_boosted--;
827
828 WARN_ON(!rt_rq->rt_nr_running && rt_rq->rt_nr_boosted);
829}
830
831#else /* CONFIG_RT_GROUP_SCHED */
832
833static void
834inc_rt_group(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
835{
836 start_rt_bandwidth(&def_rt_bandwidth);
837}
838
839static inline
840void dec_rt_group(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq) {}
841
842#endif /* CONFIG_RT_GROUP_SCHED */
843
844static inline
845void inc_rt_tasks(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
846{
847 int prio = rt_se_prio(rt_se);
848
849 WARN_ON(!rt_prio(prio));
850 rt_rq->rt_nr_running++;
851
852 inc_rt_prio(rt_rq, prio);
853 inc_rt_migration(rt_se, rt_rq);
854 inc_rt_group(rt_se, rt_rq);
855}
856
857static inline
858void dec_rt_tasks(struct sched_rt_entity *rt_se, struct rt_rq *rt_rq)
859{
860 WARN_ON(!rt_prio(rt_se_prio(rt_se)));
861 WARN_ON(!rt_rq->rt_nr_running);
862 rt_rq->rt_nr_running--;
863
864 dec_rt_prio(rt_rq, rt_se_prio(rt_se));
865 dec_rt_migration(rt_se, rt_rq);
866 dec_rt_group(rt_se, rt_rq);
867}
868
869static void __enqueue_rt_entity(struct sched_rt_entity *rt_se, bool head)
870{
871 struct rt_rq *rt_rq = rt_rq_of_se(rt_se);
872 struct rt_prio_array *array = &rt_rq->active;
873 struct rt_rq *group_rq = group_rt_rq(rt_se);
874 struct list_head *queue = array->queue + rt_se_prio(rt_se);
875
876 /*
877 * Don't enqueue the group if its throttled, or when empty.
878 * The latter is a consequence of the former when a child group
879 * get throttled and the current group doesn't have any other
880 * active members.
881 */
882 if (group_rq && (rt_rq_throttled(group_rq) || !group_rq->rt_nr_running))
883 return;
884
885 if (!rt_rq->rt_nr_running)
886 list_add_leaf_rt_rq(rt_rq);
887
888 if (head)
889 list_add(&rt_se->run_list, queue);
890 else
891 list_add_tail(&rt_se->run_list, queue);
892 __set_bit(rt_se_prio(rt_se), array->bitmap);
893
894 inc_rt_tasks(rt_se, rt_rq);
895}
896
897static void __dequeue_rt_entity(struct sched_rt_entity *rt_se)
898{
899 struct rt_rq *rt_rq = rt_rq_of_se(rt_se);
900 struct rt_prio_array *array = &rt_rq->active;
901
902 list_del_init(&rt_se->run_list);
903 if (list_empty(array->queue + rt_se_prio(rt_se)))
904 __clear_bit(rt_se_prio(rt_se), array->bitmap);
905
906 dec_rt_tasks(rt_se, rt_rq);
907 if (!rt_rq->rt_nr_running)
908 list_del_leaf_rt_rq(rt_rq);
909}
910
911/*
912 * Because the prio of an upper entry depends on the lower
913 * entries, we must remove entries top - down.
914 */
915static void dequeue_rt_stack(struct sched_rt_entity *rt_se)
916{
917 struct sched_rt_entity *back = NULL;
918
919 for_each_sched_rt_entity(rt_se) {
920 rt_se->back = back;
921 back = rt_se;
922 }
923
924 for (rt_se = back; rt_se; rt_se = rt_se->back) {
925 if (on_rt_rq(rt_se))
926 __dequeue_rt_entity(rt_se);
927 }
928}
929
930static void enqueue_rt_entity(struct sched_rt_entity *rt_se, bool head)
931{
932 dequeue_rt_stack(rt_se);
933 for_each_sched_rt_entity(rt_se)
934 __enqueue_rt_entity(rt_se, head);
935}
936
937static void dequeue_rt_entity(struct sched_rt_entity *rt_se)
938{
939 dequeue_rt_stack(rt_se);
940
941 for_each_sched_rt_entity(rt_se) {
942 struct rt_rq *rt_rq = group_rt_rq(rt_se);
943
944 if (rt_rq && rt_rq->rt_nr_running)
945 __enqueue_rt_entity(rt_se, false);
946 }
947}
948
949/*
950 * Adding/removing a task to/from a priority array:
951 */
952static void
953enqueue_task_rt(struct rq *rq, struct task_struct *p, int flags)
954{
955 struct sched_rt_entity *rt_se = &p->rt;
956
957 if (flags & ENQUEUE_WAKEUP)
958 rt_se->timeout = 0;
959
960 enqueue_rt_entity(rt_se, flags & ENQUEUE_HEAD);
961
962 if (!task_current(rq, p) && p->rt.nr_cpus_allowed > 1)
963 enqueue_pushable_task(rq, p);
964}
965
966static void dequeue_task_rt(struct rq *rq, struct task_struct *p, int flags)
967{
968 struct sched_rt_entity *rt_se = &p->rt;
969
970 update_curr_rt(rq);
971 dequeue_rt_entity(rt_se);
972
973 dequeue_pushable_task(rq, p);
974}
975
976/*
977 * Put task to the end of the run list without the overhead of dequeue
978 * followed by enqueue.
979 */
980static void
981requeue_rt_entity(struct rt_rq *rt_rq, struct sched_rt_entity *rt_se, int head)
982{
983 if (on_rt_rq(rt_se)) {
984 struct rt_prio_array *array = &rt_rq->active;
985 struct list_head *queue = array->queue + rt_se_prio(rt_se);
986
987 if (head)
988 list_move(&rt_se->run_list, queue);
989 else
990 list_move_tail(&rt_se->run_list, queue);
991 }
992}
993
994static void requeue_task_rt(struct rq *rq, struct task_struct *p, int head)
995{
996 struct sched_rt_entity *rt_se = &p->rt;
997 struct rt_rq *rt_rq;
998
999 for_each_sched_rt_entity(rt_se) {
1000 rt_rq = rt_rq_of_se(rt_se);
1001 requeue_rt_entity(rt_rq, rt_se, head);
1002 }
1003}
1004
1005static void yield_task_rt(struct rq *rq)
1006{
1007 requeue_task_rt(rq, rq->curr, 0);
1008}
1009
1010#ifdef CONFIG_SMP
1011static int find_lowest_rq(struct task_struct *task);
1012
1013static int
1014select_task_rq_rt(struct task_struct *p, int sd_flag, int flags)
1015{
1016 struct task_struct *curr;
1017 struct rq *rq;
1018 int cpu;
1019
1020 if (sd_flag != SD_BALANCE_WAKE)
1021 return smp_processor_id();
1022
1023 cpu = task_cpu(p);
1024 rq = cpu_rq(cpu);
1025
1026 rcu_read_lock();
1027 curr = ACCESS_ONCE(rq->curr); /* unlocked access */
1028
1029 /*
1030 * If the current task on @p's runqueue is an RT task, then
1031 * try to see if we can wake this RT task up on another
1032 * runqueue. Otherwise simply start this RT task
1033 * on its current runqueue.
1034 *
1035 * We want to avoid overloading runqueues. If the woken
1036 * task is a higher priority, then it will stay on this CPU
1037 * and the lower prio task should be moved to another CPU.
1038 * Even though this will probably make the lower prio task
1039 * lose its cache, we do not want to bounce a higher task
1040 * around just because it gave up its CPU, perhaps for a
1041 * lock?
1042 *
1043 * For equal prio tasks, we just let the scheduler sort it out.
1044 *
1045 * Otherwise, just let it ride on the affined RQ and the
1046 * post-schedule router will push the preempted task away
1047 *
1048 * This test is optimistic, if we get it wrong the load-balancer
1049 * will have to sort it out.
1050 */
1051 if (curr && unlikely(rt_task(curr)) &&
1052 (curr->rt.nr_cpus_allowed < 2 ||
1053 curr->prio <= p->prio) &&
1054 (p->rt.nr_cpus_allowed > 1)) {
1055 int target = find_lowest_rq(p);
1056
1057 if (target != -1)
1058 cpu = target;
1059 }
1060 rcu_read_unlock();
1061
1062 return cpu;
1063}
1064
1065static void check_preempt_equal_prio(struct rq *rq, struct task_struct *p)
1066{
1067 if (rq->curr->rt.nr_cpus_allowed == 1)
1068 return;
1069
1070 if (p->rt.nr_cpus_allowed != 1
1071 && cpupri_find(&rq->rd->cpupri, p, NULL))
1072 return;
1073
1074 if (!cpupri_find(&rq->rd->cpupri, rq->curr, NULL))
1075 return;
1076
1077 /*
1078 * There appears to be other cpus that can accept
1079 * current and none to run 'p', so lets reschedule
1080 * to try and push current away:
1081 */
1082 requeue_task_rt(rq, p, 1);
1083 resched_task(rq->curr);
1084}
1085
1086#endif /* CONFIG_SMP */
1087
1088/*
1089 * Preempt the current task with a newly woken task if needed:
1090 */
1091static void check_preempt_curr_rt(struct rq *rq, struct task_struct *p, int flags)
1092{
1093 if (p->prio < rq->curr->prio) {
1094 resched_task(rq->curr);
1095 return;
1096 }
1097
1098#ifdef CONFIG_SMP
1099 /*
1100 * If:
1101 *
1102 * - the newly woken task is of equal priority to the current task
1103 * - the newly woken task is non-migratable while current is migratable
1104 * - current will be preempted on the next reschedule
1105 *
1106 * we should check to see if current can readily move to a different
1107 * cpu. If so, we will reschedule to allow the push logic to try
1108 * to move current somewhere else, making room for our non-migratable
1109 * task.
1110 */
1111 if (p->prio == rq->curr->prio && !test_tsk_need_resched(rq->curr))
1112 check_preempt_equal_prio(rq, p);
1113#endif
1114}
1115
1116static struct sched_rt_entity *pick_next_rt_entity(struct rq *rq,
1117 struct rt_rq *rt_rq)
1118{
1119 struct rt_prio_array *array = &rt_rq->active;
1120 struct sched_rt_entity *next = NULL;
1121 struct list_head *queue;
1122 int idx;
1123
1124 idx = sched_find_first_bit(array->bitmap);
1125 BUG_ON(idx >= MAX_RT_PRIO);
1126
1127 queue = array->queue + idx;
1128 next = list_entry(queue->next, struct sched_rt_entity, run_list);
1129
1130 return next;
1131}
1132
1133static struct task_struct *_pick_next_task_rt(struct rq *rq)
1134{
1135 struct sched_rt_entity *rt_se;
1136 struct task_struct *p;
1137 struct rt_rq *rt_rq;
1138
1139 rt_rq = &rq->rt;
1140
1141 if (!rt_rq->rt_nr_running)
1142 return NULL;
1143
1144 if (rt_rq_throttled(rt_rq))
1145 return NULL;
1146
1147 do {
1148 rt_se = pick_next_rt_entity(rq, rt_rq);
1149 BUG_ON(!rt_se);
1150 rt_rq = group_rt_rq(rt_se);
1151 } while (rt_rq);
1152
1153 p = rt_task_of(rt_se);
1154 p->se.exec_start = rq->clock_task;
1155
1156 return p;
1157}
1158
1159static struct task_struct *pick_next_task_rt(struct rq *rq)
1160{
1161 struct task_struct *p = _pick_next_task_rt(rq);
1162
1163 /* The running task is never eligible for pushing */
1164 if (p)
1165 dequeue_pushable_task(rq, p);
1166
1167#ifdef CONFIG_SMP
1168 /*
1169 * We detect this state here so that we can avoid taking the RQ
1170 * lock again later if there is no need to push
1171 */
1172 rq->post_schedule = has_pushable_tasks(rq);
1173#endif
1174
1175 return p;
1176}
1177
1178static void put_prev_task_rt(struct rq *rq, struct task_struct *p)
1179{
1180 update_curr_rt(rq);
1181 p->se.exec_start = 0;
1182
1183 /*
1184 * The previous task needs to be made eligible for pushing
1185 * if it is still active
1186 */
1187 if (on_rt_rq(&p->rt) && p->rt.nr_cpus_allowed > 1)
1188 enqueue_pushable_task(rq, p);
1189}
1190
1191#ifdef CONFIG_SMP
1192
1193/* Only try algorithms three times */
1194#define RT_MAX_TRIES 3
1195
1196static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep);
1197
1198static int pick_rt_task(struct rq *rq, struct task_struct *p, int cpu)
1199{
1200 if (!task_running(rq, p) &&
1201 (cpu < 0 || cpumask_test_cpu(cpu, &p->cpus_allowed)) &&
1202 (p->rt.nr_cpus_allowed > 1))
1203 return 1;
1204 return 0;
1205}
1206
1207/* Return the second highest RT task, NULL otherwise */
1208static struct task_struct *pick_next_highest_task_rt(struct rq *rq, int cpu)
1209{
1210 struct task_struct *next = NULL;
1211 struct sched_rt_entity *rt_se;
1212 struct rt_prio_array *array;
1213 struct rt_rq *rt_rq;
1214 int idx;
1215
1216 for_each_leaf_rt_rq(rt_rq, rq) {
1217 array = &rt_rq->active;
1218 idx = sched_find_first_bit(array->bitmap);
1219next_idx:
1220 if (idx >= MAX_RT_PRIO)
1221 continue;
1222 if (next && next->prio < idx)
1223 continue;
1224 list_for_each_entry(rt_se, array->queue + idx, run_list) {
1225 struct task_struct *p;
1226
1227 if (!rt_entity_is_task(rt_se))
1228 continue;
1229
1230 p = rt_task_of(rt_se);
1231 if (pick_rt_task(rq, p, cpu)) {
1232 next = p;
1233 break;
1234 }
1235 }
1236 if (!next) {
1237 idx = find_next_bit(array->bitmap, MAX_RT_PRIO, idx+1);
1238 goto next_idx;
1239 }
1240 }
1241
1242 return next;
1243}
1244
1245static DEFINE_PER_CPU(cpumask_var_t, local_cpu_mask);
1246
1247static int find_lowest_rq(struct task_struct *task)
1248{
1249 struct sched_domain *sd;
1250 struct cpumask *lowest_mask = __get_cpu_var(local_cpu_mask);
1251 int this_cpu = smp_processor_id();
1252 int cpu = task_cpu(task);
1253
1254 /* Make sure the mask is initialized first */
1255 if (unlikely(!lowest_mask))
1256 return -1;
1257
1258 if (task->rt.nr_cpus_allowed == 1)
1259 return -1; /* No other targets possible */
1260
1261 if (!cpupri_find(&task_rq(task)->rd->cpupri, task, lowest_mask))
1262 return -1; /* No targets found */
1263
1264 /*
1265 * At this point we have built a mask of cpus representing the
1266 * lowest priority tasks in the system. Now we want to elect
1267 * the best one based on our affinity and topology.
1268 *
1269 * We prioritize the last cpu that the task executed on since
1270 * it is most likely cache-hot in that location.
1271 */
1272 if (cpumask_test_cpu(cpu, lowest_mask))
1273 return cpu;
1274
1275 /*
1276 * Otherwise, we consult the sched_domains span maps to figure
1277 * out which cpu is logically closest to our hot cache data.
1278 */
1279 if (!cpumask_test_cpu(this_cpu, lowest_mask))
1280 this_cpu = -1; /* Skip this_cpu opt if not among lowest */
1281
1282 rcu_read_lock();
1283 for_each_domain(cpu, sd) {
1284 if (sd->flags & SD_WAKE_AFFINE) {
1285 int best_cpu;
1286
1287 /*
1288 * "this_cpu" is cheaper to preempt than a
1289 * remote processor.
1290 */
1291 if (this_cpu != -1 &&
1292 cpumask_test_cpu(this_cpu, sched_domain_span(sd))) {
1293 rcu_read_unlock();
1294 return this_cpu;
1295 }
1296
1297 best_cpu = cpumask_first_and(lowest_mask,
1298 sched_domain_span(sd));
1299 if (best_cpu < nr_cpu_ids) {
1300 rcu_read_unlock();
1301 return best_cpu;
1302 }
1303 }
1304 }
1305 rcu_read_unlock();
1306
1307 /*
1308 * And finally, if there were no matches within the domains
1309 * just give the caller *something* to work with from the compatible
1310 * locations.
1311 */
1312 if (this_cpu != -1)
1313 return this_cpu;
1314
1315 cpu = cpumask_any(lowest_mask);
1316 if (cpu < nr_cpu_ids)
1317 return cpu;
1318 return -1;
1319}
1320
1321/* Will lock the rq it finds */
1322static struct rq *find_lock_lowest_rq(struct task_struct *task, struct rq *rq)
1323{
1324 struct rq *lowest_rq = NULL;
1325 int tries;
1326 int cpu;
1327
1328 for (tries = 0; tries < RT_MAX_TRIES; tries++) {
1329 cpu = find_lowest_rq(task);
1330
1331 if ((cpu == -1) || (cpu == rq->cpu))
1332 break;
1333
1334 lowest_rq = cpu_rq(cpu);
1335
1336 /* if the prio of this runqueue changed, try again */
1337 if (double_lock_balance(rq, lowest_rq)) {
1338 /*
1339 * We had to unlock the run queue. In
1340 * the mean time, task could have
1341 * migrated already or had its affinity changed.
1342 * Also make sure that it wasn't scheduled on its rq.
1343 */
1344 if (unlikely(task_rq(task) != rq ||
1345 !cpumask_test_cpu(lowest_rq->cpu,
1346 &task->cpus_allowed) ||
1347 task_running(rq, task) ||
1348 !task->on_rq)) {
1349
1350 raw_spin_unlock(&lowest_rq->lock);
1351 lowest_rq = NULL;
1352 break;
1353 }
1354 }
1355
1356 /* If this rq is still suitable use it. */
1357 if (lowest_rq->rt.highest_prio.curr > task->prio)
1358 break;
1359
1360 /* try again */
1361 double_unlock_balance(rq, lowest_rq);
1362 lowest_rq = NULL;
1363 }
1364
1365 return lowest_rq;
1366}
1367
1368static struct task_struct *pick_next_pushable_task(struct rq *rq)
1369{
1370 struct task_struct *p;
1371
1372 if (!has_pushable_tasks(rq))
1373 return NULL;
1374
1375 p = plist_first_entry(&rq->rt.pushable_tasks,
1376 struct task_struct, pushable_tasks);
1377
1378 BUG_ON(rq->cpu != task_cpu(p));
1379 BUG_ON(task_current(rq, p));
1380 BUG_ON(p->rt.nr_cpus_allowed <= 1);
1381
1382 BUG_ON(!p->on_rq);
1383 BUG_ON(!rt_task(p));
1384
1385 return p;
1386}
1387
1388/*
1389 * If the current CPU has more than one RT task, see if the non
1390 * running task can migrate over to a CPU that is running a task
1391 * of lesser priority.
1392 */
1393static int push_rt_task(struct rq *rq)
1394{
1395 struct task_struct *next_task;
1396 struct rq *lowest_rq;
1397
1398 if (!rq->rt.overloaded)
1399 return 0;
1400
1401 next_task = pick_next_pushable_task(rq);
1402 if (!next_task)
1403 return 0;
1404
1405retry:
1406 if (unlikely(next_task == rq->curr)) {
1407 WARN_ON(1);
1408 return 0;
1409 }
1410
1411 /*
1412 * It's possible that the next_task slipped in of
1413 * higher priority than current. If that's the case
1414 * just reschedule current.
1415 */
1416 if (unlikely(next_task->prio < rq->curr->prio)) {
1417 resched_task(rq->curr);
1418 return 0;
1419 }
1420
1421 /* We might release rq lock */
1422 get_task_struct(next_task);
1423
1424 /* find_lock_lowest_rq locks the rq if found */
1425 lowest_rq = find_lock_lowest_rq(next_task, rq);
1426 if (!lowest_rq) {
1427 struct task_struct *task;
1428 /*
1429 * find lock_lowest_rq releases rq->lock
1430 * so it is possible that next_task has migrated.
1431 *
1432 * We need to make sure that the task is still on the same
1433 * run-queue and is also still the next task eligible for
1434 * pushing.
1435 */
1436 task = pick_next_pushable_task(rq);
1437 if (task_cpu(next_task) == rq->cpu && task == next_task) {
1438 /*
1439 * If we get here, the task hasn't moved at all, but
1440 * it has failed to push. We will not try again,
1441 * since the other cpus will pull from us when they
1442 * are ready.
1443 */
1444 dequeue_pushable_task(rq, next_task);
1445 goto out;
1446 }
1447
1448 if (!task)
1449 /* No more tasks, just exit */
1450 goto out;
1451
1452 /*
1453 * Something has shifted, try again.
1454 */
1455 put_task_struct(next_task);
1456 next_task = task;
1457 goto retry;
1458 }
1459
1460 deactivate_task(rq, next_task, 0);
1461 set_task_cpu(next_task, lowest_rq->cpu);
1462 activate_task(lowest_rq, next_task, 0);
1463
1464 resched_task(lowest_rq->curr);
1465
1466 double_unlock_balance(rq, lowest_rq);
1467
1468out:
1469 put_task_struct(next_task);
1470
1471 return 1;
1472}
1473
1474static void push_rt_tasks(struct rq *rq)
1475{
1476 /* push_rt_task will return true if it moved an RT */
1477 while (push_rt_task(rq))
1478 ;
1479}
1480
1481static int pull_rt_task(struct rq *this_rq)
1482{
1483 int this_cpu = this_rq->cpu, ret = 0, cpu;
1484 struct task_struct *p;
1485 struct rq *src_rq;
1486
1487 if (likely(!rt_overloaded(this_rq)))
1488 return 0;
1489
1490 for_each_cpu(cpu, this_rq->rd->rto_mask) {
1491 if (this_cpu == cpu)
1492 continue;
1493
1494 src_rq = cpu_rq(cpu);
1495
1496 /*
1497 * Don't bother taking the src_rq->lock if the next highest
1498 * task is known to be lower-priority than our current task.
1499 * This may look racy, but if this value is about to go
1500 * logically higher, the src_rq will push this task away.
1501 * And if its going logically lower, we do not care
1502 */
1503 if (src_rq->rt.highest_prio.next >=
1504 this_rq->rt.highest_prio.curr)
1505 continue;
1506
1507 /*
1508 * We can potentially drop this_rq's lock in
1509 * double_lock_balance, and another CPU could
1510 * alter this_rq
1511 */
1512 double_lock_balance(this_rq, src_rq);
1513
1514 /*
1515 * Are there still pullable RT tasks?
1516 */
1517 if (src_rq->rt.rt_nr_running <= 1)
1518 goto skip;
1519
1520 p = pick_next_highest_task_rt(src_rq, this_cpu);
1521
1522 /*
1523 * Do we have an RT task that preempts
1524 * the to-be-scheduled task?
1525 */
1526 if (p && (p->prio < this_rq->rt.highest_prio.curr)) {
1527 WARN_ON(p == src_rq->curr);
1528 WARN_ON(!p->on_rq);
1529
1530 /*
1531 * There's a chance that p is higher in priority
1532 * than what's currently running on its cpu.
1533 * This is just that p is wakeing up and hasn't
1534 * had a chance to schedule. We only pull
1535 * p if it is lower in priority than the
1536 * current task on the run queue
1537 */
1538 if (p->prio < src_rq->curr->prio)
1539 goto skip;
1540
1541 ret = 1;
1542
1543 deactivate_task(src_rq, p, 0);
1544 set_task_cpu(p, this_cpu);
1545 activate_task(this_rq, p, 0);
1546 /*
1547 * We continue with the search, just in
1548 * case there's an even higher prio task
1549 * in another runqueue. (low likelihood
1550 * but possible)
1551 */
1552 }
1553skip:
1554 double_unlock_balance(this_rq, src_rq);
1555 }
1556
1557 return ret;
1558}
1559
1560static void pre_schedule_rt(struct rq *rq, struct task_struct *prev)
1561{
1562 /* Try to pull RT tasks here if we lower this rq's prio */
1563 if (rq->rt.highest_prio.curr > prev->prio)
1564 pull_rt_task(rq);
1565}
1566
1567static void post_schedule_rt(struct rq *rq)
1568{
1569 push_rt_tasks(rq);
1570}
1571
1572/*
1573 * If we are not running and we are not going to reschedule soon, we should
1574 * try to push tasks away now
1575 */
1576static void task_woken_rt(struct rq *rq, struct task_struct *p)
1577{
1578 if (!task_running(rq, p) &&
1579 !test_tsk_need_resched(rq->curr) &&
1580 has_pushable_tasks(rq) &&
1581 p->rt.nr_cpus_allowed > 1 &&
1582 rt_task(rq->curr) &&
1583 (rq->curr->rt.nr_cpus_allowed < 2 ||
1584 rq->curr->prio <= p->prio))
1585 push_rt_tasks(rq);
1586}
1587
1588static void set_cpus_allowed_rt(struct task_struct *p,
1589 const struct cpumask *new_mask)
1590{
1591 int weight = cpumask_weight(new_mask);
1592
1593 BUG_ON(!rt_task(p));
1594
1595 /*
1596 * Update the migration status of the RQ if we have an RT task
1597 * which is running AND changing its weight value.
1598 */
1599 if (p->on_rq && (weight != p->rt.nr_cpus_allowed)) {
1600 struct rq *rq = task_rq(p);
1601
1602 if (!task_current(rq, p)) {
1603 /*
1604 * Make sure we dequeue this task from the pushable list
1605 * before going further. It will either remain off of
1606 * the list because we are no longer pushable, or it
1607 * will be requeued.
1608 */
1609 if (p->rt.nr_cpus_allowed > 1)
1610 dequeue_pushable_task(rq, p);
1611
1612 /*
1613 * Requeue if our weight is changing and still > 1
1614 */
1615 if (weight > 1)
1616 enqueue_pushable_task(rq, p);
1617
1618 }
1619
1620 if ((p->rt.nr_cpus_allowed <= 1) && (weight > 1)) {
1621 rq->rt.rt_nr_migratory++;
1622 } else if ((p->rt.nr_cpus_allowed > 1) && (weight <= 1)) {
1623 BUG_ON(!rq->rt.rt_nr_migratory);
1624 rq->rt.rt_nr_migratory--;
1625 }
1626
1627 update_rt_migration(&rq->rt);
1628 }
1629
1630 cpumask_copy(&p->cpus_allowed, new_mask);
1631 p->rt.nr_cpus_allowed = weight;
1632}
1633
1634/* Assumes rq->lock is held */
1635static void rq_online_rt(struct rq *rq)
1636{
1637 if (rq->rt.overloaded)
1638 rt_set_overload(rq);
1639
1640 __enable_runtime(rq);
1641
1642 cpupri_set(&rq->rd->cpupri, rq->cpu, rq->rt.highest_prio.curr);
1643}
1644
1645/* Assumes rq->lock is held */
1646static void rq_offline_rt(struct rq *rq)
1647{
1648 if (rq->rt.overloaded)
1649 rt_clear_overload(rq);
1650
1651 __disable_runtime(rq);
1652
1653 cpupri_set(&rq->rd->cpupri, rq->cpu, CPUPRI_INVALID);
1654}
1655
1656/*
1657 * When switch from the rt queue, we bring ourselves to a position
1658 * that we might want to pull RT tasks from other runqueues.
1659 */
1660static void switched_from_rt(struct rq *rq, struct task_struct *p)
1661{
1662 /*
1663 * If there are other RT tasks then we will reschedule
1664 * and the scheduling of the other RT tasks will handle
1665 * the balancing. But if we are the last RT task
1666 * we may need to handle the pulling of RT tasks
1667 * now.
1668 */
1669 if (p->on_rq && !rq->rt.rt_nr_running)
1670 pull_rt_task(rq);
1671}
1672
1673static inline void init_sched_rt_class(void)
1674{
1675 unsigned int i;
1676
1677 for_each_possible_cpu(i)
1678 zalloc_cpumask_var_node(&per_cpu(local_cpu_mask, i),
1679 GFP_KERNEL, cpu_to_node(i));
1680}
1681#endif /* CONFIG_SMP */
1682
1683/*
1684 * When switching a task to RT, we may overload the runqueue
1685 * with RT tasks. In this case we try to push them off to
1686 * other runqueues.
1687 */
1688static void switched_to_rt(struct rq *rq, struct task_struct *p)
1689{
1690 int check_resched = 1;
1691
1692 /*
1693 * If we are already running, then there's nothing
1694 * that needs to be done. But if we are not running
1695 * we may need to preempt the current running task.
1696 * If that current running task is also an RT task
1697 * then see if we can move to another run queue.
1698 */
1699 if (p->on_rq && rq->curr != p) {
1700#ifdef CONFIG_SMP
1701 if (rq->rt.overloaded && push_rt_task(rq) &&
1702 /* Don't resched if we changed runqueues */
1703 rq != task_rq(p))
1704 check_resched = 0;
1705#endif /* CONFIG_SMP */
1706 if (check_resched && p->prio < rq->curr->prio)
1707 resched_task(rq->curr);
1708 }
1709}
1710
1711/*
1712 * Priority of the task has changed. This may cause
1713 * us to initiate a push or pull.
1714 */
1715static void
1716prio_changed_rt(struct rq *rq, struct task_struct *p, int oldprio)
1717{
1718 if (!p->on_rq)
1719 return;
1720
1721 if (rq->curr == p) {
1722#ifdef CONFIG_SMP
1723 /*
1724 * If our priority decreases while running, we
1725 * may need to pull tasks to this runqueue.
1726 */
1727 if (oldprio < p->prio)
1728 pull_rt_task(rq);
1729 /*
1730 * If there's a higher priority task waiting to run
1731 * then reschedule. Note, the above pull_rt_task
1732 * can release the rq lock and p could migrate.
1733 * Only reschedule if p is still on the same runqueue.
1734 */
1735 if (p->prio > rq->rt.highest_prio.curr && rq->curr == p)
1736 resched_task(p);
1737#else
1738 /* For UP simply resched on drop of prio */
1739 if (oldprio < p->prio)
1740 resched_task(p);
1741#endif /* CONFIG_SMP */
1742 } else {
1743 /*
1744 * This task is not running, but if it is
1745 * greater than the current running task
1746 * then reschedule.
1747 */
1748 if (p->prio < rq->curr->prio)
1749 resched_task(rq->curr);
1750 }
1751}
1752
1753static void watchdog(struct rq *rq, struct task_struct *p)
1754{
1755 unsigned long soft, hard;
1756
1757 /* max may change after cur was read, this will be fixed next tick */
1758 soft = task_rlimit(p, RLIMIT_RTTIME);
1759 hard = task_rlimit_max(p, RLIMIT_RTTIME);
1760
1761 if (soft != RLIM_INFINITY) {
1762 unsigned long next;
1763
1764 p->rt.timeout++;
1765 next = DIV_ROUND_UP(min(soft, hard), USEC_PER_SEC/HZ);
1766 if (p->rt.timeout > next)
1767 p->cputime_expires.sched_exp = p->se.sum_exec_runtime;
1768 }
1769}
1770
1771static void task_tick_rt(struct rq *rq, struct task_struct *p, int queued)
1772{
1773 update_curr_rt(rq);
1774
1775 watchdog(rq, p);
1776
1777 /*
1778 * RR tasks need a special form of timeslice management.
1779 * FIFO tasks have no timeslices.
1780 */
1781 if (p->policy != SCHED_RR)
1782 return;
1783
1784 if (--p->rt.time_slice)
1785 return;
1786
1787 p->rt.time_slice = DEF_TIMESLICE;
1788
1789 /*
1790 * Requeue to the end of queue if we are not the only element
1791 * on the queue:
1792 */
1793 if (p->rt.run_list.prev != p->rt.run_list.next) {
1794 requeue_task_rt(rq, p, 0);
1795 set_tsk_need_resched(p);
1796 }
1797}
1798
1799static void set_curr_task_rt(struct rq *rq)
1800{
1801 struct task_struct *p = rq->curr;
1802
1803 p->se.exec_start = rq->clock_task;
1804
1805 /* The running task is never eligible for pushing */
1806 dequeue_pushable_task(rq, p);
1807}
1808
1809static unsigned int get_rr_interval_rt(struct rq *rq, struct task_struct *task)
1810{
1811 /*
1812 * Time slice is 0 for SCHED_FIFO tasks
1813 */
1814 if (task->policy == SCHED_RR)
1815 return DEF_TIMESLICE;
1816 else
1817 return 0;
1818}
1819
1820static const struct sched_class rt_sched_class = {
1821 .next = &fair_sched_class,
1822 .enqueue_task = enqueue_task_rt,
1823 .dequeue_task = dequeue_task_rt,
1824 .yield_task = yield_task_rt,
1825
1826 .check_preempt_curr = check_preempt_curr_rt,
1827
1828 .pick_next_task = pick_next_task_rt,
1829 .put_prev_task = put_prev_task_rt,
1830
1831#ifdef CONFIG_SMP
1832 .select_task_rq = select_task_rq_rt,
1833
1834 .set_cpus_allowed = set_cpus_allowed_rt,
1835 .rq_online = rq_online_rt,
1836 .rq_offline = rq_offline_rt,
1837 .pre_schedule = pre_schedule_rt,
1838 .post_schedule = post_schedule_rt,
1839 .task_woken = task_woken_rt,
1840 .switched_from = switched_from_rt,
1841#endif
1842
1843 .set_curr_task = set_curr_task_rt,
1844 .task_tick = task_tick_rt,
1845
1846 .get_rr_interval = get_rr_interval_rt,
1847
1848 .prio_changed = prio_changed_rt,
1849 .switched_to = switched_to_rt,
1850};
1851
1852#ifdef CONFIG_SCHED_DEBUG
1853extern void print_rt_rq(struct seq_file *m, int cpu, struct rt_rq *rt_rq);
1854
1855static void print_rt_stats(struct seq_file *m, int cpu)
1856{
1857 rt_rq_iter_t iter;
1858 struct rt_rq *rt_rq;
1859
1860 rcu_read_lock();
1861 for_each_rt_rq(rt_rq, iter, cpu_rq(cpu))
1862 print_rt_rq(m, cpu, rt_rq);
1863 rcu_read_unlock();
1864}
1865#endif /* CONFIG_SCHED_DEBUG */
1866
diff --git a/kernel/sched_stats.h b/kernel/sched_stats.h
new file mode 100644
index 00000000000..331e01bcd02
--- /dev/null
+++ b/kernel/sched_stats.h
@@ -0,0 +1,336 @@
1
2#ifdef CONFIG_SCHEDSTATS
3/*
4 * bump this up when changing the output format or the meaning of an existing
5 * format, so that tools can adapt (or abort)
6 */
7#define SCHEDSTAT_VERSION 15
8
9static int show_schedstat(struct seq_file *seq, void *v)
10{
11 int cpu;
12 int mask_len = DIV_ROUND_UP(NR_CPUS, 32) * 9;
13 char *mask_str = kmalloc(mask_len, GFP_KERNEL);
14
15 if (mask_str == NULL)
16 return -ENOMEM;
17
18 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
19 seq_printf(seq, "timestamp %lu\n", jiffies);
20 for_each_online_cpu(cpu) {
21 struct rq *rq = cpu_rq(cpu);
22#ifdef CONFIG_SMP
23 struct sched_domain *sd;
24 int dcount = 0;
25#endif
26
27 /* runqueue-specific stats */
28 seq_printf(seq,
29 "cpu%d %u %u %u %u %u %u %llu %llu %lu",
30 cpu, rq->yld_count,
31 rq->sched_switch, rq->sched_count, rq->sched_goidle,
32 rq->ttwu_count, rq->ttwu_local,
33 rq->rq_cpu_time,
34 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcount);
35
36 seq_printf(seq, "\n");
37
38#ifdef CONFIG_SMP
39 /* domain-specific stats */
40 rcu_read_lock();
41 for_each_domain(cpu, sd) {
42 enum cpu_idle_type itype;
43
44 cpumask_scnprintf(mask_str, mask_len,
45 sched_domain_span(sd));
46 seq_printf(seq, "domain%d %s", dcount++, mask_str);
47 for (itype = CPU_IDLE; itype < CPU_MAX_IDLE_TYPES;
48 itype++) {
49 seq_printf(seq, " %u %u %u %u %u %u %u %u",
50 sd->lb_count[itype],
51 sd->lb_balanced[itype],
52 sd->lb_failed[itype],
53 sd->lb_imbalance[itype],
54 sd->lb_gained[itype],
55 sd->lb_hot_gained[itype],
56 sd->lb_nobusyq[itype],
57 sd->lb_nobusyg[itype]);
58 }
59 seq_printf(seq,
60 " %u %u %u %u %u %u %u %u %u %u %u %u\n",
61 sd->alb_count, sd->alb_failed, sd->alb_pushed,
62 sd->sbe_count, sd->sbe_balanced, sd->sbe_pushed,
63 sd->sbf_count, sd->sbf_balanced, sd->sbf_pushed,
64 sd->ttwu_wake_remote, sd->ttwu_move_affine,
65 sd->ttwu_move_balance);
66 }
67 rcu_read_unlock();
68#endif
69 }
70 kfree(mask_str);
71 return 0;
72}
73
74static int schedstat_open(struct inode *inode, struct file *file)
75{
76 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
77 char *buf = kmalloc(size, GFP_KERNEL);
78 struct seq_file *m;
79 int res;
80
81 if (!buf)
82 return -ENOMEM;
83 res = single_open(file, show_schedstat, NULL);
84 if (!res) {
85 m = file->private_data;
86 m->buf = buf;
87 m->size = size;
88 } else
89 kfree(buf);
90 return res;
91}
92
93static const struct file_operations proc_schedstat_operations = {
94 .open = schedstat_open,
95 .read = seq_read,
96 .llseek = seq_lseek,
97 .release = single_release,
98};
99
100static int __init proc_schedstat_init(void)
101{
102 proc_create("schedstat", 0, NULL, &proc_schedstat_operations);
103 return 0;
104}
105module_init(proc_schedstat_init);
106
107/*
108 * Expects runqueue lock to be held for atomicity of update
109 */
110static inline void
111rq_sched_info_arrive(struct rq *rq, unsigned long long delta)
112{
113 if (rq) {
114 rq->rq_sched_info.run_delay += delta;
115 rq->rq_sched_info.pcount++;
116 }
117}
118
119/*
120 * Expects runqueue lock to be held for atomicity of update
121 */
122static inline void
123rq_sched_info_depart(struct rq *rq, unsigned long long delta)
124{
125 if (rq)
126 rq->rq_cpu_time += delta;
127}
128
129static inline void
130rq_sched_info_dequeued(struct rq *rq, unsigned long long delta)
131{
132 if (rq)
133 rq->rq_sched_info.run_delay += delta;
134}
135# define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
136# define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
137# define schedstat_set(var, val) do { var = (val); } while (0)
138#else /* !CONFIG_SCHEDSTATS */
139static inline void
140rq_sched_info_arrive(struct rq *rq, unsigned long long delta)
141{}
142static inline void
143rq_sched_info_dequeued(struct rq *rq, unsigned long long delta)
144{}
145static inline void
146rq_sched_info_depart(struct rq *rq, unsigned long long delta)
147{}
148# define schedstat_inc(rq, field) do { } while (0)
149# define schedstat_add(rq, field, amt) do { } while (0)
150# define schedstat_set(var, val) do { } while (0)
151#endif
152
153#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
154static inline void sched_info_reset_dequeued(struct task_struct *t)
155{
156 t->sched_info.last_queued = 0;
157}
158
159/*
160 * We are interested in knowing how long it was from the *first* time a
161 * task was queued to the time that it finally hit a cpu, we call this routine
162 * from dequeue_task() to account for possible rq->clock skew across cpus. The
163 * delta taken on each cpu would annul the skew.
164 */
165static inline void sched_info_dequeued(struct task_struct *t)
166{
167 unsigned long long now = task_rq(t)->clock, delta = 0;
168
169 if (unlikely(sched_info_on()))
170 if (t->sched_info.last_queued)
171 delta = now - t->sched_info.last_queued;
172 sched_info_reset_dequeued(t);
173 t->sched_info.run_delay += delta;
174
175 rq_sched_info_dequeued(task_rq(t), delta);
176}
177
178/*
179 * Called when a task finally hits the cpu. We can now calculate how
180 * long it was waiting to run. We also note when it began so that we
181 * can keep stats on how long its timeslice is.
182 */
183static void sched_info_arrive(struct task_struct *t)
184{
185 unsigned long long now = task_rq(t)->clock, delta = 0;
186
187 if (t->sched_info.last_queued)
188 delta = now - t->sched_info.last_queued;
189 sched_info_reset_dequeued(t);
190 t->sched_info.run_delay += delta;
191 t->sched_info.last_arrival = now;
192 t->sched_info.pcount++;
193
194 rq_sched_info_arrive(task_rq(t), delta);
195}
196
197/*
198 * This function is only called from enqueue_task(), but also only updates
199 * the timestamp if it is already not set. It's assumed that
200 * sched_info_dequeued() will clear that stamp when appropriate.
201 */
202static inline void sched_info_queued(struct task_struct *t)
203{
204 if (unlikely(sched_info_on()))
205 if (!t->sched_info.last_queued)
206 t->sched_info.last_queued = task_rq(t)->clock;
207}
208
209/*
210 * Called when a process ceases being the active-running process, either
211 * voluntarily or involuntarily. Now we can calculate how long we ran.
212 * Also, if the process is still in the TASK_RUNNING state, call
213 * sched_info_queued() to mark that it has now again started waiting on
214 * the runqueue.
215 */
216static inline void sched_info_depart(struct task_struct *t)
217{
218 unsigned long long delta = task_rq(t)->clock -
219 t->sched_info.last_arrival;
220
221 rq_sched_info_depart(task_rq(t), delta);
222
223 if (t->state == TASK_RUNNING)
224 sched_info_queued(t);
225}
226
227/*
228 * Called when tasks are switched involuntarily due, typically, to expiring
229 * their time slice. (This may also be called when switching to or from
230 * the idle task.) We are only called when prev != next.
231 */
232static inline void
233__sched_info_switch(struct task_struct *prev, struct task_struct *next)
234{
235 struct rq *rq = task_rq(prev);
236
237 /*
238 * prev now departs the cpu. It's not interesting to record
239 * stats about how efficient we were at scheduling the idle
240 * process, however.
241 */
242 if (prev != rq->idle)
243 sched_info_depart(prev);
244
245 if (next != rq->idle)
246 sched_info_arrive(next);
247}
248static inline void
249sched_info_switch(struct task_struct *prev, struct task_struct *next)
250{
251 if (unlikely(sched_info_on()))
252 __sched_info_switch(prev, next);
253}
254#else
255#define sched_info_queued(t) do { } while (0)
256#define sched_info_reset_dequeued(t) do { } while (0)
257#define sched_info_dequeued(t) do { } while (0)
258#define sched_info_switch(t, next) do { } while (0)
259#endif /* CONFIG_SCHEDSTATS || CONFIG_TASK_DELAY_ACCT */
260
261/*
262 * The following are functions that support scheduler-internal time accounting.
263 * These functions are generally called at the timer tick. None of this depends
264 * on CONFIG_SCHEDSTATS.
265 */
266
267/**
268 * account_group_user_time - Maintain utime for a thread group.
269 *
270 * @tsk: Pointer to task structure.
271 * @cputime: Time value by which to increment the utime field of the
272 * thread_group_cputime structure.
273 *
274 * If thread group time is being maintained, get the structure for the
275 * running CPU and update the utime field there.
276 */
277static inline void account_group_user_time(struct task_struct *tsk,
278 cputime_t cputime)
279{
280 struct thread_group_cputimer *cputimer = &tsk->signal->cputimer;
281
282 if (!cputimer->running)
283 return;
284
285 spin_lock(&cputimer->lock);
286 cputimer->cputime.utime =
287 cputime_add(cputimer->cputime.utime, cputime);
288 spin_unlock(&cputimer->lock);
289}
290
291/**
292 * account_group_system_time - Maintain stime for a thread group.
293 *
294 * @tsk: Pointer to task structure.
295 * @cputime: Time value by which to increment the stime field of the
296 * thread_group_cputime structure.
297 *
298 * If thread group time is being maintained, get the structure for the
299 * running CPU and update the stime field there.
300 */
301static inline void account_group_system_time(struct task_struct *tsk,
302 cputime_t cputime)
303{
304 struct thread_group_cputimer *cputimer = &tsk->signal->cputimer;
305
306 if (!cputimer->running)
307 return;
308
309 spin_lock(&cputimer->lock);
310 cputimer->cputime.stime =
311 cputime_add(cputimer->cputime.stime, cputime);
312 spin_unlock(&cputimer->lock);
313}
314
315/**
316 * account_group_exec_runtime - Maintain exec runtime for a thread group.
317 *
318 * @tsk: Pointer to task structure.
319 * @ns: Time value by which to increment the sum_exec_runtime field
320 * of the thread_group_cputime structure.
321 *
322 * If thread group time is being maintained, get the structure for the
323 * running CPU and update the sum_exec_runtime field there.
324 */
325static inline void account_group_exec_runtime(struct task_struct *tsk,
326 unsigned long long ns)
327{
328 struct thread_group_cputimer *cputimer = &tsk->signal->cputimer;
329
330 if (!cputimer->running)
331 return;
332
333 spin_lock(&cputimer->lock);
334 cputimer->cputime.sum_exec_runtime += ns;
335 spin_unlock(&cputimer->lock);
336}
diff --git a/kernel/sched_stoptask.c b/kernel/sched_stoptask.c
new file mode 100644
index 00000000000..6f437632afa
--- /dev/null
+++ b/kernel/sched_stoptask.c
@@ -0,0 +1,104 @@
1/*
2 * stop-task scheduling class.
3 *
4 * The stop task is the highest priority task in the system, it preempts
5 * everything and will be preempted by nothing.
6 *
7 * See kernel/stop_machine.c
8 */
9
10#ifdef CONFIG_SMP
11static int
12select_task_rq_stop(struct task_struct *p, int sd_flag, int flags)
13{
14 return task_cpu(p); /* stop tasks as never migrate */
15}
16#endif /* CONFIG_SMP */
17
18static void
19check_preempt_curr_stop(struct rq *rq, struct task_struct *p, int flags)
20{
21 /* we're never preempted */
22}
23
24static struct task_struct *pick_next_task_stop(struct rq *rq)
25{
26 struct task_struct *stop = rq->stop;
27
28 if (stop && stop->on_rq)
29 return stop;
30
31 return NULL;
32}
33
34static void
35enqueue_task_stop(struct rq *rq, struct task_struct *p, int flags)
36{
37}
38
39static void
40dequeue_task_stop(struct rq *rq, struct task_struct *p, int flags)
41{
42}
43
44static void yield_task_stop(struct rq *rq)
45{
46 BUG(); /* the stop task should never yield, its pointless. */
47}
48
49static void put_prev_task_stop(struct rq *rq, struct task_struct *prev)
50{
51}
52
53static void task_tick_stop(struct rq *rq, struct task_struct *curr, int queued)
54{
55}
56
57static void set_curr_task_stop(struct rq *rq)
58{
59}
60
61static void switched_to_stop(struct rq *rq, struct task_struct *p)
62{
63 BUG(); /* its impossible to change to this class */
64}
65
66static void
67prio_changed_stop(struct rq *rq, struct task_struct *p, int oldprio)
68{
69 BUG(); /* how!?, what priority? */
70}
71
72static unsigned int
73get_rr_interval_stop(struct rq *rq, struct task_struct *task)
74{
75 return 0;
76}
77
78/*
79 * Simple, special scheduling class for the per-CPU stop tasks:
80 */
81static const struct sched_class stop_sched_class = {
82 .next = &rt_sched_class,
83
84 .enqueue_task = enqueue_task_stop,
85 .dequeue_task = dequeue_task_stop,
86 .yield_task = yield_task_stop,
87
88 .check_preempt_curr = check_preempt_curr_stop,
89
90 .pick_next_task = pick_next_task_stop,
91 .put_prev_task = put_prev_task_stop,
92
93#ifdef CONFIG_SMP
94 .select_task_rq = select_task_rq_stop,
95#endif
96
97 .set_curr_task = set_curr_task_stop,
98 .task_tick = task_tick_stop,
99
100 .get_rr_interval = get_rr_interval_stop,
101
102 .prio_changed = prio_changed_stop,
103 .switched_to = switched_to_stop,
104};
diff --git a/kernel/sysctl_check.c b/kernel/sysctl_check.c
new file mode 100644
index 00000000000..362da653813
--- /dev/null
+++ b/kernel/sysctl_check.c
@@ -0,0 +1,160 @@
1#include <linux/stat.h>
2#include <linux/sysctl.h>
3#include "../fs/xfs/xfs_sysctl.h"
4#include <linux/sunrpc/debug.h>
5#include <linux/string.h>
6#include <net/ip_vs.h>
7
8
9static int sysctl_depth(struct ctl_table *table)
10{
11 struct ctl_table *tmp;
12 int depth;
13
14 depth = 0;
15 for (tmp = table; tmp->parent; tmp = tmp->parent)
16 depth++;
17
18 return depth;
19}
20
21static struct ctl_table *sysctl_parent(struct ctl_table *table, int n)
22{
23 int i;
24
25 for (i = 0; table && i < n; i++)
26 table = table->parent;
27
28 return table;
29}
30
31
32static void sysctl_print_path(struct ctl_table *table)
33{
34 struct ctl_table *tmp;
35 int depth, i;
36 depth = sysctl_depth(table);
37 if (table->procname) {
38 for (i = depth; i >= 0; i--) {
39 tmp = sysctl_parent(table, i);
40 printk("/%s", tmp->procname?tmp->procname:"");
41 }
42 }
43 printk(" ");
44}
45
46static struct ctl_table *sysctl_check_lookup(struct nsproxy *namespaces,
47 struct ctl_table *table)
48{
49 struct ctl_table_header *head;
50 struct ctl_table *ref, *test;
51 int depth, cur_depth;
52
53 depth = sysctl_depth(table);
54
55 for (head = __sysctl_head_next(namespaces, NULL); head;
56 head = __sysctl_head_next(namespaces, head)) {
57 cur_depth = depth;
58 ref = head->ctl_table;
59repeat:
60 test = sysctl_parent(table, cur_depth);
61 for (; ref->procname; ref++) {
62 int match = 0;
63 if (cur_depth && !ref->child)
64 continue;
65
66 if (test->procname && ref->procname &&
67 (strcmp(test->procname, ref->procname) == 0))
68 match++;
69
70 if (match) {
71 if (cur_depth != 0) {
72 cur_depth--;
73 ref = ref->child;
74 goto repeat;
75 }
76 goto out;
77 }
78 }
79 }
80 ref = NULL;
81out:
82 sysctl_head_finish(head);
83 return ref;
84}
85
86static void set_fail(const char **fail, struct ctl_table *table, const char *str)
87{
88 if (*fail) {
89 printk(KERN_ERR "sysctl table check failed: ");
90 sysctl_print_path(table);
91 printk(" %s\n", *fail);
92 dump_stack();
93 }
94 *fail = str;
95}
96
97static void sysctl_check_leaf(struct nsproxy *namespaces,
98 struct ctl_table *table, const char **fail)
99{
100 struct ctl_table *ref;
101
102 ref = sysctl_check_lookup(namespaces, table);
103 if (ref && (ref != table))
104 set_fail(fail, table, "Sysctl already exists");
105}
106
107int sysctl_check_table(struct nsproxy *namespaces, struct ctl_table *table)
108{
109 int error = 0;
110 for (; table->procname; table++) {
111 const char *fail = NULL;
112
113 if (table->parent) {
114 if (!table->parent->procname)
115 set_fail(&fail, table, "Parent without procname");
116 }
117 if (table->child) {
118 if (table->data)
119 set_fail(&fail, table, "Directory with data?");
120 if (table->maxlen)
121 set_fail(&fail, table, "Directory with maxlen?");
122 if ((table->mode & (S_IRUGO|S_IXUGO)) != table->mode)
123 set_fail(&fail, table, "Writable sysctl directory");
124 if (table->proc_handler)
125 set_fail(&fail, table, "Directory with proc_handler");
126 if (table->extra1)
127 set_fail(&fail, table, "Directory with extra1");
128 if (table->extra2)
129 set_fail(&fail, table, "Directory with extra2");
130 } else {
131 if ((table->proc_handler == proc_dostring) ||
132 (table->proc_handler == proc_dointvec) ||
133 (table->proc_handler == proc_dointvec_minmax) ||
134 (table->proc_handler == proc_dointvec_jiffies) ||
135 (table->proc_handler == proc_dointvec_userhz_jiffies) ||
136 (table->proc_handler == proc_dointvec_ms_jiffies) ||
137 (table->proc_handler == proc_doulongvec_minmax) ||
138 (table->proc_handler == proc_doulongvec_ms_jiffies_minmax)) {
139 if (!table->data)
140 set_fail(&fail, table, "No data");
141 if (!table->maxlen)
142 set_fail(&fail, table, "No maxlen");
143 }
144#ifdef CONFIG_PROC_SYSCTL
145 if (!table->proc_handler)
146 set_fail(&fail, table, "No proc_handler");
147#endif
148 sysctl_check_leaf(namespaces, table, &fail);
149 }
150 if (table->mode > 0777)
151 set_fail(&fail, table, "bogus .mode");
152 if (fail) {
153 set_fail(&fail, table, NULL);
154 error = -EINVAL;
155 }
156 if (table->child)
157 error |= sysctl_check_table(namespaces, table->child);
158 }
159 return error;
160}
diff --git a/kernel/time/timecompare.c b/kernel/time/timecompare.c
new file mode 100644
index 00000000000..a9ae369925c
--- /dev/null
+++ b/kernel/time/timecompare.c
@@ -0,0 +1,193 @@
1/*
2 * Copyright (C) 2009 Intel Corporation.
3 * Author: Patrick Ohly <patrick.ohly@intel.com>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18 */
19
20#include <linux/timecompare.h>
21#include <linux/module.h>
22#include <linux/slab.h>
23#include <linux/math64.h>
24#include <linux/kernel.h>
25
26/*
27 * fixed point arithmetic scale factor for skew
28 *
29 * Usually one would measure skew in ppb (parts per billion, 1e9), but
30 * using a factor of 2 simplifies the math.
31 */
32#define TIMECOMPARE_SKEW_RESOLUTION (((s64)1)<<30)
33
34ktime_t timecompare_transform(struct timecompare *sync,
35 u64 source_tstamp)
36{
37 u64 nsec;
38
39 nsec = source_tstamp + sync->offset;
40 nsec += (s64)(source_tstamp - sync->last_update) * sync->skew /
41 TIMECOMPARE_SKEW_RESOLUTION;
42
43 return ns_to_ktime(nsec);
44}
45EXPORT_SYMBOL_GPL(timecompare_transform);
46
47int timecompare_offset(struct timecompare *sync,
48 s64 *offset,
49 u64 *source_tstamp)
50{
51 u64 start_source = 0, end_source = 0;
52 struct {
53 s64 offset;
54 s64 duration_target;
55 } buffer[10], sample, *samples;
56 int counter = 0, i;
57 int used;
58 int index;
59 int num_samples = sync->num_samples;
60
61 if (num_samples > ARRAY_SIZE(buffer)) {
62 samples = kmalloc(sizeof(*samples) * num_samples, GFP_ATOMIC);
63 if (!samples) {
64 samples = buffer;
65 num_samples = ARRAY_SIZE(buffer);
66 }
67 } else {
68 samples = buffer;
69 }
70
71 /* run until we have enough valid samples, but do not try forever */
72 i = 0;
73 counter = 0;
74 while (1) {
75 u64 ts;
76 ktime_t start, end;
77
78 start = sync->target();
79 ts = timecounter_read(sync->source);
80 end = sync->target();
81
82 if (!i)
83 start_source = ts;
84
85 /* ignore negative durations */
86 sample.duration_target = ktime_to_ns(ktime_sub(end, start));
87 if (sample.duration_target >= 0) {
88 /*
89 * assume symetric delay to and from source:
90 * average target time corresponds to measured
91 * source time
92 */
93 sample.offset =
94 (ktime_to_ns(end) + ktime_to_ns(start)) / 2 -
95 ts;
96
97 /* simple insertion sort based on duration */
98 index = counter - 1;
99 while (index >= 0) {
100 if (samples[index].duration_target <
101 sample.duration_target)
102 break;
103 samples[index + 1] = samples[index];
104 index--;
105 }
106 samples[index + 1] = sample;
107 counter++;
108 }
109
110 i++;
111 if (counter >= num_samples || i >= 100000) {
112 end_source = ts;
113 break;
114 }
115 }
116
117 *source_tstamp = (end_source + start_source) / 2;
118
119 /* remove outliers by only using 75% of the samples */
120 used = counter * 3 / 4;
121 if (!used)
122 used = counter;
123 if (used) {
124 /* calculate average */
125 s64 off = 0;
126 for (index = 0; index < used; index++)
127 off += samples[index].offset;
128 *offset = div_s64(off, used);
129 }
130
131 if (samples && samples != buffer)
132 kfree(samples);
133
134 return used;
135}
136EXPORT_SYMBOL_GPL(timecompare_offset);
137
138void __timecompare_update(struct timecompare *sync,
139 u64 source_tstamp)
140{
141 s64 offset;
142 u64 average_time;
143
144 if (!timecompare_offset(sync, &offset, &average_time))
145 return;
146
147 if (!sync->last_update) {
148 sync->last_update = average_time;
149 sync->offset = offset;
150 sync->skew = 0;
151 } else {
152 s64 delta_nsec = average_time - sync->last_update;
153
154 /* avoid division by negative or small deltas */
155 if (delta_nsec >= 10000) {
156 s64 delta_offset_nsec = offset - sync->offset;
157 s64 skew; /* delta_offset_nsec *
158 TIMECOMPARE_SKEW_RESOLUTION /
159 delta_nsec */
160 u64 divisor;
161
162 /* div_s64() is limited to 32 bit divisor */
163 skew = delta_offset_nsec * TIMECOMPARE_SKEW_RESOLUTION;
164 divisor = delta_nsec;
165 while (unlikely(divisor >= ((s64)1) << 32)) {
166 /* divide both by 2; beware, right shift
167 of negative value has undefined
168 behavior and can only be used for
169 the positive divisor */
170 skew = div_s64(skew, 2);
171 divisor >>= 1;
172 }
173 skew = div_s64(skew, divisor);
174
175 /*
176 * Calculate new overall skew as 4/16 the
177 * old value and 12/16 the new one. This is
178 * a rather arbitrary tradeoff between
179 * only using the latest measurement (0/16 and
180 * 16/16) and even more weight on past measurements.
181 */
182#define TIMECOMPARE_NEW_SKEW_PER_16 12
183 sync->skew =
184 div_s64((16 - TIMECOMPARE_NEW_SKEW_PER_16) *
185 sync->skew +
186 TIMECOMPARE_NEW_SKEW_PER_16 * skew,
187 16);
188 sync->last_update = average_time;
189 sync->offset = offset;
190 }
191 }
192}
193EXPORT_SYMBOL_GPL(__timecompare_update);
diff --git a/kernel/trace/trace_workqueue.c b/kernel/trace/trace_workqueue.c
new file mode 100644
index 00000000000..209b379a472
--- /dev/null
+++ b/kernel/trace/trace_workqueue.c
@@ -0,0 +1,300 @@
1/*
2 * Workqueue statistical tracer.
3 *
4 * Copyright (C) 2008 Frederic Weisbecker <fweisbec@gmail.com>
5 *
6 */
7
8
9#include <trace/events/workqueue.h>
10#include <linux/list.h>
11#include <linux/percpu.h>
12#include <linux/slab.h>
13#include <linux/kref.h>
14#include "trace_stat.h"
15#include "trace.h"
16
17
18/* A cpu workqueue thread */
19struct cpu_workqueue_stats {
20 struct list_head list;
21 struct kref kref;
22 int cpu;
23 pid_t pid;
24/* Can be inserted from interrupt or user context, need to be atomic */
25 atomic_t inserted;
26/*
27 * Don't need to be atomic, works are serialized in a single workqueue thread
28 * on a single CPU.
29 */
30 unsigned int executed;
31};
32
33/* List of workqueue threads on one cpu */
34struct workqueue_global_stats {
35 struct list_head list;
36 spinlock_t lock;
37};
38
39/* Don't need a global lock because allocated before the workqueues, and
40 * never freed.
41 */
42static DEFINE_PER_CPU(struct workqueue_global_stats, all_workqueue_stat);
43#define workqueue_cpu_stat(cpu) (&per_cpu(all_workqueue_stat, cpu))
44
45static void cpu_workqueue_stat_free(struct kref *kref)
46{
47 kfree(container_of(kref, struct cpu_workqueue_stats, kref));
48}
49
50/* Insertion of a work */
51static void
52probe_workqueue_insertion(void *ignore,
53 struct task_struct *wq_thread,
54 struct work_struct *work)
55{
56 int cpu = cpumask_first(&wq_thread->cpus_allowed);
57 struct cpu_workqueue_stats *node;
58 unsigned long flags;
59
60 spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
61 list_for_each_entry(node, &workqueue_cpu_stat(cpu)->list, list) {
62 if (node->pid == wq_thread->pid) {
63 atomic_inc(&node->inserted);
64 goto found;
65 }
66 }
67 pr_debug("trace_workqueue: entry not found\n");
68found:
69 spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
70}
71
72/* Execution of a work */
73static void
74probe_workqueue_execution(void *ignore,
75 struct task_struct *wq_thread,
76 struct work_struct *work)
77{
78 int cpu = cpumask_first(&wq_thread->cpus_allowed);
79 struct cpu_workqueue_stats *node;
80 unsigned long flags;
81
82 spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
83 list_for_each_entry(node, &workqueue_cpu_stat(cpu)->list, list) {
84 if (node->pid == wq_thread->pid) {
85 node->executed++;
86 goto found;
87 }
88 }
89 pr_debug("trace_workqueue: entry not found\n");
90found:
91 spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
92}
93
94/* Creation of a cpu workqueue thread */
95static void probe_workqueue_creation(void *ignore,
96 struct task_struct *wq_thread, int cpu)
97{
98 struct cpu_workqueue_stats *cws;
99 unsigned long flags;
100
101 WARN_ON(cpu < 0);
102
103 /* Workqueues are sometimes created in atomic context */
104 cws = kzalloc(sizeof(struct cpu_workqueue_stats), GFP_ATOMIC);
105 if (!cws) {
106 pr_warning("trace_workqueue: not enough memory\n");
107 return;
108 }
109 INIT_LIST_HEAD(&cws->list);
110 kref_init(&cws->kref);
111 cws->cpu = cpu;
112 cws->pid = wq_thread->pid;
113
114 spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
115 list_add_tail(&cws->list, &workqueue_cpu_stat(cpu)->list);
116 spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
117}
118
119/* Destruction of a cpu workqueue thread */
120static void
121probe_workqueue_destruction(void *ignore, struct task_struct *wq_thread)
122{
123 /* Workqueue only execute on one cpu */
124 int cpu = cpumask_first(&wq_thread->cpus_allowed);
125 struct cpu_workqueue_stats *node, *next;
126 unsigned long flags;
127
128 spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
129 list_for_each_entry_safe(node, next, &workqueue_cpu_stat(cpu)->list,
130 list) {
131 if (node->pid == wq_thread->pid) {
132 list_del(&node->list);
133 kref_put(&node->kref, cpu_workqueue_stat_free);
134 goto found;
135 }
136 }
137
138 pr_debug("trace_workqueue: don't find workqueue to destroy\n");
139found:
140 spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
141
142}
143
144static struct cpu_workqueue_stats *workqueue_stat_start_cpu(int cpu)
145{
146 unsigned long flags;
147 struct cpu_workqueue_stats *ret = NULL;
148
149
150 spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
151
152 if (!list_empty(&workqueue_cpu_stat(cpu)->list)) {
153 ret = list_entry(workqueue_cpu_stat(cpu)->list.next,
154 struct cpu_workqueue_stats, list);
155 kref_get(&ret->kref);
156 }
157
158 spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
159
160 return ret;
161}
162
163static void *workqueue_stat_start(struct tracer_stat *trace)
164{
165 int cpu;
166 void *ret = NULL;
167
168 for_each_possible_cpu(cpu) {
169 ret = workqueue_stat_start_cpu(cpu);
170 if (ret)
171 return ret;
172 }
173 return NULL;
174}
175
176static void *workqueue_stat_next(void *prev, int idx)
177{
178 struct cpu_workqueue_stats *prev_cws = prev;
179 struct cpu_workqueue_stats *ret;
180 int cpu = prev_cws->cpu;
181 unsigned long flags;
182
183 spin_lock_irqsave(&workqueue_cpu_stat(cpu)->lock, flags);
184 if (list_is_last(&prev_cws->list, &workqueue_cpu_stat(cpu)->list)) {
185 spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
186 do {
187 cpu = cpumask_next(cpu, cpu_possible_mask);
188 if (cpu >= nr_cpu_ids)
189 return NULL;
190 } while (!(ret = workqueue_stat_start_cpu(cpu)));
191 return ret;
192 } else {
193 ret = list_entry(prev_cws->list.next,
194 struct cpu_workqueue_stats, list);
195 kref_get(&ret->kref);
196 }
197 spin_unlock_irqrestore(&workqueue_cpu_stat(cpu)->lock, flags);
198
199 return ret;
200}
201
202static int workqueue_stat_show(struct seq_file *s, void *p)
203{
204 struct cpu_workqueue_stats *cws = p;
205 struct pid *pid;
206 struct task_struct *tsk;
207
208 pid = find_get_pid(cws->pid);
209 if (pid) {
210 tsk = get_pid_task(pid, PIDTYPE_PID);
211 if (tsk) {
212 seq_printf(s, "%3d %6d %6u %s\n", cws->cpu,
213 atomic_read(&cws->inserted), cws->executed,
214 tsk->comm);
215 put_task_struct(tsk);
216 }
217 put_pid(pid);
218 }
219
220 return 0;
221}
222
223static void workqueue_stat_release(void *stat)
224{
225 struct cpu_workqueue_stats *node = stat;
226
227 kref_put(&node->kref, cpu_workqueue_stat_free);
228}
229
230static int workqueue_stat_headers(struct seq_file *s)
231{
232 seq_printf(s, "# CPU INSERTED EXECUTED NAME\n");
233 seq_printf(s, "# | | | |\n");
234 return 0;
235}
236
237struct tracer_stat workqueue_stats __read_mostly = {
238 .name = "workqueues",
239 .stat_start = workqueue_stat_start,
240 .stat_next = workqueue_stat_next,
241 .stat_show = workqueue_stat_show,
242 .stat_release = workqueue_stat_release,
243 .stat_headers = workqueue_stat_headers
244};
245
246
247int __init stat_workqueue_init(void)
248{
249 if (register_stat_tracer(&workqueue_stats)) {
250 pr_warning("Unable to register workqueue stat tracer\n");
251 return 1;
252 }
253
254 return 0;
255}
256fs_initcall(stat_workqueue_init);
257
258/*
259 * Workqueues are created very early, just after pre-smp initcalls.
260 * So we must register our tracepoints at this stage.
261 */
262int __init trace_workqueue_early_init(void)
263{
264 int ret, cpu;
265
266 for_each_possible_cpu(cpu) {
267 spin_lock_init(&workqueue_cpu_stat(cpu)->lock);
268 INIT_LIST_HEAD(&workqueue_cpu_stat(cpu)->list);
269 }
270
271 ret = register_trace_workqueue_insertion(probe_workqueue_insertion, NULL);
272 if (ret)
273 goto out;
274
275 ret = register_trace_workqueue_execution(probe_workqueue_execution, NULL);
276 if (ret)
277 goto no_insertion;
278
279 ret = register_trace_workqueue_creation(probe_workqueue_creation, NULL);
280 if (ret)
281 goto no_execution;
282
283 ret = register_trace_workqueue_destruction(probe_workqueue_destruction, NULL);
284 if (ret)
285 goto no_creation;
286
287 return 0;
288
289no_creation:
290 unregister_trace_workqueue_creation(probe_workqueue_creation, NULL);
291no_execution:
292 unregister_trace_workqueue_execution(probe_workqueue_execution, NULL);
293no_insertion:
294 unregister_trace_workqueue_insertion(probe_workqueue_insertion, NULL);
295out:
296 pr_warning("trace_workqueue: unable to trace workqueues\n");
297
298 return 1;
299}
300early_initcall(trace_workqueue_early_init);
diff --git a/kernel/trace/tracedump.c b/kernel/trace/tracedump.c
new file mode 100644
index 00000000000..a83532bc36d
--- /dev/null
+++ b/kernel/trace/tracedump.c
@@ -0,0 +1,682 @@
1/*
2 * kernel/trace/tracedump.c
3 *
4 * Copyright (c) 2011, NVIDIA CORPORATION. All rights reserved.
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms and conditions of the GNU General Public License,
8 * version 2, as published by the Free Software Foundation.
9 *
10 * This program is distributed in the hope it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13 * more details.
14 *
15 * You should have received a copy of the GNU General Public License along with
16 * this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 */
20
21#include <linux/console.h>
22#include <linux/cpumask.h>
23#include <linux/init.h>
24#include <linux/irqflags.h>
25#include <linux/module.h>
26#include <linux/moduleparam.h>
27#include <linux/mutex.h>
28#include <linux/notifier.h>
29#include <linux/proc_fs.h>
30#include <linux/ring_buffer.h>
31#include <linux/sched.h>
32#include <linux/smp.h>
33#include <linux/string.h>
34#include <linux/threads.h>
35#include <linux/tracedump.h>
36#include <linux/uaccess.h>
37#include <linux/vmalloc.h>
38#include <linux/zlib.h>
39
40#include "trace.h"
41#include "trace_output.h"
42
43#define CPU_MAX (NR_CPUS-1)
44
45#define TRYM(fn, ...) do { \
46 int try_error = (fn); \
47 if (try_error < 0) { \
48 printk(__VA_ARGS__); \
49 return try_error; \
50 } \
51} while (0)
52
53#define TRY(fn) TRYM(fn, TAG "Caught error from %s in %s\n", #fn, __func__)
54
55/* Stolen from printk.c */
56#define for_each_console(con) \
57 for (con = console_drivers; con != NULL; con = con->next)
58
59#define TAG KERN_ERR "tracedump: "
60
61#define TD_MIN_CONSUME 2000
62#define TD_COMPRESS_CHUNK 0x8000
63
64static DEFINE_MUTEX(tracedump_proc_lock);
65
66static const char MAGIC_NUMBER[9] = "TRACEDUMP";
67static const char CPU_DELIM[7] = "CPU_END";
68#define CMDLINE_DELIM "|"
69
70/* Type of output */
71static bool current_format;
72static bool format_ascii;
73module_param(format_ascii, bool, S_IRUGO | S_IWUSR);
74MODULE_PARM_DESC(format_ascii, "Dump ascii or raw data");
75
76/* Max size of output */
77static uint panic_size = 0x80000;
78module_param(panic_size, uint, S_IRUGO | S_IWUSR);
79MODULE_PARM_DESC(panic_size, "Max dump size during kernel panic (bytes)");
80
81static uint compress_level = 9;
82module_param(compress_level, uint, S_IRUGO | S_IWUSR);
83MODULE_PARM_DESC(compress_level, "Level of compression to use. [0-9]");
84
85static char out_buf[TD_COMPRESS_CHUNK];
86static z_stream stream;
87static int compress_done;
88static int flush;
89
90static int old_trace_flags;
91
92static struct trace_iterator iter;
93static struct pager_s {
94 struct trace_array *tr;
95 void *spare;
96 int cpu;
97 int len;
98 char __user *ubuf;
99} pager;
100
101static char cmdline_buf[16+TASK_COMM_LEN];
102
103static int print_to_console(const char *buf, size_t len)
104{
105 struct console *con;
106
107 /* Stolen from printk.c */
108 for_each_console(con) {
109 if ((con->flags & CON_ENABLED) && con->write &&
110 (cpu_online(smp_processor_id()) ||
111 (con->flags & CON_ANYTIME)))
112 con->write(con, buf, len);
113 }
114 return 0;
115}
116
117static int print_to_user(const char *buf, size_t len)
118{
119 int size;
120 size = copy_to_user(pager.ubuf, buf, len);
121 if (size > 0) {
122 printk(TAG "Failed to copy to user %d bytes\n", size);
123 return -EINVAL;
124 }
125 return 0;
126}
127
128static int print(const char *buf, size_t len, int print_to)
129{
130 if (print_to == TD_PRINT_CONSOLE)
131 TRY(print_to_console(buf, len));
132 else if (print_to == TD_PRINT_USER)
133 TRY(print_to_user(buf, len));
134 return 0;
135}
136
137/* print_magic will print MAGIC_NUMBER using the
138 * print function selected by print_to.
139 */
140static inline ssize_t print_magic(int print_to)
141{
142 print(MAGIC_NUMBER, sizeof(MAGIC_NUMBER), print_to);
143 return sizeof(MAGIC_NUMBER);
144}
145
146static int iter_init(void)
147{
148 int cpu;
149
150 /* Make iter point to global ring buffer used in trace. */
151 trace_init_global_iter(&iter);
152
153 /* Disable tracing */
154 for_each_tracing_cpu(cpu) {
155 atomic_inc(&iter.tr->data[cpu]->disabled);
156 }
157
158 /* Save flags */
159 old_trace_flags = trace_flags;
160
161 /* Dont look at memory in panic mode. */
162 trace_flags &= ~TRACE_ITER_SYM_USEROBJ;
163
164 /* Prepare ring buffer iter */
165 for_each_tracing_cpu(cpu) {
166 iter.buffer_iter[cpu] =
167 ring_buffer_read_prepare(iter.tr->buffer, cpu);
168 }
169 ring_buffer_read_prepare_sync();
170 for_each_tracing_cpu(cpu) {
171 ring_buffer_read_start(iter.buffer_iter[cpu]);
172 tracing_iter_reset(&iter, cpu);
173 }
174 return 0;
175}
176
177/* iter_next gets the next entry in the ring buffer, ordered by time.
178 * If there are no more entries, returns 0.
179 */
180static ssize_t iter_next(void)
181{
182 /* Zero out the iterator's seq */
183 memset(&iter.seq, 0,
184 sizeof(struct trace_iterator) -
185 offsetof(struct trace_iterator, seq));
186
187 while (!trace_empty(&iter)) {
188 if (trace_find_next_entry_inc(&iter) == NULL) {
189 printk(TAG "trace_find_next_entry failed!\n");
190 return -EINVAL;
191 }
192
193 /* Copy the ring buffer data to iterator's seq */
194 print_trace_line(&iter);
195 if (iter.seq.len != 0)
196 return iter.seq.len;
197 }
198 return 0;
199}
200
201static int iter_deinit(void)
202{
203 int cpu;
204 /* Enable tracing */
205 for_each_tracing_cpu(cpu) {
206 ring_buffer_read_finish(iter.buffer_iter[cpu]);
207 }
208 for_each_tracing_cpu(cpu) {
209 atomic_dec(&iter.tr->data[cpu]->disabled);
210 }
211
212 /* Restore flags */
213 trace_flags = old_trace_flags;
214 return 0;
215}
216
217static int pager_init(void)
218{
219 int cpu;
220
221 /* Need to do this to get a pointer to global_trace (iter.tr).
222 Lame, I know. */
223 trace_init_global_iter(&iter);
224
225 /* Turn off tracing */
226 for_each_tracing_cpu(cpu) {
227 atomic_inc(&iter.tr->data[cpu]->disabled);
228 }
229
230 memset(&pager, 0, sizeof(pager));
231 pager.tr = iter.tr;
232 pager.len = TD_COMPRESS_CHUNK;
233
234 return 0;
235}
236
237/* pager_next_cpu moves the pager to the next cpu.
238 * Returns 0 if pager is done, else 1.
239 */
240static ssize_t pager_next_cpu(void)
241{
242 if (pager.cpu <= CPU_MAX) {
243 pager.cpu += 1;
244 return 1;
245 }
246
247 return 0;
248}
249
250/* pager_next gets the next page of data from the ring buffer
251 * of the current cpu. Returns page size or 0 if no more data.
252 */
253static ssize_t pager_next(void)
254{
255 int ret;
256
257 if (pager.cpu > CPU_MAX)
258 return 0;
259
260 if (!pager.spare)
261 pager.spare = ring_buffer_alloc_read_page(pager.tr->buffer, pager.cpu);
262 if (!pager.spare) {
263 printk(TAG "ring_buffer_alloc_read_page failed!");
264 return -ENOMEM;
265 }
266
267 ret = ring_buffer_read_page(pager.tr->buffer,
268 &pager.spare,
269 pager.len,
270 pager.cpu, 0);
271 if (ret < 0)
272 return 0;
273
274 return PAGE_SIZE;
275}
276
277static int pager_deinit(void)
278{
279 int cpu;
280 if (pager.spare != NULL)
281 ring_buffer_free_read_page(pager.tr->buffer, pager.spare);
282
283 for_each_tracing_cpu(cpu) {
284 atomic_dec(&iter.tr->data[cpu]->disabled);
285 }
286 return 0;
287}
288
289/* cmdline_next gets the next saved cmdline from the trace and
290 * puts it in cmdline_buf. Returns the size of the cmdline, or 0 if empty.
291 * but will reset itself on a subsequent call.
292 */
293static ssize_t cmdline_next(void)
294{
295 static int pid;
296 ssize_t size = 0;
297
298 if (pid >= PID_MAX_DEFAULT)
299 pid = -1;
300
301 while (size == 0 && pid < PID_MAX_DEFAULT) {
302 pid++;
303 trace_find_cmdline(pid, cmdline_buf);
304 if (!strncmp(cmdline_buf, "<...>", 5))
305 continue;
306
307 sprintf(&cmdline_buf[strlen(cmdline_buf)], " %d"
308 CMDLINE_DELIM, pid);
309 size = strlen(cmdline_buf);
310 }
311 return size;
312}
313
314/* comsume_events removes the first 'num' entries from the ring buffer. */
315static int consume_events(size_t num)
316{
317 TRY(iter_init());
318 for (; num > 0 && !trace_empty(&iter); num--) {
319 trace_find_next_entry_inc(&iter);
320 ring_buffer_consume(iter.tr->buffer, iter.cpu, &iter.ts,
321 &iter.lost_events);
322 }
323 TRY(iter_deinit());
324 return 0;
325}
326
327static int data_init(void)
328{
329 if (current_format)
330 TRY(iter_init());
331 else
332 TRY(pager_init());
333 return 0;
334}
335
336/* data_next will figure out the right 'next' function to
337 * call and will select the right buffer to pass back
338 * to compress_next.
339 *
340 * iter_next should be used to get data entry-by-entry, ordered
341 * by time, which is what we need in order to convert it to ascii.
342 *
343 * pager_next will return a full page of raw data at a time, one
344 * CPU at a time. pager_next_cpu must be called to get the next CPU.
345 * cmdline_next will get the next saved cmdline
346 */
347static ssize_t data_next(const char **buf)
348{
349 ssize_t size;
350
351 if (current_format) {
352 TRY(size = iter_next());
353 *buf = iter.seq.buffer;
354 } else {
355 TRY(size = pager_next());
356 *buf = pager.spare;
357 if (size == 0) {
358 if (pager_next_cpu()) {
359 size = sizeof(CPU_DELIM);
360 *buf = CPU_DELIM;
361 } else {
362 TRY(size = cmdline_next());
363 *buf = cmdline_buf;
364 }
365 }
366 }
367 return size;
368}
369
370static int data_deinit(void)
371{
372 if (current_format)
373 TRY(iter_deinit());
374 else
375 TRY(pager_deinit());
376 return 0;
377}
378
379static int compress_init(void)
380{
381 int workspacesize, ret;
382
383 compress_done = 0;
384 flush = Z_NO_FLUSH;
385 stream.data_type = current_format ? Z_ASCII : Z_BINARY;
386 workspacesize = zlib_deflate_workspacesize(MAX_WBITS, MAX_MEM_LEVEL);
387 stream.workspace = vmalloc(workspacesize);
388 if (!stream.workspace) {
389 printk(TAG "Could not allocate "
390 "enough memory for zlib!\n");
391 return -ENOMEM;
392 }
393 memset(stream.workspace, 0, workspacesize);
394
395 ret = zlib_deflateInit(&stream, compress_level);
396 if (ret != Z_OK) {
397 printk(TAG "%s\n", stream.msg);
398 return ret;
399 }
400 stream.avail_in = 0;
401 stream.avail_out = 0;
402 TRY(data_init());
403 return 0;
404}
405
406/* compress_next will compress up to min(max_out, TD_COMPRESS_CHUNK) bytes
407 * of data into the output buffer. It gets the data by calling data_next.
408 * It will return the most data it possibly can. If it returns 0, then
409 * there is no more data.
410 *
411 * By the way that zlib works, each call to zlib_deflate will possibly
412 * consume up to avail_in bytes from next_in, and will fill up to
413 * avail_out bytes in next_out. Once flush == Z_FINISH, it can not take
414 * any more input. It will output until it is finished, and will return
415 * Z_STREAM_END.
416 */
417static ssize_t compress_next(size_t max_out)
418{
419 ssize_t ret;
420 max_out = min(max_out, (size_t)TD_COMPRESS_CHUNK);
421 stream.next_out = out_buf;
422 stream.avail_out = max_out;
423 while (stream.avail_out > 0 && !compress_done) {
424 if (stream.avail_in == 0 && flush != Z_FINISH) {
425 TRY(stream.avail_in =
426 data_next((const char **)&stream.next_in));
427 flush = (stream.avail_in == 0) ? Z_FINISH : Z_NO_FLUSH;
428 }
429 if (stream.next_in != NULL) {
430 TRYM((ret = zlib_deflate(&stream, flush)),
431 "zlib: %s\n", stream.msg);
432 compress_done = (ret == Z_STREAM_END);
433 }
434 }
435 ret = max_out - stream.avail_out;
436 return ret;
437}
438
439static int compress_deinit(void)
440{
441 TRY(data_deinit());
442
443 zlib_deflateEnd(&stream);
444 vfree(stream.workspace);
445
446 /* TODO: remove */
447 printk(TAG "Total in: %ld\n", stream.total_in);
448 printk(TAG "Total out: %ld\n", stream.total_out);
449 return stream.total_out;
450}
451
452static int compress_reset(void)
453{
454 TRY(compress_deinit());
455 TRY(compress_init());
456 return 0;
457}
458
459/* tracedump_init initializes all tracedump components.
460 * Call this before tracedump_next
461 */
462int tracedump_init(void)
463{
464 TRY(compress_init());
465 return 0;
466}
467
468/* tracedump_next will print up to max_out data from the tracing ring
469 * buffers using the print function selected by print_to. The data is
470 * compressed using zlib.
471 *
472 * The output type of the data is specified by the format_ascii module
473 * parameter. If format_ascii == 1, human-readable data will be output.
474 * Otherwise, it will output raw data from the ring buffer in cpu order,
475 * followed by the saved_cmdlines data.
476 */
477ssize_t tracedump_next(size_t max_out, int print_to)
478{
479 ssize_t size;
480 TRY(size = compress_next(max_out));
481 print(out_buf, size, print_to);
482 return size;
483}
484
485/* tracedump_all will print all data in the tracing ring buffers using
486 * the print function selected by print_to. The data is compressed using
487 * zlib, and is surrounded by MAGIC_NUMBER.
488 *
489 * The output type of the data is specified by the format_ascii module
490 * parameter. If format_ascii == 1, human-readable data will be output.
491 * Otherwise, it will output raw data from the ring buffer in cpu order,
492 * followed by the saved_cmdlines data.
493 */
494ssize_t tracedump_all(int print_to)
495{
496 ssize_t ret, size = 0;
497 TRY(size += print_magic(print_to));
498
499 do {
500 /* Here the size used doesn't really matter,
501 * since we're dumping everything. */
502 TRY(ret = tracedump_next(0xFFFFFFFF, print_to));
503 size += ret;
504 } while (ret > 0);
505
506 TRY(size += print_magic(print_to));
507
508 return size;
509}
510
511/* tracedump_deinit deinitializes all tracedump components.
512 * This must be called, even on error.
513 */
514int tracedump_deinit(void)
515{
516 TRY(compress_deinit());
517 return 0;
518}
519
520/* tracedump_reset reinitializes all tracedump components. */
521int tracedump_reset(void)
522{
523 TRY(compress_reset());
524 return 0;
525}
526
527
528
529/* tracedump_open opens the tracedump file for reading. */
530static int tracedump_open(struct inode *inode, struct file *file)
531{
532 int ret;
533 mutex_lock(&tracedump_proc_lock);
534 current_format = format_ascii;
535 ret = tracedump_init();
536 if (ret < 0)
537 goto err;
538
539 ret = nonseekable_open(inode, file);
540 if (ret < 0)
541 goto err;
542 return ret;
543
544err:
545 mutex_unlock(&tracedump_proc_lock);
546 return ret;
547}
548
549/* tracedump_read will reads data from tracedump_next and prints
550 * it to userspace. It will surround the data with MAGIC_NUMBER.
551 */
552static ssize_t tracedump_read(struct file *file, char __user *buf,
553 size_t len, loff_t *offset)
554{
555 static int done;
556 ssize_t size = 0;
557
558 pager.ubuf = buf;
559
560 if (*offset == 0) {
561 done = 0;
562 TRY(size = print_magic(TD_PRINT_USER));
563 } else if (!done) {
564 TRY(size = tracedump_next(len, TD_PRINT_USER));
565 if (size == 0) {
566 TRY(size = print_magic(TD_PRINT_USER));
567 done = 1;
568 }
569 }
570
571 *offset += size;
572
573 return size;
574}
575
576static int tracedump_release(struct inode *inode, struct file *file)
577{
578 int ret;
579 ret = tracedump_deinit();
580 mutex_unlock(&tracedump_proc_lock);
581 return ret;
582}
583
584/* tracedump_dump dumps all tracing data from the tracing ring buffers
585 * to all consoles. For details about the output format, see
586 * tracedump_all.
587
588 * At most max_out bytes are dumped. To accomplish this,
589 * tracedump_dump calls tracedump_all several times without writing the data,
590 * each time tossing out old data until it reaches its goal.
591 *
592 * Note: dumping raw pages currently does NOT follow the size limit.
593 */
594
595int tracedump_dump(size_t max_out)
596{
597 ssize_t size;
598 size_t consume;
599
600 printk(TAG "\n");
601
602 tracedump_init();
603
604 if (format_ascii) {
605 size = tracedump_all(TD_NO_PRINT);
606 if (size < 0) {
607 printk(TAG "failed to dump\n");
608 goto out;
609 }
610 while (size > max_out) {
611 TRY(tracedump_deinit());
612 /* Events take more or less 60 ascii bytes each,
613 not counting compression */
614 consume = TD_MIN_CONSUME + (size - max_out) /
615 (60 / (compress_level + 1));
616 TRY(consume_events(consume));
617 TRY(tracedump_init());
618 size = tracedump_all(TD_NO_PRINT);
619 if (size < 0) {
620 printk(TAG "failed to dump\n");
621 goto out;
622 }
623 }
624
625 TRY(tracedump_reset());
626 }
627 size = tracedump_all(TD_PRINT_CONSOLE);
628 if (size < 0) {
629 printk(TAG "failed to dump\n");
630 goto out;
631 }
632
633out:
634 tracedump_deinit();
635 printk(KERN_INFO "\n" TAG " end\n");
636 return size;
637}
638
639static const struct file_operations tracedump_fops = {
640 .owner = THIS_MODULE,
641 .open = tracedump_open,
642 .read = tracedump_read,
643 .release = tracedump_release,
644};
645
646#ifdef CONFIG_TRACEDUMP_PANIC
647static int tracedump_panic_handler(struct notifier_block *this,
648 unsigned long event, void *unused)
649{
650 tracedump_dump(panic_size);
651 return 0;
652}
653
654static struct notifier_block tracedump_panic_notifier = {
655 .notifier_call = tracedump_panic_handler,
656 .next = NULL,
657 .priority = 150 /* priority: INT_MAX >= x >= 0 */
658};
659#endif
660
661static int __init tracedump_initcall(void)
662{
663#ifdef CONFIG_TRACEDUMP_PROCFS
664 struct proc_dir_entry *entry;
665
666 /* Create a procfs file for easy dumping */
667 entry = create_proc_entry("tracedump", S_IFREG | S_IRUGO, NULL);
668 if (!entry)
669 printk(TAG "failed to create proc entry\n");
670 else
671 entry->proc_fops = &tracedump_fops;
672#endif
673
674#ifdef CONFIG_TRACEDUMP_PANIC
675 /* Automatically dump to console on a kernel panic */
676 atomic_notifier_chain_register(&panic_notifier_list,
677 &tracedump_panic_notifier);
678#endif
679 return 0;
680}
681
682early_initcall(tracedump_initcall);
diff --git a/kernel/trace/tracelevel.c b/kernel/trace/tracelevel.c
new file mode 100644
index 00000000000..9f8b8eedbb5
--- /dev/null
+++ b/kernel/trace/tracelevel.c
@@ -0,0 +1,142 @@
1/*
2 * kernel/trace/tracelevel.c
3 *
4 * Copyright (c) 2011, NVIDIA CORPORATION. All rights reserved.
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms and conditions of the GNU General Public License,
8 * version 2, as published by the Free Software Foundation.
9 *
10 * This program is distributed in the hope it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
13 * more details.
14 *
15 * You should have received a copy of the GNU General Public License along with
16 * this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 */
20
21#include <linux/ftrace_event.h>
22#include <linux/list.h>
23#include <linux/moduleparam.h>
24#include <linux/mutex.h>
25#include <linux/tracelevel.h>
26#include <linux/vmalloc.h>
27
28#include "trace.h"
29
30#define TAG KERN_ERR "tracelevel: "
31
32struct tracelevel_record {
33 struct list_head list;
34 char *name;
35 int level;
36};
37
38static LIST_HEAD(tracelevel_list);
39
40static bool started;
41static unsigned int tracelevel_level = TRACELEVEL_DEFAULT;
42
43static DEFINE_MUTEX(tracelevel_record_lock);
44
45/* tracelevel_set_event sets a single event if set = 1, or
46 * clears an event if set = 0.
47 */
48static int tracelevel_set_event(struct tracelevel_record *evt, bool set)
49{
50 if (trace_set_clr_event(NULL, evt->name, set) < 0) {
51 printk(TAG "failed to set event %s\n", evt->name);
52 return -EINVAL;
53 }
54 return 0;
55}
56
57/* Registers an event. If possible, it also sets it.
58 * If not, we'll set it in tracelevel_init.
59 */
60int __tracelevel_register(char *name, unsigned int level)
61{
62 struct tracelevel_record *evt = (struct tracelevel_record *)
63 vmalloc(sizeof(struct tracelevel_record));
64 if (!evt) {
65 printk(TAG "failed to allocate tracelevel_record for %s\n",
66 name);
67 return -ENOMEM;
68 }
69
70 evt->name = name;
71 evt->level = level;
72
73 mutex_lock(&tracelevel_record_lock);
74 list_add(&evt->list, &tracelevel_list);
75 mutex_unlock(&tracelevel_record_lock);
76
77 if (level >= tracelevel_level && started)
78 tracelevel_set_event(evt, 1);
79 return 0;
80}
81
82/* tracelevel_set_level sets the global level, clears events
83 * lower than that level, and enables events greater or equal.
84 */
85int tracelevel_set_level(int level)
86{
87 struct tracelevel_record *evt = NULL;
88
89 if (level < 0 || level > TRACELEVEL_MAX)
90 return -EINVAL;
91 tracelevel_level = level;
92
93 mutex_lock(&tracelevel_record_lock);
94 list_for_each_entry(evt, &tracelevel_list, list) {
95 if (evt->level >= level)
96 tracelevel_set_event(evt, 1);
97 else
98 tracelevel_set_event(evt, 0);
99 }
100 mutex_unlock(&tracelevel_record_lock);
101 return 0;
102}
103
104static int param_set_level(const char *val, const struct kernel_param *kp)
105{
106 int level, ret;
107 ret = strict_strtol(val, 0, &level);
108 if (ret < 0)
109 return ret;
110 return tracelevel_set_level(level);
111}
112
113static int param_get_level(char *buffer, const struct kernel_param *kp)
114{
115 return param_get_int(buffer, kp);
116}
117
118static struct kernel_param_ops tracelevel_level_ops = {
119 .set = param_set_level,
120 .get = param_get_level
121};
122
123module_param_cb(level, &tracelevel_level_ops, &tracelevel_level, 0644);
124
125/* Turn on the tracing that has been registered thus far. */
126static int __init tracelevel_init(void)
127{
128 int ret;
129 started = true;
130
131 /* Ring buffer is initialize to 1 page until the user sets a tracer.
132 * Since we're doing this manually, we need to ask for expanded buffer.
133 */
134 ret = tracing_update_buffers();
135 if (ret < 0)
136 return ret;
137
138 return tracelevel_set_level(tracelevel_level);
139}
140
141/* Tracing mechanism is set up during fs_initcall. */
142fs_initcall_sync(tracelevel_init);