posix-cpu-timers.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Implement CPU time clocks for the POSIX clock interface.
  4. */
  5. #include <linux/sched/signal.h>
  6. #include <linux/sched/cputime.h>
  7. #include <linux/posix-timers.h>
  8. #include <linux/errno.h>
  9. #include <linux/math64.h>
  10. #include <linux/uaccess.h>
  11. #include <linux/kernel_stat.h>
  12. #include <trace/events/timer.h>
  13. #include <linux/tick.h>
  14. #include <linux/workqueue.h>
  15. #include <linux/compat.h>
  16. #include <linux/sched/deadline.h>
  17. #include "posix-timers.h"
  18. static void posix_cpu_timer_rearm(struct k_itimer *timer);
  19. void posix_cputimers_group_init(struct posix_cputimers *pct, u64 cpu_limit)
  20. {
  21. posix_cputimers_init(pct);
  22. if (cpu_limit != RLIM_INFINITY) {
  23. pct->bases[CPUCLOCK_PROF].nextevt = cpu_limit * NSEC_PER_SEC;
  24. pct->timers_active = true;
  25. }
  26. }
  27. /*
  28. * Called after updating RLIMIT_CPU to run cpu timer and update
  29. * tsk->signal->posix_cputimers.bases[clock].nextevt expiration cache if
  30. * necessary. Needs siglock protection since other code may update the
  31. * expiration cache as well.
  32. */
  33. void update_rlimit_cpu(struct task_struct *task, unsigned long rlim_new)
  34. {
  35. u64 nsecs = rlim_new * NSEC_PER_SEC;
  36. spin_lock_irq(&task->sighand->siglock);
  37. set_process_cpu_timer(task, CPUCLOCK_PROF, &nsecs, NULL);
  38. spin_unlock_irq(&task->sighand->siglock);
  39. }
  40. /*
  41. * Functions for validating access to tasks.
  42. */
  43. static struct pid *pid_for_clock(const clockid_t clock, bool gettime)
  44. {
  45. const bool thread = !!CPUCLOCK_PERTHREAD(clock);
  46. const pid_t upid = CPUCLOCK_PID(clock);
  47. struct pid *pid;
  48. if (CPUCLOCK_WHICH(clock) >= CPUCLOCK_MAX)
  49. return NULL;
  50. /*
  51. * If the encoded PID is 0, then the timer is targeted at current
  52. * or the process to which current belongs.
  53. */
  54. if (upid == 0)
  55. return thread ? task_pid(current) : task_tgid(current);
  56. pid = find_vpid(upid);
  57. if (!pid)
  58. return NULL;
  59. if (thread) {
  60. struct task_struct *tsk = pid_task(pid, PIDTYPE_PID);
  61. return (tsk && same_thread_group(tsk, current)) ? pid : NULL;
  62. }
  63. /*
  64. * For clock_gettime(PROCESS) allow finding the process by
  65. * with the pid of the current task. The code needs the tgid
  66. * of the process so that pid_task(pid, PIDTYPE_TGID) can be
  67. * used to find the process.
  68. */
  69. if (gettime && (pid == task_pid(current)))
  70. return task_tgid(current);
  71. /*
  72. * For processes require that pid identifies a process.
  73. */
  74. return pid_has_task(pid, PIDTYPE_TGID) ? pid : NULL;
  75. }
  76. static inline int validate_clock_permissions(const clockid_t clock)
  77. {
  78. int ret;
  79. rcu_read_lock();
  80. ret = pid_for_clock(clock, false) ? 0 : -EINVAL;
  81. rcu_read_unlock();
  82. return ret;
  83. }
  84. static inline enum pid_type clock_pid_type(const clockid_t clock)
  85. {
  86. return CPUCLOCK_PERTHREAD(clock) ? PIDTYPE_PID : PIDTYPE_TGID;
  87. }
  88. static inline struct task_struct *cpu_timer_task_rcu(struct k_itimer *timer)
  89. {
  90. return pid_task(timer->it.cpu.pid, clock_pid_type(timer->it_clock));
  91. }
  92. /*
  93. * Update expiry time from increment, and increase overrun count,
  94. * given the current clock sample.
  95. */
  96. static u64 bump_cpu_timer(struct k_itimer *timer, u64 now)
  97. {
  98. u64 delta, incr, expires = timer->it.cpu.node.expires;
  99. int i;
  100. if (!timer->it_interval)
  101. return expires;
  102. if (now < expires)
  103. return expires;
  104. incr = timer->it_interval;
  105. delta = now + incr - expires;
  106. /* Don't use (incr*2 < delta), incr*2 might overflow. */
  107. for (i = 0; incr < delta - incr; i++)
  108. incr = incr << 1;
  109. for (; i >= 0; incr >>= 1, i--) {
  110. if (delta < incr)
  111. continue;
  112. timer->it.cpu.node.expires += incr;
  113. timer->it_overrun += 1LL << i;
  114. delta -= incr;
  115. }
  116. return timer->it.cpu.node.expires;
  117. }
  118. /* Check whether all cache entries contain U64_MAX, i.e. eternal expiry time */
  119. static inline bool expiry_cache_is_inactive(const struct posix_cputimers *pct)
  120. {
  121. return !(~pct->bases[CPUCLOCK_PROF].nextevt |
  122. ~pct->bases[CPUCLOCK_VIRT].nextevt |
  123. ~pct->bases[CPUCLOCK_SCHED].nextevt);
  124. }
  125. static int
  126. posix_cpu_clock_getres(const clockid_t which_clock, struct timespec64 *tp)
  127. {
  128. int error = validate_clock_permissions(which_clock);
  129. if (!error) {
  130. tp->tv_sec = 0;
  131. tp->tv_nsec = ((NSEC_PER_SEC + HZ - 1) / HZ);
  132. if (CPUCLOCK_WHICH(which_clock) == CPUCLOCK_SCHED) {
  133. /*
  134. * If sched_clock is using a cycle counter, we
  135. * don't have any idea of its true resolution
  136. * exported, but it is much more than 1s/HZ.
  137. */
  138. tp->tv_nsec = 1;
  139. }
  140. }
  141. return error;
  142. }
  143. static int
  144. posix_cpu_clock_set(const clockid_t clock, const struct timespec64 *tp)
  145. {
  146. int error = validate_clock_permissions(clock);
  147. /*
  148. * You can never reset a CPU clock, but we check for other errors
  149. * in the call before failing with EPERM.
  150. */
  151. return error ? : -EPERM;
  152. }
  153. /*
  154. * Sample a per-thread clock for the given task. clkid is validated.
  155. */
  156. static u64 cpu_clock_sample(const clockid_t clkid, struct task_struct *p)
  157. {
  158. u64 utime, stime;
  159. if (clkid == CPUCLOCK_SCHED)
  160. return task_sched_runtime(p);
  161. task_cputime(p, &utime, &stime);
  162. switch (clkid) {
  163. case CPUCLOCK_PROF:
  164. return utime + stime;
  165. case CPUCLOCK_VIRT:
  166. return utime;
  167. default:
  168. WARN_ON_ONCE(1);
  169. }
  170. return 0;
  171. }
  172. static inline void store_samples(u64 *samples, u64 stime, u64 utime, u64 rtime)
  173. {
  174. samples[CPUCLOCK_PROF] = stime + utime;
  175. samples[CPUCLOCK_VIRT] = utime;
  176. samples[CPUCLOCK_SCHED] = rtime;
  177. }
  178. static void task_sample_cputime(struct task_struct *p, u64 *samples)
  179. {
  180. u64 stime, utime;
  181. task_cputime(p, &utime, &stime);
  182. store_samples(samples, stime, utime, p->se.sum_exec_runtime);
  183. }
  184. static void proc_sample_cputime_atomic(struct task_cputime_atomic *at,
  185. u64 *samples)
  186. {
  187. u64 stime, utime, rtime;
  188. utime = atomic64_read(&at->utime);
  189. stime = atomic64_read(&at->stime);
  190. rtime = atomic64_read(&at->sum_exec_runtime);
  191. store_samples(samples, stime, utime, rtime);
  192. }
  193. /*
  194. * Set cputime to sum_cputime if sum_cputime > cputime. Use cmpxchg
  195. * to avoid race conditions with concurrent updates to cputime.
  196. */
  197. static inline void __update_gt_cputime(atomic64_t *cputime, u64 sum_cputime)
  198. {
  199. u64 curr_cputime;
  200. retry:
  201. curr_cputime = atomic64_read(cputime);
  202. if (sum_cputime > curr_cputime) {
  203. if (atomic64_cmpxchg(cputime, curr_cputime, sum_cputime) != curr_cputime)
  204. goto retry;
  205. }
  206. }
  207. static void update_gt_cputime(struct task_cputime_atomic *cputime_atomic,
  208. struct task_cputime *sum)
  209. {
  210. __update_gt_cputime(&cputime_atomic->utime, sum->utime);
  211. __update_gt_cputime(&cputime_atomic->stime, sum->stime);
  212. __update_gt_cputime(&cputime_atomic->sum_exec_runtime, sum->sum_exec_runtime);
  213. }
  214. /**
  215. * thread_group_sample_cputime - Sample cputime for a given task
  216. * @tsk: Task for which cputime needs to be started
  217. * @samples: Storage for time samples
  218. *
  219. * Called from sys_getitimer() to calculate the expiry time of an active
  220. * timer. That means group cputime accounting is already active. Called
  221. * with task sighand lock held.
  222. *
  223. * Updates @times with an uptodate sample of the thread group cputimes.
  224. */
  225. void thread_group_sample_cputime(struct task_struct *tsk, u64 *samples)
  226. {
  227. struct thread_group_cputimer *cputimer = &tsk->signal->cputimer;
  228. struct posix_cputimers *pct = &tsk->signal->posix_cputimers;
  229. WARN_ON_ONCE(!pct->timers_active);
  230. proc_sample_cputime_atomic(&cputimer->cputime_atomic, samples);
  231. }
  232. /**
  233. * thread_group_start_cputime - Start cputime and return a sample
  234. * @tsk: Task for which cputime needs to be started
  235. * @samples: Storage for time samples
  236. *
  237. * The thread group cputime accouting is avoided when there are no posix
  238. * CPU timers armed. Before starting a timer it's required to check whether
  239. * the time accounting is active. If not, a full update of the atomic
  240. * accounting store needs to be done and the accounting enabled.
  241. *
  242. * Updates @times with an uptodate sample of the thread group cputimes.
  243. */
  244. static void thread_group_start_cputime(struct task_struct *tsk, u64 *samples)
  245. {
  246. struct thread_group_cputimer *cputimer = &tsk->signal->cputimer;
  247. struct posix_cputimers *pct = &tsk->signal->posix_cputimers;
  248. /* Check if cputimer isn't running. This is accessed without locking. */
  249. if (!READ_ONCE(pct->timers_active)) {
  250. struct task_cputime sum;
  251. /*
  252. * The POSIX timer interface allows for absolute time expiry
  253. * values through the TIMER_ABSTIME flag, therefore we have
  254. * to synchronize the timer to the clock every time we start it.
  255. */
  256. thread_group_cputime(tsk, &sum);
  257. update_gt_cputime(&cputimer->cputime_atomic, &sum);
  258. /*
  259. * We're setting timers_active without a lock. Ensure this
  260. * only gets written to in one operation. We set it after
  261. * update_gt_cputime() as a small optimization, but
  262. * barriers are not required because update_gt_cputime()
  263. * can handle concurrent updates.
  264. */
  265. WRITE_ONCE(pct->timers_active, true);
  266. }
  267. proc_sample_cputime_atomic(&cputimer->cputime_atomic, samples);
  268. }
  269. static void __thread_group_cputime(struct task_struct *tsk, u64 *samples)
  270. {
  271. struct task_cputime ct;
  272. thread_group_cputime(tsk, &ct);
  273. store_samples(samples, ct.stime, ct.utime, ct.sum_exec_runtime);
  274. }
  275. /*
  276. * Sample a process (thread group) clock for the given task clkid. If the
  277. * group's cputime accounting is already enabled, read the atomic
  278. * store. Otherwise a full update is required. clkid is already validated.
  279. */
  280. static u64 cpu_clock_sample_group(const clockid_t clkid, struct task_struct *p,
  281. bool start)
  282. {
  283. struct thread_group_cputimer *cputimer = &p->signal->cputimer;
  284. struct posix_cputimers *pct = &p->signal->posix_cputimers;
  285. u64 samples[CPUCLOCK_MAX];
  286. if (!READ_ONCE(pct->timers_active)) {
  287. if (start)
  288. thread_group_start_cputime(p, samples);
  289. else
  290. __thread_group_cputime(p, samples);
  291. } else {
  292. proc_sample_cputime_atomic(&cputimer->cputime_atomic, samples);
  293. }
  294. return samples[clkid];
  295. }
  296. static int posix_cpu_clock_get(const clockid_t clock, struct timespec64 *tp)
  297. {
  298. const clockid_t clkid = CPUCLOCK_WHICH(clock);
  299. struct task_struct *tsk;
  300. u64 t;
  301. rcu_read_lock();
  302. tsk = pid_task(pid_for_clock(clock, true), clock_pid_type(clock));
  303. if (!tsk) {
  304. rcu_read_unlock();
  305. return -EINVAL;
  306. }
  307. if (CPUCLOCK_PERTHREAD(clock))
  308. t = cpu_clock_sample(clkid, tsk);
  309. else
  310. t = cpu_clock_sample_group(clkid, tsk, false);
  311. rcu_read_unlock();
  312. *tp = ns_to_timespec64(t);
  313. return 0;
  314. }
  315. /*
  316. * Validate the clockid_t for a new CPU-clock timer, and initialize the timer.
  317. * This is called from sys_timer_create() and do_cpu_nanosleep() with the
  318. * new timer already all-zeros initialized.
  319. */
  320. static int posix_cpu_timer_create(struct k_itimer *new_timer)
  321. {
  322. static struct lock_class_key posix_cpu_timers_key;
  323. struct pid *pid;
  324. rcu_read_lock();
  325. pid = pid_for_clock(new_timer->it_clock, false);
  326. if (!pid) {
  327. rcu_read_unlock();
  328. return -EINVAL;
  329. }
  330. /*
  331. * If posix timer expiry is handled in task work context then
  332. * timer::it_lock can be taken without disabling interrupts as all
  333. * other locking happens in task context. This requires a seperate
  334. * lock class key otherwise regular posix timer expiry would record
  335. * the lock class being taken in interrupt context and generate a
  336. * false positive warning.
  337. */
  338. if (IS_ENABLED(CONFIG_POSIX_CPU_TIMERS_TASK_WORK))
  339. lockdep_set_class(&new_timer->it_lock, &posix_cpu_timers_key);
  340. new_timer->kclock = &clock_posix_cpu;
  341. timerqueue_init(&new_timer->it.cpu.node);
  342. new_timer->it.cpu.pid = get_pid(pid);
  343. rcu_read_unlock();
  344. return 0;
  345. }
  346. /*
  347. * Clean up a CPU-clock timer that is about to be destroyed.
  348. * This is called from timer deletion with the timer already locked.
  349. * If we return TIMER_RETRY, it's necessary to release the timer's lock
  350. * and try again. (This happens when the timer is in the middle of firing.)
  351. */
  352. static int posix_cpu_timer_del(struct k_itimer *timer)
  353. {
  354. struct cpu_timer *ctmr = &timer->it.cpu;
  355. struct sighand_struct *sighand;
  356. struct task_struct *p;
  357. unsigned long flags;
  358. int ret = 0;
  359. rcu_read_lock();
  360. p = cpu_timer_task_rcu(timer);
  361. if (!p)
  362. goto out;
  363. /*
  364. * Protect against sighand release/switch in exit/exec and process/
  365. * thread timer list entry concurrent read/writes.
  366. */
  367. sighand = lock_task_sighand(p, &flags);
  368. if (unlikely(sighand == NULL)) {
  369. /*
  370. * This raced with the reaping of the task. The exit cleanup
  371. * should have removed this timer from the timer queue.
  372. */
  373. WARN_ON_ONCE(ctmr->head || timerqueue_node_queued(&ctmr->node));
  374. } else {
  375. if (timer->it.cpu.firing)
  376. ret = TIMER_RETRY;
  377. else
  378. cpu_timer_dequeue(ctmr);
  379. unlock_task_sighand(p, &flags);
  380. }
  381. out:
  382. rcu_read_unlock();
  383. if (!ret)
  384. put_pid(ctmr->pid);
  385. return ret;
  386. }
  387. static void cleanup_timerqueue(struct timerqueue_head *head)
  388. {
  389. struct timerqueue_node *node;
  390. struct cpu_timer *ctmr;
  391. while ((node = timerqueue_getnext(head))) {
  392. timerqueue_del(head, node);
  393. ctmr = container_of(node, struct cpu_timer, node);
  394. ctmr->head = NULL;
  395. }
  396. }
  397. /*
  398. * Clean out CPU timers which are still armed when a thread exits. The
  399. * timers are only removed from the list. No other updates are done. The
  400. * corresponding posix timers are still accessible, but cannot be rearmed.
  401. *
  402. * This must be called with the siglock held.
  403. */
  404. static void cleanup_timers(struct posix_cputimers *pct)
  405. {
  406. cleanup_timerqueue(&pct->bases[CPUCLOCK_PROF].tqhead);
  407. cleanup_timerqueue(&pct->bases[CPUCLOCK_VIRT].tqhead);
  408. cleanup_timerqueue(&pct->bases[CPUCLOCK_SCHED].tqhead);
  409. }
  410. /*
  411. * These are both called with the siglock held, when the current thread
  412. * is being reaped. When the final (leader) thread in the group is reaped,
  413. * posix_cpu_timers_exit_group will be called after posix_cpu_timers_exit.
  414. */
  415. void posix_cpu_timers_exit(struct task_struct *tsk)
  416. {
  417. cleanup_timers(&tsk->posix_cputimers);
  418. }
  419. void posix_cpu_timers_exit_group(struct task_struct *tsk)
  420. {
  421. cleanup_timers(&tsk->signal->posix_cputimers);
  422. }
  423. /*
  424. * Insert the timer on the appropriate list before any timers that
  425. * expire later. This must be called with the sighand lock held.
  426. */
  427. static void arm_timer(struct k_itimer *timer, struct task_struct *p)
  428. {
  429. int clkidx = CPUCLOCK_WHICH(timer->it_clock);
  430. struct cpu_timer *ctmr = &timer->it.cpu;
  431. u64 newexp = cpu_timer_getexpires(ctmr);
  432. struct posix_cputimer_base *base;
  433. if (CPUCLOCK_PERTHREAD(timer->it_clock))
  434. base = p->posix_cputimers.bases + clkidx;
  435. else
  436. base = p->signal->posix_cputimers.bases + clkidx;
  437. if (!cpu_timer_enqueue(&base->tqhead, ctmr))
  438. return;
  439. /*
  440. * We are the new earliest-expiring POSIX 1.b timer, hence
  441. * need to update expiration cache. Take into account that
  442. * for process timers we share expiration cache with itimers
  443. * and RLIMIT_CPU and for thread timers with RLIMIT_RTTIME.
  444. */
  445. if (newexp < base->nextevt)
  446. base->nextevt = newexp;
  447. if (CPUCLOCK_PERTHREAD(timer->it_clock))
  448. tick_dep_set_task(p, TICK_DEP_BIT_POSIX_TIMER);
  449. else
  450. tick_dep_set_signal(p->signal, TICK_DEP_BIT_POSIX_TIMER);
  451. }
  452. /*
  453. * The timer is locked, fire it and arrange for its reload.
  454. */
  455. static void cpu_timer_fire(struct k_itimer *timer)
  456. {
  457. struct cpu_timer *ctmr = &timer->it.cpu;
  458. if ((timer->it_sigev_notify & ~SIGEV_THREAD_ID) == SIGEV_NONE) {
  459. /*
  460. * User don't want any signal.
  461. */
  462. cpu_timer_setexpires(ctmr, 0);
  463. } else if (unlikely(timer->sigq == NULL)) {
  464. /*
  465. * This a special case for clock_nanosleep,
  466. * not a normal timer from sys_timer_create.
  467. */
  468. wake_up_process(timer->it_process);
  469. cpu_timer_setexpires(ctmr, 0);
  470. } else if (!timer->it_interval) {
  471. /*
  472. * One-shot timer. Clear it as soon as it's fired.
  473. */
  474. posix_timer_event(timer, 0);
  475. cpu_timer_setexpires(ctmr, 0);
  476. } else if (posix_timer_event(timer, ++timer->it_requeue_pending)) {
  477. /*
  478. * The signal did not get queued because the signal
  479. * was ignored, so we won't get any callback to
  480. * reload the timer. But we need to keep it
  481. * ticking in case the signal is deliverable next time.
  482. */
  483. posix_cpu_timer_rearm(timer);
  484. ++timer->it_requeue_pending;
  485. }
  486. }
  487. /*
  488. * Guts of sys_timer_settime for CPU timers.
  489. * This is called with the timer locked and interrupts disabled.
  490. * If we return TIMER_RETRY, it's necessary to release the timer's lock
  491. * and try again. (This happens when the timer is in the middle of firing.)
  492. */
  493. static int posix_cpu_timer_set(struct k_itimer *timer, int timer_flags,
  494. struct itimerspec64 *new, struct itimerspec64 *old)
  495. {
  496. clockid_t clkid = CPUCLOCK_WHICH(timer->it_clock);
  497. u64 old_expires, new_expires, old_incr, val;
  498. struct cpu_timer *ctmr = &timer->it.cpu;
  499. struct sighand_struct *sighand;
  500. struct task_struct *p;
  501. unsigned long flags;
  502. int ret = 0;
  503. rcu_read_lock();
  504. p = cpu_timer_task_rcu(timer);
  505. if (!p) {
  506. /*
  507. * If p has just been reaped, we can no
  508. * longer get any information about it at all.
  509. */
  510. rcu_read_unlock();
  511. return -ESRCH;
  512. }
  513. /*
  514. * Use the to_ktime conversion because that clamps the maximum
  515. * value to KTIME_MAX and avoid multiplication overflows.
  516. */
  517. new_expires = ktime_to_ns(timespec64_to_ktime(new->it_value));
  518. /*
  519. * Protect against sighand release/switch in exit/exec and p->cpu_timers
  520. * and p->signal->cpu_timers read/write in arm_timer()
  521. */
  522. sighand = lock_task_sighand(p, &flags);
  523. /*
  524. * If p has just been reaped, we can no
  525. * longer get any information about it at all.
  526. */
  527. if (unlikely(sighand == NULL)) {
  528. rcu_read_unlock();
  529. return -ESRCH;
  530. }
  531. /*
  532. * Disarm any old timer after extracting its expiry time.
  533. */
  534. old_incr = timer->it_interval;
  535. old_expires = cpu_timer_getexpires(ctmr);
  536. if (unlikely(timer->it.cpu.firing)) {
  537. timer->it.cpu.firing = -1;
  538. ret = TIMER_RETRY;
  539. } else {
  540. cpu_timer_dequeue(ctmr);
  541. }
  542. /*
  543. * We need to sample the current value to convert the new
  544. * value from to relative and absolute, and to convert the
  545. * old value from absolute to relative. To set a process
  546. * timer, we need a sample to balance the thread expiry
  547. * times (in arm_timer). With an absolute time, we must
  548. * check if it's already passed. In short, we need a sample.
  549. */
  550. if (CPUCLOCK_PERTHREAD(timer->it_clock))
  551. val = cpu_clock_sample(clkid, p);
  552. else
  553. val = cpu_clock_sample_group(clkid, p, true);
  554. if (old) {
  555. if (old_expires == 0) {
  556. old->it_value.tv_sec = 0;
  557. old->it_value.tv_nsec = 0;
  558. } else {
  559. /*
  560. * Update the timer in case it has overrun already.
  561. * If it has, we'll report it as having overrun and
  562. * with the next reloaded timer already ticking,
  563. * though we are swallowing that pending
  564. * notification here to install the new setting.
  565. */
  566. u64 exp = bump_cpu_timer(timer, val);
  567. if (val < exp) {
  568. old_expires = exp - val;
  569. old->it_value = ns_to_timespec64(old_expires);
  570. } else {
  571. old->it_value.tv_nsec = 1;
  572. old->it_value.tv_sec = 0;
  573. }
  574. }
  575. }
  576. if (unlikely(ret)) {
  577. /*
  578. * We are colliding with the timer actually firing.
  579. * Punt after filling in the timer's old value, and
  580. * disable this firing since we are already reporting
  581. * it as an overrun (thanks to bump_cpu_timer above).
  582. */
  583. unlock_task_sighand(p, &flags);
  584. goto out;
  585. }
  586. if (new_expires != 0 && !(timer_flags & TIMER_ABSTIME)) {
  587. new_expires += val;
  588. }
  589. /*
  590. * Install the new expiry time (or zero).
  591. * For a timer with no notification action, we don't actually
  592. * arm the timer (we'll just fake it for timer_gettime).
  593. */
  594. cpu_timer_setexpires(ctmr, new_expires);
  595. if (new_expires != 0 && val < new_expires) {
  596. arm_timer(timer, p);
  597. }
  598. unlock_task_sighand(p, &flags);
  599. /*
  600. * Install the new reload setting, and
  601. * set up the signal and overrun bookkeeping.
  602. */
  603. timer->it_interval = timespec64_to_ktime(new->it_interval);
  604. /*
  605. * This acts as a modification timestamp for the timer,
  606. * so any automatic reload attempt will punt on seeing
  607. * that we have reset the timer manually.
  608. */
  609. timer->it_requeue_pending = (timer->it_requeue_pending + 2) &
  610. ~REQUEUE_PENDING;
  611. timer->it_overrun_last = 0;
  612. timer->it_overrun = -1;
  613. if (new_expires != 0 && !(val < new_expires)) {
  614. /*
  615. * The designated time already passed, so we notify
  616. * immediately, even if the thread never runs to
  617. * accumulate more time on this clock.
  618. */
  619. cpu_timer_fire(timer);
  620. }
  621. ret = 0;
  622. out:
  623. rcu_read_unlock();
  624. if (old)
  625. old->it_interval = ns_to_timespec64(old_incr);
  626. return ret;
  627. }
  628. static void posix_cpu_timer_get(struct k_itimer *timer, struct itimerspec64 *itp)
  629. {
  630. clockid_t clkid = CPUCLOCK_WHICH(timer->it_clock);
  631. struct cpu_timer *ctmr = &timer->it.cpu;
  632. u64 now, expires = cpu_timer_getexpires(ctmr);
  633. struct task_struct *p;
  634. rcu_read_lock();
  635. p = cpu_timer_task_rcu(timer);
  636. if (!p)
  637. goto out;
  638. /*
  639. * Easy part: convert the reload time.
  640. */
  641. itp->it_interval = ktime_to_timespec64(timer->it_interval);
  642. if (!expires)
  643. goto out;
  644. /*
  645. * Sample the clock to take the difference with the expiry time.
  646. */
  647. if (CPUCLOCK_PERTHREAD(timer->it_clock))
  648. now = cpu_clock_sample(clkid, p);
  649. else
  650. now = cpu_clock_sample_group(clkid, p, false);
  651. if (now < expires) {
  652. itp->it_value = ns_to_timespec64(expires - now);
  653. } else {
  654. /*
  655. * The timer should have expired already, but the firing
  656. * hasn't taken place yet. Say it's just about to expire.
  657. */
  658. itp->it_value.tv_nsec = 1;
  659. itp->it_value.tv_sec = 0;
  660. }
  661. out:
  662. rcu_read_unlock();
  663. }
  664. #define MAX_COLLECTED 20
  665. static u64 collect_timerqueue(struct timerqueue_head *head,
  666. struct list_head *firing, u64 now)
  667. {
  668. struct timerqueue_node *next;
  669. int i = 0;
  670. while ((next = timerqueue_getnext(head))) {
  671. struct cpu_timer *ctmr;
  672. u64 expires;
  673. ctmr = container_of(next, struct cpu_timer, node);
  674. expires = cpu_timer_getexpires(ctmr);
  675. /* Limit the number of timers to expire at once */
  676. if (++i == MAX_COLLECTED || now < expires)
  677. return expires;
  678. ctmr->firing = 1;
  679. cpu_timer_dequeue(ctmr);
  680. list_add_tail(&ctmr->elist, firing);
  681. }
  682. return U64_MAX;
  683. }
  684. static void collect_posix_cputimers(struct posix_cputimers *pct, u64 *samples,
  685. struct list_head *firing)
  686. {
  687. struct posix_cputimer_base *base = pct->bases;
  688. int i;
  689. for (i = 0; i < CPUCLOCK_MAX; i++, base++) {
  690. base->nextevt = collect_timerqueue(&base->tqhead, firing,
  691. samples[i]);
  692. }
  693. }
  694. static inline void check_dl_overrun(struct task_struct *tsk)
  695. {
  696. if (tsk->dl.dl_overrun) {
  697. tsk->dl.dl_overrun = 0;
  698. __group_send_sig_info(SIGXCPU, SEND_SIG_PRIV, tsk);
  699. }
  700. }
  701. static bool check_rlimit(u64 time, u64 limit, int signo, bool rt, bool hard)
  702. {
  703. if (time < limit)
  704. return false;
  705. if (print_fatal_signals) {
  706. pr_info("%s Watchdog Timeout (%s): %s[%d]\n",
  707. rt ? "RT" : "CPU", hard ? "hard" : "soft",
  708. current->comm, task_pid_nr(current));
  709. }
  710. __group_send_sig_info(signo, SEND_SIG_PRIV, current);
  711. return true;
  712. }
  713. /*
  714. * Check for any per-thread CPU timers that have fired and move them off
  715. * the tsk->cpu_timers[N] list onto the firing list. Here we update the
  716. * tsk->it_*_expires values to reflect the remaining thread CPU timers.
  717. */
  718. static void check_thread_timers(struct task_struct *tsk,
  719. struct list_head *firing)
  720. {
  721. struct posix_cputimers *pct = &tsk->posix_cputimers;
  722. u64 samples[CPUCLOCK_MAX];
  723. unsigned long soft;
  724. if (dl_task(tsk))
  725. check_dl_overrun(tsk);
  726. if (expiry_cache_is_inactive(pct))
  727. return;
  728. task_sample_cputime(tsk, samples);
  729. collect_posix_cputimers(pct, samples, firing);
  730. /*
  731. * Check for the special case thread timers.
  732. */
  733. soft = task_rlimit(tsk, RLIMIT_RTTIME);
  734. if (soft != RLIM_INFINITY) {
  735. /* Task RT timeout is accounted in jiffies. RTTIME is usec */
  736. unsigned long rttime = tsk->rt.timeout * (USEC_PER_SEC / HZ);
  737. unsigned long hard = task_rlimit_max(tsk, RLIMIT_RTTIME);
  738. /* At the hard limit, send SIGKILL. No further action. */
  739. if (hard != RLIM_INFINITY &&
  740. check_rlimit(rttime, hard, SIGKILL, true, true))
  741. return;
  742. /* At the soft limit, send a SIGXCPU every second */
  743. if (check_rlimit(rttime, soft, SIGXCPU, true, false)) {
  744. soft += USEC_PER_SEC;
  745. tsk->signal->rlim[RLIMIT_RTTIME].rlim_cur = soft;
  746. }
  747. }
  748. if (expiry_cache_is_inactive(pct))
  749. tick_dep_clear_task(tsk, TICK_DEP_BIT_POSIX_TIMER);
  750. }
  751. static inline void stop_process_timers(struct signal_struct *sig)
  752. {
  753. struct posix_cputimers *pct = &sig->posix_cputimers;
  754. /* Turn off the active flag. This is done without locking. */
  755. WRITE_ONCE(pct->timers_active, false);
  756. tick_dep_clear_signal(sig, TICK_DEP_BIT_POSIX_TIMER);
  757. }
  758. static void check_cpu_itimer(struct task_struct *tsk, struct cpu_itimer *it,
  759. u64 *expires, u64 cur_time, int signo)
  760. {
  761. if (!it->expires)
  762. return;
  763. if (cur_time >= it->expires) {
  764. if (it->incr)
  765. it->expires += it->incr;
  766. else
  767. it->expires = 0;
  768. trace_itimer_expire(signo == SIGPROF ?
  769. ITIMER_PROF : ITIMER_VIRTUAL,
  770. task_tgid(tsk), cur_time);
  771. __group_send_sig_info(signo, SEND_SIG_PRIV, tsk);
  772. }
  773. if (it->expires && it->expires < *expires)
  774. *expires = it->expires;
  775. }
  776. /*
  777. * Check for any per-thread CPU timers that have fired and move them
  778. * off the tsk->*_timers list onto the firing list. Per-thread timers
  779. * have already been taken off.
  780. */
  781. static void check_process_timers(struct task_struct *tsk,
  782. struct list_head *firing)
  783. {
  784. struct signal_struct *const sig = tsk->signal;
  785. struct posix_cputimers *pct = &sig->posix_cputimers;
  786. u64 samples[CPUCLOCK_MAX];
  787. unsigned long soft;
  788. /*
  789. * If there are no active process wide timers (POSIX 1.b, itimers,
  790. * RLIMIT_CPU) nothing to check. Also skip the process wide timer
  791. * processing when there is already another task handling them.
  792. */
  793. if (!READ_ONCE(pct->timers_active) || pct->expiry_active)
  794. return;
  795. /*
  796. * Signify that a thread is checking for process timers.
  797. * Write access to this field is protected by the sighand lock.
  798. */
  799. pct->expiry_active = true;
  800. /*
  801. * Collect the current process totals. Group accounting is active
  802. * so the sample can be taken directly.
  803. */
  804. proc_sample_cputime_atomic(&sig->cputimer.cputime_atomic, samples);
  805. collect_posix_cputimers(pct, samples, firing);
  806. /*
  807. * Check for the special case process timers.
  808. */
  809. check_cpu_itimer(tsk, &sig->it[CPUCLOCK_PROF],
  810. &pct->bases[CPUCLOCK_PROF].nextevt,
  811. samples[CPUCLOCK_PROF], SIGPROF);
  812. check_cpu_itimer(tsk, &sig->it[CPUCLOCK_VIRT],
  813. &pct->bases[CPUCLOCK_VIRT].nextevt,
  814. samples[CPUCLOCK_VIRT], SIGVTALRM);
  815. soft = task_rlimit(tsk, RLIMIT_CPU);
  816. if (soft != RLIM_INFINITY) {
  817. /* RLIMIT_CPU is in seconds. Samples are nanoseconds */
  818. unsigned long hard = task_rlimit_max(tsk, RLIMIT_CPU);
  819. u64 ptime = samples[CPUCLOCK_PROF];
  820. u64 softns = (u64)soft * NSEC_PER_SEC;
  821. u64 hardns = (u64)hard * NSEC_PER_SEC;
  822. /* At the hard limit, send SIGKILL. No further action. */
  823. if (hard != RLIM_INFINITY &&
  824. check_rlimit(ptime, hardns, SIGKILL, false, true))
  825. return;
  826. /* At the soft limit, send a SIGXCPU every second */
  827. if (check_rlimit(ptime, softns, SIGXCPU, false, false)) {
  828. sig->rlim[RLIMIT_CPU].rlim_cur = soft + 1;
  829. softns += NSEC_PER_SEC;
  830. }
  831. /* Update the expiry cache */
  832. if (softns < pct->bases[CPUCLOCK_PROF].nextevt)
  833. pct->bases[CPUCLOCK_PROF].nextevt = softns;
  834. }
  835. if (expiry_cache_is_inactive(pct))
  836. stop_process_timers(sig);
  837. pct->expiry_active = false;
  838. }
  839. /*
  840. * This is called from the signal code (via posixtimer_rearm)
  841. * when the last timer signal was delivered and we have to reload the timer.
  842. */
  843. static void posix_cpu_timer_rearm(struct k_itimer *timer)
  844. {
  845. clockid_t clkid = CPUCLOCK_WHICH(timer->it_clock);
  846. struct task_struct *p;
  847. struct sighand_struct *sighand;
  848. unsigned long flags;
  849. u64 now;
  850. rcu_read_lock();
  851. p = cpu_timer_task_rcu(timer);
  852. if (!p)
  853. goto out;
  854. /* Protect timer list r/w in arm_timer() */
  855. sighand = lock_task_sighand(p, &flags);
  856. if (unlikely(sighand == NULL))
  857. goto out;
  858. /*
  859. * Fetch the current sample and update the timer's expiry time.
  860. */
  861. if (CPUCLOCK_PERTHREAD(timer->it_clock))
  862. now = cpu_clock_sample(clkid, p);
  863. else
  864. now = cpu_clock_sample_group(clkid, p, true);
  865. bump_cpu_timer(timer, now);
  866. /*
  867. * Now re-arm for the new expiry time.
  868. */
  869. arm_timer(timer, p);
  870. unlock_task_sighand(p, &flags);
  871. out:
  872. rcu_read_unlock();
  873. }
  874. /**
  875. * task_cputimers_expired - Check whether posix CPU timers are expired
  876. *
  877. * @samples: Array of current samples for the CPUCLOCK clocks
  878. * @pct: Pointer to a posix_cputimers container
  879. *
  880. * Returns true if any member of @samples is greater than the corresponding
  881. * member of @pct->bases[CLK].nextevt. False otherwise
  882. */
  883. static inline bool
  884. task_cputimers_expired(const u64 *samples, struct posix_cputimers *pct)
  885. {
  886. int i;
  887. for (i = 0; i < CPUCLOCK_MAX; i++) {
  888. if (samples[i] >= pct->bases[i].nextevt)
  889. return true;
  890. }
  891. return false;
  892. }
  893. /**
  894. * fastpath_timer_check - POSIX CPU timers fast path.
  895. *
  896. * @tsk: The task (thread) being checked.
  897. *
  898. * Check the task and thread group timers. If both are zero (there are no
  899. * timers set) return false. Otherwise snapshot the task and thread group
  900. * timers and compare them with the corresponding expiration times. Return
  901. * true if a timer has expired, else return false.
  902. */
  903. static inline bool fastpath_timer_check(struct task_struct *tsk)
  904. {
  905. struct posix_cputimers *pct = &tsk->posix_cputimers;
  906. struct signal_struct *sig;
  907. if (!expiry_cache_is_inactive(pct)) {
  908. u64 samples[CPUCLOCK_MAX];
  909. task_sample_cputime(tsk, samples);
  910. if (task_cputimers_expired(samples, pct))
  911. return true;
  912. }
  913. sig = tsk->signal;
  914. pct = &sig->posix_cputimers;
  915. /*
  916. * Check if thread group timers expired when timers are active and
  917. * no other thread in the group is already handling expiry for
  918. * thread group cputimers. These fields are read without the
  919. * sighand lock. However, this is fine because this is meant to be
  920. * a fastpath heuristic to determine whether we should try to
  921. * acquire the sighand lock to handle timer expiry.
  922. *
  923. * In the worst case scenario, if concurrently timers_active is set
  924. * or expiry_active is cleared, but the current thread doesn't see
  925. * the change yet, the timer checks are delayed until the next
  926. * thread in the group gets a scheduler interrupt to handle the
  927. * timer. This isn't an issue in practice because these types of
  928. * delays with signals actually getting sent are expected.
  929. */
  930. if (READ_ONCE(pct->timers_active) && !READ_ONCE(pct->expiry_active)) {
  931. u64 samples[CPUCLOCK_MAX];
  932. proc_sample_cputime_atomic(&sig->cputimer.cputime_atomic,
  933. samples);
  934. if (task_cputimers_expired(samples, pct))
  935. return true;
  936. }
  937. if (dl_task(tsk) && tsk->dl.dl_overrun)
  938. return true;
  939. return false;
  940. }
  941. static void handle_posix_cpu_timers(struct task_struct *tsk);
  942. #ifdef CONFIG_POSIX_CPU_TIMERS_TASK_WORK
  943. static void posix_cpu_timers_work(struct callback_head *work)
  944. {
  945. handle_posix_cpu_timers(current);
  946. }
  947. /*
  948. * Clear existing posix CPU timers task work.
  949. */
  950. void clear_posix_cputimers_work(struct task_struct *p)
  951. {
  952. /*
  953. * A copied work entry from the old task is not meaningful, clear it.
  954. * N.B. init_task_work will not do this.
  955. */
  956. memset(&p->posix_cputimers_work.work, 0,
  957. sizeof(p->posix_cputimers_work.work));
  958. init_task_work(&p->posix_cputimers_work.work,
  959. posix_cpu_timers_work);
  960. p->posix_cputimers_work.scheduled = false;
  961. }
  962. /*
  963. * Initialize posix CPU timers task work in init task. Out of line to
  964. * keep the callback static and to avoid header recursion hell.
  965. */
  966. void __init posix_cputimers_init_work(void)
  967. {
  968. clear_posix_cputimers_work(current);
  969. }
  970. /*
  971. * Note: All operations on tsk->posix_cputimer_work.scheduled happen either
  972. * in hard interrupt context or in task context with interrupts
  973. * disabled. Aside of that the writer/reader interaction is always in the
  974. * context of the current task, which means they are strict per CPU.
  975. */
  976. static inline bool posix_cpu_timers_work_scheduled(struct task_struct *tsk)
  977. {
  978. return tsk->posix_cputimers_work.scheduled;
  979. }
  980. static inline void __run_posix_cpu_timers(struct task_struct *tsk)
  981. {
  982. if (WARN_ON_ONCE(tsk->posix_cputimers_work.scheduled))
  983. return;
  984. /* Schedule task work to actually expire the timers */
  985. tsk->posix_cputimers_work.scheduled = true;
  986. task_work_add(tsk, &tsk->posix_cputimers_work.work, TWA_RESUME);
  987. }
  988. static inline bool posix_cpu_timers_enable_work(struct task_struct *tsk,
  989. unsigned long start)
  990. {
  991. bool ret = true;
  992. /*
  993. * On !RT kernels interrupts are disabled while collecting expired
  994. * timers, so no tick can happen and the fast path check can be
  995. * reenabled without further checks.
  996. */
  997. if (!IS_ENABLED(CONFIG_PREEMPT_RT)) {
  998. tsk->posix_cputimers_work.scheduled = false;
  999. return true;
  1000. }
  1001. /*
  1002. * On RT enabled kernels ticks can happen while the expired timers
  1003. * are collected under sighand lock. But any tick which observes
  1004. * the CPUTIMERS_WORK_SCHEDULED bit set, does not run the fastpath
  1005. * checks. So reenabling the tick work has do be done carefully:
  1006. *
  1007. * Disable interrupts and run the fast path check if jiffies have
  1008. * advanced since the collecting of expired timers started. If
  1009. * jiffies have not advanced or the fast path check did not find
  1010. * newly expired timers, reenable the fast path check in the timer
  1011. * interrupt. If there are newly expired timers, return false and
  1012. * let the collection loop repeat.
  1013. */
  1014. local_irq_disable();
  1015. if (start != jiffies && fastpath_timer_check(tsk))
  1016. ret = false;
  1017. else
  1018. tsk->posix_cputimers_work.scheduled = false;
  1019. local_irq_enable();
  1020. return ret;
  1021. }
  1022. #else /* CONFIG_POSIX_CPU_TIMERS_TASK_WORK */
  1023. static inline void __run_posix_cpu_timers(struct task_struct *tsk)
  1024. {
  1025. lockdep_posixtimer_enter();
  1026. handle_posix_cpu_timers(tsk);
  1027. lockdep_posixtimer_exit();
  1028. }
  1029. static inline bool posix_cpu_timers_work_scheduled(struct task_struct *tsk)
  1030. {
  1031. return false;
  1032. }
  1033. static inline bool posix_cpu_timers_enable_work(struct task_struct *tsk,
  1034. unsigned long start)
  1035. {
  1036. return true;
  1037. }
  1038. #endif /* CONFIG_POSIX_CPU_TIMERS_TASK_WORK */
  1039. static void handle_posix_cpu_timers(struct task_struct *tsk)
  1040. {
  1041. struct k_itimer *timer, *next;
  1042. unsigned long flags, start;
  1043. LIST_HEAD(firing);
  1044. if (!lock_task_sighand(tsk, &flags))
  1045. return;
  1046. do {
  1047. /*
  1048. * On RT locking sighand lock does not disable interrupts,
  1049. * so this needs to be careful vs. ticks. Store the current
  1050. * jiffies value.
  1051. */
  1052. start = READ_ONCE(jiffies);
  1053. barrier();
  1054. /*
  1055. * Here we take off tsk->signal->cpu_timers[N] and
  1056. * tsk->cpu_timers[N] all the timers that are firing, and
  1057. * put them on the firing list.
  1058. */
  1059. check_thread_timers(tsk, &firing);
  1060. check_process_timers(tsk, &firing);
  1061. /*
  1062. * The above timer checks have updated the exipry cache and
  1063. * because nothing can have queued or modified timers after
  1064. * sighand lock was taken above it is guaranteed to be
  1065. * consistent. So the next timer interrupt fastpath check
  1066. * will find valid data.
  1067. *
  1068. * If timer expiry runs in the timer interrupt context then
  1069. * the loop is not relevant as timers will be directly
  1070. * expired in interrupt context. The stub function below
  1071. * returns always true which allows the compiler to
  1072. * optimize the loop out.
  1073. *
  1074. * If timer expiry is deferred to task work context then
  1075. * the following rules apply:
  1076. *
  1077. * - On !RT kernels no tick can have happened on this CPU
  1078. * after sighand lock was acquired because interrupts are
  1079. * disabled. So reenabling task work before dropping
  1080. * sighand lock and reenabling interrupts is race free.
  1081. *
  1082. * - On RT kernels ticks might have happened but the tick
  1083. * work ignored posix CPU timer handling because the
  1084. * CPUTIMERS_WORK_SCHEDULED bit is set. Reenabling work
  1085. * must be done very carefully including a check whether
  1086. * ticks have happened since the start of the timer
  1087. * expiry checks. posix_cpu_timers_enable_work() takes
  1088. * care of that and eventually lets the expiry checks
  1089. * run again.
  1090. */
  1091. } while (!posix_cpu_timers_enable_work(tsk, start));
  1092. /*
  1093. * We must release sighand lock before taking any timer's lock.
  1094. * There is a potential race with timer deletion here, as the
  1095. * siglock now protects our private firing list. We have set
  1096. * the firing flag in each timer, so that a deletion attempt
  1097. * that gets the timer lock before we do will give it up and
  1098. * spin until we've taken care of that timer below.
  1099. */
  1100. unlock_task_sighand(tsk, &flags);
  1101. /*
  1102. * Now that all the timers on our list have the firing flag,
  1103. * no one will touch their list entries but us. We'll take
  1104. * each timer's lock before clearing its firing flag, so no
  1105. * timer call will interfere.
  1106. */
  1107. list_for_each_entry_safe(timer, next, &firing, it.cpu.elist) {
  1108. int cpu_firing;
  1109. /*
  1110. * spin_lock() is sufficient here even independent of the
  1111. * expiry context. If expiry happens in hard interrupt
  1112. * context it's obvious. For task work context it's safe
  1113. * because all other operations on timer::it_lock happen in
  1114. * task context (syscall or exit).
  1115. */
  1116. spin_lock(&timer->it_lock);
  1117. list_del_init(&timer->it.cpu.elist);
  1118. cpu_firing = timer->it.cpu.firing;
  1119. timer->it.cpu.firing = 0;
  1120. /*
  1121. * The firing flag is -1 if we collided with a reset
  1122. * of the timer, which already reported this
  1123. * almost-firing as an overrun. So don't generate an event.
  1124. */
  1125. if (likely(cpu_firing >= 0))
  1126. cpu_timer_fire(timer);
  1127. spin_unlock(&timer->it_lock);
  1128. }
  1129. }
  1130. /*
  1131. * This is called from the timer interrupt handler. The irq handler has
  1132. * already updated our counts. We need to check if any timers fire now.
  1133. * Interrupts are disabled.
  1134. */
  1135. void run_posix_cpu_timers(void)
  1136. {
  1137. struct task_struct *tsk = current;
  1138. lockdep_assert_irqs_disabled();
  1139. /*
  1140. * If the actual expiry is deferred to task work context and the
  1141. * work is already scheduled there is no point to do anything here.
  1142. */
  1143. if (posix_cpu_timers_work_scheduled(tsk))
  1144. return;
  1145. /*
  1146. * The fast path checks that there are no expired thread or thread
  1147. * group timers. If that's so, just return.
  1148. */
  1149. if (!fastpath_timer_check(tsk))
  1150. return;
  1151. __run_posix_cpu_timers(tsk);
  1152. }
  1153. /*
  1154. * Set one of the process-wide special case CPU timers or RLIMIT_CPU.
  1155. * The tsk->sighand->siglock must be held by the caller.
  1156. */
  1157. void set_process_cpu_timer(struct task_struct *tsk, unsigned int clkid,
  1158. u64 *newval, u64 *oldval)
  1159. {
  1160. u64 now, *nextevt;
  1161. if (WARN_ON_ONCE(clkid >= CPUCLOCK_SCHED))
  1162. return;
  1163. nextevt = &tsk->signal->posix_cputimers.bases[clkid].nextevt;
  1164. now = cpu_clock_sample_group(clkid, tsk, true);
  1165. if (oldval) {
  1166. /*
  1167. * We are setting itimer. The *oldval is absolute and we update
  1168. * it to be relative, *newval argument is relative and we update
  1169. * it to be absolute.
  1170. */
  1171. if (*oldval) {
  1172. if (*oldval <= now) {
  1173. /* Just about to fire. */
  1174. *oldval = TICK_NSEC;
  1175. } else {
  1176. *oldval -= now;
  1177. }
  1178. }
  1179. if (!*newval)
  1180. return;
  1181. *newval += now;
  1182. }
  1183. /*
  1184. * Update expiration cache if this is the earliest timer. CPUCLOCK_PROF
  1185. * expiry cache is also used by RLIMIT_CPU!.
  1186. */
  1187. if (*newval < *nextevt)
  1188. *nextevt = *newval;
  1189. tick_dep_set_signal(tsk->signal, TICK_DEP_BIT_POSIX_TIMER);
  1190. }
  1191. static int do_cpu_nanosleep(const clockid_t which_clock, int flags,
  1192. const struct timespec64 *rqtp)
  1193. {
  1194. struct itimerspec64 it;
  1195. struct k_itimer timer;
  1196. u64 expires;
  1197. int error;
  1198. /*
  1199. * Set up a temporary timer and then wait for it to go off.
  1200. */
  1201. memset(&timer, 0, sizeof timer);
  1202. spin_lock_init(&timer.it_lock);
  1203. timer.it_clock = which_clock;
  1204. timer.it_overrun = -1;
  1205. error = posix_cpu_timer_create(&timer);
  1206. timer.it_process = current;
  1207. if (!error) {
  1208. static struct itimerspec64 zero_it;
  1209. struct restart_block *restart;
  1210. memset(&it, 0, sizeof(it));
  1211. it.it_value = *rqtp;
  1212. spin_lock_irq(&timer.it_lock);
  1213. error = posix_cpu_timer_set(&timer, flags, &it, NULL);
  1214. if (error) {
  1215. spin_unlock_irq(&timer.it_lock);
  1216. return error;
  1217. }
  1218. while (!signal_pending(current)) {
  1219. if (!cpu_timer_getexpires(&timer.it.cpu)) {
  1220. /*
  1221. * Our timer fired and was reset, below
  1222. * deletion can not fail.
  1223. */
  1224. posix_cpu_timer_del(&timer);
  1225. spin_unlock_irq(&timer.it_lock);
  1226. return 0;
  1227. }
  1228. /*
  1229. * Block until cpu_timer_fire (or a signal) wakes us.
  1230. */
  1231. __set_current_state(TASK_INTERRUPTIBLE);
  1232. spin_unlock_irq(&timer.it_lock);
  1233. schedule();
  1234. spin_lock_irq(&timer.it_lock);
  1235. }
  1236. /*
  1237. * We were interrupted by a signal.
  1238. */
  1239. expires = cpu_timer_getexpires(&timer.it.cpu);
  1240. error = posix_cpu_timer_set(&timer, 0, &zero_it, &it);
  1241. if (!error) {
  1242. /*
  1243. * Timer is now unarmed, deletion can not fail.
  1244. */
  1245. posix_cpu_timer_del(&timer);
  1246. }
  1247. spin_unlock_irq(&timer.it_lock);
  1248. while (error == TIMER_RETRY) {
  1249. /*
  1250. * We need to handle case when timer was or is in the
  1251. * middle of firing. In other cases we already freed
  1252. * resources.
  1253. */
  1254. spin_lock_irq(&timer.it_lock);
  1255. error = posix_cpu_timer_del(&timer);
  1256. spin_unlock_irq(&timer.it_lock);
  1257. }
  1258. if ((it.it_value.tv_sec | it.it_value.tv_nsec) == 0) {
  1259. /*
  1260. * It actually did fire already.
  1261. */
  1262. return 0;
  1263. }
  1264. error = -ERESTART_RESTARTBLOCK;
  1265. /*
  1266. * Report back to the user the time still remaining.
  1267. */
  1268. restart = &current->restart_block;
  1269. restart->nanosleep.expires = expires;
  1270. if (restart->nanosleep.type != TT_NONE)
  1271. error = nanosleep_copyout(restart, &it.it_value);
  1272. }
  1273. return error;
  1274. }
  1275. static long posix_cpu_nsleep_restart(struct restart_block *restart_block);
  1276. static int posix_cpu_nsleep(const clockid_t which_clock, int flags,
  1277. const struct timespec64 *rqtp)
  1278. {
  1279. struct restart_block *restart_block = &current->restart_block;
  1280. int error;
  1281. /*
  1282. * Diagnose required errors first.
  1283. */
  1284. if (CPUCLOCK_PERTHREAD(which_clock) &&
  1285. (CPUCLOCK_PID(which_clock) == 0 ||
  1286. CPUCLOCK_PID(which_clock) == task_pid_vnr(current)))
  1287. return -EINVAL;
  1288. error = do_cpu_nanosleep(which_clock, flags, rqtp);
  1289. if (error == -ERESTART_RESTARTBLOCK) {
  1290. if (flags & TIMER_ABSTIME)
  1291. return -ERESTARTNOHAND;
  1292. restart_block->nanosleep.clockid = which_clock;
  1293. set_restart_fn(restart_block, posix_cpu_nsleep_restart);
  1294. }
  1295. return error;
  1296. }
  1297. static long posix_cpu_nsleep_restart(struct restart_block *restart_block)
  1298. {
  1299. clockid_t which_clock = restart_block->nanosleep.clockid;
  1300. struct timespec64 t;
  1301. t = ns_to_timespec64(restart_block->nanosleep.expires);
  1302. return do_cpu_nanosleep(which_clock, TIMER_ABSTIME, &t);
  1303. }
  1304. #define PROCESS_CLOCK make_process_cpuclock(0, CPUCLOCK_SCHED)
  1305. #define THREAD_CLOCK make_thread_cpuclock(0, CPUCLOCK_SCHED)
  1306. static int process_cpu_clock_getres(const clockid_t which_clock,
  1307. struct timespec64 *tp)
  1308. {
  1309. return posix_cpu_clock_getres(PROCESS_CLOCK, tp);
  1310. }
  1311. static int process_cpu_clock_get(const clockid_t which_clock,
  1312. struct timespec64 *tp)
  1313. {
  1314. return posix_cpu_clock_get(PROCESS_CLOCK, tp);
  1315. }
  1316. static int process_cpu_timer_create(struct k_itimer *timer)
  1317. {
  1318. timer->it_clock = PROCESS_CLOCK;
  1319. return posix_cpu_timer_create(timer);
  1320. }
  1321. static int process_cpu_nsleep(const clockid_t which_clock, int flags,
  1322. const struct timespec64 *rqtp)
  1323. {
  1324. return posix_cpu_nsleep(PROCESS_CLOCK, flags, rqtp);
  1325. }
  1326. static int thread_cpu_clock_getres(const clockid_t which_clock,
  1327. struct timespec64 *tp)
  1328. {
  1329. return posix_cpu_clock_getres(THREAD_CLOCK, tp);
  1330. }
  1331. static int thread_cpu_clock_get(const clockid_t which_clock,
  1332. struct timespec64 *tp)
  1333. {
  1334. return posix_cpu_clock_get(THREAD_CLOCK, tp);
  1335. }
  1336. static int thread_cpu_timer_create(struct k_itimer *timer)
  1337. {
  1338. timer->it_clock = THREAD_CLOCK;
  1339. return posix_cpu_timer_create(timer);
  1340. }
  1341. const struct k_clock clock_posix_cpu = {
  1342. .clock_getres = posix_cpu_clock_getres,
  1343. .clock_set = posix_cpu_clock_set,
  1344. .clock_get_timespec = posix_cpu_clock_get,
  1345. .timer_create = posix_cpu_timer_create,
  1346. .nsleep = posix_cpu_nsleep,
  1347. .timer_set = posix_cpu_timer_set,
  1348. .timer_del = posix_cpu_timer_del,
  1349. .timer_get = posix_cpu_timer_get,
  1350. .timer_rearm = posix_cpu_timer_rearm,
  1351. };
  1352. const struct k_clock clock_process = {
  1353. .clock_getres = process_cpu_clock_getres,
  1354. .clock_get_timespec = process_cpu_clock_get,
  1355. .timer_create = process_cpu_timer_create,
  1356. .nsleep = process_cpu_nsleep,
  1357. };
  1358. const struct k_clock clock_thread = {
  1359. .clock_getres = thread_cpu_clock_getres,
  1360. .clock_get_timespec = thread_cpu_clock_get,
  1361. .timer_create = thread_cpu_timer_create,
  1362. };