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