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