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