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