1/*
2 * bebob_stream.c - a part of driver for BeBoB based devices
3 *
4 * Copyright (c) 2013-2014 Takashi Sakamoto
5 *
6 * Licensed under the terms of the GNU General Public License, version 2.
7 */
8
9#include "./bebob.h"
10
11#define CALLBACK_TIMEOUT	1000
12#define FW_ISO_RESOURCE_DELAY	1000
13
14/*
15 * NOTE;
16 * For BeBoB streams, Both of input and output CMP connection are important.
17 *
18 * For most devices, each CMP connection starts to transmit/receive a
19 * corresponding stream. But for a few devices, both of CMP connection needs
20 * to start transmitting stream. An example is 'M-Audio Firewire 410'.
21 */
22
23/* 128 is an arbitrary length but it seems to be enough */
24#define FORMAT_MAXIMUM_LENGTH 128
25
26const unsigned int snd_bebob_rate_table[SND_BEBOB_STRM_FMT_ENTRIES] = {
27	[0] = 32000,
28	[1] = 44100,
29	[2] = 48000,
30	[3] = 88200,
31	[4] = 96000,
32	[5] = 176400,
33	[6] = 192000,
34};
35
36/*
37 * See: Table 51: Extended Stream Format Info ‘Sampling Frequency’
38 * in Additional AVC commands (Nov 2003, BridgeCo)
39 */
40static const unsigned int bridgeco_freq_table[] = {
41	[0] = 0x02,
42	[1] = 0x03,
43	[2] = 0x04,
44	[3] = 0x0a,
45	[4] = 0x05,
46	[5] = 0x06,
47	[6] = 0x07,
48};
49
50static int
51get_formation_index(unsigned int rate, unsigned int *index)
52{
53	unsigned int i;
54
55	for (i = 0; i < ARRAY_SIZE(snd_bebob_rate_table); i++) {
56		if (snd_bebob_rate_table[i] == rate) {
57			*index = i;
58			return 0;
59		}
60	}
61	return -EINVAL;
62}
63
64int
65snd_bebob_stream_get_rate(struct snd_bebob *bebob, unsigned int *curr_rate)
66{
67	unsigned int tx_rate, rx_rate, trials;
68	int err;
69
70	trials = 0;
71	do {
72		err = avc_general_get_sig_fmt(bebob->unit, &tx_rate,
73					      AVC_GENERAL_PLUG_DIR_OUT, 0);
74	} while (err == -EAGAIN && ++trials < 3);
75	if (err < 0)
76		goto end;
77
78	trials = 0;
79	do {
80		err = avc_general_get_sig_fmt(bebob->unit, &rx_rate,
81					      AVC_GENERAL_PLUG_DIR_IN, 0);
82	} while (err == -EAGAIN && ++trials < 3);
83	if (err < 0)
84		goto end;
85
86	*curr_rate = rx_rate;
87	if (rx_rate == tx_rate)
88		goto end;
89
90	/* synchronize receive stream rate to transmit stream rate */
91	err = avc_general_set_sig_fmt(bebob->unit, rx_rate,
92				      AVC_GENERAL_PLUG_DIR_IN, 0);
93end:
94	return err;
95}
96
97int
98snd_bebob_stream_set_rate(struct snd_bebob *bebob, unsigned int rate)
99{
100	int err;
101
102	err = avc_general_set_sig_fmt(bebob->unit, rate,
103				      AVC_GENERAL_PLUG_DIR_OUT, 0);
104	if (err < 0)
105		goto end;
106
107	err = avc_general_set_sig_fmt(bebob->unit, rate,
108				      AVC_GENERAL_PLUG_DIR_IN, 0);
109	if (err < 0)
110		goto end;
111
112	/*
113	 * Some devices need a bit time for transition.
114	 * 300msec is got by some experiments.
115	 */
116	msleep(300);
117end:
118	return err;
119}
120
121int
122snd_bebob_stream_check_internal_clock(struct snd_bebob *bebob, bool *internal)
123{
124	struct snd_bebob_clock_spec *clk_spec = bebob->spec->clock;
125	u8 addr[AVC_BRIDGECO_ADDR_BYTES], input[7];
126	unsigned int id;
127	int err = 0;
128
129	*internal = false;
130
131	/* 1.The device has its own operation to switch source of clock */
132	if (clk_spec) {
133		err = clk_spec->get(bebob, &id);
134		if (err < 0) {
135			dev_err(&bebob->unit->device,
136				"fail to get clock source: %d\n", err);
137			goto end;
138		}
139
140		if (id >= clk_spec->num) {
141			dev_err(&bebob->unit->device,
142				"clock source %d out of range 0..%d\n",
143				id, clk_spec->num - 1);
144			err = -EIO;
145			goto end;
146		}
147
148		if (strncmp(clk_spec->labels[id], SND_BEBOB_CLOCK_INTERNAL,
149			    strlen(SND_BEBOB_CLOCK_INTERNAL)) == 0)
150			*internal = true;
151
152		goto end;
153	}
154
155	/*
156	 * 2.The device don't support to switch source of clock then assumed
157	 *   to use internal clock always
158	 */
159	if (bebob->sync_input_plug < 0) {
160		*internal = true;
161		goto end;
162	}
163
164	/*
165	 * 3.The device supports to switch source of clock by an usual way.
166	 *   Let's check input for 'Music Sub Unit Sync Input' plug.
167	 */
168	avc_bridgeco_fill_msu_addr(addr, AVC_BRIDGECO_PLUG_DIR_IN,
169				   bebob->sync_input_plug);
170	err = avc_bridgeco_get_plug_input(bebob->unit, addr, input);
171	if (err < 0) {
172		dev_err(&bebob->unit->device,
173			"fail to get an input for MSU in plug %d: %d\n",
174			bebob->sync_input_plug, err);
175		goto end;
176	}
177
178	/*
179	 * If there are no input plugs, all of fields are 0xff.
180	 * Here check the first field. This field is used for direction.
181	 */
182	if (input[0] == 0xff) {
183		*internal = true;
184		goto end;
185	}
186
187	/*
188	 * If source of clock is internal CSR, Music Sub Unit Sync Input is
189	 * a destination of Music Sub Unit Sync Output.
190	 */
191	*internal = ((input[0] == AVC_BRIDGECO_PLUG_DIR_OUT) &&
192		     (input[1] == AVC_BRIDGECO_PLUG_MODE_SUBUNIT) &&
193		     (input[2] == 0x0c) &&
194		     (input[3] == 0x00));
195end:
196	return err;
197}
198
199static unsigned int
200map_data_channels(struct snd_bebob *bebob, struct amdtp_stream *s)
201{
202	unsigned int sec, sections, ch, channels;
203	unsigned int pcm, midi, location;
204	unsigned int stm_pos, sec_loc, pos;
205	u8 *buf, addr[AVC_BRIDGECO_ADDR_BYTES], type;
206	enum avc_bridgeco_plug_dir dir;
207	int err;
208
209	/*
210	 * The length of return value of this command cannot be expected. Here
211	 * use the maximum length of FCP.
212	 */
213	buf = kzalloc(256, GFP_KERNEL);
214	if (buf == NULL)
215		return -ENOMEM;
216
217	if (s == &bebob->tx_stream)
218		dir = AVC_BRIDGECO_PLUG_DIR_OUT;
219	else
220		dir = AVC_BRIDGECO_PLUG_DIR_IN;
221
222	avc_bridgeco_fill_unit_addr(addr, dir, AVC_BRIDGECO_PLUG_UNIT_ISOC, 0);
223	err = avc_bridgeco_get_plug_ch_pos(bebob->unit, addr, buf, 256);
224	if (err < 0) {
225		dev_err(&bebob->unit->device,
226			"fail to get channel position for isoc %s plug 0: %d\n",
227			(dir == AVC_BRIDGECO_PLUG_DIR_IN) ? "in" : "out",
228			err);
229		goto end;
230	}
231	pos = 0;
232
233	/* positions in I/O buffer */
234	pcm = 0;
235	midi = 0;
236
237	/* the number of sections in AMDTP packet */
238	sections = buf[pos++];
239
240	for (sec = 0; sec < sections; sec++) {
241		/* type of this section */
242		avc_bridgeco_fill_unit_addr(addr, dir,
243					    AVC_BRIDGECO_PLUG_UNIT_ISOC, 0);
244		err = avc_bridgeco_get_plug_section_type(bebob->unit, addr,
245							 sec, &type);
246		if (err < 0) {
247			dev_err(&bebob->unit->device,
248			"fail to get section type for isoc %s plug 0: %d\n",
249				(dir == AVC_BRIDGECO_PLUG_DIR_IN) ? "in" :
250								    "out",
251				err);
252			goto end;
253		}
254		/* NoType */
255		if (type == 0xff) {
256			err = -ENOSYS;
257			goto end;
258		}
259
260		/* the number of channels in this section */
261		channels = buf[pos++];
262
263		for (ch = 0; ch < channels; ch++) {
264			/* position of this channel in AMDTP packet */
265			stm_pos = buf[pos++] - 1;
266			/* location of this channel in this section */
267			sec_loc = buf[pos++] - 1;
268
269			/*
270			 * Basically the number of location is within the
271			 * number of channels in this section. But some models
272			 * of M-Audio don't follow this. Its location for MIDI
273			 * is the position of MIDI channels in AMDTP packet.
274			 */
275			if (sec_loc >= channels)
276				sec_loc = ch;
277
278			switch (type) {
279			/* for MIDI conformant data channel */
280			case 0x0a:
281				/* AMDTP_MAX_CHANNELS_FOR_MIDI is 1. */
282				if ((midi > 0) && (stm_pos != midi)) {
283					err = -ENOSYS;
284					goto end;
285				}
286				s->midi_position = stm_pos;
287				midi = stm_pos;
288				break;
289			/* for PCM data channel */
290			case 0x01:	/* Headphone */
291			case 0x02:	/* Microphone */
292			case 0x03:	/* Line */
293			case 0x04:	/* SPDIF */
294			case 0x05:	/* ADAT */
295			case 0x06:	/* TDIF */
296			case 0x07:	/* MADI */
297			/* for undefined/changeable signal  */
298			case 0x08:	/* Analog */
299			case 0x09:	/* Digital */
300			default:
301				location = pcm + sec_loc;
302				if (location >= AMDTP_MAX_CHANNELS_FOR_PCM) {
303					err = -ENOSYS;
304					goto end;
305				}
306				s->pcm_positions[location] = stm_pos;
307				break;
308			}
309		}
310
311		if (type != 0x0a)
312			pcm += channels;
313		else
314			midi += channels;
315	}
316end:
317	kfree(buf);
318	return err;
319}
320
321static int
322init_both_connections(struct snd_bebob *bebob)
323{
324	int err;
325
326	err = cmp_connection_init(&bebob->in_conn,
327				  bebob->unit, CMP_INPUT, 0);
328	if (err < 0)
329		goto end;
330
331	err = cmp_connection_init(&bebob->out_conn,
332				  bebob->unit, CMP_OUTPUT, 0);
333	if (err < 0)
334		cmp_connection_destroy(&bebob->in_conn);
335end:
336	return err;
337}
338
339static int
340check_connection_used_by_others(struct snd_bebob *bebob, struct amdtp_stream *s)
341{
342	struct cmp_connection *conn;
343	bool used;
344	int err;
345
346	if (s == &bebob->tx_stream)
347		conn = &bebob->out_conn;
348	else
349		conn = &bebob->in_conn;
350
351	err = cmp_connection_check_used(conn, &used);
352	if ((err >= 0) && used && !amdtp_stream_running(s)) {
353		dev_err(&bebob->unit->device,
354			"Connection established by others: %cPCR[%d]\n",
355			(conn->direction == CMP_OUTPUT) ? 'o' : 'i',
356			conn->pcr_index);
357		err = -EBUSY;
358	}
359
360	return err;
361}
362
363static int
364make_both_connections(struct snd_bebob *bebob, unsigned int rate)
365{
366	int index, pcm_channels, midi_channels, err = 0;
367
368	if (bebob->connected)
369		goto end;
370
371	/* confirm params for both streams */
372	err = get_formation_index(rate, &index);
373	if (err < 0)
374		goto end;
375	pcm_channels = bebob->tx_stream_formations[index].pcm;
376	midi_channels = bebob->tx_stream_formations[index].midi;
377	amdtp_stream_set_parameters(&bebob->tx_stream,
378				    rate, pcm_channels, midi_channels * 8);
379	pcm_channels = bebob->rx_stream_formations[index].pcm;
380	midi_channels = bebob->rx_stream_formations[index].midi;
381	amdtp_stream_set_parameters(&bebob->rx_stream,
382				    rate, pcm_channels, midi_channels * 8);
383
384	/* establish connections for both streams */
385	err = cmp_connection_establish(&bebob->out_conn,
386			amdtp_stream_get_max_payload(&bebob->tx_stream));
387	if (err < 0)
388		goto end;
389	err = cmp_connection_establish(&bebob->in_conn,
390			amdtp_stream_get_max_payload(&bebob->rx_stream));
391	if (err < 0) {
392		cmp_connection_break(&bebob->out_conn);
393		goto end;
394	}
395
396	bebob->connected = true;
397end:
398	return err;
399}
400
401static void
402break_both_connections(struct snd_bebob *bebob)
403{
404	cmp_connection_break(&bebob->in_conn);
405	cmp_connection_break(&bebob->out_conn);
406
407	bebob->connected = false;
408
409	/* These models seems to be in transition state for a longer time. */
410	if (bebob->maudio_special_quirk != NULL)
411		msleep(200);
412}
413
414static void
415destroy_both_connections(struct snd_bebob *bebob)
416{
417	cmp_connection_destroy(&bebob->in_conn);
418	cmp_connection_destroy(&bebob->out_conn);
419}
420
421static int
422get_sync_mode(struct snd_bebob *bebob, enum cip_flags *sync_mode)
423{
424	/* currently this module doesn't support SYT-Match mode */
425	*sync_mode = CIP_SYNC_TO_DEVICE;
426	return 0;
427}
428
429static int
430start_stream(struct snd_bebob *bebob, struct amdtp_stream *stream,
431	     unsigned int rate)
432{
433	struct cmp_connection *conn;
434	int err = 0;
435
436	if (stream == &bebob->rx_stream)
437		conn = &bebob->in_conn;
438	else
439		conn = &bebob->out_conn;
440
441	/* channel mapping */
442	if (bebob->maudio_special_quirk == NULL) {
443		err = map_data_channels(bebob, stream);
444		if (err < 0)
445			goto end;
446	}
447
448	/* start amdtp stream */
449	err = amdtp_stream_start(stream,
450				 conn->resources.channel,
451				 conn->speed);
452end:
453	return err;
454}
455
456int snd_bebob_stream_init_duplex(struct snd_bebob *bebob)
457{
458	int err;
459
460	err = init_both_connections(bebob);
461	if (err < 0)
462		goto end;
463
464	err = amdtp_stream_init(&bebob->tx_stream, bebob->unit,
465				AMDTP_IN_STREAM, CIP_BLOCKING);
466	if (err < 0) {
467		amdtp_stream_destroy(&bebob->tx_stream);
468		destroy_both_connections(bebob);
469		goto end;
470	}
471	/* See comments in next function */
472	init_completion(&bebob->bus_reset);
473	bebob->tx_stream.flags |= CIP_SKIP_INIT_DBC_CHECK;
474	/*
475	 * At high sampling rate, M-Audio special firmware transmits empty
476	 * packet with the value of dbc incremented by 8 but the others are
477	 * valid to IEC 61883-1.
478	 */
479	if (bebob->maudio_special_quirk)
480		bebob->tx_stream.flags |= CIP_EMPTY_HAS_WRONG_DBC;
481
482	err = amdtp_stream_init(&bebob->rx_stream, bebob->unit,
483				AMDTP_OUT_STREAM, CIP_BLOCKING);
484	if (err < 0) {
485		amdtp_stream_destroy(&bebob->tx_stream);
486		amdtp_stream_destroy(&bebob->rx_stream);
487		destroy_both_connections(bebob);
488	}
489end:
490	return err;
491}
492
493int snd_bebob_stream_start_duplex(struct snd_bebob *bebob, unsigned int rate)
494{
495	struct snd_bebob_rate_spec *rate_spec = bebob->spec->rate;
496	struct amdtp_stream *master, *slave;
497	atomic_t *slave_substreams;
498	enum cip_flags sync_mode;
499	unsigned int curr_rate;
500	bool updated = false;
501	int err = 0;
502
503	/*
504	 * Normal BeBoB firmware has a quirk at bus reset to transmits packets
505	 * with discontinuous value in dbc field.
506	 *
507	 * This 'struct completion' is used to call .update() at first to update
508	 * connections/streams. Next following codes handle streaming error.
509	 */
510	if (amdtp_streaming_error(&bebob->tx_stream)) {
511		if (completion_done(&bebob->bus_reset))
512			reinit_completion(&bebob->bus_reset);
513
514		updated = (wait_for_completion_interruptible_timeout(
515				&bebob->bus_reset,
516				msecs_to_jiffies(FW_ISO_RESOURCE_DELAY)) > 0);
517	}
518
519	mutex_lock(&bebob->mutex);
520
521	/* Need no substreams */
522	if (atomic_read(&bebob->playback_substreams) == 0 &&
523	    atomic_read(&bebob->capture_substreams)  == 0)
524		goto end;
525
526	err = get_sync_mode(bebob, &sync_mode);
527	if (err < 0)
528		goto end;
529	if (sync_mode == CIP_SYNC_TO_DEVICE) {
530		master = &bebob->tx_stream;
531		slave  = &bebob->rx_stream;
532		slave_substreams = &bebob->playback_substreams;
533	} else {
534		master = &bebob->rx_stream;
535		slave  = &bebob->tx_stream;
536		slave_substreams = &bebob->capture_substreams;
537	}
538
539	/*
540	 * Considering JACK/FFADO streaming:
541	 * TODO: This can be removed hwdep functionality becomes popular.
542	 */
543	err = check_connection_used_by_others(bebob, master);
544	if (err < 0)
545		goto end;
546
547	/*
548	 * packet queueing error or detecting discontinuity
549	 *
550	 * At bus reset, connections should not be broken here. So streams need
551	 * to be re-started. This is a reason to use SKIP_INIT_DBC_CHECK flag.
552	 */
553	if (amdtp_streaming_error(master))
554		amdtp_stream_stop(master);
555	if (amdtp_streaming_error(slave))
556		amdtp_stream_stop(slave);
557	if (!updated &&
558	    !amdtp_stream_running(master) && !amdtp_stream_running(slave))
559		break_both_connections(bebob);
560
561	/* stop streams if rate is different */
562	err = rate_spec->get(bebob, &curr_rate);
563	if (err < 0) {
564		dev_err(&bebob->unit->device,
565			"fail to get sampling rate: %d\n", err);
566		goto end;
567	}
568	if (rate == 0)
569		rate = curr_rate;
570	if (rate != curr_rate) {
571		amdtp_stream_stop(master);
572		amdtp_stream_stop(slave);
573		break_both_connections(bebob);
574	}
575
576	/* master should be always running */
577	if (!amdtp_stream_running(master)) {
578		amdtp_stream_set_sync(sync_mode, master, slave);
579		bebob->master = master;
580
581		/*
582		 * NOTE:
583		 * If establishing connections at first, Yamaha GO46
584		 * (and maybe Terratec X24) don't generate sound.
585		 *
586		 * For firmware customized by M-Audio, refer to next NOTE.
587		 */
588		if (bebob->maudio_special_quirk == NULL) {
589			err = rate_spec->set(bebob, rate);
590			if (err < 0) {
591				dev_err(&bebob->unit->device,
592					"fail to set sampling rate: %d\n",
593					err);
594				goto end;
595			}
596		}
597
598		err = make_both_connections(bebob, rate);
599		if (err < 0)
600			goto end;
601
602		err = start_stream(bebob, master, rate);
603		if (err < 0) {
604			dev_err(&bebob->unit->device,
605				"fail to run AMDTP master stream:%d\n", err);
606			break_both_connections(bebob);
607			goto end;
608		}
609
610		/*
611		 * NOTE:
612		 * The firmware customized by M-Audio uses these commands to
613		 * start transmitting stream. This is not usual way.
614		 */
615		if (bebob->maudio_special_quirk != NULL) {
616			err = rate_spec->set(bebob, rate);
617			if (err < 0) {
618				dev_err(&bebob->unit->device,
619					"fail to ensure sampling rate: %d\n",
620					err);
621				amdtp_stream_stop(master);
622				break_both_connections(bebob);
623				goto end;
624			}
625		}
626
627		/* wait first callback */
628		if (!amdtp_stream_wait_callback(master, CALLBACK_TIMEOUT)) {
629			amdtp_stream_stop(master);
630			break_both_connections(bebob);
631			err = -ETIMEDOUT;
632			goto end;
633		}
634	}
635
636	/* start slave if needed */
637	if (atomic_read(slave_substreams) > 0 && !amdtp_stream_running(slave)) {
638		err = start_stream(bebob, slave, rate);
639		if (err < 0) {
640			dev_err(&bebob->unit->device,
641				"fail to run AMDTP slave stream:%d\n", err);
642			amdtp_stream_stop(master);
643			break_both_connections(bebob);
644			goto end;
645		}
646
647		/* wait first callback */
648		if (!amdtp_stream_wait_callback(slave, CALLBACK_TIMEOUT)) {
649			amdtp_stream_stop(slave);
650			amdtp_stream_stop(master);
651			break_both_connections(bebob);
652			err = -ETIMEDOUT;
653		}
654	}
655end:
656	mutex_unlock(&bebob->mutex);
657	return err;
658}
659
660void snd_bebob_stream_stop_duplex(struct snd_bebob *bebob)
661{
662	struct amdtp_stream *master, *slave;
663	atomic_t *master_substreams, *slave_substreams;
664
665	if (bebob->master == &bebob->rx_stream) {
666		slave  = &bebob->tx_stream;
667		master = &bebob->rx_stream;
668		slave_substreams  = &bebob->capture_substreams;
669		master_substreams = &bebob->playback_substreams;
670	} else {
671		slave  = &bebob->rx_stream;
672		master = &bebob->tx_stream;
673		slave_substreams  = &bebob->playback_substreams;
674		master_substreams = &bebob->capture_substreams;
675	}
676
677	mutex_lock(&bebob->mutex);
678
679	if (atomic_read(slave_substreams) == 0) {
680		amdtp_stream_pcm_abort(slave);
681		amdtp_stream_stop(slave);
682
683		if (atomic_read(master_substreams) == 0) {
684			amdtp_stream_pcm_abort(master);
685			amdtp_stream_stop(master);
686			break_both_connections(bebob);
687		}
688	}
689
690	mutex_unlock(&bebob->mutex);
691}
692
693void snd_bebob_stream_update_duplex(struct snd_bebob *bebob)
694{
695	/* vs. XRUN recovery due to discontinuity at bus reset */
696	mutex_lock(&bebob->mutex);
697
698	if ((cmp_connection_update(&bebob->in_conn) < 0) ||
699	    (cmp_connection_update(&bebob->out_conn) < 0)) {
700		amdtp_stream_pcm_abort(&bebob->rx_stream);
701		amdtp_stream_pcm_abort(&bebob->tx_stream);
702		amdtp_stream_stop(&bebob->rx_stream);
703		amdtp_stream_stop(&bebob->tx_stream);
704		break_both_connections(bebob);
705	} else {
706		amdtp_stream_update(&bebob->rx_stream);
707		amdtp_stream_update(&bebob->tx_stream);
708	}
709
710	/* wake up stream_start_duplex() */
711	if (!completion_done(&bebob->bus_reset))
712		complete_all(&bebob->bus_reset);
713
714	mutex_unlock(&bebob->mutex);
715}
716
717/*
718 * This function should be called before starting streams or after stopping
719 * streams.
720 */
721void snd_bebob_stream_destroy_duplex(struct snd_bebob *bebob)
722{
723	amdtp_stream_destroy(&bebob->rx_stream);
724	amdtp_stream_destroy(&bebob->tx_stream);
725
726	destroy_both_connections(bebob);
727}
728
729/*
730 * See: Table 50: Extended Stream Format Info Format Hierarchy Level 2’
731 * in Additional AVC commands (Nov 2003, BridgeCo)
732 * Also 'Clause 12 AM824 sequence adaption layers' in IEC 61883-6:2005
733 */
734static int
735parse_stream_formation(u8 *buf, unsigned int len,
736		       struct snd_bebob_stream_formation *formation)
737{
738	unsigned int i, e, channels, format;
739
740	/*
741	 * this module can support a hierarchy combination that:
742	 *  Root:	Audio and Music (0x90)
743	 *  Level 1:	AM824 Compound  (0x40)
744	 */
745	if ((buf[0] != 0x90) || (buf[1] != 0x40))
746		return -ENOSYS;
747
748	/* check sampling rate */
749	for (i = 0; i < ARRAY_SIZE(bridgeco_freq_table); i++) {
750		if (buf[2] == bridgeco_freq_table[i])
751			break;
752	}
753	if (i == ARRAY_SIZE(bridgeco_freq_table))
754		return -ENOSYS;
755
756	/* Avoid double count by different entries for the same rate. */
757	memset(&formation[i], 0, sizeof(struct snd_bebob_stream_formation));
758
759	for (e = 0; e < buf[4]; e++) {
760		channels = buf[5 + e * 2];
761		format = buf[6 + e * 2];
762
763		switch (format) {
764		/* IEC 60958 Conformant, currently handled as MBLA */
765		case 0x00:
766		/* Multi bit linear audio */
767		case 0x06:	/* Raw */
768			formation[i].pcm += channels;
769			break;
770		/* MIDI Conformant */
771		case 0x0d:
772			formation[i].midi += channels;
773			break;
774		/* IEC 61937-3 to 7 */
775		case 0x01:
776		case 0x02:
777		case 0x03:
778		case 0x04:
779		case 0x05:
780		/* Multi bit linear audio */
781		case 0x07:	/* DVD-Audio */
782		case 0x0c:	/* High Precision */
783		/* One Bit Audio */
784		case 0x08:	/* (Plain) Raw */
785		case 0x09:	/* (Plain) SACD */
786		case 0x0a:	/* (Encoded) Raw */
787		case 0x0b:	/* (Encoded) SACD */
788		/* Synchronization Stream (Stereo Raw audio) */
789		case 0x40:
790		/* Don't care */
791		case 0xff:
792		default:
793			return -ENOSYS;	/* not supported */
794		}
795	}
796
797	if (formation[i].pcm  > AMDTP_MAX_CHANNELS_FOR_PCM ||
798	    formation[i].midi > AMDTP_MAX_CHANNELS_FOR_MIDI)
799		return -ENOSYS;
800
801	return 0;
802}
803
804static int
805fill_stream_formations(struct snd_bebob *bebob, enum avc_bridgeco_plug_dir dir,
806		       unsigned short pid)
807{
808	u8 *buf;
809	struct snd_bebob_stream_formation *formations;
810	unsigned int len, eid;
811	u8 addr[AVC_BRIDGECO_ADDR_BYTES];
812	int err;
813
814	buf = kmalloc(FORMAT_MAXIMUM_LENGTH, GFP_KERNEL);
815	if (buf == NULL)
816		return -ENOMEM;
817
818	if (dir == AVC_BRIDGECO_PLUG_DIR_IN)
819		formations = bebob->rx_stream_formations;
820	else
821		formations = bebob->tx_stream_formations;
822
823	for (eid = 0; eid < SND_BEBOB_STRM_FMT_ENTRIES; eid++) {
824		len = FORMAT_MAXIMUM_LENGTH;
825		avc_bridgeco_fill_unit_addr(addr, dir,
826					    AVC_BRIDGECO_PLUG_UNIT_ISOC, pid);
827		err = avc_bridgeco_get_plug_strm_fmt(bebob->unit, addr, buf,
828						     &len, eid);
829		/* No entries remained. */
830		if (err == -EINVAL && eid > 0) {
831			err = 0;
832			break;
833		} else if (err < 0) {
834			dev_err(&bebob->unit->device,
835			"fail to get stream format %d for isoc %s plug %d:%d\n",
836				eid,
837				(dir == AVC_BRIDGECO_PLUG_DIR_IN) ? "in" :
838								    "out",
839				pid, err);
840			break;
841		}
842
843		err = parse_stream_formation(buf, len, formations);
844		if (err < 0)
845			break;
846	}
847
848	kfree(buf);
849	return err;
850}
851
852static int
853seek_msu_sync_input_plug(struct snd_bebob *bebob)
854{
855	u8 plugs[AVC_PLUG_INFO_BUF_BYTES], addr[AVC_BRIDGECO_ADDR_BYTES];
856	unsigned int i;
857	enum avc_bridgeco_plug_type type;
858	int err;
859
860	/* Get the number of Music Sub Unit for both direction. */
861	err = avc_general_get_plug_info(bebob->unit, 0x0c, 0x00, 0x00, plugs);
862	if (err < 0) {
863		dev_err(&bebob->unit->device,
864			"fail to get info for MSU in/out plugs: %d\n",
865			err);
866		goto end;
867	}
868
869	/* seek destination plugs for 'MSU sync input' */
870	bebob->sync_input_plug = -1;
871	for (i = 0; i < plugs[0]; i++) {
872		avc_bridgeco_fill_msu_addr(addr, AVC_BRIDGECO_PLUG_DIR_IN, i);
873		err = avc_bridgeco_get_plug_type(bebob->unit, addr, &type);
874		if (err < 0) {
875			dev_err(&bebob->unit->device,
876				"fail to get type for MSU in plug %d: %d\n",
877				i, err);
878			goto end;
879		}
880
881		if (type == AVC_BRIDGECO_PLUG_TYPE_SYNC) {
882			bebob->sync_input_plug = i;
883			break;
884		}
885	}
886end:
887	return err;
888}
889
890int snd_bebob_stream_discover(struct snd_bebob *bebob)
891{
892	struct snd_bebob_clock_spec *clk_spec = bebob->spec->clock;
893	u8 plugs[AVC_PLUG_INFO_BUF_BYTES], addr[AVC_BRIDGECO_ADDR_BYTES];
894	enum avc_bridgeco_plug_type type;
895	unsigned int i;
896	int err;
897
898	/* the number of plugs for isoc in/out, ext in/out  */
899	err = avc_general_get_plug_info(bebob->unit, 0x1f, 0x07, 0x00, plugs);
900	if (err < 0) {
901		dev_err(&bebob->unit->device,
902		"fail to get info for isoc/external in/out plugs: %d\n",
903			err);
904		goto end;
905	}
906
907	/*
908	 * This module supports at least one isoc input plug and one isoc
909	 * output plug.
910	 */
911	if ((plugs[0] == 0) || (plugs[1] == 0)) {
912		err = -ENOSYS;
913		goto end;
914	}
915
916	avc_bridgeco_fill_unit_addr(addr, AVC_BRIDGECO_PLUG_DIR_IN,
917				    AVC_BRIDGECO_PLUG_UNIT_ISOC, 0);
918	err = avc_bridgeco_get_plug_type(bebob->unit, addr, &type);
919	if (err < 0) {
920		dev_err(&bebob->unit->device,
921			"fail to get type for isoc in plug 0: %d\n", err);
922		goto end;
923	} else if (type != AVC_BRIDGECO_PLUG_TYPE_ISOC) {
924		err = -ENOSYS;
925		goto end;
926	}
927	err = fill_stream_formations(bebob, AVC_BRIDGECO_PLUG_DIR_IN, 0);
928	if (err < 0)
929		goto end;
930
931	avc_bridgeco_fill_unit_addr(addr, AVC_BRIDGECO_PLUG_DIR_OUT,
932				    AVC_BRIDGECO_PLUG_UNIT_ISOC, 0);
933	err = avc_bridgeco_get_plug_type(bebob->unit, addr, &type);
934	if (err < 0) {
935		dev_err(&bebob->unit->device,
936			"fail to get type for isoc out plug 0: %d\n", err);
937		goto end;
938	} else if (type != AVC_BRIDGECO_PLUG_TYPE_ISOC) {
939		err = -ENOSYS;
940		goto end;
941	}
942	err = fill_stream_formations(bebob, AVC_BRIDGECO_PLUG_DIR_OUT, 0);
943	if (err < 0)
944		goto end;
945
946	/* count external input plugs for MIDI */
947	bebob->midi_input_ports = 0;
948	for (i = 0; i < plugs[2]; i++) {
949		avc_bridgeco_fill_unit_addr(addr, AVC_BRIDGECO_PLUG_DIR_IN,
950					    AVC_BRIDGECO_PLUG_UNIT_EXT, i);
951		err = avc_bridgeco_get_plug_type(bebob->unit, addr, &type);
952		if (err < 0) {
953			dev_err(&bebob->unit->device,
954			"fail to get type for external in plug %d: %d\n",
955				i, err);
956			goto end;
957		} else if (type == AVC_BRIDGECO_PLUG_TYPE_MIDI) {
958			bebob->midi_input_ports++;
959		}
960	}
961
962	/* count external output plugs for MIDI */
963	bebob->midi_output_ports = 0;
964	for (i = 0; i < plugs[3]; i++) {
965		avc_bridgeco_fill_unit_addr(addr, AVC_BRIDGECO_PLUG_DIR_OUT,
966					    AVC_BRIDGECO_PLUG_UNIT_EXT, i);
967		err = avc_bridgeco_get_plug_type(bebob->unit, addr, &type);
968		if (err < 0) {
969			dev_err(&bebob->unit->device,
970			"fail to get type for external out plug %d: %d\n",
971				i, err);
972			goto end;
973		} else if (type == AVC_BRIDGECO_PLUG_TYPE_MIDI) {
974			bebob->midi_output_ports++;
975		}
976	}
977
978	/* for check source of clock later */
979	if (!clk_spec)
980		err = seek_msu_sync_input_plug(bebob);
981end:
982	return err;
983}
984
985void snd_bebob_stream_lock_changed(struct snd_bebob *bebob)
986{
987	bebob->dev_lock_changed = true;
988	wake_up(&bebob->hwdep_wait);
989}
990
991int snd_bebob_stream_lock_try(struct snd_bebob *bebob)
992{
993	int err;
994
995	spin_lock_irq(&bebob->lock);
996
997	/* user land lock this */
998	if (bebob->dev_lock_count < 0) {
999		err = -EBUSY;
1000		goto end;
1001	}
1002
1003	/* this is the first time */
1004	if (bebob->dev_lock_count++ == 0)
1005		snd_bebob_stream_lock_changed(bebob);
1006	err = 0;
1007end:
1008	spin_unlock_irq(&bebob->lock);
1009	return err;
1010}
1011
1012void snd_bebob_stream_lock_release(struct snd_bebob *bebob)
1013{
1014	spin_lock_irq(&bebob->lock);
1015
1016	if (WARN_ON(bebob->dev_lock_count <= 0))
1017		goto end;
1018	if (--bebob->dev_lock_count == 0)
1019		snd_bebob_stream_lock_changed(bebob);
1020end:
1021	spin_unlock_irq(&bebob->lock);
1022}
1023