Commit 5ab551d662396f8437ec5aba12210b7a67eb492b

Authored by Linus Torvalds

Merge branch 'sched-urgent-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/tip/tip

Pull scheduler fixes from Ingo Molnar:
 "Misc fixes: group scheduling corner case fix, two deadline scheduler
  fixes, effective_load() overflow fix, nested sleep fix, 6144 CPUs
  system fix"

* 'sched-urgent-for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/tip/tip:
  sched/fair: Fix RCU stall upon -ENOMEM in sched_create_group()
  sched/deadline: Avoid double-accounting in case of missed deadlines
  sched/deadline: Fix migration of SCHED_DEADLINE tasks
  sched: Fix odd values in effective_load() calculations
  sched, fanotify: Deal with nested sleeps
  sched: Fix KMALLOC_MAX_SIZE overflow during cpumask allocation

Showing 4 changed files Inline Diff

fs/notify/fanotify/fanotify_user.c
1 #include <linux/fanotify.h> 1 #include <linux/fanotify.h>
2 #include <linux/fcntl.h> 2 #include <linux/fcntl.h>
3 #include <linux/file.h> 3 #include <linux/file.h>
4 #include <linux/fs.h> 4 #include <linux/fs.h>
5 #include <linux/anon_inodes.h> 5 #include <linux/anon_inodes.h>
6 #include <linux/fsnotify_backend.h> 6 #include <linux/fsnotify_backend.h>
7 #include <linux/init.h> 7 #include <linux/init.h>
8 #include <linux/mount.h> 8 #include <linux/mount.h>
9 #include <linux/namei.h> 9 #include <linux/namei.h>
10 #include <linux/poll.h> 10 #include <linux/poll.h>
11 #include <linux/security.h> 11 #include <linux/security.h>
12 #include <linux/syscalls.h> 12 #include <linux/syscalls.h>
13 #include <linux/slab.h> 13 #include <linux/slab.h>
14 #include <linux/types.h> 14 #include <linux/types.h>
15 #include <linux/uaccess.h> 15 #include <linux/uaccess.h>
16 #include <linux/compat.h> 16 #include <linux/compat.h>
17 17
18 #include <asm/ioctls.h> 18 #include <asm/ioctls.h>
19 19
20 #include "../../mount.h" 20 #include "../../mount.h"
21 #include "../fdinfo.h" 21 #include "../fdinfo.h"
22 #include "fanotify.h" 22 #include "fanotify.h"
23 23
24 #define FANOTIFY_DEFAULT_MAX_EVENTS 16384 24 #define FANOTIFY_DEFAULT_MAX_EVENTS 16384
25 #define FANOTIFY_DEFAULT_MAX_MARKS 8192 25 #define FANOTIFY_DEFAULT_MAX_MARKS 8192
26 #define FANOTIFY_DEFAULT_MAX_LISTENERS 128 26 #define FANOTIFY_DEFAULT_MAX_LISTENERS 128
27 27
28 /* 28 /*
29 * All flags that may be specified in parameter event_f_flags of fanotify_init. 29 * All flags that may be specified in parameter event_f_flags of fanotify_init.
30 * 30 *
31 * Internal and external open flags are stored together in field f_flags of 31 * Internal and external open flags are stored together in field f_flags of
32 * struct file. Only external open flags shall be allowed in event_f_flags. 32 * struct file. Only external open flags shall be allowed in event_f_flags.
33 * Internal flags like FMODE_NONOTIFY, FMODE_EXEC, FMODE_NOCMTIME shall be 33 * Internal flags like FMODE_NONOTIFY, FMODE_EXEC, FMODE_NOCMTIME shall be
34 * excluded. 34 * excluded.
35 */ 35 */
36 #define FANOTIFY_INIT_ALL_EVENT_F_BITS ( \ 36 #define FANOTIFY_INIT_ALL_EVENT_F_BITS ( \
37 O_ACCMODE | O_APPEND | O_NONBLOCK | \ 37 O_ACCMODE | O_APPEND | O_NONBLOCK | \
38 __O_SYNC | O_DSYNC | O_CLOEXEC | \ 38 __O_SYNC | O_DSYNC | O_CLOEXEC | \
39 O_LARGEFILE | O_NOATIME ) 39 O_LARGEFILE | O_NOATIME )
40 40
41 extern const struct fsnotify_ops fanotify_fsnotify_ops; 41 extern const struct fsnotify_ops fanotify_fsnotify_ops;
42 42
43 static struct kmem_cache *fanotify_mark_cache __read_mostly; 43 static struct kmem_cache *fanotify_mark_cache __read_mostly;
44 struct kmem_cache *fanotify_event_cachep __read_mostly; 44 struct kmem_cache *fanotify_event_cachep __read_mostly;
45 struct kmem_cache *fanotify_perm_event_cachep __read_mostly; 45 struct kmem_cache *fanotify_perm_event_cachep __read_mostly;
46 46
47 /* 47 /*
48 * Get an fsnotify notification event if one exists and is small 48 * Get an fsnotify notification event if one exists and is small
49 * enough to fit in "count". Return an error pointer if the count 49 * enough to fit in "count". Return an error pointer if the count
50 * is not large enough. 50 * is not large enough.
51 * 51 *
52 * Called with the group->notification_mutex held. 52 * Called with the group->notification_mutex held.
53 */ 53 */
54 static struct fsnotify_event *get_one_event(struct fsnotify_group *group, 54 static struct fsnotify_event *get_one_event(struct fsnotify_group *group,
55 size_t count) 55 size_t count)
56 { 56 {
57 BUG_ON(!mutex_is_locked(&group->notification_mutex)); 57 BUG_ON(!mutex_is_locked(&group->notification_mutex));
58 58
59 pr_debug("%s: group=%p count=%zd\n", __func__, group, count); 59 pr_debug("%s: group=%p count=%zd\n", __func__, group, count);
60 60
61 if (fsnotify_notify_queue_is_empty(group)) 61 if (fsnotify_notify_queue_is_empty(group))
62 return NULL; 62 return NULL;
63 63
64 if (FAN_EVENT_METADATA_LEN > count) 64 if (FAN_EVENT_METADATA_LEN > count)
65 return ERR_PTR(-EINVAL); 65 return ERR_PTR(-EINVAL);
66 66
67 /* held the notification_mutex the whole time, so this is the 67 /* held the notification_mutex the whole time, so this is the
68 * same event we peeked above */ 68 * same event we peeked above */
69 return fsnotify_remove_first_event(group); 69 return fsnotify_remove_first_event(group);
70 } 70 }
71 71
72 static int create_fd(struct fsnotify_group *group, 72 static int create_fd(struct fsnotify_group *group,
73 struct fanotify_event_info *event, 73 struct fanotify_event_info *event,
74 struct file **file) 74 struct file **file)
75 { 75 {
76 int client_fd; 76 int client_fd;
77 struct file *new_file; 77 struct file *new_file;
78 78
79 pr_debug("%s: group=%p event=%p\n", __func__, group, event); 79 pr_debug("%s: group=%p event=%p\n", __func__, group, event);
80 80
81 client_fd = get_unused_fd_flags(group->fanotify_data.f_flags); 81 client_fd = get_unused_fd_flags(group->fanotify_data.f_flags);
82 if (client_fd < 0) 82 if (client_fd < 0)
83 return client_fd; 83 return client_fd;
84 84
85 /* 85 /*
86 * we need a new file handle for the userspace program so it can read even if it was 86 * we need a new file handle for the userspace program so it can read even if it was
87 * originally opened O_WRONLY. 87 * originally opened O_WRONLY.
88 */ 88 */
89 /* it's possible this event was an overflow event. in that case dentry and mnt 89 /* it's possible this event was an overflow event. in that case dentry and mnt
90 * are NULL; That's fine, just don't call dentry open */ 90 * are NULL; That's fine, just don't call dentry open */
91 if (event->path.dentry && event->path.mnt) 91 if (event->path.dentry && event->path.mnt)
92 new_file = dentry_open(&event->path, 92 new_file = dentry_open(&event->path,
93 group->fanotify_data.f_flags | FMODE_NONOTIFY, 93 group->fanotify_data.f_flags | FMODE_NONOTIFY,
94 current_cred()); 94 current_cred());
95 else 95 else
96 new_file = ERR_PTR(-EOVERFLOW); 96 new_file = ERR_PTR(-EOVERFLOW);
97 if (IS_ERR(new_file)) { 97 if (IS_ERR(new_file)) {
98 /* 98 /*
99 * we still send an event even if we can't open the file. this 99 * we still send an event even if we can't open the file. this
100 * can happen when say tasks are gone and we try to open their 100 * can happen when say tasks are gone and we try to open their
101 * /proc files or we try to open a WRONLY file like in sysfs 101 * /proc files or we try to open a WRONLY file like in sysfs
102 * we just send the errno to userspace since there isn't much 102 * we just send the errno to userspace since there isn't much
103 * else we can do. 103 * else we can do.
104 */ 104 */
105 put_unused_fd(client_fd); 105 put_unused_fd(client_fd);
106 client_fd = PTR_ERR(new_file); 106 client_fd = PTR_ERR(new_file);
107 } else { 107 } else {
108 *file = new_file; 108 *file = new_file;
109 } 109 }
110 110
111 return client_fd; 111 return client_fd;
112 } 112 }
113 113
114 static int fill_event_metadata(struct fsnotify_group *group, 114 static int fill_event_metadata(struct fsnotify_group *group,
115 struct fanotify_event_metadata *metadata, 115 struct fanotify_event_metadata *metadata,
116 struct fsnotify_event *fsn_event, 116 struct fsnotify_event *fsn_event,
117 struct file **file) 117 struct file **file)
118 { 118 {
119 int ret = 0; 119 int ret = 0;
120 struct fanotify_event_info *event; 120 struct fanotify_event_info *event;
121 121
122 pr_debug("%s: group=%p metadata=%p event=%p\n", __func__, 122 pr_debug("%s: group=%p metadata=%p event=%p\n", __func__,
123 group, metadata, fsn_event); 123 group, metadata, fsn_event);
124 124
125 *file = NULL; 125 *file = NULL;
126 event = container_of(fsn_event, struct fanotify_event_info, fse); 126 event = container_of(fsn_event, struct fanotify_event_info, fse);
127 metadata->event_len = FAN_EVENT_METADATA_LEN; 127 metadata->event_len = FAN_EVENT_METADATA_LEN;
128 metadata->metadata_len = FAN_EVENT_METADATA_LEN; 128 metadata->metadata_len = FAN_EVENT_METADATA_LEN;
129 metadata->vers = FANOTIFY_METADATA_VERSION; 129 metadata->vers = FANOTIFY_METADATA_VERSION;
130 metadata->reserved = 0; 130 metadata->reserved = 0;
131 metadata->mask = fsn_event->mask & FAN_ALL_OUTGOING_EVENTS; 131 metadata->mask = fsn_event->mask & FAN_ALL_OUTGOING_EVENTS;
132 metadata->pid = pid_vnr(event->tgid); 132 metadata->pid = pid_vnr(event->tgid);
133 if (unlikely(fsn_event->mask & FAN_Q_OVERFLOW)) 133 if (unlikely(fsn_event->mask & FAN_Q_OVERFLOW))
134 metadata->fd = FAN_NOFD; 134 metadata->fd = FAN_NOFD;
135 else { 135 else {
136 metadata->fd = create_fd(group, event, file); 136 metadata->fd = create_fd(group, event, file);
137 if (metadata->fd < 0) 137 if (metadata->fd < 0)
138 ret = metadata->fd; 138 ret = metadata->fd;
139 } 139 }
140 140
141 return ret; 141 return ret;
142 } 142 }
143 143
144 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS 144 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS
145 static struct fanotify_perm_event_info *dequeue_event( 145 static struct fanotify_perm_event_info *dequeue_event(
146 struct fsnotify_group *group, int fd) 146 struct fsnotify_group *group, int fd)
147 { 147 {
148 struct fanotify_perm_event_info *event, *return_e = NULL; 148 struct fanotify_perm_event_info *event, *return_e = NULL;
149 149
150 spin_lock(&group->fanotify_data.access_lock); 150 spin_lock(&group->fanotify_data.access_lock);
151 list_for_each_entry(event, &group->fanotify_data.access_list, 151 list_for_each_entry(event, &group->fanotify_data.access_list,
152 fae.fse.list) { 152 fae.fse.list) {
153 if (event->fd != fd) 153 if (event->fd != fd)
154 continue; 154 continue;
155 155
156 list_del_init(&event->fae.fse.list); 156 list_del_init(&event->fae.fse.list);
157 return_e = event; 157 return_e = event;
158 break; 158 break;
159 } 159 }
160 spin_unlock(&group->fanotify_data.access_lock); 160 spin_unlock(&group->fanotify_data.access_lock);
161 161
162 pr_debug("%s: found return_re=%p\n", __func__, return_e); 162 pr_debug("%s: found return_re=%p\n", __func__, return_e);
163 163
164 return return_e; 164 return return_e;
165 } 165 }
166 166
167 static int process_access_response(struct fsnotify_group *group, 167 static int process_access_response(struct fsnotify_group *group,
168 struct fanotify_response *response_struct) 168 struct fanotify_response *response_struct)
169 { 169 {
170 struct fanotify_perm_event_info *event; 170 struct fanotify_perm_event_info *event;
171 int fd = response_struct->fd; 171 int fd = response_struct->fd;
172 int response = response_struct->response; 172 int response = response_struct->response;
173 173
174 pr_debug("%s: group=%p fd=%d response=%d\n", __func__, group, 174 pr_debug("%s: group=%p fd=%d response=%d\n", __func__, group,
175 fd, response); 175 fd, response);
176 /* 176 /*
177 * make sure the response is valid, if invalid we do nothing and either 177 * make sure the response is valid, if invalid we do nothing and either
178 * userspace can send a valid response or we will clean it up after the 178 * userspace can send a valid response or we will clean it up after the
179 * timeout 179 * timeout
180 */ 180 */
181 switch (response) { 181 switch (response) {
182 case FAN_ALLOW: 182 case FAN_ALLOW:
183 case FAN_DENY: 183 case FAN_DENY:
184 break; 184 break;
185 default: 185 default:
186 return -EINVAL; 186 return -EINVAL;
187 } 187 }
188 188
189 if (fd < 0) 189 if (fd < 0)
190 return -EINVAL; 190 return -EINVAL;
191 191
192 event = dequeue_event(group, fd); 192 event = dequeue_event(group, fd);
193 if (!event) 193 if (!event)
194 return -ENOENT; 194 return -ENOENT;
195 195
196 event->response = response; 196 event->response = response;
197 wake_up(&group->fanotify_data.access_waitq); 197 wake_up(&group->fanotify_data.access_waitq);
198 198
199 return 0; 199 return 0;
200 } 200 }
201 #endif 201 #endif
202 202
203 static ssize_t copy_event_to_user(struct fsnotify_group *group, 203 static ssize_t copy_event_to_user(struct fsnotify_group *group,
204 struct fsnotify_event *event, 204 struct fsnotify_event *event,
205 char __user *buf) 205 char __user *buf)
206 { 206 {
207 struct fanotify_event_metadata fanotify_event_metadata; 207 struct fanotify_event_metadata fanotify_event_metadata;
208 struct file *f; 208 struct file *f;
209 int fd, ret; 209 int fd, ret;
210 210
211 pr_debug("%s: group=%p event=%p\n", __func__, group, event); 211 pr_debug("%s: group=%p event=%p\n", __func__, group, event);
212 212
213 ret = fill_event_metadata(group, &fanotify_event_metadata, event, &f); 213 ret = fill_event_metadata(group, &fanotify_event_metadata, event, &f);
214 if (ret < 0) 214 if (ret < 0)
215 return ret; 215 return ret;
216 216
217 fd = fanotify_event_metadata.fd; 217 fd = fanotify_event_metadata.fd;
218 ret = -EFAULT; 218 ret = -EFAULT;
219 if (copy_to_user(buf, &fanotify_event_metadata, 219 if (copy_to_user(buf, &fanotify_event_metadata,
220 fanotify_event_metadata.event_len)) 220 fanotify_event_metadata.event_len))
221 goto out_close_fd; 221 goto out_close_fd;
222 222
223 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS 223 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS
224 if (event->mask & FAN_ALL_PERM_EVENTS) 224 if (event->mask & FAN_ALL_PERM_EVENTS)
225 FANOTIFY_PE(event)->fd = fd; 225 FANOTIFY_PE(event)->fd = fd;
226 #endif 226 #endif
227 227
228 if (fd != FAN_NOFD) 228 if (fd != FAN_NOFD)
229 fd_install(fd, f); 229 fd_install(fd, f);
230 return fanotify_event_metadata.event_len; 230 return fanotify_event_metadata.event_len;
231 231
232 out_close_fd: 232 out_close_fd:
233 if (fd != FAN_NOFD) { 233 if (fd != FAN_NOFD) {
234 put_unused_fd(fd); 234 put_unused_fd(fd);
235 fput(f); 235 fput(f);
236 } 236 }
237 return ret; 237 return ret;
238 } 238 }
239 239
240 /* intofiy userspace file descriptor functions */ 240 /* intofiy userspace file descriptor functions */
241 static unsigned int fanotify_poll(struct file *file, poll_table *wait) 241 static unsigned int fanotify_poll(struct file *file, poll_table *wait)
242 { 242 {
243 struct fsnotify_group *group = file->private_data; 243 struct fsnotify_group *group = file->private_data;
244 int ret = 0; 244 int ret = 0;
245 245
246 poll_wait(file, &group->notification_waitq, wait); 246 poll_wait(file, &group->notification_waitq, wait);
247 mutex_lock(&group->notification_mutex); 247 mutex_lock(&group->notification_mutex);
248 if (!fsnotify_notify_queue_is_empty(group)) 248 if (!fsnotify_notify_queue_is_empty(group))
249 ret = POLLIN | POLLRDNORM; 249 ret = POLLIN | POLLRDNORM;
250 mutex_unlock(&group->notification_mutex); 250 mutex_unlock(&group->notification_mutex);
251 251
252 return ret; 252 return ret;
253 } 253 }
254 254
255 static ssize_t fanotify_read(struct file *file, char __user *buf, 255 static ssize_t fanotify_read(struct file *file, char __user *buf,
256 size_t count, loff_t *pos) 256 size_t count, loff_t *pos)
257 { 257 {
258 struct fsnotify_group *group; 258 struct fsnotify_group *group;
259 struct fsnotify_event *kevent; 259 struct fsnotify_event *kevent;
260 char __user *start; 260 char __user *start;
261 int ret; 261 int ret;
262 DEFINE_WAIT(wait); 262 DEFINE_WAIT_FUNC(wait, woken_wake_function);
263 263
264 start = buf; 264 start = buf;
265 group = file->private_data; 265 group = file->private_data;
266 266
267 pr_debug("%s: group=%p\n", __func__, group); 267 pr_debug("%s: group=%p\n", __func__, group);
268 268
269 add_wait_queue(&group->notification_waitq, &wait);
269 while (1) { 270 while (1) {
270 prepare_to_wait(&group->notification_waitq, &wait, TASK_INTERRUPTIBLE);
271
272 mutex_lock(&group->notification_mutex); 271 mutex_lock(&group->notification_mutex);
273 kevent = get_one_event(group, count); 272 kevent = get_one_event(group, count);
274 mutex_unlock(&group->notification_mutex); 273 mutex_unlock(&group->notification_mutex);
275 274
276 if (IS_ERR(kevent)) { 275 if (IS_ERR(kevent)) {
277 ret = PTR_ERR(kevent); 276 ret = PTR_ERR(kevent);
278 break; 277 break;
279 } 278 }
280 279
281 if (!kevent) { 280 if (!kevent) {
282 ret = -EAGAIN; 281 ret = -EAGAIN;
283 if (file->f_flags & O_NONBLOCK) 282 if (file->f_flags & O_NONBLOCK)
284 break; 283 break;
285 284
286 ret = -ERESTARTSYS; 285 ret = -ERESTARTSYS;
287 if (signal_pending(current)) 286 if (signal_pending(current))
288 break; 287 break;
289 288
290 if (start != buf) 289 if (start != buf)
291 break; 290 break;
292 schedule(); 291
292 wait_woken(&wait, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
293 continue; 293 continue;
294 } 294 }
295 295
296 ret = copy_event_to_user(group, kevent, buf); 296 ret = copy_event_to_user(group, kevent, buf);
297 /* 297 /*
298 * Permission events get queued to wait for response. Other 298 * Permission events get queued to wait for response. Other
299 * events can be destroyed now. 299 * events can be destroyed now.
300 */ 300 */
301 if (!(kevent->mask & FAN_ALL_PERM_EVENTS)) { 301 if (!(kevent->mask & FAN_ALL_PERM_EVENTS)) {
302 fsnotify_destroy_event(group, kevent); 302 fsnotify_destroy_event(group, kevent);
303 if (ret < 0) 303 if (ret < 0)
304 break; 304 break;
305 } else { 305 } else {
306 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS 306 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS
307 if (ret < 0) { 307 if (ret < 0) {
308 FANOTIFY_PE(kevent)->response = FAN_DENY; 308 FANOTIFY_PE(kevent)->response = FAN_DENY;
309 wake_up(&group->fanotify_data.access_waitq); 309 wake_up(&group->fanotify_data.access_waitq);
310 break; 310 break;
311 } 311 }
312 spin_lock(&group->fanotify_data.access_lock); 312 spin_lock(&group->fanotify_data.access_lock);
313 list_add_tail(&kevent->list, 313 list_add_tail(&kevent->list,
314 &group->fanotify_data.access_list); 314 &group->fanotify_data.access_list);
315 spin_unlock(&group->fanotify_data.access_lock); 315 spin_unlock(&group->fanotify_data.access_lock);
316 #endif 316 #endif
317 } 317 }
318 buf += ret; 318 buf += ret;
319 count -= ret; 319 count -= ret;
320 } 320 }
321 remove_wait_queue(&group->notification_waitq, &wait);
321 322
322 finish_wait(&group->notification_waitq, &wait);
323 if (start != buf && ret != -EFAULT) 323 if (start != buf && ret != -EFAULT)
324 ret = buf - start; 324 ret = buf - start;
325 return ret; 325 return ret;
326 } 326 }
327 327
328 static ssize_t fanotify_write(struct file *file, const char __user *buf, size_t count, loff_t *pos) 328 static ssize_t fanotify_write(struct file *file, const char __user *buf, size_t count, loff_t *pos)
329 { 329 {
330 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS 330 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS
331 struct fanotify_response response = { .fd = -1, .response = -1 }; 331 struct fanotify_response response = { .fd = -1, .response = -1 };
332 struct fsnotify_group *group; 332 struct fsnotify_group *group;
333 int ret; 333 int ret;
334 334
335 group = file->private_data; 335 group = file->private_data;
336 336
337 if (count > sizeof(response)) 337 if (count > sizeof(response))
338 count = sizeof(response); 338 count = sizeof(response);
339 339
340 pr_debug("%s: group=%p count=%zu\n", __func__, group, count); 340 pr_debug("%s: group=%p count=%zu\n", __func__, group, count);
341 341
342 if (copy_from_user(&response, buf, count)) 342 if (copy_from_user(&response, buf, count))
343 return -EFAULT; 343 return -EFAULT;
344 344
345 ret = process_access_response(group, &response); 345 ret = process_access_response(group, &response);
346 if (ret < 0) 346 if (ret < 0)
347 count = ret; 347 count = ret;
348 348
349 return count; 349 return count;
350 #else 350 #else
351 return -EINVAL; 351 return -EINVAL;
352 #endif 352 #endif
353 } 353 }
354 354
355 static int fanotify_release(struct inode *ignored, struct file *file) 355 static int fanotify_release(struct inode *ignored, struct file *file)
356 { 356 {
357 struct fsnotify_group *group = file->private_data; 357 struct fsnotify_group *group = file->private_data;
358 358
359 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS 359 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS
360 struct fanotify_perm_event_info *event, *next; 360 struct fanotify_perm_event_info *event, *next;
361 361
362 /* 362 /*
363 * There may be still new events arriving in the notification queue 363 * There may be still new events arriving in the notification queue
364 * but since userspace cannot use fanotify fd anymore, no event can 364 * but since userspace cannot use fanotify fd anymore, no event can
365 * enter or leave access_list by now. 365 * enter or leave access_list by now.
366 */ 366 */
367 spin_lock(&group->fanotify_data.access_lock); 367 spin_lock(&group->fanotify_data.access_lock);
368 368
369 atomic_inc(&group->fanotify_data.bypass_perm); 369 atomic_inc(&group->fanotify_data.bypass_perm);
370 370
371 list_for_each_entry_safe(event, next, &group->fanotify_data.access_list, 371 list_for_each_entry_safe(event, next, &group->fanotify_data.access_list,
372 fae.fse.list) { 372 fae.fse.list) {
373 pr_debug("%s: found group=%p event=%p\n", __func__, group, 373 pr_debug("%s: found group=%p event=%p\n", __func__, group,
374 event); 374 event);
375 375
376 list_del_init(&event->fae.fse.list); 376 list_del_init(&event->fae.fse.list);
377 event->response = FAN_ALLOW; 377 event->response = FAN_ALLOW;
378 } 378 }
379 spin_unlock(&group->fanotify_data.access_lock); 379 spin_unlock(&group->fanotify_data.access_lock);
380 380
381 /* 381 /*
382 * Since bypass_perm is set, newly queued events will not wait for 382 * Since bypass_perm is set, newly queued events will not wait for
383 * access response. Wake up the already sleeping ones now. 383 * access response. Wake up the already sleeping ones now.
384 * synchronize_srcu() in fsnotify_destroy_group() will wait for all 384 * synchronize_srcu() in fsnotify_destroy_group() will wait for all
385 * processes sleeping in fanotify_handle_event() waiting for access 385 * processes sleeping in fanotify_handle_event() waiting for access
386 * response and thus also for all permission events to be freed. 386 * response and thus also for all permission events to be freed.
387 */ 387 */
388 wake_up(&group->fanotify_data.access_waitq); 388 wake_up(&group->fanotify_data.access_waitq);
389 #endif 389 #endif
390 390
391 /* matches the fanotify_init->fsnotify_alloc_group */ 391 /* matches the fanotify_init->fsnotify_alloc_group */
392 fsnotify_destroy_group(group); 392 fsnotify_destroy_group(group);
393 393
394 return 0; 394 return 0;
395 } 395 }
396 396
397 static long fanotify_ioctl(struct file *file, unsigned int cmd, unsigned long arg) 397 static long fanotify_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
398 { 398 {
399 struct fsnotify_group *group; 399 struct fsnotify_group *group;
400 struct fsnotify_event *fsn_event; 400 struct fsnotify_event *fsn_event;
401 void __user *p; 401 void __user *p;
402 int ret = -ENOTTY; 402 int ret = -ENOTTY;
403 size_t send_len = 0; 403 size_t send_len = 0;
404 404
405 group = file->private_data; 405 group = file->private_data;
406 406
407 p = (void __user *) arg; 407 p = (void __user *) arg;
408 408
409 switch (cmd) { 409 switch (cmd) {
410 case FIONREAD: 410 case FIONREAD:
411 mutex_lock(&group->notification_mutex); 411 mutex_lock(&group->notification_mutex);
412 list_for_each_entry(fsn_event, &group->notification_list, list) 412 list_for_each_entry(fsn_event, &group->notification_list, list)
413 send_len += FAN_EVENT_METADATA_LEN; 413 send_len += FAN_EVENT_METADATA_LEN;
414 mutex_unlock(&group->notification_mutex); 414 mutex_unlock(&group->notification_mutex);
415 ret = put_user(send_len, (int __user *) p); 415 ret = put_user(send_len, (int __user *) p);
416 break; 416 break;
417 } 417 }
418 418
419 return ret; 419 return ret;
420 } 420 }
421 421
422 static const struct file_operations fanotify_fops = { 422 static const struct file_operations fanotify_fops = {
423 .show_fdinfo = fanotify_show_fdinfo, 423 .show_fdinfo = fanotify_show_fdinfo,
424 .poll = fanotify_poll, 424 .poll = fanotify_poll,
425 .read = fanotify_read, 425 .read = fanotify_read,
426 .write = fanotify_write, 426 .write = fanotify_write,
427 .fasync = NULL, 427 .fasync = NULL,
428 .release = fanotify_release, 428 .release = fanotify_release,
429 .unlocked_ioctl = fanotify_ioctl, 429 .unlocked_ioctl = fanotify_ioctl,
430 .compat_ioctl = fanotify_ioctl, 430 .compat_ioctl = fanotify_ioctl,
431 .llseek = noop_llseek, 431 .llseek = noop_llseek,
432 }; 432 };
433 433
434 static void fanotify_free_mark(struct fsnotify_mark *fsn_mark) 434 static void fanotify_free_mark(struct fsnotify_mark *fsn_mark)
435 { 435 {
436 kmem_cache_free(fanotify_mark_cache, fsn_mark); 436 kmem_cache_free(fanotify_mark_cache, fsn_mark);
437 } 437 }
438 438
439 static int fanotify_find_path(int dfd, const char __user *filename, 439 static int fanotify_find_path(int dfd, const char __user *filename,
440 struct path *path, unsigned int flags) 440 struct path *path, unsigned int flags)
441 { 441 {
442 int ret; 442 int ret;
443 443
444 pr_debug("%s: dfd=%d filename=%p flags=%x\n", __func__, 444 pr_debug("%s: dfd=%d filename=%p flags=%x\n", __func__,
445 dfd, filename, flags); 445 dfd, filename, flags);
446 446
447 if (filename == NULL) { 447 if (filename == NULL) {
448 struct fd f = fdget(dfd); 448 struct fd f = fdget(dfd);
449 449
450 ret = -EBADF; 450 ret = -EBADF;
451 if (!f.file) 451 if (!f.file)
452 goto out; 452 goto out;
453 453
454 ret = -ENOTDIR; 454 ret = -ENOTDIR;
455 if ((flags & FAN_MARK_ONLYDIR) && 455 if ((flags & FAN_MARK_ONLYDIR) &&
456 !(S_ISDIR(file_inode(f.file)->i_mode))) { 456 !(S_ISDIR(file_inode(f.file)->i_mode))) {
457 fdput(f); 457 fdput(f);
458 goto out; 458 goto out;
459 } 459 }
460 460
461 *path = f.file->f_path; 461 *path = f.file->f_path;
462 path_get(path); 462 path_get(path);
463 fdput(f); 463 fdput(f);
464 } else { 464 } else {
465 unsigned int lookup_flags = 0; 465 unsigned int lookup_flags = 0;
466 466
467 if (!(flags & FAN_MARK_DONT_FOLLOW)) 467 if (!(flags & FAN_MARK_DONT_FOLLOW))
468 lookup_flags |= LOOKUP_FOLLOW; 468 lookup_flags |= LOOKUP_FOLLOW;
469 if (flags & FAN_MARK_ONLYDIR) 469 if (flags & FAN_MARK_ONLYDIR)
470 lookup_flags |= LOOKUP_DIRECTORY; 470 lookup_flags |= LOOKUP_DIRECTORY;
471 471
472 ret = user_path_at(dfd, filename, lookup_flags, path); 472 ret = user_path_at(dfd, filename, lookup_flags, path);
473 if (ret) 473 if (ret)
474 goto out; 474 goto out;
475 } 475 }
476 476
477 /* you can only watch an inode if you have read permissions on it */ 477 /* you can only watch an inode if you have read permissions on it */
478 ret = inode_permission(path->dentry->d_inode, MAY_READ); 478 ret = inode_permission(path->dentry->d_inode, MAY_READ);
479 if (ret) 479 if (ret)
480 path_put(path); 480 path_put(path);
481 out: 481 out:
482 return ret; 482 return ret;
483 } 483 }
484 484
485 static __u32 fanotify_mark_remove_from_mask(struct fsnotify_mark *fsn_mark, 485 static __u32 fanotify_mark_remove_from_mask(struct fsnotify_mark *fsn_mark,
486 __u32 mask, 486 __u32 mask,
487 unsigned int flags, 487 unsigned int flags,
488 int *destroy) 488 int *destroy)
489 { 489 {
490 __u32 oldmask; 490 __u32 oldmask;
491 491
492 spin_lock(&fsn_mark->lock); 492 spin_lock(&fsn_mark->lock);
493 if (!(flags & FAN_MARK_IGNORED_MASK)) { 493 if (!(flags & FAN_MARK_IGNORED_MASK)) {
494 oldmask = fsn_mark->mask; 494 oldmask = fsn_mark->mask;
495 fsnotify_set_mark_mask_locked(fsn_mark, (oldmask & ~mask)); 495 fsnotify_set_mark_mask_locked(fsn_mark, (oldmask & ~mask));
496 } else { 496 } else {
497 oldmask = fsn_mark->ignored_mask; 497 oldmask = fsn_mark->ignored_mask;
498 fsnotify_set_mark_ignored_mask_locked(fsn_mark, (oldmask & ~mask)); 498 fsnotify_set_mark_ignored_mask_locked(fsn_mark, (oldmask & ~mask));
499 } 499 }
500 spin_unlock(&fsn_mark->lock); 500 spin_unlock(&fsn_mark->lock);
501 501
502 *destroy = !(oldmask & ~mask); 502 *destroy = !(oldmask & ~mask);
503 503
504 return mask & oldmask; 504 return mask & oldmask;
505 } 505 }
506 506
507 static int fanotify_remove_vfsmount_mark(struct fsnotify_group *group, 507 static int fanotify_remove_vfsmount_mark(struct fsnotify_group *group,
508 struct vfsmount *mnt, __u32 mask, 508 struct vfsmount *mnt, __u32 mask,
509 unsigned int flags) 509 unsigned int flags)
510 { 510 {
511 struct fsnotify_mark *fsn_mark = NULL; 511 struct fsnotify_mark *fsn_mark = NULL;
512 __u32 removed; 512 __u32 removed;
513 int destroy_mark; 513 int destroy_mark;
514 514
515 mutex_lock(&group->mark_mutex); 515 mutex_lock(&group->mark_mutex);
516 fsn_mark = fsnotify_find_vfsmount_mark(group, mnt); 516 fsn_mark = fsnotify_find_vfsmount_mark(group, mnt);
517 if (!fsn_mark) { 517 if (!fsn_mark) {
518 mutex_unlock(&group->mark_mutex); 518 mutex_unlock(&group->mark_mutex);
519 return -ENOENT; 519 return -ENOENT;
520 } 520 }
521 521
522 removed = fanotify_mark_remove_from_mask(fsn_mark, mask, flags, 522 removed = fanotify_mark_remove_from_mask(fsn_mark, mask, flags,
523 &destroy_mark); 523 &destroy_mark);
524 if (destroy_mark) 524 if (destroy_mark)
525 fsnotify_destroy_mark_locked(fsn_mark, group); 525 fsnotify_destroy_mark_locked(fsn_mark, group);
526 mutex_unlock(&group->mark_mutex); 526 mutex_unlock(&group->mark_mutex);
527 527
528 fsnotify_put_mark(fsn_mark); 528 fsnotify_put_mark(fsn_mark);
529 if (removed & real_mount(mnt)->mnt_fsnotify_mask) 529 if (removed & real_mount(mnt)->mnt_fsnotify_mask)
530 fsnotify_recalc_vfsmount_mask(mnt); 530 fsnotify_recalc_vfsmount_mask(mnt);
531 531
532 return 0; 532 return 0;
533 } 533 }
534 534
535 static int fanotify_remove_inode_mark(struct fsnotify_group *group, 535 static int fanotify_remove_inode_mark(struct fsnotify_group *group,
536 struct inode *inode, __u32 mask, 536 struct inode *inode, __u32 mask,
537 unsigned int flags) 537 unsigned int flags)
538 { 538 {
539 struct fsnotify_mark *fsn_mark = NULL; 539 struct fsnotify_mark *fsn_mark = NULL;
540 __u32 removed; 540 __u32 removed;
541 int destroy_mark; 541 int destroy_mark;
542 542
543 mutex_lock(&group->mark_mutex); 543 mutex_lock(&group->mark_mutex);
544 fsn_mark = fsnotify_find_inode_mark(group, inode); 544 fsn_mark = fsnotify_find_inode_mark(group, inode);
545 if (!fsn_mark) { 545 if (!fsn_mark) {
546 mutex_unlock(&group->mark_mutex); 546 mutex_unlock(&group->mark_mutex);
547 return -ENOENT; 547 return -ENOENT;
548 } 548 }
549 549
550 removed = fanotify_mark_remove_from_mask(fsn_mark, mask, flags, 550 removed = fanotify_mark_remove_from_mask(fsn_mark, mask, flags,
551 &destroy_mark); 551 &destroy_mark);
552 if (destroy_mark) 552 if (destroy_mark)
553 fsnotify_destroy_mark_locked(fsn_mark, group); 553 fsnotify_destroy_mark_locked(fsn_mark, group);
554 mutex_unlock(&group->mark_mutex); 554 mutex_unlock(&group->mark_mutex);
555 555
556 /* matches the fsnotify_find_inode_mark() */ 556 /* matches the fsnotify_find_inode_mark() */
557 fsnotify_put_mark(fsn_mark); 557 fsnotify_put_mark(fsn_mark);
558 if (removed & inode->i_fsnotify_mask) 558 if (removed & inode->i_fsnotify_mask)
559 fsnotify_recalc_inode_mask(inode); 559 fsnotify_recalc_inode_mask(inode);
560 560
561 return 0; 561 return 0;
562 } 562 }
563 563
564 static __u32 fanotify_mark_add_to_mask(struct fsnotify_mark *fsn_mark, 564 static __u32 fanotify_mark_add_to_mask(struct fsnotify_mark *fsn_mark,
565 __u32 mask, 565 __u32 mask,
566 unsigned int flags) 566 unsigned int flags)
567 { 567 {
568 __u32 oldmask = -1; 568 __u32 oldmask = -1;
569 569
570 spin_lock(&fsn_mark->lock); 570 spin_lock(&fsn_mark->lock);
571 if (!(flags & FAN_MARK_IGNORED_MASK)) { 571 if (!(flags & FAN_MARK_IGNORED_MASK)) {
572 oldmask = fsn_mark->mask; 572 oldmask = fsn_mark->mask;
573 fsnotify_set_mark_mask_locked(fsn_mark, (oldmask | mask)); 573 fsnotify_set_mark_mask_locked(fsn_mark, (oldmask | mask));
574 } else { 574 } else {
575 __u32 tmask = fsn_mark->ignored_mask | mask; 575 __u32 tmask = fsn_mark->ignored_mask | mask;
576 fsnotify_set_mark_ignored_mask_locked(fsn_mark, tmask); 576 fsnotify_set_mark_ignored_mask_locked(fsn_mark, tmask);
577 if (flags & FAN_MARK_IGNORED_SURV_MODIFY) 577 if (flags & FAN_MARK_IGNORED_SURV_MODIFY)
578 fsn_mark->flags |= FSNOTIFY_MARK_FLAG_IGNORED_SURV_MODIFY; 578 fsn_mark->flags |= FSNOTIFY_MARK_FLAG_IGNORED_SURV_MODIFY;
579 } 579 }
580 580
581 if (!(flags & FAN_MARK_ONDIR)) { 581 if (!(flags & FAN_MARK_ONDIR)) {
582 __u32 tmask = fsn_mark->ignored_mask | FAN_ONDIR; 582 __u32 tmask = fsn_mark->ignored_mask | FAN_ONDIR;
583 fsnotify_set_mark_ignored_mask_locked(fsn_mark, tmask); 583 fsnotify_set_mark_ignored_mask_locked(fsn_mark, tmask);
584 } 584 }
585 585
586 spin_unlock(&fsn_mark->lock); 586 spin_unlock(&fsn_mark->lock);
587 587
588 return mask & ~oldmask; 588 return mask & ~oldmask;
589 } 589 }
590 590
591 static struct fsnotify_mark *fanotify_add_new_mark(struct fsnotify_group *group, 591 static struct fsnotify_mark *fanotify_add_new_mark(struct fsnotify_group *group,
592 struct inode *inode, 592 struct inode *inode,
593 struct vfsmount *mnt) 593 struct vfsmount *mnt)
594 { 594 {
595 struct fsnotify_mark *mark; 595 struct fsnotify_mark *mark;
596 int ret; 596 int ret;
597 597
598 if (atomic_read(&group->num_marks) > group->fanotify_data.max_marks) 598 if (atomic_read(&group->num_marks) > group->fanotify_data.max_marks)
599 return ERR_PTR(-ENOSPC); 599 return ERR_PTR(-ENOSPC);
600 600
601 mark = kmem_cache_alloc(fanotify_mark_cache, GFP_KERNEL); 601 mark = kmem_cache_alloc(fanotify_mark_cache, GFP_KERNEL);
602 if (!mark) 602 if (!mark)
603 return ERR_PTR(-ENOMEM); 603 return ERR_PTR(-ENOMEM);
604 604
605 fsnotify_init_mark(mark, fanotify_free_mark); 605 fsnotify_init_mark(mark, fanotify_free_mark);
606 ret = fsnotify_add_mark_locked(mark, group, inode, mnt, 0); 606 ret = fsnotify_add_mark_locked(mark, group, inode, mnt, 0);
607 if (ret) { 607 if (ret) {
608 fsnotify_put_mark(mark); 608 fsnotify_put_mark(mark);
609 return ERR_PTR(ret); 609 return ERR_PTR(ret);
610 } 610 }
611 611
612 return mark; 612 return mark;
613 } 613 }
614 614
615 615
616 static int fanotify_add_vfsmount_mark(struct fsnotify_group *group, 616 static int fanotify_add_vfsmount_mark(struct fsnotify_group *group,
617 struct vfsmount *mnt, __u32 mask, 617 struct vfsmount *mnt, __u32 mask,
618 unsigned int flags) 618 unsigned int flags)
619 { 619 {
620 struct fsnotify_mark *fsn_mark; 620 struct fsnotify_mark *fsn_mark;
621 __u32 added; 621 __u32 added;
622 622
623 mutex_lock(&group->mark_mutex); 623 mutex_lock(&group->mark_mutex);
624 fsn_mark = fsnotify_find_vfsmount_mark(group, mnt); 624 fsn_mark = fsnotify_find_vfsmount_mark(group, mnt);
625 if (!fsn_mark) { 625 if (!fsn_mark) {
626 fsn_mark = fanotify_add_new_mark(group, NULL, mnt); 626 fsn_mark = fanotify_add_new_mark(group, NULL, mnt);
627 if (IS_ERR(fsn_mark)) { 627 if (IS_ERR(fsn_mark)) {
628 mutex_unlock(&group->mark_mutex); 628 mutex_unlock(&group->mark_mutex);
629 return PTR_ERR(fsn_mark); 629 return PTR_ERR(fsn_mark);
630 } 630 }
631 } 631 }
632 added = fanotify_mark_add_to_mask(fsn_mark, mask, flags); 632 added = fanotify_mark_add_to_mask(fsn_mark, mask, flags);
633 mutex_unlock(&group->mark_mutex); 633 mutex_unlock(&group->mark_mutex);
634 634
635 if (added & ~real_mount(mnt)->mnt_fsnotify_mask) 635 if (added & ~real_mount(mnt)->mnt_fsnotify_mask)
636 fsnotify_recalc_vfsmount_mask(mnt); 636 fsnotify_recalc_vfsmount_mask(mnt);
637 637
638 fsnotify_put_mark(fsn_mark); 638 fsnotify_put_mark(fsn_mark);
639 return 0; 639 return 0;
640 } 640 }
641 641
642 static int fanotify_add_inode_mark(struct fsnotify_group *group, 642 static int fanotify_add_inode_mark(struct fsnotify_group *group,
643 struct inode *inode, __u32 mask, 643 struct inode *inode, __u32 mask,
644 unsigned int flags) 644 unsigned int flags)
645 { 645 {
646 struct fsnotify_mark *fsn_mark; 646 struct fsnotify_mark *fsn_mark;
647 __u32 added; 647 __u32 added;
648 648
649 pr_debug("%s: group=%p inode=%p\n", __func__, group, inode); 649 pr_debug("%s: group=%p inode=%p\n", __func__, group, inode);
650 650
651 /* 651 /*
652 * If some other task has this inode open for write we should not add 652 * If some other task has this inode open for write we should not add
653 * an ignored mark, unless that ignored mark is supposed to survive 653 * an ignored mark, unless that ignored mark is supposed to survive
654 * modification changes anyway. 654 * modification changes anyway.
655 */ 655 */
656 if ((flags & FAN_MARK_IGNORED_MASK) && 656 if ((flags & FAN_MARK_IGNORED_MASK) &&
657 !(flags & FAN_MARK_IGNORED_SURV_MODIFY) && 657 !(flags & FAN_MARK_IGNORED_SURV_MODIFY) &&
658 (atomic_read(&inode->i_writecount) > 0)) 658 (atomic_read(&inode->i_writecount) > 0))
659 return 0; 659 return 0;
660 660
661 mutex_lock(&group->mark_mutex); 661 mutex_lock(&group->mark_mutex);
662 fsn_mark = fsnotify_find_inode_mark(group, inode); 662 fsn_mark = fsnotify_find_inode_mark(group, inode);
663 if (!fsn_mark) { 663 if (!fsn_mark) {
664 fsn_mark = fanotify_add_new_mark(group, inode, NULL); 664 fsn_mark = fanotify_add_new_mark(group, inode, NULL);
665 if (IS_ERR(fsn_mark)) { 665 if (IS_ERR(fsn_mark)) {
666 mutex_unlock(&group->mark_mutex); 666 mutex_unlock(&group->mark_mutex);
667 return PTR_ERR(fsn_mark); 667 return PTR_ERR(fsn_mark);
668 } 668 }
669 } 669 }
670 added = fanotify_mark_add_to_mask(fsn_mark, mask, flags); 670 added = fanotify_mark_add_to_mask(fsn_mark, mask, flags);
671 mutex_unlock(&group->mark_mutex); 671 mutex_unlock(&group->mark_mutex);
672 672
673 if (added & ~inode->i_fsnotify_mask) 673 if (added & ~inode->i_fsnotify_mask)
674 fsnotify_recalc_inode_mask(inode); 674 fsnotify_recalc_inode_mask(inode);
675 675
676 fsnotify_put_mark(fsn_mark); 676 fsnotify_put_mark(fsn_mark);
677 return 0; 677 return 0;
678 } 678 }
679 679
680 /* fanotify syscalls */ 680 /* fanotify syscalls */
681 SYSCALL_DEFINE2(fanotify_init, unsigned int, flags, unsigned int, event_f_flags) 681 SYSCALL_DEFINE2(fanotify_init, unsigned int, flags, unsigned int, event_f_flags)
682 { 682 {
683 struct fsnotify_group *group; 683 struct fsnotify_group *group;
684 int f_flags, fd; 684 int f_flags, fd;
685 struct user_struct *user; 685 struct user_struct *user;
686 struct fanotify_event_info *oevent; 686 struct fanotify_event_info *oevent;
687 687
688 pr_debug("%s: flags=%d event_f_flags=%d\n", 688 pr_debug("%s: flags=%d event_f_flags=%d\n",
689 __func__, flags, event_f_flags); 689 __func__, flags, event_f_flags);
690 690
691 if (!capable(CAP_SYS_ADMIN)) 691 if (!capable(CAP_SYS_ADMIN))
692 return -EPERM; 692 return -EPERM;
693 693
694 if (flags & ~FAN_ALL_INIT_FLAGS) 694 if (flags & ~FAN_ALL_INIT_FLAGS)
695 return -EINVAL; 695 return -EINVAL;
696 696
697 if (event_f_flags & ~FANOTIFY_INIT_ALL_EVENT_F_BITS) 697 if (event_f_flags & ~FANOTIFY_INIT_ALL_EVENT_F_BITS)
698 return -EINVAL; 698 return -EINVAL;
699 699
700 switch (event_f_flags & O_ACCMODE) { 700 switch (event_f_flags & O_ACCMODE) {
701 case O_RDONLY: 701 case O_RDONLY:
702 case O_RDWR: 702 case O_RDWR:
703 case O_WRONLY: 703 case O_WRONLY:
704 break; 704 break;
705 default: 705 default:
706 return -EINVAL; 706 return -EINVAL;
707 } 707 }
708 708
709 user = get_current_user(); 709 user = get_current_user();
710 if (atomic_read(&user->fanotify_listeners) > FANOTIFY_DEFAULT_MAX_LISTENERS) { 710 if (atomic_read(&user->fanotify_listeners) > FANOTIFY_DEFAULT_MAX_LISTENERS) {
711 free_uid(user); 711 free_uid(user);
712 return -EMFILE; 712 return -EMFILE;
713 } 713 }
714 714
715 f_flags = O_RDWR | FMODE_NONOTIFY; 715 f_flags = O_RDWR | FMODE_NONOTIFY;
716 if (flags & FAN_CLOEXEC) 716 if (flags & FAN_CLOEXEC)
717 f_flags |= O_CLOEXEC; 717 f_flags |= O_CLOEXEC;
718 if (flags & FAN_NONBLOCK) 718 if (flags & FAN_NONBLOCK)
719 f_flags |= O_NONBLOCK; 719 f_flags |= O_NONBLOCK;
720 720
721 /* fsnotify_alloc_group takes a ref. Dropped in fanotify_release */ 721 /* fsnotify_alloc_group takes a ref. Dropped in fanotify_release */
722 group = fsnotify_alloc_group(&fanotify_fsnotify_ops); 722 group = fsnotify_alloc_group(&fanotify_fsnotify_ops);
723 if (IS_ERR(group)) { 723 if (IS_ERR(group)) {
724 free_uid(user); 724 free_uid(user);
725 return PTR_ERR(group); 725 return PTR_ERR(group);
726 } 726 }
727 727
728 group->fanotify_data.user = user; 728 group->fanotify_data.user = user;
729 atomic_inc(&user->fanotify_listeners); 729 atomic_inc(&user->fanotify_listeners);
730 730
731 oevent = fanotify_alloc_event(NULL, FS_Q_OVERFLOW, NULL); 731 oevent = fanotify_alloc_event(NULL, FS_Q_OVERFLOW, NULL);
732 if (unlikely(!oevent)) { 732 if (unlikely(!oevent)) {
733 fd = -ENOMEM; 733 fd = -ENOMEM;
734 goto out_destroy_group; 734 goto out_destroy_group;
735 } 735 }
736 group->overflow_event = &oevent->fse; 736 group->overflow_event = &oevent->fse;
737 737
738 if (force_o_largefile()) 738 if (force_o_largefile())
739 event_f_flags |= O_LARGEFILE; 739 event_f_flags |= O_LARGEFILE;
740 group->fanotify_data.f_flags = event_f_flags; 740 group->fanotify_data.f_flags = event_f_flags;
741 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS 741 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS
742 spin_lock_init(&group->fanotify_data.access_lock); 742 spin_lock_init(&group->fanotify_data.access_lock);
743 init_waitqueue_head(&group->fanotify_data.access_waitq); 743 init_waitqueue_head(&group->fanotify_data.access_waitq);
744 INIT_LIST_HEAD(&group->fanotify_data.access_list); 744 INIT_LIST_HEAD(&group->fanotify_data.access_list);
745 atomic_set(&group->fanotify_data.bypass_perm, 0); 745 atomic_set(&group->fanotify_data.bypass_perm, 0);
746 #endif 746 #endif
747 switch (flags & FAN_ALL_CLASS_BITS) { 747 switch (flags & FAN_ALL_CLASS_BITS) {
748 case FAN_CLASS_NOTIF: 748 case FAN_CLASS_NOTIF:
749 group->priority = FS_PRIO_0; 749 group->priority = FS_PRIO_0;
750 break; 750 break;
751 case FAN_CLASS_CONTENT: 751 case FAN_CLASS_CONTENT:
752 group->priority = FS_PRIO_1; 752 group->priority = FS_PRIO_1;
753 break; 753 break;
754 case FAN_CLASS_PRE_CONTENT: 754 case FAN_CLASS_PRE_CONTENT:
755 group->priority = FS_PRIO_2; 755 group->priority = FS_PRIO_2;
756 break; 756 break;
757 default: 757 default:
758 fd = -EINVAL; 758 fd = -EINVAL;
759 goto out_destroy_group; 759 goto out_destroy_group;
760 } 760 }
761 761
762 if (flags & FAN_UNLIMITED_QUEUE) { 762 if (flags & FAN_UNLIMITED_QUEUE) {
763 fd = -EPERM; 763 fd = -EPERM;
764 if (!capable(CAP_SYS_ADMIN)) 764 if (!capable(CAP_SYS_ADMIN))
765 goto out_destroy_group; 765 goto out_destroy_group;
766 group->max_events = UINT_MAX; 766 group->max_events = UINT_MAX;
767 } else { 767 } else {
768 group->max_events = FANOTIFY_DEFAULT_MAX_EVENTS; 768 group->max_events = FANOTIFY_DEFAULT_MAX_EVENTS;
769 } 769 }
770 770
771 if (flags & FAN_UNLIMITED_MARKS) { 771 if (flags & FAN_UNLIMITED_MARKS) {
772 fd = -EPERM; 772 fd = -EPERM;
773 if (!capable(CAP_SYS_ADMIN)) 773 if (!capable(CAP_SYS_ADMIN))
774 goto out_destroy_group; 774 goto out_destroy_group;
775 group->fanotify_data.max_marks = UINT_MAX; 775 group->fanotify_data.max_marks = UINT_MAX;
776 } else { 776 } else {
777 group->fanotify_data.max_marks = FANOTIFY_DEFAULT_MAX_MARKS; 777 group->fanotify_data.max_marks = FANOTIFY_DEFAULT_MAX_MARKS;
778 } 778 }
779 779
780 fd = anon_inode_getfd("[fanotify]", &fanotify_fops, group, f_flags); 780 fd = anon_inode_getfd("[fanotify]", &fanotify_fops, group, f_flags);
781 if (fd < 0) 781 if (fd < 0)
782 goto out_destroy_group; 782 goto out_destroy_group;
783 783
784 return fd; 784 return fd;
785 785
786 out_destroy_group: 786 out_destroy_group:
787 fsnotify_destroy_group(group); 787 fsnotify_destroy_group(group);
788 return fd; 788 return fd;
789 } 789 }
790 790
791 SYSCALL_DEFINE5(fanotify_mark, int, fanotify_fd, unsigned int, flags, 791 SYSCALL_DEFINE5(fanotify_mark, int, fanotify_fd, unsigned int, flags,
792 __u64, mask, int, dfd, 792 __u64, mask, int, dfd,
793 const char __user *, pathname) 793 const char __user *, pathname)
794 { 794 {
795 struct inode *inode = NULL; 795 struct inode *inode = NULL;
796 struct vfsmount *mnt = NULL; 796 struct vfsmount *mnt = NULL;
797 struct fsnotify_group *group; 797 struct fsnotify_group *group;
798 struct fd f; 798 struct fd f;
799 struct path path; 799 struct path path;
800 int ret; 800 int ret;
801 801
802 pr_debug("%s: fanotify_fd=%d flags=%x dfd=%d pathname=%p mask=%llx\n", 802 pr_debug("%s: fanotify_fd=%d flags=%x dfd=%d pathname=%p mask=%llx\n",
803 __func__, fanotify_fd, flags, dfd, pathname, mask); 803 __func__, fanotify_fd, flags, dfd, pathname, mask);
804 804
805 /* we only use the lower 32 bits as of right now. */ 805 /* we only use the lower 32 bits as of right now. */
806 if (mask & ((__u64)0xffffffff << 32)) 806 if (mask & ((__u64)0xffffffff << 32))
807 return -EINVAL; 807 return -EINVAL;
808 808
809 if (flags & ~FAN_ALL_MARK_FLAGS) 809 if (flags & ~FAN_ALL_MARK_FLAGS)
810 return -EINVAL; 810 return -EINVAL;
811 switch (flags & (FAN_MARK_ADD | FAN_MARK_REMOVE | FAN_MARK_FLUSH)) { 811 switch (flags & (FAN_MARK_ADD | FAN_MARK_REMOVE | FAN_MARK_FLUSH)) {
812 case FAN_MARK_ADD: /* fallthrough */ 812 case FAN_MARK_ADD: /* fallthrough */
813 case FAN_MARK_REMOVE: 813 case FAN_MARK_REMOVE:
814 if (!mask) 814 if (!mask)
815 return -EINVAL; 815 return -EINVAL;
816 break; 816 break;
817 case FAN_MARK_FLUSH: 817 case FAN_MARK_FLUSH:
818 if (flags & ~(FAN_MARK_MOUNT | FAN_MARK_FLUSH)) 818 if (flags & ~(FAN_MARK_MOUNT | FAN_MARK_FLUSH))
819 return -EINVAL; 819 return -EINVAL;
820 break; 820 break;
821 default: 821 default:
822 return -EINVAL; 822 return -EINVAL;
823 } 823 }
824 824
825 if (mask & FAN_ONDIR) { 825 if (mask & FAN_ONDIR) {
826 flags |= FAN_MARK_ONDIR; 826 flags |= FAN_MARK_ONDIR;
827 mask &= ~FAN_ONDIR; 827 mask &= ~FAN_ONDIR;
828 } 828 }
829 829
830 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS 830 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS
831 if (mask & ~(FAN_ALL_EVENTS | FAN_ALL_PERM_EVENTS | FAN_EVENT_ON_CHILD)) 831 if (mask & ~(FAN_ALL_EVENTS | FAN_ALL_PERM_EVENTS | FAN_EVENT_ON_CHILD))
832 #else 832 #else
833 if (mask & ~(FAN_ALL_EVENTS | FAN_EVENT_ON_CHILD)) 833 if (mask & ~(FAN_ALL_EVENTS | FAN_EVENT_ON_CHILD))
834 #endif 834 #endif
835 return -EINVAL; 835 return -EINVAL;
836 836
837 f = fdget(fanotify_fd); 837 f = fdget(fanotify_fd);
838 if (unlikely(!f.file)) 838 if (unlikely(!f.file))
839 return -EBADF; 839 return -EBADF;
840 840
841 /* verify that this is indeed an fanotify instance */ 841 /* verify that this is indeed an fanotify instance */
842 ret = -EINVAL; 842 ret = -EINVAL;
843 if (unlikely(f.file->f_op != &fanotify_fops)) 843 if (unlikely(f.file->f_op != &fanotify_fops))
844 goto fput_and_out; 844 goto fput_and_out;
845 group = f.file->private_data; 845 group = f.file->private_data;
846 846
847 /* 847 /*
848 * group->priority == FS_PRIO_0 == FAN_CLASS_NOTIF. These are not 848 * group->priority == FS_PRIO_0 == FAN_CLASS_NOTIF. These are not
849 * allowed to set permissions events. 849 * allowed to set permissions events.
850 */ 850 */
851 ret = -EINVAL; 851 ret = -EINVAL;
852 if (mask & FAN_ALL_PERM_EVENTS && 852 if (mask & FAN_ALL_PERM_EVENTS &&
853 group->priority == FS_PRIO_0) 853 group->priority == FS_PRIO_0)
854 goto fput_and_out; 854 goto fput_and_out;
855 855
856 if (flags & FAN_MARK_FLUSH) { 856 if (flags & FAN_MARK_FLUSH) {
857 ret = 0; 857 ret = 0;
858 if (flags & FAN_MARK_MOUNT) 858 if (flags & FAN_MARK_MOUNT)
859 fsnotify_clear_vfsmount_marks_by_group(group); 859 fsnotify_clear_vfsmount_marks_by_group(group);
860 else 860 else
861 fsnotify_clear_inode_marks_by_group(group); 861 fsnotify_clear_inode_marks_by_group(group);
862 goto fput_and_out; 862 goto fput_and_out;
863 } 863 }
864 864
865 ret = fanotify_find_path(dfd, pathname, &path, flags); 865 ret = fanotify_find_path(dfd, pathname, &path, flags);
866 if (ret) 866 if (ret)
867 goto fput_and_out; 867 goto fput_and_out;
868 868
869 /* inode held in place by reference to path; group by fget on fd */ 869 /* inode held in place by reference to path; group by fget on fd */
870 if (!(flags & FAN_MARK_MOUNT)) 870 if (!(flags & FAN_MARK_MOUNT))
871 inode = path.dentry->d_inode; 871 inode = path.dentry->d_inode;
872 else 872 else
873 mnt = path.mnt; 873 mnt = path.mnt;
874 874
875 /* create/update an inode mark */ 875 /* create/update an inode mark */
876 switch (flags & (FAN_MARK_ADD | FAN_MARK_REMOVE)) { 876 switch (flags & (FAN_MARK_ADD | FAN_MARK_REMOVE)) {
877 case FAN_MARK_ADD: 877 case FAN_MARK_ADD:
878 if (flags & FAN_MARK_MOUNT) 878 if (flags & FAN_MARK_MOUNT)
879 ret = fanotify_add_vfsmount_mark(group, mnt, mask, flags); 879 ret = fanotify_add_vfsmount_mark(group, mnt, mask, flags);
880 else 880 else
881 ret = fanotify_add_inode_mark(group, inode, mask, flags); 881 ret = fanotify_add_inode_mark(group, inode, mask, flags);
882 break; 882 break;
883 case FAN_MARK_REMOVE: 883 case FAN_MARK_REMOVE:
884 if (flags & FAN_MARK_MOUNT) 884 if (flags & FAN_MARK_MOUNT)
885 ret = fanotify_remove_vfsmount_mark(group, mnt, mask, flags); 885 ret = fanotify_remove_vfsmount_mark(group, mnt, mask, flags);
886 else 886 else
887 ret = fanotify_remove_inode_mark(group, inode, mask, flags); 887 ret = fanotify_remove_inode_mark(group, inode, mask, flags);
888 break; 888 break;
889 default: 889 default:
890 ret = -EINVAL; 890 ret = -EINVAL;
891 } 891 }
892 892
893 path_put(&path); 893 path_put(&path);
894 fput_and_out: 894 fput_and_out:
895 fdput(f); 895 fdput(f);
896 return ret; 896 return ret;
897 } 897 }
898 898
899 #ifdef CONFIG_COMPAT 899 #ifdef CONFIG_COMPAT
900 COMPAT_SYSCALL_DEFINE6(fanotify_mark, 900 COMPAT_SYSCALL_DEFINE6(fanotify_mark,
901 int, fanotify_fd, unsigned int, flags, 901 int, fanotify_fd, unsigned int, flags,
902 __u32, mask0, __u32, mask1, int, dfd, 902 __u32, mask0, __u32, mask1, int, dfd,
903 const char __user *, pathname) 903 const char __user *, pathname)
904 { 904 {
905 return sys_fanotify_mark(fanotify_fd, flags, 905 return sys_fanotify_mark(fanotify_fd, flags,
906 #ifdef __BIG_ENDIAN 906 #ifdef __BIG_ENDIAN
907 ((__u64)mask0 << 32) | mask1, 907 ((__u64)mask0 << 32) | mask1,
908 #else 908 #else
909 ((__u64)mask1 << 32) | mask0, 909 ((__u64)mask1 << 32) | mask0,
910 #endif 910 #endif
911 dfd, pathname); 911 dfd, pathname);
912 } 912 }
913 #endif 913 #endif
914 914
915 /* 915 /*
916 * fanotify_user_setup - Our initialization function. Note that we cannot return 916 * fanotify_user_setup - Our initialization function. Note that we cannot return
917 * error because we have compiled-in VFS hooks. So an (unlikely) failure here 917 * error because we have compiled-in VFS hooks. So an (unlikely) failure here
918 * must result in panic(). 918 * must result in panic().
919 */ 919 */
920 static int __init fanotify_user_setup(void) 920 static int __init fanotify_user_setup(void)
921 { 921 {
922 fanotify_mark_cache = KMEM_CACHE(fsnotify_mark, SLAB_PANIC); 922 fanotify_mark_cache = KMEM_CACHE(fsnotify_mark, SLAB_PANIC);
923 fanotify_event_cachep = KMEM_CACHE(fanotify_event_info, SLAB_PANIC); 923 fanotify_event_cachep = KMEM_CACHE(fanotify_event_info, SLAB_PANIC);
924 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS 924 #ifdef CONFIG_FANOTIFY_ACCESS_PERMISSIONS
925 fanotify_perm_event_cachep = KMEM_CACHE(fanotify_perm_event_info, 925 fanotify_perm_event_cachep = KMEM_CACHE(fanotify_perm_event_info,
926 SLAB_PANIC); 926 SLAB_PANIC);
927 #endif 927 #endif
928 928
929 return 0; 929 return 0;
1 /* 1 /*
2 * kernel/sched/core.c 2 * kernel/sched/core.c
3 * 3 *
4 * Kernel scheduler and related syscalls 4 * Kernel scheduler and related syscalls
5 * 5 *
6 * Copyright (C) 1991-2002 Linus Torvalds 6 * Copyright (C) 1991-2002 Linus Torvalds
7 * 7 *
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and 8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe 9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff 10 * 1998-11-19 Implemented schedule_timeout() and related stuff
11 * by Andrea Arcangeli 11 * by Andrea Arcangeli
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar: 12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with 13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices 14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions 15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love. 16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas. 17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin 18 * 2004-04-02 Scheduler domains code by Nick Piggin
19 * 2007-04-15 Work begun on replacing all interactivity tuning with a 19 * 2007-04-15 Work begun on replacing all interactivity tuning with a
20 * fair scheduling design by Con Kolivas. 20 * fair scheduling design by Con Kolivas.
21 * 2007-05-05 Load balancing (smp-nice) and other improvements 21 * 2007-05-05 Load balancing (smp-nice) and other improvements
22 * by Peter Williams 22 * by Peter Williams
23 * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith 23 * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
24 * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri 24 * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
25 * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins, 25 * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
26 * Thomas Gleixner, Mike Kravetz 26 * Thomas Gleixner, Mike Kravetz
27 */ 27 */
28 28
29 #include <linux/mm.h> 29 #include <linux/mm.h>
30 #include <linux/module.h> 30 #include <linux/module.h>
31 #include <linux/nmi.h> 31 #include <linux/nmi.h>
32 #include <linux/init.h> 32 #include <linux/init.h>
33 #include <linux/uaccess.h> 33 #include <linux/uaccess.h>
34 #include <linux/highmem.h> 34 #include <linux/highmem.h>
35 #include <asm/mmu_context.h> 35 #include <asm/mmu_context.h>
36 #include <linux/interrupt.h> 36 #include <linux/interrupt.h>
37 #include <linux/capability.h> 37 #include <linux/capability.h>
38 #include <linux/completion.h> 38 #include <linux/completion.h>
39 #include <linux/kernel_stat.h> 39 #include <linux/kernel_stat.h>
40 #include <linux/debug_locks.h> 40 #include <linux/debug_locks.h>
41 #include <linux/perf_event.h> 41 #include <linux/perf_event.h>
42 #include <linux/security.h> 42 #include <linux/security.h>
43 #include <linux/notifier.h> 43 #include <linux/notifier.h>
44 #include <linux/profile.h> 44 #include <linux/profile.h>
45 #include <linux/freezer.h> 45 #include <linux/freezer.h>
46 #include <linux/vmalloc.h> 46 #include <linux/vmalloc.h>
47 #include <linux/blkdev.h> 47 #include <linux/blkdev.h>
48 #include <linux/delay.h> 48 #include <linux/delay.h>
49 #include <linux/pid_namespace.h> 49 #include <linux/pid_namespace.h>
50 #include <linux/smp.h> 50 #include <linux/smp.h>
51 #include <linux/threads.h> 51 #include <linux/threads.h>
52 #include <linux/timer.h> 52 #include <linux/timer.h>
53 #include <linux/rcupdate.h> 53 #include <linux/rcupdate.h>
54 #include <linux/cpu.h> 54 #include <linux/cpu.h>
55 #include <linux/cpuset.h> 55 #include <linux/cpuset.h>
56 #include <linux/percpu.h> 56 #include <linux/percpu.h>
57 #include <linux/proc_fs.h> 57 #include <linux/proc_fs.h>
58 #include <linux/seq_file.h> 58 #include <linux/seq_file.h>
59 #include <linux/sysctl.h> 59 #include <linux/sysctl.h>
60 #include <linux/syscalls.h> 60 #include <linux/syscalls.h>
61 #include <linux/times.h> 61 #include <linux/times.h>
62 #include <linux/tsacct_kern.h> 62 #include <linux/tsacct_kern.h>
63 #include <linux/kprobes.h> 63 #include <linux/kprobes.h>
64 #include <linux/delayacct.h> 64 #include <linux/delayacct.h>
65 #include <linux/unistd.h> 65 #include <linux/unistd.h>
66 #include <linux/pagemap.h> 66 #include <linux/pagemap.h>
67 #include <linux/hrtimer.h> 67 #include <linux/hrtimer.h>
68 #include <linux/tick.h> 68 #include <linux/tick.h>
69 #include <linux/debugfs.h> 69 #include <linux/debugfs.h>
70 #include <linux/ctype.h> 70 #include <linux/ctype.h>
71 #include <linux/ftrace.h> 71 #include <linux/ftrace.h>
72 #include <linux/slab.h> 72 #include <linux/slab.h>
73 #include <linux/init_task.h> 73 #include <linux/init_task.h>
74 #include <linux/binfmts.h> 74 #include <linux/binfmts.h>
75 #include <linux/context_tracking.h> 75 #include <linux/context_tracking.h>
76 #include <linux/compiler.h> 76 #include <linux/compiler.h>
77 77
78 #include <asm/switch_to.h> 78 #include <asm/switch_to.h>
79 #include <asm/tlb.h> 79 #include <asm/tlb.h>
80 #include <asm/irq_regs.h> 80 #include <asm/irq_regs.h>
81 #include <asm/mutex.h> 81 #include <asm/mutex.h>
82 #ifdef CONFIG_PARAVIRT 82 #ifdef CONFIG_PARAVIRT
83 #include <asm/paravirt.h> 83 #include <asm/paravirt.h>
84 #endif 84 #endif
85 85
86 #include "sched.h" 86 #include "sched.h"
87 #include "../workqueue_internal.h" 87 #include "../workqueue_internal.h"
88 #include "../smpboot.h" 88 #include "../smpboot.h"
89 89
90 #define CREATE_TRACE_POINTS 90 #define CREATE_TRACE_POINTS
91 #include <trace/events/sched.h> 91 #include <trace/events/sched.h>
92 92
93 void start_bandwidth_timer(struct hrtimer *period_timer, ktime_t period) 93 void start_bandwidth_timer(struct hrtimer *period_timer, ktime_t period)
94 { 94 {
95 unsigned long delta; 95 unsigned long delta;
96 ktime_t soft, hard, now; 96 ktime_t soft, hard, now;
97 97
98 for (;;) { 98 for (;;) {
99 if (hrtimer_active(period_timer)) 99 if (hrtimer_active(period_timer))
100 break; 100 break;
101 101
102 now = hrtimer_cb_get_time(period_timer); 102 now = hrtimer_cb_get_time(period_timer);
103 hrtimer_forward(period_timer, now, period); 103 hrtimer_forward(period_timer, now, period);
104 104
105 soft = hrtimer_get_softexpires(period_timer); 105 soft = hrtimer_get_softexpires(period_timer);
106 hard = hrtimer_get_expires(period_timer); 106 hard = hrtimer_get_expires(period_timer);
107 delta = ktime_to_ns(ktime_sub(hard, soft)); 107 delta = ktime_to_ns(ktime_sub(hard, soft));
108 __hrtimer_start_range_ns(period_timer, soft, delta, 108 __hrtimer_start_range_ns(period_timer, soft, delta,
109 HRTIMER_MODE_ABS_PINNED, 0); 109 HRTIMER_MODE_ABS_PINNED, 0);
110 } 110 }
111 } 111 }
112 112
113 DEFINE_MUTEX(sched_domains_mutex); 113 DEFINE_MUTEX(sched_domains_mutex);
114 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues); 114 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
115 115
116 static void update_rq_clock_task(struct rq *rq, s64 delta); 116 static void update_rq_clock_task(struct rq *rq, s64 delta);
117 117
118 void update_rq_clock(struct rq *rq) 118 void update_rq_clock(struct rq *rq)
119 { 119 {
120 s64 delta; 120 s64 delta;
121 121
122 if (rq->skip_clock_update > 0) 122 if (rq->skip_clock_update > 0)
123 return; 123 return;
124 124
125 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock; 125 delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
126 if (delta < 0) 126 if (delta < 0)
127 return; 127 return;
128 rq->clock += delta; 128 rq->clock += delta;
129 update_rq_clock_task(rq, delta); 129 update_rq_clock_task(rq, delta);
130 } 130 }
131 131
132 /* 132 /*
133 * Debugging: various feature bits 133 * Debugging: various feature bits
134 */ 134 */
135 135
136 #define SCHED_FEAT(name, enabled) \ 136 #define SCHED_FEAT(name, enabled) \
137 (1UL << __SCHED_FEAT_##name) * enabled | 137 (1UL << __SCHED_FEAT_##name) * enabled |
138 138
139 const_debug unsigned int sysctl_sched_features = 139 const_debug unsigned int sysctl_sched_features =
140 #include "features.h" 140 #include "features.h"
141 0; 141 0;
142 142
143 #undef SCHED_FEAT 143 #undef SCHED_FEAT
144 144
145 #ifdef CONFIG_SCHED_DEBUG 145 #ifdef CONFIG_SCHED_DEBUG
146 #define SCHED_FEAT(name, enabled) \ 146 #define SCHED_FEAT(name, enabled) \
147 #name , 147 #name ,
148 148
149 static const char * const sched_feat_names[] = { 149 static const char * const sched_feat_names[] = {
150 #include "features.h" 150 #include "features.h"
151 }; 151 };
152 152
153 #undef SCHED_FEAT 153 #undef SCHED_FEAT
154 154
155 static int sched_feat_show(struct seq_file *m, void *v) 155 static int sched_feat_show(struct seq_file *m, void *v)
156 { 156 {
157 int i; 157 int i;
158 158
159 for (i = 0; i < __SCHED_FEAT_NR; i++) { 159 for (i = 0; i < __SCHED_FEAT_NR; i++) {
160 if (!(sysctl_sched_features & (1UL << i))) 160 if (!(sysctl_sched_features & (1UL << i)))
161 seq_puts(m, "NO_"); 161 seq_puts(m, "NO_");
162 seq_printf(m, "%s ", sched_feat_names[i]); 162 seq_printf(m, "%s ", sched_feat_names[i]);
163 } 163 }
164 seq_puts(m, "\n"); 164 seq_puts(m, "\n");
165 165
166 return 0; 166 return 0;
167 } 167 }
168 168
169 #ifdef HAVE_JUMP_LABEL 169 #ifdef HAVE_JUMP_LABEL
170 170
171 #define jump_label_key__true STATIC_KEY_INIT_TRUE 171 #define jump_label_key__true STATIC_KEY_INIT_TRUE
172 #define jump_label_key__false STATIC_KEY_INIT_FALSE 172 #define jump_label_key__false STATIC_KEY_INIT_FALSE
173 173
174 #define SCHED_FEAT(name, enabled) \ 174 #define SCHED_FEAT(name, enabled) \
175 jump_label_key__##enabled , 175 jump_label_key__##enabled ,
176 176
177 struct static_key sched_feat_keys[__SCHED_FEAT_NR] = { 177 struct static_key sched_feat_keys[__SCHED_FEAT_NR] = {
178 #include "features.h" 178 #include "features.h"
179 }; 179 };
180 180
181 #undef SCHED_FEAT 181 #undef SCHED_FEAT
182 182
183 static void sched_feat_disable(int i) 183 static void sched_feat_disable(int i)
184 { 184 {
185 if (static_key_enabled(&sched_feat_keys[i])) 185 if (static_key_enabled(&sched_feat_keys[i]))
186 static_key_slow_dec(&sched_feat_keys[i]); 186 static_key_slow_dec(&sched_feat_keys[i]);
187 } 187 }
188 188
189 static void sched_feat_enable(int i) 189 static void sched_feat_enable(int i)
190 { 190 {
191 if (!static_key_enabled(&sched_feat_keys[i])) 191 if (!static_key_enabled(&sched_feat_keys[i]))
192 static_key_slow_inc(&sched_feat_keys[i]); 192 static_key_slow_inc(&sched_feat_keys[i]);
193 } 193 }
194 #else 194 #else
195 static void sched_feat_disable(int i) { }; 195 static void sched_feat_disable(int i) { };
196 static void sched_feat_enable(int i) { }; 196 static void sched_feat_enable(int i) { };
197 #endif /* HAVE_JUMP_LABEL */ 197 #endif /* HAVE_JUMP_LABEL */
198 198
199 static int sched_feat_set(char *cmp) 199 static int sched_feat_set(char *cmp)
200 { 200 {
201 int i; 201 int i;
202 int neg = 0; 202 int neg = 0;
203 203
204 if (strncmp(cmp, "NO_", 3) == 0) { 204 if (strncmp(cmp, "NO_", 3) == 0) {
205 neg = 1; 205 neg = 1;
206 cmp += 3; 206 cmp += 3;
207 } 207 }
208 208
209 for (i = 0; i < __SCHED_FEAT_NR; i++) { 209 for (i = 0; i < __SCHED_FEAT_NR; i++) {
210 if (strcmp(cmp, sched_feat_names[i]) == 0) { 210 if (strcmp(cmp, sched_feat_names[i]) == 0) {
211 if (neg) { 211 if (neg) {
212 sysctl_sched_features &= ~(1UL << i); 212 sysctl_sched_features &= ~(1UL << i);
213 sched_feat_disable(i); 213 sched_feat_disable(i);
214 } else { 214 } else {
215 sysctl_sched_features |= (1UL << i); 215 sysctl_sched_features |= (1UL << i);
216 sched_feat_enable(i); 216 sched_feat_enable(i);
217 } 217 }
218 break; 218 break;
219 } 219 }
220 } 220 }
221 221
222 return i; 222 return i;
223 } 223 }
224 224
225 static ssize_t 225 static ssize_t
226 sched_feat_write(struct file *filp, const char __user *ubuf, 226 sched_feat_write(struct file *filp, const char __user *ubuf,
227 size_t cnt, loff_t *ppos) 227 size_t cnt, loff_t *ppos)
228 { 228 {
229 char buf[64]; 229 char buf[64];
230 char *cmp; 230 char *cmp;
231 int i; 231 int i;
232 struct inode *inode; 232 struct inode *inode;
233 233
234 if (cnt > 63) 234 if (cnt > 63)
235 cnt = 63; 235 cnt = 63;
236 236
237 if (copy_from_user(&buf, ubuf, cnt)) 237 if (copy_from_user(&buf, ubuf, cnt))
238 return -EFAULT; 238 return -EFAULT;
239 239
240 buf[cnt] = 0; 240 buf[cnt] = 0;
241 cmp = strstrip(buf); 241 cmp = strstrip(buf);
242 242
243 /* Ensure the static_key remains in a consistent state */ 243 /* Ensure the static_key remains in a consistent state */
244 inode = file_inode(filp); 244 inode = file_inode(filp);
245 mutex_lock(&inode->i_mutex); 245 mutex_lock(&inode->i_mutex);
246 i = sched_feat_set(cmp); 246 i = sched_feat_set(cmp);
247 mutex_unlock(&inode->i_mutex); 247 mutex_unlock(&inode->i_mutex);
248 if (i == __SCHED_FEAT_NR) 248 if (i == __SCHED_FEAT_NR)
249 return -EINVAL; 249 return -EINVAL;
250 250
251 *ppos += cnt; 251 *ppos += cnt;
252 252
253 return cnt; 253 return cnt;
254 } 254 }
255 255
256 static int sched_feat_open(struct inode *inode, struct file *filp) 256 static int sched_feat_open(struct inode *inode, struct file *filp)
257 { 257 {
258 return single_open(filp, sched_feat_show, NULL); 258 return single_open(filp, sched_feat_show, NULL);
259 } 259 }
260 260
261 static const struct file_operations sched_feat_fops = { 261 static const struct file_operations sched_feat_fops = {
262 .open = sched_feat_open, 262 .open = sched_feat_open,
263 .write = sched_feat_write, 263 .write = sched_feat_write,
264 .read = seq_read, 264 .read = seq_read,
265 .llseek = seq_lseek, 265 .llseek = seq_lseek,
266 .release = single_release, 266 .release = single_release,
267 }; 267 };
268 268
269 static __init int sched_init_debug(void) 269 static __init int sched_init_debug(void)
270 { 270 {
271 debugfs_create_file("sched_features", 0644, NULL, NULL, 271 debugfs_create_file("sched_features", 0644, NULL, NULL,
272 &sched_feat_fops); 272 &sched_feat_fops);
273 273
274 return 0; 274 return 0;
275 } 275 }
276 late_initcall(sched_init_debug); 276 late_initcall(sched_init_debug);
277 #endif /* CONFIG_SCHED_DEBUG */ 277 #endif /* CONFIG_SCHED_DEBUG */
278 278
279 /* 279 /*
280 * Number of tasks to iterate in a single balance run. 280 * Number of tasks to iterate in a single balance run.
281 * Limited because this is done with IRQs disabled. 281 * Limited because this is done with IRQs disabled.
282 */ 282 */
283 const_debug unsigned int sysctl_sched_nr_migrate = 32; 283 const_debug unsigned int sysctl_sched_nr_migrate = 32;
284 284
285 /* 285 /*
286 * period over which we average the RT time consumption, measured 286 * period over which we average the RT time consumption, measured
287 * in ms. 287 * in ms.
288 * 288 *
289 * default: 1s 289 * default: 1s
290 */ 290 */
291 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC; 291 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
292 292
293 /* 293 /*
294 * period over which we measure -rt task cpu usage in us. 294 * period over which we measure -rt task cpu usage in us.
295 * default: 1s 295 * default: 1s
296 */ 296 */
297 unsigned int sysctl_sched_rt_period = 1000000; 297 unsigned int sysctl_sched_rt_period = 1000000;
298 298
299 __read_mostly int scheduler_running; 299 __read_mostly int scheduler_running;
300 300
301 /* 301 /*
302 * part of the period that we allow rt tasks to run in us. 302 * part of the period that we allow rt tasks to run in us.
303 * default: 0.95s 303 * default: 0.95s
304 */ 304 */
305 int sysctl_sched_rt_runtime = 950000; 305 int sysctl_sched_rt_runtime = 950000;
306 306
307 /* 307 /*
308 * __task_rq_lock - lock the rq @p resides on. 308 * __task_rq_lock - lock the rq @p resides on.
309 */ 309 */
310 static inline struct rq *__task_rq_lock(struct task_struct *p) 310 static inline struct rq *__task_rq_lock(struct task_struct *p)
311 __acquires(rq->lock) 311 __acquires(rq->lock)
312 { 312 {
313 struct rq *rq; 313 struct rq *rq;
314 314
315 lockdep_assert_held(&p->pi_lock); 315 lockdep_assert_held(&p->pi_lock);
316 316
317 for (;;) { 317 for (;;) {
318 rq = task_rq(p); 318 rq = task_rq(p);
319 raw_spin_lock(&rq->lock); 319 raw_spin_lock(&rq->lock);
320 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) 320 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p)))
321 return rq; 321 return rq;
322 raw_spin_unlock(&rq->lock); 322 raw_spin_unlock(&rq->lock);
323 323
324 while (unlikely(task_on_rq_migrating(p))) 324 while (unlikely(task_on_rq_migrating(p)))
325 cpu_relax(); 325 cpu_relax();
326 } 326 }
327 } 327 }
328 328
329 /* 329 /*
330 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on. 330 * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
331 */ 331 */
332 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags) 332 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
333 __acquires(p->pi_lock) 333 __acquires(p->pi_lock)
334 __acquires(rq->lock) 334 __acquires(rq->lock)
335 { 335 {
336 struct rq *rq; 336 struct rq *rq;
337 337
338 for (;;) { 338 for (;;) {
339 raw_spin_lock_irqsave(&p->pi_lock, *flags); 339 raw_spin_lock_irqsave(&p->pi_lock, *flags);
340 rq = task_rq(p); 340 rq = task_rq(p);
341 raw_spin_lock(&rq->lock); 341 raw_spin_lock(&rq->lock);
342 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) 342 if (likely(rq == task_rq(p) && !task_on_rq_migrating(p)))
343 return rq; 343 return rq;
344 raw_spin_unlock(&rq->lock); 344 raw_spin_unlock(&rq->lock);
345 raw_spin_unlock_irqrestore(&p->pi_lock, *flags); 345 raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
346 346
347 while (unlikely(task_on_rq_migrating(p))) 347 while (unlikely(task_on_rq_migrating(p)))
348 cpu_relax(); 348 cpu_relax();
349 } 349 }
350 } 350 }
351 351
352 static void __task_rq_unlock(struct rq *rq) 352 static void __task_rq_unlock(struct rq *rq)
353 __releases(rq->lock) 353 __releases(rq->lock)
354 { 354 {
355 raw_spin_unlock(&rq->lock); 355 raw_spin_unlock(&rq->lock);
356 } 356 }
357 357
358 static inline void 358 static inline void
359 task_rq_unlock(struct rq *rq, struct task_struct *p, unsigned long *flags) 359 task_rq_unlock(struct rq *rq, struct task_struct *p, unsigned long *flags)
360 __releases(rq->lock) 360 __releases(rq->lock)
361 __releases(p->pi_lock) 361 __releases(p->pi_lock)
362 { 362 {
363 raw_spin_unlock(&rq->lock); 363 raw_spin_unlock(&rq->lock);
364 raw_spin_unlock_irqrestore(&p->pi_lock, *flags); 364 raw_spin_unlock_irqrestore(&p->pi_lock, *flags);
365 } 365 }
366 366
367 /* 367 /*
368 * this_rq_lock - lock this runqueue and disable interrupts. 368 * this_rq_lock - lock this runqueue and disable interrupts.
369 */ 369 */
370 static struct rq *this_rq_lock(void) 370 static struct rq *this_rq_lock(void)
371 __acquires(rq->lock) 371 __acquires(rq->lock)
372 { 372 {
373 struct rq *rq; 373 struct rq *rq;
374 374
375 local_irq_disable(); 375 local_irq_disable();
376 rq = this_rq(); 376 rq = this_rq();
377 raw_spin_lock(&rq->lock); 377 raw_spin_lock(&rq->lock);
378 378
379 return rq; 379 return rq;
380 } 380 }
381 381
382 #ifdef CONFIG_SCHED_HRTICK 382 #ifdef CONFIG_SCHED_HRTICK
383 /* 383 /*
384 * Use HR-timers to deliver accurate preemption points. 384 * Use HR-timers to deliver accurate preemption points.
385 */ 385 */
386 386
387 static void hrtick_clear(struct rq *rq) 387 static void hrtick_clear(struct rq *rq)
388 { 388 {
389 if (hrtimer_active(&rq->hrtick_timer)) 389 if (hrtimer_active(&rq->hrtick_timer))
390 hrtimer_cancel(&rq->hrtick_timer); 390 hrtimer_cancel(&rq->hrtick_timer);
391 } 391 }
392 392
393 /* 393 /*
394 * High-resolution timer tick. 394 * High-resolution timer tick.
395 * Runs from hardirq context with interrupts disabled. 395 * Runs from hardirq context with interrupts disabled.
396 */ 396 */
397 static enum hrtimer_restart hrtick(struct hrtimer *timer) 397 static enum hrtimer_restart hrtick(struct hrtimer *timer)
398 { 398 {
399 struct rq *rq = container_of(timer, struct rq, hrtick_timer); 399 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
400 400
401 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id()); 401 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
402 402
403 raw_spin_lock(&rq->lock); 403 raw_spin_lock(&rq->lock);
404 update_rq_clock(rq); 404 update_rq_clock(rq);
405 rq->curr->sched_class->task_tick(rq, rq->curr, 1); 405 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
406 raw_spin_unlock(&rq->lock); 406 raw_spin_unlock(&rq->lock);
407 407
408 return HRTIMER_NORESTART; 408 return HRTIMER_NORESTART;
409 } 409 }
410 410
411 #ifdef CONFIG_SMP 411 #ifdef CONFIG_SMP
412 412
413 static int __hrtick_restart(struct rq *rq) 413 static int __hrtick_restart(struct rq *rq)
414 { 414 {
415 struct hrtimer *timer = &rq->hrtick_timer; 415 struct hrtimer *timer = &rq->hrtick_timer;
416 ktime_t time = hrtimer_get_softexpires(timer); 416 ktime_t time = hrtimer_get_softexpires(timer);
417 417
418 return __hrtimer_start_range_ns(timer, time, 0, HRTIMER_MODE_ABS_PINNED, 0); 418 return __hrtimer_start_range_ns(timer, time, 0, HRTIMER_MODE_ABS_PINNED, 0);
419 } 419 }
420 420
421 /* 421 /*
422 * called from hardirq (IPI) context 422 * called from hardirq (IPI) context
423 */ 423 */
424 static void __hrtick_start(void *arg) 424 static void __hrtick_start(void *arg)
425 { 425 {
426 struct rq *rq = arg; 426 struct rq *rq = arg;
427 427
428 raw_spin_lock(&rq->lock); 428 raw_spin_lock(&rq->lock);
429 __hrtick_restart(rq); 429 __hrtick_restart(rq);
430 rq->hrtick_csd_pending = 0; 430 rq->hrtick_csd_pending = 0;
431 raw_spin_unlock(&rq->lock); 431 raw_spin_unlock(&rq->lock);
432 } 432 }
433 433
434 /* 434 /*
435 * Called to set the hrtick timer state. 435 * Called to set the hrtick timer state.
436 * 436 *
437 * called with rq->lock held and irqs disabled 437 * called with rq->lock held and irqs disabled
438 */ 438 */
439 void hrtick_start(struct rq *rq, u64 delay) 439 void hrtick_start(struct rq *rq, u64 delay)
440 { 440 {
441 struct hrtimer *timer = &rq->hrtick_timer; 441 struct hrtimer *timer = &rq->hrtick_timer;
442 ktime_t time; 442 ktime_t time;
443 s64 delta; 443 s64 delta;
444 444
445 /* 445 /*
446 * Don't schedule slices shorter than 10000ns, that just 446 * Don't schedule slices shorter than 10000ns, that just
447 * doesn't make sense and can cause timer DoS. 447 * doesn't make sense and can cause timer DoS.
448 */ 448 */
449 delta = max_t(s64, delay, 10000LL); 449 delta = max_t(s64, delay, 10000LL);
450 time = ktime_add_ns(timer->base->get_time(), delta); 450 time = ktime_add_ns(timer->base->get_time(), delta);
451 451
452 hrtimer_set_expires(timer, time); 452 hrtimer_set_expires(timer, time);
453 453
454 if (rq == this_rq()) { 454 if (rq == this_rq()) {
455 __hrtick_restart(rq); 455 __hrtick_restart(rq);
456 } else if (!rq->hrtick_csd_pending) { 456 } else if (!rq->hrtick_csd_pending) {
457 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd); 457 smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
458 rq->hrtick_csd_pending = 1; 458 rq->hrtick_csd_pending = 1;
459 } 459 }
460 } 460 }
461 461
462 static int 462 static int
463 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu) 463 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
464 { 464 {
465 int cpu = (int)(long)hcpu; 465 int cpu = (int)(long)hcpu;
466 466
467 switch (action) { 467 switch (action) {
468 case CPU_UP_CANCELED: 468 case CPU_UP_CANCELED:
469 case CPU_UP_CANCELED_FROZEN: 469 case CPU_UP_CANCELED_FROZEN:
470 case CPU_DOWN_PREPARE: 470 case CPU_DOWN_PREPARE:
471 case CPU_DOWN_PREPARE_FROZEN: 471 case CPU_DOWN_PREPARE_FROZEN:
472 case CPU_DEAD: 472 case CPU_DEAD:
473 case CPU_DEAD_FROZEN: 473 case CPU_DEAD_FROZEN:
474 hrtick_clear(cpu_rq(cpu)); 474 hrtick_clear(cpu_rq(cpu));
475 return NOTIFY_OK; 475 return NOTIFY_OK;
476 } 476 }
477 477
478 return NOTIFY_DONE; 478 return NOTIFY_DONE;
479 } 479 }
480 480
481 static __init void init_hrtick(void) 481 static __init void init_hrtick(void)
482 { 482 {
483 hotcpu_notifier(hotplug_hrtick, 0); 483 hotcpu_notifier(hotplug_hrtick, 0);
484 } 484 }
485 #else 485 #else
486 /* 486 /*
487 * Called to set the hrtick timer state. 487 * Called to set the hrtick timer state.
488 * 488 *
489 * called with rq->lock held and irqs disabled 489 * called with rq->lock held and irqs disabled
490 */ 490 */
491 void hrtick_start(struct rq *rq, u64 delay) 491 void hrtick_start(struct rq *rq, u64 delay)
492 { 492 {
493 __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0, 493 __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
494 HRTIMER_MODE_REL_PINNED, 0); 494 HRTIMER_MODE_REL_PINNED, 0);
495 } 495 }
496 496
497 static inline void init_hrtick(void) 497 static inline void init_hrtick(void)
498 { 498 {
499 } 499 }
500 #endif /* CONFIG_SMP */ 500 #endif /* CONFIG_SMP */
501 501
502 static void init_rq_hrtick(struct rq *rq) 502 static void init_rq_hrtick(struct rq *rq)
503 { 503 {
504 #ifdef CONFIG_SMP 504 #ifdef CONFIG_SMP
505 rq->hrtick_csd_pending = 0; 505 rq->hrtick_csd_pending = 0;
506 506
507 rq->hrtick_csd.flags = 0; 507 rq->hrtick_csd.flags = 0;
508 rq->hrtick_csd.func = __hrtick_start; 508 rq->hrtick_csd.func = __hrtick_start;
509 rq->hrtick_csd.info = rq; 509 rq->hrtick_csd.info = rq;
510 #endif 510 #endif
511 511
512 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); 512 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
513 rq->hrtick_timer.function = hrtick; 513 rq->hrtick_timer.function = hrtick;
514 } 514 }
515 #else /* CONFIG_SCHED_HRTICK */ 515 #else /* CONFIG_SCHED_HRTICK */
516 static inline void hrtick_clear(struct rq *rq) 516 static inline void hrtick_clear(struct rq *rq)
517 { 517 {
518 } 518 }
519 519
520 static inline void init_rq_hrtick(struct rq *rq) 520 static inline void init_rq_hrtick(struct rq *rq)
521 { 521 {
522 } 522 }
523 523
524 static inline void init_hrtick(void) 524 static inline void init_hrtick(void)
525 { 525 {
526 } 526 }
527 #endif /* CONFIG_SCHED_HRTICK */ 527 #endif /* CONFIG_SCHED_HRTICK */
528 528
529 /* 529 /*
530 * cmpxchg based fetch_or, macro so it works for different integer types 530 * cmpxchg based fetch_or, macro so it works for different integer types
531 */ 531 */
532 #define fetch_or(ptr, val) \ 532 #define fetch_or(ptr, val) \
533 ({ typeof(*(ptr)) __old, __val = *(ptr); \ 533 ({ typeof(*(ptr)) __old, __val = *(ptr); \
534 for (;;) { \ 534 for (;;) { \
535 __old = cmpxchg((ptr), __val, __val | (val)); \ 535 __old = cmpxchg((ptr), __val, __val | (val)); \
536 if (__old == __val) \ 536 if (__old == __val) \
537 break; \ 537 break; \
538 __val = __old; \ 538 __val = __old; \
539 } \ 539 } \
540 __old; \ 540 __old; \
541 }) 541 })
542 542
543 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG) 543 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
544 /* 544 /*
545 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG, 545 * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
546 * this avoids any races wrt polling state changes and thereby avoids 546 * this avoids any races wrt polling state changes and thereby avoids
547 * spurious IPIs. 547 * spurious IPIs.
548 */ 548 */
549 static bool set_nr_and_not_polling(struct task_struct *p) 549 static bool set_nr_and_not_polling(struct task_struct *p)
550 { 550 {
551 struct thread_info *ti = task_thread_info(p); 551 struct thread_info *ti = task_thread_info(p);
552 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG); 552 return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
553 } 553 }
554 554
555 /* 555 /*
556 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set. 556 * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
557 * 557 *
558 * If this returns true, then the idle task promises to call 558 * If this returns true, then the idle task promises to call
559 * sched_ttwu_pending() and reschedule soon. 559 * sched_ttwu_pending() and reschedule soon.
560 */ 560 */
561 static bool set_nr_if_polling(struct task_struct *p) 561 static bool set_nr_if_polling(struct task_struct *p)
562 { 562 {
563 struct thread_info *ti = task_thread_info(p); 563 struct thread_info *ti = task_thread_info(p);
564 typeof(ti->flags) old, val = ACCESS_ONCE(ti->flags); 564 typeof(ti->flags) old, val = ACCESS_ONCE(ti->flags);
565 565
566 for (;;) { 566 for (;;) {
567 if (!(val & _TIF_POLLING_NRFLAG)) 567 if (!(val & _TIF_POLLING_NRFLAG))
568 return false; 568 return false;
569 if (val & _TIF_NEED_RESCHED) 569 if (val & _TIF_NEED_RESCHED)
570 return true; 570 return true;
571 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED); 571 old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
572 if (old == val) 572 if (old == val)
573 break; 573 break;
574 val = old; 574 val = old;
575 } 575 }
576 return true; 576 return true;
577 } 577 }
578 578
579 #else 579 #else
580 static bool set_nr_and_not_polling(struct task_struct *p) 580 static bool set_nr_and_not_polling(struct task_struct *p)
581 { 581 {
582 set_tsk_need_resched(p); 582 set_tsk_need_resched(p);
583 return true; 583 return true;
584 } 584 }
585 585
586 #ifdef CONFIG_SMP 586 #ifdef CONFIG_SMP
587 static bool set_nr_if_polling(struct task_struct *p) 587 static bool set_nr_if_polling(struct task_struct *p)
588 { 588 {
589 return false; 589 return false;
590 } 590 }
591 #endif 591 #endif
592 #endif 592 #endif
593 593
594 /* 594 /*
595 * resched_curr - mark rq's current task 'to be rescheduled now'. 595 * resched_curr - mark rq's current task 'to be rescheduled now'.
596 * 596 *
597 * On UP this means the setting of the need_resched flag, on SMP it 597 * On UP this means the setting of the need_resched flag, on SMP it
598 * might also involve a cross-CPU call to trigger the scheduler on 598 * might also involve a cross-CPU call to trigger the scheduler on
599 * the target CPU. 599 * the target CPU.
600 */ 600 */
601 void resched_curr(struct rq *rq) 601 void resched_curr(struct rq *rq)
602 { 602 {
603 struct task_struct *curr = rq->curr; 603 struct task_struct *curr = rq->curr;
604 int cpu; 604 int cpu;
605 605
606 lockdep_assert_held(&rq->lock); 606 lockdep_assert_held(&rq->lock);
607 607
608 if (test_tsk_need_resched(curr)) 608 if (test_tsk_need_resched(curr))
609 return; 609 return;
610 610
611 cpu = cpu_of(rq); 611 cpu = cpu_of(rq);
612 612
613 if (cpu == smp_processor_id()) { 613 if (cpu == smp_processor_id()) {
614 set_tsk_need_resched(curr); 614 set_tsk_need_resched(curr);
615 set_preempt_need_resched(); 615 set_preempt_need_resched();
616 return; 616 return;
617 } 617 }
618 618
619 if (set_nr_and_not_polling(curr)) 619 if (set_nr_and_not_polling(curr))
620 smp_send_reschedule(cpu); 620 smp_send_reschedule(cpu);
621 else 621 else
622 trace_sched_wake_idle_without_ipi(cpu); 622 trace_sched_wake_idle_without_ipi(cpu);
623 } 623 }
624 624
625 void resched_cpu(int cpu) 625 void resched_cpu(int cpu)
626 { 626 {
627 struct rq *rq = cpu_rq(cpu); 627 struct rq *rq = cpu_rq(cpu);
628 unsigned long flags; 628 unsigned long flags;
629 629
630 if (!raw_spin_trylock_irqsave(&rq->lock, flags)) 630 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
631 return; 631 return;
632 resched_curr(rq); 632 resched_curr(rq);
633 raw_spin_unlock_irqrestore(&rq->lock, flags); 633 raw_spin_unlock_irqrestore(&rq->lock, flags);
634 } 634 }
635 635
636 #ifdef CONFIG_SMP 636 #ifdef CONFIG_SMP
637 #ifdef CONFIG_NO_HZ_COMMON 637 #ifdef CONFIG_NO_HZ_COMMON
638 /* 638 /*
639 * In the semi idle case, use the nearest busy cpu for migrating timers 639 * In the semi idle case, use the nearest busy cpu for migrating timers
640 * from an idle cpu. This is good for power-savings. 640 * from an idle cpu. This is good for power-savings.
641 * 641 *
642 * We don't do similar optimization for completely idle system, as 642 * We don't do similar optimization for completely idle system, as
643 * selecting an idle cpu will add more delays to the timers than intended 643 * selecting an idle cpu will add more delays to the timers than intended
644 * (as that cpu's timer base may not be uptodate wrt jiffies etc). 644 * (as that cpu's timer base may not be uptodate wrt jiffies etc).
645 */ 645 */
646 int get_nohz_timer_target(int pinned) 646 int get_nohz_timer_target(int pinned)
647 { 647 {
648 int cpu = smp_processor_id(); 648 int cpu = smp_processor_id();
649 int i; 649 int i;
650 struct sched_domain *sd; 650 struct sched_domain *sd;
651 651
652 if (pinned || !get_sysctl_timer_migration() || !idle_cpu(cpu)) 652 if (pinned || !get_sysctl_timer_migration() || !idle_cpu(cpu))
653 return cpu; 653 return cpu;
654 654
655 rcu_read_lock(); 655 rcu_read_lock();
656 for_each_domain(cpu, sd) { 656 for_each_domain(cpu, sd) {
657 for_each_cpu(i, sched_domain_span(sd)) { 657 for_each_cpu(i, sched_domain_span(sd)) {
658 if (!idle_cpu(i)) { 658 if (!idle_cpu(i)) {
659 cpu = i; 659 cpu = i;
660 goto unlock; 660 goto unlock;
661 } 661 }
662 } 662 }
663 } 663 }
664 unlock: 664 unlock:
665 rcu_read_unlock(); 665 rcu_read_unlock();
666 return cpu; 666 return cpu;
667 } 667 }
668 /* 668 /*
669 * When add_timer_on() enqueues a timer into the timer wheel of an 669 * When add_timer_on() enqueues a timer into the timer wheel of an
670 * idle CPU then this timer might expire before the next timer event 670 * idle CPU then this timer might expire before the next timer event
671 * which is scheduled to wake up that CPU. In case of a completely 671 * which is scheduled to wake up that CPU. In case of a completely
672 * idle system the next event might even be infinite time into the 672 * idle system the next event might even be infinite time into the
673 * future. wake_up_idle_cpu() ensures that the CPU is woken up and 673 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
674 * leaves the inner idle loop so the newly added timer is taken into 674 * leaves the inner idle loop so the newly added timer is taken into
675 * account when the CPU goes back to idle and evaluates the timer 675 * account when the CPU goes back to idle and evaluates the timer
676 * wheel for the next timer event. 676 * wheel for the next timer event.
677 */ 677 */
678 static void wake_up_idle_cpu(int cpu) 678 static void wake_up_idle_cpu(int cpu)
679 { 679 {
680 struct rq *rq = cpu_rq(cpu); 680 struct rq *rq = cpu_rq(cpu);
681 681
682 if (cpu == smp_processor_id()) 682 if (cpu == smp_processor_id())
683 return; 683 return;
684 684
685 if (set_nr_and_not_polling(rq->idle)) 685 if (set_nr_and_not_polling(rq->idle))
686 smp_send_reschedule(cpu); 686 smp_send_reschedule(cpu);
687 else 687 else
688 trace_sched_wake_idle_without_ipi(cpu); 688 trace_sched_wake_idle_without_ipi(cpu);
689 } 689 }
690 690
691 static bool wake_up_full_nohz_cpu(int cpu) 691 static bool wake_up_full_nohz_cpu(int cpu)
692 { 692 {
693 /* 693 /*
694 * We just need the target to call irq_exit() and re-evaluate 694 * We just need the target to call irq_exit() and re-evaluate
695 * the next tick. The nohz full kick at least implies that. 695 * the next tick. The nohz full kick at least implies that.
696 * If needed we can still optimize that later with an 696 * If needed we can still optimize that later with an
697 * empty IRQ. 697 * empty IRQ.
698 */ 698 */
699 if (tick_nohz_full_cpu(cpu)) { 699 if (tick_nohz_full_cpu(cpu)) {
700 if (cpu != smp_processor_id() || 700 if (cpu != smp_processor_id() ||
701 tick_nohz_tick_stopped()) 701 tick_nohz_tick_stopped())
702 tick_nohz_full_kick_cpu(cpu); 702 tick_nohz_full_kick_cpu(cpu);
703 return true; 703 return true;
704 } 704 }
705 705
706 return false; 706 return false;
707 } 707 }
708 708
709 void wake_up_nohz_cpu(int cpu) 709 void wake_up_nohz_cpu(int cpu)
710 { 710 {
711 if (!wake_up_full_nohz_cpu(cpu)) 711 if (!wake_up_full_nohz_cpu(cpu))
712 wake_up_idle_cpu(cpu); 712 wake_up_idle_cpu(cpu);
713 } 713 }
714 714
715 static inline bool got_nohz_idle_kick(void) 715 static inline bool got_nohz_idle_kick(void)
716 { 716 {
717 int cpu = smp_processor_id(); 717 int cpu = smp_processor_id();
718 718
719 if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu))) 719 if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
720 return false; 720 return false;
721 721
722 if (idle_cpu(cpu) && !need_resched()) 722 if (idle_cpu(cpu) && !need_resched())
723 return true; 723 return true;
724 724
725 /* 725 /*
726 * We can't run Idle Load Balance on this CPU for this time so we 726 * We can't run Idle Load Balance on this CPU for this time so we
727 * cancel it and clear NOHZ_BALANCE_KICK 727 * cancel it and clear NOHZ_BALANCE_KICK
728 */ 728 */
729 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)); 729 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
730 return false; 730 return false;
731 } 731 }
732 732
733 #else /* CONFIG_NO_HZ_COMMON */ 733 #else /* CONFIG_NO_HZ_COMMON */
734 734
735 static inline bool got_nohz_idle_kick(void) 735 static inline bool got_nohz_idle_kick(void)
736 { 736 {
737 return false; 737 return false;
738 } 738 }
739 739
740 #endif /* CONFIG_NO_HZ_COMMON */ 740 #endif /* CONFIG_NO_HZ_COMMON */
741 741
742 #ifdef CONFIG_NO_HZ_FULL 742 #ifdef CONFIG_NO_HZ_FULL
743 bool sched_can_stop_tick(void) 743 bool sched_can_stop_tick(void)
744 { 744 {
745 /* 745 /*
746 * More than one running task need preemption. 746 * More than one running task need preemption.
747 * nr_running update is assumed to be visible 747 * nr_running update is assumed to be visible
748 * after IPI is sent from wakers. 748 * after IPI is sent from wakers.
749 */ 749 */
750 if (this_rq()->nr_running > 1) 750 if (this_rq()->nr_running > 1)
751 return false; 751 return false;
752 752
753 return true; 753 return true;
754 } 754 }
755 #endif /* CONFIG_NO_HZ_FULL */ 755 #endif /* CONFIG_NO_HZ_FULL */
756 756
757 void sched_avg_update(struct rq *rq) 757 void sched_avg_update(struct rq *rq)
758 { 758 {
759 s64 period = sched_avg_period(); 759 s64 period = sched_avg_period();
760 760
761 while ((s64)(rq_clock(rq) - rq->age_stamp) > period) { 761 while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
762 /* 762 /*
763 * Inline assembly required to prevent the compiler 763 * Inline assembly required to prevent the compiler
764 * optimising this loop into a divmod call. 764 * optimising this loop into a divmod call.
765 * See __iter_div_u64_rem() for another example of this. 765 * See __iter_div_u64_rem() for another example of this.
766 */ 766 */
767 asm("" : "+rm" (rq->age_stamp)); 767 asm("" : "+rm" (rq->age_stamp));
768 rq->age_stamp += period; 768 rq->age_stamp += period;
769 rq->rt_avg /= 2; 769 rq->rt_avg /= 2;
770 } 770 }
771 } 771 }
772 772
773 #endif /* CONFIG_SMP */ 773 #endif /* CONFIG_SMP */
774 774
775 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \ 775 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
776 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH))) 776 (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
777 /* 777 /*
778 * Iterate task_group tree rooted at *from, calling @down when first entering a 778 * Iterate task_group tree rooted at *from, calling @down when first entering a
779 * node and @up when leaving it for the final time. 779 * node and @up when leaving it for the final time.
780 * 780 *
781 * Caller must hold rcu_lock or sufficient equivalent. 781 * Caller must hold rcu_lock or sufficient equivalent.
782 */ 782 */
783 int walk_tg_tree_from(struct task_group *from, 783 int walk_tg_tree_from(struct task_group *from,
784 tg_visitor down, tg_visitor up, void *data) 784 tg_visitor down, tg_visitor up, void *data)
785 { 785 {
786 struct task_group *parent, *child; 786 struct task_group *parent, *child;
787 int ret; 787 int ret;
788 788
789 parent = from; 789 parent = from;
790 790
791 down: 791 down:
792 ret = (*down)(parent, data); 792 ret = (*down)(parent, data);
793 if (ret) 793 if (ret)
794 goto out; 794 goto out;
795 list_for_each_entry_rcu(child, &parent->children, siblings) { 795 list_for_each_entry_rcu(child, &parent->children, siblings) {
796 parent = child; 796 parent = child;
797 goto down; 797 goto down;
798 798
799 up: 799 up:
800 continue; 800 continue;
801 } 801 }
802 ret = (*up)(parent, data); 802 ret = (*up)(parent, data);
803 if (ret || parent == from) 803 if (ret || parent == from)
804 goto out; 804 goto out;
805 805
806 child = parent; 806 child = parent;
807 parent = parent->parent; 807 parent = parent->parent;
808 if (parent) 808 if (parent)
809 goto up; 809 goto up;
810 out: 810 out:
811 return ret; 811 return ret;
812 } 812 }
813 813
814 int tg_nop(struct task_group *tg, void *data) 814 int tg_nop(struct task_group *tg, void *data)
815 { 815 {
816 return 0; 816 return 0;
817 } 817 }
818 #endif 818 #endif
819 819
820 static void set_load_weight(struct task_struct *p) 820 static void set_load_weight(struct task_struct *p)
821 { 821 {
822 int prio = p->static_prio - MAX_RT_PRIO; 822 int prio = p->static_prio - MAX_RT_PRIO;
823 struct load_weight *load = &p->se.load; 823 struct load_weight *load = &p->se.load;
824 824
825 /* 825 /*
826 * SCHED_IDLE tasks get minimal weight: 826 * SCHED_IDLE tasks get minimal weight:
827 */ 827 */
828 if (p->policy == SCHED_IDLE) { 828 if (p->policy == SCHED_IDLE) {
829 load->weight = scale_load(WEIGHT_IDLEPRIO); 829 load->weight = scale_load(WEIGHT_IDLEPRIO);
830 load->inv_weight = WMULT_IDLEPRIO; 830 load->inv_weight = WMULT_IDLEPRIO;
831 return; 831 return;
832 } 832 }
833 833
834 load->weight = scale_load(prio_to_weight[prio]); 834 load->weight = scale_load(prio_to_weight[prio]);
835 load->inv_weight = prio_to_wmult[prio]; 835 load->inv_weight = prio_to_wmult[prio];
836 } 836 }
837 837
838 static void enqueue_task(struct rq *rq, struct task_struct *p, int flags) 838 static void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
839 { 839 {
840 update_rq_clock(rq); 840 update_rq_clock(rq);
841 sched_info_queued(rq, p); 841 sched_info_queued(rq, p);
842 p->sched_class->enqueue_task(rq, p, flags); 842 p->sched_class->enqueue_task(rq, p, flags);
843 } 843 }
844 844
845 static void dequeue_task(struct rq *rq, struct task_struct *p, int flags) 845 static void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
846 { 846 {
847 update_rq_clock(rq); 847 update_rq_clock(rq);
848 sched_info_dequeued(rq, p); 848 sched_info_dequeued(rq, p);
849 p->sched_class->dequeue_task(rq, p, flags); 849 p->sched_class->dequeue_task(rq, p, flags);
850 } 850 }
851 851
852 void activate_task(struct rq *rq, struct task_struct *p, int flags) 852 void activate_task(struct rq *rq, struct task_struct *p, int flags)
853 { 853 {
854 if (task_contributes_to_load(p)) 854 if (task_contributes_to_load(p))
855 rq->nr_uninterruptible--; 855 rq->nr_uninterruptible--;
856 856
857 enqueue_task(rq, p, flags); 857 enqueue_task(rq, p, flags);
858 } 858 }
859 859
860 void deactivate_task(struct rq *rq, struct task_struct *p, int flags) 860 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
861 { 861 {
862 if (task_contributes_to_load(p)) 862 if (task_contributes_to_load(p))
863 rq->nr_uninterruptible++; 863 rq->nr_uninterruptible++;
864 864
865 dequeue_task(rq, p, flags); 865 dequeue_task(rq, p, flags);
866 } 866 }
867 867
868 static void update_rq_clock_task(struct rq *rq, s64 delta) 868 static void update_rq_clock_task(struct rq *rq, s64 delta)
869 { 869 {
870 /* 870 /*
871 * In theory, the compile should just see 0 here, and optimize out the call 871 * In theory, the compile should just see 0 here, and optimize out the call
872 * to sched_rt_avg_update. But I don't trust it... 872 * to sched_rt_avg_update. But I don't trust it...
873 */ 873 */
874 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING) 874 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
875 s64 steal = 0, irq_delta = 0; 875 s64 steal = 0, irq_delta = 0;
876 #endif 876 #endif
877 #ifdef CONFIG_IRQ_TIME_ACCOUNTING 877 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
878 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time; 878 irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
879 879
880 /* 880 /*
881 * Since irq_time is only updated on {soft,}irq_exit, we might run into 881 * Since irq_time is only updated on {soft,}irq_exit, we might run into
882 * this case when a previous update_rq_clock() happened inside a 882 * this case when a previous update_rq_clock() happened inside a
883 * {soft,}irq region. 883 * {soft,}irq region.
884 * 884 *
885 * When this happens, we stop ->clock_task and only update the 885 * When this happens, we stop ->clock_task and only update the
886 * prev_irq_time stamp to account for the part that fit, so that a next 886 * prev_irq_time stamp to account for the part that fit, so that a next
887 * update will consume the rest. This ensures ->clock_task is 887 * update will consume the rest. This ensures ->clock_task is
888 * monotonic. 888 * monotonic.
889 * 889 *
890 * It does however cause some slight miss-attribution of {soft,}irq 890 * It does however cause some slight miss-attribution of {soft,}irq
891 * time, a more accurate solution would be to update the irq_time using 891 * time, a more accurate solution would be to update the irq_time using
892 * the current rq->clock timestamp, except that would require using 892 * the current rq->clock timestamp, except that would require using
893 * atomic ops. 893 * atomic ops.
894 */ 894 */
895 if (irq_delta > delta) 895 if (irq_delta > delta)
896 irq_delta = delta; 896 irq_delta = delta;
897 897
898 rq->prev_irq_time += irq_delta; 898 rq->prev_irq_time += irq_delta;
899 delta -= irq_delta; 899 delta -= irq_delta;
900 #endif 900 #endif
901 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING 901 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
902 if (static_key_false((&paravirt_steal_rq_enabled))) { 902 if (static_key_false((&paravirt_steal_rq_enabled))) {
903 steal = paravirt_steal_clock(cpu_of(rq)); 903 steal = paravirt_steal_clock(cpu_of(rq));
904 steal -= rq->prev_steal_time_rq; 904 steal -= rq->prev_steal_time_rq;
905 905
906 if (unlikely(steal > delta)) 906 if (unlikely(steal > delta))
907 steal = delta; 907 steal = delta;
908 908
909 rq->prev_steal_time_rq += steal; 909 rq->prev_steal_time_rq += steal;
910 delta -= steal; 910 delta -= steal;
911 } 911 }
912 #endif 912 #endif
913 913
914 rq->clock_task += delta; 914 rq->clock_task += delta;
915 915
916 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING) 916 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
917 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY)) 917 if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
918 sched_rt_avg_update(rq, irq_delta + steal); 918 sched_rt_avg_update(rq, irq_delta + steal);
919 #endif 919 #endif
920 } 920 }
921 921
922 void sched_set_stop_task(int cpu, struct task_struct *stop) 922 void sched_set_stop_task(int cpu, struct task_struct *stop)
923 { 923 {
924 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 }; 924 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
925 struct task_struct *old_stop = cpu_rq(cpu)->stop; 925 struct task_struct *old_stop = cpu_rq(cpu)->stop;
926 926
927 if (stop) { 927 if (stop) {
928 /* 928 /*
929 * Make it appear like a SCHED_FIFO task, its something 929 * Make it appear like a SCHED_FIFO task, its something
930 * userspace knows about and won't get confused about. 930 * userspace knows about and won't get confused about.
931 * 931 *
932 * Also, it will make PI more or less work without too 932 * Also, it will make PI more or less work without too
933 * much confusion -- but then, stop work should not 933 * much confusion -- but then, stop work should not
934 * rely on PI working anyway. 934 * rely on PI working anyway.
935 */ 935 */
936 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param); 936 sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
937 937
938 stop->sched_class = &stop_sched_class; 938 stop->sched_class = &stop_sched_class;
939 } 939 }
940 940
941 cpu_rq(cpu)->stop = stop; 941 cpu_rq(cpu)->stop = stop;
942 942
943 if (old_stop) { 943 if (old_stop) {
944 /* 944 /*
945 * Reset it back to a normal scheduling class so that 945 * Reset it back to a normal scheduling class so that
946 * it can die in pieces. 946 * it can die in pieces.
947 */ 947 */
948 old_stop->sched_class = &rt_sched_class; 948 old_stop->sched_class = &rt_sched_class;
949 } 949 }
950 } 950 }
951 951
952 /* 952 /*
953 * __normal_prio - return the priority that is based on the static prio 953 * __normal_prio - return the priority that is based on the static prio
954 */ 954 */
955 static inline int __normal_prio(struct task_struct *p) 955 static inline int __normal_prio(struct task_struct *p)
956 { 956 {
957 return p->static_prio; 957 return p->static_prio;
958 } 958 }
959 959
960 /* 960 /*
961 * Calculate the expected normal priority: i.e. priority 961 * Calculate the expected normal priority: i.e. priority
962 * without taking RT-inheritance into account. Might be 962 * without taking RT-inheritance into account. Might be
963 * boosted by interactivity modifiers. Changes upon fork, 963 * boosted by interactivity modifiers. Changes upon fork,
964 * setprio syscalls, and whenever the interactivity 964 * setprio syscalls, and whenever the interactivity
965 * estimator recalculates. 965 * estimator recalculates.
966 */ 966 */
967 static inline int normal_prio(struct task_struct *p) 967 static inline int normal_prio(struct task_struct *p)
968 { 968 {
969 int prio; 969 int prio;
970 970
971 if (task_has_dl_policy(p)) 971 if (task_has_dl_policy(p))
972 prio = MAX_DL_PRIO-1; 972 prio = MAX_DL_PRIO-1;
973 else if (task_has_rt_policy(p)) 973 else if (task_has_rt_policy(p))
974 prio = MAX_RT_PRIO-1 - p->rt_priority; 974 prio = MAX_RT_PRIO-1 - p->rt_priority;
975 else 975 else
976 prio = __normal_prio(p); 976 prio = __normal_prio(p);
977 return prio; 977 return prio;
978 } 978 }
979 979
980 /* 980 /*
981 * Calculate the current priority, i.e. the priority 981 * Calculate the current priority, i.e. the priority
982 * taken into account by the scheduler. This value might 982 * taken into account by the scheduler. This value might
983 * be boosted by RT tasks, or might be boosted by 983 * be boosted by RT tasks, or might be boosted by
984 * interactivity modifiers. Will be RT if the task got 984 * interactivity modifiers. Will be RT if the task got
985 * RT-boosted. If not then it returns p->normal_prio. 985 * RT-boosted. If not then it returns p->normal_prio.
986 */ 986 */
987 static int effective_prio(struct task_struct *p) 987 static int effective_prio(struct task_struct *p)
988 { 988 {
989 p->normal_prio = normal_prio(p); 989 p->normal_prio = normal_prio(p);
990 /* 990 /*
991 * If we are RT tasks or we were boosted to RT priority, 991 * If we are RT tasks or we were boosted to RT priority,
992 * keep the priority unchanged. Otherwise, update priority 992 * keep the priority unchanged. Otherwise, update priority
993 * to the normal priority: 993 * to the normal priority:
994 */ 994 */
995 if (!rt_prio(p->prio)) 995 if (!rt_prio(p->prio))
996 return p->normal_prio; 996 return p->normal_prio;
997 return p->prio; 997 return p->prio;
998 } 998 }
999 999
1000 /** 1000 /**
1001 * task_curr - is this task currently executing on a CPU? 1001 * task_curr - is this task currently executing on a CPU?
1002 * @p: the task in question. 1002 * @p: the task in question.
1003 * 1003 *
1004 * Return: 1 if the task is currently executing. 0 otherwise. 1004 * Return: 1 if the task is currently executing. 0 otherwise.
1005 */ 1005 */
1006 inline int task_curr(const struct task_struct *p) 1006 inline int task_curr(const struct task_struct *p)
1007 { 1007 {
1008 return cpu_curr(task_cpu(p)) == p; 1008 return cpu_curr(task_cpu(p)) == p;
1009 } 1009 }
1010 1010
1011 /* 1011 /*
1012 * Can drop rq->lock because from sched_class::switched_from() methods drop it. 1012 * Can drop rq->lock because from sched_class::switched_from() methods drop it.
1013 */ 1013 */
1014 static inline void check_class_changed(struct rq *rq, struct task_struct *p, 1014 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1015 const struct sched_class *prev_class, 1015 const struct sched_class *prev_class,
1016 int oldprio) 1016 int oldprio)
1017 { 1017 {
1018 if (prev_class != p->sched_class) { 1018 if (prev_class != p->sched_class) {
1019 if (prev_class->switched_from) 1019 if (prev_class->switched_from)
1020 prev_class->switched_from(rq, p); 1020 prev_class->switched_from(rq, p);
1021 /* Possble rq->lock 'hole'. */ 1021 /* Possble rq->lock 'hole'. */
1022 p->sched_class->switched_to(rq, p); 1022 p->sched_class->switched_to(rq, p);
1023 } else if (oldprio != p->prio || dl_task(p)) 1023 } else if (oldprio != p->prio || dl_task(p))
1024 p->sched_class->prio_changed(rq, p, oldprio); 1024 p->sched_class->prio_changed(rq, p, oldprio);
1025 } 1025 }
1026 1026
1027 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags) 1027 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
1028 { 1028 {
1029 const struct sched_class *class; 1029 const struct sched_class *class;
1030 1030
1031 if (p->sched_class == rq->curr->sched_class) { 1031 if (p->sched_class == rq->curr->sched_class) {
1032 rq->curr->sched_class->check_preempt_curr(rq, p, flags); 1032 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
1033 } else { 1033 } else {
1034 for_each_class(class) { 1034 for_each_class(class) {
1035 if (class == rq->curr->sched_class) 1035 if (class == rq->curr->sched_class)
1036 break; 1036 break;
1037 if (class == p->sched_class) { 1037 if (class == p->sched_class) {
1038 resched_curr(rq); 1038 resched_curr(rq);
1039 break; 1039 break;
1040 } 1040 }
1041 } 1041 }
1042 } 1042 }
1043 1043
1044 /* 1044 /*
1045 * A queue event has occurred, and we're going to schedule. In 1045 * A queue event has occurred, and we're going to schedule. In
1046 * this case, we can save a useless back to back clock update. 1046 * this case, we can save a useless back to back clock update.
1047 */ 1047 */
1048 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr)) 1048 if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
1049 rq->skip_clock_update = 1; 1049 rq->skip_clock_update = 1;
1050 } 1050 }
1051 1051
1052 #ifdef CONFIG_SMP 1052 #ifdef CONFIG_SMP
1053 void set_task_cpu(struct task_struct *p, unsigned int new_cpu) 1053 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1054 { 1054 {
1055 #ifdef CONFIG_SCHED_DEBUG 1055 #ifdef CONFIG_SCHED_DEBUG
1056 /* 1056 /*
1057 * We should never call set_task_cpu() on a blocked task, 1057 * We should never call set_task_cpu() on a blocked task,
1058 * ttwu() will sort out the placement. 1058 * ttwu() will sort out the placement.
1059 */ 1059 */
1060 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING && 1060 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
1061 !p->on_rq); 1061 !p->on_rq);
1062 1062
1063 #ifdef CONFIG_LOCKDEP 1063 #ifdef CONFIG_LOCKDEP
1064 /* 1064 /*
1065 * The caller should hold either p->pi_lock or rq->lock, when changing 1065 * The caller should hold either p->pi_lock or rq->lock, when changing
1066 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks. 1066 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1067 * 1067 *
1068 * sched_move_task() holds both and thus holding either pins the cgroup, 1068 * sched_move_task() holds both and thus holding either pins the cgroup,
1069 * see task_group(). 1069 * see task_group().
1070 * 1070 *
1071 * Furthermore, all task_rq users should acquire both locks, see 1071 * Furthermore, all task_rq users should acquire both locks, see
1072 * task_rq_lock(). 1072 * task_rq_lock().
1073 */ 1073 */
1074 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) || 1074 WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1075 lockdep_is_held(&task_rq(p)->lock))); 1075 lockdep_is_held(&task_rq(p)->lock)));
1076 #endif 1076 #endif
1077 #endif 1077 #endif
1078 1078
1079 trace_sched_migrate_task(p, new_cpu); 1079 trace_sched_migrate_task(p, new_cpu);
1080 1080
1081 if (task_cpu(p) != new_cpu) { 1081 if (task_cpu(p) != new_cpu) {
1082 if (p->sched_class->migrate_task_rq) 1082 if (p->sched_class->migrate_task_rq)
1083 p->sched_class->migrate_task_rq(p, new_cpu); 1083 p->sched_class->migrate_task_rq(p, new_cpu);
1084 p->se.nr_migrations++; 1084 p->se.nr_migrations++;
1085 perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, NULL, 0); 1085 perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, NULL, 0);
1086 } 1086 }
1087 1087
1088 __set_task_cpu(p, new_cpu); 1088 __set_task_cpu(p, new_cpu);
1089 } 1089 }
1090 1090
1091 static void __migrate_swap_task(struct task_struct *p, int cpu) 1091 static void __migrate_swap_task(struct task_struct *p, int cpu)
1092 { 1092 {
1093 if (task_on_rq_queued(p)) { 1093 if (task_on_rq_queued(p)) {
1094 struct rq *src_rq, *dst_rq; 1094 struct rq *src_rq, *dst_rq;
1095 1095
1096 src_rq = task_rq(p); 1096 src_rq = task_rq(p);
1097 dst_rq = cpu_rq(cpu); 1097 dst_rq = cpu_rq(cpu);
1098 1098
1099 deactivate_task(src_rq, p, 0); 1099 deactivate_task(src_rq, p, 0);
1100 set_task_cpu(p, cpu); 1100 set_task_cpu(p, cpu);
1101 activate_task(dst_rq, p, 0); 1101 activate_task(dst_rq, p, 0);
1102 check_preempt_curr(dst_rq, p, 0); 1102 check_preempt_curr(dst_rq, p, 0);
1103 } else { 1103 } else {
1104 /* 1104 /*
1105 * Task isn't running anymore; make it appear like we migrated 1105 * Task isn't running anymore; make it appear like we migrated
1106 * it before it went to sleep. This means on wakeup we make the 1106 * it before it went to sleep. This means on wakeup we make the
1107 * previous cpu our targer instead of where it really is. 1107 * previous cpu our targer instead of where it really is.
1108 */ 1108 */
1109 p->wake_cpu = cpu; 1109 p->wake_cpu = cpu;
1110 } 1110 }
1111 } 1111 }
1112 1112
1113 struct migration_swap_arg { 1113 struct migration_swap_arg {
1114 struct task_struct *src_task, *dst_task; 1114 struct task_struct *src_task, *dst_task;
1115 int src_cpu, dst_cpu; 1115 int src_cpu, dst_cpu;
1116 }; 1116 };
1117 1117
1118 static int migrate_swap_stop(void *data) 1118 static int migrate_swap_stop(void *data)
1119 { 1119 {
1120 struct migration_swap_arg *arg = data; 1120 struct migration_swap_arg *arg = data;
1121 struct rq *src_rq, *dst_rq; 1121 struct rq *src_rq, *dst_rq;
1122 int ret = -EAGAIN; 1122 int ret = -EAGAIN;
1123 1123
1124 src_rq = cpu_rq(arg->src_cpu); 1124 src_rq = cpu_rq(arg->src_cpu);
1125 dst_rq = cpu_rq(arg->dst_cpu); 1125 dst_rq = cpu_rq(arg->dst_cpu);
1126 1126
1127 double_raw_lock(&arg->src_task->pi_lock, 1127 double_raw_lock(&arg->src_task->pi_lock,
1128 &arg->dst_task->pi_lock); 1128 &arg->dst_task->pi_lock);
1129 double_rq_lock(src_rq, dst_rq); 1129 double_rq_lock(src_rq, dst_rq);
1130 if (task_cpu(arg->dst_task) != arg->dst_cpu) 1130 if (task_cpu(arg->dst_task) != arg->dst_cpu)
1131 goto unlock; 1131 goto unlock;
1132 1132
1133 if (task_cpu(arg->src_task) != arg->src_cpu) 1133 if (task_cpu(arg->src_task) != arg->src_cpu)
1134 goto unlock; 1134 goto unlock;
1135 1135
1136 if (!cpumask_test_cpu(arg->dst_cpu, tsk_cpus_allowed(arg->src_task))) 1136 if (!cpumask_test_cpu(arg->dst_cpu, tsk_cpus_allowed(arg->src_task)))
1137 goto unlock; 1137 goto unlock;
1138 1138
1139 if (!cpumask_test_cpu(arg->src_cpu, tsk_cpus_allowed(arg->dst_task))) 1139 if (!cpumask_test_cpu(arg->src_cpu, tsk_cpus_allowed(arg->dst_task)))
1140 goto unlock; 1140 goto unlock;
1141 1141
1142 __migrate_swap_task(arg->src_task, arg->dst_cpu); 1142 __migrate_swap_task(arg->src_task, arg->dst_cpu);
1143 __migrate_swap_task(arg->dst_task, arg->src_cpu); 1143 __migrate_swap_task(arg->dst_task, arg->src_cpu);
1144 1144
1145 ret = 0; 1145 ret = 0;
1146 1146
1147 unlock: 1147 unlock:
1148 double_rq_unlock(src_rq, dst_rq); 1148 double_rq_unlock(src_rq, dst_rq);
1149 raw_spin_unlock(&arg->dst_task->pi_lock); 1149 raw_spin_unlock(&arg->dst_task->pi_lock);
1150 raw_spin_unlock(&arg->src_task->pi_lock); 1150 raw_spin_unlock(&arg->src_task->pi_lock);
1151 1151
1152 return ret; 1152 return ret;
1153 } 1153 }
1154 1154
1155 /* 1155 /*
1156 * Cross migrate two tasks 1156 * Cross migrate two tasks
1157 */ 1157 */
1158 int migrate_swap(struct task_struct *cur, struct task_struct *p) 1158 int migrate_swap(struct task_struct *cur, struct task_struct *p)
1159 { 1159 {
1160 struct migration_swap_arg arg; 1160 struct migration_swap_arg arg;
1161 int ret = -EINVAL; 1161 int ret = -EINVAL;
1162 1162
1163 arg = (struct migration_swap_arg){ 1163 arg = (struct migration_swap_arg){
1164 .src_task = cur, 1164 .src_task = cur,
1165 .src_cpu = task_cpu(cur), 1165 .src_cpu = task_cpu(cur),
1166 .dst_task = p, 1166 .dst_task = p,
1167 .dst_cpu = task_cpu(p), 1167 .dst_cpu = task_cpu(p),
1168 }; 1168 };
1169 1169
1170 if (arg.src_cpu == arg.dst_cpu) 1170 if (arg.src_cpu == arg.dst_cpu)
1171 goto out; 1171 goto out;
1172 1172
1173 /* 1173 /*
1174 * These three tests are all lockless; this is OK since all of them 1174 * These three tests are all lockless; this is OK since all of them
1175 * will be re-checked with proper locks held further down the line. 1175 * will be re-checked with proper locks held further down the line.
1176 */ 1176 */
1177 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu)) 1177 if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
1178 goto out; 1178 goto out;
1179 1179
1180 if (!cpumask_test_cpu(arg.dst_cpu, tsk_cpus_allowed(arg.src_task))) 1180 if (!cpumask_test_cpu(arg.dst_cpu, tsk_cpus_allowed(arg.src_task)))
1181 goto out; 1181 goto out;
1182 1182
1183 if (!cpumask_test_cpu(arg.src_cpu, tsk_cpus_allowed(arg.dst_task))) 1183 if (!cpumask_test_cpu(arg.src_cpu, tsk_cpus_allowed(arg.dst_task)))
1184 goto out; 1184 goto out;
1185 1185
1186 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu); 1186 trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
1187 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg); 1187 ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
1188 1188
1189 out: 1189 out:
1190 return ret; 1190 return ret;
1191 } 1191 }
1192 1192
1193 struct migration_arg { 1193 struct migration_arg {
1194 struct task_struct *task; 1194 struct task_struct *task;
1195 int dest_cpu; 1195 int dest_cpu;
1196 }; 1196 };
1197 1197
1198 static int migration_cpu_stop(void *data); 1198 static int migration_cpu_stop(void *data);
1199 1199
1200 /* 1200 /*
1201 * wait_task_inactive - wait for a thread to unschedule. 1201 * wait_task_inactive - wait for a thread to unschedule.
1202 * 1202 *
1203 * If @match_state is nonzero, it's the @p->state value just checked and 1203 * If @match_state is nonzero, it's the @p->state value just checked and
1204 * not expected to change. If it changes, i.e. @p might have woken up, 1204 * not expected to change. If it changes, i.e. @p might have woken up,
1205 * then return zero. When we succeed in waiting for @p to be off its CPU, 1205 * then return zero. When we succeed in waiting for @p to be off its CPU,
1206 * we return a positive number (its total switch count). If a second call 1206 * we return a positive number (its total switch count). If a second call
1207 * a short while later returns the same number, the caller can be sure that 1207 * a short while later returns the same number, the caller can be sure that
1208 * @p has remained unscheduled the whole time. 1208 * @p has remained unscheduled the whole time.
1209 * 1209 *
1210 * The caller must ensure that the task *will* unschedule sometime soon, 1210 * The caller must ensure that the task *will* unschedule sometime soon,
1211 * else this function might spin for a *long* time. This function can't 1211 * else this function might spin for a *long* time. This function can't
1212 * be called with interrupts off, or it may introduce deadlock with 1212 * be called with interrupts off, or it may introduce deadlock with
1213 * smp_call_function() if an IPI is sent by the same process we are 1213 * smp_call_function() if an IPI is sent by the same process we are
1214 * waiting to become inactive. 1214 * waiting to become inactive.
1215 */ 1215 */
1216 unsigned long wait_task_inactive(struct task_struct *p, long match_state) 1216 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1217 { 1217 {
1218 unsigned long flags; 1218 unsigned long flags;
1219 int running, queued; 1219 int running, queued;
1220 unsigned long ncsw; 1220 unsigned long ncsw;
1221 struct rq *rq; 1221 struct rq *rq;
1222 1222
1223 for (;;) { 1223 for (;;) {
1224 /* 1224 /*
1225 * We do the initial early heuristics without holding 1225 * We do the initial early heuristics without holding
1226 * any task-queue locks at all. We'll only try to get 1226 * any task-queue locks at all. We'll only try to get
1227 * the runqueue lock when things look like they will 1227 * the runqueue lock when things look like they will
1228 * work out! 1228 * work out!
1229 */ 1229 */
1230 rq = task_rq(p); 1230 rq = task_rq(p);
1231 1231
1232 /* 1232 /*
1233 * If the task is actively running on another CPU 1233 * If the task is actively running on another CPU
1234 * still, just relax and busy-wait without holding 1234 * still, just relax and busy-wait without holding
1235 * any locks. 1235 * any locks.
1236 * 1236 *
1237 * NOTE! Since we don't hold any locks, it's not 1237 * NOTE! Since we don't hold any locks, it's not
1238 * even sure that "rq" stays as the right runqueue! 1238 * even sure that "rq" stays as the right runqueue!
1239 * But we don't care, since "task_running()" will 1239 * But we don't care, since "task_running()" will
1240 * return false if the runqueue has changed and p 1240 * return false if the runqueue has changed and p
1241 * is actually now running somewhere else! 1241 * is actually now running somewhere else!
1242 */ 1242 */
1243 while (task_running(rq, p)) { 1243 while (task_running(rq, p)) {
1244 if (match_state && unlikely(p->state != match_state)) 1244 if (match_state && unlikely(p->state != match_state))
1245 return 0; 1245 return 0;
1246 cpu_relax(); 1246 cpu_relax();
1247 } 1247 }
1248 1248
1249 /* 1249 /*
1250 * Ok, time to look more closely! We need the rq 1250 * Ok, time to look more closely! We need the rq
1251 * lock now, to be *sure*. If we're wrong, we'll 1251 * lock now, to be *sure*. If we're wrong, we'll
1252 * just go back and repeat. 1252 * just go back and repeat.
1253 */ 1253 */
1254 rq = task_rq_lock(p, &flags); 1254 rq = task_rq_lock(p, &flags);
1255 trace_sched_wait_task(p); 1255 trace_sched_wait_task(p);
1256 running = task_running(rq, p); 1256 running = task_running(rq, p);
1257 queued = task_on_rq_queued(p); 1257 queued = task_on_rq_queued(p);
1258 ncsw = 0; 1258 ncsw = 0;
1259 if (!match_state || p->state == match_state) 1259 if (!match_state || p->state == match_state)
1260 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */ 1260 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
1261 task_rq_unlock(rq, p, &flags); 1261 task_rq_unlock(rq, p, &flags);
1262 1262
1263 /* 1263 /*
1264 * If it changed from the expected state, bail out now. 1264 * If it changed from the expected state, bail out now.
1265 */ 1265 */
1266 if (unlikely(!ncsw)) 1266 if (unlikely(!ncsw))
1267 break; 1267 break;
1268 1268
1269 /* 1269 /*
1270 * Was it really running after all now that we 1270 * Was it really running after all now that we
1271 * checked with the proper locks actually held? 1271 * checked with the proper locks actually held?
1272 * 1272 *
1273 * Oops. Go back and try again.. 1273 * Oops. Go back and try again..
1274 */ 1274 */
1275 if (unlikely(running)) { 1275 if (unlikely(running)) {
1276 cpu_relax(); 1276 cpu_relax();
1277 continue; 1277 continue;
1278 } 1278 }
1279 1279
1280 /* 1280 /*
1281 * It's not enough that it's not actively running, 1281 * It's not enough that it's not actively running,
1282 * it must be off the runqueue _entirely_, and not 1282 * it must be off the runqueue _entirely_, and not
1283 * preempted! 1283 * preempted!
1284 * 1284 *
1285 * So if it was still runnable (but just not actively 1285 * So if it was still runnable (but just not actively
1286 * running right now), it's preempted, and we should 1286 * running right now), it's preempted, and we should
1287 * yield - it could be a while. 1287 * yield - it could be a while.
1288 */ 1288 */
1289 if (unlikely(queued)) { 1289 if (unlikely(queued)) {
1290 ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ); 1290 ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
1291 1291
1292 set_current_state(TASK_UNINTERRUPTIBLE); 1292 set_current_state(TASK_UNINTERRUPTIBLE);
1293 schedule_hrtimeout(&to, HRTIMER_MODE_REL); 1293 schedule_hrtimeout(&to, HRTIMER_MODE_REL);
1294 continue; 1294 continue;
1295 } 1295 }
1296 1296
1297 /* 1297 /*
1298 * Ahh, all good. It wasn't running, and it wasn't 1298 * Ahh, all good. It wasn't running, and it wasn't
1299 * runnable, which means that it will never become 1299 * runnable, which means that it will never become
1300 * running in the future either. We're all done! 1300 * running in the future either. We're all done!
1301 */ 1301 */
1302 break; 1302 break;
1303 } 1303 }
1304 1304
1305 return ncsw; 1305 return ncsw;
1306 } 1306 }
1307 1307
1308 /*** 1308 /***
1309 * kick_process - kick a running thread to enter/exit the kernel 1309 * kick_process - kick a running thread to enter/exit the kernel
1310 * @p: the to-be-kicked thread 1310 * @p: the to-be-kicked thread
1311 * 1311 *
1312 * Cause a process which is running on another CPU to enter 1312 * Cause a process which is running on another CPU to enter
1313 * kernel-mode, without any delay. (to get signals handled.) 1313 * kernel-mode, without any delay. (to get signals handled.)
1314 * 1314 *
1315 * NOTE: this function doesn't have to take the runqueue lock, 1315 * NOTE: this function doesn't have to take the runqueue lock,
1316 * because all it wants to ensure is that the remote task enters 1316 * because all it wants to ensure is that the remote task enters
1317 * the kernel. If the IPI races and the task has been migrated 1317 * the kernel. If the IPI races and the task has been migrated
1318 * to another CPU then no harm is done and the purpose has been 1318 * to another CPU then no harm is done and the purpose has been
1319 * achieved as well. 1319 * achieved as well.
1320 */ 1320 */
1321 void kick_process(struct task_struct *p) 1321 void kick_process(struct task_struct *p)
1322 { 1322 {
1323 int cpu; 1323 int cpu;
1324 1324
1325 preempt_disable(); 1325 preempt_disable();
1326 cpu = task_cpu(p); 1326 cpu = task_cpu(p);
1327 if ((cpu != smp_processor_id()) && task_curr(p)) 1327 if ((cpu != smp_processor_id()) && task_curr(p))
1328 smp_send_reschedule(cpu); 1328 smp_send_reschedule(cpu);
1329 preempt_enable(); 1329 preempt_enable();
1330 } 1330 }
1331 EXPORT_SYMBOL_GPL(kick_process); 1331 EXPORT_SYMBOL_GPL(kick_process);
1332 #endif /* CONFIG_SMP */ 1332 #endif /* CONFIG_SMP */
1333 1333
1334 #ifdef CONFIG_SMP 1334 #ifdef CONFIG_SMP
1335 /* 1335 /*
1336 * ->cpus_allowed is protected by both rq->lock and p->pi_lock 1336 * ->cpus_allowed is protected by both rq->lock and p->pi_lock
1337 */ 1337 */
1338 static int select_fallback_rq(int cpu, struct task_struct *p) 1338 static int select_fallback_rq(int cpu, struct task_struct *p)
1339 { 1339 {
1340 int nid = cpu_to_node(cpu); 1340 int nid = cpu_to_node(cpu);
1341 const struct cpumask *nodemask = NULL; 1341 const struct cpumask *nodemask = NULL;
1342 enum { cpuset, possible, fail } state = cpuset; 1342 enum { cpuset, possible, fail } state = cpuset;
1343 int dest_cpu; 1343 int dest_cpu;
1344 1344
1345 /* 1345 /*
1346 * If the node that the cpu is on has been offlined, cpu_to_node() 1346 * If the node that the cpu is on has been offlined, cpu_to_node()
1347 * will return -1. There is no cpu on the node, and we should 1347 * will return -1. There is no cpu on the node, and we should
1348 * select the cpu on the other node. 1348 * select the cpu on the other node.
1349 */ 1349 */
1350 if (nid != -1) { 1350 if (nid != -1) {
1351 nodemask = cpumask_of_node(nid); 1351 nodemask = cpumask_of_node(nid);
1352 1352
1353 /* Look for allowed, online CPU in same node. */ 1353 /* Look for allowed, online CPU in same node. */
1354 for_each_cpu(dest_cpu, nodemask) { 1354 for_each_cpu(dest_cpu, nodemask) {
1355 if (!cpu_online(dest_cpu)) 1355 if (!cpu_online(dest_cpu))
1356 continue; 1356 continue;
1357 if (!cpu_active(dest_cpu)) 1357 if (!cpu_active(dest_cpu))
1358 continue; 1358 continue;
1359 if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p))) 1359 if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
1360 return dest_cpu; 1360 return dest_cpu;
1361 } 1361 }
1362 } 1362 }
1363 1363
1364 for (;;) { 1364 for (;;) {
1365 /* Any allowed, online CPU? */ 1365 /* Any allowed, online CPU? */
1366 for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) { 1366 for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
1367 if (!cpu_online(dest_cpu)) 1367 if (!cpu_online(dest_cpu))
1368 continue; 1368 continue;
1369 if (!cpu_active(dest_cpu)) 1369 if (!cpu_active(dest_cpu))
1370 continue; 1370 continue;
1371 goto out; 1371 goto out;
1372 } 1372 }
1373 1373
1374 switch (state) { 1374 switch (state) {
1375 case cpuset: 1375 case cpuset:
1376 /* No more Mr. Nice Guy. */ 1376 /* No more Mr. Nice Guy. */
1377 cpuset_cpus_allowed_fallback(p); 1377 cpuset_cpus_allowed_fallback(p);
1378 state = possible; 1378 state = possible;
1379 break; 1379 break;
1380 1380
1381 case possible: 1381 case possible:
1382 do_set_cpus_allowed(p, cpu_possible_mask); 1382 do_set_cpus_allowed(p, cpu_possible_mask);
1383 state = fail; 1383 state = fail;
1384 break; 1384 break;
1385 1385
1386 case fail: 1386 case fail:
1387 BUG(); 1387 BUG();
1388 break; 1388 break;
1389 } 1389 }
1390 } 1390 }
1391 1391
1392 out: 1392 out:
1393 if (state != cpuset) { 1393 if (state != cpuset) {
1394 /* 1394 /*
1395 * Don't tell them about moving exiting tasks or 1395 * Don't tell them about moving exiting tasks or
1396 * kernel threads (both mm NULL), since they never 1396 * kernel threads (both mm NULL), since they never
1397 * leave kernel. 1397 * leave kernel.
1398 */ 1398 */
1399 if (p->mm && printk_ratelimit()) { 1399 if (p->mm && printk_ratelimit()) {
1400 printk_deferred("process %d (%s) no longer affine to cpu%d\n", 1400 printk_deferred("process %d (%s) no longer affine to cpu%d\n",
1401 task_pid_nr(p), p->comm, cpu); 1401 task_pid_nr(p), p->comm, cpu);
1402 } 1402 }
1403 } 1403 }
1404 1404
1405 return dest_cpu; 1405 return dest_cpu;
1406 } 1406 }
1407 1407
1408 /* 1408 /*
1409 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable. 1409 * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
1410 */ 1410 */
1411 static inline 1411 static inline
1412 int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags) 1412 int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
1413 { 1413 {
1414 if (p->nr_cpus_allowed > 1) 1414 if (p->nr_cpus_allowed > 1)
1415 cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags); 1415 cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
1416 1416
1417 /* 1417 /*
1418 * In order not to call set_task_cpu() on a blocking task we need 1418 * In order not to call set_task_cpu() on a blocking task we need
1419 * to rely on ttwu() to place the task on a valid ->cpus_allowed 1419 * to rely on ttwu() to place the task on a valid ->cpus_allowed
1420 * cpu. 1420 * cpu.
1421 * 1421 *
1422 * Since this is common to all placement strategies, this lives here. 1422 * Since this is common to all placement strategies, this lives here.
1423 * 1423 *
1424 * [ this allows ->select_task() to simply return task_cpu(p) and 1424 * [ this allows ->select_task() to simply return task_cpu(p) and
1425 * not worry about this generic constraint ] 1425 * not worry about this generic constraint ]
1426 */ 1426 */
1427 if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) || 1427 if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
1428 !cpu_online(cpu))) 1428 !cpu_online(cpu)))
1429 cpu = select_fallback_rq(task_cpu(p), p); 1429 cpu = select_fallback_rq(task_cpu(p), p);
1430 1430
1431 return cpu; 1431 return cpu;
1432 } 1432 }
1433 1433
1434 static void update_avg(u64 *avg, u64 sample) 1434 static void update_avg(u64 *avg, u64 sample)
1435 { 1435 {
1436 s64 diff = sample - *avg; 1436 s64 diff = sample - *avg;
1437 *avg += diff >> 3; 1437 *avg += diff >> 3;
1438 } 1438 }
1439 #endif 1439 #endif
1440 1440
1441 static void 1441 static void
1442 ttwu_stat(struct task_struct *p, int cpu, int wake_flags) 1442 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
1443 { 1443 {
1444 #ifdef CONFIG_SCHEDSTATS 1444 #ifdef CONFIG_SCHEDSTATS
1445 struct rq *rq = this_rq(); 1445 struct rq *rq = this_rq();
1446 1446
1447 #ifdef CONFIG_SMP 1447 #ifdef CONFIG_SMP
1448 int this_cpu = smp_processor_id(); 1448 int this_cpu = smp_processor_id();
1449 1449
1450 if (cpu == this_cpu) { 1450 if (cpu == this_cpu) {
1451 schedstat_inc(rq, ttwu_local); 1451 schedstat_inc(rq, ttwu_local);
1452 schedstat_inc(p, se.statistics.nr_wakeups_local); 1452 schedstat_inc(p, se.statistics.nr_wakeups_local);
1453 } else { 1453 } else {
1454 struct sched_domain *sd; 1454 struct sched_domain *sd;
1455 1455
1456 schedstat_inc(p, se.statistics.nr_wakeups_remote); 1456 schedstat_inc(p, se.statistics.nr_wakeups_remote);
1457 rcu_read_lock(); 1457 rcu_read_lock();
1458 for_each_domain(this_cpu, sd) { 1458 for_each_domain(this_cpu, sd) {
1459 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) { 1459 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
1460 schedstat_inc(sd, ttwu_wake_remote); 1460 schedstat_inc(sd, ttwu_wake_remote);
1461 break; 1461 break;
1462 } 1462 }
1463 } 1463 }
1464 rcu_read_unlock(); 1464 rcu_read_unlock();
1465 } 1465 }
1466 1466
1467 if (wake_flags & WF_MIGRATED) 1467 if (wake_flags & WF_MIGRATED)
1468 schedstat_inc(p, se.statistics.nr_wakeups_migrate); 1468 schedstat_inc(p, se.statistics.nr_wakeups_migrate);
1469 1469
1470 #endif /* CONFIG_SMP */ 1470 #endif /* CONFIG_SMP */
1471 1471
1472 schedstat_inc(rq, ttwu_count); 1472 schedstat_inc(rq, ttwu_count);
1473 schedstat_inc(p, se.statistics.nr_wakeups); 1473 schedstat_inc(p, se.statistics.nr_wakeups);
1474 1474
1475 if (wake_flags & WF_SYNC) 1475 if (wake_flags & WF_SYNC)
1476 schedstat_inc(p, se.statistics.nr_wakeups_sync); 1476 schedstat_inc(p, se.statistics.nr_wakeups_sync);
1477 1477
1478 #endif /* CONFIG_SCHEDSTATS */ 1478 #endif /* CONFIG_SCHEDSTATS */
1479 } 1479 }
1480 1480
1481 static void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags) 1481 static void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
1482 { 1482 {
1483 activate_task(rq, p, en_flags); 1483 activate_task(rq, p, en_flags);
1484 p->on_rq = TASK_ON_RQ_QUEUED; 1484 p->on_rq = TASK_ON_RQ_QUEUED;
1485 1485
1486 /* if a worker is waking up, notify workqueue */ 1486 /* if a worker is waking up, notify workqueue */
1487 if (p->flags & PF_WQ_WORKER) 1487 if (p->flags & PF_WQ_WORKER)
1488 wq_worker_waking_up(p, cpu_of(rq)); 1488 wq_worker_waking_up(p, cpu_of(rq));
1489 } 1489 }
1490 1490
1491 /* 1491 /*
1492 * Mark the task runnable and perform wakeup-preemption. 1492 * Mark the task runnable and perform wakeup-preemption.
1493 */ 1493 */
1494 static void 1494 static void
1495 ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags) 1495 ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
1496 { 1496 {
1497 check_preempt_curr(rq, p, wake_flags); 1497 check_preempt_curr(rq, p, wake_flags);
1498 trace_sched_wakeup(p, true); 1498 trace_sched_wakeup(p, true);
1499 1499
1500 p->state = TASK_RUNNING; 1500 p->state = TASK_RUNNING;
1501 #ifdef CONFIG_SMP 1501 #ifdef CONFIG_SMP
1502 if (p->sched_class->task_woken) 1502 if (p->sched_class->task_woken)
1503 p->sched_class->task_woken(rq, p); 1503 p->sched_class->task_woken(rq, p);
1504 1504
1505 if (rq->idle_stamp) { 1505 if (rq->idle_stamp) {
1506 u64 delta = rq_clock(rq) - rq->idle_stamp; 1506 u64 delta = rq_clock(rq) - rq->idle_stamp;
1507 u64 max = 2*rq->max_idle_balance_cost; 1507 u64 max = 2*rq->max_idle_balance_cost;
1508 1508
1509 update_avg(&rq->avg_idle, delta); 1509 update_avg(&rq->avg_idle, delta);
1510 1510
1511 if (rq->avg_idle > max) 1511 if (rq->avg_idle > max)
1512 rq->avg_idle = max; 1512 rq->avg_idle = max;
1513 1513
1514 rq->idle_stamp = 0; 1514 rq->idle_stamp = 0;
1515 } 1515 }
1516 #endif 1516 #endif
1517 } 1517 }
1518 1518
1519 static void 1519 static void
1520 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags) 1520 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags)
1521 { 1521 {
1522 #ifdef CONFIG_SMP 1522 #ifdef CONFIG_SMP
1523 if (p->sched_contributes_to_load) 1523 if (p->sched_contributes_to_load)
1524 rq->nr_uninterruptible--; 1524 rq->nr_uninterruptible--;
1525 #endif 1525 #endif
1526 1526
1527 ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING); 1527 ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING);
1528 ttwu_do_wakeup(rq, p, wake_flags); 1528 ttwu_do_wakeup(rq, p, wake_flags);
1529 } 1529 }
1530 1530
1531 /* 1531 /*
1532 * Called in case the task @p isn't fully descheduled from its runqueue, 1532 * Called in case the task @p isn't fully descheduled from its runqueue,
1533 * in this case we must do a remote wakeup. Its a 'light' wakeup though, 1533 * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1534 * since all we need to do is flip p->state to TASK_RUNNING, since 1534 * since all we need to do is flip p->state to TASK_RUNNING, since
1535 * the task is still ->on_rq. 1535 * the task is still ->on_rq.
1536 */ 1536 */
1537 static int ttwu_remote(struct task_struct *p, int wake_flags) 1537 static int ttwu_remote(struct task_struct *p, int wake_flags)
1538 { 1538 {
1539 struct rq *rq; 1539 struct rq *rq;
1540 int ret = 0; 1540 int ret = 0;
1541 1541
1542 rq = __task_rq_lock(p); 1542 rq = __task_rq_lock(p);
1543 if (task_on_rq_queued(p)) { 1543 if (task_on_rq_queued(p)) {
1544 /* check_preempt_curr() may use rq clock */ 1544 /* check_preempt_curr() may use rq clock */
1545 update_rq_clock(rq); 1545 update_rq_clock(rq);
1546 ttwu_do_wakeup(rq, p, wake_flags); 1546 ttwu_do_wakeup(rq, p, wake_flags);
1547 ret = 1; 1547 ret = 1;
1548 } 1548 }
1549 __task_rq_unlock(rq); 1549 __task_rq_unlock(rq);
1550 1550
1551 return ret; 1551 return ret;
1552 } 1552 }
1553 1553
1554 #ifdef CONFIG_SMP 1554 #ifdef CONFIG_SMP
1555 void sched_ttwu_pending(void) 1555 void sched_ttwu_pending(void)
1556 { 1556 {
1557 struct rq *rq = this_rq(); 1557 struct rq *rq = this_rq();
1558 struct llist_node *llist = llist_del_all(&rq->wake_list); 1558 struct llist_node *llist = llist_del_all(&rq->wake_list);
1559 struct task_struct *p; 1559 struct task_struct *p;
1560 unsigned long flags; 1560 unsigned long flags;
1561 1561
1562 if (!llist) 1562 if (!llist)
1563 return; 1563 return;
1564 1564
1565 raw_spin_lock_irqsave(&rq->lock, flags); 1565 raw_spin_lock_irqsave(&rq->lock, flags);
1566 1566
1567 while (llist) { 1567 while (llist) {
1568 p = llist_entry(llist, struct task_struct, wake_entry); 1568 p = llist_entry(llist, struct task_struct, wake_entry);
1569 llist = llist_next(llist); 1569 llist = llist_next(llist);
1570 ttwu_do_activate(rq, p, 0); 1570 ttwu_do_activate(rq, p, 0);
1571 } 1571 }
1572 1572
1573 raw_spin_unlock_irqrestore(&rq->lock, flags); 1573 raw_spin_unlock_irqrestore(&rq->lock, flags);
1574 } 1574 }
1575 1575
1576 void scheduler_ipi(void) 1576 void scheduler_ipi(void)
1577 { 1577 {
1578 /* 1578 /*
1579 * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting 1579 * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
1580 * TIF_NEED_RESCHED remotely (for the first time) will also send 1580 * TIF_NEED_RESCHED remotely (for the first time) will also send
1581 * this IPI. 1581 * this IPI.
1582 */ 1582 */
1583 preempt_fold_need_resched(); 1583 preempt_fold_need_resched();
1584 1584
1585 if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick()) 1585 if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
1586 return; 1586 return;
1587 1587
1588 /* 1588 /*
1589 * Not all reschedule IPI handlers call irq_enter/irq_exit, since 1589 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1590 * traditionally all their work was done from the interrupt return 1590 * traditionally all their work was done from the interrupt return
1591 * path. Now that we actually do some work, we need to make sure 1591 * path. Now that we actually do some work, we need to make sure
1592 * we do call them. 1592 * we do call them.
1593 * 1593 *
1594 * Some archs already do call them, luckily irq_enter/exit nest 1594 * Some archs already do call them, luckily irq_enter/exit nest
1595 * properly. 1595 * properly.
1596 * 1596 *
1597 * Arguably we should visit all archs and update all handlers, 1597 * Arguably we should visit all archs and update all handlers,
1598 * however a fair share of IPIs are still resched only so this would 1598 * however a fair share of IPIs are still resched only so this would
1599 * somewhat pessimize the simple resched case. 1599 * somewhat pessimize the simple resched case.
1600 */ 1600 */
1601 irq_enter(); 1601 irq_enter();
1602 sched_ttwu_pending(); 1602 sched_ttwu_pending();
1603 1603
1604 /* 1604 /*
1605 * Check if someone kicked us for doing the nohz idle load balance. 1605 * Check if someone kicked us for doing the nohz idle load balance.
1606 */ 1606 */
1607 if (unlikely(got_nohz_idle_kick())) { 1607 if (unlikely(got_nohz_idle_kick())) {
1608 this_rq()->idle_balance = 1; 1608 this_rq()->idle_balance = 1;
1609 raise_softirq_irqoff(SCHED_SOFTIRQ); 1609 raise_softirq_irqoff(SCHED_SOFTIRQ);
1610 } 1610 }
1611 irq_exit(); 1611 irq_exit();
1612 } 1612 }
1613 1613
1614 static void ttwu_queue_remote(struct task_struct *p, int cpu) 1614 static void ttwu_queue_remote(struct task_struct *p, int cpu)
1615 { 1615 {
1616 struct rq *rq = cpu_rq(cpu); 1616 struct rq *rq = cpu_rq(cpu);
1617 1617
1618 if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) { 1618 if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
1619 if (!set_nr_if_polling(rq->idle)) 1619 if (!set_nr_if_polling(rq->idle))
1620 smp_send_reschedule(cpu); 1620 smp_send_reschedule(cpu);
1621 else 1621 else
1622 trace_sched_wake_idle_without_ipi(cpu); 1622 trace_sched_wake_idle_without_ipi(cpu);
1623 } 1623 }
1624 } 1624 }
1625 1625
1626 void wake_up_if_idle(int cpu) 1626 void wake_up_if_idle(int cpu)
1627 { 1627 {
1628 struct rq *rq = cpu_rq(cpu); 1628 struct rq *rq = cpu_rq(cpu);
1629 unsigned long flags; 1629 unsigned long flags;
1630 1630
1631 rcu_read_lock(); 1631 rcu_read_lock();
1632 1632
1633 if (!is_idle_task(rcu_dereference(rq->curr))) 1633 if (!is_idle_task(rcu_dereference(rq->curr)))
1634 goto out; 1634 goto out;
1635 1635
1636 if (set_nr_if_polling(rq->idle)) { 1636 if (set_nr_if_polling(rq->idle)) {
1637 trace_sched_wake_idle_without_ipi(cpu); 1637 trace_sched_wake_idle_without_ipi(cpu);
1638 } else { 1638 } else {
1639 raw_spin_lock_irqsave(&rq->lock, flags); 1639 raw_spin_lock_irqsave(&rq->lock, flags);
1640 if (is_idle_task(rq->curr)) 1640 if (is_idle_task(rq->curr))
1641 smp_send_reschedule(cpu); 1641 smp_send_reschedule(cpu);
1642 /* Else cpu is not in idle, do nothing here */ 1642 /* Else cpu is not in idle, do nothing here */
1643 raw_spin_unlock_irqrestore(&rq->lock, flags); 1643 raw_spin_unlock_irqrestore(&rq->lock, flags);
1644 } 1644 }
1645 1645
1646 out: 1646 out:
1647 rcu_read_unlock(); 1647 rcu_read_unlock();
1648 } 1648 }
1649 1649
1650 bool cpus_share_cache(int this_cpu, int that_cpu) 1650 bool cpus_share_cache(int this_cpu, int that_cpu)
1651 { 1651 {
1652 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu); 1652 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1653 } 1653 }
1654 #endif /* CONFIG_SMP */ 1654 #endif /* CONFIG_SMP */
1655 1655
1656 static void ttwu_queue(struct task_struct *p, int cpu) 1656 static void ttwu_queue(struct task_struct *p, int cpu)
1657 { 1657 {
1658 struct rq *rq = cpu_rq(cpu); 1658 struct rq *rq = cpu_rq(cpu);
1659 1659
1660 #if defined(CONFIG_SMP) 1660 #if defined(CONFIG_SMP)
1661 if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) { 1661 if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
1662 sched_clock_cpu(cpu); /* sync clocks x-cpu */ 1662 sched_clock_cpu(cpu); /* sync clocks x-cpu */
1663 ttwu_queue_remote(p, cpu); 1663 ttwu_queue_remote(p, cpu);
1664 return; 1664 return;
1665 } 1665 }
1666 #endif 1666 #endif
1667 1667
1668 raw_spin_lock(&rq->lock); 1668 raw_spin_lock(&rq->lock);
1669 ttwu_do_activate(rq, p, 0); 1669 ttwu_do_activate(rq, p, 0);
1670 raw_spin_unlock(&rq->lock); 1670 raw_spin_unlock(&rq->lock);
1671 } 1671 }
1672 1672
1673 /** 1673 /**
1674 * try_to_wake_up - wake up a thread 1674 * try_to_wake_up - wake up a thread
1675 * @p: the thread to be awakened 1675 * @p: the thread to be awakened
1676 * @state: the mask of task states that can be woken 1676 * @state: the mask of task states that can be woken
1677 * @wake_flags: wake modifier flags (WF_*) 1677 * @wake_flags: wake modifier flags (WF_*)
1678 * 1678 *
1679 * Put it on the run-queue if it's not already there. The "current" 1679 * Put it on the run-queue if it's not already there. The "current"
1680 * thread is always on the run-queue (except when the actual 1680 * thread is always on the run-queue (except when the actual
1681 * re-schedule is in progress), and as such you're allowed to do 1681 * re-schedule is in progress), and as such you're allowed to do
1682 * the simpler "current->state = TASK_RUNNING" to mark yourself 1682 * the simpler "current->state = TASK_RUNNING" to mark yourself
1683 * runnable without the overhead of this. 1683 * runnable without the overhead of this.
1684 * 1684 *
1685 * Return: %true if @p was woken up, %false if it was already running. 1685 * Return: %true if @p was woken up, %false if it was already running.
1686 * or @state didn't match @p's state. 1686 * or @state didn't match @p's state.
1687 */ 1687 */
1688 static int 1688 static int
1689 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) 1689 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1690 { 1690 {
1691 unsigned long flags; 1691 unsigned long flags;
1692 int cpu, success = 0; 1692 int cpu, success = 0;
1693 1693
1694 /* 1694 /*
1695 * If we are going to wake up a thread waiting for CONDITION we 1695 * If we are going to wake up a thread waiting for CONDITION we
1696 * need to ensure that CONDITION=1 done by the caller can not be 1696 * need to ensure that CONDITION=1 done by the caller can not be
1697 * reordered with p->state check below. This pairs with mb() in 1697 * reordered with p->state check below. This pairs with mb() in
1698 * set_current_state() the waiting thread does. 1698 * set_current_state() the waiting thread does.
1699 */ 1699 */
1700 smp_mb__before_spinlock(); 1700 smp_mb__before_spinlock();
1701 raw_spin_lock_irqsave(&p->pi_lock, flags); 1701 raw_spin_lock_irqsave(&p->pi_lock, flags);
1702 if (!(p->state & state)) 1702 if (!(p->state & state))
1703 goto out; 1703 goto out;
1704 1704
1705 success = 1; /* we're going to change ->state */ 1705 success = 1; /* we're going to change ->state */
1706 cpu = task_cpu(p); 1706 cpu = task_cpu(p);
1707 1707
1708 if (p->on_rq && ttwu_remote(p, wake_flags)) 1708 if (p->on_rq && ttwu_remote(p, wake_flags))
1709 goto stat; 1709 goto stat;
1710 1710
1711 #ifdef CONFIG_SMP 1711 #ifdef CONFIG_SMP
1712 /* 1712 /*
1713 * If the owning (remote) cpu is still in the middle of schedule() with 1713 * If the owning (remote) cpu is still in the middle of schedule() with
1714 * this task as prev, wait until its done referencing the task. 1714 * this task as prev, wait until its done referencing the task.
1715 */ 1715 */
1716 while (p->on_cpu) 1716 while (p->on_cpu)
1717 cpu_relax(); 1717 cpu_relax();
1718 /* 1718 /*
1719 * Pairs with the smp_wmb() in finish_lock_switch(). 1719 * Pairs with the smp_wmb() in finish_lock_switch().
1720 */ 1720 */
1721 smp_rmb(); 1721 smp_rmb();
1722 1722
1723 p->sched_contributes_to_load = !!task_contributes_to_load(p); 1723 p->sched_contributes_to_load = !!task_contributes_to_load(p);
1724 p->state = TASK_WAKING; 1724 p->state = TASK_WAKING;
1725 1725
1726 if (p->sched_class->task_waking) 1726 if (p->sched_class->task_waking)
1727 p->sched_class->task_waking(p); 1727 p->sched_class->task_waking(p);
1728 1728
1729 cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags); 1729 cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
1730 if (task_cpu(p) != cpu) { 1730 if (task_cpu(p) != cpu) {
1731 wake_flags |= WF_MIGRATED; 1731 wake_flags |= WF_MIGRATED;
1732 set_task_cpu(p, cpu); 1732 set_task_cpu(p, cpu);
1733 } 1733 }
1734 #endif /* CONFIG_SMP */ 1734 #endif /* CONFIG_SMP */
1735 1735
1736 ttwu_queue(p, cpu); 1736 ttwu_queue(p, cpu);
1737 stat: 1737 stat:
1738 ttwu_stat(p, cpu, wake_flags); 1738 ttwu_stat(p, cpu, wake_flags);
1739 out: 1739 out:
1740 raw_spin_unlock_irqrestore(&p->pi_lock, flags); 1740 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1741 1741
1742 return success; 1742 return success;
1743 } 1743 }
1744 1744
1745 /** 1745 /**
1746 * try_to_wake_up_local - try to wake up a local task with rq lock held 1746 * try_to_wake_up_local - try to wake up a local task with rq lock held
1747 * @p: the thread to be awakened 1747 * @p: the thread to be awakened
1748 * 1748 *
1749 * Put @p on the run-queue if it's not already there. The caller must 1749 * Put @p on the run-queue if it's not already there. The caller must
1750 * ensure that this_rq() is locked, @p is bound to this_rq() and not 1750 * ensure that this_rq() is locked, @p is bound to this_rq() and not
1751 * the current task. 1751 * the current task.
1752 */ 1752 */
1753 static void try_to_wake_up_local(struct task_struct *p) 1753 static void try_to_wake_up_local(struct task_struct *p)
1754 { 1754 {
1755 struct rq *rq = task_rq(p); 1755 struct rq *rq = task_rq(p);
1756 1756
1757 if (WARN_ON_ONCE(rq != this_rq()) || 1757 if (WARN_ON_ONCE(rq != this_rq()) ||
1758 WARN_ON_ONCE(p == current)) 1758 WARN_ON_ONCE(p == current))
1759 return; 1759 return;
1760 1760
1761 lockdep_assert_held(&rq->lock); 1761 lockdep_assert_held(&rq->lock);
1762 1762
1763 if (!raw_spin_trylock(&p->pi_lock)) { 1763 if (!raw_spin_trylock(&p->pi_lock)) {
1764 raw_spin_unlock(&rq->lock); 1764 raw_spin_unlock(&rq->lock);
1765 raw_spin_lock(&p->pi_lock); 1765 raw_spin_lock(&p->pi_lock);
1766 raw_spin_lock(&rq->lock); 1766 raw_spin_lock(&rq->lock);
1767 } 1767 }
1768 1768
1769 if (!(p->state & TASK_NORMAL)) 1769 if (!(p->state & TASK_NORMAL))
1770 goto out; 1770 goto out;
1771 1771
1772 if (!task_on_rq_queued(p)) 1772 if (!task_on_rq_queued(p))
1773 ttwu_activate(rq, p, ENQUEUE_WAKEUP); 1773 ttwu_activate(rq, p, ENQUEUE_WAKEUP);
1774 1774
1775 ttwu_do_wakeup(rq, p, 0); 1775 ttwu_do_wakeup(rq, p, 0);
1776 ttwu_stat(p, smp_processor_id(), 0); 1776 ttwu_stat(p, smp_processor_id(), 0);
1777 out: 1777 out:
1778 raw_spin_unlock(&p->pi_lock); 1778 raw_spin_unlock(&p->pi_lock);
1779 } 1779 }
1780 1780
1781 /** 1781 /**
1782 * wake_up_process - Wake up a specific process 1782 * wake_up_process - Wake up a specific process
1783 * @p: The process to be woken up. 1783 * @p: The process to be woken up.
1784 * 1784 *
1785 * Attempt to wake up the nominated process and move it to the set of runnable 1785 * Attempt to wake up the nominated process and move it to the set of runnable
1786 * processes. 1786 * processes.
1787 * 1787 *
1788 * Return: 1 if the process was woken up, 0 if it was already running. 1788 * Return: 1 if the process was woken up, 0 if it was already running.
1789 * 1789 *
1790 * It may be assumed that this function implies a write memory barrier before 1790 * It may be assumed that this function implies a write memory barrier before
1791 * changing the task state if and only if any tasks are woken up. 1791 * changing the task state if and only if any tasks are woken up.
1792 */ 1792 */
1793 int wake_up_process(struct task_struct *p) 1793 int wake_up_process(struct task_struct *p)
1794 { 1794 {
1795 WARN_ON(task_is_stopped_or_traced(p)); 1795 WARN_ON(task_is_stopped_or_traced(p));
1796 return try_to_wake_up(p, TASK_NORMAL, 0); 1796 return try_to_wake_up(p, TASK_NORMAL, 0);
1797 } 1797 }
1798 EXPORT_SYMBOL(wake_up_process); 1798 EXPORT_SYMBOL(wake_up_process);
1799 1799
1800 int wake_up_state(struct task_struct *p, unsigned int state) 1800 int wake_up_state(struct task_struct *p, unsigned int state)
1801 { 1801 {
1802 return try_to_wake_up(p, state, 0); 1802 return try_to_wake_up(p, state, 0);
1803 } 1803 }
1804 1804
1805 /* 1805 /*
1806 * This function clears the sched_dl_entity static params. 1806 * This function clears the sched_dl_entity static params.
1807 */ 1807 */
1808 void __dl_clear_params(struct task_struct *p) 1808 void __dl_clear_params(struct task_struct *p)
1809 { 1809 {
1810 struct sched_dl_entity *dl_se = &p->dl; 1810 struct sched_dl_entity *dl_se = &p->dl;
1811 1811
1812 dl_se->dl_runtime = 0; 1812 dl_se->dl_runtime = 0;
1813 dl_se->dl_deadline = 0; 1813 dl_se->dl_deadline = 0;
1814 dl_se->dl_period = 0; 1814 dl_se->dl_period = 0;
1815 dl_se->flags = 0; 1815 dl_se->flags = 0;
1816 dl_se->dl_bw = 0; 1816 dl_se->dl_bw = 0;
1817 } 1817 }
1818 1818
1819 /* 1819 /*
1820 * Perform scheduler related setup for a newly forked process p. 1820 * Perform scheduler related setup for a newly forked process p.
1821 * p is forked by current. 1821 * p is forked by current.
1822 * 1822 *
1823 * __sched_fork() is basic setup used by init_idle() too: 1823 * __sched_fork() is basic setup used by init_idle() too:
1824 */ 1824 */
1825 static void __sched_fork(unsigned long clone_flags, struct task_struct *p) 1825 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
1826 { 1826 {
1827 p->on_rq = 0; 1827 p->on_rq = 0;
1828 1828
1829 p->se.on_rq = 0; 1829 p->se.on_rq = 0;
1830 p->se.exec_start = 0; 1830 p->se.exec_start = 0;
1831 p->se.sum_exec_runtime = 0; 1831 p->se.sum_exec_runtime = 0;
1832 p->se.prev_sum_exec_runtime = 0; 1832 p->se.prev_sum_exec_runtime = 0;
1833 p->se.nr_migrations = 0; 1833 p->se.nr_migrations = 0;
1834 p->se.vruntime = 0; 1834 p->se.vruntime = 0;
1835 INIT_LIST_HEAD(&p->se.group_node); 1835 INIT_LIST_HEAD(&p->se.group_node);
1836 1836
1837 #ifdef CONFIG_SCHEDSTATS 1837 #ifdef CONFIG_SCHEDSTATS
1838 memset(&p->se.statistics, 0, sizeof(p->se.statistics)); 1838 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
1839 #endif 1839 #endif
1840 1840
1841 RB_CLEAR_NODE(&p->dl.rb_node); 1841 RB_CLEAR_NODE(&p->dl.rb_node);
1842 hrtimer_init(&p->dl.dl_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); 1842 hrtimer_init(&p->dl.dl_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1843 __dl_clear_params(p); 1843 __dl_clear_params(p);
1844 1844
1845 INIT_LIST_HEAD(&p->rt.run_list); 1845 INIT_LIST_HEAD(&p->rt.run_list);
1846 1846
1847 #ifdef CONFIG_PREEMPT_NOTIFIERS 1847 #ifdef CONFIG_PREEMPT_NOTIFIERS
1848 INIT_HLIST_HEAD(&p->preempt_notifiers); 1848 INIT_HLIST_HEAD(&p->preempt_notifiers);
1849 #endif 1849 #endif
1850 1850
1851 #ifdef CONFIG_NUMA_BALANCING 1851 #ifdef CONFIG_NUMA_BALANCING
1852 if (p->mm && atomic_read(&p->mm->mm_users) == 1) { 1852 if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
1853 p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 1853 p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
1854 p->mm->numa_scan_seq = 0; 1854 p->mm->numa_scan_seq = 0;
1855 } 1855 }
1856 1856
1857 if (clone_flags & CLONE_VM) 1857 if (clone_flags & CLONE_VM)
1858 p->numa_preferred_nid = current->numa_preferred_nid; 1858 p->numa_preferred_nid = current->numa_preferred_nid;
1859 else 1859 else
1860 p->numa_preferred_nid = -1; 1860 p->numa_preferred_nid = -1;
1861 1861
1862 p->node_stamp = 0ULL; 1862 p->node_stamp = 0ULL;
1863 p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0; 1863 p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
1864 p->numa_scan_period = sysctl_numa_balancing_scan_delay; 1864 p->numa_scan_period = sysctl_numa_balancing_scan_delay;
1865 p->numa_work.next = &p->numa_work; 1865 p->numa_work.next = &p->numa_work;
1866 p->numa_faults = NULL; 1866 p->numa_faults = NULL;
1867 p->last_task_numa_placement = 0; 1867 p->last_task_numa_placement = 0;
1868 p->last_sum_exec_runtime = 0; 1868 p->last_sum_exec_runtime = 0;
1869 1869
1870 p->numa_group = NULL; 1870 p->numa_group = NULL;
1871 #endif /* CONFIG_NUMA_BALANCING */ 1871 #endif /* CONFIG_NUMA_BALANCING */
1872 } 1872 }
1873 1873
1874 #ifdef CONFIG_NUMA_BALANCING 1874 #ifdef CONFIG_NUMA_BALANCING
1875 #ifdef CONFIG_SCHED_DEBUG 1875 #ifdef CONFIG_SCHED_DEBUG
1876 void set_numabalancing_state(bool enabled) 1876 void set_numabalancing_state(bool enabled)
1877 { 1877 {
1878 if (enabled) 1878 if (enabled)
1879 sched_feat_set("NUMA"); 1879 sched_feat_set("NUMA");
1880 else 1880 else
1881 sched_feat_set("NO_NUMA"); 1881 sched_feat_set("NO_NUMA");
1882 } 1882 }
1883 #else 1883 #else
1884 __read_mostly bool numabalancing_enabled; 1884 __read_mostly bool numabalancing_enabled;
1885 1885
1886 void set_numabalancing_state(bool enabled) 1886 void set_numabalancing_state(bool enabled)
1887 { 1887 {
1888 numabalancing_enabled = enabled; 1888 numabalancing_enabled = enabled;
1889 } 1889 }
1890 #endif /* CONFIG_SCHED_DEBUG */ 1890 #endif /* CONFIG_SCHED_DEBUG */
1891 1891
1892 #ifdef CONFIG_PROC_SYSCTL 1892 #ifdef CONFIG_PROC_SYSCTL
1893 int sysctl_numa_balancing(struct ctl_table *table, int write, 1893 int sysctl_numa_balancing(struct ctl_table *table, int write,
1894 void __user *buffer, size_t *lenp, loff_t *ppos) 1894 void __user *buffer, size_t *lenp, loff_t *ppos)
1895 { 1895 {
1896 struct ctl_table t; 1896 struct ctl_table t;
1897 int err; 1897 int err;
1898 int state = numabalancing_enabled; 1898 int state = numabalancing_enabled;
1899 1899
1900 if (write && !capable(CAP_SYS_ADMIN)) 1900 if (write && !capable(CAP_SYS_ADMIN))
1901 return -EPERM; 1901 return -EPERM;
1902 1902
1903 t = *table; 1903 t = *table;
1904 t.data = &state; 1904 t.data = &state;
1905 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos); 1905 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
1906 if (err < 0) 1906 if (err < 0)
1907 return err; 1907 return err;
1908 if (write) 1908 if (write)
1909 set_numabalancing_state(state); 1909 set_numabalancing_state(state);
1910 return err; 1910 return err;
1911 } 1911 }
1912 #endif 1912 #endif
1913 #endif 1913 #endif
1914 1914
1915 /* 1915 /*
1916 * fork()/clone()-time setup: 1916 * fork()/clone()-time setup:
1917 */ 1917 */
1918 int sched_fork(unsigned long clone_flags, struct task_struct *p) 1918 int sched_fork(unsigned long clone_flags, struct task_struct *p)
1919 { 1919 {
1920 unsigned long flags; 1920 unsigned long flags;
1921 int cpu = get_cpu(); 1921 int cpu = get_cpu();
1922 1922
1923 __sched_fork(clone_flags, p); 1923 __sched_fork(clone_flags, p);
1924 /* 1924 /*
1925 * We mark the process as running here. This guarantees that 1925 * We mark the process as running here. This guarantees that
1926 * nobody will actually run it, and a signal or other external 1926 * nobody will actually run it, and a signal or other external
1927 * event cannot wake it up and insert it on the runqueue either. 1927 * event cannot wake it up and insert it on the runqueue either.
1928 */ 1928 */
1929 p->state = TASK_RUNNING; 1929 p->state = TASK_RUNNING;
1930 1930
1931 /* 1931 /*
1932 * Make sure we do not leak PI boosting priority to the child. 1932 * Make sure we do not leak PI boosting priority to the child.
1933 */ 1933 */
1934 p->prio = current->normal_prio; 1934 p->prio = current->normal_prio;
1935 1935
1936 /* 1936 /*
1937 * Revert to default priority/policy on fork if requested. 1937 * Revert to default priority/policy on fork if requested.
1938 */ 1938 */
1939 if (unlikely(p->sched_reset_on_fork)) { 1939 if (unlikely(p->sched_reset_on_fork)) {
1940 if (task_has_dl_policy(p) || task_has_rt_policy(p)) { 1940 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
1941 p->policy = SCHED_NORMAL; 1941 p->policy = SCHED_NORMAL;
1942 p->static_prio = NICE_TO_PRIO(0); 1942 p->static_prio = NICE_TO_PRIO(0);
1943 p->rt_priority = 0; 1943 p->rt_priority = 0;
1944 } else if (PRIO_TO_NICE(p->static_prio) < 0) 1944 } else if (PRIO_TO_NICE(p->static_prio) < 0)
1945 p->static_prio = NICE_TO_PRIO(0); 1945 p->static_prio = NICE_TO_PRIO(0);
1946 1946
1947 p->prio = p->normal_prio = __normal_prio(p); 1947 p->prio = p->normal_prio = __normal_prio(p);
1948 set_load_weight(p); 1948 set_load_weight(p);
1949 1949
1950 /* 1950 /*
1951 * We don't need the reset flag anymore after the fork. It has 1951 * We don't need the reset flag anymore after the fork. It has
1952 * fulfilled its duty: 1952 * fulfilled its duty:
1953 */ 1953 */
1954 p->sched_reset_on_fork = 0; 1954 p->sched_reset_on_fork = 0;
1955 } 1955 }
1956 1956
1957 if (dl_prio(p->prio)) { 1957 if (dl_prio(p->prio)) {
1958 put_cpu(); 1958 put_cpu();
1959 return -EAGAIN; 1959 return -EAGAIN;
1960 } else if (rt_prio(p->prio)) { 1960 } else if (rt_prio(p->prio)) {
1961 p->sched_class = &rt_sched_class; 1961 p->sched_class = &rt_sched_class;
1962 } else { 1962 } else {
1963 p->sched_class = &fair_sched_class; 1963 p->sched_class = &fair_sched_class;
1964 } 1964 }
1965 1965
1966 if (p->sched_class->task_fork) 1966 if (p->sched_class->task_fork)
1967 p->sched_class->task_fork(p); 1967 p->sched_class->task_fork(p);
1968 1968
1969 /* 1969 /*
1970 * The child is not yet in the pid-hash so no cgroup attach races, 1970 * The child is not yet in the pid-hash so no cgroup attach races,
1971 * and the cgroup is pinned to this child due to cgroup_fork() 1971 * and the cgroup is pinned to this child due to cgroup_fork()
1972 * is ran before sched_fork(). 1972 * is ran before sched_fork().
1973 * 1973 *
1974 * Silence PROVE_RCU. 1974 * Silence PROVE_RCU.
1975 */ 1975 */
1976 raw_spin_lock_irqsave(&p->pi_lock, flags); 1976 raw_spin_lock_irqsave(&p->pi_lock, flags);
1977 set_task_cpu(p, cpu); 1977 set_task_cpu(p, cpu);
1978 raw_spin_unlock_irqrestore(&p->pi_lock, flags); 1978 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
1979 1979
1980 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT) 1980 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
1981 if (likely(sched_info_on())) 1981 if (likely(sched_info_on()))
1982 memset(&p->sched_info, 0, sizeof(p->sched_info)); 1982 memset(&p->sched_info, 0, sizeof(p->sched_info));
1983 #endif 1983 #endif
1984 #if defined(CONFIG_SMP) 1984 #if defined(CONFIG_SMP)
1985 p->on_cpu = 0; 1985 p->on_cpu = 0;
1986 #endif 1986 #endif
1987 init_task_preempt_count(p); 1987 init_task_preempt_count(p);
1988 #ifdef CONFIG_SMP 1988 #ifdef CONFIG_SMP
1989 plist_node_init(&p->pushable_tasks, MAX_PRIO); 1989 plist_node_init(&p->pushable_tasks, MAX_PRIO);
1990 RB_CLEAR_NODE(&p->pushable_dl_tasks); 1990 RB_CLEAR_NODE(&p->pushable_dl_tasks);
1991 #endif 1991 #endif
1992 1992
1993 put_cpu(); 1993 put_cpu();
1994 return 0; 1994 return 0;
1995 } 1995 }
1996 1996
1997 unsigned long to_ratio(u64 period, u64 runtime) 1997 unsigned long to_ratio(u64 period, u64 runtime)
1998 { 1998 {
1999 if (runtime == RUNTIME_INF) 1999 if (runtime == RUNTIME_INF)
2000 return 1ULL << 20; 2000 return 1ULL << 20;
2001 2001
2002 /* 2002 /*
2003 * Doing this here saves a lot of checks in all 2003 * Doing this here saves a lot of checks in all
2004 * the calling paths, and returning zero seems 2004 * the calling paths, and returning zero seems
2005 * safe for them anyway. 2005 * safe for them anyway.
2006 */ 2006 */
2007 if (period == 0) 2007 if (period == 0)
2008 return 0; 2008 return 0;
2009 2009
2010 return div64_u64(runtime << 20, period); 2010 return div64_u64(runtime << 20, period);
2011 } 2011 }
2012 2012
2013 #ifdef CONFIG_SMP 2013 #ifdef CONFIG_SMP
2014 inline struct dl_bw *dl_bw_of(int i) 2014 inline struct dl_bw *dl_bw_of(int i)
2015 { 2015 {
2016 rcu_lockdep_assert(rcu_read_lock_sched_held(), 2016 rcu_lockdep_assert(rcu_read_lock_sched_held(),
2017 "sched RCU must be held"); 2017 "sched RCU must be held");
2018 return &cpu_rq(i)->rd->dl_bw; 2018 return &cpu_rq(i)->rd->dl_bw;
2019 } 2019 }
2020 2020
2021 static inline int dl_bw_cpus(int i) 2021 static inline int dl_bw_cpus(int i)
2022 { 2022 {
2023 struct root_domain *rd = cpu_rq(i)->rd; 2023 struct root_domain *rd = cpu_rq(i)->rd;
2024 int cpus = 0; 2024 int cpus = 0;
2025 2025
2026 rcu_lockdep_assert(rcu_read_lock_sched_held(), 2026 rcu_lockdep_assert(rcu_read_lock_sched_held(),
2027 "sched RCU must be held"); 2027 "sched RCU must be held");
2028 for_each_cpu_and(i, rd->span, cpu_active_mask) 2028 for_each_cpu_and(i, rd->span, cpu_active_mask)
2029 cpus++; 2029 cpus++;
2030 2030
2031 return cpus; 2031 return cpus;
2032 } 2032 }
2033 #else 2033 #else
2034 inline struct dl_bw *dl_bw_of(int i) 2034 inline struct dl_bw *dl_bw_of(int i)
2035 { 2035 {
2036 return &cpu_rq(i)->dl.dl_bw; 2036 return &cpu_rq(i)->dl.dl_bw;
2037 } 2037 }
2038 2038
2039 static inline int dl_bw_cpus(int i) 2039 static inline int dl_bw_cpus(int i)
2040 { 2040 {
2041 return 1; 2041 return 1;
2042 } 2042 }
2043 #endif 2043 #endif
2044 2044
2045 /* 2045 /*
2046 * We must be sure that accepting a new task (or allowing changing the 2046 * We must be sure that accepting a new task (or allowing changing the
2047 * parameters of an existing one) is consistent with the bandwidth 2047 * parameters of an existing one) is consistent with the bandwidth
2048 * constraints. If yes, this function also accordingly updates the currently 2048 * constraints. If yes, this function also accordingly updates the currently
2049 * allocated bandwidth to reflect the new situation. 2049 * allocated bandwidth to reflect the new situation.
2050 * 2050 *
2051 * This function is called while holding p's rq->lock. 2051 * This function is called while holding p's rq->lock.
2052 */ 2052 */
2053 static int dl_overflow(struct task_struct *p, int policy, 2053 static int dl_overflow(struct task_struct *p, int policy,
2054 const struct sched_attr *attr) 2054 const struct sched_attr *attr)
2055 { 2055 {
2056 2056
2057 struct dl_bw *dl_b = dl_bw_of(task_cpu(p)); 2057 struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
2058 u64 period = attr->sched_period ?: attr->sched_deadline; 2058 u64 period = attr->sched_period ?: attr->sched_deadline;
2059 u64 runtime = attr->sched_runtime; 2059 u64 runtime = attr->sched_runtime;
2060 u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0; 2060 u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
2061 int cpus, err = -1; 2061 int cpus, err = -1;
2062 2062
2063 if (new_bw == p->dl.dl_bw) 2063 if (new_bw == p->dl.dl_bw)
2064 return 0; 2064 return 0;
2065 2065
2066 /* 2066 /*
2067 * Either if a task, enters, leave, or stays -deadline but changes 2067 * Either if a task, enters, leave, or stays -deadline but changes
2068 * its parameters, we may need to update accordingly the total 2068 * its parameters, we may need to update accordingly the total
2069 * allocated bandwidth of the container. 2069 * allocated bandwidth of the container.
2070 */ 2070 */
2071 raw_spin_lock(&dl_b->lock); 2071 raw_spin_lock(&dl_b->lock);
2072 cpus = dl_bw_cpus(task_cpu(p)); 2072 cpus = dl_bw_cpus(task_cpu(p));
2073 if (dl_policy(policy) && !task_has_dl_policy(p) && 2073 if (dl_policy(policy) && !task_has_dl_policy(p) &&
2074 !__dl_overflow(dl_b, cpus, 0, new_bw)) { 2074 !__dl_overflow(dl_b, cpus, 0, new_bw)) {
2075 __dl_add(dl_b, new_bw); 2075 __dl_add(dl_b, new_bw);
2076 err = 0; 2076 err = 0;
2077 } else if (dl_policy(policy) && task_has_dl_policy(p) && 2077 } else if (dl_policy(policy) && task_has_dl_policy(p) &&
2078 !__dl_overflow(dl_b, cpus, p->dl.dl_bw, new_bw)) { 2078 !__dl_overflow(dl_b, cpus, p->dl.dl_bw, new_bw)) {
2079 __dl_clear(dl_b, p->dl.dl_bw); 2079 __dl_clear(dl_b, p->dl.dl_bw);
2080 __dl_add(dl_b, new_bw); 2080 __dl_add(dl_b, new_bw);
2081 err = 0; 2081 err = 0;
2082 } else if (!dl_policy(policy) && task_has_dl_policy(p)) { 2082 } else if (!dl_policy(policy) && task_has_dl_policy(p)) {
2083 __dl_clear(dl_b, p->dl.dl_bw); 2083 __dl_clear(dl_b, p->dl.dl_bw);
2084 err = 0; 2084 err = 0;
2085 } 2085 }
2086 raw_spin_unlock(&dl_b->lock); 2086 raw_spin_unlock(&dl_b->lock);
2087 2087
2088 return err; 2088 return err;
2089 } 2089 }
2090 2090
2091 extern void init_dl_bw(struct dl_bw *dl_b); 2091 extern void init_dl_bw(struct dl_bw *dl_b);
2092 2092
2093 /* 2093 /*
2094 * wake_up_new_task - wake up a newly created task for the first time. 2094 * wake_up_new_task - wake up a newly created task for the first time.
2095 * 2095 *
2096 * This function will do some initial scheduler statistics housekeeping 2096 * This function will do some initial scheduler statistics housekeeping
2097 * that must be done for every newly created context, then puts the task 2097 * that must be done for every newly created context, then puts the task
2098 * on the runqueue and wakes it. 2098 * on the runqueue and wakes it.
2099 */ 2099 */
2100 void wake_up_new_task(struct task_struct *p) 2100 void wake_up_new_task(struct task_struct *p)
2101 { 2101 {
2102 unsigned long flags; 2102 unsigned long flags;
2103 struct rq *rq; 2103 struct rq *rq;
2104 2104
2105 raw_spin_lock_irqsave(&p->pi_lock, flags); 2105 raw_spin_lock_irqsave(&p->pi_lock, flags);
2106 #ifdef CONFIG_SMP 2106 #ifdef CONFIG_SMP
2107 /* 2107 /*
2108 * Fork balancing, do it here and not earlier because: 2108 * Fork balancing, do it here and not earlier because:
2109 * - cpus_allowed can change in the fork path 2109 * - cpus_allowed can change in the fork path
2110 * - any previously selected cpu might disappear through hotplug 2110 * - any previously selected cpu might disappear through hotplug
2111 */ 2111 */
2112 set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0)); 2112 set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
2113 #endif 2113 #endif
2114 2114
2115 /* Initialize new task's runnable average */ 2115 /* Initialize new task's runnable average */
2116 init_task_runnable_average(p); 2116 init_task_runnable_average(p);
2117 rq = __task_rq_lock(p); 2117 rq = __task_rq_lock(p);
2118 activate_task(rq, p, 0); 2118 activate_task(rq, p, 0);
2119 p->on_rq = TASK_ON_RQ_QUEUED; 2119 p->on_rq = TASK_ON_RQ_QUEUED;
2120 trace_sched_wakeup_new(p, true); 2120 trace_sched_wakeup_new(p, true);
2121 check_preempt_curr(rq, p, WF_FORK); 2121 check_preempt_curr(rq, p, WF_FORK);
2122 #ifdef CONFIG_SMP 2122 #ifdef CONFIG_SMP
2123 if (p->sched_class->task_woken) 2123 if (p->sched_class->task_woken)
2124 p->sched_class->task_woken(rq, p); 2124 p->sched_class->task_woken(rq, p);
2125 #endif 2125 #endif
2126 task_rq_unlock(rq, p, &flags); 2126 task_rq_unlock(rq, p, &flags);
2127 } 2127 }
2128 2128
2129 #ifdef CONFIG_PREEMPT_NOTIFIERS 2129 #ifdef CONFIG_PREEMPT_NOTIFIERS
2130 2130
2131 /** 2131 /**
2132 * preempt_notifier_register - tell me when current is being preempted & rescheduled 2132 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2133 * @notifier: notifier struct to register 2133 * @notifier: notifier struct to register
2134 */ 2134 */
2135 void preempt_notifier_register(struct preempt_notifier *notifier) 2135 void preempt_notifier_register(struct preempt_notifier *notifier)
2136 { 2136 {
2137 hlist_add_head(&notifier->link, &current->preempt_notifiers); 2137 hlist_add_head(&notifier->link, &current->preempt_notifiers);
2138 } 2138 }
2139 EXPORT_SYMBOL_GPL(preempt_notifier_register); 2139 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2140 2140
2141 /** 2141 /**
2142 * preempt_notifier_unregister - no longer interested in preemption notifications 2142 * preempt_notifier_unregister - no longer interested in preemption notifications
2143 * @notifier: notifier struct to unregister 2143 * @notifier: notifier struct to unregister
2144 * 2144 *
2145 * This is safe to call from within a preemption notifier. 2145 * This is safe to call from within a preemption notifier.
2146 */ 2146 */
2147 void preempt_notifier_unregister(struct preempt_notifier *notifier) 2147 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2148 { 2148 {
2149 hlist_del(&notifier->link); 2149 hlist_del(&notifier->link);
2150 } 2150 }
2151 EXPORT_SYMBOL_GPL(preempt_notifier_unregister); 2151 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2152 2152
2153 static void fire_sched_in_preempt_notifiers(struct task_struct *curr) 2153 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2154 { 2154 {
2155 struct preempt_notifier *notifier; 2155 struct preempt_notifier *notifier;
2156 2156
2157 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link) 2157 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2158 notifier->ops->sched_in(notifier, raw_smp_processor_id()); 2158 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2159 } 2159 }
2160 2160
2161 static void 2161 static void
2162 fire_sched_out_preempt_notifiers(struct task_struct *curr, 2162 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2163 struct task_struct *next) 2163 struct task_struct *next)
2164 { 2164 {
2165 struct preempt_notifier *notifier; 2165 struct preempt_notifier *notifier;
2166 2166
2167 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link) 2167 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2168 notifier->ops->sched_out(notifier, next); 2168 notifier->ops->sched_out(notifier, next);
2169 } 2169 }
2170 2170
2171 #else /* !CONFIG_PREEMPT_NOTIFIERS */ 2171 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2172 2172
2173 static void fire_sched_in_preempt_notifiers(struct task_struct *curr) 2173 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2174 { 2174 {
2175 } 2175 }
2176 2176
2177 static void 2177 static void
2178 fire_sched_out_preempt_notifiers(struct task_struct *curr, 2178 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2179 struct task_struct *next) 2179 struct task_struct *next)
2180 { 2180 {
2181 } 2181 }
2182 2182
2183 #endif /* CONFIG_PREEMPT_NOTIFIERS */ 2183 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2184 2184
2185 /** 2185 /**
2186 * prepare_task_switch - prepare to switch tasks 2186 * prepare_task_switch - prepare to switch tasks
2187 * @rq: the runqueue preparing to switch 2187 * @rq: the runqueue preparing to switch
2188 * @prev: the current task that is being switched out 2188 * @prev: the current task that is being switched out
2189 * @next: the task we are going to switch to. 2189 * @next: the task we are going to switch to.
2190 * 2190 *
2191 * This is called with the rq lock held and interrupts off. It must 2191 * This is called with the rq lock held and interrupts off. It must
2192 * be paired with a subsequent finish_task_switch after the context 2192 * be paired with a subsequent finish_task_switch after the context
2193 * switch. 2193 * switch.
2194 * 2194 *
2195 * prepare_task_switch sets up locking and calls architecture specific 2195 * prepare_task_switch sets up locking and calls architecture specific
2196 * hooks. 2196 * hooks.
2197 */ 2197 */
2198 static inline void 2198 static inline void
2199 prepare_task_switch(struct rq *rq, struct task_struct *prev, 2199 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2200 struct task_struct *next) 2200 struct task_struct *next)
2201 { 2201 {
2202 trace_sched_switch(prev, next); 2202 trace_sched_switch(prev, next);
2203 sched_info_switch(rq, prev, next); 2203 sched_info_switch(rq, prev, next);
2204 perf_event_task_sched_out(prev, next); 2204 perf_event_task_sched_out(prev, next);
2205 fire_sched_out_preempt_notifiers(prev, next); 2205 fire_sched_out_preempt_notifiers(prev, next);
2206 prepare_lock_switch(rq, next); 2206 prepare_lock_switch(rq, next);
2207 prepare_arch_switch(next); 2207 prepare_arch_switch(next);
2208 } 2208 }
2209 2209
2210 /** 2210 /**
2211 * finish_task_switch - clean up after a task-switch 2211 * finish_task_switch - clean up after a task-switch
2212 * @prev: the thread we just switched away from. 2212 * @prev: the thread we just switched away from.
2213 * 2213 *
2214 * finish_task_switch must be called after the context switch, paired 2214 * finish_task_switch must be called after the context switch, paired
2215 * with a prepare_task_switch call before the context switch. 2215 * with a prepare_task_switch call before the context switch.
2216 * finish_task_switch will reconcile locking set up by prepare_task_switch, 2216 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2217 * and do any other architecture-specific cleanup actions. 2217 * and do any other architecture-specific cleanup actions.
2218 * 2218 *
2219 * Note that we may have delayed dropping an mm in context_switch(). If 2219 * Note that we may have delayed dropping an mm in context_switch(). If
2220 * so, we finish that here outside of the runqueue lock. (Doing it 2220 * so, we finish that here outside of the runqueue lock. (Doing it
2221 * with the lock held can cause deadlocks; see schedule() for 2221 * with the lock held can cause deadlocks; see schedule() for
2222 * details.) 2222 * details.)
2223 * 2223 *
2224 * The context switch have flipped the stack from under us and restored the 2224 * The context switch have flipped the stack from under us and restored the
2225 * local variables which were saved when this task called schedule() in the 2225 * local variables which were saved when this task called schedule() in the
2226 * past. prev == current is still correct but we need to recalculate this_rq 2226 * past. prev == current is still correct but we need to recalculate this_rq
2227 * because prev may have moved to another CPU. 2227 * because prev may have moved to another CPU.
2228 */ 2228 */
2229 static struct rq *finish_task_switch(struct task_struct *prev) 2229 static struct rq *finish_task_switch(struct task_struct *prev)
2230 __releases(rq->lock) 2230 __releases(rq->lock)
2231 { 2231 {
2232 struct rq *rq = this_rq(); 2232 struct rq *rq = this_rq();
2233 struct mm_struct *mm = rq->prev_mm; 2233 struct mm_struct *mm = rq->prev_mm;
2234 long prev_state; 2234 long prev_state;
2235 2235
2236 rq->prev_mm = NULL; 2236 rq->prev_mm = NULL;
2237 2237
2238 /* 2238 /*
2239 * A task struct has one reference for the use as "current". 2239 * A task struct has one reference for the use as "current".
2240 * If a task dies, then it sets TASK_DEAD in tsk->state and calls 2240 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2241 * schedule one last time. The schedule call will never return, and 2241 * schedule one last time. The schedule call will never return, and
2242 * the scheduled task must drop that reference. 2242 * the scheduled task must drop that reference.
2243 * The test for TASK_DEAD must occur while the runqueue locks are 2243 * The test for TASK_DEAD must occur while the runqueue locks are
2244 * still held, otherwise prev could be scheduled on another cpu, die 2244 * still held, otherwise prev could be scheduled on another cpu, die
2245 * there before we look at prev->state, and then the reference would 2245 * there before we look at prev->state, and then the reference would
2246 * be dropped twice. 2246 * be dropped twice.
2247 * Manfred Spraul <manfred@colorfullife.com> 2247 * Manfred Spraul <manfred@colorfullife.com>
2248 */ 2248 */
2249 prev_state = prev->state; 2249 prev_state = prev->state;
2250 vtime_task_switch(prev); 2250 vtime_task_switch(prev);
2251 finish_arch_switch(prev); 2251 finish_arch_switch(prev);
2252 perf_event_task_sched_in(prev, current); 2252 perf_event_task_sched_in(prev, current);
2253 finish_lock_switch(rq, prev); 2253 finish_lock_switch(rq, prev);
2254 finish_arch_post_lock_switch(); 2254 finish_arch_post_lock_switch();
2255 2255
2256 fire_sched_in_preempt_notifiers(current); 2256 fire_sched_in_preempt_notifiers(current);
2257 if (mm) 2257 if (mm)
2258 mmdrop(mm); 2258 mmdrop(mm);
2259 if (unlikely(prev_state == TASK_DEAD)) { 2259 if (unlikely(prev_state == TASK_DEAD)) {
2260 if (prev->sched_class->task_dead) 2260 if (prev->sched_class->task_dead)
2261 prev->sched_class->task_dead(prev); 2261 prev->sched_class->task_dead(prev);
2262 2262
2263 /* 2263 /*
2264 * Remove function-return probe instances associated with this 2264 * Remove function-return probe instances associated with this
2265 * task and put them back on the free list. 2265 * task and put them back on the free list.
2266 */ 2266 */
2267 kprobe_flush_task(prev); 2267 kprobe_flush_task(prev);
2268 put_task_struct(prev); 2268 put_task_struct(prev);
2269 } 2269 }
2270 2270
2271 tick_nohz_task_switch(current); 2271 tick_nohz_task_switch(current);
2272 return rq; 2272 return rq;
2273 } 2273 }
2274 2274
2275 #ifdef CONFIG_SMP 2275 #ifdef CONFIG_SMP
2276 2276
2277 /* rq->lock is NOT held, but preemption is disabled */ 2277 /* rq->lock is NOT held, but preemption is disabled */
2278 static inline void post_schedule(struct rq *rq) 2278 static inline void post_schedule(struct rq *rq)
2279 { 2279 {
2280 if (rq->post_schedule) { 2280 if (rq->post_schedule) {
2281 unsigned long flags; 2281 unsigned long flags;
2282 2282
2283 raw_spin_lock_irqsave(&rq->lock, flags); 2283 raw_spin_lock_irqsave(&rq->lock, flags);
2284 if (rq->curr->sched_class->post_schedule) 2284 if (rq->curr->sched_class->post_schedule)
2285 rq->curr->sched_class->post_schedule(rq); 2285 rq->curr->sched_class->post_schedule(rq);
2286 raw_spin_unlock_irqrestore(&rq->lock, flags); 2286 raw_spin_unlock_irqrestore(&rq->lock, flags);
2287 2287
2288 rq->post_schedule = 0; 2288 rq->post_schedule = 0;
2289 } 2289 }
2290 } 2290 }
2291 2291
2292 #else 2292 #else
2293 2293
2294 static inline void post_schedule(struct rq *rq) 2294 static inline void post_schedule(struct rq *rq)
2295 { 2295 {
2296 } 2296 }
2297 2297
2298 #endif 2298 #endif
2299 2299
2300 /** 2300 /**
2301 * schedule_tail - first thing a freshly forked thread must call. 2301 * schedule_tail - first thing a freshly forked thread must call.
2302 * @prev: the thread we just switched away from. 2302 * @prev: the thread we just switched away from.
2303 */ 2303 */
2304 asmlinkage __visible void schedule_tail(struct task_struct *prev) 2304 asmlinkage __visible void schedule_tail(struct task_struct *prev)
2305 __releases(rq->lock) 2305 __releases(rq->lock)
2306 { 2306 {
2307 struct rq *rq; 2307 struct rq *rq;
2308 2308
2309 /* finish_task_switch() drops rq->lock and enables preemtion */ 2309 /* finish_task_switch() drops rq->lock and enables preemtion */
2310 preempt_disable(); 2310 preempt_disable();
2311 rq = finish_task_switch(prev); 2311 rq = finish_task_switch(prev);
2312 post_schedule(rq); 2312 post_schedule(rq);
2313 preempt_enable(); 2313 preempt_enable();
2314 2314
2315 if (current->set_child_tid) 2315 if (current->set_child_tid)
2316 put_user(task_pid_vnr(current), current->set_child_tid); 2316 put_user(task_pid_vnr(current), current->set_child_tid);
2317 } 2317 }
2318 2318
2319 /* 2319 /*
2320 * context_switch - switch to the new MM and the new thread's register state. 2320 * context_switch - switch to the new MM and the new thread's register state.
2321 */ 2321 */
2322 static inline struct rq * 2322 static inline struct rq *
2323 context_switch(struct rq *rq, struct task_struct *prev, 2323 context_switch(struct rq *rq, struct task_struct *prev,
2324 struct task_struct *next) 2324 struct task_struct *next)
2325 { 2325 {
2326 struct mm_struct *mm, *oldmm; 2326 struct mm_struct *mm, *oldmm;
2327 2327
2328 prepare_task_switch(rq, prev, next); 2328 prepare_task_switch(rq, prev, next);
2329 2329
2330 mm = next->mm; 2330 mm = next->mm;
2331 oldmm = prev->active_mm; 2331 oldmm = prev->active_mm;
2332 /* 2332 /*
2333 * For paravirt, this is coupled with an exit in switch_to to 2333 * For paravirt, this is coupled with an exit in switch_to to
2334 * combine the page table reload and the switch backend into 2334 * combine the page table reload and the switch backend into
2335 * one hypercall. 2335 * one hypercall.
2336 */ 2336 */
2337 arch_start_context_switch(prev); 2337 arch_start_context_switch(prev);
2338 2338
2339 if (!mm) { 2339 if (!mm) {
2340 next->active_mm = oldmm; 2340 next->active_mm = oldmm;
2341 atomic_inc(&oldmm->mm_count); 2341 atomic_inc(&oldmm->mm_count);
2342 enter_lazy_tlb(oldmm, next); 2342 enter_lazy_tlb(oldmm, next);
2343 } else 2343 } else
2344 switch_mm(oldmm, mm, next); 2344 switch_mm(oldmm, mm, next);
2345 2345
2346 if (!prev->mm) { 2346 if (!prev->mm) {
2347 prev->active_mm = NULL; 2347 prev->active_mm = NULL;
2348 rq->prev_mm = oldmm; 2348 rq->prev_mm = oldmm;
2349 } 2349 }
2350 /* 2350 /*
2351 * Since the runqueue lock will be released by the next 2351 * Since the runqueue lock will be released by the next
2352 * task (which is an invalid locking op but in the case 2352 * task (which is an invalid locking op but in the case
2353 * of the scheduler it's an obvious special-case), so we 2353 * of the scheduler it's an obvious special-case), so we
2354 * do an early lockdep release here: 2354 * do an early lockdep release here:
2355 */ 2355 */
2356 spin_release(&rq->lock.dep_map, 1, _THIS_IP_); 2356 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2357 2357
2358 context_tracking_task_switch(prev, next); 2358 context_tracking_task_switch(prev, next);
2359 /* Here we just switch the register state and the stack. */ 2359 /* Here we just switch the register state and the stack. */
2360 switch_to(prev, next, prev); 2360 switch_to(prev, next, prev);
2361 barrier(); 2361 barrier();
2362 2362
2363 return finish_task_switch(prev); 2363 return finish_task_switch(prev);
2364 } 2364 }
2365 2365
2366 /* 2366 /*
2367 * nr_running and nr_context_switches: 2367 * nr_running and nr_context_switches:
2368 * 2368 *
2369 * externally visible scheduler statistics: current number of runnable 2369 * externally visible scheduler statistics: current number of runnable
2370 * threads, total number of context switches performed since bootup. 2370 * threads, total number of context switches performed since bootup.
2371 */ 2371 */
2372 unsigned long nr_running(void) 2372 unsigned long nr_running(void)
2373 { 2373 {
2374 unsigned long i, sum = 0; 2374 unsigned long i, sum = 0;
2375 2375
2376 for_each_online_cpu(i) 2376 for_each_online_cpu(i)
2377 sum += cpu_rq(i)->nr_running; 2377 sum += cpu_rq(i)->nr_running;
2378 2378
2379 return sum; 2379 return sum;
2380 } 2380 }
2381 2381
2382 /* 2382 /*
2383 * Check if only the current task is running on the cpu. 2383 * Check if only the current task is running on the cpu.
2384 */ 2384 */
2385 bool single_task_running(void) 2385 bool single_task_running(void)
2386 { 2386 {
2387 if (cpu_rq(smp_processor_id())->nr_running == 1) 2387 if (cpu_rq(smp_processor_id())->nr_running == 1)
2388 return true; 2388 return true;
2389 else 2389 else
2390 return false; 2390 return false;
2391 } 2391 }
2392 EXPORT_SYMBOL(single_task_running); 2392 EXPORT_SYMBOL(single_task_running);
2393 2393
2394 unsigned long long nr_context_switches(void) 2394 unsigned long long nr_context_switches(void)
2395 { 2395 {
2396 int i; 2396 int i;
2397 unsigned long long sum = 0; 2397 unsigned long long sum = 0;
2398 2398
2399 for_each_possible_cpu(i) 2399 for_each_possible_cpu(i)
2400 sum += cpu_rq(i)->nr_switches; 2400 sum += cpu_rq(i)->nr_switches;
2401 2401
2402 return sum; 2402 return sum;
2403 } 2403 }
2404 2404
2405 unsigned long nr_iowait(void) 2405 unsigned long nr_iowait(void)
2406 { 2406 {
2407 unsigned long i, sum = 0; 2407 unsigned long i, sum = 0;
2408 2408
2409 for_each_possible_cpu(i) 2409 for_each_possible_cpu(i)
2410 sum += atomic_read(&cpu_rq(i)->nr_iowait); 2410 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2411 2411
2412 return sum; 2412 return sum;
2413 } 2413 }
2414 2414
2415 unsigned long nr_iowait_cpu(int cpu) 2415 unsigned long nr_iowait_cpu(int cpu)
2416 { 2416 {
2417 struct rq *this = cpu_rq(cpu); 2417 struct rq *this = cpu_rq(cpu);
2418 return atomic_read(&this->nr_iowait); 2418 return atomic_read(&this->nr_iowait);
2419 } 2419 }
2420 2420
2421 void get_iowait_load(unsigned long *nr_waiters, unsigned long *load) 2421 void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
2422 { 2422 {
2423 struct rq *this = this_rq(); 2423 struct rq *this = this_rq();
2424 *nr_waiters = atomic_read(&this->nr_iowait); 2424 *nr_waiters = atomic_read(&this->nr_iowait);
2425 *load = this->cpu_load[0]; 2425 *load = this->cpu_load[0];
2426 } 2426 }
2427 2427
2428 #ifdef CONFIG_SMP 2428 #ifdef CONFIG_SMP
2429 2429
2430 /* 2430 /*
2431 * sched_exec - execve() is a valuable balancing opportunity, because at 2431 * sched_exec - execve() is a valuable balancing opportunity, because at
2432 * this point the task has the smallest effective memory and cache footprint. 2432 * this point the task has the smallest effective memory and cache footprint.
2433 */ 2433 */
2434 void sched_exec(void) 2434 void sched_exec(void)
2435 { 2435 {
2436 struct task_struct *p = current; 2436 struct task_struct *p = current;
2437 unsigned long flags; 2437 unsigned long flags;
2438 int dest_cpu; 2438 int dest_cpu;
2439 2439
2440 raw_spin_lock_irqsave(&p->pi_lock, flags); 2440 raw_spin_lock_irqsave(&p->pi_lock, flags);
2441 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0); 2441 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
2442 if (dest_cpu == smp_processor_id()) 2442 if (dest_cpu == smp_processor_id())
2443 goto unlock; 2443 goto unlock;
2444 2444
2445 if (likely(cpu_active(dest_cpu))) { 2445 if (likely(cpu_active(dest_cpu))) {
2446 struct migration_arg arg = { p, dest_cpu }; 2446 struct migration_arg arg = { p, dest_cpu };
2447 2447
2448 raw_spin_unlock_irqrestore(&p->pi_lock, flags); 2448 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2449 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg); 2449 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
2450 return; 2450 return;
2451 } 2451 }
2452 unlock: 2452 unlock:
2453 raw_spin_unlock_irqrestore(&p->pi_lock, flags); 2453 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2454 } 2454 }
2455 2455
2456 #endif 2456 #endif
2457 2457
2458 DEFINE_PER_CPU(struct kernel_stat, kstat); 2458 DEFINE_PER_CPU(struct kernel_stat, kstat);
2459 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat); 2459 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
2460 2460
2461 EXPORT_PER_CPU_SYMBOL(kstat); 2461 EXPORT_PER_CPU_SYMBOL(kstat);
2462 EXPORT_PER_CPU_SYMBOL(kernel_cpustat); 2462 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
2463 2463
2464 /* 2464 /*
2465 * Return accounted runtime for the task. 2465 * Return accounted runtime for the task.
2466 * In case the task is currently running, return the runtime plus current's 2466 * In case the task is currently running, return the runtime plus current's
2467 * pending runtime that have not been accounted yet. 2467 * pending runtime that have not been accounted yet.
2468 */ 2468 */
2469 unsigned long long task_sched_runtime(struct task_struct *p) 2469 unsigned long long task_sched_runtime(struct task_struct *p)
2470 { 2470 {
2471 unsigned long flags; 2471 unsigned long flags;
2472 struct rq *rq; 2472 struct rq *rq;
2473 u64 ns; 2473 u64 ns;
2474 2474
2475 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP) 2475 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
2476 /* 2476 /*
2477 * 64-bit doesn't need locks to atomically read a 64bit value. 2477 * 64-bit doesn't need locks to atomically read a 64bit value.
2478 * So we have a optimization chance when the task's delta_exec is 0. 2478 * So we have a optimization chance when the task's delta_exec is 0.
2479 * Reading ->on_cpu is racy, but this is ok. 2479 * Reading ->on_cpu is racy, but this is ok.
2480 * 2480 *
2481 * If we race with it leaving cpu, we'll take a lock. So we're correct. 2481 * If we race with it leaving cpu, we'll take a lock. So we're correct.
2482 * If we race with it entering cpu, unaccounted time is 0. This is 2482 * If we race with it entering cpu, unaccounted time is 0. This is
2483 * indistinguishable from the read occurring a few cycles earlier. 2483 * indistinguishable from the read occurring a few cycles earlier.
2484 * If we see ->on_cpu without ->on_rq, the task is leaving, and has 2484 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
2485 * been accounted, so we're correct here as well. 2485 * been accounted, so we're correct here as well.
2486 */ 2486 */
2487 if (!p->on_cpu || !task_on_rq_queued(p)) 2487 if (!p->on_cpu || !task_on_rq_queued(p))
2488 return p->se.sum_exec_runtime; 2488 return p->se.sum_exec_runtime;
2489 #endif 2489 #endif
2490 2490
2491 rq = task_rq_lock(p, &flags); 2491 rq = task_rq_lock(p, &flags);
2492 /* 2492 /*
2493 * Must be ->curr _and_ ->on_rq. If dequeued, we would 2493 * Must be ->curr _and_ ->on_rq. If dequeued, we would
2494 * project cycles that may never be accounted to this 2494 * project cycles that may never be accounted to this
2495 * thread, breaking clock_gettime(). 2495 * thread, breaking clock_gettime().
2496 */ 2496 */
2497 if (task_current(rq, p) && task_on_rq_queued(p)) { 2497 if (task_current(rq, p) && task_on_rq_queued(p)) {
2498 update_rq_clock(rq); 2498 update_rq_clock(rq);
2499 p->sched_class->update_curr(rq); 2499 p->sched_class->update_curr(rq);
2500 } 2500 }
2501 ns = p->se.sum_exec_runtime; 2501 ns = p->se.sum_exec_runtime;
2502 task_rq_unlock(rq, p, &flags); 2502 task_rq_unlock(rq, p, &flags);
2503 2503
2504 return ns; 2504 return ns;
2505 } 2505 }
2506 2506
2507 /* 2507 /*
2508 * This function gets called by the timer code, with HZ frequency. 2508 * This function gets called by the timer code, with HZ frequency.
2509 * We call it with interrupts disabled. 2509 * We call it with interrupts disabled.
2510 */ 2510 */
2511 void scheduler_tick(void) 2511 void scheduler_tick(void)
2512 { 2512 {
2513 int cpu = smp_processor_id(); 2513 int cpu = smp_processor_id();
2514 struct rq *rq = cpu_rq(cpu); 2514 struct rq *rq = cpu_rq(cpu);
2515 struct task_struct *curr = rq->curr; 2515 struct task_struct *curr = rq->curr;
2516 2516
2517 sched_clock_tick(); 2517 sched_clock_tick();
2518 2518
2519 raw_spin_lock(&rq->lock); 2519 raw_spin_lock(&rq->lock);
2520 update_rq_clock(rq); 2520 update_rq_clock(rq);
2521 curr->sched_class->task_tick(rq, curr, 0); 2521 curr->sched_class->task_tick(rq, curr, 0);
2522 update_cpu_load_active(rq); 2522 update_cpu_load_active(rq);
2523 raw_spin_unlock(&rq->lock); 2523 raw_spin_unlock(&rq->lock);
2524 2524
2525 perf_event_task_tick(); 2525 perf_event_task_tick();
2526 2526
2527 #ifdef CONFIG_SMP 2527 #ifdef CONFIG_SMP
2528 rq->idle_balance = idle_cpu(cpu); 2528 rq->idle_balance = idle_cpu(cpu);
2529 trigger_load_balance(rq); 2529 trigger_load_balance(rq);
2530 #endif 2530 #endif
2531 rq_last_tick_reset(rq); 2531 rq_last_tick_reset(rq);
2532 } 2532 }
2533 2533
2534 #ifdef CONFIG_NO_HZ_FULL 2534 #ifdef CONFIG_NO_HZ_FULL
2535 /** 2535 /**
2536 * scheduler_tick_max_deferment 2536 * scheduler_tick_max_deferment
2537 * 2537 *
2538 * Keep at least one tick per second when a single 2538 * Keep at least one tick per second when a single
2539 * active task is running because the scheduler doesn't 2539 * active task is running because the scheduler doesn't
2540 * yet completely support full dynticks environment. 2540 * yet completely support full dynticks environment.
2541 * 2541 *
2542 * This makes sure that uptime, CFS vruntime, load 2542 * This makes sure that uptime, CFS vruntime, load
2543 * balancing, etc... continue to move forward, even 2543 * balancing, etc... continue to move forward, even
2544 * with a very low granularity. 2544 * with a very low granularity.
2545 * 2545 *
2546 * Return: Maximum deferment in nanoseconds. 2546 * Return: Maximum deferment in nanoseconds.
2547 */ 2547 */
2548 u64 scheduler_tick_max_deferment(void) 2548 u64 scheduler_tick_max_deferment(void)
2549 { 2549 {
2550 struct rq *rq = this_rq(); 2550 struct rq *rq = this_rq();
2551 unsigned long next, now = ACCESS_ONCE(jiffies); 2551 unsigned long next, now = ACCESS_ONCE(jiffies);
2552 2552
2553 next = rq->last_sched_tick + HZ; 2553 next = rq->last_sched_tick + HZ;
2554 2554
2555 if (time_before_eq(next, now)) 2555 if (time_before_eq(next, now))
2556 return 0; 2556 return 0;
2557 2557
2558 return jiffies_to_nsecs(next - now); 2558 return jiffies_to_nsecs(next - now);
2559 } 2559 }
2560 #endif 2560 #endif
2561 2561
2562 notrace unsigned long get_parent_ip(unsigned long addr) 2562 notrace unsigned long get_parent_ip(unsigned long addr)
2563 { 2563 {
2564 if (in_lock_functions(addr)) { 2564 if (in_lock_functions(addr)) {
2565 addr = CALLER_ADDR2; 2565 addr = CALLER_ADDR2;
2566 if (in_lock_functions(addr)) 2566 if (in_lock_functions(addr))
2567 addr = CALLER_ADDR3; 2567 addr = CALLER_ADDR3;
2568 } 2568 }
2569 return addr; 2569 return addr;
2570 } 2570 }
2571 2571
2572 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \ 2572 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
2573 defined(CONFIG_PREEMPT_TRACER)) 2573 defined(CONFIG_PREEMPT_TRACER))
2574 2574
2575 void preempt_count_add(int val) 2575 void preempt_count_add(int val)
2576 { 2576 {
2577 #ifdef CONFIG_DEBUG_PREEMPT 2577 #ifdef CONFIG_DEBUG_PREEMPT
2578 /* 2578 /*
2579 * Underflow? 2579 * Underflow?
2580 */ 2580 */
2581 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0))) 2581 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
2582 return; 2582 return;
2583 #endif 2583 #endif
2584 __preempt_count_add(val); 2584 __preempt_count_add(val);
2585 #ifdef CONFIG_DEBUG_PREEMPT 2585 #ifdef CONFIG_DEBUG_PREEMPT
2586 /* 2586 /*
2587 * Spinlock count overflowing soon? 2587 * Spinlock count overflowing soon?
2588 */ 2588 */
2589 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >= 2589 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
2590 PREEMPT_MASK - 10); 2590 PREEMPT_MASK - 10);
2591 #endif 2591 #endif
2592 if (preempt_count() == val) { 2592 if (preempt_count() == val) {
2593 unsigned long ip = get_parent_ip(CALLER_ADDR1); 2593 unsigned long ip = get_parent_ip(CALLER_ADDR1);
2594 #ifdef CONFIG_DEBUG_PREEMPT 2594 #ifdef CONFIG_DEBUG_PREEMPT
2595 current->preempt_disable_ip = ip; 2595 current->preempt_disable_ip = ip;
2596 #endif 2596 #endif
2597 trace_preempt_off(CALLER_ADDR0, ip); 2597 trace_preempt_off(CALLER_ADDR0, ip);
2598 } 2598 }
2599 } 2599 }
2600 EXPORT_SYMBOL(preempt_count_add); 2600 EXPORT_SYMBOL(preempt_count_add);
2601 NOKPROBE_SYMBOL(preempt_count_add); 2601 NOKPROBE_SYMBOL(preempt_count_add);
2602 2602
2603 void preempt_count_sub(int val) 2603 void preempt_count_sub(int val)
2604 { 2604 {
2605 #ifdef CONFIG_DEBUG_PREEMPT 2605 #ifdef CONFIG_DEBUG_PREEMPT
2606 /* 2606 /*
2607 * Underflow? 2607 * Underflow?
2608 */ 2608 */
2609 if (DEBUG_LOCKS_WARN_ON(val > preempt_count())) 2609 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
2610 return; 2610 return;
2611 /* 2611 /*
2612 * Is the spinlock portion underflowing? 2612 * Is the spinlock portion underflowing?
2613 */ 2613 */
2614 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) && 2614 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
2615 !(preempt_count() & PREEMPT_MASK))) 2615 !(preempt_count() & PREEMPT_MASK)))
2616 return; 2616 return;
2617 #endif 2617 #endif
2618 2618
2619 if (preempt_count() == val) 2619 if (preempt_count() == val)
2620 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1)); 2620 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
2621 __preempt_count_sub(val); 2621 __preempt_count_sub(val);
2622 } 2622 }
2623 EXPORT_SYMBOL(preempt_count_sub); 2623 EXPORT_SYMBOL(preempt_count_sub);
2624 NOKPROBE_SYMBOL(preempt_count_sub); 2624 NOKPROBE_SYMBOL(preempt_count_sub);
2625 2625
2626 #endif 2626 #endif
2627 2627
2628 /* 2628 /*
2629 * Print scheduling while atomic bug: 2629 * Print scheduling while atomic bug:
2630 */ 2630 */
2631 static noinline void __schedule_bug(struct task_struct *prev) 2631 static noinline void __schedule_bug(struct task_struct *prev)
2632 { 2632 {
2633 if (oops_in_progress) 2633 if (oops_in_progress)
2634 return; 2634 return;
2635 2635
2636 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n", 2636 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
2637 prev->comm, prev->pid, preempt_count()); 2637 prev->comm, prev->pid, preempt_count());
2638 2638
2639 debug_show_held_locks(prev); 2639 debug_show_held_locks(prev);
2640 print_modules(); 2640 print_modules();
2641 if (irqs_disabled()) 2641 if (irqs_disabled())
2642 print_irqtrace_events(prev); 2642 print_irqtrace_events(prev);
2643 #ifdef CONFIG_DEBUG_PREEMPT 2643 #ifdef CONFIG_DEBUG_PREEMPT
2644 if (in_atomic_preempt_off()) { 2644 if (in_atomic_preempt_off()) {
2645 pr_err("Preemption disabled at:"); 2645 pr_err("Preemption disabled at:");
2646 print_ip_sym(current->preempt_disable_ip); 2646 print_ip_sym(current->preempt_disable_ip);
2647 pr_cont("\n"); 2647 pr_cont("\n");
2648 } 2648 }
2649 #endif 2649 #endif
2650 dump_stack(); 2650 dump_stack();
2651 add_taint(TAINT_WARN, LOCKDEP_STILL_OK); 2651 add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
2652 } 2652 }
2653 2653
2654 /* 2654 /*
2655 * Various schedule()-time debugging checks and statistics: 2655 * Various schedule()-time debugging checks and statistics:
2656 */ 2656 */
2657 static inline void schedule_debug(struct task_struct *prev) 2657 static inline void schedule_debug(struct task_struct *prev)
2658 { 2658 {
2659 #ifdef CONFIG_SCHED_STACK_END_CHECK 2659 #ifdef CONFIG_SCHED_STACK_END_CHECK
2660 BUG_ON(unlikely(task_stack_end_corrupted(prev))); 2660 BUG_ON(unlikely(task_stack_end_corrupted(prev)));
2661 #endif 2661 #endif
2662 /* 2662 /*
2663 * Test if we are atomic. Since do_exit() needs to call into 2663 * Test if we are atomic. Since do_exit() needs to call into
2664 * schedule() atomically, we ignore that path. Otherwise whine 2664 * schedule() atomically, we ignore that path. Otherwise whine
2665 * if we are scheduling when we should not. 2665 * if we are scheduling when we should not.
2666 */ 2666 */
2667 if (unlikely(in_atomic_preempt_off() && prev->state != TASK_DEAD)) 2667 if (unlikely(in_atomic_preempt_off() && prev->state != TASK_DEAD))
2668 __schedule_bug(prev); 2668 __schedule_bug(prev);
2669 rcu_sleep_check(); 2669 rcu_sleep_check();
2670 2670
2671 profile_hit(SCHED_PROFILING, __builtin_return_address(0)); 2671 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2672 2672
2673 schedstat_inc(this_rq(), sched_count); 2673 schedstat_inc(this_rq(), sched_count);
2674 } 2674 }
2675 2675
2676 /* 2676 /*
2677 * Pick up the highest-prio task: 2677 * Pick up the highest-prio task:
2678 */ 2678 */
2679 static inline struct task_struct * 2679 static inline struct task_struct *
2680 pick_next_task(struct rq *rq, struct task_struct *prev) 2680 pick_next_task(struct rq *rq, struct task_struct *prev)
2681 { 2681 {
2682 const struct sched_class *class = &fair_sched_class; 2682 const struct sched_class *class = &fair_sched_class;
2683 struct task_struct *p; 2683 struct task_struct *p;
2684 2684
2685 /* 2685 /*
2686 * Optimization: we know that if all tasks are in 2686 * Optimization: we know that if all tasks are in
2687 * the fair class we can call that function directly: 2687 * the fair class we can call that function directly:
2688 */ 2688 */
2689 if (likely(prev->sched_class == class && 2689 if (likely(prev->sched_class == class &&
2690 rq->nr_running == rq->cfs.h_nr_running)) { 2690 rq->nr_running == rq->cfs.h_nr_running)) {
2691 p = fair_sched_class.pick_next_task(rq, prev); 2691 p = fair_sched_class.pick_next_task(rq, prev);
2692 if (unlikely(p == RETRY_TASK)) 2692 if (unlikely(p == RETRY_TASK))
2693 goto again; 2693 goto again;
2694 2694
2695 /* assumes fair_sched_class->next == idle_sched_class */ 2695 /* assumes fair_sched_class->next == idle_sched_class */
2696 if (unlikely(!p)) 2696 if (unlikely(!p))
2697 p = idle_sched_class.pick_next_task(rq, prev); 2697 p = idle_sched_class.pick_next_task(rq, prev);
2698 2698
2699 return p; 2699 return p;
2700 } 2700 }
2701 2701
2702 again: 2702 again:
2703 for_each_class(class) { 2703 for_each_class(class) {
2704 p = class->pick_next_task(rq, prev); 2704 p = class->pick_next_task(rq, prev);
2705 if (p) { 2705 if (p) {
2706 if (unlikely(p == RETRY_TASK)) 2706 if (unlikely(p == RETRY_TASK))
2707 goto again; 2707 goto again;
2708 return p; 2708 return p;
2709 } 2709 }
2710 } 2710 }
2711 2711
2712 BUG(); /* the idle class will always have a runnable task */ 2712 BUG(); /* the idle class will always have a runnable task */
2713 } 2713 }
2714 2714
2715 /* 2715 /*
2716 * __schedule() is the main scheduler function. 2716 * __schedule() is the main scheduler function.
2717 * 2717 *
2718 * The main means of driving the scheduler and thus entering this function are: 2718 * The main means of driving the scheduler and thus entering this function are:
2719 * 2719 *
2720 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc. 2720 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
2721 * 2721 *
2722 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return 2722 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
2723 * paths. For example, see arch/x86/entry_64.S. 2723 * paths. For example, see arch/x86/entry_64.S.
2724 * 2724 *
2725 * To drive preemption between tasks, the scheduler sets the flag in timer 2725 * To drive preemption between tasks, the scheduler sets the flag in timer
2726 * interrupt handler scheduler_tick(). 2726 * interrupt handler scheduler_tick().
2727 * 2727 *
2728 * 3. Wakeups don't really cause entry into schedule(). They add a 2728 * 3. Wakeups don't really cause entry into schedule(). They add a
2729 * task to the run-queue and that's it. 2729 * task to the run-queue and that's it.
2730 * 2730 *
2731 * Now, if the new task added to the run-queue preempts the current 2731 * Now, if the new task added to the run-queue preempts the current
2732 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets 2732 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
2733 * called on the nearest possible occasion: 2733 * called on the nearest possible occasion:
2734 * 2734 *
2735 * - If the kernel is preemptible (CONFIG_PREEMPT=y): 2735 * - If the kernel is preemptible (CONFIG_PREEMPT=y):
2736 * 2736 *
2737 * - in syscall or exception context, at the next outmost 2737 * - in syscall or exception context, at the next outmost
2738 * preempt_enable(). (this might be as soon as the wake_up()'s 2738 * preempt_enable(). (this might be as soon as the wake_up()'s
2739 * spin_unlock()!) 2739 * spin_unlock()!)
2740 * 2740 *
2741 * - in IRQ context, return from interrupt-handler to 2741 * - in IRQ context, return from interrupt-handler to
2742 * preemptible context 2742 * preemptible context
2743 * 2743 *
2744 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set) 2744 * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
2745 * then at the next: 2745 * then at the next:
2746 * 2746 *
2747 * - cond_resched() call 2747 * - cond_resched() call
2748 * - explicit schedule() call 2748 * - explicit schedule() call
2749 * - return from syscall or exception to user-space 2749 * - return from syscall or exception to user-space
2750 * - return from interrupt-handler to user-space 2750 * - return from interrupt-handler to user-space
2751 */ 2751 */
2752 static void __sched __schedule(void) 2752 static void __sched __schedule(void)
2753 { 2753 {
2754 struct task_struct *prev, *next; 2754 struct task_struct *prev, *next;
2755 unsigned long *switch_count; 2755 unsigned long *switch_count;
2756 struct rq *rq; 2756 struct rq *rq;
2757 int cpu; 2757 int cpu;
2758 2758
2759 need_resched: 2759 need_resched:
2760 preempt_disable(); 2760 preempt_disable();
2761 cpu = smp_processor_id(); 2761 cpu = smp_processor_id();
2762 rq = cpu_rq(cpu); 2762 rq = cpu_rq(cpu);
2763 rcu_note_context_switch(); 2763 rcu_note_context_switch();
2764 prev = rq->curr; 2764 prev = rq->curr;
2765 2765
2766 schedule_debug(prev); 2766 schedule_debug(prev);
2767 2767
2768 if (sched_feat(HRTICK)) 2768 if (sched_feat(HRTICK))
2769 hrtick_clear(rq); 2769 hrtick_clear(rq);
2770 2770
2771 /* 2771 /*
2772 * Make sure that signal_pending_state()->signal_pending() below 2772 * Make sure that signal_pending_state()->signal_pending() below
2773 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE) 2773 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
2774 * done by the caller to avoid the race with signal_wake_up(). 2774 * done by the caller to avoid the race with signal_wake_up().
2775 */ 2775 */
2776 smp_mb__before_spinlock(); 2776 smp_mb__before_spinlock();
2777 raw_spin_lock_irq(&rq->lock); 2777 raw_spin_lock_irq(&rq->lock);
2778 2778
2779 switch_count = &prev->nivcsw; 2779 switch_count = &prev->nivcsw;
2780 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) { 2780 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2781 if (unlikely(signal_pending_state(prev->state, prev))) { 2781 if (unlikely(signal_pending_state(prev->state, prev))) {
2782 prev->state = TASK_RUNNING; 2782 prev->state = TASK_RUNNING;
2783 } else { 2783 } else {
2784 deactivate_task(rq, prev, DEQUEUE_SLEEP); 2784 deactivate_task(rq, prev, DEQUEUE_SLEEP);
2785 prev->on_rq = 0; 2785 prev->on_rq = 0;
2786 2786
2787 /* 2787 /*
2788 * If a worker went to sleep, notify and ask workqueue 2788 * If a worker went to sleep, notify and ask workqueue
2789 * whether it wants to wake up a task to maintain 2789 * whether it wants to wake up a task to maintain
2790 * concurrency. 2790 * concurrency.
2791 */ 2791 */
2792 if (prev->flags & PF_WQ_WORKER) { 2792 if (prev->flags & PF_WQ_WORKER) {
2793 struct task_struct *to_wakeup; 2793 struct task_struct *to_wakeup;
2794 2794
2795 to_wakeup = wq_worker_sleeping(prev, cpu); 2795 to_wakeup = wq_worker_sleeping(prev, cpu);
2796 if (to_wakeup) 2796 if (to_wakeup)
2797 try_to_wake_up_local(to_wakeup); 2797 try_to_wake_up_local(to_wakeup);
2798 } 2798 }
2799 } 2799 }
2800 switch_count = &prev->nvcsw; 2800 switch_count = &prev->nvcsw;
2801 } 2801 }
2802 2802
2803 if (task_on_rq_queued(prev) || rq->skip_clock_update < 0) 2803 if (task_on_rq_queued(prev) || rq->skip_clock_update < 0)
2804 update_rq_clock(rq); 2804 update_rq_clock(rq);
2805 2805
2806 next = pick_next_task(rq, prev); 2806 next = pick_next_task(rq, prev);
2807 clear_tsk_need_resched(prev); 2807 clear_tsk_need_resched(prev);
2808 clear_preempt_need_resched(); 2808 clear_preempt_need_resched();
2809 rq->skip_clock_update = 0; 2809 rq->skip_clock_update = 0;
2810 2810
2811 if (likely(prev != next)) { 2811 if (likely(prev != next)) {
2812 rq->nr_switches++; 2812 rq->nr_switches++;
2813 rq->curr = next; 2813 rq->curr = next;
2814 ++*switch_count; 2814 ++*switch_count;
2815 2815
2816 rq = context_switch(rq, prev, next); /* unlocks the rq */ 2816 rq = context_switch(rq, prev, next); /* unlocks the rq */
2817 cpu = cpu_of(rq); 2817 cpu = cpu_of(rq);
2818 } else 2818 } else
2819 raw_spin_unlock_irq(&rq->lock); 2819 raw_spin_unlock_irq(&rq->lock);
2820 2820
2821 post_schedule(rq); 2821 post_schedule(rq);
2822 2822
2823 sched_preempt_enable_no_resched(); 2823 sched_preempt_enable_no_resched();
2824 if (need_resched()) 2824 if (need_resched())
2825 goto need_resched; 2825 goto need_resched;
2826 } 2826 }
2827 2827
2828 static inline void sched_submit_work(struct task_struct *tsk) 2828 static inline void sched_submit_work(struct task_struct *tsk)
2829 { 2829 {
2830 if (!tsk->state || tsk_is_pi_blocked(tsk)) 2830 if (!tsk->state || tsk_is_pi_blocked(tsk))
2831 return; 2831 return;
2832 /* 2832 /*
2833 * If we are going to sleep and we have plugged IO queued, 2833 * If we are going to sleep and we have plugged IO queued,
2834 * make sure to submit it to avoid deadlocks. 2834 * make sure to submit it to avoid deadlocks.
2835 */ 2835 */
2836 if (blk_needs_flush_plug(tsk)) 2836 if (blk_needs_flush_plug(tsk))
2837 blk_schedule_flush_plug(tsk); 2837 blk_schedule_flush_plug(tsk);
2838 } 2838 }
2839 2839
2840 asmlinkage __visible void __sched schedule(void) 2840 asmlinkage __visible void __sched schedule(void)
2841 { 2841 {
2842 struct task_struct *tsk = current; 2842 struct task_struct *tsk = current;
2843 2843
2844 sched_submit_work(tsk); 2844 sched_submit_work(tsk);
2845 __schedule(); 2845 __schedule();
2846 } 2846 }
2847 EXPORT_SYMBOL(schedule); 2847 EXPORT_SYMBOL(schedule);
2848 2848
2849 #ifdef CONFIG_CONTEXT_TRACKING 2849 #ifdef CONFIG_CONTEXT_TRACKING
2850 asmlinkage __visible void __sched schedule_user(void) 2850 asmlinkage __visible void __sched schedule_user(void)
2851 { 2851 {
2852 /* 2852 /*
2853 * If we come here after a random call to set_need_resched(), 2853 * If we come here after a random call to set_need_resched(),
2854 * or we have been woken up remotely but the IPI has not yet arrived, 2854 * or we have been woken up remotely but the IPI has not yet arrived,
2855 * we haven't yet exited the RCU idle mode. Do it here manually until 2855 * we haven't yet exited the RCU idle mode. Do it here manually until
2856 * we find a better solution. 2856 * we find a better solution.
2857 * 2857 *
2858 * NB: There are buggy callers of this function. Ideally we 2858 * NB: There are buggy callers of this function. Ideally we
2859 * should warn if prev_state != IN_USER, but that will trigger 2859 * should warn if prev_state != IN_USER, but that will trigger
2860 * too frequently to make sense yet. 2860 * too frequently to make sense yet.
2861 */ 2861 */
2862 enum ctx_state prev_state = exception_enter(); 2862 enum ctx_state prev_state = exception_enter();
2863 schedule(); 2863 schedule();
2864 exception_exit(prev_state); 2864 exception_exit(prev_state);
2865 } 2865 }
2866 #endif 2866 #endif
2867 2867
2868 /** 2868 /**
2869 * schedule_preempt_disabled - called with preemption disabled 2869 * schedule_preempt_disabled - called with preemption disabled
2870 * 2870 *
2871 * Returns with preemption disabled. Note: preempt_count must be 1 2871 * Returns with preemption disabled. Note: preempt_count must be 1
2872 */ 2872 */
2873 void __sched schedule_preempt_disabled(void) 2873 void __sched schedule_preempt_disabled(void)
2874 { 2874 {
2875 sched_preempt_enable_no_resched(); 2875 sched_preempt_enable_no_resched();
2876 schedule(); 2876 schedule();
2877 preempt_disable(); 2877 preempt_disable();
2878 } 2878 }
2879 2879
2880 #ifdef CONFIG_PREEMPT 2880 #ifdef CONFIG_PREEMPT
2881 /* 2881 /*
2882 * this is the entry point to schedule() from in-kernel preemption 2882 * this is the entry point to schedule() from in-kernel preemption
2883 * off of preempt_enable. Kernel preemptions off return from interrupt 2883 * off of preempt_enable. Kernel preemptions off return from interrupt
2884 * occur there and call schedule directly. 2884 * occur there and call schedule directly.
2885 */ 2885 */
2886 asmlinkage __visible void __sched notrace preempt_schedule(void) 2886 asmlinkage __visible void __sched notrace preempt_schedule(void)
2887 { 2887 {
2888 /* 2888 /*
2889 * If there is a non-zero preempt_count or interrupts are disabled, 2889 * If there is a non-zero preempt_count or interrupts are disabled,
2890 * we do not want to preempt the current task. Just return.. 2890 * we do not want to preempt the current task. Just return..
2891 */ 2891 */
2892 if (likely(!preemptible())) 2892 if (likely(!preemptible()))
2893 return; 2893 return;
2894 2894
2895 do { 2895 do {
2896 __preempt_count_add(PREEMPT_ACTIVE); 2896 __preempt_count_add(PREEMPT_ACTIVE);
2897 __schedule(); 2897 __schedule();
2898 __preempt_count_sub(PREEMPT_ACTIVE); 2898 __preempt_count_sub(PREEMPT_ACTIVE);
2899 2899
2900 /* 2900 /*
2901 * Check again in case we missed a preemption opportunity 2901 * Check again in case we missed a preemption opportunity
2902 * between schedule and now. 2902 * between schedule and now.
2903 */ 2903 */
2904 barrier(); 2904 barrier();
2905 } while (need_resched()); 2905 } while (need_resched());
2906 } 2906 }
2907 NOKPROBE_SYMBOL(preempt_schedule); 2907 NOKPROBE_SYMBOL(preempt_schedule);
2908 EXPORT_SYMBOL(preempt_schedule); 2908 EXPORT_SYMBOL(preempt_schedule);
2909 2909
2910 #ifdef CONFIG_CONTEXT_TRACKING 2910 #ifdef CONFIG_CONTEXT_TRACKING
2911 /** 2911 /**
2912 * preempt_schedule_context - preempt_schedule called by tracing 2912 * preempt_schedule_context - preempt_schedule called by tracing
2913 * 2913 *
2914 * The tracing infrastructure uses preempt_enable_notrace to prevent 2914 * The tracing infrastructure uses preempt_enable_notrace to prevent
2915 * recursion and tracing preempt enabling caused by the tracing 2915 * recursion and tracing preempt enabling caused by the tracing
2916 * infrastructure itself. But as tracing can happen in areas coming 2916 * infrastructure itself. But as tracing can happen in areas coming
2917 * from userspace or just about to enter userspace, a preempt enable 2917 * from userspace or just about to enter userspace, a preempt enable
2918 * can occur before user_exit() is called. This will cause the scheduler 2918 * can occur before user_exit() is called. This will cause the scheduler
2919 * to be called when the system is still in usermode. 2919 * to be called when the system is still in usermode.
2920 * 2920 *
2921 * To prevent this, the preempt_enable_notrace will use this function 2921 * To prevent this, the preempt_enable_notrace will use this function
2922 * instead of preempt_schedule() to exit user context if needed before 2922 * instead of preempt_schedule() to exit user context if needed before
2923 * calling the scheduler. 2923 * calling the scheduler.
2924 */ 2924 */
2925 asmlinkage __visible void __sched notrace preempt_schedule_context(void) 2925 asmlinkage __visible void __sched notrace preempt_schedule_context(void)
2926 { 2926 {
2927 enum ctx_state prev_ctx; 2927 enum ctx_state prev_ctx;
2928 2928
2929 if (likely(!preemptible())) 2929 if (likely(!preemptible()))
2930 return; 2930 return;
2931 2931
2932 do { 2932 do {
2933 __preempt_count_add(PREEMPT_ACTIVE); 2933 __preempt_count_add(PREEMPT_ACTIVE);
2934 /* 2934 /*
2935 * Needs preempt disabled in case user_exit() is traced 2935 * Needs preempt disabled in case user_exit() is traced
2936 * and the tracer calls preempt_enable_notrace() causing 2936 * and the tracer calls preempt_enable_notrace() causing
2937 * an infinite recursion. 2937 * an infinite recursion.
2938 */ 2938 */
2939 prev_ctx = exception_enter(); 2939 prev_ctx = exception_enter();
2940 __schedule(); 2940 __schedule();
2941 exception_exit(prev_ctx); 2941 exception_exit(prev_ctx);
2942 2942
2943 __preempt_count_sub(PREEMPT_ACTIVE); 2943 __preempt_count_sub(PREEMPT_ACTIVE);
2944 barrier(); 2944 barrier();
2945 } while (need_resched()); 2945 } while (need_resched());
2946 } 2946 }
2947 EXPORT_SYMBOL_GPL(preempt_schedule_context); 2947 EXPORT_SYMBOL_GPL(preempt_schedule_context);
2948 #endif /* CONFIG_CONTEXT_TRACKING */ 2948 #endif /* CONFIG_CONTEXT_TRACKING */
2949 2949
2950 #endif /* CONFIG_PREEMPT */ 2950 #endif /* CONFIG_PREEMPT */
2951 2951
2952 /* 2952 /*
2953 * this is the entry point to schedule() from kernel preemption 2953 * this is the entry point to schedule() from kernel preemption
2954 * off of irq context. 2954 * off of irq context.
2955 * Note, that this is called and return with irqs disabled. This will 2955 * Note, that this is called and return with irqs disabled. This will
2956 * protect us against recursive calling from irq. 2956 * protect us against recursive calling from irq.
2957 */ 2957 */
2958 asmlinkage __visible void __sched preempt_schedule_irq(void) 2958 asmlinkage __visible void __sched preempt_schedule_irq(void)
2959 { 2959 {
2960 enum ctx_state prev_state; 2960 enum ctx_state prev_state;
2961 2961
2962 /* Catch callers which need to be fixed */ 2962 /* Catch callers which need to be fixed */
2963 BUG_ON(preempt_count() || !irqs_disabled()); 2963 BUG_ON(preempt_count() || !irqs_disabled());
2964 2964
2965 prev_state = exception_enter(); 2965 prev_state = exception_enter();
2966 2966
2967 do { 2967 do {
2968 __preempt_count_add(PREEMPT_ACTIVE); 2968 __preempt_count_add(PREEMPT_ACTIVE);
2969 local_irq_enable(); 2969 local_irq_enable();
2970 __schedule(); 2970 __schedule();
2971 local_irq_disable(); 2971 local_irq_disable();
2972 __preempt_count_sub(PREEMPT_ACTIVE); 2972 __preempt_count_sub(PREEMPT_ACTIVE);
2973 2973
2974 /* 2974 /*
2975 * Check again in case we missed a preemption opportunity 2975 * Check again in case we missed a preemption opportunity
2976 * between schedule and now. 2976 * between schedule and now.
2977 */ 2977 */
2978 barrier(); 2978 barrier();
2979 } while (need_resched()); 2979 } while (need_resched());
2980 2980
2981 exception_exit(prev_state); 2981 exception_exit(prev_state);
2982 } 2982 }
2983 2983
2984 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags, 2984 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
2985 void *key) 2985 void *key)
2986 { 2986 {
2987 return try_to_wake_up(curr->private, mode, wake_flags); 2987 return try_to_wake_up(curr->private, mode, wake_flags);
2988 } 2988 }
2989 EXPORT_SYMBOL(default_wake_function); 2989 EXPORT_SYMBOL(default_wake_function);
2990 2990
2991 #ifdef CONFIG_RT_MUTEXES 2991 #ifdef CONFIG_RT_MUTEXES
2992 2992
2993 /* 2993 /*
2994 * rt_mutex_setprio - set the current priority of a task 2994 * rt_mutex_setprio - set the current priority of a task
2995 * @p: task 2995 * @p: task
2996 * @prio: prio value (kernel-internal form) 2996 * @prio: prio value (kernel-internal form)
2997 * 2997 *
2998 * This function changes the 'effective' priority of a task. It does 2998 * This function changes the 'effective' priority of a task. It does
2999 * not touch ->normal_prio like __setscheduler(). 2999 * not touch ->normal_prio like __setscheduler().
3000 * 3000 *
3001 * Used by the rt_mutex code to implement priority inheritance 3001 * Used by the rt_mutex code to implement priority inheritance
3002 * logic. Call site only calls if the priority of the task changed. 3002 * logic. Call site only calls if the priority of the task changed.
3003 */ 3003 */
3004 void rt_mutex_setprio(struct task_struct *p, int prio) 3004 void rt_mutex_setprio(struct task_struct *p, int prio)
3005 { 3005 {
3006 int oldprio, queued, running, enqueue_flag = 0; 3006 int oldprio, queued, running, enqueue_flag = 0;
3007 struct rq *rq; 3007 struct rq *rq;
3008 const struct sched_class *prev_class; 3008 const struct sched_class *prev_class;
3009 3009
3010 BUG_ON(prio > MAX_PRIO); 3010 BUG_ON(prio > MAX_PRIO);
3011 3011
3012 rq = __task_rq_lock(p); 3012 rq = __task_rq_lock(p);
3013 3013
3014 /* 3014 /*
3015 * Idle task boosting is a nono in general. There is one 3015 * Idle task boosting is a nono in general. There is one
3016 * exception, when PREEMPT_RT and NOHZ is active: 3016 * exception, when PREEMPT_RT and NOHZ is active:
3017 * 3017 *
3018 * The idle task calls get_next_timer_interrupt() and holds 3018 * The idle task calls get_next_timer_interrupt() and holds
3019 * the timer wheel base->lock on the CPU and another CPU wants 3019 * the timer wheel base->lock on the CPU and another CPU wants
3020 * to access the timer (probably to cancel it). We can safely 3020 * to access the timer (probably to cancel it). We can safely
3021 * ignore the boosting request, as the idle CPU runs this code 3021 * ignore the boosting request, as the idle CPU runs this code
3022 * with interrupts disabled and will complete the lock 3022 * with interrupts disabled and will complete the lock
3023 * protected section without being interrupted. So there is no 3023 * protected section without being interrupted. So there is no
3024 * real need to boost. 3024 * real need to boost.
3025 */ 3025 */
3026 if (unlikely(p == rq->idle)) { 3026 if (unlikely(p == rq->idle)) {
3027 WARN_ON(p != rq->curr); 3027 WARN_ON(p != rq->curr);
3028 WARN_ON(p->pi_blocked_on); 3028 WARN_ON(p->pi_blocked_on);
3029 goto out_unlock; 3029 goto out_unlock;
3030 } 3030 }
3031 3031
3032 trace_sched_pi_setprio(p, prio); 3032 trace_sched_pi_setprio(p, prio);
3033 oldprio = p->prio; 3033 oldprio = p->prio;
3034 prev_class = p->sched_class; 3034 prev_class = p->sched_class;
3035 queued = task_on_rq_queued(p); 3035 queued = task_on_rq_queued(p);
3036 running = task_current(rq, p); 3036 running = task_current(rq, p);
3037 if (queued) 3037 if (queued)
3038 dequeue_task(rq, p, 0); 3038 dequeue_task(rq, p, 0);
3039 if (running) 3039 if (running)
3040 put_prev_task(rq, p); 3040 put_prev_task(rq, p);
3041 3041
3042 /* 3042 /*
3043 * Boosting condition are: 3043 * Boosting condition are:
3044 * 1. -rt task is running and holds mutex A 3044 * 1. -rt task is running and holds mutex A
3045 * --> -dl task blocks on mutex A 3045 * --> -dl task blocks on mutex A
3046 * 3046 *
3047 * 2. -dl task is running and holds mutex A 3047 * 2. -dl task is running and holds mutex A
3048 * --> -dl task blocks on mutex A and could preempt the 3048 * --> -dl task blocks on mutex A and could preempt the
3049 * running task 3049 * running task
3050 */ 3050 */
3051 if (dl_prio(prio)) { 3051 if (dl_prio(prio)) {
3052 struct task_struct *pi_task = rt_mutex_get_top_task(p); 3052 struct task_struct *pi_task = rt_mutex_get_top_task(p);
3053 if (!dl_prio(p->normal_prio) || 3053 if (!dl_prio(p->normal_prio) ||
3054 (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) { 3054 (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
3055 p->dl.dl_boosted = 1; 3055 p->dl.dl_boosted = 1;
3056 p->dl.dl_throttled = 0; 3056 p->dl.dl_throttled = 0;
3057 enqueue_flag = ENQUEUE_REPLENISH; 3057 enqueue_flag = ENQUEUE_REPLENISH;
3058 } else 3058 } else
3059 p->dl.dl_boosted = 0; 3059 p->dl.dl_boosted = 0;
3060 p->sched_class = &dl_sched_class; 3060 p->sched_class = &dl_sched_class;
3061 } else if (rt_prio(prio)) { 3061 } else if (rt_prio(prio)) {
3062 if (dl_prio(oldprio)) 3062 if (dl_prio(oldprio))
3063 p->dl.dl_boosted = 0; 3063 p->dl.dl_boosted = 0;
3064 if (oldprio < prio) 3064 if (oldprio < prio)
3065 enqueue_flag = ENQUEUE_HEAD; 3065 enqueue_flag = ENQUEUE_HEAD;
3066 p->sched_class = &rt_sched_class; 3066 p->sched_class = &rt_sched_class;
3067 } else { 3067 } else {
3068 if (dl_prio(oldprio)) 3068 if (dl_prio(oldprio))
3069 p->dl.dl_boosted = 0; 3069 p->dl.dl_boosted = 0;
3070 p->sched_class = &fair_sched_class; 3070 p->sched_class = &fair_sched_class;
3071 } 3071 }
3072 3072
3073 p->prio = prio; 3073 p->prio = prio;
3074 3074
3075 if (running) 3075 if (running)
3076 p->sched_class->set_curr_task(rq); 3076 p->sched_class->set_curr_task(rq);
3077 if (queued) 3077 if (queued)
3078 enqueue_task(rq, p, enqueue_flag); 3078 enqueue_task(rq, p, enqueue_flag);
3079 3079
3080 check_class_changed(rq, p, prev_class, oldprio); 3080 check_class_changed(rq, p, prev_class, oldprio);
3081 out_unlock: 3081 out_unlock:
3082 __task_rq_unlock(rq); 3082 __task_rq_unlock(rq);
3083 } 3083 }
3084 #endif 3084 #endif
3085 3085
3086 void set_user_nice(struct task_struct *p, long nice) 3086 void set_user_nice(struct task_struct *p, long nice)
3087 { 3087 {
3088 int old_prio, delta, queued; 3088 int old_prio, delta, queued;
3089 unsigned long flags; 3089 unsigned long flags;
3090 struct rq *rq; 3090 struct rq *rq;
3091 3091
3092 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE) 3092 if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
3093 return; 3093 return;
3094 /* 3094 /*
3095 * We have to be careful, if called from sys_setpriority(), 3095 * We have to be careful, if called from sys_setpriority(),
3096 * the task might be in the middle of scheduling on another CPU. 3096 * the task might be in the middle of scheduling on another CPU.
3097 */ 3097 */
3098 rq = task_rq_lock(p, &flags); 3098 rq = task_rq_lock(p, &flags);
3099 /* 3099 /*
3100 * The RT priorities are set via sched_setscheduler(), but we still 3100 * The RT priorities are set via sched_setscheduler(), but we still
3101 * allow the 'normal' nice value to be set - but as expected 3101 * allow the 'normal' nice value to be set - but as expected
3102 * it wont have any effect on scheduling until the task is 3102 * it wont have any effect on scheduling until the task is
3103 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR: 3103 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
3104 */ 3104 */
3105 if (task_has_dl_policy(p) || task_has_rt_policy(p)) { 3105 if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
3106 p->static_prio = NICE_TO_PRIO(nice); 3106 p->static_prio = NICE_TO_PRIO(nice);
3107 goto out_unlock; 3107 goto out_unlock;
3108 } 3108 }
3109 queued = task_on_rq_queued(p); 3109 queued = task_on_rq_queued(p);
3110 if (queued) 3110 if (queued)
3111 dequeue_task(rq, p, 0); 3111 dequeue_task(rq, p, 0);
3112 3112
3113 p->static_prio = NICE_TO_PRIO(nice); 3113 p->static_prio = NICE_TO_PRIO(nice);
3114 set_load_weight(p); 3114 set_load_weight(p);
3115 old_prio = p->prio; 3115 old_prio = p->prio;
3116 p->prio = effective_prio(p); 3116 p->prio = effective_prio(p);
3117 delta = p->prio - old_prio; 3117 delta = p->prio - old_prio;
3118 3118
3119 if (queued) { 3119 if (queued) {
3120 enqueue_task(rq, p, 0); 3120 enqueue_task(rq, p, 0);
3121 /* 3121 /*
3122 * If the task increased its priority or is running and 3122 * If the task increased its priority or is running and
3123 * lowered its priority, then reschedule its CPU: 3123 * lowered its priority, then reschedule its CPU:
3124 */ 3124 */
3125 if (delta < 0 || (delta > 0 && task_running(rq, p))) 3125 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3126 resched_curr(rq); 3126 resched_curr(rq);
3127 } 3127 }
3128 out_unlock: 3128 out_unlock:
3129 task_rq_unlock(rq, p, &flags); 3129 task_rq_unlock(rq, p, &flags);
3130 } 3130 }
3131 EXPORT_SYMBOL(set_user_nice); 3131 EXPORT_SYMBOL(set_user_nice);
3132 3132
3133 /* 3133 /*
3134 * can_nice - check if a task can reduce its nice value 3134 * can_nice - check if a task can reduce its nice value
3135 * @p: task 3135 * @p: task
3136 * @nice: nice value 3136 * @nice: nice value
3137 */ 3137 */
3138 int can_nice(const struct task_struct *p, const int nice) 3138 int can_nice(const struct task_struct *p, const int nice)
3139 { 3139 {
3140 /* convert nice value [19,-20] to rlimit style value [1,40] */ 3140 /* convert nice value [19,-20] to rlimit style value [1,40] */
3141 int nice_rlim = nice_to_rlimit(nice); 3141 int nice_rlim = nice_to_rlimit(nice);
3142 3142
3143 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) || 3143 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
3144 capable(CAP_SYS_NICE)); 3144 capable(CAP_SYS_NICE));
3145 } 3145 }
3146 3146
3147 #ifdef __ARCH_WANT_SYS_NICE 3147 #ifdef __ARCH_WANT_SYS_NICE
3148 3148
3149 /* 3149 /*
3150 * sys_nice - change the priority of the current process. 3150 * sys_nice - change the priority of the current process.
3151 * @increment: priority increment 3151 * @increment: priority increment
3152 * 3152 *
3153 * sys_setpriority is a more generic, but much slower function that 3153 * sys_setpriority is a more generic, but much slower function that
3154 * does similar things. 3154 * does similar things.
3155 */ 3155 */
3156 SYSCALL_DEFINE1(nice, int, increment) 3156 SYSCALL_DEFINE1(nice, int, increment)
3157 { 3157 {
3158 long nice, retval; 3158 long nice, retval;
3159 3159
3160 /* 3160 /*
3161 * Setpriority might change our priority at the same moment. 3161 * Setpriority might change our priority at the same moment.
3162 * We don't have to worry. Conceptually one call occurs first 3162 * We don't have to worry. Conceptually one call occurs first
3163 * and we have a single winner. 3163 * and we have a single winner.
3164 */ 3164 */
3165 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH); 3165 increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
3166 nice = task_nice(current) + increment; 3166 nice = task_nice(current) + increment;
3167 3167
3168 nice = clamp_val(nice, MIN_NICE, MAX_NICE); 3168 nice = clamp_val(nice, MIN_NICE, MAX_NICE);
3169 if (increment < 0 && !can_nice(current, nice)) 3169 if (increment < 0 && !can_nice(current, nice))
3170 return -EPERM; 3170 return -EPERM;
3171 3171
3172 retval = security_task_setnice(current, nice); 3172 retval = security_task_setnice(current, nice);
3173 if (retval) 3173 if (retval)
3174 return retval; 3174 return retval;
3175 3175
3176 set_user_nice(current, nice); 3176 set_user_nice(current, nice);
3177 return 0; 3177 return 0;
3178 } 3178 }
3179 3179
3180 #endif 3180 #endif
3181 3181
3182 /** 3182 /**
3183 * task_prio - return the priority value of a given task. 3183 * task_prio - return the priority value of a given task.
3184 * @p: the task in question. 3184 * @p: the task in question.
3185 * 3185 *
3186 * Return: The priority value as seen by users in /proc. 3186 * Return: The priority value as seen by users in /proc.
3187 * RT tasks are offset by -200. Normal tasks are centered 3187 * RT tasks are offset by -200. Normal tasks are centered
3188 * around 0, value goes from -16 to +15. 3188 * around 0, value goes from -16 to +15.
3189 */ 3189 */
3190 int task_prio(const struct task_struct *p) 3190 int task_prio(const struct task_struct *p)
3191 { 3191 {
3192 return p->prio - MAX_RT_PRIO; 3192 return p->prio - MAX_RT_PRIO;
3193 } 3193 }
3194 3194
3195 /** 3195 /**
3196 * idle_cpu - is a given cpu idle currently? 3196 * idle_cpu - is a given cpu idle currently?
3197 * @cpu: the processor in question. 3197 * @cpu: the processor in question.
3198 * 3198 *
3199 * Return: 1 if the CPU is currently idle. 0 otherwise. 3199 * Return: 1 if the CPU is currently idle. 0 otherwise.
3200 */ 3200 */
3201 int idle_cpu(int cpu) 3201 int idle_cpu(int cpu)
3202 { 3202 {
3203 struct rq *rq = cpu_rq(cpu); 3203 struct rq *rq = cpu_rq(cpu);
3204 3204
3205 if (rq->curr != rq->idle) 3205 if (rq->curr != rq->idle)
3206 return 0; 3206 return 0;
3207 3207
3208 if (rq->nr_running) 3208 if (rq->nr_running)
3209 return 0; 3209 return 0;
3210 3210
3211 #ifdef CONFIG_SMP 3211 #ifdef CONFIG_SMP
3212 if (!llist_empty(&rq->wake_list)) 3212 if (!llist_empty(&rq->wake_list))
3213 return 0; 3213 return 0;
3214 #endif 3214 #endif
3215 3215
3216 return 1; 3216 return 1;
3217 } 3217 }
3218 3218
3219 /** 3219 /**
3220 * idle_task - return the idle task for a given cpu. 3220 * idle_task - return the idle task for a given cpu.
3221 * @cpu: the processor in question. 3221 * @cpu: the processor in question.
3222 * 3222 *
3223 * Return: The idle task for the cpu @cpu. 3223 * Return: The idle task for the cpu @cpu.
3224 */ 3224 */
3225 struct task_struct *idle_task(int cpu) 3225 struct task_struct *idle_task(int cpu)
3226 { 3226 {
3227 return cpu_rq(cpu)->idle; 3227 return cpu_rq(cpu)->idle;
3228 } 3228 }
3229 3229
3230 /** 3230 /**
3231 * find_process_by_pid - find a process with a matching PID value. 3231 * find_process_by_pid - find a process with a matching PID value.
3232 * @pid: the pid in question. 3232 * @pid: the pid in question.
3233 * 3233 *
3234 * The task of @pid, if found. %NULL otherwise. 3234 * The task of @pid, if found. %NULL otherwise.
3235 */ 3235 */
3236 static struct task_struct *find_process_by_pid(pid_t pid) 3236 static struct task_struct *find_process_by_pid(pid_t pid)
3237 { 3237 {
3238 return pid ? find_task_by_vpid(pid) : current; 3238 return pid ? find_task_by_vpid(pid) : current;
3239 } 3239 }
3240 3240
3241 /* 3241 /*
3242 * This function initializes the sched_dl_entity of a newly becoming 3242 * This function initializes the sched_dl_entity of a newly becoming
3243 * SCHED_DEADLINE task. 3243 * SCHED_DEADLINE task.
3244 * 3244 *
3245 * Only the static values are considered here, the actual runtime and the 3245 * Only the static values are considered here, the actual runtime and the
3246 * absolute deadline will be properly calculated when the task is enqueued 3246 * absolute deadline will be properly calculated when the task is enqueued
3247 * for the first time with its new policy. 3247 * for the first time with its new policy.
3248 */ 3248 */
3249 static void 3249 static void
3250 __setparam_dl(struct task_struct *p, const struct sched_attr *attr) 3250 __setparam_dl(struct task_struct *p, const struct sched_attr *attr)
3251 { 3251 {
3252 struct sched_dl_entity *dl_se = &p->dl; 3252 struct sched_dl_entity *dl_se = &p->dl;
3253 3253
3254 init_dl_task_timer(dl_se); 3254 init_dl_task_timer(dl_se);
3255 dl_se->dl_runtime = attr->sched_runtime; 3255 dl_se->dl_runtime = attr->sched_runtime;
3256 dl_se->dl_deadline = attr->sched_deadline; 3256 dl_se->dl_deadline = attr->sched_deadline;
3257 dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline; 3257 dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
3258 dl_se->flags = attr->sched_flags; 3258 dl_se->flags = attr->sched_flags;
3259 dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime); 3259 dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
3260 dl_se->dl_throttled = 0; 3260 dl_se->dl_throttled = 0;
3261 dl_se->dl_new = 1; 3261 dl_se->dl_new = 1;
3262 dl_se->dl_yielded = 0; 3262 dl_se->dl_yielded = 0;
3263 } 3263 }
3264 3264
3265 /* 3265 /*
3266 * sched_setparam() passes in -1 for its policy, to let the functions 3266 * sched_setparam() passes in -1 for its policy, to let the functions
3267 * it calls know not to change it. 3267 * it calls know not to change it.
3268 */ 3268 */
3269 #define SETPARAM_POLICY -1 3269 #define SETPARAM_POLICY -1
3270 3270
3271 static void __setscheduler_params(struct task_struct *p, 3271 static void __setscheduler_params(struct task_struct *p,
3272 const struct sched_attr *attr) 3272 const struct sched_attr *attr)
3273 { 3273 {
3274 int policy = attr->sched_policy; 3274 int policy = attr->sched_policy;
3275 3275
3276 if (policy == SETPARAM_POLICY) 3276 if (policy == SETPARAM_POLICY)
3277 policy = p->policy; 3277 policy = p->policy;
3278 3278
3279 p->policy = policy; 3279 p->policy = policy;
3280 3280
3281 if (dl_policy(policy)) 3281 if (dl_policy(policy))
3282 __setparam_dl(p, attr); 3282 __setparam_dl(p, attr);
3283 else if (fair_policy(policy)) 3283 else if (fair_policy(policy))
3284 p->static_prio = NICE_TO_PRIO(attr->sched_nice); 3284 p->static_prio = NICE_TO_PRIO(attr->sched_nice);
3285 3285
3286 /* 3286 /*
3287 * __sched_setscheduler() ensures attr->sched_priority == 0 when 3287 * __sched_setscheduler() ensures attr->sched_priority == 0 when
3288 * !rt_policy. Always setting this ensures that things like 3288 * !rt_policy. Always setting this ensures that things like
3289 * getparam()/getattr() don't report silly values for !rt tasks. 3289 * getparam()/getattr() don't report silly values for !rt tasks.
3290 */ 3290 */
3291 p->rt_priority = attr->sched_priority; 3291 p->rt_priority = attr->sched_priority;
3292 p->normal_prio = normal_prio(p); 3292 p->normal_prio = normal_prio(p);
3293 set_load_weight(p); 3293 set_load_weight(p);
3294 } 3294 }
3295 3295
3296 /* Actually do priority change: must hold pi & rq lock. */ 3296 /* Actually do priority change: must hold pi & rq lock. */
3297 static void __setscheduler(struct rq *rq, struct task_struct *p, 3297 static void __setscheduler(struct rq *rq, struct task_struct *p,
3298 const struct sched_attr *attr) 3298 const struct sched_attr *attr)
3299 { 3299 {
3300 __setscheduler_params(p, attr); 3300 __setscheduler_params(p, attr);
3301 3301
3302 /* 3302 /*
3303 * If we get here, there was no pi waiters boosting the 3303 * If we get here, there was no pi waiters boosting the
3304 * task. It is safe to use the normal prio. 3304 * task. It is safe to use the normal prio.
3305 */ 3305 */
3306 p->prio = normal_prio(p); 3306 p->prio = normal_prio(p);
3307 3307
3308 if (dl_prio(p->prio)) 3308 if (dl_prio(p->prio))
3309 p->sched_class = &dl_sched_class; 3309 p->sched_class = &dl_sched_class;
3310 else if (rt_prio(p->prio)) 3310 else if (rt_prio(p->prio))
3311 p->sched_class = &rt_sched_class; 3311 p->sched_class = &rt_sched_class;
3312 else 3312 else
3313 p->sched_class = &fair_sched_class; 3313 p->sched_class = &fair_sched_class;
3314 } 3314 }
3315 3315
3316 static void 3316 static void
3317 __getparam_dl(struct task_struct *p, struct sched_attr *attr) 3317 __getparam_dl(struct task_struct *p, struct sched_attr *attr)
3318 { 3318 {
3319 struct sched_dl_entity *dl_se = &p->dl; 3319 struct sched_dl_entity *dl_se = &p->dl;
3320 3320
3321 attr->sched_priority = p->rt_priority; 3321 attr->sched_priority = p->rt_priority;
3322 attr->sched_runtime = dl_se->dl_runtime; 3322 attr->sched_runtime = dl_se->dl_runtime;
3323 attr->sched_deadline = dl_se->dl_deadline; 3323 attr->sched_deadline = dl_se->dl_deadline;
3324 attr->sched_period = dl_se->dl_period; 3324 attr->sched_period = dl_se->dl_period;
3325 attr->sched_flags = dl_se->flags; 3325 attr->sched_flags = dl_se->flags;
3326 } 3326 }
3327 3327
3328 /* 3328 /*
3329 * This function validates the new parameters of a -deadline task. 3329 * This function validates the new parameters of a -deadline task.
3330 * We ask for the deadline not being zero, and greater or equal 3330 * We ask for the deadline not being zero, and greater or equal
3331 * than the runtime, as well as the period of being zero or 3331 * than the runtime, as well as the period of being zero or
3332 * greater than deadline. Furthermore, we have to be sure that 3332 * greater than deadline. Furthermore, we have to be sure that
3333 * user parameters are above the internal resolution of 1us (we 3333 * user parameters are above the internal resolution of 1us (we
3334 * check sched_runtime only since it is always the smaller one) and 3334 * check sched_runtime only since it is always the smaller one) and
3335 * below 2^63 ns (we have to check both sched_deadline and 3335 * below 2^63 ns (we have to check both sched_deadline and
3336 * sched_period, as the latter can be zero). 3336 * sched_period, as the latter can be zero).
3337 */ 3337 */
3338 static bool 3338 static bool
3339 __checkparam_dl(const struct sched_attr *attr) 3339 __checkparam_dl(const struct sched_attr *attr)
3340 { 3340 {
3341 /* deadline != 0 */ 3341 /* deadline != 0 */
3342 if (attr->sched_deadline == 0) 3342 if (attr->sched_deadline == 0)
3343 return false; 3343 return false;
3344 3344
3345 /* 3345 /*
3346 * Since we truncate DL_SCALE bits, make sure we're at least 3346 * Since we truncate DL_SCALE bits, make sure we're at least
3347 * that big. 3347 * that big.
3348 */ 3348 */
3349 if (attr->sched_runtime < (1ULL << DL_SCALE)) 3349 if (attr->sched_runtime < (1ULL << DL_SCALE))
3350 return false; 3350 return false;
3351 3351
3352 /* 3352 /*
3353 * Since we use the MSB for wrap-around and sign issues, make 3353 * Since we use the MSB for wrap-around and sign issues, make
3354 * sure it's not set (mind that period can be equal to zero). 3354 * sure it's not set (mind that period can be equal to zero).
3355 */ 3355 */
3356 if (attr->sched_deadline & (1ULL << 63) || 3356 if (attr->sched_deadline & (1ULL << 63) ||
3357 attr->sched_period & (1ULL << 63)) 3357 attr->sched_period & (1ULL << 63))
3358 return false; 3358 return false;
3359 3359
3360 /* runtime <= deadline <= period (if period != 0) */ 3360 /* runtime <= deadline <= period (if period != 0) */
3361 if ((attr->sched_period != 0 && 3361 if ((attr->sched_period != 0 &&
3362 attr->sched_period < attr->sched_deadline) || 3362 attr->sched_period < attr->sched_deadline) ||
3363 attr->sched_deadline < attr->sched_runtime) 3363 attr->sched_deadline < attr->sched_runtime)
3364 return false; 3364 return false;
3365 3365
3366 return true; 3366 return true;
3367 } 3367 }
3368 3368
3369 /* 3369 /*
3370 * check the target process has a UID that matches the current process's 3370 * check the target process has a UID that matches the current process's
3371 */ 3371 */
3372 static bool check_same_owner(struct task_struct *p) 3372 static bool check_same_owner(struct task_struct *p)
3373 { 3373 {
3374 const struct cred *cred = current_cred(), *pcred; 3374 const struct cred *cred = current_cred(), *pcred;
3375 bool match; 3375 bool match;
3376 3376
3377 rcu_read_lock(); 3377 rcu_read_lock();
3378 pcred = __task_cred(p); 3378 pcred = __task_cred(p);
3379 match = (uid_eq(cred->euid, pcred->euid) || 3379 match = (uid_eq(cred->euid, pcred->euid) ||
3380 uid_eq(cred->euid, pcred->uid)); 3380 uid_eq(cred->euid, pcred->uid));
3381 rcu_read_unlock(); 3381 rcu_read_unlock();
3382 return match; 3382 return match;
3383 } 3383 }
3384 3384
3385 static int __sched_setscheduler(struct task_struct *p, 3385 static int __sched_setscheduler(struct task_struct *p,
3386 const struct sched_attr *attr, 3386 const struct sched_attr *attr,
3387 bool user) 3387 bool user)
3388 { 3388 {
3389 int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 : 3389 int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
3390 MAX_RT_PRIO - 1 - attr->sched_priority; 3390 MAX_RT_PRIO - 1 - attr->sched_priority;
3391 int retval, oldprio, oldpolicy = -1, queued, running; 3391 int retval, oldprio, oldpolicy = -1, queued, running;
3392 int policy = attr->sched_policy; 3392 int policy = attr->sched_policy;
3393 unsigned long flags; 3393 unsigned long flags;
3394 const struct sched_class *prev_class; 3394 const struct sched_class *prev_class;
3395 struct rq *rq; 3395 struct rq *rq;
3396 int reset_on_fork; 3396 int reset_on_fork;
3397 3397
3398 /* may grab non-irq protected spin_locks */ 3398 /* may grab non-irq protected spin_locks */
3399 BUG_ON(in_interrupt()); 3399 BUG_ON(in_interrupt());
3400 recheck: 3400 recheck:
3401 /* double check policy once rq lock held */ 3401 /* double check policy once rq lock held */
3402 if (policy < 0) { 3402 if (policy < 0) {
3403 reset_on_fork = p->sched_reset_on_fork; 3403 reset_on_fork = p->sched_reset_on_fork;
3404 policy = oldpolicy = p->policy; 3404 policy = oldpolicy = p->policy;
3405 } else { 3405 } else {
3406 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK); 3406 reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
3407 3407
3408 if (policy != SCHED_DEADLINE && 3408 if (policy != SCHED_DEADLINE &&
3409 policy != SCHED_FIFO && policy != SCHED_RR && 3409 policy != SCHED_FIFO && policy != SCHED_RR &&
3410 policy != SCHED_NORMAL && policy != SCHED_BATCH && 3410 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
3411 policy != SCHED_IDLE) 3411 policy != SCHED_IDLE)
3412 return -EINVAL; 3412 return -EINVAL;
3413 } 3413 }
3414 3414
3415 if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK)) 3415 if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK))
3416 return -EINVAL; 3416 return -EINVAL;
3417 3417
3418 /* 3418 /*
3419 * Valid priorities for SCHED_FIFO and SCHED_RR are 3419 * Valid priorities for SCHED_FIFO and SCHED_RR are
3420 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL, 3420 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
3421 * SCHED_BATCH and SCHED_IDLE is 0. 3421 * SCHED_BATCH and SCHED_IDLE is 0.
3422 */ 3422 */
3423 if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) || 3423 if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
3424 (!p->mm && attr->sched_priority > MAX_RT_PRIO-1)) 3424 (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
3425 return -EINVAL; 3425 return -EINVAL;
3426 if ((dl_policy(policy) && !__checkparam_dl(attr)) || 3426 if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
3427 (rt_policy(policy) != (attr->sched_priority != 0))) 3427 (rt_policy(policy) != (attr->sched_priority != 0)))
3428 return -EINVAL; 3428 return -EINVAL;
3429 3429
3430 /* 3430 /*
3431 * Allow unprivileged RT tasks to decrease priority: 3431 * Allow unprivileged RT tasks to decrease priority:
3432 */ 3432 */
3433 if (user && !capable(CAP_SYS_NICE)) { 3433 if (user && !capable(CAP_SYS_NICE)) {
3434 if (fair_policy(policy)) { 3434 if (fair_policy(policy)) {
3435 if (attr->sched_nice < task_nice(p) && 3435 if (attr->sched_nice < task_nice(p) &&
3436 !can_nice(p, attr->sched_nice)) 3436 !can_nice(p, attr->sched_nice))
3437 return -EPERM; 3437 return -EPERM;
3438 } 3438 }
3439 3439
3440 if (rt_policy(policy)) { 3440 if (rt_policy(policy)) {
3441 unsigned long rlim_rtprio = 3441 unsigned long rlim_rtprio =
3442 task_rlimit(p, RLIMIT_RTPRIO); 3442 task_rlimit(p, RLIMIT_RTPRIO);
3443 3443
3444 /* can't set/change the rt policy */ 3444 /* can't set/change the rt policy */
3445 if (policy != p->policy && !rlim_rtprio) 3445 if (policy != p->policy && !rlim_rtprio)
3446 return -EPERM; 3446 return -EPERM;
3447 3447
3448 /* can't increase priority */ 3448 /* can't increase priority */
3449 if (attr->sched_priority > p->rt_priority && 3449 if (attr->sched_priority > p->rt_priority &&
3450 attr->sched_priority > rlim_rtprio) 3450 attr->sched_priority > rlim_rtprio)
3451 return -EPERM; 3451 return -EPERM;
3452 } 3452 }
3453 3453
3454 /* 3454 /*
3455 * Can't set/change SCHED_DEADLINE policy at all for now 3455 * Can't set/change SCHED_DEADLINE policy at all for now
3456 * (safest behavior); in the future we would like to allow 3456 * (safest behavior); in the future we would like to allow
3457 * unprivileged DL tasks to increase their relative deadline 3457 * unprivileged DL tasks to increase their relative deadline
3458 * or reduce their runtime (both ways reducing utilization) 3458 * or reduce their runtime (both ways reducing utilization)
3459 */ 3459 */
3460 if (dl_policy(policy)) 3460 if (dl_policy(policy))
3461 return -EPERM; 3461 return -EPERM;
3462 3462
3463 /* 3463 /*
3464 * Treat SCHED_IDLE as nice 20. Only allow a switch to 3464 * Treat SCHED_IDLE as nice 20. Only allow a switch to
3465 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it. 3465 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
3466 */ 3466 */
3467 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) { 3467 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) {
3468 if (!can_nice(p, task_nice(p))) 3468 if (!can_nice(p, task_nice(p)))
3469 return -EPERM; 3469 return -EPERM;
3470 } 3470 }
3471 3471
3472 /* can't change other user's priorities */ 3472 /* can't change other user's priorities */
3473 if (!check_same_owner(p)) 3473 if (!check_same_owner(p))
3474 return -EPERM; 3474 return -EPERM;
3475 3475
3476 /* Normal users shall not reset the sched_reset_on_fork flag */ 3476 /* Normal users shall not reset the sched_reset_on_fork flag */
3477 if (p->sched_reset_on_fork && !reset_on_fork) 3477 if (p->sched_reset_on_fork && !reset_on_fork)
3478 return -EPERM; 3478 return -EPERM;
3479 } 3479 }
3480 3480
3481 if (user) { 3481 if (user) {
3482 retval = security_task_setscheduler(p); 3482 retval = security_task_setscheduler(p);
3483 if (retval) 3483 if (retval)
3484 return retval; 3484 return retval;
3485 } 3485 }
3486 3486
3487 /* 3487 /*
3488 * make sure no PI-waiters arrive (or leave) while we are 3488 * make sure no PI-waiters arrive (or leave) while we are
3489 * changing the priority of the task: 3489 * changing the priority of the task:
3490 * 3490 *
3491 * To be able to change p->policy safely, the appropriate 3491 * To be able to change p->policy safely, the appropriate
3492 * runqueue lock must be held. 3492 * runqueue lock must be held.
3493 */ 3493 */
3494 rq = task_rq_lock(p, &flags); 3494 rq = task_rq_lock(p, &flags);
3495 3495
3496 /* 3496 /*
3497 * Changing the policy of the stop threads its a very bad idea 3497 * Changing the policy of the stop threads its a very bad idea
3498 */ 3498 */
3499 if (p == rq->stop) { 3499 if (p == rq->stop) {
3500 task_rq_unlock(rq, p, &flags); 3500 task_rq_unlock(rq, p, &flags);
3501 return -EINVAL; 3501 return -EINVAL;
3502 } 3502 }
3503 3503
3504 /* 3504 /*
3505 * If not changing anything there's no need to proceed further, 3505 * If not changing anything there's no need to proceed further,
3506 * but store a possible modification of reset_on_fork. 3506 * but store a possible modification of reset_on_fork.
3507 */ 3507 */
3508 if (unlikely(policy == p->policy)) { 3508 if (unlikely(policy == p->policy)) {
3509 if (fair_policy(policy) && attr->sched_nice != task_nice(p)) 3509 if (fair_policy(policy) && attr->sched_nice != task_nice(p))
3510 goto change; 3510 goto change;
3511 if (rt_policy(policy) && attr->sched_priority != p->rt_priority) 3511 if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
3512 goto change; 3512 goto change;
3513 if (dl_policy(policy)) 3513 if (dl_policy(policy))
3514 goto change; 3514 goto change;
3515 3515
3516 p->sched_reset_on_fork = reset_on_fork; 3516 p->sched_reset_on_fork = reset_on_fork;
3517 task_rq_unlock(rq, p, &flags); 3517 task_rq_unlock(rq, p, &flags);
3518 return 0; 3518 return 0;
3519 } 3519 }
3520 change: 3520 change:
3521 3521
3522 if (user) { 3522 if (user) {
3523 #ifdef CONFIG_RT_GROUP_SCHED 3523 #ifdef CONFIG_RT_GROUP_SCHED
3524 /* 3524 /*
3525 * Do not allow realtime tasks into groups that have no runtime 3525 * Do not allow realtime tasks into groups that have no runtime
3526 * assigned. 3526 * assigned.
3527 */ 3527 */
3528 if (rt_bandwidth_enabled() && rt_policy(policy) && 3528 if (rt_bandwidth_enabled() && rt_policy(policy) &&
3529 task_group(p)->rt_bandwidth.rt_runtime == 0 && 3529 task_group(p)->rt_bandwidth.rt_runtime == 0 &&
3530 !task_group_is_autogroup(task_group(p))) { 3530 !task_group_is_autogroup(task_group(p))) {
3531 task_rq_unlock(rq, p, &flags); 3531 task_rq_unlock(rq, p, &flags);
3532 return -EPERM; 3532 return -EPERM;
3533 } 3533 }
3534 #endif 3534 #endif
3535 #ifdef CONFIG_SMP 3535 #ifdef CONFIG_SMP
3536 if (dl_bandwidth_enabled() && dl_policy(policy)) { 3536 if (dl_bandwidth_enabled() && dl_policy(policy)) {
3537 cpumask_t *span = rq->rd->span; 3537 cpumask_t *span = rq->rd->span;
3538 3538
3539 /* 3539 /*
3540 * Don't allow tasks with an affinity mask smaller than 3540 * Don't allow tasks with an affinity mask smaller than
3541 * the entire root_domain to become SCHED_DEADLINE. We 3541 * the entire root_domain to become SCHED_DEADLINE. We
3542 * will also fail if there's no bandwidth available. 3542 * will also fail if there's no bandwidth available.
3543 */ 3543 */
3544 if (!cpumask_subset(span, &p->cpus_allowed) || 3544 if (!cpumask_subset(span, &p->cpus_allowed) ||
3545 rq->rd->dl_bw.bw == 0) { 3545 rq->rd->dl_bw.bw == 0) {
3546 task_rq_unlock(rq, p, &flags); 3546 task_rq_unlock(rq, p, &flags);
3547 return -EPERM; 3547 return -EPERM;
3548 } 3548 }
3549 } 3549 }
3550 #endif 3550 #endif
3551 } 3551 }
3552 3552
3553 /* recheck policy now with rq lock held */ 3553 /* recheck policy now with rq lock held */
3554 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) { 3554 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3555 policy = oldpolicy = -1; 3555 policy = oldpolicy = -1;
3556 task_rq_unlock(rq, p, &flags); 3556 task_rq_unlock(rq, p, &flags);
3557 goto recheck; 3557 goto recheck;
3558 } 3558 }
3559 3559
3560 /* 3560 /*
3561 * If setscheduling to SCHED_DEADLINE (or changing the parameters 3561 * If setscheduling to SCHED_DEADLINE (or changing the parameters
3562 * of a SCHED_DEADLINE task) we need to check if enough bandwidth 3562 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
3563 * is available. 3563 * is available.
3564 */ 3564 */
3565 if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) { 3565 if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) {
3566 task_rq_unlock(rq, p, &flags); 3566 task_rq_unlock(rq, p, &flags);
3567 return -EBUSY; 3567 return -EBUSY;
3568 } 3568 }
3569 3569
3570 p->sched_reset_on_fork = reset_on_fork; 3570 p->sched_reset_on_fork = reset_on_fork;
3571 oldprio = p->prio; 3571 oldprio = p->prio;
3572 3572
3573 /* 3573 /*
3574 * Special case for priority boosted tasks. 3574 * Special case for priority boosted tasks.
3575 * 3575 *
3576 * If the new priority is lower or equal (user space view) 3576 * If the new priority is lower or equal (user space view)
3577 * than the current (boosted) priority, we just store the new 3577 * than the current (boosted) priority, we just store the new
3578 * normal parameters and do not touch the scheduler class and 3578 * normal parameters and do not touch the scheduler class and
3579 * the runqueue. This will be done when the task deboost 3579 * the runqueue. This will be done when the task deboost
3580 * itself. 3580 * itself.
3581 */ 3581 */
3582 if (rt_mutex_check_prio(p, newprio)) { 3582 if (rt_mutex_check_prio(p, newprio)) {
3583 __setscheduler_params(p, attr); 3583 __setscheduler_params(p, attr);
3584 task_rq_unlock(rq, p, &flags); 3584 task_rq_unlock(rq, p, &flags);
3585 return 0; 3585 return 0;
3586 } 3586 }
3587 3587
3588 queued = task_on_rq_queued(p); 3588 queued = task_on_rq_queued(p);
3589 running = task_current(rq, p); 3589 running = task_current(rq, p);
3590 if (queued) 3590 if (queued)
3591 dequeue_task(rq, p, 0); 3591 dequeue_task(rq, p, 0);
3592 if (running) 3592 if (running)
3593 put_prev_task(rq, p); 3593 put_prev_task(rq, p);
3594 3594
3595 prev_class = p->sched_class; 3595 prev_class = p->sched_class;
3596 __setscheduler(rq, p, attr); 3596 __setscheduler(rq, p, attr);
3597 3597
3598 if (running) 3598 if (running)
3599 p->sched_class->set_curr_task(rq); 3599 p->sched_class->set_curr_task(rq);
3600 if (queued) { 3600 if (queued) {
3601 /* 3601 /*
3602 * We enqueue to tail when the priority of a task is 3602 * We enqueue to tail when the priority of a task is
3603 * increased (user space view). 3603 * increased (user space view).
3604 */ 3604 */
3605 enqueue_task(rq, p, oldprio <= p->prio ? ENQUEUE_HEAD : 0); 3605 enqueue_task(rq, p, oldprio <= p->prio ? ENQUEUE_HEAD : 0);
3606 } 3606 }
3607 3607
3608 check_class_changed(rq, p, prev_class, oldprio); 3608 check_class_changed(rq, p, prev_class, oldprio);
3609 task_rq_unlock(rq, p, &flags); 3609 task_rq_unlock(rq, p, &flags);
3610 3610
3611 rt_mutex_adjust_pi(p); 3611 rt_mutex_adjust_pi(p);
3612 3612
3613 return 0; 3613 return 0;
3614 } 3614 }
3615 3615
3616 static int _sched_setscheduler(struct task_struct *p, int policy, 3616 static int _sched_setscheduler(struct task_struct *p, int policy,
3617 const struct sched_param *param, bool check) 3617 const struct sched_param *param, bool check)
3618 { 3618 {
3619 struct sched_attr attr = { 3619 struct sched_attr attr = {
3620 .sched_policy = policy, 3620 .sched_policy = policy,
3621 .sched_priority = param->sched_priority, 3621 .sched_priority = param->sched_priority,
3622 .sched_nice = PRIO_TO_NICE(p->static_prio), 3622 .sched_nice = PRIO_TO_NICE(p->static_prio),
3623 }; 3623 };
3624 3624
3625 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */ 3625 /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
3626 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) { 3626 if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
3627 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK; 3627 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
3628 policy &= ~SCHED_RESET_ON_FORK; 3628 policy &= ~SCHED_RESET_ON_FORK;
3629 attr.sched_policy = policy; 3629 attr.sched_policy = policy;
3630 } 3630 }
3631 3631
3632 return __sched_setscheduler(p, &attr, check); 3632 return __sched_setscheduler(p, &attr, check);
3633 } 3633 }
3634 /** 3634 /**
3635 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread. 3635 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
3636 * @p: the task in question. 3636 * @p: the task in question.
3637 * @policy: new policy. 3637 * @policy: new policy.
3638 * @param: structure containing the new RT priority. 3638 * @param: structure containing the new RT priority.
3639 * 3639 *
3640 * Return: 0 on success. An error code otherwise. 3640 * Return: 0 on success. An error code otherwise.
3641 * 3641 *
3642 * NOTE that the task may be already dead. 3642 * NOTE that the task may be already dead.
3643 */ 3643 */
3644 int sched_setscheduler(struct task_struct *p, int policy, 3644 int sched_setscheduler(struct task_struct *p, int policy,
3645 const struct sched_param *param) 3645 const struct sched_param *param)
3646 { 3646 {
3647 return _sched_setscheduler(p, policy, param, true); 3647 return _sched_setscheduler(p, policy, param, true);
3648 } 3648 }
3649 EXPORT_SYMBOL_GPL(sched_setscheduler); 3649 EXPORT_SYMBOL_GPL(sched_setscheduler);
3650 3650
3651 int sched_setattr(struct task_struct *p, const struct sched_attr *attr) 3651 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
3652 { 3652 {
3653 return __sched_setscheduler(p, attr, true); 3653 return __sched_setscheduler(p, attr, true);
3654 } 3654 }
3655 EXPORT_SYMBOL_GPL(sched_setattr); 3655 EXPORT_SYMBOL_GPL(sched_setattr);
3656 3656
3657 /** 3657 /**
3658 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace. 3658 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
3659 * @p: the task in question. 3659 * @p: the task in question.
3660 * @policy: new policy. 3660 * @policy: new policy.
3661 * @param: structure containing the new RT priority. 3661 * @param: structure containing the new RT priority.
3662 * 3662 *
3663 * Just like sched_setscheduler, only don't bother checking if the 3663 * Just like sched_setscheduler, only don't bother checking if the
3664 * current context has permission. For example, this is needed in 3664 * current context has permission. For example, this is needed in
3665 * stop_machine(): we create temporary high priority worker threads, 3665 * stop_machine(): we create temporary high priority worker threads,
3666 * but our caller might not have that capability. 3666 * but our caller might not have that capability.
3667 * 3667 *
3668 * Return: 0 on success. An error code otherwise. 3668 * Return: 0 on success. An error code otherwise.
3669 */ 3669 */
3670 int sched_setscheduler_nocheck(struct task_struct *p, int policy, 3670 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
3671 const struct sched_param *param) 3671 const struct sched_param *param)
3672 { 3672 {
3673 return _sched_setscheduler(p, policy, param, false); 3673 return _sched_setscheduler(p, policy, param, false);
3674 } 3674 }
3675 3675
3676 static int 3676 static int
3677 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param) 3677 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3678 { 3678 {
3679 struct sched_param lparam; 3679 struct sched_param lparam;
3680 struct task_struct *p; 3680 struct task_struct *p;
3681 int retval; 3681 int retval;
3682 3682
3683 if (!param || pid < 0) 3683 if (!param || pid < 0)
3684 return -EINVAL; 3684 return -EINVAL;
3685 if (copy_from_user(&lparam, param, sizeof(struct sched_param))) 3685 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
3686 return -EFAULT; 3686 return -EFAULT;
3687 3687
3688 rcu_read_lock(); 3688 rcu_read_lock();
3689 retval = -ESRCH; 3689 retval = -ESRCH;
3690 p = find_process_by_pid(pid); 3690 p = find_process_by_pid(pid);
3691 if (p != NULL) 3691 if (p != NULL)
3692 retval = sched_setscheduler(p, policy, &lparam); 3692 retval = sched_setscheduler(p, policy, &lparam);
3693 rcu_read_unlock(); 3693 rcu_read_unlock();
3694 3694
3695 return retval; 3695 return retval;
3696 } 3696 }
3697 3697
3698 /* 3698 /*
3699 * Mimics kernel/events/core.c perf_copy_attr(). 3699 * Mimics kernel/events/core.c perf_copy_attr().
3700 */ 3700 */
3701 static int sched_copy_attr(struct sched_attr __user *uattr, 3701 static int sched_copy_attr(struct sched_attr __user *uattr,
3702 struct sched_attr *attr) 3702 struct sched_attr *attr)
3703 { 3703 {
3704 u32 size; 3704 u32 size;
3705 int ret; 3705 int ret;
3706 3706
3707 if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0)) 3707 if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
3708 return -EFAULT; 3708 return -EFAULT;
3709 3709
3710 /* 3710 /*
3711 * zero the full structure, so that a short copy will be nice. 3711 * zero the full structure, so that a short copy will be nice.
3712 */ 3712 */
3713 memset(attr, 0, sizeof(*attr)); 3713 memset(attr, 0, sizeof(*attr));
3714 3714
3715 ret = get_user(size, &uattr->size); 3715 ret = get_user(size, &uattr->size);
3716 if (ret) 3716 if (ret)
3717 return ret; 3717 return ret;
3718 3718
3719 if (size > PAGE_SIZE) /* silly large */ 3719 if (size > PAGE_SIZE) /* silly large */
3720 goto err_size; 3720 goto err_size;
3721 3721
3722 if (!size) /* abi compat */ 3722 if (!size) /* abi compat */
3723 size = SCHED_ATTR_SIZE_VER0; 3723 size = SCHED_ATTR_SIZE_VER0;
3724 3724
3725 if (size < SCHED_ATTR_SIZE_VER0) 3725 if (size < SCHED_ATTR_SIZE_VER0)
3726 goto err_size; 3726 goto err_size;
3727 3727
3728 /* 3728 /*
3729 * If we're handed a bigger struct than we know of, 3729 * If we're handed a bigger struct than we know of,
3730 * ensure all the unknown bits are 0 - i.e. new 3730 * ensure all the unknown bits are 0 - i.e. new
3731 * user-space does not rely on any kernel feature 3731 * user-space does not rely on any kernel feature
3732 * extensions we dont know about yet. 3732 * extensions we dont know about yet.
3733 */ 3733 */
3734 if (size > sizeof(*attr)) { 3734 if (size > sizeof(*attr)) {
3735 unsigned char __user *addr; 3735 unsigned char __user *addr;
3736 unsigned char __user *end; 3736 unsigned char __user *end;
3737 unsigned char val; 3737 unsigned char val;
3738 3738
3739 addr = (void __user *)uattr + sizeof(*attr); 3739 addr = (void __user *)uattr + sizeof(*attr);
3740 end = (void __user *)uattr + size; 3740 end = (void __user *)uattr + size;
3741 3741
3742 for (; addr < end; addr++) { 3742 for (; addr < end; addr++) {
3743 ret = get_user(val, addr); 3743 ret = get_user(val, addr);
3744 if (ret) 3744 if (ret)
3745 return ret; 3745 return ret;
3746 if (val) 3746 if (val)
3747 goto err_size; 3747 goto err_size;
3748 } 3748 }
3749 size = sizeof(*attr); 3749 size = sizeof(*attr);
3750 } 3750 }
3751 3751
3752 ret = copy_from_user(attr, uattr, size); 3752 ret = copy_from_user(attr, uattr, size);
3753 if (ret) 3753 if (ret)
3754 return -EFAULT; 3754 return -EFAULT;
3755 3755
3756 /* 3756 /*
3757 * XXX: do we want to be lenient like existing syscalls; or do we want 3757 * XXX: do we want to be lenient like existing syscalls; or do we want
3758 * to be strict and return an error on out-of-bounds values? 3758 * to be strict and return an error on out-of-bounds values?
3759 */ 3759 */
3760 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE); 3760 attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
3761 3761
3762 return 0; 3762 return 0;
3763 3763
3764 err_size: 3764 err_size:
3765 put_user(sizeof(*attr), &uattr->size); 3765 put_user(sizeof(*attr), &uattr->size);
3766 return -E2BIG; 3766 return -E2BIG;
3767 } 3767 }
3768 3768
3769 /** 3769 /**
3770 * sys_sched_setscheduler - set/change the scheduler policy and RT priority 3770 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3771 * @pid: the pid in question. 3771 * @pid: the pid in question.
3772 * @policy: new policy. 3772 * @policy: new policy.
3773 * @param: structure containing the new RT priority. 3773 * @param: structure containing the new RT priority.
3774 * 3774 *
3775 * Return: 0 on success. An error code otherwise. 3775 * Return: 0 on success. An error code otherwise.
3776 */ 3776 */
3777 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, 3777 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
3778 struct sched_param __user *, param) 3778 struct sched_param __user *, param)
3779 { 3779 {
3780 /* negative values for policy are not valid */ 3780 /* negative values for policy are not valid */
3781 if (policy < 0) 3781 if (policy < 0)
3782 return -EINVAL; 3782 return -EINVAL;
3783 3783
3784 return do_sched_setscheduler(pid, policy, param); 3784 return do_sched_setscheduler(pid, policy, param);
3785 } 3785 }
3786 3786
3787 /** 3787 /**
3788 * sys_sched_setparam - set/change the RT priority of a thread 3788 * sys_sched_setparam - set/change the RT priority of a thread
3789 * @pid: the pid in question. 3789 * @pid: the pid in question.
3790 * @param: structure containing the new RT priority. 3790 * @param: structure containing the new RT priority.
3791 * 3791 *
3792 * Return: 0 on success. An error code otherwise. 3792 * Return: 0 on success. An error code otherwise.
3793 */ 3793 */
3794 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param) 3794 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
3795 { 3795 {
3796 return do_sched_setscheduler(pid, SETPARAM_POLICY, param); 3796 return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
3797 } 3797 }
3798 3798
3799 /** 3799 /**
3800 * sys_sched_setattr - same as above, but with extended sched_attr 3800 * sys_sched_setattr - same as above, but with extended sched_attr
3801 * @pid: the pid in question. 3801 * @pid: the pid in question.
3802 * @uattr: structure containing the extended parameters. 3802 * @uattr: structure containing the extended parameters.
3803 * @flags: for future extension. 3803 * @flags: for future extension.
3804 */ 3804 */
3805 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr, 3805 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
3806 unsigned int, flags) 3806 unsigned int, flags)
3807 { 3807 {
3808 struct sched_attr attr; 3808 struct sched_attr attr;
3809 struct task_struct *p; 3809 struct task_struct *p;
3810 int retval; 3810 int retval;
3811 3811
3812 if (!uattr || pid < 0 || flags) 3812 if (!uattr || pid < 0 || flags)
3813 return -EINVAL; 3813 return -EINVAL;
3814 3814
3815 retval = sched_copy_attr(uattr, &attr); 3815 retval = sched_copy_attr(uattr, &attr);
3816 if (retval) 3816 if (retval)
3817 return retval; 3817 return retval;
3818 3818
3819 if ((int)attr.sched_policy < 0) 3819 if ((int)attr.sched_policy < 0)
3820 return -EINVAL; 3820 return -EINVAL;
3821 3821
3822 rcu_read_lock(); 3822 rcu_read_lock();
3823 retval = -ESRCH; 3823 retval = -ESRCH;
3824 p = find_process_by_pid(pid); 3824 p = find_process_by_pid(pid);
3825 if (p != NULL) 3825 if (p != NULL)
3826 retval = sched_setattr(p, &attr); 3826 retval = sched_setattr(p, &attr);
3827 rcu_read_unlock(); 3827 rcu_read_unlock();
3828 3828
3829 return retval; 3829 return retval;
3830 } 3830 }
3831 3831
3832 /** 3832 /**
3833 * sys_sched_getscheduler - get the policy (scheduling class) of a thread 3833 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3834 * @pid: the pid in question. 3834 * @pid: the pid in question.
3835 * 3835 *
3836 * Return: On success, the policy of the thread. Otherwise, a negative error 3836 * Return: On success, the policy of the thread. Otherwise, a negative error
3837 * code. 3837 * code.
3838 */ 3838 */
3839 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid) 3839 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
3840 { 3840 {
3841 struct task_struct *p; 3841 struct task_struct *p;
3842 int retval; 3842 int retval;
3843 3843
3844 if (pid < 0) 3844 if (pid < 0)
3845 return -EINVAL; 3845 return -EINVAL;
3846 3846
3847 retval = -ESRCH; 3847 retval = -ESRCH;
3848 rcu_read_lock(); 3848 rcu_read_lock();
3849 p = find_process_by_pid(pid); 3849 p = find_process_by_pid(pid);
3850 if (p) { 3850 if (p) {
3851 retval = security_task_getscheduler(p); 3851 retval = security_task_getscheduler(p);
3852 if (!retval) 3852 if (!retval)
3853 retval = p->policy 3853 retval = p->policy
3854 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0); 3854 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
3855 } 3855 }
3856 rcu_read_unlock(); 3856 rcu_read_unlock();
3857 return retval; 3857 return retval;
3858 } 3858 }
3859 3859
3860 /** 3860 /**
3861 * sys_sched_getparam - get the RT priority of a thread 3861 * sys_sched_getparam - get the RT priority of a thread
3862 * @pid: the pid in question. 3862 * @pid: the pid in question.
3863 * @param: structure containing the RT priority. 3863 * @param: structure containing the RT priority.
3864 * 3864 *
3865 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error 3865 * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
3866 * code. 3866 * code.
3867 */ 3867 */
3868 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param) 3868 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
3869 { 3869 {
3870 struct sched_param lp = { .sched_priority = 0 }; 3870 struct sched_param lp = { .sched_priority = 0 };
3871 struct task_struct *p; 3871 struct task_struct *p;
3872 int retval; 3872 int retval;
3873 3873
3874 if (!param || pid < 0) 3874 if (!param || pid < 0)
3875 return -EINVAL; 3875 return -EINVAL;
3876 3876
3877 rcu_read_lock(); 3877 rcu_read_lock();
3878 p = find_process_by_pid(pid); 3878 p = find_process_by_pid(pid);
3879 retval = -ESRCH; 3879 retval = -ESRCH;
3880 if (!p) 3880 if (!p)
3881 goto out_unlock; 3881 goto out_unlock;
3882 3882
3883 retval = security_task_getscheduler(p); 3883 retval = security_task_getscheduler(p);
3884 if (retval) 3884 if (retval)
3885 goto out_unlock; 3885 goto out_unlock;
3886 3886
3887 if (task_has_rt_policy(p)) 3887 if (task_has_rt_policy(p))
3888 lp.sched_priority = p->rt_priority; 3888 lp.sched_priority = p->rt_priority;
3889 rcu_read_unlock(); 3889 rcu_read_unlock();
3890 3890
3891 /* 3891 /*
3892 * This one might sleep, we cannot do it with a spinlock held ... 3892 * This one might sleep, we cannot do it with a spinlock held ...
3893 */ 3893 */
3894 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0; 3894 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3895 3895
3896 return retval; 3896 return retval;
3897 3897
3898 out_unlock: 3898 out_unlock:
3899 rcu_read_unlock(); 3899 rcu_read_unlock();
3900 return retval; 3900 return retval;
3901 } 3901 }
3902 3902
3903 static int sched_read_attr(struct sched_attr __user *uattr, 3903 static int sched_read_attr(struct sched_attr __user *uattr,
3904 struct sched_attr *attr, 3904 struct sched_attr *attr,
3905 unsigned int usize) 3905 unsigned int usize)
3906 { 3906 {
3907 int ret; 3907 int ret;
3908 3908
3909 if (!access_ok(VERIFY_WRITE, uattr, usize)) 3909 if (!access_ok(VERIFY_WRITE, uattr, usize))
3910 return -EFAULT; 3910 return -EFAULT;
3911 3911
3912 /* 3912 /*
3913 * If we're handed a smaller struct than we know of, 3913 * If we're handed a smaller struct than we know of,
3914 * ensure all the unknown bits are 0 - i.e. old 3914 * ensure all the unknown bits are 0 - i.e. old
3915 * user-space does not get uncomplete information. 3915 * user-space does not get uncomplete information.
3916 */ 3916 */
3917 if (usize < sizeof(*attr)) { 3917 if (usize < sizeof(*attr)) {
3918 unsigned char *addr; 3918 unsigned char *addr;
3919 unsigned char *end; 3919 unsigned char *end;
3920 3920
3921 addr = (void *)attr + usize; 3921 addr = (void *)attr + usize;
3922 end = (void *)attr + sizeof(*attr); 3922 end = (void *)attr + sizeof(*attr);
3923 3923
3924 for (; addr < end; addr++) { 3924 for (; addr < end; addr++) {
3925 if (*addr) 3925 if (*addr)
3926 return -EFBIG; 3926 return -EFBIG;
3927 } 3927 }
3928 3928
3929 attr->size = usize; 3929 attr->size = usize;
3930 } 3930 }
3931 3931
3932 ret = copy_to_user(uattr, attr, attr->size); 3932 ret = copy_to_user(uattr, attr, attr->size);
3933 if (ret) 3933 if (ret)
3934 return -EFAULT; 3934 return -EFAULT;
3935 3935
3936 return 0; 3936 return 0;
3937 } 3937 }
3938 3938
3939 /** 3939 /**
3940 * sys_sched_getattr - similar to sched_getparam, but with sched_attr 3940 * sys_sched_getattr - similar to sched_getparam, but with sched_attr
3941 * @pid: the pid in question. 3941 * @pid: the pid in question.
3942 * @uattr: structure containing the extended parameters. 3942 * @uattr: structure containing the extended parameters.
3943 * @size: sizeof(attr) for fwd/bwd comp. 3943 * @size: sizeof(attr) for fwd/bwd comp.
3944 * @flags: for future extension. 3944 * @flags: for future extension.
3945 */ 3945 */
3946 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr, 3946 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
3947 unsigned int, size, unsigned int, flags) 3947 unsigned int, size, unsigned int, flags)
3948 { 3948 {
3949 struct sched_attr attr = { 3949 struct sched_attr attr = {
3950 .size = sizeof(struct sched_attr), 3950 .size = sizeof(struct sched_attr),
3951 }; 3951 };
3952 struct task_struct *p; 3952 struct task_struct *p;
3953 int retval; 3953 int retval;
3954 3954
3955 if (!uattr || pid < 0 || size > PAGE_SIZE || 3955 if (!uattr || pid < 0 || size > PAGE_SIZE ||
3956 size < SCHED_ATTR_SIZE_VER0 || flags) 3956 size < SCHED_ATTR_SIZE_VER0 || flags)
3957 return -EINVAL; 3957 return -EINVAL;
3958 3958
3959 rcu_read_lock(); 3959 rcu_read_lock();
3960 p = find_process_by_pid(pid); 3960 p = find_process_by_pid(pid);
3961 retval = -ESRCH; 3961 retval = -ESRCH;
3962 if (!p) 3962 if (!p)
3963 goto out_unlock; 3963 goto out_unlock;
3964 3964
3965 retval = security_task_getscheduler(p); 3965 retval = security_task_getscheduler(p);
3966 if (retval) 3966 if (retval)
3967 goto out_unlock; 3967 goto out_unlock;
3968 3968
3969 attr.sched_policy = p->policy; 3969 attr.sched_policy = p->policy;
3970 if (p->sched_reset_on_fork) 3970 if (p->sched_reset_on_fork)
3971 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK; 3971 attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
3972 if (task_has_dl_policy(p)) 3972 if (task_has_dl_policy(p))
3973 __getparam_dl(p, &attr); 3973 __getparam_dl(p, &attr);
3974 else if (task_has_rt_policy(p)) 3974 else if (task_has_rt_policy(p))
3975 attr.sched_priority = p->rt_priority; 3975 attr.sched_priority = p->rt_priority;
3976 else 3976 else
3977 attr.sched_nice = task_nice(p); 3977 attr.sched_nice = task_nice(p);
3978 3978
3979 rcu_read_unlock(); 3979 rcu_read_unlock();
3980 3980
3981 retval = sched_read_attr(uattr, &attr, size); 3981 retval = sched_read_attr(uattr, &attr, size);
3982 return retval; 3982 return retval;
3983 3983
3984 out_unlock: 3984 out_unlock:
3985 rcu_read_unlock(); 3985 rcu_read_unlock();
3986 return retval; 3986 return retval;
3987 } 3987 }
3988 3988
3989 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask) 3989 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
3990 { 3990 {
3991 cpumask_var_t cpus_allowed, new_mask; 3991 cpumask_var_t cpus_allowed, new_mask;
3992 struct task_struct *p; 3992 struct task_struct *p;
3993 int retval; 3993 int retval;
3994 3994
3995 rcu_read_lock(); 3995 rcu_read_lock();
3996 3996
3997 p = find_process_by_pid(pid); 3997 p = find_process_by_pid(pid);
3998 if (!p) { 3998 if (!p) {
3999 rcu_read_unlock(); 3999 rcu_read_unlock();
4000 return -ESRCH; 4000 return -ESRCH;
4001 } 4001 }
4002 4002
4003 /* Prevent p going away */ 4003 /* Prevent p going away */
4004 get_task_struct(p); 4004 get_task_struct(p);
4005 rcu_read_unlock(); 4005 rcu_read_unlock();
4006 4006
4007 if (p->flags & PF_NO_SETAFFINITY) { 4007 if (p->flags & PF_NO_SETAFFINITY) {
4008 retval = -EINVAL; 4008 retval = -EINVAL;
4009 goto out_put_task; 4009 goto out_put_task;
4010 } 4010 }
4011 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) { 4011 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4012 retval = -ENOMEM; 4012 retval = -ENOMEM;
4013 goto out_put_task; 4013 goto out_put_task;
4014 } 4014 }
4015 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) { 4015 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4016 retval = -ENOMEM; 4016 retval = -ENOMEM;
4017 goto out_free_cpus_allowed; 4017 goto out_free_cpus_allowed;
4018 } 4018 }
4019 retval = -EPERM; 4019 retval = -EPERM;
4020 if (!check_same_owner(p)) { 4020 if (!check_same_owner(p)) {
4021 rcu_read_lock(); 4021 rcu_read_lock();
4022 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) { 4022 if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4023 rcu_read_unlock(); 4023 rcu_read_unlock();
4024 goto out_free_new_mask; 4024 goto out_free_new_mask;
4025 } 4025 }
4026 rcu_read_unlock(); 4026 rcu_read_unlock();
4027 } 4027 }
4028 4028
4029 retval = security_task_setscheduler(p); 4029 retval = security_task_setscheduler(p);
4030 if (retval) 4030 if (retval)
4031 goto out_free_new_mask; 4031 goto out_free_new_mask;
4032 4032
4033 4033
4034 cpuset_cpus_allowed(p, cpus_allowed); 4034 cpuset_cpus_allowed(p, cpus_allowed);
4035 cpumask_and(new_mask, in_mask, cpus_allowed); 4035 cpumask_and(new_mask, in_mask, cpus_allowed);
4036 4036
4037 /* 4037 /*
4038 * Since bandwidth control happens on root_domain basis, 4038 * Since bandwidth control happens on root_domain basis,
4039 * if admission test is enabled, we only admit -deadline 4039 * if admission test is enabled, we only admit -deadline
4040 * tasks allowed to run on all the CPUs in the task's 4040 * tasks allowed to run on all the CPUs in the task's
4041 * root_domain. 4041 * root_domain.
4042 */ 4042 */
4043 #ifdef CONFIG_SMP 4043 #ifdef CONFIG_SMP
4044 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) { 4044 if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
4045 rcu_read_lock(); 4045 rcu_read_lock();
4046 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) { 4046 if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
4047 retval = -EBUSY; 4047 retval = -EBUSY;
4048 rcu_read_unlock(); 4048 rcu_read_unlock();
4049 goto out_free_new_mask; 4049 goto out_free_new_mask;
4050 } 4050 }
4051 rcu_read_unlock(); 4051 rcu_read_unlock();
4052 } 4052 }
4053 #endif 4053 #endif
4054 again: 4054 again:
4055 retval = set_cpus_allowed_ptr(p, new_mask); 4055 retval = set_cpus_allowed_ptr(p, new_mask);
4056 4056
4057 if (!retval) { 4057 if (!retval) {
4058 cpuset_cpus_allowed(p, cpus_allowed); 4058 cpuset_cpus_allowed(p, cpus_allowed);
4059 if (!cpumask_subset(new_mask, cpus_allowed)) { 4059 if (!cpumask_subset(new_mask, cpus_allowed)) {
4060 /* 4060 /*
4061 * We must have raced with a concurrent cpuset 4061 * We must have raced with a concurrent cpuset
4062 * update. Just reset the cpus_allowed to the 4062 * update. Just reset the cpus_allowed to the
4063 * cpuset's cpus_allowed 4063 * cpuset's cpus_allowed
4064 */ 4064 */
4065 cpumask_copy(new_mask, cpus_allowed); 4065 cpumask_copy(new_mask, cpus_allowed);
4066 goto again; 4066 goto again;
4067 } 4067 }
4068 } 4068 }
4069 out_free_new_mask: 4069 out_free_new_mask:
4070 free_cpumask_var(new_mask); 4070 free_cpumask_var(new_mask);
4071 out_free_cpus_allowed: 4071 out_free_cpus_allowed:
4072 free_cpumask_var(cpus_allowed); 4072 free_cpumask_var(cpus_allowed);
4073 out_put_task: 4073 out_put_task:
4074 put_task_struct(p); 4074 put_task_struct(p);
4075 return retval; 4075 return retval;
4076 } 4076 }
4077 4077
4078 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len, 4078 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4079 struct cpumask *new_mask) 4079 struct cpumask *new_mask)
4080 { 4080 {
4081 if (len < cpumask_size()) 4081 if (len < cpumask_size())
4082 cpumask_clear(new_mask); 4082 cpumask_clear(new_mask);
4083 else if (len > cpumask_size()) 4083 else if (len > cpumask_size())
4084 len = cpumask_size(); 4084 len = cpumask_size();
4085 4085
4086 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0; 4086 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4087 } 4087 }
4088 4088
4089 /** 4089 /**
4090 * sys_sched_setaffinity - set the cpu affinity of a process 4090 * sys_sched_setaffinity - set the cpu affinity of a process
4091 * @pid: pid of the process 4091 * @pid: pid of the process
4092 * @len: length in bytes of the bitmask pointed to by user_mask_ptr 4092 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4093 * @user_mask_ptr: user-space pointer to the new cpu mask 4093 * @user_mask_ptr: user-space pointer to the new cpu mask
4094 * 4094 *
4095 * Return: 0 on success. An error code otherwise. 4095 * Return: 0 on success. An error code otherwise.
4096 */ 4096 */
4097 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len, 4097 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4098 unsigned long __user *, user_mask_ptr) 4098 unsigned long __user *, user_mask_ptr)
4099 { 4099 {
4100 cpumask_var_t new_mask; 4100 cpumask_var_t new_mask;
4101 int retval; 4101 int retval;
4102 4102
4103 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) 4103 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4104 return -ENOMEM; 4104 return -ENOMEM;
4105 4105
4106 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask); 4106 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4107 if (retval == 0) 4107 if (retval == 0)
4108 retval = sched_setaffinity(pid, new_mask); 4108 retval = sched_setaffinity(pid, new_mask);
4109 free_cpumask_var(new_mask); 4109 free_cpumask_var(new_mask);
4110 return retval; 4110 return retval;
4111 } 4111 }
4112 4112
4113 long sched_getaffinity(pid_t pid, struct cpumask *mask) 4113 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4114 { 4114 {
4115 struct task_struct *p; 4115 struct task_struct *p;
4116 unsigned long flags; 4116 unsigned long flags;
4117 int retval; 4117 int retval;
4118 4118
4119 rcu_read_lock(); 4119 rcu_read_lock();
4120 4120
4121 retval = -ESRCH; 4121 retval = -ESRCH;
4122 p = find_process_by_pid(pid); 4122 p = find_process_by_pid(pid);
4123 if (!p) 4123 if (!p)
4124 goto out_unlock; 4124 goto out_unlock;
4125 4125
4126 retval = security_task_getscheduler(p); 4126 retval = security_task_getscheduler(p);
4127 if (retval) 4127 if (retval)
4128 goto out_unlock; 4128 goto out_unlock;
4129 4129
4130 raw_spin_lock_irqsave(&p->pi_lock, flags); 4130 raw_spin_lock_irqsave(&p->pi_lock, flags);
4131 cpumask_and(mask, &p->cpus_allowed, cpu_active_mask); 4131 cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
4132 raw_spin_unlock_irqrestore(&p->pi_lock, flags); 4132 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4133 4133
4134 out_unlock: 4134 out_unlock:
4135 rcu_read_unlock(); 4135 rcu_read_unlock();
4136 4136
4137 return retval; 4137 return retval;
4138 } 4138 }
4139 4139
4140 /** 4140 /**
4141 * sys_sched_getaffinity - get the cpu affinity of a process 4141 * sys_sched_getaffinity - get the cpu affinity of a process
4142 * @pid: pid of the process 4142 * @pid: pid of the process
4143 * @len: length in bytes of the bitmask pointed to by user_mask_ptr 4143 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4144 * @user_mask_ptr: user-space pointer to hold the current cpu mask 4144 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4145 * 4145 *
4146 * Return: 0 on success. An error code otherwise. 4146 * Return: 0 on success. An error code otherwise.
4147 */ 4147 */
4148 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len, 4148 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4149 unsigned long __user *, user_mask_ptr) 4149 unsigned long __user *, user_mask_ptr)
4150 { 4150 {
4151 int ret; 4151 int ret;
4152 cpumask_var_t mask; 4152 cpumask_var_t mask;
4153 4153
4154 if ((len * BITS_PER_BYTE) < nr_cpu_ids) 4154 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
4155 return -EINVAL; 4155 return -EINVAL;
4156 if (len & (sizeof(unsigned long)-1)) 4156 if (len & (sizeof(unsigned long)-1))
4157 return -EINVAL; 4157 return -EINVAL;
4158 4158
4159 if (!alloc_cpumask_var(&mask, GFP_KERNEL)) 4159 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4160 return -ENOMEM; 4160 return -ENOMEM;
4161 4161
4162 ret = sched_getaffinity(pid, mask); 4162 ret = sched_getaffinity(pid, mask);
4163 if (ret == 0) { 4163 if (ret == 0) {
4164 size_t retlen = min_t(size_t, len, cpumask_size()); 4164 size_t retlen = min_t(size_t, len, cpumask_size());
4165 4165
4166 if (copy_to_user(user_mask_ptr, mask, retlen)) 4166 if (copy_to_user(user_mask_ptr, mask, retlen))
4167 ret = -EFAULT; 4167 ret = -EFAULT;
4168 else 4168 else
4169 ret = retlen; 4169 ret = retlen;
4170 } 4170 }
4171 free_cpumask_var(mask); 4171 free_cpumask_var(mask);
4172 4172
4173 return ret; 4173 return ret;
4174 } 4174 }
4175 4175
4176 /** 4176 /**
4177 * sys_sched_yield - yield the current processor to other threads. 4177 * sys_sched_yield - yield the current processor to other threads.
4178 * 4178 *
4179 * This function yields the current CPU to other tasks. If there are no 4179 * This function yields the current CPU to other tasks. If there are no
4180 * other threads running on this CPU then this function will return. 4180 * other threads running on this CPU then this function will return.
4181 * 4181 *
4182 * Return: 0. 4182 * Return: 0.
4183 */ 4183 */
4184 SYSCALL_DEFINE0(sched_yield) 4184 SYSCALL_DEFINE0(sched_yield)
4185 { 4185 {
4186 struct rq *rq = this_rq_lock(); 4186 struct rq *rq = this_rq_lock();
4187 4187
4188 schedstat_inc(rq, yld_count); 4188 schedstat_inc(rq, yld_count);
4189 current->sched_class->yield_task(rq); 4189 current->sched_class->yield_task(rq);
4190 4190
4191 /* 4191 /*
4192 * Since we are going to call schedule() anyway, there's 4192 * Since we are going to call schedule() anyway, there's
4193 * no need to preempt or enable interrupts: 4193 * no need to preempt or enable interrupts:
4194 */ 4194 */
4195 __release(rq->lock); 4195 __release(rq->lock);
4196 spin_release(&rq->lock.dep_map, 1, _THIS_IP_); 4196 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4197 do_raw_spin_unlock(&rq->lock); 4197 do_raw_spin_unlock(&rq->lock);
4198 sched_preempt_enable_no_resched(); 4198 sched_preempt_enable_no_resched();
4199 4199
4200 schedule(); 4200 schedule();
4201 4201
4202 return 0; 4202 return 0;
4203 } 4203 }
4204 4204
4205 static void __cond_resched(void) 4205 static void __cond_resched(void)
4206 { 4206 {
4207 __preempt_count_add(PREEMPT_ACTIVE); 4207 __preempt_count_add(PREEMPT_ACTIVE);
4208 __schedule(); 4208 __schedule();
4209 __preempt_count_sub(PREEMPT_ACTIVE); 4209 __preempt_count_sub(PREEMPT_ACTIVE);
4210 } 4210 }
4211 4211
4212 int __sched _cond_resched(void) 4212 int __sched _cond_resched(void)
4213 { 4213 {
4214 if (should_resched()) { 4214 if (should_resched()) {
4215 __cond_resched(); 4215 __cond_resched();
4216 return 1; 4216 return 1;
4217 } 4217 }
4218 return 0; 4218 return 0;
4219 } 4219 }
4220 EXPORT_SYMBOL(_cond_resched); 4220 EXPORT_SYMBOL(_cond_resched);
4221 4221
4222 /* 4222 /*
4223 * __cond_resched_lock() - if a reschedule is pending, drop the given lock, 4223 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
4224 * call schedule, and on return reacquire the lock. 4224 * call schedule, and on return reacquire the lock.
4225 * 4225 *
4226 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level 4226 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4227 * operations here to prevent schedule() from being called twice (once via 4227 * operations here to prevent schedule() from being called twice (once via
4228 * spin_unlock(), once by hand). 4228 * spin_unlock(), once by hand).
4229 */ 4229 */
4230 int __cond_resched_lock(spinlock_t *lock) 4230 int __cond_resched_lock(spinlock_t *lock)
4231 { 4231 {
4232 int resched = should_resched(); 4232 int resched = should_resched();
4233 int ret = 0; 4233 int ret = 0;
4234 4234
4235 lockdep_assert_held(lock); 4235 lockdep_assert_held(lock);
4236 4236
4237 if (spin_needbreak(lock) || resched) { 4237 if (spin_needbreak(lock) || resched) {
4238 spin_unlock(lock); 4238 spin_unlock(lock);
4239 if (resched) 4239 if (resched)
4240 __cond_resched(); 4240 __cond_resched();
4241 else 4241 else
4242 cpu_relax(); 4242 cpu_relax();
4243 ret = 1; 4243 ret = 1;
4244 spin_lock(lock); 4244 spin_lock(lock);
4245 } 4245 }
4246 return ret; 4246 return ret;
4247 } 4247 }
4248 EXPORT_SYMBOL(__cond_resched_lock); 4248 EXPORT_SYMBOL(__cond_resched_lock);
4249 4249
4250 int __sched __cond_resched_softirq(void) 4250 int __sched __cond_resched_softirq(void)
4251 { 4251 {
4252 BUG_ON(!in_softirq()); 4252 BUG_ON(!in_softirq());
4253 4253
4254 if (should_resched()) { 4254 if (should_resched()) {
4255 local_bh_enable(); 4255 local_bh_enable();
4256 __cond_resched(); 4256 __cond_resched();
4257 local_bh_disable(); 4257 local_bh_disable();
4258 return 1; 4258 return 1;
4259 } 4259 }
4260 return 0; 4260 return 0;
4261 } 4261 }
4262 EXPORT_SYMBOL(__cond_resched_softirq); 4262 EXPORT_SYMBOL(__cond_resched_softirq);
4263 4263
4264 /** 4264 /**
4265 * yield - yield the current processor to other threads. 4265 * yield - yield the current processor to other threads.
4266 * 4266 *
4267 * Do not ever use this function, there's a 99% chance you're doing it wrong. 4267 * Do not ever use this function, there's a 99% chance you're doing it wrong.
4268 * 4268 *
4269 * The scheduler is at all times free to pick the calling task as the most 4269 * The scheduler is at all times free to pick the calling task as the most
4270 * eligible task to run, if removing the yield() call from your code breaks 4270 * eligible task to run, if removing the yield() call from your code breaks
4271 * it, its already broken. 4271 * it, its already broken.
4272 * 4272 *
4273 * Typical broken usage is: 4273 * Typical broken usage is:
4274 * 4274 *
4275 * while (!event) 4275 * while (!event)
4276 * yield(); 4276 * yield();
4277 * 4277 *
4278 * where one assumes that yield() will let 'the other' process run that will 4278 * where one assumes that yield() will let 'the other' process run that will
4279 * make event true. If the current task is a SCHED_FIFO task that will never 4279 * make event true. If the current task is a SCHED_FIFO task that will never
4280 * happen. Never use yield() as a progress guarantee!! 4280 * happen. Never use yield() as a progress guarantee!!
4281 * 4281 *
4282 * If you want to use yield() to wait for something, use wait_event(). 4282 * If you want to use yield() to wait for something, use wait_event().
4283 * If you want to use yield() to be 'nice' for others, use cond_resched(). 4283 * If you want to use yield() to be 'nice' for others, use cond_resched().
4284 * If you still want to use yield(), do not! 4284 * If you still want to use yield(), do not!
4285 */ 4285 */
4286 void __sched yield(void) 4286 void __sched yield(void)
4287 { 4287 {
4288 set_current_state(TASK_RUNNING); 4288 set_current_state(TASK_RUNNING);
4289 sys_sched_yield(); 4289 sys_sched_yield();
4290 } 4290 }
4291 EXPORT_SYMBOL(yield); 4291 EXPORT_SYMBOL(yield);
4292 4292
4293 /** 4293 /**
4294 * yield_to - yield the current processor to another thread in 4294 * yield_to - yield the current processor to another thread in
4295 * your thread group, or accelerate that thread toward the 4295 * your thread group, or accelerate that thread toward the
4296 * processor it's on. 4296 * processor it's on.
4297 * @p: target task 4297 * @p: target task
4298 * @preempt: whether task preemption is allowed or not 4298 * @preempt: whether task preemption is allowed or not
4299 * 4299 *
4300 * It's the caller's job to ensure that the target task struct 4300 * It's the caller's job to ensure that the target task struct
4301 * can't go away on us before we can do any checks. 4301 * can't go away on us before we can do any checks.
4302 * 4302 *
4303 * Return: 4303 * Return:
4304 * true (>0) if we indeed boosted the target task. 4304 * true (>0) if we indeed boosted the target task.
4305 * false (0) if we failed to boost the target. 4305 * false (0) if we failed to boost the target.
4306 * -ESRCH if there's no task to yield to. 4306 * -ESRCH if there's no task to yield to.
4307 */ 4307 */
4308 int __sched yield_to(struct task_struct *p, bool preempt) 4308 int __sched yield_to(struct task_struct *p, bool preempt)
4309 { 4309 {
4310 struct task_struct *curr = current; 4310 struct task_struct *curr = current;
4311 struct rq *rq, *p_rq; 4311 struct rq *rq, *p_rq;
4312 unsigned long flags; 4312 unsigned long flags;
4313 int yielded = 0; 4313 int yielded = 0;
4314 4314
4315 local_irq_save(flags); 4315 local_irq_save(flags);
4316 rq = this_rq(); 4316 rq = this_rq();
4317 4317
4318 again: 4318 again:
4319 p_rq = task_rq(p); 4319 p_rq = task_rq(p);
4320 /* 4320 /*
4321 * If we're the only runnable task on the rq and target rq also 4321 * If we're the only runnable task on the rq and target rq also
4322 * has only one task, there's absolutely no point in yielding. 4322 * has only one task, there's absolutely no point in yielding.
4323 */ 4323 */
4324 if (rq->nr_running == 1 && p_rq->nr_running == 1) { 4324 if (rq->nr_running == 1 && p_rq->nr_running == 1) {
4325 yielded = -ESRCH; 4325 yielded = -ESRCH;
4326 goto out_irq; 4326 goto out_irq;
4327 } 4327 }
4328 4328
4329 double_rq_lock(rq, p_rq); 4329 double_rq_lock(rq, p_rq);
4330 if (task_rq(p) != p_rq) { 4330 if (task_rq(p) != p_rq) {
4331 double_rq_unlock(rq, p_rq); 4331 double_rq_unlock(rq, p_rq);
4332 goto again; 4332 goto again;
4333 } 4333 }
4334 4334
4335 if (!curr->sched_class->yield_to_task) 4335 if (!curr->sched_class->yield_to_task)
4336 goto out_unlock; 4336 goto out_unlock;
4337 4337
4338 if (curr->sched_class != p->sched_class) 4338 if (curr->sched_class != p->sched_class)
4339 goto out_unlock; 4339 goto out_unlock;
4340 4340
4341 if (task_running(p_rq, p) || p->state) 4341 if (task_running(p_rq, p) || p->state)
4342 goto out_unlock; 4342 goto out_unlock;
4343 4343
4344 yielded = curr->sched_class->yield_to_task(rq, p, preempt); 4344 yielded = curr->sched_class->yield_to_task(rq, p, preempt);
4345 if (yielded) { 4345 if (yielded) {
4346 schedstat_inc(rq, yld_count); 4346 schedstat_inc(rq, yld_count);
4347 /* 4347 /*
4348 * Make p's CPU reschedule; pick_next_entity takes care of 4348 * Make p's CPU reschedule; pick_next_entity takes care of
4349 * fairness. 4349 * fairness.
4350 */ 4350 */
4351 if (preempt && rq != p_rq) 4351 if (preempt && rq != p_rq)
4352 resched_curr(p_rq); 4352 resched_curr(p_rq);
4353 } 4353 }
4354 4354
4355 out_unlock: 4355 out_unlock:
4356 double_rq_unlock(rq, p_rq); 4356 double_rq_unlock(rq, p_rq);
4357 out_irq: 4357 out_irq:
4358 local_irq_restore(flags); 4358 local_irq_restore(flags);
4359 4359
4360 if (yielded > 0) 4360 if (yielded > 0)
4361 schedule(); 4361 schedule();
4362 4362
4363 return yielded; 4363 return yielded;
4364 } 4364 }
4365 EXPORT_SYMBOL_GPL(yield_to); 4365 EXPORT_SYMBOL_GPL(yield_to);
4366 4366
4367 /* 4367 /*
4368 * This task is about to go to sleep on IO. Increment rq->nr_iowait so 4368 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4369 * that process accounting knows that this is a task in IO wait state. 4369 * that process accounting knows that this is a task in IO wait state.
4370 */ 4370 */
4371 void __sched io_schedule(void) 4371 void __sched io_schedule(void)
4372 { 4372 {
4373 struct rq *rq = raw_rq(); 4373 struct rq *rq = raw_rq();
4374 4374
4375 delayacct_blkio_start(); 4375 delayacct_blkio_start();
4376 atomic_inc(&rq->nr_iowait); 4376 atomic_inc(&rq->nr_iowait);
4377 blk_flush_plug(current); 4377 blk_flush_plug(current);
4378 current->in_iowait = 1; 4378 current->in_iowait = 1;
4379 schedule(); 4379 schedule();
4380 current->in_iowait = 0; 4380 current->in_iowait = 0;
4381 atomic_dec(&rq->nr_iowait); 4381 atomic_dec(&rq->nr_iowait);
4382 delayacct_blkio_end(); 4382 delayacct_blkio_end();
4383 } 4383 }
4384 EXPORT_SYMBOL(io_schedule); 4384 EXPORT_SYMBOL(io_schedule);
4385 4385
4386 long __sched io_schedule_timeout(long timeout) 4386 long __sched io_schedule_timeout(long timeout)
4387 { 4387 {
4388 struct rq *rq = raw_rq(); 4388 struct rq *rq = raw_rq();
4389 long ret; 4389 long ret;
4390 4390
4391 delayacct_blkio_start(); 4391 delayacct_blkio_start();
4392 atomic_inc(&rq->nr_iowait); 4392 atomic_inc(&rq->nr_iowait);
4393 blk_flush_plug(current); 4393 blk_flush_plug(current);
4394 current->in_iowait = 1; 4394 current->in_iowait = 1;
4395 ret = schedule_timeout(timeout); 4395 ret = schedule_timeout(timeout);
4396 current->in_iowait = 0; 4396 current->in_iowait = 0;
4397 atomic_dec(&rq->nr_iowait); 4397 atomic_dec(&rq->nr_iowait);
4398 delayacct_blkio_end(); 4398 delayacct_blkio_end();
4399 return ret; 4399 return ret;
4400 } 4400 }
4401 4401
4402 /** 4402 /**
4403 * sys_sched_get_priority_max - return maximum RT priority. 4403 * sys_sched_get_priority_max - return maximum RT priority.
4404 * @policy: scheduling class. 4404 * @policy: scheduling class.
4405 * 4405 *
4406 * Return: On success, this syscall returns the maximum 4406 * Return: On success, this syscall returns the maximum
4407 * rt_priority that can be used by a given scheduling class. 4407 * rt_priority that can be used by a given scheduling class.
4408 * On failure, a negative error code is returned. 4408 * On failure, a negative error code is returned.
4409 */ 4409 */
4410 SYSCALL_DEFINE1(sched_get_priority_max, int, policy) 4410 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
4411 { 4411 {
4412 int ret = -EINVAL; 4412 int ret = -EINVAL;
4413 4413
4414 switch (policy) { 4414 switch (policy) {
4415 case SCHED_FIFO: 4415 case SCHED_FIFO:
4416 case SCHED_RR: 4416 case SCHED_RR:
4417 ret = MAX_USER_RT_PRIO-1; 4417 ret = MAX_USER_RT_PRIO-1;
4418 break; 4418 break;
4419 case SCHED_DEADLINE: 4419 case SCHED_DEADLINE:
4420 case SCHED_NORMAL: 4420 case SCHED_NORMAL:
4421 case SCHED_BATCH: 4421 case SCHED_BATCH:
4422 case SCHED_IDLE: 4422 case SCHED_IDLE:
4423 ret = 0; 4423 ret = 0;
4424 break; 4424 break;
4425 } 4425 }
4426 return ret; 4426 return ret;
4427 } 4427 }
4428 4428
4429 /** 4429 /**
4430 * sys_sched_get_priority_min - return minimum RT priority. 4430 * sys_sched_get_priority_min - return minimum RT priority.
4431 * @policy: scheduling class. 4431 * @policy: scheduling class.
4432 * 4432 *
4433 * Return: On success, this syscall returns the minimum 4433 * Return: On success, this syscall returns the minimum
4434 * rt_priority that can be used by a given scheduling class. 4434 * rt_priority that can be used by a given scheduling class.
4435 * On failure, a negative error code is returned. 4435 * On failure, a negative error code is returned.
4436 */ 4436 */
4437 SYSCALL_DEFINE1(sched_get_priority_min, int, policy) 4437 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
4438 { 4438 {
4439 int ret = -EINVAL; 4439 int ret = -EINVAL;
4440 4440
4441 switch (policy) { 4441 switch (policy) {
4442 case SCHED_FIFO: 4442 case SCHED_FIFO:
4443 case SCHED_RR: 4443 case SCHED_RR:
4444 ret = 1; 4444 ret = 1;
4445 break; 4445 break;
4446 case SCHED_DEADLINE: 4446 case SCHED_DEADLINE:
4447 case SCHED_NORMAL: 4447 case SCHED_NORMAL:
4448 case SCHED_BATCH: 4448 case SCHED_BATCH:
4449 case SCHED_IDLE: 4449 case SCHED_IDLE:
4450 ret = 0; 4450 ret = 0;
4451 } 4451 }
4452 return ret; 4452 return ret;
4453 } 4453 }
4454 4454
4455 /** 4455 /**
4456 * sys_sched_rr_get_interval - return the default timeslice of a process. 4456 * sys_sched_rr_get_interval - return the default timeslice of a process.
4457 * @pid: pid of the process. 4457 * @pid: pid of the process.
4458 * @interval: userspace pointer to the timeslice value. 4458 * @interval: userspace pointer to the timeslice value.
4459 * 4459 *
4460 * this syscall writes the default timeslice value of a given process 4460 * this syscall writes the default timeslice value of a given process
4461 * into the user-space timespec buffer. A value of '0' means infinity. 4461 * into the user-space timespec buffer. A value of '0' means infinity.
4462 * 4462 *
4463 * Return: On success, 0 and the timeslice is in @interval. Otherwise, 4463 * Return: On success, 0 and the timeslice is in @interval. Otherwise,
4464 * an error code. 4464 * an error code.
4465 */ 4465 */
4466 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid, 4466 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
4467 struct timespec __user *, interval) 4467 struct timespec __user *, interval)
4468 { 4468 {
4469 struct task_struct *p; 4469 struct task_struct *p;
4470 unsigned int time_slice; 4470 unsigned int time_slice;
4471 unsigned long flags; 4471 unsigned long flags;
4472 struct rq *rq; 4472 struct rq *rq;
4473 int retval; 4473 int retval;
4474 struct timespec t; 4474 struct timespec t;
4475 4475
4476 if (pid < 0) 4476 if (pid < 0)
4477 return -EINVAL; 4477 return -EINVAL;
4478 4478
4479 retval = -ESRCH; 4479 retval = -ESRCH;
4480 rcu_read_lock(); 4480 rcu_read_lock();
4481 p = find_process_by_pid(pid); 4481 p = find_process_by_pid(pid);
4482 if (!p) 4482 if (!p)
4483 goto out_unlock; 4483 goto out_unlock;
4484 4484
4485 retval = security_task_getscheduler(p); 4485 retval = security_task_getscheduler(p);
4486 if (retval) 4486 if (retval)
4487 goto out_unlock; 4487 goto out_unlock;
4488 4488
4489 rq = task_rq_lock(p, &flags); 4489 rq = task_rq_lock(p, &flags);
4490 time_slice = 0; 4490 time_slice = 0;
4491 if (p->sched_class->get_rr_interval) 4491 if (p->sched_class->get_rr_interval)
4492 time_slice = p->sched_class->get_rr_interval(rq, p); 4492 time_slice = p->sched_class->get_rr_interval(rq, p);
4493 task_rq_unlock(rq, p, &flags); 4493 task_rq_unlock(rq, p, &flags);
4494 4494
4495 rcu_read_unlock(); 4495 rcu_read_unlock();
4496 jiffies_to_timespec(time_slice, &t); 4496 jiffies_to_timespec(time_slice, &t);
4497 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0; 4497 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4498 return retval; 4498 return retval;
4499 4499
4500 out_unlock: 4500 out_unlock:
4501 rcu_read_unlock(); 4501 rcu_read_unlock();
4502 return retval; 4502 return retval;
4503 } 4503 }
4504 4504
4505 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR; 4505 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
4506 4506
4507 void sched_show_task(struct task_struct *p) 4507 void sched_show_task(struct task_struct *p)
4508 { 4508 {
4509 unsigned long free = 0; 4509 unsigned long free = 0;
4510 int ppid; 4510 int ppid;
4511 unsigned state; 4511 unsigned state;
4512 4512
4513 state = p->state ? __ffs(p->state) + 1 : 0; 4513 state = p->state ? __ffs(p->state) + 1 : 0;
4514 printk(KERN_INFO "%-15.15s %c", p->comm, 4514 printk(KERN_INFO "%-15.15s %c", p->comm,
4515 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?'); 4515 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4516 #if BITS_PER_LONG == 32 4516 #if BITS_PER_LONG == 32
4517 if (state == TASK_RUNNING) 4517 if (state == TASK_RUNNING)
4518 printk(KERN_CONT " running "); 4518 printk(KERN_CONT " running ");
4519 else 4519 else
4520 printk(KERN_CONT " %08lx ", thread_saved_pc(p)); 4520 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
4521 #else 4521 #else
4522 if (state == TASK_RUNNING) 4522 if (state == TASK_RUNNING)
4523 printk(KERN_CONT " running task "); 4523 printk(KERN_CONT " running task ");
4524 else 4524 else
4525 printk(KERN_CONT " %016lx ", thread_saved_pc(p)); 4525 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
4526 #endif 4526 #endif
4527 #ifdef CONFIG_DEBUG_STACK_USAGE 4527 #ifdef CONFIG_DEBUG_STACK_USAGE
4528 free = stack_not_used(p); 4528 free = stack_not_used(p);
4529 #endif 4529 #endif
4530 ppid = 0; 4530 ppid = 0;
4531 rcu_read_lock(); 4531 rcu_read_lock();
4532 if (pid_alive(p)) 4532 if (pid_alive(p))
4533 ppid = task_pid_nr(rcu_dereference(p->real_parent)); 4533 ppid = task_pid_nr(rcu_dereference(p->real_parent));
4534 rcu_read_unlock(); 4534 rcu_read_unlock();
4535 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free, 4535 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
4536 task_pid_nr(p), ppid, 4536 task_pid_nr(p), ppid,
4537 (unsigned long)task_thread_info(p)->flags); 4537 (unsigned long)task_thread_info(p)->flags);
4538 4538
4539 print_worker_info(KERN_INFO, p); 4539 print_worker_info(KERN_INFO, p);
4540 show_stack(p, NULL); 4540 show_stack(p, NULL);
4541 } 4541 }
4542 4542
4543 void show_state_filter(unsigned long state_filter) 4543 void show_state_filter(unsigned long state_filter)
4544 { 4544 {
4545 struct task_struct *g, *p; 4545 struct task_struct *g, *p;
4546 4546
4547 #if BITS_PER_LONG == 32 4547 #if BITS_PER_LONG == 32
4548 printk(KERN_INFO 4548 printk(KERN_INFO
4549 " task PC stack pid father\n"); 4549 " task PC stack pid father\n");
4550 #else 4550 #else
4551 printk(KERN_INFO 4551 printk(KERN_INFO
4552 " task PC stack pid father\n"); 4552 " task PC stack pid father\n");
4553 #endif 4553 #endif
4554 rcu_read_lock(); 4554 rcu_read_lock();
4555 for_each_process_thread(g, p) { 4555 for_each_process_thread(g, p) {
4556 /* 4556 /*
4557 * reset the NMI-timeout, listing all files on a slow 4557 * reset the NMI-timeout, listing all files on a slow
4558 * console might take a lot of time: 4558 * console might take a lot of time:
4559 */ 4559 */
4560 touch_nmi_watchdog(); 4560 touch_nmi_watchdog();
4561 if (!state_filter || (p->state & state_filter)) 4561 if (!state_filter || (p->state & state_filter))
4562 sched_show_task(p); 4562 sched_show_task(p);
4563 } 4563 }
4564 4564
4565 touch_all_softlockup_watchdogs(); 4565 touch_all_softlockup_watchdogs();
4566 4566
4567 #ifdef CONFIG_SCHED_DEBUG 4567 #ifdef CONFIG_SCHED_DEBUG
4568 sysrq_sched_debug_show(); 4568 sysrq_sched_debug_show();
4569 #endif 4569 #endif
4570 rcu_read_unlock(); 4570 rcu_read_unlock();
4571 /* 4571 /*
4572 * Only show locks if all tasks are dumped: 4572 * Only show locks if all tasks are dumped:
4573 */ 4573 */
4574 if (!state_filter) 4574 if (!state_filter)
4575 debug_show_all_locks(); 4575 debug_show_all_locks();
4576 } 4576 }
4577 4577
4578 void init_idle_bootup_task(struct task_struct *idle) 4578 void init_idle_bootup_task(struct task_struct *idle)
4579 { 4579 {
4580 idle->sched_class = &idle_sched_class; 4580 idle->sched_class = &idle_sched_class;
4581 } 4581 }
4582 4582
4583 /** 4583 /**
4584 * init_idle - set up an idle thread for a given CPU 4584 * init_idle - set up an idle thread for a given CPU
4585 * @idle: task in question 4585 * @idle: task in question
4586 * @cpu: cpu the idle task belongs to 4586 * @cpu: cpu the idle task belongs to
4587 * 4587 *
4588 * NOTE: this function does not set the idle thread's NEED_RESCHED 4588 * NOTE: this function does not set the idle thread's NEED_RESCHED
4589 * flag, to make booting more robust. 4589 * flag, to make booting more robust.
4590 */ 4590 */
4591 void init_idle(struct task_struct *idle, int cpu) 4591 void init_idle(struct task_struct *idle, int cpu)
4592 { 4592 {
4593 struct rq *rq = cpu_rq(cpu); 4593 struct rq *rq = cpu_rq(cpu);
4594 unsigned long flags; 4594 unsigned long flags;
4595 4595
4596 raw_spin_lock_irqsave(&rq->lock, flags); 4596 raw_spin_lock_irqsave(&rq->lock, flags);
4597 4597
4598 __sched_fork(0, idle); 4598 __sched_fork(0, idle);
4599 idle->state = TASK_RUNNING; 4599 idle->state = TASK_RUNNING;
4600 idle->se.exec_start = sched_clock(); 4600 idle->se.exec_start = sched_clock();
4601 4601
4602 do_set_cpus_allowed(idle, cpumask_of(cpu)); 4602 do_set_cpus_allowed(idle, cpumask_of(cpu));
4603 /* 4603 /*
4604 * We're having a chicken and egg problem, even though we are 4604 * We're having a chicken and egg problem, even though we are
4605 * holding rq->lock, the cpu isn't yet set to this cpu so the 4605 * holding rq->lock, the cpu isn't yet set to this cpu so the
4606 * lockdep check in task_group() will fail. 4606 * lockdep check in task_group() will fail.
4607 * 4607 *
4608 * Similar case to sched_fork(). / Alternatively we could 4608 * Similar case to sched_fork(). / Alternatively we could
4609 * use task_rq_lock() here and obtain the other rq->lock. 4609 * use task_rq_lock() here and obtain the other rq->lock.
4610 * 4610 *
4611 * Silence PROVE_RCU 4611 * Silence PROVE_RCU
4612 */ 4612 */
4613 rcu_read_lock(); 4613 rcu_read_lock();
4614 __set_task_cpu(idle, cpu); 4614 __set_task_cpu(idle, cpu);
4615 rcu_read_unlock(); 4615 rcu_read_unlock();
4616 4616
4617 rq->curr = rq->idle = idle; 4617 rq->curr = rq->idle = idle;
4618 idle->on_rq = TASK_ON_RQ_QUEUED; 4618 idle->on_rq = TASK_ON_RQ_QUEUED;
4619 #if defined(CONFIG_SMP) 4619 #if defined(CONFIG_SMP)
4620 idle->on_cpu = 1; 4620 idle->on_cpu = 1;
4621 #endif 4621 #endif
4622 raw_spin_unlock_irqrestore(&rq->lock, flags); 4622 raw_spin_unlock_irqrestore(&rq->lock, flags);
4623 4623
4624 /* Set the preempt count _outside_ the spinlocks! */ 4624 /* Set the preempt count _outside_ the spinlocks! */
4625 init_idle_preempt_count(idle, cpu); 4625 init_idle_preempt_count(idle, cpu);
4626 4626
4627 /* 4627 /*
4628 * The idle tasks have their own, simple scheduling class: 4628 * The idle tasks have their own, simple scheduling class:
4629 */ 4629 */
4630 idle->sched_class = &idle_sched_class; 4630 idle->sched_class = &idle_sched_class;
4631 ftrace_graph_init_idle_task(idle, cpu); 4631 ftrace_graph_init_idle_task(idle, cpu);
4632 vtime_init_idle(idle, cpu); 4632 vtime_init_idle(idle, cpu);
4633 #if defined(CONFIG_SMP) 4633 #if defined(CONFIG_SMP)
4634 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu); 4634 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
4635 #endif 4635 #endif
4636 } 4636 }
4637 4637
4638 int cpuset_cpumask_can_shrink(const struct cpumask *cur, 4638 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
4639 const struct cpumask *trial) 4639 const struct cpumask *trial)
4640 { 4640 {
4641 int ret = 1, trial_cpus; 4641 int ret = 1, trial_cpus;
4642 struct dl_bw *cur_dl_b; 4642 struct dl_bw *cur_dl_b;
4643 unsigned long flags; 4643 unsigned long flags;
4644 4644
4645 rcu_read_lock_sched(); 4645 rcu_read_lock_sched();
4646 cur_dl_b = dl_bw_of(cpumask_any(cur)); 4646 cur_dl_b = dl_bw_of(cpumask_any(cur));
4647 trial_cpus = cpumask_weight(trial); 4647 trial_cpus = cpumask_weight(trial);
4648 4648
4649 raw_spin_lock_irqsave(&cur_dl_b->lock, flags); 4649 raw_spin_lock_irqsave(&cur_dl_b->lock, flags);
4650 if (cur_dl_b->bw != -1 && 4650 if (cur_dl_b->bw != -1 &&
4651 cur_dl_b->bw * trial_cpus < cur_dl_b->total_bw) 4651 cur_dl_b->bw * trial_cpus < cur_dl_b->total_bw)
4652 ret = 0; 4652 ret = 0;
4653 raw_spin_unlock_irqrestore(&cur_dl_b->lock, flags); 4653 raw_spin_unlock_irqrestore(&cur_dl_b->lock, flags);
4654 rcu_read_unlock_sched(); 4654 rcu_read_unlock_sched();
4655 4655
4656 return ret; 4656 return ret;
4657 } 4657 }
4658 4658
4659 int task_can_attach(struct task_struct *p, 4659 int task_can_attach(struct task_struct *p,
4660 const struct cpumask *cs_cpus_allowed) 4660 const struct cpumask *cs_cpus_allowed)
4661 { 4661 {
4662 int ret = 0; 4662 int ret = 0;
4663 4663
4664 /* 4664 /*
4665 * Kthreads which disallow setaffinity shouldn't be moved 4665 * Kthreads which disallow setaffinity shouldn't be moved
4666 * to a new cpuset; we don't want to change their cpu 4666 * to a new cpuset; we don't want to change their cpu
4667 * affinity and isolating such threads by their set of 4667 * affinity and isolating such threads by their set of
4668 * allowed nodes is unnecessary. Thus, cpusets are not 4668 * allowed nodes is unnecessary. Thus, cpusets are not
4669 * applicable for such threads. This prevents checking for 4669 * applicable for such threads. This prevents checking for
4670 * success of set_cpus_allowed_ptr() on all attached tasks 4670 * success of set_cpus_allowed_ptr() on all attached tasks
4671 * before cpus_allowed may be changed. 4671 * before cpus_allowed may be changed.
4672 */ 4672 */
4673 if (p->flags & PF_NO_SETAFFINITY) { 4673 if (p->flags & PF_NO_SETAFFINITY) {
4674 ret = -EINVAL; 4674 ret = -EINVAL;
4675 goto out; 4675 goto out;
4676 } 4676 }
4677 4677
4678 #ifdef CONFIG_SMP 4678 #ifdef CONFIG_SMP
4679 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span, 4679 if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
4680 cs_cpus_allowed)) { 4680 cs_cpus_allowed)) {
4681 unsigned int dest_cpu = cpumask_any_and(cpu_active_mask, 4681 unsigned int dest_cpu = cpumask_any_and(cpu_active_mask,
4682 cs_cpus_allowed); 4682 cs_cpus_allowed);
4683 struct dl_bw *dl_b; 4683 struct dl_bw *dl_b;
4684 bool overflow; 4684 bool overflow;
4685 int cpus; 4685 int cpus;
4686 unsigned long flags; 4686 unsigned long flags;
4687 4687
4688 rcu_read_lock_sched(); 4688 rcu_read_lock_sched();
4689 dl_b = dl_bw_of(dest_cpu); 4689 dl_b = dl_bw_of(dest_cpu);
4690 raw_spin_lock_irqsave(&dl_b->lock, flags); 4690 raw_spin_lock_irqsave(&dl_b->lock, flags);
4691 cpus = dl_bw_cpus(dest_cpu); 4691 cpus = dl_bw_cpus(dest_cpu);
4692 overflow = __dl_overflow(dl_b, cpus, 0, p->dl.dl_bw); 4692 overflow = __dl_overflow(dl_b, cpus, 0, p->dl.dl_bw);
4693 if (overflow) 4693 if (overflow)
4694 ret = -EBUSY; 4694 ret = -EBUSY;
4695 else { 4695 else {
4696 /* 4696 /*
4697 * We reserve space for this task in the destination 4697 * We reserve space for this task in the destination
4698 * root_domain, as we can't fail after this point. 4698 * root_domain, as we can't fail after this point.
4699 * We will free resources in the source root_domain 4699 * We will free resources in the source root_domain
4700 * later on (see set_cpus_allowed_dl()). 4700 * later on (see set_cpus_allowed_dl()).
4701 */ 4701 */
4702 __dl_add(dl_b, p->dl.dl_bw); 4702 __dl_add(dl_b, p->dl.dl_bw);
4703 } 4703 }
4704 raw_spin_unlock_irqrestore(&dl_b->lock, flags); 4704 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
4705 rcu_read_unlock_sched(); 4705 rcu_read_unlock_sched();
4706 4706
4707 } 4707 }
4708 #endif 4708 #endif
4709 out: 4709 out:
4710 return ret; 4710 return ret;
4711 } 4711 }
4712 4712
4713 #ifdef CONFIG_SMP 4713 #ifdef CONFIG_SMP
4714 /* 4714 /*
4715 * move_queued_task - move a queued task to new rq. 4715 * move_queued_task - move a queued task to new rq.
4716 * 4716 *
4717 * Returns (locked) new rq. Old rq's lock is released. 4717 * Returns (locked) new rq. Old rq's lock is released.
4718 */ 4718 */
4719 static struct rq *move_queued_task(struct task_struct *p, int new_cpu) 4719 static struct rq *move_queued_task(struct task_struct *p, int new_cpu)
4720 { 4720 {
4721 struct rq *rq = task_rq(p); 4721 struct rq *rq = task_rq(p);
4722 4722
4723 lockdep_assert_held(&rq->lock); 4723 lockdep_assert_held(&rq->lock);
4724 4724
4725 dequeue_task(rq, p, 0); 4725 dequeue_task(rq, p, 0);
4726 p->on_rq = TASK_ON_RQ_MIGRATING; 4726 p->on_rq = TASK_ON_RQ_MIGRATING;
4727 set_task_cpu(p, new_cpu); 4727 set_task_cpu(p, new_cpu);
4728 raw_spin_unlock(&rq->lock); 4728 raw_spin_unlock(&rq->lock);
4729 4729
4730 rq = cpu_rq(new_cpu); 4730 rq = cpu_rq(new_cpu);
4731 4731
4732 raw_spin_lock(&rq->lock); 4732 raw_spin_lock(&rq->lock);
4733 BUG_ON(task_cpu(p) != new_cpu); 4733 BUG_ON(task_cpu(p) != new_cpu);
4734 p->on_rq = TASK_ON_RQ_QUEUED; 4734 p->on_rq = TASK_ON_RQ_QUEUED;
4735 enqueue_task(rq, p, 0); 4735 enqueue_task(rq, p, 0);
4736 check_preempt_curr(rq, p, 0); 4736 check_preempt_curr(rq, p, 0);
4737 4737
4738 return rq; 4738 return rq;
4739 } 4739 }
4740 4740
4741 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask) 4741 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
4742 { 4742 {
4743 if (p->sched_class && p->sched_class->set_cpus_allowed) 4743 if (p->sched_class && p->sched_class->set_cpus_allowed)
4744 p->sched_class->set_cpus_allowed(p, new_mask); 4744 p->sched_class->set_cpus_allowed(p, new_mask);
4745 4745
4746 cpumask_copy(&p->cpus_allowed, new_mask); 4746 cpumask_copy(&p->cpus_allowed, new_mask);
4747 p->nr_cpus_allowed = cpumask_weight(new_mask); 4747 p->nr_cpus_allowed = cpumask_weight(new_mask);
4748 } 4748 }
4749 4749
4750 /* 4750 /*
4751 * This is how migration works: 4751 * This is how migration works:
4752 * 4752 *
4753 * 1) we invoke migration_cpu_stop() on the target CPU using 4753 * 1) we invoke migration_cpu_stop() on the target CPU using
4754 * stop_one_cpu(). 4754 * stop_one_cpu().
4755 * 2) stopper starts to run (implicitly forcing the migrated thread 4755 * 2) stopper starts to run (implicitly forcing the migrated thread
4756 * off the CPU) 4756 * off the CPU)
4757 * 3) it checks whether the migrated task is still in the wrong runqueue. 4757 * 3) it checks whether the migrated task is still in the wrong runqueue.
4758 * 4) if it's in the wrong runqueue then the migration thread removes 4758 * 4) if it's in the wrong runqueue then the migration thread removes
4759 * it and puts it into the right queue. 4759 * it and puts it into the right queue.
4760 * 5) stopper completes and stop_one_cpu() returns and the migration 4760 * 5) stopper completes and stop_one_cpu() returns and the migration
4761 * is done. 4761 * is done.
4762 */ 4762 */
4763 4763
4764 /* 4764 /*
4765 * Change a given task's CPU affinity. Migrate the thread to a 4765 * Change a given task's CPU affinity. Migrate the thread to a
4766 * proper CPU and schedule it away if the CPU it's executing on 4766 * proper CPU and schedule it away if the CPU it's executing on
4767 * is removed from the allowed bitmask. 4767 * is removed from the allowed bitmask.
4768 * 4768 *
4769 * NOTE: the caller must have a valid reference to the task, the 4769 * NOTE: the caller must have a valid reference to the task, the
4770 * task must not exit() & deallocate itself prematurely. The 4770 * task must not exit() & deallocate itself prematurely. The
4771 * call is not atomic; no spinlocks may be held. 4771 * call is not atomic; no spinlocks may be held.
4772 */ 4772 */
4773 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask) 4773 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
4774 { 4774 {
4775 unsigned long flags; 4775 unsigned long flags;
4776 struct rq *rq; 4776 struct rq *rq;
4777 unsigned int dest_cpu; 4777 unsigned int dest_cpu;
4778 int ret = 0; 4778 int ret = 0;
4779 4779
4780 rq = task_rq_lock(p, &flags); 4780 rq = task_rq_lock(p, &flags);
4781 4781
4782 if (cpumask_equal(&p->cpus_allowed, new_mask)) 4782 if (cpumask_equal(&p->cpus_allowed, new_mask))
4783 goto out; 4783 goto out;
4784 4784
4785 if (!cpumask_intersects(new_mask, cpu_active_mask)) { 4785 if (!cpumask_intersects(new_mask, cpu_active_mask)) {
4786 ret = -EINVAL; 4786 ret = -EINVAL;
4787 goto out; 4787 goto out;
4788 } 4788 }
4789 4789
4790 do_set_cpus_allowed(p, new_mask); 4790 do_set_cpus_allowed(p, new_mask);
4791 4791
4792 /* Can the task run on the task's current CPU? If so, we're done */ 4792 /* Can the task run on the task's current CPU? If so, we're done */
4793 if (cpumask_test_cpu(task_cpu(p), new_mask)) 4793 if (cpumask_test_cpu(task_cpu(p), new_mask))
4794 goto out; 4794 goto out;
4795 4795
4796 dest_cpu = cpumask_any_and(cpu_active_mask, new_mask); 4796 dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
4797 if (task_running(rq, p) || p->state == TASK_WAKING) { 4797 if (task_running(rq, p) || p->state == TASK_WAKING) {
4798 struct migration_arg arg = { p, dest_cpu }; 4798 struct migration_arg arg = { p, dest_cpu };
4799 /* Need help from migration thread: drop lock and wait. */ 4799 /* Need help from migration thread: drop lock and wait. */
4800 task_rq_unlock(rq, p, &flags); 4800 task_rq_unlock(rq, p, &flags);
4801 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg); 4801 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
4802 tlb_migrate_finish(p->mm); 4802 tlb_migrate_finish(p->mm);
4803 return 0; 4803 return 0;
4804 } else if (task_on_rq_queued(p)) 4804 } else if (task_on_rq_queued(p))
4805 rq = move_queued_task(p, dest_cpu); 4805 rq = move_queued_task(p, dest_cpu);
4806 out: 4806 out:
4807 task_rq_unlock(rq, p, &flags); 4807 task_rq_unlock(rq, p, &flags);
4808 4808
4809 return ret; 4809 return ret;
4810 } 4810 }
4811 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr); 4811 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
4812 4812
4813 /* 4813 /*
4814 * Move (not current) task off this cpu, onto dest cpu. We're doing 4814 * Move (not current) task off this cpu, onto dest cpu. We're doing
4815 * this because either it can't run here any more (set_cpus_allowed() 4815 * this because either it can't run here any more (set_cpus_allowed()
4816 * away from this CPU, or CPU going down), or because we're 4816 * away from this CPU, or CPU going down), or because we're
4817 * attempting to rebalance this task on exec (sched_exec). 4817 * attempting to rebalance this task on exec (sched_exec).
4818 * 4818 *
4819 * So we race with normal scheduler movements, but that's OK, as long 4819 * So we race with normal scheduler movements, but that's OK, as long
4820 * as the task is no longer on this CPU. 4820 * as the task is no longer on this CPU.
4821 * 4821 *
4822 * Returns non-zero if task was successfully migrated. 4822 * Returns non-zero if task was successfully migrated.
4823 */ 4823 */
4824 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu) 4824 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4825 { 4825 {
4826 struct rq *rq; 4826 struct rq *rq;
4827 int ret = 0; 4827 int ret = 0;
4828 4828
4829 if (unlikely(!cpu_active(dest_cpu))) 4829 if (unlikely(!cpu_active(dest_cpu)))
4830 return ret; 4830 return ret;
4831 4831
4832 rq = cpu_rq(src_cpu); 4832 rq = cpu_rq(src_cpu);
4833 4833
4834 raw_spin_lock(&p->pi_lock); 4834 raw_spin_lock(&p->pi_lock);
4835 raw_spin_lock(&rq->lock); 4835 raw_spin_lock(&rq->lock);
4836 /* Already moved. */ 4836 /* Already moved. */
4837 if (task_cpu(p) != src_cpu) 4837 if (task_cpu(p) != src_cpu)
4838 goto done; 4838 goto done;
4839 4839
4840 /* Affinity changed (again). */ 4840 /* Affinity changed (again). */
4841 if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p))) 4841 if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
4842 goto fail; 4842 goto fail;
4843 4843
4844 /* 4844 /*
4845 * If we're not on a rq, the next wake-up will ensure we're 4845 * If we're not on a rq, the next wake-up will ensure we're
4846 * placed properly. 4846 * placed properly.
4847 */ 4847 */
4848 if (task_on_rq_queued(p)) 4848 if (task_on_rq_queued(p))
4849 rq = move_queued_task(p, dest_cpu); 4849 rq = move_queued_task(p, dest_cpu);
4850 done: 4850 done:
4851 ret = 1; 4851 ret = 1;
4852 fail: 4852 fail:
4853 raw_spin_unlock(&rq->lock); 4853 raw_spin_unlock(&rq->lock);
4854 raw_spin_unlock(&p->pi_lock); 4854 raw_spin_unlock(&p->pi_lock);
4855 return ret; 4855 return ret;
4856 } 4856 }
4857 4857
4858 #ifdef CONFIG_NUMA_BALANCING 4858 #ifdef CONFIG_NUMA_BALANCING
4859 /* Migrate current task p to target_cpu */ 4859 /* Migrate current task p to target_cpu */
4860 int migrate_task_to(struct task_struct *p, int target_cpu) 4860 int migrate_task_to(struct task_struct *p, int target_cpu)
4861 { 4861 {
4862 struct migration_arg arg = { p, target_cpu }; 4862 struct migration_arg arg = { p, target_cpu };
4863 int curr_cpu = task_cpu(p); 4863 int curr_cpu = task_cpu(p);
4864 4864
4865 if (curr_cpu == target_cpu) 4865 if (curr_cpu == target_cpu)
4866 return 0; 4866 return 0;
4867 4867
4868 if (!cpumask_test_cpu(target_cpu, tsk_cpus_allowed(p))) 4868 if (!cpumask_test_cpu(target_cpu, tsk_cpus_allowed(p)))
4869 return -EINVAL; 4869 return -EINVAL;
4870 4870
4871 /* TODO: This is not properly updating schedstats */ 4871 /* TODO: This is not properly updating schedstats */
4872 4872
4873 trace_sched_move_numa(p, curr_cpu, target_cpu); 4873 trace_sched_move_numa(p, curr_cpu, target_cpu);
4874 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg); 4874 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
4875 } 4875 }
4876 4876
4877 /* 4877 /*
4878 * Requeue a task on a given node and accurately track the number of NUMA 4878 * Requeue a task on a given node and accurately track the number of NUMA
4879 * tasks on the runqueues 4879 * tasks on the runqueues
4880 */ 4880 */
4881 void sched_setnuma(struct task_struct *p, int nid) 4881 void sched_setnuma(struct task_struct *p, int nid)
4882 { 4882 {
4883 struct rq *rq; 4883 struct rq *rq;
4884 unsigned long flags; 4884 unsigned long flags;
4885 bool queued, running; 4885 bool queued, running;
4886 4886
4887 rq = task_rq_lock(p, &flags); 4887 rq = task_rq_lock(p, &flags);
4888 queued = task_on_rq_queued(p); 4888 queued = task_on_rq_queued(p);
4889 running = task_current(rq, p); 4889 running = task_current(rq, p);
4890 4890
4891 if (queued) 4891 if (queued)
4892 dequeue_task(rq, p, 0); 4892 dequeue_task(rq, p, 0);
4893 if (running) 4893 if (running)
4894 put_prev_task(rq, p); 4894 put_prev_task(rq, p);
4895 4895
4896 p->numa_preferred_nid = nid; 4896 p->numa_preferred_nid = nid;
4897 4897
4898 if (running) 4898 if (running)
4899 p->sched_class->set_curr_task(rq); 4899 p->sched_class->set_curr_task(rq);
4900 if (queued) 4900 if (queued)
4901 enqueue_task(rq, p, 0); 4901 enqueue_task(rq, p, 0);
4902 task_rq_unlock(rq, p, &flags); 4902 task_rq_unlock(rq, p, &flags);
4903 } 4903 }
4904 #endif 4904 #endif
4905 4905
4906 /* 4906 /*
4907 * migration_cpu_stop - this will be executed by a highprio stopper thread 4907 * migration_cpu_stop - this will be executed by a highprio stopper thread
4908 * and performs thread migration by bumping thread off CPU then 4908 * and performs thread migration by bumping thread off CPU then
4909 * 'pushing' onto another runqueue. 4909 * 'pushing' onto another runqueue.
4910 */ 4910 */
4911 static int migration_cpu_stop(void *data) 4911 static int migration_cpu_stop(void *data)
4912 { 4912 {
4913 struct migration_arg *arg = data; 4913 struct migration_arg *arg = data;
4914 4914
4915 /* 4915 /*
4916 * The original target cpu might have gone down and we might 4916 * The original target cpu might have gone down and we might
4917 * be on another cpu but it doesn't matter. 4917 * be on another cpu but it doesn't matter.
4918 */ 4918 */
4919 local_irq_disable(); 4919 local_irq_disable();
4920 /* 4920 /*
4921 * We need to explicitly wake pending tasks before running 4921 * We need to explicitly wake pending tasks before running
4922 * __migrate_task() such that we will not miss enforcing cpus_allowed 4922 * __migrate_task() such that we will not miss enforcing cpus_allowed
4923 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test. 4923 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
4924 */ 4924 */
4925 sched_ttwu_pending(); 4925 sched_ttwu_pending();
4926 __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu); 4926 __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu);
4927 local_irq_enable(); 4927 local_irq_enable();
4928 return 0; 4928 return 0;
4929 } 4929 }
4930 4930
4931 #ifdef CONFIG_HOTPLUG_CPU 4931 #ifdef CONFIG_HOTPLUG_CPU
4932 4932
4933 /* 4933 /*
4934 * Ensures that the idle task is using init_mm right before its cpu goes 4934 * Ensures that the idle task is using init_mm right before its cpu goes
4935 * offline. 4935 * offline.
4936 */ 4936 */
4937 void idle_task_exit(void) 4937 void idle_task_exit(void)
4938 { 4938 {
4939 struct mm_struct *mm = current->active_mm; 4939 struct mm_struct *mm = current->active_mm;
4940 4940
4941 BUG_ON(cpu_online(smp_processor_id())); 4941 BUG_ON(cpu_online(smp_processor_id()));
4942 4942
4943 if (mm != &init_mm) { 4943 if (mm != &init_mm) {
4944 switch_mm(mm, &init_mm, current); 4944 switch_mm(mm, &init_mm, current);
4945 finish_arch_post_lock_switch(); 4945 finish_arch_post_lock_switch();
4946 } 4946 }
4947 mmdrop(mm); 4947 mmdrop(mm);
4948 } 4948 }
4949 4949
4950 /* 4950 /*
4951 * Since this CPU is going 'away' for a while, fold any nr_active delta 4951 * Since this CPU is going 'away' for a while, fold any nr_active delta
4952 * we might have. Assumes we're called after migrate_tasks() so that the 4952 * we might have. Assumes we're called after migrate_tasks() so that the
4953 * nr_active count is stable. 4953 * nr_active count is stable.
4954 * 4954 *
4955 * Also see the comment "Global load-average calculations". 4955 * Also see the comment "Global load-average calculations".
4956 */ 4956 */
4957 static void calc_load_migrate(struct rq *rq) 4957 static void calc_load_migrate(struct rq *rq)
4958 { 4958 {
4959 long delta = calc_load_fold_active(rq); 4959 long delta = calc_load_fold_active(rq);
4960 if (delta) 4960 if (delta)
4961 atomic_long_add(delta, &calc_load_tasks); 4961 atomic_long_add(delta, &calc_load_tasks);
4962 } 4962 }
4963 4963
4964 static void put_prev_task_fake(struct rq *rq, struct task_struct *prev) 4964 static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
4965 { 4965 {
4966 } 4966 }
4967 4967
4968 static const struct sched_class fake_sched_class = { 4968 static const struct sched_class fake_sched_class = {
4969 .put_prev_task = put_prev_task_fake, 4969 .put_prev_task = put_prev_task_fake,
4970 }; 4970 };
4971 4971
4972 static struct task_struct fake_task = { 4972 static struct task_struct fake_task = {
4973 /* 4973 /*
4974 * Avoid pull_{rt,dl}_task() 4974 * Avoid pull_{rt,dl}_task()
4975 */ 4975 */
4976 .prio = MAX_PRIO + 1, 4976 .prio = MAX_PRIO + 1,
4977 .sched_class = &fake_sched_class, 4977 .sched_class = &fake_sched_class,
4978 }; 4978 };
4979 4979
4980 /* 4980 /*
4981 * Migrate all tasks from the rq, sleeping tasks will be migrated by 4981 * Migrate all tasks from the rq, sleeping tasks will be migrated by
4982 * try_to_wake_up()->select_task_rq(). 4982 * try_to_wake_up()->select_task_rq().
4983 * 4983 *
4984 * Called with rq->lock held even though we'er in stop_machine() and 4984 * Called with rq->lock held even though we'er in stop_machine() and
4985 * there's no concurrency possible, we hold the required locks anyway 4985 * there's no concurrency possible, we hold the required locks anyway
4986 * because of lock validation efforts. 4986 * because of lock validation efforts.
4987 */ 4987 */
4988 static void migrate_tasks(unsigned int dead_cpu) 4988 static void migrate_tasks(unsigned int dead_cpu)
4989 { 4989 {
4990 struct rq *rq = cpu_rq(dead_cpu); 4990 struct rq *rq = cpu_rq(dead_cpu);
4991 struct task_struct *next, *stop = rq->stop; 4991 struct task_struct *next, *stop = rq->stop;
4992 int dest_cpu; 4992 int dest_cpu;
4993 4993
4994 /* 4994 /*
4995 * Fudge the rq selection such that the below task selection loop 4995 * Fudge the rq selection such that the below task selection loop
4996 * doesn't get stuck on the currently eligible stop task. 4996 * doesn't get stuck on the currently eligible stop task.
4997 * 4997 *
4998 * We're currently inside stop_machine() and the rq is either stuck 4998 * We're currently inside stop_machine() and the rq is either stuck
4999 * in the stop_machine_cpu_stop() loop, or we're executing this code, 4999 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5000 * either way we should never end up calling schedule() until we're 5000 * either way we should never end up calling schedule() until we're
5001 * done here. 5001 * done here.
5002 */ 5002 */
5003 rq->stop = NULL; 5003 rq->stop = NULL;
5004 5004
5005 /* 5005 /*
5006 * put_prev_task() and pick_next_task() sched 5006 * put_prev_task() and pick_next_task() sched
5007 * class method both need to have an up-to-date 5007 * class method both need to have an up-to-date
5008 * value of rq->clock[_task] 5008 * value of rq->clock[_task]
5009 */ 5009 */
5010 update_rq_clock(rq); 5010 update_rq_clock(rq);
5011 5011
5012 for ( ; ; ) { 5012 for ( ; ; ) {
5013 /* 5013 /*
5014 * There's this thread running, bail when that's the only 5014 * There's this thread running, bail when that's the only
5015 * remaining thread. 5015 * remaining thread.
5016 */ 5016 */
5017 if (rq->nr_running == 1) 5017 if (rq->nr_running == 1)
5018 break; 5018 break;
5019 5019
5020 next = pick_next_task(rq, &fake_task); 5020 next = pick_next_task(rq, &fake_task);
5021 BUG_ON(!next); 5021 BUG_ON(!next);
5022 next->sched_class->put_prev_task(rq, next); 5022 next->sched_class->put_prev_task(rq, next);
5023 5023
5024 /* Find suitable destination for @next, with force if needed. */ 5024 /* Find suitable destination for @next, with force if needed. */
5025 dest_cpu = select_fallback_rq(dead_cpu, next); 5025 dest_cpu = select_fallback_rq(dead_cpu, next);
5026 raw_spin_unlock(&rq->lock); 5026 raw_spin_unlock(&rq->lock);
5027 5027
5028 __migrate_task(next, dead_cpu, dest_cpu); 5028 __migrate_task(next, dead_cpu, dest_cpu);
5029 5029
5030 raw_spin_lock(&rq->lock); 5030 raw_spin_lock(&rq->lock);
5031 } 5031 }
5032 5032
5033 rq->stop = stop; 5033 rq->stop = stop;
5034 } 5034 }
5035 5035
5036 #endif /* CONFIG_HOTPLUG_CPU */ 5036 #endif /* CONFIG_HOTPLUG_CPU */
5037 5037
5038 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL) 5038 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5039 5039
5040 static struct ctl_table sd_ctl_dir[] = { 5040 static struct ctl_table sd_ctl_dir[] = {
5041 { 5041 {
5042 .procname = "sched_domain", 5042 .procname = "sched_domain",
5043 .mode = 0555, 5043 .mode = 0555,
5044 }, 5044 },
5045 {} 5045 {}
5046 }; 5046 };
5047 5047
5048 static struct ctl_table sd_ctl_root[] = { 5048 static struct ctl_table sd_ctl_root[] = {
5049 { 5049 {
5050 .procname = "kernel", 5050 .procname = "kernel",
5051 .mode = 0555, 5051 .mode = 0555,
5052 .child = sd_ctl_dir, 5052 .child = sd_ctl_dir,
5053 }, 5053 },
5054 {} 5054 {}
5055 }; 5055 };
5056 5056
5057 static struct ctl_table *sd_alloc_ctl_entry(int n) 5057 static struct ctl_table *sd_alloc_ctl_entry(int n)
5058 { 5058 {
5059 struct ctl_table *entry = 5059 struct ctl_table *entry =
5060 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL); 5060 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5061 5061
5062 return entry; 5062 return entry;
5063 } 5063 }
5064 5064
5065 static void sd_free_ctl_entry(struct ctl_table **tablep) 5065 static void sd_free_ctl_entry(struct ctl_table **tablep)
5066 { 5066 {
5067 struct ctl_table *entry; 5067 struct ctl_table *entry;
5068 5068
5069 /* 5069 /*
5070 * In the intermediate directories, both the child directory and 5070 * In the intermediate directories, both the child directory and
5071 * procname are dynamically allocated and could fail but the mode 5071 * procname are dynamically allocated and could fail but the mode
5072 * will always be set. In the lowest directory the names are 5072 * will always be set. In the lowest directory the names are
5073 * static strings and all have proc handlers. 5073 * static strings and all have proc handlers.
5074 */ 5074 */
5075 for (entry = *tablep; entry->mode; entry++) { 5075 for (entry = *tablep; entry->mode; entry++) {
5076 if (entry->child) 5076 if (entry->child)
5077 sd_free_ctl_entry(&entry->child); 5077 sd_free_ctl_entry(&entry->child);
5078 if (entry->proc_handler == NULL) 5078 if (entry->proc_handler == NULL)
5079 kfree(entry->procname); 5079 kfree(entry->procname);
5080 } 5080 }
5081 5081
5082 kfree(*tablep); 5082 kfree(*tablep);
5083 *tablep = NULL; 5083 *tablep = NULL;
5084 } 5084 }
5085 5085
5086 static int min_load_idx = 0; 5086 static int min_load_idx = 0;
5087 static int max_load_idx = CPU_LOAD_IDX_MAX-1; 5087 static int max_load_idx = CPU_LOAD_IDX_MAX-1;
5088 5088
5089 static void 5089 static void
5090 set_table_entry(struct ctl_table *entry, 5090 set_table_entry(struct ctl_table *entry,
5091 const char *procname, void *data, int maxlen, 5091 const char *procname, void *data, int maxlen,
5092 umode_t mode, proc_handler *proc_handler, 5092 umode_t mode, proc_handler *proc_handler,
5093 bool load_idx) 5093 bool load_idx)
5094 { 5094 {
5095 entry->procname = procname; 5095 entry->procname = procname;
5096 entry->data = data; 5096 entry->data = data;
5097 entry->maxlen = maxlen; 5097 entry->maxlen = maxlen;
5098 entry->mode = mode; 5098 entry->mode = mode;
5099 entry->proc_handler = proc_handler; 5099 entry->proc_handler = proc_handler;
5100 5100
5101 if (load_idx) { 5101 if (load_idx) {
5102 entry->extra1 = &min_load_idx; 5102 entry->extra1 = &min_load_idx;
5103 entry->extra2 = &max_load_idx; 5103 entry->extra2 = &max_load_idx;
5104 } 5104 }
5105 } 5105 }
5106 5106
5107 static struct ctl_table * 5107 static struct ctl_table *
5108 sd_alloc_ctl_domain_table(struct sched_domain *sd) 5108 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5109 { 5109 {
5110 struct ctl_table *table = sd_alloc_ctl_entry(14); 5110 struct ctl_table *table = sd_alloc_ctl_entry(14);
5111 5111
5112 if (table == NULL) 5112 if (table == NULL)
5113 return NULL; 5113 return NULL;
5114 5114
5115 set_table_entry(&table[0], "min_interval", &sd->min_interval, 5115 set_table_entry(&table[0], "min_interval", &sd->min_interval,
5116 sizeof(long), 0644, proc_doulongvec_minmax, false); 5116 sizeof(long), 0644, proc_doulongvec_minmax, false);
5117 set_table_entry(&table[1], "max_interval", &sd->max_interval, 5117 set_table_entry(&table[1], "max_interval", &sd->max_interval,
5118 sizeof(long), 0644, proc_doulongvec_minmax, false); 5118 sizeof(long), 0644, proc_doulongvec_minmax, false);
5119 set_table_entry(&table[2], "busy_idx", &sd->busy_idx, 5119 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5120 sizeof(int), 0644, proc_dointvec_minmax, true); 5120 sizeof(int), 0644, proc_dointvec_minmax, true);
5121 set_table_entry(&table[3], "idle_idx", &sd->idle_idx, 5121 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5122 sizeof(int), 0644, proc_dointvec_minmax, true); 5122 sizeof(int), 0644, proc_dointvec_minmax, true);
5123 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx, 5123 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5124 sizeof(int), 0644, proc_dointvec_minmax, true); 5124 sizeof(int), 0644, proc_dointvec_minmax, true);
5125 set_table_entry(&table[5], "wake_idx", &sd->wake_idx, 5125 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5126 sizeof(int), 0644, proc_dointvec_minmax, true); 5126 sizeof(int), 0644, proc_dointvec_minmax, true);
5127 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx, 5127 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5128 sizeof(int), 0644, proc_dointvec_minmax, true); 5128 sizeof(int), 0644, proc_dointvec_minmax, true);
5129 set_table_entry(&table[7], "busy_factor", &sd->busy_factor, 5129 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5130 sizeof(int), 0644, proc_dointvec_minmax, false); 5130 sizeof(int), 0644, proc_dointvec_minmax, false);
5131 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct, 5131 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5132 sizeof(int), 0644, proc_dointvec_minmax, false); 5132 sizeof(int), 0644, proc_dointvec_minmax, false);
5133 set_table_entry(&table[9], "cache_nice_tries", 5133 set_table_entry(&table[9], "cache_nice_tries",
5134 &sd->cache_nice_tries, 5134 &sd->cache_nice_tries,
5135 sizeof(int), 0644, proc_dointvec_minmax, false); 5135 sizeof(int), 0644, proc_dointvec_minmax, false);
5136 set_table_entry(&table[10], "flags", &sd->flags, 5136 set_table_entry(&table[10], "flags", &sd->flags,
5137 sizeof(int), 0644, proc_dointvec_minmax, false); 5137 sizeof(int), 0644, proc_dointvec_minmax, false);
5138 set_table_entry(&table[11], "max_newidle_lb_cost", 5138 set_table_entry(&table[11], "max_newidle_lb_cost",
5139 &sd->max_newidle_lb_cost, 5139 &sd->max_newidle_lb_cost,
5140 sizeof(long), 0644, proc_doulongvec_minmax, false); 5140 sizeof(long), 0644, proc_doulongvec_minmax, false);
5141 set_table_entry(&table[12], "name", sd->name, 5141 set_table_entry(&table[12], "name", sd->name,
5142 CORENAME_MAX_SIZE, 0444, proc_dostring, false); 5142 CORENAME_MAX_SIZE, 0444, proc_dostring, false);
5143 /* &table[13] is terminator */ 5143 /* &table[13] is terminator */
5144 5144
5145 return table; 5145 return table;
5146 } 5146 }
5147 5147
5148 static struct ctl_table *sd_alloc_ctl_cpu_table(int cpu) 5148 static struct ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5149 { 5149 {
5150 struct ctl_table *entry, *table; 5150 struct ctl_table *entry, *table;
5151 struct sched_domain *sd; 5151 struct sched_domain *sd;
5152 int domain_num = 0, i; 5152 int domain_num = 0, i;
5153 char buf[32]; 5153 char buf[32];
5154 5154
5155 for_each_domain(cpu, sd) 5155 for_each_domain(cpu, sd)
5156 domain_num++; 5156 domain_num++;
5157 entry = table = sd_alloc_ctl_entry(domain_num + 1); 5157 entry = table = sd_alloc_ctl_entry(domain_num + 1);
5158 if (table == NULL) 5158 if (table == NULL)
5159 return NULL; 5159 return NULL;
5160 5160
5161 i = 0; 5161 i = 0;
5162 for_each_domain(cpu, sd) { 5162 for_each_domain(cpu, sd) {
5163 snprintf(buf, 32, "domain%d", i); 5163 snprintf(buf, 32, "domain%d", i);
5164 entry->procname = kstrdup(buf, GFP_KERNEL); 5164 entry->procname = kstrdup(buf, GFP_KERNEL);
5165 entry->mode = 0555; 5165 entry->mode = 0555;
5166 entry->child = sd_alloc_ctl_domain_table(sd); 5166 entry->child = sd_alloc_ctl_domain_table(sd);
5167 entry++; 5167 entry++;
5168 i++; 5168 i++;
5169 } 5169 }
5170 return table; 5170 return table;
5171 } 5171 }
5172 5172
5173 static struct ctl_table_header *sd_sysctl_header; 5173 static struct ctl_table_header *sd_sysctl_header;
5174 static void register_sched_domain_sysctl(void) 5174 static void register_sched_domain_sysctl(void)
5175 { 5175 {
5176 int i, cpu_num = num_possible_cpus(); 5176 int i, cpu_num = num_possible_cpus();
5177 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1); 5177 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5178 char buf[32]; 5178 char buf[32];
5179 5179
5180 WARN_ON(sd_ctl_dir[0].child); 5180 WARN_ON(sd_ctl_dir[0].child);
5181 sd_ctl_dir[0].child = entry; 5181 sd_ctl_dir[0].child = entry;
5182 5182
5183 if (entry == NULL) 5183 if (entry == NULL)
5184 return; 5184 return;
5185 5185
5186 for_each_possible_cpu(i) { 5186 for_each_possible_cpu(i) {
5187 snprintf(buf, 32, "cpu%d", i); 5187 snprintf(buf, 32, "cpu%d", i);
5188 entry->procname = kstrdup(buf, GFP_KERNEL); 5188 entry->procname = kstrdup(buf, GFP_KERNEL);
5189 entry->mode = 0555; 5189 entry->mode = 0555;
5190 entry->child = sd_alloc_ctl_cpu_table(i); 5190 entry->child = sd_alloc_ctl_cpu_table(i);
5191 entry++; 5191 entry++;
5192 } 5192 }
5193 5193
5194 WARN_ON(sd_sysctl_header); 5194 WARN_ON(sd_sysctl_header);
5195 sd_sysctl_header = register_sysctl_table(sd_ctl_root); 5195 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5196 } 5196 }
5197 5197
5198 /* may be called multiple times per register */ 5198 /* may be called multiple times per register */
5199 static void unregister_sched_domain_sysctl(void) 5199 static void unregister_sched_domain_sysctl(void)
5200 { 5200 {
5201 if (sd_sysctl_header) 5201 if (sd_sysctl_header)
5202 unregister_sysctl_table(sd_sysctl_header); 5202 unregister_sysctl_table(sd_sysctl_header);
5203 sd_sysctl_header = NULL; 5203 sd_sysctl_header = NULL;
5204 if (sd_ctl_dir[0].child) 5204 if (sd_ctl_dir[0].child)
5205 sd_free_ctl_entry(&sd_ctl_dir[0].child); 5205 sd_free_ctl_entry(&sd_ctl_dir[0].child);
5206 } 5206 }
5207 #else 5207 #else
5208 static void register_sched_domain_sysctl(void) 5208 static void register_sched_domain_sysctl(void)
5209 { 5209 {
5210 } 5210 }
5211 static void unregister_sched_domain_sysctl(void) 5211 static void unregister_sched_domain_sysctl(void)
5212 { 5212 {
5213 } 5213 }
5214 #endif 5214 #endif
5215 5215
5216 static void set_rq_online(struct rq *rq) 5216 static void set_rq_online(struct rq *rq)
5217 { 5217 {
5218 if (!rq->online) { 5218 if (!rq->online) {
5219 const struct sched_class *class; 5219 const struct sched_class *class;
5220 5220
5221 cpumask_set_cpu(rq->cpu, rq->rd->online); 5221 cpumask_set_cpu(rq->cpu, rq->rd->online);
5222 rq->online = 1; 5222 rq->online = 1;
5223 5223
5224 for_each_class(class) { 5224 for_each_class(class) {
5225 if (class->rq_online) 5225 if (class->rq_online)
5226 class->rq_online(rq); 5226 class->rq_online(rq);
5227 } 5227 }
5228 } 5228 }
5229 } 5229 }
5230 5230
5231 static void set_rq_offline(struct rq *rq) 5231 static void set_rq_offline(struct rq *rq)
5232 { 5232 {
5233 if (rq->online) { 5233 if (rq->online) {
5234 const struct sched_class *class; 5234 const struct sched_class *class;
5235 5235
5236 for_each_class(class) { 5236 for_each_class(class) {
5237 if (class->rq_offline) 5237 if (class->rq_offline)
5238 class->rq_offline(rq); 5238 class->rq_offline(rq);
5239 } 5239 }
5240 5240
5241 cpumask_clear_cpu(rq->cpu, rq->rd->online); 5241 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5242 rq->online = 0; 5242 rq->online = 0;
5243 } 5243 }
5244 } 5244 }
5245 5245
5246 /* 5246 /*
5247 * migration_call - callback that gets triggered when a CPU is added. 5247 * migration_call - callback that gets triggered when a CPU is added.
5248 * Here we can start up the necessary migration thread for the new CPU. 5248 * Here we can start up the necessary migration thread for the new CPU.
5249 */ 5249 */
5250 static int 5250 static int
5251 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu) 5251 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5252 { 5252 {
5253 int cpu = (long)hcpu; 5253 int cpu = (long)hcpu;
5254 unsigned long flags; 5254 unsigned long flags;
5255 struct rq *rq = cpu_rq(cpu); 5255 struct rq *rq = cpu_rq(cpu);
5256 5256
5257 switch (action & ~CPU_TASKS_FROZEN) { 5257 switch (action & ~CPU_TASKS_FROZEN) {
5258 5258
5259 case CPU_UP_PREPARE: 5259 case CPU_UP_PREPARE:
5260 rq->calc_load_update = calc_load_update; 5260 rq->calc_load_update = calc_load_update;
5261 break; 5261 break;
5262 5262
5263 case CPU_ONLINE: 5263 case CPU_ONLINE:
5264 /* Update our root-domain */ 5264 /* Update our root-domain */
5265 raw_spin_lock_irqsave(&rq->lock, flags); 5265 raw_spin_lock_irqsave(&rq->lock, flags);
5266 if (rq->rd) { 5266 if (rq->rd) {
5267 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span)); 5267 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5268 5268
5269 set_rq_online(rq); 5269 set_rq_online(rq);
5270 } 5270 }
5271 raw_spin_unlock_irqrestore(&rq->lock, flags); 5271 raw_spin_unlock_irqrestore(&rq->lock, flags);
5272 break; 5272 break;
5273 5273
5274 #ifdef CONFIG_HOTPLUG_CPU 5274 #ifdef CONFIG_HOTPLUG_CPU
5275 case CPU_DYING: 5275 case CPU_DYING:
5276 sched_ttwu_pending(); 5276 sched_ttwu_pending();
5277 /* Update our root-domain */ 5277 /* Update our root-domain */
5278 raw_spin_lock_irqsave(&rq->lock, flags); 5278 raw_spin_lock_irqsave(&rq->lock, flags);
5279 if (rq->rd) { 5279 if (rq->rd) {
5280 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span)); 5280 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5281 set_rq_offline(rq); 5281 set_rq_offline(rq);
5282 } 5282 }
5283 migrate_tasks(cpu); 5283 migrate_tasks(cpu);
5284 BUG_ON(rq->nr_running != 1); /* the migration thread */ 5284 BUG_ON(rq->nr_running != 1); /* the migration thread */
5285 raw_spin_unlock_irqrestore(&rq->lock, flags); 5285 raw_spin_unlock_irqrestore(&rq->lock, flags);
5286 break; 5286 break;
5287 5287
5288 case CPU_DEAD: 5288 case CPU_DEAD:
5289 calc_load_migrate(rq); 5289 calc_load_migrate(rq);
5290 break; 5290 break;
5291 #endif 5291 #endif
5292 } 5292 }
5293 5293
5294 update_max_interval(); 5294 update_max_interval();
5295 5295
5296 return NOTIFY_OK; 5296 return NOTIFY_OK;
5297 } 5297 }
5298 5298
5299 /* 5299 /*
5300 * Register at high priority so that task migration (migrate_all_tasks) 5300 * Register at high priority so that task migration (migrate_all_tasks)
5301 * happens before everything else. This has to be lower priority than 5301 * happens before everything else. This has to be lower priority than
5302 * the notifier in the perf_event subsystem, though. 5302 * the notifier in the perf_event subsystem, though.
5303 */ 5303 */
5304 static struct notifier_block migration_notifier = { 5304 static struct notifier_block migration_notifier = {
5305 .notifier_call = migration_call, 5305 .notifier_call = migration_call,
5306 .priority = CPU_PRI_MIGRATION, 5306 .priority = CPU_PRI_MIGRATION,
5307 }; 5307 };
5308 5308
5309 static void __cpuinit set_cpu_rq_start_time(void) 5309 static void __cpuinit set_cpu_rq_start_time(void)
5310 { 5310 {
5311 int cpu = smp_processor_id(); 5311 int cpu = smp_processor_id();
5312 struct rq *rq = cpu_rq(cpu); 5312 struct rq *rq = cpu_rq(cpu);
5313 rq->age_stamp = sched_clock_cpu(cpu); 5313 rq->age_stamp = sched_clock_cpu(cpu);
5314 } 5314 }
5315 5315
5316 static int sched_cpu_active(struct notifier_block *nfb, 5316 static int sched_cpu_active(struct notifier_block *nfb,
5317 unsigned long action, void *hcpu) 5317 unsigned long action, void *hcpu)
5318 { 5318 {
5319 switch (action & ~CPU_TASKS_FROZEN) { 5319 switch (action & ~CPU_TASKS_FROZEN) {
5320 case CPU_STARTING: 5320 case CPU_STARTING:
5321 set_cpu_rq_start_time(); 5321 set_cpu_rq_start_time();
5322 return NOTIFY_OK; 5322 return NOTIFY_OK;
5323 case CPU_DOWN_FAILED: 5323 case CPU_DOWN_FAILED:
5324 set_cpu_active((long)hcpu, true); 5324 set_cpu_active((long)hcpu, true);
5325 return NOTIFY_OK; 5325 return NOTIFY_OK;
5326 default: 5326 default:
5327 return NOTIFY_DONE; 5327 return NOTIFY_DONE;
5328 } 5328 }
5329 } 5329 }
5330 5330
5331 static int sched_cpu_inactive(struct notifier_block *nfb, 5331 static int sched_cpu_inactive(struct notifier_block *nfb,
5332 unsigned long action, void *hcpu) 5332 unsigned long action, void *hcpu)
5333 { 5333 {
5334 unsigned long flags; 5334 unsigned long flags;
5335 long cpu = (long)hcpu; 5335 long cpu = (long)hcpu;
5336 struct dl_bw *dl_b; 5336 struct dl_bw *dl_b;
5337 5337
5338 switch (action & ~CPU_TASKS_FROZEN) { 5338 switch (action & ~CPU_TASKS_FROZEN) {
5339 case CPU_DOWN_PREPARE: 5339 case CPU_DOWN_PREPARE:
5340 set_cpu_active(cpu, false); 5340 set_cpu_active(cpu, false);
5341 5341
5342 /* explicitly allow suspend */ 5342 /* explicitly allow suspend */
5343 if (!(action & CPU_TASKS_FROZEN)) { 5343 if (!(action & CPU_TASKS_FROZEN)) {
5344 bool overflow; 5344 bool overflow;
5345 int cpus; 5345 int cpus;
5346 5346
5347 rcu_read_lock_sched(); 5347 rcu_read_lock_sched();
5348 dl_b = dl_bw_of(cpu); 5348 dl_b = dl_bw_of(cpu);
5349 5349
5350 raw_spin_lock_irqsave(&dl_b->lock, flags); 5350 raw_spin_lock_irqsave(&dl_b->lock, flags);
5351 cpus = dl_bw_cpus(cpu); 5351 cpus = dl_bw_cpus(cpu);
5352 overflow = __dl_overflow(dl_b, cpus, 0, 0); 5352 overflow = __dl_overflow(dl_b, cpus, 0, 0);
5353 raw_spin_unlock_irqrestore(&dl_b->lock, flags); 5353 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
5354 5354
5355 rcu_read_unlock_sched(); 5355 rcu_read_unlock_sched();
5356 5356
5357 if (overflow) 5357 if (overflow)
5358 return notifier_from_errno(-EBUSY); 5358 return notifier_from_errno(-EBUSY);
5359 } 5359 }
5360 return NOTIFY_OK; 5360 return NOTIFY_OK;
5361 } 5361 }
5362 5362
5363 return NOTIFY_DONE; 5363 return NOTIFY_DONE;
5364 } 5364 }
5365 5365
5366 static int __init migration_init(void) 5366 static int __init migration_init(void)
5367 { 5367 {
5368 void *cpu = (void *)(long)smp_processor_id(); 5368 void *cpu = (void *)(long)smp_processor_id();
5369 int err; 5369 int err;
5370 5370
5371 /* Initialize migration for the boot CPU */ 5371 /* Initialize migration for the boot CPU */
5372 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu); 5372 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5373 BUG_ON(err == NOTIFY_BAD); 5373 BUG_ON(err == NOTIFY_BAD);
5374 migration_call(&migration_notifier, CPU_ONLINE, cpu); 5374 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5375 register_cpu_notifier(&migration_notifier); 5375 register_cpu_notifier(&migration_notifier);
5376 5376
5377 /* Register cpu active notifiers */ 5377 /* Register cpu active notifiers */
5378 cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE); 5378 cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
5379 cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE); 5379 cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
5380 5380
5381 return 0; 5381 return 0;
5382 } 5382 }
5383 early_initcall(migration_init); 5383 early_initcall(migration_init);
5384 #endif 5384 #endif
5385 5385
5386 #ifdef CONFIG_SMP 5386 #ifdef CONFIG_SMP
5387 5387
5388 static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */ 5388 static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
5389 5389
5390 #ifdef CONFIG_SCHED_DEBUG 5390 #ifdef CONFIG_SCHED_DEBUG
5391 5391
5392 static __read_mostly int sched_debug_enabled; 5392 static __read_mostly int sched_debug_enabled;
5393 5393
5394 static int __init sched_debug_setup(char *str) 5394 static int __init sched_debug_setup(char *str)
5395 { 5395 {
5396 sched_debug_enabled = 1; 5396 sched_debug_enabled = 1;
5397 5397
5398 return 0; 5398 return 0;
5399 } 5399 }
5400 early_param("sched_debug", sched_debug_setup); 5400 early_param("sched_debug", sched_debug_setup);
5401 5401
5402 static inline bool sched_debug(void) 5402 static inline bool sched_debug(void)
5403 { 5403 {
5404 return sched_debug_enabled; 5404 return sched_debug_enabled;
5405 } 5405 }
5406 5406
5407 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level, 5407 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
5408 struct cpumask *groupmask) 5408 struct cpumask *groupmask)
5409 { 5409 {
5410 struct sched_group *group = sd->groups; 5410 struct sched_group *group = sd->groups;
5411 char str[256]; 5411 char str[256];
5412 5412
5413 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd)); 5413 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
5414 cpumask_clear(groupmask); 5414 cpumask_clear(groupmask);
5415 5415
5416 printk(KERN_DEBUG "%*s domain %d: ", level, "", level); 5416 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
5417 5417
5418 if (!(sd->flags & SD_LOAD_BALANCE)) { 5418 if (!(sd->flags & SD_LOAD_BALANCE)) {
5419 printk("does not load-balance\n"); 5419 printk("does not load-balance\n");
5420 if (sd->parent) 5420 if (sd->parent)
5421 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain" 5421 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5422 " has parent"); 5422 " has parent");
5423 return -1; 5423 return -1;
5424 } 5424 }
5425 5425
5426 printk(KERN_CONT "span %s level %s\n", str, sd->name); 5426 printk(KERN_CONT "span %s level %s\n", str, sd->name);
5427 5427
5428 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) { 5428 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
5429 printk(KERN_ERR "ERROR: domain->span does not contain " 5429 printk(KERN_ERR "ERROR: domain->span does not contain "
5430 "CPU%d\n", cpu); 5430 "CPU%d\n", cpu);
5431 } 5431 }
5432 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) { 5432 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
5433 printk(KERN_ERR "ERROR: domain->groups does not contain" 5433 printk(KERN_ERR "ERROR: domain->groups does not contain"
5434 " CPU%d\n", cpu); 5434 " CPU%d\n", cpu);
5435 } 5435 }
5436 5436
5437 printk(KERN_DEBUG "%*s groups:", level + 1, ""); 5437 printk(KERN_DEBUG "%*s groups:", level + 1, "");
5438 do { 5438 do {
5439 if (!group) { 5439 if (!group) {
5440 printk("\n"); 5440 printk("\n");
5441 printk(KERN_ERR "ERROR: group is NULL\n"); 5441 printk(KERN_ERR "ERROR: group is NULL\n");
5442 break; 5442 break;
5443 } 5443 }
5444 5444
5445 /* 5445 /*
5446 * Even though we initialize ->capacity to something semi-sane, 5446 * Even though we initialize ->capacity to something semi-sane,
5447 * we leave capacity_orig unset. This allows us to detect if 5447 * we leave capacity_orig unset. This allows us to detect if
5448 * domain iteration is still funny without causing /0 traps. 5448 * domain iteration is still funny without causing /0 traps.
5449 */ 5449 */
5450 if (!group->sgc->capacity_orig) { 5450 if (!group->sgc->capacity_orig) {
5451 printk(KERN_CONT "\n"); 5451 printk(KERN_CONT "\n");
5452 printk(KERN_ERR "ERROR: domain->cpu_capacity not set\n"); 5452 printk(KERN_ERR "ERROR: domain->cpu_capacity not set\n");
5453 break; 5453 break;
5454 } 5454 }
5455 5455
5456 if (!cpumask_weight(sched_group_cpus(group))) { 5456 if (!cpumask_weight(sched_group_cpus(group))) {
5457 printk(KERN_CONT "\n"); 5457 printk(KERN_CONT "\n");
5458 printk(KERN_ERR "ERROR: empty group\n"); 5458 printk(KERN_ERR "ERROR: empty group\n");
5459 break; 5459 break;
5460 } 5460 }
5461 5461
5462 if (!(sd->flags & SD_OVERLAP) && 5462 if (!(sd->flags & SD_OVERLAP) &&
5463 cpumask_intersects(groupmask, sched_group_cpus(group))) { 5463 cpumask_intersects(groupmask, sched_group_cpus(group))) {
5464 printk(KERN_CONT "\n"); 5464 printk(KERN_CONT "\n");
5465 printk(KERN_ERR "ERROR: repeated CPUs\n"); 5465 printk(KERN_ERR "ERROR: repeated CPUs\n");
5466 break; 5466 break;
5467 } 5467 }
5468 5468
5469 cpumask_or(groupmask, groupmask, sched_group_cpus(group)); 5469 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
5470 5470
5471 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group)); 5471 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
5472 5472
5473 printk(KERN_CONT " %s", str); 5473 printk(KERN_CONT " %s", str);
5474 if (group->sgc->capacity != SCHED_CAPACITY_SCALE) { 5474 if (group->sgc->capacity != SCHED_CAPACITY_SCALE) {
5475 printk(KERN_CONT " (cpu_capacity = %d)", 5475 printk(KERN_CONT " (cpu_capacity = %d)",
5476 group->sgc->capacity); 5476 group->sgc->capacity);
5477 } 5477 }
5478 5478
5479 group = group->next; 5479 group = group->next;
5480 } while (group != sd->groups); 5480 } while (group != sd->groups);
5481 printk(KERN_CONT "\n"); 5481 printk(KERN_CONT "\n");
5482 5482
5483 if (!cpumask_equal(sched_domain_span(sd), groupmask)) 5483 if (!cpumask_equal(sched_domain_span(sd), groupmask))
5484 printk(KERN_ERR "ERROR: groups don't span domain->span\n"); 5484 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5485 5485
5486 if (sd->parent && 5486 if (sd->parent &&
5487 !cpumask_subset(groupmask, sched_domain_span(sd->parent))) 5487 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
5488 printk(KERN_ERR "ERROR: parent span is not a superset " 5488 printk(KERN_ERR "ERROR: parent span is not a superset "
5489 "of domain->span\n"); 5489 "of domain->span\n");
5490 return 0; 5490 return 0;
5491 } 5491 }
5492 5492
5493 static void sched_domain_debug(struct sched_domain *sd, int cpu) 5493 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5494 { 5494 {
5495 int level = 0; 5495 int level = 0;
5496 5496
5497 if (!sched_debug_enabled) 5497 if (!sched_debug_enabled)
5498 return; 5498 return;
5499 5499
5500 if (!sd) { 5500 if (!sd) {
5501 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu); 5501 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5502 return; 5502 return;
5503 } 5503 }
5504 5504
5505 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu); 5505 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5506 5506
5507 for (;;) { 5507 for (;;) {
5508 if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask)) 5508 if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
5509 break; 5509 break;
5510 level++; 5510 level++;
5511 sd = sd->parent; 5511 sd = sd->parent;
5512 if (!sd) 5512 if (!sd)
5513 break; 5513 break;
5514 } 5514 }
5515 } 5515 }
5516 #else /* !CONFIG_SCHED_DEBUG */ 5516 #else /* !CONFIG_SCHED_DEBUG */
5517 # define sched_domain_debug(sd, cpu) do { } while (0) 5517 # define sched_domain_debug(sd, cpu) do { } while (0)
5518 static inline bool sched_debug(void) 5518 static inline bool sched_debug(void)
5519 { 5519 {
5520 return false; 5520 return false;
5521 } 5521 }
5522 #endif /* CONFIG_SCHED_DEBUG */ 5522 #endif /* CONFIG_SCHED_DEBUG */
5523 5523
5524 static int sd_degenerate(struct sched_domain *sd) 5524 static int sd_degenerate(struct sched_domain *sd)
5525 { 5525 {
5526 if (cpumask_weight(sched_domain_span(sd)) == 1) 5526 if (cpumask_weight(sched_domain_span(sd)) == 1)
5527 return 1; 5527 return 1;
5528 5528
5529 /* Following flags need at least 2 groups */ 5529 /* Following flags need at least 2 groups */
5530 if (sd->flags & (SD_LOAD_BALANCE | 5530 if (sd->flags & (SD_LOAD_BALANCE |
5531 SD_BALANCE_NEWIDLE | 5531 SD_BALANCE_NEWIDLE |
5532 SD_BALANCE_FORK | 5532 SD_BALANCE_FORK |
5533 SD_BALANCE_EXEC | 5533 SD_BALANCE_EXEC |
5534 SD_SHARE_CPUCAPACITY | 5534 SD_SHARE_CPUCAPACITY |
5535 SD_SHARE_PKG_RESOURCES | 5535 SD_SHARE_PKG_RESOURCES |
5536 SD_SHARE_POWERDOMAIN)) { 5536 SD_SHARE_POWERDOMAIN)) {
5537 if (sd->groups != sd->groups->next) 5537 if (sd->groups != sd->groups->next)
5538 return 0; 5538 return 0;
5539 } 5539 }
5540 5540
5541 /* Following flags don't use groups */ 5541 /* Following flags don't use groups */
5542 if (sd->flags & (SD_WAKE_AFFINE)) 5542 if (sd->flags & (SD_WAKE_AFFINE))
5543 return 0; 5543 return 0;
5544 5544
5545 return 1; 5545 return 1;
5546 } 5546 }
5547 5547
5548 static int 5548 static int
5549 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent) 5549 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5550 { 5550 {
5551 unsigned long cflags = sd->flags, pflags = parent->flags; 5551 unsigned long cflags = sd->flags, pflags = parent->flags;
5552 5552
5553 if (sd_degenerate(parent)) 5553 if (sd_degenerate(parent))
5554 return 1; 5554 return 1;
5555 5555
5556 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent))) 5556 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
5557 return 0; 5557 return 0;
5558 5558
5559 /* Flags needing groups don't count if only 1 group in parent */ 5559 /* Flags needing groups don't count if only 1 group in parent */
5560 if (parent->groups == parent->groups->next) { 5560 if (parent->groups == parent->groups->next) {
5561 pflags &= ~(SD_LOAD_BALANCE | 5561 pflags &= ~(SD_LOAD_BALANCE |
5562 SD_BALANCE_NEWIDLE | 5562 SD_BALANCE_NEWIDLE |
5563 SD_BALANCE_FORK | 5563 SD_BALANCE_FORK |
5564 SD_BALANCE_EXEC | 5564 SD_BALANCE_EXEC |
5565 SD_SHARE_CPUCAPACITY | 5565 SD_SHARE_CPUCAPACITY |
5566 SD_SHARE_PKG_RESOURCES | 5566 SD_SHARE_PKG_RESOURCES |
5567 SD_PREFER_SIBLING | 5567 SD_PREFER_SIBLING |
5568 SD_SHARE_POWERDOMAIN); 5568 SD_SHARE_POWERDOMAIN);
5569 if (nr_node_ids == 1) 5569 if (nr_node_ids == 1)
5570 pflags &= ~SD_SERIALIZE; 5570 pflags &= ~SD_SERIALIZE;
5571 } 5571 }
5572 if (~cflags & pflags) 5572 if (~cflags & pflags)
5573 return 0; 5573 return 0;
5574 5574
5575 return 1; 5575 return 1;
5576 } 5576 }
5577 5577
5578 static void free_rootdomain(struct rcu_head *rcu) 5578 static void free_rootdomain(struct rcu_head *rcu)
5579 { 5579 {
5580 struct root_domain *rd = container_of(rcu, struct root_domain, rcu); 5580 struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
5581 5581
5582 cpupri_cleanup(&rd->cpupri); 5582 cpupri_cleanup(&rd->cpupri);
5583 cpudl_cleanup(&rd->cpudl); 5583 cpudl_cleanup(&rd->cpudl);
5584 free_cpumask_var(rd->dlo_mask); 5584 free_cpumask_var(rd->dlo_mask);
5585 free_cpumask_var(rd->rto_mask); 5585 free_cpumask_var(rd->rto_mask);
5586 free_cpumask_var(rd->online); 5586 free_cpumask_var(rd->online);
5587 free_cpumask_var(rd->span); 5587 free_cpumask_var(rd->span);
5588 kfree(rd); 5588 kfree(rd);
5589 } 5589 }
5590 5590
5591 static void rq_attach_root(struct rq *rq, struct root_domain *rd) 5591 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
5592 { 5592 {
5593 struct root_domain *old_rd = NULL; 5593 struct root_domain *old_rd = NULL;
5594 unsigned long flags; 5594 unsigned long flags;
5595 5595
5596 raw_spin_lock_irqsave(&rq->lock, flags); 5596 raw_spin_lock_irqsave(&rq->lock, flags);
5597 5597
5598 if (rq->rd) { 5598 if (rq->rd) {
5599 old_rd = rq->rd; 5599 old_rd = rq->rd;
5600 5600
5601 if (cpumask_test_cpu(rq->cpu, old_rd->online)) 5601 if (cpumask_test_cpu(rq->cpu, old_rd->online))
5602 set_rq_offline(rq); 5602 set_rq_offline(rq);
5603 5603
5604 cpumask_clear_cpu(rq->cpu, old_rd->span); 5604 cpumask_clear_cpu(rq->cpu, old_rd->span);
5605 5605
5606 /* 5606 /*
5607 * If we dont want to free the old_rd yet then 5607 * If we dont want to free the old_rd yet then
5608 * set old_rd to NULL to skip the freeing later 5608 * set old_rd to NULL to skip the freeing later
5609 * in this function: 5609 * in this function:
5610 */ 5610 */
5611 if (!atomic_dec_and_test(&old_rd->refcount)) 5611 if (!atomic_dec_and_test(&old_rd->refcount))
5612 old_rd = NULL; 5612 old_rd = NULL;
5613 } 5613 }
5614 5614
5615 atomic_inc(&rd->refcount); 5615 atomic_inc(&rd->refcount);
5616 rq->rd = rd; 5616 rq->rd = rd;
5617 5617
5618 cpumask_set_cpu(rq->cpu, rd->span); 5618 cpumask_set_cpu(rq->cpu, rd->span);
5619 if (cpumask_test_cpu(rq->cpu, cpu_active_mask)) 5619 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
5620 set_rq_online(rq); 5620 set_rq_online(rq);
5621 5621
5622 raw_spin_unlock_irqrestore(&rq->lock, flags); 5622 raw_spin_unlock_irqrestore(&rq->lock, flags);
5623 5623
5624 if (old_rd) 5624 if (old_rd)
5625 call_rcu_sched(&old_rd->rcu, free_rootdomain); 5625 call_rcu_sched(&old_rd->rcu, free_rootdomain);
5626 } 5626 }
5627 5627
5628 static int init_rootdomain(struct root_domain *rd) 5628 static int init_rootdomain(struct root_domain *rd)
5629 { 5629 {
5630 memset(rd, 0, sizeof(*rd)); 5630 memset(rd, 0, sizeof(*rd));
5631 5631
5632 if (!alloc_cpumask_var(&rd->span, GFP_KERNEL)) 5632 if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
5633 goto out; 5633 goto out;
5634 if (!alloc_cpumask_var(&rd->online, GFP_KERNEL)) 5634 if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
5635 goto free_span; 5635 goto free_span;
5636 if (!alloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL)) 5636 if (!alloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL))
5637 goto free_online; 5637 goto free_online;
5638 if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL)) 5638 if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
5639 goto free_dlo_mask; 5639 goto free_dlo_mask;
5640 5640
5641 init_dl_bw(&rd->dl_bw); 5641 init_dl_bw(&rd->dl_bw);
5642 if (cpudl_init(&rd->cpudl) != 0) 5642 if (cpudl_init(&rd->cpudl) != 0)
5643 goto free_dlo_mask; 5643 goto free_dlo_mask;
5644 5644
5645 if (cpupri_init(&rd->cpupri) != 0) 5645 if (cpupri_init(&rd->cpupri) != 0)
5646 goto free_rto_mask; 5646 goto free_rto_mask;
5647 return 0; 5647 return 0;
5648 5648
5649 free_rto_mask: 5649 free_rto_mask:
5650 free_cpumask_var(rd->rto_mask); 5650 free_cpumask_var(rd->rto_mask);
5651 free_dlo_mask: 5651 free_dlo_mask:
5652 free_cpumask_var(rd->dlo_mask); 5652 free_cpumask_var(rd->dlo_mask);
5653 free_online: 5653 free_online:
5654 free_cpumask_var(rd->online); 5654 free_cpumask_var(rd->online);
5655 free_span: 5655 free_span:
5656 free_cpumask_var(rd->span); 5656 free_cpumask_var(rd->span);
5657 out: 5657 out:
5658 return -ENOMEM; 5658 return -ENOMEM;
5659 } 5659 }
5660 5660
5661 /* 5661 /*
5662 * By default the system creates a single root-domain with all cpus as 5662 * By default the system creates a single root-domain with all cpus as
5663 * members (mimicking the global state we have today). 5663 * members (mimicking the global state we have today).
5664 */ 5664 */
5665 struct root_domain def_root_domain; 5665 struct root_domain def_root_domain;
5666 5666
5667 static void init_defrootdomain(void) 5667 static void init_defrootdomain(void)
5668 { 5668 {
5669 init_rootdomain(&def_root_domain); 5669 init_rootdomain(&def_root_domain);
5670 5670
5671 atomic_set(&def_root_domain.refcount, 1); 5671 atomic_set(&def_root_domain.refcount, 1);
5672 } 5672 }
5673 5673
5674 static struct root_domain *alloc_rootdomain(void) 5674 static struct root_domain *alloc_rootdomain(void)
5675 { 5675 {
5676 struct root_domain *rd; 5676 struct root_domain *rd;
5677 5677
5678 rd = kmalloc(sizeof(*rd), GFP_KERNEL); 5678 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
5679 if (!rd) 5679 if (!rd)
5680 return NULL; 5680 return NULL;
5681 5681
5682 if (init_rootdomain(rd) != 0) { 5682 if (init_rootdomain(rd) != 0) {
5683 kfree(rd); 5683 kfree(rd);
5684 return NULL; 5684 return NULL;
5685 } 5685 }
5686 5686
5687 return rd; 5687 return rd;
5688 } 5688 }
5689 5689
5690 static void free_sched_groups(struct sched_group *sg, int free_sgc) 5690 static void free_sched_groups(struct sched_group *sg, int free_sgc)
5691 { 5691 {
5692 struct sched_group *tmp, *first; 5692 struct sched_group *tmp, *first;
5693 5693
5694 if (!sg) 5694 if (!sg)
5695 return; 5695 return;
5696 5696
5697 first = sg; 5697 first = sg;
5698 do { 5698 do {
5699 tmp = sg->next; 5699 tmp = sg->next;
5700 5700
5701 if (free_sgc && atomic_dec_and_test(&sg->sgc->ref)) 5701 if (free_sgc && atomic_dec_and_test(&sg->sgc->ref))
5702 kfree(sg->sgc); 5702 kfree(sg->sgc);
5703 5703
5704 kfree(sg); 5704 kfree(sg);
5705 sg = tmp; 5705 sg = tmp;
5706 } while (sg != first); 5706 } while (sg != first);
5707 } 5707 }
5708 5708
5709 static void free_sched_domain(struct rcu_head *rcu) 5709 static void free_sched_domain(struct rcu_head *rcu)
5710 { 5710 {
5711 struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu); 5711 struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
5712 5712
5713 /* 5713 /*
5714 * If its an overlapping domain it has private groups, iterate and 5714 * If its an overlapping domain it has private groups, iterate and
5715 * nuke them all. 5715 * nuke them all.
5716 */ 5716 */
5717 if (sd->flags & SD_OVERLAP) { 5717 if (sd->flags & SD_OVERLAP) {
5718 free_sched_groups(sd->groups, 1); 5718 free_sched_groups(sd->groups, 1);
5719 } else if (atomic_dec_and_test(&sd->groups->ref)) { 5719 } else if (atomic_dec_and_test(&sd->groups->ref)) {
5720 kfree(sd->groups->sgc); 5720 kfree(sd->groups->sgc);
5721 kfree(sd->groups); 5721 kfree(sd->groups);
5722 } 5722 }
5723 kfree(sd); 5723 kfree(sd);
5724 } 5724 }
5725 5725
5726 static void destroy_sched_domain(struct sched_domain *sd, int cpu) 5726 static void destroy_sched_domain(struct sched_domain *sd, int cpu)
5727 { 5727 {
5728 call_rcu(&sd->rcu, free_sched_domain); 5728 call_rcu(&sd->rcu, free_sched_domain);
5729 } 5729 }
5730 5730
5731 static void destroy_sched_domains(struct sched_domain *sd, int cpu) 5731 static void destroy_sched_domains(struct sched_domain *sd, int cpu)
5732 { 5732 {
5733 for (; sd; sd = sd->parent) 5733 for (; sd; sd = sd->parent)
5734 destroy_sched_domain(sd, cpu); 5734 destroy_sched_domain(sd, cpu);
5735 } 5735 }
5736 5736
5737 /* 5737 /*
5738 * Keep a special pointer to the highest sched_domain that has 5738 * Keep a special pointer to the highest sched_domain that has
5739 * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this 5739 * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
5740 * allows us to avoid some pointer chasing select_idle_sibling(). 5740 * allows us to avoid some pointer chasing select_idle_sibling().
5741 * 5741 *
5742 * Also keep a unique ID per domain (we use the first cpu number in 5742 * Also keep a unique ID per domain (we use the first cpu number in
5743 * the cpumask of the domain), this allows us to quickly tell if 5743 * the cpumask of the domain), this allows us to quickly tell if
5744 * two cpus are in the same cache domain, see cpus_share_cache(). 5744 * two cpus are in the same cache domain, see cpus_share_cache().
5745 */ 5745 */
5746 DEFINE_PER_CPU(struct sched_domain *, sd_llc); 5746 DEFINE_PER_CPU(struct sched_domain *, sd_llc);
5747 DEFINE_PER_CPU(int, sd_llc_size); 5747 DEFINE_PER_CPU(int, sd_llc_size);
5748 DEFINE_PER_CPU(int, sd_llc_id); 5748 DEFINE_PER_CPU(int, sd_llc_id);
5749 DEFINE_PER_CPU(struct sched_domain *, sd_numa); 5749 DEFINE_PER_CPU(struct sched_domain *, sd_numa);
5750 DEFINE_PER_CPU(struct sched_domain *, sd_busy); 5750 DEFINE_PER_CPU(struct sched_domain *, sd_busy);
5751 DEFINE_PER_CPU(struct sched_domain *, sd_asym); 5751 DEFINE_PER_CPU(struct sched_domain *, sd_asym);
5752 5752
5753 static void update_top_cache_domain(int cpu) 5753 static void update_top_cache_domain(int cpu)
5754 { 5754 {
5755 struct sched_domain *sd; 5755 struct sched_domain *sd;
5756 struct sched_domain *busy_sd = NULL; 5756 struct sched_domain *busy_sd = NULL;
5757 int id = cpu; 5757 int id = cpu;
5758 int size = 1; 5758 int size = 1;
5759 5759
5760 sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES); 5760 sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
5761 if (sd) { 5761 if (sd) {
5762 id = cpumask_first(sched_domain_span(sd)); 5762 id = cpumask_first(sched_domain_span(sd));
5763 size = cpumask_weight(sched_domain_span(sd)); 5763 size = cpumask_weight(sched_domain_span(sd));
5764 busy_sd = sd->parent; /* sd_busy */ 5764 busy_sd = sd->parent; /* sd_busy */
5765 } 5765 }
5766 rcu_assign_pointer(per_cpu(sd_busy, cpu), busy_sd); 5766 rcu_assign_pointer(per_cpu(sd_busy, cpu), busy_sd);
5767 5767
5768 rcu_assign_pointer(per_cpu(sd_llc, cpu), sd); 5768 rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
5769 per_cpu(sd_llc_size, cpu) = size; 5769 per_cpu(sd_llc_size, cpu) = size;
5770 per_cpu(sd_llc_id, cpu) = id; 5770 per_cpu(sd_llc_id, cpu) = id;
5771 5771
5772 sd = lowest_flag_domain(cpu, SD_NUMA); 5772 sd = lowest_flag_domain(cpu, SD_NUMA);
5773 rcu_assign_pointer(per_cpu(sd_numa, cpu), sd); 5773 rcu_assign_pointer(per_cpu(sd_numa, cpu), sd);
5774 5774
5775 sd = highest_flag_domain(cpu, SD_ASYM_PACKING); 5775 sd = highest_flag_domain(cpu, SD_ASYM_PACKING);
5776 rcu_assign_pointer(per_cpu(sd_asym, cpu), sd); 5776 rcu_assign_pointer(per_cpu(sd_asym, cpu), sd);
5777 } 5777 }
5778 5778
5779 /* 5779 /*
5780 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must 5780 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5781 * hold the hotplug lock. 5781 * hold the hotplug lock.
5782 */ 5782 */
5783 static void 5783 static void
5784 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu) 5784 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
5785 { 5785 {
5786 struct rq *rq = cpu_rq(cpu); 5786 struct rq *rq = cpu_rq(cpu);
5787 struct sched_domain *tmp; 5787 struct sched_domain *tmp;
5788 5788
5789 /* Remove the sched domains which do not contribute to scheduling. */ 5789 /* Remove the sched domains which do not contribute to scheduling. */
5790 for (tmp = sd; tmp; ) { 5790 for (tmp = sd; tmp; ) {
5791 struct sched_domain *parent = tmp->parent; 5791 struct sched_domain *parent = tmp->parent;
5792 if (!parent) 5792 if (!parent)
5793 break; 5793 break;
5794 5794
5795 if (sd_parent_degenerate(tmp, parent)) { 5795 if (sd_parent_degenerate(tmp, parent)) {
5796 tmp->parent = parent->parent; 5796 tmp->parent = parent->parent;
5797 if (parent->parent) 5797 if (parent->parent)
5798 parent->parent->child = tmp; 5798 parent->parent->child = tmp;
5799 /* 5799 /*
5800 * Transfer SD_PREFER_SIBLING down in case of a 5800 * Transfer SD_PREFER_SIBLING down in case of a
5801 * degenerate parent; the spans match for this 5801 * degenerate parent; the spans match for this
5802 * so the property transfers. 5802 * so the property transfers.
5803 */ 5803 */
5804 if (parent->flags & SD_PREFER_SIBLING) 5804 if (parent->flags & SD_PREFER_SIBLING)
5805 tmp->flags |= SD_PREFER_SIBLING; 5805 tmp->flags |= SD_PREFER_SIBLING;
5806 destroy_sched_domain(parent, cpu); 5806 destroy_sched_domain(parent, cpu);
5807 } else 5807 } else
5808 tmp = tmp->parent; 5808 tmp = tmp->parent;
5809 } 5809 }
5810 5810
5811 if (sd && sd_degenerate(sd)) { 5811 if (sd && sd_degenerate(sd)) {
5812 tmp = sd; 5812 tmp = sd;
5813 sd = sd->parent; 5813 sd = sd->parent;
5814 destroy_sched_domain(tmp, cpu); 5814 destroy_sched_domain(tmp, cpu);
5815 if (sd) 5815 if (sd)
5816 sd->child = NULL; 5816 sd->child = NULL;
5817 } 5817 }
5818 5818
5819 sched_domain_debug(sd, cpu); 5819 sched_domain_debug(sd, cpu);
5820 5820
5821 rq_attach_root(rq, rd); 5821 rq_attach_root(rq, rd);
5822 tmp = rq->sd; 5822 tmp = rq->sd;
5823 rcu_assign_pointer(rq->sd, sd); 5823 rcu_assign_pointer(rq->sd, sd);
5824 destroy_sched_domains(tmp, cpu); 5824 destroy_sched_domains(tmp, cpu);
5825 5825
5826 update_top_cache_domain(cpu); 5826 update_top_cache_domain(cpu);
5827 } 5827 }
5828 5828
5829 /* cpus with isolated domains */ 5829 /* cpus with isolated domains */
5830 static cpumask_var_t cpu_isolated_map; 5830 static cpumask_var_t cpu_isolated_map;
5831 5831
5832 /* Setup the mask of cpus configured for isolated domains */ 5832 /* Setup the mask of cpus configured for isolated domains */
5833 static int __init isolated_cpu_setup(char *str) 5833 static int __init isolated_cpu_setup(char *str)
5834 { 5834 {
5835 alloc_bootmem_cpumask_var(&cpu_isolated_map); 5835 alloc_bootmem_cpumask_var(&cpu_isolated_map);
5836 cpulist_parse(str, cpu_isolated_map); 5836 cpulist_parse(str, cpu_isolated_map);
5837 return 1; 5837 return 1;
5838 } 5838 }
5839 5839
5840 __setup("isolcpus=", isolated_cpu_setup); 5840 __setup("isolcpus=", isolated_cpu_setup);
5841 5841
5842 struct s_data { 5842 struct s_data {
5843 struct sched_domain ** __percpu sd; 5843 struct sched_domain ** __percpu sd;
5844 struct root_domain *rd; 5844 struct root_domain *rd;
5845 }; 5845 };
5846 5846
5847 enum s_alloc { 5847 enum s_alloc {
5848 sa_rootdomain, 5848 sa_rootdomain,
5849 sa_sd, 5849 sa_sd,
5850 sa_sd_storage, 5850 sa_sd_storage,
5851 sa_none, 5851 sa_none,
5852 }; 5852 };
5853 5853
5854 /* 5854 /*
5855 * Build an iteration mask that can exclude certain CPUs from the upwards 5855 * Build an iteration mask that can exclude certain CPUs from the upwards
5856 * domain traversal. 5856 * domain traversal.
5857 * 5857 *
5858 * Asymmetric node setups can result in situations where the domain tree is of 5858 * Asymmetric node setups can result in situations where the domain tree is of
5859 * unequal depth, make sure to skip domains that already cover the entire 5859 * unequal depth, make sure to skip domains that already cover the entire
5860 * range. 5860 * range.
5861 * 5861 *
5862 * In that case build_sched_domains() will have terminated the iteration early 5862 * In that case build_sched_domains() will have terminated the iteration early
5863 * and our sibling sd spans will be empty. Domains should always include the 5863 * and our sibling sd spans will be empty. Domains should always include the
5864 * cpu they're built on, so check that. 5864 * cpu they're built on, so check that.
5865 * 5865 *
5866 */ 5866 */
5867 static void build_group_mask(struct sched_domain *sd, struct sched_group *sg) 5867 static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
5868 { 5868 {
5869 const struct cpumask *span = sched_domain_span(sd); 5869 const struct cpumask *span = sched_domain_span(sd);
5870 struct sd_data *sdd = sd->private; 5870 struct sd_data *sdd = sd->private;
5871 struct sched_domain *sibling; 5871 struct sched_domain *sibling;
5872 int i; 5872 int i;
5873 5873
5874 for_each_cpu(i, span) { 5874 for_each_cpu(i, span) {
5875 sibling = *per_cpu_ptr(sdd->sd, i); 5875 sibling = *per_cpu_ptr(sdd->sd, i);
5876 if (!cpumask_test_cpu(i, sched_domain_span(sibling))) 5876 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
5877 continue; 5877 continue;
5878 5878
5879 cpumask_set_cpu(i, sched_group_mask(sg)); 5879 cpumask_set_cpu(i, sched_group_mask(sg));
5880 } 5880 }
5881 } 5881 }
5882 5882
5883 /* 5883 /*
5884 * Return the canonical balance cpu for this group, this is the first cpu 5884 * Return the canonical balance cpu for this group, this is the first cpu
5885 * of this group that's also in the iteration mask. 5885 * of this group that's also in the iteration mask.
5886 */ 5886 */
5887 int group_balance_cpu(struct sched_group *sg) 5887 int group_balance_cpu(struct sched_group *sg)
5888 { 5888 {
5889 return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg)); 5889 return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
5890 } 5890 }
5891 5891
5892 static int 5892 static int
5893 build_overlap_sched_groups(struct sched_domain *sd, int cpu) 5893 build_overlap_sched_groups(struct sched_domain *sd, int cpu)
5894 { 5894 {
5895 struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg; 5895 struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
5896 const struct cpumask *span = sched_domain_span(sd); 5896 const struct cpumask *span = sched_domain_span(sd);
5897 struct cpumask *covered = sched_domains_tmpmask; 5897 struct cpumask *covered = sched_domains_tmpmask;
5898 struct sd_data *sdd = sd->private; 5898 struct sd_data *sdd = sd->private;
5899 struct sched_domain *sibling; 5899 struct sched_domain *sibling;
5900 int i; 5900 int i;
5901 5901
5902 cpumask_clear(covered); 5902 cpumask_clear(covered);
5903 5903
5904 for_each_cpu(i, span) { 5904 for_each_cpu(i, span) {
5905 struct cpumask *sg_span; 5905 struct cpumask *sg_span;
5906 5906
5907 if (cpumask_test_cpu(i, covered)) 5907 if (cpumask_test_cpu(i, covered))
5908 continue; 5908 continue;
5909 5909
5910 sibling = *per_cpu_ptr(sdd->sd, i); 5910 sibling = *per_cpu_ptr(sdd->sd, i);
5911 5911
5912 /* See the comment near build_group_mask(). */ 5912 /* See the comment near build_group_mask(). */
5913 if (!cpumask_test_cpu(i, sched_domain_span(sibling))) 5913 if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
5914 continue; 5914 continue;
5915 5915
5916 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(), 5916 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
5917 GFP_KERNEL, cpu_to_node(cpu)); 5917 GFP_KERNEL, cpu_to_node(cpu));
5918 5918
5919 if (!sg) 5919 if (!sg)
5920 goto fail; 5920 goto fail;
5921 5921
5922 sg_span = sched_group_cpus(sg); 5922 sg_span = sched_group_cpus(sg);
5923 if (sibling->child) 5923 if (sibling->child)
5924 cpumask_copy(sg_span, sched_domain_span(sibling->child)); 5924 cpumask_copy(sg_span, sched_domain_span(sibling->child));
5925 else 5925 else
5926 cpumask_set_cpu(i, sg_span); 5926 cpumask_set_cpu(i, sg_span);
5927 5927
5928 cpumask_or(covered, covered, sg_span); 5928 cpumask_or(covered, covered, sg_span);
5929 5929
5930 sg->sgc = *per_cpu_ptr(sdd->sgc, i); 5930 sg->sgc = *per_cpu_ptr(sdd->sgc, i);
5931 if (atomic_inc_return(&sg->sgc->ref) == 1) 5931 if (atomic_inc_return(&sg->sgc->ref) == 1)
5932 build_group_mask(sd, sg); 5932 build_group_mask(sd, sg);
5933 5933
5934 /* 5934 /*
5935 * Initialize sgc->capacity such that even if we mess up the 5935 * Initialize sgc->capacity such that even if we mess up the
5936 * domains and no possible iteration will get us here, we won't 5936 * domains and no possible iteration will get us here, we won't
5937 * die on a /0 trap. 5937 * die on a /0 trap.
5938 */ 5938 */
5939 sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sg_span); 5939 sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sg_span);
5940 sg->sgc->capacity_orig = sg->sgc->capacity; 5940 sg->sgc->capacity_orig = sg->sgc->capacity;
5941 5941
5942 /* 5942 /*
5943 * Make sure the first group of this domain contains the 5943 * Make sure the first group of this domain contains the
5944 * canonical balance cpu. Otherwise the sched_domain iteration 5944 * canonical balance cpu. Otherwise the sched_domain iteration
5945 * breaks. See update_sg_lb_stats(). 5945 * breaks. See update_sg_lb_stats().
5946 */ 5946 */
5947 if ((!groups && cpumask_test_cpu(cpu, sg_span)) || 5947 if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
5948 group_balance_cpu(sg) == cpu) 5948 group_balance_cpu(sg) == cpu)
5949 groups = sg; 5949 groups = sg;
5950 5950
5951 if (!first) 5951 if (!first)
5952 first = sg; 5952 first = sg;
5953 if (last) 5953 if (last)
5954 last->next = sg; 5954 last->next = sg;
5955 last = sg; 5955 last = sg;
5956 last->next = first; 5956 last->next = first;
5957 } 5957 }
5958 sd->groups = groups; 5958 sd->groups = groups;
5959 5959
5960 return 0; 5960 return 0;
5961 5961
5962 fail: 5962 fail:
5963 free_sched_groups(first, 0); 5963 free_sched_groups(first, 0);
5964 5964
5965 return -ENOMEM; 5965 return -ENOMEM;
5966 } 5966 }
5967 5967
5968 static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg) 5968 static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
5969 { 5969 {
5970 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu); 5970 struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
5971 struct sched_domain *child = sd->child; 5971 struct sched_domain *child = sd->child;
5972 5972
5973 if (child) 5973 if (child)
5974 cpu = cpumask_first(sched_domain_span(child)); 5974 cpu = cpumask_first(sched_domain_span(child));
5975 5975
5976 if (sg) { 5976 if (sg) {
5977 *sg = *per_cpu_ptr(sdd->sg, cpu); 5977 *sg = *per_cpu_ptr(sdd->sg, cpu);
5978 (*sg)->sgc = *per_cpu_ptr(sdd->sgc, cpu); 5978 (*sg)->sgc = *per_cpu_ptr(sdd->sgc, cpu);
5979 atomic_set(&(*sg)->sgc->ref, 1); /* for claim_allocations */ 5979 atomic_set(&(*sg)->sgc->ref, 1); /* for claim_allocations */
5980 } 5980 }
5981 5981
5982 return cpu; 5982 return cpu;
5983 } 5983 }
5984 5984
5985 /* 5985 /*
5986 * build_sched_groups will build a circular linked list of the groups 5986 * build_sched_groups will build a circular linked list of the groups
5987 * covered by the given span, and will set each group's ->cpumask correctly, 5987 * covered by the given span, and will set each group's ->cpumask correctly,
5988 * and ->cpu_capacity to 0. 5988 * and ->cpu_capacity to 0.
5989 * 5989 *
5990 * Assumes the sched_domain tree is fully constructed 5990 * Assumes the sched_domain tree is fully constructed
5991 */ 5991 */
5992 static int 5992 static int
5993 build_sched_groups(struct sched_domain *sd, int cpu) 5993 build_sched_groups(struct sched_domain *sd, int cpu)
5994 { 5994 {
5995 struct sched_group *first = NULL, *last = NULL; 5995 struct sched_group *first = NULL, *last = NULL;
5996 struct sd_data *sdd = sd->private; 5996 struct sd_data *sdd = sd->private;
5997 const struct cpumask *span = sched_domain_span(sd); 5997 const struct cpumask *span = sched_domain_span(sd);
5998 struct cpumask *covered; 5998 struct cpumask *covered;
5999 int i; 5999 int i;
6000 6000
6001 get_group(cpu, sdd, &sd->groups); 6001 get_group(cpu, sdd, &sd->groups);
6002 atomic_inc(&sd->groups->ref); 6002 atomic_inc(&sd->groups->ref);
6003 6003
6004 if (cpu != cpumask_first(span)) 6004 if (cpu != cpumask_first(span))
6005 return 0; 6005 return 0;
6006 6006
6007 lockdep_assert_held(&sched_domains_mutex); 6007 lockdep_assert_held(&sched_domains_mutex);
6008 covered = sched_domains_tmpmask; 6008 covered = sched_domains_tmpmask;
6009 6009
6010 cpumask_clear(covered); 6010 cpumask_clear(covered);
6011 6011
6012 for_each_cpu(i, span) { 6012 for_each_cpu(i, span) {
6013 struct sched_group *sg; 6013 struct sched_group *sg;
6014 int group, j; 6014 int group, j;
6015 6015
6016 if (cpumask_test_cpu(i, covered)) 6016 if (cpumask_test_cpu(i, covered))
6017 continue; 6017 continue;
6018 6018
6019 group = get_group(i, sdd, &sg); 6019 group = get_group(i, sdd, &sg);
6020 cpumask_setall(sched_group_mask(sg)); 6020 cpumask_setall(sched_group_mask(sg));
6021 6021
6022 for_each_cpu(j, span) { 6022 for_each_cpu(j, span) {
6023 if (get_group(j, sdd, NULL) != group) 6023 if (get_group(j, sdd, NULL) != group)
6024 continue; 6024 continue;
6025 6025
6026 cpumask_set_cpu(j, covered); 6026 cpumask_set_cpu(j, covered);
6027 cpumask_set_cpu(j, sched_group_cpus(sg)); 6027 cpumask_set_cpu(j, sched_group_cpus(sg));
6028 } 6028 }
6029 6029
6030 if (!first) 6030 if (!first)
6031 first = sg; 6031 first = sg;
6032 if (last) 6032 if (last)
6033 last->next = sg; 6033 last->next = sg;
6034 last = sg; 6034 last = sg;
6035 } 6035 }
6036 last->next = first; 6036 last->next = first;
6037 6037
6038 return 0; 6038 return 0;
6039 } 6039 }
6040 6040
6041 /* 6041 /*
6042 * Initialize sched groups cpu_capacity. 6042 * Initialize sched groups cpu_capacity.
6043 * 6043 *
6044 * cpu_capacity indicates the capacity of sched group, which is used while 6044 * cpu_capacity indicates the capacity of sched group, which is used while
6045 * distributing the load between different sched groups in a sched domain. 6045 * distributing the load between different sched groups in a sched domain.
6046 * Typically cpu_capacity for all the groups in a sched domain will be same 6046 * Typically cpu_capacity for all the groups in a sched domain will be same
6047 * unless there are asymmetries in the topology. If there are asymmetries, 6047 * unless there are asymmetries in the topology. If there are asymmetries,
6048 * group having more cpu_capacity will pickup more load compared to the 6048 * group having more cpu_capacity will pickup more load compared to the
6049 * group having less cpu_capacity. 6049 * group having less cpu_capacity.
6050 */ 6050 */
6051 static void init_sched_groups_capacity(int cpu, struct sched_domain *sd) 6051 static void init_sched_groups_capacity(int cpu, struct sched_domain *sd)
6052 { 6052 {
6053 struct sched_group *sg = sd->groups; 6053 struct sched_group *sg = sd->groups;
6054 6054
6055 WARN_ON(!sg); 6055 WARN_ON(!sg);
6056 6056
6057 do { 6057 do {
6058 sg->group_weight = cpumask_weight(sched_group_cpus(sg)); 6058 sg->group_weight = cpumask_weight(sched_group_cpus(sg));
6059 sg = sg->next; 6059 sg = sg->next;
6060 } while (sg != sd->groups); 6060 } while (sg != sd->groups);
6061 6061
6062 if (cpu != group_balance_cpu(sg)) 6062 if (cpu != group_balance_cpu(sg))
6063 return; 6063 return;
6064 6064
6065 update_group_capacity(sd, cpu); 6065 update_group_capacity(sd, cpu);
6066 atomic_set(&sg->sgc->nr_busy_cpus, sg->group_weight); 6066 atomic_set(&sg->sgc->nr_busy_cpus, sg->group_weight);
6067 } 6067 }
6068 6068
6069 /* 6069 /*
6070 * Initializers for schedule domains 6070 * Initializers for schedule domains
6071 * Non-inlined to reduce accumulated stack pressure in build_sched_domains() 6071 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6072 */ 6072 */
6073 6073
6074 static int default_relax_domain_level = -1; 6074 static int default_relax_domain_level = -1;
6075 int sched_domain_level_max; 6075 int sched_domain_level_max;
6076 6076
6077 static int __init setup_relax_domain_level(char *str) 6077 static int __init setup_relax_domain_level(char *str)
6078 { 6078 {
6079 if (kstrtoint(str, 0, &default_relax_domain_level)) 6079 if (kstrtoint(str, 0, &default_relax_domain_level))
6080 pr_warn("Unable to set relax_domain_level\n"); 6080 pr_warn("Unable to set relax_domain_level\n");
6081 6081
6082 return 1; 6082 return 1;
6083 } 6083 }
6084 __setup("relax_domain_level=", setup_relax_domain_level); 6084 __setup("relax_domain_level=", setup_relax_domain_level);
6085 6085
6086 static void set_domain_attribute(struct sched_domain *sd, 6086 static void set_domain_attribute(struct sched_domain *sd,
6087 struct sched_domain_attr *attr) 6087 struct sched_domain_attr *attr)
6088 { 6088 {
6089 int request; 6089 int request;
6090 6090
6091 if (!attr || attr->relax_domain_level < 0) { 6091 if (!attr || attr->relax_domain_level < 0) {
6092 if (default_relax_domain_level < 0) 6092 if (default_relax_domain_level < 0)
6093 return; 6093 return;
6094 else 6094 else
6095 request = default_relax_domain_level; 6095 request = default_relax_domain_level;
6096 } else 6096 } else
6097 request = attr->relax_domain_level; 6097 request = attr->relax_domain_level;
6098 if (request < sd->level) { 6098 if (request < sd->level) {
6099 /* turn off idle balance on this domain */ 6099 /* turn off idle balance on this domain */
6100 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE); 6100 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6101 } else { 6101 } else {
6102 /* turn on idle balance on this domain */ 6102 /* turn on idle balance on this domain */
6103 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE); 6103 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6104 } 6104 }
6105 } 6105 }
6106 6106
6107 static void __sdt_free(const struct cpumask *cpu_map); 6107 static void __sdt_free(const struct cpumask *cpu_map);
6108 static int __sdt_alloc(const struct cpumask *cpu_map); 6108 static int __sdt_alloc(const struct cpumask *cpu_map);
6109 6109
6110 static void __free_domain_allocs(struct s_data *d, enum s_alloc what, 6110 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
6111 const struct cpumask *cpu_map) 6111 const struct cpumask *cpu_map)
6112 { 6112 {
6113 switch (what) { 6113 switch (what) {
6114 case sa_rootdomain: 6114 case sa_rootdomain:
6115 if (!atomic_read(&d->rd->refcount)) 6115 if (!atomic_read(&d->rd->refcount))
6116 free_rootdomain(&d->rd->rcu); /* fall through */ 6116 free_rootdomain(&d->rd->rcu); /* fall through */
6117 case sa_sd: 6117 case sa_sd:
6118 free_percpu(d->sd); /* fall through */ 6118 free_percpu(d->sd); /* fall through */
6119 case sa_sd_storage: 6119 case sa_sd_storage:
6120 __sdt_free(cpu_map); /* fall through */ 6120 __sdt_free(cpu_map); /* fall through */
6121 case sa_none: 6121 case sa_none:
6122 break; 6122 break;
6123 } 6123 }
6124 } 6124 }
6125 6125
6126 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d, 6126 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
6127 const struct cpumask *cpu_map) 6127 const struct cpumask *cpu_map)
6128 { 6128 {
6129 memset(d, 0, sizeof(*d)); 6129 memset(d, 0, sizeof(*d));
6130 6130
6131 if (__sdt_alloc(cpu_map)) 6131 if (__sdt_alloc(cpu_map))
6132 return sa_sd_storage; 6132 return sa_sd_storage;
6133 d->sd = alloc_percpu(struct sched_domain *); 6133 d->sd = alloc_percpu(struct sched_domain *);
6134 if (!d->sd) 6134 if (!d->sd)
6135 return sa_sd_storage; 6135 return sa_sd_storage;
6136 d->rd = alloc_rootdomain(); 6136 d->rd = alloc_rootdomain();
6137 if (!d->rd) 6137 if (!d->rd)
6138 return sa_sd; 6138 return sa_sd;
6139 return sa_rootdomain; 6139 return sa_rootdomain;
6140 } 6140 }
6141 6141
6142 /* 6142 /*
6143 * NULL the sd_data elements we've used to build the sched_domain and 6143 * NULL the sd_data elements we've used to build the sched_domain and
6144 * sched_group structure so that the subsequent __free_domain_allocs() 6144 * sched_group structure so that the subsequent __free_domain_allocs()
6145 * will not free the data we're using. 6145 * will not free the data we're using.
6146 */ 6146 */
6147 static void claim_allocations(int cpu, struct sched_domain *sd) 6147 static void claim_allocations(int cpu, struct sched_domain *sd)
6148 { 6148 {
6149 struct sd_data *sdd = sd->private; 6149 struct sd_data *sdd = sd->private;
6150 6150
6151 WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd); 6151 WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
6152 *per_cpu_ptr(sdd->sd, cpu) = NULL; 6152 *per_cpu_ptr(sdd->sd, cpu) = NULL;
6153 6153
6154 if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref)) 6154 if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
6155 *per_cpu_ptr(sdd->sg, cpu) = NULL; 6155 *per_cpu_ptr(sdd->sg, cpu) = NULL;
6156 6156
6157 if (atomic_read(&(*per_cpu_ptr(sdd->sgc, cpu))->ref)) 6157 if (atomic_read(&(*per_cpu_ptr(sdd->sgc, cpu))->ref))
6158 *per_cpu_ptr(sdd->sgc, cpu) = NULL; 6158 *per_cpu_ptr(sdd->sgc, cpu) = NULL;
6159 } 6159 }
6160 6160
6161 #ifdef CONFIG_NUMA 6161 #ifdef CONFIG_NUMA
6162 static int sched_domains_numa_levels; 6162 static int sched_domains_numa_levels;
6163 enum numa_topology_type sched_numa_topology_type; 6163 enum numa_topology_type sched_numa_topology_type;
6164 static int *sched_domains_numa_distance; 6164 static int *sched_domains_numa_distance;
6165 int sched_max_numa_distance; 6165 int sched_max_numa_distance;
6166 static struct cpumask ***sched_domains_numa_masks; 6166 static struct cpumask ***sched_domains_numa_masks;
6167 static int sched_domains_curr_level; 6167 static int sched_domains_curr_level;
6168 #endif 6168 #endif
6169 6169
6170 /* 6170 /*
6171 * SD_flags allowed in topology descriptions. 6171 * SD_flags allowed in topology descriptions.
6172 * 6172 *
6173 * SD_SHARE_CPUCAPACITY - describes SMT topologies 6173 * SD_SHARE_CPUCAPACITY - describes SMT topologies
6174 * SD_SHARE_PKG_RESOURCES - describes shared caches 6174 * SD_SHARE_PKG_RESOURCES - describes shared caches
6175 * SD_NUMA - describes NUMA topologies 6175 * SD_NUMA - describes NUMA topologies
6176 * SD_SHARE_POWERDOMAIN - describes shared power domain 6176 * SD_SHARE_POWERDOMAIN - describes shared power domain
6177 * 6177 *
6178 * Odd one out: 6178 * Odd one out:
6179 * SD_ASYM_PACKING - describes SMT quirks 6179 * SD_ASYM_PACKING - describes SMT quirks
6180 */ 6180 */
6181 #define TOPOLOGY_SD_FLAGS \ 6181 #define TOPOLOGY_SD_FLAGS \
6182 (SD_SHARE_CPUCAPACITY | \ 6182 (SD_SHARE_CPUCAPACITY | \
6183 SD_SHARE_PKG_RESOURCES | \ 6183 SD_SHARE_PKG_RESOURCES | \
6184 SD_NUMA | \ 6184 SD_NUMA | \
6185 SD_ASYM_PACKING | \ 6185 SD_ASYM_PACKING | \
6186 SD_SHARE_POWERDOMAIN) 6186 SD_SHARE_POWERDOMAIN)
6187 6187
6188 static struct sched_domain * 6188 static struct sched_domain *
6189 sd_init(struct sched_domain_topology_level *tl, int cpu) 6189 sd_init(struct sched_domain_topology_level *tl, int cpu)
6190 { 6190 {
6191 struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu); 6191 struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu);
6192 int sd_weight, sd_flags = 0; 6192 int sd_weight, sd_flags = 0;
6193 6193
6194 #ifdef CONFIG_NUMA 6194 #ifdef CONFIG_NUMA
6195 /* 6195 /*
6196 * Ugly hack to pass state to sd_numa_mask()... 6196 * Ugly hack to pass state to sd_numa_mask()...
6197 */ 6197 */
6198 sched_domains_curr_level = tl->numa_level; 6198 sched_domains_curr_level = tl->numa_level;
6199 #endif 6199 #endif
6200 6200
6201 sd_weight = cpumask_weight(tl->mask(cpu)); 6201 sd_weight = cpumask_weight(tl->mask(cpu));
6202 6202
6203 if (tl->sd_flags) 6203 if (tl->sd_flags)
6204 sd_flags = (*tl->sd_flags)(); 6204 sd_flags = (*tl->sd_flags)();
6205 if (WARN_ONCE(sd_flags & ~TOPOLOGY_SD_FLAGS, 6205 if (WARN_ONCE(sd_flags & ~TOPOLOGY_SD_FLAGS,
6206 "wrong sd_flags in topology description\n")) 6206 "wrong sd_flags in topology description\n"))
6207 sd_flags &= ~TOPOLOGY_SD_FLAGS; 6207 sd_flags &= ~TOPOLOGY_SD_FLAGS;
6208 6208
6209 *sd = (struct sched_domain){ 6209 *sd = (struct sched_domain){
6210 .min_interval = sd_weight, 6210 .min_interval = sd_weight,
6211 .max_interval = 2*sd_weight, 6211 .max_interval = 2*sd_weight,
6212 .busy_factor = 32, 6212 .busy_factor = 32,
6213 .imbalance_pct = 125, 6213 .imbalance_pct = 125,
6214 6214
6215 .cache_nice_tries = 0, 6215 .cache_nice_tries = 0,
6216 .busy_idx = 0, 6216 .busy_idx = 0,
6217 .idle_idx = 0, 6217 .idle_idx = 0,
6218 .newidle_idx = 0, 6218 .newidle_idx = 0,
6219 .wake_idx = 0, 6219 .wake_idx = 0,
6220 .forkexec_idx = 0, 6220 .forkexec_idx = 0,
6221 6221
6222 .flags = 1*SD_LOAD_BALANCE 6222 .flags = 1*SD_LOAD_BALANCE
6223 | 1*SD_BALANCE_NEWIDLE 6223 | 1*SD_BALANCE_NEWIDLE
6224 | 1*SD_BALANCE_EXEC 6224 | 1*SD_BALANCE_EXEC
6225 | 1*SD_BALANCE_FORK 6225 | 1*SD_BALANCE_FORK
6226 | 0*SD_BALANCE_WAKE 6226 | 0*SD_BALANCE_WAKE
6227 | 1*SD_WAKE_AFFINE 6227 | 1*SD_WAKE_AFFINE
6228 | 0*SD_SHARE_CPUCAPACITY 6228 | 0*SD_SHARE_CPUCAPACITY
6229 | 0*SD_SHARE_PKG_RESOURCES 6229 | 0*SD_SHARE_PKG_RESOURCES
6230 | 0*SD_SERIALIZE 6230 | 0*SD_SERIALIZE
6231 | 0*SD_PREFER_SIBLING 6231 | 0*SD_PREFER_SIBLING
6232 | 0*SD_NUMA 6232 | 0*SD_NUMA
6233 | sd_flags 6233 | sd_flags
6234 , 6234 ,
6235 6235
6236 .last_balance = jiffies, 6236 .last_balance = jiffies,
6237 .balance_interval = sd_weight, 6237 .balance_interval = sd_weight,
6238 .smt_gain = 0, 6238 .smt_gain = 0,
6239 .max_newidle_lb_cost = 0, 6239 .max_newidle_lb_cost = 0,
6240 .next_decay_max_lb_cost = jiffies, 6240 .next_decay_max_lb_cost = jiffies,
6241 #ifdef CONFIG_SCHED_DEBUG 6241 #ifdef CONFIG_SCHED_DEBUG
6242 .name = tl->name, 6242 .name = tl->name,
6243 #endif 6243 #endif
6244 }; 6244 };
6245 6245
6246 /* 6246 /*
6247 * Convert topological properties into behaviour. 6247 * Convert topological properties into behaviour.
6248 */ 6248 */
6249 6249
6250 if (sd->flags & SD_SHARE_CPUCAPACITY) { 6250 if (sd->flags & SD_SHARE_CPUCAPACITY) {
6251 sd->imbalance_pct = 110; 6251 sd->imbalance_pct = 110;
6252 sd->smt_gain = 1178; /* ~15% */ 6252 sd->smt_gain = 1178; /* ~15% */
6253 6253
6254 } else if (sd->flags & SD_SHARE_PKG_RESOURCES) { 6254 } else if (sd->flags & SD_SHARE_PKG_RESOURCES) {
6255 sd->imbalance_pct = 117; 6255 sd->imbalance_pct = 117;
6256 sd->cache_nice_tries = 1; 6256 sd->cache_nice_tries = 1;
6257 sd->busy_idx = 2; 6257 sd->busy_idx = 2;
6258 6258
6259 #ifdef CONFIG_NUMA 6259 #ifdef CONFIG_NUMA
6260 } else if (sd->flags & SD_NUMA) { 6260 } else if (sd->flags & SD_NUMA) {
6261 sd->cache_nice_tries = 2; 6261 sd->cache_nice_tries = 2;
6262 sd->busy_idx = 3; 6262 sd->busy_idx = 3;
6263 sd->idle_idx = 2; 6263 sd->idle_idx = 2;
6264 6264
6265 sd->flags |= SD_SERIALIZE; 6265 sd->flags |= SD_SERIALIZE;
6266 if (sched_domains_numa_distance[tl->numa_level] > RECLAIM_DISTANCE) { 6266 if (sched_domains_numa_distance[tl->numa_level] > RECLAIM_DISTANCE) {
6267 sd->flags &= ~(SD_BALANCE_EXEC | 6267 sd->flags &= ~(SD_BALANCE_EXEC |
6268 SD_BALANCE_FORK | 6268 SD_BALANCE_FORK |
6269 SD_WAKE_AFFINE); 6269 SD_WAKE_AFFINE);
6270 } 6270 }
6271 6271
6272 #endif 6272 #endif
6273 } else { 6273 } else {
6274 sd->flags |= SD_PREFER_SIBLING; 6274 sd->flags |= SD_PREFER_SIBLING;
6275 sd->cache_nice_tries = 1; 6275 sd->cache_nice_tries = 1;
6276 sd->busy_idx = 2; 6276 sd->busy_idx = 2;
6277 sd->idle_idx = 1; 6277 sd->idle_idx = 1;
6278 } 6278 }
6279 6279
6280 sd->private = &tl->data; 6280 sd->private = &tl->data;
6281 6281
6282 return sd; 6282 return sd;
6283 } 6283 }
6284 6284
6285 /* 6285 /*
6286 * Topology list, bottom-up. 6286 * Topology list, bottom-up.
6287 */ 6287 */
6288 static struct sched_domain_topology_level default_topology[] = { 6288 static struct sched_domain_topology_level default_topology[] = {
6289 #ifdef CONFIG_SCHED_SMT 6289 #ifdef CONFIG_SCHED_SMT
6290 { cpu_smt_mask, cpu_smt_flags, SD_INIT_NAME(SMT) }, 6290 { cpu_smt_mask, cpu_smt_flags, SD_INIT_NAME(SMT) },
6291 #endif 6291 #endif
6292 #ifdef CONFIG_SCHED_MC 6292 #ifdef CONFIG_SCHED_MC
6293 { cpu_coregroup_mask, cpu_core_flags, SD_INIT_NAME(MC) }, 6293 { cpu_coregroup_mask, cpu_core_flags, SD_INIT_NAME(MC) },
6294 #endif 6294 #endif
6295 { cpu_cpu_mask, SD_INIT_NAME(DIE) }, 6295 { cpu_cpu_mask, SD_INIT_NAME(DIE) },
6296 { NULL, }, 6296 { NULL, },
6297 }; 6297 };
6298 6298
6299 struct sched_domain_topology_level *sched_domain_topology = default_topology; 6299 struct sched_domain_topology_level *sched_domain_topology = default_topology;
6300 6300
6301 #define for_each_sd_topology(tl) \ 6301 #define for_each_sd_topology(tl) \
6302 for (tl = sched_domain_topology; tl->mask; tl++) 6302 for (tl = sched_domain_topology; tl->mask; tl++)
6303 6303
6304 void set_sched_topology(struct sched_domain_topology_level *tl) 6304 void set_sched_topology(struct sched_domain_topology_level *tl)
6305 { 6305 {
6306 sched_domain_topology = tl; 6306 sched_domain_topology = tl;
6307 } 6307 }
6308 6308
6309 #ifdef CONFIG_NUMA 6309 #ifdef CONFIG_NUMA
6310 6310
6311 static const struct cpumask *sd_numa_mask(int cpu) 6311 static const struct cpumask *sd_numa_mask(int cpu)
6312 { 6312 {
6313 return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)]; 6313 return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
6314 } 6314 }
6315 6315
6316 static void sched_numa_warn(const char *str) 6316 static void sched_numa_warn(const char *str)
6317 { 6317 {
6318 static int done = false; 6318 static int done = false;
6319 int i,j; 6319 int i,j;
6320 6320
6321 if (done) 6321 if (done)
6322 return; 6322 return;
6323 6323
6324 done = true; 6324 done = true;
6325 6325
6326 printk(KERN_WARNING "ERROR: %s\n\n", str); 6326 printk(KERN_WARNING "ERROR: %s\n\n", str);
6327 6327
6328 for (i = 0; i < nr_node_ids; i++) { 6328 for (i = 0; i < nr_node_ids; i++) {
6329 printk(KERN_WARNING " "); 6329 printk(KERN_WARNING " ");
6330 for (j = 0; j < nr_node_ids; j++) 6330 for (j = 0; j < nr_node_ids; j++)
6331 printk(KERN_CONT "%02d ", node_distance(i,j)); 6331 printk(KERN_CONT "%02d ", node_distance(i,j));
6332 printk(KERN_CONT "\n"); 6332 printk(KERN_CONT "\n");
6333 } 6333 }
6334 printk(KERN_WARNING "\n"); 6334 printk(KERN_WARNING "\n");
6335 } 6335 }
6336 6336
6337 bool find_numa_distance(int distance) 6337 bool find_numa_distance(int distance)
6338 { 6338 {
6339 int i; 6339 int i;
6340 6340
6341 if (distance == node_distance(0, 0)) 6341 if (distance == node_distance(0, 0))
6342 return true; 6342 return true;
6343 6343
6344 for (i = 0; i < sched_domains_numa_levels; i++) { 6344 for (i = 0; i < sched_domains_numa_levels; i++) {
6345 if (sched_domains_numa_distance[i] == distance) 6345 if (sched_domains_numa_distance[i] == distance)
6346 return true; 6346 return true;
6347 } 6347 }
6348 6348
6349 return false; 6349 return false;
6350 } 6350 }
6351 6351
6352 /* 6352 /*
6353 * A system can have three types of NUMA topology: 6353 * A system can have three types of NUMA topology:
6354 * NUMA_DIRECT: all nodes are directly connected, or not a NUMA system 6354 * NUMA_DIRECT: all nodes are directly connected, or not a NUMA system
6355 * NUMA_GLUELESS_MESH: some nodes reachable through intermediary nodes 6355 * NUMA_GLUELESS_MESH: some nodes reachable through intermediary nodes
6356 * NUMA_BACKPLANE: nodes can reach other nodes through a backplane 6356 * NUMA_BACKPLANE: nodes can reach other nodes through a backplane
6357 * 6357 *
6358 * The difference between a glueless mesh topology and a backplane 6358 * The difference between a glueless mesh topology and a backplane
6359 * topology lies in whether communication between not directly 6359 * topology lies in whether communication between not directly
6360 * connected nodes goes through intermediary nodes (where programs 6360 * connected nodes goes through intermediary nodes (where programs
6361 * could run), or through backplane controllers. This affects 6361 * could run), or through backplane controllers. This affects
6362 * placement of programs. 6362 * placement of programs.
6363 * 6363 *
6364 * The type of topology can be discerned with the following tests: 6364 * The type of topology can be discerned with the following tests:
6365 * - If the maximum distance between any nodes is 1 hop, the system 6365 * - If the maximum distance between any nodes is 1 hop, the system
6366 * is directly connected. 6366 * is directly connected.
6367 * - If for two nodes A and B, located N > 1 hops away from each other, 6367 * - If for two nodes A and B, located N > 1 hops away from each other,
6368 * there is an intermediary node C, which is < N hops away from both 6368 * there is an intermediary node C, which is < N hops away from both
6369 * nodes A and B, the system is a glueless mesh. 6369 * nodes A and B, the system is a glueless mesh.
6370 */ 6370 */
6371 static void init_numa_topology_type(void) 6371 static void init_numa_topology_type(void)
6372 { 6372 {
6373 int a, b, c, n; 6373 int a, b, c, n;
6374 6374
6375 n = sched_max_numa_distance; 6375 n = sched_max_numa_distance;
6376 6376
6377 if (n <= 1) 6377 if (n <= 1)
6378 sched_numa_topology_type = NUMA_DIRECT; 6378 sched_numa_topology_type = NUMA_DIRECT;
6379 6379
6380 for_each_online_node(a) { 6380 for_each_online_node(a) {
6381 for_each_online_node(b) { 6381 for_each_online_node(b) {
6382 /* Find two nodes furthest removed from each other. */ 6382 /* Find two nodes furthest removed from each other. */
6383 if (node_distance(a, b) < n) 6383 if (node_distance(a, b) < n)
6384 continue; 6384 continue;
6385 6385
6386 /* Is there an intermediary node between a and b? */ 6386 /* Is there an intermediary node between a and b? */
6387 for_each_online_node(c) { 6387 for_each_online_node(c) {
6388 if (node_distance(a, c) < n && 6388 if (node_distance(a, c) < n &&
6389 node_distance(b, c) < n) { 6389 node_distance(b, c) < n) {
6390 sched_numa_topology_type = 6390 sched_numa_topology_type =
6391 NUMA_GLUELESS_MESH; 6391 NUMA_GLUELESS_MESH;
6392 return; 6392 return;
6393 } 6393 }
6394 } 6394 }
6395 6395
6396 sched_numa_topology_type = NUMA_BACKPLANE; 6396 sched_numa_topology_type = NUMA_BACKPLANE;
6397 return; 6397 return;
6398 } 6398 }
6399 } 6399 }
6400 } 6400 }
6401 6401
6402 static void sched_init_numa(void) 6402 static void sched_init_numa(void)
6403 { 6403 {
6404 int next_distance, curr_distance = node_distance(0, 0); 6404 int next_distance, curr_distance = node_distance(0, 0);
6405 struct sched_domain_topology_level *tl; 6405 struct sched_domain_topology_level *tl;
6406 int level = 0; 6406 int level = 0;
6407 int i, j, k; 6407 int i, j, k;
6408 6408
6409 sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL); 6409 sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
6410 if (!sched_domains_numa_distance) 6410 if (!sched_domains_numa_distance)
6411 return; 6411 return;
6412 6412
6413 /* 6413 /*
6414 * O(nr_nodes^2) deduplicating selection sort -- in order to find the 6414 * O(nr_nodes^2) deduplicating selection sort -- in order to find the
6415 * unique distances in the node_distance() table. 6415 * unique distances in the node_distance() table.
6416 * 6416 *
6417 * Assumes node_distance(0,j) includes all distances in 6417 * Assumes node_distance(0,j) includes all distances in
6418 * node_distance(i,j) in order to avoid cubic time. 6418 * node_distance(i,j) in order to avoid cubic time.
6419 */ 6419 */
6420 next_distance = curr_distance; 6420 next_distance = curr_distance;
6421 for (i = 0; i < nr_node_ids; i++) { 6421 for (i = 0; i < nr_node_ids; i++) {
6422 for (j = 0; j < nr_node_ids; j++) { 6422 for (j = 0; j < nr_node_ids; j++) {
6423 for (k = 0; k < nr_node_ids; k++) { 6423 for (k = 0; k < nr_node_ids; k++) {
6424 int distance = node_distance(i, k); 6424 int distance = node_distance(i, k);
6425 6425
6426 if (distance > curr_distance && 6426 if (distance > curr_distance &&
6427 (distance < next_distance || 6427 (distance < next_distance ||
6428 next_distance == curr_distance)) 6428 next_distance == curr_distance))
6429 next_distance = distance; 6429 next_distance = distance;
6430 6430
6431 /* 6431 /*
6432 * While not a strong assumption it would be nice to know 6432 * While not a strong assumption it would be nice to know
6433 * about cases where if node A is connected to B, B is not 6433 * about cases where if node A is connected to B, B is not
6434 * equally connected to A. 6434 * equally connected to A.
6435 */ 6435 */
6436 if (sched_debug() && node_distance(k, i) != distance) 6436 if (sched_debug() && node_distance(k, i) != distance)
6437 sched_numa_warn("Node-distance not symmetric"); 6437 sched_numa_warn("Node-distance not symmetric");
6438 6438
6439 if (sched_debug() && i && !find_numa_distance(distance)) 6439 if (sched_debug() && i && !find_numa_distance(distance))
6440 sched_numa_warn("Node-0 not representative"); 6440 sched_numa_warn("Node-0 not representative");
6441 } 6441 }
6442 if (next_distance != curr_distance) { 6442 if (next_distance != curr_distance) {
6443 sched_domains_numa_distance[level++] = next_distance; 6443 sched_domains_numa_distance[level++] = next_distance;
6444 sched_domains_numa_levels = level; 6444 sched_domains_numa_levels = level;
6445 curr_distance = next_distance; 6445 curr_distance = next_distance;
6446 } else break; 6446 } else break;
6447 } 6447 }
6448 6448
6449 /* 6449 /*
6450 * In case of sched_debug() we verify the above assumption. 6450 * In case of sched_debug() we verify the above assumption.
6451 */ 6451 */
6452 if (!sched_debug()) 6452 if (!sched_debug())
6453 break; 6453 break;
6454 } 6454 }
6455 6455
6456 if (!level) 6456 if (!level)
6457 return; 6457 return;
6458 6458
6459 /* 6459 /*
6460 * 'level' contains the number of unique distances, excluding the 6460 * 'level' contains the number of unique distances, excluding the
6461 * identity distance node_distance(i,i). 6461 * identity distance node_distance(i,i).
6462 * 6462 *
6463 * The sched_domains_numa_distance[] array includes the actual distance 6463 * The sched_domains_numa_distance[] array includes the actual distance
6464 * numbers. 6464 * numbers.
6465 */ 6465 */
6466 6466
6467 /* 6467 /*
6468 * Here, we should temporarily reset sched_domains_numa_levels to 0. 6468 * Here, we should temporarily reset sched_domains_numa_levels to 0.
6469 * If it fails to allocate memory for array sched_domains_numa_masks[][], 6469 * If it fails to allocate memory for array sched_domains_numa_masks[][],
6470 * the array will contain less then 'level' members. This could be 6470 * the array will contain less then 'level' members. This could be
6471 * dangerous when we use it to iterate array sched_domains_numa_masks[][] 6471 * dangerous when we use it to iterate array sched_domains_numa_masks[][]
6472 * in other functions. 6472 * in other functions.
6473 * 6473 *
6474 * We reset it to 'level' at the end of this function. 6474 * We reset it to 'level' at the end of this function.
6475 */ 6475 */
6476 sched_domains_numa_levels = 0; 6476 sched_domains_numa_levels = 0;
6477 6477
6478 sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL); 6478 sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
6479 if (!sched_domains_numa_masks) 6479 if (!sched_domains_numa_masks)
6480 return; 6480 return;
6481 6481
6482 /* 6482 /*
6483 * Now for each level, construct a mask per node which contains all 6483 * Now for each level, construct a mask per node which contains all
6484 * cpus of nodes that are that many hops away from us. 6484 * cpus of nodes that are that many hops away from us.
6485 */ 6485 */
6486 for (i = 0; i < level; i++) { 6486 for (i = 0; i < level; i++) {
6487 sched_domains_numa_masks[i] = 6487 sched_domains_numa_masks[i] =
6488 kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL); 6488 kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
6489 if (!sched_domains_numa_masks[i]) 6489 if (!sched_domains_numa_masks[i])
6490 return; 6490 return;
6491 6491
6492 for (j = 0; j < nr_node_ids; j++) { 6492 for (j = 0; j < nr_node_ids; j++) {
6493 struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL); 6493 struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
6494 if (!mask) 6494 if (!mask)
6495 return; 6495 return;
6496 6496
6497 sched_domains_numa_masks[i][j] = mask; 6497 sched_domains_numa_masks[i][j] = mask;
6498 6498
6499 for (k = 0; k < nr_node_ids; k++) { 6499 for (k = 0; k < nr_node_ids; k++) {
6500 if (node_distance(j, k) > sched_domains_numa_distance[i]) 6500 if (node_distance(j, k) > sched_domains_numa_distance[i])
6501 continue; 6501 continue;
6502 6502
6503 cpumask_or(mask, mask, cpumask_of_node(k)); 6503 cpumask_or(mask, mask, cpumask_of_node(k));
6504 } 6504 }
6505 } 6505 }
6506 } 6506 }
6507 6507
6508 /* Compute default topology size */ 6508 /* Compute default topology size */
6509 for (i = 0; sched_domain_topology[i].mask; i++); 6509 for (i = 0; sched_domain_topology[i].mask; i++);
6510 6510
6511 tl = kzalloc((i + level + 1) * 6511 tl = kzalloc((i + level + 1) *
6512 sizeof(struct sched_domain_topology_level), GFP_KERNEL); 6512 sizeof(struct sched_domain_topology_level), GFP_KERNEL);
6513 if (!tl) 6513 if (!tl)
6514 return; 6514 return;
6515 6515
6516 /* 6516 /*
6517 * Copy the default topology bits.. 6517 * Copy the default topology bits..
6518 */ 6518 */
6519 for (i = 0; sched_domain_topology[i].mask; i++) 6519 for (i = 0; sched_domain_topology[i].mask; i++)
6520 tl[i] = sched_domain_topology[i]; 6520 tl[i] = sched_domain_topology[i];
6521 6521
6522 /* 6522 /*
6523 * .. and append 'j' levels of NUMA goodness. 6523 * .. and append 'j' levels of NUMA goodness.
6524 */ 6524 */
6525 for (j = 0; j < level; i++, j++) { 6525 for (j = 0; j < level; i++, j++) {
6526 tl[i] = (struct sched_domain_topology_level){ 6526 tl[i] = (struct sched_domain_topology_level){
6527 .mask = sd_numa_mask, 6527 .mask = sd_numa_mask,
6528 .sd_flags = cpu_numa_flags, 6528 .sd_flags = cpu_numa_flags,
6529 .flags = SDTL_OVERLAP, 6529 .flags = SDTL_OVERLAP,
6530 .numa_level = j, 6530 .numa_level = j,
6531 SD_INIT_NAME(NUMA) 6531 SD_INIT_NAME(NUMA)
6532 }; 6532 };
6533 } 6533 }
6534 6534
6535 sched_domain_topology = tl; 6535 sched_domain_topology = tl;
6536 6536
6537 sched_domains_numa_levels = level; 6537 sched_domains_numa_levels = level;
6538 sched_max_numa_distance = sched_domains_numa_distance[level - 1]; 6538 sched_max_numa_distance = sched_domains_numa_distance[level - 1];
6539 6539
6540 init_numa_topology_type(); 6540 init_numa_topology_type();
6541 } 6541 }
6542 6542
6543 static void sched_domains_numa_masks_set(int cpu) 6543 static void sched_domains_numa_masks_set(int cpu)
6544 { 6544 {
6545 int i, j; 6545 int i, j;
6546 int node = cpu_to_node(cpu); 6546 int node = cpu_to_node(cpu);
6547 6547
6548 for (i = 0; i < sched_domains_numa_levels; i++) { 6548 for (i = 0; i < sched_domains_numa_levels; i++) {
6549 for (j = 0; j < nr_node_ids; j++) { 6549 for (j = 0; j < nr_node_ids; j++) {
6550 if (node_distance(j, node) <= sched_domains_numa_distance[i]) 6550 if (node_distance(j, node) <= sched_domains_numa_distance[i])
6551 cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]); 6551 cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
6552 } 6552 }
6553 } 6553 }
6554 } 6554 }
6555 6555
6556 static void sched_domains_numa_masks_clear(int cpu) 6556 static void sched_domains_numa_masks_clear(int cpu)
6557 { 6557 {
6558 int i, j; 6558 int i, j;
6559 for (i = 0; i < sched_domains_numa_levels; i++) { 6559 for (i = 0; i < sched_domains_numa_levels; i++) {
6560 for (j = 0; j < nr_node_ids; j++) 6560 for (j = 0; j < nr_node_ids; j++)
6561 cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]); 6561 cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
6562 } 6562 }
6563 } 6563 }
6564 6564
6565 /* 6565 /*
6566 * Update sched_domains_numa_masks[level][node] array when new cpus 6566 * Update sched_domains_numa_masks[level][node] array when new cpus
6567 * are onlined. 6567 * are onlined.
6568 */ 6568 */
6569 static int sched_domains_numa_masks_update(struct notifier_block *nfb, 6569 static int sched_domains_numa_masks_update(struct notifier_block *nfb,
6570 unsigned long action, 6570 unsigned long action,
6571 void *hcpu) 6571 void *hcpu)
6572 { 6572 {
6573 int cpu = (long)hcpu; 6573 int cpu = (long)hcpu;
6574 6574
6575 switch (action & ~CPU_TASKS_FROZEN) { 6575 switch (action & ~CPU_TASKS_FROZEN) {
6576 case CPU_ONLINE: 6576 case CPU_ONLINE:
6577 sched_domains_numa_masks_set(cpu); 6577 sched_domains_numa_masks_set(cpu);
6578 break; 6578 break;
6579 6579
6580 case CPU_DEAD: 6580 case CPU_DEAD:
6581 sched_domains_numa_masks_clear(cpu); 6581 sched_domains_numa_masks_clear(cpu);
6582 break; 6582 break;
6583 6583
6584 default: 6584 default:
6585 return NOTIFY_DONE; 6585 return NOTIFY_DONE;
6586 } 6586 }
6587 6587
6588 return NOTIFY_OK; 6588 return NOTIFY_OK;
6589 } 6589 }
6590 #else 6590 #else
6591 static inline void sched_init_numa(void) 6591 static inline void sched_init_numa(void)
6592 { 6592 {
6593 } 6593 }
6594 6594
6595 static int sched_domains_numa_masks_update(struct notifier_block *nfb, 6595 static int sched_domains_numa_masks_update(struct notifier_block *nfb,
6596 unsigned long action, 6596 unsigned long action,
6597 void *hcpu) 6597 void *hcpu)
6598 { 6598 {
6599 return 0; 6599 return 0;
6600 } 6600 }
6601 #endif /* CONFIG_NUMA */ 6601 #endif /* CONFIG_NUMA */
6602 6602
6603 static int __sdt_alloc(const struct cpumask *cpu_map) 6603 static int __sdt_alloc(const struct cpumask *cpu_map)
6604 { 6604 {
6605 struct sched_domain_topology_level *tl; 6605 struct sched_domain_topology_level *tl;
6606 int j; 6606 int j;
6607 6607
6608 for_each_sd_topology(tl) { 6608 for_each_sd_topology(tl) {
6609 struct sd_data *sdd = &tl->data; 6609 struct sd_data *sdd = &tl->data;
6610 6610
6611 sdd->sd = alloc_percpu(struct sched_domain *); 6611 sdd->sd = alloc_percpu(struct sched_domain *);
6612 if (!sdd->sd) 6612 if (!sdd->sd)
6613 return -ENOMEM; 6613 return -ENOMEM;
6614 6614
6615 sdd->sg = alloc_percpu(struct sched_group *); 6615 sdd->sg = alloc_percpu(struct sched_group *);
6616 if (!sdd->sg) 6616 if (!sdd->sg)
6617 return -ENOMEM; 6617 return -ENOMEM;
6618 6618
6619 sdd->sgc = alloc_percpu(struct sched_group_capacity *); 6619 sdd->sgc = alloc_percpu(struct sched_group_capacity *);
6620 if (!sdd->sgc) 6620 if (!sdd->sgc)
6621 return -ENOMEM; 6621 return -ENOMEM;
6622 6622
6623 for_each_cpu(j, cpu_map) { 6623 for_each_cpu(j, cpu_map) {
6624 struct sched_domain *sd; 6624 struct sched_domain *sd;
6625 struct sched_group *sg; 6625 struct sched_group *sg;
6626 struct sched_group_capacity *sgc; 6626 struct sched_group_capacity *sgc;
6627 6627
6628 sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(), 6628 sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
6629 GFP_KERNEL, cpu_to_node(j)); 6629 GFP_KERNEL, cpu_to_node(j));
6630 if (!sd) 6630 if (!sd)
6631 return -ENOMEM; 6631 return -ENOMEM;
6632 6632
6633 *per_cpu_ptr(sdd->sd, j) = sd; 6633 *per_cpu_ptr(sdd->sd, j) = sd;
6634 6634
6635 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(), 6635 sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
6636 GFP_KERNEL, cpu_to_node(j)); 6636 GFP_KERNEL, cpu_to_node(j));
6637 if (!sg) 6637 if (!sg)
6638 return -ENOMEM; 6638 return -ENOMEM;
6639 6639
6640 sg->next = sg; 6640 sg->next = sg;
6641 6641
6642 *per_cpu_ptr(sdd->sg, j) = sg; 6642 *per_cpu_ptr(sdd->sg, j) = sg;
6643 6643
6644 sgc = kzalloc_node(sizeof(struct sched_group_capacity) + cpumask_size(), 6644 sgc = kzalloc_node(sizeof(struct sched_group_capacity) + cpumask_size(),
6645 GFP_KERNEL, cpu_to_node(j)); 6645 GFP_KERNEL, cpu_to_node(j));
6646 if (!sgc) 6646 if (!sgc)
6647 return -ENOMEM; 6647 return -ENOMEM;
6648 6648
6649 *per_cpu_ptr(sdd->sgc, j) = sgc; 6649 *per_cpu_ptr(sdd->sgc, j) = sgc;
6650 } 6650 }
6651 } 6651 }
6652 6652
6653 return 0; 6653 return 0;
6654 } 6654 }
6655 6655
6656 static void __sdt_free(const struct cpumask *cpu_map) 6656 static void __sdt_free(const struct cpumask *cpu_map)
6657 { 6657 {
6658 struct sched_domain_topology_level *tl; 6658 struct sched_domain_topology_level *tl;
6659 int j; 6659 int j;
6660 6660
6661 for_each_sd_topology(tl) { 6661 for_each_sd_topology(tl) {
6662 struct sd_data *sdd = &tl->data; 6662 struct sd_data *sdd = &tl->data;
6663 6663
6664 for_each_cpu(j, cpu_map) { 6664 for_each_cpu(j, cpu_map) {
6665 struct sched_domain *sd; 6665 struct sched_domain *sd;
6666 6666
6667 if (sdd->sd) { 6667 if (sdd->sd) {
6668 sd = *per_cpu_ptr(sdd->sd, j); 6668 sd = *per_cpu_ptr(sdd->sd, j);
6669 if (sd && (sd->flags & SD_OVERLAP)) 6669 if (sd && (sd->flags & SD_OVERLAP))
6670 free_sched_groups(sd->groups, 0); 6670 free_sched_groups(sd->groups, 0);
6671 kfree(*per_cpu_ptr(sdd->sd, j)); 6671 kfree(*per_cpu_ptr(sdd->sd, j));
6672 } 6672 }
6673 6673
6674 if (sdd->sg) 6674 if (sdd->sg)
6675 kfree(*per_cpu_ptr(sdd->sg, j)); 6675 kfree(*per_cpu_ptr(sdd->sg, j));
6676 if (sdd->sgc) 6676 if (sdd->sgc)
6677 kfree(*per_cpu_ptr(sdd->sgc, j)); 6677 kfree(*per_cpu_ptr(sdd->sgc, j));
6678 } 6678 }
6679 free_percpu(sdd->sd); 6679 free_percpu(sdd->sd);
6680 sdd->sd = NULL; 6680 sdd->sd = NULL;
6681 free_percpu(sdd->sg); 6681 free_percpu(sdd->sg);
6682 sdd->sg = NULL; 6682 sdd->sg = NULL;
6683 free_percpu(sdd->sgc); 6683 free_percpu(sdd->sgc);
6684 sdd->sgc = NULL; 6684 sdd->sgc = NULL;
6685 } 6685 }
6686 } 6686 }
6687 6687
6688 struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl, 6688 struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
6689 const struct cpumask *cpu_map, struct sched_domain_attr *attr, 6689 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
6690 struct sched_domain *child, int cpu) 6690 struct sched_domain *child, int cpu)
6691 { 6691 {
6692 struct sched_domain *sd = sd_init(tl, cpu); 6692 struct sched_domain *sd = sd_init(tl, cpu);
6693 if (!sd) 6693 if (!sd)
6694 return child; 6694 return child;
6695 6695
6696 cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu)); 6696 cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
6697 if (child) { 6697 if (child) {
6698 sd->level = child->level + 1; 6698 sd->level = child->level + 1;
6699 sched_domain_level_max = max(sched_domain_level_max, sd->level); 6699 sched_domain_level_max = max(sched_domain_level_max, sd->level);
6700 child->parent = sd; 6700 child->parent = sd;
6701 sd->child = child; 6701 sd->child = child;
6702 6702
6703 if (!cpumask_subset(sched_domain_span(child), 6703 if (!cpumask_subset(sched_domain_span(child),
6704 sched_domain_span(sd))) { 6704 sched_domain_span(sd))) {
6705 pr_err("BUG: arch topology borken\n"); 6705 pr_err("BUG: arch topology borken\n");
6706 #ifdef CONFIG_SCHED_DEBUG 6706 #ifdef CONFIG_SCHED_DEBUG
6707 pr_err(" the %s domain not a subset of the %s domain\n", 6707 pr_err(" the %s domain not a subset of the %s domain\n",
6708 child->name, sd->name); 6708 child->name, sd->name);
6709 #endif 6709 #endif
6710 /* Fixup, ensure @sd has at least @child cpus. */ 6710 /* Fixup, ensure @sd has at least @child cpus. */
6711 cpumask_or(sched_domain_span(sd), 6711 cpumask_or(sched_domain_span(sd),
6712 sched_domain_span(sd), 6712 sched_domain_span(sd),
6713 sched_domain_span(child)); 6713 sched_domain_span(child));
6714 } 6714 }
6715 6715
6716 } 6716 }
6717 set_domain_attribute(sd, attr); 6717 set_domain_attribute(sd, attr);
6718 6718
6719 return sd; 6719 return sd;
6720 } 6720 }
6721 6721
6722 /* 6722 /*
6723 * Build sched domains for a given set of cpus and attach the sched domains 6723 * Build sched domains for a given set of cpus and attach the sched domains
6724 * to the individual cpus 6724 * to the individual cpus
6725 */ 6725 */
6726 static int build_sched_domains(const struct cpumask *cpu_map, 6726 static int build_sched_domains(const struct cpumask *cpu_map,
6727 struct sched_domain_attr *attr) 6727 struct sched_domain_attr *attr)
6728 { 6728 {
6729 enum s_alloc alloc_state; 6729 enum s_alloc alloc_state;
6730 struct sched_domain *sd; 6730 struct sched_domain *sd;
6731 struct s_data d; 6731 struct s_data d;
6732 int i, ret = -ENOMEM; 6732 int i, ret = -ENOMEM;
6733 6733
6734 alloc_state = __visit_domain_allocation_hell(&d, cpu_map); 6734 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
6735 if (alloc_state != sa_rootdomain) 6735 if (alloc_state != sa_rootdomain)
6736 goto error; 6736 goto error;
6737 6737
6738 /* Set up domains for cpus specified by the cpu_map. */ 6738 /* Set up domains for cpus specified by the cpu_map. */
6739 for_each_cpu(i, cpu_map) { 6739 for_each_cpu(i, cpu_map) {
6740 struct sched_domain_topology_level *tl; 6740 struct sched_domain_topology_level *tl;
6741 6741
6742 sd = NULL; 6742 sd = NULL;
6743 for_each_sd_topology(tl) { 6743 for_each_sd_topology(tl) {
6744 sd = build_sched_domain(tl, cpu_map, attr, sd, i); 6744 sd = build_sched_domain(tl, cpu_map, attr, sd, i);
6745 if (tl == sched_domain_topology) 6745 if (tl == sched_domain_topology)
6746 *per_cpu_ptr(d.sd, i) = sd; 6746 *per_cpu_ptr(d.sd, i) = sd;
6747 if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP)) 6747 if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
6748 sd->flags |= SD_OVERLAP; 6748 sd->flags |= SD_OVERLAP;
6749 if (cpumask_equal(cpu_map, sched_domain_span(sd))) 6749 if (cpumask_equal(cpu_map, sched_domain_span(sd)))
6750 break; 6750 break;
6751 } 6751 }
6752 } 6752 }
6753 6753
6754 /* Build the groups for the domains */ 6754 /* Build the groups for the domains */
6755 for_each_cpu(i, cpu_map) { 6755 for_each_cpu(i, cpu_map) {
6756 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) { 6756 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
6757 sd->span_weight = cpumask_weight(sched_domain_span(sd)); 6757 sd->span_weight = cpumask_weight(sched_domain_span(sd));
6758 if (sd->flags & SD_OVERLAP) { 6758 if (sd->flags & SD_OVERLAP) {
6759 if (build_overlap_sched_groups(sd, i)) 6759 if (build_overlap_sched_groups(sd, i))
6760 goto error; 6760 goto error;
6761 } else { 6761 } else {
6762 if (build_sched_groups(sd, i)) 6762 if (build_sched_groups(sd, i))
6763 goto error; 6763 goto error;
6764 } 6764 }
6765 } 6765 }
6766 } 6766 }
6767 6767
6768 /* Calculate CPU capacity for physical packages and nodes */ 6768 /* Calculate CPU capacity for physical packages and nodes */
6769 for (i = nr_cpumask_bits-1; i >= 0; i--) { 6769 for (i = nr_cpumask_bits-1; i >= 0; i--) {
6770 if (!cpumask_test_cpu(i, cpu_map)) 6770 if (!cpumask_test_cpu(i, cpu_map))
6771 continue; 6771 continue;
6772 6772
6773 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) { 6773 for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
6774 claim_allocations(i, sd); 6774 claim_allocations(i, sd);
6775 init_sched_groups_capacity(i, sd); 6775 init_sched_groups_capacity(i, sd);
6776 } 6776 }
6777 } 6777 }
6778 6778
6779 /* Attach the domains */ 6779 /* Attach the domains */
6780 rcu_read_lock(); 6780 rcu_read_lock();
6781 for_each_cpu(i, cpu_map) { 6781 for_each_cpu(i, cpu_map) {
6782 sd = *per_cpu_ptr(d.sd, i); 6782 sd = *per_cpu_ptr(d.sd, i);
6783 cpu_attach_domain(sd, d.rd, i); 6783 cpu_attach_domain(sd, d.rd, i);
6784 } 6784 }
6785 rcu_read_unlock(); 6785 rcu_read_unlock();
6786 6786
6787 ret = 0; 6787 ret = 0;
6788 error: 6788 error:
6789 __free_domain_allocs(&d, alloc_state, cpu_map); 6789 __free_domain_allocs(&d, alloc_state, cpu_map);
6790 return ret; 6790 return ret;
6791 } 6791 }
6792 6792
6793 static cpumask_var_t *doms_cur; /* current sched domains */ 6793 static cpumask_var_t *doms_cur; /* current sched domains */
6794 static int ndoms_cur; /* number of sched domains in 'doms_cur' */ 6794 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
6795 static struct sched_domain_attr *dattr_cur; 6795 static struct sched_domain_attr *dattr_cur;
6796 /* attribues of custom domains in 'doms_cur' */ 6796 /* attribues of custom domains in 'doms_cur' */
6797 6797
6798 /* 6798 /*
6799 * Special case: If a kmalloc of a doms_cur partition (array of 6799 * Special case: If a kmalloc of a doms_cur partition (array of
6800 * cpumask) fails, then fallback to a single sched domain, 6800 * cpumask) fails, then fallback to a single sched domain,
6801 * as determined by the single cpumask fallback_doms. 6801 * as determined by the single cpumask fallback_doms.
6802 */ 6802 */
6803 static cpumask_var_t fallback_doms; 6803 static cpumask_var_t fallback_doms;
6804 6804
6805 /* 6805 /*
6806 * arch_update_cpu_topology lets virtualized architectures update the 6806 * arch_update_cpu_topology lets virtualized architectures update the
6807 * cpu core maps. It is supposed to return 1 if the topology changed 6807 * cpu core maps. It is supposed to return 1 if the topology changed
6808 * or 0 if it stayed the same. 6808 * or 0 if it stayed the same.
6809 */ 6809 */
6810 int __weak arch_update_cpu_topology(void) 6810 int __weak arch_update_cpu_topology(void)
6811 { 6811 {
6812 return 0; 6812 return 0;
6813 } 6813 }
6814 6814
6815 cpumask_var_t *alloc_sched_domains(unsigned int ndoms) 6815 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
6816 { 6816 {
6817 int i; 6817 int i;
6818 cpumask_var_t *doms; 6818 cpumask_var_t *doms;
6819 6819
6820 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL); 6820 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
6821 if (!doms) 6821 if (!doms)
6822 return NULL; 6822 return NULL;
6823 for (i = 0; i < ndoms; i++) { 6823 for (i = 0; i < ndoms; i++) {
6824 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) { 6824 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
6825 free_sched_domains(doms, i); 6825 free_sched_domains(doms, i);
6826 return NULL; 6826 return NULL;
6827 } 6827 }
6828 } 6828 }
6829 return doms; 6829 return doms;
6830 } 6830 }
6831 6831
6832 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms) 6832 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
6833 { 6833 {
6834 unsigned int i; 6834 unsigned int i;
6835 for (i = 0; i < ndoms; i++) 6835 for (i = 0; i < ndoms; i++)
6836 free_cpumask_var(doms[i]); 6836 free_cpumask_var(doms[i]);
6837 kfree(doms); 6837 kfree(doms);
6838 } 6838 }
6839 6839
6840 /* 6840 /*
6841 * Set up scheduler domains and groups. Callers must hold the hotplug lock. 6841 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6842 * For now this just excludes isolated cpus, but could be used to 6842 * For now this just excludes isolated cpus, but could be used to
6843 * exclude other special cases in the future. 6843 * exclude other special cases in the future.
6844 */ 6844 */
6845 static int init_sched_domains(const struct cpumask *cpu_map) 6845 static int init_sched_domains(const struct cpumask *cpu_map)
6846 { 6846 {
6847 int err; 6847 int err;
6848 6848
6849 arch_update_cpu_topology(); 6849 arch_update_cpu_topology();
6850 ndoms_cur = 1; 6850 ndoms_cur = 1;
6851 doms_cur = alloc_sched_domains(ndoms_cur); 6851 doms_cur = alloc_sched_domains(ndoms_cur);
6852 if (!doms_cur) 6852 if (!doms_cur)
6853 doms_cur = &fallback_doms; 6853 doms_cur = &fallback_doms;
6854 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map); 6854 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
6855 err = build_sched_domains(doms_cur[0], NULL); 6855 err = build_sched_domains(doms_cur[0], NULL);
6856 register_sched_domain_sysctl(); 6856 register_sched_domain_sysctl();
6857 6857
6858 return err; 6858 return err;
6859 } 6859 }
6860 6860
6861 /* 6861 /*
6862 * Detach sched domains from a group of cpus specified in cpu_map 6862 * Detach sched domains from a group of cpus specified in cpu_map
6863 * These cpus will now be attached to the NULL domain 6863 * These cpus will now be attached to the NULL domain
6864 */ 6864 */
6865 static void detach_destroy_domains(const struct cpumask *cpu_map) 6865 static void detach_destroy_domains(const struct cpumask *cpu_map)
6866 { 6866 {
6867 int i; 6867 int i;
6868 6868
6869 rcu_read_lock(); 6869 rcu_read_lock();
6870 for_each_cpu(i, cpu_map) 6870 for_each_cpu(i, cpu_map)
6871 cpu_attach_domain(NULL, &def_root_domain, i); 6871 cpu_attach_domain(NULL, &def_root_domain, i);
6872 rcu_read_unlock(); 6872 rcu_read_unlock();
6873 } 6873 }
6874 6874
6875 /* handle null as "default" */ 6875 /* handle null as "default" */
6876 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur, 6876 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
6877 struct sched_domain_attr *new, int idx_new) 6877 struct sched_domain_attr *new, int idx_new)
6878 { 6878 {
6879 struct sched_domain_attr tmp; 6879 struct sched_domain_attr tmp;
6880 6880
6881 /* fast path */ 6881 /* fast path */
6882 if (!new && !cur) 6882 if (!new && !cur)
6883 return 1; 6883 return 1;
6884 6884
6885 tmp = SD_ATTR_INIT; 6885 tmp = SD_ATTR_INIT;
6886 return !memcmp(cur ? (cur + idx_cur) : &tmp, 6886 return !memcmp(cur ? (cur + idx_cur) : &tmp,
6887 new ? (new + idx_new) : &tmp, 6887 new ? (new + idx_new) : &tmp,
6888 sizeof(struct sched_domain_attr)); 6888 sizeof(struct sched_domain_attr));
6889 } 6889 }
6890 6890
6891 /* 6891 /*
6892 * Partition sched domains as specified by the 'ndoms_new' 6892 * Partition sched domains as specified by the 'ndoms_new'
6893 * cpumasks in the array doms_new[] of cpumasks. This compares 6893 * cpumasks in the array doms_new[] of cpumasks. This compares
6894 * doms_new[] to the current sched domain partitioning, doms_cur[]. 6894 * doms_new[] to the current sched domain partitioning, doms_cur[].
6895 * It destroys each deleted domain and builds each new domain. 6895 * It destroys each deleted domain and builds each new domain.
6896 * 6896 *
6897 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'. 6897 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
6898 * The masks don't intersect (don't overlap.) We should setup one 6898 * The masks don't intersect (don't overlap.) We should setup one
6899 * sched domain for each mask. CPUs not in any of the cpumasks will 6899 * sched domain for each mask. CPUs not in any of the cpumasks will
6900 * not be load balanced. If the same cpumask appears both in the 6900 * not be load balanced. If the same cpumask appears both in the
6901 * current 'doms_cur' domains and in the new 'doms_new', we can leave 6901 * current 'doms_cur' domains and in the new 'doms_new', we can leave
6902 * it as it is. 6902 * it as it is.
6903 * 6903 *
6904 * The passed in 'doms_new' should be allocated using 6904 * The passed in 'doms_new' should be allocated using
6905 * alloc_sched_domains. This routine takes ownership of it and will 6905 * alloc_sched_domains. This routine takes ownership of it and will
6906 * free_sched_domains it when done with it. If the caller failed the 6906 * free_sched_domains it when done with it. If the caller failed the
6907 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1, 6907 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
6908 * and partition_sched_domains() will fallback to the single partition 6908 * and partition_sched_domains() will fallback to the single partition
6909 * 'fallback_doms', it also forces the domains to be rebuilt. 6909 * 'fallback_doms', it also forces the domains to be rebuilt.
6910 * 6910 *
6911 * If doms_new == NULL it will be replaced with cpu_online_mask. 6911 * If doms_new == NULL it will be replaced with cpu_online_mask.
6912 * ndoms_new == 0 is a special case for destroying existing domains, 6912 * ndoms_new == 0 is a special case for destroying existing domains,
6913 * and it will not create the default domain. 6913 * and it will not create the default domain.
6914 * 6914 *
6915 * Call with hotplug lock held 6915 * Call with hotplug lock held
6916 */ 6916 */
6917 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[], 6917 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
6918 struct sched_domain_attr *dattr_new) 6918 struct sched_domain_attr *dattr_new)
6919 { 6919 {
6920 int i, j, n; 6920 int i, j, n;
6921 int new_topology; 6921 int new_topology;
6922 6922
6923 mutex_lock(&sched_domains_mutex); 6923 mutex_lock(&sched_domains_mutex);
6924 6924
6925 /* always unregister in case we don't destroy any domains */ 6925 /* always unregister in case we don't destroy any domains */
6926 unregister_sched_domain_sysctl(); 6926 unregister_sched_domain_sysctl();
6927 6927
6928 /* Let architecture update cpu core mappings. */ 6928 /* Let architecture update cpu core mappings. */
6929 new_topology = arch_update_cpu_topology(); 6929 new_topology = arch_update_cpu_topology();
6930 6930
6931 n = doms_new ? ndoms_new : 0; 6931 n = doms_new ? ndoms_new : 0;
6932 6932
6933 /* Destroy deleted domains */ 6933 /* Destroy deleted domains */
6934 for (i = 0; i < ndoms_cur; i++) { 6934 for (i = 0; i < ndoms_cur; i++) {
6935 for (j = 0; j < n && !new_topology; j++) { 6935 for (j = 0; j < n && !new_topology; j++) {
6936 if (cpumask_equal(doms_cur[i], doms_new[j]) 6936 if (cpumask_equal(doms_cur[i], doms_new[j])
6937 && dattrs_equal(dattr_cur, i, dattr_new, j)) 6937 && dattrs_equal(dattr_cur, i, dattr_new, j))
6938 goto match1; 6938 goto match1;
6939 } 6939 }
6940 /* no match - a current sched domain not in new doms_new[] */ 6940 /* no match - a current sched domain not in new doms_new[] */
6941 detach_destroy_domains(doms_cur[i]); 6941 detach_destroy_domains(doms_cur[i]);
6942 match1: 6942 match1:
6943 ; 6943 ;
6944 } 6944 }
6945 6945
6946 n = ndoms_cur; 6946 n = ndoms_cur;
6947 if (doms_new == NULL) { 6947 if (doms_new == NULL) {
6948 n = 0; 6948 n = 0;
6949 doms_new = &fallback_doms; 6949 doms_new = &fallback_doms;
6950 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map); 6950 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
6951 WARN_ON_ONCE(dattr_new); 6951 WARN_ON_ONCE(dattr_new);
6952 } 6952 }
6953 6953
6954 /* Build new domains */ 6954 /* Build new domains */
6955 for (i = 0; i < ndoms_new; i++) { 6955 for (i = 0; i < ndoms_new; i++) {
6956 for (j = 0; j < n && !new_topology; j++) { 6956 for (j = 0; j < n && !new_topology; j++) {
6957 if (cpumask_equal(doms_new[i], doms_cur[j]) 6957 if (cpumask_equal(doms_new[i], doms_cur[j])
6958 && dattrs_equal(dattr_new, i, dattr_cur, j)) 6958 && dattrs_equal(dattr_new, i, dattr_cur, j))
6959 goto match2; 6959 goto match2;
6960 } 6960 }
6961 /* no match - add a new doms_new */ 6961 /* no match - add a new doms_new */
6962 build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL); 6962 build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
6963 match2: 6963 match2:
6964 ; 6964 ;
6965 } 6965 }
6966 6966
6967 /* Remember the new sched domains */ 6967 /* Remember the new sched domains */
6968 if (doms_cur != &fallback_doms) 6968 if (doms_cur != &fallback_doms)
6969 free_sched_domains(doms_cur, ndoms_cur); 6969 free_sched_domains(doms_cur, ndoms_cur);
6970 kfree(dattr_cur); /* kfree(NULL) is safe */ 6970 kfree(dattr_cur); /* kfree(NULL) is safe */
6971 doms_cur = doms_new; 6971 doms_cur = doms_new;
6972 dattr_cur = dattr_new; 6972 dattr_cur = dattr_new;
6973 ndoms_cur = ndoms_new; 6973 ndoms_cur = ndoms_new;
6974 6974
6975 register_sched_domain_sysctl(); 6975 register_sched_domain_sysctl();
6976 6976
6977 mutex_unlock(&sched_domains_mutex); 6977 mutex_unlock(&sched_domains_mutex);
6978 } 6978 }
6979 6979
6980 static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */ 6980 static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */
6981 6981
6982 /* 6982 /*
6983 * Update cpusets according to cpu_active mask. If cpusets are 6983 * Update cpusets according to cpu_active mask. If cpusets are
6984 * disabled, cpuset_update_active_cpus() becomes a simple wrapper 6984 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
6985 * around partition_sched_domains(). 6985 * around partition_sched_domains().
6986 * 6986 *
6987 * If we come here as part of a suspend/resume, don't touch cpusets because we 6987 * If we come here as part of a suspend/resume, don't touch cpusets because we
6988 * want to restore it back to its original state upon resume anyway. 6988 * want to restore it back to its original state upon resume anyway.
6989 */ 6989 */
6990 static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action, 6990 static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
6991 void *hcpu) 6991 void *hcpu)
6992 { 6992 {
6993 switch (action) { 6993 switch (action) {
6994 case CPU_ONLINE_FROZEN: 6994 case CPU_ONLINE_FROZEN:
6995 case CPU_DOWN_FAILED_FROZEN: 6995 case CPU_DOWN_FAILED_FROZEN:
6996 6996
6997 /* 6997 /*
6998 * num_cpus_frozen tracks how many CPUs are involved in suspend 6998 * num_cpus_frozen tracks how many CPUs are involved in suspend
6999 * resume sequence. As long as this is not the last online 6999 * resume sequence. As long as this is not the last online
7000 * operation in the resume sequence, just build a single sched 7000 * operation in the resume sequence, just build a single sched
7001 * domain, ignoring cpusets. 7001 * domain, ignoring cpusets.
7002 */ 7002 */
7003 num_cpus_frozen--; 7003 num_cpus_frozen--;
7004 if (likely(num_cpus_frozen)) { 7004 if (likely(num_cpus_frozen)) {
7005 partition_sched_domains(1, NULL, NULL); 7005 partition_sched_domains(1, NULL, NULL);
7006 break; 7006 break;
7007 } 7007 }
7008 7008
7009 /* 7009 /*
7010 * This is the last CPU online operation. So fall through and 7010 * This is the last CPU online operation. So fall through and
7011 * restore the original sched domains by considering the 7011 * restore the original sched domains by considering the
7012 * cpuset configurations. 7012 * cpuset configurations.
7013 */ 7013 */
7014 7014
7015 case CPU_ONLINE: 7015 case CPU_ONLINE:
7016 case CPU_DOWN_FAILED: 7016 case CPU_DOWN_FAILED:
7017 cpuset_update_active_cpus(true); 7017 cpuset_update_active_cpus(true);
7018 break; 7018 break;
7019 default: 7019 default:
7020 return NOTIFY_DONE; 7020 return NOTIFY_DONE;
7021 } 7021 }
7022 return NOTIFY_OK; 7022 return NOTIFY_OK;
7023 } 7023 }
7024 7024
7025 static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action, 7025 static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
7026 void *hcpu) 7026 void *hcpu)
7027 { 7027 {
7028 switch (action) { 7028 switch (action) {
7029 case CPU_DOWN_PREPARE: 7029 case CPU_DOWN_PREPARE:
7030 cpuset_update_active_cpus(false); 7030 cpuset_update_active_cpus(false);
7031 break; 7031 break;
7032 case CPU_DOWN_PREPARE_FROZEN: 7032 case CPU_DOWN_PREPARE_FROZEN:
7033 num_cpus_frozen++; 7033 num_cpus_frozen++;
7034 partition_sched_domains(1, NULL, NULL); 7034 partition_sched_domains(1, NULL, NULL);
7035 break; 7035 break;
7036 default: 7036 default:
7037 return NOTIFY_DONE; 7037 return NOTIFY_DONE;
7038 } 7038 }
7039 return NOTIFY_OK; 7039 return NOTIFY_OK;
7040 } 7040 }
7041 7041
7042 void __init sched_init_smp(void) 7042 void __init sched_init_smp(void)
7043 { 7043 {
7044 cpumask_var_t non_isolated_cpus; 7044 cpumask_var_t non_isolated_cpus;
7045 7045
7046 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL); 7046 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
7047 alloc_cpumask_var(&fallback_doms, GFP_KERNEL); 7047 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
7048 7048
7049 sched_init_numa(); 7049 sched_init_numa();
7050 7050
7051 /* 7051 /*
7052 * There's no userspace yet to cause hotplug operations; hence all the 7052 * There's no userspace yet to cause hotplug operations; hence all the
7053 * cpu masks are stable and all blatant races in the below code cannot 7053 * cpu masks are stable and all blatant races in the below code cannot
7054 * happen. 7054 * happen.
7055 */ 7055 */
7056 mutex_lock(&sched_domains_mutex); 7056 mutex_lock(&sched_domains_mutex);
7057 init_sched_domains(cpu_active_mask); 7057 init_sched_domains(cpu_active_mask);
7058 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map); 7058 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
7059 if (cpumask_empty(non_isolated_cpus)) 7059 if (cpumask_empty(non_isolated_cpus))
7060 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus); 7060 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
7061 mutex_unlock(&sched_domains_mutex); 7061 mutex_unlock(&sched_domains_mutex);
7062 7062
7063 hotcpu_notifier(sched_domains_numa_masks_update, CPU_PRI_SCHED_ACTIVE); 7063 hotcpu_notifier(sched_domains_numa_masks_update, CPU_PRI_SCHED_ACTIVE);
7064 hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE); 7064 hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
7065 hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE); 7065 hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
7066 7066
7067 init_hrtick(); 7067 init_hrtick();
7068 7068
7069 /* Move init over to a non-isolated CPU */ 7069 /* Move init over to a non-isolated CPU */
7070 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0) 7070 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
7071 BUG(); 7071 BUG();
7072 sched_init_granularity(); 7072 sched_init_granularity();
7073 free_cpumask_var(non_isolated_cpus); 7073 free_cpumask_var(non_isolated_cpus);
7074 7074
7075 init_sched_rt_class(); 7075 init_sched_rt_class();
7076 init_sched_dl_class(); 7076 init_sched_dl_class();
7077 } 7077 }
7078 #else 7078 #else
7079 void __init sched_init_smp(void) 7079 void __init sched_init_smp(void)
7080 { 7080 {
7081 sched_init_granularity(); 7081 sched_init_granularity();
7082 } 7082 }
7083 #endif /* CONFIG_SMP */ 7083 #endif /* CONFIG_SMP */
7084 7084
7085 const_debug unsigned int sysctl_timer_migration = 1; 7085 const_debug unsigned int sysctl_timer_migration = 1;
7086 7086
7087 int in_sched_functions(unsigned long addr) 7087 int in_sched_functions(unsigned long addr)
7088 { 7088 {
7089 return in_lock_functions(addr) || 7089 return in_lock_functions(addr) ||
7090 (addr >= (unsigned long)__sched_text_start 7090 (addr >= (unsigned long)__sched_text_start
7091 && addr < (unsigned long)__sched_text_end); 7091 && addr < (unsigned long)__sched_text_end);
7092 } 7092 }
7093 7093
7094 #ifdef CONFIG_CGROUP_SCHED 7094 #ifdef CONFIG_CGROUP_SCHED
7095 /* 7095 /*
7096 * Default task group. 7096 * Default task group.
7097 * Every task in system belongs to this group at bootup. 7097 * Every task in system belongs to this group at bootup.
7098 */ 7098 */
7099 struct task_group root_task_group; 7099 struct task_group root_task_group;
7100 LIST_HEAD(task_groups); 7100 LIST_HEAD(task_groups);
7101 #endif 7101 #endif
7102 7102
7103 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask); 7103 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
7104 7104
7105 void __init sched_init(void) 7105 void __init sched_init(void)
7106 { 7106 {
7107 int i, j; 7107 int i, j;
7108 unsigned long alloc_size = 0, ptr; 7108 unsigned long alloc_size = 0, ptr;
7109 7109
7110 #ifdef CONFIG_FAIR_GROUP_SCHED 7110 #ifdef CONFIG_FAIR_GROUP_SCHED
7111 alloc_size += 2 * nr_cpu_ids * sizeof(void **); 7111 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7112 #endif 7112 #endif
7113 #ifdef CONFIG_RT_GROUP_SCHED 7113 #ifdef CONFIG_RT_GROUP_SCHED
7114 alloc_size += 2 * nr_cpu_ids * sizeof(void **); 7114 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7115 #endif 7115 #endif
7116 #ifdef CONFIG_CPUMASK_OFFSTACK
7117 alloc_size += num_possible_cpus() * cpumask_size();
7118 #endif
7119 if (alloc_size) { 7116 if (alloc_size) {
7120 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT); 7117 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
7121 7118
7122 #ifdef CONFIG_FAIR_GROUP_SCHED 7119 #ifdef CONFIG_FAIR_GROUP_SCHED
7123 root_task_group.se = (struct sched_entity **)ptr; 7120 root_task_group.se = (struct sched_entity **)ptr;
7124 ptr += nr_cpu_ids * sizeof(void **); 7121 ptr += nr_cpu_ids * sizeof(void **);
7125 7122
7126 root_task_group.cfs_rq = (struct cfs_rq **)ptr; 7123 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
7127 ptr += nr_cpu_ids * sizeof(void **); 7124 ptr += nr_cpu_ids * sizeof(void **);
7128 7125
7129 #endif /* CONFIG_FAIR_GROUP_SCHED */ 7126 #endif /* CONFIG_FAIR_GROUP_SCHED */
7130 #ifdef CONFIG_RT_GROUP_SCHED 7127 #ifdef CONFIG_RT_GROUP_SCHED
7131 root_task_group.rt_se = (struct sched_rt_entity **)ptr; 7128 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
7132 ptr += nr_cpu_ids * sizeof(void **); 7129 ptr += nr_cpu_ids * sizeof(void **);
7133 7130
7134 root_task_group.rt_rq = (struct rt_rq **)ptr; 7131 root_task_group.rt_rq = (struct rt_rq **)ptr;
7135 ptr += nr_cpu_ids * sizeof(void **); 7132 ptr += nr_cpu_ids * sizeof(void **);
7136 7133
7137 #endif /* CONFIG_RT_GROUP_SCHED */ 7134 #endif /* CONFIG_RT_GROUP_SCHED */
7135 }
7138 #ifdef CONFIG_CPUMASK_OFFSTACK 7136 #ifdef CONFIG_CPUMASK_OFFSTACK
7139 for_each_possible_cpu(i) { 7137 for_each_possible_cpu(i) {
7140 per_cpu(load_balance_mask, i) = (void *)ptr; 7138 per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
7141 ptr += cpumask_size(); 7139 cpumask_size(), GFP_KERNEL, cpu_to_node(i));
7142 }
7143 #endif /* CONFIG_CPUMASK_OFFSTACK */
7144 } 7140 }
7141 #endif /* CONFIG_CPUMASK_OFFSTACK */
7145 7142
7146 init_rt_bandwidth(&def_rt_bandwidth, 7143 init_rt_bandwidth(&def_rt_bandwidth,
7147 global_rt_period(), global_rt_runtime()); 7144 global_rt_period(), global_rt_runtime());
7148 init_dl_bandwidth(&def_dl_bandwidth, 7145 init_dl_bandwidth(&def_dl_bandwidth,
7149 global_rt_period(), global_rt_runtime()); 7146 global_rt_period(), global_rt_runtime());
7150 7147
7151 #ifdef CONFIG_SMP 7148 #ifdef CONFIG_SMP
7152 init_defrootdomain(); 7149 init_defrootdomain();
7153 #endif 7150 #endif
7154 7151
7155 #ifdef CONFIG_RT_GROUP_SCHED 7152 #ifdef CONFIG_RT_GROUP_SCHED
7156 init_rt_bandwidth(&root_task_group.rt_bandwidth, 7153 init_rt_bandwidth(&root_task_group.rt_bandwidth,
7157 global_rt_period(), global_rt_runtime()); 7154 global_rt_period(), global_rt_runtime());
7158 #endif /* CONFIG_RT_GROUP_SCHED */ 7155 #endif /* CONFIG_RT_GROUP_SCHED */
7159 7156
7160 #ifdef CONFIG_CGROUP_SCHED 7157 #ifdef CONFIG_CGROUP_SCHED
7161 list_add(&root_task_group.list, &task_groups); 7158 list_add(&root_task_group.list, &task_groups);
7162 INIT_LIST_HEAD(&root_task_group.children); 7159 INIT_LIST_HEAD(&root_task_group.children);
7163 INIT_LIST_HEAD(&root_task_group.siblings); 7160 INIT_LIST_HEAD(&root_task_group.siblings);
7164 autogroup_init(&init_task); 7161 autogroup_init(&init_task);
7165 7162
7166 #endif /* CONFIG_CGROUP_SCHED */ 7163 #endif /* CONFIG_CGROUP_SCHED */
7167 7164
7168 for_each_possible_cpu(i) { 7165 for_each_possible_cpu(i) {
7169 struct rq *rq; 7166 struct rq *rq;
7170 7167
7171 rq = cpu_rq(i); 7168 rq = cpu_rq(i);
7172 raw_spin_lock_init(&rq->lock); 7169 raw_spin_lock_init(&rq->lock);
7173 rq->nr_running = 0; 7170 rq->nr_running = 0;
7174 rq->calc_load_active = 0; 7171 rq->calc_load_active = 0;
7175 rq->calc_load_update = jiffies + LOAD_FREQ; 7172 rq->calc_load_update = jiffies + LOAD_FREQ;
7176 init_cfs_rq(&rq->cfs); 7173 init_cfs_rq(&rq->cfs);
7177 init_rt_rq(&rq->rt, rq); 7174 init_rt_rq(&rq->rt, rq);
7178 init_dl_rq(&rq->dl, rq); 7175 init_dl_rq(&rq->dl, rq);
7179 #ifdef CONFIG_FAIR_GROUP_SCHED 7176 #ifdef CONFIG_FAIR_GROUP_SCHED
7180 root_task_group.shares = ROOT_TASK_GROUP_LOAD; 7177 root_task_group.shares = ROOT_TASK_GROUP_LOAD;
7181 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list); 7178 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7182 /* 7179 /*
7183 * How much cpu bandwidth does root_task_group get? 7180 * How much cpu bandwidth does root_task_group get?
7184 * 7181 *
7185 * In case of task-groups formed thr' the cgroup filesystem, it 7182 * In case of task-groups formed thr' the cgroup filesystem, it
7186 * gets 100% of the cpu resources in the system. This overall 7183 * gets 100% of the cpu resources in the system. This overall
7187 * system cpu resource is divided among the tasks of 7184 * system cpu resource is divided among the tasks of
7188 * root_task_group and its child task-groups in a fair manner, 7185 * root_task_group and its child task-groups in a fair manner,
7189 * based on each entity's (task or task-group's) weight 7186 * based on each entity's (task or task-group's) weight
7190 * (se->load.weight). 7187 * (se->load.weight).
7191 * 7188 *
7192 * In other words, if root_task_group has 10 tasks of weight 7189 * In other words, if root_task_group has 10 tasks of weight
7193 * 1024) and two child groups A0 and A1 (of weight 1024 each), 7190 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7194 * then A0's share of the cpu resource is: 7191 * then A0's share of the cpu resource is:
7195 * 7192 *
7196 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33% 7193 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7197 * 7194 *
7198 * We achieve this by letting root_task_group's tasks sit 7195 * We achieve this by letting root_task_group's tasks sit
7199 * directly in rq->cfs (i.e root_task_group->se[] = NULL). 7196 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
7200 */ 7197 */
7201 init_cfs_bandwidth(&root_task_group.cfs_bandwidth); 7198 init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
7202 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL); 7199 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
7203 #endif /* CONFIG_FAIR_GROUP_SCHED */ 7200 #endif /* CONFIG_FAIR_GROUP_SCHED */
7204 7201
7205 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime; 7202 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7206 #ifdef CONFIG_RT_GROUP_SCHED 7203 #ifdef CONFIG_RT_GROUP_SCHED
7207 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL); 7204 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
7208 #endif 7205 #endif
7209 7206
7210 for (j = 0; j < CPU_LOAD_IDX_MAX; j++) 7207 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7211 rq->cpu_load[j] = 0; 7208 rq->cpu_load[j] = 0;
7212 7209
7213 rq->last_load_update_tick = jiffies; 7210 rq->last_load_update_tick = jiffies;
7214 7211
7215 #ifdef CONFIG_SMP 7212 #ifdef CONFIG_SMP
7216 rq->sd = NULL; 7213 rq->sd = NULL;
7217 rq->rd = NULL; 7214 rq->rd = NULL;
7218 rq->cpu_capacity = SCHED_CAPACITY_SCALE; 7215 rq->cpu_capacity = SCHED_CAPACITY_SCALE;
7219 rq->post_schedule = 0; 7216 rq->post_schedule = 0;
7220 rq->active_balance = 0; 7217 rq->active_balance = 0;
7221 rq->next_balance = jiffies; 7218 rq->next_balance = jiffies;
7222 rq->push_cpu = 0; 7219 rq->push_cpu = 0;
7223 rq->cpu = i; 7220 rq->cpu = i;
7224 rq->online = 0; 7221 rq->online = 0;
7225 rq->idle_stamp = 0; 7222 rq->idle_stamp = 0;
7226 rq->avg_idle = 2*sysctl_sched_migration_cost; 7223 rq->avg_idle = 2*sysctl_sched_migration_cost;
7227 rq->max_idle_balance_cost = sysctl_sched_migration_cost; 7224 rq->max_idle_balance_cost = sysctl_sched_migration_cost;
7228 7225
7229 INIT_LIST_HEAD(&rq->cfs_tasks); 7226 INIT_LIST_HEAD(&rq->cfs_tasks);
7230 7227
7231 rq_attach_root(rq, &def_root_domain); 7228 rq_attach_root(rq, &def_root_domain);
7232 #ifdef CONFIG_NO_HZ_COMMON 7229 #ifdef CONFIG_NO_HZ_COMMON
7233 rq->nohz_flags = 0; 7230 rq->nohz_flags = 0;
7234 #endif 7231 #endif
7235 #ifdef CONFIG_NO_HZ_FULL 7232 #ifdef CONFIG_NO_HZ_FULL
7236 rq->last_sched_tick = 0; 7233 rq->last_sched_tick = 0;
7237 #endif 7234 #endif
7238 #endif 7235 #endif
7239 init_rq_hrtick(rq); 7236 init_rq_hrtick(rq);
7240 atomic_set(&rq->nr_iowait, 0); 7237 atomic_set(&rq->nr_iowait, 0);
7241 } 7238 }
7242 7239
7243 set_load_weight(&init_task); 7240 set_load_weight(&init_task);
7244 7241
7245 #ifdef CONFIG_PREEMPT_NOTIFIERS 7242 #ifdef CONFIG_PREEMPT_NOTIFIERS
7246 INIT_HLIST_HEAD(&init_task.preempt_notifiers); 7243 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7247 #endif 7244 #endif
7248 7245
7249 /* 7246 /*
7250 * The boot idle thread does lazy MMU switching as well: 7247 * The boot idle thread does lazy MMU switching as well:
7251 */ 7248 */
7252 atomic_inc(&init_mm.mm_count); 7249 atomic_inc(&init_mm.mm_count);
7253 enter_lazy_tlb(&init_mm, current); 7250 enter_lazy_tlb(&init_mm, current);
7254 7251
7255 /* 7252 /*
7256 * Make us the idle thread. Technically, schedule() should not be 7253 * Make us the idle thread. Technically, schedule() should not be
7257 * called from this thread, however somewhere below it might be, 7254 * called from this thread, however somewhere below it might be,
7258 * but because we are the idle thread, we just pick up running again 7255 * but because we are the idle thread, we just pick up running again
7259 * when this runqueue becomes "idle". 7256 * when this runqueue becomes "idle".
7260 */ 7257 */
7261 init_idle(current, smp_processor_id()); 7258 init_idle(current, smp_processor_id());
7262 7259
7263 calc_load_update = jiffies + LOAD_FREQ; 7260 calc_load_update = jiffies + LOAD_FREQ;
7264 7261
7265 /* 7262 /*
7266 * During early bootup we pretend to be a normal task: 7263 * During early bootup we pretend to be a normal task:
7267 */ 7264 */
7268 current->sched_class = &fair_sched_class; 7265 current->sched_class = &fair_sched_class;
7269 7266
7270 #ifdef CONFIG_SMP 7267 #ifdef CONFIG_SMP
7271 zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT); 7268 zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
7272 /* May be allocated at isolcpus cmdline parse time */ 7269 /* May be allocated at isolcpus cmdline parse time */
7273 if (cpu_isolated_map == NULL) 7270 if (cpu_isolated_map == NULL)
7274 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT); 7271 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
7275 idle_thread_set_boot_cpu(); 7272 idle_thread_set_boot_cpu();
7276 set_cpu_rq_start_time(); 7273 set_cpu_rq_start_time();
7277 #endif 7274 #endif
7278 init_sched_fair_class(); 7275 init_sched_fair_class();
7279 7276
7280 scheduler_running = 1; 7277 scheduler_running = 1;
7281 } 7278 }
7282 7279
7283 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP 7280 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
7284 static inline int preempt_count_equals(int preempt_offset) 7281 static inline int preempt_count_equals(int preempt_offset)
7285 { 7282 {
7286 int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth(); 7283 int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
7287 7284
7288 return (nested == preempt_offset); 7285 return (nested == preempt_offset);
7289 } 7286 }
7290 7287
7291 void __might_sleep(const char *file, int line, int preempt_offset) 7288 void __might_sleep(const char *file, int line, int preempt_offset)
7292 { 7289 {
7293 /* 7290 /*
7294 * Blocking primitives will set (and therefore destroy) current->state, 7291 * Blocking primitives will set (and therefore destroy) current->state,
7295 * since we will exit with TASK_RUNNING make sure we enter with it, 7292 * since we will exit with TASK_RUNNING make sure we enter with it,
7296 * otherwise we will destroy state. 7293 * otherwise we will destroy state.
7297 */ 7294 */
7298 if (WARN_ONCE(current->state != TASK_RUNNING, 7295 if (WARN_ONCE(current->state != TASK_RUNNING,
7299 "do not call blocking ops when !TASK_RUNNING; " 7296 "do not call blocking ops when !TASK_RUNNING; "
7300 "state=%lx set at [<%p>] %pS\n", 7297 "state=%lx set at [<%p>] %pS\n",
7301 current->state, 7298 current->state,
7302 (void *)current->task_state_change, 7299 (void *)current->task_state_change,
7303 (void *)current->task_state_change)) 7300 (void *)current->task_state_change))
7304 __set_current_state(TASK_RUNNING); 7301 __set_current_state(TASK_RUNNING);
7305 7302
7306 ___might_sleep(file, line, preempt_offset); 7303 ___might_sleep(file, line, preempt_offset);
7307 } 7304 }
7308 EXPORT_SYMBOL(__might_sleep); 7305 EXPORT_SYMBOL(__might_sleep);
7309 7306
7310 void ___might_sleep(const char *file, int line, int preempt_offset) 7307 void ___might_sleep(const char *file, int line, int preempt_offset)
7311 { 7308 {
7312 static unsigned long prev_jiffy; /* ratelimiting */ 7309 static unsigned long prev_jiffy; /* ratelimiting */
7313 7310
7314 rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */ 7311 rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
7315 if ((preempt_count_equals(preempt_offset) && !irqs_disabled() && 7312 if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
7316 !is_idle_task(current)) || 7313 !is_idle_task(current)) ||
7317 system_state != SYSTEM_RUNNING || oops_in_progress) 7314 system_state != SYSTEM_RUNNING || oops_in_progress)
7318 return; 7315 return;
7319 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) 7316 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7320 return; 7317 return;
7321 prev_jiffy = jiffies; 7318 prev_jiffy = jiffies;
7322 7319
7323 printk(KERN_ERR 7320 printk(KERN_ERR
7324 "BUG: sleeping function called from invalid context at %s:%d\n", 7321 "BUG: sleeping function called from invalid context at %s:%d\n",
7325 file, line); 7322 file, line);
7326 printk(KERN_ERR 7323 printk(KERN_ERR
7327 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n", 7324 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7328 in_atomic(), irqs_disabled(), 7325 in_atomic(), irqs_disabled(),
7329 current->pid, current->comm); 7326 current->pid, current->comm);
7330 7327
7331 debug_show_held_locks(current); 7328 debug_show_held_locks(current);
7332 if (irqs_disabled()) 7329 if (irqs_disabled())
7333 print_irqtrace_events(current); 7330 print_irqtrace_events(current);
7334 #ifdef CONFIG_DEBUG_PREEMPT 7331 #ifdef CONFIG_DEBUG_PREEMPT
7335 if (!preempt_count_equals(preempt_offset)) { 7332 if (!preempt_count_equals(preempt_offset)) {
7336 pr_err("Preemption disabled at:"); 7333 pr_err("Preemption disabled at:");
7337 print_ip_sym(current->preempt_disable_ip); 7334 print_ip_sym(current->preempt_disable_ip);
7338 pr_cont("\n"); 7335 pr_cont("\n");
7339 } 7336 }
7340 #endif 7337 #endif
7341 dump_stack(); 7338 dump_stack();
7342 } 7339 }
7343 EXPORT_SYMBOL(___might_sleep); 7340 EXPORT_SYMBOL(___might_sleep);
7344 #endif 7341 #endif
7345 7342
7346 #ifdef CONFIG_MAGIC_SYSRQ 7343 #ifdef CONFIG_MAGIC_SYSRQ
7347 static void normalize_task(struct rq *rq, struct task_struct *p) 7344 static void normalize_task(struct rq *rq, struct task_struct *p)
7348 { 7345 {
7349 const struct sched_class *prev_class = p->sched_class; 7346 const struct sched_class *prev_class = p->sched_class;
7350 struct sched_attr attr = { 7347 struct sched_attr attr = {
7351 .sched_policy = SCHED_NORMAL, 7348 .sched_policy = SCHED_NORMAL,
7352 }; 7349 };
7353 int old_prio = p->prio; 7350 int old_prio = p->prio;
7354 int queued; 7351 int queued;
7355 7352
7356 queued = task_on_rq_queued(p); 7353 queued = task_on_rq_queued(p);
7357 if (queued) 7354 if (queued)
7358 dequeue_task(rq, p, 0); 7355 dequeue_task(rq, p, 0);
7359 __setscheduler(rq, p, &attr); 7356 __setscheduler(rq, p, &attr);
7360 if (queued) { 7357 if (queued) {
7361 enqueue_task(rq, p, 0); 7358 enqueue_task(rq, p, 0);
7362 resched_curr(rq); 7359 resched_curr(rq);
7363 } 7360 }
7364 7361
7365 check_class_changed(rq, p, prev_class, old_prio); 7362 check_class_changed(rq, p, prev_class, old_prio);
7366 } 7363 }
7367 7364
7368 void normalize_rt_tasks(void) 7365 void normalize_rt_tasks(void)
7369 { 7366 {
7370 struct task_struct *g, *p; 7367 struct task_struct *g, *p;
7371 unsigned long flags; 7368 unsigned long flags;
7372 struct rq *rq; 7369 struct rq *rq;
7373 7370
7374 read_lock(&tasklist_lock); 7371 read_lock(&tasklist_lock);
7375 for_each_process_thread(g, p) { 7372 for_each_process_thread(g, p) {
7376 /* 7373 /*
7377 * Only normalize user tasks: 7374 * Only normalize user tasks:
7378 */ 7375 */
7379 if (p->flags & PF_KTHREAD) 7376 if (p->flags & PF_KTHREAD)
7380 continue; 7377 continue;
7381 7378
7382 p->se.exec_start = 0; 7379 p->se.exec_start = 0;
7383 #ifdef CONFIG_SCHEDSTATS 7380 #ifdef CONFIG_SCHEDSTATS
7384 p->se.statistics.wait_start = 0; 7381 p->se.statistics.wait_start = 0;
7385 p->se.statistics.sleep_start = 0; 7382 p->se.statistics.sleep_start = 0;
7386 p->se.statistics.block_start = 0; 7383 p->se.statistics.block_start = 0;
7387 #endif 7384 #endif
7388 7385
7389 if (!dl_task(p) && !rt_task(p)) { 7386 if (!dl_task(p) && !rt_task(p)) {
7390 /* 7387 /*
7391 * Renice negative nice level userspace 7388 * Renice negative nice level userspace
7392 * tasks back to 0: 7389 * tasks back to 0:
7393 */ 7390 */
7394 if (task_nice(p) < 0) 7391 if (task_nice(p) < 0)
7395 set_user_nice(p, 0); 7392 set_user_nice(p, 0);
7396 continue; 7393 continue;
7397 } 7394 }
7398 7395
7399 rq = task_rq_lock(p, &flags); 7396 rq = task_rq_lock(p, &flags);
7400 normalize_task(rq, p); 7397 normalize_task(rq, p);
7401 task_rq_unlock(rq, p, &flags); 7398 task_rq_unlock(rq, p, &flags);
7402 } 7399 }
7403 read_unlock(&tasklist_lock); 7400 read_unlock(&tasklist_lock);
7404 } 7401 }
7405 7402
7406 #endif /* CONFIG_MAGIC_SYSRQ */ 7403 #endif /* CONFIG_MAGIC_SYSRQ */
7407 7404
7408 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) 7405 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
7409 /* 7406 /*
7410 * These functions are only useful for the IA64 MCA handling, or kdb. 7407 * These functions are only useful for the IA64 MCA handling, or kdb.
7411 * 7408 *
7412 * They can only be called when the whole system has been 7409 * They can only be called when the whole system has been
7413 * stopped - every CPU needs to be quiescent, and no scheduling 7410 * stopped - every CPU needs to be quiescent, and no scheduling
7414 * activity can take place. Using them for anything else would 7411 * activity can take place. Using them for anything else would
7415 * be a serious bug, and as a result, they aren't even visible 7412 * be a serious bug, and as a result, they aren't even visible
7416 * under any other configuration. 7413 * under any other configuration.
7417 */ 7414 */
7418 7415
7419 /** 7416 /**
7420 * curr_task - return the current task for a given cpu. 7417 * curr_task - return the current task for a given cpu.
7421 * @cpu: the processor in question. 7418 * @cpu: the processor in question.
7422 * 7419 *
7423 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED! 7420 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7424 * 7421 *
7425 * Return: The current task for @cpu. 7422 * Return: The current task for @cpu.
7426 */ 7423 */
7427 struct task_struct *curr_task(int cpu) 7424 struct task_struct *curr_task(int cpu)
7428 { 7425 {
7429 return cpu_curr(cpu); 7426 return cpu_curr(cpu);
7430 } 7427 }
7431 7428
7432 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */ 7429 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
7433 7430
7434 #ifdef CONFIG_IA64 7431 #ifdef CONFIG_IA64
7435 /** 7432 /**
7436 * set_curr_task - set the current task for a given cpu. 7433 * set_curr_task - set the current task for a given cpu.
7437 * @cpu: the processor in question. 7434 * @cpu: the processor in question.
7438 * @p: the task pointer to set. 7435 * @p: the task pointer to set.
7439 * 7436 *
7440 * Description: This function must only be used when non-maskable interrupts 7437 * Description: This function must only be used when non-maskable interrupts
7441 * are serviced on a separate stack. It allows the architecture to switch the 7438 * are serviced on a separate stack. It allows the architecture to switch the
7442 * notion of the current task on a cpu in a non-blocking manner. This function 7439 * notion of the current task on a cpu in a non-blocking manner. This function
7443 * must be called with all CPU's synchronized, and interrupts disabled, the 7440 * must be called with all CPU's synchronized, and interrupts disabled, the
7444 * and caller must save the original value of the current task (see 7441 * and caller must save the original value of the current task (see
7445 * curr_task() above) and restore that value before reenabling interrupts and 7442 * curr_task() above) and restore that value before reenabling interrupts and
7446 * re-starting the system. 7443 * re-starting the system.
7447 * 7444 *
7448 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED! 7445 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7449 */ 7446 */
7450 void set_curr_task(int cpu, struct task_struct *p) 7447 void set_curr_task(int cpu, struct task_struct *p)
7451 { 7448 {
7452 cpu_curr(cpu) = p; 7449 cpu_curr(cpu) = p;
7453 } 7450 }
7454 7451
7455 #endif 7452 #endif
7456 7453
7457 #ifdef CONFIG_CGROUP_SCHED 7454 #ifdef CONFIG_CGROUP_SCHED
7458 /* task_group_lock serializes the addition/removal of task groups */ 7455 /* task_group_lock serializes the addition/removal of task groups */
7459 static DEFINE_SPINLOCK(task_group_lock); 7456 static DEFINE_SPINLOCK(task_group_lock);
7460 7457
7461 static void free_sched_group(struct task_group *tg) 7458 static void free_sched_group(struct task_group *tg)
7462 { 7459 {
7463 free_fair_sched_group(tg); 7460 free_fair_sched_group(tg);
7464 free_rt_sched_group(tg); 7461 free_rt_sched_group(tg);
7465 autogroup_free(tg); 7462 autogroup_free(tg);
7466 kfree(tg); 7463 kfree(tg);
7467 } 7464 }
7468 7465
7469 /* allocate runqueue etc for a new task group */ 7466 /* allocate runqueue etc for a new task group */
7470 struct task_group *sched_create_group(struct task_group *parent) 7467 struct task_group *sched_create_group(struct task_group *parent)
7471 { 7468 {
7472 struct task_group *tg; 7469 struct task_group *tg;
7473 7470
7474 tg = kzalloc(sizeof(*tg), GFP_KERNEL); 7471 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
7475 if (!tg) 7472 if (!tg)
7476 return ERR_PTR(-ENOMEM); 7473 return ERR_PTR(-ENOMEM);
7477 7474
7478 if (!alloc_fair_sched_group(tg, parent)) 7475 if (!alloc_fair_sched_group(tg, parent))
7479 goto err; 7476 goto err;
7480 7477
7481 if (!alloc_rt_sched_group(tg, parent)) 7478 if (!alloc_rt_sched_group(tg, parent))
7482 goto err; 7479 goto err;
7483 7480
7484 return tg; 7481 return tg;
7485 7482
7486 err: 7483 err:
7487 free_sched_group(tg); 7484 free_sched_group(tg);
7488 return ERR_PTR(-ENOMEM); 7485 return ERR_PTR(-ENOMEM);
7489 } 7486 }
7490 7487
7491 void sched_online_group(struct task_group *tg, struct task_group *parent) 7488 void sched_online_group(struct task_group *tg, struct task_group *parent)
7492 { 7489 {
7493 unsigned long flags; 7490 unsigned long flags;
7494 7491
7495 spin_lock_irqsave(&task_group_lock, flags); 7492 spin_lock_irqsave(&task_group_lock, flags);
7496 list_add_rcu(&tg->list, &task_groups); 7493 list_add_rcu(&tg->list, &task_groups);
7497 7494
7498 WARN_ON(!parent); /* root should already exist */ 7495 WARN_ON(!parent); /* root should already exist */
7499 7496
7500 tg->parent = parent; 7497 tg->parent = parent;
7501 INIT_LIST_HEAD(&tg->children); 7498 INIT_LIST_HEAD(&tg->children);
7502 list_add_rcu(&tg->siblings, &parent->children); 7499 list_add_rcu(&tg->siblings, &parent->children);
7503 spin_unlock_irqrestore(&task_group_lock, flags); 7500 spin_unlock_irqrestore(&task_group_lock, flags);
7504 } 7501 }
7505 7502
7506 /* rcu callback to free various structures associated with a task group */ 7503 /* rcu callback to free various structures associated with a task group */
7507 static void free_sched_group_rcu(struct rcu_head *rhp) 7504 static void free_sched_group_rcu(struct rcu_head *rhp)
7508 { 7505 {
7509 /* now it should be safe to free those cfs_rqs */ 7506 /* now it should be safe to free those cfs_rqs */
7510 free_sched_group(container_of(rhp, struct task_group, rcu)); 7507 free_sched_group(container_of(rhp, struct task_group, rcu));
7511 } 7508 }
7512 7509
7513 /* Destroy runqueue etc associated with a task group */ 7510 /* Destroy runqueue etc associated with a task group */
7514 void sched_destroy_group(struct task_group *tg) 7511 void sched_destroy_group(struct task_group *tg)
7515 { 7512 {
7516 /* wait for possible concurrent references to cfs_rqs complete */ 7513 /* wait for possible concurrent references to cfs_rqs complete */
7517 call_rcu(&tg->rcu, free_sched_group_rcu); 7514 call_rcu(&tg->rcu, free_sched_group_rcu);
7518 } 7515 }
7519 7516
7520 void sched_offline_group(struct task_group *tg) 7517 void sched_offline_group(struct task_group *tg)
7521 { 7518 {
7522 unsigned long flags; 7519 unsigned long flags;
7523 int i; 7520 int i;
7524 7521
7525 /* end participation in shares distribution */ 7522 /* end participation in shares distribution */
7526 for_each_possible_cpu(i) 7523 for_each_possible_cpu(i)
7527 unregister_fair_sched_group(tg, i); 7524 unregister_fair_sched_group(tg, i);
7528 7525
7529 spin_lock_irqsave(&task_group_lock, flags); 7526 spin_lock_irqsave(&task_group_lock, flags);
7530 list_del_rcu(&tg->list); 7527 list_del_rcu(&tg->list);
7531 list_del_rcu(&tg->siblings); 7528 list_del_rcu(&tg->siblings);
7532 spin_unlock_irqrestore(&task_group_lock, flags); 7529 spin_unlock_irqrestore(&task_group_lock, flags);
7533 } 7530 }
7534 7531
7535 /* change task's runqueue when it moves between groups. 7532 /* change task's runqueue when it moves between groups.
7536 * The caller of this function should have put the task in its new group 7533 * The caller of this function should have put the task in its new group
7537 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to 7534 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7538 * reflect its new group. 7535 * reflect its new group.
7539 */ 7536 */
7540 void sched_move_task(struct task_struct *tsk) 7537 void sched_move_task(struct task_struct *tsk)
7541 { 7538 {
7542 struct task_group *tg; 7539 struct task_group *tg;
7543 int queued, running; 7540 int queued, running;
7544 unsigned long flags; 7541 unsigned long flags;
7545 struct rq *rq; 7542 struct rq *rq;
7546 7543
7547 rq = task_rq_lock(tsk, &flags); 7544 rq = task_rq_lock(tsk, &flags);
7548 7545
7549 running = task_current(rq, tsk); 7546 running = task_current(rq, tsk);
7550 queued = task_on_rq_queued(tsk); 7547 queued = task_on_rq_queued(tsk);
7551 7548
7552 if (queued) 7549 if (queued)
7553 dequeue_task(rq, tsk, 0); 7550 dequeue_task(rq, tsk, 0);
7554 if (unlikely(running)) 7551 if (unlikely(running))
7555 put_prev_task(rq, tsk); 7552 put_prev_task(rq, tsk);
7556 7553
7557 /* 7554 /*
7558 * All callers are synchronized by task_rq_lock(); we do not use RCU 7555 * All callers are synchronized by task_rq_lock(); we do not use RCU
7559 * which is pointless here. Thus, we pass "true" to task_css_check() 7556 * which is pointless here. Thus, we pass "true" to task_css_check()
7560 * to prevent lockdep warnings. 7557 * to prevent lockdep warnings.
7561 */ 7558 */
7562 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true), 7559 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
7563 struct task_group, css); 7560 struct task_group, css);
7564 tg = autogroup_task_group(tsk, tg); 7561 tg = autogroup_task_group(tsk, tg);
7565 tsk->sched_task_group = tg; 7562 tsk->sched_task_group = tg;
7566 7563
7567 #ifdef CONFIG_FAIR_GROUP_SCHED 7564 #ifdef CONFIG_FAIR_GROUP_SCHED
7568 if (tsk->sched_class->task_move_group) 7565 if (tsk->sched_class->task_move_group)
7569 tsk->sched_class->task_move_group(tsk, queued); 7566 tsk->sched_class->task_move_group(tsk, queued);
7570 else 7567 else
7571 #endif 7568 #endif
7572 set_task_rq(tsk, task_cpu(tsk)); 7569 set_task_rq(tsk, task_cpu(tsk));
7573 7570
7574 if (unlikely(running)) 7571 if (unlikely(running))
7575 tsk->sched_class->set_curr_task(rq); 7572 tsk->sched_class->set_curr_task(rq);
7576 if (queued) 7573 if (queued)
7577 enqueue_task(rq, tsk, 0); 7574 enqueue_task(rq, tsk, 0);
7578 7575
7579 task_rq_unlock(rq, tsk, &flags); 7576 task_rq_unlock(rq, tsk, &flags);
7580 } 7577 }
7581 #endif /* CONFIG_CGROUP_SCHED */ 7578 #endif /* CONFIG_CGROUP_SCHED */
7582 7579
7583 #ifdef CONFIG_RT_GROUP_SCHED 7580 #ifdef CONFIG_RT_GROUP_SCHED
7584 /* 7581 /*
7585 * Ensure that the real time constraints are schedulable. 7582 * Ensure that the real time constraints are schedulable.
7586 */ 7583 */
7587 static DEFINE_MUTEX(rt_constraints_mutex); 7584 static DEFINE_MUTEX(rt_constraints_mutex);
7588 7585
7589 /* Must be called with tasklist_lock held */ 7586 /* Must be called with tasklist_lock held */
7590 static inline int tg_has_rt_tasks(struct task_group *tg) 7587 static inline int tg_has_rt_tasks(struct task_group *tg)
7591 { 7588 {
7592 struct task_struct *g, *p; 7589 struct task_struct *g, *p;
7593 7590
7594 for_each_process_thread(g, p) { 7591 for_each_process_thread(g, p) {
7595 if (rt_task(p) && task_group(p) == tg) 7592 if (rt_task(p) && task_group(p) == tg)
7596 return 1; 7593 return 1;
7597 } 7594 }
7598 7595
7599 return 0; 7596 return 0;
7600 } 7597 }
7601 7598
7602 struct rt_schedulable_data { 7599 struct rt_schedulable_data {
7603 struct task_group *tg; 7600 struct task_group *tg;
7604 u64 rt_period; 7601 u64 rt_period;
7605 u64 rt_runtime; 7602 u64 rt_runtime;
7606 }; 7603 };
7607 7604
7608 static int tg_rt_schedulable(struct task_group *tg, void *data) 7605 static int tg_rt_schedulable(struct task_group *tg, void *data)
7609 { 7606 {
7610 struct rt_schedulable_data *d = data; 7607 struct rt_schedulable_data *d = data;
7611 struct task_group *child; 7608 struct task_group *child;
7612 unsigned long total, sum = 0; 7609 unsigned long total, sum = 0;
7613 u64 period, runtime; 7610 u64 period, runtime;
7614 7611
7615 period = ktime_to_ns(tg->rt_bandwidth.rt_period); 7612 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
7616 runtime = tg->rt_bandwidth.rt_runtime; 7613 runtime = tg->rt_bandwidth.rt_runtime;
7617 7614
7618 if (tg == d->tg) { 7615 if (tg == d->tg) {
7619 period = d->rt_period; 7616 period = d->rt_period;
7620 runtime = d->rt_runtime; 7617 runtime = d->rt_runtime;
7621 } 7618 }
7622 7619
7623 /* 7620 /*
7624 * Cannot have more runtime than the period. 7621 * Cannot have more runtime than the period.
7625 */ 7622 */
7626 if (runtime > period && runtime != RUNTIME_INF) 7623 if (runtime > period && runtime != RUNTIME_INF)
7627 return -EINVAL; 7624 return -EINVAL;
7628 7625
7629 /* 7626 /*
7630 * Ensure we don't starve existing RT tasks. 7627 * Ensure we don't starve existing RT tasks.
7631 */ 7628 */
7632 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg)) 7629 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
7633 return -EBUSY; 7630 return -EBUSY;
7634 7631
7635 total = to_ratio(period, runtime); 7632 total = to_ratio(period, runtime);
7636 7633
7637 /* 7634 /*
7638 * Nobody can have more than the global setting allows. 7635 * Nobody can have more than the global setting allows.
7639 */ 7636 */
7640 if (total > to_ratio(global_rt_period(), global_rt_runtime())) 7637 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
7641 return -EINVAL; 7638 return -EINVAL;
7642 7639
7643 /* 7640 /*
7644 * The sum of our children's runtime should not exceed our own. 7641 * The sum of our children's runtime should not exceed our own.
7645 */ 7642 */
7646 list_for_each_entry_rcu(child, &tg->children, siblings) { 7643 list_for_each_entry_rcu(child, &tg->children, siblings) {
7647 period = ktime_to_ns(child->rt_bandwidth.rt_period); 7644 period = ktime_to_ns(child->rt_bandwidth.rt_period);
7648 runtime = child->rt_bandwidth.rt_runtime; 7645 runtime = child->rt_bandwidth.rt_runtime;
7649 7646
7650 if (child == d->tg) { 7647 if (child == d->tg) {
7651 period = d->rt_period; 7648 period = d->rt_period;
7652 runtime = d->rt_runtime; 7649 runtime = d->rt_runtime;
7653 } 7650 }
7654 7651
7655 sum += to_ratio(period, runtime); 7652 sum += to_ratio(period, runtime);
7656 } 7653 }
7657 7654
7658 if (sum > total) 7655 if (sum > total)
7659 return -EINVAL; 7656 return -EINVAL;
7660 7657
7661 return 0; 7658 return 0;
7662 } 7659 }
7663 7660
7664 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime) 7661 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
7665 { 7662 {
7666 int ret; 7663 int ret;
7667 7664
7668 struct rt_schedulable_data data = { 7665 struct rt_schedulable_data data = {
7669 .tg = tg, 7666 .tg = tg,
7670 .rt_period = period, 7667 .rt_period = period,
7671 .rt_runtime = runtime, 7668 .rt_runtime = runtime,
7672 }; 7669 };
7673 7670
7674 rcu_read_lock(); 7671 rcu_read_lock();
7675 ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data); 7672 ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
7676 rcu_read_unlock(); 7673 rcu_read_unlock();
7677 7674
7678 return ret; 7675 return ret;
7679 } 7676 }
7680 7677
7681 static int tg_set_rt_bandwidth(struct task_group *tg, 7678 static int tg_set_rt_bandwidth(struct task_group *tg,
7682 u64 rt_period, u64 rt_runtime) 7679 u64 rt_period, u64 rt_runtime)
7683 { 7680 {
7684 int i, err = 0; 7681 int i, err = 0;
7685 7682
7686 mutex_lock(&rt_constraints_mutex); 7683 mutex_lock(&rt_constraints_mutex);
7687 read_lock(&tasklist_lock); 7684 read_lock(&tasklist_lock);
7688 err = __rt_schedulable(tg, rt_period, rt_runtime); 7685 err = __rt_schedulable(tg, rt_period, rt_runtime);
7689 if (err) 7686 if (err)
7690 goto unlock; 7687 goto unlock;
7691 7688
7692 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock); 7689 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
7693 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period); 7690 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
7694 tg->rt_bandwidth.rt_runtime = rt_runtime; 7691 tg->rt_bandwidth.rt_runtime = rt_runtime;
7695 7692
7696 for_each_possible_cpu(i) { 7693 for_each_possible_cpu(i) {
7697 struct rt_rq *rt_rq = tg->rt_rq[i]; 7694 struct rt_rq *rt_rq = tg->rt_rq[i];
7698 7695
7699 raw_spin_lock(&rt_rq->rt_runtime_lock); 7696 raw_spin_lock(&rt_rq->rt_runtime_lock);
7700 rt_rq->rt_runtime = rt_runtime; 7697 rt_rq->rt_runtime = rt_runtime;
7701 raw_spin_unlock(&rt_rq->rt_runtime_lock); 7698 raw_spin_unlock(&rt_rq->rt_runtime_lock);
7702 } 7699 }
7703 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock); 7700 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
7704 unlock: 7701 unlock:
7705 read_unlock(&tasklist_lock); 7702 read_unlock(&tasklist_lock);
7706 mutex_unlock(&rt_constraints_mutex); 7703 mutex_unlock(&rt_constraints_mutex);
7707 7704
7708 return err; 7705 return err;
7709 } 7706 }
7710 7707
7711 static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us) 7708 static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
7712 { 7709 {
7713 u64 rt_runtime, rt_period; 7710 u64 rt_runtime, rt_period;
7714 7711
7715 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period); 7712 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
7716 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC; 7713 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
7717 if (rt_runtime_us < 0) 7714 if (rt_runtime_us < 0)
7718 rt_runtime = RUNTIME_INF; 7715 rt_runtime = RUNTIME_INF;
7719 7716
7720 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime); 7717 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
7721 } 7718 }
7722 7719
7723 static long sched_group_rt_runtime(struct task_group *tg) 7720 static long sched_group_rt_runtime(struct task_group *tg)
7724 { 7721 {
7725 u64 rt_runtime_us; 7722 u64 rt_runtime_us;
7726 7723
7727 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF) 7724 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
7728 return -1; 7725 return -1;
7729 7726
7730 rt_runtime_us = tg->rt_bandwidth.rt_runtime; 7727 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
7731 do_div(rt_runtime_us, NSEC_PER_USEC); 7728 do_div(rt_runtime_us, NSEC_PER_USEC);
7732 return rt_runtime_us; 7729 return rt_runtime_us;
7733 } 7730 }
7734 7731
7735 static int sched_group_set_rt_period(struct task_group *tg, long rt_period_us) 7732 static int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
7736 { 7733 {
7737 u64 rt_runtime, rt_period; 7734 u64 rt_runtime, rt_period;
7738 7735
7739 rt_period = (u64)rt_period_us * NSEC_PER_USEC; 7736 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
7740 rt_runtime = tg->rt_bandwidth.rt_runtime; 7737 rt_runtime = tg->rt_bandwidth.rt_runtime;
7741 7738
7742 if (rt_period == 0) 7739 if (rt_period == 0)
7743 return -EINVAL; 7740 return -EINVAL;
7744 7741
7745 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime); 7742 return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
7746 } 7743 }
7747 7744
7748 static long sched_group_rt_period(struct task_group *tg) 7745 static long sched_group_rt_period(struct task_group *tg)
7749 { 7746 {
7750 u64 rt_period_us; 7747 u64 rt_period_us;
7751 7748
7752 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period); 7749 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
7753 do_div(rt_period_us, NSEC_PER_USEC); 7750 do_div(rt_period_us, NSEC_PER_USEC);
7754 return rt_period_us; 7751 return rt_period_us;
7755 } 7752 }
7756 #endif /* CONFIG_RT_GROUP_SCHED */ 7753 #endif /* CONFIG_RT_GROUP_SCHED */
7757 7754
7758 #ifdef CONFIG_RT_GROUP_SCHED 7755 #ifdef CONFIG_RT_GROUP_SCHED
7759 static int sched_rt_global_constraints(void) 7756 static int sched_rt_global_constraints(void)
7760 { 7757 {
7761 int ret = 0; 7758 int ret = 0;
7762 7759
7763 mutex_lock(&rt_constraints_mutex); 7760 mutex_lock(&rt_constraints_mutex);
7764 read_lock(&tasklist_lock); 7761 read_lock(&tasklist_lock);
7765 ret = __rt_schedulable(NULL, 0, 0); 7762 ret = __rt_schedulable(NULL, 0, 0);
7766 read_unlock(&tasklist_lock); 7763 read_unlock(&tasklist_lock);
7767 mutex_unlock(&rt_constraints_mutex); 7764 mutex_unlock(&rt_constraints_mutex);
7768 7765
7769 return ret; 7766 return ret;
7770 } 7767 }
7771 7768
7772 static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk) 7769 static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
7773 { 7770 {
7774 /* Don't accept realtime tasks when there is no way for them to run */ 7771 /* Don't accept realtime tasks when there is no way for them to run */
7775 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0) 7772 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
7776 return 0; 7773 return 0;
7777 7774
7778 return 1; 7775 return 1;
7779 } 7776 }
7780 7777
7781 #else /* !CONFIG_RT_GROUP_SCHED */ 7778 #else /* !CONFIG_RT_GROUP_SCHED */
7782 static int sched_rt_global_constraints(void) 7779 static int sched_rt_global_constraints(void)
7783 { 7780 {
7784 unsigned long flags; 7781 unsigned long flags;
7785 int i, ret = 0; 7782 int i, ret = 0;
7786 7783
7787 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags); 7784 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
7788 for_each_possible_cpu(i) { 7785 for_each_possible_cpu(i) {
7789 struct rt_rq *rt_rq = &cpu_rq(i)->rt; 7786 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
7790 7787
7791 raw_spin_lock(&rt_rq->rt_runtime_lock); 7788 raw_spin_lock(&rt_rq->rt_runtime_lock);
7792 rt_rq->rt_runtime = global_rt_runtime(); 7789 rt_rq->rt_runtime = global_rt_runtime();
7793 raw_spin_unlock(&rt_rq->rt_runtime_lock); 7790 raw_spin_unlock(&rt_rq->rt_runtime_lock);
7794 } 7791 }
7795 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags); 7792 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
7796 7793
7797 return ret; 7794 return ret;
7798 } 7795 }
7799 #endif /* CONFIG_RT_GROUP_SCHED */ 7796 #endif /* CONFIG_RT_GROUP_SCHED */
7800 7797
7801 static int sched_dl_global_constraints(void) 7798 static int sched_dl_global_constraints(void)
7802 { 7799 {
7803 u64 runtime = global_rt_runtime(); 7800 u64 runtime = global_rt_runtime();
7804 u64 period = global_rt_period(); 7801 u64 period = global_rt_period();
7805 u64 new_bw = to_ratio(period, runtime); 7802 u64 new_bw = to_ratio(period, runtime);
7806 struct dl_bw *dl_b; 7803 struct dl_bw *dl_b;
7807 int cpu, ret = 0; 7804 int cpu, ret = 0;
7808 unsigned long flags; 7805 unsigned long flags;
7809 7806
7810 /* 7807 /*
7811 * Here we want to check the bandwidth not being set to some 7808 * Here we want to check the bandwidth not being set to some
7812 * value smaller than the currently allocated bandwidth in 7809 * value smaller than the currently allocated bandwidth in
7813 * any of the root_domains. 7810 * any of the root_domains.
7814 * 7811 *
7815 * FIXME: Cycling on all the CPUs is overdoing, but simpler than 7812 * FIXME: Cycling on all the CPUs is overdoing, but simpler than
7816 * cycling on root_domains... Discussion on different/better 7813 * cycling on root_domains... Discussion on different/better
7817 * solutions is welcome! 7814 * solutions is welcome!
7818 */ 7815 */
7819 for_each_possible_cpu(cpu) { 7816 for_each_possible_cpu(cpu) {
7820 rcu_read_lock_sched(); 7817 rcu_read_lock_sched();
7821 dl_b = dl_bw_of(cpu); 7818 dl_b = dl_bw_of(cpu);
7822 7819
7823 raw_spin_lock_irqsave(&dl_b->lock, flags); 7820 raw_spin_lock_irqsave(&dl_b->lock, flags);
7824 if (new_bw < dl_b->total_bw) 7821 if (new_bw < dl_b->total_bw)
7825 ret = -EBUSY; 7822 ret = -EBUSY;
7826 raw_spin_unlock_irqrestore(&dl_b->lock, flags); 7823 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
7827 7824
7828 rcu_read_unlock_sched(); 7825 rcu_read_unlock_sched();
7829 7826
7830 if (ret) 7827 if (ret)
7831 break; 7828 break;
7832 } 7829 }
7833 7830
7834 return ret; 7831 return ret;
7835 } 7832 }
7836 7833
7837 static void sched_dl_do_global(void) 7834 static void sched_dl_do_global(void)
7838 { 7835 {
7839 u64 new_bw = -1; 7836 u64 new_bw = -1;
7840 struct dl_bw *dl_b; 7837 struct dl_bw *dl_b;
7841 int cpu; 7838 int cpu;
7842 unsigned long flags; 7839 unsigned long flags;
7843 7840
7844 def_dl_bandwidth.dl_period = global_rt_period(); 7841 def_dl_bandwidth.dl_period = global_rt_period();
7845 def_dl_bandwidth.dl_runtime = global_rt_runtime(); 7842 def_dl_bandwidth.dl_runtime = global_rt_runtime();
7846 7843
7847 if (global_rt_runtime() != RUNTIME_INF) 7844 if (global_rt_runtime() != RUNTIME_INF)
7848 new_bw = to_ratio(global_rt_period(), global_rt_runtime()); 7845 new_bw = to_ratio(global_rt_period(), global_rt_runtime());
7849 7846
7850 /* 7847 /*
7851 * FIXME: As above... 7848 * FIXME: As above...
7852 */ 7849 */
7853 for_each_possible_cpu(cpu) { 7850 for_each_possible_cpu(cpu) {
7854 rcu_read_lock_sched(); 7851 rcu_read_lock_sched();
7855 dl_b = dl_bw_of(cpu); 7852 dl_b = dl_bw_of(cpu);
7856 7853
7857 raw_spin_lock_irqsave(&dl_b->lock, flags); 7854 raw_spin_lock_irqsave(&dl_b->lock, flags);
7858 dl_b->bw = new_bw; 7855 dl_b->bw = new_bw;
7859 raw_spin_unlock_irqrestore(&dl_b->lock, flags); 7856 raw_spin_unlock_irqrestore(&dl_b->lock, flags);
7860 7857
7861 rcu_read_unlock_sched(); 7858 rcu_read_unlock_sched();
7862 } 7859 }
7863 } 7860 }
7864 7861
7865 static int sched_rt_global_validate(void) 7862 static int sched_rt_global_validate(void)
7866 { 7863 {
7867 if (sysctl_sched_rt_period <= 0) 7864 if (sysctl_sched_rt_period <= 0)
7868 return -EINVAL; 7865 return -EINVAL;
7869 7866
7870 if ((sysctl_sched_rt_runtime != RUNTIME_INF) && 7867 if ((sysctl_sched_rt_runtime != RUNTIME_INF) &&
7871 (sysctl_sched_rt_runtime > sysctl_sched_rt_period)) 7868 (sysctl_sched_rt_runtime > sysctl_sched_rt_period))
7872 return -EINVAL; 7869 return -EINVAL;
7873 7870
7874 return 0; 7871 return 0;
7875 } 7872 }
7876 7873
7877 static void sched_rt_do_global(void) 7874 static void sched_rt_do_global(void)
7878 { 7875 {
7879 def_rt_bandwidth.rt_runtime = global_rt_runtime(); 7876 def_rt_bandwidth.rt_runtime = global_rt_runtime();
7880 def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period()); 7877 def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period());
7881 } 7878 }
7882 7879
7883 int sched_rt_handler(struct ctl_table *table, int write, 7880 int sched_rt_handler(struct ctl_table *table, int write,
7884 void __user *buffer, size_t *lenp, 7881 void __user *buffer, size_t *lenp,
7885 loff_t *ppos) 7882 loff_t *ppos)
7886 { 7883 {
7887 int old_period, old_runtime; 7884 int old_period, old_runtime;
7888 static DEFINE_MUTEX(mutex); 7885 static DEFINE_MUTEX(mutex);
7889 int ret; 7886 int ret;
7890 7887
7891 mutex_lock(&mutex); 7888 mutex_lock(&mutex);
7892 old_period = sysctl_sched_rt_period; 7889 old_period = sysctl_sched_rt_period;
7893 old_runtime = sysctl_sched_rt_runtime; 7890 old_runtime = sysctl_sched_rt_runtime;
7894 7891
7895 ret = proc_dointvec(table, write, buffer, lenp, ppos); 7892 ret = proc_dointvec(table, write, buffer, lenp, ppos);
7896 7893
7897 if (!ret && write) { 7894 if (!ret && write) {
7898 ret = sched_rt_global_validate(); 7895 ret = sched_rt_global_validate();
7899 if (ret) 7896 if (ret)
7900 goto undo; 7897 goto undo;
7901 7898
7902 ret = sched_rt_global_constraints(); 7899 ret = sched_rt_global_constraints();
7903 if (ret) 7900 if (ret)
7904 goto undo; 7901 goto undo;
7905 7902
7906 ret = sched_dl_global_constraints(); 7903 ret = sched_dl_global_constraints();
7907 if (ret) 7904 if (ret)
7908 goto undo; 7905 goto undo;
7909 7906
7910 sched_rt_do_global(); 7907 sched_rt_do_global();
7911 sched_dl_do_global(); 7908 sched_dl_do_global();
7912 } 7909 }
7913 if (0) { 7910 if (0) {
7914 undo: 7911 undo:
7915 sysctl_sched_rt_period = old_period; 7912 sysctl_sched_rt_period = old_period;
7916 sysctl_sched_rt_runtime = old_runtime; 7913 sysctl_sched_rt_runtime = old_runtime;
7917 } 7914 }
7918 mutex_unlock(&mutex); 7915 mutex_unlock(&mutex);
7919 7916
7920 return ret; 7917 return ret;
7921 } 7918 }
7922 7919
7923 int sched_rr_handler(struct ctl_table *table, int write, 7920 int sched_rr_handler(struct ctl_table *table, int write,
7924 void __user *buffer, size_t *lenp, 7921 void __user *buffer, size_t *lenp,
7925 loff_t *ppos) 7922 loff_t *ppos)
7926 { 7923 {
7927 int ret; 7924 int ret;
7928 static DEFINE_MUTEX(mutex); 7925 static DEFINE_MUTEX(mutex);
7929 7926
7930 mutex_lock(&mutex); 7927 mutex_lock(&mutex);
7931 ret = proc_dointvec(table, write, buffer, lenp, ppos); 7928 ret = proc_dointvec(table, write, buffer, lenp, ppos);
7932 /* make sure that internally we keep jiffies */ 7929 /* make sure that internally we keep jiffies */
7933 /* also, writing zero resets timeslice to default */ 7930 /* also, writing zero resets timeslice to default */
7934 if (!ret && write) { 7931 if (!ret && write) {
7935 sched_rr_timeslice = sched_rr_timeslice <= 0 ? 7932 sched_rr_timeslice = sched_rr_timeslice <= 0 ?
7936 RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice); 7933 RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
7937 } 7934 }
7938 mutex_unlock(&mutex); 7935 mutex_unlock(&mutex);
7939 return ret; 7936 return ret;
7940 } 7937 }
7941 7938
7942 #ifdef CONFIG_CGROUP_SCHED 7939 #ifdef CONFIG_CGROUP_SCHED
7943 7940
7944 static inline struct task_group *css_tg(struct cgroup_subsys_state *css) 7941 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
7945 { 7942 {
7946 return css ? container_of(css, struct task_group, css) : NULL; 7943 return css ? container_of(css, struct task_group, css) : NULL;
7947 } 7944 }
7948 7945
7949 static struct cgroup_subsys_state * 7946 static struct cgroup_subsys_state *
7950 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) 7947 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
7951 { 7948 {
7952 struct task_group *parent = css_tg(parent_css); 7949 struct task_group *parent = css_tg(parent_css);
7953 struct task_group *tg; 7950 struct task_group *tg;
7954 7951
7955 if (!parent) { 7952 if (!parent) {
7956 /* This is early initialization for the top cgroup */ 7953 /* This is early initialization for the top cgroup */
7957 return &root_task_group.css; 7954 return &root_task_group.css;
7958 } 7955 }
7959 7956
7960 tg = sched_create_group(parent); 7957 tg = sched_create_group(parent);
7961 if (IS_ERR(tg)) 7958 if (IS_ERR(tg))
7962 return ERR_PTR(-ENOMEM); 7959 return ERR_PTR(-ENOMEM);
7963 7960
7964 return &tg->css; 7961 return &tg->css;
7965 } 7962 }
7966 7963
7967 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css) 7964 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
7968 { 7965 {
7969 struct task_group *tg = css_tg(css); 7966 struct task_group *tg = css_tg(css);
7970 struct task_group *parent = css_tg(css->parent); 7967 struct task_group *parent = css_tg(css->parent);
7971 7968
7972 if (parent) 7969 if (parent)
7973 sched_online_group(tg, parent); 7970 sched_online_group(tg, parent);
7974 return 0; 7971 return 0;
7975 } 7972 }
7976 7973
7977 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css) 7974 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
7978 { 7975 {
7979 struct task_group *tg = css_tg(css); 7976 struct task_group *tg = css_tg(css);
7980 7977
7981 sched_destroy_group(tg); 7978 sched_destroy_group(tg);
7982 } 7979 }
7983 7980
7984 static void cpu_cgroup_css_offline(struct cgroup_subsys_state *css) 7981 static void cpu_cgroup_css_offline(struct cgroup_subsys_state *css)
7985 { 7982 {
7986 struct task_group *tg = css_tg(css); 7983 struct task_group *tg = css_tg(css);
7987 7984
7988 sched_offline_group(tg); 7985 sched_offline_group(tg);
7989 } 7986 }
7990 7987
7991 static void cpu_cgroup_fork(struct task_struct *task) 7988 static void cpu_cgroup_fork(struct task_struct *task)
7992 { 7989 {
7993 sched_move_task(task); 7990 sched_move_task(task);
7994 } 7991 }
7995 7992
7996 static int cpu_cgroup_can_attach(struct cgroup_subsys_state *css, 7993 static int cpu_cgroup_can_attach(struct cgroup_subsys_state *css,
7997 struct cgroup_taskset *tset) 7994 struct cgroup_taskset *tset)
7998 { 7995 {
7999 struct task_struct *task; 7996 struct task_struct *task;
8000 7997
8001 cgroup_taskset_for_each(task, tset) { 7998 cgroup_taskset_for_each(task, tset) {
8002 #ifdef CONFIG_RT_GROUP_SCHED 7999 #ifdef CONFIG_RT_GROUP_SCHED
8003 if (!sched_rt_can_attach(css_tg(css), task)) 8000 if (!sched_rt_can_attach(css_tg(css), task))
8004 return -EINVAL; 8001 return -EINVAL;
8005 #else 8002 #else
8006 /* We don't support RT-tasks being in separate groups */ 8003 /* We don't support RT-tasks being in separate groups */
8007 if (task->sched_class != &fair_sched_class) 8004 if (task->sched_class != &fair_sched_class)
8008 return -EINVAL; 8005 return -EINVAL;
8009 #endif 8006 #endif
8010 } 8007 }
8011 return 0; 8008 return 0;
8012 } 8009 }
8013 8010
8014 static void cpu_cgroup_attach(struct cgroup_subsys_state *css, 8011 static void cpu_cgroup_attach(struct cgroup_subsys_state *css,
8015 struct cgroup_taskset *tset) 8012 struct cgroup_taskset *tset)
8016 { 8013 {
8017 struct task_struct *task; 8014 struct task_struct *task;
8018 8015
8019 cgroup_taskset_for_each(task, tset) 8016 cgroup_taskset_for_each(task, tset)
8020 sched_move_task(task); 8017 sched_move_task(task);
8021 } 8018 }
8022 8019
8023 static void cpu_cgroup_exit(struct cgroup_subsys_state *css, 8020 static void cpu_cgroup_exit(struct cgroup_subsys_state *css,
8024 struct cgroup_subsys_state *old_css, 8021 struct cgroup_subsys_state *old_css,
8025 struct task_struct *task) 8022 struct task_struct *task)
8026 { 8023 {
8027 /* 8024 /*
8028 * cgroup_exit() is called in the copy_process() failure path. 8025 * cgroup_exit() is called in the copy_process() failure path.
8029 * Ignore this case since the task hasn't ran yet, this avoids 8026 * Ignore this case since the task hasn't ran yet, this avoids
8030 * trying to poke a half freed task state from generic code. 8027 * trying to poke a half freed task state from generic code.
8031 */ 8028 */
8032 if (!(task->flags & PF_EXITING)) 8029 if (!(task->flags & PF_EXITING))
8033 return; 8030 return;
8034 8031
8035 sched_move_task(task); 8032 sched_move_task(task);
8036 } 8033 }
8037 8034
8038 #ifdef CONFIG_FAIR_GROUP_SCHED 8035 #ifdef CONFIG_FAIR_GROUP_SCHED
8039 static int cpu_shares_write_u64(struct cgroup_subsys_state *css, 8036 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
8040 struct cftype *cftype, u64 shareval) 8037 struct cftype *cftype, u64 shareval)
8041 { 8038 {
8042 return sched_group_set_shares(css_tg(css), scale_load(shareval)); 8039 return sched_group_set_shares(css_tg(css), scale_load(shareval));
8043 } 8040 }
8044 8041
8045 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css, 8042 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
8046 struct cftype *cft) 8043 struct cftype *cft)
8047 { 8044 {
8048 struct task_group *tg = css_tg(css); 8045 struct task_group *tg = css_tg(css);
8049 8046
8050 return (u64) scale_load_down(tg->shares); 8047 return (u64) scale_load_down(tg->shares);
8051 } 8048 }
8052 8049
8053 #ifdef CONFIG_CFS_BANDWIDTH 8050 #ifdef CONFIG_CFS_BANDWIDTH
8054 static DEFINE_MUTEX(cfs_constraints_mutex); 8051 static DEFINE_MUTEX(cfs_constraints_mutex);
8055 8052
8056 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */ 8053 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
8057 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */ 8054 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
8058 8055
8059 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime); 8056 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
8060 8057
8061 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota) 8058 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
8062 { 8059 {
8063 int i, ret = 0, runtime_enabled, runtime_was_enabled; 8060 int i, ret = 0, runtime_enabled, runtime_was_enabled;
8064 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 8061 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8065 8062
8066 if (tg == &root_task_group) 8063 if (tg == &root_task_group)
8067 return -EINVAL; 8064 return -EINVAL;
8068 8065
8069 /* 8066 /*
8070 * Ensure we have at some amount of bandwidth every period. This is 8067 * Ensure we have at some amount of bandwidth every period. This is
8071 * to prevent reaching a state of large arrears when throttled via 8068 * to prevent reaching a state of large arrears when throttled via
8072 * entity_tick() resulting in prolonged exit starvation. 8069 * entity_tick() resulting in prolonged exit starvation.
8073 */ 8070 */
8074 if (quota < min_cfs_quota_period || period < min_cfs_quota_period) 8071 if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
8075 return -EINVAL; 8072 return -EINVAL;
8076 8073
8077 /* 8074 /*
8078 * Likewise, bound things on the otherside by preventing insane quota 8075 * Likewise, bound things on the otherside by preventing insane quota
8079 * periods. This also allows us to normalize in computing quota 8076 * periods. This also allows us to normalize in computing quota
8080 * feasibility. 8077 * feasibility.
8081 */ 8078 */
8082 if (period > max_cfs_quota_period) 8079 if (period > max_cfs_quota_period)
8083 return -EINVAL; 8080 return -EINVAL;
8084 8081
8085 /* 8082 /*
8086 * Prevent race between setting of cfs_rq->runtime_enabled and 8083 * Prevent race between setting of cfs_rq->runtime_enabled and
8087 * unthrottle_offline_cfs_rqs(). 8084 * unthrottle_offline_cfs_rqs().
8088 */ 8085 */
8089 get_online_cpus(); 8086 get_online_cpus();
8090 mutex_lock(&cfs_constraints_mutex); 8087 mutex_lock(&cfs_constraints_mutex);
8091 ret = __cfs_schedulable(tg, period, quota); 8088 ret = __cfs_schedulable(tg, period, quota);
8092 if (ret) 8089 if (ret)
8093 goto out_unlock; 8090 goto out_unlock;
8094 8091
8095 runtime_enabled = quota != RUNTIME_INF; 8092 runtime_enabled = quota != RUNTIME_INF;
8096 runtime_was_enabled = cfs_b->quota != RUNTIME_INF; 8093 runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
8097 /* 8094 /*
8098 * If we need to toggle cfs_bandwidth_used, off->on must occur 8095 * If we need to toggle cfs_bandwidth_used, off->on must occur
8099 * before making related changes, and on->off must occur afterwards 8096 * before making related changes, and on->off must occur afterwards
8100 */ 8097 */
8101 if (runtime_enabled && !runtime_was_enabled) 8098 if (runtime_enabled && !runtime_was_enabled)
8102 cfs_bandwidth_usage_inc(); 8099 cfs_bandwidth_usage_inc();
8103 raw_spin_lock_irq(&cfs_b->lock); 8100 raw_spin_lock_irq(&cfs_b->lock);
8104 cfs_b->period = ns_to_ktime(period); 8101 cfs_b->period = ns_to_ktime(period);
8105 cfs_b->quota = quota; 8102 cfs_b->quota = quota;
8106 8103
8107 __refill_cfs_bandwidth_runtime(cfs_b); 8104 __refill_cfs_bandwidth_runtime(cfs_b);
8108 /* restart the period timer (if active) to handle new period expiry */ 8105 /* restart the period timer (if active) to handle new period expiry */
8109 if (runtime_enabled && cfs_b->timer_active) { 8106 if (runtime_enabled && cfs_b->timer_active) {
8110 /* force a reprogram */ 8107 /* force a reprogram */
8111 __start_cfs_bandwidth(cfs_b, true); 8108 __start_cfs_bandwidth(cfs_b, true);
8112 } 8109 }
8113 raw_spin_unlock_irq(&cfs_b->lock); 8110 raw_spin_unlock_irq(&cfs_b->lock);
8114 8111
8115 for_each_online_cpu(i) { 8112 for_each_online_cpu(i) {
8116 struct cfs_rq *cfs_rq = tg->cfs_rq[i]; 8113 struct cfs_rq *cfs_rq = tg->cfs_rq[i];
8117 struct rq *rq = cfs_rq->rq; 8114 struct rq *rq = cfs_rq->rq;
8118 8115
8119 raw_spin_lock_irq(&rq->lock); 8116 raw_spin_lock_irq(&rq->lock);
8120 cfs_rq->runtime_enabled = runtime_enabled; 8117 cfs_rq->runtime_enabled = runtime_enabled;
8121 cfs_rq->runtime_remaining = 0; 8118 cfs_rq->runtime_remaining = 0;
8122 8119
8123 if (cfs_rq->throttled) 8120 if (cfs_rq->throttled)
8124 unthrottle_cfs_rq(cfs_rq); 8121 unthrottle_cfs_rq(cfs_rq);
8125 raw_spin_unlock_irq(&rq->lock); 8122 raw_spin_unlock_irq(&rq->lock);
8126 } 8123 }
8127 if (runtime_was_enabled && !runtime_enabled) 8124 if (runtime_was_enabled && !runtime_enabled)
8128 cfs_bandwidth_usage_dec(); 8125 cfs_bandwidth_usage_dec();
8129 out_unlock: 8126 out_unlock:
8130 mutex_unlock(&cfs_constraints_mutex); 8127 mutex_unlock(&cfs_constraints_mutex);
8131 put_online_cpus(); 8128 put_online_cpus();
8132 8129
8133 return ret; 8130 return ret;
8134 } 8131 }
8135 8132
8136 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us) 8133 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
8137 { 8134 {
8138 u64 quota, period; 8135 u64 quota, period;
8139 8136
8140 period = ktime_to_ns(tg->cfs_bandwidth.period); 8137 period = ktime_to_ns(tg->cfs_bandwidth.period);
8141 if (cfs_quota_us < 0) 8138 if (cfs_quota_us < 0)
8142 quota = RUNTIME_INF; 8139 quota = RUNTIME_INF;
8143 else 8140 else
8144 quota = (u64)cfs_quota_us * NSEC_PER_USEC; 8141 quota = (u64)cfs_quota_us * NSEC_PER_USEC;
8145 8142
8146 return tg_set_cfs_bandwidth(tg, period, quota); 8143 return tg_set_cfs_bandwidth(tg, period, quota);
8147 } 8144 }
8148 8145
8149 long tg_get_cfs_quota(struct task_group *tg) 8146 long tg_get_cfs_quota(struct task_group *tg)
8150 { 8147 {
8151 u64 quota_us; 8148 u64 quota_us;
8152 8149
8153 if (tg->cfs_bandwidth.quota == RUNTIME_INF) 8150 if (tg->cfs_bandwidth.quota == RUNTIME_INF)
8154 return -1; 8151 return -1;
8155 8152
8156 quota_us = tg->cfs_bandwidth.quota; 8153 quota_us = tg->cfs_bandwidth.quota;
8157 do_div(quota_us, NSEC_PER_USEC); 8154 do_div(quota_us, NSEC_PER_USEC);
8158 8155
8159 return quota_us; 8156 return quota_us;
8160 } 8157 }
8161 8158
8162 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us) 8159 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
8163 { 8160 {
8164 u64 quota, period; 8161 u64 quota, period;
8165 8162
8166 period = (u64)cfs_period_us * NSEC_PER_USEC; 8163 period = (u64)cfs_period_us * NSEC_PER_USEC;
8167 quota = tg->cfs_bandwidth.quota; 8164 quota = tg->cfs_bandwidth.quota;
8168 8165
8169 return tg_set_cfs_bandwidth(tg, period, quota); 8166 return tg_set_cfs_bandwidth(tg, period, quota);
8170 } 8167 }
8171 8168
8172 long tg_get_cfs_period(struct task_group *tg) 8169 long tg_get_cfs_period(struct task_group *tg)
8173 { 8170 {
8174 u64 cfs_period_us; 8171 u64 cfs_period_us;
8175 8172
8176 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period); 8173 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
8177 do_div(cfs_period_us, NSEC_PER_USEC); 8174 do_div(cfs_period_us, NSEC_PER_USEC);
8178 8175
8179 return cfs_period_us; 8176 return cfs_period_us;
8180 } 8177 }
8181 8178
8182 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css, 8179 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
8183 struct cftype *cft) 8180 struct cftype *cft)
8184 { 8181 {
8185 return tg_get_cfs_quota(css_tg(css)); 8182 return tg_get_cfs_quota(css_tg(css));
8186 } 8183 }
8187 8184
8188 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css, 8185 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
8189 struct cftype *cftype, s64 cfs_quota_us) 8186 struct cftype *cftype, s64 cfs_quota_us)
8190 { 8187 {
8191 return tg_set_cfs_quota(css_tg(css), cfs_quota_us); 8188 return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
8192 } 8189 }
8193 8190
8194 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css, 8191 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
8195 struct cftype *cft) 8192 struct cftype *cft)
8196 { 8193 {
8197 return tg_get_cfs_period(css_tg(css)); 8194 return tg_get_cfs_period(css_tg(css));
8198 } 8195 }
8199 8196
8200 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css, 8197 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
8201 struct cftype *cftype, u64 cfs_period_us) 8198 struct cftype *cftype, u64 cfs_period_us)
8202 { 8199 {
8203 return tg_set_cfs_period(css_tg(css), cfs_period_us); 8200 return tg_set_cfs_period(css_tg(css), cfs_period_us);
8204 } 8201 }
8205 8202
8206 struct cfs_schedulable_data { 8203 struct cfs_schedulable_data {
8207 struct task_group *tg; 8204 struct task_group *tg;
8208 u64 period, quota; 8205 u64 period, quota;
8209 }; 8206 };
8210 8207
8211 /* 8208 /*
8212 * normalize group quota/period to be quota/max_period 8209 * normalize group quota/period to be quota/max_period
8213 * note: units are usecs 8210 * note: units are usecs
8214 */ 8211 */
8215 static u64 normalize_cfs_quota(struct task_group *tg, 8212 static u64 normalize_cfs_quota(struct task_group *tg,
8216 struct cfs_schedulable_data *d) 8213 struct cfs_schedulable_data *d)
8217 { 8214 {
8218 u64 quota, period; 8215 u64 quota, period;
8219 8216
8220 if (tg == d->tg) { 8217 if (tg == d->tg) {
8221 period = d->period; 8218 period = d->period;
8222 quota = d->quota; 8219 quota = d->quota;
8223 } else { 8220 } else {
8224 period = tg_get_cfs_period(tg); 8221 period = tg_get_cfs_period(tg);
8225 quota = tg_get_cfs_quota(tg); 8222 quota = tg_get_cfs_quota(tg);
8226 } 8223 }
8227 8224
8228 /* note: these should typically be equivalent */ 8225 /* note: these should typically be equivalent */
8229 if (quota == RUNTIME_INF || quota == -1) 8226 if (quota == RUNTIME_INF || quota == -1)
8230 return RUNTIME_INF; 8227 return RUNTIME_INF;
8231 8228
8232 return to_ratio(period, quota); 8229 return to_ratio(period, quota);
8233 } 8230 }
8234 8231
8235 static int tg_cfs_schedulable_down(struct task_group *tg, void *data) 8232 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
8236 { 8233 {
8237 struct cfs_schedulable_data *d = data; 8234 struct cfs_schedulable_data *d = data;
8238 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 8235 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8239 s64 quota = 0, parent_quota = -1; 8236 s64 quota = 0, parent_quota = -1;
8240 8237
8241 if (!tg->parent) { 8238 if (!tg->parent) {
8242 quota = RUNTIME_INF; 8239 quota = RUNTIME_INF;
8243 } else { 8240 } else {
8244 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth; 8241 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
8245 8242
8246 quota = normalize_cfs_quota(tg, d); 8243 quota = normalize_cfs_quota(tg, d);
8247 parent_quota = parent_b->hierarchical_quota; 8244 parent_quota = parent_b->hierarchical_quota;
8248 8245
8249 /* 8246 /*
8250 * ensure max(child_quota) <= parent_quota, inherit when no 8247 * ensure max(child_quota) <= parent_quota, inherit when no
8251 * limit is set 8248 * limit is set
8252 */ 8249 */
8253 if (quota == RUNTIME_INF) 8250 if (quota == RUNTIME_INF)
8254 quota = parent_quota; 8251 quota = parent_quota;
8255 else if (parent_quota != RUNTIME_INF && quota > parent_quota) 8252 else if (parent_quota != RUNTIME_INF && quota > parent_quota)
8256 return -EINVAL; 8253 return -EINVAL;
8257 } 8254 }
8258 cfs_b->hierarchical_quota = quota; 8255 cfs_b->hierarchical_quota = quota;
8259 8256
8260 return 0; 8257 return 0;
8261 } 8258 }
8262 8259
8263 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota) 8260 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
8264 { 8261 {
8265 int ret; 8262 int ret;
8266 struct cfs_schedulable_data data = { 8263 struct cfs_schedulable_data data = {
8267 .tg = tg, 8264 .tg = tg,
8268 .period = period, 8265 .period = period,
8269 .quota = quota, 8266 .quota = quota,
8270 }; 8267 };
8271 8268
8272 if (quota != RUNTIME_INF) { 8269 if (quota != RUNTIME_INF) {
8273 do_div(data.period, NSEC_PER_USEC); 8270 do_div(data.period, NSEC_PER_USEC);
8274 do_div(data.quota, NSEC_PER_USEC); 8271 do_div(data.quota, NSEC_PER_USEC);
8275 } 8272 }
8276 8273
8277 rcu_read_lock(); 8274 rcu_read_lock();
8278 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data); 8275 ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
8279 rcu_read_unlock(); 8276 rcu_read_unlock();
8280 8277
8281 return ret; 8278 return ret;
8282 } 8279 }
8283 8280
8284 static int cpu_stats_show(struct seq_file *sf, void *v) 8281 static int cpu_stats_show(struct seq_file *sf, void *v)
8285 { 8282 {
8286 struct task_group *tg = css_tg(seq_css(sf)); 8283 struct task_group *tg = css_tg(seq_css(sf));
8287 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 8284 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8288 8285
8289 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods); 8286 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
8290 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled); 8287 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
8291 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time); 8288 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
8292 8289
8293 return 0; 8290 return 0;
8294 } 8291 }
8295 #endif /* CONFIG_CFS_BANDWIDTH */ 8292 #endif /* CONFIG_CFS_BANDWIDTH */
8296 #endif /* CONFIG_FAIR_GROUP_SCHED */ 8293 #endif /* CONFIG_FAIR_GROUP_SCHED */
8297 8294
8298 #ifdef CONFIG_RT_GROUP_SCHED 8295 #ifdef CONFIG_RT_GROUP_SCHED
8299 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css, 8296 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
8300 struct cftype *cft, s64 val) 8297 struct cftype *cft, s64 val)
8301 { 8298 {
8302 return sched_group_set_rt_runtime(css_tg(css), val); 8299 return sched_group_set_rt_runtime(css_tg(css), val);
8303 } 8300 }
8304 8301
8305 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css, 8302 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
8306 struct cftype *cft) 8303 struct cftype *cft)
8307 { 8304 {
8308 return sched_group_rt_runtime(css_tg(css)); 8305 return sched_group_rt_runtime(css_tg(css));
8309 } 8306 }
8310 8307
8311 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css, 8308 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
8312 struct cftype *cftype, u64 rt_period_us) 8309 struct cftype *cftype, u64 rt_period_us)
8313 { 8310 {
8314 return sched_group_set_rt_period(css_tg(css), rt_period_us); 8311 return sched_group_set_rt_period(css_tg(css), rt_period_us);
8315 } 8312 }
8316 8313
8317 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css, 8314 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
8318 struct cftype *cft) 8315 struct cftype *cft)
8319 { 8316 {
8320 return sched_group_rt_period(css_tg(css)); 8317 return sched_group_rt_period(css_tg(css));
8321 } 8318 }
8322 #endif /* CONFIG_RT_GROUP_SCHED */ 8319 #endif /* CONFIG_RT_GROUP_SCHED */
8323 8320
8324 static struct cftype cpu_files[] = { 8321 static struct cftype cpu_files[] = {
8325 #ifdef CONFIG_FAIR_GROUP_SCHED 8322 #ifdef CONFIG_FAIR_GROUP_SCHED
8326 { 8323 {
8327 .name = "shares", 8324 .name = "shares",
8328 .read_u64 = cpu_shares_read_u64, 8325 .read_u64 = cpu_shares_read_u64,
8329 .write_u64 = cpu_shares_write_u64, 8326 .write_u64 = cpu_shares_write_u64,
8330 }, 8327 },
8331 #endif 8328 #endif
8332 #ifdef CONFIG_CFS_BANDWIDTH 8329 #ifdef CONFIG_CFS_BANDWIDTH
8333 { 8330 {
8334 .name = "cfs_quota_us", 8331 .name = "cfs_quota_us",
8335 .read_s64 = cpu_cfs_quota_read_s64, 8332 .read_s64 = cpu_cfs_quota_read_s64,
8336 .write_s64 = cpu_cfs_quota_write_s64, 8333 .write_s64 = cpu_cfs_quota_write_s64,
8337 }, 8334 },
8338 { 8335 {
8339 .name = "cfs_period_us", 8336 .name = "cfs_period_us",
8340 .read_u64 = cpu_cfs_period_read_u64, 8337 .read_u64 = cpu_cfs_period_read_u64,
8341 .write_u64 = cpu_cfs_period_write_u64, 8338 .write_u64 = cpu_cfs_period_write_u64,
8342 }, 8339 },
8343 { 8340 {
8344 .name = "stat", 8341 .name = "stat",
8345 .seq_show = cpu_stats_show, 8342 .seq_show = cpu_stats_show,
8346 }, 8343 },
8347 #endif 8344 #endif
8348 #ifdef CONFIG_RT_GROUP_SCHED 8345 #ifdef CONFIG_RT_GROUP_SCHED
8349 { 8346 {
8350 .name = "rt_runtime_us", 8347 .name = "rt_runtime_us",
8351 .read_s64 = cpu_rt_runtime_read, 8348 .read_s64 = cpu_rt_runtime_read,
8352 .write_s64 = cpu_rt_runtime_write, 8349 .write_s64 = cpu_rt_runtime_write,
8353 }, 8350 },
8354 { 8351 {
8355 .name = "rt_period_us", 8352 .name = "rt_period_us",
8356 .read_u64 = cpu_rt_period_read_uint, 8353 .read_u64 = cpu_rt_period_read_uint,
8357 .write_u64 = cpu_rt_period_write_uint, 8354 .write_u64 = cpu_rt_period_write_uint,
8358 }, 8355 },
8359 #endif 8356 #endif
8360 { } /* terminate */ 8357 { } /* terminate */
8361 }; 8358 };
8362 8359
8363 struct cgroup_subsys cpu_cgrp_subsys = { 8360 struct cgroup_subsys cpu_cgrp_subsys = {
8364 .css_alloc = cpu_cgroup_css_alloc, 8361 .css_alloc = cpu_cgroup_css_alloc,
8365 .css_free = cpu_cgroup_css_free, 8362 .css_free = cpu_cgroup_css_free,
8366 .css_online = cpu_cgroup_css_online, 8363 .css_online = cpu_cgroup_css_online,
8367 .css_offline = cpu_cgroup_css_offline, 8364 .css_offline = cpu_cgroup_css_offline,
8368 .fork = cpu_cgroup_fork, 8365 .fork = cpu_cgroup_fork,
8369 .can_attach = cpu_cgroup_can_attach, 8366 .can_attach = cpu_cgroup_can_attach,
8370 .attach = cpu_cgroup_attach, 8367 .attach = cpu_cgroup_attach,
8371 .exit = cpu_cgroup_exit, 8368 .exit = cpu_cgroup_exit,
8372 .legacy_cftypes = cpu_files, 8369 .legacy_cftypes = cpu_files,
8373 .early_init = 1, 8370 .early_init = 1,
8374 }; 8371 };
8375 8372
8376 #endif /* CONFIG_CGROUP_SCHED */ 8373 #endif /* CONFIG_CGROUP_SCHED */
8377 8374
8378 void dump_cpu_task(int cpu) 8375 void dump_cpu_task(int cpu)
8379 { 8376 {
8380 pr_info("Task dump for CPU %d:\n", cpu); 8377 pr_info("Task dump for CPU %d:\n", cpu);
8381 sched_show_task(cpu_curr(cpu)); 8378 sched_show_task(cpu_curr(cpu));
kernel/sched/deadline.c
1 /* 1 /*
2 * Deadline Scheduling Class (SCHED_DEADLINE) 2 * Deadline Scheduling Class (SCHED_DEADLINE)
3 * 3 *
4 * Earliest Deadline First (EDF) + Constant Bandwidth Server (CBS). 4 * Earliest Deadline First (EDF) + Constant Bandwidth Server (CBS).
5 * 5 *
6 * Tasks that periodically executes their instances for less than their 6 * Tasks that periodically executes their instances for less than their
7 * runtime won't miss any of their deadlines. 7 * runtime won't miss any of their deadlines.
8 * Tasks that are not periodic or sporadic or that tries to execute more 8 * Tasks that are not periodic or sporadic or that tries to execute more
9 * than their reserved bandwidth will be slowed down (and may potentially 9 * than their reserved bandwidth will be slowed down (and may potentially
10 * miss some of their deadlines), and won't affect any other task. 10 * miss some of their deadlines), and won't affect any other task.
11 * 11 *
12 * Copyright (C) 2012 Dario Faggioli <raistlin@linux.it>, 12 * Copyright (C) 2012 Dario Faggioli <raistlin@linux.it>,
13 * Juri Lelli <juri.lelli@gmail.com>, 13 * Juri Lelli <juri.lelli@gmail.com>,
14 * Michael Trimarchi <michael@amarulasolutions.com>, 14 * Michael Trimarchi <michael@amarulasolutions.com>,
15 * Fabio Checconi <fchecconi@gmail.com> 15 * Fabio Checconi <fchecconi@gmail.com>
16 */ 16 */
17 #include "sched.h" 17 #include "sched.h"
18 18
19 #include <linux/slab.h> 19 #include <linux/slab.h>
20 20
21 struct dl_bandwidth def_dl_bandwidth; 21 struct dl_bandwidth def_dl_bandwidth;
22 22
23 static inline struct task_struct *dl_task_of(struct sched_dl_entity *dl_se) 23 static inline struct task_struct *dl_task_of(struct sched_dl_entity *dl_se)
24 { 24 {
25 return container_of(dl_se, struct task_struct, dl); 25 return container_of(dl_se, struct task_struct, dl);
26 } 26 }
27 27
28 static inline struct rq *rq_of_dl_rq(struct dl_rq *dl_rq) 28 static inline struct rq *rq_of_dl_rq(struct dl_rq *dl_rq)
29 { 29 {
30 return container_of(dl_rq, struct rq, dl); 30 return container_of(dl_rq, struct rq, dl);
31 } 31 }
32 32
33 static inline struct dl_rq *dl_rq_of_se(struct sched_dl_entity *dl_se) 33 static inline struct dl_rq *dl_rq_of_se(struct sched_dl_entity *dl_se)
34 { 34 {
35 struct task_struct *p = dl_task_of(dl_se); 35 struct task_struct *p = dl_task_of(dl_se);
36 struct rq *rq = task_rq(p); 36 struct rq *rq = task_rq(p);
37 37
38 return &rq->dl; 38 return &rq->dl;
39 } 39 }
40 40
41 static inline int on_dl_rq(struct sched_dl_entity *dl_se) 41 static inline int on_dl_rq(struct sched_dl_entity *dl_se)
42 { 42 {
43 return !RB_EMPTY_NODE(&dl_se->rb_node); 43 return !RB_EMPTY_NODE(&dl_se->rb_node);
44 } 44 }
45 45
46 static inline int is_leftmost(struct task_struct *p, struct dl_rq *dl_rq) 46 static inline int is_leftmost(struct task_struct *p, struct dl_rq *dl_rq)
47 { 47 {
48 struct sched_dl_entity *dl_se = &p->dl; 48 struct sched_dl_entity *dl_se = &p->dl;
49 49
50 return dl_rq->rb_leftmost == &dl_se->rb_node; 50 return dl_rq->rb_leftmost == &dl_se->rb_node;
51 } 51 }
52 52
53 void init_dl_bandwidth(struct dl_bandwidth *dl_b, u64 period, u64 runtime) 53 void init_dl_bandwidth(struct dl_bandwidth *dl_b, u64 period, u64 runtime)
54 { 54 {
55 raw_spin_lock_init(&dl_b->dl_runtime_lock); 55 raw_spin_lock_init(&dl_b->dl_runtime_lock);
56 dl_b->dl_period = period; 56 dl_b->dl_period = period;
57 dl_b->dl_runtime = runtime; 57 dl_b->dl_runtime = runtime;
58 } 58 }
59 59
60 void init_dl_bw(struct dl_bw *dl_b) 60 void init_dl_bw(struct dl_bw *dl_b)
61 { 61 {
62 raw_spin_lock_init(&dl_b->lock); 62 raw_spin_lock_init(&dl_b->lock);
63 raw_spin_lock(&def_dl_bandwidth.dl_runtime_lock); 63 raw_spin_lock(&def_dl_bandwidth.dl_runtime_lock);
64 if (global_rt_runtime() == RUNTIME_INF) 64 if (global_rt_runtime() == RUNTIME_INF)
65 dl_b->bw = -1; 65 dl_b->bw = -1;
66 else 66 else
67 dl_b->bw = to_ratio(global_rt_period(), global_rt_runtime()); 67 dl_b->bw = to_ratio(global_rt_period(), global_rt_runtime());
68 raw_spin_unlock(&def_dl_bandwidth.dl_runtime_lock); 68 raw_spin_unlock(&def_dl_bandwidth.dl_runtime_lock);
69 dl_b->total_bw = 0; 69 dl_b->total_bw = 0;
70 } 70 }
71 71
72 void init_dl_rq(struct dl_rq *dl_rq, struct rq *rq) 72 void init_dl_rq(struct dl_rq *dl_rq, struct rq *rq)
73 { 73 {
74 dl_rq->rb_root = RB_ROOT; 74 dl_rq->rb_root = RB_ROOT;
75 75
76 #ifdef CONFIG_SMP 76 #ifdef CONFIG_SMP
77 /* zero means no -deadline tasks */ 77 /* zero means no -deadline tasks */
78 dl_rq->earliest_dl.curr = dl_rq->earliest_dl.next = 0; 78 dl_rq->earliest_dl.curr = dl_rq->earliest_dl.next = 0;
79 79
80 dl_rq->dl_nr_migratory = 0; 80 dl_rq->dl_nr_migratory = 0;
81 dl_rq->overloaded = 0; 81 dl_rq->overloaded = 0;
82 dl_rq->pushable_dl_tasks_root = RB_ROOT; 82 dl_rq->pushable_dl_tasks_root = RB_ROOT;
83 #else 83 #else
84 init_dl_bw(&dl_rq->dl_bw); 84 init_dl_bw(&dl_rq->dl_bw);
85 #endif 85 #endif
86 } 86 }
87 87
88 #ifdef CONFIG_SMP 88 #ifdef CONFIG_SMP
89 89
90 static inline int dl_overloaded(struct rq *rq) 90 static inline int dl_overloaded(struct rq *rq)
91 { 91 {
92 return atomic_read(&rq->rd->dlo_count); 92 return atomic_read(&rq->rd->dlo_count);
93 } 93 }
94 94
95 static inline void dl_set_overload(struct rq *rq) 95 static inline void dl_set_overload(struct rq *rq)
96 { 96 {
97 if (!rq->online) 97 if (!rq->online)
98 return; 98 return;
99 99
100 cpumask_set_cpu(rq->cpu, rq->rd->dlo_mask); 100 cpumask_set_cpu(rq->cpu, rq->rd->dlo_mask);
101 /* 101 /*
102 * Must be visible before the overload count is 102 * Must be visible before the overload count is
103 * set (as in sched_rt.c). 103 * set (as in sched_rt.c).
104 * 104 *
105 * Matched by the barrier in pull_dl_task(). 105 * Matched by the barrier in pull_dl_task().
106 */ 106 */
107 smp_wmb(); 107 smp_wmb();
108 atomic_inc(&rq->rd->dlo_count); 108 atomic_inc(&rq->rd->dlo_count);
109 } 109 }
110 110
111 static inline void dl_clear_overload(struct rq *rq) 111 static inline void dl_clear_overload(struct rq *rq)
112 { 112 {
113 if (!rq->online) 113 if (!rq->online)
114 return; 114 return;
115 115
116 atomic_dec(&rq->rd->dlo_count); 116 atomic_dec(&rq->rd->dlo_count);
117 cpumask_clear_cpu(rq->cpu, rq->rd->dlo_mask); 117 cpumask_clear_cpu(rq->cpu, rq->rd->dlo_mask);
118 } 118 }
119 119
120 static void update_dl_migration(struct dl_rq *dl_rq) 120 static void update_dl_migration(struct dl_rq *dl_rq)
121 { 121 {
122 if (dl_rq->dl_nr_migratory && dl_rq->dl_nr_running > 1) { 122 if (dl_rq->dl_nr_migratory && dl_rq->dl_nr_running > 1) {
123 if (!dl_rq->overloaded) { 123 if (!dl_rq->overloaded) {
124 dl_set_overload(rq_of_dl_rq(dl_rq)); 124 dl_set_overload(rq_of_dl_rq(dl_rq));
125 dl_rq->overloaded = 1; 125 dl_rq->overloaded = 1;
126 } 126 }
127 } else if (dl_rq->overloaded) { 127 } else if (dl_rq->overloaded) {
128 dl_clear_overload(rq_of_dl_rq(dl_rq)); 128 dl_clear_overload(rq_of_dl_rq(dl_rq));
129 dl_rq->overloaded = 0; 129 dl_rq->overloaded = 0;
130 } 130 }
131 } 131 }
132 132
133 static void inc_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq) 133 static void inc_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
134 { 134 {
135 struct task_struct *p = dl_task_of(dl_se); 135 struct task_struct *p = dl_task_of(dl_se);
136 136
137 if (p->nr_cpus_allowed > 1) 137 if (p->nr_cpus_allowed > 1)
138 dl_rq->dl_nr_migratory++; 138 dl_rq->dl_nr_migratory++;
139 139
140 update_dl_migration(dl_rq); 140 update_dl_migration(dl_rq);
141 } 141 }
142 142
143 static void dec_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq) 143 static void dec_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
144 { 144 {
145 struct task_struct *p = dl_task_of(dl_se); 145 struct task_struct *p = dl_task_of(dl_se);
146 146
147 if (p->nr_cpus_allowed > 1) 147 if (p->nr_cpus_allowed > 1)
148 dl_rq->dl_nr_migratory--; 148 dl_rq->dl_nr_migratory--;
149 149
150 update_dl_migration(dl_rq); 150 update_dl_migration(dl_rq);
151 } 151 }
152 152
153 /* 153 /*
154 * The list of pushable -deadline task is not a plist, like in 154 * The list of pushable -deadline task is not a plist, like in
155 * sched_rt.c, it is an rb-tree with tasks ordered by deadline. 155 * sched_rt.c, it is an rb-tree with tasks ordered by deadline.
156 */ 156 */
157 static void enqueue_pushable_dl_task(struct rq *rq, struct task_struct *p) 157 static void enqueue_pushable_dl_task(struct rq *rq, struct task_struct *p)
158 { 158 {
159 struct dl_rq *dl_rq = &rq->dl; 159 struct dl_rq *dl_rq = &rq->dl;
160 struct rb_node **link = &dl_rq->pushable_dl_tasks_root.rb_node; 160 struct rb_node **link = &dl_rq->pushable_dl_tasks_root.rb_node;
161 struct rb_node *parent = NULL; 161 struct rb_node *parent = NULL;
162 struct task_struct *entry; 162 struct task_struct *entry;
163 int leftmost = 1; 163 int leftmost = 1;
164 164
165 BUG_ON(!RB_EMPTY_NODE(&p->pushable_dl_tasks)); 165 BUG_ON(!RB_EMPTY_NODE(&p->pushable_dl_tasks));
166 166
167 while (*link) { 167 while (*link) {
168 parent = *link; 168 parent = *link;
169 entry = rb_entry(parent, struct task_struct, 169 entry = rb_entry(parent, struct task_struct,
170 pushable_dl_tasks); 170 pushable_dl_tasks);
171 if (dl_entity_preempt(&p->dl, &entry->dl)) 171 if (dl_entity_preempt(&p->dl, &entry->dl))
172 link = &parent->rb_left; 172 link = &parent->rb_left;
173 else { 173 else {
174 link = &parent->rb_right; 174 link = &parent->rb_right;
175 leftmost = 0; 175 leftmost = 0;
176 } 176 }
177 } 177 }
178 178
179 if (leftmost) 179 if (leftmost)
180 dl_rq->pushable_dl_tasks_leftmost = &p->pushable_dl_tasks; 180 dl_rq->pushable_dl_tasks_leftmost = &p->pushable_dl_tasks;
181 181
182 rb_link_node(&p->pushable_dl_tasks, parent, link); 182 rb_link_node(&p->pushable_dl_tasks, parent, link);
183 rb_insert_color(&p->pushable_dl_tasks, &dl_rq->pushable_dl_tasks_root); 183 rb_insert_color(&p->pushable_dl_tasks, &dl_rq->pushable_dl_tasks_root);
184 } 184 }
185 185
186 static void dequeue_pushable_dl_task(struct rq *rq, struct task_struct *p) 186 static void dequeue_pushable_dl_task(struct rq *rq, struct task_struct *p)
187 { 187 {
188 struct dl_rq *dl_rq = &rq->dl; 188 struct dl_rq *dl_rq = &rq->dl;
189 189
190 if (RB_EMPTY_NODE(&p->pushable_dl_tasks)) 190 if (RB_EMPTY_NODE(&p->pushable_dl_tasks))
191 return; 191 return;
192 192
193 if (dl_rq->pushable_dl_tasks_leftmost == &p->pushable_dl_tasks) { 193 if (dl_rq->pushable_dl_tasks_leftmost == &p->pushable_dl_tasks) {
194 struct rb_node *next_node; 194 struct rb_node *next_node;
195 195
196 next_node = rb_next(&p->pushable_dl_tasks); 196 next_node = rb_next(&p->pushable_dl_tasks);
197 dl_rq->pushable_dl_tasks_leftmost = next_node; 197 dl_rq->pushable_dl_tasks_leftmost = next_node;
198 } 198 }
199 199
200 rb_erase(&p->pushable_dl_tasks, &dl_rq->pushable_dl_tasks_root); 200 rb_erase(&p->pushable_dl_tasks, &dl_rq->pushable_dl_tasks_root);
201 RB_CLEAR_NODE(&p->pushable_dl_tasks); 201 RB_CLEAR_NODE(&p->pushable_dl_tasks);
202 } 202 }
203 203
204 static inline int has_pushable_dl_tasks(struct rq *rq) 204 static inline int has_pushable_dl_tasks(struct rq *rq)
205 { 205 {
206 return !RB_EMPTY_ROOT(&rq->dl.pushable_dl_tasks_root); 206 return !RB_EMPTY_ROOT(&rq->dl.pushable_dl_tasks_root);
207 } 207 }
208 208
209 static int push_dl_task(struct rq *rq); 209 static int push_dl_task(struct rq *rq);
210 210
211 static inline bool need_pull_dl_task(struct rq *rq, struct task_struct *prev) 211 static inline bool need_pull_dl_task(struct rq *rq, struct task_struct *prev)
212 { 212 {
213 return dl_task(prev); 213 return dl_task(prev);
214 } 214 }
215 215
216 static inline void set_post_schedule(struct rq *rq) 216 static inline void set_post_schedule(struct rq *rq)
217 { 217 {
218 rq->post_schedule = has_pushable_dl_tasks(rq); 218 rq->post_schedule = has_pushable_dl_tasks(rq);
219 } 219 }
220 220
221 #else 221 #else
222 222
223 static inline 223 static inline
224 void enqueue_pushable_dl_task(struct rq *rq, struct task_struct *p) 224 void enqueue_pushable_dl_task(struct rq *rq, struct task_struct *p)
225 { 225 {
226 } 226 }
227 227
228 static inline 228 static inline
229 void dequeue_pushable_dl_task(struct rq *rq, struct task_struct *p) 229 void dequeue_pushable_dl_task(struct rq *rq, struct task_struct *p)
230 { 230 {
231 } 231 }
232 232
233 static inline 233 static inline
234 void inc_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq) 234 void inc_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
235 { 235 {
236 } 236 }
237 237
238 static inline 238 static inline
239 void dec_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq) 239 void dec_dl_migration(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
240 { 240 {
241 } 241 }
242 242
243 static inline bool need_pull_dl_task(struct rq *rq, struct task_struct *prev) 243 static inline bool need_pull_dl_task(struct rq *rq, struct task_struct *prev)
244 { 244 {
245 return false; 245 return false;
246 } 246 }
247 247
248 static inline int pull_dl_task(struct rq *rq) 248 static inline int pull_dl_task(struct rq *rq)
249 { 249 {
250 return 0; 250 return 0;
251 } 251 }
252 252
253 static inline void set_post_schedule(struct rq *rq) 253 static inline void set_post_schedule(struct rq *rq)
254 { 254 {
255 } 255 }
256 #endif /* CONFIG_SMP */ 256 #endif /* CONFIG_SMP */
257 257
258 static void enqueue_task_dl(struct rq *rq, struct task_struct *p, int flags); 258 static void enqueue_task_dl(struct rq *rq, struct task_struct *p, int flags);
259 static void __dequeue_task_dl(struct rq *rq, struct task_struct *p, int flags); 259 static void __dequeue_task_dl(struct rq *rq, struct task_struct *p, int flags);
260 static void check_preempt_curr_dl(struct rq *rq, struct task_struct *p, 260 static void check_preempt_curr_dl(struct rq *rq, struct task_struct *p,
261 int flags); 261 int flags);
262 262
263 /* 263 /*
264 * We are being explicitly informed that a new instance is starting, 264 * We are being explicitly informed that a new instance is starting,
265 * and this means that: 265 * and this means that:
266 * - the absolute deadline of the entity has to be placed at 266 * - the absolute deadline of the entity has to be placed at
267 * current time + relative deadline; 267 * current time + relative deadline;
268 * - the runtime of the entity has to be set to the maximum value. 268 * - the runtime of the entity has to be set to the maximum value.
269 * 269 *
270 * The capability of specifying such event is useful whenever a -deadline 270 * The capability of specifying such event is useful whenever a -deadline
271 * entity wants to (try to!) synchronize its behaviour with the scheduler's 271 * entity wants to (try to!) synchronize its behaviour with the scheduler's
272 * one, and to (try to!) reconcile itself with its own scheduling 272 * one, and to (try to!) reconcile itself with its own scheduling
273 * parameters. 273 * parameters.
274 */ 274 */
275 static inline void setup_new_dl_entity(struct sched_dl_entity *dl_se, 275 static inline void setup_new_dl_entity(struct sched_dl_entity *dl_se,
276 struct sched_dl_entity *pi_se) 276 struct sched_dl_entity *pi_se)
277 { 277 {
278 struct dl_rq *dl_rq = dl_rq_of_se(dl_se); 278 struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
279 struct rq *rq = rq_of_dl_rq(dl_rq); 279 struct rq *rq = rq_of_dl_rq(dl_rq);
280 280
281 WARN_ON(!dl_se->dl_new || dl_se->dl_throttled); 281 WARN_ON(!dl_se->dl_new || dl_se->dl_throttled);
282 282
283 /* 283 /*
284 * We use the regular wall clock time to set deadlines in the 284 * We use the regular wall clock time to set deadlines in the
285 * future; in fact, we must consider execution overheads (time 285 * future; in fact, we must consider execution overheads (time
286 * spent on hardirq context, etc.). 286 * spent on hardirq context, etc.).
287 */ 287 */
288 dl_se->deadline = rq_clock(rq) + pi_se->dl_deadline; 288 dl_se->deadline = rq_clock(rq) + pi_se->dl_deadline;
289 dl_se->runtime = pi_se->dl_runtime; 289 dl_se->runtime = pi_se->dl_runtime;
290 dl_se->dl_new = 0; 290 dl_se->dl_new = 0;
291 } 291 }
292 292
293 /* 293 /*
294 * Pure Earliest Deadline First (EDF) scheduling does not deal with the 294 * Pure Earliest Deadline First (EDF) scheduling does not deal with the
295 * possibility of a entity lasting more than what it declared, and thus 295 * possibility of a entity lasting more than what it declared, and thus
296 * exhausting its runtime. 296 * exhausting its runtime.
297 * 297 *
298 * Here we are interested in making runtime overrun possible, but we do 298 * Here we are interested in making runtime overrun possible, but we do
299 * not want a entity which is misbehaving to affect the scheduling of all 299 * not want a entity which is misbehaving to affect the scheduling of all
300 * other entities. 300 * other entities.
301 * Therefore, a budgeting strategy called Constant Bandwidth Server (CBS) 301 * Therefore, a budgeting strategy called Constant Bandwidth Server (CBS)
302 * is used, in order to confine each entity within its own bandwidth. 302 * is used, in order to confine each entity within its own bandwidth.
303 * 303 *
304 * This function deals exactly with that, and ensures that when the runtime 304 * This function deals exactly with that, and ensures that when the runtime
305 * of a entity is replenished, its deadline is also postponed. That ensures 305 * of a entity is replenished, its deadline is also postponed. That ensures
306 * the overrunning entity can't interfere with other entity in the system and 306 * the overrunning entity can't interfere with other entity in the system and
307 * can't make them miss their deadlines. Reasons why this kind of overruns 307 * can't make them miss their deadlines. Reasons why this kind of overruns
308 * could happen are, typically, a entity voluntarily trying to overcome its 308 * could happen are, typically, a entity voluntarily trying to overcome its
309 * runtime, or it just underestimated it during sched_setattr(). 309 * runtime, or it just underestimated it during sched_setattr().
310 */ 310 */
311 static void replenish_dl_entity(struct sched_dl_entity *dl_se, 311 static void replenish_dl_entity(struct sched_dl_entity *dl_se,
312 struct sched_dl_entity *pi_se) 312 struct sched_dl_entity *pi_se)
313 { 313 {
314 struct dl_rq *dl_rq = dl_rq_of_se(dl_se); 314 struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
315 struct rq *rq = rq_of_dl_rq(dl_rq); 315 struct rq *rq = rq_of_dl_rq(dl_rq);
316 316
317 BUG_ON(pi_se->dl_runtime <= 0); 317 BUG_ON(pi_se->dl_runtime <= 0);
318 318
319 /* 319 /*
320 * This could be the case for a !-dl task that is boosted. 320 * This could be the case for a !-dl task that is boosted.
321 * Just go with full inherited parameters. 321 * Just go with full inherited parameters.
322 */ 322 */
323 if (dl_se->dl_deadline == 0) { 323 if (dl_se->dl_deadline == 0) {
324 dl_se->deadline = rq_clock(rq) + pi_se->dl_deadline; 324 dl_se->deadline = rq_clock(rq) + pi_se->dl_deadline;
325 dl_se->runtime = pi_se->dl_runtime; 325 dl_se->runtime = pi_se->dl_runtime;
326 } 326 }
327 327
328 /* 328 /*
329 * We keep moving the deadline away until we get some 329 * We keep moving the deadline away until we get some
330 * available runtime for the entity. This ensures correct 330 * available runtime for the entity. This ensures correct
331 * handling of situations where the runtime overrun is 331 * handling of situations where the runtime overrun is
332 * arbitrary large. 332 * arbitrary large.
333 */ 333 */
334 while (dl_se->runtime <= 0) { 334 while (dl_se->runtime <= 0) {
335 dl_se->deadline += pi_se->dl_period; 335 dl_se->deadline += pi_se->dl_period;
336 dl_se->runtime += pi_se->dl_runtime; 336 dl_se->runtime += pi_se->dl_runtime;
337 } 337 }
338 338
339 /* 339 /*
340 * At this point, the deadline really should be "in 340 * At this point, the deadline really should be "in
341 * the future" with respect to rq->clock. If it's 341 * the future" with respect to rq->clock. If it's
342 * not, we are, for some reason, lagging too much! 342 * not, we are, for some reason, lagging too much!
343 * Anyway, after having warn userspace abut that, 343 * Anyway, after having warn userspace abut that,
344 * we still try to keep the things running by 344 * we still try to keep the things running by
345 * resetting the deadline and the budget of the 345 * resetting the deadline and the budget of the
346 * entity. 346 * entity.
347 */ 347 */
348 if (dl_time_before(dl_se->deadline, rq_clock(rq))) { 348 if (dl_time_before(dl_se->deadline, rq_clock(rq))) {
349 printk_deferred_once("sched: DL replenish lagged to much\n"); 349 printk_deferred_once("sched: DL replenish lagged to much\n");
350 dl_se->deadline = rq_clock(rq) + pi_se->dl_deadline; 350 dl_se->deadline = rq_clock(rq) + pi_se->dl_deadline;
351 dl_se->runtime = pi_se->dl_runtime; 351 dl_se->runtime = pi_se->dl_runtime;
352 } 352 }
353 } 353 }
354 354
355 /* 355 /*
356 * Here we check if --at time t-- an entity (which is probably being 356 * Here we check if --at time t-- an entity (which is probably being
357 * [re]activated or, in general, enqueued) can use its remaining runtime 357 * [re]activated or, in general, enqueued) can use its remaining runtime
358 * and its current deadline _without_ exceeding the bandwidth it is 358 * and its current deadline _without_ exceeding the bandwidth it is
359 * assigned (function returns true if it can't). We are in fact applying 359 * assigned (function returns true if it can't). We are in fact applying
360 * one of the CBS rules: when a task wakes up, if the residual runtime 360 * one of the CBS rules: when a task wakes up, if the residual runtime
361 * over residual deadline fits within the allocated bandwidth, then we 361 * over residual deadline fits within the allocated bandwidth, then we
362 * can keep the current (absolute) deadline and residual budget without 362 * can keep the current (absolute) deadline and residual budget without
363 * disrupting the schedulability of the system. Otherwise, we should 363 * disrupting the schedulability of the system. Otherwise, we should
364 * refill the runtime and set the deadline a period in the future, 364 * refill the runtime and set the deadline a period in the future,
365 * because keeping the current (absolute) deadline of the task would 365 * because keeping the current (absolute) deadline of the task would
366 * result in breaking guarantees promised to other tasks (refer to 366 * result in breaking guarantees promised to other tasks (refer to
367 * Documentation/scheduler/sched-deadline.txt for more informations). 367 * Documentation/scheduler/sched-deadline.txt for more informations).
368 * 368 *
369 * This function returns true if: 369 * This function returns true if:
370 * 370 *
371 * runtime / (deadline - t) > dl_runtime / dl_period , 371 * runtime / (deadline - t) > dl_runtime / dl_period ,
372 * 372 *
373 * IOW we can't recycle current parameters. 373 * IOW we can't recycle current parameters.
374 * 374 *
375 * Notice that the bandwidth check is done against the period. For 375 * Notice that the bandwidth check is done against the period. For
376 * task with deadline equal to period this is the same of using 376 * task with deadline equal to period this is the same of using
377 * dl_deadline instead of dl_period in the equation above. 377 * dl_deadline instead of dl_period in the equation above.
378 */ 378 */
379 static bool dl_entity_overflow(struct sched_dl_entity *dl_se, 379 static bool dl_entity_overflow(struct sched_dl_entity *dl_se,
380 struct sched_dl_entity *pi_se, u64 t) 380 struct sched_dl_entity *pi_se, u64 t)
381 { 381 {
382 u64 left, right; 382 u64 left, right;
383 383
384 /* 384 /*
385 * left and right are the two sides of the equation above, 385 * left and right are the two sides of the equation above,
386 * after a bit of shuffling to use multiplications instead 386 * after a bit of shuffling to use multiplications instead
387 * of divisions. 387 * of divisions.
388 * 388 *
389 * Note that none of the time values involved in the two 389 * Note that none of the time values involved in the two
390 * multiplications are absolute: dl_deadline and dl_runtime 390 * multiplications are absolute: dl_deadline and dl_runtime
391 * are the relative deadline and the maximum runtime of each 391 * are the relative deadline and the maximum runtime of each
392 * instance, runtime is the runtime left for the last instance 392 * instance, runtime is the runtime left for the last instance
393 * and (deadline - t), since t is rq->clock, is the time left 393 * and (deadline - t), since t is rq->clock, is the time left
394 * to the (absolute) deadline. Even if overflowing the u64 type 394 * to the (absolute) deadline. Even if overflowing the u64 type
395 * is very unlikely to occur in both cases, here we scale down 395 * is very unlikely to occur in both cases, here we scale down
396 * as we want to avoid that risk at all. Scaling down by 10 396 * as we want to avoid that risk at all. Scaling down by 10
397 * means that we reduce granularity to 1us. We are fine with it, 397 * means that we reduce granularity to 1us. We are fine with it,
398 * since this is only a true/false check and, anyway, thinking 398 * since this is only a true/false check and, anyway, thinking
399 * of anything below microseconds resolution is actually fiction 399 * of anything below microseconds resolution is actually fiction
400 * (but still we want to give the user that illusion >;). 400 * (but still we want to give the user that illusion >;).
401 */ 401 */
402 left = (pi_se->dl_period >> DL_SCALE) * (dl_se->runtime >> DL_SCALE); 402 left = (pi_se->dl_period >> DL_SCALE) * (dl_se->runtime >> DL_SCALE);
403 right = ((dl_se->deadline - t) >> DL_SCALE) * 403 right = ((dl_se->deadline - t) >> DL_SCALE) *
404 (pi_se->dl_runtime >> DL_SCALE); 404 (pi_se->dl_runtime >> DL_SCALE);
405 405
406 return dl_time_before(right, left); 406 return dl_time_before(right, left);
407 } 407 }
408 408
409 /* 409 /*
410 * When a -deadline entity is queued back on the runqueue, its runtime and 410 * When a -deadline entity is queued back on the runqueue, its runtime and
411 * deadline might need updating. 411 * deadline might need updating.
412 * 412 *
413 * The policy here is that we update the deadline of the entity only if: 413 * The policy here is that we update the deadline of the entity only if:
414 * - the current deadline is in the past, 414 * - the current deadline is in the past,
415 * - using the remaining runtime with the current deadline would make 415 * - using the remaining runtime with the current deadline would make
416 * the entity exceed its bandwidth. 416 * the entity exceed its bandwidth.
417 */ 417 */
418 static void update_dl_entity(struct sched_dl_entity *dl_se, 418 static void update_dl_entity(struct sched_dl_entity *dl_se,
419 struct sched_dl_entity *pi_se) 419 struct sched_dl_entity *pi_se)
420 { 420 {
421 struct dl_rq *dl_rq = dl_rq_of_se(dl_se); 421 struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
422 struct rq *rq = rq_of_dl_rq(dl_rq); 422 struct rq *rq = rq_of_dl_rq(dl_rq);
423 423
424 /* 424 /*
425 * The arrival of a new instance needs special treatment, i.e., 425 * The arrival of a new instance needs special treatment, i.e.,
426 * the actual scheduling parameters have to be "renewed". 426 * the actual scheduling parameters have to be "renewed".
427 */ 427 */
428 if (dl_se->dl_new) { 428 if (dl_se->dl_new) {
429 setup_new_dl_entity(dl_se, pi_se); 429 setup_new_dl_entity(dl_se, pi_se);
430 return; 430 return;
431 } 431 }
432 432
433 if (dl_time_before(dl_se->deadline, rq_clock(rq)) || 433 if (dl_time_before(dl_se->deadline, rq_clock(rq)) ||
434 dl_entity_overflow(dl_se, pi_se, rq_clock(rq))) { 434 dl_entity_overflow(dl_se, pi_se, rq_clock(rq))) {
435 dl_se->deadline = rq_clock(rq) + pi_se->dl_deadline; 435 dl_se->deadline = rq_clock(rq) + pi_se->dl_deadline;
436 dl_se->runtime = pi_se->dl_runtime; 436 dl_se->runtime = pi_se->dl_runtime;
437 } 437 }
438 } 438 }
439 439
440 /* 440 /*
441 * If the entity depleted all its runtime, and if we want it to sleep 441 * If the entity depleted all its runtime, and if we want it to sleep
442 * while waiting for some new execution time to become available, we 442 * while waiting for some new execution time to become available, we
443 * set the bandwidth enforcement timer to the replenishment instant 443 * set the bandwidth enforcement timer to the replenishment instant
444 * and try to activate it. 444 * and try to activate it.
445 * 445 *
446 * Notice that it is important for the caller to know if the timer 446 * Notice that it is important for the caller to know if the timer
447 * actually started or not (i.e., the replenishment instant is in 447 * actually started or not (i.e., the replenishment instant is in
448 * the future or in the past). 448 * the future or in the past).
449 */ 449 */
450 static int start_dl_timer(struct sched_dl_entity *dl_se, bool boosted) 450 static int start_dl_timer(struct sched_dl_entity *dl_se, bool boosted)
451 { 451 {
452 struct dl_rq *dl_rq = dl_rq_of_se(dl_se); 452 struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
453 struct rq *rq = rq_of_dl_rq(dl_rq); 453 struct rq *rq = rq_of_dl_rq(dl_rq);
454 ktime_t now, act; 454 ktime_t now, act;
455 ktime_t soft, hard; 455 ktime_t soft, hard;
456 unsigned long range; 456 unsigned long range;
457 s64 delta; 457 s64 delta;
458 458
459 if (boosted) 459 if (boosted)
460 return 0; 460 return 0;
461 /* 461 /*
462 * We want the timer to fire at the deadline, but considering 462 * We want the timer to fire at the deadline, but considering
463 * that it is actually coming from rq->clock and not from 463 * that it is actually coming from rq->clock and not from
464 * hrtimer's time base reading. 464 * hrtimer's time base reading.
465 */ 465 */
466 act = ns_to_ktime(dl_se->deadline); 466 act = ns_to_ktime(dl_se->deadline);
467 now = hrtimer_cb_get_time(&dl_se->dl_timer); 467 now = hrtimer_cb_get_time(&dl_se->dl_timer);
468 delta = ktime_to_ns(now) - rq_clock(rq); 468 delta = ktime_to_ns(now) - rq_clock(rq);
469 act = ktime_add_ns(act, delta); 469 act = ktime_add_ns(act, delta);
470 470
471 /* 471 /*
472 * If the expiry time already passed, e.g., because the value 472 * If the expiry time already passed, e.g., because the value
473 * chosen as the deadline is too small, don't even try to 473 * chosen as the deadline is too small, don't even try to
474 * start the timer in the past! 474 * start the timer in the past!
475 */ 475 */
476 if (ktime_us_delta(act, now) < 0) 476 if (ktime_us_delta(act, now) < 0)
477 return 0; 477 return 0;
478 478
479 hrtimer_set_expires(&dl_se->dl_timer, act); 479 hrtimer_set_expires(&dl_se->dl_timer, act);
480 480
481 soft = hrtimer_get_softexpires(&dl_se->dl_timer); 481 soft = hrtimer_get_softexpires(&dl_se->dl_timer);
482 hard = hrtimer_get_expires(&dl_se->dl_timer); 482 hard = hrtimer_get_expires(&dl_se->dl_timer);
483 range = ktime_to_ns(ktime_sub(hard, soft)); 483 range = ktime_to_ns(ktime_sub(hard, soft));
484 __hrtimer_start_range_ns(&dl_se->dl_timer, soft, 484 __hrtimer_start_range_ns(&dl_se->dl_timer, soft,
485 range, HRTIMER_MODE_ABS, 0); 485 range, HRTIMER_MODE_ABS, 0);
486 486
487 return hrtimer_active(&dl_se->dl_timer); 487 return hrtimer_active(&dl_se->dl_timer);
488 } 488 }
489 489
490 /* 490 /*
491 * This is the bandwidth enforcement timer callback. If here, we know 491 * This is the bandwidth enforcement timer callback. If here, we know
492 * a task is not on its dl_rq, since the fact that the timer was running 492 * a task is not on its dl_rq, since the fact that the timer was running
493 * means the task is throttled and needs a runtime replenishment. 493 * means the task is throttled and needs a runtime replenishment.
494 * 494 *
495 * However, what we actually do depends on the fact the task is active, 495 * However, what we actually do depends on the fact the task is active,
496 * (it is on its rq) or has been removed from there by a call to 496 * (it is on its rq) or has been removed from there by a call to
497 * dequeue_task_dl(). In the former case we must issue the runtime 497 * dequeue_task_dl(). In the former case we must issue the runtime
498 * replenishment and add the task back to the dl_rq; in the latter, we just 498 * replenishment and add the task back to the dl_rq; in the latter, we just
499 * do nothing but clearing dl_throttled, so that runtime and deadline 499 * do nothing but clearing dl_throttled, so that runtime and deadline
500 * updating (and the queueing back to dl_rq) will be done by the 500 * updating (and the queueing back to dl_rq) will be done by the
501 * next call to enqueue_task_dl(). 501 * next call to enqueue_task_dl().
502 */ 502 */
503 static enum hrtimer_restart dl_task_timer(struct hrtimer *timer) 503 static enum hrtimer_restart dl_task_timer(struct hrtimer *timer)
504 { 504 {
505 struct sched_dl_entity *dl_se = container_of(timer, 505 struct sched_dl_entity *dl_se = container_of(timer,
506 struct sched_dl_entity, 506 struct sched_dl_entity,
507 dl_timer); 507 dl_timer);
508 struct task_struct *p = dl_task_of(dl_se); 508 struct task_struct *p = dl_task_of(dl_se);
509 struct rq *rq; 509 struct rq *rq;
510 again: 510 again:
511 rq = task_rq(p); 511 rq = task_rq(p);
512 raw_spin_lock(&rq->lock); 512 raw_spin_lock(&rq->lock);
513 513
514 if (rq != task_rq(p)) { 514 if (rq != task_rq(p)) {
515 /* Task was moved, retrying. */ 515 /* Task was moved, retrying. */
516 raw_spin_unlock(&rq->lock); 516 raw_spin_unlock(&rq->lock);
517 goto again; 517 goto again;
518 } 518 }
519 519
520 /* 520 /*
521 * We need to take care of several possible races here: 521 * We need to take care of several possible races here:
522 * 522 *
523 * - the task might have changed its scheduling policy 523 * - the task might have changed its scheduling policy
524 * to something different than SCHED_DEADLINE 524 * to something different than SCHED_DEADLINE
525 * - the task might have changed its reservation parameters 525 * - the task might have changed its reservation parameters
526 * (through sched_setattr()) 526 * (through sched_setattr())
527 * - the task might have been boosted by someone else and 527 * - the task might have been boosted by someone else and
528 * might be in the boosting/deboosting path 528 * might be in the boosting/deboosting path
529 * 529 *
530 * In all this cases we bail out, as the task is already 530 * In all this cases we bail out, as the task is already
531 * in the runqueue or is going to be enqueued back anyway. 531 * in the runqueue or is going to be enqueued back anyway.
532 */ 532 */
533 if (!dl_task(p) || dl_se->dl_new || 533 if (!dl_task(p) || dl_se->dl_new ||
534 dl_se->dl_boosted || !dl_se->dl_throttled) 534 dl_se->dl_boosted || !dl_se->dl_throttled)
535 goto unlock; 535 goto unlock;
536 536
537 sched_clock_tick(); 537 sched_clock_tick();
538 update_rq_clock(rq); 538 update_rq_clock(rq);
539 dl_se->dl_throttled = 0; 539 dl_se->dl_throttled = 0;
540 dl_se->dl_yielded = 0; 540 dl_se->dl_yielded = 0;
541 if (task_on_rq_queued(p)) { 541 if (task_on_rq_queued(p)) {
542 enqueue_task_dl(rq, p, ENQUEUE_REPLENISH); 542 enqueue_task_dl(rq, p, ENQUEUE_REPLENISH);
543 if (dl_task(rq->curr)) 543 if (dl_task(rq->curr))
544 check_preempt_curr_dl(rq, p, 0); 544 check_preempt_curr_dl(rq, p, 0);
545 else 545 else
546 resched_curr(rq); 546 resched_curr(rq);
547 #ifdef CONFIG_SMP 547 #ifdef CONFIG_SMP
548 /* 548 /*
549 * Queueing this task back might have overloaded rq, 549 * Queueing this task back might have overloaded rq,
550 * check if we need to kick someone away. 550 * check if we need to kick someone away.
551 */ 551 */
552 if (has_pushable_dl_tasks(rq)) 552 if (has_pushable_dl_tasks(rq))
553 push_dl_task(rq); 553 push_dl_task(rq);
554 #endif 554 #endif
555 } 555 }
556 unlock: 556 unlock:
557 raw_spin_unlock(&rq->lock); 557 raw_spin_unlock(&rq->lock);
558 558
559 return HRTIMER_NORESTART; 559 return HRTIMER_NORESTART;
560 } 560 }
561 561
562 void init_dl_task_timer(struct sched_dl_entity *dl_se) 562 void init_dl_task_timer(struct sched_dl_entity *dl_se)
563 { 563 {
564 struct hrtimer *timer = &dl_se->dl_timer; 564 struct hrtimer *timer = &dl_se->dl_timer;
565 565
566 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); 566 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
567 timer->function = dl_task_timer; 567 timer->function = dl_task_timer;
568 } 568 }
569 569
570 static 570 static
571 int dl_runtime_exceeded(struct rq *rq, struct sched_dl_entity *dl_se) 571 int dl_runtime_exceeded(struct rq *rq, struct sched_dl_entity *dl_se)
572 { 572 {
573 int dmiss = dl_time_before(dl_se->deadline, rq_clock(rq)); 573 return (dl_se->runtime <= 0);
574 int rorun = dl_se->runtime <= 0;
575
576 if (!rorun && !dmiss)
577 return 0;
578
579 /*
580 * If we are beyond our current deadline and we are still
581 * executing, then we have already used some of the runtime of
582 * the next instance. Thus, if we do not account that, we are
583 * stealing bandwidth from the system at each deadline miss!
584 */
585 if (dmiss) {
586 dl_se->runtime = rorun ? dl_se->runtime : 0;
587 dl_se->runtime -= rq_clock(rq) - dl_se->deadline;
588 }
589
590 return 1;
591 } 574 }
592 575
593 extern bool sched_rt_bandwidth_account(struct rt_rq *rt_rq); 576 extern bool sched_rt_bandwidth_account(struct rt_rq *rt_rq);
594 577
595 /* 578 /*
596 * Update the current task's runtime statistics (provided it is still 579 * Update the current task's runtime statistics (provided it is still
597 * a -deadline task and has not been removed from the dl_rq). 580 * a -deadline task and has not been removed from the dl_rq).
598 */ 581 */
599 static void update_curr_dl(struct rq *rq) 582 static void update_curr_dl(struct rq *rq)
600 { 583 {
601 struct task_struct *curr = rq->curr; 584 struct task_struct *curr = rq->curr;
602 struct sched_dl_entity *dl_se = &curr->dl; 585 struct sched_dl_entity *dl_se = &curr->dl;
603 u64 delta_exec; 586 u64 delta_exec;
604 587
605 if (!dl_task(curr) || !on_dl_rq(dl_se)) 588 if (!dl_task(curr) || !on_dl_rq(dl_se))
606 return; 589 return;
607 590
608 /* 591 /*
609 * Consumed budget is computed considering the time as 592 * Consumed budget is computed considering the time as
610 * observed by schedulable tasks (excluding time spent 593 * observed by schedulable tasks (excluding time spent
611 * in hardirq context, etc.). Deadlines are instead 594 * in hardirq context, etc.). Deadlines are instead
612 * computed using hard walltime. This seems to be the more 595 * computed using hard walltime. This seems to be the more
613 * natural solution, but the full ramifications of this 596 * natural solution, but the full ramifications of this
614 * approach need further study. 597 * approach need further study.
615 */ 598 */
616 delta_exec = rq_clock_task(rq) - curr->se.exec_start; 599 delta_exec = rq_clock_task(rq) - curr->se.exec_start;
617 if (unlikely((s64)delta_exec <= 0)) 600 if (unlikely((s64)delta_exec <= 0))
618 return; 601 return;
619 602
620 schedstat_set(curr->se.statistics.exec_max, 603 schedstat_set(curr->se.statistics.exec_max,
621 max(curr->se.statistics.exec_max, delta_exec)); 604 max(curr->se.statistics.exec_max, delta_exec));
622 605
623 curr->se.sum_exec_runtime += delta_exec; 606 curr->se.sum_exec_runtime += delta_exec;
624 account_group_exec_runtime(curr, delta_exec); 607 account_group_exec_runtime(curr, delta_exec);
625 608
626 curr->se.exec_start = rq_clock_task(rq); 609 curr->se.exec_start = rq_clock_task(rq);
627 cpuacct_charge(curr, delta_exec); 610 cpuacct_charge(curr, delta_exec);
628 611
629 sched_rt_avg_update(rq, delta_exec); 612 sched_rt_avg_update(rq, delta_exec);
630 613
631 dl_se->runtime -= dl_se->dl_yielded ? 0 : delta_exec; 614 dl_se->runtime -= dl_se->dl_yielded ? 0 : delta_exec;
632 if (dl_runtime_exceeded(rq, dl_se)) { 615 if (dl_runtime_exceeded(rq, dl_se)) {
633 __dequeue_task_dl(rq, curr, 0); 616 __dequeue_task_dl(rq, curr, 0);
634 if (likely(start_dl_timer(dl_se, curr->dl.dl_boosted))) 617 if (likely(start_dl_timer(dl_se, curr->dl.dl_boosted)))
635 dl_se->dl_throttled = 1; 618 dl_se->dl_throttled = 1;
636 else 619 else
637 enqueue_task_dl(rq, curr, ENQUEUE_REPLENISH); 620 enqueue_task_dl(rq, curr, ENQUEUE_REPLENISH);
638 621
639 if (!is_leftmost(curr, &rq->dl)) 622 if (!is_leftmost(curr, &rq->dl))
640 resched_curr(rq); 623 resched_curr(rq);
641 } 624 }
642 625
643 /* 626 /*
644 * Because -- for now -- we share the rt bandwidth, we need to 627 * Because -- for now -- we share the rt bandwidth, we need to
645 * account our runtime there too, otherwise actual rt tasks 628 * account our runtime there too, otherwise actual rt tasks
646 * would be able to exceed the shared quota. 629 * would be able to exceed the shared quota.
647 * 630 *
648 * Account to the root rt group for now. 631 * Account to the root rt group for now.
649 * 632 *
650 * The solution we're working towards is having the RT groups scheduled 633 * The solution we're working towards is having the RT groups scheduled
651 * using deadline servers -- however there's a few nasties to figure 634 * using deadline servers -- however there's a few nasties to figure
652 * out before that can happen. 635 * out before that can happen.
653 */ 636 */
654 if (rt_bandwidth_enabled()) { 637 if (rt_bandwidth_enabled()) {
655 struct rt_rq *rt_rq = &rq->rt; 638 struct rt_rq *rt_rq = &rq->rt;
656 639
657 raw_spin_lock(&rt_rq->rt_runtime_lock); 640 raw_spin_lock(&rt_rq->rt_runtime_lock);
658 /* 641 /*
659 * We'll let actual RT tasks worry about the overflow here, we 642 * We'll let actual RT tasks worry about the overflow here, we
660 * have our own CBS to keep us inline; only account when RT 643 * have our own CBS to keep us inline; only account when RT
661 * bandwidth is relevant. 644 * bandwidth is relevant.
662 */ 645 */
663 if (sched_rt_bandwidth_account(rt_rq)) 646 if (sched_rt_bandwidth_account(rt_rq))
664 rt_rq->rt_time += delta_exec; 647 rt_rq->rt_time += delta_exec;
665 raw_spin_unlock(&rt_rq->rt_runtime_lock); 648 raw_spin_unlock(&rt_rq->rt_runtime_lock);
666 } 649 }
667 } 650 }
668 651
669 #ifdef CONFIG_SMP 652 #ifdef CONFIG_SMP
670 653
671 static struct task_struct *pick_next_earliest_dl_task(struct rq *rq, int cpu); 654 static struct task_struct *pick_next_earliest_dl_task(struct rq *rq, int cpu);
672 655
673 static inline u64 next_deadline(struct rq *rq) 656 static inline u64 next_deadline(struct rq *rq)
674 { 657 {
675 struct task_struct *next = pick_next_earliest_dl_task(rq, rq->cpu); 658 struct task_struct *next = pick_next_earliest_dl_task(rq, rq->cpu);
676 659
677 if (next && dl_prio(next->prio)) 660 if (next && dl_prio(next->prio))
678 return next->dl.deadline; 661 return next->dl.deadline;
679 else 662 else
680 return 0; 663 return 0;
681 } 664 }
682 665
683 static void inc_dl_deadline(struct dl_rq *dl_rq, u64 deadline) 666 static void inc_dl_deadline(struct dl_rq *dl_rq, u64 deadline)
684 { 667 {
685 struct rq *rq = rq_of_dl_rq(dl_rq); 668 struct rq *rq = rq_of_dl_rq(dl_rq);
686 669
687 if (dl_rq->earliest_dl.curr == 0 || 670 if (dl_rq->earliest_dl.curr == 0 ||
688 dl_time_before(deadline, dl_rq->earliest_dl.curr)) { 671 dl_time_before(deadline, dl_rq->earliest_dl.curr)) {
689 /* 672 /*
690 * If the dl_rq had no -deadline tasks, or if the new task 673 * If the dl_rq had no -deadline tasks, or if the new task
691 * has shorter deadline than the current one on dl_rq, we 674 * has shorter deadline than the current one on dl_rq, we
692 * know that the previous earliest becomes our next earliest, 675 * know that the previous earliest becomes our next earliest,
693 * as the new task becomes the earliest itself. 676 * as the new task becomes the earliest itself.
694 */ 677 */
695 dl_rq->earliest_dl.next = dl_rq->earliest_dl.curr; 678 dl_rq->earliest_dl.next = dl_rq->earliest_dl.curr;
696 dl_rq->earliest_dl.curr = deadline; 679 dl_rq->earliest_dl.curr = deadline;
697 cpudl_set(&rq->rd->cpudl, rq->cpu, deadline, 1); 680 cpudl_set(&rq->rd->cpudl, rq->cpu, deadline, 1);
698 } else if (dl_rq->earliest_dl.next == 0 || 681 } else if (dl_rq->earliest_dl.next == 0 ||
699 dl_time_before(deadline, dl_rq->earliest_dl.next)) { 682 dl_time_before(deadline, dl_rq->earliest_dl.next)) {
700 /* 683 /*
701 * On the other hand, if the new -deadline task has a 684 * On the other hand, if the new -deadline task has a
702 * a later deadline than the earliest one on dl_rq, but 685 * a later deadline than the earliest one on dl_rq, but
703 * it is earlier than the next (if any), we must 686 * it is earlier than the next (if any), we must
704 * recompute the next-earliest. 687 * recompute the next-earliest.
705 */ 688 */
706 dl_rq->earliest_dl.next = next_deadline(rq); 689 dl_rq->earliest_dl.next = next_deadline(rq);
707 } 690 }
708 } 691 }
709 692
710 static void dec_dl_deadline(struct dl_rq *dl_rq, u64 deadline) 693 static void dec_dl_deadline(struct dl_rq *dl_rq, u64 deadline)
711 { 694 {
712 struct rq *rq = rq_of_dl_rq(dl_rq); 695 struct rq *rq = rq_of_dl_rq(dl_rq);
713 696
714 /* 697 /*
715 * Since we may have removed our earliest (and/or next earliest) 698 * Since we may have removed our earliest (and/or next earliest)
716 * task we must recompute them. 699 * task we must recompute them.
717 */ 700 */
718 if (!dl_rq->dl_nr_running) { 701 if (!dl_rq->dl_nr_running) {
719 dl_rq->earliest_dl.curr = 0; 702 dl_rq->earliest_dl.curr = 0;
720 dl_rq->earliest_dl.next = 0; 703 dl_rq->earliest_dl.next = 0;
721 cpudl_set(&rq->rd->cpudl, rq->cpu, 0, 0); 704 cpudl_set(&rq->rd->cpudl, rq->cpu, 0, 0);
722 } else { 705 } else {
723 struct rb_node *leftmost = dl_rq->rb_leftmost; 706 struct rb_node *leftmost = dl_rq->rb_leftmost;
724 struct sched_dl_entity *entry; 707 struct sched_dl_entity *entry;
725 708
726 entry = rb_entry(leftmost, struct sched_dl_entity, rb_node); 709 entry = rb_entry(leftmost, struct sched_dl_entity, rb_node);
727 dl_rq->earliest_dl.curr = entry->deadline; 710 dl_rq->earliest_dl.curr = entry->deadline;
728 dl_rq->earliest_dl.next = next_deadline(rq); 711 dl_rq->earliest_dl.next = next_deadline(rq);
729 cpudl_set(&rq->rd->cpudl, rq->cpu, entry->deadline, 1); 712 cpudl_set(&rq->rd->cpudl, rq->cpu, entry->deadline, 1);
730 } 713 }
731 } 714 }
732 715
733 #else 716 #else
734 717
735 static inline void inc_dl_deadline(struct dl_rq *dl_rq, u64 deadline) {} 718 static inline void inc_dl_deadline(struct dl_rq *dl_rq, u64 deadline) {}
736 static inline void dec_dl_deadline(struct dl_rq *dl_rq, u64 deadline) {} 719 static inline void dec_dl_deadline(struct dl_rq *dl_rq, u64 deadline) {}
737 720
738 #endif /* CONFIG_SMP */ 721 #endif /* CONFIG_SMP */
739 722
740 static inline 723 static inline
741 void inc_dl_tasks(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq) 724 void inc_dl_tasks(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
742 { 725 {
743 int prio = dl_task_of(dl_se)->prio; 726 int prio = dl_task_of(dl_se)->prio;
744 u64 deadline = dl_se->deadline; 727 u64 deadline = dl_se->deadline;
745 728
746 WARN_ON(!dl_prio(prio)); 729 WARN_ON(!dl_prio(prio));
747 dl_rq->dl_nr_running++; 730 dl_rq->dl_nr_running++;
748 add_nr_running(rq_of_dl_rq(dl_rq), 1); 731 add_nr_running(rq_of_dl_rq(dl_rq), 1);
749 732
750 inc_dl_deadline(dl_rq, deadline); 733 inc_dl_deadline(dl_rq, deadline);
751 inc_dl_migration(dl_se, dl_rq); 734 inc_dl_migration(dl_se, dl_rq);
752 } 735 }
753 736
754 static inline 737 static inline
755 void dec_dl_tasks(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq) 738 void dec_dl_tasks(struct sched_dl_entity *dl_se, struct dl_rq *dl_rq)
756 { 739 {
757 int prio = dl_task_of(dl_se)->prio; 740 int prio = dl_task_of(dl_se)->prio;
758 741
759 WARN_ON(!dl_prio(prio)); 742 WARN_ON(!dl_prio(prio));
760 WARN_ON(!dl_rq->dl_nr_running); 743 WARN_ON(!dl_rq->dl_nr_running);
761 dl_rq->dl_nr_running--; 744 dl_rq->dl_nr_running--;
762 sub_nr_running(rq_of_dl_rq(dl_rq), 1); 745 sub_nr_running(rq_of_dl_rq(dl_rq), 1);
763 746
764 dec_dl_deadline(dl_rq, dl_se->deadline); 747 dec_dl_deadline(dl_rq, dl_se->deadline);
765 dec_dl_migration(dl_se, dl_rq); 748 dec_dl_migration(dl_se, dl_rq);
766 } 749 }
767 750
768 static void __enqueue_dl_entity(struct sched_dl_entity *dl_se) 751 static void __enqueue_dl_entity(struct sched_dl_entity *dl_se)
769 { 752 {
770 struct dl_rq *dl_rq = dl_rq_of_se(dl_se); 753 struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
771 struct rb_node **link = &dl_rq->rb_root.rb_node; 754 struct rb_node **link = &dl_rq->rb_root.rb_node;
772 struct rb_node *parent = NULL; 755 struct rb_node *parent = NULL;
773 struct sched_dl_entity *entry; 756 struct sched_dl_entity *entry;
774 int leftmost = 1; 757 int leftmost = 1;
775 758
776 BUG_ON(!RB_EMPTY_NODE(&dl_se->rb_node)); 759 BUG_ON(!RB_EMPTY_NODE(&dl_se->rb_node));
777 760
778 while (*link) { 761 while (*link) {
779 parent = *link; 762 parent = *link;
780 entry = rb_entry(parent, struct sched_dl_entity, rb_node); 763 entry = rb_entry(parent, struct sched_dl_entity, rb_node);
781 if (dl_time_before(dl_se->deadline, entry->deadline)) 764 if (dl_time_before(dl_se->deadline, entry->deadline))
782 link = &parent->rb_left; 765 link = &parent->rb_left;
783 else { 766 else {
784 link = &parent->rb_right; 767 link = &parent->rb_right;
785 leftmost = 0; 768 leftmost = 0;
786 } 769 }
787 } 770 }
788 771
789 if (leftmost) 772 if (leftmost)
790 dl_rq->rb_leftmost = &dl_se->rb_node; 773 dl_rq->rb_leftmost = &dl_se->rb_node;
791 774
792 rb_link_node(&dl_se->rb_node, parent, link); 775 rb_link_node(&dl_se->rb_node, parent, link);
793 rb_insert_color(&dl_se->rb_node, &dl_rq->rb_root); 776 rb_insert_color(&dl_se->rb_node, &dl_rq->rb_root);
794 777
795 inc_dl_tasks(dl_se, dl_rq); 778 inc_dl_tasks(dl_se, dl_rq);
796 } 779 }
797 780
798 static void __dequeue_dl_entity(struct sched_dl_entity *dl_se) 781 static void __dequeue_dl_entity(struct sched_dl_entity *dl_se)
799 { 782 {
800 struct dl_rq *dl_rq = dl_rq_of_se(dl_se); 783 struct dl_rq *dl_rq = dl_rq_of_se(dl_se);
801 784
802 if (RB_EMPTY_NODE(&dl_se->rb_node)) 785 if (RB_EMPTY_NODE(&dl_se->rb_node))
803 return; 786 return;
804 787
805 if (dl_rq->rb_leftmost == &dl_se->rb_node) { 788 if (dl_rq->rb_leftmost == &dl_se->rb_node) {
806 struct rb_node *next_node; 789 struct rb_node *next_node;
807 790
808 next_node = rb_next(&dl_se->rb_node); 791 next_node = rb_next(&dl_se->rb_node);
809 dl_rq->rb_leftmost = next_node; 792 dl_rq->rb_leftmost = next_node;
810 } 793 }
811 794
812 rb_erase(&dl_se->rb_node, &dl_rq->rb_root); 795 rb_erase(&dl_se->rb_node, &dl_rq->rb_root);
813 RB_CLEAR_NODE(&dl_se->rb_node); 796 RB_CLEAR_NODE(&dl_se->rb_node);
814 797
815 dec_dl_tasks(dl_se, dl_rq); 798 dec_dl_tasks(dl_se, dl_rq);
816 } 799 }
817 800
818 static void 801 static void
819 enqueue_dl_entity(struct sched_dl_entity *dl_se, 802 enqueue_dl_entity(struct sched_dl_entity *dl_se,
820 struct sched_dl_entity *pi_se, int flags) 803 struct sched_dl_entity *pi_se, int flags)
821 { 804 {
822 BUG_ON(on_dl_rq(dl_se)); 805 BUG_ON(on_dl_rq(dl_se));
823 806
824 /* 807 /*
825 * If this is a wakeup or a new instance, the scheduling 808 * If this is a wakeup or a new instance, the scheduling
826 * parameters of the task might need updating. Otherwise, 809 * parameters of the task might need updating. Otherwise,
827 * we want a replenishment of its runtime. 810 * we want a replenishment of its runtime.
828 */ 811 */
829 if (!dl_se->dl_new && flags & ENQUEUE_REPLENISH) 812 if (dl_se->dl_new || flags & ENQUEUE_WAKEUP)
830 replenish_dl_entity(dl_se, pi_se);
831 else
832 update_dl_entity(dl_se, pi_se); 813 update_dl_entity(dl_se, pi_se);
814 else if (flags & ENQUEUE_REPLENISH)
815 replenish_dl_entity(dl_se, pi_se);
833 816
834 __enqueue_dl_entity(dl_se); 817 __enqueue_dl_entity(dl_se);
835 } 818 }
836 819
837 static void dequeue_dl_entity(struct sched_dl_entity *dl_se) 820 static void dequeue_dl_entity(struct sched_dl_entity *dl_se)
838 { 821 {
839 __dequeue_dl_entity(dl_se); 822 __dequeue_dl_entity(dl_se);
840 } 823 }
841 824
842 static void enqueue_task_dl(struct rq *rq, struct task_struct *p, int flags) 825 static void enqueue_task_dl(struct rq *rq, struct task_struct *p, int flags)
843 { 826 {
844 struct task_struct *pi_task = rt_mutex_get_top_task(p); 827 struct task_struct *pi_task = rt_mutex_get_top_task(p);
845 struct sched_dl_entity *pi_se = &p->dl; 828 struct sched_dl_entity *pi_se = &p->dl;
846 829
847 /* 830 /*
848 * Use the scheduling parameters of the top pi-waiter 831 * Use the scheduling parameters of the top pi-waiter
849 * task if we have one and its (relative) deadline is 832 * task if we have one and its (relative) deadline is
850 * smaller than our one... OTW we keep our runtime and 833 * smaller than our one... OTW we keep our runtime and
851 * deadline. 834 * deadline.
852 */ 835 */
853 if (pi_task && p->dl.dl_boosted && dl_prio(pi_task->normal_prio)) { 836 if (pi_task && p->dl.dl_boosted && dl_prio(pi_task->normal_prio)) {
854 pi_se = &pi_task->dl; 837 pi_se = &pi_task->dl;
855 } else if (!dl_prio(p->normal_prio)) { 838 } else if (!dl_prio(p->normal_prio)) {
856 /* 839 /*
857 * Special case in which we have a !SCHED_DEADLINE task 840 * Special case in which we have a !SCHED_DEADLINE task
858 * that is going to be deboosted, but exceedes its 841 * that is going to be deboosted, but exceedes its
859 * runtime while doing so. No point in replenishing 842 * runtime while doing so. No point in replenishing
860 * it, as it's going to return back to its original 843 * it, as it's going to return back to its original
861 * scheduling class after this. 844 * scheduling class after this.
862 */ 845 */
863 BUG_ON(!p->dl.dl_boosted || flags != ENQUEUE_REPLENISH); 846 BUG_ON(!p->dl.dl_boosted || flags != ENQUEUE_REPLENISH);
864 return; 847 return;
865 } 848 }
866 849
867 /* 850 /*
868 * If p is throttled, we do nothing. In fact, if it exhausted 851 * If p is throttled, we do nothing. In fact, if it exhausted
869 * its budget it needs a replenishment and, since it now is on 852 * its budget it needs a replenishment and, since it now is on
870 * its rq, the bandwidth timer callback (which clearly has not 853 * its rq, the bandwidth timer callback (which clearly has not
871 * run yet) will take care of this. 854 * run yet) will take care of this.
872 */ 855 */
873 if (p->dl.dl_throttled) 856 if (p->dl.dl_throttled)
874 return; 857 return;
875 858
876 enqueue_dl_entity(&p->dl, pi_se, flags); 859 enqueue_dl_entity(&p->dl, pi_se, flags);
877 860
878 if (!task_current(rq, p) && p->nr_cpus_allowed > 1) 861 if (!task_current(rq, p) && p->nr_cpus_allowed > 1)
879 enqueue_pushable_dl_task(rq, p); 862 enqueue_pushable_dl_task(rq, p);
880 } 863 }
881 864
882 static void __dequeue_task_dl(struct rq *rq, struct task_struct *p, int flags) 865 static void __dequeue_task_dl(struct rq *rq, struct task_struct *p, int flags)
883 { 866 {
884 dequeue_dl_entity(&p->dl); 867 dequeue_dl_entity(&p->dl);
885 dequeue_pushable_dl_task(rq, p); 868 dequeue_pushable_dl_task(rq, p);
886 } 869 }
887 870
888 static void dequeue_task_dl(struct rq *rq, struct task_struct *p, int flags) 871 static void dequeue_task_dl(struct rq *rq, struct task_struct *p, int flags)
889 { 872 {
890 update_curr_dl(rq); 873 update_curr_dl(rq);
891 __dequeue_task_dl(rq, p, flags); 874 __dequeue_task_dl(rq, p, flags);
892 } 875 }
893 876
894 /* 877 /*
895 * Yield task semantic for -deadline tasks is: 878 * Yield task semantic for -deadline tasks is:
896 * 879 *
897 * get off from the CPU until our next instance, with 880 * get off from the CPU until our next instance, with
898 * a new runtime. This is of little use now, since we 881 * a new runtime. This is of little use now, since we
899 * don't have a bandwidth reclaiming mechanism. Anyway, 882 * don't have a bandwidth reclaiming mechanism. Anyway,
900 * bandwidth reclaiming is planned for the future, and 883 * bandwidth reclaiming is planned for the future, and
901 * yield_task_dl will indicate that some spare budget 884 * yield_task_dl will indicate that some spare budget
902 * is available for other task instances to use it. 885 * is available for other task instances to use it.
903 */ 886 */
904 static void yield_task_dl(struct rq *rq) 887 static void yield_task_dl(struct rq *rq)
905 { 888 {
906 struct task_struct *p = rq->curr; 889 struct task_struct *p = rq->curr;
907 890
908 /* 891 /*
909 * We make the task go to sleep until its current deadline by 892 * We make the task go to sleep until its current deadline by
910 * forcing its runtime to zero. This way, update_curr_dl() stops 893 * forcing its runtime to zero. This way, update_curr_dl() stops
911 * it and the bandwidth timer will wake it up and will give it 894 * it and the bandwidth timer will wake it up and will give it
912 * new scheduling parameters (thanks to dl_yielded=1). 895 * new scheduling parameters (thanks to dl_yielded=1).
913 */ 896 */
914 if (p->dl.runtime > 0) { 897 if (p->dl.runtime > 0) {
915 rq->curr->dl.dl_yielded = 1; 898 rq->curr->dl.dl_yielded = 1;
916 p->dl.runtime = 0; 899 p->dl.runtime = 0;
917 } 900 }
918 update_curr_dl(rq); 901 update_curr_dl(rq);
919 } 902 }
920 903
921 #ifdef CONFIG_SMP 904 #ifdef CONFIG_SMP
922 905
923 static int find_later_rq(struct task_struct *task); 906 static int find_later_rq(struct task_struct *task);
924 907
925 static int 908 static int
926 select_task_rq_dl(struct task_struct *p, int cpu, int sd_flag, int flags) 909 select_task_rq_dl(struct task_struct *p, int cpu, int sd_flag, int flags)
927 { 910 {
928 struct task_struct *curr; 911 struct task_struct *curr;
929 struct rq *rq; 912 struct rq *rq;
930 913
931 if (sd_flag != SD_BALANCE_WAKE) 914 if (sd_flag != SD_BALANCE_WAKE)
932 goto out; 915 goto out;
933 916
934 rq = cpu_rq(cpu); 917 rq = cpu_rq(cpu);
935 918
936 rcu_read_lock(); 919 rcu_read_lock();
937 curr = ACCESS_ONCE(rq->curr); /* unlocked access */ 920 curr = ACCESS_ONCE(rq->curr); /* unlocked access */
938 921
939 /* 922 /*
940 * If we are dealing with a -deadline task, we must 923 * If we are dealing with a -deadline task, we must
941 * decide where to wake it up. 924 * decide where to wake it up.
942 * If it has a later deadline and the current task 925 * If it has a later deadline and the current task
943 * on this rq can't move (provided the waking task 926 * on this rq can't move (provided the waking task
944 * can!) we prefer to send it somewhere else. On the 927 * can!) we prefer to send it somewhere else. On the
945 * other hand, if it has a shorter deadline, we 928 * other hand, if it has a shorter deadline, we
946 * try to make it stay here, it might be important. 929 * try to make it stay here, it might be important.
947 */ 930 */
948 if (unlikely(dl_task(curr)) && 931 if (unlikely(dl_task(curr)) &&
949 (curr->nr_cpus_allowed < 2 || 932 (curr->nr_cpus_allowed < 2 ||
950 !dl_entity_preempt(&p->dl, &curr->dl)) && 933 !dl_entity_preempt(&p->dl, &curr->dl)) &&
951 (p->nr_cpus_allowed > 1)) { 934 (p->nr_cpus_allowed > 1)) {
952 int target = find_later_rq(p); 935 int target = find_later_rq(p);
953 936
954 if (target != -1) 937 if (target != -1)
955 cpu = target; 938 cpu = target;
956 } 939 }
957 rcu_read_unlock(); 940 rcu_read_unlock();
958 941
959 out: 942 out:
960 return cpu; 943 return cpu;
961 } 944 }
962 945
963 static void check_preempt_equal_dl(struct rq *rq, struct task_struct *p) 946 static void check_preempt_equal_dl(struct rq *rq, struct task_struct *p)
964 { 947 {
965 /* 948 /*
966 * Current can't be migrated, useless to reschedule, 949 * Current can't be migrated, useless to reschedule,
967 * let's hope p can move out. 950 * let's hope p can move out.
968 */ 951 */
969 if (rq->curr->nr_cpus_allowed == 1 || 952 if (rq->curr->nr_cpus_allowed == 1 ||
970 cpudl_find(&rq->rd->cpudl, rq->curr, NULL) == -1) 953 cpudl_find(&rq->rd->cpudl, rq->curr, NULL) == -1)
971 return; 954 return;
972 955
973 /* 956 /*
974 * p is migratable, so let's not schedule it and 957 * p is migratable, so let's not schedule it and
975 * see if it is pushed or pulled somewhere else. 958 * see if it is pushed or pulled somewhere else.
976 */ 959 */
977 if (p->nr_cpus_allowed != 1 && 960 if (p->nr_cpus_allowed != 1 &&
978 cpudl_find(&rq->rd->cpudl, p, NULL) != -1) 961 cpudl_find(&rq->rd->cpudl, p, NULL) != -1)
979 return; 962 return;
980 963
981 resched_curr(rq); 964 resched_curr(rq);
982 } 965 }
983 966
984 static int pull_dl_task(struct rq *this_rq); 967 static int pull_dl_task(struct rq *this_rq);
985 968
986 #endif /* CONFIG_SMP */ 969 #endif /* CONFIG_SMP */
987 970
988 /* 971 /*
989 * Only called when both the current and waking task are -deadline 972 * Only called when both the current and waking task are -deadline
990 * tasks. 973 * tasks.
991 */ 974 */
992 static void check_preempt_curr_dl(struct rq *rq, struct task_struct *p, 975 static void check_preempt_curr_dl(struct rq *rq, struct task_struct *p,
993 int flags) 976 int flags)
994 { 977 {
995 if (dl_entity_preempt(&p->dl, &rq->curr->dl)) { 978 if (dl_entity_preempt(&p->dl, &rq->curr->dl)) {
996 resched_curr(rq); 979 resched_curr(rq);
997 return; 980 return;
998 } 981 }
999 982
1000 #ifdef CONFIG_SMP 983 #ifdef CONFIG_SMP
1001 /* 984 /*
1002 * In the unlikely case current and p have the same deadline 985 * In the unlikely case current and p have the same deadline
1003 * let us try to decide what's the best thing to do... 986 * let us try to decide what's the best thing to do...
1004 */ 987 */
1005 if ((p->dl.deadline == rq->curr->dl.deadline) && 988 if ((p->dl.deadline == rq->curr->dl.deadline) &&
1006 !test_tsk_need_resched(rq->curr)) 989 !test_tsk_need_resched(rq->curr))
1007 check_preempt_equal_dl(rq, p); 990 check_preempt_equal_dl(rq, p);
1008 #endif /* CONFIG_SMP */ 991 #endif /* CONFIG_SMP */
1009 } 992 }
1010 993
1011 #ifdef CONFIG_SCHED_HRTICK 994 #ifdef CONFIG_SCHED_HRTICK
1012 static void start_hrtick_dl(struct rq *rq, struct task_struct *p) 995 static void start_hrtick_dl(struct rq *rq, struct task_struct *p)
1013 { 996 {
1014 hrtick_start(rq, p->dl.runtime); 997 hrtick_start(rq, p->dl.runtime);
1015 } 998 }
1016 #else /* !CONFIG_SCHED_HRTICK */ 999 #else /* !CONFIG_SCHED_HRTICK */
1017 static void start_hrtick_dl(struct rq *rq, struct task_struct *p) 1000 static void start_hrtick_dl(struct rq *rq, struct task_struct *p)
1018 { 1001 {
1019 } 1002 }
1020 #endif 1003 #endif
1021 1004
1022 static struct sched_dl_entity *pick_next_dl_entity(struct rq *rq, 1005 static struct sched_dl_entity *pick_next_dl_entity(struct rq *rq,
1023 struct dl_rq *dl_rq) 1006 struct dl_rq *dl_rq)
1024 { 1007 {
1025 struct rb_node *left = dl_rq->rb_leftmost; 1008 struct rb_node *left = dl_rq->rb_leftmost;
1026 1009
1027 if (!left) 1010 if (!left)
1028 return NULL; 1011 return NULL;
1029 1012
1030 return rb_entry(left, struct sched_dl_entity, rb_node); 1013 return rb_entry(left, struct sched_dl_entity, rb_node);
1031 } 1014 }
1032 1015
1033 struct task_struct *pick_next_task_dl(struct rq *rq, struct task_struct *prev) 1016 struct task_struct *pick_next_task_dl(struct rq *rq, struct task_struct *prev)
1034 { 1017 {
1035 struct sched_dl_entity *dl_se; 1018 struct sched_dl_entity *dl_se;
1036 struct task_struct *p; 1019 struct task_struct *p;
1037 struct dl_rq *dl_rq; 1020 struct dl_rq *dl_rq;
1038 1021
1039 dl_rq = &rq->dl; 1022 dl_rq = &rq->dl;
1040 1023
1041 if (need_pull_dl_task(rq, prev)) { 1024 if (need_pull_dl_task(rq, prev)) {
1042 pull_dl_task(rq); 1025 pull_dl_task(rq);
1043 /* 1026 /*
1044 * pull_rt_task() can drop (and re-acquire) rq->lock; this 1027 * pull_rt_task() can drop (and re-acquire) rq->lock; this
1045 * means a stop task can slip in, in which case we need to 1028 * means a stop task can slip in, in which case we need to
1046 * re-start task selection. 1029 * re-start task selection.
1047 */ 1030 */
1048 if (rq->stop && task_on_rq_queued(rq->stop)) 1031 if (rq->stop && task_on_rq_queued(rq->stop))
1049 return RETRY_TASK; 1032 return RETRY_TASK;
1050 } 1033 }
1051 1034
1052 /* 1035 /*
1053 * When prev is DL, we may throttle it in put_prev_task(). 1036 * When prev is DL, we may throttle it in put_prev_task().
1054 * So, we update time before we check for dl_nr_running. 1037 * So, we update time before we check for dl_nr_running.
1055 */ 1038 */
1056 if (prev->sched_class == &dl_sched_class) 1039 if (prev->sched_class == &dl_sched_class)
1057 update_curr_dl(rq); 1040 update_curr_dl(rq);
1058 1041
1059 if (unlikely(!dl_rq->dl_nr_running)) 1042 if (unlikely(!dl_rq->dl_nr_running))
1060 return NULL; 1043 return NULL;
1061 1044
1062 put_prev_task(rq, prev); 1045 put_prev_task(rq, prev);
1063 1046
1064 dl_se = pick_next_dl_entity(rq, dl_rq); 1047 dl_se = pick_next_dl_entity(rq, dl_rq);
1065 BUG_ON(!dl_se); 1048 BUG_ON(!dl_se);
1066 1049
1067 p = dl_task_of(dl_se); 1050 p = dl_task_of(dl_se);
1068 p->se.exec_start = rq_clock_task(rq); 1051 p->se.exec_start = rq_clock_task(rq);
1069 1052
1070 /* Running task will never be pushed. */ 1053 /* Running task will never be pushed. */
1071 dequeue_pushable_dl_task(rq, p); 1054 dequeue_pushable_dl_task(rq, p);
1072 1055
1073 if (hrtick_enabled(rq)) 1056 if (hrtick_enabled(rq))
1074 start_hrtick_dl(rq, p); 1057 start_hrtick_dl(rq, p);
1075 1058
1076 set_post_schedule(rq); 1059 set_post_schedule(rq);
1077 1060
1078 return p; 1061 return p;
1079 } 1062 }
1080 1063
1081 static void put_prev_task_dl(struct rq *rq, struct task_struct *p) 1064 static void put_prev_task_dl(struct rq *rq, struct task_struct *p)
1082 { 1065 {
1083 update_curr_dl(rq); 1066 update_curr_dl(rq);
1084 1067
1085 if (on_dl_rq(&p->dl) && p->nr_cpus_allowed > 1) 1068 if (on_dl_rq(&p->dl) && p->nr_cpus_allowed > 1)
1086 enqueue_pushable_dl_task(rq, p); 1069 enqueue_pushable_dl_task(rq, p);
1087 } 1070 }
1088 1071
1089 static void task_tick_dl(struct rq *rq, struct task_struct *p, int queued) 1072 static void task_tick_dl(struct rq *rq, struct task_struct *p, int queued)
1090 { 1073 {
1091 update_curr_dl(rq); 1074 update_curr_dl(rq);
1092 1075
1093 if (hrtick_enabled(rq) && queued && p->dl.runtime > 0) 1076 if (hrtick_enabled(rq) && queued && p->dl.runtime > 0)
1094 start_hrtick_dl(rq, p); 1077 start_hrtick_dl(rq, p);
1095 } 1078 }
1096 1079
1097 static void task_fork_dl(struct task_struct *p) 1080 static void task_fork_dl(struct task_struct *p)
1098 { 1081 {
1099 /* 1082 /*
1100 * SCHED_DEADLINE tasks cannot fork and this is achieved through 1083 * SCHED_DEADLINE tasks cannot fork and this is achieved through
1101 * sched_fork() 1084 * sched_fork()
1102 */ 1085 */
1103 } 1086 }
1104 1087
1105 static void task_dead_dl(struct task_struct *p) 1088 static void task_dead_dl(struct task_struct *p)
1106 { 1089 {
1107 struct hrtimer *timer = &p->dl.dl_timer; 1090 struct hrtimer *timer = &p->dl.dl_timer;
1108 struct dl_bw *dl_b = dl_bw_of(task_cpu(p)); 1091 struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
1109 1092
1110 /* 1093 /*
1111 * Since we are TASK_DEAD we won't slip out of the domain! 1094 * Since we are TASK_DEAD we won't slip out of the domain!
1112 */ 1095 */
1113 raw_spin_lock_irq(&dl_b->lock); 1096 raw_spin_lock_irq(&dl_b->lock);
1114 dl_b->total_bw -= p->dl.dl_bw; 1097 dl_b->total_bw -= p->dl.dl_bw;
1115 raw_spin_unlock_irq(&dl_b->lock); 1098 raw_spin_unlock_irq(&dl_b->lock);
1116 1099
1117 hrtimer_cancel(timer); 1100 hrtimer_cancel(timer);
1118 } 1101 }
1119 1102
1120 static void set_curr_task_dl(struct rq *rq) 1103 static void set_curr_task_dl(struct rq *rq)
1121 { 1104 {
1122 struct task_struct *p = rq->curr; 1105 struct task_struct *p = rq->curr;
1123 1106
1124 p->se.exec_start = rq_clock_task(rq); 1107 p->se.exec_start = rq_clock_task(rq);
1125 1108
1126 /* You can't push away the running task */ 1109 /* You can't push away the running task */
1127 dequeue_pushable_dl_task(rq, p); 1110 dequeue_pushable_dl_task(rq, p);
1128 } 1111 }
1129 1112
1130 #ifdef CONFIG_SMP 1113 #ifdef CONFIG_SMP
1131 1114
1132 /* Only try algorithms three times */ 1115 /* Only try algorithms three times */
1133 #define DL_MAX_TRIES 3 1116 #define DL_MAX_TRIES 3
1134 1117
1135 static int pick_dl_task(struct rq *rq, struct task_struct *p, int cpu) 1118 static int pick_dl_task(struct rq *rq, struct task_struct *p, int cpu)
1136 { 1119 {
1137 if (!task_running(rq, p) && 1120 if (!task_running(rq, p) &&
1138 cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) 1121 cpumask_test_cpu(cpu, tsk_cpus_allowed(p)))
1139 return 1; 1122 return 1;
1140 return 0; 1123 return 0;
1141 } 1124 }
1142 1125
1143 /* Returns the second earliest -deadline task, NULL otherwise */ 1126 /* Returns the second earliest -deadline task, NULL otherwise */
1144 static struct task_struct *pick_next_earliest_dl_task(struct rq *rq, int cpu) 1127 static struct task_struct *pick_next_earliest_dl_task(struct rq *rq, int cpu)
1145 { 1128 {
1146 struct rb_node *next_node = rq->dl.rb_leftmost; 1129 struct rb_node *next_node = rq->dl.rb_leftmost;
1147 struct sched_dl_entity *dl_se; 1130 struct sched_dl_entity *dl_se;
1148 struct task_struct *p = NULL; 1131 struct task_struct *p = NULL;
1149 1132
1150 next_node: 1133 next_node:
1151 next_node = rb_next(next_node); 1134 next_node = rb_next(next_node);
1152 if (next_node) { 1135 if (next_node) {
1153 dl_se = rb_entry(next_node, struct sched_dl_entity, rb_node); 1136 dl_se = rb_entry(next_node, struct sched_dl_entity, rb_node);
1154 p = dl_task_of(dl_se); 1137 p = dl_task_of(dl_se);
1155 1138
1156 if (pick_dl_task(rq, p, cpu)) 1139 if (pick_dl_task(rq, p, cpu))
1157 return p; 1140 return p;
1158 1141
1159 goto next_node; 1142 goto next_node;
1160 } 1143 }
1161 1144
1162 return NULL; 1145 return NULL;
1163 } 1146 }
1164 1147
1165 static DEFINE_PER_CPU(cpumask_var_t, local_cpu_mask_dl); 1148 static DEFINE_PER_CPU(cpumask_var_t, local_cpu_mask_dl);
1166 1149
1167 static int find_later_rq(struct task_struct *task) 1150 static int find_later_rq(struct task_struct *task)
1168 { 1151 {
1169 struct sched_domain *sd; 1152 struct sched_domain *sd;
1170 struct cpumask *later_mask = this_cpu_cpumask_var_ptr(local_cpu_mask_dl); 1153 struct cpumask *later_mask = this_cpu_cpumask_var_ptr(local_cpu_mask_dl);
1171 int this_cpu = smp_processor_id(); 1154 int this_cpu = smp_processor_id();
1172 int best_cpu, cpu = task_cpu(task); 1155 int best_cpu, cpu = task_cpu(task);
1173 1156
1174 /* Make sure the mask is initialized first */ 1157 /* Make sure the mask is initialized first */
1175 if (unlikely(!later_mask)) 1158 if (unlikely(!later_mask))
1176 return -1; 1159 return -1;
1177 1160
1178 if (task->nr_cpus_allowed == 1) 1161 if (task->nr_cpus_allowed == 1)
1179 return -1; 1162 return -1;
1180 1163
1181 /* 1164 /*
1182 * We have to consider system topology and task affinity 1165 * We have to consider system topology and task affinity
1183 * first, then we can look for a suitable cpu. 1166 * first, then we can look for a suitable cpu.
1184 */ 1167 */
1185 cpumask_copy(later_mask, task_rq(task)->rd->span); 1168 cpumask_copy(later_mask, task_rq(task)->rd->span);
1186 cpumask_and(later_mask, later_mask, cpu_active_mask); 1169 cpumask_and(later_mask, later_mask, cpu_active_mask);
1187 cpumask_and(later_mask, later_mask, &task->cpus_allowed); 1170 cpumask_and(later_mask, later_mask, &task->cpus_allowed);
1188 best_cpu = cpudl_find(&task_rq(task)->rd->cpudl, 1171 best_cpu = cpudl_find(&task_rq(task)->rd->cpudl,
1189 task, later_mask); 1172 task, later_mask);
1190 if (best_cpu == -1) 1173 if (best_cpu == -1)
1191 return -1; 1174 return -1;
1192 1175
1193 /* 1176 /*
1194 * If we are here, some target has been found, 1177 * If we are here, some target has been found,
1195 * the most suitable of which is cached in best_cpu. 1178 * the most suitable of which is cached in best_cpu.
1196 * This is, among the runqueues where the current tasks 1179 * This is, among the runqueues where the current tasks
1197 * have later deadlines than the task's one, the rq 1180 * have later deadlines than the task's one, the rq
1198 * with the latest possible one. 1181 * with the latest possible one.
1199 * 1182 *
1200 * Now we check how well this matches with task's 1183 * Now we check how well this matches with task's
1201 * affinity and system topology. 1184 * affinity and system topology.
1202 * 1185 *
1203 * The last cpu where the task run is our first 1186 * The last cpu where the task run is our first
1204 * guess, since it is most likely cache-hot there. 1187 * guess, since it is most likely cache-hot there.
1205 */ 1188 */
1206 if (cpumask_test_cpu(cpu, later_mask)) 1189 if (cpumask_test_cpu(cpu, later_mask))
1207 return cpu; 1190 return cpu;
1208 /* 1191 /*
1209 * Check if this_cpu is to be skipped (i.e., it is 1192 * Check if this_cpu is to be skipped (i.e., it is
1210 * not in the mask) or not. 1193 * not in the mask) or not.
1211 */ 1194 */
1212 if (!cpumask_test_cpu(this_cpu, later_mask)) 1195 if (!cpumask_test_cpu(this_cpu, later_mask))
1213 this_cpu = -1; 1196 this_cpu = -1;
1214 1197
1215 rcu_read_lock(); 1198 rcu_read_lock();
1216 for_each_domain(cpu, sd) { 1199 for_each_domain(cpu, sd) {
1217 if (sd->flags & SD_WAKE_AFFINE) { 1200 if (sd->flags & SD_WAKE_AFFINE) {
1218 1201
1219 /* 1202 /*
1220 * If possible, preempting this_cpu is 1203 * If possible, preempting this_cpu is
1221 * cheaper than migrating. 1204 * cheaper than migrating.
1222 */ 1205 */
1223 if (this_cpu != -1 && 1206 if (this_cpu != -1 &&
1224 cpumask_test_cpu(this_cpu, sched_domain_span(sd))) { 1207 cpumask_test_cpu(this_cpu, sched_domain_span(sd))) {
1225 rcu_read_unlock(); 1208 rcu_read_unlock();
1226 return this_cpu; 1209 return this_cpu;
1227 } 1210 }
1228 1211
1229 /* 1212 /*
1230 * Last chance: if best_cpu is valid and is 1213 * Last chance: if best_cpu is valid and is
1231 * in the mask, that becomes our choice. 1214 * in the mask, that becomes our choice.
1232 */ 1215 */
1233 if (best_cpu < nr_cpu_ids && 1216 if (best_cpu < nr_cpu_ids &&
1234 cpumask_test_cpu(best_cpu, sched_domain_span(sd))) { 1217 cpumask_test_cpu(best_cpu, sched_domain_span(sd))) {
1235 rcu_read_unlock(); 1218 rcu_read_unlock();
1236 return best_cpu; 1219 return best_cpu;
1237 } 1220 }
1238 } 1221 }
1239 } 1222 }
1240 rcu_read_unlock(); 1223 rcu_read_unlock();
1241 1224
1242 /* 1225 /*
1243 * At this point, all our guesses failed, we just return 1226 * At this point, all our guesses failed, we just return
1244 * 'something', and let the caller sort the things out. 1227 * 'something', and let the caller sort the things out.
1245 */ 1228 */
1246 if (this_cpu != -1) 1229 if (this_cpu != -1)
1247 return this_cpu; 1230 return this_cpu;
1248 1231
1249 cpu = cpumask_any(later_mask); 1232 cpu = cpumask_any(later_mask);
1250 if (cpu < nr_cpu_ids) 1233 if (cpu < nr_cpu_ids)
1251 return cpu; 1234 return cpu;
1252 1235
1253 return -1; 1236 return -1;
1254 } 1237 }
1255 1238
1256 /* Locks the rq it finds */ 1239 /* Locks the rq it finds */
1257 static struct rq *find_lock_later_rq(struct task_struct *task, struct rq *rq) 1240 static struct rq *find_lock_later_rq(struct task_struct *task, struct rq *rq)
1258 { 1241 {
1259 struct rq *later_rq = NULL; 1242 struct rq *later_rq = NULL;
1260 int tries; 1243 int tries;
1261 int cpu; 1244 int cpu;
1262 1245
1263 for (tries = 0; tries < DL_MAX_TRIES; tries++) { 1246 for (tries = 0; tries < DL_MAX_TRIES; tries++) {
1264 cpu = find_later_rq(task); 1247 cpu = find_later_rq(task);
1265 1248
1266 if ((cpu == -1) || (cpu == rq->cpu)) 1249 if ((cpu == -1) || (cpu == rq->cpu))
1267 break; 1250 break;
1268 1251
1269 later_rq = cpu_rq(cpu); 1252 later_rq = cpu_rq(cpu);
1270 1253
1271 /* Retry if something changed. */ 1254 /* Retry if something changed. */
1272 if (double_lock_balance(rq, later_rq)) { 1255 if (double_lock_balance(rq, later_rq)) {
1273 if (unlikely(task_rq(task) != rq || 1256 if (unlikely(task_rq(task) != rq ||
1274 !cpumask_test_cpu(later_rq->cpu, 1257 !cpumask_test_cpu(later_rq->cpu,
1275 &task->cpus_allowed) || 1258 &task->cpus_allowed) ||
1276 task_running(rq, task) || 1259 task_running(rq, task) ||
1277 !task_on_rq_queued(task))) { 1260 !task_on_rq_queued(task))) {
1278 double_unlock_balance(rq, later_rq); 1261 double_unlock_balance(rq, later_rq);
1279 later_rq = NULL; 1262 later_rq = NULL;
1280 break; 1263 break;
1281 } 1264 }
1282 } 1265 }
1283 1266
1284 /* 1267 /*
1285 * If the rq we found has no -deadline task, or 1268 * If the rq we found has no -deadline task, or
1286 * its earliest one has a later deadline than our 1269 * its earliest one has a later deadline than our
1287 * task, the rq is a good one. 1270 * task, the rq is a good one.
1288 */ 1271 */
1289 if (!later_rq->dl.dl_nr_running || 1272 if (!later_rq->dl.dl_nr_running ||
1290 dl_time_before(task->dl.deadline, 1273 dl_time_before(task->dl.deadline,
1291 later_rq->dl.earliest_dl.curr)) 1274 later_rq->dl.earliest_dl.curr))
1292 break; 1275 break;
1293 1276
1294 /* Otherwise we try again. */ 1277 /* Otherwise we try again. */
1295 double_unlock_balance(rq, later_rq); 1278 double_unlock_balance(rq, later_rq);
1296 later_rq = NULL; 1279 later_rq = NULL;
1297 } 1280 }
1298 1281
1299 return later_rq; 1282 return later_rq;
1300 } 1283 }
1301 1284
1302 static struct task_struct *pick_next_pushable_dl_task(struct rq *rq) 1285 static struct task_struct *pick_next_pushable_dl_task(struct rq *rq)
1303 { 1286 {
1304 struct task_struct *p; 1287 struct task_struct *p;
1305 1288
1306 if (!has_pushable_dl_tasks(rq)) 1289 if (!has_pushable_dl_tasks(rq))
1307 return NULL; 1290 return NULL;
1308 1291
1309 p = rb_entry(rq->dl.pushable_dl_tasks_leftmost, 1292 p = rb_entry(rq->dl.pushable_dl_tasks_leftmost,
1310 struct task_struct, pushable_dl_tasks); 1293 struct task_struct, pushable_dl_tasks);
1311 1294
1312 BUG_ON(rq->cpu != task_cpu(p)); 1295 BUG_ON(rq->cpu != task_cpu(p));
1313 BUG_ON(task_current(rq, p)); 1296 BUG_ON(task_current(rq, p));
1314 BUG_ON(p->nr_cpus_allowed <= 1); 1297 BUG_ON(p->nr_cpus_allowed <= 1);
1315 1298
1316 BUG_ON(!task_on_rq_queued(p)); 1299 BUG_ON(!task_on_rq_queued(p));
1317 BUG_ON(!dl_task(p)); 1300 BUG_ON(!dl_task(p));
1318 1301
1319 return p; 1302 return p;
1320 } 1303 }
1321 1304
1322 /* 1305 /*
1323 * See if the non running -deadline tasks on this rq 1306 * See if the non running -deadline tasks on this rq
1324 * can be sent to some other CPU where they can preempt 1307 * can be sent to some other CPU where they can preempt
1325 * and start executing. 1308 * and start executing.
1326 */ 1309 */
1327 static int push_dl_task(struct rq *rq) 1310 static int push_dl_task(struct rq *rq)
1328 { 1311 {
1329 struct task_struct *next_task; 1312 struct task_struct *next_task;
1330 struct rq *later_rq; 1313 struct rq *later_rq;
1331 int ret = 0; 1314 int ret = 0;
1332 1315
1333 if (!rq->dl.overloaded) 1316 if (!rq->dl.overloaded)
1334 return 0; 1317 return 0;
1335 1318
1336 next_task = pick_next_pushable_dl_task(rq); 1319 next_task = pick_next_pushable_dl_task(rq);
1337 if (!next_task) 1320 if (!next_task)
1338 return 0; 1321 return 0;
1339 1322
1340 retry: 1323 retry:
1341 if (unlikely(next_task == rq->curr)) { 1324 if (unlikely(next_task == rq->curr)) {
1342 WARN_ON(1); 1325 WARN_ON(1);
1343 return 0; 1326 return 0;
1344 } 1327 }
1345 1328
1346 /* 1329 /*
1347 * If next_task preempts rq->curr, and rq->curr 1330 * If next_task preempts rq->curr, and rq->curr
1348 * can move away, it makes sense to just reschedule 1331 * can move away, it makes sense to just reschedule
1349 * without going further in pushing next_task. 1332 * without going further in pushing next_task.
1350 */ 1333 */
1351 if (dl_task(rq->curr) && 1334 if (dl_task(rq->curr) &&
1352 dl_time_before(next_task->dl.deadline, rq->curr->dl.deadline) && 1335 dl_time_before(next_task->dl.deadline, rq->curr->dl.deadline) &&
1353 rq->curr->nr_cpus_allowed > 1) { 1336 rq->curr->nr_cpus_allowed > 1) {
1354 resched_curr(rq); 1337 resched_curr(rq);
1355 return 0; 1338 return 0;
1356 } 1339 }
1357 1340
1358 /* We might release rq lock */ 1341 /* We might release rq lock */
1359 get_task_struct(next_task); 1342 get_task_struct(next_task);
1360 1343
1361 /* Will lock the rq it'll find */ 1344 /* Will lock the rq it'll find */
1362 later_rq = find_lock_later_rq(next_task, rq); 1345 later_rq = find_lock_later_rq(next_task, rq);
1363 if (!later_rq) { 1346 if (!later_rq) {
1364 struct task_struct *task; 1347 struct task_struct *task;
1365 1348
1366 /* 1349 /*
1367 * We must check all this again, since 1350 * We must check all this again, since
1368 * find_lock_later_rq releases rq->lock and it is 1351 * find_lock_later_rq releases rq->lock and it is
1369 * then possible that next_task has migrated. 1352 * then possible that next_task has migrated.
1370 */ 1353 */
1371 task = pick_next_pushable_dl_task(rq); 1354 task = pick_next_pushable_dl_task(rq);
1372 if (task_cpu(next_task) == rq->cpu && task == next_task) { 1355 if (task_cpu(next_task) == rq->cpu && task == next_task) {
1373 /* 1356 /*
1374 * The task is still there. We don't try 1357 * The task is still there. We don't try
1375 * again, some other cpu will pull it when ready. 1358 * again, some other cpu will pull it when ready.
1376 */ 1359 */
1377 goto out; 1360 goto out;
1378 } 1361 }
1379 1362
1380 if (!task) 1363 if (!task)
1381 /* No more tasks */ 1364 /* No more tasks */
1382 goto out; 1365 goto out;
1383 1366
1384 put_task_struct(next_task); 1367 put_task_struct(next_task);
1385 next_task = task; 1368 next_task = task;
1386 goto retry; 1369 goto retry;
1387 } 1370 }
1388 1371
1389 deactivate_task(rq, next_task, 0); 1372 deactivate_task(rq, next_task, 0);
1390 set_task_cpu(next_task, later_rq->cpu); 1373 set_task_cpu(next_task, later_rq->cpu);
1391 activate_task(later_rq, next_task, 0); 1374 activate_task(later_rq, next_task, 0);
1392 ret = 1; 1375 ret = 1;
1393 1376
1394 resched_curr(later_rq); 1377 resched_curr(later_rq);
1395 1378
1396 double_unlock_balance(rq, later_rq); 1379 double_unlock_balance(rq, later_rq);
1397 1380
1398 out: 1381 out:
1399 put_task_struct(next_task); 1382 put_task_struct(next_task);
1400 1383
1401 return ret; 1384 return ret;
1402 } 1385 }
1403 1386
1404 static void push_dl_tasks(struct rq *rq) 1387 static void push_dl_tasks(struct rq *rq)
1405 { 1388 {
1406 /* Terminates as it moves a -deadline task */ 1389 /* Terminates as it moves a -deadline task */
1407 while (push_dl_task(rq)) 1390 while (push_dl_task(rq))
1408 ; 1391 ;
1409 } 1392 }
1410 1393
1411 static int pull_dl_task(struct rq *this_rq) 1394 static int pull_dl_task(struct rq *this_rq)
1412 { 1395 {
1413 int this_cpu = this_rq->cpu, ret = 0, cpu; 1396 int this_cpu = this_rq->cpu, ret = 0, cpu;
1414 struct task_struct *p; 1397 struct task_struct *p;
1415 struct rq *src_rq; 1398 struct rq *src_rq;
1416 u64 dmin = LONG_MAX; 1399 u64 dmin = LONG_MAX;
1417 1400
1418 if (likely(!dl_overloaded(this_rq))) 1401 if (likely(!dl_overloaded(this_rq)))
1419 return 0; 1402 return 0;
1420 1403
1421 /* 1404 /*
1422 * Match the barrier from dl_set_overloaded; this guarantees that if we 1405 * Match the barrier from dl_set_overloaded; this guarantees that if we
1423 * see overloaded we must also see the dlo_mask bit. 1406 * see overloaded we must also see the dlo_mask bit.
1424 */ 1407 */
1425 smp_rmb(); 1408 smp_rmb();
1426 1409
1427 for_each_cpu(cpu, this_rq->rd->dlo_mask) { 1410 for_each_cpu(cpu, this_rq->rd->dlo_mask) {
1428 if (this_cpu == cpu) 1411 if (this_cpu == cpu)
1429 continue; 1412 continue;
1430 1413
1431 src_rq = cpu_rq(cpu); 1414 src_rq = cpu_rq(cpu);
1432 1415
1433 /* 1416 /*
1434 * It looks racy, abd it is! However, as in sched_rt.c, 1417 * It looks racy, abd it is! However, as in sched_rt.c,
1435 * we are fine with this. 1418 * we are fine with this.
1436 */ 1419 */
1437 if (this_rq->dl.dl_nr_running && 1420 if (this_rq->dl.dl_nr_running &&
1438 dl_time_before(this_rq->dl.earliest_dl.curr, 1421 dl_time_before(this_rq->dl.earliest_dl.curr,
1439 src_rq->dl.earliest_dl.next)) 1422 src_rq->dl.earliest_dl.next))
1440 continue; 1423 continue;
1441 1424
1442 /* Might drop this_rq->lock */ 1425 /* Might drop this_rq->lock */
1443 double_lock_balance(this_rq, src_rq); 1426 double_lock_balance(this_rq, src_rq);
1444 1427
1445 /* 1428 /*
1446 * If there are no more pullable tasks on the 1429 * If there are no more pullable tasks on the
1447 * rq, we're done with it. 1430 * rq, we're done with it.
1448 */ 1431 */
1449 if (src_rq->dl.dl_nr_running <= 1) 1432 if (src_rq->dl.dl_nr_running <= 1)
1450 goto skip; 1433 goto skip;
1451 1434
1452 p = pick_next_earliest_dl_task(src_rq, this_cpu); 1435 p = pick_next_earliest_dl_task(src_rq, this_cpu);
1453 1436
1454 /* 1437 /*
1455 * We found a task to be pulled if: 1438 * We found a task to be pulled if:
1456 * - it preempts our current (if there's one), 1439 * - it preempts our current (if there's one),
1457 * - it will preempt the last one we pulled (if any). 1440 * - it will preempt the last one we pulled (if any).
1458 */ 1441 */
1459 if (p && dl_time_before(p->dl.deadline, dmin) && 1442 if (p && dl_time_before(p->dl.deadline, dmin) &&
1460 (!this_rq->dl.dl_nr_running || 1443 (!this_rq->dl.dl_nr_running ||
1461 dl_time_before(p->dl.deadline, 1444 dl_time_before(p->dl.deadline,
1462 this_rq->dl.earliest_dl.curr))) { 1445 this_rq->dl.earliest_dl.curr))) {
1463 WARN_ON(p == src_rq->curr); 1446 WARN_ON(p == src_rq->curr);
1464 WARN_ON(!task_on_rq_queued(p)); 1447 WARN_ON(!task_on_rq_queued(p));
1465 1448
1466 /* 1449 /*
1467 * Then we pull iff p has actually an earlier 1450 * Then we pull iff p has actually an earlier
1468 * deadline than the current task of its runqueue. 1451 * deadline than the current task of its runqueue.
1469 */ 1452 */
1470 if (dl_time_before(p->dl.deadline, 1453 if (dl_time_before(p->dl.deadline,
1471 src_rq->curr->dl.deadline)) 1454 src_rq->curr->dl.deadline))
1472 goto skip; 1455 goto skip;
1473 1456
1474 ret = 1; 1457 ret = 1;
1475 1458
1476 deactivate_task(src_rq, p, 0); 1459 deactivate_task(src_rq, p, 0);
1477 set_task_cpu(p, this_cpu); 1460 set_task_cpu(p, this_cpu);
1478 activate_task(this_rq, p, 0); 1461 activate_task(this_rq, p, 0);
1479 dmin = p->dl.deadline; 1462 dmin = p->dl.deadline;
1480 1463
1481 /* Is there any other task even earlier? */ 1464 /* Is there any other task even earlier? */
1482 } 1465 }
1483 skip: 1466 skip:
1484 double_unlock_balance(this_rq, src_rq); 1467 double_unlock_balance(this_rq, src_rq);
1485 } 1468 }
1486 1469
1487 return ret; 1470 return ret;
1488 } 1471 }
1489 1472
1490 static void post_schedule_dl(struct rq *rq) 1473 static void post_schedule_dl(struct rq *rq)
1491 { 1474 {
1492 push_dl_tasks(rq); 1475 push_dl_tasks(rq);
1493 } 1476 }
1494 1477
1495 /* 1478 /*
1496 * Since the task is not running and a reschedule is not going to happen 1479 * Since the task is not running and a reschedule is not going to happen
1497 * anytime soon on its runqueue, we try pushing it away now. 1480 * anytime soon on its runqueue, we try pushing it away now.
1498 */ 1481 */
1499 static void task_woken_dl(struct rq *rq, struct task_struct *p) 1482 static void task_woken_dl(struct rq *rq, struct task_struct *p)
1500 { 1483 {
1501 if (!task_running(rq, p) && 1484 if (!task_running(rq, p) &&
1502 !test_tsk_need_resched(rq->curr) && 1485 !test_tsk_need_resched(rq->curr) &&
1503 has_pushable_dl_tasks(rq) && 1486 has_pushable_dl_tasks(rq) &&
1504 p->nr_cpus_allowed > 1 && 1487 p->nr_cpus_allowed > 1 &&
1505 dl_task(rq->curr) && 1488 dl_task(rq->curr) &&
1506 (rq->curr->nr_cpus_allowed < 2 || 1489 (rq->curr->nr_cpus_allowed < 2 ||
1507 !dl_entity_preempt(&p->dl, &rq->curr->dl))) { 1490 !dl_entity_preempt(&p->dl, &rq->curr->dl))) {
1508 push_dl_tasks(rq); 1491 push_dl_tasks(rq);
1509 } 1492 }
1510 } 1493 }
1511 1494
1512 static void set_cpus_allowed_dl(struct task_struct *p, 1495 static void set_cpus_allowed_dl(struct task_struct *p,
1513 const struct cpumask *new_mask) 1496 const struct cpumask *new_mask)
1514 { 1497 {
1515 struct rq *rq; 1498 struct rq *rq;
1516 struct root_domain *src_rd; 1499 struct root_domain *src_rd;
1517 int weight; 1500 int weight;
1518 1501
1519 BUG_ON(!dl_task(p)); 1502 BUG_ON(!dl_task(p));
1520 1503
1521 rq = task_rq(p); 1504 rq = task_rq(p);
1522 src_rd = rq->rd; 1505 src_rd = rq->rd;
1523 /* 1506 /*
1524 * Migrating a SCHED_DEADLINE task between exclusive 1507 * Migrating a SCHED_DEADLINE task between exclusive
1525 * cpusets (different root_domains) entails a bandwidth 1508 * cpusets (different root_domains) entails a bandwidth
1526 * update. We already made space for us in the destination 1509 * update. We already made space for us in the destination
1527 * domain (see cpuset_can_attach()). 1510 * domain (see cpuset_can_attach()).
1528 */ 1511 */
1529 if (!cpumask_intersects(src_rd->span, new_mask)) { 1512 if (!cpumask_intersects(src_rd->span, new_mask)) {
1530 struct dl_bw *src_dl_b; 1513 struct dl_bw *src_dl_b;
1531 1514
1532 src_dl_b = dl_bw_of(cpu_of(rq)); 1515 src_dl_b = dl_bw_of(cpu_of(rq));
1533 /* 1516 /*
1534 * We now free resources of the root_domain we are migrating 1517 * We now free resources of the root_domain we are migrating
1535 * off. In the worst case, sched_setattr() may temporary fail 1518 * off. In the worst case, sched_setattr() may temporary fail
1536 * until we complete the update. 1519 * until we complete the update.
1537 */ 1520 */
1538 raw_spin_lock(&src_dl_b->lock); 1521 raw_spin_lock(&src_dl_b->lock);
1539 __dl_clear(src_dl_b, p->dl.dl_bw); 1522 __dl_clear(src_dl_b, p->dl.dl_bw);
1540 raw_spin_unlock(&src_dl_b->lock); 1523 raw_spin_unlock(&src_dl_b->lock);
1541 } 1524 }
1542 1525
1543 /* 1526 /*
1544 * Update only if the task is actually running (i.e., 1527 * Update only if the task is actually running (i.e.,
1545 * it is on the rq AND it is not throttled). 1528 * it is on the rq AND it is not throttled).
1546 */ 1529 */
1547 if (!on_dl_rq(&p->dl)) 1530 if (!on_dl_rq(&p->dl))
1548 return; 1531 return;
1549 1532
1550 weight = cpumask_weight(new_mask); 1533 weight = cpumask_weight(new_mask);
1551 1534
1552 /* 1535 /*
1553 * Only update if the process changes its state from whether it 1536 * Only update if the process changes its state from whether it
1554 * can migrate or not. 1537 * can migrate or not.
1555 */ 1538 */
1556 if ((p->nr_cpus_allowed > 1) == (weight > 1)) 1539 if ((p->nr_cpus_allowed > 1) == (weight > 1))
1557 return; 1540 return;
1558 1541
1559 /* 1542 /*
1560 * The process used to be able to migrate OR it can now migrate 1543 * The process used to be able to migrate OR it can now migrate
1561 */ 1544 */
1562 if (weight <= 1) { 1545 if (weight <= 1) {
1563 if (!task_current(rq, p)) 1546 if (!task_current(rq, p))
1564 dequeue_pushable_dl_task(rq, p); 1547 dequeue_pushable_dl_task(rq, p);
1565 BUG_ON(!rq->dl.dl_nr_migratory); 1548 BUG_ON(!rq->dl.dl_nr_migratory);
1566 rq->dl.dl_nr_migratory--; 1549 rq->dl.dl_nr_migratory--;
1567 } else { 1550 } else {
1568 if (!task_current(rq, p)) 1551 if (!task_current(rq, p))
1569 enqueue_pushable_dl_task(rq, p); 1552 enqueue_pushable_dl_task(rq, p);
1570 rq->dl.dl_nr_migratory++; 1553 rq->dl.dl_nr_migratory++;
1571 } 1554 }
1572 1555
1573 update_dl_migration(&rq->dl); 1556 update_dl_migration(&rq->dl);
1574 } 1557 }
1575 1558
1576 /* Assumes rq->lock is held */ 1559 /* Assumes rq->lock is held */
1577 static void rq_online_dl(struct rq *rq) 1560 static void rq_online_dl(struct rq *rq)
1578 { 1561 {
1579 if (rq->dl.overloaded) 1562 if (rq->dl.overloaded)
1580 dl_set_overload(rq); 1563 dl_set_overload(rq);
1581 1564
1582 if (rq->dl.dl_nr_running > 0) 1565 if (rq->dl.dl_nr_running > 0)
1583 cpudl_set(&rq->rd->cpudl, rq->cpu, rq->dl.earliest_dl.curr, 1); 1566 cpudl_set(&rq->rd->cpudl, rq->cpu, rq->dl.earliest_dl.curr, 1);
1584 } 1567 }
1585 1568
1586 /* Assumes rq->lock is held */ 1569 /* Assumes rq->lock is held */
1587 static void rq_offline_dl(struct rq *rq) 1570 static void rq_offline_dl(struct rq *rq)
1588 { 1571 {
1589 if (rq->dl.overloaded) 1572 if (rq->dl.overloaded)
1590 dl_clear_overload(rq); 1573 dl_clear_overload(rq);
1591 1574
1592 cpudl_set(&rq->rd->cpudl, rq->cpu, 0, 0); 1575 cpudl_set(&rq->rd->cpudl, rq->cpu, 0, 0);
1593 } 1576 }
1594 1577
1595 void init_sched_dl_class(void) 1578 void init_sched_dl_class(void)
1596 { 1579 {
1597 unsigned int i; 1580 unsigned int i;
1598 1581
1599 for_each_possible_cpu(i) 1582 for_each_possible_cpu(i)
1600 zalloc_cpumask_var_node(&per_cpu(local_cpu_mask_dl, i), 1583 zalloc_cpumask_var_node(&per_cpu(local_cpu_mask_dl, i),
1601 GFP_KERNEL, cpu_to_node(i)); 1584 GFP_KERNEL, cpu_to_node(i));
1602 } 1585 }
1603 1586
1604 #endif /* CONFIG_SMP */ 1587 #endif /* CONFIG_SMP */
1605 1588
1606 /* 1589 /*
1607 * Ensure p's dl_timer is cancelled. May drop rq->lock for a while. 1590 * Ensure p's dl_timer is cancelled. May drop rq->lock for a while.
1608 */ 1591 */
1609 static void cancel_dl_timer(struct rq *rq, struct task_struct *p) 1592 static void cancel_dl_timer(struct rq *rq, struct task_struct *p)
1610 { 1593 {
1611 struct hrtimer *dl_timer = &p->dl.dl_timer; 1594 struct hrtimer *dl_timer = &p->dl.dl_timer;
1612 1595
1613 /* Nobody will change task's class if pi_lock is held */ 1596 /* Nobody will change task's class if pi_lock is held */
1614 lockdep_assert_held(&p->pi_lock); 1597 lockdep_assert_held(&p->pi_lock);
1615 1598
1616 if (hrtimer_active(dl_timer)) { 1599 if (hrtimer_active(dl_timer)) {
1617 int ret = hrtimer_try_to_cancel(dl_timer); 1600 int ret = hrtimer_try_to_cancel(dl_timer);
1618 1601
1619 if (unlikely(ret == -1)) { 1602 if (unlikely(ret == -1)) {
1620 /* 1603 /*
1621 * Note, p may migrate OR new deadline tasks 1604 * Note, p may migrate OR new deadline tasks
1622 * may appear in rq when we are unlocking it. 1605 * may appear in rq when we are unlocking it.
1623 * A caller of us must be fine with that. 1606 * A caller of us must be fine with that.
1624 */ 1607 */
1625 raw_spin_unlock(&rq->lock); 1608 raw_spin_unlock(&rq->lock);
1626 hrtimer_cancel(dl_timer); 1609 hrtimer_cancel(dl_timer);
1627 raw_spin_lock(&rq->lock); 1610 raw_spin_lock(&rq->lock);
1628 } 1611 }
1629 } 1612 }
1630 } 1613 }
1631 1614
1632 static void switched_from_dl(struct rq *rq, struct task_struct *p) 1615 static void switched_from_dl(struct rq *rq, struct task_struct *p)
1633 { 1616 {
1634 cancel_dl_timer(rq, p); 1617 cancel_dl_timer(rq, p);
1635 1618
1636 __dl_clear_params(p); 1619 __dl_clear_params(p);
1637 1620
1638 /* 1621 /*
1639 * Since this might be the only -deadline task on the rq, 1622 * Since this might be the only -deadline task on the rq,
1640 * this is the right place to try to pull some other one 1623 * this is the right place to try to pull some other one
1641 * from an overloaded cpu, if any. 1624 * from an overloaded cpu, if any.
1642 */ 1625 */
1643 if (!task_on_rq_queued(p) || rq->dl.dl_nr_running) 1626 if (!task_on_rq_queued(p) || rq->dl.dl_nr_running)
1644 return; 1627 return;
1645 1628
1646 if (pull_dl_task(rq)) 1629 if (pull_dl_task(rq))
1647 resched_curr(rq); 1630 resched_curr(rq);
1648 } 1631 }
1649 1632
1650 /* 1633 /*
1651 * When switching to -deadline, we may overload the rq, then 1634 * When switching to -deadline, we may overload the rq, then
1652 * we try to push someone off, if possible. 1635 * we try to push someone off, if possible.
1653 */ 1636 */
1654 static void switched_to_dl(struct rq *rq, struct task_struct *p) 1637 static void switched_to_dl(struct rq *rq, struct task_struct *p)
1655 { 1638 {
1656 int check_resched = 1; 1639 int check_resched = 1;
1657 1640
1658 /* 1641 /*
1659 * If p is throttled, don't consider the possibility 1642 * If p is throttled, don't consider the possibility
1660 * of preempting rq->curr, the check will be done right 1643 * of preempting rq->curr, the check will be done right
1661 * after its runtime will get replenished. 1644 * after its runtime will get replenished.
1662 */ 1645 */
1663 if (unlikely(p->dl.dl_throttled)) 1646 if (unlikely(p->dl.dl_throttled))
1664 return; 1647 return;
1665 1648
1666 if (task_on_rq_queued(p) && rq->curr != p) { 1649 if (task_on_rq_queued(p) && rq->curr != p) {
1667 #ifdef CONFIG_SMP 1650 #ifdef CONFIG_SMP
1668 if (p->nr_cpus_allowed > 1 && rq->dl.overloaded && 1651 if (p->nr_cpus_allowed > 1 && rq->dl.overloaded &&
1669 push_dl_task(rq) && rq != task_rq(p)) 1652 push_dl_task(rq) && rq != task_rq(p))
1670 /* Only reschedule if pushing failed */ 1653 /* Only reschedule if pushing failed */
1671 check_resched = 0; 1654 check_resched = 0;
1672 #endif /* CONFIG_SMP */ 1655 #endif /* CONFIG_SMP */
1673 if (check_resched) { 1656 if (check_resched) {
1674 if (dl_task(rq->curr)) 1657 if (dl_task(rq->curr))
1675 check_preempt_curr_dl(rq, p, 0); 1658 check_preempt_curr_dl(rq, p, 0);
1676 else 1659 else
1677 resched_curr(rq); 1660 resched_curr(rq);
1678 } 1661 }
1679 } 1662 }
1680 } 1663 }
1681 1664
1682 /* 1665 /*
1683 * If the scheduling parameters of a -deadline task changed, 1666 * If the scheduling parameters of a -deadline task changed,
1684 * a push or pull operation might be needed. 1667 * a push or pull operation might be needed.
1685 */ 1668 */
1686 static void prio_changed_dl(struct rq *rq, struct task_struct *p, 1669 static void prio_changed_dl(struct rq *rq, struct task_struct *p,
1687 int oldprio) 1670 int oldprio)
1688 { 1671 {
1689 if (task_on_rq_queued(p) || rq->curr == p) { 1672 if (task_on_rq_queued(p) || rq->curr == p) {
1690 #ifdef CONFIG_SMP 1673 #ifdef CONFIG_SMP
1691 /* 1674 /*
1692 * This might be too much, but unfortunately 1675 * This might be too much, but unfortunately
1693 * we don't have the old deadline value, and 1676 * we don't have the old deadline value, and
1694 * we can't argue if the task is increasing 1677 * we can't argue if the task is increasing
1695 * or lowering its prio, so... 1678 * or lowering its prio, so...
1696 */ 1679 */
1697 if (!rq->dl.overloaded) 1680 if (!rq->dl.overloaded)
1698 pull_dl_task(rq); 1681 pull_dl_task(rq);
1699 1682
1700 /* 1683 /*
1701 * If we now have a earlier deadline task than p, 1684 * If we now have a earlier deadline task than p,
1702 * then reschedule, provided p is still on this 1685 * then reschedule, provided p is still on this
1703 * runqueue. 1686 * runqueue.
1704 */ 1687 */
1705 if (dl_time_before(rq->dl.earliest_dl.curr, p->dl.deadline) && 1688 if (dl_time_before(rq->dl.earliest_dl.curr, p->dl.deadline) &&
1706 rq->curr == p) 1689 rq->curr == p)
1707 resched_curr(rq); 1690 resched_curr(rq);
1708 #else 1691 #else
1709 /* 1692 /*
1710 * Again, we don't know if p has a earlier 1693 * Again, we don't know if p has a earlier
1711 * or later deadline, so let's blindly set a 1694 * or later deadline, so let's blindly set a
1712 * (maybe not needed) rescheduling point. 1695 * (maybe not needed) rescheduling point.
1713 */ 1696 */
1714 resched_curr(rq); 1697 resched_curr(rq);
1715 #endif /* CONFIG_SMP */ 1698 #endif /* CONFIG_SMP */
1716 } else 1699 } else
1717 switched_to_dl(rq, p); 1700 switched_to_dl(rq, p);
1718 } 1701 }
1719 1702
1720 const struct sched_class dl_sched_class = { 1703 const struct sched_class dl_sched_class = {
1721 .next = &rt_sched_class, 1704 .next = &rt_sched_class,
1722 .enqueue_task = enqueue_task_dl, 1705 .enqueue_task = enqueue_task_dl,
1723 .dequeue_task = dequeue_task_dl, 1706 .dequeue_task = dequeue_task_dl,
1724 .yield_task = yield_task_dl, 1707 .yield_task = yield_task_dl,
1725 1708
1726 .check_preempt_curr = check_preempt_curr_dl, 1709 .check_preempt_curr = check_preempt_curr_dl,
1727 1710
1728 .pick_next_task = pick_next_task_dl, 1711 .pick_next_task = pick_next_task_dl,
1729 .put_prev_task = put_prev_task_dl, 1712 .put_prev_task = put_prev_task_dl,
1730 1713
1731 #ifdef CONFIG_SMP 1714 #ifdef CONFIG_SMP
1732 .select_task_rq = select_task_rq_dl, 1715 .select_task_rq = select_task_rq_dl,
1733 .set_cpus_allowed = set_cpus_allowed_dl, 1716 .set_cpus_allowed = set_cpus_allowed_dl,
1734 .rq_online = rq_online_dl, 1717 .rq_online = rq_online_dl,
1735 .rq_offline = rq_offline_dl, 1718 .rq_offline = rq_offline_dl,
1736 .post_schedule = post_schedule_dl, 1719 .post_schedule = post_schedule_dl,
1737 .task_woken = task_woken_dl, 1720 .task_woken = task_woken_dl,
1738 #endif 1721 #endif
1739 1722
1740 .set_curr_task = set_curr_task_dl, 1723 .set_curr_task = set_curr_task_dl,
1741 .task_tick = task_tick_dl, 1724 .task_tick = task_tick_dl,
1742 .task_fork = task_fork_dl, 1725 .task_fork = task_fork_dl,
1743 .task_dead = task_dead_dl, 1726 .task_dead = task_dead_dl,
1744 1727
1745 .prio_changed = prio_changed_dl, 1728 .prio_changed = prio_changed_dl,
1746 .switched_from = switched_from_dl, 1729 .switched_from = switched_from_dl,
1747 .switched_to = switched_to_dl, 1730 .switched_to = switched_to_dl,
1748 1731
1749 .update_curr = update_curr_dl, 1732 .update_curr = update_curr_dl,
1750 }; 1733 };
1751 1734
1752 #ifdef CONFIG_SCHED_DEBUG 1735 #ifdef CONFIG_SCHED_DEBUG
1753 extern void print_dl_rq(struct seq_file *m, int cpu, struct dl_rq *dl_rq); 1736 extern void print_dl_rq(struct seq_file *m, int cpu, struct dl_rq *dl_rq);
1754 1737
1755 void print_dl_stats(struct seq_file *m, int cpu) 1738 void print_dl_stats(struct seq_file *m, int cpu)
1756 { 1739 {
1757 print_dl_rq(m, cpu, &cpu_rq(cpu)->dl); 1740 print_dl_rq(m, cpu, &cpu_rq(cpu)->dl);
1758 } 1741 }
1 /* 1 /*
2 * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH) 2 * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH)
3 * 3 *
4 * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com> 4 * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com>
5 * 5 *
6 * Interactivity improvements by Mike Galbraith 6 * Interactivity improvements by Mike Galbraith
7 * (C) 2007 Mike Galbraith <efault@gmx.de> 7 * (C) 2007 Mike Galbraith <efault@gmx.de>
8 * 8 *
9 * Various enhancements by Dmitry Adamushko. 9 * Various enhancements by Dmitry Adamushko.
10 * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com> 10 * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com>
11 * 11 *
12 * Group scheduling enhancements by Srivatsa Vaddagiri 12 * Group scheduling enhancements by Srivatsa Vaddagiri
13 * Copyright IBM Corporation, 2007 13 * Copyright IBM Corporation, 2007
14 * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com> 14 * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com>
15 * 15 *
16 * Scaled math optimizations by Thomas Gleixner 16 * Scaled math optimizations by Thomas Gleixner
17 * Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de> 17 * Copyright (C) 2007, Thomas Gleixner <tglx@linutronix.de>
18 * 18 *
19 * Adaptive scheduling granularity, math enhancements by Peter Zijlstra 19 * Adaptive scheduling granularity, math enhancements by Peter Zijlstra
20 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com> 20 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
21 */ 21 */
22 22
23 #include <linux/latencytop.h> 23 #include <linux/latencytop.h>
24 #include <linux/sched.h> 24 #include <linux/sched.h>
25 #include <linux/cpumask.h> 25 #include <linux/cpumask.h>
26 #include <linux/cpuidle.h> 26 #include <linux/cpuidle.h>
27 #include <linux/slab.h> 27 #include <linux/slab.h>
28 #include <linux/profile.h> 28 #include <linux/profile.h>
29 #include <linux/interrupt.h> 29 #include <linux/interrupt.h>
30 #include <linux/mempolicy.h> 30 #include <linux/mempolicy.h>
31 #include <linux/migrate.h> 31 #include <linux/migrate.h>
32 #include <linux/task_work.h> 32 #include <linux/task_work.h>
33 33
34 #include <trace/events/sched.h> 34 #include <trace/events/sched.h>
35 35
36 #include "sched.h" 36 #include "sched.h"
37 37
38 /* 38 /*
39 * Targeted preemption latency for CPU-bound tasks: 39 * Targeted preemption latency for CPU-bound tasks:
40 * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds) 40 * (default: 6ms * (1 + ilog(ncpus)), units: nanoseconds)
41 * 41 *
42 * NOTE: this latency value is not the same as the concept of 42 * NOTE: this latency value is not the same as the concept of
43 * 'timeslice length' - timeslices in CFS are of variable length 43 * 'timeslice length' - timeslices in CFS are of variable length
44 * and have no persistent notion like in traditional, time-slice 44 * and have no persistent notion like in traditional, time-slice
45 * based scheduling concepts. 45 * based scheduling concepts.
46 * 46 *
47 * (to see the precise effective timeslice length of your workload, 47 * (to see the precise effective timeslice length of your workload,
48 * run vmstat and monitor the context-switches (cs) field) 48 * run vmstat and monitor the context-switches (cs) field)
49 */ 49 */
50 unsigned int sysctl_sched_latency = 6000000ULL; 50 unsigned int sysctl_sched_latency = 6000000ULL;
51 unsigned int normalized_sysctl_sched_latency = 6000000ULL; 51 unsigned int normalized_sysctl_sched_latency = 6000000ULL;
52 52
53 /* 53 /*
54 * The initial- and re-scaling of tunables is configurable 54 * The initial- and re-scaling of tunables is configurable
55 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus)) 55 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus))
56 * 56 *
57 * Options are: 57 * Options are:
58 * SCHED_TUNABLESCALING_NONE - unscaled, always *1 58 * SCHED_TUNABLESCALING_NONE - unscaled, always *1
59 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus) 59 * SCHED_TUNABLESCALING_LOG - scaled logarithmical, *1+ilog(ncpus)
60 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus 60 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus
61 */ 61 */
62 enum sched_tunable_scaling sysctl_sched_tunable_scaling 62 enum sched_tunable_scaling sysctl_sched_tunable_scaling
63 = SCHED_TUNABLESCALING_LOG; 63 = SCHED_TUNABLESCALING_LOG;
64 64
65 /* 65 /*
66 * Minimal preemption granularity for CPU-bound tasks: 66 * Minimal preemption granularity for CPU-bound tasks:
67 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds) 67 * (default: 0.75 msec * (1 + ilog(ncpus)), units: nanoseconds)
68 */ 68 */
69 unsigned int sysctl_sched_min_granularity = 750000ULL; 69 unsigned int sysctl_sched_min_granularity = 750000ULL;
70 unsigned int normalized_sysctl_sched_min_granularity = 750000ULL; 70 unsigned int normalized_sysctl_sched_min_granularity = 750000ULL;
71 71
72 /* 72 /*
73 * is kept at sysctl_sched_latency / sysctl_sched_min_granularity 73 * is kept at sysctl_sched_latency / sysctl_sched_min_granularity
74 */ 74 */
75 static unsigned int sched_nr_latency = 8; 75 static unsigned int sched_nr_latency = 8;
76 76
77 /* 77 /*
78 * After fork, child runs first. If set to 0 (default) then 78 * After fork, child runs first. If set to 0 (default) then
79 * parent will (try to) run first. 79 * parent will (try to) run first.
80 */ 80 */
81 unsigned int sysctl_sched_child_runs_first __read_mostly; 81 unsigned int sysctl_sched_child_runs_first __read_mostly;
82 82
83 /* 83 /*
84 * SCHED_OTHER wake-up granularity. 84 * SCHED_OTHER wake-up granularity.
85 * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds) 85 * (default: 1 msec * (1 + ilog(ncpus)), units: nanoseconds)
86 * 86 *
87 * This option delays the preemption effects of decoupled workloads 87 * This option delays the preemption effects of decoupled workloads
88 * and reduces their over-scheduling. Synchronous workloads will still 88 * and reduces their over-scheduling. Synchronous workloads will still
89 * have immediate wakeup/sleep latencies. 89 * have immediate wakeup/sleep latencies.
90 */ 90 */
91 unsigned int sysctl_sched_wakeup_granularity = 1000000UL; 91 unsigned int sysctl_sched_wakeup_granularity = 1000000UL;
92 unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL; 92 unsigned int normalized_sysctl_sched_wakeup_granularity = 1000000UL;
93 93
94 const_debug unsigned int sysctl_sched_migration_cost = 500000UL; 94 const_debug unsigned int sysctl_sched_migration_cost = 500000UL;
95 95
96 /* 96 /*
97 * The exponential sliding window over which load is averaged for shares 97 * The exponential sliding window over which load is averaged for shares
98 * distribution. 98 * distribution.
99 * (default: 10msec) 99 * (default: 10msec)
100 */ 100 */
101 unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL; 101 unsigned int __read_mostly sysctl_sched_shares_window = 10000000UL;
102 102
103 #ifdef CONFIG_CFS_BANDWIDTH 103 #ifdef CONFIG_CFS_BANDWIDTH
104 /* 104 /*
105 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool 105 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool
106 * each time a cfs_rq requests quota. 106 * each time a cfs_rq requests quota.
107 * 107 *
108 * Note: in the case that the slice exceeds the runtime remaining (either due 108 * Note: in the case that the slice exceeds the runtime remaining (either due
109 * to consumption or the quota being specified to be smaller than the slice) 109 * to consumption or the quota being specified to be smaller than the slice)
110 * we will always only issue the remaining available time. 110 * we will always only issue the remaining available time.
111 * 111 *
112 * default: 5 msec, units: microseconds 112 * default: 5 msec, units: microseconds
113 */ 113 */
114 unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL; 114 unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL;
115 #endif 115 #endif
116 116
117 static inline void update_load_add(struct load_weight *lw, unsigned long inc) 117 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
118 { 118 {
119 lw->weight += inc; 119 lw->weight += inc;
120 lw->inv_weight = 0; 120 lw->inv_weight = 0;
121 } 121 }
122 122
123 static inline void update_load_sub(struct load_weight *lw, unsigned long dec) 123 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
124 { 124 {
125 lw->weight -= dec; 125 lw->weight -= dec;
126 lw->inv_weight = 0; 126 lw->inv_weight = 0;
127 } 127 }
128 128
129 static inline void update_load_set(struct load_weight *lw, unsigned long w) 129 static inline void update_load_set(struct load_weight *lw, unsigned long w)
130 { 130 {
131 lw->weight = w; 131 lw->weight = w;
132 lw->inv_weight = 0; 132 lw->inv_weight = 0;
133 } 133 }
134 134
135 /* 135 /*
136 * Increase the granularity value when there are more CPUs, 136 * Increase the granularity value when there are more CPUs,
137 * because with more CPUs the 'effective latency' as visible 137 * because with more CPUs the 'effective latency' as visible
138 * to users decreases. But the relationship is not linear, 138 * to users decreases. But the relationship is not linear,
139 * so pick a second-best guess by going with the log2 of the 139 * so pick a second-best guess by going with the log2 of the
140 * number of CPUs. 140 * number of CPUs.
141 * 141 *
142 * This idea comes from the SD scheduler of Con Kolivas: 142 * This idea comes from the SD scheduler of Con Kolivas:
143 */ 143 */
144 static int get_update_sysctl_factor(void) 144 static int get_update_sysctl_factor(void)
145 { 145 {
146 unsigned int cpus = min_t(int, num_online_cpus(), 8); 146 unsigned int cpus = min_t(int, num_online_cpus(), 8);
147 unsigned int factor; 147 unsigned int factor;
148 148
149 switch (sysctl_sched_tunable_scaling) { 149 switch (sysctl_sched_tunable_scaling) {
150 case SCHED_TUNABLESCALING_NONE: 150 case SCHED_TUNABLESCALING_NONE:
151 factor = 1; 151 factor = 1;
152 break; 152 break;
153 case SCHED_TUNABLESCALING_LINEAR: 153 case SCHED_TUNABLESCALING_LINEAR:
154 factor = cpus; 154 factor = cpus;
155 break; 155 break;
156 case SCHED_TUNABLESCALING_LOG: 156 case SCHED_TUNABLESCALING_LOG:
157 default: 157 default:
158 factor = 1 + ilog2(cpus); 158 factor = 1 + ilog2(cpus);
159 break; 159 break;
160 } 160 }
161 161
162 return factor; 162 return factor;
163 } 163 }
164 164
165 static void update_sysctl(void) 165 static void update_sysctl(void)
166 { 166 {
167 unsigned int factor = get_update_sysctl_factor(); 167 unsigned int factor = get_update_sysctl_factor();
168 168
169 #define SET_SYSCTL(name) \ 169 #define SET_SYSCTL(name) \
170 (sysctl_##name = (factor) * normalized_sysctl_##name) 170 (sysctl_##name = (factor) * normalized_sysctl_##name)
171 SET_SYSCTL(sched_min_granularity); 171 SET_SYSCTL(sched_min_granularity);
172 SET_SYSCTL(sched_latency); 172 SET_SYSCTL(sched_latency);
173 SET_SYSCTL(sched_wakeup_granularity); 173 SET_SYSCTL(sched_wakeup_granularity);
174 #undef SET_SYSCTL 174 #undef SET_SYSCTL
175 } 175 }
176 176
177 void sched_init_granularity(void) 177 void sched_init_granularity(void)
178 { 178 {
179 update_sysctl(); 179 update_sysctl();
180 } 180 }
181 181
182 #define WMULT_CONST (~0U) 182 #define WMULT_CONST (~0U)
183 #define WMULT_SHIFT 32 183 #define WMULT_SHIFT 32
184 184
185 static void __update_inv_weight(struct load_weight *lw) 185 static void __update_inv_weight(struct load_weight *lw)
186 { 186 {
187 unsigned long w; 187 unsigned long w;
188 188
189 if (likely(lw->inv_weight)) 189 if (likely(lw->inv_weight))
190 return; 190 return;
191 191
192 w = scale_load_down(lw->weight); 192 w = scale_load_down(lw->weight);
193 193
194 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST)) 194 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST))
195 lw->inv_weight = 1; 195 lw->inv_weight = 1;
196 else if (unlikely(!w)) 196 else if (unlikely(!w))
197 lw->inv_weight = WMULT_CONST; 197 lw->inv_weight = WMULT_CONST;
198 else 198 else
199 lw->inv_weight = WMULT_CONST / w; 199 lw->inv_weight = WMULT_CONST / w;
200 } 200 }
201 201
202 /* 202 /*
203 * delta_exec * weight / lw.weight 203 * delta_exec * weight / lw.weight
204 * OR 204 * OR
205 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT 205 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT
206 * 206 *
207 * Either weight := NICE_0_LOAD and lw \e prio_to_wmult[], in which case 207 * Either weight := NICE_0_LOAD and lw \e prio_to_wmult[], in which case
208 * we're guaranteed shift stays positive because inv_weight is guaranteed to 208 * we're guaranteed shift stays positive because inv_weight is guaranteed to
209 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22. 209 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22.
210 * 210 *
211 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus 211 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus
212 * weight/lw.weight <= 1, and therefore our shift will also be positive. 212 * weight/lw.weight <= 1, and therefore our shift will also be positive.
213 */ 213 */
214 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw) 214 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw)
215 { 215 {
216 u64 fact = scale_load_down(weight); 216 u64 fact = scale_load_down(weight);
217 int shift = WMULT_SHIFT; 217 int shift = WMULT_SHIFT;
218 218
219 __update_inv_weight(lw); 219 __update_inv_weight(lw);
220 220
221 if (unlikely(fact >> 32)) { 221 if (unlikely(fact >> 32)) {
222 while (fact >> 32) { 222 while (fact >> 32) {
223 fact >>= 1; 223 fact >>= 1;
224 shift--; 224 shift--;
225 } 225 }
226 } 226 }
227 227
228 /* hint to use a 32x32->64 mul */ 228 /* hint to use a 32x32->64 mul */
229 fact = (u64)(u32)fact * lw->inv_weight; 229 fact = (u64)(u32)fact * lw->inv_weight;
230 230
231 while (fact >> 32) { 231 while (fact >> 32) {
232 fact >>= 1; 232 fact >>= 1;
233 shift--; 233 shift--;
234 } 234 }
235 235
236 return mul_u64_u32_shr(delta_exec, fact, shift); 236 return mul_u64_u32_shr(delta_exec, fact, shift);
237 } 237 }
238 238
239 239
240 const struct sched_class fair_sched_class; 240 const struct sched_class fair_sched_class;
241 241
242 /************************************************************** 242 /**************************************************************
243 * CFS operations on generic schedulable entities: 243 * CFS operations on generic schedulable entities:
244 */ 244 */
245 245
246 #ifdef CONFIG_FAIR_GROUP_SCHED 246 #ifdef CONFIG_FAIR_GROUP_SCHED
247 247
248 /* cpu runqueue to which this cfs_rq is attached */ 248 /* cpu runqueue to which this cfs_rq is attached */
249 static inline struct rq *rq_of(struct cfs_rq *cfs_rq) 249 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
250 { 250 {
251 return cfs_rq->rq; 251 return cfs_rq->rq;
252 } 252 }
253 253
254 /* An entity is a task if it doesn't "own" a runqueue */ 254 /* An entity is a task if it doesn't "own" a runqueue */
255 #define entity_is_task(se) (!se->my_q) 255 #define entity_is_task(se) (!se->my_q)
256 256
257 static inline struct task_struct *task_of(struct sched_entity *se) 257 static inline struct task_struct *task_of(struct sched_entity *se)
258 { 258 {
259 #ifdef CONFIG_SCHED_DEBUG 259 #ifdef CONFIG_SCHED_DEBUG
260 WARN_ON_ONCE(!entity_is_task(se)); 260 WARN_ON_ONCE(!entity_is_task(se));
261 #endif 261 #endif
262 return container_of(se, struct task_struct, se); 262 return container_of(se, struct task_struct, se);
263 } 263 }
264 264
265 /* Walk up scheduling entities hierarchy */ 265 /* Walk up scheduling entities hierarchy */
266 #define for_each_sched_entity(se) \ 266 #define for_each_sched_entity(se) \
267 for (; se; se = se->parent) 267 for (; se; se = se->parent)
268 268
269 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p) 269 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
270 { 270 {
271 return p->se.cfs_rq; 271 return p->se.cfs_rq;
272 } 272 }
273 273
274 /* runqueue on which this entity is (to be) queued */ 274 /* runqueue on which this entity is (to be) queued */
275 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se) 275 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
276 { 276 {
277 return se->cfs_rq; 277 return se->cfs_rq;
278 } 278 }
279 279
280 /* runqueue "owned" by this group */ 280 /* runqueue "owned" by this group */
281 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp) 281 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
282 { 282 {
283 return grp->my_q; 283 return grp->my_q;
284 } 284 }
285 285
286 static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq, 286 static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq,
287 int force_update); 287 int force_update);
288 288
289 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq) 289 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
290 { 290 {
291 if (!cfs_rq->on_list) { 291 if (!cfs_rq->on_list) {
292 /* 292 /*
293 * Ensure we either appear before our parent (if already 293 * Ensure we either appear before our parent (if already
294 * enqueued) or force our parent to appear after us when it is 294 * enqueued) or force our parent to appear after us when it is
295 * enqueued. The fact that we always enqueue bottom-up 295 * enqueued. The fact that we always enqueue bottom-up
296 * reduces this to two cases. 296 * reduces this to two cases.
297 */ 297 */
298 if (cfs_rq->tg->parent && 298 if (cfs_rq->tg->parent &&
299 cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) { 299 cfs_rq->tg->parent->cfs_rq[cpu_of(rq_of(cfs_rq))]->on_list) {
300 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, 300 list_add_rcu(&cfs_rq->leaf_cfs_rq_list,
301 &rq_of(cfs_rq)->leaf_cfs_rq_list); 301 &rq_of(cfs_rq)->leaf_cfs_rq_list);
302 } else { 302 } else {
303 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list, 303 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list,
304 &rq_of(cfs_rq)->leaf_cfs_rq_list); 304 &rq_of(cfs_rq)->leaf_cfs_rq_list);
305 } 305 }
306 306
307 cfs_rq->on_list = 1; 307 cfs_rq->on_list = 1;
308 /* We should have no load, but we need to update last_decay. */ 308 /* We should have no load, but we need to update last_decay. */
309 update_cfs_rq_blocked_load(cfs_rq, 0); 309 update_cfs_rq_blocked_load(cfs_rq, 0);
310 } 310 }
311 } 311 }
312 312
313 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq) 313 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
314 { 314 {
315 if (cfs_rq->on_list) { 315 if (cfs_rq->on_list) {
316 list_del_rcu(&cfs_rq->leaf_cfs_rq_list); 316 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
317 cfs_rq->on_list = 0; 317 cfs_rq->on_list = 0;
318 } 318 }
319 } 319 }
320 320
321 /* Iterate thr' all leaf cfs_rq's on a runqueue */ 321 /* Iterate thr' all leaf cfs_rq's on a runqueue */
322 #define for_each_leaf_cfs_rq(rq, cfs_rq) \ 322 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
323 list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list) 323 list_for_each_entry_rcu(cfs_rq, &rq->leaf_cfs_rq_list, leaf_cfs_rq_list)
324 324
325 /* Do the two (enqueued) entities belong to the same group ? */ 325 /* Do the two (enqueued) entities belong to the same group ? */
326 static inline struct cfs_rq * 326 static inline struct cfs_rq *
327 is_same_group(struct sched_entity *se, struct sched_entity *pse) 327 is_same_group(struct sched_entity *se, struct sched_entity *pse)
328 { 328 {
329 if (se->cfs_rq == pse->cfs_rq) 329 if (se->cfs_rq == pse->cfs_rq)
330 return se->cfs_rq; 330 return se->cfs_rq;
331 331
332 return NULL; 332 return NULL;
333 } 333 }
334 334
335 static inline struct sched_entity *parent_entity(struct sched_entity *se) 335 static inline struct sched_entity *parent_entity(struct sched_entity *se)
336 { 336 {
337 return se->parent; 337 return se->parent;
338 } 338 }
339 339
340 static void 340 static void
341 find_matching_se(struct sched_entity **se, struct sched_entity **pse) 341 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
342 { 342 {
343 int se_depth, pse_depth; 343 int se_depth, pse_depth;
344 344
345 /* 345 /*
346 * preemption test can be made between sibling entities who are in the 346 * preemption test can be made between sibling entities who are in the
347 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of 347 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of
348 * both tasks until we find their ancestors who are siblings of common 348 * both tasks until we find their ancestors who are siblings of common
349 * parent. 349 * parent.
350 */ 350 */
351 351
352 /* First walk up until both entities are at same depth */ 352 /* First walk up until both entities are at same depth */
353 se_depth = (*se)->depth; 353 se_depth = (*se)->depth;
354 pse_depth = (*pse)->depth; 354 pse_depth = (*pse)->depth;
355 355
356 while (se_depth > pse_depth) { 356 while (se_depth > pse_depth) {
357 se_depth--; 357 se_depth--;
358 *se = parent_entity(*se); 358 *se = parent_entity(*se);
359 } 359 }
360 360
361 while (pse_depth > se_depth) { 361 while (pse_depth > se_depth) {
362 pse_depth--; 362 pse_depth--;
363 *pse = parent_entity(*pse); 363 *pse = parent_entity(*pse);
364 } 364 }
365 365
366 while (!is_same_group(*se, *pse)) { 366 while (!is_same_group(*se, *pse)) {
367 *se = parent_entity(*se); 367 *se = parent_entity(*se);
368 *pse = parent_entity(*pse); 368 *pse = parent_entity(*pse);
369 } 369 }
370 } 370 }
371 371
372 #else /* !CONFIG_FAIR_GROUP_SCHED */ 372 #else /* !CONFIG_FAIR_GROUP_SCHED */
373 373
374 static inline struct task_struct *task_of(struct sched_entity *se) 374 static inline struct task_struct *task_of(struct sched_entity *se)
375 { 375 {
376 return container_of(se, struct task_struct, se); 376 return container_of(se, struct task_struct, se);
377 } 377 }
378 378
379 static inline struct rq *rq_of(struct cfs_rq *cfs_rq) 379 static inline struct rq *rq_of(struct cfs_rq *cfs_rq)
380 { 380 {
381 return container_of(cfs_rq, struct rq, cfs); 381 return container_of(cfs_rq, struct rq, cfs);
382 } 382 }
383 383
384 #define entity_is_task(se) 1 384 #define entity_is_task(se) 1
385 385
386 #define for_each_sched_entity(se) \ 386 #define for_each_sched_entity(se) \
387 for (; se; se = NULL) 387 for (; se; se = NULL)
388 388
389 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p) 389 static inline struct cfs_rq *task_cfs_rq(struct task_struct *p)
390 { 390 {
391 return &task_rq(p)->cfs; 391 return &task_rq(p)->cfs;
392 } 392 }
393 393
394 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se) 394 static inline struct cfs_rq *cfs_rq_of(struct sched_entity *se)
395 { 395 {
396 struct task_struct *p = task_of(se); 396 struct task_struct *p = task_of(se);
397 struct rq *rq = task_rq(p); 397 struct rq *rq = task_rq(p);
398 398
399 return &rq->cfs; 399 return &rq->cfs;
400 } 400 }
401 401
402 /* runqueue "owned" by this group */ 402 /* runqueue "owned" by this group */
403 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp) 403 static inline struct cfs_rq *group_cfs_rq(struct sched_entity *grp)
404 { 404 {
405 return NULL; 405 return NULL;
406 } 406 }
407 407
408 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq) 408 static inline void list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq)
409 { 409 {
410 } 410 }
411 411
412 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq) 412 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq)
413 { 413 {
414 } 414 }
415 415
416 #define for_each_leaf_cfs_rq(rq, cfs_rq) \ 416 #define for_each_leaf_cfs_rq(rq, cfs_rq) \
417 for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL) 417 for (cfs_rq = &rq->cfs; cfs_rq; cfs_rq = NULL)
418 418
419 static inline struct sched_entity *parent_entity(struct sched_entity *se) 419 static inline struct sched_entity *parent_entity(struct sched_entity *se)
420 { 420 {
421 return NULL; 421 return NULL;
422 } 422 }
423 423
424 static inline void 424 static inline void
425 find_matching_se(struct sched_entity **se, struct sched_entity **pse) 425 find_matching_se(struct sched_entity **se, struct sched_entity **pse)
426 { 426 {
427 } 427 }
428 428
429 #endif /* CONFIG_FAIR_GROUP_SCHED */ 429 #endif /* CONFIG_FAIR_GROUP_SCHED */
430 430
431 static __always_inline 431 static __always_inline
432 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec); 432 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec);
433 433
434 /************************************************************** 434 /**************************************************************
435 * Scheduling class tree data structure manipulation methods: 435 * Scheduling class tree data structure manipulation methods:
436 */ 436 */
437 437
438 static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime) 438 static inline u64 max_vruntime(u64 max_vruntime, u64 vruntime)
439 { 439 {
440 s64 delta = (s64)(vruntime - max_vruntime); 440 s64 delta = (s64)(vruntime - max_vruntime);
441 if (delta > 0) 441 if (delta > 0)
442 max_vruntime = vruntime; 442 max_vruntime = vruntime;
443 443
444 return max_vruntime; 444 return max_vruntime;
445 } 445 }
446 446
447 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime) 447 static inline u64 min_vruntime(u64 min_vruntime, u64 vruntime)
448 { 448 {
449 s64 delta = (s64)(vruntime - min_vruntime); 449 s64 delta = (s64)(vruntime - min_vruntime);
450 if (delta < 0) 450 if (delta < 0)
451 min_vruntime = vruntime; 451 min_vruntime = vruntime;
452 452
453 return min_vruntime; 453 return min_vruntime;
454 } 454 }
455 455
456 static inline int entity_before(struct sched_entity *a, 456 static inline int entity_before(struct sched_entity *a,
457 struct sched_entity *b) 457 struct sched_entity *b)
458 { 458 {
459 return (s64)(a->vruntime - b->vruntime) < 0; 459 return (s64)(a->vruntime - b->vruntime) < 0;
460 } 460 }
461 461
462 static void update_min_vruntime(struct cfs_rq *cfs_rq) 462 static void update_min_vruntime(struct cfs_rq *cfs_rq)
463 { 463 {
464 u64 vruntime = cfs_rq->min_vruntime; 464 u64 vruntime = cfs_rq->min_vruntime;
465 465
466 if (cfs_rq->curr) 466 if (cfs_rq->curr)
467 vruntime = cfs_rq->curr->vruntime; 467 vruntime = cfs_rq->curr->vruntime;
468 468
469 if (cfs_rq->rb_leftmost) { 469 if (cfs_rq->rb_leftmost) {
470 struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost, 470 struct sched_entity *se = rb_entry(cfs_rq->rb_leftmost,
471 struct sched_entity, 471 struct sched_entity,
472 run_node); 472 run_node);
473 473
474 if (!cfs_rq->curr) 474 if (!cfs_rq->curr)
475 vruntime = se->vruntime; 475 vruntime = se->vruntime;
476 else 476 else
477 vruntime = min_vruntime(vruntime, se->vruntime); 477 vruntime = min_vruntime(vruntime, se->vruntime);
478 } 478 }
479 479
480 /* ensure we never gain time by being placed backwards. */ 480 /* ensure we never gain time by being placed backwards. */
481 cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime); 481 cfs_rq->min_vruntime = max_vruntime(cfs_rq->min_vruntime, vruntime);
482 #ifndef CONFIG_64BIT 482 #ifndef CONFIG_64BIT
483 smp_wmb(); 483 smp_wmb();
484 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime; 484 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
485 #endif 485 #endif
486 } 486 }
487 487
488 /* 488 /*
489 * Enqueue an entity into the rb-tree: 489 * Enqueue an entity into the rb-tree:
490 */ 490 */
491 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) 491 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
492 { 492 {
493 struct rb_node **link = &cfs_rq->tasks_timeline.rb_node; 493 struct rb_node **link = &cfs_rq->tasks_timeline.rb_node;
494 struct rb_node *parent = NULL; 494 struct rb_node *parent = NULL;
495 struct sched_entity *entry; 495 struct sched_entity *entry;
496 int leftmost = 1; 496 int leftmost = 1;
497 497
498 /* 498 /*
499 * Find the right place in the rbtree: 499 * Find the right place in the rbtree:
500 */ 500 */
501 while (*link) { 501 while (*link) {
502 parent = *link; 502 parent = *link;
503 entry = rb_entry(parent, struct sched_entity, run_node); 503 entry = rb_entry(parent, struct sched_entity, run_node);
504 /* 504 /*
505 * We dont care about collisions. Nodes with 505 * We dont care about collisions. Nodes with
506 * the same key stay together. 506 * the same key stay together.
507 */ 507 */
508 if (entity_before(se, entry)) { 508 if (entity_before(se, entry)) {
509 link = &parent->rb_left; 509 link = &parent->rb_left;
510 } else { 510 } else {
511 link = &parent->rb_right; 511 link = &parent->rb_right;
512 leftmost = 0; 512 leftmost = 0;
513 } 513 }
514 } 514 }
515 515
516 /* 516 /*
517 * Maintain a cache of leftmost tree entries (it is frequently 517 * Maintain a cache of leftmost tree entries (it is frequently
518 * used): 518 * used):
519 */ 519 */
520 if (leftmost) 520 if (leftmost)
521 cfs_rq->rb_leftmost = &se->run_node; 521 cfs_rq->rb_leftmost = &se->run_node;
522 522
523 rb_link_node(&se->run_node, parent, link); 523 rb_link_node(&se->run_node, parent, link);
524 rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline); 524 rb_insert_color(&se->run_node, &cfs_rq->tasks_timeline);
525 } 525 }
526 526
527 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) 527 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
528 { 528 {
529 if (cfs_rq->rb_leftmost == &se->run_node) { 529 if (cfs_rq->rb_leftmost == &se->run_node) {
530 struct rb_node *next_node; 530 struct rb_node *next_node;
531 531
532 next_node = rb_next(&se->run_node); 532 next_node = rb_next(&se->run_node);
533 cfs_rq->rb_leftmost = next_node; 533 cfs_rq->rb_leftmost = next_node;
534 } 534 }
535 535
536 rb_erase(&se->run_node, &cfs_rq->tasks_timeline); 536 rb_erase(&se->run_node, &cfs_rq->tasks_timeline);
537 } 537 }
538 538
539 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq) 539 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq)
540 { 540 {
541 struct rb_node *left = cfs_rq->rb_leftmost; 541 struct rb_node *left = cfs_rq->rb_leftmost;
542 542
543 if (!left) 543 if (!left)
544 return NULL; 544 return NULL;
545 545
546 return rb_entry(left, struct sched_entity, run_node); 546 return rb_entry(left, struct sched_entity, run_node);
547 } 547 }
548 548
549 static struct sched_entity *__pick_next_entity(struct sched_entity *se) 549 static struct sched_entity *__pick_next_entity(struct sched_entity *se)
550 { 550 {
551 struct rb_node *next = rb_next(&se->run_node); 551 struct rb_node *next = rb_next(&se->run_node);
552 552
553 if (!next) 553 if (!next)
554 return NULL; 554 return NULL;
555 555
556 return rb_entry(next, struct sched_entity, run_node); 556 return rb_entry(next, struct sched_entity, run_node);
557 } 557 }
558 558
559 #ifdef CONFIG_SCHED_DEBUG 559 #ifdef CONFIG_SCHED_DEBUG
560 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq) 560 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq)
561 { 561 {
562 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline); 562 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline);
563 563
564 if (!last) 564 if (!last)
565 return NULL; 565 return NULL;
566 566
567 return rb_entry(last, struct sched_entity, run_node); 567 return rb_entry(last, struct sched_entity, run_node);
568 } 568 }
569 569
570 /************************************************************** 570 /**************************************************************
571 * Scheduling class statistics methods: 571 * Scheduling class statistics methods:
572 */ 572 */
573 573
574 int sched_proc_update_handler(struct ctl_table *table, int write, 574 int sched_proc_update_handler(struct ctl_table *table, int write,
575 void __user *buffer, size_t *lenp, 575 void __user *buffer, size_t *lenp,
576 loff_t *ppos) 576 loff_t *ppos)
577 { 577 {
578 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); 578 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
579 int factor = get_update_sysctl_factor(); 579 int factor = get_update_sysctl_factor();
580 580
581 if (ret || !write) 581 if (ret || !write)
582 return ret; 582 return ret;
583 583
584 sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency, 584 sched_nr_latency = DIV_ROUND_UP(sysctl_sched_latency,
585 sysctl_sched_min_granularity); 585 sysctl_sched_min_granularity);
586 586
587 #define WRT_SYSCTL(name) \ 587 #define WRT_SYSCTL(name) \
588 (normalized_sysctl_##name = sysctl_##name / (factor)) 588 (normalized_sysctl_##name = sysctl_##name / (factor))
589 WRT_SYSCTL(sched_min_granularity); 589 WRT_SYSCTL(sched_min_granularity);
590 WRT_SYSCTL(sched_latency); 590 WRT_SYSCTL(sched_latency);
591 WRT_SYSCTL(sched_wakeup_granularity); 591 WRT_SYSCTL(sched_wakeup_granularity);
592 #undef WRT_SYSCTL 592 #undef WRT_SYSCTL
593 593
594 return 0; 594 return 0;
595 } 595 }
596 #endif 596 #endif
597 597
598 /* 598 /*
599 * delta /= w 599 * delta /= w
600 */ 600 */
601 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se) 601 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se)
602 { 602 {
603 if (unlikely(se->load.weight != NICE_0_LOAD)) 603 if (unlikely(se->load.weight != NICE_0_LOAD))
604 delta = __calc_delta(delta, NICE_0_LOAD, &se->load); 604 delta = __calc_delta(delta, NICE_0_LOAD, &se->load);
605 605
606 return delta; 606 return delta;
607 } 607 }
608 608
609 /* 609 /*
610 * The idea is to set a period in which each task runs once. 610 * The idea is to set a period in which each task runs once.
611 * 611 *
612 * When there are too many tasks (sched_nr_latency) we have to stretch 612 * When there are too many tasks (sched_nr_latency) we have to stretch
613 * this period because otherwise the slices get too small. 613 * this period because otherwise the slices get too small.
614 * 614 *
615 * p = (nr <= nl) ? l : l*nr/nl 615 * p = (nr <= nl) ? l : l*nr/nl
616 */ 616 */
617 static u64 __sched_period(unsigned long nr_running) 617 static u64 __sched_period(unsigned long nr_running)
618 { 618 {
619 u64 period = sysctl_sched_latency; 619 u64 period = sysctl_sched_latency;
620 unsigned long nr_latency = sched_nr_latency; 620 unsigned long nr_latency = sched_nr_latency;
621 621
622 if (unlikely(nr_running > nr_latency)) { 622 if (unlikely(nr_running > nr_latency)) {
623 period = sysctl_sched_min_granularity; 623 period = sysctl_sched_min_granularity;
624 period *= nr_running; 624 period *= nr_running;
625 } 625 }
626 626
627 return period; 627 return period;
628 } 628 }
629 629
630 /* 630 /*
631 * We calculate the wall-time slice from the period by taking a part 631 * We calculate the wall-time slice from the period by taking a part
632 * proportional to the weight. 632 * proportional to the weight.
633 * 633 *
634 * s = p*P[w/rw] 634 * s = p*P[w/rw]
635 */ 635 */
636 static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se) 636 static u64 sched_slice(struct cfs_rq *cfs_rq, struct sched_entity *se)
637 { 637 {
638 u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq); 638 u64 slice = __sched_period(cfs_rq->nr_running + !se->on_rq);
639 639
640 for_each_sched_entity(se) { 640 for_each_sched_entity(se) {
641 struct load_weight *load; 641 struct load_weight *load;
642 struct load_weight lw; 642 struct load_weight lw;
643 643
644 cfs_rq = cfs_rq_of(se); 644 cfs_rq = cfs_rq_of(se);
645 load = &cfs_rq->load; 645 load = &cfs_rq->load;
646 646
647 if (unlikely(!se->on_rq)) { 647 if (unlikely(!se->on_rq)) {
648 lw = cfs_rq->load; 648 lw = cfs_rq->load;
649 649
650 update_load_add(&lw, se->load.weight); 650 update_load_add(&lw, se->load.weight);
651 load = &lw; 651 load = &lw;
652 } 652 }
653 slice = __calc_delta(slice, se->load.weight, load); 653 slice = __calc_delta(slice, se->load.weight, load);
654 } 654 }
655 return slice; 655 return slice;
656 } 656 }
657 657
658 /* 658 /*
659 * We calculate the vruntime slice of a to-be-inserted task. 659 * We calculate the vruntime slice of a to-be-inserted task.
660 * 660 *
661 * vs = s/w 661 * vs = s/w
662 */ 662 */
663 static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se) 663 static u64 sched_vslice(struct cfs_rq *cfs_rq, struct sched_entity *se)
664 { 664 {
665 return calc_delta_fair(sched_slice(cfs_rq, se), se); 665 return calc_delta_fair(sched_slice(cfs_rq, se), se);
666 } 666 }
667 667
668 #ifdef CONFIG_SMP 668 #ifdef CONFIG_SMP
669 static int select_idle_sibling(struct task_struct *p, int cpu); 669 static int select_idle_sibling(struct task_struct *p, int cpu);
670 static unsigned long task_h_load(struct task_struct *p); 670 static unsigned long task_h_load(struct task_struct *p);
671 671
672 static inline void __update_task_entity_contrib(struct sched_entity *se); 672 static inline void __update_task_entity_contrib(struct sched_entity *se);
673 673
674 /* Give new task start runnable values to heavy its load in infant time */ 674 /* Give new task start runnable values to heavy its load in infant time */
675 void init_task_runnable_average(struct task_struct *p) 675 void init_task_runnable_average(struct task_struct *p)
676 { 676 {
677 u32 slice; 677 u32 slice;
678 678
679 p->se.avg.decay_count = 0; 679 p->se.avg.decay_count = 0;
680 slice = sched_slice(task_cfs_rq(p), &p->se) >> 10; 680 slice = sched_slice(task_cfs_rq(p), &p->se) >> 10;
681 p->se.avg.runnable_avg_sum = slice; 681 p->se.avg.runnable_avg_sum = slice;
682 p->se.avg.runnable_avg_period = slice; 682 p->se.avg.runnable_avg_period = slice;
683 __update_task_entity_contrib(&p->se); 683 __update_task_entity_contrib(&p->se);
684 } 684 }
685 #else 685 #else
686 void init_task_runnable_average(struct task_struct *p) 686 void init_task_runnable_average(struct task_struct *p)
687 { 687 {
688 } 688 }
689 #endif 689 #endif
690 690
691 /* 691 /*
692 * Update the current task's runtime statistics. 692 * Update the current task's runtime statistics.
693 */ 693 */
694 static void update_curr(struct cfs_rq *cfs_rq) 694 static void update_curr(struct cfs_rq *cfs_rq)
695 { 695 {
696 struct sched_entity *curr = cfs_rq->curr; 696 struct sched_entity *curr = cfs_rq->curr;
697 u64 now = rq_clock_task(rq_of(cfs_rq)); 697 u64 now = rq_clock_task(rq_of(cfs_rq));
698 u64 delta_exec; 698 u64 delta_exec;
699 699
700 if (unlikely(!curr)) 700 if (unlikely(!curr))
701 return; 701 return;
702 702
703 delta_exec = now - curr->exec_start; 703 delta_exec = now - curr->exec_start;
704 if (unlikely((s64)delta_exec <= 0)) 704 if (unlikely((s64)delta_exec <= 0))
705 return; 705 return;
706 706
707 curr->exec_start = now; 707 curr->exec_start = now;
708 708
709 schedstat_set(curr->statistics.exec_max, 709 schedstat_set(curr->statistics.exec_max,
710 max(delta_exec, curr->statistics.exec_max)); 710 max(delta_exec, curr->statistics.exec_max));
711 711
712 curr->sum_exec_runtime += delta_exec; 712 curr->sum_exec_runtime += delta_exec;
713 schedstat_add(cfs_rq, exec_clock, delta_exec); 713 schedstat_add(cfs_rq, exec_clock, delta_exec);
714 714
715 curr->vruntime += calc_delta_fair(delta_exec, curr); 715 curr->vruntime += calc_delta_fair(delta_exec, curr);
716 update_min_vruntime(cfs_rq); 716 update_min_vruntime(cfs_rq);
717 717
718 if (entity_is_task(curr)) { 718 if (entity_is_task(curr)) {
719 struct task_struct *curtask = task_of(curr); 719 struct task_struct *curtask = task_of(curr);
720 720
721 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime); 721 trace_sched_stat_runtime(curtask, delta_exec, curr->vruntime);
722 cpuacct_charge(curtask, delta_exec); 722 cpuacct_charge(curtask, delta_exec);
723 account_group_exec_runtime(curtask, delta_exec); 723 account_group_exec_runtime(curtask, delta_exec);
724 } 724 }
725 725
726 account_cfs_rq_runtime(cfs_rq, delta_exec); 726 account_cfs_rq_runtime(cfs_rq, delta_exec);
727 } 727 }
728 728
729 static void update_curr_fair(struct rq *rq) 729 static void update_curr_fair(struct rq *rq)
730 { 730 {
731 update_curr(cfs_rq_of(&rq->curr->se)); 731 update_curr(cfs_rq_of(&rq->curr->se));
732 } 732 }
733 733
734 static inline void 734 static inline void
735 update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se) 735 update_stats_wait_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
736 { 736 {
737 schedstat_set(se->statistics.wait_start, rq_clock(rq_of(cfs_rq))); 737 schedstat_set(se->statistics.wait_start, rq_clock(rq_of(cfs_rq)));
738 } 738 }
739 739
740 /* 740 /*
741 * Task is being enqueued - update stats: 741 * Task is being enqueued - update stats:
742 */ 742 */
743 static void update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se) 743 static void update_stats_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
744 { 744 {
745 /* 745 /*
746 * Are we enqueueing a waiting task? (for current tasks 746 * Are we enqueueing a waiting task? (for current tasks
747 * a dequeue/enqueue event is a NOP) 747 * a dequeue/enqueue event is a NOP)
748 */ 748 */
749 if (se != cfs_rq->curr) 749 if (se != cfs_rq->curr)
750 update_stats_wait_start(cfs_rq, se); 750 update_stats_wait_start(cfs_rq, se);
751 } 751 }
752 752
753 static void 753 static void
754 update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se) 754 update_stats_wait_end(struct cfs_rq *cfs_rq, struct sched_entity *se)
755 { 755 {
756 schedstat_set(se->statistics.wait_max, max(se->statistics.wait_max, 756 schedstat_set(se->statistics.wait_max, max(se->statistics.wait_max,
757 rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start)); 757 rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start));
758 schedstat_set(se->statistics.wait_count, se->statistics.wait_count + 1); 758 schedstat_set(se->statistics.wait_count, se->statistics.wait_count + 1);
759 schedstat_set(se->statistics.wait_sum, se->statistics.wait_sum + 759 schedstat_set(se->statistics.wait_sum, se->statistics.wait_sum +
760 rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start); 760 rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start);
761 #ifdef CONFIG_SCHEDSTATS 761 #ifdef CONFIG_SCHEDSTATS
762 if (entity_is_task(se)) { 762 if (entity_is_task(se)) {
763 trace_sched_stat_wait(task_of(se), 763 trace_sched_stat_wait(task_of(se),
764 rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start); 764 rq_clock(rq_of(cfs_rq)) - se->statistics.wait_start);
765 } 765 }
766 #endif 766 #endif
767 schedstat_set(se->statistics.wait_start, 0); 767 schedstat_set(se->statistics.wait_start, 0);
768 } 768 }
769 769
770 static inline void 770 static inline void
771 update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se) 771 update_stats_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
772 { 772 {
773 /* 773 /*
774 * Mark the end of the wait period if dequeueing a 774 * Mark the end of the wait period if dequeueing a
775 * waiting task: 775 * waiting task:
776 */ 776 */
777 if (se != cfs_rq->curr) 777 if (se != cfs_rq->curr)
778 update_stats_wait_end(cfs_rq, se); 778 update_stats_wait_end(cfs_rq, se);
779 } 779 }
780 780
781 /* 781 /*
782 * We are picking a new current task - update its stats: 782 * We are picking a new current task - update its stats:
783 */ 783 */
784 static inline void 784 static inline void
785 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se) 785 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se)
786 { 786 {
787 /* 787 /*
788 * We are starting a new run period: 788 * We are starting a new run period:
789 */ 789 */
790 se->exec_start = rq_clock_task(rq_of(cfs_rq)); 790 se->exec_start = rq_clock_task(rq_of(cfs_rq));
791 } 791 }
792 792
793 /************************************************** 793 /**************************************************
794 * Scheduling class queueing methods: 794 * Scheduling class queueing methods:
795 */ 795 */
796 796
797 #ifdef CONFIG_NUMA_BALANCING 797 #ifdef CONFIG_NUMA_BALANCING
798 /* 798 /*
799 * Approximate time to scan a full NUMA task in ms. The task scan period is 799 * Approximate time to scan a full NUMA task in ms. The task scan period is
800 * calculated based on the tasks virtual memory size and 800 * calculated based on the tasks virtual memory size and
801 * numa_balancing_scan_size. 801 * numa_balancing_scan_size.
802 */ 802 */
803 unsigned int sysctl_numa_balancing_scan_period_min = 1000; 803 unsigned int sysctl_numa_balancing_scan_period_min = 1000;
804 unsigned int sysctl_numa_balancing_scan_period_max = 60000; 804 unsigned int sysctl_numa_balancing_scan_period_max = 60000;
805 805
806 /* Portion of address space to scan in MB */ 806 /* Portion of address space to scan in MB */
807 unsigned int sysctl_numa_balancing_scan_size = 256; 807 unsigned int sysctl_numa_balancing_scan_size = 256;
808 808
809 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */ 809 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */
810 unsigned int sysctl_numa_balancing_scan_delay = 1000; 810 unsigned int sysctl_numa_balancing_scan_delay = 1000;
811 811
812 static unsigned int task_nr_scan_windows(struct task_struct *p) 812 static unsigned int task_nr_scan_windows(struct task_struct *p)
813 { 813 {
814 unsigned long rss = 0; 814 unsigned long rss = 0;
815 unsigned long nr_scan_pages; 815 unsigned long nr_scan_pages;
816 816
817 /* 817 /*
818 * Calculations based on RSS as non-present and empty pages are skipped 818 * Calculations based on RSS as non-present and empty pages are skipped
819 * by the PTE scanner and NUMA hinting faults should be trapped based 819 * by the PTE scanner and NUMA hinting faults should be trapped based
820 * on resident pages 820 * on resident pages
821 */ 821 */
822 nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT); 822 nr_scan_pages = sysctl_numa_balancing_scan_size << (20 - PAGE_SHIFT);
823 rss = get_mm_rss(p->mm); 823 rss = get_mm_rss(p->mm);
824 if (!rss) 824 if (!rss)
825 rss = nr_scan_pages; 825 rss = nr_scan_pages;
826 826
827 rss = round_up(rss, nr_scan_pages); 827 rss = round_up(rss, nr_scan_pages);
828 return rss / nr_scan_pages; 828 return rss / nr_scan_pages;
829 } 829 }
830 830
831 /* For sanitys sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */ 831 /* For sanitys sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */
832 #define MAX_SCAN_WINDOW 2560 832 #define MAX_SCAN_WINDOW 2560
833 833
834 static unsigned int task_scan_min(struct task_struct *p) 834 static unsigned int task_scan_min(struct task_struct *p)
835 { 835 {
836 unsigned int scan_size = ACCESS_ONCE(sysctl_numa_balancing_scan_size); 836 unsigned int scan_size = ACCESS_ONCE(sysctl_numa_balancing_scan_size);
837 unsigned int scan, floor; 837 unsigned int scan, floor;
838 unsigned int windows = 1; 838 unsigned int windows = 1;
839 839
840 if (scan_size < MAX_SCAN_WINDOW) 840 if (scan_size < MAX_SCAN_WINDOW)
841 windows = MAX_SCAN_WINDOW / scan_size; 841 windows = MAX_SCAN_WINDOW / scan_size;
842 floor = 1000 / windows; 842 floor = 1000 / windows;
843 843
844 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p); 844 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p);
845 return max_t(unsigned int, floor, scan); 845 return max_t(unsigned int, floor, scan);
846 } 846 }
847 847
848 static unsigned int task_scan_max(struct task_struct *p) 848 static unsigned int task_scan_max(struct task_struct *p)
849 { 849 {
850 unsigned int smin = task_scan_min(p); 850 unsigned int smin = task_scan_min(p);
851 unsigned int smax; 851 unsigned int smax;
852 852
853 /* Watch for min being lower than max due to floor calculations */ 853 /* Watch for min being lower than max due to floor calculations */
854 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p); 854 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p);
855 return max(smin, smax); 855 return max(smin, smax);
856 } 856 }
857 857
858 static void account_numa_enqueue(struct rq *rq, struct task_struct *p) 858 static void account_numa_enqueue(struct rq *rq, struct task_struct *p)
859 { 859 {
860 rq->nr_numa_running += (p->numa_preferred_nid != -1); 860 rq->nr_numa_running += (p->numa_preferred_nid != -1);
861 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p)); 861 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p));
862 } 862 }
863 863
864 static void account_numa_dequeue(struct rq *rq, struct task_struct *p) 864 static void account_numa_dequeue(struct rq *rq, struct task_struct *p)
865 { 865 {
866 rq->nr_numa_running -= (p->numa_preferred_nid != -1); 866 rq->nr_numa_running -= (p->numa_preferred_nid != -1);
867 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p)); 867 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p));
868 } 868 }
869 869
870 struct numa_group { 870 struct numa_group {
871 atomic_t refcount; 871 atomic_t refcount;
872 872
873 spinlock_t lock; /* nr_tasks, tasks */ 873 spinlock_t lock; /* nr_tasks, tasks */
874 int nr_tasks; 874 int nr_tasks;
875 pid_t gid; 875 pid_t gid;
876 876
877 struct rcu_head rcu; 877 struct rcu_head rcu;
878 nodemask_t active_nodes; 878 nodemask_t active_nodes;
879 unsigned long total_faults; 879 unsigned long total_faults;
880 /* 880 /*
881 * Faults_cpu is used to decide whether memory should move 881 * Faults_cpu is used to decide whether memory should move
882 * towards the CPU. As a consequence, these stats are weighted 882 * towards the CPU. As a consequence, these stats are weighted
883 * more by CPU use than by memory faults. 883 * more by CPU use than by memory faults.
884 */ 884 */
885 unsigned long *faults_cpu; 885 unsigned long *faults_cpu;
886 unsigned long faults[0]; 886 unsigned long faults[0];
887 }; 887 };
888 888
889 /* Shared or private faults. */ 889 /* Shared or private faults. */
890 #define NR_NUMA_HINT_FAULT_TYPES 2 890 #define NR_NUMA_HINT_FAULT_TYPES 2
891 891
892 /* Memory and CPU locality */ 892 /* Memory and CPU locality */
893 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2) 893 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2)
894 894
895 /* Averaged statistics, and temporary buffers. */ 895 /* Averaged statistics, and temporary buffers. */
896 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2) 896 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2)
897 897
898 pid_t task_numa_group_id(struct task_struct *p) 898 pid_t task_numa_group_id(struct task_struct *p)
899 { 899 {
900 return p->numa_group ? p->numa_group->gid : 0; 900 return p->numa_group ? p->numa_group->gid : 0;
901 } 901 }
902 902
903 /* 903 /*
904 * The averaged statistics, shared & private, memory & cpu, 904 * The averaged statistics, shared & private, memory & cpu,
905 * occupy the first half of the array. The second half of the 905 * occupy the first half of the array. The second half of the
906 * array is for current counters, which are averaged into the 906 * array is for current counters, which are averaged into the
907 * first set by task_numa_placement. 907 * first set by task_numa_placement.
908 */ 908 */
909 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv) 909 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv)
910 { 910 {
911 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv; 911 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv;
912 } 912 }
913 913
914 static inline unsigned long task_faults(struct task_struct *p, int nid) 914 static inline unsigned long task_faults(struct task_struct *p, int nid)
915 { 915 {
916 if (!p->numa_faults) 916 if (!p->numa_faults)
917 return 0; 917 return 0;
918 918
919 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] + 919 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] +
920 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)]; 920 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)];
921 } 921 }
922 922
923 static inline unsigned long group_faults(struct task_struct *p, int nid) 923 static inline unsigned long group_faults(struct task_struct *p, int nid)
924 { 924 {
925 if (!p->numa_group) 925 if (!p->numa_group)
926 return 0; 926 return 0;
927 927
928 return p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 0)] + 928 return p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 0)] +
929 p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 1)]; 929 p->numa_group->faults[task_faults_idx(NUMA_MEM, nid, 1)];
930 } 930 }
931 931
932 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid) 932 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid)
933 { 933 {
934 return group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 0)] + 934 return group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 0)] +
935 group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 1)]; 935 group->faults_cpu[task_faults_idx(NUMA_MEM, nid, 1)];
936 } 936 }
937 937
938 /* Handle placement on systems where not all nodes are directly connected. */ 938 /* Handle placement on systems where not all nodes are directly connected. */
939 static unsigned long score_nearby_nodes(struct task_struct *p, int nid, 939 static unsigned long score_nearby_nodes(struct task_struct *p, int nid,
940 int maxdist, bool task) 940 int maxdist, bool task)
941 { 941 {
942 unsigned long score = 0; 942 unsigned long score = 0;
943 int node; 943 int node;
944 944
945 /* 945 /*
946 * All nodes are directly connected, and the same distance 946 * All nodes are directly connected, and the same distance
947 * from each other. No need for fancy placement algorithms. 947 * from each other. No need for fancy placement algorithms.
948 */ 948 */
949 if (sched_numa_topology_type == NUMA_DIRECT) 949 if (sched_numa_topology_type == NUMA_DIRECT)
950 return 0; 950 return 0;
951 951
952 /* 952 /*
953 * This code is called for each node, introducing N^2 complexity, 953 * This code is called for each node, introducing N^2 complexity,
954 * which should be ok given the number of nodes rarely exceeds 8. 954 * which should be ok given the number of nodes rarely exceeds 8.
955 */ 955 */
956 for_each_online_node(node) { 956 for_each_online_node(node) {
957 unsigned long faults; 957 unsigned long faults;
958 int dist = node_distance(nid, node); 958 int dist = node_distance(nid, node);
959 959
960 /* 960 /*
961 * The furthest away nodes in the system are not interesting 961 * The furthest away nodes in the system are not interesting
962 * for placement; nid was already counted. 962 * for placement; nid was already counted.
963 */ 963 */
964 if (dist == sched_max_numa_distance || node == nid) 964 if (dist == sched_max_numa_distance || node == nid)
965 continue; 965 continue;
966 966
967 /* 967 /*
968 * On systems with a backplane NUMA topology, compare groups 968 * On systems with a backplane NUMA topology, compare groups
969 * of nodes, and move tasks towards the group with the most 969 * of nodes, and move tasks towards the group with the most
970 * memory accesses. When comparing two nodes at distance 970 * memory accesses. When comparing two nodes at distance
971 * "hoplimit", only nodes closer by than "hoplimit" are part 971 * "hoplimit", only nodes closer by than "hoplimit" are part
972 * of each group. Skip other nodes. 972 * of each group. Skip other nodes.
973 */ 973 */
974 if (sched_numa_topology_type == NUMA_BACKPLANE && 974 if (sched_numa_topology_type == NUMA_BACKPLANE &&
975 dist > maxdist) 975 dist > maxdist)
976 continue; 976 continue;
977 977
978 /* Add up the faults from nearby nodes. */ 978 /* Add up the faults from nearby nodes. */
979 if (task) 979 if (task)
980 faults = task_faults(p, node); 980 faults = task_faults(p, node);
981 else 981 else
982 faults = group_faults(p, node); 982 faults = group_faults(p, node);
983 983
984 /* 984 /*
985 * On systems with a glueless mesh NUMA topology, there are 985 * On systems with a glueless mesh NUMA topology, there are
986 * no fixed "groups of nodes". Instead, nodes that are not 986 * no fixed "groups of nodes". Instead, nodes that are not
987 * directly connected bounce traffic through intermediate 987 * directly connected bounce traffic through intermediate
988 * nodes; a numa_group can occupy any set of nodes. 988 * nodes; a numa_group can occupy any set of nodes.
989 * The further away a node is, the less the faults count. 989 * The further away a node is, the less the faults count.
990 * This seems to result in good task placement. 990 * This seems to result in good task placement.
991 */ 991 */
992 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) { 992 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
993 faults *= (sched_max_numa_distance - dist); 993 faults *= (sched_max_numa_distance - dist);
994 faults /= (sched_max_numa_distance - LOCAL_DISTANCE); 994 faults /= (sched_max_numa_distance - LOCAL_DISTANCE);
995 } 995 }
996 996
997 score += faults; 997 score += faults;
998 } 998 }
999 999
1000 return score; 1000 return score;
1001 } 1001 }
1002 1002
1003 /* 1003 /*
1004 * These return the fraction of accesses done by a particular task, or 1004 * These return the fraction of accesses done by a particular task, or
1005 * task group, on a particular numa node. The group weight is given a 1005 * task group, on a particular numa node. The group weight is given a
1006 * larger multiplier, in order to group tasks together that are almost 1006 * larger multiplier, in order to group tasks together that are almost
1007 * evenly spread out between numa nodes. 1007 * evenly spread out between numa nodes.
1008 */ 1008 */
1009 static inline unsigned long task_weight(struct task_struct *p, int nid, 1009 static inline unsigned long task_weight(struct task_struct *p, int nid,
1010 int dist) 1010 int dist)
1011 { 1011 {
1012 unsigned long faults, total_faults; 1012 unsigned long faults, total_faults;
1013 1013
1014 if (!p->numa_faults) 1014 if (!p->numa_faults)
1015 return 0; 1015 return 0;
1016 1016
1017 total_faults = p->total_numa_faults; 1017 total_faults = p->total_numa_faults;
1018 1018
1019 if (!total_faults) 1019 if (!total_faults)
1020 return 0; 1020 return 0;
1021 1021
1022 faults = task_faults(p, nid); 1022 faults = task_faults(p, nid);
1023 faults += score_nearby_nodes(p, nid, dist, true); 1023 faults += score_nearby_nodes(p, nid, dist, true);
1024 1024
1025 return 1000 * faults / total_faults; 1025 return 1000 * faults / total_faults;
1026 } 1026 }
1027 1027
1028 static inline unsigned long group_weight(struct task_struct *p, int nid, 1028 static inline unsigned long group_weight(struct task_struct *p, int nid,
1029 int dist) 1029 int dist)
1030 { 1030 {
1031 unsigned long faults, total_faults; 1031 unsigned long faults, total_faults;
1032 1032
1033 if (!p->numa_group) 1033 if (!p->numa_group)
1034 return 0; 1034 return 0;
1035 1035
1036 total_faults = p->numa_group->total_faults; 1036 total_faults = p->numa_group->total_faults;
1037 1037
1038 if (!total_faults) 1038 if (!total_faults)
1039 return 0; 1039 return 0;
1040 1040
1041 faults = group_faults(p, nid); 1041 faults = group_faults(p, nid);
1042 faults += score_nearby_nodes(p, nid, dist, false); 1042 faults += score_nearby_nodes(p, nid, dist, false);
1043 1043
1044 return 1000 * faults / total_faults; 1044 return 1000 * faults / total_faults;
1045 } 1045 }
1046 1046
1047 bool should_numa_migrate_memory(struct task_struct *p, struct page * page, 1047 bool should_numa_migrate_memory(struct task_struct *p, struct page * page,
1048 int src_nid, int dst_cpu) 1048 int src_nid, int dst_cpu)
1049 { 1049 {
1050 struct numa_group *ng = p->numa_group; 1050 struct numa_group *ng = p->numa_group;
1051 int dst_nid = cpu_to_node(dst_cpu); 1051 int dst_nid = cpu_to_node(dst_cpu);
1052 int last_cpupid, this_cpupid; 1052 int last_cpupid, this_cpupid;
1053 1053
1054 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid); 1054 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid);
1055 1055
1056 /* 1056 /*
1057 * Multi-stage node selection is used in conjunction with a periodic 1057 * Multi-stage node selection is used in conjunction with a periodic
1058 * migration fault to build a temporal task<->page relation. By using 1058 * migration fault to build a temporal task<->page relation. By using
1059 * a two-stage filter we remove short/unlikely relations. 1059 * a two-stage filter we remove short/unlikely relations.
1060 * 1060 *
1061 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate 1061 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate
1062 * a task's usage of a particular page (n_p) per total usage of this 1062 * a task's usage of a particular page (n_p) per total usage of this
1063 * page (n_t) (in a given time-span) to a probability. 1063 * page (n_t) (in a given time-span) to a probability.
1064 * 1064 *
1065 * Our periodic faults will sample this probability and getting the 1065 * Our periodic faults will sample this probability and getting the
1066 * same result twice in a row, given these samples are fully 1066 * same result twice in a row, given these samples are fully
1067 * independent, is then given by P(n)^2, provided our sample period 1067 * independent, is then given by P(n)^2, provided our sample period
1068 * is sufficiently short compared to the usage pattern. 1068 * is sufficiently short compared to the usage pattern.
1069 * 1069 *
1070 * This quadric squishes small probabilities, making it less likely we 1070 * This quadric squishes small probabilities, making it less likely we
1071 * act on an unlikely task<->page relation. 1071 * act on an unlikely task<->page relation.
1072 */ 1072 */
1073 last_cpupid = page_cpupid_xchg_last(page, this_cpupid); 1073 last_cpupid = page_cpupid_xchg_last(page, this_cpupid);
1074 if (!cpupid_pid_unset(last_cpupid) && 1074 if (!cpupid_pid_unset(last_cpupid) &&
1075 cpupid_to_nid(last_cpupid) != dst_nid) 1075 cpupid_to_nid(last_cpupid) != dst_nid)
1076 return false; 1076 return false;
1077 1077
1078 /* Always allow migrate on private faults */ 1078 /* Always allow migrate on private faults */
1079 if (cpupid_match_pid(p, last_cpupid)) 1079 if (cpupid_match_pid(p, last_cpupid))
1080 return true; 1080 return true;
1081 1081
1082 /* A shared fault, but p->numa_group has not been set up yet. */ 1082 /* A shared fault, but p->numa_group has not been set up yet. */
1083 if (!ng) 1083 if (!ng)
1084 return true; 1084 return true;
1085 1085
1086 /* 1086 /*
1087 * Do not migrate if the destination is not a node that 1087 * Do not migrate if the destination is not a node that
1088 * is actively used by this numa group. 1088 * is actively used by this numa group.
1089 */ 1089 */
1090 if (!node_isset(dst_nid, ng->active_nodes)) 1090 if (!node_isset(dst_nid, ng->active_nodes))
1091 return false; 1091 return false;
1092 1092
1093 /* 1093 /*
1094 * Source is a node that is not actively used by this 1094 * Source is a node that is not actively used by this
1095 * numa group, while the destination is. Migrate. 1095 * numa group, while the destination is. Migrate.
1096 */ 1096 */
1097 if (!node_isset(src_nid, ng->active_nodes)) 1097 if (!node_isset(src_nid, ng->active_nodes))
1098 return true; 1098 return true;
1099 1099
1100 /* 1100 /*
1101 * Both source and destination are nodes in active 1101 * Both source and destination are nodes in active
1102 * use by this numa group. Maximize memory bandwidth 1102 * use by this numa group. Maximize memory bandwidth
1103 * by migrating from more heavily used groups, to less 1103 * by migrating from more heavily used groups, to less
1104 * heavily used ones, spreading the load around. 1104 * heavily used ones, spreading the load around.
1105 * Use a 1/4 hysteresis to avoid spurious page movement. 1105 * Use a 1/4 hysteresis to avoid spurious page movement.
1106 */ 1106 */
1107 return group_faults(p, dst_nid) < (group_faults(p, src_nid) * 3 / 4); 1107 return group_faults(p, dst_nid) < (group_faults(p, src_nid) * 3 / 4);
1108 } 1108 }
1109 1109
1110 static unsigned long weighted_cpuload(const int cpu); 1110 static unsigned long weighted_cpuload(const int cpu);
1111 static unsigned long source_load(int cpu, int type); 1111 static unsigned long source_load(int cpu, int type);
1112 static unsigned long target_load(int cpu, int type); 1112 static unsigned long target_load(int cpu, int type);
1113 static unsigned long capacity_of(int cpu); 1113 static unsigned long capacity_of(int cpu);
1114 static long effective_load(struct task_group *tg, int cpu, long wl, long wg); 1114 static long effective_load(struct task_group *tg, int cpu, long wl, long wg);
1115 1115
1116 /* Cached statistics for all CPUs within a node */ 1116 /* Cached statistics for all CPUs within a node */
1117 struct numa_stats { 1117 struct numa_stats {
1118 unsigned long nr_running; 1118 unsigned long nr_running;
1119 unsigned long load; 1119 unsigned long load;
1120 1120
1121 /* Total compute capacity of CPUs on a node */ 1121 /* Total compute capacity of CPUs on a node */
1122 unsigned long compute_capacity; 1122 unsigned long compute_capacity;
1123 1123
1124 /* Approximate capacity in terms of runnable tasks on a node */ 1124 /* Approximate capacity in terms of runnable tasks on a node */
1125 unsigned long task_capacity; 1125 unsigned long task_capacity;
1126 int has_free_capacity; 1126 int has_free_capacity;
1127 }; 1127 };
1128 1128
1129 /* 1129 /*
1130 * XXX borrowed from update_sg_lb_stats 1130 * XXX borrowed from update_sg_lb_stats
1131 */ 1131 */
1132 static void update_numa_stats(struct numa_stats *ns, int nid) 1132 static void update_numa_stats(struct numa_stats *ns, int nid)
1133 { 1133 {
1134 int smt, cpu, cpus = 0; 1134 int smt, cpu, cpus = 0;
1135 unsigned long capacity; 1135 unsigned long capacity;
1136 1136
1137 memset(ns, 0, sizeof(*ns)); 1137 memset(ns, 0, sizeof(*ns));
1138 for_each_cpu(cpu, cpumask_of_node(nid)) { 1138 for_each_cpu(cpu, cpumask_of_node(nid)) {
1139 struct rq *rq = cpu_rq(cpu); 1139 struct rq *rq = cpu_rq(cpu);
1140 1140
1141 ns->nr_running += rq->nr_running; 1141 ns->nr_running += rq->nr_running;
1142 ns->load += weighted_cpuload(cpu); 1142 ns->load += weighted_cpuload(cpu);
1143 ns->compute_capacity += capacity_of(cpu); 1143 ns->compute_capacity += capacity_of(cpu);
1144 1144
1145 cpus++; 1145 cpus++;
1146 } 1146 }
1147 1147
1148 /* 1148 /*
1149 * If we raced with hotplug and there are no CPUs left in our mask 1149 * If we raced with hotplug and there are no CPUs left in our mask
1150 * the @ns structure is NULL'ed and task_numa_compare() will 1150 * the @ns structure is NULL'ed and task_numa_compare() will
1151 * not find this node attractive. 1151 * not find this node attractive.
1152 * 1152 *
1153 * We'll either bail at !has_free_capacity, or we'll detect a huge 1153 * We'll either bail at !has_free_capacity, or we'll detect a huge
1154 * imbalance and bail there. 1154 * imbalance and bail there.
1155 */ 1155 */
1156 if (!cpus) 1156 if (!cpus)
1157 return; 1157 return;
1158 1158
1159 /* smt := ceil(cpus / capacity), assumes: 1 < smt_power < 2 */ 1159 /* smt := ceil(cpus / capacity), assumes: 1 < smt_power < 2 */
1160 smt = DIV_ROUND_UP(SCHED_CAPACITY_SCALE * cpus, ns->compute_capacity); 1160 smt = DIV_ROUND_UP(SCHED_CAPACITY_SCALE * cpus, ns->compute_capacity);
1161 capacity = cpus / smt; /* cores */ 1161 capacity = cpus / smt; /* cores */
1162 1162
1163 ns->task_capacity = min_t(unsigned, capacity, 1163 ns->task_capacity = min_t(unsigned, capacity,
1164 DIV_ROUND_CLOSEST(ns->compute_capacity, SCHED_CAPACITY_SCALE)); 1164 DIV_ROUND_CLOSEST(ns->compute_capacity, SCHED_CAPACITY_SCALE));
1165 ns->has_free_capacity = (ns->nr_running < ns->task_capacity); 1165 ns->has_free_capacity = (ns->nr_running < ns->task_capacity);
1166 } 1166 }
1167 1167
1168 struct task_numa_env { 1168 struct task_numa_env {
1169 struct task_struct *p; 1169 struct task_struct *p;
1170 1170
1171 int src_cpu, src_nid; 1171 int src_cpu, src_nid;
1172 int dst_cpu, dst_nid; 1172 int dst_cpu, dst_nid;
1173 1173
1174 struct numa_stats src_stats, dst_stats; 1174 struct numa_stats src_stats, dst_stats;
1175 1175
1176 int imbalance_pct; 1176 int imbalance_pct;
1177 int dist; 1177 int dist;
1178 1178
1179 struct task_struct *best_task; 1179 struct task_struct *best_task;
1180 long best_imp; 1180 long best_imp;
1181 int best_cpu; 1181 int best_cpu;
1182 }; 1182 };
1183 1183
1184 static void task_numa_assign(struct task_numa_env *env, 1184 static void task_numa_assign(struct task_numa_env *env,
1185 struct task_struct *p, long imp) 1185 struct task_struct *p, long imp)
1186 { 1186 {
1187 if (env->best_task) 1187 if (env->best_task)
1188 put_task_struct(env->best_task); 1188 put_task_struct(env->best_task);
1189 if (p) 1189 if (p)
1190 get_task_struct(p); 1190 get_task_struct(p);
1191 1191
1192 env->best_task = p; 1192 env->best_task = p;
1193 env->best_imp = imp; 1193 env->best_imp = imp;
1194 env->best_cpu = env->dst_cpu; 1194 env->best_cpu = env->dst_cpu;
1195 } 1195 }
1196 1196
1197 static bool load_too_imbalanced(long src_load, long dst_load, 1197 static bool load_too_imbalanced(long src_load, long dst_load,
1198 struct task_numa_env *env) 1198 struct task_numa_env *env)
1199 { 1199 {
1200 long imb, old_imb; 1200 long imb, old_imb;
1201 long orig_src_load, orig_dst_load; 1201 long orig_src_load, orig_dst_load;
1202 long src_capacity, dst_capacity; 1202 long src_capacity, dst_capacity;
1203 1203
1204 /* 1204 /*
1205 * The load is corrected for the CPU capacity available on each node. 1205 * The load is corrected for the CPU capacity available on each node.
1206 * 1206 *
1207 * src_load dst_load 1207 * src_load dst_load
1208 * ------------ vs --------- 1208 * ------------ vs ---------
1209 * src_capacity dst_capacity 1209 * src_capacity dst_capacity
1210 */ 1210 */
1211 src_capacity = env->src_stats.compute_capacity; 1211 src_capacity = env->src_stats.compute_capacity;
1212 dst_capacity = env->dst_stats.compute_capacity; 1212 dst_capacity = env->dst_stats.compute_capacity;
1213 1213
1214 /* We care about the slope of the imbalance, not the direction. */ 1214 /* We care about the slope of the imbalance, not the direction. */
1215 if (dst_load < src_load) 1215 if (dst_load < src_load)
1216 swap(dst_load, src_load); 1216 swap(dst_load, src_load);
1217 1217
1218 /* Is the difference below the threshold? */ 1218 /* Is the difference below the threshold? */
1219 imb = dst_load * src_capacity * 100 - 1219 imb = dst_load * src_capacity * 100 -
1220 src_load * dst_capacity * env->imbalance_pct; 1220 src_load * dst_capacity * env->imbalance_pct;
1221 if (imb <= 0) 1221 if (imb <= 0)
1222 return false; 1222 return false;
1223 1223
1224 /* 1224 /*
1225 * The imbalance is above the allowed threshold. 1225 * The imbalance is above the allowed threshold.
1226 * Compare it with the old imbalance. 1226 * Compare it with the old imbalance.
1227 */ 1227 */
1228 orig_src_load = env->src_stats.load; 1228 orig_src_load = env->src_stats.load;
1229 orig_dst_load = env->dst_stats.load; 1229 orig_dst_load = env->dst_stats.load;
1230 1230
1231 if (orig_dst_load < orig_src_load) 1231 if (orig_dst_load < orig_src_load)
1232 swap(orig_dst_load, orig_src_load); 1232 swap(orig_dst_load, orig_src_load);
1233 1233
1234 old_imb = orig_dst_load * src_capacity * 100 - 1234 old_imb = orig_dst_load * src_capacity * 100 -
1235 orig_src_load * dst_capacity * env->imbalance_pct; 1235 orig_src_load * dst_capacity * env->imbalance_pct;
1236 1236
1237 /* Would this change make things worse? */ 1237 /* Would this change make things worse? */
1238 return (imb > old_imb); 1238 return (imb > old_imb);
1239 } 1239 }
1240 1240
1241 /* 1241 /*
1242 * This checks if the overall compute and NUMA accesses of the system would 1242 * This checks if the overall compute and NUMA accesses of the system would
1243 * be improved if the source tasks was migrated to the target dst_cpu taking 1243 * be improved if the source tasks was migrated to the target dst_cpu taking
1244 * into account that it might be best if task running on the dst_cpu should 1244 * into account that it might be best if task running on the dst_cpu should
1245 * be exchanged with the source task 1245 * be exchanged with the source task
1246 */ 1246 */
1247 static void task_numa_compare(struct task_numa_env *env, 1247 static void task_numa_compare(struct task_numa_env *env,
1248 long taskimp, long groupimp) 1248 long taskimp, long groupimp)
1249 { 1249 {
1250 struct rq *src_rq = cpu_rq(env->src_cpu); 1250 struct rq *src_rq = cpu_rq(env->src_cpu);
1251 struct rq *dst_rq = cpu_rq(env->dst_cpu); 1251 struct rq *dst_rq = cpu_rq(env->dst_cpu);
1252 struct task_struct *cur; 1252 struct task_struct *cur;
1253 long src_load, dst_load; 1253 long src_load, dst_load;
1254 long load; 1254 long load;
1255 long imp = env->p->numa_group ? groupimp : taskimp; 1255 long imp = env->p->numa_group ? groupimp : taskimp;
1256 long moveimp = imp; 1256 long moveimp = imp;
1257 int dist = env->dist; 1257 int dist = env->dist;
1258 1258
1259 rcu_read_lock(); 1259 rcu_read_lock();
1260 1260
1261 raw_spin_lock_irq(&dst_rq->lock); 1261 raw_spin_lock_irq(&dst_rq->lock);
1262 cur = dst_rq->curr; 1262 cur = dst_rq->curr;
1263 /* 1263 /*
1264 * No need to move the exiting task, and this ensures that ->curr 1264 * No need to move the exiting task, and this ensures that ->curr
1265 * wasn't reaped and thus get_task_struct() in task_numa_assign() 1265 * wasn't reaped and thus get_task_struct() in task_numa_assign()
1266 * is safe under RCU read lock. 1266 * is safe under RCU read lock.
1267 * Note that rcu_read_lock() itself can't protect from the final 1267 * Note that rcu_read_lock() itself can't protect from the final
1268 * put_task_struct() after the last schedule(). 1268 * put_task_struct() after the last schedule().
1269 */ 1269 */
1270 if ((cur->flags & PF_EXITING) || is_idle_task(cur)) 1270 if ((cur->flags & PF_EXITING) || is_idle_task(cur))
1271 cur = NULL; 1271 cur = NULL;
1272 raw_spin_unlock_irq(&dst_rq->lock); 1272 raw_spin_unlock_irq(&dst_rq->lock);
1273 1273
1274 /* 1274 /*
1275 * Because we have preemption enabled we can get migrated around and 1275 * Because we have preemption enabled we can get migrated around and
1276 * end try selecting ourselves (current == env->p) as a swap candidate. 1276 * end try selecting ourselves (current == env->p) as a swap candidate.
1277 */ 1277 */
1278 if (cur == env->p) 1278 if (cur == env->p)
1279 goto unlock; 1279 goto unlock;
1280 1280
1281 /* 1281 /*
1282 * "imp" is the fault differential for the source task between the 1282 * "imp" is the fault differential for the source task between the
1283 * source and destination node. Calculate the total differential for 1283 * source and destination node. Calculate the total differential for
1284 * the source task and potential destination task. The more negative 1284 * the source task and potential destination task. The more negative
1285 * the value is, the more rmeote accesses that would be expected to 1285 * the value is, the more rmeote accesses that would be expected to
1286 * be incurred if the tasks were swapped. 1286 * be incurred if the tasks were swapped.
1287 */ 1287 */
1288 if (cur) { 1288 if (cur) {
1289 /* Skip this swap candidate if cannot move to the source cpu */ 1289 /* Skip this swap candidate if cannot move to the source cpu */
1290 if (!cpumask_test_cpu(env->src_cpu, tsk_cpus_allowed(cur))) 1290 if (!cpumask_test_cpu(env->src_cpu, tsk_cpus_allowed(cur)))
1291 goto unlock; 1291 goto unlock;
1292 1292
1293 /* 1293 /*
1294 * If dst and source tasks are in the same NUMA group, or not 1294 * If dst and source tasks are in the same NUMA group, or not
1295 * in any group then look only at task weights. 1295 * in any group then look only at task weights.
1296 */ 1296 */
1297 if (cur->numa_group == env->p->numa_group) { 1297 if (cur->numa_group == env->p->numa_group) {
1298 imp = taskimp + task_weight(cur, env->src_nid, dist) - 1298 imp = taskimp + task_weight(cur, env->src_nid, dist) -
1299 task_weight(cur, env->dst_nid, dist); 1299 task_weight(cur, env->dst_nid, dist);
1300 /* 1300 /*
1301 * Add some hysteresis to prevent swapping the 1301 * Add some hysteresis to prevent swapping the
1302 * tasks within a group over tiny differences. 1302 * tasks within a group over tiny differences.
1303 */ 1303 */
1304 if (cur->numa_group) 1304 if (cur->numa_group)
1305 imp -= imp/16; 1305 imp -= imp/16;
1306 } else { 1306 } else {
1307 /* 1307 /*
1308 * Compare the group weights. If a task is all by 1308 * Compare the group weights. If a task is all by
1309 * itself (not part of a group), use the task weight 1309 * itself (not part of a group), use the task weight
1310 * instead. 1310 * instead.
1311 */ 1311 */
1312 if (cur->numa_group) 1312 if (cur->numa_group)
1313 imp += group_weight(cur, env->src_nid, dist) - 1313 imp += group_weight(cur, env->src_nid, dist) -
1314 group_weight(cur, env->dst_nid, dist); 1314 group_weight(cur, env->dst_nid, dist);
1315 else 1315 else
1316 imp += task_weight(cur, env->src_nid, dist) - 1316 imp += task_weight(cur, env->src_nid, dist) -
1317 task_weight(cur, env->dst_nid, dist); 1317 task_weight(cur, env->dst_nid, dist);
1318 } 1318 }
1319 } 1319 }
1320 1320
1321 if (imp <= env->best_imp && moveimp <= env->best_imp) 1321 if (imp <= env->best_imp && moveimp <= env->best_imp)
1322 goto unlock; 1322 goto unlock;
1323 1323
1324 if (!cur) { 1324 if (!cur) {
1325 /* Is there capacity at our destination? */ 1325 /* Is there capacity at our destination? */
1326 if (env->src_stats.nr_running <= env->src_stats.task_capacity && 1326 if (env->src_stats.nr_running <= env->src_stats.task_capacity &&
1327 !env->dst_stats.has_free_capacity) 1327 !env->dst_stats.has_free_capacity)
1328 goto unlock; 1328 goto unlock;
1329 1329
1330 goto balance; 1330 goto balance;
1331 } 1331 }
1332 1332
1333 /* Balance doesn't matter much if we're running a task per cpu */ 1333 /* Balance doesn't matter much if we're running a task per cpu */
1334 if (imp > env->best_imp && src_rq->nr_running == 1 && 1334 if (imp > env->best_imp && src_rq->nr_running == 1 &&
1335 dst_rq->nr_running == 1) 1335 dst_rq->nr_running == 1)
1336 goto assign; 1336 goto assign;
1337 1337
1338 /* 1338 /*
1339 * In the overloaded case, try and keep the load balanced. 1339 * In the overloaded case, try and keep the load balanced.
1340 */ 1340 */
1341 balance: 1341 balance:
1342 load = task_h_load(env->p); 1342 load = task_h_load(env->p);
1343 dst_load = env->dst_stats.load + load; 1343 dst_load = env->dst_stats.load + load;
1344 src_load = env->src_stats.load - load; 1344 src_load = env->src_stats.load - load;
1345 1345
1346 if (moveimp > imp && moveimp > env->best_imp) { 1346 if (moveimp > imp && moveimp > env->best_imp) {
1347 /* 1347 /*
1348 * If the improvement from just moving env->p direction is 1348 * If the improvement from just moving env->p direction is
1349 * better than swapping tasks around, check if a move is 1349 * better than swapping tasks around, check if a move is
1350 * possible. Store a slightly smaller score than moveimp, 1350 * possible. Store a slightly smaller score than moveimp,
1351 * so an actually idle CPU will win. 1351 * so an actually idle CPU will win.
1352 */ 1352 */
1353 if (!load_too_imbalanced(src_load, dst_load, env)) { 1353 if (!load_too_imbalanced(src_load, dst_load, env)) {
1354 imp = moveimp - 1; 1354 imp = moveimp - 1;
1355 cur = NULL; 1355 cur = NULL;
1356 goto assign; 1356 goto assign;
1357 } 1357 }
1358 } 1358 }
1359 1359
1360 if (imp <= env->best_imp) 1360 if (imp <= env->best_imp)
1361 goto unlock; 1361 goto unlock;
1362 1362
1363 if (cur) { 1363 if (cur) {
1364 load = task_h_load(cur); 1364 load = task_h_load(cur);
1365 dst_load -= load; 1365 dst_load -= load;
1366 src_load += load; 1366 src_load += load;
1367 } 1367 }
1368 1368
1369 if (load_too_imbalanced(src_load, dst_load, env)) 1369 if (load_too_imbalanced(src_load, dst_load, env))
1370 goto unlock; 1370 goto unlock;
1371 1371
1372 /* 1372 /*
1373 * One idle CPU per node is evaluated for a task numa move. 1373 * One idle CPU per node is evaluated for a task numa move.
1374 * Call select_idle_sibling to maybe find a better one. 1374 * Call select_idle_sibling to maybe find a better one.
1375 */ 1375 */
1376 if (!cur) 1376 if (!cur)
1377 env->dst_cpu = select_idle_sibling(env->p, env->dst_cpu); 1377 env->dst_cpu = select_idle_sibling(env->p, env->dst_cpu);
1378 1378
1379 assign: 1379 assign:
1380 task_numa_assign(env, cur, imp); 1380 task_numa_assign(env, cur, imp);
1381 unlock: 1381 unlock:
1382 rcu_read_unlock(); 1382 rcu_read_unlock();
1383 } 1383 }
1384 1384
1385 static void task_numa_find_cpu(struct task_numa_env *env, 1385 static void task_numa_find_cpu(struct task_numa_env *env,
1386 long taskimp, long groupimp) 1386 long taskimp, long groupimp)
1387 { 1387 {
1388 int cpu; 1388 int cpu;
1389 1389
1390 for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) { 1390 for_each_cpu(cpu, cpumask_of_node(env->dst_nid)) {
1391 /* Skip this CPU if the source task cannot migrate */ 1391 /* Skip this CPU if the source task cannot migrate */
1392 if (!cpumask_test_cpu(cpu, tsk_cpus_allowed(env->p))) 1392 if (!cpumask_test_cpu(cpu, tsk_cpus_allowed(env->p)))
1393 continue; 1393 continue;
1394 1394
1395 env->dst_cpu = cpu; 1395 env->dst_cpu = cpu;
1396 task_numa_compare(env, taskimp, groupimp); 1396 task_numa_compare(env, taskimp, groupimp);
1397 } 1397 }
1398 } 1398 }
1399 1399
1400 static int task_numa_migrate(struct task_struct *p) 1400 static int task_numa_migrate(struct task_struct *p)
1401 { 1401 {
1402 struct task_numa_env env = { 1402 struct task_numa_env env = {
1403 .p = p, 1403 .p = p,
1404 1404
1405 .src_cpu = task_cpu(p), 1405 .src_cpu = task_cpu(p),
1406 .src_nid = task_node(p), 1406 .src_nid = task_node(p),
1407 1407
1408 .imbalance_pct = 112, 1408 .imbalance_pct = 112,
1409 1409
1410 .best_task = NULL, 1410 .best_task = NULL,
1411 .best_imp = 0, 1411 .best_imp = 0,
1412 .best_cpu = -1 1412 .best_cpu = -1
1413 }; 1413 };
1414 struct sched_domain *sd; 1414 struct sched_domain *sd;
1415 unsigned long taskweight, groupweight; 1415 unsigned long taskweight, groupweight;
1416 int nid, ret, dist; 1416 int nid, ret, dist;
1417 long taskimp, groupimp; 1417 long taskimp, groupimp;
1418 1418
1419 /* 1419 /*
1420 * Pick the lowest SD_NUMA domain, as that would have the smallest 1420 * Pick the lowest SD_NUMA domain, as that would have the smallest
1421 * imbalance and would be the first to start moving tasks about. 1421 * imbalance and would be the first to start moving tasks about.
1422 * 1422 *
1423 * And we want to avoid any moving of tasks about, as that would create 1423 * And we want to avoid any moving of tasks about, as that would create
1424 * random movement of tasks -- counter the numa conditions we're trying 1424 * random movement of tasks -- counter the numa conditions we're trying
1425 * to satisfy here. 1425 * to satisfy here.
1426 */ 1426 */
1427 rcu_read_lock(); 1427 rcu_read_lock();
1428 sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu)); 1428 sd = rcu_dereference(per_cpu(sd_numa, env.src_cpu));
1429 if (sd) 1429 if (sd)
1430 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2; 1430 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2;
1431 rcu_read_unlock(); 1431 rcu_read_unlock();
1432 1432
1433 /* 1433 /*
1434 * Cpusets can break the scheduler domain tree into smaller 1434 * Cpusets can break the scheduler domain tree into smaller
1435 * balance domains, some of which do not cross NUMA boundaries. 1435 * balance domains, some of which do not cross NUMA boundaries.
1436 * Tasks that are "trapped" in such domains cannot be migrated 1436 * Tasks that are "trapped" in such domains cannot be migrated
1437 * elsewhere, so there is no point in (re)trying. 1437 * elsewhere, so there is no point in (re)trying.
1438 */ 1438 */
1439 if (unlikely(!sd)) { 1439 if (unlikely(!sd)) {
1440 p->numa_preferred_nid = task_node(p); 1440 p->numa_preferred_nid = task_node(p);
1441 return -EINVAL; 1441 return -EINVAL;
1442 } 1442 }
1443 1443
1444 env.dst_nid = p->numa_preferred_nid; 1444 env.dst_nid = p->numa_preferred_nid;
1445 dist = env.dist = node_distance(env.src_nid, env.dst_nid); 1445 dist = env.dist = node_distance(env.src_nid, env.dst_nid);
1446 taskweight = task_weight(p, env.src_nid, dist); 1446 taskweight = task_weight(p, env.src_nid, dist);
1447 groupweight = group_weight(p, env.src_nid, dist); 1447 groupweight = group_weight(p, env.src_nid, dist);
1448 update_numa_stats(&env.src_stats, env.src_nid); 1448 update_numa_stats(&env.src_stats, env.src_nid);
1449 taskimp = task_weight(p, env.dst_nid, dist) - taskweight; 1449 taskimp = task_weight(p, env.dst_nid, dist) - taskweight;
1450 groupimp = group_weight(p, env.dst_nid, dist) - groupweight; 1450 groupimp = group_weight(p, env.dst_nid, dist) - groupweight;
1451 update_numa_stats(&env.dst_stats, env.dst_nid); 1451 update_numa_stats(&env.dst_stats, env.dst_nid);
1452 1452
1453 /* Try to find a spot on the preferred nid. */ 1453 /* Try to find a spot on the preferred nid. */
1454 task_numa_find_cpu(&env, taskimp, groupimp); 1454 task_numa_find_cpu(&env, taskimp, groupimp);
1455 1455
1456 /* 1456 /*
1457 * Look at other nodes in these cases: 1457 * Look at other nodes in these cases:
1458 * - there is no space available on the preferred_nid 1458 * - there is no space available on the preferred_nid
1459 * - the task is part of a numa_group that is interleaved across 1459 * - the task is part of a numa_group that is interleaved across
1460 * multiple NUMA nodes; in order to better consolidate the group, 1460 * multiple NUMA nodes; in order to better consolidate the group,
1461 * we need to check other locations. 1461 * we need to check other locations.
1462 */ 1462 */
1463 if (env.best_cpu == -1 || (p->numa_group && 1463 if (env.best_cpu == -1 || (p->numa_group &&
1464 nodes_weight(p->numa_group->active_nodes) > 1)) { 1464 nodes_weight(p->numa_group->active_nodes) > 1)) {
1465 for_each_online_node(nid) { 1465 for_each_online_node(nid) {
1466 if (nid == env.src_nid || nid == p->numa_preferred_nid) 1466 if (nid == env.src_nid || nid == p->numa_preferred_nid)
1467 continue; 1467 continue;
1468 1468
1469 dist = node_distance(env.src_nid, env.dst_nid); 1469 dist = node_distance(env.src_nid, env.dst_nid);
1470 if (sched_numa_topology_type == NUMA_BACKPLANE && 1470 if (sched_numa_topology_type == NUMA_BACKPLANE &&
1471 dist != env.dist) { 1471 dist != env.dist) {
1472 taskweight = task_weight(p, env.src_nid, dist); 1472 taskweight = task_weight(p, env.src_nid, dist);
1473 groupweight = group_weight(p, env.src_nid, dist); 1473 groupweight = group_weight(p, env.src_nid, dist);
1474 } 1474 }
1475 1475
1476 /* Only consider nodes where both task and groups benefit */ 1476 /* Only consider nodes where both task and groups benefit */
1477 taskimp = task_weight(p, nid, dist) - taskweight; 1477 taskimp = task_weight(p, nid, dist) - taskweight;
1478 groupimp = group_weight(p, nid, dist) - groupweight; 1478 groupimp = group_weight(p, nid, dist) - groupweight;
1479 if (taskimp < 0 && groupimp < 0) 1479 if (taskimp < 0 && groupimp < 0)
1480 continue; 1480 continue;
1481 1481
1482 env.dist = dist; 1482 env.dist = dist;
1483 env.dst_nid = nid; 1483 env.dst_nid = nid;
1484 update_numa_stats(&env.dst_stats, env.dst_nid); 1484 update_numa_stats(&env.dst_stats, env.dst_nid);
1485 task_numa_find_cpu(&env, taskimp, groupimp); 1485 task_numa_find_cpu(&env, taskimp, groupimp);
1486 } 1486 }
1487 } 1487 }
1488 1488
1489 /* 1489 /*
1490 * If the task is part of a workload that spans multiple NUMA nodes, 1490 * If the task is part of a workload that spans multiple NUMA nodes,
1491 * and is migrating into one of the workload's active nodes, remember 1491 * and is migrating into one of the workload's active nodes, remember
1492 * this node as the task's preferred numa node, so the workload can 1492 * this node as the task's preferred numa node, so the workload can
1493 * settle down. 1493 * settle down.
1494 * A task that migrated to a second choice node will be better off 1494 * A task that migrated to a second choice node will be better off
1495 * trying for a better one later. Do not set the preferred node here. 1495 * trying for a better one later. Do not set the preferred node here.
1496 */ 1496 */
1497 if (p->numa_group) { 1497 if (p->numa_group) {
1498 if (env.best_cpu == -1) 1498 if (env.best_cpu == -1)
1499 nid = env.src_nid; 1499 nid = env.src_nid;
1500 else 1500 else
1501 nid = env.dst_nid; 1501 nid = env.dst_nid;
1502 1502
1503 if (node_isset(nid, p->numa_group->active_nodes)) 1503 if (node_isset(nid, p->numa_group->active_nodes))
1504 sched_setnuma(p, env.dst_nid); 1504 sched_setnuma(p, env.dst_nid);
1505 } 1505 }
1506 1506
1507 /* No better CPU than the current one was found. */ 1507 /* No better CPU than the current one was found. */
1508 if (env.best_cpu == -1) 1508 if (env.best_cpu == -1)
1509 return -EAGAIN; 1509 return -EAGAIN;
1510 1510
1511 /* 1511 /*
1512 * Reset the scan period if the task is being rescheduled on an 1512 * Reset the scan period if the task is being rescheduled on an
1513 * alternative node to recheck if the tasks is now properly placed. 1513 * alternative node to recheck if the tasks is now properly placed.
1514 */ 1514 */
1515 p->numa_scan_period = task_scan_min(p); 1515 p->numa_scan_period = task_scan_min(p);
1516 1516
1517 if (env.best_task == NULL) { 1517 if (env.best_task == NULL) {
1518 ret = migrate_task_to(p, env.best_cpu); 1518 ret = migrate_task_to(p, env.best_cpu);
1519 if (ret != 0) 1519 if (ret != 0)
1520 trace_sched_stick_numa(p, env.src_cpu, env.best_cpu); 1520 trace_sched_stick_numa(p, env.src_cpu, env.best_cpu);
1521 return ret; 1521 return ret;
1522 } 1522 }
1523 1523
1524 ret = migrate_swap(p, env.best_task); 1524 ret = migrate_swap(p, env.best_task);
1525 if (ret != 0) 1525 if (ret != 0)
1526 trace_sched_stick_numa(p, env.src_cpu, task_cpu(env.best_task)); 1526 trace_sched_stick_numa(p, env.src_cpu, task_cpu(env.best_task));
1527 put_task_struct(env.best_task); 1527 put_task_struct(env.best_task);
1528 return ret; 1528 return ret;
1529 } 1529 }
1530 1530
1531 /* Attempt to migrate a task to a CPU on the preferred node. */ 1531 /* Attempt to migrate a task to a CPU on the preferred node. */
1532 static void numa_migrate_preferred(struct task_struct *p) 1532 static void numa_migrate_preferred(struct task_struct *p)
1533 { 1533 {
1534 unsigned long interval = HZ; 1534 unsigned long interval = HZ;
1535 1535
1536 /* This task has no NUMA fault statistics yet */ 1536 /* This task has no NUMA fault statistics yet */
1537 if (unlikely(p->numa_preferred_nid == -1 || !p->numa_faults)) 1537 if (unlikely(p->numa_preferred_nid == -1 || !p->numa_faults))
1538 return; 1538 return;
1539 1539
1540 /* Periodically retry migrating the task to the preferred node */ 1540 /* Periodically retry migrating the task to the preferred node */
1541 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16); 1541 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16);
1542 p->numa_migrate_retry = jiffies + interval; 1542 p->numa_migrate_retry = jiffies + interval;
1543 1543
1544 /* Success if task is already running on preferred CPU */ 1544 /* Success if task is already running on preferred CPU */
1545 if (task_node(p) == p->numa_preferred_nid) 1545 if (task_node(p) == p->numa_preferred_nid)
1546 return; 1546 return;
1547 1547
1548 /* Otherwise, try migrate to a CPU on the preferred node */ 1548 /* Otherwise, try migrate to a CPU on the preferred node */
1549 task_numa_migrate(p); 1549 task_numa_migrate(p);
1550 } 1550 }
1551 1551
1552 /* 1552 /*
1553 * Find the nodes on which the workload is actively running. We do this by 1553 * Find the nodes on which the workload is actively running. We do this by
1554 * tracking the nodes from which NUMA hinting faults are triggered. This can 1554 * tracking the nodes from which NUMA hinting faults are triggered. This can
1555 * be different from the set of nodes where the workload's memory is currently 1555 * be different from the set of nodes where the workload's memory is currently
1556 * located. 1556 * located.
1557 * 1557 *
1558 * The bitmask is used to make smarter decisions on when to do NUMA page 1558 * The bitmask is used to make smarter decisions on when to do NUMA page
1559 * migrations, To prevent flip-flopping, and excessive page migrations, nodes 1559 * migrations, To prevent flip-flopping, and excessive page migrations, nodes
1560 * are added when they cause over 6/16 of the maximum number of faults, but 1560 * are added when they cause over 6/16 of the maximum number of faults, but
1561 * only removed when they drop below 3/16. 1561 * only removed when they drop below 3/16.
1562 */ 1562 */
1563 static void update_numa_active_node_mask(struct numa_group *numa_group) 1563 static void update_numa_active_node_mask(struct numa_group *numa_group)
1564 { 1564 {
1565 unsigned long faults, max_faults = 0; 1565 unsigned long faults, max_faults = 0;
1566 int nid; 1566 int nid;
1567 1567
1568 for_each_online_node(nid) { 1568 for_each_online_node(nid) {
1569 faults = group_faults_cpu(numa_group, nid); 1569 faults = group_faults_cpu(numa_group, nid);
1570 if (faults > max_faults) 1570 if (faults > max_faults)
1571 max_faults = faults; 1571 max_faults = faults;
1572 } 1572 }
1573 1573
1574 for_each_online_node(nid) { 1574 for_each_online_node(nid) {
1575 faults = group_faults_cpu(numa_group, nid); 1575 faults = group_faults_cpu(numa_group, nid);
1576 if (!node_isset(nid, numa_group->active_nodes)) { 1576 if (!node_isset(nid, numa_group->active_nodes)) {
1577 if (faults > max_faults * 6 / 16) 1577 if (faults > max_faults * 6 / 16)
1578 node_set(nid, numa_group->active_nodes); 1578 node_set(nid, numa_group->active_nodes);
1579 } else if (faults < max_faults * 3 / 16) 1579 } else if (faults < max_faults * 3 / 16)
1580 node_clear(nid, numa_group->active_nodes); 1580 node_clear(nid, numa_group->active_nodes);
1581 } 1581 }
1582 } 1582 }
1583 1583
1584 /* 1584 /*
1585 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS 1585 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS
1586 * increments. The more local the fault statistics are, the higher the scan 1586 * increments. The more local the fault statistics are, the higher the scan
1587 * period will be for the next scan window. If local/(local+remote) ratio is 1587 * period will be for the next scan window. If local/(local+remote) ratio is
1588 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS) 1588 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS)
1589 * the scan period will decrease. Aim for 70% local accesses. 1589 * the scan period will decrease. Aim for 70% local accesses.
1590 */ 1590 */
1591 #define NUMA_PERIOD_SLOTS 10 1591 #define NUMA_PERIOD_SLOTS 10
1592 #define NUMA_PERIOD_THRESHOLD 7 1592 #define NUMA_PERIOD_THRESHOLD 7
1593 1593
1594 /* 1594 /*
1595 * Increase the scan period (slow down scanning) if the majority of 1595 * Increase the scan period (slow down scanning) if the majority of
1596 * our memory is already on our local node, or if the majority of 1596 * our memory is already on our local node, or if the majority of
1597 * the page accesses are shared with other processes. 1597 * the page accesses are shared with other processes.
1598 * Otherwise, decrease the scan period. 1598 * Otherwise, decrease the scan period.
1599 */ 1599 */
1600 static void update_task_scan_period(struct task_struct *p, 1600 static void update_task_scan_period(struct task_struct *p,
1601 unsigned long shared, unsigned long private) 1601 unsigned long shared, unsigned long private)
1602 { 1602 {
1603 unsigned int period_slot; 1603 unsigned int period_slot;
1604 int ratio; 1604 int ratio;
1605 int diff; 1605 int diff;
1606 1606
1607 unsigned long remote = p->numa_faults_locality[0]; 1607 unsigned long remote = p->numa_faults_locality[0];
1608 unsigned long local = p->numa_faults_locality[1]; 1608 unsigned long local = p->numa_faults_locality[1];
1609 1609
1610 /* 1610 /*
1611 * If there were no record hinting faults then either the task is 1611 * If there were no record hinting faults then either the task is
1612 * completely idle or all activity is areas that are not of interest 1612 * completely idle or all activity is areas that are not of interest
1613 * to automatic numa balancing. Scan slower 1613 * to automatic numa balancing. Scan slower
1614 */ 1614 */
1615 if (local + shared == 0) { 1615 if (local + shared == 0) {
1616 p->numa_scan_period = min(p->numa_scan_period_max, 1616 p->numa_scan_period = min(p->numa_scan_period_max,
1617 p->numa_scan_period << 1); 1617 p->numa_scan_period << 1);
1618 1618
1619 p->mm->numa_next_scan = jiffies + 1619 p->mm->numa_next_scan = jiffies +
1620 msecs_to_jiffies(p->numa_scan_period); 1620 msecs_to_jiffies(p->numa_scan_period);
1621 1621
1622 return; 1622 return;
1623 } 1623 }
1624 1624
1625 /* 1625 /*
1626 * Prepare to scale scan period relative to the current period. 1626 * Prepare to scale scan period relative to the current period.
1627 * == NUMA_PERIOD_THRESHOLD scan period stays the same 1627 * == NUMA_PERIOD_THRESHOLD scan period stays the same
1628 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster) 1628 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster)
1629 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower) 1629 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower)
1630 */ 1630 */
1631 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS); 1631 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS);
1632 ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote); 1632 ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote);
1633 if (ratio >= NUMA_PERIOD_THRESHOLD) { 1633 if (ratio >= NUMA_PERIOD_THRESHOLD) {
1634 int slot = ratio - NUMA_PERIOD_THRESHOLD; 1634 int slot = ratio - NUMA_PERIOD_THRESHOLD;
1635 if (!slot) 1635 if (!slot)
1636 slot = 1; 1636 slot = 1;
1637 diff = slot * period_slot; 1637 diff = slot * period_slot;
1638 } else { 1638 } else {
1639 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot; 1639 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot;
1640 1640
1641 /* 1641 /*
1642 * Scale scan rate increases based on sharing. There is an 1642 * Scale scan rate increases based on sharing. There is an
1643 * inverse relationship between the degree of sharing and 1643 * inverse relationship between the degree of sharing and
1644 * the adjustment made to the scanning period. Broadly 1644 * the adjustment made to the scanning period. Broadly
1645 * speaking the intent is that there is little point 1645 * speaking the intent is that there is little point
1646 * scanning faster if shared accesses dominate as it may 1646 * scanning faster if shared accesses dominate as it may
1647 * simply bounce migrations uselessly 1647 * simply bounce migrations uselessly
1648 */ 1648 */
1649 ratio = DIV_ROUND_UP(private * NUMA_PERIOD_SLOTS, (private + shared + 1)); 1649 ratio = DIV_ROUND_UP(private * NUMA_PERIOD_SLOTS, (private + shared + 1));
1650 diff = (diff * ratio) / NUMA_PERIOD_SLOTS; 1650 diff = (diff * ratio) / NUMA_PERIOD_SLOTS;
1651 } 1651 }
1652 1652
1653 p->numa_scan_period = clamp(p->numa_scan_period + diff, 1653 p->numa_scan_period = clamp(p->numa_scan_period + diff,
1654 task_scan_min(p), task_scan_max(p)); 1654 task_scan_min(p), task_scan_max(p));
1655 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality)); 1655 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
1656 } 1656 }
1657 1657
1658 /* 1658 /*
1659 * Get the fraction of time the task has been running since the last 1659 * Get the fraction of time the task has been running since the last
1660 * NUMA placement cycle. The scheduler keeps similar statistics, but 1660 * NUMA placement cycle. The scheduler keeps similar statistics, but
1661 * decays those on a 32ms period, which is orders of magnitude off 1661 * decays those on a 32ms period, which is orders of magnitude off
1662 * from the dozens-of-seconds NUMA balancing period. Use the scheduler 1662 * from the dozens-of-seconds NUMA balancing period. Use the scheduler
1663 * stats only if the task is so new there are no NUMA statistics yet. 1663 * stats only if the task is so new there are no NUMA statistics yet.
1664 */ 1664 */
1665 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period) 1665 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period)
1666 { 1666 {
1667 u64 runtime, delta, now; 1667 u64 runtime, delta, now;
1668 /* Use the start of this time slice to avoid calculations. */ 1668 /* Use the start of this time slice to avoid calculations. */
1669 now = p->se.exec_start; 1669 now = p->se.exec_start;
1670 runtime = p->se.sum_exec_runtime; 1670 runtime = p->se.sum_exec_runtime;
1671 1671
1672 if (p->last_task_numa_placement) { 1672 if (p->last_task_numa_placement) {
1673 delta = runtime - p->last_sum_exec_runtime; 1673 delta = runtime - p->last_sum_exec_runtime;
1674 *period = now - p->last_task_numa_placement; 1674 *period = now - p->last_task_numa_placement;
1675 } else { 1675 } else {
1676 delta = p->se.avg.runnable_avg_sum; 1676 delta = p->se.avg.runnable_avg_sum;
1677 *period = p->se.avg.runnable_avg_period; 1677 *period = p->se.avg.runnable_avg_period;
1678 } 1678 }
1679 1679
1680 p->last_sum_exec_runtime = runtime; 1680 p->last_sum_exec_runtime = runtime;
1681 p->last_task_numa_placement = now; 1681 p->last_task_numa_placement = now;
1682 1682
1683 return delta; 1683 return delta;
1684 } 1684 }
1685 1685
1686 /* 1686 /*
1687 * Determine the preferred nid for a task in a numa_group. This needs to 1687 * Determine the preferred nid for a task in a numa_group. This needs to
1688 * be done in a way that produces consistent results with group_weight, 1688 * be done in a way that produces consistent results with group_weight,
1689 * otherwise workloads might not converge. 1689 * otherwise workloads might not converge.
1690 */ 1690 */
1691 static int preferred_group_nid(struct task_struct *p, int nid) 1691 static int preferred_group_nid(struct task_struct *p, int nid)
1692 { 1692 {
1693 nodemask_t nodes; 1693 nodemask_t nodes;
1694 int dist; 1694 int dist;
1695 1695
1696 /* Direct connections between all NUMA nodes. */ 1696 /* Direct connections between all NUMA nodes. */
1697 if (sched_numa_topology_type == NUMA_DIRECT) 1697 if (sched_numa_topology_type == NUMA_DIRECT)
1698 return nid; 1698 return nid;
1699 1699
1700 /* 1700 /*
1701 * On a system with glueless mesh NUMA topology, group_weight 1701 * On a system with glueless mesh NUMA topology, group_weight
1702 * scores nodes according to the number of NUMA hinting faults on 1702 * scores nodes according to the number of NUMA hinting faults on
1703 * both the node itself, and on nearby nodes. 1703 * both the node itself, and on nearby nodes.
1704 */ 1704 */
1705 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) { 1705 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) {
1706 unsigned long score, max_score = 0; 1706 unsigned long score, max_score = 0;
1707 int node, max_node = nid; 1707 int node, max_node = nid;
1708 1708
1709 dist = sched_max_numa_distance; 1709 dist = sched_max_numa_distance;
1710 1710
1711 for_each_online_node(node) { 1711 for_each_online_node(node) {
1712 score = group_weight(p, node, dist); 1712 score = group_weight(p, node, dist);
1713 if (score > max_score) { 1713 if (score > max_score) {
1714 max_score = score; 1714 max_score = score;
1715 max_node = node; 1715 max_node = node;
1716 } 1716 }
1717 } 1717 }
1718 return max_node; 1718 return max_node;
1719 } 1719 }
1720 1720
1721 /* 1721 /*
1722 * Finding the preferred nid in a system with NUMA backplane 1722 * Finding the preferred nid in a system with NUMA backplane
1723 * interconnect topology is more involved. The goal is to locate 1723 * interconnect topology is more involved. The goal is to locate
1724 * tasks from numa_groups near each other in the system, and 1724 * tasks from numa_groups near each other in the system, and
1725 * untangle workloads from different sides of the system. This requires 1725 * untangle workloads from different sides of the system. This requires
1726 * searching down the hierarchy of node groups, recursively searching 1726 * searching down the hierarchy of node groups, recursively searching
1727 * inside the highest scoring group of nodes. The nodemask tricks 1727 * inside the highest scoring group of nodes. The nodemask tricks
1728 * keep the complexity of the search down. 1728 * keep the complexity of the search down.
1729 */ 1729 */
1730 nodes = node_online_map; 1730 nodes = node_online_map;
1731 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) { 1731 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) {
1732 unsigned long max_faults = 0; 1732 unsigned long max_faults = 0;
1733 nodemask_t max_group; 1733 nodemask_t max_group;
1734 int a, b; 1734 int a, b;
1735 1735
1736 /* Are there nodes at this distance from each other? */ 1736 /* Are there nodes at this distance from each other? */
1737 if (!find_numa_distance(dist)) 1737 if (!find_numa_distance(dist))
1738 continue; 1738 continue;
1739 1739
1740 for_each_node_mask(a, nodes) { 1740 for_each_node_mask(a, nodes) {
1741 unsigned long faults = 0; 1741 unsigned long faults = 0;
1742 nodemask_t this_group; 1742 nodemask_t this_group;
1743 nodes_clear(this_group); 1743 nodes_clear(this_group);
1744 1744
1745 /* Sum group's NUMA faults; includes a==b case. */ 1745 /* Sum group's NUMA faults; includes a==b case. */
1746 for_each_node_mask(b, nodes) { 1746 for_each_node_mask(b, nodes) {
1747 if (node_distance(a, b) < dist) { 1747 if (node_distance(a, b) < dist) {
1748 faults += group_faults(p, b); 1748 faults += group_faults(p, b);
1749 node_set(b, this_group); 1749 node_set(b, this_group);
1750 node_clear(b, nodes); 1750 node_clear(b, nodes);
1751 } 1751 }
1752 } 1752 }
1753 1753
1754 /* Remember the top group. */ 1754 /* Remember the top group. */
1755 if (faults > max_faults) { 1755 if (faults > max_faults) {
1756 max_faults = faults; 1756 max_faults = faults;
1757 max_group = this_group; 1757 max_group = this_group;
1758 /* 1758 /*
1759 * subtle: at the smallest distance there is 1759 * subtle: at the smallest distance there is
1760 * just one node left in each "group", the 1760 * just one node left in each "group", the
1761 * winner is the preferred nid. 1761 * winner is the preferred nid.
1762 */ 1762 */
1763 nid = a; 1763 nid = a;
1764 } 1764 }
1765 } 1765 }
1766 /* Next round, evaluate the nodes within max_group. */ 1766 /* Next round, evaluate the nodes within max_group. */
1767 nodes = max_group; 1767 nodes = max_group;
1768 } 1768 }
1769 return nid; 1769 return nid;
1770 } 1770 }
1771 1771
1772 static void task_numa_placement(struct task_struct *p) 1772 static void task_numa_placement(struct task_struct *p)
1773 { 1773 {
1774 int seq, nid, max_nid = -1, max_group_nid = -1; 1774 int seq, nid, max_nid = -1, max_group_nid = -1;
1775 unsigned long max_faults = 0, max_group_faults = 0; 1775 unsigned long max_faults = 0, max_group_faults = 0;
1776 unsigned long fault_types[2] = { 0, 0 }; 1776 unsigned long fault_types[2] = { 0, 0 };
1777 unsigned long total_faults; 1777 unsigned long total_faults;
1778 u64 runtime, period; 1778 u64 runtime, period;
1779 spinlock_t *group_lock = NULL; 1779 spinlock_t *group_lock = NULL;
1780 1780
1781 seq = ACCESS_ONCE(p->mm->numa_scan_seq); 1781 seq = ACCESS_ONCE(p->mm->numa_scan_seq);
1782 if (p->numa_scan_seq == seq) 1782 if (p->numa_scan_seq == seq)
1783 return; 1783 return;
1784 p->numa_scan_seq = seq; 1784 p->numa_scan_seq = seq;
1785 p->numa_scan_period_max = task_scan_max(p); 1785 p->numa_scan_period_max = task_scan_max(p);
1786 1786
1787 total_faults = p->numa_faults_locality[0] + 1787 total_faults = p->numa_faults_locality[0] +
1788 p->numa_faults_locality[1]; 1788 p->numa_faults_locality[1];
1789 runtime = numa_get_avg_runtime(p, &period); 1789 runtime = numa_get_avg_runtime(p, &period);
1790 1790
1791 /* If the task is part of a group prevent parallel updates to group stats */ 1791 /* If the task is part of a group prevent parallel updates to group stats */
1792 if (p->numa_group) { 1792 if (p->numa_group) {
1793 group_lock = &p->numa_group->lock; 1793 group_lock = &p->numa_group->lock;
1794 spin_lock_irq(group_lock); 1794 spin_lock_irq(group_lock);
1795 } 1795 }
1796 1796
1797 /* Find the node with the highest number of faults */ 1797 /* Find the node with the highest number of faults */
1798 for_each_online_node(nid) { 1798 for_each_online_node(nid) {
1799 /* Keep track of the offsets in numa_faults array */ 1799 /* Keep track of the offsets in numa_faults array */
1800 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx; 1800 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx;
1801 unsigned long faults = 0, group_faults = 0; 1801 unsigned long faults = 0, group_faults = 0;
1802 int priv; 1802 int priv;
1803 1803
1804 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) { 1804 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) {
1805 long diff, f_diff, f_weight; 1805 long diff, f_diff, f_weight;
1806 1806
1807 mem_idx = task_faults_idx(NUMA_MEM, nid, priv); 1807 mem_idx = task_faults_idx(NUMA_MEM, nid, priv);
1808 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv); 1808 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv);
1809 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv); 1809 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv);
1810 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv); 1810 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv);
1811 1811
1812 /* Decay existing window, copy faults since last scan */ 1812 /* Decay existing window, copy faults since last scan */
1813 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2; 1813 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2;
1814 fault_types[priv] += p->numa_faults[membuf_idx]; 1814 fault_types[priv] += p->numa_faults[membuf_idx];
1815 p->numa_faults[membuf_idx] = 0; 1815 p->numa_faults[membuf_idx] = 0;
1816 1816
1817 /* 1817 /*
1818 * Normalize the faults_from, so all tasks in a group 1818 * Normalize the faults_from, so all tasks in a group
1819 * count according to CPU use, instead of by the raw 1819 * count according to CPU use, instead of by the raw
1820 * number of faults. Tasks with little runtime have 1820 * number of faults. Tasks with little runtime have
1821 * little over-all impact on throughput, and thus their 1821 * little over-all impact on throughput, and thus their
1822 * faults are less important. 1822 * faults are less important.
1823 */ 1823 */
1824 f_weight = div64_u64(runtime << 16, period + 1); 1824 f_weight = div64_u64(runtime << 16, period + 1);
1825 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) / 1825 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) /
1826 (total_faults + 1); 1826 (total_faults + 1);
1827 f_diff = f_weight - p->numa_faults[cpu_idx] / 2; 1827 f_diff = f_weight - p->numa_faults[cpu_idx] / 2;
1828 p->numa_faults[cpubuf_idx] = 0; 1828 p->numa_faults[cpubuf_idx] = 0;
1829 1829
1830 p->numa_faults[mem_idx] += diff; 1830 p->numa_faults[mem_idx] += diff;
1831 p->numa_faults[cpu_idx] += f_diff; 1831 p->numa_faults[cpu_idx] += f_diff;
1832 faults += p->numa_faults[mem_idx]; 1832 faults += p->numa_faults[mem_idx];
1833 p->total_numa_faults += diff; 1833 p->total_numa_faults += diff;
1834 if (p->numa_group) { 1834 if (p->numa_group) {
1835 /* 1835 /*
1836 * safe because we can only change our own group 1836 * safe because we can only change our own group
1837 * 1837 *
1838 * mem_idx represents the offset for a given 1838 * mem_idx represents the offset for a given
1839 * nid and priv in a specific region because it 1839 * nid and priv in a specific region because it
1840 * is at the beginning of the numa_faults array. 1840 * is at the beginning of the numa_faults array.
1841 */ 1841 */
1842 p->numa_group->faults[mem_idx] += diff; 1842 p->numa_group->faults[mem_idx] += diff;
1843 p->numa_group->faults_cpu[mem_idx] += f_diff; 1843 p->numa_group->faults_cpu[mem_idx] += f_diff;
1844 p->numa_group->total_faults += diff; 1844 p->numa_group->total_faults += diff;
1845 group_faults += p->numa_group->faults[mem_idx]; 1845 group_faults += p->numa_group->faults[mem_idx];
1846 } 1846 }
1847 } 1847 }
1848 1848
1849 if (faults > max_faults) { 1849 if (faults > max_faults) {
1850 max_faults = faults; 1850 max_faults = faults;
1851 max_nid = nid; 1851 max_nid = nid;
1852 } 1852 }
1853 1853
1854 if (group_faults > max_group_faults) { 1854 if (group_faults > max_group_faults) {
1855 max_group_faults = group_faults; 1855 max_group_faults = group_faults;
1856 max_group_nid = nid; 1856 max_group_nid = nid;
1857 } 1857 }
1858 } 1858 }
1859 1859
1860 update_task_scan_period(p, fault_types[0], fault_types[1]); 1860 update_task_scan_period(p, fault_types[0], fault_types[1]);
1861 1861
1862 if (p->numa_group) { 1862 if (p->numa_group) {
1863 update_numa_active_node_mask(p->numa_group); 1863 update_numa_active_node_mask(p->numa_group);
1864 spin_unlock_irq(group_lock); 1864 spin_unlock_irq(group_lock);
1865 max_nid = preferred_group_nid(p, max_group_nid); 1865 max_nid = preferred_group_nid(p, max_group_nid);
1866 } 1866 }
1867 1867
1868 if (max_faults) { 1868 if (max_faults) {
1869 /* Set the new preferred node */ 1869 /* Set the new preferred node */
1870 if (max_nid != p->numa_preferred_nid) 1870 if (max_nid != p->numa_preferred_nid)
1871 sched_setnuma(p, max_nid); 1871 sched_setnuma(p, max_nid);
1872 1872
1873 if (task_node(p) != p->numa_preferred_nid) 1873 if (task_node(p) != p->numa_preferred_nid)
1874 numa_migrate_preferred(p); 1874 numa_migrate_preferred(p);
1875 } 1875 }
1876 } 1876 }
1877 1877
1878 static inline int get_numa_group(struct numa_group *grp) 1878 static inline int get_numa_group(struct numa_group *grp)
1879 { 1879 {
1880 return atomic_inc_not_zero(&grp->refcount); 1880 return atomic_inc_not_zero(&grp->refcount);
1881 } 1881 }
1882 1882
1883 static inline void put_numa_group(struct numa_group *grp) 1883 static inline void put_numa_group(struct numa_group *grp)
1884 { 1884 {
1885 if (atomic_dec_and_test(&grp->refcount)) 1885 if (atomic_dec_and_test(&grp->refcount))
1886 kfree_rcu(grp, rcu); 1886 kfree_rcu(grp, rcu);
1887 } 1887 }
1888 1888
1889 static void task_numa_group(struct task_struct *p, int cpupid, int flags, 1889 static void task_numa_group(struct task_struct *p, int cpupid, int flags,
1890 int *priv) 1890 int *priv)
1891 { 1891 {
1892 struct numa_group *grp, *my_grp; 1892 struct numa_group *grp, *my_grp;
1893 struct task_struct *tsk; 1893 struct task_struct *tsk;
1894 bool join = false; 1894 bool join = false;
1895 int cpu = cpupid_to_cpu(cpupid); 1895 int cpu = cpupid_to_cpu(cpupid);
1896 int i; 1896 int i;
1897 1897
1898 if (unlikely(!p->numa_group)) { 1898 if (unlikely(!p->numa_group)) {
1899 unsigned int size = sizeof(struct numa_group) + 1899 unsigned int size = sizeof(struct numa_group) +
1900 4*nr_node_ids*sizeof(unsigned long); 1900 4*nr_node_ids*sizeof(unsigned long);
1901 1901
1902 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN); 1902 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
1903 if (!grp) 1903 if (!grp)
1904 return; 1904 return;
1905 1905
1906 atomic_set(&grp->refcount, 1); 1906 atomic_set(&grp->refcount, 1);
1907 spin_lock_init(&grp->lock); 1907 spin_lock_init(&grp->lock);
1908 grp->gid = p->pid; 1908 grp->gid = p->pid;
1909 /* Second half of the array tracks nids where faults happen */ 1909 /* Second half of the array tracks nids where faults happen */
1910 grp->faults_cpu = grp->faults + NR_NUMA_HINT_FAULT_TYPES * 1910 grp->faults_cpu = grp->faults + NR_NUMA_HINT_FAULT_TYPES *
1911 nr_node_ids; 1911 nr_node_ids;
1912 1912
1913 node_set(task_node(current), grp->active_nodes); 1913 node_set(task_node(current), grp->active_nodes);
1914 1914
1915 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 1915 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
1916 grp->faults[i] = p->numa_faults[i]; 1916 grp->faults[i] = p->numa_faults[i];
1917 1917
1918 grp->total_faults = p->total_numa_faults; 1918 grp->total_faults = p->total_numa_faults;
1919 1919
1920 grp->nr_tasks++; 1920 grp->nr_tasks++;
1921 rcu_assign_pointer(p->numa_group, grp); 1921 rcu_assign_pointer(p->numa_group, grp);
1922 } 1922 }
1923 1923
1924 rcu_read_lock(); 1924 rcu_read_lock();
1925 tsk = ACCESS_ONCE(cpu_rq(cpu)->curr); 1925 tsk = ACCESS_ONCE(cpu_rq(cpu)->curr);
1926 1926
1927 if (!cpupid_match_pid(tsk, cpupid)) 1927 if (!cpupid_match_pid(tsk, cpupid))
1928 goto no_join; 1928 goto no_join;
1929 1929
1930 grp = rcu_dereference(tsk->numa_group); 1930 grp = rcu_dereference(tsk->numa_group);
1931 if (!grp) 1931 if (!grp)
1932 goto no_join; 1932 goto no_join;
1933 1933
1934 my_grp = p->numa_group; 1934 my_grp = p->numa_group;
1935 if (grp == my_grp) 1935 if (grp == my_grp)
1936 goto no_join; 1936 goto no_join;
1937 1937
1938 /* 1938 /*
1939 * Only join the other group if its bigger; if we're the bigger group, 1939 * Only join the other group if its bigger; if we're the bigger group,
1940 * the other task will join us. 1940 * the other task will join us.
1941 */ 1941 */
1942 if (my_grp->nr_tasks > grp->nr_tasks) 1942 if (my_grp->nr_tasks > grp->nr_tasks)
1943 goto no_join; 1943 goto no_join;
1944 1944
1945 /* 1945 /*
1946 * Tie-break on the grp address. 1946 * Tie-break on the grp address.
1947 */ 1947 */
1948 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp) 1948 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp)
1949 goto no_join; 1949 goto no_join;
1950 1950
1951 /* Always join threads in the same process. */ 1951 /* Always join threads in the same process. */
1952 if (tsk->mm == current->mm) 1952 if (tsk->mm == current->mm)
1953 join = true; 1953 join = true;
1954 1954
1955 /* Simple filter to avoid false positives due to PID collisions */ 1955 /* Simple filter to avoid false positives due to PID collisions */
1956 if (flags & TNF_SHARED) 1956 if (flags & TNF_SHARED)
1957 join = true; 1957 join = true;
1958 1958
1959 /* Update priv based on whether false sharing was detected */ 1959 /* Update priv based on whether false sharing was detected */
1960 *priv = !join; 1960 *priv = !join;
1961 1961
1962 if (join && !get_numa_group(grp)) 1962 if (join && !get_numa_group(grp))
1963 goto no_join; 1963 goto no_join;
1964 1964
1965 rcu_read_unlock(); 1965 rcu_read_unlock();
1966 1966
1967 if (!join) 1967 if (!join)
1968 return; 1968 return;
1969 1969
1970 BUG_ON(irqs_disabled()); 1970 BUG_ON(irqs_disabled());
1971 double_lock_irq(&my_grp->lock, &grp->lock); 1971 double_lock_irq(&my_grp->lock, &grp->lock);
1972 1972
1973 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) { 1973 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) {
1974 my_grp->faults[i] -= p->numa_faults[i]; 1974 my_grp->faults[i] -= p->numa_faults[i];
1975 grp->faults[i] += p->numa_faults[i]; 1975 grp->faults[i] += p->numa_faults[i];
1976 } 1976 }
1977 my_grp->total_faults -= p->total_numa_faults; 1977 my_grp->total_faults -= p->total_numa_faults;
1978 grp->total_faults += p->total_numa_faults; 1978 grp->total_faults += p->total_numa_faults;
1979 1979
1980 my_grp->nr_tasks--; 1980 my_grp->nr_tasks--;
1981 grp->nr_tasks++; 1981 grp->nr_tasks++;
1982 1982
1983 spin_unlock(&my_grp->lock); 1983 spin_unlock(&my_grp->lock);
1984 spin_unlock_irq(&grp->lock); 1984 spin_unlock_irq(&grp->lock);
1985 1985
1986 rcu_assign_pointer(p->numa_group, grp); 1986 rcu_assign_pointer(p->numa_group, grp);
1987 1987
1988 put_numa_group(my_grp); 1988 put_numa_group(my_grp);
1989 return; 1989 return;
1990 1990
1991 no_join: 1991 no_join:
1992 rcu_read_unlock(); 1992 rcu_read_unlock();
1993 return; 1993 return;
1994 } 1994 }
1995 1995
1996 void task_numa_free(struct task_struct *p) 1996 void task_numa_free(struct task_struct *p)
1997 { 1997 {
1998 struct numa_group *grp = p->numa_group; 1998 struct numa_group *grp = p->numa_group;
1999 void *numa_faults = p->numa_faults; 1999 void *numa_faults = p->numa_faults;
2000 unsigned long flags; 2000 unsigned long flags;
2001 int i; 2001 int i;
2002 2002
2003 if (grp) { 2003 if (grp) {
2004 spin_lock_irqsave(&grp->lock, flags); 2004 spin_lock_irqsave(&grp->lock, flags);
2005 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 2005 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++)
2006 grp->faults[i] -= p->numa_faults[i]; 2006 grp->faults[i] -= p->numa_faults[i];
2007 grp->total_faults -= p->total_numa_faults; 2007 grp->total_faults -= p->total_numa_faults;
2008 2008
2009 grp->nr_tasks--; 2009 grp->nr_tasks--;
2010 spin_unlock_irqrestore(&grp->lock, flags); 2010 spin_unlock_irqrestore(&grp->lock, flags);
2011 RCU_INIT_POINTER(p->numa_group, NULL); 2011 RCU_INIT_POINTER(p->numa_group, NULL);
2012 put_numa_group(grp); 2012 put_numa_group(grp);
2013 } 2013 }
2014 2014
2015 p->numa_faults = NULL; 2015 p->numa_faults = NULL;
2016 kfree(numa_faults); 2016 kfree(numa_faults);
2017 } 2017 }
2018 2018
2019 /* 2019 /*
2020 * Got a PROT_NONE fault for a page on @node. 2020 * Got a PROT_NONE fault for a page on @node.
2021 */ 2021 */
2022 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags) 2022 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags)
2023 { 2023 {
2024 struct task_struct *p = current; 2024 struct task_struct *p = current;
2025 bool migrated = flags & TNF_MIGRATED; 2025 bool migrated = flags & TNF_MIGRATED;
2026 int cpu_node = task_node(current); 2026 int cpu_node = task_node(current);
2027 int local = !!(flags & TNF_FAULT_LOCAL); 2027 int local = !!(flags & TNF_FAULT_LOCAL);
2028 int priv; 2028 int priv;
2029 2029
2030 if (!numabalancing_enabled) 2030 if (!numabalancing_enabled)
2031 return; 2031 return;
2032 2032
2033 /* for example, ksmd faulting in a user's mm */ 2033 /* for example, ksmd faulting in a user's mm */
2034 if (!p->mm) 2034 if (!p->mm)
2035 return; 2035 return;
2036 2036
2037 /* Allocate buffer to track faults on a per-node basis */ 2037 /* Allocate buffer to track faults on a per-node basis */
2038 if (unlikely(!p->numa_faults)) { 2038 if (unlikely(!p->numa_faults)) {
2039 int size = sizeof(*p->numa_faults) * 2039 int size = sizeof(*p->numa_faults) *
2040 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids; 2040 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids;
2041 2041
2042 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN); 2042 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN);
2043 if (!p->numa_faults) 2043 if (!p->numa_faults)
2044 return; 2044 return;
2045 2045
2046 p->total_numa_faults = 0; 2046 p->total_numa_faults = 0;
2047 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality)); 2047 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality));
2048 } 2048 }
2049 2049
2050 /* 2050 /*
2051 * First accesses are treated as private, otherwise consider accesses 2051 * First accesses are treated as private, otherwise consider accesses
2052 * to be private if the accessing pid has not changed 2052 * to be private if the accessing pid has not changed
2053 */ 2053 */
2054 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) { 2054 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) {
2055 priv = 1; 2055 priv = 1;
2056 } else { 2056 } else {
2057 priv = cpupid_match_pid(p, last_cpupid); 2057 priv = cpupid_match_pid(p, last_cpupid);
2058 if (!priv && !(flags & TNF_NO_GROUP)) 2058 if (!priv && !(flags & TNF_NO_GROUP))
2059 task_numa_group(p, last_cpupid, flags, &priv); 2059 task_numa_group(p, last_cpupid, flags, &priv);
2060 } 2060 }
2061 2061
2062 /* 2062 /*
2063 * If a workload spans multiple NUMA nodes, a shared fault that 2063 * If a workload spans multiple NUMA nodes, a shared fault that
2064 * occurs wholly within the set of nodes that the workload is 2064 * occurs wholly within the set of nodes that the workload is
2065 * actively using should be counted as local. This allows the 2065 * actively using should be counted as local. This allows the
2066 * scan rate to slow down when a workload has settled down. 2066 * scan rate to slow down when a workload has settled down.
2067 */ 2067 */
2068 if (!priv && !local && p->numa_group && 2068 if (!priv && !local && p->numa_group &&
2069 node_isset(cpu_node, p->numa_group->active_nodes) && 2069 node_isset(cpu_node, p->numa_group->active_nodes) &&
2070 node_isset(mem_node, p->numa_group->active_nodes)) 2070 node_isset(mem_node, p->numa_group->active_nodes))
2071 local = 1; 2071 local = 1;
2072 2072
2073 task_numa_placement(p); 2073 task_numa_placement(p);
2074 2074
2075 /* 2075 /*
2076 * Retry task to preferred node migration periodically, in case it 2076 * Retry task to preferred node migration periodically, in case it
2077 * case it previously failed, or the scheduler moved us. 2077 * case it previously failed, or the scheduler moved us.
2078 */ 2078 */
2079 if (time_after(jiffies, p->numa_migrate_retry)) 2079 if (time_after(jiffies, p->numa_migrate_retry))
2080 numa_migrate_preferred(p); 2080 numa_migrate_preferred(p);
2081 2081
2082 if (migrated) 2082 if (migrated)
2083 p->numa_pages_migrated += pages; 2083 p->numa_pages_migrated += pages;
2084 2084
2085 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages; 2085 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages;
2086 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages; 2086 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages;
2087 p->numa_faults_locality[local] += pages; 2087 p->numa_faults_locality[local] += pages;
2088 } 2088 }
2089 2089
2090 static void reset_ptenuma_scan(struct task_struct *p) 2090 static void reset_ptenuma_scan(struct task_struct *p)
2091 { 2091 {
2092 ACCESS_ONCE(p->mm->numa_scan_seq)++; 2092 ACCESS_ONCE(p->mm->numa_scan_seq)++;
2093 p->mm->numa_scan_offset = 0; 2093 p->mm->numa_scan_offset = 0;
2094 } 2094 }
2095 2095
2096 /* 2096 /*
2097 * The expensive part of numa migration is done from task_work context. 2097 * The expensive part of numa migration is done from task_work context.
2098 * Triggered from task_tick_numa(). 2098 * Triggered from task_tick_numa().
2099 */ 2099 */
2100 void task_numa_work(struct callback_head *work) 2100 void task_numa_work(struct callback_head *work)
2101 { 2101 {
2102 unsigned long migrate, next_scan, now = jiffies; 2102 unsigned long migrate, next_scan, now = jiffies;
2103 struct task_struct *p = current; 2103 struct task_struct *p = current;
2104 struct mm_struct *mm = p->mm; 2104 struct mm_struct *mm = p->mm;
2105 struct vm_area_struct *vma; 2105 struct vm_area_struct *vma;
2106 unsigned long start, end; 2106 unsigned long start, end;
2107 unsigned long nr_pte_updates = 0; 2107 unsigned long nr_pte_updates = 0;
2108 long pages; 2108 long pages;
2109 2109
2110 WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work)); 2110 WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work));
2111 2111
2112 work->next = work; /* protect against double add */ 2112 work->next = work; /* protect against double add */
2113 /* 2113 /*
2114 * Who cares about NUMA placement when they're dying. 2114 * Who cares about NUMA placement when they're dying.
2115 * 2115 *
2116 * NOTE: make sure not to dereference p->mm before this check, 2116 * NOTE: make sure not to dereference p->mm before this check,
2117 * exit_task_work() happens _after_ exit_mm() so we could be called 2117 * exit_task_work() happens _after_ exit_mm() so we could be called
2118 * without p->mm even though we still had it when we enqueued this 2118 * without p->mm even though we still had it when we enqueued this
2119 * work. 2119 * work.
2120 */ 2120 */
2121 if (p->flags & PF_EXITING) 2121 if (p->flags & PF_EXITING)
2122 return; 2122 return;
2123 2123
2124 if (!mm->numa_next_scan) { 2124 if (!mm->numa_next_scan) {
2125 mm->numa_next_scan = now + 2125 mm->numa_next_scan = now +
2126 msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 2126 msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
2127 } 2127 }
2128 2128
2129 /* 2129 /*
2130 * Enforce maximal scan/migration frequency.. 2130 * Enforce maximal scan/migration frequency..
2131 */ 2131 */
2132 migrate = mm->numa_next_scan; 2132 migrate = mm->numa_next_scan;
2133 if (time_before(now, migrate)) 2133 if (time_before(now, migrate))
2134 return; 2134 return;
2135 2135
2136 if (p->numa_scan_period == 0) { 2136 if (p->numa_scan_period == 0) {
2137 p->numa_scan_period_max = task_scan_max(p); 2137 p->numa_scan_period_max = task_scan_max(p);
2138 p->numa_scan_period = task_scan_min(p); 2138 p->numa_scan_period = task_scan_min(p);
2139 } 2139 }
2140 2140
2141 next_scan = now + msecs_to_jiffies(p->numa_scan_period); 2141 next_scan = now + msecs_to_jiffies(p->numa_scan_period);
2142 if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate) 2142 if (cmpxchg(&mm->numa_next_scan, migrate, next_scan) != migrate)
2143 return; 2143 return;
2144 2144
2145 /* 2145 /*
2146 * Delay this task enough that another task of this mm will likely win 2146 * Delay this task enough that another task of this mm will likely win
2147 * the next time around. 2147 * the next time around.
2148 */ 2148 */
2149 p->node_stamp += 2 * TICK_NSEC; 2149 p->node_stamp += 2 * TICK_NSEC;
2150 2150
2151 start = mm->numa_scan_offset; 2151 start = mm->numa_scan_offset;
2152 pages = sysctl_numa_balancing_scan_size; 2152 pages = sysctl_numa_balancing_scan_size;
2153 pages <<= 20 - PAGE_SHIFT; /* MB in pages */ 2153 pages <<= 20 - PAGE_SHIFT; /* MB in pages */
2154 if (!pages) 2154 if (!pages)
2155 return; 2155 return;
2156 2156
2157 down_read(&mm->mmap_sem); 2157 down_read(&mm->mmap_sem);
2158 vma = find_vma(mm, start); 2158 vma = find_vma(mm, start);
2159 if (!vma) { 2159 if (!vma) {
2160 reset_ptenuma_scan(p); 2160 reset_ptenuma_scan(p);
2161 start = 0; 2161 start = 0;
2162 vma = mm->mmap; 2162 vma = mm->mmap;
2163 } 2163 }
2164 for (; vma; vma = vma->vm_next) { 2164 for (; vma; vma = vma->vm_next) {
2165 if (!vma_migratable(vma) || !vma_policy_mof(vma)) 2165 if (!vma_migratable(vma) || !vma_policy_mof(vma))
2166 continue; 2166 continue;
2167 2167
2168 /* 2168 /*
2169 * Shared library pages mapped by multiple processes are not 2169 * Shared library pages mapped by multiple processes are not
2170 * migrated as it is expected they are cache replicated. Avoid 2170 * migrated as it is expected they are cache replicated. Avoid
2171 * hinting faults in read-only file-backed mappings or the vdso 2171 * hinting faults in read-only file-backed mappings or the vdso
2172 * as migrating the pages will be of marginal benefit. 2172 * as migrating the pages will be of marginal benefit.
2173 */ 2173 */
2174 if (!vma->vm_mm || 2174 if (!vma->vm_mm ||
2175 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) 2175 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ)))
2176 continue; 2176 continue;
2177 2177
2178 /* 2178 /*
2179 * Skip inaccessible VMAs to avoid any confusion between 2179 * Skip inaccessible VMAs to avoid any confusion between
2180 * PROT_NONE and NUMA hinting ptes 2180 * PROT_NONE and NUMA hinting ptes
2181 */ 2181 */
2182 if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE))) 2182 if (!(vma->vm_flags & (VM_READ | VM_EXEC | VM_WRITE)))
2183 continue; 2183 continue;
2184 2184
2185 do { 2185 do {
2186 start = max(start, vma->vm_start); 2186 start = max(start, vma->vm_start);
2187 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE); 2187 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE);
2188 end = min(end, vma->vm_end); 2188 end = min(end, vma->vm_end);
2189 nr_pte_updates += change_prot_numa(vma, start, end); 2189 nr_pte_updates += change_prot_numa(vma, start, end);
2190 2190
2191 /* 2191 /*
2192 * Scan sysctl_numa_balancing_scan_size but ensure that 2192 * Scan sysctl_numa_balancing_scan_size but ensure that
2193 * at least one PTE is updated so that unused virtual 2193 * at least one PTE is updated so that unused virtual
2194 * address space is quickly skipped. 2194 * address space is quickly skipped.
2195 */ 2195 */
2196 if (nr_pte_updates) 2196 if (nr_pte_updates)
2197 pages -= (end - start) >> PAGE_SHIFT; 2197 pages -= (end - start) >> PAGE_SHIFT;
2198 2198
2199 start = end; 2199 start = end;
2200 if (pages <= 0) 2200 if (pages <= 0)
2201 goto out; 2201 goto out;
2202 2202
2203 cond_resched(); 2203 cond_resched();
2204 } while (end != vma->vm_end); 2204 } while (end != vma->vm_end);
2205 } 2205 }
2206 2206
2207 out: 2207 out:
2208 /* 2208 /*
2209 * It is possible to reach the end of the VMA list but the last few 2209 * It is possible to reach the end of the VMA list but the last few
2210 * VMAs are not guaranteed to the vma_migratable. If they are not, we 2210 * VMAs are not guaranteed to the vma_migratable. If they are not, we
2211 * would find the !migratable VMA on the next scan but not reset the 2211 * would find the !migratable VMA on the next scan but not reset the
2212 * scanner to the start so check it now. 2212 * scanner to the start so check it now.
2213 */ 2213 */
2214 if (vma) 2214 if (vma)
2215 mm->numa_scan_offset = start; 2215 mm->numa_scan_offset = start;
2216 else 2216 else
2217 reset_ptenuma_scan(p); 2217 reset_ptenuma_scan(p);
2218 up_read(&mm->mmap_sem); 2218 up_read(&mm->mmap_sem);
2219 } 2219 }
2220 2220
2221 /* 2221 /*
2222 * Drive the periodic memory faults.. 2222 * Drive the periodic memory faults..
2223 */ 2223 */
2224 void task_tick_numa(struct rq *rq, struct task_struct *curr) 2224 void task_tick_numa(struct rq *rq, struct task_struct *curr)
2225 { 2225 {
2226 struct callback_head *work = &curr->numa_work; 2226 struct callback_head *work = &curr->numa_work;
2227 u64 period, now; 2227 u64 period, now;
2228 2228
2229 /* 2229 /*
2230 * We don't care about NUMA placement if we don't have memory. 2230 * We don't care about NUMA placement if we don't have memory.
2231 */ 2231 */
2232 if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work) 2232 if (!curr->mm || (curr->flags & PF_EXITING) || work->next != work)
2233 return; 2233 return;
2234 2234
2235 /* 2235 /*
2236 * Using runtime rather than walltime has the dual advantage that 2236 * Using runtime rather than walltime has the dual advantage that
2237 * we (mostly) drive the selection from busy threads and that the 2237 * we (mostly) drive the selection from busy threads and that the
2238 * task needs to have done some actual work before we bother with 2238 * task needs to have done some actual work before we bother with
2239 * NUMA placement. 2239 * NUMA placement.
2240 */ 2240 */
2241 now = curr->se.sum_exec_runtime; 2241 now = curr->se.sum_exec_runtime;
2242 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC; 2242 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC;
2243 2243
2244 if (now - curr->node_stamp > period) { 2244 if (now - curr->node_stamp > period) {
2245 if (!curr->node_stamp) 2245 if (!curr->node_stamp)
2246 curr->numa_scan_period = task_scan_min(curr); 2246 curr->numa_scan_period = task_scan_min(curr);
2247 curr->node_stamp += period; 2247 curr->node_stamp += period;
2248 2248
2249 if (!time_before(jiffies, curr->mm->numa_next_scan)) { 2249 if (!time_before(jiffies, curr->mm->numa_next_scan)) {
2250 init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */ 2250 init_task_work(work, task_numa_work); /* TODO: move this into sched_fork() */
2251 task_work_add(curr, work, true); 2251 task_work_add(curr, work, true);
2252 } 2252 }
2253 } 2253 }
2254 } 2254 }
2255 #else 2255 #else
2256 static void task_tick_numa(struct rq *rq, struct task_struct *curr) 2256 static void task_tick_numa(struct rq *rq, struct task_struct *curr)
2257 { 2257 {
2258 } 2258 }
2259 2259
2260 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p) 2260 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p)
2261 { 2261 {
2262 } 2262 }
2263 2263
2264 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p) 2264 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p)
2265 { 2265 {
2266 } 2266 }
2267 #endif /* CONFIG_NUMA_BALANCING */ 2267 #endif /* CONFIG_NUMA_BALANCING */
2268 2268
2269 static void 2269 static void
2270 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se) 2270 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se)
2271 { 2271 {
2272 update_load_add(&cfs_rq->load, se->load.weight); 2272 update_load_add(&cfs_rq->load, se->load.weight);
2273 if (!parent_entity(se)) 2273 if (!parent_entity(se))
2274 update_load_add(&rq_of(cfs_rq)->load, se->load.weight); 2274 update_load_add(&rq_of(cfs_rq)->load, se->load.weight);
2275 #ifdef CONFIG_SMP 2275 #ifdef CONFIG_SMP
2276 if (entity_is_task(se)) { 2276 if (entity_is_task(se)) {
2277 struct rq *rq = rq_of(cfs_rq); 2277 struct rq *rq = rq_of(cfs_rq);
2278 2278
2279 account_numa_enqueue(rq, task_of(se)); 2279 account_numa_enqueue(rq, task_of(se));
2280 list_add(&se->group_node, &rq->cfs_tasks); 2280 list_add(&se->group_node, &rq->cfs_tasks);
2281 } 2281 }
2282 #endif 2282 #endif
2283 cfs_rq->nr_running++; 2283 cfs_rq->nr_running++;
2284 } 2284 }
2285 2285
2286 static void 2286 static void
2287 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se) 2287 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se)
2288 { 2288 {
2289 update_load_sub(&cfs_rq->load, se->load.weight); 2289 update_load_sub(&cfs_rq->load, se->load.weight);
2290 if (!parent_entity(se)) 2290 if (!parent_entity(se))
2291 update_load_sub(&rq_of(cfs_rq)->load, se->load.weight); 2291 update_load_sub(&rq_of(cfs_rq)->load, se->load.weight);
2292 if (entity_is_task(se)) { 2292 if (entity_is_task(se)) {
2293 account_numa_dequeue(rq_of(cfs_rq), task_of(se)); 2293 account_numa_dequeue(rq_of(cfs_rq), task_of(se));
2294 list_del_init(&se->group_node); 2294 list_del_init(&se->group_node);
2295 } 2295 }
2296 cfs_rq->nr_running--; 2296 cfs_rq->nr_running--;
2297 } 2297 }
2298 2298
2299 #ifdef CONFIG_FAIR_GROUP_SCHED 2299 #ifdef CONFIG_FAIR_GROUP_SCHED
2300 # ifdef CONFIG_SMP 2300 # ifdef CONFIG_SMP
2301 static inline long calc_tg_weight(struct task_group *tg, struct cfs_rq *cfs_rq) 2301 static inline long calc_tg_weight(struct task_group *tg, struct cfs_rq *cfs_rq)
2302 { 2302 {
2303 long tg_weight; 2303 long tg_weight;
2304 2304
2305 /* 2305 /*
2306 * Use this CPU's actual weight instead of the last load_contribution 2306 * Use this CPU's actual weight instead of the last load_contribution
2307 * to gain a more accurate current total weight. See 2307 * to gain a more accurate current total weight. See
2308 * update_cfs_rq_load_contribution(). 2308 * update_cfs_rq_load_contribution().
2309 */ 2309 */
2310 tg_weight = atomic_long_read(&tg->load_avg); 2310 tg_weight = atomic_long_read(&tg->load_avg);
2311 tg_weight -= cfs_rq->tg_load_contrib; 2311 tg_weight -= cfs_rq->tg_load_contrib;
2312 tg_weight += cfs_rq->load.weight; 2312 tg_weight += cfs_rq->load.weight;
2313 2313
2314 return tg_weight; 2314 return tg_weight;
2315 } 2315 }
2316 2316
2317 static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg) 2317 static long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
2318 { 2318 {
2319 long tg_weight, load, shares; 2319 long tg_weight, load, shares;
2320 2320
2321 tg_weight = calc_tg_weight(tg, cfs_rq); 2321 tg_weight = calc_tg_weight(tg, cfs_rq);
2322 load = cfs_rq->load.weight; 2322 load = cfs_rq->load.weight;
2323 2323
2324 shares = (tg->shares * load); 2324 shares = (tg->shares * load);
2325 if (tg_weight) 2325 if (tg_weight)
2326 shares /= tg_weight; 2326 shares /= tg_weight;
2327 2327
2328 if (shares < MIN_SHARES) 2328 if (shares < MIN_SHARES)
2329 shares = MIN_SHARES; 2329 shares = MIN_SHARES;
2330 if (shares > tg->shares) 2330 if (shares > tg->shares)
2331 shares = tg->shares; 2331 shares = tg->shares;
2332 2332
2333 return shares; 2333 return shares;
2334 } 2334 }
2335 # else /* CONFIG_SMP */ 2335 # else /* CONFIG_SMP */
2336 static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg) 2336 static inline long calc_cfs_shares(struct cfs_rq *cfs_rq, struct task_group *tg)
2337 { 2337 {
2338 return tg->shares; 2338 return tg->shares;
2339 } 2339 }
2340 # endif /* CONFIG_SMP */ 2340 # endif /* CONFIG_SMP */
2341 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, 2341 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se,
2342 unsigned long weight) 2342 unsigned long weight)
2343 { 2343 {
2344 if (se->on_rq) { 2344 if (se->on_rq) {
2345 /* commit outstanding execution time */ 2345 /* commit outstanding execution time */
2346 if (cfs_rq->curr == se) 2346 if (cfs_rq->curr == se)
2347 update_curr(cfs_rq); 2347 update_curr(cfs_rq);
2348 account_entity_dequeue(cfs_rq, se); 2348 account_entity_dequeue(cfs_rq, se);
2349 } 2349 }
2350 2350
2351 update_load_set(&se->load, weight); 2351 update_load_set(&se->load, weight);
2352 2352
2353 if (se->on_rq) 2353 if (se->on_rq)
2354 account_entity_enqueue(cfs_rq, se); 2354 account_entity_enqueue(cfs_rq, se);
2355 } 2355 }
2356 2356
2357 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq); 2357 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq);
2358 2358
2359 static void update_cfs_shares(struct cfs_rq *cfs_rq) 2359 static void update_cfs_shares(struct cfs_rq *cfs_rq)
2360 { 2360 {
2361 struct task_group *tg; 2361 struct task_group *tg;
2362 struct sched_entity *se; 2362 struct sched_entity *se;
2363 long shares; 2363 long shares;
2364 2364
2365 tg = cfs_rq->tg; 2365 tg = cfs_rq->tg;
2366 se = tg->se[cpu_of(rq_of(cfs_rq))]; 2366 se = tg->se[cpu_of(rq_of(cfs_rq))];
2367 if (!se || throttled_hierarchy(cfs_rq)) 2367 if (!se || throttled_hierarchy(cfs_rq))
2368 return; 2368 return;
2369 #ifndef CONFIG_SMP 2369 #ifndef CONFIG_SMP
2370 if (likely(se->load.weight == tg->shares)) 2370 if (likely(se->load.weight == tg->shares))
2371 return; 2371 return;
2372 #endif 2372 #endif
2373 shares = calc_cfs_shares(cfs_rq, tg); 2373 shares = calc_cfs_shares(cfs_rq, tg);
2374 2374
2375 reweight_entity(cfs_rq_of(se), se, shares); 2375 reweight_entity(cfs_rq_of(se), se, shares);
2376 } 2376 }
2377 #else /* CONFIG_FAIR_GROUP_SCHED */ 2377 #else /* CONFIG_FAIR_GROUP_SCHED */
2378 static inline void update_cfs_shares(struct cfs_rq *cfs_rq) 2378 static inline void update_cfs_shares(struct cfs_rq *cfs_rq)
2379 { 2379 {
2380 } 2380 }
2381 #endif /* CONFIG_FAIR_GROUP_SCHED */ 2381 #endif /* CONFIG_FAIR_GROUP_SCHED */
2382 2382
2383 #ifdef CONFIG_SMP 2383 #ifdef CONFIG_SMP
2384 /* 2384 /*
2385 * We choose a half-life close to 1 scheduling period. 2385 * We choose a half-life close to 1 scheduling period.
2386 * Note: The tables below are dependent on this value. 2386 * Note: The tables below are dependent on this value.
2387 */ 2387 */
2388 #define LOAD_AVG_PERIOD 32 2388 #define LOAD_AVG_PERIOD 32
2389 #define LOAD_AVG_MAX 47742 /* maximum possible load avg */ 2389 #define LOAD_AVG_MAX 47742 /* maximum possible load avg */
2390 #define LOAD_AVG_MAX_N 345 /* number of full periods to produce LOAD_MAX_AVG */ 2390 #define LOAD_AVG_MAX_N 345 /* number of full periods to produce LOAD_MAX_AVG */
2391 2391
2392 /* Precomputed fixed inverse multiplies for multiplication by y^n */ 2392 /* Precomputed fixed inverse multiplies for multiplication by y^n */
2393 static const u32 runnable_avg_yN_inv[] = { 2393 static const u32 runnable_avg_yN_inv[] = {
2394 0xffffffff, 0xfa83b2da, 0xf5257d14, 0xefe4b99a, 0xeac0c6e6, 0xe5b906e6, 2394 0xffffffff, 0xfa83b2da, 0xf5257d14, 0xefe4b99a, 0xeac0c6e6, 0xe5b906e6,
2395 0xe0ccdeeb, 0xdbfbb796, 0xd744fcc9, 0xd2a81d91, 0xce248c14, 0xc9b9bd85, 2395 0xe0ccdeeb, 0xdbfbb796, 0xd744fcc9, 0xd2a81d91, 0xce248c14, 0xc9b9bd85,
2396 0xc5672a10, 0xc12c4cc9, 0xbd08a39e, 0xb8fbaf46, 0xb504f333, 0xb123f581, 2396 0xc5672a10, 0xc12c4cc9, 0xbd08a39e, 0xb8fbaf46, 0xb504f333, 0xb123f581,
2397 0xad583ee9, 0xa9a15ab4, 0xa5fed6a9, 0xa2704302, 0x9ef5325f, 0x9b8d39b9, 2397 0xad583ee9, 0xa9a15ab4, 0xa5fed6a9, 0xa2704302, 0x9ef5325f, 0x9b8d39b9,
2398 0x9837f050, 0x94f4efa8, 0x91c3d373, 0x8ea4398a, 0x8b95c1e3, 0x88980e80, 2398 0x9837f050, 0x94f4efa8, 0x91c3d373, 0x8ea4398a, 0x8b95c1e3, 0x88980e80,
2399 0x85aac367, 0x82cd8698, 2399 0x85aac367, 0x82cd8698,
2400 }; 2400 };
2401 2401
2402 /* 2402 /*
2403 * Precomputed \Sum y^k { 1<=k<=n }. These are floor(true_value) to prevent 2403 * Precomputed \Sum y^k { 1<=k<=n }. These are floor(true_value) to prevent
2404 * over-estimates when re-combining. 2404 * over-estimates when re-combining.
2405 */ 2405 */
2406 static const u32 runnable_avg_yN_sum[] = { 2406 static const u32 runnable_avg_yN_sum[] = {
2407 0, 1002, 1982, 2941, 3880, 4798, 5697, 6576, 7437, 8279, 9103, 2407 0, 1002, 1982, 2941, 3880, 4798, 5697, 6576, 7437, 8279, 9103,
2408 9909,10698,11470,12226,12966,13690,14398,15091,15769,16433,17082, 2408 9909,10698,11470,12226,12966,13690,14398,15091,15769,16433,17082,
2409 17718,18340,18949,19545,20128,20698,21256,21802,22336,22859,23371, 2409 17718,18340,18949,19545,20128,20698,21256,21802,22336,22859,23371,
2410 }; 2410 };
2411 2411
2412 /* 2412 /*
2413 * Approximate: 2413 * Approximate:
2414 * val * y^n, where y^32 ~= 0.5 (~1 scheduling period) 2414 * val * y^n, where y^32 ~= 0.5 (~1 scheduling period)
2415 */ 2415 */
2416 static __always_inline u64 decay_load(u64 val, u64 n) 2416 static __always_inline u64 decay_load(u64 val, u64 n)
2417 { 2417 {
2418 unsigned int local_n; 2418 unsigned int local_n;
2419 2419
2420 if (!n) 2420 if (!n)
2421 return val; 2421 return val;
2422 else if (unlikely(n > LOAD_AVG_PERIOD * 63)) 2422 else if (unlikely(n > LOAD_AVG_PERIOD * 63))
2423 return 0; 2423 return 0;
2424 2424
2425 /* after bounds checking we can collapse to 32-bit */ 2425 /* after bounds checking we can collapse to 32-bit */
2426 local_n = n; 2426 local_n = n;
2427 2427
2428 /* 2428 /*
2429 * As y^PERIOD = 1/2, we can combine 2429 * As y^PERIOD = 1/2, we can combine
2430 * y^n = 1/2^(n/PERIOD) * y^(n%PERIOD) 2430 * y^n = 1/2^(n/PERIOD) * y^(n%PERIOD)
2431 * With a look-up table which covers y^n (n<PERIOD) 2431 * With a look-up table which covers y^n (n<PERIOD)
2432 * 2432 *
2433 * To achieve constant time decay_load. 2433 * To achieve constant time decay_load.
2434 */ 2434 */
2435 if (unlikely(local_n >= LOAD_AVG_PERIOD)) { 2435 if (unlikely(local_n >= LOAD_AVG_PERIOD)) {
2436 val >>= local_n / LOAD_AVG_PERIOD; 2436 val >>= local_n / LOAD_AVG_PERIOD;
2437 local_n %= LOAD_AVG_PERIOD; 2437 local_n %= LOAD_AVG_PERIOD;
2438 } 2438 }
2439 2439
2440 val *= runnable_avg_yN_inv[local_n]; 2440 val *= runnable_avg_yN_inv[local_n];
2441 /* We don't use SRR here since we always want to round down. */ 2441 /* We don't use SRR here since we always want to round down. */
2442 return val >> 32; 2442 return val >> 32;
2443 } 2443 }
2444 2444
2445 /* 2445 /*
2446 * For updates fully spanning n periods, the contribution to runnable 2446 * For updates fully spanning n periods, the contribution to runnable
2447 * average will be: \Sum 1024*y^n 2447 * average will be: \Sum 1024*y^n
2448 * 2448 *
2449 * We can compute this reasonably efficiently by combining: 2449 * We can compute this reasonably efficiently by combining:
2450 * y^PERIOD = 1/2 with precomputed \Sum 1024*y^n {for n <PERIOD} 2450 * y^PERIOD = 1/2 with precomputed \Sum 1024*y^n {for n <PERIOD}
2451 */ 2451 */
2452 static u32 __compute_runnable_contrib(u64 n) 2452 static u32 __compute_runnable_contrib(u64 n)
2453 { 2453 {
2454 u32 contrib = 0; 2454 u32 contrib = 0;
2455 2455
2456 if (likely(n <= LOAD_AVG_PERIOD)) 2456 if (likely(n <= LOAD_AVG_PERIOD))
2457 return runnable_avg_yN_sum[n]; 2457 return runnable_avg_yN_sum[n];
2458 else if (unlikely(n >= LOAD_AVG_MAX_N)) 2458 else if (unlikely(n >= LOAD_AVG_MAX_N))
2459 return LOAD_AVG_MAX; 2459 return LOAD_AVG_MAX;
2460 2460
2461 /* Compute \Sum k^n combining precomputed values for k^i, \Sum k^j */ 2461 /* Compute \Sum k^n combining precomputed values for k^i, \Sum k^j */
2462 do { 2462 do {
2463 contrib /= 2; /* y^LOAD_AVG_PERIOD = 1/2 */ 2463 contrib /= 2; /* y^LOAD_AVG_PERIOD = 1/2 */
2464 contrib += runnable_avg_yN_sum[LOAD_AVG_PERIOD]; 2464 contrib += runnable_avg_yN_sum[LOAD_AVG_PERIOD];
2465 2465
2466 n -= LOAD_AVG_PERIOD; 2466 n -= LOAD_AVG_PERIOD;
2467 } while (n > LOAD_AVG_PERIOD); 2467 } while (n > LOAD_AVG_PERIOD);
2468 2468
2469 contrib = decay_load(contrib, n); 2469 contrib = decay_load(contrib, n);
2470 return contrib + runnable_avg_yN_sum[n]; 2470 return contrib + runnable_avg_yN_sum[n];
2471 } 2471 }
2472 2472
2473 /* 2473 /*
2474 * We can represent the historical contribution to runnable average as the 2474 * We can represent the historical contribution to runnable average as the
2475 * coefficients of a geometric series. To do this we sub-divide our runnable 2475 * coefficients of a geometric series. To do this we sub-divide our runnable
2476 * history into segments of approximately 1ms (1024us); label the segment that 2476 * history into segments of approximately 1ms (1024us); label the segment that
2477 * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g. 2477 * occurred N-ms ago p_N, with p_0 corresponding to the current period, e.g.
2478 * 2478 *
2479 * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ... 2479 * [<- 1024us ->|<- 1024us ->|<- 1024us ->| ...
2480 * p0 p1 p2 2480 * p0 p1 p2
2481 * (now) (~1ms ago) (~2ms ago) 2481 * (now) (~1ms ago) (~2ms ago)
2482 * 2482 *
2483 * Let u_i denote the fraction of p_i that the entity was runnable. 2483 * Let u_i denote the fraction of p_i that the entity was runnable.
2484 * 2484 *
2485 * We then designate the fractions u_i as our co-efficients, yielding the 2485 * We then designate the fractions u_i as our co-efficients, yielding the
2486 * following representation of historical load: 2486 * following representation of historical load:
2487 * u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ... 2487 * u_0 + u_1*y + u_2*y^2 + u_3*y^3 + ...
2488 * 2488 *
2489 * We choose y based on the with of a reasonably scheduling period, fixing: 2489 * We choose y based on the with of a reasonably scheduling period, fixing:
2490 * y^32 = 0.5 2490 * y^32 = 0.5
2491 * 2491 *
2492 * This means that the contribution to load ~32ms ago (u_32) will be weighted 2492 * This means that the contribution to load ~32ms ago (u_32) will be weighted
2493 * approximately half as much as the contribution to load within the last ms 2493 * approximately half as much as the contribution to load within the last ms
2494 * (u_0). 2494 * (u_0).
2495 * 2495 *
2496 * When a period "rolls over" and we have new u_0`, multiplying the previous 2496 * When a period "rolls over" and we have new u_0`, multiplying the previous
2497 * sum again by y is sufficient to update: 2497 * sum again by y is sufficient to update:
2498 * load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... ) 2498 * load_avg = u_0` + y*(u_0 + u_1*y + u_2*y^2 + ... )
2499 * = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}] 2499 * = u_0 + u_1*y + u_2*y^2 + ... [re-labeling u_i --> u_{i+1}]
2500 */ 2500 */
2501 static __always_inline int __update_entity_runnable_avg(u64 now, 2501 static __always_inline int __update_entity_runnable_avg(u64 now,
2502 struct sched_avg *sa, 2502 struct sched_avg *sa,
2503 int runnable) 2503 int runnable)
2504 { 2504 {
2505 u64 delta, periods; 2505 u64 delta, periods;
2506 u32 runnable_contrib; 2506 u32 runnable_contrib;
2507 int delta_w, decayed = 0; 2507 int delta_w, decayed = 0;
2508 2508
2509 delta = now - sa->last_runnable_update; 2509 delta = now - sa->last_runnable_update;
2510 /* 2510 /*
2511 * This should only happen when time goes backwards, which it 2511 * This should only happen when time goes backwards, which it
2512 * unfortunately does during sched clock init when we swap over to TSC. 2512 * unfortunately does during sched clock init when we swap over to TSC.
2513 */ 2513 */
2514 if ((s64)delta < 0) { 2514 if ((s64)delta < 0) {
2515 sa->last_runnable_update = now; 2515 sa->last_runnable_update = now;
2516 return 0; 2516 return 0;
2517 } 2517 }
2518 2518
2519 /* 2519 /*
2520 * Use 1024ns as the unit of measurement since it's a reasonable 2520 * Use 1024ns as the unit of measurement since it's a reasonable
2521 * approximation of 1us and fast to compute. 2521 * approximation of 1us and fast to compute.
2522 */ 2522 */
2523 delta >>= 10; 2523 delta >>= 10;
2524 if (!delta) 2524 if (!delta)
2525 return 0; 2525 return 0;
2526 sa->last_runnable_update = now; 2526 sa->last_runnable_update = now;
2527 2527
2528 /* delta_w is the amount already accumulated against our next period */ 2528 /* delta_w is the amount already accumulated against our next period */
2529 delta_w = sa->runnable_avg_period % 1024; 2529 delta_w = sa->runnable_avg_period % 1024;
2530 if (delta + delta_w >= 1024) { 2530 if (delta + delta_w >= 1024) {
2531 /* period roll-over */ 2531 /* period roll-over */
2532 decayed = 1; 2532 decayed = 1;
2533 2533
2534 /* 2534 /*
2535 * Now that we know we're crossing a period boundary, figure 2535 * Now that we know we're crossing a period boundary, figure
2536 * out how much from delta we need to complete the current 2536 * out how much from delta we need to complete the current
2537 * period and accrue it. 2537 * period and accrue it.
2538 */ 2538 */
2539 delta_w = 1024 - delta_w; 2539 delta_w = 1024 - delta_w;
2540 if (runnable) 2540 if (runnable)
2541 sa->runnable_avg_sum += delta_w; 2541 sa->runnable_avg_sum += delta_w;
2542 sa->runnable_avg_period += delta_w; 2542 sa->runnable_avg_period += delta_w;
2543 2543
2544 delta -= delta_w; 2544 delta -= delta_w;
2545 2545
2546 /* Figure out how many additional periods this update spans */ 2546 /* Figure out how many additional periods this update spans */
2547 periods = delta / 1024; 2547 periods = delta / 1024;
2548 delta %= 1024; 2548 delta %= 1024;
2549 2549
2550 sa->runnable_avg_sum = decay_load(sa->runnable_avg_sum, 2550 sa->runnable_avg_sum = decay_load(sa->runnable_avg_sum,
2551 periods + 1); 2551 periods + 1);
2552 sa->runnable_avg_period = decay_load(sa->runnable_avg_period, 2552 sa->runnable_avg_period = decay_load(sa->runnable_avg_period,
2553 periods + 1); 2553 periods + 1);
2554 2554
2555 /* Efficiently calculate \sum (1..n_period) 1024*y^i */ 2555 /* Efficiently calculate \sum (1..n_period) 1024*y^i */
2556 runnable_contrib = __compute_runnable_contrib(periods); 2556 runnable_contrib = __compute_runnable_contrib(periods);
2557 if (runnable) 2557 if (runnable)
2558 sa->runnable_avg_sum += runnable_contrib; 2558 sa->runnable_avg_sum += runnable_contrib;
2559 sa->runnable_avg_period += runnable_contrib; 2559 sa->runnable_avg_period += runnable_contrib;
2560 } 2560 }
2561 2561
2562 /* Remainder of delta accrued against u_0` */ 2562 /* Remainder of delta accrued against u_0` */
2563 if (runnable) 2563 if (runnable)
2564 sa->runnable_avg_sum += delta; 2564 sa->runnable_avg_sum += delta;
2565 sa->runnable_avg_period += delta; 2565 sa->runnable_avg_period += delta;
2566 2566
2567 return decayed; 2567 return decayed;
2568 } 2568 }
2569 2569
2570 /* Synchronize an entity's decay with its parenting cfs_rq.*/ 2570 /* Synchronize an entity's decay with its parenting cfs_rq.*/
2571 static inline u64 __synchronize_entity_decay(struct sched_entity *se) 2571 static inline u64 __synchronize_entity_decay(struct sched_entity *se)
2572 { 2572 {
2573 struct cfs_rq *cfs_rq = cfs_rq_of(se); 2573 struct cfs_rq *cfs_rq = cfs_rq_of(se);
2574 u64 decays = atomic64_read(&cfs_rq->decay_counter); 2574 u64 decays = atomic64_read(&cfs_rq->decay_counter);
2575 2575
2576 decays -= se->avg.decay_count; 2576 decays -= se->avg.decay_count;
2577 if (!decays) 2577 if (!decays)
2578 return 0; 2578 return 0;
2579 2579
2580 se->avg.load_avg_contrib = decay_load(se->avg.load_avg_contrib, decays); 2580 se->avg.load_avg_contrib = decay_load(se->avg.load_avg_contrib, decays);
2581 se->avg.decay_count = 0; 2581 se->avg.decay_count = 0;
2582 2582
2583 return decays; 2583 return decays;
2584 } 2584 }
2585 2585
2586 #ifdef CONFIG_FAIR_GROUP_SCHED 2586 #ifdef CONFIG_FAIR_GROUP_SCHED
2587 static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq, 2587 static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq,
2588 int force_update) 2588 int force_update)
2589 { 2589 {
2590 struct task_group *tg = cfs_rq->tg; 2590 struct task_group *tg = cfs_rq->tg;
2591 long tg_contrib; 2591 long tg_contrib;
2592 2592
2593 tg_contrib = cfs_rq->runnable_load_avg + cfs_rq->blocked_load_avg; 2593 tg_contrib = cfs_rq->runnable_load_avg + cfs_rq->blocked_load_avg;
2594 tg_contrib -= cfs_rq->tg_load_contrib; 2594 tg_contrib -= cfs_rq->tg_load_contrib;
2595 2595
2596 if (!tg_contrib) 2596 if (!tg_contrib)
2597 return; 2597 return;
2598 2598
2599 if (force_update || abs(tg_contrib) > cfs_rq->tg_load_contrib / 8) { 2599 if (force_update || abs(tg_contrib) > cfs_rq->tg_load_contrib / 8) {
2600 atomic_long_add(tg_contrib, &tg->load_avg); 2600 atomic_long_add(tg_contrib, &tg->load_avg);
2601 cfs_rq->tg_load_contrib += tg_contrib; 2601 cfs_rq->tg_load_contrib += tg_contrib;
2602 } 2602 }
2603 } 2603 }
2604 2604
2605 /* 2605 /*
2606 * Aggregate cfs_rq runnable averages into an equivalent task_group 2606 * Aggregate cfs_rq runnable averages into an equivalent task_group
2607 * representation for computing load contributions. 2607 * representation for computing load contributions.
2608 */ 2608 */
2609 static inline void __update_tg_runnable_avg(struct sched_avg *sa, 2609 static inline void __update_tg_runnable_avg(struct sched_avg *sa,
2610 struct cfs_rq *cfs_rq) 2610 struct cfs_rq *cfs_rq)
2611 { 2611 {
2612 struct task_group *tg = cfs_rq->tg; 2612 struct task_group *tg = cfs_rq->tg;
2613 long contrib; 2613 long contrib;
2614 2614
2615 /* The fraction of a cpu used by this cfs_rq */ 2615 /* The fraction of a cpu used by this cfs_rq */
2616 contrib = div_u64((u64)sa->runnable_avg_sum << NICE_0_SHIFT, 2616 contrib = div_u64((u64)sa->runnable_avg_sum << NICE_0_SHIFT,
2617 sa->runnable_avg_period + 1); 2617 sa->runnable_avg_period + 1);
2618 contrib -= cfs_rq->tg_runnable_contrib; 2618 contrib -= cfs_rq->tg_runnable_contrib;
2619 2619
2620 if (abs(contrib) > cfs_rq->tg_runnable_contrib / 64) { 2620 if (abs(contrib) > cfs_rq->tg_runnable_contrib / 64) {
2621 atomic_add(contrib, &tg->runnable_avg); 2621 atomic_add(contrib, &tg->runnable_avg);
2622 cfs_rq->tg_runnable_contrib += contrib; 2622 cfs_rq->tg_runnable_contrib += contrib;
2623 } 2623 }
2624 } 2624 }
2625 2625
2626 static inline void __update_group_entity_contrib(struct sched_entity *se) 2626 static inline void __update_group_entity_contrib(struct sched_entity *se)
2627 { 2627 {
2628 struct cfs_rq *cfs_rq = group_cfs_rq(se); 2628 struct cfs_rq *cfs_rq = group_cfs_rq(se);
2629 struct task_group *tg = cfs_rq->tg; 2629 struct task_group *tg = cfs_rq->tg;
2630 int runnable_avg; 2630 int runnable_avg;
2631 2631
2632 u64 contrib; 2632 u64 contrib;
2633 2633
2634 contrib = cfs_rq->tg_load_contrib * tg->shares; 2634 contrib = cfs_rq->tg_load_contrib * tg->shares;
2635 se->avg.load_avg_contrib = div_u64(contrib, 2635 se->avg.load_avg_contrib = div_u64(contrib,
2636 atomic_long_read(&tg->load_avg) + 1); 2636 atomic_long_read(&tg->load_avg) + 1);
2637 2637
2638 /* 2638 /*
2639 * For group entities we need to compute a correction term in the case 2639 * For group entities we need to compute a correction term in the case
2640 * that they are consuming <1 cpu so that we would contribute the same 2640 * that they are consuming <1 cpu so that we would contribute the same
2641 * load as a task of equal weight. 2641 * load as a task of equal weight.
2642 * 2642 *
2643 * Explicitly co-ordinating this measurement would be expensive, but 2643 * Explicitly co-ordinating this measurement would be expensive, but
2644 * fortunately the sum of each cpus contribution forms a usable 2644 * fortunately the sum of each cpus contribution forms a usable
2645 * lower-bound on the true value. 2645 * lower-bound on the true value.
2646 * 2646 *
2647 * Consider the aggregate of 2 contributions. Either they are disjoint 2647 * Consider the aggregate of 2 contributions. Either they are disjoint
2648 * (and the sum represents true value) or they are disjoint and we are 2648 * (and the sum represents true value) or they are disjoint and we are
2649 * understating by the aggregate of their overlap. 2649 * understating by the aggregate of their overlap.
2650 * 2650 *
2651 * Extending this to N cpus, for a given overlap, the maximum amount we 2651 * Extending this to N cpus, for a given overlap, the maximum amount we
2652 * understand is then n_i(n_i+1)/2 * w_i where n_i is the number of 2652 * understand is then n_i(n_i+1)/2 * w_i where n_i is the number of
2653 * cpus that overlap for this interval and w_i is the interval width. 2653 * cpus that overlap for this interval and w_i is the interval width.
2654 * 2654 *
2655 * On a small machine; the first term is well-bounded which bounds the 2655 * On a small machine; the first term is well-bounded which bounds the
2656 * total error since w_i is a subset of the period. Whereas on a 2656 * total error since w_i is a subset of the period. Whereas on a
2657 * larger machine, while this first term can be larger, if w_i is the 2657 * larger machine, while this first term can be larger, if w_i is the
2658 * of consequential size guaranteed to see n_i*w_i quickly converge to 2658 * of consequential size guaranteed to see n_i*w_i quickly converge to
2659 * our upper bound of 1-cpu. 2659 * our upper bound of 1-cpu.
2660 */ 2660 */
2661 runnable_avg = atomic_read(&tg->runnable_avg); 2661 runnable_avg = atomic_read(&tg->runnable_avg);
2662 if (runnable_avg < NICE_0_LOAD) { 2662 if (runnable_avg < NICE_0_LOAD) {
2663 se->avg.load_avg_contrib *= runnable_avg; 2663 se->avg.load_avg_contrib *= runnable_avg;
2664 se->avg.load_avg_contrib >>= NICE_0_SHIFT; 2664 se->avg.load_avg_contrib >>= NICE_0_SHIFT;
2665 } 2665 }
2666 } 2666 }
2667 2667
2668 static inline void update_rq_runnable_avg(struct rq *rq, int runnable) 2668 static inline void update_rq_runnable_avg(struct rq *rq, int runnable)
2669 { 2669 {
2670 __update_entity_runnable_avg(rq_clock_task(rq), &rq->avg, runnable); 2670 __update_entity_runnable_avg(rq_clock_task(rq), &rq->avg, runnable);
2671 __update_tg_runnable_avg(&rq->avg, &rq->cfs); 2671 __update_tg_runnable_avg(&rq->avg, &rq->cfs);
2672 } 2672 }
2673 #else /* CONFIG_FAIR_GROUP_SCHED */ 2673 #else /* CONFIG_FAIR_GROUP_SCHED */
2674 static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq, 2674 static inline void __update_cfs_rq_tg_load_contrib(struct cfs_rq *cfs_rq,
2675 int force_update) {} 2675 int force_update) {}
2676 static inline void __update_tg_runnable_avg(struct sched_avg *sa, 2676 static inline void __update_tg_runnable_avg(struct sched_avg *sa,
2677 struct cfs_rq *cfs_rq) {} 2677 struct cfs_rq *cfs_rq) {}
2678 static inline void __update_group_entity_contrib(struct sched_entity *se) {} 2678 static inline void __update_group_entity_contrib(struct sched_entity *se) {}
2679 static inline void update_rq_runnable_avg(struct rq *rq, int runnable) {} 2679 static inline void update_rq_runnable_avg(struct rq *rq, int runnable) {}
2680 #endif /* CONFIG_FAIR_GROUP_SCHED */ 2680 #endif /* CONFIG_FAIR_GROUP_SCHED */
2681 2681
2682 static inline void __update_task_entity_contrib(struct sched_entity *se) 2682 static inline void __update_task_entity_contrib(struct sched_entity *se)
2683 { 2683 {
2684 u32 contrib; 2684 u32 contrib;
2685 2685
2686 /* avoid overflowing a 32-bit type w/ SCHED_LOAD_SCALE */ 2686 /* avoid overflowing a 32-bit type w/ SCHED_LOAD_SCALE */
2687 contrib = se->avg.runnable_avg_sum * scale_load_down(se->load.weight); 2687 contrib = se->avg.runnable_avg_sum * scale_load_down(se->load.weight);
2688 contrib /= (se->avg.runnable_avg_period + 1); 2688 contrib /= (se->avg.runnable_avg_period + 1);
2689 se->avg.load_avg_contrib = scale_load(contrib); 2689 se->avg.load_avg_contrib = scale_load(contrib);
2690 } 2690 }
2691 2691
2692 /* Compute the current contribution to load_avg by se, return any delta */ 2692 /* Compute the current contribution to load_avg by se, return any delta */
2693 static long __update_entity_load_avg_contrib(struct sched_entity *se) 2693 static long __update_entity_load_avg_contrib(struct sched_entity *se)
2694 { 2694 {
2695 long old_contrib = se->avg.load_avg_contrib; 2695 long old_contrib = se->avg.load_avg_contrib;
2696 2696
2697 if (entity_is_task(se)) { 2697 if (entity_is_task(se)) {
2698 __update_task_entity_contrib(se); 2698 __update_task_entity_contrib(se);
2699 } else { 2699 } else {
2700 __update_tg_runnable_avg(&se->avg, group_cfs_rq(se)); 2700 __update_tg_runnable_avg(&se->avg, group_cfs_rq(se));
2701 __update_group_entity_contrib(se); 2701 __update_group_entity_contrib(se);
2702 } 2702 }
2703 2703
2704 return se->avg.load_avg_contrib - old_contrib; 2704 return se->avg.load_avg_contrib - old_contrib;
2705 } 2705 }
2706 2706
2707 static inline void subtract_blocked_load_contrib(struct cfs_rq *cfs_rq, 2707 static inline void subtract_blocked_load_contrib(struct cfs_rq *cfs_rq,
2708 long load_contrib) 2708 long load_contrib)
2709 { 2709 {
2710 if (likely(load_contrib < cfs_rq->blocked_load_avg)) 2710 if (likely(load_contrib < cfs_rq->blocked_load_avg))
2711 cfs_rq->blocked_load_avg -= load_contrib; 2711 cfs_rq->blocked_load_avg -= load_contrib;
2712 else 2712 else
2713 cfs_rq->blocked_load_avg = 0; 2713 cfs_rq->blocked_load_avg = 0;
2714 } 2714 }
2715 2715
2716 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq); 2716 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq);
2717 2717
2718 /* Update a sched_entity's runnable average */ 2718 /* Update a sched_entity's runnable average */
2719 static inline void update_entity_load_avg(struct sched_entity *se, 2719 static inline void update_entity_load_avg(struct sched_entity *se,
2720 int update_cfs_rq) 2720 int update_cfs_rq)
2721 { 2721 {
2722 struct cfs_rq *cfs_rq = cfs_rq_of(se); 2722 struct cfs_rq *cfs_rq = cfs_rq_of(se);
2723 long contrib_delta; 2723 long contrib_delta;
2724 u64 now; 2724 u64 now;
2725 2725
2726 /* 2726 /*
2727 * For a group entity we need to use their owned cfs_rq_clock_task() in 2727 * For a group entity we need to use their owned cfs_rq_clock_task() in
2728 * case they are the parent of a throttled hierarchy. 2728 * case they are the parent of a throttled hierarchy.
2729 */ 2729 */
2730 if (entity_is_task(se)) 2730 if (entity_is_task(se))
2731 now = cfs_rq_clock_task(cfs_rq); 2731 now = cfs_rq_clock_task(cfs_rq);
2732 else 2732 else
2733 now = cfs_rq_clock_task(group_cfs_rq(se)); 2733 now = cfs_rq_clock_task(group_cfs_rq(se));
2734 2734
2735 if (!__update_entity_runnable_avg(now, &se->avg, se->on_rq)) 2735 if (!__update_entity_runnable_avg(now, &se->avg, se->on_rq))
2736 return; 2736 return;
2737 2737
2738 contrib_delta = __update_entity_load_avg_contrib(se); 2738 contrib_delta = __update_entity_load_avg_contrib(se);
2739 2739
2740 if (!update_cfs_rq) 2740 if (!update_cfs_rq)
2741 return; 2741 return;
2742 2742
2743 if (se->on_rq) 2743 if (se->on_rq)
2744 cfs_rq->runnable_load_avg += contrib_delta; 2744 cfs_rq->runnable_load_avg += contrib_delta;
2745 else 2745 else
2746 subtract_blocked_load_contrib(cfs_rq, -contrib_delta); 2746 subtract_blocked_load_contrib(cfs_rq, -contrib_delta);
2747 } 2747 }
2748 2748
2749 /* 2749 /*
2750 * Decay the load contributed by all blocked children and account this so that 2750 * Decay the load contributed by all blocked children and account this so that
2751 * their contribution may appropriately discounted when they wake up. 2751 * their contribution may appropriately discounted when they wake up.
2752 */ 2752 */
2753 static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq, int force_update) 2753 static void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq, int force_update)
2754 { 2754 {
2755 u64 now = cfs_rq_clock_task(cfs_rq) >> 20; 2755 u64 now = cfs_rq_clock_task(cfs_rq) >> 20;
2756 u64 decays; 2756 u64 decays;
2757 2757
2758 decays = now - cfs_rq->last_decay; 2758 decays = now - cfs_rq->last_decay;
2759 if (!decays && !force_update) 2759 if (!decays && !force_update)
2760 return; 2760 return;
2761 2761
2762 if (atomic_long_read(&cfs_rq->removed_load)) { 2762 if (atomic_long_read(&cfs_rq->removed_load)) {
2763 unsigned long removed_load; 2763 unsigned long removed_load;
2764 removed_load = atomic_long_xchg(&cfs_rq->removed_load, 0); 2764 removed_load = atomic_long_xchg(&cfs_rq->removed_load, 0);
2765 subtract_blocked_load_contrib(cfs_rq, removed_load); 2765 subtract_blocked_load_contrib(cfs_rq, removed_load);
2766 } 2766 }
2767 2767
2768 if (decays) { 2768 if (decays) {
2769 cfs_rq->blocked_load_avg = decay_load(cfs_rq->blocked_load_avg, 2769 cfs_rq->blocked_load_avg = decay_load(cfs_rq->blocked_load_avg,
2770 decays); 2770 decays);
2771 atomic64_add(decays, &cfs_rq->decay_counter); 2771 atomic64_add(decays, &cfs_rq->decay_counter);
2772 cfs_rq->last_decay = now; 2772 cfs_rq->last_decay = now;
2773 } 2773 }
2774 2774
2775 __update_cfs_rq_tg_load_contrib(cfs_rq, force_update); 2775 __update_cfs_rq_tg_load_contrib(cfs_rq, force_update);
2776 } 2776 }
2777 2777
2778 /* Add the load generated by se into cfs_rq's child load-average */ 2778 /* Add the load generated by se into cfs_rq's child load-average */
2779 static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq, 2779 static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq,
2780 struct sched_entity *se, 2780 struct sched_entity *se,
2781 int wakeup) 2781 int wakeup)
2782 { 2782 {
2783 /* 2783 /*
2784 * We track migrations using entity decay_count <= 0, on a wake-up 2784 * We track migrations using entity decay_count <= 0, on a wake-up
2785 * migration we use a negative decay count to track the remote decays 2785 * migration we use a negative decay count to track the remote decays
2786 * accumulated while sleeping. 2786 * accumulated while sleeping.
2787 * 2787 *
2788 * Newly forked tasks are enqueued with se->avg.decay_count == 0, they 2788 * Newly forked tasks are enqueued with se->avg.decay_count == 0, they
2789 * are seen by enqueue_entity_load_avg() as a migration with an already 2789 * are seen by enqueue_entity_load_avg() as a migration with an already
2790 * constructed load_avg_contrib. 2790 * constructed load_avg_contrib.
2791 */ 2791 */
2792 if (unlikely(se->avg.decay_count <= 0)) { 2792 if (unlikely(se->avg.decay_count <= 0)) {
2793 se->avg.last_runnable_update = rq_clock_task(rq_of(cfs_rq)); 2793 se->avg.last_runnable_update = rq_clock_task(rq_of(cfs_rq));
2794 if (se->avg.decay_count) { 2794 if (se->avg.decay_count) {
2795 /* 2795 /*
2796 * In a wake-up migration we have to approximate the 2796 * In a wake-up migration we have to approximate the
2797 * time sleeping. This is because we can't synchronize 2797 * time sleeping. This is because we can't synchronize
2798 * clock_task between the two cpus, and it is not 2798 * clock_task between the two cpus, and it is not
2799 * guaranteed to be read-safe. Instead, we can 2799 * guaranteed to be read-safe. Instead, we can
2800 * approximate this using our carried decays, which are 2800 * approximate this using our carried decays, which are
2801 * explicitly atomically readable. 2801 * explicitly atomically readable.
2802 */ 2802 */
2803 se->avg.last_runnable_update -= (-se->avg.decay_count) 2803 se->avg.last_runnable_update -= (-se->avg.decay_count)
2804 << 20; 2804 << 20;
2805 update_entity_load_avg(se, 0); 2805 update_entity_load_avg(se, 0);
2806 /* Indicate that we're now synchronized and on-rq */ 2806 /* Indicate that we're now synchronized and on-rq */
2807 se->avg.decay_count = 0; 2807 se->avg.decay_count = 0;
2808 } 2808 }
2809 wakeup = 0; 2809 wakeup = 0;
2810 } else { 2810 } else {
2811 __synchronize_entity_decay(se); 2811 __synchronize_entity_decay(se);
2812 } 2812 }
2813 2813
2814 /* migrated tasks did not contribute to our blocked load */ 2814 /* migrated tasks did not contribute to our blocked load */
2815 if (wakeup) { 2815 if (wakeup) {
2816 subtract_blocked_load_contrib(cfs_rq, se->avg.load_avg_contrib); 2816 subtract_blocked_load_contrib(cfs_rq, se->avg.load_avg_contrib);
2817 update_entity_load_avg(se, 0); 2817 update_entity_load_avg(se, 0);
2818 } 2818 }
2819 2819
2820 cfs_rq->runnable_load_avg += se->avg.load_avg_contrib; 2820 cfs_rq->runnable_load_avg += se->avg.load_avg_contrib;
2821 /* we force update consideration on load-balancer moves */ 2821 /* we force update consideration on load-balancer moves */
2822 update_cfs_rq_blocked_load(cfs_rq, !wakeup); 2822 update_cfs_rq_blocked_load(cfs_rq, !wakeup);
2823 } 2823 }
2824 2824
2825 /* 2825 /*
2826 * Remove se's load from this cfs_rq child load-average, if the entity is 2826 * Remove se's load from this cfs_rq child load-average, if the entity is
2827 * transitioning to a blocked state we track its projected decay using 2827 * transitioning to a blocked state we track its projected decay using
2828 * blocked_load_avg. 2828 * blocked_load_avg.
2829 */ 2829 */
2830 static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq, 2830 static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq,
2831 struct sched_entity *se, 2831 struct sched_entity *se,
2832 int sleep) 2832 int sleep)
2833 { 2833 {
2834 update_entity_load_avg(se, 1); 2834 update_entity_load_avg(se, 1);
2835 /* we force update consideration on load-balancer moves */ 2835 /* we force update consideration on load-balancer moves */
2836 update_cfs_rq_blocked_load(cfs_rq, !sleep); 2836 update_cfs_rq_blocked_load(cfs_rq, !sleep);
2837 2837
2838 cfs_rq->runnable_load_avg -= se->avg.load_avg_contrib; 2838 cfs_rq->runnable_load_avg -= se->avg.load_avg_contrib;
2839 if (sleep) { 2839 if (sleep) {
2840 cfs_rq->blocked_load_avg += se->avg.load_avg_contrib; 2840 cfs_rq->blocked_load_avg += se->avg.load_avg_contrib;
2841 se->avg.decay_count = atomic64_read(&cfs_rq->decay_counter); 2841 se->avg.decay_count = atomic64_read(&cfs_rq->decay_counter);
2842 } /* migrations, e.g. sleep=0 leave decay_count == 0 */ 2842 } /* migrations, e.g. sleep=0 leave decay_count == 0 */
2843 } 2843 }
2844 2844
2845 /* 2845 /*
2846 * Update the rq's load with the elapsed running time before entering 2846 * Update the rq's load with the elapsed running time before entering
2847 * idle. if the last scheduled task is not a CFS task, idle_enter will 2847 * idle. if the last scheduled task is not a CFS task, idle_enter will
2848 * be the only way to update the runnable statistic. 2848 * be the only way to update the runnable statistic.
2849 */ 2849 */
2850 void idle_enter_fair(struct rq *this_rq) 2850 void idle_enter_fair(struct rq *this_rq)
2851 { 2851 {
2852 update_rq_runnable_avg(this_rq, 1); 2852 update_rq_runnable_avg(this_rq, 1);
2853 } 2853 }
2854 2854
2855 /* 2855 /*
2856 * Update the rq's load with the elapsed idle time before a task is 2856 * Update the rq's load with the elapsed idle time before a task is
2857 * scheduled. if the newly scheduled task is not a CFS task, idle_exit will 2857 * scheduled. if the newly scheduled task is not a CFS task, idle_exit will
2858 * be the only way to update the runnable statistic. 2858 * be the only way to update the runnable statistic.
2859 */ 2859 */
2860 void idle_exit_fair(struct rq *this_rq) 2860 void idle_exit_fair(struct rq *this_rq)
2861 { 2861 {
2862 update_rq_runnable_avg(this_rq, 0); 2862 update_rq_runnable_avg(this_rq, 0);
2863 } 2863 }
2864 2864
2865 static int idle_balance(struct rq *this_rq); 2865 static int idle_balance(struct rq *this_rq);
2866 2866
2867 #else /* CONFIG_SMP */ 2867 #else /* CONFIG_SMP */
2868 2868
2869 static inline void update_entity_load_avg(struct sched_entity *se, 2869 static inline void update_entity_load_avg(struct sched_entity *se,
2870 int update_cfs_rq) {} 2870 int update_cfs_rq) {}
2871 static inline void update_rq_runnable_avg(struct rq *rq, int runnable) {} 2871 static inline void update_rq_runnable_avg(struct rq *rq, int runnable) {}
2872 static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq, 2872 static inline void enqueue_entity_load_avg(struct cfs_rq *cfs_rq,
2873 struct sched_entity *se, 2873 struct sched_entity *se,
2874 int wakeup) {} 2874 int wakeup) {}
2875 static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq, 2875 static inline void dequeue_entity_load_avg(struct cfs_rq *cfs_rq,
2876 struct sched_entity *se, 2876 struct sched_entity *se,
2877 int sleep) {} 2877 int sleep) {}
2878 static inline void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq, 2878 static inline void update_cfs_rq_blocked_load(struct cfs_rq *cfs_rq,
2879 int force_update) {} 2879 int force_update) {}
2880 2880
2881 static inline int idle_balance(struct rq *rq) 2881 static inline int idle_balance(struct rq *rq)
2882 { 2882 {
2883 return 0; 2883 return 0;
2884 } 2884 }
2885 2885
2886 #endif /* CONFIG_SMP */ 2886 #endif /* CONFIG_SMP */
2887 2887
2888 static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se) 2888 static void enqueue_sleeper(struct cfs_rq *cfs_rq, struct sched_entity *se)
2889 { 2889 {
2890 #ifdef CONFIG_SCHEDSTATS 2890 #ifdef CONFIG_SCHEDSTATS
2891 struct task_struct *tsk = NULL; 2891 struct task_struct *tsk = NULL;
2892 2892
2893 if (entity_is_task(se)) 2893 if (entity_is_task(se))
2894 tsk = task_of(se); 2894 tsk = task_of(se);
2895 2895
2896 if (se->statistics.sleep_start) { 2896 if (se->statistics.sleep_start) {
2897 u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.sleep_start; 2897 u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.sleep_start;
2898 2898
2899 if ((s64)delta < 0) 2899 if ((s64)delta < 0)
2900 delta = 0; 2900 delta = 0;
2901 2901
2902 if (unlikely(delta > se->statistics.sleep_max)) 2902 if (unlikely(delta > se->statistics.sleep_max))
2903 se->statistics.sleep_max = delta; 2903 se->statistics.sleep_max = delta;
2904 2904
2905 se->statistics.sleep_start = 0; 2905 se->statistics.sleep_start = 0;
2906 se->statistics.sum_sleep_runtime += delta; 2906 se->statistics.sum_sleep_runtime += delta;
2907 2907
2908 if (tsk) { 2908 if (tsk) {
2909 account_scheduler_latency(tsk, delta >> 10, 1); 2909 account_scheduler_latency(tsk, delta >> 10, 1);
2910 trace_sched_stat_sleep(tsk, delta); 2910 trace_sched_stat_sleep(tsk, delta);
2911 } 2911 }
2912 } 2912 }
2913 if (se->statistics.block_start) { 2913 if (se->statistics.block_start) {
2914 u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.block_start; 2914 u64 delta = rq_clock(rq_of(cfs_rq)) - se->statistics.block_start;
2915 2915
2916 if ((s64)delta < 0) 2916 if ((s64)delta < 0)
2917 delta = 0; 2917 delta = 0;
2918 2918
2919 if (unlikely(delta > se->statistics.block_max)) 2919 if (unlikely(delta > se->statistics.block_max))
2920 se->statistics.block_max = delta; 2920 se->statistics.block_max = delta;
2921 2921
2922 se->statistics.block_start = 0; 2922 se->statistics.block_start = 0;
2923 se->statistics.sum_sleep_runtime += delta; 2923 se->statistics.sum_sleep_runtime += delta;
2924 2924
2925 if (tsk) { 2925 if (tsk) {
2926 if (tsk->in_iowait) { 2926 if (tsk->in_iowait) {
2927 se->statistics.iowait_sum += delta; 2927 se->statistics.iowait_sum += delta;
2928 se->statistics.iowait_count++; 2928 se->statistics.iowait_count++;
2929 trace_sched_stat_iowait(tsk, delta); 2929 trace_sched_stat_iowait(tsk, delta);
2930 } 2930 }
2931 2931
2932 trace_sched_stat_blocked(tsk, delta); 2932 trace_sched_stat_blocked(tsk, delta);
2933 2933
2934 /* 2934 /*
2935 * Blocking time is in units of nanosecs, so shift by 2935 * Blocking time is in units of nanosecs, so shift by
2936 * 20 to get a milliseconds-range estimation of the 2936 * 20 to get a milliseconds-range estimation of the
2937 * amount of time that the task spent sleeping: 2937 * amount of time that the task spent sleeping:
2938 */ 2938 */
2939 if (unlikely(prof_on == SLEEP_PROFILING)) { 2939 if (unlikely(prof_on == SLEEP_PROFILING)) {
2940 profile_hits(SLEEP_PROFILING, 2940 profile_hits(SLEEP_PROFILING,
2941 (void *)get_wchan(tsk), 2941 (void *)get_wchan(tsk),
2942 delta >> 20); 2942 delta >> 20);
2943 } 2943 }
2944 account_scheduler_latency(tsk, delta >> 10, 0); 2944 account_scheduler_latency(tsk, delta >> 10, 0);
2945 } 2945 }
2946 } 2946 }
2947 #endif 2947 #endif
2948 } 2948 }
2949 2949
2950 static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se) 2950 static void check_spread(struct cfs_rq *cfs_rq, struct sched_entity *se)
2951 { 2951 {
2952 #ifdef CONFIG_SCHED_DEBUG 2952 #ifdef CONFIG_SCHED_DEBUG
2953 s64 d = se->vruntime - cfs_rq->min_vruntime; 2953 s64 d = se->vruntime - cfs_rq->min_vruntime;
2954 2954
2955 if (d < 0) 2955 if (d < 0)
2956 d = -d; 2956 d = -d;
2957 2957
2958 if (d > 3*sysctl_sched_latency) 2958 if (d > 3*sysctl_sched_latency)
2959 schedstat_inc(cfs_rq, nr_spread_over); 2959 schedstat_inc(cfs_rq, nr_spread_over);
2960 #endif 2960 #endif
2961 } 2961 }
2962 2962
2963 static void 2963 static void
2964 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial) 2964 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int initial)
2965 { 2965 {
2966 u64 vruntime = cfs_rq->min_vruntime; 2966 u64 vruntime = cfs_rq->min_vruntime;
2967 2967
2968 /* 2968 /*
2969 * The 'current' period is already promised to the current tasks, 2969 * The 'current' period is already promised to the current tasks,
2970 * however the extra weight of the new task will slow them down a 2970 * however the extra weight of the new task will slow them down a
2971 * little, place the new task so that it fits in the slot that 2971 * little, place the new task so that it fits in the slot that
2972 * stays open at the end. 2972 * stays open at the end.
2973 */ 2973 */
2974 if (initial && sched_feat(START_DEBIT)) 2974 if (initial && sched_feat(START_DEBIT))
2975 vruntime += sched_vslice(cfs_rq, se); 2975 vruntime += sched_vslice(cfs_rq, se);
2976 2976
2977 /* sleeps up to a single latency don't count. */ 2977 /* sleeps up to a single latency don't count. */
2978 if (!initial) { 2978 if (!initial) {
2979 unsigned long thresh = sysctl_sched_latency; 2979 unsigned long thresh = sysctl_sched_latency;
2980 2980
2981 /* 2981 /*
2982 * Halve their sleep time's effect, to allow 2982 * Halve their sleep time's effect, to allow
2983 * for a gentler effect of sleepers: 2983 * for a gentler effect of sleepers:
2984 */ 2984 */
2985 if (sched_feat(GENTLE_FAIR_SLEEPERS)) 2985 if (sched_feat(GENTLE_FAIR_SLEEPERS))
2986 thresh >>= 1; 2986 thresh >>= 1;
2987 2987
2988 vruntime -= thresh; 2988 vruntime -= thresh;
2989 } 2989 }
2990 2990
2991 /* ensure we never gain time by being placed backwards. */ 2991 /* ensure we never gain time by being placed backwards. */
2992 se->vruntime = max_vruntime(se->vruntime, vruntime); 2992 se->vruntime = max_vruntime(se->vruntime, vruntime);
2993 } 2993 }
2994 2994
2995 static void check_enqueue_throttle(struct cfs_rq *cfs_rq); 2995 static void check_enqueue_throttle(struct cfs_rq *cfs_rq);
2996 2996
2997 static void 2997 static void
2998 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 2998 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
2999 { 2999 {
3000 /* 3000 /*
3001 * Update the normalized vruntime before updating min_vruntime 3001 * Update the normalized vruntime before updating min_vruntime
3002 * through calling update_curr(). 3002 * through calling update_curr().
3003 */ 3003 */
3004 if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING)) 3004 if (!(flags & ENQUEUE_WAKEUP) || (flags & ENQUEUE_WAKING))
3005 se->vruntime += cfs_rq->min_vruntime; 3005 se->vruntime += cfs_rq->min_vruntime;
3006 3006
3007 /* 3007 /*
3008 * Update run-time statistics of the 'current'. 3008 * Update run-time statistics of the 'current'.
3009 */ 3009 */
3010 update_curr(cfs_rq); 3010 update_curr(cfs_rq);
3011 enqueue_entity_load_avg(cfs_rq, se, flags & ENQUEUE_WAKEUP); 3011 enqueue_entity_load_avg(cfs_rq, se, flags & ENQUEUE_WAKEUP);
3012 account_entity_enqueue(cfs_rq, se); 3012 account_entity_enqueue(cfs_rq, se);
3013 update_cfs_shares(cfs_rq); 3013 update_cfs_shares(cfs_rq);
3014 3014
3015 if (flags & ENQUEUE_WAKEUP) { 3015 if (flags & ENQUEUE_WAKEUP) {
3016 place_entity(cfs_rq, se, 0); 3016 place_entity(cfs_rq, se, 0);
3017 enqueue_sleeper(cfs_rq, se); 3017 enqueue_sleeper(cfs_rq, se);
3018 } 3018 }
3019 3019
3020 update_stats_enqueue(cfs_rq, se); 3020 update_stats_enqueue(cfs_rq, se);
3021 check_spread(cfs_rq, se); 3021 check_spread(cfs_rq, se);
3022 if (se != cfs_rq->curr) 3022 if (se != cfs_rq->curr)
3023 __enqueue_entity(cfs_rq, se); 3023 __enqueue_entity(cfs_rq, se);
3024 se->on_rq = 1; 3024 se->on_rq = 1;
3025 3025
3026 if (cfs_rq->nr_running == 1) { 3026 if (cfs_rq->nr_running == 1) {
3027 list_add_leaf_cfs_rq(cfs_rq); 3027 list_add_leaf_cfs_rq(cfs_rq);
3028 check_enqueue_throttle(cfs_rq); 3028 check_enqueue_throttle(cfs_rq);
3029 } 3029 }
3030 } 3030 }
3031 3031
3032 static void __clear_buddies_last(struct sched_entity *se) 3032 static void __clear_buddies_last(struct sched_entity *se)
3033 { 3033 {
3034 for_each_sched_entity(se) { 3034 for_each_sched_entity(se) {
3035 struct cfs_rq *cfs_rq = cfs_rq_of(se); 3035 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3036 if (cfs_rq->last != se) 3036 if (cfs_rq->last != se)
3037 break; 3037 break;
3038 3038
3039 cfs_rq->last = NULL; 3039 cfs_rq->last = NULL;
3040 } 3040 }
3041 } 3041 }
3042 3042
3043 static void __clear_buddies_next(struct sched_entity *se) 3043 static void __clear_buddies_next(struct sched_entity *se)
3044 { 3044 {
3045 for_each_sched_entity(se) { 3045 for_each_sched_entity(se) {
3046 struct cfs_rq *cfs_rq = cfs_rq_of(se); 3046 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3047 if (cfs_rq->next != se) 3047 if (cfs_rq->next != se)
3048 break; 3048 break;
3049 3049
3050 cfs_rq->next = NULL; 3050 cfs_rq->next = NULL;
3051 } 3051 }
3052 } 3052 }
3053 3053
3054 static void __clear_buddies_skip(struct sched_entity *se) 3054 static void __clear_buddies_skip(struct sched_entity *se)
3055 { 3055 {
3056 for_each_sched_entity(se) { 3056 for_each_sched_entity(se) {
3057 struct cfs_rq *cfs_rq = cfs_rq_of(se); 3057 struct cfs_rq *cfs_rq = cfs_rq_of(se);
3058 if (cfs_rq->skip != se) 3058 if (cfs_rq->skip != se)
3059 break; 3059 break;
3060 3060
3061 cfs_rq->skip = NULL; 3061 cfs_rq->skip = NULL;
3062 } 3062 }
3063 } 3063 }
3064 3064
3065 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se) 3065 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se)
3066 { 3066 {
3067 if (cfs_rq->last == se) 3067 if (cfs_rq->last == se)
3068 __clear_buddies_last(se); 3068 __clear_buddies_last(se);
3069 3069
3070 if (cfs_rq->next == se) 3070 if (cfs_rq->next == se)
3071 __clear_buddies_next(se); 3071 __clear_buddies_next(se);
3072 3072
3073 if (cfs_rq->skip == se) 3073 if (cfs_rq->skip == se)
3074 __clear_buddies_skip(se); 3074 __clear_buddies_skip(se);
3075 } 3075 }
3076 3076
3077 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq); 3077 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq);
3078 3078
3079 static void 3079 static void
3080 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 3080 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags)
3081 { 3081 {
3082 /* 3082 /*
3083 * Update run-time statistics of the 'current'. 3083 * Update run-time statistics of the 'current'.
3084 */ 3084 */
3085 update_curr(cfs_rq); 3085 update_curr(cfs_rq);
3086 dequeue_entity_load_avg(cfs_rq, se, flags & DEQUEUE_SLEEP); 3086 dequeue_entity_load_avg(cfs_rq, se, flags & DEQUEUE_SLEEP);
3087 3087
3088 update_stats_dequeue(cfs_rq, se); 3088 update_stats_dequeue(cfs_rq, se);
3089 if (flags & DEQUEUE_SLEEP) { 3089 if (flags & DEQUEUE_SLEEP) {
3090 #ifdef CONFIG_SCHEDSTATS 3090 #ifdef CONFIG_SCHEDSTATS
3091 if (entity_is_task(se)) { 3091 if (entity_is_task(se)) {
3092 struct task_struct *tsk = task_of(se); 3092 struct task_struct *tsk = task_of(se);
3093 3093
3094 if (tsk->state & TASK_INTERRUPTIBLE) 3094 if (tsk->state & TASK_INTERRUPTIBLE)
3095 se->statistics.sleep_start = rq_clock(rq_of(cfs_rq)); 3095 se->statistics.sleep_start = rq_clock(rq_of(cfs_rq));
3096 if (tsk->state & TASK_UNINTERRUPTIBLE) 3096 if (tsk->state & TASK_UNINTERRUPTIBLE)
3097 se->statistics.block_start = rq_clock(rq_of(cfs_rq)); 3097 se->statistics.block_start = rq_clock(rq_of(cfs_rq));
3098 } 3098 }
3099 #endif 3099 #endif
3100 } 3100 }
3101 3101
3102 clear_buddies(cfs_rq, se); 3102 clear_buddies(cfs_rq, se);
3103 3103
3104 if (se != cfs_rq->curr) 3104 if (se != cfs_rq->curr)
3105 __dequeue_entity(cfs_rq, se); 3105 __dequeue_entity(cfs_rq, se);
3106 se->on_rq = 0; 3106 se->on_rq = 0;
3107 account_entity_dequeue(cfs_rq, se); 3107 account_entity_dequeue(cfs_rq, se);
3108 3108
3109 /* 3109 /*
3110 * Normalize the entity after updating the min_vruntime because the 3110 * Normalize the entity after updating the min_vruntime because the
3111 * update can refer to the ->curr item and we need to reflect this 3111 * update can refer to the ->curr item and we need to reflect this
3112 * movement in our normalized position. 3112 * movement in our normalized position.
3113 */ 3113 */
3114 if (!(flags & DEQUEUE_SLEEP)) 3114 if (!(flags & DEQUEUE_SLEEP))
3115 se->vruntime -= cfs_rq->min_vruntime; 3115 se->vruntime -= cfs_rq->min_vruntime;
3116 3116
3117 /* return excess runtime on last dequeue */ 3117 /* return excess runtime on last dequeue */
3118 return_cfs_rq_runtime(cfs_rq); 3118 return_cfs_rq_runtime(cfs_rq);
3119 3119
3120 update_min_vruntime(cfs_rq); 3120 update_min_vruntime(cfs_rq);
3121 update_cfs_shares(cfs_rq); 3121 update_cfs_shares(cfs_rq);
3122 } 3122 }
3123 3123
3124 /* 3124 /*
3125 * Preempt the current task with a newly woken task if needed: 3125 * Preempt the current task with a newly woken task if needed:
3126 */ 3126 */
3127 static void 3127 static void
3128 check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr) 3128 check_preempt_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr)
3129 { 3129 {
3130 unsigned long ideal_runtime, delta_exec; 3130 unsigned long ideal_runtime, delta_exec;
3131 struct sched_entity *se; 3131 struct sched_entity *se;
3132 s64 delta; 3132 s64 delta;
3133 3133
3134 ideal_runtime = sched_slice(cfs_rq, curr); 3134 ideal_runtime = sched_slice(cfs_rq, curr);
3135 delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime; 3135 delta_exec = curr->sum_exec_runtime - curr->prev_sum_exec_runtime;
3136 if (delta_exec > ideal_runtime) { 3136 if (delta_exec > ideal_runtime) {
3137 resched_curr(rq_of(cfs_rq)); 3137 resched_curr(rq_of(cfs_rq));
3138 /* 3138 /*
3139 * The current task ran long enough, ensure it doesn't get 3139 * The current task ran long enough, ensure it doesn't get
3140 * re-elected due to buddy favours. 3140 * re-elected due to buddy favours.
3141 */ 3141 */
3142 clear_buddies(cfs_rq, curr); 3142 clear_buddies(cfs_rq, curr);
3143 return; 3143 return;
3144 } 3144 }
3145 3145
3146 /* 3146 /*
3147 * Ensure that a task that missed wakeup preemption by a 3147 * Ensure that a task that missed wakeup preemption by a
3148 * narrow margin doesn't have to wait for a full slice. 3148 * narrow margin doesn't have to wait for a full slice.
3149 * This also mitigates buddy induced latencies under load. 3149 * This also mitigates buddy induced latencies under load.
3150 */ 3150 */
3151 if (delta_exec < sysctl_sched_min_granularity) 3151 if (delta_exec < sysctl_sched_min_granularity)
3152 return; 3152 return;
3153 3153
3154 se = __pick_first_entity(cfs_rq); 3154 se = __pick_first_entity(cfs_rq);
3155 delta = curr->vruntime - se->vruntime; 3155 delta = curr->vruntime - se->vruntime;
3156 3156
3157 if (delta < 0) 3157 if (delta < 0)
3158 return; 3158 return;
3159 3159
3160 if (delta > ideal_runtime) 3160 if (delta > ideal_runtime)
3161 resched_curr(rq_of(cfs_rq)); 3161 resched_curr(rq_of(cfs_rq));
3162 } 3162 }
3163 3163
3164 static void 3164 static void
3165 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) 3165 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se)
3166 { 3166 {
3167 /* 'current' is not kept within the tree. */ 3167 /* 'current' is not kept within the tree. */
3168 if (se->on_rq) { 3168 if (se->on_rq) {
3169 /* 3169 /*
3170 * Any task has to be enqueued before it get to execute on 3170 * Any task has to be enqueued before it get to execute on
3171 * a CPU. So account for the time it spent waiting on the 3171 * a CPU. So account for the time it spent waiting on the
3172 * runqueue. 3172 * runqueue.
3173 */ 3173 */
3174 update_stats_wait_end(cfs_rq, se); 3174 update_stats_wait_end(cfs_rq, se);
3175 __dequeue_entity(cfs_rq, se); 3175 __dequeue_entity(cfs_rq, se);
3176 } 3176 }
3177 3177
3178 update_stats_curr_start(cfs_rq, se); 3178 update_stats_curr_start(cfs_rq, se);
3179 cfs_rq->curr = se; 3179 cfs_rq->curr = se;
3180 #ifdef CONFIG_SCHEDSTATS 3180 #ifdef CONFIG_SCHEDSTATS
3181 /* 3181 /*
3182 * Track our maximum slice length, if the CPU's load is at 3182 * Track our maximum slice length, if the CPU's load is at
3183 * least twice that of our own weight (i.e. dont track it 3183 * least twice that of our own weight (i.e. dont track it
3184 * when there are only lesser-weight tasks around): 3184 * when there are only lesser-weight tasks around):
3185 */ 3185 */
3186 if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) { 3186 if (rq_of(cfs_rq)->load.weight >= 2*se->load.weight) {
3187 se->statistics.slice_max = max(se->statistics.slice_max, 3187 se->statistics.slice_max = max(se->statistics.slice_max,
3188 se->sum_exec_runtime - se->prev_sum_exec_runtime); 3188 se->sum_exec_runtime - se->prev_sum_exec_runtime);
3189 } 3189 }
3190 #endif 3190 #endif
3191 se->prev_sum_exec_runtime = se->sum_exec_runtime; 3191 se->prev_sum_exec_runtime = se->sum_exec_runtime;
3192 } 3192 }
3193 3193
3194 static int 3194 static int
3195 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se); 3195 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se);
3196 3196
3197 /* 3197 /*
3198 * Pick the next process, keeping these things in mind, in this order: 3198 * Pick the next process, keeping these things in mind, in this order:
3199 * 1) keep things fair between processes/task groups 3199 * 1) keep things fair between processes/task groups
3200 * 2) pick the "next" process, since someone really wants that to run 3200 * 2) pick the "next" process, since someone really wants that to run
3201 * 3) pick the "last" process, for cache locality 3201 * 3) pick the "last" process, for cache locality
3202 * 4) do not run the "skip" process, if something else is available 3202 * 4) do not run the "skip" process, if something else is available
3203 */ 3203 */
3204 static struct sched_entity * 3204 static struct sched_entity *
3205 pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr) 3205 pick_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *curr)
3206 { 3206 {
3207 struct sched_entity *left = __pick_first_entity(cfs_rq); 3207 struct sched_entity *left = __pick_first_entity(cfs_rq);
3208 struct sched_entity *se; 3208 struct sched_entity *se;
3209 3209
3210 /* 3210 /*
3211 * If curr is set we have to see if its left of the leftmost entity 3211 * If curr is set we have to see if its left of the leftmost entity
3212 * still in the tree, provided there was anything in the tree at all. 3212 * still in the tree, provided there was anything in the tree at all.
3213 */ 3213 */
3214 if (!left || (curr && entity_before(curr, left))) 3214 if (!left || (curr && entity_before(curr, left)))
3215 left = curr; 3215 left = curr;
3216 3216
3217 se = left; /* ideally we run the leftmost entity */ 3217 se = left; /* ideally we run the leftmost entity */
3218 3218
3219 /* 3219 /*
3220 * Avoid running the skip buddy, if running something else can 3220 * Avoid running the skip buddy, if running something else can
3221 * be done without getting too unfair. 3221 * be done without getting too unfair.
3222 */ 3222 */
3223 if (cfs_rq->skip == se) { 3223 if (cfs_rq->skip == se) {
3224 struct sched_entity *second; 3224 struct sched_entity *second;
3225 3225
3226 if (se == curr) { 3226 if (se == curr) {
3227 second = __pick_first_entity(cfs_rq); 3227 second = __pick_first_entity(cfs_rq);
3228 } else { 3228 } else {
3229 second = __pick_next_entity(se); 3229 second = __pick_next_entity(se);
3230 if (!second || (curr && entity_before(curr, second))) 3230 if (!second || (curr && entity_before(curr, second)))
3231 second = curr; 3231 second = curr;
3232 } 3232 }
3233 3233
3234 if (second && wakeup_preempt_entity(second, left) < 1) 3234 if (second && wakeup_preempt_entity(second, left) < 1)
3235 se = second; 3235 se = second;
3236 } 3236 }
3237 3237
3238 /* 3238 /*
3239 * Prefer last buddy, try to return the CPU to a preempted task. 3239 * Prefer last buddy, try to return the CPU to a preempted task.
3240 */ 3240 */
3241 if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1) 3241 if (cfs_rq->last && wakeup_preempt_entity(cfs_rq->last, left) < 1)
3242 se = cfs_rq->last; 3242 se = cfs_rq->last;
3243 3243
3244 /* 3244 /*
3245 * Someone really wants this to run. If it's not unfair, run it. 3245 * Someone really wants this to run. If it's not unfair, run it.
3246 */ 3246 */
3247 if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1) 3247 if (cfs_rq->next && wakeup_preempt_entity(cfs_rq->next, left) < 1)
3248 se = cfs_rq->next; 3248 se = cfs_rq->next;
3249 3249
3250 clear_buddies(cfs_rq, se); 3250 clear_buddies(cfs_rq, se);
3251 3251
3252 return se; 3252 return se;
3253 } 3253 }
3254 3254
3255 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq); 3255 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq);
3256 3256
3257 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev) 3257 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev)
3258 { 3258 {
3259 /* 3259 /*
3260 * If still on the runqueue then deactivate_task() 3260 * If still on the runqueue then deactivate_task()
3261 * was not called and update_curr() has to be done: 3261 * was not called and update_curr() has to be done:
3262 */ 3262 */
3263 if (prev->on_rq) 3263 if (prev->on_rq)
3264 update_curr(cfs_rq); 3264 update_curr(cfs_rq);
3265 3265
3266 /* throttle cfs_rqs exceeding runtime */ 3266 /* throttle cfs_rqs exceeding runtime */
3267 check_cfs_rq_runtime(cfs_rq); 3267 check_cfs_rq_runtime(cfs_rq);
3268 3268
3269 check_spread(cfs_rq, prev); 3269 check_spread(cfs_rq, prev);
3270 if (prev->on_rq) { 3270 if (prev->on_rq) {
3271 update_stats_wait_start(cfs_rq, prev); 3271 update_stats_wait_start(cfs_rq, prev);
3272 /* Put 'current' back into the tree. */ 3272 /* Put 'current' back into the tree. */
3273 __enqueue_entity(cfs_rq, prev); 3273 __enqueue_entity(cfs_rq, prev);
3274 /* in !on_rq case, update occurred at dequeue */ 3274 /* in !on_rq case, update occurred at dequeue */
3275 update_entity_load_avg(prev, 1); 3275 update_entity_load_avg(prev, 1);
3276 } 3276 }
3277 cfs_rq->curr = NULL; 3277 cfs_rq->curr = NULL;
3278 } 3278 }
3279 3279
3280 static void 3280 static void
3281 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued) 3281 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued)
3282 { 3282 {
3283 /* 3283 /*
3284 * Update run-time statistics of the 'current'. 3284 * Update run-time statistics of the 'current'.
3285 */ 3285 */
3286 update_curr(cfs_rq); 3286 update_curr(cfs_rq);
3287 3287
3288 /* 3288 /*
3289 * Ensure that runnable average is periodically updated. 3289 * Ensure that runnable average is periodically updated.
3290 */ 3290 */
3291 update_entity_load_avg(curr, 1); 3291 update_entity_load_avg(curr, 1);
3292 update_cfs_rq_blocked_load(cfs_rq, 1); 3292 update_cfs_rq_blocked_load(cfs_rq, 1);
3293 update_cfs_shares(cfs_rq); 3293 update_cfs_shares(cfs_rq);
3294 3294
3295 #ifdef CONFIG_SCHED_HRTICK 3295 #ifdef CONFIG_SCHED_HRTICK
3296 /* 3296 /*
3297 * queued ticks are scheduled to match the slice, so don't bother 3297 * queued ticks are scheduled to match the slice, so don't bother
3298 * validating it and just reschedule. 3298 * validating it and just reschedule.
3299 */ 3299 */
3300 if (queued) { 3300 if (queued) {
3301 resched_curr(rq_of(cfs_rq)); 3301 resched_curr(rq_of(cfs_rq));
3302 return; 3302 return;
3303 } 3303 }
3304 /* 3304 /*
3305 * don't let the period tick interfere with the hrtick preemption 3305 * don't let the period tick interfere with the hrtick preemption
3306 */ 3306 */
3307 if (!sched_feat(DOUBLE_TICK) && 3307 if (!sched_feat(DOUBLE_TICK) &&
3308 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer)) 3308 hrtimer_active(&rq_of(cfs_rq)->hrtick_timer))
3309 return; 3309 return;
3310 #endif 3310 #endif
3311 3311
3312 if (cfs_rq->nr_running > 1) 3312 if (cfs_rq->nr_running > 1)
3313 check_preempt_tick(cfs_rq, curr); 3313 check_preempt_tick(cfs_rq, curr);
3314 } 3314 }
3315 3315
3316 3316
3317 /************************************************** 3317 /**************************************************
3318 * CFS bandwidth control machinery 3318 * CFS bandwidth control machinery
3319 */ 3319 */
3320 3320
3321 #ifdef CONFIG_CFS_BANDWIDTH 3321 #ifdef CONFIG_CFS_BANDWIDTH
3322 3322
3323 #ifdef HAVE_JUMP_LABEL 3323 #ifdef HAVE_JUMP_LABEL
3324 static struct static_key __cfs_bandwidth_used; 3324 static struct static_key __cfs_bandwidth_used;
3325 3325
3326 static inline bool cfs_bandwidth_used(void) 3326 static inline bool cfs_bandwidth_used(void)
3327 { 3327 {
3328 return static_key_false(&__cfs_bandwidth_used); 3328 return static_key_false(&__cfs_bandwidth_used);
3329 } 3329 }
3330 3330
3331 void cfs_bandwidth_usage_inc(void) 3331 void cfs_bandwidth_usage_inc(void)
3332 { 3332 {
3333 static_key_slow_inc(&__cfs_bandwidth_used); 3333 static_key_slow_inc(&__cfs_bandwidth_used);
3334 } 3334 }
3335 3335
3336 void cfs_bandwidth_usage_dec(void) 3336 void cfs_bandwidth_usage_dec(void)
3337 { 3337 {
3338 static_key_slow_dec(&__cfs_bandwidth_used); 3338 static_key_slow_dec(&__cfs_bandwidth_used);
3339 } 3339 }
3340 #else /* HAVE_JUMP_LABEL */ 3340 #else /* HAVE_JUMP_LABEL */
3341 static bool cfs_bandwidth_used(void) 3341 static bool cfs_bandwidth_used(void)
3342 { 3342 {
3343 return true; 3343 return true;
3344 } 3344 }
3345 3345
3346 void cfs_bandwidth_usage_inc(void) {} 3346 void cfs_bandwidth_usage_inc(void) {}
3347 void cfs_bandwidth_usage_dec(void) {} 3347 void cfs_bandwidth_usage_dec(void) {}
3348 #endif /* HAVE_JUMP_LABEL */ 3348 #endif /* HAVE_JUMP_LABEL */
3349 3349
3350 /* 3350 /*
3351 * default period for cfs group bandwidth. 3351 * default period for cfs group bandwidth.
3352 * default: 0.1s, units: nanoseconds 3352 * default: 0.1s, units: nanoseconds
3353 */ 3353 */
3354 static inline u64 default_cfs_period(void) 3354 static inline u64 default_cfs_period(void)
3355 { 3355 {
3356 return 100000000ULL; 3356 return 100000000ULL;
3357 } 3357 }
3358 3358
3359 static inline u64 sched_cfs_bandwidth_slice(void) 3359 static inline u64 sched_cfs_bandwidth_slice(void)
3360 { 3360 {
3361 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC; 3361 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC;
3362 } 3362 }
3363 3363
3364 /* 3364 /*
3365 * Replenish runtime according to assigned quota and update expiration time. 3365 * Replenish runtime according to assigned quota and update expiration time.
3366 * We use sched_clock_cpu directly instead of rq->clock to avoid adding 3366 * We use sched_clock_cpu directly instead of rq->clock to avoid adding
3367 * additional synchronization around rq->lock. 3367 * additional synchronization around rq->lock.
3368 * 3368 *
3369 * requires cfs_b->lock 3369 * requires cfs_b->lock
3370 */ 3370 */
3371 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b) 3371 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b)
3372 { 3372 {
3373 u64 now; 3373 u64 now;
3374 3374
3375 if (cfs_b->quota == RUNTIME_INF) 3375 if (cfs_b->quota == RUNTIME_INF)
3376 return; 3376 return;
3377 3377
3378 now = sched_clock_cpu(smp_processor_id()); 3378 now = sched_clock_cpu(smp_processor_id());
3379 cfs_b->runtime = cfs_b->quota; 3379 cfs_b->runtime = cfs_b->quota;
3380 cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period); 3380 cfs_b->runtime_expires = now + ktime_to_ns(cfs_b->period);
3381 } 3381 }
3382 3382
3383 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg) 3383 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
3384 { 3384 {
3385 return &tg->cfs_bandwidth; 3385 return &tg->cfs_bandwidth;
3386 } 3386 }
3387 3387
3388 /* rq->task_clock normalized against any time this cfs_rq has spent throttled */ 3388 /* rq->task_clock normalized against any time this cfs_rq has spent throttled */
3389 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq) 3389 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
3390 { 3390 {
3391 if (unlikely(cfs_rq->throttle_count)) 3391 if (unlikely(cfs_rq->throttle_count))
3392 return cfs_rq->throttled_clock_task; 3392 return cfs_rq->throttled_clock_task;
3393 3393
3394 return rq_clock_task(rq_of(cfs_rq)) - cfs_rq->throttled_clock_task_time; 3394 return rq_clock_task(rq_of(cfs_rq)) - cfs_rq->throttled_clock_task_time;
3395 } 3395 }
3396 3396
3397 /* returns 0 on failure to allocate runtime */ 3397 /* returns 0 on failure to allocate runtime */
3398 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq) 3398 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq)
3399 { 3399 {
3400 struct task_group *tg = cfs_rq->tg; 3400 struct task_group *tg = cfs_rq->tg;
3401 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg); 3401 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg);
3402 u64 amount = 0, min_amount, expires; 3402 u64 amount = 0, min_amount, expires;
3403 3403
3404 /* note: this is a positive sum as runtime_remaining <= 0 */ 3404 /* note: this is a positive sum as runtime_remaining <= 0 */
3405 min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining; 3405 min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining;
3406 3406
3407 raw_spin_lock(&cfs_b->lock); 3407 raw_spin_lock(&cfs_b->lock);
3408 if (cfs_b->quota == RUNTIME_INF) 3408 if (cfs_b->quota == RUNTIME_INF)
3409 amount = min_amount; 3409 amount = min_amount;
3410 else { 3410 else {
3411 /* 3411 /*
3412 * If the bandwidth pool has become inactive, then at least one 3412 * If the bandwidth pool has become inactive, then at least one
3413 * period must have elapsed since the last consumption. 3413 * period must have elapsed since the last consumption.
3414 * Refresh the global state and ensure bandwidth timer becomes 3414 * Refresh the global state and ensure bandwidth timer becomes
3415 * active. 3415 * active.
3416 */ 3416 */
3417 if (!cfs_b->timer_active) { 3417 if (!cfs_b->timer_active) {
3418 __refill_cfs_bandwidth_runtime(cfs_b); 3418 __refill_cfs_bandwidth_runtime(cfs_b);
3419 __start_cfs_bandwidth(cfs_b, false); 3419 __start_cfs_bandwidth(cfs_b, false);
3420 } 3420 }
3421 3421
3422 if (cfs_b->runtime > 0) { 3422 if (cfs_b->runtime > 0) {
3423 amount = min(cfs_b->runtime, min_amount); 3423 amount = min(cfs_b->runtime, min_amount);
3424 cfs_b->runtime -= amount; 3424 cfs_b->runtime -= amount;
3425 cfs_b->idle = 0; 3425 cfs_b->idle = 0;
3426 } 3426 }
3427 } 3427 }
3428 expires = cfs_b->runtime_expires; 3428 expires = cfs_b->runtime_expires;
3429 raw_spin_unlock(&cfs_b->lock); 3429 raw_spin_unlock(&cfs_b->lock);
3430 3430
3431 cfs_rq->runtime_remaining += amount; 3431 cfs_rq->runtime_remaining += amount;
3432 /* 3432 /*
3433 * we may have advanced our local expiration to account for allowed 3433 * we may have advanced our local expiration to account for allowed
3434 * spread between our sched_clock and the one on which runtime was 3434 * spread between our sched_clock and the one on which runtime was
3435 * issued. 3435 * issued.
3436 */ 3436 */
3437 if ((s64)(expires - cfs_rq->runtime_expires) > 0) 3437 if ((s64)(expires - cfs_rq->runtime_expires) > 0)
3438 cfs_rq->runtime_expires = expires; 3438 cfs_rq->runtime_expires = expires;
3439 3439
3440 return cfs_rq->runtime_remaining > 0; 3440 return cfs_rq->runtime_remaining > 0;
3441 } 3441 }
3442 3442
3443 /* 3443 /*
3444 * Note: This depends on the synchronization provided by sched_clock and the 3444 * Note: This depends on the synchronization provided by sched_clock and the
3445 * fact that rq->clock snapshots this value. 3445 * fact that rq->clock snapshots this value.
3446 */ 3446 */
3447 static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq) 3447 static void expire_cfs_rq_runtime(struct cfs_rq *cfs_rq)
3448 { 3448 {
3449 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 3449 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
3450 3450
3451 /* if the deadline is ahead of our clock, nothing to do */ 3451 /* if the deadline is ahead of our clock, nothing to do */
3452 if (likely((s64)(rq_clock(rq_of(cfs_rq)) - cfs_rq->runtime_expires) < 0)) 3452 if (likely((s64)(rq_clock(rq_of(cfs_rq)) - cfs_rq->runtime_expires) < 0))
3453 return; 3453 return;
3454 3454
3455 if (cfs_rq->runtime_remaining < 0) 3455 if (cfs_rq->runtime_remaining < 0)
3456 return; 3456 return;
3457 3457
3458 /* 3458 /*
3459 * If the local deadline has passed we have to consider the 3459 * If the local deadline has passed we have to consider the
3460 * possibility that our sched_clock is 'fast' and the global deadline 3460 * possibility that our sched_clock is 'fast' and the global deadline
3461 * has not truly expired. 3461 * has not truly expired.
3462 * 3462 *
3463 * Fortunately we can check determine whether this the case by checking 3463 * Fortunately we can check determine whether this the case by checking
3464 * whether the global deadline has advanced. It is valid to compare 3464 * whether the global deadline has advanced. It is valid to compare
3465 * cfs_b->runtime_expires without any locks since we only care about 3465 * cfs_b->runtime_expires without any locks since we only care about
3466 * exact equality, so a partial write will still work. 3466 * exact equality, so a partial write will still work.
3467 */ 3467 */
3468 3468
3469 if (cfs_rq->runtime_expires != cfs_b->runtime_expires) { 3469 if (cfs_rq->runtime_expires != cfs_b->runtime_expires) {
3470 /* extend local deadline, drift is bounded above by 2 ticks */ 3470 /* extend local deadline, drift is bounded above by 2 ticks */
3471 cfs_rq->runtime_expires += TICK_NSEC; 3471 cfs_rq->runtime_expires += TICK_NSEC;
3472 } else { 3472 } else {
3473 /* global deadline is ahead, expiration has passed */ 3473 /* global deadline is ahead, expiration has passed */
3474 cfs_rq->runtime_remaining = 0; 3474 cfs_rq->runtime_remaining = 0;
3475 } 3475 }
3476 } 3476 }
3477 3477
3478 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) 3478 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
3479 { 3479 {
3480 /* dock delta_exec before expiring quota (as it could span periods) */ 3480 /* dock delta_exec before expiring quota (as it could span periods) */
3481 cfs_rq->runtime_remaining -= delta_exec; 3481 cfs_rq->runtime_remaining -= delta_exec;
3482 expire_cfs_rq_runtime(cfs_rq); 3482 expire_cfs_rq_runtime(cfs_rq);
3483 3483
3484 if (likely(cfs_rq->runtime_remaining > 0)) 3484 if (likely(cfs_rq->runtime_remaining > 0))
3485 return; 3485 return;
3486 3486
3487 /* 3487 /*
3488 * if we're unable to extend our runtime we resched so that the active 3488 * if we're unable to extend our runtime we resched so that the active
3489 * hierarchy can be throttled 3489 * hierarchy can be throttled
3490 */ 3490 */
3491 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr)) 3491 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr))
3492 resched_curr(rq_of(cfs_rq)); 3492 resched_curr(rq_of(cfs_rq));
3493 } 3493 }
3494 3494
3495 static __always_inline 3495 static __always_inline
3496 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) 3496 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec)
3497 { 3497 {
3498 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled) 3498 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled)
3499 return; 3499 return;
3500 3500
3501 __account_cfs_rq_runtime(cfs_rq, delta_exec); 3501 __account_cfs_rq_runtime(cfs_rq, delta_exec);
3502 } 3502 }
3503 3503
3504 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq) 3504 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
3505 { 3505 {
3506 return cfs_bandwidth_used() && cfs_rq->throttled; 3506 return cfs_bandwidth_used() && cfs_rq->throttled;
3507 } 3507 }
3508 3508
3509 /* check whether cfs_rq, or any parent, is throttled */ 3509 /* check whether cfs_rq, or any parent, is throttled */
3510 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq) 3510 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
3511 { 3511 {
3512 return cfs_bandwidth_used() && cfs_rq->throttle_count; 3512 return cfs_bandwidth_used() && cfs_rq->throttle_count;
3513 } 3513 }
3514 3514
3515 /* 3515 /*
3516 * Ensure that neither of the group entities corresponding to src_cpu or 3516 * Ensure that neither of the group entities corresponding to src_cpu or
3517 * dest_cpu are members of a throttled hierarchy when performing group 3517 * dest_cpu are members of a throttled hierarchy when performing group
3518 * load-balance operations. 3518 * load-balance operations.
3519 */ 3519 */
3520 static inline int throttled_lb_pair(struct task_group *tg, 3520 static inline int throttled_lb_pair(struct task_group *tg,
3521 int src_cpu, int dest_cpu) 3521 int src_cpu, int dest_cpu)
3522 { 3522 {
3523 struct cfs_rq *src_cfs_rq, *dest_cfs_rq; 3523 struct cfs_rq *src_cfs_rq, *dest_cfs_rq;
3524 3524
3525 src_cfs_rq = tg->cfs_rq[src_cpu]; 3525 src_cfs_rq = tg->cfs_rq[src_cpu];
3526 dest_cfs_rq = tg->cfs_rq[dest_cpu]; 3526 dest_cfs_rq = tg->cfs_rq[dest_cpu];
3527 3527
3528 return throttled_hierarchy(src_cfs_rq) || 3528 return throttled_hierarchy(src_cfs_rq) ||
3529 throttled_hierarchy(dest_cfs_rq); 3529 throttled_hierarchy(dest_cfs_rq);
3530 } 3530 }
3531 3531
3532 /* updated child weight may affect parent so we have to do this bottom up */ 3532 /* updated child weight may affect parent so we have to do this bottom up */
3533 static int tg_unthrottle_up(struct task_group *tg, void *data) 3533 static int tg_unthrottle_up(struct task_group *tg, void *data)
3534 { 3534 {
3535 struct rq *rq = data; 3535 struct rq *rq = data;
3536 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)]; 3536 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
3537 3537
3538 cfs_rq->throttle_count--; 3538 cfs_rq->throttle_count--;
3539 #ifdef CONFIG_SMP 3539 #ifdef CONFIG_SMP
3540 if (!cfs_rq->throttle_count) { 3540 if (!cfs_rq->throttle_count) {
3541 /* adjust cfs_rq_clock_task() */ 3541 /* adjust cfs_rq_clock_task() */
3542 cfs_rq->throttled_clock_task_time += rq_clock_task(rq) - 3542 cfs_rq->throttled_clock_task_time += rq_clock_task(rq) -
3543 cfs_rq->throttled_clock_task; 3543 cfs_rq->throttled_clock_task;
3544 } 3544 }
3545 #endif 3545 #endif
3546 3546
3547 return 0; 3547 return 0;
3548 } 3548 }
3549 3549
3550 static int tg_throttle_down(struct task_group *tg, void *data) 3550 static int tg_throttle_down(struct task_group *tg, void *data)
3551 { 3551 {
3552 struct rq *rq = data; 3552 struct rq *rq = data;
3553 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)]; 3553 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)];
3554 3554
3555 /* group is entering throttled state, stop time */ 3555 /* group is entering throttled state, stop time */
3556 if (!cfs_rq->throttle_count) 3556 if (!cfs_rq->throttle_count)
3557 cfs_rq->throttled_clock_task = rq_clock_task(rq); 3557 cfs_rq->throttled_clock_task = rq_clock_task(rq);
3558 cfs_rq->throttle_count++; 3558 cfs_rq->throttle_count++;
3559 3559
3560 return 0; 3560 return 0;
3561 } 3561 }
3562 3562
3563 static void throttle_cfs_rq(struct cfs_rq *cfs_rq) 3563 static void throttle_cfs_rq(struct cfs_rq *cfs_rq)
3564 { 3564 {
3565 struct rq *rq = rq_of(cfs_rq); 3565 struct rq *rq = rq_of(cfs_rq);
3566 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 3566 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
3567 struct sched_entity *se; 3567 struct sched_entity *se;
3568 long task_delta, dequeue = 1; 3568 long task_delta, dequeue = 1;
3569 3569
3570 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))]; 3570 se = cfs_rq->tg->se[cpu_of(rq_of(cfs_rq))];
3571 3571
3572 /* freeze hierarchy runnable averages while throttled */ 3572 /* freeze hierarchy runnable averages while throttled */
3573 rcu_read_lock(); 3573 rcu_read_lock();
3574 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq); 3574 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq);
3575 rcu_read_unlock(); 3575 rcu_read_unlock();
3576 3576
3577 task_delta = cfs_rq->h_nr_running; 3577 task_delta = cfs_rq->h_nr_running;
3578 for_each_sched_entity(se) { 3578 for_each_sched_entity(se) {
3579 struct cfs_rq *qcfs_rq = cfs_rq_of(se); 3579 struct cfs_rq *qcfs_rq = cfs_rq_of(se);
3580 /* throttled entity or throttle-on-deactivate */ 3580 /* throttled entity or throttle-on-deactivate */
3581 if (!se->on_rq) 3581 if (!se->on_rq)
3582 break; 3582 break;
3583 3583
3584 if (dequeue) 3584 if (dequeue)
3585 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP); 3585 dequeue_entity(qcfs_rq, se, DEQUEUE_SLEEP);
3586 qcfs_rq->h_nr_running -= task_delta; 3586 qcfs_rq->h_nr_running -= task_delta;
3587 3587
3588 if (qcfs_rq->load.weight) 3588 if (qcfs_rq->load.weight)
3589 dequeue = 0; 3589 dequeue = 0;
3590 } 3590 }
3591 3591
3592 if (!se) 3592 if (!se)
3593 sub_nr_running(rq, task_delta); 3593 sub_nr_running(rq, task_delta);
3594 3594
3595 cfs_rq->throttled = 1; 3595 cfs_rq->throttled = 1;
3596 cfs_rq->throttled_clock = rq_clock(rq); 3596 cfs_rq->throttled_clock = rq_clock(rq);
3597 raw_spin_lock(&cfs_b->lock); 3597 raw_spin_lock(&cfs_b->lock);
3598 /* 3598 /*
3599 * Add to the _head_ of the list, so that an already-started 3599 * Add to the _head_ of the list, so that an already-started
3600 * distribute_cfs_runtime will not see us 3600 * distribute_cfs_runtime will not see us
3601 */ 3601 */
3602 list_add_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq); 3602 list_add_rcu(&cfs_rq->throttled_list, &cfs_b->throttled_cfs_rq);
3603 if (!cfs_b->timer_active) 3603 if (!cfs_b->timer_active)
3604 __start_cfs_bandwidth(cfs_b, false); 3604 __start_cfs_bandwidth(cfs_b, false);
3605 raw_spin_unlock(&cfs_b->lock); 3605 raw_spin_unlock(&cfs_b->lock);
3606 } 3606 }
3607 3607
3608 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq) 3608 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq)
3609 { 3609 {
3610 struct rq *rq = rq_of(cfs_rq); 3610 struct rq *rq = rq_of(cfs_rq);
3611 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 3611 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
3612 struct sched_entity *se; 3612 struct sched_entity *se;
3613 int enqueue = 1; 3613 int enqueue = 1;
3614 long task_delta; 3614 long task_delta;
3615 3615
3616 se = cfs_rq->tg->se[cpu_of(rq)]; 3616 se = cfs_rq->tg->se[cpu_of(rq)];
3617 3617
3618 cfs_rq->throttled = 0; 3618 cfs_rq->throttled = 0;
3619 3619
3620 update_rq_clock(rq); 3620 update_rq_clock(rq);
3621 3621
3622 raw_spin_lock(&cfs_b->lock); 3622 raw_spin_lock(&cfs_b->lock);
3623 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock; 3623 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock;
3624 list_del_rcu(&cfs_rq->throttled_list); 3624 list_del_rcu(&cfs_rq->throttled_list);
3625 raw_spin_unlock(&cfs_b->lock); 3625 raw_spin_unlock(&cfs_b->lock);
3626 3626
3627 /* update hierarchical throttle state */ 3627 /* update hierarchical throttle state */
3628 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq); 3628 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq);
3629 3629
3630 if (!cfs_rq->load.weight) 3630 if (!cfs_rq->load.weight)
3631 return; 3631 return;
3632 3632
3633 task_delta = cfs_rq->h_nr_running; 3633 task_delta = cfs_rq->h_nr_running;
3634 for_each_sched_entity(se) { 3634 for_each_sched_entity(se) {
3635 if (se->on_rq) 3635 if (se->on_rq)
3636 enqueue = 0; 3636 enqueue = 0;
3637 3637
3638 cfs_rq = cfs_rq_of(se); 3638 cfs_rq = cfs_rq_of(se);
3639 if (enqueue) 3639 if (enqueue)
3640 enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP); 3640 enqueue_entity(cfs_rq, se, ENQUEUE_WAKEUP);
3641 cfs_rq->h_nr_running += task_delta; 3641 cfs_rq->h_nr_running += task_delta;
3642 3642
3643 if (cfs_rq_throttled(cfs_rq)) 3643 if (cfs_rq_throttled(cfs_rq))
3644 break; 3644 break;
3645 } 3645 }
3646 3646
3647 if (!se) 3647 if (!se)
3648 add_nr_running(rq, task_delta); 3648 add_nr_running(rq, task_delta);
3649 3649
3650 /* determine whether we need to wake up potentially idle cpu */ 3650 /* determine whether we need to wake up potentially idle cpu */
3651 if (rq->curr == rq->idle && rq->cfs.nr_running) 3651 if (rq->curr == rq->idle && rq->cfs.nr_running)
3652 resched_curr(rq); 3652 resched_curr(rq);
3653 } 3653 }
3654 3654
3655 static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b, 3655 static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b,
3656 u64 remaining, u64 expires) 3656 u64 remaining, u64 expires)
3657 { 3657 {
3658 struct cfs_rq *cfs_rq; 3658 struct cfs_rq *cfs_rq;
3659 u64 runtime; 3659 u64 runtime;
3660 u64 starting_runtime = remaining; 3660 u64 starting_runtime = remaining;
3661 3661
3662 rcu_read_lock(); 3662 rcu_read_lock();
3663 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq, 3663 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq,
3664 throttled_list) { 3664 throttled_list) {
3665 struct rq *rq = rq_of(cfs_rq); 3665 struct rq *rq = rq_of(cfs_rq);
3666 3666
3667 raw_spin_lock(&rq->lock); 3667 raw_spin_lock(&rq->lock);
3668 if (!cfs_rq_throttled(cfs_rq)) 3668 if (!cfs_rq_throttled(cfs_rq))
3669 goto next; 3669 goto next;
3670 3670
3671 runtime = -cfs_rq->runtime_remaining + 1; 3671 runtime = -cfs_rq->runtime_remaining + 1;
3672 if (runtime > remaining) 3672 if (runtime > remaining)
3673 runtime = remaining; 3673 runtime = remaining;
3674 remaining -= runtime; 3674 remaining -= runtime;
3675 3675
3676 cfs_rq->runtime_remaining += runtime; 3676 cfs_rq->runtime_remaining += runtime;
3677 cfs_rq->runtime_expires = expires; 3677 cfs_rq->runtime_expires = expires;
3678 3678
3679 /* we check whether we're throttled above */ 3679 /* we check whether we're throttled above */
3680 if (cfs_rq->runtime_remaining > 0) 3680 if (cfs_rq->runtime_remaining > 0)
3681 unthrottle_cfs_rq(cfs_rq); 3681 unthrottle_cfs_rq(cfs_rq);
3682 3682
3683 next: 3683 next:
3684 raw_spin_unlock(&rq->lock); 3684 raw_spin_unlock(&rq->lock);
3685 3685
3686 if (!remaining) 3686 if (!remaining)
3687 break; 3687 break;
3688 } 3688 }
3689 rcu_read_unlock(); 3689 rcu_read_unlock();
3690 3690
3691 return starting_runtime - remaining; 3691 return starting_runtime - remaining;
3692 } 3692 }
3693 3693
3694 /* 3694 /*
3695 * Responsible for refilling a task_group's bandwidth and unthrottling its 3695 * Responsible for refilling a task_group's bandwidth and unthrottling its
3696 * cfs_rqs as appropriate. If there has been no activity within the last 3696 * cfs_rqs as appropriate. If there has been no activity within the last
3697 * period the timer is deactivated until scheduling resumes; cfs_b->idle is 3697 * period the timer is deactivated until scheduling resumes; cfs_b->idle is
3698 * used to track this state. 3698 * used to track this state.
3699 */ 3699 */
3700 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun) 3700 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun)
3701 { 3701 {
3702 u64 runtime, runtime_expires; 3702 u64 runtime, runtime_expires;
3703 int throttled; 3703 int throttled;
3704 3704
3705 /* no need to continue the timer with no bandwidth constraint */ 3705 /* no need to continue the timer with no bandwidth constraint */
3706 if (cfs_b->quota == RUNTIME_INF) 3706 if (cfs_b->quota == RUNTIME_INF)
3707 goto out_deactivate; 3707 goto out_deactivate;
3708 3708
3709 throttled = !list_empty(&cfs_b->throttled_cfs_rq); 3709 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
3710 cfs_b->nr_periods += overrun; 3710 cfs_b->nr_periods += overrun;
3711 3711
3712 /* 3712 /*
3713 * idle depends on !throttled (for the case of a large deficit), and if 3713 * idle depends on !throttled (for the case of a large deficit), and if
3714 * we're going inactive then everything else can be deferred 3714 * we're going inactive then everything else can be deferred
3715 */ 3715 */
3716 if (cfs_b->idle && !throttled) 3716 if (cfs_b->idle && !throttled)
3717 goto out_deactivate; 3717 goto out_deactivate;
3718 3718
3719 /* 3719 /*
3720 * if we have relooped after returning idle once, we need to update our 3720 * if we have relooped after returning idle once, we need to update our
3721 * status as actually running, so that other cpus doing 3721 * status as actually running, so that other cpus doing
3722 * __start_cfs_bandwidth will stop trying to cancel us. 3722 * __start_cfs_bandwidth will stop trying to cancel us.
3723 */ 3723 */
3724 cfs_b->timer_active = 1; 3724 cfs_b->timer_active = 1;
3725 3725
3726 __refill_cfs_bandwidth_runtime(cfs_b); 3726 __refill_cfs_bandwidth_runtime(cfs_b);
3727 3727
3728 if (!throttled) { 3728 if (!throttled) {
3729 /* mark as potentially idle for the upcoming period */ 3729 /* mark as potentially idle for the upcoming period */
3730 cfs_b->idle = 1; 3730 cfs_b->idle = 1;
3731 return 0; 3731 return 0;
3732 } 3732 }
3733 3733
3734 /* account preceding periods in which throttling occurred */ 3734 /* account preceding periods in which throttling occurred */
3735 cfs_b->nr_throttled += overrun; 3735 cfs_b->nr_throttled += overrun;
3736 3736
3737 runtime_expires = cfs_b->runtime_expires; 3737 runtime_expires = cfs_b->runtime_expires;
3738 3738
3739 /* 3739 /*
3740 * This check is repeated as we are holding onto the new bandwidth while 3740 * This check is repeated as we are holding onto the new bandwidth while
3741 * we unthrottle. This can potentially race with an unthrottled group 3741 * we unthrottle. This can potentially race with an unthrottled group
3742 * trying to acquire new bandwidth from the global pool. This can result 3742 * trying to acquire new bandwidth from the global pool. This can result
3743 * in us over-using our runtime if it is all used during this loop, but 3743 * in us over-using our runtime if it is all used during this loop, but
3744 * only by limited amounts in that extreme case. 3744 * only by limited amounts in that extreme case.
3745 */ 3745 */
3746 while (throttled && cfs_b->runtime > 0) { 3746 while (throttled && cfs_b->runtime > 0) {
3747 runtime = cfs_b->runtime; 3747 runtime = cfs_b->runtime;
3748 raw_spin_unlock(&cfs_b->lock); 3748 raw_spin_unlock(&cfs_b->lock);
3749 /* we can't nest cfs_b->lock while distributing bandwidth */ 3749 /* we can't nest cfs_b->lock while distributing bandwidth */
3750 runtime = distribute_cfs_runtime(cfs_b, runtime, 3750 runtime = distribute_cfs_runtime(cfs_b, runtime,
3751 runtime_expires); 3751 runtime_expires);
3752 raw_spin_lock(&cfs_b->lock); 3752 raw_spin_lock(&cfs_b->lock);
3753 3753
3754 throttled = !list_empty(&cfs_b->throttled_cfs_rq); 3754 throttled = !list_empty(&cfs_b->throttled_cfs_rq);
3755 3755
3756 cfs_b->runtime -= min(runtime, cfs_b->runtime); 3756 cfs_b->runtime -= min(runtime, cfs_b->runtime);
3757 } 3757 }
3758 3758
3759 /* 3759 /*
3760 * While we are ensured activity in the period following an 3760 * While we are ensured activity in the period following an
3761 * unthrottle, this also covers the case in which the new bandwidth is 3761 * unthrottle, this also covers the case in which the new bandwidth is
3762 * insufficient to cover the existing bandwidth deficit. (Forcing the 3762 * insufficient to cover the existing bandwidth deficit. (Forcing the
3763 * timer to remain active while there are any throttled entities.) 3763 * timer to remain active while there are any throttled entities.)
3764 */ 3764 */
3765 cfs_b->idle = 0; 3765 cfs_b->idle = 0;
3766 3766
3767 return 0; 3767 return 0;
3768 3768
3769 out_deactivate: 3769 out_deactivate:
3770 cfs_b->timer_active = 0; 3770 cfs_b->timer_active = 0;
3771 return 1; 3771 return 1;
3772 } 3772 }
3773 3773
3774 /* a cfs_rq won't donate quota below this amount */ 3774 /* a cfs_rq won't donate quota below this amount */
3775 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC; 3775 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC;
3776 /* minimum remaining period time to redistribute slack quota */ 3776 /* minimum remaining period time to redistribute slack quota */
3777 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC; 3777 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC;
3778 /* how long we wait to gather additional slack before distributing */ 3778 /* how long we wait to gather additional slack before distributing */
3779 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC; 3779 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC;
3780 3780
3781 /* 3781 /*
3782 * Are we near the end of the current quota period? 3782 * Are we near the end of the current quota period?
3783 * 3783 *
3784 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the 3784 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the
3785 * hrtimer base being cleared by __hrtimer_start_range_ns. In the case of 3785 * hrtimer base being cleared by __hrtimer_start_range_ns. In the case of
3786 * migrate_hrtimers, base is never cleared, so we are fine. 3786 * migrate_hrtimers, base is never cleared, so we are fine.
3787 */ 3787 */
3788 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire) 3788 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire)
3789 { 3789 {
3790 struct hrtimer *refresh_timer = &cfs_b->period_timer; 3790 struct hrtimer *refresh_timer = &cfs_b->period_timer;
3791 u64 remaining; 3791 u64 remaining;
3792 3792
3793 /* if the call-back is running a quota refresh is already occurring */ 3793 /* if the call-back is running a quota refresh is already occurring */
3794 if (hrtimer_callback_running(refresh_timer)) 3794 if (hrtimer_callback_running(refresh_timer))
3795 return 1; 3795 return 1;
3796 3796
3797 /* is a quota refresh about to occur? */ 3797 /* is a quota refresh about to occur? */
3798 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer)); 3798 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer));
3799 if (remaining < min_expire) 3799 if (remaining < min_expire)
3800 return 1; 3800 return 1;
3801 3801
3802 return 0; 3802 return 0;
3803 } 3803 }
3804 3804
3805 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b) 3805 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b)
3806 { 3806 {
3807 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration; 3807 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration;
3808 3808
3809 /* if there's a quota refresh soon don't bother with slack */ 3809 /* if there's a quota refresh soon don't bother with slack */
3810 if (runtime_refresh_within(cfs_b, min_left)) 3810 if (runtime_refresh_within(cfs_b, min_left))
3811 return; 3811 return;
3812 3812
3813 start_bandwidth_timer(&cfs_b->slack_timer, 3813 start_bandwidth_timer(&cfs_b->slack_timer,
3814 ns_to_ktime(cfs_bandwidth_slack_period)); 3814 ns_to_ktime(cfs_bandwidth_slack_period));
3815 } 3815 }
3816 3816
3817 /* we know any runtime found here is valid as update_curr() precedes return */ 3817 /* we know any runtime found here is valid as update_curr() precedes return */
3818 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq) 3818 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
3819 { 3819 {
3820 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 3820 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg);
3821 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime; 3821 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime;
3822 3822
3823 if (slack_runtime <= 0) 3823 if (slack_runtime <= 0)
3824 return; 3824 return;
3825 3825
3826 raw_spin_lock(&cfs_b->lock); 3826 raw_spin_lock(&cfs_b->lock);
3827 if (cfs_b->quota != RUNTIME_INF && 3827 if (cfs_b->quota != RUNTIME_INF &&
3828 cfs_rq->runtime_expires == cfs_b->runtime_expires) { 3828 cfs_rq->runtime_expires == cfs_b->runtime_expires) {
3829 cfs_b->runtime += slack_runtime; 3829 cfs_b->runtime += slack_runtime;
3830 3830
3831 /* we are under rq->lock, defer unthrottling using a timer */ 3831 /* we are under rq->lock, defer unthrottling using a timer */
3832 if (cfs_b->runtime > sched_cfs_bandwidth_slice() && 3832 if (cfs_b->runtime > sched_cfs_bandwidth_slice() &&
3833 !list_empty(&cfs_b->throttled_cfs_rq)) 3833 !list_empty(&cfs_b->throttled_cfs_rq))
3834 start_cfs_slack_bandwidth(cfs_b); 3834 start_cfs_slack_bandwidth(cfs_b);
3835 } 3835 }
3836 raw_spin_unlock(&cfs_b->lock); 3836 raw_spin_unlock(&cfs_b->lock);
3837 3837
3838 /* even if it's not valid for return we don't want to try again */ 3838 /* even if it's not valid for return we don't want to try again */
3839 cfs_rq->runtime_remaining -= slack_runtime; 3839 cfs_rq->runtime_remaining -= slack_runtime;
3840 } 3840 }
3841 3841
3842 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) 3842 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq)
3843 { 3843 {
3844 if (!cfs_bandwidth_used()) 3844 if (!cfs_bandwidth_used())
3845 return; 3845 return;
3846 3846
3847 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running) 3847 if (!cfs_rq->runtime_enabled || cfs_rq->nr_running)
3848 return; 3848 return;
3849 3849
3850 __return_cfs_rq_runtime(cfs_rq); 3850 __return_cfs_rq_runtime(cfs_rq);
3851 } 3851 }
3852 3852
3853 /* 3853 /*
3854 * This is done with a timer (instead of inline with bandwidth return) since 3854 * This is done with a timer (instead of inline with bandwidth return) since
3855 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs. 3855 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs.
3856 */ 3856 */
3857 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b) 3857 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b)
3858 { 3858 {
3859 u64 runtime = 0, slice = sched_cfs_bandwidth_slice(); 3859 u64 runtime = 0, slice = sched_cfs_bandwidth_slice();
3860 u64 expires; 3860 u64 expires;
3861 3861
3862 /* confirm we're still not at a refresh boundary */ 3862 /* confirm we're still not at a refresh boundary */
3863 raw_spin_lock(&cfs_b->lock); 3863 raw_spin_lock(&cfs_b->lock);
3864 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) { 3864 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) {
3865 raw_spin_unlock(&cfs_b->lock); 3865 raw_spin_unlock(&cfs_b->lock);
3866 return; 3866 return;
3867 } 3867 }
3868 3868
3869 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) 3869 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice)
3870 runtime = cfs_b->runtime; 3870 runtime = cfs_b->runtime;
3871 3871
3872 expires = cfs_b->runtime_expires; 3872 expires = cfs_b->runtime_expires;
3873 raw_spin_unlock(&cfs_b->lock); 3873 raw_spin_unlock(&cfs_b->lock);
3874 3874
3875 if (!runtime) 3875 if (!runtime)
3876 return; 3876 return;
3877 3877
3878 runtime = distribute_cfs_runtime(cfs_b, runtime, expires); 3878 runtime = distribute_cfs_runtime(cfs_b, runtime, expires);
3879 3879
3880 raw_spin_lock(&cfs_b->lock); 3880 raw_spin_lock(&cfs_b->lock);
3881 if (expires == cfs_b->runtime_expires) 3881 if (expires == cfs_b->runtime_expires)
3882 cfs_b->runtime -= min(runtime, cfs_b->runtime); 3882 cfs_b->runtime -= min(runtime, cfs_b->runtime);
3883 raw_spin_unlock(&cfs_b->lock); 3883 raw_spin_unlock(&cfs_b->lock);
3884 } 3884 }
3885 3885
3886 /* 3886 /*
3887 * When a group wakes up we want to make sure that its quota is not already 3887 * When a group wakes up we want to make sure that its quota is not already
3888 * expired/exceeded, otherwise it may be allowed to steal additional ticks of 3888 * expired/exceeded, otherwise it may be allowed to steal additional ticks of
3889 * runtime as update_curr() throttling can not not trigger until it's on-rq. 3889 * runtime as update_curr() throttling can not not trigger until it's on-rq.
3890 */ 3890 */
3891 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) 3891 static void check_enqueue_throttle(struct cfs_rq *cfs_rq)
3892 { 3892 {
3893 if (!cfs_bandwidth_used()) 3893 if (!cfs_bandwidth_used())
3894 return; 3894 return;
3895 3895
3896 /* an active group must be handled by the update_curr()->put() path */ 3896 /* an active group must be handled by the update_curr()->put() path */
3897 if (!cfs_rq->runtime_enabled || cfs_rq->curr) 3897 if (!cfs_rq->runtime_enabled || cfs_rq->curr)
3898 return; 3898 return;
3899 3899
3900 /* ensure the group is not already throttled */ 3900 /* ensure the group is not already throttled */
3901 if (cfs_rq_throttled(cfs_rq)) 3901 if (cfs_rq_throttled(cfs_rq))
3902 return; 3902 return;
3903 3903
3904 /* update runtime allocation */ 3904 /* update runtime allocation */
3905 account_cfs_rq_runtime(cfs_rq, 0); 3905 account_cfs_rq_runtime(cfs_rq, 0);
3906 if (cfs_rq->runtime_remaining <= 0) 3906 if (cfs_rq->runtime_remaining <= 0)
3907 throttle_cfs_rq(cfs_rq); 3907 throttle_cfs_rq(cfs_rq);
3908 } 3908 }
3909 3909
3910 /* conditionally throttle active cfs_rq's from put_prev_entity() */ 3910 /* conditionally throttle active cfs_rq's from put_prev_entity() */
3911 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) 3911 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq)
3912 { 3912 {
3913 if (!cfs_bandwidth_used()) 3913 if (!cfs_bandwidth_used())
3914 return false; 3914 return false;
3915 3915
3916 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0)) 3916 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0))
3917 return false; 3917 return false;
3918 3918
3919 /* 3919 /*
3920 * it's possible for a throttled entity to be forced into a running 3920 * it's possible for a throttled entity to be forced into a running
3921 * state (e.g. set_curr_task), in this case we're finished. 3921 * state (e.g. set_curr_task), in this case we're finished.
3922 */ 3922 */
3923 if (cfs_rq_throttled(cfs_rq)) 3923 if (cfs_rq_throttled(cfs_rq))
3924 return true; 3924 return true;
3925 3925
3926 throttle_cfs_rq(cfs_rq); 3926 throttle_cfs_rq(cfs_rq);
3927 return true; 3927 return true;
3928 } 3928 }
3929 3929
3930 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer) 3930 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer)
3931 { 3931 {
3932 struct cfs_bandwidth *cfs_b = 3932 struct cfs_bandwidth *cfs_b =
3933 container_of(timer, struct cfs_bandwidth, slack_timer); 3933 container_of(timer, struct cfs_bandwidth, slack_timer);
3934 do_sched_cfs_slack_timer(cfs_b); 3934 do_sched_cfs_slack_timer(cfs_b);
3935 3935
3936 return HRTIMER_NORESTART; 3936 return HRTIMER_NORESTART;
3937 } 3937 }
3938 3938
3939 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer) 3939 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer)
3940 { 3940 {
3941 struct cfs_bandwidth *cfs_b = 3941 struct cfs_bandwidth *cfs_b =
3942 container_of(timer, struct cfs_bandwidth, period_timer); 3942 container_of(timer, struct cfs_bandwidth, period_timer);
3943 ktime_t now; 3943 ktime_t now;
3944 int overrun; 3944 int overrun;
3945 int idle = 0; 3945 int idle = 0;
3946 3946
3947 raw_spin_lock(&cfs_b->lock); 3947 raw_spin_lock(&cfs_b->lock);
3948 for (;;) { 3948 for (;;) {
3949 now = hrtimer_cb_get_time(timer); 3949 now = hrtimer_cb_get_time(timer);
3950 overrun = hrtimer_forward(timer, now, cfs_b->period); 3950 overrun = hrtimer_forward(timer, now, cfs_b->period);
3951 3951
3952 if (!overrun) 3952 if (!overrun)
3953 break; 3953 break;
3954 3954
3955 idle = do_sched_cfs_period_timer(cfs_b, overrun); 3955 idle = do_sched_cfs_period_timer(cfs_b, overrun);
3956 } 3956 }
3957 raw_spin_unlock(&cfs_b->lock); 3957 raw_spin_unlock(&cfs_b->lock);
3958 3958
3959 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART; 3959 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
3960 } 3960 }
3961 3961
3962 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) 3962 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
3963 { 3963 {
3964 raw_spin_lock_init(&cfs_b->lock); 3964 raw_spin_lock_init(&cfs_b->lock);
3965 cfs_b->runtime = 0; 3965 cfs_b->runtime = 0;
3966 cfs_b->quota = RUNTIME_INF; 3966 cfs_b->quota = RUNTIME_INF;
3967 cfs_b->period = ns_to_ktime(default_cfs_period()); 3967 cfs_b->period = ns_to_ktime(default_cfs_period());
3968 3968
3969 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq); 3969 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq);
3970 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); 3970 hrtimer_init(&cfs_b->period_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3971 cfs_b->period_timer.function = sched_cfs_period_timer; 3971 cfs_b->period_timer.function = sched_cfs_period_timer;
3972 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); 3972 hrtimer_init(&cfs_b->slack_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3973 cfs_b->slack_timer.function = sched_cfs_slack_timer; 3973 cfs_b->slack_timer.function = sched_cfs_slack_timer;
3974 } 3974 }
3975 3975
3976 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) 3976 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq)
3977 { 3977 {
3978 cfs_rq->runtime_enabled = 0; 3978 cfs_rq->runtime_enabled = 0;
3979 INIT_LIST_HEAD(&cfs_rq->throttled_list); 3979 INIT_LIST_HEAD(&cfs_rq->throttled_list);
3980 } 3980 }
3981 3981
3982 /* requires cfs_b->lock, may release to reprogram timer */ 3982 /* requires cfs_b->lock, may release to reprogram timer */
3983 void __start_cfs_bandwidth(struct cfs_bandwidth *cfs_b, bool force) 3983 void __start_cfs_bandwidth(struct cfs_bandwidth *cfs_b, bool force)
3984 { 3984 {
3985 /* 3985 /*
3986 * The timer may be active because we're trying to set a new bandwidth 3986 * The timer may be active because we're trying to set a new bandwidth
3987 * period or because we're racing with the tear-down path 3987 * period or because we're racing with the tear-down path
3988 * (timer_active==0 becomes visible before the hrtimer call-back 3988 * (timer_active==0 becomes visible before the hrtimer call-back
3989 * terminates). In either case we ensure that it's re-programmed 3989 * terminates). In either case we ensure that it's re-programmed
3990 */ 3990 */
3991 while (unlikely(hrtimer_active(&cfs_b->period_timer)) && 3991 while (unlikely(hrtimer_active(&cfs_b->period_timer)) &&
3992 hrtimer_try_to_cancel(&cfs_b->period_timer) < 0) { 3992 hrtimer_try_to_cancel(&cfs_b->period_timer) < 0) {
3993 /* bounce the lock to allow do_sched_cfs_period_timer to run */ 3993 /* bounce the lock to allow do_sched_cfs_period_timer to run */
3994 raw_spin_unlock(&cfs_b->lock); 3994 raw_spin_unlock(&cfs_b->lock);
3995 cpu_relax(); 3995 cpu_relax();
3996 raw_spin_lock(&cfs_b->lock); 3996 raw_spin_lock(&cfs_b->lock);
3997 /* if someone else restarted the timer then we're done */ 3997 /* if someone else restarted the timer then we're done */
3998 if (!force && cfs_b->timer_active) 3998 if (!force && cfs_b->timer_active)
3999 return; 3999 return;
4000 } 4000 }
4001 4001
4002 cfs_b->timer_active = 1; 4002 cfs_b->timer_active = 1;
4003 start_bandwidth_timer(&cfs_b->period_timer, cfs_b->period); 4003 start_bandwidth_timer(&cfs_b->period_timer, cfs_b->period);
4004 } 4004 }
4005 4005
4006 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) 4006 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b)
4007 { 4007 {
4008 /* init_cfs_bandwidth() was not called */
4009 if (!cfs_b->throttled_cfs_rq.next)
4010 return;
4011
4008 hrtimer_cancel(&cfs_b->period_timer); 4012 hrtimer_cancel(&cfs_b->period_timer);
4009 hrtimer_cancel(&cfs_b->slack_timer); 4013 hrtimer_cancel(&cfs_b->slack_timer);
4010 } 4014 }
4011 4015
4012 static void __maybe_unused update_runtime_enabled(struct rq *rq) 4016 static void __maybe_unused update_runtime_enabled(struct rq *rq)
4013 { 4017 {
4014 struct cfs_rq *cfs_rq; 4018 struct cfs_rq *cfs_rq;
4015 4019
4016 for_each_leaf_cfs_rq(rq, cfs_rq) { 4020 for_each_leaf_cfs_rq(rq, cfs_rq) {
4017 struct cfs_bandwidth *cfs_b = &cfs_rq->tg->cfs_bandwidth; 4021 struct cfs_bandwidth *cfs_b = &cfs_rq->tg->cfs_bandwidth;
4018 4022
4019 raw_spin_lock(&cfs_b->lock); 4023 raw_spin_lock(&cfs_b->lock);
4020 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF; 4024 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF;
4021 raw_spin_unlock(&cfs_b->lock); 4025 raw_spin_unlock(&cfs_b->lock);
4022 } 4026 }
4023 } 4027 }
4024 4028
4025 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq) 4029 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq)
4026 { 4030 {
4027 struct cfs_rq *cfs_rq; 4031 struct cfs_rq *cfs_rq;
4028 4032
4029 for_each_leaf_cfs_rq(rq, cfs_rq) { 4033 for_each_leaf_cfs_rq(rq, cfs_rq) {
4030 if (!cfs_rq->runtime_enabled) 4034 if (!cfs_rq->runtime_enabled)
4031 continue; 4035 continue;
4032 4036
4033 /* 4037 /*
4034 * clock_task is not advancing so we just need to make sure 4038 * clock_task is not advancing so we just need to make sure
4035 * there's some valid quota amount 4039 * there's some valid quota amount
4036 */ 4040 */
4037 cfs_rq->runtime_remaining = 1; 4041 cfs_rq->runtime_remaining = 1;
4038 /* 4042 /*
4039 * Offline rq is schedulable till cpu is completely disabled 4043 * Offline rq is schedulable till cpu is completely disabled
4040 * in take_cpu_down(), so we prevent new cfs throttling here. 4044 * in take_cpu_down(), so we prevent new cfs throttling here.
4041 */ 4045 */
4042 cfs_rq->runtime_enabled = 0; 4046 cfs_rq->runtime_enabled = 0;
4043 4047
4044 if (cfs_rq_throttled(cfs_rq)) 4048 if (cfs_rq_throttled(cfs_rq))
4045 unthrottle_cfs_rq(cfs_rq); 4049 unthrottle_cfs_rq(cfs_rq);
4046 } 4050 }
4047 } 4051 }
4048 4052
4049 #else /* CONFIG_CFS_BANDWIDTH */ 4053 #else /* CONFIG_CFS_BANDWIDTH */
4050 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq) 4054 static inline u64 cfs_rq_clock_task(struct cfs_rq *cfs_rq)
4051 { 4055 {
4052 return rq_clock_task(rq_of(cfs_rq)); 4056 return rq_clock_task(rq_of(cfs_rq));
4053 } 4057 }
4054 4058
4055 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {} 4059 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {}
4056 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; } 4060 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; }
4057 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {} 4061 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {}
4058 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {} 4062 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
4059 4063
4060 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq) 4064 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq)
4061 { 4065 {
4062 return 0; 4066 return 0;
4063 } 4067 }
4064 4068
4065 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq) 4069 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq)
4066 { 4070 {
4067 return 0; 4071 return 0;
4068 } 4072 }
4069 4073
4070 static inline int throttled_lb_pair(struct task_group *tg, 4074 static inline int throttled_lb_pair(struct task_group *tg,
4071 int src_cpu, int dest_cpu) 4075 int src_cpu, int dest_cpu)
4072 { 4076 {
4073 return 0; 4077 return 0;
4074 } 4078 }
4075 4079
4076 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {} 4080 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
4077 4081
4078 #ifdef CONFIG_FAIR_GROUP_SCHED 4082 #ifdef CONFIG_FAIR_GROUP_SCHED
4079 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {} 4083 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {}
4080 #endif 4084 #endif
4081 4085
4082 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg) 4086 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg)
4083 { 4087 {
4084 return NULL; 4088 return NULL;
4085 } 4089 }
4086 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {} 4090 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {}
4087 static inline void update_runtime_enabled(struct rq *rq) {} 4091 static inline void update_runtime_enabled(struct rq *rq) {}
4088 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {} 4092 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {}
4089 4093
4090 #endif /* CONFIG_CFS_BANDWIDTH */ 4094 #endif /* CONFIG_CFS_BANDWIDTH */
4091 4095
4092 /************************************************** 4096 /**************************************************
4093 * CFS operations on tasks: 4097 * CFS operations on tasks:
4094 */ 4098 */
4095 4099
4096 #ifdef CONFIG_SCHED_HRTICK 4100 #ifdef CONFIG_SCHED_HRTICK
4097 static void hrtick_start_fair(struct rq *rq, struct task_struct *p) 4101 static void hrtick_start_fair(struct rq *rq, struct task_struct *p)
4098 { 4102 {
4099 struct sched_entity *se = &p->se; 4103 struct sched_entity *se = &p->se;
4100 struct cfs_rq *cfs_rq = cfs_rq_of(se); 4104 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4101 4105
4102 WARN_ON(task_rq(p) != rq); 4106 WARN_ON(task_rq(p) != rq);
4103 4107
4104 if (cfs_rq->nr_running > 1) { 4108 if (cfs_rq->nr_running > 1) {
4105 u64 slice = sched_slice(cfs_rq, se); 4109 u64 slice = sched_slice(cfs_rq, se);
4106 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime; 4110 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime;
4107 s64 delta = slice - ran; 4111 s64 delta = slice - ran;
4108 4112
4109 if (delta < 0) { 4113 if (delta < 0) {
4110 if (rq->curr == p) 4114 if (rq->curr == p)
4111 resched_curr(rq); 4115 resched_curr(rq);
4112 return; 4116 return;
4113 } 4117 }
4114 hrtick_start(rq, delta); 4118 hrtick_start(rq, delta);
4115 } 4119 }
4116 } 4120 }
4117 4121
4118 /* 4122 /*
4119 * called from enqueue/dequeue and updates the hrtick when the 4123 * called from enqueue/dequeue and updates the hrtick when the
4120 * current task is from our class and nr_running is low enough 4124 * current task is from our class and nr_running is low enough
4121 * to matter. 4125 * to matter.
4122 */ 4126 */
4123 static void hrtick_update(struct rq *rq) 4127 static void hrtick_update(struct rq *rq)
4124 { 4128 {
4125 struct task_struct *curr = rq->curr; 4129 struct task_struct *curr = rq->curr;
4126 4130
4127 if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class) 4131 if (!hrtick_enabled(rq) || curr->sched_class != &fair_sched_class)
4128 return; 4132 return;
4129 4133
4130 if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency) 4134 if (cfs_rq_of(&curr->se)->nr_running < sched_nr_latency)
4131 hrtick_start_fair(rq, curr); 4135 hrtick_start_fair(rq, curr);
4132 } 4136 }
4133 #else /* !CONFIG_SCHED_HRTICK */ 4137 #else /* !CONFIG_SCHED_HRTICK */
4134 static inline void 4138 static inline void
4135 hrtick_start_fair(struct rq *rq, struct task_struct *p) 4139 hrtick_start_fair(struct rq *rq, struct task_struct *p)
4136 { 4140 {
4137 } 4141 }
4138 4142
4139 static inline void hrtick_update(struct rq *rq) 4143 static inline void hrtick_update(struct rq *rq)
4140 { 4144 {
4141 } 4145 }
4142 #endif 4146 #endif
4143 4147
4144 /* 4148 /*
4145 * The enqueue_task method is called before nr_running is 4149 * The enqueue_task method is called before nr_running is
4146 * increased. Here we update the fair scheduling stats and 4150 * increased. Here we update the fair scheduling stats and
4147 * then put the task into the rbtree: 4151 * then put the task into the rbtree:
4148 */ 4152 */
4149 static void 4153 static void
4150 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) 4154 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags)
4151 { 4155 {
4152 struct cfs_rq *cfs_rq; 4156 struct cfs_rq *cfs_rq;
4153 struct sched_entity *se = &p->se; 4157 struct sched_entity *se = &p->se;
4154 4158
4155 for_each_sched_entity(se) { 4159 for_each_sched_entity(se) {
4156 if (se->on_rq) 4160 if (se->on_rq)
4157 break; 4161 break;
4158 cfs_rq = cfs_rq_of(se); 4162 cfs_rq = cfs_rq_of(se);
4159 enqueue_entity(cfs_rq, se, flags); 4163 enqueue_entity(cfs_rq, se, flags);
4160 4164
4161 /* 4165 /*
4162 * end evaluation on encountering a throttled cfs_rq 4166 * end evaluation on encountering a throttled cfs_rq
4163 * 4167 *
4164 * note: in the case of encountering a throttled cfs_rq we will 4168 * note: in the case of encountering a throttled cfs_rq we will
4165 * post the final h_nr_running increment below. 4169 * post the final h_nr_running increment below.
4166 */ 4170 */
4167 if (cfs_rq_throttled(cfs_rq)) 4171 if (cfs_rq_throttled(cfs_rq))
4168 break; 4172 break;
4169 cfs_rq->h_nr_running++; 4173 cfs_rq->h_nr_running++;
4170 4174
4171 flags = ENQUEUE_WAKEUP; 4175 flags = ENQUEUE_WAKEUP;
4172 } 4176 }
4173 4177
4174 for_each_sched_entity(se) { 4178 for_each_sched_entity(se) {
4175 cfs_rq = cfs_rq_of(se); 4179 cfs_rq = cfs_rq_of(se);
4176 cfs_rq->h_nr_running++; 4180 cfs_rq->h_nr_running++;
4177 4181
4178 if (cfs_rq_throttled(cfs_rq)) 4182 if (cfs_rq_throttled(cfs_rq))
4179 break; 4183 break;
4180 4184
4181 update_cfs_shares(cfs_rq); 4185 update_cfs_shares(cfs_rq);
4182 update_entity_load_avg(se, 1); 4186 update_entity_load_avg(se, 1);
4183 } 4187 }
4184 4188
4185 if (!se) { 4189 if (!se) {
4186 update_rq_runnable_avg(rq, rq->nr_running); 4190 update_rq_runnable_avg(rq, rq->nr_running);
4187 add_nr_running(rq, 1); 4191 add_nr_running(rq, 1);
4188 } 4192 }
4189 hrtick_update(rq); 4193 hrtick_update(rq);
4190 } 4194 }
4191 4195
4192 static void set_next_buddy(struct sched_entity *se); 4196 static void set_next_buddy(struct sched_entity *se);
4193 4197
4194 /* 4198 /*
4195 * The dequeue_task method is called before nr_running is 4199 * The dequeue_task method is called before nr_running is
4196 * decreased. We remove the task from the rbtree and 4200 * decreased. We remove the task from the rbtree and
4197 * update the fair scheduling stats: 4201 * update the fair scheduling stats:
4198 */ 4202 */
4199 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags) 4203 static void dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags)
4200 { 4204 {
4201 struct cfs_rq *cfs_rq; 4205 struct cfs_rq *cfs_rq;
4202 struct sched_entity *se = &p->se; 4206 struct sched_entity *se = &p->se;
4203 int task_sleep = flags & DEQUEUE_SLEEP; 4207 int task_sleep = flags & DEQUEUE_SLEEP;
4204 4208
4205 for_each_sched_entity(se) { 4209 for_each_sched_entity(se) {
4206 cfs_rq = cfs_rq_of(se); 4210 cfs_rq = cfs_rq_of(se);
4207 dequeue_entity(cfs_rq, se, flags); 4211 dequeue_entity(cfs_rq, se, flags);
4208 4212
4209 /* 4213 /*
4210 * end evaluation on encountering a throttled cfs_rq 4214 * end evaluation on encountering a throttled cfs_rq
4211 * 4215 *
4212 * note: in the case of encountering a throttled cfs_rq we will 4216 * note: in the case of encountering a throttled cfs_rq we will
4213 * post the final h_nr_running decrement below. 4217 * post the final h_nr_running decrement below.
4214 */ 4218 */
4215 if (cfs_rq_throttled(cfs_rq)) 4219 if (cfs_rq_throttled(cfs_rq))
4216 break; 4220 break;
4217 cfs_rq->h_nr_running--; 4221 cfs_rq->h_nr_running--;
4218 4222
4219 /* Don't dequeue parent if it has other entities besides us */ 4223 /* Don't dequeue parent if it has other entities besides us */
4220 if (cfs_rq->load.weight) { 4224 if (cfs_rq->load.weight) {
4221 /* 4225 /*
4222 * Bias pick_next to pick a task from this cfs_rq, as 4226 * Bias pick_next to pick a task from this cfs_rq, as
4223 * p is sleeping when it is within its sched_slice. 4227 * p is sleeping when it is within its sched_slice.
4224 */ 4228 */
4225 if (task_sleep && parent_entity(se)) 4229 if (task_sleep && parent_entity(se))
4226 set_next_buddy(parent_entity(se)); 4230 set_next_buddy(parent_entity(se));
4227 4231
4228 /* avoid re-evaluating load for this entity */ 4232 /* avoid re-evaluating load for this entity */
4229 se = parent_entity(se); 4233 se = parent_entity(se);
4230 break; 4234 break;
4231 } 4235 }
4232 flags |= DEQUEUE_SLEEP; 4236 flags |= DEQUEUE_SLEEP;
4233 } 4237 }
4234 4238
4235 for_each_sched_entity(se) { 4239 for_each_sched_entity(se) {
4236 cfs_rq = cfs_rq_of(se); 4240 cfs_rq = cfs_rq_of(se);
4237 cfs_rq->h_nr_running--; 4241 cfs_rq->h_nr_running--;
4238 4242
4239 if (cfs_rq_throttled(cfs_rq)) 4243 if (cfs_rq_throttled(cfs_rq))
4240 break; 4244 break;
4241 4245
4242 update_cfs_shares(cfs_rq); 4246 update_cfs_shares(cfs_rq);
4243 update_entity_load_avg(se, 1); 4247 update_entity_load_avg(se, 1);
4244 } 4248 }
4245 4249
4246 if (!se) { 4250 if (!se) {
4247 sub_nr_running(rq, 1); 4251 sub_nr_running(rq, 1);
4248 update_rq_runnable_avg(rq, 1); 4252 update_rq_runnable_avg(rq, 1);
4249 } 4253 }
4250 hrtick_update(rq); 4254 hrtick_update(rq);
4251 } 4255 }
4252 4256
4253 #ifdef CONFIG_SMP 4257 #ifdef CONFIG_SMP
4254 /* Used instead of source_load when we know the type == 0 */ 4258 /* Used instead of source_load when we know the type == 0 */
4255 static unsigned long weighted_cpuload(const int cpu) 4259 static unsigned long weighted_cpuload(const int cpu)
4256 { 4260 {
4257 return cpu_rq(cpu)->cfs.runnable_load_avg; 4261 return cpu_rq(cpu)->cfs.runnable_load_avg;
4258 } 4262 }
4259 4263
4260 /* 4264 /*
4261 * Return a low guess at the load of a migration-source cpu weighted 4265 * Return a low guess at the load of a migration-source cpu weighted
4262 * according to the scheduling class and "nice" value. 4266 * according to the scheduling class and "nice" value.
4263 * 4267 *
4264 * We want to under-estimate the load of migration sources, to 4268 * We want to under-estimate the load of migration sources, to
4265 * balance conservatively. 4269 * balance conservatively.
4266 */ 4270 */
4267 static unsigned long source_load(int cpu, int type) 4271 static unsigned long source_load(int cpu, int type)
4268 { 4272 {
4269 struct rq *rq = cpu_rq(cpu); 4273 struct rq *rq = cpu_rq(cpu);
4270 unsigned long total = weighted_cpuload(cpu); 4274 unsigned long total = weighted_cpuload(cpu);
4271 4275
4272 if (type == 0 || !sched_feat(LB_BIAS)) 4276 if (type == 0 || !sched_feat(LB_BIAS))
4273 return total; 4277 return total;
4274 4278
4275 return min(rq->cpu_load[type-1], total); 4279 return min(rq->cpu_load[type-1], total);
4276 } 4280 }
4277 4281
4278 /* 4282 /*
4279 * Return a high guess at the load of a migration-target cpu weighted 4283 * Return a high guess at the load of a migration-target cpu weighted
4280 * according to the scheduling class and "nice" value. 4284 * according to the scheduling class and "nice" value.
4281 */ 4285 */
4282 static unsigned long target_load(int cpu, int type) 4286 static unsigned long target_load(int cpu, int type)
4283 { 4287 {
4284 struct rq *rq = cpu_rq(cpu); 4288 struct rq *rq = cpu_rq(cpu);
4285 unsigned long total = weighted_cpuload(cpu); 4289 unsigned long total = weighted_cpuload(cpu);
4286 4290
4287 if (type == 0 || !sched_feat(LB_BIAS)) 4291 if (type == 0 || !sched_feat(LB_BIAS))
4288 return total; 4292 return total;
4289 4293
4290 return max(rq->cpu_load[type-1], total); 4294 return max(rq->cpu_load[type-1], total);
4291 } 4295 }
4292 4296
4293 static unsigned long capacity_of(int cpu) 4297 static unsigned long capacity_of(int cpu)
4294 { 4298 {
4295 return cpu_rq(cpu)->cpu_capacity; 4299 return cpu_rq(cpu)->cpu_capacity;
4296 } 4300 }
4297 4301
4298 static unsigned long cpu_avg_load_per_task(int cpu) 4302 static unsigned long cpu_avg_load_per_task(int cpu)
4299 { 4303 {
4300 struct rq *rq = cpu_rq(cpu); 4304 struct rq *rq = cpu_rq(cpu);
4301 unsigned long nr_running = ACCESS_ONCE(rq->cfs.h_nr_running); 4305 unsigned long nr_running = ACCESS_ONCE(rq->cfs.h_nr_running);
4302 unsigned long load_avg = rq->cfs.runnable_load_avg; 4306 unsigned long load_avg = rq->cfs.runnable_load_avg;
4303 4307
4304 if (nr_running) 4308 if (nr_running)
4305 return load_avg / nr_running; 4309 return load_avg / nr_running;
4306 4310
4307 return 0; 4311 return 0;
4308 } 4312 }
4309 4313
4310 static void record_wakee(struct task_struct *p) 4314 static void record_wakee(struct task_struct *p)
4311 { 4315 {
4312 /* 4316 /*
4313 * Rough decay (wiping) for cost saving, don't worry 4317 * Rough decay (wiping) for cost saving, don't worry
4314 * about the boundary, really active task won't care 4318 * about the boundary, really active task won't care
4315 * about the loss. 4319 * about the loss.
4316 */ 4320 */
4317 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) { 4321 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) {
4318 current->wakee_flips >>= 1; 4322 current->wakee_flips >>= 1;
4319 current->wakee_flip_decay_ts = jiffies; 4323 current->wakee_flip_decay_ts = jiffies;
4320 } 4324 }
4321 4325
4322 if (current->last_wakee != p) { 4326 if (current->last_wakee != p) {
4323 current->last_wakee = p; 4327 current->last_wakee = p;
4324 current->wakee_flips++; 4328 current->wakee_flips++;
4325 } 4329 }
4326 } 4330 }
4327 4331
4328 static void task_waking_fair(struct task_struct *p) 4332 static void task_waking_fair(struct task_struct *p)
4329 { 4333 {
4330 struct sched_entity *se = &p->se; 4334 struct sched_entity *se = &p->se;
4331 struct cfs_rq *cfs_rq = cfs_rq_of(se); 4335 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4332 u64 min_vruntime; 4336 u64 min_vruntime;
4333 4337
4334 #ifndef CONFIG_64BIT 4338 #ifndef CONFIG_64BIT
4335 u64 min_vruntime_copy; 4339 u64 min_vruntime_copy;
4336 4340
4337 do { 4341 do {
4338 min_vruntime_copy = cfs_rq->min_vruntime_copy; 4342 min_vruntime_copy = cfs_rq->min_vruntime_copy;
4339 smp_rmb(); 4343 smp_rmb();
4340 min_vruntime = cfs_rq->min_vruntime; 4344 min_vruntime = cfs_rq->min_vruntime;
4341 } while (min_vruntime != min_vruntime_copy); 4345 } while (min_vruntime != min_vruntime_copy);
4342 #else 4346 #else
4343 min_vruntime = cfs_rq->min_vruntime; 4347 min_vruntime = cfs_rq->min_vruntime;
4344 #endif 4348 #endif
4345 4349
4346 se->vruntime -= min_vruntime; 4350 se->vruntime -= min_vruntime;
4347 record_wakee(p); 4351 record_wakee(p);
4348 } 4352 }
4349 4353
4350 #ifdef CONFIG_FAIR_GROUP_SCHED 4354 #ifdef CONFIG_FAIR_GROUP_SCHED
4351 /* 4355 /*
4352 * effective_load() calculates the load change as seen from the root_task_group 4356 * effective_load() calculates the load change as seen from the root_task_group
4353 * 4357 *
4354 * Adding load to a group doesn't make a group heavier, but can cause movement 4358 * Adding load to a group doesn't make a group heavier, but can cause movement
4355 * of group shares between cpus. Assuming the shares were perfectly aligned one 4359 * of group shares between cpus. Assuming the shares were perfectly aligned one
4356 * can calculate the shift in shares. 4360 * can calculate the shift in shares.
4357 * 4361 *
4358 * Calculate the effective load difference if @wl is added (subtracted) to @tg 4362 * Calculate the effective load difference if @wl is added (subtracted) to @tg
4359 * on this @cpu and results in a total addition (subtraction) of @wg to the 4363 * on this @cpu and results in a total addition (subtraction) of @wg to the
4360 * total group weight. 4364 * total group weight.
4361 * 4365 *
4362 * Given a runqueue weight distribution (rw_i) we can compute a shares 4366 * Given a runqueue weight distribution (rw_i) we can compute a shares
4363 * distribution (s_i) using: 4367 * distribution (s_i) using:
4364 * 4368 *
4365 * s_i = rw_i / \Sum rw_j (1) 4369 * s_i = rw_i / \Sum rw_j (1)
4366 * 4370 *
4367 * Suppose we have 4 CPUs and our @tg is a direct child of the root group and 4371 * Suppose we have 4 CPUs and our @tg is a direct child of the root group and
4368 * has 7 equal weight tasks, distributed as below (rw_i), with the resulting 4372 * has 7 equal weight tasks, distributed as below (rw_i), with the resulting
4369 * shares distribution (s_i): 4373 * shares distribution (s_i):
4370 * 4374 *
4371 * rw_i = { 2, 4, 1, 0 } 4375 * rw_i = { 2, 4, 1, 0 }
4372 * s_i = { 2/7, 4/7, 1/7, 0 } 4376 * s_i = { 2/7, 4/7, 1/7, 0 }
4373 * 4377 *
4374 * As per wake_affine() we're interested in the load of two CPUs (the CPU the 4378 * As per wake_affine() we're interested in the load of two CPUs (the CPU the
4375 * task used to run on and the CPU the waker is running on), we need to 4379 * task used to run on and the CPU the waker is running on), we need to
4376 * compute the effect of waking a task on either CPU and, in case of a sync 4380 * compute the effect of waking a task on either CPU and, in case of a sync
4377 * wakeup, compute the effect of the current task going to sleep. 4381 * wakeup, compute the effect of the current task going to sleep.
4378 * 4382 *
4379 * So for a change of @wl to the local @cpu with an overall group weight change 4383 * So for a change of @wl to the local @cpu with an overall group weight change
4380 * of @wl we can compute the new shares distribution (s'_i) using: 4384 * of @wl we can compute the new shares distribution (s'_i) using:
4381 * 4385 *
4382 * s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2) 4386 * s'_i = (rw_i + @wl) / (@wg + \Sum rw_j) (2)
4383 * 4387 *
4384 * Suppose we're interested in CPUs 0 and 1, and want to compute the load 4388 * Suppose we're interested in CPUs 0 and 1, and want to compute the load
4385 * differences in waking a task to CPU 0. The additional task changes the 4389 * differences in waking a task to CPU 0. The additional task changes the
4386 * weight and shares distributions like: 4390 * weight and shares distributions like:
4387 * 4391 *
4388 * rw'_i = { 3, 4, 1, 0 } 4392 * rw'_i = { 3, 4, 1, 0 }
4389 * s'_i = { 3/8, 4/8, 1/8, 0 } 4393 * s'_i = { 3/8, 4/8, 1/8, 0 }
4390 * 4394 *
4391 * We can then compute the difference in effective weight by using: 4395 * We can then compute the difference in effective weight by using:
4392 * 4396 *
4393 * dw_i = S * (s'_i - s_i) (3) 4397 * dw_i = S * (s'_i - s_i) (3)
4394 * 4398 *
4395 * Where 'S' is the group weight as seen by its parent. 4399 * Where 'S' is the group weight as seen by its parent.
4396 * 4400 *
4397 * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7) 4401 * Therefore the effective change in loads on CPU 0 would be 5/56 (3/8 - 2/7)
4398 * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 - 4402 * times the weight of the group. The effect on CPU 1 would be -4/56 (4/8 -
4399 * 4/7) times the weight of the group. 4403 * 4/7) times the weight of the group.
4400 */ 4404 */
4401 static long effective_load(struct task_group *tg, int cpu, long wl, long wg) 4405 static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
4402 { 4406 {
4403 struct sched_entity *se = tg->se[cpu]; 4407 struct sched_entity *se = tg->se[cpu];
4404 4408
4405 if (!tg->parent) /* the trivial, non-cgroup case */ 4409 if (!tg->parent) /* the trivial, non-cgroup case */
4406 return wl; 4410 return wl;
4407 4411
4408 for_each_sched_entity(se) { 4412 for_each_sched_entity(se) {
4409 long w, W; 4413 long w, W;
4410 4414
4411 tg = se->my_q->tg; 4415 tg = se->my_q->tg;
4412 4416
4413 /* 4417 /*
4414 * W = @wg + \Sum rw_j 4418 * W = @wg + \Sum rw_j
4415 */ 4419 */
4416 W = wg + calc_tg_weight(tg, se->my_q); 4420 W = wg + calc_tg_weight(tg, se->my_q);
4417 4421
4418 /* 4422 /*
4419 * w = rw_i + @wl 4423 * w = rw_i + @wl
4420 */ 4424 */
4421 w = se->my_q->load.weight + wl; 4425 w = se->my_q->load.weight + wl;
4422 4426
4423 /* 4427 /*
4424 * wl = S * s'_i; see (2) 4428 * wl = S * s'_i; see (2)
4425 */ 4429 */
4426 if (W > 0 && w < W) 4430 if (W > 0 && w < W)
4427 wl = (w * tg->shares) / W; 4431 wl = (w * (long)tg->shares) / W;
4428 else 4432 else
4429 wl = tg->shares; 4433 wl = tg->shares;
4430 4434
4431 /* 4435 /*
4432 * Per the above, wl is the new se->load.weight value; since 4436 * Per the above, wl is the new se->load.weight value; since
4433 * those are clipped to [MIN_SHARES, ...) do so now. See 4437 * those are clipped to [MIN_SHARES, ...) do so now. See
4434 * calc_cfs_shares(). 4438 * calc_cfs_shares().
4435 */ 4439 */
4436 if (wl < MIN_SHARES) 4440 if (wl < MIN_SHARES)
4437 wl = MIN_SHARES; 4441 wl = MIN_SHARES;
4438 4442
4439 /* 4443 /*
4440 * wl = dw_i = S * (s'_i - s_i); see (3) 4444 * wl = dw_i = S * (s'_i - s_i); see (3)
4441 */ 4445 */
4442 wl -= se->load.weight; 4446 wl -= se->load.weight;
4443 4447
4444 /* 4448 /*
4445 * Recursively apply this logic to all parent groups to compute 4449 * Recursively apply this logic to all parent groups to compute
4446 * the final effective load change on the root group. Since 4450 * the final effective load change on the root group. Since
4447 * only the @tg group gets extra weight, all parent groups can 4451 * only the @tg group gets extra weight, all parent groups can
4448 * only redistribute existing shares. @wl is the shift in shares 4452 * only redistribute existing shares. @wl is the shift in shares
4449 * resulting from this level per the above. 4453 * resulting from this level per the above.
4450 */ 4454 */
4451 wg = 0; 4455 wg = 0;
4452 } 4456 }
4453 4457
4454 return wl; 4458 return wl;
4455 } 4459 }
4456 #else 4460 #else
4457 4461
4458 static long effective_load(struct task_group *tg, int cpu, long wl, long wg) 4462 static long effective_load(struct task_group *tg, int cpu, long wl, long wg)
4459 { 4463 {
4460 return wl; 4464 return wl;
4461 } 4465 }
4462 4466
4463 #endif 4467 #endif
4464 4468
4465 static int wake_wide(struct task_struct *p) 4469 static int wake_wide(struct task_struct *p)
4466 { 4470 {
4467 int factor = this_cpu_read(sd_llc_size); 4471 int factor = this_cpu_read(sd_llc_size);
4468 4472
4469 /* 4473 /*
4470 * Yeah, it's the switching-frequency, could means many wakee or 4474 * Yeah, it's the switching-frequency, could means many wakee or
4471 * rapidly switch, use factor here will just help to automatically 4475 * rapidly switch, use factor here will just help to automatically
4472 * adjust the loose-degree, so bigger node will lead to more pull. 4476 * adjust the loose-degree, so bigger node will lead to more pull.
4473 */ 4477 */
4474 if (p->wakee_flips > factor) { 4478 if (p->wakee_flips > factor) {
4475 /* 4479 /*
4476 * wakee is somewhat hot, it needs certain amount of cpu 4480 * wakee is somewhat hot, it needs certain amount of cpu
4477 * resource, so if waker is far more hot, prefer to leave 4481 * resource, so if waker is far more hot, prefer to leave
4478 * it alone. 4482 * it alone.
4479 */ 4483 */
4480 if (current->wakee_flips > (factor * p->wakee_flips)) 4484 if (current->wakee_flips > (factor * p->wakee_flips))
4481 return 1; 4485 return 1;
4482 } 4486 }
4483 4487
4484 return 0; 4488 return 0;
4485 } 4489 }
4486 4490
4487 static int wake_affine(struct sched_domain *sd, struct task_struct *p, int sync) 4491 static int wake_affine(struct sched_domain *sd, struct task_struct *p, int sync)
4488 { 4492 {
4489 s64 this_load, load; 4493 s64 this_load, load;
4490 s64 this_eff_load, prev_eff_load; 4494 s64 this_eff_load, prev_eff_load;
4491 int idx, this_cpu, prev_cpu; 4495 int idx, this_cpu, prev_cpu;
4492 struct task_group *tg; 4496 struct task_group *tg;
4493 unsigned long weight; 4497 unsigned long weight;
4494 int balanced; 4498 int balanced;
4495 4499
4496 /* 4500 /*
4497 * If we wake multiple tasks be careful to not bounce 4501 * If we wake multiple tasks be careful to not bounce
4498 * ourselves around too much. 4502 * ourselves around too much.
4499 */ 4503 */
4500 if (wake_wide(p)) 4504 if (wake_wide(p))
4501 return 0; 4505 return 0;
4502 4506
4503 idx = sd->wake_idx; 4507 idx = sd->wake_idx;
4504 this_cpu = smp_processor_id(); 4508 this_cpu = smp_processor_id();
4505 prev_cpu = task_cpu(p); 4509 prev_cpu = task_cpu(p);
4506 load = source_load(prev_cpu, idx); 4510 load = source_load(prev_cpu, idx);
4507 this_load = target_load(this_cpu, idx); 4511 this_load = target_load(this_cpu, idx);
4508 4512
4509 /* 4513 /*
4510 * If sync wakeup then subtract the (maximum possible) 4514 * If sync wakeup then subtract the (maximum possible)
4511 * effect of the currently running task from the load 4515 * effect of the currently running task from the load
4512 * of the current CPU: 4516 * of the current CPU:
4513 */ 4517 */
4514 if (sync) { 4518 if (sync) {
4515 tg = task_group(current); 4519 tg = task_group(current);
4516 weight = current->se.load.weight; 4520 weight = current->se.load.weight;
4517 4521
4518 this_load += effective_load(tg, this_cpu, -weight, -weight); 4522 this_load += effective_load(tg, this_cpu, -weight, -weight);
4519 load += effective_load(tg, prev_cpu, 0, -weight); 4523 load += effective_load(tg, prev_cpu, 0, -weight);
4520 } 4524 }
4521 4525
4522 tg = task_group(p); 4526 tg = task_group(p);
4523 weight = p->se.load.weight; 4527 weight = p->se.load.weight;
4524 4528
4525 /* 4529 /*
4526 * In low-load situations, where prev_cpu is idle and this_cpu is idle 4530 * In low-load situations, where prev_cpu is idle and this_cpu is idle
4527 * due to the sync cause above having dropped this_load to 0, we'll 4531 * due to the sync cause above having dropped this_load to 0, we'll
4528 * always have an imbalance, but there's really nothing you can do 4532 * always have an imbalance, but there's really nothing you can do
4529 * about that, so that's good too. 4533 * about that, so that's good too.
4530 * 4534 *
4531 * Otherwise check if either cpus are near enough in load to allow this 4535 * Otherwise check if either cpus are near enough in load to allow this
4532 * task to be woken on this_cpu. 4536 * task to be woken on this_cpu.
4533 */ 4537 */
4534 this_eff_load = 100; 4538 this_eff_load = 100;
4535 this_eff_load *= capacity_of(prev_cpu); 4539 this_eff_load *= capacity_of(prev_cpu);
4536 4540
4537 prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2; 4541 prev_eff_load = 100 + (sd->imbalance_pct - 100) / 2;
4538 prev_eff_load *= capacity_of(this_cpu); 4542 prev_eff_load *= capacity_of(this_cpu);
4539 4543
4540 if (this_load > 0) { 4544 if (this_load > 0) {
4541 this_eff_load *= this_load + 4545 this_eff_load *= this_load +
4542 effective_load(tg, this_cpu, weight, weight); 4546 effective_load(tg, this_cpu, weight, weight);
4543 4547
4544 prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight); 4548 prev_eff_load *= load + effective_load(tg, prev_cpu, 0, weight);
4545 } 4549 }
4546 4550
4547 balanced = this_eff_load <= prev_eff_load; 4551 balanced = this_eff_load <= prev_eff_load;
4548 4552
4549 schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts); 4553 schedstat_inc(p, se.statistics.nr_wakeups_affine_attempts);
4550 4554
4551 if (!balanced) 4555 if (!balanced)
4552 return 0; 4556 return 0;
4553 4557
4554 schedstat_inc(sd, ttwu_move_affine); 4558 schedstat_inc(sd, ttwu_move_affine);
4555 schedstat_inc(p, se.statistics.nr_wakeups_affine); 4559 schedstat_inc(p, se.statistics.nr_wakeups_affine);
4556 4560
4557 return 1; 4561 return 1;
4558 } 4562 }
4559 4563
4560 /* 4564 /*
4561 * find_idlest_group finds and returns the least busy CPU group within the 4565 * find_idlest_group finds and returns the least busy CPU group within the
4562 * domain. 4566 * domain.
4563 */ 4567 */
4564 static struct sched_group * 4568 static struct sched_group *
4565 find_idlest_group(struct sched_domain *sd, struct task_struct *p, 4569 find_idlest_group(struct sched_domain *sd, struct task_struct *p,
4566 int this_cpu, int sd_flag) 4570 int this_cpu, int sd_flag)
4567 { 4571 {
4568 struct sched_group *idlest = NULL, *group = sd->groups; 4572 struct sched_group *idlest = NULL, *group = sd->groups;
4569 unsigned long min_load = ULONG_MAX, this_load = 0; 4573 unsigned long min_load = ULONG_MAX, this_load = 0;
4570 int load_idx = sd->forkexec_idx; 4574 int load_idx = sd->forkexec_idx;
4571 int imbalance = 100 + (sd->imbalance_pct-100)/2; 4575 int imbalance = 100 + (sd->imbalance_pct-100)/2;
4572 4576
4573 if (sd_flag & SD_BALANCE_WAKE) 4577 if (sd_flag & SD_BALANCE_WAKE)
4574 load_idx = sd->wake_idx; 4578 load_idx = sd->wake_idx;
4575 4579
4576 do { 4580 do {
4577 unsigned long load, avg_load; 4581 unsigned long load, avg_load;
4578 int local_group; 4582 int local_group;
4579 int i; 4583 int i;
4580 4584
4581 /* Skip over this group if it has no CPUs allowed */ 4585 /* Skip over this group if it has no CPUs allowed */
4582 if (!cpumask_intersects(sched_group_cpus(group), 4586 if (!cpumask_intersects(sched_group_cpus(group),
4583 tsk_cpus_allowed(p))) 4587 tsk_cpus_allowed(p)))
4584 continue; 4588 continue;
4585 4589
4586 local_group = cpumask_test_cpu(this_cpu, 4590 local_group = cpumask_test_cpu(this_cpu,
4587 sched_group_cpus(group)); 4591 sched_group_cpus(group));
4588 4592
4589 /* Tally up the load of all CPUs in the group */ 4593 /* Tally up the load of all CPUs in the group */
4590 avg_load = 0; 4594 avg_load = 0;
4591 4595
4592 for_each_cpu(i, sched_group_cpus(group)) { 4596 for_each_cpu(i, sched_group_cpus(group)) {
4593 /* Bias balancing toward cpus of our domain */ 4597 /* Bias balancing toward cpus of our domain */
4594 if (local_group) 4598 if (local_group)
4595 load = source_load(i, load_idx); 4599 load = source_load(i, load_idx);
4596 else 4600 else
4597 load = target_load(i, load_idx); 4601 load = target_load(i, load_idx);
4598 4602
4599 avg_load += load; 4603 avg_load += load;
4600 } 4604 }
4601 4605
4602 /* Adjust by relative CPU capacity of the group */ 4606 /* Adjust by relative CPU capacity of the group */
4603 avg_load = (avg_load * SCHED_CAPACITY_SCALE) / group->sgc->capacity; 4607 avg_load = (avg_load * SCHED_CAPACITY_SCALE) / group->sgc->capacity;
4604 4608
4605 if (local_group) { 4609 if (local_group) {
4606 this_load = avg_load; 4610 this_load = avg_load;
4607 } else if (avg_load < min_load) { 4611 } else if (avg_load < min_load) {
4608 min_load = avg_load; 4612 min_load = avg_load;
4609 idlest = group; 4613 idlest = group;
4610 } 4614 }
4611 } while (group = group->next, group != sd->groups); 4615 } while (group = group->next, group != sd->groups);
4612 4616
4613 if (!idlest || 100*this_load < imbalance*min_load) 4617 if (!idlest || 100*this_load < imbalance*min_load)
4614 return NULL; 4618 return NULL;
4615 return idlest; 4619 return idlest;
4616 } 4620 }
4617 4621
4618 /* 4622 /*
4619 * find_idlest_cpu - find the idlest cpu among the cpus in group. 4623 * find_idlest_cpu - find the idlest cpu among the cpus in group.
4620 */ 4624 */
4621 static int 4625 static int
4622 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu) 4626 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
4623 { 4627 {
4624 unsigned long load, min_load = ULONG_MAX; 4628 unsigned long load, min_load = ULONG_MAX;
4625 unsigned int min_exit_latency = UINT_MAX; 4629 unsigned int min_exit_latency = UINT_MAX;
4626 u64 latest_idle_timestamp = 0; 4630 u64 latest_idle_timestamp = 0;
4627 int least_loaded_cpu = this_cpu; 4631 int least_loaded_cpu = this_cpu;
4628 int shallowest_idle_cpu = -1; 4632 int shallowest_idle_cpu = -1;
4629 int i; 4633 int i;
4630 4634
4631 /* Traverse only the allowed CPUs */ 4635 /* Traverse only the allowed CPUs */
4632 for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) { 4636 for_each_cpu_and(i, sched_group_cpus(group), tsk_cpus_allowed(p)) {
4633 if (idle_cpu(i)) { 4637 if (idle_cpu(i)) {
4634 struct rq *rq = cpu_rq(i); 4638 struct rq *rq = cpu_rq(i);
4635 struct cpuidle_state *idle = idle_get_state(rq); 4639 struct cpuidle_state *idle = idle_get_state(rq);
4636 if (idle && idle->exit_latency < min_exit_latency) { 4640 if (idle && idle->exit_latency < min_exit_latency) {
4637 /* 4641 /*
4638 * We give priority to a CPU whose idle state 4642 * We give priority to a CPU whose idle state
4639 * has the smallest exit latency irrespective 4643 * has the smallest exit latency irrespective
4640 * of any idle timestamp. 4644 * of any idle timestamp.
4641 */ 4645 */
4642 min_exit_latency = idle->exit_latency; 4646 min_exit_latency = idle->exit_latency;
4643 latest_idle_timestamp = rq->idle_stamp; 4647 latest_idle_timestamp = rq->idle_stamp;
4644 shallowest_idle_cpu = i; 4648 shallowest_idle_cpu = i;
4645 } else if ((!idle || idle->exit_latency == min_exit_latency) && 4649 } else if ((!idle || idle->exit_latency == min_exit_latency) &&
4646 rq->idle_stamp > latest_idle_timestamp) { 4650 rq->idle_stamp > latest_idle_timestamp) {
4647 /* 4651 /*
4648 * If equal or no active idle state, then 4652 * If equal or no active idle state, then
4649 * the most recently idled CPU might have 4653 * the most recently idled CPU might have
4650 * a warmer cache. 4654 * a warmer cache.
4651 */ 4655 */
4652 latest_idle_timestamp = rq->idle_stamp; 4656 latest_idle_timestamp = rq->idle_stamp;
4653 shallowest_idle_cpu = i; 4657 shallowest_idle_cpu = i;
4654 } 4658 }
4655 } else if (shallowest_idle_cpu == -1) { 4659 } else if (shallowest_idle_cpu == -1) {
4656 load = weighted_cpuload(i); 4660 load = weighted_cpuload(i);
4657 if (load < min_load || (load == min_load && i == this_cpu)) { 4661 if (load < min_load || (load == min_load && i == this_cpu)) {
4658 min_load = load; 4662 min_load = load;
4659 least_loaded_cpu = i; 4663 least_loaded_cpu = i;
4660 } 4664 }
4661 } 4665 }
4662 } 4666 }
4663 4667
4664 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu; 4668 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu;
4665 } 4669 }
4666 4670
4667 /* 4671 /*
4668 * Try and locate an idle CPU in the sched_domain. 4672 * Try and locate an idle CPU in the sched_domain.
4669 */ 4673 */
4670 static int select_idle_sibling(struct task_struct *p, int target) 4674 static int select_idle_sibling(struct task_struct *p, int target)
4671 { 4675 {
4672 struct sched_domain *sd; 4676 struct sched_domain *sd;
4673 struct sched_group *sg; 4677 struct sched_group *sg;
4674 int i = task_cpu(p); 4678 int i = task_cpu(p);
4675 4679
4676 if (idle_cpu(target)) 4680 if (idle_cpu(target))
4677 return target; 4681 return target;
4678 4682
4679 /* 4683 /*
4680 * If the prevous cpu is cache affine and idle, don't be stupid. 4684 * If the prevous cpu is cache affine and idle, don't be stupid.
4681 */ 4685 */
4682 if (i != target && cpus_share_cache(i, target) && idle_cpu(i)) 4686 if (i != target && cpus_share_cache(i, target) && idle_cpu(i))
4683 return i; 4687 return i;
4684 4688
4685 /* 4689 /*
4686 * Otherwise, iterate the domains and find an elegible idle cpu. 4690 * Otherwise, iterate the domains and find an elegible idle cpu.
4687 */ 4691 */
4688 sd = rcu_dereference(per_cpu(sd_llc, target)); 4692 sd = rcu_dereference(per_cpu(sd_llc, target));
4689 for_each_lower_domain(sd) { 4693 for_each_lower_domain(sd) {
4690 sg = sd->groups; 4694 sg = sd->groups;
4691 do { 4695 do {
4692 if (!cpumask_intersects(sched_group_cpus(sg), 4696 if (!cpumask_intersects(sched_group_cpus(sg),
4693 tsk_cpus_allowed(p))) 4697 tsk_cpus_allowed(p)))
4694 goto next; 4698 goto next;
4695 4699
4696 for_each_cpu(i, sched_group_cpus(sg)) { 4700 for_each_cpu(i, sched_group_cpus(sg)) {
4697 if (i == target || !idle_cpu(i)) 4701 if (i == target || !idle_cpu(i))
4698 goto next; 4702 goto next;
4699 } 4703 }
4700 4704
4701 target = cpumask_first_and(sched_group_cpus(sg), 4705 target = cpumask_first_and(sched_group_cpus(sg),
4702 tsk_cpus_allowed(p)); 4706 tsk_cpus_allowed(p));
4703 goto done; 4707 goto done;
4704 next: 4708 next:
4705 sg = sg->next; 4709 sg = sg->next;
4706 } while (sg != sd->groups); 4710 } while (sg != sd->groups);
4707 } 4711 }
4708 done: 4712 done:
4709 return target; 4713 return target;
4710 } 4714 }
4711 4715
4712 /* 4716 /*
4713 * select_task_rq_fair: Select target runqueue for the waking task in domains 4717 * select_task_rq_fair: Select target runqueue for the waking task in domains
4714 * that have the 'sd_flag' flag set. In practice, this is SD_BALANCE_WAKE, 4718 * that have the 'sd_flag' flag set. In practice, this is SD_BALANCE_WAKE,
4715 * SD_BALANCE_FORK, or SD_BALANCE_EXEC. 4719 * SD_BALANCE_FORK, or SD_BALANCE_EXEC.
4716 * 4720 *
4717 * Balances load by selecting the idlest cpu in the idlest group, or under 4721 * Balances load by selecting the idlest cpu in the idlest group, or under
4718 * certain conditions an idle sibling cpu if the domain has SD_WAKE_AFFINE set. 4722 * certain conditions an idle sibling cpu if the domain has SD_WAKE_AFFINE set.
4719 * 4723 *
4720 * Returns the target cpu number. 4724 * Returns the target cpu number.
4721 * 4725 *
4722 * preempt must be disabled. 4726 * preempt must be disabled.
4723 */ 4727 */
4724 static int 4728 static int
4725 select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags) 4729 select_task_rq_fair(struct task_struct *p, int prev_cpu, int sd_flag, int wake_flags)
4726 { 4730 {
4727 struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL; 4731 struct sched_domain *tmp, *affine_sd = NULL, *sd = NULL;
4728 int cpu = smp_processor_id(); 4732 int cpu = smp_processor_id();
4729 int new_cpu = cpu; 4733 int new_cpu = cpu;
4730 int want_affine = 0; 4734 int want_affine = 0;
4731 int sync = wake_flags & WF_SYNC; 4735 int sync = wake_flags & WF_SYNC;
4732 4736
4733 if (sd_flag & SD_BALANCE_WAKE) 4737 if (sd_flag & SD_BALANCE_WAKE)
4734 want_affine = cpumask_test_cpu(cpu, tsk_cpus_allowed(p)); 4738 want_affine = cpumask_test_cpu(cpu, tsk_cpus_allowed(p));
4735 4739
4736 rcu_read_lock(); 4740 rcu_read_lock();
4737 for_each_domain(cpu, tmp) { 4741 for_each_domain(cpu, tmp) {
4738 if (!(tmp->flags & SD_LOAD_BALANCE)) 4742 if (!(tmp->flags & SD_LOAD_BALANCE))
4739 continue; 4743 continue;
4740 4744
4741 /* 4745 /*
4742 * If both cpu and prev_cpu are part of this domain, 4746 * If both cpu and prev_cpu are part of this domain,
4743 * cpu is a valid SD_WAKE_AFFINE target. 4747 * cpu is a valid SD_WAKE_AFFINE target.
4744 */ 4748 */
4745 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) && 4749 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) &&
4746 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) { 4750 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) {
4747 affine_sd = tmp; 4751 affine_sd = tmp;
4748 break; 4752 break;
4749 } 4753 }
4750 4754
4751 if (tmp->flags & sd_flag) 4755 if (tmp->flags & sd_flag)
4752 sd = tmp; 4756 sd = tmp;
4753 } 4757 }
4754 4758
4755 if (affine_sd && cpu != prev_cpu && wake_affine(affine_sd, p, sync)) 4759 if (affine_sd && cpu != prev_cpu && wake_affine(affine_sd, p, sync))
4756 prev_cpu = cpu; 4760 prev_cpu = cpu;
4757 4761
4758 if (sd_flag & SD_BALANCE_WAKE) { 4762 if (sd_flag & SD_BALANCE_WAKE) {
4759 new_cpu = select_idle_sibling(p, prev_cpu); 4763 new_cpu = select_idle_sibling(p, prev_cpu);
4760 goto unlock; 4764 goto unlock;
4761 } 4765 }
4762 4766
4763 while (sd) { 4767 while (sd) {
4764 struct sched_group *group; 4768 struct sched_group *group;
4765 int weight; 4769 int weight;
4766 4770
4767 if (!(sd->flags & sd_flag)) { 4771 if (!(sd->flags & sd_flag)) {
4768 sd = sd->child; 4772 sd = sd->child;
4769 continue; 4773 continue;
4770 } 4774 }
4771 4775
4772 group = find_idlest_group(sd, p, cpu, sd_flag); 4776 group = find_idlest_group(sd, p, cpu, sd_flag);
4773 if (!group) { 4777 if (!group) {
4774 sd = sd->child; 4778 sd = sd->child;
4775 continue; 4779 continue;
4776 } 4780 }
4777 4781
4778 new_cpu = find_idlest_cpu(group, p, cpu); 4782 new_cpu = find_idlest_cpu(group, p, cpu);
4779 if (new_cpu == -1 || new_cpu == cpu) { 4783 if (new_cpu == -1 || new_cpu == cpu) {
4780 /* Now try balancing at a lower domain level of cpu */ 4784 /* Now try balancing at a lower domain level of cpu */
4781 sd = sd->child; 4785 sd = sd->child;
4782 continue; 4786 continue;
4783 } 4787 }
4784 4788
4785 /* Now try balancing at a lower domain level of new_cpu */ 4789 /* Now try balancing at a lower domain level of new_cpu */
4786 cpu = new_cpu; 4790 cpu = new_cpu;
4787 weight = sd->span_weight; 4791 weight = sd->span_weight;
4788 sd = NULL; 4792 sd = NULL;
4789 for_each_domain(cpu, tmp) { 4793 for_each_domain(cpu, tmp) {
4790 if (weight <= tmp->span_weight) 4794 if (weight <= tmp->span_weight)
4791 break; 4795 break;
4792 if (tmp->flags & sd_flag) 4796 if (tmp->flags & sd_flag)
4793 sd = tmp; 4797 sd = tmp;
4794 } 4798 }
4795 /* while loop will break here if sd == NULL */ 4799 /* while loop will break here if sd == NULL */
4796 } 4800 }
4797 unlock: 4801 unlock:
4798 rcu_read_unlock(); 4802 rcu_read_unlock();
4799 4803
4800 return new_cpu; 4804 return new_cpu;
4801 } 4805 }
4802 4806
4803 /* 4807 /*
4804 * Called immediately before a task is migrated to a new cpu; task_cpu(p) and 4808 * Called immediately before a task is migrated to a new cpu; task_cpu(p) and
4805 * cfs_rq_of(p) references at time of call are still valid and identify the 4809 * cfs_rq_of(p) references at time of call are still valid and identify the
4806 * previous cpu. However, the caller only guarantees p->pi_lock is held; no 4810 * previous cpu. However, the caller only guarantees p->pi_lock is held; no
4807 * other assumptions, including the state of rq->lock, should be made. 4811 * other assumptions, including the state of rq->lock, should be made.
4808 */ 4812 */
4809 static void 4813 static void
4810 migrate_task_rq_fair(struct task_struct *p, int next_cpu) 4814 migrate_task_rq_fair(struct task_struct *p, int next_cpu)
4811 { 4815 {
4812 struct sched_entity *se = &p->se; 4816 struct sched_entity *se = &p->se;
4813 struct cfs_rq *cfs_rq = cfs_rq_of(se); 4817 struct cfs_rq *cfs_rq = cfs_rq_of(se);
4814 4818
4815 /* 4819 /*
4816 * Load tracking: accumulate removed load so that it can be processed 4820 * Load tracking: accumulate removed load so that it can be processed
4817 * when we next update owning cfs_rq under rq->lock. Tasks contribute 4821 * when we next update owning cfs_rq under rq->lock. Tasks contribute
4818 * to blocked load iff they have a positive decay-count. It can never 4822 * to blocked load iff they have a positive decay-count. It can never
4819 * be negative here since on-rq tasks have decay-count == 0. 4823 * be negative here since on-rq tasks have decay-count == 0.
4820 */ 4824 */
4821 if (se->avg.decay_count) { 4825 if (se->avg.decay_count) {
4822 se->avg.decay_count = -__synchronize_entity_decay(se); 4826 se->avg.decay_count = -__synchronize_entity_decay(se);
4823 atomic_long_add(se->avg.load_avg_contrib, 4827 atomic_long_add(se->avg.load_avg_contrib,
4824 &cfs_rq->removed_load); 4828 &cfs_rq->removed_load);
4825 } 4829 }
4826 4830
4827 /* We have migrated, no longer consider this task hot */ 4831 /* We have migrated, no longer consider this task hot */
4828 se->exec_start = 0; 4832 se->exec_start = 0;
4829 } 4833 }
4830 #endif /* CONFIG_SMP */ 4834 #endif /* CONFIG_SMP */
4831 4835
4832 static unsigned long 4836 static unsigned long
4833 wakeup_gran(struct sched_entity *curr, struct sched_entity *se) 4837 wakeup_gran(struct sched_entity *curr, struct sched_entity *se)
4834 { 4838 {
4835 unsigned long gran = sysctl_sched_wakeup_granularity; 4839 unsigned long gran = sysctl_sched_wakeup_granularity;
4836 4840
4837 /* 4841 /*
4838 * Since its curr running now, convert the gran from real-time 4842 * Since its curr running now, convert the gran from real-time
4839 * to virtual-time in his units. 4843 * to virtual-time in his units.
4840 * 4844 *
4841 * By using 'se' instead of 'curr' we penalize light tasks, so 4845 * By using 'se' instead of 'curr' we penalize light tasks, so
4842 * they get preempted easier. That is, if 'se' < 'curr' then 4846 * they get preempted easier. That is, if 'se' < 'curr' then
4843 * the resulting gran will be larger, therefore penalizing the 4847 * the resulting gran will be larger, therefore penalizing the
4844 * lighter, if otoh 'se' > 'curr' then the resulting gran will 4848 * lighter, if otoh 'se' > 'curr' then the resulting gran will
4845 * be smaller, again penalizing the lighter task. 4849 * be smaller, again penalizing the lighter task.
4846 * 4850 *
4847 * This is especially important for buddies when the leftmost 4851 * This is especially important for buddies when the leftmost
4848 * task is higher priority than the buddy. 4852 * task is higher priority than the buddy.
4849 */ 4853 */
4850 return calc_delta_fair(gran, se); 4854 return calc_delta_fair(gran, se);
4851 } 4855 }
4852 4856
4853 /* 4857 /*
4854 * Should 'se' preempt 'curr'. 4858 * Should 'se' preempt 'curr'.
4855 * 4859 *
4856 * |s1 4860 * |s1
4857 * |s2 4861 * |s2
4858 * |s3 4862 * |s3
4859 * g 4863 * g
4860 * |<--->|c 4864 * |<--->|c
4861 * 4865 *
4862 * w(c, s1) = -1 4866 * w(c, s1) = -1
4863 * w(c, s2) = 0 4867 * w(c, s2) = 0
4864 * w(c, s3) = 1 4868 * w(c, s3) = 1
4865 * 4869 *
4866 */ 4870 */
4867 static int 4871 static int
4868 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se) 4872 wakeup_preempt_entity(struct sched_entity *curr, struct sched_entity *se)
4869 { 4873 {
4870 s64 gran, vdiff = curr->vruntime - se->vruntime; 4874 s64 gran, vdiff = curr->vruntime - se->vruntime;
4871 4875
4872 if (vdiff <= 0) 4876 if (vdiff <= 0)
4873 return -1; 4877 return -1;
4874 4878
4875 gran = wakeup_gran(curr, se); 4879 gran = wakeup_gran(curr, se);
4876 if (vdiff > gran) 4880 if (vdiff > gran)
4877 return 1; 4881 return 1;
4878 4882
4879 return 0; 4883 return 0;
4880 } 4884 }
4881 4885
4882 static void set_last_buddy(struct sched_entity *se) 4886 static void set_last_buddy(struct sched_entity *se)
4883 { 4887 {
4884 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE)) 4888 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
4885 return; 4889 return;
4886 4890
4887 for_each_sched_entity(se) 4891 for_each_sched_entity(se)
4888 cfs_rq_of(se)->last = se; 4892 cfs_rq_of(se)->last = se;
4889 } 4893 }
4890 4894
4891 static void set_next_buddy(struct sched_entity *se) 4895 static void set_next_buddy(struct sched_entity *se)
4892 { 4896 {
4893 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE)) 4897 if (entity_is_task(se) && unlikely(task_of(se)->policy == SCHED_IDLE))
4894 return; 4898 return;
4895 4899
4896 for_each_sched_entity(se) 4900 for_each_sched_entity(se)
4897 cfs_rq_of(se)->next = se; 4901 cfs_rq_of(se)->next = se;
4898 } 4902 }
4899 4903
4900 static void set_skip_buddy(struct sched_entity *se) 4904 static void set_skip_buddy(struct sched_entity *se)
4901 { 4905 {
4902 for_each_sched_entity(se) 4906 for_each_sched_entity(se)
4903 cfs_rq_of(se)->skip = se; 4907 cfs_rq_of(se)->skip = se;
4904 } 4908 }
4905 4909
4906 /* 4910 /*
4907 * Preempt the current task with a newly woken task if needed: 4911 * Preempt the current task with a newly woken task if needed:
4908 */ 4912 */
4909 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags) 4913 static void check_preempt_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
4910 { 4914 {
4911 struct task_struct *curr = rq->curr; 4915 struct task_struct *curr = rq->curr;
4912 struct sched_entity *se = &curr->se, *pse = &p->se; 4916 struct sched_entity *se = &curr->se, *pse = &p->se;
4913 struct cfs_rq *cfs_rq = task_cfs_rq(curr); 4917 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
4914 int scale = cfs_rq->nr_running >= sched_nr_latency; 4918 int scale = cfs_rq->nr_running >= sched_nr_latency;
4915 int next_buddy_marked = 0; 4919 int next_buddy_marked = 0;
4916 4920
4917 if (unlikely(se == pse)) 4921 if (unlikely(se == pse))
4918 return; 4922 return;
4919 4923
4920 /* 4924 /*
4921 * This is possible from callers such as attach_tasks(), in which we 4925 * This is possible from callers such as attach_tasks(), in which we
4922 * unconditionally check_prempt_curr() after an enqueue (which may have 4926 * unconditionally check_prempt_curr() after an enqueue (which may have
4923 * lead to a throttle). This both saves work and prevents false 4927 * lead to a throttle). This both saves work and prevents false
4924 * next-buddy nomination below. 4928 * next-buddy nomination below.
4925 */ 4929 */
4926 if (unlikely(throttled_hierarchy(cfs_rq_of(pse)))) 4930 if (unlikely(throttled_hierarchy(cfs_rq_of(pse))))
4927 return; 4931 return;
4928 4932
4929 if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) { 4933 if (sched_feat(NEXT_BUDDY) && scale && !(wake_flags & WF_FORK)) {
4930 set_next_buddy(pse); 4934 set_next_buddy(pse);
4931 next_buddy_marked = 1; 4935 next_buddy_marked = 1;
4932 } 4936 }
4933 4937
4934 /* 4938 /*
4935 * We can come here with TIF_NEED_RESCHED already set from new task 4939 * We can come here with TIF_NEED_RESCHED already set from new task
4936 * wake up path. 4940 * wake up path.
4937 * 4941 *
4938 * Note: this also catches the edge-case of curr being in a throttled 4942 * Note: this also catches the edge-case of curr being in a throttled
4939 * group (e.g. via set_curr_task), since update_curr() (in the 4943 * group (e.g. via set_curr_task), since update_curr() (in the
4940 * enqueue of curr) will have resulted in resched being set. This 4944 * enqueue of curr) will have resulted in resched being set. This
4941 * prevents us from potentially nominating it as a false LAST_BUDDY 4945 * prevents us from potentially nominating it as a false LAST_BUDDY
4942 * below. 4946 * below.
4943 */ 4947 */
4944 if (test_tsk_need_resched(curr)) 4948 if (test_tsk_need_resched(curr))
4945 return; 4949 return;
4946 4950
4947 /* Idle tasks are by definition preempted by non-idle tasks. */ 4951 /* Idle tasks are by definition preempted by non-idle tasks. */
4948 if (unlikely(curr->policy == SCHED_IDLE) && 4952 if (unlikely(curr->policy == SCHED_IDLE) &&
4949 likely(p->policy != SCHED_IDLE)) 4953 likely(p->policy != SCHED_IDLE))
4950 goto preempt; 4954 goto preempt;
4951 4955
4952 /* 4956 /*
4953 * Batch and idle tasks do not preempt non-idle tasks (their preemption 4957 * Batch and idle tasks do not preempt non-idle tasks (their preemption
4954 * is driven by the tick): 4958 * is driven by the tick):
4955 */ 4959 */
4956 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION)) 4960 if (unlikely(p->policy != SCHED_NORMAL) || !sched_feat(WAKEUP_PREEMPTION))
4957 return; 4961 return;
4958 4962
4959 find_matching_se(&se, &pse); 4963 find_matching_se(&se, &pse);
4960 update_curr(cfs_rq_of(se)); 4964 update_curr(cfs_rq_of(se));
4961 BUG_ON(!pse); 4965 BUG_ON(!pse);
4962 if (wakeup_preempt_entity(se, pse) == 1) { 4966 if (wakeup_preempt_entity(se, pse) == 1) {
4963 /* 4967 /*
4964 * Bias pick_next to pick the sched entity that is 4968 * Bias pick_next to pick the sched entity that is
4965 * triggering this preemption. 4969 * triggering this preemption.
4966 */ 4970 */
4967 if (!next_buddy_marked) 4971 if (!next_buddy_marked)
4968 set_next_buddy(pse); 4972 set_next_buddy(pse);
4969 goto preempt; 4973 goto preempt;
4970 } 4974 }
4971 4975
4972 return; 4976 return;
4973 4977
4974 preempt: 4978 preempt:
4975 resched_curr(rq); 4979 resched_curr(rq);
4976 /* 4980 /*
4977 * Only set the backward buddy when the current task is still 4981 * Only set the backward buddy when the current task is still
4978 * on the rq. This can happen when a wakeup gets interleaved 4982 * on the rq. This can happen when a wakeup gets interleaved
4979 * with schedule on the ->pre_schedule() or idle_balance() 4983 * with schedule on the ->pre_schedule() or idle_balance()
4980 * point, either of which can * drop the rq lock. 4984 * point, either of which can * drop the rq lock.
4981 * 4985 *
4982 * Also, during early boot the idle thread is in the fair class, 4986 * Also, during early boot the idle thread is in the fair class,
4983 * for obvious reasons its a bad idea to schedule back to it. 4987 * for obvious reasons its a bad idea to schedule back to it.
4984 */ 4988 */
4985 if (unlikely(!se->on_rq || curr == rq->idle)) 4989 if (unlikely(!se->on_rq || curr == rq->idle))
4986 return; 4990 return;
4987 4991
4988 if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se)) 4992 if (sched_feat(LAST_BUDDY) && scale && entity_is_task(se))
4989 set_last_buddy(se); 4993 set_last_buddy(se);
4990 } 4994 }
4991 4995
4992 static struct task_struct * 4996 static struct task_struct *
4993 pick_next_task_fair(struct rq *rq, struct task_struct *prev) 4997 pick_next_task_fair(struct rq *rq, struct task_struct *prev)
4994 { 4998 {
4995 struct cfs_rq *cfs_rq = &rq->cfs; 4999 struct cfs_rq *cfs_rq = &rq->cfs;
4996 struct sched_entity *se; 5000 struct sched_entity *se;
4997 struct task_struct *p; 5001 struct task_struct *p;
4998 int new_tasks; 5002 int new_tasks;
4999 5003
5000 again: 5004 again:
5001 #ifdef CONFIG_FAIR_GROUP_SCHED 5005 #ifdef CONFIG_FAIR_GROUP_SCHED
5002 if (!cfs_rq->nr_running) 5006 if (!cfs_rq->nr_running)
5003 goto idle; 5007 goto idle;
5004 5008
5005 if (prev->sched_class != &fair_sched_class) 5009 if (prev->sched_class != &fair_sched_class)
5006 goto simple; 5010 goto simple;
5007 5011
5008 /* 5012 /*
5009 * Because of the set_next_buddy() in dequeue_task_fair() it is rather 5013 * Because of the set_next_buddy() in dequeue_task_fair() it is rather
5010 * likely that a next task is from the same cgroup as the current. 5014 * likely that a next task is from the same cgroup as the current.
5011 * 5015 *
5012 * Therefore attempt to avoid putting and setting the entire cgroup 5016 * Therefore attempt to avoid putting and setting the entire cgroup
5013 * hierarchy, only change the part that actually changes. 5017 * hierarchy, only change the part that actually changes.
5014 */ 5018 */
5015 5019
5016 do { 5020 do {
5017 struct sched_entity *curr = cfs_rq->curr; 5021 struct sched_entity *curr = cfs_rq->curr;
5018 5022
5019 /* 5023 /*
5020 * Since we got here without doing put_prev_entity() we also 5024 * Since we got here without doing put_prev_entity() we also
5021 * have to consider cfs_rq->curr. If it is still a runnable 5025 * have to consider cfs_rq->curr. If it is still a runnable
5022 * entity, update_curr() will update its vruntime, otherwise 5026 * entity, update_curr() will update its vruntime, otherwise
5023 * forget we've ever seen it. 5027 * forget we've ever seen it.
5024 */ 5028 */
5025 if (curr && curr->on_rq) 5029 if (curr && curr->on_rq)
5026 update_curr(cfs_rq); 5030 update_curr(cfs_rq);
5027 else 5031 else
5028 curr = NULL; 5032 curr = NULL;
5029 5033
5030 /* 5034 /*
5031 * This call to check_cfs_rq_runtime() will do the throttle and 5035 * This call to check_cfs_rq_runtime() will do the throttle and
5032 * dequeue its entity in the parent(s). Therefore the 'simple' 5036 * dequeue its entity in the parent(s). Therefore the 'simple'
5033 * nr_running test will indeed be correct. 5037 * nr_running test will indeed be correct.
5034 */ 5038 */
5035 if (unlikely(check_cfs_rq_runtime(cfs_rq))) 5039 if (unlikely(check_cfs_rq_runtime(cfs_rq)))
5036 goto simple; 5040 goto simple;
5037 5041
5038 se = pick_next_entity(cfs_rq, curr); 5042 se = pick_next_entity(cfs_rq, curr);
5039 cfs_rq = group_cfs_rq(se); 5043 cfs_rq = group_cfs_rq(se);
5040 } while (cfs_rq); 5044 } while (cfs_rq);
5041 5045
5042 p = task_of(se); 5046 p = task_of(se);
5043 5047
5044 /* 5048 /*
5045 * Since we haven't yet done put_prev_entity and if the selected task 5049 * Since we haven't yet done put_prev_entity and if the selected task
5046 * is a different task than we started out with, try and touch the 5050 * is a different task than we started out with, try and touch the
5047 * least amount of cfs_rqs. 5051 * least amount of cfs_rqs.
5048 */ 5052 */
5049 if (prev != p) { 5053 if (prev != p) {
5050 struct sched_entity *pse = &prev->se; 5054 struct sched_entity *pse = &prev->se;
5051 5055
5052 while (!(cfs_rq = is_same_group(se, pse))) { 5056 while (!(cfs_rq = is_same_group(se, pse))) {
5053 int se_depth = se->depth; 5057 int se_depth = se->depth;
5054 int pse_depth = pse->depth; 5058 int pse_depth = pse->depth;
5055 5059
5056 if (se_depth <= pse_depth) { 5060 if (se_depth <= pse_depth) {
5057 put_prev_entity(cfs_rq_of(pse), pse); 5061 put_prev_entity(cfs_rq_of(pse), pse);
5058 pse = parent_entity(pse); 5062 pse = parent_entity(pse);
5059 } 5063 }
5060 if (se_depth >= pse_depth) { 5064 if (se_depth >= pse_depth) {
5061 set_next_entity(cfs_rq_of(se), se); 5065 set_next_entity(cfs_rq_of(se), se);
5062 se = parent_entity(se); 5066 se = parent_entity(se);
5063 } 5067 }
5064 } 5068 }
5065 5069
5066 put_prev_entity(cfs_rq, pse); 5070 put_prev_entity(cfs_rq, pse);
5067 set_next_entity(cfs_rq, se); 5071 set_next_entity(cfs_rq, se);
5068 } 5072 }
5069 5073
5070 if (hrtick_enabled(rq)) 5074 if (hrtick_enabled(rq))
5071 hrtick_start_fair(rq, p); 5075 hrtick_start_fair(rq, p);
5072 5076
5073 return p; 5077 return p;
5074 simple: 5078 simple:
5075 cfs_rq = &rq->cfs; 5079 cfs_rq = &rq->cfs;
5076 #endif 5080 #endif
5077 5081
5078 if (!cfs_rq->nr_running) 5082 if (!cfs_rq->nr_running)
5079 goto idle; 5083 goto idle;
5080 5084
5081 put_prev_task(rq, prev); 5085 put_prev_task(rq, prev);
5082 5086
5083 do { 5087 do {
5084 se = pick_next_entity(cfs_rq, NULL); 5088 se = pick_next_entity(cfs_rq, NULL);
5085 set_next_entity(cfs_rq, se); 5089 set_next_entity(cfs_rq, se);
5086 cfs_rq = group_cfs_rq(se); 5090 cfs_rq = group_cfs_rq(se);
5087 } while (cfs_rq); 5091 } while (cfs_rq);
5088 5092
5089 p = task_of(se); 5093 p = task_of(se);
5090 5094
5091 if (hrtick_enabled(rq)) 5095 if (hrtick_enabled(rq))
5092 hrtick_start_fair(rq, p); 5096 hrtick_start_fair(rq, p);
5093 5097
5094 return p; 5098 return p;
5095 5099
5096 idle: 5100 idle:
5097 new_tasks = idle_balance(rq); 5101 new_tasks = idle_balance(rq);
5098 /* 5102 /*
5099 * Because idle_balance() releases (and re-acquires) rq->lock, it is 5103 * Because idle_balance() releases (and re-acquires) rq->lock, it is
5100 * possible for any higher priority task to appear. In that case we 5104 * possible for any higher priority task to appear. In that case we
5101 * must re-start the pick_next_entity() loop. 5105 * must re-start the pick_next_entity() loop.
5102 */ 5106 */
5103 if (new_tasks < 0) 5107 if (new_tasks < 0)
5104 return RETRY_TASK; 5108 return RETRY_TASK;
5105 5109
5106 if (new_tasks > 0) 5110 if (new_tasks > 0)
5107 goto again; 5111 goto again;
5108 5112
5109 return NULL; 5113 return NULL;
5110 } 5114 }
5111 5115
5112 /* 5116 /*
5113 * Account for a descheduled task: 5117 * Account for a descheduled task:
5114 */ 5118 */
5115 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev) 5119 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev)
5116 { 5120 {
5117 struct sched_entity *se = &prev->se; 5121 struct sched_entity *se = &prev->se;
5118 struct cfs_rq *cfs_rq; 5122 struct cfs_rq *cfs_rq;
5119 5123
5120 for_each_sched_entity(se) { 5124 for_each_sched_entity(se) {
5121 cfs_rq = cfs_rq_of(se); 5125 cfs_rq = cfs_rq_of(se);
5122 put_prev_entity(cfs_rq, se); 5126 put_prev_entity(cfs_rq, se);
5123 } 5127 }
5124 } 5128 }
5125 5129
5126 /* 5130 /*
5127 * sched_yield() is very simple 5131 * sched_yield() is very simple
5128 * 5132 *
5129 * The magic of dealing with the ->skip buddy is in pick_next_entity. 5133 * The magic of dealing with the ->skip buddy is in pick_next_entity.
5130 */ 5134 */
5131 static void yield_task_fair(struct rq *rq) 5135 static void yield_task_fair(struct rq *rq)
5132 { 5136 {
5133 struct task_struct *curr = rq->curr; 5137 struct task_struct *curr = rq->curr;
5134 struct cfs_rq *cfs_rq = task_cfs_rq(curr); 5138 struct cfs_rq *cfs_rq = task_cfs_rq(curr);
5135 struct sched_entity *se = &curr->se; 5139 struct sched_entity *se = &curr->se;
5136 5140
5137 /* 5141 /*
5138 * Are we the only task in the tree? 5142 * Are we the only task in the tree?
5139 */ 5143 */
5140 if (unlikely(rq->nr_running == 1)) 5144 if (unlikely(rq->nr_running == 1))
5141 return; 5145 return;
5142 5146
5143 clear_buddies(cfs_rq, se); 5147 clear_buddies(cfs_rq, se);
5144 5148
5145 if (curr->policy != SCHED_BATCH) { 5149 if (curr->policy != SCHED_BATCH) {
5146 update_rq_clock(rq); 5150 update_rq_clock(rq);
5147 /* 5151 /*
5148 * Update run-time statistics of the 'current'. 5152 * Update run-time statistics of the 'current'.
5149 */ 5153 */
5150 update_curr(cfs_rq); 5154 update_curr(cfs_rq);
5151 /* 5155 /*
5152 * Tell update_rq_clock() that we've just updated, 5156 * Tell update_rq_clock() that we've just updated,
5153 * so we don't do microscopic update in schedule() 5157 * so we don't do microscopic update in schedule()
5154 * and double the fastpath cost. 5158 * and double the fastpath cost.
5155 */ 5159 */
5156 rq->skip_clock_update = 1; 5160 rq->skip_clock_update = 1;
5157 } 5161 }
5158 5162
5159 set_skip_buddy(se); 5163 set_skip_buddy(se);
5160 } 5164 }
5161 5165
5162 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt) 5166 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p, bool preempt)
5163 { 5167 {
5164 struct sched_entity *se = &p->se; 5168 struct sched_entity *se = &p->se;
5165 5169
5166 /* throttled hierarchies are not runnable */ 5170 /* throttled hierarchies are not runnable */
5167 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se))) 5171 if (!se->on_rq || throttled_hierarchy(cfs_rq_of(se)))
5168 return false; 5172 return false;
5169 5173
5170 /* Tell the scheduler that we'd really like pse to run next. */ 5174 /* Tell the scheduler that we'd really like pse to run next. */
5171 set_next_buddy(se); 5175 set_next_buddy(se);
5172 5176
5173 yield_task_fair(rq); 5177 yield_task_fair(rq);
5174 5178
5175 return true; 5179 return true;
5176 } 5180 }
5177 5181
5178 #ifdef CONFIG_SMP 5182 #ifdef CONFIG_SMP
5179 /************************************************** 5183 /**************************************************
5180 * Fair scheduling class load-balancing methods. 5184 * Fair scheduling class load-balancing methods.
5181 * 5185 *
5182 * BASICS 5186 * BASICS
5183 * 5187 *
5184 * The purpose of load-balancing is to achieve the same basic fairness the 5188 * The purpose of load-balancing is to achieve the same basic fairness the
5185 * per-cpu scheduler provides, namely provide a proportional amount of compute 5189 * per-cpu scheduler provides, namely provide a proportional amount of compute
5186 * time to each task. This is expressed in the following equation: 5190 * time to each task. This is expressed in the following equation:
5187 * 5191 *
5188 * W_i,n/P_i == W_j,n/P_j for all i,j (1) 5192 * W_i,n/P_i == W_j,n/P_j for all i,j (1)
5189 * 5193 *
5190 * Where W_i,n is the n-th weight average for cpu i. The instantaneous weight 5194 * Where W_i,n is the n-th weight average for cpu i. The instantaneous weight
5191 * W_i,0 is defined as: 5195 * W_i,0 is defined as:
5192 * 5196 *
5193 * W_i,0 = \Sum_j w_i,j (2) 5197 * W_i,0 = \Sum_j w_i,j (2)
5194 * 5198 *
5195 * Where w_i,j is the weight of the j-th runnable task on cpu i. This weight 5199 * Where w_i,j is the weight of the j-th runnable task on cpu i. This weight
5196 * is derived from the nice value as per prio_to_weight[]. 5200 * is derived from the nice value as per prio_to_weight[].
5197 * 5201 *
5198 * The weight average is an exponential decay average of the instantaneous 5202 * The weight average is an exponential decay average of the instantaneous
5199 * weight: 5203 * weight:
5200 * 5204 *
5201 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3) 5205 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3)
5202 * 5206 *
5203 * C_i is the compute capacity of cpu i, typically it is the 5207 * C_i is the compute capacity of cpu i, typically it is the
5204 * fraction of 'recent' time available for SCHED_OTHER task execution. But it 5208 * fraction of 'recent' time available for SCHED_OTHER task execution. But it
5205 * can also include other factors [XXX]. 5209 * can also include other factors [XXX].
5206 * 5210 *
5207 * To achieve this balance we define a measure of imbalance which follows 5211 * To achieve this balance we define a measure of imbalance which follows
5208 * directly from (1): 5212 * directly from (1):
5209 * 5213 *
5210 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4) 5214 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4)
5211 * 5215 *
5212 * We them move tasks around to minimize the imbalance. In the continuous 5216 * We them move tasks around to minimize the imbalance. In the continuous
5213 * function space it is obvious this converges, in the discrete case we get 5217 * function space it is obvious this converges, in the discrete case we get
5214 * a few fun cases generally called infeasible weight scenarios. 5218 * a few fun cases generally called infeasible weight scenarios.
5215 * 5219 *
5216 * [XXX expand on: 5220 * [XXX expand on:
5217 * - infeasible weights; 5221 * - infeasible weights;
5218 * - local vs global optima in the discrete case. ] 5222 * - local vs global optima in the discrete case. ]
5219 * 5223 *
5220 * 5224 *
5221 * SCHED DOMAINS 5225 * SCHED DOMAINS
5222 * 5226 *
5223 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2) 5227 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2)
5224 * for all i,j solution, we create a tree of cpus that follows the hardware 5228 * for all i,j solution, we create a tree of cpus that follows the hardware
5225 * topology where each level pairs two lower groups (or better). This results 5229 * topology where each level pairs two lower groups (or better). This results
5226 * in O(log n) layers. Furthermore we reduce the number of cpus going up the 5230 * in O(log n) layers. Furthermore we reduce the number of cpus going up the
5227 * tree to only the first of the previous level and we decrease the frequency 5231 * tree to only the first of the previous level and we decrease the frequency
5228 * of load-balance at each level inv. proportional to the number of cpus in 5232 * of load-balance at each level inv. proportional to the number of cpus in
5229 * the groups. 5233 * the groups.
5230 * 5234 *
5231 * This yields: 5235 * This yields:
5232 * 5236 *
5233 * log_2 n 1 n 5237 * log_2 n 1 n
5234 * \Sum { --- * --- * 2^i } = O(n) (5) 5238 * \Sum { --- * --- * 2^i } = O(n) (5)
5235 * i = 0 2^i 2^i 5239 * i = 0 2^i 2^i
5236 * `- size of each group 5240 * `- size of each group
5237 * | | `- number of cpus doing load-balance 5241 * | | `- number of cpus doing load-balance
5238 * | `- freq 5242 * | `- freq
5239 * `- sum over all levels 5243 * `- sum over all levels
5240 * 5244 *
5241 * Coupled with a limit on how many tasks we can migrate every balance pass, 5245 * Coupled with a limit on how many tasks we can migrate every balance pass,
5242 * this makes (5) the runtime complexity of the balancer. 5246 * this makes (5) the runtime complexity of the balancer.
5243 * 5247 *
5244 * An important property here is that each CPU is still (indirectly) connected 5248 * An important property here is that each CPU is still (indirectly) connected
5245 * to every other cpu in at most O(log n) steps: 5249 * to every other cpu in at most O(log n) steps:
5246 * 5250 *
5247 * The adjacency matrix of the resulting graph is given by: 5251 * The adjacency matrix of the resulting graph is given by:
5248 * 5252 *
5249 * log_2 n 5253 * log_2 n
5250 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6) 5254 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6)
5251 * k = 0 5255 * k = 0
5252 * 5256 *
5253 * And you'll find that: 5257 * And you'll find that:
5254 * 5258 *
5255 * A^(log_2 n)_i,j != 0 for all i,j (7) 5259 * A^(log_2 n)_i,j != 0 for all i,j (7)
5256 * 5260 *
5257 * Showing there's indeed a path between every cpu in at most O(log n) steps. 5261 * Showing there's indeed a path between every cpu in at most O(log n) steps.
5258 * The task movement gives a factor of O(m), giving a convergence complexity 5262 * The task movement gives a factor of O(m), giving a convergence complexity
5259 * of: 5263 * of:
5260 * 5264 *
5261 * O(nm log n), n := nr_cpus, m := nr_tasks (8) 5265 * O(nm log n), n := nr_cpus, m := nr_tasks (8)
5262 * 5266 *
5263 * 5267 *
5264 * WORK CONSERVING 5268 * WORK CONSERVING
5265 * 5269 *
5266 * In order to avoid CPUs going idle while there's still work to do, new idle 5270 * In order to avoid CPUs going idle while there's still work to do, new idle
5267 * balancing is more aggressive and has the newly idle cpu iterate up the domain 5271 * balancing is more aggressive and has the newly idle cpu iterate up the domain
5268 * tree itself instead of relying on other CPUs to bring it work. 5272 * tree itself instead of relying on other CPUs to bring it work.
5269 * 5273 *
5270 * This adds some complexity to both (5) and (8) but it reduces the total idle 5274 * This adds some complexity to both (5) and (8) but it reduces the total idle
5271 * time. 5275 * time.
5272 * 5276 *
5273 * [XXX more?] 5277 * [XXX more?]
5274 * 5278 *
5275 * 5279 *
5276 * CGROUPS 5280 * CGROUPS
5277 * 5281 *
5278 * Cgroups make a horror show out of (2), instead of a simple sum we get: 5282 * Cgroups make a horror show out of (2), instead of a simple sum we get:
5279 * 5283 *
5280 * s_k,i 5284 * s_k,i
5281 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9) 5285 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9)
5282 * S_k 5286 * S_k
5283 * 5287 *
5284 * Where 5288 * Where
5285 * 5289 *
5286 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10) 5290 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10)
5287 * 5291 *
5288 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on cpu i. 5292 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on cpu i.
5289 * 5293 *
5290 * The big problem is S_k, its a global sum needed to compute a local (W_i) 5294 * The big problem is S_k, its a global sum needed to compute a local (W_i)
5291 * property. 5295 * property.
5292 * 5296 *
5293 * [XXX write more on how we solve this.. _after_ merging pjt's patches that 5297 * [XXX write more on how we solve this.. _after_ merging pjt's patches that
5294 * rewrite all of this once again.] 5298 * rewrite all of this once again.]
5295 */ 5299 */
5296 5300
5297 static unsigned long __read_mostly max_load_balance_interval = HZ/10; 5301 static unsigned long __read_mostly max_load_balance_interval = HZ/10;
5298 5302
5299 enum fbq_type { regular, remote, all }; 5303 enum fbq_type { regular, remote, all };
5300 5304
5301 #define LBF_ALL_PINNED 0x01 5305 #define LBF_ALL_PINNED 0x01
5302 #define LBF_NEED_BREAK 0x02 5306 #define LBF_NEED_BREAK 0x02
5303 #define LBF_DST_PINNED 0x04 5307 #define LBF_DST_PINNED 0x04
5304 #define LBF_SOME_PINNED 0x08 5308 #define LBF_SOME_PINNED 0x08
5305 5309
5306 struct lb_env { 5310 struct lb_env {
5307 struct sched_domain *sd; 5311 struct sched_domain *sd;
5308 5312
5309 struct rq *src_rq; 5313 struct rq *src_rq;
5310 int src_cpu; 5314 int src_cpu;
5311 5315
5312 int dst_cpu; 5316 int dst_cpu;
5313 struct rq *dst_rq; 5317 struct rq *dst_rq;
5314 5318
5315 struct cpumask *dst_grpmask; 5319 struct cpumask *dst_grpmask;
5316 int new_dst_cpu; 5320 int new_dst_cpu;
5317 enum cpu_idle_type idle; 5321 enum cpu_idle_type idle;
5318 long imbalance; 5322 long imbalance;
5319 /* The set of CPUs under consideration for load-balancing */ 5323 /* The set of CPUs under consideration for load-balancing */
5320 struct cpumask *cpus; 5324 struct cpumask *cpus;
5321 5325
5322 unsigned int flags; 5326 unsigned int flags;
5323 5327
5324 unsigned int loop; 5328 unsigned int loop;
5325 unsigned int loop_break; 5329 unsigned int loop_break;
5326 unsigned int loop_max; 5330 unsigned int loop_max;
5327 5331
5328 enum fbq_type fbq_type; 5332 enum fbq_type fbq_type;
5329 struct list_head tasks; 5333 struct list_head tasks;
5330 }; 5334 };
5331 5335
5332 /* 5336 /*
5333 * Is this task likely cache-hot: 5337 * Is this task likely cache-hot:
5334 */ 5338 */
5335 static int task_hot(struct task_struct *p, struct lb_env *env) 5339 static int task_hot(struct task_struct *p, struct lb_env *env)
5336 { 5340 {
5337 s64 delta; 5341 s64 delta;
5338 5342
5339 lockdep_assert_held(&env->src_rq->lock); 5343 lockdep_assert_held(&env->src_rq->lock);
5340 5344
5341 if (p->sched_class != &fair_sched_class) 5345 if (p->sched_class != &fair_sched_class)
5342 return 0; 5346 return 0;
5343 5347
5344 if (unlikely(p->policy == SCHED_IDLE)) 5348 if (unlikely(p->policy == SCHED_IDLE))
5345 return 0; 5349 return 0;
5346 5350
5347 /* 5351 /*
5348 * Buddy candidates are cache hot: 5352 * Buddy candidates are cache hot:
5349 */ 5353 */
5350 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running && 5354 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running &&
5351 (&p->se == cfs_rq_of(&p->se)->next || 5355 (&p->se == cfs_rq_of(&p->se)->next ||
5352 &p->se == cfs_rq_of(&p->se)->last)) 5356 &p->se == cfs_rq_of(&p->se)->last))
5353 return 1; 5357 return 1;
5354 5358
5355 if (sysctl_sched_migration_cost == -1) 5359 if (sysctl_sched_migration_cost == -1)
5356 return 1; 5360 return 1;
5357 if (sysctl_sched_migration_cost == 0) 5361 if (sysctl_sched_migration_cost == 0)
5358 return 0; 5362 return 0;
5359 5363
5360 delta = rq_clock_task(env->src_rq) - p->se.exec_start; 5364 delta = rq_clock_task(env->src_rq) - p->se.exec_start;
5361 5365
5362 return delta < (s64)sysctl_sched_migration_cost; 5366 return delta < (s64)sysctl_sched_migration_cost;
5363 } 5367 }
5364 5368
5365 #ifdef CONFIG_NUMA_BALANCING 5369 #ifdef CONFIG_NUMA_BALANCING
5366 /* Returns true if the destination node has incurred more faults */ 5370 /* Returns true if the destination node has incurred more faults */
5367 static bool migrate_improves_locality(struct task_struct *p, struct lb_env *env) 5371 static bool migrate_improves_locality(struct task_struct *p, struct lb_env *env)
5368 { 5372 {
5369 struct numa_group *numa_group = rcu_dereference(p->numa_group); 5373 struct numa_group *numa_group = rcu_dereference(p->numa_group);
5370 int src_nid, dst_nid; 5374 int src_nid, dst_nid;
5371 5375
5372 if (!sched_feat(NUMA_FAVOUR_HIGHER) || !p->numa_faults || 5376 if (!sched_feat(NUMA_FAVOUR_HIGHER) || !p->numa_faults ||
5373 !(env->sd->flags & SD_NUMA)) { 5377 !(env->sd->flags & SD_NUMA)) {
5374 return false; 5378 return false;
5375 } 5379 }
5376 5380
5377 src_nid = cpu_to_node(env->src_cpu); 5381 src_nid = cpu_to_node(env->src_cpu);
5378 dst_nid = cpu_to_node(env->dst_cpu); 5382 dst_nid = cpu_to_node(env->dst_cpu);
5379 5383
5380 if (src_nid == dst_nid) 5384 if (src_nid == dst_nid)
5381 return false; 5385 return false;
5382 5386
5383 if (numa_group) { 5387 if (numa_group) {
5384 /* Task is already in the group's interleave set. */ 5388 /* Task is already in the group's interleave set. */
5385 if (node_isset(src_nid, numa_group->active_nodes)) 5389 if (node_isset(src_nid, numa_group->active_nodes))
5386 return false; 5390 return false;
5387 5391
5388 /* Task is moving into the group's interleave set. */ 5392 /* Task is moving into the group's interleave set. */
5389 if (node_isset(dst_nid, numa_group->active_nodes)) 5393 if (node_isset(dst_nid, numa_group->active_nodes))
5390 return true; 5394 return true;
5391 5395
5392 return group_faults(p, dst_nid) > group_faults(p, src_nid); 5396 return group_faults(p, dst_nid) > group_faults(p, src_nid);
5393 } 5397 }
5394 5398
5395 /* Encourage migration to the preferred node. */ 5399 /* Encourage migration to the preferred node. */
5396 if (dst_nid == p->numa_preferred_nid) 5400 if (dst_nid == p->numa_preferred_nid)
5397 return true; 5401 return true;
5398 5402
5399 return task_faults(p, dst_nid) > task_faults(p, src_nid); 5403 return task_faults(p, dst_nid) > task_faults(p, src_nid);
5400 } 5404 }
5401 5405
5402 5406
5403 static bool migrate_degrades_locality(struct task_struct *p, struct lb_env *env) 5407 static bool migrate_degrades_locality(struct task_struct *p, struct lb_env *env)
5404 { 5408 {
5405 struct numa_group *numa_group = rcu_dereference(p->numa_group); 5409 struct numa_group *numa_group = rcu_dereference(p->numa_group);
5406 int src_nid, dst_nid; 5410 int src_nid, dst_nid;
5407 5411
5408 if (!sched_feat(NUMA) || !sched_feat(NUMA_RESIST_LOWER)) 5412 if (!sched_feat(NUMA) || !sched_feat(NUMA_RESIST_LOWER))
5409 return false; 5413 return false;
5410 5414
5411 if (!p->numa_faults || !(env->sd->flags & SD_NUMA)) 5415 if (!p->numa_faults || !(env->sd->flags & SD_NUMA))
5412 return false; 5416 return false;
5413 5417
5414 src_nid = cpu_to_node(env->src_cpu); 5418 src_nid = cpu_to_node(env->src_cpu);
5415 dst_nid = cpu_to_node(env->dst_cpu); 5419 dst_nid = cpu_to_node(env->dst_cpu);
5416 5420
5417 if (src_nid == dst_nid) 5421 if (src_nid == dst_nid)
5418 return false; 5422 return false;
5419 5423
5420 if (numa_group) { 5424 if (numa_group) {
5421 /* Task is moving within/into the group's interleave set. */ 5425 /* Task is moving within/into the group's interleave set. */
5422 if (node_isset(dst_nid, numa_group->active_nodes)) 5426 if (node_isset(dst_nid, numa_group->active_nodes))
5423 return false; 5427 return false;
5424 5428
5425 /* Task is moving out of the group's interleave set. */ 5429 /* Task is moving out of the group's interleave set. */
5426 if (node_isset(src_nid, numa_group->active_nodes)) 5430 if (node_isset(src_nid, numa_group->active_nodes))
5427 return true; 5431 return true;
5428 5432
5429 return group_faults(p, dst_nid) < group_faults(p, src_nid); 5433 return group_faults(p, dst_nid) < group_faults(p, src_nid);
5430 } 5434 }
5431 5435
5432 /* Migrating away from the preferred node is always bad. */ 5436 /* Migrating away from the preferred node is always bad. */
5433 if (src_nid == p->numa_preferred_nid) 5437 if (src_nid == p->numa_preferred_nid)
5434 return true; 5438 return true;
5435 5439
5436 return task_faults(p, dst_nid) < task_faults(p, src_nid); 5440 return task_faults(p, dst_nid) < task_faults(p, src_nid);
5437 } 5441 }
5438 5442
5439 #else 5443 #else
5440 static inline bool migrate_improves_locality(struct task_struct *p, 5444 static inline bool migrate_improves_locality(struct task_struct *p,
5441 struct lb_env *env) 5445 struct lb_env *env)
5442 { 5446 {
5443 return false; 5447 return false;
5444 } 5448 }
5445 5449
5446 static inline bool migrate_degrades_locality(struct task_struct *p, 5450 static inline bool migrate_degrades_locality(struct task_struct *p,
5447 struct lb_env *env) 5451 struct lb_env *env)
5448 { 5452 {
5449 return false; 5453 return false;
5450 } 5454 }
5451 #endif 5455 #endif
5452 5456
5453 /* 5457 /*
5454 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu? 5458 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
5455 */ 5459 */
5456 static 5460 static
5457 int can_migrate_task(struct task_struct *p, struct lb_env *env) 5461 int can_migrate_task(struct task_struct *p, struct lb_env *env)
5458 { 5462 {
5459 int tsk_cache_hot = 0; 5463 int tsk_cache_hot = 0;
5460 5464
5461 lockdep_assert_held(&env->src_rq->lock); 5465 lockdep_assert_held(&env->src_rq->lock);
5462 5466
5463 /* 5467 /*
5464 * We do not migrate tasks that are: 5468 * We do not migrate tasks that are:
5465 * 1) throttled_lb_pair, or 5469 * 1) throttled_lb_pair, or
5466 * 2) cannot be migrated to this CPU due to cpus_allowed, or 5470 * 2) cannot be migrated to this CPU due to cpus_allowed, or
5467 * 3) running (obviously), or 5471 * 3) running (obviously), or
5468 * 4) are cache-hot on their current CPU. 5472 * 4) are cache-hot on their current CPU.
5469 */ 5473 */
5470 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu)) 5474 if (throttled_lb_pair(task_group(p), env->src_cpu, env->dst_cpu))
5471 return 0; 5475 return 0;
5472 5476
5473 if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) { 5477 if (!cpumask_test_cpu(env->dst_cpu, tsk_cpus_allowed(p))) {
5474 int cpu; 5478 int cpu;
5475 5479
5476 schedstat_inc(p, se.statistics.nr_failed_migrations_affine); 5480 schedstat_inc(p, se.statistics.nr_failed_migrations_affine);
5477 5481
5478 env->flags |= LBF_SOME_PINNED; 5482 env->flags |= LBF_SOME_PINNED;
5479 5483
5480 /* 5484 /*
5481 * Remember if this task can be migrated to any other cpu in 5485 * Remember if this task can be migrated to any other cpu in
5482 * our sched_group. We may want to revisit it if we couldn't 5486 * our sched_group. We may want to revisit it if we couldn't
5483 * meet load balance goals by pulling other tasks on src_cpu. 5487 * meet load balance goals by pulling other tasks on src_cpu.
5484 * 5488 *
5485 * Also avoid computing new_dst_cpu if we have already computed 5489 * Also avoid computing new_dst_cpu if we have already computed
5486 * one in current iteration. 5490 * one in current iteration.
5487 */ 5491 */
5488 if (!env->dst_grpmask || (env->flags & LBF_DST_PINNED)) 5492 if (!env->dst_grpmask || (env->flags & LBF_DST_PINNED))
5489 return 0; 5493 return 0;
5490 5494
5491 /* Prevent to re-select dst_cpu via env's cpus */ 5495 /* Prevent to re-select dst_cpu via env's cpus */
5492 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) { 5496 for_each_cpu_and(cpu, env->dst_grpmask, env->cpus) {
5493 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) { 5497 if (cpumask_test_cpu(cpu, tsk_cpus_allowed(p))) {
5494 env->flags |= LBF_DST_PINNED; 5498 env->flags |= LBF_DST_PINNED;
5495 env->new_dst_cpu = cpu; 5499 env->new_dst_cpu = cpu;
5496 break; 5500 break;
5497 } 5501 }
5498 } 5502 }
5499 5503
5500 return 0; 5504 return 0;
5501 } 5505 }
5502 5506
5503 /* Record that we found atleast one task that could run on dst_cpu */ 5507 /* Record that we found atleast one task that could run on dst_cpu */
5504 env->flags &= ~LBF_ALL_PINNED; 5508 env->flags &= ~LBF_ALL_PINNED;
5505 5509
5506 if (task_running(env->src_rq, p)) { 5510 if (task_running(env->src_rq, p)) {
5507 schedstat_inc(p, se.statistics.nr_failed_migrations_running); 5511 schedstat_inc(p, se.statistics.nr_failed_migrations_running);
5508 return 0; 5512 return 0;
5509 } 5513 }
5510 5514
5511 /* 5515 /*
5512 * Aggressive migration if: 5516 * Aggressive migration if:
5513 * 1) destination numa is preferred 5517 * 1) destination numa is preferred
5514 * 2) task is cache cold, or 5518 * 2) task is cache cold, or
5515 * 3) too many balance attempts have failed. 5519 * 3) too many balance attempts have failed.
5516 */ 5520 */
5517 tsk_cache_hot = task_hot(p, env); 5521 tsk_cache_hot = task_hot(p, env);
5518 if (!tsk_cache_hot) 5522 if (!tsk_cache_hot)
5519 tsk_cache_hot = migrate_degrades_locality(p, env); 5523 tsk_cache_hot = migrate_degrades_locality(p, env);
5520 5524
5521 if (migrate_improves_locality(p, env) || !tsk_cache_hot || 5525 if (migrate_improves_locality(p, env) || !tsk_cache_hot ||
5522 env->sd->nr_balance_failed > env->sd->cache_nice_tries) { 5526 env->sd->nr_balance_failed > env->sd->cache_nice_tries) {
5523 if (tsk_cache_hot) { 5527 if (tsk_cache_hot) {
5524 schedstat_inc(env->sd, lb_hot_gained[env->idle]); 5528 schedstat_inc(env->sd, lb_hot_gained[env->idle]);
5525 schedstat_inc(p, se.statistics.nr_forced_migrations); 5529 schedstat_inc(p, se.statistics.nr_forced_migrations);
5526 } 5530 }
5527 return 1; 5531 return 1;
5528 } 5532 }
5529 5533
5530 schedstat_inc(p, se.statistics.nr_failed_migrations_hot); 5534 schedstat_inc(p, se.statistics.nr_failed_migrations_hot);
5531 return 0; 5535 return 0;
5532 } 5536 }
5533 5537
5534 /* 5538 /*
5535 * detach_task() -- detach the task for the migration specified in env 5539 * detach_task() -- detach the task for the migration specified in env
5536 */ 5540 */
5537 static void detach_task(struct task_struct *p, struct lb_env *env) 5541 static void detach_task(struct task_struct *p, struct lb_env *env)
5538 { 5542 {
5539 lockdep_assert_held(&env->src_rq->lock); 5543 lockdep_assert_held(&env->src_rq->lock);
5540 5544
5541 deactivate_task(env->src_rq, p, 0); 5545 deactivate_task(env->src_rq, p, 0);
5542 p->on_rq = TASK_ON_RQ_MIGRATING; 5546 p->on_rq = TASK_ON_RQ_MIGRATING;
5543 set_task_cpu(p, env->dst_cpu); 5547 set_task_cpu(p, env->dst_cpu);
5544 } 5548 }
5545 5549
5546 /* 5550 /*
5547 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as 5551 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as
5548 * part of active balancing operations within "domain". 5552 * part of active balancing operations within "domain".
5549 * 5553 *
5550 * Returns a task if successful and NULL otherwise. 5554 * Returns a task if successful and NULL otherwise.
5551 */ 5555 */
5552 static struct task_struct *detach_one_task(struct lb_env *env) 5556 static struct task_struct *detach_one_task(struct lb_env *env)
5553 { 5557 {
5554 struct task_struct *p, *n; 5558 struct task_struct *p, *n;
5555 5559
5556 lockdep_assert_held(&env->src_rq->lock); 5560 lockdep_assert_held(&env->src_rq->lock);
5557 5561
5558 list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) { 5562 list_for_each_entry_safe(p, n, &env->src_rq->cfs_tasks, se.group_node) {
5559 if (!can_migrate_task(p, env)) 5563 if (!can_migrate_task(p, env))
5560 continue; 5564 continue;
5561 5565
5562 detach_task(p, env); 5566 detach_task(p, env);
5563 5567
5564 /* 5568 /*
5565 * Right now, this is only the second place where 5569 * Right now, this is only the second place where
5566 * lb_gained[env->idle] is updated (other is detach_tasks) 5570 * lb_gained[env->idle] is updated (other is detach_tasks)
5567 * so we can safely collect stats here rather than 5571 * so we can safely collect stats here rather than
5568 * inside detach_tasks(). 5572 * inside detach_tasks().
5569 */ 5573 */
5570 schedstat_inc(env->sd, lb_gained[env->idle]); 5574 schedstat_inc(env->sd, lb_gained[env->idle]);
5571 return p; 5575 return p;
5572 } 5576 }
5573 return NULL; 5577 return NULL;
5574 } 5578 }
5575 5579
5576 static const unsigned int sched_nr_migrate_break = 32; 5580 static const unsigned int sched_nr_migrate_break = 32;
5577 5581
5578 /* 5582 /*
5579 * detach_tasks() -- tries to detach up to imbalance weighted load from 5583 * detach_tasks() -- tries to detach up to imbalance weighted load from
5580 * busiest_rq, as part of a balancing operation within domain "sd". 5584 * busiest_rq, as part of a balancing operation within domain "sd".
5581 * 5585 *
5582 * Returns number of detached tasks if successful and 0 otherwise. 5586 * Returns number of detached tasks if successful and 0 otherwise.
5583 */ 5587 */
5584 static int detach_tasks(struct lb_env *env) 5588 static int detach_tasks(struct lb_env *env)
5585 { 5589 {
5586 struct list_head *tasks = &env->src_rq->cfs_tasks; 5590 struct list_head *tasks = &env->src_rq->cfs_tasks;
5587 struct task_struct *p; 5591 struct task_struct *p;
5588 unsigned long load; 5592 unsigned long load;
5589 int detached = 0; 5593 int detached = 0;
5590 5594
5591 lockdep_assert_held(&env->src_rq->lock); 5595 lockdep_assert_held(&env->src_rq->lock);
5592 5596
5593 if (env->imbalance <= 0) 5597 if (env->imbalance <= 0)
5594 return 0; 5598 return 0;
5595 5599
5596 while (!list_empty(tasks)) { 5600 while (!list_empty(tasks)) {
5597 p = list_first_entry(tasks, struct task_struct, se.group_node); 5601 p = list_first_entry(tasks, struct task_struct, se.group_node);
5598 5602
5599 env->loop++; 5603 env->loop++;
5600 /* We've more or less seen every task there is, call it quits */ 5604 /* We've more or less seen every task there is, call it quits */
5601 if (env->loop > env->loop_max) 5605 if (env->loop > env->loop_max)
5602 break; 5606 break;
5603 5607
5604 /* take a breather every nr_migrate tasks */ 5608 /* take a breather every nr_migrate tasks */
5605 if (env->loop > env->loop_break) { 5609 if (env->loop > env->loop_break) {
5606 env->loop_break += sched_nr_migrate_break; 5610 env->loop_break += sched_nr_migrate_break;
5607 env->flags |= LBF_NEED_BREAK; 5611 env->flags |= LBF_NEED_BREAK;
5608 break; 5612 break;
5609 } 5613 }
5610 5614
5611 if (!can_migrate_task(p, env)) 5615 if (!can_migrate_task(p, env))
5612 goto next; 5616 goto next;
5613 5617
5614 load = task_h_load(p); 5618 load = task_h_load(p);
5615 5619
5616 if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed) 5620 if (sched_feat(LB_MIN) && load < 16 && !env->sd->nr_balance_failed)
5617 goto next; 5621 goto next;
5618 5622
5619 if ((load / 2) > env->imbalance) 5623 if ((load / 2) > env->imbalance)
5620 goto next; 5624 goto next;
5621 5625
5622 detach_task(p, env); 5626 detach_task(p, env);
5623 list_add(&p->se.group_node, &env->tasks); 5627 list_add(&p->se.group_node, &env->tasks);
5624 5628
5625 detached++; 5629 detached++;
5626 env->imbalance -= load; 5630 env->imbalance -= load;
5627 5631
5628 #ifdef CONFIG_PREEMPT 5632 #ifdef CONFIG_PREEMPT
5629 /* 5633 /*
5630 * NEWIDLE balancing is a source of latency, so preemptible 5634 * NEWIDLE balancing is a source of latency, so preemptible
5631 * kernels will stop after the first task is detached to minimize 5635 * kernels will stop after the first task is detached to minimize
5632 * the critical section. 5636 * the critical section.
5633 */ 5637 */
5634 if (env->idle == CPU_NEWLY_IDLE) 5638 if (env->idle == CPU_NEWLY_IDLE)
5635 break; 5639 break;
5636 #endif 5640 #endif
5637 5641
5638 /* 5642 /*
5639 * We only want to steal up to the prescribed amount of 5643 * We only want to steal up to the prescribed amount of
5640 * weighted load. 5644 * weighted load.
5641 */ 5645 */
5642 if (env->imbalance <= 0) 5646 if (env->imbalance <= 0)
5643 break; 5647 break;
5644 5648
5645 continue; 5649 continue;
5646 next: 5650 next:
5647 list_move_tail(&p->se.group_node, tasks); 5651 list_move_tail(&p->se.group_node, tasks);
5648 } 5652 }
5649 5653
5650 /* 5654 /*
5651 * Right now, this is one of only two places we collect this stat 5655 * Right now, this is one of only two places we collect this stat
5652 * so we can safely collect detach_one_task() stats here rather 5656 * so we can safely collect detach_one_task() stats here rather
5653 * than inside detach_one_task(). 5657 * than inside detach_one_task().
5654 */ 5658 */
5655 schedstat_add(env->sd, lb_gained[env->idle], detached); 5659 schedstat_add(env->sd, lb_gained[env->idle], detached);
5656 5660
5657 return detached; 5661 return detached;
5658 } 5662 }
5659 5663
5660 /* 5664 /*
5661 * attach_task() -- attach the task detached by detach_task() to its new rq. 5665 * attach_task() -- attach the task detached by detach_task() to its new rq.
5662 */ 5666 */
5663 static void attach_task(struct rq *rq, struct task_struct *p) 5667 static void attach_task(struct rq *rq, struct task_struct *p)
5664 { 5668 {
5665 lockdep_assert_held(&rq->lock); 5669 lockdep_assert_held(&rq->lock);
5666 5670
5667 BUG_ON(task_rq(p) != rq); 5671 BUG_ON(task_rq(p) != rq);
5668 p->on_rq = TASK_ON_RQ_QUEUED; 5672 p->on_rq = TASK_ON_RQ_QUEUED;
5669 activate_task(rq, p, 0); 5673 activate_task(rq, p, 0);
5670 check_preempt_curr(rq, p, 0); 5674 check_preempt_curr(rq, p, 0);
5671 } 5675 }
5672 5676
5673 /* 5677 /*
5674 * attach_one_task() -- attaches the task returned from detach_one_task() to 5678 * attach_one_task() -- attaches the task returned from detach_one_task() to
5675 * its new rq. 5679 * its new rq.
5676 */ 5680 */
5677 static void attach_one_task(struct rq *rq, struct task_struct *p) 5681 static void attach_one_task(struct rq *rq, struct task_struct *p)
5678 { 5682 {
5679 raw_spin_lock(&rq->lock); 5683 raw_spin_lock(&rq->lock);
5680 attach_task(rq, p); 5684 attach_task(rq, p);
5681 raw_spin_unlock(&rq->lock); 5685 raw_spin_unlock(&rq->lock);
5682 } 5686 }
5683 5687
5684 /* 5688 /*
5685 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their 5689 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their
5686 * new rq. 5690 * new rq.
5687 */ 5691 */
5688 static void attach_tasks(struct lb_env *env) 5692 static void attach_tasks(struct lb_env *env)
5689 { 5693 {
5690 struct list_head *tasks = &env->tasks; 5694 struct list_head *tasks = &env->tasks;
5691 struct task_struct *p; 5695 struct task_struct *p;
5692 5696
5693 raw_spin_lock(&env->dst_rq->lock); 5697 raw_spin_lock(&env->dst_rq->lock);
5694 5698
5695 while (!list_empty(tasks)) { 5699 while (!list_empty(tasks)) {
5696 p = list_first_entry(tasks, struct task_struct, se.group_node); 5700 p = list_first_entry(tasks, struct task_struct, se.group_node);
5697 list_del_init(&p->se.group_node); 5701 list_del_init(&p->se.group_node);
5698 5702
5699 attach_task(env->dst_rq, p); 5703 attach_task(env->dst_rq, p);
5700 } 5704 }
5701 5705
5702 raw_spin_unlock(&env->dst_rq->lock); 5706 raw_spin_unlock(&env->dst_rq->lock);
5703 } 5707 }
5704 5708
5705 #ifdef CONFIG_FAIR_GROUP_SCHED 5709 #ifdef CONFIG_FAIR_GROUP_SCHED
5706 /* 5710 /*
5707 * update tg->load_weight by folding this cpu's load_avg 5711 * update tg->load_weight by folding this cpu's load_avg
5708 */ 5712 */
5709 static void __update_blocked_averages_cpu(struct task_group *tg, int cpu) 5713 static void __update_blocked_averages_cpu(struct task_group *tg, int cpu)
5710 { 5714 {
5711 struct sched_entity *se = tg->se[cpu]; 5715 struct sched_entity *se = tg->se[cpu];
5712 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu]; 5716 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu];
5713 5717
5714 /* throttled entities do not contribute to load */ 5718 /* throttled entities do not contribute to load */
5715 if (throttled_hierarchy(cfs_rq)) 5719 if (throttled_hierarchy(cfs_rq))
5716 return; 5720 return;
5717 5721
5718 update_cfs_rq_blocked_load(cfs_rq, 1); 5722 update_cfs_rq_blocked_load(cfs_rq, 1);
5719 5723
5720 if (se) { 5724 if (se) {
5721 update_entity_load_avg(se, 1); 5725 update_entity_load_avg(se, 1);
5722 /* 5726 /*
5723 * We pivot on our runnable average having decayed to zero for 5727 * We pivot on our runnable average having decayed to zero for
5724 * list removal. This generally implies that all our children 5728 * list removal. This generally implies that all our children
5725 * have also been removed (modulo rounding error or bandwidth 5729 * have also been removed (modulo rounding error or bandwidth
5726 * control); however, such cases are rare and we can fix these 5730 * control); however, such cases are rare and we can fix these
5727 * at enqueue. 5731 * at enqueue.
5728 * 5732 *
5729 * TODO: fix up out-of-order children on enqueue. 5733 * TODO: fix up out-of-order children on enqueue.
5730 */ 5734 */
5731 if (!se->avg.runnable_avg_sum && !cfs_rq->nr_running) 5735 if (!se->avg.runnable_avg_sum && !cfs_rq->nr_running)
5732 list_del_leaf_cfs_rq(cfs_rq); 5736 list_del_leaf_cfs_rq(cfs_rq);
5733 } else { 5737 } else {
5734 struct rq *rq = rq_of(cfs_rq); 5738 struct rq *rq = rq_of(cfs_rq);
5735 update_rq_runnable_avg(rq, rq->nr_running); 5739 update_rq_runnable_avg(rq, rq->nr_running);
5736 } 5740 }
5737 } 5741 }
5738 5742
5739 static void update_blocked_averages(int cpu) 5743 static void update_blocked_averages(int cpu)
5740 { 5744 {
5741 struct rq *rq = cpu_rq(cpu); 5745 struct rq *rq = cpu_rq(cpu);
5742 struct cfs_rq *cfs_rq; 5746 struct cfs_rq *cfs_rq;
5743 unsigned long flags; 5747 unsigned long flags;
5744 5748
5745 raw_spin_lock_irqsave(&rq->lock, flags); 5749 raw_spin_lock_irqsave(&rq->lock, flags);
5746 update_rq_clock(rq); 5750 update_rq_clock(rq);
5747 /* 5751 /*
5748 * Iterates the task_group tree in a bottom up fashion, see 5752 * Iterates the task_group tree in a bottom up fashion, see
5749 * list_add_leaf_cfs_rq() for details. 5753 * list_add_leaf_cfs_rq() for details.
5750 */ 5754 */
5751 for_each_leaf_cfs_rq(rq, cfs_rq) { 5755 for_each_leaf_cfs_rq(rq, cfs_rq) {
5752 /* 5756 /*
5753 * Note: We may want to consider periodically releasing 5757 * Note: We may want to consider periodically releasing
5754 * rq->lock about these updates so that creating many task 5758 * rq->lock about these updates so that creating many task
5755 * groups does not result in continually extending hold time. 5759 * groups does not result in continually extending hold time.
5756 */ 5760 */
5757 __update_blocked_averages_cpu(cfs_rq->tg, rq->cpu); 5761 __update_blocked_averages_cpu(cfs_rq->tg, rq->cpu);
5758 } 5762 }
5759 5763
5760 raw_spin_unlock_irqrestore(&rq->lock, flags); 5764 raw_spin_unlock_irqrestore(&rq->lock, flags);
5761 } 5765 }
5762 5766
5763 /* 5767 /*
5764 * Compute the hierarchical load factor for cfs_rq and all its ascendants. 5768 * Compute the hierarchical load factor for cfs_rq and all its ascendants.
5765 * This needs to be done in a top-down fashion because the load of a child 5769 * This needs to be done in a top-down fashion because the load of a child
5766 * group is a fraction of its parents load. 5770 * group is a fraction of its parents load.
5767 */ 5771 */
5768 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq) 5772 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq)
5769 { 5773 {
5770 struct rq *rq = rq_of(cfs_rq); 5774 struct rq *rq = rq_of(cfs_rq);
5771 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)]; 5775 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)];
5772 unsigned long now = jiffies; 5776 unsigned long now = jiffies;
5773 unsigned long load; 5777 unsigned long load;
5774 5778
5775 if (cfs_rq->last_h_load_update == now) 5779 if (cfs_rq->last_h_load_update == now)
5776 return; 5780 return;
5777 5781
5778 cfs_rq->h_load_next = NULL; 5782 cfs_rq->h_load_next = NULL;
5779 for_each_sched_entity(se) { 5783 for_each_sched_entity(se) {
5780 cfs_rq = cfs_rq_of(se); 5784 cfs_rq = cfs_rq_of(se);
5781 cfs_rq->h_load_next = se; 5785 cfs_rq->h_load_next = se;
5782 if (cfs_rq->last_h_load_update == now) 5786 if (cfs_rq->last_h_load_update == now)
5783 break; 5787 break;
5784 } 5788 }
5785 5789
5786 if (!se) { 5790 if (!se) {
5787 cfs_rq->h_load = cfs_rq->runnable_load_avg; 5791 cfs_rq->h_load = cfs_rq->runnable_load_avg;
5788 cfs_rq->last_h_load_update = now; 5792 cfs_rq->last_h_load_update = now;
5789 } 5793 }
5790 5794
5791 while ((se = cfs_rq->h_load_next) != NULL) { 5795 while ((se = cfs_rq->h_load_next) != NULL) {
5792 load = cfs_rq->h_load; 5796 load = cfs_rq->h_load;
5793 load = div64_ul(load * se->avg.load_avg_contrib, 5797 load = div64_ul(load * se->avg.load_avg_contrib,
5794 cfs_rq->runnable_load_avg + 1); 5798 cfs_rq->runnable_load_avg + 1);
5795 cfs_rq = group_cfs_rq(se); 5799 cfs_rq = group_cfs_rq(se);
5796 cfs_rq->h_load = load; 5800 cfs_rq->h_load = load;
5797 cfs_rq->last_h_load_update = now; 5801 cfs_rq->last_h_load_update = now;
5798 } 5802 }
5799 } 5803 }
5800 5804
5801 static unsigned long task_h_load(struct task_struct *p) 5805 static unsigned long task_h_load(struct task_struct *p)
5802 { 5806 {
5803 struct cfs_rq *cfs_rq = task_cfs_rq(p); 5807 struct cfs_rq *cfs_rq = task_cfs_rq(p);
5804 5808
5805 update_cfs_rq_h_load(cfs_rq); 5809 update_cfs_rq_h_load(cfs_rq);
5806 return div64_ul(p->se.avg.load_avg_contrib * cfs_rq->h_load, 5810 return div64_ul(p->se.avg.load_avg_contrib * cfs_rq->h_load,
5807 cfs_rq->runnable_load_avg + 1); 5811 cfs_rq->runnable_load_avg + 1);
5808 } 5812 }
5809 #else 5813 #else
5810 static inline void update_blocked_averages(int cpu) 5814 static inline void update_blocked_averages(int cpu)
5811 { 5815 {
5812 } 5816 }
5813 5817
5814 static unsigned long task_h_load(struct task_struct *p) 5818 static unsigned long task_h_load(struct task_struct *p)
5815 { 5819 {
5816 return p->se.avg.load_avg_contrib; 5820 return p->se.avg.load_avg_contrib;
5817 } 5821 }
5818 #endif 5822 #endif
5819 5823
5820 /********** Helpers for find_busiest_group ************************/ 5824 /********** Helpers for find_busiest_group ************************/
5821 5825
5822 enum group_type { 5826 enum group_type {
5823 group_other = 0, 5827 group_other = 0,
5824 group_imbalanced, 5828 group_imbalanced,
5825 group_overloaded, 5829 group_overloaded,
5826 }; 5830 };
5827 5831
5828 /* 5832 /*
5829 * sg_lb_stats - stats of a sched_group required for load_balancing 5833 * sg_lb_stats - stats of a sched_group required for load_balancing
5830 */ 5834 */
5831 struct sg_lb_stats { 5835 struct sg_lb_stats {
5832 unsigned long avg_load; /*Avg load across the CPUs of the group */ 5836 unsigned long avg_load; /*Avg load across the CPUs of the group */
5833 unsigned long group_load; /* Total load over the CPUs of the group */ 5837 unsigned long group_load; /* Total load over the CPUs of the group */
5834 unsigned long sum_weighted_load; /* Weighted load of group's tasks */ 5838 unsigned long sum_weighted_load; /* Weighted load of group's tasks */
5835 unsigned long load_per_task; 5839 unsigned long load_per_task;
5836 unsigned long group_capacity; 5840 unsigned long group_capacity;
5837 unsigned int sum_nr_running; /* Nr tasks running in the group */ 5841 unsigned int sum_nr_running; /* Nr tasks running in the group */
5838 unsigned int group_capacity_factor; 5842 unsigned int group_capacity_factor;
5839 unsigned int idle_cpus; 5843 unsigned int idle_cpus;
5840 unsigned int group_weight; 5844 unsigned int group_weight;
5841 enum group_type group_type; 5845 enum group_type group_type;
5842 int group_has_free_capacity; 5846 int group_has_free_capacity;
5843 #ifdef CONFIG_NUMA_BALANCING 5847 #ifdef CONFIG_NUMA_BALANCING
5844 unsigned int nr_numa_running; 5848 unsigned int nr_numa_running;
5845 unsigned int nr_preferred_running; 5849 unsigned int nr_preferred_running;
5846 #endif 5850 #endif
5847 }; 5851 };
5848 5852
5849 /* 5853 /*
5850 * sd_lb_stats - Structure to store the statistics of a sched_domain 5854 * sd_lb_stats - Structure to store the statistics of a sched_domain
5851 * during load balancing. 5855 * during load balancing.
5852 */ 5856 */
5853 struct sd_lb_stats { 5857 struct sd_lb_stats {
5854 struct sched_group *busiest; /* Busiest group in this sd */ 5858 struct sched_group *busiest; /* Busiest group in this sd */
5855 struct sched_group *local; /* Local group in this sd */ 5859 struct sched_group *local; /* Local group in this sd */
5856 unsigned long total_load; /* Total load of all groups in sd */ 5860 unsigned long total_load; /* Total load of all groups in sd */
5857 unsigned long total_capacity; /* Total capacity of all groups in sd */ 5861 unsigned long total_capacity; /* Total capacity of all groups in sd */
5858 unsigned long avg_load; /* Average load across all groups in sd */ 5862 unsigned long avg_load; /* Average load across all groups in sd */
5859 5863
5860 struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */ 5864 struct sg_lb_stats busiest_stat;/* Statistics of the busiest group */
5861 struct sg_lb_stats local_stat; /* Statistics of the local group */ 5865 struct sg_lb_stats local_stat; /* Statistics of the local group */
5862 }; 5866 };
5863 5867
5864 static inline void init_sd_lb_stats(struct sd_lb_stats *sds) 5868 static inline void init_sd_lb_stats(struct sd_lb_stats *sds)
5865 { 5869 {
5866 /* 5870 /*
5867 * Skimp on the clearing to avoid duplicate work. We can avoid clearing 5871 * Skimp on the clearing to avoid duplicate work. We can avoid clearing
5868 * local_stat because update_sg_lb_stats() does a full clear/assignment. 5872 * local_stat because update_sg_lb_stats() does a full clear/assignment.
5869 * We must however clear busiest_stat::avg_load because 5873 * We must however clear busiest_stat::avg_load because
5870 * update_sd_pick_busiest() reads this before assignment. 5874 * update_sd_pick_busiest() reads this before assignment.
5871 */ 5875 */
5872 *sds = (struct sd_lb_stats){ 5876 *sds = (struct sd_lb_stats){
5873 .busiest = NULL, 5877 .busiest = NULL,
5874 .local = NULL, 5878 .local = NULL,
5875 .total_load = 0UL, 5879 .total_load = 0UL,
5876 .total_capacity = 0UL, 5880 .total_capacity = 0UL,
5877 .busiest_stat = { 5881 .busiest_stat = {
5878 .avg_load = 0UL, 5882 .avg_load = 0UL,
5879 .sum_nr_running = 0, 5883 .sum_nr_running = 0,
5880 .group_type = group_other, 5884 .group_type = group_other,
5881 }, 5885 },
5882 }; 5886 };
5883 } 5887 }
5884 5888
5885 /** 5889 /**
5886 * get_sd_load_idx - Obtain the load index for a given sched domain. 5890 * get_sd_load_idx - Obtain the load index for a given sched domain.
5887 * @sd: The sched_domain whose load_idx is to be obtained. 5891 * @sd: The sched_domain whose load_idx is to be obtained.
5888 * @idle: The idle status of the CPU for whose sd load_idx is obtained. 5892 * @idle: The idle status of the CPU for whose sd load_idx is obtained.
5889 * 5893 *
5890 * Return: The load index. 5894 * Return: The load index.
5891 */ 5895 */
5892 static inline int get_sd_load_idx(struct sched_domain *sd, 5896 static inline int get_sd_load_idx(struct sched_domain *sd,
5893 enum cpu_idle_type idle) 5897 enum cpu_idle_type idle)
5894 { 5898 {
5895 int load_idx; 5899 int load_idx;
5896 5900
5897 switch (idle) { 5901 switch (idle) {
5898 case CPU_NOT_IDLE: 5902 case CPU_NOT_IDLE:
5899 load_idx = sd->busy_idx; 5903 load_idx = sd->busy_idx;
5900 break; 5904 break;
5901 5905
5902 case CPU_NEWLY_IDLE: 5906 case CPU_NEWLY_IDLE:
5903 load_idx = sd->newidle_idx; 5907 load_idx = sd->newidle_idx;
5904 break; 5908 break;
5905 default: 5909 default:
5906 load_idx = sd->idle_idx; 5910 load_idx = sd->idle_idx;
5907 break; 5911 break;
5908 } 5912 }
5909 5913
5910 return load_idx; 5914 return load_idx;
5911 } 5915 }
5912 5916
5913 static unsigned long default_scale_capacity(struct sched_domain *sd, int cpu) 5917 static unsigned long default_scale_capacity(struct sched_domain *sd, int cpu)
5914 { 5918 {
5915 return SCHED_CAPACITY_SCALE; 5919 return SCHED_CAPACITY_SCALE;
5916 } 5920 }
5917 5921
5918 unsigned long __weak arch_scale_freq_capacity(struct sched_domain *sd, int cpu) 5922 unsigned long __weak arch_scale_freq_capacity(struct sched_domain *sd, int cpu)
5919 { 5923 {
5920 return default_scale_capacity(sd, cpu); 5924 return default_scale_capacity(sd, cpu);
5921 } 5925 }
5922 5926
5923 static unsigned long default_scale_cpu_capacity(struct sched_domain *sd, int cpu) 5927 static unsigned long default_scale_cpu_capacity(struct sched_domain *sd, int cpu)
5924 { 5928 {
5925 if ((sd->flags & SD_SHARE_CPUCAPACITY) && (sd->span_weight > 1)) 5929 if ((sd->flags & SD_SHARE_CPUCAPACITY) && (sd->span_weight > 1))
5926 return sd->smt_gain / sd->span_weight; 5930 return sd->smt_gain / sd->span_weight;
5927 5931
5928 return SCHED_CAPACITY_SCALE; 5932 return SCHED_CAPACITY_SCALE;
5929 } 5933 }
5930 5934
5931 unsigned long __weak arch_scale_cpu_capacity(struct sched_domain *sd, int cpu) 5935 unsigned long __weak arch_scale_cpu_capacity(struct sched_domain *sd, int cpu)
5932 { 5936 {
5933 return default_scale_cpu_capacity(sd, cpu); 5937 return default_scale_cpu_capacity(sd, cpu);
5934 } 5938 }
5935 5939
5936 static unsigned long scale_rt_capacity(int cpu) 5940 static unsigned long scale_rt_capacity(int cpu)
5937 { 5941 {
5938 struct rq *rq = cpu_rq(cpu); 5942 struct rq *rq = cpu_rq(cpu);
5939 u64 total, available, age_stamp, avg; 5943 u64 total, available, age_stamp, avg;
5940 s64 delta; 5944 s64 delta;
5941 5945
5942 /* 5946 /*
5943 * Since we're reading these variables without serialization make sure 5947 * Since we're reading these variables without serialization make sure
5944 * we read them once before doing sanity checks on them. 5948 * we read them once before doing sanity checks on them.
5945 */ 5949 */
5946 age_stamp = ACCESS_ONCE(rq->age_stamp); 5950 age_stamp = ACCESS_ONCE(rq->age_stamp);
5947 avg = ACCESS_ONCE(rq->rt_avg); 5951 avg = ACCESS_ONCE(rq->rt_avg);
5948 5952
5949 delta = rq_clock(rq) - age_stamp; 5953 delta = rq_clock(rq) - age_stamp;
5950 if (unlikely(delta < 0)) 5954 if (unlikely(delta < 0))
5951 delta = 0; 5955 delta = 0;
5952 5956
5953 total = sched_avg_period() + delta; 5957 total = sched_avg_period() + delta;
5954 5958
5955 if (unlikely(total < avg)) { 5959 if (unlikely(total < avg)) {
5956 /* Ensures that capacity won't end up being negative */ 5960 /* Ensures that capacity won't end up being negative */
5957 available = 0; 5961 available = 0;
5958 } else { 5962 } else {
5959 available = total - avg; 5963 available = total - avg;
5960 } 5964 }
5961 5965
5962 if (unlikely((s64)total < SCHED_CAPACITY_SCALE)) 5966 if (unlikely((s64)total < SCHED_CAPACITY_SCALE))
5963 total = SCHED_CAPACITY_SCALE; 5967 total = SCHED_CAPACITY_SCALE;
5964 5968
5965 total >>= SCHED_CAPACITY_SHIFT; 5969 total >>= SCHED_CAPACITY_SHIFT;
5966 5970
5967 return div_u64(available, total); 5971 return div_u64(available, total);
5968 } 5972 }
5969 5973
5970 static void update_cpu_capacity(struct sched_domain *sd, int cpu) 5974 static void update_cpu_capacity(struct sched_domain *sd, int cpu)
5971 { 5975 {
5972 unsigned long capacity = SCHED_CAPACITY_SCALE; 5976 unsigned long capacity = SCHED_CAPACITY_SCALE;
5973 struct sched_group *sdg = sd->groups; 5977 struct sched_group *sdg = sd->groups;
5974 5978
5975 if (sched_feat(ARCH_CAPACITY)) 5979 if (sched_feat(ARCH_CAPACITY))
5976 capacity *= arch_scale_cpu_capacity(sd, cpu); 5980 capacity *= arch_scale_cpu_capacity(sd, cpu);
5977 else 5981 else
5978 capacity *= default_scale_cpu_capacity(sd, cpu); 5982 capacity *= default_scale_cpu_capacity(sd, cpu);
5979 5983
5980 capacity >>= SCHED_CAPACITY_SHIFT; 5984 capacity >>= SCHED_CAPACITY_SHIFT;
5981 5985
5982 sdg->sgc->capacity_orig = capacity; 5986 sdg->sgc->capacity_orig = capacity;
5983 5987
5984 if (sched_feat(ARCH_CAPACITY)) 5988 if (sched_feat(ARCH_CAPACITY))
5985 capacity *= arch_scale_freq_capacity(sd, cpu); 5989 capacity *= arch_scale_freq_capacity(sd, cpu);
5986 else 5990 else
5987 capacity *= default_scale_capacity(sd, cpu); 5991 capacity *= default_scale_capacity(sd, cpu);
5988 5992
5989 capacity >>= SCHED_CAPACITY_SHIFT; 5993 capacity >>= SCHED_CAPACITY_SHIFT;
5990 5994
5991 capacity *= scale_rt_capacity(cpu); 5995 capacity *= scale_rt_capacity(cpu);
5992 capacity >>= SCHED_CAPACITY_SHIFT; 5996 capacity >>= SCHED_CAPACITY_SHIFT;
5993 5997
5994 if (!capacity) 5998 if (!capacity)
5995 capacity = 1; 5999 capacity = 1;
5996 6000
5997 cpu_rq(cpu)->cpu_capacity = capacity; 6001 cpu_rq(cpu)->cpu_capacity = capacity;
5998 sdg->sgc->capacity = capacity; 6002 sdg->sgc->capacity = capacity;
5999 } 6003 }
6000 6004
6001 void update_group_capacity(struct sched_domain *sd, int cpu) 6005 void update_group_capacity(struct sched_domain *sd, int cpu)
6002 { 6006 {
6003 struct sched_domain *child = sd->child; 6007 struct sched_domain *child = sd->child;
6004 struct sched_group *group, *sdg = sd->groups; 6008 struct sched_group *group, *sdg = sd->groups;
6005 unsigned long capacity, capacity_orig; 6009 unsigned long capacity, capacity_orig;
6006 unsigned long interval; 6010 unsigned long interval;
6007 6011
6008 interval = msecs_to_jiffies(sd->balance_interval); 6012 interval = msecs_to_jiffies(sd->balance_interval);
6009 interval = clamp(interval, 1UL, max_load_balance_interval); 6013 interval = clamp(interval, 1UL, max_load_balance_interval);
6010 sdg->sgc->next_update = jiffies + interval; 6014 sdg->sgc->next_update = jiffies + interval;
6011 6015
6012 if (!child) { 6016 if (!child) {
6013 update_cpu_capacity(sd, cpu); 6017 update_cpu_capacity(sd, cpu);
6014 return; 6018 return;
6015 } 6019 }
6016 6020
6017 capacity_orig = capacity = 0; 6021 capacity_orig = capacity = 0;
6018 6022
6019 if (child->flags & SD_OVERLAP) { 6023 if (child->flags & SD_OVERLAP) {
6020 /* 6024 /*
6021 * SD_OVERLAP domains cannot assume that child groups 6025 * SD_OVERLAP domains cannot assume that child groups
6022 * span the current group. 6026 * span the current group.
6023 */ 6027 */
6024 6028
6025 for_each_cpu(cpu, sched_group_cpus(sdg)) { 6029 for_each_cpu(cpu, sched_group_cpus(sdg)) {
6026 struct sched_group_capacity *sgc; 6030 struct sched_group_capacity *sgc;
6027 struct rq *rq = cpu_rq(cpu); 6031 struct rq *rq = cpu_rq(cpu);
6028 6032
6029 /* 6033 /*
6030 * build_sched_domains() -> init_sched_groups_capacity() 6034 * build_sched_domains() -> init_sched_groups_capacity()
6031 * gets here before we've attached the domains to the 6035 * gets here before we've attached the domains to the
6032 * runqueues. 6036 * runqueues.
6033 * 6037 *
6034 * Use capacity_of(), which is set irrespective of domains 6038 * Use capacity_of(), which is set irrespective of domains
6035 * in update_cpu_capacity(). 6039 * in update_cpu_capacity().
6036 * 6040 *
6037 * This avoids capacity/capacity_orig from being 0 and 6041 * This avoids capacity/capacity_orig from being 0 and
6038 * causing divide-by-zero issues on boot. 6042 * causing divide-by-zero issues on boot.
6039 * 6043 *
6040 * Runtime updates will correct capacity_orig. 6044 * Runtime updates will correct capacity_orig.
6041 */ 6045 */
6042 if (unlikely(!rq->sd)) { 6046 if (unlikely(!rq->sd)) {
6043 capacity_orig += capacity_of(cpu); 6047 capacity_orig += capacity_of(cpu);
6044 capacity += capacity_of(cpu); 6048 capacity += capacity_of(cpu);
6045 continue; 6049 continue;
6046 } 6050 }
6047 6051
6048 sgc = rq->sd->groups->sgc; 6052 sgc = rq->sd->groups->sgc;
6049 capacity_orig += sgc->capacity_orig; 6053 capacity_orig += sgc->capacity_orig;
6050 capacity += sgc->capacity; 6054 capacity += sgc->capacity;
6051 } 6055 }
6052 } else { 6056 } else {
6053 /* 6057 /*
6054 * !SD_OVERLAP domains can assume that child groups 6058 * !SD_OVERLAP domains can assume that child groups
6055 * span the current group. 6059 * span the current group.
6056 */ 6060 */
6057 6061
6058 group = child->groups; 6062 group = child->groups;
6059 do { 6063 do {
6060 capacity_orig += group->sgc->capacity_orig; 6064 capacity_orig += group->sgc->capacity_orig;
6061 capacity += group->sgc->capacity; 6065 capacity += group->sgc->capacity;
6062 group = group->next; 6066 group = group->next;
6063 } while (group != child->groups); 6067 } while (group != child->groups);
6064 } 6068 }
6065 6069
6066 sdg->sgc->capacity_orig = capacity_orig; 6070 sdg->sgc->capacity_orig = capacity_orig;
6067 sdg->sgc->capacity = capacity; 6071 sdg->sgc->capacity = capacity;
6068 } 6072 }
6069 6073
6070 /* 6074 /*
6071 * Try and fix up capacity for tiny siblings, this is needed when 6075 * Try and fix up capacity for tiny siblings, this is needed when
6072 * things like SD_ASYM_PACKING need f_b_g to select another sibling 6076 * things like SD_ASYM_PACKING need f_b_g to select another sibling
6073 * which on its own isn't powerful enough. 6077 * which on its own isn't powerful enough.
6074 * 6078 *
6075 * See update_sd_pick_busiest() and check_asym_packing(). 6079 * See update_sd_pick_busiest() and check_asym_packing().
6076 */ 6080 */
6077 static inline int 6081 static inline int
6078 fix_small_capacity(struct sched_domain *sd, struct sched_group *group) 6082 fix_small_capacity(struct sched_domain *sd, struct sched_group *group)
6079 { 6083 {
6080 /* 6084 /*
6081 * Only siblings can have significantly less than SCHED_CAPACITY_SCALE 6085 * Only siblings can have significantly less than SCHED_CAPACITY_SCALE
6082 */ 6086 */
6083 if (!(sd->flags & SD_SHARE_CPUCAPACITY)) 6087 if (!(sd->flags & SD_SHARE_CPUCAPACITY))
6084 return 0; 6088 return 0;
6085 6089
6086 /* 6090 /*
6087 * If ~90% of the cpu_capacity is still there, we're good. 6091 * If ~90% of the cpu_capacity is still there, we're good.
6088 */ 6092 */
6089 if (group->sgc->capacity * 32 > group->sgc->capacity_orig * 29) 6093 if (group->sgc->capacity * 32 > group->sgc->capacity_orig * 29)
6090 return 1; 6094 return 1;
6091 6095
6092 return 0; 6096 return 0;
6093 } 6097 }
6094 6098
6095 /* 6099 /*
6096 * Group imbalance indicates (and tries to solve) the problem where balancing 6100 * Group imbalance indicates (and tries to solve) the problem where balancing
6097 * groups is inadequate due to tsk_cpus_allowed() constraints. 6101 * groups is inadequate due to tsk_cpus_allowed() constraints.
6098 * 6102 *
6099 * Imagine a situation of two groups of 4 cpus each and 4 tasks each with a 6103 * Imagine a situation of two groups of 4 cpus each and 4 tasks each with a
6100 * cpumask covering 1 cpu of the first group and 3 cpus of the second group. 6104 * cpumask covering 1 cpu of the first group and 3 cpus of the second group.
6101 * Something like: 6105 * Something like:
6102 * 6106 *
6103 * { 0 1 2 3 } { 4 5 6 7 } 6107 * { 0 1 2 3 } { 4 5 6 7 }
6104 * * * * * 6108 * * * * *
6105 * 6109 *
6106 * If we were to balance group-wise we'd place two tasks in the first group and 6110 * If we were to balance group-wise we'd place two tasks in the first group and
6107 * two tasks in the second group. Clearly this is undesired as it will overload 6111 * two tasks in the second group. Clearly this is undesired as it will overload
6108 * cpu 3 and leave one of the cpus in the second group unused. 6112 * cpu 3 and leave one of the cpus in the second group unused.
6109 * 6113 *
6110 * The current solution to this issue is detecting the skew in the first group 6114 * The current solution to this issue is detecting the skew in the first group
6111 * by noticing the lower domain failed to reach balance and had difficulty 6115 * by noticing the lower domain failed to reach balance and had difficulty
6112 * moving tasks due to affinity constraints. 6116 * moving tasks due to affinity constraints.
6113 * 6117 *
6114 * When this is so detected; this group becomes a candidate for busiest; see 6118 * When this is so detected; this group becomes a candidate for busiest; see
6115 * update_sd_pick_busiest(). And calculate_imbalance() and 6119 * update_sd_pick_busiest(). And calculate_imbalance() and
6116 * find_busiest_group() avoid some of the usual balance conditions to allow it 6120 * find_busiest_group() avoid some of the usual balance conditions to allow it
6117 * to create an effective group imbalance. 6121 * to create an effective group imbalance.
6118 * 6122 *
6119 * This is a somewhat tricky proposition since the next run might not find the 6123 * This is a somewhat tricky proposition since the next run might not find the
6120 * group imbalance and decide the groups need to be balanced again. A most 6124 * group imbalance and decide the groups need to be balanced again. A most
6121 * subtle and fragile situation. 6125 * subtle and fragile situation.
6122 */ 6126 */
6123 6127
6124 static inline int sg_imbalanced(struct sched_group *group) 6128 static inline int sg_imbalanced(struct sched_group *group)
6125 { 6129 {
6126 return group->sgc->imbalance; 6130 return group->sgc->imbalance;
6127 } 6131 }
6128 6132
6129 /* 6133 /*
6130 * Compute the group capacity factor. 6134 * Compute the group capacity factor.
6131 * 6135 *
6132 * Avoid the issue where N*frac(smt_capacity) >= 1 creates 'phantom' cores by 6136 * Avoid the issue where N*frac(smt_capacity) >= 1 creates 'phantom' cores by
6133 * first dividing out the smt factor and computing the actual number of cores 6137 * first dividing out the smt factor and computing the actual number of cores
6134 * and limit unit capacity with that. 6138 * and limit unit capacity with that.
6135 */ 6139 */
6136 static inline int sg_capacity_factor(struct lb_env *env, struct sched_group *group) 6140 static inline int sg_capacity_factor(struct lb_env *env, struct sched_group *group)
6137 { 6141 {
6138 unsigned int capacity_factor, smt, cpus; 6142 unsigned int capacity_factor, smt, cpus;
6139 unsigned int capacity, capacity_orig; 6143 unsigned int capacity, capacity_orig;
6140 6144
6141 capacity = group->sgc->capacity; 6145 capacity = group->sgc->capacity;
6142 capacity_orig = group->sgc->capacity_orig; 6146 capacity_orig = group->sgc->capacity_orig;
6143 cpus = group->group_weight; 6147 cpus = group->group_weight;
6144 6148
6145 /* smt := ceil(cpus / capacity), assumes: 1 < smt_capacity < 2 */ 6149 /* smt := ceil(cpus / capacity), assumes: 1 < smt_capacity < 2 */
6146 smt = DIV_ROUND_UP(SCHED_CAPACITY_SCALE * cpus, capacity_orig); 6150 smt = DIV_ROUND_UP(SCHED_CAPACITY_SCALE * cpus, capacity_orig);
6147 capacity_factor = cpus / smt; /* cores */ 6151 capacity_factor = cpus / smt; /* cores */
6148 6152
6149 capacity_factor = min_t(unsigned, 6153 capacity_factor = min_t(unsigned,
6150 capacity_factor, DIV_ROUND_CLOSEST(capacity, SCHED_CAPACITY_SCALE)); 6154 capacity_factor, DIV_ROUND_CLOSEST(capacity, SCHED_CAPACITY_SCALE));
6151 if (!capacity_factor) 6155 if (!capacity_factor)
6152 capacity_factor = fix_small_capacity(env->sd, group); 6156 capacity_factor = fix_small_capacity(env->sd, group);
6153 6157
6154 return capacity_factor; 6158 return capacity_factor;
6155 } 6159 }
6156 6160
6157 static enum group_type 6161 static enum group_type
6158 group_classify(struct sched_group *group, struct sg_lb_stats *sgs) 6162 group_classify(struct sched_group *group, struct sg_lb_stats *sgs)
6159 { 6163 {
6160 if (sgs->sum_nr_running > sgs->group_capacity_factor) 6164 if (sgs->sum_nr_running > sgs->group_capacity_factor)
6161 return group_overloaded; 6165 return group_overloaded;
6162 6166
6163 if (sg_imbalanced(group)) 6167 if (sg_imbalanced(group))
6164 return group_imbalanced; 6168 return group_imbalanced;
6165 6169
6166 return group_other; 6170 return group_other;
6167 } 6171 }
6168 6172
6169 /** 6173 /**
6170 * update_sg_lb_stats - Update sched_group's statistics for load balancing. 6174 * update_sg_lb_stats - Update sched_group's statistics for load balancing.
6171 * @env: The load balancing environment. 6175 * @env: The load balancing environment.
6172 * @group: sched_group whose statistics are to be updated. 6176 * @group: sched_group whose statistics are to be updated.
6173 * @load_idx: Load index of sched_domain of this_cpu for load calc. 6177 * @load_idx: Load index of sched_domain of this_cpu for load calc.
6174 * @local_group: Does group contain this_cpu. 6178 * @local_group: Does group contain this_cpu.
6175 * @sgs: variable to hold the statistics for this group. 6179 * @sgs: variable to hold the statistics for this group.
6176 * @overload: Indicate more than one runnable task for any CPU. 6180 * @overload: Indicate more than one runnable task for any CPU.
6177 */ 6181 */
6178 static inline void update_sg_lb_stats(struct lb_env *env, 6182 static inline void update_sg_lb_stats(struct lb_env *env,
6179 struct sched_group *group, int load_idx, 6183 struct sched_group *group, int load_idx,
6180 int local_group, struct sg_lb_stats *sgs, 6184 int local_group, struct sg_lb_stats *sgs,
6181 bool *overload) 6185 bool *overload)
6182 { 6186 {
6183 unsigned long load; 6187 unsigned long load;
6184 int i; 6188 int i;
6185 6189
6186 memset(sgs, 0, sizeof(*sgs)); 6190 memset(sgs, 0, sizeof(*sgs));
6187 6191
6188 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) { 6192 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
6189 struct rq *rq = cpu_rq(i); 6193 struct rq *rq = cpu_rq(i);
6190 6194
6191 /* Bias balancing toward cpus of our domain */ 6195 /* Bias balancing toward cpus of our domain */
6192 if (local_group) 6196 if (local_group)
6193 load = target_load(i, load_idx); 6197 load = target_load(i, load_idx);
6194 else 6198 else
6195 load = source_load(i, load_idx); 6199 load = source_load(i, load_idx);
6196 6200
6197 sgs->group_load += load; 6201 sgs->group_load += load;
6198 sgs->sum_nr_running += rq->cfs.h_nr_running; 6202 sgs->sum_nr_running += rq->cfs.h_nr_running;
6199 6203
6200 if (rq->nr_running > 1) 6204 if (rq->nr_running > 1)
6201 *overload = true; 6205 *overload = true;
6202 6206
6203 #ifdef CONFIG_NUMA_BALANCING 6207 #ifdef CONFIG_NUMA_BALANCING
6204 sgs->nr_numa_running += rq->nr_numa_running; 6208 sgs->nr_numa_running += rq->nr_numa_running;
6205 sgs->nr_preferred_running += rq->nr_preferred_running; 6209 sgs->nr_preferred_running += rq->nr_preferred_running;
6206 #endif 6210 #endif
6207 sgs->sum_weighted_load += weighted_cpuload(i); 6211 sgs->sum_weighted_load += weighted_cpuload(i);
6208 if (idle_cpu(i)) 6212 if (idle_cpu(i))
6209 sgs->idle_cpus++; 6213 sgs->idle_cpus++;
6210 } 6214 }
6211 6215
6212 /* Adjust by relative CPU capacity of the group */ 6216 /* Adjust by relative CPU capacity of the group */
6213 sgs->group_capacity = group->sgc->capacity; 6217 sgs->group_capacity = group->sgc->capacity;
6214 sgs->avg_load = (sgs->group_load*SCHED_CAPACITY_SCALE) / sgs->group_capacity; 6218 sgs->avg_load = (sgs->group_load*SCHED_CAPACITY_SCALE) / sgs->group_capacity;
6215 6219
6216 if (sgs->sum_nr_running) 6220 if (sgs->sum_nr_running)
6217 sgs->load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running; 6221 sgs->load_per_task = sgs->sum_weighted_load / sgs->sum_nr_running;
6218 6222
6219 sgs->group_weight = group->group_weight; 6223 sgs->group_weight = group->group_weight;
6220 sgs->group_capacity_factor = sg_capacity_factor(env, group); 6224 sgs->group_capacity_factor = sg_capacity_factor(env, group);
6221 sgs->group_type = group_classify(group, sgs); 6225 sgs->group_type = group_classify(group, sgs);
6222 6226
6223 if (sgs->group_capacity_factor > sgs->sum_nr_running) 6227 if (sgs->group_capacity_factor > sgs->sum_nr_running)
6224 sgs->group_has_free_capacity = 1; 6228 sgs->group_has_free_capacity = 1;
6225 } 6229 }
6226 6230
6227 /** 6231 /**
6228 * update_sd_pick_busiest - return 1 on busiest group 6232 * update_sd_pick_busiest - return 1 on busiest group
6229 * @env: The load balancing environment. 6233 * @env: The load balancing environment.
6230 * @sds: sched_domain statistics 6234 * @sds: sched_domain statistics
6231 * @sg: sched_group candidate to be checked for being the busiest 6235 * @sg: sched_group candidate to be checked for being the busiest
6232 * @sgs: sched_group statistics 6236 * @sgs: sched_group statistics
6233 * 6237 *
6234 * Determine if @sg is a busier group than the previously selected 6238 * Determine if @sg is a busier group than the previously selected
6235 * busiest group. 6239 * busiest group.
6236 * 6240 *
6237 * Return: %true if @sg is a busier group than the previously selected 6241 * Return: %true if @sg is a busier group than the previously selected
6238 * busiest group. %false otherwise. 6242 * busiest group. %false otherwise.
6239 */ 6243 */
6240 static bool update_sd_pick_busiest(struct lb_env *env, 6244 static bool update_sd_pick_busiest(struct lb_env *env,
6241 struct sd_lb_stats *sds, 6245 struct sd_lb_stats *sds,
6242 struct sched_group *sg, 6246 struct sched_group *sg,
6243 struct sg_lb_stats *sgs) 6247 struct sg_lb_stats *sgs)
6244 { 6248 {
6245 struct sg_lb_stats *busiest = &sds->busiest_stat; 6249 struct sg_lb_stats *busiest = &sds->busiest_stat;
6246 6250
6247 if (sgs->group_type > busiest->group_type) 6251 if (sgs->group_type > busiest->group_type)
6248 return true; 6252 return true;
6249 6253
6250 if (sgs->group_type < busiest->group_type) 6254 if (sgs->group_type < busiest->group_type)
6251 return false; 6255 return false;
6252 6256
6253 if (sgs->avg_load <= busiest->avg_load) 6257 if (sgs->avg_load <= busiest->avg_load)
6254 return false; 6258 return false;
6255 6259
6256 /* This is the busiest node in its class. */ 6260 /* This is the busiest node in its class. */
6257 if (!(env->sd->flags & SD_ASYM_PACKING)) 6261 if (!(env->sd->flags & SD_ASYM_PACKING))
6258 return true; 6262 return true;
6259 6263
6260 /* 6264 /*
6261 * ASYM_PACKING needs to move all the work to the lowest 6265 * ASYM_PACKING needs to move all the work to the lowest
6262 * numbered CPUs in the group, therefore mark all groups 6266 * numbered CPUs in the group, therefore mark all groups
6263 * higher than ourself as busy. 6267 * higher than ourself as busy.
6264 */ 6268 */
6265 if (sgs->sum_nr_running && env->dst_cpu < group_first_cpu(sg)) { 6269 if (sgs->sum_nr_running && env->dst_cpu < group_first_cpu(sg)) {
6266 if (!sds->busiest) 6270 if (!sds->busiest)
6267 return true; 6271 return true;
6268 6272
6269 if (group_first_cpu(sds->busiest) > group_first_cpu(sg)) 6273 if (group_first_cpu(sds->busiest) > group_first_cpu(sg))
6270 return true; 6274 return true;
6271 } 6275 }
6272 6276
6273 return false; 6277 return false;
6274 } 6278 }
6275 6279
6276 #ifdef CONFIG_NUMA_BALANCING 6280 #ifdef CONFIG_NUMA_BALANCING
6277 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs) 6281 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
6278 { 6282 {
6279 if (sgs->sum_nr_running > sgs->nr_numa_running) 6283 if (sgs->sum_nr_running > sgs->nr_numa_running)
6280 return regular; 6284 return regular;
6281 if (sgs->sum_nr_running > sgs->nr_preferred_running) 6285 if (sgs->sum_nr_running > sgs->nr_preferred_running)
6282 return remote; 6286 return remote;
6283 return all; 6287 return all;
6284 } 6288 }
6285 6289
6286 static inline enum fbq_type fbq_classify_rq(struct rq *rq) 6290 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
6287 { 6291 {
6288 if (rq->nr_running > rq->nr_numa_running) 6292 if (rq->nr_running > rq->nr_numa_running)
6289 return regular; 6293 return regular;
6290 if (rq->nr_running > rq->nr_preferred_running) 6294 if (rq->nr_running > rq->nr_preferred_running)
6291 return remote; 6295 return remote;
6292 return all; 6296 return all;
6293 } 6297 }
6294 #else 6298 #else
6295 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs) 6299 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs)
6296 { 6300 {
6297 return all; 6301 return all;
6298 } 6302 }
6299 6303
6300 static inline enum fbq_type fbq_classify_rq(struct rq *rq) 6304 static inline enum fbq_type fbq_classify_rq(struct rq *rq)
6301 { 6305 {
6302 return regular; 6306 return regular;
6303 } 6307 }
6304 #endif /* CONFIG_NUMA_BALANCING */ 6308 #endif /* CONFIG_NUMA_BALANCING */
6305 6309
6306 /** 6310 /**
6307 * update_sd_lb_stats - Update sched_domain's statistics for load balancing. 6311 * update_sd_lb_stats - Update sched_domain's statistics for load balancing.
6308 * @env: The load balancing environment. 6312 * @env: The load balancing environment.
6309 * @sds: variable to hold the statistics for this sched_domain. 6313 * @sds: variable to hold the statistics for this sched_domain.
6310 */ 6314 */
6311 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds) 6315 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds)
6312 { 6316 {
6313 struct sched_domain *child = env->sd->child; 6317 struct sched_domain *child = env->sd->child;
6314 struct sched_group *sg = env->sd->groups; 6318 struct sched_group *sg = env->sd->groups;
6315 struct sg_lb_stats tmp_sgs; 6319 struct sg_lb_stats tmp_sgs;
6316 int load_idx, prefer_sibling = 0; 6320 int load_idx, prefer_sibling = 0;
6317 bool overload = false; 6321 bool overload = false;
6318 6322
6319 if (child && child->flags & SD_PREFER_SIBLING) 6323 if (child && child->flags & SD_PREFER_SIBLING)
6320 prefer_sibling = 1; 6324 prefer_sibling = 1;
6321 6325
6322 load_idx = get_sd_load_idx(env->sd, env->idle); 6326 load_idx = get_sd_load_idx(env->sd, env->idle);
6323 6327
6324 do { 6328 do {
6325 struct sg_lb_stats *sgs = &tmp_sgs; 6329 struct sg_lb_stats *sgs = &tmp_sgs;
6326 int local_group; 6330 int local_group;
6327 6331
6328 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg)); 6332 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_cpus(sg));
6329 if (local_group) { 6333 if (local_group) {
6330 sds->local = sg; 6334 sds->local = sg;
6331 sgs = &sds->local_stat; 6335 sgs = &sds->local_stat;
6332 6336
6333 if (env->idle != CPU_NEWLY_IDLE || 6337 if (env->idle != CPU_NEWLY_IDLE ||
6334 time_after_eq(jiffies, sg->sgc->next_update)) 6338 time_after_eq(jiffies, sg->sgc->next_update))
6335 update_group_capacity(env->sd, env->dst_cpu); 6339 update_group_capacity(env->sd, env->dst_cpu);
6336 } 6340 }
6337 6341
6338 update_sg_lb_stats(env, sg, load_idx, local_group, sgs, 6342 update_sg_lb_stats(env, sg, load_idx, local_group, sgs,
6339 &overload); 6343 &overload);
6340 6344
6341 if (local_group) 6345 if (local_group)
6342 goto next_group; 6346 goto next_group;
6343 6347
6344 /* 6348 /*
6345 * In case the child domain prefers tasks go to siblings 6349 * In case the child domain prefers tasks go to siblings
6346 * first, lower the sg capacity factor to one so that we'll try 6350 * first, lower the sg capacity factor to one so that we'll try
6347 * and move all the excess tasks away. We lower the capacity 6351 * and move all the excess tasks away. We lower the capacity
6348 * of a group only if the local group has the capacity to fit 6352 * of a group only if the local group has the capacity to fit
6349 * these excess tasks, i.e. nr_running < group_capacity_factor. The 6353 * these excess tasks, i.e. nr_running < group_capacity_factor. The
6350 * extra check prevents the case where you always pull from the 6354 * extra check prevents the case where you always pull from the
6351 * heaviest group when it is already under-utilized (possible 6355 * heaviest group when it is already under-utilized (possible
6352 * with a large weight task outweighs the tasks on the system). 6356 * with a large weight task outweighs the tasks on the system).
6353 */ 6357 */
6354 if (prefer_sibling && sds->local && 6358 if (prefer_sibling && sds->local &&
6355 sds->local_stat.group_has_free_capacity) { 6359 sds->local_stat.group_has_free_capacity) {
6356 sgs->group_capacity_factor = min(sgs->group_capacity_factor, 1U); 6360 sgs->group_capacity_factor = min(sgs->group_capacity_factor, 1U);
6357 sgs->group_type = group_classify(sg, sgs); 6361 sgs->group_type = group_classify(sg, sgs);
6358 } 6362 }
6359 6363
6360 if (update_sd_pick_busiest(env, sds, sg, sgs)) { 6364 if (update_sd_pick_busiest(env, sds, sg, sgs)) {
6361 sds->busiest = sg; 6365 sds->busiest = sg;
6362 sds->busiest_stat = *sgs; 6366 sds->busiest_stat = *sgs;
6363 } 6367 }
6364 6368
6365 next_group: 6369 next_group:
6366 /* Now, start updating sd_lb_stats */ 6370 /* Now, start updating sd_lb_stats */
6367 sds->total_load += sgs->group_load; 6371 sds->total_load += sgs->group_load;
6368 sds->total_capacity += sgs->group_capacity; 6372 sds->total_capacity += sgs->group_capacity;
6369 6373
6370 sg = sg->next; 6374 sg = sg->next;
6371 } while (sg != env->sd->groups); 6375 } while (sg != env->sd->groups);
6372 6376
6373 if (env->sd->flags & SD_NUMA) 6377 if (env->sd->flags & SD_NUMA)
6374 env->fbq_type = fbq_classify_group(&sds->busiest_stat); 6378 env->fbq_type = fbq_classify_group(&sds->busiest_stat);
6375 6379
6376 if (!env->sd->parent) { 6380 if (!env->sd->parent) {
6377 /* update overload indicator if we are at root domain */ 6381 /* update overload indicator if we are at root domain */
6378 if (env->dst_rq->rd->overload != overload) 6382 if (env->dst_rq->rd->overload != overload)
6379 env->dst_rq->rd->overload = overload; 6383 env->dst_rq->rd->overload = overload;
6380 } 6384 }
6381 6385
6382 } 6386 }
6383 6387
6384 /** 6388 /**
6385 * check_asym_packing - Check to see if the group is packed into the 6389 * check_asym_packing - Check to see if the group is packed into the
6386 * sched doman. 6390 * sched doman.
6387 * 6391 *
6388 * This is primarily intended to used at the sibling level. Some 6392 * This is primarily intended to used at the sibling level. Some
6389 * cores like POWER7 prefer to use lower numbered SMT threads. In the 6393 * cores like POWER7 prefer to use lower numbered SMT threads. In the
6390 * case of POWER7, it can move to lower SMT modes only when higher 6394 * case of POWER7, it can move to lower SMT modes only when higher
6391 * threads are idle. When in lower SMT modes, the threads will 6395 * threads are idle. When in lower SMT modes, the threads will
6392 * perform better since they share less core resources. Hence when we 6396 * perform better since they share less core resources. Hence when we
6393 * have idle threads, we want them to be the higher ones. 6397 * have idle threads, we want them to be the higher ones.
6394 * 6398 *
6395 * This packing function is run on idle threads. It checks to see if 6399 * This packing function is run on idle threads. It checks to see if
6396 * the busiest CPU in this domain (core in the P7 case) has a higher 6400 * the busiest CPU in this domain (core in the P7 case) has a higher
6397 * CPU number than the packing function is being run on. Here we are 6401 * CPU number than the packing function is being run on. Here we are
6398 * assuming lower CPU number will be equivalent to lower a SMT thread 6402 * assuming lower CPU number will be equivalent to lower a SMT thread
6399 * number. 6403 * number.
6400 * 6404 *
6401 * Return: 1 when packing is required and a task should be moved to 6405 * Return: 1 when packing is required and a task should be moved to
6402 * this CPU. The amount of the imbalance is returned in *imbalance. 6406 * this CPU. The amount of the imbalance is returned in *imbalance.
6403 * 6407 *
6404 * @env: The load balancing environment. 6408 * @env: The load balancing environment.
6405 * @sds: Statistics of the sched_domain which is to be packed 6409 * @sds: Statistics of the sched_domain which is to be packed
6406 */ 6410 */
6407 static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds) 6411 static int check_asym_packing(struct lb_env *env, struct sd_lb_stats *sds)
6408 { 6412 {
6409 int busiest_cpu; 6413 int busiest_cpu;
6410 6414
6411 if (!(env->sd->flags & SD_ASYM_PACKING)) 6415 if (!(env->sd->flags & SD_ASYM_PACKING))
6412 return 0; 6416 return 0;
6413 6417
6414 if (!sds->busiest) 6418 if (!sds->busiest)
6415 return 0; 6419 return 0;
6416 6420
6417 busiest_cpu = group_first_cpu(sds->busiest); 6421 busiest_cpu = group_first_cpu(sds->busiest);
6418 if (env->dst_cpu > busiest_cpu) 6422 if (env->dst_cpu > busiest_cpu)
6419 return 0; 6423 return 0;
6420 6424
6421 env->imbalance = DIV_ROUND_CLOSEST( 6425 env->imbalance = DIV_ROUND_CLOSEST(
6422 sds->busiest_stat.avg_load * sds->busiest_stat.group_capacity, 6426 sds->busiest_stat.avg_load * sds->busiest_stat.group_capacity,
6423 SCHED_CAPACITY_SCALE); 6427 SCHED_CAPACITY_SCALE);
6424 6428
6425 return 1; 6429 return 1;
6426 } 6430 }
6427 6431
6428 /** 6432 /**
6429 * fix_small_imbalance - Calculate the minor imbalance that exists 6433 * fix_small_imbalance - Calculate the minor imbalance that exists
6430 * amongst the groups of a sched_domain, during 6434 * amongst the groups of a sched_domain, during
6431 * load balancing. 6435 * load balancing.
6432 * @env: The load balancing environment. 6436 * @env: The load balancing environment.
6433 * @sds: Statistics of the sched_domain whose imbalance is to be calculated. 6437 * @sds: Statistics of the sched_domain whose imbalance is to be calculated.
6434 */ 6438 */
6435 static inline 6439 static inline
6436 void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds) 6440 void fix_small_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
6437 { 6441 {
6438 unsigned long tmp, capa_now = 0, capa_move = 0; 6442 unsigned long tmp, capa_now = 0, capa_move = 0;
6439 unsigned int imbn = 2; 6443 unsigned int imbn = 2;
6440 unsigned long scaled_busy_load_per_task; 6444 unsigned long scaled_busy_load_per_task;
6441 struct sg_lb_stats *local, *busiest; 6445 struct sg_lb_stats *local, *busiest;
6442 6446
6443 local = &sds->local_stat; 6447 local = &sds->local_stat;
6444 busiest = &sds->busiest_stat; 6448 busiest = &sds->busiest_stat;
6445 6449
6446 if (!local->sum_nr_running) 6450 if (!local->sum_nr_running)
6447 local->load_per_task = cpu_avg_load_per_task(env->dst_cpu); 6451 local->load_per_task = cpu_avg_load_per_task(env->dst_cpu);
6448 else if (busiest->load_per_task > local->load_per_task) 6452 else if (busiest->load_per_task > local->load_per_task)
6449 imbn = 1; 6453 imbn = 1;
6450 6454
6451 scaled_busy_load_per_task = 6455 scaled_busy_load_per_task =
6452 (busiest->load_per_task * SCHED_CAPACITY_SCALE) / 6456 (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
6453 busiest->group_capacity; 6457 busiest->group_capacity;
6454 6458
6455 if (busiest->avg_load + scaled_busy_load_per_task >= 6459 if (busiest->avg_load + scaled_busy_load_per_task >=
6456 local->avg_load + (scaled_busy_load_per_task * imbn)) { 6460 local->avg_load + (scaled_busy_load_per_task * imbn)) {
6457 env->imbalance = busiest->load_per_task; 6461 env->imbalance = busiest->load_per_task;
6458 return; 6462 return;
6459 } 6463 }
6460 6464
6461 /* 6465 /*
6462 * OK, we don't have enough imbalance to justify moving tasks, 6466 * OK, we don't have enough imbalance to justify moving tasks,
6463 * however we may be able to increase total CPU capacity used by 6467 * however we may be able to increase total CPU capacity used by
6464 * moving them. 6468 * moving them.
6465 */ 6469 */
6466 6470
6467 capa_now += busiest->group_capacity * 6471 capa_now += busiest->group_capacity *
6468 min(busiest->load_per_task, busiest->avg_load); 6472 min(busiest->load_per_task, busiest->avg_load);
6469 capa_now += local->group_capacity * 6473 capa_now += local->group_capacity *
6470 min(local->load_per_task, local->avg_load); 6474 min(local->load_per_task, local->avg_load);
6471 capa_now /= SCHED_CAPACITY_SCALE; 6475 capa_now /= SCHED_CAPACITY_SCALE;
6472 6476
6473 /* Amount of load we'd subtract */ 6477 /* Amount of load we'd subtract */
6474 if (busiest->avg_load > scaled_busy_load_per_task) { 6478 if (busiest->avg_load > scaled_busy_load_per_task) {
6475 capa_move += busiest->group_capacity * 6479 capa_move += busiest->group_capacity *
6476 min(busiest->load_per_task, 6480 min(busiest->load_per_task,
6477 busiest->avg_load - scaled_busy_load_per_task); 6481 busiest->avg_load - scaled_busy_load_per_task);
6478 } 6482 }
6479 6483
6480 /* Amount of load we'd add */ 6484 /* Amount of load we'd add */
6481 if (busiest->avg_load * busiest->group_capacity < 6485 if (busiest->avg_load * busiest->group_capacity <
6482 busiest->load_per_task * SCHED_CAPACITY_SCALE) { 6486 busiest->load_per_task * SCHED_CAPACITY_SCALE) {
6483 tmp = (busiest->avg_load * busiest->group_capacity) / 6487 tmp = (busiest->avg_load * busiest->group_capacity) /
6484 local->group_capacity; 6488 local->group_capacity;
6485 } else { 6489 } else {
6486 tmp = (busiest->load_per_task * SCHED_CAPACITY_SCALE) / 6490 tmp = (busiest->load_per_task * SCHED_CAPACITY_SCALE) /
6487 local->group_capacity; 6491 local->group_capacity;
6488 } 6492 }
6489 capa_move += local->group_capacity * 6493 capa_move += local->group_capacity *
6490 min(local->load_per_task, local->avg_load + tmp); 6494 min(local->load_per_task, local->avg_load + tmp);
6491 capa_move /= SCHED_CAPACITY_SCALE; 6495 capa_move /= SCHED_CAPACITY_SCALE;
6492 6496
6493 /* Move if we gain throughput */ 6497 /* Move if we gain throughput */
6494 if (capa_move > capa_now) 6498 if (capa_move > capa_now)
6495 env->imbalance = busiest->load_per_task; 6499 env->imbalance = busiest->load_per_task;
6496 } 6500 }
6497 6501
6498 /** 6502 /**
6499 * calculate_imbalance - Calculate the amount of imbalance present within the 6503 * calculate_imbalance - Calculate the amount of imbalance present within the
6500 * groups of a given sched_domain during load balance. 6504 * groups of a given sched_domain during load balance.
6501 * @env: load balance environment 6505 * @env: load balance environment
6502 * @sds: statistics of the sched_domain whose imbalance is to be calculated. 6506 * @sds: statistics of the sched_domain whose imbalance is to be calculated.
6503 */ 6507 */
6504 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds) 6508 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds)
6505 { 6509 {
6506 unsigned long max_pull, load_above_capacity = ~0UL; 6510 unsigned long max_pull, load_above_capacity = ~0UL;
6507 struct sg_lb_stats *local, *busiest; 6511 struct sg_lb_stats *local, *busiest;
6508 6512
6509 local = &sds->local_stat; 6513 local = &sds->local_stat;
6510 busiest = &sds->busiest_stat; 6514 busiest = &sds->busiest_stat;
6511 6515
6512 if (busiest->group_type == group_imbalanced) { 6516 if (busiest->group_type == group_imbalanced) {
6513 /* 6517 /*
6514 * In the group_imb case we cannot rely on group-wide averages 6518 * In the group_imb case we cannot rely on group-wide averages
6515 * to ensure cpu-load equilibrium, look at wider averages. XXX 6519 * to ensure cpu-load equilibrium, look at wider averages. XXX
6516 */ 6520 */
6517 busiest->load_per_task = 6521 busiest->load_per_task =
6518 min(busiest->load_per_task, sds->avg_load); 6522 min(busiest->load_per_task, sds->avg_load);
6519 } 6523 }
6520 6524
6521 /* 6525 /*
6522 * In the presence of smp nice balancing, certain scenarios can have 6526 * In the presence of smp nice balancing, certain scenarios can have
6523 * max load less than avg load(as we skip the groups at or below 6527 * max load less than avg load(as we skip the groups at or below
6524 * its cpu_capacity, while calculating max_load..) 6528 * its cpu_capacity, while calculating max_load..)
6525 */ 6529 */
6526 if (busiest->avg_load <= sds->avg_load || 6530 if (busiest->avg_load <= sds->avg_load ||
6527 local->avg_load >= sds->avg_load) { 6531 local->avg_load >= sds->avg_load) {
6528 env->imbalance = 0; 6532 env->imbalance = 0;
6529 return fix_small_imbalance(env, sds); 6533 return fix_small_imbalance(env, sds);
6530 } 6534 }
6531 6535
6532 /* 6536 /*
6533 * If there aren't any idle cpus, avoid creating some. 6537 * If there aren't any idle cpus, avoid creating some.
6534 */ 6538 */
6535 if (busiest->group_type == group_overloaded && 6539 if (busiest->group_type == group_overloaded &&
6536 local->group_type == group_overloaded) { 6540 local->group_type == group_overloaded) {
6537 load_above_capacity = 6541 load_above_capacity =
6538 (busiest->sum_nr_running - busiest->group_capacity_factor); 6542 (busiest->sum_nr_running - busiest->group_capacity_factor);
6539 6543
6540 load_above_capacity *= (SCHED_LOAD_SCALE * SCHED_CAPACITY_SCALE); 6544 load_above_capacity *= (SCHED_LOAD_SCALE * SCHED_CAPACITY_SCALE);
6541 load_above_capacity /= busiest->group_capacity; 6545 load_above_capacity /= busiest->group_capacity;
6542 } 6546 }
6543 6547
6544 /* 6548 /*
6545 * We're trying to get all the cpus to the average_load, so we don't 6549 * We're trying to get all the cpus to the average_load, so we don't
6546 * want to push ourselves above the average load, nor do we wish to 6550 * want to push ourselves above the average load, nor do we wish to
6547 * reduce the max loaded cpu below the average load. At the same time, 6551 * reduce the max loaded cpu below the average load. At the same time,
6548 * we also don't want to reduce the group load below the group capacity 6552 * we also don't want to reduce the group load below the group capacity
6549 * (so that we can implement power-savings policies etc). Thus we look 6553 * (so that we can implement power-savings policies etc). Thus we look
6550 * for the minimum possible imbalance. 6554 * for the minimum possible imbalance.
6551 */ 6555 */
6552 max_pull = min(busiest->avg_load - sds->avg_load, load_above_capacity); 6556 max_pull = min(busiest->avg_load - sds->avg_load, load_above_capacity);
6553 6557
6554 /* How much load to actually move to equalise the imbalance */ 6558 /* How much load to actually move to equalise the imbalance */
6555 env->imbalance = min( 6559 env->imbalance = min(
6556 max_pull * busiest->group_capacity, 6560 max_pull * busiest->group_capacity,
6557 (sds->avg_load - local->avg_load) * local->group_capacity 6561 (sds->avg_load - local->avg_load) * local->group_capacity
6558 ) / SCHED_CAPACITY_SCALE; 6562 ) / SCHED_CAPACITY_SCALE;
6559 6563
6560 /* 6564 /*
6561 * if *imbalance is less than the average load per runnable task 6565 * if *imbalance is less than the average load per runnable task
6562 * there is no guarantee that any tasks will be moved so we'll have 6566 * there is no guarantee that any tasks will be moved so we'll have
6563 * a think about bumping its value to force at least one task to be 6567 * a think about bumping its value to force at least one task to be
6564 * moved 6568 * moved
6565 */ 6569 */
6566 if (env->imbalance < busiest->load_per_task) 6570 if (env->imbalance < busiest->load_per_task)
6567 return fix_small_imbalance(env, sds); 6571 return fix_small_imbalance(env, sds);
6568 } 6572 }
6569 6573
6570 /******* find_busiest_group() helpers end here *********************/ 6574 /******* find_busiest_group() helpers end here *********************/
6571 6575
6572 /** 6576 /**
6573 * find_busiest_group - Returns the busiest group within the sched_domain 6577 * find_busiest_group - Returns the busiest group within the sched_domain
6574 * if there is an imbalance. If there isn't an imbalance, and 6578 * if there is an imbalance. If there isn't an imbalance, and
6575 * the user has opted for power-savings, it returns a group whose 6579 * the user has opted for power-savings, it returns a group whose
6576 * CPUs can be put to idle by rebalancing those tasks elsewhere, if 6580 * CPUs can be put to idle by rebalancing those tasks elsewhere, if
6577 * such a group exists. 6581 * such a group exists.
6578 * 6582 *
6579 * Also calculates the amount of weighted load which should be moved 6583 * Also calculates the amount of weighted load which should be moved
6580 * to restore balance. 6584 * to restore balance.
6581 * 6585 *
6582 * @env: The load balancing environment. 6586 * @env: The load balancing environment.
6583 * 6587 *
6584 * Return: - The busiest group if imbalance exists. 6588 * Return: - The busiest group if imbalance exists.
6585 * - If no imbalance and user has opted for power-savings balance, 6589 * - If no imbalance and user has opted for power-savings balance,
6586 * return the least loaded group whose CPUs can be 6590 * return the least loaded group whose CPUs can be
6587 * put to idle by rebalancing its tasks onto our group. 6591 * put to idle by rebalancing its tasks onto our group.
6588 */ 6592 */
6589 static struct sched_group *find_busiest_group(struct lb_env *env) 6593 static struct sched_group *find_busiest_group(struct lb_env *env)
6590 { 6594 {
6591 struct sg_lb_stats *local, *busiest; 6595 struct sg_lb_stats *local, *busiest;
6592 struct sd_lb_stats sds; 6596 struct sd_lb_stats sds;
6593 6597
6594 init_sd_lb_stats(&sds); 6598 init_sd_lb_stats(&sds);
6595 6599
6596 /* 6600 /*
6597 * Compute the various statistics relavent for load balancing at 6601 * Compute the various statistics relavent for load balancing at
6598 * this level. 6602 * this level.
6599 */ 6603 */
6600 update_sd_lb_stats(env, &sds); 6604 update_sd_lb_stats(env, &sds);
6601 local = &sds.local_stat; 6605 local = &sds.local_stat;
6602 busiest = &sds.busiest_stat; 6606 busiest = &sds.busiest_stat;
6603 6607
6604 if ((env->idle == CPU_IDLE || env->idle == CPU_NEWLY_IDLE) && 6608 if ((env->idle == CPU_IDLE || env->idle == CPU_NEWLY_IDLE) &&
6605 check_asym_packing(env, &sds)) 6609 check_asym_packing(env, &sds))
6606 return sds.busiest; 6610 return sds.busiest;
6607 6611
6608 /* There is no busy sibling group to pull tasks from */ 6612 /* There is no busy sibling group to pull tasks from */
6609 if (!sds.busiest || busiest->sum_nr_running == 0) 6613 if (!sds.busiest || busiest->sum_nr_running == 0)
6610 goto out_balanced; 6614 goto out_balanced;
6611 6615
6612 sds.avg_load = (SCHED_CAPACITY_SCALE * sds.total_load) 6616 sds.avg_load = (SCHED_CAPACITY_SCALE * sds.total_load)
6613 / sds.total_capacity; 6617 / sds.total_capacity;
6614 6618
6615 /* 6619 /*
6616 * If the busiest group is imbalanced the below checks don't 6620 * If the busiest group is imbalanced the below checks don't
6617 * work because they assume all things are equal, which typically 6621 * work because they assume all things are equal, which typically
6618 * isn't true due to cpus_allowed constraints and the like. 6622 * isn't true due to cpus_allowed constraints and the like.
6619 */ 6623 */
6620 if (busiest->group_type == group_imbalanced) 6624 if (busiest->group_type == group_imbalanced)
6621 goto force_balance; 6625 goto force_balance;
6622 6626
6623 /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */ 6627 /* SD_BALANCE_NEWIDLE trumps SMP nice when underutilized */
6624 if (env->idle == CPU_NEWLY_IDLE && local->group_has_free_capacity && 6628 if (env->idle == CPU_NEWLY_IDLE && local->group_has_free_capacity &&
6625 !busiest->group_has_free_capacity) 6629 !busiest->group_has_free_capacity)
6626 goto force_balance; 6630 goto force_balance;
6627 6631
6628 /* 6632 /*
6629 * If the local group is busier than the selected busiest group 6633 * If the local group is busier than the selected busiest group
6630 * don't try and pull any tasks. 6634 * don't try and pull any tasks.
6631 */ 6635 */
6632 if (local->avg_load >= busiest->avg_load) 6636 if (local->avg_load >= busiest->avg_load)
6633 goto out_balanced; 6637 goto out_balanced;
6634 6638
6635 /* 6639 /*
6636 * Don't pull any tasks if this group is already above the domain 6640 * Don't pull any tasks if this group is already above the domain
6637 * average load. 6641 * average load.
6638 */ 6642 */
6639 if (local->avg_load >= sds.avg_load) 6643 if (local->avg_load >= sds.avg_load)
6640 goto out_balanced; 6644 goto out_balanced;
6641 6645
6642 if (env->idle == CPU_IDLE) { 6646 if (env->idle == CPU_IDLE) {
6643 /* 6647 /*
6644 * This cpu is idle. If the busiest group is not overloaded 6648 * This cpu is idle. If the busiest group is not overloaded
6645 * and there is no imbalance between this and busiest group 6649 * and there is no imbalance between this and busiest group
6646 * wrt idle cpus, it is balanced. The imbalance becomes 6650 * wrt idle cpus, it is balanced. The imbalance becomes
6647 * significant if the diff is greater than 1 otherwise we 6651 * significant if the diff is greater than 1 otherwise we
6648 * might end up to just move the imbalance on another group 6652 * might end up to just move the imbalance on another group
6649 */ 6653 */
6650 if ((busiest->group_type != group_overloaded) && 6654 if ((busiest->group_type != group_overloaded) &&
6651 (local->idle_cpus <= (busiest->idle_cpus + 1))) 6655 (local->idle_cpus <= (busiest->idle_cpus + 1)))
6652 goto out_balanced; 6656 goto out_balanced;
6653 } else { 6657 } else {
6654 /* 6658 /*
6655 * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use 6659 * In the CPU_NEWLY_IDLE, CPU_NOT_IDLE cases, use
6656 * imbalance_pct to be conservative. 6660 * imbalance_pct to be conservative.
6657 */ 6661 */
6658 if (100 * busiest->avg_load <= 6662 if (100 * busiest->avg_load <=
6659 env->sd->imbalance_pct * local->avg_load) 6663 env->sd->imbalance_pct * local->avg_load)
6660 goto out_balanced; 6664 goto out_balanced;
6661 } 6665 }
6662 6666
6663 force_balance: 6667 force_balance:
6664 /* Looks like there is an imbalance. Compute it */ 6668 /* Looks like there is an imbalance. Compute it */
6665 calculate_imbalance(env, &sds); 6669 calculate_imbalance(env, &sds);
6666 return sds.busiest; 6670 return sds.busiest;
6667 6671
6668 out_balanced: 6672 out_balanced:
6669 env->imbalance = 0; 6673 env->imbalance = 0;
6670 return NULL; 6674 return NULL;
6671 } 6675 }
6672 6676
6673 /* 6677 /*
6674 * find_busiest_queue - find the busiest runqueue among the cpus in group. 6678 * find_busiest_queue - find the busiest runqueue among the cpus in group.
6675 */ 6679 */
6676 static struct rq *find_busiest_queue(struct lb_env *env, 6680 static struct rq *find_busiest_queue(struct lb_env *env,
6677 struct sched_group *group) 6681 struct sched_group *group)
6678 { 6682 {
6679 struct rq *busiest = NULL, *rq; 6683 struct rq *busiest = NULL, *rq;
6680 unsigned long busiest_load = 0, busiest_capacity = 1; 6684 unsigned long busiest_load = 0, busiest_capacity = 1;
6681 int i; 6685 int i;
6682 6686
6683 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) { 6687 for_each_cpu_and(i, sched_group_cpus(group), env->cpus) {
6684 unsigned long capacity, capacity_factor, wl; 6688 unsigned long capacity, capacity_factor, wl;
6685 enum fbq_type rt; 6689 enum fbq_type rt;
6686 6690
6687 rq = cpu_rq(i); 6691 rq = cpu_rq(i);
6688 rt = fbq_classify_rq(rq); 6692 rt = fbq_classify_rq(rq);
6689 6693
6690 /* 6694 /*
6691 * We classify groups/runqueues into three groups: 6695 * We classify groups/runqueues into three groups:
6692 * - regular: there are !numa tasks 6696 * - regular: there are !numa tasks
6693 * - remote: there are numa tasks that run on the 'wrong' node 6697 * - remote: there are numa tasks that run on the 'wrong' node
6694 * - all: there is no distinction 6698 * - all: there is no distinction
6695 * 6699 *
6696 * In order to avoid migrating ideally placed numa tasks, 6700 * In order to avoid migrating ideally placed numa tasks,
6697 * ignore those when there's better options. 6701 * ignore those when there's better options.
6698 * 6702 *
6699 * If we ignore the actual busiest queue to migrate another 6703 * If we ignore the actual busiest queue to migrate another
6700 * task, the next balance pass can still reduce the busiest 6704 * task, the next balance pass can still reduce the busiest
6701 * queue by moving tasks around inside the node. 6705 * queue by moving tasks around inside the node.
6702 * 6706 *
6703 * If we cannot move enough load due to this classification 6707 * If we cannot move enough load due to this classification
6704 * the next pass will adjust the group classification and 6708 * the next pass will adjust the group classification and
6705 * allow migration of more tasks. 6709 * allow migration of more tasks.
6706 * 6710 *
6707 * Both cases only affect the total convergence complexity. 6711 * Both cases only affect the total convergence complexity.
6708 */ 6712 */
6709 if (rt > env->fbq_type) 6713 if (rt > env->fbq_type)
6710 continue; 6714 continue;
6711 6715
6712 capacity = capacity_of(i); 6716 capacity = capacity_of(i);
6713 capacity_factor = DIV_ROUND_CLOSEST(capacity, SCHED_CAPACITY_SCALE); 6717 capacity_factor = DIV_ROUND_CLOSEST(capacity, SCHED_CAPACITY_SCALE);
6714 if (!capacity_factor) 6718 if (!capacity_factor)
6715 capacity_factor = fix_small_capacity(env->sd, group); 6719 capacity_factor = fix_small_capacity(env->sd, group);
6716 6720
6717 wl = weighted_cpuload(i); 6721 wl = weighted_cpuload(i);
6718 6722
6719 /* 6723 /*
6720 * When comparing with imbalance, use weighted_cpuload() 6724 * When comparing with imbalance, use weighted_cpuload()
6721 * which is not scaled with the cpu capacity. 6725 * which is not scaled with the cpu capacity.
6722 */ 6726 */
6723 if (capacity_factor && rq->nr_running == 1 && wl > env->imbalance) 6727 if (capacity_factor && rq->nr_running == 1 && wl > env->imbalance)
6724 continue; 6728 continue;
6725 6729
6726 /* 6730 /*
6727 * For the load comparisons with the other cpu's, consider 6731 * For the load comparisons with the other cpu's, consider
6728 * the weighted_cpuload() scaled with the cpu capacity, so 6732 * the weighted_cpuload() scaled with the cpu capacity, so
6729 * that the load can be moved away from the cpu that is 6733 * that the load can be moved away from the cpu that is
6730 * potentially running at a lower capacity. 6734 * potentially running at a lower capacity.
6731 * 6735 *
6732 * Thus we're looking for max(wl_i / capacity_i), crosswise 6736 * Thus we're looking for max(wl_i / capacity_i), crosswise
6733 * multiplication to rid ourselves of the division works out 6737 * multiplication to rid ourselves of the division works out
6734 * to: wl_i * capacity_j > wl_j * capacity_i; where j is 6738 * to: wl_i * capacity_j > wl_j * capacity_i; where j is
6735 * our previous maximum. 6739 * our previous maximum.
6736 */ 6740 */
6737 if (wl * busiest_capacity > busiest_load * capacity) { 6741 if (wl * busiest_capacity > busiest_load * capacity) {
6738 busiest_load = wl; 6742 busiest_load = wl;
6739 busiest_capacity = capacity; 6743 busiest_capacity = capacity;
6740 busiest = rq; 6744 busiest = rq;
6741 } 6745 }
6742 } 6746 }
6743 6747
6744 return busiest; 6748 return busiest;
6745 } 6749 }
6746 6750
6747 /* 6751 /*
6748 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but 6752 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
6749 * so long as it is large enough. 6753 * so long as it is large enough.
6750 */ 6754 */
6751 #define MAX_PINNED_INTERVAL 512 6755 #define MAX_PINNED_INTERVAL 512
6752 6756
6753 /* Working cpumask for load_balance and load_balance_newidle. */ 6757 /* Working cpumask for load_balance and load_balance_newidle. */
6754 DEFINE_PER_CPU(cpumask_var_t, load_balance_mask); 6758 DEFINE_PER_CPU(cpumask_var_t, load_balance_mask);
6755 6759
6756 static int need_active_balance(struct lb_env *env) 6760 static int need_active_balance(struct lb_env *env)
6757 { 6761 {
6758 struct sched_domain *sd = env->sd; 6762 struct sched_domain *sd = env->sd;
6759 6763
6760 if (env->idle == CPU_NEWLY_IDLE) { 6764 if (env->idle == CPU_NEWLY_IDLE) {
6761 6765
6762 /* 6766 /*
6763 * ASYM_PACKING needs to force migrate tasks from busy but 6767 * ASYM_PACKING needs to force migrate tasks from busy but
6764 * higher numbered CPUs in order to pack all tasks in the 6768 * higher numbered CPUs in order to pack all tasks in the
6765 * lowest numbered CPUs. 6769 * lowest numbered CPUs.
6766 */ 6770 */
6767 if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu) 6771 if ((sd->flags & SD_ASYM_PACKING) && env->src_cpu > env->dst_cpu)
6768 return 1; 6772 return 1;
6769 } 6773 }
6770 6774
6771 return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2); 6775 return unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2);
6772 } 6776 }
6773 6777
6774 static int active_load_balance_cpu_stop(void *data); 6778 static int active_load_balance_cpu_stop(void *data);
6775 6779
6776 static int should_we_balance(struct lb_env *env) 6780 static int should_we_balance(struct lb_env *env)
6777 { 6781 {
6778 struct sched_group *sg = env->sd->groups; 6782 struct sched_group *sg = env->sd->groups;
6779 struct cpumask *sg_cpus, *sg_mask; 6783 struct cpumask *sg_cpus, *sg_mask;
6780 int cpu, balance_cpu = -1; 6784 int cpu, balance_cpu = -1;
6781 6785
6782 /* 6786 /*
6783 * In the newly idle case, we will allow all the cpu's 6787 * In the newly idle case, we will allow all the cpu's
6784 * to do the newly idle load balance. 6788 * to do the newly idle load balance.
6785 */ 6789 */
6786 if (env->idle == CPU_NEWLY_IDLE) 6790 if (env->idle == CPU_NEWLY_IDLE)
6787 return 1; 6791 return 1;
6788 6792
6789 sg_cpus = sched_group_cpus(sg); 6793 sg_cpus = sched_group_cpus(sg);
6790 sg_mask = sched_group_mask(sg); 6794 sg_mask = sched_group_mask(sg);
6791 /* Try to find first idle cpu */ 6795 /* Try to find first idle cpu */
6792 for_each_cpu_and(cpu, sg_cpus, env->cpus) { 6796 for_each_cpu_and(cpu, sg_cpus, env->cpus) {
6793 if (!cpumask_test_cpu(cpu, sg_mask) || !idle_cpu(cpu)) 6797 if (!cpumask_test_cpu(cpu, sg_mask) || !idle_cpu(cpu))
6794 continue; 6798 continue;
6795 6799
6796 balance_cpu = cpu; 6800 balance_cpu = cpu;
6797 break; 6801 break;
6798 } 6802 }
6799 6803
6800 if (balance_cpu == -1) 6804 if (balance_cpu == -1)
6801 balance_cpu = group_balance_cpu(sg); 6805 balance_cpu = group_balance_cpu(sg);
6802 6806
6803 /* 6807 /*
6804 * First idle cpu or the first cpu(busiest) in this sched group 6808 * First idle cpu or the first cpu(busiest) in this sched group
6805 * is eligible for doing load balancing at this and above domains. 6809 * is eligible for doing load balancing at this and above domains.
6806 */ 6810 */
6807 return balance_cpu == env->dst_cpu; 6811 return balance_cpu == env->dst_cpu;
6808 } 6812 }
6809 6813
6810 /* 6814 /*
6811 * Check this_cpu to ensure it is balanced within domain. Attempt to move 6815 * Check this_cpu to ensure it is balanced within domain. Attempt to move
6812 * tasks if there is an imbalance. 6816 * tasks if there is an imbalance.
6813 */ 6817 */
6814 static int load_balance(int this_cpu, struct rq *this_rq, 6818 static int load_balance(int this_cpu, struct rq *this_rq,
6815 struct sched_domain *sd, enum cpu_idle_type idle, 6819 struct sched_domain *sd, enum cpu_idle_type idle,
6816 int *continue_balancing) 6820 int *continue_balancing)
6817 { 6821 {
6818 int ld_moved, cur_ld_moved, active_balance = 0; 6822 int ld_moved, cur_ld_moved, active_balance = 0;
6819 struct sched_domain *sd_parent = sd->parent; 6823 struct sched_domain *sd_parent = sd->parent;
6820 struct sched_group *group; 6824 struct sched_group *group;
6821 struct rq *busiest; 6825 struct rq *busiest;
6822 unsigned long flags; 6826 unsigned long flags;
6823 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask); 6827 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask);
6824 6828
6825 struct lb_env env = { 6829 struct lb_env env = {
6826 .sd = sd, 6830 .sd = sd,
6827 .dst_cpu = this_cpu, 6831 .dst_cpu = this_cpu,
6828 .dst_rq = this_rq, 6832 .dst_rq = this_rq,
6829 .dst_grpmask = sched_group_cpus(sd->groups), 6833 .dst_grpmask = sched_group_cpus(sd->groups),
6830 .idle = idle, 6834 .idle = idle,
6831 .loop_break = sched_nr_migrate_break, 6835 .loop_break = sched_nr_migrate_break,
6832 .cpus = cpus, 6836 .cpus = cpus,
6833 .fbq_type = all, 6837 .fbq_type = all,
6834 .tasks = LIST_HEAD_INIT(env.tasks), 6838 .tasks = LIST_HEAD_INIT(env.tasks),
6835 }; 6839 };
6836 6840
6837 /* 6841 /*
6838 * For NEWLY_IDLE load_balancing, we don't need to consider 6842 * For NEWLY_IDLE load_balancing, we don't need to consider
6839 * other cpus in our group 6843 * other cpus in our group
6840 */ 6844 */
6841 if (idle == CPU_NEWLY_IDLE) 6845 if (idle == CPU_NEWLY_IDLE)
6842 env.dst_grpmask = NULL; 6846 env.dst_grpmask = NULL;
6843 6847
6844 cpumask_copy(cpus, cpu_active_mask); 6848 cpumask_copy(cpus, cpu_active_mask);
6845 6849
6846 schedstat_inc(sd, lb_count[idle]); 6850 schedstat_inc(sd, lb_count[idle]);
6847 6851
6848 redo: 6852 redo:
6849 if (!should_we_balance(&env)) { 6853 if (!should_we_balance(&env)) {
6850 *continue_balancing = 0; 6854 *continue_balancing = 0;
6851 goto out_balanced; 6855 goto out_balanced;
6852 } 6856 }
6853 6857
6854 group = find_busiest_group(&env); 6858 group = find_busiest_group(&env);
6855 if (!group) { 6859 if (!group) {
6856 schedstat_inc(sd, lb_nobusyg[idle]); 6860 schedstat_inc(sd, lb_nobusyg[idle]);
6857 goto out_balanced; 6861 goto out_balanced;
6858 } 6862 }
6859 6863
6860 busiest = find_busiest_queue(&env, group); 6864 busiest = find_busiest_queue(&env, group);
6861 if (!busiest) { 6865 if (!busiest) {
6862 schedstat_inc(sd, lb_nobusyq[idle]); 6866 schedstat_inc(sd, lb_nobusyq[idle]);
6863 goto out_balanced; 6867 goto out_balanced;
6864 } 6868 }
6865 6869
6866 BUG_ON(busiest == env.dst_rq); 6870 BUG_ON(busiest == env.dst_rq);
6867 6871
6868 schedstat_add(sd, lb_imbalance[idle], env.imbalance); 6872 schedstat_add(sd, lb_imbalance[idle], env.imbalance);
6869 6873
6870 ld_moved = 0; 6874 ld_moved = 0;
6871 if (busiest->nr_running > 1) { 6875 if (busiest->nr_running > 1) {
6872 /* 6876 /*
6873 * Attempt to move tasks. If find_busiest_group has found 6877 * Attempt to move tasks. If find_busiest_group has found
6874 * an imbalance but busiest->nr_running <= 1, the group is 6878 * an imbalance but busiest->nr_running <= 1, the group is
6875 * still unbalanced. ld_moved simply stays zero, so it is 6879 * still unbalanced. ld_moved simply stays zero, so it is
6876 * correctly treated as an imbalance. 6880 * correctly treated as an imbalance.
6877 */ 6881 */
6878 env.flags |= LBF_ALL_PINNED; 6882 env.flags |= LBF_ALL_PINNED;
6879 env.src_cpu = busiest->cpu; 6883 env.src_cpu = busiest->cpu;
6880 env.src_rq = busiest; 6884 env.src_rq = busiest;
6881 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running); 6885 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running);
6882 6886
6883 more_balance: 6887 more_balance:
6884 raw_spin_lock_irqsave(&busiest->lock, flags); 6888 raw_spin_lock_irqsave(&busiest->lock, flags);
6885 6889
6886 /* 6890 /*
6887 * cur_ld_moved - load moved in current iteration 6891 * cur_ld_moved - load moved in current iteration
6888 * ld_moved - cumulative load moved across iterations 6892 * ld_moved - cumulative load moved across iterations
6889 */ 6893 */
6890 cur_ld_moved = detach_tasks(&env); 6894 cur_ld_moved = detach_tasks(&env);
6891 6895
6892 /* 6896 /*
6893 * We've detached some tasks from busiest_rq. Every 6897 * We've detached some tasks from busiest_rq. Every
6894 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely 6898 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely
6895 * unlock busiest->lock, and we are able to be sure 6899 * unlock busiest->lock, and we are able to be sure
6896 * that nobody can manipulate the tasks in parallel. 6900 * that nobody can manipulate the tasks in parallel.
6897 * See task_rq_lock() family for the details. 6901 * See task_rq_lock() family for the details.
6898 */ 6902 */
6899 6903
6900 raw_spin_unlock(&busiest->lock); 6904 raw_spin_unlock(&busiest->lock);
6901 6905
6902 if (cur_ld_moved) { 6906 if (cur_ld_moved) {
6903 attach_tasks(&env); 6907 attach_tasks(&env);
6904 ld_moved += cur_ld_moved; 6908 ld_moved += cur_ld_moved;
6905 } 6909 }
6906 6910
6907 local_irq_restore(flags); 6911 local_irq_restore(flags);
6908 6912
6909 if (env.flags & LBF_NEED_BREAK) { 6913 if (env.flags & LBF_NEED_BREAK) {
6910 env.flags &= ~LBF_NEED_BREAK; 6914 env.flags &= ~LBF_NEED_BREAK;
6911 goto more_balance; 6915 goto more_balance;
6912 } 6916 }
6913 6917
6914 /* 6918 /*
6915 * Revisit (affine) tasks on src_cpu that couldn't be moved to 6919 * Revisit (affine) tasks on src_cpu that couldn't be moved to
6916 * us and move them to an alternate dst_cpu in our sched_group 6920 * us and move them to an alternate dst_cpu in our sched_group
6917 * where they can run. The upper limit on how many times we 6921 * where they can run. The upper limit on how many times we
6918 * iterate on same src_cpu is dependent on number of cpus in our 6922 * iterate on same src_cpu is dependent on number of cpus in our
6919 * sched_group. 6923 * sched_group.
6920 * 6924 *
6921 * This changes load balance semantics a bit on who can move 6925 * This changes load balance semantics a bit on who can move
6922 * load to a given_cpu. In addition to the given_cpu itself 6926 * load to a given_cpu. In addition to the given_cpu itself
6923 * (or a ilb_cpu acting on its behalf where given_cpu is 6927 * (or a ilb_cpu acting on its behalf where given_cpu is
6924 * nohz-idle), we now have balance_cpu in a position to move 6928 * nohz-idle), we now have balance_cpu in a position to move
6925 * load to given_cpu. In rare situations, this may cause 6929 * load to given_cpu. In rare situations, this may cause
6926 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding 6930 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding
6927 * _independently_ and at _same_ time to move some load to 6931 * _independently_ and at _same_ time to move some load to
6928 * given_cpu) causing exceess load to be moved to given_cpu. 6932 * given_cpu) causing exceess load to be moved to given_cpu.
6929 * This however should not happen so much in practice and 6933 * This however should not happen so much in practice and
6930 * moreover subsequent load balance cycles should correct the 6934 * moreover subsequent load balance cycles should correct the
6931 * excess load moved. 6935 * excess load moved.
6932 */ 6936 */
6933 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) { 6937 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) {
6934 6938
6935 /* Prevent to re-select dst_cpu via env's cpus */ 6939 /* Prevent to re-select dst_cpu via env's cpus */
6936 cpumask_clear_cpu(env.dst_cpu, env.cpus); 6940 cpumask_clear_cpu(env.dst_cpu, env.cpus);
6937 6941
6938 env.dst_rq = cpu_rq(env.new_dst_cpu); 6942 env.dst_rq = cpu_rq(env.new_dst_cpu);
6939 env.dst_cpu = env.new_dst_cpu; 6943 env.dst_cpu = env.new_dst_cpu;
6940 env.flags &= ~LBF_DST_PINNED; 6944 env.flags &= ~LBF_DST_PINNED;
6941 env.loop = 0; 6945 env.loop = 0;
6942 env.loop_break = sched_nr_migrate_break; 6946 env.loop_break = sched_nr_migrate_break;
6943 6947
6944 /* 6948 /*
6945 * Go back to "more_balance" rather than "redo" since we 6949 * Go back to "more_balance" rather than "redo" since we
6946 * need to continue with same src_cpu. 6950 * need to continue with same src_cpu.
6947 */ 6951 */
6948 goto more_balance; 6952 goto more_balance;
6949 } 6953 }
6950 6954
6951 /* 6955 /*
6952 * We failed to reach balance because of affinity. 6956 * We failed to reach balance because of affinity.
6953 */ 6957 */
6954 if (sd_parent) { 6958 if (sd_parent) {
6955 int *group_imbalance = &sd_parent->groups->sgc->imbalance; 6959 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
6956 6960
6957 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0) 6961 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0)
6958 *group_imbalance = 1; 6962 *group_imbalance = 1;
6959 } 6963 }
6960 6964
6961 /* All tasks on this runqueue were pinned by CPU affinity */ 6965 /* All tasks on this runqueue were pinned by CPU affinity */
6962 if (unlikely(env.flags & LBF_ALL_PINNED)) { 6966 if (unlikely(env.flags & LBF_ALL_PINNED)) {
6963 cpumask_clear_cpu(cpu_of(busiest), cpus); 6967 cpumask_clear_cpu(cpu_of(busiest), cpus);
6964 if (!cpumask_empty(cpus)) { 6968 if (!cpumask_empty(cpus)) {
6965 env.loop = 0; 6969 env.loop = 0;
6966 env.loop_break = sched_nr_migrate_break; 6970 env.loop_break = sched_nr_migrate_break;
6967 goto redo; 6971 goto redo;
6968 } 6972 }
6969 goto out_all_pinned; 6973 goto out_all_pinned;
6970 } 6974 }
6971 } 6975 }
6972 6976
6973 if (!ld_moved) { 6977 if (!ld_moved) {
6974 schedstat_inc(sd, lb_failed[idle]); 6978 schedstat_inc(sd, lb_failed[idle]);
6975 /* 6979 /*
6976 * Increment the failure counter only on periodic balance. 6980 * Increment the failure counter only on periodic balance.
6977 * We do not want newidle balance, which can be very 6981 * We do not want newidle balance, which can be very
6978 * frequent, pollute the failure counter causing 6982 * frequent, pollute the failure counter causing
6979 * excessive cache_hot migrations and active balances. 6983 * excessive cache_hot migrations and active balances.
6980 */ 6984 */
6981 if (idle != CPU_NEWLY_IDLE) 6985 if (idle != CPU_NEWLY_IDLE)
6982 sd->nr_balance_failed++; 6986 sd->nr_balance_failed++;
6983 6987
6984 if (need_active_balance(&env)) { 6988 if (need_active_balance(&env)) {
6985 raw_spin_lock_irqsave(&busiest->lock, flags); 6989 raw_spin_lock_irqsave(&busiest->lock, flags);
6986 6990
6987 /* don't kick the active_load_balance_cpu_stop, 6991 /* don't kick the active_load_balance_cpu_stop,
6988 * if the curr task on busiest cpu can't be 6992 * if the curr task on busiest cpu can't be
6989 * moved to this_cpu 6993 * moved to this_cpu
6990 */ 6994 */
6991 if (!cpumask_test_cpu(this_cpu, 6995 if (!cpumask_test_cpu(this_cpu,
6992 tsk_cpus_allowed(busiest->curr))) { 6996 tsk_cpus_allowed(busiest->curr))) {
6993 raw_spin_unlock_irqrestore(&busiest->lock, 6997 raw_spin_unlock_irqrestore(&busiest->lock,
6994 flags); 6998 flags);
6995 env.flags |= LBF_ALL_PINNED; 6999 env.flags |= LBF_ALL_PINNED;
6996 goto out_one_pinned; 7000 goto out_one_pinned;
6997 } 7001 }
6998 7002
6999 /* 7003 /*
7000 * ->active_balance synchronizes accesses to 7004 * ->active_balance synchronizes accesses to
7001 * ->active_balance_work. Once set, it's cleared 7005 * ->active_balance_work. Once set, it's cleared
7002 * only after active load balance is finished. 7006 * only after active load balance is finished.
7003 */ 7007 */
7004 if (!busiest->active_balance) { 7008 if (!busiest->active_balance) {
7005 busiest->active_balance = 1; 7009 busiest->active_balance = 1;
7006 busiest->push_cpu = this_cpu; 7010 busiest->push_cpu = this_cpu;
7007 active_balance = 1; 7011 active_balance = 1;
7008 } 7012 }
7009 raw_spin_unlock_irqrestore(&busiest->lock, flags); 7013 raw_spin_unlock_irqrestore(&busiest->lock, flags);
7010 7014
7011 if (active_balance) { 7015 if (active_balance) {
7012 stop_one_cpu_nowait(cpu_of(busiest), 7016 stop_one_cpu_nowait(cpu_of(busiest),
7013 active_load_balance_cpu_stop, busiest, 7017 active_load_balance_cpu_stop, busiest,
7014 &busiest->active_balance_work); 7018 &busiest->active_balance_work);
7015 } 7019 }
7016 7020
7017 /* 7021 /*
7018 * We've kicked active balancing, reset the failure 7022 * We've kicked active balancing, reset the failure
7019 * counter. 7023 * counter.
7020 */ 7024 */
7021 sd->nr_balance_failed = sd->cache_nice_tries+1; 7025 sd->nr_balance_failed = sd->cache_nice_tries+1;
7022 } 7026 }
7023 } else 7027 } else
7024 sd->nr_balance_failed = 0; 7028 sd->nr_balance_failed = 0;
7025 7029
7026 if (likely(!active_balance)) { 7030 if (likely(!active_balance)) {
7027 /* We were unbalanced, so reset the balancing interval */ 7031 /* We were unbalanced, so reset the balancing interval */
7028 sd->balance_interval = sd->min_interval; 7032 sd->balance_interval = sd->min_interval;
7029 } else { 7033 } else {
7030 /* 7034 /*
7031 * If we've begun active balancing, start to back off. This 7035 * If we've begun active balancing, start to back off. This
7032 * case may not be covered by the all_pinned logic if there 7036 * case may not be covered by the all_pinned logic if there
7033 * is only 1 task on the busy runqueue (because we don't call 7037 * is only 1 task on the busy runqueue (because we don't call
7034 * detach_tasks). 7038 * detach_tasks).
7035 */ 7039 */
7036 if (sd->balance_interval < sd->max_interval) 7040 if (sd->balance_interval < sd->max_interval)
7037 sd->balance_interval *= 2; 7041 sd->balance_interval *= 2;
7038 } 7042 }
7039 7043
7040 goto out; 7044 goto out;
7041 7045
7042 out_balanced: 7046 out_balanced:
7043 /* 7047 /*
7044 * We reach balance although we may have faced some affinity 7048 * We reach balance although we may have faced some affinity
7045 * constraints. Clear the imbalance flag if it was set. 7049 * constraints. Clear the imbalance flag if it was set.
7046 */ 7050 */
7047 if (sd_parent) { 7051 if (sd_parent) {
7048 int *group_imbalance = &sd_parent->groups->sgc->imbalance; 7052 int *group_imbalance = &sd_parent->groups->sgc->imbalance;
7049 7053
7050 if (*group_imbalance) 7054 if (*group_imbalance)
7051 *group_imbalance = 0; 7055 *group_imbalance = 0;
7052 } 7056 }
7053 7057
7054 out_all_pinned: 7058 out_all_pinned:
7055 /* 7059 /*
7056 * We reach balance because all tasks are pinned at this level so 7060 * We reach balance because all tasks are pinned at this level so
7057 * we can't migrate them. Let the imbalance flag set so parent level 7061 * we can't migrate them. Let the imbalance flag set so parent level
7058 * can try to migrate them. 7062 * can try to migrate them.
7059 */ 7063 */
7060 schedstat_inc(sd, lb_balanced[idle]); 7064 schedstat_inc(sd, lb_balanced[idle]);
7061 7065
7062 sd->nr_balance_failed = 0; 7066 sd->nr_balance_failed = 0;
7063 7067
7064 out_one_pinned: 7068 out_one_pinned:
7065 /* tune up the balancing interval */ 7069 /* tune up the balancing interval */
7066 if (((env.flags & LBF_ALL_PINNED) && 7070 if (((env.flags & LBF_ALL_PINNED) &&
7067 sd->balance_interval < MAX_PINNED_INTERVAL) || 7071 sd->balance_interval < MAX_PINNED_INTERVAL) ||
7068 (sd->balance_interval < sd->max_interval)) 7072 (sd->balance_interval < sd->max_interval))
7069 sd->balance_interval *= 2; 7073 sd->balance_interval *= 2;
7070 7074
7071 ld_moved = 0; 7075 ld_moved = 0;
7072 out: 7076 out:
7073 return ld_moved; 7077 return ld_moved;
7074 } 7078 }
7075 7079
7076 static inline unsigned long 7080 static inline unsigned long
7077 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy) 7081 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy)
7078 { 7082 {
7079 unsigned long interval = sd->balance_interval; 7083 unsigned long interval = sd->balance_interval;
7080 7084
7081 if (cpu_busy) 7085 if (cpu_busy)
7082 interval *= sd->busy_factor; 7086 interval *= sd->busy_factor;
7083 7087
7084 /* scale ms to jiffies */ 7088 /* scale ms to jiffies */
7085 interval = msecs_to_jiffies(interval); 7089 interval = msecs_to_jiffies(interval);
7086 interval = clamp(interval, 1UL, max_load_balance_interval); 7090 interval = clamp(interval, 1UL, max_load_balance_interval);
7087 7091
7088 return interval; 7092 return interval;
7089 } 7093 }
7090 7094
7091 static inline void 7095 static inline void
7092 update_next_balance(struct sched_domain *sd, int cpu_busy, unsigned long *next_balance) 7096 update_next_balance(struct sched_domain *sd, int cpu_busy, unsigned long *next_balance)
7093 { 7097 {
7094 unsigned long interval, next; 7098 unsigned long interval, next;
7095 7099
7096 interval = get_sd_balance_interval(sd, cpu_busy); 7100 interval = get_sd_balance_interval(sd, cpu_busy);
7097 next = sd->last_balance + interval; 7101 next = sd->last_balance + interval;
7098 7102
7099 if (time_after(*next_balance, next)) 7103 if (time_after(*next_balance, next))
7100 *next_balance = next; 7104 *next_balance = next;
7101 } 7105 }
7102 7106
7103 /* 7107 /*
7104 * idle_balance is called by schedule() if this_cpu is about to become 7108 * idle_balance is called by schedule() if this_cpu is about to become
7105 * idle. Attempts to pull tasks from other CPUs. 7109 * idle. Attempts to pull tasks from other CPUs.
7106 */ 7110 */
7107 static int idle_balance(struct rq *this_rq) 7111 static int idle_balance(struct rq *this_rq)
7108 { 7112 {
7109 unsigned long next_balance = jiffies + HZ; 7113 unsigned long next_balance = jiffies + HZ;
7110 int this_cpu = this_rq->cpu; 7114 int this_cpu = this_rq->cpu;
7111 struct sched_domain *sd; 7115 struct sched_domain *sd;
7112 int pulled_task = 0; 7116 int pulled_task = 0;
7113 u64 curr_cost = 0; 7117 u64 curr_cost = 0;
7114 7118
7115 idle_enter_fair(this_rq); 7119 idle_enter_fair(this_rq);
7116 7120
7117 /* 7121 /*
7118 * We must set idle_stamp _before_ calling idle_balance(), such that we 7122 * We must set idle_stamp _before_ calling idle_balance(), such that we
7119 * measure the duration of idle_balance() as idle time. 7123 * measure the duration of idle_balance() as idle time.
7120 */ 7124 */
7121 this_rq->idle_stamp = rq_clock(this_rq); 7125 this_rq->idle_stamp = rq_clock(this_rq);
7122 7126
7123 if (this_rq->avg_idle < sysctl_sched_migration_cost || 7127 if (this_rq->avg_idle < sysctl_sched_migration_cost ||
7124 !this_rq->rd->overload) { 7128 !this_rq->rd->overload) {
7125 rcu_read_lock(); 7129 rcu_read_lock();
7126 sd = rcu_dereference_check_sched_domain(this_rq->sd); 7130 sd = rcu_dereference_check_sched_domain(this_rq->sd);
7127 if (sd) 7131 if (sd)
7128 update_next_balance(sd, 0, &next_balance); 7132 update_next_balance(sd, 0, &next_balance);
7129 rcu_read_unlock(); 7133 rcu_read_unlock();
7130 7134
7131 goto out; 7135 goto out;
7132 } 7136 }
7133 7137
7134 /* 7138 /*
7135 * Drop the rq->lock, but keep IRQ/preempt disabled. 7139 * Drop the rq->lock, but keep IRQ/preempt disabled.
7136 */ 7140 */
7137 raw_spin_unlock(&this_rq->lock); 7141 raw_spin_unlock(&this_rq->lock);
7138 7142
7139 update_blocked_averages(this_cpu); 7143 update_blocked_averages(this_cpu);
7140 rcu_read_lock(); 7144 rcu_read_lock();
7141 for_each_domain(this_cpu, sd) { 7145 for_each_domain(this_cpu, sd) {
7142 int continue_balancing = 1; 7146 int continue_balancing = 1;
7143 u64 t0, domain_cost; 7147 u64 t0, domain_cost;
7144 7148
7145 if (!(sd->flags & SD_LOAD_BALANCE)) 7149 if (!(sd->flags & SD_LOAD_BALANCE))
7146 continue; 7150 continue;
7147 7151
7148 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) { 7152 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) {
7149 update_next_balance(sd, 0, &next_balance); 7153 update_next_balance(sd, 0, &next_balance);
7150 break; 7154 break;
7151 } 7155 }
7152 7156
7153 if (sd->flags & SD_BALANCE_NEWIDLE) { 7157 if (sd->flags & SD_BALANCE_NEWIDLE) {
7154 t0 = sched_clock_cpu(this_cpu); 7158 t0 = sched_clock_cpu(this_cpu);
7155 7159
7156 pulled_task = load_balance(this_cpu, this_rq, 7160 pulled_task = load_balance(this_cpu, this_rq,
7157 sd, CPU_NEWLY_IDLE, 7161 sd, CPU_NEWLY_IDLE,
7158 &continue_balancing); 7162 &continue_balancing);
7159 7163
7160 domain_cost = sched_clock_cpu(this_cpu) - t0; 7164 domain_cost = sched_clock_cpu(this_cpu) - t0;
7161 if (domain_cost > sd->max_newidle_lb_cost) 7165 if (domain_cost > sd->max_newidle_lb_cost)
7162 sd->max_newidle_lb_cost = domain_cost; 7166 sd->max_newidle_lb_cost = domain_cost;
7163 7167
7164 curr_cost += domain_cost; 7168 curr_cost += domain_cost;
7165 } 7169 }
7166 7170
7167 update_next_balance(sd, 0, &next_balance); 7171 update_next_balance(sd, 0, &next_balance);
7168 7172
7169 /* 7173 /*
7170 * Stop searching for tasks to pull if there are 7174 * Stop searching for tasks to pull if there are
7171 * now runnable tasks on this rq. 7175 * now runnable tasks on this rq.
7172 */ 7176 */
7173 if (pulled_task || this_rq->nr_running > 0) 7177 if (pulled_task || this_rq->nr_running > 0)
7174 break; 7178 break;
7175 } 7179 }
7176 rcu_read_unlock(); 7180 rcu_read_unlock();
7177 7181
7178 raw_spin_lock(&this_rq->lock); 7182 raw_spin_lock(&this_rq->lock);
7179 7183
7180 if (curr_cost > this_rq->max_idle_balance_cost) 7184 if (curr_cost > this_rq->max_idle_balance_cost)
7181 this_rq->max_idle_balance_cost = curr_cost; 7185 this_rq->max_idle_balance_cost = curr_cost;
7182 7186
7183 /* 7187 /*
7184 * While browsing the domains, we released the rq lock, a task could 7188 * While browsing the domains, we released the rq lock, a task could
7185 * have been enqueued in the meantime. Since we're not going idle, 7189 * have been enqueued in the meantime. Since we're not going idle,
7186 * pretend we pulled a task. 7190 * pretend we pulled a task.
7187 */ 7191 */
7188 if (this_rq->cfs.h_nr_running && !pulled_task) 7192 if (this_rq->cfs.h_nr_running && !pulled_task)
7189 pulled_task = 1; 7193 pulled_task = 1;
7190 7194
7191 out: 7195 out:
7192 /* Move the next balance forward */ 7196 /* Move the next balance forward */
7193 if (time_after(this_rq->next_balance, next_balance)) 7197 if (time_after(this_rq->next_balance, next_balance))
7194 this_rq->next_balance = next_balance; 7198 this_rq->next_balance = next_balance;
7195 7199
7196 /* Is there a task of a high priority class? */ 7200 /* Is there a task of a high priority class? */
7197 if (this_rq->nr_running != this_rq->cfs.h_nr_running) 7201 if (this_rq->nr_running != this_rq->cfs.h_nr_running)
7198 pulled_task = -1; 7202 pulled_task = -1;
7199 7203
7200 if (pulled_task) { 7204 if (pulled_task) {
7201 idle_exit_fair(this_rq); 7205 idle_exit_fair(this_rq);
7202 this_rq->idle_stamp = 0; 7206 this_rq->idle_stamp = 0;
7203 } 7207 }
7204 7208
7205 return pulled_task; 7209 return pulled_task;
7206 } 7210 }
7207 7211
7208 /* 7212 /*
7209 * active_load_balance_cpu_stop is run by cpu stopper. It pushes 7213 * active_load_balance_cpu_stop is run by cpu stopper. It pushes
7210 * running tasks off the busiest CPU onto idle CPUs. It requires at 7214 * running tasks off the busiest CPU onto idle CPUs. It requires at
7211 * least 1 task to be running on each physical CPU where possible, and 7215 * least 1 task to be running on each physical CPU where possible, and
7212 * avoids physical / logical imbalances. 7216 * avoids physical / logical imbalances.
7213 */ 7217 */
7214 static int active_load_balance_cpu_stop(void *data) 7218 static int active_load_balance_cpu_stop(void *data)
7215 { 7219 {
7216 struct rq *busiest_rq = data; 7220 struct rq *busiest_rq = data;
7217 int busiest_cpu = cpu_of(busiest_rq); 7221 int busiest_cpu = cpu_of(busiest_rq);
7218 int target_cpu = busiest_rq->push_cpu; 7222 int target_cpu = busiest_rq->push_cpu;
7219 struct rq *target_rq = cpu_rq(target_cpu); 7223 struct rq *target_rq = cpu_rq(target_cpu);
7220 struct sched_domain *sd; 7224 struct sched_domain *sd;
7221 struct task_struct *p = NULL; 7225 struct task_struct *p = NULL;
7222 7226
7223 raw_spin_lock_irq(&busiest_rq->lock); 7227 raw_spin_lock_irq(&busiest_rq->lock);
7224 7228
7225 /* make sure the requested cpu hasn't gone down in the meantime */ 7229 /* make sure the requested cpu hasn't gone down in the meantime */
7226 if (unlikely(busiest_cpu != smp_processor_id() || 7230 if (unlikely(busiest_cpu != smp_processor_id() ||
7227 !busiest_rq->active_balance)) 7231 !busiest_rq->active_balance))
7228 goto out_unlock; 7232 goto out_unlock;
7229 7233
7230 /* Is there any task to move? */ 7234 /* Is there any task to move? */
7231 if (busiest_rq->nr_running <= 1) 7235 if (busiest_rq->nr_running <= 1)
7232 goto out_unlock; 7236 goto out_unlock;
7233 7237
7234 /* 7238 /*
7235 * This condition is "impossible", if it occurs 7239 * This condition is "impossible", if it occurs
7236 * we need to fix it. Originally reported by 7240 * we need to fix it. Originally reported by
7237 * Bjorn Helgaas on a 128-cpu setup. 7241 * Bjorn Helgaas on a 128-cpu setup.
7238 */ 7242 */
7239 BUG_ON(busiest_rq == target_rq); 7243 BUG_ON(busiest_rq == target_rq);
7240 7244
7241 /* Search for an sd spanning us and the target CPU. */ 7245 /* Search for an sd spanning us and the target CPU. */
7242 rcu_read_lock(); 7246 rcu_read_lock();
7243 for_each_domain(target_cpu, sd) { 7247 for_each_domain(target_cpu, sd) {
7244 if ((sd->flags & SD_LOAD_BALANCE) && 7248 if ((sd->flags & SD_LOAD_BALANCE) &&
7245 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd))) 7249 cpumask_test_cpu(busiest_cpu, sched_domain_span(sd)))
7246 break; 7250 break;
7247 } 7251 }
7248 7252
7249 if (likely(sd)) { 7253 if (likely(sd)) {
7250 struct lb_env env = { 7254 struct lb_env env = {
7251 .sd = sd, 7255 .sd = sd,
7252 .dst_cpu = target_cpu, 7256 .dst_cpu = target_cpu,
7253 .dst_rq = target_rq, 7257 .dst_rq = target_rq,
7254 .src_cpu = busiest_rq->cpu, 7258 .src_cpu = busiest_rq->cpu,
7255 .src_rq = busiest_rq, 7259 .src_rq = busiest_rq,
7256 .idle = CPU_IDLE, 7260 .idle = CPU_IDLE,
7257 }; 7261 };
7258 7262
7259 schedstat_inc(sd, alb_count); 7263 schedstat_inc(sd, alb_count);
7260 7264
7261 p = detach_one_task(&env); 7265 p = detach_one_task(&env);
7262 if (p) 7266 if (p)
7263 schedstat_inc(sd, alb_pushed); 7267 schedstat_inc(sd, alb_pushed);
7264 else 7268 else
7265 schedstat_inc(sd, alb_failed); 7269 schedstat_inc(sd, alb_failed);
7266 } 7270 }
7267 rcu_read_unlock(); 7271 rcu_read_unlock();
7268 out_unlock: 7272 out_unlock:
7269 busiest_rq->active_balance = 0; 7273 busiest_rq->active_balance = 0;
7270 raw_spin_unlock(&busiest_rq->lock); 7274 raw_spin_unlock(&busiest_rq->lock);
7271 7275
7272 if (p) 7276 if (p)
7273 attach_one_task(target_rq, p); 7277 attach_one_task(target_rq, p);
7274 7278
7275 local_irq_enable(); 7279 local_irq_enable();
7276 7280
7277 return 0; 7281 return 0;
7278 } 7282 }
7279 7283
7280 static inline int on_null_domain(struct rq *rq) 7284 static inline int on_null_domain(struct rq *rq)
7281 { 7285 {
7282 return unlikely(!rcu_dereference_sched(rq->sd)); 7286 return unlikely(!rcu_dereference_sched(rq->sd));
7283 } 7287 }
7284 7288
7285 #ifdef CONFIG_NO_HZ_COMMON 7289 #ifdef CONFIG_NO_HZ_COMMON
7286 /* 7290 /*
7287 * idle load balancing details 7291 * idle load balancing details
7288 * - When one of the busy CPUs notice that there may be an idle rebalancing 7292 * - When one of the busy CPUs notice that there may be an idle rebalancing
7289 * needed, they will kick the idle load balancer, which then does idle 7293 * needed, they will kick the idle load balancer, which then does idle
7290 * load balancing for all the idle CPUs. 7294 * load balancing for all the idle CPUs.
7291 */ 7295 */
7292 static struct { 7296 static struct {
7293 cpumask_var_t idle_cpus_mask; 7297 cpumask_var_t idle_cpus_mask;
7294 atomic_t nr_cpus; 7298 atomic_t nr_cpus;
7295 unsigned long next_balance; /* in jiffy units */ 7299 unsigned long next_balance; /* in jiffy units */
7296 } nohz ____cacheline_aligned; 7300 } nohz ____cacheline_aligned;
7297 7301
7298 static inline int find_new_ilb(void) 7302 static inline int find_new_ilb(void)
7299 { 7303 {
7300 int ilb = cpumask_first(nohz.idle_cpus_mask); 7304 int ilb = cpumask_first(nohz.idle_cpus_mask);
7301 7305
7302 if (ilb < nr_cpu_ids && idle_cpu(ilb)) 7306 if (ilb < nr_cpu_ids && idle_cpu(ilb))
7303 return ilb; 7307 return ilb;
7304 7308
7305 return nr_cpu_ids; 7309 return nr_cpu_ids;
7306 } 7310 }
7307 7311
7308 /* 7312 /*
7309 * Kick a CPU to do the nohz balancing, if it is time for it. We pick the 7313 * Kick a CPU to do the nohz balancing, if it is time for it. We pick the
7310 * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle 7314 * nohz_load_balancer CPU (if there is one) otherwise fallback to any idle
7311 * CPU (if there is one). 7315 * CPU (if there is one).
7312 */ 7316 */
7313 static void nohz_balancer_kick(void) 7317 static void nohz_balancer_kick(void)
7314 { 7318 {
7315 int ilb_cpu; 7319 int ilb_cpu;
7316 7320
7317 nohz.next_balance++; 7321 nohz.next_balance++;
7318 7322
7319 ilb_cpu = find_new_ilb(); 7323 ilb_cpu = find_new_ilb();
7320 7324
7321 if (ilb_cpu >= nr_cpu_ids) 7325 if (ilb_cpu >= nr_cpu_ids)
7322 return; 7326 return;
7323 7327
7324 if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu))) 7328 if (test_and_set_bit(NOHZ_BALANCE_KICK, nohz_flags(ilb_cpu)))
7325 return; 7329 return;
7326 /* 7330 /*
7327 * Use smp_send_reschedule() instead of resched_cpu(). 7331 * Use smp_send_reschedule() instead of resched_cpu().
7328 * This way we generate a sched IPI on the target cpu which 7332 * This way we generate a sched IPI on the target cpu which
7329 * is idle. And the softirq performing nohz idle load balance 7333 * is idle. And the softirq performing nohz idle load balance
7330 * will be run before returning from the IPI. 7334 * will be run before returning from the IPI.
7331 */ 7335 */
7332 smp_send_reschedule(ilb_cpu); 7336 smp_send_reschedule(ilb_cpu);
7333 return; 7337 return;
7334 } 7338 }
7335 7339
7336 static inline void nohz_balance_exit_idle(int cpu) 7340 static inline void nohz_balance_exit_idle(int cpu)
7337 { 7341 {
7338 if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) { 7342 if (unlikely(test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))) {
7339 /* 7343 /*
7340 * Completely isolated CPUs don't ever set, so we must test. 7344 * Completely isolated CPUs don't ever set, so we must test.
7341 */ 7345 */
7342 if (likely(cpumask_test_cpu(cpu, nohz.idle_cpus_mask))) { 7346 if (likely(cpumask_test_cpu(cpu, nohz.idle_cpus_mask))) {
7343 cpumask_clear_cpu(cpu, nohz.idle_cpus_mask); 7347 cpumask_clear_cpu(cpu, nohz.idle_cpus_mask);
7344 atomic_dec(&nohz.nr_cpus); 7348 atomic_dec(&nohz.nr_cpus);
7345 } 7349 }
7346 clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)); 7350 clear_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
7347 } 7351 }
7348 } 7352 }
7349 7353
7350 static inline void set_cpu_sd_state_busy(void) 7354 static inline void set_cpu_sd_state_busy(void)
7351 { 7355 {
7352 struct sched_domain *sd; 7356 struct sched_domain *sd;
7353 int cpu = smp_processor_id(); 7357 int cpu = smp_processor_id();
7354 7358
7355 rcu_read_lock(); 7359 rcu_read_lock();
7356 sd = rcu_dereference(per_cpu(sd_busy, cpu)); 7360 sd = rcu_dereference(per_cpu(sd_busy, cpu));
7357 7361
7358 if (!sd || !sd->nohz_idle) 7362 if (!sd || !sd->nohz_idle)
7359 goto unlock; 7363 goto unlock;
7360 sd->nohz_idle = 0; 7364 sd->nohz_idle = 0;
7361 7365
7362 atomic_inc(&sd->groups->sgc->nr_busy_cpus); 7366 atomic_inc(&sd->groups->sgc->nr_busy_cpus);
7363 unlock: 7367 unlock:
7364 rcu_read_unlock(); 7368 rcu_read_unlock();
7365 } 7369 }
7366 7370
7367 void set_cpu_sd_state_idle(void) 7371 void set_cpu_sd_state_idle(void)
7368 { 7372 {
7369 struct sched_domain *sd; 7373 struct sched_domain *sd;
7370 int cpu = smp_processor_id(); 7374 int cpu = smp_processor_id();
7371 7375
7372 rcu_read_lock(); 7376 rcu_read_lock();
7373 sd = rcu_dereference(per_cpu(sd_busy, cpu)); 7377 sd = rcu_dereference(per_cpu(sd_busy, cpu));
7374 7378
7375 if (!sd || sd->nohz_idle) 7379 if (!sd || sd->nohz_idle)
7376 goto unlock; 7380 goto unlock;
7377 sd->nohz_idle = 1; 7381 sd->nohz_idle = 1;
7378 7382
7379 atomic_dec(&sd->groups->sgc->nr_busy_cpus); 7383 atomic_dec(&sd->groups->sgc->nr_busy_cpus);
7380 unlock: 7384 unlock:
7381 rcu_read_unlock(); 7385 rcu_read_unlock();
7382 } 7386 }
7383 7387
7384 /* 7388 /*
7385 * This routine will record that the cpu is going idle with tick stopped. 7389 * This routine will record that the cpu is going idle with tick stopped.
7386 * This info will be used in performing idle load balancing in the future. 7390 * This info will be used in performing idle load balancing in the future.
7387 */ 7391 */
7388 void nohz_balance_enter_idle(int cpu) 7392 void nohz_balance_enter_idle(int cpu)
7389 { 7393 {
7390 /* 7394 /*
7391 * If this cpu is going down, then nothing needs to be done. 7395 * If this cpu is going down, then nothing needs to be done.
7392 */ 7396 */
7393 if (!cpu_active(cpu)) 7397 if (!cpu_active(cpu))
7394 return; 7398 return;
7395 7399
7396 if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu))) 7400 if (test_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)))
7397 return; 7401 return;
7398 7402
7399 /* 7403 /*
7400 * If we're a completely isolated CPU, we don't play. 7404 * If we're a completely isolated CPU, we don't play.
7401 */ 7405 */
7402 if (on_null_domain(cpu_rq(cpu))) 7406 if (on_null_domain(cpu_rq(cpu)))
7403 return; 7407 return;
7404 7408
7405 cpumask_set_cpu(cpu, nohz.idle_cpus_mask); 7409 cpumask_set_cpu(cpu, nohz.idle_cpus_mask);
7406 atomic_inc(&nohz.nr_cpus); 7410 atomic_inc(&nohz.nr_cpus);
7407 set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu)); 7411 set_bit(NOHZ_TICK_STOPPED, nohz_flags(cpu));
7408 } 7412 }
7409 7413
7410 static int sched_ilb_notifier(struct notifier_block *nfb, 7414 static int sched_ilb_notifier(struct notifier_block *nfb,
7411 unsigned long action, void *hcpu) 7415 unsigned long action, void *hcpu)
7412 { 7416 {
7413 switch (action & ~CPU_TASKS_FROZEN) { 7417 switch (action & ~CPU_TASKS_FROZEN) {
7414 case CPU_DYING: 7418 case CPU_DYING:
7415 nohz_balance_exit_idle(smp_processor_id()); 7419 nohz_balance_exit_idle(smp_processor_id());
7416 return NOTIFY_OK; 7420 return NOTIFY_OK;
7417 default: 7421 default:
7418 return NOTIFY_DONE; 7422 return NOTIFY_DONE;
7419 } 7423 }
7420 } 7424 }
7421 #endif 7425 #endif
7422 7426
7423 static DEFINE_SPINLOCK(balancing); 7427 static DEFINE_SPINLOCK(balancing);
7424 7428
7425 /* 7429 /*
7426 * Scale the max load_balance interval with the number of CPUs in the system. 7430 * Scale the max load_balance interval with the number of CPUs in the system.
7427 * This trades load-balance latency on larger machines for less cross talk. 7431 * This trades load-balance latency on larger machines for less cross talk.
7428 */ 7432 */
7429 void update_max_interval(void) 7433 void update_max_interval(void)
7430 { 7434 {
7431 max_load_balance_interval = HZ*num_online_cpus()/10; 7435 max_load_balance_interval = HZ*num_online_cpus()/10;
7432 } 7436 }
7433 7437
7434 /* 7438 /*
7435 * It checks each scheduling domain to see if it is due to be balanced, 7439 * It checks each scheduling domain to see if it is due to be balanced,
7436 * and initiates a balancing operation if so. 7440 * and initiates a balancing operation if so.
7437 * 7441 *
7438 * Balancing parameters are set up in init_sched_domains. 7442 * Balancing parameters are set up in init_sched_domains.
7439 */ 7443 */
7440 static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle) 7444 static void rebalance_domains(struct rq *rq, enum cpu_idle_type idle)
7441 { 7445 {
7442 int continue_balancing = 1; 7446 int continue_balancing = 1;
7443 int cpu = rq->cpu; 7447 int cpu = rq->cpu;
7444 unsigned long interval; 7448 unsigned long interval;
7445 struct sched_domain *sd; 7449 struct sched_domain *sd;
7446 /* Earliest time when we have to do rebalance again */ 7450 /* Earliest time when we have to do rebalance again */
7447 unsigned long next_balance = jiffies + 60*HZ; 7451 unsigned long next_balance = jiffies + 60*HZ;
7448 int update_next_balance = 0; 7452 int update_next_balance = 0;
7449 int need_serialize, need_decay = 0; 7453 int need_serialize, need_decay = 0;
7450 u64 max_cost = 0; 7454 u64 max_cost = 0;
7451 7455
7452 update_blocked_averages(cpu); 7456 update_blocked_averages(cpu);
7453 7457
7454 rcu_read_lock(); 7458 rcu_read_lock();
7455 for_each_domain(cpu, sd) { 7459 for_each_domain(cpu, sd) {
7456 /* 7460 /*
7457 * Decay the newidle max times here because this is a regular 7461 * Decay the newidle max times here because this is a regular
7458 * visit to all the domains. Decay ~1% per second. 7462 * visit to all the domains. Decay ~1% per second.
7459 */ 7463 */
7460 if (time_after(jiffies, sd->next_decay_max_lb_cost)) { 7464 if (time_after(jiffies, sd->next_decay_max_lb_cost)) {
7461 sd->max_newidle_lb_cost = 7465 sd->max_newidle_lb_cost =
7462 (sd->max_newidle_lb_cost * 253) / 256; 7466 (sd->max_newidle_lb_cost * 253) / 256;
7463 sd->next_decay_max_lb_cost = jiffies + HZ; 7467 sd->next_decay_max_lb_cost = jiffies + HZ;
7464 need_decay = 1; 7468 need_decay = 1;
7465 } 7469 }
7466 max_cost += sd->max_newidle_lb_cost; 7470 max_cost += sd->max_newidle_lb_cost;
7467 7471
7468 if (!(sd->flags & SD_LOAD_BALANCE)) 7472 if (!(sd->flags & SD_LOAD_BALANCE))
7469 continue; 7473 continue;
7470 7474
7471 /* 7475 /*
7472 * Stop the load balance at this level. There is another 7476 * Stop the load balance at this level. There is another
7473 * CPU in our sched group which is doing load balancing more 7477 * CPU in our sched group which is doing load balancing more
7474 * actively. 7478 * actively.
7475 */ 7479 */
7476 if (!continue_balancing) { 7480 if (!continue_balancing) {
7477 if (need_decay) 7481 if (need_decay)
7478 continue; 7482 continue;
7479 break; 7483 break;
7480 } 7484 }
7481 7485
7482 interval = get_sd_balance_interval(sd, idle != CPU_IDLE); 7486 interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
7483 7487
7484 need_serialize = sd->flags & SD_SERIALIZE; 7488 need_serialize = sd->flags & SD_SERIALIZE;
7485 if (need_serialize) { 7489 if (need_serialize) {
7486 if (!spin_trylock(&balancing)) 7490 if (!spin_trylock(&balancing))
7487 goto out; 7491 goto out;
7488 } 7492 }
7489 7493
7490 if (time_after_eq(jiffies, sd->last_balance + interval)) { 7494 if (time_after_eq(jiffies, sd->last_balance + interval)) {
7491 if (load_balance(cpu, rq, sd, idle, &continue_balancing)) { 7495 if (load_balance(cpu, rq, sd, idle, &continue_balancing)) {
7492 /* 7496 /*
7493 * The LBF_DST_PINNED logic could have changed 7497 * The LBF_DST_PINNED logic could have changed
7494 * env->dst_cpu, so we can't know our idle 7498 * env->dst_cpu, so we can't know our idle
7495 * state even if we migrated tasks. Update it. 7499 * state even if we migrated tasks. Update it.
7496 */ 7500 */
7497 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE; 7501 idle = idle_cpu(cpu) ? CPU_IDLE : CPU_NOT_IDLE;
7498 } 7502 }
7499 sd->last_balance = jiffies; 7503 sd->last_balance = jiffies;
7500 interval = get_sd_balance_interval(sd, idle != CPU_IDLE); 7504 interval = get_sd_balance_interval(sd, idle != CPU_IDLE);
7501 } 7505 }
7502 if (need_serialize) 7506 if (need_serialize)
7503 spin_unlock(&balancing); 7507 spin_unlock(&balancing);
7504 out: 7508 out:
7505 if (time_after(next_balance, sd->last_balance + interval)) { 7509 if (time_after(next_balance, sd->last_balance + interval)) {
7506 next_balance = sd->last_balance + interval; 7510 next_balance = sd->last_balance + interval;
7507 update_next_balance = 1; 7511 update_next_balance = 1;
7508 } 7512 }
7509 } 7513 }
7510 if (need_decay) { 7514 if (need_decay) {
7511 /* 7515 /*
7512 * Ensure the rq-wide value also decays but keep it at a 7516 * Ensure the rq-wide value also decays but keep it at a
7513 * reasonable floor to avoid funnies with rq->avg_idle. 7517 * reasonable floor to avoid funnies with rq->avg_idle.
7514 */ 7518 */
7515 rq->max_idle_balance_cost = 7519 rq->max_idle_balance_cost =
7516 max((u64)sysctl_sched_migration_cost, max_cost); 7520 max((u64)sysctl_sched_migration_cost, max_cost);
7517 } 7521 }
7518 rcu_read_unlock(); 7522 rcu_read_unlock();
7519 7523
7520 /* 7524 /*
7521 * next_balance will be updated only when there is a need. 7525 * next_balance will be updated only when there is a need.
7522 * When the cpu is attached to null domain for ex, it will not be 7526 * When the cpu is attached to null domain for ex, it will not be
7523 * updated. 7527 * updated.
7524 */ 7528 */
7525 if (likely(update_next_balance)) 7529 if (likely(update_next_balance))
7526 rq->next_balance = next_balance; 7530 rq->next_balance = next_balance;
7527 } 7531 }
7528 7532
7529 #ifdef CONFIG_NO_HZ_COMMON 7533 #ifdef CONFIG_NO_HZ_COMMON
7530 /* 7534 /*
7531 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the 7535 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the
7532 * rebalancing for all the cpus for whom scheduler ticks are stopped. 7536 * rebalancing for all the cpus for whom scheduler ticks are stopped.
7533 */ 7537 */
7534 static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) 7538 static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle)
7535 { 7539 {
7536 int this_cpu = this_rq->cpu; 7540 int this_cpu = this_rq->cpu;
7537 struct rq *rq; 7541 struct rq *rq;
7538 int balance_cpu; 7542 int balance_cpu;
7539 7543
7540 if (idle != CPU_IDLE || 7544 if (idle != CPU_IDLE ||
7541 !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu))) 7545 !test_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)))
7542 goto end; 7546 goto end;
7543 7547
7544 for_each_cpu(balance_cpu, nohz.idle_cpus_mask) { 7548 for_each_cpu(balance_cpu, nohz.idle_cpus_mask) {
7545 if (balance_cpu == this_cpu || !idle_cpu(balance_cpu)) 7549 if (balance_cpu == this_cpu || !idle_cpu(balance_cpu))
7546 continue; 7550 continue;
7547 7551
7548 /* 7552 /*
7549 * If this cpu gets work to do, stop the load balancing 7553 * If this cpu gets work to do, stop the load balancing
7550 * work being done for other cpus. Next load 7554 * work being done for other cpus. Next load
7551 * balancing owner will pick it up. 7555 * balancing owner will pick it up.
7552 */ 7556 */
7553 if (need_resched()) 7557 if (need_resched())
7554 break; 7558 break;
7555 7559
7556 rq = cpu_rq(balance_cpu); 7560 rq = cpu_rq(balance_cpu);
7557 7561
7558 /* 7562 /*
7559 * If time for next balance is due, 7563 * If time for next balance is due,
7560 * do the balance. 7564 * do the balance.
7561 */ 7565 */
7562 if (time_after_eq(jiffies, rq->next_balance)) { 7566 if (time_after_eq(jiffies, rq->next_balance)) {
7563 raw_spin_lock_irq(&rq->lock); 7567 raw_spin_lock_irq(&rq->lock);
7564 update_rq_clock(rq); 7568 update_rq_clock(rq);
7565 update_idle_cpu_load(rq); 7569 update_idle_cpu_load(rq);
7566 raw_spin_unlock_irq(&rq->lock); 7570 raw_spin_unlock_irq(&rq->lock);
7567 rebalance_domains(rq, CPU_IDLE); 7571 rebalance_domains(rq, CPU_IDLE);
7568 } 7572 }
7569 7573
7570 if (time_after(this_rq->next_balance, rq->next_balance)) 7574 if (time_after(this_rq->next_balance, rq->next_balance))
7571 this_rq->next_balance = rq->next_balance; 7575 this_rq->next_balance = rq->next_balance;
7572 } 7576 }
7573 nohz.next_balance = this_rq->next_balance; 7577 nohz.next_balance = this_rq->next_balance;
7574 end: 7578 end:
7575 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu)); 7579 clear_bit(NOHZ_BALANCE_KICK, nohz_flags(this_cpu));
7576 } 7580 }
7577 7581
7578 /* 7582 /*
7579 * Current heuristic for kicking the idle load balancer in the presence 7583 * Current heuristic for kicking the idle load balancer in the presence
7580 * of an idle cpu is the system. 7584 * of an idle cpu is the system.
7581 * - This rq has more than one task. 7585 * - This rq has more than one task.
7582 * - At any scheduler domain level, this cpu's scheduler group has multiple 7586 * - At any scheduler domain level, this cpu's scheduler group has multiple
7583 * busy cpu's exceeding the group's capacity. 7587 * busy cpu's exceeding the group's capacity.
7584 * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler 7588 * - For SD_ASYM_PACKING, if the lower numbered cpu's in the scheduler
7585 * domain span are idle. 7589 * domain span are idle.
7586 */ 7590 */
7587 static inline int nohz_kick_needed(struct rq *rq) 7591 static inline int nohz_kick_needed(struct rq *rq)
7588 { 7592 {
7589 unsigned long now = jiffies; 7593 unsigned long now = jiffies;
7590 struct sched_domain *sd; 7594 struct sched_domain *sd;
7591 struct sched_group_capacity *sgc; 7595 struct sched_group_capacity *sgc;
7592 int nr_busy, cpu = rq->cpu; 7596 int nr_busy, cpu = rq->cpu;
7593 7597
7594 if (unlikely(rq->idle_balance)) 7598 if (unlikely(rq->idle_balance))
7595 return 0; 7599 return 0;
7596 7600
7597 /* 7601 /*
7598 * We may be recently in ticked or tickless idle mode. At the first 7602 * We may be recently in ticked or tickless idle mode. At the first
7599 * busy tick after returning from idle, we will update the busy stats. 7603 * busy tick after returning from idle, we will update the busy stats.
7600 */ 7604 */
7601 set_cpu_sd_state_busy(); 7605 set_cpu_sd_state_busy();
7602 nohz_balance_exit_idle(cpu); 7606 nohz_balance_exit_idle(cpu);
7603 7607
7604 /* 7608 /*
7605 * None are in tickless mode and hence no need for NOHZ idle load 7609 * None are in tickless mode and hence no need for NOHZ idle load
7606 * balancing. 7610 * balancing.
7607 */ 7611 */
7608 if (likely(!atomic_read(&nohz.nr_cpus))) 7612 if (likely(!atomic_read(&nohz.nr_cpus)))
7609 return 0; 7613 return 0;
7610 7614
7611 if (time_before(now, nohz.next_balance)) 7615 if (time_before(now, nohz.next_balance))
7612 return 0; 7616 return 0;
7613 7617
7614 if (rq->nr_running >= 2) 7618 if (rq->nr_running >= 2)
7615 goto need_kick; 7619 goto need_kick;
7616 7620
7617 rcu_read_lock(); 7621 rcu_read_lock();
7618 sd = rcu_dereference(per_cpu(sd_busy, cpu)); 7622 sd = rcu_dereference(per_cpu(sd_busy, cpu));
7619 7623
7620 if (sd) { 7624 if (sd) {
7621 sgc = sd->groups->sgc; 7625 sgc = sd->groups->sgc;
7622 nr_busy = atomic_read(&sgc->nr_busy_cpus); 7626 nr_busy = atomic_read(&sgc->nr_busy_cpus);
7623 7627
7624 if (nr_busy > 1) 7628 if (nr_busy > 1)
7625 goto need_kick_unlock; 7629 goto need_kick_unlock;
7626 } 7630 }
7627 7631
7628 sd = rcu_dereference(per_cpu(sd_asym, cpu)); 7632 sd = rcu_dereference(per_cpu(sd_asym, cpu));
7629 7633
7630 if (sd && (cpumask_first_and(nohz.idle_cpus_mask, 7634 if (sd && (cpumask_first_and(nohz.idle_cpus_mask,
7631 sched_domain_span(sd)) < cpu)) 7635 sched_domain_span(sd)) < cpu))
7632 goto need_kick_unlock; 7636 goto need_kick_unlock;
7633 7637
7634 rcu_read_unlock(); 7638 rcu_read_unlock();
7635 return 0; 7639 return 0;
7636 7640
7637 need_kick_unlock: 7641 need_kick_unlock:
7638 rcu_read_unlock(); 7642 rcu_read_unlock();
7639 need_kick: 7643 need_kick:
7640 return 1; 7644 return 1;
7641 } 7645 }
7642 #else 7646 #else
7643 static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) { } 7647 static void nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) { }
7644 #endif 7648 #endif
7645 7649
7646 /* 7650 /*
7647 * run_rebalance_domains is triggered when needed from the scheduler tick. 7651 * run_rebalance_domains is triggered when needed from the scheduler tick.
7648 * Also triggered for nohz idle balancing (with nohz_balancing_kick set). 7652 * Also triggered for nohz idle balancing (with nohz_balancing_kick set).
7649 */ 7653 */
7650 static void run_rebalance_domains(struct softirq_action *h) 7654 static void run_rebalance_domains(struct softirq_action *h)
7651 { 7655 {
7652 struct rq *this_rq = this_rq(); 7656 struct rq *this_rq = this_rq();
7653 enum cpu_idle_type idle = this_rq->idle_balance ? 7657 enum cpu_idle_type idle = this_rq->idle_balance ?
7654 CPU_IDLE : CPU_NOT_IDLE; 7658 CPU_IDLE : CPU_NOT_IDLE;
7655 7659
7656 rebalance_domains(this_rq, idle); 7660 rebalance_domains(this_rq, idle);
7657 7661
7658 /* 7662 /*
7659 * If this cpu has a pending nohz_balance_kick, then do the 7663 * If this cpu has a pending nohz_balance_kick, then do the
7660 * balancing on behalf of the other idle cpus whose ticks are 7664 * balancing on behalf of the other idle cpus whose ticks are
7661 * stopped. 7665 * stopped.
7662 */ 7666 */
7663 nohz_idle_balance(this_rq, idle); 7667 nohz_idle_balance(this_rq, idle);
7664 } 7668 }
7665 7669
7666 /* 7670 /*
7667 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing. 7671 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
7668 */ 7672 */
7669 void trigger_load_balance(struct rq *rq) 7673 void trigger_load_balance(struct rq *rq)
7670 { 7674 {
7671 /* Don't need to rebalance while attached to NULL domain */ 7675 /* Don't need to rebalance while attached to NULL domain */
7672 if (unlikely(on_null_domain(rq))) 7676 if (unlikely(on_null_domain(rq)))
7673 return; 7677 return;
7674 7678
7675 if (time_after_eq(jiffies, rq->next_balance)) 7679 if (time_after_eq(jiffies, rq->next_balance))
7676 raise_softirq(SCHED_SOFTIRQ); 7680 raise_softirq(SCHED_SOFTIRQ);
7677 #ifdef CONFIG_NO_HZ_COMMON 7681 #ifdef CONFIG_NO_HZ_COMMON
7678 if (nohz_kick_needed(rq)) 7682 if (nohz_kick_needed(rq))
7679 nohz_balancer_kick(); 7683 nohz_balancer_kick();
7680 #endif 7684 #endif
7681 } 7685 }
7682 7686
7683 static void rq_online_fair(struct rq *rq) 7687 static void rq_online_fair(struct rq *rq)
7684 { 7688 {
7685 update_sysctl(); 7689 update_sysctl();
7686 7690
7687 update_runtime_enabled(rq); 7691 update_runtime_enabled(rq);
7688 } 7692 }
7689 7693
7690 static void rq_offline_fair(struct rq *rq) 7694 static void rq_offline_fair(struct rq *rq)
7691 { 7695 {
7692 update_sysctl(); 7696 update_sysctl();
7693 7697
7694 /* Ensure any throttled groups are reachable by pick_next_task */ 7698 /* Ensure any throttled groups are reachable by pick_next_task */
7695 unthrottle_offline_cfs_rqs(rq); 7699 unthrottle_offline_cfs_rqs(rq);
7696 } 7700 }
7697 7701
7698 #endif /* CONFIG_SMP */ 7702 #endif /* CONFIG_SMP */
7699 7703
7700 /* 7704 /*
7701 * scheduler tick hitting a task of our scheduling class: 7705 * scheduler tick hitting a task of our scheduling class:
7702 */ 7706 */
7703 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued) 7707 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued)
7704 { 7708 {
7705 struct cfs_rq *cfs_rq; 7709 struct cfs_rq *cfs_rq;
7706 struct sched_entity *se = &curr->se; 7710 struct sched_entity *se = &curr->se;
7707 7711
7708 for_each_sched_entity(se) { 7712 for_each_sched_entity(se) {
7709 cfs_rq = cfs_rq_of(se); 7713 cfs_rq = cfs_rq_of(se);
7710 entity_tick(cfs_rq, se, queued); 7714 entity_tick(cfs_rq, se, queued);
7711 } 7715 }
7712 7716
7713 if (numabalancing_enabled) 7717 if (numabalancing_enabled)
7714 task_tick_numa(rq, curr); 7718 task_tick_numa(rq, curr);
7715 7719
7716 update_rq_runnable_avg(rq, 1); 7720 update_rq_runnable_avg(rq, 1);
7717 } 7721 }
7718 7722
7719 /* 7723 /*
7720 * called on fork with the child task as argument from the parent's context 7724 * called on fork with the child task as argument from the parent's context
7721 * - child not yet on the tasklist 7725 * - child not yet on the tasklist
7722 * - preemption disabled 7726 * - preemption disabled
7723 */ 7727 */
7724 static void task_fork_fair(struct task_struct *p) 7728 static void task_fork_fair(struct task_struct *p)
7725 { 7729 {
7726 struct cfs_rq *cfs_rq; 7730 struct cfs_rq *cfs_rq;
7727 struct sched_entity *se = &p->se, *curr; 7731 struct sched_entity *se = &p->se, *curr;
7728 int this_cpu = smp_processor_id(); 7732 int this_cpu = smp_processor_id();
7729 struct rq *rq = this_rq(); 7733 struct rq *rq = this_rq();
7730 unsigned long flags; 7734 unsigned long flags;
7731 7735
7732 raw_spin_lock_irqsave(&rq->lock, flags); 7736 raw_spin_lock_irqsave(&rq->lock, flags);
7733 7737
7734 update_rq_clock(rq); 7738 update_rq_clock(rq);
7735 7739
7736 cfs_rq = task_cfs_rq(current); 7740 cfs_rq = task_cfs_rq(current);
7737 curr = cfs_rq->curr; 7741 curr = cfs_rq->curr;
7738 7742
7739 /* 7743 /*
7740 * Not only the cpu but also the task_group of the parent might have 7744 * Not only the cpu but also the task_group of the parent might have
7741 * been changed after parent->se.parent,cfs_rq were copied to 7745 * been changed after parent->se.parent,cfs_rq were copied to
7742 * child->se.parent,cfs_rq. So call __set_task_cpu() to make those 7746 * child->se.parent,cfs_rq. So call __set_task_cpu() to make those
7743 * of child point to valid ones. 7747 * of child point to valid ones.
7744 */ 7748 */
7745 rcu_read_lock(); 7749 rcu_read_lock();
7746 __set_task_cpu(p, this_cpu); 7750 __set_task_cpu(p, this_cpu);
7747 rcu_read_unlock(); 7751 rcu_read_unlock();
7748 7752
7749 update_curr(cfs_rq); 7753 update_curr(cfs_rq);
7750 7754
7751 if (curr) 7755 if (curr)
7752 se->vruntime = curr->vruntime; 7756 se->vruntime = curr->vruntime;
7753 place_entity(cfs_rq, se, 1); 7757 place_entity(cfs_rq, se, 1);
7754 7758
7755 if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) { 7759 if (sysctl_sched_child_runs_first && curr && entity_before(curr, se)) {
7756 /* 7760 /*
7757 * Upon rescheduling, sched_class::put_prev_task() will place 7761 * Upon rescheduling, sched_class::put_prev_task() will place
7758 * 'current' within the tree based on its new key value. 7762 * 'current' within the tree based on its new key value.
7759 */ 7763 */
7760 swap(curr->vruntime, se->vruntime); 7764 swap(curr->vruntime, se->vruntime);
7761 resched_curr(rq); 7765 resched_curr(rq);
7762 } 7766 }
7763 7767
7764 se->vruntime -= cfs_rq->min_vruntime; 7768 se->vruntime -= cfs_rq->min_vruntime;
7765 7769
7766 raw_spin_unlock_irqrestore(&rq->lock, flags); 7770 raw_spin_unlock_irqrestore(&rq->lock, flags);
7767 } 7771 }
7768 7772
7769 /* 7773 /*
7770 * Priority of the task has changed. Check to see if we preempt 7774 * Priority of the task has changed. Check to see if we preempt
7771 * the current task. 7775 * the current task.
7772 */ 7776 */
7773 static void 7777 static void
7774 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio) 7778 prio_changed_fair(struct rq *rq, struct task_struct *p, int oldprio)
7775 { 7779 {
7776 if (!task_on_rq_queued(p)) 7780 if (!task_on_rq_queued(p))
7777 return; 7781 return;
7778 7782
7779 /* 7783 /*
7780 * Reschedule if we are currently running on this runqueue and 7784 * Reschedule if we are currently running on this runqueue and
7781 * our priority decreased, or if we are not currently running on 7785 * our priority decreased, or if we are not currently running on
7782 * this runqueue and our priority is higher than the current's 7786 * this runqueue and our priority is higher than the current's
7783 */ 7787 */
7784 if (rq->curr == p) { 7788 if (rq->curr == p) {
7785 if (p->prio > oldprio) 7789 if (p->prio > oldprio)
7786 resched_curr(rq); 7790 resched_curr(rq);
7787 } else 7791 } else
7788 check_preempt_curr(rq, p, 0); 7792 check_preempt_curr(rq, p, 0);
7789 } 7793 }
7790 7794
7791 static void switched_from_fair(struct rq *rq, struct task_struct *p) 7795 static void switched_from_fair(struct rq *rq, struct task_struct *p)
7792 { 7796 {
7793 struct sched_entity *se = &p->se; 7797 struct sched_entity *se = &p->se;
7794 struct cfs_rq *cfs_rq = cfs_rq_of(se); 7798 struct cfs_rq *cfs_rq = cfs_rq_of(se);
7795 7799
7796 /* 7800 /*
7797 * Ensure the task's vruntime is normalized, so that when it's 7801 * Ensure the task's vruntime is normalized, so that when it's
7798 * switched back to the fair class the enqueue_entity(.flags=0) will 7802 * switched back to the fair class the enqueue_entity(.flags=0) will
7799 * do the right thing. 7803 * do the right thing.
7800 * 7804 *
7801 * If it's queued, then the dequeue_entity(.flags=0) will already 7805 * If it's queued, then the dequeue_entity(.flags=0) will already
7802 * have normalized the vruntime, if it's !queued, then only when 7806 * have normalized the vruntime, if it's !queued, then only when
7803 * the task is sleeping will it still have non-normalized vruntime. 7807 * the task is sleeping will it still have non-normalized vruntime.
7804 */ 7808 */
7805 if (!task_on_rq_queued(p) && p->state != TASK_RUNNING) { 7809 if (!task_on_rq_queued(p) && p->state != TASK_RUNNING) {
7806 /* 7810 /*
7807 * Fix up our vruntime so that the current sleep doesn't 7811 * Fix up our vruntime so that the current sleep doesn't
7808 * cause 'unlimited' sleep bonus. 7812 * cause 'unlimited' sleep bonus.
7809 */ 7813 */
7810 place_entity(cfs_rq, se, 0); 7814 place_entity(cfs_rq, se, 0);
7811 se->vruntime -= cfs_rq->min_vruntime; 7815 se->vruntime -= cfs_rq->min_vruntime;
7812 } 7816 }
7813 7817
7814 #ifdef CONFIG_SMP 7818 #ifdef CONFIG_SMP
7815 /* 7819 /*
7816 * Remove our load from contribution when we leave sched_fair 7820 * Remove our load from contribution when we leave sched_fair
7817 * and ensure we don't carry in an old decay_count if we 7821 * and ensure we don't carry in an old decay_count if we
7818 * switch back. 7822 * switch back.
7819 */ 7823 */
7820 if (se->avg.decay_count) { 7824 if (se->avg.decay_count) {
7821 __synchronize_entity_decay(se); 7825 __synchronize_entity_decay(se);
7822 subtract_blocked_load_contrib(cfs_rq, se->avg.load_avg_contrib); 7826 subtract_blocked_load_contrib(cfs_rq, se->avg.load_avg_contrib);
7823 } 7827 }
7824 #endif 7828 #endif
7825 } 7829 }
7826 7830
7827 /* 7831 /*
7828 * We switched to the sched_fair class. 7832 * We switched to the sched_fair class.
7829 */ 7833 */
7830 static void switched_to_fair(struct rq *rq, struct task_struct *p) 7834 static void switched_to_fair(struct rq *rq, struct task_struct *p)
7831 { 7835 {
7832 #ifdef CONFIG_FAIR_GROUP_SCHED 7836 #ifdef CONFIG_FAIR_GROUP_SCHED
7833 struct sched_entity *se = &p->se; 7837 struct sched_entity *se = &p->se;
7834 /* 7838 /*
7835 * Since the real-depth could have been changed (only FAIR 7839 * Since the real-depth could have been changed (only FAIR
7836 * class maintain depth value), reset depth properly. 7840 * class maintain depth value), reset depth properly.
7837 */ 7841 */
7838 se->depth = se->parent ? se->parent->depth + 1 : 0; 7842 se->depth = se->parent ? se->parent->depth + 1 : 0;
7839 #endif 7843 #endif
7840 if (!task_on_rq_queued(p)) 7844 if (!task_on_rq_queued(p))
7841 return; 7845 return;
7842 7846
7843 /* 7847 /*
7844 * We were most likely switched from sched_rt, so 7848 * We were most likely switched from sched_rt, so
7845 * kick off the schedule if running, otherwise just see 7849 * kick off the schedule if running, otherwise just see
7846 * if we can still preempt the current task. 7850 * if we can still preempt the current task.
7847 */ 7851 */
7848 if (rq->curr == p) 7852 if (rq->curr == p)
7849 resched_curr(rq); 7853 resched_curr(rq);
7850 else 7854 else
7851 check_preempt_curr(rq, p, 0); 7855 check_preempt_curr(rq, p, 0);
7852 } 7856 }
7853 7857
7854 /* Account for a task changing its policy or group. 7858 /* Account for a task changing its policy or group.
7855 * 7859 *
7856 * This routine is mostly called to set cfs_rq->curr field when a task 7860 * This routine is mostly called to set cfs_rq->curr field when a task
7857 * migrates between groups/classes. 7861 * migrates between groups/classes.
7858 */ 7862 */
7859 static void set_curr_task_fair(struct rq *rq) 7863 static void set_curr_task_fair(struct rq *rq)
7860 { 7864 {
7861 struct sched_entity *se = &rq->curr->se; 7865 struct sched_entity *se = &rq->curr->se;
7862 7866
7863 for_each_sched_entity(se) { 7867 for_each_sched_entity(se) {
7864 struct cfs_rq *cfs_rq = cfs_rq_of(se); 7868 struct cfs_rq *cfs_rq = cfs_rq_of(se);
7865 7869
7866 set_next_entity(cfs_rq, se); 7870 set_next_entity(cfs_rq, se);
7867 /* ensure bandwidth has been allocated on our new cfs_rq */ 7871 /* ensure bandwidth has been allocated on our new cfs_rq */
7868 account_cfs_rq_runtime(cfs_rq, 0); 7872 account_cfs_rq_runtime(cfs_rq, 0);
7869 } 7873 }
7870 } 7874 }
7871 7875
7872 void init_cfs_rq(struct cfs_rq *cfs_rq) 7876 void init_cfs_rq(struct cfs_rq *cfs_rq)
7873 { 7877 {
7874 cfs_rq->tasks_timeline = RB_ROOT; 7878 cfs_rq->tasks_timeline = RB_ROOT;
7875 cfs_rq->min_vruntime = (u64)(-(1LL << 20)); 7879 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7876 #ifndef CONFIG_64BIT 7880 #ifndef CONFIG_64BIT
7877 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime; 7881 cfs_rq->min_vruntime_copy = cfs_rq->min_vruntime;
7878 #endif 7882 #endif
7879 #ifdef CONFIG_SMP 7883 #ifdef CONFIG_SMP
7880 atomic64_set(&cfs_rq->decay_counter, 1); 7884 atomic64_set(&cfs_rq->decay_counter, 1);
7881 atomic_long_set(&cfs_rq->removed_load, 0); 7885 atomic_long_set(&cfs_rq->removed_load, 0);
7882 #endif 7886 #endif
7883 } 7887 }
7884 7888
7885 #ifdef CONFIG_FAIR_GROUP_SCHED 7889 #ifdef CONFIG_FAIR_GROUP_SCHED
7886 static void task_move_group_fair(struct task_struct *p, int queued) 7890 static void task_move_group_fair(struct task_struct *p, int queued)
7887 { 7891 {
7888 struct sched_entity *se = &p->se; 7892 struct sched_entity *se = &p->se;
7889 struct cfs_rq *cfs_rq; 7893 struct cfs_rq *cfs_rq;
7890 7894
7891 /* 7895 /*
7892 * If the task was not on the rq at the time of this cgroup movement 7896 * If the task was not on the rq at the time of this cgroup movement
7893 * it must have been asleep, sleeping tasks keep their ->vruntime 7897 * it must have been asleep, sleeping tasks keep their ->vruntime
7894 * absolute on their old rq until wakeup (needed for the fair sleeper 7898 * absolute on their old rq until wakeup (needed for the fair sleeper
7895 * bonus in place_entity()). 7899 * bonus in place_entity()).
7896 * 7900 *
7897 * If it was on the rq, we've just 'preempted' it, which does convert 7901 * If it was on the rq, we've just 'preempted' it, which does convert
7898 * ->vruntime to a relative base. 7902 * ->vruntime to a relative base.
7899 * 7903 *
7900 * Make sure both cases convert their relative position when migrating 7904 * Make sure both cases convert their relative position when migrating
7901 * to another cgroup's rq. This does somewhat interfere with the 7905 * to another cgroup's rq. This does somewhat interfere with the
7902 * fair sleeper stuff for the first placement, but who cares. 7906 * fair sleeper stuff for the first placement, but who cares.
7903 */ 7907 */
7904 /* 7908 /*
7905 * When !queued, vruntime of the task has usually NOT been normalized. 7909 * When !queued, vruntime of the task has usually NOT been normalized.
7906 * But there are some cases where it has already been normalized: 7910 * But there are some cases where it has already been normalized:
7907 * 7911 *
7908 * - Moving a forked child which is waiting for being woken up by 7912 * - Moving a forked child which is waiting for being woken up by
7909 * wake_up_new_task(). 7913 * wake_up_new_task().
7910 * - Moving a task which has been woken up by try_to_wake_up() and 7914 * - Moving a task which has been woken up by try_to_wake_up() and
7911 * waiting for actually being woken up by sched_ttwu_pending(). 7915 * waiting for actually being woken up by sched_ttwu_pending().
7912 * 7916 *
7913 * To prevent boost or penalty in the new cfs_rq caused by delta 7917 * To prevent boost or penalty in the new cfs_rq caused by delta
7914 * min_vruntime between the two cfs_rqs, we skip vruntime adjustment. 7918 * min_vruntime between the two cfs_rqs, we skip vruntime adjustment.
7915 */ 7919 */
7916 if (!queued && (!se->sum_exec_runtime || p->state == TASK_WAKING)) 7920 if (!queued && (!se->sum_exec_runtime || p->state == TASK_WAKING))
7917 queued = 1; 7921 queued = 1;
7918 7922
7919 if (!queued) 7923 if (!queued)
7920 se->vruntime -= cfs_rq_of(se)->min_vruntime; 7924 se->vruntime -= cfs_rq_of(se)->min_vruntime;
7921 set_task_rq(p, task_cpu(p)); 7925 set_task_rq(p, task_cpu(p));
7922 se->depth = se->parent ? se->parent->depth + 1 : 0; 7926 se->depth = se->parent ? se->parent->depth + 1 : 0;
7923 if (!queued) { 7927 if (!queued) {
7924 cfs_rq = cfs_rq_of(se); 7928 cfs_rq = cfs_rq_of(se);
7925 se->vruntime += cfs_rq->min_vruntime; 7929 se->vruntime += cfs_rq->min_vruntime;
7926 #ifdef CONFIG_SMP 7930 #ifdef CONFIG_SMP
7927 /* 7931 /*
7928 * migrate_task_rq_fair() will have removed our previous 7932 * migrate_task_rq_fair() will have removed our previous
7929 * contribution, but we must synchronize for ongoing future 7933 * contribution, but we must synchronize for ongoing future
7930 * decay. 7934 * decay.
7931 */ 7935 */
7932 se->avg.decay_count = atomic64_read(&cfs_rq->decay_counter); 7936 se->avg.decay_count = atomic64_read(&cfs_rq->decay_counter);
7933 cfs_rq->blocked_load_avg += se->avg.load_avg_contrib; 7937 cfs_rq->blocked_load_avg += se->avg.load_avg_contrib;
7934 #endif 7938 #endif
7935 } 7939 }
7936 } 7940 }
7937 7941
7938 void free_fair_sched_group(struct task_group *tg) 7942 void free_fair_sched_group(struct task_group *tg)
7939 { 7943 {
7940 int i; 7944 int i;
7941 7945
7942 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg)); 7946 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg));
7943 7947
7944 for_each_possible_cpu(i) { 7948 for_each_possible_cpu(i) {
7945 if (tg->cfs_rq) 7949 if (tg->cfs_rq)
7946 kfree(tg->cfs_rq[i]); 7950 kfree(tg->cfs_rq[i]);
7947 if (tg->se) 7951 if (tg->se)
7948 kfree(tg->se[i]); 7952 kfree(tg->se[i]);
7949 } 7953 }
7950 7954
7951 kfree(tg->cfs_rq); 7955 kfree(tg->cfs_rq);
7952 kfree(tg->se); 7956 kfree(tg->se);
7953 } 7957 }
7954 7958
7955 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent) 7959 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
7956 { 7960 {
7957 struct cfs_rq *cfs_rq; 7961 struct cfs_rq *cfs_rq;
7958 struct sched_entity *se; 7962 struct sched_entity *se;
7959 int i; 7963 int i;
7960 7964
7961 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL); 7965 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
7962 if (!tg->cfs_rq) 7966 if (!tg->cfs_rq)
7963 goto err; 7967 goto err;
7964 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL); 7968 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
7965 if (!tg->se) 7969 if (!tg->se)
7966 goto err; 7970 goto err;
7967 7971
7968 tg->shares = NICE_0_LOAD; 7972 tg->shares = NICE_0_LOAD;
7969 7973
7970 init_cfs_bandwidth(tg_cfs_bandwidth(tg)); 7974 init_cfs_bandwidth(tg_cfs_bandwidth(tg));
7971 7975
7972 for_each_possible_cpu(i) { 7976 for_each_possible_cpu(i) {
7973 cfs_rq = kzalloc_node(sizeof(struct cfs_rq), 7977 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
7974 GFP_KERNEL, cpu_to_node(i)); 7978 GFP_KERNEL, cpu_to_node(i));
7975 if (!cfs_rq) 7979 if (!cfs_rq)
7976 goto err; 7980 goto err;
7977 7981
7978 se = kzalloc_node(sizeof(struct sched_entity), 7982 se = kzalloc_node(sizeof(struct sched_entity),
7979 GFP_KERNEL, cpu_to_node(i)); 7983 GFP_KERNEL, cpu_to_node(i));
7980 if (!se) 7984 if (!se)
7981 goto err_free_rq; 7985 goto err_free_rq;
7982 7986
7983 init_cfs_rq(cfs_rq); 7987 init_cfs_rq(cfs_rq);
7984 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]); 7988 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
7985 } 7989 }
7986 7990
7987 return 1; 7991 return 1;
7988 7992
7989 err_free_rq: 7993 err_free_rq:
7990 kfree(cfs_rq); 7994 kfree(cfs_rq);
7991 err: 7995 err:
7992 return 0; 7996 return 0;
7993 } 7997 }
7994 7998
7995 void unregister_fair_sched_group(struct task_group *tg, int cpu) 7999 void unregister_fair_sched_group(struct task_group *tg, int cpu)
7996 { 8000 {
7997 struct rq *rq = cpu_rq(cpu); 8001 struct rq *rq = cpu_rq(cpu);
7998 unsigned long flags; 8002 unsigned long flags;
7999 8003
8000 /* 8004 /*
8001 * Only empty task groups can be destroyed; so we can speculatively 8005 * Only empty task groups can be destroyed; so we can speculatively
8002 * check on_list without danger of it being re-added. 8006 * check on_list without danger of it being re-added.
8003 */ 8007 */
8004 if (!tg->cfs_rq[cpu]->on_list) 8008 if (!tg->cfs_rq[cpu]->on_list)
8005 return; 8009 return;
8006 8010
8007 raw_spin_lock_irqsave(&rq->lock, flags); 8011 raw_spin_lock_irqsave(&rq->lock, flags);
8008 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]); 8012 list_del_leaf_cfs_rq(tg->cfs_rq[cpu]);
8009 raw_spin_unlock_irqrestore(&rq->lock, flags); 8013 raw_spin_unlock_irqrestore(&rq->lock, flags);
8010 } 8014 }
8011 8015
8012 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq, 8016 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
8013 struct sched_entity *se, int cpu, 8017 struct sched_entity *se, int cpu,
8014 struct sched_entity *parent) 8018 struct sched_entity *parent)
8015 { 8019 {
8016 struct rq *rq = cpu_rq(cpu); 8020 struct rq *rq = cpu_rq(cpu);
8017 8021
8018 cfs_rq->tg = tg; 8022 cfs_rq->tg = tg;
8019 cfs_rq->rq = rq; 8023 cfs_rq->rq = rq;
8020 init_cfs_rq_runtime(cfs_rq); 8024 init_cfs_rq_runtime(cfs_rq);
8021 8025
8022 tg->cfs_rq[cpu] = cfs_rq; 8026 tg->cfs_rq[cpu] = cfs_rq;
8023 tg->se[cpu] = se; 8027 tg->se[cpu] = se;
8024 8028
8025 /* se could be NULL for root_task_group */ 8029 /* se could be NULL for root_task_group */
8026 if (!se) 8030 if (!se)
8027 return; 8031 return;
8028 8032
8029 if (!parent) { 8033 if (!parent) {
8030 se->cfs_rq = &rq->cfs; 8034 se->cfs_rq = &rq->cfs;
8031 se->depth = 0; 8035 se->depth = 0;
8032 } else { 8036 } else {
8033 se->cfs_rq = parent->my_q; 8037 se->cfs_rq = parent->my_q;
8034 se->depth = parent->depth + 1; 8038 se->depth = parent->depth + 1;
8035 } 8039 }
8036 8040
8037 se->my_q = cfs_rq; 8041 se->my_q = cfs_rq;
8038 /* guarantee group entities always have weight */ 8042 /* guarantee group entities always have weight */
8039 update_load_set(&se->load, NICE_0_LOAD); 8043 update_load_set(&se->load, NICE_0_LOAD);
8040 se->parent = parent; 8044 se->parent = parent;
8041 } 8045 }
8042 8046
8043 static DEFINE_MUTEX(shares_mutex); 8047 static DEFINE_MUTEX(shares_mutex);
8044 8048
8045 int sched_group_set_shares(struct task_group *tg, unsigned long shares) 8049 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8046 { 8050 {
8047 int i; 8051 int i;
8048 unsigned long flags; 8052 unsigned long flags;
8049 8053
8050 /* 8054 /*
8051 * We can't change the weight of the root cgroup. 8055 * We can't change the weight of the root cgroup.
8052 */ 8056 */
8053 if (!tg->se[0]) 8057 if (!tg->se[0])
8054 return -EINVAL; 8058 return -EINVAL;
8055 8059
8056 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES)); 8060 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES));
8057 8061
8058 mutex_lock(&shares_mutex); 8062 mutex_lock(&shares_mutex);
8059 if (tg->shares == shares) 8063 if (tg->shares == shares)
8060 goto done; 8064 goto done;
8061 8065
8062 tg->shares = shares; 8066 tg->shares = shares;
8063 for_each_possible_cpu(i) { 8067 for_each_possible_cpu(i) {
8064 struct rq *rq = cpu_rq(i); 8068 struct rq *rq = cpu_rq(i);
8065 struct sched_entity *se; 8069 struct sched_entity *se;
8066 8070
8067 se = tg->se[i]; 8071 se = tg->se[i];
8068 /* Propagate contribution to hierarchy */ 8072 /* Propagate contribution to hierarchy */
8069 raw_spin_lock_irqsave(&rq->lock, flags); 8073 raw_spin_lock_irqsave(&rq->lock, flags);
8070 8074
8071 /* Possible calls to update_curr() need rq clock */ 8075 /* Possible calls to update_curr() need rq clock */
8072 update_rq_clock(rq); 8076 update_rq_clock(rq);
8073 for_each_sched_entity(se) 8077 for_each_sched_entity(se)
8074 update_cfs_shares(group_cfs_rq(se)); 8078 update_cfs_shares(group_cfs_rq(se));
8075 raw_spin_unlock_irqrestore(&rq->lock, flags); 8079 raw_spin_unlock_irqrestore(&rq->lock, flags);
8076 } 8080 }
8077 8081
8078 done: 8082 done:
8079 mutex_unlock(&shares_mutex); 8083 mutex_unlock(&shares_mutex);
8080 return 0; 8084 return 0;
8081 } 8085 }
8082 #else /* CONFIG_FAIR_GROUP_SCHED */ 8086 #else /* CONFIG_FAIR_GROUP_SCHED */
8083 8087
8084 void free_fair_sched_group(struct task_group *tg) { } 8088 void free_fair_sched_group(struct task_group *tg) { }
8085 8089
8086 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent) 8090 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8087 { 8091 {
8088 return 1; 8092 return 1;
8089 } 8093 }
8090 8094
8091 void unregister_fair_sched_group(struct task_group *tg, int cpu) { } 8095 void unregister_fair_sched_group(struct task_group *tg, int cpu) { }
8092 8096
8093 #endif /* CONFIG_FAIR_GROUP_SCHED */ 8097 #endif /* CONFIG_FAIR_GROUP_SCHED */
8094 8098
8095 8099
8096 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task) 8100 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task)
8097 { 8101 {
8098 struct sched_entity *se = &task->se; 8102 struct sched_entity *se = &task->se;
8099 unsigned int rr_interval = 0; 8103 unsigned int rr_interval = 0;
8100 8104
8101 /* 8105 /*
8102 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise 8106 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise
8103 * idle runqueue: 8107 * idle runqueue:
8104 */ 8108 */
8105 if (rq->cfs.load.weight) 8109 if (rq->cfs.load.weight)
8106 rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se)); 8110 rr_interval = NS_TO_JIFFIES(sched_slice(cfs_rq_of(se), se));
8107 8111
8108 return rr_interval; 8112 return rr_interval;
8109 } 8113 }
8110 8114
8111 /* 8115 /*
8112 * All the scheduling class methods: 8116 * All the scheduling class methods:
8113 */ 8117 */
8114 const struct sched_class fair_sched_class = { 8118 const struct sched_class fair_sched_class = {
8115 .next = &idle_sched_class, 8119 .next = &idle_sched_class,
8116 .enqueue_task = enqueue_task_fair, 8120 .enqueue_task = enqueue_task_fair,
8117 .dequeue_task = dequeue_task_fair, 8121 .dequeue_task = dequeue_task_fair,
8118 .yield_task = yield_task_fair, 8122 .yield_task = yield_task_fair,
8119 .yield_to_task = yield_to_task_fair, 8123 .yield_to_task = yield_to_task_fair,
8120 8124
8121 .check_preempt_curr = check_preempt_wakeup, 8125 .check_preempt_curr = check_preempt_wakeup,
8122 8126
8123 .pick_next_task = pick_next_task_fair, 8127 .pick_next_task = pick_next_task_fair,
8124 .put_prev_task = put_prev_task_fair, 8128 .put_prev_task = put_prev_task_fair,
8125 8129
8126 #ifdef CONFIG_SMP 8130 #ifdef CONFIG_SMP
8127 .select_task_rq = select_task_rq_fair, 8131 .select_task_rq = select_task_rq_fair,
8128 .migrate_task_rq = migrate_task_rq_fair, 8132 .migrate_task_rq = migrate_task_rq_fair,
8129 8133
8130 .rq_online = rq_online_fair, 8134 .rq_online = rq_online_fair,
8131 .rq_offline = rq_offline_fair, 8135 .rq_offline = rq_offline_fair,
8132 8136
8133 .task_waking = task_waking_fair, 8137 .task_waking = task_waking_fair,
8134 #endif 8138 #endif
8135 8139
8136 .set_curr_task = set_curr_task_fair, 8140 .set_curr_task = set_curr_task_fair,
8137 .task_tick = task_tick_fair, 8141 .task_tick = task_tick_fair,
8138 .task_fork = task_fork_fair, 8142 .task_fork = task_fork_fair,
8139 8143
8140 .prio_changed = prio_changed_fair, 8144 .prio_changed = prio_changed_fair,
8141 .switched_from = switched_from_fair, 8145 .switched_from = switched_from_fair,
8142 .switched_to = switched_to_fair, 8146 .switched_to = switched_to_fair,
8143 8147
8144 .get_rr_interval = get_rr_interval_fair, 8148 .get_rr_interval = get_rr_interval_fair,
8145 8149
8146 .update_curr = update_curr_fair, 8150 .update_curr = update_curr_fair,
8147 8151
8148 #ifdef CONFIG_FAIR_GROUP_SCHED 8152 #ifdef CONFIG_FAIR_GROUP_SCHED
8149 .task_move_group = task_move_group_fair, 8153 .task_move_group = task_move_group_fair,
8150 #endif 8154 #endif
8151 }; 8155 };
8152 8156
8153 #ifdef CONFIG_SCHED_DEBUG 8157 #ifdef CONFIG_SCHED_DEBUG
8154 void print_cfs_stats(struct seq_file *m, int cpu) 8158 void print_cfs_stats(struct seq_file *m, int cpu)
8155 { 8159 {
8156 struct cfs_rq *cfs_rq; 8160 struct cfs_rq *cfs_rq;
8157 8161
8158 rcu_read_lock(); 8162 rcu_read_lock();
8159 for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq) 8163 for_each_leaf_cfs_rq(cpu_rq(cpu), cfs_rq)
8160 print_cfs_rq(m, cpu, cfs_rq); 8164 print_cfs_rq(m, cpu, cfs_rq);
8161 rcu_read_unlock(); 8165 rcu_read_unlock();
8162 } 8166 }
8163 #endif 8167 #endif
8164 8168
8165 __init void init_sched_fair_class(void) 8169 __init void init_sched_fair_class(void)
8166 { 8170 {
8167 #ifdef CONFIG_SMP 8171 #ifdef CONFIG_SMP
8168 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains); 8172 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
8169 8173
8170 #ifdef CONFIG_NO_HZ_COMMON 8174 #ifdef CONFIG_NO_HZ_COMMON
8171 nohz.next_balance = jiffies; 8175 nohz.next_balance = jiffies;
8172 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT); 8176 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
8173 cpu_notifier(sched_ilb_notifier, 0); 8177 cpu_notifier(sched_ilb_notifier, 0);
8174 #endif 8178 #endif
8175 #endif /* SMP */ 8179 #endif /* SMP */
8176 8180
8177 } 8181 }
8178 8182