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