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