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