fedora core 6 1.2949 + vserver 2.2.0
[linux-2.6.git] / drivers / xen / xenbus / xenbus_probe.c
1 /******************************************************************************
2  * Talks to Xen Store to figure out what devices we have.
3  *
4  * Copyright (C) 2005 Rusty Russell, IBM Corporation
5  * Copyright (C) 2005 Mike Wray, Hewlett-Packard
6  * Copyright (C) 2005, 2006 XenSource Ltd
7  * 
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License version 2
10  * as published by the Free Software Foundation; or, when distributed
11  * separately from the Linux kernel or incorporated into other
12  * software packages, subject to the following license:
13  * 
14  * Permission is hereby granted, free of charge, to any person obtaining a copy
15  * of this source file (the "Software"), to deal in the Software without
16  * restriction, including without limitation the rights to use, copy, modify,
17  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
18  * and to permit persons to whom the Software is furnished to do so, subject to
19  * the following conditions:
20  * 
21  * The above copyright notice and this permission notice shall be included in
22  * all copies or substantial portions of the Software.
23  * 
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
29  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
30  * IN THE SOFTWARE.
31  */
32
33 #define DPRINTK(fmt, args...)                           \
34         pr_debug("xenbus_probe (%s:%d) " fmt ".\n",     \
35                  __FUNCTION__, __LINE__, ##args)
36
37 #include <linux/kernel.h>
38 #include <linux/err.h>
39 #include <linux/string.h>
40 #include <linux/ctype.h>
41 #include <linux/fcntl.h>
42 #include <linux/mm.h>
43 #include <linux/notifier.h>
44 #include <linux/kthread.h>
45
46 #include <asm/io.h>
47 #include <asm/page.h>
48 #include <asm/maddr.h>
49 #include <asm/pgtable.h>
50 #include <asm/hypervisor.h>
51 #include <xen/xenbus.h>
52 #include <xen/xen_proc.h>
53 #include <xen/evtchn.h>
54 #include <xen/features.h>
55 #include <xen/hvm.h>
56
57 #include "xenbus_comms.h"
58
59 int xen_store_evtchn;
60 struct xenstore_domain_interface *xen_store_interface;
61 static unsigned long xen_store_mfn;
62
63 extern struct mutex xenwatch_mutex;
64
65 static BLOCKING_NOTIFIER_HEAD(xenstore_notifier_list);
66
67 static void wait_for_devices(struct xenbus_driver *xendrv);
68
69 static int xenbus_probe_frontend(const char *type, const char *name);
70 static int xenbus_uevent_backend(struct device *dev, char **envp,
71                                  int num_envp, char *buffer, int buffer_size);
72 static int xenbus_probe_backend(const char *type, const char *domid);
73
74 static int xenbus_dev_probe(struct device *_dev);
75 static int xenbus_dev_remove(struct device *_dev);
76 static void xenbus_dev_shutdown(struct device *_dev);
77
78 /* If something in array of ids matches this device, return it. */
79 static const struct xenbus_device_id *
80 match_device(const struct xenbus_device_id *arr, struct xenbus_device *dev)
81 {
82         for (; *arr->devicetype != '\0'; arr++) {
83                 if (!strcmp(arr->devicetype, dev->devicetype))
84                         return arr;
85         }
86         return NULL;
87 }
88
89 static int xenbus_match(struct device *_dev, struct device_driver *_drv)
90 {
91         struct xenbus_driver *drv = to_xenbus_driver(_drv);
92
93         if (!drv->ids)
94                 return 0;
95
96         return match_device(drv->ids, to_xenbus_device(_dev)) != NULL;
97 }
98
99 struct xen_bus_type
100 {
101         char *root;
102         unsigned int levels;
103         int (*get_bus_id)(char bus_id[BUS_ID_SIZE], const char *nodename);
104         int (*probe)(const char *type, const char *dir);
105         struct bus_type bus;
106         struct device dev;
107 };
108
109
110 /* device/<type>/<id> => <type>-<id> */
111 static int frontend_bus_id(char bus_id[BUS_ID_SIZE], const char *nodename)
112 {
113         nodename = strchr(nodename, '/');
114         if (!nodename || strlen(nodename + 1) >= BUS_ID_SIZE) {
115                 printk(KERN_WARNING "XENBUS: bad frontend %s\n", nodename);
116                 return -EINVAL;
117         }
118
119         strlcpy(bus_id, nodename + 1, BUS_ID_SIZE);
120         if (!strchr(bus_id, '/')) {
121                 printk(KERN_WARNING "XENBUS: bus_id %s no slash\n", bus_id);
122                 return -EINVAL;
123         }
124         *strchr(bus_id, '/') = '-';
125         return 0;
126 }
127
128
129 static void free_otherend_details(struct xenbus_device *dev)
130 {
131         kfree(dev->otherend);
132         dev->otherend = NULL;
133 }
134
135
136 static void free_otherend_watch(struct xenbus_device *dev)
137 {
138         if (dev->otherend_watch.node) {
139                 unregister_xenbus_watch(&dev->otherend_watch);
140                 kfree(dev->otherend_watch.node);
141                 dev->otherend_watch.node = NULL;
142         }
143 }
144
145
146 static int read_otherend_details(struct xenbus_device *xendev,
147                                  char *id_node, char *path_node)
148 {
149         int err = xenbus_gather(XBT_NIL, xendev->nodename,
150                                 id_node, "%i", &xendev->otherend_id,
151                                 path_node, NULL, &xendev->otherend,
152                                 NULL);
153         if (err) {
154                 xenbus_dev_fatal(xendev, err,
155                                  "reading other end details from %s",
156                                  xendev->nodename);
157                 return err;
158         }
159         if (strlen(xendev->otherend) == 0 ||
160             !xenbus_exists(XBT_NIL, xendev->otherend, "")) {
161                 xenbus_dev_fatal(xendev, -ENOENT,
162                                  "unable to read other end from %s.  "
163                                  "missing or inaccessible.",
164                                  xendev->nodename);
165                 free_otherend_details(xendev);
166                 return -ENOENT;
167         }
168
169         return 0;
170 }
171
172
173 static int read_backend_details(struct xenbus_device *xendev)
174 {
175         return read_otherend_details(xendev, "backend-id", "backend");
176 }
177
178
179 static int read_frontend_details(struct xenbus_device *xendev)
180 {
181         return read_otherend_details(xendev, "frontend-id", "frontend");
182 }
183
184
185 /* Bus type for frontend drivers. */
186 static struct xen_bus_type xenbus_frontend = {
187         .root = "device",
188         .levels = 2,            /* device/type/<id> */
189         .get_bus_id = frontend_bus_id,
190         .probe = xenbus_probe_frontend,
191         .bus = {
192                 .name     = "xen",
193                 .match    = xenbus_match,
194                 .probe    = xenbus_dev_probe,
195                 .remove   = xenbus_dev_remove,
196                 .shutdown = xenbus_dev_shutdown,
197         },
198         .dev = {
199                 .bus_id = "xen",
200         },
201 };
202
203 /* backend/<type>/<fe-uuid>/<id> => <type>-<fe-domid>-<id> */
204 static int backend_bus_id(char bus_id[BUS_ID_SIZE], const char *nodename)
205 {
206         int domid, err;
207         const char *devid, *type, *frontend;
208         unsigned int typelen;
209
210         type = strchr(nodename, '/');
211         if (!type)
212                 return -EINVAL;
213         type++;
214         typelen = strcspn(type, "/");
215         if (!typelen || type[typelen] != '/')
216                 return -EINVAL;
217
218         devid = strrchr(nodename, '/') + 1;
219
220         err = xenbus_gather(XBT_NIL, nodename, "frontend-id", "%i", &domid,
221                             "frontend", NULL, &frontend,
222                             NULL);
223         if (err)
224                 return err;
225         if (strlen(frontend) == 0)
226                 err = -ERANGE;
227         if (!err && !xenbus_exists(XBT_NIL, frontend, ""))
228                 err = -ENOENT;
229
230         kfree(frontend);
231
232         if (err)
233                 return err;
234
235         if (snprintf(bus_id, BUS_ID_SIZE,
236                      "%.*s-%i-%s", typelen, type, domid, devid) >= BUS_ID_SIZE)
237                 return -ENOSPC;
238         return 0;
239 }
240
241 static struct xen_bus_type xenbus_backend = {
242         .root = "backend",
243         .levels = 3,            /* backend/type/<frontend>/<id> */
244         .get_bus_id = backend_bus_id,
245         .probe = xenbus_probe_backend,
246         .bus = {
247                 .name     = "xen-backend",
248                 .match    = xenbus_match,
249                 .probe    = xenbus_dev_probe,
250                 .remove   = xenbus_dev_remove,
251 //              .shutdown = xenbus_dev_shutdown,
252                 .uevent   = xenbus_uevent_backend,
253         },
254         .dev = {
255                 .bus_id = "xen-backend",
256         },
257 };
258
259 static int xenbus_uevent_backend(struct device *dev, char **envp,
260                                  int num_envp, char *buffer, int buffer_size)
261 {
262         struct xenbus_device *xdev;
263         struct xenbus_driver *drv;
264         int i = 0;
265         int length = 0;
266
267         DPRINTK("");
268
269         if (dev == NULL)
270                 return -ENODEV;
271
272         xdev = to_xenbus_device(dev);
273         if (xdev == NULL)
274                 return -ENODEV;
275
276         /* stuff we want to pass to /sbin/hotplug */
277         add_uevent_var(envp, num_envp, &i, buffer, buffer_size, &length,
278                        "XENBUS_TYPE=%s", xdev->devicetype);
279
280         add_uevent_var(envp, num_envp, &i, buffer, buffer_size, &length,
281                        "XENBUS_PATH=%s", xdev->nodename);
282
283         add_uevent_var(envp, num_envp, &i, buffer, buffer_size, &length,
284                        "XENBUS_BASE_PATH=%s", xenbus_backend.root);
285
286         /* terminate, set to next free slot, shrink available space */
287         envp[i] = NULL;
288         envp = &envp[i];
289         num_envp -= i;
290         buffer = &buffer[length];
291         buffer_size -= length;
292
293         if (dev->driver) {
294                 drv = to_xenbus_driver(dev->driver);
295                 if (drv && drv->uevent)
296                         return drv->uevent(xdev, envp, num_envp, buffer,
297                                            buffer_size);
298         }
299
300         return 0;
301 }
302
303 static void otherend_changed(struct xenbus_watch *watch,
304                              const char **vec, unsigned int len)
305 {
306         struct xenbus_device *dev =
307                 container_of(watch, struct xenbus_device, otherend_watch);
308         struct xenbus_driver *drv = to_xenbus_driver(dev->dev.driver);
309         enum xenbus_state state;
310
311         /* Protect us against watches firing on old details when the otherend
312            details change, say immediately after a resume. */
313         if (!dev->otherend ||
314             strncmp(dev->otherend, vec[XS_WATCH_PATH],
315                     strlen(dev->otherend))) {
316                 DPRINTK("Ignoring watch at %s", vec[XS_WATCH_PATH]);
317                 return;
318         }
319
320         state = xenbus_read_driver_state(dev->otherend);
321
322         DPRINTK("state is %d (%s), %s, %s", state, xenbus_strstate(state),
323                 dev->otherend_watch.node, vec[XS_WATCH_PATH]);
324
325         /*
326          * Ignore xenbus transitions during shutdown. This prevents us doing
327          * work that can fail e.g., when the rootfs is gone.
328          */
329         if (system_state > SYSTEM_RUNNING) {
330                 struct xen_bus_type *bus = bus;
331                 bus = container_of(dev->dev.bus, struct xen_bus_type, bus);
332                 /* If we're frontend, drive the state machine to Closed. */
333                 /* This should cause the backend to release our resources. */
334                 if ((bus == &xenbus_frontend) && (state == XenbusStateClosing))
335                         xenbus_frontend_closed(dev);
336                 return;
337         }
338
339         if (drv->otherend_changed)
340                 drv->otherend_changed(dev, state);
341 }
342
343
344 static int talk_to_otherend(struct xenbus_device *dev)
345 {
346         struct xenbus_driver *drv = to_xenbus_driver(dev->dev.driver);
347
348         free_otherend_watch(dev);
349         free_otherend_details(dev);
350
351         return drv->read_otherend_details(dev);
352 }
353
354
355 static int watch_otherend(struct xenbus_device *dev)
356 {
357         return xenbus_watch_path2(dev, dev->otherend, "state",
358                                   &dev->otherend_watch, otherend_changed);
359 }
360
361
362 static int xenbus_dev_probe(struct device *_dev)
363 {
364         struct xenbus_device *dev = to_xenbus_device(_dev);
365         struct xenbus_driver *drv = to_xenbus_driver(_dev->driver);
366         const struct xenbus_device_id *id;
367         int err;
368
369         DPRINTK("%s", dev->nodename);
370
371         if (!drv->probe) {
372                 err = -ENODEV;
373                 goto fail;
374         }
375
376         id = match_device(drv->ids, dev);
377         if (!id) {
378                 err = -ENODEV;
379                 goto fail;
380         }
381
382         err = talk_to_otherend(dev);
383         if (err) {
384                 printk(KERN_WARNING
385                        "xenbus_probe: talk_to_otherend on %s failed.\n",
386                        dev->nodename);
387                 return err;
388         }
389
390         err = drv->probe(dev, id);
391         if (err)
392                 goto fail;
393
394         err = watch_otherend(dev);
395         if (err) {
396                 printk(KERN_WARNING
397                        "xenbus_probe: watch_otherend on %s failed.\n",
398                        dev->nodename);
399                 return err;
400         }
401
402         return 0;
403 fail:
404         xenbus_dev_error(dev, err, "xenbus_dev_probe on %s", dev->nodename);
405         xenbus_switch_state(dev, XenbusStateClosed);
406         return -ENODEV;
407 }
408
409 static int xenbus_dev_remove(struct device *_dev)
410 {
411         struct xenbus_device *dev = to_xenbus_device(_dev);
412         struct xenbus_driver *drv = to_xenbus_driver(_dev->driver);
413
414         DPRINTK("%s", dev->nodename);
415
416         free_otherend_watch(dev);
417         free_otherend_details(dev);
418
419         if (drv->remove)
420                 drv->remove(dev);
421
422         xenbus_switch_state(dev, XenbusStateClosed);
423         return 0;
424 }
425
426 static void xenbus_dev_shutdown(struct device *_dev)
427 {
428         struct xenbus_device *dev = to_xenbus_device(_dev);
429         unsigned long timeout = 5*HZ;
430
431         DPRINTK("%s", dev->nodename);
432
433         get_device(&dev->dev);
434         if (dev->state != XenbusStateConnected) {
435                 printk("%s: %s: %s != Connected, skipping\n", __FUNCTION__,
436                        dev->nodename, xenbus_strstate(dev->state));
437                 goto out;
438         }
439         xenbus_switch_state(dev, XenbusStateClosing);
440         timeout = wait_for_completion_timeout(&dev->down, timeout);
441         if (!timeout)
442                 printk("%s: %s timeout closing device\n", __FUNCTION__, dev->nodename);
443  out:
444         put_device(&dev->dev);
445 }
446
447 static int xenbus_register_driver_common(struct xenbus_driver *drv,
448                                          struct xen_bus_type *bus)
449 {
450         int ret;
451
452         drv->driver.name = drv->name;
453         drv->driver.bus = &bus->bus;
454         drv->driver.owner = drv->owner;
455
456         mutex_lock(&xenwatch_mutex);
457         ret = driver_register(&drv->driver);
458         mutex_unlock(&xenwatch_mutex);
459         return ret;
460 }
461
462 int xenbus_register_frontend(struct xenbus_driver *drv)
463 {
464         int ret;
465
466         drv->read_otherend_details = read_backend_details;
467
468         ret = xenbus_register_driver_common(drv, &xenbus_frontend);
469         if (ret)
470                 return ret;
471
472         /* If this driver is loaded as a module wait for devices to attach. */
473         wait_for_devices(drv);
474
475         return 0;
476 }
477 EXPORT_SYMBOL_GPL(xenbus_register_frontend);
478
479 int xenbus_register_backend(struct xenbus_driver *drv)
480 {
481         drv->read_otherend_details = read_frontend_details;
482
483         return xenbus_register_driver_common(drv, &xenbus_backend);
484 }
485 EXPORT_SYMBOL_GPL(xenbus_register_backend);
486
487 void xenbus_unregister_driver(struct xenbus_driver *drv)
488 {
489         driver_unregister(&drv->driver);
490 }
491 EXPORT_SYMBOL_GPL(xenbus_unregister_driver);
492
493 struct xb_find_info
494 {
495         struct xenbus_device *dev;
496         const char *nodename;
497 };
498
499 static int cmp_dev(struct device *dev, void *data)
500 {
501         struct xenbus_device *xendev = to_xenbus_device(dev);
502         struct xb_find_info *info = data;
503
504         if (!strcmp(xendev->nodename, info->nodename)) {
505                 info->dev = xendev;
506                 get_device(dev);
507                 return 1;
508         }
509         return 0;
510 }
511
512 struct xenbus_device *xenbus_device_find(const char *nodename,
513                                          struct bus_type *bus)
514 {
515         struct xb_find_info info = { .dev = NULL, .nodename = nodename };
516
517         bus_for_each_dev(bus, NULL, &info, cmp_dev);
518         return info.dev;
519 }
520
521 static int cleanup_dev(struct device *dev, void *data)
522 {
523         struct xenbus_device *xendev = to_xenbus_device(dev);
524         struct xb_find_info *info = data;
525         int len = strlen(info->nodename);
526
527         DPRINTK("%s", info->nodename);
528
529         /* Match the info->nodename path, or any subdirectory of that path. */
530         if (strncmp(xendev->nodename, info->nodename, len))
531                 return 0;
532
533         /* If the node name is longer, ensure it really is a subdirectory. */
534         if ((strlen(xendev->nodename) > len) && (xendev->nodename[len] != '/'))
535                 return 0;
536
537         info->dev = xendev;
538         get_device(dev);
539         return 1;
540 }
541
542 static void xenbus_cleanup_devices(const char *path, struct bus_type *bus)
543 {
544         struct xb_find_info info = { .nodename = path };
545
546         do {
547                 info.dev = NULL;
548                 bus_for_each_dev(bus, NULL, &info, cleanup_dev);
549                 if (info.dev) {
550                         device_unregister(&info.dev->dev);
551                         put_device(&info.dev->dev);
552                 }
553         } while (info.dev);
554 }
555
556 static void xenbus_dev_release(struct device *dev)
557 {
558         if (dev)
559                 kfree(to_xenbus_device(dev));
560 }
561
562 static ssize_t xendev_show_nodename(struct device *dev,
563                                     struct device_attribute *attr, char *buf)
564 {
565         return sprintf(buf, "%s\n", to_xenbus_device(dev)->nodename);
566 }
567 DEVICE_ATTR(nodename, S_IRUSR | S_IRGRP | S_IROTH, xendev_show_nodename, NULL);
568
569 static ssize_t xendev_show_devtype(struct device *dev,
570                                    struct device_attribute *attr, char *buf)
571 {
572         return sprintf(buf, "%s\n", to_xenbus_device(dev)->devicetype);
573 }
574 DEVICE_ATTR(devtype, S_IRUSR | S_IRGRP | S_IROTH, xendev_show_devtype, NULL);
575
576
577 static int xenbus_probe_node(struct xen_bus_type *bus,
578                              const char *type,
579                              const char *nodename)
580 {
581         int err;
582         struct xenbus_device *xendev;
583         size_t stringlen;
584         char *tmpstring;
585
586         enum xenbus_state state = xenbus_read_driver_state(nodename);
587
588         if (state != XenbusStateInitialising) {
589                 /* Device is not new, so ignore it.  This can happen if a
590                    device is going away after switching to Closed.  */
591                 return 0;
592         }
593
594         stringlen = strlen(nodename) + 1 + strlen(type) + 1;
595         xendev = kzalloc(sizeof(*xendev) + stringlen, GFP_KERNEL);
596         if (!xendev)
597                 return -ENOMEM;
598
599         /* Copy the strings into the extra space. */
600
601         tmpstring = (char *)(xendev + 1);
602         strcpy(tmpstring, nodename);
603         xendev->nodename = tmpstring;
604
605         tmpstring += strlen(tmpstring) + 1;
606         strcpy(tmpstring, type);
607         xendev->devicetype = tmpstring;
608         init_completion(&xendev->down);
609
610         xendev->dev.parent = &bus->dev;
611         xendev->dev.bus = &bus->bus;
612         xendev->dev.release = xenbus_dev_release;
613
614         err = bus->get_bus_id(xendev->dev.bus_id, xendev->nodename);
615         if (err)
616                 goto fail;
617
618         /* Register with generic device framework. */
619         err = device_register(&xendev->dev);
620         if (err)
621                 goto fail;
622
623         err = device_create_file(&xendev->dev, &dev_attr_nodename);
624         if (err)
625                 goto fail;
626
627         err = device_create_file(&xendev->dev, &dev_attr_devtype);
628         if (err)
629                 goto fail;
630
631         return 0;
632 fail:
633         kfree(xendev);
634         return err;
635 }
636
637 /* device/<typename>/<name> */
638 static int xenbus_probe_frontend(const char *type, const char *name)
639 {
640         char *nodename;
641         int err;
642
643         nodename = kasprintf(GFP_KERNEL, "%s/%s/%s", xenbus_frontend.root, type, name);
644         if (!nodename)
645                 return -ENOMEM;
646
647         DPRINTK("%s", nodename);
648
649         err = xenbus_probe_node(&xenbus_frontend, type, nodename);
650         kfree(nodename);
651         return err;
652 }
653
654 /* backend/<typename>/<frontend-uuid>/<name> */
655 static int xenbus_probe_backend_unit(const char *dir,
656                                      const char *type,
657                                      const char *name)
658 {
659         char *nodename;
660         int err;
661
662         nodename = kasprintf(GFP_KERNEL, "%s/%s", dir, name);
663         if (!nodename)
664                 return -ENOMEM;
665
666         DPRINTK("%s\n", nodename);
667
668         err = xenbus_probe_node(&xenbus_backend, type, nodename);
669         kfree(nodename);
670         return err;
671 }
672
673 /* backend/<typename>/<frontend-domid> */
674 static int xenbus_probe_backend(const char *type, const char *domid)
675 {
676         char *nodename;
677         int err = 0;
678         char **dir;
679         unsigned int i, dir_n = 0;
680
681         DPRINTK("");
682
683         nodename = kasprintf(GFP_KERNEL, "%s/%s/%s", xenbus_backend.root, type, domid);
684         if (!nodename)
685                 return -ENOMEM;
686
687         dir = xenbus_directory(XBT_NIL, nodename, "", &dir_n);
688         if (IS_ERR(dir)) {
689                 kfree(nodename);
690                 return PTR_ERR(dir);
691         }
692
693         for (i = 0; i < dir_n; i++) {
694                 err = xenbus_probe_backend_unit(nodename, type, dir[i]);
695                 if (err)
696                         break;
697         }
698         kfree(dir);
699         kfree(nodename);
700         return err;
701 }
702
703 static int xenbus_probe_device_type(struct xen_bus_type *bus, const char *type)
704 {
705         int err = 0;
706         char **dir;
707         unsigned int dir_n = 0;
708         int i;
709
710         dir = xenbus_directory(XBT_NIL, bus->root, type, &dir_n);
711         if (IS_ERR(dir))
712                 return PTR_ERR(dir);
713
714         for (i = 0; i < dir_n; i++) {
715                 err = bus->probe(type, dir[i]);
716                 if (err)
717                         break;
718         }
719         kfree(dir);
720         return err;
721 }
722
723 static int xenbus_probe_devices(struct xen_bus_type *bus)
724 {
725         int err = 0;
726         char **dir;
727         unsigned int i, dir_n;
728
729         dir = xenbus_directory(XBT_NIL, bus->root, "", &dir_n);
730         if (IS_ERR(dir))
731                 return PTR_ERR(dir);
732
733         for (i = 0; i < dir_n; i++) {
734                 err = xenbus_probe_device_type(bus, dir[i]);
735                 if (err)
736                         break;
737         }
738         kfree(dir);
739         return err;
740 }
741
742 static unsigned int char_count(const char *str, char c)
743 {
744         unsigned int i, ret = 0;
745
746         for (i = 0; str[i]; i++)
747                 if (str[i] == c)
748                         ret++;
749         return ret;
750 }
751
752 static int strsep_len(const char *str, char c, unsigned int len)
753 {
754         unsigned int i;
755
756         for (i = 0; str[i]; i++)
757                 if (str[i] == c) {
758                         if (len == 0)
759                                 return i;
760                         len--;
761                 }
762         return (len == 0) ? i : -ERANGE;
763 }
764
765 static void dev_changed(const char *node, struct xen_bus_type *bus)
766 {
767         int exists, rootlen;
768         struct xenbus_device *dev;
769         char type[BUS_ID_SIZE];
770         const char *p, *root;
771
772         if (char_count(node, '/') < 2)
773                 return;
774
775         exists = xenbus_exists(XBT_NIL, node, "");
776         if (!exists) {
777                 xenbus_cleanup_devices(node, &bus->bus);
778                 return;
779         }
780
781         /* backend/<type>/... or device/<type>/... */
782         p = strchr(node, '/') + 1;
783         snprintf(type, BUS_ID_SIZE, "%.*s", (int)strcspn(p, "/"), p);
784         type[BUS_ID_SIZE-1] = '\0';
785
786         rootlen = strsep_len(node, '/', bus->levels);
787         if (rootlen < 0)
788                 return;
789         root = kasprintf(GFP_KERNEL, "%.*s", rootlen, node);
790         if (!root)
791                 return;
792
793         dev = xenbus_device_find(root, &bus->bus);
794         if (!dev)
795                 xenbus_probe_node(bus, type, root);
796         else
797                 put_device(&dev->dev);
798
799         kfree(root);
800 }
801
802 static void frontend_changed(struct xenbus_watch *watch,
803                              const char **vec, unsigned int len)
804 {
805         DPRINTK("");
806
807         dev_changed(vec[XS_WATCH_PATH], &xenbus_frontend);
808 }
809
810 static void backend_changed(struct xenbus_watch *watch,
811                             const char **vec, unsigned int len)
812 {
813         DPRINTK("");
814
815         dev_changed(vec[XS_WATCH_PATH], &xenbus_backend);
816 }
817
818 /* We watch for devices appearing and vanishing. */
819 static struct xenbus_watch fe_watch = {
820         .node = "device",
821         .callback = frontend_changed,
822 };
823
824 static struct xenbus_watch be_watch = {
825         .node = "backend",
826         .callback = backend_changed,
827 };
828
829 static int suspend_dev(struct device *dev, void *data)
830 {
831         int err = 0;
832         struct xenbus_driver *drv;
833         struct xenbus_device *xdev;
834
835         DPRINTK("");
836
837         if (dev->driver == NULL)
838                 return 0;
839         drv = to_xenbus_driver(dev->driver);
840         xdev = container_of(dev, struct xenbus_device, dev);
841         if (drv->suspend)
842                 err = drv->suspend(xdev);
843         if (err)
844                 printk(KERN_WARNING
845                        "xenbus: suspend %s failed: %i\n", dev->bus_id, err);
846         return 0;
847 }
848
849 static int resume_dev(struct device *dev, void *data)
850 {
851         int err;
852         struct xenbus_driver *drv;
853         struct xenbus_device *xdev;
854
855         DPRINTK("");
856
857         if (dev->driver == NULL)
858                 return 0;
859
860         drv = to_xenbus_driver(dev->driver);
861         xdev = container_of(dev, struct xenbus_device, dev);
862
863         err = talk_to_otherend(xdev);
864         if (err) {
865                 printk(KERN_WARNING
866                        "xenbus: resume (talk_to_otherend) %s failed: %i\n",
867                        dev->bus_id, err);
868                 return err;
869         }
870
871         xdev->state = XenbusStateInitialising;
872
873         if (drv->resume) {
874                 err = drv->resume(xdev);
875                 if (err) { 
876                         printk(KERN_WARNING
877                                "xenbus: resume %s failed: %i\n", 
878                                dev->bus_id, err);
879                         return err;
880                 }
881         }
882
883         err = watch_otherend(xdev);
884         if (err) {
885                 printk(KERN_WARNING
886                        "xenbus_probe: resume (watch_otherend) %s failed: "
887                        "%d.\n", dev->bus_id, err);
888                 return err;
889         }
890
891         return 0;
892 }
893
894 void xenbus_suspend(void)
895 {
896         DPRINTK("");
897
898         bus_for_each_dev(&xenbus_frontend.bus, NULL, NULL, suspend_dev);
899         bus_for_each_dev(&xenbus_backend.bus, NULL, NULL, suspend_dev);
900         xs_suspend();
901 }
902 EXPORT_SYMBOL_GPL(xenbus_suspend);
903
904 void xenbus_resume(void)
905 {
906         xb_init_comms();
907         xs_resume();
908         bus_for_each_dev(&xenbus_frontend.bus, NULL, NULL, resume_dev);
909         bus_for_each_dev(&xenbus_backend.bus, NULL, NULL, resume_dev);
910 }
911 EXPORT_SYMBOL_GPL(xenbus_resume);
912
913
914 /* A flag to determine if xenstored is 'ready' (i.e. has started) */
915 int xenstored_ready = 0;
916
917
918 int register_xenstore_notifier(struct notifier_block *nb)
919 {
920         int ret = 0;
921
922         if (xenstored_ready > 0)
923                 ret = nb->notifier_call(nb, 0, NULL);
924         else
925                 blocking_notifier_chain_register(&xenstore_notifier_list, nb);
926
927         return ret;
928 }
929 EXPORT_SYMBOL_GPL(register_xenstore_notifier);
930
931 void unregister_xenstore_notifier(struct notifier_block *nb)
932 {
933         blocking_notifier_chain_unregister(&xenstore_notifier_list, nb);
934 }
935 EXPORT_SYMBOL_GPL(unregister_xenstore_notifier);
936
937
938 void xenbus_probe(struct work_struct *unused)
939 {
940         BUG_ON((xenstored_ready <= 0));
941
942         /* Enumerate devices in xenstore. */
943         xenbus_probe_devices(&xenbus_frontend);
944         xenbus_probe_devices(&xenbus_backend);
945
946         /* Watch for changes. */
947         register_xenbus_watch(&fe_watch);
948         register_xenbus_watch(&be_watch);
949
950         /* Notify others that xenstore is up */
951         blocking_notifier_call_chain(&xenstore_notifier_list, 0, NULL);
952 }
953
954
955 #ifdef CONFIG_PROC_FS
956 static struct file_operations xsd_kva_fops;
957 static struct proc_dir_entry *xsd_kva_intf;
958 static struct proc_dir_entry *xsd_port_intf;
959
960 static int xsd_kva_mmap(struct file *file, struct vm_area_struct *vma)
961 {
962         size_t size = vma->vm_end - vma->vm_start;
963
964         if ((size > PAGE_SIZE) || (vma->vm_pgoff != 0))
965                 return -EINVAL;
966
967         if (remap_pfn_range(vma, vma->vm_start, mfn_to_pfn(xen_store_mfn),
968                             size, vma->vm_page_prot))
969                 return -EAGAIN;
970
971         return 0;
972 }
973
974 static int xsd_kva_read(char *page, char **start, off_t off,
975                         int count, int *eof, void *data)
976 {
977         int len;
978
979         len  = sprintf(page, "0x%p", xen_store_interface);
980         *eof = 1;
981         return len;
982 }
983
984 static int xsd_port_read(char *page, char **start, off_t off,
985                          int count, int *eof, void *data)
986 {
987         int len;
988
989         len  = sprintf(page, "%d", xen_store_evtchn);
990         *eof = 1;
991         return len;
992 }
993 #endif
994
995 static int __init xenbus_probe_init(void)
996 {
997         int err = 0;
998         unsigned long page = 0;
999
1000         DPRINTK("");
1001
1002         if (!is_running_on_xen())
1003                 return -ENODEV;
1004
1005         /* Register ourselves with the kernel bus subsystem */
1006         err = bus_register(&xenbus_frontend.bus);
1007         if (err)
1008                 goto err_frontend_bus;
1009         err = bus_register(&xenbus_backend.bus);
1010         if (err)
1011                 goto err_backend_bus;
1012
1013         /*
1014          * Domain0 doesn't have a store_evtchn or store_mfn yet.
1015          */
1016         if (is_initial_xendomain()) {
1017                 struct evtchn_alloc_unbound alloc_unbound;
1018
1019                 /* Allocate page. */
1020                 page = get_zeroed_page(GFP_KERNEL);
1021                 if (!page) {
1022                         err = -ENOMEM;
1023                         goto err_nomem;
1024                 }
1025
1026                 xen_store_mfn = xen_start_info->store_mfn =
1027                         pfn_to_mfn(virt_to_phys((void *)page) >>
1028                                    PAGE_SHIFT);
1029
1030                 /* Next allocate a local port which xenstored can bind to */
1031                 alloc_unbound.dom        = DOMID_SELF;
1032                 alloc_unbound.remote_dom = 0;
1033
1034                 err = HYPERVISOR_event_channel_op(EVTCHNOP_alloc_unbound,
1035                                                   &alloc_unbound);
1036                 if (err == -ENOSYS)
1037                         goto err;
1038                 BUG_ON(err);
1039                 xen_store_evtchn = xen_start_info->store_evtchn =
1040                         alloc_unbound.port;
1041
1042 #ifdef CONFIG_PROC_FS
1043                 /* And finally publish the above info in /proc/xen */
1044                 xsd_kva_intf = create_xen_proc_entry("xsd_kva", 0600);
1045                 if (xsd_kva_intf) {
1046                         memcpy(&xsd_kva_fops, xsd_kva_intf->proc_fops,
1047                                sizeof(xsd_kva_fops));
1048                         xsd_kva_fops.mmap = xsd_kva_mmap;
1049                         xsd_kva_intf->proc_fops = &xsd_kva_fops;
1050                         xsd_kva_intf->read_proc = xsd_kva_read;
1051                 }
1052                 xsd_port_intf = create_xen_proc_entry("xsd_port", 0400);
1053                 if (xsd_port_intf)
1054                         xsd_port_intf->read_proc = xsd_port_read;
1055 #endif
1056                 xen_store_interface = mfn_to_virt(xen_store_mfn);
1057         } else {
1058                 xenstored_ready = 1;
1059 #ifdef CONFIG_XEN
1060                 xen_store_evtchn = xen_start_info->store_evtchn;
1061                 xen_store_mfn = xen_start_info->store_mfn;
1062                 xen_store_interface = mfn_to_virt(xen_store_mfn);
1063 #else
1064                 xen_store_evtchn = hvm_get_parameter(HVM_PARAM_STORE_EVTCHN);
1065                 xen_store_mfn = hvm_get_parameter(HVM_PARAM_STORE_PFN);
1066                 xen_store_interface = ioremap(xen_store_mfn << PAGE_SHIFT,
1067                                               PAGE_SIZE);
1068 #endif
1069         }
1070
1071
1072         xenbus_dev_init();
1073
1074         /* Initialize the interface to xenstore. */
1075         err = xs_init();
1076         if (err) {
1077                 printk(KERN_WARNING
1078                        "XENBUS: Error initializing xenstore comms: %i\n", err);
1079                 goto err;
1080         }
1081
1082         /* Register ourselves with the kernel device subsystem */
1083         err = device_register(&xenbus_frontend.dev);
1084         if (err)
1085                 goto err;
1086         err = device_register(&xenbus_backend.dev);
1087         if (err)
1088                 goto err;
1089
1090         if (!is_initial_xendomain())
1091                 xenbus_probe(NULL);
1092
1093         return 0;
1094
1095  err:
1096         if (page)
1097                 free_page(page);
1098
1099         /*
1100          * Do not unregister the xenbus front/backend buses here. The buses
1101          * must exist because front/backend drivers will use them when they are
1102          * registered.
1103          */
1104  err_nomem:
1105         bus_unregister(&xenbus_frontend.bus);
1106  err_backend_bus:
1107         bus_unregister(&xenbus_frontend.bus);
1108  err_frontend_bus:
1109         return err;
1110 }
1111
1112 postcore_initcall(xenbus_probe_init);
1113
1114 MODULE_LICENSE("Dual BSD/GPL");
1115
1116
1117 static int is_disconnected_device(struct device *dev, void *data)
1118 {
1119         struct xenbus_device *xendev = to_xenbus_device(dev);
1120         struct device_driver *drv = data;
1121
1122         /*
1123          * A device with no driver will never connect. We care only about
1124          * devices which should currently be in the process of connecting.
1125          */
1126         if (!dev->driver)
1127                 return 0;
1128
1129         /* Is this search limited to a particular driver? */
1130         if (drv && (dev->driver != drv))
1131                 return 0;
1132
1133         return (xendev->state != XenbusStateConnected);
1134 }
1135
1136 static int exists_disconnected_device(struct device_driver *drv)
1137 {
1138         return bus_for_each_dev(&xenbus_frontend.bus, NULL, drv,
1139                                 is_disconnected_device);
1140 }
1141
1142 static int print_device_status(struct device *dev, void *data)
1143 {
1144         struct xenbus_device *xendev = to_xenbus_device(dev);
1145         struct device_driver *drv = data;
1146
1147         /* Is this operation limited to a particular driver? */
1148         if (drv && (dev->driver != drv))
1149                 return 0;
1150
1151         if (!dev->driver) {
1152                 /* Information only: is this too noisy? */
1153                 printk(KERN_INFO "XENBUS: Device with no driver: %s\n",
1154                        xendev->nodename);
1155         } else if (xendev->state != XenbusStateConnected) {
1156                 printk(KERN_WARNING "XENBUS: Timeout connecting "
1157                        "to device: %s (state %d)\n",
1158                        xendev->nodename, xendev->state);
1159         }
1160
1161         return 0;
1162 }
1163
1164 /* We only wait for device setup after most initcalls have run. */
1165 static int ready_to_wait_for_devices;
1166
1167 /*
1168  * On a 10 second timeout, wait for all devices currently configured.  We need
1169  * to do this to guarantee that the filesystems and / or network devices
1170  * needed for boot are available, before we can allow the boot to proceed.
1171  *
1172  * This needs to be on a late_initcall, to happen after the frontend device
1173  * drivers have been initialised, but before the root fs is mounted.
1174  *
1175  * A possible improvement here would be to have the tools add a per-device
1176  * flag to the store entry, indicating whether it is needed at boot time.
1177  * This would allow people who knew what they were doing to accelerate their
1178  * boot slightly, but of course needs tools or manual intervention to set up
1179  * those flags correctly.
1180  */
1181 static void wait_for_devices(struct xenbus_driver *xendrv)
1182 {
1183         unsigned long timeout = jiffies + 10*HZ;
1184         struct device_driver *drv = xendrv ? &xendrv->driver : NULL;
1185
1186         if (!ready_to_wait_for_devices || !is_running_on_xen())
1187                 return;
1188
1189         while (exists_disconnected_device(drv)) {
1190                 if (time_after(jiffies, timeout))
1191                         break;
1192                 schedule_timeout_interruptible(HZ/10);
1193         }
1194
1195         bus_for_each_dev(&xenbus_frontend.bus, NULL, drv,
1196                          print_device_status);
1197 }
1198
1199 #ifndef MODULE
1200 static int __init boot_wait_for_devices(void)
1201 {
1202         ready_to_wait_for_devices = 1;
1203         wait_for_devices(NULL);
1204         return 0;
1205 }
1206
1207 late_initcall(boot_wait_for_devices);
1208 #endif