Merge mulgrave-w:git/linux-2.6
[linux-2.6] / drivers / scsi / scsi_debug.c
1 /*
2  * vvvvvvvvvvvvvvvvvvvvvvv Original vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
3  *  Copyright (C) 1992  Eric Youngdale
4  *  Simulate a host adapter with 2 disks attached.  Do a lot of checking
5  *  to make sure that we are not getting blocks mixed up, and PANIC if
6  *  anything out of the ordinary is seen.
7  * ^^^^^^^^^^^^^^^^^^^^^^^ Original ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
8  *
9  *  This version is more generic, simulating a variable number of disk
10  *  (or disk like devices) sharing a common amount of RAM. To be more
11  *  realistic, the simulated devices have the transport attributes of
12  *  SAS disks.
13  *
14  *
15  *  For documentation see http://www.torque.net/sg/sdebug26.html
16  *
17  *   D. Gilbert (dpg) work for Magneto-Optical device test [20010421]
18  *   dpg: work for devfs large number of disks [20010809]
19  *        forked for lk 2.5 series [20011216, 20020101]
20  *        use vmalloc() more inquiry+mode_sense [20020302]
21  *        add timers for delayed responses [20020721]
22  *   Patrick Mansfield <patmans@us.ibm.com> max_luns+scsi_level [20021031]
23  *   Mike Anderson <andmike@us.ibm.com> sysfs work [20021118]
24  *   dpg: change style of boot options to "scsi_debug.num_tgts=2" and
25  *        module options to "modprobe scsi_debug num_tgts=2" [20021221]
26  */
27
28 #include <linux/module.h>
29
30 #include <linux/kernel.h>
31 #include <linux/sched.h>
32 #include <linux/errno.h>
33 #include <linux/timer.h>
34 #include <linux/types.h>
35 #include <linux/string.h>
36 #include <linux/genhd.h>
37 #include <linux/fs.h>
38 #include <linux/init.h>
39 #include <linux/proc_fs.h>
40 #include <linux/smp_lock.h>
41 #include <linux/vmalloc.h>
42 #include <linux/moduleparam.h>
43
44 #include <linux/blkdev.h>
45 #include "scsi.h"
46 #include <scsi/scsi_host.h>
47 #include <scsi/scsicam.h>
48
49 #include <linux/stat.h>
50
51 #include "scsi_logging.h"
52 #include "scsi_debug.h"
53
54 #define SCSI_DEBUG_VERSION "1.80"
55 static const char * scsi_debug_version_date = "20060914";
56
57 /* Additional Sense Code (ASC) used */
58 #define NO_ADDITIONAL_SENSE 0x0
59 #define LOGICAL_UNIT_NOT_READY 0x4
60 #define UNRECOVERED_READ_ERR 0x11
61 #define PARAMETER_LIST_LENGTH_ERR 0x1a
62 #define INVALID_OPCODE 0x20
63 #define ADDR_OUT_OF_RANGE 0x21
64 #define INVALID_FIELD_IN_CDB 0x24
65 #define INVALID_FIELD_IN_PARAM_LIST 0x26
66 #define POWERON_RESET 0x29
67 #define SAVING_PARAMS_UNSUP 0x39
68 #define THRESHOLD_EXCEEDED 0x5d
69 #define LOW_POWER_COND_ON 0x5e
70
71 #define SDEBUG_TAGGED_QUEUING 0 /* 0 | MSG_SIMPLE_TAG | MSG_ORDERED_TAG */
72
73 /* Default values for driver parameters */
74 #define DEF_NUM_HOST   1
75 #define DEF_NUM_TGTS   1
76 #define DEF_MAX_LUNS   1
77 /* With these defaults, this driver will make 1 host with 1 target
78  * (id 0) containing 1 logical unit (lun 0). That is 1 device.
79  */
80 #define DEF_DELAY   1
81 #define DEF_DEV_SIZE_MB   8
82 #define DEF_EVERY_NTH   0
83 #define DEF_NUM_PARTS   0
84 #define DEF_OPTS   0
85 #define DEF_SCSI_LEVEL   5    /* INQUIRY, byte2 [5->SPC-3] */
86 #define DEF_PTYPE   0
87 #define DEF_D_SENSE   0
88 #define DEF_NO_LUN_0   0
89 #define DEF_VIRTUAL_GB   0
90 #define DEF_FAKE_RW     0
91 #define DEF_VPD_USE_HOSTNO 1
92
93 /* bit mask values for scsi_debug_opts */
94 #define SCSI_DEBUG_OPT_NOISE   1
95 #define SCSI_DEBUG_OPT_MEDIUM_ERR   2
96 #define SCSI_DEBUG_OPT_TIMEOUT   4
97 #define SCSI_DEBUG_OPT_RECOVERED_ERR   8
98 /* When "every_nth" > 0 then modulo "every_nth" commands:
99  *   - a no response is simulated if SCSI_DEBUG_OPT_TIMEOUT is set
100  *   - a RECOVERED_ERROR is simulated on successful read and write
101  *     commands if SCSI_DEBUG_OPT_RECOVERED_ERR is set.
102  *
103  * When "every_nth" < 0 then after "- every_nth" commands:
104  *   - a no response is simulated if SCSI_DEBUG_OPT_TIMEOUT is set
105  *   - a RECOVERED_ERROR is simulated on successful read and write
106  *     commands if SCSI_DEBUG_OPT_RECOVERED_ERR is set.
107  * This will continue until some other action occurs (e.g. the user
108  * writing a new value (other than -1 or 1) to every_nth via sysfs).
109  */
110
111 /* when 1==SCSI_DEBUG_OPT_MEDIUM_ERR, a medium error is simulated at this
112  * sector on read commands: */
113 #define OPT_MEDIUM_ERR_ADDR   0x1234 /* that's sector 4660 in decimal */
114
115 /* If REPORT LUNS has luns >= 256 it can choose "flat space" (value 1)
116  * or "peripheral device" addressing (value 0) */
117 #define SAM2_LUN_ADDRESS_METHOD 0
118 #define SAM2_WLUN_REPORT_LUNS 0xc101
119
120 static int scsi_debug_add_host = DEF_NUM_HOST;
121 static int scsi_debug_delay = DEF_DELAY;
122 static int scsi_debug_dev_size_mb = DEF_DEV_SIZE_MB;
123 static int scsi_debug_every_nth = DEF_EVERY_NTH;
124 static int scsi_debug_max_luns = DEF_MAX_LUNS;
125 static int scsi_debug_num_parts = DEF_NUM_PARTS;
126 static int scsi_debug_num_tgts = DEF_NUM_TGTS; /* targets per host */
127 static int scsi_debug_opts = DEF_OPTS;
128 static int scsi_debug_scsi_level = DEF_SCSI_LEVEL;
129 static int scsi_debug_ptype = DEF_PTYPE; /* SCSI peripheral type (0==disk) */
130 static int scsi_debug_dsense = DEF_D_SENSE;
131 static int scsi_debug_no_lun_0 = DEF_NO_LUN_0;
132 static int scsi_debug_virtual_gb = DEF_VIRTUAL_GB;
133 static int scsi_debug_fake_rw = DEF_FAKE_RW;
134 static int scsi_debug_vpd_use_hostno = DEF_VPD_USE_HOSTNO;
135
136 static int scsi_debug_cmnd_count = 0;
137
138 #define DEV_READONLY(TGT)      (0)
139 #define DEV_REMOVEABLE(TGT)    (0)
140
141 static unsigned int sdebug_store_size;  /* in bytes */
142 static unsigned int sdebug_store_sectors;
143 static sector_t sdebug_capacity;        /* in sectors */
144
145 /* old BIOS stuff, kernel may get rid of them but some mode sense pages
146    may still need them */
147 static int sdebug_heads;                /* heads per disk */
148 static int sdebug_cylinders_per;        /* cylinders per surface */
149 static int sdebug_sectors_per;          /* sectors per cylinder */
150
151 /* default sector size is 512 bytes, 2**9 bytes */
152 #define POW2_SECT_SIZE 9
153 #define SECT_SIZE (1 << POW2_SECT_SIZE)
154 #define SECT_SIZE_PER(TGT) SECT_SIZE
155
156 #define SDEBUG_MAX_PARTS 4
157
158 #define SDEBUG_SENSE_LEN 32
159
160 struct sdebug_dev_info {
161         struct list_head dev_list;
162         unsigned char sense_buff[SDEBUG_SENSE_LEN];     /* weak nexus */
163         unsigned int channel;
164         unsigned int target;
165         unsigned int lun;
166         struct sdebug_host_info *sdbg_host;
167         unsigned int wlun;
168         char reset;
169         char stopped;
170         char used;
171 };
172
173 struct sdebug_host_info {
174         struct list_head host_list;
175         struct Scsi_Host *shost;
176         struct device dev;
177         struct list_head dev_info_list;
178 };
179
180 #define to_sdebug_host(d)       \
181         container_of(d, struct sdebug_host_info, dev)
182
183 static LIST_HEAD(sdebug_host_list);
184 static DEFINE_SPINLOCK(sdebug_host_list_lock);
185
186 typedef void (* done_funct_t) (struct scsi_cmnd *);
187
188 struct sdebug_queued_cmd {
189         int in_use;
190         struct timer_list cmnd_timer;
191         done_funct_t done_funct;
192         struct scsi_cmnd * a_cmnd;
193         int scsi_result;
194 };
195 static struct sdebug_queued_cmd queued_arr[SCSI_DEBUG_CANQUEUE];
196
197 static struct scsi_host_template sdebug_driver_template = {
198         .proc_info =            scsi_debug_proc_info,
199         .name =                 "SCSI DEBUG",
200         .info =                 scsi_debug_info,
201         .slave_alloc =          scsi_debug_slave_alloc,
202         .slave_configure =      scsi_debug_slave_configure,
203         .slave_destroy =        scsi_debug_slave_destroy,
204         .ioctl =                scsi_debug_ioctl,
205         .queuecommand =         scsi_debug_queuecommand,
206         .eh_abort_handler =     scsi_debug_abort,
207         .eh_bus_reset_handler = scsi_debug_bus_reset,
208         .eh_device_reset_handler = scsi_debug_device_reset,
209         .eh_host_reset_handler = scsi_debug_host_reset,
210         .bios_param =           scsi_debug_biosparam,
211         .can_queue =            SCSI_DEBUG_CANQUEUE,
212         .this_id =              7,
213         .sg_tablesize =         256,
214         .cmd_per_lun =          16,
215         .max_sectors =          0xffff,
216         .unchecked_isa_dma =    0,
217         .use_clustering =       ENABLE_CLUSTERING,
218         .module =               THIS_MODULE,
219 };
220
221 static unsigned char * fake_storep;     /* ramdisk storage */
222
223 static int num_aborts = 0;
224 static int num_dev_resets = 0;
225 static int num_bus_resets = 0;
226 static int num_host_resets = 0;
227
228 static DEFINE_SPINLOCK(queued_arr_lock);
229 static DEFINE_RWLOCK(atomic_rw);
230
231 static char sdebug_proc_name[] = "scsi_debug";
232
233 static int sdebug_driver_probe(struct device *);
234 static int sdebug_driver_remove(struct device *);
235 static struct bus_type pseudo_lld_bus;
236
237 static struct device_driver sdebug_driverfs_driver = {
238         .name           = sdebug_proc_name,
239         .bus            = &pseudo_lld_bus,
240 };
241
242 static const int check_condition_result =
243                 (DRIVER_SENSE << 24) | SAM_STAT_CHECK_CONDITION;
244
245 static unsigned char ctrl_m_pg[] = {0xa, 10, 2, 0, 0, 0, 0, 0,
246                                     0, 0, 0x2, 0x4b};
247 static unsigned char iec_m_pg[] = {0x1c, 0xa, 0x08, 0, 0, 0, 0, 0,
248                                    0, 0, 0x0, 0x0};
249
250 /* function declarations */
251 static int resp_inquiry(struct scsi_cmnd * SCpnt, int target,
252                         struct sdebug_dev_info * devip);
253 static int resp_requests(struct scsi_cmnd * SCpnt,
254                          struct sdebug_dev_info * devip);
255 static int resp_start_stop(struct scsi_cmnd * scp,
256                            struct sdebug_dev_info * devip);
257 static int resp_readcap(struct scsi_cmnd * SCpnt,
258                         struct sdebug_dev_info * devip);
259 static int resp_readcap16(struct scsi_cmnd * SCpnt,
260                           struct sdebug_dev_info * devip);
261 static int resp_mode_sense(struct scsi_cmnd * scp, int target,
262                            struct sdebug_dev_info * devip);
263 static int resp_mode_select(struct scsi_cmnd * scp, int mselect6,
264                             struct sdebug_dev_info * devip);
265 static int resp_log_sense(struct scsi_cmnd * scp,
266                           struct sdebug_dev_info * devip);
267 static int resp_read(struct scsi_cmnd * SCpnt, unsigned long long lba,
268                      unsigned int num, struct sdebug_dev_info * devip);
269 static int resp_write(struct scsi_cmnd * SCpnt, unsigned long long lba,
270                       unsigned int num, struct sdebug_dev_info * devip);
271 static int resp_report_luns(struct scsi_cmnd * SCpnt,
272                             struct sdebug_dev_info * devip);
273 static int fill_from_dev_buffer(struct scsi_cmnd * scp, unsigned char * arr,
274                                 int arr_len);
275 static int fetch_to_dev_buffer(struct scsi_cmnd * scp, unsigned char * arr,
276                                int max_arr_len);
277 static void timer_intr_handler(unsigned long);
278 static struct sdebug_dev_info * devInfoReg(struct scsi_device * sdev);
279 static void mk_sense_buffer(struct sdebug_dev_info * devip, int key,
280                             int asc, int asq);
281 static int check_readiness(struct scsi_cmnd * SCpnt, int reset_only,
282                            struct sdebug_dev_info * devip);
283 static int schedule_resp(struct scsi_cmnd * cmnd,
284                          struct sdebug_dev_info * devip,
285                          done_funct_t done, int scsi_result, int delta_jiff);
286 static void __init sdebug_build_parts(unsigned char * ramp);
287 static void __init init_all_queued(void);
288 static void stop_all_queued(void);
289 static int stop_queued_cmnd(struct scsi_cmnd * cmnd);
290 static int inquiry_evpd_83(unsigned char * arr, int target_dev_id,
291                            int dev_id_num, const char * dev_id_str,
292                            int dev_id_str_len);
293 static int inquiry_evpd_88(unsigned char * arr, int target_dev_id);
294 static int do_create_driverfs_files(void);
295 static void do_remove_driverfs_files(void);
296
297 static int sdebug_add_adapter(void);
298 static void sdebug_remove_adapter(void);
299 static void sdebug_max_tgts_luns(void);
300
301 static struct device pseudo_primary;
302 static struct bus_type pseudo_lld_bus;
303
304
305 static
306 int scsi_debug_queuecommand(struct scsi_cmnd * SCpnt, done_funct_t done)
307 {
308         unsigned char *cmd = (unsigned char *) SCpnt->cmnd;
309         int len, k, j;
310         unsigned int num;
311         unsigned long long lba;
312         int errsts = 0;
313         int target = SCpnt->device->id;
314         struct sdebug_dev_info * devip = NULL;
315         int inj_recovered = 0;
316         int delay_override = 0;
317
318         if (done == NULL)
319                 return 0;       /* assume mid level reprocessing command */
320
321         SCpnt->resid = 0;
322         if ((SCSI_DEBUG_OPT_NOISE & scsi_debug_opts) && cmd) {
323                 printk(KERN_INFO "scsi_debug: cmd ");
324                 for (k = 0, len = SCpnt->cmd_len; k < len; ++k)
325                         printk("%02x ", (int)cmd[k]);
326                 printk("\n");
327         }
328         if(target == sdebug_driver_template.this_id) {
329                 printk(KERN_INFO "scsi_debug: initiator's id used as "
330                        "target!\n");
331                 return schedule_resp(SCpnt, NULL, done,
332                                      DID_NO_CONNECT << 16, 0);
333         }
334
335         if ((SCpnt->device->lun >= scsi_debug_max_luns) &&
336             (SCpnt->device->lun != SAM2_WLUN_REPORT_LUNS))
337                 return schedule_resp(SCpnt, NULL, done,
338                                      DID_NO_CONNECT << 16, 0);
339         devip = devInfoReg(SCpnt->device);
340         if (NULL == devip)
341                 return schedule_resp(SCpnt, NULL, done,
342                                      DID_NO_CONNECT << 16, 0);
343
344         if ((scsi_debug_every_nth != 0) &&
345             (++scsi_debug_cmnd_count >= abs(scsi_debug_every_nth))) {
346                 scsi_debug_cmnd_count = 0;
347                 if (scsi_debug_every_nth < -1)
348                         scsi_debug_every_nth = -1;
349                 if (SCSI_DEBUG_OPT_TIMEOUT & scsi_debug_opts)
350                         return 0; /* ignore command causing timeout */
351                 else if (SCSI_DEBUG_OPT_RECOVERED_ERR & scsi_debug_opts)
352                         inj_recovered = 1; /* to reads and writes below */
353         }
354
355         if (devip->wlun) {
356                 switch (*cmd) {
357                 case INQUIRY:
358                 case REQUEST_SENSE:
359                 case TEST_UNIT_READY:
360                 case REPORT_LUNS:
361                         break;  /* only allowable wlun commands */
362                 default:
363                         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
364                                 printk(KERN_INFO "scsi_debug: Opcode: 0x%x "
365                                        "not supported for wlun\n", *cmd);
366                         mk_sense_buffer(devip, ILLEGAL_REQUEST,
367                                         INVALID_OPCODE, 0);
368                         errsts = check_condition_result;
369                         return schedule_resp(SCpnt, devip, done, errsts,
370                                              0);
371                 }
372         }
373
374         switch (*cmd) {
375         case INQUIRY:     /* mandatory, ignore unit attention */
376                 delay_override = 1;
377                 errsts = resp_inquiry(SCpnt, target, devip);
378                 break;
379         case REQUEST_SENSE:     /* mandatory, ignore unit attention */
380                 delay_override = 1;
381                 errsts = resp_requests(SCpnt, devip);
382                 break;
383         case REZERO_UNIT:       /* actually this is REWIND for SSC */
384         case START_STOP:
385                 errsts = resp_start_stop(SCpnt, devip);
386                 break;
387         case ALLOW_MEDIUM_REMOVAL:
388                 if ((errsts = check_readiness(SCpnt, 1, devip)))
389                         break;
390                 if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
391                         printk(KERN_INFO "scsi_debug: Medium removal %s\n",
392                                 cmd[4] ? "inhibited" : "enabled");
393                 break;
394         case SEND_DIAGNOSTIC:     /* mandatory */
395                 errsts = check_readiness(SCpnt, 1, devip);
396                 break;
397         case TEST_UNIT_READY:     /* mandatory */
398                 delay_override = 1;
399                 errsts = check_readiness(SCpnt, 0, devip);
400                 break;
401         case RESERVE:
402                 errsts = check_readiness(SCpnt, 1, devip);
403                 break;
404         case RESERVE_10:
405                 errsts = check_readiness(SCpnt, 1, devip);
406                 break;
407         case RELEASE:
408                 errsts = check_readiness(SCpnt, 1, devip);
409                 break;
410         case RELEASE_10:
411                 errsts = check_readiness(SCpnt, 1, devip);
412                 break;
413         case READ_CAPACITY:
414                 errsts = resp_readcap(SCpnt, devip);
415                 break;
416         case SERVICE_ACTION_IN:
417                 if (SAI_READ_CAPACITY_16 != cmd[1]) {
418                         mk_sense_buffer(devip, ILLEGAL_REQUEST,
419                                         INVALID_OPCODE, 0);
420                         errsts = check_condition_result;
421                         break;
422                 }
423                 errsts = resp_readcap16(SCpnt, devip);
424                 break;
425         case READ_16:
426         case READ_12:
427         case READ_10:
428         case READ_6:
429                 if ((errsts = check_readiness(SCpnt, 0, devip)))
430                         break;
431                 if (scsi_debug_fake_rw)
432                         break;
433                 if ((*cmd) == READ_16) {
434                         for (lba = 0, j = 0; j < 8; ++j) {
435                                 if (j > 0)
436                                         lba <<= 8;
437                                 lba += cmd[2 + j];
438                         }
439                         num = cmd[13] + (cmd[12] << 8) +
440                                 (cmd[11] << 16) + (cmd[10] << 24);
441                 } else if ((*cmd) == READ_12) {
442                         lba = cmd[5] + (cmd[4] << 8) +
443                                 (cmd[3] << 16) + (cmd[2] << 24);
444                         num = cmd[9] + (cmd[8] << 8) +
445                                 (cmd[7] << 16) + (cmd[6] << 24);
446                 } else if ((*cmd) == READ_10) {
447                         lba = cmd[5] + (cmd[4] << 8) +
448                                 (cmd[3] << 16) + (cmd[2] << 24);
449                         num = cmd[8] + (cmd[7] << 8);
450                 } else {        /* READ (6) */
451                         lba = cmd[3] + (cmd[2] << 8) +
452                                 ((cmd[1] & 0x1f) << 16);
453                         num = (0 == cmd[4]) ? 256 : cmd[4];
454                 }
455                 errsts = resp_read(SCpnt, lba, num, devip);
456                 if (inj_recovered && (0 == errsts)) {
457                         mk_sense_buffer(devip, RECOVERED_ERROR,
458                                         THRESHOLD_EXCEEDED, 0);
459                         errsts = check_condition_result;
460                 }
461                 break;
462         case REPORT_LUNS:       /* mandatory, ignore unit attention */
463                 delay_override = 1;
464                 errsts = resp_report_luns(SCpnt, devip);
465                 break;
466         case VERIFY:            /* 10 byte SBC-2 command */
467                 errsts = check_readiness(SCpnt, 0, devip);
468                 break;
469         case WRITE_16:
470         case WRITE_12:
471         case WRITE_10:
472         case WRITE_6:
473                 if ((errsts = check_readiness(SCpnt, 0, devip)))
474                         break;
475                 if (scsi_debug_fake_rw)
476                         break;
477                 if ((*cmd) == WRITE_16) {
478                         for (lba = 0, j = 0; j < 8; ++j) {
479                                 if (j > 0)
480                                         lba <<= 8;
481                                 lba += cmd[2 + j];
482                         }
483                         num = cmd[13] + (cmd[12] << 8) +
484                                 (cmd[11] << 16) + (cmd[10] << 24);
485                 } else if ((*cmd) == WRITE_12) {
486                         lba = cmd[5] + (cmd[4] << 8) +
487                                 (cmd[3] << 16) + (cmd[2] << 24);
488                         num = cmd[9] + (cmd[8] << 8) +
489                                 (cmd[7] << 16) + (cmd[6] << 24);
490                 } else if ((*cmd) == WRITE_10) {
491                         lba = cmd[5] + (cmd[4] << 8) +
492                                 (cmd[3] << 16) + (cmd[2] << 24);
493                         num = cmd[8] + (cmd[7] << 8);
494                 } else {        /* WRITE (6) */
495                         lba = cmd[3] + (cmd[2] << 8) +
496                                 ((cmd[1] & 0x1f) << 16);
497                         num = (0 == cmd[4]) ? 256 : cmd[4];
498                 }
499                 errsts = resp_write(SCpnt, lba, num, devip);
500                 if (inj_recovered && (0 == errsts)) {
501                         mk_sense_buffer(devip, RECOVERED_ERROR,
502                                         THRESHOLD_EXCEEDED, 0);
503                         errsts = check_condition_result;
504                 }
505                 break;
506         case MODE_SENSE:
507         case MODE_SENSE_10:
508                 errsts = resp_mode_sense(SCpnt, target, devip);
509                 break;
510         case MODE_SELECT:
511                 errsts = resp_mode_select(SCpnt, 1, devip);
512                 break;
513         case MODE_SELECT_10:
514                 errsts = resp_mode_select(SCpnt, 0, devip);
515                 break;
516         case LOG_SENSE:
517                 errsts = resp_log_sense(SCpnt, devip);
518                 break;
519         case SYNCHRONIZE_CACHE:
520                 delay_override = 1;
521                 errsts = check_readiness(SCpnt, 0, devip);
522                 break;
523         default:
524                 if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
525                         printk(KERN_INFO "scsi_debug: Opcode: 0x%x not "
526                                "supported\n", *cmd);
527                 if ((errsts = check_readiness(SCpnt, 1, devip)))
528                         break;  /* Unit attention takes precedence */
529                 mk_sense_buffer(devip, ILLEGAL_REQUEST, INVALID_OPCODE, 0);
530                 errsts = check_condition_result;
531                 break;
532         }
533         return schedule_resp(SCpnt, devip, done, errsts,
534                              (delay_override ? 0 : scsi_debug_delay));
535 }
536
537 static int scsi_debug_ioctl(struct scsi_device *dev, int cmd, void __user *arg)
538 {
539         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts) {
540                 printk(KERN_INFO "scsi_debug: ioctl: cmd=0x%x\n", cmd);
541         }
542         return -EINVAL;
543         /* return -ENOTTY; // correct return but upsets fdisk */
544 }
545
546 static int check_readiness(struct scsi_cmnd * SCpnt, int reset_only,
547                            struct sdebug_dev_info * devip)
548 {
549         if (devip->reset) {
550                 if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
551                         printk(KERN_INFO "scsi_debug: Reporting Unit "
552                                "attention: power on reset\n");
553                 devip->reset = 0;
554                 mk_sense_buffer(devip, UNIT_ATTENTION, POWERON_RESET, 0);
555                 return check_condition_result;
556         }
557         if ((0 == reset_only) && devip->stopped) {
558                 if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
559                         printk(KERN_INFO "scsi_debug: Reporting Not "
560                                "ready: initializing command required\n");
561                 mk_sense_buffer(devip, NOT_READY, LOGICAL_UNIT_NOT_READY,
562                                 0x2);
563                 return check_condition_result;
564         }
565         return 0;
566 }
567
568 /* Returns 0 if ok else (DID_ERROR << 16). Sets scp->resid . */
569 static int fill_from_dev_buffer(struct scsi_cmnd * scp, unsigned char * arr,
570                                 int arr_len)
571 {
572         int k, req_len, act_len, len, active;
573         void * kaddr;
574         void * kaddr_off;
575         struct scatterlist * sgpnt;
576
577         if (0 == scp->request_bufflen)
578                 return 0;
579         if (NULL == scp->request_buffer)
580                 return (DID_ERROR << 16);
581         if (! ((scp->sc_data_direction == DMA_BIDIRECTIONAL) ||
582               (scp->sc_data_direction == DMA_FROM_DEVICE)))
583                 return (DID_ERROR << 16);
584         if (0 == scp->use_sg) {
585                 req_len = scp->request_bufflen;
586                 act_len = (req_len < arr_len) ? req_len : arr_len;
587                 memcpy(scp->request_buffer, arr, act_len);
588                 if (scp->resid)
589                         scp->resid -= act_len;
590                 else
591                         scp->resid = req_len - act_len;
592                 return 0;
593         }
594         sgpnt = (struct scatterlist *)scp->request_buffer;
595         active = 1;
596         for (k = 0, req_len = 0, act_len = 0; k < scp->use_sg; ++k, ++sgpnt) {
597                 if (active) {
598                         kaddr = (unsigned char *)
599                                 kmap_atomic(sgpnt->page, KM_USER0);
600                         if (NULL == kaddr)
601                                 return (DID_ERROR << 16);
602                         kaddr_off = (unsigned char *)kaddr + sgpnt->offset;
603                         len = sgpnt->length;
604                         if ((req_len + len) > arr_len) {
605                                 active = 0;
606                                 len = arr_len - req_len;
607                         }
608                         memcpy(kaddr_off, arr + req_len, len);
609                         kunmap_atomic(kaddr, KM_USER0);
610                         act_len += len;
611                 }
612                 req_len += sgpnt->length;
613         }
614         if (scp->resid)
615                 scp->resid -= act_len;
616         else
617                 scp->resid = req_len - act_len;
618         return 0;
619 }
620
621 /* Returns number of bytes fetched into 'arr' or -1 if error. */
622 static int fetch_to_dev_buffer(struct scsi_cmnd * scp, unsigned char * arr,
623                                int max_arr_len)
624 {
625         int k, req_len, len, fin;
626         void * kaddr;
627         void * kaddr_off;
628         struct scatterlist * sgpnt;
629
630         if (0 == scp->request_bufflen)
631                 return 0;
632         if (NULL == scp->request_buffer)
633                 return -1;
634         if (! ((scp->sc_data_direction == DMA_BIDIRECTIONAL) ||
635               (scp->sc_data_direction == DMA_TO_DEVICE)))
636                 return -1;
637         if (0 == scp->use_sg) {
638                 req_len = scp->request_bufflen;
639                 len = (req_len < max_arr_len) ? req_len : max_arr_len;
640                 memcpy(arr, scp->request_buffer, len);
641                 return len;
642         }
643         sgpnt = (struct scatterlist *)scp->request_buffer;
644         for (k = 0, req_len = 0, fin = 0; k < scp->use_sg; ++k, ++sgpnt) {
645                 kaddr = (unsigned char *)kmap_atomic(sgpnt->page, KM_USER0);
646                 if (NULL == kaddr)
647                         return -1;
648                 kaddr_off = (unsigned char *)kaddr + sgpnt->offset;
649                 len = sgpnt->length;
650                 if ((req_len + len) > max_arr_len) {
651                         len = max_arr_len - req_len;
652                         fin = 1;
653                 }
654                 memcpy(arr + req_len, kaddr_off, len);
655                 kunmap_atomic(kaddr, KM_USER0);
656                 if (fin)
657                         return req_len + len;
658                 req_len += sgpnt->length;
659         }
660         return req_len;
661 }
662
663
664 static const char * inq_vendor_id = "Linux   ";
665 static const char * inq_product_id = "scsi_debug      ";
666 static const char * inq_product_rev = "0004";
667
668 static int inquiry_evpd_83(unsigned char * arr, int target_dev_id,
669                            int dev_id_num, const char * dev_id_str,
670                            int dev_id_str_len)
671 {
672         int num, port_a;
673         char b[32];
674
675         port_a = target_dev_id + 1;
676         /* T10 vendor identifier field format (faked) */
677         arr[0] = 0x2;   /* ASCII */
678         arr[1] = 0x1;
679         arr[2] = 0x0;
680         memcpy(&arr[4], inq_vendor_id, 8);
681         memcpy(&arr[12], inq_product_id, 16);
682         memcpy(&arr[28], dev_id_str, dev_id_str_len);
683         num = 8 + 16 + dev_id_str_len;
684         arr[3] = num;
685         num += 4;
686         if (dev_id_num >= 0) {
687                 /* NAA-5, Logical unit identifier (binary) */
688                 arr[num++] = 0x1;       /* binary (not necessarily sas) */
689                 arr[num++] = 0x3;       /* PIV=0, lu, naa */
690                 arr[num++] = 0x0;
691                 arr[num++] = 0x8;
692                 arr[num++] = 0x53;  /* naa-5 ieee company id=0x333333 (fake) */
693                 arr[num++] = 0x33;
694                 arr[num++] = 0x33;
695                 arr[num++] = 0x30;
696                 arr[num++] = (dev_id_num >> 24);
697                 arr[num++] = (dev_id_num >> 16) & 0xff;
698                 arr[num++] = (dev_id_num >> 8) & 0xff;
699                 arr[num++] = dev_id_num & 0xff;
700                 /* Target relative port number */
701                 arr[num++] = 0x61;      /* proto=sas, binary */
702                 arr[num++] = 0x94;      /* PIV=1, target port, rel port */
703                 arr[num++] = 0x0;       /* reserved */
704                 arr[num++] = 0x4;       /* length */
705                 arr[num++] = 0x0;       /* reserved */
706                 arr[num++] = 0x0;       /* reserved */
707                 arr[num++] = 0x0;
708                 arr[num++] = 0x1;       /* relative port A */
709         }
710         /* NAA-5, Target port identifier */
711         arr[num++] = 0x61;      /* proto=sas, binary */
712         arr[num++] = 0x93;      /* piv=1, target port, naa */
713         arr[num++] = 0x0;
714         arr[num++] = 0x8;
715         arr[num++] = 0x52;      /* naa-5, company id=0x222222 (fake) */
716         arr[num++] = 0x22;
717         arr[num++] = 0x22;
718         arr[num++] = 0x20;
719         arr[num++] = (port_a >> 24);
720         arr[num++] = (port_a >> 16) & 0xff;
721         arr[num++] = (port_a >> 8) & 0xff;
722         arr[num++] = port_a & 0xff;
723         /* NAA-5, Target device identifier */
724         arr[num++] = 0x61;      /* proto=sas, binary */
725         arr[num++] = 0xa3;      /* piv=1, target device, naa */
726         arr[num++] = 0x0;
727         arr[num++] = 0x8;
728         arr[num++] = 0x52;      /* naa-5, company id=0x222222 (fake) */
729         arr[num++] = 0x22;
730         arr[num++] = 0x22;
731         arr[num++] = 0x20;
732         arr[num++] = (target_dev_id >> 24);
733         arr[num++] = (target_dev_id >> 16) & 0xff;
734         arr[num++] = (target_dev_id >> 8) & 0xff;
735         arr[num++] = target_dev_id & 0xff;
736         /* SCSI name string: Target device identifier */
737         arr[num++] = 0x63;      /* proto=sas, UTF-8 */
738         arr[num++] = 0xa8;      /* piv=1, target device, SCSI name string */
739         arr[num++] = 0x0;
740         arr[num++] = 24;
741         memcpy(arr + num, "naa.52222220", 12);
742         num += 12;
743         snprintf(b, sizeof(b), "%08X", target_dev_id);
744         memcpy(arr + num, b, 8);
745         num += 8;
746         memset(arr + num, 0, 4);
747         num += 4;
748         return num;
749 }
750
751
752 static unsigned char vpd84_data[] = {
753 /* from 4th byte */ 0x22,0x22,0x22,0x0,0xbb,0x0,
754     0x22,0x22,0x22,0x0,0xbb,0x1,
755     0x22,0x22,0x22,0x0,0xbb,0x2,
756 };
757
758 static int inquiry_evpd_84(unsigned char * arr)
759 {
760         memcpy(arr, vpd84_data, sizeof(vpd84_data));
761         return sizeof(vpd84_data);
762 }
763
764 static int inquiry_evpd_85(unsigned char * arr)
765 {
766         int num = 0;
767         const char * na1 = "https://www.kernel.org/config";
768         const char * na2 = "http://www.kernel.org/log";
769         int plen, olen;
770
771         arr[num++] = 0x1;       /* lu, storage config */
772         arr[num++] = 0x0;       /* reserved */
773         arr[num++] = 0x0;
774         olen = strlen(na1);
775         plen = olen + 1;
776         if (plen % 4)
777                 plen = ((plen / 4) + 1) * 4;
778         arr[num++] = plen;      /* length, null termianted, padded */
779         memcpy(arr + num, na1, olen);
780         memset(arr + num + olen, 0, plen - olen);
781         num += plen;
782
783         arr[num++] = 0x4;       /* lu, logging */
784         arr[num++] = 0x0;       /* reserved */
785         arr[num++] = 0x0;
786         olen = strlen(na2);
787         plen = olen + 1;
788         if (plen % 4)
789                 plen = ((plen / 4) + 1) * 4;
790         arr[num++] = plen;      /* length, null terminated, padded */
791         memcpy(arr + num, na2, olen);
792         memset(arr + num + olen, 0, plen - olen);
793         num += plen;
794
795         return num;
796 }
797
798 /* SCSI ports VPD page */
799 static int inquiry_evpd_88(unsigned char * arr, int target_dev_id)
800 {
801         int num = 0;
802         int port_a, port_b;
803
804         port_a = target_dev_id + 1;
805         port_b = port_a + 1;
806         arr[num++] = 0x0;       /* reserved */
807         arr[num++] = 0x0;       /* reserved */
808         arr[num++] = 0x0;
809         arr[num++] = 0x1;       /* relative port 1 (primary) */
810         memset(arr + num, 0, 6);
811         num += 6;
812         arr[num++] = 0x0;
813         arr[num++] = 12;        /* length tp descriptor */
814         /* naa-5 target port identifier (A) */
815         arr[num++] = 0x61;      /* proto=sas, binary */
816         arr[num++] = 0x93;      /* PIV=1, target port, NAA */
817         arr[num++] = 0x0;       /* reserved */
818         arr[num++] = 0x8;       /* length */
819         arr[num++] = 0x52;      /* NAA-5, company_id=0x222222 (fake) */
820         arr[num++] = 0x22;
821         arr[num++] = 0x22;
822         arr[num++] = 0x20;
823         arr[num++] = (port_a >> 24);
824         arr[num++] = (port_a >> 16) & 0xff;
825         arr[num++] = (port_a >> 8) & 0xff;
826         arr[num++] = port_a & 0xff;
827
828         arr[num++] = 0x0;       /* reserved */
829         arr[num++] = 0x0;       /* reserved */
830         arr[num++] = 0x0;
831         arr[num++] = 0x2;       /* relative port 2 (secondary) */
832         memset(arr + num, 0, 6);
833         num += 6;
834         arr[num++] = 0x0;
835         arr[num++] = 12;        /* length tp descriptor */
836         /* naa-5 target port identifier (B) */
837         arr[num++] = 0x61;      /* proto=sas, binary */
838         arr[num++] = 0x93;      /* PIV=1, target port, NAA */
839         arr[num++] = 0x0;       /* reserved */
840         arr[num++] = 0x8;       /* length */
841         arr[num++] = 0x52;      /* NAA-5, company_id=0x222222 (fake) */
842         arr[num++] = 0x22;
843         arr[num++] = 0x22;
844         arr[num++] = 0x20;
845         arr[num++] = (port_b >> 24);
846         arr[num++] = (port_b >> 16) & 0xff;
847         arr[num++] = (port_b >> 8) & 0xff;
848         arr[num++] = port_b & 0xff;
849
850         return num;
851 }
852
853
854 static unsigned char vpd89_data[] = {
855 /* from 4th byte */ 0,0,0,0,
856 'l','i','n','u','x',' ',' ',' ',
857 'S','A','T',' ','s','c','s','i','_','d','e','b','u','g',' ',' ',
858 '1','2','3','4',
859 0x34,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,
860 0xec,0,0,0,
861 0x5a,0xc,0xff,0x3f,0x37,0xc8,0x10,0,0,0,0,0,0x3f,0,0,0,
862 0,0,0,0,0x58,0x58,0x58,0x58,0x58,0x58,0x58,0x58,0x20,0x20,0x20,0x20,
863 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0,0,0,0x40,0x4,0,0x2e,0x33,
864 0x38,0x31,0x20,0x20,0x20,0x20,0x54,0x53,0x38,0x33,0x30,0x30,0x33,0x31,
865 0x53,0x41,
866 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
867 0x20,0x20,
868 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
869 0x10,0x80,
870 0,0,0,0x2f,0,0,0,0x2,0,0x2,0x7,0,0xff,0xff,0x1,0,
871 0x3f,0,0xc1,0xff,0x3e,0,0x10,0x1,0xb0,0xf8,0x50,0x9,0,0,0x7,0,
872 0x3,0,0x78,0,0x78,0,0xf0,0,0x78,0,0,0,0,0,0,0,
873 0,0,0,0,0,0,0,0,0x2,0,0,0,0,0,0,0,
874 0x7e,0,0x1b,0,0x6b,0x34,0x1,0x7d,0x3,0x40,0x69,0x34,0x1,0x3c,0x3,0x40,
875 0x7f,0x40,0,0,0,0,0xfe,0xfe,0,0,0,0,0,0xfe,0,0,
876 0,0,0,0,0,0,0,0,0xb0,0xf8,0x50,0x9,0,0,0,0,
877 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
878 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
879 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
880 0x1,0,0xb0,0xf8,0x50,0x9,0xb0,0xf8,0x50,0x9,0x20,0x20,0x2,0,0xb6,0x42,
881 0,0x80,0x8a,0,0x6,0x3c,0xa,0x3c,0xff,0xff,0xc6,0x7,0,0x1,0,0x8,
882 0xf0,0xf,0,0x10,0x2,0,0x30,0,0,0,0,0,0,0,0x6,0xfe,
883 0,0,0x2,0,0x50,0,0x8a,0,0x4f,0x95,0,0,0x21,0,0xb,0,
884 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
885 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
886 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
887 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
888 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
889 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
890 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
891 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
892 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
893 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
894 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
895 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0xa5,0x51,
896 };
897
898 static int inquiry_evpd_89(unsigned char * arr)
899 {
900         memcpy(arr, vpd89_data, sizeof(vpd89_data));
901         return sizeof(vpd89_data);
902 }
903
904
905 static unsigned char vpdb0_data[] = {
906         /* from 4th byte */ 0,0,0,4,
907         0,0,0x4,0,
908         0,0,0,64,
909 };
910
911 static int inquiry_evpd_b0(unsigned char * arr)
912 {
913         memcpy(arr, vpdb0_data, sizeof(vpdb0_data));
914         if (sdebug_store_sectors > 0x400) {
915                 arr[4] = (sdebug_store_sectors >> 24) & 0xff;
916                 arr[5] = (sdebug_store_sectors >> 16) & 0xff;
917                 arr[6] = (sdebug_store_sectors >> 8) & 0xff;
918                 arr[7] = sdebug_store_sectors & 0xff;
919         }
920         return sizeof(vpdb0_data);
921 }
922
923
924 #define SDEBUG_LONG_INQ_SZ 96
925 #define SDEBUG_MAX_INQ_ARR_SZ 584
926
927 static int resp_inquiry(struct scsi_cmnd * scp, int target,
928                         struct sdebug_dev_info * devip)
929 {
930         unsigned char pq_pdt;
931         unsigned char arr[SDEBUG_MAX_INQ_ARR_SZ];
932         unsigned char *cmd = (unsigned char *)scp->cmnd;
933         int alloc_len, n;
934
935         alloc_len = (cmd[3] << 8) + cmd[4];
936         memset(arr, 0, SDEBUG_MAX_INQ_ARR_SZ);
937         if (devip->wlun)
938                 pq_pdt = 0x1e;  /* present, wlun */
939         else if (scsi_debug_no_lun_0 && (0 == devip->lun))
940                 pq_pdt = 0x7f;  /* not present, no device type */
941         else
942                 pq_pdt = (scsi_debug_ptype & 0x1f);
943         arr[0] = pq_pdt;
944         if (0x2 & cmd[1]) {  /* CMDDT bit set */
945                 mk_sense_buffer(devip, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB,
946                                 0);
947                 return check_condition_result;
948         } else if (0x1 & cmd[1]) {  /* EVPD bit set */
949                 int lu_id_num, target_dev_id, len;
950                 char lu_id_str[6];
951                 int host_no = devip->sdbg_host->shost->host_no;
952                 
953                 if (0 == scsi_debug_vpd_use_hostno)
954                         host_no = 0;
955                 lu_id_num = devip->wlun ? -1 : (((host_no + 1) * 2000) +
956                             (devip->target * 1000) + devip->lun);
957                 target_dev_id = ((host_no + 1) * 2000) +
958                                  (devip->target * 1000) - 3;
959                 len = scnprintf(lu_id_str, 6, "%d", lu_id_num);
960                 if (0 == cmd[2]) { /* supported vital product data pages */
961                         arr[1] = cmd[2];        /*sanity */
962                         n = 4;
963                         arr[n++] = 0x0;   /* this page */
964                         arr[n++] = 0x80;  /* unit serial number */
965                         arr[n++] = 0x83;  /* device identification */
966                         arr[n++] = 0x84;  /* software interface ident. */
967                         arr[n++] = 0x85;  /* management network addresses */
968                         arr[n++] = 0x86;  /* extended inquiry */
969                         arr[n++] = 0x87;  /* mode page policy */
970                         arr[n++] = 0x88;  /* SCSI ports */
971                         arr[n++] = 0x89;  /* ATA information */
972                         arr[n++] = 0xb0;  /* Block limits (SBC) */
973                         arr[3] = n - 4;   /* number of supported VPD pages */
974                 } else if (0x80 == cmd[2]) { /* unit serial number */
975                         arr[1] = cmd[2];        /*sanity */
976                         arr[3] = len;
977                         memcpy(&arr[4], lu_id_str, len);
978                 } else if (0x83 == cmd[2]) { /* device identification */
979                         arr[1] = cmd[2];        /*sanity */
980                         arr[3] = inquiry_evpd_83(&arr[4], target_dev_id,
981                                                  lu_id_num, lu_id_str, len);
982                 } else if (0x84 == cmd[2]) { /* Software interface ident. */
983                         arr[1] = cmd[2];        /*sanity */
984                         arr[3] = inquiry_evpd_84(&arr[4]);
985                 } else if (0x85 == cmd[2]) { /* Management network addresses */
986                         arr[1] = cmd[2];        /*sanity */
987                         arr[3] = inquiry_evpd_85(&arr[4]);
988                 } else if (0x86 == cmd[2]) { /* extended inquiry */
989                         arr[1] = cmd[2];        /*sanity */
990                         arr[3] = 0x3c;  /* number of following entries */
991                         arr[4] = 0x0;   /* no protection stuff */
992                         arr[5] = 0x7;   /* head of q, ordered + simple q's */
993                 } else if (0x87 == cmd[2]) { /* mode page policy */
994                         arr[1] = cmd[2];        /*sanity */
995                         arr[3] = 0x8;   /* number of following entries */
996                         arr[4] = 0x2;   /* disconnect-reconnect mp */
997                         arr[6] = 0x80;  /* mlus, shared */
998                         arr[8] = 0x18;   /* protocol specific lu */
999                         arr[10] = 0x82;  /* mlus, per initiator port */
1000                 } else if (0x88 == cmd[2]) { /* SCSI Ports */
1001                         arr[1] = cmd[2];        /*sanity */
1002                         arr[3] = inquiry_evpd_88(&arr[4], target_dev_id);
1003                 } else if (0x89 == cmd[2]) { /* ATA information */
1004                         arr[1] = cmd[2];        /*sanity */
1005                         n = inquiry_evpd_89(&arr[4]);
1006                         arr[2] = (n >> 8);
1007                         arr[3] = (n & 0xff);
1008                 } else if (0xb0 == cmd[2]) { /* Block limits (SBC) */
1009                         arr[1] = cmd[2];        /*sanity */
1010                         arr[3] = inquiry_evpd_b0(&arr[4]);
1011                 } else {
1012                         /* Illegal request, invalid field in cdb */
1013                         mk_sense_buffer(devip, ILLEGAL_REQUEST,
1014                                         INVALID_FIELD_IN_CDB, 0);
1015                         return check_condition_result;
1016                 }
1017                 len = min(((arr[2] << 8) + arr[3]) + 4, alloc_len);
1018                 return fill_from_dev_buffer(scp, arr,
1019                             min(len, SDEBUG_MAX_INQ_ARR_SZ));
1020         }
1021         /* drops through here for a standard inquiry */
1022         arr[1] = DEV_REMOVEABLE(target) ? 0x80 : 0;     /* Removable disk */
1023         arr[2] = scsi_debug_scsi_level;
1024         arr[3] = 2;    /* response_data_format==2 */
1025         arr[4] = SDEBUG_LONG_INQ_SZ - 5;
1026         arr[6] = 0x10; /* claim: MultiP */
1027         /* arr[6] |= 0x40; ... claim: EncServ (enclosure services) */
1028         arr[7] = 0xa; /* claim: LINKED + CMDQUE */
1029         memcpy(&arr[8], inq_vendor_id, 8);
1030         memcpy(&arr[16], inq_product_id, 16);
1031         memcpy(&arr[32], inq_product_rev, 4);
1032         /* version descriptors (2 bytes each) follow */
1033         arr[58] = 0x0; arr[59] = 0x77; /* SAM-3 ANSI */
1034         arr[60] = 0x3; arr[61] = 0x14;  /* SPC-3 ANSI */
1035         n = 62;
1036         if (scsi_debug_ptype == 0) {
1037                 arr[n++] = 0x3; arr[n++] = 0x3d; /* SBC-2 ANSI */
1038         } else if (scsi_debug_ptype == 1) {
1039                 arr[n++] = 0x3; arr[n++] = 0x60; /* SSC-2 no version */
1040         }
1041         arr[n++] = 0xc; arr[n++] = 0xf;  /* SAS-1.1 rev 10 */
1042         return fill_from_dev_buffer(scp, arr,
1043                             min(alloc_len, SDEBUG_LONG_INQ_SZ));
1044 }
1045
1046 static int resp_requests(struct scsi_cmnd * scp,
1047                          struct sdebug_dev_info * devip)
1048 {
1049         unsigned char * sbuff;
1050         unsigned char *cmd = (unsigned char *)scp->cmnd;
1051         unsigned char arr[SDEBUG_SENSE_LEN];
1052         int want_dsense;
1053         int len = 18;
1054
1055         memset(arr, 0, sizeof(arr));
1056         if (devip->reset == 1)
1057                 mk_sense_buffer(devip, 0, NO_ADDITIONAL_SENSE, 0);
1058         want_dsense = !!(cmd[1] & 1) || scsi_debug_dsense;
1059         sbuff = devip->sense_buff;
1060         if ((iec_m_pg[2] & 0x4) && (6 == (iec_m_pg[3] & 0xf))) {
1061                 if (want_dsense) {
1062                         arr[0] = 0x72;
1063                         arr[1] = 0x0;           /* NO_SENSE in sense_key */
1064                         arr[2] = THRESHOLD_EXCEEDED;
1065                         arr[3] = 0xff;          /* TEST set and MRIE==6 */
1066                 } else {
1067                         arr[0] = 0x70;
1068                         arr[2] = 0x0;           /* NO_SENSE in sense_key */
1069                         arr[7] = 0xa;           /* 18 byte sense buffer */
1070                         arr[12] = THRESHOLD_EXCEEDED;
1071                         arr[13] = 0xff;         /* TEST set and MRIE==6 */
1072                 }
1073         } else {
1074                 memcpy(arr, sbuff, SDEBUG_SENSE_LEN);
1075                 if ((cmd[1] & 1) && (! scsi_debug_dsense)) {
1076                         /* DESC bit set and sense_buff in fixed format */
1077                         memset(arr, 0, sizeof(arr));
1078                         arr[0] = 0x72;
1079                         arr[1] = sbuff[2];     /* sense key */
1080                         arr[2] = sbuff[12];    /* asc */
1081                         arr[3] = sbuff[13];    /* ascq */
1082                         len = 8;
1083                 }
1084         }
1085         mk_sense_buffer(devip, 0, NO_ADDITIONAL_SENSE, 0);
1086         return fill_from_dev_buffer(scp, arr, len);
1087 }
1088
1089 static int resp_start_stop(struct scsi_cmnd * scp,
1090                            struct sdebug_dev_info * devip)
1091 {
1092         unsigned char *cmd = (unsigned char *)scp->cmnd;
1093         int power_cond, errsts, start;
1094
1095         if ((errsts = check_readiness(scp, 1, devip)))
1096                 return errsts;
1097         power_cond = (cmd[4] & 0xf0) >> 4;
1098         if (power_cond) {
1099                 mk_sense_buffer(devip, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB,
1100                                 0);
1101                 return check_condition_result;
1102         }
1103         start = cmd[4] & 1;
1104         if (start == devip->stopped)
1105                 devip->stopped = !start;
1106         return 0;
1107 }
1108
1109 #define SDEBUG_READCAP_ARR_SZ 8
1110 static int resp_readcap(struct scsi_cmnd * scp,
1111                         struct sdebug_dev_info * devip)
1112 {
1113         unsigned char arr[SDEBUG_READCAP_ARR_SZ];
1114         unsigned int capac;
1115         int errsts;
1116
1117         if ((errsts = check_readiness(scp, 1, devip)))
1118                 return errsts;
1119         /* following just in case virtual_gb changed */
1120         if (scsi_debug_virtual_gb > 0) {
1121                 sdebug_capacity = 2048 * 1024;
1122                 sdebug_capacity *= scsi_debug_virtual_gb;
1123         } else
1124                 sdebug_capacity = sdebug_store_sectors;
1125         memset(arr, 0, SDEBUG_READCAP_ARR_SZ);
1126         if (sdebug_capacity < 0xffffffff) {
1127                 capac = (unsigned int)sdebug_capacity - 1;
1128                 arr[0] = (capac >> 24);
1129                 arr[1] = (capac >> 16) & 0xff;
1130                 arr[2] = (capac >> 8) & 0xff;
1131                 arr[3] = capac & 0xff;
1132         } else {
1133                 arr[0] = 0xff;
1134                 arr[1] = 0xff;
1135                 arr[2] = 0xff;
1136                 arr[3] = 0xff;
1137         }
1138         arr[6] = (SECT_SIZE_PER(target) >> 8) & 0xff;
1139         arr[7] = SECT_SIZE_PER(target) & 0xff;
1140         return fill_from_dev_buffer(scp, arr, SDEBUG_READCAP_ARR_SZ);
1141 }
1142
1143 #define SDEBUG_READCAP16_ARR_SZ 32
1144 static int resp_readcap16(struct scsi_cmnd * scp,
1145                           struct sdebug_dev_info * devip)
1146 {
1147         unsigned char *cmd = (unsigned char *)scp->cmnd;
1148         unsigned char arr[SDEBUG_READCAP16_ARR_SZ];
1149         unsigned long long capac;
1150         int errsts, k, alloc_len;
1151
1152         if ((errsts = check_readiness(scp, 1, devip)))
1153                 return errsts;
1154         alloc_len = ((cmd[10] << 24) + (cmd[11] << 16) + (cmd[12] << 8)
1155                      + cmd[13]);
1156         /* following just in case virtual_gb changed */
1157         if (scsi_debug_virtual_gb > 0) {
1158                 sdebug_capacity = 2048 * 1024;
1159                 sdebug_capacity *= scsi_debug_virtual_gb;
1160         } else
1161                 sdebug_capacity = sdebug_store_sectors;
1162         memset(arr, 0, SDEBUG_READCAP16_ARR_SZ);
1163         capac = sdebug_capacity - 1;
1164         for (k = 0; k < 8; ++k, capac >>= 8)
1165                 arr[7 - k] = capac & 0xff;
1166         arr[8] = (SECT_SIZE_PER(target) >> 24) & 0xff;
1167         arr[9] = (SECT_SIZE_PER(target) >> 16) & 0xff;
1168         arr[10] = (SECT_SIZE_PER(target) >> 8) & 0xff;
1169         arr[11] = SECT_SIZE_PER(target) & 0xff;
1170         return fill_from_dev_buffer(scp, arr,
1171                                     min(alloc_len, SDEBUG_READCAP16_ARR_SZ));
1172 }
1173
1174 /* <<Following mode page info copied from ST318451LW>> */
1175
1176 static int resp_err_recov_pg(unsigned char * p, int pcontrol, int target)
1177 {       /* Read-Write Error Recovery page for mode_sense */
1178         unsigned char err_recov_pg[] = {0x1, 0xa, 0xc0, 11, 240, 0, 0, 0,
1179                                         5, 0, 0xff, 0xff};
1180
1181         memcpy(p, err_recov_pg, sizeof(err_recov_pg));
1182         if (1 == pcontrol)
1183                 memset(p + 2, 0, sizeof(err_recov_pg) - 2);
1184         return sizeof(err_recov_pg);
1185 }
1186
1187 static int resp_disconnect_pg(unsigned char * p, int pcontrol, int target)
1188 {       /* Disconnect-Reconnect page for mode_sense */
1189         unsigned char disconnect_pg[] = {0x2, 0xe, 128, 128, 0, 10, 0, 0,
1190                                          0, 0, 0, 0, 0, 0, 0, 0};
1191
1192         memcpy(p, disconnect_pg, sizeof(disconnect_pg));
1193         if (1 == pcontrol)
1194                 memset(p + 2, 0, sizeof(disconnect_pg) - 2);
1195         return sizeof(disconnect_pg);
1196 }
1197
1198 static int resp_format_pg(unsigned char * p, int pcontrol, int target)
1199 {       /* Format device page for mode_sense */
1200         unsigned char format_pg[] = {0x3, 0x16, 0, 0, 0, 0, 0, 0,
1201                                      0, 0, 0, 0, 0, 0, 0, 0,
1202                                      0, 0, 0, 0, 0x40, 0, 0, 0};
1203
1204         memcpy(p, format_pg, sizeof(format_pg));
1205         p[10] = (sdebug_sectors_per >> 8) & 0xff;
1206         p[11] = sdebug_sectors_per & 0xff;
1207         p[12] = (SECT_SIZE >> 8) & 0xff;
1208         p[13] = SECT_SIZE & 0xff;
1209         if (DEV_REMOVEABLE(target))
1210                 p[20] |= 0x20; /* should agree with INQUIRY */
1211         if (1 == pcontrol)
1212                 memset(p + 2, 0, sizeof(format_pg) - 2);
1213         return sizeof(format_pg);
1214 }
1215
1216 static int resp_caching_pg(unsigned char * p, int pcontrol, int target)
1217 {       /* Caching page for mode_sense */
1218         unsigned char caching_pg[] = {0x8, 18, 0x14, 0, 0xff, 0xff, 0, 0,
1219                 0xff, 0xff, 0xff, 0xff, 0x80, 0x14, 0, 0,     0, 0, 0, 0};
1220
1221         memcpy(p, caching_pg, sizeof(caching_pg));
1222         if (1 == pcontrol)
1223                 memset(p + 2, 0, sizeof(caching_pg) - 2);
1224         return sizeof(caching_pg);
1225 }
1226
1227 static int resp_ctrl_m_pg(unsigned char * p, int pcontrol, int target)
1228 {       /* Control mode page for mode_sense */
1229         unsigned char ch_ctrl_m_pg[] = {/* 0xa, 10, */ 0x6, 0, 0, 0, 0, 0,
1230                                         0, 0, 0, 0};
1231         unsigned char d_ctrl_m_pg[] = {0xa, 10, 2, 0, 0, 0, 0, 0,
1232                                      0, 0, 0x2, 0x4b};
1233
1234         if (scsi_debug_dsense)
1235                 ctrl_m_pg[2] |= 0x4;
1236         else
1237                 ctrl_m_pg[2] &= ~0x4;
1238         memcpy(p, ctrl_m_pg, sizeof(ctrl_m_pg));
1239         if (1 == pcontrol)
1240                 memcpy(p + 2, ch_ctrl_m_pg, sizeof(ch_ctrl_m_pg));
1241         else if (2 == pcontrol)
1242                 memcpy(p, d_ctrl_m_pg, sizeof(d_ctrl_m_pg));
1243         return sizeof(ctrl_m_pg);
1244 }
1245
1246
1247 static int resp_iec_m_pg(unsigned char * p, int pcontrol, int target)
1248 {       /* Informational Exceptions control mode page for mode_sense */
1249         unsigned char ch_iec_m_pg[] = {/* 0x1c, 0xa, */ 0x4, 0xf, 0, 0, 0, 0,
1250                                        0, 0, 0x0, 0x0};
1251         unsigned char d_iec_m_pg[] = {0x1c, 0xa, 0x08, 0, 0, 0, 0, 0,
1252                                       0, 0, 0x0, 0x0};
1253
1254         memcpy(p, iec_m_pg, sizeof(iec_m_pg));
1255         if (1 == pcontrol)
1256                 memcpy(p + 2, ch_iec_m_pg, sizeof(ch_iec_m_pg));
1257         else if (2 == pcontrol)
1258                 memcpy(p, d_iec_m_pg, sizeof(d_iec_m_pg));
1259         return sizeof(iec_m_pg);
1260 }
1261
1262 static int resp_sas_sf_m_pg(unsigned char * p, int pcontrol, int target)
1263 {       /* SAS SSP mode page - short format for mode_sense */
1264         unsigned char sas_sf_m_pg[] = {0x19, 0x6,
1265                 0x6, 0x0, 0x7, 0xd0, 0x0, 0x0};
1266
1267         memcpy(p, sas_sf_m_pg, sizeof(sas_sf_m_pg));
1268         if (1 == pcontrol)
1269                 memset(p + 2, 0, sizeof(sas_sf_m_pg) - 2);
1270         return sizeof(sas_sf_m_pg);
1271 }
1272
1273
1274 static int resp_sas_pcd_m_spg(unsigned char * p, int pcontrol, int target,
1275                               int target_dev_id)
1276 {       /* SAS phy control and discover mode page for mode_sense */
1277         unsigned char sas_pcd_m_pg[] = {0x59, 0x1, 0, 0x64, 0, 0x6, 0, 2,
1278                     0, 0, 0, 0, 0x10, 0x9, 0x8, 0x0,
1279                     0x52, 0x22, 0x22, 0x20, 0x0, 0x0, 0x0, 0x0,
1280                     0x51, 0x11, 0x11, 0x10, 0x0, 0x0, 0x0, 0x1,
1281                     0x2, 0, 0, 0, 0, 0, 0, 0,
1282                     0x88, 0x99, 0, 0, 0, 0, 0, 0,
1283                     0, 0, 0, 0, 0, 0, 0, 0,
1284                     0, 1, 0, 0, 0x10, 0x9, 0x8, 0x0,
1285                     0x52, 0x22, 0x22, 0x20, 0x0, 0x0, 0x0, 0x0,
1286                     0x51, 0x11, 0x11, 0x10, 0x0, 0x0, 0x0, 0x1,
1287                     0x3, 0, 0, 0, 0, 0, 0, 0,
1288                     0x88, 0x99, 0, 0, 0, 0, 0, 0,
1289                     0, 0, 0, 0, 0, 0, 0, 0,
1290                 };
1291         int port_a, port_b;
1292
1293         port_a = target_dev_id + 1;
1294         port_b = port_a + 1;
1295         memcpy(p, sas_pcd_m_pg, sizeof(sas_pcd_m_pg));
1296         p[20] = (port_a >> 24);
1297         p[21] = (port_a >> 16) & 0xff;
1298         p[22] = (port_a >> 8) & 0xff;
1299         p[23] = port_a & 0xff;
1300         p[48 + 20] = (port_b >> 24);
1301         p[48 + 21] = (port_b >> 16) & 0xff;
1302         p[48 + 22] = (port_b >> 8) & 0xff;
1303         p[48 + 23] = port_b & 0xff;
1304         if (1 == pcontrol)
1305                 memset(p + 4, 0, sizeof(sas_pcd_m_pg) - 4);
1306         return sizeof(sas_pcd_m_pg);
1307 }
1308
1309 static int resp_sas_sha_m_spg(unsigned char * p, int pcontrol)
1310 {       /* SAS SSP shared protocol specific port mode subpage */
1311         unsigned char sas_sha_m_pg[] = {0x59, 0x2, 0, 0xc, 0, 0x6, 0x10, 0,
1312                     0, 0, 0, 0, 0, 0, 0, 0,
1313                 };
1314
1315         memcpy(p, sas_sha_m_pg, sizeof(sas_sha_m_pg));
1316         if (1 == pcontrol)
1317                 memset(p + 4, 0, sizeof(sas_sha_m_pg) - 4);
1318         return sizeof(sas_sha_m_pg);
1319 }
1320
1321 #define SDEBUG_MAX_MSENSE_SZ 256
1322
1323 static int resp_mode_sense(struct scsi_cmnd * scp, int target,
1324                            struct sdebug_dev_info * devip)
1325 {
1326         unsigned char dbd, llbaa;
1327         int pcontrol, pcode, subpcode, bd_len;
1328         unsigned char dev_spec;
1329         int k, alloc_len, msense_6, offset, len, errsts, target_dev_id;
1330         unsigned char * ap;
1331         unsigned char arr[SDEBUG_MAX_MSENSE_SZ];
1332         unsigned char *cmd = (unsigned char *)scp->cmnd;
1333
1334         if ((errsts = check_readiness(scp, 1, devip)))
1335                 return errsts;
1336         dbd = !!(cmd[1] & 0x8);
1337         pcontrol = (cmd[2] & 0xc0) >> 6;
1338         pcode = cmd[2] & 0x3f;
1339         subpcode = cmd[3];
1340         msense_6 = (MODE_SENSE == cmd[0]);
1341         llbaa = msense_6 ? 0 : !!(cmd[1] & 0x10);
1342         if ((0 == scsi_debug_ptype) && (0 == dbd))
1343                 bd_len = llbaa ? 16 : 8;
1344         else
1345                 bd_len = 0;
1346         alloc_len = msense_6 ? cmd[4] : ((cmd[7] << 8) | cmd[8]);
1347         memset(arr, 0, SDEBUG_MAX_MSENSE_SZ);
1348         if (0x3 == pcontrol) {  /* Saving values not supported */
1349                 mk_sense_buffer(devip, ILLEGAL_REQUEST, SAVING_PARAMS_UNSUP,
1350                                 0);
1351                 return check_condition_result;
1352         }
1353         target_dev_id = ((devip->sdbg_host->shost->host_no + 1) * 2000) +
1354                         (devip->target * 1000) - 3;
1355         /* set DPOFUA bit for disks */
1356         if (0 == scsi_debug_ptype)
1357                 dev_spec = (DEV_READONLY(target) ? 0x80 : 0x0) | 0x10;
1358         else
1359                 dev_spec = 0x0;
1360         if (msense_6) {
1361                 arr[2] = dev_spec;
1362                 arr[3] = bd_len;
1363                 offset = 4;
1364         } else {
1365                 arr[3] = dev_spec;
1366                 if (16 == bd_len)
1367                         arr[4] = 0x1;   /* set LONGLBA bit */
1368                 arr[7] = bd_len;        /* assume 255 or less */
1369                 offset = 8;
1370         }
1371         ap = arr + offset;
1372         if ((bd_len > 0) && (0 == sdebug_capacity)) {
1373                 if (scsi_debug_virtual_gb > 0) {
1374                         sdebug_capacity = 2048 * 1024;
1375                         sdebug_capacity *= scsi_debug_virtual_gb;
1376                 } else
1377                         sdebug_capacity = sdebug_store_sectors;
1378         }
1379         if (8 == bd_len) {
1380                 if (sdebug_capacity > 0xfffffffe) {
1381                         ap[0] = 0xff;
1382                         ap[1] = 0xff;
1383                         ap[2] = 0xff;
1384                         ap[3] = 0xff;
1385                 } else {
1386                         ap[0] = (sdebug_capacity >> 24) & 0xff;
1387                         ap[1] = (sdebug_capacity >> 16) & 0xff;
1388                         ap[2] = (sdebug_capacity >> 8) & 0xff;
1389                         ap[3] = sdebug_capacity & 0xff;
1390                 }
1391                 ap[6] = (SECT_SIZE_PER(target) >> 8) & 0xff;
1392                 ap[7] = SECT_SIZE_PER(target) & 0xff;
1393                 offset += bd_len;
1394                 ap = arr + offset;
1395         } else if (16 == bd_len) {
1396                 unsigned long long capac = sdebug_capacity;
1397
1398                 for (k = 0; k < 8; ++k, capac >>= 8)
1399                         ap[7 - k] = capac & 0xff;
1400                 ap[12] = (SECT_SIZE_PER(target) >> 24) & 0xff;
1401                 ap[13] = (SECT_SIZE_PER(target) >> 16) & 0xff;
1402                 ap[14] = (SECT_SIZE_PER(target) >> 8) & 0xff;
1403                 ap[15] = SECT_SIZE_PER(target) & 0xff;
1404                 offset += bd_len;
1405                 ap = arr + offset;
1406         }
1407
1408         if ((subpcode > 0x0) && (subpcode < 0xff) && (0x19 != pcode)) {
1409                 /* TODO: Control Extension page */
1410                 mk_sense_buffer(devip, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB,
1411                                 0);
1412                 return check_condition_result;
1413         }
1414         switch (pcode) {
1415         case 0x1:       /* Read-Write error recovery page, direct access */
1416                 len = resp_err_recov_pg(ap, pcontrol, target);
1417                 offset += len;
1418                 break;
1419         case 0x2:       /* Disconnect-Reconnect page, all devices */
1420                 len = resp_disconnect_pg(ap, pcontrol, target);
1421                 offset += len;
1422                 break;
1423         case 0x3:       /* Format device page, direct access */
1424                 len = resp_format_pg(ap, pcontrol, target);
1425                 offset += len;
1426                 break;
1427         case 0x8:       /* Caching page, direct access */
1428                 len = resp_caching_pg(ap, pcontrol, target);
1429                 offset += len;
1430                 break;
1431         case 0xa:       /* Control Mode page, all devices */
1432                 len = resp_ctrl_m_pg(ap, pcontrol, target);
1433                 offset += len;
1434                 break;
1435         case 0x19:      /* if spc==1 then sas phy, control+discover */
1436                 if ((subpcode > 0x2) && (subpcode < 0xff)) {
1437                         mk_sense_buffer(devip, ILLEGAL_REQUEST,
1438                                         INVALID_FIELD_IN_CDB, 0);
1439                         return check_condition_result;
1440                 }
1441                 len = 0;
1442                 if ((0x0 == subpcode) || (0xff == subpcode))
1443                         len += resp_sas_sf_m_pg(ap + len, pcontrol, target);
1444                 if ((0x1 == subpcode) || (0xff == subpcode))
1445                         len += resp_sas_pcd_m_spg(ap + len, pcontrol, target,
1446                                                   target_dev_id);
1447                 if ((0x2 == subpcode) || (0xff == subpcode))
1448                         len += resp_sas_sha_m_spg(ap + len, pcontrol);
1449                 offset += len;
1450                 break;
1451         case 0x1c:      /* Informational Exceptions Mode page, all devices */
1452                 len = resp_iec_m_pg(ap, pcontrol, target);
1453                 offset += len;
1454                 break;
1455         case 0x3f:      /* Read all Mode pages */
1456                 if ((0 == subpcode) || (0xff == subpcode)) {
1457                         len = resp_err_recov_pg(ap, pcontrol, target);
1458                         len += resp_disconnect_pg(ap + len, pcontrol, target);
1459                         len += resp_format_pg(ap + len, pcontrol, target);
1460                         len += resp_caching_pg(ap + len, pcontrol, target);
1461                         len += resp_ctrl_m_pg(ap + len, pcontrol, target);
1462                         len += resp_sas_sf_m_pg(ap + len, pcontrol, target);
1463                         if (0xff == subpcode) {
1464                                 len += resp_sas_pcd_m_spg(ap + len, pcontrol,
1465                                                   target, target_dev_id);
1466                                 len += resp_sas_sha_m_spg(ap + len, pcontrol);
1467                         }
1468                         len += resp_iec_m_pg(ap + len, pcontrol, target);
1469                 } else {
1470                         mk_sense_buffer(devip, ILLEGAL_REQUEST,
1471                                         INVALID_FIELD_IN_CDB, 0);
1472                         return check_condition_result;
1473                 }
1474                 offset += len;
1475                 break;
1476         default:
1477                 mk_sense_buffer(devip, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB,
1478                                 0);
1479                 return check_condition_result;
1480         }
1481         if (msense_6)
1482                 arr[0] = offset - 1;
1483         else {
1484                 arr[0] = ((offset - 2) >> 8) & 0xff;
1485                 arr[1] = (offset - 2) & 0xff;
1486         }
1487         return fill_from_dev_buffer(scp, arr, min(alloc_len, offset));
1488 }
1489
1490 #define SDEBUG_MAX_MSELECT_SZ 512
1491
1492 static int resp_mode_select(struct scsi_cmnd * scp, int mselect6,
1493                             struct sdebug_dev_info * devip)
1494 {
1495         int pf, sp, ps, md_len, bd_len, off, spf, pg_len;
1496         int param_len, res, errsts, mpage;
1497         unsigned char arr[SDEBUG_MAX_MSELECT_SZ];
1498         unsigned char *cmd = (unsigned char *)scp->cmnd;
1499
1500         if ((errsts = check_readiness(scp, 1, devip)))
1501                 return errsts;
1502         memset(arr, 0, sizeof(arr));
1503         pf = cmd[1] & 0x10;
1504         sp = cmd[1] & 0x1;
1505         param_len = mselect6 ? cmd[4] : ((cmd[7] << 8) + cmd[8]);
1506         if ((0 == pf) || sp || (param_len > SDEBUG_MAX_MSELECT_SZ)) {
1507                 mk_sense_buffer(devip, ILLEGAL_REQUEST,
1508                                 INVALID_FIELD_IN_CDB, 0);
1509                 return check_condition_result;
1510         }
1511         res = fetch_to_dev_buffer(scp, arr, param_len);
1512         if (-1 == res)
1513                 return (DID_ERROR << 16);
1514         else if ((res < param_len) &&
1515                  (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts))
1516                 printk(KERN_INFO "scsi_debug: mode_select: cdb indicated=%d, "
1517                        " IO sent=%d bytes\n", param_len, res);
1518         md_len = mselect6 ? (arr[0] + 1) : ((arr[0] << 8) + arr[1] + 2);
1519         bd_len = mselect6 ? arr[3] : ((arr[6] << 8) + arr[7]);
1520         if (md_len > 2) {
1521                 mk_sense_buffer(devip, ILLEGAL_REQUEST,
1522                                 INVALID_FIELD_IN_PARAM_LIST, 0);
1523                 return check_condition_result;
1524         }
1525         off = bd_len + (mselect6 ? 4 : 8);
1526         mpage = arr[off] & 0x3f;
1527         ps = !!(arr[off] & 0x80);
1528         if (ps) {
1529                 mk_sense_buffer(devip, ILLEGAL_REQUEST,
1530                                 INVALID_FIELD_IN_PARAM_LIST, 0);
1531                 return check_condition_result;
1532         }
1533         spf = !!(arr[off] & 0x40);
1534         pg_len = spf ? ((arr[off + 2] << 8) + arr[off + 3] + 4) :
1535                        (arr[off + 1] + 2);
1536         if ((pg_len + off) > param_len) {
1537                 mk_sense_buffer(devip, ILLEGAL_REQUEST,
1538                                 PARAMETER_LIST_LENGTH_ERR, 0);
1539                 return check_condition_result;
1540         }
1541         switch (mpage) {
1542         case 0xa:      /* Control Mode page */
1543                 if (ctrl_m_pg[1] == arr[off + 1]) {
1544                         memcpy(ctrl_m_pg + 2, arr + off + 2,
1545                                sizeof(ctrl_m_pg) - 2);
1546                         scsi_debug_dsense = !!(ctrl_m_pg[2] & 0x4);
1547                         return 0;
1548                 }
1549                 break;
1550         case 0x1c:      /* Informational Exceptions Mode page */
1551                 if (iec_m_pg[1] == arr[off + 1]) {
1552                         memcpy(iec_m_pg + 2, arr + off + 2,
1553                                sizeof(iec_m_pg) - 2);
1554                         return 0;
1555                 }
1556                 break;
1557         default:
1558                 break;
1559         }
1560         mk_sense_buffer(devip, ILLEGAL_REQUEST,
1561                         INVALID_FIELD_IN_PARAM_LIST, 0);
1562         return check_condition_result;
1563 }
1564
1565 static int resp_temp_l_pg(unsigned char * arr)
1566 {
1567         unsigned char temp_l_pg[] = {0x0, 0x0, 0x3, 0x2, 0x0, 38,
1568                                      0x0, 0x1, 0x3, 0x2, 0x0, 65,
1569                 };
1570
1571         memcpy(arr, temp_l_pg, sizeof(temp_l_pg));
1572         return sizeof(temp_l_pg);
1573 }
1574
1575 static int resp_ie_l_pg(unsigned char * arr)
1576 {
1577         unsigned char ie_l_pg[] = {0x0, 0x0, 0x3, 0x3, 0x0, 0x0, 38,
1578                 };
1579
1580         memcpy(arr, ie_l_pg, sizeof(ie_l_pg));
1581         if (iec_m_pg[2] & 0x4) {        /* TEST bit set */
1582                 arr[4] = THRESHOLD_EXCEEDED;
1583                 arr[5] = 0xff;
1584         }
1585         return sizeof(ie_l_pg);
1586 }
1587
1588 #define SDEBUG_MAX_LSENSE_SZ 512
1589
1590 static int resp_log_sense(struct scsi_cmnd * scp,
1591                           struct sdebug_dev_info * devip)
1592 {
1593         int ppc, sp, pcontrol, pcode, subpcode, alloc_len, errsts, len, n;
1594         unsigned char arr[SDEBUG_MAX_LSENSE_SZ];
1595         unsigned char *cmd = (unsigned char *)scp->cmnd;
1596
1597         if ((errsts = check_readiness(scp, 1, devip)))
1598                 return errsts;
1599         memset(arr, 0, sizeof(arr));
1600         ppc = cmd[1] & 0x2;
1601         sp = cmd[1] & 0x1;
1602         if (ppc || sp) {
1603                 mk_sense_buffer(devip, ILLEGAL_REQUEST,
1604                                 INVALID_FIELD_IN_CDB, 0);
1605                 return check_condition_result;
1606         }
1607         pcontrol = (cmd[2] & 0xc0) >> 6;
1608         pcode = cmd[2] & 0x3f;
1609         subpcode = cmd[3] & 0xff;
1610         alloc_len = (cmd[7] << 8) + cmd[8];
1611         arr[0] = pcode;
1612         if (0 == subpcode) {
1613                 switch (pcode) {
1614                 case 0x0:       /* Supported log pages log page */
1615                         n = 4;
1616                         arr[n++] = 0x0;         /* this page */
1617                         arr[n++] = 0xd;         /* Temperature */
1618                         arr[n++] = 0x2f;        /* Informational exceptions */
1619                         arr[3] = n - 4;
1620                         break;
1621                 case 0xd:       /* Temperature log page */
1622                         arr[3] = resp_temp_l_pg(arr + 4);
1623                         break;
1624                 case 0x2f:      /* Informational exceptions log page */
1625                         arr[3] = resp_ie_l_pg(arr + 4);
1626                         break;
1627                 default:
1628                         mk_sense_buffer(devip, ILLEGAL_REQUEST,
1629                                         INVALID_FIELD_IN_CDB, 0);
1630                         return check_condition_result;
1631                 }
1632         } else if (0xff == subpcode) {
1633                 arr[0] |= 0x40;
1634                 arr[1] = subpcode;
1635                 switch (pcode) {
1636                 case 0x0:       /* Supported log pages and subpages log page */
1637                         n = 4;
1638                         arr[n++] = 0x0;
1639                         arr[n++] = 0x0;         /* 0,0 page */
1640                         arr[n++] = 0x0;
1641                         arr[n++] = 0xff;        /* this page */
1642                         arr[n++] = 0xd;
1643                         arr[n++] = 0x0;         /* Temperature */
1644                         arr[n++] = 0x2f;
1645                         arr[n++] = 0x0; /* Informational exceptions */
1646                         arr[3] = n - 4;
1647                         break;
1648                 case 0xd:       /* Temperature subpages */
1649                         n = 4;
1650                         arr[n++] = 0xd;
1651                         arr[n++] = 0x0;         /* Temperature */
1652                         arr[3] = n - 4;
1653                         break;
1654                 case 0x2f:      /* Informational exceptions subpages */
1655                         n = 4;
1656                         arr[n++] = 0x2f;
1657                         arr[n++] = 0x0;         /* Informational exceptions */
1658                         arr[3] = n - 4;
1659                         break;
1660                 default:
1661                         mk_sense_buffer(devip, ILLEGAL_REQUEST,
1662                                         INVALID_FIELD_IN_CDB, 0);
1663                         return check_condition_result;
1664                 }
1665         } else {
1666                 mk_sense_buffer(devip, ILLEGAL_REQUEST,
1667                                 INVALID_FIELD_IN_CDB, 0);
1668                 return check_condition_result;
1669         }
1670         len = min(((arr[2] << 8) + arr[3]) + 4, alloc_len);
1671         return fill_from_dev_buffer(scp, arr,
1672                     min(len, SDEBUG_MAX_INQ_ARR_SZ));
1673 }
1674
1675 static int resp_read(struct scsi_cmnd * SCpnt, unsigned long long lba,
1676                      unsigned int num, struct sdebug_dev_info * devip)
1677 {
1678         unsigned long iflags;
1679         unsigned int block, from_bottom;
1680         unsigned long long u;
1681         int ret;
1682
1683         if (lba + num > sdebug_capacity) {
1684                 mk_sense_buffer(devip, ILLEGAL_REQUEST, ADDR_OUT_OF_RANGE,
1685                                 0);
1686                 return check_condition_result;
1687         }
1688         /* transfer length excessive (tie in to block limits VPD page) */
1689         if (num > sdebug_store_sectors) {
1690                 mk_sense_buffer(devip, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB,
1691                                 0);
1692                 return check_condition_result;
1693         }
1694         if ((SCSI_DEBUG_OPT_MEDIUM_ERR & scsi_debug_opts) &&
1695             (lba <= OPT_MEDIUM_ERR_ADDR) &&
1696             ((lba + num) > OPT_MEDIUM_ERR_ADDR)) {
1697                 /* claim unrecoverable read error */
1698                 mk_sense_buffer(devip, MEDIUM_ERROR, UNRECOVERED_READ_ERR,
1699                                 0);
1700                 /* set info field and valid bit for fixed descriptor */
1701                 if (0x70 == (devip->sense_buff[0] & 0x7f)) {
1702                         devip->sense_buff[0] |= 0x80;   /* Valid bit */
1703                         ret = OPT_MEDIUM_ERR_ADDR;
1704                         devip->sense_buff[3] = (ret >> 24) & 0xff;
1705                         devip->sense_buff[4] = (ret >> 16) & 0xff;
1706                         devip->sense_buff[5] = (ret >> 8) & 0xff;
1707                         devip->sense_buff[6] = ret & 0xff;
1708                 }
1709                 return check_condition_result;
1710         }
1711         read_lock_irqsave(&atomic_rw, iflags);
1712         if ((lba + num) <= sdebug_store_sectors)
1713                 ret = fill_from_dev_buffer(SCpnt,
1714                                            fake_storep + (lba * SECT_SIZE),
1715                                            num * SECT_SIZE);
1716         else {
1717                 /* modulo when one arg is 64 bits needs do_div() */
1718                 u = lba;
1719                 block = do_div(u, sdebug_store_sectors);
1720                 from_bottom = 0;
1721                 if ((block + num) > sdebug_store_sectors)
1722                         from_bottom = (block + num) - sdebug_store_sectors;
1723                 ret = fill_from_dev_buffer(SCpnt,
1724                                            fake_storep + (block * SECT_SIZE),
1725                                            (num - from_bottom) * SECT_SIZE);
1726                 if ((0 == ret) && (from_bottom > 0))
1727                         ret = fill_from_dev_buffer(SCpnt, fake_storep,
1728                                                    from_bottom * SECT_SIZE);
1729         }
1730         read_unlock_irqrestore(&atomic_rw, iflags);
1731         return ret;
1732 }
1733
1734 static int resp_write(struct scsi_cmnd * SCpnt, unsigned long long lba,
1735                       unsigned int num, struct sdebug_dev_info * devip)
1736 {
1737         unsigned long iflags;
1738         unsigned int block, to_bottom;
1739         unsigned long long u;
1740         int res;
1741
1742         if (lba + num > sdebug_capacity) {
1743                 mk_sense_buffer(devip, ILLEGAL_REQUEST, ADDR_OUT_OF_RANGE,
1744                                 0);
1745                 return check_condition_result;
1746         }
1747         /* transfer length excessive (tie in to block limits VPD page) */
1748         if (num > sdebug_store_sectors) {
1749                 mk_sense_buffer(devip, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB,
1750                                 0);
1751                 return check_condition_result;
1752         }
1753
1754         write_lock_irqsave(&atomic_rw, iflags);
1755         if ((lba + num) <= sdebug_store_sectors)
1756                 res = fetch_to_dev_buffer(SCpnt,
1757                                           fake_storep + (lba * SECT_SIZE),
1758                                           num * SECT_SIZE);
1759         else {
1760                 /* modulo when one arg is 64 bits needs do_div() */
1761                 u = lba;
1762                 block = do_div(u, sdebug_store_sectors);
1763                 to_bottom = 0;
1764                 if ((block + num) > sdebug_store_sectors)
1765                         to_bottom = (block + num) - sdebug_store_sectors;
1766                 res = fetch_to_dev_buffer(SCpnt,
1767                                           fake_storep + (block * SECT_SIZE),
1768                                           (num - to_bottom) * SECT_SIZE);
1769                 if ((0 == res) && (to_bottom > 0))
1770                         res = fetch_to_dev_buffer(SCpnt, fake_storep,
1771                                                   to_bottom * SECT_SIZE);
1772         }
1773         write_unlock_irqrestore(&atomic_rw, iflags);
1774         if (-1 == res)
1775                 return (DID_ERROR << 16);
1776         else if ((res < (num * SECT_SIZE)) &&
1777                  (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts))
1778                 printk(KERN_INFO "scsi_debug: write: cdb indicated=%u, "
1779                        " IO sent=%d bytes\n", num * SECT_SIZE, res);
1780         return 0;
1781 }
1782
1783 #define SDEBUG_RLUN_ARR_SZ 256
1784
1785 static int resp_report_luns(struct scsi_cmnd * scp,
1786                             struct sdebug_dev_info * devip)
1787 {
1788         unsigned int alloc_len;
1789         int lun_cnt, i, upper, num, n, wlun, lun;
1790         unsigned char *cmd = (unsigned char *)scp->cmnd;
1791         int select_report = (int)cmd[2];
1792         struct scsi_lun *one_lun;
1793         unsigned char arr[SDEBUG_RLUN_ARR_SZ];
1794         unsigned char * max_addr;
1795
1796         alloc_len = cmd[9] + (cmd[8] << 8) + (cmd[7] << 16) + (cmd[6] << 24);
1797         if ((alloc_len < 4) || (select_report > 2)) {
1798                 mk_sense_buffer(devip, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB,
1799                                 0);
1800                 return check_condition_result;
1801         }
1802         /* can produce response with up to 16k luns (lun 0 to lun 16383) */
1803         memset(arr, 0, SDEBUG_RLUN_ARR_SZ);
1804         lun_cnt = scsi_debug_max_luns;
1805         if (1 == select_report)
1806                 lun_cnt = 0;
1807         else if (scsi_debug_no_lun_0 && (lun_cnt > 0))
1808                 --lun_cnt;
1809         wlun = (select_report > 0) ? 1 : 0;
1810         num = lun_cnt + wlun;
1811         arr[2] = ((sizeof(struct scsi_lun) * num) >> 8) & 0xff;
1812         arr[3] = (sizeof(struct scsi_lun) * num) & 0xff;
1813         n = min((int)((SDEBUG_RLUN_ARR_SZ - 8) /
1814                             sizeof(struct scsi_lun)), num);
1815         if (n < num) {
1816                 wlun = 0;
1817                 lun_cnt = n;
1818         }
1819         one_lun = (struct scsi_lun *) &arr[8];
1820         max_addr = arr + SDEBUG_RLUN_ARR_SZ;
1821         for (i = 0, lun = (scsi_debug_no_lun_0 ? 1 : 0);
1822              ((i < lun_cnt) && ((unsigned char *)(one_lun + i) < max_addr));
1823              i++, lun++) {
1824                 upper = (lun >> 8) & 0x3f;
1825                 if (upper)
1826                         one_lun[i].scsi_lun[0] =
1827                             (upper | (SAM2_LUN_ADDRESS_METHOD << 6));
1828                 one_lun[i].scsi_lun[1] = lun & 0xff;
1829         }
1830         if (wlun) {
1831                 one_lun[i].scsi_lun[0] = (SAM2_WLUN_REPORT_LUNS >> 8) & 0xff;
1832                 one_lun[i].scsi_lun[1] = SAM2_WLUN_REPORT_LUNS & 0xff;
1833                 i++;
1834         }
1835         alloc_len = (unsigned char *)(one_lun + i) - arr;
1836         return fill_from_dev_buffer(scp, arr,
1837                                     min((int)alloc_len, SDEBUG_RLUN_ARR_SZ));
1838 }
1839
1840 /* When timer goes off this function is called. */
1841 static void timer_intr_handler(unsigned long indx)
1842 {
1843         struct sdebug_queued_cmd * sqcp;
1844         unsigned long iflags;
1845
1846         if (indx >= SCSI_DEBUG_CANQUEUE) {
1847                 printk(KERN_ERR "scsi_debug:timer_intr_handler: indx too "
1848                        "large\n");
1849                 return;
1850         }
1851         spin_lock_irqsave(&queued_arr_lock, iflags);
1852         sqcp = &queued_arr[(int)indx];
1853         if (! sqcp->in_use) {
1854                 printk(KERN_ERR "scsi_debug:timer_intr_handler: Unexpected "
1855                        "interrupt\n");
1856                 spin_unlock_irqrestore(&queued_arr_lock, iflags);
1857                 return;
1858         }
1859         sqcp->in_use = 0;
1860         if (sqcp->done_funct) {
1861                 sqcp->a_cmnd->result = sqcp->scsi_result;
1862                 sqcp->done_funct(sqcp->a_cmnd); /* callback to mid level */
1863         }
1864         sqcp->done_funct = NULL;
1865         spin_unlock_irqrestore(&queued_arr_lock, iflags);
1866 }
1867
1868 static int scsi_debug_slave_alloc(struct scsi_device * sdp)
1869 {
1870         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1871                 printk(KERN_INFO "scsi_debug: slave_alloc <%u %u %u %u>\n",
1872                        sdp->host->host_no, sdp->channel, sdp->id, sdp->lun);
1873         return 0;
1874 }
1875
1876 static int scsi_debug_slave_configure(struct scsi_device * sdp)
1877 {
1878         struct sdebug_dev_info * devip;
1879
1880         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1881                 printk(KERN_INFO "scsi_debug: slave_configure <%u %u %u %u>\n",
1882                        sdp->host->host_no, sdp->channel, sdp->id, sdp->lun);
1883         if (sdp->host->max_cmd_len != SCSI_DEBUG_MAX_CMD_LEN)
1884                 sdp->host->max_cmd_len = SCSI_DEBUG_MAX_CMD_LEN;
1885         devip = devInfoReg(sdp);
1886         sdp->hostdata = devip;
1887         if (sdp->host->cmd_per_lun)
1888                 scsi_adjust_queue_depth(sdp, SDEBUG_TAGGED_QUEUING,
1889                                         sdp->host->cmd_per_lun);
1890         blk_queue_max_segment_size(sdp->request_queue, 256 * 1024);
1891         return 0;
1892 }
1893
1894 static void scsi_debug_slave_destroy(struct scsi_device * sdp)
1895 {
1896         struct sdebug_dev_info * devip =
1897                                 (struct sdebug_dev_info *)sdp->hostdata;
1898
1899         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1900                 printk(KERN_INFO "scsi_debug: slave_destroy <%u %u %u %u>\n",
1901                        sdp->host->host_no, sdp->channel, sdp->id, sdp->lun);
1902         if (devip) {
1903                 /* make this slot avaliable for re-use */
1904                 devip->used = 0;
1905                 sdp->hostdata = NULL;
1906         }
1907 }
1908
1909 static struct sdebug_dev_info * devInfoReg(struct scsi_device * sdev)
1910 {
1911         struct sdebug_host_info * sdbg_host;
1912         struct sdebug_dev_info * open_devip = NULL;
1913         struct sdebug_dev_info * devip =
1914                         (struct sdebug_dev_info *)sdev->hostdata;
1915
1916         if (devip)
1917                 return devip;
1918         sdbg_host = *(struct sdebug_host_info **) sdev->host->hostdata;
1919         if(! sdbg_host) {
1920                 printk(KERN_ERR "Host info NULL\n");
1921                 return NULL;
1922         }
1923         list_for_each_entry(devip, &sdbg_host->dev_info_list, dev_list) {
1924                 if ((devip->used) && (devip->channel == sdev->channel) &&
1925                     (devip->target == sdev->id) &&
1926                     (devip->lun == sdev->lun))
1927                         return devip;
1928                 else {
1929                         if ((!devip->used) && (!open_devip))
1930                                 open_devip = devip;
1931                 }
1932         }
1933         if (NULL == open_devip) { /* try and make a new one */
1934                 open_devip = kzalloc(sizeof(*open_devip),GFP_KERNEL);
1935                 if (NULL == open_devip) {
1936                         printk(KERN_ERR "%s: out of memory at line %d\n",
1937                                 __FUNCTION__, __LINE__);
1938                         return NULL;
1939                 }
1940                 open_devip->sdbg_host = sdbg_host;
1941                 list_add_tail(&open_devip->dev_list,
1942                 &sdbg_host->dev_info_list);
1943         }
1944         if (open_devip) {
1945                 open_devip->channel = sdev->channel;
1946                 open_devip->target = sdev->id;
1947                 open_devip->lun = sdev->lun;
1948                 open_devip->sdbg_host = sdbg_host;
1949                 open_devip->reset = 1;
1950                 open_devip->used = 1;
1951                 memset(open_devip->sense_buff, 0, SDEBUG_SENSE_LEN);
1952                 if (scsi_debug_dsense)
1953                         open_devip->sense_buff[0] = 0x72;
1954                 else {
1955                         open_devip->sense_buff[0] = 0x70;
1956                         open_devip->sense_buff[7] = 0xa;
1957                 }
1958                 if (sdev->lun == SAM2_WLUN_REPORT_LUNS)
1959                         open_devip->wlun = SAM2_WLUN_REPORT_LUNS & 0xff;
1960                 return open_devip;
1961         }
1962         return NULL;
1963 }
1964
1965 static void mk_sense_buffer(struct sdebug_dev_info * devip, int key,
1966                             int asc, int asq)
1967 {
1968         unsigned char * sbuff;
1969
1970         sbuff = devip->sense_buff;
1971         memset(sbuff, 0, SDEBUG_SENSE_LEN);
1972         if (scsi_debug_dsense) {
1973                 sbuff[0] = 0x72;  /* descriptor, current */
1974                 sbuff[1] = key;
1975                 sbuff[2] = asc;
1976                 sbuff[3] = asq;
1977         } else {
1978                 sbuff[0] = 0x70;  /* fixed, current */
1979                 sbuff[2] = key;
1980                 sbuff[7] = 0xa;   /* implies 18 byte sense buffer */
1981                 sbuff[12] = asc;
1982                 sbuff[13] = asq;
1983         }
1984         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1985                 printk(KERN_INFO "scsi_debug:    [sense_key,asc,ascq]: "
1986                       "[0x%x,0x%x,0x%x]\n", key, asc, asq);
1987 }
1988
1989 static int scsi_debug_abort(struct scsi_cmnd * SCpnt)
1990 {
1991         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1992                 printk(KERN_INFO "scsi_debug: abort\n");
1993         ++num_aborts;
1994         stop_queued_cmnd(SCpnt);
1995         return SUCCESS;
1996 }
1997
1998 static int scsi_debug_biosparam(struct scsi_device *sdev,
1999                 struct block_device * bdev, sector_t capacity, int *info)
2000 {
2001         int res;
2002         unsigned char *buf;
2003
2004         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
2005                 printk(KERN_INFO "scsi_debug: biosparam\n");
2006         buf = scsi_bios_ptable(bdev);
2007         if (buf) {
2008                 res = scsi_partsize(buf, capacity,
2009                                     &info[2], &info[0], &info[1]);
2010                 kfree(buf);
2011                 if (! res)
2012                         return res;
2013         }
2014         info[0] = sdebug_heads;
2015         info[1] = sdebug_sectors_per;
2016         info[2] = sdebug_cylinders_per;
2017         return 0;
2018 }
2019
2020 static int scsi_debug_device_reset(struct scsi_cmnd * SCpnt)
2021 {
2022         struct sdebug_dev_info * devip;
2023
2024         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
2025                 printk(KERN_INFO "scsi_debug: device_reset\n");
2026         ++num_dev_resets;
2027         if (SCpnt) {
2028                 devip = devInfoReg(SCpnt->device);
2029                 if (devip)
2030                         devip->reset = 1;
2031         }
2032         return SUCCESS;
2033 }
2034
2035 static int scsi_debug_bus_reset(struct scsi_cmnd * SCpnt)
2036 {
2037         struct sdebug_host_info *sdbg_host;
2038         struct sdebug_dev_info * dev_info;
2039         struct scsi_device * sdp;
2040         struct Scsi_Host * hp;
2041
2042         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
2043                 printk(KERN_INFO "scsi_debug: bus_reset\n");
2044         ++num_bus_resets;
2045         if (SCpnt && ((sdp = SCpnt->device)) && ((hp = sdp->host))) {
2046                 sdbg_host = *(struct sdebug_host_info **) hp->hostdata;
2047                 if (sdbg_host) {
2048                         list_for_each_entry(dev_info,
2049                                             &sdbg_host->dev_info_list,
2050                                             dev_list)
2051                                 dev_info->reset = 1;
2052                 }
2053         }
2054         return SUCCESS;
2055 }
2056
2057 static int scsi_debug_host_reset(struct scsi_cmnd * SCpnt)
2058 {
2059         struct sdebug_host_info * sdbg_host;
2060         struct sdebug_dev_info * dev_info;
2061
2062         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
2063                 printk(KERN_INFO "scsi_debug: host_reset\n");
2064         ++num_host_resets;
2065         spin_lock(&sdebug_host_list_lock);
2066         list_for_each_entry(sdbg_host, &sdebug_host_list, host_list) {
2067                 list_for_each_entry(dev_info, &sdbg_host->dev_info_list,
2068                                     dev_list)
2069                         dev_info->reset = 1;
2070         }
2071         spin_unlock(&sdebug_host_list_lock);
2072         stop_all_queued();
2073         return SUCCESS;
2074 }
2075
2076 /* Returns 1 if found 'cmnd' and deleted its timer. else returns 0 */
2077 static int stop_queued_cmnd(struct scsi_cmnd * cmnd)
2078 {
2079         unsigned long iflags;
2080         int k;
2081         struct sdebug_queued_cmd * sqcp;
2082
2083         spin_lock_irqsave(&queued_arr_lock, iflags);
2084         for (k = 0; k < SCSI_DEBUG_CANQUEUE; ++k) {
2085                 sqcp = &queued_arr[k];
2086                 if (sqcp->in_use && (cmnd == sqcp->a_cmnd)) {
2087                         del_timer_sync(&sqcp->cmnd_timer);
2088                         sqcp->in_use = 0;
2089                         sqcp->a_cmnd = NULL;
2090                         break;
2091                 }
2092         }
2093         spin_unlock_irqrestore(&queued_arr_lock, iflags);
2094         return (k < SCSI_DEBUG_CANQUEUE) ? 1 : 0;
2095 }
2096
2097 /* Deletes (stops) timers of all queued commands */
2098 static void stop_all_queued(void)
2099 {
2100         unsigned long iflags;
2101         int k;
2102         struct sdebug_queued_cmd * sqcp;
2103
2104         spin_lock_irqsave(&queued_arr_lock, iflags);
2105         for (k = 0; k < SCSI_DEBUG_CANQUEUE; ++k) {
2106                 sqcp = &queued_arr[k];
2107                 if (sqcp->in_use && sqcp->a_cmnd) {
2108                         del_timer_sync(&sqcp->cmnd_timer);
2109                         sqcp->in_use = 0;
2110                         sqcp->a_cmnd = NULL;
2111                 }
2112         }
2113         spin_unlock_irqrestore(&queued_arr_lock, iflags);
2114 }
2115
2116 /* Initializes timers in queued array */
2117 static void __init init_all_queued(void)
2118 {
2119         unsigned long iflags;
2120         int k;
2121         struct sdebug_queued_cmd * sqcp;
2122
2123         spin_lock_irqsave(&queued_arr_lock, iflags);
2124         for (k = 0; k < SCSI_DEBUG_CANQUEUE; ++k) {
2125                 sqcp = &queued_arr[k];
2126                 init_timer(&sqcp->cmnd_timer);
2127                 sqcp->in_use = 0;
2128                 sqcp->a_cmnd = NULL;
2129         }
2130         spin_unlock_irqrestore(&queued_arr_lock, iflags);
2131 }
2132
2133 static void __init sdebug_build_parts(unsigned char * ramp)
2134 {
2135         struct partition * pp;
2136         int starts[SDEBUG_MAX_PARTS + 2];
2137         int sectors_per_part, num_sectors, k;
2138         int heads_by_sects, start_sec, end_sec;
2139
2140         /* assume partition table already zeroed */
2141         if ((scsi_debug_num_parts < 1) || (sdebug_store_size < 1048576))
2142                 return;
2143         if (scsi_debug_num_parts > SDEBUG_MAX_PARTS) {
2144                 scsi_debug_num_parts = SDEBUG_MAX_PARTS;
2145                 printk(KERN_WARNING "scsi_debug:build_parts: reducing "
2146                                     "partitions to %d\n", SDEBUG_MAX_PARTS);
2147         }
2148         num_sectors = (int)sdebug_store_sectors;
2149         sectors_per_part = (num_sectors - sdebug_sectors_per)
2150                            / scsi_debug_num_parts;
2151         heads_by_sects = sdebug_heads * sdebug_sectors_per;
2152         starts[0] = sdebug_sectors_per;
2153         for (k = 1; k < scsi_debug_num_parts; ++k)
2154                 starts[k] = ((k * sectors_per_part) / heads_by_sects)
2155                             * heads_by_sects;
2156         starts[scsi_debug_num_parts] = num_sectors;
2157         starts[scsi_debug_num_parts + 1] = 0;
2158
2159         ramp[510] = 0x55;       /* magic partition markings */
2160         ramp[511] = 0xAA;
2161         pp = (struct partition *)(ramp + 0x1be);
2162         for (k = 0; starts[k + 1]; ++k, ++pp) {
2163                 start_sec = starts[k];
2164                 end_sec = starts[k + 1] - 1;
2165                 pp->boot_ind = 0;
2166
2167                 pp->cyl = start_sec / heads_by_sects;
2168                 pp->head = (start_sec - (pp->cyl * heads_by_sects))
2169                            / sdebug_sectors_per;
2170                 pp->sector = (start_sec % sdebug_sectors_per) + 1;
2171
2172                 pp->end_cyl = end_sec / heads_by_sects;
2173                 pp->end_head = (end_sec - (pp->end_cyl * heads_by_sects))
2174                                / sdebug_sectors_per;
2175                 pp->end_sector = (end_sec % sdebug_sectors_per) + 1;
2176
2177                 pp->start_sect = start_sec;
2178                 pp->nr_sects = end_sec - start_sec + 1;
2179                 pp->sys_ind = 0x83;     /* plain Linux partition */
2180         }
2181 }
2182
2183 static int schedule_resp(struct scsi_cmnd * cmnd,
2184                          struct sdebug_dev_info * devip,
2185                          done_funct_t done, int scsi_result, int delta_jiff)
2186 {
2187         if ((SCSI_DEBUG_OPT_NOISE & scsi_debug_opts) && cmnd) {
2188                 if (scsi_result) {
2189                         struct scsi_device * sdp = cmnd->device;
2190
2191                         printk(KERN_INFO "scsi_debug:    <%u %u %u %u> "
2192                                "non-zero result=0x%x\n", sdp->host->host_no,
2193                                sdp->channel, sdp->id, sdp->lun, scsi_result);
2194                 }
2195         }
2196         if (cmnd && devip) {
2197                 /* simulate autosense by this driver */
2198                 if (SAM_STAT_CHECK_CONDITION == (scsi_result & 0xff))
2199                         memcpy(cmnd->sense_buffer, devip->sense_buff,
2200                                (SCSI_SENSE_BUFFERSIZE > SDEBUG_SENSE_LEN) ?
2201                                SDEBUG_SENSE_LEN : SCSI_SENSE_BUFFERSIZE);
2202         }
2203         if (delta_jiff <= 0) {
2204                 if (cmnd)
2205                         cmnd->result = scsi_result;
2206                 if (done)
2207                         done(cmnd);
2208                 return 0;
2209         } else {
2210                 unsigned long iflags;
2211                 int k;
2212                 struct sdebug_queued_cmd * sqcp = NULL;
2213
2214                 spin_lock_irqsave(&queued_arr_lock, iflags);
2215                 for (k = 0; k < SCSI_DEBUG_CANQUEUE; ++k) {
2216                         sqcp = &queued_arr[k];
2217                         if (! sqcp->in_use)
2218                                 break;
2219                 }
2220                 if (k >= SCSI_DEBUG_CANQUEUE) {
2221                         spin_unlock_irqrestore(&queued_arr_lock, iflags);
2222                         printk(KERN_WARNING "scsi_debug: can_queue exceeded\n");
2223                         return 1;       /* report busy to mid level */
2224                 }
2225                 sqcp->in_use = 1;
2226                 sqcp->a_cmnd = cmnd;
2227                 sqcp->scsi_result = scsi_result;
2228                 sqcp->done_funct = done;
2229                 sqcp->cmnd_timer.function = timer_intr_handler;
2230                 sqcp->cmnd_timer.data = k;
2231                 sqcp->cmnd_timer.expires = jiffies + delta_jiff;
2232                 add_timer(&sqcp->cmnd_timer);
2233                 spin_unlock_irqrestore(&queued_arr_lock, iflags);
2234                 if (cmnd)
2235                         cmnd->result = 0;
2236                 return 0;
2237         }
2238 }
2239
2240 /* Note: The following macros create attribute files in the
2241    /sys/module/scsi_debug/parameters directory. Unfortunately this
2242    driver is unaware of a change and cannot trigger auxiliary actions
2243    as it can when the corresponding attribute in the
2244    /sys/bus/pseudo/drivers/scsi_debug directory is changed.
2245  */
2246 module_param_named(add_host, scsi_debug_add_host, int, S_IRUGO | S_IWUSR);
2247 module_param_named(delay, scsi_debug_delay, int, S_IRUGO | S_IWUSR);
2248 module_param_named(dev_size_mb, scsi_debug_dev_size_mb, int, S_IRUGO);
2249 module_param_named(dsense, scsi_debug_dsense, int, S_IRUGO | S_IWUSR);
2250 module_param_named(every_nth, scsi_debug_every_nth, int, S_IRUGO | S_IWUSR);
2251 module_param_named(fake_rw, scsi_debug_fake_rw, int, S_IRUGO | S_IWUSR);
2252 module_param_named(max_luns, scsi_debug_max_luns, int, S_IRUGO | S_IWUSR);
2253 module_param_named(no_lun_0, scsi_debug_no_lun_0, int, S_IRUGO | S_IWUSR);
2254 module_param_named(num_parts, scsi_debug_num_parts, int, S_IRUGO);
2255 module_param_named(num_tgts, scsi_debug_num_tgts, int, S_IRUGO | S_IWUSR);
2256 module_param_named(opts, scsi_debug_opts, int, S_IRUGO | S_IWUSR);
2257 module_param_named(ptype, scsi_debug_ptype, int, S_IRUGO | S_IWUSR);
2258 module_param_named(scsi_level, scsi_debug_scsi_level, int, S_IRUGO);
2259 module_param_named(virtual_gb, scsi_debug_virtual_gb, int, S_IRUGO | S_IWUSR);
2260 module_param_named(vpd_use_hostno, scsi_debug_vpd_use_hostno, int,
2261                    S_IRUGO | S_IWUSR);
2262
2263 MODULE_AUTHOR("Eric Youngdale + Douglas Gilbert");
2264 MODULE_DESCRIPTION("SCSI debug adapter driver");
2265 MODULE_LICENSE("GPL");
2266 MODULE_VERSION(SCSI_DEBUG_VERSION);
2267
2268 MODULE_PARM_DESC(add_host, "0..127 hosts allowed(def=1)");
2269 MODULE_PARM_DESC(delay, "# of jiffies to delay response(def=1)");
2270 MODULE_PARM_DESC(dev_size_mb, "size in MB of ram shared by devs(def=8)");
2271 MODULE_PARM_DESC(dsense, "use descriptor sense format(def=0 -> fixed)");
2272 MODULE_PARM_DESC(every_nth, "timeout every nth command(def=100)");
2273 MODULE_PARM_DESC(fake_rw, "fake reads/writes instead of copying (def=0)");
2274 MODULE_PARM_DESC(max_luns, "number of LUNs per target to simulate(def=1)");
2275 MODULE_PARM_DESC(no_lun_0, "no LU number 0 (def=0 -> have lun 0)");
2276 MODULE_PARM_DESC(num_parts, "number of partitions(def=0)");
2277 MODULE_PARM_DESC(num_tgts, "number of targets per host to simulate(def=1)");
2278 MODULE_PARM_DESC(opts, "1->noise, 2->medium_error, 4->... (def=0)");
2279 MODULE_PARM_DESC(ptype, "SCSI peripheral type(def=0[disk])");
2280 MODULE_PARM_DESC(scsi_level, "SCSI level to simulate(def=5[SPC-3])");
2281 MODULE_PARM_DESC(virtual_gb, "virtual gigabyte size (def=0 -> use dev_size_mb)");
2282 MODULE_PARM_DESC(vpd_use_hostno, "0 -> dev ids ignore hostno (def=1 -> unique dev ids)");
2283
2284
2285 static char sdebug_info[256];
2286
2287 static const char * scsi_debug_info(struct Scsi_Host * shp)
2288 {
2289         sprintf(sdebug_info, "scsi_debug, version %s [%s], "
2290                 "dev_size_mb=%d, opts=0x%x", SCSI_DEBUG_VERSION,
2291                 scsi_debug_version_date, scsi_debug_dev_size_mb,
2292                 scsi_debug_opts);
2293         return sdebug_info;
2294 }
2295
2296 /* scsi_debug_proc_info
2297  * Used if the driver currently has no own support for /proc/scsi
2298  */
2299 static int scsi_debug_proc_info(struct Scsi_Host *host, char *buffer, char **start, off_t offset,
2300                                 int length, int inout)
2301 {
2302         int len, pos, begin;
2303         int orig_length;
2304
2305         orig_length = length;
2306
2307         if (inout == 1) {
2308                 char arr[16];
2309                 int minLen = length > 15 ? 15 : length;
2310
2311                 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
2312                         return -EACCES;
2313                 memcpy(arr, buffer, minLen);
2314                 arr[minLen] = '\0';
2315                 if (1 != sscanf(arr, "%d", &pos))
2316                         return -EINVAL;
2317                 scsi_debug_opts = pos;
2318                 if (scsi_debug_every_nth != 0)
2319                         scsi_debug_cmnd_count = 0;
2320                 return length;
2321         }
2322         begin = 0;
2323         pos = len = sprintf(buffer, "scsi_debug adapter driver, version "
2324             "%s [%s]\n"
2325             "num_tgts=%d, shared (ram) size=%d MB, opts=0x%x, "
2326             "every_nth=%d(curr:%d)\n"
2327             "delay=%d, max_luns=%d, scsi_level=%d\n"
2328             "sector_size=%d bytes, cylinders=%d, heads=%d, sectors=%d\n"
2329             "number of aborts=%d, device_reset=%d, bus_resets=%d, "
2330             "host_resets=%d\n",
2331             SCSI_DEBUG_VERSION, scsi_debug_version_date, scsi_debug_num_tgts,
2332             scsi_debug_dev_size_mb, scsi_debug_opts, scsi_debug_every_nth,
2333             scsi_debug_cmnd_count, scsi_debug_delay,
2334             scsi_debug_max_luns, scsi_debug_scsi_level,
2335             SECT_SIZE, sdebug_cylinders_per, sdebug_heads, sdebug_sectors_per,
2336             num_aborts, num_dev_resets, num_bus_resets, num_host_resets);
2337         if (pos < offset) {
2338                 len = 0;
2339                 begin = pos;
2340         }
2341         *start = buffer + (offset - begin);     /* Start of wanted data */
2342         len -= (offset - begin);
2343         if (len > length)
2344                 len = length;
2345         return len;
2346 }
2347
2348 static ssize_t sdebug_delay_show(struct device_driver * ddp, char * buf)
2349 {
2350         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_delay);
2351 }
2352
2353 static ssize_t sdebug_delay_store(struct device_driver * ddp,
2354                                   const char * buf, size_t count)
2355 {
2356         int delay;
2357         char work[20];
2358
2359         if (1 == sscanf(buf, "%10s", work)) {
2360                 if ((1 == sscanf(work, "%d", &delay)) && (delay >= 0)) {
2361                         scsi_debug_delay = delay;
2362                         return count;
2363                 }
2364         }
2365         return -EINVAL;
2366 }
2367 DRIVER_ATTR(delay, S_IRUGO | S_IWUSR, sdebug_delay_show,
2368             sdebug_delay_store);
2369
2370 static ssize_t sdebug_opts_show(struct device_driver * ddp, char * buf)
2371 {
2372         return scnprintf(buf, PAGE_SIZE, "0x%x\n", scsi_debug_opts);
2373 }
2374
2375 static ssize_t sdebug_opts_store(struct device_driver * ddp,
2376                                  const char * buf, size_t count)
2377 {
2378         int opts;
2379         char work[20];
2380
2381         if (1 == sscanf(buf, "%10s", work)) {
2382                 if (0 == strnicmp(work,"0x", 2)) {
2383                         if (1 == sscanf(&work[2], "%x", &opts))
2384                                 goto opts_done;
2385                 } else {
2386                         if (1 == sscanf(work, "%d", &opts))
2387                                 goto opts_done;
2388                 }
2389         }
2390         return -EINVAL;
2391 opts_done:
2392         scsi_debug_opts = opts;
2393         scsi_debug_cmnd_count = 0;
2394         return count;
2395 }
2396 DRIVER_ATTR(opts, S_IRUGO | S_IWUSR, sdebug_opts_show,
2397             sdebug_opts_store);
2398
2399 static ssize_t sdebug_ptype_show(struct device_driver * ddp, char * buf)
2400 {
2401         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_ptype);
2402 }
2403 static ssize_t sdebug_ptype_store(struct device_driver * ddp,
2404                                   const char * buf, size_t count)
2405 {
2406         int n;
2407
2408         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
2409                 scsi_debug_ptype = n;
2410                 return count;
2411         }
2412         return -EINVAL;
2413 }
2414 DRIVER_ATTR(ptype, S_IRUGO | S_IWUSR, sdebug_ptype_show, sdebug_ptype_store);
2415
2416 static ssize_t sdebug_dsense_show(struct device_driver * ddp, char * buf)
2417 {
2418         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_dsense);
2419 }
2420 static ssize_t sdebug_dsense_store(struct device_driver * ddp,
2421                                   const char * buf, size_t count)
2422 {
2423         int n;
2424
2425         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
2426                 scsi_debug_dsense = n;
2427                 return count;
2428         }
2429         return -EINVAL;
2430 }
2431 DRIVER_ATTR(dsense, S_IRUGO | S_IWUSR, sdebug_dsense_show,
2432             sdebug_dsense_store);
2433
2434 static ssize_t sdebug_fake_rw_show(struct device_driver * ddp, char * buf)
2435 {
2436         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_fake_rw);
2437 }
2438 static ssize_t sdebug_fake_rw_store(struct device_driver * ddp,
2439                                     const char * buf, size_t count)
2440 {
2441         int n;
2442
2443         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
2444                 scsi_debug_fake_rw = n;
2445                 return count;
2446         }
2447         return -EINVAL;
2448 }
2449 DRIVER_ATTR(fake_rw, S_IRUGO | S_IWUSR, sdebug_fake_rw_show,
2450             sdebug_fake_rw_store);
2451
2452 static ssize_t sdebug_no_lun_0_show(struct device_driver * ddp, char * buf)
2453 {
2454         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_no_lun_0);
2455 }
2456 static ssize_t sdebug_no_lun_0_store(struct device_driver * ddp,
2457                                      const char * buf, size_t count)
2458 {
2459         int n;
2460
2461         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
2462                 scsi_debug_no_lun_0 = n;
2463                 return count;
2464         }
2465         return -EINVAL;
2466 }
2467 DRIVER_ATTR(no_lun_0, S_IRUGO | S_IWUSR, sdebug_no_lun_0_show,
2468             sdebug_no_lun_0_store);
2469
2470 static ssize_t sdebug_num_tgts_show(struct device_driver * ddp, char * buf)
2471 {
2472         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_num_tgts);
2473 }
2474 static ssize_t sdebug_num_tgts_store(struct device_driver * ddp,
2475                                      const char * buf, size_t count)
2476 {
2477         int n;
2478
2479         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
2480                 scsi_debug_num_tgts = n;
2481                 sdebug_max_tgts_luns();
2482                 return count;
2483         }
2484         return -EINVAL;
2485 }
2486 DRIVER_ATTR(num_tgts, S_IRUGO | S_IWUSR, sdebug_num_tgts_show,
2487             sdebug_num_tgts_store);
2488
2489 static ssize_t sdebug_dev_size_mb_show(struct device_driver * ddp, char * buf)
2490 {
2491         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_dev_size_mb);
2492 }
2493 DRIVER_ATTR(dev_size_mb, S_IRUGO, sdebug_dev_size_mb_show, NULL);
2494
2495 static ssize_t sdebug_num_parts_show(struct device_driver * ddp, char * buf)
2496 {
2497         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_num_parts);
2498 }
2499 DRIVER_ATTR(num_parts, S_IRUGO, sdebug_num_parts_show, NULL);
2500
2501 static ssize_t sdebug_every_nth_show(struct device_driver * ddp, char * buf)
2502 {
2503         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_every_nth);
2504 }
2505 static ssize_t sdebug_every_nth_store(struct device_driver * ddp,
2506                                       const char * buf, size_t count)
2507 {
2508         int nth;
2509
2510         if ((count > 0) && (1 == sscanf(buf, "%d", &nth))) {
2511                 scsi_debug_every_nth = nth;
2512                 scsi_debug_cmnd_count = 0;
2513                 return count;
2514         }
2515         return -EINVAL;
2516 }
2517 DRIVER_ATTR(every_nth, S_IRUGO | S_IWUSR, sdebug_every_nth_show,
2518             sdebug_every_nth_store);
2519
2520 static ssize_t sdebug_max_luns_show(struct device_driver * ddp, char * buf)
2521 {
2522         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_max_luns);
2523 }
2524 static ssize_t sdebug_max_luns_store(struct device_driver * ddp,
2525                                      const char * buf, size_t count)
2526 {
2527         int n;
2528
2529         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
2530                 scsi_debug_max_luns = n;
2531                 sdebug_max_tgts_luns();
2532                 return count;
2533         }
2534         return -EINVAL;
2535 }
2536 DRIVER_ATTR(max_luns, S_IRUGO | S_IWUSR, sdebug_max_luns_show,
2537             sdebug_max_luns_store);
2538
2539 static ssize_t sdebug_scsi_level_show(struct device_driver * ddp, char * buf)
2540 {
2541         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_scsi_level);
2542 }
2543 DRIVER_ATTR(scsi_level, S_IRUGO, sdebug_scsi_level_show, NULL);
2544
2545 static ssize_t sdebug_virtual_gb_show(struct device_driver * ddp, char * buf)
2546 {
2547         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_virtual_gb);
2548 }
2549 static ssize_t sdebug_virtual_gb_store(struct device_driver * ddp,
2550                                        const char * buf, size_t count)
2551 {
2552         int n;
2553
2554         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
2555                 scsi_debug_virtual_gb = n;
2556                 if (scsi_debug_virtual_gb > 0) {
2557                         sdebug_capacity = 2048 * 1024;
2558                         sdebug_capacity *= scsi_debug_virtual_gb;
2559                 } else
2560                         sdebug_capacity = sdebug_store_sectors;
2561                 return count;
2562         }
2563         return -EINVAL;
2564 }
2565 DRIVER_ATTR(virtual_gb, S_IRUGO | S_IWUSR, sdebug_virtual_gb_show,
2566             sdebug_virtual_gb_store);
2567
2568 static ssize_t sdebug_add_host_show(struct device_driver * ddp, char * buf)
2569 {
2570         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_add_host);
2571 }
2572
2573 static ssize_t sdebug_add_host_store(struct device_driver * ddp,
2574                                      const char * buf, size_t count)
2575 {
2576         int delta_hosts;
2577         char work[20];
2578
2579         if (1 != sscanf(buf, "%10s", work))
2580                 return -EINVAL;
2581         {       /* temporary hack around sscanf() problem with -ve nums */
2582                 int neg = 0;
2583
2584                 if ('-' == *work)
2585                         neg = 1;
2586                 if (1 != sscanf(work + neg, "%d", &delta_hosts))
2587                         return -EINVAL;
2588                 if (neg)
2589                         delta_hosts = -delta_hosts;
2590         }
2591         if (delta_hosts > 0) {
2592                 do {
2593                         sdebug_add_adapter();
2594                 } while (--delta_hosts);
2595         } else if (delta_hosts < 0) {
2596                 do {
2597                         sdebug_remove_adapter();
2598                 } while (++delta_hosts);
2599         }
2600         return count;
2601 }
2602 DRIVER_ATTR(add_host, S_IRUGO | S_IWUSR, sdebug_add_host_show, 
2603             sdebug_add_host_store);
2604
2605 static ssize_t sdebug_vpd_use_hostno_show(struct device_driver * ddp,
2606                                           char * buf)
2607 {
2608         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_vpd_use_hostno);
2609 }
2610 static ssize_t sdebug_vpd_use_hostno_store(struct device_driver * ddp,
2611                                            const char * buf, size_t count)
2612 {
2613         int n;
2614
2615         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
2616                 scsi_debug_vpd_use_hostno = n;
2617                 return count;
2618         }
2619         return -EINVAL;
2620 }
2621 DRIVER_ATTR(vpd_use_hostno, S_IRUGO | S_IWUSR, sdebug_vpd_use_hostno_show,
2622             sdebug_vpd_use_hostno_store);
2623
2624 /* Note: The following function creates attribute files in the
2625    /sys/bus/pseudo/drivers/scsi_debug directory. The advantage of these
2626    files (over those found in the /sys/module/scsi_debug/parameters
2627    directory) is that auxiliary actions can be triggered when an attribute
2628    is changed. For example see: sdebug_add_host_store() above.
2629  */
2630 static int do_create_driverfs_files(void)
2631 {
2632         int ret;
2633
2634         ret = driver_create_file(&sdebug_driverfs_driver, &driver_attr_add_host);
2635         ret |= driver_create_file(&sdebug_driverfs_driver, &driver_attr_delay);
2636         ret |= driver_create_file(&sdebug_driverfs_driver, &driver_attr_dev_size_mb);
2637         ret |= driver_create_file(&sdebug_driverfs_driver, &driver_attr_dsense);
2638         ret |= driver_create_file(&sdebug_driverfs_driver, &driver_attr_every_nth);
2639         ret |= driver_create_file(&sdebug_driverfs_driver, &driver_attr_fake_rw);
2640         ret |= driver_create_file(&sdebug_driverfs_driver, &driver_attr_max_luns);
2641         ret |= driver_create_file(&sdebug_driverfs_driver, &driver_attr_no_lun_0);
2642         ret |= driver_create_file(&sdebug_driverfs_driver, &driver_attr_num_parts);
2643         ret |= driver_create_file(&sdebug_driverfs_driver, &driver_attr_num_tgts);
2644         ret |= driver_create_file(&sdebug_driverfs_driver, &driver_attr_ptype);
2645         ret |= driver_create_file(&sdebug_driverfs_driver, &driver_attr_opts);
2646         ret |= driver_create_file(&sdebug_driverfs_driver, &driver_attr_scsi_level);
2647         ret |= driver_create_file(&sdebug_driverfs_driver, &driver_attr_virtual_gb);
2648         ret |= driver_create_file(&sdebug_driverfs_driver, &driver_attr_vpd_use_hostno);
2649         return ret;
2650 }
2651
2652 static void do_remove_driverfs_files(void)
2653 {
2654         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_vpd_use_hostno);
2655         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_virtual_gb);
2656         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_scsi_level);
2657         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_opts);
2658         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_ptype);
2659         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_num_tgts);
2660         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_num_parts);
2661         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_no_lun_0);
2662         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_max_luns);
2663         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_fake_rw);
2664         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_every_nth);
2665         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_dsense);
2666         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_dev_size_mb);
2667         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_delay);
2668         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_add_host);
2669 }
2670
2671 static int __init scsi_debug_init(void)
2672 {
2673         unsigned int sz;
2674         int host_to_add;
2675         int k;
2676         int ret;
2677
2678         if (scsi_debug_dev_size_mb < 1)
2679                 scsi_debug_dev_size_mb = 1;  /* force minimum 1 MB ramdisk */
2680         sdebug_store_size = (unsigned int)scsi_debug_dev_size_mb * 1048576;
2681         sdebug_store_sectors = sdebug_store_size / SECT_SIZE;
2682         if (scsi_debug_virtual_gb > 0) {
2683                 sdebug_capacity = 2048 * 1024;
2684                 sdebug_capacity *= scsi_debug_virtual_gb;
2685         } else
2686                 sdebug_capacity = sdebug_store_sectors;
2687
2688         /* play around with geometry, don't waste too much on track 0 */
2689         sdebug_heads = 8;
2690         sdebug_sectors_per = 32;
2691         if (scsi_debug_dev_size_mb >= 16)
2692                 sdebug_heads = 32;
2693         else if (scsi_debug_dev_size_mb >= 256)
2694                 sdebug_heads = 64;
2695         sdebug_cylinders_per = (unsigned long)sdebug_capacity /
2696                                (sdebug_sectors_per * sdebug_heads);
2697         if (sdebug_cylinders_per >= 1024) {
2698                 /* other LLDs do this; implies >= 1GB ram disk ... */
2699                 sdebug_heads = 255;
2700                 sdebug_sectors_per = 63;
2701                 sdebug_cylinders_per = (unsigned long)sdebug_capacity /
2702                                (sdebug_sectors_per * sdebug_heads);
2703         }
2704
2705         sz = sdebug_store_size;
2706         fake_storep = vmalloc(sz);
2707         if (NULL == fake_storep) {
2708                 printk(KERN_ERR "scsi_debug_init: out of memory, 1\n");
2709                 return -ENOMEM;
2710         }
2711         memset(fake_storep, 0, sz);
2712         if (scsi_debug_num_parts > 0)
2713                 sdebug_build_parts(fake_storep);
2714
2715         ret = device_register(&pseudo_primary);
2716         if (ret < 0) {
2717                 printk(KERN_WARNING "scsi_debug: device_register error: %d\n",
2718                         ret);
2719                 goto free_vm;
2720         }
2721         ret = bus_register(&pseudo_lld_bus);
2722         if (ret < 0) {
2723                 printk(KERN_WARNING "scsi_debug: bus_register error: %d\n",
2724                         ret);
2725                 goto dev_unreg;
2726         }
2727         ret = driver_register(&sdebug_driverfs_driver);
2728         if (ret < 0) {
2729                 printk(KERN_WARNING "scsi_debug: driver_register error: %d\n",
2730                         ret);
2731                 goto bus_unreg;
2732         }
2733         ret = do_create_driverfs_files();
2734         if (ret < 0) {
2735                 printk(KERN_WARNING "scsi_debug: driver_create_file error: %d\n",
2736                         ret);
2737                 goto del_files;
2738         }
2739
2740         init_all_queued();
2741
2742         sdebug_driver_template.proc_name = (char *)sdebug_proc_name;
2743
2744         host_to_add = scsi_debug_add_host;
2745         scsi_debug_add_host = 0;
2746
2747         for (k = 0; k < host_to_add; k++) {
2748                 if (sdebug_add_adapter()) {
2749                         printk(KERN_ERR "scsi_debug_init: "
2750                                "sdebug_add_adapter failed k=%d\n", k);
2751                         break;
2752                 }
2753         }
2754
2755         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts) {
2756                 printk(KERN_INFO "scsi_debug_init: built %d host(s)\n",
2757                        scsi_debug_add_host);
2758         }
2759         return 0;
2760
2761 del_files:
2762         do_remove_driverfs_files();
2763         driver_unregister(&sdebug_driverfs_driver);
2764 bus_unreg:
2765         bus_unregister(&pseudo_lld_bus);
2766 dev_unreg:
2767         device_unregister(&pseudo_primary);
2768 free_vm:
2769         vfree(fake_storep);
2770
2771         return ret;
2772 }
2773
2774 static void __exit scsi_debug_exit(void)
2775 {
2776         int k = scsi_debug_add_host;
2777
2778         stop_all_queued();
2779         for (; k; k--)
2780                 sdebug_remove_adapter();
2781         do_remove_driverfs_files();
2782         driver_unregister(&sdebug_driverfs_driver);
2783         bus_unregister(&pseudo_lld_bus);
2784         device_unregister(&pseudo_primary);
2785
2786         vfree(fake_storep);
2787 }
2788
2789 device_initcall(scsi_debug_init);
2790 module_exit(scsi_debug_exit);
2791
2792 static void pseudo_0_release(struct device * dev)
2793 {
2794         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
2795                 printk(KERN_INFO "scsi_debug: pseudo_0_release() called\n");
2796 }
2797
2798 static struct device pseudo_primary = {
2799         .bus_id         = "pseudo_0",
2800         .release        = pseudo_0_release,
2801 };
2802
2803 static int pseudo_lld_bus_match(struct device *dev,
2804                           struct device_driver *dev_driver)
2805 {
2806         return 1;
2807 }
2808
2809 static struct bus_type pseudo_lld_bus = {
2810         .name = "pseudo",
2811         .match = pseudo_lld_bus_match,
2812         .probe = sdebug_driver_probe,
2813         .remove = sdebug_driver_remove,
2814 };
2815
2816 static void sdebug_release_adapter(struct device * dev)
2817 {
2818         struct sdebug_host_info *sdbg_host;
2819
2820         sdbg_host = to_sdebug_host(dev);
2821         kfree(sdbg_host);
2822 }
2823
2824 static int sdebug_add_adapter(void)
2825 {
2826         int k, devs_per_host;
2827         int error = 0;
2828         struct sdebug_host_info *sdbg_host;
2829         struct sdebug_dev_info *sdbg_devinfo;
2830         struct list_head *lh, *lh_sf;
2831
2832         sdbg_host = kzalloc(sizeof(*sdbg_host),GFP_KERNEL);
2833
2834         if (NULL == sdbg_host) {
2835                 printk(KERN_ERR "%s: out of memory at line %d\n",
2836                        __FUNCTION__, __LINE__);
2837                 return -ENOMEM;
2838         }
2839
2840         INIT_LIST_HEAD(&sdbg_host->dev_info_list);
2841
2842         devs_per_host = scsi_debug_num_tgts * scsi_debug_max_luns;
2843         for (k = 0; k < devs_per_host; k++) {
2844                 sdbg_devinfo = kzalloc(sizeof(*sdbg_devinfo),GFP_KERNEL);
2845                 if (NULL == sdbg_devinfo) {
2846                         printk(KERN_ERR "%s: out of memory at line %d\n",
2847                                __FUNCTION__, __LINE__);
2848                         error = -ENOMEM;
2849                         goto clean;
2850                 }
2851                 sdbg_devinfo->sdbg_host = sdbg_host;
2852                 list_add_tail(&sdbg_devinfo->dev_list,
2853                               &sdbg_host->dev_info_list);
2854         }
2855
2856         spin_lock(&sdebug_host_list_lock);
2857         list_add_tail(&sdbg_host->host_list, &sdebug_host_list);
2858         spin_unlock(&sdebug_host_list_lock);
2859
2860         sdbg_host->dev.bus = &pseudo_lld_bus;
2861         sdbg_host->dev.parent = &pseudo_primary;
2862         sdbg_host->dev.release = &sdebug_release_adapter;
2863         sprintf(sdbg_host->dev.bus_id, "adapter%d", scsi_debug_add_host);
2864
2865         error = device_register(&sdbg_host->dev);
2866
2867         if (error)
2868                 goto clean;
2869
2870         ++scsi_debug_add_host;
2871         return error;
2872
2873 clean:
2874         list_for_each_safe(lh, lh_sf, &sdbg_host->dev_info_list) {
2875                 sdbg_devinfo = list_entry(lh, struct sdebug_dev_info,
2876                                           dev_list);
2877                 list_del(&sdbg_devinfo->dev_list);
2878                 kfree(sdbg_devinfo);
2879         }
2880
2881         kfree(sdbg_host);
2882         return error;
2883 }
2884
2885 static void sdebug_remove_adapter(void)
2886 {
2887         struct sdebug_host_info * sdbg_host = NULL;
2888
2889         spin_lock(&sdebug_host_list_lock);
2890         if (!list_empty(&sdebug_host_list)) {
2891                 sdbg_host = list_entry(sdebug_host_list.prev,
2892                                        struct sdebug_host_info, host_list);
2893                 list_del(&sdbg_host->host_list);
2894         }
2895         spin_unlock(&sdebug_host_list_lock);
2896
2897         if (!sdbg_host)
2898                 return;
2899
2900         device_unregister(&sdbg_host->dev);
2901         --scsi_debug_add_host;
2902 }
2903
2904 static int sdebug_driver_probe(struct device * dev)
2905 {
2906         int error = 0;
2907         struct sdebug_host_info *sdbg_host;
2908         struct Scsi_Host *hpnt;
2909
2910         sdbg_host = to_sdebug_host(dev);
2911
2912         hpnt = scsi_host_alloc(&sdebug_driver_template, sizeof(sdbg_host));
2913         if (NULL == hpnt) {
2914                 printk(KERN_ERR "%s: scsi_register failed\n", __FUNCTION__);
2915                 error = -ENODEV;
2916                 return error;
2917         }
2918
2919         sdbg_host->shost = hpnt;
2920         *((struct sdebug_host_info **)hpnt->hostdata) = sdbg_host;
2921         if ((hpnt->this_id >= 0) && (scsi_debug_num_tgts > hpnt->this_id))
2922                 hpnt->max_id = scsi_debug_num_tgts + 1;
2923         else
2924                 hpnt->max_id = scsi_debug_num_tgts;
2925         hpnt->max_lun = SAM2_WLUN_REPORT_LUNS;  /* = scsi_debug_max_luns; */
2926
2927         error = scsi_add_host(hpnt, &sdbg_host->dev);
2928         if (error) {
2929                 printk(KERN_ERR "%s: scsi_add_host failed\n", __FUNCTION__);
2930                 error = -ENODEV;
2931                 scsi_host_put(hpnt);
2932         } else
2933                 scsi_scan_host(hpnt);
2934
2935
2936         return error;
2937 }
2938
2939 static int sdebug_driver_remove(struct device * dev)
2940 {
2941         struct list_head *lh, *lh_sf;
2942         struct sdebug_host_info *sdbg_host;
2943         struct sdebug_dev_info *sdbg_devinfo;
2944
2945         sdbg_host = to_sdebug_host(dev);
2946
2947         if (!sdbg_host) {
2948                 printk(KERN_ERR "%s: Unable to locate host info\n",
2949                        __FUNCTION__);
2950                 return -ENODEV;
2951         }
2952
2953         scsi_remove_host(sdbg_host->shost);
2954
2955         list_for_each_safe(lh, lh_sf, &sdbg_host->dev_info_list) {
2956                 sdbg_devinfo = list_entry(lh, struct sdebug_dev_info,
2957                                           dev_list);
2958                 list_del(&sdbg_devinfo->dev_list);
2959                 kfree(sdbg_devinfo);
2960         }
2961
2962         scsi_host_put(sdbg_host->shost);
2963         return 0;
2964 }
2965
2966 static void sdebug_max_tgts_luns(void)
2967 {
2968         struct sdebug_host_info * sdbg_host;
2969         struct Scsi_Host *hpnt;
2970
2971         spin_lock(&sdebug_host_list_lock);
2972         list_for_each_entry(sdbg_host, &sdebug_host_list, host_list) {
2973                 hpnt = sdbg_host->shost;
2974                 if ((hpnt->this_id >= 0) &&
2975                     (scsi_debug_num_tgts > hpnt->this_id))
2976                         hpnt->max_id = scsi_debug_num_tgts + 1;
2977                 else
2978                         hpnt->max_id = scsi_debug_num_tgts;
2979                 hpnt->max_lun = SAM2_WLUN_REPORT_LUNS; /* scsi_debug_max_luns; */
2980         }
2981         spin_unlock(&sdebug_host_list_lock);
2982 }