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