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