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