GNU Linux-libre 5.10.153-gnu1
[releases.git] / drivers / scsi / vmw_pvscsi.c
1 /*
2  * Linux driver for VMware's para-virtualized SCSI HBA.
3  *
4  * Copyright (C) 2008-2014, VMware, Inc. All Rights Reserved.
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published by the
8  * Free Software Foundation; version 2 of the License and no later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
13  * NON INFRINGEMENT.  See the GNU General Public License for more
14  * details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19  *
20  * Maintained by: Jim Gill <jgill@vmware.com>
21  *
22  */
23
24 #include <linux/kernel.h>
25 #include <linux/module.h>
26 #include <linux/interrupt.h>
27 #include <linux/slab.h>
28 #include <linux/workqueue.h>
29 #include <linux/pci.h>
30
31 #include <scsi/scsi.h>
32 #include <scsi/scsi_host.h>
33 #include <scsi/scsi_cmnd.h>
34 #include <scsi/scsi_device.h>
35 #include <scsi/scsi_tcq.h>
36
37 #include "vmw_pvscsi.h"
38
39 #define PVSCSI_LINUX_DRIVER_DESC "VMware PVSCSI driver"
40
41 MODULE_DESCRIPTION(PVSCSI_LINUX_DRIVER_DESC);
42 MODULE_AUTHOR("VMware, Inc.");
43 MODULE_LICENSE("GPL");
44 MODULE_VERSION(PVSCSI_DRIVER_VERSION_STRING);
45
46 #define PVSCSI_DEFAULT_NUM_PAGES_PER_RING       8
47 #define PVSCSI_DEFAULT_NUM_PAGES_MSG_RING       1
48 #define PVSCSI_DEFAULT_QUEUE_DEPTH              254
49 #define SGL_SIZE                                PAGE_SIZE
50
51 struct pvscsi_sg_list {
52         struct PVSCSISGElement sge[PVSCSI_MAX_NUM_SG_ENTRIES_PER_SEGMENT];
53 };
54
55 struct pvscsi_ctx {
56         /*
57          * The index of the context in cmd_map serves as the context ID for a
58          * 1-to-1 mapping completions back to requests.
59          */
60         struct scsi_cmnd        *cmd;
61         struct pvscsi_sg_list   *sgl;
62         struct list_head        list;
63         dma_addr_t              dataPA;
64         dma_addr_t              sensePA;
65         dma_addr_t              sglPA;
66         struct completion       *abort_cmp;
67 };
68
69 struct pvscsi_adapter {
70         char                            *mmioBase;
71         u8                              rev;
72         bool                            use_msg;
73         bool                            use_req_threshold;
74
75         spinlock_t                      hw_lock;
76
77         struct workqueue_struct         *workqueue;
78         struct work_struct              work;
79
80         struct PVSCSIRingReqDesc        *req_ring;
81         unsigned                        req_pages;
82         unsigned                        req_depth;
83         dma_addr_t                      reqRingPA;
84
85         struct PVSCSIRingCmpDesc        *cmp_ring;
86         unsigned                        cmp_pages;
87         dma_addr_t                      cmpRingPA;
88
89         struct PVSCSIRingMsgDesc        *msg_ring;
90         unsigned                        msg_pages;
91         dma_addr_t                      msgRingPA;
92
93         struct PVSCSIRingsState         *rings_state;
94         dma_addr_t                      ringStatePA;
95
96         struct pci_dev                  *dev;
97         struct Scsi_Host                *host;
98
99         struct list_head                cmd_pool;
100         struct pvscsi_ctx               *cmd_map;
101 };
102
103
104 /* Command line parameters */
105 static int pvscsi_ring_pages;
106 static int pvscsi_msg_ring_pages = PVSCSI_DEFAULT_NUM_PAGES_MSG_RING;
107 static int pvscsi_cmd_per_lun    = PVSCSI_DEFAULT_QUEUE_DEPTH;
108 static bool pvscsi_disable_msi;
109 static bool pvscsi_disable_msix;
110 static bool pvscsi_use_msg       = true;
111 static bool pvscsi_use_req_threshold = true;
112
113 #define PVSCSI_RW (S_IRUSR | S_IWUSR)
114
115 module_param_named(ring_pages, pvscsi_ring_pages, int, PVSCSI_RW);
116 MODULE_PARM_DESC(ring_pages, "Number of pages per req/cmp ring - (default="
117                  __stringify(PVSCSI_DEFAULT_NUM_PAGES_PER_RING)
118                  "[up to 16 targets],"
119                  __stringify(PVSCSI_SETUP_RINGS_MAX_NUM_PAGES)
120                  "[for 16+ targets])");
121
122 module_param_named(msg_ring_pages, pvscsi_msg_ring_pages, int, PVSCSI_RW);
123 MODULE_PARM_DESC(msg_ring_pages, "Number of pages for the msg ring - (default="
124                  __stringify(PVSCSI_DEFAULT_NUM_PAGES_MSG_RING) ")");
125
126 module_param_named(cmd_per_lun, pvscsi_cmd_per_lun, int, PVSCSI_RW);
127 MODULE_PARM_DESC(cmd_per_lun, "Maximum commands per lun - (default="
128                  __stringify(PVSCSI_DEFAULT_QUEUE_DEPTH) ")");
129
130 module_param_named(disable_msi, pvscsi_disable_msi, bool, PVSCSI_RW);
131 MODULE_PARM_DESC(disable_msi, "Disable MSI use in driver - (default=0)");
132
133 module_param_named(disable_msix, pvscsi_disable_msix, bool, PVSCSI_RW);
134 MODULE_PARM_DESC(disable_msix, "Disable MSI-X use in driver - (default=0)");
135
136 module_param_named(use_msg, pvscsi_use_msg, bool, PVSCSI_RW);
137 MODULE_PARM_DESC(use_msg, "Use msg ring when available - (default=1)");
138
139 module_param_named(use_req_threshold, pvscsi_use_req_threshold,
140                    bool, PVSCSI_RW);
141 MODULE_PARM_DESC(use_req_threshold, "Use driver-based request coalescing if configured - (default=1)");
142
143 static const struct pci_device_id pvscsi_pci_tbl[] = {
144         { PCI_VDEVICE(VMWARE, PCI_DEVICE_ID_VMWARE_PVSCSI) },
145         { 0 }
146 };
147
148 MODULE_DEVICE_TABLE(pci, pvscsi_pci_tbl);
149
150 static struct device *
151 pvscsi_dev(const struct pvscsi_adapter *adapter)
152 {
153         return &(adapter->dev->dev);
154 }
155
156 static struct pvscsi_ctx *
157 pvscsi_find_context(const struct pvscsi_adapter *adapter, struct scsi_cmnd *cmd)
158 {
159         struct pvscsi_ctx *ctx, *end;
160
161         end = &adapter->cmd_map[adapter->req_depth];
162         for (ctx = adapter->cmd_map; ctx < end; ctx++)
163                 if (ctx->cmd == cmd)
164                         return ctx;
165
166         return NULL;
167 }
168
169 static struct pvscsi_ctx *
170 pvscsi_acquire_context(struct pvscsi_adapter *adapter, struct scsi_cmnd *cmd)
171 {
172         struct pvscsi_ctx *ctx;
173
174         if (list_empty(&adapter->cmd_pool))
175                 return NULL;
176
177         ctx = list_first_entry(&adapter->cmd_pool, struct pvscsi_ctx, list);
178         ctx->cmd = cmd;
179         list_del(&ctx->list);
180
181         return ctx;
182 }
183
184 static void pvscsi_release_context(struct pvscsi_adapter *adapter,
185                                    struct pvscsi_ctx *ctx)
186 {
187         ctx->cmd = NULL;
188         ctx->abort_cmp = NULL;
189         list_add(&ctx->list, &adapter->cmd_pool);
190 }
191
192 /*
193  * Map a pvscsi_ctx struct to a context ID field value; we map to a simple
194  * non-zero integer. ctx always points to an entry in cmd_map array, hence
195  * the return value is always >=1.
196  */
197 static u64 pvscsi_map_context(const struct pvscsi_adapter *adapter,
198                               const struct pvscsi_ctx *ctx)
199 {
200         return ctx - adapter->cmd_map + 1;
201 }
202
203 static struct pvscsi_ctx *
204 pvscsi_get_context(const struct pvscsi_adapter *adapter, u64 context)
205 {
206         return &adapter->cmd_map[context - 1];
207 }
208
209 static void pvscsi_reg_write(const struct pvscsi_adapter *adapter,
210                              u32 offset, u32 val)
211 {
212         writel(val, adapter->mmioBase + offset);
213 }
214
215 static u32 pvscsi_reg_read(const struct pvscsi_adapter *adapter, u32 offset)
216 {
217         return readl(adapter->mmioBase + offset);
218 }
219
220 static u32 pvscsi_read_intr_status(const struct pvscsi_adapter *adapter)
221 {
222         return pvscsi_reg_read(adapter, PVSCSI_REG_OFFSET_INTR_STATUS);
223 }
224
225 static void pvscsi_write_intr_status(const struct pvscsi_adapter *adapter,
226                                      u32 val)
227 {
228         pvscsi_reg_write(adapter, PVSCSI_REG_OFFSET_INTR_STATUS, val);
229 }
230
231 static void pvscsi_unmask_intr(const struct pvscsi_adapter *adapter)
232 {
233         u32 intr_bits;
234
235         intr_bits = PVSCSI_INTR_CMPL_MASK;
236         if (adapter->use_msg)
237                 intr_bits |= PVSCSI_INTR_MSG_MASK;
238
239         pvscsi_reg_write(adapter, PVSCSI_REG_OFFSET_INTR_MASK, intr_bits);
240 }
241
242 static void pvscsi_mask_intr(const struct pvscsi_adapter *adapter)
243 {
244         pvscsi_reg_write(adapter, PVSCSI_REG_OFFSET_INTR_MASK, 0);
245 }
246
247 static void pvscsi_write_cmd_desc(const struct pvscsi_adapter *adapter,
248                                   u32 cmd, const void *desc, size_t len)
249 {
250         const u32 *ptr = desc;
251         size_t i;
252
253         len /= sizeof(*ptr);
254         pvscsi_reg_write(adapter, PVSCSI_REG_OFFSET_COMMAND, cmd);
255         for (i = 0; i < len; i++)
256                 pvscsi_reg_write(adapter,
257                                  PVSCSI_REG_OFFSET_COMMAND_DATA, ptr[i]);
258 }
259
260 static void pvscsi_abort_cmd(const struct pvscsi_adapter *adapter,
261                              const struct pvscsi_ctx *ctx)
262 {
263         struct PVSCSICmdDescAbortCmd cmd = { 0 };
264
265         cmd.target = ctx->cmd->device->id;
266         cmd.context = pvscsi_map_context(adapter, ctx);
267
268         pvscsi_write_cmd_desc(adapter, PVSCSI_CMD_ABORT_CMD, &cmd, sizeof(cmd));
269 }
270
271 static void pvscsi_kick_rw_io(const struct pvscsi_adapter *adapter)
272 {
273         pvscsi_reg_write(adapter, PVSCSI_REG_OFFSET_KICK_RW_IO, 0);
274 }
275
276 static void pvscsi_process_request_ring(const struct pvscsi_adapter *adapter)
277 {
278         pvscsi_reg_write(adapter, PVSCSI_REG_OFFSET_KICK_NON_RW_IO, 0);
279 }
280
281 static int scsi_is_rw(unsigned char op)
282 {
283         return op == READ_6  || op == WRITE_6 ||
284                op == READ_10 || op == WRITE_10 ||
285                op == READ_12 || op == WRITE_12 ||
286                op == READ_16 || op == WRITE_16;
287 }
288
289 static void pvscsi_kick_io(const struct pvscsi_adapter *adapter,
290                            unsigned char op)
291 {
292         if (scsi_is_rw(op)) {
293                 struct PVSCSIRingsState *s = adapter->rings_state;
294
295                 if (!adapter->use_req_threshold ||
296                     s->reqProdIdx - s->reqConsIdx >= s->reqCallThreshold)
297                         pvscsi_kick_rw_io(adapter);
298         } else {
299                 pvscsi_process_request_ring(adapter);
300         }
301 }
302
303 static void ll_adapter_reset(const struct pvscsi_adapter *adapter)
304 {
305         dev_dbg(pvscsi_dev(adapter), "Adapter Reset on %p\n", adapter);
306
307         pvscsi_write_cmd_desc(adapter, PVSCSI_CMD_ADAPTER_RESET, NULL, 0);
308 }
309
310 static void ll_bus_reset(const struct pvscsi_adapter *adapter)
311 {
312         dev_dbg(pvscsi_dev(adapter), "Resetting bus on %p\n", adapter);
313
314         pvscsi_write_cmd_desc(adapter, PVSCSI_CMD_RESET_BUS, NULL, 0);
315 }
316
317 static void ll_device_reset(const struct pvscsi_adapter *adapter, u32 target)
318 {
319         struct PVSCSICmdDescResetDevice cmd = { 0 };
320
321         dev_dbg(pvscsi_dev(adapter), "Resetting device: target=%u\n", target);
322
323         cmd.target = target;
324
325         pvscsi_write_cmd_desc(adapter, PVSCSI_CMD_RESET_DEVICE,
326                               &cmd, sizeof(cmd));
327 }
328
329 static void pvscsi_create_sg(struct pvscsi_ctx *ctx,
330                              struct scatterlist *sg, unsigned count)
331 {
332         unsigned i;
333         struct PVSCSISGElement *sge;
334
335         BUG_ON(count > PVSCSI_MAX_NUM_SG_ENTRIES_PER_SEGMENT);
336
337         sge = &ctx->sgl->sge[0];
338         for (i = 0; i < count; i++, sg = sg_next(sg)) {
339                 sge[i].addr   = sg_dma_address(sg);
340                 sge[i].length = sg_dma_len(sg);
341                 sge[i].flags  = 0;
342         }
343 }
344
345 /*
346  * Map all data buffers for a command into PCI space and
347  * setup the scatter/gather list if needed.
348  */
349 static int pvscsi_map_buffers(struct pvscsi_adapter *adapter,
350                               struct pvscsi_ctx *ctx, struct scsi_cmnd *cmd,
351                               struct PVSCSIRingReqDesc *e)
352 {
353         unsigned count;
354         unsigned bufflen = scsi_bufflen(cmd);
355         struct scatterlist *sg;
356
357         e->dataLen = bufflen;
358         e->dataAddr = 0;
359         if (bufflen == 0)
360                 return 0;
361
362         sg = scsi_sglist(cmd);
363         count = scsi_sg_count(cmd);
364         if (count != 0) {
365                 int segs = scsi_dma_map(cmd);
366
367                 if (segs == -ENOMEM) {
368                         scmd_printk(KERN_DEBUG, cmd,
369                                     "vmw_pvscsi: Failed to map cmd sglist for DMA.\n");
370                         return -ENOMEM;
371                 } else if (segs > 1) {
372                         pvscsi_create_sg(ctx, sg, segs);
373
374                         e->flags |= PVSCSI_FLAG_CMD_WITH_SG_LIST;
375                         ctx->sglPA = dma_map_single(&adapter->dev->dev,
376                                         ctx->sgl, SGL_SIZE, DMA_TO_DEVICE);
377                         if (dma_mapping_error(&adapter->dev->dev, ctx->sglPA)) {
378                                 scmd_printk(KERN_ERR, cmd,
379                                             "vmw_pvscsi: Failed to map ctx sglist for DMA.\n");
380                                 scsi_dma_unmap(cmd);
381                                 ctx->sglPA = 0;
382                                 return -ENOMEM;
383                         }
384                         e->dataAddr = ctx->sglPA;
385                 } else
386                         e->dataAddr = sg_dma_address(sg);
387         } else {
388                 /*
389                  * In case there is no S/G list, scsi_sglist points
390                  * directly to the buffer.
391                  */
392                 ctx->dataPA = dma_map_single(&adapter->dev->dev, sg, bufflen,
393                                              cmd->sc_data_direction);
394                 if (dma_mapping_error(&adapter->dev->dev, ctx->dataPA)) {
395                         scmd_printk(KERN_DEBUG, cmd,
396                                     "vmw_pvscsi: Failed to map direct data buffer for DMA.\n");
397                         return -ENOMEM;
398                 }
399                 e->dataAddr = ctx->dataPA;
400         }
401
402         return 0;
403 }
404
405 /*
406  * The device incorrectly doesn't clear the first byte of the sense
407  * buffer in some cases. We have to do it ourselves.
408  * Otherwise we run into trouble when SWIOTLB is forced.
409  */
410 static void pvscsi_patch_sense(struct scsi_cmnd *cmd)
411 {
412         if (cmd->sense_buffer)
413                 cmd->sense_buffer[0] = 0;
414 }
415
416 static void pvscsi_unmap_buffers(const struct pvscsi_adapter *adapter,
417                                  struct pvscsi_ctx *ctx)
418 {
419         struct scsi_cmnd *cmd;
420         unsigned bufflen;
421
422         cmd = ctx->cmd;
423         bufflen = scsi_bufflen(cmd);
424
425         if (bufflen != 0) {
426                 unsigned count = scsi_sg_count(cmd);
427
428                 if (count != 0) {
429                         scsi_dma_unmap(cmd);
430                         if (ctx->sglPA) {
431                                 dma_unmap_single(&adapter->dev->dev, ctx->sglPA,
432                                                  SGL_SIZE, DMA_TO_DEVICE);
433                                 ctx->sglPA = 0;
434                         }
435                 } else
436                         dma_unmap_single(&adapter->dev->dev, ctx->dataPA,
437                                          bufflen, cmd->sc_data_direction);
438         }
439         if (cmd->sense_buffer)
440                 dma_unmap_single(&adapter->dev->dev, ctx->sensePA,
441                                  SCSI_SENSE_BUFFERSIZE, DMA_FROM_DEVICE);
442 }
443
444 static int pvscsi_allocate_rings(struct pvscsi_adapter *adapter)
445 {
446         adapter->rings_state = dma_alloc_coherent(&adapter->dev->dev, PAGE_SIZE,
447                         &adapter->ringStatePA, GFP_KERNEL);
448         if (!adapter->rings_state)
449                 return -ENOMEM;
450
451         adapter->req_pages = min(PVSCSI_MAX_NUM_PAGES_REQ_RING,
452                                  pvscsi_ring_pages);
453         adapter->req_depth = adapter->req_pages
454                                         * PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE;
455         adapter->req_ring = dma_alloc_coherent(&adapter->dev->dev,
456                         adapter->req_pages * PAGE_SIZE, &adapter->reqRingPA,
457                         GFP_KERNEL);
458         if (!adapter->req_ring)
459                 return -ENOMEM;
460
461         adapter->cmp_pages = min(PVSCSI_MAX_NUM_PAGES_CMP_RING,
462                                  pvscsi_ring_pages);
463         adapter->cmp_ring = dma_alloc_coherent(&adapter->dev->dev,
464                         adapter->cmp_pages * PAGE_SIZE, &adapter->cmpRingPA,
465                         GFP_KERNEL);
466         if (!adapter->cmp_ring)
467                 return -ENOMEM;
468
469         BUG_ON(!IS_ALIGNED(adapter->ringStatePA, PAGE_SIZE));
470         BUG_ON(!IS_ALIGNED(adapter->reqRingPA, PAGE_SIZE));
471         BUG_ON(!IS_ALIGNED(adapter->cmpRingPA, PAGE_SIZE));
472
473         if (!adapter->use_msg)
474                 return 0;
475
476         adapter->msg_pages = min(PVSCSI_MAX_NUM_PAGES_MSG_RING,
477                                  pvscsi_msg_ring_pages);
478         adapter->msg_ring = dma_alloc_coherent(&adapter->dev->dev,
479                         adapter->msg_pages * PAGE_SIZE, &adapter->msgRingPA,
480                         GFP_KERNEL);
481         if (!adapter->msg_ring)
482                 return -ENOMEM;
483         BUG_ON(!IS_ALIGNED(adapter->msgRingPA, PAGE_SIZE));
484
485         return 0;
486 }
487
488 static void pvscsi_setup_all_rings(const struct pvscsi_adapter *adapter)
489 {
490         struct PVSCSICmdDescSetupRings cmd = { 0 };
491         dma_addr_t base;
492         unsigned i;
493
494         cmd.ringsStatePPN   = adapter->ringStatePA >> PAGE_SHIFT;
495         cmd.reqRingNumPages = adapter->req_pages;
496         cmd.cmpRingNumPages = adapter->cmp_pages;
497
498         base = adapter->reqRingPA;
499         for (i = 0; i < adapter->req_pages; i++) {
500                 cmd.reqRingPPNs[i] = base >> PAGE_SHIFT;
501                 base += PAGE_SIZE;
502         }
503
504         base = adapter->cmpRingPA;
505         for (i = 0; i < adapter->cmp_pages; i++) {
506                 cmd.cmpRingPPNs[i] = base >> PAGE_SHIFT;
507                 base += PAGE_SIZE;
508         }
509
510         memset(adapter->rings_state, 0, PAGE_SIZE);
511         memset(adapter->req_ring, 0, adapter->req_pages * PAGE_SIZE);
512         memset(adapter->cmp_ring, 0, adapter->cmp_pages * PAGE_SIZE);
513
514         pvscsi_write_cmd_desc(adapter, PVSCSI_CMD_SETUP_RINGS,
515                               &cmd, sizeof(cmd));
516
517         if (adapter->use_msg) {
518                 struct PVSCSICmdDescSetupMsgRing cmd_msg = { 0 };
519
520                 cmd_msg.numPages = adapter->msg_pages;
521
522                 base = adapter->msgRingPA;
523                 for (i = 0; i < adapter->msg_pages; i++) {
524                         cmd_msg.ringPPNs[i] = base >> PAGE_SHIFT;
525                         base += PAGE_SIZE;
526                 }
527                 memset(adapter->msg_ring, 0, adapter->msg_pages * PAGE_SIZE);
528
529                 pvscsi_write_cmd_desc(adapter, PVSCSI_CMD_SETUP_MSG_RING,
530                                       &cmd_msg, sizeof(cmd_msg));
531         }
532 }
533
534 static int pvscsi_change_queue_depth(struct scsi_device *sdev, int qdepth)
535 {
536         if (!sdev->tagged_supported)
537                 qdepth = 1;
538         return scsi_change_queue_depth(sdev, qdepth);
539 }
540
541 /*
542  * Pull a completion descriptor off and pass the completion back
543  * to the SCSI mid layer.
544  */
545 static void pvscsi_complete_request(struct pvscsi_adapter *adapter,
546                                     const struct PVSCSIRingCmpDesc *e)
547 {
548         struct pvscsi_ctx *ctx;
549         struct scsi_cmnd *cmd;
550         struct completion *abort_cmp;
551         u32 btstat = e->hostStatus;
552         u32 sdstat = e->scsiStatus;
553
554         ctx = pvscsi_get_context(adapter, e->context);
555         cmd = ctx->cmd;
556         abort_cmp = ctx->abort_cmp;
557         pvscsi_unmap_buffers(adapter, ctx);
558         if (sdstat != SAM_STAT_CHECK_CONDITION)
559                 pvscsi_patch_sense(cmd);
560         pvscsi_release_context(adapter, ctx);
561         if (abort_cmp) {
562                 /*
563                  * The command was requested to be aborted. Just signal that
564                  * the request completed and swallow the actual cmd completion
565                  * here. The abort handler will post a completion for this
566                  * command indicating that it got successfully aborted.
567                  */
568                 complete(abort_cmp);
569                 return;
570         }
571
572         cmd->result = 0;
573         if (sdstat != SAM_STAT_GOOD &&
574             (btstat == BTSTAT_SUCCESS ||
575              btstat == BTSTAT_LINKED_COMMAND_COMPLETED ||
576              btstat == BTSTAT_LINKED_COMMAND_COMPLETED_WITH_FLAG)) {
577                 if (sdstat == SAM_STAT_COMMAND_TERMINATED) {
578                         cmd->result = (DID_RESET << 16);
579                 } else {
580                         cmd->result = (DID_OK << 16) | sdstat;
581                         if (sdstat == SAM_STAT_CHECK_CONDITION &&
582                             cmd->sense_buffer)
583                                 cmd->result |= (DRIVER_SENSE << 24);
584                 }
585         } else
586                 switch (btstat) {
587                 case BTSTAT_SUCCESS:
588                 case BTSTAT_LINKED_COMMAND_COMPLETED:
589                 case BTSTAT_LINKED_COMMAND_COMPLETED_WITH_FLAG:
590                         /*
591                          * Commands like INQUIRY may transfer less data than
592                          * requested by the initiator via bufflen. Set residual
593                          * count to make upper layer aware of the actual amount
594                          * of data returned. There are cases when controller
595                          * returns zero dataLen with non zero data - do not set
596                          * residual count in that case.
597                          */
598                         if (e->dataLen && (e->dataLen < scsi_bufflen(cmd)))
599                                 scsi_set_resid(cmd, scsi_bufflen(cmd) - e->dataLen);
600                         cmd->result = (DID_OK << 16);
601                         break;
602
603                 case BTSTAT_DATARUN:
604                 case BTSTAT_DATA_UNDERRUN:
605                         /* Report residual data in underruns */
606                         scsi_set_resid(cmd, scsi_bufflen(cmd) - e->dataLen);
607                         cmd->result = (DID_ERROR << 16);
608                         break;
609
610                 case BTSTAT_SELTIMEO:
611                         /* Our emulation returns this for non-connected devs */
612                         cmd->result = (DID_BAD_TARGET << 16);
613                         break;
614
615                 case BTSTAT_LUNMISMATCH:
616                 case BTSTAT_TAGREJECT:
617                 case BTSTAT_BADMSG:
618                         cmd->result = (DRIVER_INVALID << 24);
619                         fallthrough;
620
621                 case BTSTAT_HAHARDWARE:
622                 case BTSTAT_INVPHASE:
623                 case BTSTAT_HATIMEOUT:
624                 case BTSTAT_NORESPONSE:
625                 case BTSTAT_DISCONNECT:
626                 case BTSTAT_HASOFTWARE:
627                 case BTSTAT_BUSFREE:
628                 case BTSTAT_SENSFAILED:
629                         cmd->result |= (DID_ERROR << 16);
630                         break;
631
632                 case BTSTAT_SENTRST:
633                 case BTSTAT_RECVRST:
634                 case BTSTAT_BUSRESET:
635                         cmd->result = (DID_RESET << 16);
636                         break;
637
638                 case BTSTAT_ABORTQUEUE:
639                         cmd->result = (DID_BUS_BUSY << 16);
640                         break;
641
642                 case BTSTAT_SCSIPARITY:
643                         cmd->result = (DID_PARITY << 16);
644                         break;
645
646                 default:
647                         cmd->result = (DID_ERROR << 16);
648                         scmd_printk(KERN_DEBUG, cmd,
649                                     "Unknown completion status: 0x%x\n",
650                                     btstat);
651         }
652
653         dev_dbg(&cmd->device->sdev_gendev,
654                 "cmd=%p %x ctx=%p result=0x%x status=0x%x,%x\n",
655                 cmd, cmd->cmnd[0], ctx, cmd->result, btstat, sdstat);
656
657         cmd->scsi_done(cmd);
658 }
659
660 /*
661  * barrier usage : Since the PVSCSI device is emulated, there could be cases
662  * where we may want to serialize some accesses between the driver and the
663  * emulation layer. We use compiler barriers instead of the more expensive
664  * memory barriers because PVSCSI is only supported on X86 which has strong
665  * memory access ordering.
666  */
667 static void pvscsi_process_completion_ring(struct pvscsi_adapter *adapter)
668 {
669         struct PVSCSIRingsState *s = adapter->rings_state;
670         struct PVSCSIRingCmpDesc *ring = adapter->cmp_ring;
671         u32 cmp_entries = s->cmpNumEntriesLog2;
672
673         while (s->cmpConsIdx != s->cmpProdIdx) {
674                 struct PVSCSIRingCmpDesc *e = ring + (s->cmpConsIdx &
675                                                       MASK(cmp_entries));
676                 /*
677                  * This barrier() ensures that *e is not dereferenced while
678                  * the device emulation still writes data into the slot.
679                  * Since the device emulation advances s->cmpProdIdx only after
680                  * updating the slot we want to check it first.
681                  */
682                 barrier();
683                 pvscsi_complete_request(adapter, e);
684                 /*
685                  * This barrier() ensures that compiler doesn't reorder write
686                  * to s->cmpConsIdx before the read of (*e) inside
687                  * pvscsi_complete_request. Otherwise, device emulation may
688                  * overwrite *e before we had a chance to read it.
689                  */
690                 barrier();
691                 s->cmpConsIdx++;
692         }
693 }
694
695 /*
696  * Translate a Linux SCSI request into a request ring entry.
697  */
698 static int pvscsi_queue_ring(struct pvscsi_adapter *adapter,
699                              struct pvscsi_ctx *ctx, struct scsi_cmnd *cmd)
700 {
701         struct PVSCSIRingsState *s;
702         struct PVSCSIRingReqDesc *e;
703         struct scsi_device *sdev;
704         u32 req_entries;
705
706         s = adapter->rings_state;
707         sdev = cmd->device;
708         req_entries = s->reqNumEntriesLog2;
709
710         /*
711          * If this condition holds, we might have room on the request ring, but
712          * we might not have room on the completion ring for the response.
713          * However, we have already ruled out this possibility - we would not
714          * have successfully allocated a context if it were true, since we only
715          * have one context per request entry.  Check for it anyway, since it
716          * would be a serious bug.
717          */
718         if (s->reqProdIdx - s->cmpConsIdx >= 1 << req_entries) {
719                 scmd_printk(KERN_ERR, cmd, "vmw_pvscsi: "
720                             "ring full: reqProdIdx=%d cmpConsIdx=%d\n",
721                             s->reqProdIdx, s->cmpConsIdx);
722                 return -1;
723         }
724
725         e = adapter->req_ring + (s->reqProdIdx & MASK(req_entries));
726
727         e->bus    = sdev->channel;
728         e->target = sdev->id;
729         memset(e->lun, 0, sizeof(e->lun));
730         e->lun[1] = sdev->lun;
731
732         if (cmd->sense_buffer) {
733                 ctx->sensePA = dma_map_single(&adapter->dev->dev,
734                                 cmd->sense_buffer, SCSI_SENSE_BUFFERSIZE,
735                                 DMA_FROM_DEVICE);
736                 if (dma_mapping_error(&adapter->dev->dev, ctx->sensePA)) {
737                         scmd_printk(KERN_DEBUG, cmd,
738                                     "vmw_pvscsi: Failed to map sense buffer for DMA.\n");
739                         ctx->sensePA = 0;
740                         return -ENOMEM;
741                 }
742                 e->senseAddr = ctx->sensePA;
743                 e->senseLen = SCSI_SENSE_BUFFERSIZE;
744         } else {
745                 e->senseLen  = 0;
746                 e->senseAddr = 0;
747         }
748         e->cdbLen   = cmd->cmd_len;
749         e->vcpuHint = smp_processor_id();
750         memcpy(e->cdb, cmd->cmnd, e->cdbLen);
751
752         e->tag = SIMPLE_QUEUE_TAG;
753
754         if (cmd->sc_data_direction == DMA_FROM_DEVICE)
755                 e->flags = PVSCSI_FLAG_CMD_DIR_TOHOST;
756         else if (cmd->sc_data_direction == DMA_TO_DEVICE)
757                 e->flags = PVSCSI_FLAG_CMD_DIR_TODEVICE;
758         else if (cmd->sc_data_direction == DMA_NONE)
759                 e->flags = PVSCSI_FLAG_CMD_DIR_NONE;
760         else
761                 e->flags = 0;
762
763         if (pvscsi_map_buffers(adapter, ctx, cmd, e) != 0) {
764                 if (cmd->sense_buffer) {
765                         dma_unmap_single(&adapter->dev->dev, ctx->sensePA,
766                                          SCSI_SENSE_BUFFERSIZE,
767                                          DMA_FROM_DEVICE);
768                         ctx->sensePA = 0;
769                 }
770                 return -ENOMEM;
771         }
772
773         e->context = pvscsi_map_context(adapter, ctx);
774
775         barrier();
776
777         s->reqProdIdx++;
778
779         return 0;
780 }
781
782 static int pvscsi_queue_lck(struct scsi_cmnd *cmd, void (*done)(struct scsi_cmnd *))
783 {
784         struct Scsi_Host *host = cmd->device->host;
785         struct pvscsi_adapter *adapter = shost_priv(host);
786         struct pvscsi_ctx *ctx;
787         unsigned long flags;
788         unsigned char op;
789
790         spin_lock_irqsave(&adapter->hw_lock, flags);
791
792         ctx = pvscsi_acquire_context(adapter, cmd);
793         if (!ctx || pvscsi_queue_ring(adapter, ctx, cmd) != 0) {
794                 if (ctx)
795                         pvscsi_release_context(adapter, ctx);
796                 spin_unlock_irqrestore(&adapter->hw_lock, flags);
797                 return SCSI_MLQUEUE_HOST_BUSY;
798         }
799
800         cmd->scsi_done = done;
801         op = cmd->cmnd[0];
802
803         dev_dbg(&cmd->device->sdev_gendev,
804                 "queued cmd %p, ctx %p, op=%x\n", cmd, ctx, op);
805
806         spin_unlock_irqrestore(&adapter->hw_lock, flags);
807
808         pvscsi_kick_io(adapter, op);
809
810         return 0;
811 }
812
813 static DEF_SCSI_QCMD(pvscsi_queue)
814
815 static int pvscsi_abort(struct scsi_cmnd *cmd)
816 {
817         struct pvscsi_adapter *adapter = shost_priv(cmd->device->host);
818         struct pvscsi_ctx *ctx;
819         unsigned long flags;
820         int result = SUCCESS;
821         DECLARE_COMPLETION_ONSTACK(abort_cmp);
822         int done;
823
824         scmd_printk(KERN_DEBUG, cmd, "task abort on host %u, %p\n",
825                     adapter->host->host_no, cmd);
826
827         spin_lock_irqsave(&adapter->hw_lock, flags);
828
829         /*
830          * Poll the completion ring first - we might be trying to abort
831          * a command that is waiting to be dispatched in the completion ring.
832          */
833         pvscsi_process_completion_ring(adapter);
834
835         /*
836          * If there is no context for the command, it either already succeeded
837          * or else was never properly issued.  Not our problem.
838          */
839         ctx = pvscsi_find_context(adapter, cmd);
840         if (!ctx) {
841                 scmd_printk(KERN_DEBUG, cmd, "Failed to abort cmd %p\n", cmd);
842                 goto out;
843         }
844
845         /*
846          * Mark that the command has been requested to be aborted and issue
847          * the abort.
848          */
849         ctx->abort_cmp = &abort_cmp;
850
851         pvscsi_abort_cmd(adapter, ctx);
852         spin_unlock_irqrestore(&adapter->hw_lock, flags);
853         /* Wait for 2 secs for the completion. */
854         done = wait_for_completion_timeout(&abort_cmp, msecs_to_jiffies(2000));
855         spin_lock_irqsave(&adapter->hw_lock, flags);
856
857         if (!done) {
858                 /*
859                  * Failed to abort the command, unmark the fact that it
860                  * was requested to be aborted.
861                  */
862                 ctx->abort_cmp = NULL;
863                 result = FAILED;
864                 scmd_printk(KERN_DEBUG, cmd,
865                             "Failed to get completion for aborted cmd %p\n",
866                             cmd);
867                 goto out;
868         }
869
870         /*
871          * Successfully aborted the command.
872          */
873         cmd->result = (DID_ABORT << 16);
874         cmd->scsi_done(cmd);
875
876 out:
877         spin_unlock_irqrestore(&adapter->hw_lock, flags);
878         return result;
879 }
880
881 /*
882  * Abort all outstanding requests.  This is only safe to use if the completion
883  * ring will never be walked again or the device has been reset, because it
884  * destroys the 1-1 mapping between context field passed to emulation and our
885  * request structure.
886  */
887 static void pvscsi_reset_all(struct pvscsi_adapter *adapter)
888 {
889         unsigned i;
890
891         for (i = 0; i < adapter->req_depth; i++) {
892                 struct pvscsi_ctx *ctx = &adapter->cmd_map[i];
893                 struct scsi_cmnd *cmd = ctx->cmd;
894                 if (cmd) {
895                         scmd_printk(KERN_ERR, cmd,
896                                     "Forced reset on cmd %p\n", cmd);
897                         pvscsi_unmap_buffers(adapter, ctx);
898                         pvscsi_patch_sense(cmd);
899                         pvscsi_release_context(adapter, ctx);
900                         cmd->result = (DID_RESET << 16);
901                         cmd->scsi_done(cmd);
902                 }
903         }
904 }
905
906 static int pvscsi_host_reset(struct scsi_cmnd *cmd)
907 {
908         struct Scsi_Host *host = cmd->device->host;
909         struct pvscsi_adapter *adapter = shost_priv(host);
910         unsigned long flags;
911         bool use_msg;
912
913         scmd_printk(KERN_INFO, cmd, "SCSI Host reset\n");
914
915         spin_lock_irqsave(&adapter->hw_lock, flags);
916
917         use_msg = adapter->use_msg;
918
919         if (use_msg) {
920                 adapter->use_msg = false;
921                 spin_unlock_irqrestore(&adapter->hw_lock, flags);
922
923                 /*
924                  * Now that we know that the ISR won't add more work on the
925                  * workqueue we can safely flush any outstanding work.
926                  */
927                 flush_workqueue(adapter->workqueue);
928                 spin_lock_irqsave(&adapter->hw_lock, flags);
929         }
930
931         /*
932          * We're going to tear down the entire ring structure and set it back
933          * up, so stalling new requests until all completions are flushed and
934          * the rings are back in place.
935          */
936
937         pvscsi_process_request_ring(adapter);
938
939         ll_adapter_reset(adapter);
940
941         /*
942          * Now process any completions.  Note we do this AFTER adapter reset,
943          * which is strange, but stops races where completions get posted
944          * between processing the ring and issuing the reset.  The backend will
945          * not touch the ring memory after reset, so the immediately pre-reset
946          * completion ring state is still valid.
947          */
948         pvscsi_process_completion_ring(adapter);
949
950         pvscsi_reset_all(adapter);
951         adapter->use_msg = use_msg;
952         pvscsi_setup_all_rings(adapter);
953         pvscsi_unmask_intr(adapter);
954
955         spin_unlock_irqrestore(&adapter->hw_lock, flags);
956
957         return SUCCESS;
958 }
959
960 static int pvscsi_bus_reset(struct scsi_cmnd *cmd)
961 {
962         struct Scsi_Host *host = cmd->device->host;
963         struct pvscsi_adapter *adapter = shost_priv(host);
964         unsigned long flags;
965
966         scmd_printk(KERN_INFO, cmd, "SCSI Bus reset\n");
967
968         /*
969          * We don't want to queue new requests for this bus after
970          * flushing all pending requests to emulation, since new
971          * requests could then sneak in during this bus reset phase,
972          * so take the lock now.
973          */
974         spin_lock_irqsave(&adapter->hw_lock, flags);
975
976         pvscsi_process_request_ring(adapter);
977         ll_bus_reset(adapter);
978         pvscsi_process_completion_ring(adapter);
979
980         spin_unlock_irqrestore(&adapter->hw_lock, flags);
981
982         return SUCCESS;
983 }
984
985 static int pvscsi_device_reset(struct scsi_cmnd *cmd)
986 {
987         struct Scsi_Host *host = cmd->device->host;
988         struct pvscsi_adapter *adapter = shost_priv(host);
989         unsigned long flags;
990
991         scmd_printk(KERN_INFO, cmd, "SCSI device reset on scsi%u:%u\n",
992                     host->host_no, cmd->device->id);
993
994         /*
995          * We don't want to queue new requests for this device after flushing
996          * all pending requests to emulation, since new requests could then
997          * sneak in during this device reset phase, so take the lock now.
998          */
999         spin_lock_irqsave(&adapter->hw_lock, flags);
1000
1001         pvscsi_process_request_ring(adapter);
1002         ll_device_reset(adapter, cmd->device->id);
1003         pvscsi_process_completion_ring(adapter);
1004
1005         spin_unlock_irqrestore(&adapter->hw_lock, flags);
1006
1007         return SUCCESS;
1008 }
1009
1010 static struct scsi_host_template pvscsi_template;
1011
1012 static const char *pvscsi_info(struct Scsi_Host *host)
1013 {
1014         struct pvscsi_adapter *adapter = shost_priv(host);
1015         static char buf[256];
1016
1017         sprintf(buf, "VMware PVSCSI storage adapter rev %d, req/cmp/msg rings: "
1018                 "%u/%u/%u pages, cmd_per_lun=%u", adapter->rev,
1019                 adapter->req_pages, adapter->cmp_pages, adapter->msg_pages,
1020                 pvscsi_template.cmd_per_lun);
1021
1022         return buf;
1023 }
1024
1025 static struct scsi_host_template pvscsi_template = {
1026         .module                         = THIS_MODULE,
1027         .name                           = "VMware PVSCSI Host Adapter",
1028         .proc_name                      = "vmw_pvscsi",
1029         .info                           = pvscsi_info,
1030         .queuecommand                   = pvscsi_queue,
1031         .this_id                        = -1,
1032         .sg_tablesize                   = PVSCSI_MAX_NUM_SG_ENTRIES_PER_SEGMENT,
1033         .dma_boundary                   = UINT_MAX,
1034         .max_sectors                    = 0xffff,
1035         .change_queue_depth             = pvscsi_change_queue_depth,
1036         .eh_abort_handler               = pvscsi_abort,
1037         .eh_device_reset_handler        = pvscsi_device_reset,
1038         .eh_bus_reset_handler           = pvscsi_bus_reset,
1039         .eh_host_reset_handler          = pvscsi_host_reset,
1040 };
1041
1042 static void pvscsi_process_msg(const struct pvscsi_adapter *adapter,
1043                                const struct PVSCSIRingMsgDesc *e)
1044 {
1045         struct PVSCSIRingsState *s = adapter->rings_state;
1046         struct Scsi_Host *host = adapter->host;
1047         struct scsi_device *sdev;
1048
1049         printk(KERN_INFO "vmw_pvscsi: msg type: 0x%x - MSG RING: %u/%u (%u) \n",
1050                e->type, s->msgProdIdx, s->msgConsIdx, s->msgNumEntriesLog2);
1051
1052         BUILD_BUG_ON(PVSCSI_MSG_LAST != 2);
1053
1054         if (e->type == PVSCSI_MSG_DEV_ADDED) {
1055                 struct PVSCSIMsgDescDevStatusChanged *desc;
1056                 desc = (struct PVSCSIMsgDescDevStatusChanged *)e;
1057
1058                 printk(KERN_INFO
1059                        "vmw_pvscsi: msg: device added at scsi%u:%u:%u\n",
1060                        desc->bus, desc->target, desc->lun[1]);
1061
1062                 if (!scsi_host_get(host))
1063                         return;
1064
1065                 sdev = scsi_device_lookup(host, desc->bus, desc->target,
1066                                           desc->lun[1]);
1067                 if (sdev) {
1068                         printk(KERN_INFO "vmw_pvscsi: device already exists\n");
1069                         scsi_device_put(sdev);
1070                 } else
1071                         scsi_add_device(adapter->host, desc->bus,
1072                                         desc->target, desc->lun[1]);
1073
1074                 scsi_host_put(host);
1075         } else if (e->type == PVSCSI_MSG_DEV_REMOVED) {
1076                 struct PVSCSIMsgDescDevStatusChanged *desc;
1077                 desc = (struct PVSCSIMsgDescDevStatusChanged *)e;
1078
1079                 printk(KERN_INFO
1080                        "vmw_pvscsi: msg: device removed at scsi%u:%u:%u\n",
1081                        desc->bus, desc->target, desc->lun[1]);
1082
1083                 if (!scsi_host_get(host))
1084                         return;
1085
1086                 sdev = scsi_device_lookup(host, desc->bus, desc->target,
1087                                           desc->lun[1]);
1088                 if (sdev) {
1089                         scsi_remove_device(sdev);
1090                         scsi_device_put(sdev);
1091                 } else
1092                         printk(KERN_INFO
1093                                "vmw_pvscsi: failed to lookup scsi%u:%u:%u\n",
1094                                desc->bus, desc->target, desc->lun[1]);
1095
1096                 scsi_host_put(host);
1097         }
1098 }
1099
1100 static int pvscsi_msg_pending(const struct pvscsi_adapter *adapter)
1101 {
1102         struct PVSCSIRingsState *s = adapter->rings_state;
1103
1104         return s->msgProdIdx != s->msgConsIdx;
1105 }
1106
1107 static void pvscsi_process_msg_ring(const struct pvscsi_adapter *adapter)
1108 {
1109         struct PVSCSIRingsState *s = adapter->rings_state;
1110         struct PVSCSIRingMsgDesc *ring = adapter->msg_ring;
1111         u32 msg_entries = s->msgNumEntriesLog2;
1112
1113         while (pvscsi_msg_pending(adapter)) {
1114                 struct PVSCSIRingMsgDesc *e = ring + (s->msgConsIdx &
1115                                                       MASK(msg_entries));
1116
1117                 barrier();
1118                 pvscsi_process_msg(adapter, e);
1119                 barrier();
1120                 s->msgConsIdx++;
1121         }
1122 }
1123
1124 static void pvscsi_msg_workqueue_handler(struct work_struct *data)
1125 {
1126         struct pvscsi_adapter *adapter;
1127
1128         adapter = container_of(data, struct pvscsi_adapter, work);
1129
1130         pvscsi_process_msg_ring(adapter);
1131 }
1132
1133 static int pvscsi_setup_msg_workqueue(struct pvscsi_adapter *adapter)
1134 {
1135         char name[32];
1136
1137         if (!pvscsi_use_msg)
1138                 return 0;
1139
1140         pvscsi_reg_write(adapter, PVSCSI_REG_OFFSET_COMMAND,
1141                          PVSCSI_CMD_SETUP_MSG_RING);
1142
1143         if (pvscsi_reg_read(adapter, PVSCSI_REG_OFFSET_COMMAND_STATUS) == -1)
1144                 return 0;
1145
1146         snprintf(name, sizeof(name),
1147                  "vmw_pvscsi_wq_%u", adapter->host->host_no);
1148
1149         adapter->workqueue = create_singlethread_workqueue(name);
1150         if (!adapter->workqueue) {
1151                 printk(KERN_ERR "vmw_pvscsi: failed to create work queue\n");
1152                 return 0;
1153         }
1154         INIT_WORK(&adapter->work, pvscsi_msg_workqueue_handler);
1155
1156         return 1;
1157 }
1158
1159 static bool pvscsi_setup_req_threshold(struct pvscsi_adapter *adapter,
1160                                       bool enable)
1161 {
1162         u32 val;
1163
1164         if (!pvscsi_use_req_threshold)
1165                 return false;
1166
1167         pvscsi_reg_write(adapter, PVSCSI_REG_OFFSET_COMMAND,
1168                          PVSCSI_CMD_SETUP_REQCALLTHRESHOLD);
1169         val = pvscsi_reg_read(adapter, PVSCSI_REG_OFFSET_COMMAND_STATUS);
1170         if (val == -1) {
1171                 printk(KERN_INFO "vmw_pvscsi: device does not support req_threshold\n");
1172                 return false;
1173         } else {
1174                 struct PVSCSICmdDescSetupReqCall cmd_msg = { 0 };
1175                 cmd_msg.enable = enable;
1176                 printk(KERN_INFO
1177                        "vmw_pvscsi: %sabling reqCallThreshold\n",
1178                         enable ? "en" : "dis");
1179                 pvscsi_write_cmd_desc(adapter,
1180                                       PVSCSI_CMD_SETUP_REQCALLTHRESHOLD,
1181                                       &cmd_msg, sizeof(cmd_msg));
1182                 return pvscsi_reg_read(adapter,
1183                                        PVSCSI_REG_OFFSET_COMMAND_STATUS) != 0;
1184         }
1185 }
1186
1187 static irqreturn_t pvscsi_isr(int irq, void *devp)
1188 {
1189         struct pvscsi_adapter *adapter = devp;
1190         unsigned long flags;
1191
1192         spin_lock_irqsave(&adapter->hw_lock, flags);
1193         pvscsi_process_completion_ring(adapter);
1194         if (adapter->use_msg && pvscsi_msg_pending(adapter))
1195                 queue_work(adapter->workqueue, &adapter->work);
1196         spin_unlock_irqrestore(&adapter->hw_lock, flags);
1197
1198         return IRQ_HANDLED;
1199 }
1200
1201 static irqreturn_t pvscsi_shared_isr(int irq, void *devp)
1202 {
1203         struct pvscsi_adapter *adapter = devp;
1204         u32 val = pvscsi_read_intr_status(adapter);
1205
1206         if (!(val & PVSCSI_INTR_ALL_SUPPORTED))
1207                 return IRQ_NONE;
1208         pvscsi_write_intr_status(devp, val);
1209         return pvscsi_isr(irq, devp);
1210 }
1211
1212 static void pvscsi_free_sgls(const struct pvscsi_adapter *adapter)
1213 {
1214         struct pvscsi_ctx *ctx = adapter->cmd_map;
1215         unsigned i;
1216
1217         for (i = 0; i < adapter->req_depth; ++i, ++ctx)
1218                 free_pages((unsigned long)ctx->sgl, get_order(SGL_SIZE));
1219 }
1220
1221 static void pvscsi_shutdown_intr(struct pvscsi_adapter *adapter)
1222 {
1223         free_irq(pci_irq_vector(adapter->dev, 0), adapter);
1224         pci_free_irq_vectors(adapter->dev);
1225 }
1226
1227 static void pvscsi_release_resources(struct pvscsi_adapter *adapter)
1228 {
1229         if (adapter->workqueue)
1230                 destroy_workqueue(adapter->workqueue);
1231
1232         if (adapter->mmioBase)
1233                 pci_iounmap(adapter->dev, adapter->mmioBase);
1234
1235         pci_release_regions(adapter->dev);
1236
1237         if (adapter->cmd_map) {
1238                 pvscsi_free_sgls(adapter);
1239                 kfree(adapter->cmd_map);
1240         }
1241
1242         if (adapter->rings_state)
1243                 dma_free_coherent(&adapter->dev->dev, PAGE_SIZE,
1244                                     adapter->rings_state, adapter->ringStatePA);
1245
1246         if (adapter->req_ring)
1247                 dma_free_coherent(&adapter->dev->dev,
1248                                     adapter->req_pages * PAGE_SIZE,
1249                                     adapter->req_ring, adapter->reqRingPA);
1250
1251         if (adapter->cmp_ring)
1252                 dma_free_coherent(&adapter->dev->dev,
1253                                     adapter->cmp_pages * PAGE_SIZE,
1254                                     adapter->cmp_ring, adapter->cmpRingPA);
1255
1256         if (adapter->msg_ring)
1257                 dma_free_coherent(&adapter->dev->dev,
1258                                     adapter->msg_pages * PAGE_SIZE,
1259                                     adapter->msg_ring, adapter->msgRingPA);
1260 }
1261
1262 /*
1263  * Allocate scatter gather lists.
1264  *
1265  * These are statically allocated.  Trying to be clever was not worth it.
1266  *
1267  * Dynamic allocation can fail, and we can't go deep into the memory
1268  * allocator, since we're a SCSI driver, and trying too hard to allocate
1269  * memory might generate disk I/O.  We also don't want to fail disk I/O
1270  * in that case because we can't get an allocation - the I/O could be
1271  * trying to swap out data to free memory.  Since that is pathological,
1272  * just use a statically allocated scatter list.
1273  *
1274  */
1275 static int pvscsi_allocate_sg(struct pvscsi_adapter *adapter)
1276 {
1277         struct pvscsi_ctx *ctx;
1278         int i;
1279
1280         ctx = adapter->cmd_map;
1281         BUILD_BUG_ON(sizeof(struct pvscsi_sg_list) > SGL_SIZE);
1282
1283         for (i = 0; i < adapter->req_depth; ++i, ++ctx) {
1284                 ctx->sgl = (void *)__get_free_pages(GFP_KERNEL,
1285                                                     get_order(SGL_SIZE));
1286                 ctx->sglPA = 0;
1287                 BUG_ON(!IS_ALIGNED(((unsigned long)ctx->sgl), PAGE_SIZE));
1288                 if (!ctx->sgl) {
1289                         for (; i >= 0; --i, --ctx) {
1290                                 free_pages((unsigned long)ctx->sgl,
1291                                            get_order(SGL_SIZE));
1292                                 ctx->sgl = NULL;
1293                         }
1294                         return -ENOMEM;
1295                 }
1296         }
1297
1298         return 0;
1299 }
1300
1301 /*
1302  * Query the device, fetch the config info and return the
1303  * maximum number of targets on the adapter. In case of
1304  * failure due to any reason return default i.e. 16.
1305  */
1306 static u32 pvscsi_get_max_targets(struct pvscsi_adapter *adapter)
1307 {
1308         struct PVSCSICmdDescConfigCmd cmd;
1309         struct PVSCSIConfigPageHeader *header;
1310         struct device *dev;
1311         dma_addr_t configPagePA;
1312         void *config_page;
1313         u32 numPhys = 16;
1314
1315         dev = pvscsi_dev(adapter);
1316         config_page = dma_alloc_coherent(&adapter->dev->dev, PAGE_SIZE,
1317                         &configPagePA, GFP_KERNEL);
1318         if (!config_page) {
1319                 dev_warn(dev, "vmw_pvscsi: failed to allocate memory for config page\n");
1320                 goto exit;
1321         }
1322         BUG_ON(configPagePA & ~PAGE_MASK);
1323
1324         /* Fetch config info from the device. */
1325         cmd.configPageAddress = ((u64)PVSCSI_CONFIG_CONTROLLER_ADDRESS) << 32;
1326         cmd.configPageNum = PVSCSI_CONFIG_PAGE_CONTROLLER;
1327         cmd.cmpAddr = configPagePA;
1328         cmd._pad = 0;
1329
1330         /*
1331          * Mark the completion page header with error values. If the device
1332          * completes the command successfully, it sets the status values to
1333          * indicate success.
1334          */
1335         header = config_page;
1336         memset(header, 0, sizeof *header);
1337         header->hostStatus = BTSTAT_INVPARAM;
1338         header->scsiStatus = SDSTAT_CHECK;
1339
1340         pvscsi_write_cmd_desc(adapter, PVSCSI_CMD_CONFIG, &cmd, sizeof cmd);
1341
1342         if (header->hostStatus == BTSTAT_SUCCESS &&
1343             header->scsiStatus == SDSTAT_GOOD) {
1344                 struct PVSCSIConfigPageController *config;
1345
1346                 config = config_page;
1347                 numPhys = config->numPhys;
1348         } else
1349                 dev_warn(dev, "vmw_pvscsi: PVSCSI_CMD_CONFIG failed. hostStatus = 0x%x, scsiStatus = 0x%x\n",
1350                          header->hostStatus, header->scsiStatus);
1351         dma_free_coherent(&adapter->dev->dev, PAGE_SIZE, config_page,
1352                           configPagePA);
1353 exit:
1354         return numPhys;
1355 }
1356
1357 static int pvscsi_probe(struct pci_dev *pdev, const struct pci_device_id *id)
1358 {
1359         unsigned int irq_flag = PCI_IRQ_MSIX | PCI_IRQ_MSI | PCI_IRQ_LEGACY;
1360         struct pvscsi_adapter *adapter;
1361         struct pvscsi_adapter adapter_temp;
1362         struct Scsi_Host *host = NULL;
1363         unsigned int i;
1364         int error;
1365         u32 max_id;
1366
1367         error = -ENODEV;
1368
1369         if (pci_enable_device(pdev))
1370                 return error;
1371
1372         if (!dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64))) {
1373                 printk(KERN_INFO "vmw_pvscsi: using 64bit dma\n");
1374         } else if (!dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32))) {
1375                 printk(KERN_INFO "vmw_pvscsi: using 32bit dma\n");
1376         } else {
1377                 printk(KERN_ERR "vmw_pvscsi: failed to set DMA mask\n");
1378                 goto out_disable_device;
1379         }
1380
1381         /*
1382          * Let's use a temp pvscsi_adapter struct until we find the number of
1383          * targets on the adapter, after that we will switch to the real
1384          * allocated struct.
1385          */
1386         adapter = &adapter_temp;
1387         memset(adapter, 0, sizeof(*adapter));
1388         adapter->dev  = pdev;
1389         adapter->rev = pdev->revision;
1390
1391         if (pci_request_regions(pdev, "vmw_pvscsi")) {
1392                 printk(KERN_ERR "vmw_pvscsi: pci memory selection failed\n");
1393                 goto out_disable_device;
1394         }
1395
1396         for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
1397                 if ((pci_resource_flags(pdev, i) & PCI_BASE_ADDRESS_SPACE_IO))
1398                         continue;
1399
1400                 if (pci_resource_len(pdev, i) < PVSCSI_MEM_SPACE_SIZE)
1401                         continue;
1402
1403                 break;
1404         }
1405
1406         if (i == DEVICE_COUNT_RESOURCE) {
1407                 printk(KERN_ERR
1408                        "vmw_pvscsi: adapter has no suitable MMIO region\n");
1409                 goto out_release_resources_and_disable;
1410         }
1411
1412         adapter->mmioBase = pci_iomap(pdev, i, PVSCSI_MEM_SPACE_SIZE);
1413
1414         if (!adapter->mmioBase) {
1415                 printk(KERN_ERR
1416                        "vmw_pvscsi: can't iomap for BAR %d memsize %lu\n",
1417                        i, PVSCSI_MEM_SPACE_SIZE);
1418                 goto out_release_resources_and_disable;
1419         }
1420
1421         pci_set_master(pdev);
1422
1423         /*
1424          * Ask the device for max number of targets before deciding the
1425          * default pvscsi_ring_pages value.
1426          */
1427         max_id = pvscsi_get_max_targets(adapter);
1428         printk(KERN_INFO "vmw_pvscsi: max_id: %u\n", max_id);
1429
1430         if (pvscsi_ring_pages == 0)
1431                 /*
1432                  * Set the right default value. Up to 16 it is 8, above it is
1433                  * max.
1434                  */
1435                 pvscsi_ring_pages = (max_id > 16) ?
1436                         PVSCSI_SETUP_RINGS_MAX_NUM_PAGES :
1437                         PVSCSI_DEFAULT_NUM_PAGES_PER_RING;
1438         printk(KERN_INFO
1439                "vmw_pvscsi: setting ring_pages to %d\n",
1440                pvscsi_ring_pages);
1441
1442         pvscsi_template.can_queue =
1443                 min(PVSCSI_MAX_NUM_PAGES_REQ_RING, pvscsi_ring_pages) *
1444                 PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE;
1445         pvscsi_template.cmd_per_lun =
1446                 min(pvscsi_template.can_queue, pvscsi_cmd_per_lun);
1447         host = scsi_host_alloc(&pvscsi_template, sizeof(struct pvscsi_adapter));
1448         if (!host) {
1449                 printk(KERN_ERR "vmw_pvscsi: failed to allocate host\n");
1450                 goto out_release_resources_and_disable;
1451         }
1452
1453         /*
1454          * Let's use the real pvscsi_adapter struct here onwards.
1455          */
1456         adapter = shost_priv(host);
1457         memset(adapter, 0, sizeof(*adapter));
1458         adapter->dev  = pdev;
1459         adapter->host = host;
1460         /*
1461          * Copy back what we already have to the allocated adapter struct.
1462          */
1463         adapter->rev = adapter_temp.rev;
1464         adapter->mmioBase = adapter_temp.mmioBase;
1465
1466         spin_lock_init(&adapter->hw_lock);
1467         host->max_channel = 0;
1468         host->max_lun     = 1;
1469         host->max_cmd_len = 16;
1470         host->max_id      = max_id;
1471
1472         pci_set_drvdata(pdev, host);
1473
1474         ll_adapter_reset(adapter);
1475
1476         adapter->use_msg = pvscsi_setup_msg_workqueue(adapter);
1477
1478         error = pvscsi_allocate_rings(adapter);
1479         if (error) {
1480                 printk(KERN_ERR "vmw_pvscsi: unable to allocate ring memory\n");
1481                 goto out_release_resources;
1482         }
1483
1484         /*
1485          * From this point on we should reset the adapter if anything goes
1486          * wrong.
1487          */
1488         pvscsi_setup_all_rings(adapter);
1489
1490         adapter->cmd_map = kcalloc(adapter->req_depth,
1491                                    sizeof(struct pvscsi_ctx), GFP_KERNEL);
1492         if (!adapter->cmd_map) {
1493                 printk(KERN_ERR "vmw_pvscsi: failed to allocate memory.\n");
1494                 error = -ENOMEM;
1495                 goto out_reset_adapter;
1496         }
1497
1498         INIT_LIST_HEAD(&adapter->cmd_pool);
1499         for (i = 0; i < adapter->req_depth; i++) {
1500                 struct pvscsi_ctx *ctx = adapter->cmd_map + i;
1501                 list_add(&ctx->list, &adapter->cmd_pool);
1502         }
1503
1504         error = pvscsi_allocate_sg(adapter);
1505         if (error) {
1506                 printk(KERN_ERR "vmw_pvscsi: unable to allocate s/g table\n");
1507                 goto out_reset_adapter;
1508         }
1509
1510         if (pvscsi_disable_msix)
1511                 irq_flag &= ~PCI_IRQ_MSIX;
1512         if (pvscsi_disable_msi)
1513                 irq_flag &= ~PCI_IRQ_MSI;
1514
1515         error = pci_alloc_irq_vectors(adapter->dev, 1, 1, irq_flag);
1516         if (error < 0)
1517                 goto out_reset_adapter;
1518
1519         adapter->use_req_threshold = pvscsi_setup_req_threshold(adapter, true);
1520         printk(KERN_DEBUG "vmw_pvscsi: driver-based request coalescing %sabled\n",
1521                adapter->use_req_threshold ? "en" : "dis");
1522
1523         if (adapter->dev->msix_enabled || adapter->dev->msi_enabled) {
1524                 printk(KERN_INFO "vmw_pvscsi: using MSI%s\n",
1525                         adapter->dev->msix_enabled ? "-X" : "");
1526                 error = request_irq(pci_irq_vector(pdev, 0), pvscsi_isr,
1527                                 0, "vmw_pvscsi", adapter);
1528         } else {
1529                 printk(KERN_INFO "vmw_pvscsi: using INTx\n");
1530                 error = request_irq(pci_irq_vector(pdev, 0), pvscsi_shared_isr,
1531                                 IRQF_SHARED, "vmw_pvscsi", adapter);
1532         }
1533
1534         if (error) {
1535                 printk(KERN_ERR
1536                        "vmw_pvscsi: unable to request IRQ: %d\n", error);
1537                 goto out_reset_adapter;
1538         }
1539
1540         error = scsi_add_host(host, &pdev->dev);
1541         if (error) {
1542                 printk(KERN_ERR
1543                        "vmw_pvscsi: scsi_add_host failed: %d\n", error);
1544                 goto out_reset_adapter;
1545         }
1546
1547         dev_info(&pdev->dev, "VMware PVSCSI rev %d host #%u\n",
1548                  adapter->rev, host->host_no);
1549
1550         pvscsi_unmask_intr(adapter);
1551
1552         scsi_scan_host(host);
1553
1554         return 0;
1555
1556 out_reset_adapter:
1557         ll_adapter_reset(adapter);
1558 out_release_resources:
1559         pvscsi_shutdown_intr(adapter);
1560         pvscsi_release_resources(adapter);
1561         scsi_host_put(host);
1562 out_disable_device:
1563         pci_disable_device(pdev);
1564
1565         return error;
1566
1567 out_release_resources_and_disable:
1568         pvscsi_shutdown_intr(adapter);
1569         pvscsi_release_resources(adapter);
1570         goto out_disable_device;
1571 }
1572
1573 static void __pvscsi_shutdown(struct pvscsi_adapter *adapter)
1574 {
1575         pvscsi_mask_intr(adapter);
1576
1577         if (adapter->workqueue)
1578                 flush_workqueue(adapter->workqueue);
1579
1580         pvscsi_shutdown_intr(adapter);
1581
1582         pvscsi_process_request_ring(adapter);
1583         pvscsi_process_completion_ring(adapter);
1584         ll_adapter_reset(adapter);
1585 }
1586
1587 static void pvscsi_shutdown(struct pci_dev *dev)
1588 {
1589         struct Scsi_Host *host = pci_get_drvdata(dev);
1590         struct pvscsi_adapter *adapter = shost_priv(host);
1591
1592         __pvscsi_shutdown(adapter);
1593 }
1594
1595 static void pvscsi_remove(struct pci_dev *pdev)
1596 {
1597         struct Scsi_Host *host = pci_get_drvdata(pdev);
1598         struct pvscsi_adapter *adapter = shost_priv(host);
1599
1600         scsi_remove_host(host);
1601
1602         __pvscsi_shutdown(adapter);
1603         pvscsi_release_resources(adapter);
1604
1605         scsi_host_put(host);
1606
1607         pci_disable_device(pdev);
1608 }
1609
1610 static struct pci_driver pvscsi_pci_driver = {
1611         .name           = "vmw_pvscsi",
1612         .id_table       = pvscsi_pci_tbl,
1613         .probe          = pvscsi_probe,
1614         .remove         = pvscsi_remove,
1615         .shutdown       = pvscsi_shutdown,
1616 };
1617
1618 static int __init pvscsi_init(void)
1619 {
1620         pr_info("%s - version %s\n",
1621                 PVSCSI_LINUX_DRIVER_DESC, PVSCSI_DRIVER_VERSION_STRING);
1622         return pci_register_driver(&pvscsi_pci_driver);
1623 }
1624
1625 static void __exit pvscsi_exit(void)
1626 {
1627         pci_unregister_driver(&pvscsi_pci_driver);
1628 }
1629
1630 module_init(pvscsi_init);
1631 module_exit(pvscsi_exit);