xen: support suspend/resume in pvscsi frontend
[cascardo/linux.git] / drivers / scsi / xen-scsifront.c
1 /*
2  * Xen SCSI frontend driver
3  *
4  * Copyright (c) 2008, FUJITSU Limited
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License version 2
8  * as published by the Free Software Foundation; or, when distributed
9  * separately from the Linux kernel or incorporated into other
10  * software packages, subject to the following license:
11  *
12  * Permission is hereby granted, free of charge, to any person obtaining a copy
13  * of this source file (the "Software"), to deal in the Software without
14  * restriction, including without limitation the rights to use, copy, modify,
15  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
16  * and to permit persons to whom the Software is furnished to do so, subject to
17  * the following conditions:
18  *
19  * The above copyright notice and this permission notice shall be included in
20  * all copies or substantial portions of the Software.
21  *
22  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
28  * IN THE SOFTWARE.
29  */
30
31 #include <linux/module.h>
32 #include <linux/kernel.h>
33 #include <linux/device.h>
34 #include <linux/wait.h>
35 #include <linux/interrupt.h>
36 #include <linux/mutex.h>
37 #include <linux/spinlock.h>
38 #include <linux/sched.h>
39 #include <linux/blkdev.h>
40 #include <linux/pfn.h>
41 #include <linux/slab.h>
42 #include <linux/bitops.h>
43
44 #include <scsi/scsi_cmnd.h>
45 #include <scsi/scsi_device.h>
46 #include <scsi/scsi.h>
47 #include <scsi/scsi_host.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
55 #include <xen/interface/grant_table.h>
56 #include <xen/interface/io/vscsiif.h>
57 #include <xen/interface/io/protocols.h>
58
59 #include <asm/xen/hypervisor.h>
60
61
62 #define GRANT_INVALID_REF       0
63
64 #define VSCSIFRONT_OP_ADD_LUN   1
65 #define VSCSIFRONT_OP_DEL_LUN   2
66 #define VSCSIFRONT_OP_READD_LUN 3
67
68 /* Tuning point. */
69 #define VSCSIIF_DEFAULT_CMD_PER_LUN 10
70 #define VSCSIIF_MAX_TARGET          64
71 #define VSCSIIF_MAX_LUN             255
72
73 #define VSCSIIF_RING_SIZE       __CONST_RING_SIZE(vscsiif, PAGE_SIZE)
74 #define VSCSIIF_MAX_REQS        VSCSIIF_RING_SIZE
75
76 #define vscsiif_grants_sg(_sg)  (PFN_UP((_sg) *         \
77                                 sizeof(struct scsiif_request_segment)))
78
79 struct vscsifrnt_shadow {
80         /* command between backend and frontend */
81         unsigned char act;
82         uint16_t rqid;
83
84         unsigned int nr_grants;         /* number of grants in gref[] */
85         struct scsiif_request_segment *sg;      /* scatter/gather elements */
86
87         /* Do reset or abort function. */
88         wait_queue_head_t wq_reset;     /* reset work queue           */
89         int wait_reset;                 /* reset work queue condition */
90         int32_t rslt_reset;             /* reset response status:     */
91                                         /* SUCCESS or FAILED or:      */
92 #define RSLT_RESET_WAITING      0
93 #define RSLT_RESET_ERR          -1
94
95         /* Requested struct scsi_cmnd is stored from kernel. */
96         struct scsi_cmnd *sc;
97         int gref[vscsiif_grants_sg(SG_ALL) + SG_ALL];
98 };
99
100 struct vscsifrnt_info {
101         struct xenbus_device *dev;
102
103         struct Scsi_Host *host;
104         int host_active;
105
106         unsigned int evtchn;
107         unsigned int irq;
108
109         grant_ref_t ring_ref;
110         struct vscsiif_front_ring ring;
111         struct vscsiif_response ring_rsp;
112
113         spinlock_t shadow_lock;
114         DECLARE_BITMAP(shadow_free_bitmap, VSCSIIF_MAX_REQS);
115         struct vscsifrnt_shadow *shadow[VSCSIIF_MAX_REQS];
116
117         /* Following items are protected by the host lock. */
118         wait_queue_head_t wq_sync;
119         wait_queue_head_t wq_pause;
120         unsigned int wait_ring_available:1;
121         unsigned int waiting_pause:1;
122         unsigned int pause:1;
123         unsigned callers;
124
125         char dev_state_path[64];
126         struct task_struct *curr;
127 };
128
129 static DEFINE_MUTEX(scsifront_mutex);
130
131 static void scsifront_wake_up(struct vscsifrnt_info *info)
132 {
133         info->wait_ring_available = 0;
134         wake_up(&info->wq_sync);
135 }
136
137 static int scsifront_get_rqid(struct vscsifrnt_info *info)
138 {
139         unsigned long flags;
140         int free;
141
142         spin_lock_irqsave(&info->shadow_lock, flags);
143
144         free = find_first_bit(info->shadow_free_bitmap, VSCSIIF_MAX_REQS);
145         __clear_bit(free, info->shadow_free_bitmap);
146
147         spin_unlock_irqrestore(&info->shadow_lock, flags);
148
149         return free;
150 }
151
152 static int _scsifront_put_rqid(struct vscsifrnt_info *info, uint32_t id)
153 {
154         int empty = bitmap_empty(info->shadow_free_bitmap, VSCSIIF_MAX_REQS);
155
156         __set_bit(id, info->shadow_free_bitmap);
157         info->shadow[id] = NULL;
158
159         return empty || info->wait_ring_available;
160 }
161
162 static void scsifront_put_rqid(struct vscsifrnt_info *info, uint32_t id)
163 {
164         unsigned long flags;
165         int kick;
166
167         spin_lock_irqsave(&info->shadow_lock, flags);
168         kick = _scsifront_put_rqid(info, id);
169         spin_unlock_irqrestore(&info->shadow_lock, flags);
170
171         if (kick)
172                 scsifront_wake_up(info);
173 }
174
175 static struct vscsiif_request *scsifront_pre_req(struct vscsifrnt_info *info)
176 {
177         struct vscsiif_front_ring *ring = &(info->ring);
178         struct vscsiif_request *ring_req;
179         uint32_t id;
180
181         id = scsifront_get_rqid(info);  /* use id in response */
182         if (id >= VSCSIIF_MAX_REQS)
183                 return NULL;
184
185         ring_req = RING_GET_REQUEST(&(info->ring), ring->req_prod_pvt);
186
187         ring->req_prod_pvt++;
188
189         ring_req->rqid = (uint16_t)id;
190
191         return ring_req;
192 }
193
194 static void scsifront_do_request(struct vscsifrnt_info *info)
195 {
196         struct vscsiif_front_ring *ring = &(info->ring);
197         int notify;
198
199         RING_PUSH_REQUESTS_AND_CHECK_NOTIFY(ring, notify);
200         if (notify)
201                 notify_remote_via_irq(info->irq);
202 }
203
204 static void scsifront_gnttab_done(struct vscsifrnt_info *info, uint32_t id)
205 {
206         struct vscsifrnt_shadow *s = info->shadow[id];
207         int i;
208
209         if (s->sc->sc_data_direction == DMA_NONE)
210                 return;
211
212         for (i = 0; i < s->nr_grants; i++) {
213                 if (unlikely(gnttab_query_foreign_access(s->gref[i]) != 0)) {
214                         shost_printk(KERN_ALERT, info->host, KBUILD_MODNAME
215                                      "grant still in use by backend\n");
216                         BUG();
217                 }
218                 gnttab_end_foreign_access(s->gref[i], 0, 0UL);
219         }
220
221         kfree(s->sg);
222 }
223
224 static void scsifront_cdb_cmd_done(struct vscsifrnt_info *info,
225                                    struct vscsiif_response *ring_rsp)
226 {
227         struct scsi_cmnd *sc;
228         uint32_t id;
229         uint8_t sense_len;
230
231         id = ring_rsp->rqid;
232         sc = info->shadow[id]->sc;
233
234         BUG_ON(sc == NULL);
235
236         scsifront_gnttab_done(info, id);
237         scsifront_put_rqid(info, id);
238
239         sc->result = ring_rsp->rslt;
240         scsi_set_resid(sc, ring_rsp->residual_len);
241
242         sense_len = min_t(uint8_t, VSCSIIF_SENSE_BUFFERSIZE,
243                           ring_rsp->sense_len);
244
245         if (sense_len)
246                 memcpy(sc->sense_buffer, ring_rsp->sense_buffer, sense_len);
247
248         sc->scsi_done(sc);
249 }
250
251 static void scsifront_sync_cmd_done(struct vscsifrnt_info *info,
252                                     struct vscsiif_response *ring_rsp)
253 {
254         uint16_t id = ring_rsp->rqid;
255         unsigned long flags;
256         struct vscsifrnt_shadow *shadow = info->shadow[id];
257         int kick;
258
259         spin_lock_irqsave(&info->shadow_lock, flags);
260         shadow->wait_reset = 1;
261         switch (shadow->rslt_reset) {
262         case RSLT_RESET_WAITING:
263                 shadow->rslt_reset = ring_rsp->rslt;
264                 break;
265         case RSLT_RESET_ERR:
266                 kick = _scsifront_put_rqid(info, id);
267                 spin_unlock_irqrestore(&info->shadow_lock, flags);
268                 kfree(shadow);
269                 if (kick)
270                         scsifront_wake_up(info);
271                 return;
272         default:
273                 shost_printk(KERN_ERR, info->host, KBUILD_MODNAME
274                              "bad reset state %d, possibly leaking %u\n",
275                              shadow->rslt_reset, id);
276                 break;
277         }
278         spin_unlock_irqrestore(&info->shadow_lock, flags);
279
280         wake_up(&shadow->wq_reset);
281 }
282
283 static void scsifront_do_response(struct vscsifrnt_info *info,
284                                   struct vscsiif_response *ring_rsp)
285 {
286         if (WARN(ring_rsp->rqid >= VSCSIIF_MAX_REQS ||
287                  test_bit(ring_rsp->rqid, info->shadow_free_bitmap),
288                  "illegal rqid %u returned by backend!\n", ring_rsp->rqid))
289                 return;
290
291         if (info->shadow[ring_rsp->rqid]->act == VSCSIIF_ACT_SCSI_CDB)
292                 scsifront_cdb_cmd_done(info, ring_rsp);
293         else
294                 scsifront_sync_cmd_done(info, ring_rsp);
295 }
296
297 static int scsifront_ring_drain(struct vscsifrnt_info *info)
298 {
299         struct vscsiif_response *ring_rsp;
300         RING_IDX i, rp;
301         int more_to_do = 0;
302
303         rp = info->ring.sring->rsp_prod;
304         rmb();  /* ordering required respective to dom0 */
305         for (i = info->ring.rsp_cons; i != rp; i++) {
306                 ring_rsp = RING_GET_RESPONSE(&info->ring, i);
307                 scsifront_do_response(info, ring_rsp);
308         }
309
310         info->ring.rsp_cons = i;
311
312         if (i != info->ring.req_prod_pvt)
313                 RING_FINAL_CHECK_FOR_RESPONSES(&info->ring, more_to_do);
314         else
315                 info->ring.sring->rsp_event = i + 1;
316
317         return more_to_do;
318 }
319
320 static int scsifront_cmd_done(struct vscsifrnt_info *info)
321 {
322         int more_to_do;
323         unsigned long flags;
324
325         spin_lock_irqsave(info->host->host_lock, flags);
326
327         more_to_do = scsifront_ring_drain(info);
328
329         info->wait_ring_available = 0;
330
331         spin_unlock_irqrestore(info->host->host_lock, flags);
332
333         wake_up(&info->wq_sync);
334
335         return more_to_do;
336 }
337
338 static irqreturn_t scsifront_irq_fn(int irq, void *dev_id)
339 {
340         struct vscsifrnt_info *info = dev_id;
341
342         while (scsifront_cmd_done(info))
343                 /* Yield point for this unbounded loop. */
344                 cond_resched();
345
346         return IRQ_HANDLED;
347 }
348
349 static void scsifront_finish_all(struct vscsifrnt_info *info)
350 {
351         unsigned i;
352         struct vscsiif_response resp;
353
354         scsifront_ring_drain(info);
355
356         for (i = 0; i < VSCSIIF_MAX_REQS; i++) {
357                 if (test_bit(i, info->shadow_free_bitmap))
358                         continue;
359                 resp.rqid = i;
360                 resp.sense_len = 0;
361                 resp.rslt = DID_RESET << 16;
362                 resp.residual_len = 0;
363                 scsifront_do_response(info, &resp);
364         }
365 }
366
367 static int map_data_for_request(struct vscsifrnt_info *info,
368                                 struct scsi_cmnd *sc,
369                                 struct vscsiif_request *ring_req,
370                                 struct vscsifrnt_shadow *shadow)
371 {
372         grant_ref_t gref_head;
373         struct page *page;
374         int err, ref, ref_cnt = 0;
375         int grant_ro = (sc->sc_data_direction == DMA_TO_DEVICE);
376         unsigned int i, off, len, bytes;
377         unsigned int data_len = scsi_bufflen(sc);
378         unsigned int data_grants = 0, seg_grants = 0;
379         struct scatterlist *sg;
380         unsigned long mfn;
381         struct scsiif_request_segment *seg;
382
383         ring_req->nr_segments = 0;
384         if (sc->sc_data_direction == DMA_NONE || !data_len)
385                 return 0;
386
387         scsi_for_each_sg(sc, sg, scsi_sg_count(sc), i)
388                 data_grants += PFN_UP(sg->offset + sg->length);
389
390         if (data_grants > VSCSIIF_SG_TABLESIZE) {
391                 if (data_grants > info->host->sg_tablesize) {
392                         shost_printk(KERN_ERR, info->host, KBUILD_MODNAME
393                              "Unable to map request_buffer for command!\n");
394                         return -E2BIG;
395                 }
396                 seg_grants = vscsiif_grants_sg(data_grants);
397                 shadow->sg = kcalloc(data_grants,
398                         sizeof(struct scsiif_request_segment), GFP_ATOMIC);
399                 if (!shadow->sg)
400                         return -ENOMEM;
401         }
402         seg = shadow->sg ? : ring_req->seg;
403
404         err = gnttab_alloc_grant_references(seg_grants + data_grants,
405                                             &gref_head);
406         if (err) {
407                 kfree(shadow->sg);
408                 shost_printk(KERN_ERR, info->host, KBUILD_MODNAME
409                              "gnttab_alloc_grant_references() error\n");
410                 return -ENOMEM;
411         }
412
413         if (seg_grants) {
414                 page = virt_to_page(seg);
415                 off = (unsigned long)seg & ~PAGE_MASK;
416                 len = sizeof(struct scsiif_request_segment) * data_grants;
417                 while (len > 0) {
418                         bytes = min_t(unsigned int, len, PAGE_SIZE - off);
419
420                         ref = gnttab_claim_grant_reference(&gref_head);
421                         BUG_ON(ref == -ENOSPC);
422
423                         mfn = pfn_to_mfn(page_to_pfn(page));
424                         gnttab_grant_foreign_access_ref(ref,
425                                 info->dev->otherend_id, mfn, 1);
426                         shadow->gref[ref_cnt] = ref;
427                         ring_req->seg[ref_cnt].gref   = ref;
428                         ring_req->seg[ref_cnt].offset = (uint16_t)off;
429                         ring_req->seg[ref_cnt].length = (uint16_t)bytes;
430
431                         page++;
432                         len -= bytes;
433                         off = 0;
434                         ref_cnt++;
435                 }
436                 BUG_ON(seg_grants < ref_cnt);
437                 seg_grants = ref_cnt;
438         }
439
440         scsi_for_each_sg(sc, sg, scsi_sg_count(sc), i) {
441                 page = sg_page(sg);
442                 off = sg->offset;
443                 len = sg->length;
444
445                 while (len > 0 && data_len > 0) {
446                         /*
447                          * sg sends a scatterlist that is larger than
448                          * the data_len it wants transferred for certain
449                          * IO sizes.
450                          */
451                         bytes = min_t(unsigned int, len, PAGE_SIZE - off);
452                         bytes = min(bytes, data_len);
453
454                         ref = gnttab_claim_grant_reference(&gref_head);
455                         BUG_ON(ref == -ENOSPC);
456
457                         mfn = pfn_to_mfn(page_to_pfn(page));
458                         gnttab_grant_foreign_access_ref(ref,
459                                 info->dev->otherend_id, mfn, grant_ro);
460
461                         shadow->gref[ref_cnt] = ref;
462                         seg->gref   = ref;
463                         seg->offset = (uint16_t)off;
464                         seg->length = (uint16_t)bytes;
465
466                         page++;
467                         seg++;
468                         len -= bytes;
469                         data_len -= bytes;
470                         off = 0;
471                         ref_cnt++;
472                 }
473         }
474
475         if (seg_grants)
476                 ring_req->nr_segments = VSCSIIF_SG_GRANT | seg_grants;
477         else
478                 ring_req->nr_segments = (uint8_t)ref_cnt;
479         shadow->nr_grants = ref_cnt;
480
481         return 0;
482 }
483
484 static struct vscsiif_request *scsifront_command2ring(
485                 struct vscsifrnt_info *info, struct scsi_cmnd *sc,
486                 struct vscsifrnt_shadow *shadow)
487 {
488         struct vscsiif_request *ring_req;
489
490         memset(shadow, 0, sizeof(*shadow));
491
492         ring_req = scsifront_pre_req(info);
493         if (!ring_req)
494                 return NULL;
495
496         info->shadow[ring_req->rqid] = shadow;
497         shadow->rqid = ring_req->rqid;
498
499         ring_req->id      = sc->device->id;
500         ring_req->lun     = sc->device->lun;
501         ring_req->channel = sc->device->channel;
502         ring_req->cmd_len = sc->cmd_len;
503
504         BUG_ON(sc->cmd_len > VSCSIIF_MAX_COMMAND_SIZE);
505
506         memcpy(ring_req->cmnd, sc->cmnd, sc->cmd_len);
507
508         ring_req->sc_data_direction   = (uint8_t)sc->sc_data_direction;
509         ring_req->timeout_per_command = sc->request->timeout / HZ;
510
511         return ring_req;
512 }
513
514 static int scsifront_enter(struct vscsifrnt_info *info)
515 {
516         if (info->pause)
517                 return 1;
518         info->callers++;
519         return 0;
520 }
521
522 static void scsifront_return(struct vscsifrnt_info *info)
523 {
524         info->callers--;
525         if (info->callers)
526                 return;
527
528         if (!info->waiting_pause)
529                 return;
530
531         info->waiting_pause = 0;
532         wake_up(&info->wq_pause);
533 }
534
535 static int scsifront_queuecommand(struct Scsi_Host *shost,
536                                   struct scsi_cmnd *sc)
537 {
538         struct vscsifrnt_info *info = shost_priv(shost);
539         struct vscsiif_request *ring_req;
540         struct vscsifrnt_shadow *shadow = scsi_cmd_priv(sc);
541         unsigned long flags;
542         int err;
543         uint16_t rqid;
544
545         spin_lock_irqsave(shost->host_lock, flags);
546         if (scsifront_enter(info)) {
547                 spin_unlock_irqrestore(shost->host_lock, flags);
548                 return SCSI_MLQUEUE_HOST_BUSY;
549         }
550         if (RING_FULL(&info->ring))
551                 goto busy;
552
553         ring_req = scsifront_command2ring(info, sc, shadow);
554         if (!ring_req)
555                 goto busy;
556
557         sc->result = 0;
558
559         rqid = ring_req->rqid;
560         ring_req->act = VSCSIIF_ACT_SCSI_CDB;
561
562         shadow->sc  = sc;
563         shadow->act = VSCSIIF_ACT_SCSI_CDB;
564
565         err = map_data_for_request(info, sc, ring_req, shadow);
566         if (err < 0) {
567                 pr_debug("%s: err %d\n", __func__, err);
568                 scsifront_put_rqid(info, rqid);
569                 scsifront_return(info);
570                 spin_unlock_irqrestore(shost->host_lock, flags);
571                 if (err == -ENOMEM)
572                         return SCSI_MLQUEUE_HOST_BUSY;
573                 sc->result = DID_ERROR << 16;
574                 sc->scsi_done(sc);
575                 return 0;
576         }
577
578         scsifront_do_request(info);
579         scsifront_return(info);
580         spin_unlock_irqrestore(shost->host_lock, flags);
581
582         return 0;
583
584 busy:
585         scsifront_return(info);
586         spin_unlock_irqrestore(shost->host_lock, flags);
587         pr_debug("%s: busy\n", __func__);
588         return SCSI_MLQUEUE_HOST_BUSY;
589 }
590
591 /*
592  * Any exception handling (reset or abort) must be forwarded to the backend.
593  * We have to wait until an answer is returned. This answer contains the
594  * result to be returned to the requestor.
595  */
596 static int scsifront_action_handler(struct scsi_cmnd *sc, uint8_t act)
597 {
598         struct Scsi_Host *host = sc->device->host;
599         struct vscsifrnt_info *info = shost_priv(host);
600         struct vscsifrnt_shadow *shadow, *s = scsi_cmd_priv(sc);
601         struct vscsiif_request *ring_req;
602         int err = 0;
603
604         shadow = kmalloc(sizeof(*shadow), GFP_NOIO);
605         if (!shadow)
606                 return FAILED;
607
608         spin_lock_irq(host->host_lock);
609
610         for (;;) {
611                 if (!RING_FULL(&info->ring)) {
612                         ring_req = scsifront_command2ring(info, sc, shadow);
613                         if (ring_req)
614                                 break;
615                 }
616                 if (err || info->pause) {
617                         spin_unlock_irq(host->host_lock);
618                         kfree(shadow);
619                         return FAILED;
620                 }
621                 info->wait_ring_available = 1;
622                 spin_unlock_irq(host->host_lock);
623                 err = wait_event_interruptible(info->wq_sync,
624                                                !info->wait_ring_available);
625                 spin_lock_irq(host->host_lock);
626         }
627
628         if (scsifront_enter(info)) {
629                 spin_unlock_irq(host->host_lock);
630                 return FAILED;
631         }
632
633         ring_req->act = act;
634         ring_req->ref_rqid = s->rqid;
635
636         shadow->act = act;
637         shadow->rslt_reset = RSLT_RESET_WAITING;
638         init_waitqueue_head(&shadow->wq_reset);
639
640         ring_req->nr_segments = 0;
641
642         scsifront_do_request(info);
643
644         spin_unlock_irq(host->host_lock);
645         err = wait_event_interruptible(shadow->wq_reset, shadow->wait_reset);
646         spin_lock_irq(host->host_lock);
647
648         if (!err) {
649                 err = shadow->rslt_reset;
650                 scsifront_put_rqid(info, shadow->rqid);
651                 kfree(shadow);
652         } else {
653                 spin_lock(&info->shadow_lock);
654                 shadow->rslt_reset = RSLT_RESET_ERR;
655                 spin_unlock(&info->shadow_lock);
656                 err = FAILED;
657         }
658
659         scsifront_return(info);
660         spin_unlock_irq(host->host_lock);
661         return err;
662 }
663
664 static int scsifront_eh_abort_handler(struct scsi_cmnd *sc)
665 {
666         pr_debug("%s\n", __func__);
667         return scsifront_action_handler(sc, VSCSIIF_ACT_SCSI_ABORT);
668 }
669
670 static int scsifront_dev_reset_handler(struct scsi_cmnd *sc)
671 {
672         pr_debug("%s\n", __func__);
673         return scsifront_action_handler(sc, VSCSIIF_ACT_SCSI_RESET);
674 }
675
676 static int scsifront_sdev_configure(struct scsi_device *sdev)
677 {
678         struct vscsifrnt_info *info = shost_priv(sdev->host);
679
680         if (info && current == info->curr)
681                 xenbus_printf(XBT_NIL, info->dev->nodename,
682                               info->dev_state_path, "%d", XenbusStateConnected);
683
684         return 0;
685 }
686
687 static void scsifront_sdev_destroy(struct scsi_device *sdev)
688 {
689         struct vscsifrnt_info *info = shost_priv(sdev->host);
690
691         if (info && current == info->curr)
692                 xenbus_printf(XBT_NIL, info->dev->nodename,
693                               info->dev_state_path, "%d", XenbusStateClosed);
694 }
695
696 static struct scsi_host_template scsifront_sht = {
697         .module                 = THIS_MODULE,
698         .name                   = "Xen SCSI frontend driver",
699         .queuecommand           = scsifront_queuecommand,
700         .eh_abort_handler       = scsifront_eh_abort_handler,
701         .eh_device_reset_handler = scsifront_dev_reset_handler,
702         .slave_configure        = scsifront_sdev_configure,
703         .slave_destroy          = scsifront_sdev_destroy,
704         .cmd_per_lun            = VSCSIIF_DEFAULT_CMD_PER_LUN,
705         .can_queue              = VSCSIIF_MAX_REQS,
706         .this_id                = -1,
707         .cmd_size               = sizeof(struct vscsifrnt_shadow),
708         .sg_tablesize           = VSCSIIF_SG_TABLESIZE,
709         .use_clustering         = DISABLE_CLUSTERING,
710         .proc_name              = "scsifront",
711 };
712
713 static int scsifront_alloc_ring(struct vscsifrnt_info *info)
714 {
715         struct xenbus_device *dev = info->dev;
716         struct vscsiif_sring *sring;
717         int err = -ENOMEM;
718
719         /***** Frontend to Backend ring start *****/
720         sring = (struct vscsiif_sring *)__get_free_page(GFP_KERNEL);
721         if (!sring) {
722                 xenbus_dev_fatal(dev, err,
723                         "fail to allocate shared ring (Front to Back)");
724                 return err;
725         }
726         SHARED_RING_INIT(sring);
727         FRONT_RING_INIT(&info->ring, sring, PAGE_SIZE);
728
729         err = xenbus_grant_ring(dev, virt_to_mfn(sring));
730         if (err < 0) {
731                 free_page((unsigned long)sring);
732                 xenbus_dev_fatal(dev, err,
733                         "fail to grant shared ring (Front to Back)");
734                 return err;
735         }
736         info->ring_ref = err;
737
738         err = xenbus_alloc_evtchn(dev, &info->evtchn);
739         if (err) {
740                 xenbus_dev_fatal(dev, err, "xenbus_alloc_evtchn");
741                 goto free_gnttab;
742         }
743
744         err = bind_evtchn_to_irq(info->evtchn);
745         if (err <= 0) {
746                 xenbus_dev_fatal(dev, err, "bind_evtchn_to_irq");
747                 goto free_gnttab;
748         }
749
750         info->irq = err;
751
752         err = request_threaded_irq(info->irq, NULL, scsifront_irq_fn,
753                                    IRQF_ONESHOT, "scsifront", info);
754         if (err) {
755                 xenbus_dev_fatal(dev, err, "request_threaded_irq");
756                 goto free_irq;
757         }
758
759         return 0;
760
761 /* free resource */
762 free_irq:
763         unbind_from_irqhandler(info->irq, info);
764 free_gnttab:
765         gnttab_end_foreign_access(info->ring_ref, 0,
766                                   (unsigned long)info->ring.sring);
767
768         return err;
769 }
770
771 static void scsifront_free_ring(struct vscsifrnt_info *info)
772 {
773         unbind_from_irqhandler(info->irq, info);
774         gnttab_end_foreign_access(info->ring_ref, 0,
775                                   (unsigned long)info->ring.sring);
776 }
777
778 static int scsifront_init_ring(struct vscsifrnt_info *info)
779 {
780         struct xenbus_device *dev = info->dev;
781         struct xenbus_transaction xbt;
782         int err;
783
784         pr_debug("%s\n", __func__);
785
786         err = scsifront_alloc_ring(info);
787         if (err)
788                 return err;
789         pr_debug("%s: %u %u\n", __func__, info->ring_ref, info->evtchn);
790
791 again:
792         err = xenbus_transaction_start(&xbt);
793         if (err)
794                 xenbus_dev_fatal(dev, err, "starting transaction");
795
796         err = xenbus_printf(xbt, dev->nodename, "ring-ref", "%u",
797                             info->ring_ref);
798         if (err) {
799                 xenbus_dev_fatal(dev, err, "%s", "writing ring-ref");
800                 goto fail;
801         }
802
803         err = xenbus_printf(xbt, dev->nodename, "event-channel", "%u",
804                             info->evtchn);
805
806         if (err) {
807                 xenbus_dev_fatal(dev, err, "%s", "writing event-channel");
808                 goto fail;
809         }
810
811         err = xenbus_transaction_end(xbt, 0);
812         if (err) {
813                 if (err == -EAGAIN)
814                         goto again;
815                 xenbus_dev_fatal(dev, err, "completing transaction");
816                 goto free_sring;
817         }
818
819         return 0;
820
821 fail:
822         xenbus_transaction_end(xbt, 1);
823 free_sring:
824         scsifront_free_ring(info);
825
826         return err;
827 }
828
829
830 static int scsifront_probe(struct xenbus_device *dev,
831                            const struct xenbus_device_id *id)
832 {
833         struct vscsifrnt_info *info;
834         struct Scsi_Host *host;
835         int err = -ENOMEM;
836         char name[TASK_COMM_LEN];
837
838         host = scsi_host_alloc(&scsifront_sht, sizeof(*info));
839         if (!host) {
840                 xenbus_dev_fatal(dev, err, "fail to allocate scsi host");
841                 return err;
842         }
843         info = (struct vscsifrnt_info *)host->hostdata;
844
845         dev_set_drvdata(&dev->dev, info);
846         info->dev = dev;
847
848         bitmap_fill(info->shadow_free_bitmap, VSCSIIF_MAX_REQS);
849
850         err = scsifront_init_ring(info);
851         if (err) {
852                 scsi_host_put(host);
853                 return err;
854         }
855
856         init_waitqueue_head(&info->wq_sync);
857         init_waitqueue_head(&info->wq_pause);
858         spin_lock_init(&info->shadow_lock);
859
860         snprintf(name, TASK_COMM_LEN, "vscsiif.%d", host->host_no);
861
862         host->max_id      = VSCSIIF_MAX_TARGET;
863         host->max_channel = 0;
864         host->max_lun     = VSCSIIF_MAX_LUN;
865         host->max_sectors = (host->sg_tablesize - 1) * PAGE_SIZE / 512;
866         host->max_cmd_len = VSCSIIF_MAX_COMMAND_SIZE;
867
868         err = scsi_add_host(host, &dev->dev);
869         if (err) {
870                 dev_err(&dev->dev, "fail to add scsi host %d\n", err);
871                 goto free_sring;
872         }
873         info->host = host;
874         info->host_active = 1;
875
876         xenbus_switch_state(dev, XenbusStateInitialised);
877
878         return 0;
879
880 free_sring:
881         scsifront_free_ring(info);
882         scsi_host_put(host);
883         return err;
884 }
885
886 static int scsifront_resume(struct xenbus_device *dev)
887 {
888         struct vscsifrnt_info *info = dev_get_drvdata(&dev->dev);
889         struct Scsi_Host *host = info->host;
890         int err;
891
892         spin_lock_irq(host->host_lock);
893
894         /* Finish all still pending commands. */
895         scsifront_finish_all(info);
896
897         spin_unlock_irq(host->host_lock);
898
899         /* Reconnect to dom0. */
900         scsifront_free_ring(info);
901         err = scsifront_init_ring(info);
902         if (err) {
903                 dev_err(&dev->dev, "fail to resume %d\n", err);
904                 scsi_host_put(host);
905                 return err;
906         }
907
908         xenbus_switch_state(dev, XenbusStateInitialised);
909
910         return 0;
911 }
912
913 static int scsifront_suspend(struct xenbus_device *dev)
914 {
915         struct vscsifrnt_info *info = dev_get_drvdata(&dev->dev);
916         struct Scsi_Host *host = info->host;
917         int err = 0;
918
919         /* No new commands for the backend. */
920         spin_lock_irq(host->host_lock);
921         info->pause = 1;
922         while (info->callers && !err) {
923                 info->waiting_pause = 1;
924                 info->wait_ring_available = 0;
925                 spin_unlock_irq(host->host_lock);
926                 wake_up(&info->wq_sync);
927                 err = wait_event_interruptible(info->wq_pause,
928                                                !info->waiting_pause);
929                 spin_lock_irq(host->host_lock);
930         }
931         spin_unlock_irq(host->host_lock);
932         return err;
933 }
934
935 static int scsifront_remove(struct xenbus_device *dev)
936 {
937         struct vscsifrnt_info *info = dev_get_drvdata(&dev->dev);
938
939         pr_debug("%s: %s removed\n", __func__, dev->nodename);
940
941         mutex_lock(&scsifront_mutex);
942         if (info->host_active) {
943                 /* Scsi_host not yet removed */
944                 scsi_remove_host(info->host);
945                 info->host_active = 0;
946         }
947         mutex_unlock(&scsifront_mutex);
948
949         scsifront_free_ring(info);
950         scsi_host_put(info->host);
951
952         return 0;
953 }
954
955 static void scsifront_disconnect(struct vscsifrnt_info *info)
956 {
957         struct xenbus_device *dev = info->dev;
958         struct Scsi_Host *host = info->host;
959
960         pr_debug("%s: %s disconnect\n", __func__, dev->nodename);
961
962         /*
963          * When this function is executed, all devices of
964          * Frontend have been deleted.
965          * Therefore, it need not block I/O before remove_host.
966          */
967
968         mutex_lock(&scsifront_mutex);
969         if (info->host_active) {
970                 scsi_remove_host(host);
971                 info->host_active = 0;
972         }
973         mutex_unlock(&scsifront_mutex);
974
975         xenbus_frontend_closed(dev);
976 }
977
978 static void scsifront_do_lun_hotplug(struct vscsifrnt_info *info, int op)
979 {
980         struct xenbus_device *dev = info->dev;
981         int i, err = 0;
982         char str[64];
983         char **dir;
984         unsigned int dir_n = 0;
985         unsigned int device_state;
986         unsigned int hst, chn, tgt, lun;
987         struct scsi_device *sdev;
988
989         dir = xenbus_directory(XBT_NIL, dev->otherend, "vscsi-devs", &dir_n);
990         if (IS_ERR(dir))
991                 return;
992
993         /* mark current task as the one allowed to modify device states */
994         BUG_ON(info->curr);
995         info->curr = current;
996
997         for (i = 0; i < dir_n; i++) {
998                 /* read status */
999                 snprintf(str, sizeof(str), "vscsi-devs/%s/state", dir[i]);
1000                 err = xenbus_scanf(XBT_NIL, dev->otherend, str, "%u",
1001                                    &device_state);
1002                 if (XENBUS_EXIST_ERR(err))
1003                         continue;
1004
1005                 /* virtual SCSI device */
1006                 snprintf(str, sizeof(str), "vscsi-devs/%s/v-dev", dir[i]);
1007                 err = xenbus_scanf(XBT_NIL, dev->otherend, str,
1008                                    "%u:%u:%u:%u", &hst, &chn, &tgt, &lun);
1009                 if (XENBUS_EXIST_ERR(err))
1010                         continue;
1011
1012                 /*
1013                  * Front device state path, used in slave_configure called
1014                  * on successfull scsi_add_device, and in slave_destroy called
1015                  * on remove of a device.
1016                  */
1017                 snprintf(info->dev_state_path, sizeof(info->dev_state_path),
1018                          "vscsi-devs/%s/state", dir[i]);
1019
1020                 switch (op) {
1021                 case VSCSIFRONT_OP_ADD_LUN:
1022                         if (device_state != XenbusStateInitialised)
1023                                 break;
1024
1025                         if (scsi_add_device(info->host, chn, tgt, lun)) {
1026                                 dev_err(&dev->dev, "scsi_add_device\n");
1027                                 xenbus_printf(XBT_NIL, dev->nodename,
1028                                               info->dev_state_path,
1029                                               "%d", XenbusStateClosed);
1030                         }
1031                         break;
1032                 case VSCSIFRONT_OP_DEL_LUN:
1033                         if (device_state != XenbusStateClosing)
1034                                 break;
1035
1036                         sdev = scsi_device_lookup(info->host, chn, tgt, lun);
1037                         if (sdev) {
1038                                 scsi_remove_device(sdev);
1039                                 scsi_device_put(sdev);
1040                         }
1041                         break;
1042                 case VSCSIFRONT_OP_READD_LUN:
1043                         if (device_state == XenbusStateConnected)
1044                                 xenbus_printf(XBT_NIL, dev->nodename,
1045                                               info->dev_state_path,
1046                                               "%d", XenbusStateConnected);
1047                         break;
1048                 default:
1049                         break;
1050                 }
1051         }
1052
1053         info->curr = NULL;
1054
1055         kfree(dir);
1056 }
1057
1058 static void scsifront_read_backend_params(struct xenbus_device *dev,
1059                                           struct vscsifrnt_info *info)
1060 {
1061         unsigned int sg_grant, nr_segs;
1062         int ret;
1063         struct Scsi_Host *host = info->host;
1064
1065         ret = xenbus_scanf(XBT_NIL, dev->otherend, "feature-sg-grant", "%u",
1066                            &sg_grant);
1067         if (ret != 1)
1068                 sg_grant = 0;
1069         nr_segs = min_t(unsigned int, sg_grant, SG_ALL);
1070         nr_segs = max_t(unsigned int, nr_segs, VSCSIIF_SG_TABLESIZE);
1071         nr_segs = min_t(unsigned int, nr_segs,
1072                         VSCSIIF_SG_TABLESIZE * PAGE_SIZE /
1073                         sizeof(struct scsiif_request_segment));
1074
1075         if (!info->pause && sg_grant)
1076                 dev_info(&dev->dev, "using up to %d SG entries\n", nr_segs);
1077         else if (info->pause && nr_segs < host->sg_tablesize)
1078                 dev_warn(&dev->dev,
1079                          "SG entries decreased from %d to %u - device may not work properly anymore\n",
1080                          host->sg_tablesize, nr_segs);
1081
1082         host->sg_tablesize = nr_segs;
1083         host->max_sectors = (nr_segs - 1) * PAGE_SIZE / 512;
1084 }
1085
1086 static void scsifront_backend_changed(struct xenbus_device *dev,
1087                                       enum xenbus_state backend_state)
1088 {
1089         struct vscsifrnt_info *info = dev_get_drvdata(&dev->dev);
1090
1091         pr_debug("%s: %p %u %u\n", __func__, dev, dev->state, backend_state);
1092
1093         switch (backend_state) {
1094         case XenbusStateUnknown:
1095         case XenbusStateInitialising:
1096         case XenbusStateInitWait:
1097         case XenbusStateInitialised:
1098                 break;
1099
1100         case XenbusStateConnected:
1101                 scsifront_read_backend_params(dev, info);
1102
1103                 if (info->pause) {
1104                         scsifront_do_lun_hotplug(info, VSCSIFRONT_OP_READD_LUN);
1105                         xenbus_switch_state(dev, XenbusStateConnected);
1106                         info->pause = 0;
1107                         return;
1108                 }
1109
1110                 if (xenbus_read_driver_state(dev->nodename) ==
1111                     XenbusStateInitialised)
1112                         scsifront_do_lun_hotplug(info, VSCSIFRONT_OP_ADD_LUN);
1113
1114                 if (dev->state != XenbusStateConnected)
1115                         xenbus_switch_state(dev, XenbusStateConnected);
1116                 break;
1117
1118         case XenbusStateClosed:
1119                 if (dev->state == XenbusStateClosed)
1120                         break;
1121                 /* Missed the backend's Closing state -- fallthrough */
1122         case XenbusStateClosing:
1123                 scsifront_disconnect(info);
1124                 break;
1125
1126         case XenbusStateReconfiguring:
1127                 scsifront_do_lun_hotplug(info, VSCSIFRONT_OP_DEL_LUN);
1128                 xenbus_switch_state(dev, XenbusStateReconfiguring);
1129                 break;
1130
1131         case XenbusStateReconfigured:
1132                 scsifront_do_lun_hotplug(info, VSCSIFRONT_OP_ADD_LUN);
1133                 xenbus_switch_state(dev, XenbusStateConnected);
1134                 break;
1135         }
1136 }
1137
1138 static const struct xenbus_device_id scsifront_ids[] = {
1139         { "vscsi" },
1140         { "" }
1141 };
1142
1143 static struct xenbus_driver scsifront_driver = {
1144         .ids                    = scsifront_ids,
1145         .probe                  = scsifront_probe,
1146         .remove                 = scsifront_remove,
1147         .resume                 = scsifront_resume,
1148         .suspend                = scsifront_suspend,
1149         .otherend_changed       = scsifront_backend_changed,
1150 };
1151
1152 static int __init scsifront_init(void)
1153 {
1154         if (!xen_domain())
1155                 return -ENODEV;
1156
1157         return xenbus_register_frontend(&scsifront_driver);
1158 }
1159 module_init(scsifront_init);
1160
1161 static void __exit scsifront_exit(void)
1162 {
1163         xenbus_unregister_driver(&scsifront_driver);
1164 }
1165 module_exit(scsifront_exit);
1166
1167 MODULE_DESCRIPTION("Xen SCSI frontend driver");
1168 MODULE_LICENSE("GPL");
1169 MODULE_ALIAS("xen:vscsi");
1170 MODULE_AUTHOR("Juergen Gross <jgross@suse.com>");