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