xref: /linux/drivers/firewire/core-card.c (revision 07fdad3a93756b872da7b53647715c48d0f4a2d0)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (C) 2005-2007  Kristian Hoegsberg <krh@bitplanet.net>
4  */
5 
6 #include <linux/bug.h>
7 #include <linux/completion.h>
8 #include <linux/crc-itu-t.h>
9 #include <linux/device.h>
10 #include <linux/errno.h>
11 #include <linux/firewire.h>
12 #include <linux/firewire-constants.h>
13 #include <linux/jiffies.h>
14 #include <linux/kernel.h>
15 #include <linux/kref.h>
16 #include <linux/list.h>
17 #include <linux/module.h>
18 #include <linux/mutex.h>
19 #include <linux/spinlock.h>
20 #include <linux/workqueue.h>
21 
22 #include <linux/atomic.h>
23 #include <asm/byteorder.h>
24 
25 #include "core.h"
26 #include <trace/events/firewire.h>
27 
28 #define define_fw_printk_level(func, kern_level)		\
29 void func(const struct fw_card *card, const char *fmt, ...)	\
30 {								\
31 	struct va_format vaf;					\
32 	va_list args;						\
33 								\
34 	va_start(args, fmt);					\
35 	vaf.fmt = fmt;						\
36 	vaf.va = &args;						\
37 	printk(kern_level KBUILD_MODNAME " %s: %pV",		\
38 	       dev_name(card->device), &vaf);			\
39 	va_end(args);						\
40 }
41 define_fw_printk_level(fw_err, KERN_ERR);
42 define_fw_printk_level(fw_notice, KERN_NOTICE);
43 
44 int fw_compute_block_crc(__be32 *block)
45 {
46 	int length;
47 	u16 crc;
48 
49 	length = (be32_to_cpu(block[0]) >> 16) & 0xff;
50 	crc = crc_itu_t(0, (u8 *)&block[1], length * 4);
51 	*block |= cpu_to_be32(crc);
52 
53 	return length;
54 }
55 
56 static DEFINE_MUTEX(card_mutex);
57 static LIST_HEAD(card_list);
58 
59 static LIST_HEAD(descriptor_list);
60 static int descriptor_count;
61 
62 static __be32 tmp_config_rom[256];
63 /* ROM header, bus info block, root dir header, capabilities = 7 quadlets */
64 static size_t config_rom_length = 1 + 4 + 1 + 1;
65 
66 #define BIB_CRC(v)		((v) <<  0)
67 #define BIB_CRC_LENGTH(v)	((v) << 16)
68 #define BIB_INFO_LENGTH(v)	((v) << 24)
69 #define BIB_BUS_NAME		0x31333934 /* "1394" */
70 #define BIB_LINK_SPEED(v)	((v) <<  0)
71 #define BIB_GENERATION(v)	((v) <<  4)
72 #define BIB_MAX_ROM(v)		((v) <<  8)
73 #define BIB_MAX_RECEIVE(v)	((v) << 12)
74 #define BIB_CYC_CLK_ACC(v)	((v) << 16)
75 #define BIB_PMC			((1) << 27)
76 #define BIB_BMC			((1) << 28)
77 #define BIB_ISC			((1) << 29)
78 #define BIB_CMC			((1) << 30)
79 #define BIB_IRMC		((1) << 31)
80 #define NODE_CAPABILITIES	0x0c0083c0 /* per IEEE 1394 clause 8.3.2.6.5.2 */
81 
82 /*
83  * IEEE-1394 specifies a default SPLIT_TIMEOUT value of 800 cycles (100 ms),
84  * but we have to make it longer because there are many devices whose firmware
85  * is just too slow for that.
86  */
87 #define DEFAULT_SPLIT_TIMEOUT	(2 * 8000)
88 
89 #define CANON_OUI		0x000085
90 
91 static void generate_config_rom(struct fw_card *card, __be32 *config_rom)
92 {
93 	struct fw_descriptor *desc;
94 	int i, j, k, length;
95 
96 	/*
97 	 * Initialize contents of config rom buffer.  On the OHCI
98 	 * controller, block reads to the config rom accesses the host
99 	 * memory, but quadlet read access the hardware bus info block
100 	 * registers.  That's just crack, but it means we should make
101 	 * sure the contents of bus info block in host memory matches
102 	 * the version stored in the OHCI registers.
103 	 */
104 
105 	config_rom[0] = cpu_to_be32(
106 		BIB_CRC_LENGTH(4) | BIB_INFO_LENGTH(4) | BIB_CRC(0));
107 	config_rom[1] = cpu_to_be32(BIB_BUS_NAME);
108 	config_rom[2] = cpu_to_be32(
109 		BIB_LINK_SPEED(card->link_speed) |
110 		BIB_GENERATION(card->config_rom_generation++ % 14 + 2) |
111 		BIB_MAX_ROM(2) |
112 		BIB_MAX_RECEIVE(card->max_receive) |
113 		BIB_BMC | BIB_ISC | BIB_CMC | BIB_IRMC);
114 	config_rom[3] = cpu_to_be32(card->guid >> 32);
115 	config_rom[4] = cpu_to_be32(card->guid);
116 
117 	/* Generate root directory. */
118 	config_rom[6] = cpu_to_be32(NODE_CAPABILITIES);
119 	i = 7;
120 	j = 7 + descriptor_count;
121 
122 	/* Generate root directory entries for descriptors. */
123 	list_for_each_entry (desc, &descriptor_list, link) {
124 		if (desc->immediate > 0)
125 			config_rom[i++] = cpu_to_be32(desc->immediate);
126 		config_rom[i] = cpu_to_be32(desc->key | (j - i));
127 		i++;
128 		j += desc->length;
129 	}
130 
131 	/* Update root directory length. */
132 	config_rom[5] = cpu_to_be32((i - 5 - 1) << 16);
133 
134 	/* End of root directory, now copy in descriptors. */
135 	list_for_each_entry (desc, &descriptor_list, link) {
136 		for (k = 0; k < desc->length; k++)
137 			config_rom[i + k] = cpu_to_be32(desc->data[k]);
138 		i += desc->length;
139 	}
140 
141 	/* Calculate CRCs for all blocks in the config rom.  This
142 	 * assumes that CRC length and info length are identical for
143 	 * the bus info block, which is always the case for this
144 	 * implementation. */
145 	for (i = 0; i < j; i += length + 1)
146 		length = fw_compute_block_crc(config_rom + i);
147 
148 	WARN_ON(j != config_rom_length);
149 }
150 
151 static void update_config_roms(void)
152 {
153 	struct fw_card *card;
154 
155 	list_for_each_entry (card, &card_list, link) {
156 		generate_config_rom(card, tmp_config_rom);
157 		card->driver->set_config_rom(card, tmp_config_rom,
158 					     config_rom_length);
159 	}
160 }
161 
162 static size_t required_space(struct fw_descriptor *desc)
163 {
164 	/* descriptor + entry into root dir + optional immediate entry */
165 	return desc->length + 1 + (desc->immediate > 0 ? 1 : 0);
166 }
167 
168 int fw_core_add_descriptor(struct fw_descriptor *desc)
169 {
170 	size_t i;
171 
172 	/*
173 	 * Check descriptor is valid; the length of all blocks in the
174 	 * descriptor has to add up to exactly the length of the
175 	 * block.
176 	 */
177 	i = 0;
178 	while (i < desc->length)
179 		i += (desc->data[i] >> 16) + 1;
180 
181 	if (i != desc->length)
182 		return -EINVAL;
183 
184 	guard(mutex)(&card_mutex);
185 
186 	if (config_rom_length + required_space(desc) > 256)
187 		return -EBUSY;
188 
189 	list_add_tail(&desc->link, &descriptor_list);
190 	config_rom_length += required_space(desc);
191 	descriptor_count++;
192 	if (desc->immediate > 0)
193 		descriptor_count++;
194 	update_config_roms();
195 
196 	return 0;
197 }
198 EXPORT_SYMBOL(fw_core_add_descriptor);
199 
200 void fw_core_remove_descriptor(struct fw_descriptor *desc)
201 {
202 	guard(mutex)(&card_mutex);
203 
204 	list_del(&desc->link);
205 	config_rom_length -= required_space(desc);
206 	descriptor_count--;
207 	if (desc->immediate > 0)
208 		descriptor_count--;
209 	update_config_roms();
210 }
211 EXPORT_SYMBOL(fw_core_remove_descriptor);
212 
213 static int reset_bus(struct fw_card *card, bool short_reset)
214 {
215 	int reg = short_reset ? 5 : 1;
216 	int bit = short_reset ? PHY_BUS_SHORT_RESET : PHY_BUS_RESET;
217 
218 	trace_bus_reset_initiate(card->index, card->generation, short_reset);
219 
220 	return card->driver->update_phy_reg(card, reg, 0, bit);
221 }
222 
223 void fw_schedule_bus_reset(struct fw_card *card, bool delayed, bool short_reset)
224 {
225 	trace_bus_reset_schedule(card->index, card->generation, short_reset);
226 
227 	/* We don't try hard to sort out requests of long vs. short resets. */
228 	card->br_short = short_reset;
229 
230 	/* Use an arbitrary short delay to combine multiple reset requests. */
231 	fw_card_get(card);
232 	if (!queue_delayed_work(fw_workqueue, &card->br_work, delayed ? msecs_to_jiffies(10) : 0))
233 		fw_card_put(card);
234 }
235 EXPORT_SYMBOL(fw_schedule_bus_reset);
236 
237 static void br_work(struct work_struct *work)
238 {
239 	struct fw_card *card = from_work(card, work, br_work.work);
240 
241 	/* Delay for 2s after last reset per IEEE 1394 clause 8.2.1. */
242 	if (card->reset_jiffies != 0 &&
243 	    time_is_after_jiffies64(card->reset_jiffies + secs_to_jiffies(2))) {
244 		trace_bus_reset_postpone(card->index, card->generation, card->br_short);
245 
246 		if (!queue_delayed_work(fw_workqueue, &card->br_work, secs_to_jiffies(2)))
247 			fw_card_put(card);
248 		return;
249 	}
250 
251 	fw_send_phy_config(card, FW_PHY_CONFIG_NO_NODE_ID, card->generation,
252 			   FW_PHY_CONFIG_CURRENT_GAP_COUNT);
253 	reset_bus(card, card->br_short);
254 	fw_card_put(card);
255 }
256 
257 static void allocate_broadcast_channel(struct fw_card *card, int generation)
258 {
259 	int channel, bandwidth = 0;
260 
261 	if (!card->broadcast_channel_allocated) {
262 		fw_iso_resource_manage(card, generation, 1ULL << 31,
263 				       &channel, &bandwidth, true);
264 		if (channel != 31) {
265 			fw_notice(card, "failed to allocate broadcast channel\n");
266 			return;
267 		}
268 		card->broadcast_channel_allocated = true;
269 	}
270 
271 	device_for_each_child(card->device, (void *)(long)generation,
272 			      fw_device_set_broadcast_channel);
273 }
274 
275 void fw_schedule_bm_work(struct fw_card *card, unsigned long delay)
276 {
277 	fw_card_get(card);
278 	if (!schedule_delayed_work(&card->bm_work, delay))
279 		fw_card_put(card);
280 }
281 
282 enum bm_contention_outcome {
283 	// The bus management contention window is not expired.
284 	BM_CONTENTION_OUTCOME_WITHIN_WINDOW = 0,
285 	// The IRM node has link off.
286 	BM_CONTENTION_OUTCOME_IRM_HAS_LINK_OFF,
287 	// The IRM node complies IEEE 1394:1994 only.
288 	BM_CONTENTION_OUTCOME_IRM_COMPLIES_1394_1995_ONLY,
289 	// Another bus reset, BM work has been rescheduled.
290 	BM_CONTENTION_OUTCOME_AT_NEW_GENERATION,
291 	// We have been unable to send the lock request to IRM node due to some local problem.
292 	BM_CONTENTION_OUTCOME_LOCAL_PROBLEM_AT_TRANSACTION,
293 	// The lock request failed, maybe the IRM isn't really IRM capable after all.
294 	BM_CONTENTION_OUTCOME_IRM_IS_NOT_CAPABLE_FOR_IRM,
295 	// Somebody else is BM.
296 	BM_CONTENTION_OUTCOME_IRM_HOLDS_ANOTHER_NODE_AS_BM,
297 	// The local node succeeds after contending for bus manager.
298 	BM_CONTENTION_OUTCOME_IRM_HOLDS_LOCAL_NODE_AS_BM,
299 };
300 
301 static enum bm_contention_outcome contend_for_bm(struct fw_card *card)
302 __must_hold(&card->lock)
303 {
304 	int generation = card->generation;
305 	int local_id = card->local_node->node_id;
306 	__be32 data[2] = {
307 		cpu_to_be32(BUS_MANAGER_ID_NOT_REGISTERED),
308 		cpu_to_be32(local_id),
309 	};
310 	bool grace = time_is_before_jiffies64(card->reset_jiffies + msecs_to_jiffies(125));
311 	bool irm_is_1394_1995_only = false;
312 	bool keep_this_irm = false;
313 	struct fw_node *irm_node;
314 	struct fw_device *irm_device;
315 	int irm_node_id;
316 	int rcode;
317 
318 	lockdep_assert_held(&card->lock);
319 
320 	if (!grace) {
321 		if (!is_next_generation(generation, card->bm_generation) || card->bm_abdicate)
322 			return BM_CONTENTION_OUTCOME_WITHIN_WINDOW;
323 	}
324 
325 	irm_node = card->irm_node;
326 	if (!irm_node->link_on) {
327 		fw_notice(card, "IRM has link off, making local node (%02x) root\n", local_id);
328 		return BM_CONTENTION_OUTCOME_IRM_HAS_LINK_OFF;
329 	}
330 
331 	irm_device = fw_node_get_device(irm_node);
332 	if (irm_device && irm_device->config_rom) {
333 		irm_is_1394_1995_only = (irm_device->config_rom[2] & 0x000000f0) == 0;
334 
335 		// Canon MV5i works unreliably if it is not root node.
336 		keep_this_irm = irm_device->config_rom[3] >> 8 == CANON_OUI;
337 	}
338 
339 	if (irm_is_1394_1995_only && !keep_this_irm) {
340 		fw_notice(card, "IRM is not 1394a compliant, making local node (%02x) root\n",
341 			  local_id);
342 		return BM_CONTENTION_OUTCOME_IRM_COMPLIES_1394_1995_ONLY;
343 	}
344 
345 	irm_node_id = irm_node->node_id;
346 
347 	spin_unlock_irq(&card->lock);
348 
349 	rcode = fw_run_transaction(card, TCODE_LOCK_COMPARE_SWAP, irm_node_id, generation,
350 				   SCODE_100, CSR_REGISTER_BASE + CSR_BUS_MANAGER_ID, data,
351 				   sizeof(data));
352 
353 	spin_lock_irq(&card->lock);
354 
355 	switch (rcode) {
356 	case RCODE_GENERATION:
357 		return BM_CONTENTION_OUTCOME_AT_NEW_GENERATION;
358 	case RCODE_SEND_ERROR:
359 		return BM_CONTENTION_OUTCOME_LOCAL_PROBLEM_AT_TRANSACTION;
360 	case RCODE_COMPLETE:
361 	{
362 		int bm_id = be32_to_cpu(data[0]);
363 
364 		// Used by cdev layer for "struct fw_cdev_event_bus_reset".
365 		if (bm_id != BUS_MANAGER_ID_NOT_REGISTERED)
366 			card->bm_node_id = 0xffc0 & bm_id;
367 		else
368 			card->bm_node_id = local_id;
369 
370 		if (bm_id != BUS_MANAGER_ID_NOT_REGISTERED)
371 			return BM_CONTENTION_OUTCOME_IRM_HOLDS_ANOTHER_NODE_AS_BM;
372 		else
373 			return BM_CONTENTION_OUTCOME_IRM_HOLDS_LOCAL_NODE_AS_BM;
374 	}
375 	default:
376 		if (!keep_this_irm) {
377 			fw_notice(card, "BM lock failed (%s), making local node (%02x) root\n",
378 				  fw_rcode_string(rcode), local_id);
379 			return BM_CONTENTION_OUTCOME_IRM_COMPLIES_1394_1995_ONLY;
380 		} else {
381 			return BM_CONTENTION_OUTCOME_IRM_IS_NOT_CAPABLE_FOR_IRM;
382 		}
383 	}
384 }
385 
386 DEFINE_FREE(node_unref, struct fw_node *, if (_T) fw_node_put(_T))
387 DEFINE_FREE(card_unref, struct fw_card *, if (_T) fw_card_put(_T))
388 
389 static void bm_work(struct work_struct *work)
390 {
391 	static const char gap_count_table[] = {
392 		63, 5, 7, 8, 10, 13, 16, 18, 21, 24, 26, 29, 32, 35, 37, 40
393 	};
394 	struct fw_card *card __free(card_unref) = from_work(card, work, bm_work.work);
395 	struct fw_node *root_node __free(node_unref) = NULL;
396 	int root_id, new_root_id, irm_id, local_id;
397 	int expected_gap_count, generation;
398 	bool stand_for_root = false;
399 
400 	spin_lock_irq(&card->lock);
401 
402 	if (card->local_node == NULL) {
403 		spin_unlock_irq(&card->lock);
404 		return;
405 	}
406 
407 	generation = card->generation;
408 
409 	root_node = fw_node_get(card->root_node);
410 
411 	root_id  = root_node->node_id;
412 	irm_id   = card->irm_node->node_id;
413 	local_id = card->local_node->node_id;
414 
415 	if (card->bm_generation != generation) {
416 		enum bm_contention_outcome result = contend_for_bm(card);
417 
418 		switch (result) {
419 		case BM_CONTENTION_OUTCOME_WITHIN_WINDOW:
420 			spin_unlock_irq(&card->lock);
421 			fw_schedule_bm_work(card, msecs_to_jiffies(125));
422 			return;
423 		case BM_CONTENTION_OUTCOME_IRM_HAS_LINK_OFF:
424 			stand_for_root = true;
425 			break;
426 		case BM_CONTENTION_OUTCOME_IRM_COMPLIES_1394_1995_ONLY:
427 			stand_for_root = true;
428 			break;
429 		case BM_CONTENTION_OUTCOME_AT_NEW_GENERATION:
430 			// BM work has been rescheduled.
431 			spin_unlock_irq(&card->lock);
432 			return;
433 		case BM_CONTENTION_OUTCOME_LOCAL_PROBLEM_AT_TRANSACTION:
434 			// Let's try again later and hope that the local problem has gone away by
435 			// then.
436 			spin_unlock_irq(&card->lock);
437 			fw_schedule_bm_work(card, msecs_to_jiffies(125));
438 			return;
439 		case BM_CONTENTION_OUTCOME_IRM_IS_NOT_CAPABLE_FOR_IRM:
440 			// Let's do a bus reset and pick the local node as root, and thus, IRM.
441 			stand_for_root = true;
442 			break;
443 		case BM_CONTENTION_OUTCOME_IRM_HOLDS_ANOTHER_NODE_AS_BM:
444 			if (local_id == irm_id) {
445 				// Only acts as IRM.
446 				spin_unlock_irq(&card->lock);
447 				allocate_broadcast_channel(card, generation);
448 				spin_lock_irq(&card->lock);
449 			}
450 			fallthrough;
451 		case BM_CONTENTION_OUTCOME_IRM_HOLDS_LOCAL_NODE_AS_BM:
452 		default:
453 			card->bm_generation = generation;
454 			break;
455 		}
456 	}
457 
458 	// We're bus manager for this generation, so next step is to make sure we have an active
459 	// cycle master and do gap count optimization.
460 	if (!stand_for_root) {
461 		if (card->gap_count == GAP_COUNT_MISMATCHED) {
462 			// If self IDs have inconsistent gap counts, do a
463 			// bus reset ASAP. The config rom read might never
464 			// complete, so don't wait for it. However, still
465 			// send a PHY configuration packet prior to the
466 			// bus reset. The PHY configuration packet might
467 			// fail, but 1394-2008 8.4.5.2 explicitly permits
468 			// it in this case, so it should be safe to try.
469 			stand_for_root = true;
470 
471 			// We must always send a bus reset if the gap count
472 			// is inconsistent, so bypass the 5-reset limit.
473 			card->bm_retries = 0;
474 		} else {
475 			// Now investigate root node.
476 			struct fw_device *root_device = fw_node_get_device(root_node);
477 
478 			if (root_device == NULL) {
479 				// Either link_on is false, or we failed to read the
480 				// config rom.  In either case, pick another root.
481 				stand_for_root = true;
482 			} else {
483 				bool root_device_is_running =
484 					atomic_read(&root_device->state) == FW_DEVICE_RUNNING;
485 
486 				if (!root_device_is_running) {
487 					// If we haven't probed this device yet, bail out now
488 					// and let's try again once that's done.
489 					spin_unlock_irq(&card->lock);
490 					return;
491 				} else if (!root_device->cmc) {
492 					// Current root has an active link layer and we
493 					// successfully read the config rom, but it's not
494 					// cycle master capable.
495 					stand_for_root = true;
496 				}
497 			}
498 		}
499 	}
500 
501 	if (stand_for_root) {
502 		new_root_id = local_id;
503 	} else {
504 		// We will send out a force root packet for this node as part of the gap count
505 		// optimization on behalf of the node.
506 		new_root_id = root_id;
507 	}
508 
509 	/*
510 	 * Pick a gap count from 1394a table E-1.  The table doesn't cover
511 	 * the typically much larger 1394b beta repeater delays though.
512 	 */
513 	if (!card->beta_repeaters_present &&
514 	    root_node->max_hops < ARRAY_SIZE(gap_count_table))
515 		expected_gap_count = gap_count_table[root_node->max_hops];
516 	else
517 		expected_gap_count = 63;
518 
519 	// Finally, figure out if we should do a reset or not. If we have done less than 5 resets
520 	// with the same physical topology and we have either a new root or a new gap count
521 	// setting, let's do it.
522 	if (card->bm_retries++ < 5 && (card->gap_count != expected_gap_count || new_root_id != root_id)) {
523 		int card_gap_count = card->gap_count;
524 
525 		spin_unlock_irq(&card->lock);
526 
527 		fw_notice(card, "phy config: new root=%x, gap_count=%d\n",
528 			  new_root_id, expected_gap_count);
529 		fw_send_phy_config(card, new_root_id, generation, expected_gap_count);
530 		/*
531 		 * Where possible, use a short bus reset to minimize
532 		 * disruption to isochronous transfers. But in the event
533 		 * of a gap count inconsistency, use a long bus reset.
534 		 *
535 		 * As noted in 1394a 8.4.6.2, nodes on a mixed 1394/1394a bus
536 		 * may set different gap counts after a bus reset. On a mixed
537 		 * 1394/1394a bus, a short bus reset can get doubled. Some
538 		 * nodes may treat the double reset as one bus reset and others
539 		 * may treat it as two, causing a gap count inconsistency
540 		 * again. Using a long bus reset prevents this.
541 		 */
542 		reset_bus(card, card_gap_count != 0);
543 		/* Will allocate broadcast channel after the reset. */
544 	} else {
545 		struct fw_device *root_device = fw_node_get_device(root_node);
546 
547 		spin_unlock_irq(&card->lock);
548 
549 		if (root_device && root_device->cmc) {
550 			// Make sure that the cycle master sends cycle start packets.
551 			__be32 data = cpu_to_be32(CSR_STATE_BIT_CMSTR);
552 			int rcode = fw_run_transaction(card, TCODE_WRITE_QUADLET_REQUEST,
553 					root_id, generation, SCODE_100,
554 					CSR_REGISTER_BASE + CSR_STATE_SET,
555 					&data, sizeof(data));
556 			if (rcode == RCODE_GENERATION)
557 				return;
558 		}
559 
560 		if (local_id == irm_id)
561 			allocate_broadcast_channel(card, generation);
562 	}
563 }
564 
565 void fw_card_initialize(struct fw_card *card,
566 			const struct fw_card_driver *driver,
567 			struct device *device)
568 {
569 	static atomic_t index = ATOMIC_INIT(-1);
570 
571 	card->index = atomic_inc_return(&index);
572 	card->driver = driver;
573 	card->device = device;
574 
575 	card->transactions.current_tlabel = 0;
576 	card->transactions.tlabel_mask = 0;
577 	INIT_LIST_HEAD(&card->transactions.list);
578 	spin_lock_init(&card->transactions.lock);
579 
580 	card->split_timeout.hi = DEFAULT_SPLIT_TIMEOUT / 8000;
581 	card->split_timeout.lo = (DEFAULT_SPLIT_TIMEOUT % 8000) << 19;
582 	card->split_timeout.cycles = DEFAULT_SPLIT_TIMEOUT;
583 	card->split_timeout.jiffies = isoc_cycles_to_jiffies(DEFAULT_SPLIT_TIMEOUT);
584 	spin_lock_init(&card->split_timeout.lock);
585 
586 	card->color = 0;
587 	card->broadcast_channel = BROADCAST_CHANNEL_INITIAL;
588 
589 	kref_init(&card->kref);
590 	init_completion(&card->done);
591 
592 	spin_lock_init(&card->lock);
593 
594 	card->local_node = NULL;
595 
596 	INIT_DELAYED_WORK(&card->br_work, br_work);
597 	INIT_DELAYED_WORK(&card->bm_work, bm_work);
598 }
599 EXPORT_SYMBOL(fw_card_initialize);
600 
601 DEFINE_FREE(workqueue_destroy, struct workqueue_struct *, if (_T) destroy_workqueue(_T))
602 
603 int fw_card_add(struct fw_card *card, u32 max_receive, u32 link_speed, u64 guid,
604 		unsigned int supported_isoc_contexts)
605 {
606 	struct workqueue_struct *isoc_wq __free(workqueue_destroy) = NULL;
607 	struct workqueue_struct *async_wq __free(workqueue_destroy) = NULL;
608 	int ret;
609 
610 	// This workqueue should be:
611 	//  * != WQ_BH			Sleepable.
612 	//  * == WQ_UNBOUND		Any core can process data for isoc context. The
613 	//				implementation of unit protocol could consumes the core
614 	//				longer somehow.
615 	//  * != WQ_MEM_RECLAIM		Not used for any backend of block device.
616 	//  * == WQ_FREEZABLE		Isochronous communication is at regular interval in real
617 	//				time, thus should be drained if possible at freeze phase.
618 	//  * == WQ_HIGHPRI		High priority to process semi-realtime timestamped data.
619 	//  * == WQ_SYSFS		Parameters are available via sysfs.
620 	//  * max_active == n_it + n_ir	A hardIRQ could notify events for multiple isochronous
621 	//				contexts if they are scheduled to the same cycle.
622 	isoc_wq = alloc_workqueue("firewire-isoc-card%u",
623 				  WQ_UNBOUND | WQ_FREEZABLE | WQ_HIGHPRI | WQ_SYSFS,
624 				  supported_isoc_contexts, card->index);
625 	if (!isoc_wq)
626 		return -ENOMEM;
627 
628 	// This workqueue should be:
629 	//  * != WQ_BH			Sleepable.
630 	//  * == WQ_UNBOUND		Any core can process data for asynchronous context.
631 	//  * == WQ_MEM_RECLAIM		Used for any backend of block device.
632 	//  * == WQ_FREEZABLE		The target device would not be available when being freezed.
633 	//  * == WQ_HIGHPRI		High priority to process semi-realtime timestamped data.
634 	//  * == WQ_SYSFS		Parameters are available via sysfs.
635 	//  * max_active == 4		A hardIRQ could notify events for a pair of requests and
636 	//				response AR/AT contexts.
637 	async_wq = alloc_workqueue("firewire-async-card%u",
638 				   WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_HIGHPRI | WQ_SYSFS,
639 				   4, card->index);
640 	if (!async_wq)
641 		return -ENOMEM;
642 
643 	card->isoc_wq = isoc_wq;
644 	card->async_wq = async_wq;
645 	card->max_receive = max_receive;
646 	card->link_speed = link_speed;
647 	card->guid = guid;
648 
649 	scoped_guard(mutex, &card_mutex) {
650 		generate_config_rom(card, tmp_config_rom);
651 		ret = card->driver->enable(card, tmp_config_rom, config_rom_length);
652 		if (ret < 0) {
653 			card->isoc_wq = NULL;
654 			card->async_wq = NULL;
655 			return ret;
656 		}
657 		retain_and_null_ptr(isoc_wq);
658 		retain_and_null_ptr(async_wq);
659 
660 		list_add_tail(&card->link, &card_list);
661 	}
662 
663 	return 0;
664 }
665 EXPORT_SYMBOL(fw_card_add);
666 
667 /*
668  * The next few functions implement a dummy driver that is used once a card
669  * driver shuts down an fw_card.  This allows the driver to cleanly unload,
670  * as all IO to the card will be handled (and failed) by the dummy driver
671  * instead of calling into the module.  Only functions for iso context
672  * shutdown still need to be provided by the card driver.
673  *
674  * .read/write_csr() should never be called anymore after the dummy driver
675  * was bound since they are only used within request handler context.
676  * .set_config_rom() is never called since the card is taken out of card_list
677  * before switching to the dummy driver.
678  */
679 
680 static int dummy_read_phy_reg(struct fw_card *card, int address)
681 {
682 	return -ENODEV;
683 }
684 
685 static int dummy_update_phy_reg(struct fw_card *card, int address,
686 				int clear_bits, int set_bits)
687 {
688 	return -ENODEV;
689 }
690 
691 static void dummy_send_request(struct fw_card *card, struct fw_packet *packet)
692 {
693 	packet->callback(packet, card, RCODE_CANCELLED);
694 }
695 
696 static void dummy_send_response(struct fw_card *card, struct fw_packet *packet)
697 {
698 	packet->callback(packet, card, RCODE_CANCELLED);
699 }
700 
701 static int dummy_cancel_packet(struct fw_card *card, struct fw_packet *packet)
702 {
703 	return -ENOENT;
704 }
705 
706 static int dummy_enable_phys_dma(struct fw_card *card,
707 				 int node_id, int generation)
708 {
709 	return -ENODEV;
710 }
711 
712 static struct fw_iso_context *dummy_allocate_iso_context(struct fw_card *card,
713 				int type, int channel, size_t header_size)
714 {
715 	return ERR_PTR(-ENODEV);
716 }
717 
718 static u32 dummy_read_csr(struct fw_card *card, int csr_offset)
719 {
720 	return 0;
721 }
722 
723 static void dummy_write_csr(struct fw_card *card, int csr_offset, u32 value)
724 {
725 }
726 
727 static int dummy_start_iso(struct fw_iso_context *ctx,
728 			   s32 cycle, u32 sync, u32 tags)
729 {
730 	return -ENODEV;
731 }
732 
733 static int dummy_set_iso_channels(struct fw_iso_context *ctx, u64 *channels)
734 {
735 	return -ENODEV;
736 }
737 
738 static int dummy_queue_iso(struct fw_iso_context *ctx, struct fw_iso_packet *p,
739 			   struct fw_iso_buffer *buffer, unsigned long payload)
740 {
741 	return -ENODEV;
742 }
743 
744 static void dummy_flush_queue_iso(struct fw_iso_context *ctx)
745 {
746 }
747 
748 static int dummy_flush_iso_completions(struct fw_iso_context *ctx)
749 {
750 	return -ENODEV;
751 }
752 
753 static const struct fw_card_driver dummy_driver_template = {
754 	.read_phy_reg		= dummy_read_phy_reg,
755 	.update_phy_reg		= dummy_update_phy_reg,
756 	.send_request		= dummy_send_request,
757 	.send_response		= dummy_send_response,
758 	.cancel_packet		= dummy_cancel_packet,
759 	.enable_phys_dma	= dummy_enable_phys_dma,
760 	.read_csr		= dummy_read_csr,
761 	.write_csr		= dummy_write_csr,
762 	.allocate_iso_context	= dummy_allocate_iso_context,
763 	.start_iso		= dummy_start_iso,
764 	.set_iso_channels	= dummy_set_iso_channels,
765 	.queue_iso		= dummy_queue_iso,
766 	.flush_queue_iso	= dummy_flush_queue_iso,
767 	.flush_iso_completions	= dummy_flush_iso_completions,
768 };
769 
770 void fw_card_release(struct kref *kref)
771 {
772 	struct fw_card *card = container_of(kref, struct fw_card, kref);
773 
774 	complete(&card->done);
775 }
776 EXPORT_SYMBOL_GPL(fw_card_release);
777 
778 void fw_core_remove_card(struct fw_card *card)
779 {
780 	struct fw_card_driver dummy_driver = dummy_driver_template;
781 
782 	might_sleep();
783 
784 	card->driver->update_phy_reg(card, 4,
785 				     PHY_LINK_ACTIVE | PHY_CONTENDER, 0);
786 	fw_schedule_bus_reset(card, false, true);
787 
788 	scoped_guard(mutex, &card_mutex)
789 		list_del_init(&card->link);
790 
791 	/* Switch off most of the card driver interface. */
792 	dummy_driver.free_iso_context	= card->driver->free_iso_context;
793 	dummy_driver.stop_iso		= card->driver->stop_iso;
794 	card->driver = &dummy_driver;
795 	drain_workqueue(card->isoc_wq);
796 	drain_workqueue(card->async_wq);
797 
798 	scoped_guard(spinlock_irqsave, &card->lock)
799 		fw_destroy_nodes(card);
800 
801 	/* Wait for all users, especially device workqueue jobs, to finish. */
802 	fw_card_put(card);
803 	wait_for_completion(&card->done);
804 
805 	destroy_workqueue(card->isoc_wq);
806 	destroy_workqueue(card->async_wq);
807 
808 	WARN_ON(!list_empty(&card->transactions.list));
809 }
810 EXPORT_SYMBOL(fw_core_remove_card);
811 
812 /**
813  * fw_card_read_cycle_time: read from Isochronous Cycle Timer Register of 1394 OHCI in MMIO region
814  *			    for controller card.
815  * @card: The instance of card for 1394 OHCI controller.
816  * @cycle_time: The mutual reference to value of cycle time for the read operation.
817  *
818  * Read value from Isochronous Cycle Timer Register of 1394 OHCI in MMIO region for the given
819  * controller card. This function accesses the region without any lock primitives or IRQ mask.
820  * When returning successfully, the content of @value argument has value aligned to host endianness,
821  * formetted by CYCLE_TIME CSR Register of IEEE 1394 std.
822  *
823  * Context: Any context.
824  * Return:
825  * * 0 - Read successfully.
826  * * -ENODEV - The controller is unavailable due to being removed or unbound.
827  */
828 int fw_card_read_cycle_time(struct fw_card *card, u32 *cycle_time)
829 {
830 	if (card->driver->read_csr == dummy_read_csr)
831 		return -ENODEV;
832 
833 	// It's possible to switch to dummy driver between the above and the below. This is the best
834 	// effort to return -ENODEV.
835 	*cycle_time = card->driver->read_csr(card, CSR_CYCLE_TIME);
836 	return 0;
837 }
838 EXPORT_SYMBOL_GPL(fw_card_read_cycle_time);
839