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