xref: /linux/drivers/scsi/scsi_debug.c (revision 5b026e34120766408e76ba19a0e33a9dc996f9f0)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * vvvvvvvvvvvvvvvvvvvvvvv Original vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
4  *  Copyright (C) 1992  Eric Youngdale
5  *  Simulate a host adapter with 2 disks attached.  Do a lot of checking
6  *  to make sure that we are not getting blocks mixed up, and PANIC if
7  *  anything out of the ordinary is seen.
8  * ^^^^^^^^^^^^^^^^^^^^^^^ Original ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
9  *
10  * Copyright (C) 2001 - 2021 Douglas Gilbert
11  *
12  *  For documentation see http://sg.danny.cz/sg/scsi_debug.html
13  */
14 
15 
16 #define pr_fmt(fmt) KBUILD_MODNAME ":%s: " fmt, __func__
17 
18 #include <linux/module.h>
19 #include <linux/align.h>
20 #include <linux/kernel.h>
21 #include <linux/errno.h>
22 #include <linux/jiffies.h>
23 #include <linux/slab.h>
24 #include <linux/types.h>
25 #include <linux/string.h>
26 #include <linux/fs.h>
27 #include <linux/init.h>
28 #include <linux/proc_fs.h>
29 #include <linux/vmalloc.h>
30 #include <linux/moduleparam.h>
31 #include <linux/scatterlist.h>
32 #include <linux/blkdev.h>
33 #include <linux/crc-t10dif.h>
34 #include <linux/spinlock.h>
35 #include <linux/interrupt.h>
36 #include <linux/atomic.h>
37 #include <linux/hrtimer.h>
38 #include <linux/uuid.h>
39 #include <linux/t10-pi.h>
40 #include <linux/msdos_partition.h>
41 #include <linux/random.h>
42 #include <linux/xarray.h>
43 #include <linux/prefetch.h>
44 #include <linux/debugfs.h>
45 #include <linux/async.h>
46 #include <linux/cleanup.h>
47 
48 #include <net/checksum.h>
49 
50 #include <asm/unaligned.h>
51 
52 #include <scsi/scsi.h>
53 #include <scsi/scsi_cmnd.h>
54 #include <scsi/scsi_device.h>
55 #include <scsi/scsi_host.h>
56 #include <scsi/scsicam.h>
57 #include <scsi/scsi_eh.h>
58 #include <scsi/scsi_tcq.h>
59 #include <scsi/scsi_dbg.h>
60 
61 #include "sd.h"
62 #include "scsi_logging.h"
63 
64 /* make sure inq_product_rev string corresponds to this version */
65 #define SDEBUG_VERSION "0191"	/* format to fit INQUIRY revision field */
66 static const char *sdebug_version_date = "20210520";
67 
68 #define MY_NAME "scsi_debug"
69 
70 /* Additional Sense Code (ASC) */
71 #define NO_ADDITIONAL_SENSE 0x0
72 #define OVERLAP_ATOMIC_COMMAND_ASC 0x0
73 #define OVERLAP_ATOMIC_COMMAND_ASCQ 0x23
74 #define LOGICAL_UNIT_NOT_READY 0x4
75 #define LOGICAL_UNIT_COMMUNICATION_FAILURE 0x8
76 #define UNRECOVERED_READ_ERR 0x11
77 #define PARAMETER_LIST_LENGTH_ERR 0x1a
78 #define INVALID_OPCODE 0x20
79 #define LBA_OUT_OF_RANGE 0x21
80 #define INVALID_FIELD_IN_CDB 0x24
81 #define INVALID_FIELD_IN_PARAM_LIST 0x26
82 #define WRITE_PROTECTED 0x27
83 #define UA_RESET_ASC 0x29
84 #define UA_CHANGED_ASC 0x2a
85 #define TARGET_CHANGED_ASC 0x3f
86 #define LUNS_CHANGED_ASCQ 0x0e
87 #define INSUFF_RES_ASC 0x55
88 #define INSUFF_RES_ASCQ 0x3
89 #define POWER_ON_RESET_ASCQ 0x0
90 #define POWER_ON_OCCURRED_ASCQ 0x1
91 #define BUS_RESET_ASCQ 0x2	/* scsi bus reset occurred */
92 #define MODE_CHANGED_ASCQ 0x1	/* mode parameters changed */
93 #define CAPACITY_CHANGED_ASCQ 0x9
94 #define SAVING_PARAMS_UNSUP 0x39
95 #define TRANSPORT_PROBLEM 0x4b
96 #define THRESHOLD_EXCEEDED 0x5d
97 #define LOW_POWER_COND_ON 0x5e
98 #define MISCOMPARE_VERIFY_ASC 0x1d
99 #define MICROCODE_CHANGED_ASCQ 0x1	/* with TARGET_CHANGED_ASC */
100 #define MICROCODE_CHANGED_WO_RESET_ASCQ 0x16
101 #define WRITE_ERROR_ASC 0xc
102 #define UNALIGNED_WRITE_ASCQ 0x4
103 #define WRITE_BOUNDARY_ASCQ 0x5
104 #define READ_INVDATA_ASCQ 0x6
105 #define READ_BOUNDARY_ASCQ 0x7
106 #define ATTEMPT_ACCESS_GAP 0x9
107 #define INSUFF_ZONE_ASCQ 0xe
108 /* see drivers/scsi/sense_codes.h */
109 
110 /* Additional Sense Code Qualifier (ASCQ) */
111 #define ACK_NAK_TO 0x3
112 
113 /* Default values for driver parameters */
114 #define DEF_NUM_HOST   1
115 #define DEF_NUM_TGTS   1
116 #define DEF_MAX_LUNS   1
117 /* With these defaults, this driver will make 1 host with 1 target
118  * (id 0) containing 1 logical unit (lun 0). That is 1 device.
119  */
120 #define DEF_ATO 1
121 #define DEF_CDB_LEN 10
122 #define DEF_JDELAY   1		/* if > 0 unit is a jiffy */
123 #define DEF_DEV_SIZE_PRE_INIT   0
124 #define DEF_DEV_SIZE_MB   8
125 #define DEF_ZBC_DEV_SIZE_MB   128
126 #define DEF_DIF 0
127 #define DEF_DIX 0
128 #define DEF_PER_HOST_STORE false
129 #define DEF_D_SENSE   0
130 #define DEF_EVERY_NTH   0
131 #define DEF_FAKE_RW	0
132 #define DEF_GUARD 0
133 #define DEF_HOST_LOCK 0
134 #define DEF_LBPU 0
135 #define DEF_LBPWS 0
136 #define DEF_LBPWS10 0
137 #define DEF_LBPRZ 1
138 #define DEF_LOWEST_ALIGNED 0
139 #define DEF_NDELAY   0		/* if > 0 unit is a nanosecond */
140 #define DEF_NO_LUN_0   0
141 #define DEF_NUM_PARTS   0
142 #define DEF_OPTS   0
143 #define DEF_OPT_BLKS 1024
144 #define DEF_PHYSBLK_EXP 0
145 #define DEF_OPT_XFERLEN_EXP 0
146 #define DEF_PTYPE   TYPE_DISK
147 #define DEF_RANDOM false
148 #define DEF_REMOVABLE false
149 #define DEF_SCSI_LEVEL   7    /* INQUIRY, byte2 [6->SPC-4; 7->SPC-5] */
150 #define DEF_SECTOR_SIZE 512
151 #define DEF_UNMAP_ALIGNMENT 0
152 #define DEF_UNMAP_GRANULARITY 1
153 #define DEF_UNMAP_MAX_BLOCKS 0xFFFFFFFF
154 #define DEF_UNMAP_MAX_DESC 256
155 #define DEF_VIRTUAL_GB   0
156 #define DEF_VPD_USE_HOSTNO 1
157 #define DEF_WRITESAME_LENGTH 0xFFFF
158 #define DEF_ATOMIC_WR 0
159 #define DEF_ATOMIC_WR_MAX_LENGTH 8192
160 #define DEF_ATOMIC_WR_ALIGN 2
161 #define DEF_ATOMIC_WR_GRAN 2
162 #define DEF_ATOMIC_WR_MAX_LENGTH_BNDRY (DEF_ATOMIC_WR_MAX_LENGTH)
163 #define DEF_ATOMIC_WR_MAX_BNDRY 128
164 #define DEF_STRICT 0
165 #define DEF_STATISTICS false
166 #define DEF_SUBMIT_QUEUES 1
167 #define DEF_TUR_MS_TO_READY 0
168 #define DEF_UUID_CTL 0
169 #define JDELAY_OVERRIDDEN -9999
170 
171 /* Default parameters for ZBC drives */
172 #define DEF_ZBC_ZONE_SIZE_MB	128
173 #define DEF_ZBC_MAX_OPEN_ZONES	8
174 #define DEF_ZBC_NR_CONV_ZONES	1
175 
176 #define SDEBUG_LUN_0_VAL 0
177 
178 /* bit mask values for sdebug_opts */
179 #define SDEBUG_OPT_NOISE		1
180 #define SDEBUG_OPT_MEDIUM_ERR		2
181 #define SDEBUG_OPT_TIMEOUT		4
182 #define SDEBUG_OPT_RECOVERED_ERR	8
183 #define SDEBUG_OPT_TRANSPORT_ERR	16
184 #define SDEBUG_OPT_DIF_ERR		32
185 #define SDEBUG_OPT_DIX_ERR		64
186 #define SDEBUG_OPT_MAC_TIMEOUT		128
187 #define SDEBUG_OPT_SHORT_TRANSFER	0x100
188 #define SDEBUG_OPT_Q_NOISE		0x200
189 #define SDEBUG_OPT_ALL_TSF		0x400	/* ignore */
190 #define SDEBUG_OPT_RARE_TSF		0x800
191 #define SDEBUG_OPT_N_WCE		0x1000
192 #define SDEBUG_OPT_RESET_NOISE		0x2000
193 #define SDEBUG_OPT_NO_CDB_NOISE		0x4000
194 #define SDEBUG_OPT_HOST_BUSY		0x8000
195 #define SDEBUG_OPT_CMD_ABORT		0x10000
196 #define SDEBUG_OPT_ALL_NOISE (SDEBUG_OPT_NOISE | SDEBUG_OPT_Q_NOISE | \
197 			      SDEBUG_OPT_RESET_NOISE)
198 #define SDEBUG_OPT_ALL_INJECTING (SDEBUG_OPT_RECOVERED_ERR | \
199 				  SDEBUG_OPT_TRANSPORT_ERR | \
200 				  SDEBUG_OPT_DIF_ERR | SDEBUG_OPT_DIX_ERR | \
201 				  SDEBUG_OPT_SHORT_TRANSFER | \
202 				  SDEBUG_OPT_HOST_BUSY | \
203 				  SDEBUG_OPT_CMD_ABORT)
204 #define SDEBUG_OPT_RECOV_DIF_DIX (SDEBUG_OPT_RECOVERED_ERR | \
205 				  SDEBUG_OPT_DIF_ERR | SDEBUG_OPT_DIX_ERR)
206 
207 /* As indicated in SAM-5 and SPC-4 Unit Attentions (UAs) are returned in
208  * priority order. In the subset implemented here lower numbers have higher
209  * priority. The UA numbers should be a sequence starting from 0 with
210  * SDEBUG_NUM_UAS being 1 higher than the highest numbered UA. */
211 #define SDEBUG_UA_POR 0		/* Power on, reset, or bus device reset */
212 #define SDEBUG_UA_POOCCUR 1	/* Power on occurred */
213 #define SDEBUG_UA_BUS_RESET 2
214 #define SDEBUG_UA_MODE_CHANGED 3
215 #define SDEBUG_UA_CAPACITY_CHANGED 4
216 #define SDEBUG_UA_LUNS_CHANGED 5
217 #define SDEBUG_UA_MICROCODE_CHANGED 6	/* simulate firmware change */
218 #define SDEBUG_UA_MICROCODE_CHANGED_WO_RESET 7
219 #define SDEBUG_NUM_UAS 8
220 
221 /* when 1==SDEBUG_OPT_MEDIUM_ERR, a medium error is simulated at this
222  * sector on read commands: */
223 #define OPT_MEDIUM_ERR_ADDR   0x1234 /* that's sector 4660 in decimal */
224 #define OPT_MEDIUM_ERR_NUM    10     /* number of consecutive medium errs */
225 
226 /* SDEBUG_CANQUEUE is the maximum number of commands that can be queued
227  * (for response) per submit queue at one time. Can be reduced by max_queue
228  * option. Command responses are not queued when jdelay=0 and ndelay=0. The
229  * per-device DEF_CMD_PER_LUN can be changed via sysfs:
230  * /sys/class/scsi_device/<h:c:t:l>/device/queue_depth
231  * but cannot exceed SDEBUG_CANQUEUE .
232  */
233 #define SDEBUG_CANQUEUE_WORDS  3	/* a WORD is bits in a long */
234 #define SDEBUG_CANQUEUE  (SDEBUG_CANQUEUE_WORDS * BITS_PER_LONG)
235 #define DEF_CMD_PER_LUN  SDEBUG_CANQUEUE
236 
237 /* UA - Unit Attention; SA - Service Action; SSU - Start Stop Unit */
238 #define F_D_IN			1	/* Data-in command (e.g. READ) */
239 #define F_D_OUT			2	/* Data-out command (e.g. WRITE) */
240 #define F_D_OUT_MAYBE		4	/* WRITE SAME, NDOB bit */
241 #define F_D_UNKN		8
242 #define F_RL_WLUN_OK		0x10	/* allowed with REPORT LUNS W-LUN */
243 #define F_SKIP_UA		0x20	/* bypass UAs (e.g. INQUIRY command) */
244 #define F_DELAY_OVERR		0x40	/* for commands like INQUIRY */
245 #define F_SA_LOW		0x80	/* SA is in cdb byte 1, bits 4 to 0 */
246 #define F_SA_HIGH		0x100	/* SA is in cdb bytes 8 and 9 */
247 #define F_INV_OP		0x200	/* invalid opcode (not supported) */
248 #define F_FAKE_RW		0x400	/* bypass resp_*() when fake_rw set */
249 #define F_M_ACCESS		0x800	/* media access, reacts to SSU state */
250 #define F_SSU_DELAY		0x1000	/* SSU command delay (long-ish) */
251 #define F_SYNC_DELAY		0x2000	/* SYNCHRONIZE CACHE delay */
252 
253 /* Useful combinations of the above flags */
254 #define FF_RESPOND (F_RL_WLUN_OK | F_SKIP_UA | F_DELAY_OVERR)
255 #define FF_MEDIA_IO (F_M_ACCESS | F_FAKE_RW)
256 #define FF_SA (F_SA_HIGH | F_SA_LOW)
257 #define F_LONG_DELAY		(F_SSU_DELAY | F_SYNC_DELAY)
258 
259 #define SDEBUG_MAX_PARTS 4
260 
261 #define SDEBUG_MAX_CMD_LEN 32
262 
263 #define SDEB_XA_NOT_IN_USE XA_MARK_1
264 
265 static struct kmem_cache *queued_cmd_cache;
266 
267 #define TO_QUEUED_CMD(scmd)  ((void *)(scmd)->host_scribble)
268 #define ASSIGN_QUEUED_CMD(scmnd, qc) { (scmnd)->host_scribble = (void *) qc; }
269 
270 /* Zone types (zbcr05 table 25) */
271 enum sdebug_z_type {
272 	ZBC_ZTYPE_CNV	= 0x1,
273 	ZBC_ZTYPE_SWR	= 0x2,
274 	ZBC_ZTYPE_SWP	= 0x3,
275 	/* ZBC_ZTYPE_SOBR = 0x4, */
276 	ZBC_ZTYPE_GAP	= 0x5,
277 };
278 
279 /* enumeration names taken from table 26, zbcr05 */
280 enum sdebug_z_cond {
281 	ZBC_NOT_WRITE_POINTER	= 0x0,
282 	ZC1_EMPTY		= 0x1,
283 	ZC2_IMPLICIT_OPEN	= 0x2,
284 	ZC3_EXPLICIT_OPEN	= 0x3,
285 	ZC4_CLOSED		= 0x4,
286 	ZC6_READ_ONLY		= 0xd,
287 	ZC5_FULL		= 0xe,
288 	ZC7_OFFLINE		= 0xf,
289 };
290 
291 struct sdeb_zone_state {	/* ZBC: per zone state */
292 	enum sdebug_z_type z_type;
293 	enum sdebug_z_cond z_cond;
294 	bool z_non_seq_resource;
295 	unsigned int z_size;
296 	sector_t z_start;
297 	sector_t z_wp;
298 };
299 
300 enum sdebug_err_type {
301 	ERR_TMOUT_CMD		= 0,	/* make specific scsi command timeout */
302 	ERR_FAIL_QUEUE_CMD	= 1,	/* make specific scsi command's */
303 					/* queuecmd return failed */
304 	ERR_FAIL_CMD		= 2,	/* make specific scsi command's */
305 					/* queuecmd return succeed but */
306 					/* with errors set in scsi_cmnd */
307 	ERR_ABORT_CMD_FAILED	= 3,	/* control return FAILED from */
308 					/* scsi_debug_abort() */
309 	ERR_LUN_RESET_FAILED	= 4,	/* control return FAILED from */
310 					/* scsi_debug_device_reseLUN_RESET_FAILEDt() */
311 };
312 
313 struct sdebug_err_inject {
314 	int type;
315 	struct list_head list;
316 	int cnt;
317 	unsigned char cmd;
318 	struct rcu_head rcu;
319 
320 	union {
321 		/*
322 		 * For ERR_FAIL_QUEUE_CMD
323 		 */
324 		int queuecmd_ret;
325 
326 		/*
327 		 * For ERR_FAIL_CMD
328 		 */
329 		struct {
330 			unsigned char host_byte;
331 			unsigned char driver_byte;
332 			unsigned char status_byte;
333 			unsigned char sense_key;
334 			unsigned char asc;
335 			unsigned char asq;
336 		};
337 	};
338 };
339 
340 struct sdebug_dev_info {
341 	struct list_head dev_list;
342 	unsigned int channel;
343 	unsigned int target;
344 	u64 lun;
345 	uuid_t lu_name;
346 	struct sdebug_host_info *sdbg_host;
347 	unsigned long uas_bm[1];
348 	atomic_t stopped;	/* 1: by SSU, 2: device start */
349 	bool used;
350 
351 	/* For ZBC devices */
352 	bool zoned;
353 	unsigned int zcap;
354 	unsigned int zsize;
355 	unsigned int zsize_shift;
356 	unsigned int nr_zones;
357 	unsigned int nr_conv_zones;
358 	unsigned int nr_seq_zones;
359 	unsigned int nr_imp_open;
360 	unsigned int nr_exp_open;
361 	unsigned int nr_closed;
362 	unsigned int max_open;
363 	ktime_t create_ts;	/* time since bootup that this device was created */
364 	struct sdeb_zone_state *zstate;
365 
366 	struct dentry *debugfs_entry;
367 	struct spinlock list_lock;
368 	struct list_head inject_err_list;
369 };
370 
371 struct sdebug_target_info {
372 	bool reset_fail;
373 	struct dentry *debugfs_entry;
374 };
375 
376 struct sdebug_host_info {
377 	struct list_head host_list;
378 	int si_idx;	/* sdeb_store_info (per host) xarray index */
379 	struct Scsi_Host *shost;
380 	struct device dev;
381 	struct list_head dev_info_list;
382 };
383 
384 /* There is an xarray of pointers to this struct's objects, one per host */
385 struct sdeb_store_info {
386 	rwlock_t macc_data_lck;	/* for media data access on this store */
387 	rwlock_t macc_meta_lck;	/* for atomic media meta access on this store */
388 	rwlock_t macc_sector_lck;	/* per-sector media data access on this store */
389 	u8 *storep;		/* user data storage (ram) */
390 	struct t10_pi_tuple *dif_storep; /* protection info */
391 	void *map_storep;	/* provisioning map */
392 };
393 
394 #define dev_to_sdebug_host(d)	\
395 	container_of(d, struct sdebug_host_info, dev)
396 
397 #define shost_to_sdebug_host(shost)	\
398 	dev_to_sdebug_host(shost->dma_dev)
399 
400 enum sdeb_defer_type {SDEB_DEFER_NONE = 0, SDEB_DEFER_HRT = 1,
401 		      SDEB_DEFER_WQ = 2, SDEB_DEFER_POLL = 3};
402 
403 struct sdebug_defer {
404 	struct hrtimer hrt;
405 	struct execute_work ew;
406 	ktime_t cmpl_ts;/* time since boot to complete this cmd */
407 	int issuing_cpu;
408 	bool aborted;	/* true when blk_abort_request() already called */
409 	enum sdeb_defer_type defer_t;
410 };
411 
412 struct sdebug_device_access_info {
413 	bool atomic_write;
414 	u64 lba;
415 	u32 num;
416 	struct scsi_cmnd *self;
417 };
418 
419 struct sdebug_queued_cmd {
420 	/* corresponding bit set in in_use_bm[] in owning struct sdebug_queue
421 	 * instance indicates this slot is in use.
422 	 */
423 	struct sdebug_defer sd_dp;
424 	struct scsi_cmnd *scmd;
425 	struct sdebug_device_access_info *i;
426 };
427 
428 struct sdebug_scsi_cmd {
429 	spinlock_t   lock;
430 };
431 
432 static atomic_t sdebug_cmnd_count;   /* number of incoming commands */
433 static atomic_t sdebug_completions;  /* count of deferred completions */
434 static atomic_t sdebug_miss_cpus;    /* submission + completion cpus differ */
435 static atomic_t sdebug_a_tsf;	     /* 'almost task set full' counter */
436 static atomic_t sdeb_inject_pending;
437 static atomic_t sdeb_mq_poll_count;  /* bumped when mq_poll returns > 0 */
438 
439 struct opcode_info_t {
440 	u8 num_attached;	/* 0 if this is it (i.e. a leaf); use 0xff */
441 				/* for terminating element */
442 	u8 opcode;		/* if num_attached > 0, preferred */
443 	u16 sa;			/* service action */
444 	u32 flags;		/* OR-ed set of SDEB_F_* */
445 	int (*pfp)(struct scsi_cmnd *, struct sdebug_dev_info *);
446 	const struct opcode_info_t *arrp;  /* num_attached elements or NULL */
447 	u8 len_mask[16];	/* len_mask[0]-->cdb_len, then mask for cdb */
448 				/* 1 to min(cdb_len, 15); ignore cdb[15...] */
449 };
450 
451 /* SCSI opcodes (first byte of cdb) of interest mapped onto these indexes */
452 enum sdeb_opcode_index {
453 	SDEB_I_INVALID_OPCODE =	0,
454 	SDEB_I_INQUIRY = 1,
455 	SDEB_I_REPORT_LUNS = 2,
456 	SDEB_I_REQUEST_SENSE = 3,
457 	SDEB_I_TEST_UNIT_READY = 4,
458 	SDEB_I_MODE_SENSE = 5,		/* 6, 10 */
459 	SDEB_I_MODE_SELECT = 6,		/* 6, 10 */
460 	SDEB_I_LOG_SENSE = 7,
461 	SDEB_I_READ_CAPACITY = 8,	/* 10; 16 is in SA_IN(16) */
462 	SDEB_I_READ = 9,		/* 6, 10, 12, 16 */
463 	SDEB_I_WRITE = 10,		/* 6, 10, 12, 16 */
464 	SDEB_I_START_STOP = 11,
465 	SDEB_I_SERV_ACT_IN_16 = 12,	/* add ...SERV_ACT_IN_12 if needed */
466 	SDEB_I_SERV_ACT_OUT_16 = 13,	/* add ...SERV_ACT_OUT_12 if needed */
467 	SDEB_I_MAINT_IN = 14,
468 	SDEB_I_MAINT_OUT = 15,
469 	SDEB_I_VERIFY = 16,		/* VERIFY(10), VERIFY(16) */
470 	SDEB_I_VARIABLE_LEN = 17,	/* READ(32), WRITE(32), WR_SCAT(32) */
471 	SDEB_I_RESERVE = 18,		/* 6, 10 */
472 	SDEB_I_RELEASE = 19,		/* 6, 10 */
473 	SDEB_I_ALLOW_REMOVAL = 20,	/* PREVENT ALLOW MEDIUM REMOVAL */
474 	SDEB_I_REZERO_UNIT = 21,	/* REWIND in SSC */
475 	SDEB_I_ATA_PT = 22,		/* 12, 16 */
476 	SDEB_I_SEND_DIAG = 23,
477 	SDEB_I_UNMAP = 24,
478 	SDEB_I_WRITE_BUFFER = 25,
479 	SDEB_I_WRITE_SAME = 26,		/* 10, 16 */
480 	SDEB_I_SYNC_CACHE = 27,		/* 10, 16 */
481 	SDEB_I_COMP_WRITE = 28,
482 	SDEB_I_PRE_FETCH = 29,		/* 10, 16 */
483 	SDEB_I_ZONE_OUT = 30,		/* 0x94+SA; includes no data xfer */
484 	SDEB_I_ZONE_IN = 31,		/* 0x95+SA; all have data-in */
485 	SDEB_I_ATOMIC_WRITE_16 = 32,
486 	SDEB_I_LAST_ELEM_P1 = 33,	/* keep this last (previous + 1) */
487 };
488 
489 
490 static const unsigned char opcode_ind_arr[256] = {
491 /* 0x0; 0x0->0x1f: 6 byte cdbs */
492 	SDEB_I_TEST_UNIT_READY, SDEB_I_REZERO_UNIT, 0, SDEB_I_REQUEST_SENSE,
493 	    0, 0, 0, 0,
494 	SDEB_I_READ, 0, SDEB_I_WRITE, 0, 0, 0, 0, 0,
495 	0, 0, SDEB_I_INQUIRY, 0, 0, SDEB_I_MODE_SELECT, SDEB_I_RESERVE,
496 	    SDEB_I_RELEASE,
497 	0, 0, SDEB_I_MODE_SENSE, SDEB_I_START_STOP, 0, SDEB_I_SEND_DIAG,
498 	    SDEB_I_ALLOW_REMOVAL, 0,
499 /* 0x20; 0x20->0x3f: 10 byte cdbs */
500 	0, 0, 0, 0, 0, SDEB_I_READ_CAPACITY, 0, 0,
501 	SDEB_I_READ, 0, SDEB_I_WRITE, 0, 0, 0, 0, SDEB_I_VERIFY,
502 	0, 0, 0, 0, SDEB_I_PRE_FETCH, SDEB_I_SYNC_CACHE, 0, 0,
503 	0, 0, 0, SDEB_I_WRITE_BUFFER, 0, 0, 0, 0,
504 /* 0x40; 0x40->0x5f: 10 byte cdbs */
505 	0, SDEB_I_WRITE_SAME, SDEB_I_UNMAP, 0, 0, 0, 0, 0,
506 	0, 0, 0, 0, 0, SDEB_I_LOG_SENSE, 0, 0,
507 	0, 0, 0, 0, 0, SDEB_I_MODE_SELECT, SDEB_I_RESERVE,
508 	    SDEB_I_RELEASE,
509 	0, 0, SDEB_I_MODE_SENSE, 0, 0, 0, 0, 0,
510 /* 0x60; 0x60->0x7d are reserved, 0x7e is "extended cdb" */
511 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
512 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
513 	0, SDEB_I_VARIABLE_LEN,
514 /* 0x80; 0x80->0x9f: 16 byte cdbs */
515 	0, 0, 0, 0, 0, SDEB_I_ATA_PT, 0, 0,
516 	SDEB_I_READ, SDEB_I_COMP_WRITE, SDEB_I_WRITE, 0,
517 	0, 0, 0, SDEB_I_VERIFY,
518 	SDEB_I_PRE_FETCH, SDEB_I_SYNC_CACHE, 0, SDEB_I_WRITE_SAME,
519 	SDEB_I_ZONE_OUT, SDEB_I_ZONE_IN, 0, 0,
520 	0, 0, 0, 0,
521 	SDEB_I_ATOMIC_WRITE_16, 0, SDEB_I_SERV_ACT_IN_16, SDEB_I_SERV_ACT_OUT_16,
522 /* 0xa0; 0xa0->0xbf: 12 byte cdbs */
523 	SDEB_I_REPORT_LUNS, SDEB_I_ATA_PT, 0, SDEB_I_MAINT_IN,
524 	     SDEB_I_MAINT_OUT, 0, 0, 0,
525 	SDEB_I_READ, 0 /* SDEB_I_SERV_ACT_OUT_12 */, SDEB_I_WRITE,
526 	     0 /* SDEB_I_SERV_ACT_IN_12 */, 0, 0, 0, 0,
527 	0, 0, 0, 0, 0, 0, 0, 0,
528 	0, 0, 0, 0, 0, 0, 0, 0,
529 /* 0xc0; 0xc0->0xff: vendor specific */
530 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
531 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
532 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
533 	0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
534 };
535 
536 /*
537  * The following "response" functions return the SCSI mid-level's 4 byte
538  * tuple-in-an-int. To handle commands with an IMMED bit, for a faster
539  * command completion, they can mask their return value with
540  * SDEG_RES_IMMED_MASK .
541  */
542 #define SDEG_RES_IMMED_MASK 0x40000000
543 
544 static int resp_inquiry(struct scsi_cmnd *, struct sdebug_dev_info *);
545 static int resp_report_luns(struct scsi_cmnd *, struct sdebug_dev_info *);
546 static int resp_requests(struct scsi_cmnd *, struct sdebug_dev_info *);
547 static int resp_mode_sense(struct scsi_cmnd *, struct sdebug_dev_info *);
548 static int resp_mode_select(struct scsi_cmnd *, struct sdebug_dev_info *);
549 static int resp_log_sense(struct scsi_cmnd *, struct sdebug_dev_info *);
550 static int resp_readcap(struct scsi_cmnd *, struct sdebug_dev_info *);
551 static int resp_read_dt0(struct scsi_cmnd *, struct sdebug_dev_info *);
552 static int resp_write_dt0(struct scsi_cmnd *, struct sdebug_dev_info *);
553 static int resp_write_scat(struct scsi_cmnd *, struct sdebug_dev_info *);
554 static int resp_start_stop(struct scsi_cmnd *, struct sdebug_dev_info *);
555 static int resp_readcap16(struct scsi_cmnd *, struct sdebug_dev_info *);
556 static int resp_get_lba_status(struct scsi_cmnd *, struct sdebug_dev_info *);
557 static int resp_get_stream_status(struct scsi_cmnd *scp,
558 				  struct sdebug_dev_info *devip);
559 static int resp_report_tgtpgs(struct scsi_cmnd *, struct sdebug_dev_info *);
560 static int resp_unmap(struct scsi_cmnd *, struct sdebug_dev_info *);
561 static int resp_rsup_opcodes(struct scsi_cmnd *, struct sdebug_dev_info *);
562 static int resp_rsup_tmfs(struct scsi_cmnd *, struct sdebug_dev_info *);
563 static int resp_verify(struct scsi_cmnd *, struct sdebug_dev_info *);
564 static int resp_write_same_10(struct scsi_cmnd *, struct sdebug_dev_info *);
565 static int resp_write_same_16(struct scsi_cmnd *, struct sdebug_dev_info *);
566 static int resp_comp_write(struct scsi_cmnd *, struct sdebug_dev_info *);
567 static int resp_write_buffer(struct scsi_cmnd *, struct sdebug_dev_info *);
568 static int resp_sync_cache(struct scsi_cmnd *, struct sdebug_dev_info *);
569 static int resp_pre_fetch(struct scsi_cmnd *, struct sdebug_dev_info *);
570 static int resp_report_zones(struct scsi_cmnd *, struct sdebug_dev_info *);
571 static int resp_atomic_write(struct scsi_cmnd *, struct sdebug_dev_info *);
572 static int resp_open_zone(struct scsi_cmnd *, struct sdebug_dev_info *);
573 static int resp_close_zone(struct scsi_cmnd *, struct sdebug_dev_info *);
574 static int resp_finish_zone(struct scsi_cmnd *, struct sdebug_dev_info *);
575 static int resp_rwp_zone(struct scsi_cmnd *, struct sdebug_dev_info *);
576 
577 static int sdebug_do_add_host(bool mk_new_store);
578 static int sdebug_add_host_helper(int per_host_idx);
579 static void sdebug_do_remove_host(bool the_end);
580 static int sdebug_add_store(void);
581 static void sdebug_erase_store(int idx, struct sdeb_store_info *sip);
582 static void sdebug_erase_all_stores(bool apart_from_first);
583 
584 static void sdebug_free_queued_cmd(struct sdebug_queued_cmd *sqcp);
585 
586 /*
587  * The following are overflow arrays for cdbs that "hit" the same index in
588  * the opcode_info_arr array. The most time sensitive (or commonly used) cdb
589  * should be placed in opcode_info_arr[], the others should be placed here.
590  */
591 static const struct opcode_info_t msense_iarr[] = {
592 	{0, 0x1a, 0, F_D_IN, NULL, NULL,
593 	    {6,  0xe8, 0xff, 0xff, 0xff, 0xc7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
594 };
595 
596 static const struct opcode_info_t mselect_iarr[] = {
597 	{0, 0x15, 0, F_D_OUT, NULL, NULL,
598 	    {6,  0xf1, 0, 0, 0xff, 0xc7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
599 };
600 
601 static const struct opcode_info_t read_iarr[] = {
602 	{0, 0x28, 0, F_D_IN | FF_MEDIA_IO, resp_read_dt0, NULL,/* READ(10) */
603 	    {10,  0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0xff, 0xff, 0xc7, 0, 0,
604 	     0, 0, 0, 0} },
605 	{0, 0x8, 0, F_D_IN | FF_MEDIA_IO, resp_read_dt0, NULL, /* READ(6) */
606 	    {6,  0xff, 0xff, 0xff, 0xff, 0xc7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
607 	{0, 0xa8, 0, F_D_IN | FF_MEDIA_IO, resp_read_dt0, NULL,/* READ(12) */
608 	    {12,  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xbf,
609 	     0xc7, 0, 0, 0, 0} },
610 };
611 
612 static const struct opcode_info_t write_iarr[] = {
613 	{0, 0x2a, 0, F_D_OUT | FF_MEDIA_IO, resp_write_dt0,  /* WRITE(10) */
614 	    NULL, {10,  0xfb, 0xff, 0xff, 0xff, 0xff, 0x3f, 0xff, 0xff, 0xc7,
615 		   0, 0, 0, 0, 0, 0} },
616 	{0, 0xa, 0, F_D_OUT | FF_MEDIA_IO, resp_write_dt0,   /* WRITE(6) */
617 	    NULL, {6,  0xff, 0xff, 0xff, 0xff, 0xc7, 0, 0, 0, 0, 0, 0, 0,
618 		   0, 0, 0} },
619 	{0, 0xaa, 0, F_D_OUT | FF_MEDIA_IO, resp_write_dt0,  /* WRITE(12) */
620 	    NULL, {12,  0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
621 		   0xbf, 0xc7, 0, 0, 0, 0} },
622 };
623 
624 static const struct opcode_info_t verify_iarr[] = {
625 	{0, 0x2f, 0, F_D_OUT_MAYBE | FF_MEDIA_IO, resp_verify,/* VERIFY(10) */
626 	    NULL, {10,  0xf7, 0xff, 0xff, 0xff, 0xff, 0xbf, 0xff, 0xff, 0xc7,
627 		   0, 0, 0, 0, 0, 0} },
628 };
629 
630 static const struct opcode_info_t sa_in_16_iarr[] = {
631 	{0, 0x9e, 0x12, F_SA_LOW | F_D_IN, resp_get_lba_status, NULL,
632 	    {16,  0x12, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
633 	     0xff, 0xff, 0xff, 0, 0xc7} },	/* GET LBA STATUS(16) */
634 	{0, 0x9e, 0x16, F_SA_LOW | F_D_IN, resp_get_stream_status, NULL,
635 	    {16, 0x16, 0, 0, 0xff, 0xff, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff,
636 	     0, 0} },	/* GET STREAM STATUS */
637 };
638 
639 static const struct opcode_info_t vl_iarr[] = {	/* VARIABLE LENGTH */
640 	{0, 0x7f, 0xb, F_SA_HIGH | F_D_OUT | FF_MEDIA_IO, resp_write_dt0,
641 	    NULL, {32,  0xc7, 0, 0, 0, 0, 0x3f, 0x18, 0x0, 0xb, 0xfa,
642 		   0, 0xff, 0xff, 0xff, 0xff} },	/* WRITE(32) */
643 	{0, 0x7f, 0x11, F_SA_HIGH | F_D_OUT | FF_MEDIA_IO, resp_write_scat,
644 	    NULL, {32,  0xc7, 0, 0, 0, 0, 0x3f, 0x18, 0x0, 0x11, 0xf8,
645 		   0, 0xff, 0xff, 0x0, 0x0} },	/* WRITE SCATTERED(32) */
646 };
647 
648 static const struct opcode_info_t maint_in_iarr[] = {	/* MAINT IN */
649 	{0, 0xa3, 0xc, F_SA_LOW | F_D_IN, resp_rsup_opcodes, NULL,
650 	    {12,  0xc, 0x87, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0,
651 	     0xc7, 0, 0, 0, 0} }, /* REPORT SUPPORTED OPERATION CODES */
652 	{0, 0xa3, 0xd, F_SA_LOW | F_D_IN, resp_rsup_tmfs, NULL,
653 	    {12,  0xd, 0x80, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0, 0xc7, 0, 0,
654 	     0, 0} },	/* REPORTED SUPPORTED TASK MANAGEMENT FUNCTIONS */
655 };
656 
657 static const struct opcode_info_t write_same_iarr[] = {
658 	{0, 0x93, 0, F_D_OUT_MAYBE | FF_MEDIA_IO, resp_write_same_16, NULL,
659 	    {16,  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
660 	     0xff, 0xff, 0xff, 0x3f, 0xc7} },		/* WRITE SAME(16) */
661 };
662 
663 static const struct opcode_info_t reserve_iarr[] = {
664 	{0, 0x16, 0, F_D_OUT, NULL, NULL,		/* RESERVE(6) */
665 	    {6,  0x1f, 0xff, 0xff, 0xff, 0xc7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
666 };
667 
668 static const struct opcode_info_t release_iarr[] = {
669 	{0, 0x17, 0, F_D_OUT, NULL, NULL,		/* RELEASE(6) */
670 	    {6,  0x1f, 0xff, 0, 0, 0xc7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
671 };
672 
673 static const struct opcode_info_t sync_cache_iarr[] = {
674 	{0, 0x91, 0, F_SYNC_DELAY | F_M_ACCESS, resp_sync_cache, NULL,
675 	    {16,  0x6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
676 	     0xff, 0xff, 0xff, 0xff, 0x3f, 0xc7} },	/* SYNC_CACHE (16) */
677 };
678 
679 static const struct opcode_info_t pre_fetch_iarr[] = {
680 	{0, 0x90, 0, F_SYNC_DELAY | FF_MEDIA_IO, resp_pre_fetch, NULL,
681 	    {16,  0x2, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
682 	     0xff, 0xff, 0xff, 0xff, 0x3f, 0xc7} },	/* PRE-FETCH (16) */
683 };
684 
685 static const struct opcode_info_t zone_out_iarr[] = {	/* ZONE OUT(16) */
686 	{0, 0x94, 0x1, F_SA_LOW | F_M_ACCESS, resp_close_zone, NULL,
687 	    {16, 0x1, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
688 	     0xff, 0, 0, 0xff, 0xff, 0x1, 0xc7} },	/* CLOSE ZONE */
689 	{0, 0x94, 0x2, F_SA_LOW | F_M_ACCESS, resp_finish_zone, NULL,
690 	    {16, 0x2, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
691 	     0xff, 0, 0, 0xff, 0xff, 0x1, 0xc7} },	/* FINISH ZONE */
692 	{0, 0x94, 0x4, F_SA_LOW | F_M_ACCESS, resp_rwp_zone, NULL,
693 	    {16, 0x4, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
694 	     0xff, 0, 0, 0xff, 0xff, 0x1, 0xc7} },  /* RESET WRITE POINTER */
695 };
696 
697 static const struct opcode_info_t zone_in_iarr[] = {	/* ZONE IN(16) */
698 	{0, 0x95, 0x6, F_SA_LOW | F_D_IN | F_M_ACCESS, NULL, NULL,
699 	    {16, 0x6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
700 	     0xff, 0xff, 0xff, 0xff, 0x3f, 0xc7} }, /* REPORT ZONES */
701 };
702 
703 
704 /* This array is accessed via SDEB_I_* values. Make sure all are mapped,
705  * plus the terminating elements for logic that scans this table such as
706  * REPORT SUPPORTED OPERATION CODES. */
707 static const struct opcode_info_t opcode_info_arr[SDEB_I_LAST_ELEM_P1 + 1] = {
708 /* 0 */
709 	{0, 0, 0, F_INV_OP | FF_RESPOND, NULL, NULL,	/* unknown opcodes */
710 	    {0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
711 	{0, 0x12, 0, FF_RESPOND | F_D_IN, resp_inquiry, NULL, /* INQUIRY */
712 	    {6,  0xe3, 0xff, 0xff, 0xff, 0xc7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
713 	{0, 0xa0, 0, FF_RESPOND | F_D_IN, resp_report_luns, NULL,
714 	    {12,  0xe3, 0xff, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0, 0xc7, 0, 0,
715 	     0, 0} },					/* REPORT LUNS */
716 	{0, 0x3, 0, FF_RESPOND | F_D_IN, resp_requests, NULL,
717 	    {6,  0xe1, 0, 0, 0xff, 0xc7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
718 	{0, 0x0, 0, F_M_ACCESS | F_RL_WLUN_OK, NULL, NULL,/* TEST UNIT READY */
719 	    {6,  0, 0, 0, 0, 0xc7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
720 /* 5 */
721 	{ARRAY_SIZE(msense_iarr), 0x5a, 0, F_D_IN,	/* MODE SENSE(10) */
722 	    resp_mode_sense, msense_iarr, {10,  0xf8, 0xff, 0xff, 0, 0, 0,
723 		0xff, 0xff, 0xc7, 0, 0, 0, 0, 0, 0} },
724 	{ARRAY_SIZE(mselect_iarr), 0x55, 0, F_D_OUT,	/* MODE SELECT(10) */
725 	    resp_mode_select, mselect_iarr, {10,  0xf1, 0, 0, 0, 0, 0, 0xff,
726 		0xff, 0xc7, 0, 0, 0, 0, 0, 0} },
727 	{0, 0x4d, 0, F_D_IN, resp_log_sense, NULL,	/* LOG SENSE */
728 	    {10,  0xe3, 0xff, 0xff, 0, 0xff, 0xff, 0xff, 0xff, 0xc7, 0, 0, 0,
729 	     0, 0, 0} },
730 	{0, 0x25, 0, F_D_IN, resp_readcap, NULL,    /* READ CAPACITY(10) */
731 	    {10,  0xe1, 0xff, 0xff, 0xff, 0xff, 0, 0, 0x1, 0xc7, 0, 0, 0, 0,
732 	     0, 0} },
733 	{ARRAY_SIZE(read_iarr), 0x88, 0, F_D_IN | FF_MEDIA_IO, /* READ(16) */
734 	    resp_read_dt0, read_iarr, {16,  0xfe, 0xff, 0xff, 0xff, 0xff,
735 	    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc7} },
736 /* 10 */
737 	{ARRAY_SIZE(write_iarr), 0x8a, 0, F_D_OUT | FF_MEDIA_IO,
738 	    resp_write_dt0, write_iarr,			/* WRITE(16) */
739 		{16,  0xfa, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
740 		 0xff, 0xff, 0xff, 0xff, 0xff, 0xc7} },
741 	{0, 0x1b, 0, F_SSU_DELAY, resp_start_stop, NULL,/* START STOP UNIT */
742 	    {6,  0x1, 0, 0xf, 0xf7, 0xc7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
743 	{ARRAY_SIZE(sa_in_16_iarr), 0x9e, 0x10, F_SA_LOW | F_D_IN,
744 	    resp_readcap16, sa_in_16_iarr, /* SA_IN(16), READ CAPACITY(16) */
745 		{16,  0x10, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
746 		 0xff, 0xff, 0xff, 0xff, 0x1, 0xc7} },
747 	{0, 0x9f, 0x12, F_SA_LOW | F_D_OUT | FF_MEDIA_IO, resp_write_scat,
748 	    NULL, {16,  0x12, 0xf9, 0x0, 0xff, 0xff, 0, 0, 0xff, 0xff, 0xff,
749 	    0xff, 0xff, 0xff, 0xff, 0xc7} },  /* SA_OUT(16), WRITE SCAT(16) */
750 	{ARRAY_SIZE(maint_in_iarr), 0xa3, 0xa, F_SA_LOW | F_D_IN,
751 	    resp_report_tgtpgs,	/* MAINT IN, REPORT TARGET PORT GROUPS */
752 		maint_in_iarr, {12,  0xea, 0, 0, 0, 0, 0xff, 0xff, 0xff,
753 				0xff, 0, 0xc7, 0, 0, 0, 0} },
754 /* 15 */
755 	{0, 0, 0, F_INV_OP | FF_RESPOND, NULL, NULL, /* MAINT OUT */
756 	    {0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
757 	{ARRAY_SIZE(verify_iarr), 0x8f, 0,
758 	    F_D_OUT_MAYBE | FF_MEDIA_IO, resp_verify,	/* VERIFY(16) */
759 	    verify_iarr, {16,  0xf6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
760 			  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0xc7} },
761 	{ARRAY_SIZE(vl_iarr), 0x7f, 0x9, F_SA_HIGH | F_D_IN | FF_MEDIA_IO,
762 	    resp_read_dt0, vl_iarr,	/* VARIABLE LENGTH, READ(32) */
763 	    {32,  0xc7, 0, 0, 0, 0, 0x3f, 0x18, 0x0, 0x9, 0xfe, 0, 0xff, 0xff,
764 	     0xff, 0xff} },
765 	{ARRAY_SIZE(reserve_iarr), 0x56, 0, F_D_OUT,
766 	    NULL, reserve_iarr,	/* RESERVE(10) <no response function> */
767 	    {10,  0xff, 0xff, 0xff, 0, 0, 0, 0xff, 0xff, 0xc7, 0, 0, 0, 0, 0,
768 	     0} },
769 	{ARRAY_SIZE(release_iarr), 0x57, 0, F_D_OUT,
770 	    NULL, release_iarr, /* RELEASE(10) <no response function> */
771 	    {10,  0x13, 0xff, 0xff, 0, 0, 0, 0xff, 0xff, 0xc7, 0, 0, 0, 0, 0,
772 	     0} },
773 /* 20 */
774 	{0, 0x1e, 0, 0, NULL, NULL, /* ALLOW REMOVAL */
775 	    {6,  0, 0, 0, 0x3, 0xc7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
776 	{0, 0x1, 0, 0, resp_start_stop, NULL, /* REWIND ?? */
777 	    {6,  0x1, 0, 0, 0, 0xc7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
778 	{0, 0, 0, F_INV_OP | FF_RESPOND, NULL, NULL, /* ATA_PT */
779 	    {0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
780 	{0, 0x1d, F_D_OUT, 0, NULL, NULL,	/* SEND DIAGNOSTIC */
781 	    {6,  0xf7, 0, 0xff, 0xff, 0xc7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
782 	{0, 0x42, 0, F_D_OUT | FF_MEDIA_IO, resp_unmap, NULL, /* UNMAP */
783 	    {10,  0x1, 0, 0, 0, 0, 0x3f, 0xff, 0xff, 0xc7, 0, 0, 0, 0, 0, 0} },
784 /* 25 */
785 	{0, 0x3b, 0, F_D_OUT_MAYBE, resp_write_buffer, NULL,
786 	    {10,  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc7, 0, 0,
787 	     0, 0, 0, 0} },			/* WRITE_BUFFER */
788 	{ARRAY_SIZE(write_same_iarr), 0x41, 0, F_D_OUT_MAYBE | FF_MEDIA_IO,
789 	    resp_write_same_10, write_same_iarr,	/* WRITE SAME(10) */
790 		{10,  0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0xff, 0xff, 0xc7, 0,
791 		 0, 0, 0, 0, 0} },
792 	{ARRAY_SIZE(sync_cache_iarr), 0x35, 0, F_SYNC_DELAY | F_M_ACCESS,
793 	    resp_sync_cache, sync_cache_iarr,
794 	    {10,  0x7, 0xff, 0xff, 0xff, 0xff, 0x3f, 0xff, 0xff, 0xc7, 0, 0,
795 	     0, 0, 0, 0} },			/* SYNC_CACHE (10) */
796 	{0, 0x89, 0, F_D_OUT | FF_MEDIA_IO, resp_comp_write, NULL,
797 	    {16,  0xf8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0, 0,
798 	     0, 0xff, 0x3f, 0xc7} },		/* COMPARE AND WRITE */
799 	{ARRAY_SIZE(pre_fetch_iarr), 0x34, 0, F_SYNC_DELAY | FF_MEDIA_IO,
800 	    resp_pre_fetch, pre_fetch_iarr,
801 	    {10,  0x2, 0xff, 0xff, 0xff, 0xff, 0x3f, 0xff, 0xff, 0xc7, 0, 0,
802 	     0, 0, 0, 0} },			/* PRE-FETCH (10) */
803 
804 /* 30 */
805 	{ARRAY_SIZE(zone_out_iarr), 0x94, 0x3, F_SA_LOW | F_M_ACCESS,
806 	    resp_open_zone, zone_out_iarr, /* ZONE_OUT(16), OPEN ZONE) */
807 		{16,  0x3 /* SA */, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
808 		 0xff, 0xff, 0x0, 0x0, 0xff, 0xff, 0x1, 0xc7} },
809 	{ARRAY_SIZE(zone_in_iarr), 0x95, 0x0, F_SA_LOW | F_M_ACCESS,
810 	    resp_report_zones, zone_in_iarr, /* ZONE_IN(16), REPORT ZONES) */
811 		{16,  0x0 /* SA */, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
812 		 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xbf, 0xc7} },
813 /* 31 */
814 	{0, 0x0, 0x0, F_D_OUT | FF_MEDIA_IO,
815 	    resp_atomic_write, NULL, /* ATOMIC WRITE 16 */
816 		{16,  0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
817 		 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff} },
818 /* sentinel */
819 	{0xff, 0, 0, 0, NULL, NULL,		/* terminating element */
820 	    {0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} },
821 };
822 
823 static int sdebug_num_hosts;
824 static int sdebug_add_host = DEF_NUM_HOST;  /* in sysfs this is relative */
825 static int sdebug_ato = DEF_ATO;
826 static int sdebug_cdb_len = DEF_CDB_LEN;
827 static int sdebug_jdelay = DEF_JDELAY;	/* if > 0 then unit is jiffies */
828 static int sdebug_dev_size_mb = DEF_DEV_SIZE_PRE_INIT;
829 static int sdebug_dif = DEF_DIF;
830 static int sdebug_dix = DEF_DIX;
831 static int sdebug_dsense = DEF_D_SENSE;
832 static int sdebug_every_nth = DEF_EVERY_NTH;
833 static int sdebug_fake_rw = DEF_FAKE_RW;
834 static unsigned int sdebug_guard = DEF_GUARD;
835 static int sdebug_host_max_queue;	/* per host */
836 static int sdebug_lowest_aligned = DEF_LOWEST_ALIGNED;
837 static int sdebug_max_luns = DEF_MAX_LUNS;
838 static int sdebug_max_queue = SDEBUG_CANQUEUE;	/* per submit queue */
839 static unsigned int sdebug_medium_error_start = OPT_MEDIUM_ERR_ADDR;
840 static int sdebug_medium_error_count = OPT_MEDIUM_ERR_NUM;
841 static int sdebug_ndelay = DEF_NDELAY;	/* if > 0 then unit is nanoseconds */
842 static int sdebug_no_lun_0 = DEF_NO_LUN_0;
843 static int sdebug_no_uld;
844 static int sdebug_num_parts = DEF_NUM_PARTS;
845 static int sdebug_num_tgts = DEF_NUM_TGTS; /* targets per host */
846 static int sdebug_opt_blks = DEF_OPT_BLKS;
847 static int sdebug_opts = DEF_OPTS;
848 static int sdebug_physblk_exp = DEF_PHYSBLK_EXP;
849 static int sdebug_opt_xferlen_exp = DEF_OPT_XFERLEN_EXP;
850 static int sdebug_ptype = DEF_PTYPE; /* SCSI peripheral device type */
851 static int sdebug_scsi_level = DEF_SCSI_LEVEL;
852 static int sdebug_sector_size = DEF_SECTOR_SIZE;
853 static int sdeb_tur_ms_to_ready = DEF_TUR_MS_TO_READY;
854 static int sdebug_virtual_gb = DEF_VIRTUAL_GB;
855 static int sdebug_vpd_use_hostno = DEF_VPD_USE_HOSTNO;
856 static unsigned int sdebug_lbpu = DEF_LBPU;
857 static unsigned int sdebug_lbpws = DEF_LBPWS;
858 static unsigned int sdebug_lbpws10 = DEF_LBPWS10;
859 static unsigned int sdebug_lbprz = DEF_LBPRZ;
860 static unsigned int sdebug_unmap_alignment = DEF_UNMAP_ALIGNMENT;
861 static unsigned int sdebug_unmap_granularity = DEF_UNMAP_GRANULARITY;
862 static unsigned int sdebug_unmap_max_blocks = DEF_UNMAP_MAX_BLOCKS;
863 static unsigned int sdebug_unmap_max_desc = DEF_UNMAP_MAX_DESC;
864 static unsigned int sdebug_write_same_length = DEF_WRITESAME_LENGTH;
865 static unsigned int sdebug_atomic_wr = DEF_ATOMIC_WR;
866 static unsigned int sdebug_atomic_wr_max_length = DEF_ATOMIC_WR_MAX_LENGTH;
867 static unsigned int sdebug_atomic_wr_align = DEF_ATOMIC_WR_ALIGN;
868 static unsigned int sdebug_atomic_wr_gran = DEF_ATOMIC_WR_GRAN;
869 static unsigned int sdebug_atomic_wr_max_length_bndry =
870 			DEF_ATOMIC_WR_MAX_LENGTH_BNDRY;
871 static unsigned int sdebug_atomic_wr_max_bndry = DEF_ATOMIC_WR_MAX_BNDRY;
872 static int sdebug_uuid_ctl = DEF_UUID_CTL;
873 static bool sdebug_random = DEF_RANDOM;
874 static bool sdebug_per_host_store = DEF_PER_HOST_STORE;
875 static bool sdebug_removable = DEF_REMOVABLE;
876 static bool sdebug_clustering;
877 static bool sdebug_host_lock = DEF_HOST_LOCK;
878 static bool sdebug_strict = DEF_STRICT;
879 static bool sdebug_any_injecting_opt;
880 static bool sdebug_no_rwlock;
881 static bool sdebug_verbose;
882 static bool have_dif_prot;
883 static bool write_since_sync;
884 static bool sdebug_statistics = DEF_STATISTICS;
885 static bool sdebug_wp;
886 static bool sdebug_allow_restart;
887 static enum {
888 	BLK_ZONED_NONE	= 0,
889 	BLK_ZONED_HA	= 1,
890 	BLK_ZONED_HM	= 2,
891 } sdeb_zbc_model = BLK_ZONED_NONE;
892 static char *sdeb_zbc_model_s;
893 
894 enum sam_lun_addr_method {SAM_LUN_AM_PERIPHERAL = 0x0,
895 			  SAM_LUN_AM_FLAT = 0x1,
896 			  SAM_LUN_AM_LOGICAL_UNIT = 0x2,
897 			  SAM_LUN_AM_EXTENDED = 0x3};
898 static enum sam_lun_addr_method sdebug_lun_am = SAM_LUN_AM_PERIPHERAL;
899 static int sdebug_lun_am_i = (int)SAM_LUN_AM_PERIPHERAL;
900 
901 static unsigned int sdebug_store_sectors;
902 static sector_t sdebug_capacity;	/* in sectors */
903 
904 /* old BIOS stuff, kernel may get rid of them but some mode sense pages
905    may still need them */
906 static int sdebug_heads;		/* heads per disk */
907 static int sdebug_cylinders_per;	/* cylinders per surface */
908 static int sdebug_sectors_per;		/* sectors per cylinder */
909 
910 static LIST_HEAD(sdebug_host_list);
911 static DEFINE_MUTEX(sdebug_host_list_mutex);
912 
913 static struct xarray per_store_arr;
914 static struct xarray *per_store_ap = &per_store_arr;
915 static int sdeb_first_idx = -1;		/* invalid index ==> none created */
916 static int sdeb_most_recent_idx = -1;
917 static DEFINE_RWLOCK(sdeb_fake_rw_lck);	/* need a RW lock when fake_rw=1 */
918 
919 static unsigned long map_size;
920 static int num_aborts;
921 static int num_dev_resets;
922 static int num_target_resets;
923 static int num_bus_resets;
924 static int num_host_resets;
925 static int dix_writes;
926 static int dix_reads;
927 static int dif_errors;
928 
929 /* ZBC global data */
930 static bool sdeb_zbc_in_use;	/* true for host-aware and host-managed disks */
931 static int sdeb_zbc_zone_cap_mb;
932 static int sdeb_zbc_zone_size_mb;
933 static int sdeb_zbc_max_open = DEF_ZBC_MAX_OPEN_ZONES;
934 static int sdeb_zbc_nr_conv = DEF_ZBC_NR_CONV_ZONES;
935 
936 static int submit_queues = DEF_SUBMIT_QUEUES;  /* > 1 for multi-queue (mq) */
937 static int poll_queues; /* iouring iopoll interface.*/
938 
939 static atomic_long_t writes_by_group_number[64];
940 
941 static char sdebug_proc_name[] = MY_NAME;
942 static const char *my_name = MY_NAME;
943 
944 static const struct bus_type pseudo_lld_bus;
945 
946 static struct device_driver sdebug_driverfs_driver = {
947 	.name 		= sdebug_proc_name,
948 	.bus		= &pseudo_lld_bus,
949 };
950 
951 static const int check_condition_result =
952 	SAM_STAT_CHECK_CONDITION;
953 
954 static const int illegal_condition_result =
955 	(DID_ABORT << 16) | SAM_STAT_CHECK_CONDITION;
956 
957 static const int device_qfull_result =
958 	(DID_ABORT << 16) | SAM_STAT_TASK_SET_FULL;
959 
960 static const int condition_met_result = SAM_STAT_CONDITION_MET;
961 
962 static struct dentry *sdebug_debugfs_root;
963 
964 static void sdebug_err_free(struct rcu_head *head)
965 {
966 	struct sdebug_err_inject *inject =
967 		container_of(head, typeof(*inject), rcu);
968 
969 	kfree(inject);
970 }
971 
972 static void sdebug_err_add(struct scsi_device *sdev, struct sdebug_err_inject *new)
973 {
974 	struct sdebug_dev_info *devip = (struct sdebug_dev_info *)sdev->hostdata;
975 	struct sdebug_err_inject *err;
976 
977 	spin_lock(&devip->list_lock);
978 	list_for_each_entry_rcu(err, &devip->inject_err_list, list) {
979 		if (err->type == new->type && err->cmd == new->cmd) {
980 			list_del_rcu(&err->list);
981 			call_rcu(&err->rcu, sdebug_err_free);
982 		}
983 	}
984 
985 	list_add_tail_rcu(&new->list, &devip->inject_err_list);
986 	spin_unlock(&devip->list_lock);
987 }
988 
989 static int sdebug_err_remove(struct scsi_device *sdev, const char *buf, size_t count)
990 {
991 	struct sdebug_dev_info *devip = (struct sdebug_dev_info *)sdev->hostdata;
992 	struct sdebug_err_inject *err;
993 	int type;
994 	unsigned char cmd;
995 
996 	if (sscanf(buf, "- %d %hhx", &type, &cmd) != 2) {
997 		kfree(buf);
998 		return -EINVAL;
999 	}
1000 
1001 	spin_lock(&devip->list_lock);
1002 	list_for_each_entry_rcu(err, &devip->inject_err_list, list) {
1003 		if (err->type == type && err->cmd == cmd) {
1004 			list_del_rcu(&err->list);
1005 			call_rcu(&err->rcu, sdebug_err_free);
1006 			spin_unlock(&devip->list_lock);
1007 			kfree(buf);
1008 			return count;
1009 		}
1010 	}
1011 	spin_unlock(&devip->list_lock);
1012 
1013 	kfree(buf);
1014 	return -EINVAL;
1015 }
1016 
1017 static int sdebug_error_show(struct seq_file *m, void *p)
1018 {
1019 	struct scsi_device *sdev = (struct scsi_device *)m->private;
1020 	struct sdebug_dev_info *devip = (struct sdebug_dev_info *)sdev->hostdata;
1021 	struct sdebug_err_inject *err;
1022 
1023 	seq_puts(m, "Type\tCount\tCommand\n");
1024 
1025 	rcu_read_lock();
1026 	list_for_each_entry_rcu(err, &devip->inject_err_list, list) {
1027 		switch (err->type) {
1028 		case ERR_TMOUT_CMD:
1029 		case ERR_ABORT_CMD_FAILED:
1030 		case ERR_LUN_RESET_FAILED:
1031 			seq_printf(m, "%d\t%d\t0x%x\n", err->type, err->cnt,
1032 				err->cmd);
1033 		break;
1034 
1035 		case ERR_FAIL_QUEUE_CMD:
1036 			seq_printf(m, "%d\t%d\t0x%x\t0x%x\n", err->type,
1037 				err->cnt, err->cmd, err->queuecmd_ret);
1038 		break;
1039 
1040 		case ERR_FAIL_CMD:
1041 			seq_printf(m, "%d\t%d\t0x%x\t0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\n",
1042 				err->type, err->cnt, err->cmd,
1043 				err->host_byte, err->driver_byte,
1044 				err->status_byte, err->sense_key,
1045 				err->asc, err->asq);
1046 		break;
1047 		}
1048 	}
1049 	rcu_read_unlock();
1050 
1051 	return 0;
1052 }
1053 
1054 static int sdebug_error_open(struct inode *inode, struct file *file)
1055 {
1056 	return single_open(file, sdebug_error_show, inode->i_private);
1057 }
1058 
1059 static ssize_t sdebug_error_write(struct file *file, const char __user *ubuf,
1060 		size_t count, loff_t *ppos)
1061 {
1062 	char *buf;
1063 	unsigned int inject_type;
1064 	struct sdebug_err_inject *inject;
1065 	struct scsi_device *sdev = (struct scsi_device *)file->f_inode->i_private;
1066 
1067 	buf = kzalloc(count + 1, GFP_KERNEL);
1068 	if (!buf)
1069 		return -ENOMEM;
1070 
1071 	if (copy_from_user(buf, ubuf, count)) {
1072 		kfree(buf);
1073 		return -EFAULT;
1074 	}
1075 
1076 	if (buf[0] == '-')
1077 		return sdebug_err_remove(sdev, buf, count);
1078 
1079 	if (sscanf(buf, "%d", &inject_type) != 1) {
1080 		kfree(buf);
1081 		return -EINVAL;
1082 	}
1083 
1084 	inject = kzalloc(sizeof(struct sdebug_err_inject), GFP_KERNEL);
1085 	if (!inject) {
1086 		kfree(buf);
1087 		return -ENOMEM;
1088 	}
1089 
1090 	switch (inject_type) {
1091 	case ERR_TMOUT_CMD:
1092 	case ERR_ABORT_CMD_FAILED:
1093 	case ERR_LUN_RESET_FAILED:
1094 		if (sscanf(buf, "%d %d %hhx", &inject->type, &inject->cnt,
1095 			   &inject->cmd) != 3)
1096 			goto out_error;
1097 	break;
1098 
1099 	case ERR_FAIL_QUEUE_CMD:
1100 		if (sscanf(buf, "%d %d %hhx %x", &inject->type, &inject->cnt,
1101 			   &inject->cmd, &inject->queuecmd_ret) != 4)
1102 			goto out_error;
1103 	break;
1104 
1105 	case ERR_FAIL_CMD:
1106 		if (sscanf(buf, "%d %d %hhx %hhx %hhx %hhx %hhx %hhx %hhx",
1107 			   &inject->type, &inject->cnt, &inject->cmd,
1108 			   &inject->host_byte, &inject->driver_byte,
1109 			   &inject->status_byte, &inject->sense_key,
1110 			   &inject->asc, &inject->asq) != 9)
1111 			goto out_error;
1112 	break;
1113 
1114 	default:
1115 		goto out_error;
1116 	break;
1117 	}
1118 
1119 	kfree(buf);
1120 	sdebug_err_add(sdev, inject);
1121 
1122 	return count;
1123 
1124 out_error:
1125 	kfree(buf);
1126 	kfree(inject);
1127 	return -EINVAL;
1128 }
1129 
1130 static const struct file_operations sdebug_error_fops = {
1131 	.open	= sdebug_error_open,
1132 	.read	= seq_read,
1133 	.write	= sdebug_error_write,
1134 	.release = single_release,
1135 };
1136 
1137 static int sdebug_target_reset_fail_show(struct seq_file *m, void *p)
1138 {
1139 	struct scsi_target *starget = (struct scsi_target *)m->private;
1140 	struct sdebug_target_info *targetip =
1141 		(struct sdebug_target_info *)starget->hostdata;
1142 
1143 	if (targetip)
1144 		seq_printf(m, "%c\n", targetip->reset_fail ? 'Y' : 'N');
1145 
1146 	return 0;
1147 }
1148 
1149 static int sdebug_target_reset_fail_open(struct inode *inode, struct file *file)
1150 {
1151 	return single_open(file, sdebug_target_reset_fail_show, inode->i_private);
1152 }
1153 
1154 static ssize_t sdebug_target_reset_fail_write(struct file *file,
1155 		const char __user *ubuf, size_t count, loff_t *ppos)
1156 {
1157 	int ret;
1158 	struct scsi_target *starget =
1159 		(struct scsi_target *)file->f_inode->i_private;
1160 	struct sdebug_target_info *targetip =
1161 		(struct sdebug_target_info *)starget->hostdata;
1162 
1163 	if (targetip) {
1164 		ret = kstrtobool_from_user(ubuf, count, &targetip->reset_fail);
1165 		return ret < 0 ? ret : count;
1166 	}
1167 	return -ENODEV;
1168 }
1169 
1170 static const struct file_operations sdebug_target_reset_fail_fops = {
1171 	.open	= sdebug_target_reset_fail_open,
1172 	.read	= seq_read,
1173 	.write	= sdebug_target_reset_fail_write,
1174 	.release = single_release,
1175 };
1176 
1177 static int sdebug_target_alloc(struct scsi_target *starget)
1178 {
1179 	struct sdebug_target_info *targetip;
1180 
1181 	targetip = kzalloc(sizeof(struct sdebug_target_info), GFP_KERNEL);
1182 	if (!targetip)
1183 		return -ENOMEM;
1184 
1185 	targetip->debugfs_entry = debugfs_create_dir(dev_name(&starget->dev),
1186 				sdebug_debugfs_root);
1187 
1188 	debugfs_create_file("fail_reset", 0600, targetip->debugfs_entry, starget,
1189 				&sdebug_target_reset_fail_fops);
1190 
1191 	starget->hostdata = targetip;
1192 
1193 	return 0;
1194 }
1195 
1196 static void sdebug_tartget_cleanup_async(void *data, async_cookie_t cookie)
1197 {
1198 	struct sdebug_target_info *targetip = data;
1199 
1200 	debugfs_remove(targetip->debugfs_entry);
1201 	kfree(targetip);
1202 }
1203 
1204 static void sdebug_target_destroy(struct scsi_target *starget)
1205 {
1206 	struct sdebug_target_info *targetip;
1207 
1208 	targetip = (struct sdebug_target_info *)starget->hostdata;
1209 	if (targetip) {
1210 		starget->hostdata = NULL;
1211 		async_schedule(sdebug_tartget_cleanup_async, targetip);
1212 	}
1213 }
1214 
1215 /* Only do the extra work involved in logical block provisioning if one or
1216  * more of the lbpu, lbpws or lbpws10 parameters are given and we are doing
1217  * real reads and writes (i.e. not skipping them for speed).
1218  */
1219 static inline bool scsi_debug_lbp(void)
1220 {
1221 	return 0 == sdebug_fake_rw &&
1222 		(sdebug_lbpu || sdebug_lbpws || sdebug_lbpws10);
1223 }
1224 
1225 static inline bool scsi_debug_atomic_write(void)
1226 {
1227 	return sdebug_fake_rw == 0 && sdebug_atomic_wr;
1228 }
1229 
1230 static void *lba2fake_store(struct sdeb_store_info *sip,
1231 			    unsigned long long lba)
1232 {
1233 	struct sdeb_store_info *lsip = sip;
1234 
1235 	lba = do_div(lba, sdebug_store_sectors);
1236 	if (!sip || !sip->storep) {
1237 		WARN_ON_ONCE(true);
1238 		lsip = xa_load(per_store_ap, 0);  /* should never be NULL */
1239 	}
1240 	return lsip->storep + lba * sdebug_sector_size;
1241 }
1242 
1243 static struct t10_pi_tuple *dif_store(struct sdeb_store_info *sip,
1244 				      sector_t sector)
1245 {
1246 	sector = sector_div(sector, sdebug_store_sectors);
1247 
1248 	return sip->dif_storep + sector;
1249 }
1250 
1251 static void sdebug_max_tgts_luns(void)
1252 {
1253 	struct sdebug_host_info *sdbg_host;
1254 	struct Scsi_Host *hpnt;
1255 
1256 	mutex_lock(&sdebug_host_list_mutex);
1257 	list_for_each_entry(sdbg_host, &sdebug_host_list, host_list) {
1258 		hpnt = sdbg_host->shost;
1259 		if ((hpnt->this_id >= 0) &&
1260 		    (sdebug_num_tgts > hpnt->this_id))
1261 			hpnt->max_id = sdebug_num_tgts + 1;
1262 		else
1263 			hpnt->max_id = sdebug_num_tgts;
1264 		/* sdebug_max_luns; */
1265 		hpnt->max_lun = SCSI_W_LUN_REPORT_LUNS + 1;
1266 	}
1267 	mutex_unlock(&sdebug_host_list_mutex);
1268 }
1269 
1270 enum sdeb_cmd_data {SDEB_IN_DATA = 0, SDEB_IN_CDB = 1};
1271 
1272 /* Set in_bit to -1 to indicate no bit position of invalid field */
1273 static void mk_sense_invalid_fld(struct scsi_cmnd *scp,
1274 				 enum sdeb_cmd_data c_d,
1275 				 int in_byte, int in_bit)
1276 {
1277 	unsigned char *sbuff;
1278 	u8 sks[4];
1279 	int sl, asc;
1280 
1281 	sbuff = scp->sense_buffer;
1282 	if (!sbuff) {
1283 		sdev_printk(KERN_ERR, scp->device,
1284 			    "%s: sense_buffer is NULL\n", __func__);
1285 		return;
1286 	}
1287 	asc = c_d ? INVALID_FIELD_IN_CDB : INVALID_FIELD_IN_PARAM_LIST;
1288 	memset(sbuff, 0, SCSI_SENSE_BUFFERSIZE);
1289 	scsi_build_sense(scp, sdebug_dsense, ILLEGAL_REQUEST, asc, 0);
1290 	memset(sks, 0, sizeof(sks));
1291 	sks[0] = 0x80;
1292 	if (c_d)
1293 		sks[0] |= 0x40;
1294 	if (in_bit >= 0) {
1295 		sks[0] |= 0x8;
1296 		sks[0] |= 0x7 & in_bit;
1297 	}
1298 	put_unaligned_be16(in_byte, sks + 1);
1299 	if (sdebug_dsense) {
1300 		sl = sbuff[7] + 8;
1301 		sbuff[7] = sl;
1302 		sbuff[sl] = 0x2;
1303 		sbuff[sl + 1] = 0x6;
1304 		memcpy(sbuff + sl + 4, sks, 3);
1305 	} else
1306 		memcpy(sbuff + 15, sks, 3);
1307 	if (sdebug_verbose)
1308 		sdev_printk(KERN_INFO, scp->device, "%s:  [sense_key,asc,ascq"
1309 			    "]: [0x5,0x%x,0x0] %c byte=%d, bit=%d\n",
1310 			    my_name, asc, c_d ? 'C' : 'D', in_byte, in_bit);
1311 }
1312 
1313 static void mk_sense_buffer(struct scsi_cmnd *scp, int key, int asc, int asq)
1314 {
1315 	if (!scp->sense_buffer) {
1316 		sdev_printk(KERN_ERR, scp->device,
1317 			    "%s: sense_buffer is NULL\n", __func__);
1318 		return;
1319 	}
1320 	memset(scp->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
1321 
1322 	scsi_build_sense(scp, sdebug_dsense, key, asc, asq);
1323 
1324 	if (sdebug_verbose)
1325 		sdev_printk(KERN_INFO, scp->device,
1326 			    "%s:  [sense_key,asc,ascq]: [0x%x,0x%x,0x%x]\n",
1327 			    my_name, key, asc, asq);
1328 }
1329 
1330 static void mk_sense_invalid_opcode(struct scsi_cmnd *scp)
1331 {
1332 	mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_OPCODE, 0);
1333 }
1334 
1335 static int scsi_debug_ioctl(struct scsi_device *dev, unsigned int cmd,
1336 			    void __user *arg)
1337 {
1338 	if (sdebug_verbose) {
1339 		if (0x1261 == cmd)
1340 			sdev_printk(KERN_INFO, dev,
1341 				    "%s: BLKFLSBUF [0x1261]\n", __func__);
1342 		else if (0x5331 == cmd)
1343 			sdev_printk(KERN_INFO, dev,
1344 				    "%s: CDROM_GET_CAPABILITY [0x5331]\n",
1345 				    __func__);
1346 		else
1347 			sdev_printk(KERN_INFO, dev, "%s: cmd=0x%x\n",
1348 				    __func__, cmd);
1349 	}
1350 	return -EINVAL;
1351 	/* return -ENOTTY; // correct return but upsets fdisk */
1352 }
1353 
1354 static void config_cdb_len(struct scsi_device *sdev)
1355 {
1356 	switch (sdebug_cdb_len) {
1357 	case 6:	/* suggest 6 byte READ, WRITE and MODE SENSE/SELECT */
1358 		sdev->use_10_for_rw = false;
1359 		sdev->use_16_for_rw = false;
1360 		sdev->use_10_for_ms = false;
1361 		break;
1362 	case 10: /* suggest 10 byte RWs and 6 byte MODE SENSE/SELECT */
1363 		sdev->use_10_for_rw = true;
1364 		sdev->use_16_for_rw = false;
1365 		sdev->use_10_for_ms = false;
1366 		break;
1367 	case 12: /* suggest 10 byte RWs and 10 byte MODE SENSE/SELECT */
1368 		sdev->use_10_for_rw = true;
1369 		sdev->use_16_for_rw = false;
1370 		sdev->use_10_for_ms = true;
1371 		break;
1372 	case 16:
1373 		sdev->use_10_for_rw = false;
1374 		sdev->use_16_for_rw = true;
1375 		sdev->use_10_for_ms = true;
1376 		break;
1377 	case 32: /* No knobs to suggest this so same as 16 for now */
1378 		sdev->use_10_for_rw = false;
1379 		sdev->use_16_for_rw = true;
1380 		sdev->use_10_for_ms = true;
1381 		break;
1382 	default:
1383 		pr_warn("unexpected cdb_len=%d, force to 10\n",
1384 			sdebug_cdb_len);
1385 		sdev->use_10_for_rw = true;
1386 		sdev->use_16_for_rw = false;
1387 		sdev->use_10_for_ms = false;
1388 		sdebug_cdb_len = 10;
1389 		break;
1390 	}
1391 }
1392 
1393 static void all_config_cdb_len(void)
1394 {
1395 	struct sdebug_host_info *sdbg_host;
1396 	struct Scsi_Host *shost;
1397 	struct scsi_device *sdev;
1398 
1399 	mutex_lock(&sdebug_host_list_mutex);
1400 	list_for_each_entry(sdbg_host, &sdebug_host_list, host_list) {
1401 		shost = sdbg_host->shost;
1402 		shost_for_each_device(sdev, shost) {
1403 			config_cdb_len(sdev);
1404 		}
1405 	}
1406 	mutex_unlock(&sdebug_host_list_mutex);
1407 }
1408 
1409 static void clear_luns_changed_on_target(struct sdebug_dev_info *devip)
1410 {
1411 	struct sdebug_host_info *sdhp = devip->sdbg_host;
1412 	struct sdebug_dev_info *dp;
1413 
1414 	list_for_each_entry(dp, &sdhp->dev_info_list, dev_list) {
1415 		if ((devip->sdbg_host == dp->sdbg_host) &&
1416 		    (devip->target == dp->target)) {
1417 			clear_bit(SDEBUG_UA_LUNS_CHANGED, dp->uas_bm);
1418 		}
1419 	}
1420 }
1421 
1422 static int make_ua(struct scsi_cmnd *scp, struct sdebug_dev_info *devip)
1423 {
1424 	int k;
1425 
1426 	k = find_first_bit(devip->uas_bm, SDEBUG_NUM_UAS);
1427 	if (k != SDEBUG_NUM_UAS) {
1428 		const char *cp = NULL;
1429 
1430 		switch (k) {
1431 		case SDEBUG_UA_POR:
1432 			mk_sense_buffer(scp, UNIT_ATTENTION, UA_RESET_ASC,
1433 					POWER_ON_RESET_ASCQ);
1434 			if (sdebug_verbose)
1435 				cp = "power on reset";
1436 			break;
1437 		case SDEBUG_UA_POOCCUR:
1438 			mk_sense_buffer(scp, UNIT_ATTENTION, UA_RESET_ASC,
1439 					POWER_ON_OCCURRED_ASCQ);
1440 			if (sdebug_verbose)
1441 				cp = "power on occurred";
1442 			break;
1443 		case SDEBUG_UA_BUS_RESET:
1444 			mk_sense_buffer(scp, UNIT_ATTENTION, UA_RESET_ASC,
1445 					BUS_RESET_ASCQ);
1446 			if (sdebug_verbose)
1447 				cp = "bus reset";
1448 			break;
1449 		case SDEBUG_UA_MODE_CHANGED:
1450 			mk_sense_buffer(scp, UNIT_ATTENTION, UA_CHANGED_ASC,
1451 					MODE_CHANGED_ASCQ);
1452 			if (sdebug_verbose)
1453 				cp = "mode parameters changed";
1454 			break;
1455 		case SDEBUG_UA_CAPACITY_CHANGED:
1456 			mk_sense_buffer(scp, UNIT_ATTENTION, UA_CHANGED_ASC,
1457 					CAPACITY_CHANGED_ASCQ);
1458 			if (sdebug_verbose)
1459 				cp = "capacity data changed";
1460 			break;
1461 		case SDEBUG_UA_MICROCODE_CHANGED:
1462 			mk_sense_buffer(scp, UNIT_ATTENTION,
1463 					TARGET_CHANGED_ASC,
1464 					MICROCODE_CHANGED_ASCQ);
1465 			if (sdebug_verbose)
1466 				cp = "microcode has been changed";
1467 			break;
1468 		case SDEBUG_UA_MICROCODE_CHANGED_WO_RESET:
1469 			mk_sense_buffer(scp, UNIT_ATTENTION,
1470 					TARGET_CHANGED_ASC,
1471 					MICROCODE_CHANGED_WO_RESET_ASCQ);
1472 			if (sdebug_verbose)
1473 				cp = "microcode has been changed without reset";
1474 			break;
1475 		case SDEBUG_UA_LUNS_CHANGED:
1476 			/*
1477 			 * SPC-3 behavior is to report a UNIT ATTENTION with
1478 			 * ASC/ASCQ REPORTED LUNS DATA HAS CHANGED on every LUN
1479 			 * on the target, until a REPORT LUNS command is
1480 			 * received.  SPC-4 behavior is to report it only once.
1481 			 * NOTE:  sdebug_scsi_level does not use the same
1482 			 * values as struct scsi_device->scsi_level.
1483 			 */
1484 			if (sdebug_scsi_level >= 6)	/* SPC-4 and above */
1485 				clear_luns_changed_on_target(devip);
1486 			mk_sense_buffer(scp, UNIT_ATTENTION,
1487 					TARGET_CHANGED_ASC,
1488 					LUNS_CHANGED_ASCQ);
1489 			if (sdebug_verbose)
1490 				cp = "reported luns data has changed";
1491 			break;
1492 		default:
1493 			pr_warn("unexpected unit attention code=%d\n", k);
1494 			if (sdebug_verbose)
1495 				cp = "unknown";
1496 			break;
1497 		}
1498 		clear_bit(k, devip->uas_bm);
1499 		if (sdebug_verbose)
1500 			sdev_printk(KERN_INFO, scp->device,
1501 				   "%s reports: Unit attention: %s\n",
1502 				   my_name, cp);
1503 		return check_condition_result;
1504 	}
1505 	return 0;
1506 }
1507 
1508 /* Build SCSI "data-in" buffer. Returns 0 if ok else (DID_ERROR << 16). */
1509 static int fill_from_dev_buffer(struct scsi_cmnd *scp, unsigned char *arr,
1510 				int arr_len)
1511 {
1512 	int act_len;
1513 	struct scsi_data_buffer *sdb = &scp->sdb;
1514 
1515 	if (!sdb->length)
1516 		return 0;
1517 	if (scp->sc_data_direction != DMA_FROM_DEVICE)
1518 		return DID_ERROR << 16;
1519 
1520 	act_len = sg_copy_from_buffer(sdb->table.sgl, sdb->table.nents,
1521 				      arr, arr_len);
1522 	scsi_set_resid(scp, scsi_bufflen(scp) - act_len);
1523 
1524 	return 0;
1525 }
1526 
1527 /* Partial build of SCSI "data-in" buffer. Returns 0 if ok else
1528  * (DID_ERROR << 16). Can write to offset in data-in buffer. If multiple
1529  * calls, not required to write in ascending offset order. Assumes resid
1530  * set to scsi_bufflen() prior to any calls.
1531  */
1532 static int p_fill_from_dev_buffer(struct scsi_cmnd *scp, const void *arr,
1533 				  int arr_len, unsigned int off_dst)
1534 {
1535 	unsigned int act_len, n;
1536 	struct scsi_data_buffer *sdb = &scp->sdb;
1537 	off_t skip = off_dst;
1538 
1539 	if (sdb->length <= off_dst)
1540 		return 0;
1541 	if (scp->sc_data_direction != DMA_FROM_DEVICE)
1542 		return DID_ERROR << 16;
1543 
1544 	act_len = sg_pcopy_from_buffer(sdb->table.sgl, sdb->table.nents,
1545 				       arr, arr_len, skip);
1546 	pr_debug("%s: off_dst=%u, scsi_bufflen=%u, act_len=%u, resid=%d\n",
1547 		 __func__, off_dst, scsi_bufflen(scp), act_len,
1548 		 scsi_get_resid(scp));
1549 	n = scsi_bufflen(scp) - (off_dst + act_len);
1550 	scsi_set_resid(scp, min_t(u32, scsi_get_resid(scp), n));
1551 	return 0;
1552 }
1553 
1554 /* Fetches from SCSI "data-out" buffer. Returns number of bytes fetched into
1555  * 'arr' or -1 if error.
1556  */
1557 static int fetch_to_dev_buffer(struct scsi_cmnd *scp, unsigned char *arr,
1558 			       int arr_len)
1559 {
1560 	if (!scsi_bufflen(scp))
1561 		return 0;
1562 	if (scp->sc_data_direction != DMA_TO_DEVICE)
1563 		return -1;
1564 
1565 	return scsi_sg_copy_to_buffer(scp, arr, arr_len);
1566 }
1567 
1568 
1569 static char sdebug_inq_vendor_id[9] = "Linux   ";
1570 static char sdebug_inq_product_id[17] = "scsi_debug      ";
1571 static char sdebug_inq_product_rev[5] = SDEBUG_VERSION;
1572 /* Use some locally assigned NAAs for SAS addresses. */
1573 static const u64 naa3_comp_a = 0x3222222000000000ULL;
1574 static const u64 naa3_comp_b = 0x3333333000000000ULL;
1575 static const u64 naa3_comp_c = 0x3111111000000000ULL;
1576 
1577 /* Device identification VPD page. Returns number of bytes placed in arr */
1578 static int inquiry_vpd_83(unsigned char *arr, int port_group_id,
1579 			  int target_dev_id, int dev_id_num,
1580 			  const char *dev_id_str, int dev_id_str_len,
1581 			  const uuid_t *lu_name)
1582 {
1583 	int num, port_a;
1584 	char b[32];
1585 
1586 	port_a = target_dev_id + 1;
1587 	/* T10 vendor identifier field format (faked) */
1588 	arr[0] = 0x2;	/* ASCII */
1589 	arr[1] = 0x1;
1590 	arr[2] = 0x0;
1591 	memcpy(&arr[4], sdebug_inq_vendor_id, 8);
1592 	memcpy(&arr[12], sdebug_inq_product_id, 16);
1593 	memcpy(&arr[28], dev_id_str, dev_id_str_len);
1594 	num = 8 + 16 + dev_id_str_len;
1595 	arr[3] = num;
1596 	num += 4;
1597 	if (dev_id_num >= 0) {
1598 		if (sdebug_uuid_ctl) {
1599 			/* Locally assigned UUID */
1600 			arr[num++] = 0x1;  /* binary (not necessarily sas) */
1601 			arr[num++] = 0xa;  /* PIV=0, lu, naa */
1602 			arr[num++] = 0x0;
1603 			arr[num++] = 0x12;
1604 			arr[num++] = 0x10; /* uuid type=1, locally assigned */
1605 			arr[num++] = 0x0;
1606 			memcpy(arr + num, lu_name, 16);
1607 			num += 16;
1608 		} else {
1609 			/* NAA-3, Logical unit identifier (binary) */
1610 			arr[num++] = 0x1;  /* binary (not necessarily sas) */
1611 			arr[num++] = 0x3;  /* PIV=0, lu, naa */
1612 			arr[num++] = 0x0;
1613 			arr[num++] = 0x8;
1614 			put_unaligned_be64(naa3_comp_b + dev_id_num, arr + num);
1615 			num += 8;
1616 		}
1617 		/* Target relative port number */
1618 		arr[num++] = 0x61;	/* proto=sas, binary */
1619 		arr[num++] = 0x94;	/* PIV=1, target port, rel port */
1620 		arr[num++] = 0x0;	/* reserved */
1621 		arr[num++] = 0x4;	/* length */
1622 		arr[num++] = 0x0;	/* reserved */
1623 		arr[num++] = 0x0;	/* reserved */
1624 		arr[num++] = 0x0;
1625 		arr[num++] = 0x1;	/* relative port A */
1626 	}
1627 	/* NAA-3, Target port identifier */
1628 	arr[num++] = 0x61;	/* proto=sas, binary */
1629 	arr[num++] = 0x93;	/* piv=1, target port, naa */
1630 	arr[num++] = 0x0;
1631 	arr[num++] = 0x8;
1632 	put_unaligned_be64(naa3_comp_a + port_a, arr + num);
1633 	num += 8;
1634 	/* NAA-3, Target port group identifier */
1635 	arr[num++] = 0x61;	/* proto=sas, binary */
1636 	arr[num++] = 0x95;	/* piv=1, target port group id */
1637 	arr[num++] = 0x0;
1638 	arr[num++] = 0x4;
1639 	arr[num++] = 0;
1640 	arr[num++] = 0;
1641 	put_unaligned_be16(port_group_id, arr + num);
1642 	num += 2;
1643 	/* NAA-3, Target device identifier */
1644 	arr[num++] = 0x61;	/* proto=sas, binary */
1645 	arr[num++] = 0xa3;	/* piv=1, target device, naa */
1646 	arr[num++] = 0x0;
1647 	arr[num++] = 0x8;
1648 	put_unaligned_be64(naa3_comp_a + target_dev_id, arr + num);
1649 	num += 8;
1650 	/* SCSI name string: Target device identifier */
1651 	arr[num++] = 0x63;	/* proto=sas, UTF-8 */
1652 	arr[num++] = 0xa8;	/* piv=1, target device, SCSI name string */
1653 	arr[num++] = 0x0;
1654 	arr[num++] = 24;
1655 	memcpy(arr + num, "naa.32222220", 12);
1656 	num += 12;
1657 	snprintf(b, sizeof(b), "%08X", target_dev_id);
1658 	memcpy(arr + num, b, 8);
1659 	num += 8;
1660 	memset(arr + num, 0, 4);
1661 	num += 4;
1662 	return num;
1663 }
1664 
1665 static unsigned char vpd84_data[] = {
1666 /* from 4th byte */ 0x22,0x22,0x22,0x0,0xbb,0x0,
1667     0x22,0x22,0x22,0x0,0xbb,0x1,
1668     0x22,0x22,0x22,0x0,0xbb,0x2,
1669 };
1670 
1671 /*  Software interface identification VPD page */
1672 static int inquiry_vpd_84(unsigned char *arr)
1673 {
1674 	memcpy(arr, vpd84_data, sizeof(vpd84_data));
1675 	return sizeof(vpd84_data);
1676 }
1677 
1678 /* Management network addresses VPD page */
1679 static int inquiry_vpd_85(unsigned char *arr)
1680 {
1681 	int num = 0;
1682 	const char *na1 = "https://www.kernel.org/config";
1683 	const char *na2 = "http://www.kernel.org/log";
1684 	int plen, olen;
1685 
1686 	arr[num++] = 0x1;	/* lu, storage config */
1687 	arr[num++] = 0x0;	/* reserved */
1688 	arr[num++] = 0x0;
1689 	olen = strlen(na1);
1690 	plen = olen + 1;
1691 	if (plen % 4)
1692 		plen = ((plen / 4) + 1) * 4;
1693 	arr[num++] = plen;	/* length, null termianted, padded */
1694 	memcpy(arr + num, na1, olen);
1695 	memset(arr + num + olen, 0, plen - olen);
1696 	num += plen;
1697 
1698 	arr[num++] = 0x4;	/* lu, logging */
1699 	arr[num++] = 0x0;	/* reserved */
1700 	arr[num++] = 0x0;
1701 	olen = strlen(na2);
1702 	plen = olen + 1;
1703 	if (plen % 4)
1704 		plen = ((plen / 4) + 1) * 4;
1705 	arr[num++] = plen;	/* length, null terminated, padded */
1706 	memcpy(arr + num, na2, olen);
1707 	memset(arr + num + olen, 0, plen - olen);
1708 	num += plen;
1709 
1710 	return num;
1711 }
1712 
1713 /* SCSI ports VPD page */
1714 static int inquiry_vpd_88(unsigned char *arr, int target_dev_id)
1715 {
1716 	int num = 0;
1717 	int port_a, port_b;
1718 
1719 	port_a = target_dev_id + 1;
1720 	port_b = port_a + 1;
1721 	arr[num++] = 0x0;	/* reserved */
1722 	arr[num++] = 0x0;	/* reserved */
1723 	arr[num++] = 0x0;
1724 	arr[num++] = 0x1;	/* relative port 1 (primary) */
1725 	memset(arr + num, 0, 6);
1726 	num += 6;
1727 	arr[num++] = 0x0;
1728 	arr[num++] = 12;	/* length tp descriptor */
1729 	/* naa-5 target port identifier (A) */
1730 	arr[num++] = 0x61;	/* proto=sas, binary */
1731 	arr[num++] = 0x93;	/* PIV=1, target port, NAA */
1732 	arr[num++] = 0x0;	/* reserved */
1733 	arr[num++] = 0x8;	/* length */
1734 	put_unaligned_be64(naa3_comp_a + port_a, arr + num);
1735 	num += 8;
1736 	arr[num++] = 0x0;	/* reserved */
1737 	arr[num++] = 0x0;	/* reserved */
1738 	arr[num++] = 0x0;
1739 	arr[num++] = 0x2;	/* relative port 2 (secondary) */
1740 	memset(arr + num, 0, 6);
1741 	num += 6;
1742 	arr[num++] = 0x0;
1743 	arr[num++] = 12;	/* length tp descriptor */
1744 	/* naa-5 target port identifier (B) */
1745 	arr[num++] = 0x61;	/* proto=sas, binary */
1746 	arr[num++] = 0x93;	/* PIV=1, target port, NAA */
1747 	arr[num++] = 0x0;	/* reserved */
1748 	arr[num++] = 0x8;	/* length */
1749 	put_unaligned_be64(naa3_comp_a + port_b, arr + num);
1750 	num += 8;
1751 
1752 	return num;
1753 }
1754 
1755 
1756 static unsigned char vpd89_data[] = {
1757 /* from 4th byte */ 0,0,0,0,
1758 'l','i','n','u','x',' ',' ',' ',
1759 'S','A','T',' ','s','c','s','i','_','d','e','b','u','g',' ',' ',
1760 '1','2','3','4',
1761 0x34,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
1762 0xec,0,0,0,
1763 0x5a,0xc,0xff,0x3f,0x37,0xc8,0x10,0,0,0,0,0,0x3f,0,0,0,
1764 0,0,0,0,0x58,0x58,0x58,0x58,0x58,0x58,0x58,0x58,0x20,0x20,0x20,0x20,
1765 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0,0,0,0x40,0x4,0,0x2e,0x33,
1766 0x38,0x31,0x20,0x20,0x20,0x20,0x54,0x53,0x38,0x33,0x30,0x30,0x33,0x31,
1767 0x53,0x41,
1768 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
1769 0x20,0x20,
1770 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
1771 0x10,0x80,
1772 0,0,0,0x2f,0,0,0,0x2,0,0x2,0x7,0,0xff,0xff,0x1,0,
1773 0x3f,0,0xc1,0xff,0x3e,0,0x10,0x1,0xb0,0xf8,0x50,0x9,0,0,0x7,0,
1774 0x3,0,0x78,0,0x78,0,0xf0,0,0x78,0,0,0,0,0,0,0,
1775 0,0,0,0,0,0,0,0,0x2,0,0,0,0,0,0,0,
1776 0x7e,0,0x1b,0,0x6b,0x34,0x1,0x7d,0x3,0x40,0x69,0x34,0x1,0x3c,0x3,0x40,
1777 0x7f,0x40,0,0,0,0,0xfe,0xfe,0,0,0,0,0,0xfe,0,0,
1778 0,0,0,0,0,0,0,0,0xb0,0xf8,0x50,0x9,0,0,0,0,
1779 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1780 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1781 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1782 0x1,0,0xb0,0xf8,0x50,0x9,0xb0,0xf8,0x50,0x9,0x20,0x20,0x2,0,0xb6,0x42,
1783 0,0x80,0x8a,0,0x6,0x3c,0xa,0x3c,0xff,0xff,0xc6,0x7,0,0x1,0,0x8,
1784 0xf0,0xf,0,0x10,0x2,0,0x30,0,0,0,0,0,0,0,0x6,0xfe,
1785 0,0,0x2,0,0x50,0,0x8a,0,0x4f,0x95,0,0,0x21,0,0xb,0,
1786 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1787 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1788 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1789 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1790 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1791 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1792 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1793 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1794 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1795 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1796 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1797 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0xa5,0x51,
1798 };
1799 
1800 /* ATA Information VPD page */
1801 static int inquiry_vpd_89(unsigned char *arr)
1802 {
1803 	memcpy(arr, vpd89_data, sizeof(vpd89_data));
1804 	return sizeof(vpd89_data);
1805 }
1806 
1807 
1808 static unsigned char vpdb0_data[] = {
1809 	/* from 4th byte */ 0,0,0,4, 0,0,0x4,0, 0,0,0,64,
1810 	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1811 	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1812 	0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1813 };
1814 
1815 /* Block limits VPD page (SBC-3) */
1816 static int inquiry_vpd_b0(unsigned char *arr)
1817 {
1818 	unsigned int gran;
1819 
1820 	memcpy(arr, vpdb0_data, sizeof(vpdb0_data));
1821 
1822 	/* Optimal transfer length granularity */
1823 	if (sdebug_opt_xferlen_exp != 0 &&
1824 	    sdebug_physblk_exp < sdebug_opt_xferlen_exp)
1825 		gran = 1 << sdebug_opt_xferlen_exp;
1826 	else
1827 		gran = 1 << sdebug_physblk_exp;
1828 	put_unaligned_be16(gran, arr + 2);
1829 
1830 	/* Maximum Transfer Length */
1831 	if (sdebug_store_sectors > 0x400)
1832 		put_unaligned_be32(sdebug_store_sectors, arr + 4);
1833 
1834 	/* Optimal Transfer Length */
1835 	put_unaligned_be32(sdebug_opt_blks, &arr[8]);
1836 
1837 	if (sdebug_lbpu) {
1838 		/* Maximum Unmap LBA Count */
1839 		put_unaligned_be32(sdebug_unmap_max_blocks, &arr[16]);
1840 
1841 		/* Maximum Unmap Block Descriptor Count */
1842 		put_unaligned_be32(sdebug_unmap_max_desc, &arr[20]);
1843 	}
1844 
1845 	/* Unmap Granularity Alignment */
1846 	if (sdebug_unmap_alignment) {
1847 		put_unaligned_be32(sdebug_unmap_alignment, &arr[28]);
1848 		arr[28] |= 0x80; /* UGAVALID */
1849 	}
1850 
1851 	/* Optimal Unmap Granularity */
1852 	put_unaligned_be32(sdebug_unmap_granularity, &arr[24]);
1853 
1854 	/* Maximum WRITE SAME Length */
1855 	put_unaligned_be64(sdebug_write_same_length, &arr[32]);
1856 
1857 	if (sdebug_atomic_wr) {
1858 		put_unaligned_be32(sdebug_atomic_wr_max_length, &arr[40]);
1859 		put_unaligned_be32(sdebug_atomic_wr_align, &arr[44]);
1860 		put_unaligned_be32(sdebug_atomic_wr_gran, &arr[48]);
1861 		put_unaligned_be32(sdebug_atomic_wr_max_length_bndry, &arr[52]);
1862 		put_unaligned_be32(sdebug_atomic_wr_max_bndry, &arr[56]);
1863 	}
1864 
1865 	return 0x3c; /* Mandatory page length for Logical Block Provisioning */
1866 }
1867 
1868 /* Block device characteristics VPD page (SBC-3) */
1869 static int inquiry_vpd_b1(struct sdebug_dev_info *devip, unsigned char *arr)
1870 {
1871 	memset(arr, 0, 0x3c);
1872 	arr[0] = 0;
1873 	arr[1] = 1;	/* non rotating medium (e.g. solid state) */
1874 	arr[2] = 0;
1875 	arr[3] = 5;	/* less than 1.8" */
1876 
1877 	return 0x3c;
1878 }
1879 
1880 /* Logical block provisioning VPD page (SBC-4) */
1881 static int inquiry_vpd_b2(unsigned char *arr)
1882 {
1883 	memset(arr, 0, 0x4);
1884 	arr[0] = 0;			/* threshold exponent */
1885 	if (sdebug_lbpu)
1886 		arr[1] = 1 << 7;
1887 	if (sdebug_lbpws)
1888 		arr[1] |= 1 << 6;
1889 	if (sdebug_lbpws10)
1890 		arr[1] |= 1 << 5;
1891 	if (sdebug_lbprz && scsi_debug_lbp())
1892 		arr[1] |= (sdebug_lbprz & 0x7) << 2;  /* sbc4r07 and later */
1893 	/* anc_sup=0; dp=0 (no provisioning group descriptor) */
1894 	/* minimum_percentage=0; provisioning_type=0 (unknown) */
1895 	/* threshold_percentage=0 */
1896 	return 0x4;
1897 }
1898 
1899 /* Zoned block device characteristics VPD page (ZBC mandatory) */
1900 static int inquiry_vpd_b6(struct sdebug_dev_info *devip, unsigned char *arr)
1901 {
1902 	memset(arr, 0, 0x3c);
1903 	arr[0] = 0x1; /* set URSWRZ (unrestricted read in seq. wr req zone) */
1904 	/*
1905 	 * Set Optimal number of open sequential write preferred zones and
1906 	 * Optimal number of non-sequentially written sequential write
1907 	 * preferred zones fields to 'not reported' (0xffffffff). Leave other
1908 	 * fields set to zero, apart from Max. number of open swrz_s field.
1909 	 */
1910 	put_unaligned_be32(0xffffffff, &arr[4]);
1911 	put_unaligned_be32(0xffffffff, &arr[8]);
1912 	if (sdeb_zbc_model == BLK_ZONED_HM && devip->max_open)
1913 		put_unaligned_be32(devip->max_open, &arr[12]);
1914 	else
1915 		put_unaligned_be32(0xffffffff, &arr[12]);
1916 	if (devip->zcap < devip->zsize) {
1917 		arr[19] = ZBC_CONSTANT_ZONE_START_OFFSET;
1918 		put_unaligned_be64(devip->zsize, &arr[20]);
1919 	} else {
1920 		arr[19] = 0;
1921 	}
1922 	return 0x3c;
1923 }
1924 
1925 #define SDEBUG_BLE_LEN_AFTER_B4 28	/* thus vpage 32 bytes long */
1926 
1927 enum { MAXIMUM_NUMBER_OF_STREAMS = 6, PERMANENT_STREAM_COUNT = 5 };
1928 
1929 /* Block limits extension VPD page (SBC-4) */
1930 static int inquiry_vpd_b7(unsigned char *arrb4)
1931 {
1932 	memset(arrb4, 0, SDEBUG_BLE_LEN_AFTER_B4);
1933 	arrb4[1] = 1; /* Reduced stream control support (RSCS) */
1934 	put_unaligned_be16(MAXIMUM_NUMBER_OF_STREAMS, &arrb4[2]);
1935 	return SDEBUG_BLE_LEN_AFTER_B4;
1936 }
1937 
1938 #define SDEBUG_LONG_INQ_SZ 96
1939 #define SDEBUG_MAX_INQ_ARR_SZ 584
1940 
1941 static int resp_inquiry(struct scsi_cmnd *scp, struct sdebug_dev_info *devip)
1942 {
1943 	unsigned char pq_pdt;
1944 	unsigned char *arr;
1945 	unsigned char *cmd = scp->cmnd;
1946 	u32 alloc_len, n;
1947 	int ret;
1948 	bool have_wlun, is_disk, is_zbc, is_disk_zbc;
1949 
1950 	alloc_len = get_unaligned_be16(cmd + 3);
1951 	arr = kzalloc(SDEBUG_MAX_INQ_ARR_SZ, GFP_ATOMIC);
1952 	if (! arr)
1953 		return DID_REQUEUE << 16;
1954 	is_disk = (sdebug_ptype == TYPE_DISK);
1955 	is_zbc = devip->zoned;
1956 	is_disk_zbc = (is_disk || is_zbc);
1957 	have_wlun = scsi_is_wlun(scp->device->lun);
1958 	if (have_wlun)
1959 		pq_pdt = TYPE_WLUN;	/* present, wlun */
1960 	else if (sdebug_no_lun_0 && (devip->lun == SDEBUG_LUN_0_VAL))
1961 		pq_pdt = 0x7f;	/* not present, PQ=3, PDT=0x1f */
1962 	else
1963 		pq_pdt = (sdebug_ptype & 0x1f);
1964 	arr[0] = pq_pdt;
1965 	if (0x2 & cmd[1]) {  /* CMDDT bit set */
1966 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, 1, 1);
1967 		kfree(arr);
1968 		return check_condition_result;
1969 	} else if (0x1 & cmd[1]) {  /* EVPD bit set */
1970 		int lu_id_num, port_group_id, target_dev_id;
1971 		u32 len;
1972 		char lu_id_str[6];
1973 		int host_no = devip->sdbg_host->shost->host_no;
1974 
1975 		arr[1] = cmd[2];
1976 		port_group_id = (((host_no + 1) & 0x7f) << 8) +
1977 		    (devip->channel & 0x7f);
1978 		if (sdebug_vpd_use_hostno == 0)
1979 			host_no = 0;
1980 		lu_id_num = have_wlun ? -1 : (((host_no + 1) * 2000) +
1981 			    (devip->target * 1000) + devip->lun);
1982 		target_dev_id = ((host_no + 1) * 2000) +
1983 				 (devip->target * 1000) - 3;
1984 		len = scnprintf(lu_id_str, 6, "%d", lu_id_num);
1985 		if (0 == cmd[2]) { /* supported vital product data pages */
1986 			n = 4;
1987 			arr[n++] = 0x0;   /* this page */
1988 			arr[n++] = 0x80;  /* unit serial number */
1989 			arr[n++] = 0x83;  /* device identification */
1990 			arr[n++] = 0x84;  /* software interface ident. */
1991 			arr[n++] = 0x85;  /* management network addresses */
1992 			arr[n++] = 0x86;  /* extended inquiry */
1993 			arr[n++] = 0x87;  /* mode page policy */
1994 			arr[n++] = 0x88;  /* SCSI ports */
1995 			if (is_disk_zbc) {	  /* SBC or ZBC */
1996 				arr[n++] = 0x89;  /* ATA information */
1997 				arr[n++] = 0xb0;  /* Block limits */
1998 				arr[n++] = 0xb1;  /* Block characteristics */
1999 				if (is_disk)
2000 					arr[n++] = 0xb2;  /* LB Provisioning */
2001 				if (is_zbc)
2002 					arr[n++] = 0xb6;  /* ZB dev. char. */
2003 				arr[n++] = 0xb7;  /* Block limits extension */
2004 			}
2005 			arr[3] = n - 4;	  /* number of supported VPD pages */
2006 		} else if (0x80 == cmd[2]) { /* unit serial number */
2007 			arr[3] = len;
2008 			memcpy(&arr[4], lu_id_str, len);
2009 		} else if (0x83 == cmd[2]) { /* device identification */
2010 			arr[3] = inquiry_vpd_83(&arr[4], port_group_id,
2011 						target_dev_id, lu_id_num,
2012 						lu_id_str, len,
2013 						&devip->lu_name);
2014 		} else if (0x84 == cmd[2]) { /* Software interface ident. */
2015 			arr[3] = inquiry_vpd_84(&arr[4]);
2016 		} else if (0x85 == cmd[2]) { /* Management network addresses */
2017 			arr[3] = inquiry_vpd_85(&arr[4]);
2018 		} else if (0x86 == cmd[2]) { /* extended inquiry */
2019 			arr[3] = 0x3c;	/* number of following entries */
2020 			if (sdebug_dif == T10_PI_TYPE3_PROTECTION)
2021 				arr[4] = 0x4;	/* SPT: GRD_CHK:1 */
2022 			else if (have_dif_prot)
2023 				arr[4] = 0x5;   /* SPT: GRD_CHK:1, REF_CHK:1 */
2024 			else
2025 				arr[4] = 0x0;   /* no protection stuff */
2026 			/*
2027 			 * GROUP_SUP=1; HEADSUP=1 (HEAD OF QUEUE); ORDSUP=1
2028 			 * (ORDERED queuing); SIMPSUP=1 (SIMPLE queuing).
2029 			 */
2030 			arr[5] = 0x17;
2031 		} else if (0x87 == cmd[2]) { /* mode page policy */
2032 			arr[3] = 0x8;	/* number of following entries */
2033 			arr[4] = 0x2;	/* disconnect-reconnect mp */
2034 			arr[6] = 0x80;	/* mlus, shared */
2035 			arr[8] = 0x18;	 /* protocol specific lu */
2036 			arr[10] = 0x82;	 /* mlus, per initiator port */
2037 		} else if (0x88 == cmd[2]) { /* SCSI Ports */
2038 			arr[3] = inquiry_vpd_88(&arr[4], target_dev_id);
2039 		} else if (is_disk_zbc && 0x89 == cmd[2]) { /* ATA info */
2040 			n = inquiry_vpd_89(&arr[4]);
2041 			put_unaligned_be16(n, arr + 2);
2042 		} else if (is_disk_zbc && 0xb0 == cmd[2]) { /* Block limits */
2043 			arr[3] = inquiry_vpd_b0(&arr[4]);
2044 		} else if (is_disk_zbc && 0xb1 == cmd[2]) { /* Block char. */
2045 			arr[3] = inquiry_vpd_b1(devip, &arr[4]);
2046 		} else if (is_disk && 0xb2 == cmd[2]) { /* LB Prov. */
2047 			arr[3] = inquiry_vpd_b2(&arr[4]);
2048 		} else if (is_zbc && cmd[2] == 0xb6) { /* ZB dev. charact. */
2049 			arr[3] = inquiry_vpd_b6(devip, &arr[4]);
2050 		} else if (cmd[2] == 0xb7) { /* block limits extension page */
2051 			arr[3] = inquiry_vpd_b7(&arr[4]);
2052 		} else {
2053 			mk_sense_invalid_fld(scp, SDEB_IN_CDB, 2, -1);
2054 			kfree(arr);
2055 			return check_condition_result;
2056 		}
2057 		len = min_t(u32, get_unaligned_be16(arr + 2) + 4, alloc_len);
2058 		ret = fill_from_dev_buffer(scp, arr,
2059 			    min_t(u32, len, SDEBUG_MAX_INQ_ARR_SZ));
2060 		kfree(arr);
2061 		return ret;
2062 	}
2063 	/* drops through here for a standard inquiry */
2064 	arr[1] = sdebug_removable ? 0x80 : 0;	/* Removable disk */
2065 	arr[2] = sdebug_scsi_level;
2066 	arr[3] = 2;    /* response_data_format==2 */
2067 	arr[4] = SDEBUG_LONG_INQ_SZ - 5;
2068 	arr[5] = (int)have_dif_prot;	/* PROTECT bit */
2069 	if (sdebug_vpd_use_hostno == 0)
2070 		arr[5] |= 0x10; /* claim: implicit TPGS */
2071 	arr[6] = 0x10; /* claim: MultiP */
2072 	/* arr[6] |= 0x40; ... claim: EncServ (enclosure services) */
2073 	arr[7] = 0xa; /* claim: LINKED + CMDQUE */
2074 	memcpy(&arr[8], sdebug_inq_vendor_id, 8);
2075 	memcpy(&arr[16], sdebug_inq_product_id, 16);
2076 	memcpy(&arr[32], sdebug_inq_product_rev, 4);
2077 	/* Use Vendor Specific area to place driver date in ASCII hex */
2078 	memcpy(&arr[36], sdebug_version_date, 8);
2079 	/* version descriptors (2 bytes each) follow */
2080 	put_unaligned_be16(0xc0, arr + 58);   /* SAM-6 no version claimed */
2081 	put_unaligned_be16(0x5c0, arr + 60);  /* SPC-5 no version claimed */
2082 	n = 62;
2083 	if (is_disk) {		/* SBC-4 no version claimed */
2084 		put_unaligned_be16(0x600, arr + n);
2085 		n += 2;
2086 	} else if (sdebug_ptype == TYPE_TAPE) {	/* SSC-4 rev 3 */
2087 		put_unaligned_be16(0x525, arr + n);
2088 		n += 2;
2089 	} else if (is_zbc) {	/* ZBC BSR INCITS 536 revision 05 */
2090 		put_unaligned_be16(0x624, arr + n);
2091 		n += 2;
2092 	}
2093 	put_unaligned_be16(0x2100, arr + n);	/* SPL-4 no version claimed */
2094 	ret = fill_from_dev_buffer(scp, arr,
2095 			    min_t(u32, alloc_len, SDEBUG_LONG_INQ_SZ));
2096 	kfree(arr);
2097 	return ret;
2098 }
2099 
2100 /* See resp_iec_m_pg() for how this data is manipulated */
2101 static unsigned char iec_m_pg[] = {0x1c, 0xa, 0x08, 0, 0, 0, 0, 0,
2102 				   0, 0, 0x0, 0x0};
2103 
2104 static int resp_requests(struct scsi_cmnd *scp,
2105 			 struct sdebug_dev_info *devip)
2106 {
2107 	unsigned char *cmd = scp->cmnd;
2108 	unsigned char arr[SCSI_SENSE_BUFFERSIZE];	/* assume >= 18 bytes */
2109 	bool dsense = !!(cmd[1] & 1);
2110 	u32 alloc_len = cmd[4];
2111 	u32 len = 18;
2112 	int stopped_state = atomic_read(&devip->stopped);
2113 
2114 	memset(arr, 0, sizeof(arr));
2115 	if (stopped_state > 0) {	/* some "pollable" data [spc6r02: 5.12.2] */
2116 		if (dsense) {
2117 			arr[0] = 0x72;
2118 			arr[1] = NOT_READY;
2119 			arr[2] = LOGICAL_UNIT_NOT_READY;
2120 			arr[3] = (stopped_state == 2) ? 0x1 : 0x2;
2121 			len = 8;
2122 		} else {
2123 			arr[0] = 0x70;
2124 			arr[2] = NOT_READY;		/* NO_SENSE in sense_key */
2125 			arr[7] = 0xa;			/* 18 byte sense buffer */
2126 			arr[12] = LOGICAL_UNIT_NOT_READY;
2127 			arr[13] = (stopped_state == 2) ? 0x1 : 0x2;
2128 		}
2129 	} else if ((iec_m_pg[2] & 0x4) && (6 == (iec_m_pg[3] & 0xf))) {
2130 		/* Information exceptions control mode page: TEST=1, MRIE=6 */
2131 		if (dsense) {
2132 			arr[0] = 0x72;
2133 			arr[1] = 0x0;		/* NO_SENSE in sense_key */
2134 			arr[2] = THRESHOLD_EXCEEDED;
2135 			arr[3] = 0xff;		/* Failure prediction(false) */
2136 			len = 8;
2137 		} else {
2138 			arr[0] = 0x70;
2139 			arr[2] = 0x0;		/* NO_SENSE in sense_key */
2140 			arr[7] = 0xa;   	/* 18 byte sense buffer */
2141 			arr[12] = THRESHOLD_EXCEEDED;
2142 			arr[13] = 0xff;		/* Failure prediction(false) */
2143 		}
2144 	} else {	/* nothing to report */
2145 		if (dsense) {
2146 			len = 8;
2147 			memset(arr, 0, len);
2148 			arr[0] = 0x72;
2149 		} else {
2150 			memset(arr, 0, len);
2151 			arr[0] = 0x70;
2152 			arr[7] = 0xa;
2153 		}
2154 	}
2155 	return fill_from_dev_buffer(scp, arr, min_t(u32, len, alloc_len));
2156 }
2157 
2158 static int resp_start_stop(struct scsi_cmnd *scp, struct sdebug_dev_info *devip)
2159 {
2160 	unsigned char *cmd = scp->cmnd;
2161 	int power_cond, want_stop, stopped_state;
2162 	bool changing;
2163 
2164 	power_cond = (cmd[4] & 0xf0) >> 4;
2165 	if (power_cond) {
2166 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, 4, 7);
2167 		return check_condition_result;
2168 	}
2169 	want_stop = !(cmd[4] & 1);
2170 	stopped_state = atomic_read(&devip->stopped);
2171 	if (stopped_state == 2) {
2172 		ktime_t now_ts = ktime_get_boottime();
2173 
2174 		if (ktime_to_ns(now_ts) > ktime_to_ns(devip->create_ts)) {
2175 			u64 diff_ns = ktime_to_ns(ktime_sub(now_ts, devip->create_ts));
2176 
2177 			if (diff_ns >= ((u64)sdeb_tur_ms_to_ready * 1000000)) {
2178 				/* tur_ms_to_ready timer extinguished */
2179 				atomic_set(&devip->stopped, 0);
2180 				stopped_state = 0;
2181 			}
2182 		}
2183 		if (stopped_state == 2) {
2184 			if (want_stop) {
2185 				stopped_state = 1;	/* dummy up success */
2186 			} else {	/* Disallow tur_ms_to_ready delay to be overridden */
2187 				mk_sense_invalid_fld(scp, SDEB_IN_CDB, 4, 0 /* START bit */);
2188 				return check_condition_result;
2189 			}
2190 		}
2191 	}
2192 	changing = (stopped_state != want_stop);
2193 	if (changing)
2194 		atomic_xchg(&devip->stopped, want_stop);
2195 	if (!changing || (cmd[1] & 0x1))  /* state unchanged or IMMED bit set in cdb */
2196 		return SDEG_RES_IMMED_MASK;
2197 	else
2198 		return 0;
2199 }
2200 
2201 static sector_t get_sdebug_capacity(void)
2202 {
2203 	static const unsigned int gibibyte = 1073741824;
2204 
2205 	if (sdebug_virtual_gb > 0)
2206 		return (sector_t)sdebug_virtual_gb *
2207 			(gibibyte / sdebug_sector_size);
2208 	else
2209 		return sdebug_store_sectors;
2210 }
2211 
2212 #define SDEBUG_READCAP_ARR_SZ 8
2213 static int resp_readcap(struct scsi_cmnd *scp,
2214 			struct sdebug_dev_info *devip)
2215 {
2216 	unsigned char arr[SDEBUG_READCAP_ARR_SZ];
2217 	unsigned int capac;
2218 
2219 	/* following just in case virtual_gb changed */
2220 	sdebug_capacity = get_sdebug_capacity();
2221 	memset(arr, 0, SDEBUG_READCAP_ARR_SZ);
2222 	if (sdebug_capacity < 0xffffffff) {
2223 		capac = (unsigned int)sdebug_capacity - 1;
2224 		put_unaligned_be32(capac, arr + 0);
2225 	} else
2226 		put_unaligned_be32(0xffffffff, arr + 0);
2227 	put_unaligned_be16(sdebug_sector_size, arr + 6);
2228 	return fill_from_dev_buffer(scp, arr, SDEBUG_READCAP_ARR_SZ);
2229 }
2230 
2231 #define SDEBUG_READCAP16_ARR_SZ 32
2232 static int resp_readcap16(struct scsi_cmnd *scp,
2233 			  struct sdebug_dev_info *devip)
2234 {
2235 	unsigned char *cmd = scp->cmnd;
2236 	unsigned char arr[SDEBUG_READCAP16_ARR_SZ];
2237 	u32 alloc_len;
2238 
2239 	alloc_len = get_unaligned_be32(cmd + 10);
2240 	/* following just in case virtual_gb changed */
2241 	sdebug_capacity = get_sdebug_capacity();
2242 	memset(arr, 0, SDEBUG_READCAP16_ARR_SZ);
2243 	put_unaligned_be64((u64)(sdebug_capacity - 1), arr + 0);
2244 	put_unaligned_be32(sdebug_sector_size, arr + 8);
2245 	arr[13] = sdebug_physblk_exp & 0xf;
2246 	arr[14] = (sdebug_lowest_aligned >> 8) & 0x3f;
2247 
2248 	if (scsi_debug_lbp()) {
2249 		arr[14] |= 0x80; /* LBPME */
2250 		/* from sbc4r07, this LBPRZ field is 1 bit, but the LBPRZ in
2251 		 * the LB Provisioning VPD page is 3 bits. Note that lbprz=2
2252 		 * in the wider field maps to 0 in this field.
2253 		 */
2254 		if (sdebug_lbprz & 1)	/* precisely what the draft requires */
2255 			arr[14] |= 0x40;
2256 	}
2257 
2258 	/*
2259 	 * Since the scsi_debug READ CAPACITY implementation always reports the
2260 	 * total disk capacity, set RC BASIS = 1 for host-managed ZBC devices.
2261 	 */
2262 	if (devip->zoned)
2263 		arr[12] |= 1 << 4;
2264 
2265 	arr[15] = sdebug_lowest_aligned & 0xff;
2266 
2267 	if (have_dif_prot) {
2268 		arr[12] = (sdebug_dif - 1) << 1; /* P_TYPE */
2269 		arr[12] |= 1; /* PROT_EN */
2270 	}
2271 
2272 	return fill_from_dev_buffer(scp, arr,
2273 			    min_t(u32, alloc_len, SDEBUG_READCAP16_ARR_SZ));
2274 }
2275 
2276 #define SDEBUG_MAX_TGTPGS_ARR_SZ 1412
2277 
2278 static int resp_report_tgtpgs(struct scsi_cmnd *scp,
2279 			      struct sdebug_dev_info *devip)
2280 {
2281 	unsigned char *cmd = scp->cmnd;
2282 	unsigned char *arr;
2283 	int host_no = devip->sdbg_host->shost->host_no;
2284 	int port_group_a, port_group_b, port_a, port_b;
2285 	u32 alen, n, rlen;
2286 	int ret;
2287 
2288 	alen = get_unaligned_be32(cmd + 6);
2289 	arr = kzalloc(SDEBUG_MAX_TGTPGS_ARR_SZ, GFP_ATOMIC);
2290 	if (! arr)
2291 		return DID_REQUEUE << 16;
2292 	/*
2293 	 * EVPD page 0x88 states we have two ports, one
2294 	 * real and a fake port with no device connected.
2295 	 * So we create two port groups with one port each
2296 	 * and set the group with port B to unavailable.
2297 	 */
2298 	port_a = 0x1; /* relative port A */
2299 	port_b = 0x2; /* relative port B */
2300 	port_group_a = (((host_no + 1) & 0x7f) << 8) +
2301 			(devip->channel & 0x7f);
2302 	port_group_b = (((host_no + 1) & 0x7f) << 8) +
2303 			(devip->channel & 0x7f) + 0x80;
2304 
2305 	/*
2306 	 * The asymmetric access state is cycled according to the host_id.
2307 	 */
2308 	n = 4;
2309 	if (sdebug_vpd_use_hostno == 0) {
2310 		arr[n++] = host_no % 3; /* Asymm access state */
2311 		arr[n++] = 0x0F; /* claim: all states are supported */
2312 	} else {
2313 		arr[n++] = 0x0; /* Active/Optimized path */
2314 		arr[n++] = 0x01; /* only support active/optimized paths */
2315 	}
2316 	put_unaligned_be16(port_group_a, arr + n);
2317 	n += 2;
2318 	arr[n++] = 0;    /* Reserved */
2319 	arr[n++] = 0;    /* Status code */
2320 	arr[n++] = 0;    /* Vendor unique */
2321 	arr[n++] = 0x1;  /* One port per group */
2322 	arr[n++] = 0;    /* Reserved */
2323 	arr[n++] = 0;    /* Reserved */
2324 	put_unaligned_be16(port_a, arr + n);
2325 	n += 2;
2326 	arr[n++] = 3;    /* Port unavailable */
2327 	arr[n++] = 0x08; /* claim: only unavailalbe paths are supported */
2328 	put_unaligned_be16(port_group_b, arr + n);
2329 	n += 2;
2330 	arr[n++] = 0;    /* Reserved */
2331 	arr[n++] = 0;    /* Status code */
2332 	arr[n++] = 0;    /* Vendor unique */
2333 	arr[n++] = 0x1;  /* One port per group */
2334 	arr[n++] = 0;    /* Reserved */
2335 	arr[n++] = 0;    /* Reserved */
2336 	put_unaligned_be16(port_b, arr + n);
2337 	n += 2;
2338 
2339 	rlen = n - 4;
2340 	put_unaligned_be32(rlen, arr + 0);
2341 
2342 	/*
2343 	 * Return the smallest value of either
2344 	 * - The allocated length
2345 	 * - The constructed command length
2346 	 * - The maximum array size
2347 	 */
2348 	rlen = min(alen, n);
2349 	ret = fill_from_dev_buffer(scp, arr,
2350 			   min_t(u32, rlen, SDEBUG_MAX_TGTPGS_ARR_SZ));
2351 	kfree(arr);
2352 	return ret;
2353 }
2354 
2355 static int resp_rsup_opcodes(struct scsi_cmnd *scp,
2356 			     struct sdebug_dev_info *devip)
2357 {
2358 	bool rctd;
2359 	u8 reporting_opts, req_opcode, sdeb_i, supp;
2360 	u16 req_sa, u;
2361 	u32 alloc_len, a_len;
2362 	int k, offset, len, errsts, count, bump, na;
2363 	const struct opcode_info_t *oip;
2364 	const struct opcode_info_t *r_oip;
2365 	u8 *arr;
2366 	u8 *cmd = scp->cmnd;
2367 
2368 	rctd = !!(cmd[2] & 0x80);
2369 	reporting_opts = cmd[2] & 0x7;
2370 	req_opcode = cmd[3];
2371 	req_sa = get_unaligned_be16(cmd + 4);
2372 	alloc_len = get_unaligned_be32(cmd + 6);
2373 	if (alloc_len < 4 || alloc_len > 0xffff) {
2374 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, 6, -1);
2375 		return check_condition_result;
2376 	}
2377 	if (alloc_len > 8192)
2378 		a_len = 8192;
2379 	else
2380 		a_len = alloc_len;
2381 	arr = kzalloc((a_len < 256) ? 320 : a_len + 64, GFP_ATOMIC);
2382 	if (NULL == arr) {
2383 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INSUFF_RES_ASC,
2384 				INSUFF_RES_ASCQ);
2385 		return check_condition_result;
2386 	}
2387 	switch (reporting_opts) {
2388 	case 0:	/* all commands */
2389 		/* count number of commands */
2390 		for (count = 0, oip = opcode_info_arr;
2391 		     oip->num_attached != 0xff; ++oip) {
2392 			if (F_INV_OP & oip->flags)
2393 				continue;
2394 			count += (oip->num_attached + 1);
2395 		}
2396 		bump = rctd ? 20 : 8;
2397 		put_unaligned_be32(count * bump, arr);
2398 		for (offset = 4, oip = opcode_info_arr;
2399 		     oip->num_attached != 0xff && offset < a_len; ++oip) {
2400 			if (F_INV_OP & oip->flags)
2401 				continue;
2402 			na = oip->num_attached;
2403 			arr[offset] = oip->opcode;
2404 			put_unaligned_be16(oip->sa, arr + offset + 2);
2405 			if (rctd)
2406 				arr[offset + 5] |= 0x2;
2407 			if (FF_SA & oip->flags)
2408 				arr[offset + 5] |= 0x1;
2409 			put_unaligned_be16(oip->len_mask[0], arr + offset + 6);
2410 			if (rctd)
2411 				put_unaligned_be16(0xa, arr + offset + 8);
2412 			r_oip = oip;
2413 			for (k = 0, oip = oip->arrp; k < na; ++k, ++oip) {
2414 				if (F_INV_OP & oip->flags)
2415 					continue;
2416 				offset += bump;
2417 				arr[offset] = oip->opcode;
2418 				put_unaligned_be16(oip->sa, arr + offset + 2);
2419 				if (rctd)
2420 					arr[offset + 5] |= 0x2;
2421 				if (FF_SA & oip->flags)
2422 					arr[offset + 5] |= 0x1;
2423 				put_unaligned_be16(oip->len_mask[0],
2424 						   arr + offset + 6);
2425 				if (rctd)
2426 					put_unaligned_be16(0xa,
2427 							   arr + offset + 8);
2428 			}
2429 			oip = r_oip;
2430 			offset += bump;
2431 		}
2432 		break;
2433 	case 1:	/* one command: opcode only */
2434 	case 2:	/* one command: opcode plus service action */
2435 	case 3:	/* one command: if sa==0 then opcode only else opcode+sa */
2436 		sdeb_i = opcode_ind_arr[req_opcode];
2437 		oip = &opcode_info_arr[sdeb_i];
2438 		if (F_INV_OP & oip->flags) {
2439 			supp = 1;
2440 			offset = 4;
2441 		} else {
2442 			if (1 == reporting_opts) {
2443 				if (FF_SA & oip->flags) {
2444 					mk_sense_invalid_fld(scp, SDEB_IN_CDB,
2445 							     2, 2);
2446 					kfree(arr);
2447 					return check_condition_result;
2448 				}
2449 				req_sa = 0;
2450 			} else if (2 == reporting_opts &&
2451 				   0 == (FF_SA & oip->flags)) {
2452 				mk_sense_invalid_fld(scp, SDEB_IN_CDB, 4, -1);
2453 				kfree(arr);	/* point at requested sa */
2454 				return check_condition_result;
2455 			}
2456 			if (0 == (FF_SA & oip->flags) &&
2457 			    req_opcode == oip->opcode)
2458 				supp = 3;
2459 			else if (0 == (FF_SA & oip->flags)) {
2460 				na = oip->num_attached;
2461 				for (k = 0, oip = oip->arrp; k < na;
2462 				     ++k, ++oip) {
2463 					if (req_opcode == oip->opcode)
2464 						break;
2465 				}
2466 				supp = (k >= na) ? 1 : 3;
2467 			} else if (req_sa != oip->sa) {
2468 				na = oip->num_attached;
2469 				for (k = 0, oip = oip->arrp; k < na;
2470 				     ++k, ++oip) {
2471 					if (req_sa == oip->sa)
2472 						break;
2473 				}
2474 				supp = (k >= na) ? 1 : 3;
2475 			} else
2476 				supp = 3;
2477 			if (3 == supp) {
2478 				u = oip->len_mask[0];
2479 				put_unaligned_be16(u, arr + 2);
2480 				arr[4] = oip->opcode;
2481 				for (k = 1; k < u; ++k)
2482 					arr[4 + k] = (k < 16) ?
2483 						 oip->len_mask[k] : 0xff;
2484 				offset = 4 + u;
2485 			} else
2486 				offset = 4;
2487 		}
2488 		arr[1] = (rctd ? 0x80 : 0) | supp;
2489 		if (rctd) {
2490 			put_unaligned_be16(0xa, arr + offset);
2491 			offset += 12;
2492 		}
2493 		break;
2494 	default:
2495 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, 2, 2);
2496 		kfree(arr);
2497 		return check_condition_result;
2498 	}
2499 	offset = (offset < a_len) ? offset : a_len;
2500 	len = (offset < alloc_len) ? offset : alloc_len;
2501 	errsts = fill_from_dev_buffer(scp, arr, len);
2502 	kfree(arr);
2503 	return errsts;
2504 }
2505 
2506 static int resp_rsup_tmfs(struct scsi_cmnd *scp,
2507 			  struct sdebug_dev_info *devip)
2508 {
2509 	bool repd;
2510 	u32 alloc_len, len;
2511 	u8 arr[16];
2512 	u8 *cmd = scp->cmnd;
2513 
2514 	memset(arr, 0, sizeof(arr));
2515 	repd = !!(cmd[2] & 0x80);
2516 	alloc_len = get_unaligned_be32(cmd + 6);
2517 	if (alloc_len < 4) {
2518 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, 6, -1);
2519 		return check_condition_result;
2520 	}
2521 	arr[0] = 0xc8;		/* ATS | ATSS | LURS */
2522 	arr[1] = 0x1;		/* ITNRS */
2523 	if (repd) {
2524 		arr[3] = 0xc;
2525 		len = 16;
2526 	} else
2527 		len = 4;
2528 
2529 	len = (len < alloc_len) ? len : alloc_len;
2530 	return fill_from_dev_buffer(scp, arr, len);
2531 }
2532 
2533 /* <<Following mode page info copied from ST318451LW>> */
2534 
2535 static int resp_err_recov_pg(unsigned char *p, int pcontrol, int target)
2536 {	/* Read-Write Error Recovery page for mode_sense */
2537 	unsigned char err_recov_pg[] = {0x1, 0xa, 0xc0, 11, 240, 0, 0, 0,
2538 					5, 0, 0xff, 0xff};
2539 
2540 	memcpy(p, err_recov_pg, sizeof(err_recov_pg));
2541 	if (1 == pcontrol)
2542 		memset(p + 2, 0, sizeof(err_recov_pg) - 2);
2543 	return sizeof(err_recov_pg);
2544 }
2545 
2546 static int resp_disconnect_pg(unsigned char *p, int pcontrol, int target)
2547 { 	/* Disconnect-Reconnect page for mode_sense */
2548 	unsigned char disconnect_pg[] = {0x2, 0xe, 128, 128, 0, 10, 0, 0,
2549 					 0, 0, 0, 0, 0, 0, 0, 0};
2550 
2551 	memcpy(p, disconnect_pg, sizeof(disconnect_pg));
2552 	if (1 == pcontrol)
2553 		memset(p + 2, 0, sizeof(disconnect_pg) - 2);
2554 	return sizeof(disconnect_pg);
2555 }
2556 
2557 static int resp_format_pg(unsigned char *p, int pcontrol, int target)
2558 {       /* Format device page for mode_sense */
2559 	unsigned char format_pg[] = {0x3, 0x16, 0, 0, 0, 0, 0, 0,
2560 				     0, 0, 0, 0, 0, 0, 0, 0,
2561 				     0, 0, 0, 0, 0x40, 0, 0, 0};
2562 
2563 	memcpy(p, format_pg, sizeof(format_pg));
2564 	put_unaligned_be16(sdebug_sectors_per, p + 10);
2565 	put_unaligned_be16(sdebug_sector_size, p + 12);
2566 	if (sdebug_removable)
2567 		p[20] |= 0x20; /* should agree with INQUIRY */
2568 	if (1 == pcontrol)
2569 		memset(p + 2, 0, sizeof(format_pg) - 2);
2570 	return sizeof(format_pg);
2571 }
2572 
2573 static unsigned char caching_pg[] = {0x8, 18, 0x14, 0, 0xff, 0xff, 0, 0,
2574 				     0xff, 0xff, 0xff, 0xff, 0x80, 0x14, 0, 0,
2575 				     0, 0, 0, 0};
2576 
2577 static int resp_caching_pg(unsigned char *p, int pcontrol, int target)
2578 { 	/* Caching page for mode_sense */
2579 	unsigned char ch_caching_pg[] = {/* 0x8, 18, */ 0x4, 0, 0, 0, 0, 0,
2580 		0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2581 	unsigned char d_caching_pg[] = {0x8, 18, 0x14, 0, 0xff, 0xff, 0, 0,
2582 		0xff, 0xff, 0xff, 0xff, 0x80, 0x14, 0, 0,     0, 0, 0, 0};
2583 
2584 	if (SDEBUG_OPT_N_WCE & sdebug_opts)
2585 		caching_pg[2] &= ~0x4;	/* set WCE=0 (default WCE=1) */
2586 	memcpy(p, caching_pg, sizeof(caching_pg));
2587 	if (1 == pcontrol)
2588 		memcpy(p + 2, ch_caching_pg, sizeof(ch_caching_pg));
2589 	else if (2 == pcontrol)
2590 		memcpy(p, d_caching_pg, sizeof(d_caching_pg));
2591 	return sizeof(caching_pg);
2592 }
2593 
2594 static unsigned char ctrl_m_pg[] = {0xa, 10, 2, 0, 0, 0, 0, 0,
2595 				    0, 0, 0x2, 0x4b};
2596 
2597 static int resp_ctrl_m_pg(unsigned char *p, int pcontrol, int target)
2598 { 	/* Control mode page for mode_sense */
2599 	unsigned char ch_ctrl_m_pg[] = {/* 0xa, 10, */ 0x6, 0, 0, 0, 0, 0,
2600 					0, 0, 0, 0};
2601 	unsigned char d_ctrl_m_pg[] = {0xa, 10, 2, 0, 0, 0, 0, 0,
2602 				     0, 0, 0x2, 0x4b};
2603 
2604 	if (sdebug_dsense)
2605 		ctrl_m_pg[2] |= 0x4;
2606 	else
2607 		ctrl_m_pg[2] &= ~0x4;
2608 
2609 	if (sdebug_ato)
2610 		ctrl_m_pg[5] |= 0x80; /* ATO=1 */
2611 
2612 	memcpy(p, ctrl_m_pg, sizeof(ctrl_m_pg));
2613 	if (1 == pcontrol)
2614 		memcpy(p + 2, ch_ctrl_m_pg, sizeof(ch_ctrl_m_pg));
2615 	else if (2 == pcontrol)
2616 		memcpy(p, d_ctrl_m_pg, sizeof(d_ctrl_m_pg));
2617 	return sizeof(ctrl_m_pg);
2618 }
2619 
2620 /* IO Advice Hints Grouping mode page */
2621 static int resp_grouping_m_pg(unsigned char *p, int pcontrol, int target)
2622 {
2623 	/* IO Advice Hints Grouping mode page */
2624 	struct grouping_m_pg {
2625 		u8 page_code;	/* OR 0x40 when subpage_code > 0 */
2626 		u8 subpage_code;
2627 		__be16 page_length;
2628 		u8 reserved[12];
2629 		struct scsi_io_group_descriptor descr[MAXIMUM_NUMBER_OF_STREAMS];
2630 	};
2631 	static const struct grouping_m_pg gr_m_pg = {
2632 		.page_code = 0xa | 0x40,
2633 		.subpage_code = 5,
2634 		.page_length = cpu_to_be16(sizeof(gr_m_pg) - 4),
2635 		.descr = {
2636 			{ .st_enble = 1 },
2637 			{ .st_enble = 1 },
2638 			{ .st_enble = 1 },
2639 			{ .st_enble = 1 },
2640 			{ .st_enble = 1 },
2641 			{ .st_enble = 0 },
2642 		}
2643 	};
2644 
2645 	BUILD_BUG_ON(sizeof(struct grouping_m_pg) !=
2646 		     16 + MAXIMUM_NUMBER_OF_STREAMS * 16);
2647 	memcpy(p, &gr_m_pg, sizeof(gr_m_pg));
2648 	if (1 == pcontrol) {
2649 		/* There are no changeable values so clear from byte 4 on. */
2650 		memset(p + 4, 0, sizeof(gr_m_pg) - 4);
2651 	}
2652 	return sizeof(gr_m_pg);
2653 }
2654 
2655 static int resp_iec_m_pg(unsigned char *p, int pcontrol, int target)
2656 {	/* Informational Exceptions control mode page for mode_sense */
2657 	unsigned char ch_iec_m_pg[] = {/* 0x1c, 0xa, */ 0x4, 0xf, 0, 0, 0, 0,
2658 				       0, 0, 0x0, 0x0};
2659 	unsigned char d_iec_m_pg[] = {0x1c, 0xa, 0x08, 0, 0, 0, 0, 0,
2660 				      0, 0, 0x0, 0x0};
2661 
2662 	memcpy(p, iec_m_pg, sizeof(iec_m_pg));
2663 	if (1 == pcontrol)
2664 		memcpy(p + 2, ch_iec_m_pg, sizeof(ch_iec_m_pg));
2665 	else if (2 == pcontrol)
2666 		memcpy(p, d_iec_m_pg, sizeof(d_iec_m_pg));
2667 	return sizeof(iec_m_pg);
2668 }
2669 
2670 static int resp_sas_sf_m_pg(unsigned char *p, int pcontrol, int target)
2671 {	/* SAS SSP mode page - short format for mode_sense */
2672 	unsigned char sas_sf_m_pg[] = {0x19, 0x6,
2673 		0x6, 0x0, 0x7, 0xd0, 0x0, 0x0};
2674 
2675 	memcpy(p, sas_sf_m_pg, sizeof(sas_sf_m_pg));
2676 	if (1 == pcontrol)
2677 		memset(p + 2, 0, sizeof(sas_sf_m_pg) - 2);
2678 	return sizeof(sas_sf_m_pg);
2679 }
2680 
2681 
2682 static int resp_sas_pcd_m_spg(unsigned char *p, int pcontrol, int target,
2683 			      int target_dev_id)
2684 {	/* SAS phy control and discover mode page for mode_sense */
2685 	unsigned char sas_pcd_m_pg[] = {0x59, 0x1, 0, 0x64, 0, 0x6, 0, 2,
2686 		    0, 0, 0, 0, 0x10, 0x9, 0x8, 0x0,
2687 		    0, 0, 0, 0, 0, 0, 0, 0,	/* insert SAS addr */
2688 		    0, 0, 0, 0, 0, 0, 0, 0,	/* insert SAS addr */
2689 		    0x2, 0, 0, 0, 0, 0, 0, 0,
2690 		    0x88, 0x99, 0, 0, 0, 0, 0, 0,
2691 		    0, 0, 0, 0, 0, 0, 0, 0,
2692 		    0, 1, 0, 0, 0x10, 0x9, 0x8, 0x0,
2693 		    0, 0, 0, 0, 0, 0, 0, 0,	/* insert SAS addr */
2694 		    0, 0, 0, 0, 0, 0, 0, 0,	/* insert SAS addr */
2695 		    0x3, 0, 0, 0, 0, 0, 0, 0,
2696 		    0x88, 0x99, 0, 0, 0, 0, 0, 0,
2697 		    0, 0, 0, 0, 0, 0, 0, 0,
2698 		};
2699 	int port_a, port_b;
2700 
2701 	put_unaligned_be64(naa3_comp_a, sas_pcd_m_pg + 16);
2702 	put_unaligned_be64(naa3_comp_c + 1, sas_pcd_m_pg + 24);
2703 	put_unaligned_be64(naa3_comp_a, sas_pcd_m_pg + 64);
2704 	put_unaligned_be64(naa3_comp_c + 1, sas_pcd_m_pg + 72);
2705 	port_a = target_dev_id + 1;
2706 	port_b = port_a + 1;
2707 	memcpy(p, sas_pcd_m_pg, sizeof(sas_pcd_m_pg));
2708 	put_unaligned_be32(port_a, p + 20);
2709 	put_unaligned_be32(port_b, p + 48 + 20);
2710 	if (1 == pcontrol)
2711 		memset(p + 4, 0, sizeof(sas_pcd_m_pg) - 4);
2712 	return sizeof(sas_pcd_m_pg);
2713 }
2714 
2715 static int resp_sas_sha_m_spg(unsigned char *p, int pcontrol)
2716 {	/* SAS SSP shared protocol specific port mode subpage */
2717 	unsigned char sas_sha_m_pg[] = {0x59, 0x2, 0, 0xc, 0, 0x6, 0x10, 0,
2718 		    0, 0, 0, 0, 0, 0, 0, 0,
2719 		};
2720 
2721 	memcpy(p, sas_sha_m_pg, sizeof(sas_sha_m_pg));
2722 	if (1 == pcontrol)
2723 		memset(p + 4, 0, sizeof(sas_sha_m_pg) - 4);
2724 	return sizeof(sas_sha_m_pg);
2725 }
2726 
2727 /* PAGE_SIZE is more than necessary but provides room for future expansion. */
2728 #define SDEBUG_MAX_MSENSE_SZ PAGE_SIZE
2729 
2730 static int resp_mode_sense(struct scsi_cmnd *scp,
2731 			   struct sdebug_dev_info *devip)
2732 {
2733 	int pcontrol, pcode, subpcode, bd_len;
2734 	unsigned char dev_spec;
2735 	u32 alloc_len, offset, len;
2736 	int target_dev_id;
2737 	int target = scp->device->id;
2738 	unsigned char *ap;
2739 	unsigned char *arr __free(kfree);
2740 	unsigned char *cmd = scp->cmnd;
2741 	bool dbd, llbaa, msense_6, is_disk, is_zbc;
2742 
2743 	arr = kzalloc(SDEBUG_MAX_MSENSE_SZ, GFP_ATOMIC);
2744 	if (!arr)
2745 		return -ENOMEM;
2746 	dbd = !!(cmd[1] & 0x8);		/* disable block descriptors */
2747 	pcontrol = (cmd[2] & 0xc0) >> 6;
2748 	pcode = cmd[2] & 0x3f;
2749 	subpcode = cmd[3];
2750 	msense_6 = (MODE_SENSE == cmd[0]);
2751 	llbaa = msense_6 ? false : !!(cmd[1] & 0x10);
2752 	is_disk = (sdebug_ptype == TYPE_DISK);
2753 	is_zbc = devip->zoned;
2754 	if ((is_disk || is_zbc) && !dbd)
2755 		bd_len = llbaa ? 16 : 8;
2756 	else
2757 		bd_len = 0;
2758 	alloc_len = msense_6 ? cmd[4] : get_unaligned_be16(cmd + 7);
2759 	memset(arr, 0, SDEBUG_MAX_MSENSE_SZ);
2760 	if (0x3 == pcontrol) {  /* Saving values not supported */
2761 		mk_sense_buffer(scp, ILLEGAL_REQUEST, SAVING_PARAMS_UNSUP, 0);
2762 		return check_condition_result;
2763 	}
2764 	target_dev_id = ((devip->sdbg_host->shost->host_no + 1) * 2000) +
2765 			(devip->target * 1000) - 3;
2766 	/* for disks+zbc set DPOFUA bit and clear write protect (WP) bit */
2767 	if (is_disk || is_zbc) {
2768 		dev_spec = 0x10;	/* =0x90 if WP=1 implies read-only */
2769 		if (sdebug_wp)
2770 			dev_spec |= 0x80;
2771 	} else
2772 		dev_spec = 0x0;
2773 	if (msense_6) {
2774 		arr[2] = dev_spec;
2775 		arr[3] = bd_len;
2776 		offset = 4;
2777 	} else {
2778 		arr[3] = dev_spec;
2779 		if (16 == bd_len)
2780 			arr[4] = 0x1;	/* set LONGLBA bit */
2781 		arr[7] = bd_len;	/* assume 255 or less */
2782 		offset = 8;
2783 	}
2784 	ap = arr + offset;
2785 	if ((bd_len > 0) && (!sdebug_capacity))
2786 		sdebug_capacity = get_sdebug_capacity();
2787 
2788 	if (8 == bd_len) {
2789 		if (sdebug_capacity > 0xfffffffe)
2790 			put_unaligned_be32(0xffffffff, ap + 0);
2791 		else
2792 			put_unaligned_be32(sdebug_capacity, ap + 0);
2793 		put_unaligned_be16(sdebug_sector_size, ap + 6);
2794 		offset += bd_len;
2795 		ap = arr + offset;
2796 	} else if (16 == bd_len) {
2797 		put_unaligned_be64((u64)sdebug_capacity, ap + 0);
2798 		put_unaligned_be32(sdebug_sector_size, ap + 12);
2799 		offset += bd_len;
2800 		ap = arr + offset;
2801 	}
2802 
2803 	/*
2804 	 * N.B. If len>0 before resp_*_pg() call, then form of that call should be:
2805 	 *        len += resp_*_pg(ap + len, pcontrol, target);
2806 	 */
2807 	switch (pcode) {
2808 	case 0x1:	/* Read-Write error recovery page, direct access */
2809 		if (subpcode > 0x0 && subpcode < 0xff)
2810 			goto bad_subpcode;
2811 		len = resp_err_recov_pg(ap, pcontrol, target);
2812 		offset += len;
2813 		break;
2814 	case 0x2:	/* Disconnect-Reconnect page, all devices */
2815 		if (subpcode > 0x0 && subpcode < 0xff)
2816 			goto bad_subpcode;
2817 		len = resp_disconnect_pg(ap, pcontrol, target);
2818 		offset += len;
2819 		break;
2820 	case 0x3:       /* Format device page, direct access */
2821 		if (subpcode > 0x0 && subpcode < 0xff)
2822 			goto bad_subpcode;
2823 		if (is_disk) {
2824 			len = resp_format_pg(ap, pcontrol, target);
2825 			offset += len;
2826 		} else {
2827 			goto bad_pcode;
2828 		}
2829 		break;
2830 	case 0x8:	/* Caching page, direct access */
2831 		if (subpcode > 0x0 && subpcode < 0xff)
2832 			goto bad_subpcode;
2833 		if (is_disk || is_zbc) {
2834 			len = resp_caching_pg(ap, pcontrol, target);
2835 			offset += len;
2836 		} else {
2837 			goto bad_pcode;
2838 		}
2839 		break;
2840 	case 0xa:	/* Control Mode page, all devices */
2841 		switch (subpcode) {
2842 		case 0:
2843 			len = resp_ctrl_m_pg(ap, pcontrol, target);
2844 			break;
2845 		case 0x05:
2846 			len = resp_grouping_m_pg(ap, pcontrol, target);
2847 			break;
2848 		case 0xff:
2849 			len = resp_ctrl_m_pg(ap, pcontrol, target);
2850 			len += resp_grouping_m_pg(ap + len, pcontrol, target);
2851 			break;
2852 		default:
2853 			goto bad_subpcode;
2854 		}
2855 		offset += len;
2856 		break;
2857 	case 0x19:	/* if spc==1 then sas phy, control+discover */
2858 		if (subpcode > 0x2 && subpcode < 0xff)
2859 			goto bad_subpcode;
2860 		len = 0;
2861 		if ((0x0 == subpcode) || (0xff == subpcode))
2862 			len += resp_sas_sf_m_pg(ap + len, pcontrol, target);
2863 		if ((0x1 == subpcode) || (0xff == subpcode))
2864 			len += resp_sas_pcd_m_spg(ap + len, pcontrol, target,
2865 						  target_dev_id);
2866 		if ((0x2 == subpcode) || (0xff == subpcode))
2867 			len += resp_sas_sha_m_spg(ap + len, pcontrol);
2868 		offset += len;
2869 		break;
2870 	case 0x1c:	/* Informational Exceptions Mode page, all devices */
2871 		if (subpcode > 0x0 && subpcode < 0xff)
2872 			goto bad_subpcode;
2873 		len = resp_iec_m_pg(ap, pcontrol, target);
2874 		offset += len;
2875 		break;
2876 	case 0x3f:	/* Read all Mode pages */
2877 		if (subpcode > 0x0 && subpcode < 0xff)
2878 			goto bad_subpcode;
2879 		len = resp_err_recov_pg(ap, pcontrol, target);
2880 		len += resp_disconnect_pg(ap + len, pcontrol, target);
2881 		if (is_disk) {
2882 			len += resp_format_pg(ap + len, pcontrol, target);
2883 			len += resp_caching_pg(ap + len, pcontrol, target);
2884 		} else if (is_zbc) {
2885 			len += resp_caching_pg(ap + len, pcontrol, target);
2886 		}
2887 		len += resp_ctrl_m_pg(ap + len, pcontrol, target);
2888 		if (0xff == subpcode)
2889 			len += resp_grouping_m_pg(ap + len, pcontrol, target);
2890 		len += resp_sas_sf_m_pg(ap + len, pcontrol, target);
2891 		if (0xff == subpcode) {
2892 			len += resp_sas_pcd_m_spg(ap + len, pcontrol, target,
2893 						  target_dev_id);
2894 			len += resp_sas_sha_m_spg(ap + len, pcontrol);
2895 		}
2896 		len += resp_iec_m_pg(ap + len, pcontrol, target);
2897 		offset += len;
2898 		break;
2899 	default:
2900 		goto bad_pcode;
2901 	}
2902 	if (msense_6)
2903 		arr[0] = offset - 1;
2904 	else
2905 		put_unaligned_be16((offset - 2), arr + 0);
2906 	return fill_from_dev_buffer(scp, arr, min_t(u32, alloc_len, offset));
2907 
2908 bad_pcode:
2909 	mk_sense_invalid_fld(scp, SDEB_IN_CDB, 2, 5);
2910 	return check_condition_result;
2911 
2912 bad_subpcode:
2913 	mk_sense_invalid_fld(scp, SDEB_IN_CDB, 3, -1);
2914 	return check_condition_result;
2915 }
2916 
2917 #define SDEBUG_MAX_MSELECT_SZ 512
2918 
2919 static int resp_mode_select(struct scsi_cmnd *scp,
2920 			    struct sdebug_dev_info *devip)
2921 {
2922 	int pf, sp, ps, md_len, bd_len, off, spf, pg_len;
2923 	int param_len, res, mpage;
2924 	unsigned char arr[SDEBUG_MAX_MSELECT_SZ];
2925 	unsigned char *cmd = scp->cmnd;
2926 	int mselect6 = (MODE_SELECT == cmd[0]);
2927 
2928 	memset(arr, 0, sizeof(arr));
2929 	pf = cmd[1] & 0x10;
2930 	sp = cmd[1] & 0x1;
2931 	param_len = mselect6 ? cmd[4] : get_unaligned_be16(cmd + 7);
2932 	if ((0 == pf) || sp || (param_len > SDEBUG_MAX_MSELECT_SZ)) {
2933 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, mselect6 ? 4 : 7, -1);
2934 		return check_condition_result;
2935 	}
2936 	res = fetch_to_dev_buffer(scp, arr, param_len);
2937 	if (-1 == res)
2938 		return DID_ERROR << 16;
2939 	else if (sdebug_verbose && (res < param_len))
2940 		sdev_printk(KERN_INFO, scp->device,
2941 			    "%s: cdb indicated=%d, IO sent=%d bytes\n",
2942 			    __func__, param_len, res);
2943 	md_len = mselect6 ? (arr[0] + 1) : (get_unaligned_be16(arr + 0) + 2);
2944 	bd_len = mselect6 ? arr[3] : get_unaligned_be16(arr + 6);
2945 	off = bd_len + (mselect6 ? 4 : 8);
2946 	if (md_len > 2 || off >= res) {
2947 		mk_sense_invalid_fld(scp, SDEB_IN_DATA, 0, -1);
2948 		return check_condition_result;
2949 	}
2950 	mpage = arr[off] & 0x3f;
2951 	ps = !!(arr[off] & 0x80);
2952 	if (ps) {
2953 		mk_sense_invalid_fld(scp, SDEB_IN_DATA, off, 7);
2954 		return check_condition_result;
2955 	}
2956 	spf = !!(arr[off] & 0x40);
2957 	pg_len = spf ? (get_unaligned_be16(arr + off + 2) + 4) :
2958 		       (arr[off + 1] + 2);
2959 	if ((pg_len + off) > param_len) {
2960 		mk_sense_buffer(scp, ILLEGAL_REQUEST,
2961 				PARAMETER_LIST_LENGTH_ERR, 0);
2962 		return check_condition_result;
2963 	}
2964 	switch (mpage) {
2965 	case 0x8:      /* Caching Mode page */
2966 		if (caching_pg[1] == arr[off + 1]) {
2967 			memcpy(caching_pg + 2, arr + off + 2,
2968 			       sizeof(caching_pg) - 2);
2969 			goto set_mode_changed_ua;
2970 		}
2971 		break;
2972 	case 0xa:      /* Control Mode page */
2973 		if (ctrl_m_pg[1] == arr[off + 1]) {
2974 			memcpy(ctrl_m_pg + 2, arr + off + 2,
2975 			       sizeof(ctrl_m_pg) - 2);
2976 			if (ctrl_m_pg[4] & 0x8)
2977 				sdebug_wp = true;
2978 			else
2979 				sdebug_wp = false;
2980 			sdebug_dsense = !!(ctrl_m_pg[2] & 0x4);
2981 			goto set_mode_changed_ua;
2982 		}
2983 		break;
2984 	case 0x1c:      /* Informational Exceptions Mode page */
2985 		if (iec_m_pg[1] == arr[off + 1]) {
2986 			memcpy(iec_m_pg + 2, arr + off + 2,
2987 			       sizeof(iec_m_pg) - 2);
2988 			goto set_mode_changed_ua;
2989 		}
2990 		break;
2991 	default:
2992 		break;
2993 	}
2994 	mk_sense_invalid_fld(scp, SDEB_IN_DATA, off, 5);
2995 	return check_condition_result;
2996 set_mode_changed_ua:
2997 	set_bit(SDEBUG_UA_MODE_CHANGED, devip->uas_bm);
2998 	return 0;
2999 }
3000 
3001 static int resp_temp_l_pg(unsigned char *arr)
3002 {
3003 	unsigned char temp_l_pg[] = {0x0, 0x0, 0x3, 0x2, 0x0, 38,
3004 				     0x0, 0x1, 0x3, 0x2, 0x0, 65,
3005 		};
3006 
3007 	memcpy(arr, temp_l_pg, sizeof(temp_l_pg));
3008 	return sizeof(temp_l_pg);
3009 }
3010 
3011 static int resp_ie_l_pg(unsigned char *arr)
3012 {
3013 	unsigned char ie_l_pg[] = {0x0, 0x0, 0x3, 0x3, 0x0, 0x0, 38,
3014 		};
3015 
3016 	memcpy(arr, ie_l_pg, sizeof(ie_l_pg));
3017 	if (iec_m_pg[2] & 0x4) {	/* TEST bit set */
3018 		arr[4] = THRESHOLD_EXCEEDED;
3019 		arr[5] = 0xff;
3020 	}
3021 	return sizeof(ie_l_pg);
3022 }
3023 
3024 static int resp_env_rep_l_spg(unsigned char *arr)
3025 {
3026 	unsigned char env_rep_l_spg[] = {0x0, 0x0, 0x23, 0x8,
3027 					 0x0, 40, 72, 0xff, 45, 18, 0, 0,
3028 					 0x1, 0x0, 0x23, 0x8,
3029 					 0x0, 55, 72, 35, 55, 45, 0, 0,
3030 		};
3031 
3032 	memcpy(arr, env_rep_l_spg, sizeof(env_rep_l_spg));
3033 	return sizeof(env_rep_l_spg);
3034 }
3035 
3036 #define SDEBUG_MAX_LSENSE_SZ 512
3037 
3038 static int resp_log_sense(struct scsi_cmnd *scp,
3039 			  struct sdebug_dev_info *devip)
3040 {
3041 	int ppc, sp, pcode, subpcode;
3042 	u32 alloc_len, len, n;
3043 	unsigned char arr[SDEBUG_MAX_LSENSE_SZ];
3044 	unsigned char *cmd = scp->cmnd;
3045 
3046 	memset(arr, 0, sizeof(arr));
3047 	ppc = cmd[1] & 0x2;
3048 	sp = cmd[1] & 0x1;
3049 	if (ppc || sp) {
3050 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, 1, ppc ? 1 : 0);
3051 		return check_condition_result;
3052 	}
3053 	pcode = cmd[2] & 0x3f;
3054 	subpcode = cmd[3] & 0xff;
3055 	alloc_len = get_unaligned_be16(cmd + 7);
3056 	arr[0] = pcode;
3057 	if (0 == subpcode) {
3058 		switch (pcode) {
3059 		case 0x0:	/* Supported log pages log page */
3060 			n = 4;
3061 			arr[n++] = 0x0;		/* this page */
3062 			arr[n++] = 0xd;		/* Temperature */
3063 			arr[n++] = 0x2f;	/* Informational exceptions */
3064 			arr[3] = n - 4;
3065 			break;
3066 		case 0xd:	/* Temperature log page */
3067 			arr[3] = resp_temp_l_pg(arr + 4);
3068 			break;
3069 		case 0x2f:	/* Informational exceptions log page */
3070 			arr[3] = resp_ie_l_pg(arr + 4);
3071 			break;
3072 		default:
3073 			mk_sense_invalid_fld(scp, SDEB_IN_CDB, 2, 5);
3074 			return check_condition_result;
3075 		}
3076 	} else if (0xff == subpcode) {
3077 		arr[0] |= 0x40;
3078 		arr[1] = subpcode;
3079 		switch (pcode) {
3080 		case 0x0:	/* Supported log pages and subpages log page */
3081 			n = 4;
3082 			arr[n++] = 0x0;
3083 			arr[n++] = 0x0;		/* 0,0 page */
3084 			arr[n++] = 0x0;
3085 			arr[n++] = 0xff;	/* this page */
3086 			arr[n++] = 0xd;
3087 			arr[n++] = 0x0;		/* Temperature */
3088 			arr[n++] = 0xd;
3089 			arr[n++] = 0x1;		/* Environment reporting */
3090 			arr[n++] = 0xd;
3091 			arr[n++] = 0xff;	/* all 0xd subpages */
3092 			arr[n++] = 0x2f;
3093 			arr[n++] = 0x0;	/* Informational exceptions */
3094 			arr[n++] = 0x2f;
3095 			arr[n++] = 0xff;	/* all 0x2f subpages */
3096 			arr[3] = n - 4;
3097 			break;
3098 		case 0xd:	/* Temperature subpages */
3099 			n = 4;
3100 			arr[n++] = 0xd;
3101 			arr[n++] = 0x0;		/* Temperature */
3102 			arr[n++] = 0xd;
3103 			arr[n++] = 0x1;		/* Environment reporting */
3104 			arr[n++] = 0xd;
3105 			arr[n++] = 0xff;	/* these subpages */
3106 			arr[3] = n - 4;
3107 			break;
3108 		case 0x2f:	/* Informational exceptions subpages */
3109 			n = 4;
3110 			arr[n++] = 0x2f;
3111 			arr[n++] = 0x0;		/* Informational exceptions */
3112 			arr[n++] = 0x2f;
3113 			arr[n++] = 0xff;	/* these subpages */
3114 			arr[3] = n - 4;
3115 			break;
3116 		default:
3117 			mk_sense_invalid_fld(scp, SDEB_IN_CDB, 2, 5);
3118 			return check_condition_result;
3119 		}
3120 	} else if (subpcode > 0) {
3121 		arr[0] |= 0x40;
3122 		arr[1] = subpcode;
3123 		if (pcode == 0xd && subpcode == 1)
3124 			arr[3] = resp_env_rep_l_spg(arr + 4);
3125 		else {
3126 			mk_sense_invalid_fld(scp, SDEB_IN_CDB, 2, 5);
3127 			return check_condition_result;
3128 		}
3129 	} else {
3130 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, 3, -1);
3131 		return check_condition_result;
3132 	}
3133 	len = min_t(u32, get_unaligned_be16(arr + 2) + 4, alloc_len);
3134 	return fill_from_dev_buffer(scp, arr,
3135 		    min_t(u32, len, SDEBUG_MAX_INQ_ARR_SZ));
3136 }
3137 
3138 static inline bool sdebug_dev_is_zoned(struct sdebug_dev_info *devip)
3139 {
3140 	return devip->nr_zones != 0;
3141 }
3142 
3143 static struct sdeb_zone_state *zbc_zone(struct sdebug_dev_info *devip,
3144 					unsigned long long lba)
3145 {
3146 	u32 zno = lba >> devip->zsize_shift;
3147 	struct sdeb_zone_state *zsp;
3148 
3149 	if (devip->zcap == devip->zsize || zno < devip->nr_conv_zones)
3150 		return &devip->zstate[zno];
3151 
3152 	/*
3153 	 * If the zone capacity is less than the zone size, adjust for gap
3154 	 * zones.
3155 	 */
3156 	zno = 2 * zno - devip->nr_conv_zones;
3157 	WARN_ONCE(zno >= devip->nr_zones, "%u > %u\n", zno, devip->nr_zones);
3158 	zsp = &devip->zstate[zno];
3159 	if (lba >= zsp->z_start + zsp->z_size)
3160 		zsp++;
3161 	WARN_ON_ONCE(lba >= zsp->z_start + zsp->z_size);
3162 	return zsp;
3163 }
3164 
3165 static inline bool zbc_zone_is_conv(struct sdeb_zone_state *zsp)
3166 {
3167 	return zsp->z_type == ZBC_ZTYPE_CNV;
3168 }
3169 
3170 static inline bool zbc_zone_is_gap(struct sdeb_zone_state *zsp)
3171 {
3172 	return zsp->z_type == ZBC_ZTYPE_GAP;
3173 }
3174 
3175 static inline bool zbc_zone_is_seq(struct sdeb_zone_state *zsp)
3176 {
3177 	return !zbc_zone_is_conv(zsp) && !zbc_zone_is_gap(zsp);
3178 }
3179 
3180 static void zbc_close_zone(struct sdebug_dev_info *devip,
3181 			   struct sdeb_zone_state *zsp)
3182 {
3183 	enum sdebug_z_cond zc;
3184 
3185 	if (!zbc_zone_is_seq(zsp))
3186 		return;
3187 
3188 	zc = zsp->z_cond;
3189 	if (!(zc == ZC2_IMPLICIT_OPEN || zc == ZC3_EXPLICIT_OPEN))
3190 		return;
3191 
3192 	if (zc == ZC2_IMPLICIT_OPEN)
3193 		devip->nr_imp_open--;
3194 	else
3195 		devip->nr_exp_open--;
3196 
3197 	if (zsp->z_wp == zsp->z_start) {
3198 		zsp->z_cond = ZC1_EMPTY;
3199 	} else {
3200 		zsp->z_cond = ZC4_CLOSED;
3201 		devip->nr_closed++;
3202 	}
3203 }
3204 
3205 static void zbc_close_imp_open_zone(struct sdebug_dev_info *devip)
3206 {
3207 	struct sdeb_zone_state *zsp = &devip->zstate[0];
3208 	unsigned int i;
3209 
3210 	for (i = 0; i < devip->nr_zones; i++, zsp++) {
3211 		if (zsp->z_cond == ZC2_IMPLICIT_OPEN) {
3212 			zbc_close_zone(devip, zsp);
3213 			return;
3214 		}
3215 	}
3216 }
3217 
3218 static void zbc_open_zone(struct sdebug_dev_info *devip,
3219 			  struct sdeb_zone_state *zsp, bool explicit)
3220 {
3221 	enum sdebug_z_cond zc;
3222 
3223 	if (!zbc_zone_is_seq(zsp))
3224 		return;
3225 
3226 	zc = zsp->z_cond;
3227 	if ((explicit && zc == ZC3_EXPLICIT_OPEN) ||
3228 	    (!explicit && zc == ZC2_IMPLICIT_OPEN))
3229 		return;
3230 
3231 	/* Close an implicit open zone if necessary */
3232 	if (explicit && zsp->z_cond == ZC2_IMPLICIT_OPEN)
3233 		zbc_close_zone(devip, zsp);
3234 	else if (devip->max_open &&
3235 		 devip->nr_imp_open + devip->nr_exp_open >= devip->max_open)
3236 		zbc_close_imp_open_zone(devip);
3237 
3238 	if (zsp->z_cond == ZC4_CLOSED)
3239 		devip->nr_closed--;
3240 	if (explicit) {
3241 		zsp->z_cond = ZC3_EXPLICIT_OPEN;
3242 		devip->nr_exp_open++;
3243 	} else {
3244 		zsp->z_cond = ZC2_IMPLICIT_OPEN;
3245 		devip->nr_imp_open++;
3246 	}
3247 }
3248 
3249 static inline void zbc_set_zone_full(struct sdebug_dev_info *devip,
3250 				     struct sdeb_zone_state *zsp)
3251 {
3252 	switch (zsp->z_cond) {
3253 	case ZC2_IMPLICIT_OPEN:
3254 		devip->nr_imp_open--;
3255 		break;
3256 	case ZC3_EXPLICIT_OPEN:
3257 		devip->nr_exp_open--;
3258 		break;
3259 	default:
3260 		WARN_ONCE(true, "Invalid zone %llu condition %x\n",
3261 			  zsp->z_start, zsp->z_cond);
3262 		break;
3263 	}
3264 	zsp->z_cond = ZC5_FULL;
3265 }
3266 
3267 static void zbc_inc_wp(struct sdebug_dev_info *devip,
3268 		       unsigned long long lba, unsigned int num)
3269 {
3270 	struct sdeb_zone_state *zsp = zbc_zone(devip, lba);
3271 	unsigned long long n, end, zend = zsp->z_start + zsp->z_size;
3272 
3273 	if (!zbc_zone_is_seq(zsp))
3274 		return;
3275 
3276 	if (zsp->z_type == ZBC_ZTYPE_SWR) {
3277 		zsp->z_wp += num;
3278 		if (zsp->z_wp >= zend)
3279 			zbc_set_zone_full(devip, zsp);
3280 		return;
3281 	}
3282 
3283 	while (num) {
3284 		if (lba != zsp->z_wp)
3285 			zsp->z_non_seq_resource = true;
3286 
3287 		end = lba + num;
3288 		if (end >= zend) {
3289 			n = zend - lba;
3290 			zsp->z_wp = zend;
3291 		} else if (end > zsp->z_wp) {
3292 			n = num;
3293 			zsp->z_wp = end;
3294 		} else {
3295 			n = num;
3296 		}
3297 		if (zsp->z_wp >= zend)
3298 			zbc_set_zone_full(devip, zsp);
3299 
3300 		num -= n;
3301 		lba += n;
3302 		if (num) {
3303 			zsp++;
3304 			zend = zsp->z_start + zsp->z_size;
3305 		}
3306 	}
3307 }
3308 
3309 static int check_zbc_access_params(struct scsi_cmnd *scp,
3310 			unsigned long long lba, unsigned int num, bool write)
3311 {
3312 	struct scsi_device *sdp = scp->device;
3313 	struct sdebug_dev_info *devip = (struct sdebug_dev_info *)sdp->hostdata;
3314 	struct sdeb_zone_state *zsp = zbc_zone(devip, lba);
3315 	struct sdeb_zone_state *zsp_end = zbc_zone(devip, lba + num - 1);
3316 
3317 	if (!write) {
3318 		/* For host-managed, reads cannot cross zone types boundaries */
3319 		if (zsp->z_type != zsp_end->z_type) {
3320 			mk_sense_buffer(scp, ILLEGAL_REQUEST,
3321 					LBA_OUT_OF_RANGE,
3322 					READ_INVDATA_ASCQ);
3323 			return check_condition_result;
3324 		}
3325 		return 0;
3326 	}
3327 
3328 	/* Writing into a gap zone is not allowed */
3329 	if (zbc_zone_is_gap(zsp)) {
3330 		mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE,
3331 				ATTEMPT_ACCESS_GAP);
3332 		return check_condition_result;
3333 	}
3334 
3335 	/* No restrictions for writes within conventional zones */
3336 	if (zbc_zone_is_conv(zsp)) {
3337 		if (!zbc_zone_is_conv(zsp_end)) {
3338 			mk_sense_buffer(scp, ILLEGAL_REQUEST,
3339 					LBA_OUT_OF_RANGE,
3340 					WRITE_BOUNDARY_ASCQ);
3341 			return check_condition_result;
3342 		}
3343 		return 0;
3344 	}
3345 
3346 	if (zsp->z_type == ZBC_ZTYPE_SWR) {
3347 		/* Writes cannot cross sequential zone boundaries */
3348 		if (zsp_end != zsp) {
3349 			mk_sense_buffer(scp, ILLEGAL_REQUEST,
3350 					LBA_OUT_OF_RANGE,
3351 					WRITE_BOUNDARY_ASCQ);
3352 			return check_condition_result;
3353 		}
3354 		/* Cannot write full zones */
3355 		if (zsp->z_cond == ZC5_FULL) {
3356 			mk_sense_buffer(scp, ILLEGAL_REQUEST,
3357 					INVALID_FIELD_IN_CDB, 0);
3358 			return check_condition_result;
3359 		}
3360 		/* Writes must be aligned to the zone WP */
3361 		if (lba != zsp->z_wp) {
3362 			mk_sense_buffer(scp, ILLEGAL_REQUEST,
3363 					LBA_OUT_OF_RANGE,
3364 					UNALIGNED_WRITE_ASCQ);
3365 			return check_condition_result;
3366 		}
3367 	}
3368 
3369 	/* Handle implicit open of closed and empty zones */
3370 	if (zsp->z_cond == ZC1_EMPTY || zsp->z_cond == ZC4_CLOSED) {
3371 		if (devip->max_open &&
3372 		    devip->nr_exp_open >= devip->max_open) {
3373 			mk_sense_buffer(scp, DATA_PROTECT,
3374 					INSUFF_RES_ASC,
3375 					INSUFF_ZONE_ASCQ);
3376 			return check_condition_result;
3377 		}
3378 		zbc_open_zone(devip, zsp, false);
3379 	}
3380 
3381 	return 0;
3382 }
3383 
3384 static inline int check_device_access_params
3385 			(struct scsi_cmnd *scp, unsigned long long lba,
3386 			 unsigned int num, bool write)
3387 {
3388 	struct scsi_device *sdp = scp->device;
3389 	struct sdebug_dev_info *devip = (struct sdebug_dev_info *)sdp->hostdata;
3390 
3391 	if (lba + num > sdebug_capacity) {
3392 		mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0);
3393 		return check_condition_result;
3394 	}
3395 	/* transfer length excessive (tie in to block limits VPD page) */
3396 	if (num > sdebug_store_sectors) {
3397 		/* needs work to find which cdb byte 'num' comes from */
3398 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0);
3399 		return check_condition_result;
3400 	}
3401 	if (write && unlikely(sdebug_wp)) {
3402 		mk_sense_buffer(scp, DATA_PROTECT, WRITE_PROTECTED, 0x2);
3403 		return check_condition_result;
3404 	}
3405 	if (sdebug_dev_is_zoned(devip))
3406 		return check_zbc_access_params(scp, lba, num, write);
3407 
3408 	return 0;
3409 }
3410 
3411 /*
3412  * Note: if BUG_ON() fires it usually indicates a problem with the parser
3413  * tables. Perhaps a missing F_FAKE_RW or FF_MEDIA_IO flag. Response functions
3414  * that access any of the "stores" in struct sdeb_store_info should call this
3415  * function with bug_if_fake_rw set to true.
3416  */
3417 static inline struct sdeb_store_info *devip2sip(struct sdebug_dev_info *devip,
3418 						bool bug_if_fake_rw)
3419 {
3420 	if (sdebug_fake_rw) {
3421 		BUG_ON(bug_if_fake_rw);	/* See note above */
3422 		return NULL;
3423 	}
3424 	return xa_load(per_store_ap, devip->sdbg_host->si_idx);
3425 }
3426 
3427 static inline void
3428 sdeb_read_lock(rwlock_t *lock)
3429 {
3430 	if (sdebug_no_rwlock)
3431 		__acquire(lock);
3432 	else
3433 		read_lock(lock);
3434 }
3435 
3436 static inline void
3437 sdeb_read_unlock(rwlock_t *lock)
3438 {
3439 	if (sdebug_no_rwlock)
3440 		__release(lock);
3441 	else
3442 		read_unlock(lock);
3443 }
3444 
3445 static inline void
3446 sdeb_write_lock(rwlock_t *lock)
3447 {
3448 	if (sdebug_no_rwlock)
3449 		__acquire(lock);
3450 	else
3451 		write_lock(lock);
3452 }
3453 
3454 static inline void
3455 sdeb_write_unlock(rwlock_t *lock)
3456 {
3457 	if (sdebug_no_rwlock)
3458 		__release(lock);
3459 	else
3460 		write_unlock(lock);
3461 }
3462 
3463 static inline void
3464 sdeb_data_read_lock(struct sdeb_store_info *sip)
3465 {
3466 	BUG_ON(!sip);
3467 
3468 	sdeb_read_lock(&sip->macc_data_lck);
3469 }
3470 
3471 static inline void
3472 sdeb_data_read_unlock(struct sdeb_store_info *sip)
3473 {
3474 	BUG_ON(!sip);
3475 
3476 	sdeb_read_unlock(&sip->macc_data_lck);
3477 }
3478 
3479 static inline void
3480 sdeb_data_write_lock(struct sdeb_store_info *sip)
3481 {
3482 	BUG_ON(!sip);
3483 
3484 	sdeb_write_lock(&sip->macc_data_lck);
3485 }
3486 
3487 static inline void
3488 sdeb_data_write_unlock(struct sdeb_store_info *sip)
3489 {
3490 	BUG_ON(!sip);
3491 
3492 	sdeb_write_unlock(&sip->macc_data_lck);
3493 }
3494 
3495 static inline void
3496 sdeb_data_sector_read_lock(struct sdeb_store_info *sip)
3497 {
3498 	BUG_ON(!sip);
3499 
3500 	sdeb_read_lock(&sip->macc_sector_lck);
3501 }
3502 
3503 static inline void
3504 sdeb_data_sector_read_unlock(struct sdeb_store_info *sip)
3505 {
3506 	BUG_ON(!sip);
3507 
3508 	sdeb_read_unlock(&sip->macc_sector_lck);
3509 }
3510 
3511 static inline void
3512 sdeb_data_sector_write_lock(struct sdeb_store_info *sip)
3513 {
3514 	BUG_ON(!sip);
3515 
3516 	sdeb_write_lock(&sip->macc_sector_lck);
3517 }
3518 
3519 static inline void
3520 sdeb_data_sector_write_unlock(struct sdeb_store_info *sip)
3521 {
3522 	BUG_ON(!sip);
3523 
3524 	sdeb_write_unlock(&sip->macc_sector_lck);
3525 }
3526 
3527 /*
3528  * Atomic locking:
3529  * We simplify the atomic model to allow only 1x atomic write and many non-
3530  * atomic reads or writes for all LBAs.
3531 
3532  * A RW lock has a similar bahaviour:
3533  * Only 1x writer and many readers.
3534 
3535  * So use a RW lock for per-device read and write locking:
3536  * An atomic access grabs the lock as a writer and non-atomic grabs the lock
3537  * as a reader.
3538  */
3539 
3540 static inline void
3541 sdeb_data_lock(struct sdeb_store_info *sip, bool atomic)
3542 {
3543 	if (atomic)
3544 		sdeb_data_write_lock(sip);
3545 	else
3546 		sdeb_data_read_lock(sip);
3547 }
3548 
3549 static inline void
3550 sdeb_data_unlock(struct sdeb_store_info *sip, bool atomic)
3551 {
3552 	if (atomic)
3553 		sdeb_data_write_unlock(sip);
3554 	else
3555 		sdeb_data_read_unlock(sip);
3556 }
3557 
3558 /* Allow many reads but only 1x write per sector */
3559 static inline void
3560 sdeb_data_sector_lock(struct sdeb_store_info *sip, bool do_write)
3561 {
3562 	if (do_write)
3563 		sdeb_data_sector_write_lock(sip);
3564 	else
3565 		sdeb_data_sector_read_lock(sip);
3566 }
3567 
3568 static inline void
3569 sdeb_data_sector_unlock(struct sdeb_store_info *sip, bool do_write)
3570 {
3571 	if (do_write)
3572 		sdeb_data_sector_write_unlock(sip);
3573 	else
3574 		sdeb_data_sector_read_unlock(sip);
3575 }
3576 
3577 static inline void
3578 sdeb_meta_read_lock(struct sdeb_store_info *sip)
3579 {
3580 	if (sdebug_no_rwlock) {
3581 		if (sip)
3582 			__acquire(&sip->macc_meta_lck);
3583 		else
3584 			__acquire(&sdeb_fake_rw_lck);
3585 	} else {
3586 		if (sip)
3587 			read_lock(&sip->macc_meta_lck);
3588 		else
3589 			read_lock(&sdeb_fake_rw_lck);
3590 	}
3591 }
3592 
3593 static inline void
3594 sdeb_meta_read_unlock(struct sdeb_store_info *sip)
3595 {
3596 	if (sdebug_no_rwlock) {
3597 		if (sip)
3598 			__release(&sip->macc_meta_lck);
3599 		else
3600 			__release(&sdeb_fake_rw_lck);
3601 	} else {
3602 		if (sip)
3603 			read_unlock(&sip->macc_meta_lck);
3604 		else
3605 			read_unlock(&sdeb_fake_rw_lck);
3606 	}
3607 }
3608 
3609 static inline void
3610 sdeb_meta_write_lock(struct sdeb_store_info *sip)
3611 {
3612 	if (sdebug_no_rwlock) {
3613 		if (sip)
3614 			__acquire(&sip->macc_meta_lck);
3615 		else
3616 			__acquire(&sdeb_fake_rw_lck);
3617 	} else {
3618 		if (sip)
3619 			write_lock(&sip->macc_meta_lck);
3620 		else
3621 			write_lock(&sdeb_fake_rw_lck);
3622 	}
3623 }
3624 
3625 static inline void
3626 sdeb_meta_write_unlock(struct sdeb_store_info *sip)
3627 {
3628 	if (sdebug_no_rwlock) {
3629 		if (sip)
3630 			__release(&sip->macc_meta_lck);
3631 		else
3632 			__release(&sdeb_fake_rw_lck);
3633 	} else {
3634 		if (sip)
3635 			write_unlock(&sip->macc_meta_lck);
3636 		else
3637 			write_unlock(&sdeb_fake_rw_lck);
3638 	}
3639 }
3640 
3641 /* Returns number of bytes copied or -1 if error. */
3642 static int do_device_access(struct sdeb_store_info *sip, struct scsi_cmnd *scp,
3643 			    u32 sg_skip, u64 lba, u32 num, u8 group_number,
3644 			    bool do_write, bool atomic)
3645 {
3646 	int ret;
3647 	u64 block;
3648 	enum dma_data_direction dir;
3649 	struct scsi_data_buffer *sdb = &scp->sdb;
3650 	u8 *fsp;
3651 	int i;
3652 
3653 	/*
3654 	 * Even though reads are inherently atomic (in this driver), we expect
3655 	 * the atomic flag only for writes.
3656 	 */
3657 	if (!do_write && atomic)
3658 		return -1;
3659 
3660 	if (do_write) {
3661 		dir = DMA_TO_DEVICE;
3662 		write_since_sync = true;
3663 	} else {
3664 		dir = DMA_FROM_DEVICE;
3665 	}
3666 
3667 	if (!sdb->length || !sip)
3668 		return 0;
3669 	if (scp->sc_data_direction != dir)
3670 		return -1;
3671 
3672 	if (do_write && group_number < ARRAY_SIZE(writes_by_group_number))
3673 		atomic_long_inc(&writes_by_group_number[group_number]);
3674 
3675 	fsp = sip->storep;
3676 
3677 	block = do_div(lba, sdebug_store_sectors);
3678 
3679 	/* Only allow 1x atomic write or multiple non-atomic writes at any given time */
3680 	sdeb_data_lock(sip, atomic);
3681 	for (i = 0; i < num; i++) {
3682 		/* We shouldn't need to lock for atomic writes, but do it anyway */
3683 		sdeb_data_sector_lock(sip, do_write);
3684 		ret = sg_copy_buffer(sdb->table.sgl, sdb->table.nents,
3685 		   fsp + (block * sdebug_sector_size),
3686 		   sdebug_sector_size, sg_skip, do_write);
3687 		sdeb_data_sector_unlock(sip, do_write);
3688 		if (ret != sdebug_sector_size) {
3689 			ret += (i * sdebug_sector_size);
3690 			break;
3691 		}
3692 		sg_skip += sdebug_sector_size;
3693 		if (++block >= sdebug_store_sectors)
3694 			block = 0;
3695 	}
3696 	ret = num * sdebug_sector_size;
3697 	sdeb_data_unlock(sip, atomic);
3698 
3699 	return ret;
3700 }
3701 
3702 /* Returns number of bytes copied or -1 if error. */
3703 static int do_dout_fetch(struct scsi_cmnd *scp, u32 num, u8 *doutp)
3704 {
3705 	struct scsi_data_buffer *sdb = &scp->sdb;
3706 
3707 	if (!sdb->length)
3708 		return 0;
3709 	if (scp->sc_data_direction != DMA_TO_DEVICE)
3710 		return -1;
3711 	return sg_copy_buffer(sdb->table.sgl, sdb->table.nents, doutp,
3712 			      num * sdebug_sector_size, 0, true);
3713 }
3714 
3715 /* If sip->storep+lba compares equal to arr(num), then copy top half of
3716  * arr into sip->storep+lba and return true. If comparison fails then
3717  * return false. */
3718 static bool comp_write_worker(struct sdeb_store_info *sip, u64 lba, u32 num,
3719 			      const u8 *arr, bool compare_only)
3720 {
3721 	bool res;
3722 	u64 block, rest = 0;
3723 	u32 store_blks = sdebug_store_sectors;
3724 	u32 lb_size = sdebug_sector_size;
3725 	u8 *fsp = sip->storep;
3726 
3727 	block = do_div(lba, store_blks);
3728 	if (block + num > store_blks)
3729 		rest = block + num - store_blks;
3730 
3731 	res = !memcmp(fsp + (block * lb_size), arr, (num - rest) * lb_size);
3732 	if (!res)
3733 		return res;
3734 	if (rest)
3735 		res = memcmp(fsp, arr + ((num - rest) * lb_size),
3736 			     rest * lb_size);
3737 	if (!res)
3738 		return res;
3739 	if (compare_only)
3740 		return true;
3741 	arr += num * lb_size;
3742 	memcpy(fsp + (block * lb_size), arr, (num - rest) * lb_size);
3743 	if (rest)
3744 		memcpy(fsp, arr + ((num - rest) * lb_size), rest * lb_size);
3745 	return res;
3746 }
3747 
3748 static __be16 dif_compute_csum(const void *buf, int len)
3749 {
3750 	__be16 csum;
3751 
3752 	if (sdebug_guard)
3753 		csum = (__force __be16)ip_compute_csum(buf, len);
3754 	else
3755 		csum = cpu_to_be16(crc_t10dif(buf, len));
3756 
3757 	return csum;
3758 }
3759 
3760 static int dif_verify(struct t10_pi_tuple *sdt, const void *data,
3761 		      sector_t sector, u32 ei_lba)
3762 {
3763 	__be16 csum = dif_compute_csum(data, sdebug_sector_size);
3764 
3765 	if (sdt->guard_tag != csum) {
3766 		pr_err("GUARD check failed on sector %lu rcvd 0x%04x, data 0x%04x\n",
3767 			(unsigned long)sector,
3768 			be16_to_cpu(sdt->guard_tag),
3769 			be16_to_cpu(csum));
3770 		return 0x01;
3771 	}
3772 	if (sdebug_dif == T10_PI_TYPE1_PROTECTION &&
3773 	    be32_to_cpu(sdt->ref_tag) != (sector & 0xffffffff)) {
3774 		pr_err("REF check failed on sector %lu\n",
3775 			(unsigned long)sector);
3776 		return 0x03;
3777 	}
3778 	if (sdebug_dif == T10_PI_TYPE2_PROTECTION &&
3779 	    be32_to_cpu(sdt->ref_tag) != ei_lba) {
3780 		pr_err("REF check failed on sector %lu\n",
3781 			(unsigned long)sector);
3782 		return 0x03;
3783 	}
3784 	return 0;
3785 }
3786 
3787 static void dif_copy_prot(struct scsi_cmnd *scp, sector_t sector,
3788 			  unsigned int sectors, bool read)
3789 {
3790 	size_t resid;
3791 	void *paddr;
3792 	struct sdeb_store_info *sip = devip2sip((struct sdebug_dev_info *)
3793 						scp->device->hostdata, true);
3794 	struct t10_pi_tuple *dif_storep = sip->dif_storep;
3795 	const void *dif_store_end = dif_storep + sdebug_store_sectors;
3796 	struct sg_mapping_iter miter;
3797 
3798 	/* Bytes of protection data to copy into sgl */
3799 	resid = sectors * sizeof(*dif_storep);
3800 
3801 	sg_miter_start(&miter, scsi_prot_sglist(scp),
3802 		       scsi_prot_sg_count(scp), SG_MITER_ATOMIC |
3803 		       (read ? SG_MITER_TO_SG : SG_MITER_FROM_SG));
3804 
3805 	while (sg_miter_next(&miter) && resid > 0) {
3806 		size_t len = min_t(size_t, miter.length, resid);
3807 		void *start = dif_store(sip, sector);
3808 		size_t rest = 0;
3809 
3810 		if (dif_store_end < start + len)
3811 			rest = start + len - dif_store_end;
3812 
3813 		paddr = miter.addr;
3814 
3815 		if (read)
3816 			memcpy(paddr, start, len - rest);
3817 		else
3818 			memcpy(start, paddr, len - rest);
3819 
3820 		if (rest) {
3821 			if (read)
3822 				memcpy(paddr + len - rest, dif_storep, rest);
3823 			else
3824 				memcpy(dif_storep, paddr + len - rest, rest);
3825 		}
3826 
3827 		sector += len / sizeof(*dif_storep);
3828 		resid -= len;
3829 	}
3830 	sg_miter_stop(&miter);
3831 }
3832 
3833 static int prot_verify_read(struct scsi_cmnd *scp, sector_t start_sec,
3834 			    unsigned int sectors, u32 ei_lba)
3835 {
3836 	int ret = 0;
3837 	unsigned int i;
3838 	sector_t sector;
3839 	struct sdeb_store_info *sip = devip2sip((struct sdebug_dev_info *)
3840 						scp->device->hostdata, true);
3841 	struct t10_pi_tuple *sdt;
3842 
3843 	for (i = 0; i < sectors; i++, ei_lba++) {
3844 		sector = start_sec + i;
3845 		sdt = dif_store(sip, sector);
3846 
3847 		if (sdt->app_tag == cpu_to_be16(0xffff))
3848 			continue;
3849 
3850 		/*
3851 		 * Because scsi_debug acts as both initiator and
3852 		 * target we proceed to verify the PI even if
3853 		 * RDPROTECT=3. This is done so the "initiator" knows
3854 		 * which type of error to return. Otherwise we would
3855 		 * have to iterate over the PI twice.
3856 		 */
3857 		if (scp->cmnd[1] >> 5) { /* RDPROTECT */
3858 			ret = dif_verify(sdt, lba2fake_store(sip, sector),
3859 					 sector, ei_lba);
3860 			if (ret) {
3861 				dif_errors++;
3862 				break;
3863 			}
3864 		}
3865 	}
3866 
3867 	dif_copy_prot(scp, start_sec, sectors, true);
3868 	dix_reads++;
3869 
3870 	return ret;
3871 }
3872 
3873 static int resp_read_dt0(struct scsi_cmnd *scp, struct sdebug_dev_info *devip)
3874 {
3875 	bool check_prot;
3876 	u32 num;
3877 	u32 ei_lba;
3878 	int ret;
3879 	u64 lba;
3880 	struct sdeb_store_info *sip = devip2sip(devip, true);
3881 	u8 *cmd = scp->cmnd;
3882 	bool meta_data_locked = false;
3883 
3884 	switch (cmd[0]) {
3885 	case READ_16:
3886 		ei_lba = 0;
3887 		lba = get_unaligned_be64(cmd + 2);
3888 		num = get_unaligned_be32(cmd + 10);
3889 		check_prot = true;
3890 		break;
3891 	case READ_10:
3892 		ei_lba = 0;
3893 		lba = get_unaligned_be32(cmd + 2);
3894 		num = get_unaligned_be16(cmd + 7);
3895 		check_prot = true;
3896 		break;
3897 	case READ_6:
3898 		ei_lba = 0;
3899 		lba = (u32)cmd[3] | (u32)cmd[2] << 8 |
3900 		      (u32)(cmd[1] & 0x1f) << 16;
3901 		num = (0 == cmd[4]) ? 256 : cmd[4];
3902 		check_prot = true;
3903 		break;
3904 	case READ_12:
3905 		ei_lba = 0;
3906 		lba = get_unaligned_be32(cmd + 2);
3907 		num = get_unaligned_be32(cmd + 6);
3908 		check_prot = true;
3909 		break;
3910 	case XDWRITEREAD_10:
3911 		ei_lba = 0;
3912 		lba = get_unaligned_be32(cmd + 2);
3913 		num = get_unaligned_be16(cmd + 7);
3914 		check_prot = false;
3915 		break;
3916 	default:	/* assume READ(32) */
3917 		lba = get_unaligned_be64(cmd + 12);
3918 		ei_lba = get_unaligned_be32(cmd + 20);
3919 		num = get_unaligned_be32(cmd + 28);
3920 		check_prot = false;
3921 		break;
3922 	}
3923 	if (unlikely(have_dif_prot && check_prot)) {
3924 		if (sdebug_dif == T10_PI_TYPE2_PROTECTION &&
3925 		    (cmd[1] & 0xe0)) {
3926 			mk_sense_invalid_opcode(scp);
3927 			return check_condition_result;
3928 		}
3929 		if ((sdebug_dif == T10_PI_TYPE1_PROTECTION ||
3930 		     sdebug_dif == T10_PI_TYPE3_PROTECTION) &&
3931 		    (cmd[1] & 0xe0) == 0)
3932 			sdev_printk(KERN_ERR, scp->device, "Unprotected RD "
3933 				    "to DIF device\n");
3934 	}
3935 	if (unlikely((sdebug_opts & SDEBUG_OPT_SHORT_TRANSFER) &&
3936 		     atomic_read(&sdeb_inject_pending))) {
3937 		num /= 2;
3938 		atomic_set(&sdeb_inject_pending, 0);
3939 	}
3940 
3941 	/*
3942 	 * When checking device access params, for reads we only check data
3943 	 * versus what is set at init time, so no need to lock.
3944 	 */
3945 	ret = check_device_access_params(scp, lba, num, false);
3946 	if (ret)
3947 		return ret;
3948 	if (unlikely((SDEBUG_OPT_MEDIUM_ERR & sdebug_opts) &&
3949 		     (lba <= (sdebug_medium_error_start + sdebug_medium_error_count - 1)) &&
3950 		     ((lba + num) > sdebug_medium_error_start))) {
3951 		/* claim unrecoverable read error */
3952 		mk_sense_buffer(scp, MEDIUM_ERROR, UNRECOVERED_READ_ERR, 0);
3953 		/* set info field and valid bit for fixed descriptor */
3954 		if (0x70 == (scp->sense_buffer[0] & 0x7f)) {
3955 			scp->sense_buffer[0] |= 0x80;	/* Valid bit */
3956 			ret = (lba < OPT_MEDIUM_ERR_ADDR)
3957 			      ? OPT_MEDIUM_ERR_ADDR : (int)lba;
3958 			put_unaligned_be32(ret, scp->sense_buffer + 3);
3959 		}
3960 		scsi_set_resid(scp, scsi_bufflen(scp));
3961 		return check_condition_result;
3962 	}
3963 
3964 	if (sdebug_dev_is_zoned(devip) ||
3965 	    (sdebug_dix && scsi_prot_sg_count(scp)))  {
3966 		sdeb_meta_read_lock(sip);
3967 		meta_data_locked = true;
3968 	}
3969 
3970 	/* DIX + T10 DIF */
3971 	if (unlikely(sdebug_dix && scsi_prot_sg_count(scp))) {
3972 		switch (prot_verify_read(scp, lba, num, ei_lba)) {
3973 		case 1: /* Guard tag error */
3974 			if (cmd[1] >> 5 != 3) { /* RDPROTECT != 3 */
3975 				sdeb_meta_read_unlock(sip);
3976 				mk_sense_buffer(scp, ABORTED_COMMAND, 0x10, 1);
3977 				return check_condition_result;
3978 			} else if (scp->prot_flags & SCSI_PROT_GUARD_CHECK) {
3979 				sdeb_meta_read_unlock(sip);
3980 				mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10, 1);
3981 				return illegal_condition_result;
3982 			}
3983 			break;
3984 		case 3: /* Reference tag error */
3985 			if (cmd[1] >> 5 != 3) { /* RDPROTECT != 3 */
3986 				sdeb_meta_read_unlock(sip);
3987 				mk_sense_buffer(scp, ABORTED_COMMAND, 0x10, 3);
3988 				return check_condition_result;
3989 			} else if (scp->prot_flags & SCSI_PROT_REF_CHECK) {
3990 				sdeb_meta_read_unlock(sip);
3991 				mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10, 3);
3992 				return illegal_condition_result;
3993 			}
3994 			break;
3995 		}
3996 	}
3997 
3998 	ret = do_device_access(sip, scp, 0, lba, num, 0, false, false);
3999 	if (meta_data_locked)
4000 		sdeb_meta_read_unlock(sip);
4001 	if (unlikely(ret == -1))
4002 		return DID_ERROR << 16;
4003 
4004 	scsi_set_resid(scp, scsi_bufflen(scp) - ret);
4005 
4006 	if (unlikely((sdebug_opts & SDEBUG_OPT_RECOV_DIF_DIX) &&
4007 		     atomic_read(&sdeb_inject_pending))) {
4008 		if (sdebug_opts & SDEBUG_OPT_RECOVERED_ERR) {
4009 			mk_sense_buffer(scp, RECOVERED_ERROR, THRESHOLD_EXCEEDED, 0);
4010 			atomic_set(&sdeb_inject_pending, 0);
4011 			return check_condition_result;
4012 		} else if (sdebug_opts & SDEBUG_OPT_DIF_ERR) {
4013 			/* Logical block guard check failed */
4014 			mk_sense_buffer(scp, ABORTED_COMMAND, 0x10, 1);
4015 			atomic_set(&sdeb_inject_pending, 0);
4016 			return illegal_condition_result;
4017 		} else if (SDEBUG_OPT_DIX_ERR & sdebug_opts) {
4018 			mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10, 1);
4019 			atomic_set(&sdeb_inject_pending, 0);
4020 			return illegal_condition_result;
4021 		}
4022 	}
4023 	return 0;
4024 }
4025 
4026 static int prot_verify_write(struct scsi_cmnd *SCpnt, sector_t start_sec,
4027 			     unsigned int sectors, u32 ei_lba)
4028 {
4029 	int ret;
4030 	struct t10_pi_tuple *sdt;
4031 	void *daddr;
4032 	sector_t sector = start_sec;
4033 	int ppage_offset;
4034 	int dpage_offset;
4035 	struct sg_mapping_iter diter;
4036 	struct sg_mapping_iter piter;
4037 
4038 	BUG_ON(scsi_sg_count(SCpnt) == 0);
4039 	BUG_ON(scsi_prot_sg_count(SCpnt) == 0);
4040 
4041 	sg_miter_start(&piter, scsi_prot_sglist(SCpnt),
4042 			scsi_prot_sg_count(SCpnt),
4043 			SG_MITER_ATOMIC | SG_MITER_FROM_SG);
4044 	sg_miter_start(&diter, scsi_sglist(SCpnt), scsi_sg_count(SCpnt),
4045 			SG_MITER_ATOMIC | SG_MITER_FROM_SG);
4046 
4047 	/* For each protection page */
4048 	while (sg_miter_next(&piter)) {
4049 		dpage_offset = 0;
4050 		if (WARN_ON(!sg_miter_next(&diter))) {
4051 			ret = 0x01;
4052 			goto out;
4053 		}
4054 
4055 		for (ppage_offset = 0; ppage_offset < piter.length;
4056 		     ppage_offset += sizeof(struct t10_pi_tuple)) {
4057 			/* If we're at the end of the current
4058 			 * data page advance to the next one
4059 			 */
4060 			if (dpage_offset >= diter.length) {
4061 				if (WARN_ON(!sg_miter_next(&diter))) {
4062 					ret = 0x01;
4063 					goto out;
4064 				}
4065 				dpage_offset = 0;
4066 			}
4067 
4068 			sdt = piter.addr + ppage_offset;
4069 			daddr = diter.addr + dpage_offset;
4070 
4071 			if (SCpnt->cmnd[1] >> 5 != 3) { /* WRPROTECT */
4072 				ret = dif_verify(sdt, daddr, sector, ei_lba);
4073 				if (ret)
4074 					goto out;
4075 			}
4076 
4077 			sector++;
4078 			ei_lba++;
4079 			dpage_offset += sdebug_sector_size;
4080 		}
4081 		diter.consumed = dpage_offset;
4082 		sg_miter_stop(&diter);
4083 	}
4084 	sg_miter_stop(&piter);
4085 
4086 	dif_copy_prot(SCpnt, start_sec, sectors, false);
4087 	dix_writes++;
4088 
4089 	return 0;
4090 
4091 out:
4092 	dif_errors++;
4093 	sg_miter_stop(&diter);
4094 	sg_miter_stop(&piter);
4095 	return ret;
4096 }
4097 
4098 static unsigned long lba_to_map_index(sector_t lba)
4099 {
4100 	if (sdebug_unmap_alignment)
4101 		lba += sdebug_unmap_granularity - sdebug_unmap_alignment;
4102 	sector_div(lba, sdebug_unmap_granularity);
4103 	return lba;
4104 }
4105 
4106 static sector_t map_index_to_lba(unsigned long index)
4107 {
4108 	sector_t lba = index * sdebug_unmap_granularity;
4109 
4110 	if (sdebug_unmap_alignment)
4111 		lba -= sdebug_unmap_granularity - sdebug_unmap_alignment;
4112 	return lba;
4113 }
4114 
4115 static unsigned int map_state(struct sdeb_store_info *sip, sector_t lba,
4116 			      unsigned int *num)
4117 {
4118 	sector_t end;
4119 	unsigned int mapped;
4120 	unsigned long index;
4121 	unsigned long next;
4122 
4123 	index = lba_to_map_index(lba);
4124 	mapped = test_bit(index, sip->map_storep);
4125 
4126 	if (mapped)
4127 		next = find_next_zero_bit(sip->map_storep, map_size, index);
4128 	else
4129 		next = find_next_bit(sip->map_storep, map_size, index);
4130 
4131 	end = min_t(sector_t, sdebug_store_sectors,  map_index_to_lba(next));
4132 	*num = end - lba;
4133 	return mapped;
4134 }
4135 
4136 static void map_region(struct sdeb_store_info *sip, sector_t lba,
4137 		       unsigned int len)
4138 {
4139 	sector_t end = lba + len;
4140 
4141 	while (lba < end) {
4142 		unsigned long index = lba_to_map_index(lba);
4143 
4144 		if (index < map_size)
4145 			set_bit(index, sip->map_storep);
4146 
4147 		lba = map_index_to_lba(index + 1);
4148 	}
4149 }
4150 
4151 static void unmap_region(struct sdeb_store_info *sip, sector_t lba,
4152 			 unsigned int len)
4153 {
4154 	sector_t end = lba + len;
4155 	u8 *fsp = sip->storep;
4156 
4157 	while (lba < end) {
4158 		unsigned long index = lba_to_map_index(lba);
4159 
4160 		if (lba == map_index_to_lba(index) &&
4161 		    lba + sdebug_unmap_granularity <= end &&
4162 		    index < map_size) {
4163 			clear_bit(index, sip->map_storep);
4164 			if (sdebug_lbprz) {  /* for LBPRZ=2 return 0xff_s */
4165 				memset(fsp + lba * sdebug_sector_size,
4166 				       (sdebug_lbprz & 1) ? 0 : 0xff,
4167 				       sdebug_sector_size *
4168 				       sdebug_unmap_granularity);
4169 			}
4170 			if (sip->dif_storep) {
4171 				memset(sip->dif_storep + lba, 0xff,
4172 				       sizeof(*sip->dif_storep) *
4173 				       sdebug_unmap_granularity);
4174 			}
4175 		}
4176 		lba = map_index_to_lba(index + 1);
4177 	}
4178 }
4179 
4180 static int resp_write_dt0(struct scsi_cmnd *scp, struct sdebug_dev_info *devip)
4181 {
4182 	bool check_prot;
4183 	u32 num;
4184 	u8 group = 0;
4185 	u32 ei_lba;
4186 	int ret;
4187 	u64 lba;
4188 	struct sdeb_store_info *sip = devip2sip(devip, true);
4189 	u8 *cmd = scp->cmnd;
4190 	bool meta_data_locked = false;
4191 
4192 	switch (cmd[0]) {
4193 	case WRITE_16:
4194 		ei_lba = 0;
4195 		lba = get_unaligned_be64(cmd + 2);
4196 		num = get_unaligned_be32(cmd + 10);
4197 		group = cmd[14] & 0x3f;
4198 		check_prot = true;
4199 		break;
4200 	case WRITE_10:
4201 		ei_lba = 0;
4202 		lba = get_unaligned_be32(cmd + 2);
4203 		group = cmd[6] & 0x3f;
4204 		num = get_unaligned_be16(cmd + 7);
4205 		check_prot = true;
4206 		break;
4207 	case WRITE_6:
4208 		ei_lba = 0;
4209 		lba = (u32)cmd[3] | (u32)cmd[2] << 8 |
4210 		      (u32)(cmd[1] & 0x1f) << 16;
4211 		num = (0 == cmd[4]) ? 256 : cmd[4];
4212 		check_prot = true;
4213 		break;
4214 	case WRITE_12:
4215 		ei_lba = 0;
4216 		lba = get_unaligned_be32(cmd + 2);
4217 		num = get_unaligned_be32(cmd + 6);
4218 		group = cmd[6] & 0x3f;
4219 		check_prot = true;
4220 		break;
4221 	case 0x53:	/* XDWRITEREAD(10) */
4222 		ei_lba = 0;
4223 		lba = get_unaligned_be32(cmd + 2);
4224 		group = cmd[6] & 0x1f;
4225 		num = get_unaligned_be16(cmd + 7);
4226 		check_prot = false;
4227 		break;
4228 	default:	/* assume WRITE(32) */
4229 		group = cmd[6] & 0x3f;
4230 		lba = get_unaligned_be64(cmd + 12);
4231 		ei_lba = get_unaligned_be32(cmd + 20);
4232 		num = get_unaligned_be32(cmd + 28);
4233 		check_prot = false;
4234 		break;
4235 	}
4236 	if (unlikely(have_dif_prot && check_prot)) {
4237 		if (sdebug_dif == T10_PI_TYPE2_PROTECTION &&
4238 		    (cmd[1] & 0xe0)) {
4239 			mk_sense_invalid_opcode(scp);
4240 			return check_condition_result;
4241 		}
4242 		if ((sdebug_dif == T10_PI_TYPE1_PROTECTION ||
4243 		     sdebug_dif == T10_PI_TYPE3_PROTECTION) &&
4244 		    (cmd[1] & 0xe0) == 0)
4245 			sdev_printk(KERN_ERR, scp->device, "Unprotected WR "
4246 				    "to DIF device\n");
4247 	}
4248 
4249 	if (sdebug_dev_is_zoned(devip) ||
4250 	    (sdebug_dix && scsi_prot_sg_count(scp)) ||
4251 	    scsi_debug_lbp())  {
4252 		sdeb_meta_write_lock(sip);
4253 		meta_data_locked = true;
4254 	}
4255 
4256 	ret = check_device_access_params(scp, lba, num, true);
4257 	if (ret) {
4258 		if (meta_data_locked)
4259 			sdeb_meta_write_unlock(sip);
4260 		return ret;
4261 	}
4262 
4263 	/* DIX + T10 DIF */
4264 	if (unlikely(sdebug_dix && scsi_prot_sg_count(scp))) {
4265 		switch (prot_verify_write(scp, lba, num, ei_lba)) {
4266 		case 1: /* Guard tag error */
4267 			if (scp->prot_flags & SCSI_PROT_GUARD_CHECK) {
4268 				sdeb_meta_write_unlock(sip);
4269 				mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10, 1);
4270 				return illegal_condition_result;
4271 			} else if (scp->cmnd[1] >> 5 != 3) { /* WRPROTECT != 3 */
4272 				sdeb_meta_write_unlock(sip);
4273 				mk_sense_buffer(scp, ABORTED_COMMAND, 0x10, 1);
4274 				return check_condition_result;
4275 			}
4276 			break;
4277 		case 3: /* Reference tag error */
4278 			if (scp->prot_flags & SCSI_PROT_REF_CHECK) {
4279 				sdeb_meta_write_unlock(sip);
4280 				mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10, 3);
4281 				return illegal_condition_result;
4282 			} else if (scp->cmnd[1] >> 5 != 3) { /* WRPROTECT != 3 */
4283 				sdeb_meta_write_unlock(sip);
4284 				mk_sense_buffer(scp, ABORTED_COMMAND, 0x10, 3);
4285 				return check_condition_result;
4286 			}
4287 			break;
4288 		}
4289 	}
4290 
4291 	ret = do_device_access(sip, scp, 0, lba, num, group, true, false);
4292 	if (unlikely(scsi_debug_lbp()))
4293 		map_region(sip, lba, num);
4294 
4295 	/* If ZBC zone then bump its write pointer */
4296 	if (sdebug_dev_is_zoned(devip))
4297 		zbc_inc_wp(devip, lba, num);
4298 	if (meta_data_locked)
4299 		sdeb_meta_write_unlock(sip);
4300 
4301 	if (unlikely(-1 == ret))
4302 		return DID_ERROR << 16;
4303 	else if (unlikely(sdebug_verbose &&
4304 			  (ret < (num * sdebug_sector_size))))
4305 		sdev_printk(KERN_INFO, scp->device,
4306 			    "%s: write: cdb indicated=%u, IO sent=%d bytes\n",
4307 			    my_name, num * sdebug_sector_size, ret);
4308 
4309 	if (unlikely((sdebug_opts & SDEBUG_OPT_RECOV_DIF_DIX) &&
4310 		     atomic_read(&sdeb_inject_pending))) {
4311 		if (sdebug_opts & SDEBUG_OPT_RECOVERED_ERR) {
4312 			mk_sense_buffer(scp, RECOVERED_ERROR, THRESHOLD_EXCEEDED, 0);
4313 			atomic_set(&sdeb_inject_pending, 0);
4314 			return check_condition_result;
4315 		} else if (sdebug_opts & SDEBUG_OPT_DIF_ERR) {
4316 			/* Logical block guard check failed */
4317 			mk_sense_buffer(scp, ABORTED_COMMAND, 0x10, 1);
4318 			atomic_set(&sdeb_inject_pending, 0);
4319 			return illegal_condition_result;
4320 		} else if (sdebug_opts & SDEBUG_OPT_DIX_ERR) {
4321 			mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10, 1);
4322 			atomic_set(&sdeb_inject_pending, 0);
4323 			return illegal_condition_result;
4324 		}
4325 	}
4326 	return 0;
4327 }
4328 
4329 /*
4330  * T10 has only specified WRITE SCATTERED(16) and WRITE SCATTERED(32).
4331  * No READ GATHERED yet (requires bidi or long cdb holding gather list).
4332  */
4333 static int resp_write_scat(struct scsi_cmnd *scp,
4334 			   struct sdebug_dev_info *devip)
4335 {
4336 	u8 *cmd = scp->cmnd;
4337 	u8 *lrdp = NULL;
4338 	u8 *up;
4339 	struct sdeb_store_info *sip = devip2sip(devip, true);
4340 	u8 wrprotect;
4341 	u16 lbdof, num_lrd, k;
4342 	u32 num, num_by, bt_len, lbdof_blen, sg_off, cum_lb;
4343 	u32 lb_size = sdebug_sector_size;
4344 	u32 ei_lba;
4345 	u64 lba;
4346 	u8 group;
4347 	int ret, res;
4348 	bool is_16;
4349 	static const u32 lrd_size = 32; /* + parameter list header size */
4350 
4351 	if (cmd[0] == VARIABLE_LENGTH_CMD) {
4352 		is_16 = false;
4353 		group = cmd[6] & 0x3f;
4354 		wrprotect = (cmd[10] >> 5) & 0x7;
4355 		lbdof = get_unaligned_be16(cmd + 12);
4356 		num_lrd = get_unaligned_be16(cmd + 16);
4357 		bt_len = get_unaligned_be32(cmd + 28);
4358 	} else {        /* that leaves WRITE SCATTERED(16) */
4359 		is_16 = true;
4360 		wrprotect = (cmd[2] >> 5) & 0x7;
4361 		lbdof = get_unaligned_be16(cmd + 4);
4362 		num_lrd = get_unaligned_be16(cmd + 8);
4363 		bt_len = get_unaligned_be32(cmd + 10);
4364 		group = cmd[14] & 0x3f;
4365 		if (unlikely(have_dif_prot)) {
4366 			if (sdebug_dif == T10_PI_TYPE2_PROTECTION &&
4367 			    wrprotect) {
4368 				mk_sense_invalid_opcode(scp);
4369 				return illegal_condition_result;
4370 			}
4371 			if ((sdebug_dif == T10_PI_TYPE1_PROTECTION ||
4372 			     sdebug_dif == T10_PI_TYPE3_PROTECTION) &&
4373 			     wrprotect == 0)
4374 				sdev_printk(KERN_ERR, scp->device,
4375 					    "Unprotected WR to DIF device\n");
4376 		}
4377 	}
4378 	if ((num_lrd == 0) || (bt_len == 0))
4379 		return 0;       /* T10 says these do-nothings are not errors */
4380 	if (lbdof == 0) {
4381 		if (sdebug_verbose)
4382 			sdev_printk(KERN_INFO, scp->device,
4383 				"%s: %s: LB Data Offset field bad\n",
4384 				my_name, __func__);
4385 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0);
4386 		return illegal_condition_result;
4387 	}
4388 	lbdof_blen = lbdof * lb_size;
4389 	if ((lrd_size + (num_lrd * lrd_size)) > lbdof_blen) {
4390 		if (sdebug_verbose)
4391 			sdev_printk(KERN_INFO, scp->device,
4392 				"%s: %s: LBA range descriptors don't fit\n",
4393 				my_name, __func__);
4394 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0);
4395 		return illegal_condition_result;
4396 	}
4397 	lrdp = kzalloc(lbdof_blen, GFP_ATOMIC | __GFP_NOWARN);
4398 	if (lrdp == NULL)
4399 		return SCSI_MLQUEUE_HOST_BUSY;
4400 	if (sdebug_verbose)
4401 		sdev_printk(KERN_INFO, scp->device,
4402 			"%s: %s: Fetch header+scatter_list, lbdof_blen=%u\n",
4403 			my_name, __func__, lbdof_blen);
4404 	res = fetch_to_dev_buffer(scp, lrdp, lbdof_blen);
4405 	if (res == -1) {
4406 		ret = DID_ERROR << 16;
4407 		goto err_out;
4408 	}
4409 
4410 	/* Just keep it simple and always lock for now */
4411 	sdeb_meta_write_lock(sip);
4412 	sg_off = lbdof_blen;
4413 	/* Spec says Buffer xfer Length field in number of LBs in dout */
4414 	cum_lb = 0;
4415 	for (k = 0, up = lrdp + lrd_size; k < num_lrd; ++k, up += lrd_size) {
4416 		lba = get_unaligned_be64(up + 0);
4417 		num = get_unaligned_be32(up + 8);
4418 		if (sdebug_verbose)
4419 			sdev_printk(KERN_INFO, scp->device,
4420 				"%s: %s: k=%d  LBA=0x%llx num=%u  sg_off=%u\n",
4421 				my_name, __func__, k, lba, num, sg_off);
4422 		if (num == 0)
4423 			continue;
4424 		ret = check_device_access_params(scp, lba, num, true);
4425 		if (ret)
4426 			goto err_out_unlock;
4427 		num_by = num * lb_size;
4428 		ei_lba = is_16 ? 0 : get_unaligned_be32(up + 12);
4429 
4430 		if ((cum_lb + num) > bt_len) {
4431 			if (sdebug_verbose)
4432 				sdev_printk(KERN_INFO, scp->device,
4433 				    "%s: %s: sum of blocks > data provided\n",
4434 				    my_name, __func__);
4435 			mk_sense_buffer(scp, ILLEGAL_REQUEST, WRITE_ERROR_ASC,
4436 					0);
4437 			ret = illegal_condition_result;
4438 			goto err_out_unlock;
4439 		}
4440 
4441 		/* DIX + T10 DIF */
4442 		if (unlikely(sdebug_dix && scsi_prot_sg_count(scp))) {
4443 			int prot_ret = prot_verify_write(scp, lba, num,
4444 							 ei_lba);
4445 
4446 			if (prot_ret) {
4447 				mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10,
4448 						prot_ret);
4449 				ret = illegal_condition_result;
4450 				goto err_out_unlock;
4451 			}
4452 		}
4453 
4454 		/*
4455 		 * Write ranges atomically to keep as close to pre-atomic
4456 		 * writes behaviour as possible.
4457 		 */
4458 		ret = do_device_access(sip, scp, sg_off, lba, num, group, true, true);
4459 		/* If ZBC zone then bump its write pointer */
4460 		if (sdebug_dev_is_zoned(devip))
4461 			zbc_inc_wp(devip, lba, num);
4462 		if (unlikely(scsi_debug_lbp()))
4463 			map_region(sip, lba, num);
4464 		if (unlikely(-1 == ret)) {
4465 			ret = DID_ERROR << 16;
4466 			goto err_out_unlock;
4467 		} else if (unlikely(sdebug_verbose && (ret < num_by)))
4468 			sdev_printk(KERN_INFO, scp->device,
4469 			    "%s: write: cdb indicated=%u, IO sent=%d bytes\n",
4470 			    my_name, num_by, ret);
4471 
4472 		if (unlikely((sdebug_opts & SDEBUG_OPT_RECOV_DIF_DIX) &&
4473 			     atomic_read(&sdeb_inject_pending))) {
4474 			if (sdebug_opts & SDEBUG_OPT_RECOVERED_ERR) {
4475 				mk_sense_buffer(scp, RECOVERED_ERROR, THRESHOLD_EXCEEDED, 0);
4476 				atomic_set(&sdeb_inject_pending, 0);
4477 				ret = check_condition_result;
4478 				goto err_out_unlock;
4479 			} else if (sdebug_opts & SDEBUG_OPT_DIF_ERR) {
4480 				/* Logical block guard check failed */
4481 				mk_sense_buffer(scp, ABORTED_COMMAND, 0x10, 1);
4482 				atomic_set(&sdeb_inject_pending, 0);
4483 				ret = illegal_condition_result;
4484 				goto err_out_unlock;
4485 			} else if (sdebug_opts & SDEBUG_OPT_DIX_ERR) {
4486 				mk_sense_buffer(scp, ILLEGAL_REQUEST, 0x10, 1);
4487 				atomic_set(&sdeb_inject_pending, 0);
4488 				ret = illegal_condition_result;
4489 				goto err_out_unlock;
4490 			}
4491 		}
4492 		sg_off += num_by;
4493 		cum_lb += num;
4494 	}
4495 	ret = 0;
4496 err_out_unlock:
4497 	sdeb_meta_write_unlock(sip);
4498 err_out:
4499 	kfree(lrdp);
4500 	return ret;
4501 }
4502 
4503 static int resp_write_same(struct scsi_cmnd *scp, u64 lba, u32 num,
4504 			   u32 ei_lba, bool unmap, bool ndob)
4505 {
4506 	struct scsi_device *sdp = scp->device;
4507 	struct sdebug_dev_info *devip = (struct sdebug_dev_info *)sdp->hostdata;
4508 	unsigned long long i;
4509 	u64 block, lbaa;
4510 	u32 lb_size = sdebug_sector_size;
4511 	int ret;
4512 	struct sdeb_store_info *sip = devip2sip((struct sdebug_dev_info *)
4513 						scp->device->hostdata, true);
4514 	u8 *fs1p;
4515 	u8 *fsp;
4516 	bool meta_data_locked = false;
4517 
4518 	if (sdebug_dev_is_zoned(devip) || scsi_debug_lbp()) {
4519 		sdeb_meta_write_lock(sip);
4520 		meta_data_locked = true;
4521 	}
4522 
4523 	ret = check_device_access_params(scp, lba, num, true);
4524 	if (ret)
4525 		goto out;
4526 
4527 	if (unmap && scsi_debug_lbp()) {
4528 		unmap_region(sip, lba, num);
4529 		goto out;
4530 	}
4531 	lbaa = lba;
4532 	block = do_div(lbaa, sdebug_store_sectors);
4533 	/* if ndob then zero 1 logical block, else fetch 1 logical block */
4534 	fsp = sip->storep;
4535 	fs1p = fsp + (block * lb_size);
4536 	sdeb_data_write_lock(sip);
4537 	if (ndob) {
4538 		memset(fs1p, 0, lb_size);
4539 		ret = 0;
4540 	} else
4541 		ret = fetch_to_dev_buffer(scp, fs1p, lb_size);
4542 
4543 	if (-1 == ret) {
4544 		ret = DID_ERROR << 16;
4545 		goto out;
4546 	} else if (sdebug_verbose && !ndob && (ret < lb_size))
4547 		sdev_printk(KERN_INFO, scp->device,
4548 			    "%s: %s: lb size=%u, IO sent=%d bytes\n",
4549 			    my_name, "write same", lb_size, ret);
4550 
4551 	/* Copy first sector to remaining blocks */
4552 	for (i = 1 ; i < num ; i++) {
4553 		lbaa = lba + i;
4554 		block = do_div(lbaa, sdebug_store_sectors);
4555 		memmove(fsp + (block * lb_size), fs1p, lb_size);
4556 	}
4557 	if (scsi_debug_lbp())
4558 		map_region(sip, lba, num);
4559 	/* If ZBC zone then bump its write pointer */
4560 	if (sdebug_dev_is_zoned(devip))
4561 		zbc_inc_wp(devip, lba, num);
4562 	sdeb_data_write_unlock(sip);
4563 	ret = 0;
4564 out:
4565 	if (meta_data_locked)
4566 		sdeb_meta_write_unlock(sip);
4567 	return ret;
4568 }
4569 
4570 static int resp_write_same_10(struct scsi_cmnd *scp,
4571 			      struct sdebug_dev_info *devip)
4572 {
4573 	u8 *cmd = scp->cmnd;
4574 	u32 lba;
4575 	u16 num;
4576 	u32 ei_lba = 0;
4577 	bool unmap = false;
4578 
4579 	if (cmd[1] & 0x8) {
4580 		if (sdebug_lbpws10 == 0) {
4581 			mk_sense_invalid_fld(scp, SDEB_IN_CDB, 1, 3);
4582 			return check_condition_result;
4583 		} else
4584 			unmap = true;
4585 	}
4586 	lba = get_unaligned_be32(cmd + 2);
4587 	num = get_unaligned_be16(cmd + 7);
4588 	if (num > sdebug_write_same_length) {
4589 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, 7, -1);
4590 		return check_condition_result;
4591 	}
4592 	return resp_write_same(scp, lba, num, ei_lba, unmap, false);
4593 }
4594 
4595 static int resp_write_same_16(struct scsi_cmnd *scp,
4596 			      struct sdebug_dev_info *devip)
4597 {
4598 	u8 *cmd = scp->cmnd;
4599 	u64 lba;
4600 	u32 num;
4601 	u32 ei_lba = 0;
4602 	bool unmap = false;
4603 	bool ndob = false;
4604 
4605 	if (cmd[1] & 0x8) {	/* UNMAP */
4606 		if (sdebug_lbpws == 0) {
4607 			mk_sense_invalid_fld(scp, SDEB_IN_CDB, 1, 3);
4608 			return check_condition_result;
4609 		} else
4610 			unmap = true;
4611 	}
4612 	if (cmd[1] & 0x1)  /* NDOB (no data-out buffer, assumes zeroes) */
4613 		ndob = true;
4614 	lba = get_unaligned_be64(cmd + 2);
4615 	num = get_unaligned_be32(cmd + 10);
4616 	if (num > sdebug_write_same_length) {
4617 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, 10, -1);
4618 		return check_condition_result;
4619 	}
4620 	return resp_write_same(scp, lba, num, ei_lba, unmap, ndob);
4621 }
4622 
4623 /* Note the mode field is in the same position as the (lower) service action
4624  * field. For the Report supported operation codes command, SPC-4 suggests
4625  * each mode of this command should be reported separately; for future. */
4626 static int resp_write_buffer(struct scsi_cmnd *scp,
4627 			     struct sdebug_dev_info *devip)
4628 {
4629 	u8 *cmd = scp->cmnd;
4630 	struct scsi_device *sdp = scp->device;
4631 	struct sdebug_dev_info *dp;
4632 	u8 mode;
4633 
4634 	mode = cmd[1] & 0x1f;
4635 	switch (mode) {
4636 	case 0x4:	/* download microcode (MC) and activate (ACT) */
4637 		/* set UAs on this device only */
4638 		set_bit(SDEBUG_UA_BUS_RESET, devip->uas_bm);
4639 		set_bit(SDEBUG_UA_MICROCODE_CHANGED, devip->uas_bm);
4640 		break;
4641 	case 0x5:	/* download MC, save and ACT */
4642 		set_bit(SDEBUG_UA_MICROCODE_CHANGED_WO_RESET, devip->uas_bm);
4643 		break;
4644 	case 0x6:	/* download MC with offsets and ACT */
4645 		/* set UAs on most devices (LUs) in this target */
4646 		list_for_each_entry(dp,
4647 				    &devip->sdbg_host->dev_info_list,
4648 				    dev_list)
4649 			if (dp->target == sdp->id) {
4650 				set_bit(SDEBUG_UA_BUS_RESET, dp->uas_bm);
4651 				if (devip != dp)
4652 					set_bit(SDEBUG_UA_MICROCODE_CHANGED,
4653 						dp->uas_bm);
4654 			}
4655 		break;
4656 	case 0x7:	/* download MC with offsets, save, and ACT */
4657 		/* set UA on all devices (LUs) in this target */
4658 		list_for_each_entry(dp,
4659 				    &devip->sdbg_host->dev_info_list,
4660 				    dev_list)
4661 			if (dp->target == sdp->id)
4662 				set_bit(SDEBUG_UA_MICROCODE_CHANGED_WO_RESET,
4663 					dp->uas_bm);
4664 		break;
4665 	default:
4666 		/* do nothing for this command for other mode values */
4667 		break;
4668 	}
4669 	return 0;
4670 }
4671 
4672 static int resp_comp_write(struct scsi_cmnd *scp,
4673 			   struct sdebug_dev_info *devip)
4674 {
4675 	u8 *cmd = scp->cmnd;
4676 	u8 *arr;
4677 	struct sdeb_store_info *sip = devip2sip(devip, true);
4678 	u64 lba;
4679 	u32 dnum;
4680 	u32 lb_size = sdebug_sector_size;
4681 	u8 num;
4682 	int ret;
4683 	int retval = 0;
4684 
4685 	lba = get_unaligned_be64(cmd + 2);
4686 	num = cmd[13];		/* 1 to a maximum of 255 logical blocks */
4687 	if (0 == num)
4688 		return 0;	/* degenerate case, not an error */
4689 	if (sdebug_dif == T10_PI_TYPE2_PROTECTION &&
4690 	    (cmd[1] & 0xe0)) {
4691 		mk_sense_invalid_opcode(scp);
4692 		return check_condition_result;
4693 	}
4694 	if ((sdebug_dif == T10_PI_TYPE1_PROTECTION ||
4695 	     sdebug_dif == T10_PI_TYPE3_PROTECTION) &&
4696 	    (cmd[1] & 0xe0) == 0)
4697 		sdev_printk(KERN_ERR, scp->device, "Unprotected WR "
4698 			    "to DIF device\n");
4699 	ret = check_device_access_params(scp, lba, num, false);
4700 	if (ret)
4701 		return ret;
4702 	dnum = 2 * num;
4703 	arr = kcalloc(lb_size, dnum, GFP_ATOMIC);
4704 	if (NULL == arr) {
4705 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INSUFF_RES_ASC,
4706 				INSUFF_RES_ASCQ);
4707 		return check_condition_result;
4708 	}
4709 
4710 	ret = do_dout_fetch(scp, dnum, arr);
4711 	if (ret == -1) {
4712 		retval = DID_ERROR << 16;
4713 		goto cleanup_free;
4714 	} else if (sdebug_verbose && (ret < (dnum * lb_size)))
4715 		sdev_printk(KERN_INFO, scp->device, "%s: compare_write: cdb "
4716 			    "indicated=%u, IO sent=%d bytes\n", my_name,
4717 			    dnum * lb_size, ret);
4718 
4719 	sdeb_data_write_lock(sip);
4720 	sdeb_meta_write_lock(sip);
4721 	if (!comp_write_worker(sip, lba, num, arr, false)) {
4722 		mk_sense_buffer(scp, MISCOMPARE, MISCOMPARE_VERIFY_ASC, 0);
4723 		retval = check_condition_result;
4724 		goto cleanup_unlock;
4725 	}
4726 
4727 	/* Cover sip->map_storep (which map_region()) sets with data lock */
4728 	if (scsi_debug_lbp())
4729 		map_region(sip, lba, num);
4730 cleanup_unlock:
4731 	sdeb_meta_write_unlock(sip);
4732 	sdeb_data_write_unlock(sip);
4733 cleanup_free:
4734 	kfree(arr);
4735 	return retval;
4736 }
4737 
4738 struct unmap_block_desc {
4739 	__be64	lba;
4740 	__be32	blocks;
4741 	__be32	__reserved;
4742 };
4743 
4744 static int resp_unmap(struct scsi_cmnd *scp, struct sdebug_dev_info *devip)
4745 {
4746 	unsigned char *buf;
4747 	struct unmap_block_desc *desc;
4748 	struct sdeb_store_info *sip = devip2sip(devip, true);
4749 	unsigned int i, payload_len, descriptors;
4750 	int ret;
4751 
4752 	if (!scsi_debug_lbp())
4753 		return 0;	/* fib and say its done */
4754 	payload_len = get_unaligned_be16(scp->cmnd + 7);
4755 	BUG_ON(scsi_bufflen(scp) != payload_len);
4756 
4757 	descriptors = (payload_len - 8) / 16;
4758 	if (descriptors > sdebug_unmap_max_desc) {
4759 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, 7, -1);
4760 		return check_condition_result;
4761 	}
4762 
4763 	buf = kzalloc(scsi_bufflen(scp), GFP_ATOMIC);
4764 	if (!buf) {
4765 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INSUFF_RES_ASC,
4766 				INSUFF_RES_ASCQ);
4767 		return check_condition_result;
4768 	}
4769 
4770 	scsi_sg_copy_to_buffer(scp, buf, scsi_bufflen(scp));
4771 
4772 	BUG_ON(get_unaligned_be16(&buf[0]) != payload_len - 2);
4773 	BUG_ON(get_unaligned_be16(&buf[2]) != descriptors * 16);
4774 
4775 	desc = (void *)&buf[8];
4776 
4777 	sdeb_meta_write_lock(sip);
4778 
4779 	for (i = 0 ; i < descriptors ; i++) {
4780 		unsigned long long lba = get_unaligned_be64(&desc[i].lba);
4781 		unsigned int num = get_unaligned_be32(&desc[i].blocks);
4782 
4783 		ret = check_device_access_params(scp, lba, num, true);
4784 		if (ret)
4785 			goto out;
4786 
4787 		unmap_region(sip, lba, num);
4788 	}
4789 
4790 	ret = 0;
4791 
4792 out:
4793 	sdeb_meta_write_unlock(sip);
4794 	kfree(buf);
4795 
4796 	return ret;
4797 }
4798 
4799 #define SDEBUG_GET_LBA_STATUS_LEN 32
4800 
4801 static int resp_get_lba_status(struct scsi_cmnd *scp,
4802 			       struct sdebug_dev_info *devip)
4803 {
4804 	u8 *cmd = scp->cmnd;
4805 	u64 lba;
4806 	u32 alloc_len, mapped, num;
4807 	int ret;
4808 	u8 arr[SDEBUG_GET_LBA_STATUS_LEN];
4809 
4810 	lba = get_unaligned_be64(cmd + 2);
4811 	alloc_len = get_unaligned_be32(cmd + 10);
4812 
4813 	if (alloc_len < 24)
4814 		return 0;
4815 
4816 	ret = check_device_access_params(scp, lba, 1, false);
4817 	if (ret)
4818 		return ret;
4819 
4820 	if (scsi_debug_lbp()) {
4821 		struct sdeb_store_info *sip = devip2sip(devip, true);
4822 
4823 		mapped = map_state(sip, lba, &num);
4824 	} else {
4825 		mapped = 1;
4826 		/* following just in case virtual_gb changed */
4827 		sdebug_capacity = get_sdebug_capacity();
4828 		if (sdebug_capacity - lba <= 0xffffffff)
4829 			num = sdebug_capacity - lba;
4830 		else
4831 			num = 0xffffffff;
4832 	}
4833 
4834 	memset(arr, 0, SDEBUG_GET_LBA_STATUS_LEN);
4835 	put_unaligned_be32(20, arr);		/* Parameter Data Length */
4836 	put_unaligned_be64(lba, arr + 8);	/* LBA */
4837 	put_unaligned_be32(num, arr + 16);	/* Number of blocks */
4838 	arr[20] = !mapped;		/* prov_stat=0: mapped; 1: dealloc */
4839 
4840 	return fill_from_dev_buffer(scp, arr, SDEBUG_GET_LBA_STATUS_LEN);
4841 }
4842 
4843 static int resp_get_stream_status(struct scsi_cmnd *scp,
4844 				  struct sdebug_dev_info *devip)
4845 {
4846 	u16 starting_stream_id, stream_id;
4847 	const u8 *cmd = scp->cmnd;
4848 	u32 alloc_len, offset;
4849 	u8 arr[256] = {};
4850 	struct scsi_stream_status_header *h = (void *)arr;
4851 
4852 	starting_stream_id = get_unaligned_be16(cmd + 4);
4853 	alloc_len = get_unaligned_be32(cmd + 10);
4854 
4855 	if (alloc_len < 8) {
4856 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, 10, -1);
4857 		return check_condition_result;
4858 	}
4859 
4860 	if (starting_stream_id >= MAXIMUM_NUMBER_OF_STREAMS) {
4861 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, 4, -1);
4862 		return check_condition_result;
4863 	}
4864 
4865 	/*
4866 	 * The GET STREAM STATUS command only reports status information
4867 	 * about open streams. Treat the non-permanent stream as open.
4868 	 */
4869 	put_unaligned_be16(MAXIMUM_NUMBER_OF_STREAMS,
4870 			   &h->number_of_open_streams);
4871 
4872 	for (offset = 8, stream_id = starting_stream_id;
4873 	     offset + 8 <= min_t(u32, alloc_len, sizeof(arr)) &&
4874 		     stream_id < MAXIMUM_NUMBER_OF_STREAMS;
4875 	     offset += 8, stream_id++) {
4876 		struct scsi_stream_status *stream_status = (void *)arr + offset;
4877 
4878 		stream_status->perm = stream_id < PERMANENT_STREAM_COUNT;
4879 		put_unaligned_be16(stream_id,
4880 				   &stream_status->stream_identifier);
4881 		stream_status->rel_lifetime = stream_id + 1;
4882 	}
4883 	put_unaligned_be32(offset - 8, &h->len); /* PARAMETER DATA LENGTH */
4884 
4885 	return fill_from_dev_buffer(scp, arr, min(offset, alloc_len));
4886 }
4887 
4888 static int resp_sync_cache(struct scsi_cmnd *scp,
4889 			   struct sdebug_dev_info *devip)
4890 {
4891 	int res = 0;
4892 	u64 lba;
4893 	u32 num_blocks;
4894 	u8 *cmd = scp->cmnd;
4895 
4896 	if (cmd[0] == SYNCHRONIZE_CACHE) {	/* 10 byte cdb */
4897 		lba = get_unaligned_be32(cmd + 2);
4898 		num_blocks = get_unaligned_be16(cmd + 7);
4899 	} else {				/* SYNCHRONIZE_CACHE(16) */
4900 		lba = get_unaligned_be64(cmd + 2);
4901 		num_blocks = get_unaligned_be32(cmd + 10);
4902 	}
4903 	if (lba + num_blocks > sdebug_capacity) {
4904 		mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0);
4905 		return check_condition_result;
4906 	}
4907 	if (!write_since_sync || (cmd[1] & 0x2))
4908 		res = SDEG_RES_IMMED_MASK;
4909 	else		/* delay if write_since_sync and IMMED clear */
4910 		write_since_sync = false;
4911 	return res;
4912 }
4913 
4914 /*
4915  * Assuming the LBA+num_blocks is not out-of-range, this function will return
4916  * CONDITION MET if the specified blocks will/have fitted in the cache, and
4917  * a GOOD status otherwise. Model a disk with a big cache and yield
4918  * CONDITION MET. Actually tries to bring range in main memory into the
4919  * cache associated with the CPU(s).
4920  */
4921 static int resp_pre_fetch(struct scsi_cmnd *scp,
4922 			  struct sdebug_dev_info *devip)
4923 {
4924 	int res = 0;
4925 	u64 lba;
4926 	u64 block, rest = 0;
4927 	u32 nblks;
4928 	u8 *cmd = scp->cmnd;
4929 	struct sdeb_store_info *sip = devip2sip(devip, true);
4930 	u8 *fsp = sip->storep;
4931 
4932 	if (cmd[0] == PRE_FETCH) {	/* 10 byte cdb */
4933 		lba = get_unaligned_be32(cmd + 2);
4934 		nblks = get_unaligned_be16(cmd + 7);
4935 	} else {			/* PRE-FETCH(16) */
4936 		lba = get_unaligned_be64(cmd + 2);
4937 		nblks = get_unaligned_be32(cmd + 10);
4938 	}
4939 	if (lba + nblks > sdebug_capacity) {
4940 		mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0);
4941 		return check_condition_result;
4942 	}
4943 	if (!fsp)
4944 		goto fini;
4945 	/* PRE-FETCH spec says nothing about LBP or PI so skip them */
4946 	block = do_div(lba, sdebug_store_sectors);
4947 	if (block + nblks > sdebug_store_sectors)
4948 		rest = block + nblks - sdebug_store_sectors;
4949 
4950 	/* Try to bring the PRE-FETCH range into CPU's cache */
4951 	sdeb_data_read_lock(sip);
4952 	prefetch_range(fsp + (sdebug_sector_size * block),
4953 		       (nblks - rest) * sdebug_sector_size);
4954 	if (rest)
4955 		prefetch_range(fsp, rest * sdebug_sector_size);
4956 
4957 	sdeb_data_read_unlock(sip);
4958 fini:
4959 	if (cmd[1] & 0x2)
4960 		res = SDEG_RES_IMMED_MASK;
4961 	return res | condition_met_result;
4962 }
4963 
4964 #define RL_BUCKET_ELEMS 8
4965 
4966 /* Even though each pseudo target has a REPORT LUNS "well known logical unit"
4967  * (W-LUN), the normal Linux scanning logic does not associate it with a
4968  * device (e.g. /dev/sg7). The following magic will make that association:
4969  *   "cd /sys/class/scsi_host/host<n> ; echo '- - 49409' > scan"
4970  * where <n> is a host number. If there are multiple targets in a host then
4971  * the above will associate a W-LUN to each target. To only get a W-LUN
4972  * for target 2, then use "echo '- 2 49409' > scan" .
4973  */
4974 static int resp_report_luns(struct scsi_cmnd *scp,
4975 			    struct sdebug_dev_info *devip)
4976 {
4977 	unsigned char *cmd = scp->cmnd;
4978 	unsigned int alloc_len;
4979 	unsigned char select_report;
4980 	u64 lun;
4981 	struct scsi_lun *lun_p;
4982 	u8 arr[RL_BUCKET_ELEMS * sizeof(struct scsi_lun)];
4983 	unsigned int lun_cnt;	/* normal LUN count (max: 256) */
4984 	unsigned int wlun_cnt;	/* report luns W-LUN count */
4985 	unsigned int tlun_cnt;	/* total LUN count */
4986 	unsigned int rlen;	/* response length (in bytes) */
4987 	int k, j, n, res;
4988 	unsigned int off_rsp = 0;
4989 	const int sz_lun = sizeof(struct scsi_lun);
4990 
4991 	clear_luns_changed_on_target(devip);
4992 
4993 	select_report = cmd[2];
4994 	alloc_len = get_unaligned_be32(cmd + 6);
4995 
4996 	if (alloc_len < 4) {
4997 		pr_err("alloc len too small %d\n", alloc_len);
4998 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, 6, -1);
4999 		return check_condition_result;
5000 	}
5001 
5002 	switch (select_report) {
5003 	case 0:		/* all LUNs apart from W-LUNs */
5004 		lun_cnt = sdebug_max_luns;
5005 		wlun_cnt = 0;
5006 		break;
5007 	case 1:		/* only W-LUNs */
5008 		lun_cnt = 0;
5009 		wlun_cnt = 1;
5010 		break;
5011 	case 2:		/* all LUNs */
5012 		lun_cnt = sdebug_max_luns;
5013 		wlun_cnt = 1;
5014 		break;
5015 	case 0x10:	/* only administrative LUs */
5016 	case 0x11:	/* see SPC-5 */
5017 	case 0x12:	/* only subsiduary LUs owned by referenced LU */
5018 	default:
5019 		pr_debug("select report invalid %d\n", select_report);
5020 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, 2, -1);
5021 		return check_condition_result;
5022 	}
5023 
5024 	if (sdebug_no_lun_0 && (lun_cnt > 0))
5025 		--lun_cnt;
5026 
5027 	tlun_cnt = lun_cnt + wlun_cnt;
5028 	rlen = tlun_cnt * sz_lun;	/* excluding 8 byte header */
5029 	scsi_set_resid(scp, scsi_bufflen(scp));
5030 	pr_debug("select_report %d luns = %d wluns = %d no_lun0 %d\n",
5031 		 select_report, lun_cnt, wlun_cnt, sdebug_no_lun_0);
5032 
5033 	/* loops rely on sizeof response header same as sizeof lun (both 8) */
5034 	lun = sdebug_no_lun_0 ? 1 : 0;
5035 	for (k = 0, j = 0, res = 0; true; ++k, j = 0) {
5036 		memset(arr, 0, sizeof(arr));
5037 		lun_p = (struct scsi_lun *)&arr[0];
5038 		if (k == 0) {
5039 			put_unaligned_be32(rlen, &arr[0]);
5040 			++lun_p;
5041 			j = 1;
5042 		}
5043 		for ( ; j < RL_BUCKET_ELEMS; ++j, ++lun_p) {
5044 			if ((k * RL_BUCKET_ELEMS) + j > lun_cnt)
5045 				break;
5046 			int_to_scsilun(lun++, lun_p);
5047 			if (lun > 1 && sdebug_lun_am == SAM_LUN_AM_FLAT)
5048 				lun_p->scsi_lun[0] |= 0x40;
5049 		}
5050 		if (j < RL_BUCKET_ELEMS)
5051 			break;
5052 		n = j * sz_lun;
5053 		res = p_fill_from_dev_buffer(scp, arr, n, off_rsp);
5054 		if (res)
5055 			return res;
5056 		off_rsp += n;
5057 	}
5058 	if (wlun_cnt) {
5059 		int_to_scsilun(SCSI_W_LUN_REPORT_LUNS, lun_p);
5060 		++j;
5061 	}
5062 	if (j > 0)
5063 		res = p_fill_from_dev_buffer(scp, arr, j * sz_lun, off_rsp);
5064 	return res;
5065 }
5066 
5067 static int resp_verify(struct scsi_cmnd *scp, struct sdebug_dev_info *devip)
5068 {
5069 	bool is_bytchk3 = false;
5070 	u8 bytchk;
5071 	int ret, j;
5072 	u32 vnum, a_num, off;
5073 	const u32 lb_size = sdebug_sector_size;
5074 	u64 lba;
5075 	u8 *arr;
5076 	u8 *cmd = scp->cmnd;
5077 	struct sdeb_store_info *sip = devip2sip(devip, true);
5078 
5079 	bytchk = (cmd[1] >> 1) & 0x3;
5080 	if (bytchk == 0) {
5081 		return 0;	/* always claim internal verify okay */
5082 	} else if (bytchk == 2) {
5083 		mk_sense_invalid_fld(scp, SDEB_IN_CDB, 2, 2);
5084 		return check_condition_result;
5085 	} else if (bytchk == 3) {
5086 		is_bytchk3 = true;	/* 1 block sent, compared repeatedly */
5087 	}
5088 	switch (cmd[0]) {
5089 	case VERIFY_16:
5090 		lba = get_unaligned_be64(cmd + 2);
5091 		vnum = get_unaligned_be32(cmd + 10);
5092 		break;
5093 	case VERIFY:		/* is VERIFY(10) */
5094 		lba = get_unaligned_be32(cmd + 2);
5095 		vnum = get_unaligned_be16(cmd + 7);
5096 		break;
5097 	default:
5098 		mk_sense_invalid_opcode(scp);
5099 		return check_condition_result;
5100 	}
5101 	if (vnum == 0)
5102 		return 0;	/* not an error */
5103 	a_num = is_bytchk3 ? 1 : vnum;
5104 	/* Treat following check like one for read (i.e. no write) access */
5105 	ret = check_device_access_params(scp, lba, a_num, false);
5106 	if (ret)
5107 		return ret;
5108 
5109 	arr = kcalloc(lb_size, vnum, GFP_ATOMIC | __GFP_NOWARN);
5110 	if (!arr) {
5111 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INSUFF_RES_ASC,
5112 				INSUFF_RES_ASCQ);
5113 		return check_condition_result;
5114 	}
5115 	/* Not changing store, so only need read access */
5116 	sdeb_data_read_lock(sip);
5117 
5118 	ret = do_dout_fetch(scp, a_num, arr);
5119 	if (ret == -1) {
5120 		ret = DID_ERROR << 16;
5121 		goto cleanup;
5122 	} else if (sdebug_verbose && (ret < (a_num * lb_size))) {
5123 		sdev_printk(KERN_INFO, scp->device,
5124 			    "%s: %s: cdb indicated=%u, IO sent=%d bytes\n",
5125 			    my_name, __func__, a_num * lb_size, ret);
5126 	}
5127 	if (is_bytchk3) {
5128 		for (j = 1, off = lb_size; j < vnum; ++j, off += lb_size)
5129 			memcpy(arr + off, arr, lb_size);
5130 	}
5131 	ret = 0;
5132 	if (!comp_write_worker(sip, lba, vnum, arr, true)) {
5133 		mk_sense_buffer(scp, MISCOMPARE, MISCOMPARE_VERIFY_ASC, 0);
5134 		ret = check_condition_result;
5135 		goto cleanup;
5136 	}
5137 cleanup:
5138 	sdeb_data_read_unlock(sip);
5139 	kfree(arr);
5140 	return ret;
5141 }
5142 
5143 #define RZONES_DESC_HD 64
5144 
5145 /* Report zones depending on start LBA and reporting options */
5146 static int resp_report_zones(struct scsi_cmnd *scp,
5147 			     struct sdebug_dev_info *devip)
5148 {
5149 	unsigned int rep_max_zones, nrz = 0;
5150 	int ret = 0;
5151 	u32 alloc_len, rep_opts, rep_len;
5152 	bool partial;
5153 	u64 lba, zs_lba;
5154 	u8 *arr = NULL, *desc;
5155 	u8 *cmd = scp->cmnd;
5156 	struct sdeb_zone_state *zsp = NULL;
5157 	struct sdeb_store_info *sip = devip2sip(devip, false);
5158 
5159 	if (!sdebug_dev_is_zoned(devip)) {
5160 		mk_sense_invalid_opcode(scp);
5161 		return check_condition_result;
5162 	}
5163 	zs_lba = get_unaligned_be64(cmd + 2);
5164 	alloc_len = get_unaligned_be32(cmd + 10);
5165 	if (alloc_len == 0)
5166 		return 0;	/* not an error */
5167 	rep_opts = cmd[14] & 0x3f;
5168 	partial = cmd[14] & 0x80;
5169 
5170 	if (zs_lba >= sdebug_capacity) {
5171 		mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0);
5172 		return check_condition_result;
5173 	}
5174 
5175 	rep_max_zones = (alloc_len - 64) >> ilog2(RZONES_DESC_HD);
5176 
5177 	arr = kzalloc(alloc_len, GFP_ATOMIC | __GFP_NOWARN);
5178 	if (!arr) {
5179 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INSUFF_RES_ASC,
5180 				INSUFF_RES_ASCQ);
5181 		return check_condition_result;
5182 	}
5183 
5184 	sdeb_meta_read_lock(sip);
5185 
5186 	desc = arr + 64;
5187 	for (lba = zs_lba; lba < sdebug_capacity;
5188 	     lba = zsp->z_start + zsp->z_size) {
5189 		if (WARN_ONCE(zbc_zone(devip, lba) == zsp, "lba = %llu\n", lba))
5190 			break;
5191 		zsp = zbc_zone(devip, lba);
5192 		switch (rep_opts) {
5193 		case 0x00:
5194 			/* All zones */
5195 			break;
5196 		case 0x01:
5197 			/* Empty zones */
5198 			if (zsp->z_cond != ZC1_EMPTY)
5199 				continue;
5200 			break;
5201 		case 0x02:
5202 			/* Implicit open zones */
5203 			if (zsp->z_cond != ZC2_IMPLICIT_OPEN)
5204 				continue;
5205 			break;
5206 		case 0x03:
5207 			/* Explicit open zones */
5208 			if (zsp->z_cond != ZC3_EXPLICIT_OPEN)
5209 				continue;
5210 			break;
5211 		case 0x04:
5212 			/* Closed zones */
5213 			if (zsp->z_cond != ZC4_CLOSED)
5214 				continue;
5215 			break;
5216 		case 0x05:
5217 			/* Full zones */
5218 			if (zsp->z_cond != ZC5_FULL)
5219 				continue;
5220 			break;
5221 		case 0x06:
5222 		case 0x07:
5223 		case 0x10:
5224 			/*
5225 			 * Read-only, offline, reset WP recommended are
5226 			 * not emulated: no zones to report;
5227 			 */
5228 			continue;
5229 		case 0x11:
5230 			/* non-seq-resource set */
5231 			if (!zsp->z_non_seq_resource)
5232 				continue;
5233 			break;
5234 		case 0x3e:
5235 			/* All zones except gap zones. */
5236 			if (zbc_zone_is_gap(zsp))
5237 				continue;
5238 			break;
5239 		case 0x3f:
5240 			/* Not write pointer (conventional) zones */
5241 			if (zbc_zone_is_seq(zsp))
5242 				continue;
5243 			break;
5244 		default:
5245 			mk_sense_buffer(scp, ILLEGAL_REQUEST,
5246 					INVALID_FIELD_IN_CDB, 0);
5247 			ret = check_condition_result;
5248 			goto fini;
5249 		}
5250 
5251 		if (nrz < rep_max_zones) {
5252 			/* Fill zone descriptor */
5253 			desc[0] = zsp->z_type;
5254 			desc[1] = zsp->z_cond << 4;
5255 			if (zsp->z_non_seq_resource)
5256 				desc[1] |= 1 << 1;
5257 			put_unaligned_be64((u64)zsp->z_size, desc + 8);
5258 			put_unaligned_be64((u64)zsp->z_start, desc + 16);
5259 			put_unaligned_be64((u64)zsp->z_wp, desc + 24);
5260 			desc += 64;
5261 		}
5262 
5263 		if (partial && nrz >= rep_max_zones)
5264 			break;
5265 
5266 		nrz++;
5267 	}
5268 
5269 	/* Report header */
5270 	/* Zone list length. */
5271 	put_unaligned_be32(nrz * RZONES_DESC_HD, arr + 0);
5272 	/* Maximum LBA */
5273 	put_unaligned_be64(sdebug_capacity - 1, arr + 8);
5274 	/* Zone starting LBA granularity. */
5275 	if (devip->zcap < devip->zsize)
5276 		put_unaligned_be64(devip->zsize, arr + 16);
5277 
5278 	rep_len = (unsigned long)desc - (unsigned long)arr;
5279 	ret = fill_from_dev_buffer(scp, arr, min_t(u32, alloc_len, rep_len));
5280 
5281 fini:
5282 	sdeb_meta_read_unlock(sip);
5283 	kfree(arr);
5284 	return ret;
5285 }
5286 
5287 static int resp_atomic_write(struct scsi_cmnd *scp,
5288 			     struct sdebug_dev_info *devip)
5289 {
5290 	struct sdeb_store_info *sip;
5291 	u8 *cmd = scp->cmnd;
5292 	u16 boundary, len;
5293 	u64 lba, lba_tmp;
5294 	int ret;
5295 
5296 	if (!scsi_debug_atomic_write()) {
5297 		mk_sense_invalid_opcode(scp);
5298 		return check_condition_result;
5299 	}
5300 
5301 	sip = devip2sip(devip, true);
5302 
5303 	lba = get_unaligned_be64(cmd + 2);
5304 	boundary = get_unaligned_be16(cmd + 10);
5305 	len = get_unaligned_be16(cmd + 12);
5306 
5307 	lba_tmp = lba;
5308 	if (sdebug_atomic_wr_align &&
5309 	    do_div(lba_tmp, sdebug_atomic_wr_align)) {
5310 		/* Does not meet alignment requirement */
5311 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0);
5312 		return check_condition_result;
5313 	}
5314 
5315 	if (sdebug_atomic_wr_gran && len % sdebug_atomic_wr_gran) {
5316 		/* Does not meet alignment requirement */
5317 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0);
5318 		return check_condition_result;
5319 	}
5320 
5321 	if (boundary > 0) {
5322 		if (boundary > sdebug_atomic_wr_max_bndry) {
5323 			mk_sense_invalid_fld(scp, SDEB_IN_CDB, 12, -1);
5324 			return check_condition_result;
5325 		}
5326 
5327 		if (len > sdebug_atomic_wr_max_length_bndry) {
5328 			mk_sense_invalid_fld(scp, SDEB_IN_CDB, 12, -1);
5329 			return check_condition_result;
5330 		}
5331 	} else {
5332 		if (len > sdebug_atomic_wr_max_length) {
5333 			mk_sense_invalid_fld(scp, SDEB_IN_CDB, 12, -1);
5334 			return check_condition_result;
5335 		}
5336 	}
5337 
5338 	ret = do_device_access(sip, scp, 0, lba, len, 0, true, true);
5339 	if (unlikely(ret == -1))
5340 		return DID_ERROR << 16;
5341 	if (unlikely(ret != len * sdebug_sector_size))
5342 		return DID_ERROR << 16;
5343 	return 0;
5344 }
5345 
5346 /* Logic transplanted from tcmu-runner, file_zbc.c */
5347 static void zbc_open_all(struct sdebug_dev_info *devip)
5348 {
5349 	struct sdeb_zone_state *zsp = &devip->zstate[0];
5350 	unsigned int i;
5351 
5352 	for (i = 0; i < devip->nr_zones; i++, zsp++) {
5353 		if (zsp->z_cond == ZC4_CLOSED)
5354 			zbc_open_zone(devip, &devip->zstate[i], true);
5355 	}
5356 }
5357 
5358 static int resp_open_zone(struct scsi_cmnd *scp, struct sdebug_dev_info *devip)
5359 {
5360 	int res = 0;
5361 	u64 z_id;
5362 	enum sdebug_z_cond zc;
5363 	u8 *cmd = scp->cmnd;
5364 	struct sdeb_zone_state *zsp;
5365 	bool all = cmd[14] & 0x01;
5366 	struct sdeb_store_info *sip = devip2sip(devip, false);
5367 
5368 	if (!sdebug_dev_is_zoned(devip)) {
5369 		mk_sense_invalid_opcode(scp);
5370 		return check_condition_result;
5371 	}
5372 	sdeb_meta_write_lock(sip);
5373 
5374 	if (all) {
5375 		/* Check if all closed zones can be open */
5376 		if (devip->max_open &&
5377 		    devip->nr_exp_open + devip->nr_closed > devip->max_open) {
5378 			mk_sense_buffer(scp, DATA_PROTECT, INSUFF_RES_ASC,
5379 					INSUFF_ZONE_ASCQ);
5380 			res = check_condition_result;
5381 			goto fini;
5382 		}
5383 		/* Open all closed zones */
5384 		zbc_open_all(devip);
5385 		goto fini;
5386 	}
5387 
5388 	/* Open the specified zone */
5389 	z_id = get_unaligned_be64(cmd + 2);
5390 	if (z_id >= sdebug_capacity) {
5391 		mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0);
5392 		res = check_condition_result;
5393 		goto fini;
5394 	}
5395 
5396 	zsp = zbc_zone(devip, z_id);
5397 	if (z_id != zsp->z_start) {
5398 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0);
5399 		res = check_condition_result;
5400 		goto fini;
5401 	}
5402 	if (zbc_zone_is_conv(zsp)) {
5403 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0);
5404 		res = check_condition_result;
5405 		goto fini;
5406 	}
5407 
5408 	zc = zsp->z_cond;
5409 	if (zc == ZC3_EXPLICIT_OPEN || zc == ZC5_FULL)
5410 		goto fini;
5411 
5412 	if (devip->max_open && devip->nr_exp_open >= devip->max_open) {
5413 		mk_sense_buffer(scp, DATA_PROTECT, INSUFF_RES_ASC,
5414 				INSUFF_ZONE_ASCQ);
5415 		res = check_condition_result;
5416 		goto fini;
5417 	}
5418 
5419 	zbc_open_zone(devip, zsp, true);
5420 fini:
5421 	sdeb_meta_write_unlock(sip);
5422 	return res;
5423 }
5424 
5425 static void zbc_close_all(struct sdebug_dev_info *devip)
5426 {
5427 	unsigned int i;
5428 
5429 	for (i = 0; i < devip->nr_zones; i++)
5430 		zbc_close_zone(devip, &devip->zstate[i]);
5431 }
5432 
5433 static int resp_close_zone(struct scsi_cmnd *scp,
5434 			   struct sdebug_dev_info *devip)
5435 {
5436 	int res = 0;
5437 	u64 z_id;
5438 	u8 *cmd = scp->cmnd;
5439 	struct sdeb_zone_state *zsp;
5440 	bool all = cmd[14] & 0x01;
5441 	struct sdeb_store_info *sip = devip2sip(devip, false);
5442 
5443 	if (!sdebug_dev_is_zoned(devip)) {
5444 		mk_sense_invalid_opcode(scp);
5445 		return check_condition_result;
5446 	}
5447 
5448 	sdeb_meta_write_lock(sip);
5449 
5450 	if (all) {
5451 		zbc_close_all(devip);
5452 		goto fini;
5453 	}
5454 
5455 	/* Close specified zone */
5456 	z_id = get_unaligned_be64(cmd + 2);
5457 	if (z_id >= sdebug_capacity) {
5458 		mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0);
5459 		res = check_condition_result;
5460 		goto fini;
5461 	}
5462 
5463 	zsp = zbc_zone(devip, z_id);
5464 	if (z_id != zsp->z_start) {
5465 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0);
5466 		res = check_condition_result;
5467 		goto fini;
5468 	}
5469 	if (zbc_zone_is_conv(zsp)) {
5470 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0);
5471 		res = check_condition_result;
5472 		goto fini;
5473 	}
5474 
5475 	zbc_close_zone(devip, zsp);
5476 fini:
5477 	sdeb_meta_write_unlock(sip);
5478 	return res;
5479 }
5480 
5481 static void zbc_finish_zone(struct sdebug_dev_info *devip,
5482 			    struct sdeb_zone_state *zsp, bool empty)
5483 {
5484 	enum sdebug_z_cond zc = zsp->z_cond;
5485 
5486 	if (zc == ZC4_CLOSED || zc == ZC2_IMPLICIT_OPEN ||
5487 	    zc == ZC3_EXPLICIT_OPEN || (empty && zc == ZC1_EMPTY)) {
5488 		if (zc == ZC2_IMPLICIT_OPEN || zc == ZC3_EXPLICIT_OPEN)
5489 			zbc_close_zone(devip, zsp);
5490 		if (zsp->z_cond == ZC4_CLOSED)
5491 			devip->nr_closed--;
5492 		zsp->z_wp = zsp->z_start + zsp->z_size;
5493 		zsp->z_cond = ZC5_FULL;
5494 	}
5495 }
5496 
5497 static void zbc_finish_all(struct sdebug_dev_info *devip)
5498 {
5499 	unsigned int i;
5500 
5501 	for (i = 0; i < devip->nr_zones; i++)
5502 		zbc_finish_zone(devip, &devip->zstate[i], false);
5503 }
5504 
5505 static int resp_finish_zone(struct scsi_cmnd *scp,
5506 			    struct sdebug_dev_info *devip)
5507 {
5508 	struct sdeb_zone_state *zsp;
5509 	int res = 0;
5510 	u64 z_id;
5511 	u8 *cmd = scp->cmnd;
5512 	bool all = cmd[14] & 0x01;
5513 	struct sdeb_store_info *sip = devip2sip(devip, false);
5514 
5515 	if (!sdebug_dev_is_zoned(devip)) {
5516 		mk_sense_invalid_opcode(scp);
5517 		return check_condition_result;
5518 	}
5519 
5520 	sdeb_meta_write_lock(sip);
5521 
5522 	if (all) {
5523 		zbc_finish_all(devip);
5524 		goto fini;
5525 	}
5526 
5527 	/* Finish the specified zone */
5528 	z_id = get_unaligned_be64(cmd + 2);
5529 	if (z_id >= sdebug_capacity) {
5530 		mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0);
5531 		res = check_condition_result;
5532 		goto fini;
5533 	}
5534 
5535 	zsp = zbc_zone(devip, z_id);
5536 	if (z_id != zsp->z_start) {
5537 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0);
5538 		res = check_condition_result;
5539 		goto fini;
5540 	}
5541 	if (zbc_zone_is_conv(zsp)) {
5542 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0);
5543 		res = check_condition_result;
5544 		goto fini;
5545 	}
5546 
5547 	zbc_finish_zone(devip, zsp, true);
5548 fini:
5549 	sdeb_meta_write_unlock(sip);
5550 	return res;
5551 }
5552 
5553 static void zbc_rwp_zone(struct sdebug_dev_info *devip,
5554 			 struct sdeb_zone_state *zsp)
5555 {
5556 	enum sdebug_z_cond zc;
5557 	struct sdeb_store_info *sip = devip2sip(devip, false);
5558 
5559 	if (!zbc_zone_is_seq(zsp))
5560 		return;
5561 
5562 	zc = zsp->z_cond;
5563 	if (zc == ZC2_IMPLICIT_OPEN || zc == ZC3_EXPLICIT_OPEN)
5564 		zbc_close_zone(devip, zsp);
5565 
5566 	if (zsp->z_cond == ZC4_CLOSED)
5567 		devip->nr_closed--;
5568 
5569 	if (zsp->z_wp > zsp->z_start)
5570 		memset(sip->storep + zsp->z_start * sdebug_sector_size, 0,
5571 		       (zsp->z_wp - zsp->z_start) * sdebug_sector_size);
5572 
5573 	zsp->z_non_seq_resource = false;
5574 	zsp->z_wp = zsp->z_start;
5575 	zsp->z_cond = ZC1_EMPTY;
5576 }
5577 
5578 static void zbc_rwp_all(struct sdebug_dev_info *devip)
5579 {
5580 	unsigned int i;
5581 
5582 	for (i = 0; i < devip->nr_zones; i++)
5583 		zbc_rwp_zone(devip, &devip->zstate[i]);
5584 }
5585 
5586 static int resp_rwp_zone(struct scsi_cmnd *scp, struct sdebug_dev_info *devip)
5587 {
5588 	struct sdeb_zone_state *zsp;
5589 	int res = 0;
5590 	u64 z_id;
5591 	u8 *cmd = scp->cmnd;
5592 	bool all = cmd[14] & 0x01;
5593 	struct sdeb_store_info *sip = devip2sip(devip, false);
5594 
5595 	if (!sdebug_dev_is_zoned(devip)) {
5596 		mk_sense_invalid_opcode(scp);
5597 		return check_condition_result;
5598 	}
5599 
5600 	sdeb_meta_write_lock(sip);
5601 
5602 	if (all) {
5603 		zbc_rwp_all(devip);
5604 		goto fini;
5605 	}
5606 
5607 	z_id = get_unaligned_be64(cmd + 2);
5608 	if (z_id >= sdebug_capacity) {
5609 		mk_sense_buffer(scp, ILLEGAL_REQUEST, LBA_OUT_OF_RANGE, 0);
5610 		res = check_condition_result;
5611 		goto fini;
5612 	}
5613 
5614 	zsp = zbc_zone(devip, z_id);
5615 	if (z_id != zsp->z_start) {
5616 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0);
5617 		res = check_condition_result;
5618 		goto fini;
5619 	}
5620 	if (zbc_zone_is_conv(zsp)) {
5621 		mk_sense_buffer(scp, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB, 0);
5622 		res = check_condition_result;
5623 		goto fini;
5624 	}
5625 
5626 	zbc_rwp_zone(devip, zsp);
5627 fini:
5628 	sdeb_meta_write_unlock(sip);
5629 	return res;
5630 }
5631 
5632 static u32 get_tag(struct scsi_cmnd *cmnd)
5633 {
5634 	return blk_mq_unique_tag(scsi_cmd_to_rq(cmnd));
5635 }
5636 
5637 /* Queued (deferred) command completions converge here. */
5638 static void sdebug_q_cmd_complete(struct sdebug_defer *sd_dp)
5639 {
5640 	struct sdebug_queued_cmd *sqcp = container_of(sd_dp, struct sdebug_queued_cmd, sd_dp);
5641 	unsigned long flags;
5642 	struct scsi_cmnd *scp = sqcp->scmd;
5643 	struct sdebug_scsi_cmd *sdsc;
5644 	bool aborted;
5645 
5646 	if (sdebug_statistics) {
5647 		atomic_inc(&sdebug_completions);
5648 		if (raw_smp_processor_id() != sd_dp->issuing_cpu)
5649 			atomic_inc(&sdebug_miss_cpus);
5650 	}
5651 
5652 	if (!scp) {
5653 		pr_err("scmd=NULL\n");
5654 		goto out;
5655 	}
5656 
5657 	sdsc = scsi_cmd_priv(scp);
5658 	spin_lock_irqsave(&sdsc->lock, flags);
5659 	aborted = sd_dp->aborted;
5660 	if (unlikely(aborted))
5661 		sd_dp->aborted = false;
5662 	ASSIGN_QUEUED_CMD(scp, NULL);
5663 
5664 	spin_unlock_irqrestore(&sdsc->lock, flags);
5665 
5666 	if (aborted) {
5667 		pr_info("bypassing scsi_done() due to aborted cmd, kicking-off EH\n");
5668 		blk_abort_request(scsi_cmd_to_rq(scp));
5669 		goto out;
5670 	}
5671 
5672 	scsi_done(scp); /* callback to mid level */
5673 out:
5674 	sdebug_free_queued_cmd(sqcp);
5675 }
5676 
5677 /* When high resolution timer goes off this function is called. */
5678 static enum hrtimer_restart sdebug_q_cmd_hrt_complete(struct hrtimer *timer)
5679 {
5680 	struct sdebug_defer *sd_dp = container_of(timer, struct sdebug_defer,
5681 						  hrt);
5682 	sdebug_q_cmd_complete(sd_dp);
5683 	return HRTIMER_NORESTART;
5684 }
5685 
5686 /* When work queue schedules work, it calls this function. */
5687 static void sdebug_q_cmd_wq_complete(struct work_struct *work)
5688 {
5689 	struct sdebug_defer *sd_dp = container_of(work, struct sdebug_defer,
5690 						  ew.work);
5691 	sdebug_q_cmd_complete(sd_dp);
5692 }
5693 
5694 static bool got_shared_uuid;
5695 static uuid_t shared_uuid;
5696 
5697 static int sdebug_device_create_zones(struct sdebug_dev_info *devip)
5698 {
5699 	struct sdeb_zone_state *zsp;
5700 	sector_t capacity = get_sdebug_capacity();
5701 	sector_t conv_capacity;
5702 	sector_t zstart = 0;
5703 	unsigned int i;
5704 
5705 	/*
5706 	 * Set the zone size: if sdeb_zbc_zone_size_mb is not set, figure out
5707 	 * a zone size allowing for at least 4 zones on the device. Otherwise,
5708 	 * use the specified zone size checking that at least 2 zones can be
5709 	 * created for the device.
5710 	 */
5711 	if (!sdeb_zbc_zone_size_mb) {
5712 		devip->zsize = (DEF_ZBC_ZONE_SIZE_MB * SZ_1M)
5713 			>> ilog2(sdebug_sector_size);
5714 		while (capacity < devip->zsize << 2 && devip->zsize >= 2)
5715 			devip->zsize >>= 1;
5716 		if (devip->zsize < 2) {
5717 			pr_err("Device capacity too small\n");
5718 			return -EINVAL;
5719 		}
5720 	} else {
5721 		if (!is_power_of_2(sdeb_zbc_zone_size_mb)) {
5722 			pr_err("Zone size is not a power of 2\n");
5723 			return -EINVAL;
5724 		}
5725 		devip->zsize = (sdeb_zbc_zone_size_mb * SZ_1M)
5726 			>> ilog2(sdebug_sector_size);
5727 		if (devip->zsize >= capacity) {
5728 			pr_err("Zone size too large for device capacity\n");
5729 			return -EINVAL;
5730 		}
5731 	}
5732 
5733 	devip->zsize_shift = ilog2(devip->zsize);
5734 	devip->nr_zones = (capacity + devip->zsize - 1) >> devip->zsize_shift;
5735 
5736 	if (sdeb_zbc_zone_cap_mb == 0) {
5737 		devip->zcap = devip->zsize;
5738 	} else {
5739 		devip->zcap = (sdeb_zbc_zone_cap_mb * SZ_1M) >>
5740 			      ilog2(sdebug_sector_size);
5741 		if (devip->zcap > devip->zsize) {
5742 			pr_err("Zone capacity too large\n");
5743 			return -EINVAL;
5744 		}
5745 	}
5746 
5747 	conv_capacity = (sector_t)sdeb_zbc_nr_conv << devip->zsize_shift;
5748 	if (conv_capacity >= capacity) {
5749 		pr_err("Number of conventional zones too large\n");
5750 		return -EINVAL;
5751 	}
5752 	devip->nr_conv_zones = sdeb_zbc_nr_conv;
5753 	devip->nr_seq_zones = ALIGN(capacity - conv_capacity, devip->zsize) >>
5754 			      devip->zsize_shift;
5755 	devip->nr_zones = devip->nr_conv_zones + devip->nr_seq_zones;
5756 
5757 	/* Add gap zones if zone capacity is smaller than the zone size */
5758 	if (devip->zcap < devip->zsize)
5759 		devip->nr_zones += devip->nr_seq_zones;
5760 
5761 	if (devip->zoned) {
5762 		/* zbc_max_open_zones can be 0, meaning "not reported" */
5763 		if (sdeb_zbc_max_open >= devip->nr_zones - 1)
5764 			devip->max_open = (devip->nr_zones - 1) / 2;
5765 		else
5766 			devip->max_open = sdeb_zbc_max_open;
5767 	}
5768 
5769 	devip->zstate = kcalloc(devip->nr_zones,
5770 				sizeof(struct sdeb_zone_state), GFP_KERNEL);
5771 	if (!devip->zstate)
5772 		return -ENOMEM;
5773 
5774 	for (i = 0; i < devip->nr_zones; i++) {
5775 		zsp = &devip->zstate[i];
5776 
5777 		zsp->z_start = zstart;
5778 
5779 		if (i < devip->nr_conv_zones) {
5780 			zsp->z_type = ZBC_ZTYPE_CNV;
5781 			zsp->z_cond = ZBC_NOT_WRITE_POINTER;
5782 			zsp->z_wp = (sector_t)-1;
5783 			zsp->z_size =
5784 				min_t(u64, devip->zsize, capacity - zstart);
5785 		} else if ((zstart & (devip->zsize - 1)) == 0) {
5786 			if (devip->zoned)
5787 				zsp->z_type = ZBC_ZTYPE_SWR;
5788 			else
5789 				zsp->z_type = ZBC_ZTYPE_SWP;
5790 			zsp->z_cond = ZC1_EMPTY;
5791 			zsp->z_wp = zsp->z_start;
5792 			zsp->z_size =
5793 				min_t(u64, devip->zcap, capacity - zstart);
5794 		} else {
5795 			zsp->z_type = ZBC_ZTYPE_GAP;
5796 			zsp->z_cond = ZBC_NOT_WRITE_POINTER;
5797 			zsp->z_wp = (sector_t)-1;
5798 			zsp->z_size = min_t(u64, devip->zsize - devip->zcap,
5799 					    capacity - zstart);
5800 		}
5801 
5802 		WARN_ON_ONCE((int)zsp->z_size <= 0);
5803 		zstart += zsp->z_size;
5804 	}
5805 
5806 	return 0;
5807 }
5808 
5809 static struct sdebug_dev_info *sdebug_device_create(
5810 			struct sdebug_host_info *sdbg_host, gfp_t flags)
5811 {
5812 	struct sdebug_dev_info *devip;
5813 
5814 	devip = kzalloc(sizeof(*devip), flags);
5815 	if (devip) {
5816 		if (sdebug_uuid_ctl == 1)
5817 			uuid_gen(&devip->lu_name);
5818 		else if (sdebug_uuid_ctl == 2) {
5819 			if (got_shared_uuid)
5820 				devip->lu_name = shared_uuid;
5821 			else {
5822 				uuid_gen(&shared_uuid);
5823 				got_shared_uuid = true;
5824 				devip->lu_name = shared_uuid;
5825 			}
5826 		}
5827 		devip->sdbg_host = sdbg_host;
5828 		if (sdeb_zbc_in_use) {
5829 			devip->zoned = sdeb_zbc_model == BLK_ZONED_HM;
5830 			if (sdebug_device_create_zones(devip)) {
5831 				kfree(devip);
5832 				return NULL;
5833 			}
5834 		} else {
5835 			devip->zoned = false;
5836 		}
5837 		devip->create_ts = ktime_get_boottime();
5838 		atomic_set(&devip->stopped, (sdeb_tur_ms_to_ready > 0 ? 2 : 0));
5839 		spin_lock_init(&devip->list_lock);
5840 		INIT_LIST_HEAD(&devip->inject_err_list);
5841 		list_add_tail(&devip->dev_list, &sdbg_host->dev_info_list);
5842 	}
5843 	return devip;
5844 }
5845 
5846 static struct sdebug_dev_info *find_build_dev_info(struct scsi_device *sdev)
5847 {
5848 	struct sdebug_host_info *sdbg_host;
5849 	struct sdebug_dev_info *open_devip = NULL;
5850 	struct sdebug_dev_info *devip;
5851 
5852 	sdbg_host = shost_to_sdebug_host(sdev->host);
5853 
5854 	list_for_each_entry(devip, &sdbg_host->dev_info_list, dev_list) {
5855 		if ((devip->used) && (devip->channel == sdev->channel) &&
5856 		    (devip->target == sdev->id) &&
5857 		    (devip->lun == sdev->lun))
5858 			return devip;
5859 		else {
5860 			if ((!devip->used) && (!open_devip))
5861 				open_devip = devip;
5862 		}
5863 	}
5864 	if (!open_devip) { /* try and make a new one */
5865 		open_devip = sdebug_device_create(sdbg_host, GFP_ATOMIC);
5866 		if (!open_devip) {
5867 			pr_err("out of memory at line %d\n", __LINE__);
5868 			return NULL;
5869 		}
5870 	}
5871 
5872 	open_devip->channel = sdev->channel;
5873 	open_devip->target = sdev->id;
5874 	open_devip->lun = sdev->lun;
5875 	open_devip->sdbg_host = sdbg_host;
5876 	set_bit(SDEBUG_UA_POOCCUR, open_devip->uas_bm);
5877 	open_devip->used = true;
5878 	return open_devip;
5879 }
5880 
5881 static int scsi_debug_slave_alloc(struct scsi_device *sdp)
5882 {
5883 	if (sdebug_verbose)
5884 		pr_info("slave_alloc <%u %u %u %llu>\n",
5885 		       sdp->host->host_no, sdp->channel, sdp->id, sdp->lun);
5886 
5887 	return 0;
5888 }
5889 
5890 static int scsi_debug_slave_configure(struct scsi_device *sdp)
5891 {
5892 	struct sdebug_dev_info *devip =
5893 			(struct sdebug_dev_info *)sdp->hostdata;
5894 	struct dentry *dentry;
5895 
5896 	if (sdebug_verbose)
5897 		pr_info("slave_configure <%u %u %u %llu>\n",
5898 		       sdp->host->host_no, sdp->channel, sdp->id, sdp->lun);
5899 	if (sdp->host->max_cmd_len != SDEBUG_MAX_CMD_LEN)
5900 		sdp->host->max_cmd_len = SDEBUG_MAX_CMD_LEN;
5901 	if (devip == NULL) {
5902 		devip = find_build_dev_info(sdp);
5903 		if (devip == NULL)
5904 			return 1;  /* no resources, will be marked offline */
5905 	}
5906 	sdp->hostdata = devip;
5907 	if (sdebug_no_uld)
5908 		sdp->no_uld_attach = 1;
5909 	config_cdb_len(sdp);
5910 
5911 	if (sdebug_allow_restart)
5912 		sdp->allow_restart = 1;
5913 
5914 	devip->debugfs_entry = debugfs_create_dir(dev_name(&sdp->sdev_dev),
5915 				sdebug_debugfs_root);
5916 	if (IS_ERR_OR_NULL(devip->debugfs_entry))
5917 		pr_info("%s: failed to create debugfs directory for device %s\n",
5918 			__func__, dev_name(&sdp->sdev_gendev));
5919 
5920 	dentry = debugfs_create_file("error", 0600, devip->debugfs_entry, sdp,
5921 				&sdebug_error_fops);
5922 	if (IS_ERR_OR_NULL(dentry))
5923 		pr_info("%s: failed to create error file for device %s\n",
5924 			__func__, dev_name(&sdp->sdev_gendev));
5925 
5926 	return 0;
5927 }
5928 
5929 static void scsi_debug_slave_destroy(struct scsi_device *sdp)
5930 {
5931 	struct sdebug_dev_info *devip =
5932 		(struct sdebug_dev_info *)sdp->hostdata;
5933 	struct sdebug_err_inject *err;
5934 
5935 	if (sdebug_verbose)
5936 		pr_info("slave_destroy <%u %u %u %llu>\n",
5937 		       sdp->host->host_no, sdp->channel, sdp->id, sdp->lun);
5938 
5939 	if (!devip)
5940 		return;
5941 
5942 	spin_lock(&devip->list_lock);
5943 	list_for_each_entry_rcu(err, &devip->inject_err_list, list) {
5944 		list_del_rcu(&err->list);
5945 		call_rcu(&err->rcu, sdebug_err_free);
5946 	}
5947 	spin_unlock(&devip->list_lock);
5948 
5949 	debugfs_remove(devip->debugfs_entry);
5950 
5951 	/* make this slot available for re-use */
5952 	devip->used = false;
5953 	sdp->hostdata = NULL;
5954 }
5955 
5956 /* Returns true if we require the queued memory to be freed by the caller. */
5957 static bool stop_qc_helper(struct sdebug_defer *sd_dp,
5958 			   enum sdeb_defer_type defer_t)
5959 {
5960 	if (defer_t == SDEB_DEFER_HRT) {
5961 		int res = hrtimer_try_to_cancel(&sd_dp->hrt);
5962 
5963 		switch (res) {
5964 		case 0: /* Not active, it must have already run */
5965 		case -1: /* -1 It's executing the CB */
5966 			return false;
5967 		case 1: /* Was active, we've now cancelled */
5968 		default:
5969 			return true;
5970 		}
5971 	} else if (defer_t == SDEB_DEFER_WQ) {
5972 		/* Cancel if pending */
5973 		if (cancel_work_sync(&sd_dp->ew.work))
5974 			return true;
5975 		/* Was not pending, so it must have run */
5976 		return false;
5977 	} else if (defer_t == SDEB_DEFER_POLL) {
5978 		return true;
5979 	}
5980 
5981 	return false;
5982 }
5983 
5984 
5985 static bool scsi_debug_stop_cmnd(struct scsi_cmnd *cmnd)
5986 {
5987 	enum sdeb_defer_type l_defer_t;
5988 	struct sdebug_defer *sd_dp;
5989 	struct sdebug_scsi_cmd *sdsc = scsi_cmd_priv(cmnd);
5990 	struct sdebug_queued_cmd *sqcp = TO_QUEUED_CMD(cmnd);
5991 
5992 	lockdep_assert_held(&sdsc->lock);
5993 
5994 	if (!sqcp)
5995 		return false;
5996 	sd_dp = &sqcp->sd_dp;
5997 	l_defer_t = READ_ONCE(sd_dp->defer_t);
5998 	ASSIGN_QUEUED_CMD(cmnd, NULL);
5999 
6000 	if (stop_qc_helper(sd_dp, l_defer_t))
6001 		sdebug_free_queued_cmd(sqcp);
6002 
6003 	return true;
6004 }
6005 
6006 /*
6007  * Called from scsi_debug_abort() only, which is for timed-out cmd.
6008  */
6009 static bool scsi_debug_abort_cmnd(struct scsi_cmnd *cmnd)
6010 {
6011 	struct sdebug_scsi_cmd *sdsc = scsi_cmd_priv(cmnd);
6012 	unsigned long flags;
6013 	bool res;
6014 
6015 	spin_lock_irqsave(&sdsc->lock, flags);
6016 	res = scsi_debug_stop_cmnd(cmnd);
6017 	spin_unlock_irqrestore(&sdsc->lock, flags);
6018 
6019 	return res;
6020 }
6021 
6022 /*
6023  * All we can do is set the cmnd as internally aborted and wait for it to
6024  * finish. We cannot call scsi_done() as normal completion path may do that.
6025  */
6026 static bool sdebug_stop_cmnd(struct request *rq, void *data)
6027 {
6028 	scsi_debug_abort_cmnd(blk_mq_rq_to_pdu(rq));
6029 
6030 	return true;
6031 }
6032 
6033 /* Deletes (stops) timers or work queues of all queued commands */
6034 static void stop_all_queued(void)
6035 {
6036 	struct sdebug_host_info *sdhp;
6037 
6038 	mutex_lock(&sdebug_host_list_mutex);
6039 	list_for_each_entry(sdhp, &sdebug_host_list, host_list) {
6040 		struct Scsi_Host *shost = sdhp->shost;
6041 
6042 		blk_mq_tagset_busy_iter(&shost->tag_set, sdebug_stop_cmnd, NULL);
6043 	}
6044 	mutex_unlock(&sdebug_host_list_mutex);
6045 }
6046 
6047 static int sdebug_fail_abort(struct scsi_cmnd *cmnd)
6048 {
6049 	struct scsi_device *sdp = cmnd->device;
6050 	struct sdebug_dev_info *devip = (struct sdebug_dev_info *)sdp->hostdata;
6051 	struct sdebug_err_inject *err;
6052 	unsigned char *cmd = cmnd->cmnd;
6053 	int ret = 0;
6054 
6055 	if (devip == NULL)
6056 		return 0;
6057 
6058 	rcu_read_lock();
6059 	list_for_each_entry_rcu(err, &devip->inject_err_list, list) {
6060 		if (err->type == ERR_ABORT_CMD_FAILED &&
6061 		    (err->cmd == cmd[0] || err->cmd == 0xff)) {
6062 			ret = !!err->cnt;
6063 			if (err->cnt < 0)
6064 				err->cnt++;
6065 
6066 			rcu_read_unlock();
6067 			return ret;
6068 		}
6069 	}
6070 	rcu_read_unlock();
6071 
6072 	return 0;
6073 }
6074 
6075 static int scsi_debug_abort(struct scsi_cmnd *SCpnt)
6076 {
6077 	bool ok = scsi_debug_abort_cmnd(SCpnt);
6078 	u8 *cmd = SCpnt->cmnd;
6079 	u8 opcode = cmd[0];
6080 
6081 	++num_aborts;
6082 
6083 	if (SDEBUG_OPT_ALL_NOISE & sdebug_opts)
6084 		sdev_printk(KERN_INFO, SCpnt->device,
6085 			    "%s: command%s found\n", __func__,
6086 			    ok ? "" : " not");
6087 
6088 	if (sdebug_fail_abort(SCpnt)) {
6089 		scmd_printk(KERN_INFO, SCpnt, "fail abort command 0x%x\n",
6090 			    opcode);
6091 		return FAILED;
6092 	}
6093 
6094 	return SUCCESS;
6095 }
6096 
6097 static bool scsi_debug_stop_all_queued_iter(struct request *rq, void *data)
6098 {
6099 	struct scsi_device *sdp = data;
6100 	struct scsi_cmnd *scmd = blk_mq_rq_to_pdu(rq);
6101 
6102 	if (scmd->device == sdp)
6103 		scsi_debug_abort_cmnd(scmd);
6104 
6105 	return true;
6106 }
6107 
6108 /* Deletes (stops) timers or work queues of all queued commands per sdev */
6109 static void scsi_debug_stop_all_queued(struct scsi_device *sdp)
6110 {
6111 	struct Scsi_Host *shost = sdp->host;
6112 
6113 	blk_mq_tagset_busy_iter(&shost->tag_set,
6114 				scsi_debug_stop_all_queued_iter, sdp);
6115 }
6116 
6117 static int sdebug_fail_lun_reset(struct scsi_cmnd *cmnd)
6118 {
6119 	struct scsi_device *sdp = cmnd->device;
6120 	struct sdebug_dev_info *devip = (struct sdebug_dev_info *)sdp->hostdata;
6121 	struct sdebug_err_inject *err;
6122 	unsigned char *cmd = cmnd->cmnd;
6123 	int ret = 0;
6124 
6125 	if (devip == NULL)
6126 		return 0;
6127 
6128 	rcu_read_lock();
6129 	list_for_each_entry_rcu(err, &devip->inject_err_list, list) {
6130 		if (err->type == ERR_LUN_RESET_FAILED &&
6131 		    (err->cmd == cmd[0] || err->cmd == 0xff)) {
6132 			ret = !!err->cnt;
6133 			if (err->cnt < 0)
6134 				err->cnt++;
6135 
6136 			rcu_read_unlock();
6137 			return ret;
6138 		}
6139 	}
6140 	rcu_read_unlock();
6141 
6142 	return 0;
6143 }
6144 
6145 static int scsi_debug_device_reset(struct scsi_cmnd *SCpnt)
6146 {
6147 	struct scsi_device *sdp = SCpnt->device;
6148 	struct sdebug_dev_info *devip = sdp->hostdata;
6149 	u8 *cmd = SCpnt->cmnd;
6150 	u8 opcode = cmd[0];
6151 
6152 	++num_dev_resets;
6153 
6154 	if (SDEBUG_OPT_ALL_NOISE & sdebug_opts)
6155 		sdev_printk(KERN_INFO, sdp, "%s\n", __func__);
6156 
6157 	scsi_debug_stop_all_queued(sdp);
6158 	if (devip)
6159 		set_bit(SDEBUG_UA_POR, devip->uas_bm);
6160 
6161 	if (sdebug_fail_lun_reset(SCpnt)) {
6162 		scmd_printk(KERN_INFO, SCpnt, "fail lun reset 0x%x\n", opcode);
6163 		return FAILED;
6164 	}
6165 
6166 	return SUCCESS;
6167 }
6168 
6169 static int sdebug_fail_target_reset(struct scsi_cmnd *cmnd)
6170 {
6171 	struct scsi_target *starget = scsi_target(cmnd->device);
6172 	struct sdebug_target_info *targetip =
6173 		(struct sdebug_target_info *)starget->hostdata;
6174 
6175 	if (targetip)
6176 		return targetip->reset_fail;
6177 
6178 	return 0;
6179 }
6180 
6181 static int scsi_debug_target_reset(struct scsi_cmnd *SCpnt)
6182 {
6183 	struct scsi_device *sdp = SCpnt->device;
6184 	struct sdebug_host_info *sdbg_host = shost_to_sdebug_host(sdp->host);
6185 	struct sdebug_dev_info *devip;
6186 	u8 *cmd = SCpnt->cmnd;
6187 	u8 opcode = cmd[0];
6188 	int k = 0;
6189 
6190 	++num_target_resets;
6191 	if (SDEBUG_OPT_ALL_NOISE & sdebug_opts)
6192 		sdev_printk(KERN_INFO, sdp, "%s\n", __func__);
6193 
6194 	list_for_each_entry(devip, &sdbg_host->dev_info_list, dev_list) {
6195 		if (devip->target == sdp->id) {
6196 			set_bit(SDEBUG_UA_BUS_RESET, devip->uas_bm);
6197 			++k;
6198 		}
6199 	}
6200 
6201 	if (SDEBUG_OPT_RESET_NOISE & sdebug_opts)
6202 		sdev_printk(KERN_INFO, sdp,
6203 			    "%s: %d device(s) found in target\n", __func__, k);
6204 
6205 	if (sdebug_fail_target_reset(SCpnt)) {
6206 		scmd_printk(KERN_INFO, SCpnt, "fail target reset 0x%x\n",
6207 			    opcode);
6208 		return FAILED;
6209 	}
6210 
6211 	return SUCCESS;
6212 }
6213 
6214 static int scsi_debug_bus_reset(struct scsi_cmnd *SCpnt)
6215 {
6216 	struct scsi_device *sdp = SCpnt->device;
6217 	struct sdebug_host_info *sdbg_host = shost_to_sdebug_host(sdp->host);
6218 	struct sdebug_dev_info *devip;
6219 	int k = 0;
6220 
6221 	++num_bus_resets;
6222 
6223 	if (SDEBUG_OPT_ALL_NOISE & sdebug_opts)
6224 		sdev_printk(KERN_INFO, sdp, "%s\n", __func__);
6225 
6226 	list_for_each_entry(devip, &sdbg_host->dev_info_list, dev_list) {
6227 		set_bit(SDEBUG_UA_BUS_RESET, devip->uas_bm);
6228 		++k;
6229 	}
6230 
6231 	if (SDEBUG_OPT_RESET_NOISE & sdebug_opts)
6232 		sdev_printk(KERN_INFO, sdp,
6233 			    "%s: %d device(s) found in host\n", __func__, k);
6234 	return SUCCESS;
6235 }
6236 
6237 static int scsi_debug_host_reset(struct scsi_cmnd *SCpnt)
6238 {
6239 	struct sdebug_host_info *sdbg_host;
6240 	struct sdebug_dev_info *devip;
6241 	int k = 0;
6242 
6243 	++num_host_resets;
6244 	if (SDEBUG_OPT_ALL_NOISE & sdebug_opts)
6245 		sdev_printk(KERN_INFO, SCpnt->device, "%s\n", __func__);
6246 	mutex_lock(&sdebug_host_list_mutex);
6247 	list_for_each_entry(sdbg_host, &sdebug_host_list, host_list) {
6248 		list_for_each_entry(devip, &sdbg_host->dev_info_list,
6249 				    dev_list) {
6250 			set_bit(SDEBUG_UA_BUS_RESET, devip->uas_bm);
6251 			++k;
6252 		}
6253 	}
6254 	mutex_unlock(&sdebug_host_list_mutex);
6255 	stop_all_queued();
6256 	if (SDEBUG_OPT_RESET_NOISE & sdebug_opts)
6257 		sdev_printk(KERN_INFO, SCpnt->device,
6258 			    "%s: %d device(s) found\n", __func__, k);
6259 	return SUCCESS;
6260 }
6261 
6262 static void sdebug_build_parts(unsigned char *ramp, unsigned long store_size)
6263 {
6264 	struct msdos_partition *pp;
6265 	int starts[SDEBUG_MAX_PARTS + 2], max_part_secs;
6266 	int sectors_per_part, num_sectors, k;
6267 	int heads_by_sects, start_sec, end_sec;
6268 
6269 	/* assume partition table already zeroed */
6270 	if ((sdebug_num_parts < 1) || (store_size < 1048576))
6271 		return;
6272 	if (sdebug_num_parts > SDEBUG_MAX_PARTS) {
6273 		sdebug_num_parts = SDEBUG_MAX_PARTS;
6274 		pr_warn("reducing partitions to %d\n", SDEBUG_MAX_PARTS);
6275 	}
6276 	num_sectors = (int)get_sdebug_capacity();
6277 	sectors_per_part = (num_sectors - sdebug_sectors_per)
6278 			   / sdebug_num_parts;
6279 	heads_by_sects = sdebug_heads * sdebug_sectors_per;
6280 	starts[0] = sdebug_sectors_per;
6281 	max_part_secs = sectors_per_part;
6282 	for (k = 1; k < sdebug_num_parts; ++k) {
6283 		starts[k] = ((k * sectors_per_part) / heads_by_sects)
6284 			    * heads_by_sects;
6285 		if (starts[k] - starts[k - 1] < max_part_secs)
6286 			max_part_secs = starts[k] - starts[k - 1];
6287 	}
6288 	starts[sdebug_num_parts] = num_sectors;
6289 	starts[sdebug_num_parts + 1] = 0;
6290 
6291 	ramp[510] = 0x55;	/* magic partition markings */
6292 	ramp[511] = 0xAA;
6293 	pp = (struct msdos_partition *)(ramp + 0x1be);
6294 	for (k = 0; starts[k + 1]; ++k, ++pp) {
6295 		start_sec = starts[k];
6296 		end_sec = starts[k] + max_part_secs - 1;
6297 		pp->boot_ind = 0;
6298 
6299 		pp->cyl = start_sec / heads_by_sects;
6300 		pp->head = (start_sec - (pp->cyl * heads_by_sects))
6301 			   / sdebug_sectors_per;
6302 		pp->sector = (start_sec % sdebug_sectors_per) + 1;
6303 
6304 		pp->end_cyl = end_sec / heads_by_sects;
6305 		pp->end_head = (end_sec - (pp->end_cyl * heads_by_sects))
6306 			       / sdebug_sectors_per;
6307 		pp->end_sector = (end_sec % sdebug_sectors_per) + 1;
6308 
6309 		pp->start_sect = cpu_to_le32(start_sec);
6310 		pp->nr_sects = cpu_to_le32(end_sec - start_sec + 1);
6311 		pp->sys_ind = 0x83;	/* plain Linux partition */
6312 	}
6313 }
6314 
6315 static void block_unblock_all_queues(bool block)
6316 {
6317 	struct sdebug_host_info *sdhp;
6318 
6319 	lockdep_assert_held(&sdebug_host_list_mutex);
6320 
6321 	list_for_each_entry(sdhp, &sdebug_host_list, host_list) {
6322 		struct Scsi_Host *shost = sdhp->shost;
6323 
6324 		if (block)
6325 			scsi_block_requests(shost);
6326 		else
6327 			scsi_unblock_requests(shost);
6328 	}
6329 }
6330 
6331 /* Adjust (by rounding down) the sdebug_cmnd_count so abs(every_nth)-1
6332  * commands will be processed normally before triggers occur.
6333  */
6334 static void tweak_cmnd_count(void)
6335 {
6336 	int count, modulo;
6337 
6338 	modulo = abs(sdebug_every_nth);
6339 	if (modulo < 2)
6340 		return;
6341 
6342 	mutex_lock(&sdebug_host_list_mutex);
6343 	block_unblock_all_queues(true);
6344 	count = atomic_read(&sdebug_cmnd_count);
6345 	atomic_set(&sdebug_cmnd_count, (count / modulo) * modulo);
6346 	block_unblock_all_queues(false);
6347 	mutex_unlock(&sdebug_host_list_mutex);
6348 }
6349 
6350 static void clear_queue_stats(void)
6351 {
6352 	atomic_set(&sdebug_cmnd_count, 0);
6353 	atomic_set(&sdebug_completions, 0);
6354 	atomic_set(&sdebug_miss_cpus, 0);
6355 	atomic_set(&sdebug_a_tsf, 0);
6356 }
6357 
6358 static bool inject_on_this_cmd(void)
6359 {
6360 	if (sdebug_every_nth == 0)
6361 		return false;
6362 	return (atomic_read(&sdebug_cmnd_count) % abs(sdebug_every_nth)) == 0;
6363 }
6364 
6365 #define INCLUSIVE_TIMING_MAX_NS 1000000		/* 1 millisecond */
6366 
6367 
6368 void sdebug_free_queued_cmd(struct sdebug_queued_cmd *sqcp)
6369 {
6370 	if (sqcp)
6371 		kmem_cache_free(queued_cmd_cache, sqcp);
6372 }
6373 
6374 static struct sdebug_queued_cmd *sdebug_alloc_queued_cmd(struct scsi_cmnd *scmd)
6375 {
6376 	struct sdebug_queued_cmd *sqcp;
6377 	struct sdebug_defer *sd_dp;
6378 
6379 	sqcp = kmem_cache_zalloc(queued_cmd_cache, GFP_ATOMIC);
6380 	if (!sqcp)
6381 		return NULL;
6382 
6383 	sd_dp = &sqcp->sd_dp;
6384 
6385 	hrtimer_init(&sd_dp->hrt, CLOCK_MONOTONIC, HRTIMER_MODE_REL_PINNED);
6386 	sd_dp->hrt.function = sdebug_q_cmd_hrt_complete;
6387 	INIT_WORK(&sd_dp->ew.work, sdebug_q_cmd_wq_complete);
6388 
6389 	sqcp->scmd = scmd;
6390 
6391 	return sqcp;
6392 }
6393 
6394 /* Complete the processing of the thread that queued a SCSI command to this
6395  * driver. It either completes the command by calling cmnd_done() or
6396  * schedules a hr timer or work queue then returns 0. Returns
6397  * SCSI_MLQUEUE_HOST_BUSY if temporarily out of resources.
6398  */
6399 static int schedule_resp(struct scsi_cmnd *cmnd, struct sdebug_dev_info *devip,
6400 			 int scsi_result,
6401 			 int (*pfp)(struct scsi_cmnd *,
6402 				    struct sdebug_dev_info *),
6403 			 int delta_jiff, int ndelay)
6404 {
6405 	struct request *rq = scsi_cmd_to_rq(cmnd);
6406 	bool polled = rq->cmd_flags & REQ_POLLED;
6407 	struct sdebug_scsi_cmd *sdsc = scsi_cmd_priv(cmnd);
6408 	unsigned long flags;
6409 	u64 ns_from_boot = 0;
6410 	struct sdebug_queued_cmd *sqcp;
6411 	struct scsi_device *sdp;
6412 	struct sdebug_defer *sd_dp;
6413 
6414 	if (unlikely(devip == NULL)) {
6415 		if (scsi_result == 0)
6416 			scsi_result = DID_NO_CONNECT << 16;
6417 		goto respond_in_thread;
6418 	}
6419 	sdp = cmnd->device;
6420 
6421 	if (delta_jiff == 0)
6422 		goto respond_in_thread;
6423 
6424 
6425 	if (unlikely(sdebug_every_nth && (SDEBUG_OPT_RARE_TSF & sdebug_opts) &&
6426 		     (scsi_result == 0))) {
6427 		int num_in_q = scsi_device_busy(sdp);
6428 		int qdepth = cmnd->device->queue_depth;
6429 
6430 		if ((num_in_q == qdepth) &&
6431 		    (atomic_inc_return(&sdebug_a_tsf) >=
6432 		     abs(sdebug_every_nth))) {
6433 			atomic_set(&sdebug_a_tsf, 0);
6434 			scsi_result = device_qfull_result;
6435 
6436 			if (unlikely(SDEBUG_OPT_Q_NOISE & sdebug_opts))
6437 				sdev_printk(KERN_INFO, sdp, "%s: num_in_q=%d +1, <inject> status: TASK SET FULL\n",
6438 					    __func__, num_in_q);
6439 		}
6440 	}
6441 
6442 	sqcp = sdebug_alloc_queued_cmd(cmnd);
6443 	if (!sqcp) {
6444 		pr_err("%s no alloc\n", __func__);
6445 		return SCSI_MLQUEUE_HOST_BUSY;
6446 	}
6447 	sd_dp = &sqcp->sd_dp;
6448 
6449 	if (polled)
6450 		ns_from_boot = ktime_get_boottime_ns();
6451 
6452 	/* one of the resp_*() response functions is called here */
6453 	cmnd->result = pfp ? pfp(cmnd, devip) : 0;
6454 	if (cmnd->result & SDEG_RES_IMMED_MASK) {
6455 		cmnd->result &= ~SDEG_RES_IMMED_MASK;
6456 		delta_jiff = ndelay = 0;
6457 	}
6458 	if (cmnd->result == 0 && scsi_result != 0)
6459 		cmnd->result = scsi_result;
6460 	if (cmnd->result == 0 && unlikely(sdebug_opts & SDEBUG_OPT_TRANSPORT_ERR)) {
6461 		if (atomic_read(&sdeb_inject_pending)) {
6462 			mk_sense_buffer(cmnd, ABORTED_COMMAND, TRANSPORT_PROBLEM, ACK_NAK_TO);
6463 			atomic_set(&sdeb_inject_pending, 0);
6464 			cmnd->result = check_condition_result;
6465 		}
6466 	}
6467 
6468 	if (unlikely(sdebug_verbose && cmnd->result))
6469 		sdev_printk(KERN_INFO, sdp, "%s: non-zero result=0x%x\n",
6470 			    __func__, cmnd->result);
6471 
6472 	if (delta_jiff > 0 || ndelay > 0) {
6473 		ktime_t kt;
6474 
6475 		if (delta_jiff > 0) {
6476 			u64 ns = jiffies_to_nsecs(delta_jiff);
6477 
6478 			if (sdebug_random && ns < U32_MAX) {
6479 				ns = get_random_u32_below((u32)ns);
6480 			} else if (sdebug_random) {
6481 				ns >>= 12;	/* scale to 4 usec precision */
6482 				if (ns < U32_MAX)	/* over 4 hours max */
6483 					ns = get_random_u32_below((u32)ns);
6484 				ns <<= 12;
6485 			}
6486 			kt = ns_to_ktime(ns);
6487 		} else {	/* ndelay has a 4.2 second max */
6488 			kt = sdebug_random ? get_random_u32_below((u32)ndelay) :
6489 					     (u32)ndelay;
6490 			if (ndelay < INCLUSIVE_TIMING_MAX_NS) {
6491 				u64 d = ktime_get_boottime_ns() - ns_from_boot;
6492 
6493 				if (kt <= d) {	/* elapsed duration >= kt */
6494 					/* call scsi_done() from this thread */
6495 					sdebug_free_queued_cmd(sqcp);
6496 					scsi_done(cmnd);
6497 					return 0;
6498 				}
6499 				/* otherwise reduce kt by elapsed time */
6500 				kt -= d;
6501 			}
6502 		}
6503 		if (sdebug_statistics)
6504 			sd_dp->issuing_cpu = raw_smp_processor_id();
6505 		if (polled) {
6506 			spin_lock_irqsave(&sdsc->lock, flags);
6507 			sd_dp->cmpl_ts = ktime_add(ns_to_ktime(ns_from_boot), kt);
6508 			ASSIGN_QUEUED_CMD(cmnd, sqcp);
6509 			WRITE_ONCE(sd_dp->defer_t, SDEB_DEFER_POLL);
6510 			spin_unlock_irqrestore(&sdsc->lock, flags);
6511 		} else {
6512 			/* schedule the invocation of scsi_done() for a later time */
6513 			spin_lock_irqsave(&sdsc->lock, flags);
6514 			ASSIGN_QUEUED_CMD(cmnd, sqcp);
6515 			WRITE_ONCE(sd_dp->defer_t, SDEB_DEFER_HRT);
6516 			hrtimer_start(&sd_dp->hrt, kt, HRTIMER_MODE_REL_PINNED);
6517 			/*
6518 			 * The completion handler will try to grab sqcp->lock,
6519 			 * so there is no chance that the completion handler
6520 			 * will call scsi_done() until we release the lock
6521 			 * here (so ok to keep referencing sdsc).
6522 			 */
6523 			spin_unlock_irqrestore(&sdsc->lock, flags);
6524 		}
6525 	} else {	/* jdelay < 0, use work queue */
6526 		if (unlikely((sdebug_opts & SDEBUG_OPT_CMD_ABORT) &&
6527 			     atomic_read(&sdeb_inject_pending))) {
6528 			sd_dp->aborted = true;
6529 			atomic_set(&sdeb_inject_pending, 0);
6530 			sdev_printk(KERN_INFO, sdp, "abort request tag=%#x\n",
6531 				    blk_mq_unique_tag_to_tag(get_tag(cmnd)));
6532 		}
6533 
6534 		if (sdebug_statistics)
6535 			sd_dp->issuing_cpu = raw_smp_processor_id();
6536 		if (polled) {
6537 			spin_lock_irqsave(&sdsc->lock, flags);
6538 			ASSIGN_QUEUED_CMD(cmnd, sqcp);
6539 			sd_dp->cmpl_ts = ns_to_ktime(ns_from_boot);
6540 			WRITE_ONCE(sd_dp->defer_t, SDEB_DEFER_POLL);
6541 			spin_unlock_irqrestore(&sdsc->lock, flags);
6542 		} else {
6543 			spin_lock_irqsave(&sdsc->lock, flags);
6544 			ASSIGN_QUEUED_CMD(cmnd, sqcp);
6545 			WRITE_ONCE(sd_dp->defer_t, SDEB_DEFER_WQ);
6546 			schedule_work(&sd_dp->ew.work);
6547 			spin_unlock_irqrestore(&sdsc->lock, flags);
6548 		}
6549 	}
6550 
6551 	return 0;
6552 
6553 respond_in_thread:	/* call back to mid-layer using invocation thread */
6554 	cmnd->result = pfp != NULL ? pfp(cmnd, devip) : 0;
6555 	cmnd->result &= ~SDEG_RES_IMMED_MASK;
6556 	if (cmnd->result == 0 && scsi_result != 0)
6557 		cmnd->result = scsi_result;
6558 	scsi_done(cmnd);
6559 	return 0;
6560 }
6561 
6562 /* Note: The following macros create attribute files in the
6563    /sys/module/scsi_debug/parameters directory. Unfortunately this
6564    driver is unaware of a change and cannot trigger auxiliary actions
6565    as it can when the corresponding attribute in the
6566    /sys/bus/pseudo/drivers/scsi_debug directory is changed.
6567  */
6568 module_param_named(add_host, sdebug_add_host, int, S_IRUGO | S_IWUSR);
6569 module_param_named(ato, sdebug_ato, int, S_IRUGO);
6570 module_param_named(cdb_len, sdebug_cdb_len, int, 0644);
6571 module_param_named(clustering, sdebug_clustering, bool, S_IRUGO | S_IWUSR);
6572 module_param_named(delay, sdebug_jdelay, int, S_IRUGO | S_IWUSR);
6573 module_param_named(dev_size_mb, sdebug_dev_size_mb, int, S_IRUGO);
6574 module_param_named(dif, sdebug_dif, int, S_IRUGO);
6575 module_param_named(dix, sdebug_dix, int, S_IRUGO);
6576 module_param_named(dsense, sdebug_dsense, int, S_IRUGO | S_IWUSR);
6577 module_param_named(every_nth, sdebug_every_nth, int, S_IRUGO | S_IWUSR);
6578 module_param_named(fake_rw, sdebug_fake_rw, int, S_IRUGO | S_IWUSR);
6579 module_param_named(guard, sdebug_guard, uint, S_IRUGO);
6580 module_param_named(host_lock, sdebug_host_lock, bool, S_IRUGO | S_IWUSR);
6581 module_param_named(host_max_queue, sdebug_host_max_queue, int, S_IRUGO);
6582 module_param_string(inq_product, sdebug_inq_product_id,
6583 		    sizeof(sdebug_inq_product_id), S_IRUGO | S_IWUSR);
6584 module_param_string(inq_rev, sdebug_inq_product_rev,
6585 		    sizeof(sdebug_inq_product_rev), S_IRUGO | S_IWUSR);
6586 module_param_string(inq_vendor, sdebug_inq_vendor_id,
6587 		    sizeof(sdebug_inq_vendor_id), S_IRUGO | S_IWUSR);
6588 module_param_named(lbprz, sdebug_lbprz, int, S_IRUGO);
6589 module_param_named(lbpu, sdebug_lbpu, int, S_IRUGO);
6590 module_param_named(lbpws, sdebug_lbpws, int, S_IRUGO);
6591 module_param_named(lbpws10, sdebug_lbpws10, int, S_IRUGO);
6592 module_param_named(atomic_wr, sdebug_atomic_wr, int, S_IRUGO);
6593 module_param_named(lowest_aligned, sdebug_lowest_aligned, int, S_IRUGO);
6594 module_param_named(lun_format, sdebug_lun_am_i, int, S_IRUGO | S_IWUSR);
6595 module_param_named(max_luns, sdebug_max_luns, int, S_IRUGO | S_IWUSR);
6596 module_param_named(max_queue, sdebug_max_queue, int, S_IRUGO | S_IWUSR);
6597 module_param_named(medium_error_count, sdebug_medium_error_count, int,
6598 		   S_IRUGO | S_IWUSR);
6599 module_param_named(medium_error_start, sdebug_medium_error_start, int,
6600 		   S_IRUGO | S_IWUSR);
6601 module_param_named(ndelay, sdebug_ndelay, int, S_IRUGO | S_IWUSR);
6602 module_param_named(no_lun_0, sdebug_no_lun_0, int, S_IRUGO | S_IWUSR);
6603 module_param_named(no_rwlock, sdebug_no_rwlock, bool, S_IRUGO | S_IWUSR);
6604 module_param_named(no_uld, sdebug_no_uld, int, S_IRUGO);
6605 module_param_named(num_parts, sdebug_num_parts, int, S_IRUGO);
6606 module_param_named(num_tgts, sdebug_num_tgts, int, S_IRUGO | S_IWUSR);
6607 module_param_named(opt_blks, sdebug_opt_blks, int, S_IRUGO);
6608 module_param_named(opt_xferlen_exp, sdebug_opt_xferlen_exp, int, S_IRUGO);
6609 module_param_named(opts, sdebug_opts, int, S_IRUGO | S_IWUSR);
6610 module_param_named(per_host_store, sdebug_per_host_store, bool,
6611 		   S_IRUGO | S_IWUSR);
6612 module_param_named(physblk_exp, sdebug_physblk_exp, int, S_IRUGO);
6613 module_param_named(ptype, sdebug_ptype, int, S_IRUGO | S_IWUSR);
6614 module_param_named(random, sdebug_random, bool, S_IRUGO | S_IWUSR);
6615 module_param_named(removable, sdebug_removable, bool, S_IRUGO | S_IWUSR);
6616 module_param_named(scsi_level, sdebug_scsi_level, int, S_IRUGO);
6617 module_param_named(sector_size, sdebug_sector_size, int, S_IRUGO);
6618 module_param_named(statistics, sdebug_statistics, bool, S_IRUGO | S_IWUSR);
6619 module_param_named(strict, sdebug_strict, bool, S_IRUGO | S_IWUSR);
6620 module_param_named(submit_queues, submit_queues, int, S_IRUGO);
6621 module_param_named(poll_queues, poll_queues, int, S_IRUGO);
6622 module_param_named(tur_ms_to_ready, sdeb_tur_ms_to_ready, int, S_IRUGO);
6623 module_param_named(unmap_alignment, sdebug_unmap_alignment, int, S_IRUGO);
6624 module_param_named(unmap_granularity, sdebug_unmap_granularity, int, S_IRUGO);
6625 module_param_named(unmap_max_blocks, sdebug_unmap_max_blocks, int, S_IRUGO);
6626 module_param_named(unmap_max_desc, sdebug_unmap_max_desc, int, S_IRUGO);
6627 module_param_named(atomic_wr_max_length, sdebug_atomic_wr_max_length, int, S_IRUGO);
6628 module_param_named(atomic_wr_align, sdebug_atomic_wr_align, int, S_IRUGO);
6629 module_param_named(atomic_wr_gran, sdebug_atomic_wr_gran, int, S_IRUGO);
6630 module_param_named(atomic_wr_max_length_bndry, sdebug_atomic_wr_max_length_bndry, int, S_IRUGO);
6631 module_param_named(atomic_wr_max_bndry, sdebug_atomic_wr_max_bndry, int, S_IRUGO);
6632 module_param_named(uuid_ctl, sdebug_uuid_ctl, int, S_IRUGO);
6633 module_param_named(virtual_gb, sdebug_virtual_gb, int, S_IRUGO | S_IWUSR);
6634 module_param_named(vpd_use_hostno, sdebug_vpd_use_hostno, int,
6635 		   S_IRUGO | S_IWUSR);
6636 module_param_named(wp, sdebug_wp, bool, S_IRUGO | S_IWUSR);
6637 module_param_named(write_same_length, sdebug_write_same_length, int,
6638 		   S_IRUGO | S_IWUSR);
6639 module_param_named(zbc, sdeb_zbc_model_s, charp, S_IRUGO);
6640 module_param_named(zone_cap_mb, sdeb_zbc_zone_cap_mb, int, S_IRUGO);
6641 module_param_named(zone_max_open, sdeb_zbc_max_open, int, S_IRUGO);
6642 module_param_named(zone_nr_conv, sdeb_zbc_nr_conv, int, S_IRUGO);
6643 module_param_named(zone_size_mb, sdeb_zbc_zone_size_mb, int, S_IRUGO);
6644 module_param_named(allow_restart, sdebug_allow_restart, bool, S_IRUGO | S_IWUSR);
6645 
6646 MODULE_AUTHOR("Eric Youngdale + Douglas Gilbert");
6647 MODULE_DESCRIPTION("SCSI debug adapter driver");
6648 MODULE_LICENSE("GPL");
6649 MODULE_VERSION(SDEBUG_VERSION);
6650 
6651 MODULE_PARM_DESC(add_host, "add n hosts, in sysfs if negative remove host(s) (def=1)");
6652 MODULE_PARM_DESC(ato, "application tag ownership: 0=disk 1=host (def=1)");
6653 MODULE_PARM_DESC(cdb_len, "suggest CDB lengths to drivers (def=10)");
6654 MODULE_PARM_DESC(clustering, "when set enables larger transfers (def=0)");
6655 MODULE_PARM_DESC(delay, "response delay (def=1 jiffy); 0:imm, -1,-2:tiny");
6656 MODULE_PARM_DESC(dev_size_mb, "size in MiB of ram shared by devs(def=8)");
6657 MODULE_PARM_DESC(dif, "data integrity field type: 0-3 (def=0)");
6658 MODULE_PARM_DESC(dix, "data integrity extensions mask (def=0)");
6659 MODULE_PARM_DESC(dsense, "use descriptor sense format(def=0 -> fixed)");
6660 MODULE_PARM_DESC(every_nth, "timeout every nth command(def=0)");
6661 MODULE_PARM_DESC(fake_rw, "fake reads/writes instead of copying (def=0)");
6662 MODULE_PARM_DESC(guard, "protection checksum: 0=crc, 1=ip (def=0)");
6663 MODULE_PARM_DESC(host_lock, "host_lock is ignored (def=0)");
6664 MODULE_PARM_DESC(host_max_queue,
6665 		 "host max # of queued cmds (0 to max(def) [max_queue fixed equal for !0])");
6666 MODULE_PARM_DESC(inq_product, "SCSI INQUIRY product string (def=\"scsi_debug\")");
6667 MODULE_PARM_DESC(inq_rev, "SCSI INQUIRY revision string (def=\""
6668 		 SDEBUG_VERSION "\")");
6669 MODULE_PARM_DESC(inq_vendor, "SCSI INQUIRY vendor string (def=\"Linux\")");
6670 MODULE_PARM_DESC(lbprz,
6671 		 "on read unmapped LBs return 0 when 1 (def), return 0xff when 2");
6672 MODULE_PARM_DESC(lbpu, "enable LBP, support UNMAP command (def=0)");
6673 MODULE_PARM_DESC(lbpws, "enable LBP, support WRITE SAME(16) with UNMAP bit (def=0)");
6674 MODULE_PARM_DESC(lbpws10, "enable LBP, support WRITE SAME(10) with UNMAP bit (def=0)");
6675 MODULE_PARM_DESC(atomic_write, "enable ATOMIC WRITE support, support WRITE ATOMIC(16) (def=0)");
6676 MODULE_PARM_DESC(lowest_aligned, "lowest aligned lba (def=0)");
6677 MODULE_PARM_DESC(lun_format, "LUN format: 0->peripheral (def); 1 --> flat address method");
6678 MODULE_PARM_DESC(max_luns, "number of LUNs per target to simulate(def=1)");
6679 MODULE_PARM_DESC(max_queue, "max number of queued commands (1 to max(def))");
6680 MODULE_PARM_DESC(medium_error_count, "count of sectors to return follow on MEDIUM error");
6681 MODULE_PARM_DESC(medium_error_start, "starting sector number to return MEDIUM error");
6682 MODULE_PARM_DESC(ndelay, "response delay in nanoseconds (def=0 -> ignore)");
6683 MODULE_PARM_DESC(no_lun_0, "no LU number 0 (def=0 -> have lun 0)");
6684 MODULE_PARM_DESC(no_rwlock, "don't protect user data reads+writes (def=0)");
6685 MODULE_PARM_DESC(no_uld, "stop ULD (e.g. sd driver) attaching (def=0))");
6686 MODULE_PARM_DESC(num_parts, "number of partitions(def=0)");
6687 MODULE_PARM_DESC(num_tgts, "number of targets per host to simulate(def=1)");
6688 MODULE_PARM_DESC(opt_blks, "optimal transfer length in blocks (def=1024)");
6689 MODULE_PARM_DESC(opt_xferlen_exp, "optimal transfer length granularity exponent (def=physblk_exp)");
6690 MODULE_PARM_DESC(opts, "1->noise, 2->medium_err, 4->timeout, 8->recovered_err... (def=0)");
6691 MODULE_PARM_DESC(per_host_store, "If set, next positive add_host will get new store (def=0)");
6692 MODULE_PARM_DESC(physblk_exp, "physical block exponent (def=0)");
6693 MODULE_PARM_DESC(poll_queues, "support for iouring iopoll queues (1 to max(submit_queues - 1))");
6694 MODULE_PARM_DESC(ptype, "SCSI peripheral type(def=0[disk])");
6695 MODULE_PARM_DESC(random, "If set, uniformly randomize command duration between 0 and delay_in_ns");
6696 MODULE_PARM_DESC(removable, "claim to have removable media (def=0)");
6697 MODULE_PARM_DESC(scsi_level, "SCSI level to simulate(def=7[SPC-5])");
6698 MODULE_PARM_DESC(sector_size, "logical block size in bytes (def=512)");
6699 MODULE_PARM_DESC(statistics, "collect statistics on commands, queues (def=0)");
6700 MODULE_PARM_DESC(strict, "stricter checks: reserved field in cdb (def=0)");
6701 MODULE_PARM_DESC(submit_queues, "support for block multi-queue (def=1)");
6702 MODULE_PARM_DESC(tur_ms_to_ready, "TEST UNIT READY millisecs before initial good status (def=0)");
6703 MODULE_PARM_DESC(unmap_alignment, "lowest aligned thin provisioning lba (def=0)");
6704 MODULE_PARM_DESC(unmap_granularity, "thin provisioning granularity in blocks (def=1)");
6705 MODULE_PARM_DESC(unmap_max_blocks, "max # of blocks can be unmapped in one cmd (def=0xffffffff)");
6706 MODULE_PARM_DESC(unmap_max_desc, "max # of ranges that can be unmapped in one cmd (def=256)");
6707 MODULE_PARM_DESC(atomic_wr_max_length, "max # of blocks can be atomically written in one cmd (def=8192)");
6708 MODULE_PARM_DESC(atomic_wr_align, "minimum alignment of atomic write in blocks (def=2)");
6709 MODULE_PARM_DESC(atomic_wr_gran, "minimum granularity of atomic write in blocks (def=2)");
6710 MODULE_PARM_DESC(atomic_wr_max_length_bndry, "max # of blocks can be atomically written in one cmd with boundary set (def=8192)");
6711 MODULE_PARM_DESC(atomic_wr_max_bndry, "max # boundaries per atomic write (def=128)");
6712 MODULE_PARM_DESC(uuid_ctl,
6713 		 "1->use uuid for lu name, 0->don't, 2->all use same (def=0)");
6714 MODULE_PARM_DESC(virtual_gb, "virtual gigabyte (GiB) size (def=0 -> use dev_size_mb)");
6715 MODULE_PARM_DESC(vpd_use_hostno, "0 -> dev ids ignore hostno (def=1 -> unique dev ids)");
6716 MODULE_PARM_DESC(wp, "Write Protect (def=0)");
6717 MODULE_PARM_DESC(write_same_length, "Maximum blocks per WRITE SAME cmd (def=0xffff)");
6718 MODULE_PARM_DESC(zbc, "'none' [0]; 'aware' [1]; 'managed' [2] (def=0). Can have 'host-' prefix");
6719 MODULE_PARM_DESC(zone_cap_mb, "Zone capacity in MiB (def=zone size)");
6720 MODULE_PARM_DESC(zone_max_open, "Maximum number of open zones; [0] for no limit (def=auto)");
6721 MODULE_PARM_DESC(zone_nr_conv, "Number of conventional zones (def=1)");
6722 MODULE_PARM_DESC(zone_size_mb, "Zone size in MiB (def=auto)");
6723 MODULE_PARM_DESC(allow_restart, "Set scsi_device's allow_restart flag(def=0)");
6724 
6725 #define SDEBUG_INFO_LEN 256
6726 static char sdebug_info[SDEBUG_INFO_LEN];
6727 
6728 static const char *scsi_debug_info(struct Scsi_Host *shp)
6729 {
6730 	int k;
6731 
6732 	k = scnprintf(sdebug_info, SDEBUG_INFO_LEN, "%s: version %s [%s]\n",
6733 		      my_name, SDEBUG_VERSION, sdebug_version_date);
6734 	if (k >= (SDEBUG_INFO_LEN - 1))
6735 		return sdebug_info;
6736 	scnprintf(sdebug_info + k, SDEBUG_INFO_LEN - k,
6737 		  "  dev_size_mb=%d, opts=0x%x, submit_queues=%d, %s=%d",
6738 		  sdebug_dev_size_mb, sdebug_opts, submit_queues,
6739 		  "statistics", (int)sdebug_statistics);
6740 	return sdebug_info;
6741 }
6742 
6743 /* 'echo <val> > /proc/scsi/scsi_debug/<host_id>' writes to opts */
6744 static int scsi_debug_write_info(struct Scsi_Host *host, char *buffer,
6745 				 int length)
6746 {
6747 	char arr[16];
6748 	int opts;
6749 	int minLen = length > 15 ? 15 : length;
6750 
6751 	if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
6752 		return -EACCES;
6753 	memcpy(arr, buffer, minLen);
6754 	arr[minLen] = '\0';
6755 	if (1 != sscanf(arr, "%d", &opts))
6756 		return -EINVAL;
6757 	sdebug_opts = opts;
6758 	sdebug_verbose = !!(SDEBUG_OPT_NOISE & opts);
6759 	sdebug_any_injecting_opt = !!(SDEBUG_OPT_ALL_INJECTING & opts);
6760 	if (sdebug_every_nth != 0)
6761 		tweak_cmnd_count();
6762 	return length;
6763 }
6764 
6765 struct sdebug_submit_queue_data {
6766 	int *first;
6767 	int *last;
6768 	int queue_num;
6769 };
6770 
6771 static bool sdebug_submit_queue_iter(struct request *rq, void *opaque)
6772 {
6773 	struct sdebug_submit_queue_data *data = opaque;
6774 	u32 unique_tag = blk_mq_unique_tag(rq);
6775 	u16 hwq = blk_mq_unique_tag_to_hwq(unique_tag);
6776 	u16 tag = blk_mq_unique_tag_to_tag(unique_tag);
6777 	int queue_num = data->queue_num;
6778 
6779 	if (hwq != queue_num)
6780 		return true;
6781 
6782 	/* Rely on iter'ing in ascending tag order */
6783 	if (*data->first == -1)
6784 		*data->first = *data->last = tag;
6785 	else
6786 		*data->last = tag;
6787 
6788 	return true;
6789 }
6790 
6791 /* Output seen with 'cat /proc/scsi/scsi_debug/<host_id>'. It will be the
6792  * same for each scsi_debug host (if more than one). Some of the counters
6793  * output are not atomics so might be inaccurate in a busy system. */
6794 static int scsi_debug_show_info(struct seq_file *m, struct Scsi_Host *host)
6795 {
6796 	struct sdebug_host_info *sdhp;
6797 	int j;
6798 
6799 	seq_printf(m, "scsi_debug adapter driver, version %s [%s]\n",
6800 		   SDEBUG_VERSION, sdebug_version_date);
6801 	seq_printf(m, "num_tgts=%d, %ssize=%d MB, opts=0x%x, every_nth=%d\n",
6802 		   sdebug_num_tgts, "shared (ram) ", sdebug_dev_size_mb,
6803 		   sdebug_opts, sdebug_every_nth);
6804 	seq_printf(m, "delay=%d, ndelay=%d, max_luns=%d, sector_size=%d %s\n",
6805 		   sdebug_jdelay, sdebug_ndelay, sdebug_max_luns,
6806 		   sdebug_sector_size, "bytes");
6807 	seq_printf(m, "cylinders=%d, heads=%d, sectors=%d, command aborts=%d\n",
6808 		   sdebug_cylinders_per, sdebug_heads, sdebug_sectors_per,
6809 		   num_aborts);
6810 	seq_printf(m, "RESETs: device=%d, target=%d, bus=%d, host=%d\n",
6811 		   num_dev_resets, num_target_resets, num_bus_resets,
6812 		   num_host_resets);
6813 	seq_printf(m, "dix_reads=%d, dix_writes=%d, dif_errors=%d\n",
6814 		   dix_reads, dix_writes, dif_errors);
6815 	seq_printf(m, "usec_in_jiffy=%lu, statistics=%d\n", TICK_NSEC / 1000,
6816 		   sdebug_statistics);
6817 	seq_printf(m, "cmnd_count=%d, completions=%d, %s=%d, a_tsf=%d, mq_polls=%d\n",
6818 		   atomic_read(&sdebug_cmnd_count),
6819 		   atomic_read(&sdebug_completions),
6820 		   "miss_cpus", atomic_read(&sdebug_miss_cpus),
6821 		   atomic_read(&sdebug_a_tsf),
6822 		   atomic_read(&sdeb_mq_poll_count));
6823 
6824 	seq_printf(m, "submit_queues=%d\n", submit_queues);
6825 	for (j = 0; j < submit_queues; ++j) {
6826 		int f = -1, l = -1;
6827 		struct sdebug_submit_queue_data data = {
6828 			.queue_num = j,
6829 			.first = &f,
6830 			.last = &l,
6831 		};
6832 		seq_printf(m, "  queue %d:\n", j);
6833 		blk_mq_tagset_busy_iter(&host->tag_set, sdebug_submit_queue_iter,
6834 					&data);
6835 		if (f >= 0) {
6836 			seq_printf(m, "    in_use_bm BUSY: %s: %d,%d\n",
6837 				   "first,last bits", f, l);
6838 		}
6839 	}
6840 
6841 	seq_printf(m, "this host_no=%d\n", host->host_no);
6842 	if (!xa_empty(per_store_ap)) {
6843 		bool niu;
6844 		int idx;
6845 		unsigned long l_idx;
6846 		struct sdeb_store_info *sip;
6847 
6848 		seq_puts(m, "\nhost list:\n");
6849 		j = 0;
6850 		list_for_each_entry(sdhp, &sdebug_host_list, host_list) {
6851 			idx = sdhp->si_idx;
6852 			seq_printf(m, "  %d: host_no=%d, si_idx=%d\n", j,
6853 				   sdhp->shost->host_no, idx);
6854 			++j;
6855 		}
6856 		seq_printf(m, "\nper_store array [most_recent_idx=%d]:\n",
6857 			   sdeb_most_recent_idx);
6858 		j = 0;
6859 		xa_for_each(per_store_ap, l_idx, sip) {
6860 			niu = xa_get_mark(per_store_ap, l_idx,
6861 					  SDEB_XA_NOT_IN_USE);
6862 			idx = (int)l_idx;
6863 			seq_printf(m, "  %d: idx=%d%s\n", j, idx,
6864 				   (niu ? "  not_in_use" : ""));
6865 			++j;
6866 		}
6867 	}
6868 	return 0;
6869 }
6870 
6871 static ssize_t delay_show(struct device_driver *ddp, char *buf)
6872 {
6873 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_jdelay);
6874 }
6875 /* Returns -EBUSY if jdelay is being changed and commands are queued. The unit
6876  * of delay is jiffies.
6877  */
6878 static ssize_t delay_store(struct device_driver *ddp, const char *buf,
6879 			   size_t count)
6880 {
6881 	int jdelay, res;
6882 
6883 	if (count > 0 && sscanf(buf, "%d", &jdelay) == 1) {
6884 		res = count;
6885 		if (sdebug_jdelay != jdelay) {
6886 			struct sdebug_host_info *sdhp;
6887 
6888 			mutex_lock(&sdebug_host_list_mutex);
6889 			block_unblock_all_queues(true);
6890 
6891 			list_for_each_entry(sdhp, &sdebug_host_list, host_list) {
6892 				struct Scsi_Host *shost = sdhp->shost;
6893 
6894 				if (scsi_host_busy(shost)) {
6895 					res = -EBUSY;   /* queued commands */
6896 					break;
6897 				}
6898 			}
6899 			if (res > 0) {
6900 				sdebug_jdelay = jdelay;
6901 				sdebug_ndelay = 0;
6902 			}
6903 			block_unblock_all_queues(false);
6904 			mutex_unlock(&sdebug_host_list_mutex);
6905 		}
6906 		return res;
6907 	}
6908 	return -EINVAL;
6909 }
6910 static DRIVER_ATTR_RW(delay);
6911 
6912 static ssize_t ndelay_show(struct device_driver *ddp, char *buf)
6913 {
6914 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_ndelay);
6915 }
6916 /* Returns -EBUSY if ndelay is being changed and commands are queued */
6917 /* If > 0 and accepted then sdebug_jdelay is set to JDELAY_OVERRIDDEN */
6918 static ssize_t ndelay_store(struct device_driver *ddp, const char *buf,
6919 			    size_t count)
6920 {
6921 	int ndelay, res;
6922 
6923 	if ((count > 0) && (1 == sscanf(buf, "%d", &ndelay)) &&
6924 	    (ndelay >= 0) && (ndelay < (1000 * 1000 * 1000))) {
6925 		res = count;
6926 		if (sdebug_ndelay != ndelay) {
6927 			struct sdebug_host_info *sdhp;
6928 
6929 			mutex_lock(&sdebug_host_list_mutex);
6930 			block_unblock_all_queues(true);
6931 
6932 			list_for_each_entry(sdhp, &sdebug_host_list, host_list) {
6933 				struct Scsi_Host *shost = sdhp->shost;
6934 
6935 				if (scsi_host_busy(shost)) {
6936 					res = -EBUSY;   /* queued commands */
6937 					break;
6938 				}
6939 			}
6940 
6941 			if (res > 0) {
6942 				sdebug_ndelay = ndelay;
6943 				sdebug_jdelay = ndelay  ? JDELAY_OVERRIDDEN
6944 							: DEF_JDELAY;
6945 			}
6946 			block_unblock_all_queues(false);
6947 			mutex_unlock(&sdebug_host_list_mutex);
6948 		}
6949 		return res;
6950 	}
6951 	return -EINVAL;
6952 }
6953 static DRIVER_ATTR_RW(ndelay);
6954 
6955 static ssize_t opts_show(struct device_driver *ddp, char *buf)
6956 {
6957 	return scnprintf(buf, PAGE_SIZE, "0x%x\n", sdebug_opts);
6958 }
6959 
6960 static ssize_t opts_store(struct device_driver *ddp, const char *buf,
6961 			  size_t count)
6962 {
6963 	int opts;
6964 	char work[20];
6965 
6966 	if (sscanf(buf, "%10s", work) == 1) {
6967 		if (strncasecmp(work, "0x", 2) == 0) {
6968 			if (kstrtoint(work + 2, 16, &opts) == 0)
6969 				goto opts_done;
6970 		} else {
6971 			if (kstrtoint(work, 10, &opts) == 0)
6972 				goto opts_done;
6973 		}
6974 	}
6975 	return -EINVAL;
6976 opts_done:
6977 	sdebug_opts = opts;
6978 	sdebug_verbose = !!(SDEBUG_OPT_NOISE & opts);
6979 	sdebug_any_injecting_opt = !!(SDEBUG_OPT_ALL_INJECTING & opts);
6980 	tweak_cmnd_count();
6981 	return count;
6982 }
6983 static DRIVER_ATTR_RW(opts);
6984 
6985 static ssize_t ptype_show(struct device_driver *ddp, char *buf)
6986 {
6987 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_ptype);
6988 }
6989 static ssize_t ptype_store(struct device_driver *ddp, const char *buf,
6990 			   size_t count)
6991 {
6992 	int n;
6993 
6994 	/* Cannot change from or to TYPE_ZBC with sysfs */
6995 	if (sdebug_ptype == TYPE_ZBC)
6996 		return -EINVAL;
6997 
6998 	if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
6999 		if (n == TYPE_ZBC)
7000 			return -EINVAL;
7001 		sdebug_ptype = n;
7002 		return count;
7003 	}
7004 	return -EINVAL;
7005 }
7006 static DRIVER_ATTR_RW(ptype);
7007 
7008 static ssize_t dsense_show(struct device_driver *ddp, char *buf)
7009 {
7010 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_dsense);
7011 }
7012 static ssize_t dsense_store(struct device_driver *ddp, const char *buf,
7013 			    size_t count)
7014 {
7015 	int n;
7016 
7017 	if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
7018 		sdebug_dsense = n;
7019 		return count;
7020 	}
7021 	return -EINVAL;
7022 }
7023 static DRIVER_ATTR_RW(dsense);
7024 
7025 static ssize_t fake_rw_show(struct device_driver *ddp, char *buf)
7026 {
7027 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_fake_rw);
7028 }
7029 static ssize_t fake_rw_store(struct device_driver *ddp, const char *buf,
7030 			     size_t count)
7031 {
7032 	int n, idx;
7033 
7034 	if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
7035 		bool want_store = (n == 0);
7036 		struct sdebug_host_info *sdhp;
7037 
7038 		n = (n > 0);
7039 		sdebug_fake_rw = (sdebug_fake_rw > 0);
7040 		if (sdebug_fake_rw == n)
7041 			return count;	/* not transitioning so do nothing */
7042 
7043 		if (want_store) {	/* 1 --> 0 transition, set up store */
7044 			if (sdeb_first_idx < 0) {
7045 				idx = sdebug_add_store();
7046 				if (idx < 0)
7047 					return idx;
7048 			} else {
7049 				idx = sdeb_first_idx;
7050 				xa_clear_mark(per_store_ap, idx,
7051 					      SDEB_XA_NOT_IN_USE);
7052 			}
7053 			/* make all hosts use same store */
7054 			list_for_each_entry(sdhp, &sdebug_host_list,
7055 					    host_list) {
7056 				if (sdhp->si_idx != idx) {
7057 					xa_set_mark(per_store_ap, sdhp->si_idx,
7058 						    SDEB_XA_NOT_IN_USE);
7059 					sdhp->si_idx = idx;
7060 				}
7061 			}
7062 			sdeb_most_recent_idx = idx;
7063 		} else {	/* 0 --> 1 transition is trigger for shrink */
7064 			sdebug_erase_all_stores(true /* apart from first */);
7065 		}
7066 		sdebug_fake_rw = n;
7067 		return count;
7068 	}
7069 	return -EINVAL;
7070 }
7071 static DRIVER_ATTR_RW(fake_rw);
7072 
7073 static ssize_t no_lun_0_show(struct device_driver *ddp, char *buf)
7074 {
7075 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_no_lun_0);
7076 }
7077 static ssize_t no_lun_0_store(struct device_driver *ddp, const char *buf,
7078 			      size_t count)
7079 {
7080 	int n;
7081 
7082 	if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
7083 		sdebug_no_lun_0 = n;
7084 		return count;
7085 	}
7086 	return -EINVAL;
7087 }
7088 static DRIVER_ATTR_RW(no_lun_0);
7089 
7090 static ssize_t num_tgts_show(struct device_driver *ddp, char *buf)
7091 {
7092 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_num_tgts);
7093 }
7094 static ssize_t num_tgts_store(struct device_driver *ddp, const char *buf,
7095 			      size_t count)
7096 {
7097 	int n;
7098 
7099 	if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
7100 		sdebug_num_tgts = n;
7101 		sdebug_max_tgts_luns();
7102 		return count;
7103 	}
7104 	return -EINVAL;
7105 }
7106 static DRIVER_ATTR_RW(num_tgts);
7107 
7108 static ssize_t dev_size_mb_show(struct device_driver *ddp, char *buf)
7109 {
7110 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_dev_size_mb);
7111 }
7112 static DRIVER_ATTR_RO(dev_size_mb);
7113 
7114 static ssize_t per_host_store_show(struct device_driver *ddp, char *buf)
7115 {
7116 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_per_host_store);
7117 }
7118 
7119 static ssize_t per_host_store_store(struct device_driver *ddp, const char *buf,
7120 				    size_t count)
7121 {
7122 	bool v;
7123 
7124 	if (kstrtobool(buf, &v))
7125 		return -EINVAL;
7126 
7127 	sdebug_per_host_store = v;
7128 	return count;
7129 }
7130 static DRIVER_ATTR_RW(per_host_store);
7131 
7132 static ssize_t num_parts_show(struct device_driver *ddp, char *buf)
7133 {
7134 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_num_parts);
7135 }
7136 static DRIVER_ATTR_RO(num_parts);
7137 
7138 static ssize_t every_nth_show(struct device_driver *ddp, char *buf)
7139 {
7140 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_every_nth);
7141 }
7142 static ssize_t every_nth_store(struct device_driver *ddp, const char *buf,
7143 			       size_t count)
7144 {
7145 	int nth;
7146 	char work[20];
7147 
7148 	if (sscanf(buf, "%10s", work) == 1) {
7149 		if (strncasecmp(work, "0x", 2) == 0) {
7150 			if (kstrtoint(work + 2, 16, &nth) == 0)
7151 				goto every_nth_done;
7152 		} else {
7153 			if (kstrtoint(work, 10, &nth) == 0)
7154 				goto every_nth_done;
7155 		}
7156 	}
7157 	return -EINVAL;
7158 
7159 every_nth_done:
7160 	sdebug_every_nth = nth;
7161 	if (nth && !sdebug_statistics) {
7162 		pr_info("every_nth needs statistics=1, set it\n");
7163 		sdebug_statistics = true;
7164 	}
7165 	tweak_cmnd_count();
7166 	return count;
7167 }
7168 static DRIVER_ATTR_RW(every_nth);
7169 
7170 static ssize_t lun_format_show(struct device_driver *ddp, char *buf)
7171 {
7172 	return scnprintf(buf, PAGE_SIZE, "%d\n", (int)sdebug_lun_am);
7173 }
7174 static ssize_t lun_format_store(struct device_driver *ddp, const char *buf,
7175 				size_t count)
7176 {
7177 	int n;
7178 	bool changed;
7179 
7180 	if (kstrtoint(buf, 0, &n))
7181 		return -EINVAL;
7182 	if (n >= 0) {
7183 		if (n > (int)SAM_LUN_AM_FLAT) {
7184 			pr_warn("only LUN address methods 0 and 1 are supported\n");
7185 			return -EINVAL;
7186 		}
7187 		changed = ((int)sdebug_lun_am != n);
7188 		sdebug_lun_am = n;
7189 		if (changed && sdebug_scsi_level >= 5) {	/* >= SPC-3 */
7190 			struct sdebug_host_info *sdhp;
7191 			struct sdebug_dev_info *dp;
7192 
7193 			mutex_lock(&sdebug_host_list_mutex);
7194 			list_for_each_entry(sdhp, &sdebug_host_list, host_list) {
7195 				list_for_each_entry(dp, &sdhp->dev_info_list, dev_list) {
7196 					set_bit(SDEBUG_UA_LUNS_CHANGED, dp->uas_bm);
7197 				}
7198 			}
7199 			mutex_unlock(&sdebug_host_list_mutex);
7200 		}
7201 		return count;
7202 	}
7203 	return -EINVAL;
7204 }
7205 static DRIVER_ATTR_RW(lun_format);
7206 
7207 static ssize_t max_luns_show(struct device_driver *ddp, char *buf)
7208 {
7209 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_max_luns);
7210 }
7211 static ssize_t max_luns_store(struct device_driver *ddp, const char *buf,
7212 			      size_t count)
7213 {
7214 	int n;
7215 	bool changed;
7216 
7217 	if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
7218 		if (n > 256) {
7219 			pr_warn("max_luns can be no more than 256\n");
7220 			return -EINVAL;
7221 		}
7222 		changed = (sdebug_max_luns != n);
7223 		sdebug_max_luns = n;
7224 		sdebug_max_tgts_luns();
7225 		if (changed && (sdebug_scsi_level >= 5)) {	/* >= SPC-3 */
7226 			struct sdebug_host_info *sdhp;
7227 			struct sdebug_dev_info *dp;
7228 
7229 			mutex_lock(&sdebug_host_list_mutex);
7230 			list_for_each_entry(sdhp, &sdebug_host_list,
7231 					    host_list) {
7232 				list_for_each_entry(dp, &sdhp->dev_info_list,
7233 						    dev_list) {
7234 					set_bit(SDEBUG_UA_LUNS_CHANGED,
7235 						dp->uas_bm);
7236 				}
7237 			}
7238 			mutex_unlock(&sdebug_host_list_mutex);
7239 		}
7240 		return count;
7241 	}
7242 	return -EINVAL;
7243 }
7244 static DRIVER_ATTR_RW(max_luns);
7245 
7246 static ssize_t max_queue_show(struct device_driver *ddp, char *buf)
7247 {
7248 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_max_queue);
7249 }
7250 /* N.B. max_queue can be changed while there are queued commands. In flight
7251  * commands beyond the new max_queue will be completed. */
7252 static ssize_t max_queue_store(struct device_driver *ddp, const char *buf,
7253 			       size_t count)
7254 {
7255 	int n;
7256 
7257 	if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n > 0) &&
7258 	    (n <= SDEBUG_CANQUEUE) &&
7259 	    (sdebug_host_max_queue == 0)) {
7260 		mutex_lock(&sdebug_host_list_mutex);
7261 
7262 		/* We may only change sdebug_max_queue when we have no shosts */
7263 		if (list_empty(&sdebug_host_list))
7264 			sdebug_max_queue = n;
7265 		else
7266 			count = -EBUSY;
7267 		mutex_unlock(&sdebug_host_list_mutex);
7268 		return count;
7269 	}
7270 	return -EINVAL;
7271 }
7272 static DRIVER_ATTR_RW(max_queue);
7273 
7274 static ssize_t host_max_queue_show(struct device_driver *ddp, char *buf)
7275 {
7276 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_host_max_queue);
7277 }
7278 
7279 static ssize_t no_rwlock_show(struct device_driver *ddp, char *buf)
7280 {
7281 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_no_rwlock);
7282 }
7283 
7284 static ssize_t no_rwlock_store(struct device_driver *ddp, const char *buf, size_t count)
7285 {
7286 	bool v;
7287 
7288 	if (kstrtobool(buf, &v))
7289 		return -EINVAL;
7290 
7291 	sdebug_no_rwlock = v;
7292 	return count;
7293 }
7294 static DRIVER_ATTR_RW(no_rwlock);
7295 
7296 /*
7297  * Since this is used for .can_queue, and we get the hc_idx tag from the bitmap
7298  * in range [0, sdebug_host_max_queue), we can't change it.
7299  */
7300 static DRIVER_ATTR_RO(host_max_queue);
7301 
7302 static ssize_t no_uld_show(struct device_driver *ddp, char *buf)
7303 {
7304 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_no_uld);
7305 }
7306 static DRIVER_ATTR_RO(no_uld);
7307 
7308 static ssize_t scsi_level_show(struct device_driver *ddp, char *buf)
7309 {
7310 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_scsi_level);
7311 }
7312 static DRIVER_ATTR_RO(scsi_level);
7313 
7314 static ssize_t virtual_gb_show(struct device_driver *ddp, char *buf)
7315 {
7316 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_virtual_gb);
7317 }
7318 static ssize_t virtual_gb_store(struct device_driver *ddp, const char *buf,
7319 				size_t count)
7320 {
7321 	int n;
7322 	bool changed;
7323 
7324 	/* Ignore capacity change for ZBC drives for now */
7325 	if (sdeb_zbc_in_use)
7326 		return -ENOTSUPP;
7327 
7328 	if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
7329 		changed = (sdebug_virtual_gb != n);
7330 		sdebug_virtual_gb = n;
7331 		sdebug_capacity = get_sdebug_capacity();
7332 		if (changed) {
7333 			struct sdebug_host_info *sdhp;
7334 			struct sdebug_dev_info *dp;
7335 
7336 			mutex_lock(&sdebug_host_list_mutex);
7337 			list_for_each_entry(sdhp, &sdebug_host_list,
7338 					    host_list) {
7339 				list_for_each_entry(dp, &sdhp->dev_info_list,
7340 						    dev_list) {
7341 					set_bit(SDEBUG_UA_CAPACITY_CHANGED,
7342 						dp->uas_bm);
7343 				}
7344 			}
7345 			mutex_unlock(&sdebug_host_list_mutex);
7346 		}
7347 		return count;
7348 	}
7349 	return -EINVAL;
7350 }
7351 static DRIVER_ATTR_RW(virtual_gb);
7352 
7353 static ssize_t add_host_show(struct device_driver *ddp, char *buf)
7354 {
7355 	/* absolute number of hosts currently active is what is shown */
7356 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_num_hosts);
7357 }
7358 
7359 static ssize_t add_host_store(struct device_driver *ddp, const char *buf,
7360 			      size_t count)
7361 {
7362 	bool found;
7363 	unsigned long idx;
7364 	struct sdeb_store_info *sip;
7365 	bool want_phs = (sdebug_fake_rw == 0) && sdebug_per_host_store;
7366 	int delta_hosts;
7367 
7368 	if (sscanf(buf, "%d", &delta_hosts) != 1)
7369 		return -EINVAL;
7370 	if (delta_hosts > 0) {
7371 		do {
7372 			found = false;
7373 			if (want_phs) {
7374 				xa_for_each_marked(per_store_ap, idx, sip,
7375 						   SDEB_XA_NOT_IN_USE) {
7376 					sdeb_most_recent_idx = (int)idx;
7377 					found = true;
7378 					break;
7379 				}
7380 				if (found)	/* re-use case */
7381 					sdebug_add_host_helper((int)idx);
7382 				else
7383 					sdebug_do_add_host(true);
7384 			} else {
7385 				sdebug_do_add_host(false);
7386 			}
7387 		} while (--delta_hosts);
7388 	} else if (delta_hosts < 0) {
7389 		do {
7390 			sdebug_do_remove_host(false);
7391 		} while (++delta_hosts);
7392 	}
7393 	return count;
7394 }
7395 static DRIVER_ATTR_RW(add_host);
7396 
7397 static ssize_t vpd_use_hostno_show(struct device_driver *ddp, char *buf)
7398 {
7399 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_vpd_use_hostno);
7400 }
7401 static ssize_t vpd_use_hostno_store(struct device_driver *ddp, const char *buf,
7402 				    size_t count)
7403 {
7404 	int n;
7405 
7406 	if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
7407 		sdebug_vpd_use_hostno = n;
7408 		return count;
7409 	}
7410 	return -EINVAL;
7411 }
7412 static DRIVER_ATTR_RW(vpd_use_hostno);
7413 
7414 static ssize_t statistics_show(struct device_driver *ddp, char *buf)
7415 {
7416 	return scnprintf(buf, PAGE_SIZE, "%d\n", (int)sdebug_statistics);
7417 }
7418 static ssize_t statistics_store(struct device_driver *ddp, const char *buf,
7419 				size_t count)
7420 {
7421 	int n;
7422 
7423 	if ((count > 0) && (sscanf(buf, "%d", &n) == 1) && (n >= 0)) {
7424 		if (n > 0)
7425 			sdebug_statistics = true;
7426 		else {
7427 			clear_queue_stats();
7428 			sdebug_statistics = false;
7429 		}
7430 		return count;
7431 	}
7432 	return -EINVAL;
7433 }
7434 static DRIVER_ATTR_RW(statistics);
7435 
7436 static ssize_t sector_size_show(struct device_driver *ddp, char *buf)
7437 {
7438 	return scnprintf(buf, PAGE_SIZE, "%u\n", sdebug_sector_size);
7439 }
7440 static DRIVER_ATTR_RO(sector_size);
7441 
7442 static ssize_t submit_queues_show(struct device_driver *ddp, char *buf)
7443 {
7444 	return scnprintf(buf, PAGE_SIZE, "%d\n", submit_queues);
7445 }
7446 static DRIVER_ATTR_RO(submit_queues);
7447 
7448 static ssize_t dix_show(struct device_driver *ddp, char *buf)
7449 {
7450 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_dix);
7451 }
7452 static DRIVER_ATTR_RO(dix);
7453 
7454 static ssize_t dif_show(struct device_driver *ddp, char *buf)
7455 {
7456 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_dif);
7457 }
7458 static DRIVER_ATTR_RO(dif);
7459 
7460 static ssize_t guard_show(struct device_driver *ddp, char *buf)
7461 {
7462 	return scnprintf(buf, PAGE_SIZE, "%u\n", sdebug_guard);
7463 }
7464 static DRIVER_ATTR_RO(guard);
7465 
7466 static ssize_t ato_show(struct device_driver *ddp, char *buf)
7467 {
7468 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_ato);
7469 }
7470 static DRIVER_ATTR_RO(ato);
7471 
7472 static ssize_t map_show(struct device_driver *ddp, char *buf)
7473 {
7474 	ssize_t count = 0;
7475 
7476 	if (!scsi_debug_lbp())
7477 		return scnprintf(buf, PAGE_SIZE, "0-%u\n",
7478 				 sdebug_store_sectors);
7479 
7480 	if (sdebug_fake_rw == 0 && !xa_empty(per_store_ap)) {
7481 		struct sdeb_store_info *sip = xa_load(per_store_ap, 0);
7482 
7483 		if (sip)
7484 			count = scnprintf(buf, PAGE_SIZE - 1, "%*pbl",
7485 					  (int)map_size, sip->map_storep);
7486 	}
7487 	buf[count++] = '\n';
7488 	buf[count] = '\0';
7489 
7490 	return count;
7491 }
7492 static DRIVER_ATTR_RO(map);
7493 
7494 static ssize_t random_show(struct device_driver *ddp, char *buf)
7495 {
7496 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_random);
7497 }
7498 
7499 static ssize_t random_store(struct device_driver *ddp, const char *buf,
7500 			    size_t count)
7501 {
7502 	bool v;
7503 
7504 	if (kstrtobool(buf, &v))
7505 		return -EINVAL;
7506 
7507 	sdebug_random = v;
7508 	return count;
7509 }
7510 static DRIVER_ATTR_RW(random);
7511 
7512 static ssize_t removable_show(struct device_driver *ddp, char *buf)
7513 {
7514 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_removable ? 1 : 0);
7515 }
7516 static ssize_t removable_store(struct device_driver *ddp, const char *buf,
7517 			       size_t count)
7518 {
7519 	int n;
7520 
7521 	if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
7522 		sdebug_removable = (n > 0);
7523 		return count;
7524 	}
7525 	return -EINVAL;
7526 }
7527 static DRIVER_ATTR_RW(removable);
7528 
7529 static ssize_t host_lock_show(struct device_driver *ddp, char *buf)
7530 {
7531 	return scnprintf(buf, PAGE_SIZE, "%d\n", !!sdebug_host_lock);
7532 }
7533 /* N.B. sdebug_host_lock does nothing, kept for backward compatibility */
7534 static ssize_t host_lock_store(struct device_driver *ddp, const char *buf,
7535 			       size_t count)
7536 {
7537 	int n;
7538 
7539 	if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
7540 		sdebug_host_lock = (n > 0);
7541 		return count;
7542 	}
7543 	return -EINVAL;
7544 }
7545 static DRIVER_ATTR_RW(host_lock);
7546 
7547 static ssize_t strict_show(struct device_driver *ddp, char *buf)
7548 {
7549 	return scnprintf(buf, PAGE_SIZE, "%d\n", !!sdebug_strict);
7550 }
7551 static ssize_t strict_store(struct device_driver *ddp, const char *buf,
7552 			    size_t count)
7553 {
7554 	int n;
7555 
7556 	if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
7557 		sdebug_strict = (n > 0);
7558 		return count;
7559 	}
7560 	return -EINVAL;
7561 }
7562 static DRIVER_ATTR_RW(strict);
7563 
7564 static ssize_t uuid_ctl_show(struct device_driver *ddp, char *buf)
7565 {
7566 	return scnprintf(buf, PAGE_SIZE, "%d\n", !!sdebug_uuid_ctl);
7567 }
7568 static DRIVER_ATTR_RO(uuid_ctl);
7569 
7570 static ssize_t cdb_len_show(struct device_driver *ddp, char *buf)
7571 {
7572 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdebug_cdb_len);
7573 }
7574 static ssize_t cdb_len_store(struct device_driver *ddp, const char *buf,
7575 			     size_t count)
7576 {
7577 	int ret, n;
7578 
7579 	ret = kstrtoint(buf, 0, &n);
7580 	if (ret)
7581 		return ret;
7582 	sdebug_cdb_len = n;
7583 	all_config_cdb_len();
7584 	return count;
7585 }
7586 static DRIVER_ATTR_RW(cdb_len);
7587 
7588 static const char * const zbc_model_strs_a[] = {
7589 	[BLK_ZONED_NONE] = "none",
7590 	[BLK_ZONED_HA]   = "host-aware",
7591 	[BLK_ZONED_HM]   = "host-managed",
7592 };
7593 
7594 static const char * const zbc_model_strs_b[] = {
7595 	[BLK_ZONED_NONE] = "no",
7596 	[BLK_ZONED_HA]   = "aware",
7597 	[BLK_ZONED_HM]   = "managed",
7598 };
7599 
7600 static const char * const zbc_model_strs_c[] = {
7601 	[BLK_ZONED_NONE] = "0",
7602 	[BLK_ZONED_HA]   = "1",
7603 	[BLK_ZONED_HM]   = "2",
7604 };
7605 
7606 static int sdeb_zbc_model_str(const char *cp)
7607 {
7608 	int res = sysfs_match_string(zbc_model_strs_a, cp);
7609 
7610 	if (res < 0) {
7611 		res = sysfs_match_string(zbc_model_strs_b, cp);
7612 		if (res < 0) {
7613 			res = sysfs_match_string(zbc_model_strs_c, cp);
7614 			if (res < 0)
7615 				return -EINVAL;
7616 		}
7617 	}
7618 	return res;
7619 }
7620 
7621 static ssize_t zbc_show(struct device_driver *ddp, char *buf)
7622 {
7623 	return scnprintf(buf, PAGE_SIZE, "%s\n",
7624 			 zbc_model_strs_a[sdeb_zbc_model]);
7625 }
7626 static DRIVER_ATTR_RO(zbc);
7627 
7628 static ssize_t tur_ms_to_ready_show(struct device_driver *ddp, char *buf)
7629 {
7630 	return scnprintf(buf, PAGE_SIZE, "%d\n", sdeb_tur_ms_to_ready);
7631 }
7632 static DRIVER_ATTR_RO(tur_ms_to_ready);
7633 
7634 static ssize_t group_number_stats_show(struct device_driver *ddp, char *buf)
7635 {
7636 	char *p = buf, *end = buf + PAGE_SIZE;
7637 	int i;
7638 
7639 	for (i = 0; i < ARRAY_SIZE(writes_by_group_number); i++)
7640 		p += scnprintf(p, end - p, "%d %ld\n", i,
7641 			       atomic_long_read(&writes_by_group_number[i]));
7642 
7643 	return p - buf;
7644 }
7645 
7646 static ssize_t group_number_stats_store(struct device_driver *ddp,
7647 					const char *buf, size_t count)
7648 {
7649 	int i;
7650 
7651 	for (i = 0; i < ARRAY_SIZE(writes_by_group_number); i++)
7652 		atomic_long_set(&writes_by_group_number[i], 0);
7653 
7654 	return count;
7655 }
7656 static DRIVER_ATTR_RW(group_number_stats);
7657 
7658 /* Note: The following array creates attribute files in the
7659    /sys/bus/pseudo/drivers/scsi_debug directory. The advantage of these
7660    files (over those found in the /sys/module/scsi_debug/parameters
7661    directory) is that auxiliary actions can be triggered when an attribute
7662    is changed. For example see: add_host_store() above.
7663  */
7664 
7665 static struct attribute *sdebug_drv_attrs[] = {
7666 	&driver_attr_delay.attr,
7667 	&driver_attr_opts.attr,
7668 	&driver_attr_ptype.attr,
7669 	&driver_attr_dsense.attr,
7670 	&driver_attr_fake_rw.attr,
7671 	&driver_attr_host_max_queue.attr,
7672 	&driver_attr_no_lun_0.attr,
7673 	&driver_attr_num_tgts.attr,
7674 	&driver_attr_dev_size_mb.attr,
7675 	&driver_attr_num_parts.attr,
7676 	&driver_attr_every_nth.attr,
7677 	&driver_attr_lun_format.attr,
7678 	&driver_attr_max_luns.attr,
7679 	&driver_attr_max_queue.attr,
7680 	&driver_attr_no_rwlock.attr,
7681 	&driver_attr_no_uld.attr,
7682 	&driver_attr_scsi_level.attr,
7683 	&driver_attr_virtual_gb.attr,
7684 	&driver_attr_add_host.attr,
7685 	&driver_attr_per_host_store.attr,
7686 	&driver_attr_vpd_use_hostno.attr,
7687 	&driver_attr_sector_size.attr,
7688 	&driver_attr_statistics.attr,
7689 	&driver_attr_submit_queues.attr,
7690 	&driver_attr_dix.attr,
7691 	&driver_attr_dif.attr,
7692 	&driver_attr_guard.attr,
7693 	&driver_attr_ato.attr,
7694 	&driver_attr_map.attr,
7695 	&driver_attr_random.attr,
7696 	&driver_attr_removable.attr,
7697 	&driver_attr_host_lock.attr,
7698 	&driver_attr_ndelay.attr,
7699 	&driver_attr_strict.attr,
7700 	&driver_attr_uuid_ctl.attr,
7701 	&driver_attr_cdb_len.attr,
7702 	&driver_attr_tur_ms_to_ready.attr,
7703 	&driver_attr_zbc.attr,
7704 	&driver_attr_group_number_stats.attr,
7705 	NULL,
7706 };
7707 ATTRIBUTE_GROUPS(sdebug_drv);
7708 
7709 static struct device *pseudo_primary;
7710 
7711 static int __init scsi_debug_init(void)
7712 {
7713 	bool want_store = (sdebug_fake_rw == 0);
7714 	unsigned long sz;
7715 	int k, ret, hosts_to_add;
7716 	int idx = -1;
7717 
7718 	if (sdebug_ndelay >= 1000 * 1000 * 1000) {
7719 		pr_warn("ndelay must be less than 1 second, ignored\n");
7720 		sdebug_ndelay = 0;
7721 	} else if (sdebug_ndelay > 0)
7722 		sdebug_jdelay = JDELAY_OVERRIDDEN;
7723 
7724 	switch (sdebug_sector_size) {
7725 	case  512:
7726 	case 1024:
7727 	case 2048:
7728 	case 4096:
7729 		break;
7730 	default:
7731 		pr_err("invalid sector_size %d\n", sdebug_sector_size);
7732 		return -EINVAL;
7733 	}
7734 
7735 	switch (sdebug_dif) {
7736 	case T10_PI_TYPE0_PROTECTION:
7737 		break;
7738 	case T10_PI_TYPE1_PROTECTION:
7739 	case T10_PI_TYPE2_PROTECTION:
7740 	case T10_PI_TYPE3_PROTECTION:
7741 		have_dif_prot = true;
7742 		break;
7743 
7744 	default:
7745 		pr_err("dif must be 0, 1, 2 or 3\n");
7746 		return -EINVAL;
7747 	}
7748 
7749 	if (sdebug_num_tgts < 0) {
7750 		pr_err("num_tgts must be >= 0\n");
7751 		return -EINVAL;
7752 	}
7753 
7754 	if (sdebug_guard > 1) {
7755 		pr_err("guard must be 0 or 1\n");
7756 		return -EINVAL;
7757 	}
7758 
7759 	if (sdebug_ato > 1) {
7760 		pr_err("ato must be 0 or 1\n");
7761 		return -EINVAL;
7762 	}
7763 
7764 	if (sdebug_physblk_exp > 15) {
7765 		pr_err("invalid physblk_exp %u\n", sdebug_physblk_exp);
7766 		return -EINVAL;
7767 	}
7768 
7769 	sdebug_lun_am = sdebug_lun_am_i;
7770 	if (sdebug_lun_am > SAM_LUN_AM_FLAT) {
7771 		pr_warn("Invalid LUN format %u, using default\n", (int)sdebug_lun_am);
7772 		sdebug_lun_am = SAM_LUN_AM_PERIPHERAL;
7773 	}
7774 
7775 	if (sdebug_max_luns > 256) {
7776 		if (sdebug_max_luns > 16384) {
7777 			pr_warn("max_luns can be no more than 16384, use default\n");
7778 			sdebug_max_luns = DEF_MAX_LUNS;
7779 		}
7780 		sdebug_lun_am = SAM_LUN_AM_FLAT;
7781 	}
7782 
7783 	if (sdebug_lowest_aligned > 0x3fff) {
7784 		pr_err("lowest_aligned too big: %u\n", sdebug_lowest_aligned);
7785 		return -EINVAL;
7786 	}
7787 
7788 	if (submit_queues < 1) {
7789 		pr_err("submit_queues must be 1 or more\n");
7790 		return -EINVAL;
7791 	}
7792 
7793 	if ((sdebug_max_queue > SDEBUG_CANQUEUE) || (sdebug_max_queue < 1)) {
7794 		pr_err("max_queue must be in range [1, %d]\n", SDEBUG_CANQUEUE);
7795 		return -EINVAL;
7796 	}
7797 
7798 	if ((sdebug_host_max_queue > SDEBUG_CANQUEUE) ||
7799 	    (sdebug_host_max_queue < 0)) {
7800 		pr_err("host_max_queue must be in range [0 %d]\n",
7801 		       SDEBUG_CANQUEUE);
7802 		return -EINVAL;
7803 	}
7804 
7805 	if (sdebug_host_max_queue &&
7806 	    (sdebug_max_queue != sdebug_host_max_queue)) {
7807 		sdebug_max_queue = sdebug_host_max_queue;
7808 		pr_warn("fixing max submit queue depth to host max queue depth, %d\n",
7809 			sdebug_max_queue);
7810 	}
7811 
7812 	/*
7813 	 * check for host managed zoned block device specified with
7814 	 * ptype=0x14 or zbc=XXX.
7815 	 */
7816 	if (sdebug_ptype == TYPE_ZBC) {
7817 		sdeb_zbc_model = BLK_ZONED_HM;
7818 	} else if (sdeb_zbc_model_s && *sdeb_zbc_model_s) {
7819 		k = sdeb_zbc_model_str(sdeb_zbc_model_s);
7820 		if (k < 0)
7821 			return k;
7822 		sdeb_zbc_model = k;
7823 		switch (sdeb_zbc_model) {
7824 		case BLK_ZONED_NONE:
7825 		case BLK_ZONED_HA:
7826 			sdebug_ptype = TYPE_DISK;
7827 			break;
7828 		case BLK_ZONED_HM:
7829 			sdebug_ptype = TYPE_ZBC;
7830 			break;
7831 		default:
7832 			pr_err("Invalid ZBC model\n");
7833 			return -EINVAL;
7834 		}
7835 	}
7836 	if (sdeb_zbc_model != BLK_ZONED_NONE) {
7837 		sdeb_zbc_in_use = true;
7838 		if (sdebug_dev_size_mb == DEF_DEV_SIZE_PRE_INIT)
7839 			sdebug_dev_size_mb = DEF_ZBC_DEV_SIZE_MB;
7840 	}
7841 
7842 	if (sdebug_dev_size_mb == DEF_DEV_SIZE_PRE_INIT)
7843 		sdebug_dev_size_mb = DEF_DEV_SIZE_MB;
7844 	if (sdebug_dev_size_mb < 1)
7845 		sdebug_dev_size_mb = 1;  /* force minimum 1 MB ramdisk */
7846 	sz = (unsigned long)sdebug_dev_size_mb * 1048576;
7847 	sdebug_store_sectors = sz / sdebug_sector_size;
7848 	sdebug_capacity = get_sdebug_capacity();
7849 
7850 	/* play around with geometry, don't waste too much on track 0 */
7851 	sdebug_heads = 8;
7852 	sdebug_sectors_per = 32;
7853 	if (sdebug_dev_size_mb >= 256)
7854 		sdebug_heads = 64;
7855 	else if (sdebug_dev_size_mb >= 16)
7856 		sdebug_heads = 32;
7857 	sdebug_cylinders_per = (unsigned long)sdebug_capacity /
7858 			       (sdebug_sectors_per * sdebug_heads);
7859 	if (sdebug_cylinders_per >= 1024) {
7860 		/* other LLDs do this; implies >= 1GB ram disk ... */
7861 		sdebug_heads = 255;
7862 		sdebug_sectors_per = 63;
7863 		sdebug_cylinders_per = (unsigned long)sdebug_capacity /
7864 			       (sdebug_sectors_per * sdebug_heads);
7865 	}
7866 	if (scsi_debug_lbp()) {
7867 		sdebug_unmap_max_blocks =
7868 			clamp(sdebug_unmap_max_blocks, 0U, 0xffffffffU);
7869 
7870 		sdebug_unmap_max_desc =
7871 			clamp(sdebug_unmap_max_desc, 0U, 256U);
7872 
7873 		sdebug_unmap_granularity =
7874 			clamp(sdebug_unmap_granularity, 1U, 0xffffffffU);
7875 
7876 		if (sdebug_unmap_alignment &&
7877 		    sdebug_unmap_granularity <=
7878 		    sdebug_unmap_alignment) {
7879 			pr_err("ERR: unmap_granularity <= unmap_alignment\n");
7880 			return -EINVAL;
7881 		}
7882 	}
7883 
7884 	xa_init_flags(per_store_ap, XA_FLAGS_ALLOC | XA_FLAGS_LOCK_IRQ);
7885 	if (want_store) {
7886 		idx = sdebug_add_store();
7887 		if (idx < 0)
7888 			return idx;
7889 	}
7890 
7891 	pseudo_primary = root_device_register("pseudo_0");
7892 	if (IS_ERR(pseudo_primary)) {
7893 		pr_warn("root_device_register() error\n");
7894 		ret = PTR_ERR(pseudo_primary);
7895 		goto free_vm;
7896 	}
7897 	ret = bus_register(&pseudo_lld_bus);
7898 	if (ret < 0) {
7899 		pr_warn("bus_register error: %d\n", ret);
7900 		goto dev_unreg;
7901 	}
7902 	ret = driver_register(&sdebug_driverfs_driver);
7903 	if (ret < 0) {
7904 		pr_warn("driver_register error: %d\n", ret);
7905 		goto bus_unreg;
7906 	}
7907 
7908 	hosts_to_add = sdebug_add_host;
7909 	sdebug_add_host = 0;
7910 
7911 	queued_cmd_cache = KMEM_CACHE(sdebug_queued_cmd, SLAB_HWCACHE_ALIGN);
7912 	if (!queued_cmd_cache) {
7913 		ret = -ENOMEM;
7914 		goto driver_unreg;
7915 	}
7916 
7917 	sdebug_debugfs_root = debugfs_create_dir("scsi_debug", NULL);
7918 	if (IS_ERR_OR_NULL(sdebug_debugfs_root))
7919 		pr_info("%s: failed to create initial debugfs directory\n", __func__);
7920 
7921 	for (k = 0; k < hosts_to_add; k++) {
7922 		if (want_store && k == 0) {
7923 			ret = sdebug_add_host_helper(idx);
7924 			if (ret < 0) {
7925 				pr_err("add_host_helper k=%d, error=%d\n",
7926 				       k, -ret);
7927 				break;
7928 			}
7929 		} else {
7930 			ret = sdebug_do_add_host(want_store &&
7931 						 sdebug_per_host_store);
7932 			if (ret < 0) {
7933 				pr_err("add_host k=%d error=%d\n", k, -ret);
7934 				break;
7935 			}
7936 		}
7937 	}
7938 	if (sdebug_verbose)
7939 		pr_info("built %d host(s)\n", sdebug_num_hosts);
7940 
7941 	return 0;
7942 
7943 driver_unreg:
7944 	driver_unregister(&sdebug_driverfs_driver);
7945 bus_unreg:
7946 	bus_unregister(&pseudo_lld_bus);
7947 dev_unreg:
7948 	root_device_unregister(pseudo_primary);
7949 free_vm:
7950 	sdebug_erase_store(idx, NULL);
7951 	return ret;
7952 }
7953 
7954 static void __exit scsi_debug_exit(void)
7955 {
7956 	int k = sdebug_num_hosts;
7957 
7958 	for (; k; k--)
7959 		sdebug_do_remove_host(true);
7960 	kmem_cache_destroy(queued_cmd_cache);
7961 	driver_unregister(&sdebug_driverfs_driver);
7962 	bus_unregister(&pseudo_lld_bus);
7963 	root_device_unregister(pseudo_primary);
7964 
7965 	sdebug_erase_all_stores(false);
7966 	xa_destroy(per_store_ap);
7967 	debugfs_remove(sdebug_debugfs_root);
7968 }
7969 
7970 device_initcall(scsi_debug_init);
7971 module_exit(scsi_debug_exit);
7972 
7973 static void sdebug_release_adapter(struct device *dev)
7974 {
7975 	struct sdebug_host_info *sdbg_host;
7976 
7977 	sdbg_host = dev_to_sdebug_host(dev);
7978 	kfree(sdbg_host);
7979 }
7980 
7981 /* idx must be valid, if sip is NULL then it will be obtained using idx */
7982 static void sdebug_erase_store(int idx, struct sdeb_store_info *sip)
7983 {
7984 	if (idx < 0)
7985 		return;
7986 	if (!sip) {
7987 		if (xa_empty(per_store_ap))
7988 			return;
7989 		sip = xa_load(per_store_ap, idx);
7990 		if (!sip)
7991 			return;
7992 	}
7993 	vfree(sip->map_storep);
7994 	vfree(sip->dif_storep);
7995 	vfree(sip->storep);
7996 	xa_erase(per_store_ap, idx);
7997 	kfree(sip);
7998 }
7999 
8000 /* Assume apart_from_first==false only in shutdown case. */
8001 static void sdebug_erase_all_stores(bool apart_from_first)
8002 {
8003 	unsigned long idx;
8004 	struct sdeb_store_info *sip = NULL;
8005 
8006 	xa_for_each(per_store_ap, idx, sip) {
8007 		if (apart_from_first)
8008 			apart_from_first = false;
8009 		else
8010 			sdebug_erase_store(idx, sip);
8011 	}
8012 	if (apart_from_first)
8013 		sdeb_most_recent_idx = sdeb_first_idx;
8014 }
8015 
8016 /*
8017  * Returns store xarray new element index (idx) if >=0 else negated errno.
8018  * Limit the number of stores to 65536.
8019  */
8020 static int sdebug_add_store(void)
8021 {
8022 	int res;
8023 	u32 n_idx;
8024 	unsigned long iflags;
8025 	unsigned long sz = (unsigned long)sdebug_dev_size_mb * 1048576;
8026 	struct sdeb_store_info *sip = NULL;
8027 	struct xa_limit xal = { .max = 1 << 16, .min = 0 };
8028 
8029 	sip = kzalloc(sizeof(*sip), GFP_KERNEL);
8030 	if (!sip)
8031 		return -ENOMEM;
8032 
8033 	xa_lock_irqsave(per_store_ap, iflags);
8034 	res = __xa_alloc(per_store_ap, &n_idx, sip, xal, GFP_ATOMIC);
8035 	if (unlikely(res < 0)) {
8036 		xa_unlock_irqrestore(per_store_ap, iflags);
8037 		kfree(sip);
8038 		pr_warn("%s: xa_alloc() errno=%d\n", __func__, -res);
8039 		return res;
8040 	}
8041 	sdeb_most_recent_idx = n_idx;
8042 	if (sdeb_first_idx < 0)
8043 		sdeb_first_idx = n_idx;
8044 	xa_unlock_irqrestore(per_store_ap, iflags);
8045 
8046 	res = -ENOMEM;
8047 	sip->storep = vzalloc(sz);
8048 	if (!sip->storep) {
8049 		pr_err("user data oom\n");
8050 		goto err;
8051 	}
8052 	if (sdebug_num_parts > 0)
8053 		sdebug_build_parts(sip->storep, sz);
8054 
8055 	/* DIF/DIX: what T10 calls Protection Information (PI) */
8056 	if (sdebug_dix) {
8057 		int dif_size;
8058 
8059 		dif_size = sdebug_store_sectors * sizeof(struct t10_pi_tuple);
8060 		sip->dif_storep = vmalloc(dif_size);
8061 
8062 		pr_info("dif_storep %u bytes @ %pK\n", dif_size,
8063 			sip->dif_storep);
8064 
8065 		if (!sip->dif_storep) {
8066 			pr_err("DIX oom\n");
8067 			goto err;
8068 		}
8069 		memset(sip->dif_storep, 0xff, dif_size);
8070 	}
8071 	/* Logical Block Provisioning */
8072 	if (scsi_debug_lbp()) {
8073 		map_size = lba_to_map_index(sdebug_store_sectors - 1) + 1;
8074 		sip->map_storep = vmalloc(array_size(sizeof(long),
8075 						     BITS_TO_LONGS(map_size)));
8076 
8077 		pr_info("%lu provisioning blocks\n", map_size);
8078 
8079 		if (!sip->map_storep) {
8080 			pr_err("LBP map oom\n");
8081 			goto err;
8082 		}
8083 
8084 		bitmap_zero(sip->map_storep, map_size);
8085 
8086 		/* Map first 1KB for partition table */
8087 		if (sdebug_num_parts)
8088 			map_region(sip, 0, 2);
8089 	}
8090 
8091 	rwlock_init(&sip->macc_data_lck);
8092 	rwlock_init(&sip->macc_meta_lck);
8093 	rwlock_init(&sip->macc_sector_lck);
8094 	return (int)n_idx;
8095 err:
8096 	sdebug_erase_store((int)n_idx, sip);
8097 	pr_warn("%s: failed, errno=%d\n", __func__, -res);
8098 	return res;
8099 }
8100 
8101 static int sdebug_add_host_helper(int per_host_idx)
8102 {
8103 	int k, devs_per_host, idx;
8104 	int error = -ENOMEM;
8105 	struct sdebug_host_info *sdbg_host;
8106 	struct sdebug_dev_info *sdbg_devinfo, *tmp;
8107 
8108 	sdbg_host = kzalloc(sizeof(*sdbg_host), GFP_KERNEL);
8109 	if (!sdbg_host)
8110 		return -ENOMEM;
8111 	idx = (per_host_idx < 0) ? sdeb_first_idx : per_host_idx;
8112 	if (xa_get_mark(per_store_ap, idx, SDEB_XA_NOT_IN_USE))
8113 		xa_clear_mark(per_store_ap, idx, SDEB_XA_NOT_IN_USE);
8114 	sdbg_host->si_idx = idx;
8115 
8116 	INIT_LIST_HEAD(&sdbg_host->dev_info_list);
8117 
8118 	devs_per_host = sdebug_num_tgts * sdebug_max_luns;
8119 	for (k = 0; k < devs_per_host; k++) {
8120 		sdbg_devinfo = sdebug_device_create(sdbg_host, GFP_KERNEL);
8121 		if (!sdbg_devinfo)
8122 			goto clean;
8123 	}
8124 
8125 	mutex_lock(&sdebug_host_list_mutex);
8126 	list_add_tail(&sdbg_host->host_list, &sdebug_host_list);
8127 	mutex_unlock(&sdebug_host_list_mutex);
8128 
8129 	sdbg_host->dev.bus = &pseudo_lld_bus;
8130 	sdbg_host->dev.parent = pseudo_primary;
8131 	sdbg_host->dev.release = &sdebug_release_adapter;
8132 	dev_set_name(&sdbg_host->dev, "adapter%d", sdebug_num_hosts);
8133 
8134 	error = device_register(&sdbg_host->dev);
8135 	if (error) {
8136 		mutex_lock(&sdebug_host_list_mutex);
8137 		list_del(&sdbg_host->host_list);
8138 		mutex_unlock(&sdebug_host_list_mutex);
8139 		goto clean;
8140 	}
8141 
8142 	++sdebug_num_hosts;
8143 	return 0;
8144 
8145 clean:
8146 	list_for_each_entry_safe(sdbg_devinfo, tmp, &sdbg_host->dev_info_list,
8147 				 dev_list) {
8148 		list_del(&sdbg_devinfo->dev_list);
8149 		kfree(sdbg_devinfo->zstate);
8150 		kfree(sdbg_devinfo);
8151 	}
8152 	if (sdbg_host->dev.release)
8153 		put_device(&sdbg_host->dev);
8154 	else
8155 		kfree(sdbg_host);
8156 	pr_warn("%s: failed, errno=%d\n", __func__, -error);
8157 	return error;
8158 }
8159 
8160 static int sdebug_do_add_host(bool mk_new_store)
8161 {
8162 	int ph_idx = sdeb_most_recent_idx;
8163 
8164 	if (mk_new_store) {
8165 		ph_idx = sdebug_add_store();
8166 		if (ph_idx < 0)
8167 			return ph_idx;
8168 	}
8169 	return sdebug_add_host_helper(ph_idx);
8170 }
8171 
8172 static void sdebug_do_remove_host(bool the_end)
8173 {
8174 	int idx = -1;
8175 	struct sdebug_host_info *sdbg_host = NULL;
8176 	struct sdebug_host_info *sdbg_host2;
8177 
8178 	mutex_lock(&sdebug_host_list_mutex);
8179 	if (!list_empty(&sdebug_host_list)) {
8180 		sdbg_host = list_entry(sdebug_host_list.prev,
8181 				       struct sdebug_host_info, host_list);
8182 		idx = sdbg_host->si_idx;
8183 	}
8184 	if (!the_end && idx >= 0) {
8185 		bool unique = true;
8186 
8187 		list_for_each_entry(sdbg_host2, &sdebug_host_list, host_list) {
8188 			if (sdbg_host2 == sdbg_host)
8189 				continue;
8190 			if (idx == sdbg_host2->si_idx) {
8191 				unique = false;
8192 				break;
8193 			}
8194 		}
8195 		if (unique) {
8196 			xa_set_mark(per_store_ap, idx, SDEB_XA_NOT_IN_USE);
8197 			if (idx == sdeb_most_recent_idx)
8198 				--sdeb_most_recent_idx;
8199 		}
8200 	}
8201 	if (sdbg_host)
8202 		list_del(&sdbg_host->host_list);
8203 	mutex_unlock(&sdebug_host_list_mutex);
8204 
8205 	if (!sdbg_host)
8206 		return;
8207 
8208 	device_unregister(&sdbg_host->dev);
8209 	--sdebug_num_hosts;
8210 }
8211 
8212 static int sdebug_change_qdepth(struct scsi_device *sdev, int qdepth)
8213 {
8214 	struct sdebug_dev_info *devip = sdev->hostdata;
8215 
8216 	if (!devip)
8217 		return	-ENODEV;
8218 
8219 	mutex_lock(&sdebug_host_list_mutex);
8220 	block_unblock_all_queues(true);
8221 
8222 	if (qdepth > SDEBUG_CANQUEUE) {
8223 		qdepth = SDEBUG_CANQUEUE;
8224 		pr_warn("%s: requested qdepth [%d] exceeds canqueue [%d], trim\n", __func__,
8225 			qdepth, SDEBUG_CANQUEUE);
8226 	}
8227 	if (qdepth < 1)
8228 		qdepth = 1;
8229 	if (qdepth != sdev->queue_depth)
8230 		scsi_change_queue_depth(sdev, qdepth);
8231 
8232 	block_unblock_all_queues(false);
8233 	mutex_unlock(&sdebug_host_list_mutex);
8234 
8235 	if (SDEBUG_OPT_Q_NOISE & sdebug_opts)
8236 		sdev_printk(KERN_INFO, sdev, "%s: qdepth=%d\n", __func__, qdepth);
8237 
8238 	return sdev->queue_depth;
8239 }
8240 
8241 static bool fake_timeout(struct scsi_cmnd *scp)
8242 {
8243 	if (0 == (atomic_read(&sdebug_cmnd_count) % abs(sdebug_every_nth))) {
8244 		if (sdebug_every_nth < -1)
8245 			sdebug_every_nth = -1;
8246 		if (SDEBUG_OPT_TIMEOUT & sdebug_opts)
8247 			return true; /* ignore command causing timeout */
8248 		else if (SDEBUG_OPT_MAC_TIMEOUT & sdebug_opts &&
8249 			 scsi_medium_access_command(scp))
8250 			return true; /* time out reads and writes */
8251 	}
8252 	return false;
8253 }
8254 
8255 /* Response to TUR or media access command when device stopped */
8256 static int resp_not_ready(struct scsi_cmnd *scp, struct sdebug_dev_info *devip)
8257 {
8258 	int stopped_state;
8259 	u64 diff_ns = 0;
8260 	ktime_t now_ts = ktime_get_boottime();
8261 	struct scsi_device *sdp = scp->device;
8262 
8263 	stopped_state = atomic_read(&devip->stopped);
8264 	if (stopped_state == 2) {
8265 		if (ktime_to_ns(now_ts) > ktime_to_ns(devip->create_ts)) {
8266 			diff_ns = ktime_to_ns(ktime_sub(now_ts, devip->create_ts));
8267 			if (diff_ns >= ((u64)sdeb_tur_ms_to_ready * 1000000)) {
8268 				/* tur_ms_to_ready timer extinguished */
8269 				atomic_set(&devip->stopped, 0);
8270 				return 0;
8271 			}
8272 		}
8273 		mk_sense_buffer(scp, NOT_READY, LOGICAL_UNIT_NOT_READY, 0x1);
8274 		if (sdebug_verbose)
8275 			sdev_printk(KERN_INFO, sdp,
8276 				    "%s: Not ready: in process of becoming ready\n", my_name);
8277 		if (scp->cmnd[0] == TEST_UNIT_READY) {
8278 			u64 tur_nanosecs_to_ready = (u64)sdeb_tur_ms_to_ready * 1000000;
8279 
8280 			if (diff_ns <= tur_nanosecs_to_ready)
8281 				diff_ns = tur_nanosecs_to_ready - diff_ns;
8282 			else
8283 				diff_ns = tur_nanosecs_to_ready;
8284 			/* As per 20-061r2 approved for spc6 by T10 on 20200716 */
8285 			do_div(diff_ns, 1000000);	/* diff_ns becomes milliseconds */
8286 			scsi_set_sense_information(scp->sense_buffer, SCSI_SENSE_BUFFERSIZE,
8287 						   diff_ns);
8288 			return check_condition_result;
8289 		}
8290 	}
8291 	mk_sense_buffer(scp, NOT_READY, LOGICAL_UNIT_NOT_READY, 0x2);
8292 	if (sdebug_verbose)
8293 		sdev_printk(KERN_INFO, sdp, "%s: Not ready: initializing command required\n",
8294 			    my_name);
8295 	return check_condition_result;
8296 }
8297 
8298 static void sdebug_map_queues(struct Scsi_Host *shost)
8299 {
8300 	int i, qoff;
8301 
8302 	if (shost->nr_hw_queues == 1)
8303 		return;
8304 
8305 	for (i = 0, qoff = 0; i < HCTX_MAX_TYPES; i++) {
8306 		struct blk_mq_queue_map *map = &shost->tag_set.map[i];
8307 
8308 		map->nr_queues  = 0;
8309 
8310 		if (i == HCTX_TYPE_DEFAULT)
8311 			map->nr_queues = submit_queues - poll_queues;
8312 		else if (i == HCTX_TYPE_POLL)
8313 			map->nr_queues = poll_queues;
8314 
8315 		if (!map->nr_queues) {
8316 			BUG_ON(i == HCTX_TYPE_DEFAULT);
8317 			continue;
8318 		}
8319 
8320 		map->queue_offset = qoff;
8321 		blk_mq_map_queues(map);
8322 
8323 		qoff += map->nr_queues;
8324 	}
8325 }
8326 
8327 struct sdebug_blk_mq_poll_data {
8328 	unsigned int queue_num;
8329 	int *num_entries;
8330 };
8331 
8332 /*
8333  * We don't handle aborted commands here, but it does not seem possible to have
8334  * aborted polled commands from schedule_resp()
8335  */
8336 static bool sdebug_blk_mq_poll_iter(struct request *rq, void *opaque)
8337 {
8338 	struct sdebug_blk_mq_poll_data *data = opaque;
8339 	struct scsi_cmnd *cmd = blk_mq_rq_to_pdu(rq);
8340 	struct sdebug_scsi_cmd *sdsc = scsi_cmd_priv(cmd);
8341 	struct sdebug_defer *sd_dp;
8342 	u32 unique_tag = blk_mq_unique_tag(rq);
8343 	u16 hwq = blk_mq_unique_tag_to_hwq(unique_tag);
8344 	struct sdebug_queued_cmd *sqcp;
8345 	unsigned long flags;
8346 	int queue_num = data->queue_num;
8347 	ktime_t time;
8348 
8349 	/* We're only interested in one queue for this iteration */
8350 	if (hwq != queue_num)
8351 		return true;
8352 
8353 	/* Subsequent checks would fail if this failed, but check anyway */
8354 	if (!test_bit(SCMD_STATE_INFLIGHT, &cmd->state))
8355 		return true;
8356 
8357 	time = ktime_get_boottime();
8358 
8359 	spin_lock_irqsave(&sdsc->lock, flags);
8360 	sqcp = TO_QUEUED_CMD(cmd);
8361 	if (!sqcp) {
8362 		spin_unlock_irqrestore(&sdsc->lock, flags);
8363 		return true;
8364 	}
8365 
8366 	sd_dp = &sqcp->sd_dp;
8367 	if (READ_ONCE(sd_dp->defer_t) != SDEB_DEFER_POLL) {
8368 		spin_unlock_irqrestore(&sdsc->lock, flags);
8369 		return true;
8370 	}
8371 
8372 	if (time < sd_dp->cmpl_ts) {
8373 		spin_unlock_irqrestore(&sdsc->lock, flags);
8374 		return true;
8375 	}
8376 
8377 	ASSIGN_QUEUED_CMD(cmd, NULL);
8378 	spin_unlock_irqrestore(&sdsc->lock, flags);
8379 
8380 	if (sdebug_statistics) {
8381 		atomic_inc(&sdebug_completions);
8382 		if (raw_smp_processor_id() != sd_dp->issuing_cpu)
8383 			atomic_inc(&sdebug_miss_cpus);
8384 	}
8385 
8386 	sdebug_free_queued_cmd(sqcp);
8387 
8388 	scsi_done(cmd); /* callback to mid level */
8389 	(*data->num_entries)++;
8390 	return true;
8391 }
8392 
8393 static int sdebug_blk_mq_poll(struct Scsi_Host *shost, unsigned int queue_num)
8394 {
8395 	int num_entries = 0;
8396 	struct sdebug_blk_mq_poll_data data = {
8397 		.queue_num = queue_num,
8398 		.num_entries = &num_entries,
8399 	};
8400 
8401 	blk_mq_tagset_busy_iter(&shost->tag_set, sdebug_blk_mq_poll_iter,
8402 				&data);
8403 
8404 	if (num_entries > 0)
8405 		atomic_add(num_entries, &sdeb_mq_poll_count);
8406 	return num_entries;
8407 }
8408 
8409 static int sdebug_timeout_cmd(struct scsi_cmnd *cmnd)
8410 {
8411 	struct scsi_device *sdp = cmnd->device;
8412 	struct sdebug_dev_info *devip = (struct sdebug_dev_info *)sdp->hostdata;
8413 	struct sdebug_err_inject *err;
8414 	unsigned char *cmd = cmnd->cmnd;
8415 	int ret = 0;
8416 
8417 	if (devip == NULL)
8418 		return 0;
8419 
8420 	rcu_read_lock();
8421 	list_for_each_entry_rcu(err, &devip->inject_err_list, list) {
8422 		if (err->type == ERR_TMOUT_CMD &&
8423 		    (err->cmd == cmd[0] || err->cmd == 0xff)) {
8424 			ret = !!err->cnt;
8425 			if (err->cnt < 0)
8426 				err->cnt++;
8427 
8428 			rcu_read_unlock();
8429 			return ret;
8430 		}
8431 	}
8432 	rcu_read_unlock();
8433 
8434 	return 0;
8435 }
8436 
8437 static int sdebug_fail_queue_cmd(struct scsi_cmnd *cmnd)
8438 {
8439 	struct scsi_device *sdp = cmnd->device;
8440 	struct sdebug_dev_info *devip = (struct sdebug_dev_info *)sdp->hostdata;
8441 	struct sdebug_err_inject *err;
8442 	unsigned char *cmd = cmnd->cmnd;
8443 	int ret = 0;
8444 
8445 	if (devip == NULL)
8446 		return 0;
8447 
8448 	rcu_read_lock();
8449 	list_for_each_entry_rcu(err, &devip->inject_err_list, list) {
8450 		if (err->type == ERR_FAIL_QUEUE_CMD &&
8451 		    (err->cmd == cmd[0] || err->cmd == 0xff)) {
8452 			ret = err->cnt ? err->queuecmd_ret : 0;
8453 			if (err->cnt < 0)
8454 				err->cnt++;
8455 
8456 			rcu_read_unlock();
8457 			return ret;
8458 		}
8459 	}
8460 	rcu_read_unlock();
8461 
8462 	return 0;
8463 }
8464 
8465 static int sdebug_fail_cmd(struct scsi_cmnd *cmnd, int *retval,
8466 			   struct sdebug_err_inject *info)
8467 {
8468 	struct scsi_device *sdp = cmnd->device;
8469 	struct sdebug_dev_info *devip = (struct sdebug_dev_info *)sdp->hostdata;
8470 	struct sdebug_err_inject *err;
8471 	unsigned char *cmd = cmnd->cmnd;
8472 	int ret = 0;
8473 	int result;
8474 
8475 	if (devip == NULL)
8476 		return 0;
8477 
8478 	rcu_read_lock();
8479 	list_for_each_entry_rcu(err, &devip->inject_err_list, list) {
8480 		if (err->type == ERR_FAIL_CMD &&
8481 		    (err->cmd == cmd[0] || err->cmd == 0xff)) {
8482 			if (!err->cnt) {
8483 				rcu_read_unlock();
8484 				return 0;
8485 			}
8486 
8487 			ret = !!err->cnt;
8488 			rcu_read_unlock();
8489 			goto out_handle;
8490 		}
8491 	}
8492 	rcu_read_unlock();
8493 
8494 	return 0;
8495 
8496 out_handle:
8497 	if (err->cnt < 0)
8498 		err->cnt++;
8499 	mk_sense_buffer(cmnd, err->sense_key, err->asc, err->asq);
8500 	result = err->status_byte | err->host_byte << 16 | err->driver_byte << 24;
8501 	*info = *err;
8502 	*retval = schedule_resp(cmnd, devip, result, NULL, 0, 0);
8503 
8504 	return ret;
8505 }
8506 
8507 static int scsi_debug_queuecommand(struct Scsi_Host *shost,
8508 				   struct scsi_cmnd *scp)
8509 {
8510 	u8 sdeb_i;
8511 	struct scsi_device *sdp = scp->device;
8512 	const struct opcode_info_t *oip;
8513 	const struct opcode_info_t *r_oip;
8514 	struct sdebug_dev_info *devip;
8515 	u8 *cmd = scp->cmnd;
8516 	int (*r_pfp)(struct scsi_cmnd *, struct sdebug_dev_info *);
8517 	int (*pfp)(struct scsi_cmnd *, struct sdebug_dev_info *) = NULL;
8518 	int k, na;
8519 	int errsts = 0;
8520 	u64 lun_index = sdp->lun & 0x3FFF;
8521 	u32 flags;
8522 	u16 sa;
8523 	u8 opcode = cmd[0];
8524 	bool has_wlun_rl;
8525 	bool inject_now;
8526 	int ret = 0;
8527 	struct sdebug_err_inject err;
8528 
8529 	scsi_set_resid(scp, 0);
8530 	if (sdebug_statistics) {
8531 		atomic_inc(&sdebug_cmnd_count);
8532 		inject_now = inject_on_this_cmd();
8533 	} else {
8534 		inject_now = false;
8535 	}
8536 	if (unlikely(sdebug_verbose &&
8537 		     !(SDEBUG_OPT_NO_CDB_NOISE & sdebug_opts))) {
8538 		char b[120];
8539 		int n, len, sb;
8540 
8541 		len = scp->cmd_len;
8542 		sb = (int)sizeof(b);
8543 		if (len > 32)
8544 			strcpy(b, "too long, over 32 bytes");
8545 		else {
8546 			for (k = 0, n = 0; k < len && n < sb; ++k)
8547 				n += scnprintf(b + n, sb - n, "%02x ",
8548 					       (u32)cmd[k]);
8549 		}
8550 		sdev_printk(KERN_INFO, sdp, "%s: tag=%#x, cmd %s\n", my_name,
8551 			    blk_mq_unique_tag(scsi_cmd_to_rq(scp)), b);
8552 	}
8553 	if (unlikely(inject_now && (sdebug_opts & SDEBUG_OPT_HOST_BUSY)))
8554 		return SCSI_MLQUEUE_HOST_BUSY;
8555 	has_wlun_rl = (sdp->lun == SCSI_W_LUN_REPORT_LUNS);
8556 	if (unlikely(lun_index >= sdebug_max_luns && !has_wlun_rl))
8557 		goto err_out;
8558 
8559 	sdeb_i = opcode_ind_arr[opcode];	/* fully mapped */
8560 	oip = &opcode_info_arr[sdeb_i];		/* safe if table consistent */
8561 	devip = (struct sdebug_dev_info *)sdp->hostdata;
8562 	if (unlikely(!devip)) {
8563 		devip = find_build_dev_info(sdp);
8564 		if (NULL == devip)
8565 			goto err_out;
8566 	}
8567 
8568 	if (sdebug_timeout_cmd(scp)) {
8569 		scmd_printk(KERN_INFO, scp, "timeout command 0x%x\n", opcode);
8570 		return 0;
8571 	}
8572 
8573 	ret = sdebug_fail_queue_cmd(scp);
8574 	if (ret) {
8575 		scmd_printk(KERN_INFO, scp, "fail queue command 0x%x with 0x%x\n",
8576 				opcode, ret);
8577 		return ret;
8578 	}
8579 
8580 	if (sdebug_fail_cmd(scp, &ret, &err)) {
8581 		scmd_printk(KERN_INFO, scp,
8582 			"fail command 0x%x with hostbyte=0x%x, "
8583 			"driverbyte=0x%x, statusbyte=0x%x, "
8584 			"sense_key=0x%x, asc=0x%x, asq=0x%x\n",
8585 			opcode, err.host_byte, err.driver_byte,
8586 			err.status_byte, err.sense_key, err.asc, err.asq);
8587 		return ret;
8588 	}
8589 
8590 	if (unlikely(inject_now && !atomic_read(&sdeb_inject_pending)))
8591 		atomic_set(&sdeb_inject_pending, 1);
8592 
8593 	na = oip->num_attached;
8594 	r_pfp = oip->pfp;
8595 	if (na) {	/* multiple commands with this opcode */
8596 		r_oip = oip;
8597 		if (FF_SA & r_oip->flags) {
8598 			if (F_SA_LOW & oip->flags)
8599 				sa = 0x1f & cmd[1];
8600 			else
8601 				sa = get_unaligned_be16(cmd + 8);
8602 			for (k = 0; k <= na; oip = r_oip->arrp + k++) {
8603 				if (opcode == oip->opcode && sa == oip->sa)
8604 					break;
8605 			}
8606 		} else {   /* since no service action only check opcode */
8607 			for (k = 0; k <= na; oip = r_oip->arrp + k++) {
8608 				if (opcode == oip->opcode)
8609 					break;
8610 			}
8611 		}
8612 		if (k > na) {
8613 			if (F_SA_LOW & r_oip->flags)
8614 				mk_sense_invalid_fld(scp, SDEB_IN_CDB, 1, 4);
8615 			else if (F_SA_HIGH & r_oip->flags)
8616 				mk_sense_invalid_fld(scp, SDEB_IN_CDB, 8, 7);
8617 			else
8618 				mk_sense_invalid_opcode(scp);
8619 			goto check_cond;
8620 		}
8621 	}	/* else (when na==0) we assume the oip is a match */
8622 	flags = oip->flags;
8623 	if (unlikely(F_INV_OP & flags)) {
8624 		mk_sense_invalid_opcode(scp);
8625 		goto check_cond;
8626 	}
8627 	if (unlikely(has_wlun_rl && !(F_RL_WLUN_OK & flags))) {
8628 		if (sdebug_verbose)
8629 			sdev_printk(KERN_INFO, sdp, "%s: Opcode 0x%x not%s\n",
8630 				    my_name, opcode, " supported for wlun");
8631 		mk_sense_invalid_opcode(scp);
8632 		goto check_cond;
8633 	}
8634 	if (unlikely(sdebug_strict)) {	/* check cdb against mask */
8635 		u8 rem;
8636 		int j;
8637 
8638 		for (k = 1; k < oip->len_mask[0] && k < 16; ++k) {
8639 			rem = ~oip->len_mask[k] & cmd[k];
8640 			if (rem) {
8641 				for (j = 7; j >= 0; --j, rem <<= 1) {
8642 					if (0x80 & rem)
8643 						break;
8644 				}
8645 				mk_sense_invalid_fld(scp, SDEB_IN_CDB, k, j);
8646 				goto check_cond;
8647 			}
8648 		}
8649 	}
8650 	if (unlikely(!(F_SKIP_UA & flags) &&
8651 		     find_first_bit(devip->uas_bm,
8652 				    SDEBUG_NUM_UAS) != SDEBUG_NUM_UAS)) {
8653 		errsts = make_ua(scp, devip);
8654 		if (errsts)
8655 			goto check_cond;
8656 	}
8657 	if (unlikely(((F_M_ACCESS & flags) || scp->cmnd[0] == TEST_UNIT_READY) &&
8658 		     atomic_read(&devip->stopped))) {
8659 		errsts = resp_not_ready(scp, devip);
8660 		if (errsts)
8661 			goto fini;
8662 	}
8663 	if (sdebug_fake_rw && (F_FAKE_RW & flags))
8664 		goto fini;
8665 	if (unlikely(sdebug_every_nth)) {
8666 		if (fake_timeout(scp))
8667 			return 0;	/* ignore command: make trouble */
8668 	}
8669 	if (likely(oip->pfp))
8670 		pfp = oip->pfp;	/* calls a resp_* function */
8671 	else
8672 		pfp = r_pfp;    /* if leaf function ptr NULL, try the root's */
8673 
8674 fini:
8675 	if (F_DELAY_OVERR & flags)	/* cmds like INQUIRY respond asap */
8676 		return schedule_resp(scp, devip, errsts, pfp, 0, 0);
8677 	else if ((flags & F_LONG_DELAY) && (sdebug_jdelay > 0 ||
8678 					    sdebug_ndelay > 10000)) {
8679 		/*
8680 		 * Skip long delays if ndelay <= 10 microseconds. Otherwise
8681 		 * for Start Stop Unit (SSU) want at least 1 second delay and
8682 		 * if sdebug_jdelay>1 want a long delay of that many seconds.
8683 		 * For Synchronize Cache want 1/20 of SSU's delay.
8684 		 */
8685 		int jdelay = (sdebug_jdelay < 2) ? 1 : sdebug_jdelay;
8686 		int denom = (flags & F_SYNC_DELAY) ? 20 : 1;
8687 
8688 		jdelay = mult_frac(USER_HZ * jdelay, HZ, denom * USER_HZ);
8689 		return schedule_resp(scp, devip, errsts, pfp, jdelay, 0);
8690 	} else
8691 		return schedule_resp(scp, devip, errsts, pfp, sdebug_jdelay,
8692 				     sdebug_ndelay);
8693 check_cond:
8694 	return schedule_resp(scp, devip, check_condition_result, NULL, 0, 0);
8695 err_out:
8696 	return schedule_resp(scp, NULL, DID_NO_CONNECT << 16, NULL, 0, 0);
8697 }
8698 
8699 static int sdebug_init_cmd_priv(struct Scsi_Host *shost, struct scsi_cmnd *cmd)
8700 {
8701 	struct sdebug_scsi_cmd *sdsc = scsi_cmd_priv(cmd);
8702 
8703 	spin_lock_init(&sdsc->lock);
8704 
8705 	return 0;
8706 }
8707 
8708 static struct scsi_host_template sdebug_driver_template = {
8709 	.show_info =		scsi_debug_show_info,
8710 	.write_info =		scsi_debug_write_info,
8711 	.proc_name =		sdebug_proc_name,
8712 	.name =			"SCSI DEBUG",
8713 	.info =			scsi_debug_info,
8714 	.slave_alloc =		scsi_debug_slave_alloc,
8715 	.slave_configure =	scsi_debug_slave_configure,
8716 	.slave_destroy =	scsi_debug_slave_destroy,
8717 	.ioctl =		scsi_debug_ioctl,
8718 	.queuecommand =		scsi_debug_queuecommand,
8719 	.change_queue_depth =	sdebug_change_qdepth,
8720 	.map_queues =		sdebug_map_queues,
8721 	.mq_poll =		sdebug_blk_mq_poll,
8722 	.eh_abort_handler =	scsi_debug_abort,
8723 	.eh_device_reset_handler = scsi_debug_device_reset,
8724 	.eh_target_reset_handler = scsi_debug_target_reset,
8725 	.eh_bus_reset_handler = scsi_debug_bus_reset,
8726 	.eh_host_reset_handler = scsi_debug_host_reset,
8727 	.can_queue =		SDEBUG_CANQUEUE,
8728 	.this_id =		7,
8729 	.sg_tablesize =		SG_MAX_SEGMENTS,
8730 	.cmd_per_lun =		DEF_CMD_PER_LUN,
8731 	.max_sectors =		-1U,
8732 	.max_segment_size =	-1U,
8733 	.module =		THIS_MODULE,
8734 	.track_queue_depth =	1,
8735 	.cmd_size = sizeof(struct sdebug_scsi_cmd),
8736 	.init_cmd_priv = sdebug_init_cmd_priv,
8737 	.target_alloc =		sdebug_target_alloc,
8738 	.target_destroy =	sdebug_target_destroy,
8739 };
8740 
8741 static int sdebug_driver_probe(struct device *dev)
8742 {
8743 	int error = 0;
8744 	struct sdebug_host_info *sdbg_host;
8745 	struct Scsi_Host *hpnt;
8746 	int hprot;
8747 
8748 	sdbg_host = dev_to_sdebug_host(dev);
8749 
8750 	sdebug_driver_template.can_queue = sdebug_max_queue;
8751 	sdebug_driver_template.cmd_per_lun = sdebug_max_queue;
8752 	if (!sdebug_clustering)
8753 		sdebug_driver_template.dma_boundary = PAGE_SIZE - 1;
8754 
8755 	hpnt = scsi_host_alloc(&sdebug_driver_template, 0);
8756 	if (NULL == hpnt) {
8757 		pr_err("scsi_host_alloc failed\n");
8758 		error = -ENODEV;
8759 		return error;
8760 	}
8761 	if (submit_queues > nr_cpu_ids) {
8762 		pr_warn("%s: trim submit_queues (was %d) to nr_cpu_ids=%u\n",
8763 			my_name, submit_queues, nr_cpu_ids);
8764 		submit_queues = nr_cpu_ids;
8765 	}
8766 	/*
8767 	 * Decide whether to tell scsi subsystem that we want mq. The
8768 	 * following should give the same answer for each host.
8769 	 */
8770 	hpnt->nr_hw_queues = submit_queues;
8771 	if (sdebug_host_max_queue)
8772 		hpnt->host_tagset = 1;
8773 
8774 	/* poll queues are possible for nr_hw_queues > 1 */
8775 	if (hpnt->nr_hw_queues == 1 || (poll_queues < 1)) {
8776 		pr_warn("%s: trim poll_queues to 0. poll_q/nr_hw = (%d/%d)\n",
8777 			 my_name, poll_queues, hpnt->nr_hw_queues);
8778 		poll_queues = 0;
8779 	}
8780 
8781 	/*
8782 	 * Poll queues don't need interrupts, but we need at least one I/O queue
8783 	 * left over for non-polled I/O.
8784 	 * If condition not met, trim poll_queues to 1 (just for simplicity).
8785 	 */
8786 	if (poll_queues >= submit_queues) {
8787 		if (submit_queues < 3)
8788 			pr_warn("%s: trim poll_queues to 1\n", my_name);
8789 		else
8790 			pr_warn("%s: trim poll_queues to 1. Perhaps try poll_queues=%d\n",
8791 				my_name, submit_queues - 1);
8792 		poll_queues = 1;
8793 	}
8794 	if (poll_queues)
8795 		hpnt->nr_maps = 3;
8796 
8797 	sdbg_host->shost = hpnt;
8798 	if ((hpnt->this_id >= 0) && (sdebug_num_tgts > hpnt->this_id))
8799 		hpnt->max_id = sdebug_num_tgts + 1;
8800 	else
8801 		hpnt->max_id = sdebug_num_tgts;
8802 	/* = sdebug_max_luns; */
8803 	hpnt->max_lun = SCSI_W_LUN_REPORT_LUNS + 1;
8804 
8805 	hprot = 0;
8806 
8807 	switch (sdebug_dif) {
8808 
8809 	case T10_PI_TYPE1_PROTECTION:
8810 		hprot = SHOST_DIF_TYPE1_PROTECTION;
8811 		if (sdebug_dix)
8812 			hprot |= SHOST_DIX_TYPE1_PROTECTION;
8813 		break;
8814 
8815 	case T10_PI_TYPE2_PROTECTION:
8816 		hprot = SHOST_DIF_TYPE2_PROTECTION;
8817 		if (sdebug_dix)
8818 			hprot |= SHOST_DIX_TYPE2_PROTECTION;
8819 		break;
8820 
8821 	case T10_PI_TYPE3_PROTECTION:
8822 		hprot = SHOST_DIF_TYPE3_PROTECTION;
8823 		if (sdebug_dix)
8824 			hprot |= SHOST_DIX_TYPE3_PROTECTION;
8825 		break;
8826 
8827 	default:
8828 		if (sdebug_dix)
8829 			hprot |= SHOST_DIX_TYPE0_PROTECTION;
8830 		break;
8831 	}
8832 
8833 	scsi_host_set_prot(hpnt, hprot);
8834 
8835 	if (have_dif_prot || sdebug_dix)
8836 		pr_info("host protection%s%s%s%s%s%s%s\n",
8837 			(hprot & SHOST_DIF_TYPE1_PROTECTION) ? " DIF1" : "",
8838 			(hprot & SHOST_DIF_TYPE2_PROTECTION) ? " DIF2" : "",
8839 			(hprot & SHOST_DIF_TYPE3_PROTECTION) ? " DIF3" : "",
8840 			(hprot & SHOST_DIX_TYPE0_PROTECTION) ? " DIX0" : "",
8841 			(hprot & SHOST_DIX_TYPE1_PROTECTION) ? " DIX1" : "",
8842 			(hprot & SHOST_DIX_TYPE2_PROTECTION) ? " DIX2" : "",
8843 			(hprot & SHOST_DIX_TYPE3_PROTECTION) ? " DIX3" : "");
8844 
8845 	if (sdebug_guard == 1)
8846 		scsi_host_set_guard(hpnt, SHOST_DIX_GUARD_IP);
8847 	else
8848 		scsi_host_set_guard(hpnt, SHOST_DIX_GUARD_CRC);
8849 
8850 	sdebug_verbose = !!(SDEBUG_OPT_NOISE & sdebug_opts);
8851 	sdebug_any_injecting_opt = !!(SDEBUG_OPT_ALL_INJECTING & sdebug_opts);
8852 	if (sdebug_every_nth)	/* need stats counters for every_nth */
8853 		sdebug_statistics = true;
8854 	error = scsi_add_host(hpnt, &sdbg_host->dev);
8855 	if (error) {
8856 		pr_err("scsi_add_host failed\n");
8857 		error = -ENODEV;
8858 		scsi_host_put(hpnt);
8859 	} else {
8860 		scsi_scan_host(hpnt);
8861 	}
8862 
8863 	return error;
8864 }
8865 
8866 static void sdebug_driver_remove(struct device *dev)
8867 {
8868 	struct sdebug_host_info *sdbg_host;
8869 	struct sdebug_dev_info *sdbg_devinfo, *tmp;
8870 
8871 	sdbg_host = dev_to_sdebug_host(dev);
8872 
8873 	scsi_remove_host(sdbg_host->shost);
8874 
8875 	list_for_each_entry_safe(sdbg_devinfo, tmp, &sdbg_host->dev_info_list,
8876 				 dev_list) {
8877 		list_del(&sdbg_devinfo->dev_list);
8878 		kfree(sdbg_devinfo->zstate);
8879 		kfree(sdbg_devinfo);
8880 	}
8881 
8882 	scsi_host_put(sdbg_host->shost);
8883 }
8884 
8885 static const struct bus_type pseudo_lld_bus = {
8886 	.name = "pseudo",
8887 	.probe = sdebug_driver_probe,
8888 	.remove = sdebug_driver_remove,
8889 	.drv_groups = sdebug_drv_groups,
8890 };
8891