1 // SPDX-License-Identifier: GPL-2.0-only
3 * Audio and Music Data Transmission Protocol (IEC 61883-6) streams
4 * with Common Isochronous Packet (IEC 61883-1) headers
6 * Copyright (c) Clemens Ladisch <clemens@ladisch.de>
9 #include <linux/device.h>
10 #include <linux/err.h>
11 #include <linux/firewire.h>
12 #include <linux/firewire-constants.h>
13 #include <linux/module.h>
14 #include <linux/slab.h>
15 #include <sound/pcm.h>
16 #include <sound/pcm_params.h>
17 #include "amdtp-stream.h"
19 #define TICKS_PER_CYCLE 3072
20 #define CYCLES_PER_SECOND 8000
21 #define TICKS_PER_SECOND (TICKS_PER_CYCLE * CYCLES_PER_SECOND)
23 #define OHCI_MAX_SECOND 8
25 /* Always support Linux tracing subsystem. */
26 #define CREATE_TRACE_POINTS
27 #include "amdtp-stream-trace.h"
29 #define TRANSFER_DELAY_TICKS 0x2e00 /* 479.17 microseconds */
31 /* isochronous header parameters */
32 #define ISO_DATA_LENGTH_SHIFT 16
33 #define TAG_NO_CIP_HEADER 0
36 /* common isochronous packet header parameters */
37 #define CIP_EOH_SHIFT 31
38 #define CIP_EOH (1u << CIP_EOH_SHIFT)
39 #define CIP_EOH_MASK 0x80000000
40 #define CIP_SID_SHIFT 24
41 #define CIP_SID_MASK 0x3f000000
42 #define CIP_DBS_MASK 0x00ff0000
43 #define CIP_DBS_SHIFT 16
44 #define CIP_SPH_MASK 0x00000400
45 #define CIP_SPH_SHIFT 10
46 #define CIP_DBC_MASK 0x000000ff
47 #define CIP_FMT_SHIFT 24
48 #define CIP_FMT_MASK 0x3f000000
49 #define CIP_FDF_MASK 0x00ff0000
50 #define CIP_FDF_SHIFT 16
51 #define CIP_SYT_MASK 0x0000ffff
52 #define CIP_SYT_NO_INFO 0xffff
54 /* Audio and Music transfer protocol specific parameters */
55 #define CIP_FMT_AM 0x10
56 #define AMDTP_FDF_NO_DATA 0xff
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
62 #define HEADER_TSTAMP_MASK 0x0000ffff
64 #define IT_PKT_HEADER_SIZE_CIP 8 // For 2 CIP header.
65 #define IT_PKT_HEADER_SIZE_NO_CIP 0 // Nothing.
67 static void pcm_period_tasklet(unsigned long data);
70 * amdtp_stream_init - initialize an AMDTP stream structure
71 * @s: the AMDTP stream to initialize
72 * @unit: the target of the stream
73 * @dir: the direction of stream
74 * @flags: the packet transmission method to use
75 * @fmt: the value of fmt field in CIP header
76 * @process_ctx_payloads: callback handler to process payloads of isoc context
77 * @protocol_size: the size to allocate newly for protocol
79 int amdtp_stream_init(struct amdtp_stream *s, struct fw_unit *unit,
80 enum amdtp_stream_direction dir, enum cip_flags flags,
82 amdtp_stream_process_ctx_payloads_t process_ctx_payloads,
83 unsigned int protocol_size)
85 if (process_ctx_payloads == NULL)
88 s->protocol = kzalloc(protocol_size, GFP_KERNEL);
95 s->context = ERR_PTR(-1);
96 mutex_init(&s->mutex);
97 tasklet_init(&s->period_tasklet, pcm_period_tasklet, (unsigned long)s);
100 init_waitqueue_head(&s->callback_wait);
101 s->callbacked = false;
104 s->process_ctx_payloads = process_ctx_payloads;
106 if (dir == AMDTP_OUT_STREAM)
107 s->ctx_data.rx.syt_override = -1;
111 EXPORT_SYMBOL(amdtp_stream_init);
114 * amdtp_stream_destroy - free stream resources
115 * @s: the AMDTP stream to destroy
117 void amdtp_stream_destroy(struct amdtp_stream *s)
119 /* Not initialized. */
120 if (s->protocol == NULL)
123 WARN_ON(amdtp_stream_running(s));
125 mutex_destroy(&s->mutex);
127 EXPORT_SYMBOL(amdtp_stream_destroy);
129 const unsigned int amdtp_syt_intervals[CIP_SFC_COUNT] = {
133 [CIP_SFC_88200] = 16,
134 [CIP_SFC_96000] = 16,
135 [CIP_SFC_176400] = 32,
136 [CIP_SFC_192000] = 32,
138 EXPORT_SYMBOL(amdtp_syt_intervals);
140 const unsigned int amdtp_rate_table[CIP_SFC_COUNT] = {
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,
149 EXPORT_SYMBOL(amdtp_rate_table);
151 static int apply_constraint_to_size(struct snd_pcm_hw_params *params,
152 struct snd_pcm_hw_rule *rule)
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);
157 struct snd_interval t = {0};
158 unsigned int step = 0;
161 for (i = 0; i < CIP_SFC_COUNT; ++i) {
162 if (snd_interval_test(r, amdtp_rate_table[i]))
163 step = max(step, amdtp_syt_intervals[i]);
166 t.min = roundup(s->min, step);
167 t.max = rounddown(s->max, step);
170 return snd_interval_refine(s, &t);
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
178 int amdtp_stream_add_pcm_hw_constraints(struct amdtp_stream *s,
179 struct snd_pcm_runtime *runtime)
181 struct snd_pcm_hardware *hw = &runtime->hw;
182 unsigned int ctx_header_size;
183 unsigned int maximum_usec_per_period;
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;
193 /* SNDRV_PCM_INFO_BATCH */
195 hw->periods_max = UINT_MAX;
197 /* bytes for a frame */
198 hw->period_bytes_min = 4 * hw->channels_max;
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;
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
212 if (!(s->flags & CIP_NO_HEADER))
213 ctx_header_size = IR_CTX_HEADER_SIZE_CIP;
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;
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
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
231 err = snd_pcm_hw_constraint_minmax(runtime,
232 SNDRV_PCM_HW_PARAM_PERIOD_TIME,
233 250, maximum_usec_per_period);
237 /* Non-Blocking stream has no more constraints */
238 if (!(s->flags & CIP_BLOCKING))
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
245 * preferrable to align period/buffer sizes to current SYT_INTERVAL.
247 err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
248 apply_constraint_to_size, NULL,
249 SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
250 SNDRV_PCM_HW_PARAM_RATE, -1);
253 err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
254 apply_constraint_to_size, NULL,
255 SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
256 SNDRV_PCM_HW_PARAM_RATE, -1);
262 EXPORT_SYMBOL(amdtp_stream_add_pcm_hw_constraints);
265 * amdtp_stream_set_parameters - set stream parameters
266 * @s: the AMDTP stream to configure
267 * @rate: the sample rate
268 * @data_block_quadlets: the size of a data block in quadlet unit
270 * The parameters must be set before the stream is started, and must not be
271 * changed while the stream is running.
273 int amdtp_stream_set_parameters(struct amdtp_stream *s, unsigned int rate,
274 unsigned int data_block_quadlets)
278 for (sfc = 0; sfc < ARRAY_SIZE(amdtp_rate_table); ++sfc) {
279 if (amdtp_rate_table[sfc] == rate)
282 if (sfc == ARRAY_SIZE(amdtp_rate_table))
286 s->data_block_quadlets = data_block_quadlets;
287 s->syt_interval = amdtp_syt_intervals[sfc];
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;
294 if (s->flags & CIP_BLOCKING) {
295 // additional buffering needed to adjust for no-data
297 s->ctx_data.rx.transfer_delay +=
298 TICKS_PER_SECOND * s->syt_interval / rate;
304 EXPORT_SYMBOL(amdtp_stream_set_parameters);
307 * amdtp_stream_get_max_payload - get the stream's packet size
308 * @s: the AMDTP stream
310 * This function must not be called before the stream has been configured
311 * with amdtp_stream_set_parameters().
313 unsigned int amdtp_stream_get_max_payload(struct amdtp_stream *s)
315 unsigned int multiplier = 1;
316 unsigned int cip_header_size = 0;
318 if (s->flags & CIP_JUMBO_PAYLOAD)
320 if (!(s->flags & CIP_NO_HEADER))
321 cip_header_size = sizeof(__be32) * 2;
323 return cip_header_size +
324 s->syt_interval * s->data_block_quadlets * sizeof(__be32) * multiplier;
326 EXPORT_SYMBOL(amdtp_stream_get_max_payload);
329 * amdtp_stream_pcm_prepare - prepare PCM device for running
330 * @s: the AMDTP stream
332 * This function should be called from the PCM device's .prepare callback.
334 void amdtp_stream_pcm_prepare(struct amdtp_stream *s)
336 tasklet_kill(&s->period_tasklet);
337 s->pcm_buffer_pointer = 0;
338 s->pcm_period_pointer = 0;
340 EXPORT_SYMBOL(amdtp_stream_pcm_prepare);
342 static unsigned int calculate_data_blocks(unsigned int *data_block_state,
343 bool is_blocking, bool is_no_info,
344 unsigned int syt_interval, enum cip_sfc sfc)
346 unsigned int data_blocks;
350 /* This module generate empty packet for 'no data'. */
354 data_blocks = syt_interval;
355 /* Non-blocking mode. */
357 if (!cip_sfc_is_base_44100(sfc)) {
358 // Sample_rate / 8000 is an integer, and precomputed.
359 data_blocks = *data_block_state;
361 unsigned int phase = *data_block_state;
364 * This calculates the number of data blocks per packet so that
365 * 1) the overall rate is correct and exactly synchronized to
367 * 2) packets with a rounded-up number of blocks occur as early
368 * as possible in the sequence (to prevent underruns of the
371 if (sfc == CIP_SFC_44100)
372 /* 6 6 5 6 5 6 5 ... */
373 data_blocks = 5 + ((phase & 1) ^
374 (phase == 0 || phase >= 40));
376 /* 12 11 11 11 11 ... or 23 22 22 22 22 ... */
377 data_blocks = 11 * (sfc >> 1) + (phase == 0);
378 if (++phase >= (80 >> (sfc >> 1)))
380 *data_block_state = phase;
387 static unsigned int calculate_syt_offset(unsigned int *last_syt_offset,
388 unsigned int *syt_offset_state, enum cip_sfc sfc)
390 unsigned int syt_offset;
392 if (*last_syt_offset < TICKS_PER_CYCLE) {
393 if (!cip_sfc_is_base_44100(sfc))
394 syt_offset = *last_syt_offset + *syt_offset_state;
397 * The time, in ticks, of the n'th SYT_INTERVAL sample is:
398 * n * SYT_INTERVAL * 24576000 / sample_rate
399 * Modulo TICKS_PER_CYCLE, the difference between successive
400 * elements is about 1386.23. Rounding the results of this
401 * formula to the SYT precision results in a sequence of
402 * differences that begins with:
403 * 1386 1386 1387 1386 1386 1386 1387 1386 1386 1386 1387 ...
404 * This code generates _exactly_ the same sequence.
406 unsigned int phase = *syt_offset_state;
407 unsigned int index = phase % 13;
409 syt_offset = *last_syt_offset;
410 syt_offset += 1386 + ((index && !(index & 3)) ||
414 *syt_offset_state = phase;
417 syt_offset = *last_syt_offset - TICKS_PER_CYCLE;
418 *last_syt_offset = syt_offset;
420 if (syt_offset >= TICKS_PER_CYCLE)
421 syt_offset = CIP_SYT_NO_INFO;
426 static void update_pcm_pointers(struct amdtp_stream *s,
427 struct snd_pcm_substream *pcm,
432 ptr = s->pcm_buffer_pointer + frames;
433 if (ptr >= pcm->runtime->buffer_size)
434 ptr -= pcm->runtime->buffer_size;
435 WRITE_ONCE(s->pcm_buffer_pointer, ptr);
437 s->pcm_period_pointer += frames;
438 if (s->pcm_period_pointer >= pcm->runtime->period_size) {
439 s->pcm_period_pointer -= pcm->runtime->period_size;
440 tasklet_hi_schedule(&s->period_tasklet);
444 static void pcm_period_tasklet(unsigned long data)
446 struct amdtp_stream *s = (void *)data;
447 struct snd_pcm_substream *pcm = READ_ONCE(s->pcm);
450 snd_pcm_period_elapsed(pcm);
453 static int queue_packet(struct amdtp_stream *s, struct fw_iso_packet *params,
458 params->interrupt = sched_irq;
459 params->tag = s->tag;
462 err = fw_iso_context_queue(s->context, params, &s->buffer.iso_buffer,
463 s->buffer.packets[s->packet_index].offset);
465 dev_err(&s->unit->device, "queueing error: %d\n", err);
469 if (++s->packet_index >= s->queue_size)
475 static inline int queue_out_packet(struct amdtp_stream *s,
476 struct fw_iso_packet *params, bool sched_irq)
479 !!(params->header_length == 0 && params->payload_length == 0);
480 return queue_packet(s, params, sched_irq);
483 static inline int queue_in_packet(struct amdtp_stream *s,
484 struct fw_iso_packet *params)
486 // Queue one packet for IR context.
487 params->header_length = s->ctx_data.tx.ctx_header_size;
488 params->payload_length = s->ctx_data.tx.max_ctx_payload_length;
489 params->skip = false;
490 return queue_packet(s, params, false);
493 static void generate_cip_header(struct amdtp_stream *s, __be32 cip_header[2],
494 unsigned int data_block_counter, unsigned int syt)
496 cip_header[0] = cpu_to_be32(READ_ONCE(s->source_node_id_field) |
497 (s->data_block_quadlets << CIP_DBS_SHIFT) |
498 ((s->sph << CIP_SPH_SHIFT) & CIP_SPH_MASK) |
500 cip_header[1] = cpu_to_be32(CIP_EOH |
501 ((s->fmt << CIP_FMT_SHIFT) & CIP_FMT_MASK) |
502 ((s->ctx_data.rx.fdf << CIP_FDF_SHIFT) & CIP_FDF_MASK) |
503 (syt & CIP_SYT_MASK));
506 static void build_it_pkt_header(struct amdtp_stream *s, unsigned int cycle,
507 struct fw_iso_packet *params,
508 unsigned int data_blocks,
509 unsigned int data_block_counter,
510 unsigned int syt, unsigned int index)
512 unsigned int payload_length;
515 payload_length = data_blocks * sizeof(__be32) * s->data_block_quadlets;
516 params->payload_length = payload_length;
518 if (!(s->flags & CIP_NO_HEADER)) {
519 cip_header = (__be32 *)params->header;
520 generate_cip_header(s, cip_header, data_block_counter, syt);
521 params->header_length = 2 * sizeof(__be32);
522 payload_length += params->header_length;
527 trace_amdtp_packet(s, cycle, cip_header, payload_length, data_blocks,
528 data_block_counter, index);
531 static int check_cip_header(struct amdtp_stream *s, const __be32 *buf,
532 unsigned int payload_length,
533 unsigned int *data_blocks,
534 unsigned int *data_block_counter, unsigned int *syt)
543 cip_header[0] = be32_to_cpu(buf[0]);
544 cip_header[1] = be32_to_cpu(buf[1]);
547 * This module supports 'Two-quadlet CIP header with SYT field'.
548 * For convenience, also check FMT field is AM824 or not.
550 if ((((cip_header[0] & CIP_EOH_MASK) == CIP_EOH) ||
551 ((cip_header[1] & CIP_EOH_MASK) != CIP_EOH)) &&
552 (!(s->flags & CIP_HEADER_WITHOUT_EOH))) {
553 dev_info_ratelimited(&s->unit->device,
554 "Invalid CIP header for AMDTP: %08X:%08X\n",
555 cip_header[0], cip_header[1]);
559 /* Check valid protocol or not. */
560 sph = (cip_header[0] & CIP_SPH_MASK) >> CIP_SPH_SHIFT;
561 fmt = (cip_header[1] & CIP_FMT_MASK) >> CIP_FMT_SHIFT;
562 if (sph != s->sph || fmt != s->fmt) {
563 dev_info_ratelimited(&s->unit->device,
564 "Detect unexpected protocol: %08x %08x\n",
565 cip_header[0], cip_header[1]);
569 /* Calculate data blocks */
570 fdf = (cip_header[1] & CIP_FDF_MASK) >> CIP_FDF_SHIFT;
571 if (payload_length < sizeof(__be32) * 2 ||
572 (fmt == CIP_FMT_AM && fdf == AMDTP_FDF_NO_DATA)) {
575 unsigned int data_block_quadlets =
576 (cip_header[0] & CIP_DBS_MASK) >> CIP_DBS_SHIFT;
577 /* avoid division by zero */
578 if (data_block_quadlets == 0) {
579 dev_err(&s->unit->device,
580 "Detect invalid value in dbs field: %08X\n",
584 if (s->flags & CIP_WRONG_DBS)
585 data_block_quadlets = s->data_block_quadlets;
587 *data_blocks = (payload_length / sizeof(__be32) - 2) /
591 /* Check data block counter continuity */
592 dbc = cip_header[0] & CIP_DBC_MASK;
593 if (*data_blocks == 0 && (s->flags & CIP_EMPTY_HAS_WRONG_DBC) &&
594 *data_block_counter != UINT_MAX)
595 dbc = *data_block_counter;
597 if ((dbc == 0x00 && (s->flags & CIP_SKIP_DBC_ZERO_CHECK)) ||
598 *data_block_counter == UINT_MAX) {
600 } else if (!(s->flags & CIP_DBC_IS_END_EVENT)) {
601 lost = dbc != *data_block_counter;
603 unsigned int dbc_interval;
605 if (*data_blocks > 0 && s->ctx_data.tx.dbc_interval > 0)
606 dbc_interval = s->ctx_data.tx.dbc_interval;
608 dbc_interval = *data_blocks;
610 lost = dbc != ((*data_block_counter + dbc_interval) & 0xff);
614 dev_err(&s->unit->device,
615 "Detect discontinuity of CIP: %02X %02X\n",
616 *data_block_counter, dbc);
620 *data_block_counter = dbc;
622 *syt = cip_header[1] & CIP_SYT_MASK;
627 static int parse_ir_ctx_header(struct amdtp_stream *s, unsigned int cycle,
628 const __be32 *ctx_header,
629 unsigned int *payload_length,
630 unsigned int *data_blocks,
631 unsigned int *data_block_counter,
632 unsigned int *syt, unsigned int index)
634 const __be32 *cip_header;
637 *payload_length = be32_to_cpu(ctx_header[0]) >> ISO_DATA_LENGTH_SHIFT;
638 if (*payload_length > s->ctx_data.tx.ctx_header_size +
639 s->ctx_data.tx.max_ctx_payload_length) {
640 dev_err(&s->unit->device,
641 "Detect jumbo payload: %04x %04x\n",
642 *payload_length, s->ctx_data.tx.max_ctx_payload_length);
646 if (!(s->flags & CIP_NO_HEADER)) {
647 cip_header = ctx_header + 2;
648 err = check_cip_header(s, cip_header, *payload_length,
649 data_blocks, data_block_counter, syt);
655 *data_blocks = *payload_length / sizeof(__be32) /
656 s->data_block_quadlets;
659 if (*data_block_counter == UINT_MAX)
660 *data_block_counter = 0;
663 trace_amdtp_packet(s, cycle, cip_header, *payload_length, *data_blocks,
664 *data_block_counter, index);
669 // In CYCLE_TIMER register of IEEE 1394, 7 bits are used to represent second. On
670 // the other hand, in DMA descriptors of 1394 OHCI, 3 bits are used to represent
671 // it. Thus, via Linux firewire subsystem, we can get the 3 bits for second.
672 static inline u32 compute_cycle_count(__be32 ctx_header_tstamp)
674 u32 tstamp = be32_to_cpu(ctx_header_tstamp) & HEADER_TSTAMP_MASK;
675 return (((tstamp >> 13) & 0x07) * 8000) + (tstamp & 0x1fff);
678 static inline u32 increment_cycle_count(u32 cycle, unsigned int addend)
681 if (cycle >= OHCI_MAX_SECOND * CYCLES_PER_SECOND)
682 cycle -= OHCI_MAX_SECOND * CYCLES_PER_SECOND;
686 // Align to actual cycle count for the packet which is going to be scheduled.
687 // This module queued the same number of isochronous cycle as the size of queue
688 // to kip isochronous cycle, therefore it's OK to just increment the cycle by
689 // the size of queue for scheduled cycle.
690 static inline u32 compute_it_cycle(const __be32 ctx_header_tstamp,
691 unsigned int queue_size)
693 u32 cycle = compute_cycle_count(ctx_header_tstamp);
694 return increment_cycle_count(cycle, queue_size);
697 static int generate_device_pkt_descs(struct amdtp_stream *s,
698 struct pkt_desc *descs,
699 const __be32 *ctx_header,
700 unsigned int packets)
702 unsigned int dbc = s->data_block_counter;
706 for (i = 0; i < packets; ++i) {
707 struct pkt_desc *desc = descs + i;
708 unsigned int index = (s->packet_index + i) % s->queue_size;
710 unsigned int payload_length;
711 unsigned int data_blocks;
714 cycle = compute_cycle_count(ctx_header[1]);
716 err = parse_ir_ctx_header(s, cycle, ctx_header, &payload_length,
717 &data_blocks, &dbc, &syt, i);
723 desc->data_blocks = data_blocks;
724 desc->data_block_counter = dbc;
725 desc->ctx_payload = s->buffer.packets[index].buffer;
727 if (!(s->flags & CIP_DBC_IS_END_EVENT))
728 dbc = (dbc + desc->data_blocks) & 0xff;
731 s->ctx_data.tx.ctx_header_size / sizeof(*ctx_header);
734 s->data_block_counter = dbc;
739 static unsigned int compute_syt(unsigned int syt_offset, unsigned int cycle,
740 unsigned int transfer_delay)
744 syt_offset += transfer_delay;
745 syt = ((cycle + syt_offset / TICKS_PER_CYCLE) << 12) |
746 (syt_offset % TICKS_PER_CYCLE);
747 return syt & CIP_SYT_MASK;
750 static void generate_ideal_pkt_descs(struct amdtp_stream *s,
751 struct pkt_desc *descs,
752 const __be32 *ctx_header,
753 unsigned int packets)
755 unsigned int dbc = s->data_block_counter;
758 for (i = 0; i < packets; ++i) {
759 struct pkt_desc *desc = descs + i;
760 unsigned int index = (s->packet_index + i) % s->queue_size;
761 unsigned int syt_offset;
763 desc->cycle = compute_it_cycle(*ctx_header, s->queue_size);
764 syt_offset = calculate_syt_offset(
765 &s->ctx_data.rx.last_syt_offset,
766 &s->ctx_data.rx.syt_offset_state, s->sfc);
767 if (syt_offset != CIP_SYT_NO_INFO) {
768 desc->syt = compute_syt(syt_offset, desc->cycle,
769 s->ctx_data.rx.transfer_delay);
771 desc->syt = syt_offset;
774 calculate_data_blocks(&s->ctx_data.rx.data_block_state,
775 !!(s->flags & CIP_BLOCKING),
776 desc->syt == CIP_SYT_NO_INFO,
777 s->syt_interval, s->sfc);
779 if (s->flags & CIP_DBC_IS_END_EVENT)
780 dbc = (dbc + desc->data_blocks) & 0xff;
782 desc->data_block_counter = dbc;
784 if (!(s->flags & CIP_DBC_IS_END_EVENT))
785 dbc = (dbc + desc->data_blocks) & 0xff;
787 desc->ctx_payload = s->buffer.packets[index].buffer;
792 s->data_block_counter = dbc;
795 static inline void cancel_stream(struct amdtp_stream *s)
797 s->packet_index = -1;
799 amdtp_stream_pcm_abort(s);
800 WRITE_ONCE(s->pcm_buffer_pointer, SNDRV_PCM_POS_XRUN);
803 static void process_ctx_payloads(struct amdtp_stream *s,
804 const struct pkt_desc *descs,
805 unsigned int packets)
807 struct snd_pcm_substream *pcm;
808 unsigned int pcm_frames;
810 pcm = READ_ONCE(s->pcm);
811 pcm_frames = s->process_ctx_payloads(s, descs, packets, pcm);
813 update_pcm_pointers(s, pcm, pcm_frames);
816 static void out_stream_callback(struct fw_iso_context *context, u32 tstamp,
817 size_t header_length, void *header,
820 struct amdtp_stream *s = private_data;
821 const __be32 *ctx_header = header;
822 unsigned int events_per_period = s->ctx_data.rx.events_per_period;
823 unsigned int event_count = s->ctx_data.rx.event_count;
824 unsigned int packets;
827 if (s->packet_index < 0)
830 // Calculate the number of packets in buffer and check XRUN.
831 packets = header_length / sizeof(*ctx_header);
833 generate_ideal_pkt_descs(s, s->pkt_descs, ctx_header, packets);
835 process_ctx_payloads(s, s->pkt_descs, packets);
837 for (i = 0; i < packets; ++i) {
838 const struct pkt_desc *desc = s->pkt_descs + i;
841 struct fw_iso_packet params;
842 __be32 header[IT_PKT_HEADER_SIZE_CIP / sizeof(__be32)];
843 } template = { {0}, {0} };
844 bool sched_irq = false;
846 if (s->ctx_data.rx.syt_override < 0)
849 syt = s->ctx_data.rx.syt_override;
851 build_it_pkt_header(s, desc->cycle, &template.params,
852 desc->data_blocks, desc->data_block_counter,
855 if (s == s->domain->irq_target) {
856 event_count += desc->data_blocks;
857 if (event_count >= events_per_period) {
858 event_count -= events_per_period;
863 if (queue_out_packet(s, &template.params, sched_irq) < 0) {
869 s->ctx_data.rx.event_count = event_count;
872 static void in_stream_callback(struct fw_iso_context *context, u32 tstamp,
873 size_t header_length, void *header,
876 struct amdtp_stream *s = private_data;
877 __be32 *ctx_header = header;
878 unsigned int packets;
882 if (s->packet_index < 0)
885 // Calculate the number of packets in buffer and check XRUN.
886 packets = header_length / s->ctx_data.tx.ctx_header_size;
888 err = generate_device_pkt_descs(s, s->pkt_descs, ctx_header, packets);
890 if (err != -EAGAIN) {
895 process_ctx_payloads(s, s->pkt_descs, packets);
898 for (i = 0; i < packets; ++i) {
899 struct fw_iso_packet params = {0};
901 if (queue_in_packet(s, ¶ms) < 0) {
908 static void irq_target_callback(struct fw_iso_context *context, u32 tstamp,
909 size_t header_length, void *header,
912 struct amdtp_stream *irq_target = private_data;
913 struct amdtp_domain *d = irq_target->domain;
914 struct amdtp_stream *s;
916 out_stream_callback(context, tstamp, header_length, header, irq_target);
917 if (amdtp_streaming_error(irq_target))
920 list_for_each_entry(s, &d->streams, list) {
921 if (s != irq_target && amdtp_stream_running(s)) {
922 fw_iso_context_flush_completions(s->context);
923 if (amdtp_streaming_error(s))
930 if (amdtp_stream_running(irq_target))
931 cancel_stream(irq_target);
933 list_for_each_entry(s, &d->streams, list) {
934 if (amdtp_stream_running(s))
939 // this is executed one time.
940 static void amdtp_stream_first_callback(struct fw_iso_context *context,
941 u32 tstamp, size_t header_length,
942 void *header, void *private_data)
944 struct amdtp_stream *s = private_data;
945 const __be32 *ctx_header = header;
949 * For in-stream, first packet has come.
950 * For out-stream, prepared to transmit first packet
952 s->callbacked = true;
953 wake_up(&s->callback_wait);
955 if (s->direction == AMDTP_IN_STREAM) {
956 cycle = compute_cycle_count(ctx_header[1]);
958 context->callback.sc = in_stream_callback;
960 cycle = compute_it_cycle(*ctx_header, s->queue_size);
962 if (s == s->domain->irq_target)
963 context->callback.sc = irq_target_callback;
965 context->callback.sc = out_stream_callback;
968 s->start_cycle = cycle;
970 context->callback.sc(context, tstamp, header_length, header, s);
974 * amdtp_stream_start - start transferring packets
975 * @s: the AMDTP stream to start
976 * @channel: the isochronous channel on the bus
977 * @speed: firewire speed code
978 * @start_cycle: the isochronous cycle to start the context. Start immediately
979 * if negative value is given.
980 * @queue_size: The number of packets in the queue.
981 * @idle_irq_interval: the interval to queue packet during initial state.
983 * The stream cannot be started until it has been configured with
984 * amdtp_stream_set_parameters() and it must be started before any PCM or MIDI
985 * device can be started.
987 static int amdtp_stream_start(struct amdtp_stream *s, int channel, int speed,
988 int start_cycle, unsigned int queue_size,
989 unsigned int idle_irq_interval)
991 static const struct {
992 unsigned int data_block;
993 unsigned int syt_offset;
994 } *entry, initial_state[] = {
995 [CIP_SFC_32000] = { 4, 3072 },
996 [CIP_SFC_48000] = { 6, 1024 },
997 [CIP_SFC_96000] = { 12, 1024 },
998 [CIP_SFC_192000] = { 24, 1024 },
999 [CIP_SFC_44100] = { 0, 67 },
1000 [CIP_SFC_88200] = { 0, 67 },
1001 [CIP_SFC_176400] = { 0, 67 },
1003 bool is_irq_target = (s == s->domain->irq_target);
1004 unsigned int ctx_header_size;
1005 unsigned int max_ctx_payload_size;
1006 enum dma_data_direction dir;
1009 mutex_lock(&s->mutex);
1011 if (WARN_ON(amdtp_stream_running(s) ||
1012 (s->data_block_quadlets < 1))) {
1017 if (s->direction == AMDTP_IN_STREAM) {
1018 // NOTE: IT context should be used for constant IRQ.
1019 if (is_irq_target) {
1024 s->data_block_counter = UINT_MAX;
1026 entry = &initial_state[s->sfc];
1028 s->data_block_counter = 0;
1029 s->ctx_data.rx.data_block_state = entry->data_block;
1030 s->ctx_data.rx.syt_offset_state = entry->syt_offset;
1031 s->ctx_data.rx.last_syt_offset = TICKS_PER_CYCLE;
1034 /* initialize packet buffer */
1035 if (s->direction == AMDTP_IN_STREAM) {
1036 dir = DMA_FROM_DEVICE;
1037 type = FW_ISO_CONTEXT_RECEIVE;
1038 if (!(s->flags & CIP_NO_HEADER))
1039 ctx_header_size = IR_CTX_HEADER_SIZE_CIP;
1041 ctx_header_size = IR_CTX_HEADER_SIZE_NO_CIP;
1043 max_ctx_payload_size = amdtp_stream_get_max_payload(s) -
1046 dir = DMA_TO_DEVICE;
1047 type = FW_ISO_CONTEXT_TRANSMIT;
1048 ctx_header_size = 0; // No effect for IT context.
1050 max_ctx_payload_size = amdtp_stream_get_max_payload(s);
1051 if (!(s->flags & CIP_NO_HEADER))
1052 max_ctx_payload_size -= IT_PKT_HEADER_SIZE_CIP;
1055 err = iso_packets_buffer_init(&s->buffer, s->unit, queue_size,
1056 max_ctx_payload_size, dir);
1059 s->queue_size = queue_size;
1061 s->context = fw_iso_context_create(fw_parent_device(s->unit)->card,
1062 type, channel, speed, ctx_header_size,
1063 amdtp_stream_first_callback, s);
1064 if (IS_ERR(s->context)) {
1065 err = PTR_ERR(s->context);
1067 dev_err(&s->unit->device,
1068 "no free stream on this controller\n");
1072 amdtp_stream_update(s);
1074 if (s->direction == AMDTP_IN_STREAM) {
1075 s->ctx_data.tx.max_ctx_payload_length = max_ctx_payload_size;
1076 s->ctx_data.tx.ctx_header_size = ctx_header_size;
1079 if (s->flags & CIP_NO_HEADER)
1080 s->tag = TAG_NO_CIP_HEADER;
1084 s->pkt_descs = kcalloc(s->queue_size, sizeof(*s->pkt_descs),
1086 if (!s->pkt_descs) {
1091 s->packet_index = 0;
1093 struct fw_iso_packet params;
1095 if (s->direction == AMDTP_IN_STREAM) {
1096 err = queue_in_packet(s, ¶ms);
1098 bool sched_irq = false;
1100 params.header_length = 0;
1101 params.payload_length = 0;
1103 if (is_irq_target) {
1104 sched_irq = !((s->packet_index + 1) %
1108 err = queue_out_packet(s, ¶ms, sched_irq);
1112 } while (s->packet_index > 0);
1114 /* NOTE: TAG1 matches CIP. This just affects in stream. */
1115 tag = FW_ISO_CONTEXT_MATCH_TAG1;
1116 if ((s->flags & CIP_EMPTY_WITH_TAG0) || (s->flags & CIP_NO_HEADER))
1117 tag |= FW_ISO_CONTEXT_MATCH_TAG0;
1119 s->callbacked = false;
1120 err = fw_iso_context_start(s->context, start_cycle, 0, tag);
1124 mutex_unlock(&s->mutex);
1128 kfree(s->pkt_descs);
1130 fw_iso_context_destroy(s->context);
1131 s->context = ERR_PTR(-1);
1133 iso_packets_buffer_destroy(&s->buffer, s->unit);
1135 mutex_unlock(&s->mutex);
1141 * amdtp_domain_stream_pcm_pointer - get the PCM buffer position
1142 * @d: the AMDTP domain.
1143 * @s: the AMDTP stream that transports the PCM data
1145 * Returns the current buffer position, in frames.
1147 unsigned long amdtp_domain_stream_pcm_pointer(struct amdtp_domain *d,
1148 struct amdtp_stream *s)
1150 struct amdtp_stream *irq_target = d->irq_target;
1152 if (irq_target && amdtp_stream_running(irq_target)) {
1153 // This function is called in software IRQ context of
1154 // period_tasklet or process context.
1156 // When the software IRQ context was scheduled by software IRQ
1157 // context of IT contexts, queued packets were already handled.
1158 // Therefore, no need to flush the queue in buffer furthermore.
1160 // When the process context reach here, some packets will be
1161 // already queued in the buffer. These packets should be handled
1162 // immediately to keep better granularity of PCM pointer.
1164 // Later, the process context will sometimes schedules software
1165 // IRQ context of the period_tasklet. Then, no need to flush the
1166 // queue by the same reason as described in the above
1167 if (!in_interrupt()) {
1168 // Queued packet should be processed without any kernel
1169 // preemption to keep latency against bus cycle.
1171 fw_iso_context_flush_completions(irq_target->context);
1176 return READ_ONCE(s->pcm_buffer_pointer);
1178 EXPORT_SYMBOL_GPL(amdtp_domain_stream_pcm_pointer);
1181 * amdtp_domain_stream_pcm_ack - acknowledge queued PCM frames
1182 * @d: the AMDTP domain.
1183 * @s: the AMDTP stream that transfers the PCM frames
1185 * Returns zero always.
1187 int amdtp_domain_stream_pcm_ack(struct amdtp_domain *d, struct amdtp_stream *s)
1189 struct amdtp_stream *irq_target = d->irq_target;
1191 // Process isochronous packets for recent isochronous cycle to handle
1192 // queued PCM frames.
1193 if (irq_target && amdtp_stream_running(irq_target)) {
1194 // Queued packet should be processed without any kernel
1195 // preemption to keep latency against bus cycle.
1197 fw_iso_context_flush_completions(irq_target->context);
1203 EXPORT_SYMBOL_GPL(amdtp_domain_stream_pcm_ack);
1206 * amdtp_stream_update - update the stream after a bus reset
1207 * @s: the AMDTP stream
1209 void amdtp_stream_update(struct amdtp_stream *s)
1212 WRITE_ONCE(s->source_node_id_field,
1213 (fw_parent_device(s->unit)->card->node_id << CIP_SID_SHIFT) & CIP_SID_MASK);
1215 EXPORT_SYMBOL(amdtp_stream_update);
1218 * amdtp_stream_stop - stop sending packets
1219 * @s: the AMDTP stream to stop
1221 * All PCM and MIDI devices of the stream must be stopped before the stream
1222 * itself can be stopped.
1224 static void amdtp_stream_stop(struct amdtp_stream *s)
1226 mutex_lock(&s->mutex);
1228 if (!amdtp_stream_running(s)) {
1229 mutex_unlock(&s->mutex);
1233 tasklet_kill(&s->period_tasklet);
1234 fw_iso_context_stop(s->context);
1235 fw_iso_context_destroy(s->context);
1236 s->context = ERR_PTR(-1);
1237 iso_packets_buffer_destroy(&s->buffer, s->unit);
1238 kfree(s->pkt_descs);
1240 s->callbacked = false;
1242 mutex_unlock(&s->mutex);
1246 * amdtp_stream_pcm_abort - abort the running PCM device
1247 * @s: the AMDTP stream about to be stopped
1249 * If the isochronous stream needs to be stopped asynchronously, call this
1250 * function first to stop the PCM device.
1252 void amdtp_stream_pcm_abort(struct amdtp_stream *s)
1254 struct snd_pcm_substream *pcm;
1256 pcm = READ_ONCE(s->pcm);
1258 snd_pcm_stop_xrun(pcm);
1260 EXPORT_SYMBOL(amdtp_stream_pcm_abort);
1263 * amdtp_domain_init - initialize an AMDTP domain structure
1264 * @d: the AMDTP domain to initialize.
1266 int amdtp_domain_init(struct amdtp_domain *d)
1268 INIT_LIST_HEAD(&d->streams);
1270 d->events_per_period = 0;
1274 EXPORT_SYMBOL_GPL(amdtp_domain_init);
1277 * amdtp_domain_destroy - destroy an AMDTP domain structure
1278 * @d: the AMDTP domain to destroy.
1280 void amdtp_domain_destroy(struct amdtp_domain *d)
1282 // At present nothing to do.
1285 EXPORT_SYMBOL_GPL(amdtp_domain_destroy);
1288 * amdtp_domain_add_stream - register isoc context into the domain.
1289 * @d: the AMDTP domain.
1290 * @s: the AMDTP stream.
1291 * @channel: the isochronous channel on the bus.
1292 * @speed: firewire speed code.
1294 int amdtp_domain_add_stream(struct amdtp_domain *d, struct amdtp_stream *s,
1295 int channel, int speed)
1297 struct amdtp_stream *tmp;
1299 list_for_each_entry(tmp, &d->streams, list) {
1304 list_add(&s->list, &d->streams);
1306 s->channel = channel;
1312 EXPORT_SYMBOL_GPL(amdtp_domain_add_stream);
1314 static int get_current_cycle_time(struct fw_card *fw_card, int *cur_cycle)
1321 // This is a request to local 1394 OHCI controller and expected to
1322 // complete without any event waiting.
1323 generation = fw_card->generation;
1324 smp_rmb(); // node_id vs. generation.
1325 rcode = fw_run_transaction(fw_card, TCODE_READ_QUADLET_REQUEST,
1326 fw_card->node_id, generation, SCODE_100,
1327 CSR_REGISTER_BASE + CSR_CYCLE_TIME,
1329 if (rcode != RCODE_COMPLETE)
1332 data = be32_to_cpu(reg);
1333 *cur_cycle = data >> 12;
1339 * amdtp_domain_start - start sending packets for isoc context in the domain.
1340 * @d: the AMDTP domain.
1341 * @ir_delay_cycle: the cycle delay to start all IR contexts.
1343 int amdtp_domain_start(struct amdtp_domain *d, unsigned int ir_delay_cycle)
1345 unsigned int events_per_buffer = d->events_per_buffer;
1346 unsigned int events_per_period = d->events_per_period;
1347 unsigned int idle_irq_interval;
1348 unsigned int queue_size;
1349 struct amdtp_stream *s;
1353 // Select an IT context as IRQ target.
1354 list_for_each_entry(s, &d->streams, list) {
1355 if (s->direction == AMDTP_OUT_STREAM)
1362 // This is a case that AMDTP streams in domain run just for MIDI
1363 // substream. Use the number of events equivalent to 10 msec as
1364 // interval of hardware IRQ.
1365 if (events_per_period == 0)
1366 events_per_period = amdtp_rate_table[d->irq_target->sfc] / 100;
1367 if (events_per_buffer == 0)
1368 events_per_buffer = events_per_period * 3;
1370 queue_size = DIV_ROUND_UP(CYCLES_PER_SECOND * events_per_buffer,
1371 amdtp_rate_table[d->irq_target->sfc]);
1373 if (ir_delay_cycle > 0) {
1374 struct fw_card *fw_card = fw_parent_device(s->unit)->card;
1376 err = get_current_cycle_time(fw_card, &cycle);
1380 // No need to care overflow in cycle field because of enough
1382 cycle += ir_delay_cycle;
1384 // Round up to sec field.
1385 if ((cycle & 0x00001fff) >= CYCLES_PER_SECOND) {
1388 // The sec field can overflow.
1389 sec = (cycle & 0xffffe000) >> 13;
1390 cycle = (++sec << 13) |
1391 ((cycle & 0x00001fff) / CYCLES_PER_SECOND);
1394 // In OHCI 1394 specification, lower 2 bits are available for
1396 cycle &= 0x00007fff;
1401 list_for_each_entry(s, &d->streams, list) {
1404 if (s->direction == AMDTP_IN_STREAM) {
1405 cycle_match = cycle;
1407 // IT context starts immediately.
1411 if (s != d->irq_target) {
1412 err = amdtp_stream_start(s, s->channel, s->speed,
1413 cycle_match, queue_size, 0);
1420 s->ctx_data.rx.events_per_period = events_per_period;
1421 s->ctx_data.rx.event_count = 0;
1423 idle_irq_interval = DIV_ROUND_UP(CYCLES_PER_SECOND * events_per_period,
1424 amdtp_rate_table[d->irq_target->sfc]);
1425 err = amdtp_stream_start(s, s->channel, s->speed, -1, queue_size,
1432 list_for_each_entry(s, &d->streams, list)
1433 amdtp_stream_stop(s);
1436 EXPORT_SYMBOL_GPL(amdtp_domain_start);
1439 * amdtp_domain_stop - stop sending packets for isoc context in the same domain.
1440 * @d: the AMDTP domain to which the isoc contexts belong.
1442 void amdtp_domain_stop(struct amdtp_domain *d)
1444 struct amdtp_stream *s, *next;
1447 amdtp_stream_stop(d->irq_target);
1449 list_for_each_entry_safe(s, next, &d->streams, list) {
1452 if (s != d->irq_target)
1453 amdtp_stream_stop(s);
1456 d->events_per_period = 0;
1457 d->irq_target = NULL;
1459 EXPORT_SYMBOL_GPL(amdtp_domain_stop);