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