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