ALSA: seq: Fix use-after-free at creating a port
[pandora-kernel.git] / sound / core / seq / seq_clientmgr.c
1 /*
2  *  ALSA sequencer Client Manager
3  *  Copyright (c) 1998-2001 by Frank van de Pol <fvdpol@coil.demon.nl>
4  *                             Jaroslav Kysela <perex@perex.cz>
5  *                             Takashi Iwai <tiwai@suse.de>
6  *
7  *
8  *   This program is free software; you can redistribute it and/or modify
9  *   it under the terms of the GNU General Public License as published by
10  *   the Free Software Foundation; either version 2 of the License, or
11  *   (at your option) any later version.
12  *
13  *   This program is distributed in the hope that it will be useful,
14  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  *   GNU General Public License for more details.
17  *
18  *   You should have received a copy of the GNU General Public License
19  *   along with this program; if not, write to the Free Software
20  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
21  *
22  */
23
24 #include <linux/init.h>
25 #include <linux/export.h>
26 #include <linux/slab.h>
27 #include <sound/core.h>
28 #include <sound/minors.h>
29 #include <linux/kmod.h>
30
31 #include <sound/seq_kernel.h>
32 #include "seq_clientmgr.h"
33 #include "seq_memory.h"
34 #include "seq_queue.h"
35 #include "seq_timer.h"
36 #include "seq_info.h"
37 #include "seq_system.h"
38 #include <sound/seq_device.h>
39 #ifdef CONFIG_COMPAT
40 #include <linux/compat.h>
41 #endif
42
43 /* Client Manager
44
45  * this module handles the connections of userland and kernel clients
46  * 
47  */
48
49 /*
50  * There are four ranges of client numbers (last two shared):
51  * 0..15: global clients
52  * 16..127: statically allocated client numbers for cards 0..27
53  * 128..191: dynamically allocated client numbers for cards 28..31
54  * 128..191: dynamically allocated client numbers for applications
55  */
56
57 /* number of kernel non-card clients */
58 #define SNDRV_SEQ_GLOBAL_CLIENTS        16
59 /* clients per cards, for static clients */
60 #define SNDRV_SEQ_CLIENTS_PER_CARD      4
61 /* dynamically allocated client numbers (both kernel drivers and user space) */
62 #define SNDRV_SEQ_DYNAMIC_CLIENTS_BEGIN 128
63
64 #define SNDRV_SEQ_LFLG_INPUT    0x0001
65 #define SNDRV_SEQ_LFLG_OUTPUT   0x0002
66 #define SNDRV_SEQ_LFLG_OPEN     (SNDRV_SEQ_LFLG_INPUT|SNDRV_SEQ_LFLG_OUTPUT)
67
68 static DEFINE_SPINLOCK(clients_lock);
69 static DEFINE_MUTEX(register_mutex);
70
71 /*
72  * client table
73  */
74 static char clienttablock[SNDRV_SEQ_MAX_CLIENTS];
75 static struct snd_seq_client *clienttab[SNDRV_SEQ_MAX_CLIENTS];
76 static struct snd_seq_usage client_usage;
77
78 /*
79  * prototypes
80  */
81 static int bounce_error_event(struct snd_seq_client *client,
82                               struct snd_seq_event *event,
83                               int err, int atomic, int hop);
84 static int snd_seq_deliver_single_event(struct snd_seq_client *client,
85                                         struct snd_seq_event *event,
86                                         int filter, int atomic, int hop);
87
88 /*
89  */
90  
91 static inline mm_segment_t snd_enter_user(void)
92 {
93         mm_segment_t fs = get_fs();
94         set_fs(get_ds());
95         return fs;
96 }
97
98 static inline void snd_leave_user(mm_segment_t fs)
99 {
100         set_fs(fs);
101 }
102
103 /*
104  */
105 static inline unsigned short snd_seq_file_flags(struct file *file)
106 {
107         switch (file->f_mode & (FMODE_READ | FMODE_WRITE)) {
108         case FMODE_WRITE:
109                 return SNDRV_SEQ_LFLG_OUTPUT;
110         case FMODE_READ:
111                 return SNDRV_SEQ_LFLG_INPUT;
112         default:
113                 return SNDRV_SEQ_LFLG_OPEN;
114         }
115 }
116
117 static inline int snd_seq_write_pool_allocated(struct snd_seq_client *client)
118 {
119         return snd_seq_total_cells(client->pool) > 0;
120 }
121
122 /* return pointer to client structure for specified id */
123 static struct snd_seq_client *clientptr(int clientid)
124 {
125         if (clientid < 0 || clientid >= SNDRV_SEQ_MAX_CLIENTS) {
126                 snd_printd("Seq: oops. Trying to get pointer to client %d\n",
127                            clientid);
128                 return NULL;
129         }
130         return clienttab[clientid];
131 }
132
133 struct snd_seq_client *snd_seq_client_use_ptr(int clientid)
134 {
135         unsigned long flags;
136         struct snd_seq_client *client;
137
138         if (clientid < 0 || clientid >= SNDRV_SEQ_MAX_CLIENTS) {
139                 snd_printd("Seq: oops. Trying to get pointer to client %d\n",
140                            clientid);
141                 return NULL;
142         }
143         spin_lock_irqsave(&clients_lock, flags);
144         client = clientptr(clientid);
145         if (client)
146                 goto __lock;
147         if (clienttablock[clientid]) {
148                 spin_unlock_irqrestore(&clients_lock, flags);
149                 return NULL;
150         }
151         spin_unlock_irqrestore(&clients_lock, flags);
152 #ifdef CONFIG_MODULES
153         if (!in_interrupt()) {
154                 static char client_requested[SNDRV_SEQ_GLOBAL_CLIENTS];
155                 static char card_requested[SNDRV_CARDS];
156                 if (clientid < SNDRV_SEQ_GLOBAL_CLIENTS) {
157                         int idx;
158                         
159                         if (!client_requested[clientid]) {
160                                 client_requested[clientid] = 1;
161                                 for (idx = 0; idx < 15; idx++) {
162                                         if (seq_client_load[idx] < 0)
163                                                 break;
164                                         if (seq_client_load[idx] == clientid) {
165                                                 request_module("snd-seq-client-%i",
166                                                                clientid);
167                                                 break;
168                                         }
169                                 }
170                         }
171                 } else if (clientid < SNDRV_SEQ_DYNAMIC_CLIENTS_BEGIN) {
172                         int card = (clientid - SNDRV_SEQ_GLOBAL_CLIENTS) /
173                                 SNDRV_SEQ_CLIENTS_PER_CARD;
174                         if (card < snd_ecards_limit) {
175                                 if (! card_requested[card]) {
176                                         card_requested[card] = 1;
177                                         snd_request_card(card);
178                                 }
179                                 snd_seq_device_load_drivers();
180                         }
181                 }
182                 spin_lock_irqsave(&clients_lock, flags);
183                 client = clientptr(clientid);
184                 if (client)
185                         goto __lock;
186                 spin_unlock_irqrestore(&clients_lock, flags);
187         }
188 #endif
189         return NULL;
190
191       __lock:
192         snd_use_lock_use(&client->use_lock);
193         spin_unlock_irqrestore(&clients_lock, flags);
194         return client;
195 }
196
197 static void usage_alloc(struct snd_seq_usage *res, int num)
198 {
199         res->cur += num;
200         if (res->cur > res->peak)
201                 res->peak = res->cur;
202 }
203
204 static void usage_free(struct snd_seq_usage *res, int num)
205 {
206         res->cur -= num;
207 }
208
209 /* initialise data structures */
210 int __init client_init_data(void)
211 {
212         /* zap out the client table */
213         memset(&clienttablock, 0, sizeof(clienttablock));
214         memset(&clienttab, 0, sizeof(clienttab));
215         return 0;
216 }
217
218
219 static struct snd_seq_client *seq_create_client1(int client_index, int poolsize)
220 {
221         unsigned long flags;
222         int c;
223         struct snd_seq_client *client;
224
225         /* init client data */
226         client = kzalloc(sizeof(*client), GFP_KERNEL);
227         if (client == NULL)
228                 return NULL;
229         client->pool = snd_seq_pool_new(poolsize);
230         if (client->pool == NULL) {
231                 kfree(client);
232                 return NULL;
233         }
234         client->type = NO_CLIENT;
235         snd_use_lock_init(&client->use_lock);
236         rwlock_init(&client->ports_lock);
237         mutex_init(&client->ports_mutex);
238         INIT_LIST_HEAD(&client->ports_list_head);
239
240         /* find free slot in the client table */
241         spin_lock_irqsave(&clients_lock, flags);
242         if (client_index < 0) {
243                 for (c = SNDRV_SEQ_DYNAMIC_CLIENTS_BEGIN;
244                      c < SNDRV_SEQ_MAX_CLIENTS;
245                      c++) {
246                         if (clienttab[c] || clienttablock[c])
247                                 continue;
248                         clienttab[client->number = c] = client;
249                         spin_unlock_irqrestore(&clients_lock, flags);
250                         return client;
251                 }
252         } else {
253                 if (clienttab[client_index] == NULL && !clienttablock[client_index]) {
254                         clienttab[client->number = client_index] = client;
255                         spin_unlock_irqrestore(&clients_lock, flags);
256                         return client;
257                 }
258         }
259         spin_unlock_irqrestore(&clients_lock, flags);
260         snd_seq_pool_delete(&client->pool);
261         kfree(client);
262         return NULL;    /* no free slot found or busy, return failure code */
263 }
264
265
266 static int seq_free_client1(struct snd_seq_client *client)
267 {
268         unsigned long flags;
269
270         if (!client)
271                 return 0;
272         snd_seq_delete_all_ports(client);
273         snd_seq_queue_client_leave(client->number);
274         spin_lock_irqsave(&clients_lock, flags);
275         clienttablock[client->number] = 1;
276         clienttab[client->number] = NULL;
277         spin_unlock_irqrestore(&clients_lock, flags);
278         snd_use_lock_sync(&client->use_lock);
279         snd_seq_queue_client_termination(client->number);
280         if (client->pool)
281                 snd_seq_pool_delete(&client->pool);
282         spin_lock_irqsave(&clients_lock, flags);
283         clienttablock[client->number] = 0;
284         spin_unlock_irqrestore(&clients_lock, flags);
285         return 0;
286 }
287
288
289 static void seq_free_client(struct snd_seq_client * client)
290 {
291         mutex_lock(&register_mutex);
292         switch (client->type) {
293         case NO_CLIENT:
294                 snd_printk(KERN_WARNING "Seq: Trying to free unused client %d\n",
295                            client->number);
296                 break;
297         case USER_CLIENT:
298         case KERNEL_CLIENT:
299                 seq_free_client1(client);
300                 usage_free(&client_usage, 1);
301                 break;
302
303         default:
304                 snd_printk(KERN_ERR "Seq: Trying to free client %d with undefined type = %d\n",
305                            client->number, client->type);
306         }
307         mutex_unlock(&register_mutex);
308
309         snd_seq_system_client_ev_client_exit(client->number);
310 }
311
312
313
314 /* -------------------------------------------------------- */
315
316 /* create a user client */
317 static int snd_seq_open(struct inode *inode, struct file *file)
318 {
319         int c, mode;                    /* client id */
320         struct snd_seq_client *client;
321         struct snd_seq_user_client *user;
322         int err;
323
324         err = nonseekable_open(inode, file);
325         if (err < 0)
326                 return err;
327
328         if (mutex_lock_interruptible(&register_mutex))
329                 return -ERESTARTSYS;
330         client = seq_create_client1(-1, SNDRV_SEQ_DEFAULT_EVENTS);
331         if (client == NULL) {
332                 mutex_unlock(&register_mutex);
333                 return -ENOMEM; /* failure code */
334         }
335
336         mode = snd_seq_file_flags(file);
337         if (mode & SNDRV_SEQ_LFLG_INPUT)
338                 client->accept_input = 1;
339         if (mode & SNDRV_SEQ_LFLG_OUTPUT)
340                 client->accept_output = 1;
341
342         user = &client->data.user;
343         user->fifo = NULL;
344         user->fifo_pool_size = 0;
345
346         if (mode & SNDRV_SEQ_LFLG_INPUT) {
347                 user->fifo_pool_size = SNDRV_SEQ_DEFAULT_CLIENT_EVENTS;
348                 user->fifo = snd_seq_fifo_new(user->fifo_pool_size);
349                 if (user->fifo == NULL) {
350                         seq_free_client1(client);
351                         kfree(client);
352                         mutex_unlock(&register_mutex);
353                         return -ENOMEM;
354                 }
355         }
356
357         usage_alloc(&client_usage, 1);
358         client->type = USER_CLIENT;
359         mutex_unlock(&register_mutex);
360
361         c = client->number;
362         file->private_data = client;
363
364         /* fill client data */
365         user->file = file;
366         sprintf(client->name, "Client-%d", c);
367
368         /* make others aware this new client */
369         snd_seq_system_client_ev_client_start(c);
370
371         return 0;
372 }
373
374 /* delete a user client */
375 static int snd_seq_release(struct inode *inode, struct file *file)
376 {
377         struct snd_seq_client *client = file->private_data;
378
379         if (client) {
380                 seq_free_client(client);
381                 if (client->data.user.fifo)
382                         snd_seq_fifo_delete(&client->data.user.fifo);
383                 kfree(client);
384         }
385
386         return 0;
387 }
388
389
390 /* handle client read() */
391 /* possible error values:
392  *      -ENXIO  invalid client or file open mode
393  *      -ENOSPC FIFO overflow (the flag is cleared after this error report)
394  *      -EINVAL no enough user-space buffer to write the whole event
395  *      -EFAULT seg. fault during copy to user space
396  */
397 static ssize_t snd_seq_read(struct file *file, char __user *buf, size_t count,
398                             loff_t *offset)
399 {
400         struct snd_seq_client *client = file->private_data;
401         struct snd_seq_fifo *fifo;
402         int err;
403         long result = 0;
404         struct snd_seq_event_cell *cell;
405
406         if (!(snd_seq_file_flags(file) & SNDRV_SEQ_LFLG_INPUT))
407                 return -ENXIO;
408
409         if (!access_ok(VERIFY_WRITE, buf, count))
410                 return -EFAULT;
411
412         /* check client structures are in place */
413         if (snd_BUG_ON(!client))
414                 return -ENXIO;
415
416         if (!client->accept_input || (fifo = client->data.user.fifo) == NULL)
417                 return -ENXIO;
418
419         if (atomic_read(&fifo->overflow) > 0) {
420                 /* buffer overflow is detected */
421                 snd_seq_fifo_clear(fifo);
422                 /* return error code */
423                 return -ENOSPC;
424         }
425
426         cell = NULL;
427         err = 0;
428         snd_seq_fifo_lock(fifo);
429
430         /* while data available in queue */
431         while (count >= sizeof(struct snd_seq_event)) {
432                 int nonblock;
433
434                 nonblock = (file->f_flags & O_NONBLOCK) || result > 0;
435                 if ((err = snd_seq_fifo_cell_out(fifo, &cell, nonblock)) < 0) {
436                         break;
437                 }
438                 if (snd_seq_ev_is_variable(&cell->event)) {
439                         struct snd_seq_event tmpev;
440                         tmpev = cell->event;
441                         tmpev.data.ext.len &= ~SNDRV_SEQ_EXT_MASK;
442                         if (copy_to_user(buf, &tmpev, sizeof(struct snd_seq_event))) {
443                                 err = -EFAULT;
444                                 break;
445                         }
446                         count -= sizeof(struct snd_seq_event);
447                         buf += sizeof(struct snd_seq_event);
448                         err = snd_seq_expand_var_event(&cell->event, count,
449                                                        (char __force *)buf, 0,
450                                                        sizeof(struct snd_seq_event));
451                         if (err < 0)
452                                 break;
453                         result += err;
454                         count -= err;
455                         buf += err;
456                 } else {
457                         if (copy_to_user(buf, &cell->event, sizeof(struct snd_seq_event))) {
458                                 err = -EFAULT;
459                                 break;
460                         }
461                         count -= sizeof(struct snd_seq_event);
462                         buf += sizeof(struct snd_seq_event);
463                 }
464                 snd_seq_cell_free(cell);
465                 cell = NULL; /* to be sure */
466                 result += sizeof(struct snd_seq_event);
467         }
468
469         if (err < 0) {
470                 if (cell)
471                         snd_seq_fifo_cell_putback(fifo, cell);
472                 if (err == -EAGAIN && result > 0)
473                         err = 0;
474         }
475         snd_seq_fifo_unlock(fifo);
476
477         return (err < 0) ? err : result;
478 }
479
480
481 /*
482  * check access permission to the port
483  */
484 static int check_port_perm(struct snd_seq_client_port *port, unsigned int flags)
485 {
486         if ((port->capability & flags) != flags)
487                 return 0;
488         return flags;
489 }
490
491 /*
492  * check if the destination client is available, and return the pointer
493  * if filter is non-zero, client filter bitmap is tested.
494  */
495 static struct snd_seq_client *get_event_dest_client(struct snd_seq_event *event,
496                                                     int filter)
497 {
498         struct snd_seq_client *dest;
499
500         dest = snd_seq_client_use_ptr(event->dest.client);
501         if (dest == NULL)
502                 return NULL;
503         if (! dest->accept_input)
504                 goto __not_avail;
505         if ((dest->filter & SNDRV_SEQ_FILTER_USE_EVENT) &&
506             ! test_bit(event->type, dest->event_filter))
507                 goto __not_avail;
508         if (filter && !(dest->filter & filter))
509                 goto __not_avail;
510
511         return dest; /* ok - accessible */
512 __not_avail:
513         snd_seq_client_unlock(dest);
514         return NULL;
515 }
516
517
518 /*
519  * Return the error event.
520  *
521  * If the receiver client is a user client, the original event is
522  * encapsulated in SNDRV_SEQ_EVENT_BOUNCE as variable length event.  If
523  * the original event is also variable length, the external data is
524  * copied after the event record. 
525  * If the receiver client is a kernel client, the original event is
526  * quoted in SNDRV_SEQ_EVENT_KERNEL_ERROR, since this requires no extra
527  * kmalloc.
528  */
529 static int bounce_error_event(struct snd_seq_client *client,
530                               struct snd_seq_event *event,
531                               int err, int atomic, int hop)
532 {
533         struct snd_seq_event bounce_ev;
534         int result;
535
536         if (client == NULL ||
537             ! (client->filter & SNDRV_SEQ_FILTER_BOUNCE) ||
538             ! client->accept_input)
539                 return 0; /* ignored */
540
541         /* set up quoted error */
542         memset(&bounce_ev, 0, sizeof(bounce_ev));
543         bounce_ev.type = SNDRV_SEQ_EVENT_KERNEL_ERROR;
544         bounce_ev.flags = SNDRV_SEQ_EVENT_LENGTH_FIXED;
545         bounce_ev.queue = SNDRV_SEQ_QUEUE_DIRECT;
546         bounce_ev.source.client = SNDRV_SEQ_CLIENT_SYSTEM;
547         bounce_ev.source.port = SNDRV_SEQ_PORT_SYSTEM_ANNOUNCE;
548         bounce_ev.dest.client = client->number;
549         bounce_ev.dest.port = event->source.port;
550         bounce_ev.data.quote.origin = event->dest;
551         bounce_ev.data.quote.event = event;
552         bounce_ev.data.quote.value = -err; /* use positive value */
553         result = snd_seq_deliver_single_event(NULL, &bounce_ev, 0, atomic, hop + 1);
554         if (result < 0) {
555                 client->event_lost++;
556                 return result;
557         }
558
559         return result;
560 }
561
562
563 /*
564  * rewrite the time-stamp of the event record with the curren time
565  * of the given queue.
566  * return non-zero if updated.
567  */
568 static int update_timestamp_of_queue(struct snd_seq_event *event,
569                                      int queue, int real_time)
570 {
571         struct snd_seq_queue *q;
572
573         q = queueptr(queue);
574         if (! q)
575                 return 0;
576         event->queue = queue;
577         event->flags &= ~SNDRV_SEQ_TIME_STAMP_MASK;
578         if (real_time) {
579                 event->time.time = snd_seq_timer_get_cur_time(q->timer);
580                 event->flags |= SNDRV_SEQ_TIME_STAMP_REAL;
581         } else {
582                 event->time.tick = snd_seq_timer_get_cur_tick(q->timer);
583                 event->flags |= SNDRV_SEQ_TIME_STAMP_TICK;
584         }
585         queuefree(q);
586         return 1;
587 }
588
589
590 /*
591  * deliver an event to the specified destination.
592  * if filter is non-zero, client filter bitmap is tested.
593  *
594  *  RETURN VALUE: 0 : if succeeded
595  *               <0 : error
596  */
597 static int snd_seq_deliver_single_event(struct snd_seq_client *client,
598                                         struct snd_seq_event *event,
599                                         int filter, int atomic, int hop)
600 {
601         struct snd_seq_client *dest = NULL;
602         struct snd_seq_client_port *dest_port = NULL;
603         int result = -ENOENT;
604         int direct;
605
606         direct = snd_seq_ev_is_direct(event);
607
608         dest = get_event_dest_client(event, filter);
609         if (dest == NULL)
610                 goto __skip;
611         dest_port = snd_seq_port_use_ptr(dest, event->dest.port);
612         if (dest_port == NULL)
613                 goto __skip;
614
615         /* check permission */
616         if (! check_port_perm(dest_port, SNDRV_SEQ_PORT_CAP_WRITE)) {
617                 result = -EPERM;
618                 goto __skip;
619         }
620                 
621         if (dest_port->timestamping)
622                 update_timestamp_of_queue(event, dest_port->time_queue,
623                                           dest_port->time_real);
624
625         switch (dest->type) {
626         case USER_CLIENT:
627                 if (dest->data.user.fifo)
628                         result = snd_seq_fifo_event_in(dest->data.user.fifo, event);
629                 break;
630
631         case KERNEL_CLIENT:
632                 if (dest_port->event_input == NULL)
633                         break;
634                 result = dest_port->event_input(event, direct,
635                                                 dest_port->private_data,
636                                                 atomic, hop);
637                 break;
638         default:
639                 break;
640         }
641
642   __skip:
643         if (dest_port)
644                 snd_seq_port_unlock(dest_port);
645         if (dest)
646                 snd_seq_client_unlock(dest);
647
648         if (result < 0 && !direct) {
649                 result = bounce_error_event(client, event, result, atomic, hop);
650         }
651         return result;
652 }
653
654
655 /*
656  * send the event to all subscribers:
657  */
658 static int deliver_to_subscribers(struct snd_seq_client *client,
659                                   struct snd_seq_event *event,
660                                   int atomic, int hop)
661 {
662         struct snd_seq_subscribers *subs;
663         int err = 0, num_ev = 0;
664         struct snd_seq_event event_saved;
665         struct snd_seq_client_port *src_port;
666         struct snd_seq_port_subs_info *grp;
667
668         src_port = snd_seq_port_use_ptr(client, event->source.port);
669         if (src_port == NULL)
670                 return -EINVAL; /* invalid source port */
671         /* save original event record */
672         event_saved = *event;
673         grp = &src_port->c_src;
674         
675         /* lock list */
676         if (atomic)
677                 read_lock(&grp->list_lock);
678         else
679                 down_read(&grp->list_mutex);
680         list_for_each_entry(subs, &grp->list_head, src_list) {
681                 /* both ports ready? */
682                 if (atomic_read(&subs->ref_count) != 2)
683                         continue;
684                 event->dest = subs->info.dest;
685                 if (subs->info.flags & SNDRV_SEQ_PORT_SUBS_TIMESTAMP)
686                         /* convert time according to flag with subscription */
687                         update_timestamp_of_queue(event, subs->info.queue,
688                                                   subs->info.flags & SNDRV_SEQ_PORT_SUBS_TIME_REAL);
689                 err = snd_seq_deliver_single_event(client, event,
690                                                    0, atomic, hop);
691                 if (err < 0)
692                         break;
693                 num_ev++;
694                 /* restore original event record */
695                 *event = event_saved;
696         }
697         if (atomic)
698                 read_unlock(&grp->list_lock);
699         else
700                 up_read(&grp->list_mutex);
701         *event = event_saved; /* restore */
702         snd_seq_port_unlock(src_port);
703         return (err < 0) ? err : num_ev;
704 }
705
706
707 #ifdef SUPPORT_BROADCAST 
708 /*
709  * broadcast to all ports:
710  */
711 static int port_broadcast_event(struct snd_seq_client *client,
712                                 struct snd_seq_event *event,
713                                 int atomic, int hop)
714 {
715         int num_ev = 0, err = 0;
716         struct snd_seq_client *dest_client;
717         struct snd_seq_client_port *port;
718
719         dest_client = get_event_dest_client(event, SNDRV_SEQ_FILTER_BROADCAST);
720         if (dest_client == NULL)
721                 return 0; /* no matching destination */
722
723         read_lock(&dest_client->ports_lock);
724         list_for_each_entry(port, &dest_client->ports_list_head, list) {
725                 event->dest.port = port->addr.port;
726                 /* pass NULL as source client to avoid error bounce */
727                 err = snd_seq_deliver_single_event(NULL, event,
728                                                    SNDRV_SEQ_FILTER_BROADCAST,
729                                                    atomic, hop);
730                 if (err < 0)
731                         break;
732                 num_ev++;
733         }
734         read_unlock(&dest_client->ports_lock);
735         snd_seq_client_unlock(dest_client);
736         event->dest.port = SNDRV_SEQ_ADDRESS_BROADCAST; /* restore */
737         return (err < 0) ? err : num_ev;
738 }
739
740 /*
741  * send the event to all clients:
742  * if destination port is also ADDRESS_BROADCAST, deliver to all ports.
743  */
744 static int broadcast_event(struct snd_seq_client *client,
745                            struct snd_seq_event *event, int atomic, int hop)
746 {
747         int err = 0, num_ev = 0;
748         int dest;
749         struct snd_seq_addr addr;
750
751         addr = event->dest; /* save */
752
753         for (dest = 0; dest < SNDRV_SEQ_MAX_CLIENTS; dest++) {
754                 /* don't send to itself */
755                 if (dest == client->number)
756                         continue;
757                 event->dest.client = dest;
758                 event->dest.port = addr.port;
759                 if (addr.port == SNDRV_SEQ_ADDRESS_BROADCAST)
760                         err = port_broadcast_event(client, event, atomic, hop);
761                 else
762                         /* pass NULL as source client to avoid error bounce */
763                         err = snd_seq_deliver_single_event(NULL, event,
764                                                            SNDRV_SEQ_FILTER_BROADCAST,
765                                                            atomic, hop);
766                 if (err < 0)
767                         break;
768                 num_ev += err;
769         }
770         event->dest = addr; /* restore */
771         return (err < 0) ? err : num_ev;
772 }
773
774
775 /* multicast - not supported yet */
776 static int multicast_event(struct snd_seq_client *client, struct snd_seq_event *event,
777                            int atomic, int hop)
778 {
779         snd_printd("seq: multicast not supported yet.\n");
780         return 0; /* ignored */
781 }
782 #endif /* SUPPORT_BROADCAST */
783
784
785 /* deliver an event to the destination port(s).
786  * if the event is to subscribers or broadcast, the event is dispatched
787  * to multiple targets.
788  *
789  * RETURN VALUE: n > 0  : the number of delivered events.
790  *               n == 0 : the event was not passed to any client.
791  *               n < 0  : error - event was not processed.
792  */
793 static int snd_seq_deliver_event(struct snd_seq_client *client, struct snd_seq_event *event,
794                                  int atomic, int hop)
795 {
796         int result;
797
798         hop++;
799         if (hop >= SNDRV_SEQ_MAX_HOPS) {
800                 snd_printd("too long delivery path (%d:%d->%d:%d)\n",
801                            event->source.client, event->source.port,
802                            event->dest.client, event->dest.port);
803                 return -EMLINK;
804         }
805
806         if (event->queue == SNDRV_SEQ_ADDRESS_SUBSCRIBERS ||
807             event->dest.client == SNDRV_SEQ_ADDRESS_SUBSCRIBERS)
808                 result = deliver_to_subscribers(client, event, atomic, hop);
809 #ifdef SUPPORT_BROADCAST
810         else if (event->queue == SNDRV_SEQ_ADDRESS_BROADCAST ||
811                  event->dest.client == SNDRV_SEQ_ADDRESS_BROADCAST)
812                 result = broadcast_event(client, event, atomic, hop);
813         else if (event->dest.client >= SNDRV_SEQ_MAX_CLIENTS)
814                 result = multicast_event(client, event, atomic, hop);
815         else if (event->dest.port == SNDRV_SEQ_ADDRESS_BROADCAST)
816                 result = port_broadcast_event(client, event, atomic, hop);
817 #endif
818         else
819                 result = snd_seq_deliver_single_event(client, event, 0, atomic, hop);
820
821         return result;
822 }
823
824 /*
825  * dispatch an event cell:
826  * This function is called only from queue check routines in timer
827  * interrupts or after enqueued.
828  * The event cell shall be released or re-queued in this function.
829  *
830  * RETURN VALUE: n > 0  : the number of delivered events.
831  *               n == 0 : the event was not passed to any client.
832  *               n < 0  : error - event was not processed.
833  */
834 int snd_seq_dispatch_event(struct snd_seq_event_cell *cell, int atomic, int hop)
835 {
836         struct snd_seq_client *client;
837         int result;
838
839         if (snd_BUG_ON(!cell))
840                 return -EINVAL;
841
842         client = snd_seq_client_use_ptr(cell->event.source.client);
843         if (client == NULL) {
844                 snd_seq_cell_free(cell); /* release this cell */
845                 return -EINVAL;
846         }
847
848         if (cell->event.type == SNDRV_SEQ_EVENT_NOTE) {
849                 /* NOTE event:
850                  * the event cell is re-used as a NOTE-OFF event and
851                  * enqueued again.
852                  */
853                 struct snd_seq_event tmpev, *ev;
854
855                 /* reserve this event to enqueue note-off later */
856                 tmpev = cell->event;
857                 tmpev.type = SNDRV_SEQ_EVENT_NOTEON;
858                 result = snd_seq_deliver_event(client, &tmpev, atomic, hop);
859
860                 /*
861                  * This was originally a note event.  We now re-use the
862                  * cell for the note-off event.
863                  */
864
865                 ev = &cell->event;
866                 ev->type = SNDRV_SEQ_EVENT_NOTEOFF;
867                 ev->flags |= SNDRV_SEQ_PRIORITY_HIGH;
868
869                 /* add the duration time */
870                 switch (ev->flags & SNDRV_SEQ_TIME_STAMP_MASK) {
871                 case SNDRV_SEQ_TIME_STAMP_TICK:
872                         ev->time.tick += ev->data.note.duration;
873                         break;
874                 case SNDRV_SEQ_TIME_STAMP_REAL:
875                         /* unit for duration is ms */
876                         ev->time.time.tv_nsec += 1000000 * (ev->data.note.duration % 1000);
877                         ev->time.time.tv_sec += ev->data.note.duration / 1000 +
878                                                 ev->time.time.tv_nsec / 1000000000;
879                         ev->time.time.tv_nsec %= 1000000000;
880                         break;
881                 }
882                 ev->data.note.velocity = ev->data.note.off_velocity;
883
884                 /* Now queue this cell as the note off event */
885                 if (snd_seq_enqueue_event(cell, atomic, hop) < 0)
886                         snd_seq_cell_free(cell); /* release this cell */
887
888         } else {
889                 /* Normal events:
890                  * event cell is freed after processing the event
891                  */
892
893                 result = snd_seq_deliver_event(client, &cell->event, atomic, hop);
894                 snd_seq_cell_free(cell);
895         }
896
897         snd_seq_client_unlock(client);
898         return result;
899 }
900
901
902 /* Allocate a cell from client pool and enqueue it to queue:
903  * if pool is empty and blocking is TRUE, sleep until a new cell is
904  * available.
905  */
906 static int snd_seq_client_enqueue_event(struct snd_seq_client *client,
907                                         struct snd_seq_event *event,
908                                         struct file *file, int blocking,
909                                         int atomic, int hop)
910 {
911         struct snd_seq_event_cell *cell;
912         int err;
913
914         /* special queue values - force direct passing */
915         if (event->queue == SNDRV_SEQ_ADDRESS_SUBSCRIBERS) {
916                 event->dest.client = SNDRV_SEQ_ADDRESS_SUBSCRIBERS;
917                 event->queue = SNDRV_SEQ_QUEUE_DIRECT;
918         } else
919 #ifdef SUPPORT_BROADCAST
920                 if (event->queue == SNDRV_SEQ_ADDRESS_BROADCAST) {
921                         event->dest.client = SNDRV_SEQ_ADDRESS_BROADCAST;
922                         event->queue = SNDRV_SEQ_QUEUE_DIRECT;
923                 }
924 #endif
925         if (event->dest.client == SNDRV_SEQ_ADDRESS_SUBSCRIBERS) {
926                 /* check presence of source port */
927                 struct snd_seq_client_port *src_port = snd_seq_port_use_ptr(client, event->source.port);
928                 if (src_port == NULL)
929                         return -EINVAL;
930                 snd_seq_port_unlock(src_port);
931         }
932
933         /* direct event processing without enqueued */
934         if (snd_seq_ev_is_direct(event)) {
935                 if (event->type == SNDRV_SEQ_EVENT_NOTE)
936                         return -EINVAL; /* this event must be enqueued! */
937                 return snd_seq_deliver_event(client, event, atomic, hop);
938         }
939
940         /* Not direct, normal queuing */
941         if (snd_seq_queue_is_used(event->queue, client->number) <= 0)
942                 return -EINVAL;  /* invalid queue */
943         if (! snd_seq_write_pool_allocated(client))
944                 return -ENXIO; /* queue is not allocated */
945
946         /* allocate an event cell */
947         err = snd_seq_event_dup(client->pool, event, &cell, !blocking || atomic, file);
948         if (err < 0)
949                 return err;
950
951         /* we got a cell. enqueue it. */
952         if ((err = snd_seq_enqueue_event(cell, atomic, hop)) < 0) {
953                 snd_seq_cell_free(cell);
954                 return err;
955         }
956
957         return 0;
958 }
959
960
961 /*
962  * check validity of event type and data length.
963  * return non-zero if invalid.
964  */
965 static int check_event_type_and_length(struct snd_seq_event *ev)
966 {
967         switch (snd_seq_ev_length_type(ev)) {
968         case SNDRV_SEQ_EVENT_LENGTH_FIXED:
969                 if (snd_seq_ev_is_variable_type(ev))
970                         return -EINVAL;
971                 break;
972         case SNDRV_SEQ_EVENT_LENGTH_VARIABLE:
973                 if (! snd_seq_ev_is_variable_type(ev) ||
974                     (ev->data.ext.len & ~SNDRV_SEQ_EXT_MASK) >= SNDRV_SEQ_MAX_EVENT_LEN)
975                         return -EINVAL;
976                 break;
977         case SNDRV_SEQ_EVENT_LENGTH_VARUSR:
978                 if (! snd_seq_ev_is_direct(ev))
979                         return -EINVAL;
980                 break;
981         }
982         return 0;
983 }
984
985
986 /* handle write() */
987 /* possible error values:
988  *      -ENXIO  invalid client or file open mode
989  *      -ENOMEM malloc failed
990  *      -EFAULT seg. fault during copy from user space
991  *      -EINVAL invalid event
992  *      -EAGAIN no space in output pool
993  *      -EINTR  interrupts while sleep
994  *      -EMLINK too many hops
995  *      others  depends on return value from driver callback
996  */
997 static ssize_t snd_seq_write(struct file *file, const char __user *buf,
998                              size_t count, loff_t *offset)
999 {
1000         struct snd_seq_client *client = file->private_data;
1001         int written = 0, len;
1002         int err = -EINVAL;
1003         struct snd_seq_event event;
1004
1005         if (!(snd_seq_file_flags(file) & SNDRV_SEQ_LFLG_OUTPUT))
1006                 return -ENXIO;
1007
1008         /* check client structures are in place */
1009         if (snd_BUG_ON(!client))
1010                 return -ENXIO;
1011                 
1012         if (!client->accept_output || client->pool == NULL)
1013                 return -ENXIO;
1014
1015         /* allocate the pool now if the pool is not allocated yet */ 
1016         if (client->pool->size > 0 && !snd_seq_write_pool_allocated(client)) {
1017                 if (snd_seq_pool_init(client->pool) < 0)
1018                         return -ENOMEM;
1019         }
1020
1021         /* only process whole events */
1022         while (count >= sizeof(struct snd_seq_event)) {
1023                 /* Read in the event header from the user */
1024                 len = sizeof(event);
1025                 if (copy_from_user(&event, buf, len)) {
1026                         err = -EFAULT;
1027                         break;
1028                 }
1029                 event.source.client = client->number;   /* fill in client number */
1030                 /* Check for extension data length */
1031                 if (check_event_type_and_length(&event)) {
1032                         err = -EINVAL;
1033                         break;
1034                 }
1035
1036                 /* check for special events */
1037                 if (event.type == SNDRV_SEQ_EVENT_NONE)
1038                         goto __skip_event;
1039                 else if (snd_seq_ev_is_reserved(&event)) {
1040                         err = -EINVAL;
1041                         break;
1042                 }
1043
1044                 if (snd_seq_ev_is_variable(&event)) {
1045                         int extlen = event.data.ext.len & ~SNDRV_SEQ_EXT_MASK;
1046                         if ((size_t)(extlen + len) > count) {
1047                                 /* back out, will get an error this time or next */
1048                                 err = -EINVAL;
1049                                 break;
1050                         }
1051                         /* set user space pointer */
1052                         event.data.ext.len = extlen | SNDRV_SEQ_EXT_USRPTR;
1053                         event.data.ext.ptr = (char __force *)buf
1054                                                 + sizeof(struct snd_seq_event);
1055                         len += extlen; /* increment data length */
1056                 } else {
1057 #ifdef CONFIG_COMPAT
1058                         if (client->convert32 && snd_seq_ev_is_varusr(&event)) {
1059                                 void *ptr = (void __force *)compat_ptr(event.data.raw32.d[1]);
1060                                 event.data.ext.ptr = ptr;
1061                         }
1062 #endif
1063                 }
1064
1065                 /* ok, enqueue it */
1066                 err = snd_seq_client_enqueue_event(client, &event, file,
1067                                                    !(file->f_flags & O_NONBLOCK),
1068                                                    0, 0);
1069                 if (err < 0)
1070                         break;
1071
1072         __skip_event:
1073                 /* Update pointers and counts */
1074                 count -= len;
1075                 buf += len;
1076                 written += len;
1077         }
1078
1079         return written ? written : err;
1080 }
1081
1082
1083 /*
1084  * handle polling
1085  */
1086 static unsigned int snd_seq_poll(struct file *file, poll_table * wait)
1087 {
1088         struct snd_seq_client *client = file->private_data;
1089         unsigned int mask = 0;
1090
1091         /* check client structures are in place */
1092         if (snd_BUG_ON(!client))
1093                 return -ENXIO;
1094
1095         if ((snd_seq_file_flags(file) & SNDRV_SEQ_LFLG_INPUT) &&
1096             client->data.user.fifo) {
1097
1098                 /* check if data is available in the outqueue */
1099                 if (snd_seq_fifo_poll_wait(client->data.user.fifo, file, wait))
1100                         mask |= POLLIN | POLLRDNORM;
1101         }
1102
1103         if (snd_seq_file_flags(file) & SNDRV_SEQ_LFLG_OUTPUT) {
1104
1105                 /* check if data is available in the pool */
1106                 if (!snd_seq_write_pool_allocated(client) ||
1107                     snd_seq_pool_poll_wait(client->pool, file, wait))
1108                         mask |= POLLOUT | POLLWRNORM;
1109         }
1110
1111         return mask;
1112 }
1113
1114
1115 /*-----------------------------------------------------*/
1116
1117
1118 /* SYSTEM_INFO ioctl() */
1119 static int snd_seq_ioctl_system_info(struct snd_seq_client *client, void __user *arg)
1120 {
1121         struct snd_seq_system_info info;
1122
1123         memset(&info, 0, sizeof(info));
1124         /* fill the info fields */
1125         info.queues = SNDRV_SEQ_MAX_QUEUES;
1126         info.clients = SNDRV_SEQ_MAX_CLIENTS;
1127         info.ports = 256;       /* fixed limit */
1128         info.channels = 256;    /* fixed limit */
1129         info.cur_clients = client_usage.cur;
1130         info.cur_queues = snd_seq_queue_get_cur_queues();
1131
1132         if (copy_to_user(arg, &info, sizeof(info)))
1133                 return -EFAULT;
1134         return 0;
1135 }
1136
1137
1138 /* RUNNING_MODE ioctl() */
1139 static int snd_seq_ioctl_running_mode(struct snd_seq_client *client, void __user *arg)
1140 {
1141         struct snd_seq_running_info info;
1142         struct snd_seq_client *cptr;
1143         int err = 0;
1144
1145         if (copy_from_user(&info, arg, sizeof(info)))
1146                 return -EFAULT;
1147
1148         /* requested client number */
1149         cptr = snd_seq_client_use_ptr(info.client);
1150         if (cptr == NULL)
1151                 return -ENOENT;         /* don't change !!! */
1152
1153 #ifdef SNDRV_BIG_ENDIAN
1154         if (! info.big_endian) {
1155                 err = -EINVAL;
1156                 goto __err;
1157         }
1158 #else
1159         if (info.big_endian) {
1160                 err = -EINVAL;
1161                 goto __err;
1162         }
1163
1164 #endif
1165         if (info.cpu_mode > sizeof(long)) {
1166                 err = -EINVAL;
1167                 goto __err;
1168         }
1169         cptr->convert32 = (info.cpu_mode < sizeof(long));
1170  __err:
1171         snd_seq_client_unlock(cptr);
1172         return err;
1173 }
1174
1175 /* CLIENT_INFO ioctl() */
1176 static void get_client_info(struct snd_seq_client *cptr,
1177                             struct snd_seq_client_info *info)
1178 {
1179         info->client = cptr->number;
1180
1181         /* fill the info fields */
1182         info->type = cptr->type;
1183         strcpy(info->name, cptr->name);
1184         info->filter = cptr->filter;
1185         info->event_lost = cptr->event_lost;
1186         memcpy(info->event_filter, cptr->event_filter, 32);
1187         info->num_ports = cptr->num_ports;
1188         memset(info->reserved, 0, sizeof(info->reserved));
1189 }
1190
1191 static int snd_seq_ioctl_get_client_info(struct snd_seq_client *client,
1192                                          void __user *arg)
1193 {
1194         struct snd_seq_client *cptr;
1195         struct snd_seq_client_info client_info;
1196
1197         if (copy_from_user(&client_info, arg, sizeof(client_info)))
1198                 return -EFAULT;
1199
1200         /* requested client number */
1201         cptr = snd_seq_client_use_ptr(client_info.client);
1202         if (cptr == NULL)
1203                 return -ENOENT;         /* don't change !!! */
1204
1205         get_client_info(cptr, &client_info);
1206         snd_seq_client_unlock(cptr);
1207
1208         if (copy_to_user(arg, &client_info, sizeof(client_info)))
1209                 return -EFAULT;
1210         return 0;
1211 }
1212
1213
1214 /* CLIENT_INFO ioctl() */
1215 static int snd_seq_ioctl_set_client_info(struct snd_seq_client *client,
1216                                          void __user *arg)
1217 {
1218         struct snd_seq_client_info client_info;
1219
1220         if (copy_from_user(&client_info, arg, sizeof(client_info)))
1221                 return -EFAULT;
1222
1223         /* it is not allowed to set the info fields for an another client */
1224         if (client->number != client_info.client)
1225                 return -EPERM;
1226         /* also client type must be set now */
1227         if (client->type != client_info.type)
1228                 return -EINVAL;
1229
1230         /* fill the info fields */
1231         if (client_info.name[0])
1232                 strlcpy(client->name, client_info.name, sizeof(client->name));
1233
1234         client->filter = client_info.filter;
1235         client->event_lost = client_info.event_lost;
1236         memcpy(client->event_filter, client_info.event_filter, 32);
1237
1238         return 0;
1239 }
1240
1241
1242 /* 
1243  * CREATE PORT ioctl() 
1244  */
1245 static int snd_seq_ioctl_create_port(struct snd_seq_client *client,
1246                                      void __user *arg)
1247 {
1248         struct snd_seq_client_port *port;
1249         struct snd_seq_port_info info;
1250         struct snd_seq_port_callback *callback;
1251         int port_idx;
1252
1253         if (copy_from_user(&info, arg, sizeof(info)))
1254                 return -EFAULT;
1255
1256         /* it is not allowed to create the port for an another client */
1257         if (info.addr.client != client->number)
1258                 return -EPERM;
1259
1260         port = snd_seq_create_port(client, (info.flags & SNDRV_SEQ_PORT_FLG_GIVEN_PORT) ? info.addr.port : -1);
1261         if (port == NULL)
1262                 return -ENOMEM;
1263
1264         if (client->type == USER_CLIENT && info.kernel) {
1265                 port_idx = port->addr.port;
1266                 snd_seq_port_unlock(port);
1267                 snd_seq_delete_port(client, port_idx);
1268                 return -EINVAL;
1269         }
1270         if (client->type == KERNEL_CLIENT) {
1271                 if ((callback = info.kernel) != NULL) {
1272                         if (callback->owner)
1273                                 port->owner = callback->owner;
1274                         port->private_data = callback->private_data;
1275                         port->private_free = callback->private_free;
1276                         port->callback_all = callback->callback_all;
1277                         port->event_input = callback->event_input;
1278                         port->c_src.open = callback->subscribe;
1279                         port->c_src.close = callback->unsubscribe;
1280                         port->c_dest.open = callback->use;
1281                         port->c_dest.close = callback->unuse;
1282                 }
1283         }
1284
1285         info.addr = port->addr;
1286
1287         snd_seq_set_port_info(port, &info);
1288         snd_seq_system_client_ev_port_start(port->addr.client, port->addr.port);
1289         snd_seq_port_unlock(port);
1290
1291         if (copy_to_user(arg, &info, sizeof(info)))
1292                 return -EFAULT;
1293
1294         return 0;
1295 }
1296
1297 /* 
1298  * DELETE PORT ioctl() 
1299  */
1300 static int snd_seq_ioctl_delete_port(struct snd_seq_client *client,
1301                                      void __user *arg)
1302 {
1303         struct snd_seq_port_info info;
1304         int err;
1305
1306         /* set passed parameters */
1307         if (copy_from_user(&info, arg, sizeof(info)))
1308                 return -EFAULT;
1309         
1310         /* it is not allowed to remove the port for an another client */
1311         if (info.addr.client != client->number)
1312                 return -EPERM;
1313
1314         err = snd_seq_delete_port(client, info.addr.port);
1315         if (err >= 0)
1316                 snd_seq_system_client_ev_port_exit(client->number, info.addr.port);
1317         return err;
1318 }
1319
1320
1321 /* 
1322  * GET_PORT_INFO ioctl() (on any client) 
1323  */
1324 static int snd_seq_ioctl_get_port_info(struct snd_seq_client *client,
1325                                        void __user *arg)
1326 {
1327         struct snd_seq_client *cptr;
1328         struct snd_seq_client_port *port;
1329         struct snd_seq_port_info info;
1330
1331         if (copy_from_user(&info, arg, sizeof(info)))
1332                 return -EFAULT;
1333         cptr = snd_seq_client_use_ptr(info.addr.client);
1334         if (cptr == NULL)
1335                 return -ENXIO;
1336
1337         port = snd_seq_port_use_ptr(cptr, info.addr.port);
1338         if (port == NULL) {
1339                 snd_seq_client_unlock(cptr);
1340                 return -ENOENT;                 /* don't change */
1341         }
1342
1343         /* get port info */
1344         snd_seq_get_port_info(port, &info);
1345         snd_seq_port_unlock(port);
1346         snd_seq_client_unlock(cptr);
1347
1348         if (copy_to_user(arg, &info, sizeof(info)))
1349                 return -EFAULT;
1350         return 0;
1351 }
1352
1353
1354 /* 
1355  * SET_PORT_INFO ioctl() (only ports on this/own client) 
1356  */
1357 static int snd_seq_ioctl_set_port_info(struct snd_seq_client *client,
1358                                        void __user *arg)
1359 {
1360         struct snd_seq_client_port *port;
1361         struct snd_seq_port_info info;
1362
1363         if (copy_from_user(&info, arg, sizeof(info)))
1364                 return -EFAULT;
1365
1366         if (info.addr.client != client->number) /* only set our own ports ! */
1367                 return -EPERM;
1368         port = snd_seq_port_use_ptr(client, info.addr.port);
1369         if (port) {
1370                 snd_seq_set_port_info(port, &info);
1371                 snd_seq_port_unlock(port);
1372         }
1373         return 0;
1374 }
1375
1376
1377 /*
1378  * port subscription (connection)
1379  */
1380 #define PERM_RD         (SNDRV_SEQ_PORT_CAP_READ|SNDRV_SEQ_PORT_CAP_SUBS_READ)
1381 #define PERM_WR         (SNDRV_SEQ_PORT_CAP_WRITE|SNDRV_SEQ_PORT_CAP_SUBS_WRITE)
1382
1383 static int check_subscription_permission(struct snd_seq_client *client,
1384                                          struct snd_seq_client_port *sport,
1385                                          struct snd_seq_client_port *dport,
1386                                          struct snd_seq_port_subscribe *subs)
1387 {
1388         if (client->number != subs->sender.client &&
1389             client->number != subs->dest.client) {
1390                 /* connection by third client - check export permission */
1391                 if (check_port_perm(sport, SNDRV_SEQ_PORT_CAP_NO_EXPORT))
1392                         return -EPERM;
1393                 if (check_port_perm(dport, SNDRV_SEQ_PORT_CAP_NO_EXPORT))
1394                         return -EPERM;
1395         }
1396
1397         /* check read permission */
1398         /* if sender or receiver is the subscribing client itself,
1399          * no permission check is necessary
1400          */
1401         if (client->number != subs->sender.client) {
1402                 if (! check_port_perm(sport, PERM_RD))
1403                         return -EPERM;
1404         }
1405         /* check write permission */
1406         if (client->number != subs->dest.client) {
1407                 if (! check_port_perm(dport, PERM_WR))
1408                         return -EPERM;
1409         }
1410         return 0;
1411 }
1412
1413 /*
1414  * send an subscription notify event to user client:
1415  * client must be user client.
1416  */
1417 int snd_seq_client_notify_subscription(int client, int port,
1418                                        struct snd_seq_port_subscribe *info,
1419                                        int evtype)
1420 {
1421         struct snd_seq_event event;
1422
1423         memset(&event, 0, sizeof(event));
1424         event.type = evtype;
1425         event.data.connect.dest = info->dest;
1426         event.data.connect.sender = info->sender;
1427
1428         return snd_seq_system_notify(client, port, &event);  /* non-atomic */
1429 }
1430
1431
1432 /* 
1433  * add to port's subscription list IOCTL interface 
1434  */
1435 static int snd_seq_ioctl_subscribe_port(struct snd_seq_client *client,
1436                                         void __user *arg)
1437 {
1438         int result = -EINVAL;
1439         struct snd_seq_client *receiver = NULL, *sender = NULL;
1440         struct snd_seq_client_port *sport = NULL, *dport = NULL;
1441         struct snd_seq_port_subscribe subs;
1442
1443         if (copy_from_user(&subs, arg, sizeof(subs)))
1444                 return -EFAULT;
1445
1446         if ((receiver = snd_seq_client_use_ptr(subs.dest.client)) == NULL)
1447                 goto __end;
1448         if ((sender = snd_seq_client_use_ptr(subs.sender.client)) == NULL)
1449                 goto __end;
1450         if ((sport = snd_seq_port_use_ptr(sender, subs.sender.port)) == NULL)
1451                 goto __end;
1452         if ((dport = snd_seq_port_use_ptr(receiver, subs.dest.port)) == NULL)
1453                 goto __end;
1454
1455         result = check_subscription_permission(client, sport, dport, &subs);
1456         if (result < 0)
1457                 goto __end;
1458
1459         /* connect them */
1460         result = snd_seq_port_connect(client, sender, sport, receiver, dport, &subs);
1461         if (! result) /* broadcast announce */
1462                 snd_seq_client_notify_subscription(SNDRV_SEQ_ADDRESS_SUBSCRIBERS, 0,
1463                                                    &subs, SNDRV_SEQ_EVENT_PORT_SUBSCRIBED);
1464       __end:
1465         if (sport)
1466                 snd_seq_port_unlock(sport);
1467         if (dport)
1468                 snd_seq_port_unlock(dport);
1469         if (sender)
1470                 snd_seq_client_unlock(sender);
1471         if (receiver)
1472                 snd_seq_client_unlock(receiver);
1473         return result;
1474 }
1475
1476
1477 /* 
1478  * remove from port's subscription list 
1479  */
1480 static int snd_seq_ioctl_unsubscribe_port(struct snd_seq_client *client,
1481                                           void __user *arg)
1482 {
1483         int result = -ENXIO;
1484         struct snd_seq_client *receiver = NULL, *sender = NULL;
1485         struct snd_seq_client_port *sport = NULL, *dport = NULL;
1486         struct snd_seq_port_subscribe subs;
1487
1488         if (copy_from_user(&subs, arg, sizeof(subs)))
1489                 return -EFAULT;
1490
1491         if ((receiver = snd_seq_client_use_ptr(subs.dest.client)) == NULL)
1492                 goto __end;
1493         if ((sender = snd_seq_client_use_ptr(subs.sender.client)) == NULL)
1494                 goto __end;
1495         if ((sport = snd_seq_port_use_ptr(sender, subs.sender.port)) == NULL)
1496                 goto __end;
1497         if ((dport = snd_seq_port_use_ptr(receiver, subs.dest.port)) == NULL)
1498                 goto __end;
1499
1500         result = check_subscription_permission(client, sport, dport, &subs);
1501         if (result < 0)
1502                 goto __end;
1503
1504         result = snd_seq_port_disconnect(client, sender, sport, receiver, dport, &subs);
1505         if (! result) /* broadcast announce */
1506                 snd_seq_client_notify_subscription(SNDRV_SEQ_ADDRESS_SUBSCRIBERS, 0,
1507                                                    &subs, SNDRV_SEQ_EVENT_PORT_UNSUBSCRIBED);
1508       __end:
1509         if (sport)
1510                 snd_seq_port_unlock(sport);
1511         if (dport)
1512                 snd_seq_port_unlock(dport);
1513         if (sender)
1514                 snd_seq_client_unlock(sender);
1515         if (receiver)
1516                 snd_seq_client_unlock(receiver);
1517         return result;
1518 }
1519
1520
1521 /* CREATE_QUEUE ioctl() */
1522 static int snd_seq_ioctl_create_queue(struct snd_seq_client *client,
1523                                       void __user *arg)
1524 {
1525         struct snd_seq_queue_info info;
1526         int result;
1527         struct snd_seq_queue *q;
1528
1529         if (copy_from_user(&info, arg, sizeof(info)))
1530                 return -EFAULT;
1531
1532         result = snd_seq_queue_alloc(client->number, info.locked, info.flags);
1533         if (result < 0)
1534                 return result;
1535
1536         q = queueptr(result);
1537         if (q == NULL)
1538                 return -EINVAL;
1539
1540         info.queue = q->queue;
1541         info.locked = q->locked;
1542         info.owner = q->owner;
1543
1544         /* set queue name */
1545         if (! info.name[0])
1546                 snprintf(info.name, sizeof(info.name), "Queue-%d", q->queue);
1547         strlcpy(q->name, info.name, sizeof(q->name));
1548         queuefree(q);
1549
1550         if (copy_to_user(arg, &info, sizeof(info)))
1551                 return -EFAULT;
1552
1553         return 0;
1554 }
1555
1556 /* DELETE_QUEUE ioctl() */
1557 static int snd_seq_ioctl_delete_queue(struct snd_seq_client *client,
1558                                       void __user *arg)
1559 {
1560         struct snd_seq_queue_info info;
1561
1562         if (copy_from_user(&info, arg, sizeof(info)))
1563                 return -EFAULT;
1564
1565         return snd_seq_queue_delete(client->number, info.queue);
1566 }
1567
1568 /* GET_QUEUE_INFO ioctl() */
1569 static int snd_seq_ioctl_get_queue_info(struct snd_seq_client *client,
1570                                         void __user *arg)
1571 {
1572         struct snd_seq_queue_info info;
1573         struct snd_seq_queue *q;
1574
1575         if (copy_from_user(&info, arg, sizeof(info)))
1576                 return -EFAULT;
1577
1578         q = queueptr(info.queue);
1579         if (q == NULL)
1580                 return -EINVAL;
1581
1582         memset(&info, 0, sizeof(info));
1583         info.queue = q->queue;
1584         info.owner = q->owner;
1585         info.locked = q->locked;
1586         strlcpy(info.name, q->name, sizeof(info.name));
1587         queuefree(q);
1588
1589         if (copy_to_user(arg, &info, sizeof(info)))
1590                 return -EFAULT;
1591
1592         return 0;
1593 }
1594
1595 /* SET_QUEUE_INFO ioctl() */
1596 static int snd_seq_ioctl_set_queue_info(struct snd_seq_client *client,
1597                                         void __user *arg)
1598 {
1599         struct snd_seq_queue_info info;
1600         struct snd_seq_queue *q;
1601
1602         if (copy_from_user(&info, arg, sizeof(info)))
1603                 return -EFAULT;
1604
1605         if (info.owner != client->number)
1606                 return -EINVAL;
1607
1608         /* change owner/locked permission */
1609         if (snd_seq_queue_check_access(info.queue, client->number)) {
1610                 if (snd_seq_queue_set_owner(info.queue, client->number, info.locked) < 0)
1611                         return -EPERM;
1612                 if (info.locked)
1613                         snd_seq_queue_use(info.queue, client->number, 1);
1614         } else {
1615                 return -EPERM;
1616         }       
1617
1618         q = queueptr(info.queue);
1619         if (! q)
1620                 return -EINVAL;
1621         if (q->owner != client->number) {
1622                 queuefree(q);
1623                 return -EPERM;
1624         }
1625         strlcpy(q->name, info.name, sizeof(q->name));
1626         queuefree(q);
1627
1628         return 0;
1629 }
1630
1631 /* GET_NAMED_QUEUE ioctl() */
1632 static int snd_seq_ioctl_get_named_queue(struct snd_seq_client *client, void __user *arg)
1633 {
1634         struct snd_seq_queue_info info;
1635         struct snd_seq_queue *q;
1636
1637         if (copy_from_user(&info, arg, sizeof(info)))
1638                 return -EFAULT;
1639
1640         q = snd_seq_queue_find_name(info.name);
1641         if (q == NULL)
1642                 return -EINVAL;
1643         info.queue = q->queue;
1644         info.owner = q->owner;
1645         info.locked = q->locked;
1646         queuefree(q);
1647
1648         if (copy_to_user(arg, &info, sizeof(info)))
1649                 return -EFAULT;
1650
1651         return 0;
1652 }
1653
1654 /* GET_QUEUE_STATUS ioctl() */
1655 static int snd_seq_ioctl_get_queue_status(struct snd_seq_client *client,
1656                                           void __user *arg)
1657 {
1658         struct snd_seq_queue_status status;
1659         struct snd_seq_queue *queue;
1660         struct snd_seq_timer *tmr;
1661
1662         if (copy_from_user(&status, arg, sizeof(status)))
1663                 return -EFAULT;
1664
1665         queue = queueptr(status.queue);
1666         if (queue == NULL)
1667                 return -EINVAL;
1668         memset(&status, 0, sizeof(status));
1669         status.queue = queue->queue;
1670         
1671         tmr = queue->timer;
1672         status.events = queue->tickq->cells + queue->timeq->cells;
1673
1674         status.time = snd_seq_timer_get_cur_time(tmr);
1675         status.tick = snd_seq_timer_get_cur_tick(tmr);
1676
1677         status.running = tmr->running;
1678
1679         status.flags = queue->flags;
1680         queuefree(queue);
1681
1682         if (copy_to_user(arg, &status, sizeof(status)))
1683                 return -EFAULT;
1684         return 0;
1685 }
1686
1687
1688 /* GET_QUEUE_TEMPO ioctl() */
1689 static int snd_seq_ioctl_get_queue_tempo(struct snd_seq_client *client,
1690                                          void __user *arg)
1691 {
1692         struct snd_seq_queue_tempo tempo;
1693         struct snd_seq_queue *queue;
1694         struct snd_seq_timer *tmr;
1695
1696         if (copy_from_user(&tempo, arg, sizeof(tempo)))
1697                 return -EFAULT;
1698
1699         queue = queueptr(tempo.queue);
1700         if (queue == NULL)
1701                 return -EINVAL;
1702         memset(&tempo, 0, sizeof(tempo));
1703         tempo.queue = queue->queue;
1704         
1705         tmr = queue->timer;
1706
1707         tempo.tempo = tmr->tempo;
1708         tempo.ppq = tmr->ppq;
1709         tempo.skew_value = tmr->skew;
1710         tempo.skew_base = tmr->skew_base;
1711         queuefree(queue);
1712
1713         if (copy_to_user(arg, &tempo, sizeof(tempo)))
1714                 return -EFAULT;
1715         return 0;
1716 }
1717
1718
1719 /* SET_QUEUE_TEMPO ioctl() */
1720 int snd_seq_set_queue_tempo(int client, struct snd_seq_queue_tempo *tempo)
1721 {
1722         if (!snd_seq_queue_check_access(tempo->queue, client))
1723                 return -EPERM;
1724         return snd_seq_queue_timer_set_tempo(tempo->queue, client, tempo);
1725 }
1726
1727 EXPORT_SYMBOL(snd_seq_set_queue_tempo);
1728
1729 static int snd_seq_ioctl_set_queue_tempo(struct snd_seq_client *client,
1730                                          void __user *arg)
1731 {
1732         int result;
1733         struct snd_seq_queue_tempo tempo;
1734
1735         if (copy_from_user(&tempo, arg, sizeof(tempo)))
1736                 return -EFAULT;
1737
1738         result = snd_seq_set_queue_tempo(client->number, &tempo);
1739         return result < 0 ? result : 0;
1740 }
1741
1742
1743 /* GET_QUEUE_TIMER ioctl() */
1744 static int snd_seq_ioctl_get_queue_timer(struct snd_seq_client *client,
1745                                          void __user *arg)
1746 {
1747         struct snd_seq_queue_timer timer;
1748         struct snd_seq_queue *queue;
1749         struct snd_seq_timer *tmr;
1750
1751         if (copy_from_user(&timer, arg, sizeof(timer)))
1752                 return -EFAULT;
1753
1754         queue = queueptr(timer.queue);
1755         if (queue == NULL)
1756                 return -EINVAL;
1757
1758         if (mutex_lock_interruptible(&queue->timer_mutex)) {
1759                 queuefree(queue);
1760                 return -ERESTARTSYS;
1761         }
1762         tmr = queue->timer;
1763         memset(&timer, 0, sizeof(timer));
1764         timer.queue = queue->queue;
1765
1766         timer.type = tmr->type;
1767         if (tmr->type == SNDRV_SEQ_TIMER_ALSA) {
1768                 timer.u.alsa.id = tmr->alsa_id;
1769                 timer.u.alsa.resolution = tmr->preferred_resolution;
1770         }
1771         mutex_unlock(&queue->timer_mutex);
1772         queuefree(queue);
1773         
1774         if (copy_to_user(arg, &timer, sizeof(timer)))
1775                 return -EFAULT;
1776         return 0;
1777 }
1778
1779
1780 /* SET_QUEUE_TIMER ioctl() */
1781 static int snd_seq_ioctl_set_queue_timer(struct snd_seq_client *client,
1782                                          void __user *arg)
1783 {
1784         int result = 0;
1785         struct snd_seq_queue_timer timer;
1786
1787         if (copy_from_user(&timer, arg, sizeof(timer)))
1788                 return -EFAULT;
1789
1790         if (timer.type != SNDRV_SEQ_TIMER_ALSA)
1791                 return -EINVAL;
1792
1793         if (snd_seq_queue_check_access(timer.queue, client->number)) {
1794                 struct snd_seq_queue *q;
1795                 struct snd_seq_timer *tmr;
1796
1797                 q = queueptr(timer.queue);
1798                 if (q == NULL)
1799                         return -ENXIO;
1800                 if (mutex_lock_interruptible(&q->timer_mutex)) {
1801                         queuefree(q);
1802                         return -ERESTARTSYS;
1803                 }
1804                 tmr = q->timer;
1805                 snd_seq_queue_timer_close(timer.queue);
1806                 tmr->type = timer.type;
1807                 if (tmr->type == SNDRV_SEQ_TIMER_ALSA) {
1808                         tmr->alsa_id = timer.u.alsa.id;
1809                         tmr->preferred_resolution = timer.u.alsa.resolution;
1810                 }
1811                 result = snd_seq_queue_timer_open(timer.queue);
1812                 mutex_unlock(&q->timer_mutex);
1813                 queuefree(q);
1814         } else {
1815                 return -EPERM;
1816         }       
1817
1818         return result;
1819 }
1820
1821
1822 /* GET_QUEUE_CLIENT ioctl() */
1823 static int snd_seq_ioctl_get_queue_client(struct snd_seq_client *client,
1824                                           void __user *arg)
1825 {
1826         struct snd_seq_queue_client info;
1827         int used;
1828
1829         if (copy_from_user(&info, arg, sizeof(info)))
1830                 return -EFAULT;
1831
1832         used = snd_seq_queue_is_used(info.queue, client->number);
1833         if (used < 0)
1834                 return -EINVAL;
1835         info.used = used;
1836         info.client = client->number;
1837
1838         if (copy_to_user(arg, &info, sizeof(info)))
1839                 return -EFAULT;
1840         return 0;
1841 }
1842
1843
1844 /* SET_QUEUE_CLIENT ioctl() */
1845 static int snd_seq_ioctl_set_queue_client(struct snd_seq_client *client,
1846                                           void __user *arg)
1847 {
1848         int err;
1849         struct snd_seq_queue_client info;
1850
1851         if (copy_from_user(&info, arg, sizeof(info)))
1852                 return -EFAULT;
1853
1854         if (info.used >= 0) {
1855                 err = snd_seq_queue_use(info.queue, client->number, info.used);
1856                 if (err < 0)
1857                         return err;
1858         }
1859
1860         return snd_seq_ioctl_get_queue_client(client, arg);
1861 }
1862
1863
1864 /* GET_CLIENT_POOL ioctl() */
1865 static int snd_seq_ioctl_get_client_pool(struct snd_seq_client *client,
1866                                          void __user *arg)
1867 {
1868         struct snd_seq_client_pool info;
1869         struct snd_seq_client *cptr;
1870
1871         if (copy_from_user(&info, arg, sizeof(info)))
1872                 return -EFAULT;
1873
1874         cptr = snd_seq_client_use_ptr(info.client);
1875         if (cptr == NULL)
1876                 return -ENOENT;
1877         memset(&info, 0, sizeof(info));
1878         info.output_pool = cptr->pool->size;
1879         info.output_room = cptr->pool->room;
1880         info.output_free = info.output_pool;
1881         info.output_free = snd_seq_unused_cells(cptr->pool);
1882         if (cptr->type == USER_CLIENT) {
1883                 info.input_pool = cptr->data.user.fifo_pool_size;
1884                 info.input_free = info.input_pool;
1885                 if (cptr->data.user.fifo)
1886                         info.input_free = snd_seq_unused_cells(cptr->data.user.fifo->pool);
1887         } else {
1888                 info.input_pool = 0;
1889                 info.input_free = 0;
1890         }
1891         snd_seq_client_unlock(cptr);
1892         
1893         if (copy_to_user(arg, &info, sizeof(info)))
1894                 return -EFAULT;
1895         return 0;
1896 }
1897
1898 /* SET_CLIENT_POOL ioctl() */
1899 static int snd_seq_ioctl_set_client_pool(struct snd_seq_client *client,
1900                                          void __user *arg)
1901 {
1902         struct snd_seq_client_pool info;
1903         int rc;
1904
1905         if (copy_from_user(&info, arg, sizeof(info)))
1906                 return -EFAULT;
1907
1908         if (client->number != info.client)
1909                 return -EINVAL; /* can't change other clients */
1910
1911         if (info.output_pool >= 1 && info.output_pool <= SNDRV_SEQ_MAX_EVENTS &&
1912             (! snd_seq_write_pool_allocated(client) ||
1913              info.output_pool != client->pool->size)) {
1914                 if (snd_seq_write_pool_allocated(client)) {
1915                         /* remove all existing cells */
1916                         snd_seq_pool_mark_closing(client->pool);
1917                         snd_seq_queue_client_leave_cells(client->number);
1918                         snd_seq_pool_done(client->pool);
1919                 }
1920                 client->pool->size = info.output_pool;
1921                 rc = snd_seq_pool_init(client->pool);
1922                 if (rc < 0)
1923                         return rc;
1924         }
1925         if (client->type == USER_CLIENT && client->data.user.fifo != NULL &&
1926             info.input_pool >= 1 &&
1927             info.input_pool <= SNDRV_SEQ_MAX_CLIENT_EVENTS &&
1928             info.input_pool != client->data.user.fifo_pool_size) {
1929                 /* change pool size */
1930                 rc = snd_seq_fifo_resize(client->data.user.fifo, info.input_pool);
1931                 if (rc < 0)
1932                         return rc;
1933                 client->data.user.fifo_pool_size = info.input_pool;
1934         }
1935         if (info.output_room >= 1 &&
1936             info.output_room <= client->pool->size) {
1937                 client->pool->room  = info.output_room;
1938         }
1939
1940         return snd_seq_ioctl_get_client_pool(client, arg);
1941 }
1942
1943
1944 /* REMOVE_EVENTS ioctl() */
1945 static int snd_seq_ioctl_remove_events(struct snd_seq_client *client,
1946                                        void __user *arg)
1947 {
1948         struct snd_seq_remove_events info;
1949
1950         if (copy_from_user(&info, arg, sizeof(info)))
1951                 return -EFAULT;
1952
1953         /*
1954          * Input mostly not implemented XXX.
1955          */
1956         if (info.remove_mode & SNDRV_SEQ_REMOVE_INPUT) {
1957                 /*
1958                  * No restrictions so for a user client we can clear
1959                  * the whole fifo
1960                  */
1961                 if (client->type == USER_CLIENT && client->data.user.fifo)
1962                         snd_seq_fifo_clear(client->data.user.fifo);
1963         }
1964
1965         if (info.remove_mode & SNDRV_SEQ_REMOVE_OUTPUT)
1966                 snd_seq_queue_remove_cells(client->number, &info);
1967
1968         return 0;
1969 }
1970
1971
1972 /*
1973  * get subscription info
1974  */
1975 static int snd_seq_ioctl_get_subscription(struct snd_seq_client *client,
1976                                           void __user *arg)
1977 {
1978         int result;
1979         struct snd_seq_client *sender = NULL;
1980         struct snd_seq_client_port *sport = NULL;
1981         struct snd_seq_port_subscribe subs;
1982         struct snd_seq_subscribers *p;
1983
1984         if (copy_from_user(&subs, arg, sizeof(subs)))
1985                 return -EFAULT;
1986
1987         result = -EINVAL;
1988         if ((sender = snd_seq_client_use_ptr(subs.sender.client)) == NULL)
1989                 goto __end;
1990         if ((sport = snd_seq_port_use_ptr(sender, subs.sender.port)) == NULL)
1991                 goto __end;
1992         p = snd_seq_port_get_subscription(&sport->c_src, &subs.dest);
1993         if (p) {
1994                 result = 0;
1995                 subs = p->info;
1996         } else
1997                 result = -ENOENT;
1998
1999       __end:
2000         if (sport)
2001                 snd_seq_port_unlock(sport);
2002         if (sender)
2003                 snd_seq_client_unlock(sender);
2004         if (result >= 0) {
2005                 if (copy_to_user(arg, &subs, sizeof(subs)))
2006                         return -EFAULT;
2007         }
2008         return result;
2009 }
2010
2011
2012 /*
2013  * get subscription info - check only its presence
2014  */
2015 static int snd_seq_ioctl_query_subs(struct snd_seq_client *client,
2016                                     void __user *arg)
2017 {
2018         int result = -ENXIO;
2019         struct snd_seq_client *cptr = NULL;
2020         struct snd_seq_client_port *port = NULL;
2021         struct snd_seq_query_subs subs;
2022         struct snd_seq_port_subs_info *group;
2023         struct list_head *p;
2024         int i;
2025
2026         if (copy_from_user(&subs, arg, sizeof(subs)))
2027                 return -EFAULT;
2028
2029         if ((cptr = snd_seq_client_use_ptr(subs.root.client)) == NULL)
2030                 goto __end;
2031         if ((port = snd_seq_port_use_ptr(cptr, subs.root.port)) == NULL)
2032                 goto __end;
2033
2034         switch (subs.type) {
2035         case SNDRV_SEQ_QUERY_SUBS_READ:
2036                 group = &port->c_src;
2037                 break;
2038         case SNDRV_SEQ_QUERY_SUBS_WRITE:
2039                 group = &port->c_dest;
2040                 break;
2041         default:
2042                 goto __end;
2043         }
2044
2045         down_read(&group->list_mutex);
2046         /* search for the subscriber */
2047         subs.num_subs = group->count;
2048         i = 0;
2049         result = -ENOENT;
2050         list_for_each(p, &group->list_head) {
2051                 if (i++ == subs.index) {
2052                         /* found! */
2053                         struct snd_seq_subscribers *s;
2054                         if (subs.type == SNDRV_SEQ_QUERY_SUBS_READ) {
2055                                 s = list_entry(p, struct snd_seq_subscribers, src_list);
2056                                 subs.addr = s->info.dest;
2057                         } else {
2058                                 s = list_entry(p, struct snd_seq_subscribers, dest_list);
2059                                 subs.addr = s->info.sender;
2060                         }
2061                         subs.flags = s->info.flags;
2062                         subs.queue = s->info.queue;
2063                         result = 0;
2064                         break;
2065                 }
2066         }
2067         up_read(&group->list_mutex);
2068
2069       __end:
2070         if (port)
2071                 snd_seq_port_unlock(port);
2072         if (cptr)
2073                 snd_seq_client_unlock(cptr);
2074         if (result >= 0) {
2075                 if (copy_to_user(arg, &subs, sizeof(subs)))
2076                         return -EFAULT;
2077         }
2078         return result;
2079 }
2080
2081
2082 /*
2083  * query next client
2084  */
2085 static int snd_seq_ioctl_query_next_client(struct snd_seq_client *client,
2086                                            void __user *arg)
2087 {
2088         struct snd_seq_client *cptr = NULL;
2089         struct snd_seq_client_info info;
2090
2091         if (copy_from_user(&info, arg, sizeof(info)))
2092                 return -EFAULT;
2093
2094         /* search for next client */
2095         info.client++;
2096         if (info.client < 0)
2097                 info.client = 0;
2098         for (; info.client < SNDRV_SEQ_MAX_CLIENTS; info.client++) {
2099                 cptr = snd_seq_client_use_ptr(info.client);
2100                 if (cptr)
2101                         break; /* found */
2102         }
2103         if (cptr == NULL)
2104                 return -ENOENT;
2105
2106         get_client_info(cptr, &info);
2107         snd_seq_client_unlock(cptr);
2108
2109         if (copy_to_user(arg, &info, sizeof(info)))
2110                 return -EFAULT;
2111         return 0;
2112 }
2113
2114 /* 
2115  * query next port
2116  */
2117 static int snd_seq_ioctl_query_next_port(struct snd_seq_client *client,
2118                                          void __user *arg)
2119 {
2120         struct snd_seq_client *cptr;
2121         struct snd_seq_client_port *port = NULL;
2122         struct snd_seq_port_info info;
2123
2124         if (copy_from_user(&info, arg, sizeof(info)))
2125                 return -EFAULT;
2126         cptr = snd_seq_client_use_ptr(info.addr.client);
2127         if (cptr == NULL)
2128                 return -ENXIO;
2129
2130         /* search for next port */
2131         info.addr.port++;
2132         port = snd_seq_port_query_nearest(cptr, &info);
2133         if (port == NULL) {
2134                 snd_seq_client_unlock(cptr);
2135                 return -ENOENT;
2136         }
2137
2138         /* get port info */
2139         info.addr = port->addr;
2140         snd_seq_get_port_info(port, &info);
2141         snd_seq_port_unlock(port);
2142         snd_seq_client_unlock(cptr);
2143
2144         if (copy_to_user(arg, &info, sizeof(info)))
2145                 return -EFAULT;
2146         return 0;
2147 }
2148
2149 /* -------------------------------------------------------- */
2150
2151 static struct seq_ioctl_table {
2152         unsigned int cmd;
2153         int (*func)(struct snd_seq_client *client, void __user * arg);
2154 } ioctl_tables[] = {
2155         { SNDRV_SEQ_IOCTL_SYSTEM_INFO, snd_seq_ioctl_system_info },
2156         { SNDRV_SEQ_IOCTL_RUNNING_MODE, snd_seq_ioctl_running_mode },
2157         { SNDRV_SEQ_IOCTL_GET_CLIENT_INFO, snd_seq_ioctl_get_client_info },
2158         { SNDRV_SEQ_IOCTL_SET_CLIENT_INFO, snd_seq_ioctl_set_client_info },
2159         { SNDRV_SEQ_IOCTL_CREATE_PORT, snd_seq_ioctl_create_port },
2160         { SNDRV_SEQ_IOCTL_DELETE_PORT, snd_seq_ioctl_delete_port },
2161         { SNDRV_SEQ_IOCTL_GET_PORT_INFO, snd_seq_ioctl_get_port_info },
2162         { SNDRV_SEQ_IOCTL_SET_PORT_INFO, snd_seq_ioctl_set_port_info },
2163         { SNDRV_SEQ_IOCTL_SUBSCRIBE_PORT, snd_seq_ioctl_subscribe_port },
2164         { SNDRV_SEQ_IOCTL_UNSUBSCRIBE_PORT, snd_seq_ioctl_unsubscribe_port },
2165         { SNDRV_SEQ_IOCTL_CREATE_QUEUE, snd_seq_ioctl_create_queue },
2166         { SNDRV_SEQ_IOCTL_DELETE_QUEUE, snd_seq_ioctl_delete_queue },
2167         { SNDRV_SEQ_IOCTL_GET_QUEUE_INFO, snd_seq_ioctl_get_queue_info },
2168         { SNDRV_SEQ_IOCTL_SET_QUEUE_INFO, snd_seq_ioctl_set_queue_info },
2169         { SNDRV_SEQ_IOCTL_GET_NAMED_QUEUE, snd_seq_ioctl_get_named_queue },
2170         { SNDRV_SEQ_IOCTL_GET_QUEUE_STATUS, snd_seq_ioctl_get_queue_status },
2171         { SNDRV_SEQ_IOCTL_GET_QUEUE_TEMPO, snd_seq_ioctl_get_queue_tempo },
2172         { SNDRV_SEQ_IOCTL_SET_QUEUE_TEMPO, snd_seq_ioctl_set_queue_tempo },
2173         { SNDRV_SEQ_IOCTL_GET_QUEUE_TIMER, snd_seq_ioctl_get_queue_timer },
2174         { SNDRV_SEQ_IOCTL_SET_QUEUE_TIMER, snd_seq_ioctl_set_queue_timer },
2175         { SNDRV_SEQ_IOCTL_GET_QUEUE_CLIENT, snd_seq_ioctl_get_queue_client },
2176         { SNDRV_SEQ_IOCTL_SET_QUEUE_CLIENT, snd_seq_ioctl_set_queue_client },
2177         { SNDRV_SEQ_IOCTL_GET_CLIENT_POOL, snd_seq_ioctl_get_client_pool },
2178         { SNDRV_SEQ_IOCTL_SET_CLIENT_POOL, snd_seq_ioctl_set_client_pool },
2179         { SNDRV_SEQ_IOCTL_GET_SUBSCRIPTION, snd_seq_ioctl_get_subscription },
2180         { SNDRV_SEQ_IOCTL_QUERY_NEXT_CLIENT, snd_seq_ioctl_query_next_client },
2181         { SNDRV_SEQ_IOCTL_QUERY_NEXT_PORT, snd_seq_ioctl_query_next_port },
2182         { SNDRV_SEQ_IOCTL_REMOVE_EVENTS, snd_seq_ioctl_remove_events },
2183         { SNDRV_SEQ_IOCTL_QUERY_SUBS, snd_seq_ioctl_query_subs },
2184         { 0, NULL },
2185 };
2186
2187 static int snd_seq_do_ioctl(struct snd_seq_client *client, unsigned int cmd,
2188                             void __user *arg)
2189 {
2190         struct seq_ioctl_table *p;
2191
2192         switch (cmd) {
2193         case SNDRV_SEQ_IOCTL_PVERSION:
2194                 /* return sequencer version number */
2195                 return put_user(SNDRV_SEQ_VERSION, (int __user *)arg) ? -EFAULT : 0;
2196         case SNDRV_SEQ_IOCTL_CLIENT_ID:
2197                 /* return the id of this client */
2198                 return put_user(client->number, (int __user *)arg) ? -EFAULT : 0;
2199         }
2200
2201         if (! arg)
2202                 return -EFAULT;
2203         for (p = ioctl_tables; p->cmd; p++) {
2204                 if (p->cmd == cmd)
2205                         return p->func(client, arg);
2206         }
2207         snd_printd("seq unknown ioctl() 0x%x (type='%c', number=0x%02x)\n",
2208                    cmd, _IOC_TYPE(cmd), _IOC_NR(cmd));
2209         return -ENOTTY;
2210 }
2211
2212
2213 static long snd_seq_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2214 {
2215         struct snd_seq_client *client = file->private_data;
2216
2217         if (snd_BUG_ON(!client))
2218                 return -ENXIO;
2219                 
2220         return snd_seq_do_ioctl(client, cmd, (void __user *) arg);
2221 }
2222
2223 #ifdef CONFIG_COMPAT
2224 #include "seq_compat.c"
2225 #else
2226 #define snd_seq_ioctl_compat    NULL
2227 #endif
2228
2229 /* -------------------------------------------------------- */
2230
2231
2232 /* exported to kernel modules */
2233 int snd_seq_create_kernel_client(struct snd_card *card, int client_index,
2234                                  const char *name_fmt, ...)
2235 {
2236         struct snd_seq_client *client;
2237         va_list args;
2238
2239         if (snd_BUG_ON(in_interrupt()))
2240                 return -EBUSY;
2241
2242         if (card && client_index >= SNDRV_SEQ_CLIENTS_PER_CARD)
2243                 return -EINVAL;
2244         if (card == NULL && client_index >= SNDRV_SEQ_GLOBAL_CLIENTS)
2245                 return -EINVAL;
2246
2247         if (mutex_lock_interruptible(&register_mutex))
2248                 return -ERESTARTSYS;
2249
2250         if (card) {
2251                 client_index += SNDRV_SEQ_GLOBAL_CLIENTS
2252                         + card->number * SNDRV_SEQ_CLIENTS_PER_CARD;
2253                 if (client_index >= SNDRV_SEQ_DYNAMIC_CLIENTS_BEGIN)
2254                         client_index = -1;
2255         }
2256
2257         /* empty write queue as default */
2258         client = seq_create_client1(client_index, 0);
2259         if (client == NULL) {
2260                 mutex_unlock(&register_mutex);
2261                 return -EBUSY;  /* failure code */
2262         }
2263         usage_alloc(&client_usage, 1);
2264
2265         client->accept_input = 1;
2266         client->accept_output = 1;
2267                 
2268         va_start(args, name_fmt);
2269         vsnprintf(client->name, sizeof(client->name), name_fmt, args);
2270         va_end(args);
2271
2272         client->type = KERNEL_CLIENT;
2273         mutex_unlock(&register_mutex);
2274
2275         /* make others aware this new client */
2276         snd_seq_system_client_ev_client_start(client->number);
2277         
2278         /* return client number to caller */
2279         return client->number;
2280 }
2281
2282 EXPORT_SYMBOL(snd_seq_create_kernel_client);
2283
2284 /* exported to kernel modules */
2285 int snd_seq_delete_kernel_client(int client)
2286 {
2287         struct snd_seq_client *ptr;
2288
2289         if (snd_BUG_ON(in_interrupt()))
2290                 return -EBUSY;
2291
2292         ptr = clientptr(client);
2293         if (ptr == NULL)
2294                 return -EINVAL;
2295
2296         seq_free_client(ptr);
2297         kfree(ptr);
2298         return 0;
2299 }
2300
2301 EXPORT_SYMBOL(snd_seq_delete_kernel_client);
2302
2303 /* skeleton to enqueue event, called from snd_seq_kernel_client_enqueue
2304  * and snd_seq_kernel_client_enqueue_blocking
2305  */
2306 static int kernel_client_enqueue(int client, struct snd_seq_event *ev,
2307                                  struct file *file, int blocking,
2308                                  int atomic, int hop)
2309 {
2310         struct snd_seq_client *cptr;
2311         int result;
2312
2313         if (snd_BUG_ON(!ev))
2314                 return -EINVAL;
2315
2316         if (ev->type == SNDRV_SEQ_EVENT_NONE)
2317                 return 0; /* ignore this */
2318         if (ev->type == SNDRV_SEQ_EVENT_KERNEL_ERROR)
2319                 return -EINVAL; /* quoted events can't be enqueued */
2320
2321         /* fill in client number */
2322         ev->source.client = client;
2323
2324         if (check_event_type_and_length(ev))
2325                 return -EINVAL;
2326
2327         cptr = snd_seq_client_use_ptr(client);
2328         if (cptr == NULL)
2329                 return -EINVAL;
2330         
2331         if (! cptr->accept_output)
2332                 result = -EPERM;
2333         else /* send it */
2334                 result = snd_seq_client_enqueue_event(cptr, ev, file, blocking, atomic, hop);
2335
2336         snd_seq_client_unlock(cptr);
2337         return result;
2338 }
2339
2340 /*
2341  * exported, called by kernel clients to enqueue events (w/o blocking)
2342  *
2343  * RETURN VALUE: zero if succeed, negative if error
2344  */
2345 int snd_seq_kernel_client_enqueue(int client, struct snd_seq_event * ev,
2346                                   int atomic, int hop)
2347 {
2348         return kernel_client_enqueue(client, ev, NULL, 0, atomic, hop);
2349 }
2350
2351 EXPORT_SYMBOL(snd_seq_kernel_client_enqueue);
2352
2353 /*
2354  * exported, called by kernel clients to enqueue events (with blocking)
2355  *
2356  * RETURN VALUE: zero if succeed, negative if error
2357  */
2358 int snd_seq_kernel_client_enqueue_blocking(int client, struct snd_seq_event * ev,
2359                                            struct file *file,
2360                                            int atomic, int hop)
2361 {
2362         return kernel_client_enqueue(client, ev, file, 1, atomic, hop);
2363 }
2364
2365 EXPORT_SYMBOL(snd_seq_kernel_client_enqueue_blocking);
2366
2367 /* 
2368  * exported, called by kernel clients to dispatch events directly to other
2369  * clients, bypassing the queues.  Event time-stamp will be updated.
2370  *
2371  * RETURN VALUE: negative = delivery failed,
2372  *               zero, or positive: the number of delivered events
2373  */
2374 int snd_seq_kernel_client_dispatch(int client, struct snd_seq_event * ev,
2375                                    int atomic, int hop)
2376 {
2377         struct snd_seq_client *cptr;
2378         int result;
2379
2380         if (snd_BUG_ON(!ev))
2381                 return -EINVAL;
2382
2383         /* fill in client number */
2384         ev->queue = SNDRV_SEQ_QUEUE_DIRECT;
2385         ev->source.client = client;
2386
2387         if (check_event_type_and_length(ev))
2388                 return -EINVAL;
2389
2390         cptr = snd_seq_client_use_ptr(client);
2391         if (cptr == NULL)
2392                 return -EINVAL;
2393
2394         if (!cptr->accept_output)
2395                 result = -EPERM;
2396         else
2397                 result = snd_seq_deliver_event(cptr, ev, atomic, hop);
2398
2399         snd_seq_client_unlock(cptr);
2400         return result;
2401 }
2402
2403 EXPORT_SYMBOL(snd_seq_kernel_client_dispatch);
2404
2405 /*
2406  * exported, called by kernel clients to perform same functions as with
2407  * userland ioctl() 
2408  */
2409 int snd_seq_kernel_client_ctl(int clientid, unsigned int cmd, void *arg)
2410 {
2411         struct snd_seq_client *client;
2412         mm_segment_t fs;
2413         int result;
2414
2415         client = clientptr(clientid);
2416         if (client == NULL)
2417                 return -ENXIO;
2418         fs = snd_enter_user();
2419         result = snd_seq_do_ioctl(client, cmd, (void __force __user *)arg);
2420         snd_leave_user(fs);
2421         return result;
2422 }
2423
2424 EXPORT_SYMBOL(snd_seq_kernel_client_ctl);
2425
2426 /* exported (for OSS emulator) */
2427 int snd_seq_kernel_client_write_poll(int clientid, struct file *file, poll_table *wait)
2428 {
2429         struct snd_seq_client *client;
2430
2431         client = clientptr(clientid);
2432         if (client == NULL)
2433                 return -ENXIO;
2434
2435         if (! snd_seq_write_pool_allocated(client))
2436                 return 1;
2437         if (snd_seq_pool_poll_wait(client->pool, file, wait))
2438                 return 1;
2439         return 0;
2440 }
2441
2442 EXPORT_SYMBOL(snd_seq_kernel_client_write_poll);
2443
2444 /*---------------------------------------------------------------------------*/
2445
2446 #ifdef CONFIG_PROC_FS
2447 /*
2448  *  /proc interface
2449  */
2450 static void snd_seq_info_dump_subscribers(struct snd_info_buffer *buffer,
2451                                           struct snd_seq_port_subs_info *group,
2452                                           int is_src, char *msg)
2453 {
2454         struct list_head *p;
2455         struct snd_seq_subscribers *s;
2456         int count = 0;
2457
2458         down_read(&group->list_mutex);
2459         if (list_empty(&group->list_head)) {
2460                 up_read(&group->list_mutex);
2461                 return;
2462         }
2463         snd_iprintf(buffer, msg);
2464         list_for_each(p, &group->list_head) {
2465                 if (is_src)
2466                         s = list_entry(p, struct snd_seq_subscribers, src_list);
2467                 else
2468                         s = list_entry(p, struct snd_seq_subscribers, dest_list);
2469                 if (count++)
2470                         snd_iprintf(buffer, ", ");
2471                 snd_iprintf(buffer, "%d:%d",
2472                             is_src ? s->info.dest.client : s->info.sender.client,
2473                             is_src ? s->info.dest.port : s->info.sender.port);
2474                 if (s->info.flags & SNDRV_SEQ_PORT_SUBS_TIMESTAMP)
2475                         snd_iprintf(buffer, "[%c:%d]", ((s->info.flags & SNDRV_SEQ_PORT_SUBS_TIME_REAL) ? 'r' : 't'), s->info.queue);
2476                 if (group->exclusive)
2477                         snd_iprintf(buffer, "[ex]");
2478         }
2479         up_read(&group->list_mutex);
2480         snd_iprintf(buffer, "\n");
2481 }
2482
2483 #define FLAG_PERM_RD(perm) ((perm) & SNDRV_SEQ_PORT_CAP_READ ? ((perm) & SNDRV_SEQ_PORT_CAP_SUBS_READ ? 'R' : 'r') : '-')
2484 #define FLAG_PERM_WR(perm) ((perm) & SNDRV_SEQ_PORT_CAP_WRITE ? ((perm) & SNDRV_SEQ_PORT_CAP_SUBS_WRITE ? 'W' : 'w') : '-')
2485 #define FLAG_PERM_EX(perm) ((perm) & SNDRV_SEQ_PORT_CAP_NO_EXPORT ? '-' : 'e')
2486
2487 #define FLAG_PERM_DUPLEX(perm) ((perm) & SNDRV_SEQ_PORT_CAP_DUPLEX ? 'X' : '-')
2488
2489 static void snd_seq_info_dump_ports(struct snd_info_buffer *buffer,
2490                                     struct snd_seq_client *client)
2491 {
2492         struct snd_seq_client_port *p;
2493
2494         mutex_lock(&client->ports_mutex);
2495         list_for_each_entry(p, &client->ports_list_head, list) {
2496                 snd_iprintf(buffer, "  Port %3d : \"%s\" (%c%c%c%c)\n",
2497                             p->addr.port, p->name,
2498                             FLAG_PERM_RD(p->capability),
2499                             FLAG_PERM_WR(p->capability),
2500                             FLAG_PERM_EX(p->capability),
2501                             FLAG_PERM_DUPLEX(p->capability));
2502                 snd_seq_info_dump_subscribers(buffer, &p->c_src, 1, "    Connecting To: ");
2503                 snd_seq_info_dump_subscribers(buffer, &p->c_dest, 0, "    Connected From: ");
2504         }
2505         mutex_unlock(&client->ports_mutex);
2506 }
2507
2508
2509 /* exported to seq_info.c */
2510 void snd_seq_info_clients_read(struct snd_info_entry *entry, 
2511                                struct snd_info_buffer *buffer)
2512 {
2513         int c;
2514         struct snd_seq_client *client;
2515
2516         snd_iprintf(buffer, "Client info\n");
2517         snd_iprintf(buffer, "  cur  clients : %d\n", client_usage.cur);
2518         snd_iprintf(buffer, "  peak clients : %d\n", client_usage.peak);
2519         snd_iprintf(buffer, "  max  clients : %d\n", SNDRV_SEQ_MAX_CLIENTS);
2520         snd_iprintf(buffer, "\n");
2521
2522         /* list the client table */
2523         for (c = 0; c < SNDRV_SEQ_MAX_CLIENTS; c++) {
2524                 client = snd_seq_client_use_ptr(c);
2525                 if (client == NULL)
2526                         continue;
2527                 if (client->type == NO_CLIENT) {
2528                         snd_seq_client_unlock(client);
2529                         continue;
2530                 }
2531
2532                 snd_iprintf(buffer, "Client %3d : \"%s\" [%s]\n",
2533                             c, client->name,
2534                             client->type == USER_CLIENT ? "User" : "Kernel");
2535                 snd_seq_info_dump_ports(buffer, client);
2536                 if (snd_seq_write_pool_allocated(client)) {
2537                         snd_iprintf(buffer, "  Output pool :\n");
2538                         snd_seq_info_pool(buffer, client->pool, "    ");
2539                 }
2540                 if (client->type == USER_CLIENT && client->data.user.fifo &&
2541                     client->data.user.fifo->pool) {
2542                         snd_iprintf(buffer, "  Input pool :\n");
2543                         snd_seq_info_pool(buffer, client->data.user.fifo->pool, "    ");
2544                 }
2545                 snd_seq_client_unlock(client);
2546         }
2547 }
2548 #endif /* CONFIG_PROC_FS */
2549
2550 /*---------------------------------------------------------------------------*/
2551
2552
2553 /*
2554  *  REGISTRATION PART
2555  */
2556
2557 static const struct file_operations snd_seq_f_ops =
2558 {
2559         .owner =        THIS_MODULE,
2560         .read =         snd_seq_read,
2561         .write =        snd_seq_write,
2562         .open =         snd_seq_open,
2563         .release =      snd_seq_release,
2564         .llseek =       no_llseek,
2565         .poll =         snd_seq_poll,
2566         .unlocked_ioctl =       snd_seq_ioctl,
2567         .compat_ioctl = snd_seq_ioctl_compat,
2568 };
2569
2570 /* 
2571  * register sequencer device 
2572  */
2573 int __init snd_sequencer_device_init(void)
2574 {
2575         int err;
2576
2577         if (mutex_lock_interruptible(&register_mutex))
2578                 return -ERESTARTSYS;
2579
2580         if ((err = snd_register_device(SNDRV_DEVICE_TYPE_SEQUENCER, NULL, 0,
2581                                        &snd_seq_f_ops, NULL, "seq")) < 0) {
2582                 mutex_unlock(&register_mutex);
2583                 return err;
2584         }
2585         
2586         mutex_unlock(&register_mutex);
2587
2588         return 0;
2589 }
2590
2591
2592
2593 /* 
2594  * unregister sequencer device 
2595  */
2596 void __exit snd_sequencer_device_done(void)
2597 {
2598         snd_unregister_device(SNDRV_DEVICE_TYPE_SEQUENCER, NULL, 0);
2599 }