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