ALSA: firewire-lib: code refactoring to queueing packets
[linux-2.6-microblaze.git] / sound / firewire / amdtp-stream.c
1 /*
2  * Audio and Music Data Transmission Protocol (IEC 61883-6) streams
3  * with Common Isochronous Packet (IEC 61883-1) headers
4  *
5  * Copyright (c) Clemens Ladisch <clemens@ladisch.de>
6  * Licensed under the terms of the GNU General Public License, version 2.
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 /* TODO: make these configurable */
56 #define INTERRUPT_INTERVAL      16
57 #define QUEUE_LENGTH            48
58
59 // For iso header, tstamp and 2 CIP header.
60 #define IR_CTX_HEADER_SIZE_CIP          16
61 // For iso header and tstamp.
62 #define IR_CTX_HEADER_SIZE_NO_CIP       8
63 #define HEADER_TSTAMP_MASK      0x0000ffff
64
65 static void pcm_period_tasklet(unsigned long data);
66
67 /**
68  * amdtp_stream_init - initialize an AMDTP stream structure
69  * @s: the AMDTP stream to initialize
70  * @unit: the target of the stream
71  * @dir: the direction of stream
72  * @flags: the packet transmission method to use
73  * @fmt: the value of fmt field in CIP header
74  * @process_data_blocks: callback handler to process data blocks
75  * @protocol_size: the size to allocate newly for protocol
76  */
77 int amdtp_stream_init(struct amdtp_stream *s, struct fw_unit *unit,
78                       enum amdtp_stream_direction dir, enum cip_flags flags,
79                       unsigned int fmt,
80                       amdtp_stream_process_data_blocks_t process_data_blocks,
81                       unsigned int protocol_size)
82 {
83         if (process_data_blocks == NULL)
84                 return -EINVAL;
85
86         s->protocol = kzalloc(protocol_size, GFP_KERNEL);
87         if (!s->protocol)
88                 return -ENOMEM;
89
90         s->unit = unit;
91         s->direction = dir;
92         s->flags = flags;
93         s->context = ERR_PTR(-1);
94         mutex_init(&s->mutex);
95         tasklet_init(&s->period_tasklet, pcm_period_tasklet, (unsigned long)s);
96         s->packet_index = 0;
97
98         init_waitqueue_head(&s->callback_wait);
99         s->callbacked = false;
100
101         s->fmt = fmt;
102         s->process_data_blocks = process_data_blocks;
103
104         return 0;
105 }
106 EXPORT_SYMBOL(amdtp_stream_init);
107
108 /**
109  * amdtp_stream_destroy - free stream resources
110  * @s: the AMDTP stream to destroy
111  */
112 void amdtp_stream_destroy(struct amdtp_stream *s)
113 {
114         /* Not initialized. */
115         if (s->protocol == NULL)
116                 return;
117
118         WARN_ON(amdtp_stream_running(s));
119         kfree(s->protocol);
120         mutex_destroy(&s->mutex);
121 }
122 EXPORT_SYMBOL(amdtp_stream_destroy);
123
124 const unsigned int amdtp_syt_intervals[CIP_SFC_COUNT] = {
125         [CIP_SFC_32000]  =  8,
126         [CIP_SFC_44100]  =  8,
127         [CIP_SFC_48000]  =  8,
128         [CIP_SFC_88200]  = 16,
129         [CIP_SFC_96000]  = 16,
130         [CIP_SFC_176400] = 32,
131         [CIP_SFC_192000] = 32,
132 };
133 EXPORT_SYMBOL(amdtp_syt_intervals);
134
135 const unsigned int amdtp_rate_table[CIP_SFC_COUNT] = {
136         [CIP_SFC_32000]  =  32000,
137         [CIP_SFC_44100]  =  44100,
138         [CIP_SFC_48000]  =  48000,
139         [CIP_SFC_88200]  =  88200,
140         [CIP_SFC_96000]  =  96000,
141         [CIP_SFC_176400] = 176400,
142         [CIP_SFC_192000] = 192000,
143 };
144 EXPORT_SYMBOL(amdtp_rate_table);
145
146 static int apply_constraint_to_size(struct snd_pcm_hw_params *params,
147                                     struct snd_pcm_hw_rule *rule)
148 {
149         struct snd_interval *s = hw_param_interval(params, rule->var);
150         const struct snd_interval *r =
151                 hw_param_interval_c(params, SNDRV_PCM_HW_PARAM_RATE);
152         struct snd_interval t = {0};
153         unsigned int step = 0;
154         int i;
155
156         for (i = 0; i < CIP_SFC_COUNT; ++i) {
157                 if (snd_interval_test(r, amdtp_rate_table[i]))
158                         step = max(step, amdtp_syt_intervals[i]);
159         }
160
161         t.min = roundup(s->min, step);
162         t.max = rounddown(s->max, step);
163         t.integer = 1;
164
165         return snd_interval_refine(s, &t);
166 }
167
168 /**
169  * amdtp_stream_add_pcm_hw_constraints - add hw constraints for PCM substream
170  * @s:          the AMDTP stream, which must be initialized.
171  * @runtime:    the PCM substream runtime
172  */
173 int amdtp_stream_add_pcm_hw_constraints(struct amdtp_stream *s,
174                                         struct snd_pcm_runtime *runtime)
175 {
176         struct snd_pcm_hardware *hw = &runtime->hw;
177         int err;
178
179         hw->info = SNDRV_PCM_INFO_BATCH |
180                    SNDRV_PCM_INFO_BLOCK_TRANSFER |
181                    SNDRV_PCM_INFO_INTERLEAVED |
182                    SNDRV_PCM_INFO_JOINT_DUPLEX |
183                    SNDRV_PCM_INFO_MMAP |
184                    SNDRV_PCM_INFO_MMAP_VALID;
185
186         /* SNDRV_PCM_INFO_BATCH */
187         hw->periods_min = 2;
188         hw->periods_max = UINT_MAX;
189
190         /* bytes for a frame */
191         hw->period_bytes_min = 4 * hw->channels_max;
192
193         /* Just to prevent from allocating much pages. */
194         hw->period_bytes_max = hw->period_bytes_min * 2048;
195         hw->buffer_bytes_max = hw->period_bytes_max * hw->periods_min;
196
197         /*
198          * Currently firewire-lib processes 16 packets in one software
199          * interrupt callback. This equals to 2msec but actually the
200          * interval of the interrupts has a jitter.
201          * Additionally, even if adding a constraint to fit period size to
202          * 2msec, actual calculated frames per period doesn't equal to 2msec,
203          * depending on sampling rate.
204          * Anyway, the interval to call snd_pcm_period_elapsed() cannot 2msec.
205          * Here let us use 5msec for safe period interrupt.
206          */
207         err = snd_pcm_hw_constraint_minmax(runtime,
208                                            SNDRV_PCM_HW_PARAM_PERIOD_TIME,
209                                            5000, UINT_MAX);
210         if (err < 0)
211                 goto end;
212
213         /* Non-Blocking stream has no more constraints */
214         if (!(s->flags & CIP_BLOCKING))
215                 goto end;
216
217         /*
218          * One AMDTP packet can include some frames. In blocking mode, the
219          * number equals to SYT_INTERVAL. So the number is 8, 16 or 32,
220          * depending on its sampling rate. For accurate period interrupt, it's
221          * preferrable to align period/buffer sizes to current SYT_INTERVAL.
222          */
223         err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
224                                   apply_constraint_to_size, NULL,
225                                   SNDRV_PCM_HW_PARAM_PERIOD_SIZE,
226                                   SNDRV_PCM_HW_PARAM_RATE, -1);
227         if (err < 0)
228                 goto end;
229         err = snd_pcm_hw_rule_add(runtime, 0, SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
230                                   apply_constraint_to_size, NULL,
231                                   SNDRV_PCM_HW_PARAM_BUFFER_SIZE,
232                                   SNDRV_PCM_HW_PARAM_RATE, -1);
233         if (err < 0)
234                 goto end;
235 end:
236         return err;
237 }
238 EXPORT_SYMBOL(amdtp_stream_add_pcm_hw_constraints);
239
240 /**
241  * amdtp_stream_set_parameters - set stream parameters
242  * @s: the AMDTP stream to configure
243  * @rate: the sample rate
244  * @data_block_quadlets: the size of a data block in quadlet unit
245  *
246  * The parameters must be set before the stream is started, and must not be
247  * changed while the stream is running.
248  */
249 int amdtp_stream_set_parameters(struct amdtp_stream *s, unsigned int rate,
250                                 unsigned int data_block_quadlets)
251 {
252         unsigned int sfc;
253
254         for (sfc = 0; sfc < ARRAY_SIZE(amdtp_rate_table); ++sfc) {
255                 if (amdtp_rate_table[sfc] == rate)
256                         break;
257         }
258         if (sfc == ARRAY_SIZE(amdtp_rate_table))
259                 return -EINVAL;
260
261         s->sfc = sfc;
262         s->data_block_quadlets = data_block_quadlets;
263         s->syt_interval = amdtp_syt_intervals[sfc];
264
265         // default buffering in the device.
266         if (s->direction == AMDTP_OUT_STREAM) {
267                 s->ctx_data.rx.transfer_delay =
268                                         TRANSFER_DELAY_TICKS - TICKS_PER_CYCLE;
269
270                 if (s->flags & CIP_BLOCKING) {
271                         // additional buffering needed to adjust for no-data
272                         // packets.
273                         s->ctx_data.rx.transfer_delay +=
274                                 TICKS_PER_SECOND * s->syt_interval / rate;
275                 }
276         }
277
278         return 0;
279 }
280 EXPORT_SYMBOL(amdtp_stream_set_parameters);
281
282 /**
283  * amdtp_stream_get_max_payload - get the stream's packet size
284  * @s: the AMDTP stream
285  *
286  * This function must not be called before the stream has been configured
287  * with amdtp_stream_set_parameters().
288  */
289 unsigned int amdtp_stream_get_max_payload(struct amdtp_stream *s)
290 {
291         unsigned int multiplier = 1;
292         unsigned int cip_header_size = 0;
293
294         if (s->flags & CIP_JUMBO_PAYLOAD)
295                 multiplier = 5;
296         if (!(s->flags & CIP_NO_HEADER))
297                 cip_header_size = sizeof(__be32) * 2;
298
299         return cip_header_size +
300                 s->syt_interval * s->data_block_quadlets * sizeof(__be32) * multiplier;
301 }
302 EXPORT_SYMBOL(amdtp_stream_get_max_payload);
303
304 /**
305  * amdtp_stream_pcm_prepare - prepare PCM device for running
306  * @s: the AMDTP stream
307  *
308  * This function should be called from the PCM device's .prepare callback.
309  */
310 void amdtp_stream_pcm_prepare(struct amdtp_stream *s)
311 {
312         tasklet_kill(&s->period_tasklet);
313         s->pcm_buffer_pointer = 0;
314         s->pcm_period_pointer = 0;
315 }
316 EXPORT_SYMBOL(amdtp_stream_pcm_prepare);
317
318 static unsigned int calculate_data_blocks(struct amdtp_stream *s,
319                                           unsigned int syt)
320 {
321         unsigned int phase, data_blocks;
322
323         /* Blocking mode. */
324         if (s->flags & CIP_BLOCKING) {
325                 /* This module generate empty packet for 'no data'. */
326                 if (syt == CIP_SYT_NO_INFO)
327                         data_blocks = 0;
328                 else
329                         data_blocks = s->syt_interval;
330         /* Non-blocking mode. */
331         } else {
332                 if (!cip_sfc_is_base_44100(s->sfc)) {
333                         // Sample_rate / 8000 is an integer, and precomputed.
334                         data_blocks = s->ctx_data.rx.data_block_state;
335                 } else {
336                         phase = s->ctx_data.rx.data_block_state;
337
338                 /*
339                  * This calculates the number of data blocks per packet so that
340                  * 1) the overall rate is correct and exactly synchronized to
341                  *    the bus clock, and
342                  * 2) packets with a rounded-up number of blocks occur as early
343                  *    as possible in the sequence (to prevent underruns of the
344                  *    device's buffer).
345                  */
346                         if (s->sfc == CIP_SFC_44100)
347                                 /* 6 6 5 6 5 6 5 ... */
348                                 data_blocks = 5 + ((phase & 1) ^
349                                                    (phase == 0 || phase >= 40));
350                         else
351                                 /* 12 11 11 11 11 ... or 23 22 22 22 22 ... */
352                                 data_blocks = 11 * (s->sfc >> 1) + (phase == 0);
353                         if (++phase >= (80 >> (s->sfc >> 1)))
354                                 phase = 0;
355                         s->ctx_data.rx.data_block_state = phase;
356                 }
357         }
358
359         return data_blocks;
360 }
361
362 static unsigned int calculate_syt(struct amdtp_stream *s,
363                                   unsigned int cycle)
364 {
365         unsigned int syt_offset, phase, index, syt;
366
367         if (s->ctx_data.rx.last_syt_offset < TICKS_PER_CYCLE) {
368                 if (!cip_sfc_is_base_44100(s->sfc))
369                         syt_offset = s->ctx_data.rx.last_syt_offset +
370                                      s->ctx_data.rx.syt_offset_state;
371                 else {
372                 /*
373                  * The time, in ticks, of the n'th SYT_INTERVAL sample is:
374                  *   n * SYT_INTERVAL * 24576000 / sample_rate
375                  * Modulo TICKS_PER_CYCLE, the difference between successive
376                  * elements is about 1386.23.  Rounding the results of this
377                  * formula to the SYT precision results in a sequence of
378                  * differences that begins with:
379                  *   1386 1386 1387 1386 1386 1386 1387 1386 1386 1386 1387 ...
380                  * This code generates _exactly_ the same sequence.
381                  */
382                         phase = s->ctx_data.rx.syt_offset_state;
383                         index = phase % 13;
384                         syt_offset = s->ctx_data.rx.last_syt_offset;
385                         syt_offset += 1386 + ((index && !(index & 3)) ||
386                                               phase == 146);
387                         if (++phase >= 147)
388                                 phase = 0;
389                         s->ctx_data.rx.syt_offset_state = phase;
390                 }
391         } else
392                 syt_offset = s->ctx_data.rx.last_syt_offset - TICKS_PER_CYCLE;
393         s->ctx_data.rx.last_syt_offset = syt_offset;
394
395         if (syt_offset < TICKS_PER_CYCLE) {
396                 syt_offset += s->ctx_data.rx.transfer_delay;
397                 syt = (cycle + syt_offset / TICKS_PER_CYCLE) << 12;
398                 syt += syt_offset % TICKS_PER_CYCLE;
399
400                 return syt & CIP_SYT_MASK;
401         } else {
402                 return CIP_SYT_NO_INFO;
403         }
404 }
405
406 static void update_pcm_pointers(struct amdtp_stream *s,
407                                 struct snd_pcm_substream *pcm,
408                                 unsigned int frames)
409 {
410         unsigned int ptr;
411
412         ptr = s->pcm_buffer_pointer + frames;
413         if (ptr >= pcm->runtime->buffer_size)
414                 ptr -= pcm->runtime->buffer_size;
415         WRITE_ONCE(s->pcm_buffer_pointer, ptr);
416
417         s->pcm_period_pointer += frames;
418         if (s->pcm_period_pointer >= pcm->runtime->period_size) {
419                 s->pcm_period_pointer -= pcm->runtime->period_size;
420                 tasklet_hi_schedule(&s->period_tasklet);
421         }
422 }
423
424 static void pcm_period_tasklet(unsigned long data)
425 {
426         struct amdtp_stream *s = (void *)data;
427         struct snd_pcm_substream *pcm = READ_ONCE(s->pcm);
428
429         if (pcm)
430                 snd_pcm_period_elapsed(pcm);
431 }
432
433 static int queue_packet(struct amdtp_stream *s, struct fw_iso_packet *params)
434 {
435         int err;
436
437         params->interrupt = IS_ALIGNED(s->packet_index + 1, INTERRUPT_INTERVAL);
438         params->tag = s->tag;
439         params->sy = 0;
440
441         err = fw_iso_context_queue(s->context, params, &s->buffer.iso_buffer,
442                                    s->buffer.packets[s->packet_index].offset);
443         if (err < 0) {
444                 dev_err(&s->unit->device, "queueing error: %d\n", err);
445                 goto end;
446         }
447
448         if (++s->packet_index >= QUEUE_LENGTH)
449                 s->packet_index = 0;
450 end:
451         return err;
452 }
453
454 static inline int queue_out_packet(struct amdtp_stream *s,
455                                    struct fw_iso_packet *params,
456                                    unsigned int payload_length)
457 {
458         // No header for this packet.
459         params->header_length = 0;
460         params->payload_length = payload_length;
461         params->skip = !!(payload_length == 0);
462         return queue_packet(s, params);
463 }
464
465 static inline int queue_in_packet(struct amdtp_stream *s,
466                                   struct fw_iso_packet *params)
467 {
468         // Queue one packet for IR context.
469         params->header_length = s->ctx_data.tx.ctx_header_size;
470         params->payload_length = s->ctx_data.tx.max_ctx_payload_length;
471         params->skip = false;
472         return queue_packet(s, params);
473 }
474
475 static void generate_cip_header(struct amdtp_stream *s, __be32 cip_header[2],
476                                 unsigned int syt)
477 {
478         cip_header[0] = cpu_to_be32(READ_ONCE(s->source_node_id_field) |
479                                 (s->data_block_quadlets << CIP_DBS_SHIFT) |
480                                 ((s->sph << CIP_SPH_SHIFT) & CIP_SPH_MASK) |
481                                 s->data_block_counter);
482         cip_header[1] = cpu_to_be32(CIP_EOH |
483                         ((s->fmt << CIP_FMT_SHIFT) & CIP_FMT_MASK) |
484                         ((s->ctx_data.rx.fdf << CIP_FDF_SHIFT) & CIP_FDF_MASK) |
485                         (syt & CIP_SYT_MASK));
486 }
487
488 static int handle_out_packet(struct amdtp_stream *s, unsigned int cycle,
489                              const __be32 *ctx_header, __be32 *buffer,
490                              unsigned int index)
491 {
492         unsigned int syt;
493         unsigned int data_blocks;
494         unsigned int payload_length;
495         __be32 *cip_header;
496         unsigned int pcm_frames;
497         struct snd_pcm_substream *pcm;
498         struct fw_iso_packet params = {0};
499
500         syt = calculate_syt(s, cycle);
501         data_blocks = calculate_data_blocks(s, syt);
502
503         payload_length = data_blocks * sizeof(__be32) * s->data_block_quadlets;
504         if (!(s->flags & CIP_NO_HEADER)) {
505                 cip_header = buffer;
506                 buffer += 2;
507                 payload_length += 2 * sizeof(__be32);
508         } else {
509                 cip_header = NULL;
510         }
511
512         pcm_frames = s->process_data_blocks(s, buffer, data_blocks, &syt);
513
514         if (s->flags & CIP_DBC_IS_END_EVENT)
515                 s->data_block_counter =
516                                 (s->data_block_counter + data_blocks) & 0xff;
517
518         if (cip_header)
519                 generate_cip_header(s, cip_header, syt);
520
521         if (!(s->flags & CIP_DBC_IS_END_EVENT))
522                 s->data_block_counter =
523                                 (s->data_block_counter + data_blocks) & 0xff;
524
525         trace_amdtp_packet(s, cycle, cip_header, payload_length, data_blocks,
526                            index);
527
528         if (queue_out_packet(s, &params, payload_length) < 0)
529                 return -EIO;
530
531         pcm = READ_ONCE(s->pcm);
532         if (pcm && pcm_frames > 0)
533                 update_pcm_pointers(s, pcm, pcm_frames);
534
535         return 0;
536 }
537
538 static int check_cip_header(struct amdtp_stream *s, const __be32 *buf,
539                             unsigned int payload_length,
540                             unsigned int *data_blocks, unsigned int *syt)
541 {
542         u32 cip_header[2];
543         unsigned int sph;
544         unsigned int fmt;
545         unsigned int fdf;
546         unsigned int data_block_counter;
547         bool lost;
548
549         cip_header[0] = be32_to_cpu(buf[0]);
550         cip_header[1] = be32_to_cpu(buf[1]);
551
552         /*
553          * This module supports 'Two-quadlet CIP header with SYT field'.
554          * For convenience, also check FMT field is AM824 or not.
555          */
556         if ((((cip_header[0] & CIP_EOH_MASK) == CIP_EOH) ||
557              ((cip_header[1] & CIP_EOH_MASK) != CIP_EOH)) &&
558             (!(s->flags & CIP_HEADER_WITHOUT_EOH))) {
559                 dev_info_ratelimited(&s->unit->device,
560                                 "Invalid CIP header for AMDTP: %08X:%08X\n",
561                                 cip_header[0], cip_header[1]);
562                 return -EAGAIN;
563         }
564
565         /* Check valid protocol or not. */
566         sph = (cip_header[0] & CIP_SPH_MASK) >> CIP_SPH_SHIFT;
567         fmt = (cip_header[1] & CIP_FMT_MASK) >> CIP_FMT_SHIFT;
568         if (sph != s->sph || fmt != s->fmt) {
569                 dev_info_ratelimited(&s->unit->device,
570                                      "Detect unexpected protocol: %08x %08x\n",
571                                      cip_header[0], cip_header[1]);
572                 return -EAGAIN;
573         }
574
575         /* Calculate data blocks */
576         fdf = (cip_header[1] & CIP_FDF_MASK) >> CIP_FDF_SHIFT;
577         if (payload_length < sizeof(__be32) * 2 ||
578             (fmt == CIP_FMT_AM && fdf == AMDTP_FDF_NO_DATA)) {
579                 *data_blocks = 0;
580         } else {
581                 unsigned int data_block_quadlets =
582                                 (cip_header[0] & CIP_DBS_MASK) >> CIP_DBS_SHIFT;
583                 /* avoid division by zero */
584                 if (data_block_quadlets == 0) {
585                         dev_err(&s->unit->device,
586                                 "Detect invalid value in dbs field: %08X\n",
587                                 cip_header[0]);
588                         return -EPROTO;
589                 }
590                 if (s->flags & CIP_WRONG_DBS)
591                         data_block_quadlets = s->data_block_quadlets;
592
593                 *data_blocks = (payload_length / sizeof(__be32) - 2) /
594                                                         data_block_quadlets;
595         }
596
597         /* Check data block counter continuity */
598         data_block_counter = cip_header[0] & CIP_DBC_MASK;
599         if (*data_blocks == 0 && (s->flags & CIP_EMPTY_HAS_WRONG_DBC) &&
600             s->data_block_counter != UINT_MAX)
601                 data_block_counter = s->data_block_counter;
602
603         if (((s->flags & CIP_SKIP_DBC_ZERO_CHECK) &&
604              data_block_counter == s->ctx_data.tx.first_dbc) ||
605             s->data_block_counter == UINT_MAX) {
606                 lost = false;
607         } else if (!(s->flags & CIP_DBC_IS_END_EVENT)) {
608                 lost = data_block_counter != s->data_block_counter;
609         } else {
610                 unsigned int dbc_interval;
611
612                 if (*data_blocks > 0 && s->ctx_data.tx.dbc_interval > 0)
613                         dbc_interval = s->ctx_data.tx.dbc_interval;
614                 else
615                         dbc_interval = *data_blocks;
616
617                 lost = data_block_counter !=
618                        ((s->data_block_counter + dbc_interval) & 0xff);
619         }
620
621         if (lost) {
622                 dev_err(&s->unit->device,
623                         "Detect discontinuity of CIP: %02X %02X\n",
624                         s->data_block_counter, data_block_counter);
625                 return -EIO;
626         }
627
628         *syt = cip_header[1] & CIP_SYT_MASK;
629
630         if (s->flags & CIP_DBC_IS_END_EVENT) {
631                 s->data_block_counter = data_block_counter;
632         } else {
633                 s->data_block_counter =
634                                 (data_block_counter + *data_blocks) & 0xff;
635         }
636
637         return 0;
638 }
639
640 static int handle_in_packet(struct amdtp_stream *s, unsigned int cycle,
641                             const __be32 *ctx_header, __be32 *buffer,
642                             unsigned int index)
643 {
644         unsigned int payload_length;
645         const __be32 *cip_header;
646         unsigned int syt;
647         unsigned int data_blocks;
648         struct snd_pcm_substream *pcm;
649         unsigned int pcm_frames;
650         struct fw_iso_packet params = {0};
651         int err;
652
653         payload_length = be32_to_cpu(ctx_header[0]) >> ISO_DATA_LENGTH_SHIFT;
654         if (payload_length > s->ctx_data.tx.ctx_header_size +
655                                         s->ctx_data.tx.max_ctx_payload_length) {
656                 dev_err(&s->unit->device,
657                         "Detect jumbo payload: %04x %04x\n",
658                         payload_length, s->ctx_data.tx.max_ctx_payload_length);
659                 return -EIO;
660         }
661
662         cip_header = ctx_header + 2;
663         if (!(s->flags & CIP_NO_HEADER)) {
664                 cip_header = &ctx_header[2];
665                 err = check_cip_header(s, cip_header, payload_length,
666                                        &data_blocks, &syt);
667                 if (err < 0) {
668                         if (err != -EAGAIN)
669                                 return err;
670                         pcm_frames = 0;
671                         goto end;
672                 }
673         } else {
674                 cip_header = NULL;
675                 data_blocks = payload_length / 4 / s->data_block_quadlets;
676                 syt = 0;
677         }
678
679         trace_amdtp_packet(s, cycle, cip_header, payload_length, data_blocks,
680                            index);
681
682         pcm_frames = s->process_data_blocks(s, buffer, data_blocks, &syt);
683 end:
684         if (queue_in_packet(s, &params) < 0)
685                 return -EIO;
686
687         pcm = READ_ONCE(s->pcm);
688         if (pcm && pcm_frames > 0)
689                 update_pcm_pointers(s, pcm, pcm_frames);
690
691         return 0;
692 }
693
694 // In CYCLE_TIMER register of IEEE 1394, 7 bits are used to represent second. On
695 // the other hand, in DMA descriptors of 1394 OHCI, 3 bits are used to represent
696 // it. Thus, via Linux firewire subsystem, we can get the 3 bits for second.
697 static inline u32 compute_cycle_count(__be32 ctx_header_tstamp)
698 {
699         u32 tstamp = be32_to_cpu(ctx_header_tstamp) & HEADER_TSTAMP_MASK;
700         return (((tstamp >> 13) & 0x07) * 8000) + (tstamp & 0x1fff);
701 }
702
703 static inline u32 increment_cycle_count(u32 cycle, unsigned int addend)
704 {
705         cycle += addend;
706         if (cycle >= 8 * CYCLES_PER_SECOND)
707                 cycle -= 8 * CYCLES_PER_SECOND;
708         return cycle;
709 }
710
711 // Align to actual cycle count for the packet which is going to be scheduled.
712 // This module queued the same number of isochronous cycle as QUEUE_LENGTH to
713 // skip isochronous cycle, therefore it's OK to just increment the cycle by
714 // QUEUE_LENGTH for scheduled cycle.
715 static inline u32 compute_it_cycle(const __be32 ctx_header_tstamp)
716 {
717         u32 cycle = compute_cycle_count(ctx_header_tstamp);
718         return increment_cycle_count(cycle, QUEUE_LENGTH);
719 }
720
721 static inline void cancel_stream(struct amdtp_stream *s)
722 {
723         s->packet_index = -1;
724         if (in_interrupt())
725                 amdtp_stream_pcm_abort(s);
726         WRITE_ONCE(s->pcm_buffer_pointer, SNDRV_PCM_POS_XRUN);
727 }
728
729 static void out_stream_callback(struct fw_iso_context *context, u32 tstamp,
730                                 size_t header_length, void *header,
731                                 void *private_data)
732 {
733         struct amdtp_stream *s = private_data;
734         const __be32 *ctx_header = header;
735         unsigned int i, packets = header_length / sizeof(*ctx_header);
736
737         if (s->packet_index < 0)
738                 return;
739
740         for (i = 0; i < packets; ++i) {
741                 u32 cycle;
742                 __be32 *buffer;
743
744                 cycle = compute_it_cycle(*ctx_header);
745                 buffer = s->buffer.packets[s->packet_index].buffer;
746
747                 if (handle_out_packet(s, cycle, ctx_header, buffer, i) < 0) {
748                         cancel_stream(s);
749                         return;
750                 }
751
752                 ++ctx_header;
753         }
754
755         fw_iso_context_queue_flush(s->context);
756 }
757
758 static void in_stream_callback(struct fw_iso_context *context, u32 tstamp,
759                                size_t header_length, void *header,
760                                void *private_data)
761 {
762         struct amdtp_stream *s = private_data;
763         unsigned int i, packets;
764         __be32 *ctx_header = header;
765
766         if (s->packet_index < 0)
767                 return;
768
769         // The number of packets in buffer.
770         packets = header_length / s->ctx_data.tx.ctx_header_size;
771
772         for (i = 0; i < packets; i++) {
773                 u32 cycle;
774                 __be32 *buffer;
775
776                 cycle = compute_cycle_count(ctx_header[1]);
777                 buffer = s->buffer.packets[s->packet_index].buffer;
778
779                 if (handle_in_packet(s, cycle, ctx_header, buffer, i) < 0)
780                         break;
781
782                 ctx_header += s->ctx_data.tx.ctx_header_size / sizeof(*ctx_header);
783         }
784
785         /* Queueing error or detecting invalid payload. */
786         if (i < packets) {
787                 cancel_stream(s);
788                 return;
789         }
790
791         fw_iso_context_queue_flush(s->context);
792 }
793
794 /* this is executed one time */
795 static void amdtp_stream_first_callback(struct fw_iso_context *context,
796                                         u32 tstamp, size_t header_length,
797                                         void *header, void *private_data)
798 {
799         struct amdtp_stream *s = private_data;
800         const __be32 *ctx_header = header;
801         u32 cycle;
802
803         /*
804          * For in-stream, first packet has come.
805          * For out-stream, prepared to transmit first packet
806          */
807         s->callbacked = true;
808         wake_up(&s->callback_wait);
809
810         if (s->direction == AMDTP_IN_STREAM) {
811                 cycle = compute_cycle_count(ctx_header[1]);
812
813                 context->callback.sc = in_stream_callback;
814         } else {
815                 cycle = compute_it_cycle(*ctx_header);
816
817                 context->callback.sc = out_stream_callback;
818         }
819
820         s->start_cycle = cycle;
821
822         context->callback.sc(context, tstamp, header_length, header, s);
823 }
824
825 /**
826  * amdtp_stream_start - start transferring packets
827  * @s: the AMDTP stream to start
828  * @channel: the isochronous channel on the bus
829  * @speed: firewire speed code
830  *
831  * The stream cannot be started until it has been configured with
832  * amdtp_stream_set_parameters() and it must be started before any PCM or MIDI
833  * device can be started.
834  */
835 int amdtp_stream_start(struct amdtp_stream *s, int channel, int speed)
836 {
837         static const struct {
838                 unsigned int data_block;
839                 unsigned int syt_offset;
840         } *entry, initial_state[] = {
841                 [CIP_SFC_32000]  = {  4, 3072 },
842                 [CIP_SFC_48000]  = {  6, 1024 },
843                 [CIP_SFC_96000]  = { 12, 1024 },
844                 [CIP_SFC_192000] = { 24, 1024 },
845                 [CIP_SFC_44100]  = {  0,   67 },
846                 [CIP_SFC_88200]  = {  0,   67 },
847                 [CIP_SFC_176400] = {  0,   67 },
848         };
849         unsigned int ctx_header_size;
850         unsigned int max_ctx_payload_size;
851         enum dma_data_direction dir;
852         int type, tag, err;
853
854         mutex_lock(&s->mutex);
855
856         if (WARN_ON(amdtp_stream_running(s) ||
857                     (s->data_block_quadlets < 1))) {
858                 err = -EBADFD;
859                 goto err_unlock;
860         }
861
862         if (s->direction == AMDTP_IN_STREAM) {
863                 s->data_block_counter = UINT_MAX;
864         } else {
865                 entry = &initial_state[s->sfc];
866
867                 s->data_block_counter = 0;
868                 s->ctx_data.rx.data_block_state = entry->data_block;
869                 s->ctx_data.rx.syt_offset_state = entry->syt_offset;
870                 s->ctx_data.rx.last_syt_offset = TICKS_PER_CYCLE;
871         }
872
873         /* initialize packet buffer */
874         if (s->direction == AMDTP_IN_STREAM) {
875                 dir = DMA_FROM_DEVICE;
876                 type = FW_ISO_CONTEXT_RECEIVE;
877                 if (!(s->flags & CIP_NO_HEADER))
878                         ctx_header_size = IR_CTX_HEADER_SIZE_CIP;
879                 else
880                         ctx_header_size = IR_CTX_HEADER_SIZE_NO_CIP;
881         } else {
882                 dir = DMA_TO_DEVICE;
883                 type = FW_ISO_CONTEXT_TRANSMIT;
884                 ctx_header_size = 0;    // No effect for IT context.
885         }
886
887         max_ctx_payload_size = amdtp_stream_get_max_payload(s) -
888                                ctx_header_size;
889
890         err = iso_packets_buffer_init(&s->buffer, s->unit, QUEUE_LENGTH,
891                                       max_ctx_payload_size, dir);
892         if (err < 0)
893                 goto err_unlock;
894
895         s->context = fw_iso_context_create(fw_parent_device(s->unit)->card,
896                                           type, channel, speed, ctx_header_size,
897                                           amdtp_stream_first_callback, s);
898         if (IS_ERR(s->context)) {
899                 err = PTR_ERR(s->context);
900                 if (err == -EBUSY)
901                         dev_err(&s->unit->device,
902                                 "no free stream on this controller\n");
903                 goto err_buffer;
904         }
905
906         amdtp_stream_update(s);
907
908         if (s->direction == AMDTP_IN_STREAM) {
909                 s->ctx_data.tx.max_ctx_payload_length = max_ctx_payload_size;
910                 s->ctx_data.tx.ctx_header_size = ctx_header_size;
911         }
912
913         if (s->flags & CIP_NO_HEADER)
914                 s->tag = TAG_NO_CIP_HEADER;
915         else
916                 s->tag = TAG_CIP;
917
918         s->packet_index = 0;
919         do {
920                 struct fw_iso_packet params;
921                 if (s->direction == AMDTP_IN_STREAM)
922                         err = queue_in_packet(s, &params);
923                 else
924                         err = queue_out_packet(s, &params, 0);
925                 if (err < 0)
926                         goto err_context;
927         } while (s->packet_index > 0);
928
929         /* NOTE: TAG1 matches CIP. This just affects in stream. */
930         tag = FW_ISO_CONTEXT_MATCH_TAG1;
931         if ((s->flags & CIP_EMPTY_WITH_TAG0) || (s->flags & CIP_NO_HEADER))
932                 tag |= FW_ISO_CONTEXT_MATCH_TAG0;
933
934         s->callbacked = false;
935         err = fw_iso_context_start(s->context, -1, 0, tag);
936         if (err < 0)
937                 goto err_context;
938
939         mutex_unlock(&s->mutex);
940
941         return 0;
942
943 err_context:
944         fw_iso_context_destroy(s->context);
945         s->context = ERR_PTR(-1);
946 err_buffer:
947         iso_packets_buffer_destroy(&s->buffer, s->unit);
948 err_unlock:
949         mutex_unlock(&s->mutex);
950
951         return err;
952 }
953 EXPORT_SYMBOL(amdtp_stream_start);
954
955 /**
956  * amdtp_stream_pcm_pointer - get the PCM buffer position
957  * @s: the AMDTP stream that transports the PCM data
958  *
959  * Returns the current buffer position, in frames.
960  */
961 unsigned long amdtp_stream_pcm_pointer(struct amdtp_stream *s)
962 {
963         /*
964          * This function is called in software IRQ context of period_tasklet or
965          * process context.
966          *
967          * When the software IRQ context was scheduled by software IRQ context
968          * of IR/IT contexts, queued packets were already handled. Therefore,
969          * no need to flush the queue in buffer anymore.
970          *
971          * When the process context reach here, some packets will be already
972          * queued in the buffer. These packets should be handled immediately
973          * to keep better granularity of PCM pointer.
974          *
975          * Later, the process context will sometimes schedules software IRQ
976          * context of the period_tasklet. Then, no need to flush the queue by
977          * the same reason as described for IR/IT contexts.
978          */
979         if (!in_interrupt() && amdtp_stream_running(s))
980                 fw_iso_context_flush_completions(s->context);
981
982         return READ_ONCE(s->pcm_buffer_pointer);
983 }
984 EXPORT_SYMBOL(amdtp_stream_pcm_pointer);
985
986 /**
987  * amdtp_stream_pcm_ack - acknowledge queued PCM frames
988  * @s: the AMDTP stream that transfers the PCM frames
989  *
990  * Returns zero always.
991  */
992 int amdtp_stream_pcm_ack(struct amdtp_stream *s)
993 {
994         /*
995          * Process isochronous packets for recent isochronous cycle to handle
996          * queued PCM frames.
997          */
998         if (amdtp_stream_running(s))
999                 fw_iso_context_flush_completions(s->context);
1000
1001         return 0;
1002 }
1003 EXPORT_SYMBOL(amdtp_stream_pcm_ack);
1004
1005 /**
1006  * amdtp_stream_update - update the stream after a bus reset
1007  * @s: the AMDTP stream
1008  */
1009 void amdtp_stream_update(struct amdtp_stream *s)
1010 {
1011         /* Precomputing. */
1012         WRITE_ONCE(s->source_node_id_field,
1013                    (fw_parent_device(s->unit)->card->node_id << CIP_SID_SHIFT) & CIP_SID_MASK);
1014 }
1015 EXPORT_SYMBOL(amdtp_stream_update);
1016
1017 /**
1018  * amdtp_stream_stop - stop sending packets
1019  * @s: the AMDTP stream to stop
1020  *
1021  * All PCM and MIDI devices of the stream must be stopped before the stream
1022  * itself can be stopped.
1023  */
1024 void amdtp_stream_stop(struct amdtp_stream *s)
1025 {
1026         mutex_lock(&s->mutex);
1027
1028         if (!amdtp_stream_running(s)) {
1029                 mutex_unlock(&s->mutex);
1030                 return;
1031         }
1032
1033         tasklet_kill(&s->period_tasklet);
1034         fw_iso_context_stop(s->context);
1035         fw_iso_context_destroy(s->context);
1036         s->context = ERR_PTR(-1);
1037         iso_packets_buffer_destroy(&s->buffer, s->unit);
1038
1039         s->callbacked = false;
1040
1041         mutex_unlock(&s->mutex);
1042 }
1043 EXPORT_SYMBOL(amdtp_stream_stop);
1044
1045 /**
1046  * amdtp_stream_pcm_abort - abort the running PCM device
1047  * @s: the AMDTP stream about to be stopped
1048  *
1049  * If the isochronous stream needs to be stopped asynchronously, call this
1050  * function first to stop the PCM device.
1051  */
1052 void amdtp_stream_pcm_abort(struct amdtp_stream *s)
1053 {
1054         struct snd_pcm_substream *pcm;
1055
1056         pcm = READ_ONCE(s->pcm);
1057         if (pcm)
1058                 snd_pcm_stop_xrun(pcm);
1059 }
1060 EXPORT_SYMBOL(amdtp_stream_pcm_abort);