firewire: Implement functionality to stop isochronous DMA contexts.
[safe/jmp/linux-2.6] / drivers / firewire / fw-ohci.c
1 /*                                              -*- c-basic-offset: 8 -*-
2  *
3  * fw-ohci.c - Driver for OHCI 1394 boards
4  * Copyright (C) 2003-2006 Kristian Hoegsberg <krh@bitplanet.net>
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 #include <linux/kernel.h>
22 #include <linux/module.h>
23 #include <linux/init.h>
24 #include <linux/interrupt.h>
25 #include <linux/pci.h>
26 #include <linux/delay.h>
27 #include <linux/poll.h>
28 #include <linux/dma-mapping.h>
29
30 #include <asm/uaccess.h>
31 #include <asm/semaphore.h>
32
33 #include "fw-transaction.h"
34 #include "fw-ohci.h"
35
36 #define descriptor_output_more          0
37 #define descriptor_output_last          (1 << 12)
38 #define descriptor_input_more           (2 << 12)
39 #define descriptor_input_last           (3 << 12)
40 #define descriptor_status               (1 << 11)
41 #define descriptor_key_immediate        (2 << 8)
42 #define descriptor_ping                 (1 << 7)
43 #define descriptor_yy                   (1 << 6)
44 #define descriptor_no_irq               (0 << 4)
45 #define descriptor_irq_error            (1 << 4)
46 #define descriptor_irq_always           (3 << 4)
47 #define descriptor_branch_always        (3 << 2)
48 #define descriptor_wait                 (3 << 0)
49
50 struct descriptor {
51         __le16 req_count;
52         __le16 control;
53         __le32 data_address;
54         __le32 branch_address;
55         __le16 res_count;
56         __le16 transfer_status;
57 } __attribute__((aligned(16)));
58
59 struct db_descriptor {
60         __le16 first_size;
61         __le16 control;
62         __le16 second_req_count;
63         __le16 first_req_count;
64         __le32 branch_address;
65         __le16 second_res_count;
66         __le16 first_res_count;
67         __le32 reserved0;
68         __le32 first_buffer;
69         __le32 second_buffer;
70         __le32 reserved1;
71 } __attribute__((aligned(16)));
72
73 #define control_set(regs)       (regs)
74 #define control_clear(regs)     ((regs) + 4)
75 #define command_ptr(regs)       ((regs) + 12)
76 #define context_match(regs)     ((regs) + 16)
77
78 struct ar_buffer {
79         struct descriptor descriptor;
80         struct ar_buffer *next;
81         __le32 data[0];
82 };
83
84 struct ar_context {
85         struct fw_ohci *ohci;
86         struct ar_buffer *current_buffer;
87         struct ar_buffer *last_buffer;
88         void *pointer;
89         u32 regs;
90         struct tasklet_struct tasklet;
91 };
92
93 struct context;
94
95 typedef int (*descriptor_callback_t)(struct context *ctx,
96                                      struct descriptor *d,
97                                      struct descriptor *last);
98 struct context {
99         struct fw_ohci *ohci;
100         u32 regs;
101  
102         struct descriptor *buffer;
103         dma_addr_t buffer_bus;
104         size_t buffer_size;
105         struct descriptor *head_descriptor;
106         struct descriptor *tail_descriptor;
107         struct descriptor *tail_descriptor_last;
108         struct descriptor *prev_descriptor;
109
110         descriptor_callback_t callback;
111
112         struct tasklet_struct tasklet;
113 };
114  
115
116
117 struct at_context {
118         struct fw_ohci *ohci;
119         dma_addr_t descriptor_bus;
120         dma_addr_t buffer_bus;
121         struct fw_packet *current_packet;
122
123         struct list_head list;
124
125         struct {
126                 struct descriptor more;
127                 __le32 header[4];
128                 struct descriptor last;
129         } d;
130
131         u32 regs;
132
133         struct tasklet_struct tasklet;
134 };
135
136 #define it_header_sy(v)          ((v) <<  0)
137 #define it_header_tcode(v)       ((v) <<  4)
138 #define it_header_channel(v)     ((v) <<  8)
139 #define it_header_tag(v)         ((v) << 14)
140 #define it_header_speed(v)       ((v) << 16)
141 #define it_header_data_length(v) ((v) << 16)
142
143 struct iso_context {
144         struct fw_iso_context base;
145         struct context context;
146 };
147
148 #define CONFIG_ROM_SIZE 1024
149
150 struct fw_ohci {
151         struct fw_card card;
152
153         __iomem char *registers;
154         dma_addr_t self_id_bus;
155         __le32 *self_id_cpu;
156         struct tasklet_struct bus_reset_tasklet;
157         int node_id;
158         int generation;
159         int request_generation;
160
161         /* Spinlock for accessing fw_ohci data.  Never call out of
162          * this driver with this lock held. */
163         spinlock_t lock;
164         u32 self_id_buffer[512];
165
166         /* Config rom buffers */
167         __be32 *config_rom;
168         dma_addr_t config_rom_bus;
169         __be32 *next_config_rom;
170         dma_addr_t next_config_rom_bus;
171         u32 next_header;
172
173         struct ar_context ar_request_ctx;
174         struct ar_context ar_response_ctx;
175         struct at_context at_request_ctx;
176         struct at_context at_response_ctx;
177
178         u32 it_context_mask;
179         struct iso_context *it_context_list;
180         u32 ir_context_mask;
181         struct iso_context *ir_context_list;
182 };
183
184 static inline struct fw_ohci *fw_ohci(struct fw_card *card)
185 {
186         return container_of(card, struct fw_ohci, card);
187 }
188
189 #define IT_CONTEXT_CYCLE_MATCH_ENABLE   0x80000000
190 #define IR_CONTEXT_BUFFER_FILL          0x80000000
191 #define IR_CONTEXT_ISOCH_HEADER         0x40000000
192 #define IR_CONTEXT_CYCLE_MATCH_ENABLE   0x20000000
193 #define IR_CONTEXT_MULTI_CHANNEL_MODE   0x10000000
194 #define IR_CONTEXT_DUAL_BUFFER_MODE     0x08000000
195
196 #define CONTEXT_RUN     0x8000
197 #define CONTEXT_WAKE    0x1000
198 #define CONTEXT_DEAD    0x0800
199 #define CONTEXT_ACTIVE  0x0400
200
201 #define OHCI1394_MAX_AT_REQ_RETRIES     0x2
202 #define OHCI1394_MAX_AT_RESP_RETRIES    0x2
203 #define OHCI1394_MAX_PHYS_RESP_RETRIES  0x8
204
205 #define FW_OHCI_MAJOR                   240
206 #define OHCI1394_REGISTER_SIZE          0x800
207 #define OHCI_LOOP_COUNT                 500
208 #define OHCI1394_PCI_HCI_Control        0x40
209 #define SELF_ID_BUF_SIZE                0x800
210 #define OHCI_TCODE_PHY_PACKET           0x0e
211
212 static char ohci_driver_name[] = KBUILD_MODNAME;
213
214 static inline void reg_write(const struct fw_ohci *ohci, int offset, u32 data)
215 {
216         writel(data, ohci->registers + offset);
217 }
218
219 static inline u32 reg_read(const struct fw_ohci *ohci, int offset)
220 {
221         return readl(ohci->registers + offset);
222 }
223
224 static inline void flush_writes(const struct fw_ohci *ohci)
225 {
226         /* Do a dummy read to flush writes. */
227         reg_read(ohci, OHCI1394_Version);
228 }
229
230 static int
231 ohci_update_phy_reg(struct fw_card *card, int addr,
232                     int clear_bits, int set_bits)
233 {
234         struct fw_ohci *ohci = fw_ohci(card);
235         u32 val, old;
236
237         reg_write(ohci, OHCI1394_PhyControl, OHCI1394_PhyControl_Read(addr));
238         msleep(2);
239         val = reg_read(ohci, OHCI1394_PhyControl);
240         if ((val & OHCI1394_PhyControl_ReadDone) == 0) {
241                 fw_error("failed to set phy reg bits.\n");
242                 return -EBUSY;
243         }
244
245         old = OHCI1394_PhyControl_ReadData(val);
246         old = (old & ~clear_bits) | set_bits;
247         reg_write(ohci, OHCI1394_PhyControl,
248                   OHCI1394_PhyControl_Write(addr, old));
249
250         return 0;
251 }
252
253 static int ar_context_add_page(struct ar_context *ctx)
254 {
255         struct device *dev = ctx->ohci->card.device;
256         struct ar_buffer *ab;
257         dma_addr_t ab_bus;
258         size_t offset;
259
260         ab = (struct ar_buffer *) __get_free_page(GFP_ATOMIC);
261         if (ab == NULL)
262                 return -ENOMEM;
263
264         ab_bus = dma_map_single(dev, ab, PAGE_SIZE, DMA_BIDIRECTIONAL);
265         if (dma_mapping_error(ab_bus)) {
266                 free_page((unsigned long) ab);
267                 return -ENOMEM;
268         }
269
270         memset(&ab->descriptor, 0, sizeof ab->descriptor);
271         ab->descriptor.control        = cpu_to_le16(descriptor_input_more |
272                                                     descriptor_status |
273                                                     descriptor_branch_always);
274         offset = offsetof(struct ar_buffer, data);
275         ab->descriptor.req_count      = cpu_to_le16(PAGE_SIZE - offset);
276         ab->descriptor.data_address   = cpu_to_le32(ab_bus + offset);
277         ab->descriptor.res_count      = cpu_to_le16(PAGE_SIZE - offset);
278         ab->descriptor.branch_address = 0;
279
280         dma_sync_single_for_device(dev, ab_bus, PAGE_SIZE, DMA_BIDIRECTIONAL);
281
282         ctx->last_buffer->descriptor.branch_address = ab_bus | 1;
283         ctx->last_buffer->next = ab;
284         ctx->last_buffer = ab;
285
286         reg_write(ctx->ohci, control_set(ctx->regs), CONTEXT_WAKE);
287         flush_writes(ctx->ohci);
288
289         return 0;
290 }
291
292 static __le32 *handle_ar_packet(struct ar_context *ctx, __le32 *buffer)
293 {
294         struct fw_ohci *ohci = ctx->ohci;
295         struct fw_packet p;
296         u32 status, length, tcode;
297
298         p.header[0] = le32_to_cpu(buffer[0]);
299         p.header[1] = le32_to_cpu(buffer[1]);
300         p.header[2] = le32_to_cpu(buffer[2]);
301
302         tcode = (p.header[0] >> 4) & 0x0f;
303         switch (tcode) {
304         case TCODE_WRITE_QUADLET_REQUEST:
305         case TCODE_READ_QUADLET_RESPONSE:
306                 p.header[3] = (__force __u32) buffer[3];
307                 p.header_length = 16;
308                 p.payload_length = 0;
309                 break;
310
311         case TCODE_READ_BLOCK_REQUEST :
312                 p.header[3] = le32_to_cpu(buffer[3]);
313                 p.header_length = 16;
314                 p.payload_length = 0;
315                 break;
316
317         case TCODE_WRITE_BLOCK_REQUEST:
318         case TCODE_READ_BLOCK_RESPONSE:
319         case TCODE_LOCK_REQUEST:
320         case TCODE_LOCK_RESPONSE:
321                 p.header[3] = le32_to_cpu(buffer[3]);
322                 p.header_length = 16;
323                 p.payload_length = p.header[3] >> 16;
324                 break;
325
326         case TCODE_WRITE_RESPONSE:
327         case TCODE_READ_QUADLET_REQUEST:
328         case OHCI_TCODE_PHY_PACKET:
329                 p.header_length = 12;
330                 p.payload_length = 0;
331                 break;
332         }
333
334         p.payload = (void *) buffer + p.header_length;
335
336         /* FIXME: What to do about evt_* errors? */
337         length = (p.header_length + p.payload_length + 3) / 4;
338         status = le32_to_cpu(buffer[length]);
339
340         p.ack        = ((status >> 16) & 0x1f) - 16;
341         p.speed      = (status >> 21) & 0x7;
342         p.timestamp  = status & 0xffff;
343         p.generation = ohci->request_generation;
344
345         /* The OHCI bus reset handler synthesizes a phy packet with
346          * the new generation number when a bus reset happens (see
347          * section 8.4.2.3).  This helps us determine when a request
348          * was received and make sure we send the response in the same
349          * generation.  We only need this for requests; for responses
350          * we use the unique tlabel for finding the matching
351          * request. */
352
353         if (p.ack + 16 == 0x09)
354                 ohci->request_generation = (buffer[2] >> 16) & 0xff;
355         else if (ctx == &ohci->ar_request_ctx)
356                 fw_core_handle_request(&ohci->card, &p);
357         else
358                 fw_core_handle_response(&ohci->card, &p);
359
360         return buffer + length + 1;
361 }
362
363 static void ar_context_tasklet(unsigned long data)
364 {
365         struct ar_context *ctx = (struct ar_context *)data;
366         struct fw_ohci *ohci = ctx->ohci;
367         struct ar_buffer *ab;
368         struct descriptor *d;
369         void *buffer, *end;
370
371         ab = ctx->current_buffer;
372         d = &ab->descriptor;
373
374         if (d->res_count == 0) {
375                 size_t size, rest, offset;
376
377                 /* This descriptor is finished and we may have a
378                  * packet split across this and the next buffer. We
379                  * reuse the page for reassembling the split packet. */
380
381                 offset = offsetof(struct ar_buffer, data);
382                 dma_unmap_single(ohci->card.device,
383                                  ab->descriptor.data_address - offset,
384                                  PAGE_SIZE, DMA_BIDIRECTIONAL);
385
386                 buffer = ab;
387                 ab = ab->next;
388                 d = &ab->descriptor;
389                 size = buffer + PAGE_SIZE - ctx->pointer;
390                 rest = le16_to_cpu(d->req_count) - le16_to_cpu(d->res_count);
391                 memmove(buffer, ctx->pointer, size);
392                 memcpy(buffer + size, ab->data, rest);
393                 ctx->current_buffer = ab;
394                 ctx->pointer = (void *) ab->data + rest;
395                 end = buffer + size + rest;
396
397                 while (buffer < end)
398                         buffer = handle_ar_packet(ctx, buffer);
399
400                 free_page((unsigned long)buffer);
401                 ar_context_add_page(ctx);
402         } else {
403                 buffer = ctx->pointer;
404                 ctx->pointer = end =
405                         (void *) ab + PAGE_SIZE - le16_to_cpu(d->res_count);
406
407                 while (buffer < end)
408                         buffer = handle_ar_packet(ctx, buffer);
409         }
410 }
411
412 static int
413 ar_context_init(struct ar_context *ctx, struct fw_ohci *ohci, u32 regs)
414 {
415         struct ar_buffer ab;
416
417         ctx->regs        = regs;
418         ctx->ohci        = ohci;
419         ctx->last_buffer = &ab;
420         tasklet_init(&ctx->tasklet, ar_context_tasklet, (unsigned long)ctx);
421
422         ar_context_add_page(ctx);
423         ar_context_add_page(ctx);
424         ctx->current_buffer = ab.next;
425         ctx->pointer = ctx->current_buffer->data;
426
427         reg_write(ctx->ohci, command_ptr(ctx->regs), ab.descriptor.branch_address);
428         reg_write(ctx->ohci, control_set(ctx->regs), CONTEXT_RUN);
429         flush_writes(ctx->ohci);
430
431         return 0;
432 }
433  
434 static void context_tasklet(unsigned long data)
435 {
436         struct context *ctx = (struct context *) data;
437         struct fw_ohci *ohci = ctx->ohci;
438         struct descriptor *d, *last;
439         u32 address;
440         int z;
441
442         dma_sync_single_for_cpu(ohci->card.device, ctx->buffer_bus,
443                                 ctx->buffer_size, DMA_TO_DEVICE);
444
445         d    = ctx->tail_descriptor;
446         last = ctx->tail_descriptor_last;
447
448         while (last->branch_address != 0) {
449                 address = le32_to_cpu(last->branch_address);
450                 z = address & 0xf;
451                 d = ctx->buffer + (address - ctx->buffer_bus) / sizeof *d;
452                 last = (z == 2) ? d : d + z - 1;
453
454                 if (!ctx->callback(ctx, d, last))
455                         break;
456
457                 ctx->tail_descriptor      = d;
458                 ctx->tail_descriptor_last = last;
459         }
460 }
461
462 static int
463 context_init(struct context *ctx, struct fw_ohci *ohci,
464              size_t buffer_size, u32 regs,
465              descriptor_callback_t callback)
466 {
467         ctx->ohci = ohci;
468         ctx->regs = regs;
469         ctx->buffer_size = buffer_size;
470         ctx->buffer = kmalloc(buffer_size, GFP_KERNEL);
471         if (ctx->buffer == NULL)
472                 return -ENOMEM;
473
474         tasklet_init(&ctx->tasklet, context_tasklet, (unsigned long)ctx);
475         ctx->callback = callback;
476
477         ctx->buffer_bus =
478                 dma_map_single(ohci->card.device, ctx->buffer,
479                                buffer_size, DMA_TO_DEVICE);
480         if (dma_mapping_error(ctx->buffer_bus)) {
481                 kfree(ctx->buffer);
482                 return -ENOMEM;
483         }
484
485         ctx->head_descriptor      = ctx->buffer;
486         ctx->prev_descriptor      = ctx->buffer;
487         ctx->tail_descriptor      = ctx->buffer;
488         ctx->tail_descriptor_last = ctx->buffer;
489
490         /* We put a dummy descriptor in the buffer that has a NULL
491          * branch address and looks like it's been sent.  That way we
492          * have a descriptor to append DMA programs to.  Also, the
493          * ring buffer invariant is that it always has at least one
494          * element so that head == tail means buffer full. */
495
496         memset(ctx->head_descriptor, 0, sizeof *ctx->head_descriptor);
497         ctx->head_descriptor->control = cpu_to_le16(descriptor_output_last);
498         ctx->head_descriptor->transfer_status = cpu_to_le16(0x8011);
499         ctx->head_descriptor++;
500
501         return 0;
502 }
503
504  static void
505 context_release(struct context *ctx)
506 {
507         struct fw_card *card = &ctx->ohci->card;
508
509         dma_unmap_single(card->device, ctx->buffer_bus,
510                          ctx->buffer_size, DMA_TO_DEVICE);
511         kfree(ctx->buffer);
512 }
513
514 static struct descriptor *
515 context_get_descriptors(struct context *ctx, int z, dma_addr_t *d_bus)
516 {
517         struct descriptor *d, *tail, *end;
518
519         d = ctx->head_descriptor;
520         tail = ctx->tail_descriptor;
521         end = ctx->buffer + ctx->buffer_size / sizeof(struct descriptor);
522
523         if (d + z <= tail) {
524                 goto has_space;
525         } else if (d > tail && d + z <= end) {
526                 goto has_space;
527         } else if (d > tail && ctx->buffer + z <= tail) {
528                 d = ctx->buffer;
529                 goto has_space;
530         }
531
532         return NULL;
533
534  has_space:
535         memset(d, 0, z * sizeof *d);
536         *d_bus = ctx->buffer_bus + (d - ctx->buffer) * sizeof *d;
537
538         return d;
539 }
540
541 static void context_run(struct context *ctx, u32 extra)
542 {
543         struct fw_ohci *ohci = ctx->ohci;
544
545         reg_write(ohci, command_ptr(ctx->regs),
546                   le32_to_cpu(ctx->tail_descriptor_last->branch_address));
547         reg_write(ohci, control_clear(ctx->regs), ~0);
548         reg_write(ohci, control_set(ctx->regs), CONTEXT_RUN | extra);
549         flush_writes(ohci);
550 }
551
552 static void context_append(struct context *ctx,
553                            struct descriptor *d, int z, int extra)
554 {
555         dma_addr_t d_bus;
556
557         d_bus = ctx->buffer_bus + (d - ctx->buffer) * sizeof *d;
558
559         ctx->head_descriptor = d + z + extra;
560         ctx->prev_descriptor->branch_address = cpu_to_le32(d_bus | z);
561         ctx->prev_descriptor = z == 2 ? d : d + z - 1;
562
563         dma_sync_single_for_device(ctx->ohci->card.device, ctx->buffer_bus,
564                                    ctx->buffer_size, DMA_TO_DEVICE);
565
566         reg_write(ctx->ohci, control_set(ctx->regs), CONTEXT_WAKE);
567         flush_writes(ctx->ohci);
568 }
569
570 static void context_stop(struct context *ctx)
571 {
572         u32 reg;
573         int i;
574
575         reg_write(ctx->ohci, control_clear(ctx->regs), CONTEXT_RUN);
576         flush_writes(ctx->ohci);
577
578         for (i = 0; i < 10; i++) {
579                 reg = reg_read(ctx->ohci, control_set(ctx->regs));
580                 if ((reg & CONTEXT_ACTIVE) == 0)
581                         break;
582
583                 fw_notify("context_stop: still active (0x%08x)\n", reg);
584                 msleep(1);
585         }
586 }
587
588 static void
589 do_packet_callbacks(struct fw_ohci *ohci, struct list_head *list)
590 {
591         struct fw_packet *p, *next;
592
593         list_for_each_entry_safe(p, next, list, link)
594                 p->callback(p, &ohci->card, p->ack);
595 }
596
597 static void
598 complete_transmission(struct fw_packet *packet,
599                       int ack, struct list_head *list)
600 {
601         list_move_tail(&packet->link, list);
602         packet->ack = ack;
603 }
604
605 /* This function prepares the first packet in the context queue for
606  * transmission.  Must always be called with the ochi->lock held to
607  * ensure proper generation handling and locking around packet queue
608  * manipulation. */
609 static void
610 at_context_setup_packet(struct at_context *ctx, struct list_head *list)
611 {
612         struct fw_packet *packet;
613         struct fw_ohci *ohci = ctx->ohci;
614         int z, tcode;
615
616         packet = fw_packet(ctx->list.next);
617
618         memset(&ctx->d, 0, sizeof ctx->d);
619         if (packet->payload_length > 0) {
620                 packet->payload_bus = dma_map_single(ohci->card.device,
621                                                      packet->payload,
622                                                      packet->payload_length,
623                                                      DMA_TO_DEVICE);
624                 if (dma_mapping_error(packet->payload_bus)) {
625                         complete_transmission(packet, RCODE_SEND_ERROR, list);
626                         return;
627                 }
628
629                 ctx->d.more.control      =
630                         cpu_to_le16(descriptor_output_more |
631                                     descriptor_key_immediate);
632                 ctx->d.more.req_count    = cpu_to_le16(packet->header_length);
633                 ctx->d.more.res_count    = cpu_to_le16(packet->timestamp);
634                 ctx->d.last.control      =
635                         cpu_to_le16(descriptor_output_last |
636                                     descriptor_irq_always |
637                                     descriptor_branch_always);
638                 ctx->d.last.req_count    = cpu_to_le16(packet->payload_length);
639                 ctx->d.last.data_address = cpu_to_le32(packet->payload_bus);
640                 z = 3;
641         } else {
642                 ctx->d.more.control   =
643                         cpu_to_le16(descriptor_output_last |
644                                     descriptor_key_immediate |
645                                     descriptor_irq_always |
646                                     descriptor_branch_always);
647                 ctx->d.more.req_count = cpu_to_le16(packet->header_length);
648                 ctx->d.more.res_count = cpu_to_le16(packet->timestamp);
649                 z = 2;
650         }
651
652         /* The DMA format for asyncronous link packets is different
653          * from the IEEE1394 layout, so shift the fields around
654          * accordingly.  If header_length is 8, it's a PHY packet, to
655          * which we need to prepend an extra quadlet. */
656         if (packet->header_length > 8) {
657                 ctx->d.header[0] = cpu_to_le32((packet->header[0] & 0xffff) |
658                                                (packet->speed << 16));
659                 ctx->d.header[1] = cpu_to_le32((packet->header[1] & 0xffff) |
660                                                (packet->header[0] & 0xffff0000));
661                 ctx->d.header[2] = cpu_to_le32(packet->header[2]);
662
663                 tcode = (packet->header[0] >> 4) & 0x0f;
664                 if (TCODE_IS_BLOCK_PACKET(tcode))
665                         ctx->d.header[3] = cpu_to_le32(packet->header[3]);
666                 else
667                         ctx->d.header[3] = packet->header[3];
668         } else {
669                 ctx->d.header[0] =
670                         cpu_to_le32((OHCI1394_phy_tcode << 4) |
671                                     (packet->speed << 16));
672                 ctx->d.header[1] = cpu_to_le32(packet->header[0]);
673                 ctx->d.header[2] = cpu_to_le32(packet->header[1]);
674                 ctx->d.more.req_count = cpu_to_le16(12);
675         }
676
677         /* FIXME: Document how the locking works. */
678         if (ohci->generation == packet->generation) {
679                 reg_write(ctx->ohci, command_ptr(ctx->regs),
680                           ctx->descriptor_bus | z);
681                 reg_write(ctx->ohci, control_set(ctx->regs),
682                           CONTEXT_RUN | CONTEXT_WAKE);
683                 ctx->current_packet = packet;
684         } else {
685                 /* We dont return error codes from this function; all
686                  * transmission errors are reported through the
687                  * callback. */
688                 complete_transmission(packet, RCODE_GENERATION, list);
689         }
690 }
691
692 static void at_context_stop(struct at_context *ctx)
693 {
694         u32 reg;
695
696         reg_write(ctx->ohci, control_clear(ctx->regs), CONTEXT_RUN);
697
698         reg = reg_read(ctx->ohci, control_set(ctx->regs));
699         if (reg & CONTEXT_ACTIVE)
700                 fw_notify("Tried to stop context, but it is still active "
701                           "(0x%08x).\n", reg);
702 }
703
704 static void at_context_tasklet(unsigned long data)
705 {
706         struct at_context *ctx = (struct at_context *)data;
707         struct fw_ohci *ohci = ctx->ohci;
708         struct fw_packet *packet;
709         LIST_HEAD(list);
710         unsigned long flags;
711         int evt;
712
713         spin_lock_irqsave(&ohci->lock, flags);
714
715         packet = fw_packet(ctx->list.next);
716
717         at_context_stop(ctx);
718
719         /* If the head of the list isn't the packet that just got
720          * transmitted, the packet got cancelled before we finished
721          * transmitting it. */
722         if (ctx->current_packet != packet)
723                 goto skip_to_next;
724
725         if (packet->payload_length > 0) {
726                 dma_unmap_single(ohci->card.device, packet->payload_bus,
727                                  packet->payload_length, DMA_TO_DEVICE);
728                 evt = le16_to_cpu(ctx->d.last.transfer_status) & 0x1f;
729                 packet->timestamp = le16_to_cpu(ctx->d.last.res_count);
730         }
731         else {
732                 evt = le16_to_cpu(ctx->d.more.transfer_status) & 0x1f;
733                 packet->timestamp = le16_to_cpu(ctx->d.more.res_count);
734         }
735
736         if (evt < 16) {
737                 switch (evt) {
738                 case OHCI1394_evt_timeout:
739                         /* Async response transmit timed out. */
740                         complete_transmission(packet, RCODE_CANCELLED, &list);
741                         break;
742
743                 case OHCI1394_evt_flushed:
744                         /* The packet was flushed should give same
745                          * error as when we try to use a stale
746                          * generation count. */
747                         complete_transmission(packet,
748                                               RCODE_GENERATION, &list);
749                         break;
750
751                 case OHCI1394_evt_missing_ack:
752                         /* Using a valid (current) generation count,
753                          * but the node is not on the bus or not
754                          * sending acks. */
755                         complete_transmission(packet, RCODE_NO_ACK, &list);
756                         break;
757
758                 default:
759                         complete_transmission(packet, RCODE_SEND_ERROR, &list);
760                         break;
761                 }
762         } else
763                 complete_transmission(packet, evt - 16, &list);
764
765  skip_to_next:
766         /* If more packets are queued, set up the next one. */
767         if (!list_empty(&ctx->list))
768                 at_context_setup_packet(ctx, &list);
769
770         spin_unlock_irqrestore(&ohci->lock, flags);
771
772         do_packet_callbacks(ohci, &list);
773 }
774
775 static int
776 at_context_init(struct at_context *ctx, struct fw_ohci *ohci, u32 regs)
777 {
778         INIT_LIST_HEAD(&ctx->list);
779
780         ctx->descriptor_bus =
781                 dma_map_single(ohci->card.device, &ctx->d,
782                                sizeof ctx->d, DMA_TO_DEVICE);
783         if (dma_mapping_error(ctx->descriptor_bus))
784                 return -ENOMEM;
785
786         ctx->regs = regs;
787         ctx->ohci = ohci;
788
789         tasklet_init(&ctx->tasklet, at_context_tasklet, (unsigned long)ctx);
790
791         return 0;
792 }
793
794 #define header_get_destination(q)       (((q) >> 16) & 0xffff)
795 #define header_get_tcode(q)             (((q) >> 4) & 0x0f)
796 #define header_get_offset_high(q)       (((q) >> 0) & 0xffff)
797 #define header_get_data_length(q)       (((q) >> 16) & 0xffff)
798 #define header_get_extended_tcode(q)    (((q) >> 0) & 0xffff)
799
800 static void
801 handle_local_rom(struct fw_ohci *ohci, struct fw_packet *packet, u32 csr)
802 {
803         struct fw_packet response;
804         int tcode, length, i;
805
806         tcode = header_get_tcode(packet->header[0]);
807         if (TCODE_IS_BLOCK_PACKET(tcode))
808                 length = header_get_data_length(packet->header[3]);
809         else
810                 length = 4;
811
812         i = csr - CSR_CONFIG_ROM;
813         if (i + length > CONFIG_ROM_SIZE) {
814                 fw_fill_response(&response, packet->header,
815                                  RCODE_ADDRESS_ERROR, NULL, 0);
816         } else if (!TCODE_IS_READ_REQUEST(tcode)) {
817                 fw_fill_response(&response, packet->header,
818                                  RCODE_TYPE_ERROR, NULL, 0);
819         } else {
820                 fw_fill_response(&response, packet->header, RCODE_COMPLETE,
821                                  (void *) ohci->config_rom + i, length);
822         }
823
824         fw_core_handle_response(&ohci->card, &response);
825 }
826
827 static void
828 handle_local_lock(struct fw_ohci *ohci, struct fw_packet *packet, u32 csr)
829 {
830         struct fw_packet response;
831         int tcode, length, ext_tcode, sel;
832         __be32 *payload, lock_old;
833         u32 lock_arg, lock_data;
834
835         tcode = header_get_tcode(packet->header[0]);
836         length = header_get_data_length(packet->header[3]);
837         payload = packet->payload;
838         ext_tcode = header_get_extended_tcode(packet->header[3]);
839
840         if (tcode == TCODE_LOCK_REQUEST &&
841             ext_tcode == EXTCODE_COMPARE_SWAP && length == 8) {
842                 lock_arg = be32_to_cpu(payload[0]);
843                 lock_data = be32_to_cpu(payload[1]);
844         } else if (tcode == TCODE_READ_QUADLET_REQUEST) {
845                 lock_arg = 0;
846                 lock_data = 0;
847         } else {
848                 fw_fill_response(&response, packet->header,
849                                  RCODE_TYPE_ERROR, NULL, 0);
850                 goto out;
851         }
852
853         sel = (csr - CSR_BUS_MANAGER_ID) / 4;
854         reg_write(ohci, OHCI1394_CSRData, lock_data);
855         reg_write(ohci, OHCI1394_CSRCompareData, lock_arg);
856         reg_write(ohci, OHCI1394_CSRControl, sel);
857
858         if (reg_read(ohci, OHCI1394_CSRControl) & 0x80000000)
859                 lock_old = cpu_to_be32(reg_read(ohci, OHCI1394_CSRData));
860         else
861                 fw_notify("swap not done yet\n");
862
863         fw_fill_response(&response, packet->header,
864                          RCODE_COMPLETE, &lock_old, sizeof lock_old);
865  out:
866         fw_core_handle_response(&ohci->card, &response);
867 }
868
869 static void
870 handle_local_request(struct at_context *ctx, struct fw_packet *packet)
871 {
872         u64 offset;
873         u32 csr;
874
875         packet->ack = ACK_PENDING;
876         packet->callback(packet, &ctx->ohci->card, packet->ack);
877
878         offset =
879                 ((unsigned long long)
880                  header_get_offset_high(packet->header[1]) << 32) |
881                 packet->header[2];
882         csr = offset - CSR_REGISTER_BASE;
883
884         /* Handle config rom reads. */
885         if (csr >= CSR_CONFIG_ROM && csr < CSR_CONFIG_ROM_END)
886                 handle_local_rom(ctx->ohci, packet, csr);
887         else switch (csr) {
888         case CSR_BUS_MANAGER_ID:
889         case CSR_BANDWIDTH_AVAILABLE:
890         case CSR_CHANNELS_AVAILABLE_HI:
891         case CSR_CHANNELS_AVAILABLE_LO:
892                 handle_local_lock(ctx->ohci, packet, csr);
893                 break;
894         default:
895                 if (ctx == &ctx->ohci->at_request_ctx)
896                         fw_core_handle_request(&ctx->ohci->card, packet);
897                 else
898                         fw_core_handle_response(&ctx->ohci->card, packet);
899                 break;
900         }
901 }
902
903 static void
904 at_context_transmit(struct at_context *ctx, struct fw_packet *packet)
905 {
906         LIST_HEAD(list);
907         unsigned long flags;
908
909         spin_lock_irqsave(&ctx->ohci->lock, flags);
910
911         if (header_get_destination(packet->header[0]) == ctx->ohci->node_id &&
912             ctx->ohci->generation == packet->generation) {
913                 spin_unlock_irqrestore(&ctx->ohci->lock, flags);
914                 handle_local_request(ctx, packet);
915                 return;
916         }
917
918         list_add_tail(&packet->link, &ctx->list);
919         if (ctx->list.next == &packet->link)
920                 at_context_setup_packet(ctx, &list);
921
922         spin_unlock_irqrestore(&ctx->ohci->lock, flags);
923
924         do_packet_callbacks(ctx->ohci, &list);
925 }
926
927 static void bus_reset_tasklet(unsigned long data)
928 {
929         struct fw_ohci *ohci = (struct fw_ohci *)data;
930         int self_id_count, i, j, reg;
931         int generation, new_generation;
932         unsigned long flags;
933
934         reg = reg_read(ohci, OHCI1394_NodeID);
935         if (!(reg & OHCI1394_NodeID_idValid)) {
936                 fw_error("node ID not valid, new bus reset in progress\n");
937                 return;
938         }
939         ohci->node_id = reg & 0xffff;
940
941         /* The count in the SelfIDCount register is the number of
942          * bytes in the self ID receive buffer.  Since we also receive
943          * the inverted quadlets and a header quadlet, we shift one
944          * bit extra to get the actual number of self IDs. */
945
946         self_id_count = (reg_read(ohci, OHCI1394_SelfIDCount) >> 3) & 0x3ff;
947         generation = (le32_to_cpu(ohci->self_id_cpu[0]) >> 16) & 0xff;
948
949         for (i = 1, j = 0; j < self_id_count; i += 2, j++) {
950                 if (ohci->self_id_cpu[i] != ~ohci->self_id_cpu[i + 1])
951                         fw_error("inconsistent self IDs\n");
952                 ohci->self_id_buffer[j] = le32_to_cpu(ohci->self_id_cpu[i]);
953         }
954
955         /* Check the consistency of the self IDs we just read.  The
956          * problem we face is that a new bus reset can start while we
957          * read out the self IDs from the DMA buffer. If this happens,
958          * the DMA buffer will be overwritten with new self IDs and we
959          * will read out inconsistent data.  The OHCI specification
960          * (section 11.2) recommends a technique similar to
961          * linux/seqlock.h, where we remember the generation of the
962          * self IDs in the buffer before reading them out and compare
963          * it to the current generation after reading them out.  If
964          * the two generations match we know we have a consistent set
965          * of self IDs. */
966
967         new_generation = (reg_read(ohci, OHCI1394_SelfIDCount) >> 16) & 0xff;
968         if (new_generation != generation) {
969                 fw_notify("recursive bus reset detected, "
970                           "discarding self ids\n");
971                 return;
972         }
973
974         /* FIXME: Document how the locking works. */
975         spin_lock_irqsave(&ohci->lock, flags);
976
977         ohci->generation = generation;
978         at_context_stop(&ohci->at_request_ctx);
979         at_context_stop(&ohci->at_response_ctx);
980         reg_write(ohci, OHCI1394_IntEventClear, OHCI1394_busReset);
981
982         /* This next bit is unrelated to the AT context stuff but we
983          * have to do it under the spinlock also.  If a new config rom
984          * was set up before this reset, the old one is now no longer
985          * in use and we can free it. Update the config rom pointers
986          * to point to the current config rom and clear the
987          * next_config_rom pointer so a new udpate can take place. */
988
989         if (ohci->next_config_rom != NULL) {
990                 dma_free_coherent(ohci->card.device, CONFIG_ROM_SIZE,
991                                   ohci->config_rom, ohci->config_rom_bus);
992                 ohci->config_rom      = ohci->next_config_rom;
993                 ohci->config_rom_bus  = ohci->next_config_rom_bus;
994                 ohci->next_config_rom = NULL;
995
996                 /* Restore config_rom image and manually update
997                  * config_rom registers.  Writing the header quadlet
998                  * will indicate that the config rom is ready, so we
999                  * do that last. */
1000                 reg_write(ohci, OHCI1394_BusOptions,
1001                           be32_to_cpu(ohci->config_rom[2]));
1002                 ohci->config_rom[0] = cpu_to_be32(ohci->next_header);
1003                 reg_write(ohci, OHCI1394_ConfigROMhdr, ohci->next_header);
1004         }
1005
1006         spin_unlock_irqrestore(&ohci->lock, flags);
1007
1008         fw_core_handle_bus_reset(&ohci->card, ohci->node_id, generation,
1009                                  self_id_count, ohci->self_id_buffer);
1010 }
1011
1012 static irqreturn_t irq_handler(int irq, void *data)
1013 {
1014         struct fw_ohci *ohci = data;
1015         u32 event, iso_event;
1016         int i;
1017
1018         event = reg_read(ohci, OHCI1394_IntEventClear);
1019
1020         if (!event)
1021                 return IRQ_NONE;
1022
1023         reg_write(ohci, OHCI1394_IntEventClear, event);
1024
1025         if (event & OHCI1394_selfIDComplete)
1026                 tasklet_schedule(&ohci->bus_reset_tasklet);
1027
1028         if (event & OHCI1394_RQPkt)
1029                 tasklet_schedule(&ohci->ar_request_ctx.tasklet);
1030
1031         if (event & OHCI1394_RSPkt)
1032                 tasklet_schedule(&ohci->ar_response_ctx.tasklet);
1033
1034         if (event & OHCI1394_reqTxComplete)
1035                 tasklet_schedule(&ohci->at_request_ctx.tasklet);
1036
1037         if (event & OHCI1394_respTxComplete)
1038                 tasklet_schedule(&ohci->at_response_ctx.tasklet);
1039
1040         iso_event = reg_read(ohci, OHCI1394_IsoRecvIntEventClear);
1041         reg_write(ohci, OHCI1394_IsoRecvIntEventClear, iso_event);
1042
1043         while (iso_event) {
1044                 i = ffs(iso_event) - 1;
1045                 tasklet_schedule(&ohci->ir_context_list[i].context.tasklet);
1046                 iso_event &= ~(1 << i);
1047         }
1048
1049         iso_event = reg_read(ohci, OHCI1394_IsoXmitIntEventClear);
1050         reg_write(ohci, OHCI1394_IsoXmitIntEventClear, iso_event);
1051
1052         while (iso_event) {
1053                 i = ffs(iso_event) - 1;
1054                 tasklet_schedule(&ohci->it_context_list[i].context.tasklet);
1055                 iso_event &= ~(1 << i);
1056         }
1057
1058         return IRQ_HANDLED;
1059 }
1060
1061 static int ohci_enable(struct fw_card *card, u32 *config_rom, size_t length)
1062 {
1063         struct fw_ohci *ohci = fw_ohci(card);
1064         struct pci_dev *dev = to_pci_dev(card->device);
1065
1066         /* When the link is not yet enabled, the atomic config rom
1067          * update mechanism described below in ohci_set_config_rom()
1068          * is not active.  We have to update ConfigRomHeader and
1069          * BusOptions manually, and the write to ConfigROMmap takes
1070          * effect immediately.  We tie this to the enabling of the
1071          * link, so we have a valid config rom before enabling - the
1072          * OHCI requires that ConfigROMhdr and BusOptions have valid
1073          * values before enabling.
1074          *
1075          * However, when the ConfigROMmap is written, some controllers
1076          * always read back quadlets 0 and 2 from the config rom to
1077          * the ConfigRomHeader and BusOptions registers on bus reset.
1078          * They shouldn't do that in this initial case where the link
1079          * isn't enabled.  This means we have to use the same
1080          * workaround here, setting the bus header to 0 and then write
1081          * the right values in the bus reset tasklet.
1082          */
1083
1084         ohci->next_config_rom =
1085                 dma_alloc_coherent(ohci->card.device, CONFIG_ROM_SIZE,
1086                                    &ohci->next_config_rom_bus, GFP_KERNEL);
1087         if (ohci->next_config_rom == NULL)
1088                 return -ENOMEM;
1089
1090         memset(ohci->next_config_rom, 0, CONFIG_ROM_SIZE);
1091         fw_memcpy_to_be32(ohci->next_config_rom, config_rom, length * 4);
1092
1093         ohci->next_header = config_rom[0];
1094         ohci->next_config_rom[0] = 0;
1095         reg_write(ohci, OHCI1394_ConfigROMhdr, 0);
1096         reg_write(ohci, OHCI1394_BusOptions, config_rom[2]);
1097         reg_write(ohci, OHCI1394_ConfigROMmap, ohci->next_config_rom_bus);
1098
1099         reg_write(ohci, OHCI1394_AsReqFilterHiSet, 0x80000000);
1100
1101         if (request_irq(dev->irq, irq_handler,
1102                         SA_SHIRQ, ohci_driver_name, ohci)) {
1103                 fw_error("Failed to allocate shared interrupt %d.\n",
1104                          dev->irq);
1105                 dma_free_coherent(ohci->card.device, CONFIG_ROM_SIZE,
1106                                   ohci->config_rom, ohci->config_rom_bus);
1107                 return -EIO;
1108         }
1109
1110         reg_write(ohci, OHCI1394_HCControlSet,
1111                   OHCI1394_HCControl_linkEnable |
1112                   OHCI1394_HCControl_BIBimageValid);
1113         flush_writes(ohci);
1114
1115         /* We are ready to go, initiate bus reset to finish the
1116          * initialization. */
1117
1118         fw_core_initiate_bus_reset(&ohci->card, 1);
1119
1120         return 0;
1121 }
1122
1123 static int
1124 ohci_set_config_rom(struct fw_card *card, u32 *config_rom, size_t length)
1125 {
1126         struct fw_ohci *ohci;
1127         unsigned long flags;
1128         int retval = 0;
1129         __be32 *next_config_rom;
1130         dma_addr_t next_config_rom_bus;
1131
1132         ohci = fw_ohci(card);
1133
1134         /* When the OHCI controller is enabled, the config rom update
1135          * mechanism is a bit tricky, but easy enough to use.  See
1136          * section 5.5.6 in the OHCI specification.
1137          *
1138          * The OHCI controller caches the new config rom address in a
1139          * shadow register (ConfigROMmapNext) and needs a bus reset
1140          * for the changes to take place.  When the bus reset is
1141          * detected, the controller loads the new values for the
1142          * ConfigRomHeader and BusOptions registers from the specified
1143          * config rom and loads ConfigROMmap from the ConfigROMmapNext
1144          * shadow register. All automatically and atomically.
1145          *
1146          * Now, there's a twist to this story.  The automatic load of
1147          * ConfigRomHeader and BusOptions doesn't honor the
1148          * noByteSwapData bit, so with a be32 config rom, the
1149          * controller will load be32 values in to these registers
1150          * during the atomic update, even on litte endian
1151          * architectures.  The workaround we use is to put a 0 in the
1152          * header quadlet; 0 is endian agnostic and means that the
1153          * config rom isn't ready yet.  In the bus reset tasklet we
1154          * then set up the real values for the two registers.
1155          *
1156          * We use ohci->lock to avoid racing with the code that sets
1157          * ohci->next_config_rom to NULL (see bus_reset_tasklet).
1158          */
1159
1160         next_config_rom =
1161                 dma_alloc_coherent(ohci->card.device, CONFIG_ROM_SIZE,
1162                                    &next_config_rom_bus, GFP_KERNEL);
1163         if (next_config_rom == NULL)
1164                 return -ENOMEM;
1165
1166         spin_lock_irqsave(&ohci->lock, flags);
1167
1168         if (ohci->next_config_rom == NULL) {
1169                 ohci->next_config_rom = next_config_rom;
1170                 ohci->next_config_rom_bus = next_config_rom_bus;
1171
1172                 memset(ohci->next_config_rom, 0, CONFIG_ROM_SIZE);
1173                 fw_memcpy_to_be32(ohci->next_config_rom, config_rom,
1174                                   length * 4);
1175
1176                 ohci->next_header = config_rom[0];
1177                 ohci->next_config_rom[0] = 0;
1178
1179                 reg_write(ohci, OHCI1394_ConfigROMmap,
1180                           ohci->next_config_rom_bus);
1181         } else {
1182                 dma_free_coherent(ohci->card.device, CONFIG_ROM_SIZE,
1183                                   next_config_rom, next_config_rom_bus);
1184                 retval = -EBUSY;
1185         }
1186
1187         spin_unlock_irqrestore(&ohci->lock, flags);
1188
1189         /* Now initiate a bus reset to have the changes take
1190          * effect. We clean up the old config rom memory and DMA
1191          * mappings in the bus reset tasklet, since the OHCI
1192          * controller could need to access it before the bus reset
1193          * takes effect. */
1194         if (retval == 0)
1195                 fw_core_initiate_bus_reset(&ohci->card, 1);
1196
1197         return retval;
1198 }
1199
1200 static void ohci_send_request(struct fw_card *card, struct fw_packet *packet)
1201 {
1202         struct fw_ohci *ohci = fw_ohci(card);
1203
1204         at_context_transmit(&ohci->at_request_ctx, packet);
1205 }
1206
1207 static void ohci_send_response(struct fw_card *card, struct fw_packet *packet)
1208 {
1209         struct fw_ohci *ohci = fw_ohci(card);
1210
1211         at_context_transmit(&ohci->at_response_ctx, packet);
1212 }
1213
1214 static int ohci_cancel_packet(struct fw_card *card, struct fw_packet *packet)
1215 {
1216         struct fw_ohci *ohci = fw_ohci(card);
1217         LIST_HEAD(list);
1218         unsigned long flags;
1219
1220         spin_lock_irqsave(&ohci->lock, flags);
1221
1222         if (packet->ack == 0) {
1223                 fw_notify("cancelling packet %p (header[0]=%08x)\n",
1224                           packet, packet->header[0]);
1225
1226                 complete_transmission(packet, RCODE_CANCELLED, &list);
1227         }
1228
1229         spin_unlock_irqrestore(&ohci->lock, flags);
1230
1231         do_packet_callbacks(ohci, &list);
1232
1233         /* Return success if we actually cancelled something. */
1234         return list_empty(&list) ? -ENOENT : 0;
1235 }
1236
1237 static int
1238 ohci_enable_phys_dma(struct fw_card *card, int node_id, int generation)
1239 {
1240         struct fw_ohci *ohci = fw_ohci(card);
1241         unsigned long flags;
1242         int n, retval = 0;
1243
1244         /* FIXME:  Make sure this bitmask is cleared when we clear the busReset
1245          * interrupt bit.  Clear physReqResourceAllBuses on bus reset. */
1246
1247         spin_lock_irqsave(&ohci->lock, flags);
1248
1249         if (ohci->generation != generation) {
1250                 retval = -ESTALE;
1251                 goto out;
1252         }
1253
1254         /* NOTE, if the node ID contains a non-local bus ID, physical DMA is
1255          * enabled for _all_ nodes on remote buses. */
1256
1257         n = (node_id & 0xffc0) == LOCAL_BUS ? node_id & 0x3f : 63;
1258         if (n < 32)
1259                 reg_write(ohci, OHCI1394_PhyReqFilterLoSet, 1 << n);
1260         else
1261                 reg_write(ohci, OHCI1394_PhyReqFilterHiSet, 1 << (n - 32));
1262
1263         flush_writes(ohci);
1264  out:
1265         spin_unlock_irqrestore(&ohci->lock, flags);
1266         return retval;
1267 }
1268
1269 static int handle_ir_packet(struct context *context,
1270                             struct descriptor *d,
1271                             struct descriptor *last)
1272 {
1273         struct iso_context *ctx =
1274                 container_of(context, struct iso_context, context);
1275         struct db_descriptor *db = (struct db_descriptor *) d;
1276  
1277         if (db->first_res_count > 0 && db->second_res_count > 0)
1278                 /* This descriptor isn't done yet, stop iteration. */
1279                 return 0;
1280
1281         if (le16_to_cpu(db->control) & descriptor_irq_always)
1282                 /* FIXME: we should pass payload address here. */
1283                 ctx->base.callback(&ctx->base,
1284                                    0, 0,
1285                                    ctx->base.callback_data);
1286
1287         return 1;
1288 }
1289
1290 #define ISO_BUFFER_SIZE (64 * 1024)
1291
1292 static int handle_it_packet(struct context *context,
1293                             struct descriptor *d,
1294                             struct descriptor *last)
1295 {
1296         struct iso_context *ctx =
1297                 container_of(context, struct iso_context, context);
1298  
1299         if (last->transfer_status == 0)
1300                 /* This descriptor isn't done yet, stop iteration. */
1301                 return 0;
1302
1303         if (le16_to_cpu(last->control) & descriptor_irq_always)
1304                 ctx->base.callback(&ctx->base,
1305                                    0, le16_to_cpu(last->res_count),
1306                                    ctx->base.callback_data);
1307
1308         return 1;
1309 }
1310
1311 static struct fw_iso_context *
1312 ohci_allocate_iso_context(struct fw_card *card, int type)
1313 {
1314         struct fw_ohci *ohci = fw_ohci(card);
1315         struct iso_context *ctx, *list;
1316         descriptor_callback_t callback;
1317         u32 *mask, regs;
1318         unsigned long flags;
1319         int index, retval;
1320
1321         if (type == FW_ISO_CONTEXT_TRANSMIT) {
1322                 mask = &ohci->it_context_mask;
1323                 list = ohci->it_context_list;
1324                 callback = handle_it_packet;
1325         } else {
1326                 mask = &ohci->ir_context_mask;
1327                 list = ohci->ir_context_list;
1328                 callback = handle_ir_packet;
1329         }
1330
1331         spin_lock_irqsave(&ohci->lock, flags);
1332         index = ffs(*mask) - 1;
1333         if (index >= 0)
1334                 *mask &= ~(1 << index);
1335         spin_unlock_irqrestore(&ohci->lock, flags);
1336
1337         if (index < 0)
1338                 return ERR_PTR(-EBUSY);
1339
1340         if (type == FW_ISO_CONTEXT_TRANSMIT)
1341                 regs = OHCI1394_IsoXmitContextBase(index);
1342         else
1343                 regs = OHCI1394_IsoRcvContextBase(index);
1344  
1345         ctx = &list[index];
1346         memset(ctx, 0, sizeof *ctx);
1347         retval = context_init(&ctx->context, ohci, ISO_BUFFER_SIZE,
1348                               regs, callback);
1349         if (retval < 0) {
1350                 spin_lock_irqsave(&ohci->lock, flags);
1351                 *mask |= 1 << index;
1352                 spin_unlock_irqrestore(&ohci->lock, flags);
1353                 return ERR_PTR(retval);
1354         }
1355
1356         return &ctx->base;
1357 }
1358
1359 static int ohci_start_iso(struct fw_iso_context *base, s32 cycle)
1360 {
1361         struct iso_context *ctx = container_of(base, struct iso_context, base);
1362         struct fw_ohci *ohci = ctx->context.ohci;
1363         u32 cycle_match = 0;
1364         int index;
1365
1366         if (ctx->base.type == FW_ISO_CONTEXT_TRANSMIT) {
1367                 index = ctx - ohci->it_context_list;
1368                 if (cycle > 0)
1369                         cycle_match = IT_CONTEXT_CYCLE_MATCH_ENABLE |
1370                                 (cycle & 0x7fff) << 16;
1371                 
1372                 reg_write(ohci, OHCI1394_IsoXmitIntEventClear, 1 << index);
1373                 reg_write(ohci, OHCI1394_IsoXmitIntMaskSet, 1 << index);
1374                 context_run(&ctx->context, cycle_match);
1375         } else {
1376                 index = ctx - ohci->ir_context_list;
1377
1378                 reg_write(ohci, OHCI1394_IsoRecvIntEventClear, 1 << index);
1379                 reg_write(ohci, OHCI1394_IsoRecvIntMaskSet, 1 << index);
1380                 reg_write(ohci, context_match(ctx->context.regs),
1381                           0xf0000000 | ctx->base.channel);
1382                 context_run(&ctx->context, IR_CONTEXT_DUAL_BUFFER_MODE);
1383         }
1384
1385         return 0;
1386 }
1387
1388 static int ohci_stop_iso(struct fw_iso_context *base)
1389 {
1390         struct fw_ohci *ohci = fw_ohci(base->card);
1391         struct iso_context *ctx = container_of(base, struct iso_context, base);
1392         int index;
1393
1394         if (ctx->base.type == FW_ISO_CONTEXT_TRANSMIT) {
1395                 index = ctx - ohci->it_context_list;
1396                 reg_write(ohci, OHCI1394_IsoXmitIntMaskClear, 1 << index);
1397         } else {
1398                 index = ctx - ohci->ir_context_list;
1399                 reg_write(ohci, OHCI1394_IsoRecvIntMaskClear, 1 << index);
1400         }
1401         flush_writes(ohci);
1402         context_stop(&ctx->context);
1403
1404         return 0;
1405 }
1406
1407 static void ohci_free_iso_context(struct fw_iso_context *base)
1408 {
1409         struct fw_ohci *ohci = fw_ohci(base->card);
1410         struct iso_context *ctx = container_of(base, struct iso_context, base);
1411         unsigned long flags;
1412         int index;
1413
1414         ohci_stop_iso(base);
1415         context_release(&ctx->context);
1416
1417         spin_lock_irqsave(&ohci->lock, flags);
1418
1419         if (ctx->base.type == FW_ISO_CONTEXT_TRANSMIT) {
1420                 index = ctx - ohci->it_context_list;
1421                 ohci->it_context_mask |= 1 << index;
1422         } else {
1423                 index = ctx - ohci->ir_context_list;
1424                 ohci->ir_context_mask |= 1 << index;
1425         }
1426
1427         spin_unlock_irqrestore(&ohci->lock, flags);
1428 }
1429
1430 static int
1431 ohci_queue_iso_transmit(struct fw_iso_context *base,
1432                         struct fw_iso_packet *packet,
1433                         struct fw_iso_buffer *buffer,
1434                         unsigned long payload)
1435 {
1436         struct iso_context *ctx = container_of(base, struct iso_context, base);
1437         struct descriptor *d, *last, *pd;
1438         struct fw_iso_packet *p;
1439         __le32 *header;
1440         dma_addr_t d_bus, page_bus;
1441         u32 z, header_z, payload_z, irq;
1442         u32 payload_index, payload_end_index, next_page_index;
1443         int page, end_page, i, length, offset;
1444
1445         /* FIXME: Cycle lost behavior should be configurable: lose
1446          * packet, retransmit or terminate.. */
1447
1448         p = packet;
1449         payload_index = payload;
1450
1451         if (p->skip)
1452                 z = 1;
1453         else
1454                 z = 2;
1455         if (p->header_length > 0)
1456                 z++;
1457
1458         /* Determine the first page the payload isn't contained in. */
1459         end_page = PAGE_ALIGN(payload_index + p->payload_length) >> PAGE_SHIFT;
1460         if (p->payload_length > 0)
1461                 payload_z = end_page - (payload_index >> PAGE_SHIFT);
1462         else
1463                 payload_z = 0;
1464
1465         z += payload_z;
1466
1467         /* Get header size in number of descriptors. */
1468         header_z = DIV_ROUND_UP(p->header_length, sizeof *d);
1469
1470         d = context_get_descriptors(&ctx->context, z + header_z, &d_bus);
1471         if (d == NULL)
1472                 return -ENOMEM;
1473
1474         if (!p->skip) {
1475                 d[0].control   = cpu_to_le16(descriptor_key_immediate);
1476                 d[0].req_count = cpu_to_le16(8);
1477
1478                 header = (__le32 *) &d[1];
1479                 header[0] = cpu_to_le32(it_header_sy(p->sy) |
1480                                         it_header_tag(p->tag) |
1481                                         it_header_tcode(TCODE_STREAM_DATA) |
1482                                         it_header_channel(ctx->base.channel) |
1483                                         it_header_speed(ctx->base.speed));
1484                 header[1] =
1485                         cpu_to_le32(it_header_data_length(p->header_length +
1486                                                           p->payload_length));
1487         }
1488
1489         if (p->header_length > 0) {
1490                 d[2].req_count    = cpu_to_le16(p->header_length);
1491                 d[2].data_address = cpu_to_le32(d_bus + z * sizeof *d);
1492                 memcpy(&d[z], p->header, p->header_length);
1493         }
1494
1495         pd = d + z - payload_z;
1496         payload_end_index = payload_index + p->payload_length;
1497         for (i = 0; i < payload_z; i++) {
1498                 page               = payload_index >> PAGE_SHIFT;
1499                 offset             = payload_index & ~PAGE_MASK;
1500                 next_page_index    = (page + 1) << PAGE_SHIFT;
1501                 length             =
1502                         min(next_page_index, payload_end_index) - payload_index;
1503                 pd[i].req_count    = cpu_to_le16(length);
1504
1505                 page_bus = page_private(buffer->pages[page]);
1506                 pd[i].data_address = cpu_to_le32(page_bus + offset);
1507
1508                 payload_index += length;
1509         }
1510
1511         if (p->interrupt)
1512                 irq = descriptor_irq_always;
1513         else
1514                 irq = descriptor_no_irq;
1515
1516         last = z == 2 ? d : d + z - 1;
1517         last->control |= cpu_to_le16(descriptor_output_last |
1518                                      descriptor_status |
1519                                      descriptor_branch_always |
1520                                      irq);
1521
1522         context_append(&ctx->context, d, z, header_z);
1523
1524         return 0;
1525 }
1526
1527 static int
1528 ohci_queue_iso_receive(struct fw_iso_context *base,
1529                        struct fw_iso_packet *packet,
1530                        struct fw_iso_buffer *buffer,
1531                        unsigned long payload)
1532 {
1533         struct iso_context *ctx = container_of(base, struct iso_context, base);
1534         struct db_descriptor *db = NULL;
1535         struct descriptor *d;
1536         struct fw_iso_packet *p;
1537         dma_addr_t d_bus, page_bus;
1538         u32 z, header_z, length, rest;
1539         int page, offset;
1540  
1541         /* FIXME: Cycle lost behavior should be configurable: lose
1542          * packet, retransmit or terminate.. */
1543
1544         p = packet;
1545         z = 2;
1546
1547         /* Get header size in number of descriptors. */
1548         header_z = DIV_ROUND_UP(p->header_length, sizeof *d);
1549         page     = payload >> PAGE_SHIFT;
1550         offset   = payload & ~PAGE_MASK;
1551         rest     = p->payload_length;
1552
1553         /* FIXME: OHCI 1.0 doesn't support dual buffer receive */
1554         /* FIXME: handle descriptor_wait */
1555         /* FIXME: make packet-per-buffer/dual-buffer a context option */
1556         while (rest > 0) {
1557                 d = context_get_descriptors(&ctx->context,
1558                                             z + header_z, &d_bus);
1559                 if (d == NULL)
1560                         return -ENOMEM;
1561
1562                 db = (struct db_descriptor *) d;
1563                 db->control = cpu_to_le16(descriptor_status |
1564                                           descriptor_branch_always);
1565                 db->first_size = cpu_to_le16(ctx->base.header_size);
1566                 db->first_req_count = cpu_to_le16(p->header_length);
1567                 db->second_req_count = cpu_to_le16(p->payload_length);
1568                 db->first_res_count = cpu_to_le16(db->first_req_count);
1569                 db->second_res_count = cpu_to_le16(db->second_req_count);
1570
1571                 db->first_buffer = cpu_to_le32(d_bus + sizeof *db);
1572                 
1573                 if (offset + rest < PAGE_SIZE)
1574                         length = rest;
1575                 else
1576                         length = PAGE_SIZE - offset;
1577
1578                 page_bus = page_private(buffer->pages[page]);
1579                 db->second_buffer = cpu_to_le32(page_bus + offset);
1580
1581                 context_append(&ctx->context, d, z, header_z);
1582                 offset = (offset + length) & ~PAGE_MASK;
1583                 rest -= length;
1584                 page++;
1585         }
1586
1587         if (p->interrupt)
1588                 db->control |= cpu_to_le16(descriptor_irq_always);
1589  
1590         return 0;
1591  }
1592  
1593 static int
1594 ohci_queue_iso(struct fw_iso_context *base,
1595                struct fw_iso_packet *packet,
1596                struct fw_iso_buffer *buffer,
1597                unsigned long payload)
1598 {
1599         if (base->type == FW_ISO_CONTEXT_TRANSMIT)
1600                 return ohci_queue_iso_transmit(base, packet, buffer, payload);
1601         else
1602                 return ohci_queue_iso_receive(base, packet, buffer, payload);
1603 }
1604
1605 static const struct fw_card_driver ohci_driver = {
1606         .name                   = ohci_driver_name,
1607         .enable                 = ohci_enable,
1608         .update_phy_reg         = ohci_update_phy_reg,
1609         .set_config_rom         = ohci_set_config_rom,
1610         .send_request           = ohci_send_request,
1611         .send_response          = ohci_send_response,
1612         .cancel_packet          = ohci_cancel_packet,
1613         .enable_phys_dma        = ohci_enable_phys_dma,
1614
1615         .allocate_iso_context   = ohci_allocate_iso_context,
1616         .free_iso_context       = ohci_free_iso_context,
1617         .queue_iso              = ohci_queue_iso,
1618         .start_iso              = ohci_start_iso,
1619         .stop_iso               = ohci_stop_iso,
1620 };
1621
1622 static int software_reset(struct fw_ohci *ohci)
1623 {
1624         int i;
1625
1626         reg_write(ohci, OHCI1394_HCControlSet, OHCI1394_HCControl_softReset);
1627
1628         for (i = 0; i < OHCI_LOOP_COUNT; i++) {
1629                 if ((reg_read(ohci, OHCI1394_HCControlSet) &
1630                      OHCI1394_HCControl_softReset) == 0)
1631                         return 0;
1632                 msleep(1);
1633         }
1634
1635         return -EBUSY;
1636 }
1637
1638 /* ---------- pci subsystem interface ---------- */
1639
1640 enum {
1641         CLEANUP_SELF_ID,
1642         CLEANUP_REGISTERS,
1643         CLEANUP_IOMEM,
1644         CLEANUP_DISABLE,
1645         CLEANUP_PUT_CARD,
1646 };
1647
1648 static int cleanup(struct fw_ohci *ohci, int stage, int code)
1649 {
1650         struct pci_dev *dev = to_pci_dev(ohci->card.device);
1651
1652         switch (stage) {
1653         case CLEANUP_SELF_ID:
1654                 dma_free_coherent(ohci->card.device, SELF_ID_BUF_SIZE,
1655                                   ohci->self_id_cpu, ohci->self_id_bus);
1656         case CLEANUP_REGISTERS:
1657                 kfree(ohci->it_context_list);
1658                 kfree(ohci->ir_context_list);
1659                 pci_iounmap(dev, ohci->registers);
1660         case CLEANUP_IOMEM:
1661                 pci_release_region(dev, 0);
1662         case CLEANUP_DISABLE:
1663                 pci_disable_device(dev);
1664         case CLEANUP_PUT_CARD:
1665                 fw_card_put(&ohci->card);
1666         }
1667
1668         return code;
1669 }
1670
1671 static int __devinit
1672 pci_probe(struct pci_dev *dev, const struct pci_device_id *ent)
1673 {
1674         struct fw_ohci *ohci;
1675         u32 bus_options, max_receive, link_speed;
1676         u64 guid;
1677         int error_code;
1678         size_t size;
1679
1680         ohci = kzalloc(sizeof *ohci, GFP_KERNEL);
1681         if (ohci == NULL) {
1682                 fw_error("Could not malloc fw_ohci data.\n");
1683                 return -ENOMEM;
1684         }
1685
1686         fw_card_initialize(&ohci->card, &ohci_driver, &dev->dev);
1687
1688         if (pci_enable_device(dev)) {
1689                 fw_error("Failed to enable OHCI hardware.\n");
1690                 return cleanup(ohci, CLEANUP_PUT_CARD, -ENODEV);
1691         }
1692
1693         pci_set_master(dev);
1694         pci_write_config_dword(dev, OHCI1394_PCI_HCI_Control, 0);
1695         pci_set_drvdata(dev, ohci);
1696
1697         spin_lock_init(&ohci->lock);
1698
1699         tasklet_init(&ohci->bus_reset_tasklet,
1700                      bus_reset_tasklet, (unsigned long)ohci);
1701
1702         if (pci_request_region(dev, 0, ohci_driver_name)) {
1703                 fw_error("MMIO resource unavailable\n");
1704                 return cleanup(ohci, CLEANUP_DISABLE, -EBUSY);
1705         }
1706
1707         ohci->registers = pci_iomap(dev, 0, OHCI1394_REGISTER_SIZE);
1708         if (ohci->registers == NULL) {
1709                 fw_error("Failed to remap registers\n");
1710                 return cleanup(ohci, CLEANUP_IOMEM, -ENXIO);
1711         }
1712
1713         if (software_reset(ohci)) {
1714                 fw_error("Failed to reset ohci card.\n");
1715                 return cleanup(ohci, CLEANUP_REGISTERS, -EBUSY);
1716         }
1717
1718         /* Now enable LPS, which we need in order to start accessing
1719          * most of the registers.  In fact, on some cards (ALI M5251),
1720          * accessing registers in the SClk domain without LPS enabled
1721          * will lock up the machine.  Wait 50msec to make sure we have
1722          * full link enabled.  */
1723         reg_write(ohci, OHCI1394_HCControlSet,
1724                   OHCI1394_HCControl_LPS |
1725                   OHCI1394_HCControl_postedWriteEnable);
1726         flush_writes(ohci);
1727         msleep(50);
1728
1729         reg_write(ohci, OHCI1394_HCControlClear,
1730                   OHCI1394_HCControl_noByteSwapData);
1731
1732         reg_write(ohci, OHCI1394_LinkControlSet,
1733                   OHCI1394_LinkControl_rcvSelfID |
1734                   OHCI1394_LinkControl_cycleTimerEnable |
1735                   OHCI1394_LinkControl_cycleMaster);
1736
1737         ar_context_init(&ohci->ar_request_ctx, ohci,
1738                         OHCI1394_AsReqRcvContextControlSet);
1739
1740         ar_context_init(&ohci->ar_response_ctx, ohci,
1741                         OHCI1394_AsRspRcvContextControlSet);
1742
1743         at_context_init(&ohci->at_request_ctx, ohci,
1744                         OHCI1394_AsReqTrContextControlSet);
1745
1746         at_context_init(&ohci->at_response_ctx, ohci,
1747                         OHCI1394_AsRspTrContextControlSet);
1748
1749         reg_write(ohci, OHCI1394_ATRetries,
1750                   OHCI1394_MAX_AT_REQ_RETRIES |
1751                   (OHCI1394_MAX_AT_RESP_RETRIES << 4) |
1752                   (OHCI1394_MAX_PHYS_RESP_RETRIES << 8));
1753
1754         reg_write(ohci, OHCI1394_IsoRecvIntMaskSet, ~0);
1755         ohci->it_context_mask = reg_read(ohci, OHCI1394_IsoRecvIntMaskSet);
1756         reg_write(ohci, OHCI1394_IsoRecvIntMaskClear, ~0);
1757         size = sizeof(struct iso_context) * hweight32(ohci->it_context_mask);
1758         ohci->it_context_list = kzalloc(size, GFP_KERNEL);
1759
1760         reg_write(ohci, OHCI1394_IsoXmitIntMaskSet, ~0);
1761         ohci->ir_context_mask = reg_read(ohci, OHCI1394_IsoXmitIntMaskSet);
1762         reg_write(ohci, OHCI1394_IsoXmitIntMaskClear, ~0);
1763         size = sizeof(struct iso_context) * hweight32(ohci->ir_context_mask);
1764         ohci->ir_context_list = kzalloc(size, GFP_KERNEL);
1765
1766         if (ohci->it_context_list == NULL || ohci->ir_context_list == NULL) {
1767                 fw_error("Out of memory for it/ir contexts.\n");
1768                 return cleanup(ohci, CLEANUP_REGISTERS, -ENOMEM);
1769         }
1770
1771         /* self-id dma buffer allocation */
1772         ohci->self_id_cpu = dma_alloc_coherent(ohci->card.device,
1773                                                SELF_ID_BUF_SIZE,
1774                                                &ohci->self_id_bus,
1775                                                GFP_KERNEL);
1776         if (ohci->self_id_cpu == NULL) {
1777                 fw_error("Out of memory for self ID buffer.\n");
1778                 return cleanup(ohci, CLEANUP_REGISTERS, -ENOMEM);
1779         }
1780
1781         reg_write(ohci, OHCI1394_SelfIDBuffer, ohci->self_id_bus);
1782         reg_write(ohci, OHCI1394_PhyUpperBound, 0x00010000);
1783         reg_write(ohci, OHCI1394_IntEventClear, ~0);
1784         reg_write(ohci, OHCI1394_IntMaskClear, ~0);
1785         reg_write(ohci, OHCI1394_IntMaskSet,
1786                   OHCI1394_selfIDComplete |
1787                   OHCI1394_RQPkt | OHCI1394_RSPkt |
1788                   OHCI1394_reqTxComplete | OHCI1394_respTxComplete |
1789                   OHCI1394_isochRx | OHCI1394_isochTx |
1790                   OHCI1394_masterIntEnable);
1791
1792         bus_options = reg_read(ohci, OHCI1394_BusOptions);
1793         max_receive = (bus_options >> 12) & 0xf;
1794         link_speed = bus_options & 0x7;
1795         guid = ((u64) reg_read(ohci, OHCI1394_GUIDHi) << 32) |
1796                 reg_read(ohci, OHCI1394_GUIDLo);
1797
1798         error_code = fw_card_add(&ohci->card, max_receive, link_speed, guid);
1799         if (error_code < 0)
1800                 return cleanup(ohci, CLEANUP_SELF_ID, error_code);
1801
1802         fw_notify("Added fw-ohci device %s.\n", dev->dev.bus_id);
1803
1804         return 0;
1805 }
1806
1807 static void pci_remove(struct pci_dev *dev)
1808 {
1809         struct fw_ohci *ohci;
1810
1811         ohci = pci_get_drvdata(dev);
1812         reg_write(ohci, OHCI1394_IntMaskClear, OHCI1394_masterIntEnable);
1813         fw_core_remove_card(&ohci->card);
1814
1815         /* FIXME: Fail all pending packets here, now that the upper
1816          * layers can't queue any more. */
1817
1818         software_reset(ohci);
1819         free_irq(dev->irq, ohci);
1820         cleanup(ohci, CLEANUP_SELF_ID, 0);
1821
1822         fw_notify("Removed fw-ohci device.\n");
1823 }
1824
1825 static struct pci_device_id pci_table[] = {
1826         { PCI_DEVICE_CLASS(PCI_CLASS_SERIAL_FIREWIRE_OHCI, ~0) },
1827         { }
1828 };
1829
1830 MODULE_DEVICE_TABLE(pci, pci_table);
1831
1832 static struct pci_driver fw_ohci_pci_driver = {
1833         .name           = ohci_driver_name,
1834         .id_table       = pci_table,
1835         .probe          = pci_probe,
1836         .remove         = pci_remove,
1837 };
1838
1839 MODULE_AUTHOR("Kristian Hoegsberg <krh@bitplanet.net>");
1840 MODULE_DESCRIPTION("Driver for PCI OHCI IEEE1394 controllers");
1841 MODULE_LICENSE("GPL");
1842
1843 static int __init fw_ohci_init(void)
1844 {
1845         return pci_register_driver(&fw_ohci_pci_driver);
1846 }
1847
1848 static void __exit fw_ohci_cleanup(void)
1849 {
1850         pci_unregister_driver(&fw_ohci_pci_driver);
1851 }
1852
1853 module_init(fw_ohci_init);
1854 module_exit(fw_ohci_cleanup);