xref: /linux/sound/core/timer.c (revision 513480da5e9c8f55b4f8f5e89f386e26188fbb3f)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *  Timers abstract layer
4  *  Copyright (c) by Jaroslav Kysela <perex@perex.cz>
5  */
6 
7 #include <linux/delay.h>
8 #include <linux/init.h>
9 #include <linux/slab.h>
10 #include <linux/time.h>
11 #include <linux/mutex.h>
12 #include <linux/device.h>
13 #include <linux/module.h>
14 #include <linux/string.h>
15 #include <linux/sched/signal.h>
16 #include <linux/anon_inodes.h>
17 #include <linux/idr.h>
18 #include <sound/core.h>
19 #include <sound/timer.h>
20 #include <sound/control.h>
21 #include <sound/info.h>
22 #include <sound/minors.h>
23 #include <sound/initval.h>
24 #include <linux/kmod.h>
25 
26 /* internal flags */
27 #define SNDRV_TIMER_IFLG_PAUSED		0x00010000
28 #define SNDRV_TIMER_IFLG_DEAD		0x00020000
29 
30 #if IS_ENABLED(CONFIG_SND_HRTIMER)
31 #define DEFAULT_TIMER_LIMIT 4
32 #else
33 #define DEFAULT_TIMER_LIMIT 1
34 #endif
35 
36 static int timer_limit = DEFAULT_TIMER_LIMIT;
37 static int timer_tstamp_monotonic = 1;
38 MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>, Takashi Iwai <tiwai@suse.de>");
39 MODULE_DESCRIPTION("ALSA timer interface");
40 MODULE_LICENSE("GPL");
41 module_param(timer_limit, int, 0444);
42 MODULE_PARM_DESC(timer_limit, "Maximum global timers in system.");
43 module_param(timer_tstamp_monotonic, int, 0444);
44 MODULE_PARM_DESC(timer_tstamp_monotonic, "Use posix monotonic clock source for timestamps (default).");
45 
46 MODULE_ALIAS_CHARDEV(CONFIG_SND_MAJOR, SNDRV_MINOR_TIMER);
47 MODULE_ALIAS("devname:snd/timer");
48 
49 enum timer_tread_format {
50 	TREAD_FORMAT_NONE = 0,
51 	TREAD_FORMAT_TIME64,
52 	TREAD_FORMAT_TIME32,
53 };
54 
55 struct snd_timer_tread32 {
56 	int event;
57 	s32 tstamp_sec;
58 	s32 tstamp_nsec;
59 	unsigned int val;
60 };
61 
62 struct snd_timer_tread64 {
63 	int event;
64 	u8 pad1[4];
65 	s64 tstamp_sec;
66 	s64 tstamp_nsec;
67 	unsigned int val;
68 	u8 pad2[4];
69 };
70 
71 struct snd_timer_user {
72 	struct snd_timer_instance *timeri;
73 	int tread;		/* enhanced read with timestamps and events */
74 	unsigned long ticks;
75 	unsigned long overrun;
76 	int qhead;
77 	int qtail;
78 	int qused;
79 	int queue_size;
80 	bool disconnected;
81 	struct snd_timer_read *queue;
82 	struct snd_timer_tread64 *tqueue;
83 	spinlock_t qlock;
84 	unsigned long last_resolution;
85 	unsigned int filter;
86 	struct timespec64 tstamp;		/* trigger tstamp */
87 	wait_queue_head_t qchange_sleep;
88 	struct snd_fasync *fasync;
89 	struct mutex ioctl_lock;
90 };
91 
92 struct snd_timer_status32 {
93 	s32 tstamp_sec;			/* Timestamp - last update */
94 	s32 tstamp_nsec;
95 	unsigned int resolution;	/* current period resolution in ns */
96 	unsigned int lost;		/* counter of master tick lost */
97 	unsigned int overrun;		/* count of read queue overruns */
98 	unsigned int queue;		/* used queue size */
99 	unsigned char reserved[64];	/* reserved */
100 };
101 
102 #define SNDRV_TIMER_IOCTL_STATUS32	_IOR('T', 0x14, struct snd_timer_status32)
103 
104 struct snd_timer_status64 {
105 	s64 tstamp_sec;			/* Timestamp - last update */
106 	s64 tstamp_nsec;
107 	unsigned int resolution;	/* current period resolution in ns */
108 	unsigned int lost;		/* counter of master tick lost */
109 	unsigned int overrun;		/* count of read queue overruns */
110 	unsigned int queue;		/* used queue size */
111 	unsigned char reserved[64];	/* reserved */
112 };
113 
114 #ifdef CONFIG_SND_UTIMER
115 #define SNDRV_UTIMERS_MAX_COUNT 128
116 /* Internal data structure for keeping the state of the userspace-driven timer */
117 struct snd_utimer {
118 	char *name;
119 	struct snd_timer *timer;
120 	unsigned int id;
121 };
122 #endif
123 
124 #define SNDRV_TIMER_IOCTL_STATUS64	_IOR('T', 0x14, struct snd_timer_status64)
125 
126 /* list of timers */
127 static LIST_HEAD(snd_timer_list);
128 
129 /* list of slave instances */
130 static LIST_HEAD(snd_timer_slave_list);
131 
132 /* list of open master instances that can accept slave links */
133 static LIST_HEAD(snd_timer_master_list);
134 
135 /* lock for slave active lists */
136 static DEFINE_SPINLOCK(slave_active_lock);
137 
138 #define MAX_SLAVE_INSTANCES	1000
139 static int num_slaves;
140 
141 static DEFINE_MUTEX(register_mutex);
142 
143 static int snd_timer_free(struct snd_timer *timer);
144 static int snd_timer_dev_free(struct snd_device *device);
145 static int snd_timer_dev_register(struct snd_device *device);
146 static int snd_timer_dev_disconnect(struct snd_device *device);
147 
148 static void snd_timer_reschedule(struct snd_timer * timer, unsigned long ticks_left);
149 
150 /*
151  * create a timer instance with the given owner string.
152  */
153 struct snd_timer_instance *snd_timer_instance_new(const char *owner)
154 {
155 	struct snd_timer_instance *timeri;
156 
157 	timeri = kzalloc_obj(*timeri);
158 	if (timeri == NULL)
159 		return NULL;
160 	timeri->owner = kstrdup(owner, GFP_KERNEL);
161 	if (! timeri->owner) {
162 		kfree(timeri);
163 		return NULL;
164 	}
165 	INIT_LIST_HEAD(&timeri->open_list);
166 	INIT_LIST_HEAD(&timeri->active_list);
167 	INIT_LIST_HEAD(&timeri->master_list);
168 	INIT_LIST_HEAD(&timeri->ack_list);
169 	INIT_LIST_HEAD(&timeri->slave_list_head);
170 	INIT_LIST_HEAD(&timeri->slave_active_head);
171 
172 	return timeri;
173 }
174 EXPORT_SYMBOL(snd_timer_instance_new);
175 
176 void snd_timer_instance_free(struct snd_timer_instance *timeri)
177 {
178 	if (timeri) {
179 		if (timeri->private_free)
180 			timeri->private_free(timeri);
181 		kfree(timeri->owner);
182 		kfree(timeri);
183 	}
184 }
185 EXPORT_SYMBOL(snd_timer_instance_free);
186 
187 /*
188  * find a timer instance from the given timer id
189  */
190 static struct snd_timer *snd_timer_find(struct snd_timer_id *tid)
191 {
192 	struct snd_timer *timer;
193 
194 	list_for_each_entry(timer, &snd_timer_list, device_list) {
195 		if (timer->tmr_class != tid->dev_class)
196 			continue;
197 		if ((timer->tmr_class == SNDRV_TIMER_CLASS_CARD ||
198 		     timer->tmr_class == SNDRV_TIMER_CLASS_PCM) &&
199 		    (timer->card == NULL ||
200 		     timer->card->number != tid->card))
201 			continue;
202 		if (timer->tmr_device != tid->device)
203 			continue;
204 		if (timer->tmr_subdevice != tid->subdevice)
205 			continue;
206 		return timer;
207 	}
208 	return NULL;
209 }
210 
211 #ifdef CONFIG_MODULES
212 
213 static void snd_timer_request(struct snd_timer_id *tid)
214 {
215 	switch (tid->dev_class) {
216 	case SNDRV_TIMER_CLASS_GLOBAL:
217 		if (tid->device < timer_limit)
218 			request_module("snd-timer-%i", tid->device);
219 		break;
220 	case SNDRV_TIMER_CLASS_CARD:
221 	case SNDRV_TIMER_CLASS_PCM:
222 		if (tid->card < snd_ecards_limit)
223 			request_module("snd-card-%i", tid->card);
224 		break;
225 	default:
226 		break;
227 	}
228 }
229 
230 #endif
231 
232 /* move the slave if it belongs to the master; return 1 if match */
233 static int check_matching_master_slave(struct snd_timer_instance *master,
234 				       struct snd_timer_instance *slave)
235 {
236 	if (slave->slave_class != master->slave_class ||
237 	    slave->slave_id != master->slave_id)
238 		return 0;
239 	if (master->timer->num_instances >= master->timer->max_instances)
240 		return -EBUSY;
241 	list_move_tail(&slave->open_list, &master->slave_list_head);
242 	master->timer->num_instances++;
243 	guard(spinlock_irq)(&slave_active_lock);
244 	guard(spinlock)(&master->timer->lock);
245 	slave->master = master;
246 	slave->timer = master->timer;
247 	if (slave->flags & SNDRV_TIMER_IFLG_RUNNING)
248 		list_add_tail(&slave->active_list, &master->slave_active_head);
249 	return 1;
250 }
251 
252 static bool snd_timer_has_slave_key(const struct snd_timer_instance *timeri)
253 {
254 	return !(timeri->flags & SNDRV_TIMER_IFLG_SLAVE) &&
255 		timeri->slave_class > SNDRV_TIMER_SCLASS_NONE;
256 }
257 
258 /*
259  * look for a master instance matching with the slave id of the given slave.
260  * when found, relink the open_link of the slave.
261  *
262  * call this with register_mutex down.
263  */
264 static int snd_timer_check_slave(struct snd_timer_instance *slave)
265 {
266 	struct snd_timer_instance *master;
267 	int err = 0;
268 
269 	list_for_each_entry(master, &snd_timer_master_list, master_list) {
270 		err = check_matching_master_slave(master, slave);
271 		if (err != 0) /* match found or error */
272 			goto out;
273 	}
274 out:
275 	return err < 0 ? err : 0;
276 }
277 
278 /*
279  * look for slave instances matching with the slave id of the given master.
280  * when found, relink the open_link of slaves.
281  *
282  * call this with register_mutex down.
283  */
284 static int snd_timer_check_master(struct snd_timer_instance *master)
285 {
286 	struct snd_timer_instance *slave, *tmp;
287 	int err = 0;
288 
289 	/* check all pending slaves */
290 	list_for_each_entry_safe(slave, tmp, &snd_timer_slave_list, open_list) {
291 		err = check_matching_master_slave(master, slave);
292 		if (err < 0)
293 			break;
294 	}
295 	return err < 0 ? err : 0;
296 }
297 
298 static void snd_timer_close_locked(struct snd_timer_instance *timeri,
299 				   struct device **card_devp_to_put);
300 
301 /*
302  * open a timer instance
303  * when opening a master, the slave id must be here given.
304  */
305 int snd_timer_open(struct snd_timer_instance *timeri,
306 		   struct snd_timer_id *tid,
307 		   unsigned int slave_id)
308 {
309 	struct snd_timer *timer;
310 	struct device *card_dev_to_put = NULL;
311 	int err;
312 
313 	mutex_lock(&register_mutex);
314 	if (tid->dev_class == SNDRV_TIMER_CLASS_SLAVE) {
315 		/* open a slave instance */
316 		if (tid->dev_sclass <= SNDRV_TIMER_SCLASS_NONE ||
317 		    tid->dev_sclass > SNDRV_TIMER_SCLASS_OSS_SEQUENCER) {
318 			pr_debug("ALSA: timer: invalid slave class %i\n",
319 				 tid->dev_sclass);
320 			err = -EINVAL;
321 			goto unlock;
322 		}
323 		if (num_slaves >= MAX_SLAVE_INSTANCES) {
324 			err = -EBUSY;
325 			goto unlock;
326 		}
327 		timeri->slave_class = tid->dev_sclass;
328 		timeri->slave_id = tid->device;
329 		timeri->flags |= SNDRV_TIMER_IFLG_SLAVE;
330 		list_add_tail(&timeri->open_list, &snd_timer_slave_list);
331 		num_slaves++;
332 		err = snd_timer_check_slave(timeri);
333 		goto list_added;
334 	}
335 
336 	/* open a master instance */
337 	timer = snd_timer_find(tid);
338 #ifdef CONFIG_MODULES
339 	if (!timer) {
340 		mutex_unlock(&register_mutex);
341 		snd_timer_request(tid);
342 		mutex_lock(&register_mutex);
343 		timer = snd_timer_find(tid);
344 	}
345 #endif
346 	if (!timer) {
347 		err = -ENODEV;
348 		goto unlock;
349 	}
350 	if (!list_empty(&timer->open_list_head)) {
351 		struct snd_timer_instance *t =
352 			list_entry(timer->open_list_head.next,
353 				    struct snd_timer_instance, open_list);
354 		if (t->flags & SNDRV_TIMER_IFLG_EXCLUSIVE) {
355 			err = -EBUSY;
356 			goto unlock;
357 		}
358 	}
359 	if (timer->num_instances >= timer->max_instances) {
360 		err = -EBUSY;
361 		goto unlock;
362 	}
363 	if (!try_module_get(timer->module)) {
364 		err = -EBUSY;
365 		goto unlock;
366 	}
367 	/* take a card refcount for safe disconnection */
368 	if (timer->card) {
369 		get_device(&timer->card->card_dev);
370 		card_dev_to_put = &timer->card->card_dev;
371 	}
372 
373 	if (list_empty(&timer->open_list_head) && timer->hw.open) {
374 		err = timer->hw.open(timer);
375 		if (err) {
376 			module_put(timer->module);
377 			goto unlock;
378 		}
379 	}
380 
381 	timeri->timer = timer;
382 	timeri->slave_class = tid->dev_sclass;
383 	timeri->slave_id = slave_id;
384 
385 	list_add_tail(&timeri->open_list, &timer->open_list_head);
386 	if (snd_timer_has_slave_key(timeri))
387 		list_add_tail(&timeri->master_list, &snd_timer_master_list);
388 	timer->num_instances++;
389 	err = snd_timer_check_master(timeri);
390 list_added:
391 	if (err < 0)
392 		snd_timer_close_locked(timeri, &card_dev_to_put);
393 
394  unlock:
395 	mutex_unlock(&register_mutex);
396 	/* put_device() is called after unlock for avoiding deadlock */
397 	if (err < 0 && card_dev_to_put)
398 		put_device(card_dev_to_put);
399 	return err;
400 }
401 EXPORT_SYMBOL(snd_timer_open);
402 
403 /* remove slave links, called from snd_timer_close_locked() below */
404 static void remove_slave_links(struct snd_timer_instance *timeri,
405 			       struct snd_timer *timer)
406 {
407 	struct snd_timer_instance *slave, *tmp;
408 
409 	guard(spinlock_irq)(&slave_active_lock);
410 	guard(spinlock)(&timer->lock);
411 	timeri->timer = NULL;
412 	list_for_each_entry_safe(slave, tmp, &timeri->slave_list_head, open_list) {
413 		list_move_tail(&slave->open_list, &snd_timer_slave_list);
414 		timer->num_instances--;
415 		slave->master = NULL;
416 		slave->timer = NULL;
417 		list_del_init(&slave->ack_list);
418 		list_del_init(&slave->active_list);
419 	}
420 }
421 
422 /*
423  * close a timer instance
424  * call this with register_mutex down.
425  */
426 static void snd_timer_close_locked(struct snd_timer_instance *timeri,
427 				   struct device **card_devp_to_put)
428 {
429 	struct snd_timer *timer = timeri->timer;
430 
431 	if (timer) {
432 		guard(spinlock_irq)(&timer->lock);
433 		if (timeri->flags & SNDRV_TIMER_IFLG_DEAD)
434 			return; /* already closed */
435 		timeri->flags |= SNDRV_TIMER_IFLG_DEAD;
436 	}
437 
438 	if (!list_empty(&timeri->open_list)) {
439 		list_del_init(&timeri->open_list);
440 		if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
441 			num_slaves--;
442 	}
443 
444 	if (!list_empty(&timeri->master_list))
445 		list_del_init(&timeri->master_list);
446 
447 	/* force to stop the timer */
448 	snd_timer_stop(timeri);
449 
450 	if (timer) {
451 		timer->num_instances--;
452 		/* wait, until the active callback is finished */
453 		spin_lock_irq(&timer->lock);
454 		while (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) {
455 			spin_unlock_irq(&timer->lock);
456 			udelay(10);
457 			spin_lock_irq(&timer->lock);
458 		}
459 		spin_unlock_irq(&timer->lock);
460 
461 		remove_slave_links(timeri, timer);
462 
463 		/* slave doesn't need to release timer resources below */
464 		if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
465 			timer = NULL;
466 	}
467 
468 	if (timer) {
469 		if (list_empty(&timer->open_list_head) && timer->hw.close)
470 			timer->hw.close(timer);
471 		/* release a card refcount for safe disconnection */
472 		if (timer->card)
473 			*card_devp_to_put = &timer->card->card_dev;
474 		module_put(timer->module);
475 	}
476 }
477 
478 /*
479  * close a timer instance
480  */
481 void snd_timer_close(struct snd_timer_instance *timeri)
482 {
483 	struct device *card_dev_to_put = NULL;
484 
485 	if (snd_BUG_ON(!timeri))
486 		return;
487 
488 	scoped_guard(mutex, &register_mutex)
489 		snd_timer_close_locked(timeri, &card_dev_to_put);
490 	/* put_device() is called after unlock for avoiding deadlock */
491 	if (card_dev_to_put)
492 		put_device(card_dev_to_put);
493 }
494 EXPORT_SYMBOL(snd_timer_close);
495 
496 static unsigned long snd_timer_hw_resolution(struct snd_timer *timer)
497 {
498 	if (timer->hw.c_resolution)
499 		return timer->hw.c_resolution(timer);
500 	else
501 		return timer->hw.resolution;
502 }
503 
504 unsigned long snd_timer_resolution(struct snd_timer_instance *timeri)
505 {
506 	struct snd_timer * timer;
507 	unsigned long ret = 0;
508 
509 	if (timeri == NULL)
510 		return 0;
511 	timer = timeri->timer;
512 	if (timer) {
513 		guard(spinlock_irqsave)(&timer->lock);
514 		ret = snd_timer_hw_resolution(timer);
515 	}
516 	return ret;
517 }
518 EXPORT_SYMBOL(snd_timer_resolution);
519 
520 static void snd_timer_notify1(struct snd_timer_instance *ti, int event)
521 {
522 	struct snd_timer *timer = ti->timer;
523 	unsigned long resolution = 0;
524 	struct snd_timer_instance *ts;
525 	struct timespec64 tstamp;
526 
527 	if (timer_tstamp_monotonic)
528 		ktime_get_ts64(&tstamp);
529 	else
530 		ktime_get_real_ts64(&tstamp);
531 	if (snd_BUG_ON(event < SNDRV_TIMER_EVENT_START ||
532 		       event > SNDRV_TIMER_EVENT_PAUSE))
533 		return;
534 	if (timer &&
535 	    (event == SNDRV_TIMER_EVENT_START ||
536 	     event == SNDRV_TIMER_EVENT_CONTINUE))
537 		resolution = snd_timer_hw_resolution(timer);
538 	if (ti->ccallback)
539 		ti->ccallback(ti, event, &tstamp, resolution);
540 	if (ti->flags & SNDRV_TIMER_IFLG_SLAVE)
541 		return;
542 	if (timer == NULL)
543 		return;
544 	if (timer->hw.flags & SNDRV_TIMER_HW_SLAVE)
545 		return;
546 	event += 10; /* convert to SNDRV_TIMER_EVENT_MXXX */
547 	list_for_each_entry(ts, &ti->slave_active_head, active_list)
548 		if (ts->ccallback)
549 			ts->ccallback(ts, event, &tstamp, resolution);
550 }
551 
552 /* start/continue a master timer */
553 static int snd_timer_start1(struct snd_timer_instance *timeri,
554 			    bool start, unsigned long ticks)
555 {
556 	struct snd_timer *timer;
557 	int result;
558 
559 	timer = timeri->timer;
560 	if (!timer)
561 		return -EINVAL;
562 
563 	guard(spinlock_irqsave)(&timer->lock);
564 	if (timeri->flags & SNDRV_TIMER_IFLG_DEAD)
565 		return -EINVAL;
566 	if (timer->card && timer->card->shutdown)
567 		return -ENODEV;
568 	if (timeri->flags & (SNDRV_TIMER_IFLG_RUNNING |
569 			     SNDRV_TIMER_IFLG_START))
570 		return -EBUSY;
571 
572 	/* check the actual time for the start tick;
573 	 * bail out as error if it's way too low (< 100us)
574 	 */
575 	if (start && !(timer->hw.flags & SNDRV_TIMER_HW_SLAVE)) {
576 		if ((u64)snd_timer_hw_resolution(timer) * ticks < 100000)
577 			return -EINVAL;
578 	}
579 
580 	if (start)
581 		timeri->ticks = timeri->cticks = ticks;
582 	else if (!timeri->cticks)
583 		timeri->cticks = 1;
584 	timeri->pticks = 0;
585 
586 	list_move_tail(&timeri->active_list, &timer->active_list_head);
587 	if (timer->running) {
588 		if (timer->hw.flags & SNDRV_TIMER_HW_SLAVE)
589 			goto __start_now;
590 		timer->flags |= SNDRV_TIMER_FLG_RESCHED;
591 		timeri->flags |= SNDRV_TIMER_IFLG_START;
592 		result = 1; /* delayed start */
593 	} else {
594 		if (start)
595 			timer->sticks = ticks;
596 		timer->hw.start(timer);
597 	      __start_now:
598 		timer->running++;
599 		timeri->flags |= SNDRV_TIMER_IFLG_RUNNING;
600 		result = 0;
601 	}
602 	snd_timer_notify1(timeri, start ? SNDRV_TIMER_EVENT_START :
603 			  SNDRV_TIMER_EVENT_CONTINUE);
604 	return result;
605 }
606 
607 /* start/continue a slave timer */
608 static int snd_timer_start_slave(struct snd_timer_instance *timeri,
609 				 bool start)
610 {
611 	guard(spinlock_irqsave)(&slave_active_lock);
612 	if (timeri->flags & SNDRV_TIMER_IFLG_DEAD)
613 		return -EINVAL;
614 	if (timeri->flags & SNDRV_TIMER_IFLG_RUNNING)
615 		return -EBUSY;
616 	timeri->flags |= SNDRV_TIMER_IFLG_RUNNING;
617 	if (timeri->master && timeri->timer) {
618 		guard(spinlock)(&timeri->timer->lock);
619 		list_add_tail(&timeri->active_list,
620 			      &timeri->master->slave_active_head);
621 		snd_timer_notify1(timeri, start ? SNDRV_TIMER_EVENT_START :
622 				  SNDRV_TIMER_EVENT_CONTINUE);
623 	}
624 	return 1; /* delayed start */
625 }
626 
627 /* stop/pause a master timer */
628 static int snd_timer_stop1(struct snd_timer_instance *timeri, bool stop)
629 {
630 	struct snd_timer *timer;
631 
632 	timer = timeri->timer;
633 	if (!timer)
634 		return -EINVAL;
635 	guard(spinlock_irqsave)(&timer->lock);
636 	list_del_init(&timeri->ack_list);
637 	list_del_init(&timeri->active_list);
638 	if (!(timeri->flags & (SNDRV_TIMER_IFLG_RUNNING |
639 			       SNDRV_TIMER_IFLG_START)))
640 		return -EBUSY;
641 	if (timer->card && timer->card->shutdown)
642 		return 0;
643 	if (stop) {
644 		timeri->cticks = timeri->ticks;
645 		timeri->pticks = 0;
646 	}
647 	if ((timeri->flags & SNDRV_TIMER_IFLG_RUNNING) &&
648 	    !(--timer->running)) {
649 		timer->hw.stop(timer);
650 		if (timer->flags & SNDRV_TIMER_FLG_RESCHED) {
651 			timer->flags &= ~SNDRV_TIMER_FLG_RESCHED;
652 			snd_timer_reschedule(timer, 0);
653 			if (timer->flags & SNDRV_TIMER_FLG_CHANGE) {
654 				timer->flags &= ~SNDRV_TIMER_FLG_CHANGE;
655 				timer->hw.start(timer);
656 			}
657 		}
658 	}
659 	timeri->flags &= ~(SNDRV_TIMER_IFLG_RUNNING | SNDRV_TIMER_IFLG_START);
660 	if (stop)
661 		timeri->flags &= ~SNDRV_TIMER_IFLG_PAUSED;
662 	else
663 		timeri->flags |= SNDRV_TIMER_IFLG_PAUSED;
664 	snd_timer_notify1(timeri, stop ? SNDRV_TIMER_EVENT_STOP :
665 			  SNDRV_TIMER_EVENT_PAUSE);
666 	return 0;
667 }
668 
669 /* stop/pause a slave timer */
670 static int snd_timer_stop_slave(struct snd_timer_instance *timeri, bool stop)
671 {
672 	bool running;
673 
674 	guard(spinlock_irqsave)(&slave_active_lock);
675 	running = timeri->flags & SNDRV_TIMER_IFLG_RUNNING;
676 	timeri->flags &= ~SNDRV_TIMER_IFLG_RUNNING;
677 	if (timeri->timer) {
678 		guard(spinlock)(&timeri->timer->lock);
679 		list_del_init(&timeri->ack_list);
680 		list_del_init(&timeri->active_list);
681 		if (running)
682 			snd_timer_notify1(timeri, stop ? SNDRV_TIMER_EVENT_STOP :
683 					  SNDRV_TIMER_EVENT_PAUSE);
684 	}
685 	return running ? 0 : -EBUSY;
686 }
687 
688 /*
689  *  start the timer instance
690  */
691 int snd_timer_start(struct snd_timer_instance *timeri, unsigned int ticks)
692 {
693 	if (timeri == NULL || ticks < 1)
694 		return -EINVAL;
695 	if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
696 		return snd_timer_start_slave(timeri, true);
697 	else
698 		return snd_timer_start1(timeri, true, ticks);
699 }
700 EXPORT_SYMBOL(snd_timer_start);
701 
702 /*
703  * stop the timer instance.
704  *
705  * do not call this from the timer callback!
706  */
707 int snd_timer_stop(struct snd_timer_instance *timeri)
708 {
709 	if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
710 		return snd_timer_stop_slave(timeri, true);
711 	else
712 		return snd_timer_stop1(timeri, true);
713 }
714 EXPORT_SYMBOL(snd_timer_stop);
715 
716 /*
717  * start again..  the tick is kept.
718  */
719 int snd_timer_continue(struct snd_timer_instance *timeri)
720 {
721 	/* timer can continue only after pause */
722 	if (!(timeri->flags & SNDRV_TIMER_IFLG_PAUSED))
723 		return -EINVAL;
724 
725 	if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
726 		return snd_timer_start_slave(timeri, false);
727 	else
728 		return snd_timer_start1(timeri, false, 0);
729 }
730 EXPORT_SYMBOL(snd_timer_continue);
731 
732 /*
733  * pause.. remember the ticks left
734  */
735 int snd_timer_pause(struct snd_timer_instance * timeri)
736 {
737 	if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE)
738 		return snd_timer_stop_slave(timeri, false);
739 	else
740 		return snd_timer_stop1(timeri, false);
741 }
742 EXPORT_SYMBOL(snd_timer_pause);
743 
744 /*
745  * reschedule the timer
746  *
747  * start pending instances and check the scheduling ticks.
748  * when the scheduling ticks is changed set CHANGE flag to reprogram the timer.
749  */
750 static void snd_timer_reschedule(struct snd_timer * timer, unsigned long ticks_left)
751 {
752 	struct snd_timer_instance *ti;
753 	unsigned long ticks = ~0UL;
754 
755 	list_for_each_entry(ti, &timer->active_list_head, active_list) {
756 		if (ti->flags & SNDRV_TIMER_IFLG_START) {
757 			ti->flags &= ~SNDRV_TIMER_IFLG_START;
758 			ti->flags |= SNDRV_TIMER_IFLG_RUNNING;
759 			timer->running++;
760 		}
761 		if (ti->flags & SNDRV_TIMER_IFLG_RUNNING) {
762 			if (ticks > ti->cticks)
763 				ticks = ti->cticks;
764 		}
765 	}
766 	if (ticks == ~0UL) {
767 		timer->flags &= ~SNDRV_TIMER_FLG_RESCHED;
768 		return;
769 	}
770 	if (ticks > timer->hw.ticks)
771 		ticks = timer->hw.ticks;
772 	if (ticks_left != ticks)
773 		timer->flags |= SNDRV_TIMER_FLG_CHANGE;
774 	timer->sticks = ticks;
775 }
776 
777 /* call callbacks in timer ack list */
778 static void snd_timer_process_callbacks(struct snd_timer *timer,
779 					struct list_head *head)
780 {
781 	struct snd_timer_instance *ti;
782 	unsigned long resolution, ticks;
783 
784 	while (!list_empty(head)) {
785 		ti = list_first_entry(head, struct snd_timer_instance,
786 				      ack_list);
787 
788 		/* remove from ack_list and make empty */
789 		list_del_init(&ti->ack_list);
790 
791 		if (!(ti->flags & SNDRV_TIMER_IFLG_DEAD)) {
792 			ticks = ti->pticks;
793 			ti->pticks = 0;
794 			resolution = ti->resolution;
795 			ti->flags |= SNDRV_TIMER_IFLG_CALLBACK;
796 			spin_unlock(&timer->lock);
797 			if (ti->callback)
798 				ti->callback(ti, resolution, ticks);
799 			spin_lock(&timer->lock);
800 			ti->flags &= ~SNDRV_TIMER_IFLG_CALLBACK;
801 		}
802 	}
803 }
804 
805 /* clear pending instances from ack list */
806 static void snd_timer_clear_callbacks(struct snd_timer *timer,
807 				      struct list_head *head)
808 {
809 	guard(spinlock_irqsave)(&timer->lock);
810 	while (!list_empty(head))
811 		list_del_init(head->next);
812 }
813 
814 /*
815  * timer work
816  *
817  */
818 static void snd_timer_work(struct work_struct *work)
819 {
820 	struct snd_timer *timer = container_of(work, struct snd_timer, task_work);
821 
822 	if (timer->card && timer->card->shutdown) {
823 		snd_timer_clear_callbacks(timer, &timer->sack_list_head);
824 		return;
825 	}
826 
827 	guard(spinlock_irqsave)(&timer->lock);
828 	snd_timer_process_callbacks(timer, &timer->sack_list_head);
829 }
830 
831 /*
832  * timer interrupt
833  *
834  * ticks_left is usually equal to timer->sticks.
835  *
836  */
837 void snd_timer_interrupt(struct snd_timer * timer, unsigned long ticks_left)
838 {
839 	struct snd_timer_instance *ti, *ts, *tmp;
840 	unsigned long resolution;
841 	struct list_head *ack_list_head;
842 
843 	if (timer == NULL)
844 		return;
845 
846 	if (timer->card && timer->card->shutdown) {
847 		snd_timer_clear_callbacks(timer, &timer->ack_list_head);
848 		return;
849 	}
850 
851 	guard(spinlock_irqsave)(&timer->lock);
852 
853 	/* remember the current resolution */
854 	resolution = snd_timer_hw_resolution(timer);
855 
856 	/* loop for all active instances
857 	 * Here we cannot use list_for_each_entry because the active_list of a
858 	 * processed instance is relinked to done_list_head before the callback
859 	 * is called.
860 	 */
861 	list_for_each_entry_safe(ti, tmp, &timer->active_list_head,
862 				 active_list) {
863 		if (ti->flags & SNDRV_TIMER_IFLG_DEAD)
864 			continue;
865 		if (!(ti->flags & SNDRV_TIMER_IFLG_RUNNING))
866 			continue;
867 		ti->pticks += ticks_left;
868 		ti->resolution = resolution;
869 		if (ti->cticks < ticks_left)
870 			ti->cticks = 0;
871 		else
872 			ti->cticks -= ticks_left;
873 		if (ti->cticks) /* not expired */
874 			continue;
875 		if (ti->flags & SNDRV_TIMER_IFLG_AUTO) {
876 			ti->cticks = ti->ticks;
877 		} else {
878 			ti->flags &= ~SNDRV_TIMER_IFLG_RUNNING;
879 			--timer->running;
880 			list_del_init(&ti->active_list);
881 		}
882 		if ((timer->hw.flags & SNDRV_TIMER_HW_WORK) ||
883 		    (ti->flags & SNDRV_TIMER_IFLG_FAST))
884 			ack_list_head = &timer->ack_list_head;
885 		else
886 			ack_list_head = &timer->sack_list_head;
887 		if (list_empty(&ti->ack_list))
888 			list_add_tail(&ti->ack_list, ack_list_head);
889 		list_for_each_entry(ts, &ti->slave_active_head, active_list) {
890 			ts->pticks = ti->pticks;
891 			ts->resolution = resolution;
892 			if (list_empty(&ts->ack_list))
893 				list_add_tail(&ts->ack_list, ack_list_head);
894 		}
895 	}
896 	if (timer->flags & SNDRV_TIMER_FLG_RESCHED)
897 		snd_timer_reschedule(timer, timer->sticks);
898 	if (timer->running) {
899 		if (timer->hw.flags & SNDRV_TIMER_HW_STOP) {
900 			timer->hw.stop(timer);
901 			timer->flags |= SNDRV_TIMER_FLG_CHANGE;
902 		}
903 		if (!(timer->hw.flags & SNDRV_TIMER_HW_AUTO) ||
904 		    (timer->flags & SNDRV_TIMER_FLG_CHANGE)) {
905 			/* restart timer */
906 			timer->flags &= ~SNDRV_TIMER_FLG_CHANGE;
907 			timer->hw.start(timer);
908 		}
909 	} else {
910 		timer->hw.stop(timer);
911 	}
912 
913 	/* now process all fast callbacks */
914 	snd_timer_process_callbacks(timer, &timer->ack_list_head);
915 
916 	/* do we have any slow callbacks? */
917 	if (!list_empty(&timer->sack_list_head))
918 		queue_work(system_highpri_wq, &timer->task_work);
919 }
920 EXPORT_SYMBOL(snd_timer_interrupt);
921 
922 /*
923 
924  */
925 
926 int snd_timer_new(struct snd_card *card, char *id, struct snd_timer_id *tid,
927 		  struct snd_timer **rtimer)
928 {
929 	struct snd_timer *timer;
930 	int err;
931 	static const struct snd_device_ops ops = {
932 		.dev_free = snd_timer_dev_free,
933 		.dev_register = snd_timer_dev_register,
934 		.dev_disconnect = snd_timer_dev_disconnect,
935 	};
936 
937 	if (snd_BUG_ON(!tid))
938 		return -EINVAL;
939 	if (tid->dev_class == SNDRV_TIMER_CLASS_CARD ||
940 	    tid->dev_class == SNDRV_TIMER_CLASS_PCM) {
941 		if (WARN_ON(!card))
942 			return -EINVAL;
943 	}
944 	if (rtimer)
945 		*rtimer = NULL;
946 	timer = kzalloc_obj(*timer);
947 	if (!timer)
948 		return -ENOMEM;
949 	timer->tmr_class = tid->dev_class;
950 	timer->card = card;
951 	timer->tmr_device = tid->device;
952 	timer->tmr_subdevice = tid->subdevice;
953 	if (id)
954 		strscpy(timer->id, id, sizeof(timer->id));
955 	timer->sticks = 1;
956 	INIT_LIST_HEAD(&timer->device_list);
957 	INIT_LIST_HEAD(&timer->open_list_head);
958 	INIT_LIST_HEAD(&timer->active_list_head);
959 	INIT_LIST_HEAD(&timer->ack_list_head);
960 	INIT_LIST_HEAD(&timer->sack_list_head);
961 	spin_lock_init(&timer->lock);
962 	INIT_WORK(&timer->task_work, snd_timer_work);
963 	timer->max_instances = 1000; /* default limit per timer */
964 	if (card != NULL) {
965 		timer->module = card->module;
966 		err = snd_device_new(card, SNDRV_DEV_TIMER, timer, &ops);
967 		if (err < 0) {
968 			snd_timer_free(timer);
969 			return err;
970 		}
971 	}
972 	if (rtimer)
973 		*rtimer = timer;
974 	return 0;
975 }
976 EXPORT_SYMBOL(snd_timer_new);
977 
978 static int snd_timer_free(struct snd_timer *timer)
979 {
980 	struct snd_timer_instance *ti, *n;
981 
982 	if (!timer)
983 		return 0;
984 
985 	guard(mutex)(&register_mutex);
986 	if (! list_empty(&timer->open_list_head)) {
987 		list_for_each_entry_safe(ti, n, &timer->open_list_head, open_list) {
988 			struct device *card_dev_to_put = NULL;
989 
990 			snd_timer_close_locked(ti, &card_dev_to_put);
991 			put_device(card_dev_to_put);
992 		}
993 	}
994 	list_del(&timer->device_list);
995 
996 	if (timer->private_free)
997 		timer->private_free(timer);
998 	kfree(timer);
999 	return 0;
1000 }
1001 
1002 static int snd_timer_dev_free(struct snd_device *device)
1003 {
1004 	struct snd_timer *timer = device->device_data;
1005 	return snd_timer_free(timer);
1006 }
1007 
1008 static int snd_timer_dev_register(struct snd_device *dev)
1009 {
1010 	struct snd_timer *timer = dev->device_data;
1011 	struct snd_timer *timer1;
1012 	struct list_head *insert_before = &snd_timer_list;
1013 
1014 	if (snd_BUG_ON(!timer || !timer->hw.start || !timer->hw.stop))
1015 		return -ENXIO;
1016 	if (!(timer->hw.flags & SNDRV_TIMER_HW_SLAVE) &&
1017 	    !timer->hw.resolution && timer->hw.c_resolution == NULL)
1018 	    	return -EINVAL;
1019 
1020 	guard(mutex)(&register_mutex);
1021 	list_for_each_entry(timer1, &snd_timer_list, device_list) {
1022 		if (timer1->tmr_class > timer->tmr_class) {
1023 			insert_before = &timer1->device_list;
1024 			break;
1025 		}
1026 		if (timer1->tmr_class < timer->tmr_class)
1027 			continue;
1028 		if (timer1->card && timer->card) {
1029 			if (timer1->card->number > timer->card->number) {
1030 				insert_before = &timer1->device_list;
1031 				break;
1032 			}
1033 			if (timer1->card->number < timer->card->number)
1034 				continue;
1035 		}
1036 		if (timer1->tmr_device > timer->tmr_device) {
1037 			insert_before = &timer1->device_list;
1038 			break;
1039 		}
1040 		if (timer1->tmr_device < timer->tmr_device)
1041 			continue;
1042 		if (timer1->tmr_subdevice > timer->tmr_subdevice) {
1043 			insert_before = &timer1->device_list;
1044 			break;
1045 		}
1046 		if (timer1->tmr_subdevice < timer->tmr_subdevice)
1047 			continue;
1048 		/* conflicts.. */
1049 		return -EBUSY;
1050 	}
1051 	list_add_tail(&timer->device_list, insert_before);
1052 	return 0;
1053 }
1054 
1055 static int snd_timer_dev_disconnect(struct snd_device *device)
1056 {
1057 	struct snd_timer *timer = device->device_data;
1058 	struct snd_timer_instance *ti;
1059 
1060 	guard(mutex)(&register_mutex);
1061 	list_del_init(&timer->device_list);
1062 	/* wake up pending sleepers */
1063 	list_for_each_entry(ti, &timer->open_list_head, open_list) {
1064 		if (ti->disconnect)
1065 			ti->disconnect(ti);
1066 	}
1067 	return 0;
1068 }
1069 
1070 void snd_timer_notify(struct snd_timer *timer, int event, struct timespec64 *tstamp)
1071 {
1072 	unsigned long resolution = 0;
1073 	struct snd_timer_instance *ti, *ts;
1074 
1075 	if (timer->card && timer->card->shutdown)
1076 		return;
1077 	if (! (timer->hw.flags & SNDRV_TIMER_HW_SLAVE))
1078 		return;
1079 	if (snd_BUG_ON(event < SNDRV_TIMER_EVENT_MSTART ||
1080 		       event > SNDRV_TIMER_EVENT_MRESUME))
1081 		return;
1082 	guard(spinlock_irqsave)(&timer->lock);
1083 	if (event == SNDRV_TIMER_EVENT_MSTART ||
1084 	    event == SNDRV_TIMER_EVENT_MCONTINUE ||
1085 	    event == SNDRV_TIMER_EVENT_MRESUME)
1086 		resolution = snd_timer_hw_resolution(timer);
1087 	list_for_each_entry(ti, &timer->active_list_head, active_list) {
1088 		if (ti->ccallback)
1089 			ti->ccallback(ti, event, tstamp, resolution);
1090 		list_for_each_entry(ts, &ti->slave_active_head, active_list)
1091 			if (ts->ccallback)
1092 				ts->ccallback(ts, event, tstamp, resolution);
1093 	}
1094 }
1095 EXPORT_SYMBOL(snd_timer_notify);
1096 
1097 /*
1098  * exported functions for global timers
1099  */
1100 int snd_timer_global_new(char *id, int device, struct snd_timer **rtimer)
1101 {
1102 	struct snd_timer_id tid;
1103 
1104 	tid.dev_class = SNDRV_TIMER_CLASS_GLOBAL;
1105 	tid.dev_sclass = SNDRV_TIMER_SCLASS_NONE;
1106 	tid.card = -1;
1107 	tid.device = device;
1108 	tid.subdevice = 0;
1109 	return snd_timer_new(NULL, id, &tid, rtimer);
1110 }
1111 EXPORT_SYMBOL(snd_timer_global_new);
1112 
1113 int snd_timer_global_free(struct snd_timer *timer)
1114 {
1115 	return snd_timer_free(timer);
1116 }
1117 EXPORT_SYMBOL(snd_timer_global_free);
1118 
1119 int snd_timer_global_register(struct snd_timer *timer)
1120 {
1121 	struct snd_device dev;
1122 
1123 	memset(&dev, 0, sizeof(dev));
1124 	dev.device_data = timer;
1125 	return snd_timer_dev_register(&dev);
1126 }
1127 EXPORT_SYMBOL(snd_timer_global_register);
1128 
1129 /*
1130  *  System timer
1131  */
1132 
1133 struct snd_timer_system_private {
1134 	struct timer_list tlist;
1135 	struct snd_timer *snd_timer;
1136 	unsigned long last_expires;
1137 	unsigned long last_jiffies;
1138 	unsigned long correction;
1139 };
1140 
1141 static void snd_timer_s_function(struct timer_list *t)
1142 {
1143 	struct snd_timer_system_private *priv = timer_container_of(priv, t,
1144 								   tlist);
1145 	struct snd_timer *timer = priv->snd_timer;
1146 	unsigned long jiff = jiffies;
1147 	if (time_after(jiff, priv->last_expires))
1148 		priv->correction += (long)jiff - (long)priv->last_expires;
1149 	snd_timer_interrupt(timer, (long)jiff - (long)priv->last_jiffies);
1150 }
1151 
1152 static int snd_timer_s_start(struct snd_timer * timer)
1153 {
1154 	struct snd_timer_system_private *priv;
1155 	unsigned long njiff;
1156 
1157 	priv = (struct snd_timer_system_private *) timer->private_data;
1158 	njiff = (priv->last_jiffies = jiffies);
1159 	if (priv->correction > timer->sticks - 1) {
1160 		priv->correction -= timer->sticks - 1;
1161 		njiff++;
1162 	} else {
1163 		njiff += timer->sticks - priv->correction;
1164 		priv->correction = 0;
1165 	}
1166 	priv->last_expires = njiff;
1167 	mod_timer(&priv->tlist, njiff);
1168 	return 0;
1169 }
1170 
1171 static int snd_timer_s_stop(struct snd_timer * timer)
1172 {
1173 	struct snd_timer_system_private *priv;
1174 	unsigned long jiff;
1175 
1176 	priv = (struct snd_timer_system_private *) timer->private_data;
1177 	timer_delete(&priv->tlist);
1178 	jiff = jiffies;
1179 	if (time_before(jiff, priv->last_expires))
1180 		timer->sticks = priv->last_expires - jiff;
1181 	else
1182 		timer->sticks = 1;
1183 	priv->correction = 0;
1184 	return 0;
1185 }
1186 
1187 static int snd_timer_s_close(struct snd_timer *timer)
1188 {
1189 	struct snd_timer_system_private *priv;
1190 
1191 	priv = (struct snd_timer_system_private *)timer->private_data;
1192 	timer_delete_sync(&priv->tlist);
1193 	return 0;
1194 }
1195 
1196 static const struct snd_timer_hardware snd_timer_system =
1197 {
1198 	.flags =	SNDRV_TIMER_HW_FIRST | SNDRV_TIMER_HW_WORK,
1199 	.resolution =	NSEC_PER_SEC / HZ,
1200 	.ticks =	10000000L,
1201 	.close =	snd_timer_s_close,
1202 	.start =	snd_timer_s_start,
1203 	.stop =		snd_timer_s_stop
1204 };
1205 
1206 static void snd_timer_free_system(struct snd_timer *timer)
1207 {
1208 	kfree(timer->private_data);
1209 }
1210 
1211 static int snd_timer_register_system(void)
1212 {
1213 	struct snd_timer *timer;
1214 	struct snd_timer_system_private *priv;
1215 	int err;
1216 
1217 	err = snd_timer_global_new("system", SNDRV_TIMER_GLOBAL_SYSTEM, &timer);
1218 	if (err < 0)
1219 		return err;
1220 	strscpy(timer->name, "system timer");
1221 	timer->hw = snd_timer_system;
1222 	priv = kzalloc_obj(*priv);
1223 	if (priv == NULL) {
1224 		snd_timer_free(timer);
1225 		return -ENOMEM;
1226 	}
1227 	priv->snd_timer = timer;
1228 	timer_setup(&priv->tlist, snd_timer_s_function, 0);
1229 	timer->private_data = priv;
1230 	timer->private_free = snd_timer_free_system;
1231 	return snd_timer_global_register(timer);
1232 }
1233 
1234 #ifdef CONFIG_SND_PROC_FS
1235 /*
1236  *  Info interface
1237  */
1238 
1239 static void snd_timer_proc_read(struct snd_info_entry *entry,
1240 				struct snd_info_buffer *buffer)
1241 {
1242 	struct snd_timer *timer;
1243 	struct snd_timer_instance *ti;
1244 	unsigned long resolution;
1245 
1246 	guard(mutex)(&register_mutex);
1247 	list_for_each_entry(timer, &snd_timer_list, device_list) {
1248 		if (timer->card && timer->card->shutdown)
1249 			continue;
1250 		switch (timer->tmr_class) {
1251 		case SNDRV_TIMER_CLASS_GLOBAL:
1252 			snd_iprintf(buffer, "G%i: ", timer->tmr_device);
1253 			break;
1254 		case SNDRV_TIMER_CLASS_CARD:
1255 			snd_iprintf(buffer, "C%i-%i: ",
1256 				    timer->card->number, timer->tmr_device);
1257 			break;
1258 		case SNDRV_TIMER_CLASS_PCM:
1259 			snd_iprintf(buffer, "P%i-%i-%i: ", timer->card->number,
1260 				    timer->tmr_device, timer->tmr_subdevice);
1261 			break;
1262 		default:
1263 			snd_iprintf(buffer, "?%i-%i-%i-%i: ", timer->tmr_class,
1264 				    timer->card ? timer->card->number : -1,
1265 				    timer->tmr_device, timer->tmr_subdevice);
1266 		}
1267 		snd_iprintf(buffer, "%s :", timer->name);
1268 		scoped_guard(spinlock_irq, &timer->lock)
1269 			resolution = snd_timer_hw_resolution(timer);
1270 		if (resolution)
1271 			snd_iprintf(buffer, " %lu.%03luus (%lu ticks)",
1272 				    resolution / 1000,
1273 				    resolution % 1000,
1274 				    timer->hw.ticks);
1275 		if (timer->hw.flags & SNDRV_TIMER_HW_SLAVE)
1276 			snd_iprintf(buffer, " SLAVE");
1277 		snd_iprintf(buffer, "\n");
1278 		list_for_each_entry(ti, &timer->open_list_head, open_list)
1279 			snd_iprintf(buffer, "  Client %s : %s\n",
1280 				    ti->owner ? ti->owner : "unknown",
1281 				    (ti->flags & (SNDRV_TIMER_IFLG_START |
1282 						  SNDRV_TIMER_IFLG_RUNNING))
1283 				    ? "running" : "stopped");
1284 	}
1285 }
1286 
1287 static struct snd_info_entry *snd_timer_proc_entry;
1288 
1289 static void __init snd_timer_proc_init(void)
1290 {
1291 	struct snd_info_entry *entry;
1292 
1293 	entry = snd_info_create_module_entry(THIS_MODULE, "timers", NULL);
1294 	if (entry != NULL) {
1295 		entry->c.text.read = snd_timer_proc_read;
1296 		if (snd_info_register(entry) < 0) {
1297 			snd_info_free_entry(entry);
1298 			entry = NULL;
1299 		}
1300 	}
1301 	snd_timer_proc_entry = entry;
1302 }
1303 
1304 static void __exit snd_timer_proc_done(void)
1305 {
1306 	snd_info_free_entry(snd_timer_proc_entry);
1307 }
1308 #else /* !CONFIG_SND_PROC_FS */
1309 #define snd_timer_proc_init()
1310 #define snd_timer_proc_done()
1311 #endif
1312 
1313 /*
1314  *  USER SPACE interface
1315  */
1316 
1317 static void snd_timer_user_interrupt(struct snd_timer_instance *timeri,
1318 				     unsigned long resolution,
1319 				     unsigned long ticks)
1320 {
1321 	struct snd_timer_user *tu = timeri->callback_data;
1322 	struct snd_timer_read *r;
1323 	int prev;
1324 
1325 	guard(spinlock)(&tu->qlock);
1326 	if (tu->qused > 0) {
1327 		prev = tu->qtail == 0 ? tu->queue_size - 1 : tu->qtail - 1;
1328 		r = &tu->queue[prev];
1329 		if (r->resolution == resolution) {
1330 			r->ticks += ticks;
1331 			goto __wake;
1332 		}
1333 	}
1334 	if (tu->qused >= tu->queue_size) {
1335 		tu->overrun++;
1336 	} else {
1337 		r = &tu->queue[tu->qtail++];
1338 		tu->qtail %= tu->queue_size;
1339 		r->resolution = resolution;
1340 		r->ticks = ticks;
1341 		tu->qused++;
1342 	}
1343       __wake:
1344 	snd_kill_fasync(tu->fasync, SIGIO, POLL_IN);
1345 	wake_up(&tu->qchange_sleep);
1346 }
1347 
1348 static void snd_timer_user_append_to_tqueue(struct snd_timer_user *tu,
1349 					    struct snd_timer_tread64 *tread)
1350 {
1351 	if (tu->qused >= tu->queue_size) {
1352 		tu->overrun++;
1353 	} else {
1354 		memcpy(&tu->tqueue[tu->qtail++], tread, sizeof(*tread));
1355 		tu->qtail %= tu->queue_size;
1356 		tu->qused++;
1357 	}
1358 }
1359 
1360 static void snd_timer_user_ccallback(struct snd_timer_instance *timeri,
1361 				     int event,
1362 				     struct timespec64 *tstamp,
1363 				     unsigned long resolution)
1364 {
1365 	struct snd_timer_user *tu = timeri->callback_data;
1366 	struct snd_timer_tread64 r1;
1367 
1368 	if (event >= SNDRV_TIMER_EVENT_START &&
1369 	    event <= SNDRV_TIMER_EVENT_PAUSE)
1370 		tu->tstamp = *tstamp;
1371 	if ((tu->filter & (1 << event)) == 0 || !tu->tread)
1372 		return;
1373 	memset(&r1, 0, sizeof(r1));
1374 	r1.event = event;
1375 	r1.tstamp_sec = tstamp->tv_sec;
1376 	r1.tstamp_nsec = tstamp->tv_nsec;
1377 	r1.val = resolution;
1378 	scoped_guard(spinlock_irqsave, &tu->qlock)
1379 		snd_timer_user_append_to_tqueue(tu, &r1);
1380 	snd_kill_fasync(tu->fasync, SIGIO, POLL_IN);
1381 	wake_up(&tu->qchange_sleep);
1382 }
1383 
1384 static void snd_timer_user_disconnect(struct snd_timer_instance *timeri)
1385 {
1386 	struct snd_timer_user *tu = timeri->callback_data;
1387 
1388 	tu->disconnected = true;
1389 	wake_up(&tu->qchange_sleep);
1390 }
1391 
1392 static void snd_timer_user_tinterrupt(struct snd_timer_instance *timeri,
1393 				      unsigned long resolution,
1394 				      unsigned long ticks)
1395 {
1396 	struct snd_timer_user *tu = timeri->callback_data;
1397 	struct snd_timer_tread64 *r, r1;
1398 	struct timespec64 tstamp;
1399 	int prev, append = 0;
1400 
1401 	memset(&r1, 0, sizeof(r1));
1402 	memset(&tstamp, 0, sizeof(tstamp));
1403 	scoped_guard(spinlock, &tu->qlock) {
1404 		if ((tu->filter & ((1 << SNDRV_TIMER_EVENT_RESOLUTION) |
1405 				   (1 << SNDRV_TIMER_EVENT_TICK))) == 0)
1406 			return;
1407 		if (tu->last_resolution != resolution || ticks > 0) {
1408 			if (timer_tstamp_monotonic)
1409 				ktime_get_ts64(&tstamp);
1410 			else
1411 				ktime_get_real_ts64(&tstamp);
1412 		}
1413 		if ((tu->filter & (1 << SNDRV_TIMER_EVENT_RESOLUTION)) &&
1414 		    tu->last_resolution != resolution) {
1415 			r1.event = SNDRV_TIMER_EVENT_RESOLUTION;
1416 			r1.tstamp_sec = tstamp.tv_sec;
1417 			r1.tstamp_nsec = tstamp.tv_nsec;
1418 			r1.val = resolution;
1419 			snd_timer_user_append_to_tqueue(tu, &r1);
1420 			tu->last_resolution = resolution;
1421 			append++;
1422 		}
1423 		if ((tu->filter & (1 << SNDRV_TIMER_EVENT_TICK)) == 0)
1424 			break;
1425 		if (ticks == 0)
1426 			break;
1427 		if (tu->qused > 0) {
1428 			prev = tu->qtail == 0 ? tu->queue_size - 1 : tu->qtail - 1;
1429 			r = &tu->tqueue[prev];
1430 			if (r->event == SNDRV_TIMER_EVENT_TICK) {
1431 				r->tstamp_sec = tstamp.tv_sec;
1432 				r->tstamp_nsec = tstamp.tv_nsec;
1433 				r->val += ticks;
1434 				append++;
1435 				break;
1436 			}
1437 		}
1438 		r1.event = SNDRV_TIMER_EVENT_TICK;
1439 		r1.tstamp_sec = tstamp.tv_sec;
1440 		r1.tstamp_nsec = tstamp.tv_nsec;
1441 		r1.val = ticks;
1442 		snd_timer_user_append_to_tqueue(tu, &r1);
1443 		append++;
1444 	}
1445 	if (append == 0)
1446 		return;
1447 	snd_kill_fasync(tu->fasync, SIGIO, POLL_IN);
1448 	wake_up(&tu->qchange_sleep);
1449 }
1450 
1451 static int realloc_user_queue(struct snd_timer_user *tu, int size)
1452 {
1453 	struct snd_timer_read *queue = NULL;
1454 	struct snd_timer_tread64 *tqueue = NULL;
1455 
1456 	if (tu->tread) {
1457 		tqueue = kzalloc_objs(*tqueue, size);
1458 		if (!tqueue)
1459 			return -ENOMEM;
1460 	} else {
1461 		queue = kzalloc_objs(*queue, size);
1462 		if (!queue)
1463 			return -ENOMEM;
1464 	}
1465 
1466 	guard(spinlock_irq)(&tu->qlock);
1467 	kfree(tu->queue);
1468 	kfree(tu->tqueue);
1469 	tu->queue_size = size;
1470 	tu->queue = queue;
1471 	tu->tqueue = tqueue;
1472 	tu->qhead = tu->qtail = tu->qused = 0;
1473 
1474 	return 0;
1475 }
1476 
1477 static int snd_timer_user_open(struct inode *inode, struct file *file)
1478 {
1479 	struct snd_timer_user *tu;
1480 	int err;
1481 
1482 	err = stream_open(inode, file);
1483 	if (err < 0)
1484 		return err;
1485 
1486 	tu = kzalloc_obj(*tu);
1487 	if (tu == NULL)
1488 		return -ENOMEM;
1489 	spin_lock_init(&tu->qlock);
1490 	init_waitqueue_head(&tu->qchange_sleep);
1491 	mutex_init(&tu->ioctl_lock);
1492 	tu->ticks = 1;
1493 	if (realloc_user_queue(tu, 128) < 0) {
1494 		kfree(tu);
1495 		return -ENOMEM;
1496 	}
1497 	file->private_data = tu;
1498 	return 0;
1499 }
1500 
1501 static int snd_timer_user_release(struct inode *inode, struct file *file)
1502 {
1503 	struct snd_timer_user *tu;
1504 
1505 	if (file->private_data) {
1506 		tu = file->private_data;
1507 		file->private_data = NULL;
1508 		scoped_guard(mutex, &tu->ioctl_lock) {
1509 			if (tu->timeri) {
1510 				snd_timer_close(tu->timeri);
1511 				snd_timer_instance_free(tu->timeri);
1512 			}
1513 		}
1514 		snd_fasync_free(tu->fasync);
1515 		kfree(tu->queue);
1516 		kfree(tu->tqueue);
1517 		kfree(tu);
1518 	}
1519 	return 0;
1520 }
1521 
1522 static void snd_timer_user_zero_id(struct snd_timer_id *id)
1523 {
1524 	id->dev_class = SNDRV_TIMER_CLASS_NONE;
1525 	id->dev_sclass = SNDRV_TIMER_SCLASS_NONE;
1526 	id->card = -1;
1527 	id->device = -1;
1528 	id->subdevice = -1;
1529 }
1530 
1531 static void snd_timer_user_copy_id(struct snd_timer_id *id, struct snd_timer *timer)
1532 {
1533 	id->dev_class = timer->tmr_class;
1534 	id->dev_sclass = SNDRV_TIMER_SCLASS_NONE;
1535 	id->card = timer->card ? timer->card->number : -1;
1536 	id->device = timer->tmr_device;
1537 	id->subdevice = timer->tmr_subdevice;
1538 }
1539 
1540 static void get_next_device(struct snd_timer_id *id)
1541 {
1542 	struct snd_timer *timer;
1543 	struct list_head *p;
1544 
1545 	if (id->dev_class < 0) {		/* first item */
1546 		if (list_empty(&snd_timer_list))
1547 			snd_timer_user_zero_id(id);
1548 		else {
1549 			timer = list_entry(snd_timer_list.next,
1550 					   struct snd_timer, device_list);
1551 			snd_timer_user_copy_id(id, timer);
1552 		}
1553 	} else {
1554 		switch (id->dev_class) {
1555 		case SNDRV_TIMER_CLASS_GLOBAL:
1556 			id->device = id->device < 0 ? 0 : id->device + 1;
1557 			list_for_each(p, &snd_timer_list) {
1558 				timer = list_entry(p, struct snd_timer, device_list);
1559 				if (timer->tmr_class > SNDRV_TIMER_CLASS_GLOBAL) {
1560 					snd_timer_user_copy_id(id, timer);
1561 					break;
1562 				}
1563 				if (timer->tmr_device >= id->device) {
1564 					snd_timer_user_copy_id(id, timer);
1565 					break;
1566 				}
1567 			}
1568 			if (p == &snd_timer_list)
1569 				snd_timer_user_zero_id(id);
1570 			break;
1571 		case SNDRV_TIMER_CLASS_CARD:
1572 		case SNDRV_TIMER_CLASS_PCM:
1573 			if (id->card < 0) {
1574 				id->card = 0;
1575 			} else {
1576 				if (id->device < 0) {
1577 					id->device = 0;
1578 				} else {
1579 					if (id->subdevice < 0)
1580 						id->subdevice = 0;
1581 					else if (id->subdevice < INT_MAX)
1582 						id->subdevice++;
1583 				}
1584 			}
1585 			list_for_each(p, &snd_timer_list) {
1586 				timer = list_entry(p, struct snd_timer, device_list);
1587 				if (timer->tmr_class > id->dev_class) {
1588 					snd_timer_user_copy_id(id, timer);
1589 					break;
1590 				}
1591 				if (timer->tmr_class < id->dev_class)
1592 					continue;
1593 				if (timer->card->number > id->card) {
1594 					snd_timer_user_copy_id(id, timer);
1595 					break;
1596 				}
1597 				if (timer->card->number < id->card)
1598 					continue;
1599 				if (timer->tmr_device > id->device) {
1600 					snd_timer_user_copy_id(id, timer);
1601 					break;
1602 				}
1603 				if (timer->tmr_device < id->device)
1604 					continue;
1605 				if (timer->tmr_subdevice > id->subdevice) {
1606 					snd_timer_user_copy_id(id, timer);
1607 					break;
1608 				}
1609 				if (timer->tmr_subdevice < id->subdevice)
1610 					continue;
1611 				snd_timer_user_copy_id(id, timer);
1612 				break;
1613 			}
1614 			if (p == &snd_timer_list)
1615 				snd_timer_user_zero_id(id);
1616 			break;
1617 		default:
1618 			snd_timer_user_zero_id(id);
1619 		}
1620 	}
1621 }
1622 
1623 static int snd_timer_user_next_device(struct snd_timer_id __user *_tid)
1624 {
1625 	struct snd_timer_id id;
1626 
1627 	if (copy_from_user(&id, _tid, sizeof(id)))
1628 		return -EFAULT;
1629 	scoped_guard(mutex, &register_mutex)
1630 		get_next_device(&id);
1631 	if (copy_to_user(_tid, &id, sizeof(*_tid)))
1632 		return -EFAULT;
1633 	return 0;
1634 }
1635 
1636 static int snd_timer_user_ginfo(struct file *file,
1637 				struct snd_timer_ginfo __user *_ginfo)
1638 {
1639 	struct snd_timer_id tid;
1640 	struct snd_timer *t;
1641 	struct list_head *p;
1642 	struct snd_timer_ginfo *ginfo __free(kfree) =
1643 		memdup_user(_ginfo, sizeof(*ginfo));
1644 
1645 	if (IS_ERR(ginfo))
1646 		return PTR_ERR(ginfo);
1647 
1648 	tid = ginfo->tid;
1649 	memset(ginfo, 0, sizeof(*ginfo));
1650 	ginfo->tid = tid;
1651 	scoped_guard(mutex, &register_mutex) {
1652 		t = snd_timer_find(&tid);
1653 		if (!t)
1654 			return -ENODEV;
1655 		ginfo->card = t->card ? t->card->number : -1;
1656 		if (t->hw.flags & SNDRV_TIMER_HW_SLAVE)
1657 			ginfo->flags |= SNDRV_TIMER_FLG_SLAVE;
1658 		strscpy(ginfo->id, t->id, sizeof(ginfo->id));
1659 		strscpy(ginfo->name, t->name, sizeof(ginfo->name));
1660 		scoped_guard(spinlock_irq, &t->lock)
1661 			ginfo->resolution = snd_timer_hw_resolution(t);
1662 		if (t->hw.resolution_min > 0) {
1663 			ginfo->resolution_min = t->hw.resolution_min;
1664 			ginfo->resolution_max = t->hw.resolution_max;
1665 		}
1666 		list_for_each(p, &t->open_list_head) {
1667 			ginfo->clients++;
1668 		}
1669 	}
1670 	if (copy_to_user(_ginfo, ginfo, sizeof(*ginfo)))
1671 		return -EFAULT;
1672 	return 0;
1673 }
1674 
1675 static int timer_set_gparams(struct snd_timer_gparams *gparams)
1676 {
1677 	struct snd_timer *t;
1678 
1679 	guard(mutex)(&register_mutex);
1680 	t = snd_timer_find(&gparams->tid);
1681 	if (!t)
1682 		return -ENODEV;
1683 	if (!list_empty(&t->open_list_head))
1684 		return -EBUSY;
1685 	if (!t->hw.set_period)
1686 		return -ENOSYS;
1687 	return t->hw.set_period(t, gparams->period_num, gparams->period_den);
1688 }
1689 
1690 static int snd_timer_user_gparams(struct file *file,
1691 				  struct snd_timer_gparams __user *_gparams)
1692 {
1693 	struct snd_timer_gparams gparams;
1694 
1695 	if (copy_from_user(&gparams, _gparams, sizeof(gparams)))
1696 		return -EFAULT;
1697 	return timer_set_gparams(&gparams);
1698 }
1699 
1700 static int snd_timer_user_gstatus(struct file *file,
1701 				  struct snd_timer_gstatus __user *_gstatus)
1702 {
1703 	struct snd_timer_gstatus gstatus;
1704 	struct snd_timer_id tid;
1705 	struct snd_timer *t;
1706 
1707 	if (copy_from_user(&gstatus, _gstatus, sizeof(gstatus)))
1708 		return -EFAULT;
1709 	tid = gstatus.tid;
1710 	memset(&gstatus, 0, sizeof(gstatus));
1711 	gstatus.tid = tid;
1712 	scoped_guard(mutex, &register_mutex) {
1713 		t = snd_timer_find(&tid);
1714 		if (t != NULL) {
1715 			guard(spinlock_irq)(&t->lock);
1716 			gstatus.resolution = snd_timer_hw_resolution(t);
1717 			if (t->hw.precise_resolution) {
1718 				t->hw.precise_resolution(t, &gstatus.resolution_num,
1719 							 &gstatus.resolution_den);
1720 			} else {
1721 				gstatus.resolution_num = gstatus.resolution;
1722 				gstatus.resolution_den = 1000000000uL;
1723 			}
1724 		} else {
1725 			return -ENODEV;
1726 		}
1727 	}
1728 	if (copy_to_user(_gstatus, &gstatus, sizeof(gstatus)))
1729 		return -EFAULT;
1730 	return 0;
1731 }
1732 
1733 static int snd_timer_user_tselect(struct file *file,
1734 				  struct snd_timer_select __user *_tselect)
1735 {
1736 	struct snd_timer_user *tu;
1737 	struct snd_timer_select tselect;
1738 	char str[32];
1739 	int err = 0;
1740 
1741 	tu = file->private_data;
1742 	if (tu->timeri) {
1743 		snd_timer_close(tu->timeri);
1744 		snd_timer_instance_free(tu->timeri);
1745 		tu->timeri = NULL;
1746 	}
1747 	if (copy_from_user(&tselect, _tselect, sizeof(tselect))) {
1748 		err = -EFAULT;
1749 		goto __err;
1750 	}
1751 	sprintf(str, "application %i", current->pid);
1752 	if (tselect.id.dev_class != SNDRV_TIMER_CLASS_SLAVE)
1753 		tselect.id.dev_sclass = SNDRV_TIMER_SCLASS_APPLICATION;
1754 	tu->timeri = snd_timer_instance_new(str);
1755 	if (!tu->timeri) {
1756 		err = -ENOMEM;
1757 		goto __err;
1758 	}
1759 
1760 	tu->timeri->flags |= SNDRV_TIMER_IFLG_FAST;
1761 	tu->timeri->callback = tu->tread
1762 			? snd_timer_user_tinterrupt : snd_timer_user_interrupt;
1763 	tu->timeri->ccallback = snd_timer_user_ccallback;
1764 	tu->timeri->callback_data = (void *)tu;
1765 	tu->timeri->disconnect = snd_timer_user_disconnect;
1766 
1767 	err = snd_timer_open(tu->timeri, &tselect.id, current->pid);
1768 	if (err < 0) {
1769 		snd_timer_instance_free(tu->timeri);
1770 		tu->timeri = NULL;
1771 	}
1772 
1773       __err:
1774 	return err;
1775 }
1776 
1777 static int snd_timer_user_info(struct file *file,
1778 			       struct snd_timer_info __user *_info)
1779 {
1780 	struct snd_timer_user *tu;
1781 	struct snd_timer *t;
1782 
1783 	tu = file->private_data;
1784 	if (!tu->timeri)
1785 		return -EBADFD;
1786 	t = tu->timeri->timer;
1787 	if (!t)
1788 		return -EBADFD;
1789 
1790 	struct snd_timer_info *info __free(kfree) =
1791 		kzalloc(sizeof(*info), GFP_KERNEL);
1792 	if (! info)
1793 		return -ENOMEM;
1794 	info->card = t->card ? t->card->number : -1;
1795 	if (t->hw.flags & SNDRV_TIMER_HW_SLAVE)
1796 		info->flags |= SNDRV_TIMER_FLG_SLAVE;
1797 	strscpy(info->id, t->id, sizeof(info->id));
1798 	strscpy(info->name, t->name, sizeof(info->name));
1799 	scoped_guard(spinlock_irq, &t->lock)
1800 		info->resolution = snd_timer_hw_resolution(t);
1801 	if (copy_to_user(_info, info, sizeof(*_info)))
1802 		return -EFAULT;
1803 	return 0;
1804 }
1805 
1806 static int snd_timer_user_params(struct file *file,
1807 				 struct snd_timer_params __user *_params)
1808 {
1809 	struct snd_timer_user *tu;
1810 	struct snd_timer_params params;
1811 	struct snd_timer *t;
1812 	int err;
1813 
1814 	guard(mutex)(&register_mutex);
1815 	tu = file->private_data;
1816 	if (!tu->timeri)
1817 		return -EBADFD;
1818 	t = tu->timeri->timer;
1819 	if (!t)
1820 		return -EBADFD;
1821 	if (copy_from_user(&params, _params, sizeof(params)))
1822 		return -EFAULT;
1823 	if (!(t->hw.flags & SNDRV_TIMER_HW_SLAVE)) {
1824 		u64 resolution;
1825 
1826 		if (params.ticks < 1) {
1827 			err = -EINVAL;
1828 			goto _end;
1829 		}
1830 
1831 		/* Don't allow resolution less than 1ms */
1832 		resolution = snd_timer_resolution(tu->timeri);
1833 		resolution *= params.ticks;
1834 		if (resolution < 1000000) {
1835 			err = -EINVAL;
1836 			goto _end;
1837 		}
1838 	}
1839 	if (params.queue_size > 0 &&
1840 	    (params.queue_size < 32 || params.queue_size > 1024)) {
1841 		err = -EINVAL;
1842 		goto _end;
1843 	}
1844 	if (params.filter & ~((1<<SNDRV_TIMER_EVENT_RESOLUTION)|
1845 			      (1<<SNDRV_TIMER_EVENT_TICK)|
1846 			      (1<<SNDRV_TIMER_EVENT_START)|
1847 			      (1<<SNDRV_TIMER_EVENT_STOP)|
1848 			      (1<<SNDRV_TIMER_EVENT_CONTINUE)|
1849 			      (1<<SNDRV_TIMER_EVENT_PAUSE)|
1850 			      (1<<SNDRV_TIMER_EVENT_SUSPEND)|
1851 			      (1<<SNDRV_TIMER_EVENT_RESUME)|
1852 			      (1<<SNDRV_TIMER_EVENT_MSTART)|
1853 			      (1<<SNDRV_TIMER_EVENT_MSTOP)|
1854 			      (1<<SNDRV_TIMER_EVENT_MCONTINUE)|
1855 			      (1<<SNDRV_TIMER_EVENT_MPAUSE)|
1856 			      (1<<SNDRV_TIMER_EVENT_MSUSPEND)|
1857 			      (1<<SNDRV_TIMER_EVENT_MRESUME))) {
1858 		err = -EINVAL;
1859 		goto _end;
1860 	}
1861 	snd_timer_stop(tu->timeri);
1862 	scoped_guard(spinlock_irq, &t->lock) {
1863 		tu->timeri->flags &= ~(SNDRV_TIMER_IFLG_AUTO|
1864 				       SNDRV_TIMER_IFLG_EXCLUSIVE|
1865 				       SNDRV_TIMER_IFLG_EARLY_EVENT);
1866 		if (params.flags & SNDRV_TIMER_PSFLG_AUTO)
1867 			tu->timeri->flags |= SNDRV_TIMER_IFLG_AUTO;
1868 		if (params.flags & SNDRV_TIMER_PSFLG_EXCLUSIVE)
1869 			tu->timeri->flags |= SNDRV_TIMER_IFLG_EXCLUSIVE;
1870 		if (params.flags & SNDRV_TIMER_PSFLG_EARLY_EVENT)
1871 			tu->timeri->flags |= SNDRV_TIMER_IFLG_EARLY_EVENT;
1872 	}
1873 	if (params.queue_size > 0 &&
1874 	    (unsigned int)tu->queue_size != params.queue_size) {
1875 		err = realloc_user_queue(tu, params.queue_size);
1876 		if (err < 0)
1877 			goto _end;
1878 	}
1879 	scoped_guard(spinlock_irq, &tu->qlock) {
1880 		tu->qhead = tu->qtail = tu->qused = 0;
1881 		if (tu->timeri->flags & SNDRV_TIMER_IFLG_EARLY_EVENT) {
1882 			if (tu->tread) {
1883 				struct snd_timer_tread64 tread;
1884 
1885 				memset(&tread, 0, sizeof(tread));
1886 				tread.event = SNDRV_TIMER_EVENT_EARLY;
1887 				tread.tstamp_sec = 0;
1888 				tread.tstamp_nsec = 0;
1889 				tread.val = 0;
1890 				snd_timer_user_append_to_tqueue(tu, &tread);
1891 			} else {
1892 				struct snd_timer_read *r = &tu->queue[0];
1893 
1894 				r->resolution = 0;
1895 				r->ticks = 0;
1896 				tu->qused++;
1897 				tu->qtail++;
1898 			}
1899 		}
1900 		tu->filter = params.filter;
1901 		tu->ticks = params.ticks;
1902 	}
1903 	err = 0;
1904  _end:
1905 	if (copy_to_user(_params, &params, sizeof(params)))
1906 		return -EFAULT;
1907 	return err;
1908 }
1909 
1910 static int snd_timer_user_status32(struct file *file,
1911 				   struct snd_timer_status32 __user *_status)
1912  {
1913 	struct snd_timer_user *tu;
1914 	struct snd_timer_status32 status;
1915 
1916 	tu = file->private_data;
1917 	if (!tu->timeri)
1918 		return -EBADFD;
1919 	memset(&status, 0, sizeof(status));
1920 	status.tstamp_sec = tu->tstamp.tv_sec;
1921 	status.tstamp_nsec = tu->tstamp.tv_nsec;
1922 	status.resolution = snd_timer_resolution(tu->timeri);
1923 	status.lost = tu->timeri->lost;
1924 	status.overrun = tu->overrun;
1925 	scoped_guard(spinlock_irq, &tu->qlock)
1926 		status.queue = tu->qused;
1927 	if (copy_to_user(_status, &status, sizeof(status)))
1928 		return -EFAULT;
1929 	return 0;
1930 }
1931 
1932 static int snd_timer_user_status64(struct file *file,
1933 				   struct snd_timer_status64 __user *_status)
1934 {
1935 	struct snd_timer_user *tu;
1936 	struct snd_timer_status64 status;
1937 
1938 	tu = file->private_data;
1939 	if (!tu->timeri)
1940 		return -EBADFD;
1941 	memset(&status, 0, sizeof(status));
1942 	status.tstamp_sec = tu->tstamp.tv_sec;
1943 	status.tstamp_nsec = tu->tstamp.tv_nsec;
1944 	status.resolution = snd_timer_resolution(tu->timeri);
1945 	status.lost = tu->timeri->lost;
1946 	status.overrun = tu->overrun;
1947 	scoped_guard(spinlock_irq, &tu->qlock)
1948 		status.queue = tu->qused;
1949 	if (copy_to_user(_status, &status, sizeof(status)))
1950 		return -EFAULT;
1951 	return 0;
1952 }
1953 
1954 static int snd_timer_user_start(struct file *file)
1955 {
1956 	int err;
1957 	struct snd_timer_user *tu;
1958 
1959 	tu = file->private_data;
1960 	if (!tu->timeri)
1961 		return -EBADFD;
1962 	snd_timer_stop(tu->timeri);
1963 	tu->timeri->lost = 0;
1964 	tu->last_resolution = 0;
1965 	err = snd_timer_start(tu->timeri, tu->ticks);
1966 	if (err < 0)
1967 		return err;
1968 	return 0;
1969 }
1970 
1971 static int snd_timer_user_stop(struct file *file)
1972 {
1973 	int err;
1974 	struct snd_timer_user *tu;
1975 
1976 	tu = file->private_data;
1977 	if (!tu->timeri)
1978 		return -EBADFD;
1979 	err = snd_timer_stop(tu->timeri);
1980 	if (err < 0)
1981 		return err;
1982 	return 0;
1983 }
1984 
1985 static int snd_timer_user_continue(struct file *file)
1986 {
1987 	int err;
1988 	struct snd_timer_user *tu;
1989 
1990 	tu = file->private_data;
1991 	if (!tu->timeri)
1992 		return -EBADFD;
1993 	/* start timer instead of continue if it's not used before */
1994 	if (!(tu->timeri->flags & SNDRV_TIMER_IFLG_PAUSED))
1995 		return snd_timer_user_start(file);
1996 	tu->timeri->lost = 0;
1997 	err = snd_timer_continue(tu->timeri);
1998 	if (err < 0)
1999 		return err;
2000 	return 0;
2001 }
2002 
2003 static int snd_timer_user_pause(struct file *file)
2004 {
2005 	int err;
2006 	struct snd_timer_user *tu;
2007 
2008 	tu = file->private_data;
2009 	if (!tu->timeri)
2010 		return -EBADFD;
2011 	err = snd_timer_pause(tu->timeri);
2012 	if (err < 0)
2013 		return err;
2014 	return 0;
2015 }
2016 
2017 static int snd_timer_user_tread(void __user *argp, struct snd_timer_user *tu,
2018 				unsigned int cmd, bool compat)
2019 {
2020 	int __user *p = argp;
2021 	int xarg, old_tread;
2022 
2023 	if (tu->timeri)	/* too late */
2024 		return -EBUSY;
2025 	if (get_user(xarg, p))
2026 		return -EFAULT;
2027 
2028 	old_tread = tu->tread;
2029 
2030 	if (!xarg)
2031 		tu->tread = TREAD_FORMAT_NONE;
2032 	else if (cmd == SNDRV_TIMER_IOCTL_TREAD64 ||
2033 		 (IS_ENABLED(CONFIG_64BIT) && !compat))
2034 		tu->tread = TREAD_FORMAT_TIME64;
2035 	else
2036 		tu->tread = TREAD_FORMAT_TIME32;
2037 
2038 	if (tu->tread != old_tread &&
2039 	    realloc_user_queue(tu, tu->queue_size) < 0) {
2040 		tu->tread = old_tread;
2041 		return -ENOMEM;
2042 	}
2043 
2044 	return 0;
2045 }
2046 
2047 enum {
2048 	SNDRV_TIMER_IOCTL_START_OLD = _IO('T', 0x20),
2049 	SNDRV_TIMER_IOCTL_STOP_OLD = _IO('T', 0x21),
2050 	SNDRV_TIMER_IOCTL_CONTINUE_OLD = _IO('T', 0x22),
2051 	SNDRV_TIMER_IOCTL_PAUSE_OLD = _IO('T', 0x23),
2052 };
2053 
2054 #ifdef CONFIG_SND_UTIMER
2055 /*
2056  * Since userspace-driven timers are passed to userspace, we need to have an identifier
2057  * which will allow us to use them (basically, the subdevice number of udriven timer).
2058  */
2059 static DEFINE_IDA(snd_utimer_ids);
2060 
2061 static void snd_utimer_put_id(struct snd_utimer *utimer)
2062 {
2063 	int timer_id = utimer->id;
2064 
2065 	snd_BUG_ON(timer_id < 0 || timer_id >= SNDRV_UTIMERS_MAX_COUNT);
2066 	ida_free(&snd_utimer_ids, timer_id);
2067 }
2068 
2069 static int snd_utimer_take_id(void)
2070 {
2071 	return ida_alloc_max(&snd_utimer_ids, SNDRV_UTIMERS_MAX_COUNT - 1, GFP_KERNEL);
2072 }
2073 
2074 static void snd_utimer_free(struct snd_utimer *utimer)
2075 {
2076 	snd_timer_free(utimer->timer);
2077 	snd_utimer_put_id(utimer);
2078 	kfree(utimer->name);
2079 	kfree(utimer);
2080 }
2081 
2082 static int snd_utimer_release(struct inode *inode, struct file *file)
2083 {
2084 	struct snd_utimer *utimer = (struct snd_utimer *)file->private_data;
2085 
2086 	snd_utimer_free(utimer);
2087 	return 0;
2088 }
2089 
2090 static int snd_utimer_trigger(struct file *file)
2091 {
2092 	struct snd_utimer *utimer = (struct snd_utimer *)file->private_data;
2093 
2094 	snd_timer_interrupt(utimer->timer, utimer->timer->sticks);
2095 	return 0;
2096 }
2097 
2098 static long snd_utimer_ioctl(struct file *file, unsigned int ioctl, unsigned long arg)
2099 {
2100 	switch (ioctl) {
2101 	case SNDRV_TIMER_IOCTL_TRIGGER:
2102 		return snd_utimer_trigger(file);
2103 	}
2104 
2105 	return -ENOTTY;
2106 }
2107 
2108 static const struct file_operations snd_utimer_fops = {
2109 	.llseek = noop_llseek,
2110 	.release = snd_utimer_release,
2111 	.unlocked_ioctl = snd_utimer_ioctl,
2112 };
2113 
2114 static int snd_utimer_start(struct snd_timer *t)
2115 {
2116 	return 0;
2117 }
2118 
2119 static int snd_utimer_stop(struct snd_timer *t)
2120 {
2121 	return 0;
2122 }
2123 
2124 static int snd_utimer_open(struct snd_timer *t)
2125 {
2126 	return 0;
2127 }
2128 
2129 static int snd_utimer_close(struct snd_timer *t)
2130 {
2131 	return 0;
2132 }
2133 
2134 static const struct snd_timer_hardware timer_hw = {
2135 	.flags = SNDRV_TIMER_HW_AUTO | SNDRV_TIMER_HW_WORK,
2136 	.open = snd_utimer_open,
2137 	.close = snd_utimer_close,
2138 	.start = snd_utimer_start,
2139 	.stop = snd_utimer_stop,
2140 };
2141 
2142 static int snd_utimer_create(struct snd_timer_uinfo *utimer_info,
2143 			     struct snd_utimer **r_utimer)
2144 {
2145 	struct snd_utimer *utimer;
2146 	struct snd_timer *timer;
2147 	struct snd_timer_id tid;
2148 	int utimer_id;
2149 	int err = 0;
2150 
2151 	if (!utimer_info || utimer_info->resolution == 0)
2152 		return -EINVAL;
2153 
2154 	utimer = kzalloc_obj(*utimer);
2155 	if (!utimer)
2156 		return -ENOMEM;
2157 
2158 	/* We hold the ioctl lock here so we won't get a race condition when allocating id */
2159 	utimer_id = snd_utimer_take_id();
2160 	if (utimer_id < 0) {
2161 		err = utimer_id;
2162 		goto err_take_id;
2163 	}
2164 
2165 	utimer->id = utimer_id;
2166 
2167 	utimer->name = kasprintf(GFP_KERNEL, "snd-utimer%d", utimer_id);
2168 	if (!utimer->name) {
2169 		err = -ENOMEM;
2170 		goto err_get_name;
2171 	}
2172 
2173 	tid.dev_sclass = SNDRV_TIMER_SCLASS_APPLICATION;
2174 	tid.dev_class = SNDRV_TIMER_CLASS_GLOBAL;
2175 	tid.card = -1;
2176 	tid.device = SNDRV_TIMER_GLOBAL_UDRIVEN;
2177 	tid.subdevice = utimer_id;
2178 
2179 	err = snd_timer_new(NULL, utimer->name, &tid, &timer);
2180 	if (err < 0) {
2181 		pr_err("Can't create userspace-driven timer\n");
2182 		goto err_timer_new;
2183 	}
2184 
2185 	timer->module = THIS_MODULE;
2186 	timer->hw = timer_hw;
2187 	timer->hw.resolution = utimer_info->resolution;
2188 	timer->hw.ticks = 1;
2189 	timer->max_instances = MAX_SLAVE_INSTANCES;
2190 
2191 	utimer->timer = timer;
2192 
2193 	err = snd_timer_global_register(timer);
2194 	if (err < 0) {
2195 		pr_err("Can't register a userspace-driven timer\n");
2196 		goto err_timer_reg;
2197 	}
2198 
2199 	*r_utimer = utimer;
2200 	return 0;
2201 
2202 err_timer_reg:
2203 	snd_timer_free(timer);
2204 err_timer_new:
2205 	kfree(utimer->name);
2206 err_get_name:
2207 	snd_utimer_put_id(utimer);
2208 err_take_id:
2209 	kfree(utimer);
2210 
2211 	return err;
2212 }
2213 
2214 static int snd_utimer_ioctl_create(struct file *file,
2215 				   struct snd_timer_uinfo __user *_utimer_info)
2216 {
2217 	struct snd_utimer *utimer;
2218 	int err, timer_fd;
2219 	struct snd_timer_uinfo *utimer_info __free(kfree) =
2220 		memdup_user(_utimer_info, sizeof(*utimer_info));
2221 
2222 	if (IS_ERR(utimer_info))
2223 		return PTR_ERR(utimer_info);
2224 
2225 	err = snd_utimer_create(utimer_info, &utimer);
2226 	if (err < 0)
2227 		return err;
2228 
2229 	utimer_info->id = utimer->id;
2230 
2231 	timer_fd = anon_inode_getfd(utimer->name, &snd_utimer_fops, utimer, O_RDWR | O_CLOEXEC);
2232 	if (timer_fd < 0) {
2233 		snd_utimer_free(utimer);
2234 		return timer_fd;
2235 	}
2236 
2237 	utimer_info->fd = timer_fd;
2238 
2239 	err = copy_to_user(_utimer_info, utimer_info, sizeof(*utimer_info));
2240 	if (err) {
2241 		/*
2242 		 * "Leak" the fd, as there is nothing we can do about it.
2243 		 * It might have been closed already since anon_inode_getfd
2244 		 * makes it available for userspace.
2245 		 *
2246 		 * We have to rely on the process exit path to do any
2247 		 * necessary cleanup (e.g. releasing the file).
2248 		 */
2249 		return -EFAULT;
2250 	}
2251 
2252 	return 0;
2253 }
2254 
2255 #else
2256 
2257 static int snd_utimer_ioctl_create(struct file *file,
2258 				   struct snd_timer_uinfo __user *_utimer_info)
2259 {
2260 	return -ENOTTY;
2261 }
2262 
2263 #endif
2264 
2265 static long __snd_timer_user_ioctl(struct file *file, unsigned int cmd,
2266 				 unsigned long arg, bool compat)
2267 {
2268 	struct snd_timer_user *tu;
2269 	void __user *argp = (void __user *)arg;
2270 	int __user *p = argp;
2271 
2272 	tu = file->private_data;
2273 	switch (cmd) {
2274 	case SNDRV_TIMER_IOCTL_PVERSION:
2275 		return put_user(SNDRV_TIMER_VERSION, p) ? -EFAULT : 0;
2276 	case SNDRV_TIMER_IOCTL_NEXT_DEVICE:
2277 		return snd_timer_user_next_device(argp);
2278 	case SNDRV_TIMER_IOCTL_TREAD_OLD:
2279 	case SNDRV_TIMER_IOCTL_TREAD64:
2280 		return snd_timer_user_tread(argp, tu, cmd, compat);
2281 	case SNDRV_TIMER_IOCTL_GINFO:
2282 		return snd_timer_user_ginfo(file, argp);
2283 	case SNDRV_TIMER_IOCTL_GPARAMS:
2284 		return snd_timer_user_gparams(file, argp);
2285 	case SNDRV_TIMER_IOCTL_GSTATUS:
2286 		return snd_timer_user_gstatus(file, argp);
2287 	case SNDRV_TIMER_IOCTL_SELECT:
2288 		return snd_timer_user_tselect(file, argp);
2289 	case SNDRV_TIMER_IOCTL_INFO:
2290 		return snd_timer_user_info(file, argp);
2291 	case SNDRV_TIMER_IOCTL_PARAMS:
2292 		return snd_timer_user_params(file, argp);
2293 	case SNDRV_TIMER_IOCTL_STATUS32:
2294 		return snd_timer_user_status32(file, argp);
2295 	case SNDRV_TIMER_IOCTL_STATUS64:
2296 		return snd_timer_user_status64(file, argp);
2297 	case SNDRV_TIMER_IOCTL_START:
2298 	case SNDRV_TIMER_IOCTL_START_OLD:
2299 		return snd_timer_user_start(file);
2300 	case SNDRV_TIMER_IOCTL_STOP:
2301 	case SNDRV_TIMER_IOCTL_STOP_OLD:
2302 		return snd_timer_user_stop(file);
2303 	case SNDRV_TIMER_IOCTL_CONTINUE:
2304 	case SNDRV_TIMER_IOCTL_CONTINUE_OLD:
2305 		return snd_timer_user_continue(file);
2306 	case SNDRV_TIMER_IOCTL_PAUSE:
2307 	case SNDRV_TIMER_IOCTL_PAUSE_OLD:
2308 		return snd_timer_user_pause(file);
2309 	case SNDRV_TIMER_IOCTL_CREATE:
2310 		return snd_utimer_ioctl_create(file, argp);
2311 	}
2312 	return -ENOTTY;
2313 }
2314 
2315 static long snd_timer_user_ioctl(struct file *file, unsigned int cmd,
2316 				 unsigned long arg)
2317 {
2318 	struct snd_timer_user *tu = file->private_data;
2319 
2320 	guard(mutex)(&tu->ioctl_lock);
2321 	return __snd_timer_user_ioctl(file, cmd, arg, false);
2322 }
2323 
2324 static int snd_timer_user_fasync(int fd, struct file * file, int on)
2325 {
2326 	struct snd_timer_user *tu;
2327 
2328 	tu = file->private_data;
2329 	return snd_fasync_helper(fd, file, on, &tu->fasync);
2330 }
2331 
2332 static ssize_t snd_timer_user_read(struct file *file, char __user *buffer,
2333 				   size_t count, loff_t *offset)
2334 {
2335 	struct snd_timer_tread64 *tread;
2336 	struct snd_timer_tread32 tread32;
2337 	struct snd_timer_user *tu;
2338 	long result = 0, unit;
2339 	int qhead;
2340 	int err = 0;
2341 
2342 	tu = file->private_data;
2343 	switch (tu->tread) {
2344 	case TREAD_FORMAT_TIME64:
2345 		unit = sizeof(struct snd_timer_tread64);
2346 		break;
2347 	case TREAD_FORMAT_TIME32:
2348 		unit = sizeof(struct snd_timer_tread32);
2349 		break;
2350 	case TREAD_FORMAT_NONE:
2351 		unit = sizeof(struct snd_timer_read);
2352 		break;
2353 	default:
2354 		WARN_ONCE(1, "Corrupt snd_timer_user\n");
2355 		return -ENOTSUPP;
2356 	}
2357 
2358 	mutex_lock(&tu->ioctl_lock);
2359 	spin_lock_irq(&tu->qlock);
2360 	while ((long)count - result >= unit) {
2361 		while (!tu->qused) {
2362 			wait_queue_entry_t wait;
2363 
2364 			if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) {
2365 				err = -EAGAIN;
2366 				goto _error;
2367 			}
2368 
2369 			set_current_state(TASK_INTERRUPTIBLE);
2370 			init_waitqueue_entry(&wait, current);
2371 			add_wait_queue(&tu->qchange_sleep, &wait);
2372 
2373 			spin_unlock_irq(&tu->qlock);
2374 			mutex_unlock(&tu->ioctl_lock);
2375 			schedule();
2376 			mutex_lock(&tu->ioctl_lock);
2377 			spin_lock_irq(&tu->qlock);
2378 
2379 			remove_wait_queue(&tu->qchange_sleep, &wait);
2380 
2381 			if (tu->disconnected) {
2382 				err = -ENODEV;
2383 				goto _error;
2384 			}
2385 			if (signal_pending(current)) {
2386 				err = -ERESTARTSYS;
2387 				goto _error;
2388 			}
2389 		}
2390 
2391 		qhead = tu->qhead++;
2392 		tu->qhead %= tu->queue_size;
2393 		tu->qused--;
2394 		spin_unlock_irq(&tu->qlock);
2395 
2396 		tread = &tu->tqueue[qhead];
2397 
2398 		switch (tu->tread) {
2399 		case TREAD_FORMAT_TIME64:
2400 			if (copy_to_user(buffer, tread,
2401 					 sizeof(struct snd_timer_tread64)))
2402 				err = -EFAULT;
2403 			break;
2404 		case TREAD_FORMAT_TIME32:
2405 			memset(&tread32, 0, sizeof(tread32));
2406 			tread32 = (struct snd_timer_tread32) {
2407 				.event = tread->event,
2408 				.tstamp_sec = tread->tstamp_sec,
2409 				.tstamp_nsec = tread->tstamp_nsec,
2410 				.val = tread->val,
2411 			};
2412 
2413 			if (copy_to_user(buffer, &tread32, sizeof(tread32)))
2414 				err = -EFAULT;
2415 			break;
2416 		case TREAD_FORMAT_NONE:
2417 			if (copy_to_user(buffer, &tu->queue[qhead],
2418 					 sizeof(struct snd_timer_read)))
2419 				err = -EFAULT;
2420 			break;
2421 		default:
2422 			err = -ENOTSUPP;
2423 			break;
2424 		}
2425 
2426 		spin_lock_irq(&tu->qlock);
2427 		if (err < 0)
2428 			goto _error;
2429 		result += unit;
2430 		buffer += unit;
2431 	}
2432  _error:
2433 	spin_unlock_irq(&tu->qlock);
2434 	mutex_unlock(&tu->ioctl_lock);
2435 	return result > 0 ? result : err;
2436 }
2437 
2438 static __poll_t snd_timer_user_poll(struct file *file, poll_table * wait)
2439 {
2440         __poll_t mask;
2441         struct snd_timer_user *tu;
2442 
2443         tu = file->private_data;
2444 
2445         poll_wait(file, &tu->qchange_sleep, wait);
2446 
2447 	mask = 0;
2448 	guard(spinlock_irq)(&tu->qlock);
2449 	if (tu->qused)
2450 		mask |= EPOLLIN | EPOLLRDNORM;
2451 	if (tu->disconnected)
2452 		mask |= EPOLLERR;
2453 
2454 	return mask;
2455 }
2456 
2457 #ifdef CONFIG_COMPAT
2458 #include "timer_compat.c"
2459 #else
2460 #define snd_timer_user_ioctl_compat	NULL
2461 #endif
2462 
2463 static const struct file_operations snd_timer_f_ops =
2464 {
2465 	.owner =	THIS_MODULE,
2466 	.read =		snd_timer_user_read,
2467 	.open =		snd_timer_user_open,
2468 	.release =	snd_timer_user_release,
2469 	.poll =		snd_timer_user_poll,
2470 	.unlocked_ioctl =	snd_timer_user_ioctl,
2471 	.compat_ioctl =	snd_timer_user_ioctl_compat,
2472 	.fasync = 	snd_timer_user_fasync,
2473 };
2474 
2475 /* unregister the system timer */
2476 static void snd_timer_free_all(void)
2477 {
2478 	struct snd_timer *timer, *n;
2479 
2480 	list_for_each_entry_safe(timer, n, &snd_timer_list, device_list)
2481 		snd_timer_free(timer);
2482 }
2483 
2484 static struct device *timer_dev;
2485 
2486 /*
2487  *  ENTRY functions
2488  */
2489 
2490 static int __init alsa_timer_init(void)
2491 {
2492 	int err;
2493 
2494 	err = snd_device_alloc(&timer_dev, NULL);
2495 	if (err < 0)
2496 		return err;
2497 	dev_set_name(timer_dev, "timer");
2498 
2499 #ifdef SNDRV_OSS_INFO_DEV_TIMERS
2500 	snd_oss_info_register(SNDRV_OSS_INFO_DEV_TIMERS, SNDRV_CARDS - 1,
2501 			      "system timer");
2502 #endif
2503 
2504 	err = snd_timer_register_system();
2505 	if (err < 0) {
2506 		pr_err("ALSA: unable to register system timer (%i)\n", err);
2507 		goto put_timer;
2508 	}
2509 
2510 	err = snd_register_device(SNDRV_DEVICE_TYPE_TIMER, NULL, 0,
2511 				  &snd_timer_f_ops, NULL, timer_dev);
2512 	if (err < 0) {
2513 		pr_err("ALSA: unable to register timer device (%i)\n", err);
2514 		snd_timer_free_all();
2515 		goto put_timer;
2516 	}
2517 
2518 	snd_timer_proc_init();
2519 	return 0;
2520 
2521 put_timer:
2522 	put_device(timer_dev);
2523 	return err;
2524 }
2525 
2526 static void __exit alsa_timer_exit(void)
2527 {
2528 	snd_unregister_device(timer_dev);
2529 	snd_timer_free_all();
2530 	put_device(timer_dev);
2531 	snd_timer_proc_done();
2532 #ifdef SNDRV_OSS_INFO_DEV_TIMERS
2533 	snd_oss_info_unregister(SNDRV_OSS_INFO_DEV_TIMERS, SNDRV_CARDS - 1);
2534 #endif
2535 }
2536 
2537 module_init(alsa_timer_init)
2538 module_exit(alsa_timer_exit)
2539