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