ALSA: firewire-lib: handle IT/IR contexts in each software interrupt context
[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 "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_CIP                 1
31
32 /* common isochronous packet header parameters */
33 #define CIP_EOH_SHIFT           31
34 #define CIP_EOH                 (1u << CIP_EOH_SHIFT)
35 #define CIP_EOH_MASK            0x80000000
36 #define CIP_SID_SHIFT           24
37 #define CIP_SID_MASK            0x3f000000
38 #define CIP_DBS_MASK            0x00ff0000
39 #define CIP_DBS_SHIFT           16
40 #define CIP_DBC_MASK            0x000000ff
41 #define CIP_FMT_SHIFT           24
42 #define CIP_FMT_MASK            0x3f000000
43 #define CIP_FDF_MASK            0x00ff0000
44 #define CIP_FDF_SHIFT           16
45 #define CIP_SYT_MASK            0x0000ffff
46 #define CIP_SYT_NO_INFO         0xffff
47
48 /* Audio and Music transfer protocol specific parameters */
49 #define CIP_FMT_AM              0x10
50 #define AMDTP_FDF_NO_DATA       0xff
51
52 /* TODO: make these configurable */
53 #define INTERRUPT_INTERVAL      16
54 #define QUEUE_LENGTH            48
55
56 #define IN_PACKET_HEADER_SIZE   4
57 #define OUT_PACKET_HEADER_SIZE  0
58
59 static void pcm_period_tasklet(unsigned long data);
60
61 /**
62  * amdtp_stream_init - initialize an AMDTP stream structure
63  * @s: the AMDTP stream to initialize
64  * @unit: the target of the stream
65  * @dir: the direction of stream
66  * @flags: the packet transmission method to use
67  * @fmt: the value of fmt field in CIP header
68  * @process_data_blocks: callback handler to process data blocks
69  * @protocol_size: the size to allocate newly for protocol
70  */
71 int amdtp_stream_init(struct amdtp_stream *s, struct fw_unit *unit,
72                       enum amdtp_stream_direction dir, enum cip_flags flags,
73                       unsigned int fmt,
74                       amdtp_stream_process_data_blocks_t process_data_blocks,
75                       unsigned int protocol_size)
76 {
77         if (process_data_blocks == NULL)
78                 return -EINVAL;
79
80         s->protocol = kzalloc(protocol_size, GFP_KERNEL);
81         if (!s->protocol)
82                 return -ENOMEM;
83
84         s->unit = unit;
85         s->direction = dir;
86         s->flags = flags;
87         s->context = ERR_PTR(-1);
88         mutex_init(&s->mutex);
89         tasklet_init(&s->period_tasklet, pcm_period_tasklet, (unsigned long)s);
90         s->packet_index = 0;
91
92         init_waitqueue_head(&s->callback_wait);
93         s->callbacked = false;
94
95         s->fmt = fmt;
96         s->process_data_blocks = process_data_blocks;
97
98         return 0;
99 }
100 EXPORT_SYMBOL(amdtp_stream_init);
101
102 /**
103  * amdtp_stream_destroy - free stream resources
104  * @s: the AMDTP stream to destroy
105  */
106 void amdtp_stream_destroy(struct amdtp_stream *s)
107 {
108         /* Not initialized. */
109         if (s->protocol == NULL)
110                 return;
111
112         WARN_ON(amdtp_stream_running(s));
113         kfree(s->protocol);
114         mutex_destroy(&s->mutex);
115 }
116 EXPORT_SYMBOL(amdtp_stream_destroy);
117
118 const unsigned int amdtp_syt_intervals[CIP_SFC_COUNT] = {
119         [CIP_SFC_32000]  =  8,
120         [CIP_SFC_44100]  =  8,
121         [CIP_SFC_48000]  =  8,
122         [CIP_SFC_88200]  = 16,
123         [CIP_SFC_96000]  = 16,
124         [CIP_SFC_176400] = 32,
125         [CIP_SFC_192000] = 32,
126 };
127 EXPORT_SYMBOL(amdtp_syt_intervals);
128
129 const unsigned int amdtp_rate_table[CIP_SFC_COUNT] = {
130         [CIP_SFC_32000]  =  32000,
131         [CIP_SFC_44100]  =  44100,
132         [CIP_SFC_48000]  =  48000,
133         [CIP_SFC_88200]  =  88200,
134         [CIP_SFC_96000]  =  96000,
135         [CIP_SFC_176400] = 176400,
136         [CIP_SFC_192000] = 192000,
137 };
138 EXPORT_SYMBOL(amdtp_rate_table);
139
140 /**
141  * amdtp_stream_add_pcm_hw_constraints - add hw constraints for PCM substream
142  * @s:          the AMDTP stream, which must be initialized.
143  * @runtime:    the PCM substream runtime
144  */
145 int amdtp_stream_add_pcm_hw_constraints(struct amdtp_stream *s,
146                                         struct snd_pcm_runtime *runtime)
147 {
148         int err;
149
150         /*
151          * Currently firewire-lib processes 16 packets in one software
152          * interrupt callback. This equals to 2msec but actually the
153          * interval of the interrupts has a jitter.
154          * Additionally, even if adding a constraint to fit period size to
155          * 2msec, actual calculated frames per period doesn't equal to 2msec,
156          * depending on sampling rate.
157          * Anyway, the interval to call snd_pcm_period_elapsed() cannot 2msec.
158          * Here let us use 5msec for safe period interrupt.
159          */
160         err = snd_pcm_hw_constraint_minmax(runtime,
161                                            SNDRV_PCM_HW_PARAM_PERIOD_TIME,
162                                            5000, UINT_MAX);
163         if (err < 0)
164                 goto end;
165
166         /* Non-Blocking stream has no more constraints */
167         if (!(s->flags & CIP_BLOCKING))
168                 goto end;
169
170         /*
171          * One AMDTP packet can include some frames. In blocking mode, the
172          * number equals to SYT_INTERVAL. So the number is 8, 16 or 32,
173          * depending on its sampling rate. For accurate period interrupt, it's
174          * preferrable to align period/buffer sizes to current SYT_INTERVAL.
175          *
176          * TODO: These constraints can be improved with proper rules.
177          * Currently apply LCM of SYT_INTERVALs.
178          */
179         err = snd_pcm_hw_constraint_step(runtime, 0,
180                                          SNDRV_PCM_HW_PARAM_PERIOD_SIZE, 32);
181         if (err < 0)
182                 goto end;
183         err = snd_pcm_hw_constraint_step(runtime, 0,
184                                          SNDRV_PCM_HW_PARAM_BUFFER_SIZE, 32);
185 end:
186         return err;
187 }
188 EXPORT_SYMBOL(amdtp_stream_add_pcm_hw_constraints);
189
190 /**
191  * amdtp_stream_set_parameters - set stream parameters
192  * @s: the AMDTP stream to configure
193  * @rate: the sample rate
194  * @data_block_quadlets: the size of a data block in quadlet unit
195  *
196  * The parameters must be set before the stream is started, and must not be
197  * changed while the stream is running.
198  */
199 int amdtp_stream_set_parameters(struct amdtp_stream *s, unsigned int rate,
200                                 unsigned int data_block_quadlets)
201 {
202         unsigned int sfc;
203
204         for (sfc = 0; sfc < ARRAY_SIZE(amdtp_rate_table); ++sfc) {
205                 if (amdtp_rate_table[sfc] == rate)
206                         break;
207         }
208         if (sfc == ARRAY_SIZE(amdtp_rate_table))
209                 return -EINVAL;
210
211         s->sfc = sfc;
212         s->data_block_quadlets = data_block_quadlets;
213         s->syt_interval = amdtp_syt_intervals[sfc];
214
215         /* default buffering in the device */
216         s->transfer_delay = TRANSFER_DELAY_TICKS - TICKS_PER_CYCLE;
217         if (s->flags & CIP_BLOCKING)
218                 /* additional buffering needed to adjust for no-data packets */
219                 s->transfer_delay += TICKS_PER_SECOND * s->syt_interval / rate;
220
221         return 0;
222 }
223 EXPORT_SYMBOL(amdtp_stream_set_parameters);
224
225 /**
226  * amdtp_stream_get_max_payload - get the stream's packet size
227  * @s: the AMDTP stream
228  *
229  * This function must not be called before the stream has been configured
230  * with amdtp_stream_set_parameters().
231  */
232 unsigned int amdtp_stream_get_max_payload(struct amdtp_stream *s)
233 {
234         unsigned int multiplier = 1;
235
236         if (s->flags & CIP_JUMBO_PAYLOAD)
237                 multiplier = 5;
238
239         return 8 + s->syt_interval * s->data_block_quadlets * 4 * multiplier;
240 }
241 EXPORT_SYMBOL(amdtp_stream_get_max_payload);
242
243 /**
244  * amdtp_stream_pcm_prepare - prepare PCM device for running
245  * @s: the AMDTP stream
246  *
247  * This function should be called from the PCM device's .prepare callback.
248  */
249 void amdtp_stream_pcm_prepare(struct amdtp_stream *s)
250 {
251         tasklet_kill(&s->period_tasklet);
252         s->pcm_buffer_pointer = 0;
253         s->pcm_period_pointer = 0;
254         s->pointer_flush = true;
255 }
256 EXPORT_SYMBOL(amdtp_stream_pcm_prepare);
257
258 static unsigned int calculate_data_blocks(struct amdtp_stream *s,
259                                           unsigned int syt)
260 {
261         unsigned int phase, data_blocks;
262
263         /* Blocking mode. */
264         if (s->flags & CIP_BLOCKING) {
265                 /* This module generate empty packet for 'no data'. */
266                 if (syt == CIP_SYT_NO_INFO)
267                         data_blocks = 0;
268                 else
269                         data_blocks = s->syt_interval;
270         /* Non-blocking mode. */
271         } else {
272                 if (!cip_sfc_is_base_44100(s->sfc)) {
273                         /* Sample_rate / 8000 is an integer, and precomputed. */
274                         data_blocks = s->data_block_state;
275                 } else {
276                         phase = s->data_block_state;
277
278                 /*
279                  * This calculates the number of data blocks per packet so that
280                  * 1) the overall rate is correct and exactly synchronized to
281                  *    the bus clock, and
282                  * 2) packets with a rounded-up number of blocks occur as early
283                  *    as possible in the sequence (to prevent underruns of the
284                  *    device's buffer).
285                  */
286                         if (s->sfc == CIP_SFC_44100)
287                                 /* 6 6 5 6 5 6 5 ... */
288                                 data_blocks = 5 + ((phase & 1) ^
289                                                    (phase == 0 || phase >= 40));
290                         else
291                                 /* 12 11 11 11 11 ... or 23 22 22 22 22 ... */
292                                 data_blocks = 11 * (s->sfc >> 1) + (phase == 0);
293                         if (++phase >= (80 >> (s->sfc >> 1)))
294                                 phase = 0;
295                         s->data_block_state = phase;
296                 }
297         }
298
299         return data_blocks;
300 }
301
302 static unsigned int calculate_syt(struct amdtp_stream *s,
303                                   unsigned int cycle)
304 {
305         unsigned int syt_offset, phase, index, syt;
306
307         if (s->last_syt_offset < TICKS_PER_CYCLE) {
308                 if (!cip_sfc_is_base_44100(s->sfc))
309                         syt_offset = s->last_syt_offset + s->syt_offset_state;
310                 else {
311                 /*
312                  * The time, in ticks, of the n'th SYT_INTERVAL sample is:
313                  *   n * SYT_INTERVAL * 24576000 / sample_rate
314                  * Modulo TICKS_PER_CYCLE, the difference between successive
315                  * elements is about 1386.23.  Rounding the results of this
316                  * formula to the SYT precision results in a sequence of
317                  * differences that begins with:
318                  *   1386 1386 1387 1386 1386 1386 1387 1386 1386 1386 1387 ...
319                  * This code generates _exactly_ the same sequence.
320                  */
321                         phase = s->syt_offset_state;
322                         index = phase % 13;
323                         syt_offset = s->last_syt_offset;
324                         syt_offset += 1386 + ((index && !(index & 3)) ||
325                                               phase == 146);
326                         if (++phase >= 147)
327                                 phase = 0;
328                         s->syt_offset_state = phase;
329                 }
330         } else
331                 syt_offset = s->last_syt_offset - TICKS_PER_CYCLE;
332         s->last_syt_offset = syt_offset;
333
334         if (syt_offset < TICKS_PER_CYCLE) {
335                 syt_offset += s->transfer_delay;
336                 syt = (cycle + syt_offset / TICKS_PER_CYCLE) << 12;
337                 syt += syt_offset % TICKS_PER_CYCLE;
338
339                 return syt & CIP_SYT_MASK;
340         } else {
341                 return CIP_SYT_NO_INFO;
342         }
343 }
344
345 static void update_pcm_pointers(struct amdtp_stream *s,
346                                 struct snd_pcm_substream *pcm,
347                                 unsigned int frames)
348 {
349         unsigned int ptr;
350
351         ptr = s->pcm_buffer_pointer + frames;
352         if (ptr >= pcm->runtime->buffer_size)
353                 ptr -= pcm->runtime->buffer_size;
354         ACCESS_ONCE(s->pcm_buffer_pointer) = ptr;
355
356         s->pcm_period_pointer += frames;
357         if (s->pcm_period_pointer >= pcm->runtime->period_size) {
358                 s->pcm_period_pointer -= pcm->runtime->period_size;
359                 s->pointer_flush = false;
360                 tasklet_hi_schedule(&s->period_tasklet);
361         }
362 }
363
364 static void pcm_period_tasklet(unsigned long data)
365 {
366         struct amdtp_stream *s = (void *)data;
367         struct snd_pcm_substream *pcm = ACCESS_ONCE(s->pcm);
368
369         if (pcm)
370                 snd_pcm_period_elapsed(pcm);
371 }
372
373 static int queue_packet(struct amdtp_stream *s,
374                         unsigned int header_length,
375                         unsigned int payload_length, bool skip)
376 {
377         struct fw_iso_packet p = {0};
378         int err = 0;
379
380         if (IS_ERR(s->context))
381                 goto end;
382
383         p.interrupt = IS_ALIGNED(s->packet_index + 1, INTERRUPT_INTERVAL);
384         p.tag = TAG_CIP;
385         p.header_length = header_length;
386         p.payload_length = (!skip) ? payload_length : 0;
387         p.skip = skip;
388         err = fw_iso_context_queue(s->context, &p, &s->buffer.iso_buffer,
389                                    s->buffer.packets[s->packet_index].offset);
390         if (err < 0) {
391                 dev_err(&s->unit->device, "queueing error: %d\n", err);
392                 goto end;
393         }
394
395         if (++s->packet_index >= QUEUE_LENGTH)
396                 s->packet_index = 0;
397 end:
398         return err;
399 }
400
401 static inline int queue_out_packet(struct amdtp_stream *s,
402                                    unsigned int payload_length, bool skip)
403 {
404         return queue_packet(s, OUT_PACKET_HEADER_SIZE,
405                             payload_length, skip);
406 }
407
408 static inline int queue_in_packet(struct amdtp_stream *s)
409 {
410         return queue_packet(s, IN_PACKET_HEADER_SIZE,
411                             amdtp_stream_get_max_payload(s), false);
412 }
413
414 static int handle_out_packet(struct amdtp_stream *s, unsigned int data_blocks,
415                              unsigned int cycle, unsigned int syt)
416 {
417         __be32 *buffer;
418         unsigned int payload_length;
419         unsigned int pcm_frames;
420         struct snd_pcm_substream *pcm;
421
422         buffer = s->buffer.packets[s->packet_index].buffer;
423         pcm_frames = s->process_data_blocks(s, buffer + 2, data_blocks, &syt);
424
425         buffer[0] = cpu_to_be32(ACCESS_ONCE(s->source_node_id_field) |
426                                 (s->data_block_quadlets << CIP_DBS_SHIFT) |
427                                 s->data_block_counter);
428         buffer[1] = cpu_to_be32(CIP_EOH |
429                                 ((s->fmt << CIP_FMT_SHIFT) & CIP_FMT_MASK) |
430                                 ((s->fdf << CIP_FDF_SHIFT) & CIP_FDF_MASK) |
431                                 (syt & CIP_SYT_MASK));
432
433         s->data_block_counter = (s->data_block_counter + data_blocks) & 0xff;
434         payload_length = 8 + data_blocks * 4 * s->data_block_quadlets;
435
436         trace_out_packet(s, cycle, buffer, payload_length);
437
438         if (queue_out_packet(s, payload_length, false) < 0)
439                 return -EIO;
440
441         pcm = ACCESS_ONCE(s->pcm);
442         if (pcm && pcm_frames > 0)
443                 update_pcm_pointers(s, pcm, pcm_frames);
444
445         /* No need to return the number of handled data blocks. */
446         return 0;
447 }
448
449 static int handle_in_packet(struct amdtp_stream *s,
450                             unsigned int payload_quadlets, __be32 *buffer,
451                             unsigned int *data_blocks, unsigned int cycle,
452                             unsigned int syt)
453 {
454         u32 cip_header[2];
455         unsigned int fmt, fdf;
456         unsigned int data_block_quadlets, data_block_counter, dbc_interval;
457         struct snd_pcm_substream *pcm;
458         unsigned int pcm_frames;
459         bool lost;
460
461         cip_header[0] = be32_to_cpu(buffer[0]);
462         cip_header[1] = be32_to_cpu(buffer[1]);
463
464         trace_in_packet(s, cycle, cip_header, payload_quadlets);
465
466         /*
467          * This module supports 'Two-quadlet CIP header with SYT field'.
468          * For convenience, also check FMT field is AM824 or not.
469          */
470         if (((cip_header[0] & CIP_EOH_MASK) == CIP_EOH) ||
471             ((cip_header[1] & CIP_EOH_MASK) != CIP_EOH)) {
472                 dev_info_ratelimited(&s->unit->device,
473                                 "Invalid CIP header for AMDTP: %08X:%08X\n",
474                                 cip_header[0], cip_header[1]);
475                 *data_blocks = 0;
476                 pcm_frames = 0;
477                 goto end;
478         }
479
480         /* Check valid protocol or not. */
481         fmt = (cip_header[1] & CIP_FMT_MASK) >> CIP_FMT_SHIFT;
482         if (fmt != s->fmt) {
483                 dev_info_ratelimited(&s->unit->device,
484                                      "Detect unexpected protocol: %08x %08x\n",
485                                      cip_header[0], cip_header[1]);
486                 *data_blocks = 0;
487                 pcm_frames = 0;
488                 goto end;
489         }
490
491         /* Calculate data blocks */
492         fdf = (cip_header[1] & CIP_FDF_MASK) >> CIP_FDF_SHIFT;
493         if (payload_quadlets < 3 ||
494             (fmt == CIP_FMT_AM && fdf == AMDTP_FDF_NO_DATA)) {
495                 *data_blocks = 0;
496         } else {
497                 data_block_quadlets =
498                         (cip_header[0] & CIP_DBS_MASK) >> CIP_DBS_SHIFT;
499                 /* avoid division by zero */
500                 if (data_block_quadlets == 0) {
501                         dev_err(&s->unit->device,
502                                 "Detect invalid value in dbs field: %08X\n",
503                                 cip_header[0]);
504                         return -EPROTO;
505                 }
506                 if (s->flags & CIP_WRONG_DBS)
507                         data_block_quadlets = s->data_block_quadlets;
508
509                 *data_blocks = (payload_quadlets - 2) / data_block_quadlets;
510         }
511
512         /* Check data block counter continuity */
513         data_block_counter = cip_header[0] & CIP_DBC_MASK;
514         if (*data_blocks == 0 && (s->flags & CIP_EMPTY_HAS_WRONG_DBC) &&
515             s->data_block_counter != UINT_MAX)
516                 data_block_counter = s->data_block_counter;
517
518         if (((s->flags & CIP_SKIP_DBC_ZERO_CHECK) &&
519              data_block_counter == s->tx_first_dbc) ||
520             s->data_block_counter == UINT_MAX) {
521                 lost = false;
522         } else if (!(s->flags & CIP_DBC_IS_END_EVENT)) {
523                 lost = data_block_counter != s->data_block_counter;
524         } else {
525                 if ((*data_blocks > 0) && (s->tx_dbc_interval > 0))
526                         dbc_interval = s->tx_dbc_interval;
527                 else
528                         dbc_interval = *data_blocks;
529
530                 lost = data_block_counter !=
531                        ((s->data_block_counter + dbc_interval) & 0xff);
532         }
533
534         if (lost) {
535                 dev_err(&s->unit->device,
536                         "Detect discontinuity of CIP: %02X %02X\n",
537                         s->data_block_counter, data_block_counter);
538                 return -EIO;
539         }
540
541         pcm_frames = s->process_data_blocks(s, buffer + 2, *data_blocks, &syt);
542
543         if (s->flags & CIP_DBC_IS_END_EVENT)
544                 s->data_block_counter = data_block_counter;
545         else
546                 s->data_block_counter =
547                                 (data_block_counter + *data_blocks) & 0xff;
548 end:
549         if (queue_in_packet(s) < 0)
550                 return -EIO;
551
552         pcm = ACCESS_ONCE(s->pcm);
553         if (pcm && pcm_frames > 0)
554                 update_pcm_pointers(s, pcm, pcm_frames);
555
556         return 0;
557 }
558
559 /*
560  * In CYCLE_TIMER register of IEEE 1394, 7 bits are used to represent second. On
561  * the other hand, in DMA descriptors of 1394 OHCI, 3 bits are used to represent
562  * it. Thus, via Linux firewire subsystem, we can get the 3 bits for second.
563  */
564 static inline u32 compute_cycle_count(u32 tstamp)
565 {
566         return (((tstamp >> 13) & 0x07) * 8000) + (tstamp & 0x1fff);
567 }
568
569 static inline u32 increment_cycle_count(u32 cycle, unsigned int addend)
570 {
571         cycle += addend;
572         if (cycle >= 8 * CYCLES_PER_SECOND)
573                 cycle -= 8 * CYCLES_PER_SECOND;
574         return cycle;
575 }
576
577 static inline u32 decrement_cycle_count(u32 cycle, unsigned int subtrahend)
578 {
579         if (cycle < subtrahend)
580                 cycle += 8 * CYCLES_PER_SECOND;
581         return cycle - subtrahend;
582 }
583
584 static void out_stream_callback(struct fw_iso_context *context, u32 tstamp,
585                                 size_t header_length, void *header,
586                                 void *private_data)
587 {
588         struct amdtp_stream *s = private_data;
589         unsigned int i, syt, packets = header_length / 4;
590         unsigned int data_blocks;
591         u32 cycle;
592
593         if (s->packet_index < 0)
594                 return;
595
596         cycle = compute_cycle_count(tstamp);
597
598         /* Align to actual cycle count for the last packet. */
599         cycle = increment_cycle_count(cycle, QUEUE_LENGTH - packets);
600
601         for (i = 0; i < packets; ++i) {
602                 cycle = increment_cycle_count(cycle, 1);
603                 syt = calculate_syt(s, cycle);
604                 data_blocks = calculate_data_blocks(s, syt);
605
606                 if (handle_out_packet(s, data_blocks, cycle, syt) < 0) {
607                         s->packet_index = -1;
608                         amdtp_stream_pcm_abort(s);
609                         return;
610                 }
611         }
612
613         fw_iso_context_queue_flush(s->context);
614 }
615
616 static void in_stream_callback(struct fw_iso_context *context, u32 tstamp,
617                                size_t header_length, void *header,
618                                void *private_data)
619 {
620         struct amdtp_stream *s = private_data;
621         unsigned int p, syt, packets;
622         unsigned int payload_quadlets, max_payload_quadlets;
623         unsigned int data_blocks;
624         __be32 *buffer, *headers = header;
625         u32 cycle;
626
627         if (s->packet_index < 0)
628                 return;
629
630         /* The number of packets in buffer */
631         packets = header_length / IN_PACKET_HEADER_SIZE;
632
633         cycle = compute_cycle_count(tstamp);
634
635         /* Align to actual cycle count for the last packet. */
636         cycle = decrement_cycle_count(cycle, packets);
637
638         /* For buffer-over-run prevention. */
639         max_payload_quadlets = amdtp_stream_get_max_payload(s) / 4;
640
641         for (p = 0; p < packets; p++) {
642                 cycle = increment_cycle_count(cycle, 1);
643                 buffer = s->buffer.packets[s->packet_index].buffer;
644
645                 /* The number of quadlets in this packet */
646                 payload_quadlets =
647                         (be32_to_cpu(headers[p]) >> ISO_DATA_LENGTH_SHIFT) / 4;
648                 if (payload_quadlets > max_payload_quadlets) {
649                         dev_err(&s->unit->device,
650                                 "Detect jumbo payload: %02x %02x\n",
651                                 payload_quadlets, max_payload_quadlets);
652                         break;
653                 }
654
655                 syt = be32_to_cpu(buffer[1]) & CIP_SYT_MASK;
656                 if (handle_in_packet(s, payload_quadlets, buffer,
657                                                 &data_blocks, cycle, syt) < 0)
658                         break;
659         }
660
661         /* Queueing error or detecting invalid payload. */
662         if (p < packets) {
663                 s->packet_index = -1;
664                 amdtp_stream_pcm_abort(s);
665                 return;
666         }
667
668         fw_iso_context_queue_flush(s->context);
669 }
670
671 /* this is executed one time */
672 static void amdtp_stream_first_callback(struct fw_iso_context *context,
673                                         u32 tstamp, size_t header_length,
674                                         void *header, void *private_data)
675 {
676         struct amdtp_stream *s = private_data;
677
678         /*
679          * For in-stream, first packet has come.
680          * For out-stream, prepared to transmit first packet
681          */
682         s->callbacked = true;
683         wake_up(&s->callback_wait);
684
685         if (s->direction == AMDTP_IN_STREAM)
686                 context->callback.sc = in_stream_callback;
687         else
688                 context->callback.sc = out_stream_callback;
689
690         context->callback.sc(context, tstamp, header_length, header, s);
691 }
692
693 /**
694  * amdtp_stream_start - start transferring packets
695  * @s: the AMDTP stream to start
696  * @channel: the isochronous channel on the bus
697  * @speed: firewire speed code
698  *
699  * The stream cannot be started until it has been configured with
700  * amdtp_stream_set_parameters() and it must be started before any PCM or MIDI
701  * device can be started.
702  */
703 int amdtp_stream_start(struct amdtp_stream *s, int channel, int speed)
704 {
705         static const struct {
706                 unsigned int data_block;
707                 unsigned int syt_offset;
708         } initial_state[] = {
709                 [CIP_SFC_32000]  = {  4, 3072 },
710                 [CIP_SFC_48000]  = {  6, 1024 },
711                 [CIP_SFC_96000]  = { 12, 1024 },
712                 [CIP_SFC_192000] = { 24, 1024 },
713                 [CIP_SFC_44100]  = {  0,   67 },
714                 [CIP_SFC_88200]  = {  0,   67 },
715                 [CIP_SFC_176400] = {  0,   67 },
716         };
717         unsigned int header_size;
718         enum dma_data_direction dir;
719         int type, tag, err;
720
721         mutex_lock(&s->mutex);
722
723         if (WARN_ON(amdtp_stream_running(s) ||
724                     (s->data_block_quadlets < 1))) {
725                 err = -EBADFD;
726                 goto err_unlock;
727         }
728
729         if (s->direction == AMDTP_IN_STREAM &&
730             s->flags & CIP_SKIP_INIT_DBC_CHECK)
731                 s->data_block_counter = UINT_MAX;
732         else
733                 s->data_block_counter = 0;
734         s->data_block_state = initial_state[s->sfc].data_block;
735         s->syt_offset_state = initial_state[s->sfc].syt_offset;
736         s->last_syt_offset = TICKS_PER_CYCLE;
737
738         /* initialize packet buffer */
739         if (s->direction == AMDTP_IN_STREAM) {
740                 dir = DMA_FROM_DEVICE;
741                 type = FW_ISO_CONTEXT_RECEIVE;
742                 header_size = IN_PACKET_HEADER_SIZE;
743         } else {
744                 dir = DMA_TO_DEVICE;
745                 type = FW_ISO_CONTEXT_TRANSMIT;
746                 header_size = OUT_PACKET_HEADER_SIZE;
747         }
748         err = iso_packets_buffer_init(&s->buffer, s->unit, QUEUE_LENGTH,
749                                       amdtp_stream_get_max_payload(s), dir);
750         if (err < 0)
751                 goto err_unlock;
752
753         s->context = fw_iso_context_create(fw_parent_device(s->unit)->card,
754                                            type, channel, speed, header_size,
755                                            amdtp_stream_first_callback, s);
756         if (IS_ERR(s->context)) {
757                 err = PTR_ERR(s->context);
758                 if (err == -EBUSY)
759                         dev_err(&s->unit->device,
760                                 "no free stream on this controller\n");
761                 goto err_buffer;
762         }
763
764         amdtp_stream_update(s);
765
766         s->packet_index = 0;
767         do {
768                 if (s->direction == AMDTP_IN_STREAM)
769                         err = queue_in_packet(s);
770                 else
771                         err = queue_out_packet(s, 0, true);
772                 if (err < 0)
773                         goto err_context;
774         } while (s->packet_index > 0);
775
776         /* NOTE: TAG1 matches CIP. This just affects in stream. */
777         tag = FW_ISO_CONTEXT_MATCH_TAG1;
778         if (s->flags & CIP_EMPTY_WITH_TAG0)
779                 tag |= FW_ISO_CONTEXT_MATCH_TAG0;
780
781         s->callbacked = false;
782         err = fw_iso_context_start(s->context, -1, 0, tag);
783         if (err < 0)
784                 goto err_context;
785
786         mutex_unlock(&s->mutex);
787
788         return 0;
789
790 err_context:
791         fw_iso_context_destroy(s->context);
792         s->context = ERR_PTR(-1);
793 err_buffer:
794         iso_packets_buffer_destroy(&s->buffer, s->unit);
795 err_unlock:
796         mutex_unlock(&s->mutex);
797
798         return err;
799 }
800 EXPORT_SYMBOL(amdtp_stream_start);
801
802 /**
803  * amdtp_stream_pcm_pointer - get the PCM buffer position
804  * @s: the AMDTP stream that transports the PCM data
805  *
806  * Returns the current buffer position, in frames.
807  */
808 unsigned long amdtp_stream_pcm_pointer(struct amdtp_stream *s)
809 {
810         /* this optimization is allowed to be racy */
811         if (s->pointer_flush && amdtp_stream_running(s))
812                 fw_iso_context_flush_completions(s->context);
813         else
814                 s->pointer_flush = true;
815
816         return ACCESS_ONCE(s->pcm_buffer_pointer);
817 }
818 EXPORT_SYMBOL(amdtp_stream_pcm_pointer);
819
820 /**
821  * amdtp_stream_update - update the stream after a bus reset
822  * @s: the AMDTP stream
823  */
824 void amdtp_stream_update(struct amdtp_stream *s)
825 {
826         /* Precomputing. */
827         ACCESS_ONCE(s->source_node_id_field) =
828                 (fw_parent_device(s->unit)->card->node_id << CIP_SID_SHIFT) &
829                                                                 CIP_SID_MASK;
830 }
831 EXPORT_SYMBOL(amdtp_stream_update);
832
833 /**
834  * amdtp_stream_stop - stop sending packets
835  * @s: the AMDTP stream to stop
836  *
837  * All PCM and MIDI devices of the stream must be stopped before the stream
838  * itself can be stopped.
839  */
840 void amdtp_stream_stop(struct amdtp_stream *s)
841 {
842         mutex_lock(&s->mutex);
843
844         if (!amdtp_stream_running(s)) {
845                 mutex_unlock(&s->mutex);
846                 return;
847         }
848
849         tasklet_kill(&s->period_tasklet);
850         fw_iso_context_stop(s->context);
851         fw_iso_context_destroy(s->context);
852         s->context = ERR_PTR(-1);
853         iso_packets_buffer_destroy(&s->buffer, s->unit);
854
855         s->callbacked = false;
856
857         mutex_unlock(&s->mutex);
858 }
859 EXPORT_SYMBOL(amdtp_stream_stop);
860
861 /**
862  * amdtp_stream_pcm_abort - abort the running PCM device
863  * @s: the AMDTP stream about to be stopped
864  *
865  * If the isochronous stream needs to be stopped asynchronously, call this
866  * function first to stop the PCM device.
867  */
868 void amdtp_stream_pcm_abort(struct amdtp_stream *s)
869 {
870         struct snd_pcm_substream *pcm;
871
872         pcm = ACCESS_ONCE(s->pcm);
873         if (pcm)
874                 snd_pcm_stop_xrun(pcm);
875 }
876 EXPORT_SYMBOL(amdtp_stream_pcm_abort);