xref: /linux/drivers/firewire/ohci.c (revision f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80)
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 	unsigned long flags;
1597 
1598 	spin_lock_irqsave(&local->lock, flags);
1599 
1600 	while ((packet = list_first_entry_or_null(&local->list, typeof(*packet), link_for_local))) {
1601 		list_del_init(&packet->link_for_local);
1602 		spin_unlock_irqrestore(&local->lock, flags);
1603 
1604 		if (unlikely(packet->ack != 0)) {
1605 			// This case is active when the call of at_context_queue_packet() returns
1606 			// error in at_context_transmit().
1607 			packet->callback(packet, &ohci->card, packet->ack);
1608 		} else {
1609 			handle_at_local_packet(ohci, packet);
1610 		}
1611 
1612 		spin_lock_irqsave(&local->lock, flags);
1613 	}
1614 
1615 	spin_unlock_irqrestore(&local->lock, flags);
1616 }
1617 
1618 static void at_request_local_work(struct work_struct *work)
1619 {
1620 	struct at_local *local = from_work(local, work, work);
1621 	struct fw_ohci *ohci = container_of(local, struct fw_ohci, at_request_local);
1622 
1623 	handle_at_local_packets(local, ohci, handle_at_request_local_packet);
1624 }
1625 
1626 static void at_response_local_work(struct work_struct *work)
1627 {
1628 	struct at_local *local = from_work(local, work, work);
1629 	struct fw_ohci *ohci = container_of(local, struct fw_ohci, at_response_local);
1630 
1631 	handle_at_local_packets(local, ohci, handle_at_response_local_packet);
1632 }
1633 
1634 static void at_local_init(struct at_local *local, work_func_t func)
1635 {
1636 	spin_lock_init(&local->lock);
1637 	INIT_LIST_HEAD(&local->list);
1638 	INIT_WORK(&local->work, func);
1639 }
1640 
1641 static bool destination_is_local(const struct fw_packet *packet, const struct fw_ohci *ohci)
1642 __must_hold(&ohci->lock)
1643 {
1644 	lockdep_assert_held(&ohci->lock);
1645 
1646 	return (async_header_get_destination(packet->header) == ohci->node_id &&
1647 		ohci->generation == packet->generation);
1648 }
1649 
1650 static void queue_work_for_at_local_packet(struct at_context *ctx, struct fw_packet *packet,
1651 					   struct fw_ohci *ohci)
1652 {
1653 	struct at_local *local;
1654 
1655 	if (ctx == &ohci->at_request_ctx)
1656 		local = &ohci->at_request_local;
1657 	else
1658 		local = &ohci->at_response_local;
1659 
1660 	// Timestamping on behalf of the hardware.
1661 	packet->timestamp = cycle_time_to_ohci_tstamp(get_cycle_time(ohci));
1662 
1663 	scoped_guard(spinlock_irqsave, &local->lock)
1664 		list_add_tail(&packet->link_for_local, &local->list);
1665 	queue_work(ohci->card.async_wq, &local->work);
1666 }
1667 
1668 static void at_context_transmit(struct at_context *ctx, struct fw_packet *packet)
1669 {
1670 	struct fw_ohci *ohci = ctx->context.ohci;
1671 	bool use_work = true;
1672 
1673 	// These members are used to cancel the packet.
1674 	packet->driver_data = NULL;
1675 	INIT_LIST_HEAD(&packet->link_for_local);
1676 
1677 	scoped_guard(spinlock_irqsave, &ohci->lock) {
1678 		if (!destination_is_local(packet, ohci)) {
1679 			if (!at_context_queue_packet(ctx, packet))
1680 				use_work = false;
1681 		}
1682 	}
1683 
1684 	if (use_work)
1685 		queue_work_for_at_local_packet(ctx, packet, ohci);
1686 }
1687 
1688 static void detect_dead_context(struct fw_ohci *ohci,
1689 				const char *name, unsigned int regs)
1690 {
1691 	static const char *const evts[] = {
1692 		[0x00] = "evt_no_status",	[0x01] = "-reserved-",
1693 		[0x02] = "evt_long_packet",	[0x03] = "evt_missing_ack",
1694 		[0x04] = "evt_underrun",	[0x05] = "evt_overrun",
1695 		[0x06] = "evt_descriptor_read",	[0x07] = "evt_data_read",
1696 		[0x08] = "evt_data_write",	[0x09] = "evt_bus_reset",
1697 		[0x0a] = "evt_timeout",		[0x0b] = "evt_tcode_err",
1698 		[0x0c] = "-reserved-",		[0x0d] = "-reserved-",
1699 		[0x0e] = "evt_unknown",		[0x0f] = "evt_flushed",
1700 		[0x10] = "-reserved-",		[0x11] = "ack_complete",
1701 		[0x12] = "ack_pending ",	[0x13] = "-reserved-",
1702 		[0x14] = "ack_busy_X",		[0x15] = "ack_busy_A",
1703 		[0x16] = "ack_busy_B",		[0x17] = "-reserved-",
1704 		[0x18] = "-reserved-",		[0x19] = "-reserved-",
1705 		[0x1a] = "-reserved-",		[0x1b] = "ack_tardy",
1706 		[0x1c] = "-reserved-",		[0x1d] = "ack_data_error",
1707 		[0x1e] = "ack_type_error",	[0x1f] = "-reserved-",
1708 		[0x20] = "pending/cancelled",
1709 	};
1710 	u32 ctl;
1711 
1712 	ctl = reg_read(ohci, CONTROL_SET(regs));
1713 	if (ctl & CONTEXT_DEAD)
1714 		ohci_err(ohci, "DMA context %s has stopped, error code: %s\n",
1715 			name, evts[ctl & 0x1f]);
1716 }
1717 
1718 static void handle_dead_contexts(struct fw_ohci *ohci)
1719 {
1720 	unsigned int i;
1721 	char name[8];
1722 
1723 	detect_dead_context(ohci, "ATReq", OHCI1394_AsReqTrContextBase);
1724 	detect_dead_context(ohci, "ATRsp", OHCI1394_AsRspTrContextBase);
1725 	detect_dead_context(ohci, "ARReq", OHCI1394_AsReqRcvContextBase);
1726 	detect_dead_context(ohci, "ARRsp", OHCI1394_AsRspRcvContextBase);
1727 	for (i = 0; i < 32; ++i) {
1728 		if (!(ohci->it_context_support & (1 << i)))
1729 			continue;
1730 		sprintf(name, "IT%u", i);
1731 		detect_dead_context(ohci, name, OHCI1394_IsoXmitContextBase(i));
1732 	}
1733 	for (i = 0; i < 32; ++i) {
1734 		if (!(ohci->ir_context_support & (1 << i)))
1735 			continue;
1736 		sprintf(name, "IR%u", i);
1737 		detect_dead_context(ohci, name, OHCI1394_IsoRcvContextBase(i));
1738 	}
1739 	/* TODO: maybe try to flush and restart the dead contexts */
1740 }
1741 
1742 static u32 cycle_timer_ticks(u32 cycle_timer)
1743 {
1744 	u32 ticks;
1745 
1746 	ticks = cycle_timer & 0xfff;
1747 	ticks += 3072 * ((cycle_timer >> 12) & 0x1fff);
1748 	ticks += (3072 * 8000) * (cycle_timer >> 25);
1749 
1750 	return ticks;
1751 }
1752 
1753 /*
1754  * Some controllers exhibit one or more of the following bugs when updating the
1755  * iso cycle timer register:
1756  *  - When the lowest six bits are wrapping around to zero, a read that happens
1757  *    at the same time will return garbage in the lowest ten bits.
1758  *  - When the cycleOffset field wraps around to zero, the cycleCount field is
1759  *    not incremented for about 60 ns.
1760  *  - Occasionally, the entire register reads zero.
1761  *
1762  * To catch these, we read the register three times and ensure that the
1763  * difference between each two consecutive reads is approximately the same, i.e.
1764  * less than twice the other.  Furthermore, any negative difference indicates an
1765  * error.  (A PCI read should take at least 20 ticks of the 24.576 MHz timer to
1766  * execute, so we have enough precision to compute the ratio of the differences.)
1767  */
1768 static u32 get_cycle_time(struct fw_ohci *ohci)
1769 {
1770 	u32 c0, c1, c2;
1771 	u32 t0, t1, t2;
1772 	s32 diff01, diff12;
1773 	int i;
1774 
1775 	if (has_reboot_by_cycle_timer_read_quirk(ohci))
1776 		return 0;
1777 
1778 	c2 = reg_read(ohci, OHCI1394_IsochronousCycleTimer);
1779 
1780 	if (ohci->quirks & QUIRK_CYCLE_TIMER) {
1781 		i = 0;
1782 		c1 = c2;
1783 		c2 = reg_read(ohci, OHCI1394_IsochronousCycleTimer);
1784 		do {
1785 			c0 = c1;
1786 			c1 = c2;
1787 			c2 = reg_read(ohci, OHCI1394_IsochronousCycleTimer);
1788 			t0 = cycle_timer_ticks(c0);
1789 			t1 = cycle_timer_ticks(c1);
1790 			t2 = cycle_timer_ticks(c2);
1791 			diff01 = t1 - t0;
1792 			diff12 = t2 - t1;
1793 		} while ((diff01 <= 0 || diff12 <= 0 ||
1794 			  diff01 / diff12 >= 2 || diff12 / diff01 >= 2)
1795 			 && i++ < 20);
1796 	}
1797 
1798 	return c2;
1799 }
1800 
1801 /*
1802  * This function has to be called at least every 64 seconds.  The bus_time
1803  * field stores not only the upper 25 bits of the BUS_TIME register but also
1804  * the most significant bit of the cycle timer in bit 6 so that we can detect
1805  * changes in this bit.
1806  */
1807 static u32 update_bus_time(struct fw_ohci *ohci)
1808 {
1809 	u32 cycle_time_seconds = get_cycle_time(ohci) >> 25;
1810 
1811 	if (unlikely(!ohci->bus_time_running)) {
1812 		reg_write(ohci, OHCI1394_IntMaskSet, OHCI1394_cycle64Seconds);
1813 		ohci->bus_time = (lower_32_bits(ktime_get_seconds()) & ~0x7f) |
1814 		                 (cycle_time_seconds & 0x40);
1815 		ohci->bus_time_running = true;
1816 	}
1817 
1818 	if ((ohci->bus_time & 0x40) != (cycle_time_seconds & 0x40))
1819 		ohci->bus_time += 0x40;
1820 
1821 	return ohci->bus_time | cycle_time_seconds;
1822 }
1823 
1824 static int get_status_for_port(struct fw_ohci *ohci, int port_index,
1825 			       enum phy_packet_self_id_port_status *status)
1826 {
1827 	int reg;
1828 
1829 	scoped_guard(mutex, &ohci->phy_reg_mutex) {
1830 		reg = write_phy_reg(ohci, 7, port_index);
1831 		if (reg < 0)
1832 			return reg;
1833 
1834 		reg = read_phy_reg(ohci, 8);
1835 		if (reg < 0)
1836 			return reg;
1837 	}
1838 
1839 	switch (reg & 0x0f) {
1840 	case 0x06:
1841 		// is child node (connected to parent node)
1842 		*status = PHY_PACKET_SELF_ID_PORT_STATUS_PARENT;
1843 		break;
1844 	case 0x0e:
1845 		// is parent node (connected to child node)
1846 		*status = PHY_PACKET_SELF_ID_PORT_STATUS_CHILD;
1847 		break;
1848 	default:
1849 		// not connected
1850 		*status = PHY_PACKET_SELF_ID_PORT_STATUS_NCONN;
1851 		break;
1852 	}
1853 
1854 	return 0;
1855 }
1856 
1857 static int get_self_id_pos(struct fw_ohci *ohci, u32 self_id,
1858 	int self_id_count)
1859 {
1860 	unsigned int left_phy_id = phy_packet_self_id_get_phy_id(self_id);
1861 	int i;
1862 
1863 	for (i = 0; i < self_id_count; i++) {
1864 		u32 entry = ohci->self_id_buffer[i];
1865 		unsigned int right_phy_id = phy_packet_self_id_get_phy_id(entry);
1866 
1867 		if (left_phy_id == right_phy_id)
1868 			return -1;
1869 		if (left_phy_id < right_phy_id)
1870 			return i;
1871 	}
1872 	return i;
1873 }
1874 
1875 static int detect_initiated_reset(struct fw_ohci *ohci, bool *is_initiated_reset)
1876 {
1877 	int reg;
1878 
1879 	guard(mutex)(&ohci->phy_reg_mutex);
1880 
1881 	// Select page 7
1882 	reg = write_phy_reg(ohci, 7, 0xe0);
1883 	if (reg < 0)
1884 		return reg;
1885 
1886 	reg = read_phy_reg(ohci, 8);
1887 	if (reg < 0)
1888 		return reg;
1889 
1890 	// set PMODE bit
1891 	reg |= 0x40;
1892 	reg = write_phy_reg(ohci, 8, reg);
1893 	if (reg < 0)
1894 		return reg;
1895 
1896 	// read register 12
1897 	reg = read_phy_reg(ohci, 12);
1898 	if (reg < 0)
1899 		return reg;
1900 
1901 	// bit 3 indicates "initiated reset"
1902 	*is_initiated_reset = !!((reg & 0x08) == 0x08);
1903 
1904 	return 0;
1905 }
1906 
1907 /*
1908  * TI TSB82AA2B and TSB12LV26 do not receive the selfID of a locally
1909  * attached TSB41BA3D phy; see http://www.ti.com/litv/pdf/sllz059.
1910  * Construct the selfID from phy register contents.
1911  */
1912 static int find_and_insert_self_id(struct fw_ohci *ohci, int self_id_count)
1913 {
1914 	int reg, i, pos, err;
1915 	bool is_initiated_reset;
1916 	u32 self_id = 0;
1917 
1918 	// link active 1, speed 3, bridge 0, contender 1, more packets 0.
1919 	phy_packet_set_packet_identifier(&self_id, PHY_PACKET_PACKET_IDENTIFIER_SELF_ID);
1920 	phy_packet_self_id_zero_set_link_active(&self_id, true);
1921 	phy_packet_self_id_zero_set_scode(&self_id, SCODE_800);
1922 	phy_packet_self_id_zero_set_contender(&self_id, true);
1923 
1924 	reg = reg_read(ohci, OHCI1394_NodeID);
1925 	if (!(reg & OHCI1394_NodeID_idValid)) {
1926 		ohci_notice(ohci,
1927 			    "node ID not valid, new bus reset in progress\n");
1928 		return -EBUSY;
1929 	}
1930 	phy_packet_self_id_set_phy_id(&self_id, reg & 0x3f);
1931 
1932 	reg = ohci_read_phy_reg(&ohci->card, 4);
1933 	if (reg < 0)
1934 		return reg;
1935 	phy_packet_self_id_zero_set_power_class(&self_id, reg & 0x07);
1936 
1937 	reg = ohci_read_phy_reg(&ohci->card, 1);
1938 	if (reg < 0)
1939 		return reg;
1940 	phy_packet_self_id_zero_set_gap_count(&self_id, reg & 0x3f);
1941 
1942 	for (i = 0; i < 3; i++) {
1943 		enum phy_packet_self_id_port_status status;
1944 
1945 		err = get_status_for_port(ohci, i, &status);
1946 		if (err < 0)
1947 			return err;
1948 
1949 		self_id_sequence_set_port_status(&self_id, 1, i, status);
1950 	}
1951 
1952 	err = detect_initiated_reset(ohci, &is_initiated_reset);
1953 	if (err < 0)
1954 		return err;
1955 	phy_packet_self_id_zero_set_initiated_reset(&self_id, is_initiated_reset);
1956 
1957 	pos = get_self_id_pos(ohci, self_id, self_id_count);
1958 	if (pos >= 0) {
1959 		memmove(&(ohci->self_id_buffer[pos+1]),
1960 			&(ohci->self_id_buffer[pos]),
1961 			(self_id_count - pos) * sizeof(*ohci->self_id_buffer));
1962 		ohci->self_id_buffer[pos] = self_id;
1963 		self_id_count++;
1964 	}
1965 	return self_id_count;
1966 }
1967 
1968 static irqreturn_t handle_selfid_complete_event(int irq, void *data)
1969 {
1970 	struct fw_ohci *ohci = data;
1971 	int self_id_count, generation, new_generation, i, j;
1972 	u32 reg, quadlet;
1973 	void *free_rom = NULL;
1974 	dma_addr_t free_rom_bus = 0;
1975 	bool is_new_root;
1976 
1977 	reg = reg_read(ohci, OHCI1394_NodeID);
1978 	if (!(reg & OHCI1394_NodeID_idValid)) {
1979 		ohci_notice(ohci,
1980 			    "node ID not valid, new bus reset in progress\n");
1981 		goto end;
1982 	}
1983 	if ((reg & OHCI1394_NodeID_nodeNumber) == 63) {
1984 		ohci_notice(ohci, "malconfigured bus\n");
1985 		goto end;
1986 	}
1987 	ohci->node_id = reg & (OHCI1394_NodeID_busNumber |
1988 			       OHCI1394_NodeID_nodeNumber);
1989 
1990 	is_new_root = (reg & OHCI1394_NodeID_root) != 0;
1991 	if (!(ohci->is_root && is_new_root))
1992 		reg_write(ohci, OHCI1394_LinkControlSet,
1993 			  OHCI1394_LinkControl_cycleMaster);
1994 	ohci->is_root = is_new_root;
1995 
1996 	reg = reg_read(ohci, OHCI1394_SelfIDCount);
1997 	if (ohci1394_self_id_count_is_error(reg)) {
1998 		ohci_notice(ohci, "self ID receive error\n");
1999 		goto end;
2000 	}
2001 
2002 	trace_self_id_complete(ohci->card.index, reg, ohci->self_id, has_be_header_quirk(ohci));
2003 
2004 	/*
2005 	 * The count in the SelfIDCount register is the number of
2006 	 * bytes in the self ID receive buffer.  Since we also receive
2007 	 * the inverted quadlets and a header quadlet, we shift one
2008 	 * bit extra to get the actual number of self IDs.
2009 	 */
2010 	self_id_count = ohci1394_self_id_count_get_size(reg) >> 1;
2011 
2012 	if (self_id_count > 252) {
2013 		ohci_notice(ohci, "bad selfIDSize (%08x)\n", reg);
2014 		goto end;
2015 	}
2016 
2017 	quadlet = cond_le32_to_cpu(ohci->self_id[0], has_be_header_quirk(ohci));
2018 	generation = ohci1394_self_id_receive_q0_get_generation(quadlet);
2019 	rmb();
2020 
2021 	for (i = 1, j = 0; j < self_id_count; i += 2, j++) {
2022 		u32 id  = cond_le32_to_cpu(ohci->self_id[i], has_be_header_quirk(ohci));
2023 		u32 id2 = cond_le32_to_cpu(ohci->self_id[i + 1], has_be_header_quirk(ohci));
2024 
2025 		if (id != ~id2) {
2026 			/*
2027 			 * If the invalid data looks like a cycle start packet,
2028 			 * it's likely to be the result of the cycle master
2029 			 * having a wrong gap count.  In this case, the self IDs
2030 			 * so far are valid and should be processed so that the
2031 			 * bus manager can then correct the gap count.
2032 			 */
2033 			if (id == 0xffff008f) {
2034 				ohci_notice(ohci, "ignoring spurious self IDs\n");
2035 				self_id_count = j;
2036 				break;
2037 			}
2038 
2039 			ohci_notice(ohci, "bad self ID %d/%d (%08x != ~%08x)\n",
2040 				    j, self_id_count, id, id2);
2041 			goto end;
2042 		}
2043 		ohci->self_id_buffer[j] = id;
2044 	}
2045 
2046 	if (ohci->quirks & QUIRK_TI_SLLZ059) {
2047 		self_id_count = find_and_insert_self_id(ohci, self_id_count);
2048 		if (self_id_count < 0) {
2049 			ohci_notice(ohci,
2050 				    "could not construct local self ID\n");
2051 			goto end;
2052 		}
2053 	}
2054 
2055 	if (self_id_count == 0) {
2056 		ohci_notice(ohci, "no self IDs\n");
2057 		goto end;
2058 	}
2059 	rmb();
2060 
2061 	/*
2062 	 * Check the consistency of the self IDs we just read.  The
2063 	 * problem we face is that a new bus reset can start while we
2064 	 * read out the self IDs from the DMA buffer. If this happens,
2065 	 * the DMA buffer will be overwritten with new self IDs and we
2066 	 * will read out inconsistent data.  The OHCI specification
2067 	 * (section 11.2) recommends a technique similar to
2068 	 * linux/seqlock.h, where we remember the generation of the
2069 	 * self IDs in the buffer before reading them out and compare
2070 	 * it to the current generation after reading them out.  If
2071 	 * the two generations match we know we have a consistent set
2072 	 * of self IDs.
2073 	 */
2074 
2075 	reg = reg_read(ohci, OHCI1394_SelfIDCount);
2076 	new_generation = ohci1394_self_id_count_get_generation(reg);
2077 	if (new_generation != generation) {
2078 		ohci_notice(ohci, "new bus reset, discarding self ids\n");
2079 		goto end;
2080 	}
2081 
2082 	// FIXME: Document how the locking works.
2083 	scoped_guard(spinlock_irq, &ohci->lock) {
2084 		ohci->generation = -1; // prevent AT packet queueing
2085 		context_stop(&ohci->at_request_ctx.context);
2086 		context_stop(&ohci->at_response_ctx.context);
2087 	}
2088 
2089 	/*
2090 	 * Per OHCI 1.2 draft, clause 7.2.3.3, hardware may leave unsent
2091 	 * packets in the AT queues and software needs to drain them.
2092 	 * Some OHCI 1.1 controllers (JMicron) apparently require this too.
2093 	 */
2094 	at_context_flush(&ohci->at_request_ctx);
2095 	at_context_flush(&ohci->at_response_ctx);
2096 
2097 	scoped_guard(spinlock_irq, &ohci->lock) {
2098 		ohci->generation = generation;
2099 		reg_write(ohci, OHCI1394_IntEventClear, OHCI1394_busReset);
2100 		reg_write(ohci, OHCI1394_IntMaskSet, OHCI1394_busReset);
2101 
2102 		if (ohci->quirks & QUIRK_RESET_PACKET)
2103 			ohci->request_generation = generation;
2104 
2105 		// This next bit is unrelated to the AT context stuff but we have to do it under the
2106 		// spinlock also. If a new config rom was set up before this reset, the old one is
2107 		// now no longer in use and we can free it. Update the config rom pointers to point
2108 		// to the current config rom and clear the next_config_rom pointer so a new update
2109 		// can take place.
2110 		if (ohci->next_config_rom != NULL) {
2111 			if (ohci->next_config_rom != ohci->config_rom) {
2112 				free_rom      = ohci->config_rom;
2113 				free_rom_bus  = ohci->config_rom_bus;
2114 			}
2115 			ohci->config_rom      = ohci->next_config_rom;
2116 			ohci->config_rom_bus  = ohci->next_config_rom_bus;
2117 			ohci->next_config_rom = NULL;
2118 
2119 			// Restore config_rom image and manually update config_rom registers.
2120 			// Writing the header quadlet will indicate that the config rom is ready,
2121 			// so we do that last.
2122 			reg_write(ohci, OHCI1394_BusOptions, be32_to_cpu(ohci->config_rom[2]));
2123 			ohci->config_rom[0] = ohci->next_header;
2124 			reg_write(ohci, OHCI1394_ConfigROMhdr, be32_to_cpu(ohci->next_header));
2125 		}
2126 
2127 		if (param_remote_dma) {
2128 			reg_write(ohci, OHCI1394_PhyReqFilterHiSet, ~0);
2129 			reg_write(ohci, OHCI1394_PhyReqFilterLoSet, ~0);
2130 		}
2131 	}
2132 
2133 	if (free_rom)
2134 		dmam_free_coherent(ohci->card.device, CONFIG_ROM_SIZE, free_rom, free_rom_bus);
2135 
2136 	fw_core_handle_bus_reset(&ohci->card, ohci->node_id, generation,
2137 				 self_id_count, ohci->self_id_buffer,
2138 				 ohci->csr_state_setclear_abdicate);
2139 	ohci->csr_state_setclear_abdicate = false;
2140 end:
2141 	return IRQ_HANDLED;
2142 }
2143 
2144 static irqreturn_t irq_handler(int irq, void *data)
2145 {
2146 	struct fw_ohci *ohci = data;
2147 	u32 event, iso_event;
2148 	int i;
2149 
2150 	event = reg_read(ohci, OHCI1394_IntEventClear);
2151 
2152 	if (!event || !~event)
2153 		return IRQ_NONE;
2154 
2155 	/*
2156 	 * busReset and postedWriteErr events must not be cleared yet
2157 	 * (OHCI 1.1 clauses 7.2.3.2 and 13.2.8.1)
2158 	 */
2159 	reg_write(ohci, OHCI1394_IntEventClear,
2160 		  event & ~(OHCI1394_busReset | OHCI1394_postedWriteErr));
2161 	trace_irqs(ohci->card.index, event);
2162 
2163 	// The flag is masked again at handle_selfid_complete_event() scheduled by selfID event.
2164 	if (event & OHCI1394_busReset)
2165 		reg_write(ohci, OHCI1394_IntMaskClear, OHCI1394_busReset);
2166 
2167 	if (event & OHCI1394_RQPkt)
2168 		queue_work(ohci->card.async_wq, &ohci->ar_request_ctx.work);
2169 
2170 	if (event & OHCI1394_RSPkt)
2171 		queue_work(ohci->card.async_wq, &ohci->ar_response_ctx.work);
2172 
2173 	if (event & OHCI1394_reqTxComplete)
2174 		queue_work(ohci->card.async_wq, &ohci->at_request_ctx.work);
2175 
2176 	if (event & OHCI1394_respTxComplete)
2177 		queue_work(ohci->card.async_wq, &ohci->at_response_ctx.work);
2178 
2179 	if (event & OHCI1394_isochRx) {
2180 		iso_event = reg_read(ohci, OHCI1394_IsoRecvIntEventClear);
2181 		reg_write(ohci, OHCI1394_IsoRecvIntEventClear, iso_event);
2182 
2183 		while (iso_event) {
2184 			i = ffs(iso_event) - 1;
2185 			fw_iso_context_schedule_flush_completions(&ohci->ir_context_list[i].base);
2186 			iso_event &= ~(1 << i);
2187 		}
2188 	}
2189 
2190 	if (event & OHCI1394_isochTx) {
2191 		iso_event = reg_read(ohci, OHCI1394_IsoXmitIntEventClear);
2192 		reg_write(ohci, OHCI1394_IsoXmitIntEventClear, iso_event);
2193 
2194 		while (iso_event) {
2195 			i = ffs(iso_event) - 1;
2196 			fw_iso_context_schedule_flush_completions(&ohci->it_context_list[i].base);
2197 			iso_event &= ~(1 << i);
2198 		}
2199 	}
2200 
2201 	if (unlikely(event & OHCI1394_regAccessFail))
2202 		ohci_err(ohci, "register access failure\n");
2203 
2204 	if (unlikely(event & OHCI1394_postedWriteErr)) {
2205 		reg_read(ohci, OHCI1394_PostedWriteAddressHi);
2206 		reg_read(ohci, OHCI1394_PostedWriteAddressLo);
2207 		reg_write(ohci, OHCI1394_IntEventClear,
2208 			  OHCI1394_postedWriteErr);
2209 		dev_err_ratelimited(ohci->card.device, "PCI posted write error\n");
2210 	}
2211 
2212 	if (unlikely(event & OHCI1394_cycleTooLong)) {
2213 		dev_notice_ratelimited(ohci->card.device, "isochronous cycle too long\n");
2214 		reg_write(ohci, OHCI1394_LinkControlSet,
2215 			  OHCI1394_LinkControl_cycleMaster);
2216 	}
2217 
2218 	if (unlikely(event & OHCI1394_cycleInconsistent)) {
2219 		/*
2220 		 * We need to clear this event bit in order to make
2221 		 * cycleMatch isochronous I/O work.  In theory we should
2222 		 * stop active cycleMatch iso contexts now and restart
2223 		 * them at least two cycles later.  (FIXME?)
2224 		 */
2225 		dev_notice_ratelimited(ohci->card.device, "isochronous cycle inconsistent\n");
2226 	}
2227 
2228 	if (unlikely(event & OHCI1394_unrecoverableError))
2229 		handle_dead_contexts(ohci);
2230 
2231 	if (event & OHCI1394_cycle64Seconds) {
2232 		guard(spinlock)(&ohci->lock);
2233 		update_bus_time(ohci);
2234 	} else
2235 		flush_writes(ohci);
2236 
2237 	if (event & OHCI1394_selfIDComplete)
2238 		return IRQ_WAKE_THREAD;
2239 	else
2240 		return IRQ_HANDLED;
2241 }
2242 
2243 static int software_reset(struct fw_ohci *ohci)
2244 {
2245 	u32 val;
2246 	int i;
2247 
2248 	reg_write(ohci, OHCI1394_HCControlSet, OHCI1394_HCControl_softReset);
2249 	for (i = 0; i < 500; i++) {
2250 		val = reg_read(ohci, OHCI1394_HCControlSet);
2251 		if (!~val)
2252 			return -ENODEV; /* Card was ejected. */
2253 
2254 		if (!(val & OHCI1394_HCControl_softReset))
2255 			return 0;
2256 
2257 		msleep(1);
2258 	}
2259 
2260 	return -EBUSY;
2261 }
2262 
2263 static void copy_config_rom(__be32 *dest, const __be32 *src, size_t length)
2264 {
2265 	size_t size = length * 4;
2266 
2267 	memcpy(dest, src, size);
2268 	if (size < CONFIG_ROM_SIZE)
2269 		memset(&dest[length], 0, CONFIG_ROM_SIZE - size);
2270 }
2271 
2272 static int configure_1394a_enhancements(struct fw_ohci *ohci)
2273 {
2274 	bool enable_1394a;
2275 	int ret, clear, set, offset;
2276 
2277 	/* Check if the driver should configure link and PHY. */
2278 	if (!(reg_read(ohci, OHCI1394_HCControlSet) &
2279 	      OHCI1394_HCControl_programPhyEnable))
2280 		return 0;
2281 
2282 	/* Paranoia: check whether the PHY supports 1394a, too. */
2283 	enable_1394a = false;
2284 	ret = read_phy_reg(ohci, 2);
2285 	if (ret < 0)
2286 		return ret;
2287 	if ((ret & PHY_EXTENDED_REGISTERS) == PHY_EXTENDED_REGISTERS) {
2288 		ret = read_paged_phy_reg(ohci, 1, 8);
2289 		if (ret < 0)
2290 			return ret;
2291 		if (ret >= 1)
2292 			enable_1394a = true;
2293 	}
2294 
2295 	if (ohci->quirks & QUIRK_NO_1394A)
2296 		enable_1394a = false;
2297 
2298 	/* Configure PHY and link consistently. */
2299 	if (enable_1394a) {
2300 		clear = 0;
2301 		set = PHY_ENABLE_ACCEL | PHY_ENABLE_MULTI;
2302 	} else {
2303 		clear = PHY_ENABLE_ACCEL | PHY_ENABLE_MULTI;
2304 		set = 0;
2305 	}
2306 	ret = update_phy_reg(ohci, 5, clear, set);
2307 	if (ret < 0)
2308 		return ret;
2309 
2310 	if (enable_1394a)
2311 		offset = OHCI1394_HCControlSet;
2312 	else
2313 		offset = OHCI1394_HCControlClear;
2314 	reg_write(ohci, offset, OHCI1394_HCControl_aPhyEnhanceEnable);
2315 
2316 	/* Clean up: configuration has been taken care of. */
2317 	reg_write(ohci, OHCI1394_HCControlClear,
2318 		  OHCI1394_HCControl_programPhyEnable);
2319 
2320 	return 0;
2321 }
2322 
2323 static int probe_tsb41ba3d(struct fw_ohci *ohci)
2324 {
2325 	/* TI vendor ID = 0x080028, TSB41BA3D product ID = 0x833005 (sic) */
2326 	static const u8 id[] = { 0x08, 0x00, 0x28, 0x83, 0x30, 0x05, };
2327 	int reg, i;
2328 
2329 	reg = read_phy_reg(ohci, 2);
2330 	if (reg < 0)
2331 		return reg;
2332 	if ((reg & PHY_EXTENDED_REGISTERS) != PHY_EXTENDED_REGISTERS)
2333 		return 0;
2334 
2335 	for (i = ARRAY_SIZE(id) - 1; i >= 0; i--) {
2336 		reg = read_paged_phy_reg(ohci, 1, i + 10);
2337 		if (reg < 0)
2338 			return reg;
2339 		if (reg != id[i])
2340 			return 0;
2341 	}
2342 	return 1;
2343 }
2344 
2345 static int ohci_enable(struct fw_card *card,
2346 		       const __be32 *config_rom, size_t length)
2347 {
2348 	struct fw_ohci *ohci = fw_ohci(card);
2349 	u32 lps, version, irqs;
2350 	int i, ret;
2351 
2352 	ret = software_reset(ohci);
2353 	if (ret < 0) {
2354 		ohci_err(ohci, "failed to reset ohci card\n");
2355 		return ret;
2356 	}
2357 
2358 	/*
2359 	 * Now enable LPS, which we need in order to start accessing
2360 	 * most of the registers.  In fact, on some cards (ALI M5251),
2361 	 * accessing registers in the SClk domain without LPS enabled
2362 	 * will lock up the machine.  Wait 50msec to make sure we have
2363 	 * full link enabled.  However, with some cards (well, at least
2364 	 * a JMicron PCIe card), we have to try again sometimes.
2365 	 *
2366 	 * TI TSB82AA2 + TSB81BA3(A) cards signal LPS enabled early but
2367 	 * cannot actually use the phy at that time.  These need tens of
2368 	 * millisecods pause between LPS write and first phy access too.
2369 	 */
2370 
2371 	reg_write(ohci, OHCI1394_HCControlSet,
2372 		  OHCI1394_HCControl_LPS |
2373 		  OHCI1394_HCControl_postedWriteEnable);
2374 	flush_writes(ohci);
2375 
2376 	for (lps = 0, i = 0; !lps && i < 3; i++) {
2377 		msleep(50);
2378 		lps = reg_read(ohci, OHCI1394_HCControlSet) &
2379 		      OHCI1394_HCControl_LPS;
2380 	}
2381 
2382 	if (!lps) {
2383 		ohci_err(ohci, "failed to set Link Power Status\n");
2384 		return -EIO;
2385 	}
2386 
2387 	if (ohci->quirks & QUIRK_TI_SLLZ059) {
2388 		ret = probe_tsb41ba3d(ohci);
2389 		if (ret < 0)
2390 			return ret;
2391 		if (ret)
2392 			ohci_notice(ohci, "local TSB41BA3D phy\n");
2393 		else
2394 			ohci->quirks &= ~QUIRK_TI_SLLZ059;
2395 	}
2396 
2397 	reg_write(ohci, OHCI1394_HCControlClear,
2398 		  OHCI1394_HCControl_noByteSwapData);
2399 
2400 	reg_write(ohci, OHCI1394_SelfIDBuffer, ohci->self_id_bus);
2401 	reg_write(ohci, OHCI1394_LinkControlSet,
2402 		  OHCI1394_LinkControl_cycleTimerEnable |
2403 		  OHCI1394_LinkControl_cycleMaster);
2404 
2405 	reg_write(ohci, OHCI1394_ATRetries,
2406 		  OHCI1394_MAX_AT_REQ_RETRIES |
2407 		  (OHCI1394_MAX_AT_RESP_RETRIES << 4) |
2408 		  (OHCI1394_MAX_PHYS_RESP_RETRIES << 8) |
2409 		  (200 << 16));
2410 
2411 	ohci->bus_time_running = false;
2412 
2413 	for (i = 0; i < 32; i++)
2414 		if (ohci->ir_context_support & (1 << i))
2415 			reg_write(ohci, OHCI1394_IsoRcvContextControlClear(i),
2416 				  IR_CONTEXT_MULTI_CHANNEL_MODE);
2417 
2418 	version = reg_read(ohci, OHCI1394_Version) & 0x00ff00ff;
2419 	if (version >= OHCI_VERSION_1_1) {
2420 		reg_write(ohci, OHCI1394_InitialChannelsAvailableHi,
2421 			  0xfffffffe);
2422 		card->broadcast_channel_auto_allocated = true;
2423 	}
2424 
2425 	/* Get implemented bits of the priority arbitration request counter. */
2426 	reg_write(ohci, OHCI1394_FairnessControl, 0x3f);
2427 	ohci->pri_req_max = reg_read(ohci, OHCI1394_FairnessControl) & 0x3f;
2428 	reg_write(ohci, OHCI1394_FairnessControl, 0);
2429 	card->priority_budget_implemented = ohci->pri_req_max != 0;
2430 
2431 	reg_write(ohci, OHCI1394_PhyUpperBound, FW_MAX_PHYSICAL_RANGE >> 16);
2432 	reg_write(ohci, OHCI1394_IntEventClear, ~0);
2433 	reg_write(ohci, OHCI1394_IntMaskClear, ~0);
2434 
2435 	ret = configure_1394a_enhancements(ohci);
2436 	if (ret < 0)
2437 		return ret;
2438 
2439 	/* Activate link_on bit and contender bit in our self ID packets.*/
2440 	ret = ohci_update_phy_reg(card, 4, 0, PHY_LINK_ACTIVE | PHY_CONTENDER);
2441 	if (ret < 0)
2442 		return ret;
2443 
2444 	/*
2445 	 * When the link is not yet enabled, the atomic config rom
2446 	 * update mechanism described below in ohci_set_config_rom()
2447 	 * is not active.  We have to update ConfigRomHeader and
2448 	 * BusOptions manually, and the write to ConfigROMmap takes
2449 	 * effect immediately.  We tie this to the enabling of the
2450 	 * link, so we have a valid config rom before enabling - the
2451 	 * OHCI requires that ConfigROMhdr and BusOptions have valid
2452 	 * values before enabling.
2453 	 *
2454 	 * However, when the ConfigROMmap is written, some controllers
2455 	 * always read back quadlets 0 and 2 from the config rom to
2456 	 * the ConfigRomHeader and BusOptions registers on bus reset.
2457 	 * They shouldn't do that in this initial case where the link
2458 	 * isn't enabled.  This means we have to use the same
2459 	 * workaround here, setting the bus header to 0 and then write
2460 	 * the right values in the bus reset work item.
2461 	 */
2462 
2463 	if (config_rom) {
2464 		ohci->next_config_rom = dmam_alloc_coherent(ohci->card.device, CONFIG_ROM_SIZE,
2465 							    &ohci->next_config_rom_bus, GFP_KERNEL);
2466 		if (ohci->next_config_rom == NULL)
2467 			return -ENOMEM;
2468 
2469 		copy_config_rom(ohci->next_config_rom, config_rom, length);
2470 	} else {
2471 		/*
2472 		 * In the suspend case, config_rom is NULL, which
2473 		 * means that we just reuse the old config rom.
2474 		 */
2475 		ohci->next_config_rom = ohci->config_rom;
2476 		ohci->next_config_rom_bus = ohci->config_rom_bus;
2477 	}
2478 
2479 	ohci->next_header = ohci->next_config_rom[0];
2480 	ohci->next_config_rom[0] = 0;
2481 	reg_write(ohci, OHCI1394_ConfigROMhdr, 0);
2482 	reg_write(ohci, OHCI1394_BusOptions,
2483 		  be32_to_cpu(ohci->next_config_rom[2]));
2484 	reg_write(ohci, OHCI1394_ConfigROMmap, ohci->next_config_rom_bus);
2485 
2486 	reg_write(ohci, OHCI1394_AsReqFilterHiSet, 0x80000000);
2487 
2488 	irqs =	OHCI1394_reqTxComplete | OHCI1394_respTxComplete |
2489 		OHCI1394_RQPkt | OHCI1394_RSPkt |
2490 		OHCI1394_isochTx | OHCI1394_isochRx |
2491 		OHCI1394_postedWriteErr |
2492 		OHCI1394_selfIDComplete |
2493 		OHCI1394_regAccessFail |
2494 		OHCI1394_cycleInconsistent |
2495 		OHCI1394_unrecoverableError |
2496 		OHCI1394_cycleTooLong |
2497 		OHCI1394_masterIntEnable |
2498 		OHCI1394_busReset;
2499 	reg_write(ohci, OHCI1394_IntMaskSet, irqs);
2500 
2501 	reg_write(ohci, OHCI1394_HCControlSet,
2502 		  OHCI1394_HCControl_linkEnable |
2503 		  OHCI1394_HCControl_BIBimageValid);
2504 
2505 	reg_write(ohci, OHCI1394_LinkControlSet,
2506 		  OHCI1394_LinkControl_rcvSelfID |
2507 		  OHCI1394_LinkControl_rcvPhyPkt);
2508 
2509 	ar_context_run(&ohci->ar_request_ctx);
2510 	ar_context_run(&ohci->ar_response_ctx);
2511 
2512 	flush_writes(ohci);
2513 
2514 	/* We are ready to go, reset bus to finish initialization. */
2515 	fw_schedule_bus_reset(&ohci->card, false, true);
2516 
2517 	return 0;
2518 }
2519 
2520 static void ohci_disable(struct fw_card *card)
2521 {
2522 	struct pci_dev *pdev = to_pci_dev(card->device);
2523 	struct fw_ohci *ohci = pci_get_drvdata(pdev);
2524 	int i, irq = pci_irq_vector(pdev, 0);
2525 
2526 	// If the removal is happening from the suspend state, LPS won't be enabled and host
2527 	// registers (eg., IntMaskClear) won't be accessible.
2528 	if (!(reg_read(ohci, OHCI1394_HCControlSet) & OHCI1394_HCControl_LPS))
2529 		return;
2530 
2531 	reg_write(ohci, OHCI1394_IntMaskClear, ~0);
2532 	flush_writes(ohci);
2533 
2534 	if (irq >= 0)
2535 		synchronize_irq(irq);
2536 
2537 	flush_work(&ohci->ar_request_ctx.work);
2538 	flush_work(&ohci->ar_response_ctx.work);
2539 	flush_work(&ohci->at_request_ctx.work);
2540 	flush_work(&ohci->at_response_ctx.work);
2541 
2542 	flush_work(&ohci->at_request_local.work);
2543 	flush_work(&ohci->at_response_local.work);
2544 
2545 	for (i = 0; i < ohci->n_ir; ++i) {
2546 		if (!(ohci->ir_context_mask & BIT(i)))
2547 			flush_work(&ohci->ir_context_list[i].base.work);
2548 	}
2549 	for (i = 0; i < ohci->n_it; ++i) {
2550 		if (!(ohci->it_context_mask & BIT(i)))
2551 			flush_work(&ohci->it_context_list[i].base.work);
2552 	}
2553 
2554 	at_context_flush(&ohci->at_request_ctx);
2555 	at_context_flush(&ohci->at_response_ctx);
2556 
2557 	at_request_local_work(&ohci->at_request_local.work);
2558 	at_response_local_work(&ohci->at_response_local.work);
2559 }
2560 
2561 static int ohci_set_config_rom(struct fw_card *card,
2562 			       const __be32 *config_rom, size_t length)
2563 {
2564 	struct fw_ohci *ohci;
2565 	__be32 *next_config_rom;
2566 	dma_addr_t next_config_rom_bus;
2567 
2568 	ohci = fw_ohci(card);
2569 
2570 	/*
2571 	 * When the OHCI controller is enabled, the config rom update
2572 	 * mechanism is a bit tricky, but easy enough to use.  See
2573 	 * section 5.5.6 in the OHCI specification.
2574 	 *
2575 	 * The OHCI controller caches the new config rom address in a
2576 	 * shadow register (ConfigROMmapNext) and needs a bus reset
2577 	 * for the changes to take place.  When the bus reset is
2578 	 * detected, the controller loads the new values for the
2579 	 * ConfigRomHeader and BusOptions registers from the specified
2580 	 * config rom and loads ConfigROMmap from the ConfigROMmapNext
2581 	 * shadow register. All automatically and atomically.
2582 	 *
2583 	 * Now, there's a twist to this story.  The automatic load of
2584 	 * ConfigRomHeader and BusOptions doesn't honor the
2585 	 * noByteSwapData bit, so with a be32 config rom, the
2586 	 * controller will load be32 values in to these registers
2587 	 * during the atomic update, even on little endian
2588 	 * architectures.  The workaround we use is to put a 0 in the
2589 	 * header quadlet; 0 is endian agnostic and means that the
2590 	 * config rom isn't ready yet.  In the bus reset work item we
2591 	 * then set up the real values for the two registers.
2592 	 *
2593 	 * We use ohci->lock to avoid racing with the code that sets
2594 	 * ohci->next_config_rom to NULL (see handle_selfid_complete_event).
2595 	 */
2596 
2597 	next_config_rom = dmam_alloc_coherent(ohci->card.device, CONFIG_ROM_SIZE,
2598 					      &next_config_rom_bus, GFP_KERNEL);
2599 	if (next_config_rom == NULL)
2600 		return -ENOMEM;
2601 
2602 	scoped_guard(spinlock_irq, &ohci->lock) {
2603 		// If there is not an already pending config_rom update, push our new allocation
2604 		// into the ohci->next_config_rom and then mark the local variable as null so that
2605 		// we won't deallocate the new buffer.
2606 		//
2607 		// OTOH, if there is a pending config_rom update, just use that buffer with the new
2608 		// config_rom data, and let this routine free the unused DMA allocation.
2609 		if (ohci->next_config_rom == NULL) {
2610 			ohci->next_config_rom = next_config_rom;
2611 			ohci->next_config_rom_bus = next_config_rom_bus;
2612 			next_config_rom = NULL;
2613 		}
2614 
2615 		copy_config_rom(ohci->next_config_rom, config_rom, length);
2616 
2617 		ohci->next_header = config_rom[0];
2618 		ohci->next_config_rom[0] = 0;
2619 
2620 		reg_write(ohci, OHCI1394_ConfigROMmap, ohci->next_config_rom_bus);
2621 	}
2622 
2623 	/* If we didn't use the DMA allocation, delete it. */
2624 	if (next_config_rom != NULL) {
2625 		dmam_free_coherent(ohci->card.device, CONFIG_ROM_SIZE, next_config_rom,
2626 				   next_config_rom_bus);
2627 	}
2628 
2629 	/*
2630 	 * Now initiate a bus reset to have the changes take
2631 	 * effect. We clean up the old config rom memory and DMA
2632 	 * mappings in the bus reset work item, since the OHCI
2633 	 * controller could need to access it before the bus reset
2634 	 * takes effect.
2635 	 */
2636 
2637 	fw_schedule_bus_reset(&ohci->card, true, true);
2638 
2639 	return 0;
2640 }
2641 
2642 static void ohci_send_request(struct fw_card *card, struct fw_packet *packet)
2643 {
2644 	struct fw_ohci *ohci = fw_ohci(card);
2645 
2646 	at_context_transmit(&ohci->at_request_ctx, packet);
2647 }
2648 
2649 static void ohci_send_response(struct fw_card *card, struct fw_packet *packet)
2650 {
2651 	struct fw_ohci *ohci = fw_ohci(card);
2652 
2653 	at_context_transmit(&ohci->at_response_ctx, packet);
2654 }
2655 
2656 static int ohci_cancel_packet(struct fw_card *card, struct fw_packet *packet)
2657 {
2658 	struct fw_ohci *ohci = fw_ohci(card);
2659 	struct at_context *ctx = &ohci->at_request_ctx;
2660 	struct at_local *local = &ohci->at_request_local;
2661 	int ret = -ENOENT;
2662 
2663 	// handle_at_request_local_packet() can reach here by calling fw_core_handle_response().
2664 	if (current_work() != &local->work)
2665 		disable_work_sync(&local->work);
2666 
2667 	// Avoid dead lock due to programming mistake.
2668 	if (WARN_ON_ONCE(current_work() == &ctx->work))
2669 		return 0;
2670 	disable_work_sync(&ctx->work);
2671 
2672 	bool use_local_work = false;
2673 
2674 	if (!packet->ack) {
2675 		// NOTE: This function relies on this value, thus it is not thread-safe.
2676 		struct driver_data *driver_data = packet->driver_data;
2677 
2678 		if (driver_data) {
2679 			if (packet->payload_mapped) {
2680 				dma_unmap_single(ohci->card.device, packet->payload_bus,
2681 						 packet->payload_length, DMA_TO_DEVICE);
2682 			}
2683 
2684 			// Invalidate the packet queued in AT request context.
2685 			driver_data->packet = NULL;
2686 
2687 			scoped_guard(spinlock_irqsave, &local->lock)
2688 				list_add_tail(&packet->link_for_local, &local->list);
2689 			use_local_work = true;
2690 		} else {
2691 			scoped_guard(spinlock_irqsave, &local->lock) {
2692 				if (!list_empty(&packet->link_for_local))
2693 					use_local_work = true;
2694 			}
2695 		}
2696 	}
2697 
2698 	enable_and_queue_work(card->async_wq, &ctx->work);
2699 
2700 	if (use_local_work) {
2701 		// Timestamping on behalf of the hardware.
2702 		packet->timestamp = cycle_time_to_ohci_tstamp(get_cycle_time(ohci));
2703 		packet->ack = RCODE_CANCELLED;
2704 
2705 		ret = 0;
2706 	}
2707 
2708 	if (current_work() != &local->work)
2709 		enable_and_queue_work(card->async_wq, &local->work);
2710 
2711 	return ret;
2712 }
2713 
2714 static int ohci_enable_phys_dma(struct fw_card *card,
2715 				int node_id, int generation)
2716 {
2717 	struct fw_ohci *ohci = fw_ohci(card);
2718 	int n, ret = 0;
2719 
2720 	if (param_remote_dma)
2721 		return 0;
2722 
2723 	/*
2724 	 * FIXME:  Make sure this bitmask is cleared when we clear the busReset
2725 	 * interrupt bit.  Clear physReqResourceAllBuses on bus reset.
2726 	 */
2727 
2728 	guard(spinlock_irqsave)(&ohci->lock);
2729 
2730 	if (ohci->generation != generation)
2731 		return -ESTALE;
2732 
2733 	/*
2734 	 * Note, if the node ID contains a non-local bus ID, physical DMA is
2735 	 * enabled for _all_ nodes on remote buses.
2736 	 */
2737 
2738 	n = (node_id & 0xffc0) == LOCAL_BUS ? node_id & 0x3f : 63;
2739 	if (n < 32)
2740 		reg_write(ohci, OHCI1394_PhyReqFilterLoSet, 1 << n);
2741 	else
2742 		reg_write(ohci, OHCI1394_PhyReqFilterHiSet, 1 << (n - 32));
2743 
2744 	flush_writes(ohci);
2745 
2746 	return ret;
2747 }
2748 
2749 static u32 ohci_read_csr(struct fw_card *card, int csr_offset)
2750 {
2751 	struct fw_ohci *ohci = fw_ohci(card);
2752 	u32 value;
2753 
2754 	switch (csr_offset) {
2755 	case CSR_STATE_CLEAR:
2756 	case CSR_STATE_SET:
2757 		if (ohci->is_root &&
2758 		    (reg_read(ohci, OHCI1394_LinkControlSet) &
2759 		     OHCI1394_LinkControl_cycleMaster))
2760 			value = CSR_STATE_BIT_CMSTR;
2761 		else
2762 			value = 0;
2763 		if (ohci->csr_state_setclear_abdicate)
2764 			value |= CSR_STATE_BIT_ABDICATE;
2765 
2766 		return value;
2767 
2768 	case CSR_NODE_IDS:
2769 		return reg_read(ohci, OHCI1394_NodeID) << 16;
2770 
2771 	case CSR_CYCLE_TIME:
2772 		return get_cycle_time(ohci);
2773 
2774 	case CSR_BUS_TIME:
2775 	{
2776 		// We might be called just after the cycle timer has wrapped around but just before
2777 		// the cycle64Seconds handler, so we better check here, too, if the bus time needs
2778 		// to be updated.
2779 
2780 		guard(spinlock_irqsave)(&ohci->lock);
2781 		return update_bus_time(ohci);
2782 	}
2783 	case CSR_BUSY_TIMEOUT:
2784 		value = reg_read(ohci, OHCI1394_ATRetries);
2785 		return (value >> 4) & 0x0ffff00f;
2786 
2787 	case CSR_PRIORITY_BUDGET:
2788 		return (reg_read(ohci, OHCI1394_FairnessControl) & 0x3f) |
2789 			(ohci->pri_req_max << 8);
2790 
2791 	default:
2792 		WARN_ON(1);
2793 		return 0;
2794 	}
2795 }
2796 
2797 static void ohci_write_csr(struct fw_card *card, int csr_offset, u32 value)
2798 {
2799 	struct fw_ohci *ohci = fw_ohci(card);
2800 
2801 	switch (csr_offset) {
2802 	case CSR_STATE_CLEAR:
2803 		if ((value & CSR_STATE_BIT_CMSTR) && ohci->is_root) {
2804 			reg_write(ohci, OHCI1394_LinkControlClear,
2805 				  OHCI1394_LinkControl_cycleMaster);
2806 			flush_writes(ohci);
2807 		}
2808 		if (value & CSR_STATE_BIT_ABDICATE)
2809 			ohci->csr_state_setclear_abdicate = false;
2810 		break;
2811 
2812 	case CSR_STATE_SET:
2813 		if ((value & CSR_STATE_BIT_CMSTR) && ohci->is_root) {
2814 			reg_write(ohci, OHCI1394_LinkControlSet,
2815 				  OHCI1394_LinkControl_cycleMaster);
2816 			flush_writes(ohci);
2817 		}
2818 		if (value & CSR_STATE_BIT_ABDICATE)
2819 			ohci->csr_state_setclear_abdicate = true;
2820 		break;
2821 
2822 	case CSR_NODE_IDS:
2823 		reg_write(ohci, OHCI1394_NodeID, value >> 16);
2824 		flush_writes(ohci);
2825 		break;
2826 
2827 	case CSR_CYCLE_TIME:
2828 		reg_write(ohci, OHCI1394_IsochronousCycleTimer, value);
2829 		reg_write(ohci, OHCI1394_IntEventSet,
2830 			  OHCI1394_cycleInconsistent);
2831 		flush_writes(ohci);
2832 		break;
2833 
2834 	case CSR_BUS_TIME:
2835 	{
2836 		guard(spinlock_irqsave)(&ohci->lock);
2837 		ohci->bus_time = (update_bus_time(ohci) & 0x40) | (value & ~0x7f);
2838 		break;
2839 	}
2840 	case CSR_BUSY_TIMEOUT:
2841 		value = (value & 0xf) | ((value & 0xf) << 4) |
2842 			((value & 0xf) << 8) | ((value & 0x0ffff000) << 4);
2843 		reg_write(ohci, OHCI1394_ATRetries, value);
2844 		flush_writes(ohci);
2845 		break;
2846 
2847 	case CSR_PRIORITY_BUDGET:
2848 		reg_write(ohci, OHCI1394_FairnessControl, value & 0x3f);
2849 		flush_writes(ohci);
2850 		break;
2851 
2852 	default:
2853 		WARN_ON(1);
2854 		break;
2855 	}
2856 }
2857 
2858 static void flush_iso_completions(struct iso_context *ctx, enum fw_iso_context_completions_cause cause)
2859 {
2860 	trace_isoc_inbound_single_completions(&ctx->base, ctx->sc.last_timestamp, cause,
2861 					      ctx->sc.header, ctx->sc.header_length);
2862 	trace_isoc_outbound_completions(&ctx->base, ctx->sc.last_timestamp, cause, ctx->sc.header,
2863 					ctx->sc.header_length);
2864 
2865 	ctx->base.callback.sc(&ctx->base, ctx->sc.last_timestamp, ctx->sc.header_length,
2866 			      ctx->sc.header, ctx->base.callback_data);
2867 	ctx->sc.header_length = 0;
2868 }
2869 
2870 static void copy_iso_headers(struct iso_context *ctx, const u32 *dma_hdr)
2871 {
2872 	u32 *ctx_hdr;
2873 
2874 	if (ctx->sc.header_length + ctx->base.header_size > ctx->base.header_storage_size) {
2875 		if (ctx->base.flags & FW_ISO_CONTEXT_FLAG_DROP_OVERFLOW_HEADERS)
2876 			return;
2877 		flush_iso_completions(ctx, FW_ISO_CONTEXT_COMPLETIONS_CAUSE_HEADER_OVERFLOW);
2878 	}
2879 
2880 	ctx_hdr = ctx->sc.header + ctx->sc.header_length;
2881 	ctx->sc.last_timestamp = (u16)le32_to_cpu((__force __le32)dma_hdr[0]);
2882 
2883 	/*
2884 	 * The two iso header quadlets are byteswapped to little
2885 	 * endian by the controller, but we want to present them
2886 	 * as big endian for consistency with the bus endianness.
2887 	 */
2888 	if (ctx->base.header_size > 0)
2889 		ctx_hdr[0] = swab32(dma_hdr[1]); /* iso packet header */
2890 	if (ctx->base.header_size > 4)
2891 		ctx_hdr[1] = swab32(dma_hdr[0]); /* timestamp */
2892 	if (ctx->base.header_size > 8)
2893 		memcpy(&ctx_hdr[2], &dma_hdr[2], ctx->base.header_size - 8);
2894 	ctx->sc.header_length += ctx->base.header_size;
2895 }
2896 
2897 static int handle_ir_packet_per_buffer(struct context *context,
2898 				       struct descriptor *d,
2899 				       struct descriptor *last)
2900 {
2901 	struct iso_context *ctx =
2902 		container_of(context, struct iso_context, context);
2903 	struct descriptor *pd;
2904 	u32 buffer_dma;
2905 
2906 	for (pd = d; pd <= last; pd++)
2907 		if (pd->transfer_status)
2908 			break;
2909 	if (pd > last)
2910 		/* Descriptor(s) not done yet, stop iteration */
2911 		return 0;
2912 
2913 	while (!(d->control & cpu_to_le16(DESCRIPTOR_BRANCH_ALWAYS))) {
2914 		d++;
2915 		buffer_dma = le32_to_cpu(d->data_address);
2916 		dma_sync_single_range_for_cpu(context->ohci->card.device,
2917 					      buffer_dma & PAGE_MASK,
2918 					      buffer_dma & ~PAGE_MASK,
2919 					      le16_to_cpu(d->req_count),
2920 					      DMA_FROM_DEVICE);
2921 	}
2922 
2923 	copy_iso_headers(ctx, (u32 *) (last + 1));
2924 
2925 	if (last->control & cpu_to_le16(DESCRIPTOR_IRQ_ALWAYS))
2926 		flush_iso_completions(ctx, FW_ISO_CONTEXT_COMPLETIONS_CAUSE_INTERRUPT);
2927 
2928 	return 1;
2929 }
2930 
2931 /* d == last because each descriptor block is only a single descriptor. */
2932 static int handle_ir_buffer_fill(struct context *context,
2933 				 struct descriptor *d,
2934 				 struct descriptor *last)
2935 {
2936 	struct iso_context *ctx =
2937 		container_of(context, struct iso_context, context);
2938 	unsigned int req_count, res_count, completed;
2939 	u32 buffer_dma;
2940 
2941 	req_count = le16_to_cpu(last->req_count);
2942 	res_count = le16_to_cpu(READ_ONCE(last->res_count));
2943 	completed = req_count - res_count;
2944 	buffer_dma = le32_to_cpu(last->data_address);
2945 
2946 	if (completed > 0) {
2947 		ctx->mc.buffer_bus = buffer_dma;
2948 		ctx->mc.completed = completed;
2949 	}
2950 
2951 	if (res_count != 0)
2952 		/* Descriptor(s) not done yet, stop iteration */
2953 		return 0;
2954 
2955 	dma_sync_single_range_for_cpu(context->ohci->card.device,
2956 				      buffer_dma & PAGE_MASK,
2957 				      buffer_dma & ~PAGE_MASK,
2958 				      completed, DMA_FROM_DEVICE);
2959 
2960 	if (last->control & cpu_to_le16(DESCRIPTOR_IRQ_ALWAYS)) {
2961 		trace_isoc_inbound_multiple_completions(&ctx->base, completed,
2962 							FW_ISO_CONTEXT_COMPLETIONS_CAUSE_INTERRUPT);
2963 
2964 		ctx->base.callback.mc(&ctx->base,
2965 				      buffer_dma + completed,
2966 				      ctx->base.callback_data);
2967 		ctx->mc.completed = 0;
2968 	}
2969 
2970 	return 1;
2971 }
2972 
2973 static void flush_ir_buffer_fill(struct iso_context *ctx)
2974 {
2975 	dma_sync_single_range_for_cpu(ctx->context.ohci->card.device,
2976 				      ctx->mc.buffer_bus & PAGE_MASK,
2977 				      ctx->mc.buffer_bus & ~PAGE_MASK,
2978 				      ctx->mc.completed, DMA_FROM_DEVICE);
2979 
2980 	trace_isoc_inbound_multiple_completions(&ctx->base, ctx->mc.completed,
2981 						FW_ISO_CONTEXT_COMPLETIONS_CAUSE_FLUSH);
2982 
2983 	ctx->base.callback.mc(&ctx->base, ctx->mc.buffer_bus + ctx->mc.completed,
2984 			      ctx->base.callback_data);
2985 	ctx->mc.completed = 0;
2986 }
2987 
2988 static inline void sync_it_packet_for_cpu(struct context *context,
2989 					  struct descriptor *pd)
2990 {
2991 	__le16 control;
2992 	u32 buffer_dma;
2993 
2994 	/* only packets beginning with OUTPUT_MORE* have data buffers */
2995 	if (pd->control & cpu_to_le16(DESCRIPTOR_BRANCH_ALWAYS))
2996 		return;
2997 
2998 	/* skip over the OUTPUT_MORE_IMMEDIATE descriptor */
2999 	pd += 2;
3000 
3001 	/*
3002 	 * If the packet has a header, the first OUTPUT_MORE/LAST descriptor's
3003 	 * data buffer is in the context program's coherent page and must not
3004 	 * be synced.
3005 	 */
3006 	if ((le32_to_cpu(pd->data_address) & PAGE_MASK) ==
3007 	    (context->current_bus          & PAGE_MASK)) {
3008 		if (pd->control & cpu_to_le16(DESCRIPTOR_BRANCH_ALWAYS))
3009 			return;
3010 		pd++;
3011 	}
3012 
3013 	do {
3014 		buffer_dma = le32_to_cpu(pd->data_address);
3015 		dma_sync_single_range_for_cpu(context->ohci->card.device,
3016 					      buffer_dma & PAGE_MASK,
3017 					      buffer_dma & ~PAGE_MASK,
3018 					      le16_to_cpu(pd->req_count),
3019 					      DMA_TO_DEVICE);
3020 		control = pd->control;
3021 		pd++;
3022 	} while (!(control & cpu_to_le16(DESCRIPTOR_BRANCH_ALWAYS)));
3023 }
3024 
3025 static int handle_it_packet(struct context *context,
3026 			    struct descriptor *d,
3027 			    struct descriptor *last)
3028 {
3029 	struct iso_context *ctx =
3030 		container_of(context, struct iso_context, context);
3031 	struct descriptor *pd;
3032 	__be32 *ctx_hdr;
3033 
3034 	for (pd = d; pd <= last; pd++)
3035 		if (pd->transfer_status)
3036 			break;
3037 	if (pd > last)
3038 		/* Descriptor(s) not done yet, stop iteration */
3039 		return 0;
3040 
3041 	sync_it_packet_for_cpu(context, d);
3042 
3043 	if (ctx->sc.header_length + 4 > ctx->base.header_storage_size) {
3044 		if (ctx->base.flags & FW_ISO_CONTEXT_FLAG_DROP_OVERFLOW_HEADERS)
3045 			return 1;
3046 		flush_iso_completions(ctx, FW_ISO_CONTEXT_COMPLETIONS_CAUSE_HEADER_OVERFLOW);
3047 	}
3048 
3049 	ctx_hdr = ctx->sc.header + ctx->sc.header_length;
3050 	ctx->sc.last_timestamp = le16_to_cpu(last->res_count);
3051 	/* Present this value as big-endian to match the receive code */
3052 	*ctx_hdr = cpu_to_be32((le16_to_cpu(pd->transfer_status) << 16) |
3053 			       le16_to_cpu(pd->res_count));
3054 	ctx->sc.header_length += 4;
3055 
3056 	if (last->control & cpu_to_le16(DESCRIPTOR_IRQ_ALWAYS))
3057 		flush_iso_completions(ctx, FW_ISO_CONTEXT_COMPLETIONS_CAUSE_INTERRUPT);
3058 
3059 	return 1;
3060 }
3061 
3062 static void set_multichannel_mask(struct fw_ohci *ohci, u64 channels)
3063 {
3064 	u32 hi = channels >> 32, lo = channels;
3065 
3066 	reg_write(ohci, OHCI1394_IRMultiChanMaskHiClear, ~hi);
3067 	reg_write(ohci, OHCI1394_IRMultiChanMaskLoClear, ~lo);
3068 	reg_write(ohci, OHCI1394_IRMultiChanMaskHiSet, hi);
3069 	reg_write(ohci, OHCI1394_IRMultiChanMaskLoSet, lo);
3070 	ohci->mc_channels = channels;
3071 }
3072 
3073 static struct fw_iso_context *ohci_allocate_iso_context(struct fw_card *card, int type, int channel,
3074 		size_t header_size, size_t header_storage_size)
3075 {
3076 	struct fw_ohci *ohci = fw_ohci(card);
3077 	void *header __free(kvfree) = NULL;
3078 	struct iso_context *ctx;
3079 	descriptor_callback_t callback;
3080 	u64 *channels;
3081 	u32 *mask, regs;
3082 	int index, ret = -EBUSY;
3083 
3084 	scoped_guard(spinlock_irq, &ohci->lock) {
3085 		switch (type) {
3086 		case FW_ISO_CONTEXT_TRANSMIT:
3087 			mask     = &ohci->it_context_mask;
3088 			callback = handle_it_packet;
3089 			index    = ffs(*mask) - 1;
3090 			if (index >= 0) {
3091 				*mask &= ~(1 << index);
3092 				regs = OHCI1394_IsoXmitContextBase(index);
3093 				ctx  = &ohci->it_context_list[index];
3094 			}
3095 			break;
3096 
3097 		case FW_ISO_CONTEXT_RECEIVE:
3098 			channels = &ohci->ir_context_channels;
3099 			mask     = &ohci->ir_context_mask;
3100 			callback = handle_ir_packet_per_buffer;
3101 			index    = *channels & 1ULL << channel ? ffs(*mask) - 1 : -1;
3102 			if (index >= 0) {
3103 				*channels &= ~(1ULL << channel);
3104 				*mask     &= ~(1 << index);
3105 				regs = OHCI1394_IsoRcvContextBase(index);
3106 				ctx  = &ohci->ir_context_list[index];
3107 			}
3108 			break;
3109 
3110 		case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
3111 			mask     = &ohci->ir_context_mask;
3112 			callback = handle_ir_buffer_fill;
3113 			index    = !ohci->mc_allocated ? ffs(*mask) - 1 : -1;
3114 			if (index >= 0) {
3115 				ohci->mc_allocated = true;
3116 				*mask &= ~(1 << index);
3117 				regs = OHCI1394_IsoRcvContextBase(index);
3118 				ctx  = &ohci->ir_context_list[index];
3119 			}
3120 			break;
3121 
3122 		default:
3123 			index = -1;
3124 			ret = -ENOSYS;
3125 		}
3126 
3127 		if (index < 0)
3128 			return ERR_PTR(ret);
3129 	}
3130 
3131 	memset(ctx, 0, sizeof(*ctx));
3132 
3133 	if (type != FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL) {
3134 		ctx->sc.header_length = 0;
3135 		header = kvmalloc(header_storage_size, GFP_KERNEL);
3136 		if (!header) {
3137 			ret = -ENOMEM;
3138 			goto out;
3139 		}
3140 	}
3141 
3142 	ret = context_init(&ctx->context, ohci, regs, callback);
3143 	if (ret < 0)
3144 		goto out;
3145 	fw_iso_context_init_work(&ctx->base, ohci_isoc_context_work);
3146 
3147 	if (type != FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL) {
3148 		ctx->sc.header = no_free_ptr(header);
3149 	} else {
3150 		set_multichannel_mask(ohci, 0);
3151 		ctx->mc.completed = 0;
3152 	}
3153 
3154 	return &ctx->base;
3155  out:
3156 	scoped_guard(spinlock_irq, &ohci->lock) {
3157 		switch (type) {
3158 		case FW_ISO_CONTEXT_RECEIVE:
3159 			*channels |= 1ULL << channel;
3160 			break;
3161 
3162 		case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
3163 			ohci->mc_allocated = false;
3164 			break;
3165 		}
3166 		*mask |= 1 << index;
3167 	}
3168 
3169 	return ERR_PTR(ret);
3170 }
3171 
3172 static int ohci_start_iso(struct fw_iso_context *base,
3173 			  s32 cycle, u32 sync, u32 tags)
3174 {
3175 	struct iso_context *ctx = container_of(base, struct iso_context, base);
3176 	struct fw_ohci *ohci = ctx->context.ohci;
3177 	u32 control = IR_CONTEXT_ISOCH_HEADER, match;
3178 	int index;
3179 
3180 	/* the controller cannot start without any queued packets */
3181 	if (ctx->context.last->branch_address == 0)
3182 		return -ENODATA;
3183 
3184 	switch (ctx->base.type) {
3185 	case FW_ISO_CONTEXT_TRANSMIT:
3186 		index = ctx - ohci->it_context_list;
3187 		match = 0;
3188 		if (cycle >= 0)
3189 			match = IT_CONTEXT_CYCLE_MATCH_ENABLE |
3190 				(cycle & 0x7fff) << 16;
3191 
3192 		reg_write(ohci, OHCI1394_IsoXmitIntEventClear, 1 << index);
3193 		reg_write(ohci, OHCI1394_IsoXmitIntMaskSet, 1 << index);
3194 		context_run(&ctx->context, match);
3195 		break;
3196 
3197 	case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
3198 		control |= IR_CONTEXT_BUFFER_FILL|IR_CONTEXT_MULTI_CHANNEL_MODE;
3199 		fallthrough;
3200 	case FW_ISO_CONTEXT_RECEIVE:
3201 		index = ctx - ohci->ir_context_list;
3202 		match = (tags << 28) | (sync << 8) | ctx->base.channel;
3203 		if (cycle >= 0) {
3204 			match |= (cycle & 0x07fff) << 12;
3205 			control |= IR_CONTEXT_CYCLE_MATCH_ENABLE;
3206 		}
3207 
3208 		reg_write(ohci, OHCI1394_IsoRecvIntEventClear, 1 << index);
3209 		reg_write(ohci, OHCI1394_IsoRecvIntMaskSet, 1 << index);
3210 		reg_write(ohci, CONTEXT_MATCH(ctx->context.regs), match);
3211 		context_run(&ctx->context, control);
3212 
3213 		ctx->sync = sync;
3214 		ctx->tags = tags;
3215 
3216 		break;
3217 	}
3218 
3219 	return 0;
3220 }
3221 
3222 static int ohci_stop_iso(struct fw_iso_context *base)
3223 {
3224 	struct fw_ohci *ohci = fw_ohci(base->card);
3225 	struct iso_context *ctx = container_of(base, struct iso_context, base);
3226 	int index;
3227 
3228 	switch (ctx->base.type) {
3229 	case FW_ISO_CONTEXT_TRANSMIT:
3230 		index = ctx - ohci->it_context_list;
3231 		reg_write(ohci, OHCI1394_IsoXmitIntMaskClear, 1 << index);
3232 		break;
3233 
3234 	case FW_ISO_CONTEXT_RECEIVE:
3235 	case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
3236 		index = ctx - ohci->ir_context_list;
3237 		reg_write(ohci, OHCI1394_IsoRecvIntMaskClear, 1 << index);
3238 		break;
3239 	}
3240 	flush_writes(ohci);
3241 	context_stop(&ctx->context);
3242 
3243 	return 0;
3244 }
3245 
3246 static void ohci_free_iso_context(struct fw_iso_context *base)
3247 {
3248 	struct fw_ohci *ohci = fw_ohci(base->card);
3249 	struct iso_context *ctx = container_of(base, struct iso_context, base);
3250 	int index;
3251 
3252 	ohci_stop_iso(base);
3253 	context_release(&ctx->context);
3254 
3255 	if (base->type != FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL) {
3256 		kvfree(ctx->sc.header);
3257 		ctx->sc.header = NULL;
3258 	}
3259 
3260 	guard(spinlock_irqsave)(&ohci->lock);
3261 
3262 	switch (base->type) {
3263 	case FW_ISO_CONTEXT_TRANSMIT:
3264 		index = ctx - ohci->it_context_list;
3265 		ohci->it_context_mask |= 1 << index;
3266 		break;
3267 
3268 	case FW_ISO_CONTEXT_RECEIVE:
3269 		index = ctx - ohci->ir_context_list;
3270 		ohci->ir_context_mask |= 1 << index;
3271 		ohci->ir_context_channels |= 1ULL << base->channel;
3272 		break;
3273 
3274 	case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
3275 		index = ctx - ohci->ir_context_list;
3276 		ohci->ir_context_mask |= 1 << index;
3277 		ohci->ir_context_channels |= ohci->mc_channels;
3278 		ohci->mc_channels = 0;
3279 		ohci->mc_allocated = false;
3280 		break;
3281 	}
3282 }
3283 
3284 static int ohci_set_iso_channels(struct fw_iso_context *base, u64 *channels)
3285 {
3286 	struct fw_ohci *ohci = fw_ohci(base->card);
3287 
3288 	switch (base->type) {
3289 	case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
3290 	{
3291 		guard(spinlock_irqsave)(&ohci->lock);
3292 
3293 		// Don't allow multichannel to grab other contexts' channels.
3294 		if (~ohci->ir_context_channels & ~ohci->mc_channels & *channels) {
3295 			*channels = ohci->ir_context_channels;
3296 			return -EBUSY;
3297 		} else {
3298 			set_multichannel_mask(ohci, *channels);
3299 			return 0;
3300 		}
3301 	}
3302 	default:
3303 		return -EINVAL;
3304 	}
3305 }
3306 
3307 static void __maybe_unused ohci_resume_iso_dma(struct fw_ohci *ohci)
3308 {
3309 	int i;
3310 	struct iso_context *ctx;
3311 
3312 	for (i = 0 ; i < ohci->n_ir ; i++) {
3313 		ctx = &ohci->ir_context_list[i];
3314 		if (ctx->context.running)
3315 			ohci_start_iso(&ctx->base, 0, ctx->sync, ctx->tags);
3316 	}
3317 
3318 	for (i = 0 ; i < ohci->n_it ; i++) {
3319 		ctx = &ohci->it_context_list[i];
3320 		if (ctx->context.running)
3321 			ohci_start_iso(&ctx->base, 0, ctx->sync, ctx->tags);
3322 	}
3323 }
3324 
3325 static int queue_iso_transmit(struct iso_context *ctx,
3326 			      struct fw_iso_packet *packet,
3327 			      struct fw_iso_buffer *buffer,
3328 			      unsigned long payload)
3329 {
3330 	struct descriptor *d, *last, *pd;
3331 	struct fw_iso_packet *p;
3332 	__le32 *header;
3333 	dma_addr_t d_bus;
3334 	u32 z, header_z, payload_z, irq;
3335 	u32 payload_index, payload_end_index, next_page_index;
3336 	int page, end_page, i, length, offset;
3337 
3338 	p = packet;
3339 	payload_index = payload;
3340 
3341 	if (p->skip)
3342 		z = 1;
3343 	else
3344 		z = 2;
3345 	if (p->header_length > 0)
3346 		z++;
3347 
3348 	/* Determine the first page the payload isn't contained in. */
3349 	end_page = PAGE_ALIGN(payload_index + p->payload_length) >> PAGE_SHIFT;
3350 	if (p->payload_length > 0)
3351 		payload_z = end_page - (payload_index >> PAGE_SHIFT);
3352 	else
3353 		payload_z = 0;
3354 
3355 	z += payload_z;
3356 
3357 	/* Get header size in number of descriptors. */
3358 	header_z = DIV_ROUND_UP(p->header_length, sizeof(*d));
3359 
3360 	d = context_get_descriptors(&ctx->context, z + header_z, &d_bus);
3361 	if (d == NULL)
3362 		return -ENOMEM;
3363 
3364 	if (!p->skip) {
3365 		d[0].control   = cpu_to_le16(DESCRIPTOR_KEY_IMMEDIATE);
3366 		d[0].req_count = cpu_to_le16(8);
3367 		/*
3368 		 * Link the skip address to this descriptor itself.  This causes
3369 		 * a context to skip a cycle whenever lost cycles or FIFO
3370 		 * overruns occur, without dropping the data.  The application
3371 		 * should then decide whether this is an error condition or not.
3372 		 * FIXME:  Make the context's cycle-lost behaviour configurable?
3373 		 */
3374 		d[0].branch_address = cpu_to_le32(d_bus | z);
3375 
3376 		header = (__le32 *) &d[1];
3377 
3378 		ohci1394_it_data_set_speed(header, ctx->base.speed);
3379 		ohci1394_it_data_set_tag(header, p->tag);
3380 		ohci1394_it_data_set_channel(header, ctx->base.channel);
3381 		ohci1394_it_data_set_tcode(header, TCODE_STREAM_DATA);
3382 		ohci1394_it_data_set_sync(header, p->sy);
3383 
3384 		ohci1394_it_data_set_data_length(header, p->header_length + p->payload_length);
3385 	}
3386 
3387 	if (p->header_length > 0) {
3388 		d[2].req_count    = cpu_to_le16(p->header_length);
3389 		d[2].data_address = cpu_to_le32(d_bus + z * sizeof(*d));
3390 		memcpy(&d[z], p->header, p->header_length);
3391 	}
3392 
3393 	pd = d + z - payload_z;
3394 	payload_end_index = payload_index + p->payload_length;
3395 	for (i = 0; i < payload_z; i++) {
3396 		page               = payload_index >> PAGE_SHIFT;
3397 		offset             = payload_index & ~PAGE_MASK;
3398 		next_page_index    = (page + 1) << PAGE_SHIFT;
3399 		length             =
3400 			min(next_page_index, payload_end_index) - payload_index;
3401 		pd[i].req_count    = cpu_to_le16(length);
3402 
3403 		dma_addr_t dma_addr = buffer->dma_addrs[page];
3404 		pd[i].data_address = cpu_to_le32(dma_addr + offset);
3405 
3406 		dma_sync_single_range_for_device(ctx->context.ohci->card.device,
3407 						 dma_addr, offset, length,
3408 						 DMA_TO_DEVICE);
3409 
3410 		payload_index += length;
3411 	}
3412 
3413 	if (p->interrupt)
3414 		irq = DESCRIPTOR_IRQ_ALWAYS;
3415 	else
3416 		irq = DESCRIPTOR_NO_IRQ;
3417 
3418 	last = z == 2 ? d : d + z - 1;
3419 	last->control |= cpu_to_le16(DESCRIPTOR_OUTPUT_LAST |
3420 				     DESCRIPTOR_STATUS |
3421 				     DESCRIPTOR_BRANCH_ALWAYS |
3422 				     irq);
3423 
3424 	context_append(&ctx->context, d, z, header_z);
3425 
3426 	return 0;
3427 }
3428 
3429 static int queue_iso_packet_per_buffer(struct iso_context *ctx,
3430 				       struct fw_iso_packet *packet,
3431 				       struct fw_iso_buffer *buffer,
3432 				       unsigned long payload)
3433 {
3434 	struct device *device = ctx->context.ohci->card.device;
3435 	struct descriptor *d, *pd;
3436 	dma_addr_t d_bus;
3437 	u32 z, header_z, rest;
3438 	int i, j, length;
3439 	int page, offset, packet_count, header_size, payload_per_buffer;
3440 
3441 	/*
3442 	 * The OHCI controller puts the isochronous header and trailer in the
3443 	 * buffer, so we need at least 8 bytes.
3444 	 */
3445 	packet_count = packet->header_length / ctx->base.header_size;
3446 	header_size  = max(ctx->base.header_size, (size_t)8);
3447 
3448 	/* Get header size in number of descriptors. */
3449 	header_z = DIV_ROUND_UP(header_size, sizeof(*d));
3450 	page     = payload >> PAGE_SHIFT;
3451 	offset   = payload & ~PAGE_MASK;
3452 	payload_per_buffer = packet->payload_length / packet_count;
3453 
3454 	for (i = 0; i < packet_count; i++) {
3455 		/* d points to the header descriptor */
3456 		z = DIV_ROUND_UP(payload_per_buffer + offset, PAGE_SIZE) + 1;
3457 		d = context_get_descriptors(&ctx->context,
3458 				z + header_z, &d_bus);
3459 		if (d == NULL)
3460 			return -ENOMEM;
3461 
3462 		d->control      = cpu_to_le16(DESCRIPTOR_STATUS |
3463 					      DESCRIPTOR_INPUT_MORE);
3464 		if (packet->skip && i == 0)
3465 			d->control |= cpu_to_le16(DESCRIPTOR_WAIT);
3466 		d->req_count    = cpu_to_le16(header_size);
3467 		d->res_count    = d->req_count;
3468 		d->transfer_status = 0;
3469 		d->data_address = cpu_to_le32(d_bus + (z * sizeof(*d)));
3470 
3471 		rest = payload_per_buffer;
3472 		pd = d;
3473 		for (j = 1; j < z; j++) {
3474 			pd++;
3475 			pd->control = cpu_to_le16(DESCRIPTOR_STATUS |
3476 						  DESCRIPTOR_INPUT_MORE);
3477 
3478 			if (offset + rest < PAGE_SIZE)
3479 				length = rest;
3480 			else
3481 				length = PAGE_SIZE - offset;
3482 			pd->req_count = cpu_to_le16(length);
3483 			pd->res_count = pd->req_count;
3484 			pd->transfer_status = 0;
3485 
3486 			dma_addr_t dma_addr = buffer->dma_addrs[page];
3487 			pd->data_address = cpu_to_le32(dma_addr + offset);
3488 
3489 			dma_sync_single_range_for_device(device, dma_addr,
3490 							 offset, length,
3491 							 DMA_FROM_DEVICE);
3492 
3493 			offset = (offset + length) & ~PAGE_MASK;
3494 			rest -= length;
3495 			if (offset == 0)
3496 				page++;
3497 		}
3498 		pd->control = cpu_to_le16(DESCRIPTOR_STATUS |
3499 					  DESCRIPTOR_INPUT_LAST |
3500 					  DESCRIPTOR_BRANCH_ALWAYS);
3501 		if (packet->interrupt && i == packet_count - 1)
3502 			pd->control |= cpu_to_le16(DESCRIPTOR_IRQ_ALWAYS);
3503 
3504 		context_append(&ctx->context, d, z, header_z);
3505 	}
3506 
3507 	return 0;
3508 }
3509 
3510 static int queue_iso_buffer_fill(struct iso_context *ctx,
3511 				 struct fw_iso_packet *packet,
3512 				 struct fw_iso_buffer *buffer,
3513 				 unsigned long payload)
3514 {
3515 	struct descriptor *d;
3516 	dma_addr_t d_bus;
3517 	int page, offset, rest, z, i, length;
3518 
3519 	page   = payload >> PAGE_SHIFT;
3520 	offset = payload & ~PAGE_MASK;
3521 	rest   = packet->payload_length;
3522 
3523 	/* We need one descriptor for each page in the buffer. */
3524 	z = DIV_ROUND_UP(offset + rest, PAGE_SIZE);
3525 
3526 	if (WARN_ON(offset & 3 || rest & 3 || page + z > buffer->page_count))
3527 		return -EFAULT;
3528 
3529 	for (i = 0; i < z; i++) {
3530 		d = context_get_descriptors(&ctx->context, 1, &d_bus);
3531 		if (d == NULL)
3532 			return -ENOMEM;
3533 
3534 		d->control = cpu_to_le16(DESCRIPTOR_INPUT_MORE |
3535 					 DESCRIPTOR_BRANCH_ALWAYS);
3536 		if (packet->skip && i == 0)
3537 			d->control |= cpu_to_le16(DESCRIPTOR_WAIT);
3538 		if (packet->interrupt && i == z - 1)
3539 			d->control |= cpu_to_le16(DESCRIPTOR_IRQ_ALWAYS);
3540 
3541 		if (offset + rest < PAGE_SIZE)
3542 			length = rest;
3543 		else
3544 			length = PAGE_SIZE - offset;
3545 		d->req_count = cpu_to_le16(length);
3546 		d->res_count = d->req_count;
3547 		d->transfer_status = 0;
3548 
3549 		dma_addr_t dma_addr = buffer->dma_addrs[page];
3550 		d->data_address = cpu_to_le32(dma_addr + offset);
3551 
3552 		dma_sync_single_range_for_device(ctx->context.ohci->card.device,
3553 						 dma_addr, offset, length,
3554 						 DMA_FROM_DEVICE);
3555 
3556 		rest -= length;
3557 		offset = 0;
3558 		page++;
3559 
3560 		context_append(&ctx->context, d, 1, 0);
3561 	}
3562 
3563 	return 0;
3564 }
3565 
3566 static int ohci_queue_iso(struct fw_iso_context *base,
3567 			  struct fw_iso_packet *packet,
3568 			  struct fw_iso_buffer *buffer,
3569 			  unsigned long payload)
3570 {
3571 	struct iso_context *ctx = container_of(base, struct iso_context, base);
3572 
3573 	guard(spinlock_irqsave)(&ctx->context.ohci->lock);
3574 
3575 	switch (base->type) {
3576 	case FW_ISO_CONTEXT_TRANSMIT:
3577 		return queue_iso_transmit(ctx, packet, buffer, payload);
3578 	case FW_ISO_CONTEXT_RECEIVE:
3579 		return queue_iso_packet_per_buffer(ctx, packet, buffer, payload);
3580 	case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
3581 		return queue_iso_buffer_fill(ctx, packet, buffer, payload);
3582 	default:
3583 		return -ENOSYS;
3584 	}
3585 }
3586 
3587 static void ohci_flush_queue_iso(struct fw_iso_context *base)
3588 {
3589 	struct context *ctx =
3590 			&container_of(base, struct iso_context, base)->context;
3591 
3592 	reg_write(ctx->ohci, CONTROL_SET(ctx->regs), CONTEXT_WAKE);
3593 }
3594 
3595 static int ohci_flush_iso_completions(struct fw_iso_context *base)
3596 {
3597 	struct iso_context *ctx = container_of(base, struct iso_context, base);
3598 	int ret = 0;
3599 
3600 	if (!test_and_set_bit_lock(0, &ctx->flushing_completions)) {
3601 		ohci_isoc_context_work(&base->work);
3602 
3603 		switch (base->type) {
3604 		case FW_ISO_CONTEXT_TRANSMIT:
3605 		case FW_ISO_CONTEXT_RECEIVE:
3606 			if (ctx->sc.header_length != 0)
3607 				flush_iso_completions(ctx, FW_ISO_CONTEXT_COMPLETIONS_CAUSE_FLUSH);
3608 			break;
3609 		case FW_ISO_CONTEXT_RECEIVE_MULTICHANNEL:
3610 			if (ctx->mc.completed != 0)
3611 				flush_ir_buffer_fill(ctx);
3612 			break;
3613 		default:
3614 			ret = -ENOSYS;
3615 		}
3616 
3617 		clear_bit_unlock(0, &ctx->flushing_completions);
3618 		smp_mb__after_atomic();
3619 	}
3620 
3621 	return ret;
3622 }
3623 
3624 static const struct fw_card_driver ohci_driver = {
3625 	.enable			= ohci_enable,
3626 	.disable		= ohci_disable,
3627 	.read_phy_reg		= ohci_read_phy_reg,
3628 	.update_phy_reg		= ohci_update_phy_reg,
3629 	.set_config_rom		= ohci_set_config_rom,
3630 	.send_request		= ohci_send_request,
3631 	.send_response		= ohci_send_response,
3632 	.cancel_packet		= ohci_cancel_packet,
3633 	.enable_phys_dma	= ohci_enable_phys_dma,
3634 	.read_csr		= ohci_read_csr,
3635 	.write_csr		= ohci_write_csr,
3636 
3637 	.allocate_iso_context	= ohci_allocate_iso_context,
3638 	.free_iso_context	= ohci_free_iso_context,
3639 	.set_iso_channels	= ohci_set_iso_channels,
3640 	.queue_iso		= ohci_queue_iso,
3641 	.flush_queue_iso	= ohci_flush_queue_iso,
3642 	.flush_iso_completions	= ohci_flush_iso_completions,
3643 	.start_iso		= ohci_start_iso,
3644 	.stop_iso		= ohci_stop_iso,
3645 };
3646 
3647 #ifdef CONFIG_PPC_PMAC
3648 static void pmac_ohci_on(struct pci_dev *dev)
3649 {
3650 	if (machine_is(powermac)) {
3651 		struct device_node *ofn = pci_device_to_OF_node(dev);
3652 
3653 		if (ofn) {
3654 			pmac_call_feature(PMAC_FTR_1394_CABLE_POWER, ofn, 0, 1);
3655 			pmac_call_feature(PMAC_FTR_1394_ENABLE, ofn, 0, 1);
3656 		}
3657 	}
3658 }
3659 
3660 static void pmac_ohci_off(struct pci_dev *dev)
3661 {
3662 	if (machine_is(powermac)) {
3663 		struct device_node *ofn = pci_device_to_OF_node(dev);
3664 
3665 		if (ofn) {
3666 			pmac_call_feature(PMAC_FTR_1394_ENABLE, ofn, 0, 0);
3667 			pmac_call_feature(PMAC_FTR_1394_CABLE_POWER, ofn, 0, 0);
3668 		}
3669 	}
3670 }
3671 #else
3672 static inline void pmac_ohci_on(struct pci_dev *dev) {}
3673 static inline void pmac_ohci_off(struct pci_dev *dev) {}
3674 #endif /* CONFIG_PPC_PMAC */
3675 
3676 static void release_ohci(struct device *dev, void *data)
3677 {
3678 	struct pci_dev *pdev = to_pci_dev(dev);
3679 	struct fw_ohci *ohci = pci_get_drvdata(pdev);
3680 
3681 	pmac_ohci_off(pdev);
3682 
3683 	ar_context_release(&ohci->ar_response_ctx);
3684 	ar_context_release(&ohci->ar_request_ctx);
3685 
3686 	dev_notice(dev, "removed fw-ohci device\n");
3687 }
3688 
3689 static int pci_probe(struct pci_dev *dev,
3690 			       const struct pci_device_id *ent)
3691 {
3692 	struct fw_ohci *ohci;
3693 	u32 bus_options, max_receive, link_speed, version;
3694 	u64 guid;
3695 	int i, flags, irq, err;
3696 
3697 	if (dev->vendor == PCI_VENDOR_ID_PINNACLE_SYSTEMS) {
3698 		dev_err(&dev->dev, "Pinnacle MovieBoard is not yet supported\n");
3699 		return -ENOSYS;
3700 	}
3701 
3702 	ohci = devres_alloc(release_ohci, sizeof(*ohci), GFP_KERNEL);
3703 	if (ohci == NULL)
3704 		return -ENOMEM;
3705 	fw_card_initialize(&ohci->card, &ohci_driver, &dev->dev);
3706 	pci_set_drvdata(dev, ohci);
3707 	pmac_ohci_on(dev);
3708 	devres_add(&dev->dev, ohci);
3709 
3710 	err = pcim_enable_device(dev);
3711 	if (err) {
3712 		dev_err(&dev->dev, "failed to enable OHCI hardware\n");
3713 		return err;
3714 	}
3715 
3716 	pci_set_master(dev);
3717 	pci_write_config_dword(dev, OHCI1394_PCI_HCI_Control, 0);
3718 
3719 	spin_lock_init(&ohci->lock);
3720 	mutex_init(&ohci->phy_reg_mutex);
3721 
3722 	if (!(pci_resource_flags(dev, 0) & IORESOURCE_MEM) ||
3723 	    pci_resource_len(dev, 0) < OHCI1394_REGISTER_SIZE) {
3724 		ohci_err(ohci, "invalid MMIO resource\n");
3725 		return -ENXIO;
3726 	}
3727 
3728 	ohci->registers = pcim_iomap_region(dev, 0, ohci_driver_name);
3729 	if (IS_ERR(ohci->registers)) {
3730 		ohci_err(ohci, "request and map MMIO resource unavailable\n");
3731 		return -ENXIO;
3732 	}
3733 
3734 	for (i = 0; i < ARRAY_SIZE(ohci_quirks); i++)
3735 		if ((ohci_quirks[i].vendor == dev->vendor) &&
3736 		    (ohci_quirks[i].device == (unsigned short)PCI_ANY_ID ||
3737 		     ohci_quirks[i].device == dev->device) &&
3738 		    (ohci_quirks[i].revision == (unsigned short)PCI_ANY_ID ||
3739 		     ohci_quirks[i].revision >= dev->revision)) {
3740 			ohci->quirks = ohci_quirks[i].flags;
3741 			break;
3742 		}
3743 	if (param_quirks)
3744 		ohci->quirks = param_quirks;
3745 
3746 	if (detect_vt630x_with_asm1083_on_amd_ryzen_machine(dev))
3747 		ohci->quirks |= QUIRK_REBOOT_BY_CYCLE_TIMER_READ;
3748 
3749 	/*
3750 	 * Because dma_alloc_coherent() allocates at least one page,
3751 	 * we save space by using a common buffer for the AR request/
3752 	 * response descriptors and the self IDs buffer.
3753 	 */
3754 	BUILD_BUG_ON(AR_BUFFERS * sizeof(struct descriptor) > PAGE_SIZE/4);
3755 	BUILD_BUG_ON(SELF_ID_BUF_SIZE > PAGE_SIZE/2);
3756 	ohci->misc_buffer = dmam_alloc_coherent(&dev->dev, PAGE_SIZE, &ohci->misc_buffer_bus,
3757 						GFP_KERNEL);
3758 	if (!ohci->misc_buffer)
3759 		return -ENOMEM;
3760 
3761 	err = ar_context_init(&ohci->ar_request_ctx, ohci, 0,
3762 			      OHCI1394_AsReqRcvContextControlSet);
3763 	if (err < 0)
3764 		return err;
3765 
3766 	err = ar_context_init(&ohci->ar_response_ctx, ohci, PAGE_SIZE/4,
3767 			      OHCI1394_AsRspRcvContextControlSet);
3768 	if (err < 0)
3769 		return err;
3770 
3771 	err = context_init(&ohci->at_request_ctx.context, ohci,
3772 			   OHCI1394_AsReqTrContextControlSet, handle_at_packet);
3773 	if (err < 0)
3774 		return err;
3775 	INIT_WORK(&ohci->at_request_ctx.work, ohci_at_context_work);
3776 
3777 	err = context_init(&ohci->at_response_ctx.context, ohci,
3778 			   OHCI1394_AsRspTrContextControlSet, handle_at_packet);
3779 	if (err < 0)
3780 		return err;
3781 	INIT_WORK(&ohci->at_response_ctx.work, ohci_at_context_work);
3782 
3783 	at_local_init(&ohci->at_request_local, at_request_local_work);
3784 	at_local_init(&ohci->at_response_local, at_response_local_work);
3785 
3786 	reg_write(ohci, OHCI1394_IsoRecvIntMaskSet, ~0);
3787 	ohci->ir_context_channels = ~0ULL;
3788 	ohci->ir_context_support = reg_read(ohci, OHCI1394_IsoRecvIntMaskSet);
3789 	reg_write(ohci, OHCI1394_IsoRecvIntMaskClear, ~0);
3790 	ohci->ir_context_mask = ohci->ir_context_support;
3791 	ohci->n_ir = hweight32(ohci->ir_context_mask);
3792 	ohci->ir_context_list = devm_kzalloc_objs(&dev->dev, struct iso_context,
3793 						  ohci->n_ir);
3794 	if (!ohci->ir_context_list)
3795 		return -ENOMEM;
3796 
3797 	reg_write(ohci, OHCI1394_IsoXmitIntMaskSet, ~0);
3798 	ohci->it_context_support = reg_read(ohci, OHCI1394_IsoXmitIntMaskSet);
3799 	/* JMicron JMB38x often shows 0 at first read, just ignore it */
3800 	if (!ohci->it_context_support) {
3801 		ohci_notice(ohci, "overriding IsoXmitIntMask\n");
3802 		ohci->it_context_support = 0xf;
3803 	}
3804 	reg_write(ohci, OHCI1394_IsoXmitIntMaskClear, ~0);
3805 	ohci->it_context_mask = ohci->it_context_support;
3806 	ohci->n_it = hweight32(ohci->it_context_mask);
3807 	ohci->it_context_list = devm_kzalloc_objs(&dev->dev, struct iso_context,
3808 						  ohci->n_it);
3809 	if (!ohci->it_context_list)
3810 		return -ENOMEM;
3811 
3812 	ohci->self_id     = ohci->misc_buffer     + PAGE_SIZE/2;
3813 	ohci->self_id_bus = ohci->misc_buffer_bus + PAGE_SIZE/2;
3814 
3815 	bus_options = reg_read(ohci, OHCI1394_BusOptions);
3816 	max_receive = (bus_options >> 12) & 0xf;
3817 	link_speed = bus_options & 0x7;
3818 	guid = ((u64) reg_read(ohci, OHCI1394_GUIDHi) << 32) |
3819 		reg_read(ohci, OHCI1394_GUIDLo);
3820 
3821 	flags = PCI_IRQ_INTX;
3822 	if (!(ohci->quirks & QUIRK_NO_MSI))
3823 		flags |= PCI_IRQ_MSI;
3824 	err = pci_alloc_irq_vectors(dev, 1, 1, flags);
3825 	if (err < 0)
3826 		return err;
3827 	irq = pci_irq_vector(dev, 0);
3828 	if (irq < 0) {
3829 		err = irq;
3830 		goto fail_msi;
3831 	}
3832 
3833 	// IRQF_ONESHOT is not applied so that any events are handled in the hardIRQ handler during
3834 	// invoking the threaded IRQ handler for SelfIDComplete event.
3835 	err = request_threaded_irq(irq, irq_handler, handle_selfid_complete_event,
3836 				   pci_dev_msi_enabled(dev) ? 0 : IRQF_SHARED, ohci_driver_name,
3837 				   ohci);
3838 	if (err < 0) {
3839 		ohci_err(ohci, "failed to allocate interrupt %d\n", irq);
3840 		goto fail_msi;
3841 	}
3842 
3843 	err = fw_card_add(&ohci->card, max_receive, link_speed, guid, ohci->n_it + ohci->n_ir);
3844 	if (err)
3845 		goto fail_irq;
3846 
3847 	version = reg_read(ohci, OHCI1394_Version) & 0x00ff00ff;
3848 	ohci_notice(ohci,
3849 		    "added OHCI v%x.%x device as card %d, "
3850 		    "%d IR + %d IT contexts, quirks 0x%x%s\n",
3851 		    version >> 16, version & 0xff, ohci->card.index,
3852 		    ohci->n_ir, ohci->n_it, ohci->quirks,
3853 		    reg_read(ohci, OHCI1394_PhyUpperBound) ?
3854 			", physUB" : "");
3855 
3856 	return 0;
3857 
3858  fail_irq:
3859 	free_irq(irq, ohci);
3860  fail_msi:
3861 	pci_free_irq_vectors(dev);
3862 
3863 	return err;
3864 }
3865 
3866 static void pci_remove(struct pci_dev *dev)
3867 {
3868 	struct fw_ohci *ohci = pci_get_drvdata(dev);
3869 	int irq;
3870 
3871 	fw_core_remove_card(&ohci->card);
3872 
3873 	software_reset(ohci);
3874 
3875 	irq = pci_irq_vector(dev, 0);
3876 	if (irq >= 0)
3877 		free_irq(irq, ohci);
3878 	pci_free_irq_vectors(dev);
3879 
3880 	dev_notice(&dev->dev, "removing fw-ohci device\n");
3881 }
3882 
3883 static int pci_suspend(struct device *dev)
3884 {
3885 	struct pci_dev *pdev = to_pci_dev(dev);
3886 	struct fw_ohci *ohci = pci_get_drvdata(pdev);
3887 
3888 	software_reset(ohci);
3889 	pmac_ohci_off(pdev);
3890 
3891 	return 0;
3892 }
3893 
3894 
3895 static int pci_resume(struct device *dev)
3896 {
3897 	struct pci_dev *pdev = to_pci_dev(dev);
3898 	struct fw_ohci *ohci = pci_get_drvdata(pdev);
3899 	int err;
3900 
3901 	pmac_ohci_on(pdev);
3902 
3903 	/* Some systems don't setup GUID register on resume from ram  */
3904 	if (!reg_read(ohci, OHCI1394_GUIDLo) &&
3905 					!reg_read(ohci, OHCI1394_GUIDHi)) {
3906 		reg_write(ohci, OHCI1394_GUIDLo, (u32)ohci->card.guid);
3907 		reg_write(ohci, OHCI1394_GUIDHi, (u32)(ohci->card.guid >> 32));
3908 	}
3909 
3910 	err = ohci_enable(&ohci->card, NULL, 0);
3911 	if (err)
3912 		return err;
3913 
3914 	ohci_resume_iso_dma(ohci);
3915 
3916 	return 0;
3917 }
3918 
3919 static const struct pci_device_id pci_table[] = {
3920 	{ PCI_DEVICE_CLASS(PCI_CLASS_SERIAL_FIREWIRE_OHCI, ~0) },
3921 	{ }
3922 };
3923 
3924 MODULE_DEVICE_TABLE(pci, pci_table);
3925 
3926 static DEFINE_SIMPLE_DEV_PM_OPS(pci_pm_ops, pci_suspend, pci_resume);
3927 
3928 static struct pci_driver fw_ohci_pci_driver = {
3929 	.name		= ohci_driver_name,
3930 	.id_table	= pci_table,
3931 	.probe		= pci_probe,
3932 	.remove		= pci_remove,
3933 	.driver.pm	= pm_sleep_ptr(&pci_pm_ops),
3934 };
3935 
3936 static int __init fw_ohci_init(void)
3937 {
3938 	return pci_register_driver(&fw_ohci_pci_driver);
3939 }
3940 
3941 static void __exit fw_ohci_cleanup(void)
3942 {
3943 	pci_unregister_driver(&fw_ohci_pci_driver);
3944 }
3945 
3946 module_init(fw_ohci_init);
3947 module_exit(fw_ohci_cleanup);
3948 
3949 MODULE_AUTHOR("Kristian Hoegsberg <krh@bitplanet.net>");
3950 MODULE_DESCRIPTION("Driver for PCI OHCI IEEE1394 controllers");
3951 MODULE_LICENSE("GPL");
3952 
3953 /* Provide a module alias so root-on-sbp2 initrds don't break. */
3954 MODULE_ALIAS("ohci1394");
3955