xref: /openbmc/linux/sound/firewire/amdtp-stream.c (revision 2f21a177631ae969537cf4ed602293d9aac9f73e)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Audio and Music Data Transmission Protocol (IEC 61883-6) streams
4  * with Common Isochronous Packet (IEC 61883-1) headers
5  *
6  * Copyright (c) Clemens Ladisch <clemens@ladisch.de>
7  */
8 
9 #include <linux/device.h>
10 #include <linux/err.h>
11 #include <linux/firewire.h>
12 #include <linux/firewire-constants.h>
13 #include <linux/module.h>
14 #include <linux/slab.h>
15 #include <sound/pcm.h>
16 #include <sound/pcm_params.h>
17 #include "amdtp-stream.h"
18 
19 #define TICKS_PER_CYCLE		3072
20 #define CYCLES_PER_SECOND	8000
21 #define TICKS_PER_SECOND	(TICKS_PER_CYCLE * CYCLES_PER_SECOND)
22 
23 #define OHCI_SECOND_MODULUS		8
24 
25 /* Always support Linux tracing subsystem. */
26 #define CREATE_TRACE_POINTS
27 #include "amdtp-stream-trace.h"
28 
29 #define TRANSFER_DELAY_TICKS	0x2e00 /* 479.17 microseconds */
30 
31 /* isochronous header parameters */
32 #define ISO_DATA_LENGTH_SHIFT	16
33 #define TAG_NO_CIP_HEADER	0
34 #define TAG_CIP			1
35 
36 // Common Isochronous Packet (CIP) header parameters. Use two quadlets CIP header when supported.
37 #define CIP_HEADER_QUADLETS	2
38 #define CIP_EOH_SHIFT		31
39 #define CIP_EOH			(1u << CIP_EOH_SHIFT)
40 #define CIP_EOH_MASK		0x80000000
41 #define CIP_SID_SHIFT		24
42 #define CIP_SID_MASK		0x3f000000
43 #define CIP_DBS_MASK		0x00ff0000
44 #define CIP_DBS_SHIFT		16
45 #define CIP_SPH_MASK		0x00000400
46 #define CIP_SPH_SHIFT		10
47 #define CIP_DBC_MASK		0x000000ff
48 #define CIP_FMT_SHIFT		24
49 #define CIP_FMT_MASK		0x3f000000
50 #define CIP_FDF_MASK		0x00ff0000
51 #define CIP_FDF_SHIFT		16
52 #define CIP_FDF_NO_DATA		0xff
53 #define CIP_SYT_MASK		0x0000ffff
54 #define CIP_SYT_NO_INFO		0xffff
55 #define CIP_SYT_CYCLE_MODULUS	16
56 #define CIP_NO_DATA		((CIP_FDF_NO_DATA << CIP_FDF_SHIFT) | CIP_SYT_NO_INFO)
57 
58 #define CIP_HEADER_SIZE		(sizeof(__be32) * CIP_HEADER_QUADLETS)
59 
60 /* Audio and Music transfer protocol specific parameters */
61 #define CIP_FMT_AM		0x10
62 #define AMDTP_FDF_NO_DATA	0xff
63 
64 // For iso header and tstamp.
65 #define IR_CTX_HEADER_DEFAULT_QUADLETS	2
66 // Add nothing.
67 #define IR_CTX_HEADER_SIZE_NO_CIP	(sizeof(__be32) * IR_CTX_HEADER_DEFAULT_QUADLETS)
68 // Add two quadlets CIP header.
69 #define IR_CTX_HEADER_SIZE_CIP		(IR_CTX_HEADER_SIZE_NO_CIP + CIP_HEADER_SIZE)
70 #define HEADER_TSTAMP_MASK	0x0000ffff
71 
72 #define IT_PKT_HEADER_SIZE_CIP		CIP_HEADER_SIZE
73 #define IT_PKT_HEADER_SIZE_NO_CIP	0 // Nothing.
74 
75 // The initial firmware of OXFW970 can postpone transmission of packet during finishing
76 // asynchronous transaction. This module accepts 5 cycles to skip as maximum to avoid buffer
77 // overrun. Actual device can skip more, then this module stops the packet streaming.
78 #define IR_JUMBO_PAYLOAD_MAX_SKIP_CYCLES	5
79 
80 static void pcm_period_work(struct work_struct *work);
81 
82 /**
83  * amdtp_stream_init - initialize an AMDTP stream structure
84  * @s: the AMDTP stream to initialize
85  * @unit: the target of the stream
86  * @dir: the direction of stream
87  * @flags: the details of the streaming protocol consist of cip_flags enumeration-constants.
88  * @fmt: the value of fmt field in CIP header
89  * @process_ctx_payloads: callback handler to process payloads of isoc context
90  * @protocol_size: the size to allocate newly for protocol
91  */
92 int amdtp_stream_init(struct amdtp_stream *s, struct fw_unit *unit,
93 		      enum amdtp_stream_direction dir, unsigned int flags,
94 		      unsigned int fmt,
95 		      amdtp_stream_process_ctx_payloads_t process_ctx_payloads,
96 		      unsigned int protocol_size)
97 {
98 	if (process_ctx_payloads == NULL)
99 		return -EINVAL;
100 
101 	s->protocol = kzalloc(protocol_size, GFP_KERNEL);
102 	if (!s->protocol)
103 		return -ENOMEM;
104 
105 	s->unit = unit;
106 	s->direction = dir;
107 	s->flags = flags;
108 	s->context = ERR_PTR(-1);
109 	mutex_init(&s->mutex);
110 	INIT_WORK(&s->period_work, pcm_period_work);
111 	s->packet_index = 0;
112 
113 	init_waitqueue_head(&s->ready_wait);
114 
115 	s->fmt = fmt;
116 	s->process_ctx_payloads = process_ctx_payloads;
117 
118 	return 0;
119 }
120 EXPORT_SYMBOL(amdtp_stream_init);
121 
122 /**
123  * amdtp_stream_destroy - free stream resources
124  * @s: the AMDTP stream to destroy
125  */
126 void amdtp_stream_destroy(struct amdtp_stream *s)
127 {
128 	/* Not initialized. */
129 	if (s->protocol == NULL)
130 		return;
131 
132 	WARN_ON(amdtp_stream_running(s));
133 	kfree(s->protocol);
134 	mutex_destroy(&s->mutex);
135 }
136 EXPORT_SYMBOL(amdtp_stream_destroy);
137 
138 const unsigned int amdtp_syt_intervals[CIP_SFC_COUNT] = {
139 	[CIP_SFC_32000]  =  8,
140 	[CIP_SFC_44100]  =  8,
141 	[CIP_SFC_48000]  =  8,
142 	[CIP_SFC_88200]  = 16,
143 	[CIP_SFC_96000]  = 16,
144 	[CIP_SFC_176400] = 32,
145 	[CIP_SFC_192000] = 32,
146 };
147 EXPORT_SYMBOL(amdtp_syt_intervals);
148 
149 const unsigned int amdtp_rate_table[CIP_SFC_COUNT] = {
150 	[CIP_SFC_32000]  =  32000,
151 	[CIP_SFC_44100]  =  44100,
152 	[CIP_SFC_48000]  =  48000,
153 	[CIP_SFC_88200]  =  88200,
154 	[CIP_SFC_96000]  =  96000,
155 	[CIP_SFC_176400] = 176400,
156 	[CIP_SFC_192000] = 192000,
157 };
158 EXPORT_SYMBOL(amdtp_rate_table);
159 
160 static int apply_constraint_to_size(struct snd_pcm_hw_params *params,
161 				    struct snd_pcm_hw_rule *rule)
162 {
163 	struct snd_interval *s = hw_param_interval(params, rule->var);
164 	const struct snd_interval *r =
165 		hw_param_interval_c(params, SNDRV_PCM_HW_PARAM_RATE);
166 	struct snd_interval t = {0};
167 	unsigned int step = 0;
168 	int i;
169 
170 	for (i = 0; i < CIP_SFC_COUNT; ++i) {
171 		if (snd_interval_test(r, amdtp_rate_table[i]))
172 			step = max(step, amdtp_syt_intervals[i]);
173 	}
174 
175 	t.min = roundup(s->min, step);
176 	t.max = rounddown(s->max, step);
177 	t.integer = 1;
178 
179 	return snd_interval_refine(s, &t);
180 }
181 
182 /**
183  * amdtp_stream_add_pcm_hw_constraints - add hw constraints for PCM substream
184  * @s:		the AMDTP stream, which must be initialized.
185  * @runtime:	the PCM substream runtime
186  */
187 int amdtp_stream_add_pcm_hw_constraints(struct amdtp_stream *s,
188 					struct snd_pcm_runtime *runtime)
189 {
190 	struct snd_pcm_hardware *hw = &runtime->hw;
191 	unsigned int ctx_header_size;
192 	unsigned int maximum_usec_per_period;
193 	int err;
194 
195 	hw->info = SNDRV_PCM_INFO_BATCH |
196 		   SNDRV_PCM_INFO_BLOCK_TRANSFER |
197 		   SNDRV_PCM_INFO_INTERLEAVED |
198 		   SNDRV_PCM_INFO_JOINT_DUPLEX |
199 		   SNDRV_PCM_INFO_MMAP |
200 		   SNDRV_PCM_INFO_MMAP_VALID;
201 
202 	/* SNDRV_PCM_INFO_BATCH */
203 	hw->periods_min = 2;
204 	hw->periods_max = UINT_MAX;
205 
206 	/* bytes for a frame */
207 	hw->period_bytes_min = 4 * hw->channels_max;
208 
209 	/* Just to prevent from allocating much pages. */
210 	hw->period_bytes_max = hw->period_bytes_min * 2048;
211 	hw->buffer_bytes_max = hw->period_bytes_max * hw->periods_min;
212 
213 	// Linux driver for 1394 OHCI controller voluntarily flushes isoc
214 	// context when total size of accumulated context header reaches
215 	// PAGE_SIZE. This kicks work for the isoc context and brings
216 	// callback in the middle of scheduled interrupts.
217 	// Although AMDTP streams in the same domain use the same events per
218 	// IRQ, use the largest size of context header between IT/IR contexts.
219 	// Here, use the value of context header in IR context is for both
220 	// contexts.
221 	if (!(s->flags & CIP_NO_HEADER))
222 		ctx_header_size = IR_CTX_HEADER_SIZE_CIP;
223 	else
224 		ctx_header_size = IR_CTX_HEADER_SIZE_NO_CIP;
225 	maximum_usec_per_period = USEC_PER_SEC * PAGE_SIZE /
226 				  CYCLES_PER_SECOND / ctx_header_size;
227 
228 	// In IEC 61883-6, one isoc packet can transfer events up to the value
229 	// of syt interval. This comes from the interval of isoc cycle. As 1394
230 	// OHCI controller can generate hardware IRQ per isoc packet, the
231 	// interval is 125 usec.
232 	// However, there are two ways of transmission in IEC 61883-6; blocking
233 	// and non-blocking modes. In blocking mode, the sequence of isoc packet
234 	// includes 'empty' or 'NODATA' packets which include no event. In
235 	// non-blocking mode, the number of events per packet is variable up to
236 	// the syt interval.
237 	// Due to the above protocol design, the minimum PCM frames per
238 	// interrupt should be double of the value of syt interval, thus it is
239 	// 250 usec.
240 	err = snd_pcm_hw_constraint_minmax(runtime,
241 					   SNDRV_PCM_HW_PARAM_PERIOD_TIME,
242 					   250, maximum_usec_per_period);
243 	if (err < 0)
244 		goto end;
245 
246 	/* Non-Blocking stream has no more constraints */
247 	if (!(s->flags & CIP_BLOCKING))
248 		goto end;
249 
250 	/*
251 	 * One AMDTP packet can include some frames. In blocking mode, the
252 	 * number equals to SYT_INTERVAL. So the number is 8, 16 or 32,
253 	 * depending on its sampling rate. For accurate period interrupt, it's
254 	 * preferrable to align period/buffer sizes to current SYT_INTERVAL.
255 	 */
256 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
257 				  apply_constraint_to_size, NULL,
258 				  SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
259 				  SNDRV_PCM_HW_PARAM_RATE, -1);
260 	if (err < 0)
261 		goto end;
262 	err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
263 				  apply_constraint_to_size, NULL,
264 				  SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
265 				  SNDRV_PCM_HW_PARAM_RATE, -1);
266 	if (err < 0)
267 		goto end;
268 end:
269 	return err;
270 }
271 EXPORT_SYMBOL(amdtp_stream_add_pcm_hw_constraints);
272 
273 /**
274  * amdtp_stream_set_parameters - set stream parameters
275  * @s: the AMDTP stream to configure
276  * @rate: the sample rate
277  * @data_block_quadlets: the size of a data block in quadlet unit
278  *
279  * The parameters must be set before the stream is started, and must not be
280  * changed while the stream is running.
281  */
282 int amdtp_stream_set_parameters(struct amdtp_stream *s, unsigned int rate,
283 				unsigned int data_block_quadlets)
284 {
285 	unsigned int sfc;
286 
287 	for (sfc = 0; sfc < ARRAY_SIZE(amdtp_rate_table); ++sfc) {
288 		if (amdtp_rate_table[sfc] == rate)
289 			break;
290 	}
291 	if (sfc == ARRAY_SIZE(amdtp_rate_table))
292 		return -EINVAL;
293 
294 	s->sfc = sfc;
295 	s->data_block_quadlets = data_block_quadlets;
296 	s->syt_interval = amdtp_syt_intervals[sfc];
297 
298 	// default buffering in the device.
299 	s->transfer_delay = TRANSFER_DELAY_TICKS - TICKS_PER_CYCLE;
300 
301 	// additional buffering needed to adjust for no-data packets.
302 	if (s->flags & CIP_BLOCKING)
303 		s->transfer_delay += TICKS_PER_SECOND * s->syt_interval / rate;
304 
305 	return 0;
306 }
307 EXPORT_SYMBOL(amdtp_stream_set_parameters);
308 
309 // The CIP header is processed in context header apart from context payload.
310 static int amdtp_stream_get_max_ctx_payload_size(struct amdtp_stream *s)
311 {
312 	unsigned int multiplier;
313 
314 	if (s->flags & CIP_JUMBO_PAYLOAD)
315 		multiplier = IR_JUMBO_PAYLOAD_MAX_SKIP_CYCLES;
316 	else
317 		multiplier = 1;
318 
319 	return s->syt_interval * s->data_block_quadlets * sizeof(__be32) * multiplier;
320 }
321 
322 /**
323  * amdtp_stream_get_max_payload - get the stream's packet size
324  * @s: the AMDTP stream
325  *
326  * This function must not be called before the stream has been configured
327  * with amdtp_stream_set_parameters().
328  */
329 unsigned int amdtp_stream_get_max_payload(struct amdtp_stream *s)
330 {
331 	unsigned int cip_header_size;
332 
333 	if (!(s->flags & CIP_NO_HEADER))
334 		cip_header_size = CIP_HEADER_SIZE;
335 	else
336 		cip_header_size = 0;
337 
338 	return cip_header_size + amdtp_stream_get_max_ctx_payload_size(s);
339 }
340 EXPORT_SYMBOL(amdtp_stream_get_max_payload);
341 
342 /**
343  * amdtp_stream_pcm_prepare - prepare PCM device for running
344  * @s: the AMDTP stream
345  *
346  * This function should be called from the PCM device's .prepare callback.
347  */
348 void amdtp_stream_pcm_prepare(struct amdtp_stream *s)
349 {
350 	cancel_work_sync(&s->period_work);
351 	s->pcm_buffer_pointer = 0;
352 	s->pcm_period_pointer = 0;
353 }
354 EXPORT_SYMBOL(amdtp_stream_pcm_prepare);
355 
356 static void pool_blocking_data_blocks(struct amdtp_stream *s, struct seq_desc *descs,
357 				      const unsigned int seq_size, unsigned int seq_tail,
358 				      unsigned int count)
359 {
360 	const unsigned int syt_interval = s->syt_interval;
361 	int i;
362 
363 	for (i = 0; i < count; ++i) {
364 		struct seq_desc *desc = descs + seq_tail;
365 
366 		if (desc->syt_offset != CIP_SYT_NO_INFO)
367 			desc->data_blocks = syt_interval;
368 		else
369 			desc->data_blocks = 0;
370 
371 		seq_tail = (seq_tail + 1) % seq_size;
372 	}
373 }
374 
375 static void pool_ideal_nonblocking_data_blocks(struct amdtp_stream *s, struct seq_desc *descs,
376 					       const unsigned int seq_size, unsigned int seq_tail,
377 					       unsigned int count)
378 {
379 	const enum cip_sfc sfc = s->sfc;
380 	unsigned int state = s->ctx_data.rx.data_block_state;
381 	int i;
382 
383 	for (i = 0; i < count; ++i) {
384 		struct seq_desc *desc = descs + seq_tail;
385 
386 		if (!cip_sfc_is_base_44100(sfc)) {
387 			// Sample_rate / 8000 is an integer, and precomputed.
388 			desc->data_blocks = state;
389 		} else {
390 			unsigned int phase = state;
391 
392 		/*
393 		 * This calculates the number of data blocks per packet so that
394 		 * 1) the overall rate is correct and exactly synchronized to
395 		 *    the bus clock, and
396 		 * 2) packets with a rounded-up number of blocks occur as early
397 		 *    as possible in the sequence (to prevent underruns of the
398 		 *    device's buffer).
399 		 */
400 			if (sfc == CIP_SFC_44100)
401 				/* 6 6 5 6 5 6 5 ... */
402 				desc->data_blocks = 5 + ((phase & 1) ^ (phase == 0 || phase >= 40));
403 			else
404 				/* 12 11 11 11 11 ... or 23 22 22 22 22 ... */
405 				desc->data_blocks = 11 * (sfc >> 1) + (phase == 0);
406 			if (++phase >= (80 >> (sfc >> 1)))
407 				phase = 0;
408 			state = phase;
409 		}
410 
411 		seq_tail = (seq_tail + 1) % seq_size;
412 	}
413 
414 	s->ctx_data.rx.data_block_state = state;
415 }
416 
417 static unsigned int calculate_syt_offset(unsigned int *last_syt_offset,
418 			unsigned int *syt_offset_state, enum cip_sfc sfc)
419 {
420 	unsigned int syt_offset;
421 
422 	if (*last_syt_offset < TICKS_PER_CYCLE) {
423 		if (!cip_sfc_is_base_44100(sfc))
424 			syt_offset = *last_syt_offset + *syt_offset_state;
425 		else {
426 		/*
427 		 * The time, in ticks, of the n'th SYT_INTERVAL sample is:
428 		 *   n * SYT_INTERVAL * 24576000 / sample_rate
429 		 * Modulo TICKS_PER_CYCLE, the difference between successive
430 		 * elements is about 1386.23.  Rounding the results of this
431 		 * formula to the SYT precision results in a sequence of
432 		 * differences that begins with:
433 		 *   1386 1386 1387 1386 1386 1386 1387 1386 1386 1386 1387 ...
434 		 * This code generates _exactly_ the same sequence.
435 		 */
436 			unsigned int phase = *syt_offset_state;
437 			unsigned int index = phase % 13;
438 
439 			syt_offset = *last_syt_offset;
440 			syt_offset += 1386 + ((index && !(index & 3)) ||
441 					      phase == 146);
442 			if (++phase >= 147)
443 				phase = 0;
444 			*syt_offset_state = phase;
445 		}
446 	} else
447 		syt_offset = *last_syt_offset - TICKS_PER_CYCLE;
448 	*last_syt_offset = syt_offset;
449 
450 	if (syt_offset >= TICKS_PER_CYCLE)
451 		syt_offset = CIP_SYT_NO_INFO;
452 
453 	return syt_offset;
454 }
455 
456 static void pool_ideal_syt_offsets(struct amdtp_stream *s, struct seq_desc *descs,
457 				   const unsigned int seq_size, unsigned int seq_tail,
458 				   unsigned int count)
459 {
460 	const enum cip_sfc sfc = s->sfc;
461 	unsigned int last = s->ctx_data.rx.last_syt_offset;
462 	unsigned int state = s->ctx_data.rx.syt_offset_state;
463 	int i;
464 
465 	for (i = 0; i < count; ++i) {
466 		struct seq_desc *desc = descs + seq_tail;
467 
468 		desc->syt_offset = calculate_syt_offset(&last, &state, sfc);
469 
470 		seq_tail = (seq_tail + 1) % seq_size;
471 	}
472 
473 	s->ctx_data.rx.last_syt_offset = last;
474 	s->ctx_data.rx.syt_offset_state = state;
475 }
476 
477 static unsigned int compute_syt_offset(unsigned int syt, unsigned int cycle,
478 				       unsigned int transfer_delay)
479 {
480 	unsigned int cycle_lo = (cycle % CYCLES_PER_SECOND) & 0x0f;
481 	unsigned int syt_cycle_lo = (syt & 0xf000) >> 12;
482 	unsigned int syt_offset;
483 
484 	// Round up.
485 	if (syt_cycle_lo < cycle_lo)
486 		syt_cycle_lo += CIP_SYT_CYCLE_MODULUS;
487 	syt_cycle_lo -= cycle_lo;
488 
489 	// Subtract transfer delay so that the synchronization offset is not so large
490 	// at transmission.
491 	syt_offset = syt_cycle_lo * TICKS_PER_CYCLE + (syt & 0x0fff);
492 	if (syt_offset < transfer_delay)
493 		syt_offset += CIP_SYT_CYCLE_MODULUS * TICKS_PER_CYCLE;
494 
495 	return syt_offset - transfer_delay;
496 }
497 
498 // Both of the producer and consumer of the queue runs in the same clock of IEEE 1394 bus.
499 // Additionally, the sequence of tx packets is severely checked against any discontinuity
500 // before filling entries in the queue. The calculation is safe even if it looks fragile by
501 // overrun.
502 static unsigned int calculate_cached_cycle_count(struct amdtp_stream *s, unsigned int head)
503 {
504 	const unsigned int cache_size = s->ctx_data.tx.cache.size;
505 	unsigned int cycles = s->ctx_data.tx.cache.tail;
506 
507 	if (cycles < head)
508 		cycles += cache_size;
509 	cycles -= head;
510 
511 	return cycles;
512 }
513 
514 static void cache_seq(struct amdtp_stream *s, const struct pkt_desc *descs, unsigned int desc_count)
515 {
516 	const unsigned int transfer_delay = s->transfer_delay;
517 	const unsigned int cache_size = s->ctx_data.tx.cache.size;
518 	struct seq_desc *cache = s->ctx_data.tx.cache.descs;
519 	unsigned int cache_tail = s->ctx_data.tx.cache.tail;
520 	bool aware_syt = !(s->flags & CIP_UNAWARE_SYT);
521 	int i;
522 
523 	for (i = 0; i < desc_count; ++i) {
524 		struct seq_desc *dst = cache + cache_tail;
525 		const struct pkt_desc *src = descs + i;
526 
527 		if (aware_syt && src->syt != CIP_SYT_NO_INFO)
528 			dst->syt_offset = compute_syt_offset(src->syt, src->cycle, transfer_delay);
529 		else
530 			dst->syt_offset = CIP_SYT_NO_INFO;
531 		dst->data_blocks = src->data_blocks;
532 
533 		cache_tail = (cache_tail + 1) % cache_size;
534 	}
535 
536 	s->ctx_data.tx.cache.tail = cache_tail;
537 }
538 
539 static void pool_ideal_seq_descs(struct amdtp_stream *s, unsigned int count)
540 {
541 	struct seq_desc *descs = s->ctx_data.rx.seq.descs;
542 	unsigned int seq_tail = s->ctx_data.rx.seq.tail;
543 	const unsigned int seq_size = s->ctx_data.rx.seq.size;
544 
545 	pool_ideal_syt_offsets(s, descs, seq_size, seq_tail, count);
546 
547 	if (s->flags & CIP_BLOCKING)
548 		pool_blocking_data_blocks(s, descs, seq_size, seq_tail, count);
549 	else
550 		pool_ideal_nonblocking_data_blocks(s, descs, seq_size, seq_tail, count);
551 
552 	s->ctx_data.rx.seq.tail = (seq_tail + count) % seq_size;
553 }
554 
555 static void pool_replayed_seq(struct amdtp_stream *s, unsigned int count)
556 {
557 	struct amdtp_stream *target = s->ctx_data.rx.replay_target;
558 	const struct seq_desc *cache = target->ctx_data.tx.cache.descs;
559 	const unsigned int cache_size = target->ctx_data.tx.cache.size;
560 	unsigned int cache_head = s->ctx_data.rx.cache_head;
561 	struct seq_desc *descs = s->ctx_data.rx.seq.descs;
562 	const unsigned int seq_size = s->ctx_data.rx.seq.size;
563 	unsigned int seq_tail = s->ctx_data.rx.seq.tail;
564 	int i;
565 
566 	for (i = 0; i < count; ++i) {
567 		descs[seq_tail] = cache[cache_head];
568 		seq_tail = (seq_tail + 1) % seq_size;
569 		cache_head = (cache_head + 1) % cache_size;
570 	}
571 
572 	s->ctx_data.rx.seq.tail = seq_tail;
573 	s->ctx_data.rx.cache_head = cache_head;
574 }
575 
576 static void pool_seq_descs(struct amdtp_stream *s, unsigned int count)
577 {
578 	struct amdtp_domain *d = s->domain;
579 
580 	if (!d->replay.enable || !s->ctx_data.rx.replay_target) {
581 		pool_ideal_seq_descs(s, count);
582 	} else {
583 		if (!d->replay.on_the_fly) {
584 			pool_replayed_seq(s, count);
585 		} else {
586 			struct amdtp_stream *tx = s->ctx_data.rx.replay_target;
587 			const unsigned int cache_size = tx->ctx_data.tx.cache.size;
588 			const unsigned int cache_head = s->ctx_data.rx.cache_head;
589 			unsigned int cached_cycles = calculate_cached_cycle_count(tx, cache_head);
590 
591 			if (cached_cycles > count && cached_cycles > cache_size / 2)
592 				pool_replayed_seq(s, count);
593 			else
594 				pool_ideal_seq_descs(s, count);
595 		}
596 	}
597 }
598 
599 static void update_pcm_pointers(struct amdtp_stream *s,
600 				struct snd_pcm_substream *pcm,
601 				unsigned int frames)
602 {
603 	unsigned int ptr;
604 
605 	ptr = s->pcm_buffer_pointer + frames;
606 	if (ptr >= pcm->runtime->buffer_size)
607 		ptr -= pcm->runtime->buffer_size;
608 	WRITE_ONCE(s->pcm_buffer_pointer, ptr);
609 
610 	s->pcm_period_pointer += frames;
611 	if (s->pcm_period_pointer >= pcm->runtime->period_size) {
612 		s->pcm_period_pointer -= pcm->runtime->period_size;
613 		queue_work(system_highpri_wq, &s->period_work);
614 	}
615 }
616 
617 static void pcm_period_work(struct work_struct *work)
618 {
619 	struct amdtp_stream *s = container_of(work, struct amdtp_stream,
620 					      period_work);
621 	struct snd_pcm_substream *pcm = READ_ONCE(s->pcm);
622 
623 	if (pcm)
624 		snd_pcm_period_elapsed(pcm);
625 }
626 
627 static int queue_packet(struct amdtp_stream *s, struct fw_iso_packet *params,
628 			bool sched_irq)
629 {
630 	int err;
631 
632 	params->interrupt = sched_irq;
633 	params->tag = s->tag;
634 	params->sy = 0;
635 
636 	err = fw_iso_context_queue(s->context, params, &s->buffer.iso_buffer,
637 				   s->buffer.packets[s->packet_index].offset);
638 	if (err < 0) {
639 		dev_err(&s->unit->device, "queueing error: %d\n", err);
640 		goto end;
641 	}
642 
643 	if (++s->packet_index >= s->queue_size)
644 		s->packet_index = 0;
645 end:
646 	return err;
647 }
648 
649 static inline int queue_out_packet(struct amdtp_stream *s,
650 				   struct fw_iso_packet *params, bool sched_irq)
651 {
652 	params->skip =
653 		!!(params->header_length == 0 && params->payload_length == 0);
654 	return queue_packet(s, params, sched_irq);
655 }
656 
657 static inline int queue_in_packet(struct amdtp_stream *s,
658 				  struct fw_iso_packet *params)
659 {
660 	// Queue one packet for IR context.
661 	params->header_length = s->ctx_data.tx.ctx_header_size;
662 	params->payload_length = s->ctx_data.tx.max_ctx_payload_length;
663 	params->skip = false;
664 	return queue_packet(s, params, false);
665 }
666 
667 static void generate_cip_header(struct amdtp_stream *s, __be32 cip_header[2],
668 			unsigned int data_block_counter, unsigned int syt)
669 {
670 	cip_header[0] = cpu_to_be32(READ_ONCE(s->source_node_id_field) |
671 				(s->data_block_quadlets << CIP_DBS_SHIFT) |
672 				((s->sph << CIP_SPH_SHIFT) & CIP_SPH_MASK) |
673 				data_block_counter);
674 	cip_header[1] = cpu_to_be32(CIP_EOH |
675 			((s->fmt << CIP_FMT_SHIFT) & CIP_FMT_MASK) |
676 			((s->ctx_data.rx.fdf << CIP_FDF_SHIFT) & CIP_FDF_MASK) |
677 			(syt & CIP_SYT_MASK));
678 }
679 
680 static void build_it_pkt_header(struct amdtp_stream *s, unsigned int cycle,
681 				struct fw_iso_packet *params, unsigned int header_length,
682 				unsigned int data_blocks,
683 				unsigned int data_block_counter,
684 				unsigned int syt, unsigned int index)
685 {
686 	unsigned int payload_length;
687 	__be32 *cip_header;
688 
689 	payload_length = data_blocks * sizeof(__be32) * s->data_block_quadlets;
690 	params->payload_length = payload_length;
691 
692 	if (header_length > 0) {
693 		cip_header = (__be32 *)params->header;
694 		generate_cip_header(s, cip_header, data_block_counter, syt);
695 		params->header_length = header_length;
696 	} else {
697 		cip_header = NULL;
698 	}
699 
700 	trace_amdtp_packet(s, cycle, cip_header, payload_length + header_length, data_blocks,
701 			   data_block_counter, s->packet_index, index);
702 }
703 
704 static int check_cip_header(struct amdtp_stream *s, const __be32 *buf,
705 			    unsigned int payload_length,
706 			    unsigned int *data_blocks,
707 			    unsigned int *data_block_counter, unsigned int *syt)
708 {
709 	u32 cip_header[2];
710 	unsigned int sph;
711 	unsigned int fmt;
712 	unsigned int fdf;
713 	unsigned int dbc;
714 	bool lost;
715 
716 	cip_header[0] = be32_to_cpu(buf[0]);
717 	cip_header[1] = be32_to_cpu(buf[1]);
718 
719 	/*
720 	 * This module supports 'Two-quadlet CIP header with SYT field'.
721 	 * For convenience, also check FMT field is AM824 or not.
722 	 */
723 	if ((((cip_header[0] & CIP_EOH_MASK) == CIP_EOH) ||
724 	     ((cip_header[1] & CIP_EOH_MASK) != CIP_EOH)) &&
725 	    (!(s->flags & CIP_HEADER_WITHOUT_EOH))) {
726 		dev_info_ratelimited(&s->unit->device,
727 				"Invalid CIP header for AMDTP: %08X:%08X\n",
728 				cip_header[0], cip_header[1]);
729 		return -EAGAIN;
730 	}
731 
732 	/* Check valid protocol or not. */
733 	sph = (cip_header[0] & CIP_SPH_MASK) >> CIP_SPH_SHIFT;
734 	fmt = (cip_header[1] & CIP_FMT_MASK) >> CIP_FMT_SHIFT;
735 	if (sph != s->sph || fmt != s->fmt) {
736 		dev_info_ratelimited(&s->unit->device,
737 				     "Detect unexpected protocol: %08x %08x\n",
738 				     cip_header[0], cip_header[1]);
739 		return -EAGAIN;
740 	}
741 
742 	/* Calculate data blocks */
743 	fdf = (cip_header[1] & CIP_FDF_MASK) >> CIP_FDF_SHIFT;
744 	if (payload_length == 0 || (fmt == CIP_FMT_AM && fdf == AMDTP_FDF_NO_DATA)) {
745 		*data_blocks = 0;
746 	} else {
747 		unsigned int data_block_quadlets =
748 				(cip_header[0] & CIP_DBS_MASK) >> CIP_DBS_SHIFT;
749 		/* avoid division by zero */
750 		if (data_block_quadlets == 0) {
751 			dev_err(&s->unit->device,
752 				"Detect invalid value in dbs field: %08X\n",
753 				cip_header[0]);
754 			return -EPROTO;
755 		}
756 		if (s->flags & CIP_WRONG_DBS)
757 			data_block_quadlets = s->data_block_quadlets;
758 
759 		*data_blocks = payload_length / sizeof(__be32) / data_block_quadlets;
760 	}
761 
762 	/* Check data block counter continuity */
763 	dbc = cip_header[0] & CIP_DBC_MASK;
764 	if (*data_blocks == 0 && (s->flags & CIP_EMPTY_HAS_WRONG_DBC) &&
765 	    *data_block_counter != UINT_MAX)
766 		dbc = *data_block_counter;
767 
768 	if ((dbc == 0x00 && (s->flags & CIP_SKIP_DBC_ZERO_CHECK)) ||
769 	    *data_block_counter == UINT_MAX) {
770 		lost = false;
771 	} else if (!(s->flags & CIP_DBC_IS_END_EVENT)) {
772 		lost = dbc != *data_block_counter;
773 	} else {
774 		unsigned int dbc_interval;
775 
776 		if (*data_blocks > 0 && s->ctx_data.tx.dbc_interval > 0)
777 			dbc_interval = s->ctx_data.tx.dbc_interval;
778 		else
779 			dbc_interval = *data_blocks;
780 
781 		lost = dbc != ((*data_block_counter + dbc_interval) & 0xff);
782 	}
783 
784 	if (lost) {
785 		dev_err(&s->unit->device,
786 			"Detect discontinuity of CIP: %02X %02X\n",
787 			*data_block_counter, dbc);
788 		return -EIO;
789 	}
790 
791 	*data_block_counter = dbc;
792 
793 	if (!(s->flags & CIP_UNAWARE_SYT))
794 		*syt = cip_header[1] & CIP_SYT_MASK;
795 
796 	return 0;
797 }
798 
799 static int parse_ir_ctx_header(struct amdtp_stream *s, unsigned int cycle,
800 			       const __be32 *ctx_header,
801 			       unsigned int *data_blocks,
802 			       unsigned int *data_block_counter,
803 			       unsigned int *syt, unsigned int packet_index, unsigned int index)
804 {
805 	unsigned int payload_length;
806 	const __be32 *cip_header;
807 	unsigned int cip_header_size;
808 
809 	payload_length = be32_to_cpu(ctx_header[0]) >> ISO_DATA_LENGTH_SHIFT;
810 
811 	if (!(s->flags & CIP_NO_HEADER))
812 		cip_header_size = CIP_HEADER_SIZE;
813 	else
814 		cip_header_size = 0;
815 
816 	if (payload_length > cip_header_size + s->ctx_data.tx.max_ctx_payload_length) {
817 		dev_err(&s->unit->device,
818 			"Detect jumbo payload: %04x %04x\n",
819 			payload_length, cip_header_size + s->ctx_data.tx.max_ctx_payload_length);
820 		return -EIO;
821 	}
822 
823 	if (cip_header_size > 0) {
824 		if (payload_length >= cip_header_size) {
825 			int err;
826 
827 			cip_header = ctx_header + IR_CTX_HEADER_DEFAULT_QUADLETS;
828 			err = check_cip_header(s, cip_header, payload_length - cip_header_size,
829 					       data_blocks, data_block_counter, syt);
830 			if (err < 0)
831 				return err;
832 		} else {
833 			// Handle the cycle so that empty packet arrives.
834 			cip_header = NULL;
835 			*data_blocks = 0;
836 			*syt = 0;
837 		}
838 	} else {
839 		cip_header = NULL;
840 		*data_blocks = payload_length / sizeof(__be32) / s->data_block_quadlets;
841 		*syt = 0;
842 
843 		if (*data_block_counter == UINT_MAX)
844 			*data_block_counter = 0;
845 	}
846 
847 	trace_amdtp_packet(s, cycle, cip_header, payload_length, *data_blocks,
848 			   *data_block_counter, packet_index, index);
849 
850 	return 0;
851 }
852 
853 // In CYCLE_TIMER register of IEEE 1394, 7 bits are used to represent second. On
854 // the other hand, in DMA descriptors of 1394 OHCI, 3 bits are used to represent
855 // it. Thus, via Linux firewire subsystem, we can get the 3 bits for second.
856 static inline u32 compute_ohci_cycle_count(__be32 ctx_header_tstamp)
857 {
858 	u32 tstamp = be32_to_cpu(ctx_header_tstamp) & HEADER_TSTAMP_MASK;
859 	return (((tstamp >> 13) & 0x07) * 8000) + (tstamp & 0x1fff);
860 }
861 
862 static inline u32 increment_ohci_cycle_count(u32 cycle, unsigned int addend)
863 {
864 	cycle += addend;
865 	if (cycle >= OHCI_SECOND_MODULUS * CYCLES_PER_SECOND)
866 		cycle -= OHCI_SECOND_MODULUS * CYCLES_PER_SECOND;
867 	return cycle;
868 }
869 
870 static int compare_ohci_cycle_count(u32 lval, u32 rval)
871 {
872 	if (lval == rval)
873 		return 0;
874 	else if (lval < rval && rval - lval < OHCI_SECOND_MODULUS * CYCLES_PER_SECOND / 2)
875 		return -1;
876 	else
877 		return 1;
878 }
879 
880 // Align to actual cycle count for the packet which is going to be scheduled.
881 // This module queued the same number of isochronous cycle as the size of queue
882 // to kip isochronous cycle, therefore it's OK to just increment the cycle by
883 // the size of queue for scheduled cycle.
884 static inline u32 compute_ohci_it_cycle(const __be32 ctx_header_tstamp,
885 					unsigned int queue_size)
886 {
887 	u32 cycle = compute_ohci_cycle_count(ctx_header_tstamp);
888 	return increment_ohci_cycle_count(cycle, queue_size);
889 }
890 
891 static int generate_device_pkt_descs(struct amdtp_stream *s,
892 				     struct pkt_desc *descs,
893 				     const __be32 *ctx_header,
894 				     unsigned int packets,
895 				     unsigned int *desc_count)
896 {
897 	unsigned int next_cycle = s->next_cycle;
898 	unsigned int dbc = s->data_block_counter;
899 	unsigned int packet_index = s->packet_index;
900 	unsigned int queue_size = s->queue_size;
901 	int i;
902 	int err;
903 
904 	*desc_count = 0;
905 	for (i = 0; i < packets; ++i) {
906 		struct pkt_desc *desc = descs + *desc_count;
907 		unsigned int cycle;
908 		bool lost;
909 		unsigned int data_blocks;
910 		unsigned int syt;
911 
912 		cycle = compute_ohci_cycle_count(ctx_header[1]);
913 		lost = (next_cycle != cycle);
914 		if (lost) {
915 			if (s->flags & CIP_NO_HEADER) {
916 				// Fireface skips transmission just for an isoc cycle corresponding
917 				// to empty packet.
918 				unsigned int prev_cycle = next_cycle;
919 
920 				next_cycle = increment_ohci_cycle_count(next_cycle, 1);
921 				lost = (next_cycle != cycle);
922 				if (!lost) {
923 					// Prepare a description for the skipped cycle for
924 					// sequence replay.
925 					desc->cycle = prev_cycle;
926 					desc->syt = 0;
927 					desc->data_blocks = 0;
928 					desc->data_block_counter = dbc;
929 					desc->ctx_payload = NULL;
930 					++desc;
931 					++(*desc_count);
932 				}
933 			} else if (s->flags & CIP_JUMBO_PAYLOAD) {
934 				// OXFW970 skips transmission for several isoc cycles during
935 				// asynchronous transaction. The sequence replay is impossible due
936 				// to the reason.
937 				unsigned int safe_cycle = increment_ohci_cycle_count(next_cycle,
938 								IR_JUMBO_PAYLOAD_MAX_SKIP_CYCLES);
939 				lost = (compare_ohci_cycle_count(safe_cycle, cycle) > 0);
940 			}
941 			if (lost) {
942 				dev_err(&s->unit->device, "Detect discontinuity of cycle: %d %d\n",
943 					next_cycle, cycle);
944 				return -EIO;
945 			}
946 		}
947 
948 		err = parse_ir_ctx_header(s, cycle, ctx_header, &data_blocks, &dbc, &syt,
949 					  packet_index, i);
950 		if (err < 0)
951 			return err;
952 
953 		desc->cycle = cycle;
954 		desc->syt = syt;
955 		desc->data_blocks = data_blocks;
956 		desc->data_block_counter = dbc;
957 		desc->ctx_payload = s->buffer.packets[packet_index].buffer;
958 
959 		if (!(s->flags & CIP_DBC_IS_END_EVENT))
960 			dbc = (dbc + desc->data_blocks) & 0xff;
961 
962 		next_cycle = increment_ohci_cycle_count(next_cycle, 1);
963 		++(*desc_count);
964 		ctx_header += s->ctx_data.tx.ctx_header_size / sizeof(*ctx_header);
965 		packet_index = (packet_index + 1) % queue_size;
966 	}
967 
968 	s->next_cycle = next_cycle;
969 	s->data_block_counter = dbc;
970 
971 	return 0;
972 }
973 
974 static unsigned int compute_syt(unsigned int syt_offset, unsigned int cycle,
975 				unsigned int transfer_delay)
976 {
977 	unsigned int syt;
978 
979 	syt_offset += transfer_delay;
980 	syt = ((cycle + syt_offset / TICKS_PER_CYCLE) << 12) |
981 	      (syt_offset % TICKS_PER_CYCLE);
982 	return syt & CIP_SYT_MASK;
983 }
984 
985 static void generate_pkt_descs(struct amdtp_stream *s, const __be32 *ctx_header, unsigned int packets)
986 {
987 	struct pkt_desc *descs = s->pkt_descs;
988 	const struct seq_desc *seq_descs = s->ctx_data.rx.seq.descs;
989 	const unsigned int seq_size = s->ctx_data.rx.seq.size;
990 	unsigned int dbc = s->data_block_counter;
991 	unsigned int seq_head = s->ctx_data.rx.seq.head;
992 	bool aware_syt = !(s->flags & CIP_UNAWARE_SYT);
993 	int i;
994 
995 	for (i = 0; i < packets; ++i) {
996 		struct pkt_desc *desc = descs + i;
997 		unsigned int index = (s->packet_index + i) % s->queue_size;
998 		const struct seq_desc *seq = seq_descs + seq_head;
999 
1000 		desc->cycle = compute_ohci_it_cycle(*ctx_header, s->queue_size);
1001 
1002 		if (aware_syt && seq->syt_offset != CIP_SYT_NO_INFO)
1003 			desc->syt = compute_syt(seq->syt_offset, desc->cycle, s->transfer_delay);
1004 		else
1005 			desc->syt = CIP_SYT_NO_INFO;
1006 
1007 		desc->data_blocks = seq->data_blocks;
1008 
1009 		if (s->flags & CIP_DBC_IS_END_EVENT)
1010 			dbc = (dbc + desc->data_blocks) & 0xff;
1011 
1012 		desc->data_block_counter = dbc;
1013 
1014 		if (!(s->flags & CIP_DBC_IS_END_EVENT))
1015 			dbc = (dbc + desc->data_blocks) & 0xff;
1016 
1017 		desc->ctx_payload = s->buffer.packets[index].buffer;
1018 
1019 		seq_head = (seq_head + 1) % seq_size;
1020 
1021 		++ctx_header;
1022 	}
1023 
1024 	s->data_block_counter = dbc;
1025 	s->ctx_data.rx.seq.head = seq_head;
1026 }
1027 
1028 static inline void cancel_stream(struct amdtp_stream *s)
1029 {
1030 	s->packet_index = -1;
1031 	if (current_work() == &s->period_work)
1032 		amdtp_stream_pcm_abort(s);
1033 	WRITE_ONCE(s->pcm_buffer_pointer, SNDRV_PCM_POS_XRUN);
1034 }
1035 
1036 static void process_ctx_payloads(struct amdtp_stream *s,
1037 				 const struct pkt_desc *descs,
1038 				 unsigned int packets)
1039 {
1040 	struct snd_pcm_substream *pcm;
1041 	unsigned int pcm_frames;
1042 
1043 	pcm = READ_ONCE(s->pcm);
1044 	pcm_frames = s->process_ctx_payloads(s, descs, packets, pcm);
1045 	if (pcm)
1046 		update_pcm_pointers(s, pcm, pcm_frames);
1047 }
1048 
1049 static void process_rx_packets(struct fw_iso_context *context, u32 tstamp, size_t header_length,
1050 			       void *header, void *private_data)
1051 {
1052 	struct amdtp_stream *s = private_data;
1053 	const struct amdtp_domain *d = s->domain;
1054 	const __be32 *ctx_header = header;
1055 	const unsigned int events_per_period = d->events_per_period;
1056 	unsigned int event_count = s->ctx_data.rx.event_count;
1057 	unsigned int pkt_header_length;
1058 	unsigned int packets;
1059 	int i;
1060 
1061 	if (s->packet_index < 0)
1062 		return;
1063 
1064 	// Calculate the number of packets in buffer and check XRUN.
1065 	packets = header_length / sizeof(*ctx_header);
1066 
1067 	pool_seq_descs(s, packets);
1068 
1069 	generate_pkt_descs(s, ctx_header, packets);
1070 
1071 	process_ctx_payloads(s, s->pkt_descs, packets);
1072 
1073 	if (!(s->flags & CIP_NO_HEADER))
1074 		pkt_header_length = IT_PKT_HEADER_SIZE_CIP;
1075 	else
1076 		pkt_header_length = 0;
1077 
1078 	for (i = 0; i < packets; ++i) {
1079 		const struct pkt_desc *desc = s->pkt_descs + i;
1080 		struct {
1081 			struct fw_iso_packet params;
1082 			__be32 header[CIP_HEADER_QUADLETS];
1083 		} template = { {0}, {0} };
1084 		bool sched_irq = false;
1085 
1086 		build_it_pkt_header(s, desc->cycle, &template.params, pkt_header_length,
1087 				    desc->data_blocks, desc->data_block_counter,
1088 				    desc->syt, i);
1089 
1090 		if (s == s->domain->irq_target) {
1091 			event_count += desc->data_blocks;
1092 			if (event_count >= events_per_period) {
1093 				event_count -= events_per_period;
1094 				sched_irq = true;
1095 			}
1096 		}
1097 
1098 		if (queue_out_packet(s, &template.params, sched_irq) < 0) {
1099 			cancel_stream(s);
1100 			return;
1101 		}
1102 	}
1103 
1104 	s->ctx_data.rx.event_count = event_count;
1105 }
1106 
1107 static void skip_rx_packets(struct fw_iso_context *context, u32 tstamp, size_t header_length,
1108 			    void *header, void *private_data)
1109 {
1110 	struct amdtp_stream *s = private_data;
1111 	struct amdtp_domain *d = s->domain;
1112 	const __be32 *ctx_header = header;
1113 	unsigned int packets;
1114 	unsigned int cycle;
1115 	int i;
1116 
1117 	if (s->packet_index < 0)
1118 		return;
1119 
1120 	packets = header_length / sizeof(*ctx_header);
1121 
1122 	cycle = compute_ohci_it_cycle(ctx_header[packets - 1], s->queue_size);
1123 	s->next_cycle = increment_ohci_cycle_count(cycle, 1);
1124 
1125 	for (i = 0; i < packets; ++i) {
1126 		struct fw_iso_packet params = {
1127 			.header_length = 0,
1128 			.payload_length = 0,
1129 		};
1130 		bool sched_irq = (s == d->irq_target && i == packets - 1);
1131 
1132 		if (queue_out_packet(s, &params, sched_irq) < 0) {
1133 			cancel_stream(s);
1134 			return;
1135 		}
1136 	}
1137 }
1138 
1139 static void irq_target_callback(struct fw_iso_context *context, u32 tstamp, size_t header_length,
1140 				void *header, void *private_data);
1141 
1142 static void process_rx_packets_intermediately(struct fw_iso_context *context, u32 tstamp,
1143 					size_t header_length, void *header, void *private_data)
1144 {
1145 	struct amdtp_stream *s = private_data;
1146 	struct amdtp_domain *d = s->domain;
1147 	__be32 *ctx_header = header;
1148 	const unsigned int queue_size = s->queue_size;
1149 	unsigned int packets;
1150 	unsigned int offset;
1151 
1152 	if (s->packet_index < 0)
1153 		return;
1154 
1155 	packets = header_length / sizeof(*ctx_header);
1156 
1157 	offset = 0;
1158 	while (offset < packets) {
1159 		unsigned int cycle = compute_ohci_it_cycle(ctx_header[offset], queue_size);
1160 
1161 		if (compare_ohci_cycle_count(cycle, d->processing_cycle.rx_start) >= 0)
1162 			break;
1163 
1164 		++offset;
1165 	}
1166 
1167 	if (offset > 0) {
1168 		unsigned int length = sizeof(*ctx_header) * offset;
1169 
1170 		skip_rx_packets(context, tstamp, length, ctx_header, private_data);
1171 		if (amdtp_streaming_error(s))
1172 			return;
1173 
1174 		ctx_header += offset;
1175 		header_length -= length;
1176 	}
1177 
1178 	if (offset < packets) {
1179 		s->ready_processing = true;
1180 		wake_up(&s->ready_wait);
1181 
1182 		process_rx_packets(context, tstamp, header_length, ctx_header, private_data);
1183 		if (amdtp_streaming_error(s))
1184 			return;
1185 
1186 		if (s == d->irq_target)
1187 			s->context->callback.sc = irq_target_callback;
1188 		else
1189 			s->context->callback.sc = process_rx_packets;
1190 	}
1191 }
1192 
1193 static void process_tx_packets(struct fw_iso_context *context, u32 tstamp, size_t header_length,
1194 			       void *header, void *private_data)
1195 {
1196 	struct amdtp_stream *s = private_data;
1197 	__be32 *ctx_header = header;
1198 	unsigned int packets;
1199 	unsigned int desc_count;
1200 	int i;
1201 	int err;
1202 
1203 	if (s->packet_index < 0)
1204 		return;
1205 
1206 	// Calculate the number of packets in buffer and check XRUN.
1207 	packets = header_length / s->ctx_data.tx.ctx_header_size;
1208 
1209 	desc_count = 0;
1210 	err = generate_device_pkt_descs(s, s->pkt_descs, ctx_header, packets, &desc_count);
1211 	if (err < 0) {
1212 		if (err != -EAGAIN) {
1213 			cancel_stream(s);
1214 			return;
1215 		}
1216 	} else {
1217 		struct amdtp_domain *d = s->domain;
1218 
1219 		process_ctx_payloads(s, s->pkt_descs, desc_count);
1220 
1221 		if (d->replay.enable)
1222 			cache_seq(s, s->pkt_descs, desc_count);
1223 	}
1224 
1225 	for (i = 0; i < packets; ++i) {
1226 		struct fw_iso_packet params = {0};
1227 
1228 		if (queue_in_packet(s, &params) < 0) {
1229 			cancel_stream(s);
1230 			return;
1231 		}
1232 	}
1233 }
1234 
1235 static void drop_tx_packets(struct fw_iso_context *context, u32 tstamp, size_t header_length,
1236 			    void *header, void *private_data)
1237 {
1238 	struct amdtp_stream *s = private_data;
1239 	const __be32 *ctx_header = header;
1240 	unsigned int packets;
1241 	unsigned int cycle;
1242 	int i;
1243 
1244 	if (s->packet_index < 0)
1245 		return;
1246 
1247 	packets = header_length / s->ctx_data.tx.ctx_header_size;
1248 
1249 	ctx_header += (packets - 1) * s->ctx_data.tx.ctx_header_size / sizeof(*ctx_header);
1250 	cycle = compute_ohci_cycle_count(ctx_header[1]);
1251 	s->next_cycle = increment_ohci_cycle_count(cycle, 1);
1252 
1253 	for (i = 0; i < packets; ++i) {
1254 		struct fw_iso_packet params = {0};
1255 
1256 		if (queue_in_packet(s, &params) < 0) {
1257 			cancel_stream(s);
1258 			return;
1259 		}
1260 	}
1261 }
1262 
1263 static void process_tx_packets_intermediately(struct fw_iso_context *context, u32 tstamp,
1264 					size_t header_length, void *header, void *private_data)
1265 {
1266 	struct amdtp_stream *s = private_data;
1267 	struct amdtp_domain *d = s->domain;
1268 	__be32 *ctx_header;
1269 	unsigned int packets;
1270 	unsigned int offset;
1271 
1272 	if (s->packet_index < 0)
1273 		return;
1274 
1275 	packets = header_length / s->ctx_data.tx.ctx_header_size;
1276 
1277 	offset = 0;
1278 	ctx_header = header;
1279 	while (offset < packets) {
1280 		unsigned int cycle = compute_ohci_cycle_count(ctx_header[1]);
1281 
1282 		if (compare_ohci_cycle_count(cycle, d->processing_cycle.tx_start) >= 0)
1283 			break;
1284 
1285 		ctx_header += s->ctx_data.tx.ctx_header_size / sizeof(__be32);
1286 		++offset;
1287 	}
1288 
1289 	ctx_header = header;
1290 
1291 	if (offset > 0) {
1292 		size_t length = s->ctx_data.tx.ctx_header_size * offset;
1293 
1294 		drop_tx_packets(context, tstamp, length, ctx_header, s);
1295 		if (amdtp_streaming_error(s))
1296 			return;
1297 
1298 		ctx_header += length / sizeof(*ctx_header);
1299 		header_length -= length;
1300 	}
1301 
1302 	if (offset < packets) {
1303 		s->ready_processing = true;
1304 		wake_up(&s->ready_wait);
1305 
1306 		process_tx_packets(context, tstamp, header_length, ctx_header, s);
1307 		if (amdtp_streaming_error(s))
1308 			return;
1309 
1310 		context->callback.sc = process_tx_packets;
1311 	}
1312 }
1313 
1314 static void drop_tx_packets_initially(struct fw_iso_context *context, u32 tstamp,
1315 				      size_t header_length, void *header, void *private_data)
1316 {
1317 	struct amdtp_stream *s = private_data;
1318 	struct amdtp_domain *d = s->domain;
1319 	__be32 *ctx_header;
1320 	unsigned int count;
1321 	unsigned int events;
1322 	int i;
1323 
1324 	if (s->packet_index < 0)
1325 		return;
1326 
1327 	count = header_length / s->ctx_data.tx.ctx_header_size;
1328 
1329 	// Attempt to detect any event in the batch of packets.
1330 	events = 0;
1331 	ctx_header = header;
1332 	for (i = 0; i < count; ++i) {
1333 		unsigned int payload_quads =
1334 			(be32_to_cpu(*ctx_header) >> ISO_DATA_LENGTH_SHIFT) / sizeof(__be32);
1335 		unsigned int data_blocks;
1336 
1337 		if (s->flags & CIP_NO_HEADER) {
1338 			data_blocks = payload_quads / s->data_block_quadlets;
1339 		} else {
1340 			__be32 *cip_headers = ctx_header + IR_CTX_HEADER_DEFAULT_QUADLETS;
1341 
1342 			if (payload_quads < CIP_HEADER_QUADLETS) {
1343 				data_blocks = 0;
1344 			} else {
1345 				payload_quads -= CIP_HEADER_QUADLETS;
1346 
1347 				if (s->flags & CIP_UNAWARE_SYT) {
1348 					data_blocks = payload_quads / s->data_block_quadlets;
1349 				} else {
1350 					u32 cip1 = be32_to_cpu(cip_headers[1]);
1351 
1352 					// NODATA packet can includes any data blocks but they are
1353 					// not available as event.
1354 					if ((cip1 & CIP_NO_DATA) == CIP_NO_DATA)
1355 						data_blocks = 0;
1356 					else
1357 						data_blocks = payload_quads / s->data_block_quadlets;
1358 				}
1359 			}
1360 		}
1361 
1362 		events += data_blocks;
1363 
1364 		ctx_header += s->ctx_data.tx.ctx_header_size / sizeof(__be32);
1365 	}
1366 
1367 	drop_tx_packets(context, tstamp, header_length, header, s);
1368 
1369 	if (events > 0)
1370 		s->ctx_data.tx.event_starts = true;
1371 
1372 	// Decide the cycle count to begin processing content of packet in IR contexts.
1373 	{
1374 		unsigned int stream_count = 0;
1375 		unsigned int event_starts_count = 0;
1376 		unsigned int cycle = UINT_MAX;
1377 
1378 		list_for_each_entry(s, &d->streams, list) {
1379 			if (s->direction == AMDTP_IN_STREAM) {
1380 				++stream_count;
1381 				if (s->ctx_data.tx.event_starts)
1382 					++event_starts_count;
1383 			}
1384 		}
1385 
1386 		if (stream_count == event_starts_count) {
1387 			unsigned int next_cycle;
1388 
1389 			list_for_each_entry(s, &d->streams, list) {
1390 				if (s->direction != AMDTP_IN_STREAM)
1391 					continue;
1392 
1393 				next_cycle = increment_ohci_cycle_count(s->next_cycle,
1394 								d->processing_cycle.tx_init_skip);
1395 				if (cycle == UINT_MAX ||
1396 				    compare_ohci_cycle_count(next_cycle, cycle) > 0)
1397 					cycle = next_cycle;
1398 
1399 				s->context->callback.sc = process_tx_packets_intermediately;
1400 			}
1401 
1402 			d->processing_cycle.tx_start = cycle;
1403 		}
1404 	}
1405 }
1406 
1407 static void process_ctxs_in_domain(struct amdtp_domain *d)
1408 {
1409 	struct amdtp_stream *s;
1410 
1411 	list_for_each_entry(s, &d->streams, list) {
1412 		if (s != d->irq_target && amdtp_stream_running(s))
1413 			fw_iso_context_flush_completions(s->context);
1414 
1415 		if (amdtp_streaming_error(s))
1416 			goto error;
1417 	}
1418 
1419 	return;
1420 error:
1421 	if (amdtp_stream_running(d->irq_target))
1422 		cancel_stream(d->irq_target);
1423 
1424 	list_for_each_entry(s, &d->streams, list) {
1425 		if (amdtp_stream_running(s))
1426 			cancel_stream(s);
1427 	}
1428 }
1429 
1430 static void irq_target_callback(struct fw_iso_context *context, u32 tstamp, size_t header_length,
1431 				void *header, void *private_data)
1432 {
1433 	struct amdtp_stream *s = private_data;
1434 	struct amdtp_domain *d = s->domain;
1435 
1436 	process_rx_packets(context, tstamp, header_length, header, private_data);
1437 	process_ctxs_in_domain(d);
1438 }
1439 
1440 static void irq_target_callback_intermediately(struct fw_iso_context *context, u32 tstamp,
1441 					size_t header_length, void *header, void *private_data)
1442 {
1443 	struct amdtp_stream *s = private_data;
1444 	struct amdtp_domain *d = s->domain;
1445 
1446 	process_rx_packets_intermediately(context, tstamp, header_length, header, private_data);
1447 	process_ctxs_in_domain(d);
1448 }
1449 
1450 static void irq_target_callback_skip(struct fw_iso_context *context, u32 tstamp,
1451 				     size_t header_length, void *header, void *private_data)
1452 {
1453 	struct amdtp_stream *s = private_data;
1454 	struct amdtp_domain *d = s->domain;
1455 	bool ready_to_start;
1456 
1457 	skip_rx_packets(context, tstamp, header_length, header, private_data);
1458 	process_ctxs_in_domain(d);
1459 
1460 	if (d->replay.enable && !d->replay.on_the_fly) {
1461 		unsigned int rx_count = 0;
1462 		unsigned int rx_ready_count = 0;
1463 		struct amdtp_stream *rx;
1464 
1465 		list_for_each_entry(rx, &d->streams, list) {
1466 			struct amdtp_stream *tx;
1467 			unsigned int cached_cycles;
1468 
1469 			if (rx->direction != AMDTP_OUT_STREAM)
1470 				continue;
1471 			++rx_count;
1472 
1473 			tx = rx->ctx_data.rx.replay_target;
1474 			cached_cycles = calculate_cached_cycle_count(tx, 0);
1475 			if (cached_cycles > tx->ctx_data.tx.cache.size / 2)
1476 				++rx_ready_count;
1477 		}
1478 
1479 		ready_to_start = (rx_count == rx_ready_count);
1480 	} else {
1481 		ready_to_start = true;
1482 	}
1483 
1484 	// Decide the cycle count to begin processing content of packet in IT contexts. All of IT
1485 	// contexts are expected to start and get callback when reaching here.
1486 	if (ready_to_start) {
1487 		unsigned int cycle = s->next_cycle;
1488 		list_for_each_entry(s, &d->streams, list) {
1489 			if (s->direction != AMDTP_OUT_STREAM)
1490 				continue;
1491 
1492 			if (compare_ohci_cycle_count(s->next_cycle, cycle) > 0)
1493 				cycle = s->next_cycle;
1494 
1495 			if (s == d->irq_target)
1496 				s->context->callback.sc = irq_target_callback_intermediately;
1497 			else
1498 				s->context->callback.sc = process_rx_packets_intermediately;
1499 		}
1500 
1501 		d->processing_cycle.rx_start = cycle;
1502 	}
1503 }
1504 
1505 // This is executed one time. For in-stream, first packet has come. For out-stream, prepared to
1506 // transmit first packet.
1507 static void amdtp_stream_first_callback(struct fw_iso_context *context,
1508 					u32 tstamp, size_t header_length,
1509 					void *header, void *private_data)
1510 {
1511 	struct amdtp_stream *s = private_data;
1512 	struct amdtp_domain *d = s->domain;
1513 
1514 	if (s->direction == AMDTP_IN_STREAM) {
1515 		context->callback.sc = drop_tx_packets_initially;
1516 	} else {
1517 		if (s == d->irq_target)
1518 			context->callback.sc = irq_target_callback_skip;
1519 		else
1520 			context->callback.sc = skip_rx_packets;
1521 	}
1522 
1523 	context->callback.sc(context, tstamp, header_length, header, s);
1524 }
1525 
1526 /**
1527  * amdtp_stream_start - start transferring packets
1528  * @s: the AMDTP stream to start
1529  * @channel: the isochronous channel on the bus
1530  * @speed: firewire speed code
1531  * @queue_size: The number of packets in the queue.
1532  * @idle_irq_interval: the interval to queue packet during initial state.
1533  *
1534  * The stream cannot be started until it has been configured with
1535  * amdtp_stream_set_parameters() and it must be started before any PCM or MIDI
1536  * device can be started.
1537  */
1538 static int amdtp_stream_start(struct amdtp_stream *s, int channel, int speed,
1539 			      unsigned int queue_size, unsigned int idle_irq_interval)
1540 {
1541 	bool is_irq_target = (s == s->domain->irq_target);
1542 	unsigned int ctx_header_size;
1543 	unsigned int max_ctx_payload_size;
1544 	enum dma_data_direction dir;
1545 	int type, tag, err;
1546 
1547 	mutex_lock(&s->mutex);
1548 
1549 	if (WARN_ON(amdtp_stream_running(s) ||
1550 		    (s->data_block_quadlets < 1))) {
1551 		err = -EBADFD;
1552 		goto err_unlock;
1553 	}
1554 
1555 	if (s->direction == AMDTP_IN_STREAM) {
1556 		// NOTE: IT context should be used for constant IRQ.
1557 		if (is_irq_target) {
1558 			err = -EINVAL;
1559 			goto err_unlock;
1560 		}
1561 
1562 		s->data_block_counter = UINT_MAX;
1563 	} else {
1564 		s->data_block_counter = 0;
1565 	}
1566 
1567 	// initialize packet buffer.
1568 	if (s->direction == AMDTP_IN_STREAM) {
1569 		dir = DMA_FROM_DEVICE;
1570 		type = FW_ISO_CONTEXT_RECEIVE;
1571 		if (!(s->flags & CIP_NO_HEADER))
1572 			ctx_header_size = IR_CTX_HEADER_SIZE_CIP;
1573 		else
1574 			ctx_header_size = IR_CTX_HEADER_SIZE_NO_CIP;
1575 	} else {
1576 		dir = DMA_TO_DEVICE;
1577 		type = FW_ISO_CONTEXT_TRANSMIT;
1578 		ctx_header_size = 0;	// No effect for IT context.
1579 	}
1580 	max_ctx_payload_size = amdtp_stream_get_max_ctx_payload_size(s);
1581 
1582 	err = iso_packets_buffer_init(&s->buffer, s->unit, queue_size, max_ctx_payload_size, dir);
1583 	if (err < 0)
1584 		goto err_unlock;
1585 	s->queue_size = queue_size;
1586 
1587 	s->context = fw_iso_context_create(fw_parent_device(s->unit)->card,
1588 					  type, channel, speed, ctx_header_size,
1589 					  amdtp_stream_first_callback, s);
1590 	if (IS_ERR(s->context)) {
1591 		err = PTR_ERR(s->context);
1592 		if (err == -EBUSY)
1593 			dev_err(&s->unit->device,
1594 				"no free stream on this controller\n");
1595 		goto err_buffer;
1596 	}
1597 
1598 	amdtp_stream_update(s);
1599 
1600 	if (s->direction == AMDTP_IN_STREAM) {
1601 		s->ctx_data.tx.max_ctx_payload_length = max_ctx_payload_size;
1602 		s->ctx_data.tx.ctx_header_size = ctx_header_size;
1603 		s->ctx_data.tx.event_starts = false;
1604 
1605 		if (s->domain->replay.enable) {
1606 			// struct fw_iso_context.drop_overflow_headers is false therefore it's
1607 			// possible to cache much unexpectedly.
1608 			s->ctx_data.tx.cache.size = max_t(unsigned int, s->syt_interval * 2,
1609 							  queue_size * 3 / 2);
1610 			s->ctx_data.tx.cache.tail = 0;
1611 			s->ctx_data.tx.cache.descs = kcalloc(s->ctx_data.tx.cache.size,
1612 						sizeof(*s->ctx_data.tx.cache.descs), GFP_KERNEL);
1613 			if (!s->ctx_data.tx.cache.descs)
1614 				goto err_context;
1615 		}
1616 	} else {
1617 		static const struct {
1618 			unsigned int data_block;
1619 			unsigned int syt_offset;
1620 		} *entry, initial_state[] = {
1621 			[CIP_SFC_32000]  = {  4, 3072 },
1622 			[CIP_SFC_48000]  = {  6, 1024 },
1623 			[CIP_SFC_96000]  = { 12, 1024 },
1624 			[CIP_SFC_192000] = { 24, 1024 },
1625 			[CIP_SFC_44100]  = {  0,   67 },
1626 			[CIP_SFC_88200]  = {  0,   67 },
1627 			[CIP_SFC_176400] = {  0,   67 },
1628 		};
1629 
1630 		s->ctx_data.rx.seq.descs = kcalloc(queue_size, sizeof(*s->ctx_data.rx.seq.descs), GFP_KERNEL);
1631 		if (!s->ctx_data.rx.seq.descs)
1632 			goto err_context;
1633 		s->ctx_data.rx.seq.size = queue_size;
1634 		s->ctx_data.rx.seq.tail = 0;
1635 		s->ctx_data.rx.seq.head = 0;
1636 
1637 		entry = &initial_state[s->sfc];
1638 		s->ctx_data.rx.data_block_state = entry->data_block;
1639 		s->ctx_data.rx.syt_offset_state = entry->syt_offset;
1640 		s->ctx_data.rx.last_syt_offset = TICKS_PER_CYCLE;
1641 
1642 		s->ctx_data.rx.event_count = 0;
1643 	}
1644 
1645 	if (s->flags & CIP_NO_HEADER)
1646 		s->tag = TAG_NO_CIP_HEADER;
1647 	else
1648 		s->tag = TAG_CIP;
1649 
1650 	s->pkt_descs = kcalloc(s->queue_size, sizeof(*s->pkt_descs),
1651 			       GFP_KERNEL);
1652 	if (!s->pkt_descs) {
1653 		err = -ENOMEM;
1654 		goto err_context;
1655 	}
1656 
1657 	s->packet_index = 0;
1658 	do {
1659 		struct fw_iso_packet params;
1660 
1661 		if (s->direction == AMDTP_IN_STREAM) {
1662 			err = queue_in_packet(s, &params);
1663 		} else {
1664 			bool sched_irq = false;
1665 
1666 			params.header_length = 0;
1667 			params.payload_length = 0;
1668 
1669 			if (is_irq_target) {
1670 				sched_irq = !((s->packet_index + 1) %
1671 					      idle_irq_interval);
1672 			}
1673 
1674 			err = queue_out_packet(s, &params, sched_irq);
1675 		}
1676 		if (err < 0)
1677 			goto err_pkt_descs;
1678 	} while (s->packet_index > 0);
1679 
1680 	/* NOTE: TAG1 matches CIP. This just affects in stream. */
1681 	tag = FW_ISO_CONTEXT_MATCH_TAG1;
1682 	if ((s->flags & CIP_EMPTY_WITH_TAG0) || (s->flags & CIP_NO_HEADER))
1683 		tag |= FW_ISO_CONTEXT_MATCH_TAG0;
1684 
1685 	s->ready_processing = false;
1686 	err = fw_iso_context_start(s->context, -1, 0, tag);
1687 	if (err < 0)
1688 		goto err_pkt_descs;
1689 
1690 	mutex_unlock(&s->mutex);
1691 
1692 	return 0;
1693 err_pkt_descs:
1694 	kfree(s->pkt_descs);
1695 err_context:
1696 	if (s->direction == AMDTP_OUT_STREAM) {
1697 		kfree(s->ctx_data.rx.seq.descs);
1698 	} else {
1699 		if (s->domain->replay.enable)
1700 			kfree(s->ctx_data.tx.cache.descs);
1701 	}
1702 	fw_iso_context_destroy(s->context);
1703 	s->context = ERR_PTR(-1);
1704 err_buffer:
1705 	iso_packets_buffer_destroy(&s->buffer, s->unit);
1706 err_unlock:
1707 	mutex_unlock(&s->mutex);
1708 
1709 	return err;
1710 }
1711 
1712 /**
1713  * amdtp_domain_stream_pcm_pointer - get the PCM buffer position
1714  * @d: the AMDTP domain.
1715  * @s: the AMDTP stream that transports the PCM data
1716  *
1717  * Returns the current buffer position, in frames.
1718  */
1719 unsigned long amdtp_domain_stream_pcm_pointer(struct amdtp_domain *d,
1720 					      struct amdtp_stream *s)
1721 {
1722 	struct amdtp_stream *irq_target = d->irq_target;
1723 
1724 	if (irq_target && amdtp_stream_running(irq_target)) {
1725 		// This function is called in software IRQ context of
1726 		// period_work or process context.
1727 		//
1728 		// When the software IRQ context was scheduled by software IRQ
1729 		// context of IT contexts, queued packets were already handled.
1730 		// Therefore, no need to flush the queue in buffer furthermore.
1731 		//
1732 		// When the process context reach here, some packets will be
1733 		// already queued in the buffer. These packets should be handled
1734 		// immediately to keep better granularity of PCM pointer.
1735 		//
1736 		// Later, the process context will sometimes schedules software
1737 		// IRQ context of the period_work. Then, no need to flush the
1738 		// queue by the same reason as described in the above
1739 		if (current_work() != &s->period_work) {
1740 			// Queued packet should be processed without any kernel
1741 			// preemption to keep latency against bus cycle.
1742 			preempt_disable();
1743 			fw_iso_context_flush_completions(irq_target->context);
1744 			preempt_enable();
1745 		}
1746 	}
1747 
1748 	return READ_ONCE(s->pcm_buffer_pointer);
1749 }
1750 EXPORT_SYMBOL_GPL(amdtp_domain_stream_pcm_pointer);
1751 
1752 /**
1753  * amdtp_domain_stream_pcm_ack - acknowledge queued PCM frames
1754  * @d: the AMDTP domain.
1755  * @s: the AMDTP stream that transfers the PCM frames
1756  *
1757  * Returns zero always.
1758  */
1759 int amdtp_domain_stream_pcm_ack(struct amdtp_domain *d, struct amdtp_stream *s)
1760 {
1761 	struct amdtp_stream *irq_target = d->irq_target;
1762 
1763 	// Process isochronous packets for recent isochronous cycle to handle
1764 	// queued PCM frames.
1765 	if (irq_target && amdtp_stream_running(irq_target)) {
1766 		// Queued packet should be processed without any kernel
1767 		// preemption to keep latency against bus cycle.
1768 		preempt_disable();
1769 		fw_iso_context_flush_completions(irq_target->context);
1770 		preempt_enable();
1771 	}
1772 
1773 	return 0;
1774 }
1775 EXPORT_SYMBOL_GPL(amdtp_domain_stream_pcm_ack);
1776 
1777 /**
1778  * amdtp_stream_update - update the stream after a bus reset
1779  * @s: the AMDTP stream
1780  */
1781 void amdtp_stream_update(struct amdtp_stream *s)
1782 {
1783 	/* Precomputing. */
1784 	WRITE_ONCE(s->source_node_id_field,
1785                    (fw_parent_device(s->unit)->card->node_id << CIP_SID_SHIFT) & CIP_SID_MASK);
1786 }
1787 EXPORT_SYMBOL(amdtp_stream_update);
1788 
1789 /**
1790  * amdtp_stream_stop - stop sending packets
1791  * @s: the AMDTP stream to stop
1792  *
1793  * All PCM and MIDI devices of the stream must be stopped before the stream
1794  * itself can be stopped.
1795  */
1796 static void amdtp_stream_stop(struct amdtp_stream *s)
1797 {
1798 	mutex_lock(&s->mutex);
1799 
1800 	if (!amdtp_stream_running(s)) {
1801 		mutex_unlock(&s->mutex);
1802 		return;
1803 	}
1804 
1805 	cancel_work_sync(&s->period_work);
1806 	fw_iso_context_stop(s->context);
1807 	fw_iso_context_destroy(s->context);
1808 	s->context = ERR_PTR(-1);
1809 	iso_packets_buffer_destroy(&s->buffer, s->unit);
1810 	kfree(s->pkt_descs);
1811 
1812 	if (s->direction == AMDTP_OUT_STREAM) {
1813 		kfree(s->ctx_data.rx.seq.descs);
1814 	} else {
1815 		if (s->domain->replay.enable)
1816 			kfree(s->ctx_data.tx.cache.descs);
1817 	}
1818 
1819 	mutex_unlock(&s->mutex);
1820 }
1821 
1822 /**
1823  * amdtp_stream_pcm_abort - abort the running PCM device
1824  * @s: the AMDTP stream about to be stopped
1825  *
1826  * If the isochronous stream needs to be stopped asynchronously, call this
1827  * function first to stop the PCM device.
1828  */
1829 void amdtp_stream_pcm_abort(struct amdtp_stream *s)
1830 {
1831 	struct snd_pcm_substream *pcm;
1832 
1833 	pcm = READ_ONCE(s->pcm);
1834 	if (pcm)
1835 		snd_pcm_stop_xrun(pcm);
1836 }
1837 EXPORT_SYMBOL(amdtp_stream_pcm_abort);
1838 
1839 /**
1840  * amdtp_domain_init - initialize an AMDTP domain structure
1841  * @d: the AMDTP domain to initialize.
1842  */
1843 int amdtp_domain_init(struct amdtp_domain *d)
1844 {
1845 	INIT_LIST_HEAD(&d->streams);
1846 
1847 	d->events_per_period = 0;
1848 
1849 	return 0;
1850 }
1851 EXPORT_SYMBOL_GPL(amdtp_domain_init);
1852 
1853 /**
1854  * amdtp_domain_destroy - destroy an AMDTP domain structure
1855  * @d: the AMDTP domain to destroy.
1856  */
1857 void amdtp_domain_destroy(struct amdtp_domain *d)
1858 {
1859 	// At present nothing to do.
1860 	return;
1861 }
1862 EXPORT_SYMBOL_GPL(amdtp_domain_destroy);
1863 
1864 /**
1865  * amdtp_domain_add_stream - register isoc context into the domain.
1866  * @d: the AMDTP domain.
1867  * @s: the AMDTP stream.
1868  * @channel: the isochronous channel on the bus.
1869  * @speed: firewire speed code.
1870  */
1871 int amdtp_domain_add_stream(struct amdtp_domain *d, struct amdtp_stream *s,
1872 			    int channel, int speed)
1873 {
1874 	struct amdtp_stream *tmp;
1875 
1876 	list_for_each_entry(tmp, &d->streams, list) {
1877 		if (s == tmp)
1878 			return -EBUSY;
1879 	}
1880 
1881 	list_add(&s->list, &d->streams);
1882 
1883 	s->channel = channel;
1884 	s->speed = speed;
1885 	s->domain = d;
1886 
1887 	return 0;
1888 }
1889 EXPORT_SYMBOL_GPL(amdtp_domain_add_stream);
1890 
1891 // Make the reference from rx stream to tx stream for sequence replay. When the number of tx streams
1892 // is less than the number of rx streams, the first tx stream is selected.
1893 static int make_association(struct amdtp_domain *d)
1894 {
1895 	unsigned int dst_index = 0;
1896 	struct amdtp_stream *rx;
1897 
1898 	// Make association to replay target.
1899 	list_for_each_entry(rx, &d->streams, list) {
1900 		if (rx->direction == AMDTP_OUT_STREAM) {
1901 			unsigned int src_index = 0;
1902 			struct amdtp_stream *tx = NULL;
1903 			struct amdtp_stream *s;
1904 
1905 			list_for_each_entry(s, &d->streams, list) {
1906 				if (s->direction == AMDTP_IN_STREAM) {
1907 					if (dst_index == src_index) {
1908 						tx = s;
1909 						break;
1910 					}
1911 
1912 					++src_index;
1913 				}
1914 			}
1915 			if (!tx) {
1916 				// Select the first entry.
1917 				list_for_each_entry(s, &d->streams, list) {
1918 					if (s->direction == AMDTP_IN_STREAM) {
1919 						tx = s;
1920 						break;
1921 					}
1922 				}
1923 				// No target is available to replay sequence.
1924 				if (!tx)
1925 					return -EINVAL;
1926 			}
1927 
1928 			rx->ctx_data.rx.replay_target = tx;
1929 			rx->ctx_data.rx.cache_head = 0;
1930 
1931 			++dst_index;
1932 		}
1933 	}
1934 
1935 	return 0;
1936 }
1937 
1938 /**
1939  * amdtp_domain_start - start sending packets for isoc context in the domain.
1940  * @d: the AMDTP domain.
1941  * @tx_init_skip_cycles: the number of cycles to skip processing packets at initial stage of IR
1942  *			 contexts.
1943  * @replay_seq: whether to replay the sequence of packet in IR context for the sequence of packet in
1944  *		IT context.
1945  * @replay_on_the_fly: transfer rx packets according to nominal frequency, then begin to replay
1946  *		       according to arrival of events in tx packets.
1947  */
1948 int amdtp_domain_start(struct amdtp_domain *d, unsigned int tx_init_skip_cycles, bool replay_seq,
1949 		       bool replay_on_the_fly)
1950 {
1951 	unsigned int events_per_buffer = d->events_per_buffer;
1952 	unsigned int events_per_period = d->events_per_period;
1953 	unsigned int queue_size;
1954 	struct amdtp_stream *s;
1955 	int err;
1956 
1957 	if (replay_seq) {
1958 		err = make_association(d);
1959 		if (err < 0)
1960 			return err;
1961 	}
1962 	d->replay.enable = replay_seq;
1963 	d->replay.on_the_fly = replay_on_the_fly;
1964 
1965 	// Select an IT context as IRQ target.
1966 	list_for_each_entry(s, &d->streams, list) {
1967 		if (s->direction == AMDTP_OUT_STREAM)
1968 			break;
1969 	}
1970 	if (!s)
1971 		return -ENXIO;
1972 	d->irq_target = s;
1973 
1974 	d->processing_cycle.tx_init_skip = tx_init_skip_cycles;
1975 
1976 	// This is a case that AMDTP streams in domain run just for MIDI
1977 	// substream. Use the number of events equivalent to 10 msec as
1978 	// interval of hardware IRQ.
1979 	if (events_per_period == 0)
1980 		events_per_period = amdtp_rate_table[d->irq_target->sfc] / 100;
1981 	if (events_per_buffer == 0)
1982 		events_per_buffer = events_per_period * 3;
1983 
1984 	queue_size = DIV_ROUND_UP(CYCLES_PER_SECOND * events_per_buffer,
1985 				  amdtp_rate_table[d->irq_target->sfc]);
1986 
1987 	list_for_each_entry(s, &d->streams, list) {
1988 		unsigned int idle_irq_interval = 0;
1989 
1990 		if (s->direction == AMDTP_OUT_STREAM && s == d->irq_target) {
1991 			idle_irq_interval = DIV_ROUND_UP(CYCLES_PER_SECOND * events_per_period,
1992 							 amdtp_rate_table[d->irq_target->sfc]);
1993 		}
1994 
1995 		// Starts immediately but actually DMA context starts several hundred cycles later.
1996 		err = amdtp_stream_start(s, s->channel, s->speed, queue_size, idle_irq_interval);
1997 		if (err < 0)
1998 			goto error;
1999 	}
2000 
2001 	return 0;
2002 error:
2003 	list_for_each_entry(s, &d->streams, list)
2004 		amdtp_stream_stop(s);
2005 	return err;
2006 }
2007 EXPORT_SYMBOL_GPL(amdtp_domain_start);
2008 
2009 /**
2010  * amdtp_domain_stop - stop sending packets for isoc context in the same domain.
2011  * @d: the AMDTP domain to which the isoc contexts belong.
2012  */
2013 void amdtp_domain_stop(struct amdtp_domain *d)
2014 {
2015 	struct amdtp_stream *s, *next;
2016 
2017 	if (d->irq_target)
2018 		amdtp_stream_stop(d->irq_target);
2019 
2020 	list_for_each_entry_safe(s, next, &d->streams, list) {
2021 		list_del(&s->list);
2022 
2023 		if (s != d->irq_target)
2024 			amdtp_stream_stop(s);
2025 	}
2026 
2027 	d->events_per_period = 0;
2028 	d->irq_target = NULL;
2029 }
2030 EXPORT_SYMBOL_GPL(amdtp_domain_stop);
2031