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