tick-sched.c 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright(C) 2005-2006, Thomas Gleixner <tglx@linutronix.de>
  4. * Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar
  5. * Copyright(C) 2006-2007 Timesys Corp., Thomas Gleixner
  6. *
  7. * NOHZ implementation for low and high resolution timers
  8. *
  9. * Started by: Thomas Gleixner and Ingo Molnar
  10. */
  11. #include <linux/compiler.h>
  12. #include <linux/cpu.h>
  13. #include <linux/err.h>
  14. #include <linux/hrtimer.h>
  15. #include <linux/interrupt.h>
  16. #include <linux/kernel_stat.h>
  17. #include <linux/percpu.h>
  18. #include <linux/nmi.h>
  19. #include <linux/profile.h>
  20. #include <linux/sched/signal.h>
  21. #include <linux/sched/clock.h>
  22. #include <linux/sched/stat.h>
  23. #include <linux/sched/nohz.h>
  24. #include <linux/sched/loadavg.h>
  25. #include <linux/module.h>
  26. #include <linux/irq_work.h>
  27. #include <linux/posix-timers.h>
  28. #include <linux/context_tracking.h>
  29. #include <linux/mm.h>
  30. #include <asm/irq_regs.h>
  31. #include "tick-internal.h"
  32. #include <trace/events/timer.h>
  33. /*
  34. * Per-CPU nohz control structure
  35. */
  36. static DEFINE_PER_CPU(struct tick_sched, tick_cpu_sched);
  37. struct tick_sched *tick_get_tick_sched(int cpu)
  38. {
  39. return &per_cpu(tick_cpu_sched, cpu);
  40. }
  41. /*
  42. * The time when the last jiffy update happened. Write access must hold
  43. * jiffies_lock and jiffies_seq. tick_nohz_next_event() needs to get a
  44. * consistent view of jiffies and last_jiffies_update.
  45. */
  46. static ktime_t last_jiffies_update;
  47. /*
  48. * Must be called with interrupts disabled !
  49. */
  50. static void tick_do_update_jiffies64(ktime_t now)
  51. {
  52. unsigned long ticks = 1;
  53. ktime_t delta, nextp;
  54. /*
  55. * 64-bit can do a quick check without holding the jiffies lock and
  56. * without looking at the sequence count. The smp_load_acquire()
  57. * pairs with the update done later in this function.
  58. *
  59. * 32-bit cannot do that because the store of 'tick_next_period'
  60. * consists of two 32-bit stores, and the first store could be
  61. * moved by the CPU to a random point in the future.
  62. */
  63. if (IS_ENABLED(CONFIG_64BIT)) {
  64. if (ktime_before(now, smp_load_acquire(&tick_next_period)))
  65. return;
  66. } else {
  67. unsigned int seq;
  68. /*
  69. * Avoid contention on 'jiffies_lock' and protect the quick
  70. * check with the sequence count.
  71. */
  72. do {
  73. seq = read_seqcount_begin(&jiffies_seq);
  74. nextp = tick_next_period;
  75. } while (read_seqcount_retry(&jiffies_seq, seq));
  76. if (ktime_before(now, nextp))
  77. return;
  78. }
  79. /* Quick check failed, i.e. update is required. */
  80. raw_spin_lock(&jiffies_lock);
  81. /*
  82. * Re-evaluate with the lock held. Another CPU might have done the
  83. * update already.
  84. */
  85. if (ktime_before(now, tick_next_period)) {
  86. raw_spin_unlock(&jiffies_lock);
  87. return;
  88. }
  89. write_seqcount_begin(&jiffies_seq);
  90. delta = ktime_sub(now, tick_next_period);
  91. if (unlikely(delta >= TICK_NSEC)) {
  92. /* Slow path for long idle sleep times */
  93. s64 incr = TICK_NSEC;
  94. ticks += ktime_divns(delta, incr);
  95. last_jiffies_update = ktime_add_ns(last_jiffies_update,
  96. incr * ticks);
  97. } else {
  98. last_jiffies_update = ktime_add_ns(last_jiffies_update,
  99. TICK_NSEC);
  100. }
  101. /* Advance jiffies to complete the 'jiffies_seq' protected job */
  102. jiffies_64 += ticks;
  103. /* Keep the tick_next_period variable up to date */
  104. nextp = ktime_add_ns(last_jiffies_update, TICK_NSEC);
  105. if (IS_ENABLED(CONFIG_64BIT)) {
  106. /*
  107. * Pairs with smp_load_acquire() in the lockless quick
  108. * check above, and ensures that the update to 'jiffies_64' is
  109. * not reordered vs. the store to 'tick_next_period', neither
  110. * by the compiler nor by the CPU.
  111. */
  112. smp_store_release(&tick_next_period, nextp);
  113. } else {
  114. /*
  115. * A plain store is good enough on 32-bit, as the quick check
  116. * above is protected by the sequence count.
  117. */
  118. tick_next_period = nextp;
  119. }
  120. /*
  121. * Release the sequence count. calc_global_load() below is not
  122. * protected by it, but 'jiffies_lock' needs to be held to prevent
  123. * concurrent invocations.
  124. */
  125. write_seqcount_end(&jiffies_seq);
  126. calc_global_load();
  127. raw_spin_unlock(&jiffies_lock);
  128. update_wall_time();
  129. }
  130. /*
  131. * Initialize and return retrieve the jiffies update.
  132. */
  133. static ktime_t tick_init_jiffy_update(void)
  134. {
  135. ktime_t period;
  136. raw_spin_lock(&jiffies_lock);
  137. write_seqcount_begin(&jiffies_seq);
  138. /* Have we started the jiffies update yet ? */
  139. if (last_jiffies_update == 0) {
  140. u32 rem;
  141. /*
  142. * Ensure that the tick is aligned to a multiple of
  143. * TICK_NSEC.
  144. */
  145. div_u64_rem(tick_next_period, TICK_NSEC, &rem);
  146. if (rem)
  147. tick_next_period += TICK_NSEC - rem;
  148. last_jiffies_update = tick_next_period;
  149. }
  150. period = last_jiffies_update;
  151. write_seqcount_end(&jiffies_seq);
  152. raw_spin_unlock(&jiffies_lock);
  153. return period;
  154. }
  155. static inline int tick_sched_flag_test(struct tick_sched *ts,
  156. unsigned long flag)
  157. {
  158. return !!(ts->flags & flag);
  159. }
  160. static inline void tick_sched_flag_set(struct tick_sched *ts,
  161. unsigned long flag)
  162. {
  163. lockdep_assert_irqs_disabled();
  164. ts->flags |= flag;
  165. }
  166. static inline void tick_sched_flag_clear(struct tick_sched *ts,
  167. unsigned long flag)
  168. {
  169. lockdep_assert_irqs_disabled();
  170. ts->flags &= ~flag;
  171. }
  172. #define MAX_STALLED_JIFFIES 5
  173. static void tick_sched_do_timer(struct tick_sched *ts, ktime_t now)
  174. {
  175. int tick_cpu, cpu = smp_processor_id();
  176. /*
  177. * Check if the do_timer duty was dropped. We don't care about
  178. * concurrency: This happens only when the CPU in charge went
  179. * into a long sleep. If two CPUs happen to assign themselves to
  180. * this duty, then the jiffies update is still serialized by
  181. * 'jiffies_lock'.
  182. *
  183. * If nohz_full is enabled, this should not happen because the
  184. * 'tick_do_timer_cpu' CPU never relinquishes.
  185. */
  186. tick_cpu = READ_ONCE(tick_do_timer_cpu);
  187. if (IS_ENABLED(CONFIG_NO_HZ_COMMON) && unlikely(tick_cpu == TICK_DO_TIMER_NONE)) {
  188. #ifdef CONFIG_NO_HZ_FULL
  189. WARN_ON_ONCE(tick_nohz_full_running);
  190. #endif
  191. WRITE_ONCE(tick_do_timer_cpu, cpu);
  192. tick_cpu = cpu;
  193. }
  194. /* Check if jiffies need an update */
  195. if (tick_cpu == cpu)
  196. tick_do_update_jiffies64(now);
  197. /*
  198. * If the jiffies update stalled for too long (timekeeper in stop_machine()
  199. * or VMEXIT'ed for several msecs), force an update.
  200. */
  201. if (ts->last_tick_jiffies != jiffies) {
  202. ts->stalled_jiffies = 0;
  203. ts->last_tick_jiffies = READ_ONCE(jiffies);
  204. } else {
  205. if (++ts->stalled_jiffies == MAX_STALLED_JIFFIES) {
  206. tick_do_update_jiffies64(now);
  207. ts->stalled_jiffies = 0;
  208. ts->last_tick_jiffies = READ_ONCE(jiffies);
  209. }
  210. }
  211. if (tick_sched_flag_test(ts, TS_FLAG_INIDLE))
  212. ts->got_idle_tick = 1;
  213. }
  214. static void tick_sched_handle(struct tick_sched *ts, struct pt_regs *regs)
  215. {
  216. /*
  217. * When we are idle and the tick is stopped, we have to touch
  218. * the watchdog as we might not schedule for a really long
  219. * time. This happens on completely idle SMP systems while
  220. * waiting on the login prompt. We also increment the "start of
  221. * idle" jiffy stamp so the idle accounting adjustment we do
  222. * when we go busy again does not account too many ticks.
  223. */
  224. if (IS_ENABLED(CONFIG_NO_HZ_COMMON) &&
  225. tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
  226. touch_softlockup_watchdog_sched();
  227. if (is_idle_task(current))
  228. ts->idle_jiffies++;
  229. /*
  230. * In case the current tick fired too early past its expected
  231. * expiration, make sure we don't bypass the next clock reprogramming
  232. * to the same deadline.
  233. */
  234. ts->next_tick = 0;
  235. }
  236. update_process_times(user_mode(regs));
  237. profile_tick(CPU_PROFILING);
  238. }
  239. /*
  240. * We rearm the timer until we get disabled by the idle code.
  241. * Called with interrupts disabled.
  242. */
  243. static enum hrtimer_restart tick_nohz_handler(struct hrtimer *timer)
  244. {
  245. struct tick_sched *ts = container_of(timer, struct tick_sched, sched_timer);
  246. struct pt_regs *regs = get_irq_regs();
  247. ktime_t now = ktime_get();
  248. tick_sched_do_timer(ts, now);
  249. /*
  250. * Do not call when we are not in IRQ context and have
  251. * no valid 'regs' pointer
  252. */
  253. if (regs)
  254. tick_sched_handle(ts, regs);
  255. else
  256. ts->next_tick = 0;
  257. /*
  258. * In dynticks mode, tick reprogram is deferred:
  259. * - to the idle task if in dynticks-idle
  260. * - to IRQ exit if in full-dynticks.
  261. */
  262. if (unlikely(tick_sched_flag_test(ts, TS_FLAG_STOPPED)))
  263. return HRTIMER_NORESTART;
  264. hrtimer_forward(timer, now, TICK_NSEC);
  265. return HRTIMER_RESTART;
  266. }
  267. static void tick_sched_timer_cancel(struct tick_sched *ts)
  268. {
  269. if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES))
  270. hrtimer_cancel(&ts->sched_timer);
  271. else if (tick_sched_flag_test(ts, TS_FLAG_NOHZ))
  272. tick_program_event(KTIME_MAX, 1);
  273. }
  274. #ifdef CONFIG_NO_HZ_FULL
  275. cpumask_var_t tick_nohz_full_mask;
  276. EXPORT_SYMBOL_GPL(tick_nohz_full_mask);
  277. bool tick_nohz_full_running;
  278. EXPORT_SYMBOL_GPL(tick_nohz_full_running);
  279. static atomic_t tick_dep_mask;
  280. static bool check_tick_dependency(atomic_t *dep)
  281. {
  282. int val = atomic_read(dep);
  283. if (val & TICK_DEP_MASK_POSIX_TIMER) {
  284. trace_tick_stop(0, TICK_DEP_MASK_POSIX_TIMER);
  285. return true;
  286. }
  287. if (val & TICK_DEP_MASK_PERF_EVENTS) {
  288. trace_tick_stop(0, TICK_DEP_MASK_PERF_EVENTS);
  289. return true;
  290. }
  291. if (val & TICK_DEP_MASK_SCHED) {
  292. trace_tick_stop(0, TICK_DEP_MASK_SCHED);
  293. return true;
  294. }
  295. if (val & TICK_DEP_MASK_CLOCK_UNSTABLE) {
  296. trace_tick_stop(0, TICK_DEP_MASK_CLOCK_UNSTABLE);
  297. return true;
  298. }
  299. if (val & TICK_DEP_MASK_RCU) {
  300. trace_tick_stop(0, TICK_DEP_MASK_RCU);
  301. return true;
  302. }
  303. if (val & TICK_DEP_MASK_RCU_EXP) {
  304. trace_tick_stop(0, TICK_DEP_MASK_RCU_EXP);
  305. return true;
  306. }
  307. return false;
  308. }
  309. static bool can_stop_full_tick(int cpu, struct tick_sched *ts)
  310. {
  311. lockdep_assert_irqs_disabled();
  312. if (unlikely(!cpu_online(cpu)))
  313. return false;
  314. if (check_tick_dependency(&tick_dep_mask))
  315. return false;
  316. if (check_tick_dependency(&ts->tick_dep_mask))
  317. return false;
  318. if (check_tick_dependency(&current->tick_dep_mask))
  319. return false;
  320. if (check_tick_dependency(&current->signal->tick_dep_mask))
  321. return false;
  322. return true;
  323. }
  324. static void nohz_full_kick_func(struct irq_work *work)
  325. {
  326. /* Empty, the tick restart happens on tick_nohz_irq_exit() */
  327. }
  328. static DEFINE_PER_CPU(struct irq_work, nohz_full_kick_work) =
  329. IRQ_WORK_INIT_HARD(nohz_full_kick_func);
  330. /*
  331. * Kick this CPU if it's full dynticks in order to force it to
  332. * re-evaluate its dependency on the tick and restart it if necessary.
  333. * This kick, unlike tick_nohz_full_kick_cpu() and tick_nohz_full_kick_all(),
  334. * is NMI safe.
  335. */
  336. static void tick_nohz_full_kick(void)
  337. {
  338. if (!tick_nohz_full_cpu(smp_processor_id()))
  339. return;
  340. irq_work_queue(this_cpu_ptr(&nohz_full_kick_work));
  341. }
  342. /*
  343. * Kick the CPU if it's full dynticks in order to force it to
  344. * re-evaluate its dependency on the tick and restart it if necessary.
  345. */
  346. void tick_nohz_full_kick_cpu(int cpu)
  347. {
  348. if (!tick_nohz_full_cpu(cpu))
  349. return;
  350. irq_work_queue_on(&per_cpu(nohz_full_kick_work, cpu), cpu);
  351. }
  352. static void tick_nohz_kick_task(struct task_struct *tsk)
  353. {
  354. int cpu;
  355. /*
  356. * If the task is not running, run_posix_cpu_timers()
  357. * has nothing to elapse, and an IPI can then be optimized out.
  358. *
  359. * activate_task() STORE p->tick_dep_mask
  360. * STORE p->on_rq
  361. * __schedule() (switch to task 'p') smp_mb() (atomic_fetch_or())
  362. * LOCK rq->lock LOAD p->on_rq
  363. * smp_mb__after_spin_lock()
  364. * tick_nohz_task_switch()
  365. * LOAD p->tick_dep_mask
  366. *
  367. * XXX given a task picks up the dependency on schedule(), should we
  368. * only care about tasks that are currently on the CPU instead of all
  369. * that are on the runqueue?
  370. *
  371. * That is, does this want to be: task_on_cpu() / task_curr()?
  372. */
  373. if (!sched_task_on_rq(tsk))
  374. return;
  375. /*
  376. * If the task concurrently migrates to another CPU,
  377. * we guarantee it sees the new tick dependency upon
  378. * schedule.
  379. *
  380. * set_task_cpu(p, cpu);
  381. * STORE p->cpu = @cpu
  382. * __schedule() (switch to task 'p')
  383. * LOCK rq->lock
  384. * smp_mb__after_spin_lock() STORE p->tick_dep_mask
  385. * tick_nohz_task_switch() smp_mb() (atomic_fetch_or())
  386. * LOAD p->tick_dep_mask LOAD p->cpu
  387. */
  388. cpu = task_cpu(tsk);
  389. preempt_disable();
  390. if (cpu_online(cpu))
  391. tick_nohz_full_kick_cpu(cpu);
  392. preempt_enable();
  393. }
  394. /*
  395. * Kick all full dynticks CPUs in order to force these to re-evaluate
  396. * their dependency on the tick and restart it if necessary.
  397. */
  398. static void tick_nohz_full_kick_all(void)
  399. {
  400. int cpu;
  401. if (!tick_nohz_full_running)
  402. return;
  403. preempt_disable();
  404. for_each_cpu_and(cpu, tick_nohz_full_mask, cpu_online_mask)
  405. tick_nohz_full_kick_cpu(cpu);
  406. preempt_enable();
  407. }
  408. static void tick_nohz_dep_set_all(atomic_t *dep,
  409. enum tick_dep_bits bit)
  410. {
  411. int prev;
  412. prev = atomic_fetch_or(BIT(bit), dep);
  413. if (!prev)
  414. tick_nohz_full_kick_all();
  415. }
  416. /*
  417. * Set a global tick dependency. Used by perf events that rely on freq and
  418. * unstable clocks.
  419. */
  420. void tick_nohz_dep_set(enum tick_dep_bits bit)
  421. {
  422. tick_nohz_dep_set_all(&tick_dep_mask, bit);
  423. }
  424. void tick_nohz_dep_clear(enum tick_dep_bits bit)
  425. {
  426. atomic_andnot(BIT(bit), &tick_dep_mask);
  427. }
  428. /*
  429. * Set per-CPU tick dependency. Used by scheduler and perf events in order to
  430. * manage event-throttling.
  431. */
  432. void tick_nohz_dep_set_cpu(int cpu, enum tick_dep_bits bit)
  433. {
  434. int prev;
  435. struct tick_sched *ts;
  436. ts = per_cpu_ptr(&tick_cpu_sched, cpu);
  437. prev = atomic_fetch_or(BIT(bit), &ts->tick_dep_mask);
  438. if (!prev) {
  439. preempt_disable();
  440. /* Perf needs local kick that is NMI safe */
  441. if (cpu == smp_processor_id()) {
  442. tick_nohz_full_kick();
  443. } else {
  444. /* Remote IRQ work not NMI-safe */
  445. if (!WARN_ON_ONCE(in_nmi()))
  446. tick_nohz_full_kick_cpu(cpu);
  447. }
  448. preempt_enable();
  449. }
  450. }
  451. EXPORT_SYMBOL_GPL(tick_nohz_dep_set_cpu);
  452. void tick_nohz_dep_clear_cpu(int cpu, enum tick_dep_bits bit)
  453. {
  454. struct tick_sched *ts = per_cpu_ptr(&tick_cpu_sched, cpu);
  455. atomic_andnot(BIT(bit), &ts->tick_dep_mask);
  456. }
  457. EXPORT_SYMBOL_GPL(tick_nohz_dep_clear_cpu);
  458. /*
  459. * Set a per-task tick dependency. RCU needs this. Also posix CPU timers
  460. * in order to elapse per task timers.
  461. */
  462. void tick_nohz_dep_set_task(struct task_struct *tsk, enum tick_dep_bits bit)
  463. {
  464. if (!atomic_fetch_or(BIT(bit), &tsk->tick_dep_mask))
  465. tick_nohz_kick_task(tsk);
  466. }
  467. EXPORT_SYMBOL_GPL(tick_nohz_dep_set_task);
  468. void tick_nohz_dep_clear_task(struct task_struct *tsk, enum tick_dep_bits bit)
  469. {
  470. atomic_andnot(BIT(bit), &tsk->tick_dep_mask);
  471. }
  472. EXPORT_SYMBOL_GPL(tick_nohz_dep_clear_task);
  473. /*
  474. * Set a per-taskgroup tick dependency. Posix CPU timers need this in order to elapse
  475. * per process timers.
  476. */
  477. void tick_nohz_dep_set_signal(struct task_struct *tsk,
  478. enum tick_dep_bits bit)
  479. {
  480. int prev;
  481. struct signal_struct *sig = tsk->signal;
  482. prev = atomic_fetch_or(BIT(bit), &sig->tick_dep_mask);
  483. if (!prev) {
  484. struct task_struct *t;
  485. lockdep_assert_held(&tsk->sighand->siglock);
  486. __for_each_thread(sig, t)
  487. tick_nohz_kick_task(t);
  488. }
  489. }
  490. void tick_nohz_dep_clear_signal(struct signal_struct *sig, enum tick_dep_bits bit)
  491. {
  492. atomic_andnot(BIT(bit), &sig->tick_dep_mask);
  493. }
  494. /*
  495. * Re-evaluate the need for the tick as we switch the current task.
  496. * It might need the tick due to per task/process properties:
  497. * perf events, posix CPU timers, ...
  498. */
  499. void __tick_nohz_task_switch(void)
  500. {
  501. struct tick_sched *ts;
  502. if (!tick_nohz_full_cpu(smp_processor_id()))
  503. return;
  504. ts = this_cpu_ptr(&tick_cpu_sched);
  505. if (tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
  506. if (atomic_read(&current->tick_dep_mask) ||
  507. atomic_read(&current->signal->tick_dep_mask))
  508. tick_nohz_full_kick();
  509. }
  510. }
  511. /* Get the boot-time nohz CPU list from the kernel parameters. */
  512. void __init tick_nohz_full_setup(cpumask_var_t cpumask)
  513. {
  514. alloc_bootmem_cpumask_var(&tick_nohz_full_mask);
  515. cpumask_copy(tick_nohz_full_mask, cpumask);
  516. tick_nohz_full_running = true;
  517. }
  518. bool tick_nohz_cpu_hotpluggable(unsigned int cpu)
  519. {
  520. /*
  521. * The 'tick_do_timer_cpu' CPU handles housekeeping duty (unbound
  522. * timers, workqueues, timekeeping, ...) on behalf of full dynticks
  523. * CPUs. It must remain online when nohz full is enabled.
  524. */
  525. if (tick_nohz_full_running && READ_ONCE(tick_do_timer_cpu) == cpu)
  526. return false;
  527. return true;
  528. }
  529. static int tick_nohz_cpu_down(unsigned int cpu)
  530. {
  531. return tick_nohz_cpu_hotpluggable(cpu) ? 0 : -EBUSY;
  532. }
  533. void __init tick_nohz_init(void)
  534. {
  535. int cpu, ret;
  536. if (!tick_nohz_full_running)
  537. return;
  538. /*
  539. * Full dynticks uses IRQ work to drive the tick rescheduling on safe
  540. * locking contexts. But then we need IRQ work to raise its own
  541. * interrupts to avoid circular dependency on the tick.
  542. */
  543. if (!arch_irq_work_has_interrupt()) {
  544. pr_warn("NO_HZ: Can't run full dynticks because arch doesn't support IRQ work self-IPIs\n");
  545. cpumask_clear(tick_nohz_full_mask);
  546. tick_nohz_full_running = false;
  547. return;
  548. }
  549. if (IS_ENABLED(CONFIG_PM_SLEEP_SMP) &&
  550. !IS_ENABLED(CONFIG_PM_SLEEP_SMP_NONZERO_CPU)) {
  551. cpu = smp_processor_id();
  552. if (cpumask_test_cpu(cpu, tick_nohz_full_mask)) {
  553. pr_warn("NO_HZ: Clearing %d from nohz_full range "
  554. "for timekeeping\n", cpu);
  555. cpumask_clear_cpu(cpu, tick_nohz_full_mask);
  556. }
  557. }
  558. for_each_cpu(cpu, tick_nohz_full_mask)
  559. ct_cpu_track_user(cpu);
  560. ret = cpuhp_setup_state_nocalls(CPUHP_AP_ONLINE_DYN,
  561. "kernel/nohz:predown", NULL,
  562. tick_nohz_cpu_down);
  563. WARN_ON(ret < 0);
  564. pr_info("NO_HZ: Full dynticks CPUs: %*pbl.\n",
  565. cpumask_pr_args(tick_nohz_full_mask));
  566. }
  567. #endif /* #ifdef CONFIG_NO_HZ_FULL */
  568. /*
  569. * NOHZ - aka dynamic tick functionality
  570. */
  571. #ifdef CONFIG_NO_HZ_COMMON
  572. /*
  573. * NO HZ enabled ?
  574. */
  575. bool tick_nohz_enabled __read_mostly = true;
  576. unsigned long tick_nohz_active __read_mostly;
  577. /*
  578. * Enable / Disable tickless mode
  579. */
  580. static int __init setup_tick_nohz(char *str)
  581. {
  582. return (kstrtobool(str, &tick_nohz_enabled) == 0);
  583. }
  584. __setup("nohz=", setup_tick_nohz);
  585. bool tick_nohz_tick_stopped(void)
  586. {
  587. struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
  588. return tick_sched_flag_test(ts, TS_FLAG_STOPPED);
  589. }
  590. bool tick_nohz_tick_stopped_cpu(int cpu)
  591. {
  592. struct tick_sched *ts = per_cpu_ptr(&tick_cpu_sched, cpu);
  593. return tick_sched_flag_test(ts, TS_FLAG_STOPPED);
  594. }
  595. /**
  596. * tick_nohz_update_jiffies - update jiffies when idle was interrupted
  597. * @now: current ktime_t
  598. *
  599. * Called from interrupt entry when the CPU was idle
  600. *
  601. * In case the sched_tick was stopped on this CPU, we have to check if jiffies
  602. * must be updated. Otherwise an interrupt handler could use a stale jiffy
  603. * value. We do this unconditionally on any CPU, as we don't know whether the
  604. * CPU, which has the update task assigned, is in a long sleep.
  605. */
  606. static void tick_nohz_update_jiffies(ktime_t now)
  607. {
  608. unsigned long flags;
  609. __this_cpu_write(tick_cpu_sched.idle_waketime, now);
  610. local_irq_save(flags);
  611. tick_do_update_jiffies64(now);
  612. local_irq_restore(flags);
  613. touch_softlockup_watchdog_sched();
  614. }
  615. static void tick_nohz_stop_idle(struct tick_sched *ts, ktime_t now)
  616. {
  617. ktime_t delta;
  618. if (WARN_ON_ONCE(!tick_sched_flag_test(ts, TS_FLAG_IDLE_ACTIVE)))
  619. return;
  620. delta = ktime_sub(now, ts->idle_entrytime);
  621. write_seqcount_begin(&ts->idle_sleeptime_seq);
  622. if (nr_iowait_cpu(smp_processor_id()) > 0)
  623. ts->iowait_sleeptime = ktime_add(ts->iowait_sleeptime, delta);
  624. else
  625. ts->idle_sleeptime = ktime_add(ts->idle_sleeptime, delta);
  626. ts->idle_entrytime = now;
  627. tick_sched_flag_clear(ts, TS_FLAG_IDLE_ACTIVE);
  628. write_seqcount_end(&ts->idle_sleeptime_seq);
  629. sched_clock_idle_wakeup_event();
  630. }
  631. static void tick_nohz_start_idle(struct tick_sched *ts)
  632. {
  633. write_seqcount_begin(&ts->idle_sleeptime_seq);
  634. ts->idle_entrytime = ktime_get();
  635. tick_sched_flag_set(ts, TS_FLAG_IDLE_ACTIVE);
  636. write_seqcount_end(&ts->idle_sleeptime_seq);
  637. sched_clock_idle_sleep_event();
  638. }
  639. static u64 get_cpu_sleep_time_us(struct tick_sched *ts, ktime_t *sleeptime,
  640. bool compute_delta, u64 *last_update_time)
  641. {
  642. ktime_t now, idle;
  643. unsigned int seq;
  644. if (!tick_nohz_active)
  645. return -1;
  646. now = ktime_get();
  647. if (last_update_time)
  648. *last_update_time = ktime_to_us(now);
  649. do {
  650. seq = read_seqcount_begin(&ts->idle_sleeptime_seq);
  651. if (tick_sched_flag_test(ts, TS_FLAG_IDLE_ACTIVE) && compute_delta) {
  652. ktime_t delta = ktime_sub(now, ts->idle_entrytime);
  653. idle = ktime_add(*sleeptime, delta);
  654. } else {
  655. idle = *sleeptime;
  656. }
  657. } while (read_seqcount_retry(&ts->idle_sleeptime_seq, seq));
  658. return ktime_to_us(idle);
  659. }
  660. /**
  661. * get_cpu_idle_time_us - get the total idle time of a CPU
  662. * @cpu: CPU number to query
  663. * @last_update_time: variable to store update time in. Do not update
  664. * counters if NULL.
  665. *
  666. * Return the cumulative idle time (since boot) for a given
  667. * CPU, in microseconds. Note that this is partially broken due to
  668. * the counter of iowait tasks that can be remotely updated without
  669. * any synchronization. Therefore it is possible to observe backward
  670. * values within two consecutive reads.
  671. *
  672. * This time is measured via accounting rather than sampling,
  673. * and is as accurate as ktime_get() is.
  674. *
  675. * Return: -1 if NOHZ is not enabled, else total idle time of the @cpu
  676. */
  677. u64 get_cpu_idle_time_us(int cpu, u64 *last_update_time)
  678. {
  679. struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
  680. return get_cpu_sleep_time_us(ts, &ts->idle_sleeptime,
  681. !nr_iowait_cpu(cpu), last_update_time);
  682. }
  683. EXPORT_SYMBOL_GPL(get_cpu_idle_time_us);
  684. /**
  685. * get_cpu_iowait_time_us - get the total iowait time of a CPU
  686. * @cpu: CPU number to query
  687. * @last_update_time: variable to store update time in. Do not update
  688. * counters if NULL.
  689. *
  690. * Return the cumulative iowait time (since boot) for a given
  691. * CPU, in microseconds. Note this is partially broken due to
  692. * the counter of iowait tasks that can be remotely updated without
  693. * any synchronization. Therefore it is possible to observe backward
  694. * values within two consecutive reads.
  695. *
  696. * This time is measured via accounting rather than sampling,
  697. * and is as accurate as ktime_get() is.
  698. *
  699. * Return: -1 if NOHZ is not enabled, else total iowait time of @cpu
  700. */
  701. u64 get_cpu_iowait_time_us(int cpu, u64 *last_update_time)
  702. {
  703. struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
  704. return get_cpu_sleep_time_us(ts, &ts->iowait_sleeptime,
  705. nr_iowait_cpu(cpu), last_update_time);
  706. }
  707. EXPORT_SYMBOL_GPL(get_cpu_iowait_time_us);
  708. static void tick_nohz_restart(struct tick_sched *ts, ktime_t now)
  709. {
  710. hrtimer_cancel(&ts->sched_timer);
  711. hrtimer_set_expires(&ts->sched_timer, ts->last_tick);
  712. /* Forward the time to expire in the future */
  713. hrtimer_forward(&ts->sched_timer, now, TICK_NSEC);
  714. if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES)) {
  715. hrtimer_start_expires(&ts->sched_timer,
  716. HRTIMER_MODE_ABS_PINNED_HARD);
  717. } else {
  718. tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
  719. }
  720. /*
  721. * Reset to make sure the next tick stop doesn't get fooled by past
  722. * cached clock deadline.
  723. */
  724. ts->next_tick = 0;
  725. }
  726. static inline bool local_timer_softirq_pending(void)
  727. {
  728. return local_softirq_pending() & BIT(TIMER_SOFTIRQ);
  729. }
  730. /*
  731. * Read jiffies and the time when jiffies were updated last
  732. */
  733. u64 get_jiffies_update(unsigned long *basej)
  734. {
  735. unsigned long basejiff;
  736. unsigned int seq;
  737. u64 basemono;
  738. do {
  739. seq = read_seqcount_begin(&jiffies_seq);
  740. basemono = last_jiffies_update;
  741. basejiff = jiffies;
  742. } while (read_seqcount_retry(&jiffies_seq, seq));
  743. *basej = basejiff;
  744. return basemono;
  745. }
  746. /**
  747. * tick_nohz_next_event() - return the clock monotonic based next event
  748. * @ts: pointer to tick_sched struct
  749. * @cpu: CPU number
  750. *
  751. * Return:
  752. * *%0 - When the next event is a maximum of TICK_NSEC in the future
  753. * and the tick is not stopped yet
  754. * *%next_event - Next event based on clock monotonic
  755. */
  756. static ktime_t tick_nohz_next_event(struct tick_sched *ts, int cpu)
  757. {
  758. u64 basemono, next_tick, delta, expires;
  759. unsigned long basejiff;
  760. int tick_cpu;
  761. basemono = get_jiffies_update(&basejiff);
  762. ts->last_jiffies = basejiff;
  763. ts->timer_expires_base = basemono;
  764. /*
  765. * Keep the periodic tick, when RCU, architecture or irq_work
  766. * requests it.
  767. * Aside of that, check whether the local timer softirq is
  768. * pending. If so, its a bad idea to call get_next_timer_interrupt(),
  769. * because there is an already expired timer, so it will request
  770. * immediate expiry, which rearms the hardware timer with a
  771. * minimal delta, which brings us back to this place
  772. * immediately. Lather, rinse and repeat...
  773. */
  774. if (rcu_needs_cpu() || arch_needs_cpu() ||
  775. irq_work_needs_cpu() || local_timer_softirq_pending()) {
  776. next_tick = basemono + TICK_NSEC;
  777. } else {
  778. /*
  779. * Get the next pending timer. If high resolution
  780. * timers are enabled this only takes the timer wheel
  781. * timers into account. If high resolution timers are
  782. * disabled this also looks at the next expiring
  783. * hrtimer.
  784. */
  785. next_tick = get_next_timer_interrupt(basejiff, basemono);
  786. ts->next_timer = next_tick;
  787. }
  788. /* Make sure next_tick is never before basemono! */
  789. if (WARN_ON_ONCE(basemono > next_tick))
  790. next_tick = basemono;
  791. /*
  792. * If the tick is due in the next period, keep it ticking or
  793. * force prod the timer.
  794. */
  795. delta = next_tick - basemono;
  796. if (delta <= (u64)TICK_NSEC) {
  797. /*
  798. * We've not stopped the tick yet, and there's a timer in the
  799. * next period, so no point in stopping it either, bail.
  800. */
  801. if (!tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
  802. ts->timer_expires = 0;
  803. goto out;
  804. }
  805. }
  806. /*
  807. * If this CPU is the one which had the do_timer() duty last, we limit
  808. * the sleep time to the timekeeping 'max_deferment' value.
  809. * Otherwise we can sleep as long as we want.
  810. */
  811. delta = timekeeping_max_deferment();
  812. tick_cpu = READ_ONCE(tick_do_timer_cpu);
  813. if (tick_cpu != cpu &&
  814. (tick_cpu != TICK_DO_TIMER_NONE || !tick_sched_flag_test(ts, TS_FLAG_DO_TIMER_LAST)))
  815. delta = KTIME_MAX;
  816. /* Calculate the next expiry time */
  817. if (delta < (KTIME_MAX - basemono))
  818. expires = basemono + delta;
  819. else
  820. expires = KTIME_MAX;
  821. ts->timer_expires = min_t(u64, expires, next_tick);
  822. out:
  823. return ts->timer_expires;
  824. }
  825. static void tick_nohz_stop_tick(struct tick_sched *ts, int cpu)
  826. {
  827. struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
  828. unsigned long basejiff = ts->last_jiffies;
  829. u64 basemono = ts->timer_expires_base;
  830. bool timer_idle = tick_sched_flag_test(ts, TS_FLAG_STOPPED);
  831. int tick_cpu;
  832. u64 expires;
  833. /* Make sure we won't be trying to stop it twice in a row. */
  834. ts->timer_expires_base = 0;
  835. /*
  836. * Now the tick should be stopped definitely - so the timer base needs
  837. * to be marked idle as well to not miss a newly queued timer.
  838. */
  839. expires = timer_base_try_to_set_idle(basejiff, basemono, &timer_idle);
  840. if (expires > ts->timer_expires) {
  841. /*
  842. * This path could only happen when the first timer was removed
  843. * between calculating the possible sleep length and now (when
  844. * high resolution mode is not active, timer could also be a
  845. * hrtimer).
  846. *
  847. * We have to stick to the original calculated expiry value to
  848. * not stop the tick for too long with a shallow C-state (which
  849. * was programmed by cpuidle because of an early next expiration
  850. * value).
  851. */
  852. expires = ts->timer_expires;
  853. }
  854. /* If the timer base is not idle, retain the not yet stopped tick. */
  855. if (!timer_idle)
  856. return;
  857. /*
  858. * If this CPU is the one which updates jiffies, then give up
  859. * the assignment and let it be taken by the CPU which runs
  860. * the tick timer next, which might be this CPU as well. If we
  861. * don't drop this here, the jiffies might be stale and
  862. * do_timer() never gets invoked. Keep track of the fact that it
  863. * was the one which had the do_timer() duty last.
  864. */
  865. tick_cpu = READ_ONCE(tick_do_timer_cpu);
  866. if (tick_cpu == cpu) {
  867. WRITE_ONCE(tick_do_timer_cpu, TICK_DO_TIMER_NONE);
  868. tick_sched_flag_set(ts, TS_FLAG_DO_TIMER_LAST);
  869. } else if (tick_cpu != TICK_DO_TIMER_NONE) {
  870. tick_sched_flag_clear(ts, TS_FLAG_DO_TIMER_LAST);
  871. }
  872. /* Skip reprogram of event if it's not changed */
  873. if (tick_sched_flag_test(ts, TS_FLAG_STOPPED) && (expires == ts->next_tick)) {
  874. /* Sanity check: make sure clockevent is actually programmed */
  875. if (expires == KTIME_MAX || ts->next_tick == hrtimer_get_expires(&ts->sched_timer))
  876. return;
  877. WARN_ONCE(1, "basemono: %llu ts->next_tick: %llu dev->next_event: %llu "
  878. "timer->active: %d timer->expires: %llu\n", basemono, ts->next_tick,
  879. dev->next_event, hrtimer_active(&ts->sched_timer),
  880. hrtimer_get_expires(&ts->sched_timer));
  881. }
  882. /*
  883. * tick_nohz_stop_tick() can be called several times before
  884. * tick_nohz_restart_sched_tick() is called. This happens when
  885. * interrupts arrive which do not cause a reschedule. In the first
  886. * call we save the current tick time, so we can restart the
  887. * scheduler tick in tick_nohz_restart_sched_tick().
  888. */
  889. if (!tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
  890. calc_load_nohz_start();
  891. quiet_vmstat();
  892. ts->last_tick = hrtimer_get_expires(&ts->sched_timer);
  893. tick_sched_flag_set(ts, TS_FLAG_STOPPED);
  894. trace_tick_stop(1, TICK_DEP_MASK_NONE);
  895. }
  896. ts->next_tick = expires;
  897. /*
  898. * If the expiration time == KTIME_MAX, then we simply stop
  899. * the tick timer.
  900. */
  901. if (unlikely(expires == KTIME_MAX)) {
  902. tick_sched_timer_cancel(ts);
  903. return;
  904. }
  905. if (tick_sched_flag_test(ts, TS_FLAG_HIGHRES)) {
  906. hrtimer_start(&ts->sched_timer, expires,
  907. HRTIMER_MODE_ABS_PINNED_HARD);
  908. } else {
  909. hrtimer_set_expires(&ts->sched_timer, expires);
  910. tick_program_event(expires, 1);
  911. }
  912. }
  913. static void tick_nohz_retain_tick(struct tick_sched *ts)
  914. {
  915. ts->timer_expires_base = 0;
  916. }
  917. #ifdef CONFIG_NO_HZ_FULL
  918. static void tick_nohz_full_stop_tick(struct tick_sched *ts, int cpu)
  919. {
  920. if (tick_nohz_next_event(ts, cpu))
  921. tick_nohz_stop_tick(ts, cpu);
  922. else
  923. tick_nohz_retain_tick(ts);
  924. }
  925. #endif /* CONFIG_NO_HZ_FULL */
  926. static void tick_nohz_restart_sched_tick(struct tick_sched *ts, ktime_t now)
  927. {
  928. /* Update jiffies first */
  929. tick_do_update_jiffies64(now);
  930. /*
  931. * Clear the timer idle flag, so we avoid IPIs on remote queueing and
  932. * the clock forward checks in the enqueue path:
  933. */
  934. timer_clear_idle();
  935. calc_load_nohz_stop();
  936. touch_softlockup_watchdog_sched();
  937. /* Cancel the scheduled timer and restore the tick: */
  938. tick_sched_flag_clear(ts, TS_FLAG_STOPPED);
  939. tick_nohz_restart(ts, now);
  940. }
  941. static void __tick_nohz_full_update_tick(struct tick_sched *ts,
  942. ktime_t now)
  943. {
  944. #ifdef CONFIG_NO_HZ_FULL
  945. int cpu = smp_processor_id();
  946. if (can_stop_full_tick(cpu, ts))
  947. tick_nohz_full_stop_tick(ts, cpu);
  948. else if (tick_sched_flag_test(ts, TS_FLAG_STOPPED))
  949. tick_nohz_restart_sched_tick(ts, now);
  950. #endif
  951. }
  952. static void tick_nohz_full_update_tick(struct tick_sched *ts)
  953. {
  954. if (!tick_nohz_full_cpu(smp_processor_id()))
  955. return;
  956. if (!tick_sched_flag_test(ts, TS_FLAG_NOHZ))
  957. return;
  958. __tick_nohz_full_update_tick(ts, ktime_get());
  959. }
  960. /*
  961. * A pending softirq outside an IRQ (or softirq disabled section) context
  962. * should be waiting for ksoftirqd to handle it. Therefore we shouldn't
  963. * reach this code due to the need_resched() early check in can_stop_idle_tick().
  964. *
  965. * However if we are between CPUHP_AP_SMPBOOT_THREADS and CPU_TEARDOWN_CPU on the
  966. * cpu_down() process, softirqs can still be raised while ksoftirqd is parked,
  967. * triggering the code below, since wakep_softirqd() is ignored.
  968. *
  969. */
  970. static bool report_idle_softirq(void)
  971. {
  972. static int ratelimit;
  973. unsigned int pending = local_softirq_pending();
  974. if (likely(!pending))
  975. return false;
  976. /* Some softirqs claim to be safe against hotplug and ksoftirqd parking */
  977. if (!cpu_active(smp_processor_id())) {
  978. pending &= ~SOFTIRQ_HOTPLUG_SAFE_MASK;
  979. if (!pending)
  980. return false;
  981. }
  982. if (ratelimit >= 10)
  983. return false;
  984. /* On RT, softirq handling may be waiting on some lock */
  985. if (local_bh_blocked())
  986. return false;
  987. pr_warn("NOHZ tick-stop error: local softirq work is pending, handler #%02x!!!\n",
  988. pending);
  989. ratelimit++;
  990. return true;
  991. }
  992. static bool can_stop_idle_tick(int cpu, struct tick_sched *ts)
  993. {
  994. WARN_ON_ONCE(cpu_is_offline(cpu));
  995. if (unlikely(!tick_sched_flag_test(ts, TS_FLAG_NOHZ)))
  996. return false;
  997. if (need_resched())
  998. return false;
  999. if (unlikely(report_idle_softirq()))
  1000. return false;
  1001. if (tick_nohz_full_enabled()) {
  1002. int tick_cpu = READ_ONCE(tick_do_timer_cpu);
  1003. /*
  1004. * Keep the tick alive to guarantee timekeeping progression
  1005. * if there are full dynticks CPUs around
  1006. */
  1007. if (tick_cpu == cpu)
  1008. return false;
  1009. /* Should not happen for nohz-full */
  1010. if (WARN_ON_ONCE(tick_cpu == TICK_DO_TIMER_NONE))
  1011. return false;
  1012. }
  1013. return true;
  1014. }
  1015. /**
  1016. * tick_nohz_idle_stop_tick - stop the idle tick from the idle task
  1017. *
  1018. * When the next event is more than a tick into the future, stop the idle tick
  1019. */
  1020. void tick_nohz_idle_stop_tick(void)
  1021. {
  1022. struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
  1023. int cpu = smp_processor_id();
  1024. ktime_t expires;
  1025. /*
  1026. * If tick_nohz_get_sleep_length() ran tick_nohz_next_event(), the
  1027. * tick timer expiration time is known already.
  1028. */
  1029. if (ts->timer_expires_base)
  1030. expires = ts->timer_expires;
  1031. else if (can_stop_idle_tick(cpu, ts))
  1032. expires = tick_nohz_next_event(ts, cpu);
  1033. else
  1034. return;
  1035. ts->idle_calls++;
  1036. if (expires > 0LL) {
  1037. int was_stopped = tick_sched_flag_test(ts, TS_FLAG_STOPPED);
  1038. tick_nohz_stop_tick(ts, cpu);
  1039. ts->idle_sleeps++;
  1040. ts->idle_expires = expires;
  1041. if (!was_stopped && tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
  1042. ts->idle_jiffies = ts->last_jiffies;
  1043. nohz_balance_enter_idle(cpu);
  1044. }
  1045. } else {
  1046. tick_nohz_retain_tick(ts);
  1047. }
  1048. }
  1049. void tick_nohz_idle_retain_tick(void)
  1050. {
  1051. tick_nohz_retain_tick(this_cpu_ptr(&tick_cpu_sched));
  1052. }
  1053. /**
  1054. * tick_nohz_idle_enter - prepare for entering idle on the current CPU
  1055. *
  1056. * Called when we start the idle loop.
  1057. */
  1058. void tick_nohz_idle_enter(void)
  1059. {
  1060. struct tick_sched *ts;
  1061. lockdep_assert_irqs_enabled();
  1062. local_irq_disable();
  1063. ts = this_cpu_ptr(&tick_cpu_sched);
  1064. WARN_ON_ONCE(ts->timer_expires_base);
  1065. tick_sched_flag_set(ts, TS_FLAG_INIDLE);
  1066. tick_nohz_start_idle(ts);
  1067. local_irq_enable();
  1068. }
  1069. /**
  1070. * tick_nohz_irq_exit - Notify the tick about IRQ exit
  1071. *
  1072. * A timer may have been added/modified/deleted either by the current IRQ,
  1073. * or by another place using this IRQ as a notification. This IRQ may have
  1074. * also updated the RCU callback list. These events may require a
  1075. * re-evaluation of the next tick. Depending on the context:
  1076. *
  1077. * 1) If the CPU is idle and no resched is pending, just proceed with idle
  1078. * time accounting. The next tick will be re-evaluated on the next idle
  1079. * loop iteration.
  1080. *
  1081. * 2) If the CPU is nohz_full:
  1082. *
  1083. * 2.1) If there is any tick dependency, restart the tick if stopped.
  1084. *
  1085. * 2.2) If there is no tick dependency, (re-)evaluate the next tick and
  1086. * stop/update it accordingly.
  1087. */
  1088. void tick_nohz_irq_exit(void)
  1089. {
  1090. struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
  1091. if (tick_sched_flag_test(ts, TS_FLAG_INIDLE))
  1092. tick_nohz_start_idle(ts);
  1093. else
  1094. tick_nohz_full_update_tick(ts);
  1095. }
  1096. /**
  1097. * tick_nohz_idle_got_tick - Check whether or not the tick handler has run
  1098. *
  1099. * Return: %true if the tick handler has run, otherwise %false
  1100. */
  1101. bool tick_nohz_idle_got_tick(void)
  1102. {
  1103. struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
  1104. if (ts->got_idle_tick) {
  1105. ts->got_idle_tick = 0;
  1106. return true;
  1107. }
  1108. return false;
  1109. }
  1110. /**
  1111. * tick_nohz_get_next_hrtimer - return the next expiration time for the hrtimer
  1112. * or the tick, whichever expires first. Note that, if the tick has been
  1113. * stopped, it returns the next hrtimer.
  1114. *
  1115. * Called from power state control code with interrupts disabled
  1116. *
  1117. * Return: the next expiration time
  1118. */
  1119. ktime_t tick_nohz_get_next_hrtimer(void)
  1120. {
  1121. return __this_cpu_read(tick_cpu_device.evtdev)->next_event;
  1122. }
  1123. /**
  1124. * tick_nohz_get_sleep_length - return the expected length of the current sleep
  1125. * @delta_next: duration until the next event if the tick cannot be stopped
  1126. *
  1127. * Called from power state control code with interrupts disabled.
  1128. *
  1129. * The return value of this function and/or the value returned by it through the
  1130. * @delta_next pointer can be negative which must be taken into account by its
  1131. * callers.
  1132. *
  1133. * Return: the expected length of the current sleep
  1134. */
  1135. ktime_t tick_nohz_get_sleep_length(ktime_t *delta_next)
  1136. {
  1137. struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
  1138. struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
  1139. int cpu = smp_processor_id();
  1140. /*
  1141. * The idle entry time is expected to be a sufficient approximation of
  1142. * the current time at this point.
  1143. */
  1144. ktime_t now = ts->idle_entrytime;
  1145. ktime_t next_event;
  1146. WARN_ON_ONCE(!tick_sched_flag_test(ts, TS_FLAG_INIDLE));
  1147. *delta_next = ktime_sub(dev->next_event, now);
  1148. if (!can_stop_idle_tick(cpu, ts))
  1149. return *delta_next;
  1150. next_event = tick_nohz_next_event(ts, cpu);
  1151. if (!next_event)
  1152. return *delta_next;
  1153. /*
  1154. * If the next highres timer to expire is earlier than 'next_event', the
  1155. * idle governor needs to know that.
  1156. */
  1157. next_event = min_t(u64, next_event,
  1158. hrtimer_next_event_without(&ts->sched_timer));
  1159. return ktime_sub(next_event, now);
  1160. }
  1161. /**
  1162. * tick_nohz_get_idle_calls_cpu - return the current idle calls counter value
  1163. * for a particular CPU.
  1164. * @cpu: target CPU number
  1165. *
  1166. * Called from the schedutil frequency scaling governor in scheduler context.
  1167. *
  1168. * Return: the current idle calls counter value for @cpu
  1169. */
  1170. unsigned long tick_nohz_get_idle_calls_cpu(int cpu)
  1171. {
  1172. struct tick_sched *ts = tick_get_tick_sched(cpu);
  1173. return ts->idle_calls;
  1174. }
  1175. static void tick_nohz_account_idle_time(struct tick_sched *ts,
  1176. ktime_t now)
  1177. {
  1178. unsigned long ticks;
  1179. ts->idle_exittime = now;
  1180. if (vtime_accounting_enabled_this_cpu())
  1181. return;
  1182. /*
  1183. * We stopped the tick in idle. update_process_times() would miss the
  1184. * time we slept, as it does only a 1 tick accounting.
  1185. * Enforce that this is accounted to idle !
  1186. */
  1187. ticks = jiffies - ts->idle_jiffies;
  1188. /*
  1189. * We might be one off. Do not randomly account a huge number of ticks!
  1190. */
  1191. if (ticks && ticks < LONG_MAX)
  1192. account_idle_ticks(ticks);
  1193. }
  1194. void tick_nohz_idle_restart_tick(void)
  1195. {
  1196. struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
  1197. if (tick_sched_flag_test(ts, TS_FLAG_STOPPED)) {
  1198. ktime_t now = ktime_get();
  1199. tick_nohz_restart_sched_tick(ts, now);
  1200. tick_nohz_account_idle_time(ts, now);
  1201. }
  1202. }
  1203. static void tick_nohz_idle_update_tick(struct tick_sched *ts, ktime_t now)
  1204. {
  1205. if (tick_nohz_full_cpu(smp_processor_id()))
  1206. __tick_nohz_full_update_tick(ts, now);
  1207. else
  1208. tick_nohz_restart_sched_tick(ts, now);
  1209. tick_nohz_account_idle_time(ts, now);
  1210. }
  1211. /**
  1212. * tick_nohz_idle_exit - Update the tick upon idle task exit
  1213. *
  1214. * When the idle task exits, update the tick depending on the
  1215. * following situations:
  1216. *
  1217. * 1) If the CPU is not in nohz_full mode (most cases), then
  1218. * restart the tick.
  1219. *
  1220. * 2) If the CPU is in nohz_full mode (corner case):
  1221. * 2.1) If the tick can be kept stopped (no tick dependencies)
  1222. * then re-evaluate the next tick and try to keep it stopped
  1223. * as long as possible.
  1224. * 2.2) If the tick has dependencies, restart the tick.
  1225. *
  1226. */
  1227. void tick_nohz_idle_exit(void)
  1228. {
  1229. struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
  1230. bool idle_active, tick_stopped;
  1231. ktime_t now;
  1232. local_irq_disable();
  1233. WARN_ON_ONCE(!tick_sched_flag_test(ts, TS_FLAG_INIDLE));
  1234. WARN_ON_ONCE(ts->timer_expires_base);
  1235. tick_sched_flag_clear(ts, TS_FLAG_INIDLE);
  1236. idle_active = tick_sched_flag_test(ts, TS_FLAG_IDLE_ACTIVE);
  1237. tick_stopped = tick_sched_flag_test(ts, TS_FLAG_STOPPED);
  1238. if (idle_active || tick_stopped)
  1239. now = ktime_get();
  1240. if (idle_active)
  1241. tick_nohz_stop_idle(ts, now);
  1242. if (tick_stopped)
  1243. tick_nohz_idle_update_tick(ts, now);
  1244. local_irq_enable();
  1245. }
  1246. /*
  1247. * In low-resolution mode, the tick handler must be implemented directly
  1248. * at the clockevent level. hrtimer can't be used instead, because its
  1249. * infrastructure actually relies on the tick itself as a backend in
  1250. * low-resolution mode (see hrtimer_run_queues()).
  1251. */
  1252. static void tick_nohz_lowres_handler(struct clock_event_device *dev)
  1253. {
  1254. struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
  1255. dev->next_event = KTIME_MAX;
  1256. if (likely(tick_nohz_handler(&ts->sched_timer) == HRTIMER_RESTART))
  1257. tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
  1258. }
  1259. static inline void tick_nohz_activate(struct tick_sched *ts)
  1260. {
  1261. if (!tick_nohz_enabled)
  1262. return;
  1263. tick_sched_flag_set(ts, TS_FLAG_NOHZ);
  1264. /* One update is enough */
  1265. if (!test_and_set_bit(0, &tick_nohz_active))
  1266. timers_update_nohz();
  1267. }
  1268. /**
  1269. * tick_nohz_switch_to_nohz - switch to NOHZ mode
  1270. */
  1271. static void tick_nohz_switch_to_nohz(void)
  1272. {
  1273. if (!tick_nohz_enabled)
  1274. return;
  1275. if (tick_switch_to_oneshot(tick_nohz_lowres_handler))
  1276. return;
  1277. /*
  1278. * Recycle the hrtimer in 'ts', so we can share the
  1279. * highres code.
  1280. */
  1281. tick_setup_sched_timer(false);
  1282. }
  1283. static inline void tick_nohz_irq_enter(void)
  1284. {
  1285. struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
  1286. ktime_t now;
  1287. if (!tick_sched_flag_test(ts, TS_FLAG_STOPPED | TS_FLAG_IDLE_ACTIVE))
  1288. return;
  1289. now = ktime_get();
  1290. if (tick_sched_flag_test(ts, TS_FLAG_IDLE_ACTIVE))
  1291. tick_nohz_stop_idle(ts, now);
  1292. /*
  1293. * If all CPUs are idle we may need to update a stale jiffies value.
  1294. * Note nohz_full is a special case: a timekeeper is guaranteed to stay
  1295. * alive but it might be busy looping with interrupts disabled in some
  1296. * rare case (typically stop machine). So we must make sure we have a
  1297. * last resort.
  1298. */
  1299. if (tick_sched_flag_test(ts, TS_FLAG_STOPPED))
  1300. tick_nohz_update_jiffies(now);
  1301. }
  1302. #else
  1303. static inline void tick_nohz_switch_to_nohz(void) { }
  1304. static inline void tick_nohz_irq_enter(void) { }
  1305. static inline void tick_nohz_activate(struct tick_sched *ts) { }
  1306. #endif /* CONFIG_NO_HZ_COMMON */
  1307. /*
  1308. * Called from irq_enter() to notify about the possible interruption of idle()
  1309. */
  1310. void tick_irq_enter(void)
  1311. {
  1312. tick_check_oneshot_broadcast_this_cpu();
  1313. tick_nohz_irq_enter();
  1314. }
  1315. static int sched_skew_tick;
  1316. static int __init skew_tick(char *str)
  1317. {
  1318. get_option(&str, &sched_skew_tick);
  1319. return 0;
  1320. }
  1321. early_param("skew_tick", skew_tick);
  1322. /**
  1323. * tick_setup_sched_timer - setup the tick emulation timer
  1324. * @hrtimer: whether to use the hrtimer or not
  1325. */
  1326. void tick_setup_sched_timer(bool hrtimer)
  1327. {
  1328. struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
  1329. /* Emulate tick processing via per-CPU hrtimers: */
  1330. hrtimer_init(&ts->sched_timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_HARD);
  1331. if (IS_ENABLED(CONFIG_HIGH_RES_TIMERS) && hrtimer) {
  1332. tick_sched_flag_set(ts, TS_FLAG_HIGHRES);
  1333. ts->sched_timer.function = tick_nohz_handler;
  1334. }
  1335. /* Get the next period (per-CPU) */
  1336. hrtimer_set_expires(&ts->sched_timer, tick_init_jiffy_update());
  1337. /* Offset the tick to avert 'jiffies_lock' contention. */
  1338. if (sched_skew_tick) {
  1339. u64 offset = TICK_NSEC >> 1;
  1340. do_div(offset, num_possible_cpus());
  1341. offset *= smp_processor_id();
  1342. hrtimer_add_expires_ns(&ts->sched_timer, offset);
  1343. }
  1344. hrtimer_forward_now(&ts->sched_timer, TICK_NSEC);
  1345. if (IS_ENABLED(CONFIG_HIGH_RES_TIMERS) && hrtimer)
  1346. hrtimer_start_expires(&ts->sched_timer, HRTIMER_MODE_ABS_PINNED_HARD);
  1347. else
  1348. tick_program_event(hrtimer_get_expires(&ts->sched_timer), 1);
  1349. tick_nohz_activate(ts);
  1350. }
  1351. /*
  1352. * Shut down the tick and make sure the CPU won't try to retake the timekeeping
  1353. * duty before disabling IRQs in idle for the last time.
  1354. */
  1355. void tick_sched_timer_dying(int cpu)
  1356. {
  1357. struct tick_device *td = &per_cpu(tick_cpu_device, cpu);
  1358. struct tick_sched *ts = &per_cpu(tick_cpu_sched, cpu);
  1359. struct clock_event_device *dev = td->evtdev;
  1360. ktime_t idle_sleeptime, iowait_sleeptime;
  1361. unsigned long idle_calls, idle_sleeps;
  1362. /* This must happen before hrtimers are migrated! */
  1363. tick_sched_timer_cancel(ts);
  1364. /*
  1365. * If the clockevents doesn't support CLOCK_EVT_STATE_ONESHOT_STOPPED,
  1366. * make sure not to call low-res tick handler.
  1367. */
  1368. if (tick_sched_flag_test(ts, TS_FLAG_NOHZ))
  1369. dev->event_handler = clockevents_handle_noop;
  1370. idle_sleeptime = ts->idle_sleeptime;
  1371. iowait_sleeptime = ts->iowait_sleeptime;
  1372. idle_calls = ts->idle_calls;
  1373. idle_sleeps = ts->idle_sleeps;
  1374. memset(ts, 0, sizeof(*ts));
  1375. ts->idle_sleeptime = idle_sleeptime;
  1376. ts->iowait_sleeptime = iowait_sleeptime;
  1377. ts->idle_calls = idle_calls;
  1378. ts->idle_sleeps = idle_sleeps;
  1379. }
  1380. /*
  1381. * Async notification about clocksource changes
  1382. */
  1383. void tick_clock_notify(void)
  1384. {
  1385. int cpu;
  1386. for_each_possible_cpu(cpu)
  1387. set_bit(0, &per_cpu(tick_cpu_sched, cpu).check_clocks);
  1388. }
  1389. /*
  1390. * Async notification about clock event changes
  1391. */
  1392. void tick_oneshot_notify(void)
  1393. {
  1394. struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
  1395. set_bit(0, &ts->check_clocks);
  1396. }
  1397. /*
  1398. * Check if a change happened, which makes oneshot possible.
  1399. *
  1400. * Called cyclically from the hrtimer softirq (driven by the timer
  1401. * softirq). 'allow_nohz' signals that we can switch into low-res NOHZ
  1402. * mode, because high resolution timers are disabled (either compile
  1403. * or runtime). Called with interrupts disabled.
  1404. */
  1405. int tick_check_oneshot_change(int allow_nohz)
  1406. {
  1407. struct tick_sched *ts = this_cpu_ptr(&tick_cpu_sched);
  1408. if (!test_and_clear_bit(0, &ts->check_clocks))
  1409. return 0;
  1410. if (tick_sched_flag_test(ts, TS_FLAG_NOHZ))
  1411. return 0;
  1412. if (!timekeeping_valid_for_hres() || !tick_is_oneshot_available())
  1413. return 0;
  1414. if (!allow_nohz)
  1415. return 1;
  1416. tick_nohz_switch_to_nohz();
  1417. return 0;
  1418. }