2503 lines · 72.9 KB · C
RawDownload
// SPDX-License-Identifier: GPL-2.0/* *  Copyright(C) 2005-2006, Linutronix GmbH, Thomas Gleixner <tglx@kernel.org> *  Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar *  Copyright(C) 2006-2007  Timesys Corp., Thomas Gleixner * *  High-resolution kernel timers * *  In contrast to the low-resolution timeout API, aka timer wheel, *  hrtimers provide finer resolution and accuracy depending on system *  configuration and capabilities. * *  Started by: Thomas Gleixner and Ingo Molnar * *  Credits: *	Based on the original timer wheel code * *	Help, testing, suggestions, bugfixes, improvements were *	provided by: * *	George Anzinger, Andrew Morton, Steven Rostedt, Roman Zippel *	et. al. */ #include <linux/cpu.h>#include <linux/export.h>#include <linux/percpu.h>#include <linux/hrtimer.h>#include <linux/notifier.h>#include <linux/syscalls.h>#include <linux/interrupt.h>#include <linux/tick.h>#include <linux/err.h>#include <linux/debugobjects.h>#include <linux/sched/signal.h>#include <linux/sched/sysctl.h>#include <linux/sched/rt.h>#include <linux/sched/deadline.h>#include <linux/sched/nohz.h>#include <linux/sched/debug.h>#include <linux/sched/isolation.h>#include <linux/timer.h>#include <linux/freezer.h>#include <linux/compat.h> #include <linux/uaccess.h> #include <trace/events/timer.h> #include "tick-internal.h" /* * Constants to set the queued state of the timer (INACTIVE, ENQUEUED) * * The callback state is kept separate in the CPU base because having it in * the timer would required touching the timer after the callback, which * makes it impossible to free the timer from the callback function. * * Therefore we track the callback state in: * *	timer->base->cpu_base->running == timer * * On SMP it is possible to have a "callback function running and enqueued" * status. It happens for example when a posix timer expired and the callback * queued a signal. Between dropping the lock which protects the posix timer * and reacquiring the base lock of the hrtimer, another CPU can deliver the * signal and rearm the timer. * * All state transitions are protected by cpu_base->lock. */#define HRTIMER_STATE_INACTIVE	false#define HRTIMER_STATE_ENQUEUED	true /* * The resolution of the clocks. The resolution value is returned in * the clock_getres() system call to give application programmers an * idea of the (in)accuracy of timers. Timer values are rounded up to * this resolution values. */#define HIGH_RES_NSEC		1 /* * Masks for selecting the soft and hard context timers from * cpu_base->active */#define MASK_SHIFT		(HRTIMER_BASE_MONOTONIC_SOFT)#define HRTIMER_ACTIVE_HARD	((1U << MASK_SHIFT) - 1)#define HRTIMER_ACTIVE_SOFT	(HRTIMER_ACTIVE_HARD << MASK_SHIFT)#define HRTIMER_ACTIVE_ALL	(HRTIMER_ACTIVE_SOFT | HRTIMER_ACTIVE_HARD) static void retrigger_next_event(void *arg);static ktime_t __hrtimer_cb_get_time(clockid_t clock_id); /* * The timer bases: * * There are more clockids than hrtimer bases. Thus, we index * into the timer bases by the hrtimer_base_type enum. When trying * to reach a base using a clockid, hrtimer_clockid_to_base() * is used to convert from clockid to the proper hrtimer_base_type. */ #define BASE_INIT(idx, cid)			\	[idx] = { .index = idx, .clockid = cid } DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) ={	.lock = __RAW_SPIN_LOCK_UNLOCKED(hrtimer_bases.lock),	.clock_base = {		BASE_INIT(HRTIMER_BASE_MONOTONIC,	CLOCK_MONOTONIC),		BASE_INIT(HRTIMER_BASE_REALTIME,	CLOCK_REALTIME),		BASE_INIT(HRTIMER_BASE_BOOTTIME,	CLOCK_BOOTTIME),		BASE_INIT(HRTIMER_BASE_TAI,		CLOCK_TAI),		BASE_INIT(HRTIMER_BASE_MONOTONIC_SOFT,	CLOCK_MONOTONIC),		BASE_INIT(HRTIMER_BASE_REALTIME_SOFT,	CLOCK_REALTIME),		BASE_INIT(HRTIMER_BASE_BOOTTIME_SOFT,	CLOCK_BOOTTIME),		BASE_INIT(HRTIMER_BASE_TAI_SOFT,	CLOCK_TAI),	},	.csd = CSD_INIT(retrigger_next_event, NULL)}; static inline bool hrtimer_base_is_online(struct hrtimer_cpu_base *base){	if (!IS_ENABLED(CONFIG_HOTPLUG_CPU))		return true;	else		return likely(base->online);} #ifdef CONFIG_HIGH_RES_TIMERSDEFINE_STATIC_KEY_FALSE(hrtimer_highres_enabled_key); static void hrtimer_hres_workfn(struct work_struct *work){	static_branch_enable(&hrtimer_highres_enabled_key);} static DECLARE_WORK(hrtimer_hres_work, hrtimer_hres_workfn); static inline void hrtimer_schedule_hres_work(void){	if (!hrtimer_highres_enabled())		schedule_work(&hrtimer_hres_work);}#elsestatic inline void hrtimer_schedule_hres_work(void) { }#endif /* * Functions and macros which are different for UP/SMP systems are kept in a * single place */#ifdef CONFIG_SMP/* * We require the migration_base for lock_hrtimer_base()/switch_hrtimer_base() * such that hrtimer_callback_running() can unconditionally dereference * timer->base->cpu_base */static struct hrtimer_cpu_base migration_cpu_base = {	.clock_base = {		[0] = {			.cpu_base = &migration_cpu_base,			.seq      = SEQCNT_RAW_SPINLOCK_ZERO(migration_cpu_base.seq,							     &migration_cpu_base.lock),		},	},}; #define migration_base	migration_cpu_base.clock_base[0] /* * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock * means that all timers which are tied to this base via timer->base are * locked, and the base itself is locked too. * * So __run_timers/migrate_timers can safely modify all timers which could * be found on the lists/queues. * * When the timer's base is locked, and the timer removed from list, it is * possible to set timer->base = &migration_base and drop the lock: the timer * remains locked. */static struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,						    unsigned long *flags)	__acquires(&timer->base->lock){	for (;;) {		struct hrtimer_clock_base *base = READ_ONCE(timer->base); 		if (likely(base != &migration_base)) {			raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);			if (likely(base == timer->base))				return base;			/* The timer has migrated to another CPU: */			raw_spin_unlock_irqrestore(&base->cpu_base->lock, *flags);		}		cpu_relax();	}} /* * Check if the elected target is suitable considering its next * event and the hotplug state of the current CPU. * * If the elected target is remote and its next event is after the timer * to queue, then a remote reprogram is necessary. However there is no * guarantee the IPI handling the operation would arrive in time to meet * the high resolution deadline. In this case the local CPU becomes a * preferred target, unless it is offline. * * High and low resolution modes are handled the same way for simplicity. * * Called with cpu_base->lock of target cpu held. */static bool hrtimer_suitable_target(struct hrtimer *timer, struct hrtimer_clock_base *new_base,				    struct hrtimer_cpu_base *new_cpu_base,				    struct hrtimer_cpu_base *this_cpu_base){	ktime_t expires; 	/*	 * The local CPU clockevent can be reprogrammed. Also get_target_base()	 * guarantees it is online.	 */	if (new_cpu_base == this_cpu_base)		return true; 	/*	 * The offline local CPU can't be the default target if the	 * next remote target event is after this timer. Keep the	 * elected new base. An IPI will be issued to reprogram	 * it as a last resort.	 */	if (!hrtimer_base_is_online(this_cpu_base))		return true; 	expires = ktime_sub(hrtimer_get_expires(timer), new_base->offset); 	return expires >= new_base->cpu_base->expires_next;} static inline struct hrtimer_cpu_base *get_target_base(struct hrtimer_cpu_base *base, bool pinned){	if (!hrtimer_base_is_online(base)) {		int cpu = cpumask_any_and(cpu_online_mask, housekeeping_cpumask(HK_TYPE_TIMER)); 		return &per_cpu(hrtimer_bases, cpu);	} #if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON)	if (static_branch_likely(&timers_migration_enabled) && !pinned)		return &per_cpu(hrtimer_bases, get_nohz_timer_target());#endif	return base;} /* * We switch the timer base to a power-optimized selected CPU target, * if: *	- NO_HZ_COMMON is enabled *	- timer migration is enabled *	- the timer callback is not running *	- the timer is not the first expiring timer on the new target * * If one of the above requirements is not fulfilled we move the timer * to the current CPU or leave it on the previously assigned CPU if * the timer callback is currently running. */static inline struct hrtimer_clock_base *switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base, bool pinned){	struct hrtimer_cpu_base *new_cpu_base, *this_cpu_base;	struct hrtimer_clock_base *new_base;	int basenum = base->index; 	this_cpu_base = this_cpu_ptr(&hrtimer_bases);	new_cpu_base = get_target_base(this_cpu_base, pinned);again:	new_base = &new_cpu_base->clock_base[basenum]; 	if (base != new_base) {		/*		 * We are trying to move timer to new_base. However we can't		 * change timer's base while it is running, so we keep it on		 * the same CPU. No hassle vs. reprogramming the event source		 * in the high resolution case. The remote CPU will take care		 * of this when the timer function has completed. There is no		 * conflict as we hold the lock until the timer is enqueued.		 */		if (unlikely(hrtimer_callback_running(timer)))			return base; 		/* See the comment in lock_hrtimer_base() */		WRITE_ONCE(timer->base, &migration_base);		raw_spin_unlock(&base->cpu_base->lock);		raw_spin_lock(&new_base->cpu_base->lock); 		if (!hrtimer_suitable_target(timer, new_base, new_cpu_base, this_cpu_base)) {			raw_spin_unlock(&new_base->cpu_base->lock);			raw_spin_lock(&base->cpu_base->lock);			new_cpu_base = this_cpu_base;			WRITE_ONCE(timer->base, base);			goto again;		}		WRITE_ONCE(timer->base, new_base);	} else {		if (!hrtimer_suitable_target(timer, new_base,  new_cpu_base, this_cpu_base)) {			new_cpu_base = this_cpu_base;			goto again;		}	}	return new_base;} #else /* CONFIG_SMP */ static inline struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,							   unsigned long *flags)	__acquires(&timer->base->cpu_base->lock){	struct hrtimer_clock_base *base = timer->base; 	raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);	return base;} # define switch_hrtimer_base(t, b, p)	(b) #endif	/* !CONFIG_SMP */ /* * Functions for the union type storage format of ktime_t which are * too large for inlining: */#if BITS_PER_LONG < 64/* * Divide a ktime value by a nanosecond value */s64 __ktime_divns(const ktime_t kt, s64 div){	int sft = 0;	s64 dclc;	u64 tmp; 	dclc = ktime_to_ns(kt);	tmp = dclc < 0 ? -dclc : dclc; 	/* Make sure the divisor is less than 2^32: */	while (div >> 32) {		sft++;		div >>= 1;	}	tmp >>= sft;	do_div(tmp, (u32) div);	return dclc < 0 ? -tmp : tmp;}EXPORT_SYMBOL_GPL(__ktime_divns);#endif /* BITS_PER_LONG < 64 */ /* * Add two ktime values and do a safety check for overflow: */ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs){	ktime_t res = ktime_add_unsafe(lhs, rhs); 	/*	 * We use KTIME_SEC_MAX here, the maximum timeout which we can	 * return to user space in a timespec:	 */	if (res < 0 || res < lhs || res < rhs)		res = ktime_set(KTIME_SEC_MAX, 0); 	return res;} EXPORT_SYMBOL_GPL(ktime_add_safe); #ifdef CONFIG_DEBUG_OBJECTS_TIMERS static const struct debug_obj_descr hrtimer_debug_descr; static void *hrtimer_debug_hint(void *addr){	return ACCESS_PRIVATE((struct hrtimer *)addr, function);} /* * fixup_init is called when: * - an active object is initialized */static bool hrtimer_fixup_init(void *addr, enum debug_obj_state state){	struct hrtimer *timer = addr; 	switch (state) {	case ODEBUG_STATE_ACTIVE:		hrtimer_cancel(timer);		debug_object_init(timer, &hrtimer_debug_descr);		return true;	default:		return false;	}} /* * fixup_activate is called when: * - an active object is activated * - an unknown non-static object is activated */static bool hrtimer_fixup_activate(void *addr, enum debug_obj_state state){	switch (state) {	case ODEBUG_STATE_ACTIVE:		WARN_ON(1);		fallthrough;	default:		return false;	}} /* * fixup_free is called when: * - an active object is freed */static bool hrtimer_fixup_free(void *addr, enum debug_obj_state state){	struct hrtimer *timer = addr; 	switch (state) {	case ODEBUG_STATE_ACTIVE:		hrtimer_cancel(timer);		debug_object_free(timer, &hrtimer_debug_descr);		return true;	default:		return false;	}} /* Stub timer callback for improperly used timers. */static enum hrtimer_restart stub_timer(struct hrtimer *unused){	WARN_ON_ONCE(1);	return HRTIMER_NORESTART;} /* * hrtimer_fixup_assert_init is called when: * - an untracked/uninit-ed object is found */static bool hrtimer_fixup_assert_init(void *addr, enum debug_obj_state state){	struct hrtimer *timer = addr; 	switch (state) {	case ODEBUG_STATE_NOTAVAILABLE:		hrtimer_setup(timer, stub_timer, CLOCK_MONOTONIC, 0);		return true;	default:		return false;	}} static const struct debug_obj_descr hrtimer_debug_descr = {	.name			= "hrtimer",	.debug_hint		= hrtimer_debug_hint,	.fixup_init		= hrtimer_fixup_init,	.fixup_activate		= hrtimer_fixup_activate,	.fixup_free		= hrtimer_fixup_free,	.fixup_assert_init	= hrtimer_fixup_assert_init,}; static inline void debug_hrtimer_init(struct hrtimer *timer){	debug_object_init(timer, &hrtimer_debug_descr);} static inline void debug_hrtimer_init_on_stack(struct hrtimer *timer){	debug_object_init_on_stack(timer, &hrtimer_debug_descr);} static inline void debug_hrtimer_activate(struct hrtimer *timer, enum hrtimer_mode mode){	debug_object_activate(timer, &hrtimer_debug_descr);} static inline void debug_hrtimer_deactivate(struct hrtimer *timer){	debug_object_deactivate(timer, &hrtimer_debug_descr);} static inline void debug_hrtimer_assert_init(struct hrtimer *timer){	debug_object_assert_init(timer, &hrtimer_debug_descr);} void destroy_hrtimer_on_stack(struct hrtimer *timer){	debug_object_free(timer, &hrtimer_debug_descr);

Lines 1–500 of 2503.