scsi: virtio_scsi: Remove duplicate check if queue is broken
[linux-block.git] / drivers / scsi / virtio_scsi.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Virtio SCSI HBA driver
4  *
5  * Copyright IBM Corp. 2010
6  * Copyright Red Hat, Inc. 2011
7  *
8  * Authors:
9  *  Stefan Hajnoczi   <stefanha@linux.vnet.ibm.com>
10  *  Paolo Bonzini   <pbonzini@redhat.com>
11  */
12
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14
15 #include <linux/module.h>
16 #include <linux/slab.h>
17 #include <linux/mempool.h>
18 #include <linux/interrupt.h>
19 #include <linux/virtio.h>
20 #include <linux/virtio_ids.h>
21 #include <linux/virtio_config.h>
22 #include <linux/virtio_scsi.h>
23 #include <linux/cpu.h>
24 #include <linux/blkdev.h>
25 #include <linux/blk-integrity.h>
26 #include <scsi/scsi_host.h>
27 #include <scsi/scsi_device.h>
28 #include <scsi/scsi_cmnd.h>
29 #include <scsi/scsi_tcq.h>
30 #include <scsi/scsi_devinfo.h>
31 #include <linux/seqlock.h>
32 #include <linux/blk-mq-virtio.h>
33
34 #include "sd.h"
35
36 #define VIRTIO_SCSI_MEMPOOL_SZ 64
37 #define VIRTIO_SCSI_EVENT_LEN 8
38 #define VIRTIO_SCSI_VQ_BASE 2
39
40 /* Command queue element */
41 struct virtio_scsi_cmd {
42         struct scsi_cmnd *sc;
43         struct completion *comp;
44         union {
45                 struct virtio_scsi_cmd_req       cmd;
46                 struct virtio_scsi_cmd_req_pi    cmd_pi;
47                 struct virtio_scsi_ctrl_tmf_req  tmf;
48                 struct virtio_scsi_ctrl_an_req   an;
49         } req;
50         union {
51                 struct virtio_scsi_cmd_resp      cmd;
52                 struct virtio_scsi_ctrl_tmf_resp tmf;
53                 struct virtio_scsi_ctrl_an_resp  an;
54                 struct virtio_scsi_event         evt;
55         } resp;
56 } ____cacheline_aligned_in_smp;
57
58 struct virtio_scsi_event_node {
59         struct virtio_scsi *vscsi;
60         struct virtio_scsi_event event;
61         struct work_struct work;
62 };
63
64 struct virtio_scsi_vq {
65         /* Protects vq */
66         spinlock_t vq_lock;
67
68         struct virtqueue *vq;
69 };
70
71 /* Driver instance state */
72 struct virtio_scsi {
73         struct virtio_device *vdev;
74
75         /* Get some buffers ready for event vq */
76         struct virtio_scsi_event_node event_list[VIRTIO_SCSI_EVENT_LEN];
77
78         u32 num_queues;
79
80         struct hlist_node node;
81
82         /* Protected by event_vq lock */
83         bool stop_events;
84
85         struct virtio_scsi_vq ctrl_vq;
86         struct virtio_scsi_vq event_vq;
87         struct virtio_scsi_vq req_vqs[];
88 };
89
90 static struct kmem_cache *virtscsi_cmd_cache;
91 static mempool_t *virtscsi_cmd_pool;
92
93 static inline struct Scsi_Host *virtio_scsi_host(struct virtio_device *vdev)
94 {
95         return vdev->priv;
96 }
97
98 static void virtscsi_compute_resid(struct scsi_cmnd *sc, u32 resid)
99 {
100         if (resid)
101                 scsi_set_resid(sc, min(resid, scsi_bufflen(sc)));
102 }
103
104 /*
105  * virtscsi_complete_cmd - finish a scsi_cmd and invoke scsi_done
106  *
107  * Called with vq_lock held.
108  */
109 static void virtscsi_complete_cmd(struct virtio_scsi *vscsi, void *buf)
110 {
111         struct virtio_scsi_cmd *cmd = buf;
112         struct scsi_cmnd *sc = cmd->sc;
113         struct virtio_scsi_cmd_resp *resp = &cmd->resp.cmd;
114
115         dev_dbg(&sc->device->sdev_gendev,
116                 "cmd %p response %u status %#02x sense_len %u\n",
117                 sc, resp->response, resp->status, resp->sense_len);
118
119         sc->result = resp->status;
120         virtscsi_compute_resid(sc, virtio32_to_cpu(vscsi->vdev, resp->resid));
121         switch (resp->response) {
122         case VIRTIO_SCSI_S_OK:
123                 set_host_byte(sc, DID_OK);
124                 break;
125         case VIRTIO_SCSI_S_OVERRUN:
126                 set_host_byte(sc, DID_ERROR);
127                 break;
128         case VIRTIO_SCSI_S_ABORTED:
129                 set_host_byte(sc, DID_ABORT);
130                 break;
131         case VIRTIO_SCSI_S_BAD_TARGET:
132                 set_host_byte(sc, DID_BAD_TARGET);
133                 break;
134         case VIRTIO_SCSI_S_RESET:
135                 set_host_byte(sc, DID_RESET);
136                 break;
137         case VIRTIO_SCSI_S_BUSY:
138                 set_host_byte(sc, DID_BUS_BUSY);
139                 break;
140         case VIRTIO_SCSI_S_TRANSPORT_FAILURE:
141                 set_host_byte(sc, DID_TRANSPORT_DISRUPTED);
142                 break;
143         case VIRTIO_SCSI_S_TARGET_FAILURE:
144                 set_host_byte(sc, DID_BAD_TARGET);
145                 break;
146         case VIRTIO_SCSI_S_NEXUS_FAILURE:
147                 set_status_byte(sc, SAM_STAT_RESERVATION_CONFLICT);
148                 break;
149         default:
150                 scmd_printk(KERN_WARNING, sc, "Unknown response %d",
151                             resp->response);
152                 fallthrough;
153         case VIRTIO_SCSI_S_FAILURE:
154                 set_host_byte(sc, DID_ERROR);
155                 break;
156         }
157
158         WARN_ON(virtio32_to_cpu(vscsi->vdev, resp->sense_len) >
159                 VIRTIO_SCSI_SENSE_SIZE);
160         if (resp->sense_len) {
161                 memcpy(sc->sense_buffer, resp->sense,
162                        min_t(u32,
163                              virtio32_to_cpu(vscsi->vdev, resp->sense_len),
164                              VIRTIO_SCSI_SENSE_SIZE));
165         }
166
167         scsi_done(sc);
168 }
169
170 static void virtscsi_vq_done(struct virtio_scsi *vscsi,
171                              struct virtio_scsi_vq *virtscsi_vq,
172                              void (*fn)(struct virtio_scsi *vscsi, void *buf))
173 {
174         void *buf;
175         unsigned int len;
176         unsigned long flags;
177         struct virtqueue *vq = virtscsi_vq->vq;
178
179         spin_lock_irqsave(&virtscsi_vq->vq_lock, flags);
180         do {
181                 virtqueue_disable_cb(vq);
182                 while ((buf = virtqueue_get_buf(vq, &len)) != NULL)
183                         fn(vscsi, buf);
184
185         } while (!virtqueue_enable_cb(vq));
186         spin_unlock_irqrestore(&virtscsi_vq->vq_lock, flags);
187 }
188
189 static void virtscsi_req_done(struct virtqueue *vq)
190 {
191         struct Scsi_Host *sh = virtio_scsi_host(vq->vdev);
192         struct virtio_scsi *vscsi = shost_priv(sh);
193         int index = vq->index - VIRTIO_SCSI_VQ_BASE;
194         struct virtio_scsi_vq *req_vq = &vscsi->req_vqs[index];
195
196         virtscsi_vq_done(vscsi, req_vq, virtscsi_complete_cmd);
197 };
198
199 static void virtscsi_poll_requests(struct virtio_scsi *vscsi)
200 {
201         int i, num_vqs;
202
203         num_vqs = vscsi->num_queues;
204         for (i = 0; i < num_vqs; i++)
205                 virtscsi_vq_done(vscsi, &vscsi->req_vqs[i],
206                                  virtscsi_complete_cmd);
207 }
208
209 static void virtscsi_complete_free(struct virtio_scsi *vscsi, void *buf)
210 {
211         struct virtio_scsi_cmd *cmd = buf;
212
213         if (cmd->comp)
214                 complete(cmd->comp);
215 }
216
217 static void virtscsi_ctrl_done(struct virtqueue *vq)
218 {
219         struct Scsi_Host *sh = virtio_scsi_host(vq->vdev);
220         struct virtio_scsi *vscsi = shost_priv(sh);
221
222         virtscsi_vq_done(vscsi, &vscsi->ctrl_vq, virtscsi_complete_free);
223 };
224
225 static void virtscsi_handle_event(struct work_struct *work);
226
227 static int virtscsi_kick_event(struct virtio_scsi *vscsi,
228                                struct virtio_scsi_event_node *event_node)
229 {
230         int err;
231         struct scatterlist sg;
232         unsigned long flags;
233
234         INIT_WORK(&event_node->work, virtscsi_handle_event);
235         sg_init_one(&sg, &event_node->event, sizeof(struct virtio_scsi_event));
236
237         spin_lock_irqsave(&vscsi->event_vq.vq_lock, flags);
238
239         err = virtqueue_add_inbuf(vscsi->event_vq.vq, &sg, 1, event_node,
240                                   GFP_ATOMIC);
241         if (!err)
242                 virtqueue_kick(vscsi->event_vq.vq);
243
244         spin_unlock_irqrestore(&vscsi->event_vq.vq_lock, flags);
245
246         return err;
247 }
248
249 static int virtscsi_kick_event_all(struct virtio_scsi *vscsi)
250 {
251         int i;
252
253         for (i = 0; i < VIRTIO_SCSI_EVENT_LEN; i++) {
254                 vscsi->event_list[i].vscsi = vscsi;
255                 virtscsi_kick_event(vscsi, &vscsi->event_list[i]);
256         }
257
258         return 0;
259 }
260
261 static void virtscsi_cancel_event_work(struct virtio_scsi *vscsi)
262 {
263         int i;
264
265         /* Stop scheduling work before calling cancel_work_sync.  */
266         spin_lock_irq(&vscsi->event_vq.vq_lock);
267         vscsi->stop_events = true;
268         spin_unlock_irq(&vscsi->event_vq.vq_lock);
269
270         for (i = 0; i < VIRTIO_SCSI_EVENT_LEN; i++)
271                 cancel_work_sync(&vscsi->event_list[i].work);
272 }
273
274 static void virtscsi_handle_transport_reset(struct virtio_scsi *vscsi,
275                                             struct virtio_scsi_event *event)
276 {
277         struct scsi_device *sdev;
278         struct Scsi_Host *shost = virtio_scsi_host(vscsi->vdev);
279         unsigned int target = event->lun[1];
280         unsigned int lun = (event->lun[2] << 8) | event->lun[3];
281
282         switch (virtio32_to_cpu(vscsi->vdev, event->reason)) {
283         case VIRTIO_SCSI_EVT_RESET_RESCAN:
284                 if (lun == 0) {
285                         scsi_scan_target(&shost->shost_gendev, 0, target,
286                                          SCAN_WILD_CARD, SCSI_SCAN_INITIAL);
287                 } else {
288                         scsi_add_device(shost, 0, target, lun);
289                 }
290                 break;
291         case VIRTIO_SCSI_EVT_RESET_REMOVED:
292                 sdev = scsi_device_lookup(shost, 0, target, lun);
293                 if (sdev) {
294                         scsi_remove_device(sdev);
295                         scsi_device_put(sdev);
296                 } else {
297                         pr_err("SCSI device %d 0 %d %d not found\n",
298                                 shost->host_no, target, lun);
299                 }
300                 break;
301         default:
302                 pr_info("Unsupported virtio scsi event reason %x\n", event->reason);
303         }
304 }
305
306 static void virtscsi_handle_param_change(struct virtio_scsi *vscsi,
307                                          struct virtio_scsi_event *event)
308 {
309         struct scsi_device *sdev;
310         struct Scsi_Host *shost = virtio_scsi_host(vscsi->vdev);
311         unsigned int target = event->lun[1];
312         unsigned int lun = (event->lun[2] << 8) | event->lun[3];
313         u8 asc = virtio32_to_cpu(vscsi->vdev, event->reason) & 255;
314         u8 ascq = virtio32_to_cpu(vscsi->vdev, event->reason) >> 8;
315
316         sdev = scsi_device_lookup(shost, 0, target, lun);
317         if (!sdev) {
318                 pr_err("SCSI device %d 0 %d %d not found\n",
319                         shost->host_no, target, lun);
320                 return;
321         }
322
323         /* Handle "Parameters changed", "Mode parameters changed", and
324            "Capacity data has changed".  */
325         if (asc == 0x2a && (ascq == 0x00 || ascq == 0x01 || ascq == 0x09))
326                 scsi_rescan_device(sdev);
327
328         scsi_device_put(sdev);
329 }
330
331 static int virtscsi_rescan_hotunplug(struct virtio_scsi *vscsi)
332 {
333         struct scsi_device *sdev;
334         struct Scsi_Host *shost = virtio_scsi_host(vscsi->vdev);
335         unsigned char scsi_cmd[MAX_COMMAND_SIZE];
336         int result, inquiry_len, inq_result_len = 256;
337         char *inq_result = kmalloc(inq_result_len, GFP_KERNEL);
338
339         if (!inq_result)
340                 return -ENOMEM;
341
342         shost_for_each_device(sdev, shost) {
343                 inquiry_len = sdev->inquiry_len ? sdev->inquiry_len : 36;
344
345                 memset(scsi_cmd, 0, sizeof(scsi_cmd));
346                 scsi_cmd[0] = INQUIRY;
347                 scsi_cmd[4] = (unsigned char) inquiry_len;
348
349                 memset(inq_result, 0, inq_result_len);
350
351                 result = scsi_execute_cmd(sdev, scsi_cmd, REQ_OP_DRV_IN,
352                                           inq_result, inquiry_len,
353                                           SD_TIMEOUT, SD_MAX_RETRIES, NULL);
354
355                 if (result == 0 && inq_result[0] >> 5) {
356                         /* PQ indicates the LUN is not attached */
357                         scsi_remove_device(sdev);
358                 } else if (result > 0 && host_byte(result) == DID_BAD_TARGET) {
359                         /*
360                          * If all LUNs of a virtio-scsi device are unplugged
361                          * it will respond with BAD TARGET on any INQUIRY
362                          * command.
363                          * Remove the device in this case as well.
364                          */
365                         scsi_remove_device(sdev);
366                 }
367         }
368
369         kfree(inq_result);
370         return 0;
371 }
372
373 static void virtscsi_handle_event(struct work_struct *work)
374 {
375         struct virtio_scsi_event_node *event_node =
376                 container_of(work, struct virtio_scsi_event_node, work);
377         struct virtio_scsi *vscsi = event_node->vscsi;
378         struct virtio_scsi_event *event = &event_node->event;
379
380         if (event->event &
381             cpu_to_virtio32(vscsi->vdev, VIRTIO_SCSI_T_EVENTS_MISSED)) {
382                 int ret;
383
384                 event->event &= ~cpu_to_virtio32(vscsi->vdev,
385                                                    VIRTIO_SCSI_T_EVENTS_MISSED);
386                 ret = virtscsi_rescan_hotunplug(vscsi);
387                 if (ret)
388                         return;
389                 scsi_scan_host(virtio_scsi_host(vscsi->vdev));
390         }
391
392         switch (virtio32_to_cpu(vscsi->vdev, event->event)) {
393         case VIRTIO_SCSI_T_NO_EVENT:
394                 break;
395         case VIRTIO_SCSI_T_TRANSPORT_RESET:
396                 virtscsi_handle_transport_reset(vscsi, event);
397                 break;
398         case VIRTIO_SCSI_T_PARAM_CHANGE:
399                 virtscsi_handle_param_change(vscsi, event);
400                 break;
401         default:
402                 pr_err("Unsupported virtio scsi event %x\n", event->event);
403         }
404         virtscsi_kick_event(vscsi, event_node);
405 }
406
407 static void virtscsi_complete_event(struct virtio_scsi *vscsi, void *buf)
408 {
409         struct virtio_scsi_event_node *event_node = buf;
410
411         if (!vscsi->stop_events)
412                 queue_work(system_freezable_wq, &event_node->work);
413 }
414
415 static void virtscsi_event_done(struct virtqueue *vq)
416 {
417         struct Scsi_Host *sh = virtio_scsi_host(vq->vdev);
418         struct virtio_scsi *vscsi = shost_priv(sh);
419
420         virtscsi_vq_done(vscsi, &vscsi->event_vq, virtscsi_complete_event);
421 };
422
423 static int __virtscsi_add_cmd(struct virtqueue *vq,
424                             struct virtio_scsi_cmd *cmd,
425                             size_t req_size, size_t resp_size)
426 {
427         struct scsi_cmnd *sc = cmd->sc;
428         struct scatterlist *sgs[6], req, resp;
429         struct sg_table *out, *in;
430         unsigned out_num = 0, in_num = 0;
431
432         out = in = NULL;
433
434         if (sc && sc->sc_data_direction != DMA_NONE) {
435                 if (sc->sc_data_direction != DMA_FROM_DEVICE)
436                         out = &sc->sdb.table;
437                 if (sc->sc_data_direction != DMA_TO_DEVICE)
438                         in = &sc->sdb.table;
439         }
440
441         /* Request header.  */
442         sg_init_one(&req, &cmd->req, req_size);
443         sgs[out_num++] = &req;
444
445         /* Data-out buffer.  */
446         if (out) {
447                 /* Place WRITE protection SGLs before Data OUT payload */
448                 if (scsi_prot_sg_count(sc))
449                         sgs[out_num++] = scsi_prot_sglist(sc);
450                 sgs[out_num++] = out->sgl;
451         }
452
453         /* Response header.  */
454         sg_init_one(&resp, &cmd->resp, resp_size);
455         sgs[out_num + in_num++] = &resp;
456
457         /* Data-in buffer */
458         if (in) {
459                 /* Place READ protection SGLs before Data IN payload */
460                 if (scsi_prot_sg_count(sc))
461                         sgs[out_num + in_num++] = scsi_prot_sglist(sc);
462                 sgs[out_num + in_num++] = in->sgl;
463         }
464
465         return virtqueue_add_sgs(vq, sgs, out_num, in_num, cmd, GFP_ATOMIC);
466 }
467
468 static void virtscsi_kick_vq(struct virtio_scsi_vq *vq)
469 {
470         bool needs_kick;
471         unsigned long flags;
472
473         spin_lock_irqsave(&vq->vq_lock, flags);
474         needs_kick = virtqueue_kick_prepare(vq->vq);
475         spin_unlock_irqrestore(&vq->vq_lock, flags);
476
477         if (needs_kick)
478                 virtqueue_notify(vq->vq);
479 }
480
481 /**
482  * virtscsi_add_cmd - add a virtio_scsi_cmd to a virtqueue, optionally kick it
483  * @vq          : the struct virtqueue we're talking about
484  * @cmd         : command structure
485  * @req_size    : size of the request buffer
486  * @resp_size   : size of the response buffer
487  * @kick        : whether to kick the virtqueue immediately
488  */
489 static int virtscsi_add_cmd(struct virtio_scsi_vq *vq,
490                              struct virtio_scsi_cmd *cmd,
491                              size_t req_size, size_t resp_size,
492                              bool kick)
493 {
494         unsigned long flags;
495         int err;
496         bool needs_kick = false;
497
498         spin_lock_irqsave(&vq->vq_lock, flags);
499         err = __virtscsi_add_cmd(vq->vq, cmd, req_size, resp_size);
500         if (!err && kick)
501                 needs_kick = virtqueue_kick_prepare(vq->vq);
502
503         spin_unlock_irqrestore(&vq->vq_lock, flags);
504
505         if (needs_kick)
506                 virtqueue_notify(vq->vq);
507         return err;
508 }
509
510 static void virtio_scsi_init_hdr(struct virtio_device *vdev,
511                                  struct virtio_scsi_cmd_req *cmd,
512                                  struct scsi_cmnd *sc)
513 {
514         cmd->lun[0] = 1;
515         cmd->lun[1] = sc->device->id;
516         cmd->lun[2] = (sc->device->lun >> 8) | 0x40;
517         cmd->lun[3] = sc->device->lun & 0xff;
518         cmd->tag = cpu_to_virtio64(vdev, (unsigned long)sc);
519         cmd->task_attr = VIRTIO_SCSI_S_SIMPLE;
520         cmd->prio = 0;
521         cmd->crn = 0;
522 }
523
524 #ifdef CONFIG_BLK_DEV_INTEGRITY
525 static void virtio_scsi_init_hdr_pi(struct virtio_device *vdev,
526                                     struct virtio_scsi_cmd_req_pi *cmd_pi,
527                                     struct scsi_cmnd *sc)
528 {
529         struct request *rq = scsi_cmd_to_rq(sc);
530         struct blk_integrity *bi;
531
532         virtio_scsi_init_hdr(vdev, (struct virtio_scsi_cmd_req *)cmd_pi, sc);
533
534         if (!rq || !scsi_prot_sg_count(sc))
535                 return;
536
537         bi = blk_get_integrity(rq->q->disk);
538
539         if (sc->sc_data_direction == DMA_TO_DEVICE)
540                 cmd_pi->pi_bytesout = cpu_to_virtio32(vdev,
541                                                       bio_integrity_bytes(bi,
542                                                         blk_rq_sectors(rq)));
543         else if (sc->sc_data_direction == DMA_FROM_DEVICE)
544                 cmd_pi->pi_bytesin = cpu_to_virtio32(vdev,
545                                                      bio_integrity_bytes(bi,
546                                                         blk_rq_sectors(rq)));
547 }
548 #endif
549
550 static struct virtio_scsi_vq *virtscsi_pick_vq_mq(struct virtio_scsi *vscsi,
551                                                   struct scsi_cmnd *sc)
552 {
553         u32 tag = blk_mq_unique_tag(scsi_cmd_to_rq(sc));
554         u16 hwq = blk_mq_unique_tag_to_hwq(tag);
555
556         return &vscsi->req_vqs[hwq];
557 }
558
559 static int virtscsi_queuecommand(struct Scsi_Host *shost,
560                                  struct scsi_cmnd *sc)
561 {
562         struct virtio_scsi *vscsi = shost_priv(shost);
563         struct virtio_scsi_vq *req_vq = virtscsi_pick_vq_mq(vscsi, sc);
564         struct virtio_scsi_cmd *cmd = scsi_cmd_priv(sc);
565         bool kick;
566         unsigned long flags;
567         int req_size;
568         int ret;
569
570         BUG_ON(scsi_sg_count(sc) > shost->sg_tablesize);
571
572         /* TODO: check feature bit and fail if unsupported?  */
573         BUG_ON(sc->sc_data_direction == DMA_BIDIRECTIONAL);
574
575         dev_dbg(&sc->device->sdev_gendev,
576                 "cmd %p CDB: %#02x\n", sc, sc->cmnd[0]);
577
578         cmd->sc = sc;
579
580         BUG_ON(sc->cmd_len > VIRTIO_SCSI_CDB_SIZE);
581
582 #ifdef CONFIG_BLK_DEV_INTEGRITY
583         if (virtio_has_feature(vscsi->vdev, VIRTIO_SCSI_F_T10_PI)) {
584                 virtio_scsi_init_hdr_pi(vscsi->vdev, &cmd->req.cmd_pi, sc);
585                 memcpy(cmd->req.cmd_pi.cdb, sc->cmnd, sc->cmd_len);
586                 req_size = sizeof(cmd->req.cmd_pi);
587         } else
588 #endif
589         {
590                 virtio_scsi_init_hdr(vscsi->vdev, &cmd->req.cmd, sc);
591                 memcpy(cmd->req.cmd.cdb, sc->cmnd, sc->cmd_len);
592                 req_size = sizeof(cmd->req.cmd);
593         }
594
595         kick = (sc->flags & SCMD_LAST) != 0;
596         ret = virtscsi_add_cmd(req_vq, cmd, req_size, sizeof(cmd->resp.cmd), kick);
597         if (ret == -EIO) {
598                 cmd->resp.cmd.response = VIRTIO_SCSI_S_BAD_TARGET;
599                 spin_lock_irqsave(&req_vq->vq_lock, flags);
600                 virtscsi_complete_cmd(vscsi, cmd);
601                 spin_unlock_irqrestore(&req_vq->vq_lock, flags);
602         } else if (ret != 0) {
603                 return SCSI_MLQUEUE_HOST_BUSY;
604         }
605         return 0;
606 }
607
608 static int virtscsi_tmf(struct virtio_scsi *vscsi, struct virtio_scsi_cmd *cmd)
609 {
610         DECLARE_COMPLETION_ONSTACK(comp);
611         int ret = FAILED;
612
613         cmd->comp = &comp;
614         if (virtscsi_add_cmd(&vscsi->ctrl_vq, cmd,
615                               sizeof cmd->req.tmf, sizeof cmd->resp.tmf, true) < 0)
616                 goto out;
617
618         wait_for_completion(&comp);
619         if (cmd->resp.tmf.response == VIRTIO_SCSI_S_OK ||
620             cmd->resp.tmf.response == VIRTIO_SCSI_S_FUNCTION_SUCCEEDED)
621                 ret = SUCCESS;
622
623         /*
624          * The spec guarantees that all requests related to the TMF have
625          * been completed, but the callback might not have run yet if
626          * we're using independent interrupts (e.g. MSI).  Poll the
627          * virtqueues once.
628          *
629          * In the abort case, scsi_done() will do nothing, because the
630          * command timed out and hence SCMD_STATE_COMPLETE has been set.
631          */
632         virtscsi_poll_requests(vscsi);
633
634 out:
635         mempool_free(cmd, virtscsi_cmd_pool);
636         return ret;
637 }
638
639 static int virtscsi_device_reset(struct scsi_cmnd *sc)
640 {
641         struct virtio_scsi *vscsi = shost_priv(sc->device->host);
642         struct virtio_scsi_cmd *cmd;
643
644         sdev_printk(KERN_INFO, sc->device, "device reset\n");
645         cmd = mempool_alloc(virtscsi_cmd_pool, GFP_NOIO);
646         if (!cmd)
647                 return FAILED;
648
649         memset(cmd, 0, sizeof(*cmd));
650         cmd->req.tmf = (struct virtio_scsi_ctrl_tmf_req){
651                 .type = VIRTIO_SCSI_T_TMF,
652                 .subtype = cpu_to_virtio32(vscsi->vdev,
653                                              VIRTIO_SCSI_T_TMF_LOGICAL_UNIT_RESET),
654                 .lun[0] = 1,
655                 .lun[1] = sc->device->id,
656                 .lun[2] = (sc->device->lun >> 8) | 0x40,
657                 .lun[3] = sc->device->lun & 0xff,
658         };
659         return virtscsi_tmf(vscsi, cmd);
660 }
661
662 static int virtscsi_device_alloc(struct scsi_device *sdevice)
663 {
664         /*
665          * Passed through SCSI targets (e.g. with qemu's 'scsi-block')
666          * may have transfer limits which come from the host SCSI
667          * controller or something on the host side other than the
668          * target itself.
669          *
670          * To make this work properly, the hypervisor can adjust the
671          * target's VPD information to advertise these limits.  But
672          * for that to work, the guest has to look at the VPD pages,
673          * which we won't do by default if it is an SPC-2 device, even
674          * if it does actually support it.
675          *
676          * So, set the blist to always try to read the VPD pages.
677          */
678         sdevice->sdev_bflags = BLIST_TRY_VPD_PAGES;
679
680         return 0;
681 }
682
683
684 /**
685  * virtscsi_change_queue_depth() - Change a virtscsi target's queue depth
686  * @sdev:       Virtscsi target whose queue depth to change
687  * @qdepth:     New queue depth
688  */
689 static int virtscsi_change_queue_depth(struct scsi_device *sdev, int qdepth)
690 {
691         struct Scsi_Host *shost = sdev->host;
692         int max_depth = shost->cmd_per_lun;
693
694         return scsi_change_queue_depth(sdev, min(max_depth, qdepth));
695 }
696
697 static int virtscsi_abort(struct scsi_cmnd *sc)
698 {
699         struct virtio_scsi *vscsi = shost_priv(sc->device->host);
700         struct virtio_scsi_cmd *cmd;
701
702         scmd_printk(KERN_INFO, sc, "abort\n");
703         cmd = mempool_alloc(virtscsi_cmd_pool, GFP_NOIO);
704         if (!cmd)
705                 return FAILED;
706
707         memset(cmd, 0, sizeof(*cmd));
708         cmd->req.tmf = (struct virtio_scsi_ctrl_tmf_req){
709                 .type = VIRTIO_SCSI_T_TMF,
710                 .subtype = VIRTIO_SCSI_T_TMF_ABORT_TASK,
711                 .lun[0] = 1,
712                 .lun[1] = sc->device->id,
713                 .lun[2] = (sc->device->lun >> 8) | 0x40,
714                 .lun[3] = sc->device->lun & 0xff,
715                 .tag = cpu_to_virtio64(vscsi->vdev, (unsigned long)sc),
716         };
717         return virtscsi_tmf(vscsi, cmd);
718 }
719
720 static void virtscsi_map_queues(struct Scsi_Host *shost)
721 {
722         struct virtio_scsi *vscsi = shost_priv(shost);
723         struct blk_mq_queue_map *qmap = &shost->tag_set.map[HCTX_TYPE_DEFAULT];
724
725         blk_mq_virtio_map_queues(qmap, vscsi->vdev, 2);
726 }
727
728 static void virtscsi_commit_rqs(struct Scsi_Host *shost, u16 hwq)
729 {
730         struct virtio_scsi *vscsi = shost_priv(shost);
731
732         virtscsi_kick_vq(&vscsi->req_vqs[hwq]);
733 }
734
735 /*
736  * The host guarantees to respond to each command, although I/O
737  * latencies might be higher than on bare metal.  Reset the timer
738  * unconditionally to give the host a chance to perform EH.
739  */
740 static enum scsi_timeout_action virtscsi_eh_timed_out(struct scsi_cmnd *scmnd)
741 {
742         return SCSI_EH_RESET_TIMER;
743 }
744
745 static const struct scsi_host_template virtscsi_host_template = {
746         .module = THIS_MODULE,
747         .name = "Virtio SCSI HBA",
748         .proc_name = "virtio_scsi",
749         .this_id = -1,
750         .cmd_size = sizeof(struct virtio_scsi_cmd),
751         .queuecommand = virtscsi_queuecommand,
752         .commit_rqs = virtscsi_commit_rqs,
753         .change_queue_depth = virtscsi_change_queue_depth,
754         .eh_abort_handler = virtscsi_abort,
755         .eh_device_reset_handler = virtscsi_device_reset,
756         .eh_timed_out = virtscsi_eh_timed_out,
757         .slave_alloc = virtscsi_device_alloc,
758
759         .dma_boundary = UINT_MAX,
760         .map_queues = virtscsi_map_queues,
761         .track_queue_depth = 1,
762 };
763
764 #define virtscsi_config_get(vdev, fld) \
765         ({ \
766                 __virtio_native_type(struct virtio_scsi_config, fld) __val; \
767                 virtio_cread(vdev, struct virtio_scsi_config, fld, &__val); \
768                 __val; \
769         })
770
771 #define virtscsi_config_set(vdev, fld, val) \
772         do { \
773                 __virtio_native_type(struct virtio_scsi_config, fld) __val = (val); \
774                 virtio_cwrite(vdev, struct virtio_scsi_config, fld, &__val); \
775         } while(0)
776
777 static void virtscsi_init_vq(struct virtio_scsi_vq *virtscsi_vq,
778                              struct virtqueue *vq)
779 {
780         spin_lock_init(&virtscsi_vq->vq_lock);
781         virtscsi_vq->vq = vq;
782 }
783
784 static void virtscsi_remove_vqs(struct virtio_device *vdev)
785 {
786         /* Stop all the virtqueues. */
787         virtio_reset_device(vdev);
788         vdev->config->del_vqs(vdev);
789 }
790
791 static int virtscsi_init(struct virtio_device *vdev,
792                          struct virtio_scsi *vscsi)
793 {
794         int err;
795         u32 i;
796         u32 num_vqs;
797         vq_callback_t **callbacks;
798         const char **names;
799         struct virtqueue **vqs;
800         struct irq_affinity desc = { .pre_vectors = 2 };
801
802         num_vqs = vscsi->num_queues + VIRTIO_SCSI_VQ_BASE;
803         vqs = kmalloc_array(num_vqs, sizeof(struct virtqueue *), GFP_KERNEL);
804         callbacks = kmalloc_array(num_vqs, sizeof(vq_callback_t *),
805                                   GFP_KERNEL);
806         names = kmalloc_array(num_vqs, sizeof(char *), GFP_KERNEL);
807
808         if (!callbacks || !vqs || !names) {
809                 err = -ENOMEM;
810                 goto out;
811         }
812
813         callbacks[0] = virtscsi_ctrl_done;
814         callbacks[1] = virtscsi_event_done;
815         names[0] = "control";
816         names[1] = "event";
817         for (i = VIRTIO_SCSI_VQ_BASE; i < num_vqs; i++) {
818                 callbacks[i] = virtscsi_req_done;
819                 names[i] = "request";
820         }
821
822         /* Discover virtqueues and write information to configuration.  */
823         err = virtio_find_vqs(vdev, num_vqs, vqs, callbacks, names, &desc);
824         if (err)
825                 goto out;
826
827         virtscsi_init_vq(&vscsi->ctrl_vq, vqs[0]);
828         virtscsi_init_vq(&vscsi->event_vq, vqs[1]);
829         for (i = VIRTIO_SCSI_VQ_BASE; i < num_vqs; i++)
830                 virtscsi_init_vq(&vscsi->req_vqs[i - VIRTIO_SCSI_VQ_BASE],
831                                  vqs[i]);
832
833         virtscsi_config_set(vdev, cdb_size, VIRTIO_SCSI_CDB_SIZE);
834         virtscsi_config_set(vdev, sense_size, VIRTIO_SCSI_SENSE_SIZE);
835
836         err = 0;
837
838 out:
839         kfree(names);
840         kfree(callbacks);
841         kfree(vqs);
842         if (err)
843                 virtscsi_remove_vqs(vdev);
844         return err;
845 }
846
847 static int virtscsi_probe(struct virtio_device *vdev)
848 {
849         struct Scsi_Host *shost;
850         struct virtio_scsi *vscsi;
851         int err;
852         u32 sg_elems, num_targets;
853         u32 cmd_per_lun;
854         u32 num_queues;
855
856         if (!vdev->config->get) {
857                 dev_err(&vdev->dev, "%s failure: config access disabled\n",
858                         __func__);
859                 return -EINVAL;
860         }
861
862         /* We need to know how many queues before we allocate. */
863         num_queues = virtscsi_config_get(vdev, num_queues) ? : 1;
864         num_queues = min_t(unsigned int, nr_cpu_ids, num_queues);
865
866         num_targets = virtscsi_config_get(vdev, max_target) + 1;
867
868         shost = scsi_host_alloc(&virtscsi_host_template,
869                                 struct_size(vscsi, req_vqs, num_queues));
870         if (!shost)
871                 return -ENOMEM;
872
873         sg_elems = virtscsi_config_get(vdev, seg_max) ?: 1;
874         shost->sg_tablesize = sg_elems;
875         vscsi = shost_priv(shost);
876         vscsi->vdev = vdev;
877         vscsi->num_queues = num_queues;
878         vdev->priv = shost;
879
880         err = virtscsi_init(vdev, vscsi);
881         if (err)
882                 goto virtscsi_init_failed;
883
884         shost->can_queue = virtqueue_get_vring_size(vscsi->req_vqs[0].vq);
885
886         cmd_per_lun = virtscsi_config_get(vdev, cmd_per_lun) ?: 1;
887         shost->cmd_per_lun = min_t(u32, cmd_per_lun, shost->can_queue);
888         shost->max_sectors = virtscsi_config_get(vdev, max_sectors) ?: 0xFFFF;
889
890         /* LUNs > 256 are reported with format 1, so they go in the range
891          * 16640-32767.
892          */
893         shost->max_lun = virtscsi_config_get(vdev, max_lun) + 1 + 0x4000;
894         shost->max_id = num_targets;
895         shost->max_channel = 0;
896         shost->max_cmd_len = VIRTIO_SCSI_CDB_SIZE;
897         shost->nr_hw_queues = num_queues;
898
899 #ifdef CONFIG_BLK_DEV_INTEGRITY
900         if (virtio_has_feature(vdev, VIRTIO_SCSI_F_T10_PI)) {
901                 int host_prot;
902
903                 host_prot = SHOST_DIF_TYPE1_PROTECTION | SHOST_DIF_TYPE2_PROTECTION |
904                             SHOST_DIF_TYPE3_PROTECTION | SHOST_DIX_TYPE1_PROTECTION |
905                             SHOST_DIX_TYPE2_PROTECTION | SHOST_DIX_TYPE3_PROTECTION;
906
907                 scsi_host_set_prot(shost, host_prot);
908                 scsi_host_set_guard(shost, SHOST_DIX_GUARD_CRC);
909         }
910 #endif
911
912         err = scsi_add_host(shost, &vdev->dev);
913         if (err)
914                 goto scsi_add_host_failed;
915
916         virtio_device_ready(vdev);
917
918         if (virtio_has_feature(vdev, VIRTIO_SCSI_F_HOTPLUG))
919                 virtscsi_kick_event_all(vscsi);
920
921         scsi_scan_host(shost);
922         return 0;
923
924 scsi_add_host_failed:
925         vdev->config->del_vqs(vdev);
926 virtscsi_init_failed:
927         scsi_host_put(shost);
928         return err;
929 }
930
931 static void virtscsi_remove(struct virtio_device *vdev)
932 {
933         struct Scsi_Host *shost = virtio_scsi_host(vdev);
934         struct virtio_scsi *vscsi = shost_priv(shost);
935
936         if (virtio_has_feature(vdev, VIRTIO_SCSI_F_HOTPLUG))
937                 virtscsi_cancel_event_work(vscsi);
938
939         scsi_remove_host(shost);
940         virtscsi_remove_vqs(vdev);
941         scsi_host_put(shost);
942 }
943
944 #ifdef CONFIG_PM_SLEEP
945 static int virtscsi_freeze(struct virtio_device *vdev)
946 {
947         virtscsi_remove_vqs(vdev);
948         return 0;
949 }
950
951 static int virtscsi_restore(struct virtio_device *vdev)
952 {
953         struct Scsi_Host *sh = virtio_scsi_host(vdev);
954         struct virtio_scsi *vscsi = shost_priv(sh);
955         int err;
956
957         err = virtscsi_init(vdev, vscsi);
958         if (err)
959                 return err;
960
961         virtio_device_ready(vdev);
962
963         if (virtio_has_feature(vdev, VIRTIO_SCSI_F_HOTPLUG))
964                 virtscsi_kick_event_all(vscsi);
965
966         return err;
967 }
968 #endif
969
970 static struct virtio_device_id id_table[] = {
971         { VIRTIO_ID_SCSI, VIRTIO_DEV_ANY_ID },
972         { 0 },
973 };
974
975 static unsigned int features[] = {
976         VIRTIO_SCSI_F_HOTPLUG,
977         VIRTIO_SCSI_F_CHANGE,
978 #ifdef CONFIG_BLK_DEV_INTEGRITY
979         VIRTIO_SCSI_F_T10_PI,
980 #endif
981 };
982
983 static struct virtio_driver virtio_scsi_driver = {
984         .feature_table = features,
985         .feature_table_size = ARRAY_SIZE(features),
986         .driver.name = KBUILD_MODNAME,
987         .driver.owner = THIS_MODULE,
988         .id_table = id_table,
989         .probe = virtscsi_probe,
990 #ifdef CONFIG_PM_SLEEP
991         .freeze = virtscsi_freeze,
992         .restore = virtscsi_restore,
993 #endif
994         .remove = virtscsi_remove,
995 };
996
997 static int __init virtio_scsi_init(void)
998 {
999         int ret = -ENOMEM;
1000
1001         virtscsi_cmd_cache = KMEM_CACHE(virtio_scsi_cmd, 0);
1002         if (!virtscsi_cmd_cache) {
1003                 pr_err("kmem_cache_create() for virtscsi_cmd_cache failed\n");
1004                 goto error;
1005         }
1006
1007
1008         virtscsi_cmd_pool =
1009                 mempool_create_slab_pool(VIRTIO_SCSI_MEMPOOL_SZ,
1010                                          virtscsi_cmd_cache);
1011         if (!virtscsi_cmd_pool) {
1012                 pr_err("mempool_create() for virtscsi_cmd_pool failed\n");
1013                 goto error;
1014         }
1015         ret = register_virtio_driver(&virtio_scsi_driver);
1016         if (ret < 0)
1017                 goto error;
1018
1019         return 0;
1020
1021 error:
1022         mempool_destroy(virtscsi_cmd_pool);
1023         virtscsi_cmd_pool = NULL;
1024         kmem_cache_destroy(virtscsi_cmd_cache);
1025         virtscsi_cmd_cache = NULL;
1026         return ret;
1027 }
1028
1029 static void __exit virtio_scsi_fini(void)
1030 {
1031         unregister_virtio_driver(&virtio_scsi_driver);
1032         mempool_destroy(virtscsi_cmd_pool);
1033         kmem_cache_destroy(virtscsi_cmd_cache);
1034 }
1035 module_init(virtio_scsi_init);
1036 module_exit(virtio_scsi_fini);
1037
1038 MODULE_DEVICE_TABLE(virtio, id_table);
1039 MODULE_DESCRIPTION("Virtio SCSI HBA driver");
1040 MODULE_LICENSE("GPL");