posix-cpu-timers.c 46 KB

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