thermal: rockchip: rk3368: ajust tsadc's data path according request of qos
[firefly-linux-kernel-4.4.55.git] / drivers / scsi / storvsc_drv.c
1 /*
2  * Copyright (c) 2009, Microsoft Corporation.
3  *
4  * This program is free software; you can redistribute it and/or modify it
5  * under the terms and conditions of the GNU General Public License,
6  * version 2, as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope it will be useful, but WITHOUT
9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
11  * more details.
12  *
13  * You should have received a copy of the GNU General Public License along with
14  * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
15  * Place - Suite 330, Boston, MA 02111-1307 USA.
16  *
17  * Authors:
18  *   Haiyang Zhang <haiyangz@microsoft.com>
19  *   Hank Janssen  <hjanssen@microsoft.com>
20  *   K. Y. Srinivasan <kys@microsoft.com>
21  */
22
23 #include <linux/kernel.h>
24 #include <linux/wait.h>
25 #include <linux/sched.h>
26 #include <linux/completion.h>
27 #include <linux/string.h>
28 #include <linux/mm.h>
29 #include <linux/delay.h>
30 #include <linux/init.h>
31 #include <linux/slab.h>
32 #include <linux/module.h>
33 #include <linux/device.h>
34 #include <linux/hyperv.h>
35 #include <linux/blkdev.h>
36 #include <scsi/scsi.h>
37 #include <scsi/scsi_cmnd.h>
38 #include <scsi/scsi_host.h>
39 #include <scsi/scsi_device.h>
40 #include <scsi/scsi_tcq.h>
41 #include <scsi/scsi_eh.h>
42 #include <scsi/scsi_devinfo.h>
43 #include <scsi/scsi_dbg.h>
44
45 /*
46  * All wire protocol details (storage protocol between the guest and the host)
47  * are consolidated here.
48  *
49  * Begin protocol definitions.
50  */
51
52 /*
53  * Version history:
54  * V1 Beta: 0.1
55  * V1 RC < 2008/1/31: 1.0
56  * V1 RC > 2008/1/31:  2.0
57  * Win7: 4.2
58  * Win8: 5.1
59  * Win8.1: 6.0
60  * Win10: 6.2
61  */
62
63 #define VMSTOR_PROTO_VERSION(MAJOR_, MINOR_)    ((((MAJOR_) & 0xff) << 8) | \
64                                                 (((MINOR_) & 0xff)))
65
66 #define VMSTOR_PROTO_VERSION_WIN6       VMSTOR_PROTO_VERSION(2, 0)
67 #define VMSTOR_PROTO_VERSION_WIN7       VMSTOR_PROTO_VERSION(4, 2)
68 #define VMSTOR_PROTO_VERSION_WIN8       VMSTOR_PROTO_VERSION(5, 1)
69 #define VMSTOR_PROTO_VERSION_WIN8_1     VMSTOR_PROTO_VERSION(6, 0)
70 #define VMSTOR_PROTO_VERSION_WIN10      VMSTOR_PROTO_VERSION(6, 2)
71
72 /*  Packet structure describing virtual storage requests. */
73 enum vstor_packet_operation {
74         VSTOR_OPERATION_COMPLETE_IO             = 1,
75         VSTOR_OPERATION_REMOVE_DEVICE           = 2,
76         VSTOR_OPERATION_EXECUTE_SRB             = 3,
77         VSTOR_OPERATION_RESET_LUN               = 4,
78         VSTOR_OPERATION_RESET_ADAPTER           = 5,
79         VSTOR_OPERATION_RESET_BUS               = 6,
80         VSTOR_OPERATION_BEGIN_INITIALIZATION    = 7,
81         VSTOR_OPERATION_END_INITIALIZATION      = 8,
82         VSTOR_OPERATION_QUERY_PROTOCOL_VERSION  = 9,
83         VSTOR_OPERATION_QUERY_PROPERTIES        = 10,
84         VSTOR_OPERATION_ENUMERATE_BUS           = 11,
85         VSTOR_OPERATION_FCHBA_DATA              = 12,
86         VSTOR_OPERATION_CREATE_SUB_CHANNELS     = 13,
87         VSTOR_OPERATION_MAXIMUM                 = 13
88 };
89
90 /*
91  * WWN packet for Fibre Channel HBA
92  */
93
94 struct hv_fc_wwn_packet {
95         bool    primary_active;
96         u8      reserved1;
97         u8      reserved2;
98         u8      primary_port_wwn[8];
99         u8      primary_node_wwn[8];
100         u8      secondary_port_wwn[8];
101         u8      secondary_node_wwn[8];
102 };
103
104
105
106 /*
107  * SRB Flag Bits
108  */
109
110 #define SRB_FLAGS_QUEUE_ACTION_ENABLE           0x00000002
111 #define SRB_FLAGS_DISABLE_DISCONNECT            0x00000004
112 #define SRB_FLAGS_DISABLE_SYNCH_TRANSFER        0x00000008
113 #define SRB_FLAGS_BYPASS_FROZEN_QUEUE           0x00000010
114 #define SRB_FLAGS_DISABLE_AUTOSENSE             0x00000020
115 #define SRB_FLAGS_DATA_IN                       0x00000040
116 #define SRB_FLAGS_DATA_OUT                      0x00000080
117 #define SRB_FLAGS_NO_DATA_TRANSFER              0x00000000
118 #define SRB_FLAGS_UNSPECIFIED_DIRECTION (SRB_FLAGS_DATA_IN | SRB_FLAGS_DATA_OUT)
119 #define SRB_FLAGS_NO_QUEUE_FREEZE               0x00000100
120 #define SRB_FLAGS_ADAPTER_CACHE_ENABLE          0x00000200
121 #define SRB_FLAGS_FREE_SENSE_BUFFER             0x00000400
122
123 /*
124  * This flag indicates the request is part of the workflow for processing a D3.
125  */
126 #define SRB_FLAGS_D3_PROCESSING                 0x00000800
127 #define SRB_FLAGS_IS_ACTIVE                     0x00010000
128 #define SRB_FLAGS_ALLOCATED_FROM_ZONE           0x00020000
129 #define SRB_FLAGS_SGLIST_FROM_POOL              0x00040000
130 #define SRB_FLAGS_BYPASS_LOCKED_QUEUE           0x00080000
131 #define SRB_FLAGS_NO_KEEP_AWAKE                 0x00100000
132 #define SRB_FLAGS_PORT_DRIVER_ALLOCSENSE        0x00200000
133 #define SRB_FLAGS_PORT_DRIVER_SENSEHASPORT      0x00400000
134 #define SRB_FLAGS_DONT_START_NEXT_PACKET        0x00800000
135 #define SRB_FLAGS_PORT_DRIVER_RESERVED          0x0F000000
136 #define SRB_FLAGS_CLASS_DRIVER_RESERVED         0xF0000000
137
138 #define SP_UNTAGGED                     ((unsigned char) ~0)
139 #define SRB_SIMPLE_TAG_REQUEST          0x20
140
141 /*
142  * Platform neutral description of a scsi request -
143  * this remains the same across the write regardless of 32/64 bit
144  * note: it's patterned off the SCSI_PASS_THROUGH structure
145  */
146 #define STORVSC_MAX_CMD_LEN                     0x10
147
148 #define POST_WIN7_STORVSC_SENSE_BUFFER_SIZE     0x14
149 #define PRE_WIN8_STORVSC_SENSE_BUFFER_SIZE      0x12
150
151 #define STORVSC_SENSE_BUFFER_SIZE               0x14
152 #define STORVSC_MAX_BUF_LEN_WITH_PADDING        0x14
153
154 /*
155  * Sense buffer size changed in win8; have a run-time
156  * variable to track the size we should use.  This value will
157  * likely change during protocol negotiation but it is valid
158  * to start by assuming pre-Win8.
159  */
160 static int sense_buffer_size = PRE_WIN8_STORVSC_SENSE_BUFFER_SIZE;
161
162 /*
163  * The storage protocol version is determined during the
164  * initial exchange with the host.  It will indicate which
165  * storage functionality is available in the host.
166 */
167 static int vmstor_proto_version;
168
169 struct vmscsi_win8_extension {
170         /*
171          * The following were added in Windows 8
172          */
173         u16 reserve;
174         u8  queue_tag;
175         u8  queue_action;
176         u32 srb_flags;
177         u32 time_out_value;
178         u32 queue_sort_ey;
179 } __packed;
180
181 struct vmscsi_request {
182         u16 length;
183         u8 srb_status;
184         u8 scsi_status;
185
186         u8  port_number;
187         u8  path_id;
188         u8  target_id;
189         u8  lun;
190
191         u8  cdb_length;
192         u8  sense_info_length;
193         u8  data_in;
194         u8  reserved;
195
196         u32 data_transfer_length;
197
198         union {
199                 u8 cdb[STORVSC_MAX_CMD_LEN];
200                 u8 sense_data[STORVSC_SENSE_BUFFER_SIZE];
201                 u8 reserved_array[STORVSC_MAX_BUF_LEN_WITH_PADDING];
202         };
203         /*
204          * The following was added in win8.
205          */
206         struct vmscsi_win8_extension win8_extension;
207
208 } __attribute((packed));
209
210
211 /*
212  * The size of the vmscsi_request has changed in win8. The
213  * additional size is because of new elements added to the
214  * structure. These elements are valid only when we are talking
215  * to a win8 host.
216  * Track the correction to size we need to apply. This value
217  * will likely change during protocol negotiation but it is
218  * valid to start by assuming pre-Win8.
219  */
220 static int vmscsi_size_delta = sizeof(struct vmscsi_win8_extension);
221
222 /*
223  * The list of storage protocols in order of preference.
224  */
225 struct vmstor_protocol {
226         int protocol_version;
227         int sense_buffer_size;
228         int vmscsi_size_delta;
229 };
230
231
232 static const struct vmstor_protocol vmstor_protocols[] = {
233         {
234                 VMSTOR_PROTO_VERSION_WIN10,
235                 POST_WIN7_STORVSC_SENSE_BUFFER_SIZE,
236                 0
237         },
238         {
239                 VMSTOR_PROTO_VERSION_WIN8_1,
240                 POST_WIN7_STORVSC_SENSE_BUFFER_SIZE,
241                 0
242         },
243         {
244                 VMSTOR_PROTO_VERSION_WIN8,
245                 POST_WIN7_STORVSC_SENSE_BUFFER_SIZE,
246                 0
247         },
248         {
249                 VMSTOR_PROTO_VERSION_WIN7,
250                 PRE_WIN8_STORVSC_SENSE_BUFFER_SIZE,
251                 sizeof(struct vmscsi_win8_extension),
252         },
253         {
254                 VMSTOR_PROTO_VERSION_WIN6,
255                 PRE_WIN8_STORVSC_SENSE_BUFFER_SIZE,
256                 sizeof(struct vmscsi_win8_extension),
257         }
258 };
259
260
261 /*
262  * This structure is sent during the intialization phase to get the different
263  * properties of the channel.
264  */
265
266 #define STORAGE_CHANNEL_SUPPORTS_MULTI_CHANNEL          0x1
267
268 struct vmstorage_channel_properties {
269         u32 reserved;
270         u16 max_channel_cnt;
271         u16 reserved1;
272
273         u32 flags;
274         u32   max_transfer_bytes;
275
276         u64  reserved2;
277 } __packed;
278
279 /*  This structure is sent during the storage protocol negotiations. */
280 struct vmstorage_protocol_version {
281         /* Major (MSW) and minor (LSW) version numbers. */
282         u16 major_minor;
283
284         /*
285          * Revision number is auto-incremented whenever this file is changed
286          * (See FILL_VMSTOR_REVISION macro above).  Mismatch does not
287          * definitely indicate incompatibility--but it does indicate mismatched
288          * builds.
289          * This is only used on the windows side. Just set it to 0.
290          */
291         u16 revision;
292 } __packed;
293
294 /* Channel Property Flags */
295 #define STORAGE_CHANNEL_REMOVABLE_FLAG          0x1
296 #define STORAGE_CHANNEL_EMULATED_IDE_FLAG       0x2
297
298 struct vstor_packet {
299         /* Requested operation type */
300         enum vstor_packet_operation operation;
301
302         /*  Flags - see below for values */
303         u32 flags;
304
305         /* Status of the request returned from the server side. */
306         u32 status;
307
308         /* Data payload area */
309         union {
310                 /*
311                  * Structure used to forward SCSI commands from the
312                  * client to the server.
313                  */
314                 struct vmscsi_request vm_srb;
315
316                 /* Structure used to query channel properties. */
317                 struct vmstorage_channel_properties storage_channel_properties;
318
319                 /* Used during version negotiations. */
320                 struct vmstorage_protocol_version version;
321
322                 /* Fibre channel address packet */
323                 struct hv_fc_wwn_packet wwn_packet;
324
325                 /* Number of sub-channels to create */
326                 u16 sub_channel_count;
327
328                 /* This will be the maximum of the union members */
329                 u8  buffer[0x34];
330         };
331 } __packed;
332
333 /*
334  * Packet Flags:
335  *
336  * This flag indicates that the server should send back a completion for this
337  * packet.
338  */
339
340 #define REQUEST_COMPLETION_FLAG 0x1
341
342 /* Matches Windows-end */
343 enum storvsc_request_type {
344         WRITE_TYPE = 0,
345         READ_TYPE,
346         UNKNOWN_TYPE,
347 };
348
349 /*
350  * SRB status codes and masks; a subset of the codes used here.
351  */
352
353 #define SRB_STATUS_AUTOSENSE_VALID      0x80
354 #define SRB_STATUS_QUEUE_FROZEN         0x40
355 #define SRB_STATUS_INVALID_LUN  0x20
356 #define SRB_STATUS_SUCCESS      0x01
357 #define SRB_STATUS_ABORTED      0x02
358 #define SRB_STATUS_ERROR        0x04
359 #define SRB_STATUS_DATA_OVERRUN 0x12
360
361 #define SRB_STATUS(status) \
362         (status & ~(SRB_STATUS_AUTOSENSE_VALID | SRB_STATUS_QUEUE_FROZEN))
363 /*
364  * This is the end of Protocol specific defines.
365  */
366
367 static int storvsc_ringbuffer_size = (256 * PAGE_SIZE);
368 static u32 max_outstanding_req_per_channel;
369
370 static int storvsc_vcpus_per_sub_channel = 4;
371
372 module_param(storvsc_ringbuffer_size, int, S_IRUGO);
373 MODULE_PARM_DESC(storvsc_ringbuffer_size, "Ring buffer size (bytes)");
374
375 module_param(storvsc_vcpus_per_sub_channel, int, S_IRUGO);
376 MODULE_PARM_DESC(vcpus_per_sub_channel, "Ratio of VCPUs to subchannels");
377 /*
378  * Timeout in seconds for all devices managed by this driver.
379  */
380 static int storvsc_timeout = 180;
381
382 static int msft_blist_flags = BLIST_TRY_VPD_PAGES;
383
384
385 static void storvsc_on_channel_callback(void *context);
386
387 #define STORVSC_MAX_LUNS_PER_TARGET                     255
388 #define STORVSC_MAX_TARGETS                             2
389 #define STORVSC_MAX_CHANNELS                            8
390
391 #define STORVSC_FC_MAX_LUNS_PER_TARGET                  255
392 #define STORVSC_FC_MAX_TARGETS                          128
393 #define STORVSC_FC_MAX_CHANNELS                         8
394
395 #define STORVSC_IDE_MAX_LUNS_PER_TARGET                 64
396 #define STORVSC_IDE_MAX_TARGETS                         1
397 #define STORVSC_IDE_MAX_CHANNELS                        1
398
399 struct storvsc_cmd_request {
400         struct scsi_cmnd *cmd;
401
402         struct hv_device *device;
403
404         /* Synchronize the request/response if needed */
405         struct completion wait_event;
406
407         struct vmbus_channel_packet_multipage_buffer mpb;
408         struct vmbus_packet_mpb_array *payload;
409         u32 payload_sz;
410
411         struct vstor_packet vstor_packet;
412 };
413
414
415 /* A storvsc device is a device object that contains a vmbus channel */
416 struct storvsc_device {
417         struct hv_device *device;
418
419         bool     destroy;
420         bool     drain_notify;
421         bool     open_sub_channel;
422         atomic_t num_outstanding_req;
423         struct Scsi_Host *host;
424
425         wait_queue_head_t waiting_to_drain;
426
427         /*
428          * Each unique Port/Path/Target represents 1 channel ie scsi
429          * controller. In reality, the pathid, targetid is always 0
430          * and the port is set by us
431          */
432         unsigned int port_number;
433         unsigned char path_id;
434         unsigned char target_id;
435
436         /*
437          * Max I/O, the device can support.
438          */
439         u32   max_transfer_bytes;
440         /* Used for vsc/vsp channel reset process */
441         struct storvsc_cmd_request init_request;
442         struct storvsc_cmd_request reset_request;
443 };
444
445 struct hv_host_device {
446         struct hv_device *dev;
447         unsigned int port;
448         unsigned char path;
449         unsigned char target;
450 };
451
452 struct storvsc_scan_work {
453         struct work_struct work;
454         struct Scsi_Host *host;
455         uint lun;
456 };
457
458 static void storvsc_device_scan(struct work_struct *work)
459 {
460         struct storvsc_scan_work *wrk;
461         uint lun;
462         struct scsi_device *sdev;
463
464         wrk = container_of(work, struct storvsc_scan_work, work);
465         lun = wrk->lun;
466
467         sdev = scsi_device_lookup(wrk->host, 0, 0, lun);
468         if (!sdev)
469                 goto done;
470         scsi_rescan_device(&sdev->sdev_gendev);
471         scsi_device_put(sdev);
472
473 done:
474         kfree(wrk);
475 }
476
477 static void storvsc_host_scan(struct work_struct *work)
478 {
479         struct storvsc_scan_work *wrk;
480         struct Scsi_Host *host;
481         struct scsi_device *sdev;
482
483         wrk = container_of(work, struct storvsc_scan_work, work);
484         host = wrk->host;
485
486         /*
487          * Before scanning the host, first check to see if any of the
488          * currrently known devices have been hot removed. We issue a
489          * "unit ready" command against all currently known devices.
490          * This I/O will result in an error for devices that have been
491          * removed. As part of handling the I/O error, we remove the device.
492          *
493          * When a LUN is added or removed, the host sends us a signal to
494          * scan the host. Thus we are forced to discover the LUNs that
495          * may have been removed this way.
496          */
497         mutex_lock(&host->scan_mutex);
498         shost_for_each_device(sdev, host)
499                 scsi_test_unit_ready(sdev, 1, 1, NULL);
500         mutex_unlock(&host->scan_mutex);
501         /*
502          * Now scan the host to discover LUNs that may have been added.
503          */
504         scsi_scan_host(host);
505
506         kfree(wrk);
507 }
508
509 static void storvsc_remove_lun(struct work_struct *work)
510 {
511         struct storvsc_scan_work *wrk;
512         struct scsi_device *sdev;
513
514         wrk = container_of(work, struct storvsc_scan_work, work);
515         if (!scsi_host_get(wrk->host))
516                 goto done;
517
518         sdev = scsi_device_lookup(wrk->host, 0, 0, wrk->lun);
519
520         if (sdev) {
521                 scsi_remove_device(sdev);
522                 scsi_device_put(sdev);
523         }
524         scsi_host_put(wrk->host);
525
526 done:
527         kfree(wrk);
528 }
529
530
531 /*
532  * We can get incoming messages from the host that are not in response to
533  * messages that we have sent out. An example of this would be messages
534  * received by the guest to notify dynamic addition/removal of LUNs. To
535  * deal with potential race conditions where the driver may be in the
536  * midst of being unloaded when we might receive an unsolicited message
537  * from the host, we have implemented a mechanism to gurantee sequential
538  * consistency:
539  *
540  * 1) Once the device is marked as being destroyed, we will fail all
541  *    outgoing messages.
542  * 2) We permit incoming messages when the device is being destroyed,
543  *    only to properly account for messages already sent out.
544  */
545
546 static inline struct storvsc_device *get_out_stor_device(
547                                         struct hv_device *device)
548 {
549         struct storvsc_device *stor_device;
550
551         stor_device = hv_get_drvdata(device);
552
553         if (stor_device && stor_device->destroy)
554                 stor_device = NULL;
555
556         return stor_device;
557 }
558
559
560 static inline void storvsc_wait_to_drain(struct storvsc_device *dev)
561 {
562         dev->drain_notify = true;
563         wait_event(dev->waiting_to_drain,
564                    atomic_read(&dev->num_outstanding_req) == 0);
565         dev->drain_notify = false;
566 }
567
568 static inline struct storvsc_device *get_in_stor_device(
569                                         struct hv_device *device)
570 {
571         struct storvsc_device *stor_device;
572
573         stor_device = hv_get_drvdata(device);
574
575         if (!stor_device)
576                 goto get_in_err;
577
578         /*
579          * If the device is being destroyed; allow incoming
580          * traffic only to cleanup outstanding requests.
581          */
582
583         if (stor_device->destroy  &&
584                 (atomic_read(&stor_device->num_outstanding_req) == 0))
585                 stor_device = NULL;
586
587 get_in_err:
588         return stor_device;
589
590 }
591
592 static void handle_sc_creation(struct vmbus_channel *new_sc)
593 {
594         struct hv_device *device = new_sc->primary_channel->device_obj;
595         struct storvsc_device *stor_device;
596         struct vmstorage_channel_properties props;
597
598         stor_device = get_out_stor_device(device);
599         if (!stor_device)
600                 return;
601
602         if (stor_device->open_sub_channel == false)
603                 return;
604
605         memset(&props, 0, sizeof(struct vmstorage_channel_properties));
606
607         vmbus_open(new_sc,
608                    storvsc_ringbuffer_size,
609                    storvsc_ringbuffer_size,
610                    (void *)&props,
611                    sizeof(struct vmstorage_channel_properties),
612                    storvsc_on_channel_callback, new_sc);
613 }
614
615 static void  handle_multichannel_storage(struct hv_device *device, int max_chns)
616 {
617         struct storvsc_device *stor_device;
618         int num_cpus = num_online_cpus();
619         int num_sc;
620         struct storvsc_cmd_request *request;
621         struct vstor_packet *vstor_packet;
622         int ret, t;
623
624         num_sc = ((max_chns > num_cpus) ? num_cpus : max_chns);
625         stor_device = get_out_stor_device(device);
626         if (!stor_device)
627                 return;
628
629         request = &stor_device->init_request;
630         vstor_packet = &request->vstor_packet;
631
632         stor_device->open_sub_channel = true;
633         /*
634          * Establish a handler for dealing with subchannels.
635          */
636         vmbus_set_sc_create_callback(device->channel, handle_sc_creation);
637
638         /*
639          * Check to see if sub-channels have already been created. This
640          * can happen when this driver is re-loaded after unloading.
641          */
642
643         if (vmbus_are_subchannels_present(device->channel))
644                 return;
645
646         stor_device->open_sub_channel = false;
647         /*
648          * Request the host to create sub-channels.
649          */
650         memset(request, 0, sizeof(struct storvsc_cmd_request));
651         init_completion(&request->wait_event);
652         vstor_packet->operation = VSTOR_OPERATION_CREATE_SUB_CHANNELS;
653         vstor_packet->flags = REQUEST_COMPLETION_FLAG;
654         vstor_packet->sub_channel_count = num_sc;
655
656         ret = vmbus_sendpacket(device->channel, vstor_packet,
657                                (sizeof(struct vstor_packet) -
658                                vmscsi_size_delta),
659                                (unsigned long)request,
660                                VM_PKT_DATA_INBAND,
661                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
662
663         if (ret != 0)
664                 return;
665
666         t = wait_for_completion_timeout(&request->wait_event, 10*HZ);
667         if (t == 0)
668                 return;
669
670         if (vstor_packet->operation != VSTOR_OPERATION_COMPLETE_IO ||
671             vstor_packet->status != 0)
672                 return;
673
674         /*
675          * Now that we created the sub-channels, invoke the check; this
676          * may trigger the callback.
677          */
678         stor_device->open_sub_channel = true;
679         vmbus_are_subchannels_present(device->channel);
680 }
681
682 static int storvsc_channel_init(struct hv_device *device)
683 {
684         struct storvsc_device *stor_device;
685         struct storvsc_cmd_request *request;
686         struct vstor_packet *vstor_packet;
687         int ret, t, i;
688         int max_chns;
689         bool process_sub_channels = false;
690
691         stor_device = get_out_stor_device(device);
692         if (!stor_device)
693                 return -ENODEV;
694
695         request = &stor_device->init_request;
696         vstor_packet = &request->vstor_packet;
697
698         /*
699          * Now, initiate the vsc/vsp initialization protocol on the open
700          * channel
701          */
702         memset(request, 0, sizeof(struct storvsc_cmd_request));
703         init_completion(&request->wait_event);
704         vstor_packet->operation = VSTOR_OPERATION_BEGIN_INITIALIZATION;
705         vstor_packet->flags = REQUEST_COMPLETION_FLAG;
706
707         ret = vmbus_sendpacket(device->channel, vstor_packet,
708                                (sizeof(struct vstor_packet) -
709                                vmscsi_size_delta),
710                                (unsigned long)request,
711                                VM_PKT_DATA_INBAND,
712                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
713         if (ret != 0)
714                 goto cleanup;
715
716         t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
717         if (t == 0) {
718                 ret = -ETIMEDOUT;
719                 goto cleanup;
720         }
721
722         if (vstor_packet->operation != VSTOR_OPERATION_COMPLETE_IO ||
723             vstor_packet->status != 0) {
724                 ret = -EINVAL;
725                 goto cleanup;
726         }
727
728
729         for (i = 0; i < ARRAY_SIZE(vmstor_protocols); i++) {
730                 /* reuse the packet for version range supported */
731                 memset(vstor_packet, 0, sizeof(struct vstor_packet));
732                 vstor_packet->operation =
733                         VSTOR_OPERATION_QUERY_PROTOCOL_VERSION;
734                 vstor_packet->flags = REQUEST_COMPLETION_FLAG;
735
736                 vstor_packet->version.major_minor =
737                         vmstor_protocols[i].protocol_version;
738
739                 /*
740                  * The revision number is only used in Windows; set it to 0.
741                  */
742                 vstor_packet->version.revision = 0;
743
744                 ret = vmbus_sendpacket(device->channel, vstor_packet,
745                                (sizeof(struct vstor_packet) -
746                                 vmscsi_size_delta),
747                                (unsigned long)request,
748                                VM_PKT_DATA_INBAND,
749                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
750                 if (ret != 0)
751                         goto cleanup;
752
753                 t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
754                 if (t == 0) {
755                         ret = -ETIMEDOUT;
756                         goto cleanup;
757                 }
758
759                 if (vstor_packet->operation != VSTOR_OPERATION_COMPLETE_IO) {
760                         ret = -EINVAL;
761                         goto cleanup;
762                 }
763
764                 if (vstor_packet->status == 0) {
765                         vmstor_proto_version =
766                                 vmstor_protocols[i].protocol_version;
767
768                         sense_buffer_size =
769                                 vmstor_protocols[i].sense_buffer_size;
770
771                         vmscsi_size_delta =
772                                 vmstor_protocols[i].vmscsi_size_delta;
773
774                         break;
775                 }
776         }
777
778         if (vstor_packet->status != 0) {
779                 ret = -EINVAL;
780                 goto cleanup;
781         }
782
783
784         memset(vstor_packet, 0, sizeof(struct vstor_packet));
785         vstor_packet->operation = VSTOR_OPERATION_QUERY_PROPERTIES;
786         vstor_packet->flags = REQUEST_COMPLETION_FLAG;
787
788         ret = vmbus_sendpacket(device->channel, vstor_packet,
789                                (sizeof(struct vstor_packet) -
790                                 vmscsi_size_delta),
791                                (unsigned long)request,
792                                VM_PKT_DATA_INBAND,
793                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
794
795         if (ret != 0)
796                 goto cleanup;
797
798         t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
799         if (t == 0) {
800                 ret = -ETIMEDOUT;
801                 goto cleanup;
802         }
803
804         if (vstor_packet->operation != VSTOR_OPERATION_COMPLETE_IO ||
805             vstor_packet->status != 0) {
806                 ret = -EINVAL;
807                 goto cleanup;
808         }
809
810         /*
811          * Check to see if multi-channel support is there.
812          * Hosts that implement protocol version of 5.1 and above
813          * support multi-channel.
814          */
815         max_chns = vstor_packet->storage_channel_properties.max_channel_cnt;
816         if (vmstor_proto_version >= VMSTOR_PROTO_VERSION_WIN8) {
817                 if (vstor_packet->storage_channel_properties.flags &
818                     STORAGE_CHANNEL_SUPPORTS_MULTI_CHANNEL)
819                         process_sub_channels = true;
820         }
821         stor_device->max_transfer_bytes =
822                 vstor_packet->storage_channel_properties.max_transfer_bytes;
823
824         memset(vstor_packet, 0, sizeof(struct vstor_packet));
825         vstor_packet->operation = VSTOR_OPERATION_END_INITIALIZATION;
826         vstor_packet->flags = REQUEST_COMPLETION_FLAG;
827
828         ret = vmbus_sendpacket(device->channel, vstor_packet,
829                                (sizeof(struct vstor_packet) -
830                                 vmscsi_size_delta),
831                                (unsigned long)request,
832                                VM_PKT_DATA_INBAND,
833                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
834
835         if (ret != 0)
836                 goto cleanup;
837
838         t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
839         if (t == 0) {
840                 ret = -ETIMEDOUT;
841                 goto cleanup;
842         }
843
844         if (vstor_packet->operation != VSTOR_OPERATION_COMPLETE_IO ||
845             vstor_packet->status != 0) {
846                 ret = -EINVAL;
847                 goto cleanup;
848         }
849
850         if (process_sub_channels)
851                 handle_multichannel_storage(device, max_chns);
852
853
854 cleanup:
855         return ret;
856 }
857
858 static void storvsc_handle_error(struct vmscsi_request *vm_srb,
859                                 struct scsi_cmnd *scmnd,
860                                 struct Scsi_Host *host,
861                                 u8 asc, u8 ascq)
862 {
863         struct storvsc_scan_work *wrk;
864         void (*process_err_fn)(struct work_struct *work);
865         bool do_work = false;
866
867         switch (SRB_STATUS(vm_srb->srb_status)) {
868         case SRB_STATUS_ERROR:
869                 /*
870                  * Let upper layer deal with error when
871                  * sense message is present.
872                  */
873
874                 if (vm_srb->srb_status & SRB_STATUS_AUTOSENSE_VALID)
875                         break;
876                 /*
877                  * If there is an error; offline the device since all
878                  * error recovery strategies would have already been
879                  * deployed on the host side. However, if the command
880                  * were a pass-through command deal with it appropriately.
881                  */
882                 switch (scmnd->cmnd[0]) {
883                 case ATA_16:
884                 case ATA_12:
885                         set_host_byte(scmnd, DID_PASSTHROUGH);
886                         break;
887                 /*
888                  * On Some Windows hosts TEST_UNIT_READY command can return
889                  * SRB_STATUS_ERROR, let the upper level code deal with it
890                  * based on the sense information.
891                  */
892                 case TEST_UNIT_READY:
893                         break;
894                 default:
895                         set_host_byte(scmnd, DID_TARGET_FAILURE);
896                 }
897                 break;
898         case SRB_STATUS_INVALID_LUN:
899                 do_work = true;
900                 process_err_fn = storvsc_remove_lun;
901                 break;
902         case SRB_STATUS_ABORTED:
903                 if (vm_srb->srb_status & SRB_STATUS_AUTOSENSE_VALID &&
904                     (asc == 0x2a) && (ascq == 0x9)) {
905                         do_work = true;
906                         process_err_fn = storvsc_device_scan;
907                         /*
908                          * Retry the I/O that trigerred this.
909                          */
910                         set_host_byte(scmnd, DID_REQUEUE);
911                 }
912                 break;
913         }
914
915         if (!do_work)
916                 return;
917
918         /*
919          * We need to schedule work to process this error; schedule it.
920          */
921         wrk = kmalloc(sizeof(struct storvsc_scan_work), GFP_ATOMIC);
922         if (!wrk) {
923                 set_host_byte(scmnd, DID_TARGET_FAILURE);
924                 return;
925         }
926
927         wrk->host = host;
928         wrk->lun = vm_srb->lun;
929         INIT_WORK(&wrk->work, process_err_fn);
930         schedule_work(&wrk->work);
931 }
932
933
934 static void storvsc_command_completion(struct storvsc_cmd_request *cmd_request)
935 {
936         struct scsi_cmnd *scmnd = cmd_request->cmd;
937         struct hv_host_device *host_dev = shost_priv(scmnd->device->host);
938         struct scsi_sense_hdr sense_hdr;
939         struct vmscsi_request *vm_srb;
940         u32 data_transfer_length;
941         struct Scsi_Host *host;
942         struct storvsc_device *stor_dev;
943         struct hv_device *dev = host_dev->dev;
944         u32 payload_sz = cmd_request->payload_sz;
945         void *payload = cmd_request->payload;
946
947         stor_dev = get_in_stor_device(dev);
948         host = stor_dev->host;
949
950         vm_srb = &cmd_request->vstor_packet.vm_srb;
951         data_transfer_length = vm_srb->data_transfer_length;
952
953         scmnd->result = vm_srb->scsi_status;
954
955         if (scmnd->result) {
956                 if (scsi_normalize_sense(scmnd->sense_buffer,
957                                 SCSI_SENSE_BUFFERSIZE, &sense_hdr))
958                         scsi_print_sense_hdr(scmnd->device, "storvsc",
959                                              &sense_hdr);
960         }
961
962         if (vm_srb->srb_status != SRB_STATUS_SUCCESS) {
963                 storvsc_handle_error(vm_srb, scmnd, host, sense_hdr.asc,
964                                          sense_hdr.ascq);
965                 /*
966                  * The Windows driver set data_transfer_length on
967                  * SRB_STATUS_DATA_OVERRUN. On other errors, this value
968                  * is untouched.  In these cases we set it to 0.
969                  */
970                 if (vm_srb->srb_status != SRB_STATUS_DATA_OVERRUN)
971                         data_transfer_length = 0;
972         }
973
974         scsi_set_resid(scmnd,
975                 cmd_request->payload->range.len - data_transfer_length);
976
977         scmnd->scsi_done(scmnd);
978
979         if (payload_sz >
980                 sizeof(struct vmbus_channel_packet_multipage_buffer))
981                 kfree(payload);
982 }
983
984 static void storvsc_on_io_completion(struct hv_device *device,
985                                   struct vstor_packet *vstor_packet,
986                                   struct storvsc_cmd_request *request)
987 {
988         struct storvsc_device *stor_device;
989         struct vstor_packet *stor_pkt;
990
991         stor_device = hv_get_drvdata(device);
992         stor_pkt = &request->vstor_packet;
993
994         /*
995          * The current SCSI handling on the host side does
996          * not correctly handle:
997          * INQUIRY command with page code parameter set to 0x80
998          * MODE_SENSE command with cmd[2] == 0x1c
999          *
1000          * Setup srb and scsi status so this won't be fatal.
1001          * We do this so we can distinguish truly fatal failues
1002          * (srb status == 0x4) and off-line the device in that case.
1003          */
1004
1005         if ((stor_pkt->vm_srb.cdb[0] == INQUIRY) ||
1006            (stor_pkt->vm_srb.cdb[0] == MODE_SENSE)) {
1007                 vstor_packet->vm_srb.scsi_status = 0;
1008                 vstor_packet->vm_srb.srb_status = SRB_STATUS_SUCCESS;
1009         }
1010
1011
1012         /* Copy over the status...etc */
1013         stor_pkt->vm_srb.scsi_status = vstor_packet->vm_srb.scsi_status;
1014         stor_pkt->vm_srb.srb_status = vstor_packet->vm_srb.srb_status;
1015         stor_pkt->vm_srb.sense_info_length =
1016         vstor_packet->vm_srb.sense_info_length;
1017
1018
1019         if ((vstor_packet->vm_srb.scsi_status & 0xFF) == 0x02) {
1020                 /* CHECK_CONDITION */
1021                 if (vstor_packet->vm_srb.srb_status &
1022                         SRB_STATUS_AUTOSENSE_VALID) {
1023                         /* autosense data available */
1024
1025                         memcpy(request->cmd->sense_buffer,
1026                                vstor_packet->vm_srb.sense_data,
1027                                vstor_packet->vm_srb.sense_info_length);
1028
1029                 }
1030         }
1031
1032         stor_pkt->vm_srb.data_transfer_length =
1033         vstor_packet->vm_srb.data_transfer_length;
1034
1035         storvsc_command_completion(request);
1036
1037         if (atomic_dec_and_test(&stor_device->num_outstanding_req) &&
1038                 stor_device->drain_notify)
1039                 wake_up(&stor_device->waiting_to_drain);
1040
1041
1042 }
1043
1044 static void storvsc_on_receive(struct hv_device *device,
1045                              struct vstor_packet *vstor_packet,
1046                              struct storvsc_cmd_request *request)
1047 {
1048         struct storvsc_scan_work *work;
1049         struct storvsc_device *stor_device;
1050
1051         switch (vstor_packet->operation) {
1052         case VSTOR_OPERATION_COMPLETE_IO:
1053                 storvsc_on_io_completion(device, vstor_packet, request);
1054                 break;
1055
1056         case VSTOR_OPERATION_REMOVE_DEVICE:
1057         case VSTOR_OPERATION_ENUMERATE_BUS:
1058                 stor_device = get_in_stor_device(device);
1059                 work = kmalloc(sizeof(struct storvsc_scan_work), GFP_ATOMIC);
1060                 if (!work)
1061                         return;
1062
1063                 INIT_WORK(&work->work, storvsc_host_scan);
1064                 work->host = stor_device->host;
1065                 schedule_work(&work->work);
1066                 break;
1067
1068         default:
1069                 break;
1070         }
1071 }
1072
1073 static void storvsc_on_channel_callback(void *context)
1074 {
1075         struct vmbus_channel *channel = (struct vmbus_channel *)context;
1076         struct hv_device *device;
1077         struct storvsc_device *stor_device;
1078         u32 bytes_recvd;
1079         u64 request_id;
1080         unsigned char packet[ALIGN(sizeof(struct vstor_packet), 8)];
1081         struct storvsc_cmd_request *request;
1082         int ret;
1083
1084         if (channel->primary_channel != NULL)
1085                 device = channel->primary_channel->device_obj;
1086         else
1087                 device = channel->device_obj;
1088
1089         stor_device = get_in_stor_device(device);
1090         if (!stor_device)
1091                 return;
1092
1093         do {
1094                 ret = vmbus_recvpacket(channel, packet,
1095                                        ALIGN((sizeof(struct vstor_packet) -
1096                                              vmscsi_size_delta), 8),
1097                                        &bytes_recvd, &request_id);
1098                 if (ret == 0 && bytes_recvd > 0) {
1099
1100                         request = (struct storvsc_cmd_request *)
1101                                         (unsigned long)request_id;
1102
1103                         if ((request == &stor_device->init_request) ||
1104                             (request == &stor_device->reset_request)) {
1105
1106                                 memcpy(&request->vstor_packet, packet,
1107                                        (sizeof(struct vstor_packet) -
1108                                         vmscsi_size_delta));
1109                                 complete(&request->wait_event);
1110                         } else {
1111                                 storvsc_on_receive(device,
1112                                                 (struct vstor_packet *)packet,
1113                                                 request);
1114                         }
1115                 } else {
1116                         break;
1117                 }
1118         } while (1);
1119
1120         return;
1121 }
1122
1123 static int storvsc_connect_to_vsp(struct hv_device *device, u32 ring_size)
1124 {
1125         struct vmstorage_channel_properties props;
1126         int ret;
1127
1128         memset(&props, 0, sizeof(struct vmstorage_channel_properties));
1129
1130         ret = vmbus_open(device->channel,
1131                          ring_size,
1132                          ring_size,
1133                          (void *)&props,
1134                          sizeof(struct vmstorage_channel_properties),
1135                          storvsc_on_channel_callback, device->channel);
1136
1137         if (ret != 0)
1138                 return ret;
1139
1140         ret = storvsc_channel_init(device);
1141
1142         return ret;
1143 }
1144
1145 static int storvsc_dev_remove(struct hv_device *device)
1146 {
1147         struct storvsc_device *stor_device;
1148         unsigned long flags;
1149
1150         stor_device = hv_get_drvdata(device);
1151
1152         spin_lock_irqsave(&device->channel->inbound_lock, flags);
1153         stor_device->destroy = true;
1154         spin_unlock_irqrestore(&device->channel->inbound_lock, flags);
1155
1156         /*
1157          * At this point, all outbound traffic should be disable. We
1158          * only allow inbound traffic (responses) to proceed so that
1159          * outstanding requests can be completed.
1160          */
1161
1162         storvsc_wait_to_drain(stor_device);
1163
1164         /*
1165          * Since we have already drained, we don't need to busy wait
1166          * as was done in final_release_stor_device()
1167          * Note that we cannot set the ext pointer to NULL until
1168          * we have drained - to drain the outgoing packets, we need to
1169          * allow incoming packets.
1170          */
1171         spin_lock_irqsave(&device->channel->inbound_lock, flags);
1172         hv_set_drvdata(device, NULL);
1173         spin_unlock_irqrestore(&device->channel->inbound_lock, flags);
1174
1175         /* Close the channel */
1176         vmbus_close(device->channel);
1177
1178         kfree(stor_device);
1179         return 0;
1180 }
1181
1182 static int storvsc_do_io(struct hv_device *device,
1183                          struct storvsc_cmd_request *request)
1184 {
1185         struct storvsc_device *stor_device;
1186         struct vstor_packet *vstor_packet;
1187         struct vmbus_channel *outgoing_channel;
1188         int ret = 0;
1189
1190         vstor_packet = &request->vstor_packet;
1191         stor_device = get_out_stor_device(device);
1192
1193         if (!stor_device)
1194                 return -ENODEV;
1195
1196
1197         request->device  = device;
1198         /*
1199          * Select an an appropriate channel to send the request out.
1200          */
1201
1202         outgoing_channel = vmbus_get_outgoing_channel(device->channel);
1203
1204
1205         vstor_packet->flags |= REQUEST_COMPLETION_FLAG;
1206
1207         vstor_packet->vm_srb.length = (sizeof(struct vmscsi_request) -
1208                                         vmscsi_size_delta);
1209
1210
1211         vstor_packet->vm_srb.sense_info_length = sense_buffer_size;
1212
1213
1214         vstor_packet->vm_srb.data_transfer_length =
1215         request->payload->range.len;
1216
1217         vstor_packet->operation = VSTOR_OPERATION_EXECUTE_SRB;
1218
1219         if (request->payload->range.len) {
1220
1221                 ret = vmbus_sendpacket_mpb_desc(outgoing_channel,
1222                                 request->payload, request->payload_sz,
1223                                 vstor_packet,
1224                                 (sizeof(struct vstor_packet) -
1225                                 vmscsi_size_delta),
1226                                 (unsigned long)request);
1227         } else {
1228                 ret = vmbus_sendpacket(outgoing_channel, vstor_packet,
1229                                (sizeof(struct vstor_packet) -
1230                                 vmscsi_size_delta),
1231                                (unsigned long)request,
1232                                VM_PKT_DATA_INBAND,
1233                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1234         }
1235
1236         if (ret != 0)
1237                 return ret;
1238
1239         atomic_inc(&stor_device->num_outstanding_req);
1240
1241         return ret;
1242 }
1243
1244 static int storvsc_device_configure(struct scsi_device *sdevice)
1245 {
1246
1247         blk_queue_max_segment_size(sdevice->request_queue, PAGE_SIZE);
1248
1249         blk_queue_bounce_limit(sdevice->request_queue, BLK_BOUNCE_ANY);
1250
1251         blk_queue_rq_timeout(sdevice->request_queue, (storvsc_timeout * HZ));
1252
1253         /* Ensure there are no gaps in presented sgls */
1254         blk_queue_virt_boundary(sdevice->request_queue, PAGE_SIZE - 1);
1255
1256         sdevice->no_write_same = 1;
1257
1258         /*
1259          * Add blist flags to permit the reading of the VPD pages even when
1260          * the target may claim SPC-2 compliance. MSFT targets currently
1261          * claim SPC-2 compliance while they implement post SPC-2 features.
1262          * With this patch we can correctly handle WRITE_SAME_16 issues.
1263          */
1264         sdevice->sdev_bflags |= msft_blist_flags;
1265
1266         /*
1267          * If the host is WIN8 or WIN8 R2, claim conformance to SPC-3
1268          * if the device is a MSFT virtual device.  If the host is
1269          * WIN10 or newer, allow write_same.
1270          */
1271         if (!strncmp(sdevice->vendor, "Msft", 4)) {
1272                 switch (vmstor_proto_version) {
1273                 case VMSTOR_PROTO_VERSION_WIN8:
1274                 case VMSTOR_PROTO_VERSION_WIN8_1:
1275                         sdevice->scsi_level = SCSI_SPC_3;
1276                         break;
1277                 }
1278
1279                 if (vmstor_proto_version >= VMSTOR_PROTO_VERSION_WIN10)
1280                         sdevice->no_write_same = 0;
1281         }
1282
1283         return 0;
1284 }
1285
1286 static int storvsc_get_chs(struct scsi_device *sdev, struct block_device * bdev,
1287                            sector_t capacity, int *info)
1288 {
1289         sector_t nsect = capacity;
1290         sector_t cylinders = nsect;
1291         int heads, sectors_pt;
1292
1293         /*
1294          * We are making up these values; let us keep it simple.
1295          */
1296         heads = 0xff;
1297         sectors_pt = 0x3f;      /* Sectors per track */
1298         sector_div(cylinders, heads * sectors_pt);
1299         if ((sector_t)(cylinders + 1) * heads * sectors_pt < nsect)
1300                 cylinders = 0xffff;
1301
1302         info[0] = heads;
1303         info[1] = sectors_pt;
1304         info[2] = (int)cylinders;
1305
1306         return 0;
1307 }
1308
1309 static int storvsc_host_reset_handler(struct scsi_cmnd *scmnd)
1310 {
1311         struct hv_host_device *host_dev = shost_priv(scmnd->device->host);
1312         struct hv_device *device = host_dev->dev;
1313
1314         struct storvsc_device *stor_device;
1315         struct storvsc_cmd_request *request;
1316         struct vstor_packet *vstor_packet;
1317         int ret, t;
1318
1319
1320         stor_device = get_out_stor_device(device);
1321         if (!stor_device)
1322                 return FAILED;
1323
1324         request = &stor_device->reset_request;
1325         vstor_packet = &request->vstor_packet;
1326
1327         init_completion(&request->wait_event);
1328
1329         vstor_packet->operation = VSTOR_OPERATION_RESET_BUS;
1330         vstor_packet->flags = REQUEST_COMPLETION_FLAG;
1331         vstor_packet->vm_srb.path_id = stor_device->path_id;
1332
1333         ret = vmbus_sendpacket(device->channel, vstor_packet,
1334                                (sizeof(struct vstor_packet) -
1335                                 vmscsi_size_delta),
1336                                (unsigned long)&stor_device->reset_request,
1337                                VM_PKT_DATA_INBAND,
1338                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1339         if (ret != 0)
1340                 return FAILED;
1341
1342         t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
1343         if (t == 0)
1344                 return TIMEOUT_ERROR;
1345
1346
1347         /*
1348          * At this point, all outstanding requests in the adapter
1349          * should have been flushed out and return to us
1350          * There is a potential race here where the host may be in
1351          * the process of responding when we return from here.
1352          * Just wait for all in-transit packets to be accounted for
1353          * before we return from here.
1354          */
1355         storvsc_wait_to_drain(stor_device);
1356
1357         return SUCCESS;
1358 }
1359
1360 /*
1361  * The host guarantees to respond to each command, although I/O latencies might
1362  * be unbounded on Azure.  Reset the timer unconditionally to give the host a
1363  * chance to perform EH.
1364  */
1365 static enum blk_eh_timer_return storvsc_eh_timed_out(struct scsi_cmnd *scmnd)
1366 {
1367         return BLK_EH_RESET_TIMER;
1368 }
1369
1370 static bool storvsc_scsi_cmd_ok(struct scsi_cmnd *scmnd)
1371 {
1372         bool allowed = true;
1373         u8 scsi_op = scmnd->cmnd[0];
1374
1375         switch (scsi_op) {
1376         /* the host does not handle WRITE_SAME, log accident usage */
1377         case WRITE_SAME:
1378         /*
1379          * smartd sends this command and the host does not handle
1380          * this. So, don't send it.
1381          */
1382         case SET_WINDOW:
1383                 scmnd->result = ILLEGAL_REQUEST << 16;
1384                 allowed = false;
1385                 break;
1386         default:
1387                 break;
1388         }
1389         return allowed;
1390 }
1391
1392 static int storvsc_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *scmnd)
1393 {
1394         int ret;
1395         struct hv_host_device *host_dev = shost_priv(host);
1396         struct hv_device *dev = host_dev->dev;
1397         struct storvsc_cmd_request *cmd_request = scsi_cmd_priv(scmnd);
1398         int i;
1399         struct scatterlist *sgl;
1400         unsigned int sg_count = 0;
1401         struct vmscsi_request *vm_srb;
1402         struct scatterlist *cur_sgl;
1403         struct vmbus_packet_mpb_array  *payload;
1404         u32 payload_sz;
1405         u32 length;
1406
1407         if (vmstor_proto_version <= VMSTOR_PROTO_VERSION_WIN8) {
1408                 /*
1409                  * On legacy hosts filter unimplemented commands.
1410                  * Future hosts are expected to correctly handle
1411                  * unsupported commands. Furthermore, it is
1412                  * possible that some of the currently
1413                  * unsupported commands maybe supported in
1414                  * future versions of the host.
1415                  */
1416                 if (!storvsc_scsi_cmd_ok(scmnd)) {
1417                         scmnd->scsi_done(scmnd);
1418                         return 0;
1419                 }
1420         }
1421
1422         /* Setup the cmd request */
1423         cmd_request->cmd = scmnd;
1424
1425         vm_srb = &cmd_request->vstor_packet.vm_srb;
1426         vm_srb->win8_extension.time_out_value = 60;
1427
1428         vm_srb->win8_extension.srb_flags |=
1429                 SRB_FLAGS_DISABLE_SYNCH_TRANSFER;
1430
1431         if (scmnd->device->tagged_supported) {
1432                 vm_srb->win8_extension.srb_flags |=
1433                 (SRB_FLAGS_QUEUE_ACTION_ENABLE | SRB_FLAGS_NO_QUEUE_FREEZE);
1434                 vm_srb->win8_extension.queue_tag = SP_UNTAGGED;
1435                 vm_srb->win8_extension.queue_action = SRB_SIMPLE_TAG_REQUEST;
1436         }
1437
1438         /* Build the SRB */
1439         switch (scmnd->sc_data_direction) {
1440         case DMA_TO_DEVICE:
1441                 vm_srb->data_in = WRITE_TYPE;
1442                 vm_srb->win8_extension.srb_flags |= SRB_FLAGS_DATA_OUT;
1443                 break;
1444         case DMA_FROM_DEVICE:
1445                 vm_srb->data_in = READ_TYPE;
1446                 vm_srb->win8_extension.srb_flags |= SRB_FLAGS_DATA_IN;
1447                 break;
1448         case DMA_NONE:
1449                 vm_srb->data_in = UNKNOWN_TYPE;
1450                 vm_srb->win8_extension.srb_flags |= SRB_FLAGS_NO_DATA_TRANSFER;
1451                 break;
1452         default:
1453                 /*
1454                  * This is DMA_BIDIRECTIONAL or something else we are never
1455                  * supposed to see here.
1456                  */
1457                 WARN(1, "Unexpected data direction: %d\n",
1458                      scmnd->sc_data_direction);
1459                 return -EINVAL;
1460         }
1461
1462
1463         vm_srb->port_number = host_dev->port;
1464         vm_srb->path_id = scmnd->device->channel;
1465         vm_srb->target_id = scmnd->device->id;
1466         vm_srb->lun = scmnd->device->lun;
1467
1468         vm_srb->cdb_length = scmnd->cmd_len;
1469
1470         memcpy(vm_srb->cdb, scmnd->cmnd, vm_srb->cdb_length);
1471
1472         sgl = (struct scatterlist *)scsi_sglist(scmnd);
1473         sg_count = scsi_sg_count(scmnd);
1474
1475         length = scsi_bufflen(scmnd);
1476         payload = (struct vmbus_packet_mpb_array *)&cmd_request->mpb;
1477         payload_sz = sizeof(cmd_request->mpb);
1478
1479         if (sg_count) {
1480                 if (sg_count > MAX_PAGE_BUFFER_COUNT) {
1481
1482                         payload_sz = (sg_count * sizeof(void *) +
1483                                       sizeof(struct vmbus_packet_mpb_array));
1484                         payload = kmalloc(payload_sz, GFP_ATOMIC);
1485                         if (!payload)
1486                                 return SCSI_MLQUEUE_DEVICE_BUSY;
1487                 }
1488
1489                 payload->range.len = length;
1490                 payload->range.offset = sgl[0].offset;
1491
1492                 cur_sgl = sgl;
1493                 for (i = 0; i < sg_count; i++) {
1494                         payload->range.pfn_array[i] =
1495                                 page_to_pfn(sg_page((cur_sgl)));
1496                         cur_sgl = sg_next(cur_sgl);
1497                 }
1498
1499         } else if (scsi_sglist(scmnd)) {
1500                 payload->range.len = length;
1501                 payload->range.offset =
1502                         virt_to_phys(scsi_sglist(scmnd)) & (PAGE_SIZE-1);
1503                 payload->range.pfn_array[0] =
1504                         virt_to_phys(scsi_sglist(scmnd)) >> PAGE_SHIFT;
1505         }
1506
1507         cmd_request->payload = payload;
1508         cmd_request->payload_sz = payload_sz;
1509
1510         /* Invokes the vsc to start an IO */
1511         ret = storvsc_do_io(dev, cmd_request);
1512
1513         if (ret == -EAGAIN) {
1514                 /* no more space */
1515                 return SCSI_MLQUEUE_DEVICE_BUSY;
1516         }
1517
1518         return 0;
1519 }
1520
1521 static struct scsi_host_template scsi_driver = {
1522         .module =               THIS_MODULE,
1523         .name =                 "storvsc_host_t",
1524         .cmd_size =             sizeof(struct storvsc_cmd_request),
1525         .bios_param =           storvsc_get_chs,
1526         .queuecommand =         storvsc_queuecommand,
1527         .eh_host_reset_handler =        storvsc_host_reset_handler,
1528         .proc_name =            "storvsc_host",
1529         .eh_timed_out =         storvsc_eh_timed_out,
1530         .slave_configure =      storvsc_device_configure,
1531         .cmd_per_lun =          255,
1532         .this_id =              -1,
1533         .use_clustering =       ENABLE_CLUSTERING,
1534         /* Make sure we dont get a sg segment crosses a page boundary */
1535         .dma_boundary =         PAGE_SIZE-1,
1536         .no_write_same =        1,
1537 };
1538
1539 enum {
1540         SCSI_GUID,
1541         IDE_GUID,
1542         SFC_GUID,
1543 };
1544
1545 static const struct hv_vmbus_device_id id_table[] = {
1546         /* SCSI guid */
1547         { HV_SCSI_GUID,
1548           .driver_data = SCSI_GUID
1549         },
1550         /* IDE guid */
1551         { HV_IDE_GUID,
1552           .driver_data = IDE_GUID
1553         },
1554         /* Fibre Channel GUID */
1555         {
1556           HV_SYNTHFC_GUID,
1557           .driver_data = SFC_GUID
1558         },
1559         { },
1560 };
1561
1562 MODULE_DEVICE_TABLE(vmbus, id_table);
1563
1564 static int storvsc_probe(struct hv_device *device,
1565                         const struct hv_vmbus_device_id *dev_id)
1566 {
1567         int ret;
1568         int num_cpus = num_online_cpus();
1569         struct Scsi_Host *host;
1570         struct hv_host_device *host_dev;
1571         bool dev_is_ide = ((dev_id->driver_data == IDE_GUID) ? true : false);
1572         int target = 0;
1573         struct storvsc_device *stor_device;
1574         int max_luns_per_target;
1575         int max_targets;
1576         int max_channels;
1577         int max_sub_channels = 0;
1578
1579         /*
1580          * Based on the windows host we are running on,
1581          * set state to properly communicate with the host.
1582          */
1583
1584         if (vmbus_proto_version < VERSION_WIN8) {
1585                 max_luns_per_target = STORVSC_IDE_MAX_LUNS_PER_TARGET;
1586                 max_targets = STORVSC_IDE_MAX_TARGETS;
1587                 max_channels = STORVSC_IDE_MAX_CHANNELS;
1588         } else {
1589                 max_luns_per_target = STORVSC_MAX_LUNS_PER_TARGET;
1590                 max_targets = STORVSC_MAX_TARGETS;
1591                 max_channels = STORVSC_MAX_CHANNELS;
1592                 /*
1593                  * On Windows8 and above, we support sub-channels for storage.
1594                  * The number of sub-channels offerred is based on the number of
1595                  * VCPUs in the guest.
1596                  */
1597                 max_sub_channels = (num_cpus / storvsc_vcpus_per_sub_channel);
1598         }
1599
1600         scsi_driver.can_queue = (max_outstanding_req_per_channel *
1601                                  (max_sub_channels + 1));
1602
1603         host = scsi_host_alloc(&scsi_driver,
1604                                sizeof(struct hv_host_device));
1605         if (!host)
1606                 return -ENOMEM;
1607
1608         host_dev = shost_priv(host);
1609         memset(host_dev, 0, sizeof(struct hv_host_device));
1610
1611         host_dev->port = host->host_no;
1612         host_dev->dev = device;
1613
1614
1615         stor_device = kzalloc(sizeof(struct storvsc_device), GFP_KERNEL);
1616         if (!stor_device) {
1617                 ret = -ENOMEM;
1618                 goto err_out0;
1619         }
1620
1621         stor_device->destroy = false;
1622         stor_device->open_sub_channel = false;
1623         init_waitqueue_head(&stor_device->waiting_to_drain);
1624         stor_device->device = device;
1625         stor_device->host = host;
1626         hv_set_drvdata(device, stor_device);
1627
1628         stor_device->port_number = host->host_no;
1629         ret = storvsc_connect_to_vsp(device, storvsc_ringbuffer_size);
1630         if (ret)
1631                 goto err_out1;
1632
1633         host_dev->path = stor_device->path_id;
1634         host_dev->target = stor_device->target_id;
1635
1636         switch (dev_id->driver_data) {
1637         case SFC_GUID:
1638                 host->max_lun = STORVSC_FC_MAX_LUNS_PER_TARGET;
1639                 host->max_id = STORVSC_FC_MAX_TARGETS;
1640                 host->max_channel = STORVSC_FC_MAX_CHANNELS - 1;
1641                 break;
1642
1643         case SCSI_GUID:
1644                 host->max_lun = max_luns_per_target;
1645                 host->max_id = max_targets;
1646                 host->max_channel = max_channels - 1;
1647                 break;
1648
1649         default:
1650                 host->max_lun = STORVSC_IDE_MAX_LUNS_PER_TARGET;
1651                 host->max_id = STORVSC_IDE_MAX_TARGETS;
1652                 host->max_channel = STORVSC_IDE_MAX_CHANNELS - 1;
1653                 break;
1654         }
1655         /* max cmd length */
1656         host->max_cmd_len = STORVSC_MAX_CMD_LEN;
1657
1658         /*
1659          * set the table size based on the info we got
1660          * from the host.
1661          */
1662         host->sg_tablesize = (stor_device->max_transfer_bytes >> PAGE_SHIFT);
1663
1664         /* Register the HBA and start the scsi bus scan */
1665         ret = scsi_add_host(host, &device->device);
1666         if (ret != 0)
1667                 goto err_out2;
1668
1669         if (!dev_is_ide) {
1670                 scsi_scan_host(host);
1671         } else {
1672                 target = (device->dev_instance.b[5] << 8 |
1673                          device->dev_instance.b[4]);
1674                 ret = scsi_add_device(host, 0, target, 0);
1675                 if (ret) {
1676                         scsi_remove_host(host);
1677                         goto err_out2;
1678                 }
1679         }
1680         return 0;
1681
1682 err_out2:
1683         /*
1684          * Once we have connected with the host, we would need to
1685          * to invoke storvsc_dev_remove() to rollback this state and
1686          * this call also frees up the stor_device; hence the jump around
1687          * err_out1 label.
1688          */
1689         storvsc_dev_remove(device);
1690         goto err_out0;
1691
1692 err_out1:
1693         kfree(stor_device);
1694
1695 err_out0:
1696         scsi_host_put(host);
1697         return ret;
1698 }
1699
1700 static int storvsc_remove(struct hv_device *dev)
1701 {
1702         struct storvsc_device *stor_device = hv_get_drvdata(dev);
1703         struct Scsi_Host *host = stor_device->host;
1704
1705         scsi_remove_host(host);
1706         storvsc_dev_remove(dev);
1707         scsi_host_put(host);
1708
1709         return 0;
1710 }
1711
1712 static struct hv_driver storvsc_drv = {
1713         .name = KBUILD_MODNAME,
1714         .id_table = id_table,
1715         .probe = storvsc_probe,
1716         .remove = storvsc_remove,
1717 };
1718
1719 static int __init storvsc_drv_init(void)
1720 {
1721
1722         /*
1723          * Divide the ring buffer data size (which is 1 page less
1724          * than the ring buffer size since that page is reserved for
1725          * the ring buffer indices) by the max request size (which is
1726          * vmbus_channel_packet_multipage_buffer + struct vstor_packet + u64)
1727          */
1728         max_outstanding_req_per_channel =
1729                 ((storvsc_ringbuffer_size - PAGE_SIZE) /
1730                 ALIGN(MAX_MULTIPAGE_BUFFER_PACKET +
1731                 sizeof(struct vstor_packet) + sizeof(u64) -
1732                 vmscsi_size_delta,
1733                 sizeof(u64)));
1734
1735         return vmbus_driver_register(&storvsc_drv);
1736 }
1737
1738 static void __exit storvsc_drv_exit(void)
1739 {
1740         vmbus_driver_unregister(&storvsc_drv);
1741 }
1742
1743 MODULE_LICENSE("GPL");
1744 MODULE_DESCRIPTION("Microsoft Hyper-V virtual storage driver");
1745 module_init(storvsc_drv_init);
1746 module_exit(storvsc_drv_exit);