1/*
2 *   ALSA sequencer Ports
3 *   Copyright (c) 1998 by Frank van de Pol <fvdpol@coil.demon.nl>
4 *                         Jaroslav Kysela <perex@suse.cz>
5 *
6 *
7 *   This program is free software; you can redistribute it and/or modify
8 *   it under the terms of the GNU General Public License as published by
9 *   the Free Software Foundation; either version 2 of the License, or
10 *   (at your option) any later version.
11 *
12 *   This program is distributed in the hope that it will be useful,
13 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 *   GNU General Public License for more details.
16 *
17 *   You should have received a copy of the GNU General Public License
18 *   along with this program; if not, write to the Free Software
19 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
20 *
21 */
22
23#include <sound/driver.h>
24#include <sound/core.h>
25#include <linux/slab.h>
26#include "seq_system.h"
27#include "seq_ports.h"
28#include "seq_clientmgr.h"
29
30/*
31
32   registration of client ports
33
34 */
35
36
37/*
38
39NOTE: the current implementation of the port structure as a linked list is
40not optimal for clients that have many ports. For sending messages to all
41subscribers of a port we first need to find the address of the port
42structure, which means we have to traverse the list. A direct access table
43(array) would be better, but big preallocated arrays waste memory.
44
45Possible actions:
46
471) leave it this way, a client does normaly does not have more than a few
48ports
49
502) replace the linked list of ports by a array of pointers which is
51dynamicly kmalloced. When a port is added or deleted we can simply allocate
52a new array, copy the corresponding pointers, and delete the old one. We
53then only need a pointer to this array, and an integer that tells us how
54much elements are in array.
55
56*/
57
58/* return pointer to port structure - port is locked if found */
59struct snd_seq_client_port *snd_seq_port_use_ptr(struct snd_seq_client *client,
60						 int num)
61{
62	struct snd_seq_client_port *port;
63
64	if (client == NULL)
65		return NULL;
66	read_lock(&client->ports_lock);
67	list_for_each_entry(port, &client->ports_list_head, list) {
68		if (port->addr.port == num) {
69			if (port->closing)
70				break; /* deleting now */
71			snd_use_lock_use(&port->use_lock);
72			read_unlock(&client->ports_lock);
73			return port;
74		}
75	}
76	read_unlock(&client->ports_lock);
77	return NULL;		/* not found */
78}
79
80
81/* search for the next port - port is locked if found */
82struct snd_seq_client_port *snd_seq_port_query_nearest(struct snd_seq_client *client,
83						       struct snd_seq_port_info *pinfo)
84{
85	int num;
86	struct snd_seq_client_port *port, *found;
87
88	num = pinfo->addr.port;
89	found = NULL;
90	read_lock(&client->ports_lock);
91	list_for_each_entry(port, &client->ports_list_head, list) {
92		if (port->addr.port < num)
93			continue;
94		if (port->addr.port == num) {
95			found = port;
96			break;
97		}
98		if (found == NULL || port->addr.port < found->addr.port)
99			found = port;
100	}
101	if (found) {
102		if (found->closing)
103			found = NULL;
104		else
105			snd_use_lock_use(&found->use_lock);
106	}
107	read_unlock(&client->ports_lock);
108	return found;
109}
110
111
112/* initialize snd_seq_port_subs_info */
113static void port_subs_info_init(struct snd_seq_port_subs_info *grp)
114{
115	INIT_LIST_HEAD(&grp->list_head);
116	grp->count = 0;
117	grp->exclusive = 0;
118	rwlock_init(&grp->list_lock);
119	init_rwsem(&grp->list_mutex);
120	grp->open = NULL;
121	grp->close = NULL;
122}
123
124
125/* create a port, port number is returned (-1 on failure) */
126struct snd_seq_client_port *snd_seq_create_port(struct snd_seq_client *client,
127						int port)
128{
129	unsigned long flags;
130	struct snd_seq_client_port *new_port, *p;
131	int num = -1;
132
133	/* sanity check */
134	snd_assert(client, return NULL);
135
136	if (client->num_ports >= SNDRV_SEQ_MAX_PORTS - 1) {
137		snd_printk(KERN_WARNING "too many ports for client %d\n", client->number);
138		return NULL;
139	}
140
141	/* create a new port */
142	new_port = kzalloc(sizeof(*new_port), GFP_KERNEL);
143	if (! new_port) {
144		snd_printd("malloc failed for registering client port\n");
145		return NULL;	/* failure, out of memory */
146	}
147	/* init port data */
148	new_port->addr.client = client->number;
149	new_port->addr.port = -1;
150	new_port->owner = THIS_MODULE;
151	sprintf(new_port->name, "port-%d", num);
152	snd_use_lock_init(&new_port->use_lock);
153	port_subs_info_init(&new_port->c_src);
154	port_subs_info_init(&new_port->c_dest);
155
156	num = port >= 0 ? port : 0;
157	mutex_lock(&client->ports_mutex);
158	write_lock_irqsave(&client->ports_lock, flags);
159	list_for_each_entry(p, &client->ports_list_head, list) {
160		if (p->addr.port > num)
161			break;
162		if (port < 0) /* auto-probe mode */
163			num = p->addr.port + 1;
164	}
165	/* insert the new port */
166	list_add_tail(&new_port->list, &p->list);
167	client->num_ports++;
168	new_port->addr.port = num;	/* store the port number in the port */
169	write_unlock_irqrestore(&client->ports_lock, flags);
170	mutex_unlock(&client->ports_mutex);
171	sprintf(new_port->name, "port-%d", num);
172
173	return new_port;
174}
175
176/* */
177enum group_type {
178	SRC_LIST, DEST_LIST
179};
180
181static int subscribe_port(struct snd_seq_client *client,
182			  struct snd_seq_client_port *port,
183			  struct snd_seq_port_subs_info *grp,
184			  struct snd_seq_port_subscribe *info, int send_ack);
185static int unsubscribe_port(struct snd_seq_client *client,
186			    struct snd_seq_client_port *port,
187			    struct snd_seq_port_subs_info *grp,
188			    struct snd_seq_port_subscribe *info, int send_ack);
189
190
191static struct snd_seq_client_port *get_client_port(struct snd_seq_addr *addr,
192						   struct snd_seq_client **cp)
193{
194	struct snd_seq_client_port *p;
195	*cp = snd_seq_client_use_ptr(addr->client);
196	if (*cp) {
197		p = snd_seq_port_use_ptr(*cp, addr->port);
198		if (! p) {
199			snd_seq_client_unlock(*cp);
200			*cp = NULL;
201		}
202		return p;
203	}
204	return NULL;
205}
206
207/*
208 * remove all subscribers on the list
209 * this is called from port_delete, for each src and dest list.
210 */
211static void clear_subscriber_list(struct snd_seq_client *client,
212				  struct snd_seq_client_port *port,
213				  struct snd_seq_port_subs_info *grp,
214				  int grptype)
215{
216	struct list_head *p, *n;
217
218	list_for_each_safe(p, n, &grp->list_head) {
219		struct snd_seq_subscribers *subs;
220		struct snd_seq_client *c;
221		struct snd_seq_client_port *aport;
222
223		if (grptype == SRC_LIST) {
224			subs = list_entry(p, struct snd_seq_subscribers, src_list);
225			aport = get_client_port(&subs->info.dest, &c);
226		} else {
227			subs = list_entry(p, struct snd_seq_subscribers, dest_list);
228			aport = get_client_port(&subs->info.sender, &c);
229		}
230		list_del(p);
231		unsubscribe_port(client, port, grp, &subs->info, 0);
232		if (!aport) {
233			/* looks like the connected port is being deleted.
234			 * we decrease the counter, and when both ports are deleted
235			 * remove the subscriber info
236			 */
237			if (atomic_dec_and_test(&subs->ref_count))
238				kfree(subs);
239		} else {
240			/* ok we got the connected port */
241			struct snd_seq_port_subs_info *agrp;
242			agrp = (grptype == SRC_LIST) ? &aport->c_dest : &aport->c_src;
243			down_write(&agrp->list_mutex);
244			if (grptype == SRC_LIST)
245				list_del(&subs->dest_list);
246			else
247				list_del(&subs->src_list);
248			up_write(&agrp->list_mutex);
249			unsubscribe_port(c, aport, agrp, &subs->info, 1);
250			kfree(subs);
251			snd_seq_port_unlock(aport);
252			snd_seq_client_unlock(c);
253		}
254	}
255}
256
257/* delete port data */
258static int port_delete(struct snd_seq_client *client,
259		       struct snd_seq_client_port *port)
260{
261	/* set closing flag and wait for all port access are gone */
262	port->closing = 1;
263	snd_use_lock_sync(&port->use_lock);
264
265	/* clear subscribers info */
266	clear_subscriber_list(client, port, &port->c_src, SRC_LIST);
267	clear_subscriber_list(client, port, &port->c_dest, DEST_LIST);
268
269	if (port->private_free)
270		port->private_free(port->private_data);
271
272	snd_assert(port->c_src.count == 0,);
273	snd_assert(port->c_dest.count == 0,);
274
275	kfree(port);
276	return 0;
277}
278
279
280/* delete a port with the given port id */
281int snd_seq_delete_port(struct snd_seq_client *client, int port)
282{
283	unsigned long flags;
284	struct snd_seq_client_port *found = NULL, *p;
285
286	mutex_lock(&client->ports_mutex);
287	write_lock_irqsave(&client->ports_lock, flags);
288	list_for_each_entry(p, &client->ports_list_head, list) {
289		if (p->addr.port == port) {
290			/* ok found.  delete from the list at first */
291			list_del(&p->list);
292			client->num_ports--;
293			found = p;
294			break;
295		}
296	}
297	write_unlock_irqrestore(&client->ports_lock, flags);
298	mutex_unlock(&client->ports_mutex);
299	if (found)
300		return port_delete(client, found);
301	else
302		return -ENOENT;
303}
304
305/* delete the all ports belonging to the given client */
306int snd_seq_delete_all_ports(struct snd_seq_client *client)
307{
308	unsigned long flags;
309	struct list_head deleted_list;
310	struct snd_seq_client_port *port, *tmp;
311
312	/* move the port list to deleted_list, and
313	 * clear the port list in the client data.
314	 */
315	mutex_lock(&client->ports_mutex);
316	write_lock_irqsave(&client->ports_lock, flags);
317	if (! list_empty(&client->ports_list_head)) {
318		list_add(&deleted_list, &client->ports_list_head);
319		list_del_init(&client->ports_list_head);
320	} else {
321		INIT_LIST_HEAD(&deleted_list);
322	}
323	client->num_ports = 0;
324	write_unlock_irqrestore(&client->ports_lock, flags);
325
326	/* remove each port in deleted_list */
327	list_for_each_entry_safe(port, tmp, &deleted_list, list) {
328		list_del(&port->list);
329		snd_seq_system_client_ev_port_exit(port->addr.client, port->addr.port);
330		port_delete(client, port);
331	}
332	mutex_unlock(&client->ports_mutex);
333	return 0;
334}
335
336/* set port info fields */
337int snd_seq_set_port_info(struct snd_seq_client_port * port,
338			  struct snd_seq_port_info * info)
339{
340	snd_assert(port && info, return -EINVAL);
341
342	/* set port name */
343	if (info->name[0])
344		strlcpy(port->name, info->name, sizeof(port->name));
345
346	/* set capabilities */
347	port->capability = info->capability;
348
349	/* get port type */
350	port->type = info->type;
351
352	/* information about supported channels/voices */
353	port->midi_channels = info->midi_channels;
354	port->midi_voices = info->midi_voices;
355	port->synth_voices = info->synth_voices;
356
357	/* timestamping */
358	port->timestamping = (info->flags & SNDRV_SEQ_PORT_FLG_TIMESTAMP) ? 1 : 0;
359	port->time_real = (info->flags & SNDRV_SEQ_PORT_FLG_TIME_REAL) ? 1 : 0;
360	port->time_queue = info->time_queue;
361
362	return 0;
363}
364
365/* get port info fields */
366int snd_seq_get_port_info(struct snd_seq_client_port * port,
367			  struct snd_seq_port_info * info)
368{
369	snd_assert(port && info, return -EINVAL);
370
371	/* get port name */
372	strlcpy(info->name, port->name, sizeof(info->name));
373
374	/* get capabilities */
375	info->capability = port->capability;
376
377	/* get port type */
378	info->type = port->type;
379
380	/* information about supported channels/voices */
381	info->midi_channels = port->midi_channels;
382	info->midi_voices = port->midi_voices;
383	info->synth_voices = port->synth_voices;
384
385	/* get subscriber counts */
386	info->read_use = port->c_src.count;
387	info->write_use = port->c_dest.count;
388
389	/* timestamping */
390	info->flags = 0;
391	if (port->timestamping) {
392		info->flags |= SNDRV_SEQ_PORT_FLG_TIMESTAMP;
393		if (port->time_real)
394			info->flags |= SNDRV_SEQ_PORT_FLG_TIME_REAL;
395		info->time_queue = port->time_queue;
396	}
397
398	return 0;
399}
400
401
402
403/*
404 * call callback functions (if any):
405 * the callbacks are invoked only when the first (for connection) or
406 * the last subscription (for disconnection) is done.  Second or later
407 * subscription results in increment of counter, but no callback is
408 * invoked.
409 * This feature is useful if these callbacks are associated with
410 * initialization or termination of devices (see seq_midi.c).
411 *
412 * If callback_all option is set, the callback function is invoked
413 * at each connnection/disconnection.
414 */
415
416static int subscribe_port(struct snd_seq_client *client,
417			  struct snd_seq_client_port *port,
418			  struct snd_seq_port_subs_info *grp,
419			  struct snd_seq_port_subscribe *info,
420			  int send_ack)
421{
422	int err = 0;
423
424	if (!try_module_get(port->owner))
425		return -EFAULT;
426	grp->count++;
427	if (grp->open && (port->callback_all || grp->count == 1)) {
428		err = grp->open(port->private_data, info);
429		if (err < 0) {
430			module_put(port->owner);
431			grp->count--;
432		}
433	}
434	if (err >= 0 && send_ack && client->type == USER_CLIENT)
435		snd_seq_client_notify_subscription(port->addr.client, port->addr.port,
436						   info, SNDRV_SEQ_EVENT_PORT_SUBSCRIBED);
437
438	return err;
439}
440
441static int unsubscribe_port(struct snd_seq_client *client,
442			    struct snd_seq_client_port *port,
443			    struct snd_seq_port_subs_info *grp,
444			    struct snd_seq_port_subscribe *info,
445			    int send_ack)
446{
447	int err = 0;
448
449	if (! grp->count)
450		return -EINVAL;
451	grp->count--;
452	if (grp->close && (port->callback_all || grp->count == 0))
453		err = grp->close(port->private_data, info);
454	if (send_ack && client->type == USER_CLIENT)
455		snd_seq_client_notify_subscription(port->addr.client, port->addr.port,
456						   info, SNDRV_SEQ_EVENT_PORT_UNSUBSCRIBED);
457	module_put(port->owner);
458	return err;
459}
460
461
462
463/* check if both addresses are identical */
464static inline int addr_match(struct snd_seq_addr *r, struct snd_seq_addr *s)
465{
466	return (r->client == s->client) && (r->port == s->port);
467}
468
469/* check the two subscribe info match */
470/* if flags is zero, checks only sender and destination addresses */
471static int match_subs_info(struct snd_seq_port_subscribe *r,
472			   struct snd_seq_port_subscribe *s)
473{
474	if (addr_match(&r->sender, &s->sender) &&
475	    addr_match(&r->dest, &s->dest)) {
476		if (r->flags && r->flags == s->flags)
477			return r->queue == s->queue;
478		else if (! r->flags)
479			return 1;
480	}
481	return 0;
482}
483
484
485/* connect two ports */
486int snd_seq_port_connect(struct snd_seq_client *connector,
487			 struct snd_seq_client *src_client,
488			 struct snd_seq_client_port *src_port,
489			 struct snd_seq_client *dest_client,
490			 struct snd_seq_client_port *dest_port,
491			 struct snd_seq_port_subscribe *info)
492{
493	struct snd_seq_port_subs_info *src = &src_port->c_src;
494	struct snd_seq_port_subs_info *dest = &dest_port->c_dest;
495	struct snd_seq_subscribers *subs, *s;
496	int err, src_called = 0;
497	unsigned long flags;
498	int exclusive;
499
500	subs = kzalloc(sizeof(*subs), GFP_KERNEL);
501	if (! subs)
502		return -ENOMEM;
503
504	subs->info = *info;
505	atomic_set(&subs->ref_count, 2);
506
507	down_write(&src->list_mutex);
508	down_write_nested(&dest->list_mutex, SINGLE_DEPTH_NESTING);
509
510	exclusive = info->flags & SNDRV_SEQ_PORT_SUBS_EXCLUSIVE ? 1 : 0;
511	err = -EBUSY;
512	if (exclusive) {
513		if (! list_empty(&src->list_head) || ! list_empty(&dest->list_head))
514			goto __error;
515	} else {
516		if (src->exclusive || dest->exclusive)
517			goto __error;
518		/* check whether already exists */
519		list_for_each_entry(s, &src->list_head, src_list) {
520			if (match_subs_info(info, &s->info))
521				goto __error;
522		}
523		list_for_each_entry(s, &dest->list_head, dest_list) {
524			if (match_subs_info(info, &s->info))
525				goto __error;
526		}
527	}
528
529	if ((err = subscribe_port(src_client, src_port, src, info,
530				  connector->number != src_client->number)) < 0)
531		goto __error;
532	src_called = 1;
533
534	if ((err = subscribe_port(dest_client, dest_port, dest, info,
535				  connector->number != dest_client->number)) < 0)
536		goto __error;
537
538	/* add to list */
539	write_lock_irqsave(&src->list_lock, flags);
540	// write_lock(&dest->list_lock); // no other lock yet
541	list_add_tail(&subs->src_list, &src->list_head);
542	list_add_tail(&subs->dest_list, &dest->list_head);
543	// write_unlock(&dest->list_lock); // no other lock yet
544	write_unlock_irqrestore(&src->list_lock, flags);
545
546	src->exclusive = dest->exclusive = exclusive;
547
548	up_write(&dest->list_mutex);
549	up_write(&src->list_mutex);
550	return 0;
551
552 __error:
553	if (src_called)
554		unsubscribe_port(src_client, src_port, src, info,
555				 connector->number != src_client->number);
556	kfree(subs);
557	up_write(&dest->list_mutex);
558	up_write(&src->list_mutex);
559	return err;
560}
561
562
563/* remove the connection */
564int snd_seq_port_disconnect(struct snd_seq_client *connector,
565			    struct snd_seq_client *src_client,
566			    struct snd_seq_client_port *src_port,
567			    struct snd_seq_client *dest_client,
568			    struct snd_seq_client_port *dest_port,
569			    struct snd_seq_port_subscribe *info)
570{
571	struct snd_seq_port_subs_info *src = &src_port->c_src;
572	struct snd_seq_port_subs_info *dest = &dest_port->c_dest;
573	struct snd_seq_subscribers *subs;
574	int err = -ENOENT;
575	unsigned long flags;
576
577	down_write(&src->list_mutex);
578	down_write_nested(&dest->list_mutex, SINGLE_DEPTH_NESTING);
579
580	/* look for the connection */
581	list_for_each_entry(subs, &src->list_head, src_list) {
582		if (match_subs_info(info, &subs->info)) {
583			write_lock_irqsave(&src->list_lock, flags);
584			// write_lock(&dest->list_lock);  // no lock yet
585			list_del(&subs->src_list);
586			list_del(&subs->dest_list);
587			// write_unlock(&dest->list_lock);
588			write_unlock_irqrestore(&src->list_lock, flags);
589			src->exclusive = dest->exclusive = 0;
590			unsubscribe_port(src_client, src_port, src, info,
591					 connector->number != src_client->number);
592			unsubscribe_port(dest_client, dest_port, dest, info,
593					 connector->number != dest_client->number);
594			kfree(subs);
595			err = 0;
596			break;
597		}
598	}
599
600	up_write(&dest->list_mutex);
601	up_write(&src->list_mutex);
602	return err;
603}
604
605
606/* get matched subscriber */
607struct snd_seq_subscribers *snd_seq_port_get_subscription(struct snd_seq_port_subs_info *src_grp,
608							  struct snd_seq_addr *dest_addr)
609{
610	struct snd_seq_subscribers *s, *found = NULL;
611
612	down_read(&src_grp->list_mutex);
613	list_for_each_entry(s, &src_grp->list_head, src_list) {
614		if (addr_match(dest_addr, &s->info.dest)) {
615			found = s;
616			break;
617		}
618	}
619	up_read(&src_grp->list_mutex);
620	return found;
621}
622
623/*
624 * Attach a device driver that wants to receive events from the
625 * sequencer.  Returns the new port number on success.
626 * A driver that wants to receive the events converted to midi, will
627 * use snd_seq_midisynth_register_port().
628 */
629/* exported */
630int snd_seq_event_port_attach(int client,
631			      struct snd_seq_port_callback *pcbp,
632			      int cap, int type, int midi_channels,
633			      int midi_voices, char *portname)
634{
635	struct snd_seq_port_info portinfo;
636	int  ret;
637
638	/* Set up the port */
639	memset(&portinfo, 0, sizeof(portinfo));
640	portinfo.addr.client = client;
641	strlcpy(portinfo.name, portname ? portname : "Unamed port",
642		sizeof(portinfo.name));
643
644	portinfo.capability = cap;
645	portinfo.type = type;
646	portinfo.kernel = pcbp;
647	portinfo.midi_channels = midi_channels;
648	portinfo.midi_voices = midi_voices;
649
650	/* Create it */
651	ret = snd_seq_kernel_client_ctl(client,
652					SNDRV_SEQ_IOCTL_CREATE_PORT,
653					&portinfo);
654
655	if (ret >= 0)
656		ret = portinfo.addr.port;
657
658	return ret;
659}
660
661EXPORT_SYMBOL(snd_seq_event_port_attach);
662
663/*
664 * Detach the driver from a port.
665 */
666/* exported */
667int snd_seq_event_port_detach(int client, int port)
668{
669	struct snd_seq_port_info portinfo;
670	int  err;
671
672	memset(&portinfo, 0, sizeof(portinfo));
673	portinfo.addr.client = client;
674	portinfo.addr.port   = port;
675	err = snd_seq_kernel_client_ctl(client,
676					SNDRV_SEQ_IOCTL_DELETE_PORT,
677					&portinfo);
678
679	return err;
680}
681
682EXPORT_SYMBOL(snd_seq_event_port_detach);
683