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