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