firewire: ohci: Move code from the bus reset tasklet into a workqueue
[pandora-kernel.git] / drivers / firewire / 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/bitops.h>
22 #include <linux/bug.h>
23 #include <linux/compiler.h>
24 #include <linux/delay.h>
25 #include <linux/device.h>
26 #include <linux/dma-mapping.h>
27 #include <linux/firewire.h>
28 #include <linux/firewire-constants.h>
29 #include <linux/init.h>
30 #include <linux/interrupt.h>
31 #include <linux/io.h>
32 #include <linux/kernel.h>
33 #include <linux/list.h>
34 #include <linux/mm.h>
35 #include <linux/module.h>
36 #include <linux/moduleparam.h>
37 #include <linux/mutex.h>
38 #include <linux/pci.h>
39 #include <linux/pci_ids.h>
40 #include <linux/slab.h>
41 #include <linux/spinlock.h>
42 #include <linux/string.h>
43 #include <linux/time.h>
44 #include <linux/vmalloc.h>
45 #include <linux/workqueue.h>
46
47 #include <asm/byteorder.h>
48 #include <asm/page.h>
49 #include <asm/system.h>
50
51 #ifdef CONFIG_PPC_PMAC
52 #include <asm/pmac_feature.h>
53 #endif
54
55 #include "core.h"
56 #include "ohci.h"
57
58 #define DESCRIPTOR_OUTPUT_MORE          0
59 #define DESCRIPTOR_OUTPUT_LAST          (1 << 12)
60 #define DESCRIPTOR_INPUT_MORE           (2 << 12)
61 #define DESCRIPTOR_INPUT_LAST           (3 << 12)
62 #define DESCRIPTOR_STATUS               (1 << 11)
63 #define DESCRIPTOR_KEY_IMMEDIATE        (2 << 8)
64 #define DESCRIPTOR_PING                 (1 << 7)
65 #define DESCRIPTOR_YY                   (1 << 6)
66 #define DESCRIPTOR_NO_IRQ               (0 << 4)
67 #define DESCRIPTOR_IRQ_ERROR            (1 << 4)
68 #define DESCRIPTOR_IRQ_ALWAYS           (3 << 4)
69 #define DESCRIPTOR_BRANCH_ALWAYS        (3 << 2)
70 #define DESCRIPTOR_WAIT                 (3 << 0)
71
72 struct descriptor {
73         __le16 req_count;
74         __le16 control;
75         __le32 data_address;
76         __le32 branch_address;
77         __le16 res_count;
78         __le16 transfer_status;
79 } __attribute__((aligned(16)));
80
81 #define CONTROL_SET(regs)       (regs)
82 #define CONTROL_CLEAR(regs)     ((regs) + 4)
83 #define COMMAND_PTR(regs)       ((regs) + 12)
84 #define CONTEXT_MATCH(regs)     ((regs) + 16)
85
86 #define AR_BUFFER_SIZE  (32*1024)
87 #define AR_BUFFERS_MIN  DIV_ROUND_UP(AR_BUFFER_SIZE, PAGE_SIZE)
88 /* we need at least two pages for proper list management */
89 #define AR_BUFFERS      (AR_BUFFERS_MIN >= 2 ? AR_BUFFERS_MIN : 2)
90
91 #define MAX_ASYNC_PAYLOAD       4096
92 #define MAX_AR_PACKET_SIZE      (16 + MAX_ASYNC_PAYLOAD + 4)
93 #define AR_WRAPAROUND_PAGES     DIV_ROUND_UP(MAX_AR_PACKET_SIZE, PAGE_SIZE)
94
95 struct ar_context {
96         struct fw_ohci *ohci;
97         struct page *pages[AR_BUFFERS];
98         void *buffer;
99         struct descriptor *descriptors;
100         dma_addr_t descriptors_bus;
101         void *pointer;
102         unsigned int last_buffer_index;
103         u32 regs;
104         struct tasklet_struct tasklet;
105 };
106
107 struct context;
108
109 typedef int (*descriptor_callback_t)(struct context *ctx,
110                                      struct descriptor *d,
111                                      struct descriptor *last);
112
113 /*
114  * A buffer that contains a block of DMA-able coherent memory used for
115  * storing a portion of a DMA descriptor program.
116  */
117 struct descriptor_buffer {
118         struct list_head list;
119         dma_addr_t buffer_bus;
120         size_t buffer_size;
121         size_t used;
122         struct descriptor buffer[0];
123 };
124
125 struct context {
126         struct fw_ohci *ohci;
127         u32 regs;
128         int total_allocation;
129         bool running;
130         bool flushing;
131
132         /*
133          * List of page-sized buffers for storing DMA descriptors.
134          * Head of list contains buffers in use and tail of list contains
135          * free buffers.
136          */
137         struct list_head buffer_list;
138
139         /*
140          * Pointer to a buffer inside buffer_list that contains the tail
141          * end of the current DMA program.
142          */
143         struct descriptor_buffer *buffer_tail;
144
145         /*
146          * The descriptor containing the branch address of the first
147          * descriptor that has not yet been filled by the device.
148          */
149         struct descriptor *last;
150
151         /*
152          * The last descriptor in the DMA program.  It contains the branch
153          * address that must be updated upon appending a new descriptor.
154          */
155         struct descriptor *prev;
156
157         descriptor_callback_t callback;
158
159         struct tasklet_struct tasklet;
160 };
161
162 #define IT_HEADER_SY(v)          ((v) <<  0)
163 #define IT_HEADER_TCODE(v)       ((v) <<  4)
164 #define IT_HEADER_CHANNEL(v)     ((v) <<  8)
165 #define IT_HEADER_TAG(v)         ((v) << 14)
166 #define IT_HEADER_SPEED(v)       ((v) << 16)
167 #define IT_HEADER_DATA_LENGTH(v) ((v) << 16)
168
169 struct iso_context {
170         struct fw_iso_context base;
171         struct context context;
172         int excess_bytes;
173         void *header;
174         size_t header_length;
175
176         u8 sync;
177         u8 tags;
178 };
179
180 #define CONFIG_ROM_SIZE 1024
181
182 struct fw_ohci {
183         struct fw_card card;
184
185         __iomem char *registers;
186         int node_id;
187         int generation;
188         int request_generation; /* for timestamping incoming requests */
189         unsigned quirks;
190         unsigned int pri_req_max;
191         u32 bus_time;
192         bool is_root;
193         bool csr_state_setclear_abdicate;
194         int n_ir;
195         int n_it;
196         /*
197          * Spinlock for accessing fw_ohci data.  Never call out of
198          * this driver with this lock held.
199          */
200         spinlock_t lock;
201
202         struct mutex phy_reg_mutex;
203
204         void *misc_buffer;
205         dma_addr_t misc_buffer_bus;
206
207         struct ar_context ar_request_ctx;
208         struct ar_context ar_response_ctx;
209         struct context at_request_ctx;
210         struct context at_response_ctx;
211
212         u32 it_context_support;
213         u32 it_context_mask;     /* unoccupied IT contexts */
214         struct iso_context *it_context_list;
215         u64 ir_context_channels; /* unoccupied channels */
216         u32 ir_context_support;
217         u32 ir_context_mask;     /* unoccupied IR contexts */
218         struct iso_context *ir_context_list;
219         u64 mc_channels; /* channels in use by the multichannel IR context */
220         bool mc_allocated;
221
222         __be32    *config_rom;
223         dma_addr_t config_rom_bus;
224         __be32    *next_config_rom;
225         dma_addr_t next_config_rom_bus;
226         __be32     next_header;
227
228         __le32    *self_id_cpu;
229         dma_addr_t self_id_bus;
230         struct work_struct bus_reset_work;
231
232         u32 self_id_buffer[512];
233 };
234
235 static inline struct fw_ohci *fw_ohci(struct fw_card *card)
236 {
237         return container_of(card, struct fw_ohci, card);
238 }
239
240 #define IT_CONTEXT_CYCLE_MATCH_ENABLE   0x80000000
241 #define IR_CONTEXT_BUFFER_FILL          0x80000000
242 #define IR_CONTEXT_ISOCH_HEADER         0x40000000
243 #define IR_CONTEXT_CYCLE_MATCH_ENABLE   0x20000000
244 #define IR_CONTEXT_MULTI_CHANNEL_MODE   0x10000000
245 #define IR_CONTEXT_DUAL_BUFFER_MODE     0x08000000
246
247 #define CONTEXT_RUN     0x8000
248 #define CONTEXT_WAKE    0x1000
249 #define CONTEXT_DEAD    0x0800
250 #define CONTEXT_ACTIVE  0x0400
251
252 #define OHCI1394_MAX_AT_REQ_RETRIES     0xf
253 #define OHCI1394_MAX_AT_RESP_RETRIES    0x2
254 #define OHCI1394_MAX_PHYS_RESP_RETRIES  0x8
255
256 #define OHCI1394_REGISTER_SIZE          0x800
257 #define OHCI1394_PCI_HCI_Control        0x40
258 #define SELF_ID_BUF_SIZE                0x800
259 #define OHCI_TCODE_PHY_PACKET           0x0e
260 #define OHCI_VERSION_1_1                0x010010
261
262 static char ohci_driver_name[] = KBUILD_MODNAME;
263
264 #define PCI_DEVICE_ID_AGERE_FW643       0x5901
265 #define PCI_DEVICE_ID_JMICRON_JMB38X_FW 0x2380
266 #define PCI_DEVICE_ID_TI_TSB12LV22      0x8009
267 #define PCI_VENDOR_ID_PINNACLE_SYSTEMS  0x11bd
268
269 #define QUIRK_CYCLE_TIMER               1
270 #define QUIRK_RESET_PACKET              2
271 #define QUIRK_BE_HEADERS                4
272 #define QUIRK_NO_1394A                  8
273 #define QUIRK_NO_MSI                    16
274
275 /* In case of multiple matches in ohci_quirks[], only the first one is used. */
276 static const struct {
277         unsigned short vendor, device, revision, flags;
278 } ohci_quirks[] = {
279         {PCI_VENDOR_ID_AL, PCI_ANY_ID, PCI_ANY_ID,
280                 QUIRK_CYCLE_TIMER},
281
282         {PCI_VENDOR_ID_APPLE, PCI_DEVICE_ID_APPLE_UNI_N_FW, PCI_ANY_ID,
283                 QUIRK_BE_HEADERS},
284
285         {PCI_VENDOR_ID_ATT, PCI_DEVICE_ID_AGERE_FW643, 6,
286                 QUIRK_NO_MSI},
287
288         {PCI_VENDOR_ID_JMICRON, PCI_DEVICE_ID_JMICRON_JMB38X_FW, PCI_ANY_ID,
289                 QUIRK_NO_MSI},
290
291         {PCI_VENDOR_ID_NEC, PCI_ANY_ID, PCI_ANY_ID,
292                 QUIRK_CYCLE_TIMER},
293
294         {PCI_VENDOR_ID_O2, PCI_ANY_ID, PCI_ANY_ID,
295                 QUIRK_NO_MSI},
296
297         {PCI_VENDOR_ID_RICOH, PCI_ANY_ID, PCI_ANY_ID,
298                 QUIRK_CYCLE_TIMER},
299
300         {PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_TSB12LV22, PCI_ANY_ID,
301                 QUIRK_CYCLE_TIMER | QUIRK_RESET_PACKET | QUIRK_NO_1394A},
302
303         {PCI_VENDOR_ID_TI, PCI_ANY_ID, PCI_ANY_ID,
304                 QUIRK_RESET_PACKET},
305
306         {PCI_VENDOR_ID_VIA, PCI_ANY_ID, PCI_ANY_ID,
307                 QUIRK_CYCLE_TIMER | QUIRK_NO_MSI},
308 };
309
310 /* This overrides anything that was found in ohci_quirks[]. */
311 static int param_quirks;
312 module_param_named(quirks, param_quirks, int, 0644);
313 MODULE_PARM_DESC(quirks, "Chip quirks (default = 0"
314         ", nonatomic cycle timer = "    __stringify(QUIRK_CYCLE_TIMER)
315         ", reset packet generation = "  __stringify(QUIRK_RESET_PACKET)
316         ", AR/selfID endianess = "      __stringify(QUIRK_BE_HEADERS)
317         ", no 1394a enhancements = "    __stringify(QUIRK_NO_1394A)
318         ", disable MSI = "              __stringify(QUIRK_NO_MSI)
319         ")");
320
321 #define OHCI_PARAM_DEBUG_AT_AR          1
322 #define OHCI_PARAM_DEBUG_SELFIDS        2
323 #define OHCI_PARAM_DEBUG_IRQS           4
324 #define OHCI_PARAM_DEBUG_BUSRESETS      8 /* only effective before chip init */
325
326 #ifdef CONFIG_FIREWIRE_OHCI_DEBUG
327
328 static int param_debug;
329 module_param_named(debug, param_debug, int, 0644);
330 MODULE_PARM_DESC(debug, "Verbose logging (default = 0"
331         ", AT/AR events = "     __stringify(OHCI_PARAM_DEBUG_AT_AR)
332         ", self-IDs = "         __stringify(OHCI_PARAM_DEBUG_SELFIDS)
333         ", IRQs = "             __stringify(OHCI_PARAM_DEBUG_IRQS)
334         ", busReset events = "  __stringify(OHCI_PARAM_DEBUG_BUSRESETS)
335         ", or a combination, or all = -1)");
336
337 static void log_irqs(u32 evt)
338 {
339         if (likely(!(param_debug &
340                         (OHCI_PARAM_DEBUG_IRQS | OHCI_PARAM_DEBUG_BUSRESETS))))
341                 return;
342
343         if (!(param_debug & OHCI_PARAM_DEBUG_IRQS) &&
344             !(evt & OHCI1394_busReset))
345                 return;
346
347         fw_notify("IRQ %08x%s%s%s%s%s%s%s%s%s%s%s%s%s%s%s\n", evt,
348             evt & OHCI1394_selfIDComplete       ? " selfID"             : "",
349             evt & OHCI1394_RQPkt                ? " AR_req"             : "",
350             evt & OHCI1394_RSPkt                ? " AR_resp"            : "",
351             evt & OHCI1394_reqTxComplete        ? " AT_req"             : "",
352             evt & OHCI1394_respTxComplete       ? " AT_resp"            : "",
353             evt & OHCI1394_isochRx              ? " IR"                 : "",
354             evt & OHCI1394_isochTx              ? " IT"                 : "",
355             evt & OHCI1394_postedWriteErr       ? " postedWriteErr"     : "",
356             evt & OHCI1394_cycleTooLong         ? " cycleTooLong"       : "",
357             evt & OHCI1394_cycle64Seconds       ? " cycle64Seconds"     : "",
358             evt & OHCI1394_cycleInconsistent    ? " cycleInconsistent"  : "",
359             evt & OHCI1394_regAccessFail        ? " regAccessFail"      : "",
360             evt & OHCI1394_unrecoverableError   ? " unrecoverableError" : "",
361             evt & OHCI1394_busReset             ? " busReset"           : "",
362             evt & ~(OHCI1394_selfIDComplete | OHCI1394_RQPkt |
363                     OHCI1394_RSPkt | OHCI1394_reqTxComplete |
364                     OHCI1394_respTxComplete | OHCI1394_isochRx |
365                     OHCI1394_isochTx | OHCI1394_postedWriteErr |
366                     OHCI1394_cycleTooLong | OHCI1394_cycle64Seconds |
367                     OHCI1394_cycleInconsistent |
368                     OHCI1394_regAccessFail | OHCI1394_busReset)
369                                                 ? " ?"                  : "");
370 }
371
372 static const char *speed[] = {
373         [0] = "S100", [1] = "S200", [2] = "S400",    [3] = "beta",
374 };
375 static const char *power[] = {
376         [0] = "+0W",  [1] = "+15W", [2] = "+30W",    [3] = "+45W",
377         [4] = "-3W",  [5] = " ?W",  [6] = "-3..-6W", [7] = "-3..-10W",
378 };
379 static const char port[] = { '.', '-', 'p', 'c', };
380
381 static char _p(u32 *s, int shift)
382 {
383         return port[*s >> shift & 3];
384 }
385
386 static void log_selfids(int node_id, int generation, int self_id_count, u32 *s)
387 {
388         if (likely(!(param_debug & OHCI_PARAM_DEBUG_SELFIDS)))
389                 return;
390
391         fw_notify("%d selfIDs, generation %d, local node ID %04x\n",
392                   self_id_count, generation, node_id);
393
394         for (; self_id_count--; ++s)
395                 if ((*s & 1 << 23) == 0)
396                         fw_notify("selfID 0: %08x, phy %d [%c%c%c] "
397                             "%s gc=%d %s %s%s%s\n",
398                             *s, *s >> 24 & 63, _p(s, 6), _p(s, 4), _p(s, 2),
399                             speed[*s >> 14 & 3], *s >> 16 & 63,
400                             power[*s >> 8 & 7], *s >> 22 & 1 ? "L" : "",
401                             *s >> 11 & 1 ? "c" : "", *s & 2 ? "i" : "");
402                 else
403                         fw_notify("selfID n: %08x, phy %d [%c%c%c%c%c%c%c%c]\n",
404                             *s, *s >> 24 & 63,
405                             _p(s, 16), _p(s, 14), _p(s, 12), _p(s, 10),
406                             _p(s,  8), _p(s,  6), _p(s,  4), _p(s,  2));
407 }
408
409 static const char *evts[] = {
410         [0x00] = "evt_no_status",       [0x01] = "-reserved-",
411         [0x02] = "evt_long_packet",     [0x03] = "evt_missing_ack",
412         [0x04] = "evt_underrun",        [0x05] = "evt_overrun",
413         [0x06] = "evt_descriptor_read", [0x07] = "evt_data_read",
414         [0x08] = "evt_data_write",      [0x09] = "evt_bus_reset",
415         [0x0a] = "evt_timeout",         [0x0b] = "evt_tcode_err",
416         [0x0c] = "-reserved-",          [0x0d] = "-reserved-",
417         [0x0e] = "evt_unknown",         [0x0f] = "evt_flushed",
418         [0x10] = "-reserved-",          [0x11] = "ack_complete",
419         [0x12] = "ack_pending ",        [0x13] = "-reserved-",
420         [0x14] = "ack_busy_X",          [0x15] = "ack_busy_A",
421         [0x16] = "ack_busy_B",          [0x17] = "-reserved-",
422         [0x18] = "-reserved-",          [0x19] = "-reserved-",
423         [0x1a] = "-reserved-",          [0x1b] = "ack_tardy",
424         [0x1c] = "-reserved-",          [0x1d] = "ack_data_error",
425         [0x1e] = "ack_type_error",      [0x1f] = "-reserved-",
426         [0x20] = "pending/cancelled",
427 };
428 static const char *tcodes[] = {
429         [0x0] = "QW req",               [0x1] = "BW req",
430         [0x2] = "W resp",               [0x3] = "-reserved-",
431         [0x4] = "QR req",               [0x5] = "BR req",
432         [0x6] = "QR resp",              [0x7] = "BR resp",
433         [0x8] = "cycle start",          [0x9] = "Lk req",
434         [0xa] = "async stream packet",  [0xb] = "Lk resp",
435         [0xc] = "-reserved-",           [0xd] = "-reserved-",
436         [0xe] = "link internal",        [0xf] = "-reserved-",
437 };
438
439 static void log_ar_at_event(char dir, int speed, u32 *header, int evt)
440 {
441         int tcode = header[0] >> 4 & 0xf;
442         char specific[12];
443
444         if (likely(!(param_debug & OHCI_PARAM_DEBUG_AT_AR)))
445                 return;
446
447         if (unlikely(evt >= ARRAY_SIZE(evts)))
448                         evt = 0x1f;
449
450         if (evt == OHCI1394_evt_bus_reset) {
451                 fw_notify("A%c evt_bus_reset, generation %d\n",
452                     dir, (header[2] >> 16) & 0xff);
453                 return;
454         }
455
456         switch (tcode) {
457         case 0x0: case 0x6: case 0x8:
458                 snprintf(specific, sizeof(specific), " = %08x",
459                          be32_to_cpu((__force __be32)header[3]));
460                 break;
461         case 0x1: case 0x5: case 0x7: case 0x9: case 0xb:
462                 snprintf(specific, sizeof(specific), " %x,%x",
463                          header[3] >> 16, header[3] & 0xffff);
464                 break;
465         default:
466                 specific[0] = '\0';
467         }
468
469         switch (tcode) {
470         case 0xa:
471                 fw_notify("A%c %s, %s\n", dir, evts[evt], tcodes[tcode]);
472                 break;
473         case 0xe:
474                 fw_notify("A%c %s, PHY %08x %08x\n",
475                           dir, evts[evt], header[1], header[2]);
476                 break;
477         case 0x0: case 0x1: case 0x4: case 0x5: case 0x9:
478                 fw_notify("A%c spd %x tl %02x, "
479                     "%04x -> %04x, %s, "
480                     "%s, %04x%08x%s\n",
481                     dir, speed, header[0] >> 10 & 0x3f,
482                     header[1] >> 16, header[0] >> 16, evts[evt],
483                     tcodes[tcode], header[1] & 0xffff, header[2], specific);
484                 break;
485         default:
486                 fw_notify("A%c spd %x tl %02x, "
487                     "%04x -> %04x, %s, "
488                     "%s%s\n",
489                     dir, speed, header[0] >> 10 & 0x3f,
490                     header[1] >> 16, header[0] >> 16, evts[evt],
491                     tcodes[tcode], specific);
492         }
493 }
494
495 #else
496
497 #define param_debug 0
498 static inline void log_irqs(u32 evt) {}
499 static inline void log_selfids(int node_id, int generation, int self_id_count, u32 *s) {}
500 static inline void log_ar_at_event(char dir, int speed, u32 *header, int evt) {}
501
502 #endif /* CONFIG_FIREWIRE_OHCI_DEBUG */
503
504 static inline void reg_write(const struct fw_ohci *ohci, int offset, u32 data)
505 {
506         writel(data, ohci->registers + offset);
507 }
508
509 static inline u32 reg_read(const struct fw_ohci *ohci, int offset)
510 {
511         return readl(ohci->registers + offset);
512 }
513
514 static inline void flush_writes(const struct fw_ohci *ohci)
515 {
516         /* Do a dummy read to flush writes. */
517         reg_read(ohci, OHCI1394_Version);
518 }
519
520 /*
521  * Beware!  read_phy_reg(), write_phy_reg(), update_phy_reg(), and
522  * read_paged_phy_reg() require the caller to hold ohci->phy_reg_mutex.
523  * In other words, only use ohci_read_phy_reg() and ohci_update_phy_reg()
524  * directly.  Exceptions are intrinsically serialized contexts like pci_probe.
525  */
526 static int read_phy_reg(struct fw_ohci *ohci, int addr)
527 {
528         u32 val;
529         int i;
530
531         reg_write(ohci, OHCI1394_PhyControl, OHCI1394_PhyControl_Read(addr));
532         for (i = 0; i < 3 + 100; i++) {
533                 val = reg_read(ohci, OHCI1394_PhyControl);
534                 if (!~val)
535                         return -ENODEV; /* Card was ejected. */
536
537                 if (val & OHCI1394_PhyControl_ReadDone)
538                         return OHCI1394_PhyControl_ReadData(val);
539
540                 /*
541                  * Try a few times without waiting.  Sleeping is necessary
542                  * only when the link/PHY interface is busy.
543                  */
544                 if (i >= 3)
545                         msleep(1);
546         }
547         fw_error("failed to read phy reg\n");
548
549         return -EBUSY;
550 }
551
552 static int write_phy_reg(const struct fw_ohci *ohci, int addr, u32 val)
553 {
554         int i;
555
556         reg_write(ohci, OHCI1394_PhyControl,
557                   OHCI1394_PhyControl_Write(addr, val));
558         for (i = 0; i < 3 + 100; i++) {
559                 val = reg_read(ohci, OHCI1394_PhyControl);
560                 if (!~val)
561                         return -ENODEV; /* Card was ejected. */
562
563                 if (!(val & OHCI1394_PhyControl_WritePending))
564                         return 0;
565
566                 if (i >= 3)
567                         msleep(1);
568         }
569         fw_error("failed to write phy reg\n");
570
571         return -EBUSY;
572 }
573
574 static int update_phy_reg(struct fw_ohci *ohci, int addr,
575                           int clear_bits, int set_bits)
576 {
577         int ret = read_phy_reg(ohci, addr);
578         if (ret < 0)
579                 return ret;
580
581         /*
582          * The interrupt status bits are cleared by writing a one bit.
583          * Avoid clearing them unless explicitly requested in set_bits.
584          */
585         if (addr == 5)
586                 clear_bits |= PHY_INT_STATUS_BITS;
587
588         return write_phy_reg(ohci, addr, (ret & ~clear_bits) | set_bits);
589 }
590
591 static int read_paged_phy_reg(struct fw_ohci *ohci, int page, int addr)
592 {
593         int ret;
594
595         ret = update_phy_reg(ohci, 7, PHY_PAGE_SELECT, page << 5);
596         if (ret < 0)
597                 return ret;
598
599         return read_phy_reg(ohci, addr);
600 }
601
602 static int ohci_read_phy_reg(struct fw_card *card, int addr)
603 {
604         struct fw_ohci *ohci = fw_ohci(card);
605         int ret;
606
607         mutex_lock(&ohci->phy_reg_mutex);
608         ret = read_phy_reg(ohci, addr);
609         mutex_unlock(&ohci->phy_reg_mutex);
610
611         return ret;
612 }
613
614 static int ohci_update_phy_reg(struct fw_card *card, int addr,
615                                int clear_bits, int set_bits)
616 {
617         struct fw_ohci *ohci = fw_ohci(card);
618         int ret;
619
620         mutex_lock(&ohci->phy_reg_mutex);
621         ret = update_phy_reg(ohci, addr, clear_bits, set_bits);
622         mutex_unlock(&ohci->phy_reg_mutex);
623
624         return ret;
625 }
626
627 static inline dma_addr_t ar_buffer_bus(struct ar_context *ctx, unsigned int i)
628 {
629         return page_private(ctx->pages[i]);
630 }
631
632 static void ar_context_link_page(struct ar_context *ctx, unsigned int index)
633 {
634         struct descriptor *d;
635
636         d = &ctx->descriptors[index];
637         d->branch_address  &= cpu_to_le32(~0xf);
638         d->res_count       =  cpu_to_le16(PAGE_SIZE);
639         d->transfer_status =  0;
640
641         wmb(); /* finish init of new descriptors before branch_address update */
642         d = &ctx->descriptors[ctx->last_buffer_index];
643         d->branch_address  |= cpu_to_le32(1);
644
645         ctx->last_buffer_index = index;
646
647         reg_write(ctx->ohci, CONTROL_SET(ctx->regs), CONTEXT_WAKE);
648 }
649
650 static void ar_context_release(struct ar_context *ctx)
651 {
652         unsigned int i;
653
654         if (ctx->buffer)
655                 vm_unmap_ram(ctx->buffer, AR_BUFFERS + AR_WRAPAROUND_PAGES);
656
657         for (i = 0; i < AR_BUFFERS; i++)
658                 if (ctx->pages[i]) {
659                         dma_unmap_page(ctx->ohci->card.device,
660                                        ar_buffer_bus(ctx, i),
661                                        PAGE_SIZE, DMA_FROM_DEVICE);
662                         __free_page(ctx->pages[i]);
663                 }
664 }
665
666 static void ar_context_abort(struct ar_context *ctx, const char *error_msg)
667 {
668         if (reg_read(ctx->ohci, CONTROL_CLEAR(ctx->regs)) & CONTEXT_RUN) {
669                 reg_write(ctx->ohci, CONTROL_CLEAR(ctx->regs), CONTEXT_RUN);
670                 flush_writes(ctx->ohci);
671
672                 fw_error("AR error: %s; DMA stopped\n", error_msg);
673         }
674         /* FIXME: restart? */
675 }
676
677 static inline unsigned int ar_next_buffer_index(unsigned int index)
678 {
679         return (index + 1) % AR_BUFFERS;
680 }
681
682 static inline unsigned int ar_prev_buffer_index(unsigned int index)
683 {
684         return (index - 1 + AR_BUFFERS) % AR_BUFFERS;
685 }
686
687 static inline unsigned int ar_first_buffer_index(struct ar_context *ctx)
688 {
689         return ar_next_buffer_index(ctx->last_buffer_index);
690 }
691
692 /*
693  * We search for the buffer that contains the last AR packet DMA data written
694  * by the controller.
695  */
696 static unsigned int ar_search_last_active_buffer(struct ar_context *ctx,
697                                                  unsigned int *buffer_offset)
698 {
699         unsigned int i, next_i, last = ctx->last_buffer_index;
700         __le16 res_count, next_res_count;
701
702         i = ar_first_buffer_index(ctx);
703         res_count = ACCESS_ONCE(ctx->descriptors[i].res_count);
704
705         /* A buffer that is not yet completely filled must be the last one. */
706         while (i != last && res_count == 0) {
707
708                 /* Peek at the next descriptor. */
709                 next_i = ar_next_buffer_index(i);
710                 rmb(); /* read descriptors in order */
711                 next_res_count = ACCESS_ONCE(
712                                 ctx->descriptors[next_i].res_count);
713                 /*
714                  * If the next descriptor is still empty, we must stop at this
715                  * descriptor.
716                  */
717                 if (next_res_count == cpu_to_le16(PAGE_SIZE)) {
718                         /*
719                          * The exception is when the DMA data for one packet is
720                          * split over three buffers; in this case, the middle
721                          * buffer's descriptor might be never updated by the
722                          * controller and look still empty, and we have to peek
723                          * at the third one.
724                          */
725                         if (MAX_AR_PACKET_SIZE > PAGE_SIZE && i != last) {
726                                 next_i = ar_next_buffer_index(next_i);
727                                 rmb();
728                                 next_res_count = ACCESS_ONCE(
729                                         ctx->descriptors[next_i].res_count);
730                                 if (next_res_count != cpu_to_le16(PAGE_SIZE))
731                                         goto next_buffer_is_active;
732                         }
733
734                         break;
735                 }
736
737 next_buffer_is_active:
738                 i = next_i;
739                 res_count = next_res_count;
740         }
741
742         rmb(); /* read res_count before the DMA data */
743
744         *buffer_offset = PAGE_SIZE - le16_to_cpu(res_count);
745         if (*buffer_offset > PAGE_SIZE) {
746                 *buffer_offset = 0;
747                 ar_context_abort(ctx, "corrupted descriptor");
748         }
749
750         return i;
751 }
752
753 static void ar_sync_buffers_for_cpu(struct ar_context *ctx,
754                                     unsigned int end_buffer_index,
755                                     unsigned int end_buffer_offset)
756 {
757         unsigned int i;
758
759         i = ar_first_buffer_index(ctx);
760         while (i != end_buffer_index) {
761                 dma_sync_single_for_cpu(ctx->ohci->card.device,
762                                         ar_buffer_bus(ctx, i),
763                                         PAGE_SIZE, DMA_FROM_DEVICE);
764                 i = ar_next_buffer_index(i);
765         }
766         if (end_buffer_offset > 0)
767                 dma_sync_single_for_cpu(ctx->ohci->card.device,
768                                         ar_buffer_bus(ctx, i),
769                                         end_buffer_offset, DMA_FROM_DEVICE);
770 }
771
772 #if defined(CONFIG_PPC_PMAC) && defined(CONFIG_PPC32)
773 #define cond_le32_to_cpu(v) \
774         (ohci->quirks & QUIRK_BE_HEADERS ? (__force __u32)(v) : le32_to_cpu(v))
775 #else
776 #define cond_le32_to_cpu(v) le32_to_cpu(v)
777 #endif
778
779 static __le32 *handle_ar_packet(struct ar_context *ctx, __le32 *buffer)
780 {
781         struct fw_ohci *ohci = ctx->ohci;
782         struct fw_packet p;
783         u32 status, length, tcode;
784         int evt;
785
786         p.header[0] = cond_le32_to_cpu(buffer[0]);
787         p.header[1] = cond_le32_to_cpu(buffer[1]);
788         p.header[2] = cond_le32_to_cpu(buffer[2]);
789
790         tcode = (p.header[0] >> 4) & 0x0f;
791         switch (tcode) {
792         case TCODE_WRITE_QUADLET_REQUEST:
793         case TCODE_READ_QUADLET_RESPONSE:
794                 p.header[3] = (__force __u32) buffer[3];
795                 p.header_length = 16;
796                 p.payload_length = 0;
797                 break;
798
799         case TCODE_READ_BLOCK_REQUEST :
800                 p.header[3] = cond_le32_to_cpu(buffer[3]);
801                 p.header_length = 16;
802                 p.payload_length = 0;
803                 break;
804
805         case TCODE_WRITE_BLOCK_REQUEST:
806         case TCODE_READ_BLOCK_RESPONSE:
807         case TCODE_LOCK_REQUEST:
808         case TCODE_LOCK_RESPONSE:
809                 p.header[3] = cond_le32_to_cpu(buffer[3]);
810                 p.header_length = 16;
811                 p.payload_length = p.header[3] >> 16;
812                 if (p.payload_length > MAX_ASYNC_PAYLOAD) {
813                         ar_context_abort(ctx, "invalid packet length");
814                         return NULL;
815                 }
816                 break;
817
818         case TCODE_WRITE_RESPONSE:
819         case TCODE_READ_QUADLET_REQUEST:
820         case OHCI_TCODE_PHY_PACKET:
821                 p.header_length = 12;
822                 p.payload_length = 0;
823                 break;
824
825         default:
826                 ar_context_abort(ctx, "invalid tcode");
827                 return NULL;
828         }
829
830         p.payload = (void *) buffer + p.header_length;
831
832         /* FIXME: What to do about evt_* errors? */
833         length = (p.header_length + p.payload_length + 3) / 4;
834         status = cond_le32_to_cpu(buffer[length]);
835         evt    = (status >> 16) & 0x1f;
836
837         p.ack        = evt - 16;
838         p.speed      = (status >> 21) & 0x7;
839         p.timestamp  = status & 0xffff;
840         p.generation = ohci->request_generation;
841
842         log_ar_at_event('R', p.speed, p.header, evt);
843
844         /*
845          * Several controllers, notably from NEC and VIA, forget to
846          * write ack_complete status at PHY packet reception.
847          */
848         if (evt == OHCI1394_evt_no_status &&
849             (p.header[0] & 0xff) == (OHCI1394_phy_tcode << 4))
850                 p.ack = ACK_COMPLETE;
851
852         /*
853          * The OHCI bus reset handler synthesizes a PHY packet with
854          * the new generation number when a bus reset happens (see
855          * section 8.4.2.3).  This helps us determine when a request
856          * was received and make sure we send the response in the same
857          * generation.  We only need this for requests; for responses
858          * we use the unique tlabel for finding the matching
859          * request.
860          *
861          * Alas some chips sometimes emit bus reset packets with a
862          * wrong generation.  We set the correct generation for these
863          * at a slightly incorrect time (in bus_reset_work).
864          */
865         if (evt == OHCI1394_evt_bus_reset) {
866                 if (!(ohci->quirks & QUIRK_RESET_PACKET))
867                         ohci->request_generation = (p.header[2] >> 16) & 0xff;
868         } else if (ctx == &ohci->ar_request_ctx) {
869                 fw_core_handle_request(&ohci->card, &p);
870         } else {
871                 fw_core_handle_response(&ohci->card, &p);
872         }
873
874         return buffer + length + 1;
875 }
876
877 static void *handle_ar_packets(struct ar_context *ctx, void *p, void *end)
878 {
879         void *next;
880
881         while (p < end) {
882                 next = handle_ar_packet(ctx, p);
883                 if (!next)
884                         return p;
885                 p = next;
886         }
887
888         return p;
889 }
890
891 static void ar_recycle_buffers(struct ar_context *ctx, unsigned int end_buffer)
892 {
893         unsigned int i;
894
895         i = ar_first_buffer_index(ctx);
896         while (i != end_buffer) {
897                 dma_sync_single_for_device(ctx->ohci->card.device,
898                                            ar_buffer_bus(ctx, i),
899                                            PAGE_SIZE, DMA_FROM_DEVICE);
900                 ar_context_link_page(ctx, i);
901                 i = ar_next_buffer_index(i);
902         }
903 }
904
905 static void ar_context_tasklet(unsigned long data)
906 {
907         struct ar_context *ctx = (struct ar_context *)data;
908         unsigned int end_buffer_index, end_buffer_offset;
909         void *p, *end;
910
911         p = ctx->pointer;
912         if (!p)
913                 return;
914
915         end_buffer_index = ar_search_last_active_buffer(ctx,
916                                                         &end_buffer_offset);
917         ar_sync_buffers_for_cpu(ctx, end_buffer_index, end_buffer_offset);
918         end = ctx->buffer + end_buffer_index * PAGE_SIZE + end_buffer_offset;
919
920         if (end_buffer_index < ar_first_buffer_index(ctx)) {
921                 /*
922                  * The filled part of the overall buffer wraps around; handle
923                  * all packets up to the buffer end here.  If the last packet
924                  * wraps around, its tail will be visible after the buffer end
925                  * because the buffer start pages are mapped there again.
926                  */
927                 void *buffer_end = ctx->buffer + AR_BUFFERS * PAGE_SIZE;
928                 p = handle_ar_packets(ctx, p, buffer_end);
929                 if (p < buffer_end)
930                         goto error;
931                 /* adjust p to point back into the actual buffer */
932                 p -= AR_BUFFERS * PAGE_SIZE;
933         }
934
935         p = handle_ar_packets(ctx, p, end);
936         if (p != end) {
937                 if (p > end)
938                         ar_context_abort(ctx, "inconsistent descriptor");
939                 goto error;
940         }
941
942         ctx->pointer = p;
943         ar_recycle_buffers(ctx, end_buffer_index);
944
945         return;
946
947 error:
948         ctx->pointer = NULL;
949 }
950
951 static int ar_context_init(struct ar_context *ctx, struct fw_ohci *ohci,
952                            unsigned int descriptors_offset, u32 regs)
953 {
954         unsigned int i;
955         dma_addr_t dma_addr;
956         struct page *pages[AR_BUFFERS + AR_WRAPAROUND_PAGES];
957         struct descriptor *d;
958
959         ctx->regs        = regs;
960         ctx->ohci        = ohci;
961         tasklet_init(&ctx->tasklet, ar_context_tasklet, (unsigned long)ctx);
962
963         for (i = 0; i < AR_BUFFERS; i++) {
964                 ctx->pages[i] = alloc_page(GFP_KERNEL | GFP_DMA32);
965                 if (!ctx->pages[i])
966                         goto out_of_memory;
967                 dma_addr = dma_map_page(ohci->card.device, ctx->pages[i],
968                                         0, PAGE_SIZE, DMA_FROM_DEVICE);
969                 if (dma_mapping_error(ohci->card.device, dma_addr)) {
970                         __free_page(ctx->pages[i]);
971                         ctx->pages[i] = NULL;
972                         goto out_of_memory;
973                 }
974                 set_page_private(ctx->pages[i], dma_addr);
975         }
976
977         for (i = 0; i < AR_BUFFERS; i++)
978                 pages[i]              = ctx->pages[i];
979         for (i = 0; i < AR_WRAPAROUND_PAGES; i++)
980                 pages[AR_BUFFERS + i] = ctx->pages[i];
981         ctx->buffer = vm_map_ram(pages, AR_BUFFERS + AR_WRAPAROUND_PAGES,
982                                  -1, PAGE_KERNEL);
983         if (!ctx->buffer)
984                 goto out_of_memory;
985
986         ctx->descriptors     = ohci->misc_buffer     + descriptors_offset;
987         ctx->descriptors_bus = ohci->misc_buffer_bus + descriptors_offset;
988
989         for (i = 0; i < AR_BUFFERS; i++) {
990                 d = &ctx->descriptors[i];
991                 d->req_count      = cpu_to_le16(PAGE_SIZE);
992                 d->control        = cpu_to_le16(DESCRIPTOR_INPUT_MORE |
993                                                 DESCRIPTOR_STATUS |
994                                                 DESCRIPTOR_BRANCH_ALWAYS);
995                 d->data_address   = cpu_to_le32(ar_buffer_bus(ctx, i));
996                 d->branch_address = cpu_to_le32(ctx->descriptors_bus +
997                         ar_next_buffer_index(i) * sizeof(struct descriptor));
998         }
999
1000         return 0;
1001
1002 out_of_memory:
1003         ar_context_release(ctx);
1004
1005         return -ENOMEM;
1006 }
1007
1008 static void ar_context_run(struct ar_context *ctx)
1009 {
1010         unsigned int i;
1011
1012         for (i = 0; i < AR_BUFFERS; i++)
1013                 ar_context_link_page(ctx, i);
1014
1015         ctx->pointer = ctx->buffer;
1016
1017         reg_write(ctx->ohci, COMMAND_PTR(ctx->regs), ctx->descriptors_bus | 1);
1018         reg_write(ctx->ohci, CONTROL_SET(ctx->regs), CONTEXT_RUN);
1019 }
1020
1021 static struct descriptor *find_branch_descriptor(struct descriptor *d, int z)
1022 {
1023         __le16 branch;
1024
1025         branch = d->control & cpu_to_le16(DESCRIPTOR_BRANCH_ALWAYS);
1026
1027         /* figure out which descriptor the branch address goes in */
1028         if (z == 2 && branch == cpu_to_le16(DESCRIPTOR_BRANCH_ALWAYS))
1029                 return d;
1030         else
1031                 return d + z - 1;
1032 }
1033
1034 static void context_tasklet(unsigned long data)
1035 {
1036         struct context *ctx = (struct context *) data;
1037         struct descriptor *d, *last;
1038         u32 address;
1039         int z;
1040         struct descriptor_buffer *desc;
1041
1042         desc = list_entry(ctx->buffer_list.next,
1043                         struct descriptor_buffer, list);
1044         last = ctx->last;
1045         while (last->branch_address != 0) {
1046                 struct descriptor_buffer *old_desc = desc;
1047                 address = le32_to_cpu(last->branch_address);
1048                 z = address & 0xf;
1049                 address &= ~0xf;
1050
1051                 /* If the branch address points to a buffer outside of the
1052                  * current buffer, advance to the next buffer. */
1053                 if (address < desc->buffer_bus ||
1054                                 address >= desc->buffer_bus + desc->used)
1055                         desc = list_entry(desc->list.next,
1056                                         struct descriptor_buffer, list);
1057                 d = desc->buffer + (address - desc->buffer_bus) / sizeof(*d);
1058                 last = find_branch_descriptor(d, z);
1059
1060                 if (!ctx->callback(ctx, d, last))
1061                         break;
1062
1063                 if (old_desc != desc) {
1064                         /* If we've advanced to the next buffer, move the
1065                          * previous buffer to the free list. */
1066                         unsigned long flags;
1067                         old_desc->used = 0;
1068                         spin_lock_irqsave(&ctx->ohci->lock, flags);
1069                         list_move_tail(&old_desc->list, &ctx->buffer_list);
1070                         spin_unlock_irqrestore(&ctx->ohci->lock, flags);
1071                 }
1072                 ctx->last = last;
1073         }
1074 }
1075
1076 /*
1077  * Allocate a new buffer and add it to the list of free buffers for this
1078  * context.  Must be called with ohci->lock held.
1079  */
1080 static int context_add_buffer(struct context *ctx)
1081 {
1082         struct descriptor_buffer *desc;
1083         dma_addr_t uninitialized_var(bus_addr);
1084         int offset;
1085
1086         /*
1087          * 16MB of descriptors should be far more than enough for any DMA
1088          * program.  This will catch run-away userspace or DoS attacks.
1089          */
1090         if (ctx->total_allocation >= 16*1024*1024)
1091                 return -ENOMEM;
1092
1093         desc = dma_alloc_coherent(ctx->ohci->card.device, PAGE_SIZE,
1094                         &bus_addr, GFP_ATOMIC);
1095         if (!desc)
1096                 return -ENOMEM;
1097
1098         offset = (void *)&desc->buffer - (void *)desc;
1099         desc->buffer_size = PAGE_SIZE - offset;
1100         desc->buffer_bus = bus_addr + offset;
1101         desc->used = 0;
1102
1103         list_add_tail(&desc->list, &ctx->buffer_list);
1104         ctx->total_allocation += PAGE_SIZE;
1105
1106         return 0;
1107 }
1108
1109 static int context_init(struct context *ctx, struct fw_ohci *ohci,
1110                         u32 regs, descriptor_callback_t callback)
1111 {
1112         ctx->ohci = ohci;
1113         ctx->regs = regs;
1114         ctx->total_allocation = 0;
1115
1116         INIT_LIST_HEAD(&ctx->buffer_list);
1117         if (context_add_buffer(ctx) < 0)
1118                 return -ENOMEM;
1119
1120         ctx->buffer_tail = list_entry(ctx->buffer_list.next,
1121                         struct descriptor_buffer, list);
1122
1123         tasklet_init(&ctx->tasklet, context_tasklet, (unsigned long)ctx);
1124         ctx->callback = callback;
1125
1126         /*
1127          * We put a dummy descriptor in the buffer that has a NULL
1128          * branch address and looks like it's been sent.  That way we
1129          * have a descriptor to append DMA programs to.
1130          */
1131         memset(ctx->buffer_tail->buffer, 0, sizeof(*ctx->buffer_tail->buffer));
1132         ctx->buffer_tail->buffer->control = cpu_to_le16(DESCRIPTOR_OUTPUT_LAST);
1133         ctx->buffer_tail->buffer->transfer_status = cpu_to_le16(0x8011);
1134         ctx->buffer_tail->used += sizeof(*ctx->buffer_tail->buffer);
1135         ctx->last = ctx->buffer_tail->buffer;
1136         ctx->prev = ctx->buffer_tail->buffer;
1137
1138         return 0;
1139 }
1140
1141 static void context_release(struct context *ctx)
1142 {
1143         struct fw_card *card = &ctx->ohci->card;
1144         struct descriptor_buffer *desc, *tmp;
1145
1146         list_for_each_entry_safe(desc, tmp, &ctx->buffer_list, list)
1147                 dma_free_coherent(card->device, PAGE_SIZE, desc,
1148                         desc->buffer_bus -
1149                         ((void *)&desc->buffer - (void *)desc));
1150 }
1151
1152 /* Must be called with ohci->lock held */
1153 static struct descriptor *context_get_descriptors(struct context *ctx,
1154                                                   int z, dma_addr_t *d_bus)
1155 {
1156         struct descriptor *d = NULL;
1157         struct descriptor_buffer *desc = ctx->buffer_tail;
1158
1159         if (z * sizeof(*d) > desc->buffer_size)
1160                 return NULL;
1161
1162         if (z * sizeof(*d) > desc->buffer_size - desc->used) {
1163                 /* No room for the descriptor in this buffer, so advance to the
1164                  * next one. */
1165
1166                 if (desc->list.next == &ctx->buffer_list) {
1167                         /* If there is no free buffer next in the list,
1168                          * allocate one. */
1169                         if (context_add_buffer(ctx) < 0)
1170                                 return NULL;
1171                 }
1172                 desc = list_entry(desc->list.next,
1173                                 struct descriptor_buffer, list);
1174                 ctx->buffer_tail = desc;
1175         }
1176
1177         d = desc->buffer + desc->used / sizeof(*d);
1178         memset(d, 0, z * sizeof(*d));
1179         *d_bus = desc->buffer_bus + desc->used;
1180
1181         return d;
1182 }
1183
1184 static void context_run(struct context *ctx, u32 extra)
1185 {
1186         struct fw_ohci *ohci = ctx->ohci;
1187
1188         reg_write(ohci, COMMAND_PTR(ctx->regs),
1189                   le32_to_cpu(ctx->last->branch_address));
1190         reg_write(ohci, CONTROL_CLEAR(ctx->regs), ~0);
1191         reg_write(ohci, CONTROL_SET(ctx->regs), CONTEXT_RUN | extra);
1192         ctx->running = true;
1193         flush_writes(ohci);
1194 }
1195
1196 static void context_append(struct context *ctx,
1197                            struct descriptor *d, int z, int extra)
1198 {
1199         dma_addr_t d_bus;
1200         struct descriptor_buffer *desc = ctx->buffer_tail;
1201
1202         d_bus = desc->buffer_bus + (d - desc->buffer) * sizeof(*d);
1203
1204         desc->used += (z + extra) * sizeof(*d);
1205
1206         wmb(); /* finish init of new descriptors before branch_address update */
1207         ctx->prev->branch_address = cpu_to_le32(d_bus | z);
1208         ctx->prev = find_branch_descriptor(d, z);
1209 }
1210
1211 static void context_stop(struct context *ctx)
1212 {
1213         u32 reg;
1214         int i;
1215
1216         reg_write(ctx->ohci, CONTROL_CLEAR(ctx->regs), CONTEXT_RUN);
1217         ctx->running = false;
1218
1219         for (i = 0; i < 1000; i++) {
1220                 reg = reg_read(ctx->ohci, CONTROL_SET(ctx->regs));
1221                 if ((reg & CONTEXT_ACTIVE) == 0)
1222                         return;
1223
1224                 if (i)
1225                         udelay(10);
1226         }
1227         fw_error("Error: DMA context still active (0x%08x)\n", reg);
1228 }
1229
1230 struct driver_data {
1231         u8 inline_data[8];
1232         struct fw_packet *packet;
1233 };
1234
1235 /*
1236  * This function apppends a packet to the DMA queue for transmission.
1237  * Must always be called with the ochi->lock held to ensure proper
1238  * generation handling and locking around packet queue manipulation.
1239  */
1240 static int at_context_queue_packet(struct context *ctx,
1241                                    struct fw_packet *packet)
1242 {
1243         struct fw_ohci *ohci = ctx->ohci;
1244         dma_addr_t d_bus, uninitialized_var(payload_bus);
1245         struct driver_data *driver_data;
1246         struct descriptor *d, *last;
1247         __le32 *header;
1248         int z, tcode;
1249
1250         d = context_get_descriptors(ctx, 4, &d_bus);
1251         if (d == NULL) {
1252                 packet->ack = RCODE_SEND_ERROR;
1253                 return -1;
1254         }
1255
1256         d[0].control   = cpu_to_le16(DESCRIPTOR_KEY_IMMEDIATE);
1257         d[0].res_count = cpu_to_le16(packet->timestamp);
1258
1259         /*
1260          * The DMA format for asyncronous link packets is different
1261          * from the IEEE1394 layout, so shift the fields around
1262          * accordingly.
1263          */
1264
1265         tcode = (packet->header[0] >> 4) & 0x0f;
1266         header = (__le32 *) &d[1];
1267         switch (tcode) {
1268         case TCODE_WRITE_QUADLET_REQUEST:
1269         case TCODE_WRITE_BLOCK_REQUEST:
1270         case TCODE_WRITE_RESPONSE:
1271         case TCODE_READ_QUADLET_REQUEST:
1272         case TCODE_READ_BLOCK_REQUEST:
1273         case TCODE_READ_QUADLET_RESPONSE:
1274         case TCODE_READ_BLOCK_RESPONSE:
1275         case TCODE_LOCK_REQUEST:
1276         case TCODE_LOCK_RESPONSE:
1277                 header[0] = cpu_to_le32((packet->header[0] & 0xffff) |
1278                                         (packet->speed << 16));
1279                 header[1] = cpu_to_le32((packet->header[1] & 0xffff) |
1280                                         (packet->header[0] & 0xffff0000));
1281                 header[2] = cpu_to_le32(packet->header[2]);
1282
1283                 if (TCODE_IS_BLOCK_PACKET(tcode))
1284                         header[3] = cpu_to_le32(packet->header[3]);
1285                 else
1286                         header[3] = (__force __le32) packet->header[3];
1287
1288                 d[0].req_count = cpu_to_le16(packet->header_length);
1289                 break;
1290
1291         case TCODE_LINK_INTERNAL:
1292                 header[0] = cpu_to_le32((OHCI1394_phy_tcode << 4) |
1293                                         (packet->speed << 16));
1294                 header[1] = cpu_to_le32(packet->header[1]);
1295                 header[2] = cpu_to_le32(packet->header[2]);
1296                 d[0].req_count = cpu_to_le16(12);
1297
1298                 if (is_ping_packet(&packet->header[1]))
1299                         d[0].control |= cpu_to_le16(DESCRIPTOR_PING);
1300                 break;
1301
1302         case TCODE_STREAM_DATA:
1303                 header[0] = cpu_to_le32((packet->header[0] & 0xffff) |
1304                                         (packet->speed << 16));
1305                 header[1] = cpu_to_le32(packet->header[0] & 0xffff0000);
1306                 d[0].req_count = cpu_to_le16(8);
1307                 break;
1308
1309         default:
1310                 /* BUG(); */
1311                 packet->ack = RCODE_SEND_ERROR;
1312                 return -1;
1313         }
1314
1315         BUILD_BUG_ON(sizeof(struct driver_data) > sizeof(struct descriptor));
1316         driver_data = (struct driver_data *) &d[3];
1317         driver_data->packet = packet;
1318         packet->driver_data = driver_data;
1319
1320         if (packet->payload_length > 0) {
1321                 if (packet->payload_length > sizeof(driver_data->inline_data)) {
1322                         payload_bus = dma_map_single(ohci->card.device,
1323                                                      packet->payload,
1324                                                      packet->payload_length,
1325                                                      DMA_TO_DEVICE);
1326                         if (dma_mapping_error(ohci->card.device, payload_bus)) {
1327                                 packet->ack = RCODE_SEND_ERROR;
1328                                 return -1;
1329                         }
1330                         packet->payload_bus     = payload_bus;
1331                         packet->payload_mapped  = true;
1332                 } else {
1333                         memcpy(driver_data->inline_data, packet->payload,
1334                                packet->payload_length);
1335                         payload_bus = d_bus + 3 * sizeof(*d);
1336                 }
1337
1338                 d[2].req_count    = cpu_to_le16(packet->payload_length);
1339                 d[2].data_address = cpu_to_le32(payload_bus);
1340                 last = &d[2];
1341                 z = 3;
1342         } else {
1343                 last = &d[0];
1344                 z = 2;
1345         }
1346
1347         last->control |= cpu_to_le16(DESCRIPTOR_OUTPUT_LAST |
1348                                      DESCRIPTOR_IRQ_ALWAYS |
1349                                      DESCRIPTOR_BRANCH_ALWAYS);
1350
1351         /* FIXME: Document how the locking works. */
1352         if (ohci->generation != packet->generation) {
1353                 if (packet->payload_mapped)
1354                         dma_unmap_single(ohci->card.device, payload_bus,
1355                                          packet->payload_length, DMA_TO_DEVICE);
1356                 packet->ack = RCODE_GENERATION;
1357                 return -1;
1358         }
1359
1360         context_append(ctx, d, z, 4 - z);
1361
1362         if (ctx->running)
1363                 reg_write(ohci, CONTROL_SET(ctx->regs), CONTEXT_WAKE);
1364         else
1365                 context_run(ctx, 0);
1366
1367         return 0;
1368 }
1369
1370 static void at_context_flush(struct context *ctx)
1371 {
1372         tasklet_disable(&ctx->tasklet);
1373
1374         ctx->flushing = true;
1375         context_tasklet((unsigned long)ctx);
1376         ctx->flushing = false;
1377
1378         tasklet_enable(&ctx->tasklet);
1379 }
1380
1381 static int handle_at_packet(struct context *context,
1382                             struct descriptor *d,
1383                             struct descriptor *last)
1384 {
1385         struct driver_data *driver_data;
1386         struct fw_packet *packet;
1387         struct fw_ohci *ohci = context->ohci;
1388         int evt;
1389
1390         if (last->transfer_status == 0 && !context->flushing)
1391                 /* This descriptor isn't done yet, stop iteration. */
1392                 return 0;
1393
1394         driver_data = (struct driver_data *) &d[3];
1395         packet = driver_data->packet;
1396         if (packet == NULL)
1397                 /* This packet was cancelled, just continue. */
1398                 return 1;
1399
1400         if (packet->payload_mapped)
1401                 dma_unmap_single(ohci->card.device, packet->payload_bus,
1402                                  packet->payload_length, DMA_TO_DEVICE);
1403
1404         evt = le16_to_cpu(last->transfer_status) & 0x1f;
1405         packet->timestamp = le16_to_cpu(last->res_count);
1406
1407         log_ar_at_event('T', packet->speed, packet->header, evt);
1408
1409         switch (evt) {
1410         case OHCI1394_evt_timeout:
1411                 /* Async response transmit timed out. */
1412                 packet->ack = RCODE_CANCELLED;
1413                 break;
1414
1415         case OHCI1394_evt_flushed:
1416                 /*
1417                  * The packet was flushed should give same error as
1418                  * when we try to use a stale generation count.
1419                  */
1420                 packet->ack = RCODE_GENERATION;
1421                 break;
1422
1423         case OHCI1394_evt_missing_ack:
1424                 if (context->flushing)
1425                         packet->ack = RCODE_GENERATION;
1426                 else {
1427                         /*
1428                          * Using a valid (current) generation count, but the
1429                          * node is not on the bus or not sending acks.
1430                          */
1431                         packet->ack = RCODE_NO_ACK;
1432                 }
1433                 break;
1434
1435         case ACK_COMPLETE + 0x10:
1436         case ACK_PENDING + 0x10:
1437         case ACK_BUSY_X + 0x10:
1438         case ACK_BUSY_A + 0x10:
1439         case ACK_BUSY_B + 0x10:
1440         case ACK_DATA_ERROR + 0x10:
1441         case ACK_TYPE_ERROR + 0x10:
1442                 packet->ack = evt - 0x10;
1443                 break;
1444
1445         case OHCI1394_evt_no_status:
1446                 if (context->flushing) {
1447                         packet->ack = RCODE_GENERATION;
1448                         break;
1449                 }
1450                 /* fall through */
1451
1452         default:
1453                 packet->ack = RCODE_SEND_ERROR;
1454                 break;
1455         }
1456
1457         packet->callback(packet, &ohci->card, packet->ack);
1458
1459         return 1;
1460 }
1461
1462 #define HEADER_GET_DESTINATION(q)       (((q) >> 16) & 0xffff)
1463 #define HEADER_GET_TCODE(q)             (((q) >> 4) & 0x0f)
1464 #define HEADER_GET_OFFSET_HIGH(q)       (((q) >> 0) & 0xffff)
1465 #define HEADER_GET_DATA_LENGTH(q)       (((q) >> 16) & 0xffff)
1466 #define HEADER_GET_EXTENDED_TCODE(q)    (((q) >> 0) & 0xffff)
1467
1468 static void handle_local_rom(struct fw_ohci *ohci,
1469                              struct fw_packet *packet, u32 csr)
1470 {
1471         struct fw_packet response;
1472         int tcode, length, i;
1473
1474         tcode = HEADER_GET_TCODE(packet->header[0]);
1475         if (TCODE_IS_BLOCK_PACKET(tcode))
1476                 length = HEADER_GET_DATA_LENGTH(packet->header[3]);
1477         else
1478                 length = 4;
1479
1480         i = csr - CSR_CONFIG_ROM;
1481         if (i + length > CONFIG_ROM_SIZE) {
1482                 fw_fill_response(&response, packet->header,
1483                                  RCODE_ADDRESS_ERROR, NULL, 0);
1484         } else if (!TCODE_IS_READ_REQUEST(tcode)) {
1485                 fw_fill_response(&response, packet->header,
1486                                  RCODE_TYPE_ERROR, NULL, 0);
1487         } else {
1488                 fw_fill_response(&response, packet->header, RCODE_COMPLETE,
1489                                  (void *) ohci->config_rom + i, length);
1490         }
1491
1492         fw_core_handle_response(&ohci->card, &response);
1493 }
1494
1495 static void handle_local_lock(struct fw_ohci *ohci,
1496                               struct fw_packet *packet, u32 csr)
1497 {
1498         struct fw_packet response;
1499         int tcode, length, ext_tcode, sel, try;
1500         __be32 *payload, lock_old;
1501         u32 lock_arg, lock_data;
1502
1503         tcode = HEADER_GET_TCODE(packet->header[0]);
1504         length = HEADER_GET_DATA_LENGTH(packet->header[3]);
1505         payload = packet->payload;
1506         ext_tcode = HEADER_GET_EXTENDED_TCODE(packet->header[3]);
1507
1508         if (tcode == TCODE_LOCK_REQUEST &&
1509             ext_tcode == EXTCODE_COMPARE_SWAP && length == 8) {
1510                 lock_arg = be32_to_cpu(payload[0]);
1511                 lock_data = be32_to_cpu(payload[1]);
1512         } else if (tcode == TCODE_READ_QUADLET_REQUEST) {
1513                 lock_arg = 0;
1514                 lock_data = 0;
1515         } else {
1516                 fw_fill_response(&response, packet->header,
1517                                  RCODE_TYPE_ERROR, NULL, 0);
1518                 goto out;
1519         }
1520
1521         sel = (csr - CSR_BUS_MANAGER_ID) / 4;
1522         reg_write(ohci, OHCI1394_CSRData, lock_data);
1523         reg_write(ohci, OHCI1394_CSRCompareData, lock_arg);
1524         reg_write(ohci, OHCI1394_CSRControl, sel);
1525
1526         for (try = 0; try < 20; try++)
1527                 if (reg_read(ohci, OHCI1394_CSRControl) & 0x80000000) {
1528                         lock_old = cpu_to_be32(reg_read(ohci,
1529                                                         OHCI1394_CSRData));
1530                         fw_fill_response(&response, packet->header,
1531                                          RCODE_COMPLETE,
1532                                          &lock_old, sizeof(lock_old));
1533                         goto out;
1534                 }
1535
1536         fw_error("swap not done (CSR lock timeout)\n");
1537         fw_fill_response(&response, packet->header, RCODE_BUSY, NULL, 0);
1538
1539  out:
1540         fw_core_handle_response(&ohci->card, &response);
1541 }
1542
1543 static void handle_local_request(struct context *ctx, struct fw_packet *packet)
1544 {
1545         u64 offset, csr;
1546
1547         if (ctx == &ctx->ohci->at_request_ctx) {
1548                 packet->ack = ACK_PENDING;
1549                 packet->callback(packet, &ctx->ohci->card, packet->ack);
1550         }
1551
1552         offset =
1553                 ((unsigned long long)
1554                  HEADER_GET_OFFSET_HIGH(packet->header[1]) << 32) |
1555                 packet->header[2];
1556         csr = offset - CSR_REGISTER_BASE;
1557
1558         /* Handle config rom reads. */
1559         if (csr >= CSR_CONFIG_ROM && csr < CSR_CONFIG_ROM_END)
1560                 handle_local_rom(ctx->ohci, packet, csr);
1561         else switch (csr) {
1562         case CSR_BUS_MANAGER_ID:
1563         case CSR_BANDWIDTH_AVAILABLE:
1564         case CSR_CHANNELS_AVAILABLE_HI:
1565         case CSR_CHANNELS_AVAILABLE_LO:
1566                 handle_local_lock(ctx->ohci, packet, csr);
1567                 break;
1568         default:
1569                 if (ctx == &ctx->ohci->at_request_ctx)
1570                         fw_core_handle_request(&ctx->ohci->card, packet);
1571                 else
1572                         fw_core_handle_response(&ctx->ohci->card, packet);
1573                 break;
1574         }
1575
1576         if (ctx == &ctx->ohci->at_response_ctx) {
1577                 packet->ack = ACK_COMPLETE;
1578                 packet->callback(packet, &ctx->ohci->card, packet->ack);
1579         }
1580 }
1581
1582 static void at_context_transmit(struct context *ctx, struct fw_packet *packet)
1583 {
1584         unsigned long flags;
1585         int ret;
1586
1587         spin_lock_irqsave(&ctx->ohci->lock, flags);
1588
1589         if (HEADER_GET_DESTINATION(packet->header[0]) == ctx->ohci->node_id &&
1590             ctx->ohci->generation == packet->generation) {
1591                 spin_unlock_irqrestore(&ctx->ohci->lock, flags);
1592                 handle_local_request(ctx, packet);
1593                 return;
1594         }
1595
1596         ret = at_context_queue_packet(ctx, packet);
1597         spin_unlock_irqrestore(&ctx->ohci->lock, flags);
1598
1599         if (ret < 0)
1600                 packet->callback(packet, &ctx->ohci->card, packet->ack);
1601
1602 }
1603
1604 static void detect_dead_context(struct fw_ohci *ohci,
1605                                 const char *name, unsigned int regs)
1606 {
1607         u32 ctl;
1608
1609         ctl = reg_read(ohci, CONTROL_SET(regs));
1610         if (ctl & CONTEXT_DEAD) {
1611 #ifdef CONFIG_FIREWIRE_OHCI_DEBUG
1612                 fw_error("DMA context %s has stopped, error code: %s\n",
1613                          name, evts[ctl & 0x1f]);
1614 #else
1615                 fw_error("DMA context %s has stopped, error code: %#x\n",
1616                          name, ctl & 0x1f);
1617 #endif
1618         }
1619 }
1620
1621 static void handle_dead_contexts(struct fw_ohci *ohci)
1622 {
1623         unsigned int i;
1624         char name[8];
1625
1626         detect_dead_context(ohci, "ATReq", OHCI1394_AsReqTrContextBase);
1627         detect_dead_context(ohci, "ATRsp", OHCI1394_AsRspTrContextBase);
1628         detect_dead_context(ohci, "ARReq", OHCI1394_AsReqRcvContextBase);
1629         detect_dead_context(ohci, "ARRsp", OHCI1394_AsRspRcvContextBase);
1630         for (i = 0; i < 32; ++i) {
1631                 if (!(ohci->it_context_support & (1 << i)))
1632                         continue;
1633                 sprintf(name, "IT%u", i);
1634                 detect_dead_context(ohci, name, OHCI1394_IsoXmitContextBase(i));
1635         }
1636         for (i = 0; i < 32; ++i) {
1637                 if (!(ohci->ir_context_support & (1 << i)))
1638                         continue;
1639                 sprintf(name, "IR%u", i);
1640                 detect_dead_context(ohci, name, OHCI1394_IsoRcvContextBase(i));
1641         }
1642         /* TODO: maybe try to flush and restart the dead contexts */
1643 }
1644
1645 static u32 cycle_timer_ticks(u32 cycle_timer)
1646 {
1647         u32 ticks;
1648
1649         ticks = cycle_timer & 0xfff;
1650         ticks += 3072 * ((cycle_timer >> 12) & 0x1fff);
1651         ticks += (3072 * 8000) * (cycle_timer >> 25);
1652
1653         return ticks;
1654 }
1655
1656 /*
1657  * Some controllers exhibit one or more of the following bugs when updating the
1658  * iso cycle timer register:
1659  *  - When the lowest six bits are wrapping around to zero, a read that happens
1660  *    at the same time will return garbage in the lowest ten bits.
1661  *  - When the cycleOffset field wraps around to zero, the cycleCount field is
1662  *    not incremented for about 60 ns.
1663  *  - Occasionally, the entire register reads zero.
1664  *
1665  * To catch these, we read the register three times and ensure that the
1666  * difference between each two consecutive reads is approximately the same, i.e.
1667  * less than twice the other.  Furthermore, any negative difference indicates an
1668  * error.  (A PCI read should take at least 20 ticks of the 24.576 MHz timer to
1669  * execute, so we have enough precision to compute the ratio of the differences.)
1670  */
1671 static u32 get_cycle_time(struct fw_ohci *ohci)
1672 {
1673         u32 c0, c1, c2;
1674         u32 t0, t1, t2;
1675         s32 diff01, diff12;
1676         int i;
1677
1678         c2 = reg_read(ohci, OHCI1394_IsochronousCycleTimer);
1679
1680         if (ohci->quirks & QUIRK_CYCLE_TIMER) {
1681                 i = 0;
1682                 c1 = c2;
1683                 c2 = reg_read(ohci, OHCI1394_IsochronousCycleTimer);
1684                 do {
1685                         c0 = c1;
1686                         c1 = c2;
1687                         c2 = reg_read(ohci, OHCI1394_IsochronousCycleTimer);
1688                         t0 = cycle_timer_ticks(c0);
1689                         t1 = cycle_timer_ticks(c1);
1690                         t2 = cycle_timer_ticks(c2);
1691                         diff01 = t1 - t0;
1692                         diff12 = t2 - t1;
1693                 } while ((diff01 <= 0 || diff12 <= 0 ||
1694                           diff01 / diff12 >= 2 || diff12 / diff01 >= 2)
1695                          && i++ < 20);
1696         }
1697
1698         return c2;
1699 }
1700
1701 /*
1702  * This function has to be called at least every 64 seconds.  The bus_time
1703  * field stores not only the upper 25 bits of the BUS_TIME register but also
1704  * the most significant bit of the cycle timer in bit 6 so that we can detect
1705  * changes in this bit.
1706  */
1707 static u32 update_bus_time(struct fw_ohci *ohci)
1708 {
1709         u32 cycle_time_seconds = get_cycle_time(ohci) >> 25;
1710
1711         if ((ohci->bus_time & 0x40) != (cycle_time_seconds & 0x40))
1712                 ohci->bus_time += 0x40;
1713
1714         return ohci->bus_time | cycle_time_seconds;
1715 }
1716
1717 static void bus_reset_work(struct work_struct *work)
1718 {
1719         struct fw_ohci *ohci =
1720                 container_of(work, struct fw_ohci, bus_reset_work);
1721         int self_id_count, i, j, reg;
1722         int generation, new_generation;
1723         unsigned long flags;
1724         void *free_rom = NULL;
1725         dma_addr_t free_rom_bus = 0;
1726         bool is_new_root;
1727
1728         reg = reg_read(ohci, OHCI1394_NodeID);
1729         if (!(reg & OHCI1394_NodeID_idValid)) {
1730                 fw_notify("node ID not valid, new bus reset in progress\n");
1731                 return;
1732         }
1733         if ((reg & OHCI1394_NodeID_nodeNumber) == 63) {
1734                 fw_notify("malconfigured bus\n");
1735                 return;
1736         }
1737         ohci->node_id = reg & (OHCI1394_NodeID_busNumber |
1738                                OHCI1394_NodeID_nodeNumber);
1739
1740         is_new_root = (reg & OHCI1394_NodeID_root) != 0;
1741         if (!(ohci->is_root && is_new_root))
1742                 reg_write(ohci, OHCI1394_LinkControlSet,
1743                           OHCI1394_LinkControl_cycleMaster);
1744         ohci->is_root = is_new_root;
1745
1746         reg = reg_read(ohci, OHCI1394_SelfIDCount);
1747         if (reg & OHCI1394_SelfIDCount_selfIDError) {
1748                 fw_notify("inconsistent self IDs\n");
1749                 return;
1750         }
1751         /*
1752          * The count in the SelfIDCount register is the number of
1753          * bytes in the self ID receive buffer.  Since we also receive
1754          * the inverted quadlets and a header quadlet, we shift one
1755          * bit extra to get the actual number of self IDs.
1756          */
1757         self_id_count = (reg >> 3) & 0xff;
1758         if (self_id_count == 0 || self_id_count > 252) {
1759                 fw_notify("inconsistent self IDs\n");
1760                 return;
1761         }
1762         generation = (cond_le32_to_cpu(ohci->self_id_cpu[0]) >> 16) & 0xff;
1763         rmb();
1764
1765         for (i = 1, j = 0; j < self_id_count; i += 2, j++) {
1766                 if (ohci->self_id_cpu[i] != ~ohci->self_id_cpu[i + 1]) {
1767                         fw_notify("inconsistent self IDs\n");
1768                         return;
1769                 }
1770                 ohci->self_id_buffer[j] =
1771                                 cond_le32_to_cpu(ohci->self_id_cpu[i]);
1772         }
1773         rmb();
1774
1775         /*
1776          * Check the consistency of the self IDs we just read.  The
1777          * problem we face is that a new bus reset can start while we
1778          * read out the self IDs from the DMA buffer. If this happens,
1779          * the DMA buffer will be overwritten with new self IDs and we
1780          * will read out inconsistent data.  The OHCI specification
1781          * (section 11.2) recommends a technique similar to
1782          * linux/seqlock.h, where we remember the generation of the
1783          * self IDs in the buffer before reading them out and compare
1784          * it to the current generation after reading them out.  If
1785          * the two generations match we know we have a consistent set
1786          * of self IDs.
1787          */
1788
1789         new_generation = (reg_read(ohci, OHCI1394_SelfIDCount) >> 16) & 0xff;
1790         if (new_generation != generation) {
1791                 fw_notify("recursive bus reset detected, "
1792                           "discarding self ids\n");
1793                 return;
1794         }
1795
1796         /* FIXME: Document how the locking works. */
1797         spin_lock_irqsave(&ohci->lock, flags);
1798
1799         ohci->generation = -1; /* prevent AT packet queueing */
1800         context_stop(&ohci->at_request_ctx);
1801         context_stop(&ohci->at_response_ctx);
1802
1803         spin_unlock_irqrestore(&ohci->lock, flags);
1804
1805         /*
1806          * Per OHCI 1.2 draft, clause 7.2.3.3, hardware may leave unsent
1807          * packets in the AT queues and software needs to drain them.
1808          * Some OHCI 1.1 controllers (JMicron) apparently require this too.
1809          */
1810         at_context_flush(&ohci->at_request_ctx);
1811         at_context_flush(&ohci->at_response_ctx);
1812
1813         spin_lock_irqsave(&ohci->lock, flags);
1814
1815         ohci->generation = generation;
1816         reg_write(ohci, OHCI1394_IntEventClear, OHCI1394_busReset);
1817
1818         if (ohci->quirks & QUIRK_RESET_PACKET)
1819                 ohci->request_generation = generation;
1820
1821         /*
1822          * This next bit is unrelated to the AT context stuff but we
1823          * have to do it under the spinlock also.  If a new config rom
1824          * was set up before this reset, the old one is now no longer
1825          * in use and we can free it. Update the config rom pointers
1826          * to point to the current config rom and clear the
1827          * next_config_rom pointer so a new update can take place.
1828          */
1829
1830         if (ohci->next_config_rom != NULL) {
1831                 if (ohci->next_config_rom != ohci->config_rom) {
1832                         free_rom      = ohci->config_rom;
1833                         free_rom_bus  = ohci->config_rom_bus;
1834                 }
1835                 ohci->config_rom      = ohci->next_config_rom;
1836                 ohci->config_rom_bus  = ohci->next_config_rom_bus;
1837                 ohci->next_config_rom = NULL;
1838
1839                 /*
1840                  * Restore config_rom image and manually update
1841                  * config_rom registers.  Writing the header quadlet
1842                  * will indicate that the config rom is ready, so we
1843                  * do that last.
1844                  */
1845                 reg_write(ohci, OHCI1394_BusOptions,
1846                           be32_to_cpu(ohci->config_rom[2]));
1847                 ohci->config_rom[0] = ohci->next_header;
1848                 reg_write(ohci, OHCI1394_ConfigROMhdr,
1849                           be32_to_cpu(ohci->next_header));
1850         }
1851
1852 #ifdef CONFIG_FIREWIRE_OHCI_REMOTE_DMA
1853         reg_write(ohci, OHCI1394_PhyReqFilterHiSet, ~0);
1854         reg_write(ohci, OHCI1394_PhyReqFilterLoSet, ~0);
1855 #endif
1856
1857         spin_unlock_irqrestore(&ohci->lock, flags);
1858
1859         if (free_rom)
1860                 dma_free_coherent(ohci->card.device, CONFIG_ROM_SIZE,
1861                                   free_rom, free_rom_bus);
1862
1863         log_selfids(ohci->node_id, generation,
1864                     self_id_count, ohci->self_id_buffer);
1865
1866         fw_core_handle_bus_reset(&ohci->card, ohci->node_id, generation,
1867                                  self_id_count, ohci->self_id_buffer,
1868                                  ohci->csr_state_setclear_abdicate);
1869         ohci->csr_state_setclear_abdicate = false;
1870 }
1871
1872 static irqreturn_t irq_handler(int irq, void *data)
1873 {
1874         struct fw_ohci *ohci = data;
1875         u32 event, iso_event;
1876         int i;
1877
1878         event = reg_read(ohci, OHCI1394_IntEventClear);
1879
1880         if (!event || !~event)
1881                 return IRQ_NONE;
1882
1883         /*
1884          * busReset and postedWriteErr must not be cleared yet
1885          * (OHCI 1.1 clauses 7.2.3.2 and 13.2.8.1)
1886          */
1887         reg_write(ohci, OHCI1394_IntEventClear,
1888                   event & ~(OHCI1394_busReset | OHCI1394_postedWriteErr));
1889         log_irqs(event);
1890
1891         if (event & OHCI1394_selfIDComplete)
1892                 queue_work(fw_workqueue, &ohci->bus_reset_work);
1893
1894         if (event & OHCI1394_RQPkt)
1895                 tasklet_schedule(&ohci->ar_request_ctx.tasklet);
1896
1897         if (event & OHCI1394_RSPkt)
1898                 tasklet_schedule(&ohci->ar_response_ctx.tasklet);
1899
1900         if (event & OHCI1394_reqTxComplete)
1901                 tasklet_schedule(&ohci->at_request_ctx.tasklet);
1902
1903         if (event & OHCI1394_respTxComplete)
1904                 tasklet_schedule(&ohci->at_response_ctx.tasklet);
1905
1906         if (event & OHCI1394_isochRx) {
1907                 iso_event = reg_read(ohci, OHCI1394_IsoRecvIntEventClear);
1908                 reg_write(ohci, OHCI1394_IsoRecvIntEventClear, iso_event);
1909
1910                 while (iso_event) {
1911                         i = ffs(iso_event) - 1;
1912                         tasklet_schedule(
1913                                 &ohci->ir_context_list[i].context.tasklet);
1914                         iso_event &= ~(1 << i);
1915                 }
1916         }
1917
1918         if (event & OHCI1394_isochTx) {
1919                 iso_event = reg_read(ohci, OHCI1394_IsoXmitIntEventClear);
1920                 reg_write(ohci, OHCI1394_IsoXmitIntEventClear, iso_event);
1921
1922                 while (iso_event) {
1923                         i = ffs(iso_event) - 1;
1924                         tasklet_schedule(
1925                                 &ohci->it_context_list[i].context.tasklet);
1926                         iso_event &= ~(1 << i);
1927                 }
1928         }
1929
1930         if (unlikely(event & OHCI1394_regAccessFail))
1931                 fw_error("Register access failure - "
1932                          "please notify linux1394-devel@lists.sf.net\n");
1933
1934         if (unlikely(event & OHCI1394_postedWriteErr)) {
1935                 reg_read(ohci, OHCI1394_PostedWriteAddressHi);
1936                 reg_read(ohci, OHCI1394_PostedWriteAddressLo);
1937                 reg_write(ohci, OHCI1394_IntEventClear,
1938                           OHCI1394_postedWriteErr);
1939                 fw_error("PCI posted write error\n");
1940         }
1941
1942         if (unlikely(event & OHCI1394_cycleTooLong)) {
1943                 if (printk_ratelimit())
1944                         fw_notify("isochronous cycle too long\n");
1945                 reg_write(ohci, OHCI1394_LinkControlSet,
1946                           OHCI1394_LinkControl_cycleMaster);
1947         }
1948
1949         if (unlikely(event & OHCI1394_cycleInconsistent)) {
1950                 /*
1951                  * We need to clear this event bit in order to make
1952                  * cycleMatch isochronous I/O work.  In theory we should
1953                  * stop active cycleMatch iso contexts now and restart
1954                  * them at least two cycles later.  (FIXME?)
1955                  */
1956                 if (printk_ratelimit())
1957                         fw_notify("isochronous cycle inconsistent\n");
1958         }
1959
1960         if (unlikely(event & OHCI1394_unrecoverableError))
1961                 handle_dead_contexts(ohci);
1962
1963         if (event & OHCI1394_cycle64Seconds) {
1964                 spin_lock(&ohci->lock);
1965                 update_bus_time(ohci);
1966                 spin_unlock(&ohci->lock);
1967         } else
1968                 flush_writes(ohci);
1969
1970         return IRQ_HANDLED;
1971 }
1972
1973 static int software_reset(struct fw_ohci *ohci)
1974 {
1975         u32 val;
1976         int i;
1977
1978         reg_write(ohci, OHCI1394_HCControlSet, OHCI1394_HCControl_softReset);
1979         for (i = 0; i < 500; i++) {
1980                 val = reg_read(ohci, OHCI1394_HCControlSet);
1981                 if (!~val)
1982                         return -ENODEV; /* Card was ejected. */
1983
1984                 if (!(val & OHCI1394_HCControl_softReset))
1985                         return 0;
1986
1987                 msleep(1);
1988         }
1989
1990         return -EBUSY;
1991 }
1992
1993 static void copy_config_rom(__be32 *dest, const __be32 *src, size_t length)
1994 {
1995         size_t size = length * 4;
1996
1997         memcpy(dest, src, size);
1998         if (size < CONFIG_ROM_SIZE)
1999                 memset(&dest[length], 0, CONFIG_ROM_SIZE - size);
2000 }
2001
2002 static int configure_1394a_enhancements(struct fw_ohci *ohci)
2003 {
2004         bool enable_1394a;
2005         int ret, clear, set, offset;
2006
2007         /* Check if the driver should configure link and PHY. */
2008         if (!(reg_read(ohci, OHCI1394_HCControlSet) &
2009               OHCI1394_HCControl_programPhyEnable))
2010                 return 0;
2011
2012         /* Paranoia: check whether the PHY supports 1394a, too. */
2013         enable_1394a = false;
2014         ret = read_phy_reg(ohci, 2);
2015         if (ret < 0)
2016                 return ret;
2017         if ((ret & PHY_EXTENDED_REGISTERS) == PHY_EXTENDED_REGISTERS) {
2018                 ret = read_paged_phy_reg(ohci, 1, 8);
2019                 if (ret < 0)
2020                         return ret;
2021                 if (ret >= 1)
2022                         enable_1394a = true;
2023         }
2024
2025         if (ohci->quirks & QUIRK_NO_1394A)
2026                 enable_1394a = false;
2027
2028         /* Configure PHY and link consistently. */
2029         if (enable_1394a) {
2030                 clear = 0;
2031                 set = PHY_ENABLE_ACCEL | PHY_ENABLE_MULTI;
2032         } else {
2033                 clear = PHY_ENABLE_ACCEL | PHY_ENABLE_MULTI;
2034                 set = 0;
2035         }
2036         ret = update_phy_reg(ohci, 5, clear, set);
2037         if (ret < 0)
2038                 return ret;
2039
2040         if (enable_1394a)
2041                 offset = OHCI1394_HCControlSet;
2042         else
2043                 offset = OHCI1394_HCControlClear;
2044         reg_write(ohci, offset, OHCI1394_HCControl_aPhyEnhanceEnable);
2045
2046         /* Clean up: configuration has been taken care of. */
2047         reg_write(ohci, OHCI1394_HCControlClear,
2048                   OHCI1394_HCControl_programPhyEnable);
2049
2050         return 0;
2051 }
2052
2053 static int ohci_enable(struct fw_card *card,
2054                        const __be32 *config_rom, size_t length)
2055 {
2056         struct fw_ohci *ohci = fw_ohci(card);
2057         struct pci_dev *dev = to_pci_dev(card->device);
2058         u32 lps, seconds, version, irqs;
2059         int i, ret;
2060
2061         if (software_reset(ohci)) {
2062                 fw_error("Failed to reset ohci card.\n");
2063                 return -EBUSY;
2064         }
2065
2066         /*
2067          * Now enable LPS, which we need in order to start accessing
2068          * most of the registers.  In fact, on some cards (ALI M5251),
2069          * accessing registers in the SClk domain without LPS enabled
2070          * will lock up the machine.  Wait 50msec to make sure we have
2071          * full link enabled.  However, with some cards (well, at least
2072          * a JMicron PCIe card), we have to try again sometimes.
2073          */
2074         reg_write(ohci, OHCI1394_HCControlSet,
2075                   OHCI1394_HCControl_LPS |
2076                   OHCI1394_HCControl_postedWriteEnable);
2077         flush_writes(ohci);
2078
2079         for (lps = 0, i = 0; !lps && i < 3; i++) {
2080                 msleep(50);
2081                 lps = reg_read(ohci, OHCI1394_HCControlSet) &
2082                       OHCI1394_HCControl_LPS;
2083         }
2084
2085         if (!lps) {
2086                 fw_error("Failed to set Link Power Status\n");
2087                 return -EIO;
2088         }
2089
2090         reg_write(ohci, OHCI1394_HCControlClear,
2091                   OHCI1394_HCControl_noByteSwapData);
2092
2093         reg_write(ohci, OHCI1394_SelfIDBuffer, ohci->self_id_bus);
2094         reg_write(ohci, OHCI1394_LinkControlSet,
2095                   OHCI1394_LinkControl_cycleTimerEnable |
2096                   OHCI1394_LinkControl_cycleMaster);
2097
2098         reg_write(ohci, OHCI1394_ATRetries,
2099                   OHCI1394_MAX_AT_REQ_RETRIES |
2100                   (OHCI1394_MAX_AT_RESP_RETRIES << 4) |
2101                   (OHCI1394_MAX_PHYS_RESP_RETRIES << 8) |
2102                   (200 << 16));
2103
2104         seconds = lower_32_bits(get_seconds());
2105         reg_write(ohci, OHCI1394_IsochronousCycleTimer, seconds << 25);
2106         ohci->bus_time = seconds & ~0x3f;
2107
2108         version = reg_read(ohci, OHCI1394_Version) & 0x00ff00ff;
2109         if (version >= OHCI_VERSION_1_1) {
2110                 reg_write(ohci, OHCI1394_InitialChannelsAvailableHi,
2111                           0xfffffffe);
2112                 card->broadcast_channel_auto_allocated = true;
2113         }
2114
2115         /* Get implemented bits of the priority arbitration request counter. */
2116         reg_write(ohci, OHCI1394_FairnessControl, 0x3f);
2117         ohci->pri_req_max = reg_read(ohci, OHCI1394_FairnessControl) & 0x3f;
2118         reg_write(ohci, OHCI1394_FairnessControl, 0);
2119         card->priority_budget_implemented = ohci->pri_req_max != 0;
2120
2121         reg_write(ohci, OHCI1394_PhyUpperBound, 0x00010000);
2122         reg_write(ohci, OHCI1394_IntEventClear, ~0);
2123         reg_write(ohci, OHCI1394_IntMaskClear, ~0);
2124
2125         ret = configure_1394a_enhancements(ohci);
2126         if (ret < 0)
2127                 return ret;
2128
2129         /* Activate link_on bit and contender bit in our self ID packets.*/
2130         ret = ohci_update_phy_reg(card, 4, 0, PHY_LINK_ACTIVE | PHY_CONTENDER);
2131         if (ret < 0)
2132                 return ret;
2133
2134         /*
2135          * When the link is not yet enabled, the atomic config rom
2136          * update mechanism described below in ohci_set_config_rom()
2137          * is not active.  We have to update ConfigRomHeader and
2138          * BusOptions manually, and the write to ConfigROMmap takes
2139          * effect immediately.  We tie this to the enabling of the
2140          * link, so we have a valid config rom before enabling - the
2141          * OHCI requires that ConfigROMhdr and BusOptions have valid
2142          * values before enabling.
2143          *
2144          * However, when the ConfigROMmap is written, some controllers
2145          * always read back quadlets 0 and 2 from the config rom to
2146          * the ConfigRomHeader and BusOptions registers on bus reset.
2147          * They shouldn't do that in this initial case where the link
2148          * isn't enabled.  This means we have to use the same
2149          * workaround here, setting the bus header to 0 and then write
2150          * the right values in the bus reset tasklet.
2151          */
2152
2153         if (config_rom) {
2154                 ohci->next_config_rom =
2155                         dma_alloc_coherent(ohci->card.device, CONFIG_ROM_SIZE,
2156                                            &ohci->next_config_rom_bus,
2157                                            GFP_KERNEL);
2158                 if (ohci->next_config_rom == NULL)
2159                         return -ENOMEM;
2160
2161                 copy_config_rom(ohci->next_config_rom, config_rom, length);
2162         } else {
2163                 /*
2164                  * In the suspend case, config_rom is NULL, which
2165                  * means that we just reuse the old config rom.
2166                  */
2167                 ohci->next_config_rom = ohci->config_rom;
2168                 ohci->next_config_rom_bus = ohci->config_rom_bus;
2169         }
2170
2171         ohci->next_header = ohci->next_config_rom[0];
2172         ohci->next_config_rom[0] = 0;
2173         reg_write(ohci, OHCI1394_ConfigROMhdr, 0);
2174         reg_write(ohci, OHCI1394_BusOptions,
2175                   be32_to_cpu(ohci->next_config_rom[2]));
2176         reg_write(ohci, OHCI1394_ConfigROMmap, ohci->next_config_rom_bus);
2177
2178         reg_write(ohci, OHCI1394_AsReqFilterHiSet, 0x80000000);
2179
2180         if (!(ohci->quirks & QUIRK_NO_MSI))
2181                 pci_enable_msi(dev);
2182         if (request_irq(dev->irq, irq_handler,
2183                         pci_dev_msi_enabled(dev) ? 0 : IRQF_SHARED,
2184                         ohci_driver_name, ohci)) {
2185                 fw_error("Failed to allocate interrupt %d.\n", dev->irq);
2186                 pci_disable_msi(dev);
2187
2188                 if (config_rom) {
2189                         dma_free_coherent(ohci->card.device, CONFIG_ROM_SIZE,
2190                                           ohci->next_config_rom,
2191                                           ohci->next_config_rom_bus);
2192                         ohci->next_config_rom = NULL;
2193                 }
2194                 return -EIO;
2195         }
2196
2197         irqs =  OHCI1394_reqTxComplete | OHCI1394_respTxComplete |
2198                 OHCI1394_RQPkt | OHCI1394_RSPkt |
2199                 OHCI1394_isochTx | OHCI1394_isochRx |
2200                 OHCI1394_postedWriteErr |
2201                 OHCI1394_selfIDComplete |
2202                 OHCI1394_regAccessFail |
2203                 OHCI1394_cycle64Seconds |
2204                 OHCI1394_cycleInconsistent |
2205                 OHCI1394_unrecoverableError |
2206                 OHCI1394_cycleTooLong |
2207                 OHCI1394_masterIntEnable;
2208         if (param_debug & OHCI_PARAM_DEBUG_BUSRESETS)
2209                 irqs |= OHCI1394_busReset;
2210         reg_write(ohci, OHCI1394_IntMaskSet, irqs);
2211
2212         reg_write(ohci, OHCI1394_HCControlSet,
2213                   OHCI1394_HCControl_linkEnable |
2214                   OHCI1394_HCControl_BIBimageValid);
2215
2216         reg_write(ohci, OHCI1394_LinkControlSet,
2217                   OHCI1394_LinkControl_rcvSelfID |
2218                   OHCI1394_LinkControl_rcvPhyPkt);
2219
2220         ar_context_run(&ohci->ar_request_ctx);
2221         ar_context_run(&ohci->ar_response_ctx);
2222
2223         flush_writes(ohci);
2224
2225         /* We are ready to go, reset bus to finish initialization. */
2226         fw_schedule_bus_reset(&ohci->card, false, true);
2227
2228         return 0;
2229 }
2230
2231 static int ohci_set_config_rom(struct fw_card *card,
2232                                const __be32 *config_rom, size_t length)
2233 {
2234         struct fw_ohci *ohci;
2235         unsigned long flags;
2236         __be32 *next_config_rom;
2237         dma_addr_t uninitialized_var(next_config_rom_bus);
2238
2239         ohci = fw_ohci(card);
2240
2241         /*
2242          * When the OHCI controller is enabled, the config rom update
2243          * mechanism is a bit tricky, but easy enough to use.  See
2244          * section 5.5.6 in the OHCI specification.
2245          *
2246          * The OHCI controller caches the new config rom address in a
2247          * shadow register (ConfigROMmapNext) and needs a bus reset
2248          * for the changes to take place.  When the bus reset is
2249          * detected, the controller loads the new values for the
2250          * ConfigRomHeader and BusOptions registers from the specified
2251          * config rom and loads ConfigROMmap from the ConfigROMmapNext
2252          * shadow register. All automatically and atomically.
2253          *
2254          * Now, there's a twist to this story.  The automatic load of
2255          * ConfigRomHeader and BusOptions doesn't honor the
2256          * noByteSwapData bit, so with a be32 config rom, the
2257          * controller will load be32 values in to these registers
2258          * during the atomic update, even on litte endian
2259          * architectures.  The workaround we use is to put a 0 in the
2260          * header quadlet; 0 is endian agnostic and means that the
2261          * config rom isn't ready yet.  In the bus reset tasklet we
2262          * then set up the real values for the two registers.
2263          *
2264          * We use ohci->lock to avoid racing with the code that sets
2265          * ohci->next_config_rom to NULL (see bus_reset_work).
2266          */
2267
2268         next_config_rom =
2269                 dma_alloc_coherent(ohci->card.device, CONFIG_ROM_SIZE,
2270                                    &next_config_rom_bus, GFP_KERNEL);
2271         if (next_config_rom == NULL)
2272                 return -ENOMEM;
2273
2274         spin_lock_irqsave(&ohci->lock, flags);
2275
2276         /*
2277          * If there is not an already pending config_rom update,
2278          * push our new allocation into the ohci->next_config_rom
2279          * and then mark the local variable as null so that we
2280          * won't deallocate the new buffer.
2281          *
2282          * OTOH, if there is a pending config_rom update, just
2283          * use that buffer with the new config_rom data, and
2284          * let this routine free the unused DMA allocation.
2285          */
2286
2287         if (ohci->next_config_rom == NULL) {
2288                 ohci->next_config_rom = next_config_rom;
2289                 ohci->next_config_rom_bus = next_config_rom_bus;
2290                 next_config_rom = NULL;
2291         }
2292
2293         copy_config_rom(ohci->next_config_rom, config_rom, length);
2294
2295         ohci->next_header = config_rom[0];
2296         ohci->next_config_rom[0] = 0;
2297
2298         reg_write(ohci, OHCI1394_ConfigROMmap, ohci->next_config_rom_bus);
2299
2300         spin_unlock_irqrestore(&ohci->lock, flags);
2301
2302         /* If we didn't use the DMA allocation, delete it. */
2303         if (next_config_rom != NULL)
2304                 dma_free_coherent(ohci->card.device, CONFIG_ROM_SIZE,
2305                                   next_config_rom, next_config_rom_bus);
2306
2307         /*
2308          * Now initiate a bus reset to have the changes take
2309          * effect. We clean up the old config rom memory and DMA
2310          * mappings in the bus reset tasklet, since the OHCI
2311          * controller could need to access it before the bus reset
2312          * takes effect.
2313          */
2314
2315         fw_schedule_bus_reset(&ohci->card, true, true);
2316
2317         return 0;
2318 }
2319
2320 static void ohci_send_request(struct fw_card *card, struct fw_packet *packet)
2321 {
2322         struct fw_ohci *ohci = fw_ohci(card);
2323
2324         at_context_transmit(&ohci->at_request_ctx, packet);
2325 }
2326
2327 static void ohci_send_response(struct fw_card *card, struct fw_packet *packet)
2328 {
2329         struct fw_ohci *ohci = fw_ohci(card);
2330
2331         at_context_transmit(&ohci->at_response_ctx, packet);
2332 }
2333
2334 static int ohci_cancel_packet(struct fw_card *card, struct fw_packet *packet)
2335 {
2336         struct fw_ohci *ohci = fw_ohci(card);
2337         struct context *ctx = &ohci->at_request_ctx;
2338         struct driver_data *driver_data = packet->driver_data;
2339         int ret = -ENOENT;
2340
2341         tasklet_disable(&ctx->tasklet);
2342
2343         if (packet->ack != 0)
2344                 goto out;
2345
2346         if (packet->payload_mapped)
2347                 dma_unmap_single(ohci->card.device, packet->payload_bus,
2348                                  packet->payload_length, DMA_TO_DEVICE);
2349
2350         log_ar_at_event('T', packet->speed, packet->header, 0x20);
2351         driver_data->packet = NULL;
2352         packet->ack = RCODE_CANCELLED;
2353         packet->callback(packet, &ohci->card, packet->ack);
2354         ret = 0;
2355  out:
2356         tasklet_enable(&ctx->tasklet);
2357
2358         return ret;
2359 }
2360
2361 static int ohci_enable_phys_dma(struct fw_card *card,
2362                                 int node_id, int generation)
2363 {
2364 #ifdef CONFIG_FIREWIRE_OHCI_REMOTE_DMA
2365         return 0;
2366 #else
2367         struct fw_ohci *ohci = fw_ohci(card);
2368         unsigned long flags;
2369         int n, ret = 0;
2370
2371         /*
2372          * FIXME:  Make sure this bitmask is cleared when we clear the busReset
2373          * interrupt bit.  Clear physReqResourceAllBuses on bus reset.
2374          */
2375
2376         spin_lock_irqsave(&ohci->lock, flags);
2377
2378         if (ohci->generation != generation) {
2379                 ret = -ESTALE;
2380                 goto out;
2381         }
2382
2383         /*
2384          * Note, if the node ID contains a non-local bus ID, physical DMA is
2385          * enabled for _all_ nodes on remote buses.
2386          */
2387
2388         n = (node_id & 0xffc0) == LOCAL_BUS ? node_id & 0x3f : 63;
2389         if (n < 32)
2390                 reg_write(ohci, OHCI1394_PhyReqFilterLoSet, 1 << n);
2391         else
2392                 reg_write(ohci, OHCI1394_PhyReqFilterHiSet, 1 << (n - 32));
2393
2394         flush_writes(ohci);
2395  out:
2396         spin_unlock_irqrestore(&ohci->lock, flags);
2397
2398         return ret;
2399 #endif /* CONFIG_FIREWIRE_OHCI_REMOTE_DMA */
2400 }
2401
2402 static u32 ohci_read_csr(struct fw_card *card, int csr_offset)
2403 {
2404         struct fw_ohci *ohci = fw_ohci(card);
2405         unsigned long flags;
2406         u32 value;
2407
2408         switch (csr_offset) {
2409         case CSR_STATE_CLEAR:
2410         case CSR_STATE_SET:
2411                 if (ohci->is_root &&
2412                     (reg_read(ohci, OHCI1394_LinkControlSet) &
2413                      OHCI1394_LinkControl_cycleMaster))
2414                         value = CSR_STATE_BIT_CMSTR;
2415                 else
2416                         value = 0;
2417                 if (ohci->csr_state_setclear_abdicate)
2418                         value |= CSR_STATE_BIT_ABDICATE;
2419
2420                 return value;
2421
2422         case CSR_NODE_IDS:
2423                 return reg_read(ohci, OHCI1394_NodeID) << 16;
2424
2425         case CSR_CYCLE_TIME:
2426                 return get_cycle_time(ohci);
2427
2428         case CSR_BUS_TIME:
2429                 /*
2430                  * We might be called just after the cycle timer has wrapped
2431                  * around but just before the cycle64Seconds handler, so we
2432                  * better check here, too, if the bus time needs to be updated.
2433                  */
2434                 spin_lock_irqsave(&ohci->lock, flags);
2435                 value = update_bus_time(ohci);
2436                 spin_unlock_irqrestore(&ohci->lock, flags);
2437                 return value;
2438
2439         case CSR_BUSY_TIMEOUT:
2440                 value = reg_read(ohci, OHCI1394_ATRetries);
2441                 return (value >> 4) & 0x0ffff00f;
2442
2443         case CSR_PRIORITY_BUDGET:
2444                 return (reg_read(ohci, OHCI1394_FairnessControl) & 0x3f) |
2445                         (ohci->pri_req_max << 8);
2446
2447         default:
2448                 WARN_ON(1);
2449                 return 0;
2450         }
2451 }
2452
2453 static void ohci_write_csr(struct fw_card *card, int csr_offset, u32 value)
2454 {
2455         struct fw_ohci *ohci = fw_ohci(card);
2456         unsigned long flags;
2457
2458         switch (csr_offset) {
2459         case CSR_STATE_CLEAR:
2460                 if ((value & CSR_STATE_BIT_CMSTR) && ohci->is_root) {
2461                         reg_write(ohci, OHCI1394_LinkControlClear,
2462                                   OHCI1394_LinkControl_cycleMaster);
2463                         flush_writes(ohci);
2464                 }
2465                 if (value & CSR_STATE_BIT_ABDICATE)
2466                         ohci->csr_state_setclear_abdicate = false;
2467                 break;
2468
2469         case CSR_STATE_SET:
2470                 if ((value & CSR_STATE_BIT_CMSTR) && ohci->is_root) {
2471                         reg_write(ohci, OHCI1394_LinkControlSet,
2472                                   OHCI1394_LinkControl_cycleMaster);
2473                         flush_writes(ohci);
2474                 }
2475                 if (value & CSR_STATE_BIT_ABDICATE)
2476                         ohci->csr_state_setclear_abdicate = true;
2477                 break;
2478
2479         case CSR_NODE_IDS:
2480                 reg_write(ohci, OHCI1394_NodeID, value >> 16);
2481                 flush_writes(ohci);
2482                 break;
2483
2484         case CSR_CYCLE_TIME:
2485                 reg_write(ohci, OHCI1394_IsochronousCycleTimer, value);
2486                 reg_write(ohci, OHCI1394_IntEventSet,
2487                           OHCI1394_cycleInconsistent);
2488                 flush_writes(ohci);
2489                 break;
2490
2491         case CSR_BUS_TIME:
2492                 spin_lock_irqsave(&ohci->lock, flags);
2493                 ohci->bus_time = (ohci->bus_time & 0x7f) | (value & ~0x7f);
2494                 spin_unlock_irqrestore(&ohci->lock, flags);
2495                 break;
2496
2497         case CSR_BUSY_TIMEOUT:
2498                 value = (value & 0xf) | ((value & 0xf) << 4) |
2499                         ((value & 0xf) << 8) | ((value & 0x0ffff000) << 4);
2500                 reg_write(ohci, OHCI1394_ATRetries, value);
2501                 flush_writes(ohci);
2502                 break;
2503
2504         case CSR_PRIORITY_BUDGET:
2505                 reg_write(ohci, OHCI1394_FairnessControl, value & 0x3f);
2506                 flush_writes(ohci);
2507                 break;
2508
2509         default:
2510                 WARN_ON(1);
2511                 break;
2512         }
2513 }
2514
2515 static void copy_iso_headers(struct iso_context *ctx, void *p)
2516 {
2517         int i = ctx->header_length;
2518
2519         if (i + ctx->base.header_size > PAGE_SIZE)
2520                 return;
2521
2522         /*
2523          * The iso header is byteswapped to little endian by
2524          * the controller, but the remaining header quadlets
2525          * are big endian.  We want to present all the headers
2526          * as big endian, so we have to swap the first quadlet.
2527          */
2528         if (ctx->base.header_size > 0)
2529                 *(u32 *) (ctx->header + i) = __swab32(*(u32 *) (p + 4));
2530         if (ctx->base.header_size > 4)
2531                 *(u32 *) (ctx->header + i + 4) = __swab32(*(u32 *) p);
2532         if (ctx->base.header_size > 8)
2533                 memcpy(ctx->header + i + 8, p + 8, ctx->base.header_size - 8);
2534         ctx->header_length += ctx->base.header_size;
2535 }
2536
2537 static int handle_ir_packet_per_buffer(struct context *context,
2538                                        struct descriptor *d,
2539                                        struct descriptor *last)
2540 {
2541         struct iso_context *ctx =
2542                 container_of(context, struct iso_context, context);
2543         struct descriptor *pd;
2544         __le32 *ir_header;
2545         void *p;
2546
2547         for (pd = d; pd <= last; pd++)
2548                 if (pd->transfer_status)
2549                         break;
2550         if (pd > last)
2551                 /* Descriptor(s) not done yet, stop iteration */
2552                 return 0;
2553
2554         p = last + 1;
2555         copy_iso_headers(ctx, p);
2556
2557         if (le16_to_cpu(last->control) & DESCRIPTOR_IRQ_ALWAYS) {
2558                 ir_header = (__le32 *) p;
2559                 ctx->base.callback.sc(&ctx->base,
2560                                       le32_to_cpu(ir_header[0]) & 0xffff,
2561                                       ctx->header_length, ctx->header,
2562                                       ctx->base.callback_data);
2563                 ctx->header_length = 0;
2564         }
2565
2566         return 1;
2567 }
2568
2569 /* d == last because each descriptor block is only a single descriptor. */
2570 static int handle_ir_buffer_fill(struct context *context,
2571                                  struct descriptor *d,
2572                                  struct descriptor *last)
2573 {
2574         struct iso_context *ctx =
2575                 container_of(context, struct iso_context, context);
2576
2577         if (!last->transfer_status)
2578                 /* Descriptor(s) not done yet, stop iteration */
2579                 return 0;
2580
2581         if (le16_to_cpu(last->control) & DESCRIPTOR_IRQ_ALWAYS)
2582                 ctx->base.callback.mc(&ctx->base,
2583                                       le32_to_cpu(last->data_address) +
2584                                       le16_to_cpu(last->req_count) -
2585                                       le16_to_cpu(last->res_count),
2586                                       ctx->base.callback_data);
2587
2588         return 1;
2589 }
2590
2591 static int handle_it_packet(struct context *context,
2592                             struct descriptor *d,
2593                             struct descriptor *last)
2594 {
2595         struct iso_context *ctx =
2596                 container_of(context, struct iso_context, context);
2597         int i;
2598         struct descriptor *pd;
2599
2600         for (pd = d; pd <= last; pd++)
2601                 if (pd->transfer_status)
2602                         break;
2603         if (pd > last)
2604                 /* Descriptor(s) not done yet, stop iteration */
2605                 return 0;
2606
2607         i = ctx->header_length;
2608         if (i + 4 < PAGE_SIZE) {
2609                 /* Present this value as big-endian to match the receive code */
2610                 *(__be32 *)(ctx->header + i) = cpu_to_be32(
2611                                 ((u32)le16_to_cpu(pd->transfer_status) << 16) |
2612                                 le16_to_cpu(pd->res_count));
2613                 ctx->header_length += 4;
2614         }
2615         if (le16_to_cpu(last->control) & DESCRIPTOR_IRQ_ALWAYS) {
2616                 ctx->base.callback.sc(&ctx->base, le16_to_cpu(last->res_count),
2617                                       ctx->header_length, ctx->header,
2618                                       ctx->base.callback_data);
2619                 ctx->header_length = 0;
2620         }
2621         return 1;
2622 }
2623
2624 static void set_multichannel_mask(struct fw_ohci *ohci, u64 channels)
2625 {
2626         u32 hi = channels >> 32, lo = channels;
2627
2628         reg_write(ohci, OHCI1394_IRMultiChanMaskHiClear, ~hi);
2629         reg_write(ohci, OHCI1394_IRMultiChanMaskLoClear, ~lo);
2630         reg_write(ohci, OHCI1394_IRMultiChanMaskHiSet, hi);
2631         reg_write(ohci, OHCI1394_IRMultiChanMaskLoSet, lo);
2632         mmiowb();
2633         ohci->mc_channels = channels;
2634 }
2635
2636 static struct fw_iso_context *ohci_allocate_iso_context(struct fw_card *card,
2637                                 int type, int channel, size_t header_size)
2638 {
2639         struct fw_ohci *ohci = fw_ohci(card);
2640         struct iso_context *uninitialized_var(ctx);
2641         descriptor_callback_t uninitialized_var(callback);
2642         u64 *uninitialized_var(channels);
2643         u32 *uninitialized_var(mask), uninitialized_var(regs);
2644         unsigned long flags;
2645         int index, ret = -EBUSY;
2646
2647         spin_lock_irqsave(&ohci->lock, flags);
2648
2649         switch (type) {
2650         case FW_ISO_CONTEXT_TRANSMIT:
2651                 mask     = &ohci->it_context_mask;
2652                 callback = handle_it_packet;
2653                 index    = ffs(*mask) - 1;
2654                 if (index >= 0) {
2655                         *mask &= ~(1 << index);
2656                         regs = OHCI1394_IsoXmitContextBase(index);
2657                         ctx  = &ohci->it_context_list[index];
2658                 }
2659                 break;
2660
2661         case FW_ISO_CONTEXT_RECEIVE:
2662                 channels = &ohci->ir_context_channels;
2663                 mask     = &ohci->ir_context_mask;
2664                 callback = handle_ir_packet_per_buffer;
2665                 index    = *channels & 1ULL << channel ? ffs(*mask) - 1 : -1;
2666                 if (index >= 0) {
2667                         *channels &= ~(1ULL << channel);
2668                         *mask     &= ~(1 << index);
2669                         regs = OHCI1394_IsoRcvContextBase(index);
2670                         ctx  = &ohci->ir_context_list[index];
2671                 }
2672                 break;
2673
2674         case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
2675                 mask     = &ohci->ir_context_mask;
2676                 callback = handle_ir_buffer_fill;
2677                 index    = !ohci->mc_allocated ? ffs(*mask) - 1 : -1;
2678                 if (index >= 0) {
2679                         ohci->mc_allocated = true;
2680                         *mask &= ~(1 << index);
2681                         regs = OHCI1394_IsoRcvContextBase(index);
2682                         ctx  = &ohci->ir_context_list[index];
2683                 }
2684                 break;
2685
2686         default:
2687                 index = -1;
2688                 ret = -ENOSYS;
2689         }
2690
2691         spin_unlock_irqrestore(&ohci->lock, flags);
2692
2693         if (index < 0)
2694                 return ERR_PTR(ret);
2695
2696         memset(ctx, 0, sizeof(*ctx));
2697         ctx->header_length = 0;
2698         ctx->header = (void *) __get_free_page(GFP_KERNEL);
2699         if (ctx->header == NULL) {
2700                 ret = -ENOMEM;
2701                 goto out;
2702         }
2703         ret = context_init(&ctx->context, ohci, regs, callback);
2704         if (ret < 0)
2705                 goto out_with_header;
2706
2707         if (type == FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL)
2708                 set_multichannel_mask(ohci, 0);
2709
2710         return &ctx->base;
2711
2712  out_with_header:
2713         free_page((unsigned long)ctx->header);
2714  out:
2715         spin_lock_irqsave(&ohci->lock, flags);
2716
2717         switch (type) {
2718         case FW_ISO_CONTEXT_RECEIVE:
2719                 *channels |= 1ULL << channel;
2720                 break;
2721
2722         case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
2723                 ohci->mc_allocated = false;
2724                 break;
2725         }
2726         *mask |= 1 << index;
2727
2728         spin_unlock_irqrestore(&ohci->lock, flags);
2729
2730         return ERR_PTR(ret);
2731 }
2732
2733 static int ohci_start_iso(struct fw_iso_context *base,
2734                           s32 cycle, u32 sync, u32 tags)
2735 {
2736         struct iso_context *ctx = container_of(base, struct iso_context, base);
2737         struct fw_ohci *ohci = ctx->context.ohci;
2738         u32 control = IR_CONTEXT_ISOCH_HEADER, match;
2739         int index;
2740
2741         /* the controller cannot start without any queued packets */
2742         if (ctx->context.last->branch_address == 0)
2743                 return -ENODATA;
2744
2745         switch (ctx->base.type) {
2746         case FW_ISO_CONTEXT_TRANSMIT:
2747                 index = ctx - ohci->it_context_list;
2748                 match = 0;
2749                 if (cycle >= 0)
2750                         match = IT_CONTEXT_CYCLE_MATCH_ENABLE |
2751                                 (cycle & 0x7fff) << 16;
2752
2753                 reg_write(ohci, OHCI1394_IsoXmitIntEventClear, 1 << index);
2754                 reg_write(ohci, OHCI1394_IsoXmitIntMaskSet, 1 << index);
2755                 context_run(&ctx->context, match);
2756                 break;
2757
2758         case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
2759                 control |= IR_CONTEXT_BUFFER_FILL|IR_CONTEXT_MULTI_CHANNEL_MODE;
2760                 /* fall through */
2761         case FW_ISO_CONTEXT_RECEIVE:
2762                 index = ctx - ohci->ir_context_list;
2763                 match = (tags << 28) | (sync << 8) | ctx->base.channel;
2764                 if (cycle >= 0) {
2765                         match |= (cycle & 0x07fff) << 12;
2766                         control |= IR_CONTEXT_CYCLE_MATCH_ENABLE;
2767                 }
2768
2769                 reg_write(ohci, OHCI1394_IsoRecvIntEventClear, 1 << index);
2770                 reg_write(ohci, OHCI1394_IsoRecvIntMaskSet, 1 << index);
2771                 reg_write(ohci, CONTEXT_MATCH(ctx->context.regs), match);
2772                 context_run(&ctx->context, control);
2773
2774                 ctx->sync = sync;
2775                 ctx->tags = tags;
2776
2777                 break;
2778         }
2779
2780         return 0;
2781 }
2782
2783 static int ohci_stop_iso(struct fw_iso_context *base)
2784 {
2785         struct fw_ohci *ohci = fw_ohci(base->card);
2786         struct iso_context *ctx = container_of(base, struct iso_context, base);
2787         int index;
2788
2789         switch (ctx->base.type) {
2790         case FW_ISO_CONTEXT_TRANSMIT:
2791                 index = ctx - ohci->it_context_list;
2792                 reg_write(ohci, OHCI1394_IsoXmitIntMaskClear, 1 << index);
2793                 break;
2794
2795         case FW_ISO_CONTEXT_RECEIVE:
2796         case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
2797                 index = ctx - ohci->ir_context_list;
2798                 reg_write(ohci, OHCI1394_IsoRecvIntMaskClear, 1 << index);
2799                 break;
2800         }
2801         flush_writes(ohci);
2802         context_stop(&ctx->context);
2803         tasklet_kill(&ctx->context.tasklet);
2804
2805         return 0;
2806 }
2807
2808 static void ohci_free_iso_context(struct fw_iso_context *base)
2809 {
2810         struct fw_ohci *ohci = fw_ohci(base->card);
2811         struct iso_context *ctx = container_of(base, struct iso_context, base);
2812         unsigned long flags;
2813         int index;
2814
2815         ohci_stop_iso(base);
2816         context_release(&ctx->context);
2817         free_page((unsigned long)ctx->header);
2818
2819         spin_lock_irqsave(&ohci->lock, flags);
2820
2821         switch (base->type) {
2822         case FW_ISO_CONTEXT_TRANSMIT:
2823                 index = ctx - ohci->it_context_list;
2824                 ohci->it_context_mask |= 1 << index;
2825                 break;
2826
2827         case FW_ISO_CONTEXT_RECEIVE:
2828                 index = ctx - ohci->ir_context_list;
2829                 ohci->ir_context_mask |= 1 << index;
2830                 ohci->ir_context_channels |= 1ULL << base->channel;
2831                 break;
2832
2833         case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
2834                 index = ctx - ohci->ir_context_list;
2835                 ohci->ir_context_mask |= 1 << index;
2836                 ohci->ir_context_channels |= ohci->mc_channels;
2837                 ohci->mc_channels = 0;
2838                 ohci->mc_allocated = false;
2839                 break;
2840         }
2841
2842         spin_unlock_irqrestore(&ohci->lock, flags);
2843 }
2844
2845 static int ohci_set_iso_channels(struct fw_iso_context *base, u64 *channels)
2846 {
2847         struct fw_ohci *ohci = fw_ohci(base->card);
2848         unsigned long flags;
2849         int ret;
2850
2851         switch (base->type) {
2852         case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
2853
2854                 spin_lock_irqsave(&ohci->lock, flags);
2855
2856                 /* Don't allow multichannel to grab other contexts' channels. */
2857                 if (~ohci->ir_context_channels & ~ohci->mc_channels & *channels) {
2858                         *channels = ohci->ir_context_channels;
2859                         ret = -EBUSY;
2860                 } else {
2861                         set_multichannel_mask(ohci, *channels);
2862                         ret = 0;
2863                 }
2864
2865                 spin_unlock_irqrestore(&ohci->lock, flags);
2866
2867                 break;
2868         default:
2869                 ret = -EINVAL;
2870         }
2871
2872         return ret;
2873 }
2874
2875 #ifdef CONFIG_PM
2876 static void ohci_resume_iso_dma(struct fw_ohci *ohci)
2877 {
2878         int i;
2879         struct iso_context *ctx;
2880
2881         for (i = 0 ; i < ohci->n_ir ; i++) {
2882                 ctx = &ohci->ir_context_list[i];
2883                 if (ctx->context.running)
2884                         ohci_start_iso(&ctx->base, 0, ctx->sync, ctx->tags);
2885         }
2886
2887         for (i = 0 ; i < ohci->n_it ; i++) {
2888                 ctx = &ohci->it_context_list[i];
2889                 if (ctx->context.running)
2890                         ohci_start_iso(&ctx->base, 0, ctx->sync, ctx->tags);
2891         }
2892 }
2893 #endif
2894
2895 static int queue_iso_transmit(struct iso_context *ctx,
2896                               struct fw_iso_packet *packet,
2897                               struct fw_iso_buffer *buffer,
2898                               unsigned long payload)
2899 {
2900         struct descriptor *d, *last, *pd;
2901         struct fw_iso_packet *p;
2902         __le32 *header;
2903         dma_addr_t d_bus, page_bus;
2904         u32 z, header_z, payload_z, irq;
2905         u32 payload_index, payload_end_index, next_page_index;
2906         int page, end_page, i, length, offset;
2907
2908         p = packet;
2909         payload_index = payload;
2910
2911         if (p->skip)
2912                 z = 1;
2913         else
2914                 z = 2;
2915         if (p->header_length > 0)
2916                 z++;
2917
2918         /* Determine the first page the payload isn't contained in. */
2919         end_page = PAGE_ALIGN(payload_index + p->payload_length) >> PAGE_SHIFT;
2920         if (p->payload_length > 0)
2921                 payload_z = end_page - (payload_index >> PAGE_SHIFT);
2922         else
2923                 payload_z = 0;
2924
2925         z += payload_z;
2926
2927         /* Get header size in number of descriptors. */
2928         header_z = DIV_ROUND_UP(p->header_length, sizeof(*d));
2929
2930         d = context_get_descriptors(&ctx->context, z + header_z, &d_bus);
2931         if (d == NULL)
2932                 return -ENOMEM;
2933
2934         if (!p->skip) {
2935                 d[0].control   = cpu_to_le16(DESCRIPTOR_KEY_IMMEDIATE);
2936                 d[0].req_count = cpu_to_le16(8);
2937                 /*
2938                  * Link the skip address to this descriptor itself.  This causes
2939                  * a context to skip a cycle whenever lost cycles or FIFO
2940                  * overruns occur, without dropping the data.  The application
2941                  * should then decide whether this is an error condition or not.
2942                  * FIXME:  Make the context's cycle-lost behaviour configurable?
2943                  */
2944                 d[0].branch_address = cpu_to_le32(d_bus | z);
2945
2946                 header = (__le32 *) &d[1];
2947                 header[0] = cpu_to_le32(IT_HEADER_SY(p->sy) |
2948                                         IT_HEADER_TAG(p->tag) |
2949                                         IT_HEADER_TCODE(TCODE_STREAM_DATA) |
2950                                         IT_HEADER_CHANNEL(ctx->base.channel) |
2951                                         IT_HEADER_SPEED(ctx->base.speed));
2952                 header[1] =
2953                         cpu_to_le32(IT_HEADER_DATA_LENGTH(p->header_length +
2954                                                           p->payload_length));
2955         }
2956
2957         if (p->header_length > 0) {
2958                 d[2].req_count    = cpu_to_le16(p->header_length);
2959                 d[2].data_address = cpu_to_le32(d_bus + z * sizeof(*d));
2960                 memcpy(&d[z], p->header, p->header_length);
2961         }
2962
2963         pd = d + z - payload_z;
2964         payload_end_index = payload_index + p->payload_length;
2965         for (i = 0; i < payload_z; i++) {
2966                 page               = payload_index >> PAGE_SHIFT;
2967                 offset             = payload_index & ~PAGE_MASK;
2968                 next_page_index    = (page + 1) << PAGE_SHIFT;
2969                 length             =
2970                         min(next_page_index, payload_end_index) - payload_index;
2971                 pd[i].req_count    = cpu_to_le16(length);
2972
2973                 page_bus = page_private(buffer->pages[page]);
2974                 pd[i].data_address = cpu_to_le32(page_bus + offset);
2975
2976                 payload_index += length;
2977         }
2978
2979         if (p->interrupt)
2980                 irq = DESCRIPTOR_IRQ_ALWAYS;
2981         else
2982                 irq = DESCRIPTOR_NO_IRQ;
2983
2984         last = z == 2 ? d : d + z - 1;
2985         last->control |= cpu_to_le16(DESCRIPTOR_OUTPUT_LAST |
2986                                      DESCRIPTOR_STATUS |
2987                                      DESCRIPTOR_BRANCH_ALWAYS |
2988                                      irq);
2989
2990         context_append(&ctx->context, d, z, header_z);
2991
2992         return 0;
2993 }
2994
2995 static int queue_iso_packet_per_buffer(struct iso_context *ctx,
2996                                        struct fw_iso_packet *packet,
2997                                        struct fw_iso_buffer *buffer,
2998                                        unsigned long payload)
2999 {
3000         struct descriptor *d, *pd;
3001         dma_addr_t d_bus, page_bus;
3002         u32 z, header_z, rest;
3003         int i, j, length;
3004         int page, offset, packet_count, header_size, payload_per_buffer;
3005
3006         /*
3007          * The OHCI controller puts the isochronous header and trailer in the
3008          * buffer, so we need at least 8 bytes.
3009          */
3010         packet_count = packet->header_length / ctx->base.header_size;
3011         header_size  = max(ctx->base.header_size, (size_t)8);
3012
3013         /* Get header size in number of descriptors. */
3014         header_z = DIV_ROUND_UP(header_size, sizeof(*d));
3015         page     = payload >> PAGE_SHIFT;
3016         offset   = payload & ~PAGE_MASK;
3017         payload_per_buffer = packet->payload_length / packet_count;
3018
3019         for (i = 0; i < packet_count; i++) {
3020                 /* d points to the header descriptor */
3021                 z = DIV_ROUND_UP(payload_per_buffer + offset, PAGE_SIZE) + 1;
3022                 d = context_get_descriptors(&ctx->context,
3023                                 z + header_z, &d_bus);
3024                 if (d == NULL)
3025                         return -ENOMEM;
3026
3027                 d->control      = cpu_to_le16(DESCRIPTOR_STATUS |
3028                                               DESCRIPTOR_INPUT_MORE);
3029                 if (packet->skip && i == 0)
3030                         d->control |= cpu_to_le16(DESCRIPTOR_WAIT);
3031                 d->req_count    = cpu_to_le16(header_size);
3032                 d->res_count    = d->req_count;
3033                 d->transfer_status = 0;
3034                 d->data_address = cpu_to_le32(d_bus + (z * sizeof(*d)));
3035
3036                 rest = payload_per_buffer;
3037                 pd = d;
3038                 for (j = 1; j < z; j++) {
3039                         pd++;
3040                         pd->control = cpu_to_le16(DESCRIPTOR_STATUS |
3041                                                   DESCRIPTOR_INPUT_MORE);
3042
3043                         if (offset + rest < PAGE_SIZE)
3044                                 length = rest;
3045                         else
3046                                 length = PAGE_SIZE - offset;
3047                         pd->req_count = cpu_to_le16(length);
3048                         pd->res_count = pd->req_count;
3049                         pd->transfer_status = 0;
3050
3051                         page_bus = page_private(buffer->pages[page]);
3052                         pd->data_address = cpu_to_le32(page_bus + offset);
3053
3054                         offset = (offset + length) & ~PAGE_MASK;
3055                         rest -= length;
3056                         if (offset == 0)
3057                                 page++;
3058                 }
3059                 pd->control = cpu_to_le16(DESCRIPTOR_STATUS |
3060                                           DESCRIPTOR_INPUT_LAST |
3061                                           DESCRIPTOR_BRANCH_ALWAYS);
3062                 if (packet->interrupt && i == packet_count - 1)
3063                         pd->control |= cpu_to_le16(DESCRIPTOR_IRQ_ALWAYS);
3064
3065                 context_append(&ctx->context, d, z, header_z);
3066         }
3067
3068         return 0;
3069 }
3070
3071 static int queue_iso_buffer_fill(struct iso_context *ctx,
3072                                  struct fw_iso_packet *packet,
3073                                  struct fw_iso_buffer *buffer,
3074                                  unsigned long payload)
3075 {
3076         struct descriptor *d;
3077         dma_addr_t d_bus, page_bus;
3078         int page, offset, rest, z, i, length;
3079
3080         page   = payload >> PAGE_SHIFT;
3081         offset = payload & ~PAGE_MASK;
3082         rest   = packet->payload_length;
3083
3084         /* We need one descriptor for each page in the buffer. */
3085         z = DIV_ROUND_UP(offset + rest, PAGE_SIZE);
3086
3087         if (WARN_ON(offset & 3 || rest & 3 || page + z > buffer->page_count))
3088                 return -EFAULT;
3089
3090         for (i = 0; i < z; i++) {
3091                 d = context_get_descriptors(&ctx->context, 1, &d_bus);
3092                 if (d == NULL)
3093                         return -ENOMEM;
3094
3095                 d->control = cpu_to_le16(DESCRIPTOR_INPUT_MORE |
3096                                          DESCRIPTOR_BRANCH_ALWAYS);
3097                 if (packet->skip && i == 0)
3098                         d->control |= cpu_to_le16(DESCRIPTOR_WAIT);
3099                 if (packet->interrupt && i == z - 1)
3100                         d->control |= cpu_to_le16(DESCRIPTOR_IRQ_ALWAYS);
3101
3102                 if (offset + rest < PAGE_SIZE)
3103                         length = rest;
3104                 else
3105                         length = PAGE_SIZE - offset;
3106                 d->req_count = cpu_to_le16(length);
3107                 d->res_count = d->req_count;
3108                 d->transfer_status = 0;
3109
3110                 page_bus = page_private(buffer->pages[page]);
3111                 d->data_address = cpu_to_le32(page_bus + offset);
3112
3113                 rest -= length;
3114                 offset = 0;
3115                 page++;
3116
3117                 context_append(&ctx->context, d, 1, 0);
3118         }
3119
3120         return 0;
3121 }
3122
3123 static int ohci_queue_iso(struct fw_iso_context *base,
3124                           struct fw_iso_packet *packet,
3125                           struct fw_iso_buffer *buffer,
3126                           unsigned long payload)
3127 {
3128         struct iso_context *ctx = container_of(base, struct iso_context, base);
3129         unsigned long flags;
3130         int ret = -ENOSYS;
3131
3132         spin_lock_irqsave(&ctx->context.ohci->lock, flags);
3133         switch (base->type) {
3134         case FW_ISO_CONTEXT_TRANSMIT:
3135                 ret = queue_iso_transmit(ctx, packet, buffer, payload);
3136                 break;
3137         case FW_ISO_CONTEXT_RECEIVE:
3138                 ret = queue_iso_packet_per_buffer(ctx, packet, buffer, payload);
3139                 break;
3140         case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
3141                 ret = queue_iso_buffer_fill(ctx, packet, buffer, payload);
3142                 break;
3143         }
3144         spin_unlock_irqrestore(&ctx->context.ohci->lock, flags);
3145
3146         return ret;
3147 }
3148
3149 static void ohci_flush_queue_iso(struct fw_iso_context *base)
3150 {
3151         struct context *ctx =
3152                         &container_of(base, struct iso_context, base)->context;
3153
3154         reg_write(ctx->ohci, CONTROL_SET(ctx->regs), CONTEXT_WAKE);
3155 }
3156
3157 static const struct fw_card_driver ohci_driver = {
3158         .enable                 = ohci_enable,
3159         .read_phy_reg           = ohci_read_phy_reg,
3160         .update_phy_reg         = ohci_update_phy_reg,
3161         .set_config_rom         = ohci_set_config_rom,
3162         .send_request           = ohci_send_request,
3163         .send_response          = ohci_send_response,
3164         .cancel_packet          = ohci_cancel_packet,
3165         .enable_phys_dma        = ohci_enable_phys_dma,
3166         .read_csr               = ohci_read_csr,
3167         .write_csr              = ohci_write_csr,
3168
3169         .allocate_iso_context   = ohci_allocate_iso_context,
3170         .free_iso_context       = ohci_free_iso_context,
3171         .set_iso_channels       = ohci_set_iso_channels,
3172         .queue_iso              = ohci_queue_iso,
3173         .flush_queue_iso        = ohci_flush_queue_iso,
3174         .start_iso              = ohci_start_iso,
3175         .stop_iso               = ohci_stop_iso,
3176 };
3177
3178 #ifdef CONFIG_PPC_PMAC
3179 static void pmac_ohci_on(struct pci_dev *dev)
3180 {
3181         if (machine_is(powermac)) {
3182                 struct device_node *ofn = pci_device_to_OF_node(dev);
3183
3184                 if (ofn) {
3185                         pmac_call_feature(PMAC_FTR_1394_CABLE_POWER, ofn, 0, 1);
3186                         pmac_call_feature(PMAC_FTR_1394_ENABLE, ofn, 0, 1);
3187                 }
3188         }
3189 }
3190
3191 static void pmac_ohci_off(struct pci_dev *dev)
3192 {
3193         if (machine_is(powermac)) {
3194                 struct device_node *ofn = pci_device_to_OF_node(dev);
3195
3196                 if (ofn) {
3197                         pmac_call_feature(PMAC_FTR_1394_ENABLE, ofn, 0, 0);
3198                         pmac_call_feature(PMAC_FTR_1394_CABLE_POWER, ofn, 0, 0);
3199                 }
3200         }
3201 }
3202 #else
3203 static inline void pmac_ohci_on(struct pci_dev *dev) {}
3204 static inline void pmac_ohci_off(struct pci_dev *dev) {}
3205 #endif /* CONFIG_PPC_PMAC */
3206
3207 static int __devinit pci_probe(struct pci_dev *dev,
3208                                const struct pci_device_id *ent)
3209 {
3210         struct fw_ohci *ohci;
3211         u32 bus_options, max_receive, link_speed, version;
3212         u64 guid;
3213         int i, err;
3214         size_t size;
3215
3216         if (dev->vendor == PCI_VENDOR_ID_PINNACLE_SYSTEMS) {
3217                 dev_err(&dev->dev, "Pinnacle MovieBoard is not yet supported\n");
3218                 return -ENOSYS;
3219         }
3220
3221         ohci = kzalloc(sizeof(*ohci), GFP_KERNEL);
3222         if (ohci == NULL) {
3223                 err = -ENOMEM;
3224                 goto fail;
3225         }
3226
3227         fw_card_initialize(&ohci->card, &ohci_driver, &dev->dev);
3228
3229         pmac_ohci_on(dev);
3230
3231         err = pci_enable_device(dev);
3232         if (err) {
3233                 fw_error("Failed to enable OHCI hardware\n");
3234                 goto fail_free;
3235         }
3236
3237         pci_set_master(dev);
3238         pci_write_config_dword(dev, OHCI1394_PCI_HCI_Control, 0);
3239         pci_set_drvdata(dev, ohci);
3240
3241         spin_lock_init(&ohci->lock);
3242         mutex_init(&ohci->phy_reg_mutex);
3243
3244         INIT_WORK(&ohci->bus_reset_work, bus_reset_work);
3245
3246         err = pci_request_region(dev, 0, ohci_driver_name);
3247         if (err) {
3248                 fw_error("MMIO resource unavailable\n");
3249                 goto fail_disable;
3250         }
3251
3252         ohci->registers = pci_iomap(dev, 0, OHCI1394_REGISTER_SIZE);
3253         if (ohci->registers == NULL) {
3254                 fw_error("Failed to remap registers\n");
3255                 err = -ENXIO;
3256                 goto fail_iomem;
3257         }
3258
3259         for (i = 0; i < ARRAY_SIZE(ohci_quirks); i++)
3260                 if ((ohci_quirks[i].vendor == dev->vendor) &&
3261                     (ohci_quirks[i].device == (unsigned short)PCI_ANY_ID ||
3262                      ohci_quirks[i].device == dev->device) &&
3263                     (ohci_quirks[i].revision == (unsigned short)PCI_ANY_ID ||
3264                      ohci_quirks[i].revision >= dev->revision)) {
3265                         ohci->quirks = ohci_quirks[i].flags;
3266                         break;
3267                 }
3268         if (param_quirks)
3269                 ohci->quirks = param_quirks;
3270
3271         /*
3272          * Because dma_alloc_coherent() allocates at least one page,
3273          * we save space by using a common buffer for the AR request/
3274          * response descriptors and the self IDs buffer.
3275          */
3276         BUILD_BUG_ON(AR_BUFFERS * sizeof(struct descriptor) > PAGE_SIZE/4);
3277         BUILD_BUG_ON(SELF_ID_BUF_SIZE > PAGE_SIZE/2);
3278         ohci->misc_buffer = dma_alloc_coherent(ohci->card.device,
3279                                                PAGE_SIZE,
3280                                                &ohci->misc_buffer_bus,
3281                                                GFP_KERNEL);
3282         if (!ohci->misc_buffer) {
3283                 err = -ENOMEM;
3284                 goto fail_iounmap;
3285         }
3286
3287         err = ar_context_init(&ohci->ar_request_ctx, ohci, 0,
3288                               OHCI1394_AsReqRcvContextControlSet);
3289         if (err < 0)
3290                 goto fail_misc_buf;
3291
3292         err = ar_context_init(&ohci->ar_response_ctx, ohci, PAGE_SIZE/4,
3293                               OHCI1394_AsRspRcvContextControlSet);
3294         if (err < 0)
3295                 goto fail_arreq_ctx;
3296
3297         err = context_init(&ohci->at_request_ctx, ohci,
3298                            OHCI1394_AsReqTrContextControlSet, handle_at_packet);
3299         if (err < 0)
3300                 goto fail_arrsp_ctx;
3301
3302         err = context_init(&ohci->at_response_ctx, ohci,
3303                            OHCI1394_AsRspTrContextControlSet, handle_at_packet);
3304         if (err < 0)
3305                 goto fail_atreq_ctx;
3306
3307         reg_write(ohci, OHCI1394_IsoRecvIntMaskSet, ~0);
3308         ohci->ir_context_channels = ~0ULL;
3309         ohci->ir_context_support = reg_read(ohci, OHCI1394_IsoRecvIntMaskSet);
3310         reg_write(ohci, OHCI1394_IsoRecvIntMaskClear, ~0);
3311         ohci->ir_context_mask = ohci->ir_context_support;
3312         ohci->n_ir = hweight32(ohci->ir_context_mask);
3313         size = sizeof(struct iso_context) * ohci->n_ir;
3314         ohci->ir_context_list = kzalloc(size, GFP_KERNEL);
3315
3316         reg_write(ohci, OHCI1394_IsoXmitIntMaskSet, ~0);
3317         ohci->it_context_support = reg_read(ohci, OHCI1394_IsoXmitIntMaskSet);
3318         reg_write(ohci, OHCI1394_IsoXmitIntMaskClear, ~0);
3319         ohci->it_context_mask = ohci->it_context_support;
3320         ohci->n_it = hweight32(ohci->it_context_mask);
3321         size = sizeof(struct iso_context) * ohci->n_it;
3322         ohci->it_context_list = kzalloc(size, GFP_KERNEL);
3323
3324         if (ohci->it_context_list == NULL || ohci->ir_context_list == NULL) {
3325                 err = -ENOMEM;
3326                 goto fail_contexts;
3327         }
3328
3329         ohci->self_id_cpu = ohci->misc_buffer     + PAGE_SIZE/2;
3330         ohci->self_id_bus = ohci->misc_buffer_bus + PAGE_SIZE/2;
3331
3332         bus_options = reg_read(ohci, OHCI1394_BusOptions);
3333         max_receive = (bus_options >> 12) & 0xf;
3334         link_speed = bus_options & 0x7;
3335         guid = ((u64) reg_read(ohci, OHCI1394_GUIDHi) << 32) |
3336                 reg_read(ohci, OHCI1394_GUIDLo);
3337
3338         err = fw_card_add(&ohci->card, max_receive, link_speed, guid);
3339         if (err)
3340                 goto fail_contexts;
3341
3342         version = reg_read(ohci, OHCI1394_Version) & 0x00ff00ff;
3343         fw_notify("Added fw-ohci device %s, OHCI v%x.%x, "
3344                   "%d IR + %d IT contexts, quirks 0x%x\n",
3345                   dev_name(&dev->dev), version >> 16, version & 0xff,
3346                   ohci->n_ir, ohci->n_it, ohci->quirks);
3347
3348         return 0;
3349
3350  fail_contexts:
3351         kfree(ohci->ir_context_list);
3352         kfree(ohci->it_context_list);
3353         context_release(&ohci->at_response_ctx);
3354  fail_atreq_ctx:
3355         context_release(&ohci->at_request_ctx);
3356  fail_arrsp_ctx:
3357         ar_context_release(&ohci->ar_response_ctx);
3358  fail_arreq_ctx:
3359         ar_context_release(&ohci->ar_request_ctx);
3360  fail_misc_buf:
3361         dma_free_coherent(ohci->card.device, PAGE_SIZE,
3362                           ohci->misc_buffer, ohci->misc_buffer_bus);
3363  fail_iounmap:
3364         pci_iounmap(dev, ohci->registers);
3365  fail_iomem:
3366         pci_release_region(dev, 0);
3367  fail_disable:
3368         pci_disable_device(dev);
3369  fail_free:
3370         kfree(ohci);
3371         pmac_ohci_off(dev);
3372  fail:
3373         if (err == -ENOMEM)
3374                 fw_error("Out of memory\n");
3375
3376         return err;
3377 }
3378
3379 static void pci_remove(struct pci_dev *dev)
3380 {
3381         struct fw_ohci *ohci;
3382
3383         ohci = pci_get_drvdata(dev);
3384         reg_write(ohci, OHCI1394_IntMaskClear, ~0);
3385         flush_writes(ohci);
3386         cancel_work_sync(&ohci->bus_reset_work);
3387         fw_core_remove_card(&ohci->card);
3388
3389         /*
3390          * FIXME: Fail all pending packets here, now that the upper
3391          * layers can't queue any more.
3392          */
3393
3394         software_reset(ohci);
3395         free_irq(dev->irq, ohci);
3396
3397         if (ohci->next_config_rom && ohci->next_config_rom != ohci->config_rom)
3398                 dma_free_coherent(ohci->card.device, CONFIG_ROM_SIZE,
3399                                   ohci->next_config_rom, ohci->next_config_rom_bus);
3400         if (ohci->config_rom)
3401                 dma_free_coherent(ohci->card.device, CONFIG_ROM_SIZE,
3402                                   ohci->config_rom, ohci->config_rom_bus);
3403         ar_context_release(&ohci->ar_request_ctx);
3404         ar_context_release(&ohci->ar_response_ctx);
3405         dma_free_coherent(ohci->card.device, PAGE_SIZE,
3406                           ohci->misc_buffer, ohci->misc_buffer_bus);
3407         context_release(&ohci->at_request_ctx);
3408         context_release(&ohci->at_response_ctx);
3409         kfree(ohci->it_context_list);
3410         kfree(ohci->ir_context_list);
3411         pci_disable_msi(dev);
3412         pci_iounmap(dev, ohci->registers);
3413         pci_release_region(dev, 0);
3414         pci_disable_device(dev);
3415         kfree(ohci);
3416         pmac_ohci_off(dev);
3417
3418         fw_notify("Removed fw-ohci device.\n");
3419 }
3420
3421 #ifdef CONFIG_PM
3422 static int pci_suspend(struct pci_dev *dev, pm_message_t state)
3423 {
3424         struct fw_ohci *ohci = pci_get_drvdata(dev);
3425         int err;
3426
3427         software_reset(ohci);
3428         free_irq(dev->irq, ohci);
3429         pci_disable_msi(dev);
3430         err = pci_save_state(dev);
3431         if (err) {
3432                 fw_error("pci_save_state failed\n");
3433                 return err;
3434         }
3435         err = pci_set_power_state(dev, pci_choose_state(dev, state));
3436         if (err)
3437                 fw_error("pci_set_power_state failed with %d\n", err);
3438         pmac_ohci_off(dev);
3439
3440         return 0;
3441 }
3442
3443 static int pci_resume(struct pci_dev *dev)
3444 {
3445         struct fw_ohci *ohci = pci_get_drvdata(dev);
3446         int err;
3447
3448         pmac_ohci_on(dev);
3449         pci_set_power_state(dev, PCI_D0);
3450         pci_restore_state(dev);
3451         err = pci_enable_device(dev);
3452         if (err) {
3453                 fw_error("pci_enable_device failed\n");
3454                 return err;
3455         }
3456
3457         /* Some systems don't setup GUID register on resume from ram  */
3458         if (!reg_read(ohci, OHCI1394_GUIDLo) &&
3459                                         !reg_read(ohci, OHCI1394_GUIDHi)) {
3460                 reg_write(ohci, OHCI1394_GUIDLo, (u32)ohci->card.guid);
3461                 reg_write(ohci, OHCI1394_GUIDHi, (u32)(ohci->card.guid >> 32));
3462         }
3463
3464         err = ohci_enable(&ohci->card, NULL, 0);
3465         if (err)
3466                 return err;
3467
3468         ohci_resume_iso_dma(ohci);
3469
3470         return 0;
3471 }
3472 #endif
3473
3474 static const struct pci_device_id pci_table[] = {
3475         { PCI_DEVICE_CLASS(PCI_CLASS_SERIAL_FIREWIRE_OHCI, ~0) },
3476         { }
3477 };
3478
3479 MODULE_DEVICE_TABLE(pci, pci_table);
3480
3481 static struct pci_driver fw_ohci_pci_driver = {
3482         .name           = ohci_driver_name,
3483         .id_table       = pci_table,
3484         .probe          = pci_probe,
3485         .remove         = pci_remove,
3486 #ifdef CONFIG_PM
3487         .resume         = pci_resume,
3488         .suspend        = pci_suspend,
3489 #endif
3490 };
3491
3492 MODULE_AUTHOR("Kristian Hoegsberg <krh@bitplanet.net>");
3493 MODULE_DESCRIPTION("Driver for PCI OHCI IEEE1394 controllers");
3494 MODULE_LICENSE("GPL");
3495
3496 /* Provide a module alias so root-on-sbp2 initrds don't break. */
3497 #ifndef CONFIG_IEEE1394_OHCI1394_MODULE
3498 MODULE_ALIAS("ohci1394");
3499 #endif
3500
3501 static int __init fw_ohci_init(void)
3502 {
3503         return pci_register_driver(&fw_ohci_pci_driver);
3504 }
3505
3506 static void __exit fw_ohci_cleanup(void)
3507 {
3508         pci_unregister_driver(&fw_ohci_pci_driver);
3509 }
3510
3511 module_init(fw_ohci_init);
3512 module_exit(fw_ohci_cleanup);