Merge to Fedora kernel-2.6.18-1.2255_FC5-vs2.0.2.2-rc9 patched with stable patch...
[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         device_create_file(&xendev->dev, &dev_attr_nodename);
624         device_create_file(&xendev->dev, &dev_attr_devtype);
625
626         return 0;
627 fail:
628         kfree(xendev);
629         return err;
630 }
631
632 /* device/<typename>/<name> */
633 static int xenbus_probe_frontend(const char *type, const char *name)
634 {
635         char *nodename;
636         int err;
637
638         nodename = kasprintf(GFP_KERNEL, "%s/%s/%s", xenbus_frontend.root, type, name);
639         if (!nodename)
640                 return -ENOMEM;
641
642         DPRINTK("%s", nodename);
643
644         err = xenbus_probe_node(&xenbus_frontend, type, nodename);
645         kfree(nodename);
646         return err;
647 }
648
649 /* backend/<typename>/<frontend-uuid>/<name> */
650 static int xenbus_probe_backend_unit(const char *dir,
651                                      const char *type,
652                                      const char *name)
653 {
654         char *nodename;
655         int err;
656
657         nodename = kasprintf(GFP_KERNEL, "%s/%s", dir, name);
658         if (!nodename)
659                 return -ENOMEM;
660
661         DPRINTK("%s\n", nodename);
662
663         err = xenbus_probe_node(&xenbus_backend, type, nodename);
664         kfree(nodename);
665         return err;
666 }
667
668 /* backend/<typename>/<frontend-domid> */
669 static int xenbus_probe_backend(const char *type, const char *domid)
670 {
671         char *nodename;
672         int err = 0;
673         char **dir;
674         unsigned int i, dir_n = 0;
675
676         DPRINTK("");
677
678         nodename = kasprintf(GFP_KERNEL, "%s/%s/%s", xenbus_backend.root, type, domid);
679         if (!nodename)
680                 return -ENOMEM;
681
682         dir = xenbus_directory(XBT_NIL, nodename, "", &dir_n);
683         if (IS_ERR(dir)) {
684                 kfree(nodename);
685                 return PTR_ERR(dir);
686         }
687
688         for (i = 0; i < dir_n; i++) {
689                 err = xenbus_probe_backend_unit(nodename, type, dir[i]);
690                 if (err)
691                         break;
692         }
693         kfree(dir);
694         kfree(nodename);
695         return err;
696 }
697
698 static int xenbus_probe_device_type(struct xen_bus_type *bus, const char *type)
699 {
700         int err = 0;
701         char **dir;
702         unsigned int dir_n = 0;
703         int i;
704
705         dir = xenbus_directory(XBT_NIL, bus->root, type, &dir_n);
706         if (IS_ERR(dir))
707                 return PTR_ERR(dir);
708
709         for (i = 0; i < dir_n; i++) {
710                 err = bus->probe(type, dir[i]);
711                 if (err)
712                         break;
713         }
714         kfree(dir);
715         return err;
716 }
717
718 static int xenbus_probe_devices(struct xen_bus_type *bus)
719 {
720         int err = 0;
721         char **dir;
722         unsigned int i, dir_n;
723
724         dir = xenbus_directory(XBT_NIL, bus->root, "", &dir_n);
725         if (IS_ERR(dir))
726                 return PTR_ERR(dir);
727
728         for (i = 0; i < dir_n; i++) {
729                 err = xenbus_probe_device_type(bus, dir[i]);
730                 if (err)
731                         break;
732         }
733         kfree(dir);
734         return err;
735 }
736
737 static unsigned int char_count(const char *str, char c)
738 {
739         unsigned int i, ret = 0;
740
741         for (i = 0; str[i]; i++)
742                 if (str[i] == c)
743                         ret++;
744         return ret;
745 }
746
747 static int strsep_len(const char *str, char c, unsigned int len)
748 {
749         unsigned int i;
750
751         for (i = 0; str[i]; i++)
752                 if (str[i] == c) {
753                         if (len == 0)
754                                 return i;
755                         len--;
756                 }
757         return (len == 0) ? i : -ERANGE;
758 }
759
760 static void dev_changed(const char *node, struct xen_bus_type *bus)
761 {
762         int exists, rootlen;
763         struct xenbus_device *dev;
764         char type[BUS_ID_SIZE];
765         const char *p, *root;
766
767         if (char_count(node, '/') < 2)
768                 return;
769
770         exists = xenbus_exists(XBT_NIL, node, "");
771         if (!exists) {
772                 xenbus_cleanup_devices(node, &bus->bus);
773                 return;
774         }
775
776         /* backend/<type>/... or device/<type>/... */
777         p = strchr(node, '/') + 1;
778         snprintf(type, BUS_ID_SIZE, "%.*s", (int)strcspn(p, "/"), p);
779         type[BUS_ID_SIZE-1] = '\0';
780
781         rootlen = strsep_len(node, '/', bus->levels);
782         if (rootlen < 0)
783                 return;
784         root = kasprintf(GFP_KERNEL, "%.*s", rootlen, node);
785         if (!root)
786                 return;
787
788         dev = xenbus_device_find(root, &bus->bus);
789         if (!dev)
790                 xenbus_probe_node(bus, type, root);
791         else
792                 put_device(&dev->dev);
793
794         kfree(root);
795 }
796
797 static void frontend_changed(struct xenbus_watch *watch,
798                              const char **vec, unsigned int len)
799 {
800         DPRINTK("");
801
802         dev_changed(vec[XS_WATCH_PATH], &xenbus_frontend);
803 }
804
805 static void backend_changed(struct xenbus_watch *watch,
806                             const char **vec, unsigned int len)
807 {
808         DPRINTK("");
809
810         dev_changed(vec[XS_WATCH_PATH], &xenbus_backend);
811 }
812
813 /* We watch for devices appearing and vanishing. */
814 static struct xenbus_watch fe_watch = {
815         .node = "device",
816         .callback = frontend_changed,
817 };
818
819 static struct xenbus_watch be_watch = {
820         .node = "backend",
821         .callback = backend_changed,
822 };
823
824 static int suspend_dev(struct device *dev, void *data)
825 {
826         int err = 0;
827         struct xenbus_driver *drv;
828         struct xenbus_device *xdev;
829
830         DPRINTK("");
831
832         if (dev->driver == NULL)
833                 return 0;
834         drv = to_xenbus_driver(dev->driver);
835         xdev = container_of(dev, struct xenbus_device, dev);
836         if (drv->suspend)
837                 err = drv->suspend(xdev);
838         if (err)
839                 printk(KERN_WARNING
840                        "xenbus: suspend %s failed: %i\n", dev->bus_id, err);
841         return 0;
842 }
843
844 static int resume_dev(struct device *dev, void *data)
845 {
846         int err;
847         struct xenbus_driver *drv;
848         struct xenbus_device *xdev;
849
850         DPRINTK("");
851
852         if (dev->driver == NULL)
853                 return 0;
854
855         drv = to_xenbus_driver(dev->driver);
856         xdev = container_of(dev, struct xenbus_device, dev);
857
858         err = talk_to_otherend(xdev);
859         if (err) {
860                 printk(KERN_WARNING
861                        "xenbus: resume (talk_to_otherend) %s failed: %i\n",
862                        dev->bus_id, err);
863                 return err;
864         }
865
866         xdev->state = XenbusStateInitialising;
867
868         if (drv->resume) {
869                 err = drv->resume(xdev);
870                 if (err) { 
871                         printk(KERN_WARNING
872                                "xenbus: resume %s failed: %i\n", 
873                                dev->bus_id, err);
874                         return err;
875                 }
876         }
877
878         err = watch_otherend(xdev);
879         if (err) {
880                 printk(KERN_WARNING
881                        "xenbus_probe: resume (watch_otherend) %s failed: "
882                        "%d.\n", dev->bus_id, err);
883                 return err;
884         }
885
886         return 0;
887 }
888
889 void xenbus_suspend(void)
890 {
891         DPRINTK("");
892
893         bus_for_each_dev(&xenbus_frontend.bus, NULL, NULL, suspend_dev);
894         bus_for_each_dev(&xenbus_backend.bus, NULL, NULL, suspend_dev);
895         xs_suspend();
896 }
897 EXPORT_SYMBOL_GPL(xenbus_suspend);
898
899 void xenbus_resume(void)
900 {
901         xb_init_comms();
902         xs_resume();
903         bus_for_each_dev(&xenbus_frontend.bus, NULL, NULL, resume_dev);
904         bus_for_each_dev(&xenbus_backend.bus, NULL, NULL, resume_dev);
905 }
906 EXPORT_SYMBOL_GPL(xenbus_resume);
907
908
909 /* A flag to determine if xenstored is 'ready' (i.e. has started) */
910 int xenstored_ready = 0;
911
912
913 int register_xenstore_notifier(struct notifier_block *nb)
914 {
915         int ret = 0;
916
917         if (xenstored_ready > 0)
918                 ret = nb->notifier_call(nb, 0, NULL);
919         else
920                 blocking_notifier_chain_register(&xenstore_notifier_list, nb);
921
922         return ret;
923 }
924 EXPORT_SYMBOL_GPL(register_xenstore_notifier);
925
926 void unregister_xenstore_notifier(struct notifier_block *nb)
927 {
928         blocking_notifier_chain_unregister(&xenstore_notifier_list, nb);
929 }
930 EXPORT_SYMBOL_GPL(unregister_xenstore_notifier);
931
932
933 void xenbus_probe(void *unused)
934 {
935         BUG_ON((xenstored_ready <= 0));
936
937         /* Enumerate devices in xenstore. */
938         xenbus_probe_devices(&xenbus_frontend);
939         xenbus_probe_devices(&xenbus_backend);
940
941         /* Watch for changes. */
942         register_xenbus_watch(&fe_watch);
943         register_xenbus_watch(&be_watch);
944
945         /* Notify others that xenstore is up */
946         blocking_notifier_call_chain(&xenstore_notifier_list, 0, NULL);
947 }
948
949
950 #ifdef CONFIG_PROC_FS
951 static struct file_operations xsd_kva_fops;
952 static struct proc_dir_entry *xsd_kva_intf;
953 static struct proc_dir_entry *xsd_port_intf;
954
955 static int xsd_kva_mmap(struct file *file, struct vm_area_struct *vma)
956 {
957         size_t size = vma->vm_end - vma->vm_start;
958
959         if ((size > PAGE_SIZE) || (vma->vm_pgoff != 0))
960                 return -EINVAL;
961
962         if (remap_pfn_range(vma, vma->vm_start, mfn_to_pfn(xen_store_mfn),
963                             size, vma->vm_page_prot))
964                 return -EAGAIN;
965
966         return 0;
967 }
968
969 static int xsd_kva_read(char *page, char **start, off_t off,
970                         int count, int *eof, void *data)
971 {
972         int len;
973
974         len  = sprintf(page, "0x%p", xen_store_interface);
975         *eof = 1;
976         return len;
977 }
978
979 static int xsd_port_read(char *page, char **start, off_t off,
980                          int count, int *eof, void *data)
981 {
982         int len;
983
984         len  = sprintf(page, "%d", xen_store_evtchn);
985         *eof = 1;
986         return len;
987 }
988 #endif
989
990 static int __init xenbus_probe_init(void)
991 {
992         int err = 0;
993         unsigned long page = 0;
994
995         DPRINTK("");
996
997         if (!is_running_on_xen())
998                 return -ENODEV;
999
1000         /* Register ourselves with the kernel bus subsystem */
1001         bus_register(&xenbus_frontend.bus);
1002         bus_register(&xenbus_backend.bus);
1003
1004         /*
1005          * Domain0 doesn't have a store_evtchn or store_mfn yet.
1006          */
1007         if (is_initial_xendomain()) {
1008                 struct evtchn_alloc_unbound alloc_unbound;
1009
1010                 /* Allocate page. */
1011                 page = get_zeroed_page(GFP_KERNEL);
1012                 if (!page)
1013                         return -ENOMEM;
1014
1015                 xen_store_mfn = xen_start_info->store_mfn =
1016                         pfn_to_mfn(virt_to_phys((void *)page) >>
1017                                    PAGE_SHIFT);
1018
1019                 /* Next allocate a local port which xenstored can bind to */
1020                 alloc_unbound.dom        = DOMID_SELF;
1021                 alloc_unbound.remote_dom = 0;
1022
1023                 err = HYPERVISOR_event_channel_op(EVTCHNOP_alloc_unbound,
1024                                                   &alloc_unbound);
1025                 if (err == -ENOSYS)
1026                         goto err;
1027                 BUG_ON(err);
1028                 xen_store_evtchn = xen_start_info->store_evtchn =
1029                         alloc_unbound.port;
1030
1031 #ifdef CONFIG_PROC_FS
1032                 /* And finally publish the above info in /proc/xen */
1033                 xsd_kva_intf = create_xen_proc_entry("xsd_kva", 0600);
1034                 if (xsd_kva_intf) {
1035                         memcpy(&xsd_kva_fops, xsd_kva_intf->proc_fops,
1036                                sizeof(xsd_kva_fops));
1037                         xsd_kva_fops.mmap = xsd_kva_mmap;
1038                         xsd_kva_intf->proc_fops = &xsd_kva_fops;
1039                         xsd_kva_intf->read_proc = xsd_kva_read;
1040                 }
1041                 xsd_port_intf = create_xen_proc_entry("xsd_port", 0400);
1042                 if (xsd_port_intf)
1043                         xsd_port_intf->read_proc = xsd_port_read;
1044 #endif
1045                 xen_store_interface = mfn_to_virt(xen_store_mfn);
1046         } else {
1047                 xenstored_ready = 1;
1048 #ifdef CONFIG_XEN
1049                 xen_store_evtchn = xen_start_info->store_evtchn;
1050                 xen_store_mfn = xen_start_info->store_mfn;
1051                 xen_store_interface = mfn_to_virt(xen_store_mfn);
1052 #else
1053                 xen_store_evtchn = hvm_get_parameter(HVM_PARAM_STORE_EVTCHN);
1054                 xen_store_mfn = hvm_get_parameter(HVM_PARAM_STORE_PFN);
1055                 xen_store_interface = ioremap(xen_store_mfn << PAGE_SHIFT,
1056                                               PAGE_SIZE);
1057 #endif
1058         }
1059
1060
1061         xenbus_dev_init();
1062
1063         /* Initialize the interface to xenstore. */
1064         err = xs_init();
1065         if (err) {
1066                 printk(KERN_WARNING
1067                        "XENBUS: Error initializing xenstore comms: %i\n", err);
1068                 goto err;
1069         }
1070
1071         /* Register ourselves with the kernel device subsystem */
1072         device_register(&xenbus_frontend.dev);
1073         device_register(&xenbus_backend.dev);
1074
1075         if (!is_initial_xendomain())
1076                 xenbus_probe(NULL);
1077
1078         return 0;
1079
1080  err:
1081         if (page)
1082                 free_page(page);
1083
1084         /*
1085          * Do not unregister the xenbus front/backend buses here. The buses
1086          * must exist because front/backend drivers will use them when they are
1087          * registered.
1088          */
1089
1090         return err;
1091 }
1092
1093 postcore_initcall(xenbus_probe_init);
1094
1095 MODULE_LICENSE("Dual BSD/GPL");
1096
1097
1098 static int is_disconnected_device(struct device *dev, void *data)
1099 {
1100         struct xenbus_device *xendev = to_xenbus_device(dev);
1101         struct device_driver *drv = data;
1102
1103         /*
1104          * A device with no driver will never connect. We care only about
1105          * devices which should currently be in the process of connecting.
1106          */
1107         if (!dev->driver)
1108                 return 0;
1109
1110         /* Is this search limited to a particular driver? */
1111         if (drv && (dev->driver != drv))
1112                 return 0;
1113
1114         return (xendev->state != XenbusStateConnected);
1115 }
1116
1117 static int exists_disconnected_device(struct device_driver *drv)
1118 {
1119         return bus_for_each_dev(&xenbus_frontend.bus, NULL, drv,
1120                                 is_disconnected_device);
1121 }
1122
1123 static int print_device_status(struct device *dev, void *data)
1124 {
1125         struct xenbus_device *xendev = to_xenbus_device(dev);
1126         struct device_driver *drv = data;
1127
1128         /* Is this operation limited to a particular driver? */
1129         if (drv && (dev->driver != drv))
1130                 return 0;
1131
1132         if (!dev->driver) {
1133                 /* Information only: is this too noisy? */
1134                 printk(KERN_INFO "XENBUS: Device with no driver: %s\n",
1135                        xendev->nodename);
1136         } else if (xendev->state != XenbusStateConnected) {
1137                 printk(KERN_WARNING "XENBUS: Timeout connecting "
1138                        "to device: %s (state %d)\n",
1139                        xendev->nodename, xendev->state);
1140         }
1141
1142         return 0;
1143 }
1144
1145 /* We only wait for device setup after most initcalls have run. */
1146 static int ready_to_wait_for_devices;
1147
1148 /*
1149  * On a 10 second timeout, wait for all devices currently configured.  We need
1150  * to do this to guarantee that the filesystems and / or network devices
1151  * needed for boot are available, before we can allow the boot to proceed.
1152  *
1153  * This needs to be on a late_initcall, to happen after the frontend device
1154  * drivers have been initialised, but before the root fs is mounted.
1155  *
1156  * A possible improvement here would be to have the tools add a per-device
1157  * flag to the store entry, indicating whether it is needed at boot time.
1158  * This would allow people who knew what they were doing to accelerate their
1159  * boot slightly, but of course needs tools or manual intervention to set up
1160  * those flags correctly.
1161  */
1162 static void wait_for_devices(struct xenbus_driver *xendrv)
1163 {
1164         unsigned long timeout = jiffies + 10*HZ;
1165         struct device_driver *drv = xendrv ? &xendrv->driver : NULL;
1166
1167         if (!ready_to_wait_for_devices || !is_running_on_xen())
1168                 return;
1169
1170         while (exists_disconnected_device(drv)) {
1171                 if (time_after(jiffies, timeout))
1172                         break;
1173                 schedule_timeout_interruptible(HZ/10);
1174         }
1175
1176         bus_for_each_dev(&xenbus_frontend.bus, NULL, drv,
1177                          print_device_status);
1178 }
1179
1180 #ifndef MODULE
1181 static int __init boot_wait_for_devices(void)
1182 {
1183         ready_to_wait_for_devices = 1;
1184         wait_for_devices(NULL);
1185         return 0;
1186 }
1187
1188 late_initcall(boot_wait_for_devices);
1189 #endif