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