1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * This file contains the base functions to manage periodic tick
4 * related events.
5 *
6 * Copyright(C) 2005-2006, Thomas Gleixner <tglx@linutronix.de>
7 * Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar
8 * Copyright(C) 2006-2007, Timesys Corp., Thomas Gleixner
9 */
10 #include <linux/compiler.h>
11 #include <linux/cpu.h>
12 #include <linux/err.h>
13 #include <linux/hrtimer.h>
14 #include <linux/interrupt.h>
15 #include <linux/nmi.h>
16 #include <linux/percpu.h>
17 #include <linux/profile.h>
18 #include <linux/sched.h>
19 #include <linux/module.h>
20 #include <trace/events/power.h>
21 #include <trace/hooks/sched.h>
22
23 #include <asm/irq_regs.h>
24
25 #include "tick-internal.h"
26
27 /*
28 * Tick devices
29 */
30 DEFINE_PER_CPU(struct tick_device, tick_cpu_device);
31 /*
32 * Tick next event: keeps track of the tick time. It's updated by the
33 * CPU which handles the tick and protected by jiffies_lock. There is
34 * no requirement to write hold the jiffies seqcount for it.
35 */
36 ktime_t tick_next_period;
37
38 /*
39 * tick_do_timer_cpu is a timer core internal variable which holds the CPU NR
40 * which is responsible for calling do_timer(), i.e. the timekeeping stuff. This
41 * variable has two functions:
42 *
43 * 1) Prevent a thundering herd issue of a gazillion of CPUs trying to grab the
44 * timekeeping lock all at once. Only the CPU which is assigned to do the
45 * update is handling it.
46 *
47 * 2) Hand off the duty in the NOHZ idle case by setting the value to
48 * TICK_DO_TIMER_NONE, i.e. a non existing CPU. So the next cpu which looks
49 * at it will take over and keep the time keeping alive. The handover
50 * procedure also covers cpu hotplug.
51 */
52 int tick_do_timer_cpu __read_mostly = TICK_DO_TIMER_BOOT;
53 #ifdef CONFIG_NO_HZ_FULL
54 /*
55 * tick_do_timer_boot_cpu indicates the boot CPU temporarily owns
56 * tick_do_timer_cpu and it should be taken over by an eligible secondary
57 * when one comes online.
58 */
59 static int tick_do_timer_boot_cpu __read_mostly = -1;
60 #endif
61
62 /*
63 * Debugging: see timer_list.c
64 */
tick_get_device(int cpu)65 struct tick_device *tick_get_device(int cpu)
66 {
67 return &per_cpu(tick_cpu_device, cpu);
68 }
69
70 /**
71 * tick_is_oneshot_available - check for a oneshot capable event device
72 */
tick_is_oneshot_available(void)73 int tick_is_oneshot_available(void)
74 {
75 struct clock_event_device *dev = __this_cpu_read(tick_cpu_device.evtdev);
76
77 if (!dev || !(dev->features & CLOCK_EVT_FEAT_ONESHOT))
78 return 0;
79 if (!(dev->features & CLOCK_EVT_FEAT_C3STOP))
80 return 1;
81 return tick_broadcast_oneshot_available();
82 }
83
84 /*
85 * Periodic tick
86 */
tick_periodic(int cpu)87 static void tick_periodic(int cpu)
88 {
89 if (READ_ONCE(tick_do_timer_cpu) == cpu) {
90 raw_spin_lock(&jiffies_lock);
91 write_seqcount_begin(&jiffies_seq);
92
93 /* Keep track of the next tick event */
94 tick_next_period = ktime_add_ns(tick_next_period, TICK_NSEC);
95
96 do_timer(1);
97 write_seqcount_end(&jiffies_seq);
98 raw_spin_unlock(&jiffies_lock);
99 update_wall_time();
100 trace_android_vh_jiffies_update(NULL);
101 }
102
103 update_process_times(user_mode(get_irq_regs()));
104 profile_tick(CPU_PROFILING);
105 }
106
107 /*
108 * Event handler for periodic ticks
109 */
tick_handle_periodic(struct clock_event_device * dev)110 void tick_handle_periodic(struct clock_event_device *dev)
111 {
112 int cpu = smp_processor_id();
113 ktime_t next = dev->next_event;
114
115 tick_periodic(cpu);
116
117 /*
118 * The cpu might have transitioned to HIGHRES or NOHZ mode via
119 * update_process_times() -> run_local_timers() ->
120 * hrtimer_run_queues().
121 */
122 if (IS_ENABLED(CONFIG_TICK_ONESHOT) && dev->event_handler != tick_handle_periodic)
123 return;
124
125 if (!clockevent_state_oneshot(dev))
126 return;
127 for (;;) {
128 /*
129 * Setup the next period for devices, which do not have
130 * periodic mode:
131 */
132 next = ktime_add_ns(next, TICK_NSEC);
133
134 if (!clockevents_program_event(dev, next, false))
135 return;
136 /*
137 * Have to be careful here. If we're in oneshot mode,
138 * before we call tick_periodic() in a loop, we need
139 * to be sure we're using a real hardware clocksource.
140 * Otherwise we could get trapped in an infinite
141 * loop, as the tick_periodic() increments jiffies,
142 * which then will increment time, possibly causing
143 * the loop to trigger again and again.
144 */
145 if (timekeeping_valid_for_hres())
146 tick_periodic(cpu);
147 }
148 }
149
150 /*
151 * Setup the device for a periodic tick
152 */
tick_setup_periodic(struct clock_event_device * dev,int broadcast)153 void tick_setup_periodic(struct clock_event_device *dev, int broadcast)
154 {
155 tick_set_periodic_handler(dev, broadcast);
156
157 /* Broadcast setup ? */
158 if (!tick_device_is_functional(dev))
159 return;
160
161 if ((dev->features & CLOCK_EVT_FEAT_PERIODIC) &&
162 !tick_broadcast_oneshot_active()) {
163 clockevents_switch_state(dev, CLOCK_EVT_STATE_PERIODIC);
164 } else {
165 unsigned int seq;
166 ktime_t next;
167
168 do {
169 seq = read_seqcount_begin(&jiffies_seq);
170 next = tick_next_period;
171 } while (read_seqcount_retry(&jiffies_seq, seq));
172
173 clockevents_switch_state(dev, CLOCK_EVT_STATE_ONESHOT);
174
175 for (;;) {
176 if (!clockevents_program_event(dev, next, false))
177 return;
178 next = ktime_add_ns(next, TICK_NSEC);
179 }
180 }
181 }
182
183 /*
184 * Setup the tick device
185 */
tick_setup_device(struct tick_device * td,struct clock_event_device * newdev,int cpu,const struct cpumask * cpumask)186 static void tick_setup_device(struct tick_device *td,
187 struct clock_event_device *newdev, int cpu,
188 const struct cpumask *cpumask)
189 {
190 void (*handler)(struct clock_event_device *) = NULL;
191 ktime_t next_event = 0;
192
193 /*
194 * First device setup ?
195 */
196 if (!td->evtdev) {
197 /*
198 * If no cpu took the do_timer update, assign it to
199 * this cpu:
200 */
201 if (READ_ONCE(tick_do_timer_cpu) == TICK_DO_TIMER_BOOT) {
202 WRITE_ONCE(tick_do_timer_cpu, cpu);
203 tick_next_period = ktime_get();
204 #ifdef CONFIG_NO_HZ_FULL
205 /*
206 * The boot CPU may be nohz_full, in which case the
207 * first housekeeping secondary will take do_timer()
208 * from it.
209 */
210 if (tick_nohz_full_cpu(cpu))
211 tick_do_timer_boot_cpu = cpu;
212
213 } else if (tick_do_timer_boot_cpu != -1 && !tick_nohz_full_cpu(cpu)) {
214 tick_do_timer_boot_cpu = -1;
215 /*
216 * The boot CPU will stay in periodic (NOHZ disabled)
217 * mode until clocksource_done_booting() called after
218 * smp_init() selects a high resolution clocksource and
219 * timekeeping_notify() kicks the NOHZ stuff alive.
220 *
221 * So this WRITE_ONCE can only race with the READ_ONCE
222 * check in tick_periodic() but this race is harmless.
223 */
224 WRITE_ONCE(tick_do_timer_cpu, cpu);
225 #endif
226 }
227
228 /*
229 * Startup in periodic mode first.
230 */
231 td->mode = TICKDEV_MODE_PERIODIC;
232 } else {
233 handler = td->evtdev->event_handler;
234 next_event = td->evtdev->next_event;
235 td->evtdev->event_handler = clockevents_handle_noop;
236 }
237
238 td->evtdev = newdev;
239
240 /*
241 * When the device is not per cpu, pin the interrupt to the
242 * current cpu:
243 */
244 if (!cpumask_equal(newdev->cpumask, cpumask))
245 irq_set_affinity(newdev->irq, cpumask);
246
247 /*
248 * When global broadcasting is active, check if the current
249 * device is registered as a placeholder for broadcast mode.
250 * This allows us to handle this x86 misfeature in a generic
251 * way. This function also returns !=0 when we keep the
252 * current active broadcast state for this CPU.
253 */
254 if (tick_device_uses_broadcast(newdev, cpu))
255 return;
256
257 if (td->mode == TICKDEV_MODE_PERIODIC)
258 tick_setup_periodic(newdev, 0);
259 else
260 tick_setup_oneshot(newdev, handler, next_event);
261 }
262
tick_install_replacement(struct clock_event_device * newdev)263 void tick_install_replacement(struct clock_event_device *newdev)
264 {
265 struct tick_device *td = this_cpu_ptr(&tick_cpu_device);
266 int cpu = smp_processor_id();
267
268 clockevents_exchange_device(td->evtdev, newdev);
269 tick_setup_device(td, newdev, cpu, cpumask_of(cpu));
270 if (newdev->features & CLOCK_EVT_FEAT_ONESHOT)
271 tick_oneshot_notify();
272 }
273
tick_check_percpu(struct clock_event_device * curdev,struct clock_event_device * newdev,int cpu)274 static bool tick_check_percpu(struct clock_event_device *curdev,
275 struct clock_event_device *newdev, int cpu)
276 {
277 if (!cpumask_test_cpu(cpu, newdev->cpumask))
278 return false;
279 if (cpumask_equal(newdev->cpumask, cpumask_of(cpu)))
280 return true;
281 /* Check if irq affinity can be set */
282 if (newdev->irq >= 0 && !irq_can_set_affinity(newdev->irq))
283 return false;
284 /* Prefer an existing cpu local device */
285 if (curdev && cpumask_equal(curdev->cpumask, cpumask_of(cpu)))
286 return false;
287 return true;
288 }
289
tick_check_preferred(struct clock_event_device * curdev,struct clock_event_device * newdev)290 static bool tick_check_preferred(struct clock_event_device *curdev,
291 struct clock_event_device *newdev)
292 {
293 /* Prefer oneshot capable device */
294 if (!(newdev->features & CLOCK_EVT_FEAT_ONESHOT)) {
295 if (curdev && (curdev->features & CLOCK_EVT_FEAT_ONESHOT))
296 return false;
297 if (tick_oneshot_mode_active())
298 return false;
299 }
300
301 /*
302 * Use the higher rated one, but prefer a CPU local device with a lower
303 * rating than a non-CPU local device
304 */
305 return !curdev ||
306 newdev->rating > curdev->rating ||
307 !cpumask_equal(curdev->cpumask, newdev->cpumask);
308 }
309
310 /*
311 * Check whether the new device is a better fit than curdev. curdev
312 * can be NULL !
313 */
tick_check_replacement(struct clock_event_device * curdev,struct clock_event_device * newdev)314 bool tick_check_replacement(struct clock_event_device *curdev,
315 struct clock_event_device *newdev)
316 {
317 if (!tick_check_percpu(curdev, newdev, smp_processor_id()))
318 return false;
319
320 return tick_check_preferred(curdev, newdev);
321 }
322
323 /*
324 * Check, if the new registered device should be used. Called with
325 * clockevents_lock held and interrupts disabled.
326 */
tick_check_new_device(struct clock_event_device * newdev)327 void tick_check_new_device(struct clock_event_device *newdev)
328 {
329 struct clock_event_device *curdev;
330 struct tick_device *td;
331 int cpu;
332
333 cpu = smp_processor_id();
334 td = &per_cpu(tick_cpu_device, cpu);
335 curdev = td->evtdev;
336
337 if (!tick_check_replacement(curdev, newdev))
338 goto out_bc;
339
340 if (!try_module_get(newdev->owner))
341 return;
342
343 /*
344 * Replace the eventually existing device by the new
345 * device. If the current device is the broadcast device, do
346 * not give it back to the clockevents layer !
347 */
348 if (tick_is_broadcast_device(curdev)) {
349 clockevents_shutdown(curdev);
350 curdev = NULL;
351 }
352 clockevents_exchange_device(curdev, newdev);
353 tick_setup_device(td, newdev, cpu, cpumask_of(cpu));
354 if (newdev->features & CLOCK_EVT_FEAT_ONESHOT)
355 tick_oneshot_notify();
356 return;
357
358 out_bc:
359 /*
360 * Can the new device be used as a broadcast device ?
361 */
362 tick_install_broadcast_device(newdev, cpu);
363 }
364
365 /**
366 * tick_broadcast_oneshot_control - Enter/exit broadcast oneshot mode
367 * @state: The target state (enter/exit)
368 *
369 * The system enters/leaves a state, where affected devices might stop
370 * Returns 0 on success, -EBUSY if the cpu is used to broadcast wakeups.
371 *
372 * Called with interrupts disabled, so clockevents_lock is not
373 * required here because the local clock event device cannot go away
374 * under us.
375 */
tick_broadcast_oneshot_control(enum tick_broadcast_state state)376 int tick_broadcast_oneshot_control(enum tick_broadcast_state state)
377 {
378 struct tick_device *td = this_cpu_ptr(&tick_cpu_device);
379
380 if (!(td->evtdev->features & CLOCK_EVT_FEAT_C3STOP))
381 return 0;
382
383 return __tick_broadcast_oneshot_control(state);
384 }
385 EXPORT_SYMBOL_GPL(tick_broadcast_oneshot_control);
386
387 #ifdef CONFIG_HOTPLUG_CPU
tick_assert_timekeeping_handover(void)388 void tick_assert_timekeeping_handover(void)
389 {
390 WARN_ON_ONCE(tick_do_timer_cpu == smp_processor_id());
391 }
392 /*
393 * Stop the tick and transfer the timekeeping job away from a dying cpu.
394 */
tick_cpu_dying(unsigned int dying_cpu)395 int tick_cpu_dying(unsigned int dying_cpu)
396 {
397 /*
398 * If the current CPU is the timekeeper, it's the only one that can
399 * safely hand over its duty. Also all online CPUs are in stop
400 * machine, guaranteed not to be idle, therefore there is no
401 * concurrency and it's safe to pick any online successor.
402 */
403 if (tick_do_timer_cpu == dying_cpu)
404 tick_do_timer_cpu = cpumask_first(cpu_online_mask);
405
406 /* Make sure the CPU won't try to retake the timekeeping duty */
407 tick_sched_timer_dying(dying_cpu);
408
409 /* Remove CPU from timer broadcasting */
410 tick_offline_cpu(dying_cpu);
411
412 return 0;
413 }
414
415 /*
416 * Shutdown an event device on a given cpu:
417 *
418 * This is called on a life CPU, when a CPU is dead. So we cannot
419 * access the hardware device itself.
420 * We just set the mode and remove it from the lists.
421 */
tick_shutdown(unsigned int cpu)422 void tick_shutdown(unsigned int cpu)
423 {
424 struct tick_device *td = &per_cpu(tick_cpu_device, cpu);
425 struct clock_event_device *dev = td->evtdev;
426
427 td->mode = TICKDEV_MODE_PERIODIC;
428 if (dev) {
429 /*
430 * Prevent that the clock events layer tries to call
431 * the set mode function!
432 */
433 clockevent_set_state(dev, CLOCK_EVT_STATE_DETACHED);
434 clockevents_exchange_device(dev, NULL);
435 dev->event_handler = clockevents_handle_noop;
436 td->evtdev = NULL;
437 }
438 }
439 #endif
440
441 /**
442 * tick_suspend_local - Suspend the local tick device
443 *
444 * Called from the local cpu for freeze with interrupts disabled.
445 *
446 * No locks required. Nothing can change the per cpu device.
447 */
tick_suspend_local(void)448 void tick_suspend_local(void)
449 {
450 struct tick_device *td = this_cpu_ptr(&tick_cpu_device);
451
452 clockevents_shutdown(td->evtdev);
453 }
454
455 /**
456 * tick_resume_local - Resume the local tick device
457 *
458 * Called from the local CPU for unfreeze or XEN resume magic.
459 *
460 * No locks required. Nothing can change the per cpu device.
461 */
tick_resume_local(void)462 void tick_resume_local(void)
463 {
464 struct tick_device *td = this_cpu_ptr(&tick_cpu_device);
465 bool broadcast = tick_resume_check_broadcast();
466
467 clockevents_tick_resume(td->evtdev);
468 if (!broadcast) {
469 if (td->mode == TICKDEV_MODE_PERIODIC)
470 tick_setup_periodic(td->evtdev, 0);
471 else
472 tick_resume_oneshot();
473 }
474
475 /*
476 * Ensure that hrtimers are up to date and the clockevents device
477 * is reprogrammed correctly when high resolution timers are
478 * enabled.
479 */
480 hrtimers_resume_local();
481 }
482
483 /**
484 * tick_suspend - Suspend the tick and the broadcast device
485 *
486 * Called from syscore_suspend() via timekeeping_suspend with only one
487 * CPU online and interrupts disabled or from tick_unfreeze() under
488 * tick_freeze_lock.
489 *
490 * No locks required. Nothing can change the per cpu device.
491 */
tick_suspend(void)492 void tick_suspend(void)
493 {
494 tick_suspend_local();
495 tick_suspend_broadcast();
496 }
497
498 /**
499 * tick_resume - Resume the tick and the broadcast device
500 *
501 * Called from syscore_resume() via timekeeping_resume with only one
502 * CPU online and interrupts disabled.
503 *
504 * No locks required. Nothing can change the per cpu device.
505 */
tick_resume(void)506 void tick_resume(void)
507 {
508 tick_resume_broadcast();
509 tick_resume_local();
510 }
511
512 #ifdef CONFIG_SUSPEND
513 static DEFINE_RAW_SPINLOCK(tick_freeze_lock);
514 static DEFINE_WAIT_OVERRIDE_MAP(tick_freeze_map, LD_WAIT_SLEEP);
515 static unsigned int tick_freeze_depth;
516
517 /**
518 * tick_freeze - Suspend the local tick and (possibly) timekeeping.
519 *
520 * Check if this is the last online CPU executing the function and if so,
521 * suspend timekeeping. Otherwise suspend the local tick.
522 *
523 * Call with interrupts disabled. Must be balanced with %tick_unfreeze().
524 * Interrupts must not be enabled before the subsequent %tick_unfreeze().
525 */
tick_freeze(void)526 void tick_freeze(void)
527 {
528 raw_spin_lock(&tick_freeze_lock);
529
530 tick_freeze_depth++;
531 if (tick_freeze_depth == num_online_cpus()) {
532 trace_suspend_resume(TPS("timekeeping_freeze"),
533 smp_processor_id(), true);
534 /*
535 * All other CPUs have their interrupts disabled and are
536 * suspended to idle. Other tasks have been frozen so there
537 * is no scheduling happening. This means that there is no
538 * concurrency in the system at this point. Therefore it is
539 * okay to acquire a sleeping lock on PREEMPT_RT, such as a
540 * spinlock, because the lock cannot be held by other CPUs
541 * or threads and acquiring it cannot block.
542 *
543 * Inform lockdep about the situation.
544 */
545 lock_map_acquire_try(&tick_freeze_map);
546 system_state = SYSTEM_SUSPEND;
547 sched_clock_suspend();
548 timekeeping_suspend();
549 lock_map_release(&tick_freeze_map);
550 } else {
551 tick_suspend_local();
552 }
553
554 raw_spin_unlock(&tick_freeze_lock);
555 }
556
557 /**
558 * tick_unfreeze - Resume the local tick and (possibly) timekeeping.
559 *
560 * Check if this is the first CPU executing the function and if so, resume
561 * timekeeping. Otherwise resume the local tick.
562 *
563 * Call with interrupts disabled. Must be balanced with %tick_freeze().
564 * Interrupts must not be enabled after the preceding %tick_freeze().
565 */
tick_unfreeze(void)566 void tick_unfreeze(void)
567 {
568 raw_spin_lock(&tick_freeze_lock);
569
570 if (tick_freeze_depth == num_online_cpus()) {
571 /*
572 * Similar to tick_freeze(). On resumption the first CPU may
573 * acquire uncontended sleeping locks while other CPUs block on
574 * tick_freeze_lock.
575 */
576 lock_map_acquire_try(&tick_freeze_map);
577 timekeeping_resume();
578 sched_clock_resume();
579 lock_map_release(&tick_freeze_map);
580
581 system_state = SYSTEM_RUNNING;
582 trace_suspend_resume(TPS("timekeeping_freeze"),
583 smp_processor_id(), false);
584 } else {
585 touch_softlockup_watchdog();
586 tick_resume_local();
587 }
588
589 tick_freeze_depth--;
590
591 raw_spin_unlock(&tick_freeze_lock);
592 }
593 #endif /* CONFIG_SUSPEND */
594
595 /**
596 * tick_init - initialize the tick control
597 */
tick_init(void)598 void __init tick_init(void)
599 {
600 tick_broadcast_init();
601 tick_nohz_init();
602 }
603