ALSA: firewire-lib: code refactoring for syt computation
[linux-block.git] / sound / firewire / amdtp-stream.c
CommitLineData
da607e19 1// SPDX-License-Identifier: GPL-2.0-only
31ef9134
CL
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>
31ef9134
CL
7 */
8
9#include <linux/device.h>
10#include <linux/err.h>
11#include <linux/firewire.h>
acfedcbe 12#include <linux/firewire-constants.h>
31ef9134
CL
13#include <linux/module.h>
14#include <linux/slab.h>
15#include <sound/pcm.h>
7b2d99fa 16#include <sound/pcm_params.h>
d67c46b9 17#include "amdtp-stream.h"
31ef9134
CL
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
10aa8e4a
TS
23#define OHCI_MAX_SECOND 8
24
0c95c1d6
TS
25/* Always support Linux tracing subsystem. */
26#define CREATE_TRACE_POINTS
27#include "amdtp-stream-trace.h"
28
ca5b5050 29#define TRANSFER_DELAY_TICKS 0x2e00 /* 479.17 microseconds */
31ef9134 30
b445db44
TS
31/* isochronous header parameters */
32#define ISO_DATA_LENGTH_SHIFT 16
3b196c39 33#define TAG_NO_CIP_HEADER 0
31ef9134
CL
34#define TAG_CIP 1
35
b445db44 36/* common isochronous packet header parameters */
9a2820c1
TS
37#define CIP_EOH_SHIFT 31
38#define CIP_EOH (1u << CIP_EOH_SHIFT)
b445db44 39#define CIP_EOH_MASK 0x80000000
9a2820c1
TS
40#define CIP_SID_SHIFT 24
41#define CIP_SID_MASK 0x3f000000
42#define CIP_DBS_MASK 0x00ff0000
43#define CIP_DBS_SHIFT 16
9863874f
TS
44#define CIP_SPH_MASK 0x00000400
45#define CIP_SPH_SHIFT 10
9a2820c1
TS
46#define CIP_DBC_MASK 0x000000ff
47#define CIP_FMT_SHIFT 24
b445db44 48#define CIP_FMT_MASK 0x3f000000
9a2820c1
TS
49#define CIP_FDF_MASK 0x00ff0000
50#define CIP_FDF_SHIFT 16
b445db44
TS
51#define CIP_SYT_MASK 0x0000ffff
52#define CIP_SYT_NO_INFO 0xffff
b445db44 53
51c29fd2 54/* Audio and Music transfer protocol specific parameters */
414ba022 55#define CIP_FMT_AM 0x10
2b3fc456 56#define AMDTP_FDF_NO_DATA 0xff
31ef9134 57
f11453c7
TS
58// For iso header, tstamp and 2 CIP header.
59#define IR_CTX_HEADER_SIZE_CIP 16
60// For iso header and tstamp.
61#define IR_CTX_HEADER_SIZE_NO_CIP 8
cc4f8e91 62#define HEADER_TSTAMP_MASK 0x0000ffff
4b7da117 63
b18f0cfa
TS
64#define IT_PKT_HEADER_SIZE_CIP 8 // For 2 CIP header.
65#define IT_PKT_HEADER_SIZE_NO_CIP 0 // Nothing.
66
76fb8789
CL
67static void pcm_period_tasklet(unsigned long data);
68
31ef9134 69/**
be4a2894
TS
70 * amdtp_stream_init - initialize an AMDTP stream structure
71 * @s: the AMDTP stream to initialize
31ef9134 72 * @unit: the target of the stream
3ff7e8f0 73 * @dir: the direction of stream
31ef9134 74 * @flags: the packet transmission method to use
5955815e 75 * @fmt: the value of fmt field in CIP header
9a738ad1 76 * @process_ctx_payloads: callback handler to process payloads of isoc context
df075fee 77 * @protocol_size: the size to allocate newly for protocol
31ef9134 78 */
be4a2894 79int amdtp_stream_init(struct amdtp_stream *s, struct fw_unit *unit,
5955815e 80 enum amdtp_stream_direction dir, enum cip_flags flags,
df075fee 81 unsigned int fmt,
9a738ad1 82 amdtp_stream_process_ctx_payloads_t process_ctx_payloads,
df075fee 83 unsigned int protocol_size)
31ef9134 84{
9a738ad1 85 if (process_ctx_payloads == NULL)
df075fee
TS
86 return -EINVAL;
87
88 s->protocol = kzalloc(protocol_size, GFP_KERNEL);
89 if (!s->protocol)
90 return -ENOMEM;
91
c6f224dc 92 s->unit = unit;
3ff7e8f0 93 s->direction = dir;
31ef9134
CL
94 s->flags = flags;
95 s->context = ERR_PTR(-1);
96 mutex_init(&s->mutex);
76fb8789 97 tasklet_init(&s->period_tasklet, pcm_period_tasklet, (unsigned long)s);
ec00f5e4 98 s->packet_index = 0;
31ef9134 99
7b3b0d85
TS
100 init_waitqueue_head(&s->callback_wait);
101 s->callbacked = false;
7b3b0d85 102
5955815e 103 s->fmt = fmt;
9a738ad1 104 s->process_ctx_payloads = process_ctx_payloads;
414ba022 105
3baf3053
TS
106 if (dir == AMDTP_OUT_STREAM)
107 s->ctx_data.rx.syt_override = -1;
108
31ef9134
CL
109 return 0;
110}
be4a2894 111EXPORT_SYMBOL(amdtp_stream_init);
31ef9134
CL
112
113/**
be4a2894
TS
114 * amdtp_stream_destroy - free stream resources
115 * @s: the AMDTP stream to destroy
31ef9134 116 */
be4a2894 117void amdtp_stream_destroy(struct amdtp_stream *s)
31ef9134 118{
44c376b9
TS
119 /* Not initialized. */
120 if (s->protocol == NULL)
121 return;
122
be4a2894 123 WARN_ON(amdtp_stream_running(s));
df075fee 124 kfree(s->protocol);
31ef9134 125 mutex_destroy(&s->mutex);
31ef9134 126}
be4a2894 127EXPORT_SYMBOL(amdtp_stream_destroy);
31ef9134 128
c5280e99 129const unsigned int amdtp_syt_intervals[CIP_SFC_COUNT] = {
a7304e3b
CL
130 [CIP_SFC_32000] = 8,
131 [CIP_SFC_44100] = 8,
132 [CIP_SFC_48000] = 8,
133 [CIP_SFC_88200] = 16,
134 [CIP_SFC_96000] = 16,
135 [CIP_SFC_176400] = 32,
136 [CIP_SFC_192000] = 32,
137};
138EXPORT_SYMBOL(amdtp_syt_intervals);
139
f9503a68 140const unsigned int amdtp_rate_table[CIP_SFC_COUNT] = {
1017abed
TS
141 [CIP_SFC_32000] = 32000,
142 [CIP_SFC_44100] = 44100,
143 [CIP_SFC_48000] = 48000,
144 [CIP_SFC_88200] = 88200,
145 [CIP_SFC_96000] = 96000,
146 [CIP_SFC_176400] = 176400,
147 [CIP_SFC_192000] = 192000,
148};
149EXPORT_SYMBOL(amdtp_rate_table);
150
59502295
TS
151static int apply_constraint_to_size(struct snd_pcm_hw_params *params,
152 struct snd_pcm_hw_rule *rule)
153{
154 struct snd_interval *s = hw_param_interval(params, rule->var);
155 const struct snd_interval *r =
156 hw_param_interval_c(params, SNDRV_PCM_HW_PARAM_RATE);
826b5de9
TS
157 struct snd_interval t = {0};
158 unsigned int step = 0;
59502295
TS
159 int i;
160
161 for (i = 0; i < CIP_SFC_COUNT; ++i) {
826b5de9
TS
162 if (snd_interval_test(r, amdtp_rate_table[i]))
163 step = max(step, amdtp_syt_intervals[i]);
59502295
TS
164 }
165
826b5de9
TS
166 t.min = roundup(s->min, step);
167 t.max = rounddown(s->max, step);
168 t.integer = 1;
59502295
TS
169
170 return snd_interval_refine(s, &t);
171}
172
7b2d99fa
TS
173/**
174 * amdtp_stream_add_pcm_hw_constraints - add hw constraints for PCM substream
175 * @s: the AMDTP stream, which must be initialized.
176 * @runtime: the PCM substream runtime
177 */
178int amdtp_stream_add_pcm_hw_constraints(struct amdtp_stream *s,
179 struct snd_pcm_runtime *runtime)
180{
55799c5a 181 struct snd_pcm_hardware *hw = &runtime->hw;
99921ec6
TS
182 unsigned int ctx_header_size;
183 unsigned int maximum_usec_per_period;
7b2d99fa
TS
184 int err;
185
55799c5a
TS
186 hw->info = SNDRV_PCM_INFO_BATCH |
187 SNDRV_PCM_INFO_BLOCK_TRANSFER |
188 SNDRV_PCM_INFO_INTERLEAVED |
189 SNDRV_PCM_INFO_JOINT_DUPLEX |
190 SNDRV_PCM_INFO_MMAP |
191 SNDRV_PCM_INFO_MMAP_VALID;
192
193 /* SNDRV_PCM_INFO_BATCH */
194 hw->periods_min = 2;
195 hw->periods_max = UINT_MAX;
196
197 /* bytes for a frame */
198 hw->period_bytes_min = 4 * hw->channels_max;
199
200 /* Just to prevent from allocating much pages. */
201 hw->period_bytes_max = hw->period_bytes_min * 2048;
202 hw->buffer_bytes_max = hw->period_bytes_max * hw->periods_min;
203
99921ec6
TS
204 // Linux driver for 1394 OHCI controller voluntarily flushes isoc
205 // context when total size of accumulated context header reaches
206 // PAGE_SIZE. This kicks tasklet for the isoc context and brings
207 // callback in the middle of scheduled interrupts.
208 // Although AMDTP streams in the same domain use the same events per
209 // IRQ, use the largest size of context header between IT/IR contexts.
210 // Here, use the value of context header in IR context is for both
211 // contexts.
212 if (!(s->flags & CIP_NO_HEADER))
213 ctx_header_size = IR_CTX_HEADER_SIZE_CIP;
214 else
215 ctx_header_size = IR_CTX_HEADER_SIZE_NO_CIP;
216 maximum_usec_per_period = USEC_PER_SEC * PAGE_SIZE /
217 CYCLES_PER_SECOND / ctx_header_size;
218
f706df4f
TS
219 // In IEC 61883-6, one isoc packet can transfer events up to the value
220 // of syt interval. This comes from the interval of isoc cycle. As 1394
221 // OHCI controller can generate hardware IRQ per isoc packet, the
222 // interval is 125 usec.
223 // However, there are two ways of transmission in IEC 61883-6; blocking
224 // and non-blocking modes. In blocking mode, the sequence of isoc packet
225 // includes 'empty' or 'NODATA' packets which include no event. In
226 // non-blocking mode, the number of events per packet is variable up to
227 // the syt interval.
228 // Due to the above protocol design, the minimum PCM frames per
229 // interrupt should be double of the value of syt interval, thus it is
230 // 250 usec.
7b2d99fa
TS
231 err = snd_pcm_hw_constraint_minmax(runtime,
232 SNDRV_PCM_HW_PARAM_PERIOD_TIME,
f706df4f 233 250, maximum_usec_per_period);
7b2d99fa
TS
234 if (err < 0)
235 goto end;
236
237 /* Non-Blocking stream has no more constraints */
238 if (!(s->flags & CIP_BLOCKING))
239 goto end;
240
241 /*
242 * One AMDTP packet can include some frames. In blocking mode, the
243 * number equals to SYT_INTERVAL. So the number is 8, 16 or 32,
244 * depending on its sampling rate. For accurate period interrupt, it's
ce991981 245 * preferrable to align period/buffer sizes to current SYT_INTERVAL.
7b2d99fa 246 */
59502295
TS
247 err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
248 apply_constraint_to_size, NULL,
826b5de9 249 SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
59502295
TS
250 SNDRV_PCM_HW_PARAM_RATE, -1);
251 if (err < 0)
252 goto end;
59502295
TS
253 err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
254 apply_constraint_to_size, NULL,
826b5de9 255 SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
59502295
TS
256 SNDRV_PCM_HW_PARAM_RATE, -1);
257 if (err < 0)
258 goto end;
7b2d99fa
TS
259end:
260 return err;
261}
262EXPORT_SYMBOL(amdtp_stream_add_pcm_hw_constraints);
263
31ef9134 264/**
be4a2894
TS
265 * amdtp_stream_set_parameters - set stream parameters
266 * @s: the AMDTP stream to configure
31ef9134 267 * @rate: the sample rate
df075fee 268 * @data_block_quadlets: the size of a data block in quadlet unit
31ef9134 269 *
a7304e3b 270 * The parameters must be set before the stream is started, and must not be
31ef9134
CL
271 * changed while the stream is running.
272 */
df075fee
TS
273int amdtp_stream_set_parameters(struct amdtp_stream *s, unsigned int rate,
274 unsigned int data_block_quadlets)
31ef9134 275{
df075fee 276 unsigned int sfc;
31ef9134 277
547e631c 278 for (sfc = 0; sfc < ARRAY_SIZE(amdtp_rate_table); ++sfc) {
1017abed 279 if (amdtp_rate_table[sfc] == rate)
547e631c
TS
280 break;
281 }
282 if (sfc == ARRAY_SIZE(amdtp_rate_table))
283 return -EINVAL;
e84d15f6 284
e84d15f6 285 s->sfc = sfc;
df075fee 286 s->data_block_quadlets = data_block_quadlets;
a7304e3b 287 s->syt_interval = amdtp_syt_intervals[sfc];
e84d15f6 288
d3d10a4a
TS
289 // default buffering in the device.
290 if (s->direction == AMDTP_OUT_STREAM) {
291 s->ctx_data.rx.transfer_delay =
292 TRANSFER_DELAY_TICKS - TICKS_PER_CYCLE;
293
294 if (s->flags & CIP_BLOCKING) {
295 // additional buffering needed to adjust for no-data
296 // packets.
297 s->ctx_data.rx.transfer_delay +=
298 TICKS_PER_SECOND * s->syt_interval / rate;
299 }
300 }
77d2a8a4 301
547e631c 302 return 0;
31ef9134 303}
be4a2894 304EXPORT_SYMBOL(amdtp_stream_set_parameters);
31ef9134
CL
305
306/**
be4a2894
TS
307 * amdtp_stream_get_max_payload - get the stream's packet size
308 * @s: the AMDTP stream
31ef9134
CL
309 *
310 * This function must not be called before the stream has been configured
be4a2894 311 * with amdtp_stream_set_parameters().
31ef9134 312 */
be4a2894 313unsigned int amdtp_stream_get_max_payload(struct amdtp_stream *s)
31ef9134 314{
a2064710 315 unsigned int multiplier = 1;
07ea238c 316 unsigned int cip_header_size = 0;
a2064710
TS
317
318 if (s->flags & CIP_JUMBO_PAYLOAD)
319 multiplier = 5;
3b196c39 320 if (!(s->flags & CIP_NO_HEADER))
07ea238c 321 cip_header_size = sizeof(__be32) * 2;
a2064710 322
07ea238c
TS
323 return cip_header_size +
324 s->syt_interval * s->data_block_quadlets * sizeof(__be32) * multiplier;
31ef9134 325}
be4a2894 326EXPORT_SYMBOL(amdtp_stream_get_max_payload);
31ef9134 327
76fb8789 328/**
be4a2894
TS
329 * amdtp_stream_pcm_prepare - prepare PCM device for running
330 * @s: the AMDTP stream
76fb8789
CL
331 *
332 * This function should be called from the PCM device's .prepare callback.
333 */
be4a2894 334void amdtp_stream_pcm_prepare(struct amdtp_stream *s)
76fb8789
CL
335{
336 tasklet_kill(&s->period_tasklet);
337 s->pcm_buffer_pointer = 0;
338 s->pcm_period_pointer = 0;
339}
be4a2894 340EXPORT_SYMBOL(amdtp_stream_pcm_prepare);
76fb8789 341
875be091
TS
342static unsigned int calculate_data_blocks(struct amdtp_stream *s,
343 unsigned int syt)
31ef9134
CL
344{
345 unsigned int phase, data_blocks;
346
875be091
TS
347 /* Blocking mode. */
348 if (s->flags & CIP_BLOCKING) {
349 /* This module generate empty packet for 'no data'. */
350 if (syt == CIP_SYT_NO_INFO)
351 data_blocks = 0;
352 else
353 data_blocks = s->syt_interval;
354 /* Non-blocking mode. */
31ef9134 355 } else {
875be091 356 if (!cip_sfc_is_base_44100(s->sfc)) {
d3d10a4a
TS
357 // Sample_rate / 8000 is an integer, and precomputed.
358 data_blocks = s->ctx_data.rx.data_block_state;
875be091 359 } else {
d3d10a4a 360 phase = s->ctx_data.rx.data_block_state;
31ef9134
CL
361
362 /*
363 * This calculates the number of data blocks per packet so that
364 * 1) the overall rate is correct and exactly synchronized to
365 * the bus clock, and
366 * 2) packets with a rounded-up number of blocks occur as early
367 * as possible in the sequence (to prevent underruns of the
368 * device's buffer).
369 */
875be091
TS
370 if (s->sfc == CIP_SFC_44100)
371 /* 6 6 5 6 5 6 5 ... */
372 data_blocks = 5 + ((phase & 1) ^
373 (phase == 0 || phase >= 40));
374 else
375 /* 12 11 11 11 11 ... or 23 22 22 22 22 ... */
376 data_blocks = 11 * (s->sfc >> 1) + (phase == 0);
377 if (++phase >= (80 >> (s->sfc >> 1)))
378 phase = 0;
d3d10a4a 379 s->ctx_data.rx.data_block_state = phase;
875be091 380 }
31ef9134
CL
381 }
382
383 return data_blocks;
384}
385
83cfb5c5 386static unsigned int calculate_syt_offset(struct amdtp_stream *s)
31ef9134 387{
83cfb5c5 388 unsigned int syt_offset, phase, index;
31ef9134 389
d3d10a4a 390 if (s->ctx_data.rx.last_syt_offset < TICKS_PER_CYCLE) {
31ef9134 391 if (!cip_sfc_is_base_44100(s->sfc))
d3d10a4a
TS
392 syt_offset = s->ctx_data.rx.last_syt_offset +
393 s->ctx_data.rx.syt_offset_state;
31ef9134
CL
394 else {
395 /*
396 * The time, in ticks, of the n'th SYT_INTERVAL sample is:
397 * n * SYT_INTERVAL * 24576000 / sample_rate
398 * Modulo TICKS_PER_CYCLE, the difference between successive
399 * elements is about 1386.23. Rounding the results of this
400 * formula to the SYT precision results in a sequence of
401 * differences that begins with:
402 * 1386 1386 1387 1386 1386 1386 1387 1386 1386 1386 1387 ...
403 * This code generates _exactly_ the same sequence.
404 */
d3d10a4a 405 phase = s->ctx_data.rx.syt_offset_state;
31ef9134 406 index = phase % 13;
d3d10a4a 407 syt_offset = s->ctx_data.rx.last_syt_offset;
31ef9134
CL
408 syt_offset += 1386 + ((index && !(index & 3)) ||
409 phase == 146);
410 if (++phase >= 147)
411 phase = 0;
d3d10a4a 412 s->ctx_data.rx.syt_offset_state = phase;
31ef9134
CL
413 }
414 } else
d3d10a4a
TS
415 syt_offset = s->ctx_data.rx.last_syt_offset - TICKS_PER_CYCLE;
416 s->ctx_data.rx.last_syt_offset = syt_offset;
31ef9134 417
83cfb5c5
TS
418 if (syt_offset >= TICKS_PER_CYCLE)
419 syt_offset = CIP_SYT_NO_INFO;
31ef9134 420
83cfb5c5 421 return syt_offset;
31ef9134
CL
422}
423
4b7da117
TS
424static void update_pcm_pointers(struct amdtp_stream *s,
425 struct snd_pcm_substream *pcm,
426 unsigned int frames)
65845f29
TS
427{
428 unsigned int ptr;
429
4b7da117
TS
430 ptr = s->pcm_buffer_pointer + frames;
431 if (ptr >= pcm->runtime->buffer_size)
432 ptr -= pcm->runtime->buffer_size;
6aa7de05 433 WRITE_ONCE(s->pcm_buffer_pointer, ptr);
4b7da117
TS
434
435 s->pcm_period_pointer += frames;
436 if (s->pcm_period_pointer >= pcm->runtime->period_size) {
437 s->pcm_period_pointer -= pcm->runtime->period_size;
4b7da117
TS
438 tasklet_hi_schedule(&s->period_tasklet);
439 }
440}
441
442static void pcm_period_tasklet(unsigned long data)
443{
444 struct amdtp_stream *s = (void *)data;
6aa7de05 445 struct snd_pcm_substream *pcm = READ_ONCE(s->pcm);
4b7da117
TS
446
447 if (pcm)
448 snd_pcm_period_elapsed(pcm);
449}
450
e229853d
TS
451static int queue_packet(struct amdtp_stream *s, struct fw_iso_packet *params,
452 bool sched_irq)
4b7da117 453{
6007bf54 454 int err;
df9160b9 455
e229853d 456 params->interrupt = sched_irq;
6007bf54
TS
457 params->tag = s->tag;
458 params->sy = 0;
df9160b9 459
6007bf54 460 err = fw_iso_context_queue(s->context, params, &s->buffer.iso_buffer,
4b7da117
TS
461 s->buffer.packets[s->packet_index].offset);
462 if (err < 0) {
463 dev_err(&s->unit->device, "queueing error: %d\n", err);
464 goto end;
465 }
466
a0e02331 467 if (++s->packet_index >= s->queue_size)
4b7da117
TS
468 s->packet_index = 0;
469end:
470 return err;
471}
472
473static inline int queue_out_packet(struct amdtp_stream *s,
e229853d 474 struct fw_iso_packet *params, bool sched_irq)
4b7da117 475{
b18f0cfa
TS
476 params->skip =
477 !!(params->header_length == 0 && params->payload_length == 0);
e229853d 478 return queue_packet(s, params, sched_irq);
4b7da117
TS
479}
480
6007bf54 481static inline int queue_in_packet(struct amdtp_stream *s,
60dd4929 482 struct fw_iso_packet *params)
2b3fc456 483{
6007bf54
TS
484 // Queue one packet for IR context.
485 params->header_length = s->ctx_data.tx.ctx_header_size;
486 params->payload_length = s->ctx_data.tx.max_ctx_payload_length;
487 params->skip = false;
60dd4929 488 return queue_packet(s, params, false);
2b3fc456
TS
489}
490
252219c7 491static void generate_cip_header(struct amdtp_stream *s, __be32 cip_header[2],
860d798c 492 unsigned int data_block_counter, unsigned int syt)
252219c7
TS
493{
494 cip_header[0] = cpu_to_be32(READ_ONCE(s->source_node_id_field) |
495 (s->data_block_quadlets << CIP_DBS_SHIFT) |
496 ((s->sph << CIP_SPH_SHIFT) & CIP_SPH_MASK) |
860d798c 497 data_block_counter);
252219c7
TS
498 cip_header[1] = cpu_to_be32(CIP_EOH |
499 ((s->fmt << CIP_FMT_SHIFT) & CIP_FMT_MASK) |
500 ((s->ctx_data.rx.fdf << CIP_FDF_SHIFT) & CIP_FDF_MASK) |
501 (syt & CIP_SYT_MASK));
502}
503
6bc1a269
TS
504static void build_it_pkt_header(struct amdtp_stream *s, unsigned int cycle,
505 struct fw_iso_packet *params,
860d798c
TS
506 unsigned int data_blocks,
507 unsigned int data_block_counter,
508 unsigned int syt, unsigned int index)
31ef9134 509{
0ebf3ceb 510 unsigned int payload_length;
16be4589 511 __be32 *cip_header;
20e44577 512
0ebf3ceb
TS
513 payload_length = data_blocks * sizeof(__be32) * s->data_block_quadlets;
514 params->payload_length = payload_length;
515
b18f0cfa 516 if (!(s->flags & CIP_NO_HEADER)) {
6bc1a269 517 cip_header = (__be32 *)params->header;
860d798c 518 generate_cip_header(s, cip_header, data_block_counter, syt);
6bc1a269 519 params->header_length = 2 * sizeof(__be32);
0ebf3ceb 520 payload_length += params->header_length;
b18f0cfa
TS
521 } else {
522 cip_header = NULL;
523 }
31ef9134 524
213fa989 525 trace_amdtp_packet(s, cycle, cip_header, payload_length, data_blocks,
860d798c 526 data_block_counter, index);
3b196c39
TS
527}
528
e335425b
TS
529static int check_cip_header(struct amdtp_stream *s, const __be32 *buf,
530 unsigned int payload_length,
a35463d1
TS
531 unsigned int *data_blocks,
532 unsigned int *data_block_counter, unsigned int *syt)
2b3fc456
TS
533{
534 u32 cip_header[2];
e335425b
TS
535 unsigned int sph;
536 unsigned int fmt;
537 unsigned int fdf;
a35463d1 538 unsigned int dbc;
c8bdf49b 539 bool lost;
2b3fc456 540
e335425b
TS
541 cip_header[0] = be32_to_cpu(buf[0]);
542 cip_header[1] = be32_to_cpu(buf[1]);
2b3fc456
TS
543
544 /*
545 * This module supports 'Two-quadlet CIP header with SYT field'.
77d2a8a4 546 * For convenience, also check FMT field is AM824 or not.
2b3fc456 547 */
2128f78f
TS
548 if ((((cip_header[0] & CIP_EOH_MASK) == CIP_EOH) ||
549 ((cip_header[1] & CIP_EOH_MASK) != CIP_EOH)) &&
550 (!(s->flags & CIP_HEADER_WITHOUT_EOH))) {
2b3fc456
TS
551 dev_info_ratelimited(&s->unit->device,
552 "Invalid CIP header for AMDTP: %08X:%08X\n",
553 cip_header[0], cip_header[1]);
e335425b 554 return -EAGAIN;
2b3fc456
TS
555 }
556
414ba022 557 /* Check valid protocol or not. */
9863874f 558 sph = (cip_header[0] & CIP_SPH_MASK) >> CIP_SPH_SHIFT;
414ba022 559 fmt = (cip_header[1] & CIP_FMT_MASK) >> CIP_FMT_SHIFT;
9863874f 560 if (sph != s->sph || fmt != s->fmt) {
2a7e1713
TS
561 dev_info_ratelimited(&s->unit->device,
562 "Detect unexpected protocol: %08x %08x\n",
563 cip_header[0], cip_header[1]);
e335425b 564 return -EAGAIN;
414ba022
TS
565 }
566
2b3fc456 567 /* Calculate data blocks */
414ba022 568 fdf = (cip_header[1] & CIP_FDF_MASK) >> CIP_FDF_SHIFT;
e335425b 569 if (payload_length < sizeof(__be32) * 2 ||
414ba022 570 (fmt == CIP_FMT_AM && fdf == AMDTP_FDF_NO_DATA)) {
e335425b 571 *data_blocks = 0;
2b3fc456 572 } else {
e335425b
TS
573 unsigned int data_block_quadlets =
574 (cip_header[0] & CIP_DBS_MASK) >> CIP_DBS_SHIFT;
2b3fc456
TS
575 /* avoid division by zero */
576 if (data_block_quadlets == 0) {
12e0f438 577 dev_err(&s->unit->device,
2b3fc456
TS
578 "Detect invalid value in dbs field: %08X\n",
579 cip_header[0]);
a9007054 580 return -EPROTO;
2b3fc456 581 }
69702239
TS
582 if (s->flags & CIP_WRONG_DBS)
583 data_block_quadlets = s->data_block_quadlets;
2b3fc456 584
e335425b 585 *data_blocks = (payload_length / sizeof(__be32) - 2) /
ff0fb5aa 586 data_block_quadlets;
2b3fc456
TS
587 }
588
589 /* Check data block counter continuity */
a35463d1 590 dbc = cip_header[0] & CIP_DBC_MASK;
e335425b 591 if (*data_blocks == 0 && (s->flags & CIP_EMPTY_HAS_WRONG_DBC) &&
a35463d1
TS
592 *data_block_counter != UINT_MAX)
593 dbc = *data_block_counter;
9d59124c 594
a35463d1
TS
595 if ((dbc == 0x00 && (s->flags & CIP_SKIP_DBC_ZERO_CHECK)) ||
596 *data_block_counter == UINT_MAX) {
b84b1a27
TS
597 lost = false;
598 } else if (!(s->flags & CIP_DBC_IS_END_EVENT)) {
a35463d1 599 lost = dbc != *data_block_counter;
d9cd0065 600 } else {
e335425b
TS
601 unsigned int dbc_interval;
602
603 if (*data_blocks > 0 && s->ctx_data.tx.dbc_interval > 0)
d3d10a4a 604 dbc_interval = s->ctx_data.tx.dbc_interval;
d9cd0065 605 else
e335425b 606 dbc_interval = *data_blocks;
d9cd0065 607
a35463d1 608 lost = dbc != ((*data_block_counter + dbc_interval) & 0xff);
d9cd0065 609 }
c8bdf49b
TS
610
611 if (lost) {
12e0f438
TS
612 dev_err(&s->unit->device,
613 "Detect discontinuity of CIP: %02X %02X\n",
a35463d1 614 *data_block_counter, dbc);
6fc6b9ce 615 return -EIO;
2b3fc456
TS
616 }
617
753e7179
TS
618 *data_block_counter = dbc;
619
e335425b 620 *syt = cip_header[1] & CIP_SYT_MASK;
2b3fc456 621
e335425b
TS
622 return 0;
623}
624
98e3e43b
TS
625static int parse_ir_ctx_header(struct amdtp_stream *s, unsigned int cycle,
626 const __be32 *ctx_header,
627 unsigned int *payload_length,
a35463d1
TS
628 unsigned int *data_blocks,
629 unsigned int *data_block_counter,
630 unsigned int *syt, unsigned int index)
e335425b 631{
f11453c7 632 const __be32 *cip_header;
e335425b
TS
633 int err;
634
98e3e43b
TS
635 *payload_length = be32_to_cpu(ctx_header[0]) >> ISO_DATA_LENGTH_SHIFT;
636 if (*payload_length > s->ctx_data.tx.ctx_header_size +
f11453c7 637 s->ctx_data.tx.max_ctx_payload_length) {
e335425b
TS
638 dev_err(&s->unit->device,
639 "Detect jumbo payload: %04x %04x\n",
98e3e43b 640 *payload_length, s->ctx_data.tx.max_ctx_payload_length);
e335425b
TS
641 return -EIO;
642 }
643
947b437e 644 if (!(s->flags & CIP_NO_HEADER)) {
98e3e43b
TS
645 cip_header = ctx_header + 2;
646 err = check_cip_header(s, cip_header, *payload_length,
a35463d1 647 data_blocks, data_block_counter, syt);
b8b0e24c
TS
648 if (err < 0)
649 return err;
947b437e
TS
650 } else {
651 cip_header = NULL;
76864868 652 err = 0;
98e3e43b
TS
653 *data_blocks = *payload_length / sizeof(__be32) /
654 s->data_block_quadlets;
655 *syt = 0;
7fbf9096 656
a35463d1
TS
657 if (*data_block_counter == UINT_MAX)
658 *data_block_counter = 0;
e335425b
TS
659 }
660
98e3e43b 661 trace_amdtp_packet(s, cycle, cip_header, *payload_length, *data_blocks,
a35463d1 662 *data_block_counter, index);
e335425b 663
76864868 664 return err;
2b3fc456
TS
665}
666
26cd1e58
TS
667// In CYCLE_TIMER register of IEEE 1394, 7 bits are used to represent second. On
668// the other hand, in DMA descriptors of 1394 OHCI, 3 bits are used to represent
669// it. Thus, via Linux firewire subsystem, we can get the 3 bits for second.
670static inline u32 compute_cycle_count(__be32 ctx_header_tstamp)
73fc7f08 671{
26cd1e58 672 u32 tstamp = be32_to_cpu(ctx_header_tstamp) & HEADER_TSTAMP_MASK;
73fc7f08
TS
673 return (((tstamp >> 13) & 0x07) * 8000) + (tstamp & 0x1fff);
674}
675
676static inline u32 increment_cycle_count(u32 cycle, unsigned int addend)
677{
678 cycle += addend;
10aa8e4a
TS
679 if (cycle >= OHCI_MAX_SECOND * CYCLES_PER_SECOND)
680 cycle -= OHCI_MAX_SECOND * CYCLES_PER_SECOND;
73fc7f08
TS
681 return cycle;
682}
683
26cd1e58 684// Align to actual cycle count for the packet which is going to be scheduled.
a0e02331
TS
685// This module queued the same number of isochronous cycle as the size of queue
686// to kip isochronous cycle, therefore it's OK to just increment the cycle by
687// the size of queue for scheduled cycle.
688static inline u32 compute_it_cycle(const __be32 ctx_header_tstamp,
689 unsigned int queue_size)
26cd1e58
TS
690{
691 u32 cycle = compute_cycle_count(ctx_header_tstamp);
a0e02331 692 return increment_cycle_count(cycle, queue_size);
26cd1e58
TS
693}
694
753e7179
TS
695static int generate_device_pkt_descs(struct amdtp_stream *s,
696 struct pkt_desc *descs,
697 const __be32 *ctx_header,
698 unsigned int packets)
699{
700 unsigned int dbc = s->data_block_counter;
701 int i;
702 int err;
703
704 for (i = 0; i < packets; ++i) {
705 struct pkt_desc *desc = descs + i;
a0e02331 706 unsigned int index = (s->packet_index + i) % s->queue_size;
753e7179
TS
707 unsigned int cycle;
708 unsigned int payload_length;
709 unsigned int data_blocks;
710 unsigned int syt;
711
712 cycle = compute_cycle_count(ctx_header[1]);
713
714 err = parse_ir_ctx_header(s, cycle, ctx_header, &payload_length,
715 &data_blocks, &dbc, &syt, i);
716 if (err < 0)
717 return err;
718
719 desc->cycle = cycle;
720 desc->syt = syt;
721 desc->data_blocks = data_blocks;
722 desc->data_block_counter = dbc;
723 desc->ctx_payload = s->buffer.packets[index].buffer;
724
725 if (!(s->flags & CIP_DBC_IS_END_EVENT))
726 dbc = (dbc + desc->data_blocks) & 0xff;
727
728 ctx_header +=
729 s->ctx_data.tx.ctx_header_size / sizeof(*ctx_header);
730 }
731
732 s->data_block_counter = dbc;
733
734 return 0;
735}
736
83cfb5c5
TS
737static unsigned int compute_syt(unsigned int syt_offset, unsigned int cycle,
738 unsigned int transfer_delay)
739{
740 unsigned int syt;
741
742 syt_offset += transfer_delay;
743 syt = ((cycle + syt_offset / TICKS_PER_CYCLE) << 12) |
744 (syt_offset % TICKS_PER_CYCLE);
745 return syt & CIP_SYT_MASK;
746}
747
f4f6ae7b
TS
748static void generate_ideal_pkt_descs(struct amdtp_stream *s,
749 struct pkt_desc *descs,
750 const __be32 *ctx_header,
751 unsigned int packets)
752{
753 unsigned int dbc = s->data_block_counter;
754 int i;
755
756 for (i = 0; i < packets; ++i) {
757 struct pkt_desc *desc = descs + i;
a0e02331 758 unsigned int index = (s->packet_index + i) % s->queue_size;
83cfb5c5 759 unsigned int syt_offset;
f4f6ae7b 760
a0e02331 761 desc->cycle = compute_it_cycle(*ctx_header, s->queue_size);
83cfb5c5
TS
762 syt_offset = calculate_syt_offset(s);
763 if (syt_offset != CIP_SYT_NO_INFO) {
764 desc->syt = compute_syt(syt_offset, desc->cycle,
765 s->ctx_data.rx.transfer_delay);
766 } else {
767 desc->syt = syt_offset;
768 }
f4f6ae7b
TS
769 desc->data_blocks = calculate_data_blocks(s, desc->syt);
770
771 if (s->flags & CIP_DBC_IS_END_EVENT)
772 dbc = (dbc + desc->data_blocks) & 0xff;
773
774 desc->data_block_counter = dbc;
775
776 if (!(s->flags & CIP_DBC_IS_END_EVENT))
777 dbc = (dbc + desc->data_blocks) & 0xff;
778
779 desc->ctx_payload = s->buffer.packets[index].buffer;
780
781 ++ctx_header;
782 }
783
784 s->data_block_counter = dbc;
785}
786
fce9b013
TS
787static inline void cancel_stream(struct amdtp_stream *s)
788{
789 s->packet_index = -1;
790 if (in_interrupt())
791 amdtp_stream_pcm_abort(s);
792 WRITE_ONCE(s->pcm_buffer_pointer, SNDRV_PCM_POS_XRUN);
793}
794
0f5cfcb2
TS
795static void process_ctx_payloads(struct amdtp_stream *s,
796 const struct pkt_desc *descs,
797 unsigned int packets)
31ef9134 798{
9a738ad1
TS
799 struct snd_pcm_substream *pcm;
800 unsigned int pcm_frames;
5e2ece0f 801
9a738ad1
TS
802 pcm = READ_ONCE(s->pcm);
803 pcm_frames = s->process_ctx_payloads(s, descs, packets, pcm);
804 if (pcm)
805 update_pcm_pointers(s, pcm, pcm_frames);
0f5cfcb2
TS
806}
807
808static void out_stream_callback(struct fw_iso_context *context, u32 tstamp,
809 size_t header_length, void *header,
810 void *private_data)
811{
812 struct amdtp_stream *s = private_data;
813 const __be32 *ctx_header = header;
60dd4929
TS
814 unsigned int events_per_period = s->ctx_data.rx.events_per_period;
815 unsigned int event_count = s->ctx_data.rx.event_count;
a0e02331 816 unsigned int packets;
0f5cfcb2
TS
817 int i;
818
819 if (s->packet_index < 0)
820 return;
821
a0e02331
TS
822 // Calculate the number of packets in buffer and check XRUN.
823 packets = header_length / sizeof(*ctx_header);
824
0f5cfcb2
TS
825 generate_ideal_pkt_descs(s, s->pkt_descs, ctx_header, packets);
826
827 process_ctx_payloads(s, s->pkt_descs, packets);
5e2ece0f
TS
828
829 for (i = 0; i < packets; ++i) {
830 const struct pkt_desc *desc = s->pkt_descs + i;
f4f6ae7b 831 unsigned int syt;
6bc1a269
TS
832 struct {
833 struct fw_iso_packet params;
834 __be32 header[IT_PKT_HEADER_SIZE_CIP / sizeof(__be32)];
835 } template = { {0}, {0} };
e229853d 836 bool sched_irq = false;
31ef9134 837
f4f6ae7b
TS
838 if (s->ctx_data.rx.syt_override < 0)
839 syt = desc->syt;
840 else
3baf3053
TS
841 syt = s->ctx_data.rx.syt_override;
842
f4f6ae7b
TS
843 build_it_pkt_header(s, desc->cycle, &template.params,
844 desc->data_blocks, desc->data_block_counter,
845 syt, i);
6bc1a269 846
2472cfb3 847 if (s == s->domain->irq_target) {
60dd4929
TS
848 event_count += desc->data_blocks;
849 if (event_count >= events_per_period) {
850 event_count -= events_per_period;
851 sched_irq = true;
852 }
e229853d
TS
853 }
854
855 if (queue_out_packet(s, &template.params, sched_irq) < 0) {
fce9b013 856 cancel_stream(s);
a4103bd7
TS
857 return;
858 }
ccccad86 859 }
a4103bd7 860
60dd4929 861 s->ctx_data.rx.event_count = event_count;
31ef9134
CL
862}
863
73fc7f08 864static void in_stream_callback(struct fw_iso_context *context, u32 tstamp,
2b3fc456
TS
865 size_t header_length, void *header,
866 void *private_data)
867{
868 struct amdtp_stream *s = private_data;
cc4f8e91 869 __be32 *ctx_header = header;
e229853d 870 unsigned int packets;
753e7179
TS
871 int i;
872 int err;
2b3fc456 873
a4103bd7
TS
874 if (s->packet_index < 0)
875 return;
876
a0e02331 877 // Calculate the number of packets in buffer and check XRUN.
d3d10a4a 878 packets = header_length / s->ctx_data.tx.ctx_header_size;
f90e2ded 879
753e7179
TS
880 err = generate_device_pkt_descs(s, s->pkt_descs, ctx_header, packets);
881 if (err < 0) {
882 if (err != -EAGAIN) {
883 cancel_stream(s);
884 return;
885 }
5e2ece0f 886 } else {
0f5cfcb2 887 process_ctx_payloads(s, s->pkt_descs, packets);
5e2ece0f
TS
888 }
889
890 for (i = 0; i < packets; ++i) {
891 struct fw_iso_packet params = {0};
2b3fc456 892
60dd4929 893 if (queue_in_packet(s, &params) < 0) {
753e7179
TS
894 cancel_stream(s);
895 return;
896 }
7b3b0d85 897 }
60dd4929
TS
898}
899
2472cfb3
TS
900static void irq_target_callback(struct fw_iso_context *context, u32 tstamp,
901 size_t header_length, void *header,
902 void *private_data)
60dd4929 903{
2472cfb3
TS
904 struct amdtp_stream *irq_target = private_data;
905 struct amdtp_domain *d = irq_target->domain;
60dd4929
TS
906 struct amdtp_stream *s;
907
908 out_stream_callback(context, tstamp, header_length, header, irq_target);
909 if (amdtp_streaming_error(irq_target))
910 goto error;
7b3b0d85 911
60dd4929
TS
912 list_for_each_entry(s, &d->streams, list) {
913 if (s != irq_target && amdtp_stream_running(s)) {
914 fw_iso_context_flush_completions(s->context);
915 if (amdtp_streaming_error(s))
916 goto error;
917 }
918 }
919
920 return;
921error:
922 if (amdtp_stream_running(irq_target))
923 cancel_stream(irq_target);
924
925 list_for_each_entry(s, &d->streams, list) {
926 if (amdtp_stream_running(s))
927 cancel_stream(s);
928 }
2b3fc456
TS
929}
930
60dd4929 931// this is executed one time.
7b3b0d85 932static void amdtp_stream_first_callback(struct fw_iso_context *context,
73fc7f08 933 u32 tstamp, size_t header_length,
7b3b0d85
TS
934 void *header, void *private_data)
935{
936 struct amdtp_stream *s = private_data;
26cd1e58 937 const __be32 *ctx_header = header;
a04513f8 938 u32 cycle;
7b3b0d85
TS
939
940 /*
941 * For in-stream, first packet has come.
942 * For out-stream, prepared to transmit first packet
943 */
944 s->callbacked = true;
945 wake_up(&s->callback_wait);
946
a04513f8 947 if (s->direction == AMDTP_IN_STREAM) {
26cd1e58 948 cycle = compute_cycle_count(ctx_header[1]);
cc4f8e91 949
7b3b0d85 950 context->callback.sc = in_stream_callback;
a04513f8 951 } else {
a0e02331 952 cycle = compute_it_cycle(*ctx_header, s->queue_size);
26cd1e58 953
2472cfb3
TS
954 if (s == s->domain->irq_target)
955 context->callback.sc = irq_target_callback;
956 else
957 context->callback.sc = out_stream_callback;
a04513f8
TS
958 }
959
960 s->start_cycle = cycle;
7b3b0d85 961
73fc7f08 962 context->callback.sc(context, tstamp, header_length, header, s);
7b3b0d85
TS
963}
964
31ef9134 965/**
be4a2894
TS
966 * amdtp_stream_start - start transferring packets
967 * @s: the AMDTP stream to start
31ef9134
CL
968 * @channel: the isochronous channel on the bus
969 * @speed: firewire speed code
acfedcbe
TS
970 * @start_cycle: the isochronous cycle to start the context. Start immediately
971 * if negative value is given.
af86b0b1
TS
972 * @queue_size: The number of packets in the queue.
973 * @idle_irq_interval: the interval to queue packet during initial state.
31ef9134
CL
974 *
975 * The stream cannot be started until it has been configured with
be4a2894
TS
976 * amdtp_stream_set_parameters() and it must be started before any PCM or MIDI
977 * device can be started.
31ef9134 978 */
a0e02331 979static int amdtp_stream_start(struct amdtp_stream *s, int channel, int speed,
af86b0b1
TS
980 int start_cycle, unsigned int queue_size,
981 unsigned int idle_irq_interval)
31ef9134
CL
982{
983 static const struct {
984 unsigned int data_block;
985 unsigned int syt_offset;
d3d10a4a 986 } *entry, initial_state[] = {
31ef9134
CL
987 [CIP_SFC_32000] = { 4, 3072 },
988 [CIP_SFC_48000] = { 6, 1024 },
989 [CIP_SFC_96000] = { 12, 1024 },
990 [CIP_SFC_192000] = { 24, 1024 },
991 [CIP_SFC_44100] = { 0, 67 },
992 [CIP_SFC_88200] = { 0, 67 },
993 [CIP_SFC_176400] = { 0, 67 },
994 };
2472cfb3 995 bool is_irq_target = (s == s->domain->irq_target);
d3d10a4a 996 unsigned int ctx_header_size;
f11453c7 997 unsigned int max_ctx_payload_size;
2b3fc456 998 enum dma_data_direction dir;
7ab56645 999 int type, tag, err;
31ef9134
CL
1000
1001 mutex_lock(&s->mutex);
1002
be4a2894 1003 if (WARN_ON(amdtp_stream_running(s) ||
4b7da117 1004 (s->data_block_quadlets < 1))) {
31ef9134
CL
1005 err = -EBADFD;
1006 goto err_unlock;
1007 }
1008
d3d10a4a 1009 if (s->direction == AMDTP_IN_STREAM) {
60dd4929
TS
1010 // NOTE: IT context should be used for constant IRQ.
1011 if (is_irq_target) {
1012 err = -EINVAL;
1013 goto err_unlock;
1014 }
1015
b6bc8123 1016 s->data_block_counter = UINT_MAX;
d3d10a4a
TS
1017 } else {
1018 entry = &initial_state[s->sfc];
1019
b6bc8123 1020 s->data_block_counter = 0;
d3d10a4a
TS
1021 s->ctx_data.rx.data_block_state = entry->data_block;
1022 s->ctx_data.rx.syt_offset_state = entry->syt_offset;
1023 s->ctx_data.rx.last_syt_offset = TICKS_PER_CYCLE;
1024 }
31ef9134 1025
2b3fc456
TS
1026 /* initialize packet buffer */
1027 if (s->direction == AMDTP_IN_STREAM) {
1028 dir = DMA_FROM_DEVICE;
1029 type = FW_ISO_CONTEXT_RECEIVE;
f11453c7
TS
1030 if (!(s->flags & CIP_NO_HEADER))
1031 ctx_header_size = IR_CTX_HEADER_SIZE_CIP;
1032 else
1033 ctx_header_size = IR_CTX_HEADER_SIZE_NO_CIP;
b18f0cfa
TS
1034
1035 max_ctx_payload_size = amdtp_stream_get_max_payload(s) -
1036 ctx_header_size;
2b3fc456
TS
1037 } else {
1038 dir = DMA_TO_DEVICE;
1039 type = FW_ISO_CONTEXT_TRANSMIT;
df9160b9 1040 ctx_header_size = 0; // No effect for IT context.
f11453c7 1041
b18f0cfa
TS
1042 max_ctx_payload_size = amdtp_stream_get_max_payload(s);
1043 if (!(s->flags & CIP_NO_HEADER))
1044 max_ctx_payload_size -= IT_PKT_HEADER_SIZE_CIP;
1045 }
f11453c7 1046
af86b0b1 1047 err = iso_packets_buffer_init(&s->buffer, s->unit, queue_size,
f11453c7 1048 max_ctx_payload_size, dir);
31ef9134
CL
1049 if (err < 0)
1050 goto err_unlock;
af86b0b1 1051 s->queue_size = queue_size;
60dd4929 1052
31ef9134 1053 s->context = fw_iso_context_create(fw_parent_device(s->unit)->card,
d3d10a4a 1054 type, channel, speed, ctx_header_size,
2472cfb3 1055 amdtp_stream_first_callback, s);
31ef9134
CL
1056 if (IS_ERR(s->context)) {
1057 err = PTR_ERR(s->context);
1058 if (err == -EBUSY)
1059 dev_err(&s->unit->device,
be4a2894 1060 "no free stream on this controller\n");
31ef9134
CL
1061 goto err_buffer;
1062 }
1063
be4a2894 1064 amdtp_stream_update(s);
31ef9134 1065
d3d10a4a 1066 if (s->direction == AMDTP_IN_STREAM) {
f11453c7 1067 s->ctx_data.tx.max_ctx_payload_length = max_ctx_payload_size;
d3d10a4a
TS
1068 s->ctx_data.tx.ctx_header_size = ctx_header_size;
1069 }
52759c09 1070
3b196c39
TS
1071 if (s->flags & CIP_NO_HEADER)
1072 s->tag = TAG_NO_CIP_HEADER;
1073 else
1074 s->tag = TAG_CIP;
1075
a0e02331 1076 s->pkt_descs = kcalloc(s->queue_size, sizeof(*s->pkt_descs),
04130cf8
TS
1077 GFP_KERNEL);
1078 if (!s->pkt_descs) {
1079 err = -ENOMEM;
1080 goto err_context;
1081 }
1082
ec00f5e4 1083 s->packet_index = 0;
4b7da117 1084 do {
6007bf54 1085 struct fw_iso_packet params;
e229853d 1086
b18f0cfa 1087 if (s->direction == AMDTP_IN_STREAM) {
60dd4929 1088 err = queue_in_packet(s, &params);
b18f0cfa 1089 } else {
60dd4929
TS
1090 bool sched_irq = false;
1091
b18f0cfa
TS
1092 params.header_length = 0;
1093 params.payload_length = 0;
60dd4929
TS
1094
1095 if (is_irq_target) {
1096 sched_irq = !((s->packet_index + 1) %
1097 idle_irq_interval);
1098 }
1099
e229853d 1100 err = queue_out_packet(s, &params, sched_irq);
b18f0cfa 1101 }
4b7da117 1102 if (err < 0)
04130cf8 1103 goto err_pkt_descs;
4b7da117 1104 } while (s->packet_index > 0);
31ef9134 1105
2b3fc456 1106 /* NOTE: TAG1 matches CIP. This just affects in stream. */
7ab56645 1107 tag = FW_ISO_CONTEXT_MATCH_TAG1;
3b196c39 1108 if ((s->flags & CIP_EMPTY_WITH_TAG0) || (s->flags & CIP_NO_HEADER))
7ab56645
TS
1109 tag |= FW_ISO_CONTEXT_MATCH_TAG0;
1110
7b3b0d85 1111 s->callbacked = false;
acfedcbe 1112 err = fw_iso_context_start(s->context, start_cycle, 0, tag);
31ef9134 1113 if (err < 0)
04130cf8 1114 goto err_pkt_descs;
31ef9134
CL
1115
1116 mutex_unlock(&s->mutex);
1117
1118 return 0;
04130cf8
TS
1119err_pkt_descs:
1120 kfree(s->pkt_descs);
31ef9134
CL
1121err_context:
1122 fw_iso_context_destroy(s->context);
1123 s->context = ERR_PTR(-1);
1124err_buffer:
1125 iso_packets_buffer_destroy(&s->buffer, s->unit);
1126err_unlock:
1127 mutex_unlock(&s->mutex);
1128
1129 return err;
1130}
31ef9134 1131
e9148ddd 1132/**
f890f9a0
TS
1133 * amdtp_domain_stream_pcm_pointer - get the PCM buffer position
1134 * @d: the AMDTP domain.
be4a2894 1135 * @s: the AMDTP stream that transports the PCM data
e9148ddd
CL
1136 *
1137 * Returns the current buffer position, in frames.
1138 */
f890f9a0
TS
1139unsigned long amdtp_domain_stream_pcm_pointer(struct amdtp_domain *d,
1140 struct amdtp_stream *s)
e9148ddd 1141{
f890f9a0
TS
1142 struct amdtp_stream *irq_target = d->irq_target;
1143
1144 if (irq_target && amdtp_stream_running(irq_target)) {
1145 // This function is called in software IRQ context of
1146 // period_tasklet or process context.
1147 //
1148 // When the software IRQ context was scheduled by software IRQ
1149 // context of IT contexts, queued packets were already handled.
1150 // Therefore, no need to flush the queue in buffer furthermore.
1151 //
1152 // When the process context reach here, some packets will be
1153 // already queued in the buffer. These packets should be handled
1154 // immediately to keep better granularity of PCM pointer.
1155 //
1156 // Later, the process context will sometimes schedules software
1157 // IRQ context of the period_tasklet. Then, no need to flush the
1158 // queue by the same reason as described in the above
1159 if (!in_interrupt()) {
1160 // Queued packet should be processed without any kernel
1161 // preemption to keep latency against bus cycle.
1162 preempt_disable();
1163 fw_iso_context_flush_completions(irq_target->context);
1164 preempt_enable();
1165 }
1166 }
e9148ddd 1167
6aa7de05 1168 return READ_ONCE(s->pcm_buffer_pointer);
e9148ddd 1169}
f890f9a0 1170EXPORT_SYMBOL_GPL(amdtp_domain_stream_pcm_pointer);
e9148ddd 1171
875becf8 1172/**
e6dcc92f
TS
1173 * amdtp_domain_stream_pcm_ack - acknowledge queued PCM frames
1174 * @d: the AMDTP domain.
875becf8
TS
1175 * @s: the AMDTP stream that transfers the PCM frames
1176 *
1177 * Returns zero always.
1178 */
e6dcc92f 1179int amdtp_domain_stream_pcm_ack(struct amdtp_domain *d, struct amdtp_stream *s)
875becf8 1180{
e6dcc92f
TS
1181 struct amdtp_stream *irq_target = d->irq_target;
1182
1183 // Process isochronous packets for recent isochronous cycle to handle
1184 // queued PCM frames.
1185 if (irq_target && amdtp_stream_running(irq_target)) {
1186 // Queued packet should be processed without any kernel
1187 // preemption to keep latency against bus cycle.
1188 preempt_disable();
1189 fw_iso_context_flush_completions(irq_target->context);
1190 preempt_enable();
1191 }
875becf8
TS
1192
1193 return 0;
1194}
e6dcc92f 1195EXPORT_SYMBOL_GPL(amdtp_domain_stream_pcm_ack);
875becf8 1196
31ef9134 1197/**
be4a2894
TS
1198 * amdtp_stream_update - update the stream after a bus reset
1199 * @s: the AMDTP stream
31ef9134 1200 */
be4a2894 1201void amdtp_stream_update(struct amdtp_stream *s)
31ef9134 1202{
9a2820c1 1203 /* Precomputing. */
6aa7de05
MR
1204 WRITE_ONCE(s->source_node_id_field,
1205 (fw_parent_device(s->unit)->card->node_id << CIP_SID_SHIFT) & CIP_SID_MASK);
31ef9134 1206}
be4a2894 1207EXPORT_SYMBOL(amdtp_stream_update);
31ef9134
CL
1208
1209/**
be4a2894
TS
1210 * amdtp_stream_stop - stop sending packets
1211 * @s: the AMDTP stream to stop
31ef9134
CL
1212 *
1213 * All PCM and MIDI devices of the stream must be stopped before the stream
1214 * itself can be stopped.
1215 */
74f94e41 1216static void amdtp_stream_stop(struct amdtp_stream *s)
31ef9134
CL
1217{
1218 mutex_lock(&s->mutex);
1219
be4a2894 1220 if (!amdtp_stream_running(s)) {
31ef9134
CL
1221 mutex_unlock(&s->mutex);
1222 return;
1223 }
1224
76fb8789 1225 tasklet_kill(&s->period_tasklet);
31ef9134
CL
1226 fw_iso_context_stop(s->context);
1227 fw_iso_context_destroy(s->context);
1228 s->context = ERR_PTR(-1);
1229 iso_packets_buffer_destroy(&s->buffer, s->unit);
04130cf8 1230 kfree(s->pkt_descs);
31ef9134 1231
7b3b0d85
TS
1232 s->callbacked = false;
1233
31ef9134
CL
1234 mutex_unlock(&s->mutex);
1235}
31ef9134
CL
1236
1237/**
be4a2894 1238 * amdtp_stream_pcm_abort - abort the running PCM device
31ef9134
CL
1239 * @s: the AMDTP stream about to be stopped
1240 *
1241 * If the isochronous stream needs to be stopped asynchronously, call this
1242 * function first to stop the PCM device.
1243 */
be4a2894 1244void amdtp_stream_pcm_abort(struct amdtp_stream *s)
31ef9134
CL
1245{
1246 struct snd_pcm_substream *pcm;
1247
6aa7de05 1248 pcm = READ_ONCE(s->pcm);
1fb8510c
TI
1249 if (pcm)
1250 snd_pcm_stop_xrun(pcm);
31ef9134 1251}
be4a2894 1252EXPORT_SYMBOL(amdtp_stream_pcm_abort);
3ec3d7a3
TS
1253
1254/**
1255 * amdtp_domain_init - initialize an AMDTP domain structure
1256 * @d: the AMDTP domain to initialize.
1257 */
1258int amdtp_domain_init(struct amdtp_domain *d)
1259{
1260 INIT_LIST_HEAD(&d->streams);
1261
d68c3123
TS
1262 d->events_per_period = 0;
1263
3ec3d7a3
TS
1264 return 0;
1265}
1266EXPORT_SYMBOL_GPL(amdtp_domain_init);
1267
1268/**
1269 * amdtp_domain_destroy - destroy an AMDTP domain structure
1270 * @d: the AMDTP domain to destroy.
1271 */
1272void amdtp_domain_destroy(struct amdtp_domain *d)
1273{
8d0d5c3f
TS
1274 // At present nothing to do.
1275 return;
3ec3d7a3
TS
1276}
1277EXPORT_SYMBOL_GPL(amdtp_domain_destroy);
6261f90b 1278
157a53ee
TS
1279/**
1280 * amdtp_domain_add_stream - register isoc context into the domain.
1281 * @d: the AMDTP domain.
1282 * @s: the AMDTP stream.
1283 * @channel: the isochronous channel on the bus.
1284 * @speed: firewire speed code.
1285 */
1286int amdtp_domain_add_stream(struct amdtp_domain *d, struct amdtp_stream *s,
1287 int channel, int speed)
1288{
1289 struct amdtp_stream *tmp;
1290
1291 list_for_each_entry(tmp, &d->streams, list) {
1292 if (s == tmp)
1293 return -EBUSY;
1294 }
1295
1296 list_add(&s->list, &d->streams);
1297
1298 s->channel = channel;
1299 s->speed = speed;
2472cfb3 1300 s->domain = d;
157a53ee
TS
1301
1302 return 0;
1303}
1304EXPORT_SYMBOL_GPL(amdtp_domain_add_stream);
1305
acfedcbe
TS
1306static int get_current_cycle_time(struct fw_card *fw_card, int *cur_cycle)
1307{
1308 int generation;
1309 int rcode;
1310 __be32 reg;
1311 u32 data;
1312
1313 // This is a request to local 1394 OHCI controller and expected to
1314 // complete without any event waiting.
1315 generation = fw_card->generation;
1316 smp_rmb(); // node_id vs. generation.
1317 rcode = fw_run_transaction(fw_card, TCODE_READ_QUADLET_REQUEST,
1318 fw_card->node_id, generation, SCODE_100,
1319 CSR_REGISTER_BASE + CSR_CYCLE_TIME,
1320 &reg, sizeof(reg));
1321 if (rcode != RCODE_COMPLETE)
1322 return -EIO;
1323
1324 data = be32_to_cpu(reg);
1325 *cur_cycle = data >> 12;
1326
1327 return 0;
1328}
1329
9b4702b0
TS
1330/**
1331 * amdtp_domain_start - start sending packets for isoc context in the domain.
1332 * @d: the AMDTP domain.
acfedcbe 1333 * @ir_delay_cycle: the cycle delay to start all IR contexts.
9b4702b0 1334 */
acfedcbe 1335int amdtp_domain_start(struct amdtp_domain *d, unsigned int ir_delay_cycle)
9b4702b0 1336{
af86b0b1
TS
1337 unsigned int events_per_buffer = d->events_per_buffer;
1338 unsigned int events_per_period = d->events_per_period;
1339 unsigned int idle_irq_interval;
1340 unsigned int queue_size;
9b4702b0 1341 struct amdtp_stream *s;
acfedcbe
TS
1342 int cycle;
1343 int err;
9b4702b0 1344
60dd4929 1345 // Select an IT context as IRQ target.
9b4702b0 1346 list_for_each_entry(s, &d->streams, list) {
60dd4929 1347 if (s->direction == AMDTP_OUT_STREAM)
9b4702b0
TS
1348 break;
1349 }
60dd4929
TS
1350 if (!s)
1351 return -ENXIO;
1352 d->irq_target = s;
9b4702b0 1353
af86b0b1
TS
1354 // This is a case that AMDTP streams in domain run just for MIDI
1355 // substream. Use the number of events equivalent to 10 msec as
1356 // interval of hardware IRQ.
1357 if (events_per_period == 0)
1358 events_per_period = amdtp_rate_table[d->irq_target->sfc] / 100;
1359 if (events_per_buffer == 0)
1360 events_per_buffer = events_per_period * 3;
1361
1362 queue_size = DIV_ROUND_UP(CYCLES_PER_SECOND * events_per_buffer,
1363 amdtp_rate_table[d->irq_target->sfc]);
1364
acfedcbe
TS
1365 if (ir_delay_cycle > 0) {
1366 struct fw_card *fw_card = fw_parent_device(s->unit)->card;
1367
1368 err = get_current_cycle_time(fw_card, &cycle);
1369 if (err < 0)
1370 return err;
1371
1372 // No need to care overflow in cycle field because of enough
1373 // width.
1374 cycle += ir_delay_cycle;
1375
1376 // Round up to sec field.
1377 if ((cycle & 0x00001fff) >= CYCLES_PER_SECOND) {
1378 unsigned int sec;
1379
1380 // The sec field can overflow.
1381 sec = (cycle & 0xffffe000) >> 13;
1382 cycle = (++sec << 13) |
1383 ((cycle & 0x00001fff) / CYCLES_PER_SECOND);
1384 }
1385
1386 // In OHCI 1394 specification, lower 2 bits are available for
1387 // sec field.
1388 cycle &= 0x00007fff;
1389 } else {
1390 cycle = -1;
1391 }
1392
60dd4929 1393 list_for_each_entry(s, &d->streams, list) {
acfedcbe
TS
1394 int cycle_match;
1395
1396 if (s->direction == AMDTP_IN_STREAM) {
1397 cycle_match = cycle;
1398 } else {
1399 // IT context starts immediately.
1400 cycle_match = -1;
1401 }
1402
60dd4929 1403 if (s != d->irq_target) {
2472cfb3 1404 err = amdtp_stream_start(s, s->channel, s->speed,
af86b0b1 1405 cycle_match, queue_size, 0);
60dd4929
TS
1406 if (err < 0)
1407 goto error;
1408 }
9b4702b0
TS
1409 }
1410
60dd4929 1411 s = d->irq_target;
af86b0b1
TS
1412 s->ctx_data.rx.events_per_period = events_per_period;
1413 s->ctx_data.rx.event_count = 0;
1414
1415 idle_irq_interval = DIV_ROUND_UP(CYCLES_PER_SECOND * events_per_period,
1416 amdtp_rate_table[d->irq_target->sfc]);
1417 err = amdtp_stream_start(s, s->channel, s->speed, -1, queue_size,
1418 idle_irq_interval);
60dd4929
TS
1419 if (err < 0)
1420 goto error;
1421
1422 return 0;
1423error:
1424 list_for_each_entry(s, &d->streams, list)
1425 amdtp_stream_stop(s);
9b4702b0
TS
1426 return err;
1427}
1428EXPORT_SYMBOL_GPL(amdtp_domain_start);
1429
6261f90b
TS
1430/**
1431 * amdtp_domain_stop - stop sending packets for isoc context in the same domain.
1432 * @d: the AMDTP domain to which the isoc contexts belong.
1433 */
1434void amdtp_domain_stop(struct amdtp_domain *d)
1435{
1436 struct amdtp_stream *s, *next;
1437
60dd4929
TS
1438 if (d->irq_target)
1439 amdtp_stream_stop(d->irq_target);
1440
6261f90b
TS
1441 list_for_each_entry_safe(s, next, &d->streams, list) {
1442 list_del(&s->list);
1443
60dd4929
TS
1444 if (s != d->irq_target)
1445 amdtp_stream_stop(s);
6261f90b 1446 }
d68c3123
TS
1447
1448 d->events_per_period = 0;
60dd4929 1449 d->irq_target = NULL;
6261f90b
TS
1450}
1451EXPORT_SYMBOL_GPL(amdtp_domain_stop);