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