ALSA: firewire-lib: rename parameter setting function for AM824 with FDF field
[cascardo/linux.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 <sound/rawmidi.h>
17 #include "amdtp-stream.h"
18
19 #define TICKS_PER_CYCLE         3072
20 #define CYCLES_PER_SECOND       8000
21 #define TICKS_PER_SECOND        (TICKS_PER_CYCLE * CYCLES_PER_SECOND)
22
23 /*
24  * Nominally 3125 bytes/second, but the MIDI port's clock might be
25  * 1% too slow, and the bus clock 100 ppm too fast.
26  */
27 #define MIDI_BYTES_PER_SECOND   3093
28
29 /*
30  * Several devices look only at the first eight data blocks.
31  * In any case, this is more than enough for the MIDI data rate.
32  */
33 #define MAX_MIDI_RX_BLOCKS      8
34
35 #define TRANSFER_DELAY_TICKS    0x2e00 /* 479.17 microseconds */
36
37 /* isochronous header parameters */
38 #define ISO_DATA_LENGTH_SHIFT   16
39 #define TAG_CIP                 1
40
41 /* common isochronous packet header parameters */
42 #define CIP_EOH_SHIFT           31
43 #define CIP_EOH                 (1u << CIP_EOH_SHIFT)
44 #define CIP_EOH_MASK            0x80000000
45 #define CIP_SID_SHIFT           24
46 #define CIP_SID_MASK            0x3f000000
47 #define CIP_DBS_MASK            0x00ff0000
48 #define CIP_DBS_SHIFT           16
49 #define CIP_DBC_MASK            0x000000ff
50 #define CIP_FMT_SHIFT           24
51 #define CIP_FMT_MASK            0x3f000000
52 #define CIP_FDF_MASK            0x00ff0000
53 #define CIP_FDF_SHIFT           16
54 #define CIP_SYT_MASK            0x0000ffff
55 #define CIP_SYT_NO_INFO         0xffff
56
57 /* Audio and Music transfer protocol specific parameters */
58 #define CIP_FMT_AM              0x10
59 #define AMDTP_FDF_NO_DATA       0xff
60
61 /* TODO: make these configurable */
62 #define INTERRUPT_INTERVAL      16
63 #define QUEUE_LENGTH            48
64
65 #define IN_PACKET_HEADER_SIZE   4
66 #define OUT_PACKET_HEADER_SIZE  0
67
68 static void pcm_period_tasklet(unsigned long data);
69
70 /**
71  * amdtp_stream_init - initialize an AMDTP stream structure
72  * @s: the AMDTP stream to initialize
73  * @unit: the target of the stream
74  * @dir: the direction of stream
75  * @flags: the packet transmission method to use
76  * @fmt: the value of fmt field in CIP header
77  */
78 int amdtp_stream_init(struct amdtp_stream *s, struct fw_unit *unit,
79                       enum amdtp_stream_direction dir, enum cip_flags flags,
80                       unsigned int fmt)
81 {
82         s->unit = unit;
83         s->direction = dir;
84         s->flags = flags;
85         s->context = ERR_PTR(-1);
86         mutex_init(&s->mutex);
87         tasklet_init(&s->period_tasklet, pcm_period_tasklet, (unsigned long)s);
88         s->packet_index = 0;
89
90         init_waitqueue_head(&s->callback_wait);
91         s->callbacked = false;
92         s->sync_slave = NULL;
93
94         s->fmt = fmt;
95
96         return 0;
97 }
98 EXPORT_SYMBOL(amdtp_stream_init);
99
100 /**
101  * amdtp_stream_destroy - free stream resources
102  * @s: the AMDTP stream to destroy
103  */
104 void amdtp_stream_destroy(struct amdtp_stream *s)
105 {
106         WARN_ON(amdtp_stream_running(s));
107         mutex_destroy(&s->mutex);
108 }
109 EXPORT_SYMBOL(amdtp_stream_destroy);
110
111 const unsigned int amdtp_syt_intervals[CIP_SFC_COUNT] = {
112         [CIP_SFC_32000]  =  8,
113         [CIP_SFC_44100]  =  8,
114         [CIP_SFC_48000]  =  8,
115         [CIP_SFC_88200]  = 16,
116         [CIP_SFC_96000]  = 16,
117         [CIP_SFC_176400] = 32,
118         [CIP_SFC_192000] = 32,
119 };
120 EXPORT_SYMBOL(amdtp_syt_intervals);
121
122 const unsigned int amdtp_rate_table[CIP_SFC_COUNT] = {
123         [CIP_SFC_32000]  =  32000,
124         [CIP_SFC_44100]  =  44100,
125         [CIP_SFC_48000]  =  48000,
126         [CIP_SFC_88200]  =  88200,
127         [CIP_SFC_96000]  =  96000,
128         [CIP_SFC_176400] = 176400,
129         [CIP_SFC_192000] = 192000,
130 };
131 EXPORT_SYMBOL(amdtp_rate_table);
132
133 /**
134  * amdtp_stream_add_pcm_hw_constraints - add hw constraints for PCM substream
135  * @s:          the AMDTP stream, which must be initialized.
136  * @runtime:    the PCM substream runtime
137  */
138 int amdtp_stream_add_pcm_hw_constraints(struct amdtp_stream *s,
139                                         struct snd_pcm_runtime *runtime)
140 {
141         int err;
142
143         /* AM824 in IEC 61883-6 can deliver 24bit data */
144         err = snd_pcm_hw_constraint_msbits(runtime, 0, 32, 24);
145         if (err < 0)
146                 goto end;
147
148         /*
149          * Currently firewire-lib processes 16 packets in one software
150          * interrupt callback. This equals to 2msec but actually the
151          * interval of the interrupts has a jitter.
152          * Additionally, even if adding a constraint to fit period size to
153          * 2msec, actual calculated frames per period doesn't equal to 2msec,
154          * depending on sampling rate.
155          * Anyway, the interval to call snd_pcm_period_elapsed() cannot 2msec.
156          * Here let us use 5msec for safe period interrupt.
157          */
158         err = snd_pcm_hw_constraint_minmax(runtime,
159                                            SNDRV_PCM_HW_PARAM_PERIOD_TIME,
160                                            5000, UINT_MAX);
161         if (err < 0)
162                 goto end;
163
164         /* Non-Blocking stream has no more constraints */
165         if (!(s->flags & CIP_BLOCKING))
166                 goto end;
167
168         /*
169          * One AMDTP packet can include some frames. In blocking mode, the
170          * number equals to SYT_INTERVAL. So the number is 8, 16 or 32,
171          * depending on its sampling rate. For accurate period interrupt, it's
172          * preferrable to align period/buffer sizes to current SYT_INTERVAL.
173          *
174          * TODO: These constraints can be improved with proper rules.
175          * Currently apply LCM of SYT_INTERVALs.
176          */
177         err = snd_pcm_hw_constraint_step(runtime, 0,
178                                          SNDRV_PCM_HW_PARAM_PERIOD_SIZE, 32);
179         if (err < 0)
180                 goto end;
181         err = snd_pcm_hw_constraint_step(runtime, 0,
182                                          SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 32);
183 end:
184         return err;
185 }
186 EXPORT_SYMBOL(amdtp_stream_add_pcm_hw_constraints);
187
188 /**
189  * amdtp_stream_set_parameters - set stream parameters
190  * @s: the AMDTP stream to configure
191  * @rate: the sample rate
192  * @pcm_channels: the number of PCM samples in each data block, to be encoded
193  *                as AM824 multi-bit linear audio
194  * @midi_ports: the number of MIDI ports (i.e., MPX-MIDI Data Channels)
195  * @double_pcm_frames: one data block transfers two PCM frames
196  *
197  * The parameters must be set before the stream is started, and must not be
198  * changed while the stream is running.
199  */
200 int amdtp_stream_set_parameters(struct amdtp_stream *s,
201                                 unsigned int rate,
202                                 unsigned int pcm_channels,
203                                 unsigned int midi_ports)
204 {
205         unsigned int i, sfc, midi_channels;
206
207         midi_channels = DIV_ROUND_UP(midi_ports, 8);
208
209         if (WARN_ON(amdtp_stream_running(s)) ||
210             WARN_ON(pcm_channels > AMDTP_MAX_CHANNELS_FOR_PCM) ||
211             WARN_ON(midi_channels > AMDTP_MAX_CHANNELS_FOR_MIDI))
212                 return -EINVAL;
213
214         for (sfc = 0; sfc < ARRAY_SIZE(amdtp_rate_table); ++sfc) {
215                 if (amdtp_rate_table[sfc] == rate)
216                         break;
217         }
218         if (sfc == ARRAY_SIZE(amdtp_rate_table))
219                 return -EINVAL;
220
221         s->pcm_channels = pcm_channels;
222         s->sfc = sfc;
223         s->data_block_quadlets = s->pcm_channels + midi_channels;
224         s->midi_ports = midi_ports;
225
226         s->syt_interval = amdtp_syt_intervals[sfc];
227
228         /* default buffering in the device */
229         s->transfer_delay = TRANSFER_DELAY_TICKS - TICKS_PER_CYCLE;
230         if (s->flags & CIP_BLOCKING)
231                 /* additional buffering needed to adjust for no-data packets */
232                 s->transfer_delay += TICKS_PER_SECOND * s->syt_interval / rate;
233
234         /* init the position map for PCM and MIDI channels */
235         for (i = 0; i < pcm_channels; i++)
236                 s->pcm_positions[i] = i;
237         s->midi_position = s->pcm_channels;
238
239         /*
240          * We do not know the actual MIDI FIFO size of most devices.  Just
241          * assume two bytes, i.e., one byte can be received over the bus while
242          * the previous one is transmitted over MIDI.
243          * (The value here is adjusted for midi_ratelimit_per_packet().)
244          */
245         s->midi_fifo_limit = rate - MIDI_BYTES_PER_SECOND * s->syt_interval + 1;
246
247         return 0;
248 }
249 EXPORT_SYMBOL(amdtp_stream_set_parameters);
250
251 /**
252  * amdtp_stream_get_max_payload - get the stream's packet size
253  * @s: the AMDTP stream
254  *
255  * This function must not be called before the stream has been configured
256  * with amdtp_stream_set_parameters().
257  */
258 unsigned int amdtp_stream_get_max_payload(struct amdtp_stream *s)
259 {
260         unsigned int multiplier = 1;
261
262         if (s->flags & CIP_JUMBO_PAYLOAD)
263                 multiplier = 5;
264
265         return 8 + s->syt_interval * s->data_block_quadlets * 4 * multiplier;
266 }
267 EXPORT_SYMBOL(amdtp_stream_get_max_payload);
268
269 static void write_pcm_s16(struct amdtp_stream *s,
270                           struct snd_pcm_substream *pcm,
271                           __be32 *buffer, unsigned int frames);
272 static void write_pcm_s32(struct amdtp_stream *s,
273                           struct snd_pcm_substream *pcm,
274                           __be32 *buffer, unsigned int frames);
275 static void read_pcm_s32(struct amdtp_stream *s,
276                          struct snd_pcm_substream *pcm,
277                          __be32 *buffer, unsigned int frames);
278
279 /**
280  * amdtp_stream_set_pcm_format - set the PCM format
281  * @s: the AMDTP stream to configure
282  * @format: the format of the ALSA PCM device
283  *
284  * The sample format must be set after the other parameters (rate/PCM channels/
285  * MIDI) and before the stream is started, and must not be changed while the
286  * stream is running.
287  */
288 void amdtp_stream_set_pcm_format(struct amdtp_stream *s,
289                                  snd_pcm_format_t format)
290 {
291         if (WARN_ON(amdtp_stream_pcm_running(s)))
292                 return;
293
294         switch (format) {
295         default:
296                 WARN_ON(1);
297                 /* fall through */
298         case SNDRV_PCM_FORMAT_S16:
299                 if (s->direction == AMDTP_OUT_STREAM) {
300                         s->transfer_samples = write_pcm_s16;
301                         break;
302                 }
303                 WARN_ON(1);
304                 /* fall through */
305         case SNDRV_PCM_FORMAT_S32:
306                 if (s->direction == AMDTP_OUT_STREAM)
307                         s->transfer_samples = write_pcm_s32;
308                 else
309                         s->transfer_samples = read_pcm_s32;
310                 break;
311         }
312 }
313 EXPORT_SYMBOL(amdtp_stream_set_pcm_format);
314
315 /**
316  * amdtp_stream_pcm_prepare - prepare PCM device for running
317  * @s: the AMDTP stream
318  *
319  * This function should be called from the PCM device's .prepare callback.
320  */
321 void amdtp_stream_pcm_prepare(struct amdtp_stream *s)
322 {
323         tasklet_kill(&s->period_tasklet);
324         s->pcm_buffer_pointer = 0;
325         s->pcm_period_pointer = 0;
326         s->pointer_flush = true;
327 }
328 EXPORT_SYMBOL(amdtp_stream_pcm_prepare);
329
330 static unsigned int calculate_data_blocks(struct amdtp_stream *s,
331                                           unsigned int syt)
332 {
333         unsigned int phase, data_blocks;
334
335         /* Blocking mode. */
336         if (s->flags & CIP_BLOCKING) {
337                 /* This module generate empty packet for 'no data'. */
338                 if (syt == CIP_SYT_NO_INFO)
339                         data_blocks = 0;
340                 else
341                         data_blocks = s->syt_interval;
342         /* Non-blocking mode. */
343         } else {
344                 if (!cip_sfc_is_base_44100(s->sfc)) {
345                         /* Sample_rate / 8000 is an integer, and precomputed. */
346                         data_blocks = s->data_block_state;
347                 } else {
348                         phase = s->data_block_state;
349
350                 /*
351                  * This calculates the number of data blocks per packet so that
352                  * 1) the overall rate is correct and exactly synchronized to
353                  *    the bus clock, and
354                  * 2) packets with a rounded-up number of blocks occur as early
355                  *    as possible in the sequence (to prevent underruns of the
356                  *    device's buffer).
357                  */
358                         if (s->sfc == CIP_SFC_44100)
359                                 /* 6 6 5 6 5 6 5 ... */
360                                 data_blocks = 5 + ((phase & 1) ^
361                                                    (phase == 0 || phase >= 40));
362                         else
363                                 /* 12 11 11 11 11 ... or 23 22 22 22 22 ... */
364                                 data_blocks = 11 * (s->sfc >> 1) + (phase == 0);
365                         if (++phase >= (80 >> (s->sfc >> 1)))
366                                 phase = 0;
367                         s->data_block_state = phase;
368                 }
369         }
370
371         return data_blocks;
372 }
373
374 static unsigned int calculate_syt(struct amdtp_stream *s,
375                                   unsigned int cycle)
376 {
377         unsigned int syt_offset, phase, index, syt;
378
379         if (s->last_syt_offset < TICKS_PER_CYCLE) {
380                 if (!cip_sfc_is_base_44100(s->sfc))
381                         syt_offset = s->last_syt_offset + s->syt_offset_state;
382                 else {
383                 /*
384                  * The time, in ticks, of the n'th SYT_INTERVAL sample is:
385                  *   n * SYT_INTERVAL * 24576000 / sample_rate
386                  * Modulo TICKS_PER_CYCLE, the difference between successive
387                  * elements is about 1386.23.  Rounding the results of this
388                  * formula to the SYT precision results in a sequence of
389                  * differences that begins with:
390                  *   1386 1386 1387 1386 1386 1386 1387 1386 1386 1386 1387 ...
391                  * This code generates _exactly_ the same sequence.
392                  */
393                         phase = s->syt_offset_state;
394                         index = phase % 13;
395                         syt_offset = s->last_syt_offset;
396                         syt_offset += 1386 + ((index && !(index & 3)) ||
397                                               phase == 146);
398                         if (++phase >= 147)
399                                 phase = 0;
400                         s->syt_offset_state = phase;
401                 }
402         } else
403                 syt_offset = s->last_syt_offset - TICKS_PER_CYCLE;
404         s->last_syt_offset = syt_offset;
405
406         if (syt_offset < TICKS_PER_CYCLE) {
407                 syt_offset += s->transfer_delay;
408                 syt = (cycle + syt_offset / TICKS_PER_CYCLE) << 12;
409                 syt += syt_offset % TICKS_PER_CYCLE;
410
411                 return syt & CIP_SYT_MASK;
412         } else {
413                 return CIP_SYT_NO_INFO;
414         }
415 }
416
417 static void write_pcm_s32(struct amdtp_stream *s,
418                           struct snd_pcm_substream *pcm,
419                           __be32 *buffer, unsigned int frames)
420 {
421         struct snd_pcm_runtime *runtime = pcm->runtime;
422         unsigned int channels, remaining_frames, i, c;
423         const u32 *src;
424
425         channels = s->pcm_channels;
426         src = (void *)runtime->dma_area +
427                         frames_to_bytes(runtime, s->pcm_buffer_pointer);
428         remaining_frames = runtime->buffer_size - s->pcm_buffer_pointer;
429
430         for (i = 0; i < frames; ++i) {
431                 for (c = 0; c < channels; ++c) {
432                         buffer[s->pcm_positions[c]] =
433                                         cpu_to_be32((*src >> 8) | 0x40000000);
434                         src++;
435                 }
436                 buffer += s->data_block_quadlets;
437                 if (--remaining_frames == 0)
438                         src = (void *)runtime->dma_area;
439         }
440 }
441
442 static void write_pcm_s16(struct amdtp_stream *s,
443                           struct snd_pcm_substream *pcm,
444                           __be32 *buffer, unsigned int frames)
445 {
446         struct snd_pcm_runtime *runtime = pcm->runtime;
447         unsigned int channels, remaining_frames, i, c;
448         const u16 *src;
449
450         channels = s->pcm_channels;
451         src = (void *)runtime->dma_area +
452                         frames_to_bytes(runtime, s->pcm_buffer_pointer);
453         remaining_frames = runtime->buffer_size - s->pcm_buffer_pointer;
454
455         for (i = 0; i < frames; ++i) {
456                 for (c = 0; c < channels; ++c) {
457                         buffer[s->pcm_positions[c]] =
458                                         cpu_to_be32((*src << 8) | 0x42000000);
459                         src++;
460                 }
461                 buffer += s->data_block_quadlets;
462                 if (--remaining_frames == 0)
463                         src = (void *)runtime->dma_area;
464         }
465 }
466
467 static void read_pcm_s32(struct amdtp_stream *s,
468                          struct snd_pcm_substream *pcm,
469                          __be32 *buffer, unsigned int frames)
470 {
471         struct snd_pcm_runtime *runtime = pcm->runtime;
472         unsigned int channels, remaining_frames, i, c;
473         u32 *dst;
474
475         channels = s->pcm_channels;
476         dst  = (void *)runtime->dma_area +
477                         frames_to_bytes(runtime, s->pcm_buffer_pointer);
478         remaining_frames = runtime->buffer_size - s->pcm_buffer_pointer;
479
480         for (i = 0; i < frames; ++i) {
481                 for (c = 0; c < channels; ++c) {
482                         *dst = be32_to_cpu(buffer[s->pcm_positions[c]]) << 8;
483                         dst++;
484                 }
485                 buffer += s->data_block_quadlets;
486                 if (--remaining_frames == 0)
487                         dst = (void *)runtime->dma_area;
488         }
489 }
490
491 static void write_pcm_silence(struct amdtp_stream *s,
492                               __be32 *buffer, unsigned int frames)
493 {
494         unsigned int i, c;
495
496         for (i = 0; i < frames; ++i) {
497                 for (c = 0; c < s->pcm_channels; ++c)
498                         buffer[s->pcm_positions[c]] = cpu_to_be32(0x40000000);
499                 buffer += s->data_block_quadlets;
500         }
501 }
502
503 /*
504  * To avoid sending MIDI bytes at too high a rate, assume that the receiving
505  * device has a FIFO, and track how much it is filled.  This values increases
506  * by one whenever we send one byte in a packet, but the FIFO empties at
507  * a constant rate independent of our packet rate.  One packet has syt_interval
508  * samples, so the number of bytes that empty out of the FIFO, per packet(!),
509  * is MIDI_BYTES_PER_SECOND * syt_interval / sample_rate.  To avoid storing
510  * fractional values, the values in midi_fifo_used[] are measured in bytes
511  * multiplied by the sample rate.
512  */
513 static bool midi_ratelimit_per_packet(struct amdtp_stream *s, unsigned int port)
514 {
515         int used;
516
517         used = s->midi_fifo_used[port];
518         if (used == 0) /* common shortcut */
519                 return true;
520
521         used -= MIDI_BYTES_PER_SECOND * s->syt_interval;
522         used = max(used, 0);
523         s->midi_fifo_used[port] = used;
524
525         return used < s->midi_fifo_limit;
526 }
527
528 static void midi_rate_use_one_byte(struct amdtp_stream *s, unsigned int port)
529 {
530         s->midi_fifo_used[port] += amdtp_rate_table[s->sfc];
531 }
532
533 static void write_midi_messages(struct amdtp_stream *s,
534                                 __be32 *buffer, unsigned int frames)
535 {
536         unsigned int f, port;
537         u8 *b;
538
539         for (f = 0; f < frames; f++) {
540                 b = (u8 *)&buffer[s->midi_position];
541
542                 port = (s->data_block_counter + f) % 8;
543                 if (f < MAX_MIDI_RX_BLOCKS &&
544                     midi_ratelimit_per_packet(s, port) &&
545                     s->midi[port] != NULL &&
546                     snd_rawmidi_transmit(s->midi[port], &b[1], 1) == 1) {
547                         midi_rate_use_one_byte(s, port);
548                         b[0] = 0x81;
549                 } else {
550                         b[0] = 0x80;
551                         b[1] = 0;
552                 }
553                 b[2] = 0;
554                 b[3] = 0;
555
556                 buffer += s->data_block_quadlets;
557         }
558 }
559
560 static void read_midi_messages(struct amdtp_stream *s,
561                                __be32 *buffer, unsigned int frames)
562 {
563         unsigned int f, port;
564         int len;
565         u8 *b;
566
567         for (f = 0; f < frames; f++) {
568                 port = (s->data_block_counter + f) % 8;
569                 b = (u8 *)&buffer[s->midi_position];
570
571                 len = b[0] - 0x80;
572                 if ((1 <= len) &&  (len <= 3) && (s->midi[port]))
573                         snd_rawmidi_receive(s->midi[port], b + 1, len);
574
575                 buffer += s->data_block_quadlets;
576         }
577 }
578
579 static void update_pcm_pointers(struct amdtp_stream *s,
580                                 struct snd_pcm_substream *pcm,
581                                 unsigned int frames)
582 {
583         unsigned int ptr;
584
585         ptr = s->pcm_buffer_pointer + frames;
586         if (ptr >= pcm->runtime->buffer_size)
587                 ptr -= pcm->runtime->buffer_size;
588         ACCESS_ONCE(s->pcm_buffer_pointer) = ptr;
589
590         s->pcm_period_pointer += frames;
591         if (s->pcm_period_pointer >= pcm->runtime->period_size) {
592                 s->pcm_period_pointer -= pcm->runtime->period_size;
593                 s->pointer_flush = false;
594                 tasklet_hi_schedule(&s->period_tasklet);
595         }
596 }
597
598 static void pcm_period_tasklet(unsigned long data)
599 {
600         struct amdtp_stream *s = (void *)data;
601         struct snd_pcm_substream *pcm = ACCESS_ONCE(s->pcm);
602
603         if (pcm)
604                 snd_pcm_period_elapsed(pcm);
605 }
606
607 static int queue_packet(struct amdtp_stream *s,
608                         unsigned int header_length,
609                         unsigned int payload_length, bool skip)
610 {
611         struct fw_iso_packet p = {0};
612         int err = 0;
613
614         if (IS_ERR(s->context))
615                 goto end;
616
617         p.interrupt = IS_ALIGNED(s->packet_index + 1, INTERRUPT_INTERVAL);
618         p.tag = TAG_CIP;
619         p.header_length = header_length;
620         p.payload_length = (!skip) ? payload_length : 0;
621         p.skip = skip;
622         err = fw_iso_context_queue(s->context, &p, &s->buffer.iso_buffer,
623                                    s->buffer.packets[s->packet_index].offset);
624         if (err < 0) {
625                 dev_err(&s->unit->device, "queueing error: %d\n", err);
626                 goto end;
627         }
628
629         if (++s->packet_index >= QUEUE_LENGTH)
630                 s->packet_index = 0;
631 end:
632         return err;
633 }
634
635 static inline int queue_out_packet(struct amdtp_stream *s,
636                                    unsigned int payload_length, bool skip)
637 {
638         return queue_packet(s, OUT_PACKET_HEADER_SIZE,
639                             payload_length, skip);
640 }
641
642 static inline int queue_in_packet(struct amdtp_stream *s)
643 {
644         return queue_packet(s, IN_PACKET_HEADER_SIZE,
645                             amdtp_stream_get_max_payload(s), false);
646 }
647
648 unsigned int process_rx_data_blocks(struct amdtp_stream *s, __be32 *buffer,
649                                     unsigned int data_blocks, unsigned int *syt)
650 {
651         struct snd_pcm_substream *pcm = ACCESS_ONCE(s->pcm);
652         unsigned int pcm_frames;
653
654         if (pcm) {
655                 s->transfer_samples(s, pcm, buffer, data_blocks);
656                 pcm_frames = data_blocks * s->frame_multiplier;
657         } else {
658                 write_pcm_silence(s, buffer, data_blocks);
659                 pcm_frames = 0;
660         }
661
662         if (s->midi_ports)
663                 write_midi_messages(s, buffer, data_blocks);
664
665         return pcm_frames;
666 }
667
668 static int handle_out_packet(struct amdtp_stream *s, unsigned int data_blocks,
669                              unsigned int syt)
670 {
671         __be32 *buffer;
672         unsigned int payload_length;
673         unsigned int pcm_frames;
674         struct snd_pcm_substream *pcm;
675
676         buffer = s->buffer.packets[s->packet_index].buffer;
677         pcm_frames = process_rx_data_blocks(s, buffer + 2, data_blocks, &syt);
678
679         buffer[0] = cpu_to_be32(ACCESS_ONCE(s->source_node_id_field) |
680                                 (s->data_block_quadlets << CIP_DBS_SHIFT) |
681                                 s->data_block_counter);
682         buffer[1] = cpu_to_be32(CIP_EOH |
683                                 ((s->fmt << CIP_FMT_SHIFT) & CIP_FMT_MASK) |
684                                 ((s->fdf << CIP_FDF_SHIFT) & CIP_FDF_MASK) |
685                                 (syt & CIP_SYT_MASK));
686
687         s->data_block_counter = (s->data_block_counter + data_blocks) & 0xff;
688
689         payload_length = 8 + data_blocks * 4 * s->data_block_quadlets;
690         if (queue_out_packet(s, payload_length, false) < 0)
691                 return -EIO;
692
693         pcm = ACCESS_ONCE(s->pcm);
694         if (pcm && pcm_frames > 0)
695                 update_pcm_pointers(s, pcm, pcm_frames);
696
697         /* No need to return the number of handled data blocks. */
698         return 0;
699 }
700
701 unsigned int process_tx_data_blocks(struct amdtp_stream *s, __be32 *buffer,
702                                     unsigned int data_blocks, unsigned int *syt)
703 {
704         struct snd_pcm_substream *pcm = ACCESS_ONCE(s->pcm);
705         unsigned int pcm_frames;
706
707         if (pcm) {
708                 s->transfer_samples(s, pcm, buffer, data_blocks);
709                 pcm_frames = data_blocks * s->frame_multiplier;
710         } else {
711                 pcm_frames = 0;
712         }
713
714         if (s->midi_ports)
715                 read_midi_messages(s, buffer, data_blocks);
716
717         return pcm_frames;
718 }
719
720 static int handle_in_packet(struct amdtp_stream *s,
721                             unsigned int payload_quadlets, __be32 *buffer,
722                             unsigned int *data_blocks, unsigned int syt)
723 {
724         u32 cip_header[2];
725         unsigned int fmt, fdf;
726         unsigned int data_block_quadlets, data_block_counter, dbc_interval;
727         struct snd_pcm_substream *pcm;
728         unsigned int pcm_frames;
729         bool lost;
730
731         cip_header[0] = be32_to_cpu(buffer[0]);
732         cip_header[1] = be32_to_cpu(buffer[1]);
733
734         /*
735          * This module supports 'Two-quadlet CIP header with SYT field'.
736          * For convenience, also check FMT field is AM824 or not.
737          */
738         if (((cip_header[0] & CIP_EOH_MASK) == CIP_EOH) ||
739             ((cip_header[1] & CIP_EOH_MASK) != CIP_EOH)) {
740                 dev_info_ratelimited(&s->unit->device,
741                                 "Invalid CIP header for AMDTP: %08X:%08X\n",
742                                 cip_header[0], cip_header[1]);
743                 *data_blocks = 0;
744                 pcm_frames = 0;
745                 goto end;
746         }
747
748         /* Check valid protocol or not. */
749         fmt = (cip_header[1] & CIP_FMT_MASK) >> CIP_FMT_SHIFT;
750         if (fmt != s->fmt) {
751                 dev_err(&s->unit->device,
752                         "Detect unexpected protocol: %08x %08x\n",
753                         cip_header[0], cip_header[1]);
754                 return -EIO;
755         }
756
757         /* Calculate data blocks */
758         fdf = (cip_header[1] & CIP_FDF_MASK) >> CIP_FDF_SHIFT;
759         if (payload_quadlets < 3 ||
760             (fmt == CIP_FMT_AM && fdf == AMDTP_FDF_NO_DATA)) {
761                 *data_blocks = 0;
762         } else {
763                 data_block_quadlets =
764                         (cip_header[0] & CIP_DBS_MASK) >> CIP_DBS_SHIFT;
765                 /* avoid division by zero */
766                 if (data_block_quadlets == 0) {
767                         dev_err(&s->unit->device,
768                                 "Detect invalid value in dbs field: %08X\n",
769                                 cip_header[0]);
770                         return -EPROTO;
771                 }
772                 if (s->flags & CIP_WRONG_DBS)
773                         data_block_quadlets = s->data_block_quadlets;
774
775                 *data_blocks = (payload_quadlets - 2) / data_block_quadlets;
776         }
777
778         /* Check data block counter continuity */
779         data_block_counter = cip_header[0] & CIP_DBC_MASK;
780         if (*data_blocks == 0 && (s->flags & CIP_EMPTY_HAS_WRONG_DBC) &&
781             s->data_block_counter != UINT_MAX)
782                 data_block_counter = s->data_block_counter;
783
784         if (((s->flags & CIP_SKIP_DBC_ZERO_CHECK) &&
785              data_block_counter == s->tx_first_dbc) ||
786             s->data_block_counter == UINT_MAX) {
787                 lost = false;
788         } else if (!(s->flags & CIP_DBC_IS_END_EVENT)) {
789                 lost = data_block_counter != s->data_block_counter;
790         } else {
791                 if ((*data_blocks > 0) && (s->tx_dbc_interval > 0))
792                         dbc_interval = s->tx_dbc_interval;
793                 else
794                         dbc_interval = *data_blocks;
795
796                 lost = data_block_counter !=
797                        ((s->data_block_counter + dbc_interval) & 0xff);
798         }
799
800         if (lost) {
801                 dev_err(&s->unit->device,
802                         "Detect discontinuity of CIP: %02X %02X\n",
803                         s->data_block_counter, data_block_counter);
804                 return -EIO;
805         }
806
807         pcm_frames = process_tx_data_blocks(s, buffer + 2, *data_blocks, &syt);
808
809         if (s->flags & CIP_DBC_IS_END_EVENT)
810                 s->data_block_counter = data_block_counter;
811         else
812                 s->data_block_counter =
813                                 (data_block_counter + *data_blocks) & 0xff;
814 end:
815         if (queue_in_packet(s) < 0)
816                 return -EIO;
817
818         pcm = ACCESS_ONCE(s->pcm);
819         if (pcm && pcm_frames > 0)
820                 update_pcm_pointers(s, pcm, pcm_frames);
821
822         return 0;
823 }
824
825 static void out_stream_callback(struct fw_iso_context *context, u32 cycle,
826                                 size_t header_length, void *header,
827                                 void *private_data)
828 {
829         struct amdtp_stream *s = private_data;
830         unsigned int i, syt, packets = header_length / 4;
831         unsigned int data_blocks;
832
833         if (s->packet_index < 0)
834                 return;
835
836         /*
837          * Compute the cycle of the last queued packet.
838          * (We need only the four lowest bits for the SYT, so we can ignore
839          * that bits 0-11 must wrap around at 3072.)
840          */
841         cycle += QUEUE_LENGTH - packets;
842
843         for (i = 0; i < packets; ++i) {
844                 syt = calculate_syt(s, ++cycle);
845                 data_blocks = calculate_data_blocks(s, syt);
846
847                 if (handle_out_packet(s, data_blocks, syt) < 0) {
848                         s->packet_index = -1;
849                         amdtp_stream_pcm_abort(s);
850                         return;
851                 }
852         }
853
854         fw_iso_context_queue_flush(s->context);
855 }
856
857 static void in_stream_callback(struct fw_iso_context *context, u32 cycle,
858                                size_t header_length, void *header,
859                                void *private_data)
860 {
861         struct amdtp_stream *s = private_data;
862         unsigned int p, syt, packets;
863         unsigned int payload_quadlets, max_payload_quadlets;
864         unsigned int data_blocks;
865         __be32 *buffer, *headers = header;
866
867         if (s->packet_index < 0)
868                 return;
869
870         /* The number of packets in buffer */
871         packets = header_length / IN_PACKET_HEADER_SIZE;
872
873         /* For buffer-over-run prevention. */
874         max_payload_quadlets = amdtp_stream_get_max_payload(s) / 4;
875
876         for (p = 0; p < packets; p++) {
877                 buffer = s->buffer.packets[s->packet_index].buffer;
878
879                 /* The number of quadlets in this packet */
880                 payload_quadlets =
881                         (be32_to_cpu(headers[p]) >> ISO_DATA_LENGTH_SHIFT) / 4;
882                 if (payload_quadlets > max_payload_quadlets) {
883                         dev_err(&s->unit->device,
884                                 "Detect jumbo payload: %02x %02x\n",
885                                 payload_quadlets, max_payload_quadlets);
886                         s->packet_index = -1;
887                         break;
888                 }
889
890                 syt = be32_to_cpu(buffer[1]) & CIP_SYT_MASK;
891                 if (handle_in_packet(s, payload_quadlets, buffer,
892                                                 &data_blocks, syt) < 0) {
893                         s->packet_index = -1;
894                         break;
895                 }
896
897                 /* Process sync slave stream */
898                 if (s->sync_slave && s->sync_slave->callbacked) {
899                         if (handle_out_packet(s->sync_slave,
900                                               data_blocks, syt) < 0) {
901                                 s->packet_index = -1;
902                                 break;
903                         }
904                 }
905         }
906
907         /* Queueing error or detecting discontinuity */
908         if (s->packet_index < 0) {
909                 amdtp_stream_pcm_abort(s);
910
911                 /* Abort sync slave. */
912                 if (s->sync_slave) {
913                         s->sync_slave->packet_index = -1;
914                         amdtp_stream_pcm_abort(s->sync_slave);
915                 }
916                 return;
917         }
918
919         /* when sync to device, flush the packets for slave stream */
920         if (s->sync_slave && s->sync_slave->callbacked)
921                 fw_iso_context_queue_flush(s->sync_slave->context);
922
923         fw_iso_context_queue_flush(s->context);
924 }
925
926 /* processing is done by master callback */
927 static void slave_stream_callback(struct fw_iso_context *context, u32 cycle,
928                                   size_t header_length, void *header,
929                                   void *private_data)
930 {
931         return;
932 }
933
934 /* this is executed one time */
935 static void amdtp_stream_first_callback(struct fw_iso_context *context,
936                                         u32 cycle, size_t header_length,
937                                         void *header, void *private_data)
938 {
939         struct amdtp_stream *s = private_data;
940
941         /*
942          * For in-stream, first packet has come.
943          * For out-stream, prepared to transmit first packet
944          */
945         s->callbacked = true;
946         wake_up(&s->callback_wait);
947
948         if (s->direction == AMDTP_IN_STREAM)
949                 context->callback.sc = in_stream_callback;
950         else if (s->flags & CIP_SYNC_TO_DEVICE)
951                 context->callback.sc = slave_stream_callback;
952         else
953                 context->callback.sc = out_stream_callback;
954
955         context->callback.sc(context, cycle, header_length, header, s);
956 }
957
958 /**
959  * amdtp_stream_start - start transferring packets
960  * @s: the AMDTP stream to start
961  * @channel: the isochronous channel on the bus
962  * @speed: firewire speed code
963  *
964  * The stream cannot be started until it has been configured with
965  * amdtp_stream_set_parameters() and it must be started before any PCM or MIDI
966  * device can be started.
967  */
968 int amdtp_stream_start(struct amdtp_stream *s, int channel, int speed)
969 {
970         static const struct {
971                 unsigned int data_block;
972                 unsigned int syt_offset;
973         } initial_state[] = {
974                 [CIP_SFC_32000]  = {  4, 3072 },
975                 [CIP_SFC_48000]  = {  6, 1024 },
976                 [CIP_SFC_96000]  = { 12, 1024 },
977                 [CIP_SFC_192000] = { 24, 1024 },
978                 [CIP_SFC_44100]  = {  0,   67 },
979                 [CIP_SFC_88200]  = {  0,   67 },
980                 [CIP_SFC_176400] = {  0,   67 },
981         };
982         unsigned int header_size;
983         enum dma_data_direction dir;
984         int type, tag, err;
985
986         mutex_lock(&s->mutex);
987
988         if (WARN_ON(amdtp_stream_running(s) ||
989                     (s->data_block_quadlets < 1))) {
990                 err = -EBADFD;
991                 goto err_unlock;
992         }
993
994         if (s->direction == AMDTP_IN_STREAM &&
995             s->flags & CIP_SKIP_INIT_DBC_CHECK)
996                 s->data_block_counter = UINT_MAX;
997         else
998                 s->data_block_counter = 0;
999         s->data_block_state = initial_state[s->sfc].data_block;
1000         s->syt_offset_state = initial_state[s->sfc].syt_offset;
1001         s->last_syt_offset = TICKS_PER_CYCLE;
1002
1003         /* initialize packet buffer */
1004         if (s->direction == AMDTP_IN_STREAM) {
1005                 dir = DMA_FROM_DEVICE;
1006                 type = FW_ISO_CONTEXT_RECEIVE;
1007                 header_size = IN_PACKET_HEADER_SIZE;
1008         } else {
1009                 dir = DMA_TO_DEVICE;
1010                 type = FW_ISO_CONTEXT_TRANSMIT;
1011                 header_size = OUT_PACKET_HEADER_SIZE;
1012         }
1013         err = iso_packets_buffer_init(&s->buffer, s->unit, QUEUE_LENGTH,
1014                                       amdtp_stream_get_max_payload(s), dir);
1015         if (err < 0)
1016                 goto err_unlock;
1017
1018         s->context = fw_iso_context_create(fw_parent_device(s->unit)->card,
1019                                            type, channel, speed, header_size,
1020                                            amdtp_stream_first_callback, s);
1021         if (IS_ERR(s->context)) {
1022                 err = PTR_ERR(s->context);
1023                 if (err == -EBUSY)
1024                         dev_err(&s->unit->device,
1025                                 "no free stream on this controller\n");
1026                 goto err_buffer;
1027         }
1028
1029         amdtp_stream_update(s);
1030
1031         s->packet_index = 0;
1032         do {
1033                 if (s->direction == AMDTP_IN_STREAM)
1034                         err = queue_in_packet(s);
1035                 else
1036                         err = queue_out_packet(s, 0, true);
1037                 if (err < 0)
1038                         goto err_context;
1039         } while (s->packet_index > 0);
1040
1041         /* NOTE: TAG1 matches CIP. This just affects in stream. */
1042         tag = FW_ISO_CONTEXT_MATCH_TAG1;
1043         if (s->flags & CIP_EMPTY_WITH_TAG0)
1044                 tag |= FW_ISO_CONTEXT_MATCH_TAG0;
1045
1046         s->callbacked = false;
1047         err = fw_iso_context_start(s->context, -1, 0, tag);
1048         if (err < 0)
1049                 goto err_context;
1050
1051         mutex_unlock(&s->mutex);
1052
1053         return 0;
1054
1055 err_context:
1056         fw_iso_context_destroy(s->context);
1057         s->context = ERR_PTR(-1);
1058 err_buffer:
1059         iso_packets_buffer_destroy(&s->buffer, s->unit);
1060 err_unlock:
1061         mutex_unlock(&s->mutex);
1062
1063         return err;
1064 }
1065 EXPORT_SYMBOL(amdtp_stream_start);
1066
1067 /**
1068  * amdtp_stream_pcm_pointer - get the PCM buffer position
1069  * @s: the AMDTP stream that transports the PCM data
1070  *
1071  * Returns the current buffer position, in frames.
1072  */
1073 unsigned long amdtp_stream_pcm_pointer(struct amdtp_stream *s)
1074 {
1075         /* this optimization is allowed to be racy */
1076         if (s->pointer_flush && amdtp_stream_running(s))
1077                 fw_iso_context_flush_completions(s->context);
1078         else
1079                 s->pointer_flush = true;
1080
1081         return ACCESS_ONCE(s->pcm_buffer_pointer);
1082 }
1083 EXPORT_SYMBOL(amdtp_stream_pcm_pointer);
1084
1085 /**
1086  * amdtp_stream_update - update the stream after a bus reset
1087  * @s: the AMDTP stream
1088  */
1089 void amdtp_stream_update(struct amdtp_stream *s)
1090 {
1091         /* Precomputing. */
1092         ACCESS_ONCE(s->source_node_id_field) =
1093                 (fw_parent_device(s->unit)->card->node_id << CIP_SID_SHIFT) &
1094                                                                 CIP_SID_MASK;
1095 }
1096 EXPORT_SYMBOL(amdtp_stream_update);
1097
1098 /**
1099  * amdtp_stream_stop - stop sending packets
1100  * @s: the AMDTP stream to stop
1101  *
1102  * All PCM and MIDI devices of the stream must be stopped before the stream
1103  * itself can be stopped.
1104  */
1105 void amdtp_stream_stop(struct amdtp_stream *s)
1106 {
1107         mutex_lock(&s->mutex);
1108
1109         if (!amdtp_stream_running(s)) {
1110                 mutex_unlock(&s->mutex);
1111                 return;
1112         }
1113
1114         tasklet_kill(&s->period_tasklet);
1115         fw_iso_context_stop(s->context);
1116         fw_iso_context_destroy(s->context);
1117         s->context = ERR_PTR(-1);
1118         iso_packets_buffer_destroy(&s->buffer, s->unit);
1119
1120         s->callbacked = false;
1121
1122         mutex_unlock(&s->mutex);
1123 }
1124 EXPORT_SYMBOL(amdtp_stream_stop);
1125
1126 /**
1127  * amdtp_stream_pcm_abort - abort the running PCM device
1128  * @s: the AMDTP stream about to be stopped
1129  *
1130  * If the isochronous stream needs to be stopped asynchronously, call this
1131  * function first to stop the PCM device.
1132  */
1133 void amdtp_stream_pcm_abort(struct amdtp_stream *s)
1134 {
1135         struct snd_pcm_substream *pcm;
1136
1137         pcm = ACCESS_ONCE(s->pcm);
1138         if (pcm)
1139                 snd_pcm_stop_xrun(pcm);
1140 }
1141 EXPORT_SYMBOL(amdtp_stream_pcm_abort);