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