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