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