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