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