xref: /linux/drivers/firewire/core-device.c (revision 119b5984675cb43c2ecdf54195b418d3155eef94)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Device probing and sysfs code.
4  *
5  * Copyright (C) 2005-2006  Kristian Hoegsberg <krh@bitplanet.net>
6  */
7 
8 #include <linux/bug.h>
9 #include <linux/ctype.h>
10 #include <linux/delay.h>
11 #include <linux/device.h>
12 #include <linux/errno.h>
13 #include <linux/firewire.h>
14 #include <linux/firewire-constants.h>
15 #include <linux/jiffies.h>
16 #include <linux/kobject.h>
17 #include <linux/list.h>
18 #include <linux/module.h>
19 #include <linux/mutex.h>
20 #include <linux/random.h>
21 #include <linux/rwsem.h>
22 #include <linux/slab.h>
23 #include <linux/spinlock.h>
24 #include <linux/string.h>
25 #include <linux/workqueue.h>
26 
27 #include <linux/atomic.h>
28 #include <asm/byteorder.h>
29 
30 #include "core.h"
31 
32 #define ROOT_DIR_OFFSET	5
33 
34 void fw_csr_iterator_init(struct fw_csr_iterator *ci, const u32 *p)
35 {
36 	ci->p = p + 1;
37 	ci->end = ci->p + (p[0] >> 16);
38 }
39 EXPORT_SYMBOL(fw_csr_iterator_init);
40 
41 int fw_csr_iterator_next(struct fw_csr_iterator *ci, int *key, int *value)
42 {
43 	*key = *ci->p >> 24;
44 	*value = *ci->p & 0xffffff;
45 
46 	return ci->p++ < ci->end;
47 }
48 EXPORT_SYMBOL(fw_csr_iterator_next);
49 
50 static const u32 *search_directory(const u32 *directory, int search_key)
51 {
52 	struct fw_csr_iterator ci;
53 	int key, value;
54 
55 	search_key |= CSR_DIRECTORY;
56 
57 	fw_csr_iterator_init(&ci, directory);
58 	while (fw_csr_iterator_next(&ci, &key, &value)) {
59 		if (key == search_key)
60 			return ci.p - 1 + value;
61 	}
62 
63 	return NULL;
64 }
65 
66 static const u32 *search_leaf(const u32 *directory, int search_key)
67 {
68 	struct fw_csr_iterator ci;
69 	int last_key = 0, key, value;
70 
71 	fw_csr_iterator_init(&ci, directory);
72 	while (fw_csr_iterator_next(&ci, &key, &value)) {
73 		if (last_key == search_key &&
74 		    key == (CSR_DESCRIPTOR | CSR_LEAF))
75 			return ci.p - 1 + value;
76 
77 		last_key = key;
78 	}
79 
80 	return NULL;
81 }
82 
83 static int textual_leaf_to_string(const u32 *block, char *buf, size_t size)
84 {
85 	unsigned int quadlets, i;
86 	char c;
87 
88 	if (!size || !buf)
89 		return -EINVAL;
90 
91 	quadlets = min(block[0] >> 16, 256U);
92 	if (quadlets < 2)
93 		return -ENODATA;
94 
95 	if (block[1] != 0 || block[2] != 0)
96 		/* unknown language/character set */
97 		return -ENODATA;
98 
99 	block += 3;
100 	quadlets -= 2;
101 	for (i = 0; i < quadlets * 4 && i < size - 1; i++) {
102 		c = block[i / 4] >> (24 - 8 * (i % 4));
103 		if (c == '\0')
104 			break;
105 		buf[i] = c;
106 	}
107 	buf[i] = '\0';
108 
109 	return i;
110 }
111 
112 /**
113  * fw_csr_string() - reads a string from the configuration ROM
114  * @directory:	e.g. root directory or unit directory
115  * @key:	the key of the preceding directory entry
116  * @buf:	where to put the string
117  * @size:	size of @buf, in bytes
118  *
119  * The string is taken from a minimal ASCII text descriptor leaf just after the entry with the
120  * @key. The string is zero-terminated. An overlong string is silently truncated such that it
121  * and the zero byte fit into @size.
122  *
123  * Returns strlen(buf) or a negative error code.
124  */
125 int fw_csr_string(const u32 *directory, int key, char *buf, size_t size)
126 {
127 	const u32 *leaf = search_leaf(directory, key);
128 	if (!leaf)
129 		return -ENOENT;
130 
131 	return textual_leaf_to_string(leaf, buf, size);
132 }
133 EXPORT_SYMBOL(fw_csr_string);
134 
135 static void get_ids(const u32 *directory, int *id)
136 {
137 	struct fw_csr_iterator ci;
138 	int key, value;
139 
140 	fw_csr_iterator_init(&ci, directory);
141 	while (fw_csr_iterator_next(&ci, &key, &value)) {
142 		switch (key) {
143 		case CSR_VENDOR:	id[0] = value; break;
144 		case CSR_MODEL:		id[1] = value; break;
145 		case CSR_SPECIFIER_ID:	id[2] = value; break;
146 		case CSR_VERSION:	id[3] = value; break;
147 		}
148 	}
149 }
150 
151 static void get_modalias_ids(const struct fw_unit *unit, int *id)
152 {
153 	const u32 *root_directory = &fw_parent_device(unit)->config_rom[ROOT_DIR_OFFSET];
154 	const u32 *directories[] = {NULL, NULL, NULL};
155 	const u32 *vendor_directory;
156 	int i;
157 
158 	directories[0] = root_directory;
159 
160 	// Legacy layout of configuration ROM described in Annex 1 of 'Configuration ROM for AV/C
161 	// Devices 1.0 (December 12, 2000, 1394 Trading Association, TA Document 1999027)'.
162 	vendor_directory = search_directory(root_directory, CSR_VENDOR);
163 	if (!vendor_directory) {
164 		directories[1] = unit->directory;
165 	} else {
166 		directories[1] = vendor_directory;
167 		directories[2] = unit->directory;
168 	}
169 
170 	for (i = 0; i < ARRAY_SIZE(directories) && !!directories[i]; ++i)
171 		get_ids(directories[i], id);
172 }
173 
174 static bool match_ids(const struct ieee1394_device_id *id_table, int *id)
175 {
176 	int match = 0;
177 
178 	if (id[0] == id_table->vendor_id)
179 		match |= IEEE1394_MATCH_VENDOR_ID;
180 	if (id[1] == id_table->model_id)
181 		match |= IEEE1394_MATCH_MODEL_ID;
182 	if (id[2] == id_table->specifier_id)
183 		match |= IEEE1394_MATCH_SPECIFIER_ID;
184 	if (id[3] == id_table->version)
185 		match |= IEEE1394_MATCH_VERSION;
186 
187 	return (match & id_table->match_flags) == id_table->match_flags;
188 }
189 
190 static const struct ieee1394_device_id *unit_match(struct device *dev,
191 						   const struct device_driver *drv)
192 {
193 	const struct ieee1394_device_id *id_table =
194 			container_of_const(drv, struct fw_driver, driver)->id_table;
195 	int id[] = {0, 0, 0, 0};
196 
197 	get_modalias_ids(fw_unit(dev), id);
198 
199 	for (; id_table->match_flags != 0; id_table++)
200 		if (match_ids(id_table, id))
201 			return id_table;
202 
203 	return NULL;
204 }
205 
206 static bool is_fw_unit(const struct device *dev);
207 
208 static int fw_unit_match(struct device *dev, const struct device_driver *drv)
209 {
210 	/* We only allow binding to fw_units. */
211 	return is_fw_unit(dev) && unit_match(dev, drv) != NULL;
212 }
213 
214 static int fw_unit_probe(struct device *dev)
215 {
216 	struct fw_driver *driver =
217 			container_of(dev->driver, struct fw_driver, driver);
218 
219 	return driver->probe(fw_unit(dev), unit_match(dev, dev->driver));
220 }
221 
222 static void fw_unit_remove(struct device *dev)
223 {
224 	struct fw_driver *driver =
225 			container_of(dev->driver, struct fw_driver, driver);
226 
227 	driver->remove(fw_unit(dev));
228 }
229 
230 static int get_modalias(const struct fw_unit *unit, char *buffer, size_t buffer_size)
231 {
232 	int id[] = {0, 0, 0, 0};
233 
234 	get_modalias_ids(unit, id);
235 
236 	return snprintf(buffer, buffer_size,
237 			"ieee1394:ven%08Xmo%08Xsp%08Xver%08X",
238 			id[0], id[1], id[2], id[3]);
239 }
240 
241 static int fw_unit_uevent(const struct device *dev, struct kobj_uevent_env *env)
242 {
243 	const struct fw_unit *unit = fw_unit(dev);
244 	char modalias[64];
245 
246 	get_modalias(unit, modalias, sizeof(modalias));
247 
248 	if (add_uevent_var(env, "MODALIAS=%s", modalias))
249 		return -ENOMEM;
250 
251 	return 0;
252 }
253 
254 const struct bus_type fw_bus_type = {
255 	.name = "firewire",
256 	.match = fw_unit_match,
257 	.probe = fw_unit_probe,
258 	.remove = fw_unit_remove,
259 };
260 EXPORT_SYMBOL(fw_bus_type);
261 
262 int fw_device_enable_phys_dma(struct fw_device *device)
263 {
264 	int generation = device->generation;
265 
266 	/* device->node_id, accessed below, must not be older than generation */
267 	smp_rmb();
268 
269 	return device->card->driver->enable_phys_dma(device->card,
270 						     device->node_id,
271 						     generation);
272 }
273 EXPORT_SYMBOL(fw_device_enable_phys_dma);
274 
275 struct config_rom_attribute {
276 	struct device_attribute attr;
277 	u32 key;
278 };
279 
280 static ssize_t show_immediate(struct device *dev,
281 			      struct device_attribute *dattr, char *buf)
282 {
283 	struct config_rom_attribute *attr =
284 		container_of(dattr, struct config_rom_attribute, attr);
285 	struct fw_csr_iterator ci;
286 	const u32 *directories[] = {NULL, NULL};
287 	int i, value = -1;
288 
289 	guard(rwsem_read)(&fw_device_rwsem);
290 
291 	if (is_fw_unit(dev)) {
292 		directories[0] = fw_unit(dev)->directory;
293 	} else {
294 		const u32 *root_directory = fw_device(dev)->config_rom + ROOT_DIR_OFFSET;
295 		const u32 *vendor_directory = search_directory(root_directory, CSR_VENDOR);
296 
297 		if (!vendor_directory) {
298 			directories[0] = root_directory;
299 		} else {
300 			// Legacy layout of configuration ROM described in Annex 1 of
301 			// 'Configuration ROM for AV/C Devices 1.0 (December 12, 2000, 1394 Trading
302 			// Association, TA Document 1999027)'.
303 			directories[0] = vendor_directory;
304 			directories[1] = root_directory;
305 		}
306 	}
307 
308 	for (i = 0; i < ARRAY_SIZE(directories) && !!directories[i]; ++i) {
309 		int key, val;
310 
311 		fw_csr_iterator_init(&ci, directories[i]);
312 		while (fw_csr_iterator_next(&ci, &key, &val)) {
313 			if (attr->key == key)
314 				value = val;
315 		}
316 	}
317 
318 	if (value < 0)
319 		return -ENOENT;
320 
321 	// Note that this function is also called by init_fw_attribute_group() with NULL pointer.
322 	return buf ? sysfs_emit(buf, "0x%06x\n", value) : 0;
323 }
324 
325 #define IMMEDIATE_ATTR(name, key)				\
326 	{ __ATTR(name, S_IRUGO, show_immediate, NULL), key }
327 
328 static ssize_t show_text_leaf(struct device *dev,
329 			      struct device_attribute *dattr, char *buf)
330 {
331 	struct config_rom_attribute *attr =
332 		container_of(dattr, struct config_rom_attribute, attr);
333 	const u32 *directories[] = {NULL, NULL};
334 	size_t bufsize;
335 	char dummy_buf[2];
336 	int i, ret = -ENOENT;
337 
338 	guard(rwsem_read)(&fw_device_rwsem);
339 
340 	if (is_fw_unit(dev)) {
341 		directories[0] = fw_unit(dev)->directory;
342 	} else {
343 		const u32 *root_directory = fw_device(dev)->config_rom + ROOT_DIR_OFFSET;
344 		const u32 *vendor_directory = search_directory(root_directory, CSR_VENDOR);
345 
346 		if (!vendor_directory) {
347 			directories[0] = root_directory;
348 		} else {
349 			// Legacy layout of configuration ROM described in Annex 1 of
350 			// 'Configuration ROM for AV/C Devices 1.0 (December 12, 2000, 1394
351 			// Trading Association, TA Document 1999027)'.
352 			directories[0] = root_directory;
353 			directories[1] = vendor_directory;
354 		}
355 	}
356 
357 	// Note that this function is also called by init_fw_attribute_group() with NULL pointer.
358 	if (buf) {
359 		bufsize = PAGE_SIZE - 1;
360 	} else {
361 		buf = dummy_buf;
362 		bufsize = 1;
363 	}
364 
365 	for (i = 0; i < ARRAY_SIZE(directories) && !!directories[i]; ++i) {
366 		int result = fw_csr_string(directories[i], attr->key, buf, bufsize);
367 		// Detected.
368 		if (result >= 0) {
369 			ret = result;
370 		} else if (i == 0 && attr->key == CSR_VENDOR) {
371 			// Sony DVMC-DA1 has configuration ROM such that the descriptor leaf entry
372 			// in the root directory follows to the directory entry for vendor ID
373 			// instead of the immediate value for vendor ID.
374 			result = fw_csr_string(directories[i], CSR_DIRECTORY | attr->key, buf,
375 					       bufsize);
376 			if (result >= 0)
377 				ret = result;
378 		}
379 	}
380 
381 	if (ret < 0)
382 		return ret;
383 
384 	// Strip trailing whitespace and add newline.
385 	while (ret > 0 && isspace(buf[ret - 1]))
386 		ret--;
387 	strcpy(buf + ret, "\n");
388 	ret++;
389 
390 	return ret;
391 }
392 
393 #define TEXT_LEAF_ATTR(name, key)				\
394 	{ __ATTR(name, S_IRUGO, show_text_leaf, NULL), key }
395 
396 static struct config_rom_attribute config_rom_attributes[] = {
397 	IMMEDIATE_ATTR(vendor, CSR_VENDOR),
398 	IMMEDIATE_ATTR(hardware_version, CSR_HARDWARE_VERSION),
399 	IMMEDIATE_ATTR(specifier_id, CSR_SPECIFIER_ID),
400 	IMMEDIATE_ATTR(version, CSR_VERSION),
401 	IMMEDIATE_ATTR(model, CSR_MODEL),
402 	TEXT_LEAF_ATTR(vendor_name, CSR_VENDOR),
403 	TEXT_LEAF_ATTR(model_name, CSR_MODEL),
404 	TEXT_LEAF_ATTR(hardware_version_name, CSR_HARDWARE_VERSION),
405 };
406 
407 static void init_fw_attribute_group(struct device *dev,
408 				    struct device_attribute *attrs,
409 				    struct fw_attribute_group *group)
410 {
411 	struct device_attribute *attr;
412 	int i, j;
413 
414 	for (j = 0; attrs[j].attr.name != NULL; j++)
415 		group->attrs[j] = &attrs[j].attr;
416 
417 	for (i = 0; i < ARRAY_SIZE(config_rom_attributes); i++) {
418 		attr = &config_rom_attributes[i].attr;
419 		if (attr->show(dev, attr, NULL) < 0)
420 			continue;
421 		group->attrs[j++] = &attr->attr;
422 	}
423 
424 	group->attrs[j] = NULL;
425 	group->groups[0] = &group->group;
426 	group->groups[1] = NULL;
427 	group->group.attrs = group->attrs;
428 	dev->groups = (const struct attribute_group **) group->groups;
429 }
430 
431 static ssize_t modalias_show(struct device *dev,
432 			     struct device_attribute *attr, char *buf)
433 {
434 	struct fw_unit *unit = fw_unit(dev);
435 	int length;
436 
437 	length = get_modalias(unit, buf, PAGE_SIZE);
438 	strcpy(buf + length, "\n");
439 
440 	return length + 1;
441 }
442 
443 static ssize_t rom_index_show(struct device *dev,
444 			      struct device_attribute *attr, char *buf)
445 {
446 	struct fw_device *device = fw_device(dev->parent);
447 	struct fw_unit *unit = fw_unit(dev);
448 
449 	return sysfs_emit(buf, "%td\n", unit->directory - device->config_rom);
450 }
451 
452 static struct device_attribute fw_unit_attributes[] = {
453 	__ATTR_RO(modalias),
454 	__ATTR_RO(rom_index),
455 	__ATTR_NULL,
456 };
457 
458 static ssize_t config_rom_show(struct device *dev,
459 			       struct device_attribute *attr, char *buf)
460 {
461 	struct fw_device *device = fw_device(dev);
462 	size_t length;
463 
464 	guard(rwsem_read)(&fw_device_rwsem);
465 
466 	length = device->config_rom_length * 4;
467 	memcpy(buf, device->config_rom, length);
468 
469 	return length;
470 }
471 
472 static ssize_t guid_show(struct device *dev,
473 			 struct device_attribute *attr, char *buf)
474 {
475 	struct fw_device *device = fw_device(dev);
476 
477 	guard(rwsem_read)(&fw_device_rwsem);
478 
479 	return sysfs_emit(buf, "0x%08x%08x\n", device->config_rom[3], device->config_rom[4]);
480 }
481 
482 static ssize_t is_local_show(struct device *dev,
483 			     struct device_attribute *attr, char *buf)
484 {
485 	struct fw_device *device = fw_device(dev);
486 
487 	return sysfs_emit(buf, "%u\n", device->is_local);
488 }
489 
490 static int units_sprintf(char *buf, const u32 *directory)
491 {
492 	struct fw_csr_iterator ci;
493 	int key, value;
494 	int specifier_id = 0;
495 	int version = 0;
496 
497 	fw_csr_iterator_init(&ci, directory);
498 	while (fw_csr_iterator_next(&ci, &key, &value)) {
499 		switch (key) {
500 		case CSR_SPECIFIER_ID:
501 			specifier_id = value;
502 			break;
503 		case CSR_VERSION:
504 			version = value;
505 			break;
506 		}
507 	}
508 
509 	return sprintf(buf, "0x%06x:0x%06x ", specifier_id, version);
510 }
511 
512 static ssize_t units_show(struct device *dev,
513 			  struct device_attribute *attr, char *buf)
514 {
515 	struct fw_device *device = fw_device(dev);
516 	struct fw_csr_iterator ci;
517 	int key, value, i = 0;
518 
519 	guard(rwsem_read)(&fw_device_rwsem);
520 
521 	fw_csr_iterator_init(&ci, &device->config_rom[ROOT_DIR_OFFSET]);
522 	while (fw_csr_iterator_next(&ci, &key, &value)) {
523 		if (key != (CSR_UNIT | CSR_DIRECTORY))
524 			continue;
525 		i += units_sprintf(&buf[i], ci.p + value - 1);
526 		if (i >= PAGE_SIZE - (8 + 1 + 8 + 1))
527 			break;
528 	}
529 
530 	if (i)
531 		buf[i - 1] = '\n';
532 
533 	return i;
534 }
535 
536 static struct device_attribute fw_device_attributes[] = {
537 	__ATTR_RO(config_rom),
538 	__ATTR_RO(guid),
539 	__ATTR_RO(is_local),
540 	__ATTR_RO(units),
541 	__ATTR_NULL,
542 };
543 
544 #define CANON_OUI		0x000085
545 
546 static int detect_quirks_by_bus_information_block(const u32 *bus_information_block)
547 {
548 	int quirks = 0;
549 
550 	if ((bus_information_block[2] & 0x000000f0) == 0)
551 		quirks |= FW_DEVICE_QUIRK_IRM_IS_1394_1995_ONLY;
552 
553 	if ((bus_information_block[3] >> 8) == CANON_OUI)
554 		quirks |= FW_DEVICE_QUIRK_IRM_IGNORES_BUS_MANAGER;
555 
556 	return quirks;
557 }
558 
559 struct entry_match {
560 	unsigned int index;
561 	u32 value;
562 };
563 
564 static const struct entry_match motu_audio_express_matches[] = {
565 	{ 1, 0x030001f2 },
566 	{ 3, 0xd1000002 },
567 	{ 4, 0x8d000005 },
568 	{ 6, 0x120001f2 },
569 	{ 7, 0x13000033 },
570 	{ 8, 0x17104800 },
571 };
572 
573 static const struct entry_match tascam_fw_series_matches[] = {
574 	{ 1, 0x0300022e },
575 	{ 3, 0x8d000006 },
576 	{ 4, 0xd1000001 },
577 	{ 6, 0x1200022e },
578 	{ 8, 0xd4000004 },
579 };
580 
581 static int detect_quirks_by_root_directory(const u32 *root_directory, unsigned int length)
582 {
583 	static const struct {
584 		enum fw_device_quirk quirk;
585 		const struct entry_match *matches;
586 		unsigned int match_count;
587 	} *entry, entries[] = {
588 		{
589 			.quirk = FW_DEVICE_QUIRK_ACK_PACKET_WITH_INVALID_PENDING_CODE,
590 			.matches = motu_audio_express_matches,
591 			.match_count = ARRAY_SIZE(motu_audio_express_matches),
592 		},
593 		{
594 			.quirk = FW_DEVICE_QUIRK_UNSTABLE_AT_S400,
595 			.matches = tascam_fw_series_matches,
596 			.match_count = ARRAY_SIZE(tascam_fw_series_matches),
597 		},
598 	};
599 	int quirks = 0;
600 	int i;
601 
602 	for (i = 0; i < ARRAY_SIZE(entries); ++i) {
603 		int j;
604 
605 		entry = entries + i;
606 		for (j = 0; j < entry->match_count; ++j) {
607 			unsigned int index = entry->matches[j].index;
608 			unsigned int value = entry->matches[j].value;
609 
610 			if ((length < index) || (root_directory[index] != value))
611 				break;
612 		}
613 		if (j == entry->match_count)
614 			quirks |= entry->quirk;
615 	}
616 
617 	return quirks;
618 }
619 
620 static int read_rom(struct fw_device *device, int generation, int speed, int index, u32 *data)
621 {
622 	u64 offset = (CSR_REGISTER_BASE | CSR_CONFIG_ROM) + index * 4;
623 	int i, rcode;
624 
625 	/* device->node_id, accessed below, must not be older than generation */
626 	smp_rmb();
627 
628 	for (i = 10; i < 100; i += 10) {
629 		rcode = fw_run_transaction(device->card,
630 				TCODE_READ_QUADLET_REQUEST, device->node_id,
631 				generation, speed, offset, data, 4);
632 		if (rcode != RCODE_BUSY)
633 			break;
634 		msleep(i);
635 	}
636 	be32_to_cpus(data);
637 
638 	return rcode;
639 }
640 
641 // By quadlet unit.
642 #define MAX_CONFIG_ROM_SIZE	((CSR_CONFIG_ROM_END - CSR_CONFIG_ROM) / sizeof(u32))
643 
644 /*
645  * Read the bus info block, perform a speed probe, and read all of the rest of
646  * the config ROM.  We do all this with a cached bus generation.  If the bus
647  * generation changes under us, read_config_rom will fail and get retried.
648  * It's better to start all over in this case because the node from which we
649  * are reading the ROM may have changed the ROM during the reset.
650  * Returns either a result code or a negative error code.
651  */
652 static int read_config_rom(struct fw_device *device, int generation)
653 {
654 	struct fw_card *card = device->card;
655 	const u32 *new_rom, *old_rom __free(kfree) = NULL;
656 	u32 *stack, *rom __free(kfree) = NULL;
657 	u32 sp, key;
658 	int i, end, length, ret, speed;
659 	int quirks;
660 
661 	rom = kmalloc(sizeof(*rom) * MAX_CONFIG_ROM_SIZE +
662 		      sizeof(*stack) * MAX_CONFIG_ROM_SIZE, GFP_KERNEL);
663 	if (rom == NULL)
664 		return -ENOMEM;
665 
666 	stack = &rom[MAX_CONFIG_ROM_SIZE];
667 	memset(rom, 0, sizeof(*rom) * MAX_CONFIG_ROM_SIZE);
668 
669 	speed = SCODE_100;
670 
671 	/* First read the bus info block. */
672 	for (i = 0; i < 5; i++) {
673 		ret = read_rom(device, generation, speed, i, &rom[i]);
674 		if (ret != RCODE_COMPLETE)
675 			return ret;
676 		/*
677 		 * As per IEEE1212 7.2, during initialization, devices can
678 		 * reply with a 0 for the first quadlet of the config
679 		 * rom to indicate that they are booting (for example,
680 		 * if the firmware is on the disk of a external
681 		 * harddisk).  In that case we just fail, and the
682 		 * retry mechanism will try again later.
683 		 */
684 		if (i == 0 && rom[i] == 0)
685 			return RCODE_BUSY;
686 	}
687 
688 	quirks = detect_quirks_by_bus_information_block(rom);
689 
690 	// Just prevent from torn writing/reading.
691 	WRITE_ONCE(device->quirks, quirks);
692 
693 	/*
694 	 * Now parse the config rom.  The config rom is a recursive
695 	 * directory structure so we parse it using a stack of
696 	 * references to the blocks that make up the structure.  We
697 	 * push a reference to the root directory on the stack to
698 	 * start things off.
699 	 */
700 	length = i;
701 	sp = 0;
702 	stack[sp++] = 0xc0000005;
703 	while (sp > 0) {
704 		/*
705 		 * Pop the next block reference of the stack.  The
706 		 * lower 24 bits is the offset into the config rom,
707 		 * the upper 8 bits are the type of the reference the
708 		 * block.
709 		 */
710 		key = stack[--sp];
711 		i = key & 0xffffff;
712 		if (WARN_ON(i >= MAX_CONFIG_ROM_SIZE))
713 			return -ENXIO;
714 
715 		/* Read header quadlet for the block to get the length. */
716 		ret = read_rom(device, generation, speed, i, &rom[i]);
717 		if (ret != RCODE_COMPLETE)
718 			return ret;
719 		end = i + (rom[i] >> 16) + 1;
720 		if (end > MAX_CONFIG_ROM_SIZE) {
721 			/*
722 			 * This block extends outside the config ROM which is
723 			 * a firmware bug.  Ignore this whole block, i.e.
724 			 * simply set a fake block length of 0.
725 			 */
726 			fw_err(card, "skipped invalid ROM block %x at %llx\n",
727 			       rom[i],
728 			       i * 4 | CSR_REGISTER_BASE | CSR_CONFIG_ROM);
729 			rom[i] = 0;
730 			end = i;
731 		}
732 		i++;
733 
734 		/*
735 		 * Now read in the block.  If this is a directory
736 		 * block, check the entries as we read them to see if
737 		 * it references another block, and push it in that case.
738 		 */
739 		for (; i < end; i++) {
740 			ret = read_rom(device, generation, speed, i, &rom[i]);
741 			if (ret != RCODE_COMPLETE)
742 				return ret;
743 
744 			if ((key >> 30) != 3 || (rom[i] >> 30) < 2)
745 				continue;
746 			/*
747 			 * Offset points outside the ROM.  May be a firmware
748 			 * bug or an Extended ROM entry (IEEE 1212-2001 clause
749 			 * 7.7.18).  Simply overwrite this pointer here by a
750 			 * fake immediate entry so that later iterators over
751 			 * the ROM don't have to check offsets all the time.
752 			 */
753 			if (i + (rom[i] & 0xffffff) >= MAX_CONFIG_ROM_SIZE) {
754 				fw_err(card,
755 				       "skipped unsupported ROM entry %x at %llx\n",
756 				       rom[i],
757 				       i * 4 | CSR_REGISTER_BASE | CSR_CONFIG_ROM);
758 				rom[i] = 0;
759 				continue;
760 			}
761 			stack[sp++] = i + rom[i];
762 		}
763 		if (length < i)
764 			length = i;
765 	}
766 
767 	quirks |= detect_quirks_by_root_directory(rom + ROOT_DIR_OFFSET, length - ROOT_DIR_OFFSET);
768 
769 	// Just prevent from torn writing/reading.
770 	WRITE_ONCE(device->quirks, quirks);
771 
772 	if (unlikely(quirks & FW_DEVICE_QUIRK_UNSTABLE_AT_S400))
773 		speed = SCODE_200;
774 	else
775 		speed = device->node->max_speed;
776 
777 	// Determine the speed of
778 	//   - devices with link speed less than PHY speed,
779 	//   - devices with 1394b PHY (unless only connected to 1394a PHYs),
780 	//   - all devices if there are 1394b repeaters.
781 	// Note, we cannot use the bus info block's link_spd as starting point because some buggy
782 	// firmwares set it lower than necessary and because 1394-1995 nodes do not have the field.
783 	if ((rom[2] & 0x7) < speed || speed == SCODE_BETA || card->beta_repeaters_present) {
784 		u32 dummy;
785 
786 		// for S1600 and S3200.
787 		if (speed == SCODE_BETA)
788 			speed = card->link_speed;
789 
790 		while (speed > SCODE_100) {
791 			if (read_rom(device, generation, speed, 0, &dummy) ==
792 			    RCODE_COMPLETE)
793 				break;
794 			--speed;
795 		}
796 	}
797 
798 	device->max_speed = speed;
799 
800 	old_rom = device->config_rom;
801 	new_rom = kmemdup(rom, length * 4, GFP_KERNEL);
802 	if (new_rom == NULL)
803 		return -ENOMEM;
804 
805 	scoped_guard(rwsem_write, &fw_device_rwsem) {
806 		device->config_rom = new_rom;
807 		device->config_rom_length = length;
808 	}
809 
810 	device->max_rec	= rom[2] >> 12 & 0xf;
811 	device->cmc	= rom[2] >> 30 & 1;
812 	device->irmc	= rom[2] >> 31 & 1;
813 
814 	return RCODE_COMPLETE;
815 }
816 
817 static void fw_unit_release(struct device *dev)
818 {
819 	struct fw_unit *unit = fw_unit(dev);
820 
821 	fw_device_put(fw_parent_device(unit));
822 	kfree(unit);
823 }
824 
825 static struct device_type fw_unit_type = {
826 	.uevent		= fw_unit_uevent,
827 	.release	= fw_unit_release,
828 };
829 
830 static bool is_fw_unit(const struct device *dev)
831 {
832 	return dev->type == &fw_unit_type;
833 }
834 
835 static void create_units(struct fw_device *device)
836 {
837 	struct fw_csr_iterator ci;
838 	struct fw_unit *unit;
839 	int key, value, i;
840 
841 	i = 0;
842 	fw_csr_iterator_init(&ci, &device->config_rom[ROOT_DIR_OFFSET]);
843 	while (fw_csr_iterator_next(&ci, &key, &value)) {
844 		if (key != (CSR_UNIT | CSR_DIRECTORY))
845 			continue;
846 
847 		/*
848 		 * Get the address of the unit directory and try to
849 		 * match the drivers id_tables against it.
850 		 */
851 		unit = kzalloc_obj(*unit);
852 		if (unit == NULL)
853 			continue;
854 
855 		unit->directory = ci.p + value - 1;
856 		unit->device.bus = &fw_bus_type;
857 		unit->device.type = &fw_unit_type;
858 		unit->device.parent = &device->device;
859 		dev_set_name(&unit->device, "%s.%d", dev_name(&device->device), i++);
860 
861 		BUILD_BUG_ON(ARRAY_SIZE(unit->attribute_group.attrs) <
862 				ARRAY_SIZE(fw_unit_attributes) +
863 				ARRAY_SIZE(config_rom_attributes));
864 		init_fw_attribute_group(&unit->device,
865 					fw_unit_attributes,
866 					&unit->attribute_group);
867 
868 		fw_device_get(device);
869 		if (device_register(&unit->device) < 0) {
870 			put_device(&unit->device);
871 			continue;
872 		}
873 	}
874 }
875 
876 static int shutdown_unit(struct device *device, void *data)
877 {
878 	device_unregister(device);
879 
880 	return 0;
881 }
882 
883 /*
884  * fw_device_rwsem acts as dual purpose mutex:
885  *   - serializes accesses to fw_device.config_rom/.config_rom_length and
886  *     fw_unit.directory, unless those accesses happen at safe occasions
887  */
888 DECLARE_RWSEM(fw_device_rwsem);
889 
890 DEFINE_XARRAY_ALLOC(fw_device_xa);
891 int fw_cdev_major;
892 
893 struct fw_device *fw_device_get_by_devt(dev_t devt)
894 {
895 	struct fw_device *device;
896 
897 	device = xa_load(&fw_device_xa, MINOR(devt));
898 	if (device)
899 		fw_device_get(device);
900 
901 	return device;
902 }
903 
904 struct workqueue_struct *fw_workqueue;
905 EXPORT_SYMBOL(fw_workqueue);
906 
907 static void fw_schedule_device_work(struct fw_device *device,
908 				    unsigned long delay)
909 {
910 	queue_delayed_work(fw_workqueue, &device->work, delay);
911 }
912 
913 /*
914  * These defines control the retry behavior for reading the config
915  * rom.  It shouldn't be necessary to tweak these; if the device
916  * doesn't respond to a config rom read within 10 seconds, it's not
917  * going to respond at all.  As for the initial delay, a lot of
918  * devices will be able to respond within half a second after bus
919  * reset.  On the other hand, it's not really worth being more
920  * aggressive than that, since it scales pretty well; if 10 devices
921  * are plugged in, they're all getting read within one second.
922  */
923 
924 #define MAX_RETRIES	10
925 #define RETRY_DELAY	secs_to_jiffies(3)
926 #define INITIAL_DELAY	msecs_to_jiffies(500)
927 #define SHUTDOWN_DELAY	secs_to_jiffies(2)
928 
929 static void fw_device_shutdown(struct work_struct *work)
930 {
931 	struct fw_device *device = from_work(device, work, work.work);
932 
933 	if (time_is_after_jiffies64(device->card->reset_jiffies + SHUTDOWN_DELAY)
934 	    && !list_empty(&device->card->link)) {
935 		fw_schedule_device_work(device, SHUTDOWN_DELAY);
936 		return;
937 	}
938 
939 	if (atomic_cmpxchg(&device->state,
940 			   FW_DEVICE_GONE,
941 			   FW_DEVICE_SHUTDOWN) != FW_DEVICE_GONE)
942 		return;
943 
944 	fw_device_cdev_remove(device);
945 	device_for_each_child(&device->device, NULL, shutdown_unit);
946 	device_unregister(&device->device);
947 
948 	xa_erase(&fw_device_xa, MINOR(device->device.devt));
949 
950 	fw_device_put(device);
951 }
952 
953 static void fw_device_release(struct device *dev)
954 {
955 	struct fw_device *device = fw_device(dev);
956 	struct fw_card *card = device->card;
957 
958 	/*
959 	 * Take the card lock so we don't set this to NULL while a
960 	 * FW_NODE_UPDATED callback is being handled or while the
961 	 * bus manager work looks at this node.
962 	 */
963 	scoped_guard(spinlock_irqsave, &card->lock)
964 		fw_node_set_device(device->node, NULL);
965 
966 	fw_node_put(device->node);
967 	kfree(device->config_rom);
968 	kfree(device);
969 	fw_card_put(card);
970 }
971 
972 static struct device_type fw_device_type = {
973 	.release = fw_device_release,
974 };
975 
976 static bool is_fw_device(const struct device *dev)
977 {
978 	return dev->type == &fw_device_type;
979 }
980 
981 static int update_unit(struct device *dev, void *data)
982 {
983 	struct fw_unit *unit = fw_unit(dev);
984 	struct fw_driver *driver = (struct fw_driver *)dev->driver;
985 
986 	if (is_fw_unit(dev) && driver != NULL && driver->update != NULL) {
987 		device_lock(dev);
988 		driver->update(unit);
989 		device_unlock(dev);
990 	}
991 
992 	return 0;
993 }
994 
995 static void fw_device_update(struct work_struct *work)
996 {
997 	struct fw_device *device = from_work(device, work, work.work);
998 
999 	fw_device_cdev_update(device);
1000 	device_for_each_child(&device->device, NULL, update_unit);
1001 }
1002 
1003 enum { BC_UNKNOWN = 0, BC_UNIMPLEMENTED, BC_IMPLEMENTED, };
1004 
1005 static void set_broadcast_channel(struct fw_device *device, int generation)
1006 {
1007 	struct fw_card *card = device->card;
1008 	__be32 data;
1009 	int rcode;
1010 
1011 	if (!card->broadcast_channel_allocated)
1012 		return;
1013 
1014 	/*
1015 	 * The Broadcast_Channel Valid bit is required by nodes which want to
1016 	 * transmit on this channel.  Such transmissions are practically
1017 	 * exclusive to IP over 1394 (RFC 2734).  IP capable nodes are required
1018 	 * to be IRM capable and have a max_rec of 8 or more.  We use this fact
1019 	 * to narrow down to which nodes we send Broadcast_Channel updates.
1020 	 */
1021 	if (!device->irmc || device->max_rec < 8)
1022 		return;
1023 
1024 	/*
1025 	 * Some 1394-1995 nodes crash if this 1394a-2000 register is written.
1026 	 * Perform a read test first.
1027 	 */
1028 	if (device->bc_implemented == BC_UNKNOWN) {
1029 		rcode = fw_run_transaction(card, TCODE_READ_QUADLET_REQUEST,
1030 				device->node_id, generation, device->max_speed,
1031 				CSR_REGISTER_BASE + CSR_BROADCAST_CHANNEL,
1032 				&data, 4);
1033 		switch (rcode) {
1034 		case RCODE_COMPLETE:
1035 			if (data & cpu_to_be32(1 << 31)) {
1036 				device->bc_implemented = BC_IMPLEMENTED;
1037 				break;
1038 			}
1039 			fallthrough;	/* to case address error */
1040 		case RCODE_ADDRESS_ERROR:
1041 			device->bc_implemented = BC_UNIMPLEMENTED;
1042 		}
1043 	}
1044 
1045 	if (device->bc_implemented == BC_IMPLEMENTED) {
1046 		data = cpu_to_be32(BROADCAST_CHANNEL_INITIAL |
1047 				   BROADCAST_CHANNEL_VALID);
1048 		fw_run_transaction(card, TCODE_WRITE_QUADLET_REQUEST,
1049 				device->node_id, generation, device->max_speed,
1050 				CSR_REGISTER_BASE + CSR_BROADCAST_CHANNEL,
1051 				&data, 4);
1052 	}
1053 }
1054 
1055 int fw_device_set_broadcast_channel(struct device *dev, void *gen)
1056 {
1057 	if (is_fw_device(dev))
1058 		set_broadcast_channel(fw_device(dev), (long)gen);
1059 
1060 	return 0;
1061 }
1062 
1063 static int compare_configuration_rom(struct device *dev, const void *data)
1064 {
1065 	const struct fw_device *old = fw_device(dev);
1066 	const u32 *config_rom = data;
1067 
1068 	if (!is_fw_device(dev))
1069 		return 0;
1070 
1071 	// Compare the bus information block and root_length/root_crc.
1072 	return !memcmp(old->config_rom, config_rom, 6 * 4);
1073 }
1074 
1075 static void fw_device_init(struct work_struct *work)
1076 {
1077 	struct fw_device *device = from_work(device, work, work.work);
1078 	struct fw_card *card = device->card;
1079 	struct device *found;
1080 	u32 minor;
1081 	int ret;
1082 
1083 	/*
1084 	 * All failure paths here call fw_node_set_device(node, NULL), so that we
1085 	 * don't try to do device_for_each_child() on a kfree()'d
1086 	 * device.
1087 	 */
1088 
1089 	ret = read_config_rom(device, device->generation);
1090 	if (ret != RCODE_COMPLETE) {
1091 		if (device->config_rom_retries < MAX_RETRIES &&
1092 		    atomic_read(&device->state) == FW_DEVICE_INITIALIZING) {
1093 			device->config_rom_retries++;
1094 			fw_schedule_device_work(device, RETRY_DELAY);
1095 		} else {
1096 			if (device->node->link_on)
1097 				fw_notice(card, "giving up on node %x: reading config rom failed: %s\n",
1098 					  device->node_id,
1099 					  fw_rcode_string(ret));
1100 			if (device->node == card->root_node)
1101 				fw_schedule_bm_work(card, 0);
1102 			fw_device_release(&device->device);
1103 		}
1104 		return;
1105 	}
1106 
1107 	// If a device was pending for deletion because its node went away but its bus info block
1108 	// and root directory header matches that of a newly discovered device, revive the
1109 	// existing fw_device. The newly allocated fw_device becomes obsolete instead.
1110 	//
1111 	// serialize config_rom access.
1112 	scoped_guard(rwsem_read, &fw_device_rwsem) {
1113 		found = device_find_child(card->device, device->config_rom,
1114 					  compare_configuration_rom);
1115 	}
1116 	if (found) {
1117 		struct fw_device *reused = fw_device(found);
1118 
1119 		if (atomic_cmpxchg(&reused->state,
1120 				   FW_DEVICE_GONE,
1121 				   FW_DEVICE_RUNNING) == FW_DEVICE_GONE) {
1122 			// serialize node access
1123 			scoped_guard(spinlock_irq, &card->lock) {
1124 				struct fw_node *current_node = device->node;
1125 				struct fw_node *obsolete_node = reused->node;
1126 
1127 				device->node = obsolete_node;
1128 				fw_node_set_device(device->node, device);
1129 				reused->node = current_node;
1130 				fw_node_set_device(reused->node, reused);
1131 
1132 				reused->max_speed = device->max_speed;
1133 				reused->node_id = current_node->node_id;
1134 				smp_wmb();  /* update node_id before generation */
1135 				reused->generation = card->generation;
1136 				reused->config_rom_retries = 0;
1137 				fw_notice(card, "rediscovered device %s\n",
1138 					  dev_name(found));
1139 
1140 				reused->workfn = fw_device_update;
1141 				fw_schedule_device_work(reused, 0);
1142 
1143 				if (current_node == card->root_node)
1144 					fw_schedule_bm_work(card, 0);
1145 			}
1146 
1147 			put_device(found);
1148 			fw_device_release(&device->device);
1149 
1150 			return;
1151 		}
1152 
1153 		put_device(found);
1154 	}
1155 
1156 	device_initialize(&device->device);
1157 
1158 	fw_device_get(device);
1159 
1160 	// The index of allocated entry is used for minor identifier of device node.
1161 	ret = xa_alloc(&fw_device_xa, &minor, device, XA_LIMIT(0, MINORMASK), GFP_KERNEL);
1162 	if (ret < 0)
1163 		goto error;
1164 
1165 	device->device.bus = &fw_bus_type;
1166 	device->device.type = &fw_device_type;
1167 	device->device.parent = card->device;
1168 	device->device.devt = MKDEV(fw_cdev_major, minor);
1169 	dev_set_name(&device->device, "fw%d", minor);
1170 
1171 	BUILD_BUG_ON(ARRAY_SIZE(device->attribute_group.attrs) <
1172 			ARRAY_SIZE(fw_device_attributes) +
1173 			ARRAY_SIZE(config_rom_attributes));
1174 	init_fw_attribute_group(&device->device,
1175 				fw_device_attributes,
1176 				&device->attribute_group);
1177 
1178 	if (device_add(&device->device)) {
1179 		fw_err(card, "failed to add device\n");
1180 		goto error_with_cdev;
1181 	}
1182 
1183 	create_units(device);
1184 
1185 	/*
1186 	 * Transition the device to running state.  If it got pulled
1187 	 * out from under us while we did the initialization work, we
1188 	 * have to shut down the device again here.  Normally, though,
1189 	 * fw_node_event will be responsible for shutting it down when
1190 	 * necessary.  We have to use the atomic cmpxchg here to avoid
1191 	 * racing with the FW_NODE_DESTROYED case in
1192 	 * fw_node_event().
1193 	 */
1194 	if (atomic_cmpxchg(&device->state,
1195 			   FW_DEVICE_INITIALIZING,
1196 			   FW_DEVICE_RUNNING) == FW_DEVICE_GONE) {
1197 		device->workfn = fw_device_shutdown;
1198 		fw_schedule_device_work(device, SHUTDOWN_DELAY);
1199 	} else {
1200 		fw_notice(card, "created device %s: GUID %08x%08x, S%d00, quirks %08x\n",
1201 			  dev_name(&device->device),
1202 			  device->config_rom[3], device->config_rom[4],
1203 			  1 << device->max_speed, device->quirks);
1204 		device->config_rom_retries = 0;
1205 
1206 		set_broadcast_channel(device, device->generation);
1207 
1208 		add_device_randomness(&device->config_rom[3], 8);
1209 	}
1210 
1211 	/*
1212 	 * Reschedule the IRM work if we just finished reading the
1213 	 * root node config rom.  If this races with a bus reset we
1214 	 * just end up running the IRM work a couple of extra times -
1215 	 * pretty harmless.
1216 	 */
1217 	if (device->node == card->root_node)
1218 		fw_schedule_bm_work(card, 0);
1219 
1220 	return;
1221 
1222  error_with_cdev:
1223 	xa_erase(&fw_device_xa, minor);
1224  error:
1225 	fw_device_put(device);		// fw_device_xa's reference.
1226 
1227 	put_device(&device->device);	/* our reference */
1228 }
1229 
1230 /* Reread and compare bus info block and header of root directory */
1231 static int reread_config_rom(struct fw_device *device, int generation,
1232 			     bool *changed)
1233 {
1234 	u32 q;
1235 	int i, rcode;
1236 
1237 	for (i = 0; i < 6; i++) {
1238 		rcode = read_rom(device, generation, device->max_speed, i, &q);
1239 		if (rcode != RCODE_COMPLETE)
1240 			return rcode;
1241 
1242 		if (i == 0 && q == 0)
1243 			/* inaccessible (see read_config_rom); retry later */
1244 			return RCODE_BUSY;
1245 
1246 		if (q != device->config_rom[i]) {
1247 			*changed = true;
1248 			return RCODE_COMPLETE;
1249 		}
1250 	}
1251 
1252 	*changed = false;
1253 	return RCODE_COMPLETE;
1254 }
1255 
1256 static void fw_device_refresh(struct work_struct *work)
1257 {
1258 	struct fw_device *device = from_work(device, work, work.work);
1259 	struct fw_card *card = device->card;
1260 	int ret, node_id = device->node_id;
1261 	bool changed;
1262 
1263 	ret = reread_config_rom(device, device->generation, &changed);
1264 	if (ret != RCODE_COMPLETE)
1265 		goto failed_config_rom;
1266 
1267 	if (!changed) {
1268 		if (atomic_cmpxchg(&device->state,
1269 				   FW_DEVICE_INITIALIZING,
1270 				   FW_DEVICE_RUNNING) == FW_DEVICE_GONE)
1271 			goto gone;
1272 
1273 		fw_device_update(work);
1274 		device->config_rom_retries = 0;
1275 		goto out;
1276 	}
1277 
1278 	/*
1279 	 * Something changed.  We keep things simple and don't investigate
1280 	 * further.  We just destroy all previous units and create new ones.
1281 	 */
1282 	device_for_each_child(&device->device, NULL, shutdown_unit);
1283 
1284 	ret = read_config_rom(device, device->generation);
1285 	if (ret != RCODE_COMPLETE)
1286 		goto failed_config_rom;
1287 
1288 	fw_device_cdev_update(device);
1289 	create_units(device);
1290 
1291 	/* Userspace may want to re-read attributes. */
1292 	kobject_uevent(&device->device.kobj, KOBJ_CHANGE);
1293 
1294 	if (atomic_cmpxchg(&device->state,
1295 			   FW_DEVICE_INITIALIZING,
1296 			   FW_DEVICE_RUNNING) == FW_DEVICE_GONE)
1297 		goto gone;
1298 
1299 	fw_notice(card, "refreshed device %s\n", dev_name(&device->device));
1300 	device->config_rom_retries = 0;
1301 	goto out;
1302 
1303  failed_config_rom:
1304 	if (device->config_rom_retries < MAX_RETRIES &&
1305 	    atomic_read(&device->state) == FW_DEVICE_INITIALIZING) {
1306 		device->config_rom_retries++;
1307 		fw_schedule_device_work(device, RETRY_DELAY);
1308 		return;
1309 	}
1310 
1311 	fw_notice(card, "giving up on refresh of device %s: %s\n",
1312 		  dev_name(&device->device), fw_rcode_string(ret));
1313  gone:
1314 	atomic_set(&device->state, FW_DEVICE_GONE);
1315 	device->workfn = fw_device_shutdown;
1316 	fw_schedule_device_work(device, SHUTDOWN_DELAY);
1317  out:
1318 	if (node_id == card->root_node->node_id)
1319 		fw_schedule_bm_work(card, 0);
1320 }
1321 
1322 static void fw_device_workfn(struct work_struct *work)
1323 {
1324 	struct fw_device *device = from_work(device, to_delayed_work(work), work);
1325 	device->workfn(work);
1326 }
1327 
1328 void fw_node_event(struct fw_card *card, struct fw_node *node, int event)
1329 {
1330 	struct fw_device *device;
1331 
1332 	switch (event) {
1333 	case FW_NODE_CREATED:
1334 		/*
1335 		 * Attempt to scan the node, regardless whether its self ID has
1336 		 * the L (link active) flag set or not.  Some broken devices
1337 		 * send L=0 but have an up-and-running link; others send L=1
1338 		 * without actually having a link.
1339 		 */
1340  create:
1341 		device = kzalloc_obj(*device, GFP_ATOMIC);
1342 		if (device == NULL)
1343 			break;
1344 
1345 		/*
1346 		 * Do minimal initialization of the device here, the
1347 		 * rest will happen in fw_device_init().
1348 		 *
1349 		 * Attention:  A lot of things, even fw_device_get(),
1350 		 * cannot be done before fw_device_init() finished!
1351 		 * You can basically just check device->state and
1352 		 * schedule work until then, but only while holding
1353 		 * card->lock.
1354 		 */
1355 		atomic_set(&device->state, FW_DEVICE_INITIALIZING);
1356 		device->card = fw_card_get(card);
1357 		device->node = fw_node_get(node);
1358 		device->node_id = node->node_id;
1359 		device->generation = card->generation;
1360 		device->is_local = node == card->local_node;
1361 		mutex_init(&device->client_list_mutex);
1362 		INIT_LIST_HEAD(&device->client_list);
1363 
1364 		/*
1365 		 * Set the node data to point back to this device so
1366 		 * FW_NODE_UPDATED callbacks can update the node_id
1367 		 * and generation for the device.
1368 		 */
1369 		fw_node_set_device(node, device);
1370 
1371 		/*
1372 		 * Many devices are slow to respond after bus resets,
1373 		 * especially if they are bus powered and go through
1374 		 * power-up after getting plugged in.  We schedule the
1375 		 * first config rom scan half a second after bus reset.
1376 		 */
1377 		device->workfn = fw_device_init;
1378 		INIT_DELAYED_WORK(&device->work, fw_device_workfn);
1379 		fw_schedule_device_work(device, INITIAL_DELAY);
1380 		break;
1381 
1382 	case FW_NODE_INITIATED_RESET:
1383 	case FW_NODE_LINK_ON:
1384 		device = fw_node_get_device(node);
1385 		if (device == NULL)
1386 			goto create;
1387 
1388 		device->node_id = node->node_id;
1389 		smp_wmb();  /* update node_id before generation */
1390 		device->generation = card->generation;
1391 		if (atomic_cmpxchg(&device->state,
1392 			    FW_DEVICE_RUNNING,
1393 			    FW_DEVICE_INITIALIZING) == FW_DEVICE_RUNNING) {
1394 			device->workfn = fw_device_refresh;
1395 			fw_schedule_device_work(device,
1396 				device->is_local ? 0 : INITIAL_DELAY);
1397 		}
1398 		break;
1399 
1400 	case FW_NODE_UPDATED:
1401 		device = fw_node_get_device(node);
1402 		if (device == NULL)
1403 			break;
1404 
1405 		device->node_id = node->node_id;
1406 		smp_wmb();  /* update node_id before generation */
1407 		device->generation = card->generation;
1408 		if (atomic_read(&device->state) == FW_DEVICE_RUNNING) {
1409 			device->workfn = fw_device_update;
1410 			fw_schedule_device_work(device, 0);
1411 		}
1412 		break;
1413 
1414 	case FW_NODE_DESTROYED:
1415 	case FW_NODE_LINK_OFF:
1416 		if (!fw_node_get_device(node))
1417 			break;
1418 
1419 		/*
1420 		 * Destroy the device associated with the node.  There
1421 		 * are two cases here: either the device is fully
1422 		 * initialized (FW_DEVICE_RUNNING) or we're in the
1423 		 * process of reading its config rom
1424 		 * (FW_DEVICE_INITIALIZING).  If it is fully
1425 		 * initialized we can reuse device->work to schedule a
1426 		 * full fw_device_shutdown().  If not, there's work
1427 		 * scheduled to read it's config rom, and we just put
1428 		 * the device in shutdown state to have that code fail
1429 		 * to create the device.
1430 		 */
1431 		device = fw_node_get_device(node);
1432 		if (atomic_xchg(&device->state,
1433 				FW_DEVICE_GONE) == FW_DEVICE_RUNNING) {
1434 			device->workfn = fw_device_shutdown;
1435 			fw_schedule_device_work(device,
1436 				list_empty(&card->link) ? 0 : SHUTDOWN_DELAY);
1437 		}
1438 		break;
1439 	}
1440 }
1441 
1442 #ifdef CONFIG_FIREWIRE_KUNIT_DEVICE_ATTRIBUTE_TEST
1443 #include "device-attribute-test.c"
1444 #endif
1445