Merge branch 'for-2.6.25' of git://git.kernel.org/pub/scm/linux/kernel/git/paulus...
[sfrench/cifs-2.6.git] / drivers / firewire / fw-ohci.c
1 /*
2  * Driver for OHCI 1394 controllers
3  *
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/compiler.h>
22 #include <linux/delay.h>
23 #include <linux/dma-mapping.h>
24 #include <linux/gfp.h>
25 #include <linux/init.h>
26 #include <linux/interrupt.h>
27 #include <linux/kernel.h>
28 #include <linux/mm.h>
29 #include <linux/module.h>
30 #include <linux/pci.h>
31 #include <linux/spinlock.h>
32
33 #include <asm/page.h>
34 #include <asm/system.h>
35
36 #include "fw-ohci.h"
37 #include "fw-transaction.h"
38
39 #define DESCRIPTOR_OUTPUT_MORE          0
40 #define DESCRIPTOR_OUTPUT_LAST          (1 << 12)
41 #define DESCRIPTOR_INPUT_MORE           (2 << 12)
42 #define DESCRIPTOR_INPUT_LAST           (3 << 12)
43 #define DESCRIPTOR_STATUS               (1 << 11)
44 #define DESCRIPTOR_KEY_IMMEDIATE        (2 << 8)
45 #define DESCRIPTOR_PING                 (1 << 7)
46 #define DESCRIPTOR_YY                   (1 << 6)
47 #define DESCRIPTOR_NO_IRQ               (0 << 4)
48 #define DESCRIPTOR_IRQ_ERROR            (1 << 4)
49 #define DESCRIPTOR_IRQ_ALWAYS           (3 << 4)
50 #define DESCRIPTOR_BRANCH_ALWAYS        (3 << 2)
51 #define DESCRIPTOR_WAIT                 (3 << 0)
52
53 struct descriptor {
54         __le16 req_count;
55         __le16 control;
56         __le32 data_address;
57         __le32 branch_address;
58         __le16 res_count;
59         __le16 transfer_status;
60 } __attribute__((aligned(16)));
61
62 struct db_descriptor {
63         __le16 first_size;
64         __le16 control;
65         __le16 second_req_count;
66         __le16 first_req_count;
67         __le32 branch_address;
68         __le16 second_res_count;
69         __le16 first_res_count;
70         __le32 reserved0;
71         __le32 first_buffer;
72         __le32 second_buffer;
73         __le32 reserved1;
74 } __attribute__((aligned(16)));
75
76 #define CONTROL_SET(regs)       (regs)
77 #define CONTROL_CLEAR(regs)     ((regs) + 4)
78 #define COMMAND_PTR(regs)       ((regs) + 12)
79 #define CONTEXT_MATCH(regs)     ((regs) + 16)
80
81 struct ar_buffer {
82         struct descriptor descriptor;
83         struct ar_buffer *next;
84         __le32 data[0];
85 };
86
87 struct ar_context {
88         struct fw_ohci *ohci;
89         struct ar_buffer *current_buffer;
90         struct ar_buffer *last_buffer;
91         void *pointer;
92         u32 regs;
93         struct tasklet_struct tasklet;
94 };
95
96 struct context;
97
98 typedef int (*descriptor_callback_t)(struct context *ctx,
99                                      struct descriptor *d,
100                                      struct descriptor *last);
101
102 /*
103  * A buffer that contains a block of DMA-able coherent memory used for
104  * storing a portion of a DMA descriptor program.
105  */
106 struct descriptor_buffer {
107         struct list_head list;
108         dma_addr_t buffer_bus;
109         size_t buffer_size;
110         size_t used;
111         struct descriptor buffer[0];
112 };
113
114 struct context {
115         struct fw_ohci *ohci;
116         u32 regs;
117         int total_allocation;
118
119         /*
120          * List of page-sized buffers for storing DMA descriptors.
121          * Head of list contains buffers in use and tail of list contains
122          * free buffers.
123          */
124         struct list_head buffer_list;
125
126         /*
127          * Pointer to a buffer inside buffer_list that contains the tail
128          * end of the current DMA program.
129          */
130         struct descriptor_buffer *buffer_tail;
131
132         /*
133          * The descriptor containing the branch address of the first
134          * descriptor that has not yet been filled by the device.
135          */
136         struct descriptor *last;
137
138         /*
139          * The last descriptor in the DMA program.  It contains the branch
140          * address that must be updated upon appending a new descriptor.
141          */
142         struct descriptor *prev;
143
144         descriptor_callback_t callback;
145
146         struct tasklet_struct tasklet;
147 };
148
149 #define IT_HEADER_SY(v)          ((v) <<  0)
150 #define IT_HEADER_TCODE(v)       ((v) <<  4)
151 #define IT_HEADER_CHANNEL(v)     ((v) <<  8)
152 #define IT_HEADER_TAG(v)         ((v) << 14)
153 #define IT_HEADER_SPEED(v)       ((v) << 16)
154 #define IT_HEADER_DATA_LENGTH(v) ((v) << 16)
155
156 struct iso_context {
157         struct fw_iso_context base;
158         struct context context;
159         int excess_bytes;
160         void *header;
161         size_t header_length;
162 };
163
164 #define CONFIG_ROM_SIZE 1024
165
166 struct fw_ohci {
167         struct fw_card card;
168
169         u32 version;
170         __iomem char *registers;
171         dma_addr_t self_id_bus;
172         __le32 *self_id_cpu;
173         struct tasklet_struct bus_reset_tasklet;
174         int node_id;
175         int generation;
176         int request_generation;
177         u32 bus_seconds;
178
179         /*
180          * Spinlock for accessing fw_ohci data.  Never call out of
181          * this driver with this lock held.
182          */
183         spinlock_t lock;
184         u32 self_id_buffer[512];
185
186         /* Config rom buffers */
187         __be32 *config_rom;
188         dma_addr_t config_rom_bus;
189         __be32 *next_config_rom;
190         dma_addr_t next_config_rom_bus;
191         u32 next_header;
192
193         struct ar_context ar_request_ctx;
194         struct ar_context ar_response_ctx;
195         struct context at_request_ctx;
196         struct context at_response_ctx;
197
198         u32 it_context_mask;
199         struct iso_context *it_context_list;
200         u32 ir_context_mask;
201         struct iso_context *ir_context_list;
202 };
203
204 static inline struct fw_ohci *fw_ohci(struct fw_card *card)
205 {
206         return container_of(card, struct fw_ohci, card);
207 }
208
209 #define IT_CONTEXT_CYCLE_MATCH_ENABLE   0x80000000
210 #define IR_CONTEXT_BUFFER_FILL          0x80000000
211 #define IR_CONTEXT_ISOCH_HEADER         0x40000000
212 #define IR_CONTEXT_CYCLE_MATCH_ENABLE   0x20000000
213 #define IR_CONTEXT_MULTI_CHANNEL_MODE   0x10000000
214 #define IR_CONTEXT_DUAL_BUFFER_MODE     0x08000000
215
216 #define CONTEXT_RUN     0x8000
217 #define CONTEXT_WAKE    0x1000
218 #define CONTEXT_DEAD    0x0800
219 #define CONTEXT_ACTIVE  0x0400
220
221 #define OHCI1394_MAX_AT_REQ_RETRIES     0x2
222 #define OHCI1394_MAX_AT_RESP_RETRIES    0x2
223 #define OHCI1394_MAX_PHYS_RESP_RETRIES  0x8
224
225 #define FW_OHCI_MAJOR                   240
226 #define OHCI1394_REGISTER_SIZE          0x800
227 #define OHCI_LOOP_COUNT                 500
228 #define OHCI1394_PCI_HCI_Control        0x40
229 #define SELF_ID_BUF_SIZE                0x800
230 #define OHCI_TCODE_PHY_PACKET           0x0e
231 #define OHCI_VERSION_1_1                0x010010
232
233 static char ohci_driver_name[] = KBUILD_MODNAME;
234
235 static inline void reg_write(const struct fw_ohci *ohci, int offset, u32 data)
236 {
237         writel(data, ohci->registers + offset);
238 }
239
240 static inline u32 reg_read(const struct fw_ohci *ohci, int offset)
241 {
242         return readl(ohci->registers + offset);
243 }
244
245 static inline void flush_writes(const struct fw_ohci *ohci)
246 {
247         /* Do a dummy read to flush writes. */
248         reg_read(ohci, OHCI1394_Version);
249 }
250
251 static int
252 ohci_update_phy_reg(struct fw_card *card, int addr,
253                     int clear_bits, int set_bits)
254 {
255         struct fw_ohci *ohci = fw_ohci(card);
256         u32 val, old;
257
258         reg_write(ohci, OHCI1394_PhyControl, OHCI1394_PhyControl_Read(addr));
259         flush_writes(ohci);
260         msleep(2);
261         val = reg_read(ohci, OHCI1394_PhyControl);
262         if ((val & OHCI1394_PhyControl_ReadDone) == 0) {
263                 fw_error("failed to set phy reg bits.\n");
264                 return -EBUSY;
265         }
266
267         old = OHCI1394_PhyControl_ReadData(val);
268         old = (old & ~clear_bits) | set_bits;
269         reg_write(ohci, OHCI1394_PhyControl,
270                   OHCI1394_PhyControl_Write(addr, old));
271
272         return 0;
273 }
274
275 static int ar_context_add_page(struct ar_context *ctx)
276 {
277         struct device *dev = ctx->ohci->card.device;
278         struct ar_buffer *ab;
279         dma_addr_t ab_bus;
280         size_t offset;
281
282         ab = (struct ar_buffer *) __get_free_page(GFP_ATOMIC);
283         if (ab == NULL)
284                 return -ENOMEM;
285
286         ab_bus = dma_map_single(dev, ab, PAGE_SIZE, DMA_BIDIRECTIONAL);
287         if (dma_mapping_error(ab_bus)) {
288                 free_page((unsigned long) ab);
289                 return -ENOMEM;
290         }
291
292         memset(&ab->descriptor, 0, sizeof(ab->descriptor));
293         ab->descriptor.control        = cpu_to_le16(DESCRIPTOR_INPUT_MORE |
294                                                     DESCRIPTOR_STATUS |
295                                                     DESCRIPTOR_BRANCH_ALWAYS);
296         offset = offsetof(struct ar_buffer, data);
297         ab->descriptor.req_count      = cpu_to_le16(PAGE_SIZE - offset);
298         ab->descriptor.data_address   = cpu_to_le32(ab_bus + offset);
299         ab->descriptor.res_count      = cpu_to_le16(PAGE_SIZE - offset);
300         ab->descriptor.branch_address = 0;
301
302         dma_sync_single_for_device(dev, ab_bus, PAGE_SIZE, DMA_BIDIRECTIONAL);
303
304         ctx->last_buffer->descriptor.branch_address = cpu_to_le32(ab_bus | 1);
305         ctx->last_buffer->next = ab;
306         ctx->last_buffer = ab;
307
308         reg_write(ctx->ohci, CONTROL_SET(ctx->regs), CONTEXT_WAKE);
309         flush_writes(ctx->ohci);
310
311         return 0;
312 }
313
314 static __le32 *handle_ar_packet(struct ar_context *ctx, __le32 *buffer)
315 {
316         struct fw_ohci *ohci = ctx->ohci;
317         struct fw_packet p;
318         u32 status, length, tcode;
319
320         p.header[0] = le32_to_cpu(buffer[0]);
321         p.header[1] = le32_to_cpu(buffer[1]);
322         p.header[2] = le32_to_cpu(buffer[2]);
323
324         tcode = (p.header[0] >> 4) & 0x0f;
325         switch (tcode) {
326         case TCODE_WRITE_QUADLET_REQUEST:
327         case TCODE_READ_QUADLET_RESPONSE:
328                 p.header[3] = (__force __u32) buffer[3];
329                 p.header_length = 16;
330                 p.payload_length = 0;
331                 break;
332
333         case TCODE_READ_BLOCK_REQUEST :
334                 p.header[3] = le32_to_cpu(buffer[3]);
335                 p.header_length = 16;
336                 p.payload_length = 0;
337                 break;
338
339         case TCODE_WRITE_BLOCK_REQUEST:
340         case TCODE_READ_BLOCK_RESPONSE:
341         case TCODE_LOCK_REQUEST:
342         case TCODE_LOCK_RESPONSE:
343                 p.header[3] = le32_to_cpu(buffer[3]);
344                 p.header_length = 16;
345                 p.payload_length = p.header[3] >> 16;
346                 break;
347
348         case TCODE_WRITE_RESPONSE:
349         case TCODE_READ_QUADLET_REQUEST:
350         case OHCI_TCODE_PHY_PACKET:
351                 p.header_length = 12;
352                 p.payload_length = 0;
353                 break;
354         }
355
356         p.payload = (void *) buffer + p.header_length;
357
358         /* FIXME: What to do about evt_* errors? */
359         length = (p.header_length + p.payload_length + 3) / 4;
360         status = le32_to_cpu(buffer[length]);
361
362         p.ack        = ((status >> 16) & 0x1f) - 16;
363         p.speed      = (status >> 21) & 0x7;
364         p.timestamp  = status & 0xffff;
365         p.generation = ohci->request_generation;
366
367         /*
368          * The OHCI bus reset handler synthesizes a phy packet with
369          * the new generation number when a bus reset happens (see
370          * section 8.4.2.3).  This helps us determine when a request
371          * was received and make sure we send the response in the same
372          * generation.  We only need this for requests; for responses
373          * we use the unique tlabel for finding the matching
374          * request.
375          */
376
377         if (p.ack + 16 == 0x09)
378                 ohci->request_generation = (buffer[2] >> 16) & 0xff;
379         else if (ctx == &ohci->ar_request_ctx)
380                 fw_core_handle_request(&ohci->card, &p);
381         else
382                 fw_core_handle_response(&ohci->card, &p);
383
384         return buffer + length + 1;
385 }
386
387 static void ar_context_tasklet(unsigned long data)
388 {
389         struct ar_context *ctx = (struct ar_context *)data;
390         struct fw_ohci *ohci = ctx->ohci;
391         struct ar_buffer *ab;
392         struct descriptor *d;
393         void *buffer, *end;
394
395         ab = ctx->current_buffer;
396         d = &ab->descriptor;
397
398         if (d->res_count == 0) {
399                 size_t size, rest, offset;
400
401                 /*
402                  * This descriptor is finished and we may have a
403                  * packet split across this and the next buffer. We
404                  * reuse the page for reassembling the split packet.
405                  */
406
407                 offset = offsetof(struct ar_buffer, data);
408                 dma_unmap_single(ohci->card.device,
409                         le32_to_cpu(ab->descriptor.data_address) - offset,
410                         PAGE_SIZE, DMA_BIDIRECTIONAL);
411
412                 buffer = ab;
413                 ab = ab->next;
414                 d = &ab->descriptor;
415                 size = buffer + PAGE_SIZE - ctx->pointer;
416                 rest = le16_to_cpu(d->req_count) - le16_to_cpu(d->res_count);
417                 memmove(buffer, ctx->pointer, size);
418                 memcpy(buffer + size, ab->data, rest);
419                 ctx->current_buffer = ab;
420                 ctx->pointer = (void *) ab->data + rest;
421                 end = buffer + size + rest;
422
423                 while (buffer < end)
424                         buffer = handle_ar_packet(ctx, buffer);
425
426                 free_page((unsigned long)buffer);
427                 ar_context_add_page(ctx);
428         } else {
429                 buffer = ctx->pointer;
430                 ctx->pointer = end =
431                         (void *) ab + PAGE_SIZE - le16_to_cpu(d->res_count);
432
433                 while (buffer < end)
434                         buffer = handle_ar_packet(ctx, buffer);
435         }
436 }
437
438 static int
439 ar_context_init(struct ar_context *ctx, struct fw_ohci *ohci, u32 regs)
440 {
441         struct ar_buffer ab;
442
443         ctx->regs        = regs;
444         ctx->ohci        = ohci;
445         ctx->last_buffer = &ab;
446         tasklet_init(&ctx->tasklet, ar_context_tasklet, (unsigned long)ctx);
447
448         ar_context_add_page(ctx);
449         ar_context_add_page(ctx);
450         ctx->current_buffer = ab.next;
451         ctx->pointer = ctx->current_buffer->data;
452
453         return 0;
454 }
455
456 static void ar_context_run(struct ar_context *ctx)
457 {
458         struct ar_buffer *ab = ctx->current_buffer;
459         dma_addr_t ab_bus;
460         size_t offset;
461
462         offset = offsetof(struct ar_buffer, data);
463         ab_bus = le32_to_cpu(ab->descriptor.data_address) - offset;
464
465         reg_write(ctx->ohci, COMMAND_PTR(ctx->regs), ab_bus | 1);
466         reg_write(ctx->ohci, CONTROL_SET(ctx->regs), CONTEXT_RUN);
467         flush_writes(ctx->ohci);
468 }
469
470 static struct descriptor *
471 find_branch_descriptor(struct descriptor *d, int z)
472 {
473         int b, key;
474
475         b   = (le16_to_cpu(d->control) & DESCRIPTOR_BRANCH_ALWAYS) >> 2;
476         key = (le16_to_cpu(d->control) & DESCRIPTOR_KEY_IMMEDIATE) >> 8;
477
478         /* figure out which descriptor the branch address goes in */
479         if (z == 2 && (b == 3 || key == 2))
480                 return d;
481         else
482                 return d + z - 1;
483 }
484
485 static void context_tasklet(unsigned long data)
486 {
487         struct context *ctx = (struct context *) data;
488         struct descriptor *d, *last;
489         u32 address;
490         int z;
491         struct descriptor_buffer *desc;
492
493         desc = list_entry(ctx->buffer_list.next,
494                         struct descriptor_buffer, list);
495         last = ctx->last;
496         while (last->branch_address != 0) {
497                 struct descriptor_buffer *old_desc = desc;
498                 address = le32_to_cpu(last->branch_address);
499                 z = address & 0xf;
500                 address &= ~0xf;
501
502                 /* If the branch address points to a buffer outside of the
503                  * current buffer, advance to the next buffer. */
504                 if (address < desc->buffer_bus ||
505                                 address >= desc->buffer_bus + desc->used)
506                         desc = list_entry(desc->list.next,
507                                         struct descriptor_buffer, list);
508                 d = desc->buffer + (address - desc->buffer_bus) / sizeof(*d);
509                 last = find_branch_descriptor(d, z);
510
511                 if (!ctx->callback(ctx, d, last))
512                         break;
513
514                 if (old_desc != desc) {
515                         /* If we've advanced to the next buffer, move the
516                          * previous buffer to the free list. */
517                         unsigned long flags;
518                         old_desc->used = 0;
519                         spin_lock_irqsave(&ctx->ohci->lock, flags);
520                         list_move_tail(&old_desc->list, &ctx->buffer_list);
521                         spin_unlock_irqrestore(&ctx->ohci->lock, flags);
522                 }
523                 ctx->last = last;
524         }
525 }
526
527 /*
528  * Allocate a new buffer and add it to the list of free buffers for this
529  * context.  Must be called with ohci->lock held.
530  */
531 static int
532 context_add_buffer(struct context *ctx)
533 {
534         struct descriptor_buffer *desc;
535         dma_addr_t bus_addr;
536         int offset;
537
538         /*
539          * 16MB of descriptors should be far more than enough for any DMA
540          * program.  This will catch run-away userspace or DoS attacks.
541          */
542         if (ctx->total_allocation >= 16*1024*1024)
543                 return -ENOMEM;
544
545         desc = dma_alloc_coherent(ctx->ohci->card.device, PAGE_SIZE,
546                         &bus_addr, GFP_ATOMIC);
547         if (!desc)
548                 return -ENOMEM;
549
550         offset = (void *)&desc->buffer - (void *)desc;
551         desc->buffer_size = PAGE_SIZE - offset;
552         desc->buffer_bus = bus_addr + offset;
553         desc->used = 0;
554
555         list_add_tail(&desc->list, &ctx->buffer_list);
556         ctx->total_allocation += PAGE_SIZE;
557
558         return 0;
559 }
560
561 static int
562 context_init(struct context *ctx, struct fw_ohci *ohci,
563              u32 regs, descriptor_callback_t callback)
564 {
565         ctx->ohci = ohci;
566         ctx->regs = regs;
567         ctx->total_allocation = 0;
568
569         INIT_LIST_HEAD(&ctx->buffer_list);
570         if (context_add_buffer(ctx) < 0)
571                 return -ENOMEM;
572
573         ctx->buffer_tail = list_entry(ctx->buffer_list.next,
574                         struct descriptor_buffer, list);
575
576         tasklet_init(&ctx->tasklet, context_tasklet, (unsigned long)ctx);
577         ctx->callback = callback;
578
579         /*
580          * We put a dummy descriptor in the buffer that has a NULL
581          * branch address and looks like it's been sent.  That way we
582          * have a descriptor to append DMA programs to.
583          */
584         memset(ctx->buffer_tail->buffer, 0, sizeof(*ctx->buffer_tail->buffer));
585         ctx->buffer_tail->buffer->control = cpu_to_le16(DESCRIPTOR_OUTPUT_LAST);
586         ctx->buffer_tail->buffer->transfer_status = cpu_to_le16(0x8011);
587         ctx->buffer_tail->used += sizeof(*ctx->buffer_tail->buffer);
588         ctx->last = ctx->buffer_tail->buffer;
589         ctx->prev = ctx->buffer_tail->buffer;
590
591         return 0;
592 }
593
594 static void
595 context_release(struct context *ctx)
596 {
597         struct fw_card *card = &ctx->ohci->card;
598         struct descriptor_buffer *desc, *tmp;
599
600         list_for_each_entry_safe(desc, tmp, &ctx->buffer_list, list)
601                 dma_free_coherent(card->device, PAGE_SIZE, desc,
602                         desc->buffer_bus -
603                         ((void *)&desc->buffer - (void *)desc));
604 }
605
606 /* Must be called with ohci->lock held */
607 static struct descriptor *
608 context_get_descriptors(struct context *ctx, int z, dma_addr_t *d_bus)
609 {
610         struct descriptor *d = NULL;
611         struct descriptor_buffer *desc = ctx->buffer_tail;
612
613         if (z * sizeof(*d) > desc->buffer_size)
614                 return NULL;
615
616         if (z * sizeof(*d) > desc->buffer_size - desc->used) {
617                 /* No room for the descriptor in this buffer, so advance to the
618                  * next one. */
619
620                 if (desc->list.next == &ctx->buffer_list) {
621                         /* If there is no free buffer next in the list,
622                          * allocate one. */
623                         if (context_add_buffer(ctx) < 0)
624                                 return NULL;
625                 }
626                 desc = list_entry(desc->list.next,
627                                 struct descriptor_buffer, list);
628                 ctx->buffer_tail = desc;
629         }
630
631         d = desc->buffer + desc->used / sizeof(*d);
632         memset(d, 0, z * sizeof(*d));
633         *d_bus = desc->buffer_bus + desc->used;
634
635         return d;
636 }
637
638 static void context_run(struct context *ctx, u32 extra)
639 {
640         struct fw_ohci *ohci = ctx->ohci;
641
642         reg_write(ohci, COMMAND_PTR(ctx->regs),
643                   le32_to_cpu(ctx->last->branch_address));
644         reg_write(ohci, CONTROL_CLEAR(ctx->regs), ~0);
645         reg_write(ohci, CONTROL_SET(ctx->regs), CONTEXT_RUN | extra);
646         flush_writes(ohci);
647 }
648
649 static void context_append(struct context *ctx,
650                            struct descriptor *d, int z, int extra)
651 {
652         dma_addr_t d_bus;
653         struct descriptor_buffer *desc = ctx->buffer_tail;
654
655         d_bus = desc->buffer_bus + (d - desc->buffer) * sizeof(*d);
656
657         desc->used += (z + extra) * sizeof(*d);
658         ctx->prev->branch_address = cpu_to_le32(d_bus | z);
659         ctx->prev = find_branch_descriptor(d, z);
660
661         reg_write(ctx->ohci, CONTROL_SET(ctx->regs), CONTEXT_WAKE);
662         flush_writes(ctx->ohci);
663 }
664
665 static void context_stop(struct context *ctx)
666 {
667         u32 reg;
668         int i;
669
670         reg_write(ctx->ohci, CONTROL_CLEAR(ctx->regs), CONTEXT_RUN);
671         flush_writes(ctx->ohci);
672
673         for (i = 0; i < 10; i++) {
674                 reg = reg_read(ctx->ohci, CONTROL_SET(ctx->regs));
675                 if ((reg & CONTEXT_ACTIVE) == 0)
676                         break;
677
678                 fw_notify("context_stop: still active (0x%08x)\n", reg);
679                 mdelay(1);
680         }
681 }
682
683 struct driver_data {
684         struct fw_packet *packet;
685 };
686
687 /*
688  * This function apppends a packet to the DMA queue for transmission.
689  * Must always be called with the ochi->lock held to ensure proper
690  * generation handling and locking around packet queue manipulation.
691  */
692 static int
693 at_context_queue_packet(struct context *ctx, struct fw_packet *packet)
694 {
695         struct fw_ohci *ohci = ctx->ohci;
696         dma_addr_t d_bus, uninitialized_var(payload_bus);
697         struct driver_data *driver_data;
698         struct descriptor *d, *last;
699         __le32 *header;
700         int z, tcode;
701         u32 reg;
702
703         d = context_get_descriptors(ctx, 4, &d_bus);
704         if (d == NULL) {
705                 packet->ack = RCODE_SEND_ERROR;
706                 return -1;
707         }
708
709         d[0].control   = cpu_to_le16(DESCRIPTOR_KEY_IMMEDIATE);
710         d[0].res_count = cpu_to_le16(packet->timestamp);
711
712         /*
713          * The DMA format for asyncronous link packets is different
714          * from the IEEE1394 layout, so shift the fields around
715          * accordingly.  If header_length is 8, it's a PHY packet, to
716          * which we need to prepend an extra quadlet.
717          */
718
719         header = (__le32 *) &d[1];
720         if (packet->header_length > 8) {
721                 header[0] = cpu_to_le32((packet->header[0] & 0xffff) |
722                                         (packet->speed << 16));
723                 header[1] = cpu_to_le32((packet->header[1] & 0xffff) |
724                                         (packet->header[0] & 0xffff0000));
725                 header[2] = cpu_to_le32(packet->header[2]);
726
727                 tcode = (packet->header[0] >> 4) & 0x0f;
728                 if (TCODE_IS_BLOCK_PACKET(tcode))
729                         header[3] = cpu_to_le32(packet->header[3]);
730                 else
731                         header[3] = (__force __le32) packet->header[3];
732
733                 d[0].req_count = cpu_to_le16(packet->header_length);
734         } else {
735                 header[0] = cpu_to_le32((OHCI1394_phy_tcode << 4) |
736                                         (packet->speed << 16));
737                 header[1] = cpu_to_le32(packet->header[0]);
738                 header[2] = cpu_to_le32(packet->header[1]);
739                 d[0].req_count = cpu_to_le16(12);
740         }
741
742         driver_data = (struct driver_data *) &d[3];
743         driver_data->packet = packet;
744         packet->driver_data = driver_data;
745
746         if (packet->payload_length > 0) {
747                 payload_bus =
748                         dma_map_single(ohci->card.device, packet->payload,
749                                        packet->payload_length, DMA_TO_DEVICE);
750                 if (dma_mapping_error(payload_bus)) {
751                         packet->ack = RCODE_SEND_ERROR;
752                         return -1;
753                 }
754
755                 d[2].req_count    = cpu_to_le16(packet->payload_length);
756                 d[2].data_address = cpu_to_le32(payload_bus);
757                 last = &d[2];
758                 z = 3;
759         } else {
760                 last = &d[0];
761                 z = 2;
762         }
763
764         last->control |= cpu_to_le16(DESCRIPTOR_OUTPUT_LAST |
765                                      DESCRIPTOR_IRQ_ALWAYS |
766                                      DESCRIPTOR_BRANCH_ALWAYS);
767
768         /* FIXME: Document how the locking works. */
769         if (ohci->generation != packet->generation) {
770                 if (packet->payload_length > 0)
771                         dma_unmap_single(ohci->card.device, payload_bus,
772                                          packet->payload_length, DMA_TO_DEVICE);
773                 packet->ack = RCODE_GENERATION;
774                 return -1;
775         }
776
777         context_append(ctx, d, z, 4 - z);
778
779         /* If the context isn't already running, start it up. */
780         reg = reg_read(ctx->ohci, CONTROL_SET(ctx->regs));
781         if ((reg & CONTEXT_RUN) == 0)
782                 context_run(ctx, 0);
783
784         return 0;
785 }
786
787 static int handle_at_packet(struct context *context,
788                             struct descriptor *d,
789                             struct descriptor *last)
790 {
791         struct driver_data *driver_data;
792         struct fw_packet *packet;
793         struct fw_ohci *ohci = context->ohci;
794         dma_addr_t payload_bus;
795         int evt;
796
797         if (last->transfer_status == 0)
798                 /* This descriptor isn't done yet, stop iteration. */
799                 return 0;
800
801         driver_data = (struct driver_data *) &d[3];
802         packet = driver_data->packet;
803         if (packet == NULL)
804                 /* This packet was cancelled, just continue. */
805                 return 1;
806
807         payload_bus = le32_to_cpu(last->data_address);
808         if (payload_bus != 0)
809                 dma_unmap_single(ohci->card.device, payload_bus,
810                                  packet->payload_length, DMA_TO_DEVICE);
811
812         evt = le16_to_cpu(last->transfer_status) & 0x1f;
813         packet->timestamp = le16_to_cpu(last->res_count);
814
815         switch (evt) {
816         case OHCI1394_evt_timeout:
817                 /* Async response transmit timed out. */
818                 packet->ack = RCODE_CANCELLED;
819                 break;
820
821         case OHCI1394_evt_flushed:
822                 /*
823                  * The packet was flushed should give same error as
824                  * when we try to use a stale generation count.
825                  */
826                 packet->ack = RCODE_GENERATION;
827                 break;
828
829         case OHCI1394_evt_missing_ack:
830                 /*
831                  * Using a valid (current) generation count, but the
832                  * node is not on the bus or not sending acks.
833                  */
834                 packet->ack = RCODE_NO_ACK;
835                 break;
836
837         case ACK_COMPLETE + 0x10:
838         case ACK_PENDING + 0x10:
839         case ACK_BUSY_X + 0x10:
840         case ACK_BUSY_A + 0x10:
841         case ACK_BUSY_B + 0x10:
842         case ACK_DATA_ERROR + 0x10:
843         case ACK_TYPE_ERROR + 0x10:
844                 packet->ack = evt - 0x10;
845                 break;
846
847         default:
848                 packet->ack = RCODE_SEND_ERROR;
849                 break;
850         }
851
852         packet->callback(packet, &ohci->card, packet->ack);
853
854         return 1;
855 }
856
857 #define HEADER_GET_DESTINATION(q)       (((q) >> 16) & 0xffff)
858 #define HEADER_GET_TCODE(q)             (((q) >> 4) & 0x0f)
859 #define HEADER_GET_OFFSET_HIGH(q)       (((q) >> 0) & 0xffff)
860 #define HEADER_GET_DATA_LENGTH(q)       (((q) >> 16) & 0xffff)
861 #define HEADER_GET_EXTENDED_TCODE(q)    (((q) >> 0) & 0xffff)
862
863 static void
864 handle_local_rom(struct fw_ohci *ohci, struct fw_packet *packet, u32 csr)
865 {
866         struct fw_packet response;
867         int tcode, length, i;
868
869         tcode = HEADER_GET_TCODE(packet->header[0]);
870         if (TCODE_IS_BLOCK_PACKET(tcode))
871                 length = HEADER_GET_DATA_LENGTH(packet->header[3]);
872         else
873                 length = 4;
874
875         i = csr - CSR_CONFIG_ROM;
876         if (i + length > CONFIG_ROM_SIZE) {
877                 fw_fill_response(&response, packet->header,
878                                  RCODE_ADDRESS_ERROR, NULL, 0);
879         } else if (!TCODE_IS_READ_REQUEST(tcode)) {
880                 fw_fill_response(&response, packet->header,
881                                  RCODE_TYPE_ERROR, NULL, 0);
882         } else {
883                 fw_fill_response(&response, packet->header, RCODE_COMPLETE,
884                                  (void *) ohci->config_rom + i, length);
885         }
886
887         fw_core_handle_response(&ohci->card, &response);
888 }
889
890 static void
891 handle_local_lock(struct fw_ohci *ohci, struct fw_packet *packet, u32 csr)
892 {
893         struct fw_packet response;
894         int tcode, length, ext_tcode, sel;
895         __be32 *payload, lock_old;
896         u32 lock_arg, lock_data;
897
898         tcode = HEADER_GET_TCODE(packet->header[0]);
899         length = HEADER_GET_DATA_LENGTH(packet->header[3]);
900         payload = packet->payload;
901         ext_tcode = HEADER_GET_EXTENDED_TCODE(packet->header[3]);
902
903         if (tcode == TCODE_LOCK_REQUEST &&
904             ext_tcode == EXTCODE_COMPARE_SWAP && length == 8) {
905                 lock_arg = be32_to_cpu(payload[0]);
906                 lock_data = be32_to_cpu(payload[1]);
907         } else if (tcode == TCODE_READ_QUADLET_REQUEST) {
908                 lock_arg = 0;
909                 lock_data = 0;
910         } else {
911                 fw_fill_response(&response, packet->header,
912                                  RCODE_TYPE_ERROR, NULL, 0);
913                 goto out;
914         }
915
916         sel = (csr - CSR_BUS_MANAGER_ID) / 4;
917         reg_write(ohci, OHCI1394_CSRData, lock_data);
918         reg_write(ohci, OHCI1394_CSRCompareData, lock_arg);
919         reg_write(ohci, OHCI1394_CSRControl, sel);
920
921         if (reg_read(ohci, OHCI1394_CSRControl) & 0x80000000)
922                 lock_old = cpu_to_be32(reg_read(ohci, OHCI1394_CSRData));
923         else
924                 fw_notify("swap not done yet\n");
925
926         fw_fill_response(&response, packet->header,
927                          RCODE_COMPLETE, &lock_old, sizeof(lock_old));
928  out:
929         fw_core_handle_response(&ohci->card, &response);
930 }
931
932 static void
933 handle_local_request(struct context *ctx, struct fw_packet *packet)
934 {
935         u64 offset;
936         u32 csr;
937
938         if (ctx == &ctx->ohci->at_request_ctx) {
939                 packet->ack = ACK_PENDING;
940                 packet->callback(packet, &ctx->ohci->card, packet->ack);
941         }
942
943         offset =
944                 ((unsigned long long)
945                  HEADER_GET_OFFSET_HIGH(packet->header[1]) << 32) |
946                 packet->header[2];
947         csr = offset - CSR_REGISTER_BASE;
948
949         /* Handle config rom reads. */
950         if (csr >= CSR_CONFIG_ROM && csr < CSR_CONFIG_ROM_END)
951                 handle_local_rom(ctx->ohci, packet, csr);
952         else switch (csr) {
953         case CSR_BUS_MANAGER_ID:
954         case CSR_BANDWIDTH_AVAILABLE:
955         case CSR_CHANNELS_AVAILABLE_HI:
956         case CSR_CHANNELS_AVAILABLE_LO:
957                 handle_local_lock(ctx->ohci, packet, csr);
958                 break;
959         default:
960                 if (ctx == &ctx->ohci->at_request_ctx)
961                         fw_core_handle_request(&ctx->ohci->card, packet);
962                 else
963                         fw_core_handle_response(&ctx->ohci->card, packet);
964                 break;
965         }
966
967         if (ctx == &ctx->ohci->at_response_ctx) {
968                 packet->ack = ACK_COMPLETE;
969                 packet->callback(packet, &ctx->ohci->card, packet->ack);
970         }
971 }
972
973 static void
974 at_context_transmit(struct context *ctx, struct fw_packet *packet)
975 {
976         unsigned long flags;
977         int retval;
978
979         spin_lock_irqsave(&ctx->ohci->lock, flags);
980
981         if (HEADER_GET_DESTINATION(packet->header[0]) == ctx->ohci->node_id &&
982             ctx->ohci->generation == packet->generation) {
983                 spin_unlock_irqrestore(&ctx->ohci->lock, flags);
984                 handle_local_request(ctx, packet);
985                 return;
986         }
987
988         retval = at_context_queue_packet(ctx, packet);
989         spin_unlock_irqrestore(&ctx->ohci->lock, flags);
990
991         if (retval < 0)
992                 packet->callback(packet, &ctx->ohci->card, packet->ack);
993
994 }
995
996 static void bus_reset_tasklet(unsigned long data)
997 {
998         struct fw_ohci *ohci = (struct fw_ohci *)data;
999         int self_id_count, i, j, reg;
1000         int generation, new_generation;
1001         unsigned long flags;
1002         void *free_rom = NULL;
1003         dma_addr_t free_rom_bus = 0;
1004
1005         reg = reg_read(ohci, OHCI1394_NodeID);
1006         if (!(reg & OHCI1394_NodeID_idValid)) {
1007                 fw_notify("node ID not valid, new bus reset in progress\n");
1008                 return;
1009         }
1010         if ((reg & OHCI1394_NodeID_nodeNumber) == 63) {
1011                 fw_notify("malconfigured bus\n");
1012                 return;
1013         }
1014         ohci->node_id = reg & (OHCI1394_NodeID_busNumber |
1015                                OHCI1394_NodeID_nodeNumber);
1016
1017         /*
1018          * The count in the SelfIDCount register is the number of
1019          * bytes in the self ID receive buffer.  Since we also receive
1020          * the inverted quadlets and a header quadlet, we shift one
1021          * bit extra to get the actual number of self IDs.
1022          */
1023
1024         self_id_count = (reg_read(ohci, OHCI1394_SelfIDCount) >> 3) & 0x3ff;
1025         generation = (le32_to_cpu(ohci->self_id_cpu[0]) >> 16) & 0xff;
1026         rmb();
1027
1028         for (i = 1, j = 0; j < self_id_count; i += 2, j++) {
1029                 if (ohci->self_id_cpu[i] != ~ohci->self_id_cpu[i + 1])
1030                         fw_error("inconsistent self IDs\n");
1031                 ohci->self_id_buffer[j] = le32_to_cpu(ohci->self_id_cpu[i]);
1032         }
1033         rmb();
1034
1035         /*
1036          * Check the consistency of the self IDs we just read.  The
1037          * problem we face is that a new bus reset can start while we
1038          * read out the self IDs from the DMA buffer. If this happens,
1039          * the DMA buffer will be overwritten with new self IDs and we
1040          * will read out inconsistent data.  The OHCI specification
1041          * (section 11.2) recommends a technique similar to
1042          * linux/seqlock.h, where we remember the generation of the
1043          * self IDs in the buffer before reading them out and compare
1044          * it to the current generation after reading them out.  If
1045          * the two generations match we know we have a consistent set
1046          * of self IDs.
1047          */
1048
1049         new_generation = (reg_read(ohci, OHCI1394_SelfIDCount) >> 16) & 0xff;
1050         if (new_generation != generation) {
1051                 fw_notify("recursive bus reset detected, "
1052                           "discarding self ids\n");
1053                 return;
1054         }
1055
1056         /* FIXME: Document how the locking works. */
1057         spin_lock_irqsave(&ohci->lock, flags);
1058
1059         ohci->generation = generation;
1060         context_stop(&ohci->at_request_ctx);
1061         context_stop(&ohci->at_response_ctx);
1062         reg_write(ohci, OHCI1394_IntEventClear, OHCI1394_busReset);
1063
1064         /*
1065          * This next bit is unrelated to the AT context stuff but we
1066          * have to do it under the spinlock also.  If a new config rom
1067          * was set up before this reset, the old one is now no longer
1068          * in use and we can free it. Update the config rom pointers
1069          * to point to the current config rom and clear the
1070          * next_config_rom pointer so a new udpate can take place.
1071          */
1072
1073         if (ohci->next_config_rom != NULL) {
1074                 if (ohci->next_config_rom != ohci->config_rom) {
1075                         free_rom      = ohci->config_rom;
1076                         free_rom_bus  = ohci->config_rom_bus;
1077                 }
1078                 ohci->config_rom      = ohci->next_config_rom;
1079                 ohci->config_rom_bus  = ohci->next_config_rom_bus;
1080                 ohci->next_config_rom = NULL;
1081
1082                 /*
1083                  * Restore config_rom image and manually update
1084                  * config_rom registers.  Writing the header quadlet
1085                  * will indicate that the config rom is ready, so we
1086                  * do that last.
1087                  */
1088                 reg_write(ohci, OHCI1394_BusOptions,
1089                           be32_to_cpu(ohci->config_rom[2]));
1090                 ohci->config_rom[0] = cpu_to_be32(ohci->next_header);
1091                 reg_write(ohci, OHCI1394_ConfigROMhdr, ohci->next_header);
1092         }
1093
1094         spin_unlock_irqrestore(&ohci->lock, flags);
1095
1096         if (free_rom)
1097                 dma_free_coherent(ohci->card.device, CONFIG_ROM_SIZE,
1098                                   free_rom, free_rom_bus);
1099
1100         fw_core_handle_bus_reset(&ohci->card, ohci->node_id, generation,
1101                                  self_id_count, ohci->self_id_buffer);
1102 }
1103
1104 static irqreturn_t irq_handler(int irq, void *data)
1105 {
1106         struct fw_ohci *ohci = data;
1107         u32 event, iso_event, cycle_time;
1108         int i;
1109
1110         event = reg_read(ohci, OHCI1394_IntEventClear);
1111
1112         if (!event || !~event)
1113                 return IRQ_NONE;
1114
1115         reg_write(ohci, OHCI1394_IntEventClear, event);
1116
1117         if (event & OHCI1394_selfIDComplete)
1118                 tasklet_schedule(&ohci->bus_reset_tasklet);
1119
1120         if (event & OHCI1394_RQPkt)
1121                 tasklet_schedule(&ohci->ar_request_ctx.tasklet);
1122
1123         if (event & OHCI1394_RSPkt)
1124                 tasklet_schedule(&ohci->ar_response_ctx.tasklet);
1125
1126         if (event & OHCI1394_reqTxComplete)
1127                 tasklet_schedule(&ohci->at_request_ctx.tasklet);
1128
1129         if (event & OHCI1394_respTxComplete)
1130                 tasklet_schedule(&ohci->at_response_ctx.tasklet);
1131
1132         iso_event = reg_read(ohci, OHCI1394_IsoRecvIntEventClear);
1133         reg_write(ohci, OHCI1394_IsoRecvIntEventClear, iso_event);
1134
1135         while (iso_event) {
1136                 i = ffs(iso_event) - 1;
1137                 tasklet_schedule(&ohci->ir_context_list[i].context.tasklet);
1138                 iso_event &= ~(1 << i);
1139         }
1140
1141         iso_event = reg_read(ohci, OHCI1394_IsoXmitIntEventClear);
1142         reg_write(ohci, OHCI1394_IsoXmitIntEventClear, iso_event);
1143
1144         while (iso_event) {
1145                 i = ffs(iso_event) - 1;
1146                 tasklet_schedule(&ohci->it_context_list[i].context.tasklet);
1147                 iso_event &= ~(1 << i);
1148         }
1149
1150         if (unlikely(event & OHCI1394_postedWriteErr))
1151                 fw_error("PCI posted write error\n");
1152
1153         if (unlikely(event & OHCI1394_cycleTooLong)) {
1154                 if (printk_ratelimit())
1155                         fw_notify("isochronous cycle too long\n");
1156                 reg_write(ohci, OHCI1394_LinkControlSet,
1157                           OHCI1394_LinkControl_cycleMaster);
1158         }
1159
1160         if (event & OHCI1394_cycle64Seconds) {
1161                 cycle_time = reg_read(ohci, OHCI1394_IsochronousCycleTimer);
1162                 if ((cycle_time & 0x80000000) == 0)
1163                         ohci->bus_seconds++;
1164         }
1165
1166         return IRQ_HANDLED;
1167 }
1168
1169 static int software_reset(struct fw_ohci *ohci)
1170 {
1171         int i;
1172
1173         reg_write(ohci, OHCI1394_HCControlSet, OHCI1394_HCControl_softReset);
1174
1175         for (i = 0; i < OHCI_LOOP_COUNT; i++) {
1176                 if ((reg_read(ohci, OHCI1394_HCControlSet) &
1177                      OHCI1394_HCControl_softReset) == 0)
1178                         return 0;
1179                 msleep(1);
1180         }
1181
1182         return -EBUSY;
1183 }
1184
1185 static int ohci_enable(struct fw_card *card, u32 *config_rom, size_t length)
1186 {
1187         struct fw_ohci *ohci = fw_ohci(card);
1188         struct pci_dev *dev = to_pci_dev(card->device);
1189
1190         if (software_reset(ohci)) {
1191                 fw_error("Failed to reset ohci card.\n");
1192                 return -EBUSY;
1193         }
1194
1195         /*
1196          * Now enable LPS, which we need in order to start accessing
1197          * most of the registers.  In fact, on some cards (ALI M5251),
1198          * accessing registers in the SClk domain without LPS enabled
1199          * will lock up the machine.  Wait 50msec to make sure we have
1200          * full link enabled.
1201          */
1202         reg_write(ohci, OHCI1394_HCControlSet,
1203                   OHCI1394_HCControl_LPS |
1204                   OHCI1394_HCControl_postedWriteEnable);
1205         flush_writes(ohci);
1206         msleep(50);
1207
1208         reg_write(ohci, OHCI1394_HCControlClear,
1209                   OHCI1394_HCControl_noByteSwapData);
1210
1211         reg_write(ohci, OHCI1394_LinkControlSet,
1212                   OHCI1394_LinkControl_rcvSelfID |
1213                   OHCI1394_LinkControl_cycleTimerEnable |
1214                   OHCI1394_LinkControl_cycleMaster);
1215
1216         reg_write(ohci, OHCI1394_ATRetries,
1217                   OHCI1394_MAX_AT_REQ_RETRIES |
1218                   (OHCI1394_MAX_AT_RESP_RETRIES << 4) |
1219                   (OHCI1394_MAX_PHYS_RESP_RETRIES << 8));
1220
1221         ar_context_run(&ohci->ar_request_ctx);
1222         ar_context_run(&ohci->ar_response_ctx);
1223
1224         reg_write(ohci, OHCI1394_SelfIDBuffer, ohci->self_id_bus);
1225         reg_write(ohci, OHCI1394_PhyUpperBound, 0x00010000);
1226         reg_write(ohci, OHCI1394_IntEventClear, ~0);
1227         reg_write(ohci, OHCI1394_IntMaskClear, ~0);
1228         reg_write(ohci, OHCI1394_IntMaskSet,
1229                   OHCI1394_selfIDComplete |
1230                   OHCI1394_RQPkt | OHCI1394_RSPkt |
1231                   OHCI1394_reqTxComplete | OHCI1394_respTxComplete |
1232                   OHCI1394_isochRx | OHCI1394_isochTx |
1233                   OHCI1394_postedWriteErr | OHCI1394_cycleTooLong |
1234                   OHCI1394_cycle64Seconds | OHCI1394_masterIntEnable);
1235
1236         /* Activate link_on bit and contender bit in our self ID packets.*/
1237         if (ohci_update_phy_reg(card, 4, 0,
1238                                 PHY_LINK_ACTIVE | PHY_CONTENDER) < 0)
1239                 return -EIO;
1240
1241         /*
1242          * When the link is not yet enabled, the atomic config rom
1243          * update mechanism described below in ohci_set_config_rom()
1244          * is not active.  We have to update ConfigRomHeader and
1245          * BusOptions manually, and the write to ConfigROMmap takes
1246          * effect immediately.  We tie this to the enabling of the
1247          * link, so we have a valid config rom before enabling - the
1248          * OHCI requires that ConfigROMhdr and BusOptions have valid
1249          * values before enabling.
1250          *
1251          * However, when the ConfigROMmap is written, some controllers
1252          * always read back quadlets 0 and 2 from the config rom to
1253          * the ConfigRomHeader and BusOptions registers on bus reset.
1254          * They shouldn't do that in this initial case where the link
1255          * isn't enabled.  This means we have to use the same
1256          * workaround here, setting the bus header to 0 and then write
1257          * the right values in the bus reset tasklet.
1258          */
1259
1260         if (config_rom) {
1261                 ohci->next_config_rom =
1262                         dma_alloc_coherent(ohci->card.device, CONFIG_ROM_SIZE,
1263                                            &ohci->next_config_rom_bus,
1264                                            GFP_KERNEL);
1265                 if (ohci->next_config_rom == NULL)
1266                         return -ENOMEM;
1267
1268                 memset(ohci->next_config_rom, 0, CONFIG_ROM_SIZE);
1269                 fw_memcpy_to_be32(ohci->next_config_rom, config_rom, length * 4);
1270         } else {
1271                 /*
1272                  * In the suspend case, config_rom is NULL, which
1273                  * means that we just reuse the old config rom.
1274                  */
1275                 ohci->next_config_rom = ohci->config_rom;
1276                 ohci->next_config_rom_bus = ohci->config_rom_bus;
1277         }
1278
1279         ohci->next_header = be32_to_cpu(ohci->next_config_rom[0]);
1280         ohci->next_config_rom[0] = 0;
1281         reg_write(ohci, OHCI1394_ConfigROMhdr, 0);
1282         reg_write(ohci, OHCI1394_BusOptions,
1283                   be32_to_cpu(ohci->next_config_rom[2]));
1284         reg_write(ohci, OHCI1394_ConfigROMmap, ohci->next_config_rom_bus);
1285
1286         reg_write(ohci, OHCI1394_AsReqFilterHiSet, 0x80000000);
1287
1288         if (request_irq(dev->irq, irq_handler,
1289                         IRQF_SHARED, ohci_driver_name, ohci)) {
1290                 fw_error("Failed to allocate shared interrupt %d.\n",
1291                          dev->irq);
1292                 dma_free_coherent(ohci->card.device, CONFIG_ROM_SIZE,
1293                                   ohci->config_rom, ohci->config_rom_bus);
1294                 return -EIO;
1295         }
1296
1297         reg_write(ohci, OHCI1394_HCControlSet,
1298                   OHCI1394_HCControl_linkEnable |
1299                   OHCI1394_HCControl_BIBimageValid);
1300         flush_writes(ohci);
1301
1302         /*
1303          * We are ready to go, initiate bus reset to finish the
1304          * initialization.
1305          */
1306
1307         fw_core_initiate_bus_reset(&ohci->card, 1);
1308
1309         return 0;
1310 }
1311
1312 static int
1313 ohci_set_config_rom(struct fw_card *card, u32 *config_rom, size_t length)
1314 {
1315         struct fw_ohci *ohci;
1316         unsigned long flags;
1317         int retval = -EBUSY;
1318         __be32 *next_config_rom;
1319         dma_addr_t next_config_rom_bus;
1320
1321         ohci = fw_ohci(card);
1322
1323         /*
1324          * When the OHCI controller is enabled, the config rom update
1325          * mechanism is a bit tricky, but easy enough to use.  See
1326          * section 5.5.6 in the OHCI specification.
1327          *
1328          * The OHCI controller caches the new config rom address in a
1329          * shadow register (ConfigROMmapNext) and needs a bus reset
1330          * for the changes to take place.  When the bus reset is
1331          * detected, the controller loads the new values for the
1332          * ConfigRomHeader and BusOptions registers from the specified
1333          * config rom and loads ConfigROMmap from the ConfigROMmapNext
1334          * shadow register. All automatically and atomically.
1335          *
1336          * Now, there's a twist to this story.  The automatic load of
1337          * ConfigRomHeader and BusOptions doesn't honor the
1338          * noByteSwapData bit, so with a be32 config rom, the
1339          * controller will load be32 values in to these registers
1340          * during the atomic update, even on litte endian
1341          * architectures.  The workaround we use is to put a 0 in the
1342          * header quadlet; 0 is endian agnostic and means that the
1343          * config rom isn't ready yet.  In the bus reset tasklet we
1344          * then set up the real values for the two registers.
1345          *
1346          * We use ohci->lock to avoid racing with the code that sets
1347          * ohci->next_config_rom to NULL (see bus_reset_tasklet).
1348          */
1349
1350         next_config_rom =
1351                 dma_alloc_coherent(ohci->card.device, CONFIG_ROM_SIZE,
1352                                    &next_config_rom_bus, GFP_KERNEL);
1353         if (next_config_rom == NULL)
1354                 return -ENOMEM;
1355
1356         spin_lock_irqsave(&ohci->lock, flags);
1357
1358         if (ohci->next_config_rom == NULL) {
1359                 ohci->next_config_rom = next_config_rom;
1360                 ohci->next_config_rom_bus = next_config_rom_bus;
1361
1362                 memset(ohci->next_config_rom, 0, CONFIG_ROM_SIZE);
1363                 fw_memcpy_to_be32(ohci->next_config_rom, config_rom,
1364                                   length * 4);
1365
1366                 ohci->next_header = config_rom[0];
1367                 ohci->next_config_rom[0] = 0;
1368
1369                 reg_write(ohci, OHCI1394_ConfigROMmap,
1370                           ohci->next_config_rom_bus);
1371                 retval = 0;
1372         }
1373
1374         spin_unlock_irqrestore(&ohci->lock, flags);
1375
1376         /*
1377          * Now initiate a bus reset to have the changes take
1378          * effect. We clean up the old config rom memory and DMA
1379          * mappings in the bus reset tasklet, since the OHCI
1380          * controller could need to access it before the bus reset
1381          * takes effect.
1382          */
1383         if (retval == 0)
1384                 fw_core_initiate_bus_reset(&ohci->card, 1);
1385         else
1386                 dma_free_coherent(ohci->card.device, CONFIG_ROM_SIZE,
1387                                   next_config_rom, next_config_rom_bus);
1388
1389         return retval;
1390 }
1391
1392 static void ohci_send_request(struct fw_card *card, struct fw_packet *packet)
1393 {
1394         struct fw_ohci *ohci = fw_ohci(card);
1395
1396         at_context_transmit(&ohci->at_request_ctx, packet);
1397 }
1398
1399 static void ohci_send_response(struct fw_card *card, struct fw_packet *packet)
1400 {
1401         struct fw_ohci *ohci = fw_ohci(card);
1402
1403         at_context_transmit(&ohci->at_response_ctx, packet);
1404 }
1405
1406 static int ohci_cancel_packet(struct fw_card *card, struct fw_packet *packet)
1407 {
1408         struct fw_ohci *ohci = fw_ohci(card);
1409         struct context *ctx = &ohci->at_request_ctx;
1410         struct driver_data *driver_data = packet->driver_data;
1411         int retval = -ENOENT;
1412
1413         tasklet_disable(&ctx->tasklet);
1414
1415         if (packet->ack != 0)
1416                 goto out;
1417
1418         driver_data->packet = NULL;
1419         packet->ack = RCODE_CANCELLED;
1420         packet->callback(packet, &ohci->card, packet->ack);
1421         retval = 0;
1422
1423  out:
1424         tasklet_enable(&ctx->tasklet);
1425
1426         return retval;
1427 }
1428
1429 static int
1430 ohci_enable_phys_dma(struct fw_card *card, int node_id, int generation)
1431 {
1432         struct fw_ohci *ohci = fw_ohci(card);
1433         unsigned long flags;
1434         int n, retval = 0;
1435
1436         /*
1437          * FIXME:  Make sure this bitmask is cleared when we clear the busReset
1438          * interrupt bit.  Clear physReqResourceAllBuses on bus reset.
1439          */
1440
1441         spin_lock_irqsave(&ohci->lock, flags);
1442
1443         if (ohci->generation != generation) {
1444                 retval = -ESTALE;
1445                 goto out;
1446         }
1447
1448         /*
1449          * Note, if the node ID contains a non-local bus ID, physical DMA is
1450          * enabled for _all_ nodes on remote buses.
1451          */
1452
1453         n = (node_id & 0xffc0) == LOCAL_BUS ? node_id & 0x3f : 63;
1454         if (n < 32)
1455                 reg_write(ohci, OHCI1394_PhyReqFilterLoSet, 1 << n);
1456         else
1457                 reg_write(ohci, OHCI1394_PhyReqFilterHiSet, 1 << (n - 32));
1458
1459         flush_writes(ohci);
1460  out:
1461         spin_unlock_irqrestore(&ohci->lock, flags);
1462         return retval;
1463 }
1464
1465 static u64
1466 ohci_get_bus_time(struct fw_card *card)
1467 {
1468         struct fw_ohci *ohci = fw_ohci(card);
1469         u32 cycle_time;
1470         u64 bus_time;
1471
1472         cycle_time = reg_read(ohci, OHCI1394_IsochronousCycleTimer);
1473         bus_time = ((u64) ohci->bus_seconds << 32) | cycle_time;
1474
1475         return bus_time;
1476 }
1477
1478 static int handle_ir_dualbuffer_packet(struct context *context,
1479                                        struct descriptor *d,
1480                                        struct descriptor *last)
1481 {
1482         struct iso_context *ctx =
1483                 container_of(context, struct iso_context, context);
1484         struct db_descriptor *db = (struct db_descriptor *) d;
1485         __le32 *ir_header;
1486         size_t header_length;
1487         void *p, *end;
1488         int i;
1489
1490         if (db->first_res_count > 0 && db->second_res_count > 0) {
1491                 if (ctx->excess_bytes <= le16_to_cpu(db->second_req_count)) {
1492                         /* This descriptor isn't done yet, stop iteration. */
1493                         return 0;
1494                 }
1495                 ctx->excess_bytes -= le16_to_cpu(db->second_req_count);
1496         }
1497
1498         header_length = le16_to_cpu(db->first_req_count) -
1499                 le16_to_cpu(db->first_res_count);
1500
1501         i = ctx->header_length;
1502         p = db + 1;
1503         end = p + header_length;
1504         while (p < end && i + ctx->base.header_size <= PAGE_SIZE) {
1505                 /*
1506                  * The iso header is byteswapped to little endian by
1507                  * the controller, but the remaining header quadlets
1508                  * are big endian.  We want to present all the headers
1509                  * as big endian, so we have to swap the first
1510                  * quadlet.
1511                  */
1512                 *(u32 *) (ctx->header + i) = __swab32(*(u32 *) (p + 4));
1513                 memcpy(ctx->header + i + 4, p + 8, ctx->base.header_size - 4);
1514                 i += ctx->base.header_size;
1515                 ctx->excess_bytes +=
1516                         (le32_to_cpu(*(u32 *)(p + 4)) >> 16) & 0xffff;
1517                 p += ctx->base.header_size + 4;
1518         }
1519         ctx->header_length = i;
1520
1521         ctx->excess_bytes -= le16_to_cpu(db->second_req_count) -
1522                 le16_to_cpu(db->second_res_count);
1523
1524         if (le16_to_cpu(db->control) & DESCRIPTOR_IRQ_ALWAYS) {
1525                 ir_header = (__le32 *) (db + 1);
1526                 ctx->base.callback(&ctx->base,
1527                                    le32_to_cpu(ir_header[0]) & 0xffff,
1528                                    ctx->header_length, ctx->header,
1529                                    ctx->base.callback_data);
1530                 ctx->header_length = 0;
1531         }
1532
1533         return 1;
1534 }
1535
1536 static int handle_ir_packet_per_buffer(struct context *context,
1537                                        struct descriptor *d,
1538                                        struct descriptor *last)
1539 {
1540         struct iso_context *ctx =
1541                 container_of(context, struct iso_context, context);
1542         struct descriptor *pd;
1543         __le32 *ir_header;
1544         void *p;
1545         int i;
1546
1547         for (pd = d; pd <= last; pd++) {
1548                 if (pd->transfer_status)
1549                         break;
1550         }
1551         if (pd > last)
1552                 /* Descriptor(s) not done yet, stop iteration */
1553                 return 0;
1554
1555         i   = ctx->header_length;
1556         p   = last + 1;
1557
1558         if (ctx->base.header_size > 0 &&
1559                         i + ctx->base.header_size <= PAGE_SIZE) {
1560                 /*
1561                  * The iso header is byteswapped to little endian by
1562                  * the controller, but the remaining header quadlets
1563                  * are big endian.  We want to present all the headers
1564                  * as big endian, so we have to swap the first quadlet.
1565                  */
1566                 *(u32 *) (ctx->header + i) = __swab32(*(u32 *) (p + 4));
1567                 memcpy(ctx->header + i + 4, p + 8, ctx->base.header_size - 4);
1568                 ctx->header_length += ctx->base.header_size;
1569         }
1570
1571         if (le16_to_cpu(last->control) & DESCRIPTOR_IRQ_ALWAYS) {
1572                 ir_header = (__le32 *) p;
1573                 ctx->base.callback(&ctx->base,
1574                                    le32_to_cpu(ir_header[0]) & 0xffff,
1575                                    ctx->header_length, ctx->header,
1576                                    ctx->base.callback_data);
1577                 ctx->header_length = 0;
1578         }
1579
1580         return 1;
1581 }
1582
1583 static int handle_it_packet(struct context *context,
1584                             struct descriptor *d,
1585                             struct descriptor *last)
1586 {
1587         struct iso_context *ctx =
1588                 container_of(context, struct iso_context, context);
1589
1590         if (last->transfer_status == 0)
1591                 /* This descriptor isn't done yet, stop iteration. */
1592                 return 0;
1593
1594         if (le16_to_cpu(last->control) & DESCRIPTOR_IRQ_ALWAYS)
1595                 ctx->base.callback(&ctx->base, le16_to_cpu(last->res_count),
1596                                    0, NULL, ctx->base.callback_data);
1597
1598         return 1;
1599 }
1600
1601 static struct fw_iso_context *
1602 ohci_allocate_iso_context(struct fw_card *card, int type, size_t header_size)
1603 {
1604         struct fw_ohci *ohci = fw_ohci(card);
1605         struct iso_context *ctx, *list;
1606         descriptor_callback_t callback;
1607         u32 *mask, regs;
1608         unsigned long flags;
1609         int index, retval = -ENOMEM;
1610
1611         if (type == FW_ISO_CONTEXT_TRANSMIT) {
1612                 mask = &ohci->it_context_mask;
1613                 list = ohci->it_context_list;
1614                 callback = handle_it_packet;
1615         } else {
1616                 mask = &ohci->ir_context_mask;
1617                 list = ohci->ir_context_list;
1618                 if (ohci->version >= OHCI_VERSION_1_1)
1619                         callback = handle_ir_dualbuffer_packet;
1620                 else
1621                         callback = handle_ir_packet_per_buffer;
1622         }
1623
1624         spin_lock_irqsave(&ohci->lock, flags);
1625         index = ffs(*mask) - 1;
1626         if (index >= 0)
1627                 *mask &= ~(1 << index);
1628         spin_unlock_irqrestore(&ohci->lock, flags);
1629
1630         if (index < 0)
1631                 return ERR_PTR(-EBUSY);
1632
1633         if (type == FW_ISO_CONTEXT_TRANSMIT)
1634                 regs = OHCI1394_IsoXmitContextBase(index);
1635         else
1636                 regs = OHCI1394_IsoRcvContextBase(index);
1637
1638         ctx = &list[index];
1639         memset(ctx, 0, sizeof(*ctx));
1640         ctx->header_length = 0;
1641         ctx->header = (void *) __get_free_page(GFP_KERNEL);
1642         if (ctx->header == NULL)
1643                 goto out;
1644
1645         retval = context_init(&ctx->context, ohci, regs, callback);
1646         if (retval < 0)
1647                 goto out_with_header;
1648
1649         return &ctx->base;
1650
1651  out_with_header:
1652         free_page((unsigned long)ctx->header);
1653  out:
1654         spin_lock_irqsave(&ohci->lock, flags);
1655         *mask |= 1 << index;
1656         spin_unlock_irqrestore(&ohci->lock, flags);
1657
1658         return ERR_PTR(retval);
1659 }
1660
1661 static int ohci_start_iso(struct fw_iso_context *base,
1662                           s32 cycle, u32 sync, u32 tags)
1663 {
1664         struct iso_context *ctx = container_of(base, struct iso_context, base);
1665         struct fw_ohci *ohci = ctx->context.ohci;
1666         u32 control, match;
1667         int index;
1668
1669         if (ctx->base.type == FW_ISO_CONTEXT_TRANSMIT) {
1670                 index = ctx - ohci->it_context_list;
1671                 match = 0;
1672                 if (cycle >= 0)
1673                         match = IT_CONTEXT_CYCLE_MATCH_ENABLE |
1674                                 (cycle & 0x7fff) << 16;
1675
1676                 reg_write(ohci, OHCI1394_IsoXmitIntEventClear, 1 << index);
1677                 reg_write(ohci, OHCI1394_IsoXmitIntMaskSet, 1 << index);
1678                 context_run(&ctx->context, match);
1679         } else {
1680                 index = ctx - ohci->ir_context_list;
1681                 control = IR_CONTEXT_ISOCH_HEADER;
1682                 if (ohci->version >= OHCI_VERSION_1_1)
1683                         control |= IR_CONTEXT_DUAL_BUFFER_MODE;
1684                 match = (tags << 28) | (sync << 8) | ctx->base.channel;
1685                 if (cycle >= 0) {
1686                         match |= (cycle & 0x07fff) << 12;
1687                         control |= IR_CONTEXT_CYCLE_MATCH_ENABLE;
1688                 }
1689
1690                 reg_write(ohci, OHCI1394_IsoRecvIntEventClear, 1 << index);
1691                 reg_write(ohci, OHCI1394_IsoRecvIntMaskSet, 1 << index);
1692                 reg_write(ohci, CONTEXT_MATCH(ctx->context.regs), match);
1693                 context_run(&ctx->context, control);
1694         }
1695
1696         return 0;
1697 }
1698
1699 static int ohci_stop_iso(struct fw_iso_context *base)
1700 {
1701         struct fw_ohci *ohci = fw_ohci(base->card);
1702         struct iso_context *ctx = container_of(base, struct iso_context, base);
1703         int index;
1704
1705         if (ctx->base.type == FW_ISO_CONTEXT_TRANSMIT) {
1706                 index = ctx - ohci->it_context_list;
1707                 reg_write(ohci, OHCI1394_IsoXmitIntMaskClear, 1 << index);
1708         } else {
1709                 index = ctx - ohci->ir_context_list;
1710                 reg_write(ohci, OHCI1394_IsoRecvIntMaskClear, 1 << index);
1711         }
1712         flush_writes(ohci);
1713         context_stop(&ctx->context);
1714
1715         return 0;
1716 }
1717
1718 static void ohci_free_iso_context(struct fw_iso_context *base)
1719 {
1720         struct fw_ohci *ohci = fw_ohci(base->card);
1721         struct iso_context *ctx = container_of(base, struct iso_context, base);
1722         unsigned long flags;
1723         int index;
1724
1725         ohci_stop_iso(base);
1726         context_release(&ctx->context);
1727         free_page((unsigned long)ctx->header);
1728
1729         spin_lock_irqsave(&ohci->lock, flags);
1730
1731         if (ctx->base.type == FW_ISO_CONTEXT_TRANSMIT) {
1732                 index = ctx - ohci->it_context_list;
1733                 ohci->it_context_mask |= 1 << index;
1734         } else {
1735                 index = ctx - ohci->ir_context_list;
1736                 ohci->ir_context_mask |= 1 << index;
1737         }
1738
1739         spin_unlock_irqrestore(&ohci->lock, flags);
1740 }
1741
1742 static int
1743 ohci_queue_iso_transmit(struct fw_iso_context *base,
1744                         struct fw_iso_packet *packet,
1745                         struct fw_iso_buffer *buffer,
1746                         unsigned long payload)
1747 {
1748         struct iso_context *ctx = container_of(base, struct iso_context, base);
1749         struct descriptor *d, *last, *pd;
1750         struct fw_iso_packet *p;
1751         __le32 *header;
1752         dma_addr_t d_bus, page_bus;
1753         u32 z, header_z, payload_z, irq;
1754         u32 payload_index, payload_end_index, next_page_index;
1755         int page, end_page, i, length, offset;
1756
1757         /*
1758          * FIXME: Cycle lost behavior should be configurable: lose
1759          * packet, retransmit or terminate..
1760          */
1761
1762         p = packet;
1763         payload_index = payload;
1764
1765         if (p->skip)
1766                 z = 1;
1767         else
1768                 z = 2;
1769         if (p->header_length > 0)
1770                 z++;
1771
1772         /* Determine the first page the payload isn't contained in. */
1773         end_page = PAGE_ALIGN(payload_index + p->payload_length) >> PAGE_SHIFT;
1774         if (p->payload_length > 0)
1775                 payload_z = end_page - (payload_index >> PAGE_SHIFT);
1776         else
1777                 payload_z = 0;
1778
1779         z += payload_z;
1780
1781         /* Get header size in number of descriptors. */
1782         header_z = DIV_ROUND_UP(p->header_length, sizeof(*d));
1783
1784         d = context_get_descriptors(&ctx->context, z + header_z, &d_bus);
1785         if (d == NULL)
1786                 return -ENOMEM;
1787
1788         if (!p->skip) {
1789                 d[0].control   = cpu_to_le16(DESCRIPTOR_KEY_IMMEDIATE);
1790                 d[0].req_count = cpu_to_le16(8);
1791
1792                 header = (__le32 *) &d[1];
1793                 header[0] = cpu_to_le32(IT_HEADER_SY(p->sy) |
1794                                         IT_HEADER_TAG(p->tag) |
1795                                         IT_HEADER_TCODE(TCODE_STREAM_DATA) |
1796                                         IT_HEADER_CHANNEL(ctx->base.channel) |
1797                                         IT_HEADER_SPEED(ctx->base.speed));
1798                 header[1] =
1799                         cpu_to_le32(IT_HEADER_DATA_LENGTH(p->header_length +
1800                                                           p->payload_length));
1801         }
1802
1803         if (p->header_length > 0) {
1804                 d[2].req_count    = cpu_to_le16(p->header_length);
1805                 d[2].data_address = cpu_to_le32(d_bus + z * sizeof(*d));
1806                 memcpy(&d[z], p->header, p->header_length);
1807         }
1808
1809         pd = d + z - payload_z;
1810         payload_end_index = payload_index + p->payload_length;
1811         for (i = 0; i < payload_z; i++) {
1812                 page               = payload_index >> PAGE_SHIFT;
1813                 offset             = payload_index & ~PAGE_MASK;
1814                 next_page_index    = (page + 1) << PAGE_SHIFT;
1815                 length             =
1816                         min(next_page_index, payload_end_index) - payload_index;
1817                 pd[i].req_count    = cpu_to_le16(length);
1818
1819                 page_bus = page_private(buffer->pages[page]);
1820                 pd[i].data_address = cpu_to_le32(page_bus + offset);
1821
1822                 payload_index += length;
1823         }
1824
1825         if (p->interrupt)
1826                 irq = DESCRIPTOR_IRQ_ALWAYS;
1827         else
1828                 irq = DESCRIPTOR_NO_IRQ;
1829
1830         last = z == 2 ? d : d + z - 1;
1831         last->control |= cpu_to_le16(DESCRIPTOR_OUTPUT_LAST |
1832                                      DESCRIPTOR_STATUS |
1833                                      DESCRIPTOR_BRANCH_ALWAYS |
1834                                      irq);
1835
1836         context_append(&ctx->context, d, z, header_z);
1837
1838         return 0;
1839 }
1840
1841 static int
1842 ohci_queue_iso_receive_dualbuffer(struct fw_iso_context *base,
1843                                   struct fw_iso_packet *packet,
1844                                   struct fw_iso_buffer *buffer,
1845                                   unsigned long payload)
1846 {
1847         struct iso_context *ctx = container_of(base, struct iso_context, base);
1848         struct db_descriptor *db = NULL;
1849         struct descriptor *d;
1850         struct fw_iso_packet *p;
1851         dma_addr_t d_bus, page_bus;
1852         u32 z, header_z, length, rest;
1853         int page, offset, packet_count, header_size;
1854
1855         /*
1856          * FIXME: Cycle lost behavior should be configurable: lose
1857          * packet, retransmit or terminate..
1858          */
1859
1860         p = packet;
1861         z = 2;
1862
1863         /*
1864          * The OHCI controller puts the status word in the header
1865          * buffer too, so we need 4 extra bytes per packet.
1866          */
1867         packet_count = p->header_length / ctx->base.header_size;
1868         header_size = packet_count * (ctx->base.header_size + 4);
1869
1870         /* Get header size in number of descriptors. */
1871         header_z = DIV_ROUND_UP(header_size, sizeof(*d));
1872         page     = payload >> PAGE_SHIFT;
1873         offset   = payload & ~PAGE_MASK;
1874         rest     = p->payload_length;
1875
1876         /* FIXME: make packet-per-buffer/dual-buffer a context option */
1877         while (rest > 0) {
1878                 d = context_get_descriptors(&ctx->context,
1879                                             z + header_z, &d_bus);
1880                 if (d == NULL)
1881                         return -ENOMEM;
1882
1883                 db = (struct db_descriptor *) d;
1884                 db->control = cpu_to_le16(DESCRIPTOR_STATUS |
1885                                           DESCRIPTOR_BRANCH_ALWAYS);
1886                 db->first_size = cpu_to_le16(ctx->base.header_size + 4);
1887                 if (p->skip && rest == p->payload_length) {
1888                         db->control |= cpu_to_le16(DESCRIPTOR_WAIT);
1889                         db->first_req_count = db->first_size;
1890                 } else {
1891                         db->first_req_count = cpu_to_le16(header_size);
1892                 }
1893                 db->first_res_count = db->first_req_count;
1894                 db->first_buffer = cpu_to_le32(d_bus + sizeof(*db));
1895
1896                 if (p->skip && rest == p->payload_length)
1897                         length = 4;
1898                 else if (offset + rest < PAGE_SIZE)
1899                         length = rest;
1900                 else
1901                         length = PAGE_SIZE - offset;
1902
1903                 db->second_req_count = cpu_to_le16(length);
1904                 db->second_res_count = db->second_req_count;
1905                 page_bus = page_private(buffer->pages[page]);
1906                 db->second_buffer = cpu_to_le32(page_bus + offset);
1907
1908                 if (p->interrupt && length == rest)
1909                         db->control |= cpu_to_le16(DESCRIPTOR_IRQ_ALWAYS);
1910
1911                 context_append(&ctx->context, d, z, header_z);
1912                 offset = (offset + length) & ~PAGE_MASK;
1913                 rest -= length;
1914                 if (offset == 0)
1915                         page++;
1916         }
1917
1918         return 0;
1919 }
1920
1921 static int
1922 ohci_queue_iso_receive_packet_per_buffer(struct fw_iso_context *base,
1923                                          struct fw_iso_packet *packet,
1924                                          struct fw_iso_buffer *buffer,
1925                                          unsigned long payload)
1926 {
1927         struct iso_context *ctx = container_of(base, struct iso_context, base);
1928         struct descriptor *d = NULL, *pd = NULL;
1929         struct fw_iso_packet *p = packet;
1930         dma_addr_t d_bus, page_bus;
1931         u32 z, header_z, rest;
1932         int i, j, length;
1933         int page, offset, packet_count, header_size, payload_per_buffer;
1934
1935         /*
1936          * The OHCI controller puts the status word in the
1937          * buffer too, so we need 4 extra bytes per packet.
1938          */
1939         packet_count = p->header_length / ctx->base.header_size;
1940         header_size  = ctx->base.header_size + 4;
1941
1942         /* Get header size in number of descriptors. */
1943         header_z = DIV_ROUND_UP(header_size, sizeof(*d));
1944         page     = payload >> PAGE_SHIFT;
1945         offset   = payload & ~PAGE_MASK;
1946         payload_per_buffer = p->payload_length / packet_count;
1947
1948         for (i = 0; i < packet_count; i++) {
1949                 /* d points to the header descriptor */
1950                 z = DIV_ROUND_UP(payload_per_buffer + offset, PAGE_SIZE) + 1;
1951                 d = context_get_descriptors(&ctx->context,
1952                                 z + header_z, &d_bus);
1953                 if (d == NULL)
1954                         return -ENOMEM;
1955
1956                 d->control      = cpu_to_le16(DESCRIPTOR_STATUS |
1957                                               DESCRIPTOR_INPUT_MORE);
1958                 if (p->skip && i == 0)
1959                         d->control |= cpu_to_le16(DESCRIPTOR_WAIT);
1960                 d->req_count    = cpu_to_le16(header_size);
1961                 d->res_count    = d->req_count;
1962                 d->transfer_status = 0;
1963                 d->data_address = cpu_to_le32(d_bus + (z * sizeof(*d)));
1964
1965                 rest = payload_per_buffer;
1966                 for (j = 1; j < z; j++) {
1967                         pd = d + j;
1968                         pd->control = cpu_to_le16(DESCRIPTOR_STATUS |
1969                                                   DESCRIPTOR_INPUT_MORE);
1970
1971                         if (offset + rest < PAGE_SIZE)
1972                                 length = rest;
1973                         else
1974                                 length = PAGE_SIZE - offset;
1975                         pd->req_count = cpu_to_le16(length);
1976                         pd->res_count = pd->req_count;
1977                         pd->transfer_status = 0;
1978
1979                         page_bus = page_private(buffer->pages[page]);
1980                         pd->data_address = cpu_to_le32(page_bus + offset);
1981
1982                         offset = (offset + length) & ~PAGE_MASK;
1983                         rest -= length;
1984                         if (offset == 0)
1985                                 page++;
1986                 }
1987                 pd->control = cpu_to_le16(DESCRIPTOR_STATUS |
1988                                           DESCRIPTOR_INPUT_LAST |
1989                                           DESCRIPTOR_BRANCH_ALWAYS);
1990                 if (p->interrupt && i == packet_count - 1)
1991                         pd->control |= cpu_to_le16(DESCRIPTOR_IRQ_ALWAYS);
1992
1993                 context_append(&ctx->context, d, z, header_z);
1994         }
1995
1996         return 0;
1997 }
1998
1999 static int
2000 ohci_queue_iso(struct fw_iso_context *base,
2001                struct fw_iso_packet *packet,
2002                struct fw_iso_buffer *buffer,
2003                unsigned long payload)
2004 {
2005         struct iso_context *ctx = container_of(base, struct iso_context, base);
2006         unsigned long flags;
2007         int retval;
2008
2009         spin_lock_irqsave(&ctx->context.ohci->lock, flags);
2010         if (base->type == FW_ISO_CONTEXT_TRANSMIT)
2011                 retval = ohci_queue_iso_transmit(base, packet, buffer, payload);
2012         else if (ctx->context.ohci->version >= OHCI_VERSION_1_1)
2013                 retval = ohci_queue_iso_receive_dualbuffer(base, packet,
2014                                                          buffer, payload);
2015         else
2016                 retval = ohci_queue_iso_receive_packet_per_buffer(base, packet,
2017                                                                 buffer,
2018                                                                 payload);
2019         spin_unlock_irqrestore(&ctx->context.ohci->lock, flags);
2020
2021         return retval;
2022 }
2023
2024 static const struct fw_card_driver ohci_driver = {
2025         .name                   = ohci_driver_name,
2026         .enable                 = ohci_enable,
2027         .update_phy_reg         = ohci_update_phy_reg,
2028         .set_config_rom         = ohci_set_config_rom,
2029         .send_request           = ohci_send_request,
2030         .send_response          = ohci_send_response,
2031         .cancel_packet          = ohci_cancel_packet,
2032         .enable_phys_dma        = ohci_enable_phys_dma,
2033         .get_bus_time           = ohci_get_bus_time,
2034
2035         .allocate_iso_context   = ohci_allocate_iso_context,
2036         .free_iso_context       = ohci_free_iso_context,
2037         .queue_iso              = ohci_queue_iso,
2038         .start_iso              = ohci_start_iso,
2039         .stop_iso               = ohci_stop_iso,
2040 };
2041
2042 static int __devinit
2043 pci_probe(struct pci_dev *dev, const struct pci_device_id *ent)
2044 {
2045         struct fw_ohci *ohci;
2046         u32 bus_options, max_receive, link_speed;
2047         u64 guid;
2048         int err;
2049         size_t size;
2050
2051         ohci = kzalloc(sizeof(*ohci), GFP_KERNEL);
2052         if (ohci == NULL) {
2053                 fw_error("Could not malloc fw_ohci data.\n");
2054                 return -ENOMEM;
2055         }
2056
2057         fw_card_initialize(&ohci->card, &ohci_driver, &dev->dev);
2058
2059         err = pci_enable_device(dev);
2060         if (err) {
2061                 fw_error("Failed to enable OHCI hardware.\n");
2062                 goto fail_put_card;
2063         }
2064
2065         pci_set_master(dev);
2066         pci_write_config_dword(dev, OHCI1394_PCI_HCI_Control, 0);
2067         pci_set_drvdata(dev, ohci);
2068
2069         spin_lock_init(&ohci->lock);
2070
2071         tasklet_init(&ohci->bus_reset_tasklet,
2072                      bus_reset_tasklet, (unsigned long)ohci);
2073
2074         err = pci_request_region(dev, 0, ohci_driver_name);
2075         if (err) {
2076                 fw_error("MMIO resource unavailable\n");
2077                 goto fail_disable;
2078         }
2079
2080         ohci->registers = pci_iomap(dev, 0, OHCI1394_REGISTER_SIZE);
2081         if (ohci->registers == NULL) {
2082                 fw_error("Failed to remap registers\n");
2083                 err = -ENXIO;
2084                 goto fail_iomem;
2085         }
2086
2087         ar_context_init(&ohci->ar_request_ctx, ohci,
2088                         OHCI1394_AsReqRcvContextControlSet);
2089
2090         ar_context_init(&ohci->ar_response_ctx, ohci,
2091                         OHCI1394_AsRspRcvContextControlSet);
2092
2093         context_init(&ohci->at_request_ctx, ohci,
2094                      OHCI1394_AsReqTrContextControlSet, handle_at_packet);
2095
2096         context_init(&ohci->at_response_ctx, ohci,
2097                      OHCI1394_AsRspTrContextControlSet, handle_at_packet);
2098
2099         reg_write(ohci, OHCI1394_IsoRecvIntMaskSet, ~0);
2100         ohci->it_context_mask = reg_read(ohci, OHCI1394_IsoRecvIntMaskSet);
2101         reg_write(ohci, OHCI1394_IsoRecvIntMaskClear, ~0);
2102         size = sizeof(struct iso_context) * hweight32(ohci->it_context_mask);
2103         ohci->it_context_list = kzalloc(size, GFP_KERNEL);
2104
2105         reg_write(ohci, OHCI1394_IsoXmitIntMaskSet, ~0);
2106         ohci->ir_context_mask = reg_read(ohci, OHCI1394_IsoXmitIntMaskSet);
2107         reg_write(ohci, OHCI1394_IsoXmitIntMaskClear, ~0);
2108         size = sizeof(struct iso_context) * hweight32(ohci->ir_context_mask);
2109         ohci->ir_context_list = kzalloc(size, GFP_KERNEL);
2110
2111         if (ohci->it_context_list == NULL || ohci->ir_context_list == NULL) {
2112                 fw_error("Out of memory for it/ir contexts.\n");
2113                 err = -ENOMEM;
2114                 goto fail_registers;
2115         }
2116
2117         /* self-id dma buffer allocation */
2118         ohci->self_id_cpu = dma_alloc_coherent(ohci->card.device,
2119                                                SELF_ID_BUF_SIZE,
2120                                                &ohci->self_id_bus,
2121                                                GFP_KERNEL);
2122         if (ohci->self_id_cpu == NULL) {
2123                 fw_error("Out of memory for self ID buffer.\n");
2124                 err = -ENOMEM;
2125                 goto fail_registers;
2126         }
2127
2128         bus_options = reg_read(ohci, OHCI1394_BusOptions);
2129         max_receive = (bus_options >> 12) & 0xf;
2130         link_speed = bus_options & 0x7;
2131         guid = ((u64) reg_read(ohci, OHCI1394_GUIDHi) << 32) |
2132                 reg_read(ohci, OHCI1394_GUIDLo);
2133
2134         err = fw_card_add(&ohci->card, max_receive, link_speed, guid);
2135         if (err < 0)
2136                 goto fail_self_id;
2137
2138         ohci->version = reg_read(ohci, OHCI1394_Version) & 0x00ff00ff;
2139         fw_notify("Added fw-ohci device %s, OHCI version %x.%x\n",
2140                   dev->dev.bus_id, ohci->version >> 16, ohci->version & 0xff);
2141         return 0;
2142
2143  fail_self_id:
2144         dma_free_coherent(ohci->card.device, SELF_ID_BUF_SIZE,
2145                           ohci->self_id_cpu, ohci->self_id_bus);
2146  fail_registers:
2147         kfree(ohci->it_context_list);
2148         kfree(ohci->ir_context_list);
2149         pci_iounmap(dev, ohci->registers);
2150  fail_iomem:
2151         pci_release_region(dev, 0);
2152  fail_disable:
2153         pci_disable_device(dev);
2154  fail_put_card:
2155         fw_card_put(&ohci->card);
2156
2157         return err;
2158 }
2159
2160 static void pci_remove(struct pci_dev *dev)
2161 {
2162         struct fw_ohci *ohci;
2163
2164         ohci = pci_get_drvdata(dev);
2165         reg_write(ohci, OHCI1394_IntMaskClear, ~0);
2166         flush_writes(ohci);
2167         fw_core_remove_card(&ohci->card);
2168
2169         /*
2170          * FIXME: Fail all pending packets here, now that the upper
2171          * layers can't queue any more.
2172          */
2173
2174         software_reset(ohci);
2175         free_irq(dev->irq, ohci);
2176         dma_free_coherent(ohci->card.device, SELF_ID_BUF_SIZE,
2177                           ohci->self_id_cpu, ohci->self_id_bus);
2178         kfree(ohci->it_context_list);
2179         kfree(ohci->ir_context_list);
2180         pci_iounmap(dev, ohci->registers);
2181         pci_release_region(dev, 0);
2182         pci_disable_device(dev);
2183         fw_card_put(&ohci->card);
2184
2185         fw_notify("Removed fw-ohci device.\n");
2186 }
2187
2188 #ifdef CONFIG_PM
2189 static int pci_suspend(struct pci_dev *pdev, pm_message_t state)
2190 {
2191         struct fw_ohci *ohci = pci_get_drvdata(pdev);
2192         int err;
2193
2194         software_reset(ohci);
2195         free_irq(pdev->irq, ohci);
2196         err = pci_save_state(pdev);
2197         if (err) {
2198                 fw_error("pci_save_state failed\n");
2199                 return err;
2200         }
2201         err = pci_set_power_state(pdev, pci_choose_state(pdev, state));
2202         if (err)
2203                 fw_error("pci_set_power_state failed with %d\n", err);
2204
2205         return 0;
2206 }
2207
2208 static int pci_resume(struct pci_dev *pdev)
2209 {
2210         struct fw_ohci *ohci = pci_get_drvdata(pdev);
2211         int err;
2212
2213         pci_set_power_state(pdev, PCI_D0);
2214         pci_restore_state(pdev);
2215         err = pci_enable_device(pdev);
2216         if (err) {
2217                 fw_error("pci_enable_device failed\n");
2218                 return err;
2219         }
2220
2221         return ohci_enable(&ohci->card, NULL, 0);
2222 }
2223 #endif
2224
2225 static struct pci_device_id pci_table[] = {
2226         { PCI_DEVICE_CLASS(PCI_CLASS_SERIAL_FIREWIRE_OHCI, ~0) },
2227         { }
2228 };
2229
2230 MODULE_DEVICE_TABLE(pci, pci_table);
2231
2232 static struct pci_driver fw_ohci_pci_driver = {
2233         .name           = ohci_driver_name,
2234         .id_table       = pci_table,
2235         .probe          = pci_probe,
2236         .remove         = pci_remove,
2237 #ifdef CONFIG_PM
2238         .resume         = pci_resume,
2239         .suspend        = pci_suspend,
2240 #endif
2241 };
2242
2243 MODULE_AUTHOR("Kristian Hoegsberg <krh@bitplanet.net>");
2244 MODULE_DESCRIPTION("Driver for PCI OHCI IEEE1394 controllers");
2245 MODULE_LICENSE("GPL");
2246
2247 /* Provide a module alias so root-on-sbp2 initrds don't break. */
2248 #ifndef CONFIG_IEEE1394_OHCI1394_MODULE
2249 MODULE_ALIAS("ohci1394");
2250 #endif
2251
2252 static int __init fw_ohci_init(void)
2253 {
2254         return pci_register_driver(&fw_ohci_pci_driver);
2255 }
2256
2257 static void __exit fw_ohci_cleanup(void)
2258 {
2259         pci_unregister_driver(&fw_ohci_pci_driver);
2260 }
2261
2262 module_init(fw_ohci_init);
2263 module_exit(fw_ohci_cleanup);