GNU Linux-libre 4.19.286-gnu1
[releases.git] / drivers / block / xen-blkback / xenbus.c
1 /*  Xenbus code for blkif backend
2     Copyright (C) 2005 Rusty Russell <rusty@rustcorp.com.au>
3     Copyright (C) 2005 XenSource Ltd
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15 */
16
17 #define pr_fmt(fmt) "xen-blkback: " fmt
18
19 #include <stdarg.h>
20 #include <linux/module.h>
21 #include <linux/kthread.h>
22 #include <xen/events.h>
23 #include <xen/grant_table.h>
24 #include "common.h"
25
26 /* On the XenBus the max length of 'ring-ref%u'. */
27 #define RINGREF_NAME_LEN (20)
28
29 struct backend_info {
30         struct xenbus_device    *dev;
31         struct xen_blkif        *blkif;
32         struct xenbus_watch     backend_watch;
33         unsigned                major;
34         unsigned                minor;
35         char                    *mode;
36 };
37
38 static struct kmem_cache *xen_blkif_cachep;
39 static void connect(struct backend_info *);
40 static int connect_ring(struct backend_info *);
41 static void backend_changed(struct xenbus_watch *, const char *,
42                             const char *);
43 static void xen_blkif_free(struct xen_blkif *blkif);
44 static void xen_vbd_free(struct xen_vbd *vbd);
45
46 struct xenbus_device *xen_blkbk_xenbus(struct backend_info *be)
47 {
48         return be->dev;
49 }
50
51 /*
52  * The last request could free the device from softirq context and
53  * xen_blkif_free() can sleep.
54  */
55 static void xen_blkif_deferred_free(struct work_struct *work)
56 {
57         struct xen_blkif *blkif;
58
59         blkif = container_of(work, struct xen_blkif, free_work);
60         xen_blkif_free(blkif);
61 }
62
63 static int blkback_name(struct xen_blkif *blkif, char *buf)
64 {
65         char *devpath, *devname;
66         struct xenbus_device *dev = blkif->be->dev;
67
68         devpath = xenbus_read(XBT_NIL, dev->nodename, "dev", NULL);
69         if (IS_ERR(devpath))
70                 return PTR_ERR(devpath);
71
72         devname = strstr(devpath, "/dev/");
73         if (devname != NULL)
74                 devname += strlen("/dev/");
75         else
76                 devname  = devpath;
77
78         snprintf(buf, TASK_COMM_LEN, "%d.%s", blkif->domid, devname);
79         kfree(devpath);
80
81         return 0;
82 }
83
84 static void xen_update_blkif_status(struct xen_blkif *blkif)
85 {
86         int err;
87         char name[TASK_COMM_LEN];
88         struct xen_blkif_ring *ring;
89         int i;
90
91         /* Not ready to connect? */
92         if (!blkif->rings || !blkif->rings[0].irq || !blkif->vbd.bdev)
93                 return;
94
95         /* Already connected? */
96         if (blkif->be->dev->state == XenbusStateConnected)
97                 return;
98
99         /* Attempt to connect: exit if we fail to. */
100         connect(blkif->be);
101         if (blkif->be->dev->state != XenbusStateConnected)
102                 return;
103
104         err = blkback_name(blkif, name);
105         if (err) {
106                 xenbus_dev_error(blkif->be->dev, err, "get blkback dev name");
107                 return;
108         }
109
110         err = filemap_write_and_wait(blkif->vbd.bdev->bd_inode->i_mapping);
111         if (err) {
112                 xenbus_dev_error(blkif->be->dev, err, "block flush");
113                 return;
114         }
115         invalidate_inode_pages2(blkif->vbd.bdev->bd_inode->i_mapping);
116
117         for (i = 0; i < blkif->nr_rings; i++) {
118                 ring = &blkif->rings[i];
119                 ring->xenblkd = kthread_run(xen_blkif_schedule, ring, "%s-%d", name, i);
120                 if (IS_ERR(ring->xenblkd)) {
121                         err = PTR_ERR(ring->xenblkd);
122                         ring->xenblkd = NULL;
123                         xenbus_dev_fatal(blkif->be->dev, err,
124                                         "start %s-%d xenblkd", name, i);
125                         goto out;
126                 }
127         }
128         return;
129
130 out:
131         while (--i >= 0) {
132                 ring = &blkif->rings[i];
133                 kthread_stop(ring->xenblkd);
134         }
135         return;
136 }
137
138 static int xen_blkif_alloc_rings(struct xen_blkif *blkif)
139 {
140         unsigned int r;
141
142         blkif->rings = kcalloc(blkif->nr_rings, sizeof(struct xen_blkif_ring),
143                                GFP_KERNEL);
144         if (!blkif->rings)
145                 return -ENOMEM;
146
147         for (r = 0; r < blkif->nr_rings; r++) {
148                 struct xen_blkif_ring *ring = &blkif->rings[r];
149
150                 spin_lock_init(&ring->blk_ring_lock);
151                 init_waitqueue_head(&ring->wq);
152                 INIT_LIST_HEAD(&ring->pending_free);
153                 INIT_LIST_HEAD(&ring->persistent_purge_list);
154                 INIT_WORK(&ring->persistent_purge_work, xen_blkbk_unmap_purged_grants);
155                 spin_lock_init(&ring->free_pages_lock);
156                 INIT_LIST_HEAD(&ring->free_pages);
157
158                 spin_lock_init(&ring->pending_free_lock);
159                 init_waitqueue_head(&ring->pending_free_wq);
160                 init_waitqueue_head(&ring->shutdown_wq);
161                 ring->blkif = blkif;
162                 ring->st_print = jiffies;
163                 ring->active = true;
164         }
165
166         return 0;
167 }
168
169 static struct xen_blkif *xen_blkif_alloc(domid_t domid)
170 {
171         struct xen_blkif *blkif;
172
173         BUILD_BUG_ON(MAX_INDIRECT_PAGES > BLKIF_MAX_INDIRECT_PAGES_PER_REQUEST);
174
175         blkif = kmem_cache_zalloc(xen_blkif_cachep, GFP_KERNEL);
176         if (!blkif)
177                 return ERR_PTR(-ENOMEM);
178
179         blkif->domid = domid;
180         atomic_set(&blkif->refcnt, 1);
181         init_completion(&blkif->drain_complete);
182
183         /*
184          * Because freeing back to the cache may be deferred, it is not
185          * safe to unload the module (and hence destroy the cache) until
186          * this has completed. To prevent premature unloading, take an
187          * extra module reference here and release only when the object
188          * has been freed back to the cache.
189          */
190         __module_get(THIS_MODULE);
191         INIT_WORK(&blkif->free_work, xen_blkif_deferred_free);
192
193         return blkif;
194 }
195
196 static int xen_blkif_map(struct xen_blkif_ring *ring, grant_ref_t *gref,
197                          unsigned int nr_grefs, unsigned int evtchn)
198 {
199         int err;
200         struct xen_blkif *blkif = ring->blkif;
201
202         /* Already connected through? */
203         if (ring->irq)
204                 return 0;
205
206         err = xenbus_map_ring_valloc(blkif->be->dev, gref, nr_grefs,
207                                      &ring->blk_ring);
208         if (err < 0)
209                 return err;
210
211         switch (blkif->blk_protocol) {
212         case BLKIF_PROTOCOL_NATIVE:
213         {
214                 struct blkif_sring *sring;
215                 sring = (struct blkif_sring *)ring->blk_ring;
216                 BACK_RING_INIT(&ring->blk_rings.native, sring,
217                                XEN_PAGE_SIZE * nr_grefs);
218                 break;
219         }
220         case BLKIF_PROTOCOL_X86_32:
221         {
222                 struct blkif_x86_32_sring *sring_x86_32;
223                 sring_x86_32 = (struct blkif_x86_32_sring *)ring->blk_ring;
224                 BACK_RING_INIT(&ring->blk_rings.x86_32, sring_x86_32,
225                                XEN_PAGE_SIZE * nr_grefs);
226                 break;
227         }
228         case BLKIF_PROTOCOL_X86_64:
229         {
230                 struct blkif_x86_64_sring *sring_x86_64;
231                 sring_x86_64 = (struct blkif_x86_64_sring *)ring->blk_ring;
232                 BACK_RING_INIT(&ring->blk_rings.x86_64, sring_x86_64,
233                                XEN_PAGE_SIZE * nr_grefs);
234                 break;
235         }
236         default:
237                 BUG();
238         }
239
240         err = bind_interdomain_evtchn_to_irqhandler_lateeoi(blkif->domid,
241                         evtchn, xen_blkif_be_int, 0, "blkif-backend", ring);
242         if (err < 0) {
243                 xenbus_unmap_ring_vfree(blkif->be->dev, ring->blk_ring);
244                 ring->blk_rings.common.sring = NULL;
245                 return err;
246         }
247         ring->irq = err;
248
249         return 0;
250 }
251
252 static int xen_blkif_disconnect(struct xen_blkif *blkif)
253 {
254         struct pending_req *req, *n;
255         unsigned int j, r;
256         bool busy = false;
257
258         for (r = 0; r < blkif->nr_rings; r++) {
259                 struct xen_blkif_ring *ring = &blkif->rings[r];
260                 unsigned int i = 0;
261
262                 if (!ring->active)
263                         continue;
264
265                 if (ring->xenblkd) {
266                         kthread_stop(ring->xenblkd);
267                         ring->xenblkd = NULL;
268                         wake_up(&ring->shutdown_wq);
269                 }
270
271                 /* The above kthread_stop() guarantees that at this point we
272                  * don't have any discard_io or other_io requests. So, checking
273                  * for inflight IO is enough.
274                  */
275                 if (atomic_read(&ring->inflight) > 0) {
276                         busy = true;
277                         continue;
278                 }
279
280                 if (ring->irq) {
281                         unbind_from_irqhandler(ring->irq, ring);
282                         ring->irq = 0;
283                 }
284
285                 if (ring->blk_rings.common.sring) {
286                         xenbus_unmap_ring_vfree(blkif->be->dev, ring->blk_ring);
287                         ring->blk_rings.common.sring = NULL;
288                 }
289
290                 /* Remove all persistent grants and the cache of ballooned pages. */
291                 xen_blkbk_free_caches(ring);
292
293                 /* Check that there is no request in use */
294                 list_for_each_entry_safe(req, n, &ring->pending_free, free_list) {
295                         list_del(&req->free_list);
296
297                         for (j = 0; j < MAX_INDIRECT_SEGMENTS; j++)
298                                 kfree(req->segments[j]);
299
300                         for (j = 0; j < MAX_INDIRECT_PAGES; j++)
301                                 kfree(req->indirect_pages[j]);
302
303                         kfree(req);
304                         i++;
305                 }
306
307                 BUG_ON(atomic_read(&ring->persistent_gnt_in_use) != 0);
308                 BUG_ON(!list_empty(&ring->persistent_purge_list));
309                 BUG_ON(!RB_EMPTY_ROOT(&ring->persistent_gnts));
310                 BUG_ON(!list_empty(&ring->free_pages));
311                 BUG_ON(ring->free_pages_num != 0);
312                 BUG_ON(ring->persistent_gnt_c != 0);
313                 WARN_ON(i != (XEN_BLKIF_REQS_PER_PAGE * blkif->nr_ring_pages));
314                 ring->active = false;
315         }
316         if (busy)
317                 return -EBUSY;
318
319         blkif->nr_ring_pages = 0;
320         /*
321          * blkif->rings was allocated in connect_ring, so we should free it in
322          * here.
323          */
324         kfree(blkif->rings);
325         blkif->rings = NULL;
326         blkif->nr_rings = 0;
327
328         return 0;
329 }
330
331 static void xen_blkif_free(struct xen_blkif *blkif)
332 {
333         WARN_ON(xen_blkif_disconnect(blkif));
334         xen_vbd_free(&blkif->vbd);
335         kfree(blkif->be->mode);
336         kfree(blkif->be);
337
338         /* Make sure everything is drained before shutting down */
339         kmem_cache_free(xen_blkif_cachep, blkif);
340         module_put(THIS_MODULE);
341 }
342
343 int __init xen_blkif_interface_init(void)
344 {
345         xen_blkif_cachep = kmem_cache_create("blkif_cache",
346                                              sizeof(struct xen_blkif),
347                                              0, 0, NULL);
348         if (!xen_blkif_cachep)
349                 return -ENOMEM;
350
351         return 0;
352 }
353
354 /*
355  *  sysfs interface for VBD I/O requests
356  */
357
358 #define VBD_SHOW_ALLRING(name, format)                                  \
359         static ssize_t show_##name(struct device *_dev,                 \
360                                    struct device_attribute *attr,       \
361                                    char *buf)                           \
362         {                                                               \
363                 struct xenbus_device *dev = to_xenbus_device(_dev);     \
364                 struct backend_info *be = dev_get_drvdata(&dev->dev);   \
365                 struct xen_blkif *blkif = be->blkif;                    \
366                 unsigned int i;                                         \
367                 unsigned long long result = 0;                          \
368                                                                         \
369                 if (!blkif->rings)                              \
370                         goto out;                                       \
371                                                                         \
372                 for (i = 0; i < blkif->nr_rings; i++) {         \
373                         struct xen_blkif_ring *ring = &blkif->rings[i]; \
374                                                                         \
375                         result += ring->st_##name;                      \
376                 }                                                       \
377                                                                         \
378 out:                                                                    \
379                 return sprintf(buf, format, result);                    \
380         }                                                               \
381         static DEVICE_ATTR(name, 0444, show_##name, NULL)
382
383 VBD_SHOW_ALLRING(oo_req,  "%llu\n");
384 VBD_SHOW_ALLRING(rd_req,  "%llu\n");
385 VBD_SHOW_ALLRING(wr_req,  "%llu\n");
386 VBD_SHOW_ALLRING(f_req,  "%llu\n");
387 VBD_SHOW_ALLRING(ds_req,  "%llu\n");
388 VBD_SHOW_ALLRING(rd_sect, "%llu\n");
389 VBD_SHOW_ALLRING(wr_sect, "%llu\n");
390
391 static struct attribute *xen_vbdstat_attrs[] = {
392         &dev_attr_oo_req.attr,
393         &dev_attr_rd_req.attr,
394         &dev_attr_wr_req.attr,
395         &dev_attr_f_req.attr,
396         &dev_attr_ds_req.attr,
397         &dev_attr_rd_sect.attr,
398         &dev_attr_wr_sect.attr,
399         NULL
400 };
401
402 static const struct attribute_group xen_vbdstat_group = {
403         .name = "statistics",
404         .attrs = xen_vbdstat_attrs,
405 };
406
407 #define VBD_SHOW(name, format, args...)                                 \
408         static ssize_t show_##name(struct device *_dev,                 \
409                                    struct device_attribute *attr,       \
410                                    char *buf)                           \
411         {                                                               \
412                 struct xenbus_device *dev = to_xenbus_device(_dev);     \
413                 struct backend_info *be = dev_get_drvdata(&dev->dev);   \
414                                                                         \
415                 return sprintf(buf, format, ##args);                    \
416         }                                                               \
417         static DEVICE_ATTR(name, 0444, show_##name, NULL)
418
419 VBD_SHOW(physical_device, "%x:%x\n", be->major, be->minor);
420 VBD_SHOW(mode, "%s\n", be->mode);
421
422 static int xenvbd_sysfs_addif(struct xenbus_device *dev)
423 {
424         int error;
425
426         error = device_create_file(&dev->dev, &dev_attr_physical_device);
427         if (error)
428                 goto fail1;
429
430         error = device_create_file(&dev->dev, &dev_attr_mode);
431         if (error)
432                 goto fail2;
433
434         error = sysfs_create_group(&dev->dev.kobj, &xen_vbdstat_group);
435         if (error)
436                 goto fail3;
437
438         return 0;
439
440 fail3:  sysfs_remove_group(&dev->dev.kobj, &xen_vbdstat_group);
441 fail2:  device_remove_file(&dev->dev, &dev_attr_mode);
442 fail1:  device_remove_file(&dev->dev, &dev_attr_physical_device);
443         return error;
444 }
445
446 static void xenvbd_sysfs_delif(struct xenbus_device *dev)
447 {
448         sysfs_remove_group(&dev->dev.kobj, &xen_vbdstat_group);
449         device_remove_file(&dev->dev, &dev_attr_mode);
450         device_remove_file(&dev->dev, &dev_attr_physical_device);
451 }
452
453
454 static void xen_vbd_free(struct xen_vbd *vbd)
455 {
456         if (vbd->bdev)
457                 blkdev_put(vbd->bdev, vbd->readonly ? FMODE_READ : FMODE_WRITE);
458         vbd->bdev = NULL;
459 }
460
461 static int xen_vbd_create(struct xen_blkif *blkif, blkif_vdev_t handle,
462                           unsigned major, unsigned minor, int readonly,
463                           int cdrom)
464 {
465         struct xen_vbd *vbd;
466         struct block_device *bdev;
467         struct request_queue *q;
468
469         vbd = &blkif->vbd;
470         vbd->handle   = handle;
471         vbd->readonly = readonly;
472         vbd->type     = 0;
473
474         vbd->pdevice  = MKDEV(major, minor);
475
476         bdev = blkdev_get_by_dev(vbd->pdevice, vbd->readonly ?
477                                  FMODE_READ : FMODE_WRITE, NULL);
478
479         if (IS_ERR(bdev)) {
480                 pr_warn("xen_vbd_create: device %08x could not be opened\n",
481                         vbd->pdevice);
482                 return -ENOENT;
483         }
484
485         vbd->bdev = bdev;
486         if (vbd->bdev->bd_disk == NULL) {
487                 pr_warn("xen_vbd_create: device %08x doesn't exist\n",
488                         vbd->pdevice);
489                 xen_vbd_free(vbd);
490                 return -ENOENT;
491         }
492         vbd->size = vbd_sz(vbd);
493
494         if (vbd->bdev->bd_disk->flags & GENHD_FL_CD || cdrom)
495                 vbd->type |= VDISK_CDROM;
496         if (vbd->bdev->bd_disk->flags & GENHD_FL_REMOVABLE)
497                 vbd->type |= VDISK_REMOVABLE;
498
499         q = bdev_get_queue(bdev);
500         if (q && test_bit(QUEUE_FLAG_WC, &q->queue_flags))
501                 vbd->flush_support = true;
502
503         if (q && blk_queue_secure_erase(q))
504                 vbd->discard_secure = true;
505
506         pr_debug("Successful creation of handle=%04x (dom=%u)\n",
507                 handle, blkif->domid);
508         return 0;
509 }
510 static int xen_blkbk_remove(struct xenbus_device *dev)
511 {
512         struct backend_info *be = dev_get_drvdata(&dev->dev);
513
514         pr_debug("%s %p %d\n", __func__, dev, dev->otherend_id);
515
516         if (be->major || be->minor)
517                 xenvbd_sysfs_delif(dev);
518
519         if (be->backend_watch.node) {
520                 unregister_xenbus_watch(&be->backend_watch);
521                 kfree(be->backend_watch.node);
522                 be->backend_watch.node = NULL;
523         }
524
525         dev_set_drvdata(&dev->dev, NULL);
526
527         if (be->blkif) {
528                 xen_blkif_disconnect(be->blkif);
529
530                 /* Put the reference we set in xen_blkif_alloc(). */
531                 xen_blkif_put(be->blkif);
532         }
533
534         return 0;
535 }
536
537 int xen_blkbk_flush_diskcache(struct xenbus_transaction xbt,
538                               struct backend_info *be, int state)
539 {
540         struct xenbus_device *dev = be->dev;
541         int err;
542
543         err = xenbus_printf(xbt, dev->nodename, "feature-flush-cache",
544                             "%d", state);
545         if (err)
546                 dev_warn(&dev->dev, "writing feature-flush-cache (%d)", err);
547
548         return err;
549 }
550
551 static void xen_blkbk_discard(struct xenbus_transaction xbt, struct backend_info *be)
552 {
553         struct xenbus_device *dev = be->dev;
554         struct xen_blkif *blkif = be->blkif;
555         int err;
556         int state = 0;
557         struct block_device *bdev = be->blkif->vbd.bdev;
558         struct request_queue *q = bdev_get_queue(bdev);
559
560         if (!xenbus_read_unsigned(dev->nodename, "discard-enable", 1))
561                 return;
562
563         if (blk_queue_discard(q)) {
564                 err = xenbus_printf(xbt, dev->nodename,
565                         "discard-granularity", "%u",
566                         q->limits.discard_granularity);
567                 if (err) {
568                         dev_warn(&dev->dev, "writing discard-granularity (%d)", err);
569                         return;
570                 }
571                 err = xenbus_printf(xbt, dev->nodename,
572                         "discard-alignment", "%u",
573                         q->limits.discard_alignment);
574                 if (err) {
575                         dev_warn(&dev->dev, "writing discard-alignment (%d)", err);
576                         return;
577                 }
578                 state = 1;
579                 /* Optional. */
580                 err = xenbus_printf(xbt, dev->nodename,
581                                     "discard-secure", "%d",
582                                     blkif->vbd.discard_secure);
583                 if (err) {
584                         dev_warn(&dev->dev, "writing discard-secure (%d)", err);
585                         return;
586                 }
587         }
588         err = xenbus_printf(xbt, dev->nodename, "feature-discard",
589                             "%d", state);
590         if (err)
591                 dev_warn(&dev->dev, "writing feature-discard (%d)", err);
592 }
593 int xen_blkbk_barrier(struct xenbus_transaction xbt,
594                       struct backend_info *be, int state)
595 {
596         struct xenbus_device *dev = be->dev;
597         int err;
598
599         err = xenbus_printf(xbt, dev->nodename, "feature-barrier",
600                             "%d", state);
601         if (err)
602                 dev_warn(&dev->dev, "writing feature-barrier (%d)", err);
603
604         return err;
605 }
606
607 /*
608  * Entry point to this code when a new device is created.  Allocate the basic
609  * structures, and watch the store waiting for the hotplug scripts to tell us
610  * the device's physical major and minor numbers.  Switch to InitWait.
611  */
612 static int xen_blkbk_probe(struct xenbus_device *dev,
613                            const struct xenbus_device_id *id)
614 {
615         int err;
616         struct backend_info *be = kzalloc(sizeof(struct backend_info),
617                                           GFP_KERNEL);
618
619         /* match the pr_debug in xen_blkbk_remove */
620         pr_debug("%s %p %d\n", __func__, dev, dev->otherend_id);
621
622         if (!be) {
623                 xenbus_dev_fatal(dev, -ENOMEM,
624                                  "allocating backend structure");
625                 return -ENOMEM;
626         }
627         be->dev = dev;
628         dev_set_drvdata(&dev->dev, be);
629
630         be->blkif = xen_blkif_alloc(dev->otherend_id);
631         if (IS_ERR(be->blkif)) {
632                 err = PTR_ERR(be->blkif);
633                 be->blkif = NULL;
634                 xenbus_dev_fatal(dev, err, "creating block interface");
635                 goto fail;
636         }
637
638         err = xenbus_printf(XBT_NIL, dev->nodename,
639                             "feature-max-indirect-segments", "%u",
640                             MAX_INDIRECT_SEGMENTS);
641         if (err)
642                 dev_warn(&dev->dev,
643                          "writing %s/feature-max-indirect-segments (%d)",
644                          dev->nodename, err);
645
646         /* Multi-queue: advertise how many queues are supported by us.*/
647         err = xenbus_printf(XBT_NIL, dev->nodename,
648                             "multi-queue-max-queues", "%u", xenblk_max_queues);
649         if (err)
650                 pr_warn("Error writing multi-queue-max-queues\n");
651
652         /* setup back pointer */
653         be->blkif->be = be;
654
655         err = xenbus_watch_pathfmt(dev, &be->backend_watch, NULL,
656                                    backend_changed,
657                                    "%s/%s", dev->nodename, "physical-device");
658         if (err)
659                 goto fail;
660
661         err = xenbus_printf(XBT_NIL, dev->nodename, "max-ring-page-order", "%u",
662                             xen_blkif_max_ring_order);
663         if (err)
664                 pr_warn("%s write out 'max-ring-page-order' failed\n", __func__);
665
666         err = xenbus_switch_state(dev, XenbusStateInitWait);
667         if (err)
668                 goto fail;
669
670         return 0;
671
672 fail:
673         pr_warn("%s failed\n", __func__);
674         xen_blkbk_remove(dev);
675         return err;
676 }
677
678
679 /*
680  * Callback received when the hotplug scripts have placed the physical-device
681  * node.  Read it and the mode node, and create a vbd.  If the frontend is
682  * ready, connect.
683  */
684 static void backend_changed(struct xenbus_watch *watch,
685                             const char *path, const char *token)
686 {
687         int err;
688         unsigned major;
689         unsigned minor;
690         struct backend_info *be
691                 = container_of(watch, struct backend_info, backend_watch);
692         struct xenbus_device *dev = be->dev;
693         int cdrom = 0;
694         unsigned long handle;
695         char *device_type;
696
697         pr_debug("%s %p %d\n", __func__, dev, dev->otherend_id);
698
699         err = xenbus_scanf(XBT_NIL, dev->nodename, "physical-device", "%x:%x",
700                            &major, &minor);
701         if (XENBUS_EXIST_ERR(err)) {
702                 /*
703                  * Since this watch will fire once immediately after it is
704                  * registered, we expect this.  Ignore it, and wait for the
705                  * hotplug scripts.
706                  */
707                 return;
708         }
709         if (err != 2) {
710                 xenbus_dev_fatal(dev, err, "reading physical-device");
711                 return;
712         }
713
714         if (be->major | be->minor) {
715                 if (be->major != major || be->minor != minor)
716                         pr_warn("changing physical device (from %x:%x to %x:%x) not supported.\n",
717                                 be->major, be->minor, major, minor);
718                 return;
719         }
720
721         be->mode = xenbus_read(XBT_NIL, dev->nodename, "mode", NULL);
722         if (IS_ERR(be->mode)) {
723                 err = PTR_ERR(be->mode);
724                 be->mode = NULL;
725                 xenbus_dev_fatal(dev, err, "reading mode");
726                 return;
727         }
728
729         device_type = xenbus_read(XBT_NIL, dev->otherend, "device-type", NULL);
730         if (!IS_ERR(device_type)) {
731                 cdrom = strcmp(device_type, "cdrom") == 0;
732                 kfree(device_type);
733         }
734
735         /* Front end dir is a number, which is used as the handle. */
736         err = kstrtoul(strrchr(dev->otherend, '/') + 1, 0, &handle);
737         if (err) {
738                 kfree(be->mode);
739                 be->mode = NULL;
740                 return;
741         }
742
743         be->major = major;
744         be->minor = minor;
745
746         err = xen_vbd_create(be->blkif, handle, major, minor,
747                              !strchr(be->mode, 'w'), cdrom);
748
749         if (err)
750                 xenbus_dev_fatal(dev, err, "creating vbd structure");
751         else {
752                 err = xenvbd_sysfs_addif(dev);
753                 if (err) {
754                         xen_vbd_free(&be->blkif->vbd);
755                         xenbus_dev_fatal(dev, err, "creating sysfs entries");
756                 }
757         }
758
759         if (err) {
760                 kfree(be->mode);
761                 be->mode = NULL;
762                 be->major = 0;
763                 be->minor = 0;
764         } else {
765                 /* We're potentially connected now */
766                 xen_update_blkif_status(be->blkif);
767         }
768 }
769
770
771 /*
772  * Callback received when the frontend's state changes.
773  */
774 static void frontend_changed(struct xenbus_device *dev,
775                              enum xenbus_state frontend_state)
776 {
777         struct backend_info *be = dev_get_drvdata(&dev->dev);
778         int err;
779
780         pr_debug("%s %p %s\n", __func__, dev, xenbus_strstate(frontend_state));
781
782         switch (frontend_state) {
783         case XenbusStateInitialising:
784                 if (dev->state == XenbusStateClosed) {
785                         pr_info("%s: prepare for reconnect\n", dev->nodename);
786                         xenbus_switch_state(dev, XenbusStateInitWait);
787                 }
788                 break;
789
790         case XenbusStateInitialised:
791         case XenbusStateConnected:
792                 /*
793                  * Ensure we connect even when two watches fire in
794                  * close succession and we miss the intermediate value
795                  * of frontend_state.
796                  */
797                 if (dev->state == XenbusStateConnected)
798                         break;
799
800                 /*
801                  * Enforce precondition before potential leak point.
802                  * xen_blkif_disconnect() is idempotent.
803                  */
804                 err = xen_blkif_disconnect(be->blkif);
805                 if (err) {
806                         xenbus_dev_fatal(dev, err, "pending I/O");
807                         break;
808                 }
809
810                 err = connect_ring(be);
811                 if (err) {
812                         /*
813                          * Clean up so that memory resources can be used by
814                          * other devices. connect_ring reported already error.
815                          */
816                         xen_blkif_disconnect(be->blkif);
817                         break;
818                 }
819                 xen_update_blkif_status(be->blkif);
820                 break;
821
822         case XenbusStateClosing:
823                 xenbus_switch_state(dev, XenbusStateClosing);
824                 break;
825
826         case XenbusStateClosed:
827                 xen_blkif_disconnect(be->blkif);
828                 xenbus_switch_state(dev, XenbusStateClosed);
829                 if (xenbus_dev_is_online(dev))
830                         break;
831                 /* fall through */
832                 /* if not online */
833         case XenbusStateUnknown:
834                 /* implies xen_blkif_disconnect() via xen_blkbk_remove() */
835                 device_unregister(&dev->dev);
836                 break;
837
838         default:
839                 xenbus_dev_fatal(dev, -EINVAL, "saw state %d at frontend",
840                                  frontend_state);
841                 break;
842         }
843 }
844
845
846 /* ** Connection ** */
847
848
849 /*
850  * Write the physical details regarding the block device to the store, and
851  * switch to Connected state.
852  */
853 static void connect(struct backend_info *be)
854 {
855         struct xenbus_transaction xbt;
856         int err;
857         struct xenbus_device *dev = be->dev;
858
859         pr_debug("%s %s\n", __func__, dev->otherend);
860
861         /* Supply the information about the device the frontend needs */
862 again:
863         err = xenbus_transaction_start(&xbt);
864         if (err) {
865                 xenbus_dev_fatal(dev, err, "starting transaction");
866                 return;
867         }
868
869         /* If we can't advertise it is OK. */
870         xen_blkbk_flush_diskcache(xbt, be, be->blkif->vbd.flush_support);
871
872         xen_blkbk_discard(xbt, be);
873
874         xen_blkbk_barrier(xbt, be, be->blkif->vbd.flush_support);
875
876         err = xenbus_printf(xbt, dev->nodename, "feature-persistent", "%u", 1);
877         if (err) {
878                 xenbus_dev_fatal(dev, err, "writing %s/feature-persistent",
879                                  dev->nodename);
880                 goto abort;
881         }
882
883         err = xenbus_printf(xbt, dev->nodename, "sectors", "%llu",
884                             (unsigned long long)vbd_sz(&be->blkif->vbd));
885         if (err) {
886                 xenbus_dev_fatal(dev, err, "writing %s/sectors",
887                                  dev->nodename);
888                 goto abort;
889         }
890
891         /* FIXME: use a typename instead */
892         err = xenbus_printf(xbt, dev->nodename, "info", "%u",
893                             be->blkif->vbd.type |
894                             (be->blkif->vbd.readonly ? VDISK_READONLY : 0));
895         if (err) {
896                 xenbus_dev_fatal(dev, err, "writing %s/info",
897                                  dev->nodename);
898                 goto abort;
899         }
900         err = xenbus_printf(xbt, dev->nodename, "sector-size", "%lu",
901                             (unsigned long)
902                             bdev_logical_block_size(be->blkif->vbd.bdev));
903         if (err) {
904                 xenbus_dev_fatal(dev, err, "writing %s/sector-size",
905                                  dev->nodename);
906                 goto abort;
907         }
908         err = xenbus_printf(xbt, dev->nodename, "physical-sector-size", "%u",
909                             bdev_physical_block_size(be->blkif->vbd.bdev));
910         if (err)
911                 xenbus_dev_error(dev, err, "writing %s/physical-sector-size",
912                                  dev->nodename);
913
914         err = xenbus_transaction_end(xbt, 0);
915         if (err == -EAGAIN)
916                 goto again;
917         if (err)
918                 xenbus_dev_fatal(dev, err, "ending transaction");
919
920         err = xenbus_switch_state(dev, XenbusStateConnected);
921         if (err)
922                 xenbus_dev_fatal(dev, err, "%s: switching to Connected state",
923                                  dev->nodename);
924
925         return;
926  abort:
927         xenbus_transaction_end(xbt, 1);
928 }
929
930 /*
931  * Each ring may have multi pages, depends on "ring-page-order".
932  */
933 static int read_per_ring_refs(struct xen_blkif_ring *ring, const char *dir)
934 {
935         unsigned int ring_ref[XENBUS_MAX_RING_GRANTS];
936         struct pending_req *req, *n;
937         int err, i, j;
938         struct xen_blkif *blkif = ring->blkif;
939         struct xenbus_device *dev = blkif->be->dev;
940         unsigned int ring_page_order, nr_grefs, evtchn;
941
942         err = xenbus_scanf(XBT_NIL, dir, "event-channel", "%u",
943                           &evtchn);
944         if (err != 1) {
945                 err = -EINVAL;
946                 xenbus_dev_fatal(dev, err, "reading %s/event-channel", dir);
947                 return err;
948         }
949
950         err = xenbus_scanf(XBT_NIL, dev->otherend, "ring-page-order", "%u",
951                           &ring_page_order);
952         if (err != 1) {
953                 err = xenbus_scanf(XBT_NIL, dir, "ring-ref", "%u", &ring_ref[0]);
954                 if (err != 1) {
955                         err = -EINVAL;
956                         xenbus_dev_fatal(dev, err, "reading %s/ring-ref", dir);
957                         return err;
958                 }
959                 nr_grefs = 1;
960         } else {
961                 unsigned int i;
962
963                 if (ring_page_order > xen_blkif_max_ring_order) {
964                         err = -EINVAL;
965                         xenbus_dev_fatal(dev, err, "%s/request %d ring page order exceed max:%d",
966                                          dir, ring_page_order,
967                                          xen_blkif_max_ring_order);
968                         return err;
969                 }
970
971                 nr_grefs = 1 << ring_page_order;
972                 for (i = 0; i < nr_grefs; i++) {
973                         char ring_ref_name[RINGREF_NAME_LEN];
974
975                         snprintf(ring_ref_name, RINGREF_NAME_LEN, "ring-ref%u", i);
976                         err = xenbus_scanf(XBT_NIL, dir, ring_ref_name,
977                                            "%u", &ring_ref[i]);
978                         if (err != 1) {
979                                 err = -EINVAL;
980                                 xenbus_dev_fatal(dev, err, "reading %s/%s",
981                                                  dir, ring_ref_name);
982                                 return err;
983                         }
984                 }
985         }
986         blkif->nr_ring_pages = nr_grefs;
987
988         err = -ENOMEM;
989         for (i = 0; i < nr_grefs * XEN_BLKIF_REQS_PER_PAGE; i++) {
990                 req = kzalloc(sizeof(*req), GFP_KERNEL);
991                 if (!req)
992                         goto fail;
993                 list_add_tail(&req->free_list, &ring->pending_free);
994                 for (j = 0; j < MAX_INDIRECT_SEGMENTS; j++) {
995                         req->segments[j] = kzalloc(sizeof(*req->segments[0]), GFP_KERNEL);
996                         if (!req->segments[j])
997                                 goto fail;
998                 }
999                 for (j = 0; j < MAX_INDIRECT_PAGES; j++) {
1000                         req->indirect_pages[j] = kzalloc(sizeof(*req->indirect_pages[0]),
1001                                                          GFP_KERNEL);
1002                         if (!req->indirect_pages[j])
1003                                 goto fail;
1004                 }
1005         }
1006
1007         /* Map the shared frame, irq etc. */
1008         err = xen_blkif_map(ring, ring_ref, nr_grefs, evtchn);
1009         if (err) {
1010                 xenbus_dev_fatal(dev, err, "mapping ring-ref port %u", evtchn);
1011                 goto fail;
1012         }
1013
1014         return 0;
1015
1016 fail:
1017         list_for_each_entry_safe(req, n, &ring->pending_free, free_list) {
1018                 list_del(&req->free_list);
1019                 for (j = 0; j < MAX_INDIRECT_SEGMENTS; j++) {
1020                         if (!req->segments[j])
1021                                 break;
1022                         kfree(req->segments[j]);
1023                 }
1024                 for (j = 0; j < MAX_INDIRECT_PAGES; j++) {
1025                         if (!req->indirect_pages[j])
1026                                 break;
1027                         kfree(req->indirect_pages[j]);
1028                 }
1029                 kfree(req);
1030         }
1031         return err;
1032 }
1033
1034 static int connect_ring(struct backend_info *be)
1035 {
1036         struct xenbus_device *dev = be->dev;
1037         unsigned int pers_grants;
1038         char protocol[64] = "";
1039         int err, i;
1040         char *xspath;
1041         size_t xspathsize;
1042         const size_t xenstore_path_ext_size = 11; /* sufficient for "/queue-NNN" */
1043         unsigned int requested_num_queues = 0;
1044
1045         pr_debug("%s %s\n", __func__, dev->otherend);
1046
1047         be->blkif->blk_protocol = BLKIF_PROTOCOL_DEFAULT;
1048         err = xenbus_scanf(XBT_NIL, dev->otherend, "protocol",
1049                            "%63s", protocol);
1050         if (err <= 0)
1051                 strcpy(protocol, "unspecified, assuming default");
1052         else if (0 == strcmp(protocol, XEN_IO_PROTO_ABI_NATIVE))
1053                 be->blkif->blk_protocol = BLKIF_PROTOCOL_NATIVE;
1054         else if (0 == strcmp(protocol, XEN_IO_PROTO_ABI_X86_32))
1055                 be->blkif->blk_protocol = BLKIF_PROTOCOL_X86_32;
1056         else if (0 == strcmp(protocol, XEN_IO_PROTO_ABI_X86_64))
1057                 be->blkif->blk_protocol = BLKIF_PROTOCOL_X86_64;
1058         else {
1059                 xenbus_dev_fatal(dev, err, "unknown fe protocol %s", protocol);
1060                 return -ENOSYS;
1061         }
1062         pers_grants = xenbus_read_unsigned(dev->otherend, "feature-persistent",
1063                                            0);
1064         be->blkif->vbd.feature_gnt_persistent = pers_grants;
1065         be->blkif->vbd.overflow_max_grants = 0;
1066
1067         /*
1068          * Read the number of hardware queues from frontend.
1069          */
1070         requested_num_queues = xenbus_read_unsigned(dev->otherend,
1071                                                     "multi-queue-num-queues",
1072                                                     1);
1073         if (requested_num_queues > xenblk_max_queues
1074             || requested_num_queues == 0) {
1075                 /* Buggy or malicious guest. */
1076                 xenbus_dev_fatal(dev, err,
1077                                 "guest requested %u queues, exceeding the maximum of %u.",
1078                                 requested_num_queues, xenblk_max_queues);
1079                 return -ENOSYS;
1080         }
1081         be->blkif->nr_rings = requested_num_queues;
1082         if (xen_blkif_alloc_rings(be->blkif))
1083                 return -ENOMEM;
1084
1085         pr_info("%s: using %d queues, protocol %d (%s) %s\n", dev->nodename,
1086                  be->blkif->nr_rings, be->blkif->blk_protocol, protocol,
1087                  pers_grants ? "persistent grants" : "");
1088
1089         if (be->blkif->nr_rings == 1)
1090                 return read_per_ring_refs(&be->blkif->rings[0], dev->otherend);
1091         else {
1092                 xspathsize = strlen(dev->otherend) + xenstore_path_ext_size;
1093                 xspath = kmalloc(xspathsize, GFP_KERNEL);
1094                 if (!xspath) {
1095                         xenbus_dev_fatal(dev, -ENOMEM, "reading ring references");
1096                         return -ENOMEM;
1097                 }
1098
1099                 for (i = 0; i < be->blkif->nr_rings; i++) {
1100                         memset(xspath, 0, xspathsize);
1101                         snprintf(xspath, xspathsize, "%s/queue-%u", dev->otherend, i);
1102                         err = read_per_ring_refs(&be->blkif->rings[i], xspath);
1103                         if (err) {
1104                                 kfree(xspath);
1105                                 return err;
1106                         }
1107                 }
1108                 kfree(xspath);
1109         }
1110         return 0;
1111 }
1112
1113 static const struct xenbus_device_id xen_blkbk_ids[] = {
1114         { "vbd" },
1115         { "" }
1116 };
1117
1118 static struct xenbus_driver xen_blkbk_driver = {
1119         .ids  = xen_blkbk_ids,
1120         .probe = xen_blkbk_probe,
1121         .remove = xen_blkbk_remove,
1122         .otherend_changed = frontend_changed
1123 };
1124
1125 int xen_blkif_xenbus_init(void)
1126 {
1127         return xenbus_register_backend(&xen_blkbk_driver);
1128 }