xen/blkfront: improve protection against issuing unsupported REQ_FUA
[firefly-linux-kernel-4.4.55.git] / drivers / block / xen-blkfront.c
1 /*
2  * blkfront.c
3  *
4  * XenLinux virtual block device driver.
5  *
6  * Copyright (c) 2003-2004, Keir Fraser & Steve Hand
7  * Modifications by Mark A. Williamson are (c) Intel Research Cambridge
8  * Copyright (c) 2004, Christian Limpach
9  * Copyright (c) 2004, Andrew Warfield
10  * Copyright (c) 2005, Christopher Clark
11  * Copyright (c) 2005, XenSource Ltd
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License version 2
15  * as published by the Free Software Foundation; or, when distributed
16  * separately from the Linux kernel or incorporated into other
17  * software packages, subject to the following license:
18  *
19  * Permission is hereby granted, free of charge, to any person obtaining a copy
20  * of this source file (the "Software"), to deal in the Software without
21  * restriction, including without limitation the rights to use, copy, modify,
22  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
23  * and to permit persons to whom the Software is furnished to do so, subject to
24  * the following conditions:
25  *
26  * The above copyright notice and this permission notice shall be included in
27  * all copies or substantial portions of the Software.
28  *
29  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
30  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
31  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
32  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
33  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
34  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
35  * IN THE SOFTWARE.
36  */
37
38 #include <linux/interrupt.h>
39 #include <linux/blkdev.h>
40 #include <linux/hdreg.h>
41 #include <linux/cdrom.h>
42 #include <linux/module.h>
43 #include <linux/slab.h>
44 #include <linux/mutex.h>
45 #include <linux/scatterlist.h>
46 #include <linux/bitmap.h>
47 #include <linux/list.h>
48
49 #include <xen/xen.h>
50 #include <xen/xenbus.h>
51 #include <xen/grant_table.h>
52 #include <xen/events.h>
53 #include <xen/page.h>
54 #include <xen/platform_pci.h>
55
56 #include <xen/interface/grant_table.h>
57 #include <xen/interface/io/blkif.h>
58 #include <xen/interface/io/protocols.h>
59
60 #include <asm/xen/hypervisor.h>
61
62 enum blkif_state {
63         BLKIF_STATE_DISCONNECTED,
64         BLKIF_STATE_CONNECTED,
65         BLKIF_STATE_SUSPENDED,
66 };
67
68 struct grant {
69         grant_ref_t gref;
70         unsigned long pfn;
71         struct list_head node;
72 };
73
74 struct blk_shadow {
75         struct blkif_request req;
76         struct request *request;
77         struct grant **grants_used;
78         struct grant **indirect_grants;
79         struct scatterlist *sg;
80 };
81
82 struct split_bio {
83         struct bio *bio;
84         atomic_t pending;
85         int err;
86 };
87
88 static DEFINE_MUTEX(blkfront_mutex);
89 static const struct block_device_operations xlvbd_block_fops;
90
91 /*
92  * Maximum number of segments in indirect requests, the actual value used by
93  * the frontend driver is the minimum of this value and the value provided
94  * by the backend driver.
95  */
96
97 static unsigned int xen_blkif_max_segments = 32;
98 module_param_named(max, xen_blkif_max_segments, int, S_IRUGO);
99 MODULE_PARM_DESC(max, "Maximum amount of segments in indirect requests (default is 32)");
100
101 #define BLK_RING_SIZE __CONST_RING_SIZE(blkif, PAGE_SIZE)
102
103 /*
104  * We have one of these per vbd, whether ide, scsi or 'other'.  They
105  * hang in private_data off the gendisk structure. We may end up
106  * putting all kinds of interesting stuff here :-)
107  */
108 struct blkfront_info
109 {
110         spinlock_t io_lock;
111         struct mutex mutex;
112         struct xenbus_device *xbdev;
113         struct gendisk *gd;
114         int vdevice;
115         blkif_vdev_t handle;
116         enum blkif_state connected;
117         int ring_ref;
118         struct blkif_front_ring ring;
119         unsigned int evtchn, irq;
120         struct request_queue *rq;
121         struct work_struct work;
122         struct gnttab_free_callback callback;
123         struct blk_shadow shadow[BLK_RING_SIZE];
124         struct list_head grants;
125         struct list_head indirect_pages;
126         unsigned int persistent_gnts_c;
127         unsigned long shadow_free;
128         unsigned int feature_flush;
129         unsigned int flush_op;
130         unsigned int feature_discard:1;
131         unsigned int feature_secdiscard:1;
132         unsigned int discard_granularity;
133         unsigned int discard_alignment;
134         unsigned int feature_persistent:1;
135         unsigned int max_indirect_segments;
136         int is_ready;
137 };
138
139 static unsigned int nr_minors;
140 static unsigned long *minors;
141 static DEFINE_SPINLOCK(minor_lock);
142
143 #define MAXIMUM_OUTSTANDING_BLOCK_REQS \
144         (BLKIF_MAX_SEGMENTS_PER_REQUEST * BLK_RING_SIZE)
145 #define GRANT_INVALID_REF       0
146
147 #define PARTS_PER_DISK          16
148 #define PARTS_PER_EXT_DISK      256
149
150 #define BLKIF_MAJOR(dev) ((dev)>>8)
151 #define BLKIF_MINOR(dev) ((dev) & 0xff)
152
153 #define EXT_SHIFT 28
154 #define EXTENDED (1<<EXT_SHIFT)
155 #define VDEV_IS_EXTENDED(dev) ((dev)&(EXTENDED))
156 #define BLKIF_MINOR_EXT(dev) ((dev)&(~EXTENDED))
157 #define EMULATED_HD_DISK_MINOR_OFFSET (0)
158 #define EMULATED_HD_DISK_NAME_OFFSET (EMULATED_HD_DISK_MINOR_OFFSET / 256)
159 #define EMULATED_SD_DISK_MINOR_OFFSET (0)
160 #define EMULATED_SD_DISK_NAME_OFFSET (EMULATED_SD_DISK_MINOR_OFFSET / 256)
161
162 #define DEV_NAME        "xvd"   /* name in /dev */
163
164 #define SEGS_PER_INDIRECT_FRAME \
165         (PAGE_SIZE/sizeof(struct blkif_request_segment))
166 #define INDIRECT_GREFS(_segs) \
167         ((_segs + SEGS_PER_INDIRECT_FRAME - 1)/SEGS_PER_INDIRECT_FRAME)
168
169 static int blkfront_setup_indirect(struct blkfront_info *info);
170
171 static int get_id_from_freelist(struct blkfront_info *info)
172 {
173         unsigned long free = info->shadow_free;
174         BUG_ON(free >= BLK_RING_SIZE);
175         info->shadow_free = info->shadow[free].req.u.rw.id;
176         info->shadow[free].req.u.rw.id = 0x0fffffee; /* debug */
177         return free;
178 }
179
180 static int add_id_to_freelist(struct blkfront_info *info,
181                                unsigned long id)
182 {
183         if (info->shadow[id].req.u.rw.id != id)
184                 return -EINVAL;
185         if (info->shadow[id].request == NULL)
186                 return -EINVAL;
187         info->shadow[id].req.u.rw.id  = info->shadow_free;
188         info->shadow[id].request = NULL;
189         info->shadow_free = id;
190         return 0;
191 }
192
193 static int fill_grant_buffer(struct blkfront_info *info, int num)
194 {
195         struct page *granted_page;
196         struct grant *gnt_list_entry, *n;
197         int i = 0;
198
199         while(i < num) {
200                 gnt_list_entry = kzalloc(sizeof(struct grant), GFP_NOIO);
201                 if (!gnt_list_entry)
202                         goto out_of_memory;
203
204                 if (info->feature_persistent) {
205                         granted_page = alloc_page(GFP_NOIO);
206                         if (!granted_page) {
207                                 kfree(gnt_list_entry);
208                                 goto out_of_memory;
209                         }
210                         gnt_list_entry->pfn = page_to_pfn(granted_page);
211                 }
212
213                 gnt_list_entry->gref = GRANT_INVALID_REF;
214                 list_add(&gnt_list_entry->node, &info->grants);
215                 i++;
216         }
217
218         return 0;
219
220 out_of_memory:
221         list_for_each_entry_safe(gnt_list_entry, n,
222                                  &info->grants, node) {
223                 list_del(&gnt_list_entry->node);
224                 if (info->feature_persistent)
225                         __free_page(pfn_to_page(gnt_list_entry->pfn));
226                 kfree(gnt_list_entry);
227                 i--;
228         }
229         BUG_ON(i != 0);
230         return -ENOMEM;
231 }
232
233 static struct grant *get_grant(grant_ref_t *gref_head,
234                                unsigned long pfn,
235                                struct blkfront_info *info)
236 {
237         struct grant *gnt_list_entry;
238         unsigned long buffer_mfn;
239
240         BUG_ON(list_empty(&info->grants));
241         gnt_list_entry = list_first_entry(&info->grants, struct grant,
242                                           node);
243         list_del(&gnt_list_entry->node);
244
245         if (gnt_list_entry->gref != GRANT_INVALID_REF) {
246                 info->persistent_gnts_c--;
247                 return gnt_list_entry;
248         }
249
250         /* Assign a gref to this page */
251         gnt_list_entry->gref = gnttab_claim_grant_reference(gref_head);
252         BUG_ON(gnt_list_entry->gref == -ENOSPC);
253         if (!info->feature_persistent) {
254                 BUG_ON(!pfn);
255                 gnt_list_entry->pfn = pfn;
256         }
257         buffer_mfn = pfn_to_mfn(gnt_list_entry->pfn);
258         gnttab_grant_foreign_access_ref(gnt_list_entry->gref,
259                                         info->xbdev->otherend_id,
260                                         buffer_mfn, 0);
261         return gnt_list_entry;
262 }
263
264 static const char *op_name(int op)
265 {
266         static const char *const names[] = {
267                 [BLKIF_OP_READ] = "read",
268                 [BLKIF_OP_WRITE] = "write",
269                 [BLKIF_OP_WRITE_BARRIER] = "barrier",
270                 [BLKIF_OP_FLUSH_DISKCACHE] = "flush",
271                 [BLKIF_OP_DISCARD] = "discard" };
272
273         if (op < 0 || op >= ARRAY_SIZE(names))
274                 return "unknown";
275
276         if (!names[op])
277                 return "reserved";
278
279         return names[op];
280 }
281 static int xlbd_reserve_minors(unsigned int minor, unsigned int nr)
282 {
283         unsigned int end = minor + nr;
284         int rc;
285
286         if (end > nr_minors) {
287                 unsigned long *bitmap, *old;
288
289                 bitmap = kcalloc(BITS_TO_LONGS(end), sizeof(*bitmap),
290                                  GFP_KERNEL);
291                 if (bitmap == NULL)
292                         return -ENOMEM;
293
294                 spin_lock(&minor_lock);
295                 if (end > nr_minors) {
296                         old = minors;
297                         memcpy(bitmap, minors,
298                                BITS_TO_LONGS(nr_minors) * sizeof(*bitmap));
299                         minors = bitmap;
300                         nr_minors = BITS_TO_LONGS(end) * BITS_PER_LONG;
301                 } else
302                         old = bitmap;
303                 spin_unlock(&minor_lock);
304                 kfree(old);
305         }
306
307         spin_lock(&minor_lock);
308         if (find_next_bit(minors, end, minor) >= end) {
309                 bitmap_set(minors, minor, nr);
310                 rc = 0;
311         } else
312                 rc = -EBUSY;
313         spin_unlock(&minor_lock);
314
315         return rc;
316 }
317
318 static void xlbd_release_minors(unsigned int minor, unsigned int nr)
319 {
320         unsigned int end = minor + nr;
321
322         BUG_ON(end > nr_minors);
323         spin_lock(&minor_lock);
324         bitmap_clear(minors,  minor, nr);
325         spin_unlock(&minor_lock);
326 }
327
328 static void blkif_restart_queue_callback(void *arg)
329 {
330         struct blkfront_info *info = (struct blkfront_info *)arg;
331         schedule_work(&info->work);
332 }
333
334 static int blkif_getgeo(struct block_device *bd, struct hd_geometry *hg)
335 {
336         /* We don't have real geometry info, but let's at least return
337            values consistent with the size of the device */
338         sector_t nsect = get_capacity(bd->bd_disk);
339         sector_t cylinders = nsect;
340
341         hg->heads = 0xff;
342         hg->sectors = 0x3f;
343         sector_div(cylinders, hg->heads * hg->sectors);
344         hg->cylinders = cylinders;
345         if ((sector_t)(hg->cylinders + 1) * hg->heads * hg->sectors < nsect)
346                 hg->cylinders = 0xffff;
347         return 0;
348 }
349
350 static int blkif_ioctl(struct block_device *bdev, fmode_t mode,
351                        unsigned command, unsigned long argument)
352 {
353         struct blkfront_info *info = bdev->bd_disk->private_data;
354         int i;
355
356         dev_dbg(&info->xbdev->dev, "command: 0x%x, argument: 0x%lx\n",
357                 command, (long)argument);
358
359         switch (command) {
360         case CDROMMULTISESSION:
361                 dev_dbg(&info->xbdev->dev, "FIXME: support multisession CDs later\n");
362                 for (i = 0; i < sizeof(struct cdrom_multisession); i++)
363                         if (put_user(0, (char __user *)(argument + i)))
364                                 return -EFAULT;
365                 return 0;
366
367         case CDROM_GET_CAPABILITY: {
368                 struct gendisk *gd = info->gd;
369                 if (gd->flags & GENHD_FL_CD)
370                         return 0;
371                 return -EINVAL;
372         }
373
374         default:
375                 /*printk(KERN_ALERT "ioctl %08x not supported by Xen blkdev\n",
376                   command);*/
377                 return -EINVAL; /* same return as native Linux */
378         }
379
380         return 0;
381 }
382
383 /*
384  * Generate a Xen blkfront IO request from a blk layer request.  Reads
385  * and writes are handled as expected.
386  *
387  * @req: a request struct
388  */
389 static int blkif_queue_request(struct request *req)
390 {
391         struct blkfront_info *info = req->rq_disk->private_data;
392         struct blkif_request *ring_req;
393         unsigned long id;
394         unsigned int fsect, lsect;
395         int i, ref, n;
396         struct blkif_request_segment *segments = NULL;
397
398         /*
399          * Used to store if we are able to queue the request by just using
400          * existing persistent grants, or if we have to get new grants,
401          * as there are not sufficiently many free.
402          */
403         bool new_persistent_gnts;
404         grant_ref_t gref_head;
405         struct grant *gnt_list_entry = NULL;
406         struct scatterlist *sg;
407         int nseg, max_grefs;
408
409         if (unlikely(info->connected != BLKIF_STATE_CONNECTED))
410                 return 1;
411
412         max_grefs = req->nr_phys_segments;
413         if (max_grefs > BLKIF_MAX_SEGMENTS_PER_REQUEST)
414                 /*
415                  * If we are using indirect segments we need to account
416                  * for the indirect grefs used in the request.
417                  */
418                 max_grefs += INDIRECT_GREFS(req->nr_phys_segments);
419
420         /* Check if we have enough grants to allocate a requests */
421         if (info->persistent_gnts_c < max_grefs) {
422                 new_persistent_gnts = 1;
423                 if (gnttab_alloc_grant_references(
424                     max_grefs - info->persistent_gnts_c,
425                     &gref_head) < 0) {
426                         gnttab_request_free_callback(
427                                 &info->callback,
428                                 blkif_restart_queue_callback,
429                                 info,
430                                 max_grefs);
431                         return 1;
432                 }
433         } else
434                 new_persistent_gnts = 0;
435
436         /* Fill out a communications ring structure. */
437         ring_req = RING_GET_REQUEST(&info->ring, info->ring.req_prod_pvt);
438         id = get_id_from_freelist(info);
439         info->shadow[id].request = req;
440
441         if (unlikely(req->cmd_flags & (REQ_DISCARD | REQ_SECURE))) {
442                 ring_req->operation = BLKIF_OP_DISCARD;
443                 ring_req->u.discard.nr_sectors = blk_rq_sectors(req);
444                 ring_req->u.discard.id = id;
445                 ring_req->u.discard.sector_number = (blkif_sector_t)blk_rq_pos(req);
446                 if ((req->cmd_flags & REQ_SECURE) && info->feature_secdiscard)
447                         ring_req->u.discard.flag = BLKIF_DISCARD_SECURE;
448                 else
449                         ring_req->u.discard.flag = 0;
450         } else {
451                 BUG_ON(info->max_indirect_segments == 0 &&
452                        req->nr_phys_segments > BLKIF_MAX_SEGMENTS_PER_REQUEST);
453                 BUG_ON(info->max_indirect_segments &&
454                        req->nr_phys_segments > info->max_indirect_segments);
455                 nseg = blk_rq_map_sg(req->q, req, info->shadow[id].sg);
456                 ring_req->u.rw.id = id;
457                 if (nseg > BLKIF_MAX_SEGMENTS_PER_REQUEST) {
458                         /*
459                          * The indirect operation can only be a BLKIF_OP_READ or
460                          * BLKIF_OP_WRITE
461                          */
462                         BUG_ON(req->cmd_flags & (REQ_FLUSH | REQ_FUA));
463                         ring_req->operation = BLKIF_OP_INDIRECT;
464                         ring_req->u.indirect.indirect_op = rq_data_dir(req) ?
465                                 BLKIF_OP_WRITE : BLKIF_OP_READ;
466                         ring_req->u.indirect.sector_number = (blkif_sector_t)blk_rq_pos(req);
467                         ring_req->u.indirect.handle = info->handle;
468                         ring_req->u.indirect.nr_segments = nseg;
469                 } else {
470                         ring_req->u.rw.sector_number = (blkif_sector_t)blk_rq_pos(req);
471                         ring_req->u.rw.handle = info->handle;
472                         ring_req->operation = rq_data_dir(req) ?
473                                 BLKIF_OP_WRITE : BLKIF_OP_READ;
474                         if (req->cmd_flags & (REQ_FLUSH | REQ_FUA)) {
475                                 /*
476                                  * Ideally we can do an unordered flush-to-disk. In case the
477                                  * backend onlysupports barriers, use that. A barrier request
478                                  * a superset of FUA, so we can implement it the same
479                                  * way.  (It's also a FLUSH+FUA, since it is
480                                  * guaranteed ordered WRT previous writes.)
481                                  */
482                                 ring_req->operation = info->flush_op;
483                         }
484                         ring_req->u.rw.nr_segments = nseg;
485                 }
486                 for_each_sg(info->shadow[id].sg, sg, nseg, i) {
487                         fsect = sg->offset >> 9;
488                         lsect = fsect + (sg->length >> 9) - 1;
489
490                         if ((ring_req->operation == BLKIF_OP_INDIRECT) &&
491                             (i % SEGS_PER_INDIRECT_FRAME == 0)) {
492                                 unsigned long uninitialized_var(pfn);
493
494                                 if (segments)
495                                         kunmap_atomic(segments);
496
497                                 n = i / SEGS_PER_INDIRECT_FRAME;
498                                 if (!info->feature_persistent) {
499                                         struct page *indirect_page;
500
501                                         /* Fetch a pre-allocated page to use for indirect grefs */
502                                         BUG_ON(list_empty(&info->indirect_pages));
503                                         indirect_page = list_first_entry(&info->indirect_pages,
504                                                                          struct page, lru);
505                                         list_del(&indirect_page->lru);
506                                         pfn = page_to_pfn(indirect_page);
507                                 }
508                                 gnt_list_entry = get_grant(&gref_head, pfn, info);
509                                 info->shadow[id].indirect_grants[n] = gnt_list_entry;
510                                 segments = kmap_atomic(pfn_to_page(gnt_list_entry->pfn));
511                                 ring_req->u.indirect.indirect_grefs[n] = gnt_list_entry->gref;
512                         }
513
514                         gnt_list_entry = get_grant(&gref_head, page_to_pfn(sg_page(sg)), info);
515                         ref = gnt_list_entry->gref;
516
517                         info->shadow[id].grants_used[i] = gnt_list_entry;
518
519                         if (rq_data_dir(req) && info->feature_persistent) {
520                                 char *bvec_data;
521                                 void *shared_data;
522
523                                 BUG_ON(sg->offset + sg->length > PAGE_SIZE);
524
525                                 shared_data = kmap_atomic(pfn_to_page(gnt_list_entry->pfn));
526                                 bvec_data = kmap_atomic(sg_page(sg));
527
528                                 /*
529                                  * this does not wipe data stored outside the
530                                  * range sg->offset..sg->offset+sg->length.
531                                  * Therefore, blkback *could* see data from
532                                  * previous requests. This is OK as long as
533                                  * persistent grants are shared with just one
534                                  * domain. It may need refactoring if this
535                                  * changes
536                                  */
537                                 memcpy(shared_data + sg->offset,
538                                        bvec_data   + sg->offset,
539                                        sg->length);
540
541                                 kunmap_atomic(bvec_data);
542                                 kunmap_atomic(shared_data);
543                         }
544                         if (ring_req->operation != BLKIF_OP_INDIRECT) {
545                                 ring_req->u.rw.seg[i] =
546                                                 (struct blkif_request_segment) {
547                                                         .gref       = ref,
548                                                         .first_sect = fsect,
549                                                         .last_sect  = lsect };
550                         } else {
551                                 n = i % SEGS_PER_INDIRECT_FRAME;
552                                 segments[n] =
553                                         (struct blkif_request_segment) {
554                                                         .gref       = ref,
555                                                         .first_sect = fsect,
556                                                         .last_sect  = lsect };
557                         }
558                 }
559                 if (segments)
560                         kunmap_atomic(segments);
561         }
562
563         info->ring.req_prod_pvt++;
564
565         /* Keep a private copy so we can reissue requests when recovering. */
566         info->shadow[id].req = *ring_req;
567
568         if (new_persistent_gnts)
569                 gnttab_free_grant_references(gref_head);
570
571         return 0;
572 }
573
574
575 static inline void flush_requests(struct blkfront_info *info)
576 {
577         int notify;
578
579         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(&info->ring, notify);
580
581         if (notify)
582                 notify_remote_via_irq(info->irq);
583 }
584
585 static inline bool blkif_request_flush_invalid(struct request *req,
586                                                struct blkfront_info *info)
587 {
588         return ((req->cmd_type != REQ_TYPE_FS) ||
589                 ((req->cmd_flags & REQ_FLUSH) &&
590                  !(info->feature_flush & REQ_FLUSH)) ||
591                 ((req->cmd_flags & REQ_FUA) &&
592                  !(info->feature_flush & REQ_FUA)));
593 }
594
595 /*
596  * do_blkif_request
597  *  read a block; request is in a request queue
598  */
599 static void do_blkif_request(struct request_queue *rq)
600 {
601         struct blkfront_info *info = NULL;
602         struct request *req;
603         int queued;
604
605         pr_debug("Entered do_blkif_request\n");
606
607         queued = 0;
608
609         while ((req = blk_peek_request(rq)) != NULL) {
610                 info = req->rq_disk->private_data;
611
612                 if (RING_FULL(&info->ring))
613                         goto wait;
614
615                 blk_start_request(req);
616
617                 if (blkif_request_flush_invalid(req, info)) {
618                         __blk_end_request_all(req, -EOPNOTSUPP);
619                         continue;
620                 }
621
622                 pr_debug("do_blk_req %p: cmd %p, sec %lx, "
623                          "(%u/%u) [%s]\n",
624                          req, req->cmd, (unsigned long)blk_rq_pos(req),
625                          blk_rq_cur_sectors(req), blk_rq_sectors(req),
626                          rq_data_dir(req) ? "write" : "read");
627
628                 if (blkif_queue_request(req)) {
629                         blk_requeue_request(rq, req);
630 wait:
631                         /* Avoid pointless unplugs. */
632                         blk_stop_queue(rq);
633                         break;
634                 }
635
636                 queued++;
637         }
638
639         if (queued != 0)
640                 flush_requests(info);
641 }
642
643 static int xlvbd_init_blk_queue(struct gendisk *gd, u16 sector_size,
644                                 unsigned int physical_sector_size,
645                                 unsigned int segments)
646 {
647         struct request_queue *rq;
648         struct blkfront_info *info = gd->private_data;
649
650         rq = blk_init_queue(do_blkif_request, &info->io_lock);
651         if (rq == NULL)
652                 return -1;
653
654         queue_flag_set_unlocked(QUEUE_FLAG_VIRT, rq);
655
656         if (info->feature_discard) {
657                 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, rq);
658                 blk_queue_max_discard_sectors(rq, get_capacity(gd));
659                 rq->limits.discard_granularity = info->discard_granularity;
660                 rq->limits.discard_alignment = info->discard_alignment;
661                 if (info->feature_secdiscard)
662                         queue_flag_set_unlocked(QUEUE_FLAG_SECDISCARD, rq);
663         }
664
665         /* Hard sector size and max sectors impersonate the equiv. hardware. */
666         blk_queue_logical_block_size(rq, sector_size);
667         blk_queue_physical_block_size(rq, physical_sector_size);
668         blk_queue_max_hw_sectors(rq, (segments * PAGE_SIZE) / 512);
669
670         /* Each segment in a request is up to an aligned page in size. */
671         blk_queue_segment_boundary(rq, PAGE_SIZE - 1);
672         blk_queue_max_segment_size(rq, PAGE_SIZE);
673
674         /* Ensure a merged request will fit in a single I/O ring slot. */
675         blk_queue_max_segments(rq, segments);
676
677         /* Make sure buffer addresses are sector-aligned. */
678         blk_queue_dma_alignment(rq, 511);
679
680         /* Make sure we don't use bounce buffers. */
681         blk_queue_bounce_limit(rq, BLK_BOUNCE_ANY);
682
683         gd->queue = rq;
684
685         return 0;
686 }
687
688
689 static void xlvbd_flush(struct blkfront_info *info)
690 {
691         blk_queue_flush(info->rq, info->feature_flush);
692         printk(KERN_INFO "blkfront: %s: %s: %s %s %s %s %s\n",
693                info->gd->disk_name,
694                info->flush_op == BLKIF_OP_WRITE_BARRIER ?
695                 "barrier" : (info->flush_op == BLKIF_OP_FLUSH_DISKCACHE ?
696                 "flush diskcache" : "barrier or flush"),
697                info->feature_flush ? "enabled;" : "disabled;",
698                "persistent grants:",
699                info->feature_persistent ? "enabled;" : "disabled;",
700                "indirect descriptors:",
701                info->max_indirect_segments ? "enabled;" : "disabled;");
702 }
703
704 static int xen_translate_vdev(int vdevice, int *minor, unsigned int *offset)
705 {
706         int major;
707         major = BLKIF_MAJOR(vdevice);
708         *minor = BLKIF_MINOR(vdevice);
709         switch (major) {
710                 case XEN_IDE0_MAJOR:
711                         *offset = (*minor / 64) + EMULATED_HD_DISK_NAME_OFFSET;
712                         *minor = ((*minor / 64) * PARTS_PER_DISK) +
713                                 EMULATED_HD_DISK_MINOR_OFFSET;
714                         break;
715                 case XEN_IDE1_MAJOR:
716                         *offset = (*minor / 64) + 2 + EMULATED_HD_DISK_NAME_OFFSET;
717                         *minor = (((*minor / 64) + 2) * PARTS_PER_DISK) +
718                                 EMULATED_HD_DISK_MINOR_OFFSET;
719                         break;
720                 case XEN_SCSI_DISK0_MAJOR:
721                         *offset = (*minor / PARTS_PER_DISK) + EMULATED_SD_DISK_NAME_OFFSET;
722                         *minor = *minor + EMULATED_SD_DISK_MINOR_OFFSET;
723                         break;
724                 case XEN_SCSI_DISK1_MAJOR:
725                 case XEN_SCSI_DISK2_MAJOR:
726                 case XEN_SCSI_DISK3_MAJOR:
727                 case XEN_SCSI_DISK4_MAJOR:
728                 case XEN_SCSI_DISK5_MAJOR:
729                 case XEN_SCSI_DISK6_MAJOR:
730                 case XEN_SCSI_DISK7_MAJOR:
731                         *offset = (*minor / PARTS_PER_DISK) + 
732                                 ((major - XEN_SCSI_DISK1_MAJOR + 1) * 16) +
733                                 EMULATED_SD_DISK_NAME_OFFSET;
734                         *minor = *minor +
735                                 ((major - XEN_SCSI_DISK1_MAJOR + 1) * 16 * PARTS_PER_DISK) +
736                                 EMULATED_SD_DISK_MINOR_OFFSET;
737                         break;
738                 case XEN_SCSI_DISK8_MAJOR:
739                 case XEN_SCSI_DISK9_MAJOR:
740                 case XEN_SCSI_DISK10_MAJOR:
741                 case XEN_SCSI_DISK11_MAJOR:
742                 case XEN_SCSI_DISK12_MAJOR:
743                 case XEN_SCSI_DISK13_MAJOR:
744                 case XEN_SCSI_DISK14_MAJOR:
745                 case XEN_SCSI_DISK15_MAJOR:
746                         *offset = (*minor / PARTS_PER_DISK) + 
747                                 ((major - XEN_SCSI_DISK8_MAJOR + 8) * 16) +
748                                 EMULATED_SD_DISK_NAME_OFFSET;
749                         *minor = *minor +
750                                 ((major - XEN_SCSI_DISK8_MAJOR + 8) * 16 * PARTS_PER_DISK) +
751                                 EMULATED_SD_DISK_MINOR_OFFSET;
752                         break;
753                 case XENVBD_MAJOR:
754                         *offset = *minor / PARTS_PER_DISK;
755                         break;
756                 default:
757                         printk(KERN_WARNING "blkfront: your disk configuration is "
758                                         "incorrect, please use an xvd device instead\n");
759                         return -ENODEV;
760         }
761         return 0;
762 }
763
764 static char *encode_disk_name(char *ptr, unsigned int n)
765 {
766         if (n >= 26)
767                 ptr = encode_disk_name(ptr, n / 26 - 1);
768         *ptr = 'a' + n % 26;
769         return ptr + 1;
770 }
771
772 static int xlvbd_alloc_gendisk(blkif_sector_t capacity,
773                                struct blkfront_info *info,
774                                u16 vdisk_info, u16 sector_size,
775                                unsigned int physical_sector_size)
776 {
777         struct gendisk *gd;
778         int nr_minors = 1;
779         int err;
780         unsigned int offset;
781         int minor;
782         int nr_parts;
783         char *ptr;
784
785         BUG_ON(info->gd != NULL);
786         BUG_ON(info->rq != NULL);
787
788         if ((info->vdevice>>EXT_SHIFT) > 1) {
789                 /* this is above the extended range; something is wrong */
790                 printk(KERN_WARNING "blkfront: vdevice 0x%x is above the extended range; ignoring\n", info->vdevice);
791                 return -ENODEV;
792         }
793
794         if (!VDEV_IS_EXTENDED(info->vdevice)) {
795                 err = xen_translate_vdev(info->vdevice, &minor, &offset);
796                 if (err)
797                         return err;             
798                 nr_parts = PARTS_PER_DISK;
799         } else {
800                 minor = BLKIF_MINOR_EXT(info->vdevice);
801                 nr_parts = PARTS_PER_EXT_DISK;
802                 offset = minor / nr_parts;
803                 if (xen_hvm_domain() && offset < EMULATED_HD_DISK_NAME_OFFSET + 4)
804                         printk(KERN_WARNING "blkfront: vdevice 0x%x might conflict with "
805                                         "emulated IDE disks,\n\t choose an xvd device name"
806                                         "from xvde on\n", info->vdevice);
807         }
808         if (minor >> MINORBITS) {
809                 pr_warn("blkfront: %#x's minor (%#x) out of range; ignoring\n",
810                         info->vdevice, minor);
811                 return -ENODEV;
812         }
813
814         if ((minor % nr_parts) == 0)
815                 nr_minors = nr_parts;
816
817         err = xlbd_reserve_minors(minor, nr_minors);
818         if (err)
819                 goto out;
820         err = -ENODEV;
821
822         gd = alloc_disk(nr_minors);
823         if (gd == NULL)
824                 goto release;
825
826         strcpy(gd->disk_name, DEV_NAME);
827         ptr = encode_disk_name(gd->disk_name + sizeof(DEV_NAME) - 1, offset);
828         BUG_ON(ptr >= gd->disk_name + DISK_NAME_LEN);
829         if (nr_minors > 1)
830                 *ptr = 0;
831         else
832                 snprintf(ptr, gd->disk_name + DISK_NAME_LEN - ptr,
833                          "%d", minor & (nr_parts - 1));
834
835         gd->major = XENVBD_MAJOR;
836         gd->first_minor = minor;
837         gd->fops = &xlvbd_block_fops;
838         gd->private_data = info;
839         gd->driverfs_dev = &(info->xbdev->dev);
840         set_capacity(gd, capacity);
841
842         if (xlvbd_init_blk_queue(gd, sector_size, physical_sector_size,
843                                  info->max_indirect_segments ? :
844                                  BLKIF_MAX_SEGMENTS_PER_REQUEST)) {
845                 del_gendisk(gd);
846                 goto release;
847         }
848
849         info->rq = gd->queue;
850         info->gd = gd;
851
852         xlvbd_flush(info);
853
854         if (vdisk_info & VDISK_READONLY)
855                 set_disk_ro(gd, 1);
856
857         if (vdisk_info & VDISK_REMOVABLE)
858                 gd->flags |= GENHD_FL_REMOVABLE;
859
860         if (vdisk_info & VDISK_CDROM)
861                 gd->flags |= GENHD_FL_CD;
862
863         return 0;
864
865  release:
866         xlbd_release_minors(minor, nr_minors);
867  out:
868         return err;
869 }
870
871 static void xlvbd_release_gendisk(struct blkfront_info *info)
872 {
873         unsigned int minor, nr_minors;
874         unsigned long flags;
875
876         if (info->rq == NULL)
877                 return;
878
879         spin_lock_irqsave(&info->io_lock, flags);
880
881         /* No more blkif_request(). */
882         blk_stop_queue(info->rq);
883
884         /* No more gnttab callback work. */
885         gnttab_cancel_free_callback(&info->callback);
886         spin_unlock_irqrestore(&info->io_lock, flags);
887
888         /* Flush gnttab callback work. Must be done with no locks held. */
889         flush_work(&info->work);
890
891         del_gendisk(info->gd);
892
893         minor = info->gd->first_minor;
894         nr_minors = info->gd->minors;
895         xlbd_release_minors(minor, nr_minors);
896
897         blk_cleanup_queue(info->rq);
898         info->rq = NULL;
899
900         put_disk(info->gd);
901         info->gd = NULL;
902 }
903
904 static void kick_pending_request_queues(struct blkfront_info *info)
905 {
906         if (!RING_FULL(&info->ring)) {
907                 /* Re-enable calldowns. */
908                 blk_start_queue(info->rq);
909                 /* Kick things off immediately. */
910                 do_blkif_request(info->rq);
911         }
912 }
913
914 static void blkif_restart_queue(struct work_struct *work)
915 {
916         struct blkfront_info *info = container_of(work, struct blkfront_info, work);
917
918         spin_lock_irq(&info->io_lock);
919         if (info->connected == BLKIF_STATE_CONNECTED)
920                 kick_pending_request_queues(info);
921         spin_unlock_irq(&info->io_lock);
922 }
923
924 static void blkif_free(struct blkfront_info *info, int suspend)
925 {
926         struct grant *persistent_gnt;
927         struct grant *n;
928         int i, j, segs;
929
930         /* Prevent new requests being issued until we fix things up. */
931         spin_lock_irq(&info->io_lock);
932         info->connected = suspend ?
933                 BLKIF_STATE_SUSPENDED : BLKIF_STATE_DISCONNECTED;
934         /* No more blkif_request(). */
935         if (info->rq)
936                 blk_stop_queue(info->rq);
937
938         /* Remove all persistent grants */
939         if (!list_empty(&info->grants)) {
940                 list_for_each_entry_safe(persistent_gnt, n,
941                                          &info->grants, node) {
942                         list_del(&persistent_gnt->node);
943                         if (persistent_gnt->gref != GRANT_INVALID_REF) {
944                                 gnttab_end_foreign_access(persistent_gnt->gref,
945                                                           0, 0UL);
946                                 info->persistent_gnts_c--;
947                         }
948                         if (info->feature_persistent)
949                                 __free_page(pfn_to_page(persistent_gnt->pfn));
950                         kfree(persistent_gnt);
951                 }
952         }
953         BUG_ON(info->persistent_gnts_c != 0);
954
955         /*
956          * Remove indirect pages, this only happens when using indirect
957          * descriptors but not persistent grants
958          */
959         if (!list_empty(&info->indirect_pages)) {
960                 struct page *indirect_page, *n;
961
962                 BUG_ON(info->feature_persistent);
963                 list_for_each_entry_safe(indirect_page, n, &info->indirect_pages, lru) {
964                         list_del(&indirect_page->lru);
965                         __free_page(indirect_page);
966                 }
967         }
968
969         for (i = 0; i < BLK_RING_SIZE; i++) {
970                 /*
971                  * Clear persistent grants present in requests already
972                  * on the shared ring
973                  */
974                 if (!info->shadow[i].request)
975                         goto free_shadow;
976
977                 segs = info->shadow[i].req.operation == BLKIF_OP_INDIRECT ?
978                        info->shadow[i].req.u.indirect.nr_segments :
979                        info->shadow[i].req.u.rw.nr_segments;
980                 for (j = 0; j < segs; j++) {
981                         persistent_gnt = info->shadow[i].grants_used[j];
982                         gnttab_end_foreign_access(persistent_gnt->gref, 0, 0UL);
983                         if (info->feature_persistent)
984                                 __free_page(pfn_to_page(persistent_gnt->pfn));
985                         kfree(persistent_gnt);
986                 }
987
988                 if (info->shadow[i].req.operation != BLKIF_OP_INDIRECT)
989                         /*
990                          * If this is not an indirect operation don't try to
991                          * free indirect segments
992                          */
993                         goto free_shadow;
994
995                 for (j = 0; j < INDIRECT_GREFS(segs); j++) {
996                         persistent_gnt = info->shadow[i].indirect_grants[j];
997                         gnttab_end_foreign_access(persistent_gnt->gref, 0, 0UL);
998                         __free_page(pfn_to_page(persistent_gnt->pfn));
999                         kfree(persistent_gnt);
1000                 }
1001
1002 free_shadow:
1003                 kfree(info->shadow[i].grants_used);
1004                 info->shadow[i].grants_used = NULL;
1005                 kfree(info->shadow[i].indirect_grants);
1006                 info->shadow[i].indirect_grants = NULL;
1007                 kfree(info->shadow[i].sg);
1008                 info->shadow[i].sg = NULL;
1009         }
1010
1011         /* No more gnttab callback work. */
1012         gnttab_cancel_free_callback(&info->callback);
1013         spin_unlock_irq(&info->io_lock);
1014
1015         /* Flush gnttab callback work. Must be done with no locks held. */
1016         flush_work(&info->work);
1017
1018         /* Free resources associated with old device channel. */
1019         if (info->ring_ref != GRANT_INVALID_REF) {
1020                 gnttab_end_foreign_access(info->ring_ref, 0,
1021                                           (unsigned long)info->ring.sring);
1022                 info->ring_ref = GRANT_INVALID_REF;
1023                 info->ring.sring = NULL;
1024         }
1025         if (info->irq)
1026                 unbind_from_irqhandler(info->irq, info);
1027         info->evtchn = info->irq = 0;
1028
1029 }
1030
1031 static void blkif_completion(struct blk_shadow *s, struct blkfront_info *info,
1032                              struct blkif_response *bret)
1033 {
1034         int i = 0;
1035         struct scatterlist *sg;
1036         char *bvec_data;
1037         void *shared_data;
1038         int nseg;
1039
1040         nseg = s->req.operation == BLKIF_OP_INDIRECT ?
1041                 s->req.u.indirect.nr_segments : s->req.u.rw.nr_segments;
1042
1043         if (bret->operation == BLKIF_OP_READ && info->feature_persistent) {
1044                 /*
1045                  * Copy the data received from the backend into the bvec.
1046                  * Since bv_offset can be different than 0, and bv_len different
1047                  * than PAGE_SIZE, we have to keep track of the current offset,
1048                  * to be sure we are copying the data from the right shared page.
1049                  */
1050                 for_each_sg(s->sg, sg, nseg, i) {
1051                         BUG_ON(sg->offset + sg->length > PAGE_SIZE);
1052                         shared_data = kmap_atomic(
1053                                 pfn_to_page(s->grants_used[i]->pfn));
1054                         bvec_data = kmap_atomic(sg_page(sg));
1055                         memcpy(bvec_data   + sg->offset,
1056                                shared_data + sg->offset,
1057                                sg->length);
1058                         kunmap_atomic(bvec_data);
1059                         kunmap_atomic(shared_data);
1060                 }
1061         }
1062         /* Add the persistent grant into the list of free grants */
1063         for (i = 0; i < nseg; i++) {
1064                 if (gnttab_query_foreign_access(s->grants_used[i]->gref)) {
1065                         /*
1066                          * If the grant is still mapped by the backend (the
1067                          * backend has chosen to make this grant persistent)
1068                          * we add it at the head of the list, so it will be
1069                          * reused first.
1070                          */
1071                         if (!info->feature_persistent)
1072                                 pr_alert_ratelimited("backed has not unmapped grant: %u\n",
1073                                                      s->grants_used[i]->gref);
1074                         list_add(&s->grants_used[i]->node, &info->grants);
1075                         info->persistent_gnts_c++;
1076                 } else {
1077                         /*
1078                          * If the grant is not mapped by the backend we end the
1079                          * foreign access and add it to the tail of the list,
1080                          * so it will not be picked again unless we run out of
1081                          * persistent grants.
1082                          */
1083                         gnttab_end_foreign_access(s->grants_used[i]->gref, 0, 0UL);
1084                         s->grants_used[i]->gref = GRANT_INVALID_REF;
1085                         list_add_tail(&s->grants_used[i]->node, &info->grants);
1086                 }
1087         }
1088         if (s->req.operation == BLKIF_OP_INDIRECT) {
1089                 for (i = 0; i < INDIRECT_GREFS(nseg); i++) {
1090                         if (gnttab_query_foreign_access(s->indirect_grants[i]->gref)) {
1091                                 if (!info->feature_persistent)
1092                                         pr_alert_ratelimited("backed has not unmapped grant: %u\n",
1093                                                              s->indirect_grants[i]->gref);
1094                                 list_add(&s->indirect_grants[i]->node, &info->grants);
1095                                 info->persistent_gnts_c++;
1096                         } else {
1097                                 struct page *indirect_page;
1098
1099                                 gnttab_end_foreign_access(s->indirect_grants[i]->gref, 0, 0UL);
1100                                 /*
1101                                  * Add the used indirect page back to the list of
1102                                  * available pages for indirect grefs.
1103                                  */
1104                                 indirect_page = pfn_to_page(s->indirect_grants[i]->pfn);
1105                                 list_add(&indirect_page->lru, &info->indirect_pages);
1106                                 s->indirect_grants[i]->gref = GRANT_INVALID_REF;
1107                                 list_add_tail(&s->indirect_grants[i]->node, &info->grants);
1108                         }
1109                 }
1110         }
1111 }
1112
1113 static irqreturn_t blkif_interrupt(int irq, void *dev_id)
1114 {
1115         struct request *req;
1116         struct blkif_response *bret;
1117         RING_IDX i, rp;
1118         unsigned long flags;
1119         struct blkfront_info *info = (struct blkfront_info *)dev_id;
1120         int error;
1121
1122         spin_lock_irqsave(&info->io_lock, flags);
1123
1124         if (unlikely(info->connected != BLKIF_STATE_CONNECTED)) {
1125                 spin_unlock_irqrestore(&info->io_lock, flags);
1126                 return IRQ_HANDLED;
1127         }
1128
1129  again:
1130         rp = info->ring.sring->rsp_prod;
1131         rmb(); /* Ensure we see queued responses up to 'rp'. */
1132
1133         for (i = info->ring.rsp_cons; i != rp; i++) {
1134                 unsigned long id;
1135
1136                 bret = RING_GET_RESPONSE(&info->ring, i);
1137                 id   = bret->id;
1138                 /*
1139                  * The backend has messed up and given us an id that we would
1140                  * never have given to it (we stamp it up to BLK_RING_SIZE -
1141                  * look in get_id_from_freelist.
1142                  */
1143                 if (id >= BLK_RING_SIZE) {
1144                         WARN(1, "%s: response to %s has incorrect id (%ld)\n",
1145                              info->gd->disk_name, op_name(bret->operation), id);
1146                         /* We can't safely get the 'struct request' as
1147                          * the id is busted. */
1148                         continue;
1149                 }
1150                 req  = info->shadow[id].request;
1151
1152                 if (bret->operation != BLKIF_OP_DISCARD)
1153                         blkif_completion(&info->shadow[id], info, bret);
1154
1155                 if (add_id_to_freelist(info, id)) {
1156                         WARN(1, "%s: response to %s (id %ld) couldn't be recycled!\n",
1157                              info->gd->disk_name, op_name(bret->operation), id);
1158                         continue;
1159                 }
1160
1161                 error = (bret->status == BLKIF_RSP_OKAY) ? 0 : -EIO;
1162                 switch (bret->operation) {
1163                 case BLKIF_OP_DISCARD:
1164                         if (unlikely(bret->status == BLKIF_RSP_EOPNOTSUPP)) {
1165                                 struct request_queue *rq = info->rq;
1166                                 printk(KERN_WARNING "blkfront: %s: %s op failed\n",
1167                                            info->gd->disk_name, op_name(bret->operation));
1168                                 error = -EOPNOTSUPP;
1169                                 info->feature_discard = 0;
1170                                 info->feature_secdiscard = 0;
1171                                 queue_flag_clear(QUEUE_FLAG_DISCARD, rq);
1172                                 queue_flag_clear(QUEUE_FLAG_SECDISCARD, rq);
1173                         }
1174                         __blk_end_request_all(req, error);
1175                         break;
1176                 case BLKIF_OP_FLUSH_DISKCACHE:
1177                 case BLKIF_OP_WRITE_BARRIER:
1178                         if (unlikely(bret->status == BLKIF_RSP_EOPNOTSUPP)) {
1179                                 printk(KERN_WARNING "blkfront: %s: %s op failed\n",
1180                                        info->gd->disk_name, op_name(bret->operation));
1181                                 error = -EOPNOTSUPP;
1182                         }
1183                         if (unlikely(bret->status == BLKIF_RSP_ERROR &&
1184                                      info->shadow[id].req.u.rw.nr_segments == 0)) {
1185                                 printk(KERN_WARNING "blkfront: %s: empty %s op failed\n",
1186                                        info->gd->disk_name, op_name(bret->operation));
1187                                 error = -EOPNOTSUPP;
1188                         }
1189                         if (unlikely(error)) {
1190                                 if (error == -EOPNOTSUPP)
1191                                         error = 0;
1192                                 info->feature_flush = 0;
1193                                 info->flush_op = 0;
1194                                 xlvbd_flush(info);
1195                         }
1196                         /* fall through */
1197                 case BLKIF_OP_READ:
1198                 case BLKIF_OP_WRITE:
1199                         if (unlikely(bret->status != BLKIF_RSP_OKAY))
1200                                 dev_dbg(&info->xbdev->dev, "Bad return from blkdev data "
1201                                         "request: %x\n", bret->status);
1202
1203                         __blk_end_request_all(req, error);
1204                         break;
1205                 default:
1206                         BUG();
1207                 }
1208         }
1209
1210         info->ring.rsp_cons = i;
1211
1212         if (i != info->ring.req_prod_pvt) {
1213                 int more_to_do;
1214                 RING_FINAL_CHECK_FOR_RESPONSES(&info->ring, more_to_do);
1215                 if (more_to_do)
1216                         goto again;
1217         } else
1218                 info->ring.sring->rsp_event = i + 1;
1219
1220         kick_pending_request_queues(info);
1221
1222         spin_unlock_irqrestore(&info->io_lock, flags);
1223
1224         return IRQ_HANDLED;
1225 }
1226
1227
1228 static int setup_blkring(struct xenbus_device *dev,
1229                          struct blkfront_info *info)
1230 {
1231         struct blkif_sring *sring;
1232         int err;
1233
1234         info->ring_ref = GRANT_INVALID_REF;
1235
1236         sring = (struct blkif_sring *)__get_free_page(GFP_NOIO | __GFP_HIGH);
1237         if (!sring) {
1238                 xenbus_dev_fatal(dev, -ENOMEM, "allocating shared ring");
1239                 return -ENOMEM;
1240         }
1241         SHARED_RING_INIT(sring);
1242         FRONT_RING_INIT(&info->ring, sring, PAGE_SIZE);
1243
1244         err = xenbus_grant_ring(dev, virt_to_mfn(info->ring.sring));
1245         if (err < 0) {
1246                 free_page((unsigned long)sring);
1247                 info->ring.sring = NULL;
1248                 goto fail;
1249         }
1250         info->ring_ref = err;
1251
1252         err = xenbus_alloc_evtchn(dev, &info->evtchn);
1253         if (err)
1254                 goto fail;
1255
1256         err = bind_evtchn_to_irqhandler(info->evtchn, blkif_interrupt, 0,
1257                                         "blkif", info);
1258         if (err <= 0) {
1259                 xenbus_dev_fatal(dev, err,
1260                                  "bind_evtchn_to_irqhandler failed");
1261                 goto fail;
1262         }
1263         info->irq = err;
1264
1265         return 0;
1266 fail:
1267         blkif_free(info, 0);
1268         return err;
1269 }
1270
1271
1272 /* Common code used when first setting up, and when resuming. */
1273 static int talk_to_blkback(struct xenbus_device *dev,
1274                            struct blkfront_info *info)
1275 {
1276         const char *message = NULL;
1277         struct xenbus_transaction xbt;
1278         int err;
1279
1280         /* Create shared ring, alloc event channel. */
1281         err = setup_blkring(dev, info);
1282         if (err)
1283                 goto out;
1284
1285 again:
1286         err = xenbus_transaction_start(&xbt);
1287         if (err) {
1288                 xenbus_dev_fatal(dev, err, "starting transaction");
1289                 goto destroy_blkring;
1290         }
1291
1292         err = xenbus_printf(xbt, dev->nodename,
1293                             "ring-ref", "%u", info->ring_ref);
1294         if (err) {
1295                 message = "writing ring-ref";
1296                 goto abort_transaction;
1297         }
1298         err = xenbus_printf(xbt, dev->nodename,
1299                             "event-channel", "%u", info->evtchn);
1300         if (err) {
1301                 message = "writing event-channel";
1302                 goto abort_transaction;
1303         }
1304         err = xenbus_printf(xbt, dev->nodename, "protocol", "%s",
1305                             XEN_IO_PROTO_ABI_NATIVE);
1306         if (err) {
1307                 message = "writing protocol";
1308                 goto abort_transaction;
1309         }
1310         err = xenbus_printf(xbt, dev->nodename,
1311                             "feature-persistent", "%u", 1);
1312         if (err)
1313                 dev_warn(&dev->dev,
1314                          "writing persistent grants feature to xenbus");
1315
1316         err = xenbus_transaction_end(xbt, 0);
1317         if (err) {
1318                 if (err == -EAGAIN)
1319                         goto again;
1320                 xenbus_dev_fatal(dev, err, "completing transaction");
1321                 goto destroy_blkring;
1322         }
1323
1324         xenbus_switch_state(dev, XenbusStateInitialised);
1325
1326         return 0;
1327
1328  abort_transaction:
1329         xenbus_transaction_end(xbt, 1);
1330         if (message)
1331                 xenbus_dev_fatal(dev, err, "%s", message);
1332  destroy_blkring:
1333         blkif_free(info, 0);
1334  out:
1335         return err;
1336 }
1337
1338 /**
1339  * Entry point to this code when a new device is created.  Allocate the basic
1340  * structures and the ring buffer for communication with the backend, and
1341  * inform the backend of the appropriate details for those.  Switch to
1342  * Initialised state.
1343  */
1344 static int blkfront_probe(struct xenbus_device *dev,
1345                           const struct xenbus_device_id *id)
1346 {
1347         int err, vdevice, i;
1348         struct blkfront_info *info;
1349
1350         /* FIXME: Use dynamic device id if this is not set. */
1351         err = xenbus_scanf(XBT_NIL, dev->nodename,
1352                            "virtual-device", "%i", &vdevice);
1353         if (err != 1) {
1354                 /* go looking in the extended area instead */
1355                 err = xenbus_scanf(XBT_NIL, dev->nodename, "virtual-device-ext",
1356                                    "%i", &vdevice);
1357                 if (err != 1) {
1358                         xenbus_dev_fatal(dev, err, "reading virtual-device");
1359                         return err;
1360                 }
1361         }
1362
1363         if (xen_hvm_domain()) {
1364                 char *type;
1365                 int len;
1366                 /* no unplug has been done: do not hook devices != xen vbds */
1367                 if (xen_has_pv_and_legacy_disk_devices()) {
1368                         int major;
1369
1370                         if (!VDEV_IS_EXTENDED(vdevice))
1371                                 major = BLKIF_MAJOR(vdevice);
1372                         else
1373                                 major = XENVBD_MAJOR;
1374
1375                         if (major != XENVBD_MAJOR) {
1376                                 printk(KERN_INFO
1377                                                 "%s: HVM does not support vbd %d as xen block device\n",
1378                                                 __FUNCTION__, vdevice);
1379                                 return -ENODEV;
1380                         }
1381                 }
1382                 /* do not create a PV cdrom device if we are an HVM guest */
1383                 type = xenbus_read(XBT_NIL, dev->nodename, "device-type", &len);
1384                 if (IS_ERR(type))
1385                         return -ENODEV;
1386                 if (strncmp(type, "cdrom", 5) == 0) {
1387                         kfree(type);
1388                         return -ENODEV;
1389                 }
1390                 kfree(type);
1391         }
1392         info = kzalloc(sizeof(*info), GFP_KERNEL);
1393         if (!info) {
1394                 xenbus_dev_fatal(dev, -ENOMEM, "allocating info structure");
1395                 return -ENOMEM;
1396         }
1397
1398         mutex_init(&info->mutex);
1399         spin_lock_init(&info->io_lock);
1400         info->xbdev = dev;
1401         info->vdevice = vdevice;
1402         INIT_LIST_HEAD(&info->grants);
1403         INIT_LIST_HEAD(&info->indirect_pages);
1404         info->persistent_gnts_c = 0;
1405         info->connected = BLKIF_STATE_DISCONNECTED;
1406         INIT_WORK(&info->work, blkif_restart_queue);
1407
1408         for (i = 0; i < BLK_RING_SIZE; i++)
1409                 info->shadow[i].req.u.rw.id = i+1;
1410         info->shadow[BLK_RING_SIZE-1].req.u.rw.id = 0x0fffffff;
1411
1412         /* Front end dir is a number, which is used as the id. */
1413         info->handle = simple_strtoul(strrchr(dev->nodename, '/')+1, NULL, 0);
1414         dev_set_drvdata(&dev->dev, info);
1415
1416         err = talk_to_blkback(dev, info);
1417         if (err) {
1418                 kfree(info);
1419                 dev_set_drvdata(&dev->dev, NULL);
1420                 return err;
1421         }
1422
1423         return 0;
1424 }
1425
1426 static void split_bio_end(struct bio *bio, int error)
1427 {
1428         struct split_bio *split_bio = bio->bi_private;
1429
1430         if (error)
1431                 split_bio->err = error;
1432
1433         if (atomic_dec_and_test(&split_bio->pending)) {
1434                 split_bio->bio->bi_phys_segments = 0;
1435                 bio_endio(split_bio->bio, split_bio->err);
1436                 kfree(split_bio);
1437         }
1438         bio_put(bio);
1439 }
1440
1441 static int blkif_recover(struct blkfront_info *info)
1442 {
1443         int i;
1444         struct request *req, *n;
1445         struct blk_shadow *copy;
1446         int rc;
1447         struct bio *bio, *cloned_bio;
1448         struct bio_list bio_list, merge_bio;
1449         unsigned int segs, offset;
1450         int pending, size;
1451         struct split_bio *split_bio;
1452         struct list_head requests;
1453
1454         /* Stage 1: Make a safe copy of the shadow state. */
1455         copy = kmemdup(info->shadow, sizeof(info->shadow),
1456                        GFP_NOIO | __GFP_REPEAT | __GFP_HIGH);
1457         if (!copy)
1458                 return -ENOMEM;
1459
1460         /* Stage 2: Set up free list. */
1461         memset(&info->shadow, 0, sizeof(info->shadow));
1462         for (i = 0; i < BLK_RING_SIZE; i++)
1463                 info->shadow[i].req.u.rw.id = i+1;
1464         info->shadow_free = info->ring.req_prod_pvt;
1465         info->shadow[BLK_RING_SIZE-1].req.u.rw.id = 0x0fffffff;
1466
1467         rc = blkfront_setup_indirect(info);
1468         if (rc) {
1469                 kfree(copy);
1470                 return rc;
1471         }
1472
1473         segs = info->max_indirect_segments ? : BLKIF_MAX_SEGMENTS_PER_REQUEST;
1474         blk_queue_max_segments(info->rq, segs);
1475         bio_list_init(&bio_list);
1476         INIT_LIST_HEAD(&requests);
1477         for (i = 0; i < BLK_RING_SIZE; i++) {
1478                 /* Not in use? */
1479                 if (!copy[i].request)
1480                         continue;
1481
1482                 /*
1483                  * Get the bios in the request so we can re-queue them.
1484                  */
1485                 if (copy[i].request->cmd_flags &
1486                     (REQ_FLUSH | REQ_FUA | REQ_DISCARD | REQ_SECURE)) {
1487                         /*
1488                          * Flush operations don't contain bios, so
1489                          * we need to requeue the whole request
1490                          */
1491                         list_add(&copy[i].request->queuelist, &requests);
1492                         continue;
1493                 }
1494                 merge_bio.head = copy[i].request->bio;
1495                 merge_bio.tail = copy[i].request->biotail;
1496                 bio_list_merge(&bio_list, &merge_bio);
1497                 copy[i].request->bio = NULL;
1498                 blk_put_request(copy[i].request);
1499         }
1500
1501         kfree(copy);
1502
1503         /*
1504          * Empty the queue, this is important because we might have
1505          * requests in the queue with more segments than what we
1506          * can handle now.
1507          */
1508         spin_lock_irq(&info->io_lock);
1509         while ((req = blk_fetch_request(info->rq)) != NULL) {
1510                 if (req->cmd_flags &
1511                     (REQ_FLUSH | REQ_FUA | REQ_DISCARD | REQ_SECURE)) {
1512                         list_add(&req->queuelist, &requests);
1513                         continue;
1514                 }
1515                 merge_bio.head = req->bio;
1516                 merge_bio.tail = req->biotail;
1517                 bio_list_merge(&bio_list, &merge_bio);
1518                 req->bio = NULL;
1519                 if (req->cmd_flags & (REQ_FLUSH | REQ_FUA))
1520                         pr_alert("diskcache flush request found!\n");
1521                 __blk_put_request(info->rq, req);
1522         }
1523         spin_unlock_irq(&info->io_lock);
1524
1525         xenbus_switch_state(info->xbdev, XenbusStateConnected);
1526
1527         spin_lock_irq(&info->io_lock);
1528
1529         /* Now safe for us to use the shared ring */
1530         info->connected = BLKIF_STATE_CONNECTED;
1531
1532         /* Kick any other new requests queued since we resumed */
1533         kick_pending_request_queues(info);
1534
1535         list_for_each_entry_safe(req, n, &requests, queuelist) {
1536                 /* Requeue pending requests (flush or discard) */
1537                 list_del_init(&req->queuelist);
1538                 BUG_ON(req->nr_phys_segments > segs);
1539                 blk_requeue_request(info->rq, req);
1540         }
1541         spin_unlock_irq(&info->io_lock);
1542
1543         while ((bio = bio_list_pop(&bio_list)) != NULL) {
1544                 /* Traverse the list of pending bios and re-queue them */
1545                 if (bio_segments(bio) > segs) {
1546                         /*
1547                          * This bio has more segments than what we can
1548                          * handle, we have to split it.
1549                          */
1550                         pending = (bio_segments(bio) + segs - 1) / segs;
1551                         split_bio = kzalloc(sizeof(*split_bio), GFP_NOIO);
1552                         BUG_ON(split_bio == NULL);
1553                         atomic_set(&split_bio->pending, pending);
1554                         split_bio->bio = bio;
1555                         for (i = 0; i < pending; i++) {
1556                                 offset = (i * segs * PAGE_SIZE) >> 9;
1557                                 size = min((unsigned int)(segs * PAGE_SIZE) >> 9,
1558                                            (unsigned int)bio_sectors(bio) - offset);
1559                                 cloned_bio = bio_clone(bio, GFP_NOIO);
1560                                 BUG_ON(cloned_bio == NULL);
1561                                 bio_trim(cloned_bio, offset, size);
1562                                 cloned_bio->bi_private = split_bio;
1563                                 cloned_bio->bi_end_io = split_bio_end;
1564                                 submit_bio(cloned_bio->bi_rw, cloned_bio);
1565                         }
1566                         /*
1567                          * Now we have to wait for all those smaller bios to
1568                          * end, so we can also end the "parent" bio.
1569                          */
1570                         continue;
1571                 }
1572                 /* We don't need to split this bio */
1573                 submit_bio(bio->bi_rw, bio);
1574         }
1575
1576         return 0;
1577 }
1578
1579 /**
1580  * We are reconnecting to the backend, due to a suspend/resume, or a backend
1581  * driver restart.  We tear down our blkif structure and recreate it, but
1582  * leave the device-layer structures intact so that this is transparent to the
1583  * rest of the kernel.
1584  */
1585 static int blkfront_resume(struct xenbus_device *dev)
1586 {
1587         struct blkfront_info *info = dev_get_drvdata(&dev->dev);
1588         int err;
1589
1590         dev_dbg(&dev->dev, "blkfront_resume: %s\n", dev->nodename);
1591
1592         blkif_free(info, info->connected == BLKIF_STATE_CONNECTED);
1593
1594         err = talk_to_blkback(dev, info);
1595
1596         /*
1597          * We have to wait for the backend to switch to
1598          * connected state, since we want to read which
1599          * features it supports.
1600          */
1601
1602         return err;
1603 }
1604
1605 static void
1606 blkfront_closing(struct blkfront_info *info)
1607 {
1608         struct xenbus_device *xbdev = info->xbdev;
1609         struct block_device *bdev = NULL;
1610
1611         mutex_lock(&info->mutex);
1612
1613         if (xbdev->state == XenbusStateClosing) {
1614                 mutex_unlock(&info->mutex);
1615                 return;
1616         }
1617
1618         if (info->gd)
1619                 bdev = bdget_disk(info->gd, 0);
1620
1621         mutex_unlock(&info->mutex);
1622
1623         if (!bdev) {
1624                 xenbus_frontend_closed(xbdev);
1625                 return;
1626         }
1627
1628         mutex_lock(&bdev->bd_mutex);
1629
1630         if (bdev->bd_openers) {
1631                 xenbus_dev_error(xbdev, -EBUSY,
1632                                  "Device in use; refusing to close");
1633                 xenbus_switch_state(xbdev, XenbusStateClosing);
1634         } else {
1635                 xlvbd_release_gendisk(info);
1636                 xenbus_frontend_closed(xbdev);
1637         }
1638
1639         mutex_unlock(&bdev->bd_mutex);
1640         bdput(bdev);
1641 }
1642
1643 static void blkfront_setup_discard(struct blkfront_info *info)
1644 {
1645         int err;
1646         unsigned int discard_granularity;
1647         unsigned int discard_alignment;
1648         unsigned int discard_secure;
1649
1650         info->feature_discard = 1;
1651         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1652                 "discard-granularity", "%u", &discard_granularity,
1653                 "discard-alignment", "%u", &discard_alignment,
1654                 NULL);
1655         if (!err) {
1656                 info->discard_granularity = discard_granularity;
1657                 info->discard_alignment = discard_alignment;
1658         }
1659         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1660                     "discard-secure", "%d", &discard_secure,
1661                     NULL);
1662         if (!err)
1663                 info->feature_secdiscard = !!discard_secure;
1664 }
1665
1666 static int blkfront_setup_indirect(struct blkfront_info *info)
1667 {
1668         unsigned int indirect_segments, segs;
1669         int err, i;
1670
1671         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1672                             "feature-max-indirect-segments", "%u", &indirect_segments,
1673                             NULL);
1674         if (err) {
1675                 info->max_indirect_segments = 0;
1676                 segs = BLKIF_MAX_SEGMENTS_PER_REQUEST;
1677         } else {
1678                 info->max_indirect_segments = min(indirect_segments,
1679                                                   xen_blkif_max_segments);
1680                 segs = info->max_indirect_segments;
1681         }
1682
1683         err = fill_grant_buffer(info, (segs + INDIRECT_GREFS(segs)) * BLK_RING_SIZE);
1684         if (err)
1685                 goto out_of_memory;
1686
1687         if (!info->feature_persistent && info->max_indirect_segments) {
1688                 /*
1689                  * We are using indirect descriptors but not persistent
1690                  * grants, we need to allocate a set of pages that can be
1691                  * used for mapping indirect grefs
1692                  */
1693                 int num = INDIRECT_GREFS(segs) * BLK_RING_SIZE;
1694
1695                 BUG_ON(!list_empty(&info->indirect_pages));
1696                 for (i = 0; i < num; i++) {
1697                         struct page *indirect_page = alloc_page(GFP_NOIO);
1698                         if (!indirect_page)
1699                                 goto out_of_memory;
1700                         list_add(&indirect_page->lru, &info->indirect_pages);
1701                 }
1702         }
1703
1704         for (i = 0; i < BLK_RING_SIZE; i++) {
1705                 info->shadow[i].grants_used = kzalloc(
1706                         sizeof(info->shadow[i].grants_used[0]) * segs,
1707                         GFP_NOIO);
1708                 info->shadow[i].sg = kzalloc(sizeof(info->shadow[i].sg[0]) * segs, GFP_NOIO);
1709                 if (info->max_indirect_segments)
1710                         info->shadow[i].indirect_grants = kzalloc(
1711                                 sizeof(info->shadow[i].indirect_grants[0]) *
1712                                 INDIRECT_GREFS(segs),
1713                                 GFP_NOIO);
1714                 if ((info->shadow[i].grants_used == NULL) ||
1715                         (info->shadow[i].sg == NULL) ||
1716                      (info->max_indirect_segments &&
1717                      (info->shadow[i].indirect_grants == NULL)))
1718                         goto out_of_memory;
1719                 sg_init_table(info->shadow[i].sg, segs);
1720         }
1721
1722
1723         return 0;
1724
1725 out_of_memory:
1726         for (i = 0; i < BLK_RING_SIZE; i++) {
1727                 kfree(info->shadow[i].grants_used);
1728                 info->shadow[i].grants_used = NULL;
1729                 kfree(info->shadow[i].sg);
1730                 info->shadow[i].sg = NULL;
1731                 kfree(info->shadow[i].indirect_grants);
1732                 info->shadow[i].indirect_grants = NULL;
1733         }
1734         if (!list_empty(&info->indirect_pages)) {
1735                 struct page *indirect_page, *n;
1736                 list_for_each_entry_safe(indirect_page, n, &info->indirect_pages, lru) {
1737                         list_del(&indirect_page->lru);
1738                         __free_page(indirect_page);
1739                 }
1740         }
1741         return -ENOMEM;
1742 }
1743
1744 /*
1745  * Invoked when the backend is finally 'ready' (and has told produced
1746  * the details about the physical device - #sectors, size, etc).
1747  */
1748 static void blkfront_connect(struct blkfront_info *info)
1749 {
1750         unsigned long long sectors;
1751         unsigned long sector_size;
1752         unsigned int physical_sector_size;
1753         unsigned int binfo;
1754         int err;
1755         int barrier, flush, discard, persistent;
1756
1757         switch (info->connected) {
1758         case BLKIF_STATE_CONNECTED:
1759                 /*
1760                  * Potentially, the back-end may be signalling
1761                  * a capacity change; update the capacity.
1762                  */
1763                 err = xenbus_scanf(XBT_NIL, info->xbdev->otherend,
1764                                    "sectors", "%Lu", &sectors);
1765                 if (XENBUS_EXIST_ERR(err))
1766                         return;
1767                 printk(KERN_INFO "Setting capacity to %Lu\n",
1768                        sectors);
1769                 set_capacity(info->gd, sectors);
1770                 revalidate_disk(info->gd);
1771
1772                 return;
1773         case BLKIF_STATE_SUSPENDED:
1774                 /*
1775                  * If we are recovering from suspension, we need to wait
1776                  * for the backend to announce it's features before
1777                  * reconnecting, at least we need to know if the backend
1778                  * supports indirect descriptors, and how many.
1779                  */
1780                 blkif_recover(info);
1781                 return;
1782
1783         default:
1784                 break;
1785         }
1786
1787         dev_dbg(&info->xbdev->dev, "%s:%s.\n",
1788                 __func__, info->xbdev->otherend);
1789
1790         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1791                             "sectors", "%llu", &sectors,
1792                             "info", "%u", &binfo,
1793                             "sector-size", "%lu", &sector_size,
1794                             NULL);
1795         if (err) {
1796                 xenbus_dev_fatal(info->xbdev, err,
1797                                  "reading backend fields at %s",
1798                                  info->xbdev->otherend);
1799                 return;
1800         }
1801
1802         /*
1803          * physcial-sector-size is a newer field, so old backends may not
1804          * provide this. Assume physical sector size to be the same as
1805          * sector_size in that case.
1806          */
1807         err = xenbus_scanf(XBT_NIL, info->xbdev->otherend,
1808                            "physical-sector-size", "%u", &physical_sector_size);
1809         if (err != 1)
1810                 physical_sector_size = sector_size;
1811
1812         info->feature_flush = 0;
1813         info->flush_op = 0;
1814
1815         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1816                             "feature-barrier", "%d", &barrier,
1817                             NULL);
1818
1819         /*
1820          * If there's no "feature-barrier" defined, then it means
1821          * we're dealing with a very old backend which writes
1822          * synchronously; nothing to do.
1823          *
1824          * If there are barriers, then we use flush.
1825          */
1826         if (!err && barrier) {
1827                 info->feature_flush = REQ_FLUSH | REQ_FUA;
1828                 info->flush_op = BLKIF_OP_WRITE_BARRIER;
1829         }
1830         /*
1831          * And if there is "feature-flush-cache" use that above
1832          * barriers.
1833          */
1834         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1835                             "feature-flush-cache", "%d", &flush,
1836                             NULL);
1837
1838         if (!err && flush) {
1839                 info->feature_flush = REQ_FLUSH;
1840                 info->flush_op = BLKIF_OP_FLUSH_DISKCACHE;
1841         }
1842
1843         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1844                             "feature-discard", "%d", &discard,
1845                             NULL);
1846
1847         if (!err && discard)
1848                 blkfront_setup_discard(info);
1849
1850         err = xenbus_gather(XBT_NIL, info->xbdev->otherend,
1851                             "feature-persistent", "%u", &persistent,
1852                             NULL);
1853         if (err)
1854                 info->feature_persistent = 0;
1855         else
1856                 info->feature_persistent = persistent;
1857
1858         err = blkfront_setup_indirect(info);
1859         if (err) {
1860                 xenbus_dev_fatal(info->xbdev, err, "setup_indirect at %s",
1861                                  info->xbdev->otherend);
1862                 return;
1863         }
1864
1865         err = xlvbd_alloc_gendisk(sectors, info, binfo, sector_size,
1866                                   physical_sector_size);
1867         if (err) {
1868                 xenbus_dev_fatal(info->xbdev, err, "xlvbd_add at %s",
1869                                  info->xbdev->otherend);
1870                 return;
1871         }
1872
1873         xenbus_switch_state(info->xbdev, XenbusStateConnected);
1874
1875         /* Kick pending requests. */
1876         spin_lock_irq(&info->io_lock);
1877         info->connected = BLKIF_STATE_CONNECTED;
1878         kick_pending_request_queues(info);
1879         spin_unlock_irq(&info->io_lock);
1880
1881         add_disk(info->gd);
1882
1883         info->is_ready = 1;
1884 }
1885
1886 /**
1887  * Callback received when the backend's state changes.
1888  */
1889 static void blkback_changed(struct xenbus_device *dev,
1890                             enum xenbus_state backend_state)
1891 {
1892         struct blkfront_info *info = dev_get_drvdata(&dev->dev);
1893
1894         dev_dbg(&dev->dev, "blkfront:blkback_changed to state %d.\n", backend_state);
1895
1896         switch (backend_state) {
1897         case XenbusStateInitialising:
1898         case XenbusStateInitWait:
1899         case XenbusStateInitialised:
1900         case XenbusStateReconfiguring:
1901         case XenbusStateReconfigured:
1902         case XenbusStateUnknown:
1903                 break;
1904
1905         case XenbusStateConnected:
1906                 blkfront_connect(info);
1907                 break;
1908
1909         case XenbusStateClosed:
1910                 if (dev->state == XenbusStateClosed)
1911                         break;
1912                 /* Missed the backend's Closing state -- fallthrough */
1913         case XenbusStateClosing:
1914                 blkfront_closing(info);
1915                 break;
1916         }
1917 }
1918
1919 static int blkfront_remove(struct xenbus_device *xbdev)
1920 {
1921         struct blkfront_info *info = dev_get_drvdata(&xbdev->dev);
1922         struct block_device *bdev = NULL;
1923         struct gendisk *disk;
1924
1925         dev_dbg(&xbdev->dev, "%s removed", xbdev->nodename);
1926
1927         blkif_free(info, 0);
1928
1929         mutex_lock(&info->mutex);
1930
1931         disk = info->gd;
1932         if (disk)
1933                 bdev = bdget_disk(disk, 0);
1934
1935         info->xbdev = NULL;
1936         mutex_unlock(&info->mutex);
1937
1938         if (!bdev) {
1939                 kfree(info);
1940                 return 0;
1941         }
1942
1943         /*
1944          * The xbdev was removed before we reached the Closed
1945          * state. See if it's safe to remove the disk. If the bdev
1946          * isn't closed yet, we let release take care of it.
1947          */
1948
1949         mutex_lock(&bdev->bd_mutex);
1950         info = disk->private_data;
1951
1952         dev_warn(disk_to_dev(disk),
1953                  "%s was hot-unplugged, %d stale handles\n",
1954                  xbdev->nodename, bdev->bd_openers);
1955
1956         if (info && !bdev->bd_openers) {
1957                 xlvbd_release_gendisk(info);
1958                 disk->private_data = NULL;
1959                 kfree(info);
1960         }
1961
1962         mutex_unlock(&bdev->bd_mutex);
1963         bdput(bdev);
1964
1965         return 0;
1966 }
1967
1968 static int blkfront_is_ready(struct xenbus_device *dev)
1969 {
1970         struct blkfront_info *info = dev_get_drvdata(&dev->dev);
1971
1972         return info->is_ready && info->xbdev;
1973 }
1974
1975 static int blkif_open(struct block_device *bdev, fmode_t mode)
1976 {
1977         struct gendisk *disk = bdev->bd_disk;
1978         struct blkfront_info *info;
1979         int err = 0;
1980
1981         mutex_lock(&blkfront_mutex);
1982
1983         info = disk->private_data;
1984         if (!info) {
1985                 /* xbdev gone */
1986                 err = -ERESTARTSYS;
1987                 goto out;
1988         }
1989
1990         mutex_lock(&info->mutex);
1991
1992         if (!info->gd)
1993                 /* xbdev is closed */
1994                 err = -ERESTARTSYS;
1995
1996         mutex_unlock(&info->mutex);
1997
1998 out:
1999         mutex_unlock(&blkfront_mutex);
2000         return err;
2001 }
2002
2003 static void blkif_release(struct gendisk *disk, fmode_t mode)
2004 {
2005         struct blkfront_info *info = disk->private_data;
2006         struct block_device *bdev;
2007         struct xenbus_device *xbdev;
2008
2009         mutex_lock(&blkfront_mutex);
2010
2011         bdev = bdget_disk(disk, 0);
2012
2013         if (!bdev) {
2014                 WARN(1, "Block device %s yanked out from us!\n", disk->disk_name);
2015                 goto out_mutex;
2016         }
2017         if (bdev->bd_openers)
2018                 goto out;
2019
2020         /*
2021          * Check if we have been instructed to close. We will have
2022          * deferred this request, because the bdev was still open.
2023          */
2024
2025         mutex_lock(&info->mutex);
2026         xbdev = info->xbdev;
2027
2028         if (xbdev && xbdev->state == XenbusStateClosing) {
2029                 /* pending switch to state closed */
2030                 dev_info(disk_to_dev(bdev->bd_disk), "releasing disk\n");
2031                 xlvbd_release_gendisk(info);
2032                 xenbus_frontend_closed(info->xbdev);
2033         }
2034
2035         mutex_unlock(&info->mutex);
2036
2037         if (!xbdev) {
2038                 /* sudden device removal */
2039                 dev_info(disk_to_dev(bdev->bd_disk), "releasing disk\n");
2040                 xlvbd_release_gendisk(info);
2041                 disk->private_data = NULL;
2042                 kfree(info);
2043         }
2044
2045 out:
2046         bdput(bdev);
2047 out_mutex:
2048         mutex_unlock(&blkfront_mutex);
2049 }
2050
2051 static const struct block_device_operations xlvbd_block_fops =
2052 {
2053         .owner = THIS_MODULE,
2054         .open = blkif_open,
2055         .release = blkif_release,
2056         .getgeo = blkif_getgeo,
2057         .ioctl = blkif_ioctl,
2058 };
2059
2060
2061 static const struct xenbus_device_id blkfront_ids[] = {
2062         { "vbd" },
2063         { "" }
2064 };
2065
2066 static struct xenbus_driver blkfront_driver = {
2067         .ids  = blkfront_ids,
2068         .probe = blkfront_probe,
2069         .remove = blkfront_remove,
2070         .resume = blkfront_resume,
2071         .otherend_changed = blkback_changed,
2072         .is_ready = blkfront_is_ready,
2073 };
2074
2075 static int __init xlblk_init(void)
2076 {
2077         int ret;
2078
2079         if (!xen_domain())
2080                 return -ENODEV;
2081
2082         if (!xen_has_pv_disk_devices())
2083                 return -ENODEV;
2084
2085         if (register_blkdev(XENVBD_MAJOR, DEV_NAME)) {
2086                 printk(KERN_WARNING "xen_blk: can't get major %d with name %s\n",
2087                        XENVBD_MAJOR, DEV_NAME);
2088                 return -ENODEV;
2089         }
2090
2091         ret = xenbus_register_frontend(&blkfront_driver);
2092         if (ret) {
2093                 unregister_blkdev(XENVBD_MAJOR, DEV_NAME);
2094                 return ret;
2095         }
2096
2097         return 0;
2098 }
2099 module_init(xlblk_init);
2100
2101
2102 static void __exit xlblk_exit(void)
2103 {
2104         xenbus_unregister_driver(&blkfront_driver);
2105         unregister_blkdev(XENVBD_MAJOR, DEV_NAME);
2106         kfree(minors);
2107 }
2108 module_exit(xlblk_exit);
2109
2110 MODULE_DESCRIPTION("Xen virtual block device frontend");
2111 MODULE_LICENSE("GPL");
2112 MODULE_ALIAS_BLOCKDEV_MAJOR(XENVBD_MAJOR);
2113 MODULE_ALIAS("xen:vbd");
2114 MODULE_ALIAS("xenblk");