xref: /linux/drivers/scsi/storvsc_drv.c (revision 288440de9e5fdb4a3ff73864850f080c1250fc81)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (c) 2009, Microsoft Corporation.
4  *
5  * Authors:
6  *   Haiyang Zhang <haiyangz@microsoft.com>
7  *   Hank Janssen  <hjanssen@microsoft.com>
8  *   K. Y. Srinivasan <kys@microsoft.com>
9  */
10 
11 #include <linux/kernel.h>
12 #include <linux/wait.h>
13 #include <linux/sched.h>
14 #include <linux/completion.h>
15 #include <linux/string.h>
16 #include <linux/mm.h>
17 #include <linux/delay.h>
18 #include <linux/init.h>
19 #include <linux/slab.h>
20 #include <linux/module.h>
21 #include <linux/device.h>
22 #include <linux/hyperv.h>
23 #include <linux/blkdev.h>
24 #include <linux/dma-mapping.h>
25 
26 #include <scsi/scsi.h>
27 #include <scsi/scsi_cmnd.h>
28 #include <scsi/scsi_host.h>
29 #include <scsi/scsi_device.h>
30 #include <scsi/scsi_tcq.h>
31 #include <scsi/scsi_eh.h>
32 #include <scsi/scsi_devinfo.h>
33 #include <scsi/scsi_dbg.h>
34 #include <scsi/scsi_transport_fc.h>
35 #include <scsi/scsi_transport.h>
36 
37 /*
38  * All wire protocol details (storage protocol between the guest and the host)
39  * are consolidated here.
40  *
41  * Begin protocol definitions.
42  */
43 
44 /*
45  * Version history:
46  * V1 Beta: 0.1
47  * V1 RC < 2008/1/31: 1.0
48  * V1 RC > 2008/1/31:  2.0
49  * Win7: 4.2
50  * Win8: 5.1
51  * Win8.1: 6.0
52  * Win10: 6.2
53  */
54 
55 #define VMSTOR_PROTO_VERSION(MAJOR_, MINOR_)	((((MAJOR_) & 0xff) << 8) | \
56 						(((MINOR_) & 0xff)))
57 #define VMSTOR_PROTO_VERSION_WIN6	VMSTOR_PROTO_VERSION(2, 0)
58 #define VMSTOR_PROTO_VERSION_WIN7	VMSTOR_PROTO_VERSION(4, 2)
59 #define VMSTOR_PROTO_VERSION_WIN8	VMSTOR_PROTO_VERSION(5, 1)
60 #define VMSTOR_PROTO_VERSION_WIN8_1	VMSTOR_PROTO_VERSION(6, 0)
61 #define VMSTOR_PROTO_VERSION_WIN10	VMSTOR_PROTO_VERSION(6, 2)
62 
63 /*  Packet structure describing virtual storage requests. */
64 enum vstor_packet_operation {
65 	VSTOR_OPERATION_COMPLETE_IO		= 1,
66 	VSTOR_OPERATION_REMOVE_DEVICE		= 2,
67 	VSTOR_OPERATION_EXECUTE_SRB		= 3,
68 	VSTOR_OPERATION_RESET_LUN		= 4,
69 	VSTOR_OPERATION_RESET_ADAPTER		= 5,
70 	VSTOR_OPERATION_RESET_BUS		= 6,
71 	VSTOR_OPERATION_BEGIN_INITIALIZATION	= 7,
72 	VSTOR_OPERATION_END_INITIALIZATION	= 8,
73 	VSTOR_OPERATION_QUERY_PROTOCOL_VERSION	= 9,
74 	VSTOR_OPERATION_QUERY_PROPERTIES	= 10,
75 	VSTOR_OPERATION_ENUMERATE_BUS		= 11,
76 	VSTOR_OPERATION_FCHBA_DATA              = 12,
77 	VSTOR_OPERATION_CREATE_SUB_CHANNELS     = 13,
78 	VSTOR_OPERATION_MAXIMUM                 = 13
79 };
80 
81 /*
82  * WWN packet for Fibre Channel HBA
83  */
84 
85 struct hv_fc_wwn_packet {
86 	u8	primary_active;
87 	u8	reserved1[3];
88 	u8	primary_port_wwn[8];
89 	u8	primary_node_wwn[8];
90 	u8	secondary_port_wwn[8];
91 	u8	secondary_node_wwn[8];
92 };
93 
94 
95 
96 /*
97  * SRB Flag Bits
98  */
99 
100 #define SRB_FLAGS_QUEUE_ACTION_ENABLE		0x00000002
101 #define SRB_FLAGS_DISABLE_DISCONNECT		0x00000004
102 #define SRB_FLAGS_DISABLE_SYNCH_TRANSFER	0x00000008
103 #define SRB_FLAGS_BYPASS_FROZEN_QUEUE		0x00000010
104 #define SRB_FLAGS_DISABLE_AUTOSENSE		0x00000020
105 #define SRB_FLAGS_DATA_IN			0x00000040
106 #define SRB_FLAGS_DATA_OUT			0x00000080
107 #define SRB_FLAGS_NO_DATA_TRANSFER		0x00000000
108 #define SRB_FLAGS_UNSPECIFIED_DIRECTION	(SRB_FLAGS_DATA_IN | SRB_FLAGS_DATA_OUT)
109 #define SRB_FLAGS_NO_QUEUE_FREEZE		0x00000100
110 #define SRB_FLAGS_ADAPTER_CACHE_ENABLE		0x00000200
111 #define SRB_FLAGS_FREE_SENSE_BUFFER		0x00000400
112 
113 /*
114  * This flag indicates the request is part of the workflow for processing a D3.
115  */
116 #define SRB_FLAGS_D3_PROCESSING			0x00000800
117 #define SRB_FLAGS_IS_ACTIVE			0x00010000
118 #define SRB_FLAGS_ALLOCATED_FROM_ZONE		0x00020000
119 #define SRB_FLAGS_SGLIST_FROM_POOL		0x00040000
120 #define SRB_FLAGS_BYPASS_LOCKED_QUEUE		0x00080000
121 #define SRB_FLAGS_NO_KEEP_AWAKE			0x00100000
122 #define SRB_FLAGS_PORT_DRIVER_ALLOCSENSE	0x00200000
123 #define SRB_FLAGS_PORT_DRIVER_SENSEHASPORT	0x00400000
124 #define SRB_FLAGS_DONT_START_NEXT_PACKET	0x00800000
125 #define SRB_FLAGS_PORT_DRIVER_RESERVED		0x0F000000
126 #define SRB_FLAGS_CLASS_DRIVER_RESERVED		0xF0000000
127 
128 #define SP_UNTAGGED			((unsigned char) ~0)
129 #define SRB_SIMPLE_TAG_REQUEST		0x20
130 
131 /*
132  * Platform neutral description of a scsi request -
133  * this remains the same across the write regardless of 32/64 bit
134  * note: it's patterned off the SCSI_PASS_THROUGH structure
135  */
136 #define STORVSC_MAX_CMD_LEN			0x10
137 
138 /* Sense buffer size is the same for all versions since Windows 8 */
139 #define STORVSC_SENSE_BUFFER_SIZE		0x14
140 #define STORVSC_MAX_BUF_LEN_WITH_PADDING	0x14
141 
142 /*
143  * The storage protocol version is determined during the
144  * initial exchange with the host.  It will indicate which
145  * storage functionality is available in the host.
146 */
147 static int vmstor_proto_version;
148 
149 #define STORVSC_LOGGING_NONE	0
150 #define STORVSC_LOGGING_ERROR	1
151 #define STORVSC_LOGGING_WARN	2
152 
153 static int logging_level = STORVSC_LOGGING_ERROR;
154 module_param(logging_level, int, S_IRUGO|S_IWUSR);
155 MODULE_PARM_DESC(logging_level,
156 	"Logging level, 0 - None, 1 - Error (default), 2 - Warning.");
157 
158 static inline bool do_logging(int level)
159 {
160 	return logging_level >= level;
161 }
162 
163 #define storvsc_log(dev, level, fmt, ...)			\
164 do {								\
165 	if (do_logging(level))					\
166 		dev_warn(&(dev)->device, fmt, ##__VA_ARGS__);	\
167 } while (0)
168 
169 struct vmscsi_request {
170 	u16 length;
171 	u8 srb_status;
172 	u8 scsi_status;
173 
174 	u8  port_number;
175 	u8  path_id;
176 	u8  target_id;
177 	u8  lun;
178 
179 	u8  cdb_length;
180 	u8  sense_info_length;
181 	u8  data_in;
182 	u8  reserved;
183 
184 	u32 data_transfer_length;
185 
186 	union {
187 		u8 cdb[STORVSC_MAX_CMD_LEN];
188 		u8 sense_data[STORVSC_SENSE_BUFFER_SIZE];
189 		u8 reserved_array[STORVSC_MAX_BUF_LEN_WITH_PADDING];
190 	};
191 	/*
192 	 * The following was added in win8.
193 	 */
194 	u16 reserve;
195 	u8  queue_tag;
196 	u8  queue_action;
197 	u32 srb_flags;
198 	u32 time_out_value;
199 	u32 queue_sort_ey;
200 
201 } __attribute((packed));
202 
203 /*
204  * The list of windows version in order of preference.
205  */
206 
207 static const int protocol_version[] = {
208 		VMSTOR_PROTO_VERSION_WIN10,
209 		VMSTOR_PROTO_VERSION_WIN8_1,
210 		VMSTOR_PROTO_VERSION_WIN8,
211 };
212 
213 
214 /*
215  * This structure is sent during the initialization phase to get the different
216  * properties of the channel.
217  */
218 
219 #define STORAGE_CHANNEL_SUPPORTS_MULTI_CHANNEL		0x1
220 
221 struct vmstorage_channel_properties {
222 	u32 reserved;
223 	u16 max_channel_cnt;
224 	u16 reserved1;
225 
226 	u32 flags;
227 	u32   max_transfer_bytes;
228 
229 	u64  reserved2;
230 } __packed;
231 
232 /*  This structure is sent during the storage protocol negotiations. */
233 struct vmstorage_protocol_version {
234 	/* Major (MSW) and minor (LSW) version numbers. */
235 	u16 major_minor;
236 
237 	/*
238 	 * Revision number is auto-incremented whenever this file is changed
239 	 * (See FILL_VMSTOR_REVISION macro above).  Mismatch does not
240 	 * definitely indicate incompatibility--but it does indicate mismatched
241 	 * builds.
242 	 * This is only used on the windows side. Just set it to 0.
243 	 */
244 	u16 revision;
245 } __packed;
246 
247 /* Channel Property Flags */
248 #define STORAGE_CHANNEL_REMOVABLE_FLAG		0x1
249 #define STORAGE_CHANNEL_EMULATED_IDE_FLAG	0x2
250 
251 struct vstor_packet {
252 	/* Requested operation type */
253 	enum vstor_packet_operation operation;
254 
255 	/*  Flags - see below for values */
256 	u32 flags;
257 
258 	/* Status of the request returned from the server side. */
259 	u32 status;
260 
261 	/* Data payload area */
262 	union {
263 		/*
264 		 * Structure used to forward SCSI commands from the
265 		 * client to the server.
266 		 */
267 		struct vmscsi_request vm_srb;
268 
269 		/* Structure used to query channel properties. */
270 		struct vmstorage_channel_properties storage_channel_properties;
271 
272 		/* Used during version negotiations. */
273 		struct vmstorage_protocol_version version;
274 
275 		/* Fibre channel address packet */
276 		struct hv_fc_wwn_packet wwn_packet;
277 
278 		/* Number of sub-channels to create */
279 		u16 sub_channel_count;
280 
281 		/* This will be the maximum of the union members */
282 		u8  buffer[0x34];
283 	};
284 } __packed;
285 
286 /*
287  * Packet Flags:
288  *
289  * This flag indicates that the server should send back a completion for this
290  * packet.
291  */
292 
293 #define REQUEST_COMPLETION_FLAG	0x1
294 
295 /* Matches Windows-end */
296 enum storvsc_request_type {
297 	WRITE_TYPE = 0,
298 	READ_TYPE,
299 	UNKNOWN_TYPE,
300 };
301 
302 /*
303  * SRB status codes and masks; a subset of the codes used here.
304  */
305 
306 #define SRB_STATUS_AUTOSENSE_VALID	0x80
307 #define SRB_STATUS_QUEUE_FROZEN		0x40
308 #define SRB_STATUS_INVALID_LUN	0x20
309 #define SRB_STATUS_SUCCESS	0x01
310 #define SRB_STATUS_ABORTED	0x02
311 #define SRB_STATUS_ERROR	0x04
312 #define SRB_STATUS_DATA_OVERRUN	0x12
313 
314 #define SRB_STATUS(status) \
315 	(status & ~(SRB_STATUS_AUTOSENSE_VALID | SRB_STATUS_QUEUE_FROZEN))
316 /*
317  * This is the end of Protocol specific defines.
318  */
319 
320 static int storvsc_ringbuffer_size = (128 * 1024);
321 static u32 max_outstanding_req_per_channel;
322 static int storvsc_change_queue_depth(struct scsi_device *sdev, int queue_depth);
323 
324 static int storvsc_vcpus_per_sub_channel = 4;
325 static unsigned int storvsc_max_hw_queues;
326 
327 module_param(storvsc_ringbuffer_size, int, S_IRUGO);
328 MODULE_PARM_DESC(storvsc_ringbuffer_size, "Ring buffer size (bytes)");
329 
330 module_param(storvsc_max_hw_queues, uint, 0644);
331 MODULE_PARM_DESC(storvsc_max_hw_queues, "Maximum number of hardware queues");
332 
333 module_param(storvsc_vcpus_per_sub_channel, int, S_IRUGO);
334 MODULE_PARM_DESC(storvsc_vcpus_per_sub_channel, "Ratio of VCPUs to subchannels");
335 
336 static int ring_avail_percent_lowater = 10;
337 module_param(ring_avail_percent_lowater, int, S_IRUGO);
338 MODULE_PARM_DESC(ring_avail_percent_lowater,
339 		"Select a channel if available ring size > this in percent");
340 
341 /*
342  * Timeout in seconds for all devices managed by this driver.
343  */
344 static int storvsc_timeout = 180;
345 
346 #if IS_ENABLED(CONFIG_SCSI_FC_ATTRS)
347 static struct scsi_transport_template *fc_transport_template;
348 #endif
349 
350 static struct scsi_host_template scsi_driver;
351 static void storvsc_on_channel_callback(void *context);
352 
353 #define STORVSC_MAX_LUNS_PER_TARGET			255
354 #define STORVSC_MAX_TARGETS				2
355 #define STORVSC_MAX_CHANNELS				8
356 
357 #define STORVSC_FC_MAX_LUNS_PER_TARGET			255
358 #define STORVSC_FC_MAX_TARGETS				128
359 #define STORVSC_FC_MAX_CHANNELS				8
360 
361 #define STORVSC_IDE_MAX_LUNS_PER_TARGET			64
362 #define STORVSC_IDE_MAX_TARGETS				1
363 #define STORVSC_IDE_MAX_CHANNELS			1
364 
365 /*
366  * Upper bound on the size of a storvsc packet.
367  */
368 #define STORVSC_MAX_PKT_SIZE (sizeof(struct vmpacket_descriptor) +\
369 			      sizeof(struct vstor_packet))
370 
371 struct storvsc_cmd_request {
372 	struct scsi_cmnd *cmd;
373 
374 	struct hv_device *device;
375 
376 	/* Synchronize the request/response if needed */
377 	struct completion wait_event;
378 
379 	struct vmbus_channel_packet_multipage_buffer mpb;
380 	struct vmbus_packet_mpb_array *payload;
381 	u32 payload_sz;
382 
383 	struct vstor_packet vstor_packet;
384 };
385 
386 
387 /* A storvsc device is a device object that contains a vmbus channel */
388 struct storvsc_device {
389 	struct hv_device *device;
390 
391 	bool	 destroy;
392 	bool	 drain_notify;
393 	atomic_t num_outstanding_req;
394 	struct Scsi_Host *host;
395 
396 	wait_queue_head_t waiting_to_drain;
397 
398 	/*
399 	 * Each unique Port/Path/Target represents 1 channel ie scsi
400 	 * controller. In reality, the pathid, targetid is always 0
401 	 * and the port is set by us
402 	 */
403 	unsigned int port_number;
404 	unsigned char path_id;
405 	unsigned char target_id;
406 
407 	/*
408 	 * Max I/O, the device can support.
409 	 */
410 	u32   max_transfer_bytes;
411 	/*
412 	 * Number of sub-channels we will open.
413 	 */
414 	u16 num_sc;
415 	struct vmbus_channel **stor_chns;
416 	/*
417 	 * Mask of CPUs bound to subchannels.
418 	 */
419 	struct cpumask alloced_cpus;
420 	/*
421 	 * Serializes modifications of stor_chns[] from storvsc_do_io()
422 	 * and storvsc_change_target_cpu().
423 	 */
424 	spinlock_t lock;
425 	/* Used for vsc/vsp channel reset process */
426 	struct storvsc_cmd_request init_request;
427 	struct storvsc_cmd_request reset_request;
428 	/*
429 	 * Currently active port and node names for FC devices.
430 	 */
431 	u64 node_name;
432 	u64 port_name;
433 #if IS_ENABLED(CONFIG_SCSI_FC_ATTRS)
434 	struct fc_rport *rport;
435 #endif
436 };
437 
438 struct hv_host_device {
439 	struct hv_device *dev;
440 	unsigned int port;
441 	unsigned char path;
442 	unsigned char target;
443 	struct workqueue_struct *handle_error_wq;
444 	struct work_struct host_scan_work;
445 	struct Scsi_Host *host;
446 };
447 
448 struct storvsc_scan_work {
449 	struct work_struct work;
450 	struct Scsi_Host *host;
451 	u8 lun;
452 	u8 tgt_id;
453 };
454 
455 static void storvsc_device_scan(struct work_struct *work)
456 {
457 	struct storvsc_scan_work *wrk;
458 	struct scsi_device *sdev;
459 
460 	wrk = container_of(work, struct storvsc_scan_work, work);
461 
462 	sdev = scsi_device_lookup(wrk->host, 0, wrk->tgt_id, wrk->lun);
463 	if (!sdev)
464 		goto done;
465 	scsi_rescan_device(&sdev->sdev_gendev);
466 	scsi_device_put(sdev);
467 
468 done:
469 	kfree(wrk);
470 }
471 
472 static void storvsc_host_scan(struct work_struct *work)
473 {
474 	struct Scsi_Host *host;
475 	struct scsi_device *sdev;
476 	struct hv_host_device *host_device =
477 		container_of(work, struct hv_host_device, host_scan_work);
478 
479 	host = host_device->host;
480 	/*
481 	 * Before scanning the host, first check to see if any of the
482 	 * currently known devices have been hot removed. We issue a
483 	 * "unit ready" command against all currently known devices.
484 	 * This I/O will result in an error for devices that have been
485 	 * removed. As part of handling the I/O error, we remove the device.
486 	 *
487 	 * When a LUN is added or removed, the host sends us a signal to
488 	 * scan the host. Thus we are forced to discover the LUNs that
489 	 * may have been removed this way.
490 	 */
491 	mutex_lock(&host->scan_mutex);
492 	shost_for_each_device(sdev, host)
493 		scsi_test_unit_ready(sdev, 1, 1, NULL);
494 	mutex_unlock(&host->scan_mutex);
495 	/*
496 	 * Now scan the host to discover LUNs that may have been added.
497 	 */
498 	scsi_scan_host(host);
499 }
500 
501 static void storvsc_remove_lun(struct work_struct *work)
502 {
503 	struct storvsc_scan_work *wrk;
504 	struct scsi_device *sdev;
505 
506 	wrk = container_of(work, struct storvsc_scan_work, work);
507 	if (!scsi_host_get(wrk->host))
508 		goto done;
509 
510 	sdev = scsi_device_lookup(wrk->host, 0, wrk->tgt_id, wrk->lun);
511 
512 	if (sdev) {
513 		scsi_remove_device(sdev);
514 		scsi_device_put(sdev);
515 	}
516 	scsi_host_put(wrk->host);
517 
518 done:
519 	kfree(wrk);
520 }
521 
522 
523 /*
524  * We can get incoming messages from the host that are not in response to
525  * messages that we have sent out. An example of this would be messages
526  * received by the guest to notify dynamic addition/removal of LUNs. To
527  * deal with potential race conditions where the driver may be in the
528  * midst of being unloaded when we might receive an unsolicited message
529  * from the host, we have implemented a mechanism to gurantee sequential
530  * consistency:
531  *
532  * 1) Once the device is marked as being destroyed, we will fail all
533  *    outgoing messages.
534  * 2) We permit incoming messages when the device is being destroyed,
535  *    only to properly account for messages already sent out.
536  */
537 
538 static inline struct storvsc_device *get_out_stor_device(
539 					struct hv_device *device)
540 {
541 	struct storvsc_device *stor_device;
542 
543 	stor_device = hv_get_drvdata(device);
544 
545 	if (stor_device && stor_device->destroy)
546 		stor_device = NULL;
547 
548 	return stor_device;
549 }
550 
551 
552 static inline void storvsc_wait_to_drain(struct storvsc_device *dev)
553 {
554 	dev->drain_notify = true;
555 	wait_event(dev->waiting_to_drain,
556 		   atomic_read(&dev->num_outstanding_req) == 0);
557 	dev->drain_notify = false;
558 }
559 
560 static inline struct storvsc_device *get_in_stor_device(
561 					struct hv_device *device)
562 {
563 	struct storvsc_device *stor_device;
564 
565 	stor_device = hv_get_drvdata(device);
566 
567 	if (!stor_device)
568 		goto get_in_err;
569 
570 	/*
571 	 * If the device is being destroyed; allow incoming
572 	 * traffic only to cleanup outstanding requests.
573 	 */
574 
575 	if (stor_device->destroy  &&
576 		(atomic_read(&stor_device->num_outstanding_req) == 0))
577 		stor_device = NULL;
578 
579 get_in_err:
580 	return stor_device;
581 
582 }
583 
584 static void storvsc_change_target_cpu(struct vmbus_channel *channel, u32 old,
585 				      u32 new)
586 {
587 	struct storvsc_device *stor_device;
588 	struct vmbus_channel *cur_chn;
589 	bool old_is_alloced = false;
590 	struct hv_device *device;
591 	unsigned long flags;
592 	int cpu;
593 
594 	device = channel->primary_channel ?
595 			channel->primary_channel->device_obj
596 				: channel->device_obj;
597 	stor_device = get_out_stor_device(device);
598 	if (!stor_device)
599 		return;
600 
601 	/* See storvsc_do_io() -> get_og_chn(). */
602 	spin_lock_irqsave(&stor_device->lock, flags);
603 
604 	/*
605 	 * Determines if the storvsc device has other channels assigned to
606 	 * the "old" CPU to update the alloced_cpus mask and the stor_chns
607 	 * array.
608 	 */
609 	if (device->channel != channel && device->channel->target_cpu == old) {
610 		cur_chn = device->channel;
611 		old_is_alloced = true;
612 		goto old_is_alloced;
613 	}
614 	list_for_each_entry(cur_chn, &device->channel->sc_list, sc_list) {
615 		if (cur_chn == channel)
616 			continue;
617 		if (cur_chn->target_cpu == old) {
618 			old_is_alloced = true;
619 			goto old_is_alloced;
620 		}
621 	}
622 
623 old_is_alloced:
624 	if (old_is_alloced)
625 		WRITE_ONCE(stor_device->stor_chns[old], cur_chn);
626 	else
627 		cpumask_clear_cpu(old, &stor_device->alloced_cpus);
628 
629 	/* "Flush" the stor_chns array. */
630 	for_each_possible_cpu(cpu) {
631 		if (stor_device->stor_chns[cpu] && !cpumask_test_cpu(
632 					cpu, &stor_device->alloced_cpus))
633 			WRITE_ONCE(stor_device->stor_chns[cpu], NULL);
634 	}
635 
636 	WRITE_ONCE(stor_device->stor_chns[new], channel);
637 	cpumask_set_cpu(new, &stor_device->alloced_cpus);
638 
639 	spin_unlock_irqrestore(&stor_device->lock, flags);
640 }
641 
642 static u64 storvsc_next_request_id(struct vmbus_channel *channel, u64 rqst_addr)
643 {
644 	struct storvsc_cmd_request *request =
645 		(struct storvsc_cmd_request *)(unsigned long)rqst_addr;
646 
647 	if (rqst_addr == VMBUS_RQST_INIT)
648 		return VMBUS_RQST_INIT;
649 	if (rqst_addr == VMBUS_RQST_RESET)
650 		return VMBUS_RQST_RESET;
651 
652 	/*
653 	 * Cannot return an ID of 0, which is reserved for an unsolicited
654 	 * message from Hyper-V.
655 	 */
656 	return (u64)blk_mq_unique_tag(scsi_cmd_to_rq(request->cmd)) + 1;
657 }
658 
659 static void handle_sc_creation(struct vmbus_channel *new_sc)
660 {
661 	struct hv_device *device = new_sc->primary_channel->device_obj;
662 	struct device *dev = &device->device;
663 	struct storvsc_device *stor_device;
664 	struct vmstorage_channel_properties props;
665 	int ret;
666 
667 	stor_device = get_out_stor_device(device);
668 	if (!stor_device)
669 		return;
670 
671 	memset(&props, 0, sizeof(struct vmstorage_channel_properties));
672 	new_sc->max_pkt_size = STORVSC_MAX_PKT_SIZE;
673 
674 	new_sc->next_request_id_callback = storvsc_next_request_id;
675 
676 	ret = vmbus_open(new_sc,
677 			 storvsc_ringbuffer_size,
678 			 storvsc_ringbuffer_size,
679 			 (void *)&props,
680 			 sizeof(struct vmstorage_channel_properties),
681 			 storvsc_on_channel_callback, new_sc);
682 
683 	/* In case vmbus_open() fails, we don't use the sub-channel. */
684 	if (ret != 0) {
685 		dev_err(dev, "Failed to open sub-channel: err=%d\n", ret);
686 		return;
687 	}
688 
689 	new_sc->change_target_cpu_callback = storvsc_change_target_cpu;
690 
691 	/* Add the sub-channel to the array of available channels. */
692 	stor_device->stor_chns[new_sc->target_cpu] = new_sc;
693 	cpumask_set_cpu(new_sc->target_cpu, &stor_device->alloced_cpus);
694 }
695 
696 static void  handle_multichannel_storage(struct hv_device *device, int max_chns)
697 {
698 	struct device *dev = &device->device;
699 	struct storvsc_device *stor_device;
700 	int num_sc;
701 	struct storvsc_cmd_request *request;
702 	struct vstor_packet *vstor_packet;
703 	int ret, t;
704 
705 	/*
706 	 * If the number of CPUs is artificially restricted, such as
707 	 * with maxcpus=1 on the kernel boot line, Hyper-V could offer
708 	 * sub-channels >= the number of CPUs. These sub-channels
709 	 * should not be created. The primary channel is already created
710 	 * and assigned to one CPU, so check against # CPUs - 1.
711 	 */
712 	num_sc = min((int)(num_online_cpus() - 1), max_chns);
713 	if (!num_sc)
714 		return;
715 
716 	stor_device = get_out_stor_device(device);
717 	if (!stor_device)
718 		return;
719 
720 	stor_device->num_sc = num_sc;
721 	request = &stor_device->init_request;
722 	vstor_packet = &request->vstor_packet;
723 
724 	/*
725 	 * Establish a handler for dealing with subchannels.
726 	 */
727 	vmbus_set_sc_create_callback(device->channel, handle_sc_creation);
728 
729 	/*
730 	 * Request the host to create sub-channels.
731 	 */
732 	memset(request, 0, sizeof(struct storvsc_cmd_request));
733 	init_completion(&request->wait_event);
734 	vstor_packet->operation = VSTOR_OPERATION_CREATE_SUB_CHANNELS;
735 	vstor_packet->flags = REQUEST_COMPLETION_FLAG;
736 	vstor_packet->sub_channel_count = num_sc;
737 
738 	ret = vmbus_sendpacket(device->channel, vstor_packet,
739 			       sizeof(struct vstor_packet),
740 			       VMBUS_RQST_INIT,
741 			       VM_PKT_DATA_INBAND,
742 			       VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
743 
744 	if (ret != 0) {
745 		dev_err(dev, "Failed to create sub-channel: err=%d\n", ret);
746 		return;
747 	}
748 
749 	t = wait_for_completion_timeout(&request->wait_event, 10*HZ);
750 	if (t == 0) {
751 		dev_err(dev, "Failed to create sub-channel: timed out\n");
752 		return;
753 	}
754 
755 	if (vstor_packet->operation != VSTOR_OPERATION_COMPLETE_IO ||
756 	    vstor_packet->status != 0) {
757 		dev_err(dev, "Failed to create sub-channel: op=%d, sts=%d\n",
758 			vstor_packet->operation, vstor_packet->status);
759 		return;
760 	}
761 
762 	/*
763 	 * We need to do nothing here, because vmbus_process_offer()
764 	 * invokes channel->sc_creation_callback, which will open and use
765 	 * the sub-channel(s).
766 	 */
767 }
768 
769 static void cache_wwn(struct storvsc_device *stor_device,
770 		      struct vstor_packet *vstor_packet)
771 {
772 	/*
773 	 * Cache the currently active port and node ww names.
774 	 */
775 	if (vstor_packet->wwn_packet.primary_active) {
776 		stor_device->node_name =
777 			wwn_to_u64(vstor_packet->wwn_packet.primary_node_wwn);
778 		stor_device->port_name =
779 			wwn_to_u64(vstor_packet->wwn_packet.primary_port_wwn);
780 	} else {
781 		stor_device->node_name =
782 			wwn_to_u64(vstor_packet->wwn_packet.secondary_node_wwn);
783 		stor_device->port_name =
784 			wwn_to_u64(vstor_packet->wwn_packet.secondary_port_wwn);
785 	}
786 }
787 
788 
789 static int storvsc_execute_vstor_op(struct hv_device *device,
790 				    struct storvsc_cmd_request *request,
791 				    bool status_check)
792 {
793 	struct storvsc_device *stor_device;
794 	struct vstor_packet *vstor_packet;
795 	int ret, t;
796 
797 	stor_device = get_out_stor_device(device);
798 	if (!stor_device)
799 		return -ENODEV;
800 
801 	vstor_packet = &request->vstor_packet;
802 
803 	init_completion(&request->wait_event);
804 	vstor_packet->flags = REQUEST_COMPLETION_FLAG;
805 
806 	ret = vmbus_sendpacket(device->channel, vstor_packet,
807 			       sizeof(struct vstor_packet),
808 			       VMBUS_RQST_INIT,
809 			       VM_PKT_DATA_INBAND,
810 			       VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
811 	if (ret != 0)
812 		return ret;
813 
814 	t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
815 	if (t == 0)
816 		return -ETIMEDOUT;
817 
818 	if (!status_check)
819 		return ret;
820 
821 	if (vstor_packet->operation != VSTOR_OPERATION_COMPLETE_IO ||
822 	    vstor_packet->status != 0)
823 		return -EINVAL;
824 
825 	return ret;
826 }
827 
828 static int storvsc_channel_init(struct hv_device *device, bool is_fc)
829 {
830 	struct storvsc_device *stor_device;
831 	struct storvsc_cmd_request *request;
832 	struct vstor_packet *vstor_packet;
833 	int ret, i;
834 	int max_chns;
835 	bool process_sub_channels = false;
836 
837 	stor_device = get_out_stor_device(device);
838 	if (!stor_device)
839 		return -ENODEV;
840 
841 	request = &stor_device->init_request;
842 	vstor_packet = &request->vstor_packet;
843 
844 	/*
845 	 * Now, initiate the vsc/vsp initialization protocol on the open
846 	 * channel
847 	 */
848 	memset(request, 0, sizeof(struct storvsc_cmd_request));
849 	vstor_packet->operation = VSTOR_OPERATION_BEGIN_INITIALIZATION;
850 	ret = storvsc_execute_vstor_op(device, request, true);
851 	if (ret)
852 		return ret;
853 	/*
854 	 * Query host supported protocol version.
855 	 */
856 
857 	for (i = 0; i < ARRAY_SIZE(protocol_version); i++) {
858 		/* reuse the packet for version range supported */
859 		memset(vstor_packet, 0, sizeof(struct vstor_packet));
860 		vstor_packet->operation =
861 			VSTOR_OPERATION_QUERY_PROTOCOL_VERSION;
862 
863 		vstor_packet->version.major_minor = protocol_version[i];
864 
865 		/*
866 		 * The revision number is only used in Windows; set it to 0.
867 		 */
868 		vstor_packet->version.revision = 0;
869 		ret = storvsc_execute_vstor_op(device, request, false);
870 		if (ret != 0)
871 			return ret;
872 
873 		if (vstor_packet->operation != VSTOR_OPERATION_COMPLETE_IO)
874 			return -EINVAL;
875 
876 		if (vstor_packet->status == 0) {
877 			vmstor_proto_version = protocol_version[i];
878 
879 			break;
880 		}
881 	}
882 
883 	if (vstor_packet->status != 0) {
884 		dev_err(&device->device, "Obsolete Hyper-V version\n");
885 		return -EINVAL;
886 	}
887 
888 
889 	memset(vstor_packet, 0, sizeof(struct vstor_packet));
890 	vstor_packet->operation = VSTOR_OPERATION_QUERY_PROPERTIES;
891 	ret = storvsc_execute_vstor_op(device, request, true);
892 	if (ret != 0)
893 		return ret;
894 
895 	/*
896 	 * Check to see if multi-channel support is there.
897 	 * Hosts that implement protocol version of 5.1 and above
898 	 * support multi-channel.
899 	 */
900 	max_chns = vstor_packet->storage_channel_properties.max_channel_cnt;
901 
902 	/*
903 	 * Allocate state to manage the sub-channels.
904 	 * We allocate an array based on the numbers of possible CPUs
905 	 * (Hyper-V does not support cpu online/offline).
906 	 * This Array will be sparseley populated with unique
907 	 * channels - primary + sub-channels.
908 	 * We will however populate all the slots to evenly distribute
909 	 * the load.
910 	 */
911 	stor_device->stor_chns = kcalloc(num_possible_cpus(), sizeof(void *),
912 					 GFP_KERNEL);
913 	if (stor_device->stor_chns == NULL)
914 		return -ENOMEM;
915 
916 	device->channel->change_target_cpu_callback = storvsc_change_target_cpu;
917 
918 	stor_device->stor_chns[device->channel->target_cpu] = device->channel;
919 	cpumask_set_cpu(device->channel->target_cpu,
920 			&stor_device->alloced_cpus);
921 
922 	if (vstor_packet->storage_channel_properties.flags &
923 	    STORAGE_CHANNEL_SUPPORTS_MULTI_CHANNEL)
924 		process_sub_channels = true;
925 
926 	stor_device->max_transfer_bytes =
927 		vstor_packet->storage_channel_properties.max_transfer_bytes;
928 
929 	if (!is_fc)
930 		goto done;
931 
932 	/*
933 	 * For FC devices retrieve FC HBA data.
934 	 */
935 	memset(vstor_packet, 0, sizeof(struct vstor_packet));
936 	vstor_packet->operation = VSTOR_OPERATION_FCHBA_DATA;
937 	ret = storvsc_execute_vstor_op(device, request, true);
938 	if (ret != 0)
939 		return ret;
940 
941 	/*
942 	 * Cache the currently active port and node ww names.
943 	 */
944 	cache_wwn(stor_device, vstor_packet);
945 
946 done:
947 
948 	memset(vstor_packet, 0, sizeof(struct vstor_packet));
949 	vstor_packet->operation = VSTOR_OPERATION_END_INITIALIZATION;
950 	ret = storvsc_execute_vstor_op(device, request, true);
951 	if (ret != 0)
952 		return ret;
953 
954 	if (process_sub_channels)
955 		handle_multichannel_storage(device, max_chns);
956 
957 	return ret;
958 }
959 
960 static void storvsc_handle_error(struct vmscsi_request *vm_srb,
961 				struct scsi_cmnd *scmnd,
962 				struct Scsi_Host *host,
963 				u8 asc, u8 ascq)
964 {
965 	struct storvsc_scan_work *wrk;
966 	void (*process_err_fn)(struct work_struct *work);
967 	struct hv_host_device *host_dev = shost_priv(host);
968 
969 	/*
970 	 * In some situations, Hyper-V sets multiple bits in the
971 	 * srb_status, such as ABORTED and ERROR. So process them
972 	 * individually, with the most specific bits first.
973 	 */
974 
975 	if (vm_srb->srb_status & SRB_STATUS_INVALID_LUN) {
976 		set_host_byte(scmnd, DID_NO_CONNECT);
977 		process_err_fn = storvsc_remove_lun;
978 		goto do_work;
979 	}
980 
981 	if (vm_srb->srb_status & SRB_STATUS_ABORTED) {
982 		if (vm_srb->srb_status & SRB_STATUS_AUTOSENSE_VALID &&
983 		    /* Capacity data has changed */
984 		    (asc == 0x2a) && (ascq == 0x9)) {
985 			process_err_fn = storvsc_device_scan;
986 			/*
987 			 * Retry the I/O that triggered this.
988 			 */
989 			set_host_byte(scmnd, DID_REQUEUE);
990 			goto do_work;
991 		}
992 	}
993 
994 	if (vm_srb->srb_status & SRB_STATUS_ERROR) {
995 		/*
996 		 * Let upper layer deal with error when
997 		 * sense message is present.
998 		 */
999 		if (vm_srb->srb_status & SRB_STATUS_AUTOSENSE_VALID)
1000 			return;
1001 
1002 		/*
1003 		 * If there is an error; offline the device since all
1004 		 * error recovery strategies would have already been
1005 		 * deployed on the host side. However, if the command
1006 		 * were a pass-through command deal with it appropriately.
1007 		 */
1008 		switch (scmnd->cmnd[0]) {
1009 		case ATA_16:
1010 		case ATA_12:
1011 			set_host_byte(scmnd, DID_PASSTHROUGH);
1012 			break;
1013 		/*
1014 		 * On some Hyper-V hosts TEST_UNIT_READY command can
1015 		 * return SRB_STATUS_ERROR. Let the upper level code
1016 		 * deal with it based on the sense information.
1017 		 */
1018 		case TEST_UNIT_READY:
1019 			break;
1020 		default:
1021 			set_host_byte(scmnd, DID_ERROR);
1022 		}
1023 	}
1024 	return;
1025 
1026 do_work:
1027 	/*
1028 	 * We need to schedule work to process this error; schedule it.
1029 	 */
1030 	wrk = kmalloc(sizeof(struct storvsc_scan_work), GFP_ATOMIC);
1031 	if (!wrk) {
1032 		set_host_byte(scmnd, DID_TARGET_FAILURE);
1033 		return;
1034 	}
1035 
1036 	wrk->host = host;
1037 	wrk->lun = vm_srb->lun;
1038 	wrk->tgt_id = vm_srb->target_id;
1039 	INIT_WORK(&wrk->work, process_err_fn);
1040 	queue_work(host_dev->handle_error_wq, &wrk->work);
1041 }
1042 
1043 
1044 static void storvsc_command_completion(struct storvsc_cmd_request *cmd_request,
1045 				       struct storvsc_device *stor_dev)
1046 {
1047 	struct scsi_cmnd *scmnd = cmd_request->cmd;
1048 	struct scsi_sense_hdr sense_hdr;
1049 	struct vmscsi_request *vm_srb;
1050 	u32 data_transfer_length;
1051 	struct Scsi_Host *host;
1052 	u32 payload_sz = cmd_request->payload_sz;
1053 	void *payload = cmd_request->payload;
1054 	bool sense_ok;
1055 
1056 	host = stor_dev->host;
1057 
1058 	vm_srb = &cmd_request->vstor_packet.vm_srb;
1059 	data_transfer_length = vm_srb->data_transfer_length;
1060 
1061 	scmnd->result = vm_srb->scsi_status;
1062 
1063 	if (scmnd->result) {
1064 		sense_ok = scsi_normalize_sense(scmnd->sense_buffer,
1065 				SCSI_SENSE_BUFFERSIZE, &sense_hdr);
1066 
1067 		if (sense_ok && do_logging(STORVSC_LOGGING_WARN))
1068 			scsi_print_sense_hdr(scmnd->device, "storvsc",
1069 					     &sense_hdr);
1070 	}
1071 
1072 	if (vm_srb->srb_status != SRB_STATUS_SUCCESS) {
1073 		storvsc_handle_error(vm_srb, scmnd, host, sense_hdr.asc,
1074 					 sense_hdr.ascq);
1075 		/*
1076 		 * The Windows driver set data_transfer_length on
1077 		 * SRB_STATUS_DATA_OVERRUN. On other errors, this value
1078 		 * is untouched.  In these cases we set it to 0.
1079 		 */
1080 		if (vm_srb->srb_status != SRB_STATUS_DATA_OVERRUN)
1081 			data_transfer_length = 0;
1082 	}
1083 
1084 	/* Validate data_transfer_length (from Hyper-V) */
1085 	if (data_transfer_length > cmd_request->payload->range.len)
1086 		data_transfer_length = cmd_request->payload->range.len;
1087 
1088 	scsi_set_resid(scmnd,
1089 		cmd_request->payload->range.len - data_transfer_length);
1090 
1091 	scsi_done(scmnd);
1092 
1093 	if (payload_sz >
1094 		sizeof(struct vmbus_channel_packet_multipage_buffer))
1095 		kfree(payload);
1096 }
1097 
1098 static void storvsc_on_io_completion(struct storvsc_device *stor_device,
1099 				  struct vstor_packet *vstor_packet,
1100 				  struct storvsc_cmd_request *request)
1101 {
1102 	struct vstor_packet *stor_pkt;
1103 	struct hv_device *device = stor_device->device;
1104 
1105 	stor_pkt = &request->vstor_packet;
1106 
1107 	/*
1108 	 * The current SCSI handling on the host side does
1109 	 * not correctly handle:
1110 	 * INQUIRY command with page code parameter set to 0x80
1111 	 * MODE_SENSE command with cmd[2] == 0x1c
1112 	 *
1113 	 * Setup srb and scsi status so this won't be fatal.
1114 	 * We do this so we can distinguish truly fatal failues
1115 	 * (srb status == 0x4) and off-line the device in that case.
1116 	 */
1117 
1118 	if ((stor_pkt->vm_srb.cdb[0] == INQUIRY) ||
1119 	   (stor_pkt->vm_srb.cdb[0] == MODE_SENSE)) {
1120 		vstor_packet->vm_srb.scsi_status = 0;
1121 		vstor_packet->vm_srb.srb_status = SRB_STATUS_SUCCESS;
1122 	}
1123 
1124 	/* Copy over the status...etc */
1125 	stor_pkt->vm_srb.scsi_status = vstor_packet->vm_srb.scsi_status;
1126 	stor_pkt->vm_srb.srb_status = vstor_packet->vm_srb.srb_status;
1127 
1128 	/*
1129 	 * Copy over the sense_info_length, but limit to the known max
1130 	 * size if Hyper-V returns a bad value.
1131 	 */
1132 	stor_pkt->vm_srb.sense_info_length = min_t(u8, STORVSC_SENSE_BUFFER_SIZE,
1133 		vstor_packet->vm_srb.sense_info_length);
1134 
1135 	if (vstor_packet->vm_srb.scsi_status != 0 ||
1136 	    vstor_packet->vm_srb.srb_status != SRB_STATUS_SUCCESS) {
1137 
1138 		/*
1139 		 * Log TEST_UNIT_READY errors only as warnings. Hyper-V can
1140 		 * return errors when detecting devices using TEST_UNIT_READY,
1141 		 * and logging these as errors produces unhelpful noise.
1142 		 */
1143 		int loglevel = (stor_pkt->vm_srb.cdb[0] == TEST_UNIT_READY) ?
1144 			STORVSC_LOGGING_WARN : STORVSC_LOGGING_ERROR;
1145 
1146 		storvsc_log(device, loglevel,
1147 			"tag#%d cmd 0x%x status: scsi 0x%x srb 0x%x hv 0x%x\n",
1148 			scsi_cmd_to_rq(request->cmd)->tag,
1149 			stor_pkt->vm_srb.cdb[0],
1150 			vstor_packet->vm_srb.scsi_status,
1151 			vstor_packet->vm_srb.srb_status,
1152 			vstor_packet->status);
1153 	}
1154 
1155 	if (vstor_packet->vm_srb.scsi_status == SAM_STAT_CHECK_CONDITION &&
1156 	    (vstor_packet->vm_srb.srb_status & SRB_STATUS_AUTOSENSE_VALID))
1157 		memcpy(request->cmd->sense_buffer,
1158 		       vstor_packet->vm_srb.sense_data,
1159 		       stor_pkt->vm_srb.sense_info_length);
1160 
1161 	stor_pkt->vm_srb.data_transfer_length =
1162 		vstor_packet->vm_srb.data_transfer_length;
1163 
1164 	storvsc_command_completion(request, stor_device);
1165 
1166 	if (atomic_dec_and_test(&stor_device->num_outstanding_req) &&
1167 		stor_device->drain_notify)
1168 		wake_up(&stor_device->waiting_to_drain);
1169 }
1170 
1171 static void storvsc_on_receive(struct storvsc_device *stor_device,
1172 			     struct vstor_packet *vstor_packet,
1173 			     struct storvsc_cmd_request *request)
1174 {
1175 	struct hv_host_device *host_dev;
1176 	switch (vstor_packet->operation) {
1177 	case VSTOR_OPERATION_COMPLETE_IO:
1178 		storvsc_on_io_completion(stor_device, vstor_packet, request);
1179 		break;
1180 
1181 	case VSTOR_OPERATION_REMOVE_DEVICE:
1182 	case VSTOR_OPERATION_ENUMERATE_BUS:
1183 		host_dev = shost_priv(stor_device->host);
1184 		queue_work(
1185 			host_dev->handle_error_wq, &host_dev->host_scan_work);
1186 		break;
1187 
1188 	case VSTOR_OPERATION_FCHBA_DATA:
1189 		cache_wwn(stor_device, vstor_packet);
1190 #if IS_ENABLED(CONFIG_SCSI_FC_ATTRS)
1191 		fc_host_node_name(stor_device->host) = stor_device->node_name;
1192 		fc_host_port_name(stor_device->host) = stor_device->port_name;
1193 #endif
1194 		break;
1195 	default:
1196 		break;
1197 	}
1198 }
1199 
1200 static void storvsc_on_channel_callback(void *context)
1201 {
1202 	struct vmbus_channel *channel = (struct vmbus_channel *)context;
1203 	const struct vmpacket_descriptor *desc;
1204 	struct hv_device *device;
1205 	struct storvsc_device *stor_device;
1206 	struct Scsi_Host *shost;
1207 
1208 	if (channel->primary_channel != NULL)
1209 		device = channel->primary_channel->device_obj;
1210 	else
1211 		device = channel->device_obj;
1212 
1213 	stor_device = get_in_stor_device(device);
1214 	if (!stor_device)
1215 		return;
1216 
1217 	shost = stor_device->host;
1218 
1219 	foreach_vmbus_pkt(desc, channel) {
1220 		struct vstor_packet *packet = hv_pkt_data(desc);
1221 		struct storvsc_cmd_request *request = NULL;
1222 		u32 pktlen = hv_pkt_datalen(desc);
1223 		u64 rqst_id = desc->trans_id;
1224 		u32 minlen = rqst_id ? sizeof(struct vstor_packet) :
1225 			sizeof(enum vstor_packet_operation);
1226 
1227 		if (pktlen < minlen) {
1228 			dev_err(&device->device,
1229 				"Invalid pkt: id=%llu, len=%u, minlen=%u\n",
1230 				rqst_id, pktlen, minlen);
1231 			continue;
1232 		}
1233 
1234 		if (rqst_id == VMBUS_RQST_INIT) {
1235 			request = &stor_device->init_request;
1236 		} else if (rqst_id == VMBUS_RQST_RESET) {
1237 			request = &stor_device->reset_request;
1238 		} else {
1239 			/* Hyper-V can send an unsolicited message with ID of 0 */
1240 			if (rqst_id == 0) {
1241 				/*
1242 				 * storvsc_on_receive() looks at the vstor_packet in the message
1243 				 * from the ring buffer.
1244 				 *
1245 				 * - If the operation in the vstor_packet is COMPLETE_IO, then
1246 				 *   we call storvsc_on_io_completion(), and dereference the
1247 				 *   guest memory address.  Make sure we don't call
1248 				 *   storvsc_on_io_completion() with a guest memory address
1249 				 *   that is zero if Hyper-V were to construct and send such
1250 				 *   a bogus packet.
1251 				 *
1252 				 * - If the operation in the vstor_packet is FCHBA_DATA, then
1253 				 *   we call cache_wwn(), and access the data payload area of
1254 				 *   the packet (wwn_packet); however, there is no guarantee
1255 				 *   that the packet is big enough to contain such area.
1256 				 *   Future-proof the code by rejecting such a bogus packet.
1257 				 */
1258 				if (packet->operation == VSTOR_OPERATION_COMPLETE_IO ||
1259 				    packet->operation == VSTOR_OPERATION_FCHBA_DATA) {
1260 					dev_err(&device->device, "Invalid packet with ID of 0\n");
1261 					continue;
1262 				}
1263 			} else {
1264 				struct scsi_cmnd *scmnd;
1265 
1266 				/* Transaction 'rqst_id' corresponds to tag 'rqst_id - 1' */
1267 				scmnd = scsi_host_find_tag(shost, rqst_id - 1);
1268 				if (scmnd == NULL) {
1269 					dev_err(&device->device, "Incorrect transaction ID\n");
1270 					continue;
1271 				}
1272 				request = (struct storvsc_cmd_request *)scsi_cmd_priv(scmnd);
1273 				scsi_dma_unmap(scmnd);
1274 			}
1275 
1276 			storvsc_on_receive(stor_device, packet, request);
1277 			continue;
1278 		}
1279 
1280 		memcpy(&request->vstor_packet, packet,
1281 		       sizeof(struct vstor_packet));
1282 		complete(&request->wait_event);
1283 	}
1284 }
1285 
1286 static int storvsc_connect_to_vsp(struct hv_device *device, u32 ring_size,
1287 				  bool is_fc)
1288 {
1289 	struct vmstorage_channel_properties props;
1290 	int ret;
1291 
1292 	memset(&props, 0, sizeof(struct vmstorage_channel_properties));
1293 
1294 	device->channel->max_pkt_size = STORVSC_MAX_PKT_SIZE;
1295 	device->channel->next_request_id_callback = storvsc_next_request_id;
1296 
1297 	ret = vmbus_open(device->channel,
1298 			 ring_size,
1299 			 ring_size,
1300 			 (void *)&props,
1301 			 sizeof(struct vmstorage_channel_properties),
1302 			 storvsc_on_channel_callback, device->channel);
1303 
1304 	if (ret != 0)
1305 		return ret;
1306 
1307 	ret = storvsc_channel_init(device, is_fc);
1308 
1309 	return ret;
1310 }
1311 
1312 static int storvsc_dev_remove(struct hv_device *device)
1313 {
1314 	struct storvsc_device *stor_device;
1315 
1316 	stor_device = hv_get_drvdata(device);
1317 
1318 	stor_device->destroy = true;
1319 
1320 	/* Make sure flag is set before waiting */
1321 	wmb();
1322 
1323 	/*
1324 	 * At this point, all outbound traffic should be disable. We
1325 	 * only allow inbound traffic (responses) to proceed so that
1326 	 * outstanding requests can be completed.
1327 	 */
1328 
1329 	storvsc_wait_to_drain(stor_device);
1330 
1331 	/*
1332 	 * Since we have already drained, we don't need to busy wait
1333 	 * as was done in final_release_stor_device()
1334 	 * Note that we cannot set the ext pointer to NULL until
1335 	 * we have drained - to drain the outgoing packets, we need to
1336 	 * allow incoming packets.
1337 	 */
1338 	hv_set_drvdata(device, NULL);
1339 
1340 	/* Close the channel */
1341 	vmbus_close(device->channel);
1342 
1343 	kfree(stor_device->stor_chns);
1344 	kfree(stor_device);
1345 	return 0;
1346 }
1347 
1348 static struct vmbus_channel *get_og_chn(struct storvsc_device *stor_device,
1349 					u16 q_num)
1350 {
1351 	u16 slot = 0;
1352 	u16 hash_qnum;
1353 	const struct cpumask *node_mask;
1354 	int num_channels, tgt_cpu;
1355 
1356 	if (stor_device->num_sc == 0) {
1357 		stor_device->stor_chns[q_num] = stor_device->device->channel;
1358 		return stor_device->device->channel;
1359 	}
1360 
1361 	/*
1362 	 * Our channel array is sparsley populated and we
1363 	 * initiated I/O on a processor/hw-q that does not
1364 	 * currently have a designated channel. Fix this.
1365 	 * The strategy is simple:
1366 	 * I. Ensure NUMA locality
1367 	 * II. Distribute evenly (best effort)
1368 	 */
1369 
1370 	node_mask = cpumask_of_node(cpu_to_node(q_num));
1371 
1372 	num_channels = 0;
1373 	for_each_cpu(tgt_cpu, &stor_device->alloced_cpus) {
1374 		if (cpumask_test_cpu(tgt_cpu, node_mask))
1375 			num_channels++;
1376 	}
1377 	if (num_channels == 0) {
1378 		stor_device->stor_chns[q_num] = stor_device->device->channel;
1379 		return stor_device->device->channel;
1380 	}
1381 
1382 	hash_qnum = q_num;
1383 	while (hash_qnum >= num_channels)
1384 		hash_qnum -= num_channels;
1385 
1386 	for_each_cpu(tgt_cpu, &stor_device->alloced_cpus) {
1387 		if (!cpumask_test_cpu(tgt_cpu, node_mask))
1388 			continue;
1389 		if (slot == hash_qnum)
1390 			break;
1391 		slot++;
1392 	}
1393 
1394 	stor_device->stor_chns[q_num] = stor_device->stor_chns[tgt_cpu];
1395 
1396 	return stor_device->stor_chns[q_num];
1397 }
1398 
1399 
1400 static int storvsc_do_io(struct hv_device *device,
1401 			 struct storvsc_cmd_request *request, u16 q_num)
1402 {
1403 	struct storvsc_device *stor_device;
1404 	struct vstor_packet *vstor_packet;
1405 	struct vmbus_channel *outgoing_channel, *channel;
1406 	unsigned long flags;
1407 	int ret = 0;
1408 	const struct cpumask *node_mask;
1409 	int tgt_cpu;
1410 
1411 	vstor_packet = &request->vstor_packet;
1412 	stor_device = get_out_stor_device(device);
1413 
1414 	if (!stor_device)
1415 		return -ENODEV;
1416 
1417 
1418 	request->device  = device;
1419 	/*
1420 	 * Select an appropriate channel to send the request out.
1421 	 */
1422 	/* See storvsc_change_target_cpu(). */
1423 	outgoing_channel = READ_ONCE(stor_device->stor_chns[q_num]);
1424 	if (outgoing_channel != NULL) {
1425 		if (outgoing_channel->target_cpu == q_num) {
1426 			/*
1427 			 * Ideally, we want to pick a different channel if
1428 			 * available on the same NUMA node.
1429 			 */
1430 			node_mask = cpumask_of_node(cpu_to_node(q_num));
1431 			for_each_cpu_wrap(tgt_cpu,
1432 				 &stor_device->alloced_cpus, q_num + 1) {
1433 				if (!cpumask_test_cpu(tgt_cpu, node_mask))
1434 					continue;
1435 				if (tgt_cpu == q_num)
1436 					continue;
1437 				channel = READ_ONCE(
1438 					stor_device->stor_chns[tgt_cpu]);
1439 				if (channel == NULL)
1440 					continue;
1441 				if (hv_get_avail_to_write_percent(
1442 							&channel->outbound)
1443 						> ring_avail_percent_lowater) {
1444 					outgoing_channel = channel;
1445 					goto found_channel;
1446 				}
1447 			}
1448 
1449 			/*
1450 			 * All the other channels on the same NUMA node are
1451 			 * busy. Try to use the channel on the current CPU
1452 			 */
1453 			if (hv_get_avail_to_write_percent(
1454 						&outgoing_channel->outbound)
1455 					> ring_avail_percent_lowater)
1456 				goto found_channel;
1457 
1458 			/*
1459 			 * If we reach here, all the channels on the current
1460 			 * NUMA node are busy. Try to find a channel in
1461 			 * other NUMA nodes
1462 			 */
1463 			for_each_cpu(tgt_cpu, &stor_device->alloced_cpus) {
1464 				if (cpumask_test_cpu(tgt_cpu, node_mask))
1465 					continue;
1466 				channel = READ_ONCE(
1467 					stor_device->stor_chns[tgt_cpu]);
1468 				if (channel == NULL)
1469 					continue;
1470 				if (hv_get_avail_to_write_percent(
1471 							&channel->outbound)
1472 						> ring_avail_percent_lowater) {
1473 					outgoing_channel = channel;
1474 					goto found_channel;
1475 				}
1476 			}
1477 		}
1478 	} else {
1479 		spin_lock_irqsave(&stor_device->lock, flags);
1480 		outgoing_channel = stor_device->stor_chns[q_num];
1481 		if (outgoing_channel != NULL) {
1482 			spin_unlock_irqrestore(&stor_device->lock, flags);
1483 			goto found_channel;
1484 		}
1485 		outgoing_channel = get_og_chn(stor_device, q_num);
1486 		spin_unlock_irqrestore(&stor_device->lock, flags);
1487 	}
1488 
1489 found_channel:
1490 	vstor_packet->flags |= REQUEST_COMPLETION_FLAG;
1491 
1492 	vstor_packet->vm_srb.length = sizeof(struct vmscsi_request);
1493 
1494 
1495 	vstor_packet->vm_srb.sense_info_length = STORVSC_SENSE_BUFFER_SIZE;
1496 
1497 
1498 	vstor_packet->vm_srb.data_transfer_length =
1499 	request->payload->range.len;
1500 
1501 	vstor_packet->operation = VSTOR_OPERATION_EXECUTE_SRB;
1502 
1503 	if (request->payload->range.len) {
1504 
1505 		ret = vmbus_sendpacket_mpb_desc(outgoing_channel,
1506 				request->payload, request->payload_sz,
1507 				vstor_packet,
1508 				sizeof(struct vstor_packet),
1509 				(unsigned long)request);
1510 	} else {
1511 		ret = vmbus_sendpacket(outgoing_channel, vstor_packet,
1512 			       sizeof(struct vstor_packet),
1513 			       (unsigned long)request,
1514 			       VM_PKT_DATA_INBAND,
1515 			       VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1516 	}
1517 
1518 	if (ret != 0)
1519 		return ret;
1520 
1521 	atomic_inc(&stor_device->num_outstanding_req);
1522 
1523 	return ret;
1524 }
1525 
1526 static int storvsc_device_alloc(struct scsi_device *sdevice)
1527 {
1528 	/*
1529 	 * Set blist flag to permit the reading of the VPD pages even when
1530 	 * the target may claim SPC-2 compliance. MSFT targets currently
1531 	 * claim SPC-2 compliance while they implement post SPC-2 features.
1532 	 * With this flag we can correctly handle WRITE_SAME_16 issues.
1533 	 *
1534 	 * Hypervisor reports SCSI_UNKNOWN type for DVD ROM device but
1535 	 * still supports REPORT LUN.
1536 	 */
1537 	sdevice->sdev_bflags = BLIST_REPORTLUN2 | BLIST_TRY_VPD_PAGES;
1538 
1539 	return 0;
1540 }
1541 
1542 static int storvsc_device_configure(struct scsi_device *sdevice)
1543 {
1544 	blk_queue_rq_timeout(sdevice->request_queue, (storvsc_timeout * HZ));
1545 
1546 	sdevice->no_write_same = 1;
1547 
1548 	/*
1549 	 * If the host is WIN8 or WIN8 R2, claim conformance to SPC-3
1550 	 * if the device is a MSFT virtual device.  If the host is
1551 	 * WIN10 or newer, allow write_same.
1552 	 */
1553 	if (!strncmp(sdevice->vendor, "Msft", 4)) {
1554 		switch (vmstor_proto_version) {
1555 		case VMSTOR_PROTO_VERSION_WIN8:
1556 		case VMSTOR_PROTO_VERSION_WIN8_1:
1557 			sdevice->scsi_level = SCSI_SPC_3;
1558 			break;
1559 		}
1560 
1561 		if (vmstor_proto_version >= VMSTOR_PROTO_VERSION_WIN10)
1562 			sdevice->no_write_same = 0;
1563 	}
1564 
1565 	return 0;
1566 }
1567 
1568 static int storvsc_get_chs(struct scsi_device *sdev, struct block_device * bdev,
1569 			   sector_t capacity, int *info)
1570 {
1571 	sector_t nsect = capacity;
1572 	sector_t cylinders = nsect;
1573 	int heads, sectors_pt;
1574 
1575 	/*
1576 	 * We are making up these values; let us keep it simple.
1577 	 */
1578 	heads = 0xff;
1579 	sectors_pt = 0x3f;      /* Sectors per track */
1580 	sector_div(cylinders, heads * sectors_pt);
1581 	if ((sector_t)(cylinders + 1) * heads * sectors_pt < nsect)
1582 		cylinders = 0xffff;
1583 
1584 	info[0] = heads;
1585 	info[1] = sectors_pt;
1586 	info[2] = (int)cylinders;
1587 
1588 	return 0;
1589 }
1590 
1591 static int storvsc_host_reset_handler(struct scsi_cmnd *scmnd)
1592 {
1593 	struct hv_host_device *host_dev = shost_priv(scmnd->device->host);
1594 	struct hv_device *device = host_dev->dev;
1595 
1596 	struct storvsc_device *stor_device;
1597 	struct storvsc_cmd_request *request;
1598 	struct vstor_packet *vstor_packet;
1599 	int ret, t;
1600 
1601 	stor_device = get_out_stor_device(device);
1602 	if (!stor_device)
1603 		return FAILED;
1604 
1605 	request = &stor_device->reset_request;
1606 	vstor_packet = &request->vstor_packet;
1607 	memset(vstor_packet, 0, sizeof(struct vstor_packet));
1608 
1609 	init_completion(&request->wait_event);
1610 
1611 	vstor_packet->operation = VSTOR_OPERATION_RESET_BUS;
1612 	vstor_packet->flags = REQUEST_COMPLETION_FLAG;
1613 	vstor_packet->vm_srb.path_id = stor_device->path_id;
1614 
1615 	ret = vmbus_sendpacket(device->channel, vstor_packet,
1616 			       sizeof(struct vstor_packet),
1617 			       VMBUS_RQST_RESET,
1618 			       VM_PKT_DATA_INBAND,
1619 			       VMBUS_DATA_PACKET_FLAG_COMPLETION_REQUESTED);
1620 	if (ret != 0)
1621 		return FAILED;
1622 
1623 	t = wait_for_completion_timeout(&request->wait_event, 5*HZ);
1624 	if (t == 0)
1625 		return TIMEOUT_ERROR;
1626 
1627 
1628 	/*
1629 	 * At this point, all outstanding requests in the adapter
1630 	 * should have been flushed out and return to us
1631 	 * There is a potential race here where the host may be in
1632 	 * the process of responding when we return from here.
1633 	 * Just wait for all in-transit packets to be accounted for
1634 	 * before we return from here.
1635 	 */
1636 	storvsc_wait_to_drain(stor_device);
1637 
1638 	return SUCCESS;
1639 }
1640 
1641 /*
1642  * The host guarantees to respond to each command, although I/O latencies might
1643  * be unbounded on Azure.  Reset the timer unconditionally to give the host a
1644  * chance to perform EH.
1645  */
1646 static enum blk_eh_timer_return storvsc_eh_timed_out(struct scsi_cmnd *scmnd)
1647 {
1648 #if IS_ENABLED(CONFIG_SCSI_FC_ATTRS)
1649 	if (scmnd->device->host->transportt == fc_transport_template)
1650 		return fc_eh_timed_out(scmnd);
1651 #endif
1652 	return BLK_EH_RESET_TIMER;
1653 }
1654 
1655 static bool storvsc_scsi_cmd_ok(struct scsi_cmnd *scmnd)
1656 {
1657 	bool allowed = true;
1658 	u8 scsi_op = scmnd->cmnd[0];
1659 
1660 	switch (scsi_op) {
1661 	/* the host does not handle WRITE_SAME, log accident usage */
1662 	case WRITE_SAME:
1663 	/*
1664 	 * smartd sends this command and the host does not handle
1665 	 * this. So, don't send it.
1666 	 */
1667 	case SET_WINDOW:
1668 		set_host_byte(scmnd, DID_ERROR);
1669 		allowed = false;
1670 		break;
1671 	default:
1672 		break;
1673 	}
1674 	return allowed;
1675 }
1676 
1677 static int storvsc_queuecommand(struct Scsi_Host *host, struct scsi_cmnd *scmnd)
1678 {
1679 	int ret;
1680 	struct hv_host_device *host_dev = shost_priv(host);
1681 	struct hv_device *dev = host_dev->dev;
1682 	struct storvsc_cmd_request *cmd_request = scsi_cmd_priv(scmnd);
1683 	struct scatterlist *sgl;
1684 	struct vmscsi_request *vm_srb;
1685 	struct vmbus_packet_mpb_array  *payload;
1686 	u32 payload_sz;
1687 	u32 length;
1688 
1689 	if (vmstor_proto_version <= VMSTOR_PROTO_VERSION_WIN8) {
1690 		/*
1691 		 * On legacy hosts filter unimplemented commands.
1692 		 * Future hosts are expected to correctly handle
1693 		 * unsupported commands. Furthermore, it is
1694 		 * possible that some of the currently
1695 		 * unsupported commands maybe supported in
1696 		 * future versions of the host.
1697 		 */
1698 		if (!storvsc_scsi_cmd_ok(scmnd)) {
1699 			scsi_done(scmnd);
1700 			return 0;
1701 		}
1702 	}
1703 
1704 	/* Setup the cmd request */
1705 	cmd_request->cmd = scmnd;
1706 
1707 	memset(&cmd_request->vstor_packet, 0, sizeof(struct vstor_packet));
1708 	vm_srb = &cmd_request->vstor_packet.vm_srb;
1709 	vm_srb->time_out_value = 60;
1710 
1711 	vm_srb->srb_flags |=
1712 		SRB_FLAGS_DISABLE_SYNCH_TRANSFER;
1713 
1714 	if (scmnd->device->tagged_supported) {
1715 		vm_srb->srb_flags |=
1716 		(SRB_FLAGS_QUEUE_ACTION_ENABLE | SRB_FLAGS_NO_QUEUE_FREEZE);
1717 		vm_srb->queue_tag = SP_UNTAGGED;
1718 		vm_srb->queue_action = SRB_SIMPLE_TAG_REQUEST;
1719 	}
1720 
1721 	/* Build the SRB */
1722 	switch (scmnd->sc_data_direction) {
1723 	case DMA_TO_DEVICE:
1724 		vm_srb->data_in = WRITE_TYPE;
1725 		vm_srb->srb_flags |= SRB_FLAGS_DATA_OUT;
1726 		break;
1727 	case DMA_FROM_DEVICE:
1728 		vm_srb->data_in = READ_TYPE;
1729 		vm_srb->srb_flags |= SRB_FLAGS_DATA_IN;
1730 		break;
1731 	case DMA_NONE:
1732 		vm_srb->data_in = UNKNOWN_TYPE;
1733 		vm_srb->srb_flags |= SRB_FLAGS_NO_DATA_TRANSFER;
1734 		break;
1735 	default:
1736 		/*
1737 		 * This is DMA_BIDIRECTIONAL or something else we are never
1738 		 * supposed to see here.
1739 		 */
1740 		WARN(1, "Unexpected data direction: %d\n",
1741 		     scmnd->sc_data_direction);
1742 		return -EINVAL;
1743 	}
1744 
1745 
1746 	vm_srb->port_number = host_dev->port;
1747 	vm_srb->path_id = scmnd->device->channel;
1748 	vm_srb->target_id = scmnd->device->id;
1749 	vm_srb->lun = scmnd->device->lun;
1750 
1751 	vm_srb->cdb_length = scmnd->cmd_len;
1752 
1753 	memcpy(vm_srb->cdb, scmnd->cmnd, vm_srb->cdb_length);
1754 
1755 	sgl = (struct scatterlist *)scsi_sglist(scmnd);
1756 
1757 	length = scsi_bufflen(scmnd);
1758 	payload = (struct vmbus_packet_mpb_array *)&cmd_request->mpb;
1759 	payload_sz = sizeof(cmd_request->mpb);
1760 
1761 	if (scsi_sg_count(scmnd)) {
1762 		unsigned long offset_in_hvpg = offset_in_hvpage(sgl->offset);
1763 		unsigned int hvpg_count = HVPFN_UP(offset_in_hvpg + length);
1764 		struct scatterlist *sg;
1765 		unsigned long hvpfn, hvpfns_to_add;
1766 		int j, i = 0, sg_count;
1767 
1768 		if (hvpg_count > MAX_PAGE_BUFFER_COUNT) {
1769 
1770 			payload_sz = (hvpg_count * sizeof(u64) +
1771 				      sizeof(struct vmbus_packet_mpb_array));
1772 			payload = kzalloc(payload_sz, GFP_ATOMIC);
1773 			if (!payload)
1774 				return SCSI_MLQUEUE_DEVICE_BUSY;
1775 		}
1776 
1777 		payload->range.len = length;
1778 		payload->range.offset = offset_in_hvpg;
1779 
1780 		sg_count = scsi_dma_map(scmnd);
1781 		if (sg_count < 0) {
1782 			ret = SCSI_MLQUEUE_DEVICE_BUSY;
1783 			goto err_free_payload;
1784 		}
1785 
1786 		for_each_sg(sgl, sg, sg_count, j) {
1787 			/*
1788 			 * Init values for the current sgl entry. hvpfns_to_add
1789 			 * is in units of Hyper-V size pages. Handling the
1790 			 * PAGE_SIZE != HV_HYP_PAGE_SIZE case also handles
1791 			 * values of sgl->offset that are larger than PAGE_SIZE.
1792 			 * Such offsets are handled even on other than the first
1793 			 * sgl entry, provided they are a multiple of PAGE_SIZE.
1794 			 */
1795 			hvpfn = HVPFN_DOWN(sg_dma_address(sg));
1796 			hvpfns_to_add = HVPFN_UP(sg_dma_address(sg) +
1797 						 sg_dma_len(sg)) - hvpfn;
1798 
1799 			/*
1800 			 * Fill the next portion of the PFN array with
1801 			 * sequential Hyper-V PFNs for the continguous physical
1802 			 * memory described by the sgl entry. The end of the
1803 			 * last sgl should be reached at the same time that
1804 			 * the PFN array is filled.
1805 			 */
1806 			while (hvpfns_to_add--)
1807 				payload->range.pfn_array[i++] = hvpfn++;
1808 		}
1809 	}
1810 
1811 	cmd_request->payload = payload;
1812 	cmd_request->payload_sz = payload_sz;
1813 
1814 	/* Invokes the vsc to start an IO */
1815 	ret = storvsc_do_io(dev, cmd_request, get_cpu());
1816 	put_cpu();
1817 
1818 	if (ret == -EAGAIN) {
1819 		/* no more space */
1820 		ret = SCSI_MLQUEUE_DEVICE_BUSY;
1821 		goto err_free_payload;
1822 	}
1823 
1824 	return 0;
1825 
1826 err_free_payload:
1827 	if (payload_sz > sizeof(cmd_request->mpb))
1828 		kfree(payload);
1829 
1830 	return ret;
1831 }
1832 
1833 static struct scsi_host_template scsi_driver = {
1834 	.module	=		THIS_MODULE,
1835 	.name =			"storvsc_host_t",
1836 	.cmd_size =             sizeof(struct storvsc_cmd_request),
1837 	.bios_param =		storvsc_get_chs,
1838 	.queuecommand =		storvsc_queuecommand,
1839 	.eh_host_reset_handler =	storvsc_host_reset_handler,
1840 	.proc_name =		"storvsc_host",
1841 	.eh_timed_out =		storvsc_eh_timed_out,
1842 	.slave_alloc =		storvsc_device_alloc,
1843 	.slave_configure =	storvsc_device_configure,
1844 	.cmd_per_lun =		2048,
1845 	.this_id =		-1,
1846 	/* Ensure there are no gaps in presented sgls */
1847 	.virt_boundary_mask =	HV_HYP_PAGE_SIZE - 1,
1848 	.no_write_same =	1,
1849 	.track_queue_depth =	1,
1850 	.change_queue_depth =	storvsc_change_queue_depth,
1851 };
1852 
1853 enum {
1854 	SCSI_GUID,
1855 	IDE_GUID,
1856 	SFC_GUID,
1857 };
1858 
1859 static const struct hv_vmbus_device_id id_table[] = {
1860 	/* SCSI guid */
1861 	{ HV_SCSI_GUID,
1862 	  .driver_data = SCSI_GUID
1863 	},
1864 	/* IDE guid */
1865 	{ HV_IDE_GUID,
1866 	  .driver_data = IDE_GUID
1867 	},
1868 	/* Fibre Channel GUID */
1869 	{
1870 	  HV_SYNTHFC_GUID,
1871 	  .driver_data = SFC_GUID
1872 	},
1873 	{ },
1874 };
1875 
1876 MODULE_DEVICE_TABLE(vmbus, id_table);
1877 
1878 static const struct { guid_t guid; } fc_guid = { HV_SYNTHFC_GUID };
1879 
1880 static bool hv_dev_is_fc(struct hv_device *hv_dev)
1881 {
1882 	return guid_equal(&fc_guid.guid, &hv_dev->dev_type);
1883 }
1884 
1885 static int storvsc_probe(struct hv_device *device,
1886 			const struct hv_vmbus_device_id *dev_id)
1887 {
1888 	int ret;
1889 	int num_cpus = num_online_cpus();
1890 	int num_present_cpus = num_present_cpus();
1891 	struct Scsi_Host *host;
1892 	struct hv_host_device *host_dev;
1893 	bool dev_is_ide = ((dev_id->driver_data == IDE_GUID) ? true : false);
1894 	bool is_fc = ((dev_id->driver_data == SFC_GUID) ? true : false);
1895 	int target = 0;
1896 	struct storvsc_device *stor_device;
1897 	int max_sub_channels = 0;
1898 	u32 max_xfer_bytes;
1899 
1900 	/*
1901 	 * We support sub-channels for storage on SCSI and FC controllers.
1902 	 * The number of sub-channels offerred is based on the number of
1903 	 * VCPUs in the guest.
1904 	 */
1905 	if (!dev_is_ide)
1906 		max_sub_channels =
1907 			(num_cpus - 1) / storvsc_vcpus_per_sub_channel;
1908 
1909 	scsi_driver.can_queue = max_outstanding_req_per_channel *
1910 				(max_sub_channels + 1) *
1911 				(100 - ring_avail_percent_lowater) / 100;
1912 
1913 	host = scsi_host_alloc(&scsi_driver,
1914 			       sizeof(struct hv_host_device));
1915 	if (!host)
1916 		return -ENOMEM;
1917 
1918 	host_dev = shost_priv(host);
1919 	memset(host_dev, 0, sizeof(struct hv_host_device));
1920 
1921 	host_dev->port = host->host_no;
1922 	host_dev->dev = device;
1923 	host_dev->host = host;
1924 
1925 
1926 	stor_device = kzalloc(sizeof(struct storvsc_device), GFP_KERNEL);
1927 	if (!stor_device) {
1928 		ret = -ENOMEM;
1929 		goto err_out0;
1930 	}
1931 
1932 	stor_device->destroy = false;
1933 	init_waitqueue_head(&stor_device->waiting_to_drain);
1934 	stor_device->device = device;
1935 	stor_device->host = host;
1936 	spin_lock_init(&stor_device->lock);
1937 	hv_set_drvdata(device, stor_device);
1938 	dma_set_min_align_mask(&device->device, HV_HYP_PAGE_SIZE - 1);
1939 
1940 	stor_device->port_number = host->host_no;
1941 	ret = storvsc_connect_to_vsp(device, storvsc_ringbuffer_size, is_fc);
1942 	if (ret)
1943 		goto err_out1;
1944 
1945 	host_dev->path = stor_device->path_id;
1946 	host_dev->target = stor_device->target_id;
1947 
1948 	switch (dev_id->driver_data) {
1949 	case SFC_GUID:
1950 		host->max_lun = STORVSC_FC_MAX_LUNS_PER_TARGET;
1951 		host->max_id = STORVSC_FC_MAX_TARGETS;
1952 		host->max_channel = STORVSC_FC_MAX_CHANNELS - 1;
1953 #if IS_ENABLED(CONFIG_SCSI_FC_ATTRS)
1954 		host->transportt = fc_transport_template;
1955 #endif
1956 		break;
1957 
1958 	case SCSI_GUID:
1959 		host->max_lun = STORVSC_MAX_LUNS_PER_TARGET;
1960 		host->max_id = STORVSC_MAX_TARGETS;
1961 		host->max_channel = STORVSC_MAX_CHANNELS - 1;
1962 		break;
1963 
1964 	default:
1965 		host->max_lun = STORVSC_IDE_MAX_LUNS_PER_TARGET;
1966 		host->max_id = STORVSC_IDE_MAX_TARGETS;
1967 		host->max_channel = STORVSC_IDE_MAX_CHANNELS - 1;
1968 		break;
1969 	}
1970 	/* max cmd length */
1971 	host->max_cmd_len = STORVSC_MAX_CMD_LEN;
1972 	/*
1973 	 * Any reasonable Hyper-V configuration should provide
1974 	 * max_transfer_bytes value aligning to HV_HYP_PAGE_SIZE,
1975 	 * protecting it from any weird value.
1976 	 */
1977 	max_xfer_bytes = round_down(stor_device->max_transfer_bytes, HV_HYP_PAGE_SIZE);
1978 	/* max_hw_sectors_kb */
1979 	host->max_sectors = max_xfer_bytes >> 9;
1980 	/*
1981 	 * There are 2 requirements for Hyper-V storvsc sgl segments,
1982 	 * based on which the below calculation for max segments is
1983 	 * done:
1984 	 *
1985 	 * 1. Except for the first and last sgl segment, all sgl segments
1986 	 *    should be align to HV_HYP_PAGE_SIZE, that also means the
1987 	 *    maximum number of segments in a sgl can be calculated by
1988 	 *    dividing the total max transfer length by HV_HYP_PAGE_SIZE.
1989 	 *
1990 	 * 2. Except for the first and last, each entry in the SGL must
1991 	 *    have an offset that is a multiple of HV_HYP_PAGE_SIZE.
1992 	 */
1993 	host->sg_tablesize = (max_xfer_bytes >> HV_HYP_PAGE_SHIFT) + 1;
1994 	/*
1995 	 * For non-IDE disks, the host supports multiple channels.
1996 	 * Set the number of HW queues we are supporting.
1997 	 */
1998 	if (!dev_is_ide) {
1999 		if (storvsc_max_hw_queues > num_present_cpus) {
2000 			storvsc_max_hw_queues = 0;
2001 			storvsc_log(device, STORVSC_LOGGING_WARN,
2002 				"Resetting invalid storvsc_max_hw_queues value to default.\n");
2003 		}
2004 		if (storvsc_max_hw_queues)
2005 			host->nr_hw_queues = storvsc_max_hw_queues;
2006 		else
2007 			host->nr_hw_queues = num_present_cpus;
2008 	}
2009 
2010 	/*
2011 	 * Set the error handler work queue.
2012 	 */
2013 	host_dev->handle_error_wq =
2014 			alloc_ordered_workqueue("storvsc_error_wq_%d",
2015 						WQ_MEM_RECLAIM,
2016 						host->host_no);
2017 	if (!host_dev->handle_error_wq) {
2018 		ret = -ENOMEM;
2019 		goto err_out2;
2020 	}
2021 	INIT_WORK(&host_dev->host_scan_work, storvsc_host_scan);
2022 	/* Register the HBA and start the scsi bus scan */
2023 	ret = scsi_add_host(host, &device->device);
2024 	if (ret != 0)
2025 		goto err_out3;
2026 
2027 	if (!dev_is_ide) {
2028 		scsi_scan_host(host);
2029 	} else {
2030 		target = (device->dev_instance.b[5] << 8 |
2031 			 device->dev_instance.b[4]);
2032 		ret = scsi_add_device(host, 0, target, 0);
2033 		if (ret)
2034 			goto err_out4;
2035 	}
2036 #if IS_ENABLED(CONFIG_SCSI_FC_ATTRS)
2037 	if (host->transportt == fc_transport_template) {
2038 		struct fc_rport_identifiers ids = {
2039 			.roles = FC_PORT_ROLE_FCP_DUMMY_INITIATOR,
2040 		};
2041 
2042 		fc_host_node_name(host) = stor_device->node_name;
2043 		fc_host_port_name(host) = stor_device->port_name;
2044 		stor_device->rport = fc_remote_port_add(host, 0, &ids);
2045 		if (!stor_device->rport) {
2046 			ret = -ENOMEM;
2047 			goto err_out4;
2048 		}
2049 	}
2050 #endif
2051 	return 0;
2052 
2053 err_out4:
2054 	scsi_remove_host(host);
2055 
2056 err_out3:
2057 	destroy_workqueue(host_dev->handle_error_wq);
2058 
2059 err_out2:
2060 	/*
2061 	 * Once we have connected with the host, we would need to
2062 	 * to invoke storvsc_dev_remove() to rollback this state and
2063 	 * this call also frees up the stor_device; hence the jump around
2064 	 * err_out1 label.
2065 	 */
2066 	storvsc_dev_remove(device);
2067 	goto err_out0;
2068 
2069 err_out1:
2070 	kfree(stor_device->stor_chns);
2071 	kfree(stor_device);
2072 
2073 err_out0:
2074 	scsi_host_put(host);
2075 	return ret;
2076 }
2077 
2078 /* Change a scsi target's queue depth */
2079 static int storvsc_change_queue_depth(struct scsi_device *sdev, int queue_depth)
2080 {
2081 	if (queue_depth > scsi_driver.can_queue)
2082 		queue_depth = scsi_driver.can_queue;
2083 
2084 	return scsi_change_queue_depth(sdev, queue_depth);
2085 }
2086 
2087 static int storvsc_remove(struct hv_device *dev)
2088 {
2089 	struct storvsc_device *stor_device = hv_get_drvdata(dev);
2090 	struct Scsi_Host *host = stor_device->host;
2091 	struct hv_host_device *host_dev = shost_priv(host);
2092 
2093 #if IS_ENABLED(CONFIG_SCSI_FC_ATTRS)
2094 	if (host->transportt == fc_transport_template) {
2095 		fc_remote_port_delete(stor_device->rport);
2096 		fc_remove_host(host);
2097 	}
2098 #endif
2099 	destroy_workqueue(host_dev->handle_error_wq);
2100 	scsi_remove_host(host);
2101 	storvsc_dev_remove(dev);
2102 	scsi_host_put(host);
2103 
2104 	return 0;
2105 }
2106 
2107 static int storvsc_suspend(struct hv_device *hv_dev)
2108 {
2109 	struct storvsc_device *stor_device = hv_get_drvdata(hv_dev);
2110 	struct Scsi_Host *host = stor_device->host;
2111 	struct hv_host_device *host_dev = shost_priv(host);
2112 
2113 	storvsc_wait_to_drain(stor_device);
2114 
2115 	drain_workqueue(host_dev->handle_error_wq);
2116 
2117 	vmbus_close(hv_dev->channel);
2118 
2119 	kfree(stor_device->stor_chns);
2120 	stor_device->stor_chns = NULL;
2121 
2122 	cpumask_clear(&stor_device->alloced_cpus);
2123 
2124 	return 0;
2125 }
2126 
2127 static int storvsc_resume(struct hv_device *hv_dev)
2128 {
2129 	int ret;
2130 
2131 	ret = storvsc_connect_to_vsp(hv_dev, storvsc_ringbuffer_size,
2132 				     hv_dev_is_fc(hv_dev));
2133 	return ret;
2134 }
2135 
2136 static struct hv_driver storvsc_drv = {
2137 	.name = KBUILD_MODNAME,
2138 	.id_table = id_table,
2139 	.probe = storvsc_probe,
2140 	.remove = storvsc_remove,
2141 	.suspend = storvsc_suspend,
2142 	.resume = storvsc_resume,
2143 	.driver = {
2144 		.probe_type = PROBE_PREFER_ASYNCHRONOUS,
2145 	},
2146 };
2147 
2148 #if IS_ENABLED(CONFIG_SCSI_FC_ATTRS)
2149 static struct fc_function_template fc_transport_functions = {
2150 	.show_host_node_name = 1,
2151 	.show_host_port_name = 1,
2152 };
2153 #endif
2154 
2155 static int __init storvsc_drv_init(void)
2156 {
2157 	int ret;
2158 
2159 	/*
2160 	 * Divide the ring buffer data size (which is 1 page less
2161 	 * than the ring buffer size since that page is reserved for
2162 	 * the ring buffer indices) by the max request size (which is
2163 	 * vmbus_channel_packet_multipage_buffer + struct vstor_packet + u64)
2164 	 */
2165 	max_outstanding_req_per_channel =
2166 		((storvsc_ringbuffer_size - PAGE_SIZE) /
2167 		ALIGN(MAX_MULTIPAGE_BUFFER_PACKET +
2168 		sizeof(struct vstor_packet) + sizeof(u64),
2169 		sizeof(u64)));
2170 
2171 #if IS_ENABLED(CONFIG_SCSI_FC_ATTRS)
2172 	fc_transport_template = fc_attach_transport(&fc_transport_functions);
2173 	if (!fc_transport_template)
2174 		return -ENODEV;
2175 #endif
2176 
2177 	ret = vmbus_driver_register(&storvsc_drv);
2178 
2179 #if IS_ENABLED(CONFIG_SCSI_FC_ATTRS)
2180 	if (ret)
2181 		fc_release_transport(fc_transport_template);
2182 #endif
2183 
2184 	return ret;
2185 }
2186 
2187 static void __exit storvsc_drv_exit(void)
2188 {
2189 	vmbus_driver_unregister(&storvsc_drv);
2190 #if IS_ENABLED(CONFIG_SCSI_FC_ATTRS)
2191 	fc_release_transport(fc_transport_template);
2192 #endif
2193 }
2194 
2195 MODULE_LICENSE("GPL");
2196 MODULE_DESCRIPTION("Microsoft Hyper-V virtual storage driver");
2197 module_init(storvsc_drv_init);
2198 module_exit(storvsc_drv_exit);
2199