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