1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_SCHED_H
3 #define _LINUX_SCHED_H
4 
5 /*
6  * Define 'struct task_struct' and provide the main scheduler
7  * APIs (schedule(), wakeup variants, etc.)
8  */
9 
10 #include <uapi/linux/sched.h>
11 
12 #include <asm/current.h>
13 
14 #include <linux/pid.h>
15 #include <linux/sem.h>
16 #include <linux/shm.h>
17 #include <linux/mutex.h>
18 #include <linux/plist.h>
19 #include <linux/hrtimer.h>
20 #include <linux/irqflags.h>
21 #include <linux/seccomp.h>
22 #include <linux/nodemask.h>
23 #include <linux/rcupdate.h>
24 #include <linux/refcount.h>
25 #include <linux/resource.h>
26 #include <linux/latencytop.h>
27 #include <linux/sched/prio.h>
28 #include <linux/sched/types.h>
29 #include <linux/signal_types.h>
30 #include <linux/syscall_user_dispatch.h>
31 #include <linux/mm_types_task.h>
32 #include <linux/task_io_accounting.h>
33 #include <linux/posix-timers.h>
34 #include <linux/rseq.h>
35 #include <linux/seqlock.h>
36 #include <linux/kcsan.h>
37 #include <asm/kmap_size.h>
38 
39 /* task_struct member predeclarations (sorted alphabetically): */
40 struct audit_context;
41 struct backing_dev_info;
42 struct bio_list;
43 struct blk_plug;
44 struct bpf_local_storage;
45 struct bpf_run_ctx;
46 struct capture_control;
47 struct cfs_rq;
48 struct fs_struct;
49 struct futex_pi_state;
50 struct io_context;
51 struct io_uring_task;
52 struct mempolicy;
53 struct nameidata;
54 struct nsproxy;
55 struct perf_event_context;
56 struct pid_namespace;
57 struct pipe_inode_info;
58 struct rcu_node;
59 struct reclaim_state;
60 struct robust_list_head;
61 struct root_domain;
62 struct rq;
63 struct sched_attr;
64 struct sched_param;
65 struct seq_file;
66 struct sighand_struct;
67 struct signal_struct;
68 struct task_delay_info;
69 struct task_group;
70 
71 /*
72  * Task state bitmask. NOTE! These bits are also
73  * encoded in fs/proc/array.c: get_task_state().
74  *
75  * We have two separate sets of flags: task->state
76  * is about runnability, while task->exit_state are
77  * about the task exiting. Confusing, but this way
78  * modifying one set can't modify the other one by
79  * mistake.
80  */
81 
82 /* Used in tsk->state: */
83 ///就绪态或正在运行,都用running
84 #define TASK_RUNNING			0x0000
85 #define TASK_INTERRUPTIBLE		0x0001
86 #define TASK_UNINTERRUPTIBLE		0x0002
87 #define __TASK_STOPPED			0x0004
88 #define __TASK_TRACED			0x0008
89 /* Used in tsk->exit_state: */
90 #define EXIT_DEAD			0x0010
91 #define EXIT_ZOMBIE			0x0020
92 #define EXIT_TRACE			(EXIT_ZOMBIE | EXIT_DEAD)
93 /* Used in tsk->state again: */
94 #define TASK_PARKED			0x0040
95 #define TASK_DEAD			0x0080
96 #define TASK_WAKEKILL			0x0100
97 #define TASK_WAKING			0x0200
98 #define TASK_NOLOAD			0x0400
99 #define TASK_NEW			0x0800
100 /* RT specific auxilliary flag to mark RT lock waiters */
101 #define TASK_RTLOCK_WAIT		0x1000
102 #define TASK_STATE_MAX			0x2000
103 
104 /* Convenience macros for the sake of set_current_state: */
105 #define TASK_KILLABLE			(TASK_WAKEKILL | TASK_UNINTERRUPTIBLE)
106 #define TASK_STOPPED			(TASK_WAKEKILL | __TASK_STOPPED)
107 #define TASK_TRACED			(TASK_WAKEKILL | __TASK_TRACED)
108 
109 #define TASK_IDLE			(TASK_UNINTERRUPTIBLE | TASK_NOLOAD)
110 
111 /* Convenience macros for the sake of wake_up(): */
112 #define TASK_NORMAL			(TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE)
113 
114 /* get_task_state(): */
115 #define TASK_REPORT			(TASK_RUNNING | TASK_INTERRUPTIBLE | \
116 					 TASK_UNINTERRUPTIBLE | __TASK_STOPPED | \
117 					 __TASK_TRACED | EXIT_DEAD | EXIT_ZOMBIE | \
118 					 TASK_PARKED)
119 
120 #define task_is_running(task)		(READ_ONCE((task)->__state) == TASK_RUNNING)
121 
122 #define task_is_traced(task)		((READ_ONCE(task->__state) & __TASK_TRACED) != 0)
123 
124 #define task_is_stopped(task)		((READ_ONCE(task->__state) & __TASK_STOPPED) != 0)
125 
126 #define task_is_stopped_or_traced(task)	((READ_ONCE(task->__state) & (__TASK_STOPPED | __TASK_TRACED)) != 0)
127 
128 /*
129  * Special states are those that do not use the normal wait-loop pattern. See
130  * the comment with set_special_state().
131  */
132 #define is_special_task_state(state)				\
133 	((state) & (__TASK_STOPPED | __TASK_TRACED | TASK_PARKED | TASK_DEAD))
134 
135 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
136 # define debug_normal_state_change(state_value)				\
137 	do {								\
138 		WARN_ON_ONCE(is_special_task_state(state_value));	\
139 		current->task_state_change = _THIS_IP_;			\
140 	} while (0)
141 
142 # define debug_special_state_change(state_value)			\
143 	do {								\
144 		WARN_ON_ONCE(!is_special_task_state(state_value));	\
145 		current->task_state_change = _THIS_IP_;			\
146 	} while (0)
147 
148 # define debug_rtlock_wait_set_state()					\
149 	do {								 \
150 		current->saved_state_change = current->task_state_change;\
151 		current->task_state_change = _THIS_IP_;			 \
152 	} while (0)
153 
154 # define debug_rtlock_wait_restore_state()				\
155 	do {								 \
156 		current->task_state_change = current->saved_state_change;\
157 	} while (0)
158 
159 #else
160 # define debug_normal_state_change(cond)	do { } while (0)
161 # define debug_special_state_change(cond)	do { } while (0)
162 # define debug_rtlock_wait_set_state()		do { } while (0)
163 # define debug_rtlock_wait_restore_state()	do { } while (0)
164 #endif
165 
166 /*
167  * set_current_state() includes a barrier so that the write of current->state
168  * is correctly serialised wrt the caller's subsequent test of whether to
169  * actually sleep:
170  *
171  *   for (;;) {
172  *	set_current_state(TASK_UNINTERRUPTIBLE);
173  *	if (CONDITION)
174  *	   break;
175  *
176  *	schedule();
177  *   }
178  *   __set_current_state(TASK_RUNNING);
179  *
180  * If the caller does not need such serialisation (because, for instance, the
181  * CONDITION test and condition change and wakeup are under the same lock) then
182  * use __set_current_state().
183  *
184  * The above is typically ordered against the wakeup, which does:
185  *
186  *   CONDITION = 1;
187  *   wake_up_state(p, TASK_UNINTERRUPTIBLE);
188  *
189  * where wake_up_state()/try_to_wake_up() executes a full memory barrier before
190  * accessing p->state.
191  *
192  * Wakeup will do: if (@state & p->state) p->state = TASK_RUNNING, that is,
193  * once it observes the TASK_UNINTERRUPTIBLE store the waking CPU can issue a
194  * TASK_RUNNING store which can collide with __set_current_state(TASK_RUNNING).
195  *
196  * However, with slightly different timing the wakeup TASK_RUNNING store can
197  * also collide with the TASK_UNINTERRUPTIBLE store. Losing that store is not
198  * a problem either because that will result in one extra go around the loop
199  * and our @cond test will save the day.
200  *
201  * Also see the comments of try_to_wake_up().
202  */
203 #define __set_current_state(state_value)				\
204 	do {								\
205 		debug_normal_state_change((state_value));		\
206 		WRITE_ONCE(current->__state, (state_value));		\
207 	} while (0)
208 
209 #define set_current_state(state_value)					\
210 	do {								\
211 		debug_normal_state_change((state_value));		\
212 		smp_store_mb(current->__state, (state_value));		\
213 	} while (0)
214 
215 /*
216  * set_special_state() should be used for those states when the blocking task
217  * can not use the regular condition based wait-loop. In that case we must
218  * serialize against wakeups such that any possible in-flight TASK_RUNNING
219  * stores will not collide with our state change.
220  */
221 #define set_special_state(state_value)					\
222 	do {								\
223 		unsigned long flags; /* may shadow */			\
224 									\
225 		raw_spin_lock_irqsave(&current->pi_lock, flags);	\
226 		debug_special_state_change((state_value));		\
227 		WRITE_ONCE(current->__state, (state_value));		\
228 		raw_spin_unlock_irqrestore(&current->pi_lock, flags);	\
229 	} while (0)
230 
231 /*
232  * PREEMPT_RT specific variants for "sleeping" spin/rwlocks
233  *
234  * RT's spin/rwlock substitutions are state preserving. The state of the
235  * task when blocking on the lock is saved in task_struct::saved_state and
236  * restored after the lock has been acquired.  These operations are
237  * serialized by task_struct::pi_lock against try_to_wake_up(). Any non RT
238  * lock related wakeups while the task is blocked on the lock are
239  * redirected to operate on task_struct::saved_state to ensure that these
240  * are not dropped. On restore task_struct::saved_state is set to
241  * TASK_RUNNING so any wakeup attempt redirected to saved_state will fail.
242  *
243  * The lock operation looks like this:
244  *
245  *	current_save_and_set_rtlock_wait_state();
246  *	for (;;) {
247  *		if (try_lock())
248  *			break;
249  *		raw_spin_unlock_irq(&lock->wait_lock);
250  *		schedule_rtlock();
251  *		raw_spin_lock_irq(&lock->wait_lock);
252  *		set_current_state(TASK_RTLOCK_WAIT);
253  *	}
254  *	current_restore_rtlock_saved_state();
255  */
256 #define current_save_and_set_rtlock_wait_state()			\
257 	do {								\
258 		lockdep_assert_irqs_disabled();				\
259 		raw_spin_lock(&current->pi_lock);			\
260 		current->saved_state = current->__state;		\
261 		debug_rtlock_wait_set_state();				\
262 		WRITE_ONCE(current->__state, TASK_RTLOCK_WAIT);		\
263 		raw_spin_unlock(&current->pi_lock);			\
264 	} while (0);
265 
266 #define current_restore_rtlock_saved_state()				\
267 	do {								\
268 		lockdep_assert_irqs_disabled();				\
269 		raw_spin_lock(&current->pi_lock);			\
270 		debug_rtlock_wait_restore_state();			\
271 		WRITE_ONCE(current->__state, current->saved_state);	\
272 		current->saved_state = TASK_RUNNING;			\
273 		raw_spin_unlock(&current->pi_lock);			\
274 	} while (0);
275 
276 #define get_current_state()	READ_ONCE(current->__state)
277 
278 /* Task command name length: */
279 #define TASK_COMM_LEN			16
280 
281 extern void scheduler_tick(void);
282 
283 #define	MAX_SCHEDULE_TIMEOUT		LONG_MAX
284 
285 extern long schedule_timeout(long timeout);
286 extern long schedule_timeout_interruptible(long timeout);
287 extern long schedule_timeout_killable(long timeout);
288 extern long schedule_timeout_uninterruptible(long timeout);
289 extern long schedule_timeout_idle(long timeout);
290 asmlinkage void schedule(void);
291 extern void schedule_preempt_disabled(void);
292 asmlinkage void preempt_schedule_irq(void);
293 #ifdef CONFIG_PREEMPT_RT
294  extern void schedule_rtlock(void);
295 #endif
296 
297 extern int __must_check io_schedule_prepare(void);
298 extern void io_schedule_finish(int token);
299 extern long io_schedule_timeout(long timeout);
300 extern void io_schedule(void);
301 
302 /**
303  * struct prev_cputime - snapshot of system and user cputime
304  * @utime: time spent in user mode
305  * @stime: time spent in system mode
306  * @lock: protects the above two fields
307  *
308  * Stores previous user/system time values such that we can guarantee
309  * monotonicity.
310  */
311 struct prev_cputime {
312 #ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
313 	u64				utime;
314 	u64				stime;
315 	raw_spinlock_t			lock;
316 #endif
317 };
318 
319 enum vtime_state {
320 	/* Task is sleeping or running in a CPU with VTIME inactive: */
321 	VTIME_INACTIVE = 0,
322 	/* Task is idle */
323 	VTIME_IDLE,
324 	/* Task runs in kernelspace in a CPU with VTIME active: */
325 	VTIME_SYS,
326 	/* Task runs in userspace in a CPU with VTIME active: */
327 	VTIME_USER,
328 	/* Task runs as guests in a CPU with VTIME active: */
329 	VTIME_GUEST,
330 };
331 
332 struct vtime {
333 	seqcount_t		seqcount;
334 	unsigned long long	starttime;
335 	enum vtime_state	state;
336 	unsigned int		cpu;
337 	u64			utime;
338 	u64			stime;
339 	u64			gtime;
340 };
341 
342 /*
343  * Utilization clamp constraints.
344  * @UCLAMP_MIN:	Minimum utilization
345  * @UCLAMP_MAX:	Maximum utilization
346  * @UCLAMP_CNT:	Utilization clamp constraints count
347  */
348 enum uclamp_id {
349 	UCLAMP_MIN = 0,
350 	UCLAMP_MAX,
351 	UCLAMP_CNT
352 };
353 
354 #ifdef CONFIG_SMP
355 extern struct root_domain def_root_domain;
356 extern struct mutex sched_domains_mutex;
357 #endif
358 
359 struct sched_info {
360 #ifdef CONFIG_SCHED_INFO
361 	/* Cumulative counters: */
362 
363 	/* # of times we have run on this CPU: */
364 	unsigned long			pcount;
365 
366 	/* Time spent waiting on a runqueue: */
367 	unsigned long long		run_delay;
368 
369 	/* Timestamps: */
370 
371 	/* When did we last run on a CPU? */
372 	unsigned long long		last_arrival;
373 
374 	/* When were we last queued to run? */
375 	unsigned long long		last_queued;
376 
377 #endif /* CONFIG_SCHED_INFO */
378 };
379 
380 /*
381  * Integer metrics need fixed point arithmetic, e.g., sched/fair
382  * has a few: load, load_avg, util_avg, freq, and capacity.
383  *
384  * We define a basic fixed point arithmetic range, and then formalize
385  * all these metrics based on that basic range.
386  */
387 # define SCHED_FIXEDPOINT_SHIFT		10
388 # define SCHED_FIXEDPOINT_SCALE		(1L << SCHED_FIXEDPOINT_SHIFT)
389 
390 /* Increase resolution of cpu_capacity calculations */
391 # define SCHED_CAPACITY_SHIFT		SCHED_FIXEDPOINT_SHIFT
392 # define SCHED_CAPACITY_SCALE		(1L << SCHED_CAPACITY_SHIFT)
393 
394 struct load_weight {
395 	unsigned long			weight;
396 	u32				inv_weight;
397 };
398 
399 /**
400  * struct util_est - Estimation utilization of FAIR tasks
401  * @enqueued: instantaneous estimated utilization of a task/cpu
402  * @ewma:     the Exponential Weighted Moving Average (EWMA)
403  *            utilization of a task
404  *
405  * Support data structure to track an Exponential Weighted Moving Average
406  * (EWMA) of a FAIR task's utilization. New samples are added to the moving
407  * average each time a task completes an activation. Sample's weight is chosen
408  * so that the EWMA will be relatively insensitive to transient changes to the
409  * task's workload.
410  *
411  * The enqueued attribute has a slightly different meaning for tasks and cpus:
412  * - task:   the task's util_avg at last task dequeue time
413  * - cfs_rq: the sum of util_est.enqueued for each RUNNABLE task on that CPU
414  * Thus, the util_est.enqueued of a task represents the contribution on the
415  * estimated utilization of the CPU where that task is currently enqueued.
416  *
417  * Only for tasks we track a moving average of the past instantaneous
418  * estimated utilization. This allows to absorb sporadic drops in utilization
419  * of an otherwise almost periodic task.
420  *
421  * The UTIL_AVG_UNCHANGED flag is used to synchronize util_est with util_avg
422  * updates. When a task is dequeued, its util_est should not be updated if its
423  * util_avg has not been updated in the meantime.
424  * This information is mapped into the MSB bit of util_est.enqueued at dequeue
425  * time. Since max value of util_est.enqueued for a task is 1024 (PELT util_avg
426  * for a task) it is safe to use MSB.
427  */
428 struct util_est {
429 	unsigned int			enqueued;
430 	unsigned int			ewma;
431 #define UTIL_EST_WEIGHT_SHIFT		2
432 #define UTIL_AVG_UNCHANGED		0x80000000
433 } __attribute__((__aligned__(sizeof(u64))));
434 
435 /*
436  * The load/runnable/util_avg accumulates an infinite geometric series
437  * (see __update_load_avg_cfs_rq() in kernel/sched/pelt.c).
438  *
439  * [load_avg definition]
440  *
441  *   load_avg = runnable% * scale_load_down(load)
442  *
443  * [runnable_avg definition]
444  *
445  *   runnable_avg = runnable% * SCHED_CAPACITY_SCALE
446  *
447  * [util_avg definition]
448  *
449  *   util_avg = running% * SCHED_CAPACITY_SCALE
450  *
451  * where runnable% is the time ratio that a sched_entity is runnable and
452  * running% the time ratio that a sched_entity is running.
453  *
454  * For cfs_rq, they are the aggregated values of all runnable and blocked
455  * sched_entities.
456  *
457  * The load/runnable/util_avg doesn't directly factor frequency scaling and CPU
458  * capacity scaling. The scaling is done through the rq_clock_pelt that is used
459  * for computing those signals (see update_rq_clock_pelt())
460  *
461  * N.B., the above ratios (runnable% and running%) themselves are in the
462  * range of [0, 1]. To do fixed point arithmetics, we therefore scale them
463  * to as large a range as necessary. This is for example reflected by
464  * util_avg's SCHED_CAPACITY_SCALE.
465  *
466  * [Overflow issue]
467  *
468  * The 64-bit load_sum can have 4353082796 (=2^64/47742/88761) entities
469  * with the highest load (=88761), always runnable on a single cfs_rq,
470  * and should not overflow as the number already hits PID_MAX_LIMIT.
471  *
472  * For all other cases (including 32-bit kernels), struct load_weight's
473  * weight will overflow first before we do, because:
474  *
475  *    Max(load_avg) <= Max(load.weight)
476  *
477  * Then it is the load_weight's responsibility to consider overflow
478  * issues.
479  */
480 
481 ///IO型进程runnable_load_sum比CPU型小很多
482 struct sched_avg {
483 	u64				last_update_time;  		///上一次更新的时间点
484 
485 	///1.对于调度实体,load_sum统计对象是调度实体在可运行状态下的累计衰减总时间, 值为时间
486 	///2.对调度队列,load_sum=decay_sum_load统计"所有进程"的累计工作总负载(时间乘以权重), 值为负载
487 	u64				load_sum;	///对应量化负载	load_avg
488 
489 	///调度实体:就绪队列里可运行状态下的累计总衰减时间decay_sum_time
490 	///调度队列:统计就绪队列里"所有可运行状态"下进程的累计总负载decay_sum_load
491 	u64				runnable_sum;///对应量化负载runnable_avg
492 
493 	///1调度实体:正在运行状态下累计衰减时间;
494 	///2调度队列:所有处于正在运行状态的衰减总时间
495 	u32				util_sum;  ///对应量化算力util_avg
496 
497 	///上一次采样,不能凑成一个周期()的时间
498 	u32				period_contrib;
499 
500 	///1.调度实体: 总量化负载,load_avg==runnable_avg;
501 	///2.调度队列:
502 	///           load_avg,所有进程量化总负载;
503 	///           runnable_avg,可运行状态量化总负载
504 	unsigned long			load_avg;
505 	unsigned long			runnable_avg; ///在SMP负载均衡调度器中用于衡量CPU是否繁忙
506 
507 	///用于EAS调度器和CPU调频
508 	unsigned long			util_avg;///实际算力
509 	struct util_est			util_est;
510 } ____cacheline_aligned;
511 
512 struct sched_statistics {
513 #ifdef CONFIG_SCHEDSTATS
514 	u64				wait_start;
515 	u64				wait_max;
516 	u64				wait_count;
517 	u64				wait_sum;
518 	u64				iowait_count;
519 	u64				iowait_sum;
520 
521 	u64				sleep_start;
522 	u64				sleep_max;
523 	s64				sum_sleep_runtime;
524 
525 	u64				block_start;
526 	u64				block_max;
527 	u64				exec_max;
528 	u64				slice_max;
529 
530 	u64				nr_migrations_cold;
531 	u64				nr_failed_migrations_affine;
532 	u64				nr_failed_migrations_running;
533 	u64				nr_failed_migrations_hot;
534 	u64				nr_forced_migrations;
535 
536 	u64				nr_wakeups;
537 	u64				nr_wakeups_sync;
538 	u64				nr_wakeups_migrate;
539 	u64				nr_wakeups_local;
540 	u64				nr_wakeups_remote;
541 	u64				nr_wakeups_affine;
542 	u64				nr_wakeups_affine_attempts;
543 	u64				nr_wakeups_passive;
544 	u64				nr_wakeups_idle;
545 #endif
546 };
547 
548 struct sched_entity {
549 	/* For load-balancing: */
550 	struct load_weight		load;         ///权重信息,计算vruntime的时候,会用到in_weight
551 	struct rb_node			run_node;     ///红黑树挂载点
552 	struct list_head		group_node;   ///se加入就绪队列后,添加到rq->cfs_tasks链表
553 	unsigned int			on_rq;        ///已加入就绪队列,on_rq=1,否则on_rq=0
554 
555 	u64				exec_start;             ///se虚拟时间的起始时间
556 	u64				sum_exec_runtime;       ///实际运行时间总和
557 	u64				vruntime;               ///虚拟运行时间,加权后的时间,单位ns,与定时器节拍无关
558 	u64				prev_sum_exec_runtime;  ///上一次统计se运行总时间
559 
560 	u64				nr_migrations;          ///该se发生迁移的次数
561 
562 	struct sched_statistics		statistics;             ///统计信息
563 
564 #ifdef CONFIG_FAIR_GROUP_SCHED
565 	int				depth;
566 	struct sched_entity		*parent;
567 	/* rq on which this entity is (to be) queued: */
568 	///该se挂在到cfs_rq,指向parent->my_rq
569 	struct cfs_rq			*cfs_rq;
570 	/* rq "owned" by this entity/group: */
571 	///本se的cfs_rq,只有group se才有cfs_rq,task_se为NULl
572 	struct cfs_rq			*my_q;
573 	/* cached value of my_q->h_nr_running */
574 	unsigned long			runnable_weight;
575 #endif
576 
577 #ifdef CONFIG_SMP
578 	/*
579 	 * Per entity load average tracking.
580 	 *
581 	 * Put into separate cache line so it does not
582 	 * collide with read-mostly values above.
583 	 */
584 	struct sched_avg		avg;   ///负载相关的信息
585 #endif
586 };
587 
588 struct sched_rt_entity {
589 	struct list_head		run_list;
590 	unsigned long			timeout;
591 	unsigned long			watchdog_stamp;
592 	unsigned int			time_slice;
593 	unsigned short			on_rq;
594 	unsigned short			on_list;
595 
596 	struct sched_rt_entity		*back;
597 #ifdef CONFIG_RT_GROUP_SCHED
598 	struct sched_rt_entity		*parent;
599 	/* rq on which this entity is (to be) queued: */
600 	struct rt_rq			*rt_rq;
601 	/* rq "owned" by this entity/group: */
602 	struct rt_rq			*my_q;
603 #endif
604 } __randomize_layout;
605 
606 struct sched_dl_entity {
607 	struct rb_node			rb_node;
608 
609 	/*
610 	 * Original scheduling parameters. Copied here from sched_attr
611 	 * during sched_setattr(), they will remain the same until
612 	 * the next sched_setattr().
613 	 */
614 	u64				dl_runtime;	/* Maximum runtime for each instance	*/
615 	u64				dl_deadline;	/* Relative deadline of each instance	*/
616 	u64				dl_period;	/* Separation of two instances (period) */
617 	u64				dl_bw;		/* dl_runtime / dl_period		*/
618 	u64				dl_density;	/* dl_runtime / dl_deadline		*/
619 
620 	/*
621 	 * Actual scheduling parameters. Initialized with the values above,
622 	 * they are continuously updated during task execution. Note that
623 	 * the remaining runtime could be < 0 in case we are in overrun.
624 	 */
625 	s64				runtime;	/* Remaining runtime for this instance	*/
626 	u64				deadline;	/* Absolute deadline for this instance	*/
627 	unsigned int			flags;		/* Specifying the scheduler behaviour	*/
628 
629 	/*
630 	 * Some bool flags:
631 	 *
632 	 * @dl_throttled tells if we exhausted the runtime. If so, the
633 	 * task has to wait for a replenishment to be performed at the
634 	 * next firing of dl_timer.
635 	 *
636 	 * @dl_boosted tells if we are boosted due to DI. If so we are
637 	 * outside bandwidth enforcement mechanism (but only until we
638 	 * exit the critical section);
639 	 *
640 	 * @dl_yielded tells if task gave up the CPU before consuming
641 	 * all its available runtime during the last job.
642 	 *
643 	 * @dl_non_contending tells if the task is inactive while still
644 	 * contributing to the active utilization. In other words, it
645 	 * indicates if the inactive timer has been armed and its handler
646 	 * has not been executed yet. This flag is useful to avoid race
647 	 * conditions between the inactive timer handler and the wakeup
648 	 * code.
649 	 *
650 	 * @dl_overrun tells if the task asked to be informed about runtime
651 	 * overruns.
652 	 */
653 	unsigned int			dl_throttled      : 1;
654 	unsigned int			dl_yielded        : 1;
655 	unsigned int			dl_non_contending : 1;
656 	unsigned int			dl_overrun	  : 1;
657 
658 	/*
659 	 * Bandwidth enforcement timer. Each -deadline task has its
660 	 * own bandwidth to be enforced, thus we need one timer per task.
661 	 */
662 	struct hrtimer			dl_timer;
663 
664 	/*
665 	 * Inactive timer, responsible for decreasing the active utilization
666 	 * at the "0-lag time". When a -deadline task blocks, it contributes
667 	 * to GRUB's active utilization until the "0-lag time", hence a
668 	 * timer is needed to decrease the active utilization at the correct
669 	 * time.
670 	 */
671 	struct hrtimer inactive_timer;
672 
673 #ifdef CONFIG_RT_MUTEXES
674 	/*
675 	 * Priority Inheritance. When a DEADLINE scheduling entity is boosted
676 	 * pi_se points to the donor, otherwise points to the dl_se it belongs
677 	 * to (the original one/itself).
678 	 */
679 	struct sched_dl_entity *pi_se;
680 #endif
681 };
682 
683 #ifdef CONFIG_UCLAMP_TASK
684 /* Number of utilization clamp buckets (shorter alias) */
685 #define UCLAMP_BUCKETS CONFIG_UCLAMP_BUCKETS_COUNT
686 
687 /*
688  * Utilization clamp for a scheduling entity
689  * @value:		clamp value "assigned" to a se
690  * @bucket_id:		bucket index corresponding to the "assigned" value
691  * @active:		the se is currently refcounted in a rq's bucket
692  * @user_defined:	the requested clamp value comes from user-space
693  *
694  * The bucket_id is the index of the clamp bucket matching the clamp value
695  * which is pre-computed and stored to avoid expensive integer divisions from
696  * the fast path.
697  *
698  * The active bit is set whenever a task has got an "effective" value assigned,
699  * which can be different from the clamp value "requested" from user-space.
700  * This allows to know a task is refcounted in the rq's bucket corresponding
701  * to the "effective" bucket_id.
702  *
703  * The user_defined bit is set whenever a task has got a task-specific clamp
704  * value requested from userspace, i.e. the system defaults apply to this task
705  * just as a restriction. This allows to relax default clamps when a less
706  * restrictive task-specific value has been requested, thus allowing to
707  * implement a "nice" semantic. For example, a task running with a 20%
708  * default boost can still drop its own boosting to 0%.
709  */
710 struct uclamp_se {
711 	unsigned int value		: bits_per(SCHED_CAPACITY_SCALE);
712 	unsigned int bucket_id		: bits_per(UCLAMP_BUCKETS);
713 	unsigned int active		: 1;
714 	unsigned int user_defined	: 1;
715 };
716 #endif /* CONFIG_UCLAMP_TASK */
717 
718 union rcu_special {
719 	struct {
720 		u8			blocked;
721 		u8			need_qs;
722 		u8			exp_hint; /* Hint for performance. */
723 		u8			need_mb; /* Readers need smp_mb(). */
724 	} b; /* Bits. */
725 	u32 s; /* Set of bits. */
726 };
727 
728 enum perf_event_task_context {
729 	perf_invalid_context = -1,
730 	perf_hw_context = 0,
731 	perf_sw_context,
732 	perf_nr_task_contexts,
733 };
734 
735 struct wake_q_node {
736 	struct wake_q_node *next;
737 };
738 
739 struct kmap_ctrl {
740 #ifdef CONFIG_KMAP_LOCAL
741 	int				idx;
742 	pte_t				pteval[KM_MAX_IDX];
743 #endif
744 };
745 
746 struct task_struct {
747 #ifdef CONFIG_THREAD_INFO_IN_TASK
748 	/*
749 	 * For reasons of header soup (see current_thread_info()), this
750 	 * must be the first element of task_struct.
751 	 */
752 	 ///Linux5.0中thread_info从内核栈移到了task_struct
753 	 ///ARM64的SP_EL0用来存放当前进程的task_struct地址
754 	struct thread_info		thread_info;
755 #endif
756 	/*
757 	 * 进程存续期间的状态:
758 	 * 1.TASK_RUNNING:就绪态和运行态都是TASK_RUNNING
759 	 * 		就绪态:唯一等待的资源是CPU,并拿到CPU可以立即运行,放在运行队列中rq;
760 	 * 		运行态:正在运行的当前进程;
761 	 *
762 	 * 2.TASK_INTERRUPTIBLE:浅度睡眠,可中断的等待状态;
763 	 * 		睡眠等待某事件或资源,当得到满足时,可以被信号唤醒,
764 	 * 		进程状态变为TASK_RUNNING, 加入运行队列rq; *
765 	 * 3.TASK_UNINTERRUPTIBLE:深度睡眠,不可中断的等待状态;
766 	 * 		该状态进程等待某个事件或资源,等待过程不能被打断,不响应任何外部信号;
767 	 * 		比如,从磁盘读入可执行代码过程中,又有代码需要从磁盘读取,会造成嵌套睡眠;
768 	 *
769 	 * 4.TASK_STOPPED:暂停状态
770 	 * 		进程暂时停止运行,收到SIGSTOP,SIGTSTP,SIGTTIN,SIGTTOU信号处于该状态;
771 	 *
772 	 * 5.TASK_ZOMBIE:僵尸态
773 	 * 		子进程死亡后,变成僵尸,mm,fs等资源都已释放,只剩task_struct结构体躯壳还没被父进程清理,
774 	 * 		父进程通过wait_pid获取子进程僵尸状态,wait结束,僵尸所有资源被释放;
775 	 */
776 	unsigned int			__state;
777 
778 #ifdef CONFIG_PREEMPT_RT
779 	/* saved state for "spinlock sleepers" */
780 	unsigned int			saved_state;
781 #endif
782 
783 	/*
784 	 * This begins the randomizable portion of task_struct. Only
785 	 * scheduling-critical items should be added above here.
786 	 */
787 	randomized_struct_fields_start
788 
789 	///指向进程的内核栈
790 	void				*stack;
791 	///进程描述符使用计数
792 	refcount_t			usage;
793 
794 	/*
795 	 * flags:进程当前的状态标志,比如
796 	 * #define PF_SIGNALED		0x00000400	// Killed by a signal
797 	 */
798 	/* Per task flags (PF_*), defined further below: */
799 	unsigned int			flags;
800 	/*
801 	 * ptrace系统调用设置,0表示不需要被跟踪
802 	 */
803 	unsigned int			ptrace;
804 
805 #ifdef CONFIG_SMP
806 	///进程是否正处于运行running状态
807 	int				on_cpu;
808 	struct __call_single_node	wake_entry;
809 #ifdef CONFIG_THREAD_INFO_IN_TASK
810 	/* Current CPU: */
811 	///当前进程在哪个CPU运行
812 	unsigned int			cpu;
813 #endif
814 	unsigned int			wakee_flips;
815 	unsigned long			wakee_flip_decay_ts;
816 	///上一次唤醒的是哪个进程
817 	struct task_struct		*last_wakee;
818 
819 	/*
820 	 * recent_used_cpu is initially set as the last CPU used by a task
821 	 * that wakes affine another task. Waker/wakee relationships can
822 	 * push tasks around a CPU where each wakeup moves to the next one.
823 	 * Tracking a recently used CPU allows a quick search for a recently
824 	 * used CPU that may be idle.
825 	 */
826 	int				recent_used_cpu;
827 	///进程上一次运行在哪个cpu
828 	int				wake_cpu;
829 #endif
830 	/*
831 	 * on_rq:进程状态
832 	 * TASK_ON_RQ_QUEUED:表示进程正在就绪队列中;
833 	 * TASK_ON_RQ_MIGRATING: 处于迁移过程中的进程,可能不再就绪队列中
834 	 */
835 	int				on_rq;
836 
837 	/*
838 	 * prio:调度类考虑的动态优先级,有些情况下可以暂时提高优先级,比如实时互斥锁;
839 	 * static_prio:进程静态优先级,进程启动时分配,不会随时间改变,可以用nice(),sched_setscheduler()修改;
840 	 * normal_prio:基于static_prio和调度策略计算的优先级,创建时继承父进程normal_prio,
841 	 *             对普通进程,normal_prio=static_prio,
842 	 *             对实时进程,会根据rt_priority重新计算normal_prio。
843 	 * rt_priority:实时进程优先级
844 	 * */
845 	int				prio;
846 	int				static_prio;
847 	int				normal_prio;
848 	unsigned int			rt_priority;
849 
850 	/*
851 	 * 调度类:
852 	 * linux实现调度类有:stop_sched_class,dl_sched_class,rt_sched_class,fair_sched_class,idle_sched_class;
853 	 * 不同的调度类,对应不同的调度操作方法
854 	 */
855 	const struct sched_class	*sched_class;
856 	/*
857 	 * 普通进程调度实体:
858 	 * se不仅用于单个进程调度,还用于“组调度”
859 	 */
860 	struct sched_entity		se;
861 	///rt进程调度实体
862 	struct sched_rt_entity		rt;
863 	///deadline进程调度实体
864 	struct sched_dl_entity		dl;
865 
866 #ifdef CONFIG_SCHED_CORE
867 	struct rb_node			core_node;
868 	unsigned long			core_cookie;
869 	unsigned int			core_occupation;
870 #endif
871 
872 #ifdef CONFIG_CGROUP_SCHED
873 	///cgroup cpu资源统计对象
874 	struct task_group		*sched_task_group;
875 #endif
876 
877 #ifdef CONFIG_UCLAMP_TASK
878 	/*
879 	 * Clamp values requested for a scheduling entity.
880 	 * Must be updated with task_rq_lock() held.
881 	 */
882 	struct uclamp_se		uclamp_req[UCLAMP_CNT];
883 	/*
884 	 * Effective clamp values used for a scheduling entity.
885 	 * Must be updated with task_rq_lock() held.
886 	 */
887 	struct uclamp_se		uclamp[UCLAMP_CNT];
888 #endif
889 
890 #ifdef CONFIG_PREEMPT_NOTIFIERS
891 	/* List of struct preempt_notifier: */
892 	struct hlist_head		preempt_notifiers;
893 #endif
894 
895 #ifdef CONFIG_BLK_DEV_IO_TRACE
896 	///blktrace,针对Linux中块设备I/O层的跟踪工具
897 	unsigned int			btrace_seq;
898 #endif
899 
900 	/*
901 	 * policy:进程的调度策略,目前主要有
902 	 * #define SCHED_NORMAL		0  //用于普通进程,cfs调度
903 	 * #define SCHED_FIFO		1  //实时调度类, 霸占型,高优先级执行完,才会执行低优先级
904 	 * #define SCHED_RR		    2  //实时调度类, 不同优先级同SCHED_FIFO, 同优先级,时间片轮转
905 	 * #define SCHED_BATCH		3  //非交互CPU密集型,通过cfs实现,不抢占cfs的其他进程,使用场景:不希望该进程影响系统交互性
906 	 * #define SCHED_IDLE		5  //cfs处理,相对权重最小
907 	 * #define SCHED_DEADLINE   6  //DL调度器思想:谁更紧急,谁先跑
908 	 **/
909 	unsigned int			policy;
910 	///进程允许运行的cpu个数
911 	int				nr_cpus_allowed;
912 	///进程允许运行cpu位图
913 	const cpumask_t			*cpus_ptr;
914 	cpumask_t			*user_cpus_ptr;
915 	cpumask_t			cpus_mask;
916 	void				*migration_pending;
917 #ifdef CONFIG_SMP
918 	unsigned short			migration_disabled;
919 #endif
920 	unsigned short			migration_flags;
921 
922 #ifdef CONFIG_PREEMPT_RCU
923 	int				rcu_read_lock_nesting;
924 	union rcu_special		rcu_read_unlock_special;
925 	struct list_head		rcu_node_entry;
926 	struct rcu_node			*rcu_blocked_node;
927 #endif /* #ifdef CONFIG_PREEMPT_RCU */
928 
929 #ifdef CONFIG_TASKS_RCU
930 	unsigned long			rcu_tasks_nvcsw;
931 	u8				rcu_tasks_holdout;
932 	u8				rcu_tasks_idx;
933 	int				rcu_tasks_idle_cpu;
934 	struct list_head		rcu_tasks_holdout_list;
935 #endif /* #ifdef CONFIG_TASKS_RCU */
936 
937 	///RCU同步原语
938 #ifdef CONFIG_TASKS_TRACE_RCU
939 	int				trc_reader_nesting;
940 	int				trc_ipi_to_cpu;
941 	union rcu_special		trc_reader_special;
942 	bool				trc_reader_checked;
943 	struct list_head		trc_holdout_list;
944 #endif /* #ifdef CONFIG_TASKS_TRACE_RCU */
945 
946 	/*
947 	 * 用于调度器统计进程的运行信息
948 	 * */
949 	struct sched_info		sched_info;
950 	/*
951 	 * 系统中所有进程通过tasks组成一个链表,双向环形链表;
952 	 * 链表头是init_task, 即0号进程
953 	 * next_task(): 遍历下一个进程
954 	 * next_thread(): 遍历线程组的下一个线程
955 	*/
956 	struct list_head		tasks;
957 #ifdef CONFIG_SMP
958 	struct plist_node		pushable_tasks;
959 	struct rb_node			pushable_dl_tasks;
960 #endif
961 
962 	/*
963 	 * mm:指向进程的内存描述符,内核线程为NULL
964 	 * active_mm:指向进程运行时所使用的内存描述符
965 	 *
966 	 * 普通进程:两个指针相同;
967 	 * 内核线程:mm==NULL,当线程运行时,active_mm被初始化为前一个运行进程的active_mm值?
968 	 * */
969 	struct mm_struct		*mm;
970 	struct mm_struct		*active_mm;
971 
972 	/* Per-thread vma caching: */
973 	struct vmacache			vmacache;
974 
975 #ifdef SPLIT_RSS_COUNTING
976 	struct task_rss_stat		rss_stat;
977 #endif
978 	/*
979 	 * 进程退出状态码
980 	 * exit_state:
981 	 * 判断标志:
982 	 * exit_code: 进程的终止代号,_exit()/exit_group()参数,或者内核提供的错误代号
983 	 * exit_signal:置-1表示属于某个线程组一员,当线程组最后一个成员终止时,产生一个信号,通知线程组leader进程的父进程
984 	 */
985 	int				exit_state;
986 	int				exit_code;
987 	int				exit_signal;
988 
989 	///父进程终止时,发送的信号
990 	/* The signal sent when the parent dies: */
991 	int				pdeath_signal;
992 	/* JOBCTL_*, siglock protected: */
993 	unsigned long			jobctl;
994 
995 	/* Used for emulating ABI behavior of previous Linux versions: */
996 	unsigned int			personality;
997 
998 	/* Scheduler bits, serialized by scheduler locks: */
999 	unsigned			sched_reset_on_fork:1;
1000 	unsigned			sched_contributes_to_load:1;
1001 	unsigned			sched_migrated:1;
1002 #ifdef CONFIG_PSI
1003 	unsigned			sched_psi_wake_requeue:1;
1004 #endif
1005 
1006 	/* Force alignment to the next boundary: */
1007 	unsigned			:0;
1008 
1009 	/* Unserialized, strictly 'current' */
1010 
1011 	/*
1012 	 * This field must not be in the scheduler word above due to wakelist
1013 	 * queueing no longer being serialized by p->on_cpu. However:
1014 	 *
1015 	 * p->XXX = X;			ttwu()
1016 	 * schedule()			  if (p->on_rq && ..) // false
1017 	 *   smp_mb__after_spinlock();	  if (smp_load_acquire(&p->on_cpu) && //true
1018 	 *   deactivate_task()		      ttwu_queue_wakelist())
1019 	 *     p->on_rq = 0;			p->sched_remote_wakeup = Y;
1020 	 *
1021 	 * guarantees all stores of 'current' are visible before
1022 	 * ->sched_remote_wakeup gets used, so it can be in this word.
1023 	 */
1024 	unsigned			sched_remote_wakeup:1;
1025 
1026 	/* Bit to tell LSMs we're in execve(): */
1027 	///通知LSM是否被do_execve()调用
1028 	unsigned			in_execve:1;
1029 	///判断是否进行iowait计数
1030 	unsigned			in_iowait:1;
1031 #ifndef TIF_RESTORE_SIGMASK
1032 	unsigned			restore_sigmask:1;
1033 #endif
1034 #ifdef CONFIG_MEMCG
1035 	unsigned			in_user_fault:1;
1036 #endif
1037 #ifdef CONFIG_COMPAT_BRK
1038 	unsigned			brk_randomized:1;
1039 #endif
1040 #ifdef CONFIG_CGROUPS
1041 	/* disallow userland-initiated cgroup migration */
1042 	unsigned			no_cgroup_migration:1;
1043 	/* task is frozen/stopped (used by the cgroup freezer) */
1044 	unsigned			frozen:1;
1045 #endif
1046 #ifdef CONFIG_BLK_CGROUP
1047 	unsigned			use_memdelay:1;
1048 #endif
1049 #ifdef CONFIG_PSI
1050 	/* Stalled due to lack of memory */
1051 	unsigned			in_memstall:1;
1052 #endif
1053 #ifdef CONFIG_PAGE_OWNER
1054 	/* Used by page_owner=on to detect recursion in page tracking. */
1055 	unsigned			in_page_owner:1;
1056 #endif
1057 #ifdef CONFIG_EVENTFD
1058 	/* Recursion prevention for eventfd_signal() */
1059 	unsigned			in_eventfd_signal:1;
1060 #endif
1061 
1062 	unsigned long			atomic_flags; /* Flags requiring atomic access. */
1063 
1064 	struct restart_block		restart_block;
1065 
1066 	/*
1067 	 * pid:线程id,每个线程都不同
1068 	 * tgid:线程组id, 同一个进程中所有线程相同
1069 	 *
1070 	 * 一个线程组中,所有线程的tgid相同,pid都不相同,只有线程组长(该组第一个线程)的pid==tgid
1071 	 * getpid():返回TGID
1072 	 * gettid():返回PID
1073 	 */
1074 	pid_t				pid;
1075 	pid_t				tgid;
1076 
1077 	///防止内核栈溢出
1078 #ifdef CONFIG_STACKPROTECTOR
1079 	/* Canary value for the -fstack-protector GCC feature: */
1080 	unsigned long			stack_canary;
1081 #endif
1082 	/*
1083 	 * Pointers to the (original) parent process, youngest child, younger sibling,
1084 	 * older sibling, respectively.  (p->father can be replaced with
1085 	 * p->real_parent->pid)
1086 	 */
1087 
1088 	/*
1089 	 * real_parent: 指向父进程
1090 	 * parent: 指向父进程,进程终止时,向父进程发送信号.通常parent==real_parent
1091 	 * children: 链表头,所有子进程构成的链表
1092 	 * sibling: 把当前进程插入到兄弟链表中
1093 	 * group_leader: 指向其所在进程组的leader进程
1094 	 * */
1095 
1096 	/* Real parent process: */
1097 	struct task_struct __rcu	*real_parent;
1098 
1099 	/* Recipient of SIGCHLD, wait4() reports: */
1100 	struct task_struct __rcu	*parent;
1101 
1102 	/*
1103 	 * Children/sibling form the list of natural children:
1104 	 */
1105 	struct list_head		children;
1106 	struct list_head		sibling;
1107 	struct task_struct		*group_leader;
1108 
1109 	/*
1110 	 * 'ptraced' is the list of tasks this task is using ptrace() on.
1111 	 *
1112 	 * This includes both natural children and PTRACE_ATTACH targets.
1113 	 * 'ptrace_entry' is this task's link on the p->parent->ptraced list.
1114 	 */
1115 	struct list_head		ptraced;
1116 	struct list_head		ptrace_entry;
1117 
1118 	/* PID/PID hash table linkage. */
1119 	///进程pid哈希表,可以用来判断线程是否alive,进程退出,这个指针为NULL
1120 	struct pid			*thread_pid;
1121 	struct hlist_node		pid_links[PIDTYPE_MAX];
1122 
1123 	///线程组中所有线程的链表
1124 	struct list_head		thread_group;
1125 	struct list_head		thread_node;
1126 
1127 	struct completion		*vfork_done;
1128 
1129 	/* CLONE_CHILD_SETTID: */
1130 	int __user			*set_child_tid;
1131 
1132 	/* CLONE_CHILD_CLEARTID: */
1133 	int __user			*clear_child_tid;
1134 
1135 	/* PF_IO_WORKER */
1136 	void				*pf_io_worker;
1137 
1138 	/*
1139 	 * utime: 用于记录进程在用户态经历的节拍数
1140 	 * stime: 用于记录进程在内核态经历的节拍数
1141 	 * utimescaled:记录进程在用户态运行时间,以处理器的频率为刻度;
1142 	 * stimescaled:记录进程在内核态运行时间,以处理器的频率为刻度;
1143 	 * */
1144 	u64				utime;
1145 	u64				stime;
1146 #ifdef CONFIG_ARCH_HAS_SCALED_CPUTIME
1147 	u64				utimescaled;
1148 	u64				stimescaled;
1149 #endif
1150 	///以节拍计数的虚拟机运行时间guest time
1151 	u64				gtime;
1152 	///先前运行的cpu时间
1153 	struct prev_cputime		prev_cputime;
1154 #ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
1155 	struct vtime			vtime;
1156 #endif
1157 
1158 #ifdef CONFIG_NO_HZ_FULL
1159 	atomic_t			tick_dep_mask;
1160 #endif
1161 	/* Context switch counts: */
1162 	unsigned long			nvcsw;		///进程主动(voluntary)切换次数
1163 	unsigned long			nivcsw;		///进程被动(involuntary)切换次数
1164 
1165 	/* Monotonic time in nsecs: */
1166 	u64				start_time;			///进程开始时间
1167 
1168 	/* Boot based time in nsecs: */
1169 	u64				start_boottime;		///进程开始时间,包含睡眠时间?
1170 
1171 	///缺页统计
1172 	/* MM fault and swap info: this can arguably be seen as either mm-specific or thread-specific: */
1173 	unsigned long			min_flt;
1174 	unsigned long			maj_flt;
1175 
1176 	/* Empty if CONFIG_POSIX_CPUTIMERS=n */
1177 	struct posix_cputimers		posix_cputimers;
1178 
1179 #ifdef CONFIG_POSIX_CPU_TIMERS_TASK_WORK
1180 	struct posix_cputimers_work	posix_cputimers_work;
1181 #endif
1182 
1183 	/* Process credentials: */
1184 
1185 	/* Tracer's credentials at attach: */
1186 	const struct cred __rcu		*ptracer_cred;
1187 
1188 	/* Objective and real subjective task credentials (COW): */
1189 	const struct cred __rcu		*real_cred;
1190 
1191 	/* Effective (overridable) subjective task credentials (COW): */
1192 	const struct cred __rcu		*cred;
1193 
1194 #ifdef CONFIG_KEYS
1195 	/* Cached requested key. */
1196 	struct key			*cached_requested_key;
1197 #endif
1198 
1199 	/*
1200 	 * executable name, excluding path.
1201 	 *
1202 	 * - normally initialized setup_new_exec()
1203 	 * - access it with [gs]et_task_comm()
1204 	 * - lock it with task_lock()
1205 	 */
1206 	char				comm[TASK_COMM_LEN];	///程序名字,不包括路径
1207 
1208 	struct nameidata		*nameidata;
1209 
1210 #ifdef CONFIG_SYSVIPC
1211 	///进程通信相关
1212 	struct sysv_sem			sysvsem;
1213 	struct sysv_shm			sysvshm;
1214 #endif
1215 #ifdef CONFIG_DETECT_HUNG_TASK
1216 	///最后一次切换时的总切换次数,只有两个地方更新:1.新建进程初始化, 2.hungtask线程中;
1217 	unsigned long			last_switch_count;
1218 	///最后一次切换的时间戳jiffies
1219 	unsigned long			last_switch_time;
1220 #endif
1221 	/*
1222 	 * fs:表示进程与文件系统的联系,包括当前目录和根目录
1223 	 * files:表示进程当前打开的文件
1224 	 * */
1225 	/* Filesystem information: */
1226 	struct fs_struct		*fs;
1227 
1228 	/* Open file information: */
1229 	struct files_struct		*files;
1230 
1231 #ifdef CONFIG_IO_URING
1232 	struct io_uring_task		*io_uring;
1233 #endif
1234 
1235 	/* Namespaces: */
1236 	struct nsproxy			*nsproxy;	///命名空间
1237 
1238 	/*
1239 	 * signal:指向进程的信号描述符
1240 	 * sighand:指向进程的信号响应函数的描述符
1241 	 * */
1242 	/* Signal handlers: */
1243 	struct signal_struct		*signal;
1244 	struct sighand_struct __rcu		*sighand;
1245 	sigset_t			blocked;		///被阻塞信号的掩码
1246 	sigset_t			real_blocked;	///临时掩码
1247 	/* Restored if set_restore_sigmask() was used: */
1248 	sigset_t			saved_sigmask;
1249 	struct sigpending		pending;	///存放私有挂起信号
1250 	unsigned long			sas_ss_sp;	///信号处理程序备用堆栈地址
1251 	size_t				sas_ss_size;	///堆栈大小
1252 	unsigned int			sas_ss_flags;
1253 
1254 	struct callback_head		*task_works;
1255 
1256 #ifdef CONFIG_AUDIT
1257 #ifdef CONFIG_AUDITSYSCALL
1258 	struct audit_context		*audit_context;
1259 #endif
1260 	kuid_t				loginuid;
1261 	unsigned int			sessionid;
1262 #endif
1263 	struct seccomp			seccomp;
1264 	struct syscall_user_dispatch	syscall_dispatch;
1265 
1266 	/* Thread group tracking: */
1267 	u64				parent_exec_id;
1268 	u64				self_exec_id;
1269 
1270 	/* Protection against (de-)allocation: mm, files, fs, tty, keyrings, mems_allowed, mempolicy: */
1271 	spinlock_t			alloc_lock;
1272 
1273 	/* Protection of the PI data structures: */
1274 	raw_spinlock_t			pi_lock;
1275 
1276 	struct wake_q_node		wake_q;
1277 
1278 #ifdef CONFIG_RT_MUTEXES
1279 	/* PI waiters blocked on a rt_mutex held by this task: */
1280 	struct rb_root_cached		pi_waiters;
1281 	/* Updated under owner's pi_lock and rq lock */
1282 	struct task_struct		*pi_top_task;
1283 	/* Deadlock detection and priority inheritance handling: */
1284 	struct rt_mutex_waiter		*pi_blocked_on;
1285 #endif
1286 
1287 #ifdef CONFIG_DEBUG_MUTEXES
1288 	/* Mutex deadlock detection: */
1289 	struct mutex_waiter		*blocked_on;
1290 #endif
1291 
1292 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
1293 	int				non_block_count;
1294 #endif
1295 
1296 #ifdef CONFIG_TRACE_IRQFLAGS
1297 	struct irqtrace_events		irqtrace;
1298 	unsigned int			hardirq_threaded;
1299 	u64				hardirq_chain_key;
1300 	int				softirqs_enabled;
1301 	int				softirq_context;
1302 	int				irq_config;
1303 #endif
1304 #ifdef CONFIG_PREEMPT_RT
1305 	int				softirq_disable_cnt;
1306 #endif
1307 
1308 #ifdef CONFIG_LOCKDEP
1309 # define MAX_LOCK_DEPTH			48UL
1310 	u64				curr_chain_key;
1311 	int				lockdep_depth;
1312 	unsigned int			lockdep_recursion;
1313 	struct held_lock		held_locks[MAX_LOCK_DEPTH];
1314 #endif
1315 
1316 #if defined(CONFIG_UBSAN) && !defined(CONFIG_UBSAN_TRAP)
1317 	unsigned int			in_ubsan;
1318 #endif
1319 
1320 	/* Journalling filesystem info: */
1321 	void				*journal_info;
1322 
1323 	/* Stacked block device info: */
1324 	struct bio_list			*bio_list;
1325 
1326 #ifdef CONFIG_BLOCK
1327 	/* Stack plugging: */
1328 	struct blk_plug			*plug;
1329 #endif
1330 
1331 	/* VM state: */
1332 	struct reclaim_state		*reclaim_state;
1333 
1334 	struct backing_dev_info		*backing_dev_info;
1335 
1336 	struct io_context		*io_context;
1337 
1338 #ifdef CONFIG_COMPACTION
1339 	struct capture_control		*capture_control;
1340 #endif
1341 	/* Ptrace state: */
1342 	unsigned long			ptrace_message;
1343 	kernel_siginfo_t		*last_siginfo;
1344 
1345 	struct task_io_accounting	ioac;
1346 #ifdef CONFIG_PSI
1347 	///PSI所处状态
1348 	/* Pressure stall state */
1349 	unsigned int			psi_flags;
1350 #endif
1351 #ifdef CONFIG_TASK_XACCT
1352 	/* Accumulated RSS usage: */
1353 	u64				acct_rss_mem1;
1354 	/* Accumulated virtual memory usage: */
1355 	u64				acct_vm_mem1;
1356 	/* stime + utime since last update: */
1357 	u64				acct_timexpd;
1358 #endif
1359 #ifdef CONFIG_CPUSETS
1360 	/* Protected by ->alloc_lock: */
1361 	nodemask_t			mems_allowed;
1362 	/* Sequence number to catch updates: */
1363 	seqcount_spinlock_t		mems_allowed_seq;
1364 	int				cpuset_mem_spread_rotor;
1365 	int				cpuset_slab_spread_rotor;
1366 #endif
1367 #ifdef CONFIG_CGROUPS
1368 	/* Control Group info protected by css_set_lock: */
1369 	struct css_set __rcu		*cgroups; ///与进程相关的cgroup信息
1370 	/* cg_list protected by css_set_lock and tsk->alloc_lock: */
1371 	struct list_head		cg_list; ///同一个css_set里所有进程,连成一个链表
1372 #endif
1373 #ifdef CONFIG_X86_CPU_RESCTRL
1374 	u32				closid;
1375 	u32				rmid;
1376 #endif
1377 #ifdef CONFIG_FUTEX
1378 	struct robust_list_head __user	*robust_list;
1379 #ifdef CONFIG_COMPAT
1380 	struct compat_robust_list_head __user *compat_robust_list;
1381 #endif
1382 	struct list_head		pi_state_list;
1383 	struct futex_pi_state		*pi_state_cache;
1384 	struct mutex			futex_exit_mutex;
1385 	unsigned int			futex_state;
1386 #endif
1387 #ifdef CONFIG_PERF_EVENTS
1388 	struct perf_event_context	*perf_event_ctxp[perf_nr_task_contexts];
1389 	struct mutex			perf_event_mutex;
1390 	struct list_head		perf_event_list;
1391 #endif
1392 #ifdef CONFIG_DEBUG_PREEMPT
1393 	unsigned long			preempt_disable_ip;
1394 #endif
1395 #ifdef CONFIG_NUMA
1396 	/* Protected by alloc_lock: */
1397 	struct mempolicy		*mempolicy;
1398 	short				il_prev;
1399 	short				pref_node_fork;
1400 #endif
1401 #ifdef CONFIG_NUMA_BALANCING
1402 	int				numa_scan_seq;
1403 	unsigned int			numa_scan_period;
1404 	unsigned int			numa_scan_period_max;
1405 	int				numa_preferred_nid;
1406 	unsigned long			numa_migrate_retry;
1407 	/* Migration stamp: */
1408 	u64				node_stamp;
1409 	u64				last_task_numa_placement;
1410 	u64				last_sum_exec_runtime;
1411 	struct callback_head		numa_work;
1412 
1413 	/*
1414 	 * This pointer is only modified for current in syscall and
1415 	 * pagefault context (and for tasks being destroyed), so it can be read
1416 	 * from any of the following contexts:
1417 	 *  - RCU read-side critical section
1418 	 *  - current->numa_group from everywhere
1419 	 *  - task's runqueue locked, task not running
1420 	 */
1421 	struct numa_group __rcu		*numa_group;
1422 
1423 	/*
1424 	 * numa_faults is an array split into four regions:
1425 	 * faults_memory, faults_cpu, faults_memory_buffer, faults_cpu_buffer
1426 	 * in this precise order.
1427 	 *
1428 	 * faults_memory: Exponential decaying average of faults on a per-node
1429 	 * basis. Scheduling placement decisions are made based on these
1430 	 * counts. The values remain static for the duration of a PTE scan.
1431 	 * faults_cpu: Track the nodes the process was running on when a NUMA
1432 	 * hinting fault was incurred.
1433 	 * faults_memory_buffer and faults_cpu_buffer: Record faults per node
1434 	 * during the current scan window. When the scan completes, the counts
1435 	 * in faults_memory and faults_cpu decay and these values are copied.
1436 	 */
1437 	unsigned long			*numa_faults;
1438 	unsigned long			total_numa_faults;
1439 
1440 	/*
1441 	 * numa_faults_locality tracks if faults recorded during the last
1442 	 * scan window were remote/local or failed to migrate. The task scan
1443 	 * period is adapted based on the locality of the faults with different
1444 	 * weights depending on whether they were shared or private faults
1445 	 */
1446 	unsigned long			numa_faults_locality[3];
1447 
1448 	unsigned long			numa_pages_migrated;
1449 #endif /* CONFIG_NUMA_BALANCING */
1450 
1451 #ifdef CONFIG_RSEQ
1452 	struct rseq __user *rseq;
1453 	u32 rseq_sig;
1454 	/*
1455 	 * RmW on rseq_event_mask must be performed atomically
1456 	 * with respect to preemption.
1457 	 */
1458 	unsigned long rseq_event_mask;
1459 #endif
1460 
1461 	struct tlbflush_unmap_batch	tlb_ubc;
1462 
1463 	union {
1464 		refcount_t		rcu_users;
1465 		struct rcu_head		rcu;
1466 	};
1467 
1468 	/* Cache last used pipe for splice(): */
1469 	struct pipe_inode_info		*splice_pipe;
1470 
1471 	struct page_frag		task_frag;
1472 
1473 #ifdef CONFIG_TASK_DELAY_ACCT
1474 	struct task_delay_info		*delays;
1475 #endif
1476 
1477 #ifdef CONFIG_FAULT_INJECTION
1478 	int				make_it_fail;
1479 	unsigned int			fail_nth;
1480 #endif
1481 	/*
1482 	 * When (nr_dirtied >= nr_dirtied_pause), it's time to call
1483 	 * balance_dirty_pages() for a dirty throttling pause:
1484 	 */
1485 	int				nr_dirtied;
1486 	int				nr_dirtied_pause;
1487 	/* Start of a write-and-pause period: */
1488 	unsigned long			dirty_paused_when;
1489 
1490 #ifdef CONFIG_LATENCYTOP
1491 	int				latency_record_count;
1492 	struct latency_record		latency_record[LT_SAVECOUNT];
1493 #endif
1494 	/*
1495 	 * Time slack values; these are used to round up poll() and
1496 	 * select() etc timeout values. These are in nanoseconds.
1497 	 */
1498 	u64				timer_slack_ns;
1499 	u64				default_timer_slack_ns;
1500 
1501 #if defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS)
1502 	unsigned int			kasan_depth;
1503 #endif
1504 
1505 #ifdef CONFIG_KCSAN
1506 	struct kcsan_ctx		kcsan_ctx;
1507 #ifdef CONFIG_TRACE_IRQFLAGS
1508 	struct irqtrace_events		kcsan_save_irqtrace;
1509 #endif
1510 #endif
1511 
1512 #if IS_ENABLED(CONFIG_KUNIT)
1513 	struct kunit			*kunit_test;
1514 #endif
1515 
1516 #ifdef CONFIG_FUNCTION_GRAPH_TRACER
1517 	/* Index of current stored address in ret_stack: */
1518 	int				curr_ret_stack;
1519 	int				curr_ret_depth;
1520 
1521 	/* Stack of return addresses for return function tracing: */
1522 	struct ftrace_ret_stack		*ret_stack;
1523 
1524 	/* Timestamp for last schedule: */
1525 	unsigned long long		ftrace_timestamp;
1526 
1527 	/*
1528 	 * Number of functions that haven't been traced
1529 	 * because of depth overrun:
1530 	 */
1531 	atomic_t			trace_overrun;
1532 
1533 	/* Pause tracing: */
1534 	atomic_t			tracing_graph_pause;
1535 #endif
1536 
1537 #ifdef CONFIG_TRACING
1538 	/* State flags for use by tracers: */
1539 	unsigned long			trace;
1540 
1541 	/* Bitmask and counter of trace recursion: */
1542 	unsigned long			trace_recursion;
1543 #endif /* CONFIG_TRACING */
1544 
1545 #ifdef CONFIG_KCOV
1546 	/* See kernel/kcov.c for more details. */
1547 
1548 	/* Coverage collection mode enabled for this task (0 if disabled): */
1549 	unsigned int			kcov_mode;
1550 
1551 	/* Size of the kcov_area: */
1552 	unsigned int			kcov_size;
1553 
1554 	/* Buffer for coverage collection: */
1555 	void				*kcov_area;
1556 
1557 	/* KCOV descriptor wired with this task or NULL: */
1558 	struct kcov			*kcov;
1559 
1560 	/* KCOV common handle for remote coverage collection: */
1561 	u64				kcov_handle;
1562 
1563 	/* KCOV sequence number: */
1564 	int				kcov_sequence;
1565 
1566 	/* Collect coverage from softirq context: */
1567 	unsigned int			kcov_softirq;
1568 #endif
1569 
1570 #ifdef CONFIG_MEMCG
1571 	struct mem_cgroup		*memcg_in_oom;
1572 	gfp_t				memcg_oom_gfp_mask;
1573 	int				memcg_oom_order;
1574 
1575 	/* Number of pages to reclaim on returning to userland: */
1576 	unsigned int			memcg_nr_pages_over_high;
1577 
1578 	/* Used by memcontrol for targeted memcg charge: */
1579 	///内存资源统计对象
1580 	struct mem_cgroup		*active_memcg;
1581 #endif
1582 
1583 #ifdef CONFIG_BLK_CGROUP
1584 	struct request_queue		*throttle_queue;
1585 #endif
1586 
1587 #ifdef CONFIG_UPROBES
1588 	struct uprobe_task		*utask;
1589 #endif
1590 #if defined(CONFIG_BCACHE) || defined(CONFIG_BCACHE_MODULE)
1591 	unsigned int			sequential_io;
1592 	unsigned int			sequential_io_avg;
1593 #endif
1594 	struct kmap_ctrl		kmap_ctrl;
1595 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
1596 	unsigned long			task_state_change;
1597 # ifdef CONFIG_PREEMPT_RT
1598 	unsigned long			saved_state_change;
1599 # endif
1600 #endif
1601 	int				pagefault_disabled;
1602 #ifdef CONFIG_MMU
1603 	struct task_struct		*oom_reaper_list;
1604 #endif
1605 #ifdef CONFIG_VMAP_STACK
1606 	struct vm_struct		*stack_vm_area;
1607 #endif
1608 #ifdef CONFIG_THREAD_INFO_IN_TASK
1609 	/* A live task holds one reference: */
1610 	refcount_t			stack_refcount;
1611 #endif
1612 #ifdef CONFIG_LIVEPATCH
1613 	int patch_state;
1614 #endif
1615 #ifdef CONFIG_SECURITY
1616 	/* Used by LSM modules for access restriction: */
1617 	void				*security;
1618 #endif
1619 #ifdef CONFIG_BPF_SYSCALL
1620 	/* Used by BPF task local storage */
1621 	struct bpf_local_storage __rcu	*bpf_storage;
1622 	/* Used for BPF run context */
1623 	struct bpf_run_ctx		*bpf_ctx;
1624 #endif
1625 
1626 #ifdef CONFIG_GCC_PLUGIN_STACKLEAK
1627 	unsigned long			lowest_stack;
1628 	unsigned long			prev_lowest_stack;
1629 #endif
1630 
1631 #ifdef CONFIG_X86_MCE
1632 	void __user			*mce_vaddr;
1633 	__u64				mce_kflags;
1634 	u64				mce_addr;
1635 	__u64				mce_ripv : 1,
1636 					mce_whole_page : 1,
1637 					__mce_reserved : 62;
1638 	struct callback_head		mce_kill_me;
1639 	int				mce_count;
1640 #endif
1641 
1642 #ifdef CONFIG_KRETPROBES
1643 	struct llist_head               kretprobe_instances;
1644 #endif
1645 
1646 #ifdef CONFIG_ARCH_HAS_PARANOID_L1D_FLUSH
1647 	/*
1648 	 * If L1D flush is supported on mm context switch
1649 	 * then we use this callback head to queue kill work
1650 	 * to kill tasks that are not running on SMT disabled
1651 	 * cores
1652 	 */
1653 	struct callback_head		l1d_flush_kill;
1654 #endif
1655 
1656 	/*
1657 	 * New fields for task_struct should be added above here, so that
1658 	 * they are included in the randomized portion of task_struct.
1659 	 */
1660 	randomized_struct_fields_end
1661 
1662 	/* CPU-specific state of this task: */
1663 	///switch_to时,保存进程的硬件上下文
1664 	struct thread_struct		thread;
1665 
1666 	/*
1667 	 * WARNING: on x86, 'thread_struct' contains a variable-sized
1668 	 * structure.  It *MUST* be at the end of 'task_struct'.
1669 	 *
1670 	 * Do not put anything below here!
1671 	 */
1672 };
1673 
task_pid(struct task_struct * task)1674 static inline struct pid *task_pid(struct task_struct *task)
1675 {
1676 	return task->thread_pid;
1677 }
1678 
1679 /*
1680  * the helpers to get the task's different pids as they are seen
1681  * from various namespaces
1682  *
1683  * task_xid_nr()     : global id, i.e. the id seen from the init namespace;
1684  * task_xid_vnr()    : virtual id, i.e. the id seen from the pid namespace of
1685  *                     current.
1686  * task_xid_nr_ns()  : id seen from the ns specified;
1687  *
1688  * see also pid_nr() etc in include/linux/pid.h
1689  */
1690 pid_t __task_pid_nr_ns(struct task_struct *task, enum pid_type type, struct pid_namespace *ns);
1691 
task_pid_nr(struct task_struct * tsk)1692 static inline pid_t task_pid_nr(struct task_struct *tsk)
1693 {
1694 	return tsk->pid;
1695 }
1696 
task_pid_nr_ns(struct task_struct * tsk,struct pid_namespace * ns)1697 static inline pid_t task_pid_nr_ns(struct task_struct *tsk, struct pid_namespace *ns)
1698 {
1699 	return __task_pid_nr_ns(tsk, PIDTYPE_PID, ns);
1700 }
1701 
task_pid_vnr(struct task_struct * tsk)1702 static inline pid_t task_pid_vnr(struct task_struct *tsk)
1703 {
1704 	return __task_pid_nr_ns(tsk, PIDTYPE_PID, NULL);
1705 }
1706 
1707 
task_tgid_nr(struct task_struct * tsk)1708 static inline pid_t task_tgid_nr(struct task_struct *tsk)
1709 {
1710 	return tsk->tgid;
1711 }
1712 
1713 /**
1714  * pid_alive - check that a task structure is not stale
1715  * @p: Task structure to be checked.
1716  *
1717  * Test if a process is not yet dead (at most zombie state)
1718  * If pid_alive fails, then pointers within the task structure
1719  * can be stale and must not be dereferenced.
1720  *
1721  * Return: 1 if the process is alive. 0 otherwise.
1722  */
pid_alive(const struct task_struct * p)1723 static inline int pid_alive(const struct task_struct *p)
1724 {
1725 	return p->thread_pid != NULL;
1726 }
1727 
task_pgrp_nr_ns(struct task_struct * tsk,struct pid_namespace * ns)1728 static inline pid_t task_pgrp_nr_ns(struct task_struct *tsk, struct pid_namespace *ns)
1729 {
1730 	return __task_pid_nr_ns(tsk, PIDTYPE_PGID, ns);
1731 }
1732 
task_pgrp_vnr(struct task_struct * tsk)1733 static inline pid_t task_pgrp_vnr(struct task_struct *tsk)
1734 {
1735 	return __task_pid_nr_ns(tsk, PIDTYPE_PGID, NULL);
1736 }
1737 
1738 
task_session_nr_ns(struct task_struct * tsk,struct pid_namespace * ns)1739 static inline pid_t task_session_nr_ns(struct task_struct *tsk, struct pid_namespace *ns)
1740 {
1741 	return __task_pid_nr_ns(tsk, PIDTYPE_SID, ns);
1742 }
1743 
task_session_vnr(struct task_struct * tsk)1744 static inline pid_t task_session_vnr(struct task_struct *tsk)
1745 {
1746 	return __task_pid_nr_ns(tsk, PIDTYPE_SID, NULL);
1747 }
1748 
task_tgid_nr_ns(struct task_struct * tsk,struct pid_namespace * ns)1749 static inline pid_t task_tgid_nr_ns(struct task_struct *tsk, struct pid_namespace *ns)
1750 {
1751 	return __task_pid_nr_ns(tsk, PIDTYPE_TGID, ns);
1752 }
1753 
task_tgid_vnr(struct task_struct * tsk)1754 static inline pid_t task_tgid_vnr(struct task_struct *tsk)
1755 {
1756 	return __task_pid_nr_ns(tsk, PIDTYPE_TGID, NULL);
1757 }
1758 
task_ppid_nr_ns(const struct task_struct * tsk,struct pid_namespace * ns)1759 static inline pid_t task_ppid_nr_ns(const struct task_struct *tsk, struct pid_namespace *ns)
1760 {
1761 	pid_t pid = 0;
1762 
1763 	rcu_read_lock();
1764 	if (pid_alive(tsk))
1765 		pid = task_tgid_nr_ns(rcu_dereference(tsk->real_parent), ns);
1766 	rcu_read_unlock();
1767 
1768 	return pid;
1769 }
1770 
task_ppid_nr(const struct task_struct * tsk)1771 static inline pid_t task_ppid_nr(const struct task_struct *tsk)
1772 {
1773 	return task_ppid_nr_ns(tsk, &init_pid_ns);
1774 }
1775 
1776 /* Obsolete, do not use: */
task_pgrp_nr(struct task_struct * tsk)1777 static inline pid_t task_pgrp_nr(struct task_struct *tsk)
1778 {
1779 	return task_pgrp_nr_ns(tsk, &init_pid_ns);
1780 }
1781 
1782 #define TASK_REPORT_IDLE	(TASK_REPORT + 1)
1783 #define TASK_REPORT_MAX		(TASK_REPORT_IDLE << 1)
1784 
task_state_index(struct task_struct * tsk)1785 static inline unsigned int task_state_index(struct task_struct *tsk)
1786 {
1787 	unsigned int tsk_state = READ_ONCE(tsk->__state);
1788 	unsigned int state = (tsk_state | tsk->exit_state) & TASK_REPORT;
1789 
1790 	BUILD_BUG_ON_NOT_POWER_OF_2(TASK_REPORT_MAX);
1791 
1792 	if (tsk_state == TASK_IDLE)
1793 		state = TASK_REPORT_IDLE;
1794 
1795 	return fls(state);
1796 }
1797 
task_index_to_char(unsigned int state)1798 static inline char task_index_to_char(unsigned int state)
1799 {
1800 	static const char state_char[] = "RSDTtXZPI";
1801 
1802 	BUILD_BUG_ON(1 + ilog2(TASK_REPORT_MAX) != sizeof(state_char) - 1);
1803 
1804 	return state_char[state];
1805 }
1806 
task_state_to_char(struct task_struct * tsk)1807 static inline char task_state_to_char(struct task_struct *tsk)
1808 {
1809 	return task_index_to_char(task_state_index(tsk));
1810 }
1811 
1812 /**
1813  * is_global_init - check if a task structure is init. Since init
1814  * is free to have sub-threads we need to check tgid.
1815  * @tsk: Task structure to be checked.
1816  *
1817  * Check if a task structure is the first user space task the kernel created.
1818  *
1819  * Return: 1 if the task structure is init. 0 otherwise.
1820  */
is_global_init(struct task_struct * tsk)1821 static inline int is_global_init(struct task_struct *tsk)
1822 {
1823 	return task_tgid_nr(tsk) == 1;
1824 }
1825 
1826 extern struct pid *cad_pid;
1827 
1828 /*
1829  * Per process flags
1830  */
1831 #define PF_VCPU			0x00000001	/* I'm a virtual CPU */
1832 #define PF_IDLE			0x00000002	/* I am an IDLE thread */
1833 #define PF_EXITING		0x00000004	/* Getting shut down */
1834 #define PF_IO_WORKER		0x00000010	/* Task is an IO worker */
1835 #define PF_WQ_WORKER		0x00000020	/* I'm a workqueue worker */
1836 #define PF_FORKNOEXEC		0x00000040	/* Forked but didn't exec */
1837 #define PF_MCE_PROCESS		0x00000080      /* Process policy on mce errors */
1838 #define PF_SUPERPRIV		0x00000100	/* Used super-user privileges */
1839 #define PF_DUMPCORE		0x00000200	/* Dumped core */
1840 #define PF_SIGNALED		0x00000400	/* Killed by a signal */
1841 #define PF_MEMALLOC		0x00000800	/* Allocating memory */
1842 #define PF_NPROC_EXCEEDED	0x00001000	/* set_user() noticed that RLIMIT_NPROC was exceeded */
1843 #define PF_USED_MATH		0x00002000	/* If unset the fpu must be initialized before use */
1844 #define PF_USED_ASYNC		0x00004000	/* Used async_schedule*(), used by module init */
1845 #define PF_NOFREEZE		0x00008000	/* This thread should not be frozen */
1846 #define PF_FROZEN		0x00010000	/* Frozen for system suspend */
1847 #define PF_KSWAPD		0x00020000	/* I am kswapd */
1848 #define PF_MEMALLOC_NOFS	0x00040000	/* All allocation requests will inherit GFP_NOFS */
1849 #define PF_MEMALLOC_NOIO	0x00080000	/* All allocation requests will inherit GFP_NOIO */
1850 #define PF_LOCAL_THROTTLE	0x00100000	/* Throttle writes only against the bdi I write to,
1851 						 * I am cleaning dirty pages from some other bdi. */
1852 #define PF_KTHREAD		0x00200000	/* I am a kernel thread */
1853 #define PF_RANDOMIZE		0x00400000	/* Randomize virtual address space */
1854 #define PF_SWAPWRITE		0x00800000	/* Allowed to write to swap */
1855 #define PF_NO_SETAFFINITY	0x04000000	/* Userland is not allowed to meddle with cpus_mask */
1856 #define PF_MCE_EARLY		0x08000000      /* Early kill for mce process policy */
1857 #define PF_MEMALLOC_PIN		0x10000000	/* Allocation context constrained to zones which allow long term pinning. */
1858 #define PF_FREEZER_SKIP		0x40000000	/* Freezer should not count it as freezable */
1859 #define PF_SUSPEND_TASK		0x80000000      /* This thread called freeze_processes() and should not be frozen */
1860 
1861 /*
1862  * Only the _current_ task can read/write to tsk->flags, but other
1863  * tasks can access tsk->flags in readonly mode for example
1864  * with tsk_used_math (like during threaded core dumping).
1865  * There is however an exception to this rule during ptrace
1866  * or during fork: the ptracer task is allowed to write to the
1867  * child->flags of its traced child (same goes for fork, the parent
1868  * can write to the child->flags), because we're guaranteed the
1869  * child is not running and in turn not changing child->flags
1870  * at the same time the parent does it.
1871  */
1872 #define clear_stopped_child_used_math(child)	do { (child)->flags &= ~PF_USED_MATH; } while (0)
1873 #define set_stopped_child_used_math(child)	do { (child)->flags |= PF_USED_MATH; } while (0)
1874 #define clear_used_math()			clear_stopped_child_used_math(current)
1875 #define set_used_math()				set_stopped_child_used_math(current)
1876 
1877 #define conditional_stopped_child_used_math(condition, child) \
1878 	do { (child)->flags &= ~PF_USED_MATH, (child)->flags |= (condition) ? PF_USED_MATH : 0; } while (0)
1879 
1880 #define conditional_used_math(condition)	conditional_stopped_child_used_math(condition, current)
1881 
1882 #define copy_to_stopped_child_used_math(child) \
1883 	do { (child)->flags &= ~PF_USED_MATH, (child)->flags |= current->flags & PF_USED_MATH; } while (0)
1884 
1885 /* NOTE: this will return 0 or PF_USED_MATH, it will never return 1 */
1886 #define tsk_used_math(p)			((p)->flags & PF_USED_MATH)
1887 #define used_math()				tsk_used_math(current)
1888 
is_percpu_thread(void)1889 static __always_inline bool is_percpu_thread(void)
1890 {
1891 #ifdef CONFIG_SMP
1892 	return (current->flags & PF_NO_SETAFFINITY) &&
1893 		(current->nr_cpus_allowed  == 1);
1894 #else
1895 	return true;
1896 #endif
1897 }
1898 
1899 /* Per-process atomic flags. */
1900 #define PFA_NO_NEW_PRIVS		0	/* May not gain new privileges. */
1901 #define PFA_SPREAD_PAGE			1	/* Spread page cache over cpuset */
1902 #define PFA_SPREAD_SLAB			2	/* Spread some slab caches over cpuset */
1903 #define PFA_SPEC_SSB_DISABLE		3	/* Speculative Store Bypass disabled */
1904 #define PFA_SPEC_SSB_FORCE_DISABLE	4	/* Speculative Store Bypass force disabled*/
1905 #define PFA_SPEC_IB_DISABLE		5	/* Indirect branch speculation restricted */
1906 #define PFA_SPEC_IB_FORCE_DISABLE	6	/* Indirect branch speculation permanently restricted */
1907 #define PFA_SPEC_SSB_NOEXEC		7	/* Speculative Store Bypass clear on execve() */
1908 
1909 #define TASK_PFA_TEST(name, func)					\
1910 	static inline bool task_##func(struct task_struct *p)		\
1911 	{ return test_bit(PFA_##name, &p->atomic_flags); }
1912 
1913 #define TASK_PFA_SET(name, func)					\
1914 	static inline void task_set_##func(struct task_struct *p)	\
1915 	{ set_bit(PFA_##name, &p->atomic_flags); }
1916 
1917 #define TASK_PFA_CLEAR(name, func)					\
1918 	static inline void task_clear_##func(struct task_struct *p)	\
1919 	{ clear_bit(PFA_##name, &p->atomic_flags); }
1920 
TASK_PFA_TEST(NO_NEW_PRIVS,no_new_privs)1921 TASK_PFA_TEST(NO_NEW_PRIVS, no_new_privs)
1922 TASK_PFA_SET(NO_NEW_PRIVS, no_new_privs)
1923 
1924 TASK_PFA_TEST(SPREAD_PAGE, spread_page)
1925 TASK_PFA_SET(SPREAD_PAGE, spread_page)
1926 TASK_PFA_CLEAR(SPREAD_PAGE, spread_page)
1927 
1928 TASK_PFA_TEST(SPREAD_SLAB, spread_slab)
1929 TASK_PFA_SET(SPREAD_SLAB, spread_slab)
1930 TASK_PFA_CLEAR(SPREAD_SLAB, spread_slab)
1931 
1932 TASK_PFA_TEST(SPEC_SSB_DISABLE, spec_ssb_disable)
1933 TASK_PFA_SET(SPEC_SSB_DISABLE, spec_ssb_disable)
1934 TASK_PFA_CLEAR(SPEC_SSB_DISABLE, spec_ssb_disable)
1935 
1936 TASK_PFA_TEST(SPEC_SSB_NOEXEC, spec_ssb_noexec)
1937 TASK_PFA_SET(SPEC_SSB_NOEXEC, spec_ssb_noexec)
1938 TASK_PFA_CLEAR(SPEC_SSB_NOEXEC, spec_ssb_noexec)
1939 
1940 TASK_PFA_TEST(SPEC_SSB_FORCE_DISABLE, spec_ssb_force_disable)
1941 TASK_PFA_SET(SPEC_SSB_FORCE_DISABLE, spec_ssb_force_disable)
1942 
1943 TASK_PFA_TEST(SPEC_IB_DISABLE, spec_ib_disable)
1944 TASK_PFA_SET(SPEC_IB_DISABLE, spec_ib_disable)
1945 TASK_PFA_CLEAR(SPEC_IB_DISABLE, spec_ib_disable)
1946 
1947 TASK_PFA_TEST(SPEC_IB_FORCE_DISABLE, spec_ib_force_disable)
1948 TASK_PFA_SET(SPEC_IB_FORCE_DISABLE, spec_ib_force_disable)
1949 
1950 static inline void
1951 current_restore_flags(unsigned long orig_flags, unsigned long flags)
1952 {
1953 	current->flags &= ~flags;
1954 	current->flags |= orig_flags & flags;
1955 }
1956 
1957 extern int cpuset_cpumask_can_shrink(const struct cpumask *cur, const struct cpumask *trial);
1958 extern int task_can_attach(struct task_struct *p, const struct cpumask *cs_cpus_allowed);
1959 #ifdef CONFIG_SMP
1960 extern void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask);
1961 extern int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask);
1962 extern int dup_user_cpus_ptr(struct task_struct *dst, struct task_struct *src, int node);
1963 extern void release_user_cpus_ptr(struct task_struct *p);
1964 extern int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask);
1965 extern void force_compatible_cpus_allowed_ptr(struct task_struct *p);
1966 extern void relax_compatible_cpus_allowed_ptr(struct task_struct *p);
1967 #else
do_set_cpus_allowed(struct task_struct * p,const struct cpumask * new_mask)1968 static inline void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1969 {
1970 }
set_cpus_allowed_ptr(struct task_struct * p,const struct cpumask * new_mask)1971 static inline int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1972 {
1973 	if (!cpumask_test_cpu(0, new_mask))
1974 		return -EINVAL;
1975 	return 0;
1976 }
dup_user_cpus_ptr(struct task_struct * dst,struct task_struct * src,int node)1977 static inline int dup_user_cpus_ptr(struct task_struct *dst, struct task_struct *src, int node)
1978 {
1979 	if (src->user_cpus_ptr)
1980 		return -EINVAL;
1981 	return 0;
1982 }
release_user_cpus_ptr(struct task_struct * p)1983 static inline void release_user_cpus_ptr(struct task_struct *p)
1984 {
1985 	WARN_ON(p->user_cpus_ptr);
1986 }
1987 
dl_task_check_affinity(struct task_struct * p,const struct cpumask * mask)1988 static inline int dl_task_check_affinity(struct task_struct *p, const struct cpumask *mask)
1989 {
1990 	return 0;
1991 }
1992 #endif
1993 
1994 extern int yield_to(struct task_struct *p, bool preempt);
1995 extern void set_user_nice(struct task_struct *p, long nice);
1996 extern int task_prio(const struct task_struct *p);
1997 
1998 /**
1999  * task_nice - return the nice value of a given task.
2000  * @p: the task in question.
2001  *
2002  * Return: The nice value [ -20 ... 0 ... 19 ].
2003  */
task_nice(const struct task_struct * p)2004 static inline int task_nice(const struct task_struct *p)
2005 {
2006 	return PRIO_TO_NICE((p)->static_prio);
2007 }
2008 
2009 extern int can_nice(const struct task_struct *p, const int nice);
2010 extern int task_curr(const struct task_struct *p);
2011 extern int idle_cpu(int cpu);
2012 extern int available_idle_cpu(int cpu);
2013 extern int sched_setscheduler(struct task_struct *, int, const struct sched_param *);
2014 extern int sched_setscheduler_nocheck(struct task_struct *, int, const struct sched_param *);
2015 extern void sched_set_fifo(struct task_struct *p);
2016 extern void sched_set_fifo_low(struct task_struct *p);
2017 extern void sched_set_normal(struct task_struct *p, int nice);
2018 extern int sched_setattr(struct task_struct *, const struct sched_attr *);
2019 extern int sched_setattr_nocheck(struct task_struct *, const struct sched_attr *);
2020 extern struct task_struct *idle_task(int cpu);
2021 
2022 /**
2023  * is_idle_task - is the specified task an idle task?
2024  * @p: the task in question.
2025  *
2026  * Return: 1 if @p is an idle task. 0 otherwise.
2027  */
is_idle_task(const struct task_struct * p)2028 static __always_inline bool is_idle_task(const struct task_struct *p)
2029 {
2030 	return !!(p->flags & PF_IDLE);
2031 }
2032 
2033 extern struct task_struct *curr_task(int cpu);
2034 extern void ia64_set_curr_task(int cpu, struct task_struct *p);
2035 
2036 void yield(void);
2037 
2038 union thread_union {
2039 #ifndef CONFIG_ARCH_TASK_STRUCT_ON_STACK
2040 	struct task_struct task;
2041 #endif
2042 #ifndef CONFIG_THREAD_INFO_IN_TASK
2043 	struct thread_info thread_info;
2044 #endif
2045 	unsigned long stack[THREAD_SIZE/sizeof(long)];
2046 };
2047 
2048 #ifndef CONFIG_THREAD_INFO_IN_TASK
2049 extern struct thread_info init_thread_info;
2050 #endif
2051 
2052 extern unsigned long init_stack[THREAD_SIZE / sizeof(unsigned long)];
2053 
2054 #ifdef CONFIG_THREAD_INFO_IN_TASK
task_thread_info(struct task_struct * task)2055 static inline struct thread_info *task_thread_info(struct task_struct *task)
2056 {
2057 	return &task->thread_info;
2058 }
2059 #elif !defined(__HAVE_THREAD_FUNCTIONS)
2060 # define task_thread_info(task)	((struct thread_info *)(task)->stack)
2061 #endif
2062 
2063 /*
2064  * find a task by one of its numerical ids
2065  *
2066  * find_task_by_pid_ns():
2067  *      finds a task by its pid in the specified namespace
2068  * find_task_by_vpid():
2069  *      finds a task by its virtual pid
2070  *
2071  * see also find_vpid() etc in include/linux/pid.h
2072  */
2073 
2074 extern struct task_struct *find_task_by_vpid(pid_t nr);
2075 extern struct task_struct *find_task_by_pid_ns(pid_t nr, struct pid_namespace *ns);
2076 
2077 /*
2078  * find a task by its virtual pid and get the task struct
2079  */
2080 extern struct task_struct *find_get_task_by_vpid(pid_t nr);
2081 
2082 extern int wake_up_state(struct task_struct *tsk, unsigned int state);
2083 extern int wake_up_process(struct task_struct *tsk);
2084 extern void wake_up_new_task(struct task_struct *tsk);
2085 
2086 #ifdef CONFIG_SMP
2087 extern void kick_process(struct task_struct *tsk);
2088 #else
kick_process(struct task_struct * tsk)2089 static inline void kick_process(struct task_struct *tsk) { }
2090 #endif
2091 
2092 extern void __set_task_comm(struct task_struct *tsk, const char *from, bool exec);
2093 
set_task_comm(struct task_struct * tsk,const char * from)2094 static inline void set_task_comm(struct task_struct *tsk, const char *from)
2095 {
2096 	__set_task_comm(tsk, from, false);
2097 }
2098 
2099 extern char *__get_task_comm(char *to, size_t len, struct task_struct *tsk);
2100 #define get_task_comm(buf, tsk) ({			\
2101 	BUILD_BUG_ON(sizeof(buf) != TASK_COMM_LEN);	\
2102 	__get_task_comm(buf, sizeof(buf), tsk);		\
2103 })
2104 
2105 #ifdef CONFIG_SMP
scheduler_ipi(void)2106 static __always_inline void scheduler_ipi(void)
2107 {
2108 	/*
2109 	 * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
2110 	 * TIF_NEED_RESCHED remotely (for the first time) will also send
2111 	 * this IPI.
2112 	 */
2113 	preempt_fold_need_resched();
2114 }
2115 extern unsigned long wait_task_inactive(struct task_struct *, unsigned int match_state);
2116 #else
scheduler_ipi(void)2117 static inline void scheduler_ipi(void) { }
wait_task_inactive(struct task_struct * p,unsigned int match_state)2118 static inline unsigned long wait_task_inactive(struct task_struct *p, unsigned int match_state)
2119 {
2120 	return 1;
2121 }
2122 #endif
2123 
2124 /*
2125  * Set thread flags in other task's structures.
2126  * See asm/thread_info.h for TIF_xxxx flags available:
2127  */
set_tsk_thread_flag(struct task_struct * tsk,int flag)2128 static inline void set_tsk_thread_flag(struct task_struct *tsk, int flag)
2129 {
2130 	set_ti_thread_flag(task_thread_info(tsk), flag);
2131 }
2132 
clear_tsk_thread_flag(struct task_struct * tsk,int flag)2133 static inline void clear_tsk_thread_flag(struct task_struct *tsk, int flag)
2134 {
2135 	clear_ti_thread_flag(task_thread_info(tsk), flag);
2136 }
2137 
update_tsk_thread_flag(struct task_struct * tsk,int flag,bool value)2138 static inline void update_tsk_thread_flag(struct task_struct *tsk, int flag,
2139 					  bool value)
2140 {
2141 	update_ti_thread_flag(task_thread_info(tsk), flag, value);
2142 }
2143 
test_and_set_tsk_thread_flag(struct task_struct * tsk,int flag)2144 static inline int test_and_set_tsk_thread_flag(struct task_struct *tsk, int flag)
2145 {
2146 	return test_and_set_ti_thread_flag(task_thread_info(tsk), flag);
2147 }
2148 
test_and_clear_tsk_thread_flag(struct task_struct * tsk,int flag)2149 static inline int test_and_clear_tsk_thread_flag(struct task_struct *tsk, int flag)
2150 {
2151 	return test_and_clear_ti_thread_flag(task_thread_info(tsk), flag);
2152 }
2153 
test_tsk_thread_flag(struct task_struct * tsk,int flag)2154 static inline int test_tsk_thread_flag(struct task_struct *tsk, int flag)
2155 {
2156 	return test_ti_thread_flag(task_thread_info(tsk), flag);
2157 }
2158 
set_tsk_need_resched(struct task_struct * tsk)2159 static inline void set_tsk_need_resched(struct task_struct *tsk)
2160 {
2161 	set_tsk_thread_flag(tsk,TIF_NEED_RESCHED);
2162 }
2163 
clear_tsk_need_resched(struct task_struct * tsk)2164 static inline void clear_tsk_need_resched(struct task_struct *tsk)
2165 {
2166 	clear_tsk_thread_flag(tsk,TIF_NEED_RESCHED);
2167 }
2168 
test_tsk_need_resched(struct task_struct * tsk)2169 static inline int test_tsk_need_resched(struct task_struct *tsk)
2170 {
2171 	return unlikely(test_tsk_thread_flag(tsk,TIF_NEED_RESCHED));
2172 }
2173 
2174 /*
2175  * cond_resched() and cond_resched_lock(): latency reduction via
2176  * explicit rescheduling in places that are safe. The return
2177  * value indicates whether a reschedule was done in fact.
2178  * cond_resched_lock() will drop the spinlock before scheduling,
2179  */
2180 #if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC)
2181 extern int __cond_resched(void);
2182 
2183 #ifdef CONFIG_PREEMPT_DYNAMIC
2184 
2185 DECLARE_STATIC_CALL(cond_resched, __cond_resched);
2186 
_cond_resched(void)2187 static __always_inline int _cond_resched(void)
2188 {
2189 	return static_call_mod(cond_resched)();
2190 }
2191 
2192 #else
2193 
_cond_resched(void)2194 static inline int _cond_resched(void)
2195 {
2196 	return __cond_resched();
2197 }
2198 
2199 #endif /* CONFIG_PREEMPT_DYNAMIC */
2200 
2201 #else
2202 
_cond_resched(void)2203 static inline int _cond_resched(void) { return 0; }
2204 
2205 #endif /* !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC) */
2206 
2207 #define cond_resched() ({			\
2208 	___might_sleep(__FILE__, __LINE__, 0);	\
2209 	_cond_resched();			\
2210 })
2211 
2212 extern int __cond_resched_lock(spinlock_t *lock);
2213 extern int __cond_resched_rwlock_read(rwlock_t *lock);
2214 extern int __cond_resched_rwlock_write(rwlock_t *lock);
2215 
2216 #define cond_resched_lock(lock) ({				\
2217 	___might_sleep(__FILE__, __LINE__, PREEMPT_LOCK_OFFSET);\
2218 	__cond_resched_lock(lock);				\
2219 })
2220 
2221 #define cond_resched_rwlock_read(lock) ({			\
2222 	__might_sleep(__FILE__, __LINE__, PREEMPT_LOCK_OFFSET);	\
2223 	__cond_resched_rwlock_read(lock);			\
2224 })
2225 
2226 #define cond_resched_rwlock_write(lock) ({			\
2227 	__might_sleep(__FILE__, __LINE__, PREEMPT_LOCK_OFFSET);	\
2228 	__cond_resched_rwlock_write(lock);			\
2229 })
2230 
cond_resched_rcu(void)2231 static inline void cond_resched_rcu(void)
2232 {
2233 #if defined(CONFIG_DEBUG_ATOMIC_SLEEP) || !defined(CONFIG_PREEMPT_RCU)
2234 	rcu_read_unlock();
2235 	cond_resched();
2236 	rcu_read_lock();
2237 #endif
2238 }
2239 
2240 /*
2241  * Does a critical section need to be broken due to another
2242  * task waiting?: (technically does not depend on CONFIG_PREEMPTION,
2243  * but a general need for low latency)
2244  */
spin_needbreak(spinlock_t * lock)2245 static inline int spin_needbreak(spinlock_t *lock)
2246 {
2247 #ifdef CONFIG_PREEMPTION
2248 	return spin_is_contended(lock);
2249 #else
2250 	return 0;
2251 #endif
2252 }
2253 
2254 /*
2255  * Check if a rwlock is contended.
2256  * Returns non-zero if there is another task waiting on the rwlock.
2257  * Returns zero if the lock is not contended or the system / underlying
2258  * rwlock implementation does not support contention detection.
2259  * Technically does not depend on CONFIG_PREEMPTION, but a general need
2260  * for low latency.
2261  */
rwlock_needbreak(rwlock_t * lock)2262 static inline int rwlock_needbreak(rwlock_t *lock)
2263 {
2264 #ifdef CONFIG_PREEMPTION
2265 	return rwlock_is_contended(lock);
2266 #else
2267 	return 0;
2268 #endif
2269 }
2270 
need_resched(void)2271 static __always_inline bool need_resched(void)
2272 {
2273 	return unlikely(tif_need_resched());
2274 }
2275 
2276 /*
2277  * Wrappers for p->thread_info->cpu access. No-op on UP.
2278  */
2279 #ifdef CONFIG_SMP
2280 
task_cpu(const struct task_struct * p)2281 static inline unsigned int task_cpu(const struct task_struct *p)
2282 {
2283 #ifdef CONFIG_THREAD_INFO_IN_TASK
2284 	return READ_ONCE(p->cpu);
2285 #else
2286 	return READ_ONCE(task_thread_info(p)->cpu);
2287 #endif
2288 }
2289 
2290 extern void set_task_cpu(struct task_struct *p, unsigned int cpu);
2291 
2292 #else
2293 
task_cpu(const struct task_struct * p)2294 static inline unsigned int task_cpu(const struct task_struct *p)
2295 {
2296 	return 0;
2297 }
2298 
set_task_cpu(struct task_struct * p,unsigned int cpu)2299 static inline void set_task_cpu(struct task_struct *p, unsigned int cpu)
2300 {
2301 }
2302 
2303 #endif /* CONFIG_SMP */
2304 
2305 extern bool sched_task_on_rq(struct task_struct *p);
2306 
2307 /*
2308  * In order to reduce various lock holder preemption latencies provide an
2309  * interface to see if a vCPU is currently running or not.
2310  *
2311  * This allows us to terminate optimistic spin loops and block, analogous to
2312  * the native optimistic spin heuristic of testing if the lock owner task is
2313  * running or not.
2314  */
2315 #ifndef vcpu_is_preempted
vcpu_is_preempted(int cpu)2316 static inline bool vcpu_is_preempted(int cpu)
2317 {
2318 	return false;
2319 }
2320 #endif
2321 
2322 extern long sched_setaffinity(pid_t pid, const struct cpumask *new_mask);
2323 extern long sched_getaffinity(pid_t pid, struct cpumask *mask);
2324 
2325 #ifndef TASK_SIZE_OF
2326 #define TASK_SIZE_OF(tsk)	TASK_SIZE
2327 #endif
2328 
2329 #ifdef CONFIG_SMP
2330 /* Returns effective CPU energy utilization, as seen by the scheduler */
2331 unsigned long sched_cpu_util(int cpu, unsigned long max);
2332 #endif /* CONFIG_SMP */
2333 
2334 #ifdef CONFIG_RSEQ
2335 
2336 /*
2337  * Map the event mask on the user-space ABI enum rseq_cs_flags
2338  * for direct mask checks.
2339  */
2340 enum rseq_event_mask_bits {
2341 	RSEQ_EVENT_PREEMPT_BIT	= RSEQ_CS_FLAG_NO_RESTART_ON_PREEMPT_BIT,
2342 	RSEQ_EVENT_SIGNAL_BIT	= RSEQ_CS_FLAG_NO_RESTART_ON_SIGNAL_BIT,
2343 	RSEQ_EVENT_MIGRATE_BIT	= RSEQ_CS_FLAG_NO_RESTART_ON_MIGRATE_BIT,
2344 };
2345 
2346 enum rseq_event_mask {
2347 	RSEQ_EVENT_PREEMPT	= (1U << RSEQ_EVENT_PREEMPT_BIT),
2348 	RSEQ_EVENT_SIGNAL	= (1U << RSEQ_EVENT_SIGNAL_BIT),
2349 	RSEQ_EVENT_MIGRATE	= (1U << RSEQ_EVENT_MIGRATE_BIT),
2350 };
2351 
rseq_set_notify_resume(struct task_struct * t)2352 static inline void rseq_set_notify_resume(struct task_struct *t)
2353 {
2354 	if (t->rseq)
2355 		set_tsk_thread_flag(t, TIF_NOTIFY_RESUME);
2356 }
2357 
2358 void __rseq_handle_notify_resume(struct ksignal *sig, struct pt_regs *regs);
2359 
rseq_handle_notify_resume(struct ksignal * ksig,struct pt_regs * regs)2360 static inline void rseq_handle_notify_resume(struct ksignal *ksig,
2361 					     struct pt_regs *regs)
2362 {
2363 	if (current->rseq)
2364 		__rseq_handle_notify_resume(ksig, regs);
2365 }
2366 
rseq_signal_deliver(struct ksignal * ksig,struct pt_regs * regs)2367 static inline void rseq_signal_deliver(struct ksignal *ksig,
2368 				       struct pt_regs *regs)
2369 {
2370 	preempt_disable();
2371 	__set_bit(RSEQ_EVENT_SIGNAL_BIT, &current->rseq_event_mask);
2372 	preempt_enable();
2373 	rseq_handle_notify_resume(ksig, regs);
2374 }
2375 
2376 /* rseq_preempt() requires preemption to be disabled. */
rseq_preempt(struct task_struct * t)2377 static inline void rseq_preempt(struct task_struct *t)
2378 {
2379 	__set_bit(RSEQ_EVENT_PREEMPT_BIT, &t->rseq_event_mask);
2380 	rseq_set_notify_resume(t);
2381 }
2382 
2383 /* rseq_migrate() requires preemption to be disabled. */
rseq_migrate(struct task_struct * t)2384 static inline void rseq_migrate(struct task_struct *t)
2385 {
2386 	__set_bit(RSEQ_EVENT_MIGRATE_BIT, &t->rseq_event_mask);
2387 	rseq_set_notify_resume(t);
2388 }
2389 
2390 /*
2391  * If parent process has a registered restartable sequences area, the
2392  * child inherits. Unregister rseq for a clone with CLONE_VM set.
2393  */
rseq_fork(struct task_struct * t,unsigned long clone_flags)2394 static inline void rseq_fork(struct task_struct *t, unsigned long clone_flags)
2395 {
2396 	if (clone_flags & CLONE_VM) {
2397 		t->rseq = NULL;
2398 		t->rseq_sig = 0;
2399 		t->rseq_event_mask = 0;
2400 	} else {
2401 		t->rseq = current->rseq;
2402 		t->rseq_sig = current->rseq_sig;
2403 		t->rseq_event_mask = current->rseq_event_mask;
2404 	}
2405 }
2406 
rseq_execve(struct task_struct * t)2407 static inline void rseq_execve(struct task_struct *t)
2408 {
2409 	t->rseq = NULL;
2410 	t->rseq_sig = 0;
2411 	t->rseq_event_mask = 0;
2412 }
2413 
2414 #else
2415 
rseq_set_notify_resume(struct task_struct * t)2416 static inline void rseq_set_notify_resume(struct task_struct *t)
2417 {
2418 }
rseq_handle_notify_resume(struct ksignal * ksig,struct pt_regs * regs)2419 static inline void rseq_handle_notify_resume(struct ksignal *ksig,
2420 					     struct pt_regs *regs)
2421 {
2422 }
rseq_signal_deliver(struct ksignal * ksig,struct pt_regs * regs)2423 static inline void rseq_signal_deliver(struct ksignal *ksig,
2424 				       struct pt_regs *regs)
2425 {
2426 }
rseq_preempt(struct task_struct * t)2427 static inline void rseq_preempt(struct task_struct *t)
2428 {
2429 }
rseq_migrate(struct task_struct * t)2430 static inline void rseq_migrate(struct task_struct *t)
2431 {
2432 }
rseq_fork(struct task_struct * t,unsigned long clone_flags)2433 static inline void rseq_fork(struct task_struct *t, unsigned long clone_flags)
2434 {
2435 }
rseq_execve(struct task_struct * t)2436 static inline void rseq_execve(struct task_struct *t)
2437 {
2438 }
2439 
2440 #endif
2441 
2442 #ifdef CONFIG_DEBUG_RSEQ
2443 
2444 void rseq_syscall(struct pt_regs *regs);
2445 
2446 #else
2447 
rseq_syscall(struct pt_regs * regs)2448 static inline void rseq_syscall(struct pt_regs *regs)
2449 {
2450 }
2451 
2452 #endif
2453 
2454 const struct sched_avg *sched_trace_cfs_rq_avg(struct cfs_rq *cfs_rq);
2455 char *sched_trace_cfs_rq_path(struct cfs_rq *cfs_rq, char *str, int len);
2456 int sched_trace_cfs_rq_cpu(struct cfs_rq *cfs_rq);
2457 
2458 const struct sched_avg *sched_trace_rq_avg_rt(struct rq *rq);
2459 const struct sched_avg *sched_trace_rq_avg_dl(struct rq *rq);
2460 const struct sched_avg *sched_trace_rq_avg_irq(struct rq *rq);
2461 
2462 int sched_trace_rq_cpu(struct rq *rq);
2463 int sched_trace_rq_cpu_capacity(struct rq *rq);
2464 int sched_trace_rq_nr_running(struct rq *rq);
2465 
2466 const struct cpumask *sched_trace_rd_span(struct root_domain *rd);
2467 
2468 #ifdef CONFIG_SCHED_CORE
2469 extern void sched_core_free(struct task_struct *tsk);
2470 extern void sched_core_fork(struct task_struct *p);
2471 extern int sched_core_share_pid(unsigned int cmd, pid_t pid, enum pid_type type,
2472 				unsigned long uaddr);
2473 #else
sched_core_free(struct task_struct * tsk)2474 static inline void sched_core_free(struct task_struct *tsk) { }
sched_core_fork(struct task_struct * p)2475 static inline void sched_core_fork(struct task_struct *p) { }
2476 #endif
2477 
2478 #endif
2479