Linux-libre 4.4.135-gnu
[librecmc/linux-libre.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
383 static void storvsc_on_channel_callback(void *context);
384
385 #define STORVSC_MAX_LUNS_PER_TARGET                     255
386 #define STORVSC_MAX_TARGETS                             2
387 #define STORVSC_MAX_CHANNELS                            8
388
389 #define STORVSC_FC_MAX_LUNS_PER_TARGET                  255
390 #define STORVSC_FC_MAX_TARGETS                          128
391 #define STORVSC_FC_MAX_CHANNELS                         8
392
393 #define STORVSC_IDE_MAX_LUNS_PER_TARGET                 64
394 #define STORVSC_IDE_MAX_TARGETS                         1
395 #define STORVSC_IDE_MAX_CHANNELS                        1
396
397 struct storvsc_cmd_request {
398         struct scsi_cmnd *cmd;
399
400         struct hv_device *device;
401
402         /* Synchronize the request/response if needed */
403         struct completion wait_event;
404
405         struct vmbus_channel_packet_multipage_buffer mpb;
406         struct vmbus_packet_mpb_array *payload;
407         u32 payload_sz;
408
409         struct vstor_packet vstor_packet;
410 };
411
412
413 /* A storvsc device is a device object that contains a vmbus channel */
414 struct storvsc_device {
415         struct hv_device *device;
416
417         bool     destroy;
418         bool     drain_notify;
419         bool     open_sub_channel;
420         atomic_t num_outstanding_req;
421         struct Scsi_Host *host;
422
423         wait_queue_head_t waiting_to_drain;
424
425         /*
426          * Each unique Port/Path/Target represents 1 channel ie scsi
427          * controller. In reality, the pathid, targetid is always 0
428          * and the port is set by us
429          */
430         unsigned int port_number;
431         unsigned char path_id;
432         unsigned char target_id;
433
434         /*
435          * Max I/O, the device can support.
436          */
437         u32   max_transfer_bytes;
438         /* Used for vsc/vsp channel reset process */
439         struct storvsc_cmd_request init_request;
440         struct storvsc_cmd_request reset_request;
441 };
442
443 struct hv_host_device {
444         struct hv_device *dev;
445         unsigned int port;
446         unsigned char path;
447         unsigned char target;
448 };
449
450 struct storvsc_scan_work {
451         struct work_struct work;
452         struct Scsi_Host *host;
453         uint lun;
454 };
455
456 static void storvsc_device_scan(struct work_struct *work)
457 {
458         struct storvsc_scan_work *wrk;
459         uint lun;
460         struct scsi_device *sdev;
461
462         wrk = container_of(work, struct storvsc_scan_work, work);
463         lun = wrk->lun;
464
465         sdev = scsi_device_lookup(wrk->host, 0, 0, lun);
466         if (!sdev)
467                 goto done;
468         scsi_rescan_device(&sdev->sdev_gendev);
469         scsi_device_put(sdev);
470
471 done:
472         kfree(wrk);
473 }
474
475 static void storvsc_host_scan(struct work_struct *work)
476 {
477         struct storvsc_scan_work *wrk;
478         struct Scsi_Host *host;
479         struct scsi_device *sdev;
480
481         wrk = container_of(work, struct storvsc_scan_work, work);
482         host = wrk->host;
483
484         /*
485          * Before scanning the host, first check to see if any of the
486          * currrently known devices have been hot removed. We issue a
487          * "unit ready" command against all currently known devices.
488          * This I/O will result in an error for devices that have been
489          * removed. As part of handling the I/O error, we remove the device.
490          *
491          * When a LUN is added or removed, the host sends us a signal to
492          * scan the host. Thus we are forced to discover the LUNs that
493          * may have been removed this way.
494          */
495         mutex_lock(&host->scan_mutex);
496         shost_for_each_device(sdev, host)
497                 scsi_test_unit_ready(sdev, 1, 1, NULL);
498         mutex_unlock(&host->scan_mutex);
499         /*
500          * Now scan the host to discover LUNs that may have been added.
501          */
502         scsi_scan_host(host);
503
504         kfree(wrk);
505 }
506
507 static void storvsc_remove_lun(struct work_struct *work)
508 {
509         struct storvsc_scan_work *wrk;
510         struct scsi_device *sdev;
511
512         wrk = container_of(work, struct storvsc_scan_work, work);
513         if (!scsi_host_get(wrk->host))
514                 goto done;
515
516         sdev = scsi_device_lookup(wrk->host, 0, 0, wrk->lun);
517
518         if (sdev) {
519                 scsi_remove_device(sdev);
520                 scsi_device_put(sdev);
521         }
522         scsi_host_put(wrk->host);
523
524 done:
525         kfree(wrk);
526 }
527
528
529 /*
530  * We can get incoming messages from the host that are not in response to
531  * messages that we have sent out. An example of this would be messages
532  * received by the guest to notify dynamic addition/removal of LUNs. To
533  * deal with potential race conditions where the driver may be in the
534  * midst of being unloaded when we might receive an unsolicited message
535  * from the host, we have implemented a mechanism to gurantee sequential
536  * consistency:
537  *
538  * 1) Once the device is marked as being destroyed, we will fail all
539  *    outgoing messages.
540  * 2) We permit incoming messages when the device is being destroyed,
541  *    only to properly account for messages already sent out.
542  */
543
544 static inline struct storvsc_device *get_out_stor_device(
545                                         struct hv_device *device)
546 {
547         struct storvsc_device *stor_device;
548
549         stor_device = hv_get_drvdata(device);
550
551         if (stor_device && stor_device->destroy)
552                 stor_device = NULL;
553
554         return stor_device;
555 }
556
557
558 static inline void storvsc_wait_to_drain(struct storvsc_device *dev)
559 {
560         dev->drain_notify = true;
561         wait_event(dev->waiting_to_drain,
562                    atomic_read(&dev->num_outstanding_req) == 0);
563         dev->drain_notify = false;
564 }
565
566 static inline struct storvsc_device *get_in_stor_device(
567                                         struct hv_device *device)
568 {
569         struct storvsc_device *stor_device;
570
571         stor_device = hv_get_drvdata(device);
572
573         if (!stor_device)
574                 goto get_in_err;
575
576         /*
577          * If the device is being destroyed; allow incoming
578          * traffic only to cleanup outstanding requests.
579          */
580
581         if (stor_device->destroy  &&
582                 (atomic_read(&stor_device->num_outstanding_req) == 0))
583                 stor_device = NULL;
584
585 get_in_err:
586         return stor_device;
587
588 }
589
590 static void handle_sc_creation(struct vmbus_channel *new_sc)
591 {
592         struct hv_device *device = new_sc->primary_channel->device_obj;
593         struct storvsc_device *stor_device;
594         struct vmstorage_channel_properties props;
595
596         stor_device = get_out_stor_device(device);
597         if (!stor_device)
598                 return;
599
600         if (stor_device->open_sub_channel == false)
601                 return;
602
603         memset(&props, 0, sizeof(struct vmstorage_channel_properties));
604
605         vmbus_open(new_sc,
606                    storvsc_ringbuffer_size,
607                    storvsc_ringbuffer_size,
608                    (void *)&props,
609                    sizeof(struct vmstorage_channel_properties),
610                    storvsc_on_channel_callback, new_sc);
611 }
612
613 static void  handle_multichannel_storage(struct hv_device *device, int max_chns)
614 {
615         struct storvsc_device *stor_device;
616         int num_cpus = num_online_cpus();
617         int num_sc;
618         struct storvsc_cmd_request *request;
619         struct vstor_packet *vstor_packet;
620         int ret, t;
621
622         num_sc = ((max_chns > num_cpus) ? num_cpus : max_chns);
623         stor_device = get_out_stor_device(device);
624         if (!stor_device)
625                 return;
626
627         request = &stor_device->init_request;
628         vstor_packet = &request->vstor_packet;
629
630         stor_device->open_sub_channel = true;
631         /*
632          * Establish a handler for dealing with subchannels.
633          */
634         vmbus_set_sc_create_callback(device->channel, handle_sc_creation);
635
636         /*
637          * Check to see if sub-channels have already been created. This
638          * can happen when this driver is re-loaded after unloading.
639          */
640
641         if (vmbus_are_subchannels_present(device->channel))
642                 return;
643
644         stor_device->open_sub_channel = false;
645         /*
646          * Request the host to create sub-channels.
647          */
648         memset(request, 0, sizeof(struct storvsc_cmd_request));
649         init_completion(&request->wait_event);
650         vstor_packet->operation = VSTOR_OPERATION_CREATE_SUB_CHANNELS;
651         vstor_packet->flags = REQUEST_COMPLETION_FLAG;
652         vstor_packet->sub_channel_count = num_sc;
653
654         ret = vmbus_sendpacket(device->channel, vstor_packet,
655                                (sizeof(struct vstor_packet) -
656                                vmscsi_size_delta),
657                                (unsigned long)request,
658                                VM_PKT_DATA_INBAND,
659                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
660
661         if (ret != 0)
662                 return;
663
664         t = wait_for_completion_timeout(&request->wait_event, 10*HZ);
665         if (t == 0)
666                 return;
667
668         if (vstor_packet->operation != VSTOR_OPERATION_COMPLETE_IO ||
669             vstor_packet->status != 0)
670                 return;
671
672         /*
673          * Now that we created the sub-channels, invoke the check; this
674          * may trigger the callback.
675          */
676         stor_device->open_sub_channel = true;
677         vmbus_are_subchannels_present(device->channel);
678 }
679
680 static int storvsc_channel_init(struct hv_device *device)
681 {
682         struct storvsc_device *stor_device;
683         struct storvsc_cmd_request *request;
684         struct vstor_packet *vstor_packet;
685         int ret, t, i;
686         int max_chns;
687         bool process_sub_channels = false;
688
689         stor_device = get_out_stor_device(device);
690         if (!stor_device)
691                 return -ENODEV;
692
693         request = &stor_device->init_request;
694         vstor_packet = &request->vstor_packet;
695
696         /*
697          * Now, initiate the vsc/vsp initialization protocol on the open
698          * channel
699          */
700         memset(request, 0, sizeof(struct storvsc_cmd_request));
701         init_completion(&request->wait_event);
702         vstor_packet->operation = VSTOR_OPERATION_BEGIN_INITIALIZATION;
703         vstor_packet->flags = REQUEST_COMPLETION_FLAG;
704
705         ret = vmbus_sendpacket(device->channel, vstor_packet,
706                                (sizeof(struct vstor_packet) -
707                                vmscsi_size_delta),
708                                (unsigned long)request,
709                                VM_PKT_DATA_INBAND,
710                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
711         if (ret != 0)
712                 goto cleanup;
713
714         t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
715         if (t == 0) {
716                 ret = -ETIMEDOUT;
717                 goto cleanup;
718         }
719
720         if (vstor_packet->operation != VSTOR_OPERATION_COMPLETE_IO ||
721             vstor_packet->status != 0) {
722                 ret = -EINVAL;
723                 goto cleanup;
724         }
725
726
727         for (i = 0; i < ARRAY_SIZE(vmstor_protocols); i++) {
728                 /* reuse the packet for version range supported */
729                 memset(vstor_packet, 0, sizeof(struct vstor_packet));
730                 vstor_packet->operation =
731                         VSTOR_OPERATION_QUERY_PROTOCOL_VERSION;
732                 vstor_packet->flags = REQUEST_COMPLETION_FLAG;
733
734                 vstor_packet->version.major_minor =
735                         vmstor_protocols[i].protocol_version;
736
737                 /*
738                  * The revision number is only used in Windows; set it to 0.
739                  */
740                 vstor_packet->version.revision = 0;
741
742                 ret = vmbus_sendpacket(device->channel, vstor_packet,
743                                (sizeof(struct vstor_packet) -
744                                 vmscsi_size_delta),
745                                (unsigned long)request,
746                                VM_PKT_DATA_INBAND,
747                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
748                 if (ret != 0)
749                         goto cleanup;
750
751                 t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
752                 if (t == 0) {
753                         ret = -ETIMEDOUT;
754                         goto cleanup;
755                 }
756
757                 if (vstor_packet->operation != VSTOR_OPERATION_COMPLETE_IO) {
758                         ret = -EINVAL;
759                         goto cleanup;
760                 }
761
762                 if (vstor_packet->status == 0) {
763                         vmstor_proto_version =
764                                 vmstor_protocols[i].protocol_version;
765
766                         sense_buffer_size =
767                                 vmstor_protocols[i].sense_buffer_size;
768
769                         vmscsi_size_delta =
770                                 vmstor_protocols[i].vmscsi_size_delta;
771
772                         break;
773                 }
774         }
775
776         if (vstor_packet->status != 0) {
777                 ret = -EINVAL;
778                 goto cleanup;
779         }
780
781
782         memset(vstor_packet, 0, sizeof(struct vstor_packet));
783         vstor_packet->operation = VSTOR_OPERATION_QUERY_PROPERTIES;
784         vstor_packet->flags = REQUEST_COMPLETION_FLAG;
785
786         ret = vmbus_sendpacket(device->channel, vstor_packet,
787                                (sizeof(struct vstor_packet) -
788                                 vmscsi_size_delta),
789                                (unsigned long)request,
790                                VM_PKT_DATA_INBAND,
791                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
792
793         if (ret != 0)
794                 goto cleanup;
795
796         t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
797         if (t == 0) {
798                 ret = -ETIMEDOUT;
799                 goto cleanup;
800         }
801
802         if (vstor_packet->operation != VSTOR_OPERATION_COMPLETE_IO ||
803             vstor_packet->status != 0) {
804                 ret = -EINVAL;
805                 goto cleanup;
806         }
807
808         /*
809          * Check to see if multi-channel support is there.
810          * Hosts that implement protocol version of 5.1 and above
811          * support multi-channel.
812          */
813         max_chns = vstor_packet->storage_channel_properties.max_channel_cnt;
814         if (vmstor_proto_version >= VMSTOR_PROTO_VERSION_WIN8) {
815                 if (vstor_packet->storage_channel_properties.flags &
816                     STORAGE_CHANNEL_SUPPORTS_MULTI_CHANNEL)
817                         process_sub_channels = true;
818         }
819         stor_device->max_transfer_bytes =
820                 vstor_packet->storage_channel_properties.max_transfer_bytes;
821
822         memset(vstor_packet, 0, sizeof(struct vstor_packet));
823         vstor_packet->operation = VSTOR_OPERATION_END_INITIALIZATION;
824         vstor_packet->flags = REQUEST_COMPLETION_FLAG;
825
826         ret = vmbus_sendpacket(device->channel, vstor_packet,
827                                (sizeof(struct vstor_packet) -
828                                 vmscsi_size_delta),
829                                (unsigned long)request,
830                                VM_PKT_DATA_INBAND,
831                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
832
833         if (ret != 0)
834                 goto cleanup;
835
836         t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
837         if (t == 0) {
838                 ret = -ETIMEDOUT;
839                 goto cleanup;
840         }
841
842         if (vstor_packet->operation != VSTOR_OPERATION_COMPLETE_IO ||
843             vstor_packet->status != 0) {
844                 ret = -EINVAL;
845                 goto cleanup;
846         }
847
848         if (process_sub_channels)
849                 handle_multichannel_storage(device, max_chns);
850
851
852 cleanup:
853         return ret;
854 }
855
856 static void storvsc_handle_error(struct vmscsi_request *vm_srb,
857                                 struct scsi_cmnd *scmnd,
858                                 struct Scsi_Host *host,
859                                 u8 asc, u8 ascq)
860 {
861         struct storvsc_scan_work *wrk;
862         void (*process_err_fn)(struct work_struct *work);
863         bool do_work = false;
864
865         switch (SRB_STATUS(vm_srb->srb_status)) {
866         case SRB_STATUS_ERROR:
867                 /*
868                  * Let upper layer deal with error when
869                  * sense message is present.
870                  */
871
872                 if (vm_srb->srb_status & SRB_STATUS_AUTOSENSE_VALID)
873                         break;
874                 /*
875                  * If there is an error; offline the device since all
876                  * error recovery strategies would have already been
877                  * deployed on the host side. However, if the command
878                  * were a pass-through command deal with it appropriately.
879                  */
880                 switch (scmnd->cmnd[0]) {
881                 case ATA_16:
882                 case ATA_12:
883                         set_host_byte(scmnd, DID_PASSTHROUGH);
884                         break;
885                 /*
886                  * On Some Windows hosts TEST_UNIT_READY command can return
887                  * SRB_STATUS_ERROR, let the upper level code deal with it
888                  * based on the sense information.
889                  */
890                 case TEST_UNIT_READY:
891                         break;
892                 default:
893                         set_host_byte(scmnd, DID_ERROR);
894                 }
895                 break;
896         case SRB_STATUS_INVALID_LUN:
897                 set_host_byte(scmnd, DID_NO_CONNECT);
898                 do_work = true;
899                 process_err_fn = storvsc_remove_lun;
900                 break;
901         case SRB_STATUS_ABORTED:
902                 if (vm_srb->srb_status & SRB_STATUS_AUTOSENSE_VALID &&
903                     (asc == 0x2a) && (ascq == 0x9)) {
904                         do_work = true;
905                         process_err_fn = storvsc_device_scan;
906                         /*
907                          * Retry the I/O that trigerred this.
908                          */
909                         set_host_byte(scmnd, DID_REQUEUE);
910                 }
911                 break;
912         }
913
914         if (!do_work)
915                 return;
916
917         /*
918          * We need to schedule work to process this error; schedule it.
919          */
920         wrk = kmalloc(sizeof(struct storvsc_scan_work), GFP_ATOMIC);
921         if (!wrk) {
922                 set_host_byte(scmnd, DID_TARGET_FAILURE);
923                 return;
924         }
925
926         wrk->host = host;
927         wrk->lun = vm_srb->lun;
928         INIT_WORK(&wrk->work, process_err_fn);
929         schedule_work(&wrk->work);
930 }
931
932
933 static void storvsc_command_completion(struct storvsc_cmd_request *cmd_request)
934 {
935         struct scsi_cmnd *scmnd = cmd_request->cmd;
936         struct hv_host_device *host_dev = shost_priv(scmnd->device->host);
937         struct scsi_sense_hdr sense_hdr;
938         struct vmscsi_request *vm_srb;
939         u32 data_transfer_length;
940         struct Scsi_Host *host;
941         struct storvsc_device *stor_dev;
942         struct hv_device *dev = host_dev->dev;
943         u32 payload_sz = cmd_request->payload_sz;
944         void *payload = cmd_request->payload;
945
946         stor_dev = get_in_stor_device(dev);
947         host = stor_dev->host;
948
949         vm_srb = &cmd_request->vstor_packet.vm_srb;
950         data_transfer_length = vm_srb->data_transfer_length;
951
952         scmnd->result = vm_srb->scsi_status;
953
954         if (scmnd->result) {
955                 if (scsi_normalize_sense(scmnd->sense_buffer,
956                                 SCSI_SENSE_BUFFERSIZE, &sense_hdr))
957                         scsi_print_sense_hdr(scmnd->device, "storvsc",
958                                              &sense_hdr);
959         }
960
961         if (vm_srb->srb_status != SRB_STATUS_SUCCESS) {
962                 storvsc_handle_error(vm_srb, scmnd, host, sense_hdr.asc,
963                                          sense_hdr.ascq);
964                 /*
965                  * The Windows driver set data_transfer_length on
966                  * SRB_STATUS_DATA_OVERRUN. On other errors, this value
967                  * is untouched.  In these cases we set it to 0.
968                  */
969                 if (vm_srb->srb_status != SRB_STATUS_DATA_OVERRUN)
970                         data_transfer_length = 0;
971         }
972
973         scsi_set_resid(scmnd,
974                 cmd_request->payload->range.len - data_transfer_length);
975
976         scmnd->scsi_done(scmnd);
977
978         if (payload_sz >
979                 sizeof(struct vmbus_channel_packet_multipage_buffer))
980                 kfree(payload);
981 }
982
983 static void storvsc_on_io_completion(struct hv_device *device,
984                                   struct vstor_packet *vstor_packet,
985                                   struct storvsc_cmd_request *request)
986 {
987         struct storvsc_device *stor_device;
988         struct vstor_packet *stor_pkt;
989
990         stor_device = hv_get_drvdata(device);
991         stor_pkt = &request->vstor_packet;
992
993         /*
994          * The current SCSI handling on the host side does
995          * not correctly handle:
996          * INQUIRY command with page code parameter set to 0x80
997          * MODE_SENSE command with cmd[2] == 0x1c
998          *
999          * Setup srb and scsi status so this won't be fatal.
1000          * We do this so we can distinguish truly fatal failues
1001          * (srb status == 0x4) and off-line the device in that case.
1002          */
1003
1004         if ((stor_pkt->vm_srb.cdb[0] == INQUIRY) ||
1005            (stor_pkt->vm_srb.cdb[0] == MODE_SENSE)) {
1006                 vstor_packet->vm_srb.scsi_status = 0;
1007                 vstor_packet->vm_srb.srb_status = SRB_STATUS_SUCCESS;
1008         }
1009
1010
1011         /* Copy over the status...etc */
1012         stor_pkt->vm_srb.scsi_status = vstor_packet->vm_srb.scsi_status;
1013         stor_pkt->vm_srb.srb_status = vstor_packet->vm_srb.srb_status;
1014         stor_pkt->vm_srb.sense_info_length =
1015         vstor_packet->vm_srb.sense_info_length;
1016
1017
1018         if ((vstor_packet->vm_srb.scsi_status & 0xFF) == 0x02) {
1019                 /* CHECK_CONDITION */
1020                 if (vstor_packet->vm_srb.srb_status &
1021                         SRB_STATUS_AUTOSENSE_VALID) {
1022                         /* autosense data available */
1023
1024                         memcpy(request->cmd->sense_buffer,
1025                                vstor_packet->vm_srb.sense_data,
1026                                vstor_packet->vm_srb.sense_info_length);
1027
1028                 }
1029         }
1030
1031         stor_pkt->vm_srb.data_transfer_length =
1032         vstor_packet->vm_srb.data_transfer_length;
1033
1034         storvsc_command_completion(request);
1035
1036         if (atomic_dec_and_test(&stor_device->num_outstanding_req) &&
1037                 stor_device->drain_notify)
1038                 wake_up(&stor_device->waiting_to_drain);
1039
1040
1041 }
1042
1043 static void storvsc_on_receive(struct hv_device *device,
1044                              struct vstor_packet *vstor_packet,
1045                              struct storvsc_cmd_request *request)
1046 {
1047         struct storvsc_scan_work *work;
1048         struct storvsc_device *stor_device;
1049
1050         switch (vstor_packet->operation) {
1051         case VSTOR_OPERATION_COMPLETE_IO:
1052                 storvsc_on_io_completion(device, vstor_packet, request);
1053                 break;
1054
1055         case VSTOR_OPERATION_REMOVE_DEVICE:
1056         case VSTOR_OPERATION_ENUMERATE_BUS:
1057                 stor_device = get_in_stor_device(device);
1058                 work = kmalloc(sizeof(struct storvsc_scan_work), GFP_ATOMIC);
1059                 if (!work)
1060                         return;
1061
1062                 INIT_WORK(&work->work, storvsc_host_scan);
1063                 work->host = stor_device->host;
1064                 schedule_work(&work->work);
1065                 break;
1066
1067         default:
1068                 break;
1069         }
1070 }
1071
1072 static void storvsc_on_channel_callback(void *context)
1073 {
1074         struct vmbus_channel *channel = (struct vmbus_channel *)context;
1075         struct hv_device *device;
1076         struct storvsc_device *stor_device;
1077         u32 bytes_recvd;
1078         u64 request_id;
1079         unsigned char packet[ALIGN(sizeof(struct vstor_packet), 8)];
1080         struct storvsc_cmd_request *request;
1081         int ret;
1082
1083         if (channel->primary_channel != NULL)
1084                 device = channel->primary_channel->device_obj;
1085         else
1086                 device = channel->device_obj;
1087
1088         stor_device = get_in_stor_device(device);
1089         if (!stor_device)
1090                 return;
1091
1092         do {
1093                 ret = vmbus_recvpacket(channel, packet,
1094                                        ALIGN((sizeof(struct vstor_packet) -
1095                                              vmscsi_size_delta), 8),
1096                                        &bytes_recvd, &request_id);
1097                 if (ret == 0 && bytes_recvd > 0) {
1098
1099                         request = (struct storvsc_cmd_request *)
1100                                         (unsigned long)request_id;
1101
1102                         if ((request == &stor_device->init_request) ||
1103                             (request == &stor_device->reset_request)) {
1104
1105                                 memcpy(&request->vstor_packet, packet,
1106                                        (sizeof(struct vstor_packet) -
1107                                         vmscsi_size_delta));
1108                                 complete(&request->wait_event);
1109                         } else {
1110                                 storvsc_on_receive(device,
1111                                                 (struct vstor_packet *)packet,
1112                                                 request);
1113                         }
1114                 } else {
1115                         break;
1116                 }
1117         } while (1);
1118
1119         return;
1120 }
1121
1122 static int storvsc_connect_to_vsp(struct hv_device *device, u32 ring_size)
1123 {
1124         struct vmstorage_channel_properties props;
1125         int ret;
1126
1127         memset(&props, 0, sizeof(struct vmstorage_channel_properties));
1128
1129         ret = vmbus_open(device->channel,
1130                          ring_size,
1131                          ring_size,
1132                          (void *)&props,
1133                          sizeof(struct vmstorage_channel_properties),
1134                          storvsc_on_channel_callback, device->channel);
1135
1136         if (ret != 0)
1137                 return ret;
1138
1139         ret = storvsc_channel_init(device);
1140
1141         return ret;
1142 }
1143
1144 static int storvsc_dev_remove(struct hv_device *device)
1145 {
1146         struct storvsc_device *stor_device;
1147         unsigned long flags;
1148
1149         stor_device = hv_get_drvdata(device);
1150
1151         spin_lock_irqsave(&device->channel->inbound_lock, flags);
1152         stor_device->destroy = true;
1153         spin_unlock_irqrestore(&device->channel->inbound_lock, flags);
1154
1155         /*
1156          * At this point, all outbound traffic should be disable. We
1157          * only allow inbound traffic (responses) to proceed so that
1158          * outstanding requests can be completed.
1159          */
1160
1161         storvsc_wait_to_drain(stor_device);
1162
1163         /*
1164          * Since we have already drained, we don't need to busy wait
1165          * as was done in final_release_stor_device()
1166          * Note that we cannot set the ext pointer to NULL until
1167          * we have drained - to drain the outgoing packets, we need to
1168          * allow incoming packets.
1169          */
1170         spin_lock_irqsave(&device->channel->inbound_lock, flags);
1171         hv_set_drvdata(device, NULL);
1172         spin_unlock_irqrestore(&device->channel->inbound_lock, flags);
1173
1174         /* Close the channel */
1175         vmbus_close(device->channel);
1176
1177         kfree(stor_device);
1178         return 0;
1179 }
1180
1181 static int storvsc_do_io(struct hv_device *device,
1182                          struct storvsc_cmd_request *request)
1183 {
1184         struct storvsc_device *stor_device;
1185         struct vstor_packet *vstor_packet;
1186         struct vmbus_channel *outgoing_channel;
1187         int ret = 0;
1188
1189         vstor_packet = &request->vstor_packet;
1190         stor_device = get_out_stor_device(device);
1191
1192         if (!stor_device)
1193                 return -ENODEV;
1194
1195
1196         request->device  = device;
1197         /*
1198          * Select an an appropriate channel to send the request out.
1199          */
1200
1201         outgoing_channel = vmbus_get_outgoing_channel(device->channel);
1202
1203
1204         vstor_packet->flags |= REQUEST_COMPLETION_FLAG;
1205
1206         vstor_packet->vm_srb.length = (sizeof(struct vmscsi_request) -
1207                                         vmscsi_size_delta);
1208
1209
1210         vstor_packet->vm_srb.sense_info_length = sense_buffer_size;
1211
1212
1213         vstor_packet->vm_srb.data_transfer_length =
1214         request->payload->range.len;
1215
1216         vstor_packet->operation = VSTOR_OPERATION_EXECUTE_SRB;
1217
1218         if (request->payload->range.len) {
1219
1220                 ret = vmbus_sendpacket_mpb_desc(outgoing_channel,
1221                                 request->payload, request->payload_sz,
1222                                 vstor_packet,
1223                                 (sizeof(struct vstor_packet) -
1224                                 vmscsi_size_delta),
1225                                 (unsigned long)request);
1226         } else {
1227                 ret = vmbus_sendpacket(outgoing_channel, vstor_packet,
1228                                (sizeof(struct vstor_packet) -
1229                                 vmscsi_size_delta),
1230                                (unsigned long)request,
1231                                VM_PKT_DATA_INBAND,
1232                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1233         }
1234
1235         if (ret != 0)
1236                 return ret;
1237
1238         atomic_inc(&stor_device->num_outstanding_req);
1239
1240         return ret;
1241 }
1242
1243 static int storvsc_device_alloc(struct scsi_device *sdevice)
1244 {
1245         /*
1246          * Set blist flag to permit the reading of the VPD pages even when
1247          * the target may claim SPC-2 compliance. MSFT targets currently
1248          * claim SPC-2 compliance while they implement post SPC-2 features.
1249          * With this flag we can correctly handle WRITE_SAME_16 issues.
1250          *
1251          * Hypervisor reports SCSI_UNKNOWN type for DVD ROM device but
1252          * still supports REPORT LUN.
1253          */
1254         sdevice->sdev_bflags = BLIST_REPORTLUN2 | BLIST_TRY_VPD_PAGES;
1255
1256         return 0;
1257 }
1258
1259 static int storvsc_device_configure(struct scsi_device *sdevice)
1260 {
1261
1262         blk_queue_max_segment_size(sdevice->request_queue, PAGE_SIZE);
1263
1264         blk_queue_bounce_limit(sdevice->request_queue, BLK_BOUNCE_ANY);
1265
1266         blk_queue_rq_timeout(sdevice->request_queue, (storvsc_timeout * HZ));
1267
1268         /* Ensure there are no gaps in presented sgls */
1269         blk_queue_virt_boundary(sdevice->request_queue, PAGE_SIZE - 1);
1270
1271         sdevice->no_write_same = 1;
1272
1273         /*
1274          * If the host is WIN8 or WIN8 R2, claim conformance to SPC-3
1275          * if the device is a MSFT virtual device.  If the host is
1276          * WIN10 or newer, allow write_same.
1277          */
1278         if (!strncmp(sdevice->vendor, "Msft", 4)) {
1279                 switch (vmstor_proto_version) {
1280                 case VMSTOR_PROTO_VERSION_WIN8:
1281                 case VMSTOR_PROTO_VERSION_WIN8_1:
1282                         sdevice->scsi_level = SCSI_SPC_3;
1283                         break;
1284                 }
1285
1286                 if (vmstor_proto_version >= VMSTOR_PROTO_VERSION_WIN10)
1287                         sdevice->no_write_same = 0;
1288         }
1289
1290         return 0;
1291 }
1292
1293 static int storvsc_get_chs(struct scsi_device *sdev, struct block_device * bdev,
1294                            sector_t capacity, int *info)
1295 {
1296         sector_t nsect = capacity;
1297         sector_t cylinders = nsect;
1298         int heads, sectors_pt;
1299
1300         /*
1301          * We are making up these values; let us keep it simple.
1302          */
1303         heads = 0xff;
1304         sectors_pt = 0x3f;      /* Sectors per track */
1305         sector_div(cylinders, heads * sectors_pt);
1306         if ((sector_t)(cylinders + 1) * heads * sectors_pt < nsect)
1307                 cylinders = 0xffff;
1308
1309         info[0] = heads;
1310         info[1] = sectors_pt;
1311         info[2] = (int)cylinders;
1312
1313         return 0;
1314 }
1315
1316 static int storvsc_host_reset_handler(struct scsi_cmnd *scmnd)
1317 {
1318         struct hv_host_device *host_dev = shost_priv(scmnd->device->host);
1319         struct hv_device *device = host_dev->dev;
1320
1321         struct storvsc_device *stor_device;
1322         struct storvsc_cmd_request *request;
1323         struct vstor_packet *vstor_packet;
1324         int ret, t;
1325
1326
1327         stor_device = get_out_stor_device(device);
1328         if (!stor_device)
1329                 return FAILED;
1330
1331         request = &stor_device->reset_request;
1332         vstor_packet = &request->vstor_packet;
1333
1334         init_completion(&request->wait_event);
1335
1336         vstor_packet->operation = VSTOR_OPERATION_RESET_BUS;
1337         vstor_packet->flags = REQUEST_COMPLETION_FLAG;
1338         vstor_packet->vm_srb.path_id = stor_device->path_id;
1339
1340         ret = vmbus_sendpacket(device->channel, vstor_packet,
1341                                (sizeof(struct vstor_packet) -
1342                                 vmscsi_size_delta),
1343                                (unsigned long)&stor_device->reset_request,
1344                                VM_PKT_DATA_INBAND,
1345                                VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1346         if (ret != 0)
1347                 return FAILED;
1348
1349         t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
1350         if (t == 0)
1351                 return TIMEOUT_ERROR;
1352
1353
1354         /*
1355          * At this point, all outstanding requests in the adapter
1356          * should have been flushed out and return to us
1357          * There is a potential race here where the host may be in
1358          * the process of responding when we return from here.
1359          * Just wait for all in-transit packets to be accounted for
1360          * before we return from here.
1361          */
1362         storvsc_wait_to_drain(stor_device);
1363
1364         return SUCCESS;
1365 }
1366
1367 /*
1368  * The host guarantees to respond to each command, although I/O latencies might
1369  * be unbounded on Azure.  Reset the timer unconditionally to give the host a
1370  * chance to perform EH.
1371  */
1372 static enum blk_eh_timer_return storvsc_eh_timed_out(struct scsi_cmnd *scmnd)
1373 {
1374         return BLK_EH_RESET_TIMER;
1375 }
1376
1377 static bool storvsc_scsi_cmd_ok(struct scsi_cmnd *scmnd)
1378 {
1379         bool allowed = true;
1380         u8 scsi_op = scmnd->cmnd[0];
1381
1382         switch (scsi_op) {
1383         /* the host does not handle WRITE_SAME, log accident usage */
1384         case WRITE_SAME:
1385         /*
1386          * smartd sends this command and the host does not handle
1387          * this. So, don't send it.
1388          */
1389         case SET_WINDOW:
1390                 scmnd->result = ILLEGAL_REQUEST << 16;
1391                 allowed = false;
1392                 break;
1393         default:
1394                 break;
1395         }
1396         return allowed;
1397 }
1398
1399 static int storvsc_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *scmnd)
1400 {
1401         int ret;
1402         struct hv_host_device *host_dev = shost_priv(host);
1403         struct hv_device *dev = host_dev->dev;
1404         struct storvsc_cmd_request *cmd_request = scsi_cmd_priv(scmnd);
1405         int i;
1406         struct scatterlist *sgl;
1407         unsigned int sg_count = 0;
1408         struct vmscsi_request *vm_srb;
1409         struct scatterlist *cur_sgl;
1410         struct vmbus_packet_mpb_array  *payload;
1411         u32 payload_sz;
1412         u32 length;
1413
1414         if (vmstor_proto_version <= VMSTOR_PROTO_VERSION_WIN8) {
1415                 /*
1416                  * On legacy hosts filter unimplemented commands.
1417                  * Future hosts are expected to correctly handle
1418                  * unsupported commands. Furthermore, it is
1419                  * possible that some of the currently
1420                  * unsupported commands maybe supported in
1421                  * future versions of the host.
1422                  */
1423                 if (!storvsc_scsi_cmd_ok(scmnd)) {
1424                         scmnd->scsi_done(scmnd);
1425                         return 0;
1426                 }
1427         }
1428
1429         /* Setup the cmd request */
1430         cmd_request->cmd = scmnd;
1431
1432         vm_srb = &cmd_request->vstor_packet.vm_srb;
1433         vm_srb->win8_extension.time_out_value = 60;
1434
1435         vm_srb->win8_extension.srb_flags |=
1436                 SRB_FLAGS_DISABLE_SYNCH_TRANSFER;
1437
1438         if (scmnd->device->tagged_supported) {
1439                 vm_srb->win8_extension.srb_flags |=
1440                 (SRB_FLAGS_QUEUE_ACTION_ENABLE | SRB_FLAGS_NO_QUEUE_FREEZE);
1441                 vm_srb->win8_extension.queue_tag = SP_UNTAGGED;
1442                 vm_srb->win8_extension.queue_action = SRB_SIMPLE_TAG_REQUEST;
1443         }
1444
1445         /* Build the SRB */
1446         switch (scmnd->sc_data_direction) {
1447         case DMA_TO_DEVICE:
1448                 vm_srb->data_in = WRITE_TYPE;
1449                 vm_srb->win8_extension.srb_flags |= SRB_FLAGS_DATA_OUT;
1450                 break;
1451         case DMA_FROM_DEVICE:
1452                 vm_srb->data_in = READ_TYPE;
1453                 vm_srb->win8_extension.srb_flags |= SRB_FLAGS_DATA_IN;
1454                 break;
1455         case DMA_NONE:
1456                 vm_srb->data_in = UNKNOWN_TYPE;
1457                 vm_srb->win8_extension.srb_flags |= SRB_FLAGS_NO_DATA_TRANSFER;
1458                 break;
1459         default:
1460                 /*
1461                  * This is DMA_BIDIRECTIONAL or something else we are never
1462                  * supposed to see here.
1463                  */
1464                 WARN(1, "Unexpected data direction: %d\n",
1465                      scmnd->sc_data_direction);
1466                 return -EINVAL;
1467         }
1468
1469
1470         vm_srb->port_number = host_dev->port;
1471         vm_srb->path_id = scmnd->device->channel;
1472         vm_srb->target_id = scmnd->device->id;
1473         vm_srb->lun = scmnd->device->lun;
1474
1475         vm_srb->cdb_length = scmnd->cmd_len;
1476
1477         memcpy(vm_srb->cdb, scmnd->cmnd, vm_srb->cdb_length);
1478
1479         sgl = (struct scatterlist *)scsi_sglist(scmnd);
1480         sg_count = scsi_sg_count(scmnd);
1481
1482         length = scsi_bufflen(scmnd);
1483         payload = (struct vmbus_packet_mpb_array *)&cmd_request->mpb;
1484         payload_sz = sizeof(cmd_request->mpb);
1485
1486         if (sg_count) {
1487                 if (sg_count > MAX_PAGE_BUFFER_COUNT) {
1488
1489                         payload_sz = (sg_count * sizeof(void *) +
1490                                       sizeof(struct vmbus_packet_mpb_array));
1491                         payload = kmalloc(payload_sz, GFP_ATOMIC);
1492                         if (!payload)
1493                                 return SCSI_MLQUEUE_DEVICE_BUSY;
1494                 }
1495
1496                 payload->range.len = length;
1497                 payload->range.offset = sgl[0].offset;
1498
1499                 cur_sgl = sgl;
1500                 for (i = 0; i < sg_count; i++) {
1501                         payload->range.pfn_array[i] =
1502                                 page_to_pfn(sg_page((cur_sgl)));
1503                         cur_sgl = sg_next(cur_sgl);
1504                 }
1505
1506         } else if (scsi_sglist(scmnd)) {
1507                 payload->range.len = length;
1508                 payload->range.offset =
1509                         virt_to_phys(scsi_sglist(scmnd)) & (PAGE_SIZE-1);
1510                 payload->range.pfn_array[0] =
1511                         virt_to_phys(scsi_sglist(scmnd)) >> PAGE_SHIFT;
1512         }
1513
1514         cmd_request->payload = payload;
1515         cmd_request->payload_sz = payload_sz;
1516
1517         /* Invokes the vsc to start an IO */
1518         ret = storvsc_do_io(dev, cmd_request);
1519
1520         if (ret == -EAGAIN) {
1521                 if (payload_sz > sizeof(cmd_request->mpb))
1522                         kfree(payload);
1523                 /* no more space */
1524                 return SCSI_MLQUEUE_DEVICE_BUSY;
1525         }
1526
1527         return 0;
1528 }
1529
1530 static struct scsi_host_template scsi_driver = {
1531         .module =               THIS_MODULE,
1532         .name =                 "storvsc_host_t",
1533         .cmd_size =             sizeof(struct storvsc_cmd_request),
1534         .bios_param =           storvsc_get_chs,
1535         .queuecommand =         storvsc_queuecommand,
1536         .eh_host_reset_handler =        storvsc_host_reset_handler,
1537         .proc_name =            "storvsc_host",
1538         .eh_timed_out =         storvsc_eh_timed_out,
1539         .slave_alloc =          storvsc_device_alloc,
1540         .slave_configure =      storvsc_device_configure,
1541         .cmd_per_lun =          2048,
1542         .this_id =              -1,
1543         .use_clustering =       ENABLE_CLUSTERING,
1544         /* Make sure we dont get a sg segment crosses a page boundary */
1545         .dma_boundary =         PAGE_SIZE-1,
1546         .no_write_same =        1,
1547 };
1548
1549 enum {
1550         SCSI_GUID,
1551         IDE_GUID,
1552         SFC_GUID,
1553 };
1554
1555 static const struct hv_vmbus_device_id id_table[] = {
1556         /* SCSI guid */
1557         { HV_SCSI_GUID,
1558           .driver_data = SCSI_GUID
1559         },
1560         /* IDE guid */
1561         { HV_IDE_GUID,
1562           .driver_data = IDE_GUID
1563         },
1564         /* Fibre Channel GUID */
1565         {
1566           HV_SYNTHFC_GUID,
1567           .driver_data = SFC_GUID
1568         },
1569         { },
1570 };
1571
1572 MODULE_DEVICE_TABLE(vmbus, id_table);
1573
1574 static int storvsc_probe(struct hv_device *device,
1575                         const struct hv_vmbus_device_id *dev_id)
1576 {
1577         int ret;
1578         int num_cpus = num_online_cpus();
1579         struct Scsi_Host *host;
1580         struct hv_host_device *host_dev;
1581         bool dev_is_ide = ((dev_id->driver_data == IDE_GUID) ? true : false);
1582         int target = 0;
1583         struct storvsc_device *stor_device;
1584         int max_luns_per_target;
1585         int max_targets;
1586         int max_channels;
1587         int max_sub_channels = 0;
1588
1589         /*
1590          * Based on the windows host we are running on,
1591          * set state to properly communicate with the host.
1592          */
1593
1594         if (vmbus_proto_version < VERSION_WIN8) {
1595                 max_luns_per_target = STORVSC_IDE_MAX_LUNS_PER_TARGET;
1596                 max_targets = STORVSC_IDE_MAX_TARGETS;
1597                 max_channels = STORVSC_IDE_MAX_CHANNELS;
1598         } else {
1599                 max_luns_per_target = STORVSC_MAX_LUNS_PER_TARGET;
1600                 max_targets = STORVSC_MAX_TARGETS;
1601                 max_channels = STORVSC_MAX_CHANNELS;
1602                 /*
1603                  * On Windows8 and above, we support sub-channels for storage.
1604                  * The number of sub-channels offerred is based on the number of
1605                  * VCPUs in the guest.
1606                  */
1607                 max_sub_channels = (num_cpus / storvsc_vcpus_per_sub_channel);
1608         }
1609
1610         scsi_driver.can_queue = (max_outstanding_req_per_channel *
1611                                  (max_sub_channels + 1));
1612
1613         host = scsi_host_alloc(&scsi_driver,
1614                                sizeof(struct hv_host_device));
1615         if (!host)
1616                 return -ENOMEM;
1617
1618         host_dev = shost_priv(host);
1619         memset(host_dev, 0, sizeof(struct hv_host_device));
1620
1621         host_dev->port = host->host_no;
1622         host_dev->dev = device;
1623
1624
1625         stor_device = kzalloc(sizeof(struct storvsc_device), GFP_KERNEL);
1626         if (!stor_device) {
1627                 ret = -ENOMEM;
1628                 goto err_out0;
1629         }
1630
1631         stor_device->destroy = false;
1632         stor_device->open_sub_channel = false;
1633         init_waitqueue_head(&stor_device->waiting_to_drain);
1634         stor_device->device = device;
1635         stor_device->host = host;
1636         hv_set_drvdata(device, stor_device);
1637
1638         stor_device->port_number = host->host_no;
1639         ret = storvsc_connect_to_vsp(device, storvsc_ringbuffer_size);
1640         if (ret)
1641                 goto err_out1;
1642
1643         host_dev->path = stor_device->path_id;
1644         host_dev->target = stor_device->target_id;
1645
1646         switch (dev_id->driver_data) {
1647         case SFC_GUID:
1648                 host->max_lun = STORVSC_FC_MAX_LUNS_PER_TARGET;
1649                 host->max_id = STORVSC_FC_MAX_TARGETS;
1650                 host->max_channel = STORVSC_FC_MAX_CHANNELS - 1;
1651                 break;
1652
1653         case SCSI_GUID:
1654                 host->max_lun = max_luns_per_target;
1655                 host->max_id = max_targets;
1656                 host->max_channel = max_channels - 1;
1657                 break;
1658
1659         default:
1660                 host->max_lun = STORVSC_IDE_MAX_LUNS_PER_TARGET;
1661                 host->max_id = STORVSC_IDE_MAX_TARGETS;
1662                 host->max_channel = STORVSC_IDE_MAX_CHANNELS - 1;
1663                 break;
1664         }
1665         /* max cmd length */
1666         host->max_cmd_len = STORVSC_MAX_CMD_LEN;
1667
1668         /*
1669          * set the table size based on the info we got
1670          * from the host.
1671          */
1672         host->sg_tablesize = (stor_device->max_transfer_bytes >> PAGE_SHIFT);
1673
1674         /* Register the HBA and start the scsi bus scan */
1675         ret = scsi_add_host(host, &device->device);
1676         if (ret != 0)
1677                 goto err_out2;
1678
1679         if (!dev_is_ide) {
1680                 scsi_scan_host(host);
1681         } else {
1682                 target = (device->dev_instance.b[5] << 8 |
1683                          device->dev_instance.b[4]);
1684                 ret = scsi_add_device(host, 0, target, 0);
1685                 if (ret) {
1686                         scsi_remove_host(host);
1687                         goto err_out2;
1688                 }
1689         }
1690         return 0;
1691
1692 err_out2:
1693         /*
1694          * Once we have connected with the host, we would need to
1695          * to invoke storvsc_dev_remove() to rollback this state and
1696          * this call also frees up the stor_device; hence the jump around
1697          * err_out1 label.
1698          */
1699         storvsc_dev_remove(device);
1700         goto err_out0;
1701
1702 err_out1:
1703         kfree(stor_device);
1704
1705 err_out0:
1706         scsi_host_put(host);
1707         return ret;
1708 }
1709
1710 static int storvsc_remove(struct hv_device *dev)
1711 {
1712         struct storvsc_device *stor_device = hv_get_drvdata(dev);
1713         struct Scsi_Host *host = stor_device->host;
1714
1715         scsi_remove_host(host);
1716         storvsc_dev_remove(dev);
1717         scsi_host_put(host);
1718
1719         return 0;
1720 }
1721
1722 static struct hv_driver storvsc_drv = {
1723         .name = KBUILD_MODNAME,
1724         .id_table = id_table,
1725         .probe = storvsc_probe,
1726         .remove = storvsc_remove,
1727 };
1728
1729 static int __init storvsc_drv_init(void)
1730 {
1731
1732         /*
1733          * Divide the ring buffer data size (which is 1 page less
1734          * than the ring buffer size since that page is reserved for
1735          * the ring buffer indices) by the max request size (which is
1736          * vmbus_channel_packet_multipage_buffer + struct vstor_packet + u64)
1737          */
1738         max_outstanding_req_per_channel =
1739                 ((storvsc_ringbuffer_size - PAGE_SIZE) /
1740                 ALIGN(MAX_MULTIPAGE_BUFFER_PACKET +
1741                 sizeof(struct vstor_packet) + sizeof(u64) -
1742                 vmscsi_size_delta,
1743                 sizeof(u64)));
1744
1745         return vmbus_driver_register(&storvsc_drv);
1746 }
1747
1748 static void __exit storvsc_drv_exit(void)
1749 {
1750         vmbus_driver_unregister(&storvsc_drv);
1751 }
1752
1753 MODULE_LICENSE("GPL");
1754 MODULE_DESCRIPTION("Microsoft Hyper-V virtual storage driver");
1755 module_init(storvsc_drv_init);
1756 module_exit(storvsc_drv_exit);