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