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