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