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