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