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