OSDN Git Service

UPSTREAM: sched/core: Allow putting thread_info into task_struct
[sagit-ice-cold/kernel_xiaomi_msm8998.git] / include / linux / sched.h
1 #ifndef _LINUX_SCHED_H
2 #define _LINUX_SCHED_H
3
4 #include <uapi/linux/sched.h>
5
6 #include <linux/sched/prio.h>
7
8
9 struct sched_param {
10         int sched_priority;
11 };
12
13 #include <asm/param.h>  /* for HZ */
14
15 #include <linux/capability.h>
16 #include <linux/threads.h>
17 #include <linux/kernel.h>
18 #include <linux/types.h>
19 #include <linux/timex.h>
20 #include <linux/jiffies.h>
21 #include <linux/plist.h>
22 #include <linux/rbtree.h>
23 #include <linux/thread_info.h>
24 #include <linux/cpumask.h>
25 #include <linux/errno.h>
26 #include <linux/nodemask.h>
27 #include <linux/mm_types.h>
28 #include <linux/preempt.h>
29
30 #include <asm/page.h>
31 #include <asm/ptrace.h>
32 #include <linux/cputime.h>
33
34 #include <linux/smp.h>
35 #include <linux/sem.h>
36 #include <linux/shm.h>
37 #include <linux/signal.h>
38 #include <linux/compiler.h>
39 #include <linux/completion.h>
40 #include <linux/pid.h>
41 #include <linux/percpu.h>
42 #include <linux/topology.h>
43 #include <linux/proportions.h>
44 #include <linux/seccomp.h>
45 #include <linux/rcupdate.h>
46 #include <linux/rculist.h>
47 #include <linux/rtmutex.h>
48
49 #include <linux/time.h>
50 #include <linux/param.h>
51 #include <linux/resource.h>
52 #include <linux/timer.h>
53 #include <linux/hrtimer.h>
54 #include <linux/task_io_accounting.h>
55 #include <linux/latencytop.h>
56 #include <linux/cred.h>
57 #include <linux/llist.h>
58 #include <linux/uidgid.h>
59 #include <linux/gfp.h>
60 #include <linux/magic.h>
61 #include <linux/cgroup-defs.h>
62
63 #include <asm/processor.h>
64
65 #define SCHED_ATTR_SIZE_VER0    48      /* sizeof first published struct */
66
67 /*
68  * Extended scheduling parameters data structure.
69  *
70  * This is needed because the original struct sched_param can not be
71  * altered without introducing ABI issues with legacy applications
72  * (e.g., in sched_getparam()).
73  *
74  * However, the possibility of specifying more than just a priority for
75  * the tasks may be useful for a wide variety of application fields, e.g.,
76  * multimedia, streaming, automation and control, and many others.
77  *
78  * This variant (sched_attr) is meant at describing a so-called
79  * sporadic time-constrained task. In such model a task is specified by:
80  *  - the activation period or minimum instance inter-arrival time;
81  *  - the maximum (or average, depending on the actual scheduling
82  *    discipline) computation time of all instances, a.k.a. runtime;
83  *  - the deadline (relative to the actual activation time) of each
84  *    instance.
85  * Very briefly, a periodic (sporadic) task asks for the execution of
86  * some specific computation --which is typically called an instance--
87  * (at most) every period. Moreover, each instance typically lasts no more
88  * than the runtime and must be completed by time instant t equal to
89  * the instance activation time + the deadline.
90  *
91  * This is reflected by the actual fields of the sched_attr structure:
92  *
93  *  @size               size of the structure, for fwd/bwd compat.
94  *
95  *  @sched_policy       task's scheduling policy
96  *  @sched_flags        for customizing the scheduler behaviour
97  *  @sched_nice         task's nice value      (SCHED_NORMAL/BATCH)
98  *  @sched_priority     task's static priority (SCHED_FIFO/RR)
99  *  @sched_deadline     representative of the task's deadline
100  *  @sched_runtime      representative of the task's runtime
101  *  @sched_period       representative of the task's period
102  *
103  * Given this task model, there are a multiplicity of scheduling algorithms
104  * and policies, that can be used to ensure all the tasks will make their
105  * timing constraints.
106  *
107  * As of now, the SCHED_DEADLINE policy (sched_dl scheduling class) is the
108  * only user of this new interface. More information about the algorithm
109  * available in the scheduling class file or in Documentation/.
110  */
111 struct sched_attr {
112         u32 size;
113
114         u32 sched_policy;
115         u64 sched_flags;
116
117         /* SCHED_NORMAL, SCHED_BATCH */
118         s32 sched_nice;
119
120         /* SCHED_FIFO, SCHED_RR */
121         u32 sched_priority;
122
123         /* SCHED_DEADLINE */
124         u64 sched_runtime;
125         u64 sched_deadline;
126         u64 sched_period;
127 };
128
129 struct futex_pi_state;
130 struct robust_list_head;
131 struct bio_list;
132 struct fs_struct;
133 struct perf_event_context;
134 struct blk_plug;
135 struct filename;
136 struct nameidata;
137
138 #define VMACACHE_BITS 2
139 #define VMACACHE_SIZE (1U << VMACACHE_BITS)
140 #define VMACACHE_MASK (VMACACHE_SIZE - 1)
141
142 /*
143  * These are the constant used to fake the fixed-point load-average
144  * counting. Some notes:
145  *  - 11 bit fractions expand to 22 bits by the multiplies: this gives
146  *    a load-average precision of 10 bits integer + 11 bits fractional
147  *  - if you want to count load-averages more often, you need more
148  *    precision, or rounding will get you. With 2-second counting freq,
149  *    the EXP_n values would be 1981, 2034 and 2043 if still using only
150  *    11 bit fractions.
151  */
152 extern unsigned long avenrun[];         /* Load averages */
153 extern void get_avenrun(unsigned long *loads, unsigned long offset, int shift);
154
155 #define FSHIFT          11              /* nr of bits of precision */
156 #define FIXED_1         (1<<FSHIFT)     /* 1.0 as fixed-point */
157 #define LOAD_FREQ       (5*HZ+1)        /* 5 sec intervals */
158 #define EXP_1           1884            /* 1/exp(5sec/1min) as fixed-point */
159 #define EXP_5           2014            /* 1/exp(5sec/5min) */
160 #define EXP_15          2037            /* 1/exp(5sec/15min) */
161
162 #define CALC_LOAD(load,exp,n) \
163         load *= exp; \
164         load += n*(FIXED_1-exp); \
165         load >>= FSHIFT;
166
167 extern unsigned long total_forks;
168 extern int nr_threads;
169 DECLARE_PER_CPU(unsigned long, process_counts);
170 extern int nr_processes(void);
171 extern unsigned long nr_running(void);
172 extern bool single_task_running(void);
173 extern unsigned long nr_iowait(void);
174 extern unsigned long nr_iowait_cpu(int cpu);
175 extern void get_iowait_load(unsigned long *nr_waiters, unsigned long *load);
176 #ifdef CONFIG_CPU_QUIET
177 extern u64 nr_running_integral(unsigned int cpu);
178 #endif
179
180 extern void calc_global_load(unsigned long ticks);
181
182 #if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON)
183 extern void update_cpu_load_nohz(void);
184 #else
185 static inline void update_cpu_load_nohz(void) { }
186 #endif
187
188 extern unsigned long get_parent_ip(unsigned long addr);
189
190 extern void dump_cpu_task(int cpu);
191
192 struct seq_file;
193 struct cfs_rq;
194 struct task_group;
195 #ifdef CONFIG_SCHED_DEBUG
196 extern void proc_sched_show_task(struct task_struct *p, struct seq_file *m);
197 extern void proc_sched_set_task(struct task_struct *p);
198 #endif
199
200 /*
201  * Task state bitmask. NOTE! These bits are also
202  * encoded in fs/proc/array.c: get_task_state().
203  *
204  * We have two separate sets of flags: task->state
205  * is about runnability, while task->exit_state are
206  * about the task exiting. Confusing, but this way
207  * modifying one set can't modify the other one by
208  * mistake.
209  */
210 #define TASK_RUNNING            0
211 #define TASK_INTERRUPTIBLE      1
212 #define TASK_UNINTERRUPTIBLE    2
213 #define __TASK_STOPPED          4
214 #define __TASK_TRACED           8
215 /* in tsk->exit_state */
216 #define EXIT_DEAD               16
217 #define EXIT_ZOMBIE             32
218 #define EXIT_TRACE              (EXIT_ZOMBIE | EXIT_DEAD)
219 /* in tsk->state again */
220 #define TASK_DEAD               64
221 #define TASK_WAKEKILL           128
222 #define TASK_WAKING             256
223 #define TASK_PARKED             512
224 #define TASK_NOLOAD             1024
225 #define TASK_STATE_MAX          2048
226
227 #define TASK_STATE_TO_CHAR_STR "RSDTtXZxKWPN"
228
229 extern char ___assert_task_state[1 - 2*!!(
230                 sizeof(TASK_STATE_TO_CHAR_STR)-1 != ilog2(TASK_STATE_MAX)+1)];
231
232 /* Convenience macros for the sake of set_task_state */
233 #define TASK_KILLABLE           (TASK_WAKEKILL | TASK_UNINTERRUPTIBLE)
234 #define TASK_STOPPED            (TASK_WAKEKILL | __TASK_STOPPED)
235 #define TASK_TRACED             (TASK_WAKEKILL | __TASK_TRACED)
236
237 #define TASK_IDLE               (TASK_UNINTERRUPTIBLE | TASK_NOLOAD)
238
239 /* Convenience macros for the sake of wake_up */
240 #define TASK_NORMAL             (TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE)
241 #define TASK_ALL                (TASK_NORMAL | __TASK_STOPPED | __TASK_TRACED)
242
243 /* get_task_state() */
244 #define TASK_REPORT             (TASK_RUNNING | TASK_INTERRUPTIBLE | \
245                                  TASK_UNINTERRUPTIBLE | __TASK_STOPPED | \
246                                  __TASK_TRACED | EXIT_ZOMBIE | EXIT_DEAD)
247
248 #define task_is_traced(task)    ((task->state & __TASK_TRACED) != 0)
249 #define task_is_stopped(task)   ((task->state & __TASK_STOPPED) != 0)
250 #define task_is_stopped_or_traced(task) \
251                         ((task->state & (__TASK_STOPPED | __TASK_TRACED)) != 0)
252 #define task_contributes_to_load(task)  \
253                                 ((task->state & TASK_UNINTERRUPTIBLE) != 0 && \
254                                  (task->flags & PF_FROZEN) == 0 && \
255                                  (task->state & TASK_NOLOAD) == 0)
256
257 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
258
259 #define __set_task_state(tsk, state_value)                      \
260         do {                                                    \
261                 (tsk)->task_state_change = _THIS_IP_;           \
262                 (tsk)->state = (state_value);                   \
263         } while (0)
264 #define set_task_state(tsk, state_value)                        \
265         do {                                                    \
266                 (tsk)->task_state_change = _THIS_IP_;           \
267                 smp_store_mb((tsk)->state, (state_value));              \
268         } while (0)
269
270 /*
271  * set_current_state() includes a barrier so that the write of current->state
272  * is correctly serialised wrt the caller's subsequent test of whether to
273  * actually sleep:
274  *
275  *      set_current_state(TASK_UNINTERRUPTIBLE);
276  *      if (do_i_need_to_sleep())
277  *              schedule();
278  *
279  * If the caller does not need such serialisation then use __set_current_state()
280  */
281 #define __set_current_state(state_value)                        \
282         do {                                                    \
283                 current->task_state_change = _THIS_IP_;         \
284                 current->state = (state_value);                 \
285         } while (0)
286 #define set_current_state(state_value)                          \
287         do {                                                    \
288                 current->task_state_change = _THIS_IP_;         \
289                 smp_store_mb(current->state, (state_value));            \
290         } while (0)
291
292 #else
293
294 #define __set_task_state(tsk, state_value)              \
295         do { (tsk)->state = (state_value); } while (0)
296 #define set_task_state(tsk, state_value)                \
297         smp_store_mb((tsk)->state, (state_value))
298
299 /*
300  * set_current_state() includes a barrier so that the write of current->state
301  * is correctly serialised wrt the caller's subsequent test of whether to
302  * actually sleep:
303  *
304  *      set_current_state(TASK_UNINTERRUPTIBLE);
305  *      if (do_i_need_to_sleep())
306  *              schedule();
307  *
308  * If the caller does not need such serialisation then use __set_current_state()
309  */
310 #define __set_current_state(state_value)                \
311         do { current->state = (state_value); } while (0)
312 #define set_current_state(state_value)                  \
313         smp_store_mb(current->state, (state_value))
314
315 #endif
316
317 /* Task command name length */
318 #define TASK_COMM_LEN 16
319
320 enum task_event {
321         PUT_PREV_TASK   = 0,
322         PICK_NEXT_TASK  = 1,
323         TASK_WAKE       = 2,
324         TASK_MIGRATE    = 3,
325         TASK_UPDATE     = 4,
326         IRQ_UPDATE      = 5,
327 };
328
329 #include <linux/spinlock.h>
330
331 /*
332  * This serializes "schedule()" and also protects
333  * the run-queue from deletions/modifications (but
334  * _adding_ to the beginning of the run-queue has
335  * a separate lock).
336  */
337 extern rwlock_t tasklist_lock;
338 extern spinlock_t mmlist_lock;
339
340 struct task_struct;
341
342 #ifdef CONFIG_PROVE_RCU
343 extern int lockdep_tasklist_lock_is_held(void);
344 #endif /* #ifdef CONFIG_PROVE_RCU */
345
346 extern void sched_init(void);
347 extern void sched_init_smp(void);
348 extern asmlinkage void schedule_tail(struct task_struct *prev);
349 extern void init_idle(struct task_struct *idle, int cpu);
350 extern void init_idle_bootup_task(struct task_struct *idle);
351
352 extern cpumask_var_t cpu_isolated_map;
353
354 extern int runqueue_is_locked(int cpu);
355
356 #if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON)
357 extern void nohz_balance_enter_idle(int cpu);
358 extern void set_cpu_sd_state_idle(void);
359 extern int get_nohz_timer_target(void);
360 #else
361 static inline void nohz_balance_enter_idle(int cpu) { }
362 static inline void set_cpu_sd_state_idle(void) { }
363 #endif
364
365 /*
366  * Only dump TASK_* tasks. (0 for all tasks)
367  */
368 extern void show_state_filter(unsigned long state_filter);
369
370 static inline void show_state(void)
371 {
372         show_state_filter(0);
373 }
374
375 extern void show_regs(struct pt_regs *);
376
377 /*
378  * TASK is a pointer to the task whose backtrace we want to see (or NULL for current
379  * task), SP is the stack pointer of the first frame that should be shown in the back
380  * trace (or NULL if the entire call-chain of the task should be shown).
381  */
382 extern void show_stack(struct task_struct *task, unsigned long *sp);
383
384 extern void cpu_init (void);
385 extern void trap_init(void);
386 extern void update_process_times(int user);
387 extern void scheduler_tick(void);
388
389 extern void sched_show_task(struct task_struct *p);
390
391 #ifdef CONFIG_LOCKUP_DETECTOR
392 extern void touch_softlockup_watchdog(void);
393 extern void touch_softlockup_watchdog_sync(void);
394 extern void touch_all_softlockup_watchdogs(void);
395 extern int proc_dowatchdog_thresh(struct ctl_table *table, int write,
396                                   void __user *buffer,
397                                   size_t *lenp, loff_t *ppos);
398 extern unsigned int  softlockup_panic;
399 extern unsigned int  hardlockup_panic;
400 void lockup_detector_init(void);
401 #else
402 static inline void touch_softlockup_watchdog(void)
403 {
404 }
405 static inline void touch_softlockup_watchdog_sync(void)
406 {
407 }
408 static inline void touch_all_softlockup_watchdogs(void)
409 {
410 }
411 static inline void lockup_detector_init(void)
412 {
413 }
414 #endif
415
416 #ifdef CONFIG_DETECT_HUNG_TASK
417 void reset_hung_task_detector(void);
418 #else
419 static inline void reset_hung_task_detector(void)
420 {
421 }
422 #endif
423
424 /* Attach to any functions which should be ignored in wchan output. */
425 #define __sched         __attribute__((__section__(".sched.text")))
426
427 /* Linker adds these: start and end of __sched functions */
428 extern char __sched_text_start[], __sched_text_end[];
429
430 /* Is this address in the __sched functions? */
431 extern int in_sched_functions(unsigned long addr);
432
433 #define MAX_SCHEDULE_TIMEOUT    LONG_MAX
434 extern signed long schedule_timeout(signed long timeout);
435 extern signed long schedule_timeout_interruptible(signed long timeout);
436 extern signed long schedule_timeout_killable(signed long timeout);
437 extern signed long schedule_timeout_uninterruptible(signed long timeout);
438 asmlinkage void schedule(void);
439 extern void schedule_preempt_disabled(void);
440
441 extern long io_schedule_timeout(long timeout);
442
443 static inline void io_schedule(void)
444 {
445         io_schedule_timeout(MAX_SCHEDULE_TIMEOUT);
446 }
447
448 struct nsproxy;
449 struct user_namespace;
450
451 #ifdef CONFIG_MMU
452 extern void arch_pick_mmap_layout(struct mm_struct *mm);
453 extern unsigned long
454 arch_get_unmapped_area(struct file *, unsigned long, unsigned long,
455                        unsigned long, unsigned long);
456 extern unsigned long
457 arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
458                           unsigned long len, unsigned long pgoff,
459                           unsigned long flags);
460 #else
461 static inline void arch_pick_mmap_layout(struct mm_struct *mm) {}
462 #endif
463
464 #define SUID_DUMP_DISABLE       0       /* No setuid dumping */
465 #define SUID_DUMP_USER          1       /* Dump as user of process */
466 #define SUID_DUMP_ROOT          2       /* Dump as root */
467
468 /* mm flags */
469
470 /* for SUID_DUMP_* above */
471 #define MMF_DUMPABLE_BITS 2
472 #define MMF_DUMPABLE_MASK ((1 << MMF_DUMPABLE_BITS) - 1)
473
474 extern void set_dumpable(struct mm_struct *mm, int value);
475 /*
476  * This returns the actual value of the suid_dumpable flag. For things
477  * that are using this for checking for privilege transitions, it must
478  * test against SUID_DUMP_USER rather than treating it as a boolean
479  * value.
480  */
481 static inline int __get_dumpable(unsigned long mm_flags)
482 {
483         return mm_flags & MMF_DUMPABLE_MASK;
484 }
485
486 static inline int get_dumpable(struct mm_struct *mm)
487 {
488         return __get_dumpable(mm->flags);
489 }
490
491 /* coredump filter bits */
492 #define MMF_DUMP_ANON_PRIVATE   2
493 #define MMF_DUMP_ANON_SHARED    3
494 #define MMF_DUMP_MAPPED_PRIVATE 4
495 #define MMF_DUMP_MAPPED_SHARED  5
496 #define MMF_DUMP_ELF_HEADERS    6
497 #define MMF_DUMP_HUGETLB_PRIVATE 7
498 #define MMF_DUMP_HUGETLB_SHARED  8
499 #define MMF_DUMP_DAX_PRIVATE    9
500 #define MMF_DUMP_DAX_SHARED     10
501
502 #define MMF_DUMP_FILTER_SHIFT   MMF_DUMPABLE_BITS
503 #define MMF_DUMP_FILTER_BITS    9
504 #define MMF_DUMP_FILTER_MASK \
505         (((1 << MMF_DUMP_FILTER_BITS) - 1) << MMF_DUMP_FILTER_SHIFT)
506 #define MMF_DUMP_FILTER_DEFAULT \
507         ((1 << MMF_DUMP_ANON_PRIVATE) | (1 << MMF_DUMP_ANON_SHARED) |\
508          (1 << MMF_DUMP_HUGETLB_PRIVATE) | MMF_DUMP_MASK_DEFAULT_ELF)
509
510 #ifdef CONFIG_CORE_DUMP_DEFAULT_ELF_HEADERS
511 # define MMF_DUMP_MASK_DEFAULT_ELF      (1 << MMF_DUMP_ELF_HEADERS)
512 #else
513 # define MMF_DUMP_MASK_DEFAULT_ELF      0
514 #endif
515                                         /* leave room for more dump flags */
516 #define MMF_VM_MERGEABLE        16      /* KSM may merge identical pages */
517 #define MMF_VM_HUGEPAGE         17      /* set when VM_HUGEPAGE is set on vma */
518 #define MMF_EXE_FILE_CHANGED    18      /* see prctl_set_mm_exe_file() */
519
520 #define MMF_HAS_UPROBES         19      /* has uprobes */
521 #define MMF_RECALC_UPROBES      20      /* MMF_HAS_UPROBES can be wrong */
522
523 #define MMF_INIT_MASK           (MMF_DUMPABLE_MASK | MMF_DUMP_FILTER_MASK)
524
525 struct sighand_struct {
526         atomic_t                count;
527         struct k_sigaction      action[_NSIG];
528         spinlock_t              siglock;
529         wait_queue_head_t       signalfd_wqh;
530 };
531
532 struct pacct_struct {
533         int                     ac_flag;
534         long                    ac_exitcode;
535         unsigned long           ac_mem;
536         cputime_t               ac_utime, ac_stime;
537         unsigned long           ac_minflt, ac_majflt;
538 };
539
540 struct cpu_itimer {
541         cputime_t expires;
542         cputime_t incr;
543         u32 error;
544         u32 incr_error;
545 };
546
547 /**
548  * struct prev_cputime - snaphsot of system and user cputime
549  * @utime: time spent in user mode
550  * @stime: time spent in system mode
551  * @lock: protects the above two fields
552  *
553  * Stores previous user/system time values such that we can guarantee
554  * monotonicity.
555  */
556 struct prev_cputime {
557 #ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
558         cputime_t utime;
559         cputime_t stime;
560         raw_spinlock_t lock;
561 #endif
562 };
563
564 static inline void prev_cputime_init(struct prev_cputime *prev)
565 {
566 #ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
567         prev->utime = prev->stime = 0;
568         raw_spin_lock_init(&prev->lock);
569 #endif
570 }
571
572 /**
573  * struct task_cputime - collected CPU time counts
574  * @utime:              time spent in user mode, in &cputime_t units
575  * @stime:              time spent in kernel mode, in &cputime_t units
576  * @sum_exec_runtime:   total time spent on the CPU, in nanoseconds
577  *
578  * This structure groups together three kinds of CPU time that are tracked for
579  * threads and thread groups.  Most things considering CPU time want to group
580  * these counts together and treat all three of them in parallel.
581  */
582 struct task_cputime {
583         cputime_t utime;
584         cputime_t stime;
585         unsigned long long sum_exec_runtime;
586 };
587
588 /* Alternate field names when used to cache expirations. */
589 #define virt_exp        utime
590 #define prof_exp        stime
591 #define sched_exp       sum_exec_runtime
592
593 #define INIT_CPUTIME    \
594         (struct task_cputime) {                                 \
595                 .utime = 0,                                     \
596                 .stime = 0,                                     \
597                 .sum_exec_runtime = 0,                          \
598         }
599
600 /*
601  * This is the atomic variant of task_cputime, which can be used for
602  * storing and updating task_cputime statistics without locking.
603  */
604 struct task_cputime_atomic {
605         atomic64_t utime;
606         atomic64_t stime;
607         atomic64_t sum_exec_runtime;
608 };
609
610 #define INIT_CPUTIME_ATOMIC \
611         (struct task_cputime_atomic) {                          \
612                 .utime = ATOMIC64_INIT(0),                      \
613                 .stime = ATOMIC64_INIT(0),                      \
614                 .sum_exec_runtime = ATOMIC64_INIT(0),           \
615         }
616
617 #define PREEMPT_DISABLED        (PREEMPT_DISABLE_OFFSET + PREEMPT_ENABLED)
618
619 /*
620  * Disable preemption until the scheduler is running -- use an unconditional
621  * value so that it also works on !PREEMPT_COUNT kernels.
622  *
623  * Reset by start_kernel()->sched_init()->init_idle()->init_idle_preempt_count().
624  */
625 #define INIT_PREEMPT_COUNT      PREEMPT_OFFSET
626
627 /*
628  * Initial preempt_count value; reflects the preempt_count schedule invariant
629  * which states that during context switches:
630  *
631  *    preempt_count() == 2*PREEMPT_DISABLE_OFFSET
632  *
633  * Note: PREEMPT_DISABLE_OFFSET is 0 for !PREEMPT_COUNT kernels.
634  * Note: See finish_task_switch().
635  */
636 #define FORK_PREEMPT_COUNT      (2*PREEMPT_DISABLE_OFFSET + PREEMPT_ENABLED)
637
638 /**
639  * struct thread_group_cputimer - thread group interval timer counts
640  * @cputime_atomic:     atomic thread group interval timers.
641  * @running:            true when there are timers running and
642  *                      @cputime_atomic receives updates.
643  * @checking_timer:     true when a thread in the group is in the
644  *                      process of checking for thread group timers.
645  *
646  * This structure contains the version of task_cputime, above, that is
647  * used for thread group CPU timer calculations.
648  */
649 struct thread_group_cputimer {
650         struct task_cputime_atomic cputime_atomic;
651         bool running;
652         bool checking_timer;
653 };
654
655 #include <linux/rwsem.h>
656 struct autogroup;
657
658 /*
659  * NOTE! "signal_struct" does not have its own
660  * locking, because a shared signal_struct always
661  * implies a shared sighand_struct, so locking
662  * sighand_struct is always a proper superset of
663  * the locking of signal_struct.
664  */
665 struct signal_struct {
666         atomic_t                sigcnt;
667         atomic_t                live;
668         int                     nr_threads;
669         struct list_head        thread_head;
670
671         wait_queue_head_t       wait_chldexit;  /* for wait4() */
672
673         /* current thread group signal load-balancing target: */
674         struct task_struct      *curr_target;
675
676         /* shared signal handling: */
677         struct sigpending       shared_pending;
678
679         /* thread group exit support */
680         int                     group_exit_code;
681         /* overloaded:
682          * - notify group_exit_task when ->count is equal to notify_count
683          * - everyone except group_exit_task is stopped during signal delivery
684          *   of fatal signals, group_exit_task processes the signal.
685          */
686         int                     notify_count;
687         struct task_struct      *group_exit_task;
688
689         /* thread group stop support, overloads group_exit_code too */
690         int                     group_stop_count;
691         unsigned int            flags; /* see SIGNAL_* flags below */
692
693         /*
694          * PR_SET_CHILD_SUBREAPER marks a process, like a service
695          * manager, to re-parent orphan (double-forking) child processes
696          * to this process instead of 'init'. The service manager is
697          * able to receive SIGCHLD signals and is able to investigate
698          * the process until it calls wait(). All children of this
699          * process will inherit a flag if they should look for a
700          * child_subreaper process at exit.
701          */
702         unsigned int            is_child_subreaper:1;
703         unsigned int            has_child_subreaper:1;
704
705         /* POSIX.1b Interval Timers */
706         int                     posix_timer_id;
707         struct list_head        posix_timers;
708
709         /* ITIMER_REAL timer for the process */
710         struct hrtimer real_timer;
711         struct pid *leader_pid;
712         ktime_t it_real_incr;
713
714         /*
715          * ITIMER_PROF and ITIMER_VIRTUAL timers for the process, we use
716          * CPUCLOCK_PROF and CPUCLOCK_VIRT for indexing array as these
717          * values are defined to 0 and 1 respectively
718          */
719         struct cpu_itimer it[2];
720
721         /*
722          * Thread group totals for process CPU timers.
723          * See thread_group_cputimer(), et al, for details.
724          */
725         struct thread_group_cputimer cputimer;
726
727         /* Earliest-expiration cache. */
728         struct task_cputime cputime_expires;
729
730         struct list_head cpu_timers[3];
731
732         struct pid *tty_old_pgrp;
733
734         /* boolean value for session group leader */
735         int leader;
736
737         struct tty_struct *tty; /* NULL if no tty */
738
739 #ifdef CONFIG_SCHED_AUTOGROUP
740         struct autogroup *autogroup;
741 #endif
742         /*
743          * Cumulative resource counters for dead threads in the group,
744          * and for reaped dead child processes forked by this group.
745          * Live threads maintain their own counters and add to these
746          * in __exit_signal, except for the group leader.
747          */
748         seqlock_t stats_lock;
749         cputime_t utime, stime, cutime, cstime;
750         cputime_t gtime;
751         cputime_t cgtime;
752         struct prev_cputime prev_cputime;
753         unsigned long nvcsw, nivcsw, cnvcsw, cnivcsw;
754         unsigned long min_flt, maj_flt, cmin_flt, cmaj_flt;
755         unsigned long inblock, oublock, cinblock, coublock;
756         unsigned long maxrss, cmaxrss;
757         struct task_io_accounting ioac;
758
759         /*
760          * Cumulative ns of schedule CPU time fo dead threads in the
761          * group, not including a zombie group leader, (This only differs
762          * from jiffies_to_ns(utime + stime) if sched_clock uses something
763          * other than jiffies.)
764          */
765         unsigned long long sum_sched_runtime;
766
767         /*
768          * We don't bother to synchronize most readers of this at all,
769          * because there is no reader checking a limit that actually needs
770          * to get both rlim_cur and rlim_max atomically, and either one
771          * alone is a single word that can safely be read normally.
772          * getrlimit/setrlimit use task_lock(current->group_leader) to
773          * protect this instead of the siglock, because they really
774          * have no need to disable irqs.
775          */
776         struct rlimit rlim[RLIM_NLIMITS];
777
778 #ifdef CONFIG_BSD_PROCESS_ACCT
779         struct pacct_struct pacct;      /* per-process accounting information */
780 #endif
781 #ifdef CONFIG_TASKSTATS
782         struct taskstats *stats;
783 #endif
784 #ifdef CONFIG_AUDIT
785         unsigned audit_tty;
786         unsigned audit_tty_log_passwd;
787         struct tty_audit_buf *tty_audit_buf;
788 #endif
789
790         oom_flags_t oom_flags;
791         short oom_score_adj;            /* OOM kill score adjustment */
792         short oom_score_adj_min;        /* OOM kill score adjustment min value.
793                                          * Only settable by CAP_SYS_RESOURCE. */
794
795         struct mutex cred_guard_mutex;  /* guard against foreign influences on
796                                          * credential calculations
797                                          * (notably. ptrace) */
798 };
799
800 /*
801  * Bits in flags field of signal_struct.
802  */
803 #define SIGNAL_STOP_STOPPED     0x00000001 /* job control stop in effect */
804 #define SIGNAL_STOP_CONTINUED   0x00000002 /* SIGCONT since WCONTINUED reap */
805 #define SIGNAL_GROUP_EXIT       0x00000004 /* group exit in progress */
806 #define SIGNAL_GROUP_COREDUMP   0x00000008 /* coredump in progress */
807 /*
808  * Pending notifications to parent.
809  */
810 #define SIGNAL_CLD_STOPPED      0x00000010
811 #define SIGNAL_CLD_CONTINUED    0x00000020
812 #define SIGNAL_CLD_MASK         (SIGNAL_CLD_STOPPED|SIGNAL_CLD_CONTINUED)
813
814 #define SIGNAL_UNKILLABLE       0x00000040 /* for init: ignore fatal signals */
815
816 /* If true, all threads except ->group_exit_task have pending SIGKILL */
817 static inline int signal_group_exit(const struct signal_struct *sig)
818 {
819         return  (sig->flags & SIGNAL_GROUP_EXIT) ||
820                 (sig->group_exit_task != NULL);
821 }
822
823 /*
824  * Some day this will be a full-fledged user tracking system..
825  */
826 struct user_struct {
827         atomic_t __count;       /* reference count */
828         atomic_t processes;     /* How many processes does this user have? */
829         atomic_t sigpending;    /* How many pending signals does this user have? */
830 #ifdef CONFIG_INOTIFY_USER
831         atomic_t inotify_watches; /* How many inotify watches does this user have? */
832         atomic_t inotify_devs;  /* How many inotify devs does this user have opened? */
833 #endif
834 #ifdef CONFIG_FANOTIFY
835         atomic_t fanotify_listeners;
836 #endif
837 #ifdef CONFIG_EPOLL
838         atomic_long_t epoll_watches; /* The number of file descriptors currently watched */
839 #endif
840 #ifdef CONFIG_POSIX_MQUEUE
841         /* protected by mq_lock */
842         unsigned long mq_bytes; /* How many bytes can be allocated to mqueue? */
843 #endif
844         unsigned long locked_shm; /* How many pages of mlocked shm ? */
845         unsigned long unix_inflight;    /* How many files in flight in unix sockets */
846         atomic_long_t pipe_bufs;  /* how many pages are allocated in pipe buffers */
847
848 #ifdef CONFIG_KEYS
849         struct key *uid_keyring;        /* UID specific keyring */
850         struct key *session_keyring;    /* UID's default session keyring */
851 #endif
852
853         /* Hash table maintenance information */
854         struct hlist_node uidhash_node;
855         kuid_t uid;
856
857 #if defined(CONFIG_PERF_EVENTS) || defined(CONFIG_BPF_SYSCALL)
858         atomic_long_t locked_vm;
859 #endif
860 };
861
862 extern int uids_sysfs_init(void);
863
864 extern struct user_struct *find_user(kuid_t);
865
866 extern struct user_struct root_user;
867 #define INIT_USER (&root_user)
868
869
870 struct backing_dev_info;
871 struct reclaim_state;
872
873 #ifdef CONFIG_SCHED_INFO
874 struct sched_info {
875         /* cumulative counters */
876         unsigned long pcount;         /* # of times run on this cpu */
877         unsigned long long run_delay; /* time spent waiting on a runqueue */
878
879         /* timestamps */
880         unsigned long long last_arrival,/* when we last ran on a cpu */
881                            last_queued; /* when we were last queued to run */
882 };
883 #endif /* CONFIG_SCHED_INFO */
884
885 #ifdef CONFIG_TASK_DELAY_ACCT
886 struct task_delay_info {
887         spinlock_t      lock;
888         unsigned int    flags;  /* Private per-task flags */
889
890         /* For each stat XXX, add following, aligned appropriately
891          *
892          * struct timespec XXX_start, XXX_end;
893          * u64 XXX_delay;
894          * u32 XXX_count;
895          *
896          * Atomicity of updates to XXX_delay, XXX_count protected by
897          * single lock above (split into XXX_lock if contention is an issue).
898          */
899
900         /*
901          * XXX_count is incremented on every XXX operation, the delay
902          * associated with the operation is added to XXX_delay.
903          * XXX_delay contains the accumulated delay time in nanoseconds.
904          */
905         u64 blkio_start;        /* Shared by blkio, swapin */
906         u64 blkio_delay;        /* wait for sync block io completion */
907         u64 swapin_delay;       /* wait for swapin block io completion */
908         u32 blkio_count;        /* total count of the number of sync block */
909                                 /* io operations performed */
910         u32 swapin_count;       /* total count of the number of swapin block */
911                                 /* io operations performed */
912
913         u64 freepages_start;
914         u64 freepages_delay;    /* wait for memory reclaim */
915         u32 freepages_count;    /* total count of memory reclaim */
916 };
917 #endif  /* CONFIG_TASK_DELAY_ACCT */
918
919 static inline int sched_info_on(void)
920 {
921 #ifdef CONFIG_SCHEDSTATS
922         return 1;
923 #elif defined(CONFIG_TASK_DELAY_ACCT)
924         extern int delayacct_on;
925         return delayacct_on;
926 #else
927         return 0;
928 #endif
929 }
930
931 enum cpu_idle_type {
932         CPU_IDLE,
933         CPU_NOT_IDLE,
934         CPU_NEWLY_IDLE,
935         CPU_MAX_IDLE_TYPES
936 };
937
938 /*
939  * Increase resolution of cpu_capacity calculations
940  */
941 #define SCHED_CAPACITY_SHIFT    10
942 #define SCHED_CAPACITY_SCALE    (1L << SCHED_CAPACITY_SHIFT)
943
944 struct sched_capacity_reqs {
945         unsigned long cfs;
946         unsigned long rt;
947         unsigned long dl;
948
949         unsigned long total;
950 };
951
952 /*
953  * Wake-queues are lists of tasks with a pending wakeup, whose
954  * callers have already marked the task as woken internally,
955  * and can thus carry on. A common use case is being able to
956  * do the wakeups once the corresponding user lock as been
957  * released.
958  *
959  * We hold reference to each task in the list across the wakeup,
960  * thus guaranteeing that the memory is still valid by the time
961  * the actual wakeups are performed in wake_up_q().
962  *
963  * One per task suffices, because there's never a need for a task to be
964  * in two wake queues simultaneously; it is forbidden to abandon a task
965  * in a wake queue (a call to wake_up_q() _must_ follow), so if a task is
966  * already in a wake queue, the wakeup will happen soon and the second
967  * waker can just skip it.
968  *
969  * The WAKE_Q macro declares and initializes the list head.
970  * wake_up_q() does NOT reinitialize the list; it's expected to be
971  * called near the end of a function, where the fact that the queue is
972  * not used again will be easy to see by inspection.
973  *
974  * Note that this can cause spurious wakeups. schedule() callers
975  * must ensure the call is done inside a loop, confirming that the
976  * wakeup condition has in fact occurred.
977  */
978 struct wake_q_node {
979         struct wake_q_node *next;
980 };
981
982 struct wake_q_head {
983         struct wake_q_node *first;
984         struct wake_q_node **lastp;
985 };
986
987 #define WAKE_Q_TAIL ((struct wake_q_node *) 0x01)
988
989 #define WAKE_Q(name)                                    \
990         struct wake_q_head name = { WAKE_Q_TAIL, &name.first }
991
992 extern void wake_q_add(struct wake_q_head *head,
993                        struct task_struct *task);
994 extern void wake_up_q(struct wake_q_head *head);
995
996 /*
997  * sched-domains (multiprocessor balancing) declarations:
998  */
999 #ifdef CONFIG_SMP
1000 #define SD_LOAD_BALANCE         0x0001  /* Do load balancing on this domain. */
1001 #define SD_BALANCE_NEWIDLE      0x0002  /* Balance when about to become idle */
1002 #define SD_BALANCE_EXEC         0x0004  /* Balance on exec */
1003 #define SD_BALANCE_FORK         0x0008  /* Balance on fork, clone */
1004 #define SD_BALANCE_WAKE         0x0010  /* Balance on wakeup */
1005 #define SD_WAKE_AFFINE          0x0020  /* Wake task to waking CPU */
1006 #define SD_ASYM_CPUCAPACITY     0x0040  /* Groups have different max cpu capacities */
1007 #define SD_SHARE_CPUCAPACITY    0x0080  /* Domain members share cpu capacity */
1008 #define SD_SHARE_POWERDOMAIN    0x0100  /* Domain members share power domain */
1009 #define SD_SHARE_PKG_RESOURCES  0x0200  /* Domain members share cpu pkg resources */
1010 #define SD_SERIALIZE            0x0400  /* Only a single load balancing instance */
1011 #define SD_ASYM_PACKING         0x0800  /* Place busy groups earlier in the domain */
1012 #define SD_PREFER_SIBLING       0x1000  /* Prefer to place tasks in a sibling domain */
1013 #define SD_OVERLAP              0x2000  /* sched_domains of this level overlap */
1014 #define SD_NUMA                 0x4000  /* cross-node balancing */
1015 #define SD_SHARE_CAP_STATES     0x8000  /* Domain members share capacity state */
1016
1017 #ifdef CONFIG_SCHED_SMT
1018 static inline int cpu_smt_flags(void)
1019 {
1020         return SD_SHARE_CPUCAPACITY | SD_SHARE_PKG_RESOURCES;
1021 }
1022 #endif
1023
1024 #ifdef CONFIG_SCHED_MC
1025 static inline int cpu_core_flags(void)
1026 {
1027         return SD_SHARE_PKG_RESOURCES;
1028 }
1029 #endif
1030
1031 #ifdef CONFIG_NUMA
1032 static inline int cpu_numa_flags(void)
1033 {
1034         return SD_NUMA;
1035 }
1036 #endif
1037
1038 struct sched_domain_attr {
1039         int relax_domain_level;
1040 };
1041
1042 #define SD_ATTR_INIT    (struct sched_domain_attr) {    \
1043         .relax_domain_level = -1,                       \
1044 }
1045
1046 extern int sched_domain_level_max;
1047
1048 struct capacity_state {
1049         unsigned long cap;      /* compute capacity */
1050         unsigned long power;    /* power consumption at this compute capacity */
1051 };
1052
1053 struct idle_state {
1054         unsigned long power;     /* power consumption in this idle state */
1055 };
1056
1057 struct sched_group_energy {
1058         unsigned int nr_idle_states;    /* number of idle states */
1059         struct idle_state *idle_states; /* ptr to idle state array */
1060         unsigned int nr_cap_states;     /* number of capacity states */
1061         struct capacity_state *cap_states; /* ptr to capacity state array */
1062 };
1063
1064 unsigned long capacity_curr_of(int cpu);
1065
1066 struct sched_group;
1067
1068 struct eas_stats {
1069         /* select_idle_sibling() stats */
1070         u64 sis_attempts;
1071         u64 sis_idle;
1072         u64 sis_cache_affine;
1073         u64 sis_suff_cap;
1074         u64 sis_idle_cpu;
1075         u64 sis_count;
1076
1077         /* select_energy_cpu_brute() stats */
1078         u64 secb_attempts;
1079         u64 secb_sync;
1080         u64 secb_idle_bt;
1081         u64 secb_insuff_cap;
1082         u64 secb_no_nrg_sav;
1083         u64 secb_nrg_sav;
1084         u64 secb_count;
1085
1086         /* find_best_target() stats */
1087         u64 fbt_attempts;
1088         u64 fbt_no_cpu;
1089         u64 fbt_no_sd;
1090         u64 fbt_pref_idle;
1091         u64 fbt_count;
1092
1093         /* cas */
1094         /* select_task_rq_fair() stats */
1095         u64 cas_attempts;
1096         u64 cas_count;
1097 };
1098
1099 struct sched_domain {
1100         /* These fields must be setup */
1101         struct sched_domain *parent;    /* top domain must be null terminated */
1102         struct sched_domain *child;     /* bottom domain must be null terminated */
1103         struct sched_group *groups;     /* the balancing groups of the domain */
1104         unsigned long min_interval;     /* Minimum balance interval ms */
1105         unsigned long max_interval;     /* Maximum balance interval ms */
1106         unsigned int busy_factor;       /* less balancing by factor if busy */
1107         unsigned int imbalance_pct;     /* No balance until over watermark */
1108         unsigned int cache_nice_tries;  /* Leave cache hot tasks for # tries */
1109         unsigned int busy_idx;
1110         unsigned int idle_idx;
1111         unsigned int newidle_idx;
1112         unsigned int wake_idx;
1113         unsigned int forkexec_idx;
1114         unsigned int smt_gain;
1115
1116         int nohz_idle;                  /* NOHZ IDLE status */
1117         int flags;                      /* See SD_* */
1118         int level;
1119
1120         /* Runtime fields. */
1121         unsigned long last_balance;     /* init to jiffies. units in jiffies */
1122         unsigned int balance_interval;  /* initialise to 1. units in ms. */
1123         unsigned int nr_balance_failed; /* initialise to 0 */
1124
1125         /* idle_balance() stats */
1126         u64 max_newidle_lb_cost;
1127         unsigned long next_decay_max_lb_cost;
1128
1129 #ifdef CONFIG_SCHEDSTATS
1130         /* load_balance() stats */
1131         unsigned int lb_count[CPU_MAX_IDLE_TYPES];
1132         unsigned int lb_failed[CPU_MAX_IDLE_TYPES];
1133         unsigned int lb_balanced[CPU_MAX_IDLE_TYPES];
1134         unsigned int lb_imbalance[CPU_MAX_IDLE_TYPES];
1135         unsigned int lb_gained[CPU_MAX_IDLE_TYPES];
1136         unsigned int lb_hot_gained[CPU_MAX_IDLE_TYPES];
1137         unsigned int lb_nobusyg[CPU_MAX_IDLE_TYPES];
1138         unsigned int lb_nobusyq[CPU_MAX_IDLE_TYPES];
1139
1140         /* Active load balancing */
1141         unsigned int alb_count;
1142         unsigned int alb_failed;
1143         unsigned int alb_pushed;
1144
1145         /* SD_BALANCE_EXEC stats */
1146         unsigned int sbe_count;
1147         unsigned int sbe_balanced;
1148         unsigned int sbe_pushed;
1149
1150         /* SD_BALANCE_FORK stats */
1151         unsigned int sbf_count;
1152         unsigned int sbf_balanced;
1153         unsigned int sbf_pushed;
1154
1155         /* try_to_wake_up() stats */
1156         unsigned int ttwu_wake_remote;
1157         unsigned int ttwu_move_affine;
1158         unsigned int ttwu_move_balance;
1159
1160         struct eas_stats eas_stats;
1161 #endif
1162 #ifdef CONFIG_SCHED_DEBUG
1163         char *name;
1164 #endif
1165         union {
1166                 void *private;          /* used during construction */
1167                 struct rcu_head rcu;    /* used during destruction */
1168         };
1169
1170         unsigned int span_weight;
1171         /*
1172          * Span of all CPUs in this domain.
1173          *
1174          * NOTE: this field is variable length. (Allocated dynamically
1175          * by attaching extra space to the end of the structure,
1176          * depending on how many CPUs the kernel has booted up with)
1177          */
1178         unsigned long span[0];
1179 };
1180
1181 static inline struct cpumask *sched_domain_span(struct sched_domain *sd)
1182 {
1183         return to_cpumask(sd->span);
1184 }
1185
1186 extern void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
1187                                     struct sched_domain_attr *dattr_new);
1188
1189 /* Allocate an array of sched domains, for partition_sched_domains(). */
1190 cpumask_var_t *alloc_sched_domains(unsigned int ndoms);
1191 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms);
1192
1193 bool cpus_share_cache(int this_cpu, int that_cpu);
1194
1195 typedef const struct cpumask *(*sched_domain_mask_f)(int cpu);
1196 typedef int (*sched_domain_flags_f)(void);
1197 typedef
1198 const struct sched_group_energy * const(*sched_domain_energy_f)(int cpu);
1199
1200 #define SDTL_OVERLAP    0x01
1201
1202 struct sd_data {
1203         struct sched_domain **__percpu sd;
1204         struct sched_group **__percpu sg;
1205         struct sched_group_capacity **__percpu sgc;
1206 };
1207
1208 struct sched_domain_topology_level {
1209         sched_domain_mask_f mask;
1210         sched_domain_flags_f sd_flags;
1211         sched_domain_energy_f energy;
1212         int                 flags;
1213         int                 numa_level;
1214         struct sd_data      data;
1215 #ifdef CONFIG_SCHED_DEBUG
1216         char                *name;
1217 #endif
1218 };
1219
1220 extern void set_sched_topology(struct sched_domain_topology_level *tl);
1221 extern void wake_up_if_idle(int cpu);
1222
1223 #ifdef CONFIG_SCHED_DEBUG
1224 # define SD_INIT_NAME(type)             .name = #type
1225 #else
1226 # define SD_INIT_NAME(type)
1227 #endif
1228
1229 #else /* CONFIG_SMP */
1230
1231 struct sched_domain_attr;
1232
1233 static inline void
1234 partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
1235                         struct sched_domain_attr *dattr_new)
1236 {
1237 }
1238
1239 static inline bool cpus_share_cache(int this_cpu, int that_cpu)
1240 {
1241         return true;
1242 }
1243
1244 #endif  /* !CONFIG_SMP */
1245
1246
1247 struct io_context;                      /* See blkdev.h */
1248
1249
1250 #ifdef ARCH_HAS_PREFETCH_SWITCH_STACK
1251 extern void prefetch_stack(struct task_struct *t);
1252 #else
1253 static inline void prefetch_stack(struct task_struct *t) { }
1254 #endif
1255
1256 struct audit_context;           /* See audit.c */
1257 struct mempolicy;
1258 struct pipe_inode_info;
1259 struct uts_namespace;
1260
1261 struct load_weight {
1262         unsigned long weight;
1263         u32 inv_weight;
1264 };
1265
1266 /*
1267  * The load_avg/util_avg accumulates an infinite geometric series.
1268  * 1) load_avg factors frequency scaling into the amount of time that a
1269  * sched_entity is runnable on a rq into its weight. For cfs_rq, it is the
1270  * aggregated such weights of all runnable and blocked sched_entities.
1271  * 2) util_avg factors frequency and cpu scaling into the amount of time
1272  * that a sched_entity is running on a CPU, in the range [0..SCHED_LOAD_SCALE].
1273  * For cfs_rq, it is the aggregated such times of all runnable and
1274  * blocked sched_entities.
1275  * The 64 bit load_sum can:
1276  * 1) for cfs_rq, afford 4353082796 (=2^64/47742/88761) entities with
1277  * the highest weight (=88761) always runnable, we should not overflow
1278  * 2) for entity, support any load.weight always runnable
1279  */
1280 struct sched_avg {
1281         u64 last_update_time, load_sum;
1282         u32 util_sum, period_contrib;
1283         unsigned long load_avg, util_avg;
1284 };
1285
1286 #ifdef CONFIG_SCHEDSTATS
1287 struct sched_statistics {
1288         u64                     wait_start;
1289         u64                     wait_max;
1290         u64                     wait_count;
1291         u64                     wait_sum;
1292         u64                     iowait_count;
1293         u64                     iowait_sum;
1294
1295         u64                     sleep_start;
1296         u64                     sleep_max;
1297         s64                     sum_sleep_runtime;
1298
1299         u64                     block_start;
1300         u64                     block_max;
1301         u64                     exec_max;
1302         u64                     slice_max;
1303
1304         u64                     nr_migrations_cold;
1305         u64                     nr_failed_migrations_affine;
1306         u64                     nr_failed_migrations_running;
1307         u64                     nr_failed_migrations_hot;
1308         u64                     nr_forced_migrations;
1309
1310         u64                     nr_wakeups;
1311         u64                     nr_wakeups_sync;
1312         u64                     nr_wakeups_migrate;
1313         u64                     nr_wakeups_local;
1314         u64                     nr_wakeups_remote;
1315         u64                     nr_wakeups_affine;
1316         u64                     nr_wakeups_affine_attempts;
1317         u64                     nr_wakeups_passive;
1318         u64                     nr_wakeups_idle;
1319
1320         /* select_idle_sibling() */
1321         u64                     nr_wakeups_sis_attempts;
1322         u64                     nr_wakeups_sis_idle;
1323         u64                     nr_wakeups_sis_cache_affine;
1324         u64                     nr_wakeups_sis_suff_cap;
1325         u64                     nr_wakeups_sis_idle_cpu;
1326         u64                     nr_wakeups_sis_count;
1327
1328         /* energy_aware_wake_cpu() */
1329         u64                     nr_wakeups_secb_attempts;
1330         u64                     nr_wakeups_secb_sync;
1331         u64                     nr_wakeups_secb_idle_bt;
1332         u64                     nr_wakeups_secb_insuff_cap;
1333         u64                     nr_wakeups_secb_no_nrg_sav;
1334         u64                     nr_wakeups_secb_nrg_sav;
1335         u64                     nr_wakeups_secb_count;
1336
1337         /* find_best_target() */
1338         u64                     nr_wakeups_fbt_attempts;
1339         u64                     nr_wakeups_fbt_no_cpu;
1340         u64                     nr_wakeups_fbt_no_sd;
1341         u64                     nr_wakeups_fbt_pref_idle;
1342         u64                     nr_wakeups_fbt_count;
1343
1344         /* cas */
1345         /* select_task_rq_fair() */
1346         u64                     nr_wakeups_cas_attempts;
1347         u64                     nr_wakeups_cas_count;
1348 };
1349 #endif
1350
1351 #ifdef CONFIG_SCHED_WALT
1352 #define RAVG_HIST_SIZE_MAX  5
1353
1354 /* ravg represents frequency scaled cpu-demand of tasks */
1355 struct ravg {
1356         /*
1357          * 'mark_start' marks the beginning of an event (task waking up, task
1358          * starting to execute, task being preempted) within a window
1359          *
1360          * 'sum' represents how runnable a task has been within current
1361          * window. It incorporates both running time and wait time and is
1362          * frequency scaled.
1363          *
1364          * 'sum_history' keeps track of history of 'sum' seen over previous
1365          * RAVG_HIST_SIZE windows. Windows where task was entirely sleeping are
1366          * ignored.
1367          *
1368          * 'demand' represents maximum sum seen over previous
1369          * sysctl_sched_ravg_hist_size windows. 'demand' could drive frequency
1370          * demand for tasks.
1371          *
1372          * 'curr_window' represents task's contribution to cpu busy time
1373          * statistics (rq->curr_runnable_sum) in current window
1374          *
1375          * 'prev_window' represents task's contribution to cpu busy time
1376          * statistics (rq->prev_runnable_sum) in previous window
1377          */
1378         u64 mark_start;
1379         u32 sum, demand;
1380         u32 sum_history[RAVG_HIST_SIZE_MAX];
1381         u32 curr_window, prev_window;
1382         u16 active_windows;
1383 };
1384 #endif
1385
1386 struct sched_entity {
1387         struct load_weight      load;           /* for load-balancing */
1388         struct rb_node          run_node;
1389         struct list_head        group_node;
1390         unsigned int            on_rq;
1391
1392         u64                     exec_start;
1393         u64                     sum_exec_runtime;
1394         u64                     vruntime;
1395         u64                     prev_sum_exec_runtime;
1396
1397         u64                     nr_migrations;
1398
1399 #ifdef CONFIG_SCHEDSTATS
1400         struct sched_statistics statistics;
1401 #endif
1402
1403 #ifdef CONFIG_FAIR_GROUP_SCHED
1404         int                     depth;
1405         struct sched_entity     *parent;
1406         /* rq on which this entity is (to be) queued: */
1407         struct cfs_rq           *cfs_rq;
1408         /* rq "owned" by this entity/group: */
1409         struct cfs_rq           *my_q;
1410 #endif
1411
1412 #ifdef CONFIG_SMP
1413         /* Per entity load average tracking */
1414         struct sched_avg        avg;
1415 #endif
1416 };
1417
1418 struct sched_rt_entity {
1419         struct list_head run_list;
1420         unsigned long timeout;
1421         unsigned long watchdog_stamp;
1422         unsigned int time_slice;
1423
1424         struct sched_rt_entity *back;
1425 #ifdef CONFIG_RT_GROUP_SCHED
1426         struct sched_rt_entity  *parent;
1427         /* rq on which this entity is (to be) queued: */
1428         struct rt_rq            *rt_rq;
1429         /* rq "owned" by this entity/group: */
1430         struct rt_rq            *my_q;
1431 #endif
1432 };
1433
1434 struct sched_dl_entity {
1435         struct rb_node  rb_node;
1436
1437         /*
1438          * Original scheduling parameters. Copied here from sched_attr
1439          * during sched_setattr(), they will remain the same until
1440          * the next sched_setattr().
1441          */
1442         u64 dl_runtime;         /* maximum runtime for each instance    */
1443         u64 dl_deadline;        /* relative deadline of each instance   */
1444         u64 dl_period;          /* separation of two instances (period) */
1445         u64 dl_bw;              /* dl_runtime / dl_deadline             */
1446
1447         /*
1448          * Actual scheduling parameters. Initialized with the values above,
1449          * they are continously updated during task execution. Note that
1450          * the remaining runtime could be < 0 in case we are in overrun.
1451          */
1452         s64 runtime;            /* remaining runtime for this instance  */
1453         u64 deadline;           /* absolute deadline for this instance  */
1454         unsigned int flags;     /* specifying the scheduler behaviour   */
1455
1456         /*
1457          * Some bool flags:
1458          *
1459          * @dl_throttled tells if we exhausted the runtime. If so, the
1460          * task has to wait for a replenishment to be performed at the
1461          * next firing of dl_timer.
1462          *
1463          * @dl_new tells if a new instance arrived. If so we must
1464          * start executing it with full runtime and reset its absolute
1465          * deadline;
1466          *
1467          * @dl_boosted tells if we are boosted due to DI. If so we are
1468          * outside bandwidth enforcement mechanism (but only until we
1469          * exit the critical section);
1470          *
1471          * @dl_yielded tells if task gave up the cpu before consuming
1472          * all its available runtime during the last job.
1473          */
1474         int dl_throttled, dl_new, dl_boosted, dl_yielded;
1475
1476         /*
1477          * Bandwidth enforcement timer. Each -deadline task has its
1478          * own bandwidth to be enforced, thus we need one timer per task.
1479          */
1480         struct hrtimer dl_timer;
1481 };
1482
1483 union rcu_special {
1484         struct {
1485                 u8 blocked;
1486                 u8 need_qs;
1487                 u8 exp_need_qs;
1488                 u8 pad; /* Otherwise the compiler can store garbage here. */
1489         } b; /* Bits. */
1490         u32 s; /* Set of bits. */
1491 };
1492 struct rcu_node;
1493
1494 enum perf_event_task_context {
1495         perf_invalid_context = -1,
1496         perf_hw_context = 0,
1497         perf_sw_context,
1498         perf_nr_task_contexts,
1499 };
1500
1501 /* Track pages that require TLB flushes */
1502 struct tlbflush_unmap_batch {
1503         /*
1504          * Each bit set is a CPU that potentially has a TLB entry for one of
1505          * the PFNs being flushed. See set_tlb_ubc_flush_pending().
1506          */
1507         struct cpumask cpumask;
1508
1509         /* True if any bit in cpumask is set */
1510         bool flush_required;
1511
1512         /*
1513          * If true then the PTE was dirty when unmapped. The entry must be
1514          * flushed before IO is initiated or a stale TLB entry potentially
1515          * allows an update without redirtying the page.
1516          */
1517         bool writable;
1518 };
1519
1520 struct task_struct {
1521 #ifdef CONFIG_THREAD_INFO_IN_TASK
1522         /*
1523          * For reasons of header soup (see current_thread_info()), this
1524          * must be the first element of task_struct.
1525          */
1526         struct thread_info thread_info;
1527 #endif
1528         volatile long state;    /* -1 unrunnable, 0 runnable, >0 stopped */
1529         void *stack;
1530         atomic_t usage;
1531         unsigned int flags;     /* per process flags, defined below */
1532         unsigned int ptrace;
1533
1534 #ifdef CONFIG_SMP
1535         struct llist_node wake_entry;
1536         int on_cpu;
1537 #ifdef CONFIG_THREAD_INFO_IN_TASK
1538         unsigned int cpu;       /* current CPU */
1539 #endif
1540         unsigned int wakee_flips;
1541         unsigned long wakee_flip_decay_ts;
1542         struct task_struct *last_wakee;
1543
1544         int wake_cpu;
1545 #endif
1546         int on_rq;
1547
1548         int prio, static_prio, normal_prio;
1549         unsigned int rt_priority;
1550         const struct sched_class *sched_class;
1551         struct sched_entity se;
1552         struct sched_rt_entity rt;
1553 #ifdef CONFIG_SCHED_WALT
1554         struct ravg ravg;
1555         /*
1556          * 'init_load_pct' represents the initial task load assigned to children
1557          * of this task
1558          */
1559         u32 init_load_pct;
1560 #endif
1561
1562 #ifdef CONFIG_CGROUP_SCHED
1563         struct task_group *sched_task_group;
1564 #endif
1565         struct sched_dl_entity dl;
1566
1567 #ifdef CONFIG_PREEMPT_NOTIFIERS
1568         /* list of struct preempt_notifier: */
1569         struct hlist_head preempt_notifiers;
1570 #endif
1571
1572 #ifdef CONFIG_BLK_DEV_IO_TRACE
1573         unsigned int btrace_seq;
1574 #endif
1575
1576         unsigned int policy;
1577         int nr_cpus_allowed;
1578         cpumask_t cpus_allowed;
1579
1580 #ifdef CONFIG_PREEMPT_RCU
1581         int rcu_read_lock_nesting;
1582         union rcu_special rcu_read_unlock_special;
1583         struct list_head rcu_node_entry;
1584         struct rcu_node *rcu_blocked_node;
1585 #endif /* #ifdef CONFIG_PREEMPT_RCU */
1586 #ifdef CONFIG_TASKS_RCU
1587         unsigned long rcu_tasks_nvcsw;
1588         bool rcu_tasks_holdout;
1589         struct list_head rcu_tasks_holdout_list;
1590         int rcu_tasks_idle_cpu;
1591 #endif /* #ifdef CONFIG_TASKS_RCU */
1592
1593 #ifdef CONFIG_SCHED_INFO
1594         struct sched_info sched_info;
1595 #endif
1596
1597         struct list_head tasks;
1598 #ifdef CONFIG_SMP
1599         struct plist_node pushable_tasks;
1600         struct rb_node pushable_dl_tasks;
1601 #endif
1602
1603         struct mm_struct *mm, *active_mm;
1604         /* per-thread vma caching */
1605         u32 vmacache_seqnum;
1606         struct vm_area_struct *vmacache[VMACACHE_SIZE];
1607 #if defined(SPLIT_RSS_COUNTING)
1608         struct task_rss_stat    rss_stat;
1609 #endif
1610 /* task state */
1611         int exit_state;
1612         int exit_code, exit_signal;
1613         int pdeath_signal;  /*  The signal sent when the parent dies  */
1614         unsigned long jobctl;   /* JOBCTL_*, siglock protected */
1615
1616         /* Used for emulating ABI behavior of previous Linux versions */
1617         unsigned int personality;
1618
1619         /* scheduler bits, serialized by scheduler locks */
1620         unsigned sched_reset_on_fork:1;
1621         unsigned sched_contributes_to_load:1;
1622         unsigned sched_migrated:1;
1623         unsigned :0; /* force alignment to the next boundary */
1624
1625         /* unserialized, strictly 'current' */
1626         unsigned in_execve:1; /* bit to tell LSMs we're in execve */
1627         unsigned in_iowait:1;
1628 #ifdef CONFIG_MEMCG
1629         unsigned memcg_may_oom:1;
1630 #endif
1631 #ifdef CONFIG_MEMCG_KMEM
1632         unsigned memcg_kmem_skip_account:1;
1633 #endif
1634 #ifdef CONFIG_COMPAT_BRK
1635         unsigned brk_randomized:1;
1636 #endif
1637 #ifdef CONFIG_CGROUPS
1638         /* disallow userland-initiated cgroup migration */
1639         unsigned no_cgroup_migration:1;
1640 #endif
1641
1642         unsigned long atomic_flags; /* Flags needing atomic access. */
1643
1644         struct restart_block restart_block;
1645
1646         pid_t pid;
1647         pid_t tgid;
1648
1649 #ifdef CONFIG_CC_STACKPROTECTOR
1650         /* Canary value for the -fstack-protector gcc feature */
1651         unsigned long stack_canary;
1652 #endif
1653         /*
1654          * pointers to (original) parent process, youngest child, younger sibling,
1655          * older sibling, respectively.  (p->father can be replaced with
1656          * p->real_parent->pid)
1657          */
1658         struct task_struct __rcu *real_parent; /* real parent process */
1659         struct task_struct __rcu *parent; /* recipient of SIGCHLD, wait4() reports */
1660         /*
1661          * children/sibling forms the list of my natural children
1662          */
1663         struct list_head children;      /* list of my children */
1664         struct list_head sibling;       /* linkage in my parent's children list */
1665         struct task_struct *group_leader;       /* threadgroup leader */
1666
1667         /*
1668          * ptraced is the list of tasks this task is using ptrace on.
1669          * This includes both natural children and PTRACE_ATTACH targets.
1670          * p->ptrace_entry is p's link on the p->parent->ptraced list.
1671          */
1672         struct list_head ptraced;
1673         struct list_head ptrace_entry;
1674
1675         /* PID/PID hash table linkage. */
1676         struct pid_link pids[PIDTYPE_MAX];
1677         struct list_head thread_group;
1678         struct list_head thread_node;
1679
1680         struct completion *vfork_done;          /* for vfork() */
1681         int __user *set_child_tid;              /* CLONE_CHILD_SETTID */
1682         int __user *clear_child_tid;            /* CLONE_CHILD_CLEARTID */
1683
1684         cputime_t utime, stime, utimescaled, stimescaled;
1685         cputime_t gtime;
1686         struct prev_cputime prev_cputime;
1687 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1688         seqlock_t vtime_seqlock;
1689         unsigned long long vtime_snap;
1690         enum {
1691                 VTIME_SLEEPING = 0,
1692                 VTIME_USER,
1693                 VTIME_SYS,
1694         } vtime_snap_whence;
1695 #endif
1696         unsigned long nvcsw, nivcsw; /* context switch counts */
1697         u64 start_time;         /* monotonic time in nsec */
1698         u64 real_start_time;    /* boot based time in nsec */
1699 /* mm fault and swap info: this can arguably be seen as either mm-specific or thread-specific */
1700         unsigned long min_flt, maj_flt;
1701
1702         struct task_cputime cputime_expires;
1703         struct list_head cpu_timers[3];
1704
1705 /* process credentials */
1706         const struct cred __rcu *ptracer_cred; /* Tracer's credentials at attach */
1707         const struct cred __rcu *real_cred; /* objective and real subjective task
1708                                          * credentials (COW) */
1709         const struct cred __rcu *cred;  /* effective (overridable) subjective task
1710                                          * credentials (COW) */
1711         char comm[TASK_COMM_LEN]; /* executable name excluding path
1712                                      - access with [gs]et_task_comm (which lock
1713                                        it with task_lock())
1714                                      - initialized normally by setup_new_exec */
1715 /* file system info */
1716         struct nameidata *nameidata;
1717 #ifdef CONFIG_SYSVIPC
1718 /* ipc stuff */
1719         struct sysv_sem sysvsem;
1720         struct sysv_shm sysvshm;
1721 #endif
1722 #ifdef CONFIG_DETECT_HUNG_TASK
1723 /* hung task detection */
1724         unsigned long last_switch_count;
1725 #endif
1726 /* filesystem information */
1727         struct fs_struct *fs;
1728 /* open file information */
1729         struct files_struct *files;
1730 /* namespaces */
1731         struct nsproxy *nsproxy;
1732 /* signal handlers */
1733         struct signal_struct *signal;
1734         struct sighand_struct *sighand;
1735
1736         sigset_t blocked, real_blocked;
1737         sigset_t saved_sigmask; /* restored if set_restore_sigmask() was used */
1738         struct sigpending pending;
1739
1740         unsigned long sas_ss_sp;
1741         size_t sas_ss_size;
1742
1743         struct callback_head *task_works;
1744
1745         struct audit_context *audit_context;
1746 #ifdef CONFIG_AUDITSYSCALL
1747         kuid_t loginuid;
1748         unsigned int sessionid;
1749 #endif
1750         struct seccomp seccomp;
1751
1752 /* Thread group tracking */
1753         u32 parent_exec_id;
1754         u32 self_exec_id;
1755 /* Protection of (de-)allocation: mm, files, fs, tty, keyrings, mems_allowed,
1756  * mempolicy */
1757         spinlock_t alloc_lock;
1758
1759         /* Protection of the PI data structures: */
1760         raw_spinlock_t pi_lock;
1761
1762         struct wake_q_node wake_q;
1763
1764 #ifdef CONFIG_RT_MUTEXES
1765         /* PI waiters blocked on a rt_mutex held by this task */
1766         struct rb_root pi_waiters;
1767         struct rb_node *pi_waiters_leftmost;
1768         /* Deadlock detection and priority inheritance handling */
1769         struct rt_mutex_waiter *pi_blocked_on;
1770 #endif
1771
1772 #ifdef CONFIG_DEBUG_MUTEXES
1773         /* mutex deadlock detection */
1774         struct mutex_waiter *blocked_on;
1775 #endif
1776 #ifdef CONFIG_TRACE_IRQFLAGS
1777         unsigned int irq_events;
1778         unsigned long hardirq_enable_ip;
1779         unsigned long hardirq_disable_ip;
1780         unsigned int hardirq_enable_event;
1781         unsigned int hardirq_disable_event;
1782         int hardirqs_enabled;
1783         int hardirq_context;
1784         unsigned long softirq_disable_ip;
1785         unsigned long softirq_enable_ip;
1786         unsigned int softirq_disable_event;
1787         unsigned int softirq_enable_event;
1788         int softirqs_enabled;
1789         int softirq_context;
1790 #endif
1791 #ifdef CONFIG_LOCKDEP
1792 # define MAX_LOCK_DEPTH 48UL
1793         u64 curr_chain_key;
1794         int lockdep_depth;
1795         unsigned int lockdep_recursion;
1796         struct held_lock held_locks[MAX_LOCK_DEPTH];
1797         gfp_t lockdep_reclaim_gfp;
1798 #endif
1799
1800 /* journalling filesystem info */
1801         void *journal_info;
1802
1803 /* stacked block device info */
1804         struct bio_list *bio_list;
1805
1806 #ifdef CONFIG_BLOCK
1807 /* stack plugging */
1808         struct blk_plug *plug;
1809 #endif
1810
1811 /* VM state */
1812         struct reclaim_state *reclaim_state;
1813
1814         struct backing_dev_info *backing_dev_info;
1815
1816         struct io_context *io_context;
1817
1818         unsigned long ptrace_message;
1819         siginfo_t *last_siginfo; /* For ptrace use.  */
1820         struct task_io_accounting ioac;
1821 #if defined(CONFIG_TASK_XACCT)
1822         u64 acct_rss_mem1;      /* accumulated rss usage */
1823         u64 acct_vm_mem1;       /* accumulated virtual memory usage */
1824         cputime_t acct_timexpd; /* stime + utime since last update */
1825 #endif
1826 #ifdef CONFIG_CPUSETS
1827         nodemask_t mems_allowed;        /* Protected by alloc_lock */
1828         seqcount_t mems_allowed_seq;    /* Seqence no to catch updates */
1829         int cpuset_mem_spread_rotor;
1830         int cpuset_slab_spread_rotor;
1831 #endif
1832 #ifdef CONFIG_CGROUPS
1833         /* Control Group info protected by css_set_lock */
1834         struct css_set __rcu *cgroups;
1835         /* cg_list protected by css_set_lock and tsk->alloc_lock */
1836         struct list_head cg_list;
1837 #endif
1838 #ifdef CONFIG_FUTEX
1839         struct robust_list_head __user *robust_list;
1840 #ifdef CONFIG_COMPAT
1841         struct compat_robust_list_head __user *compat_robust_list;
1842 #endif
1843         struct list_head pi_state_list;
1844         struct futex_pi_state *pi_state_cache;
1845 #endif
1846 #ifdef CONFIG_PERF_EVENTS
1847         struct perf_event_context *perf_event_ctxp[perf_nr_task_contexts];
1848         struct mutex perf_event_mutex;
1849         struct list_head perf_event_list;
1850 #endif
1851 #ifdef CONFIG_DEBUG_PREEMPT
1852         unsigned long preempt_disable_ip;
1853 #endif
1854 #ifdef CONFIG_NUMA
1855         struct mempolicy *mempolicy;    /* Protected by alloc_lock */
1856         short il_next;
1857         short pref_node_fork;
1858 #endif
1859 #ifdef CONFIG_NUMA_BALANCING
1860         int numa_scan_seq;
1861         unsigned int numa_scan_period;
1862         unsigned int numa_scan_period_max;
1863         int numa_preferred_nid;
1864         unsigned long numa_migrate_retry;
1865         u64 node_stamp;                 /* migration stamp  */
1866         u64 last_task_numa_placement;
1867         u64 last_sum_exec_runtime;
1868         struct callback_head numa_work;
1869
1870         struct list_head numa_entry;
1871         struct numa_group *numa_group;
1872
1873         /*
1874          * numa_faults is an array split into four regions:
1875          * faults_memory, faults_cpu, faults_memory_buffer, faults_cpu_buffer
1876          * in this precise order.
1877          *
1878          * faults_memory: Exponential decaying average of faults on a per-node
1879          * basis. Scheduling placement decisions are made based on these
1880          * counts. The values remain static for the duration of a PTE scan.
1881          * faults_cpu: Track the nodes the process was running on when a NUMA
1882          * hinting fault was incurred.
1883          * faults_memory_buffer and faults_cpu_buffer: Record faults per node
1884          * during the current scan window. When the scan completes, the counts
1885          * in faults_memory and faults_cpu decay and these values are copied.
1886          */
1887         unsigned long *numa_faults;
1888         unsigned long total_numa_faults;
1889
1890         /*
1891          * numa_faults_locality tracks if faults recorded during the last
1892          * scan window were remote/local or failed to migrate. The task scan
1893          * period is adapted based on the locality of the faults with different
1894          * weights depending on whether they were shared or private faults
1895          */
1896         unsigned long numa_faults_locality[3];
1897
1898         unsigned long numa_pages_migrated;
1899 #endif /* CONFIG_NUMA_BALANCING */
1900
1901 #ifdef CONFIG_ARCH_WANT_BATCHED_UNMAP_TLB_FLUSH
1902         struct tlbflush_unmap_batch tlb_ubc;
1903 #endif
1904
1905         struct rcu_head rcu;
1906
1907         /*
1908          * cache last used pipe for splice
1909          */
1910         struct pipe_inode_info *splice_pipe;
1911
1912         struct page_frag task_frag;
1913
1914 #ifdef  CONFIG_TASK_DELAY_ACCT
1915         struct task_delay_info *delays;
1916 #endif
1917 #ifdef CONFIG_FAULT_INJECTION
1918         int make_it_fail;
1919 #endif
1920         /*
1921          * when (nr_dirtied >= nr_dirtied_pause), it's time to call
1922          * balance_dirty_pages() for some dirty throttling pause
1923          */
1924         int nr_dirtied;
1925         int nr_dirtied_pause;
1926         unsigned long dirty_paused_when; /* start of a write-and-pause period */
1927
1928 #ifdef CONFIG_LATENCYTOP
1929         int latency_record_count;
1930         struct latency_record latency_record[LT_SAVECOUNT];
1931 #endif
1932         /*
1933          * time slack values; these are used to round up poll() and
1934          * select() etc timeout values. These are in nanoseconds.
1935          */
1936         u64 timer_slack_ns;
1937         u64 default_timer_slack_ns;
1938
1939 #ifdef CONFIG_KASAN
1940         unsigned int kasan_depth;
1941 #endif
1942 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
1943         /* Index of current stored address in ret_stack */
1944         int curr_ret_stack;
1945         /* Stack of return addresses for return function tracing */
1946         struct ftrace_ret_stack *ret_stack;
1947         /* time stamp for last schedule */
1948         unsigned long long ftrace_timestamp;
1949         /*
1950          * Number of functions that haven't been traced
1951          * because of depth overrun.
1952          */
1953         atomic_t trace_overrun;
1954         /* Pause for the tracing */
1955         atomic_t tracing_graph_pause;
1956 #endif
1957 #ifdef CONFIG_TRACING
1958         /* state flags for use by tracers */
1959         unsigned long trace;
1960         /* bitmask and counter of trace recursion */
1961         unsigned long trace_recursion;
1962 #endif /* CONFIG_TRACING */
1963 #ifdef CONFIG_MEMCG
1964         struct mem_cgroup *memcg_in_oom;
1965         gfp_t memcg_oom_gfp_mask;
1966         int memcg_oom_order;
1967
1968         /* number of pages to reclaim on returning to userland */
1969         unsigned int memcg_nr_pages_over_high;
1970 #endif
1971 #ifdef CONFIG_UPROBES
1972         struct uprobe_task *utask;
1973 #endif
1974 #if defined(CONFIG_BCACHE) || defined(CONFIG_BCACHE_MODULE)
1975         unsigned int    sequential_io;
1976         unsigned int    sequential_io_avg;
1977 #endif
1978 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
1979         unsigned long   task_state_change;
1980 #endif
1981         int pagefault_disabled;
1982 /* CPU-specific state of this task */
1983         struct thread_struct thread;
1984 /*
1985  * WARNING: on x86, 'thread_struct' contains a variable-sized
1986  * structure.  It *MUST* be at the end of 'task_struct'.
1987  *
1988  * Do not put anything below here!
1989  */
1990 };
1991
1992 #ifdef CONFIG_ARCH_WANTS_DYNAMIC_TASK_STRUCT
1993 extern int arch_task_struct_size __read_mostly;
1994 #else
1995 # define arch_task_struct_size (sizeof(struct task_struct))
1996 #endif
1997
1998 /* Future-safe accessor for struct task_struct's cpus_allowed. */
1999 #define tsk_cpus_allowed(tsk) (&(tsk)->cpus_allowed)
2000
2001 #define TNF_MIGRATED    0x01
2002 #define TNF_NO_GROUP    0x02
2003 #define TNF_SHARED      0x04
2004 #define TNF_FAULT_LOCAL 0x08
2005 #define TNF_MIGRATE_FAIL 0x10
2006
2007 #ifdef CONFIG_NUMA_BALANCING
2008 extern void task_numa_fault(int last_node, int node, int pages, int flags);
2009 extern pid_t task_numa_group_id(struct task_struct *p);
2010 extern void set_numabalancing_state(bool enabled);
2011 extern void task_numa_free(struct task_struct *p);
2012 extern bool should_numa_migrate_memory(struct task_struct *p, struct page *page,
2013                                         int src_nid, int dst_cpu);
2014 #else
2015 static inline void task_numa_fault(int last_node, int node, int pages,
2016                                    int flags)
2017 {
2018 }
2019 static inline pid_t task_numa_group_id(struct task_struct *p)
2020 {
2021         return 0;
2022 }
2023 static inline void set_numabalancing_state(bool enabled)
2024 {
2025 }
2026 static inline void task_numa_free(struct task_struct *p)
2027 {
2028 }
2029 static inline bool should_numa_migrate_memory(struct task_struct *p,
2030                                 struct page *page, int src_nid, int dst_cpu)
2031 {
2032         return true;
2033 }
2034 #endif
2035
2036 static inline struct pid *task_pid(struct task_struct *task)
2037 {
2038         return task->pids[PIDTYPE_PID].pid;
2039 }
2040
2041 static inline struct pid *task_tgid(struct task_struct *task)
2042 {
2043         return task->group_leader->pids[PIDTYPE_PID].pid;
2044 }
2045
2046 /*
2047  * Without tasklist or rcu lock it is not safe to dereference
2048  * the result of task_pgrp/task_session even if task == current,
2049  * we can race with another thread doing sys_setsid/sys_setpgid.
2050  */
2051 static inline struct pid *task_pgrp(struct task_struct *task)
2052 {
2053         return task->group_leader->pids[PIDTYPE_PGID].pid;
2054 }
2055
2056 static inline struct pid *task_session(struct task_struct *task)
2057 {
2058         return task->group_leader->pids[PIDTYPE_SID].pid;
2059 }
2060
2061 struct pid_namespace;
2062
2063 /*
2064  * the helpers to get the task's different pids as they are seen
2065  * from various namespaces
2066  *
2067  * task_xid_nr()     : global id, i.e. the id seen from the init namespace;
2068  * task_xid_vnr()    : virtual id, i.e. the id seen from the pid namespace of
2069  *                     current.
2070  * task_xid_nr_ns()  : id seen from the ns specified;
2071  *
2072  * set_task_vxid()   : assigns a virtual id to a task;
2073  *
2074  * see also pid_nr() etc in include/linux/pid.h
2075  */
2076 pid_t __task_pid_nr_ns(struct task_struct *task, enum pid_type type,
2077                         struct pid_namespace *ns);
2078
2079 static inline pid_t task_pid_nr(struct task_struct *tsk)
2080 {
2081         return tsk->pid;
2082 }
2083
2084 static inline pid_t task_pid_nr_ns(struct task_struct *tsk,
2085                                         struct pid_namespace *ns)
2086 {
2087         return __task_pid_nr_ns(tsk, PIDTYPE_PID, ns);
2088 }
2089
2090 static inline pid_t task_pid_vnr(struct task_struct *tsk)
2091 {
2092         return __task_pid_nr_ns(tsk, PIDTYPE_PID, NULL);
2093 }
2094
2095
2096 static inline pid_t task_tgid_nr(struct task_struct *tsk)
2097 {
2098         return tsk->tgid;
2099 }
2100
2101 pid_t task_tgid_nr_ns(struct task_struct *tsk, struct pid_namespace *ns);
2102
2103 static inline pid_t task_tgid_vnr(struct task_struct *tsk)
2104 {
2105         return pid_vnr(task_tgid(tsk));
2106 }
2107
2108
2109 static inline int pid_alive(const struct task_struct *p);
2110 static inline pid_t task_ppid_nr_ns(const struct task_struct *tsk, struct pid_namespace *ns)
2111 {
2112         pid_t pid = 0;
2113
2114         rcu_read_lock();
2115         if (pid_alive(tsk))
2116                 pid = task_tgid_nr_ns(rcu_dereference(tsk->real_parent), ns);
2117         rcu_read_unlock();
2118
2119         return pid;
2120 }
2121
2122 static inline pid_t task_ppid_nr(const struct task_struct *tsk)
2123 {
2124         return task_ppid_nr_ns(tsk, &init_pid_ns);
2125 }
2126
2127 static inline pid_t task_pgrp_nr_ns(struct task_struct *tsk,
2128                                         struct pid_namespace *ns)
2129 {
2130         return __task_pid_nr_ns(tsk, PIDTYPE_PGID, ns);
2131 }
2132
2133 static inline pid_t task_pgrp_vnr(struct task_struct *tsk)
2134 {
2135         return __task_pid_nr_ns(tsk, PIDTYPE_PGID, NULL);
2136 }
2137
2138
2139 static inline pid_t task_session_nr_ns(struct task_struct *tsk,
2140                                         struct pid_namespace *ns)
2141 {
2142         return __task_pid_nr_ns(tsk, PIDTYPE_SID, ns);
2143 }
2144
2145 static inline pid_t task_session_vnr(struct task_struct *tsk)
2146 {
2147         return __task_pid_nr_ns(tsk, PIDTYPE_SID, NULL);
2148 }
2149
2150 /* obsolete, do not use */
2151 static inline pid_t task_pgrp_nr(struct task_struct *tsk)
2152 {
2153         return task_pgrp_nr_ns(tsk, &init_pid_ns);
2154 }
2155
2156 /**
2157  * pid_alive - check that a task structure is not stale
2158  * @p: Task structure to be checked.
2159  *
2160  * Test if a process is not yet dead (at most zombie state)
2161  * If pid_alive fails, then pointers within the task structure
2162  * can be stale and must not be dereferenced.
2163  *
2164  * Return: 1 if the process is alive. 0 otherwise.
2165  */
2166 static inline int pid_alive(const struct task_struct *p)
2167 {
2168         return p->pids[PIDTYPE_PID].pid != NULL;
2169 }
2170
2171 /**
2172  * is_global_init - check if a task structure is init. Since init
2173  * is free to have sub-threads we need to check tgid.
2174  * @tsk: Task structure to be checked.
2175  *
2176  * Check if a task structure is the first user space task the kernel created.
2177  *
2178  * Return: 1 if the task structure is init. 0 otherwise.
2179  */
2180 static inline int is_global_init(struct task_struct *tsk)
2181 {
2182         return task_tgid_nr(tsk) == 1;
2183 }
2184
2185 extern struct pid *cad_pid;
2186
2187 extern void free_task(struct task_struct *tsk);
2188 #define get_task_struct(tsk) do { atomic_inc(&(tsk)->usage); } while(0)
2189
2190 extern void __put_task_struct(struct task_struct *t);
2191
2192 static inline void put_task_struct(struct task_struct *t)
2193 {
2194         if (atomic_dec_and_test(&t->usage))
2195                 __put_task_struct(t);
2196 }
2197
2198 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
2199 extern void task_cputime(struct task_struct *t,
2200                          cputime_t *utime, cputime_t *stime);
2201 extern void task_cputime_scaled(struct task_struct *t,
2202                                 cputime_t *utimescaled, cputime_t *stimescaled);
2203 extern cputime_t task_gtime(struct task_struct *t);
2204 #else
2205 static inline void task_cputime(struct task_struct *t,
2206                                 cputime_t *utime, cputime_t *stime)
2207 {
2208         if (utime)
2209                 *utime = t->utime;
2210         if (stime)
2211                 *stime = t->stime;
2212 }
2213
2214 static inline void task_cputime_scaled(struct task_struct *t,
2215                                        cputime_t *utimescaled,
2216                                        cputime_t *stimescaled)
2217 {
2218         if (utimescaled)
2219                 *utimescaled = t->utimescaled;
2220         if (stimescaled)
2221                 *stimescaled = t->stimescaled;
2222 }
2223
2224 static inline cputime_t task_gtime(struct task_struct *t)
2225 {
2226         return t->gtime;
2227 }
2228 #endif
2229 extern void task_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t *st);
2230 extern void thread_group_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t *st);
2231
2232 /*
2233  * Per process flags
2234  */
2235 #define PF_EXITING      0x00000004      /* getting shut down */
2236 #define PF_EXITPIDONE   0x00000008      /* pi exit done on shut down */
2237 #define PF_VCPU         0x00000010      /* I'm a virtual CPU */
2238 #define PF_WQ_WORKER    0x00000020      /* I'm a workqueue worker */
2239 #define PF_FORKNOEXEC   0x00000040      /* forked but didn't exec */
2240 #define PF_MCE_PROCESS  0x00000080      /* process policy on mce errors */
2241 #define PF_SUPERPRIV    0x00000100      /* used super-user privileges */
2242 #define PF_DUMPCORE     0x00000200      /* dumped core */
2243 #define PF_SIGNALED     0x00000400      /* killed by a signal */
2244 #define PF_MEMALLOC     0x00000800      /* Allocating memory */
2245 #define PF_NPROC_EXCEEDED 0x00001000    /* set_user noticed that RLIMIT_NPROC was exceeded */
2246 #define PF_USED_MATH    0x00002000      /* if unset the fpu must be initialized before use */
2247 #define PF_USED_ASYNC   0x00004000      /* used async_schedule*(), used by module init */
2248 #define PF_NOFREEZE     0x00008000      /* this thread should not be frozen */
2249 #define PF_FROZEN       0x00010000      /* frozen for system suspend */
2250 #define PF_FSTRANS      0x00020000      /* inside a filesystem transaction */
2251 #define PF_KSWAPD       0x00040000      /* I am kswapd */
2252 #define PF_MEMALLOC_NOIO 0x00080000     /* Allocating memory without IO involved */
2253 #define PF_LESS_THROTTLE 0x00100000     /* Throttle me less: I clean memory */
2254 #define PF_KTHREAD      0x00200000      /* I am a kernel thread */
2255 #define PF_RANDOMIZE    0x00400000      /* randomize virtual address space */
2256 #define PF_SWAPWRITE    0x00800000      /* Allowed to write to swap */
2257 #define PF_NO_SETAFFINITY 0x04000000    /* Userland is not allowed to meddle with cpus_allowed */
2258 #define PF_MCE_EARLY    0x08000000      /* Early kill for mce process policy */
2259 #define PF_MUTEX_TESTER 0x20000000      /* Thread belongs to the rt mutex tester */
2260 #define PF_FREEZER_SKIP 0x40000000      /* Freezer should not count it as freezable */
2261 #define PF_SUSPEND_TASK 0x80000000      /* this thread called freeze_processes and should not be frozen */
2262
2263 /*
2264  * Only the _current_ task can read/write to tsk->flags, but other
2265  * tasks can access tsk->flags in readonly mode for example
2266  * with tsk_used_math (like during threaded core dumping).
2267  * There is however an exception to this rule during ptrace
2268  * or during fork: the ptracer task is allowed to write to the
2269  * child->flags of its traced child (same goes for fork, the parent
2270  * can write to the child->flags), because we're guaranteed the
2271  * child is not running and in turn not changing child->flags
2272  * at the same time the parent does it.
2273  */
2274 #define clear_stopped_child_used_math(child) do { (child)->flags &= ~PF_USED_MATH; } while (0)
2275 #define set_stopped_child_used_math(child) do { (child)->flags |= PF_USED_MATH; } while (0)
2276 #define clear_used_math() clear_stopped_child_used_math(current)
2277 #define set_used_math() set_stopped_child_used_math(current)
2278 #define conditional_stopped_child_used_math(condition, child) \
2279         do { (child)->flags &= ~PF_USED_MATH, (child)->flags |= (condition) ? PF_USED_MATH : 0; } while (0)
2280 #define conditional_used_math(condition) \
2281         conditional_stopped_child_used_math(condition, current)
2282 #define copy_to_stopped_child_used_math(child) \
2283         do { (child)->flags &= ~PF_USED_MATH, (child)->flags |= current->flags & PF_USED_MATH; } while (0)
2284 /* NOTE: this will return 0 or PF_USED_MATH, it will never return 1 */
2285 #define tsk_used_math(p) ((p)->flags & PF_USED_MATH)
2286 #define used_math() tsk_used_math(current)
2287
2288 /* __GFP_IO isn't allowed if PF_MEMALLOC_NOIO is set in current->flags
2289  * __GFP_FS is also cleared as it implies __GFP_IO.
2290  */
2291 static inline gfp_t memalloc_noio_flags(gfp_t flags)
2292 {
2293         if (unlikely(current->flags & PF_MEMALLOC_NOIO))
2294                 flags &= ~(__GFP_IO | __GFP_FS);
2295         return flags;
2296 }
2297
2298 static inline unsigned int memalloc_noio_save(void)
2299 {
2300         unsigned int flags = current->flags & PF_MEMALLOC_NOIO;
2301         current->flags |= PF_MEMALLOC_NOIO;
2302         return flags;
2303 }
2304
2305 static inline void memalloc_noio_restore(unsigned int flags)
2306 {
2307         current->flags = (current->flags & ~PF_MEMALLOC_NOIO) | flags;
2308 }
2309
2310 /* Per-process atomic flags. */
2311 #define PFA_NO_NEW_PRIVS 0      /* May not gain new privileges. */
2312 #define PFA_SPREAD_PAGE  1      /* Spread page cache over cpuset */
2313 #define PFA_SPREAD_SLAB  2      /* Spread some slab caches over cpuset */
2314
2315
2316 #define TASK_PFA_TEST(name, func)                                       \
2317         static inline bool task_##func(struct task_struct *p)           \
2318         { return test_bit(PFA_##name, &p->atomic_flags); }
2319 #define TASK_PFA_SET(name, func)                                        \
2320         static inline void task_set_##func(struct task_struct *p)       \
2321         { set_bit(PFA_##name, &p->atomic_flags); }
2322 #define TASK_PFA_CLEAR(name, func)                                      \
2323         static inline void task_clear_##func(struct task_struct *p)     \
2324         { clear_bit(PFA_##name, &p->atomic_flags); }
2325
2326 TASK_PFA_TEST(NO_NEW_PRIVS, no_new_privs)
2327 TASK_PFA_SET(NO_NEW_PRIVS, no_new_privs)
2328
2329 TASK_PFA_TEST(SPREAD_PAGE, spread_page)
2330 TASK_PFA_SET(SPREAD_PAGE, spread_page)
2331 TASK_PFA_CLEAR(SPREAD_PAGE, spread_page)
2332
2333 TASK_PFA_TEST(SPREAD_SLAB, spread_slab)
2334 TASK_PFA_SET(SPREAD_SLAB, spread_slab)
2335 TASK_PFA_CLEAR(SPREAD_SLAB, spread_slab)
2336
2337 /*
2338  * task->jobctl flags
2339  */
2340 #define JOBCTL_STOP_SIGMASK     0xffff  /* signr of the last group stop */
2341
2342 #define JOBCTL_STOP_DEQUEUED_BIT 16     /* stop signal dequeued */
2343 #define JOBCTL_STOP_PENDING_BIT 17      /* task should stop for group stop */
2344 #define JOBCTL_STOP_CONSUME_BIT 18      /* consume group stop count */
2345 #define JOBCTL_TRAP_STOP_BIT    19      /* trap for STOP */
2346 #define JOBCTL_TRAP_NOTIFY_BIT  20      /* trap for NOTIFY */
2347 #define JOBCTL_TRAPPING_BIT     21      /* switching to TRACED */
2348 #define JOBCTL_LISTENING_BIT    22      /* ptracer is listening for events */
2349
2350 #define JOBCTL_STOP_DEQUEUED    (1UL << JOBCTL_STOP_DEQUEUED_BIT)
2351 #define JOBCTL_STOP_PENDING     (1UL << JOBCTL_STOP_PENDING_BIT)
2352 #define JOBCTL_STOP_CONSUME     (1UL << JOBCTL_STOP_CONSUME_BIT)
2353 #define JOBCTL_TRAP_STOP        (1UL << JOBCTL_TRAP_STOP_BIT)
2354 #define JOBCTL_TRAP_NOTIFY      (1UL << JOBCTL_TRAP_NOTIFY_BIT)
2355 #define JOBCTL_TRAPPING         (1UL << JOBCTL_TRAPPING_BIT)
2356 #define JOBCTL_LISTENING        (1UL << JOBCTL_LISTENING_BIT)
2357
2358 #define JOBCTL_TRAP_MASK        (JOBCTL_TRAP_STOP | JOBCTL_TRAP_NOTIFY)
2359 #define JOBCTL_PENDING_MASK     (JOBCTL_STOP_PENDING | JOBCTL_TRAP_MASK)
2360
2361 extern bool task_set_jobctl_pending(struct task_struct *task,
2362                                     unsigned long mask);
2363 extern void task_clear_jobctl_trapping(struct task_struct *task);
2364 extern void task_clear_jobctl_pending(struct task_struct *task,
2365                                       unsigned long mask);
2366
2367 static inline void rcu_copy_process(struct task_struct *p)
2368 {
2369 #ifdef CONFIG_PREEMPT_RCU
2370         p->rcu_read_lock_nesting = 0;
2371         p->rcu_read_unlock_special.s = 0;
2372         p->rcu_blocked_node = NULL;
2373         INIT_LIST_HEAD(&p->rcu_node_entry);
2374 #endif /* #ifdef CONFIG_PREEMPT_RCU */
2375 #ifdef CONFIG_TASKS_RCU
2376         p->rcu_tasks_holdout = false;
2377         INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
2378         p->rcu_tasks_idle_cpu = -1;
2379 #endif /* #ifdef CONFIG_TASKS_RCU */
2380 }
2381
2382 static inline void tsk_restore_flags(struct task_struct *task,
2383                                 unsigned long orig_flags, unsigned long flags)
2384 {
2385         task->flags &= ~flags;
2386         task->flags |= orig_flags & flags;
2387 }
2388
2389 extern int cpuset_cpumask_can_shrink(const struct cpumask *cur,
2390                                      const struct cpumask *trial);
2391 extern int task_can_attach(struct task_struct *p,
2392                            const struct cpumask *cs_cpus_allowed);
2393 #ifdef CONFIG_SMP
2394 extern void do_set_cpus_allowed(struct task_struct *p,
2395                                const struct cpumask *new_mask);
2396
2397 extern int set_cpus_allowed_ptr(struct task_struct *p,
2398                                 const struct cpumask *new_mask);
2399 #else
2400 static inline void do_set_cpus_allowed(struct task_struct *p,
2401                                       const struct cpumask *new_mask)
2402 {
2403 }
2404 static inline int set_cpus_allowed_ptr(struct task_struct *p,
2405                                        const struct cpumask *new_mask)
2406 {
2407         if (!cpumask_test_cpu(0, new_mask))
2408                 return -EINVAL;
2409         return 0;
2410 }
2411 #endif
2412
2413 #ifdef CONFIG_NO_HZ_COMMON
2414 void calc_load_enter_idle(void);
2415 void calc_load_exit_idle(void);
2416 #else
2417 static inline void calc_load_enter_idle(void) { }
2418 static inline void calc_load_exit_idle(void) { }
2419 #endif /* CONFIG_NO_HZ_COMMON */
2420
2421 /*
2422  * Do not use outside of architecture code which knows its limitations.
2423  *
2424  * sched_clock() has no promise of monotonicity or bounded drift between
2425  * CPUs, use (which you should not) requires disabling IRQs.
2426  *
2427  * Please use one of the three interfaces below.
2428  */
2429 extern unsigned long long notrace sched_clock(void);
2430 /*
2431  * See the comment in kernel/sched/clock.c
2432  */
2433 extern u64 cpu_clock(int cpu);
2434 extern u64 local_clock(void);
2435 extern u64 running_clock(void);
2436 extern u64 sched_clock_cpu(int cpu);
2437
2438
2439 extern void sched_clock_init(void);
2440
2441 #ifndef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK
2442 static inline void sched_clock_tick(void)
2443 {
2444 }
2445
2446 static inline void sched_clock_idle_sleep_event(void)
2447 {
2448 }
2449
2450 static inline void sched_clock_idle_wakeup_event(u64 delta_ns)
2451 {
2452 }
2453 #else
2454 /*
2455  * Architectures can set this to 1 if they have specified
2456  * CONFIG_HAVE_UNSTABLE_SCHED_CLOCK in their arch Kconfig,
2457  * but then during bootup it turns out that sched_clock()
2458  * is reliable after all:
2459  */
2460 extern int sched_clock_stable(void);
2461 extern void set_sched_clock_stable(void);
2462 extern void clear_sched_clock_stable(void);
2463
2464 extern void sched_clock_tick(void);
2465 extern void sched_clock_idle_sleep_event(void);
2466 extern void sched_clock_idle_wakeup_event(u64 delta_ns);
2467 #endif
2468
2469 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
2470 /*
2471  * An i/f to runtime opt-in for irq time accounting based off of sched_clock.
2472  * The reason for this explicit opt-in is not to have perf penalty with
2473  * slow sched_clocks.
2474  */
2475 extern void enable_sched_clock_irqtime(void);
2476 extern void disable_sched_clock_irqtime(void);
2477 #else
2478 static inline void enable_sched_clock_irqtime(void) {}
2479 static inline void disable_sched_clock_irqtime(void) {}
2480 #endif
2481
2482 extern unsigned long long
2483 task_sched_runtime(struct task_struct *task);
2484
2485 /* sched_exec is called by processes performing an exec */
2486 #ifdef CONFIG_SMP
2487 extern void sched_exec(void);
2488 #else
2489 #define sched_exec()   {}
2490 #endif
2491
2492 extern void sched_clock_idle_sleep_event(void);
2493 extern void sched_clock_idle_wakeup_event(u64 delta_ns);
2494
2495 #ifdef CONFIG_HOTPLUG_CPU
2496 extern void idle_task_exit(void);
2497 #else
2498 static inline void idle_task_exit(void) {}
2499 #endif
2500
2501 #if defined(CONFIG_NO_HZ_COMMON) && defined(CONFIG_SMP)
2502 extern void wake_up_nohz_cpu(int cpu);
2503 #else
2504 static inline void wake_up_nohz_cpu(int cpu) { }
2505 #endif
2506
2507 #ifdef CONFIG_NO_HZ_FULL
2508 extern bool sched_can_stop_tick(void);
2509 extern u64 scheduler_tick_max_deferment(void);
2510 #else
2511 static inline bool sched_can_stop_tick(void) { return false; }
2512 #endif
2513
2514 #ifdef CONFIG_SCHED_AUTOGROUP
2515 extern void sched_autogroup_create_attach(struct task_struct *p);
2516 extern void sched_autogroup_detach(struct task_struct *p);
2517 extern void sched_autogroup_fork(struct signal_struct *sig);
2518 extern void sched_autogroup_exit(struct signal_struct *sig);
2519 #ifdef CONFIG_PROC_FS
2520 extern void proc_sched_autogroup_show_task(struct task_struct *p, struct seq_file *m);
2521 extern int proc_sched_autogroup_set_nice(struct task_struct *p, int nice);
2522 #endif
2523 #else
2524 static inline void sched_autogroup_create_attach(struct task_struct *p) { }
2525 static inline void sched_autogroup_detach(struct task_struct *p) { }
2526 static inline void sched_autogroup_fork(struct signal_struct *sig) { }
2527 static inline void sched_autogroup_exit(struct signal_struct *sig) { }
2528 #endif
2529
2530 extern int yield_to(struct task_struct *p, bool preempt);
2531 extern void set_user_nice(struct task_struct *p, long nice);
2532 extern int task_prio(const struct task_struct *p);
2533 /**
2534  * task_nice - return the nice value of a given task.
2535  * @p: the task in question.
2536  *
2537  * Return: The nice value [ -20 ... 0 ... 19 ].
2538  */
2539 static inline int task_nice(const struct task_struct *p)
2540 {
2541         return PRIO_TO_NICE((p)->static_prio);
2542 }
2543 extern int can_nice(const struct task_struct *p, const int nice);
2544 extern int task_curr(const struct task_struct *p);
2545 extern int idle_cpu(int cpu);
2546 extern int sched_setscheduler(struct task_struct *, int,
2547                               const struct sched_param *);
2548 extern int sched_setscheduler_nocheck(struct task_struct *, int,
2549                                       const struct sched_param *);
2550 extern int sched_setattr(struct task_struct *,
2551                          const struct sched_attr *);
2552 extern struct task_struct *idle_task(int cpu);
2553 /**
2554  * is_idle_task - is the specified task an idle task?
2555  * @p: the task in question.
2556  *
2557  * Return: 1 if @p is an idle task. 0 otherwise.
2558  */
2559 static inline bool is_idle_task(const struct task_struct *p)
2560 {
2561         return p->pid == 0;
2562 }
2563 extern struct task_struct *curr_task(int cpu);
2564 extern void set_curr_task(int cpu, struct task_struct *p);
2565
2566 void yield(void);
2567
2568 union thread_union {
2569 #ifndef CONFIG_THREAD_INFO_IN_TASK
2570         struct thread_info thread_info;
2571 #endif
2572         unsigned long stack[THREAD_SIZE/sizeof(long)];
2573 };
2574
2575 #ifndef __HAVE_ARCH_KSTACK_END
2576 static inline int kstack_end(void *addr)
2577 {
2578         /* Reliable end of stack detection:
2579          * Some APM bios versions misalign the stack
2580          */
2581         return !(((unsigned long)addr+sizeof(void*)-1) & (THREAD_SIZE-sizeof(void*)));
2582 }
2583 #endif
2584
2585 extern union thread_union init_thread_union;
2586 extern struct task_struct init_task;
2587
2588 extern struct   mm_struct init_mm;
2589
2590 extern struct pid_namespace init_pid_ns;
2591
2592 /*
2593  * find a task by one of its numerical ids
2594  *
2595  * find_task_by_pid_ns():
2596  *      finds a task by its pid in the specified namespace
2597  * find_task_by_vpid():
2598  *      finds a task by its virtual pid
2599  *
2600  * see also find_vpid() etc in include/linux/pid.h
2601  */
2602
2603 extern struct task_struct *find_task_by_vpid(pid_t nr);
2604 extern struct task_struct *find_task_by_pid_ns(pid_t nr,
2605                 struct pid_namespace *ns);
2606
2607 /* per-UID process charging. */
2608 extern struct user_struct * alloc_uid(kuid_t);
2609 static inline struct user_struct *get_uid(struct user_struct *u)
2610 {
2611         atomic_inc(&u->__count);
2612         return u;
2613 }
2614 extern void free_uid(struct user_struct *);
2615
2616 #include <asm/current.h>
2617
2618 extern void xtime_update(unsigned long ticks);
2619
2620 extern int wake_up_state(struct task_struct *tsk, unsigned int state);
2621 extern int wake_up_process(struct task_struct *tsk);
2622 extern void wake_up_new_task(struct task_struct *tsk);
2623 #ifdef CONFIG_SMP
2624  extern void kick_process(struct task_struct *tsk);
2625 #else
2626  static inline void kick_process(struct task_struct *tsk) { }
2627 #endif
2628 extern int sched_fork(unsigned long clone_flags, struct task_struct *p);
2629 extern void sched_dead(struct task_struct *p);
2630
2631 extern void proc_caches_init(void);
2632 extern void flush_signals(struct task_struct *);
2633 extern void ignore_signals(struct task_struct *);
2634 extern void flush_signal_handlers(struct task_struct *, int force_default);
2635 extern int dequeue_signal(struct task_struct *tsk, sigset_t *mask, siginfo_t *info);
2636
2637 static inline int kernel_dequeue_signal(siginfo_t *info)
2638 {
2639         struct task_struct *tsk = current;
2640         siginfo_t __info;
2641         int ret;
2642
2643         spin_lock_irq(&tsk->sighand->siglock);
2644         ret = dequeue_signal(tsk, &tsk->blocked, info ?: &__info);
2645         spin_unlock_irq(&tsk->sighand->siglock);
2646
2647         return ret;
2648 }
2649
2650 static inline void kernel_signal_stop(void)
2651 {
2652         spin_lock_irq(&current->sighand->siglock);
2653         if (current->jobctl & JOBCTL_STOP_DEQUEUED)
2654                 __set_current_state(TASK_STOPPED);
2655         spin_unlock_irq(&current->sighand->siglock);
2656
2657         schedule();
2658 }
2659
2660 extern void release_task(struct task_struct * p);
2661 extern int send_sig_info(int, struct siginfo *, struct task_struct *);
2662 extern int force_sigsegv(int, struct task_struct *);
2663 extern int force_sig_info(int, struct siginfo *, struct task_struct *);
2664 extern int __kill_pgrp_info(int sig, struct siginfo *info, struct pid *pgrp);
2665 extern int kill_pid_info(int sig, struct siginfo *info, struct pid *pid);
2666 extern int kill_pid_info_as_cred(int, struct siginfo *, struct pid *,
2667                                 const struct cred *, u32);
2668 extern int kill_pgrp(struct pid *pid, int sig, int priv);
2669 extern int kill_pid(struct pid *pid, int sig, int priv);
2670 extern int kill_proc_info(int, struct siginfo *, pid_t);
2671 extern __must_check bool do_notify_parent(struct task_struct *, int);
2672 extern void __wake_up_parent(struct task_struct *p, struct task_struct *parent);
2673 extern void force_sig(int, struct task_struct *);
2674 extern int send_sig(int, struct task_struct *, int);
2675 extern int zap_other_threads(struct task_struct *p);
2676 extern struct sigqueue *sigqueue_alloc(void);
2677 extern void sigqueue_free(struct sigqueue *);
2678 extern int send_sigqueue(struct sigqueue *,  struct task_struct *, int group);
2679 extern int do_sigaction(int, struct k_sigaction *, struct k_sigaction *);
2680
2681 static inline void restore_saved_sigmask(void)
2682 {
2683         if (test_and_clear_restore_sigmask())
2684                 __set_current_blocked(&current->saved_sigmask);
2685 }
2686
2687 static inline sigset_t *sigmask_to_save(void)
2688 {
2689         sigset_t *res = &current->blocked;
2690         if (unlikely(test_restore_sigmask()))
2691                 res = &current->saved_sigmask;
2692         return res;
2693 }
2694
2695 static inline int kill_cad_pid(int sig, int priv)
2696 {
2697         return kill_pid(cad_pid, sig, priv);
2698 }
2699
2700 /* These can be the second arg to send_sig_info/send_group_sig_info.  */
2701 #define SEND_SIG_NOINFO ((struct siginfo *) 0)
2702 #define SEND_SIG_PRIV   ((struct siginfo *) 1)
2703 #define SEND_SIG_FORCED ((struct siginfo *) 2)
2704
2705 /*
2706  * True if we are on the alternate signal stack.
2707  */
2708 static inline int on_sig_stack(unsigned long sp)
2709 {
2710 #ifdef CONFIG_STACK_GROWSUP
2711         return sp >= current->sas_ss_sp &&
2712                 sp - current->sas_ss_sp < current->sas_ss_size;
2713 #else
2714         return sp > current->sas_ss_sp &&
2715                 sp - current->sas_ss_sp <= current->sas_ss_size;
2716 #endif
2717 }
2718
2719 static inline int sas_ss_flags(unsigned long sp)
2720 {
2721         if (!current->sas_ss_size)
2722                 return SS_DISABLE;
2723
2724         return on_sig_stack(sp) ? SS_ONSTACK : 0;
2725 }
2726
2727 static inline unsigned long sigsp(unsigned long sp, struct ksignal *ksig)
2728 {
2729         if (unlikely((ksig->ka.sa.sa_flags & SA_ONSTACK)) && ! sas_ss_flags(sp))
2730 #ifdef CONFIG_STACK_GROWSUP
2731                 return current->sas_ss_sp;
2732 #else
2733                 return current->sas_ss_sp + current->sas_ss_size;
2734 #endif
2735         return sp;
2736 }
2737
2738 /*
2739  * Routines for handling mm_structs
2740  */
2741 extern struct mm_struct * mm_alloc(void);
2742
2743 /* mmdrop drops the mm and the page tables */
2744 extern void __mmdrop(struct mm_struct *);
2745 static inline void mmdrop(struct mm_struct * mm)
2746 {
2747         if (unlikely(atomic_dec_and_test(&mm->mm_count)))
2748                 __mmdrop(mm);
2749 }
2750
2751 /* mmput gets rid of the mappings and all user-space */
2752 extern void mmput(struct mm_struct *);
2753 /* Grab a reference to a task's mm, if it is not already going away */
2754 extern struct mm_struct *get_task_mm(struct task_struct *task);
2755 /*
2756  * Grab a reference to a task's mm, if it is not already going away
2757  * and ptrace_may_access with the mode parameter passed to it
2758  * succeeds.
2759  */
2760 extern struct mm_struct *mm_access(struct task_struct *task, unsigned int mode);
2761 /* Remove the current tasks stale references to the old mm_struct */
2762 extern void mm_release(struct task_struct *, struct mm_struct *);
2763
2764 #ifdef CONFIG_HAVE_COPY_THREAD_TLS
2765 extern int copy_thread_tls(unsigned long, unsigned long, unsigned long,
2766                         struct task_struct *, unsigned long);
2767 #else
2768 extern int copy_thread(unsigned long, unsigned long, unsigned long,
2769                         struct task_struct *);
2770
2771 /* Architectures that haven't opted into copy_thread_tls get the tls argument
2772  * via pt_regs, so ignore the tls argument passed via C. */
2773 static inline int copy_thread_tls(
2774                 unsigned long clone_flags, unsigned long sp, unsigned long arg,
2775                 struct task_struct *p, unsigned long tls)
2776 {
2777         return copy_thread(clone_flags, sp, arg, p);
2778 }
2779 #endif
2780 extern void flush_thread(void);
2781 extern void exit_thread(void);
2782
2783 extern void exit_files(struct task_struct *);
2784 extern void __cleanup_sighand(struct sighand_struct *);
2785
2786 extern void exit_itimers(struct signal_struct *);
2787 extern void flush_itimer_signals(void);
2788
2789 extern void do_group_exit(int);
2790
2791 extern int do_execve(struct filename *,
2792                      const char __user * const __user *,
2793                      const char __user * const __user *);
2794 extern int do_execveat(int, struct filename *,
2795                        const char __user * const __user *,
2796                        const char __user * const __user *,
2797                        int);
2798 extern long _do_fork(unsigned long, unsigned long, unsigned long, int __user *, int __user *, unsigned long);
2799 extern long do_fork(unsigned long, unsigned long, unsigned long, int __user *, int __user *);
2800 struct task_struct *fork_idle(int);
2801 extern pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags);
2802
2803 extern void __set_task_comm(struct task_struct *tsk, const char *from, bool exec);
2804 static inline void set_task_comm(struct task_struct *tsk, const char *from)
2805 {
2806         __set_task_comm(tsk, from, false);
2807 }
2808 extern char *get_task_comm(char *to, struct task_struct *tsk);
2809
2810 #ifdef CONFIG_SMP
2811 void scheduler_ipi(void);
2812 extern unsigned long wait_task_inactive(struct task_struct *, long match_state);
2813 #else
2814 static inline void scheduler_ipi(void) { }
2815 static inline unsigned long wait_task_inactive(struct task_struct *p,
2816                                                long match_state)
2817 {
2818         return 1;
2819 }
2820 #endif
2821
2822 #define tasklist_empty() \
2823         list_empty(&init_task.tasks)
2824
2825 #define next_task(p) \
2826         list_entry_rcu((p)->tasks.next, struct task_struct, tasks)
2827
2828 #define for_each_process(p) \
2829         for (p = &init_task ; (p = next_task(p)) != &init_task ; )
2830
2831 extern bool current_is_single_threaded(void);
2832
2833 /*
2834  * Careful: do_each_thread/while_each_thread is a double loop so
2835  *          'break' will not work as expected - use goto instead.
2836  */
2837 #define do_each_thread(g, t) \
2838         for (g = t = &init_task ; (g = t = next_task(g)) != &init_task ; ) do
2839
2840 #define while_each_thread(g, t) \
2841         while ((t = next_thread(t)) != g)
2842
2843 #define __for_each_thread(signal, t)    \
2844         list_for_each_entry_rcu(t, &(signal)->thread_head, thread_node)
2845
2846 #define for_each_thread(p, t)           \
2847         __for_each_thread((p)->signal, t)
2848
2849 /* Careful: this is a double loop, 'break' won't work as expected. */
2850 #define for_each_process_thread(p, t)   \
2851         for_each_process(p) for_each_thread(p, t)
2852
2853 static inline int get_nr_threads(struct task_struct *tsk)
2854 {
2855         return tsk->signal->nr_threads;
2856 }
2857
2858 static inline bool thread_group_leader(struct task_struct *p)
2859 {
2860         return p->exit_signal >= 0;
2861 }
2862
2863 /* Do to the insanities of de_thread it is possible for a process
2864  * to have the pid of the thread group leader without actually being
2865  * the thread group leader.  For iteration through the pids in proc
2866  * all we care about is that we have a task with the appropriate
2867  * pid, we don't actually care if we have the right task.
2868  */
2869 static inline bool has_group_leader_pid(struct task_struct *p)
2870 {
2871         return task_pid(p) == p->signal->leader_pid;
2872 }
2873
2874 static inline
2875 bool same_thread_group(struct task_struct *p1, struct task_struct *p2)
2876 {
2877         return p1->signal == p2->signal;
2878 }
2879
2880 static inline struct task_struct *next_thread(const struct task_struct *p)
2881 {
2882         return list_entry_rcu(p->thread_group.next,
2883                               struct task_struct, thread_group);
2884 }
2885
2886 static inline int thread_group_empty(struct task_struct *p)
2887 {
2888         return list_empty(&p->thread_group);
2889 }
2890
2891 #define delay_group_leader(p) \
2892                 (thread_group_leader(p) && !thread_group_empty(p))
2893
2894 /*
2895  * Protects ->fs, ->files, ->mm, ->group_info, ->comm, keyring
2896  * subscriptions and synchronises with wait4().  Also used in procfs.  Also
2897  * pins the final release of task.io_context.  Also protects ->cpuset and
2898  * ->cgroup.subsys[]. And ->vfork_done.
2899  *
2900  * Nests both inside and outside of read_lock(&tasklist_lock).
2901  * It must not be nested with write_lock_irq(&tasklist_lock),
2902  * neither inside nor outside.
2903  */
2904 static inline void task_lock(struct task_struct *p)
2905 {
2906         spin_lock(&p->alloc_lock);
2907 }
2908
2909 static inline void task_unlock(struct task_struct *p)
2910 {
2911         spin_unlock(&p->alloc_lock);
2912 }
2913
2914 extern struct sighand_struct *__lock_task_sighand(struct task_struct *tsk,
2915                                                         unsigned long *flags);
2916
2917 static inline struct sighand_struct *lock_task_sighand(struct task_struct *tsk,
2918                                                        unsigned long *flags)
2919 {
2920         struct sighand_struct *ret;
2921
2922         ret = __lock_task_sighand(tsk, flags);
2923         (void)__cond_lock(&tsk->sighand->siglock, ret);
2924         return ret;
2925 }
2926
2927 static inline void unlock_task_sighand(struct task_struct *tsk,
2928                                                 unsigned long *flags)
2929 {
2930         spin_unlock_irqrestore(&tsk->sighand->siglock, *flags);
2931 }
2932
2933 /**
2934  * threadgroup_change_begin - mark the beginning of changes to a threadgroup
2935  * @tsk: task causing the changes
2936  *
2937  * All operations which modify a threadgroup - a new thread joining the
2938  * group, death of a member thread (the assertion of PF_EXITING) and
2939  * exec(2) dethreading the process and replacing the leader - are wrapped
2940  * by threadgroup_change_{begin|end}().  This is to provide a place which
2941  * subsystems needing threadgroup stability can hook into for
2942  * synchronization.
2943  */
2944 static inline void threadgroup_change_begin(struct task_struct *tsk)
2945 {
2946         might_sleep();
2947         cgroup_threadgroup_change_begin(tsk);
2948 }
2949
2950 /**
2951  * threadgroup_change_end - mark the end of changes to a threadgroup
2952  * @tsk: task causing the changes
2953  *
2954  * See threadgroup_change_begin().
2955  */
2956 static inline void threadgroup_change_end(struct task_struct *tsk)
2957 {
2958         cgroup_threadgroup_change_end(tsk);
2959 }
2960
2961 #ifdef CONFIG_THREAD_INFO_IN_TASK
2962
2963 static inline struct thread_info *task_thread_info(struct task_struct *task)
2964 {
2965         return &task->thread_info;
2966 }
2967 static inline void *task_stack_page(const struct task_struct *task)
2968 {
2969         return task->stack;
2970 }
2971 #define setup_thread_stack(new,old)     do { } while(0)
2972 static inline unsigned long *end_of_stack(const struct task_struct *task)
2973 {
2974         return task->stack;
2975 }
2976
2977 #elif !defined(__HAVE_THREAD_FUNCTIONS)
2978
2979 #define task_thread_info(task)  ((struct thread_info *)(task)->stack)
2980 #define task_stack_page(task)   ((void *)(task)->stack)
2981
2982 static inline void setup_thread_stack(struct task_struct *p, struct task_struct *org)
2983 {
2984         *task_thread_info(p) = *task_thread_info(org);
2985         task_thread_info(p)->task = p;
2986 }
2987
2988 /*
2989  * Return the address of the last usable long on the stack.
2990  *
2991  * When the stack grows down, this is just above the thread
2992  * info struct. Going any lower will corrupt the threadinfo.
2993  *
2994  * When the stack grows up, this is the highest address.
2995  * Beyond that position, we corrupt data on the next page.
2996  */
2997 static inline unsigned long *end_of_stack(struct task_struct *p)
2998 {
2999 #ifdef CONFIG_STACK_GROWSUP
3000         return (unsigned long *)((unsigned long)task_thread_info(p) + THREAD_SIZE) - 1;
3001 #else
3002         return (unsigned long *)(task_thread_info(p) + 1);
3003 #endif
3004 }
3005
3006 #endif
3007 #define task_stack_end_corrupted(task) \
3008                 (*(end_of_stack(task)) != STACK_END_MAGIC)
3009
3010 static inline int object_is_on_stack(void *obj)
3011 {
3012         void *stack = task_stack_page(current);
3013
3014         return (obj >= stack) && (obj < (stack + THREAD_SIZE));
3015 }
3016
3017 extern void thread_stack_cache_init(void);
3018
3019 #ifdef CONFIG_DEBUG_STACK_USAGE
3020 static inline unsigned long stack_not_used(struct task_struct *p)
3021 {
3022         unsigned long *n = end_of_stack(p);
3023
3024         do {    /* Skip over canary */
3025                 n++;
3026         } while (!*n);
3027
3028         return (unsigned long)n - (unsigned long)end_of_stack(p);
3029 }
3030 #endif
3031 extern void set_task_stack_end_magic(struct task_struct *tsk);
3032
3033 /* set thread flags in other task's structures
3034  * - see asm/thread_info.h for TIF_xxxx flags available
3035  */
3036 static inline void set_tsk_thread_flag(struct task_struct *tsk, int flag)
3037 {
3038         set_ti_thread_flag(task_thread_info(tsk), flag);
3039 }
3040
3041 static inline void clear_tsk_thread_flag(struct task_struct *tsk, int flag)
3042 {
3043         clear_ti_thread_flag(task_thread_info(tsk), flag);
3044 }
3045
3046 static inline int test_and_set_tsk_thread_flag(struct task_struct *tsk, int flag)
3047 {
3048         return test_and_set_ti_thread_flag(task_thread_info(tsk), flag);
3049 }
3050
3051 static inline int test_and_clear_tsk_thread_flag(struct task_struct *tsk, int flag)
3052 {
3053         return test_and_clear_ti_thread_flag(task_thread_info(tsk), flag);
3054 }
3055
3056 static inline int test_tsk_thread_flag(struct task_struct *tsk, int flag)
3057 {
3058         return test_ti_thread_flag(task_thread_info(tsk), flag);
3059 }
3060
3061 static inline void set_tsk_need_resched(struct task_struct *tsk)
3062 {
3063         set_tsk_thread_flag(tsk,TIF_NEED_RESCHED);
3064 }
3065
3066 static inline void clear_tsk_need_resched(struct task_struct *tsk)
3067 {
3068         clear_tsk_thread_flag(tsk,TIF_NEED_RESCHED);
3069 }
3070
3071 static inline int test_tsk_need_resched(struct task_struct *tsk)
3072 {
3073         return unlikely(test_tsk_thread_flag(tsk,TIF_NEED_RESCHED));
3074 }
3075
3076 static inline int restart_syscall(void)
3077 {
3078         set_tsk_thread_flag(current, TIF_SIGPENDING);
3079         return -ERESTARTNOINTR;
3080 }
3081
3082 static inline int signal_pending(struct task_struct *p)
3083 {
3084         return unlikely(test_tsk_thread_flag(p,TIF_SIGPENDING));
3085 }
3086
3087 static inline int __fatal_signal_pending(struct task_struct *p)
3088 {
3089         return unlikely(sigismember(&p->pending.signal, SIGKILL));
3090 }
3091
3092 static inline int fatal_signal_pending(struct task_struct *p)
3093 {
3094         return signal_pending(p) && __fatal_signal_pending(p);
3095 }
3096
3097 static inline int signal_pending_state(long state, struct task_struct *p)
3098 {
3099         if (!(state & (TASK_INTERRUPTIBLE | TASK_WAKEKILL)))
3100                 return 0;
3101         if (!signal_pending(p))
3102                 return 0;
3103
3104         return (state & TASK_INTERRUPTIBLE) || __fatal_signal_pending(p);
3105 }
3106
3107 /*
3108  * cond_resched() and cond_resched_lock(): latency reduction via
3109  * explicit rescheduling in places that are safe. The return
3110  * value indicates whether a reschedule was done in fact.
3111  * cond_resched_lock() will drop the spinlock before scheduling,
3112  * cond_resched_softirq() will enable bhs before scheduling.
3113  */
3114 extern int _cond_resched(void);
3115
3116 #define cond_resched() ({                       \
3117         ___might_sleep(__FILE__, __LINE__, 0);  \
3118         _cond_resched();                        \
3119 })
3120
3121 extern int __cond_resched_lock(spinlock_t *lock);
3122
3123 #define cond_resched_lock(lock) ({                              \
3124         ___might_sleep(__FILE__, __LINE__, PREEMPT_LOCK_OFFSET);\
3125         __cond_resched_lock(lock);                              \
3126 })
3127
3128 extern int __cond_resched_softirq(void);
3129
3130 #define cond_resched_softirq() ({                                       \
3131         ___might_sleep(__FILE__, __LINE__, SOFTIRQ_DISABLE_OFFSET);     \
3132         __cond_resched_softirq();                                       \
3133 })
3134
3135 static inline void cond_resched_rcu(void)
3136 {
3137 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP) || !defined(CONFIG_PREEMPT_RCU)
3138         rcu_read_unlock();
3139         cond_resched();
3140         rcu_read_lock();
3141 #endif
3142 }
3143
3144 /*
3145  * Does a critical section need to be broken due to another
3146  * task waiting?: (technically does not depend on CONFIG_PREEMPT,
3147  * but a general need for low latency)
3148  */
3149 static inline int spin_needbreak(spinlock_t *lock)
3150 {
3151 #ifdef CONFIG_PREEMPT
3152         return spin_is_contended(lock);
3153 #else
3154         return 0;
3155 #endif
3156 }
3157
3158 /*
3159  * Idle thread specific functions to determine the need_resched
3160  * polling state.
3161  */
3162 #ifdef TIF_POLLING_NRFLAG
3163 static inline int tsk_is_polling(struct task_struct *p)
3164 {
3165         return test_tsk_thread_flag(p, TIF_POLLING_NRFLAG);
3166 }
3167
3168 static inline void __current_set_polling(void)
3169 {
3170         set_thread_flag(TIF_POLLING_NRFLAG);
3171 }
3172
3173 static inline bool __must_check current_set_polling_and_test(void)
3174 {
3175         __current_set_polling();
3176
3177         /*
3178          * Polling state must be visible before we test NEED_RESCHED,
3179          * paired by resched_curr()
3180          */
3181         smp_mb__after_atomic();
3182
3183         return unlikely(tif_need_resched());
3184 }
3185
3186 static inline void __current_clr_polling(void)
3187 {
3188         clear_thread_flag(TIF_POLLING_NRFLAG);
3189 }
3190
3191 static inline bool __must_check current_clr_polling_and_test(void)
3192 {
3193         __current_clr_polling();
3194
3195         /*
3196          * Polling state must be visible before we test NEED_RESCHED,
3197          * paired by resched_curr()
3198          */
3199         smp_mb__after_atomic();
3200
3201         return unlikely(tif_need_resched());
3202 }
3203
3204 #else
3205 static inline int tsk_is_polling(struct task_struct *p) { return 0; }
3206 static inline void __current_set_polling(void) { }
3207 static inline void __current_clr_polling(void) { }
3208
3209 static inline bool __must_check current_set_polling_and_test(void)
3210 {
3211         return unlikely(tif_need_resched());
3212 }
3213 static inline bool __must_check current_clr_polling_and_test(void)
3214 {
3215         return unlikely(tif_need_resched());
3216 }
3217 #endif
3218
3219 static inline void current_clr_polling(void)
3220 {
3221         __current_clr_polling();
3222
3223         /*
3224          * Ensure we check TIF_NEED_RESCHED after we clear the polling bit.
3225          * Once the bit is cleared, we'll get IPIs with every new
3226          * TIF_NEED_RESCHED and the IPI handler, scheduler_ipi(), will also
3227          * fold.
3228          */
3229         smp_mb(); /* paired with resched_curr() */
3230
3231         preempt_fold_need_resched();
3232 }
3233
3234 static __always_inline bool need_resched(void)
3235 {
3236         return unlikely(tif_need_resched());
3237 }
3238
3239 /*
3240  * Thread group CPU time accounting.
3241  */
3242 void thread_group_cputime(struct task_struct *tsk, struct task_cputime *times);
3243 void thread_group_cputimer(struct task_struct *tsk, struct task_cputime *times);
3244
3245 /*
3246  * Reevaluate whether the task has signals pending delivery.
3247  * Wake the task if so.
3248  * This is required every time the blocked sigset_t changes.
3249  * callers must hold sighand->siglock.
3250  */
3251 extern void recalc_sigpending_and_wake(struct task_struct *t);
3252 extern void recalc_sigpending(void);
3253
3254 extern void signal_wake_up_state(struct task_struct *t, unsigned int state);
3255
3256 static inline void signal_wake_up(struct task_struct *t, bool resume)
3257 {
3258         signal_wake_up_state(t, resume ? TASK_WAKEKILL : 0);
3259 }
3260 static inline void ptrace_signal_wake_up(struct task_struct *t, bool resume)
3261 {
3262         signal_wake_up_state(t, resume ? __TASK_TRACED : 0);
3263 }
3264
3265 /*
3266  * Wrappers for p->thread_info->cpu access. No-op on UP.
3267  */
3268 #ifdef CONFIG_SMP
3269
3270 static inline unsigned int task_cpu(const struct task_struct *p)
3271 {
3272 #ifdef CONFIG_THREAD_INFO_IN_TASK
3273         return p->cpu;
3274 #else
3275         return task_thread_info(p)->cpu;
3276 #endif
3277 }
3278
3279 static inline int task_node(const struct task_struct *p)
3280 {
3281         return cpu_to_node(task_cpu(p));
3282 }
3283
3284 extern void set_task_cpu(struct task_struct *p, unsigned int cpu);
3285
3286 #else
3287
3288 static inline unsigned int task_cpu(const struct task_struct *p)
3289 {
3290         return 0;
3291 }
3292
3293 static inline void set_task_cpu(struct task_struct *p, unsigned int cpu)
3294 {
3295 }
3296
3297 #endif /* CONFIG_SMP */
3298
3299 extern long sched_setaffinity(pid_t pid, const struct cpumask *new_mask);
3300 extern long sched_getaffinity(pid_t pid, struct cpumask *mask);
3301
3302 #ifdef CONFIG_CGROUP_SCHED
3303 extern struct task_group root_task_group;
3304 #endif /* CONFIG_CGROUP_SCHED */
3305
3306 extern int task_can_switch_user(struct user_struct *up,
3307                                         struct task_struct *tsk);
3308
3309 #ifdef CONFIG_TASK_XACCT
3310 static inline void add_rchar(struct task_struct *tsk, ssize_t amt)
3311 {
3312         tsk->ioac.rchar += amt;
3313 }
3314
3315 static inline void add_wchar(struct task_struct *tsk, ssize_t amt)
3316 {
3317         tsk->ioac.wchar += amt;
3318 }
3319
3320 static inline void inc_syscr(struct task_struct *tsk)
3321 {
3322         tsk->ioac.syscr++;
3323 }
3324
3325 static inline void inc_syscw(struct task_struct *tsk)
3326 {
3327         tsk->ioac.syscw++;
3328 }
3329
3330 static inline void inc_syscfs(struct task_struct *tsk)
3331 {
3332         tsk->ioac.syscfs++;
3333 }
3334 #else
3335 static inline void add_rchar(struct task_struct *tsk, ssize_t amt)
3336 {
3337 }
3338
3339 static inline void add_wchar(struct task_struct *tsk, ssize_t amt)
3340 {
3341 }
3342
3343 static inline void inc_syscr(struct task_struct *tsk)
3344 {
3345 }
3346
3347 static inline void inc_syscw(struct task_struct *tsk)
3348 {
3349 }
3350 static inline void inc_syscfs(struct task_struct *tsk)
3351 {
3352 }
3353 #endif
3354
3355 #ifndef TASK_SIZE_OF
3356 #define TASK_SIZE_OF(tsk)       TASK_SIZE
3357 #endif
3358
3359 #ifdef CONFIG_MEMCG
3360 extern void mm_update_next_owner(struct mm_struct *mm);
3361 #else
3362 static inline void mm_update_next_owner(struct mm_struct *mm)
3363 {
3364 }
3365 #endif /* CONFIG_MEMCG */
3366
3367 static inline unsigned long task_rlimit(const struct task_struct *tsk,
3368                 unsigned int limit)
3369 {
3370         return READ_ONCE(tsk->signal->rlim[limit].rlim_cur);
3371 }
3372
3373 static inline unsigned long task_rlimit_max(const struct task_struct *tsk,
3374                 unsigned int limit)
3375 {
3376         return READ_ONCE(tsk->signal->rlim[limit].rlim_max);
3377 }
3378
3379 static inline unsigned long rlimit(unsigned int limit)
3380 {
3381         return task_rlimit(current, limit);
3382 }
3383
3384 static inline unsigned long rlimit_max(unsigned int limit)
3385 {
3386         return task_rlimit_max(current, limit);
3387 }
3388
3389 #define SCHED_CPUFREQ_RT        (1U << 0)
3390 #define SCHED_CPUFREQ_DL        (1U << 1)
3391 #define SCHED_CPUFREQ_IOWAIT    (1U << 2)
3392
3393 #ifdef CONFIG_CPU_FREQ
3394 struct update_util_data {
3395         void (*func)(struct update_util_data *data, u64 time, unsigned int flags);
3396 };
3397
3398 void cpufreq_add_update_util_hook(int cpu, struct update_util_data *data,
3399                        void (*func)(struct update_util_data *data, u64 time,
3400                                     unsigned int flags));
3401 void cpufreq_remove_update_util_hook(int cpu);
3402 #endif /* CONFIG_CPU_FREQ */
3403
3404 #endif