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