[PATCH] libata: if condition fix for ata_dev_identify()
[linux-2.6] / drivers / scsi / scsi_debug.c
1 /*
2  *  linux/kernel/scsi_debug.c
3  * vvvvvvvvvvvvvvvvvvvvvvv Original vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
4  *  Copyright (C) 1992  Eric Youngdale
5  *  Simulate a host adapter with 2 disks attached.  Do a lot of checking
6  *  to make sure that we are not getting blocks mixed up, and PANIC if
7  *  anything out of the ordinary is seen.
8  * ^^^^^^^^^^^^^^^^^^^^^^^ Original ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
9  *
10  *  This version is more generic, simulating a variable number of disk
11  *  (or disk like devices) sharing a common amount of RAM
12  *
13  *
14  *  For documentation see http://www.torque.net/sg/sdebug26.html
15  *
16  *   D. Gilbert (dpg) work for Magneto-Optical device test [20010421]
17  *   dpg: work for devfs large number of disks [20010809]
18  *        forked for lk 2.5 series [20011216, 20020101]
19  *        use vmalloc() more inquiry+mode_sense [20020302]
20  *        add timers for delayed responses [20020721]
21  *   Patrick Mansfield <patmans@us.ibm.com> max_luns+scsi_level [20021031]
22  *   Mike Anderson <andmike@us.ibm.com> sysfs work [20021118]
23  *   dpg: change style of boot options to "scsi_debug.num_tgts=2" and
24  *        module options to "modprobe scsi_debug num_tgts=2" [20021221]
25  */
26
27 #include <linux/config.h>
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 #ifndef LINUX_VERSION_CODE
52 #include <linux/version.h>
53 #endif
54
55 #include "scsi_logging.h"
56 #include "scsi_debug.h"
57
58 #define SCSI_DEBUG_VERSION "1.75"
59 static const char * scsi_debug_version_date = "20050113";
60
61 /* Additional Sense Code (ASC) used */
62 #define NO_ADDED_SENSE 0x0
63 #define UNRECOVERED_READ_ERR 0x11
64 #define INVALID_OPCODE 0x20
65 #define ADDR_OUT_OF_RANGE 0x21
66 #define INVALID_FIELD_IN_CDB 0x24
67 #define POWERON_RESET 0x29
68 #define SAVING_PARAMS_UNSUP 0x39
69 #define THRESHHOLD_EXCEEDED 0x5d
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
89 /* bit mask values for scsi_debug_opts */
90 #define SCSI_DEBUG_OPT_NOISE   1
91 #define SCSI_DEBUG_OPT_MEDIUM_ERR   2
92 #define SCSI_DEBUG_OPT_TIMEOUT   4
93 #define SCSI_DEBUG_OPT_RECOVERED_ERR   8
94 /* When "every_nth" > 0 then modulo "every_nth" commands:
95  *   - a no response is simulated if SCSI_DEBUG_OPT_TIMEOUT is set
96  *   - a RECOVERED_ERROR is simulated on successful read and write
97  *     commands if SCSI_DEBUG_OPT_RECOVERED_ERR is set.
98  *
99  * When "every_nth" < 0 then after "- every_nth" commands:
100  *   - a no response is simulated if SCSI_DEBUG_OPT_TIMEOUT is set
101  *   - a RECOVERED_ERROR is simulated on successful read and write
102  *     commands if SCSI_DEBUG_OPT_RECOVERED_ERR is set.
103  * This will continue until some other action occurs (e.g. the user
104  * writing a new value (other than -1 or 1) to every_nth via sysfs).
105  */
106
107 /* when 1==SCSI_DEBUG_OPT_MEDIUM_ERR, a medium error is simulated at this
108  * sector on read commands: */
109 #define OPT_MEDIUM_ERR_ADDR   0x1234 /* that's sector 4660 in decimal */
110
111 /* If REPORT LUNS has luns >= 256 it can choose "flat space" (value 1)
112  * or "peripheral device" addressing (value 0) */
113 #define SAM2_LUN_ADDRESS_METHOD 0
114
115 static int scsi_debug_add_host = DEF_NUM_HOST;
116 static int scsi_debug_delay = DEF_DELAY;
117 static int scsi_debug_dev_size_mb = DEF_DEV_SIZE_MB;
118 static int scsi_debug_every_nth = DEF_EVERY_NTH;
119 static int scsi_debug_max_luns = DEF_MAX_LUNS;
120 static int scsi_debug_num_parts = DEF_NUM_PARTS;
121 static int scsi_debug_num_tgts = DEF_NUM_TGTS; /* targets per host */
122 static int scsi_debug_opts = DEF_OPTS;
123 static int scsi_debug_scsi_level = DEF_SCSI_LEVEL;
124 static int scsi_debug_ptype = DEF_PTYPE; /* SCSI peripheral type (0==disk) */
125 static int scsi_debug_dsense = DEF_D_SENSE;
126
127 static int scsi_debug_cmnd_count = 0;
128
129 #define DEV_READONLY(TGT)      (0)
130 #define DEV_REMOVEABLE(TGT)    (0)
131
132 static unsigned long sdebug_store_size; /* in bytes */
133 static sector_t sdebug_capacity;        /* in sectors */
134
135 /* old BIOS stuff, kernel may get rid of them but some mode sense pages
136    may still need them */
137 static int sdebug_heads;                /* heads per disk */
138 static int sdebug_cylinders_per;        /* cylinders per surface */
139 static int sdebug_sectors_per;          /* sectors per cylinder */
140
141 /* default sector size is 512 bytes, 2**9 bytes */
142 #define POW2_SECT_SIZE 9
143 #define SECT_SIZE (1 << POW2_SECT_SIZE)
144 #define SECT_SIZE_PER(TGT) SECT_SIZE
145
146 #define SDEBUG_MAX_PARTS 4
147
148 #define SDEBUG_SENSE_LEN 32
149
150 struct sdebug_dev_info {
151         struct list_head dev_list;
152         unsigned char sense_buff[SDEBUG_SENSE_LEN];     /* weak nexus */
153         unsigned int channel;
154         unsigned int target;
155         unsigned int lun;
156         struct sdebug_host_info *sdbg_host;
157         char reset;
158         char used;
159 };
160
161 struct sdebug_host_info {
162         struct list_head host_list;
163         struct Scsi_Host *shost;
164         struct device dev;
165         struct list_head dev_info_list;
166 };
167
168 #define to_sdebug_host(d)       \
169         container_of(d, struct sdebug_host_info, dev)
170
171 static LIST_HEAD(sdebug_host_list);
172 static DEFINE_SPINLOCK(sdebug_host_list_lock);
173
174 typedef void (* done_funct_t) (struct scsi_cmnd *);
175
176 struct sdebug_queued_cmd {
177         int in_use;
178         struct timer_list cmnd_timer;
179         done_funct_t done_funct;
180         struct scsi_cmnd * a_cmnd;
181         int scsi_result;
182 };
183 static struct sdebug_queued_cmd queued_arr[SCSI_DEBUG_CANQUEUE];
184
185 static Scsi_Host_Template sdebug_driver_template = {
186         .proc_info =            scsi_debug_proc_info,
187         .name =                 "SCSI DEBUG",
188         .info =                 scsi_debug_info,
189         .slave_alloc =          scsi_debug_slave_alloc,
190         .slave_configure =      scsi_debug_slave_configure,
191         .slave_destroy =        scsi_debug_slave_destroy,
192         .ioctl =                scsi_debug_ioctl,
193         .queuecommand =         scsi_debug_queuecommand,
194         .eh_abort_handler =     scsi_debug_abort,
195         .eh_bus_reset_handler = scsi_debug_bus_reset,
196         .eh_device_reset_handler = scsi_debug_device_reset,
197         .eh_host_reset_handler = scsi_debug_host_reset,
198         .bios_param =           scsi_debug_biosparam,
199         .can_queue =            SCSI_DEBUG_CANQUEUE,
200         .this_id =              7,
201         .sg_tablesize =         64,
202         .cmd_per_lun =          3,
203         .max_sectors =          4096,
204         .unchecked_isa_dma =    0,
205         .use_clustering =       DISABLE_CLUSTERING,
206         .module =               THIS_MODULE,
207 };
208
209 static unsigned char * fake_storep;     /* ramdisk storage */
210
211 static int num_aborts = 0;
212 static int num_dev_resets = 0;
213 static int num_bus_resets = 0;
214 static int num_host_resets = 0;
215
216 static DEFINE_SPINLOCK(queued_arr_lock);
217 static DEFINE_RWLOCK(atomic_rw);
218
219 static char sdebug_proc_name[] = "scsi_debug";
220
221 static int sdebug_driver_probe(struct device *);
222 static int sdebug_driver_remove(struct device *);
223 static struct bus_type pseudo_lld_bus;
224
225 static struct device_driver sdebug_driverfs_driver = {
226         .name           = sdebug_proc_name,
227         .bus            = &pseudo_lld_bus,
228         .probe          = sdebug_driver_probe,
229         .remove         = sdebug_driver_remove,
230 };
231
232 static const int check_condition_result =
233                 (DRIVER_SENSE << 24) | SAM_STAT_CHECK_CONDITION;
234
235 /* function declarations */
236 static int resp_inquiry(struct scsi_cmnd * SCpnt, int target,
237                         struct sdebug_dev_info * devip);
238 static int resp_requests(struct scsi_cmnd * SCpnt,
239                          struct sdebug_dev_info * devip);
240 static int resp_readcap(struct scsi_cmnd * SCpnt,
241                         struct sdebug_dev_info * devip);
242 static int resp_mode_sense(struct scsi_cmnd * SCpnt, int target,
243                            struct sdebug_dev_info * devip);
244 static int resp_read(struct scsi_cmnd * SCpnt, int upper_blk, int block,
245                      int num, struct sdebug_dev_info * devip);
246 static int resp_write(struct scsi_cmnd * SCpnt, int upper_blk, int block,
247                       int num, struct sdebug_dev_info * devip);
248 static int resp_report_luns(struct scsi_cmnd * SCpnt,
249                             struct sdebug_dev_info * devip);
250 static int fill_from_dev_buffer(struct scsi_cmnd * scp, unsigned char * arr,
251                                 int arr_len);
252 static int fetch_to_dev_buffer(struct scsi_cmnd * scp, unsigned char * arr,
253                                int max_arr_len);
254 static void timer_intr_handler(unsigned long);
255 static struct sdebug_dev_info * devInfoReg(struct scsi_device * sdev);
256 static void mk_sense_buffer(struct sdebug_dev_info * devip, int key,
257                             int asc, int asq);
258 static int check_reset(struct scsi_cmnd * SCpnt,
259                        struct sdebug_dev_info * devip);
260 static int schedule_resp(struct scsi_cmnd * cmnd,
261                          struct sdebug_dev_info * devip,
262                          done_funct_t done, int scsi_result, int delta_jiff);
263 static void __init sdebug_build_parts(unsigned char * ramp);
264 static void __init init_all_queued(void);
265 static void stop_all_queued(void);
266 static int stop_queued_cmnd(struct scsi_cmnd * cmnd);
267 static int inquiry_evpd_83(unsigned char * arr, int dev_id_num,
268                            const char * dev_id_str, int dev_id_str_len);
269 static void do_create_driverfs_files(void);
270 static void do_remove_driverfs_files(void);
271
272 static int sdebug_add_adapter(void);
273 static void sdebug_remove_adapter(void);
274 static void sdebug_max_tgts_luns(void);
275
276 static struct device pseudo_primary;
277 static struct bus_type pseudo_lld_bus;
278
279
280 static
281 int scsi_debug_queuecommand(struct scsi_cmnd * SCpnt, done_funct_t done)
282 {
283         unsigned char *cmd = (unsigned char *) SCpnt->cmnd;
284         int block, upper_blk, num, k;
285         int errsts = 0;
286         int target = scmd_id(SCpnt);
287         struct sdebug_dev_info * devip = NULL;
288         int inj_recovered = 0;
289
290         if (done == NULL)
291                 return 0;       /* assume mid level reprocessing command */
292
293         if ((SCSI_DEBUG_OPT_NOISE & scsi_debug_opts) && cmd) {
294                 printk(KERN_INFO "scsi_debug: cmd ");
295                 for (k = 0, num = SCpnt->cmd_len; k < num; ++k)
296                         printk("%02x ", (int)cmd[k]);
297                 printk("\n");
298         }
299         if(target == sdebug_driver_template.this_id) {
300                 printk(KERN_INFO "scsi_debug: initiator's id used as "
301                        "target!\n");
302                 return schedule_resp(SCpnt, NULL, done,
303                                      DID_NO_CONNECT << 16, 0);
304         }
305
306         if (SCpnt->device->lun >= scsi_debug_max_luns)
307                 return schedule_resp(SCpnt, NULL, done,
308                                      DID_NO_CONNECT << 16, 0);
309         devip = devInfoReg(SCpnt->device);
310         if (NULL == devip)
311                 return schedule_resp(SCpnt, NULL, done,
312                                      DID_NO_CONNECT << 16, 0);
313
314         if ((scsi_debug_every_nth != 0) &&
315             (++scsi_debug_cmnd_count >= abs(scsi_debug_every_nth))) {
316                 scsi_debug_cmnd_count = 0;
317                 if (scsi_debug_every_nth < -1)
318                         scsi_debug_every_nth = -1;
319                 if (SCSI_DEBUG_OPT_TIMEOUT & scsi_debug_opts)
320                         return 0; /* ignore command causing timeout */
321                 else if (SCSI_DEBUG_OPT_RECOVERED_ERR & scsi_debug_opts)
322                         inj_recovered = 1; /* to reads and writes below */
323         }
324
325         switch (*cmd) {
326         case INQUIRY:     /* mandatory, ignore unit attention */
327                 errsts = resp_inquiry(SCpnt, target, devip);
328                 break;
329         case REQUEST_SENSE:     /* mandatory, ignore unit attention */
330                 errsts = resp_requests(SCpnt, devip);
331                 break;
332         case REZERO_UNIT:       /* actually this is REWIND for SSC */
333         case START_STOP:
334                 errsts = check_reset(SCpnt, devip);
335                 break;
336         case ALLOW_MEDIUM_REMOVAL:
337                 if ((errsts = check_reset(SCpnt, devip)))
338                         break;
339                 if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
340                         printk(KERN_INFO "scsi_debug: Medium removal %s\n",
341                                 cmd[4] ? "inhibited" : "enabled");
342                 break;
343         case SEND_DIAGNOSTIC:     /* mandatory */
344                 errsts = check_reset(SCpnt, devip);
345                 break;
346         case TEST_UNIT_READY:     /* mandatory */
347                 errsts = check_reset(SCpnt, devip);
348                 break;
349         case RESERVE:
350                 errsts = check_reset(SCpnt, devip);
351                 break;
352         case RESERVE_10:
353                 errsts = check_reset(SCpnt, devip);
354                 break;
355         case RELEASE:
356                 errsts = check_reset(SCpnt, devip);
357                 break;
358         case RELEASE_10:
359                 errsts = check_reset(SCpnt, devip);
360                 break;
361         case READ_CAPACITY:
362                 errsts = resp_readcap(SCpnt, devip);
363                 break;
364         case READ_16:
365         case READ_12:
366         case READ_10:
367         case READ_6:
368                 if ((errsts = check_reset(SCpnt, devip)))
369                         break;
370                 upper_blk = 0;
371                 if ((*cmd) == READ_16) {
372                         upper_blk = cmd[5] + (cmd[4] << 8) +
373                                     (cmd[3] << 16) + (cmd[2] << 24);
374                         block = cmd[9] + (cmd[8] << 8) +
375                                 (cmd[7] << 16) + (cmd[6] << 24);
376                         num = cmd[13] + (cmd[12] << 8) +
377                                 (cmd[11] << 16) + (cmd[10] << 24);
378                 } else if ((*cmd) == READ_12) {
379                         block = cmd[5] + (cmd[4] << 8) +
380                                 (cmd[3] << 16) + (cmd[2] << 24);
381                         num = cmd[9] + (cmd[8] << 8) +
382                                 (cmd[7] << 16) + (cmd[6] << 24);
383                 } else if ((*cmd) == READ_10) {
384                         block = cmd[5] + (cmd[4] << 8) +
385                                 (cmd[3] << 16) + (cmd[2] << 24);
386                         num = cmd[8] + (cmd[7] << 8);
387                 } else {
388                         block = cmd[3] + (cmd[2] << 8) +
389                                 ((cmd[1] & 0x1f) << 16);
390                         num = cmd[4];
391                 }
392                 errsts = resp_read(SCpnt, upper_blk, block, num, devip);
393                 if (inj_recovered && (0 == errsts)) {
394                         mk_sense_buffer(devip, RECOVERED_ERROR,
395                                         THRESHHOLD_EXCEEDED, 0);
396                         errsts = check_condition_result;
397                 }
398                 break;
399         case REPORT_LUNS:       /* mandatory, ignore unit attention */
400                 errsts = resp_report_luns(SCpnt, devip);
401                 break;
402         case VERIFY:            /* 10 byte SBC-2 command */
403                 errsts = check_reset(SCpnt, devip);
404                 break;
405         case WRITE_16:
406         case WRITE_12:
407         case WRITE_10:
408         case WRITE_6:
409                 if ((errsts = check_reset(SCpnt, devip)))
410                         break;
411                 upper_blk = 0;
412                 if ((*cmd) == WRITE_16) {
413                         upper_blk = cmd[5] + (cmd[4] << 8) +
414                                     (cmd[3] << 16) + (cmd[2] << 24);
415                         block = cmd[9] + (cmd[8] << 8) +
416                                 (cmd[7] << 16) + (cmd[6] << 24);
417                         num = cmd[13] + (cmd[12] << 8) +
418                                 (cmd[11] << 16) + (cmd[10] << 24);
419                 } else if ((*cmd) == WRITE_12) {
420                         block = cmd[5] + (cmd[4] << 8) +
421                                 (cmd[3] << 16) + (cmd[2] << 24);
422                         num = cmd[9] + (cmd[8] << 8) +
423                                 (cmd[7] << 16) + (cmd[6] << 24);
424                 } else if ((*cmd) == WRITE_10) {
425                         block = cmd[5] + (cmd[4] << 8) +
426                                 (cmd[3] << 16) + (cmd[2] << 24);
427                         num = cmd[8] + (cmd[7] << 8);
428                 } else {
429                         block = cmd[3] + (cmd[2] << 8) +
430                                 ((cmd[1] & 0x1f) << 16);
431                         num = cmd[4];
432                 }
433                 errsts = resp_write(SCpnt, upper_blk, block, num, devip);
434                 if (inj_recovered && (0 == errsts)) {
435                         mk_sense_buffer(devip, RECOVERED_ERROR,
436                                         THRESHHOLD_EXCEEDED, 0);
437                         errsts = check_condition_result;
438                 }
439                 break;
440         case MODE_SENSE:
441         case MODE_SENSE_10:
442                 errsts = resp_mode_sense(SCpnt, target, devip);
443                 break;
444         case SYNCHRONIZE_CACHE:
445                 errsts = check_reset(SCpnt, devip);
446                 break;
447         default:
448                 if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
449                         printk(KERN_INFO "scsi_debug: Opcode: 0x%x not "
450                                "supported\n", *cmd);
451                 if ((errsts = check_reset(SCpnt, devip)))
452                         break;  /* Unit attention takes precedence */
453                 mk_sense_buffer(devip, ILLEGAL_REQUEST, INVALID_OPCODE, 0);
454                 errsts = check_condition_result;
455                 break;
456         }
457         return schedule_resp(SCpnt, devip, done, errsts, scsi_debug_delay);
458 }
459
460 static int scsi_debug_ioctl(struct scsi_device *dev, int cmd, void __user *arg)
461 {
462         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts) {
463                 printk(KERN_INFO "scsi_debug: ioctl: cmd=0x%x\n", cmd);
464         }
465         return -EINVAL;
466         /* return -ENOTTY; // correct return but upsets fdisk */
467 }
468
469 static int check_reset(struct scsi_cmnd * SCpnt, struct sdebug_dev_info * devip)
470 {
471         if (devip->reset) {
472                 if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
473                         printk(KERN_INFO "scsi_debug: Reporting Unit "
474                                "attention: power on reset\n");
475                 devip->reset = 0;
476                 mk_sense_buffer(devip, UNIT_ATTENTION, POWERON_RESET, 0);
477                 return check_condition_result;
478         }
479         return 0;
480 }
481
482 /* Returns 0 if ok else (DID_ERROR << 16). Sets scp->resid . */
483 static int fill_from_dev_buffer(struct scsi_cmnd * scp, unsigned char * arr,
484                                 int arr_len)
485 {
486         int k, req_len, act_len, len, active;
487         void * kaddr;
488         void * kaddr_off;
489         struct scatterlist * sgpnt;
490
491         if (0 == scp->request_bufflen)
492                 return 0;
493         if (NULL == scp->request_buffer)
494                 return (DID_ERROR << 16);
495         if (! ((scp->sc_data_direction == DMA_BIDIRECTIONAL) ||
496               (scp->sc_data_direction == DMA_FROM_DEVICE)))
497                 return (DID_ERROR << 16);
498         if (0 == scp->use_sg) {
499                 req_len = scp->request_bufflen;
500                 act_len = (req_len < arr_len) ? req_len : arr_len;
501                 memcpy(scp->request_buffer, arr, act_len);
502                 scp->resid = req_len - act_len;
503                 return 0;
504         }
505         sgpnt = (struct scatterlist *)scp->request_buffer;
506         active = 1;
507         for (k = 0, req_len = 0, act_len = 0; k < scp->use_sg; ++k, ++sgpnt) {
508                 if (active) {
509                         kaddr = (unsigned char *)
510                                 kmap_atomic(sgpnt->page, KM_USER0);
511                         if (NULL == kaddr)
512                                 return (DID_ERROR << 16);
513                         kaddr_off = (unsigned char *)kaddr + sgpnt->offset;
514                         len = sgpnt->length;
515                         if ((req_len + len) > arr_len) {
516                                 active = 0;
517                                 len = arr_len - req_len;
518                         }
519                         memcpy(kaddr_off, arr + req_len, len);
520                         kunmap_atomic(kaddr, KM_USER0);
521                         act_len += len;
522                 }
523                 req_len += sgpnt->length;
524         }
525         scp->resid = req_len - act_len;
526         return 0;
527 }
528
529 /* Returns number of bytes fetched into 'arr' or -1 if error. */
530 static int fetch_to_dev_buffer(struct scsi_cmnd * scp, unsigned char * arr,
531                                int max_arr_len)
532 {
533         int k, req_len, len, fin;
534         void * kaddr;
535         void * kaddr_off;
536         struct scatterlist * sgpnt;
537
538         if (0 == scp->request_bufflen)
539                 return 0;
540         if (NULL == scp->request_buffer)
541                 return -1;
542         if (! ((scp->sc_data_direction == DMA_BIDIRECTIONAL) ||
543               (scp->sc_data_direction == DMA_TO_DEVICE)))
544                 return -1;
545         if (0 == scp->use_sg) {
546                 req_len = scp->request_bufflen;
547                 len = (req_len < max_arr_len) ? req_len : max_arr_len;
548                 memcpy(arr, scp->request_buffer, len);
549                 return len;
550         }
551         sgpnt = (struct scatterlist *)scp->request_buffer;
552         for (k = 0, req_len = 0, fin = 0; k < scp->use_sg; ++k, ++sgpnt) {
553                 kaddr = (unsigned char *)kmap_atomic(sgpnt->page, KM_USER0);
554                 if (NULL == kaddr)
555                         return -1;
556                 kaddr_off = (unsigned char *)kaddr + sgpnt->offset;
557                 len = sgpnt->length;
558                 if ((req_len + len) > max_arr_len) {
559                         len = max_arr_len - req_len;
560                         fin = 1;
561                 }
562                 memcpy(arr + req_len, kaddr_off, len);
563                 kunmap_atomic(kaddr, KM_USER0);
564                 if (fin)
565                         return req_len + len;
566                 req_len += sgpnt->length;
567         }
568         return req_len;
569 }
570
571
572 static const char * inq_vendor_id = "Linux   ";
573 static const char * inq_product_id = "scsi_debug      ";
574 static const char * inq_product_rev = "0004";
575
576 static int inquiry_evpd_83(unsigned char * arr, int dev_id_num,
577                            const char * dev_id_str, int dev_id_str_len)
578 {
579         int num;
580
581         /* Two identification descriptors: */
582         /* T10 vendor identifier field format (faked) */
583         arr[0] = 0x2;   /* ASCII */
584         arr[1] = 0x1;
585         arr[2] = 0x0;
586         memcpy(&arr[4], inq_vendor_id, 8);
587         memcpy(&arr[12], inq_product_id, 16);
588         memcpy(&arr[28], dev_id_str, dev_id_str_len);
589         num = 8 + 16 + dev_id_str_len;
590         arr[3] = num;
591         num += 4;
592         /* NAA IEEE registered identifier (faked) */
593         arr[num] = 0x1; /* binary */
594         arr[num + 1] = 0x3;
595         arr[num + 2] = 0x0;
596         arr[num + 3] = 0x8;
597         arr[num + 4] = 0x51;    /* ieee company id=0x123456 (faked) */
598         arr[num + 5] = 0x23;
599         arr[num + 6] = 0x45;
600         arr[num + 7] = 0x60;
601         arr[num + 8] = (dev_id_num >> 24);
602         arr[num + 9] = (dev_id_num >> 16) & 0xff;
603         arr[num + 10] = (dev_id_num >> 8) & 0xff;
604         arr[num + 11] = dev_id_num & 0xff;
605         return num + 12;
606 }
607
608
609 #define SDEBUG_LONG_INQ_SZ 96
610 #define SDEBUG_MAX_INQ_ARR_SZ 128
611
612 static int resp_inquiry(struct scsi_cmnd * scp, int target,
613                         struct sdebug_dev_info * devip)
614 {
615         unsigned char pq_pdt;
616         unsigned char arr[SDEBUG_MAX_INQ_ARR_SZ];
617         unsigned char *cmd = (unsigned char *)scp->cmnd;
618         int alloc_len;
619
620         alloc_len = (cmd[3] << 8) + cmd[4];
621         memset(arr, 0, SDEBUG_MAX_INQ_ARR_SZ);
622         pq_pdt = (scsi_debug_ptype & 0x1f);
623         arr[0] = pq_pdt;
624         if (0x2 & cmd[1]) {  /* CMDDT bit set */
625                 mk_sense_buffer(devip, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB,
626                                 0);
627                 return check_condition_result;
628         } else if (0x1 & cmd[1]) {  /* EVPD bit set */
629                 int dev_id_num, len;
630                 char dev_id_str[6];
631                 
632                 dev_id_num = ((devip->sdbg_host->shost->host_no + 1) * 2000) +
633                              (devip->target * 1000) + devip->lun;
634                 len = scnprintf(dev_id_str, 6, "%d", dev_id_num);
635                 if (0 == cmd[2]) { /* supported vital product data pages */
636                         arr[3] = 3;
637                         arr[4] = 0x0; /* this page */
638                         arr[5] = 0x80; /* unit serial number */
639                         arr[6] = 0x83; /* device identification */
640                 } else if (0x80 == cmd[2]) { /* unit serial number */
641                         arr[1] = 0x80;
642                         arr[3] = len;
643                         memcpy(&arr[4], dev_id_str, len);
644                 } else if (0x83 == cmd[2]) { /* device identification */
645                         arr[1] = 0x83;
646                         arr[3] = inquiry_evpd_83(&arr[4], dev_id_num,
647                                                  dev_id_str, len);
648                 } else {
649                         /* Illegal request, invalid field in cdb */
650                         mk_sense_buffer(devip, ILLEGAL_REQUEST,
651                                         INVALID_FIELD_IN_CDB, 0);
652                         return check_condition_result;
653                 }
654                 return fill_from_dev_buffer(scp, arr,
655                             min(alloc_len, SDEBUG_MAX_INQ_ARR_SZ));
656         }
657         /* drops through here for a standard inquiry */
658         arr[1] = DEV_REMOVEABLE(target) ? 0x80 : 0;     /* Removable disk */
659         arr[2] = scsi_debug_scsi_level;
660         arr[3] = 2;    /* response_data_format==2 */
661         arr[4] = SDEBUG_LONG_INQ_SZ - 5;
662         arr[6] = 0x1; /* claim: ADDR16 */
663         /* arr[6] |= 0x40; ... claim: EncServ (enclosure services) */
664         arr[7] = 0x3a; /* claim: WBUS16, SYNC, LINKED + CMDQUE */
665         memcpy(&arr[8], inq_vendor_id, 8);
666         memcpy(&arr[16], inq_product_id, 16);
667         memcpy(&arr[32], inq_product_rev, 4);
668         /* version descriptors (2 bytes each) follow */
669         arr[58] = 0x0; arr[59] = 0x40; /* SAM-2 */
670         arr[60] = 0x3; arr[61] = 0x0;  /* SPC-3 */
671         if (scsi_debug_ptype == 0) {
672                 arr[62] = 0x1; arr[63] = 0x80; /* SBC */
673         } else if (scsi_debug_ptype == 1) {
674                 arr[62] = 0x2; arr[63] = 0x00; /* SSC */
675         }
676         return fill_from_dev_buffer(scp, arr,
677                             min(alloc_len, SDEBUG_LONG_INQ_SZ));
678 }
679
680 static int resp_requests(struct scsi_cmnd * scp,
681                          struct sdebug_dev_info * devip)
682 {
683         unsigned char * sbuff;
684         unsigned char *cmd = (unsigned char *)scp->cmnd;
685         unsigned char arr[SDEBUG_SENSE_LEN];
686         int len = 18;
687
688         memset(arr, 0, SDEBUG_SENSE_LEN);
689         if (devip->reset == 1)
690                 mk_sense_buffer(devip, 0, NO_ADDED_SENSE, 0);
691         sbuff = devip->sense_buff;
692         if ((cmd[1] & 1) && (! scsi_debug_dsense)) {
693                 /* DESC bit set and sense_buff in fixed format */
694                 arr[0] = 0x72;
695                 arr[1] = sbuff[2];     /* sense key */
696                 arr[2] = sbuff[12];    /* asc */
697                 arr[3] = sbuff[13];    /* ascq */
698                 len = 8;
699         } else
700                 memcpy(arr, sbuff, SDEBUG_SENSE_LEN);
701         mk_sense_buffer(devip, 0, NO_ADDED_SENSE, 0);
702         return fill_from_dev_buffer(scp, arr, len);
703 }
704
705 #define SDEBUG_READCAP_ARR_SZ 8
706 static int resp_readcap(struct scsi_cmnd * scp,
707                         struct sdebug_dev_info * devip)
708 {
709         unsigned char arr[SDEBUG_READCAP_ARR_SZ];
710         unsigned long capac;
711         int errsts;
712
713         if ((errsts = check_reset(scp, devip)))
714                 return errsts;
715         memset(arr, 0, SDEBUG_READCAP_ARR_SZ);
716         capac = (unsigned long)sdebug_capacity - 1;
717         arr[0] = (capac >> 24);
718         arr[1] = (capac >> 16) & 0xff;
719         arr[2] = (capac >> 8) & 0xff;
720         arr[3] = capac & 0xff;
721         arr[6] = (SECT_SIZE_PER(target) >> 8) & 0xff;
722         arr[7] = SECT_SIZE_PER(target) & 0xff;
723         return fill_from_dev_buffer(scp, arr, SDEBUG_READCAP_ARR_SZ);
724 }
725
726 /* <<Following mode page info copied from ST318451LW>> */
727
728 static int resp_err_recov_pg(unsigned char * p, int pcontrol, int target)
729 {       /* Read-Write Error Recovery page for mode_sense */
730         unsigned char err_recov_pg[] = {0x1, 0xa, 0xc0, 11, 240, 0, 0, 0,
731                                         5, 0, 0xff, 0xff};
732
733         memcpy(p, err_recov_pg, sizeof(err_recov_pg));
734         if (1 == pcontrol)
735                 memset(p + 2, 0, sizeof(err_recov_pg) - 2);
736         return sizeof(err_recov_pg);
737 }
738
739 static int resp_disconnect_pg(unsigned char * p, int pcontrol, int target)
740 {       /* Disconnect-Reconnect page for mode_sense */
741         unsigned char disconnect_pg[] = {0x2, 0xe, 128, 128, 0, 10, 0, 0,
742                                          0, 0, 0, 0, 0, 0, 0, 0};
743
744         memcpy(p, disconnect_pg, sizeof(disconnect_pg));
745         if (1 == pcontrol)
746                 memset(p + 2, 0, sizeof(disconnect_pg) - 2);
747         return sizeof(disconnect_pg);
748 }
749
750 static int resp_format_pg(unsigned char * p, int pcontrol, int target)
751 {       /* Format device page for mode_sense */
752         unsigned char format_pg[] = {0x3, 0x16, 0, 0, 0, 0, 0, 0,
753                                      0, 0, 0, 0, 0, 0, 0, 0,
754                                      0, 0, 0, 0, 0x40, 0, 0, 0};
755
756         memcpy(p, format_pg, sizeof(format_pg));
757         p[10] = (sdebug_sectors_per >> 8) & 0xff;
758         p[11] = sdebug_sectors_per & 0xff;
759         p[12] = (SECT_SIZE >> 8) & 0xff;
760         p[13] = SECT_SIZE & 0xff;
761         if (DEV_REMOVEABLE(target))
762                 p[20] |= 0x20; /* should agree with INQUIRY */
763         if (1 == pcontrol)
764                 memset(p + 2, 0, sizeof(format_pg) - 2);
765         return sizeof(format_pg);
766 }
767
768 static int resp_caching_pg(unsigned char * p, int pcontrol, int target)
769 {       /* Caching page for mode_sense */
770         unsigned char caching_pg[] = {0x8, 18, 0x14, 0, 0xff, 0xff, 0, 0,
771                 0xff, 0xff, 0xff, 0xff, 0x80, 0x14, 0, 0,     0, 0, 0, 0};
772
773         memcpy(p, caching_pg, sizeof(caching_pg));
774         if (1 == pcontrol)
775                 memset(p + 2, 0, sizeof(caching_pg) - 2);
776         return sizeof(caching_pg);
777 }
778
779 static int resp_ctrl_m_pg(unsigned char * p, int pcontrol, int target)
780 {       /* Control mode page for mode_sense */
781         unsigned char ctrl_m_pg[] = {0xa, 10, 2, 0, 0, 0, 0, 0,
782                                      0, 0, 0x2, 0x4b};
783
784         if (scsi_debug_dsense)
785                 ctrl_m_pg[2] |= 0x4;
786         memcpy(p, ctrl_m_pg, sizeof(ctrl_m_pg));
787         if (1 == pcontrol)
788                 memset(p + 2, 0, sizeof(ctrl_m_pg) - 2);
789         return sizeof(ctrl_m_pg);
790 }
791
792 static int resp_iec_m_pg(unsigned char * p, int pcontrol, int target)
793 {       /* Informational Exceptions control mode page for mode_sense */
794         unsigned char iec_m_pg[] = {0x1c, 0xa, 0x08, 0, 0, 0, 0, 0,
795                                     0, 0, 0x0, 0x0};
796         memcpy(p, iec_m_pg, sizeof(iec_m_pg));
797         if (1 == pcontrol)
798                 memset(p + 2, 0, sizeof(iec_m_pg) - 2);
799         return sizeof(iec_m_pg);
800 }
801
802 #define SDEBUG_MAX_MSENSE_SZ 256
803
804 static int resp_mode_sense(struct scsi_cmnd * scp, int target,
805                            struct sdebug_dev_info * devip)
806 {
807         unsigned char dbd;
808         int pcontrol, pcode, subpcode;
809         unsigned char dev_spec;
810         int alloc_len, msense_6, offset, len, errsts;
811         unsigned char * ap;
812         unsigned char arr[SDEBUG_MAX_MSENSE_SZ];
813         unsigned char *cmd = (unsigned char *)scp->cmnd;
814
815         if ((errsts = check_reset(scp, devip)))
816                 return errsts;
817         dbd = cmd[1] & 0x8;
818         pcontrol = (cmd[2] & 0xc0) >> 6;
819         pcode = cmd[2] & 0x3f;
820         subpcode = cmd[3];
821         msense_6 = (MODE_SENSE == cmd[0]);
822         alloc_len = msense_6 ? cmd[4] : ((cmd[7] << 8) | cmd[8]);
823         memset(arr, 0, SDEBUG_MAX_MSENSE_SZ);
824         if (0x3 == pcontrol) {  /* Saving values not supported */
825                 mk_sense_buffer(devip, ILLEGAL_REQUEST, SAVING_PARAMS_UNSUP,
826                                 0);
827                 return check_condition_result;
828         }
829         dev_spec = DEV_READONLY(target) ? 0x80 : 0x0;
830         if (msense_6) {
831                 arr[2] = dev_spec;
832                 offset = 4;
833         } else {
834                 arr[3] = dev_spec;
835                 offset = 8;
836         }
837         ap = arr + offset;
838
839         if (0 != subpcode) { /* TODO: Control Extension page */
840                 mk_sense_buffer(devip, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB,
841                                 0);
842                 return check_condition_result;
843         }
844         switch (pcode) {
845         case 0x1:       /* Read-Write error recovery page, direct access */
846                 len = resp_err_recov_pg(ap, pcontrol, target);
847                 offset += len;
848                 break;
849         case 0x2:       /* Disconnect-Reconnect page, all devices */
850                 len = resp_disconnect_pg(ap, pcontrol, target);
851                 offset += len;
852                 break;
853         case 0x3:       /* Format device page, direct access */
854                 len = resp_format_pg(ap, pcontrol, target);
855                 offset += len;
856                 break;
857         case 0x8:       /* Caching page, direct access */
858                 len = resp_caching_pg(ap, pcontrol, target);
859                 offset += len;
860                 break;
861         case 0xa:       /* Control Mode page, all devices */
862                 len = resp_ctrl_m_pg(ap, pcontrol, target);
863                 offset += len;
864                 break;
865         case 0x1c:      /* Informational Exceptions Mode page, all devices */
866                 len = resp_iec_m_pg(ap, pcontrol, target);
867                 offset += len;
868                 break;
869         case 0x3f:      /* Read all Mode pages */
870                 len = resp_err_recov_pg(ap, pcontrol, target);
871                 len += resp_disconnect_pg(ap + len, pcontrol, target);
872                 len += resp_format_pg(ap + len, pcontrol, target);
873                 len += resp_caching_pg(ap + len, pcontrol, target);
874                 len += resp_ctrl_m_pg(ap + len, pcontrol, target);
875                 len += resp_iec_m_pg(ap + len, pcontrol, target);
876                 offset += len;
877                 break;
878         default:
879                 mk_sense_buffer(devip, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB,
880                                 0);
881                 return check_condition_result;
882         }
883         if (msense_6)
884                 arr[0] = offset - 1;
885         else {
886                 arr[0] = ((offset - 2) >> 8) & 0xff;
887                 arr[1] = (offset - 2) & 0xff;
888         }
889         return fill_from_dev_buffer(scp, arr, min(alloc_len, offset));
890 }
891
892 static int resp_read(struct scsi_cmnd * SCpnt, int upper_blk, int block,
893                      int num, struct sdebug_dev_info * devip)
894 {
895         unsigned long iflags;
896         int ret;
897
898         if (upper_blk || (block + num > sdebug_capacity)) {
899                 mk_sense_buffer(devip, ILLEGAL_REQUEST, ADDR_OUT_OF_RANGE,
900                                 0);
901                 return check_condition_result;
902         }
903         if ((SCSI_DEBUG_OPT_MEDIUM_ERR & scsi_debug_opts) &&
904             (block <= OPT_MEDIUM_ERR_ADDR) &&
905             ((block + num) > OPT_MEDIUM_ERR_ADDR)) {
906                 mk_sense_buffer(devip, MEDIUM_ERROR, UNRECOVERED_READ_ERR,
907                                 0);
908                 /* claim unrecoverable read error */
909                 return check_condition_result;
910         }
911         read_lock_irqsave(&atomic_rw, iflags);
912         ret = fill_from_dev_buffer(SCpnt, fake_storep + (block * SECT_SIZE),
913                                    num * SECT_SIZE);
914         read_unlock_irqrestore(&atomic_rw, iflags);
915         return ret;
916 }
917
918 static int resp_write(struct scsi_cmnd * SCpnt, int upper_blk, int block,
919                       int num, struct sdebug_dev_info * devip)
920 {
921         unsigned long iflags;
922         int res;
923
924         if (upper_blk || (block + num > sdebug_capacity)) {
925                 mk_sense_buffer(devip, ILLEGAL_REQUEST, ADDR_OUT_OF_RANGE,
926                                 0);
927                 return check_condition_result;
928         }
929
930         write_lock_irqsave(&atomic_rw, iflags);
931         res = fetch_to_dev_buffer(SCpnt, fake_storep + (block * SECT_SIZE),
932                                   num * SECT_SIZE);
933         write_unlock_irqrestore(&atomic_rw, iflags);
934         if (-1 == res)
935                 return (DID_ERROR << 16);
936         else if ((res < (num * SECT_SIZE)) &&
937                  (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts))
938                 printk(KERN_INFO "scsi_debug: write: cdb indicated=%d, "
939                        " IO sent=%d bytes\n", num * SECT_SIZE, res);
940         return 0;
941 }
942
943 #define SDEBUG_RLUN_ARR_SZ 128
944
945 static int resp_report_luns(struct scsi_cmnd * scp,
946                             struct sdebug_dev_info * devip)
947 {
948         unsigned int alloc_len;
949         int lun_cnt, i, upper;
950         unsigned char *cmd = (unsigned char *)scp->cmnd;
951         int select_report = (int)cmd[2];
952         struct scsi_lun *one_lun;
953         unsigned char arr[SDEBUG_RLUN_ARR_SZ];
954
955         alloc_len = cmd[9] + (cmd[8] << 8) + (cmd[7] << 16) + (cmd[6] << 24);
956         if ((alloc_len < 16) || (select_report > 2)) {
957                 mk_sense_buffer(devip, ILLEGAL_REQUEST, INVALID_FIELD_IN_CDB,
958                                 0);
959                 return check_condition_result;
960         }
961         /* can produce response with up to 16k luns (lun 0 to lun 16383) */
962         memset(arr, 0, SDEBUG_RLUN_ARR_SZ);
963         lun_cnt = scsi_debug_max_luns;
964         arr[2] = ((sizeof(struct scsi_lun) * lun_cnt) >> 8) & 0xff;
965         arr[3] = (sizeof(struct scsi_lun) * lun_cnt) & 0xff;
966         lun_cnt = min((int)((SDEBUG_RLUN_ARR_SZ - 8) /
967                             sizeof(struct scsi_lun)), lun_cnt);
968         one_lun = (struct scsi_lun *) &arr[8];
969         for (i = 0; i < lun_cnt; i++) {
970                 upper = (i >> 8) & 0x3f;
971                 if (upper)
972                         one_lun[i].scsi_lun[0] =
973                             (upper | (SAM2_LUN_ADDRESS_METHOD << 6));
974                 one_lun[i].scsi_lun[1] = i & 0xff;
975         }
976         return fill_from_dev_buffer(scp, arr,
977                                     min((int)alloc_len, SDEBUG_RLUN_ARR_SZ));
978 }
979
980 /* When timer goes off this function is called. */
981 static void timer_intr_handler(unsigned long indx)
982 {
983         struct sdebug_queued_cmd * sqcp;
984         unsigned long iflags;
985
986         if (indx >= SCSI_DEBUG_CANQUEUE) {
987                 printk(KERN_ERR "scsi_debug:timer_intr_handler: indx too "
988                        "large\n");
989                 return;
990         }
991         spin_lock_irqsave(&queued_arr_lock, iflags);
992         sqcp = &queued_arr[(int)indx];
993         if (! sqcp->in_use) {
994                 printk(KERN_ERR "scsi_debug:timer_intr_handler: Unexpected "
995                        "interrupt\n");
996                 spin_unlock_irqrestore(&queued_arr_lock, iflags);
997                 return;
998         }
999         sqcp->in_use = 0;
1000         if (sqcp->done_funct) {
1001                 sqcp->a_cmnd->result = sqcp->scsi_result;
1002                 sqcp->done_funct(sqcp->a_cmnd); /* callback to mid level */
1003         }
1004         sqcp->done_funct = NULL;
1005         spin_unlock_irqrestore(&queued_arr_lock, iflags);
1006 }
1007
1008 static int scsi_debug_slave_alloc(struct scsi_device * sdp)
1009 {
1010         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1011                 sdev_printk(KERN_INFO, sdp, "scsi_debug: slave_alloc\n");
1012         return 0;
1013 }
1014
1015 static int scsi_debug_slave_configure(struct scsi_device * sdp)
1016 {
1017         struct sdebug_dev_info * devip;
1018
1019         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1020                 sdev_printk(KERN_INFO, sdp, "scsi_debug: slave_configure\n");
1021         if (sdp->host->max_cmd_len != SCSI_DEBUG_MAX_CMD_LEN)
1022                 sdp->host->max_cmd_len = SCSI_DEBUG_MAX_CMD_LEN;
1023         devip = devInfoReg(sdp);
1024         sdp->hostdata = devip;
1025         if (sdp->host->cmd_per_lun)
1026                 scsi_adjust_queue_depth(sdp, SDEBUG_TAGGED_QUEUING,
1027                                         sdp->host->cmd_per_lun);
1028         return 0;
1029 }
1030
1031 static void scsi_debug_slave_destroy(struct scsi_device * sdp)
1032 {
1033         struct sdebug_dev_info * devip =
1034                                 (struct sdebug_dev_info *)sdp->hostdata;
1035
1036         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1037                 sdev_printk(KERN_INFO, sdp, "scsi_debug: slave_destroy\n");
1038         if (devip) {
1039                 /* make this slot avaliable for re-use */
1040                 devip->used = 0;
1041                 sdp->hostdata = NULL;
1042         }
1043 }
1044
1045 static struct sdebug_dev_info * devInfoReg(struct scsi_device * sdev)
1046 {
1047         struct sdebug_host_info * sdbg_host;
1048         struct sdebug_dev_info * open_devip = NULL;
1049         struct sdebug_dev_info * devip =
1050                         (struct sdebug_dev_info *)sdev->hostdata;
1051
1052         if (devip)
1053                 return devip;
1054         sdbg_host = *(struct sdebug_host_info **) sdev->host->hostdata;
1055         if(! sdbg_host) {
1056                 printk(KERN_ERR "Host info NULL\n");
1057                 return NULL;
1058         }
1059         list_for_each_entry(devip, &sdbg_host->dev_info_list, dev_list) {
1060                 if ((devip->used) && (devip->channel == sdev->channel) &&
1061                     (devip->target == sdev->id) &&
1062                     (devip->lun == sdev->lun))
1063                         return devip;
1064                 else {
1065                         if ((!devip->used) && (!open_devip))
1066                                 open_devip = devip;
1067                 }
1068         }
1069         if (NULL == open_devip) { /* try and make a new one */
1070                 open_devip = kmalloc(sizeof(*open_devip),GFP_KERNEL);
1071                 if (NULL == open_devip) {
1072                         printk(KERN_ERR "%s: out of memory at line %d\n",
1073                                 __FUNCTION__, __LINE__);
1074                         return NULL;
1075                 }
1076                 memset(open_devip, 0, sizeof(*open_devip));
1077                 open_devip->sdbg_host = sdbg_host;
1078                 list_add_tail(&open_devip->dev_list,
1079                 &sdbg_host->dev_info_list);
1080         }
1081         if (open_devip) {
1082                 open_devip->channel = sdev->channel;
1083                 open_devip->target = sdev->id;
1084                 open_devip->lun = sdev->lun;
1085                 open_devip->sdbg_host = sdbg_host;
1086                 open_devip->reset = 1;
1087                 open_devip->used = 1;
1088                 memset(open_devip->sense_buff, 0, SDEBUG_SENSE_LEN);
1089                 if (scsi_debug_dsense)
1090                         open_devip->sense_buff[0] = 0x72;
1091                 else {
1092                         open_devip->sense_buff[0] = 0x70;
1093                         open_devip->sense_buff[7] = 0xa;
1094                 }
1095                 return open_devip;
1096         }
1097         return NULL;
1098 }
1099
1100 static void mk_sense_buffer(struct sdebug_dev_info * devip, int key,
1101                             int asc, int asq)
1102 {
1103         unsigned char * sbuff;
1104
1105         sbuff = devip->sense_buff;
1106         memset(sbuff, 0, SDEBUG_SENSE_LEN);
1107         if (scsi_debug_dsense) {
1108                 sbuff[0] = 0x72;  /* descriptor, current */
1109                 sbuff[1] = key;
1110                 sbuff[2] = asc;
1111                 sbuff[3] = asq;
1112         } else {
1113                 sbuff[0] = 0x70;  /* fixed, current */
1114                 sbuff[2] = key;
1115                 sbuff[7] = 0xa;   /* implies 18 byte sense buffer */
1116                 sbuff[12] = asc;
1117                 sbuff[13] = asq;
1118         }
1119         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1120                 printk(KERN_INFO "scsi_debug:    [sense_key,asc,ascq]: "
1121                       "[0x%x,0x%x,0x%x]\n", key, asc, asq);
1122 }
1123
1124 static int scsi_debug_abort(struct scsi_cmnd * SCpnt)
1125 {
1126         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1127                 printk(KERN_INFO "scsi_debug: abort\n");
1128         ++num_aborts;
1129         stop_queued_cmnd(SCpnt);
1130         return SUCCESS;
1131 }
1132
1133 static int scsi_debug_biosparam(struct scsi_device *sdev,
1134                 struct block_device * bdev, sector_t capacity, int *info)
1135 {
1136         int res;
1137         unsigned char *buf;
1138
1139         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1140                 printk(KERN_INFO "scsi_debug: biosparam\n");
1141         buf = scsi_bios_ptable(bdev);
1142         if (buf) {
1143                 res = scsi_partsize(buf, capacity,
1144                                     &info[2], &info[0], &info[1]);
1145                 kfree(buf);
1146                 if (! res)
1147                         return res;
1148         }
1149         info[0] = sdebug_heads;
1150         info[1] = sdebug_sectors_per;
1151         info[2] = sdebug_cylinders_per;
1152         return 0;
1153 }
1154
1155 static int scsi_debug_device_reset(struct scsi_cmnd * SCpnt)
1156 {
1157         struct sdebug_dev_info * devip;
1158
1159         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1160                 printk(KERN_INFO "scsi_debug: device_reset\n");
1161         ++num_dev_resets;
1162         if (SCpnt) {
1163                 devip = devInfoReg(SCpnt->device);
1164                 if (devip)
1165                         devip->reset = 1;
1166         }
1167         return SUCCESS;
1168 }
1169
1170 static int scsi_debug_bus_reset(struct scsi_cmnd * SCpnt)
1171 {
1172         struct sdebug_host_info *sdbg_host;
1173         struct sdebug_dev_info * dev_info;
1174         struct scsi_device * sdp;
1175         struct Scsi_Host * hp;
1176
1177         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1178                 printk(KERN_INFO "scsi_debug: bus_reset\n");
1179         ++num_bus_resets;
1180         if (SCpnt && ((sdp = SCpnt->device)) && ((hp = sdp->host))) {
1181                 sdbg_host = *(struct sdebug_host_info **) hp->hostdata;
1182                 if (sdbg_host) {
1183                         list_for_each_entry(dev_info,
1184                                             &sdbg_host->dev_info_list,
1185                                             dev_list)
1186                                 dev_info->reset = 1;
1187                 }
1188         }
1189         return SUCCESS;
1190 }
1191
1192 static int scsi_debug_host_reset(struct scsi_cmnd * SCpnt)
1193 {
1194         struct sdebug_host_info * sdbg_host;
1195         struct sdebug_dev_info * dev_info;
1196
1197         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1198                 printk(KERN_INFO "scsi_debug: host_reset\n");
1199         ++num_host_resets;
1200         spin_lock(&sdebug_host_list_lock);
1201         list_for_each_entry(sdbg_host, &sdebug_host_list, host_list) {
1202                 list_for_each_entry(dev_info, &sdbg_host->dev_info_list,
1203                                     dev_list)
1204                         dev_info->reset = 1;
1205         }
1206         spin_unlock(&sdebug_host_list_lock);
1207         stop_all_queued();
1208         return SUCCESS;
1209 }
1210
1211 /* Returns 1 if found 'cmnd' and deleted its timer. else returns 0 */
1212 static int stop_queued_cmnd(struct scsi_cmnd * cmnd)
1213 {
1214         unsigned long iflags;
1215         int k;
1216         struct sdebug_queued_cmd * sqcp;
1217
1218         spin_lock_irqsave(&queued_arr_lock, iflags);
1219         for (k = 0; k < SCSI_DEBUG_CANQUEUE; ++k) {
1220                 sqcp = &queued_arr[k];
1221                 if (sqcp->in_use && (cmnd == sqcp->a_cmnd)) {
1222                         del_timer_sync(&sqcp->cmnd_timer);
1223                         sqcp->in_use = 0;
1224                         sqcp->a_cmnd = NULL;
1225                         break;
1226                 }
1227         }
1228         spin_unlock_irqrestore(&queued_arr_lock, iflags);
1229         return (k < SCSI_DEBUG_CANQUEUE) ? 1 : 0;
1230 }
1231
1232 /* Deletes (stops) timers of all queued commands */
1233 static void stop_all_queued(void)
1234 {
1235         unsigned long iflags;
1236         int k;
1237         struct sdebug_queued_cmd * sqcp;
1238
1239         spin_lock_irqsave(&queued_arr_lock, iflags);
1240         for (k = 0; k < SCSI_DEBUG_CANQUEUE; ++k) {
1241                 sqcp = &queued_arr[k];
1242                 if (sqcp->in_use && sqcp->a_cmnd) {
1243                         del_timer_sync(&sqcp->cmnd_timer);
1244                         sqcp->in_use = 0;
1245                         sqcp->a_cmnd = NULL;
1246                 }
1247         }
1248         spin_unlock_irqrestore(&queued_arr_lock, iflags);
1249 }
1250
1251 /* Initializes timers in queued array */
1252 static void __init init_all_queued(void)
1253 {
1254         unsigned long iflags;
1255         int k;
1256         struct sdebug_queued_cmd * sqcp;
1257
1258         spin_lock_irqsave(&queued_arr_lock, iflags);
1259         for (k = 0; k < SCSI_DEBUG_CANQUEUE; ++k) {
1260                 sqcp = &queued_arr[k];
1261                 init_timer(&sqcp->cmnd_timer);
1262                 sqcp->in_use = 0;
1263                 sqcp->a_cmnd = NULL;
1264         }
1265         spin_unlock_irqrestore(&queued_arr_lock, iflags);
1266 }
1267
1268 static void __init sdebug_build_parts(unsigned char * ramp)
1269 {
1270         struct partition * pp;
1271         int starts[SDEBUG_MAX_PARTS + 2];
1272         int sectors_per_part, num_sectors, k;
1273         int heads_by_sects, start_sec, end_sec;
1274
1275         /* assume partition table already zeroed */
1276         if ((scsi_debug_num_parts < 1) || (sdebug_store_size < 1048576))
1277                 return;
1278         if (scsi_debug_num_parts > SDEBUG_MAX_PARTS) {
1279                 scsi_debug_num_parts = SDEBUG_MAX_PARTS;
1280                 printk(KERN_WARNING "scsi_debug:build_parts: reducing "
1281                                     "partitions to %d\n", SDEBUG_MAX_PARTS);
1282         }
1283         num_sectors = (int)(sdebug_store_size / SECT_SIZE);
1284         sectors_per_part = (num_sectors - sdebug_sectors_per)
1285                            / scsi_debug_num_parts;
1286         heads_by_sects = sdebug_heads * sdebug_sectors_per;
1287         starts[0] = sdebug_sectors_per;
1288         for (k = 1; k < scsi_debug_num_parts; ++k)
1289                 starts[k] = ((k * sectors_per_part) / heads_by_sects)
1290                             * heads_by_sects;
1291         starts[scsi_debug_num_parts] = num_sectors;
1292         starts[scsi_debug_num_parts + 1] = 0;
1293
1294         ramp[510] = 0x55;       /* magic partition markings */
1295         ramp[511] = 0xAA;
1296         pp = (struct partition *)(ramp + 0x1be);
1297         for (k = 0; starts[k + 1]; ++k, ++pp) {
1298                 start_sec = starts[k];
1299                 end_sec = starts[k + 1] - 1;
1300                 pp->boot_ind = 0;
1301
1302                 pp->cyl = start_sec / heads_by_sects;
1303                 pp->head = (start_sec - (pp->cyl * heads_by_sects))
1304                            / sdebug_sectors_per;
1305                 pp->sector = (start_sec % sdebug_sectors_per) + 1;
1306
1307                 pp->end_cyl = end_sec / heads_by_sects;
1308                 pp->end_head = (end_sec - (pp->end_cyl * heads_by_sects))
1309                                / sdebug_sectors_per;
1310                 pp->end_sector = (end_sec % sdebug_sectors_per) + 1;
1311
1312                 pp->start_sect = start_sec;
1313                 pp->nr_sects = end_sec - start_sec + 1;
1314                 pp->sys_ind = 0x83;     /* plain Linux partition */
1315         }
1316 }
1317
1318 static int schedule_resp(struct scsi_cmnd * cmnd,
1319                          struct sdebug_dev_info * devip,
1320                          done_funct_t done, int scsi_result, int delta_jiff)
1321 {
1322         if ((SCSI_DEBUG_OPT_NOISE & scsi_debug_opts) && cmnd) {
1323                 if (scsi_result) {
1324                         struct scsi_device * sdp = cmnd->device;
1325
1326                         sdev_printk(KERN_INFO, sdp,
1327                                 "non-zero result=0x%x\n",
1328                                 scsi_result);
1329                 }
1330         }
1331         if (cmnd && devip) {
1332                 /* simulate autosense by this driver */
1333                 if (SAM_STAT_CHECK_CONDITION == (scsi_result & 0xff))
1334                         memcpy(cmnd->sense_buffer, devip->sense_buff,
1335                                (SCSI_SENSE_BUFFERSIZE > SDEBUG_SENSE_LEN) ?
1336                                SDEBUG_SENSE_LEN : SCSI_SENSE_BUFFERSIZE);
1337         }
1338         if (delta_jiff <= 0) {
1339                 if (cmnd)
1340                         cmnd->result = scsi_result;
1341                 if (done)
1342                         done(cmnd);
1343                 return 0;
1344         } else {
1345                 unsigned long iflags;
1346                 int k;
1347                 struct sdebug_queued_cmd * sqcp = NULL;
1348
1349                 spin_lock_irqsave(&queued_arr_lock, iflags);
1350                 for (k = 0; k < SCSI_DEBUG_CANQUEUE; ++k) {
1351                         sqcp = &queued_arr[k];
1352                         if (! sqcp->in_use)
1353                                 break;
1354                 }
1355                 if (k >= SCSI_DEBUG_CANQUEUE) {
1356                         spin_unlock_irqrestore(&queued_arr_lock, iflags);
1357                         printk(KERN_WARNING "scsi_debug: can_queue exceeded\n");
1358                         return 1;       /* report busy to mid level */
1359                 }
1360                 sqcp->in_use = 1;
1361                 sqcp->a_cmnd = cmnd;
1362                 sqcp->scsi_result = scsi_result;
1363                 sqcp->done_funct = done;
1364                 sqcp->cmnd_timer.function = timer_intr_handler;
1365                 sqcp->cmnd_timer.data = k;
1366                 sqcp->cmnd_timer.expires = jiffies + delta_jiff;
1367                 add_timer(&sqcp->cmnd_timer);
1368                 spin_unlock_irqrestore(&queued_arr_lock, iflags);
1369                 if (cmnd)
1370                         cmnd->result = 0;
1371                 return 0;
1372         }
1373 }
1374
1375 /* Set 'perm' (4th argument) to 0 to disable module_param's definition
1376  * of sysfs parameters (which module_param doesn't yet support).
1377  * Sysfs parameters defined explicitly below.
1378  */
1379 module_param_named(add_host, scsi_debug_add_host, int, 0); /* perm=0644 */
1380 module_param_named(delay, scsi_debug_delay, int, 0); /* perm=0644 */
1381 module_param_named(dev_size_mb, scsi_debug_dev_size_mb, int, 0);
1382 module_param_named(dsense, scsi_debug_dsense, int, 0);
1383 module_param_named(every_nth, scsi_debug_every_nth, int, 0);
1384 module_param_named(max_luns, scsi_debug_max_luns, int, 0);
1385 module_param_named(num_parts, scsi_debug_num_parts, int, 0);
1386 module_param_named(num_tgts, scsi_debug_num_tgts, int, 0);
1387 module_param_named(opts, scsi_debug_opts, int, 0); /* perm=0644 */
1388 module_param_named(ptype, scsi_debug_ptype, int, 0);
1389 module_param_named(scsi_level, scsi_debug_scsi_level, int, 0);
1390
1391 MODULE_AUTHOR("Eric Youngdale + Douglas Gilbert");
1392 MODULE_DESCRIPTION("SCSI debug adapter driver");
1393 MODULE_LICENSE("GPL");
1394 MODULE_VERSION(SCSI_DEBUG_VERSION);
1395
1396 MODULE_PARM_DESC(add_host, "0..127 hosts allowed(def=1)");
1397 MODULE_PARM_DESC(delay, "# of jiffies to delay response(def=1)");
1398 MODULE_PARM_DESC(dev_size_mb, "size in MB of ram shared by devs");
1399 MODULE_PARM_DESC(dsense, "use descriptor sense format(def: fixed)");
1400 MODULE_PARM_DESC(every_nth, "timeout every nth command(def=100)");
1401 MODULE_PARM_DESC(max_luns, "number of SCSI LUNs per target to simulate");
1402 MODULE_PARM_DESC(num_parts, "number of partitions(def=0)");
1403 MODULE_PARM_DESC(num_tgts, "number of SCSI targets per host to simulate");
1404 MODULE_PARM_DESC(opts, "1->noise, 2->medium_error, 4->...");
1405 MODULE_PARM_DESC(ptype, "SCSI peripheral type(def=0[disk])");
1406 MODULE_PARM_DESC(scsi_level, "SCSI level to simulate(def=5[SPC-3])");
1407
1408
1409 static char sdebug_info[256];
1410
1411 static const char * scsi_debug_info(struct Scsi_Host * shp)
1412 {
1413         sprintf(sdebug_info, "scsi_debug, version %s [%s], "
1414                 "dev_size_mb=%d, opts=0x%x", SCSI_DEBUG_VERSION,
1415                 scsi_debug_version_date, scsi_debug_dev_size_mb,
1416                 scsi_debug_opts);
1417         return sdebug_info;
1418 }
1419
1420 /* scsi_debug_proc_info
1421  * Used if the driver currently has no own support for /proc/scsi
1422  */
1423 static int scsi_debug_proc_info(struct Scsi_Host *host, char *buffer, char **start, off_t offset,
1424                                 int length, int inout)
1425 {
1426         int len, pos, begin;
1427         int orig_length;
1428
1429         orig_length = length;
1430
1431         if (inout == 1) {
1432                 char arr[16];
1433                 int minLen = length > 15 ? 15 : length;
1434
1435                 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
1436                         return -EACCES;
1437                 memcpy(arr, buffer, minLen);
1438                 arr[minLen] = '\0';
1439                 if (1 != sscanf(arr, "%d", &pos))
1440                         return -EINVAL;
1441                 scsi_debug_opts = pos;
1442                 if (scsi_debug_every_nth != 0)
1443                         scsi_debug_cmnd_count = 0;
1444                 return length;
1445         }
1446         begin = 0;
1447         pos = len = sprintf(buffer, "scsi_debug adapter driver, version "
1448             "%s [%s]\n"
1449             "num_tgts=%d, shared (ram) size=%d MB, opts=0x%x, "
1450             "every_nth=%d(curr:%d)\n"
1451             "delay=%d, max_luns=%d, scsi_level=%d\n"
1452             "sector_size=%d bytes, cylinders=%d, heads=%d, sectors=%d\n"
1453             "number of aborts=%d, device_reset=%d, bus_resets=%d, "
1454             "host_resets=%d\n",
1455             SCSI_DEBUG_VERSION, scsi_debug_version_date, scsi_debug_num_tgts,
1456             scsi_debug_dev_size_mb, scsi_debug_opts, scsi_debug_every_nth,
1457             scsi_debug_cmnd_count, scsi_debug_delay,
1458             scsi_debug_max_luns, scsi_debug_scsi_level,
1459             SECT_SIZE, sdebug_cylinders_per, sdebug_heads, sdebug_sectors_per,
1460             num_aborts, num_dev_resets, num_bus_resets, num_host_resets);
1461         if (pos < offset) {
1462                 len = 0;
1463                 begin = pos;
1464         }
1465         *start = buffer + (offset - begin);     /* Start of wanted data */
1466         len -= (offset - begin);
1467         if (len > length)
1468                 len = length;
1469         return len;
1470 }
1471
1472 static ssize_t sdebug_delay_show(struct device_driver * ddp, char * buf)
1473 {
1474         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_delay);
1475 }
1476
1477 static ssize_t sdebug_delay_store(struct device_driver * ddp,
1478                                   const char * buf, size_t count)
1479 {
1480         int delay;
1481         char work[20];
1482
1483         if (1 == sscanf(buf, "%10s", work)) {
1484                 if ((1 == sscanf(work, "%d", &delay)) && (delay >= 0)) {
1485                         scsi_debug_delay = delay;
1486                         return count;
1487                 }
1488         }
1489         return -EINVAL;
1490 }
1491 DRIVER_ATTR(delay, S_IRUGO | S_IWUSR, sdebug_delay_show,
1492             sdebug_delay_store);
1493
1494 static ssize_t sdebug_opts_show(struct device_driver * ddp, char * buf)
1495 {
1496         return scnprintf(buf, PAGE_SIZE, "0x%x\n", scsi_debug_opts);
1497 }
1498
1499 static ssize_t sdebug_opts_store(struct device_driver * ddp,
1500                                  const char * buf, size_t count)
1501 {
1502         int opts;
1503         char work[20];
1504
1505         if (1 == sscanf(buf, "%10s", work)) {
1506                 if (0 == strnicmp(work,"0x", 2)) {
1507                         if (1 == sscanf(&work[2], "%x", &opts))
1508                                 goto opts_done;
1509                 } else {
1510                         if (1 == sscanf(work, "%d", &opts))
1511                                 goto opts_done;
1512                 }
1513         }
1514         return -EINVAL;
1515 opts_done:
1516         scsi_debug_opts = opts;
1517         scsi_debug_cmnd_count = 0;
1518         return count;
1519 }
1520 DRIVER_ATTR(opts, S_IRUGO | S_IWUSR, sdebug_opts_show,
1521             sdebug_opts_store);
1522
1523 static ssize_t sdebug_ptype_show(struct device_driver * ddp, char * buf)
1524 {
1525         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_ptype);
1526 }
1527 static ssize_t sdebug_ptype_store(struct device_driver * ddp,
1528                                   const char * buf, size_t count)
1529 {
1530         int n;
1531
1532         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
1533                 scsi_debug_ptype = n;
1534                 return count;
1535         }
1536         return -EINVAL;
1537 }
1538 DRIVER_ATTR(ptype, S_IRUGO | S_IWUSR, sdebug_ptype_show, sdebug_ptype_store);
1539
1540 static ssize_t sdebug_dsense_show(struct device_driver * ddp, char * buf)
1541 {
1542         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_dsense);
1543 }
1544 static ssize_t sdebug_dsense_store(struct device_driver * ddp,
1545                                   const char * buf, size_t count)
1546 {
1547         int n;
1548
1549         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
1550                 scsi_debug_dsense = n;
1551                 return count;
1552         }
1553         return -EINVAL;
1554 }
1555 DRIVER_ATTR(dsense, S_IRUGO | S_IWUSR, sdebug_dsense_show,
1556             sdebug_dsense_store);
1557
1558 static ssize_t sdebug_num_tgts_show(struct device_driver * ddp, char * buf)
1559 {
1560         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_num_tgts);
1561 }
1562 static ssize_t sdebug_num_tgts_store(struct device_driver * ddp,
1563                                      const char * buf, size_t count)
1564 {
1565         int n;
1566
1567         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
1568                 scsi_debug_num_tgts = n;
1569                 sdebug_max_tgts_luns();
1570                 return count;
1571         }
1572         return -EINVAL;
1573 }
1574 DRIVER_ATTR(num_tgts, S_IRUGO | S_IWUSR, sdebug_num_tgts_show,
1575             sdebug_num_tgts_store);
1576
1577 static ssize_t sdebug_dev_size_mb_show(struct device_driver * ddp, char * buf)
1578 {
1579         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_dev_size_mb);
1580 }
1581 DRIVER_ATTR(dev_size_mb, S_IRUGO, sdebug_dev_size_mb_show, NULL);
1582
1583 static ssize_t sdebug_num_parts_show(struct device_driver * ddp, char * buf)
1584 {
1585         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_num_parts);
1586 }
1587 DRIVER_ATTR(num_parts, S_IRUGO, sdebug_num_parts_show, NULL);
1588
1589 static ssize_t sdebug_every_nth_show(struct device_driver * ddp, char * buf)
1590 {
1591         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_every_nth);
1592 }
1593 static ssize_t sdebug_every_nth_store(struct device_driver * ddp,
1594                                       const char * buf, size_t count)
1595 {
1596         int nth;
1597
1598         if ((count > 0) && (1 == sscanf(buf, "%d", &nth))) {
1599                 scsi_debug_every_nth = nth;
1600                 scsi_debug_cmnd_count = 0;
1601                 return count;
1602         }
1603         return -EINVAL;
1604 }
1605 DRIVER_ATTR(every_nth, S_IRUGO | S_IWUSR, sdebug_every_nth_show,
1606             sdebug_every_nth_store);
1607
1608 static ssize_t sdebug_max_luns_show(struct device_driver * ddp, char * buf)
1609 {
1610         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_max_luns);
1611 }
1612 static ssize_t sdebug_max_luns_store(struct device_driver * ddp,
1613                                      const char * buf, size_t count)
1614 {
1615         int n;
1616
1617         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
1618                 scsi_debug_max_luns = n;
1619                 sdebug_max_tgts_luns();
1620                 return count;
1621         }
1622         return -EINVAL;
1623 }
1624 DRIVER_ATTR(max_luns, S_IRUGO | S_IWUSR, sdebug_max_luns_show,
1625             sdebug_max_luns_store);
1626
1627 static ssize_t sdebug_scsi_level_show(struct device_driver * ddp, char * buf)
1628 {
1629         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_scsi_level);
1630 }
1631 DRIVER_ATTR(scsi_level, S_IRUGO, sdebug_scsi_level_show, NULL);
1632
1633 static ssize_t sdebug_add_host_show(struct device_driver * ddp, char * buf)
1634 {
1635         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_add_host);
1636 }
1637
1638 static ssize_t sdebug_add_host_store(struct device_driver * ddp,
1639                                      const char * buf, size_t count)
1640 {
1641         int delta_hosts;
1642         char work[20];
1643
1644         if (1 != sscanf(buf, "%10s", work))
1645                 return -EINVAL;
1646         {       /* temporary hack around sscanf() problem with -ve nums */
1647                 int neg = 0;
1648
1649                 if ('-' == *work)
1650                         neg = 1;
1651                 if (1 != sscanf(work + neg, "%d", &delta_hosts))
1652                         return -EINVAL;
1653                 if (neg)
1654                         delta_hosts = -delta_hosts;
1655         }
1656         if (delta_hosts > 0) {
1657                 do {
1658                         sdebug_add_adapter();
1659                 } while (--delta_hosts);
1660         } else if (delta_hosts < 0) {
1661                 do {
1662                         sdebug_remove_adapter();
1663                 } while (++delta_hosts);
1664         }
1665         return count;
1666 }
1667 DRIVER_ATTR(add_host, S_IRUGO | S_IWUSR, sdebug_add_host_show, 
1668             sdebug_add_host_store);
1669
1670 static void do_create_driverfs_files(void)
1671 {
1672         driver_create_file(&sdebug_driverfs_driver, &driver_attr_add_host);
1673         driver_create_file(&sdebug_driverfs_driver, &driver_attr_delay);
1674         driver_create_file(&sdebug_driverfs_driver, &driver_attr_dev_size_mb);
1675         driver_create_file(&sdebug_driverfs_driver, &driver_attr_dsense);
1676         driver_create_file(&sdebug_driverfs_driver, &driver_attr_every_nth);
1677         driver_create_file(&sdebug_driverfs_driver, &driver_attr_max_luns);
1678         driver_create_file(&sdebug_driverfs_driver, &driver_attr_num_tgts);
1679         driver_create_file(&sdebug_driverfs_driver, &driver_attr_num_parts);
1680         driver_create_file(&sdebug_driverfs_driver, &driver_attr_ptype);
1681         driver_create_file(&sdebug_driverfs_driver, &driver_attr_opts);
1682         driver_create_file(&sdebug_driverfs_driver, &driver_attr_scsi_level);
1683 }
1684
1685 static void do_remove_driverfs_files(void)
1686 {
1687         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_scsi_level);
1688         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_opts);
1689         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_ptype);
1690         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_num_parts);
1691         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_num_tgts);
1692         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_max_luns);
1693         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_every_nth);
1694         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_dsense);
1695         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_dev_size_mb);
1696         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_delay);
1697         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_add_host);
1698 }
1699
1700 static int __init scsi_debug_init(void)
1701 {
1702         unsigned long sz;
1703         int host_to_add;
1704         int k;
1705
1706         if (scsi_debug_dev_size_mb < 1)
1707                 scsi_debug_dev_size_mb = 1;  /* force minimum 1 MB ramdisk */
1708         sdebug_store_size = (unsigned long)scsi_debug_dev_size_mb * 1048576;
1709         sdebug_capacity = sdebug_store_size / SECT_SIZE;
1710
1711         /* play around with geometry, don't waste too much on track 0 */
1712         sdebug_heads = 8;
1713         sdebug_sectors_per = 32;
1714         if (scsi_debug_dev_size_mb >= 16)
1715                 sdebug_heads = 32;
1716         else if (scsi_debug_dev_size_mb >= 256)
1717                 sdebug_heads = 64;
1718         sdebug_cylinders_per = (unsigned long)sdebug_capacity /
1719                                (sdebug_sectors_per * sdebug_heads);
1720         if (sdebug_cylinders_per >= 1024) {
1721                 /* other LLDs do this; implies >= 1GB ram disk ... */
1722                 sdebug_heads = 255;
1723                 sdebug_sectors_per = 63;
1724                 sdebug_cylinders_per = (unsigned long)sdebug_capacity /
1725                                (sdebug_sectors_per * sdebug_heads);
1726         }
1727
1728         sz = sdebug_store_size;
1729         fake_storep = vmalloc(sz);
1730         if (NULL == fake_storep) {
1731                 printk(KERN_ERR "scsi_debug_init: out of memory, 1\n");
1732                 return -ENOMEM;
1733         }
1734         memset(fake_storep, 0, sz);
1735         if (scsi_debug_num_parts > 0)
1736                 sdebug_build_parts(fake_storep);
1737
1738         init_all_queued();
1739
1740         device_register(&pseudo_primary);
1741         bus_register(&pseudo_lld_bus);
1742         driver_register(&sdebug_driverfs_driver);
1743         do_create_driverfs_files();
1744
1745         sdebug_driver_template.proc_name = (char *)sdebug_proc_name;
1746
1747         host_to_add = scsi_debug_add_host;
1748         scsi_debug_add_host = 0;
1749
1750         for (k = 0; k < host_to_add; k++) {
1751                 if (sdebug_add_adapter()) {
1752                         printk(KERN_ERR "scsi_debug_init: "
1753                                "sdebug_add_adapter failed k=%d\n", k);
1754                         break;
1755                 }
1756         }
1757
1758         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts) {
1759                 printk(KERN_INFO "scsi_debug_init: built %d host(s)\n",
1760                        scsi_debug_add_host);
1761         }
1762         return 0;
1763 }
1764
1765 static void __exit scsi_debug_exit(void)
1766 {
1767         int k = scsi_debug_add_host;
1768
1769         stop_all_queued();
1770         for (; k; k--)
1771                 sdebug_remove_adapter();
1772         do_remove_driverfs_files();
1773         driver_unregister(&sdebug_driverfs_driver);
1774         bus_unregister(&pseudo_lld_bus);
1775         device_unregister(&pseudo_primary);
1776
1777         vfree(fake_storep);
1778 }
1779
1780 device_initcall(scsi_debug_init);
1781 module_exit(scsi_debug_exit);
1782
1783 static void pseudo_0_release(struct device * dev)
1784 {
1785         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1786                 printk(KERN_INFO "scsi_debug: pseudo_0_release() called\n");
1787 }
1788
1789 static struct device pseudo_primary = {
1790         .bus_id         = "pseudo_0",
1791         .release        = pseudo_0_release,
1792 };
1793
1794 static int pseudo_lld_bus_match(struct device *dev,
1795                           struct device_driver *dev_driver)
1796 {
1797         return 1;
1798 }
1799
1800 static struct bus_type pseudo_lld_bus = {
1801         .name = "pseudo",
1802         .match = pseudo_lld_bus_match,
1803 };
1804
1805 static void sdebug_release_adapter(struct device * dev)
1806 {
1807         struct sdebug_host_info *sdbg_host;
1808
1809         sdbg_host = to_sdebug_host(dev);
1810         kfree(sdbg_host);
1811 }
1812
1813 static int sdebug_add_adapter(void)
1814 {
1815         int k, devs_per_host;
1816         int error = 0;
1817         struct sdebug_host_info *sdbg_host;
1818         struct sdebug_dev_info *sdbg_devinfo;
1819         struct list_head *lh, *lh_sf;
1820
1821         sdbg_host = kmalloc(sizeof(*sdbg_host),GFP_KERNEL);
1822
1823         if (NULL == sdbg_host) {
1824                 printk(KERN_ERR "%s: out of memory at line %d\n",
1825                        __FUNCTION__, __LINE__);
1826                 return -ENOMEM;
1827         }
1828
1829         memset(sdbg_host, 0, sizeof(*sdbg_host));
1830         INIT_LIST_HEAD(&sdbg_host->dev_info_list);
1831
1832         devs_per_host = scsi_debug_num_tgts * scsi_debug_max_luns;
1833         for (k = 0; k < devs_per_host; k++) {
1834                 sdbg_devinfo = kmalloc(sizeof(*sdbg_devinfo),GFP_KERNEL);
1835                 if (NULL == sdbg_devinfo) {
1836                         printk(KERN_ERR "%s: out of memory at line %d\n",
1837                                __FUNCTION__, __LINE__);
1838                         error = -ENOMEM;
1839                         goto clean;
1840                 }
1841                 memset(sdbg_devinfo, 0, sizeof(*sdbg_devinfo));
1842                 sdbg_devinfo->sdbg_host = sdbg_host;
1843                 list_add_tail(&sdbg_devinfo->dev_list,
1844                               &sdbg_host->dev_info_list);
1845         }
1846
1847         spin_lock(&sdebug_host_list_lock);
1848         list_add_tail(&sdbg_host->host_list, &sdebug_host_list);
1849         spin_unlock(&sdebug_host_list_lock);
1850
1851         sdbg_host->dev.bus = &pseudo_lld_bus;
1852         sdbg_host->dev.parent = &pseudo_primary;
1853         sdbg_host->dev.release = &sdebug_release_adapter;
1854         sprintf(sdbg_host->dev.bus_id, "adapter%d", scsi_debug_add_host);
1855
1856         error = device_register(&sdbg_host->dev);
1857
1858         if (error)
1859                 goto clean;
1860
1861         ++scsi_debug_add_host;
1862         return error;
1863
1864 clean:
1865         list_for_each_safe(lh, lh_sf, &sdbg_host->dev_info_list) {
1866                 sdbg_devinfo = list_entry(lh, struct sdebug_dev_info,
1867                                           dev_list);
1868                 list_del(&sdbg_devinfo->dev_list);
1869                 kfree(sdbg_devinfo);
1870         }
1871
1872         kfree(sdbg_host);
1873         return error;
1874 }
1875
1876 static void sdebug_remove_adapter(void)
1877 {
1878         struct sdebug_host_info * sdbg_host = NULL;
1879
1880         spin_lock(&sdebug_host_list_lock);
1881         if (!list_empty(&sdebug_host_list)) {
1882                 sdbg_host = list_entry(sdebug_host_list.prev,
1883                                        struct sdebug_host_info, host_list);
1884                 list_del(&sdbg_host->host_list);
1885         }
1886         spin_unlock(&sdebug_host_list_lock);
1887
1888         if (!sdbg_host)
1889                 return;
1890
1891         device_unregister(&sdbg_host->dev);
1892         --scsi_debug_add_host;
1893 }
1894
1895 static int sdebug_driver_probe(struct device * dev)
1896 {
1897         int error = 0;
1898         struct sdebug_host_info *sdbg_host;
1899         struct Scsi_Host *hpnt;
1900
1901         sdbg_host = to_sdebug_host(dev);
1902
1903         hpnt = scsi_host_alloc(&sdebug_driver_template, sizeof(sdbg_host));
1904         if (NULL == hpnt) {
1905                 printk(KERN_ERR "%s: scsi_register failed\n", __FUNCTION__);
1906                 error = -ENODEV;
1907                 return error;
1908         }
1909
1910         sdbg_host->shost = hpnt;
1911         *((struct sdebug_host_info **)hpnt->hostdata) = sdbg_host;
1912         if ((hpnt->this_id >= 0) && (scsi_debug_num_tgts > hpnt->this_id))
1913                 hpnt->max_id = scsi_debug_num_tgts + 1;
1914         else
1915                 hpnt->max_id = scsi_debug_num_tgts;
1916         hpnt->max_lun = scsi_debug_max_luns;
1917
1918         error = scsi_add_host(hpnt, &sdbg_host->dev);
1919         if (error) {
1920                 printk(KERN_ERR "%s: scsi_add_host failed\n", __FUNCTION__);
1921                 error = -ENODEV;
1922                 scsi_host_put(hpnt);
1923         } else
1924                 scsi_scan_host(hpnt);
1925
1926
1927         return error;
1928 }
1929
1930 static int sdebug_driver_remove(struct device * dev)
1931 {
1932         struct list_head *lh, *lh_sf;
1933         struct sdebug_host_info *sdbg_host;
1934         struct sdebug_dev_info *sdbg_devinfo;
1935
1936         sdbg_host = to_sdebug_host(dev);
1937
1938         if (!sdbg_host) {
1939                 printk(KERN_ERR "%s: Unable to locate host info\n",
1940                        __FUNCTION__);
1941                 return -ENODEV;
1942         }
1943
1944         scsi_remove_host(sdbg_host->shost);
1945
1946         list_for_each_safe(lh, lh_sf, &sdbg_host->dev_info_list) {
1947                 sdbg_devinfo = list_entry(lh, struct sdebug_dev_info,
1948                                           dev_list);
1949                 list_del(&sdbg_devinfo->dev_list);
1950                 kfree(sdbg_devinfo);
1951         }
1952
1953         scsi_host_put(sdbg_host->shost);
1954         return 0;
1955 }
1956
1957 static void sdebug_max_tgts_luns(void)
1958 {
1959         struct sdebug_host_info * sdbg_host;
1960         struct Scsi_Host *hpnt;
1961
1962         spin_lock(&sdebug_host_list_lock);
1963         list_for_each_entry(sdbg_host, &sdebug_host_list, host_list) {
1964                 hpnt = sdbg_host->shost;
1965                 if ((hpnt->this_id >= 0) &&
1966                     (scsi_debug_num_tgts > hpnt->this_id))
1967                         hpnt->max_id = scsi_debug_num_tgts + 1;
1968                 else
1969                         hpnt->max_id = scsi_debug_num_tgts;
1970                 hpnt->max_lun = scsi_debug_max_luns;
1971         }
1972         spin_unlock(&sdebug_host_list_lock);
1973 }