xref: /openbmc/linux/sound/firewire/amdtp-stream.c (revision a36954f5)
1 /*
2  * Audio and Music Data Transmission Protocol (IEC 61883-6) streams
3  * with Common Isochronous Packet (IEC 61883-1) headers
4  *
5  * Copyright (c) Clemens Ladisch <clemens@ladisch.de>
6  * Licensed under the terms of the GNU General Public License, version 2.
7  */
8 
9 #include <linux/device.h>
10 #include <linux/err.h>
11 #include <linux/firewire.h>
12 #include <linux/module.h>
13 #include <linux/slab.h>
14 #include <sound/pcm.h>
15 #include <sound/pcm_params.h>
16 #include "amdtp-stream.h"
17 
18 #define TICKS_PER_CYCLE		3072
19 #define CYCLES_PER_SECOND	8000
20 #define TICKS_PER_SECOND	(TICKS_PER_CYCLE * CYCLES_PER_SECOND)
21 
22 /* Always support Linux tracing subsystem. */
23 #define CREATE_TRACE_POINTS
24 #include "amdtp-stream-trace.h"
25 
26 #define TRANSFER_DELAY_TICKS	0x2e00 /* 479.17 microseconds */
27 
28 /* isochronous header parameters */
29 #define ISO_DATA_LENGTH_SHIFT	16
30 #define TAG_NO_CIP_HEADER	0
31 #define TAG_CIP			1
32 
33 /* common isochronous packet header parameters */
34 #define CIP_EOH_SHIFT		31
35 #define CIP_EOH			(1u << CIP_EOH_SHIFT)
36 #define CIP_EOH_MASK		0x80000000
37 #define CIP_SID_SHIFT		24
38 #define CIP_SID_MASK		0x3f000000
39 #define CIP_DBS_MASK		0x00ff0000
40 #define CIP_DBS_SHIFT		16
41 #define CIP_SPH_MASK		0x00000400
42 #define CIP_SPH_SHIFT		10
43 #define CIP_DBC_MASK		0x000000ff
44 #define CIP_FMT_SHIFT		24
45 #define CIP_FMT_MASK		0x3f000000
46 #define CIP_FDF_MASK		0x00ff0000
47 #define CIP_FDF_SHIFT		16
48 #define CIP_SYT_MASK		0x0000ffff
49 #define CIP_SYT_NO_INFO		0xffff
50 
51 /* Audio and Music transfer protocol specific parameters */
52 #define CIP_FMT_AM		0x10
53 #define AMDTP_FDF_NO_DATA	0xff
54 
55 /* TODO: make these configurable */
56 #define INTERRUPT_INTERVAL	16
57 #define QUEUE_LENGTH		48
58 
59 #define IN_PACKET_HEADER_SIZE	4
60 #define OUT_PACKET_HEADER_SIZE	0
61 
62 static void pcm_period_tasklet(unsigned long data);
63 
64 /**
65  * amdtp_stream_init - initialize an AMDTP stream structure
66  * @s: the AMDTP stream to initialize
67  * @unit: the target of the stream
68  * @dir: the direction of stream
69  * @flags: the packet transmission method to use
70  * @fmt: the value of fmt field in CIP header
71  * @process_data_blocks: callback handler to process data blocks
72  * @protocol_size: the size to allocate newly for protocol
73  */
74 int amdtp_stream_init(struct amdtp_stream *s, struct fw_unit *unit,
75 		      enum amdtp_stream_direction dir, enum cip_flags flags,
76 		      unsigned int fmt,
77 		      amdtp_stream_process_data_blocks_t process_data_blocks,
78 		      unsigned int protocol_size)
79 {
80 	if (process_data_blocks == NULL)
81 		return -EINVAL;
82 
83 	s->protocol = kzalloc(protocol_size, GFP_KERNEL);
84 	if (!s->protocol)
85 		return -ENOMEM;
86 
87 	s->unit = unit;
88 	s->direction = dir;
89 	s->flags = flags;
90 	s->context = ERR_PTR(-1);
91 	mutex_init(&s->mutex);
92 	tasklet_init(&s->period_tasklet, pcm_period_tasklet, (unsigned long)s);
93 	s->packet_index = 0;
94 
95 	init_waitqueue_head(&s->callback_wait);
96 	s->callbacked = false;
97 
98 	s->fmt = fmt;
99 	s->process_data_blocks = process_data_blocks;
100 
101 	return 0;
102 }
103 EXPORT_SYMBOL(amdtp_stream_init);
104 
105 /**
106  * amdtp_stream_destroy - free stream resources
107  * @s: the AMDTP stream to destroy
108  */
109 void amdtp_stream_destroy(struct amdtp_stream *s)
110 {
111 	/* Not initialized. */
112 	if (s->protocol == NULL)
113 		return;
114 
115 	WARN_ON(amdtp_stream_running(s));
116 	kfree(s->protocol);
117 	mutex_destroy(&s->mutex);
118 }
119 EXPORT_SYMBOL(amdtp_stream_destroy);
120 
121 const unsigned int amdtp_syt_intervals[CIP_SFC_COUNT] = {
122 	[CIP_SFC_32000]  =  8,
123 	[CIP_SFC_44100]  =  8,
124 	[CIP_SFC_48000]  =  8,
125 	[CIP_SFC_88200]  = 16,
126 	[CIP_SFC_96000]  = 16,
127 	[CIP_SFC_176400] = 32,
128 	[CIP_SFC_192000] = 32,
129 };
130 EXPORT_SYMBOL(amdtp_syt_intervals);
131 
132 const unsigned int amdtp_rate_table[CIP_SFC_COUNT] = {
133 	[CIP_SFC_32000]  =  32000,
134 	[CIP_SFC_44100]  =  44100,
135 	[CIP_SFC_48000]  =  48000,
136 	[CIP_SFC_88200]  =  88200,
137 	[CIP_SFC_96000]  =  96000,
138 	[CIP_SFC_176400] = 176400,
139 	[CIP_SFC_192000] = 192000,
140 };
141 EXPORT_SYMBOL(amdtp_rate_table);
142 
143 /**
144  * amdtp_stream_add_pcm_hw_constraints - add hw constraints for PCM substream
145  * @s:		the AMDTP stream, which must be initialized.
146  * @runtime:	the PCM substream runtime
147  */
148 int amdtp_stream_add_pcm_hw_constraints(struct amdtp_stream *s,
149 					struct snd_pcm_runtime *runtime)
150 {
151 	int err;
152 
153 	/*
154 	 * Currently firewire-lib processes 16 packets in one software
155 	 * interrupt callback. This equals to 2msec but actually the
156 	 * interval of the interrupts has a jitter.
157 	 * Additionally, even if adding a constraint to fit period size to
158 	 * 2msec, actual calculated frames per period doesn't equal to 2msec,
159 	 * depending on sampling rate.
160 	 * Anyway, the interval to call snd_pcm_period_elapsed() cannot 2msec.
161 	 * Here let us use 5msec for safe period interrupt.
162 	 */
163 	err = snd_pcm_hw_constraint_minmax(runtime,
164 					   SNDRV_PCM_HW_PARAM_PERIOD_TIME,
165 					   5000, UINT_MAX);
166 	if (err < 0)
167 		goto end;
168 
169 	/* Non-Blocking stream has no more constraints */
170 	if (!(s->flags & CIP_BLOCKING))
171 		goto end;
172 
173 	/*
174 	 * One AMDTP packet can include some frames. In blocking mode, the
175 	 * number equals to SYT_INTERVAL. So the number is 8, 16 or 32,
176 	 * depending on its sampling rate. For accurate period interrupt, it's
177 	 * preferrable to align period/buffer sizes to current SYT_INTERVAL.
178 	 *
179 	 * TODO: These constraints can be improved with proper rules.
180 	 * Currently apply LCM of SYT_INTERVALs.
181 	 */
182 	err = snd_pcm_hw_constraint_step(runtime, 0,
183 					 SNDRV_PCM_HW_PARAM_PERIOD_SIZE, 32);
184 	if (err < 0)
185 		goto end;
186 	err = snd_pcm_hw_constraint_step(runtime, 0,
187 					 SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 32);
188 end:
189 	return err;
190 }
191 EXPORT_SYMBOL(amdtp_stream_add_pcm_hw_constraints);
192 
193 /**
194  * amdtp_stream_set_parameters - set stream parameters
195  * @s: the AMDTP stream to configure
196  * @rate: the sample rate
197  * @data_block_quadlets: the size of a data block in quadlet unit
198  *
199  * The parameters must be set before the stream is started, and must not be
200  * changed while the stream is running.
201  */
202 int amdtp_stream_set_parameters(struct amdtp_stream *s, unsigned int rate,
203 				unsigned int data_block_quadlets)
204 {
205 	unsigned int sfc;
206 
207 	for (sfc = 0; sfc < ARRAY_SIZE(amdtp_rate_table); ++sfc) {
208 		if (amdtp_rate_table[sfc] == rate)
209 			break;
210 	}
211 	if (sfc == ARRAY_SIZE(amdtp_rate_table))
212 		return -EINVAL;
213 
214 	s->sfc = sfc;
215 	s->data_block_quadlets = data_block_quadlets;
216 	s->syt_interval = amdtp_syt_intervals[sfc];
217 
218 	/* default buffering in the device */
219 	s->transfer_delay = TRANSFER_DELAY_TICKS - TICKS_PER_CYCLE;
220 	if (s->flags & CIP_BLOCKING)
221 		/* additional buffering needed to adjust for no-data packets */
222 		s->transfer_delay += TICKS_PER_SECOND * s->syt_interval / rate;
223 
224 	return 0;
225 }
226 EXPORT_SYMBOL(amdtp_stream_set_parameters);
227 
228 /**
229  * amdtp_stream_get_max_payload - get the stream's packet size
230  * @s: the AMDTP stream
231  *
232  * This function must not be called before the stream has been configured
233  * with amdtp_stream_set_parameters().
234  */
235 unsigned int amdtp_stream_get_max_payload(struct amdtp_stream *s)
236 {
237 	unsigned int multiplier = 1;
238 	unsigned int header_size = 0;
239 
240 	if (s->flags & CIP_JUMBO_PAYLOAD)
241 		multiplier = 5;
242 	if (!(s->flags & CIP_NO_HEADER))
243 		header_size = 8;
244 
245 	return header_size +
246 		s->syt_interval * s->data_block_quadlets * 4 * multiplier;
247 }
248 EXPORT_SYMBOL(amdtp_stream_get_max_payload);
249 
250 /**
251  * amdtp_stream_pcm_prepare - prepare PCM device for running
252  * @s: the AMDTP stream
253  *
254  * This function should be called from the PCM device's .prepare callback.
255  */
256 void amdtp_stream_pcm_prepare(struct amdtp_stream *s)
257 {
258 	tasklet_kill(&s->period_tasklet);
259 	s->pcm_buffer_pointer = 0;
260 	s->pcm_period_pointer = 0;
261 }
262 EXPORT_SYMBOL(amdtp_stream_pcm_prepare);
263 
264 static unsigned int calculate_data_blocks(struct amdtp_stream *s,
265 					  unsigned int syt)
266 {
267 	unsigned int phase, data_blocks;
268 
269 	/* Blocking mode. */
270 	if (s->flags & CIP_BLOCKING) {
271 		/* This module generate empty packet for 'no data'. */
272 		if (syt == CIP_SYT_NO_INFO)
273 			data_blocks = 0;
274 		else
275 			data_blocks = s->syt_interval;
276 	/* Non-blocking mode. */
277 	} else {
278 		if (!cip_sfc_is_base_44100(s->sfc)) {
279 			/* Sample_rate / 8000 is an integer, and precomputed. */
280 			data_blocks = s->data_block_state;
281 		} else {
282 			phase = s->data_block_state;
283 
284 		/*
285 		 * This calculates the number of data blocks per packet so that
286 		 * 1) the overall rate is correct and exactly synchronized to
287 		 *    the bus clock, and
288 		 * 2) packets with a rounded-up number of blocks occur as early
289 		 *    as possible in the sequence (to prevent underruns of the
290 		 *    device's buffer).
291 		 */
292 			if (s->sfc == CIP_SFC_44100)
293 				/* 6 6 5 6 5 6 5 ... */
294 				data_blocks = 5 + ((phase & 1) ^
295 						   (phase == 0 || phase >= 40));
296 			else
297 				/* 12 11 11 11 11 ... or 23 22 22 22 22 ... */
298 				data_blocks = 11 * (s->sfc >> 1) + (phase == 0);
299 			if (++phase >= (80 >> (s->sfc >> 1)))
300 				phase = 0;
301 			s->data_block_state = phase;
302 		}
303 	}
304 
305 	return data_blocks;
306 }
307 
308 static unsigned int calculate_syt(struct amdtp_stream *s,
309 				  unsigned int cycle)
310 {
311 	unsigned int syt_offset, phase, index, syt;
312 
313 	if (s->last_syt_offset < TICKS_PER_CYCLE) {
314 		if (!cip_sfc_is_base_44100(s->sfc))
315 			syt_offset = s->last_syt_offset + s->syt_offset_state;
316 		else {
317 		/*
318 		 * The time, in ticks, of the n'th SYT_INTERVAL sample is:
319 		 *   n * SYT_INTERVAL * 24576000 / sample_rate
320 		 * Modulo TICKS_PER_CYCLE, the difference between successive
321 		 * elements is about 1386.23.  Rounding the results of this
322 		 * formula to the SYT precision results in a sequence of
323 		 * differences that begins with:
324 		 *   1386 1386 1387 1386 1386 1386 1387 1386 1386 1386 1387 ...
325 		 * This code generates _exactly_ the same sequence.
326 		 */
327 			phase = s->syt_offset_state;
328 			index = phase % 13;
329 			syt_offset = s->last_syt_offset;
330 			syt_offset += 1386 + ((index && !(index & 3)) ||
331 					      phase == 146);
332 			if (++phase >= 147)
333 				phase = 0;
334 			s->syt_offset_state = phase;
335 		}
336 	} else
337 		syt_offset = s->last_syt_offset - TICKS_PER_CYCLE;
338 	s->last_syt_offset = syt_offset;
339 
340 	if (syt_offset < TICKS_PER_CYCLE) {
341 		syt_offset += s->transfer_delay;
342 		syt = (cycle + syt_offset / TICKS_PER_CYCLE) << 12;
343 		syt += syt_offset % TICKS_PER_CYCLE;
344 
345 		return syt & CIP_SYT_MASK;
346 	} else {
347 		return CIP_SYT_NO_INFO;
348 	}
349 }
350 
351 static void update_pcm_pointers(struct amdtp_stream *s,
352 				struct snd_pcm_substream *pcm,
353 				unsigned int frames)
354 {
355 	unsigned int ptr;
356 
357 	ptr = s->pcm_buffer_pointer + frames;
358 	if (ptr >= pcm->runtime->buffer_size)
359 		ptr -= pcm->runtime->buffer_size;
360 	ACCESS_ONCE(s->pcm_buffer_pointer) = ptr;
361 
362 	s->pcm_period_pointer += frames;
363 	if (s->pcm_period_pointer >= pcm->runtime->period_size) {
364 		s->pcm_period_pointer -= pcm->runtime->period_size;
365 		tasklet_hi_schedule(&s->period_tasklet);
366 	}
367 }
368 
369 static void pcm_period_tasklet(unsigned long data)
370 {
371 	struct amdtp_stream *s = (void *)data;
372 	struct snd_pcm_substream *pcm = ACCESS_ONCE(s->pcm);
373 
374 	if (pcm)
375 		snd_pcm_period_elapsed(pcm);
376 }
377 
378 static int queue_packet(struct amdtp_stream *s, unsigned int header_length,
379 			unsigned int payload_length)
380 {
381 	struct fw_iso_packet p = {0};
382 	int err = 0;
383 
384 	if (IS_ERR(s->context))
385 		goto end;
386 
387 	p.interrupt = IS_ALIGNED(s->packet_index + 1, INTERRUPT_INTERVAL);
388 	p.tag = s->tag;
389 	p.header_length = header_length;
390 	if (payload_length > 0)
391 		p.payload_length = payload_length;
392 	else
393 		p.skip = true;
394 	err = fw_iso_context_queue(s->context, &p, &s->buffer.iso_buffer,
395 				   s->buffer.packets[s->packet_index].offset);
396 	if (err < 0) {
397 		dev_err(&s->unit->device, "queueing error: %d\n", err);
398 		goto end;
399 	}
400 
401 	if (++s->packet_index >= QUEUE_LENGTH)
402 		s->packet_index = 0;
403 end:
404 	return err;
405 }
406 
407 static inline int queue_out_packet(struct amdtp_stream *s,
408 				   unsigned int payload_length)
409 {
410 	return queue_packet(s, OUT_PACKET_HEADER_SIZE, payload_length);
411 }
412 
413 static inline int queue_in_packet(struct amdtp_stream *s)
414 {
415 	return queue_packet(s, IN_PACKET_HEADER_SIZE, s->max_payload_length);
416 }
417 
418 static int handle_out_packet(struct amdtp_stream *s,
419 			     unsigned int payload_length, unsigned int cycle,
420 			     unsigned int index)
421 {
422 	__be32 *buffer;
423 	unsigned int syt;
424 	unsigned int data_blocks;
425 	unsigned int pcm_frames;
426 	struct snd_pcm_substream *pcm;
427 
428 	buffer = s->buffer.packets[s->packet_index].buffer;
429 	syt = calculate_syt(s, cycle);
430 	data_blocks = calculate_data_blocks(s, syt);
431 	pcm_frames = s->process_data_blocks(s, buffer + 2, data_blocks, &syt);
432 
433 	if (s->flags & CIP_DBC_IS_END_EVENT)
434 		s->data_block_counter =
435 				(s->data_block_counter + data_blocks) & 0xff;
436 
437 	buffer[0] = cpu_to_be32(ACCESS_ONCE(s->source_node_id_field) |
438 				(s->data_block_quadlets << CIP_DBS_SHIFT) |
439 				((s->sph << CIP_SPH_SHIFT) & CIP_SPH_MASK) |
440 				s->data_block_counter);
441 	buffer[1] = cpu_to_be32(CIP_EOH |
442 				((s->fmt << CIP_FMT_SHIFT) & CIP_FMT_MASK) |
443 				((s->fdf << CIP_FDF_SHIFT) & CIP_FDF_MASK) |
444 				(syt & CIP_SYT_MASK));
445 
446 	if (!(s->flags & CIP_DBC_IS_END_EVENT))
447 		s->data_block_counter =
448 				(s->data_block_counter + data_blocks) & 0xff;
449 	payload_length = 8 + data_blocks * 4 * s->data_block_quadlets;
450 
451 	trace_out_packet(s, cycle, buffer, payload_length, index);
452 
453 	if (queue_out_packet(s, payload_length) < 0)
454 		return -EIO;
455 
456 	pcm = ACCESS_ONCE(s->pcm);
457 	if (pcm && pcm_frames > 0)
458 		update_pcm_pointers(s, pcm, pcm_frames);
459 
460 	/* No need to return the number of handled data blocks. */
461 	return 0;
462 }
463 
464 static int handle_out_packet_without_header(struct amdtp_stream *s,
465 			unsigned int payload_length, unsigned int cycle,
466 			unsigned int index)
467 {
468 	__be32 *buffer;
469 	unsigned int syt;
470 	unsigned int data_blocks;
471 	unsigned int pcm_frames;
472 	struct snd_pcm_substream *pcm;
473 
474 	buffer = s->buffer.packets[s->packet_index].buffer;
475 	syt = calculate_syt(s, cycle);
476 	data_blocks = calculate_data_blocks(s, syt);
477 	pcm_frames = s->process_data_blocks(s, buffer, data_blocks, &syt);
478 	s->data_block_counter = (s->data_block_counter + data_blocks) & 0xff;
479 
480 	payload_length = data_blocks * 4 * s->data_block_quadlets;
481 
482 	trace_out_packet_without_header(s, cycle, payload_length, data_blocks,
483 					index);
484 
485 	if (queue_out_packet(s, payload_length) < 0)
486 		return -EIO;
487 
488 	pcm = ACCESS_ONCE(s->pcm);
489 	if (pcm && pcm_frames > 0)
490 		update_pcm_pointers(s, pcm, pcm_frames);
491 
492 	/* No need to return the number of handled data blocks. */
493 	return 0;
494 }
495 
496 static int handle_in_packet(struct amdtp_stream *s,
497 			    unsigned int payload_length, unsigned int cycle,
498 			    unsigned int index)
499 {
500 	__be32 *buffer;
501 	u32 cip_header[2];
502 	unsigned int sph, fmt, fdf, syt;
503 	unsigned int data_block_quadlets, data_block_counter, dbc_interval;
504 	unsigned int data_blocks;
505 	struct snd_pcm_substream *pcm;
506 	unsigned int pcm_frames;
507 	bool lost;
508 
509 	buffer = s->buffer.packets[s->packet_index].buffer;
510 	cip_header[0] = be32_to_cpu(buffer[0]);
511 	cip_header[1] = be32_to_cpu(buffer[1]);
512 
513 	trace_in_packet(s, cycle, cip_header, payload_length, index);
514 
515 	/*
516 	 * This module supports 'Two-quadlet CIP header with SYT field'.
517 	 * For convenience, also check FMT field is AM824 or not.
518 	 */
519 	if ((((cip_header[0] & CIP_EOH_MASK) == CIP_EOH) ||
520 	     ((cip_header[1] & CIP_EOH_MASK) != CIP_EOH)) &&
521 	    (!(s->flags & CIP_HEADER_WITHOUT_EOH))) {
522 		dev_info_ratelimited(&s->unit->device,
523 				"Invalid CIP header for AMDTP: %08X:%08X\n",
524 				cip_header[0], cip_header[1]);
525 		data_blocks = 0;
526 		pcm_frames = 0;
527 		goto end;
528 	}
529 
530 	/* Check valid protocol or not. */
531 	sph = (cip_header[0] & CIP_SPH_MASK) >> CIP_SPH_SHIFT;
532 	fmt = (cip_header[1] & CIP_FMT_MASK) >> CIP_FMT_SHIFT;
533 	if (sph != s->sph || fmt != s->fmt) {
534 		dev_info_ratelimited(&s->unit->device,
535 				     "Detect unexpected protocol: %08x %08x\n",
536 				     cip_header[0], cip_header[1]);
537 		data_blocks = 0;
538 		pcm_frames = 0;
539 		goto end;
540 	}
541 
542 	/* Calculate data blocks */
543 	fdf = (cip_header[1] & CIP_FDF_MASK) >> CIP_FDF_SHIFT;
544 	if (payload_length < 12 ||
545 	    (fmt == CIP_FMT_AM && fdf == AMDTP_FDF_NO_DATA)) {
546 		data_blocks = 0;
547 	} else {
548 		data_block_quadlets =
549 			(cip_header[0] & CIP_DBS_MASK) >> CIP_DBS_SHIFT;
550 		/* avoid division by zero */
551 		if (data_block_quadlets == 0) {
552 			dev_err(&s->unit->device,
553 				"Detect invalid value in dbs field: %08X\n",
554 				cip_header[0]);
555 			return -EPROTO;
556 		}
557 		if (s->flags & CIP_WRONG_DBS)
558 			data_block_quadlets = s->data_block_quadlets;
559 
560 		data_blocks = (payload_length / 4 - 2) /
561 							data_block_quadlets;
562 	}
563 
564 	/* Check data block counter continuity */
565 	data_block_counter = cip_header[0] & CIP_DBC_MASK;
566 	if (data_blocks == 0 && (s->flags & CIP_EMPTY_HAS_WRONG_DBC) &&
567 	    s->data_block_counter != UINT_MAX)
568 		data_block_counter = s->data_block_counter;
569 
570 	if (((s->flags & CIP_SKIP_DBC_ZERO_CHECK) &&
571 	     data_block_counter == s->tx_first_dbc) ||
572 	    s->data_block_counter == UINT_MAX) {
573 		lost = false;
574 	} else if (!(s->flags & CIP_DBC_IS_END_EVENT)) {
575 		lost = data_block_counter != s->data_block_counter;
576 	} else {
577 		if (data_blocks > 0 && s->tx_dbc_interval > 0)
578 			dbc_interval = s->tx_dbc_interval;
579 		else
580 			dbc_interval = data_blocks;
581 
582 		lost = data_block_counter !=
583 		       ((s->data_block_counter + dbc_interval) & 0xff);
584 	}
585 
586 	if (lost) {
587 		dev_err(&s->unit->device,
588 			"Detect discontinuity of CIP: %02X %02X\n",
589 			s->data_block_counter, data_block_counter);
590 		return -EIO;
591 	}
592 
593 	syt = be32_to_cpu(buffer[1]) & CIP_SYT_MASK;
594 	pcm_frames = s->process_data_blocks(s, buffer + 2, data_blocks, &syt);
595 
596 	if (s->flags & CIP_DBC_IS_END_EVENT)
597 		s->data_block_counter = data_block_counter;
598 	else
599 		s->data_block_counter =
600 				(data_block_counter + data_blocks) & 0xff;
601 end:
602 	if (queue_in_packet(s) < 0)
603 		return -EIO;
604 
605 	pcm = ACCESS_ONCE(s->pcm);
606 	if (pcm && pcm_frames > 0)
607 		update_pcm_pointers(s, pcm, pcm_frames);
608 
609 	return 0;
610 }
611 
612 static int handle_in_packet_without_header(struct amdtp_stream *s,
613 			unsigned int payload_quadlets, unsigned int cycle,
614 			unsigned int index)
615 {
616 	__be32 *buffer;
617 	unsigned int data_blocks;
618 	struct snd_pcm_substream *pcm;
619 	unsigned int pcm_frames;
620 
621 	buffer = s->buffer.packets[s->packet_index].buffer;
622 	data_blocks = payload_quadlets / s->data_block_quadlets;
623 
624 	trace_in_packet_without_header(s, cycle, payload_quadlets, data_blocks,
625 				       index);
626 
627 	pcm_frames = s->process_data_blocks(s, buffer, data_blocks, NULL);
628 	s->data_block_counter = (s->data_block_counter + data_blocks) & 0xff;
629 
630 	if (queue_in_packet(s) < 0)
631 		return -EIO;
632 
633 	pcm = ACCESS_ONCE(s->pcm);
634 	if (pcm && pcm_frames > 0)
635 		update_pcm_pointers(s, pcm, pcm_frames);
636 
637 	return 0;
638 }
639 
640 /*
641  * In CYCLE_TIMER register of IEEE 1394, 7 bits are used to represent second. On
642  * the other hand, in DMA descriptors of 1394 OHCI, 3 bits are used to represent
643  * it. Thus, via Linux firewire subsystem, we can get the 3 bits for second.
644  */
645 static inline u32 compute_cycle_count(u32 tstamp)
646 {
647 	return (((tstamp >> 13) & 0x07) * 8000) + (tstamp & 0x1fff);
648 }
649 
650 static inline u32 increment_cycle_count(u32 cycle, unsigned int addend)
651 {
652 	cycle += addend;
653 	if (cycle >= 8 * CYCLES_PER_SECOND)
654 		cycle -= 8 * CYCLES_PER_SECOND;
655 	return cycle;
656 }
657 
658 static inline u32 decrement_cycle_count(u32 cycle, unsigned int subtrahend)
659 {
660 	if (cycle < subtrahend)
661 		cycle += 8 * CYCLES_PER_SECOND;
662 	return cycle - subtrahend;
663 }
664 
665 static void out_stream_callback(struct fw_iso_context *context, u32 tstamp,
666 				size_t header_length, void *header,
667 				void *private_data)
668 {
669 	struct amdtp_stream *s = private_data;
670 	unsigned int i, packets = header_length / 4;
671 	u32 cycle;
672 
673 	if (s->packet_index < 0)
674 		return;
675 
676 	cycle = compute_cycle_count(tstamp);
677 
678 	/* Align to actual cycle count for the last packet. */
679 	cycle = increment_cycle_count(cycle, QUEUE_LENGTH - packets);
680 
681 	for (i = 0; i < packets; ++i) {
682 		cycle = increment_cycle_count(cycle, 1);
683 		if (s->handle_packet(s, 0, cycle, i) < 0) {
684 			s->packet_index = -1;
685 			amdtp_stream_pcm_abort(s);
686 			return;
687 		}
688 	}
689 
690 	fw_iso_context_queue_flush(s->context);
691 }
692 
693 static void in_stream_callback(struct fw_iso_context *context, u32 tstamp,
694 			       size_t header_length, void *header,
695 			       void *private_data)
696 {
697 	struct amdtp_stream *s = private_data;
698 	unsigned int i, packets;
699 	unsigned int payload_length, max_payload_length;
700 	__be32 *headers = header;
701 	u32 cycle;
702 
703 	if (s->packet_index < 0)
704 		return;
705 
706 	/* The number of packets in buffer */
707 	packets = header_length / IN_PACKET_HEADER_SIZE;
708 
709 	cycle = compute_cycle_count(tstamp);
710 
711 	/* Align to actual cycle count for the last packet. */
712 	cycle = decrement_cycle_count(cycle, packets);
713 
714 	/* For buffer-over-run prevention. */
715 	max_payload_length = s->max_payload_length;
716 
717 	for (i = 0; i < packets; i++) {
718 		cycle = increment_cycle_count(cycle, 1);
719 
720 		/* The number of bytes in this packet */
721 		payload_length =
722 			(be32_to_cpu(headers[i]) >> ISO_DATA_LENGTH_SHIFT);
723 		if (payload_length > max_payload_length) {
724 			dev_err(&s->unit->device,
725 				"Detect jumbo payload: %04x %04x\n",
726 				payload_length, max_payload_length);
727 			break;
728 		}
729 
730 		if (s->handle_packet(s, payload_length, cycle, i) < 0)
731 			break;
732 	}
733 
734 	/* Queueing error or detecting invalid payload. */
735 	if (i < packets) {
736 		s->packet_index = -1;
737 		amdtp_stream_pcm_abort(s);
738 		return;
739 	}
740 
741 	fw_iso_context_queue_flush(s->context);
742 }
743 
744 /* this is executed one time */
745 static void amdtp_stream_first_callback(struct fw_iso_context *context,
746 					u32 tstamp, size_t header_length,
747 					void *header, void *private_data)
748 {
749 	struct amdtp_stream *s = private_data;
750 	u32 cycle;
751 	unsigned int packets;
752 
753 	s->max_payload_length = amdtp_stream_get_max_payload(s);
754 
755 	/*
756 	 * For in-stream, first packet has come.
757 	 * For out-stream, prepared to transmit first packet
758 	 */
759 	s->callbacked = true;
760 	wake_up(&s->callback_wait);
761 
762 	cycle = compute_cycle_count(tstamp);
763 
764 	if (s->direction == AMDTP_IN_STREAM) {
765 		packets = header_length / IN_PACKET_HEADER_SIZE;
766 		cycle = decrement_cycle_count(cycle, packets);
767 		context->callback.sc = in_stream_callback;
768 		if (s->flags & CIP_NO_HEADER)
769 			s->handle_packet = handle_in_packet_without_header;
770 		else
771 			s->handle_packet = handle_in_packet;
772 	} else {
773 		packets = header_length / 4;
774 		cycle = increment_cycle_count(cycle, QUEUE_LENGTH - packets);
775 		context->callback.sc = out_stream_callback;
776 		if (s->flags & CIP_NO_HEADER)
777 			s->handle_packet = handle_out_packet_without_header;
778 		else
779 			s->handle_packet = handle_out_packet;
780 	}
781 
782 	s->start_cycle = cycle;
783 
784 	context->callback.sc(context, tstamp, header_length, header, s);
785 }
786 
787 /**
788  * amdtp_stream_start - start transferring packets
789  * @s: the AMDTP stream to start
790  * @channel: the isochronous channel on the bus
791  * @speed: firewire speed code
792  *
793  * The stream cannot be started until it has been configured with
794  * amdtp_stream_set_parameters() and it must be started before any PCM or MIDI
795  * device can be started.
796  */
797 int amdtp_stream_start(struct amdtp_stream *s, int channel, int speed)
798 {
799 	static const struct {
800 		unsigned int data_block;
801 		unsigned int syt_offset;
802 	} initial_state[] = {
803 		[CIP_SFC_32000]  = {  4, 3072 },
804 		[CIP_SFC_48000]  = {  6, 1024 },
805 		[CIP_SFC_96000]  = { 12, 1024 },
806 		[CIP_SFC_192000] = { 24, 1024 },
807 		[CIP_SFC_44100]  = {  0,   67 },
808 		[CIP_SFC_88200]  = {  0,   67 },
809 		[CIP_SFC_176400] = {  0,   67 },
810 	};
811 	unsigned int header_size;
812 	enum dma_data_direction dir;
813 	int type, tag, err;
814 
815 	mutex_lock(&s->mutex);
816 
817 	if (WARN_ON(amdtp_stream_running(s) ||
818 		    (s->data_block_quadlets < 1))) {
819 		err = -EBADFD;
820 		goto err_unlock;
821 	}
822 
823 	if (s->direction == AMDTP_IN_STREAM)
824 		s->data_block_counter = UINT_MAX;
825 	else
826 		s->data_block_counter = 0;
827 	s->data_block_state = initial_state[s->sfc].data_block;
828 	s->syt_offset_state = initial_state[s->sfc].syt_offset;
829 	s->last_syt_offset = TICKS_PER_CYCLE;
830 
831 	/* initialize packet buffer */
832 	if (s->direction == AMDTP_IN_STREAM) {
833 		dir = DMA_FROM_DEVICE;
834 		type = FW_ISO_CONTEXT_RECEIVE;
835 		header_size = IN_PACKET_HEADER_SIZE;
836 	} else {
837 		dir = DMA_TO_DEVICE;
838 		type = FW_ISO_CONTEXT_TRANSMIT;
839 		header_size = OUT_PACKET_HEADER_SIZE;
840 	}
841 	err = iso_packets_buffer_init(&s->buffer, s->unit, QUEUE_LENGTH,
842 				      amdtp_stream_get_max_payload(s), dir);
843 	if (err < 0)
844 		goto err_unlock;
845 
846 	s->context = fw_iso_context_create(fw_parent_device(s->unit)->card,
847 					   type, channel, speed, header_size,
848 					   amdtp_stream_first_callback, s);
849 	if (IS_ERR(s->context)) {
850 		err = PTR_ERR(s->context);
851 		if (err == -EBUSY)
852 			dev_err(&s->unit->device,
853 				"no free stream on this controller\n");
854 		goto err_buffer;
855 	}
856 
857 	amdtp_stream_update(s);
858 
859 	if (s->flags & CIP_NO_HEADER)
860 		s->tag = TAG_NO_CIP_HEADER;
861 	else
862 		s->tag = TAG_CIP;
863 
864 	s->packet_index = 0;
865 	do {
866 		if (s->direction == AMDTP_IN_STREAM)
867 			err = queue_in_packet(s);
868 		else
869 			err = queue_out_packet(s, 0);
870 		if (err < 0)
871 			goto err_context;
872 	} while (s->packet_index > 0);
873 
874 	/* NOTE: TAG1 matches CIP. This just affects in stream. */
875 	tag = FW_ISO_CONTEXT_MATCH_TAG1;
876 	if ((s->flags & CIP_EMPTY_WITH_TAG0) || (s->flags & CIP_NO_HEADER))
877 		tag |= FW_ISO_CONTEXT_MATCH_TAG0;
878 
879 	s->callbacked = false;
880 	err = fw_iso_context_start(s->context, -1, 0, tag);
881 	if (err < 0)
882 		goto err_context;
883 
884 	mutex_unlock(&s->mutex);
885 
886 	return 0;
887 
888 err_context:
889 	fw_iso_context_destroy(s->context);
890 	s->context = ERR_PTR(-1);
891 err_buffer:
892 	iso_packets_buffer_destroy(&s->buffer, s->unit);
893 err_unlock:
894 	mutex_unlock(&s->mutex);
895 
896 	return err;
897 }
898 EXPORT_SYMBOL(amdtp_stream_start);
899 
900 /**
901  * amdtp_stream_pcm_pointer - get the PCM buffer position
902  * @s: the AMDTP stream that transports the PCM data
903  *
904  * Returns the current buffer position, in frames.
905  */
906 unsigned long amdtp_stream_pcm_pointer(struct amdtp_stream *s)
907 {
908 	/*
909 	 * This function is called in software IRQ context of period_tasklet or
910 	 * process context.
911 	 *
912 	 * When the software IRQ context was scheduled by software IRQ context
913 	 * of IR/IT contexts, queued packets were already handled. Therefore,
914 	 * no need to flush the queue in buffer anymore.
915 	 *
916 	 * When the process context reach here, some packets will be already
917 	 * queued in the buffer. These packets should be handled immediately
918 	 * to keep better granularity of PCM pointer.
919 	 *
920 	 * Later, the process context will sometimes schedules software IRQ
921 	 * context of the period_tasklet. Then, no need to flush the queue by
922 	 * the same reason as described for IR/IT contexts.
923 	 */
924 	if (!in_interrupt() && amdtp_stream_running(s))
925 		fw_iso_context_flush_completions(s->context);
926 
927 	return ACCESS_ONCE(s->pcm_buffer_pointer);
928 }
929 EXPORT_SYMBOL(amdtp_stream_pcm_pointer);
930 
931 /**
932  * amdtp_stream_update - update the stream after a bus reset
933  * @s: the AMDTP stream
934  */
935 void amdtp_stream_update(struct amdtp_stream *s)
936 {
937 	/* Precomputing. */
938 	ACCESS_ONCE(s->source_node_id_field) =
939 		(fw_parent_device(s->unit)->card->node_id << CIP_SID_SHIFT) &
940 								CIP_SID_MASK;
941 }
942 EXPORT_SYMBOL(amdtp_stream_update);
943 
944 /**
945  * amdtp_stream_stop - stop sending packets
946  * @s: the AMDTP stream to stop
947  *
948  * All PCM and MIDI devices of the stream must be stopped before the stream
949  * itself can be stopped.
950  */
951 void amdtp_stream_stop(struct amdtp_stream *s)
952 {
953 	mutex_lock(&s->mutex);
954 
955 	if (!amdtp_stream_running(s)) {
956 		mutex_unlock(&s->mutex);
957 		return;
958 	}
959 
960 	tasklet_kill(&s->period_tasklet);
961 	fw_iso_context_stop(s->context);
962 	fw_iso_context_destroy(s->context);
963 	s->context = ERR_PTR(-1);
964 	iso_packets_buffer_destroy(&s->buffer, s->unit);
965 
966 	s->callbacked = false;
967 
968 	mutex_unlock(&s->mutex);
969 }
970 EXPORT_SYMBOL(amdtp_stream_stop);
971 
972 /**
973  * amdtp_stream_pcm_abort - abort the running PCM device
974  * @s: the AMDTP stream about to be stopped
975  *
976  * If the isochronous stream needs to be stopped asynchronously, call this
977  * function first to stop the PCM device.
978  */
979 void amdtp_stream_pcm_abort(struct amdtp_stream *s)
980 {
981 	struct snd_pcm_substream *pcm;
982 
983 	pcm = ACCESS_ONCE(s->pcm);
984 	if (pcm)
985 		snd_pcm_stop_xrun(pcm);
986 }
987 EXPORT_SYMBOL(amdtp_stream_pcm_abort);
988