V4L/DVB (4165): Add in tuner names
[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 = kzalloc(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                 open_devip->sdbg_host = sdbg_host;
1071                 list_add_tail(&open_devip->dev_list,
1072                 &sdbg_host->dev_info_list);
1073         }
1074         if (open_devip) {
1075                 open_devip->channel = sdev->channel;
1076                 open_devip->target = sdev->id;
1077                 open_devip->lun = sdev->lun;
1078                 open_devip->sdbg_host = sdbg_host;
1079                 open_devip->reset = 1;
1080                 open_devip->used = 1;
1081                 memset(open_devip->sense_buff, 0, SDEBUG_SENSE_LEN);
1082                 if (scsi_debug_dsense)
1083                         open_devip->sense_buff[0] = 0x72;
1084                 else {
1085                         open_devip->sense_buff[0] = 0x70;
1086                         open_devip->sense_buff[7] = 0xa;
1087                 }
1088                 return open_devip;
1089         }
1090         return NULL;
1091 }
1092
1093 static void mk_sense_buffer(struct sdebug_dev_info * devip, int key,
1094                             int asc, int asq)
1095 {
1096         unsigned char * sbuff;
1097
1098         sbuff = devip->sense_buff;
1099         memset(sbuff, 0, SDEBUG_SENSE_LEN);
1100         if (scsi_debug_dsense) {
1101                 sbuff[0] = 0x72;  /* descriptor, current */
1102                 sbuff[1] = key;
1103                 sbuff[2] = asc;
1104                 sbuff[3] = asq;
1105         } else {
1106                 sbuff[0] = 0x70;  /* fixed, current */
1107                 sbuff[2] = key;
1108                 sbuff[7] = 0xa;   /* implies 18 byte sense buffer */
1109                 sbuff[12] = asc;
1110                 sbuff[13] = asq;
1111         }
1112         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1113                 printk(KERN_INFO "scsi_debug:    [sense_key,asc,ascq]: "
1114                       "[0x%x,0x%x,0x%x]\n", key, asc, asq);
1115 }
1116
1117 static int scsi_debug_abort(struct scsi_cmnd * SCpnt)
1118 {
1119         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1120                 printk(KERN_INFO "scsi_debug: abort\n");
1121         ++num_aborts;
1122         stop_queued_cmnd(SCpnt);
1123         return SUCCESS;
1124 }
1125
1126 static int scsi_debug_biosparam(struct scsi_device *sdev,
1127                 struct block_device * bdev, sector_t capacity, int *info)
1128 {
1129         int res;
1130         unsigned char *buf;
1131
1132         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1133                 printk(KERN_INFO "scsi_debug: biosparam\n");
1134         buf = scsi_bios_ptable(bdev);
1135         if (buf) {
1136                 res = scsi_partsize(buf, capacity,
1137                                     &info[2], &info[0], &info[1]);
1138                 kfree(buf);
1139                 if (! res)
1140                         return res;
1141         }
1142         info[0] = sdebug_heads;
1143         info[1] = sdebug_sectors_per;
1144         info[2] = sdebug_cylinders_per;
1145         return 0;
1146 }
1147
1148 static int scsi_debug_device_reset(struct scsi_cmnd * SCpnt)
1149 {
1150         struct sdebug_dev_info * devip;
1151
1152         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1153                 printk(KERN_INFO "scsi_debug: device_reset\n");
1154         ++num_dev_resets;
1155         if (SCpnt) {
1156                 devip = devInfoReg(SCpnt->device);
1157                 if (devip)
1158                         devip->reset = 1;
1159         }
1160         return SUCCESS;
1161 }
1162
1163 static int scsi_debug_bus_reset(struct scsi_cmnd * SCpnt)
1164 {
1165         struct sdebug_host_info *sdbg_host;
1166         struct sdebug_dev_info * dev_info;
1167         struct scsi_device * sdp;
1168         struct Scsi_Host * hp;
1169
1170         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1171                 printk(KERN_INFO "scsi_debug: bus_reset\n");
1172         ++num_bus_resets;
1173         if (SCpnt && ((sdp = SCpnt->device)) && ((hp = sdp->host))) {
1174                 sdbg_host = *(struct sdebug_host_info **) hp->hostdata;
1175                 if (sdbg_host) {
1176                         list_for_each_entry(dev_info,
1177                                             &sdbg_host->dev_info_list,
1178                                             dev_list)
1179                                 dev_info->reset = 1;
1180                 }
1181         }
1182         return SUCCESS;
1183 }
1184
1185 static int scsi_debug_host_reset(struct scsi_cmnd * SCpnt)
1186 {
1187         struct sdebug_host_info * sdbg_host;
1188         struct sdebug_dev_info * dev_info;
1189
1190         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1191                 printk(KERN_INFO "scsi_debug: host_reset\n");
1192         ++num_host_resets;
1193         spin_lock(&sdebug_host_list_lock);
1194         list_for_each_entry(sdbg_host, &sdebug_host_list, host_list) {
1195                 list_for_each_entry(dev_info, &sdbg_host->dev_info_list,
1196                                     dev_list)
1197                         dev_info->reset = 1;
1198         }
1199         spin_unlock(&sdebug_host_list_lock);
1200         stop_all_queued();
1201         return SUCCESS;
1202 }
1203
1204 /* Returns 1 if found 'cmnd' and deleted its timer. else returns 0 */
1205 static int stop_queued_cmnd(struct scsi_cmnd * cmnd)
1206 {
1207         unsigned long iflags;
1208         int k;
1209         struct sdebug_queued_cmd * sqcp;
1210
1211         spin_lock_irqsave(&queued_arr_lock, iflags);
1212         for (k = 0; k < SCSI_DEBUG_CANQUEUE; ++k) {
1213                 sqcp = &queued_arr[k];
1214                 if (sqcp->in_use && (cmnd == sqcp->a_cmnd)) {
1215                         del_timer_sync(&sqcp->cmnd_timer);
1216                         sqcp->in_use = 0;
1217                         sqcp->a_cmnd = NULL;
1218                         break;
1219                 }
1220         }
1221         spin_unlock_irqrestore(&queued_arr_lock, iflags);
1222         return (k < SCSI_DEBUG_CANQUEUE) ? 1 : 0;
1223 }
1224
1225 /* Deletes (stops) timers of all queued commands */
1226 static void stop_all_queued(void)
1227 {
1228         unsigned long iflags;
1229         int k;
1230         struct sdebug_queued_cmd * sqcp;
1231
1232         spin_lock_irqsave(&queued_arr_lock, iflags);
1233         for (k = 0; k < SCSI_DEBUG_CANQUEUE; ++k) {
1234                 sqcp = &queued_arr[k];
1235                 if (sqcp->in_use && sqcp->a_cmnd) {
1236                         del_timer_sync(&sqcp->cmnd_timer);
1237                         sqcp->in_use = 0;
1238                         sqcp->a_cmnd = NULL;
1239                 }
1240         }
1241         spin_unlock_irqrestore(&queued_arr_lock, iflags);
1242 }
1243
1244 /* Initializes timers in queued array */
1245 static void __init init_all_queued(void)
1246 {
1247         unsigned long iflags;
1248         int k;
1249         struct sdebug_queued_cmd * sqcp;
1250
1251         spin_lock_irqsave(&queued_arr_lock, iflags);
1252         for (k = 0; k < SCSI_DEBUG_CANQUEUE; ++k) {
1253                 sqcp = &queued_arr[k];
1254                 init_timer(&sqcp->cmnd_timer);
1255                 sqcp->in_use = 0;
1256                 sqcp->a_cmnd = NULL;
1257         }
1258         spin_unlock_irqrestore(&queued_arr_lock, iflags);
1259 }
1260
1261 static void __init sdebug_build_parts(unsigned char * ramp)
1262 {
1263         struct partition * pp;
1264         int starts[SDEBUG_MAX_PARTS + 2];
1265         int sectors_per_part, num_sectors, k;
1266         int heads_by_sects, start_sec, end_sec;
1267
1268         /* assume partition table already zeroed */
1269         if ((scsi_debug_num_parts < 1) || (sdebug_store_size < 1048576))
1270                 return;
1271         if (scsi_debug_num_parts > SDEBUG_MAX_PARTS) {
1272                 scsi_debug_num_parts = SDEBUG_MAX_PARTS;
1273                 printk(KERN_WARNING "scsi_debug:build_parts: reducing "
1274                                     "partitions to %d\n", SDEBUG_MAX_PARTS);
1275         }
1276         num_sectors = (int)(sdebug_store_size / SECT_SIZE);
1277         sectors_per_part = (num_sectors - sdebug_sectors_per)
1278                            / scsi_debug_num_parts;
1279         heads_by_sects = sdebug_heads * sdebug_sectors_per;
1280         starts[0] = sdebug_sectors_per;
1281         for (k = 1; k < scsi_debug_num_parts; ++k)
1282                 starts[k] = ((k * sectors_per_part) / heads_by_sects)
1283                             * heads_by_sects;
1284         starts[scsi_debug_num_parts] = num_sectors;
1285         starts[scsi_debug_num_parts + 1] = 0;
1286
1287         ramp[510] = 0x55;       /* magic partition markings */
1288         ramp[511] = 0xAA;
1289         pp = (struct partition *)(ramp + 0x1be);
1290         for (k = 0; starts[k + 1]; ++k, ++pp) {
1291                 start_sec = starts[k];
1292                 end_sec = starts[k + 1] - 1;
1293                 pp->boot_ind = 0;
1294
1295                 pp->cyl = start_sec / heads_by_sects;
1296                 pp->head = (start_sec - (pp->cyl * heads_by_sects))
1297                            / sdebug_sectors_per;
1298                 pp->sector = (start_sec % sdebug_sectors_per) + 1;
1299
1300                 pp->end_cyl = end_sec / heads_by_sects;
1301                 pp->end_head = (end_sec - (pp->end_cyl * heads_by_sects))
1302                                / sdebug_sectors_per;
1303                 pp->end_sector = (end_sec % sdebug_sectors_per) + 1;
1304
1305                 pp->start_sect = start_sec;
1306                 pp->nr_sects = end_sec - start_sec + 1;
1307                 pp->sys_ind = 0x83;     /* plain Linux partition */
1308         }
1309 }
1310
1311 static int schedule_resp(struct scsi_cmnd * cmnd,
1312                          struct sdebug_dev_info * devip,
1313                          done_funct_t done, int scsi_result, int delta_jiff)
1314 {
1315         if ((SCSI_DEBUG_OPT_NOISE & scsi_debug_opts) && cmnd) {
1316                 if (scsi_result) {
1317                         struct scsi_device * sdp = cmnd->device;
1318
1319                         sdev_printk(KERN_INFO, sdp,
1320                                 "non-zero result=0x%x\n",
1321                                 scsi_result);
1322                 }
1323         }
1324         if (cmnd && devip) {
1325                 /* simulate autosense by this driver */
1326                 if (SAM_STAT_CHECK_CONDITION == (scsi_result & 0xff))
1327                         memcpy(cmnd->sense_buffer, devip->sense_buff,
1328                                (SCSI_SENSE_BUFFERSIZE > SDEBUG_SENSE_LEN) ?
1329                                SDEBUG_SENSE_LEN : SCSI_SENSE_BUFFERSIZE);
1330         }
1331         if (delta_jiff <= 0) {
1332                 if (cmnd)
1333                         cmnd->result = scsi_result;
1334                 if (done)
1335                         done(cmnd);
1336                 return 0;
1337         } else {
1338                 unsigned long iflags;
1339                 int k;
1340                 struct sdebug_queued_cmd * sqcp = NULL;
1341
1342                 spin_lock_irqsave(&queued_arr_lock, iflags);
1343                 for (k = 0; k < SCSI_DEBUG_CANQUEUE; ++k) {
1344                         sqcp = &queued_arr[k];
1345                         if (! sqcp->in_use)
1346                                 break;
1347                 }
1348                 if (k >= SCSI_DEBUG_CANQUEUE) {
1349                         spin_unlock_irqrestore(&queued_arr_lock, iflags);
1350                         printk(KERN_WARNING "scsi_debug: can_queue exceeded\n");
1351                         return 1;       /* report busy to mid level */
1352                 }
1353                 sqcp->in_use = 1;
1354                 sqcp->a_cmnd = cmnd;
1355                 sqcp->scsi_result = scsi_result;
1356                 sqcp->done_funct = done;
1357                 sqcp->cmnd_timer.function = timer_intr_handler;
1358                 sqcp->cmnd_timer.data = k;
1359                 sqcp->cmnd_timer.expires = jiffies + delta_jiff;
1360                 add_timer(&sqcp->cmnd_timer);
1361                 spin_unlock_irqrestore(&queued_arr_lock, iflags);
1362                 if (cmnd)
1363                         cmnd->result = 0;
1364                 return 0;
1365         }
1366 }
1367
1368 /* Set 'perm' (4th argument) to 0 to disable module_param's definition
1369  * of sysfs parameters (which module_param doesn't yet support).
1370  * Sysfs parameters defined explicitly below.
1371  */
1372 module_param_named(add_host, scsi_debug_add_host, int, 0); /* perm=0644 */
1373 module_param_named(delay, scsi_debug_delay, int, 0); /* perm=0644 */
1374 module_param_named(dev_size_mb, scsi_debug_dev_size_mb, int, 0);
1375 module_param_named(dsense, scsi_debug_dsense, int, 0);
1376 module_param_named(every_nth, scsi_debug_every_nth, int, 0);
1377 module_param_named(max_luns, scsi_debug_max_luns, int, 0);
1378 module_param_named(num_parts, scsi_debug_num_parts, int, 0);
1379 module_param_named(num_tgts, scsi_debug_num_tgts, int, 0);
1380 module_param_named(opts, scsi_debug_opts, int, 0); /* perm=0644 */
1381 module_param_named(ptype, scsi_debug_ptype, int, 0);
1382 module_param_named(scsi_level, scsi_debug_scsi_level, int, 0);
1383
1384 MODULE_AUTHOR("Eric Youngdale + Douglas Gilbert");
1385 MODULE_DESCRIPTION("SCSI debug adapter driver");
1386 MODULE_LICENSE("GPL");
1387 MODULE_VERSION(SCSI_DEBUG_VERSION);
1388
1389 MODULE_PARM_DESC(add_host, "0..127 hosts allowed(def=1)");
1390 MODULE_PARM_DESC(delay, "# of jiffies to delay response(def=1)");
1391 MODULE_PARM_DESC(dev_size_mb, "size in MB of ram shared by devs");
1392 MODULE_PARM_DESC(dsense, "use descriptor sense format(def: fixed)");
1393 MODULE_PARM_DESC(every_nth, "timeout every nth command(def=100)");
1394 MODULE_PARM_DESC(max_luns, "number of SCSI LUNs per target to simulate");
1395 MODULE_PARM_DESC(num_parts, "number of partitions(def=0)");
1396 MODULE_PARM_DESC(num_tgts, "number of SCSI targets per host to simulate");
1397 MODULE_PARM_DESC(opts, "1->noise, 2->medium_error, 4->...");
1398 MODULE_PARM_DESC(ptype, "SCSI peripheral type(def=0[disk])");
1399 MODULE_PARM_DESC(scsi_level, "SCSI level to simulate(def=5[SPC-3])");
1400
1401
1402 static char sdebug_info[256];
1403
1404 static const char * scsi_debug_info(struct Scsi_Host * shp)
1405 {
1406         sprintf(sdebug_info, "scsi_debug, version %s [%s], "
1407                 "dev_size_mb=%d, opts=0x%x", SCSI_DEBUG_VERSION,
1408                 scsi_debug_version_date, scsi_debug_dev_size_mb,
1409                 scsi_debug_opts);
1410         return sdebug_info;
1411 }
1412
1413 /* scsi_debug_proc_info
1414  * Used if the driver currently has no own support for /proc/scsi
1415  */
1416 static int scsi_debug_proc_info(struct Scsi_Host *host, char *buffer, char **start, off_t offset,
1417                                 int length, int inout)
1418 {
1419         int len, pos, begin;
1420         int orig_length;
1421
1422         orig_length = length;
1423
1424         if (inout == 1) {
1425                 char arr[16];
1426                 int minLen = length > 15 ? 15 : length;
1427
1428                 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
1429                         return -EACCES;
1430                 memcpy(arr, buffer, minLen);
1431                 arr[minLen] = '\0';
1432                 if (1 != sscanf(arr, "%d", &pos))
1433                         return -EINVAL;
1434                 scsi_debug_opts = pos;
1435                 if (scsi_debug_every_nth != 0)
1436                         scsi_debug_cmnd_count = 0;
1437                 return length;
1438         }
1439         begin = 0;
1440         pos = len = sprintf(buffer, "scsi_debug adapter driver, version "
1441             "%s [%s]\n"
1442             "num_tgts=%d, shared (ram) size=%d MB, opts=0x%x, "
1443             "every_nth=%d(curr:%d)\n"
1444             "delay=%d, max_luns=%d, scsi_level=%d\n"
1445             "sector_size=%d bytes, cylinders=%d, heads=%d, sectors=%d\n"
1446             "number of aborts=%d, device_reset=%d, bus_resets=%d, "
1447             "host_resets=%d\n",
1448             SCSI_DEBUG_VERSION, scsi_debug_version_date, scsi_debug_num_tgts,
1449             scsi_debug_dev_size_mb, scsi_debug_opts, scsi_debug_every_nth,
1450             scsi_debug_cmnd_count, scsi_debug_delay,
1451             scsi_debug_max_luns, scsi_debug_scsi_level,
1452             SECT_SIZE, sdebug_cylinders_per, sdebug_heads, sdebug_sectors_per,
1453             num_aborts, num_dev_resets, num_bus_resets, num_host_resets);
1454         if (pos < offset) {
1455                 len = 0;
1456                 begin = pos;
1457         }
1458         *start = buffer + (offset - begin);     /* Start of wanted data */
1459         len -= (offset - begin);
1460         if (len > length)
1461                 len = length;
1462         return len;
1463 }
1464
1465 static ssize_t sdebug_delay_show(struct device_driver * ddp, char * buf)
1466 {
1467         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_delay);
1468 }
1469
1470 static ssize_t sdebug_delay_store(struct device_driver * ddp,
1471                                   const char * buf, size_t count)
1472 {
1473         int delay;
1474         char work[20];
1475
1476         if (1 == sscanf(buf, "%10s", work)) {
1477                 if ((1 == sscanf(work, "%d", &delay)) && (delay >= 0)) {
1478                         scsi_debug_delay = delay;
1479                         return count;
1480                 }
1481         }
1482         return -EINVAL;
1483 }
1484 DRIVER_ATTR(delay, S_IRUGO | S_IWUSR, sdebug_delay_show,
1485             sdebug_delay_store);
1486
1487 static ssize_t sdebug_opts_show(struct device_driver * ddp, char * buf)
1488 {
1489         return scnprintf(buf, PAGE_SIZE, "0x%x\n", scsi_debug_opts);
1490 }
1491
1492 static ssize_t sdebug_opts_store(struct device_driver * ddp,
1493                                  const char * buf, size_t count)
1494 {
1495         int opts;
1496         char work[20];
1497
1498         if (1 == sscanf(buf, "%10s", work)) {
1499                 if (0 == strnicmp(work,"0x", 2)) {
1500                         if (1 == sscanf(&work[2], "%x", &opts))
1501                                 goto opts_done;
1502                 } else {
1503                         if (1 == sscanf(work, "%d", &opts))
1504                                 goto opts_done;
1505                 }
1506         }
1507         return -EINVAL;
1508 opts_done:
1509         scsi_debug_opts = opts;
1510         scsi_debug_cmnd_count = 0;
1511         return count;
1512 }
1513 DRIVER_ATTR(opts, S_IRUGO | S_IWUSR, sdebug_opts_show,
1514             sdebug_opts_store);
1515
1516 static ssize_t sdebug_ptype_show(struct device_driver * ddp, char * buf)
1517 {
1518         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_ptype);
1519 }
1520 static ssize_t sdebug_ptype_store(struct device_driver * ddp,
1521                                   const char * buf, size_t count)
1522 {
1523         int n;
1524
1525         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
1526                 scsi_debug_ptype = n;
1527                 return count;
1528         }
1529         return -EINVAL;
1530 }
1531 DRIVER_ATTR(ptype, S_IRUGO | S_IWUSR, sdebug_ptype_show, sdebug_ptype_store);
1532
1533 static ssize_t sdebug_dsense_show(struct device_driver * ddp, char * buf)
1534 {
1535         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_dsense);
1536 }
1537 static ssize_t sdebug_dsense_store(struct device_driver * ddp,
1538                                   const char * buf, size_t count)
1539 {
1540         int n;
1541
1542         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
1543                 scsi_debug_dsense = n;
1544                 return count;
1545         }
1546         return -EINVAL;
1547 }
1548 DRIVER_ATTR(dsense, S_IRUGO | S_IWUSR, sdebug_dsense_show,
1549             sdebug_dsense_store);
1550
1551 static ssize_t sdebug_num_tgts_show(struct device_driver * ddp, char * buf)
1552 {
1553         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_num_tgts);
1554 }
1555 static ssize_t sdebug_num_tgts_store(struct device_driver * ddp,
1556                                      const char * buf, size_t count)
1557 {
1558         int n;
1559
1560         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
1561                 scsi_debug_num_tgts = n;
1562                 sdebug_max_tgts_luns();
1563                 return count;
1564         }
1565         return -EINVAL;
1566 }
1567 DRIVER_ATTR(num_tgts, S_IRUGO | S_IWUSR, sdebug_num_tgts_show,
1568             sdebug_num_tgts_store);
1569
1570 static ssize_t sdebug_dev_size_mb_show(struct device_driver * ddp, char * buf)
1571 {
1572         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_dev_size_mb);
1573 }
1574 DRIVER_ATTR(dev_size_mb, S_IRUGO, sdebug_dev_size_mb_show, NULL);
1575
1576 static ssize_t sdebug_num_parts_show(struct device_driver * ddp, char * buf)
1577 {
1578         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_num_parts);
1579 }
1580 DRIVER_ATTR(num_parts, S_IRUGO, sdebug_num_parts_show, NULL);
1581
1582 static ssize_t sdebug_every_nth_show(struct device_driver * ddp, char * buf)
1583 {
1584         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_every_nth);
1585 }
1586 static ssize_t sdebug_every_nth_store(struct device_driver * ddp,
1587                                       const char * buf, size_t count)
1588 {
1589         int nth;
1590
1591         if ((count > 0) && (1 == sscanf(buf, "%d", &nth))) {
1592                 scsi_debug_every_nth = nth;
1593                 scsi_debug_cmnd_count = 0;
1594                 return count;
1595         }
1596         return -EINVAL;
1597 }
1598 DRIVER_ATTR(every_nth, S_IRUGO | S_IWUSR, sdebug_every_nth_show,
1599             sdebug_every_nth_store);
1600
1601 static ssize_t sdebug_max_luns_show(struct device_driver * ddp, char * buf)
1602 {
1603         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_max_luns);
1604 }
1605 static ssize_t sdebug_max_luns_store(struct device_driver * ddp,
1606                                      const char * buf, size_t count)
1607 {
1608         int n;
1609
1610         if ((count > 0) && (1 == sscanf(buf, "%d", &n)) && (n >= 0)) {
1611                 scsi_debug_max_luns = n;
1612                 sdebug_max_tgts_luns();
1613                 return count;
1614         }
1615         return -EINVAL;
1616 }
1617 DRIVER_ATTR(max_luns, S_IRUGO | S_IWUSR, sdebug_max_luns_show,
1618             sdebug_max_luns_store);
1619
1620 static ssize_t sdebug_scsi_level_show(struct device_driver * ddp, char * buf)
1621 {
1622         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_scsi_level);
1623 }
1624 DRIVER_ATTR(scsi_level, S_IRUGO, sdebug_scsi_level_show, NULL);
1625
1626 static ssize_t sdebug_add_host_show(struct device_driver * ddp, char * buf)
1627 {
1628         return scnprintf(buf, PAGE_SIZE, "%d\n", scsi_debug_add_host);
1629 }
1630
1631 static ssize_t sdebug_add_host_store(struct device_driver * ddp,
1632                                      const char * buf, size_t count)
1633 {
1634         int delta_hosts;
1635         char work[20];
1636
1637         if (1 != sscanf(buf, "%10s", work))
1638                 return -EINVAL;
1639         {       /* temporary hack around sscanf() problem with -ve nums */
1640                 int neg = 0;
1641
1642                 if ('-' == *work)
1643                         neg = 1;
1644                 if (1 != sscanf(work + neg, "%d", &delta_hosts))
1645                         return -EINVAL;
1646                 if (neg)
1647                         delta_hosts = -delta_hosts;
1648         }
1649         if (delta_hosts > 0) {
1650                 do {
1651                         sdebug_add_adapter();
1652                 } while (--delta_hosts);
1653         } else if (delta_hosts < 0) {
1654                 do {
1655                         sdebug_remove_adapter();
1656                 } while (++delta_hosts);
1657         }
1658         return count;
1659 }
1660 DRIVER_ATTR(add_host, S_IRUGO | S_IWUSR, sdebug_add_host_show, 
1661             sdebug_add_host_store);
1662
1663 static void do_create_driverfs_files(void)
1664 {
1665         driver_create_file(&sdebug_driverfs_driver, &driver_attr_add_host);
1666         driver_create_file(&sdebug_driverfs_driver, &driver_attr_delay);
1667         driver_create_file(&sdebug_driverfs_driver, &driver_attr_dev_size_mb);
1668         driver_create_file(&sdebug_driverfs_driver, &driver_attr_dsense);
1669         driver_create_file(&sdebug_driverfs_driver, &driver_attr_every_nth);
1670         driver_create_file(&sdebug_driverfs_driver, &driver_attr_max_luns);
1671         driver_create_file(&sdebug_driverfs_driver, &driver_attr_num_tgts);
1672         driver_create_file(&sdebug_driverfs_driver, &driver_attr_num_parts);
1673         driver_create_file(&sdebug_driverfs_driver, &driver_attr_ptype);
1674         driver_create_file(&sdebug_driverfs_driver, &driver_attr_opts);
1675         driver_create_file(&sdebug_driverfs_driver, &driver_attr_scsi_level);
1676 }
1677
1678 static void do_remove_driverfs_files(void)
1679 {
1680         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_scsi_level);
1681         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_opts);
1682         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_ptype);
1683         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_num_parts);
1684         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_num_tgts);
1685         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_max_luns);
1686         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_every_nth);
1687         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_dsense);
1688         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_dev_size_mb);
1689         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_delay);
1690         driver_remove_file(&sdebug_driverfs_driver, &driver_attr_add_host);
1691 }
1692
1693 static int __init scsi_debug_init(void)
1694 {
1695         unsigned long sz;
1696         int host_to_add;
1697         int k;
1698
1699         if (scsi_debug_dev_size_mb < 1)
1700                 scsi_debug_dev_size_mb = 1;  /* force minimum 1 MB ramdisk */
1701         sdebug_store_size = (unsigned long)scsi_debug_dev_size_mb * 1048576;
1702         sdebug_capacity = sdebug_store_size / SECT_SIZE;
1703
1704         /* play around with geometry, don't waste too much on track 0 */
1705         sdebug_heads = 8;
1706         sdebug_sectors_per = 32;
1707         if (scsi_debug_dev_size_mb >= 16)
1708                 sdebug_heads = 32;
1709         else if (scsi_debug_dev_size_mb >= 256)
1710                 sdebug_heads = 64;
1711         sdebug_cylinders_per = (unsigned long)sdebug_capacity /
1712                                (sdebug_sectors_per * sdebug_heads);
1713         if (sdebug_cylinders_per >= 1024) {
1714                 /* other LLDs do this; implies >= 1GB ram disk ... */
1715                 sdebug_heads = 255;
1716                 sdebug_sectors_per = 63;
1717                 sdebug_cylinders_per = (unsigned long)sdebug_capacity /
1718                                (sdebug_sectors_per * sdebug_heads);
1719         }
1720
1721         sz = sdebug_store_size;
1722         fake_storep = vmalloc(sz);
1723         if (NULL == fake_storep) {
1724                 printk(KERN_ERR "scsi_debug_init: out of memory, 1\n");
1725                 return -ENOMEM;
1726         }
1727         memset(fake_storep, 0, sz);
1728         if (scsi_debug_num_parts > 0)
1729                 sdebug_build_parts(fake_storep);
1730
1731         init_all_queued();
1732
1733         device_register(&pseudo_primary);
1734         bus_register(&pseudo_lld_bus);
1735         driver_register(&sdebug_driverfs_driver);
1736         do_create_driverfs_files();
1737
1738         sdebug_driver_template.proc_name = (char *)sdebug_proc_name;
1739
1740         host_to_add = scsi_debug_add_host;
1741         scsi_debug_add_host = 0;
1742
1743         for (k = 0; k < host_to_add; k++) {
1744                 if (sdebug_add_adapter()) {
1745                         printk(KERN_ERR "scsi_debug_init: "
1746                                "sdebug_add_adapter failed k=%d\n", k);
1747                         break;
1748                 }
1749         }
1750
1751         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts) {
1752                 printk(KERN_INFO "scsi_debug_init: built %d host(s)\n",
1753                        scsi_debug_add_host);
1754         }
1755         return 0;
1756 }
1757
1758 static void __exit scsi_debug_exit(void)
1759 {
1760         int k = scsi_debug_add_host;
1761
1762         stop_all_queued();
1763         for (; k; k--)
1764                 sdebug_remove_adapter();
1765         do_remove_driverfs_files();
1766         driver_unregister(&sdebug_driverfs_driver);
1767         bus_unregister(&pseudo_lld_bus);
1768         device_unregister(&pseudo_primary);
1769
1770         vfree(fake_storep);
1771 }
1772
1773 device_initcall(scsi_debug_init);
1774 module_exit(scsi_debug_exit);
1775
1776 static void pseudo_0_release(struct device * dev)
1777 {
1778         if (SCSI_DEBUG_OPT_NOISE & scsi_debug_opts)
1779                 printk(KERN_INFO "scsi_debug: pseudo_0_release() called\n");
1780 }
1781
1782 static struct device pseudo_primary = {
1783         .bus_id         = "pseudo_0",
1784         .release        = pseudo_0_release,
1785 };
1786
1787 static int pseudo_lld_bus_match(struct device *dev,
1788                           struct device_driver *dev_driver)
1789 {
1790         return 1;
1791 }
1792
1793 static struct bus_type pseudo_lld_bus = {
1794         .name = "pseudo",
1795         .match = pseudo_lld_bus_match,
1796         .probe = sdebug_driver_probe,
1797         .remove = sdebug_driver_remove,
1798 };
1799
1800 static void sdebug_release_adapter(struct device * dev)
1801 {
1802         struct sdebug_host_info *sdbg_host;
1803
1804         sdbg_host = to_sdebug_host(dev);
1805         kfree(sdbg_host);
1806 }
1807
1808 static int sdebug_add_adapter(void)
1809 {
1810         int k, devs_per_host;
1811         int error = 0;
1812         struct sdebug_host_info *sdbg_host;
1813         struct sdebug_dev_info *sdbg_devinfo;
1814         struct list_head *lh, *lh_sf;
1815
1816         sdbg_host = kzalloc(sizeof(*sdbg_host), GFP_KERNEL);
1817
1818         if (NULL == sdbg_host) {
1819                 printk(KERN_ERR "%s: out of memory at line %d\n",
1820                        __FUNCTION__, __LINE__);
1821                 return -ENOMEM;
1822         }
1823
1824         INIT_LIST_HEAD(&sdbg_host->dev_info_list);
1825
1826         devs_per_host = scsi_debug_num_tgts * scsi_debug_max_luns;
1827         for (k = 0; k < devs_per_host; k++) {
1828                 sdbg_devinfo = kzalloc(sizeof(*sdbg_devinfo), GFP_KERNEL);
1829                 if (NULL == sdbg_devinfo) {
1830                         printk(KERN_ERR "%s: out of memory at line %d\n",
1831                                __FUNCTION__, __LINE__);
1832                         error = -ENOMEM;
1833                         goto clean;
1834                 }
1835                 sdbg_devinfo->sdbg_host = sdbg_host;
1836                 list_add_tail(&sdbg_devinfo->dev_list,
1837                               &sdbg_host->dev_info_list);
1838         }
1839
1840         spin_lock(&sdebug_host_list_lock);
1841         list_add_tail(&sdbg_host->host_list, &sdebug_host_list);
1842         spin_unlock(&sdebug_host_list_lock);
1843
1844         sdbg_host->dev.bus = &pseudo_lld_bus;
1845         sdbg_host->dev.parent = &pseudo_primary;
1846         sdbg_host->dev.release = &sdebug_release_adapter;
1847         sprintf(sdbg_host->dev.bus_id, "adapter%d", scsi_debug_add_host);
1848
1849         error = device_register(&sdbg_host->dev);
1850
1851         if (error)
1852                 goto clean;
1853
1854         ++scsi_debug_add_host;
1855         return error;
1856
1857 clean:
1858         list_for_each_safe(lh, lh_sf, &sdbg_host->dev_info_list) {
1859                 sdbg_devinfo = list_entry(lh, struct sdebug_dev_info,
1860                                           dev_list);
1861                 list_del(&sdbg_devinfo->dev_list);
1862                 kfree(sdbg_devinfo);
1863         }
1864
1865         kfree(sdbg_host);
1866         return error;
1867 }
1868
1869 static void sdebug_remove_adapter(void)
1870 {
1871         struct sdebug_host_info * sdbg_host = NULL;
1872
1873         spin_lock(&sdebug_host_list_lock);
1874         if (!list_empty(&sdebug_host_list)) {
1875                 sdbg_host = list_entry(sdebug_host_list.prev,
1876                                        struct sdebug_host_info, host_list);
1877                 list_del(&sdbg_host->host_list);
1878         }
1879         spin_unlock(&sdebug_host_list_lock);
1880
1881         if (!sdbg_host)
1882                 return;
1883
1884         device_unregister(&sdbg_host->dev);
1885         --scsi_debug_add_host;
1886 }
1887
1888 static int sdebug_driver_probe(struct device * dev)
1889 {
1890         int error = 0;
1891         struct sdebug_host_info *sdbg_host;
1892         struct Scsi_Host *hpnt;
1893
1894         sdbg_host = to_sdebug_host(dev);
1895
1896         hpnt = scsi_host_alloc(&sdebug_driver_template, sizeof(sdbg_host));
1897         if (NULL == hpnt) {
1898                 printk(KERN_ERR "%s: scsi_register failed\n", __FUNCTION__);
1899                 error = -ENODEV;
1900                 return error;
1901         }
1902
1903         sdbg_host->shost = hpnt;
1904         *((struct sdebug_host_info **)hpnt->hostdata) = sdbg_host;
1905         if ((hpnt->this_id >= 0) && (scsi_debug_num_tgts > hpnt->this_id))
1906                 hpnt->max_id = scsi_debug_num_tgts + 1;
1907         else
1908                 hpnt->max_id = scsi_debug_num_tgts;
1909         hpnt->max_lun = scsi_debug_max_luns;
1910
1911         error = scsi_add_host(hpnt, &sdbg_host->dev);
1912         if (error) {
1913                 printk(KERN_ERR "%s: scsi_add_host failed\n", __FUNCTION__);
1914                 error = -ENODEV;
1915                 scsi_host_put(hpnt);
1916         } else
1917                 scsi_scan_host(hpnt);
1918
1919
1920         return error;
1921 }
1922
1923 static int sdebug_driver_remove(struct device * dev)
1924 {
1925         struct list_head *lh, *lh_sf;
1926         struct sdebug_host_info *sdbg_host;
1927         struct sdebug_dev_info *sdbg_devinfo;
1928
1929         sdbg_host = to_sdebug_host(dev);
1930
1931         if (!sdbg_host) {
1932                 printk(KERN_ERR "%s: Unable to locate host info\n",
1933                        __FUNCTION__);
1934                 return -ENODEV;
1935         }
1936
1937         scsi_remove_host(sdbg_host->shost);
1938
1939         list_for_each_safe(lh, lh_sf, &sdbg_host->dev_info_list) {
1940                 sdbg_devinfo = list_entry(lh, struct sdebug_dev_info,
1941                                           dev_list);
1942                 list_del(&sdbg_devinfo->dev_list);
1943                 kfree(sdbg_devinfo);
1944         }
1945
1946         scsi_host_put(sdbg_host->shost);
1947         return 0;
1948 }
1949
1950 static void sdebug_max_tgts_luns(void)
1951 {
1952         struct sdebug_host_info * sdbg_host;
1953         struct Scsi_Host *hpnt;
1954
1955         spin_lock(&sdebug_host_list_lock);
1956         list_for_each_entry(sdbg_host, &sdebug_host_list, host_list) {
1957                 hpnt = sdbg_host->shost;
1958                 if ((hpnt->this_id >= 0) &&
1959                     (scsi_debug_num_tgts > hpnt->this_id))
1960                         hpnt->max_id = scsi_debug_num_tgts + 1;
1961                 else
1962                         hpnt->max_id = scsi_debug_num_tgts;
1963                 hpnt->max_lun = scsi_debug_max_luns;
1964         }
1965         spin_unlock(&sdebug_host_list_lock);
1966 }