ALSA: firewire-lib: cancel flushing isoc context in the laste step to process context...
[linux-2.6-block.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
847 static void in_stream_callback(struct fw_iso_context *context, u32 tstamp,
848                                size_t header_length, void *header,
849                                void *private_data)
850 {
851         struct amdtp_stream *s = private_data;
852         __be32 *ctx_header = header;
853         unsigned int events_per_period = s->events_per_period;
854         unsigned int event_count = s->event_count;
855         unsigned int packets;
856         int i;
857         int err;
858
859         if (s->packet_index < 0)
860                 return;
861
862         // Calculate the number of packets in buffer and check XRUN.
863         packets = header_length / s->ctx_data.tx.ctx_header_size;
864
865         err = generate_device_pkt_descs(s, s->pkt_descs, ctx_header, packets);
866         if (err < 0) {
867                 if (err != -EAGAIN) {
868                         cancel_stream(s);
869                         return;
870                 }
871         } else {
872                 process_ctx_payloads(s, s->pkt_descs, packets);
873         }
874
875         for (i = 0; i < packets; ++i) {
876                 const struct pkt_desc *desc = s->pkt_descs + i;
877                 struct fw_iso_packet params = {0};
878                 bool sched_irq = false;
879
880                 if (err >= 0) {
881                         event_count += desc->data_blocks;
882                         if (event_count >= events_per_period) {
883                                 event_count -= events_per_period;
884                                 sched_irq = true;
885                         }
886                 } else {
887                         sched_irq =
888                                 !((s->packet_index + 1) % s->idle_irq_interval);
889                 }
890
891                 if (queue_in_packet(s, &params, sched_irq) < 0) {
892                         cancel_stream(s);
893                         return;
894                 }
895         }
896
897         s->event_count = event_count;
898 }
899
900 /* this is executed one time */
901 static void amdtp_stream_first_callback(struct fw_iso_context *context,
902                                         u32 tstamp, size_t header_length,
903                                         void *header, void *private_data)
904 {
905         struct amdtp_stream *s = private_data;
906         const __be32 *ctx_header = header;
907         u32 cycle;
908
909         /*
910          * For in-stream, first packet has come.
911          * For out-stream, prepared to transmit first packet
912          */
913         s->callbacked = true;
914         wake_up(&s->callback_wait);
915
916         if (s->direction == AMDTP_IN_STREAM) {
917                 cycle = compute_cycle_count(ctx_header[1]);
918
919                 context->callback.sc = in_stream_callback;
920         } else {
921                 cycle = compute_it_cycle(*ctx_header, s->queue_size);
922
923                 context->callback.sc = out_stream_callback;
924         }
925
926         s->start_cycle = cycle;
927
928         context->callback.sc(context, tstamp, header_length, header, s);
929 }
930
931 /**
932  * amdtp_stream_start - start transferring packets
933  * @s: the AMDTP stream to start
934  * @channel: the isochronous channel on the bus
935  * @speed: firewire speed code
936  *
937  * The stream cannot be started until it has been configured with
938  * amdtp_stream_set_parameters() and it must be started before any PCM or MIDI
939  * device can be started.
940  */
941 static int amdtp_stream_start(struct amdtp_stream *s, int channel, int speed,
942                               struct amdtp_domain *d)
943 {
944         static const struct {
945                 unsigned int data_block;
946                 unsigned int syt_offset;
947         } *entry, initial_state[] = {
948                 [CIP_SFC_32000]  = {  4, 3072 },
949                 [CIP_SFC_48000]  = {  6, 1024 },
950                 [CIP_SFC_96000]  = { 12, 1024 },
951                 [CIP_SFC_192000] = { 24, 1024 },
952                 [CIP_SFC_44100]  = {  0,   67 },
953                 [CIP_SFC_88200]  = {  0,   67 },
954                 [CIP_SFC_176400] = {  0,   67 },
955         };
956         unsigned int events_per_buffer = d->events_per_buffer;
957         unsigned int events_per_period = d->events_per_period;
958         unsigned int ctx_header_size;
959         unsigned int max_ctx_payload_size;
960         enum dma_data_direction dir;
961         int type, tag, err;
962
963         mutex_lock(&s->mutex);
964
965         if (WARN_ON(amdtp_stream_running(s) ||
966                     (s->data_block_quadlets < 1))) {
967                 err = -EBADFD;
968                 goto err_unlock;
969         }
970
971         if (s->direction == AMDTP_IN_STREAM) {
972                 s->data_block_counter = UINT_MAX;
973         } else {
974                 entry = &initial_state[s->sfc];
975
976                 s->data_block_counter = 0;
977                 s->ctx_data.rx.data_block_state = entry->data_block;
978                 s->ctx_data.rx.syt_offset_state = entry->syt_offset;
979                 s->ctx_data.rx.last_syt_offset = TICKS_PER_CYCLE;
980         }
981
982         /* initialize packet buffer */
983         if (s->direction == AMDTP_IN_STREAM) {
984                 dir = DMA_FROM_DEVICE;
985                 type = FW_ISO_CONTEXT_RECEIVE;
986                 if (!(s->flags & CIP_NO_HEADER))
987                         ctx_header_size = IR_CTX_HEADER_SIZE_CIP;
988                 else
989                         ctx_header_size = IR_CTX_HEADER_SIZE_NO_CIP;
990
991                 max_ctx_payload_size = amdtp_stream_get_max_payload(s) -
992                                        ctx_header_size;
993         } else {
994                 dir = DMA_TO_DEVICE;
995                 type = FW_ISO_CONTEXT_TRANSMIT;
996                 ctx_header_size = 0;    // No effect for IT context.
997
998                 max_ctx_payload_size = amdtp_stream_get_max_payload(s);
999                 if (!(s->flags & CIP_NO_HEADER))
1000                         max_ctx_payload_size -= IT_PKT_HEADER_SIZE_CIP;
1001         }
1002
1003         // This is a case that AMDTP streams in domain run just for MIDI
1004         // substream. Use the number of events equivalent to 10 msec as
1005         // interval of hardware IRQ.
1006         if (events_per_period == 0)
1007                 events_per_period = amdtp_rate_table[s->sfc] / 100;
1008         if (events_per_buffer == 0)
1009                 events_per_buffer = events_per_period * 3;
1010
1011         s->idle_irq_interval =
1012                         DIV_ROUND_UP(CYCLES_PER_SECOND * events_per_period,
1013                                      amdtp_rate_table[s->sfc]);
1014         s->queue_size = DIV_ROUND_UP(CYCLES_PER_SECOND * events_per_buffer,
1015                                      amdtp_rate_table[s->sfc]);
1016         s->events_per_period = events_per_period;
1017         s->event_count = 0;
1018
1019         err = iso_packets_buffer_init(&s->buffer, s->unit, s->queue_size,
1020                                       max_ctx_payload_size, dir);
1021         if (err < 0)
1022                 goto err_unlock;
1023
1024         s->context = fw_iso_context_create(fw_parent_device(s->unit)->card,
1025                                           type, channel, speed, ctx_header_size,
1026                                           amdtp_stream_first_callback, s);
1027         if (IS_ERR(s->context)) {
1028                 err = PTR_ERR(s->context);
1029                 if (err == -EBUSY)
1030                         dev_err(&s->unit->device,
1031                                 "no free stream on this controller\n");
1032                 goto err_buffer;
1033         }
1034
1035         amdtp_stream_update(s);
1036
1037         if (s->direction == AMDTP_IN_STREAM) {
1038                 s->ctx_data.tx.max_ctx_payload_length = max_ctx_payload_size;
1039                 s->ctx_data.tx.ctx_header_size = ctx_header_size;
1040         }
1041
1042         if (s->flags & CIP_NO_HEADER)
1043                 s->tag = TAG_NO_CIP_HEADER;
1044         else
1045                 s->tag = TAG_CIP;
1046
1047         s->pkt_descs = kcalloc(s->queue_size, sizeof(*s->pkt_descs),
1048                                GFP_KERNEL);
1049         if (!s->pkt_descs) {
1050                 err = -ENOMEM;
1051                 goto err_context;
1052         }
1053
1054         s->packet_index = 0;
1055         do {
1056                 struct fw_iso_packet params;
1057                 bool sched_irq;
1058
1059                 sched_irq = !((s->packet_index + 1) % s->idle_irq_interval);
1060                 if (s->direction == AMDTP_IN_STREAM) {
1061                         err = queue_in_packet(s, &params, sched_irq);
1062                 } else {
1063                         params.header_length = 0;
1064                         params.payload_length = 0;
1065                         err = queue_out_packet(s, &params, sched_irq);
1066                 }
1067                 if (err < 0)
1068                         goto err_pkt_descs;
1069         } while (s->packet_index > 0);
1070
1071         /* NOTE: TAG1 matches CIP. This just affects in stream. */
1072         tag = FW_ISO_CONTEXT_MATCH_TAG1;
1073         if ((s->flags & CIP_EMPTY_WITH_TAG0) || (s->flags & CIP_NO_HEADER))
1074                 tag |= FW_ISO_CONTEXT_MATCH_TAG0;
1075
1076         s->callbacked = false;
1077         err = fw_iso_context_start(s->context, -1, 0, tag);
1078         if (err < 0)
1079                 goto err_pkt_descs;
1080
1081         mutex_unlock(&s->mutex);
1082
1083         return 0;
1084 err_pkt_descs:
1085         kfree(s->pkt_descs);
1086 err_context:
1087         fw_iso_context_destroy(s->context);
1088         s->context = ERR_PTR(-1);
1089 err_buffer:
1090         iso_packets_buffer_destroy(&s->buffer, s->unit);
1091 err_unlock:
1092         mutex_unlock(&s->mutex);
1093
1094         return err;
1095 }
1096
1097 /**
1098  * amdtp_domain_stream_pcm_pointer - get the PCM buffer position
1099  * @d: the AMDTP domain.
1100  * @s: the AMDTP stream that transports the PCM data
1101  *
1102  * Returns the current buffer position, in frames.
1103  */
1104 unsigned long amdtp_domain_stream_pcm_pointer(struct amdtp_domain *d,
1105                                               struct amdtp_stream *s)
1106 {
1107         struct amdtp_stream *irq_target = d->irq_target;
1108
1109         if (irq_target && amdtp_stream_running(irq_target)) {
1110                 // This function is called in software IRQ context of
1111                 // period_tasklet or process context.
1112                 //
1113                 // When the software IRQ context was scheduled by software IRQ
1114                 // context of IT contexts, queued packets were already handled.
1115                 // Therefore, no need to flush the queue in buffer furthermore.
1116                 //
1117                 // When the process context reach here, some packets will be
1118                 // already queued in the buffer. These packets should be handled
1119                 // immediately to keep better granularity of PCM pointer.
1120                 //
1121                 // Later, the process context will sometimes schedules software
1122                 // IRQ context of the period_tasklet. Then, no need to flush the
1123                 // queue by the same reason as described in the above
1124                 if (!in_interrupt()) {
1125                         // Queued packet should be processed without any kernel
1126                         // preemption to keep latency against bus cycle.
1127                         preempt_disable();
1128                         fw_iso_context_flush_completions(irq_target->context);
1129                         preempt_enable();
1130                 }
1131         }
1132
1133         return READ_ONCE(s->pcm_buffer_pointer);
1134 }
1135 EXPORT_SYMBOL_GPL(amdtp_domain_stream_pcm_pointer);
1136
1137 /**
1138  * amdtp_domain_stream_pcm_ack - acknowledge queued PCM frames
1139  * @d: the AMDTP domain.
1140  * @s: the AMDTP stream that transfers the PCM frames
1141  *
1142  * Returns zero always.
1143  */
1144 int amdtp_domain_stream_pcm_ack(struct amdtp_domain *d, struct amdtp_stream *s)
1145 {
1146         struct amdtp_stream *irq_target = d->irq_target;
1147
1148         // Process isochronous packets for recent isochronous cycle to handle
1149         // queued PCM frames.
1150         if (irq_target && amdtp_stream_running(irq_target)) {
1151                 // Queued packet should be processed without any kernel
1152                 // preemption to keep latency against bus cycle.
1153                 preempt_disable();
1154                 fw_iso_context_flush_completions(irq_target->context);
1155                 preempt_enable();
1156         }
1157
1158         return 0;
1159 }
1160 EXPORT_SYMBOL_GPL(amdtp_domain_stream_pcm_ack);
1161
1162 /**
1163  * amdtp_stream_update - update the stream after a bus reset
1164  * @s: the AMDTP stream
1165  */
1166 void amdtp_stream_update(struct amdtp_stream *s)
1167 {
1168         /* Precomputing. */
1169         WRITE_ONCE(s->source_node_id_field,
1170                    (fw_parent_device(s->unit)->card->node_id << CIP_SID_SHIFT) & CIP_SID_MASK);
1171 }
1172 EXPORT_SYMBOL(amdtp_stream_update);
1173
1174 /**
1175  * amdtp_stream_stop - stop sending packets
1176  * @s: the AMDTP stream to stop
1177  *
1178  * All PCM and MIDI devices of the stream must be stopped before the stream
1179  * itself can be stopped.
1180  */
1181 static void amdtp_stream_stop(struct amdtp_stream *s)
1182 {
1183         mutex_lock(&s->mutex);
1184
1185         if (!amdtp_stream_running(s)) {
1186                 mutex_unlock(&s->mutex);
1187                 return;
1188         }
1189
1190         tasklet_kill(&s->period_tasklet);
1191         fw_iso_context_stop(s->context);
1192         fw_iso_context_destroy(s->context);
1193         s->context = ERR_PTR(-1);
1194         iso_packets_buffer_destroy(&s->buffer, s->unit);
1195         kfree(s->pkt_descs);
1196
1197         s->callbacked = false;
1198
1199         mutex_unlock(&s->mutex);
1200 }
1201
1202 /**
1203  * amdtp_stream_pcm_abort - abort the running PCM device
1204  * @s: the AMDTP stream about to be stopped
1205  *
1206  * If the isochronous stream needs to be stopped asynchronously, call this
1207  * function first to stop the PCM device.
1208  */
1209 void amdtp_stream_pcm_abort(struct amdtp_stream *s)
1210 {
1211         struct snd_pcm_substream *pcm;
1212
1213         pcm = READ_ONCE(s->pcm);
1214         if (pcm)
1215                 snd_pcm_stop_xrun(pcm);
1216 }
1217 EXPORT_SYMBOL(amdtp_stream_pcm_abort);
1218
1219 /**
1220  * amdtp_domain_init - initialize an AMDTP domain structure
1221  * @d: the AMDTP domain to initialize.
1222  */
1223 int amdtp_domain_init(struct amdtp_domain *d)
1224 {
1225         INIT_LIST_HEAD(&d->streams);
1226
1227         d->events_per_period = 0;
1228
1229         return 0;
1230 }
1231 EXPORT_SYMBOL_GPL(amdtp_domain_init);
1232
1233 /**
1234  * amdtp_domain_destroy - destroy an AMDTP domain structure
1235  * @d: the AMDTP domain to destroy.
1236  */
1237 void amdtp_domain_destroy(struct amdtp_domain *d)
1238 {
1239         // At present nothing to do.
1240         return;
1241 }
1242 EXPORT_SYMBOL_GPL(amdtp_domain_destroy);
1243
1244 /**
1245  * amdtp_domain_add_stream - register isoc context into the domain.
1246  * @d: the AMDTP domain.
1247  * @s: the AMDTP stream.
1248  * @channel: the isochronous channel on the bus.
1249  * @speed: firewire speed code.
1250  */
1251 int amdtp_domain_add_stream(struct amdtp_domain *d, struct amdtp_stream *s,
1252                             int channel, int speed)
1253 {
1254         struct amdtp_stream *tmp;
1255
1256         list_for_each_entry(tmp, &d->streams, list) {
1257                 if (s == tmp)
1258                         return -EBUSY;
1259         }
1260
1261         list_add(&s->list, &d->streams);
1262
1263         s->channel = channel;
1264         s->speed = speed;
1265
1266         return 0;
1267 }
1268 EXPORT_SYMBOL_GPL(amdtp_domain_add_stream);
1269
1270 /**
1271  * amdtp_domain_start - start sending packets for isoc context in the domain.
1272  * @d: the AMDTP domain.
1273  */
1274 int amdtp_domain_start(struct amdtp_domain *d)
1275 {
1276         struct amdtp_stream *s;
1277         int err = 0;
1278
1279         list_for_each_entry(s, &d->streams, list) {
1280                 err = amdtp_stream_start(s, s->channel, s->speed, d);
1281                 if (err < 0)
1282                         break;
1283         }
1284
1285         if (err < 0) {
1286                 list_for_each_entry(s, &d->streams, list)
1287                         amdtp_stream_stop(s);
1288         }
1289
1290         return err;
1291 }
1292 EXPORT_SYMBOL_GPL(amdtp_domain_start);
1293
1294 /**
1295  * amdtp_domain_stop - stop sending packets for isoc context in the same domain.
1296  * @d: the AMDTP domain to which the isoc contexts belong.
1297  */
1298 void amdtp_domain_stop(struct amdtp_domain *d)
1299 {
1300         struct amdtp_stream *s, *next;
1301
1302         list_for_each_entry_safe(s, next, &d->streams, list) {
1303                 list_del(&s->list);
1304
1305                 amdtp_stream_stop(s);
1306         }
1307
1308         d->events_per_period = 0;
1309 }
1310 EXPORT_SYMBOL_GPL(amdtp_domain_stop);