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