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