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