fix to allow loader.o to boot kernel with parametars
[linux-2.4.21-pre4.git] / drivers / ieee1394 / amdtp.c
1 /* -*- c-basic-offset: 8 -*-
2  *
3  * amdtp.c - Audio and Music Data Transmission Protocol Driver
4  * Copyright (C) 2001 Kristian Høgsberg
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
19  */
20
21 /* OVERVIEW
22  * --------
23  *
24  * The AMDTP driver is designed to expose the IEEE1394 bus as a
25  * regular OSS soundcard, i.e. you can link /dev/dsp to /dev/amdtp and
26  * then your favourite MP3 player, game or whatever sound program will
27  * output to an IEEE1394 isochronous channel.  The signal destination
28  * could be a set of IEEE1394 loudspeakers (if and when such things
29  * become available) or an amplifier with IEEE1394 input (like the
30  * Sony STR-LSA1).  The driver only handles the actual streaming, some
31  * connection management is also required for this to actually work.
32  * That is outside the scope of this driver, and furthermore it is not
33  * really standardized yet.
34  *
35  * The Audio and Music Data Tranmission Protocol is available at
36  *
37  *     http://www.1394ta.org/Download/Technology/Specifications/2001/AM20Final-jf2.pdf
38  *
39  *
40  * TODO
41  * ----
42  *
43  * - We should be able to change input sample format between LE/BE, as
44  *   we already shift the bytes around when we construct the iso
45  *   packets.
46  *
47  * - Fix DMA stop after bus reset!
48  *
49  * - Clean up iso context handling in ohci1394.
50  *
51  *
52  * MAYBE TODO
53  * ----------
54  *
55  * - Receive data for local playback or recording.  Playback requires
56  *   soft syncing with the sound card.
57  *
58  * - Signal processing, i.e. receive packets, do some processing, and
59  *   transmit them again using the same packet structure and timestamps
60  *   offset by processing time.
61  *
62  * - Maybe make an ALSA interface, that is, create a file_ops
63  *   implementation that recognizes ALSA ioctls and uses defaults for
64  *   things that can't be controlled through ALSA (iso channel).
65  */
66
67 #include <linux/module.h>
68 #include <linux/list.h>
69 #include <linux/sched.h>
70 #include <linux/types.h>
71 #include <linux/fs.h>
72 #include <linux/ioctl.h>
73 #include <linux/wait.h>
74 #include <linux/pci.h>
75 #include <linux/interrupt.h>
76 #include <linux/poll.h>
77 #include <asm/uaccess.h>
78 #include <asm/atomic.h>
79
80 #include "hosts.h"
81 #include "highlevel.h"
82 #include "ieee1394.h"
83 #include "ieee1394_core.h"
84 #include "ohci1394.h"
85
86 #include "amdtp.h"
87 #include "cmp.h"
88
89 #define FMT_AMDTP 0x10
90 #define FDF_AM824 0x00
91 #define FDF_SFC_32KHZ   0x00
92 #define FDF_SFC_44K1HZ  0x01
93 #define FDF_SFC_48KHZ   0x02
94 #define FDF_SFC_88K2HZ  0x03
95 #define FDF_SFC_96KHZ   0x04
96 #define FDF_SFC_176K4HZ 0x05
97 #define FDF_SFC_192KHZ  0x06
98
99 struct descriptor_block {
100         struct output_more_immediate {
101                 u32 control;
102                 u32 pad0;
103                 u32 skip;
104                 u32 pad1;
105                 u32 header[4];
106         } header_desc;
107
108         struct output_last {
109                 u32 control;
110                 u32 data_address;
111                 u32 branch;
112                 u32 status;
113         } payload_desc;
114 };
115
116 struct packet {
117         struct descriptor_block *db;
118         dma_addr_t db_bus;
119         struct iso_packet *payload;
120         dma_addr_t payload_bus;
121 };
122
123 #include <asm/byteorder.h>
124
125 #if defined __BIG_ENDIAN_BITFIELD
126
127 struct iso_packet {
128         /* First quadlet */
129         unsigned int dbs      : 8;
130         unsigned int eoh0     : 2;
131         unsigned int sid      : 6;
132
133         unsigned int dbc      : 8;
134         unsigned int fn       : 2;
135         unsigned int qpc      : 3;
136         unsigned int sph      : 1;
137         unsigned int reserved : 2;
138
139         /* Second quadlet */
140         unsigned int fdf      : 8;
141         unsigned int eoh1     : 2;
142         unsigned int fmt      : 6;
143
144         unsigned int syt      : 16;
145
146         quadlet_t data[0];
147 };
148
149 #elif defined __LITTLE_ENDIAN_BITFIELD
150
151 struct iso_packet {
152         /* First quadlet */
153         unsigned int sid      : 6;
154         unsigned int eoh0     : 2;
155         unsigned int dbs      : 8;
156
157         unsigned int reserved : 2;
158         unsigned int sph      : 1;
159         unsigned int qpc      : 3;
160         unsigned int fn       : 2;
161         unsigned int dbc      : 8;
162
163         /* Second quadlet */
164         unsigned int fmt      : 6;
165         unsigned int eoh1     : 2;
166         unsigned int fdf      : 8;
167
168         unsigned int syt      : 16;
169
170         quadlet_t data[0];
171 };
172
173 #else
174
175 #error Unknown bitfield type
176
177 #endif
178
179 struct fraction {
180         int integer;
181         int numerator;
182         int denominator;
183 };
184
185 #define PACKET_LIST_SIZE 256
186 #define MAX_PACKET_LISTS 4
187
188 struct packet_list {
189         struct list_head link;
190         int last_cycle_count;
191         struct packet packets[PACKET_LIST_SIZE];
192 };
193
194 #define BUFFER_SIZE 128
195
196 /* This implements a circular buffer for incoming samples. */
197
198 struct buffer {
199         size_t head, tail, length, size;
200         unsigned char data[0];
201 };
202
203 struct stream {
204         int iso_channel;
205         int format;
206         int rate;
207         int dimension;
208         int fdf;
209         int mode;
210         int sample_format;
211         struct cmp_pcr *opcr;
212
213         /* Input samples are copied here. */
214         struct buffer *input;
215
216         /* ISO Packer state */
217         unsigned char dbc;
218         struct packet_list *current_packet_list;
219         int current_packet;
220         struct fraction ready_samples, samples_per_cycle;
221
222         /* We use these to generate control bits when we are packing
223          * iec958 data.
224          */
225         int iec958_frame_count;
226         int iec958_rate_code;
227
228         /* The cycle_count and cycle_offset fields are used for the
229          * synchronization timestamps (syt) in the cip header.  They
230          * are incremented by at least a cycle every time we put a
231          * time stamp in a packet.  As we dont time stamp all
232          * packages, cycle_count isn't updated in every cycle, and
233          * sometimes it's incremented by 2.  Thus, we have
234          * cycle_count2, which is simply incremented by one with each
235          * packet, so we can compare it to the transmission time
236          * written back in the dma programs.
237          */
238         atomic_t cycle_count, cycle_count2;
239         struct fraction cycle_offset, ticks_per_syt_offset;
240         int syt_interval;
241         int stale_count;
242
243         /* Theses fields control the sample output to the DMA engine.
244          * The dma_packet_lists list holds packet lists currently
245          * queued for dma; the head of the list is currently being
246          * processed.  The last program in a packet list generates an
247          * interrupt, which removes the head from dma_packet_lists and
248          * puts it back on the free list.
249          */
250         struct list_head dma_packet_lists;
251         struct list_head free_packet_lists;
252         wait_queue_head_t packet_list_wait;
253         spinlock_t packet_list_lock;
254         struct ohci1394_iso_tasklet iso_tasklet;
255         struct pci_pool *descriptor_pool, *packet_pool;
256
257         /* Streams at a host controller are chained through this field. */
258         struct list_head link;
259         struct amdtp_host *host;
260 };
261
262 struct amdtp_host {
263         struct hpsb_host *host;
264         struct ti_ohci *ohci;
265         struct list_head stream_list;
266         spinlock_t stream_list_lock;
267         struct list_head link;
268 };
269
270 static struct hpsb_highlevel *amdtp_highlevel;
271 static LIST_HEAD(host_list);
272 static spinlock_t host_list_lock = SPIN_LOCK_UNLOCKED;
273
274 /* FIXME: This doesn't belong here... */
275
276 #define OHCI1394_CONTEXT_CYCLE_MATCH 0x80000000
277 #define OHCI1394_CONTEXT_RUN         0x00008000
278 #define OHCI1394_CONTEXT_WAKE        0x00001000
279 #define OHCI1394_CONTEXT_DEAD        0x00000800
280 #define OHCI1394_CONTEXT_ACTIVE      0x00000400
281
282 void ohci1394_start_it_ctx(struct ti_ohci *ohci, int ctx,
283                            dma_addr_t first_cmd, int z, int cycle_match)
284 {
285         reg_write(ohci, OHCI1394_IsoXmitIntMaskSet, 1 << ctx);
286         reg_write(ohci, OHCI1394_IsoXmitCommandPtr + ctx * 16, first_cmd | z);
287         reg_write(ohci, OHCI1394_IsoXmitContextControlClear + ctx * 16, ~0);
288         wmb();
289         reg_write(ohci, OHCI1394_IsoXmitContextControlSet + ctx * 16,
290                   OHCI1394_CONTEXT_CYCLE_MATCH | (cycle_match << 16) |
291                   OHCI1394_CONTEXT_RUN);
292 }
293
294 void ohci1394_wake_it_ctx(struct ti_ohci *ohci, int ctx)
295 {
296         reg_write(ohci, OHCI1394_IsoXmitContextControlSet + ctx * 16,
297                   OHCI1394_CONTEXT_WAKE);
298 }
299
300 void ohci1394_stop_it_ctx(struct ti_ohci *ohci, int ctx, int synchronous)
301 {
302         u32 control;
303         int wait;
304
305         reg_write(ohci, OHCI1394_IsoXmitIntMaskClear, 1 << ctx);
306         reg_write(ohci, OHCI1394_IsoXmitContextControlClear + ctx * 16,
307                   OHCI1394_CONTEXT_RUN);
308         wmb();
309
310         if (synchronous) {
311                 for (wait = 0; wait < 5; wait++) {
312                         control = reg_read(ohci, OHCI1394_IsoXmitContextControlSet + ctx * 16);
313                         if ((control & OHCI1394_CONTEXT_ACTIVE) == 0)
314                                 break;
315                         
316                         set_current_state(TASK_INTERRUPTIBLE);
317                         schedule_timeout(1);
318                 }
319         }
320 }
321
322 /* Note: we can test if free_packet_lists is empty without aquiring
323  * the packet_list_lock.  The interrupt handler only adds to the free
324  * list, there is no race condition between testing the list non-empty
325  * and acquiring the lock.
326  */
327
328 static struct packet_list *stream_get_free_packet_list(struct stream *s)
329 {
330         struct packet_list *pl;
331         unsigned long flags;
332
333         if (list_empty(&s->free_packet_lists))
334                 return NULL;
335
336         spin_lock_irqsave(&s->packet_list_lock, flags);
337         pl = list_entry(s->free_packet_lists.next, struct packet_list, link);
338         list_del(&pl->link);
339         spin_unlock_irqrestore(&s->packet_list_lock, flags);
340
341         return pl;
342 }
343
344 static void stream_start_dma(struct stream *s, struct packet_list *pl)
345 {
346         u32 syt_cycle, cycle_count, start_cycle;
347
348         cycle_count = reg_read(s->host->host->hostdata,
349                                OHCI1394_IsochronousCycleTimer) >> 12;
350         syt_cycle = (pl->last_cycle_count - PACKET_LIST_SIZE + 1) & 0x0f;
351
352         /* We program the DMA controller to start transmission at
353          * least 17 cycles from now - this happens when the lower four
354          * bits of cycle_count is 0x0f and syt_cycle is 0, in this
355          * case the start cycle is cycle_count - 15 + 32. */
356         start_cycle = (cycle_count & ~0x0f) + 32 + syt_cycle;
357         if ((start_cycle & 0x1fff) >= 8000)
358                 start_cycle = start_cycle - 8000 + 0x2000;
359
360         ohci1394_start_it_ctx(s->host->ohci, s->iso_tasklet.context,
361                               pl->packets[0].db_bus, 3,
362                               start_cycle & 0x7fff);
363 }
364
365 static void stream_put_dma_packet_list(struct stream *s,
366                                        struct packet_list *pl)
367 {
368         unsigned long flags;
369         struct packet_list *prev;
370
371         /* Remember the cycle_count used for timestamping the last packet. */
372         pl->last_cycle_count = atomic_read(&s->cycle_count2) - 1;
373         pl->packets[PACKET_LIST_SIZE - 1].db->payload_desc.branch = 0;
374
375         spin_lock_irqsave(&s->packet_list_lock, flags);
376         list_add_tail(&pl->link, &s->dma_packet_lists);
377         spin_unlock_irqrestore(&s->packet_list_lock, flags);
378
379         prev = list_entry(pl->link.prev, struct packet_list, link);
380         if (pl->link.prev != &s->dma_packet_lists) {
381                 struct packet *last = &prev->packets[PACKET_LIST_SIZE - 1];
382                 last->db->payload_desc.branch = pl->packets[0].db_bus | 3;
383                 last->db->header_desc.skip = pl->packets[0].db_bus | 3;
384                 ohci1394_wake_it_ctx(s->host->ohci, s->iso_tasklet.context);
385         }
386         else
387                 stream_start_dma(s, pl);
388 }
389
390 static void stream_shift_packet_lists(unsigned long l)
391 {
392         struct stream *s = (struct stream *) l;
393         struct packet_list *pl;
394         struct packet *last;
395         int diff;
396
397         if (list_empty(&s->dma_packet_lists)) {
398                 HPSB_ERR("empty dma_packet_lists in %s", __FUNCTION__);
399                 return;
400         }
401
402         /* Now that we know the list is non-empty, we can get the head
403          * of the list without locking, because the process context
404          * only adds to the tail.  
405          */
406         pl = list_entry(s->dma_packet_lists.next, struct packet_list, link);
407         last = &pl->packets[PACKET_LIST_SIZE - 1];
408
409         /* This is weird... if we stop dma processing in the middle of
410          * a packet list, the dma context immediately generates an
411          * interrupt if we enable it again later.  This only happens
412          * when amdtp_release is interrupted while waiting for dma to
413          * complete, though.  Anyway, we detect this by seeing that
414          * the status of the dma descriptor that we expected an
415          * interrupt from is still 0.
416          */
417         if (last->db->payload_desc.status == 0) {
418                 HPSB_INFO("weird interrupt...");
419                 return;
420         }               
421
422         /* If the last descriptor block does not specify a branch
423          * address, we have a sample underflow.
424          */
425         if (last->db->payload_desc.branch == 0)
426                 HPSB_INFO("FIXME: sample underflow...");
427
428         /* Here we check when (which cycle) the last packet was sent
429          * and compare it to what the iso packer was using at the
430          * time.  If there is a mismatch, we adjust the cycle count in
431          * the iso packer.  However, there are still up to
432          * MAX_PACKET_LISTS packet lists queued with bad time stamps,
433          * so we disable time stamp monitoring for the next
434          * MAX_PACKET_LISTS packet lists.
435          */
436         diff = (last->db->payload_desc.status - pl->last_cycle_count) & 0xf;
437         if (diff > 0 && s->stale_count == 0) {
438                 atomic_add(diff, &s->cycle_count);
439                 atomic_add(diff, &s->cycle_count2);
440                 s->stale_count = MAX_PACKET_LISTS;
441         }
442
443         if (s->stale_count > 0)
444                 s->stale_count--;
445
446         /* Finally, we move the packet list that was just processed
447          * back to the free list, and notify any waiters.
448          */
449         spin_lock(&s->packet_list_lock);
450         list_del(&pl->link);
451         list_add_tail(&pl->link, &s->free_packet_lists);
452         spin_unlock(&s->packet_list_lock);
453
454         wake_up_interruptible(&s->packet_list_wait);
455 }
456
457 static struct packet *stream_current_packet(struct stream *s)
458 {
459         if (s->current_packet_list == NULL &&
460             (s->current_packet_list = stream_get_free_packet_list(s)) == NULL)
461                 return NULL;
462
463         return &s->current_packet_list->packets[s->current_packet];
464 }
465         
466 static void stream_queue_packet(struct stream *s)
467 {
468         s->current_packet++;
469         if (s->current_packet == PACKET_LIST_SIZE) {
470                 stream_put_dma_packet_list(s, s->current_packet_list);
471                 s->current_packet_list = NULL;
472                 s->current_packet = 0;
473         }
474 }
475
476 /* Integer fractional math.  When we transmit a 44k1Hz signal we must
477  * send 5 41/80 samples per isochronous cycle, as these occur 8000
478  * times a second.  Of course, we must send an integral number of
479  * samples in a packet, so we use the integer math to alternate
480  * between sending 5 and 6 samples per packet.
481  */
482
483 static void fraction_init(struct fraction *f, int numerator, int denominator)
484 {
485         f->integer = numerator / denominator;
486         f->numerator = numerator % denominator;
487         f->denominator = denominator;
488 }
489
490 static __inline__ void fraction_add(struct fraction *dst,
491                                     struct fraction *src1,
492                                     struct fraction *src2)
493 {
494         /* assert: src1->denominator == src2->denominator */
495
496         int sum, denom;
497
498         /* We use these two local variables to allow gcc to optimize
499          * the division and the modulo into only one division. */
500
501         sum = src1->numerator + src2->numerator;
502         denom = src1->denominator;
503         dst->integer = src1->integer + src2->integer + sum / denom;
504         dst->numerator = sum % denom;
505         dst->denominator = denom;
506 }
507
508 static __inline__ void fraction_sub_int(struct fraction *dst,
509                                         struct fraction *src, int integer)
510 {
511         dst->integer = src->integer - integer;
512         dst->numerator = src->numerator;
513         dst->denominator = src->denominator;
514 }
515
516 static __inline__ int fraction_floor(struct fraction *frac)
517 {
518         return frac->integer;
519 }
520
521 static __inline__ int fraction_ceil(struct fraction *frac)
522 {
523         return frac->integer + (frac->numerator > 0 ? 1 : 0);
524 }
525
526 void packet_initialize(struct packet *p, struct packet *next)
527 {
528         /* Here we initialize the dma descriptor block for
529          * transferring one iso packet.  We use two descriptors per
530          * packet: an OUTPUT_MORE_IMMMEDIATE descriptor for the
531          * IEEE1394 iso packet header and an OUTPUT_LAST descriptor
532          * for the payload.
533          */
534
535         p->db->header_desc.control =
536                 DMA_CTL_OUTPUT_MORE | DMA_CTL_IMMEDIATE | 8;
537
538         if (next) {
539                 p->db->payload_desc.control = 
540                         DMA_CTL_OUTPUT_LAST | DMA_CTL_BRANCH;
541                 p->db->payload_desc.branch = next->db_bus | 3;
542                 p->db->header_desc.skip = next->db_bus | 3;
543         }
544         else {
545                 p->db->payload_desc.control = 
546                         DMA_CTL_OUTPUT_LAST | DMA_CTL_BRANCH |
547                         DMA_CTL_UPDATE | DMA_CTL_IRQ;
548                 p->db->payload_desc.branch = 0;
549                 p->db->header_desc.skip = 0;
550         }
551         p->db->payload_desc.data_address = p->payload_bus;
552         p->db->payload_desc.status = 0;
553 }
554
555 struct packet_list *packet_list_alloc(struct stream *s)
556 {
557         int i;
558         struct packet_list *pl;
559         struct packet *next;
560
561         pl = kmalloc(sizeof *pl, SLAB_KERNEL);
562         if (pl == NULL)
563                 return NULL;
564
565         for (i = 0; i < PACKET_LIST_SIZE; i++) {
566                 struct packet *p = &pl->packets[i];
567                 p->db = pci_pool_alloc(s->descriptor_pool, SLAB_KERNEL,
568                                        &p->db_bus);
569                 p->payload = pci_pool_alloc(s->packet_pool, SLAB_KERNEL,
570                                             &p->payload_bus);
571         }
572
573         for (i = 0; i < PACKET_LIST_SIZE; i++) {
574                 if (i < PACKET_LIST_SIZE - 1)
575                         next = &pl->packets[i + 1];
576                 else 
577                         next = NULL;
578                 packet_initialize(&pl->packets[i], next);
579         }
580
581         return pl;
582 }
583
584 void packet_list_free(struct packet_list *pl, struct stream *s)
585 {
586         int i;
587
588         for (i = 0; i < PACKET_LIST_SIZE; i++) {
589                 struct packet *p = &pl->packets[i];
590                 pci_pool_free(s->descriptor_pool, p->db, p->db_bus);
591                 pci_pool_free(s->packet_pool, p->payload, p->payload_bus);
592         }
593         kfree(pl);
594 }
595
596 static struct buffer *buffer_alloc(int size)
597 {
598         struct buffer *b;
599
600         b = kmalloc(sizeof *b + size, SLAB_KERNEL);
601         b->head = 0;
602         b->tail = 0;
603         b->length = 0;
604         b->size = size;
605
606         return b;
607 }
608
609 static unsigned char *buffer_get_bytes(struct buffer *buffer, int size)
610 {
611         unsigned char *p;
612
613         if (buffer->head + size > buffer->size)
614                 BUG();
615
616         p = &buffer->data[buffer->head];
617         buffer->head += size;
618         if (buffer->head == buffer->size)
619                 buffer->head = 0;
620         buffer->length -= size;
621
622         return p;
623 }
624
625 static unsigned char *buffer_put_bytes(struct buffer *buffer,
626                                        size_t max, size_t *actual)
627 {
628         size_t length;
629         unsigned char *p;
630
631         p = &buffer->data[buffer->tail];
632         length = min(buffer->size - buffer->length, max);
633         if (buffer->tail + length < buffer->size) {
634                 *actual = length;
635                 buffer->tail += length;
636         }
637         else {
638                 *actual = buffer->size - buffer->tail;
639                  buffer->tail = 0;
640         }
641
642         buffer->length += *actual;
643         return p;
644 }
645
646 static u32 get_iec958_header_bits(struct stream *s, int sub_frame, u32 sample)
647 {
648         int csi, parity, shift;
649         int block_start;
650         u32 bits;
651
652         switch (s->iec958_frame_count) {
653         case 1:
654                 csi = s->format == AMDTP_FORMAT_IEC958_AC3;
655                 break;
656         case 2:
657         case 9:
658                 csi = 1;
659                 break;
660         case 24 ... 27:
661                 csi = (s->iec958_rate_code >> (27 - s->iec958_frame_count)) & 0x01;
662                 break;
663         default:
664                 csi = 0;
665                 break;
666         }
667
668         block_start = (s->iec958_frame_count == 0 && sub_frame == 0);
669
670         /* The parity bit is the xor of the sample bits and the
671          * channel status info bit. */
672         for (shift = 16, parity = sample ^ csi; shift > 0; shift >>= 1)
673                 parity ^= (parity >> shift);
674
675         bits =  (block_start << 5) |            /* Block start bit */
676                 ((sub_frame == 0) << 4) |       /* Subframe bit */
677                 ((parity & 1) << 3) |           /* Parity bit */
678                 (csi << 2);                     /* Channel status info bit */
679
680         return bits;
681 }
682
683 static u32 get_header_bits(struct stream *s, int sub_frame, u32 sample)
684 {
685         switch (s->format) {
686         case AMDTP_FORMAT_IEC958_PCM:
687         case AMDTP_FORMAT_IEC958_AC3:
688                 return get_iec958_header_bits(s, sub_frame, sample);
689                 
690         case AMDTP_FORMAT_RAW:
691                 return 0x40000000;
692
693         default:
694                 return 0;
695         }
696 }
697
698 static void fill_payload_le16(struct stream *s, quadlet_t *data, int nevents)
699 {
700         quadlet_t *event, sample, bits;
701         unsigned char *p;
702         int i, j;
703
704         for (i = 0, event = data; i < nevents; i++) {
705
706                 for (j = 0; j < s->dimension; j++) {
707                         p = buffer_get_bytes(s->input, 2);
708                         sample = (p[1] << 16) | (p[0] << 8);
709                         bits = get_header_bits(s, j, sample);
710                         event[j] = cpu_to_be32((bits << 24) | sample);
711                 }
712
713                 event += s->dimension;
714                 if (++s->iec958_frame_count == 192)
715                         s->iec958_frame_count = 0;
716         }
717 }
718
719 static void fill_packet(struct stream *s, struct packet *packet, int nevents)
720 {
721         int syt_index, syt, size;
722         u32 control;
723
724         size = (nevents * s->dimension + 2) * sizeof(quadlet_t);
725
726         /* Update DMA descriptors */
727         packet->db->payload_desc.status = 0;
728         control = packet->db->payload_desc.control & 0xffff0000;
729         packet->db->payload_desc.control = control | size;
730
731         /* Fill IEEE1394 headers */
732         packet->db->header_desc.header[0] =
733                 (SPEED_100 << 16) | (0x01 << 14) | 
734                 (s->iso_channel << 8) | (TCODE_ISO_DATA << 4);
735         packet->db->header_desc.header[1] = size << 16;
736         
737         /* Calculate synchronization timestamp (syt). First we
738          * determine syt_index, that is, the index in the packet of
739          * the sample for which the timestamp is valid. */
740         syt_index = (s->syt_interval - s->dbc) & (s->syt_interval - 1);
741         if (syt_index < nevents) {
742                 syt = ((atomic_read(&s->cycle_count) << 12) | 
743                        s->cycle_offset.integer) & 0xffff;
744                 fraction_add(&s->cycle_offset, 
745                              &s->cycle_offset, &s->ticks_per_syt_offset);
746
747                 /* This next addition should be modulo 8000 (0x1f40),
748                  * but we only use the lower 4 bits of cycle_count, so
749                  * we dont need the modulo. */
750                 atomic_add(s->cycle_offset.integer / 3072, &s->cycle_count);
751                 s->cycle_offset.integer %= 3072;
752         }
753         else
754                 syt = 0xffff;
755
756         atomic_inc(&s->cycle_count2);
757         
758         /* Fill cip header */
759         packet->payload->eoh0 = 0;
760         packet->payload->sid = s->host->host->node_id & 0x3f;
761         packet->payload->dbs = s->dimension;
762         packet->payload->fn = 0;
763         packet->payload->qpc = 0;
764         packet->payload->sph = 0;
765         packet->payload->reserved = 0;
766         packet->payload->dbc = s->dbc;
767         packet->payload->eoh1 = 2;
768         packet->payload->fmt = FMT_AMDTP;
769         packet->payload->fdf = s->fdf;
770         packet->payload->syt = cpu_to_be16(syt);
771
772         switch (s->sample_format) {
773         case AMDTP_INPUT_LE16:
774                 fill_payload_le16(s, packet->payload->data, nevents);
775                 break;
776         }
777
778         s->dbc += nevents;
779 }
780
781 static void stream_flush(struct stream *s)
782 {
783         struct packet *p;
784         int nevents;
785         struct fraction next;
786
787         /* The AMDTP specifies two transmission modes: blocking and
788          * non-blocking.  In blocking mode you always transfer
789          * syt_interval or zero samples, whereas in non-blocking mode
790          * you send as many samples as you have available at transfer
791          * time.
792          *
793          * The fraction samples_per_cycle specifies the number of
794          * samples that become available per cycle.  We add this to
795          * the fraction ready_samples, which specifies the number of
796          * leftover samples from the previous transmission.  The sum,
797          * stored in the fraction next, specifies the number of
798          * samples available for transmission, and from this we
799          * determine the number of samples to actually transmit.
800          */
801
802         while (1) {
803                 fraction_add(&next, &s->ready_samples, &s->samples_per_cycle);
804                 if (s->mode == AMDTP_MODE_BLOCKING) {
805                         if (fraction_floor(&next) >= s->syt_interval)
806                                 nevents = s->syt_interval;
807                         else
808                                 nevents = 0;
809                 }
810                 else
811                         nevents = fraction_floor(&next);
812
813                 p = stream_current_packet(s);
814                 if (s->input->length < nevents * s->dimension * 2 || p == NULL)
815                         break;
816
817                 fill_packet(s, p, nevents);
818                 stream_queue_packet(s);
819
820                 /* Now that we have successfully queued the packet for
821                  * transmission, we update the fraction ready_samples. */
822                 fraction_sub_int(&s->ready_samples, &next, nevents);
823         }
824 }
825
826 static int stream_alloc_packet_lists(struct stream *s)
827 {
828         int max_nevents, max_packet_size, i;
829
830         if (s->mode == AMDTP_MODE_BLOCKING)
831                 max_nevents = s->syt_interval;
832         else
833                 max_nevents = fraction_ceil(&s->samples_per_cycle);
834
835         max_packet_size = max_nevents * s->dimension * 4 + 8;
836         s->packet_pool = pci_pool_create("packet pool", s->host->ohci->dev,
837                                          max_packet_size, 0, 0 ,SLAB_KERNEL);
838
839         if (s->packet_pool == NULL)
840                 return -1;
841
842         INIT_LIST_HEAD(&s->free_packet_lists);
843         INIT_LIST_HEAD(&s->dma_packet_lists);
844         for (i = 0; i < MAX_PACKET_LISTS; i++) {
845                 struct packet_list *pl = packet_list_alloc(s);
846                 if (pl == NULL)
847                         break;
848                 list_add_tail(&pl->link, &s->free_packet_lists);
849         }
850
851         return i < MAX_PACKET_LISTS ? -1 : 0;
852 }
853
854 static void stream_free_packet_lists(struct stream *s)
855 {
856         struct list_head *lh, *next;
857
858         if (s->current_packet_list != NULL)
859                 packet_list_free(s->current_packet_list, s);
860         list_for_each_safe(lh, next, &s->dma_packet_lists)
861                 packet_list_free(list_entry(lh, struct packet_list, link), s);
862         list_for_each_safe(lh, next, &s->free_packet_lists)
863                 packet_list_free(list_entry(lh, struct packet_list, link), s);
864         if (s->packet_pool != NULL)
865                 pci_pool_destroy(s->packet_pool);
866
867         s->current_packet_list = NULL;
868         INIT_LIST_HEAD(&s->free_packet_lists);
869         INIT_LIST_HEAD(&s->dma_packet_lists);
870         s->packet_pool = NULL;
871 }
872
873 static void plug_update(struct cmp_pcr *plug, void *data)
874 {
875         struct stream *s = data;
876
877         HPSB_INFO("plug update: p2p_count=%d, channel=%d",
878                   plug->p2p_count, plug->channel);
879         s->iso_channel = plug->channel;
880         if (plug->p2p_count > 0) {
881                 struct packet_list *pl;
882
883                 pl = list_entry(s->dma_packet_lists.next, struct packet_list, link);
884                 stream_start_dma(s, pl);
885         }
886         else {
887                 ohci1394_stop_it_ctx(s->host->ohci, s->iso_tasklet.context, 0);
888         }
889 }
890
891 static int stream_configure(struct stream *s, int cmd, struct amdtp_ioctl *cfg)
892 {
893         const int transfer_delay = 9000;
894
895         if (cfg->format <= AMDTP_FORMAT_IEC958_AC3)
896                 s->format = cfg->format;
897         else
898                 return -EINVAL;
899
900         switch (cfg->rate) {
901         case 32000:
902                 s->syt_interval = 8;
903                 s->fdf = FDF_SFC_32KHZ;
904                 s->iec958_rate_code = 0x0c;
905                 break;
906         case 44100:
907                 s->syt_interval = 8;
908                 s->fdf = FDF_SFC_44K1HZ;
909                 s->iec958_rate_code = 0x00;
910                 break;
911         case 48000:
912                 s->syt_interval = 8;
913                 s->fdf = FDF_SFC_48KHZ;
914                 s->iec958_rate_code = 0x04;
915                 break;
916         case 88200:
917                 s->syt_interval = 16;
918                 s->fdf = FDF_SFC_88K2HZ;
919                 s->iec958_rate_code = 0x00;
920                 break;
921         case 96000:
922                 s->syt_interval = 16;
923                 s->fdf = FDF_SFC_96KHZ;
924                 s->iec958_rate_code = 0x00;
925                 break;
926         case 176400:
927                 s->syt_interval = 32;
928                 s->fdf = FDF_SFC_176K4HZ;
929                 s->iec958_rate_code = 0x00;
930                 break;
931         case 192000:
932                 s->syt_interval = 32;
933                 s->fdf = FDF_SFC_192KHZ;
934                 s->iec958_rate_code = 0x00;
935                 break;
936
937         default:
938                 return -EINVAL;
939         }
940
941         s->rate = cfg->rate;
942         fraction_init(&s->samples_per_cycle, s->rate, 8000);
943         fraction_init(&s->ready_samples, 0, 8000);
944
945         /* The ticks_per_syt_offset is initialized to the number of
946          * ticks between syt_interval events.  The number of ticks per
947          * second is 24.576e6, so the number of ticks between
948          * syt_interval events is 24.576e6 * syt_interval / rate.
949          */
950         fraction_init(&s->ticks_per_syt_offset,
951                       24576000 * s->syt_interval, s->rate);
952         fraction_init(&s->cycle_offset, (transfer_delay % 3072) * s->rate, s->rate);
953         atomic_set(&s->cycle_count, transfer_delay / 3072);
954         atomic_set(&s->cycle_count2, 0);
955
956         s->mode = cfg->mode;
957         s->sample_format = AMDTP_INPUT_LE16;
958
959         /* When using the AM824 raw subformat we can stream signals of
960          * any dimension.  The IEC958 subformat, however, only
961          * supports 2 channels.
962          */
963         if (s->format == AMDTP_FORMAT_RAW || cfg->dimension == 2)
964                 s->dimension = cfg->dimension;
965         else
966                 return -EINVAL;
967
968         if (s->opcr != NULL) {
969                 cmp_unregister_opcr(s->host->host, s->opcr);
970                 s->opcr = NULL;
971         }
972
973         switch(cmd) {
974         case AMDTP_IOC_PLUG:
975                 s->opcr = cmp_register_opcr(s->host->host, cfg->u.plug,
976                                            /*payload*/ 12, plug_update, s);
977                 if (s->opcr == NULL)
978                         return -EINVAL;
979                 s->iso_channel = s->opcr->channel;
980                 break;
981
982         case AMDTP_IOC_CHANNEL:
983                 if (cfg->u.channel >= 0 && cfg->u.channel < 64)
984                         s->iso_channel = cfg->u.channel;
985                 else
986                         return -EINVAL;
987                 break;
988         }
989
990         /* The ioctl settings were all valid, so we realloc the packet
991          * lists to make sure the packet size is big enough.
992          */
993         if (s->packet_pool != NULL)
994                 stream_free_packet_lists(s);
995
996         if (stream_alloc_packet_lists(s) < 0) {
997                 stream_free_packet_lists(s);
998                 return -ENOMEM;
999         }
1000
1001         return 0;
1002 }
1003
1004 struct stream *stream_alloc(struct amdtp_host *host)
1005 {
1006         struct stream *s;
1007         unsigned long flags;
1008
1009         s = kmalloc(sizeof(struct stream), SLAB_KERNEL);
1010         if (s == NULL)
1011                 return NULL;
1012
1013         memset(s, 0, sizeof(struct stream));
1014         s->host = host;
1015
1016         s->input = buffer_alloc(BUFFER_SIZE);
1017         if (s->input == NULL) {
1018                 kfree(s);
1019                 return NULL;
1020         }
1021
1022         s->descriptor_pool = pci_pool_create("descriptor pool", host->ohci->dev,
1023                                              sizeof(struct descriptor_block),
1024                                              16, 0, SLAB_KERNEL);
1025
1026         if (s->descriptor_pool == NULL) {
1027                 kfree(s->input);
1028                 kfree(s);
1029                 return NULL;
1030         }
1031
1032         INIT_LIST_HEAD(&s->free_packet_lists);
1033         INIT_LIST_HEAD(&s->dma_packet_lists);
1034
1035         init_waitqueue_head(&s->packet_list_wait);
1036         spin_lock_init(&s->packet_list_lock);
1037
1038         ohci1394_init_iso_tasklet(&s->iso_tasklet, OHCI_ISO_TRANSMIT,
1039                                   stream_shift_packet_lists,
1040                                   (unsigned long) s);
1041
1042         if (ohci1394_register_iso_tasklet(host->ohci, &s->iso_tasklet) < 0) {
1043                 pci_pool_destroy(s->descriptor_pool);
1044                 kfree(s->input);
1045                 kfree(s);
1046                 return NULL;
1047         }
1048
1049         spin_lock_irqsave(&host->stream_list_lock, flags);
1050         list_add_tail(&s->link, &host->stream_list);
1051         spin_unlock_irqrestore(&host->stream_list_lock, flags);
1052
1053         return s;
1054 }
1055
1056 void stream_free(struct stream *s)
1057 {
1058         unsigned long flags;
1059
1060         /* Stop the DMA.  We wait for the dma packet list to become
1061          * empty and let the dma controller run out of programs.  This
1062          * seems to be more reliable than stopping it directly, since
1063          * that sometimes generates an it transmit interrupt if we
1064          * later re-enable the context.
1065          */
1066         wait_event_interruptible(s->packet_list_wait, 
1067                                  list_empty(&s->dma_packet_lists));
1068
1069         ohci1394_stop_it_ctx(s->host->ohci, s->iso_tasklet.context, 1);
1070         ohci1394_unregister_iso_tasklet(s->host->ohci, &s->iso_tasklet);
1071
1072         if (s->opcr != NULL)
1073                 cmp_unregister_opcr(s->host->host, s->opcr);
1074
1075         spin_lock_irqsave(&s->host->stream_list_lock, flags);
1076         list_del(&s->link);
1077         spin_unlock_irqrestore(&s->host->stream_list_lock, flags);
1078
1079         kfree(s->input);
1080
1081         stream_free_packet_lists(s);
1082         pci_pool_destroy(s->descriptor_pool);
1083
1084         kfree(s);
1085 }
1086
1087 /* File operations */
1088
1089 static ssize_t amdtp_write(struct file *file, const char *buffer, size_t count,
1090                            loff_t *offset_is_ignored)
1091 {
1092         struct stream *s = file->private_data;
1093         unsigned char *p;
1094         int i;
1095         size_t length;
1096         
1097         if (s->packet_pool == NULL)
1098                 return -EBADFD;
1099
1100         /* Fill the circular buffer from the input buffer and call the
1101          * iso packer when the buffer is full.  The iso packer may
1102          * leave bytes in the buffer for two reasons: either the
1103          * remaining bytes wasn't enough to build a new packet, or
1104          * there were no free packet lists.  In the first case we
1105          * re-fill the buffer and call the iso packer again or return
1106          * if we used all the data from userspace.  In the second
1107          * case, the wait_event_interruptible will block until the irq
1108          * handler frees a packet list.
1109          */
1110
1111         for (i = 0; i < count; i += length) {
1112                 p = buffer_put_bytes(s->input, count, &length);
1113                 copy_from_user(p, buffer + i, length);
1114                 if (s->input->length < s->input->size)
1115                         continue;
1116                 
1117                 stream_flush(s);
1118                 
1119                 if (s->current_packet_list != NULL)
1120                         continue;
1121
1122                 if (file->f_flags & O_NONBLOCK)
1123                         return i + length > 0 ? i + length : -EAGAIN;
1124
1125                 if (wait_event_interruptible(s->packet_list_wait, 
1126                                              !list_empty(&s->free_packet_lists)))
1127                         return -EINTR;
1128         }
1129
1130         return count;
1131 }
1132
1133 static int amdtp_ioctl(struct inode *inode, struct file *file,
1134                            unsigned int cmd, unsigned long arg)
1135 {
1136         struct stream *s = file->private_data;
1137         struct amdtp_ioctl cfg;
1138
1139         switch(cmd)
1140         {
1141         case AMDTP_IOC_PLUG:
1142         case AMDTP_IOC_CHANNEL:
1143                 if (copy_from_user(&cfg, (struct amdtp_ioctl *) arg, sizeof cfg))
1144                         return -EFAULT;
1145                 else 
1146                         return stream_configure(s, cmd, &cfg);
1147
1148         default:
1149                 return -EINVAL;
1150         }
1151 }
1152
1153 static unsigned int amdtp_poll(struct file *file, poll_table *pt)
1154 {
1155         struct stream *s = file->private_data;
1156
1157         poll_wait(file, &s->packet_list_wait, pt);
1158
1159         if (!list_empty(&s->free_packet_lists))
1160                 return POLLOUT | POLLWRNORM;
1161         else
1162                 return 0;
1163 }
1164
1165 static int amdtp_open(struct inode *inode, struct file *file)
1166 {
1167         struct amdtp_host *host;
1168
1169         /* FIXME: We just grab the first registered host */
1170         spin_lock(&host_list_lock);
1171         if (!list_empty(&host_list))
1172                 host = list_entry(host_list.next, struct amdtp_host, link);
1173         else
1174                 host = NULL;
1175         spin_unlock(&host_list_lock);
1176
1177         if (host == NULL)
1178                 return -ENODEV;
1179
1180         file->private_data = stream_alloc(host);
1181         if (file->private_data == NULL)
1182                 return -ENOMEM;
1183
1184         return 0;
1185 }
1186
1187 static int amdtp_release(struct inode *inode, struct file *file)
1188 {
1189         struct stream *s = file->private_data;
1190
1191         stream_free(s);
1192
1193         return 0;
1194 }
1195
1196 static struct file_operations amdtp_fops =
1197 {
1198         .owner =        THIS_MODULE,
1199         .write =        amdtp_write,
1200         .poll =         amdtp_poll,
1201         .ioctl =        amdtp_ioctl,
1202         .open =         amdtp_open,
1203         .release =      amdtp_release
1204 };
1205
1206 /* IEEE1394 Subsystem functions */
1207
1208 static void amdtp_add_host(struct hpsb_host *host)
1209 {
1210         struct amdtp_host *ah;
1211
1212         if (strcmp(host->driver->name, OHCI1394_DRIVER_NAME) != 0)
1213                 return;
1214
1215         ah = kmalloc(sizeof *ah, SLAB_KERNEL);
1216         ah->host = host;
1217         ah->ohci = host->hostdata;
1218         INIT_LIST_HEAD(&ah->stream_list);
1219         spin_lock_init(&ah->stream_list_lock);
1220
1221         spin_lock_irq(&host_list_lock);
1222         list_add_tail(&ah->link, &host_list);
1223         spin_unlock_irq(&host_list_lock);
1224 }
1225
1226 static void amdtp_remove_host(struct hpsb_host *host)
1227 {
1228         struct list_head *lh;
1229         struct amdtp_host *ah;
1230
1231         spin_lock_irq(&host_list_lock);
1232         list_for_each(lh, &host_list) {
1233                 if (list_entry(lh, struct amdtp_host, link)->host == host) {
1234                         list_del(lh);
1235                         break;
1236                 }
1237         }
1238         spin_unlock_irq(&host_list_lock);
1239         
1240         if (lh != &host_list) {
1241                 ah = list_entry(lh, struct amdtp_host, link);
1242                 kfree(ah);
1243         }
1244         else
1245                 HPSB_ERR("remove_host: bogus ohci host: %p", host);
1246 }
1247
1248 static struct hpsb_highlevel_ops amdtp_highlevel_ops = {
1249         .add_host =     amdtp_add_host,
1250         .remove_host =  amdtp_remove_host,
1251 };
1252
1253 /* Module interface */
1254
1255 MODULE_AUTHOR("Kristian Hogsberg <hogsberg@users.sf.net>");
1256 MODULE_DESCRIPTION("Driver for Audio & Music Data Transmission Protocol "
1257                    "on OHCI boards.");
1258 MODULE_SUPPORTED_DEVICE("amdtp");
1259 MODULE_LICENSE("GPL");
1260
1261 static int __init amdtp_init_module (void)
1262 {
1263         if (ieee1394_register_chardev(IEEE1394_MINOR_BLOCK_AMDTP,
1264                                       THIS_MODULE, &amdtp_fops)) {
1265                 HPSB_ERR("amdtp: unable to get minor device block");
1266                 return -EIO;
1267         }
1268
1269         amdtp_highlevel = hpsb_register_highlevel ("amdtp",
1270                                                    &amdtp_highlevel_ops);
1271         if (amdtp_highlevel == NULL) {
1272                 HPSB_ERR("amdtp: unable to register highlevel ops");
1273                 ieee1394_unregister_chardev(IEEE1394_MINOR_BLOCK_AMDTP);
1274                 return -EIO;
1275         }
1276
1277         HPSB_INFO("Loaded AMDTP driver");
1278
1279         return 0;
1280 }
1281
1282 static void __exit amdtp_exit_module (void)
1283 {
1284         hpsb_unregister_highlevel(amdtp_highlevel);
1285         ieee1394_unregister_chardev(IEEE1394_MINOR_BLOCK_AMDTP);
1286
1287         HPSB_INFO("Unloaded AMDTP driver");
1288 }
1289
1290 module_init(amdtp_init_module);
1291 module_exit(amdtp_exit_module);