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