[SCSI] Remove devfs support from the SCSI subsystem
[linux-3.10.git] / drivers / scsi / sg.c
1 /*
2  *  History:
3  *  Started: Aug 9 by Lawrence Foard (entropy@world.std.com),
4  *           to allow user process control of SCSI devices.
5  *  Development Sponsored by Killy Corp. NY NY
6  *
7  * Original driver (sg.c):
8  *        Copyright (C) 1992 Lawrence Foard
9  * Version 2 and 3 extensions to driver:
10  *        Copyright (C) 1998 - 2005 Douglas Gilbert
11  *
12  *  Modified  19-JAN-1998  Richard Gooch <rgooch@atnf.csiro.au>  Devfs support
13  *
14  * This program is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 2, or (at your option)
17  * any later version.
18  *
19  */
20
21 static int sg_version_num = 30533;      /* 2 digits for each component */
22 #define SG_VERSION_STR "3.5.33"
23
24 /*
25  *  D. P. Gilbert (dgilbert@interlog.com, dougg@triode.net.au), notes:
26  *      - scsi logging is available via SCSI_LOG_TIMEOUT macros. First
27  *        the kernel/module needs to be built with CONFIG_SCSI_LOGGING
28  *        (otherwise the macros compile to empty statements).
29  *
30  */
31 #include <linux/config.h>
32 #include <linux/module.h>
33
34 #include <linux/fs.h>
35 #include <linux/kernel.h>
36 #include <linux/sched.h>
37 #include <linux/string.h>
38 #include <linux/mm.h>
39 #include <linux/errno.h>
40 #include <linux/mtio.h>
41 #include <linux/ioctl.h>
42 #include <linux/fcntl.h>
43 #include <linux/init.h>
44 #include <linux/poll.h>
45 #include <linux/smp_lock.h>
46 #include <linux/moduleparam.h>
47 #include <linux/cdev.h>
48 #include <linux/seq_file.h>
49 #include <linux/blkdev.h>
50 #include <linux/delay.h>
51 #include <linux/scatterlist.h>
52
53 #include "scsi.h"
54 #include <scsi/scsi_dbg.h>
55 #include <scsi/scsi_host.h>
56 #include <scsi/scsi_driver.h>
57 #include <scsi/scsi_ioctl.h>
58 #include <scsi/sg.h>
59
60 #include "scsi_logging.h"
61
62 #ifdef CONFIG_SCSI_PROC_FS
63 #include <linux/proc_fs.h>
64 static char *sg_version_date = "20050908";
65
66 static int sg_proc_init(void);
67 static void sg_proc_cleanup(void);
68 #endif
69
70 #define SG_ALLOW_DIO_DEF 0
71 #define SG_ALLOW_DIO_CODE /* compile out by commenting this define */
72
73 #define SG_MAX_DEVS 32768
74
75 /*
76  * Suppose you want to calculate the formula muldiv(x,m,d)=int(x * m / d)
77  * Then when using 32 bit integers x * m may overflow during the calculation.
78  * Replacing muldiv(x) by muldiv(x)=((x % d) * m) / d + int(x / d) * m
79  * calculates the same, but prevents the overflow when both m and d
80  * are "small" numbers (like HZ and USER_HZ).
81  * Of course an overflow is inavoidable if the result of muldiv doesn't fit
82  * in 32 bits.
83  */
84 #define MULDIV(X,MUL,DIV) ((((X % DIV) * MUL) / DIV) + ((X / DIV) * MUL))
85
86 #define SG_DEFAULT_TIMEOUT MULDIV(SG_DEFAULT_TIMEOUT_USER, HZ, USER_HZ)
87
88 int sg_big_buff = SG_DEF_RESERVED_SIZE;
89 /* N.B. This variable is readable and writeable via
90    /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
91    of this size (or less if there is not enough memory) will be reserved
92    for use by this file descriptor. [Deprecated usage: this variable is also
93    readable via /proc/sys/kernel/sg-big-buff if the sg driver is built into
94    the kernel (i.e. it is not a module).] */
95 static int def_reserved_size = -1;      /* picks up init parameter */
96 static int sg_allow_dio = SG_ALLOW_DIO_DEF;
97
98 #define SG_SECTOR_SZ 512
99 #define SG_SECTOR_MSK (SG_SECTOR_SZ - 1)
100
101 #define SG_DEV_ARR_LUMP 32      /* amount to over allocate sg_dev_arr by */
102
103 static int sg_add(struct class_device *, struct class_interface *);
104 static void sg_remove(struct class_device *, struct class_interface *);
105
106 static DEFINE_RWLOCK(sg_dev_arr_lock);  /* Also used to lock
107                                                            file descriptor list for device */
108
109 static struct class_interface sg_interface = {
110         .add            = sg_add,
111         .remove         = sg_remove,
112 };
113
114 typedef struct sg_scatter_hold { /* holding area for scsi scatter gather info */
115         unsigned short k_use_sg; /* Count of kernel scatter-gather pieces */
116         unsigned short sglist_len; /* size of malloc'd scatter-gather list ++ */
117         unsigned bufflen;       /* Size of (aggregate) data buffer */
118         unsigned b_malloc_len;  /* actual len malloc'ed in buffer */
119         struct scatterlist *buffer;/* scatter list */
120         char dio_in_use;        /* 0->indirect IO (or mmap), 1->dio */
121         unsigned char cmd_opcode; /* first byte of command */
122 } Sg_scatter_hold;
123
124 struct sg_device;               /* forward declarations */
125 struct sg_fd;
126
127 typedef struct sg_request {     /* SG_MAX_QUEUE requests outstanding per file */
128         struct sg_request *nextrp;      /* NULL -> tail request (slist) */
129         struct sg_fd *parentfp; /* NULL -> not in use */
130         Sg_scatter_hold data;   /* hold buffer, perhaps scatter list */
131         sg_io_hdr_t header;     /* scsi command+info, see <scsi/sg.h> */
132         unsigned char sense_b[SCSI_SENSE_BUFFERSIZE];
133         char res_used;          /* 1 -> using reserve buffer, 0 -> not ... */
134         char orphan;            /* 1 -> drop on sight, 0 -> normal */
135         char sg_io_owned;       /* 1 -> packet belongs to SG_IO */
136         volatile char done;     /* 0->before bh, 1->before read, 2->read */
137 } Sg_request;
138
139 typedef struct sg_fd {          /* holds the state of a file descriptor */
140         struct sg_fd *nextfp;   /* NULL when last opened fd on this device */
141         struct sg_device *parentdp;     /* owning device */
142         wait_queue_head_t read_wait;    /* queue read until command done */
143         rwlock_t rq_list_lock;  /* protect access to list in req_arr */
144         int timeout;            /* defaults to SG_DEFAULT_TIMEOUT      */
145         int timeout_user;       /* defaults to SG_DEFAULT_TIMEOUT_USER */
146         Sg_scatter_hold reserve;        /* buffer held for this file descriptor */
147         unsigned save_scat_len; /* original length of trunc. scat. element */
148         Sg_request *headrp;     /* head of request slist, NULL->empty */
149         struct fasync_struct *async_qp; /* used by asynchronous notification */
150         Sg_request req_arr[SG_MAX_QUEUE];       /* used as singly-linked list */
151         char low_dma;           /* as in parent but possibly overridden to 1 */
152         char force_packid;      /* 1 -> pack_id input to read(), 0 -> ignored */
153         volatile char closed;   /* 1 -> fd closed but request(s) outstanding */
154         char cmd_q;             /* 1 -> allow command queuing, 0 -> don't */
155         char next_cmd_len;      /* 0 -> automatic (def), >0 -> use on next write() */
156         char keep_orphan;       /* 0 -> drop orphan (def), 1 -> keep for read() */
157         char mmap_called;       /* 0 -> mmap() never called on this fd */
158 } Sg_fd;
159
160 typedef struct sg_device { /* holds the state of each scsi generic device */
161         struct scsi_device *device;
162         wait_queue_head_t o_excl_wait;  /* queue open() when O_EXCL in use */
163         int sg_tablesize;       /* adapter's max scatter-gather table size */
164         Sg_fd *headfp;          /* first open fd belonging to this device */
165         volatile char detached; /* 0->attached, 1->detached pending removal */
166         volatile char exclude;  /* opened for exclusive access */
167         char sgdebug;           /* 0->off, 1->sense, 9->dump dev, 10-> all devs */
168         struct gendisk *disk;
169         struct cdev * cdev;     /* char_dev [sysfs: /sys/cdev/major/sg<n>] */
170 } Sg_device;
171
172 static int sg_fasync(int fd, struct file *filp, int mode);
173 /* tasklet or soft irq callback */
174 static void sg_cmd_done(void *data, char *sense, int result, int resid);
175 static int sg_start_req(Sg_request * srp);
176 static void sg_finish_rem_req(Sg_request * srp);
177 static int sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size);
178 static int sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp,
179                          int tablesize);
180 static ssize_t sg_new_read(Sg_fd * sfp, char __user *buf, size_t count,
181                            Sg_request * srp);
182 static ssize_t sg_new_write(Sg_fd * sfp, const char __user *buf, size_t count,
183                             int blocking, int read_only, Sg_request ** o_srp);
184 static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
185                            unsigned char *cmnd, int timeout, int blocking);
186 static int sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
187                       int wr_xf, int *countp, unsigned char __user **up);
188 static int sg_write_xfer(Sg_request * srp);
189 static int sg_read_xfer(Sg_request * srp);
190 static int sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer);
191 static void sg_remove_scat(Sg_scatter_hold * schp);
192 static void sg_build_reserve(Sg_fd * sfp, int req_size);
193 static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);
194 static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);
195 static struct page *sg_page_malloc(int rqSz, int lowDma, int *retSzp);
196 static void sg_page_free(struct page *page, int size);
197 static Sg_fd *sg_add_sfp(Sg_device * sdp, int dev);
198 static int sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
199 static void __sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
200 static Sg_request *sg_get_rq_mark(Sg_fd * sfp, int pack_id);
201 static Sg_request *sg_add_request(Sg_fd * sfp);
202 static int sg_remove_request(Sg_fd * sfp, Sg_request * srp);
203 static int sg_res_in_use(Sg_fd * sfp);
204 static int sg_allow_access(unsigned char opcode, char dev_type);
205 static int sg_build_direct(Sg_request * srp, Sg_fd * sfp, int dxfer_len);
206 static Sg_device *sg_get_dev(int dev);
207 #ifdef CONFIG_SCSI_PROC_FS
208 static int sg_last_dev(void);
209 #endif
210
211 static Sg_device **sg_dev_arr = NULL;
212 static int sg_dev_max;
213 static int sg_nr_dev;
214
215 #define SZ_SG_HEADER sizeof(struct sg_header)
216 #define SZ_SG_IO_HDR sizeof(sg_io_hdr_t)
217 #define SZ_SG_IOVEC sizeof(sg_iovec_t)
218 #define SZ_SG_REQ_INFO sizeof(sg_req_info_t)
219
220 static int
221 sg_open(struct inode *inode, struct file *filp)
222 {
223         int dev = iminor(inode);
224         int flags = filp->f_flags;
225         struct request_queue *q;
226         Sg_device *sdp;
227         Sg_fd *sfp;
228         int res;
229         int retval;
230
231         nonseekable_open(inode, filp);
232         SCSI_LOG_TIMEOUT(3, printk("sg_open: dev=%d, flags=0x%x\n", dev, flags));
233         sdp = sg_get_dev(dev);
234         if ((!sdp) || (!sdp->device))
235                 return -ENXIO;
236         if (sdp->detached)
237                 return -ENODEV;
238
239         /* This driver's module count bumped by fops_get in <linux/fs.h> */
240         /* Prevent the device driver from vanishing while we sleep */
241         retval = scsi_device_get(sdp->device);
242         if (retval)
243                 return retval;
244
245         if (!((flags & O_NONBLOCK) ||
246               scsi_block_when_processing_errors(sdp->device))) {
247                 retval = -ENXIO;
248                 /* we are in error recovery for this device */
249                 goto error_out;
250         }
251
252         if (flags & O_EXCL) {
253                 if (O_RDONLY == (flags & O_ACCMODE)) {
254                         retval = -EPERM; /* Can't lock it with read only access */
255                         goto error_out;
256                 }
257                 if (sdp->headfp && (flags & O_NONBLOCK)) {
258                         retval = -EBUSY;
259                         goto error_out;
260                 }
261                 res = 0;
262                 __wait_event_interruptible(sdp->o_excl_wait,
263                         ((sdp->headfp || sdp->exclude) ? 0 : (sdp->exclude = 1)), res);
264                 if (res) {
265                         retval = res;   /* -ERESTARTSYS because signal hit process */
266                         goto error_out;
267                 }
268         } else if (sdp->exclude) {      /* some other fd has an exclusive lock on dev */
269                 if (flags & O_NONBLOCK) {
270                         retval = -EBUSY;
271                         goto error_out;
272                 }
273                 res = 0;
274                 __wait_event_interruptible(sdp->o_excl_wait, (!sdp->exclude),
275                                            res);
276                 if (res) {
277                         retval = res;   /* -ERESTARTSYS because signal hit process */
278                         goto error_out;
279                 }
280         }
281         if (sdp->detached) {
282                 retval = -ENODEV;
283                 goto error_out;
284         }
285         if (!sdp->headfp) {     /* no existing opens on this device */
286                 sdp->sgdebug = 0;
287                 q = sdp->device->request_queue;
288                 sdp->sg_tablesize = min(q->max_hw_segments,
289                                         q->max_phys_segments);
290         }
291         if ((sfp = sg_add_sfp(sdp, dev)))
292                 filp->private_data = sfp;
293         else {
294                 if (flags & O_EXCL)
295                         sdp->exclude = 0;       /* undo if error */
296                 retval = -ENOMEM;
297                 goto error_out;
298         }
299         return 0;
300
301       error_out:
302         scsi_device_put(sdp->device);
303         return retval;
304 }
305
306 /* Following function was formerly called 'sg_close' */
307 static int
308 sg_release(struct inode *inode, struct file *filp)
309 {
310         Sg_device *sdp;
311         Sg_fd *sfp;
312
313         if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
314                 return -ENXIO;
315         SCSI_LOG_TIMEOUT(3, printk("sg_release: %s\n", sdp->disk->disk_name));
316         sg_fasync(-1, filp, 0); /* remove filp from async notification list */
317         if (0 == sg_remove_sfp(sdp, sfp)) {     /* Returns 1 when sdp gone */
318                 if (!sdp->detached) {
319                         scsi_device_put(sdp->device);
320                 }
321                 sdp->exclude = 0;
322                 wake_up_interruptible(&sdp->o_excl_wait);
323         }
324         return 0;
325 }
326
327 static ssize_t
328 sg_read(struct file *filp, char __user *buf, size_t count, loff_t * ppos)
329 {
330         Sg_device *sdp;
331         Sg_fd *sfp;
332         Sg_request *srp;
333         int req_pack_id = -1;
334         sg_io_hdr_t *hp;
335         struct sg_header *old_hdr = NULL;
336         int retval = 0;
337
338         if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
339                 return -ENXIO;
340         SCSI_LOG_TIMEOUT(3, printk("sg_read: %s, count=%d\n",
341                                    sdp->disk->disk_name, (int) count));
342
343         if (!access_ok(VERIFY_WRITE, buf, count))
344                 return -EFAULT;
345         if (sfp->force_packid && (count >= SZ_SG_HEADER)) {
346                 old_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL);
347                 if (!old_hdr)
348                         return -ENOMEM;
349                 if (__copy_from_user(old_hdr, buf, SZ_SG_HEADER)) {
350                         retval = -EFAULT;
351                         goto free_old_hdr;
352                 }
353                 if (old_hdr->reply_len < 0) {
354                         if (count >= SZ_SG_IO_HDR) {
355                                 sg_io_hdr_t *new_hdr;
356                                 new_hdr = kmalloc(SZ_SG_IO_HDR, GFP_KERNEL);
357                                 if (!new_hdr) {
358                                         retval = -ENOMEM;
359                                         goto free_old_hdr;
360                                 }
361                                 retval =__copy_from_user
362                                     (new_hdr, buf, SZ_SG_IO_HDR);
363                                 req_pack_id = new_hdr->pack_id;
364                                 kfree(new_hdr);
365                                 if (retval) {
366                                         retval = -EFAULT;
367                                         goto free_old_hdr;
368                                 }
369                         }
370                 } else
371                         req_pack_id = old_hdr->pack_id;
372         }
373         srp = sg_get_rq_mark(sfp, req_pack_id);
374         if (!srp) {             /* now wait on packet to arrive */
375                 if (sdp->detached) {
376                         retval = -ENODEV;
377                         goto free_old_hdr;
378                 }
379                 if (filp->f_flags & O_NONBLOCK) {
380                         retval = -EAGAIN;
381                         goto free_old_hdr;
382                 }
383                 while (1) {
384                         retval = 0; /* following macro beats race condition */
385                         __wait_event_interruptible(sfp->read_wait,
386                                 (sdp->detached ||
387                                 (srp = sg_get_rq_mark(sfp, req_pack_id))), 
388                                 retval);
389                         if (sdp->detached) {
390                                 retval = -ENODEV;
391                                 goto free_old_hdr;
392                         }
393                         if (0 == retval)
394                                 break;
395
396                         /* -ERESTARTSYS as signal hit process */
397                         goto free_old_hdr;
398                 }
399         }
400         if (srp->header.interface_id != '\0') {
401                 retval = sg_new_read(sfp, buf, count, srp);
402                 goto free_old_hdr;
403         }
404
405         hp = &srp->header;
406         if (old_hdr == NULL) {
407                 old_hdr = kmalloc(SZ_SG_HEADER, GFP_KERNEL);
408                 if (! old_hdr) {
409                         retval = -ENOMEM;
410                         goto free_old_hdr;
411                 }
412         }
413         memset(old_hdr, 0, SZ_SG_HEADER);
414         old_hdr->reply_len = (int) hp->timeout;
415         old_hdr->pack_len = old_hdr->reply_len; /* old, strange behaviour */
416         old_hdr->pack_id = hp->pack_id;
417         old_hdr->twelve_byte =
418             ((srp->data.cmd_opcode >= 0xc0) && (12 == hp->cmd_len)) ? 1 : 0;
419         old_hdr->target_status = hp->masked_status;
420         old_hdr->host_status = hp->host_status;
421         old_hdr->driver_status = hp->driver_status;
422         if ((CHECK_CONDITION & hp->masked_status) ||
423             (DRIVER_SENSE & hp->driver_status))
424                 memcpy(old_hdr->sense_buffer, srp->sense_b,
425                        sizeof (old_hdr->sense_buffer));
426         switch (hp->host_status) {
427         /* This setup of 'result' is for backward compatibility and is best
428            ignored by the user who should use target, host + driver status */
429         case DID_OK:
430         case DID_PASSTHROUGH:
431         case DID_SOFT_ERROR:
432                 old_hdr->result = 0;
433                 break;
434         case DID_NO_CONNECT:
435         case DID_BUS_BUSY:
436         case DID_TIME_OUT:
437                 old_hdr->result = EBUSY;
438                 break;
439         case DID_BAD_TARGET:
440         case DID_ABORT:
441         case DID_PARITY:
442         case DID_RESET:
443         case DID_BAD_INTR:
444                 old_hdr->result = EIO;
445                 break;
446         case DID_ERROR:
447                 old_hdr->result = (srp->sense_b[0] == 0 && 
448                                   hp->masked_status == GOOD) ? 0 : EIO;
449                 break;
450         default:
451                 old_hdr->result = EIO;
452                 break;
453         }
454
455         /* Now copy the result back to the user buffer.  */
456         if (count >= SZ_SG_HEADER) {
457                 if (__copy_to_user(buf, old_hdr, SZ_SG_HEADER)) {
458                         retval = -EFAULT;
459                         goto free_old_hdr;
460                 }
461                 buf += SZ_SG_HEADER;
462                 if (count > old_hdr->reply_len)
463                         count = old_hdr->reply_len;
464                 if (count > SZ_SG_HEADER) {
465                         if (sg_read_oxfer(srp, buf, count - SZ_SG_HEADER)) {
466                                 retval = -EFAULT;
467                                 goto free_old_hdr;
468                         }
469                 }
470         } else
471                 count = (old_hdr->result == 0) ? 0 : -EIO;
472         sg_finish_rem_req(srp);
473         retval = count;
474 free_old_hdr:
475         kfree(old_hdr);
476         return retval;
477 }
478
479 static ssize_t
480 sg_new_read(Sg_fd * sfp, char __user *buf, size_t count, Sg_request * srp)
481 {
482         sg_io_hdr_t *hp = &srp->header;
483         int err = 0;
484         int len;
485
486         if (count < SZ_SG_IO_HDR) {
487                 err = -EINVAL;
488                 goto err_out;
489         }
490         hp->sb_len_wr = 0;
491         if ((hp->mx_sb_len > 0) && hp->sbp) {
492                 if ((CHECK_CONDITION & hp->masked_status) ||
493                     (DRIVER_SENSE & hp->driver_status)) {
494                         int sb_len = SCSI_SENSE_BUFFERSIZE;
495                         sb_len = (hp->mx_sb_len > sb_len) ? sb_len : hp->mx_sb_len;
496                         len = 8 + (int) srp->sense_b[7];        /* Additional sense length field */
497                         len = (len > sb_len) ? sb_len : len;
498                         if (copy_to_user(hp->sbp, srp->sense_b, len)) {
499                                 err = -EFAULT;
500                                 goto err_out;
501                         }
502                         hp->sb_len_wr = len;
503                 }
504         }
505         if (hp->masked_status || hp->host_status || hp->driver_status)
506                 hp->info |= SG_INFO_CHECK;
507         if (copy_to_user(buf, hp, SZ_SG_IO_HDR)) {
508                 err = -EFAULT;
509                 goto err_out;
510         }
511         err = sg_read_xfer(srp);
512       err_out:
513         sg_finish_rem_req(srp);
514         return (0 == err) ? count : err;
515 }
516
517 static ssize_t
518 sg_write(struct file *filp, const char __user *buf, size_t count, loff_t * ppos)
519 {
520         int mxsize, cmd_size, k;
521         int input_size, blocking;
522         unsigned char opcode;
523         Sg_device *sdp;
524         Sg_fd *sfp;
525         Sg_request *srp;
526         struct sg_header old_hdr;
527         sg_io_hdr_t *hp;
528         unsigned char cmnd[MAX_COMMAND_SIZE];
529
530         if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
531                 return -ENXIO;
532         SCSI_LOG_TIMEOUT(3, printk("sg_write: %s, count=%d\n",
533                                    sdp->disk->disk_name, (int) count));
534         if (sdp->detached)
535                 return -ENODEV;
536         if (!((filp->f_flags & O_NONBLOCK) ||
537               scsi_block_when_processing_errors(sdp->device)))
538                 return -ENXIO;
539
540         if (!access_ok(VERIFY_READ, buf, count))
541                 return -EFAULT; /* protects following copy_from_user()s + get_user()s */
542         if (count < SZ_SG_HEADER)
543                 return -EIO;
544         if (__copy_from_user(&old_hdr, buf, SZ_SG_HEADER))
545                 return -EFAULT;
546         blocking = !(filp->f_flags & O_NONBLOCK);
547         if (old_hdr.reply_len < 0)
548                 return sg_new_write(sfp, buf, count, blocking, 0, NULL);
549         if (count < (SZ_SG_HEADER + 6))
550                 return -EIO;    /* The minimum scsi command length is 6 bytes. */
551
552         if (!(srp = sg_add_request(sfp))) {
553                 SCSI_LOG_TIMEOUT(1, printk("sg_write: queue full\n"));
554                 return -EDOM;
555         }
556         buf += SZ_SG_HEADER;
557         __get_user(opcode, buf);
558         if (sfp->next_cmd_len > 0) {
559                 if (sfp->next_cmd_len > MAX_COMMAND_SIZE) {
560                         SCSI_LOG_TIMEOUT(1, printk("sg_write: command length too long\n"));
561                         sfp->next_cmd_len = 0;
562                         sg_remove_request(sfp, srp);
563                         return -EIO;
564                 }
565                 cmd_size = sfp->next_cmd_len;
566                 sfp->next_cmd_len = 0;  /* reset so only this write() effected */
567         } else {
568                 cmd_size = COMMAND_SIZE(opcode);        /* based on SCSI command group */
569                 if ((opcode >= 0xc0) && old_hdr.twelve_byte)
570                         cmd_size = 12;
571         }
572         SCSI_LOG_TIMEOUT(4, printk(
573                 "sg_write:   scsi opcode=0x%02x, cmd_size=%d\n", (int) opcode, cmd_size));
574 /* Determine buffer size.  */
575         input_size = count - cmd_size;
576         mxsize = (input_size > old_hdr.reply_len) ? input_size : old_hdr.reply_len;
577         mxsize -= SZ_SG_HEADER;
578         input_size -= SZ_SG_HEADER;
579         if (input_size < 0) {
580                 sg_remove_request(sfp, srp);
581                 return -EIO;    /* User did not pass enough bytes for this command. */
582         }
583         hp = &srp->header;
584         hp->interface_id = '\0';        /* indicator of old interface tunnelled */
585         hp->cmd_len = (unsigned char) cmd_size;
586         hp->iovec_count = 0;
587         hp->mx_sb_len = 0;
588         if (input_size > 0)
589                 hp->dxfer_direction = (old_hdr.reply_len > SZ_SG_HEADER) ?
590                     SG_DXFER_TO_FROM_DEV : SG_DXFER_TO_DEV;
591         else
592                 hp->dxfer_direction = (mxsize > 0) ? SG_DXFER_FROM_DEV : SG_DXFER_NONE;
593         hp->dxfer_len = mxsize;
594         hp->dxferp = (char __user *)buf + cmd_size;
595         hp->sbp = NULL;
596         hp->timeout = old_hdr.reply_len;        /* structure abuse ... */
597         hp->flags = input_size; /* structure abuse ... */
598         hp->pack_id = old_hdr.pack_id;
599         hp->usr_ptr = NULL;
600         if (__copy_from_user(cmnd, buf, cmd_size))
601                 return -EFAULT;
602         /*
603          * SG_DXFER_TO_FROM_DEV is functionally equivalent to SG_DXFER_FROM_DEV,
604          * but is is possible that the app intended SG_DXFER_TO_DEV, because there
605          * is a non-zero input_size, so emit a warning.
606          */
607         if (hp->dxfer_direction == SG_DXFER_TO_FROM_DEV)
608                 if (printk_ratelimit())
609                         printk(KERN_WARNING
610                                "sg_write: data in/out %d/%d bytes for SCSI command 0x%x--"
611                                "guessing data in;\n" KERN_WARNING "   "
612                                "program %s not setting count and/or reply_len properly\n",
613                                old_hdr.reply_len - (int)SZ_SG_HEADER,
614                                input_size, (unsigned int) cmnd[0],
615                                current->comm);
616         k = sg_common_write(sfp, srp, cmnd, sfp->timeout, blocking);
617         return (k < 0) ? k : count;
618 }
619
620 static ssize_t
621 sg_new_write(Sg_fd * sfp, const char __user *buf, size_t count,
622              int blocking, int read_only, Sg_request ** o_srp)
623 {
624         int k;
625         Sg_request *srp;
626         sg_io_hdr_t *hp;
627         unsigned char cmnd[MAX_COMMAND_SIZE];
628         int timeout;
629         unsigned long ul_timeout;
630
631         if (count < SZ_SG_IO_HDR)
632                 return -EINVAL;
633         if (!access_ok(VERIFY_READ, buf, count))
634                 return -EFAULT; /* protects following copy_from_user()s + get_user()s */
635
636         sfp->cmd_q = 1; /* when sg_io_hdr seen, set command queuing on */
637         if (!(srp = sg_add_request(sfp))) {
638                 SCSI_LOG_TIMEOUT(1, printk("sg_new_write: queue full\n"));
639                 return -EDOM;
640         }
641         hp = &srp->header;
642         if (__copy_from_user(hp, buf, SZ_SG_IO_HDR)) {
643                 sg_remove_request(sfp, srp);
644                 return -EFAULT;
645         }
646         if (hp->interface_id != 'S') {
647                 sg_remove_request(sfp, srp);
648                 return -ENOSYS;
649         }
650         if (hp->flags & SG_FLAG_MMAP_IO) {
651                 if (hp->dxfer_len > sfp->reserve.bufflen) {
652                         sg_remove_request(sfp, srp);
653                         return -ENOMEM; /* MMAP_IO size must fit in reserve buffer */
654                 }
655                 if (hp->flags & SG_FLAG_DIRECT_IO) {
656                         sg_remove_request(sfp, srp);
657                         return -EINVAL; /* either MMAP_IO or DIRECT_IO (not both) */
658                 }
659                 if (sg_res_in_use(sfp)) {
660                         sg_remove_request(sfp, srp);
661                         return -EBUSY;  /* reserve buffer already being used */
662                 }
663         }
664         ul_timeout = msecs_to_jiffies(srp->header.timeout);
665         timeout = (ul_timeout < INT_MAX) ? ul_timeout : INT_MAX;
666         if ((!hp->cmdp) || (hp->cmd_len < 6) || (hp->cmd_len > sizeof (cmnd))) {
667                 sg_remove_request(sfp, srp);
668                 return -EMSGSIZE;
669         }
670         if (!access_ok(VERIFY_READ, hp->cmdp, hp->cmd_len)) {
671                 sg_remove_request(sfp, srp);
672                 return -EFAULT; /* protects following copy_from_user()s + get_user()s */
673         }
674         if (__copy_from_user(cmnd, hp->cmdp, hp->cmd_len)) {
675                 sg_remove_request(sfp, srp);
676                 return -EFAULT;
677         }
678         if (read_only &&
679             (!sg_allow_access(cmnd[0], sfp->parentdp->device->type))) {
680                 sg_remove_request(sfp, srp);
681                 return -EPERM;
682         }
683         k = sg_common_write(sfp, srp, cmnd, timeout, blocking);
684         if (k < 0)
685                 return k;
686         if (o_srp)
687                 *o_srp = srp;
688         return count;
689 }
690
691 static int
692 sg_common_write(Sg_fd * sfp, Sg_request * srp,
693                 unsigned char *cmnd, int timeout, int blocking)
694 {
695         int k, data_dir;
696         Sg_device *sdp = sfp->parentdp;
697         sg_io_hdr_t *hp = &srp->header;
698
699         srp->data.cmd_opcode = cmnd[0]; /* hold opcode of command */
700         hp->status = 0;
701         hp->masked_status = 0;
702         hp->msg_status = 0;
703         hp->info = 0;
704         hp->host_status = 0;
705         hp->driver_status = 0;
706         hp->resid = 0;
707         SCSI_LOG_TIMEOUT(4, printk("sg_common_write:  scsi opcode=0x%02x, cmd_size=%d\n",
708                           (int) cmnd[0], (int) hp->cmd_len));
709
710         if ((k = sg_start_req(srp))) {
711                 SCSI_LOG_TIMEOUT(1, printk("sg_write: start_req err=%d\n", k));
712                 sg_finish_rem_req(srp);
713                 return k;       /* probably out of space --> ENOMEM */
714         }
715         if ((k = sg_write_xfer(srp))) {
716                 SCSI_LOG_TIMEOUT(1, printk("sg_write: write_xfer, bad address\n"));
717                 sg_finish_rem_req(srp);
718                 return k;
719         }
720         if (sdp->detached) {
721                 sg_finish_rem_req(srp);
722                 return -ENODEV;
723         }
724
725         switch (hp->dxfer_direction) {
726         case SG_DXFER_TO_FROM_DEV:
727         case SG_DXFER_FROM_DEV:
728                 data_dir = DMA_FROM_DEVICE;
729                 break;
730         case SG_DXFER_TO_DEV:
731                 data_dir = DMA_TO_DEVICE;
732                 break;
733         case SG_DXFER_UNKNOWN:
734                 data_dir = DMA_BIDIRECTIONAL;
735                 break;
736         default:
737                 data_dir = DMA_NONE;
738                 break;
739         }
740         hp->duration = jiffies_to_msecs(jiffies);
741 /* Now send everything of to mid-level. The next time we hear about this
742    packet is when sg_cmd_done() is called (i.e. a callback). */
743         if (scsi_execute_async(sdp->device, cmnd, hp->cmd_len, data_dir, srp->data.buffer,
744                                 hp->dxfer_len, srp->data.k_use_sg, timeout,
745                                 SG_DEFAULT_RETRIES, srp, sg_cmd_done,
746                                 GFP_ATOMIC)) {
747                 SCSI_LOG_TIMEOUT(1, printk("sg_write: scsi_execute_async failed\n"));
748                 /*
749                  * most likely out of mem, but could also be a bad map
750                  */
751                 return -ENOMEM;
752         } else
753                 return 0;
754 }
755
756 static int
757 sg_srp_done(Sg_request *srp, Sg_fd *sfp)
758 {
759         unsigned long iflags;
760         int done;
761
762         read_lock_irqsave(&sfp->rq_list_lock, iflags);
763         done = srp->done;
764         read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
765         return done;
766 }
767
768 static int
769 sg_ioctl(struct inode *inode, struct file *filp,
770          unsigned int cmd_in, unsigned long arg)
771 {
772         void __user *p = (void __user *)arg;
773         int __user *ip = p;
774         int result, val, read_only;
775         Sg_device *sdp;
776         Sg_fd *sfp;
777         Sg_request *srp;
778         unsigned long iflags;
779
780         if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
781                 return -ENXIO;
782         SCSI_LOG_TIMEOUT(3, printk("sg_ioctl: %s, cmd=0x%x\n",
783                                    sdp->disk->disk_name, (int) cmd_in));
784         read_only = (O_RDWR != (filp->f_flags & O_ACCMODE));
785
786         switch (cmd_in) {
787         case SG_IO:
788                 {
789                         int blocking = 1;       /* ignore O_NONBLOCK flag */
790
791                         if (sdp->detached)
792                                 return -ENODEV;
793                         if (!scsi_block_when_processing_errors(sdp->device))
794                                 return -ENXIO;
795                         if (!access_ok(VERIFY_WRITE, p, SZ_SG_IO_HDR))
796                                 return -EFAULT;
797                         result =
798                             sg_new_write(sfp, p, SZ_SG_IO_HDR,
799                                          blocking, read_only, &srp);
800                         if (result < 0)
801                                 return result;
802                         srp->sg_io_owned = 1;
803                         while (1) {
804                                 result = 0;     /* following macro to beat race condition */
805                                 __wait_event_interruptible(sfp->read_wait,
806                                         (sdp->detached || sfp->closed || sg_srp_done(srp, sfp)),
807                                                            result);
808                                 if (sdp->detached)
809                                         return -ENODEV;
810                                 if (sfp->closed)
811                                         return 0;       /* request packet dropped already */
812                                 if (0 == result)
813                                         break;
814                                 srp->orphan = 1;
815                                 return result;  /* -ERESTARTSYS because signal hit process */
816                         }
817                         write_lock_irqsave(&sfp->rq_list_lock, iflags);
818                         srp->done = 2;
819                         write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
820                         result = sg_new_read(sfp, p, SZ_SG_IO_HDR, srp);
821                         return (result < 0) ? result : 0;
822                 }
823         case SG_SET_TIMEOUT:
824                 result = get_user(val, ip);
825                 if (result)
826                         return result;
827                 if (val < 0)
828                         return -EIO;
829                 if (val >= MULDIV (INT_MAX, USER_HZ, HZ))
830                     val = MULDIV (INT_MAX, USER_HZ, HZ);
831                 sfp->timeout_user = val;
832                 sfp->timeout = MULDIV (val, HZ, USER_HZ);
833
834                 return 0;
835         case SG_GET_TIMEOUT:    /* N.B. User receives timeout as return value */
836                                 /* strange ..., for backward compatibility */
837                 return sfp->timeout_user;
838         case SG_SET_FORCE_LOW_DMA:
839                 result = get_user(val, ip);
840                 if (result)
841                         return result;
842                 if (val) {
843                         sfp->low_dma = 1;
844                         if ((0 == sfp->low_dma) && (0 == sg_res_in_use(sfp))) {
845                                 val = (int) sfp->reserve.bufflen;
846                                 sg_remove_scat(&sfp->reserve);
847                                 sg_build_reserve(sfp, val);
848                         }
849                 } else {
850                         if (sdp->detached)
851                                 return -ENODEV;
852                         sfp->low_dma = sdp->device->host->unchecked_isa_dma;
853                 }
854                 return 0;
855         case SG_GET_LOW_DMA:
856                 return put_user((int) sfp->low_dma, ip);
857         case SG_GET_SCSI_ID:
858                 if (!access_ok(VERIFY_WRITE, p, sizeof (sg_scsi_id_t)))
859                         return -EFAULT;
860                 else {
861                         sg_scsi_id_t __user *sg_idp = p;
862
863                         if (sdp->detached)
864                                 return -ENODEV;
865                         __put_user((int) sdp->device->host->host_no,
866                                    &sg_idp->host_no);
867                         __put_user((int) sdp->device->channel,
868                                    &sg_idp->channel);
869                         __put_user((int) sdp->device->id, &sg_idp->scsi_id);
870                         __put_user((int) sdp->device->lun, &sg_idp->lun);
871                         __put_user((int) sdp->device->type, &sg_idp->scsi_type);
872                         __put_user((short) sdp->device->host->cmd_per_lun,
873                                    &sg_idp->h_cmd_per_lun);
874                         __put_user((short) sdp->device->queue_depth,
875                                    &sg_idp->d_queue_depth);
876                         __put_user(0, &sg_idp->unused[0]);
877                         __put_user(0, &sg_idp->unused[1]);
878                         return 0;
879                 }
880         case SG_SET_FORCE_PACK_ID:
881                 result = get_user(val, ip);
882                 if (result)
883                         return result;
884                 sfp->force_packid = val ? 1 : 0;
885                 return 0;
886         case SG_GET_PACK_ID:
887                 if (!access_ok(VERIFY_WRITE, ip, sizeof (int)))
888                         return -EFAULT;
889                 read_lock_irqsave(&sfp->rq_list_lock, iflags);
890                 for (srp = sfp->headrp; srp; srp = srp->nextrp) {
891                         if ((1 == srp->done) && (!srp->sg_io_owned)) {
892                                 read_unlock_irqrestore(&sfp->rq_list_lock,
893                                                        iflags);
894                                 __put_user(srp->header.pack_id, ip);
895                                 return 0;
896                         }
897                 }
898                 read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
899                 __put_user(-1, ip);
900                 return 0;
901         case SG_GET_NUM_WAITING:
902                 read_lock_irqsave(&sfp->rq_list_lock, iflags);
903                 for (val = 0, srp = sfp->headrp; srp; srp = srp->nextrp) {
904                         if ((1 == srp->done) && (!srp->sg_io_owned))
905                                 ++val;
906                 }
907                 read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
908                 return put_user(val, ip);
909         case SG_GET_SG_TABLESIZE:
910                 return put_user(sdp->sg_tablesize, ip);
911         case SG_SET_RESERVED_SIZE:
912                 result = get_user(val, ip);
913                 if (result)
914                         return result;
915                 if (val < 0)
916                         return -EINVAL;
917                 if (val != sfp->reserve.bufflen) {
918                         if (sg_res_in_use(sfp) || sfp->mmap_called)
919                                 return -EBUSY;
920                         sg_remove_scat(&sfp->reserve);
921                         sg_build_reserve(sfp, val);
922                 }
923                 return 0;
924         case SG_GET_RESERVED_SIZE:
925                 val = (int) sfp->reserve.bufflen;
926                 return put_user(val, ip);
927         case SG_SET_COMMAND_Q:
928                 result = get_user(val, ip);
929                 if (result)
930                         return result;
931                 sfp->cmd_q = val ? 1 : 0;
932                 return 0;
933         case SG_GET_COMMAND_Q:
934                 return put_user((int) sfp->cmd_q, ip);
935         case SG_SET_KEEP_ORPHAN:
936                 result = get_user(val, ip);
937                 if (result)
938                         return result;
939                 sfp->keep_orphan = val;
940                 return 0;
941         case SG_GET_KEEP_ORPHAN:
942                 return put_user((int) sfp->keep_orphan, ip);
943         case SG_NEXT_CMD_LEN:
944                 result = get_user(val, ip);
945                 if (result)
946                         return result;
947                 sfp->next_cmd_len = (val > 0) ? val : 0;
948                 return 0;
949         case SG_GET_VERSION_NUM:
950                 return put_user(sg_version_num, ip);
951         case SG_GET_ACCESS_COUNT:
952                 /* faked - we don't have a real access count anymore */
953                 val = (sdp->device ? 1 : 0);
954                 return put_user(val, ip);
955         case SG_GET_REQUEST_TABLE:
956                 if (!access_ok(VERIFY_WRITE, p, SZ_SG_REQ_INFO * SG_MAX_QUEUE))
957                         return -EFAULT;
958                 else {
959                         sg_req_info_t *rinfo;
960                         unsigned int ms;
961
962                         rinfo = kmalloc(SZ_SG_REQ_INFO * SG_MAX_QUEUE,
963                                                                 GFP_KERNEL);
964                         if (!rinfo)
965                                 return -ENOMEM;
966                         read_lock_irqsave(&sfp->rq_list_lock, iflags);
967                         for (srp = sfp->headrp, val = 0; val < SG_MAX_QUEUE;
968                              ++val, srp = srp ? srp->nextrp : srp) {
969                                 memset(&rinfo[val], 0, SZ_SG_REQ_INFO);
970                                 if (srp) {
971                                         rinfo[val].req_state = srp->done + 1;
972                                         rinfo[val].problem =
973                                             srp->header.masked_status & 
974                                             srp->header.host_status & 
975                                             srp->header.driver_status;
976                                         if (srp->done)
977                                                 rinfo[val].duration =
978                                                         srp->header.duration;
979                                         else {
980                                                 ms = jiffies_to_msecs(jiffies);
981                                                 rinfo[val].duration =
982                                                     (ms > srp->header.duration) ?
983                                                     (ms - srp->header.duration) : 0;
984                                         }
985                                         rinfo[val].orphan = srp->orphan;
986                                         rinfo[val].sg_io_owned =
987                                                         srp->sg_io_owned;
988                                         rinfo[val].pack_id =
989                                                         srp->header.pack_id;
990                                         rinfo[val].usr_ptr =
991                                                         srp->header.usr_ptr;
992                                 }
993                         }
994                         read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
995                         result = __copy_to_user(p, rinfo, 
996                                                 SZ_SG_REQ_INFO * SG_MAX_QUEUE);
997                         result = result ? -EFAULT : 0;
998                         kfree(rinfo);
999                         return result;
1000                 }
1001         case SG_EMULATED_HOST:
1002                 if (sdp->detached)
1003                         return -ENODEV;
1004                 return put_user(sdp->device->host->hostt->emulated, ip);
1005         case SG_SCSI_RESET:
1006                 if (sdp->detached)
1007                         return -ENODEV;
1008                 if (filp->f_flags & O_NONBLOCK) {
1009                         if (scsi_host_in_recovery(sdp->device->host))
1010                                 return -EBUSY;
1011                 } else if (!scsi_block_when_processing_errors(sdp->device))
1012                         return -EBUSY;
1013                 result = get_user(val, ip);
1014                 if (result)
1015                         return result;
1016                 if (SG_SCSI_RESET_NOTHING == val)
1017                         return 0;
1018                 switch (val) {
1019                 case SG_SCSI_RESET_DEVICE:
1020                         val = SCSI_TRY_RESET_DEVICE;
1021                         break;
1022                 case SG_SCSI_RESET_BUS:
1023                         val = SCSI_TRY_RESET_BUS;
1024                         break;
1025                 case SG_SCSI_RESET_HOST:
1026                         val = SCSI_TRY_RESET_HOST;
1027                         break;
1028                 default:
1029                         return -EINVAL;
1030                 }
1031                 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
1032                         return -EACCES;
1033                 return (scsi_reset_provider(sdp->device, val) ==
1034                         SUCCESS) ? 0 : -EIO;
1035         case SCSI_IOCTL_SEND_COMMAND:
1036                 if (sdp->detached)
1037                         return -ENODEV;
1038                 if (read_only) {
1039                         unsigned char opcode = WRITE_6;
1040                         Scsi_Ioctl_Command __user *siocp = p;
1041
1042                         if (copy_from_user(&opcode, siocp->data, 1))
1043                                 return -EFAULT;
1044                         if (!sg_allow_access(opcode, sdp->device->type))
1045                                 return -EPERM;
1046                 }
1047                 return scsi_ioctl_send_command(sdp->device, p);
1048         case SG_SET_DEBUG:
1049                 result = get_user(val, ip);
1050                 if (result)
1051                         return result;
1052                 sdp->sgdebug = (char) val;
1053                 return 0;
1054         case SCSI_IOCTL_GET_IDLUN:
1055         case SCSI_IOCTL_GET_BUS_NUMBER:
1056         case SCSI_IOCTL_PROBE_HOST:
1057         case SG_GET_TRANSFORM:
1058                 if (sdp->detached)
1059                         return -ENODEV;
1060                 return scsi_ioctl(sdp->device, cmd_in, p);
1061         default:
1062                 if (read_only)
1063                         return -EPERM;  /* don't know so take safe approach */
1064                 return scsi_ioctl(sdp->device, cmd_in, p);
1065         }
1066 }
1067
1068 #ifdef CONFIG_COMPAT
1069 static long sg_compat_ioctl(struct file *filp, unsigned int cmd_in, unsigned long arg)
1070 {
1071         Sg_device *sdp;
1072         Sg_fd *sfp;
1073         struct scsi_device *sdev;
1074
1075         if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
1076                 return -ENXIO;
1077
1078         sdev = sdp->device;
1079         if (sdev->host->hostt->compat_ioctl) { 
1080                 int ret;
1081
1082                 ret = sdev->host->hostt->compat_ioctl(sdev, cmd_in, (void __user *)arg);
1083
1084                 return ret;
1085         }
1086         
1087         return -ENOIOCTLCMD;
1088 }
1089 #endif
1090
1091 static unsigned int
1092 sg_poll(struct file *filp, poll_table * wait)
1093 {
1094         unsigned int res = 0;
1095         Sg_device *sdp;
1096         Sg_fd *sfp;
1097         Sg_request *srp;
1098         int count = 0;
1099         unsigned long iflags;
1100
1101         if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp))
1102             || sfp->closed)
1103                 return POLLERR;
1104         poll_wait(filp, &sfp->read_wait, wait);
1105         read_lock_irqsave(&sfp->rq_list_lock, iflags);
1106         for (srp = sfp->headrp; srp; srp = srp->nextrp) {
1107                 /* if any read waiting, flag it */
1108                 if ((0 == res) && (1 == srp->done) && (!srp->sg_io_owned))
1109                         res = POLLIN | POLLRDNORM;
1110                 ++count;
1111         }
1112         read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
1113
1114         if (sdp->detached)
1115                 res |= POLLHUP;
1116         else if (!sfp->cmd_q) {
1117                 if (0 == count)
1118                         res |= POLLOUT | POLLWRNORM;
1119         } else if (count < SG_MAX_QUEUE)
1120                 res |= POLLOUT | POLLWRNORM;
1121         SCSI_LOG_TIMEOUT(3, printk("sg_poll: %s, res=0x%x\n",
1122                                    sdp->disk->disk_name, (int) res));
1123         return res;
1124 }
1125
1126 static int
1127 sg_fasync(int fd, struct file *filp, int mode)
1128 {
1129         int retval;
1130         Sg_device *sdp;
1131         Sg_fd *sfp;
1132
1133         if ((!(sfp = (Sg_fd *) filp->private_data)) || (!(sdp = sfp->parentdp)))
1134                 return -ENXIO;
1135         SCSI_LOG_TIMEOUT(3, printk("sg_fasync: %s, mode=%d\n",
1136                                    sdp->disk->disk_name, mode));
1137
1138         retval = fasync_helper(fd, filp, mode, &sfp->async_qp);
1139         return (retval < 0) ? retval : 0;
1140 }
1141
1142 /* When startFinish==1 increments page counts for pages other than the 
1143    first of scatter gather elements obtained from alloc_pages().
1144    When startFinish==0 decrements ... */
1145 static void
1146 sg_rb_correct4mmap(Sg_scatter_hold * rsv_schp, int startFinish)
1147 {
1148         struct scatterlist *sg = rsv_schp->buffer;
1149         struct page *page;
1150         int k, m;
1151
1152         SCSI_LOG_TIMEOUT(3, printk("sg_rb_correct4mmap: startFinish=%d, scatg=%d\n", 
1153                                    startFinish, rsv_schp->k_use_sg));
1154         /* N.B. correction _not_ applied to base page of each allocation */
1155         for (k = 0; k < rsv_schp->k_use_sg; ++k, ++sg) {
1156                 for (m = PAGE_SIZE; m < sg->length; m += PAGE_SIZE) {
1157                         page = sg->page;
1158                         if (startFinish)
1159                                 get_page(page);
1160                         else {
1161                                 if (page_count(page) > 0)
1162                                         __put_page(page);
1163                         }
1164                 }
1165         }
1166 }
1167
1168 static struct page *
1169 sg_vma_nopage(struct vm_area_struct *vma, unsigned long addr, int *type)
1170 {
1171         Sg_fd *sfp;
1172         struct page *page = NOPAGE_SIGBUS;
1173         unsigned long offset, len, sa;
1174         Sg_scatter_hold *rsv_schp;
1175         struct scatterlist *sg;
1176         int k;
1177
1178         if ((NULL == vma) || (!(sfp = (Sg_fd *) vma->vm_private_data)))
1179                 return page;
1180         rsv_schp = &sfp->reserve;
1181         offset = addr - vma->vm_start;
1182         if (offset >= rsv_schp->bufflen)
1183                 return page;
1184         SCSI_LOG_TIMEOUT(3, printk("sg_vma_nopage: offset=%lu, scatg=%d\n",
1185                                    offset, rsv_schp->k_use_sg));
1186         sg = rsv_schp->buffer;
1187         sa = vma->vm_start;
1188         for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
1189              ++k, ++sg) {
1190                 len = vma->vm_end - sa;
1191                 len = (len < sg->length) ? len : sg->length;
1192                 if (offset < len) {
1193                         page = sg->page;
1194                         get_page(page); /* increment page count */
1195                         break;
1196                 }
1197                 sa += len;
1198                 offset -= len;
1199         }
1200
1201         if (type)
1202                 *type = VM_FAULT_MINOR;
1203         return page;
1204 }
1205
1206 static struct vm_operations_struct sg_mmap_vm_ops = {
1207         .nopage = sg_vma_nopage,
1208 };
1209
1210 static int
1211 sg_mmap(struct file *filp, struct vm_area_struct *vma)
1212 {
1213         Sg_fd *sfp;
1214         unsigned long req_sz, len, sa;
1215         Sg_scatter_hold *rsv_schp;
1216         int k;
1217         struct scatterlist *sg;
1218
1219         if ((!filp) || (!vma) || (!(sfp = (Sg_fd *) filp->private_data)))
1220                 return -ENXIO;
1221         req_sz = vma->vm_end - vma->vm_start;
1222         SCSI_LOG_TIMEOUT(3, printk("sg_mmap starting, vm_start=%p, len=%d\n",
1223                                    (void *) vma->vm_start, (int) req_sz));
1224         if (vma->vm_pgoff)
1225                 return -EINVAL; /* want no offset */
1226         rsv_schp = &sfp->reserve;
1227         if (req_sz > rsv_schp->bufflen)
1228                 return -ENOMEM; /* cannot map more than reserved buffer */
1229
1230         sa = vma->vm_start;
1231         sg = rsv_schp->buffer;
1232         for (k = 0; (k < rsv_schp->k_use_sg) && (sa < vma->vm_end);
1233              ++k, ++sg) {
1234                 len = vma->vm_end - sa;
1235                 len = (len < sg->length) ? len : sg->length;
1236                 sa += len;
1237         }
1238
1239         if (0 == sfp->mmap_called) {
1240                 sg_rb_correct4mmap(rsv_schp, 1);        /* do only once per fd lifetime */
1241                 sfp->mmap_called = 1;
1242         }
1243         vma->vm_flags |= VM_RESERVED;
1244         vma->vm_private_data = sfp;
1245         vma->vm_ops = &sg_mmap_vm_ops;
1246         return 0;
1247 }
1248
1249 /* This function is a "bottom half" handler that is called by the
1250  * mid level when a command is completed (or has failed). */
1251 static void
1252 sg_cmd_done(void *data, char *sense, int result, int resid)
1253 {
1254         Sg_request *srp = data;
1255         Sg_device *sdp = NULL;
1256         Sg_fd *sfp;
1257         unsigned long iflags;
1258         unsigned int ms;
1259
1260         if (NULL == srp) {
1261                 printk(KERN_ERR "sg_cmd_done: NULL request\n");
1262                 return;
1263         }
1264         sfp = srp->parentfp;
1265         if (sfp)
1266                 sdp = sfp->parentdp;
1267         if ((NULL == sdp) || sdp->detached) {
1268                 printk(KERN_INFO "sg_cmd_done: device detached\n");
1269                 return;
1270         }
1271
1272
1273         SCSI_LOG_TIMEOUT(4, printk("sg_cmd_done: %s, pack_id=%d, res=0x%x\n",
1274                 sdp->disk->disk_name, srp->header.pack_id, result));
1275         srp->header.resid = resid;
1276         ms = jiffies_to_msecs(jiffies);
1277         srp->header.duration = (ms > srp->header.duration) ?
1278                                 (ms - srp->header.duration) : 0;
1279         if (0 != result) {
1280                 struct scsi_sense_hdr sshdr;
1281
1282                 memcpy(srp->sense_b, sense, sizeof (srp->sense_b));
1283                 srp->header.status = 0xff & result;
1284                 srp->header.masked_status = status_byte(result);
1285                 srp->header.msg_status = msg_byte(result);
1286                 srp->header.host_status = host_byte(result);
1287                 srp->header.driver_status = driver_byte(result);
1288                 if ((sdp->sgdebug > 0) &&
1289                     ((CHECK_CONDITION == srp->header.masked_status) ||
1290                      (COMMAND_TERMINATED == srp->header.masked_status)))
1291                         __scsi_print_sense("sg_cmd_done", sense,
1292                                            SCSI_SENSE_BUFFERSIZE);
1293
1294                 /* Following if statement is a patch supplied by Eric Youngdale */
1295                 if (driver_byte(result) != 0
1296                     && scsi_normalize_sense(sense, SCSI_SENSE_BUFFERSIZE, &sshdr)
1297                     && !scsi_sense_is_deferred(&sshdr)
1298                     && sshdr.sense_key == UNIT_ATTENTION
1299                     && sdp->device->removable) {
1300                         /* Detected possible disc change. Set the bit - this */
1301                         /* may be used if there are filesystems using this device */
1302                         sdp->device->changed = 1;
1303                 }
1304         }
1305         /* Rely on write phase to clean out srp status values, so no "else" */
1306
1307         if (sfp->closed) {      /* whoops this fd already released, cleanup */
1308                 SCSI_LOG_TIMEOUT(1, printk("sg_cmd_done: already closed, freeing ...\n"));
1309                 sg_finish_rem_req(srp);
1310                 srp = NULL;
1311                 if (NULL == sfp->headrp) {
1312                         SCSI_LOG_TIMEOUT(1, printk("sg...bh: already closed, final cleanup\n"));
1313                         if (0 == sg_remove_sfp(sdp, sfp)) {     /* device still present */
1314                                 scsi_device_put(sdp->device);
1315                         }
1316                         sfp = NULL;
1317                 }
1318         } else if (srp && srp->orphan) {
1319                 if (sfp->keep_orphan)
1320                         srp->sg_io_owned = 0;
1321                 else {
1322                         sg_finish_rem_req(srp);
1323                         srp = NULL;
1324                 }
1325         }
1326         if (sfp && srp) {
1327                 /* Now wake up any sg_read() that is waiting for this packet. */
1328                 kill_fasync(&sfp->async_qp, SIGPOLL, POLL_IN);
1329                 write_lock_irqsave(&sfp->rq_list_lock, iflags);
1330                 srp->done = 1;
1331                 wake_up_interruptible(&sfp->read_wait);
1332                 write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
1333         }
1334 }
1335
1336 static struct file_operations sg_fops = {
1337         .owner = THIS_MODULE,
1338         .read = sg_read,
1339         .write = sg_write,
1340         .poll = sg_poll,
1341         .ioctl = sg_ioctl,
1342 #ifdef CONFIG_COMPAT
1343         .compat_ioctl = sg_compat_ioctl,
1344 #endif
1345         .open = sg_open,
1346         .mmap = sg_mmap,
1347         .release = sg_release,
1348         .fasync = sg_fasync,
1349 };
1350
1351 static struct class *sg_sysfs_class;
1352
1353 static int sg_sysfs_valid = 0;
1354
1355 static int sg_alloc(struct gendisk *disk, struct scsi_device *scsidp)
1356 {
1357         struct request_queue *q = scsidp->request_queue;
1358         Sg_device *sdp;
1359         unsigned long iflags;
1360         void *old_sg_dev_arr = NULL;
1361         int k, error;
1362
1363         sdp = kzalloc(sizeof(Sg_device), GFP_KERNEL);
1364         if (!sdp) {
1365                 printk(KERN_WARNING "kmalloc Sg_device failure\n");
1366                 return -ENOMEM;
1367         }
1368
1369         write_lock_irqsave(&sg_dev_arr_lock, iflags);
1370         if (unlikely(sg_nr_dev >= sg_dev_max)) {        /* try to resize */
1371                 Sg_device **tmp_da;
1372                 int tmp_dev_max = sg_nr_dev + SG_DEV_ARR_LUMP;
1373                 write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
1374
1375                 tmp_da = kzalloc(tmp_dev_max * sizeof(Sg_device *), GFP_KERNEL);
1376                 if (unlikely(!tmp_da))
1377                         goto expand_failed;
1378
1379                 write_lock_irqsave(&sg_dev_arr_lock, iflags);
1380                 memcpy(tmp_da, sg_dev_arr, sg_dev_max * sizeof(Sg_device *));
1381                 old_sg_dev_arr = sg_dev_arr;
1382                 sg_dev_arr = tmp_da;
1383                 sg_dev_max = tmp_dev_max;
1384         }
1385
1386         for (k = 0; k < sg_dev_max; k++)
1387                 if (!sg_dev_arr[k])
1388                         break;
1389         if (unlikely(k >= SG_MAX_DEVS))
1390                 goto overflow;
1391
1392         SCSI_LOG_TIMEOUT(3, printk("sg_alloc: dev=%d \n", k));
1393         sprintf(disk->disk_name, "sg%d", k);
1394         disk->first_minor = k;
1395         sdp->disk = disk;
1396         sdp->device = scsidp;
1397         init_waitqueue_head(&sdp->o_excl_wait);
1398         sdp->sg_tablesize = min(q->max_hw_segments, q->max_phys_segments);
1399
1400         sg_nr_dev++;
1401         sg_dev_arr[k] = sdp;
1402         write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
1403         error = k;
1404
1405  out:
1406         if (error < 0)
1407                 kfree(sdp);
1408         kfree(old_sg_dev_arr);
1409         return error;
1410
1411  expand_failed:
1412         printk(KERN_WARNING "sg_alloc: device array cannot be resized\n");
1413         error = -ENOMEM;
1414         goto out;
1415
1416  overflow:
1417         write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
1418         sdev_printk(KERN_WARNING, scsidp,
1419                     "Unable to attach sg device type=%d, minor "
1420                     "number exceeds %d\n", scsidp->type, SG_MAX_DEVS - 1);
1421         error = -ENODEV;
1422         goto out;
1423 }
1424
1425 static int
1426 sg_add(struct class_device *cl_dev, struct class_interface *cl_intf)
1427 {
1428         struct scsi_device *scsidp = to_scsi_device(cl_dev->dev);
1429         struct gendisk *disk;
1430         Sg_device *sdp = NULL;
1431         struct cdev * cdev = NULL;
1432         int error, k;
1433
1434         disk = alloc_disk(1);
1435         if (!disk) {
1436                 printk(KERN_WARNING "alloc_disk failed\n");
1437                 return -ENOMEM;
1438         }
1439         disk->major = SCSI_GENERIC_MAJOR;
1440
1441         error = -ENOMEM;
1442         cdev = cdev_alloc();
1443         if (!cdev) {
1444                 printk(KERN_WARNING "cdev_alloc failed\n");
1445                 goto out;
1446         }
1447         cdev->owner = THIS_MODULE;
1448         cdev->ops = &sg_fops;
1449
1450         error = sg_alloc(disk, scsidp);
1451         if (error < 0) {
1452                 printk(KERN_WARNING "sg_alloc failed\n");
1453                 goto out;
1454         }
1455         k = error;
1456         sdp = sg_dev_arr[k];
1457
1458         error = cdev_add(cdev, MKDEV(SCSI_GENERIC_MAJOR, k), 1);
1459         if (error)
1460                 goto out;
1461
1462         sdp->cdev = cdev;
1463         if (sg_sysfs_valid) {
1464                 struct class_device * sg_class_member;
1465
1466                 sg_class_member = class_device_create(sg_sysfs_class, NULL,
1467                                 MKDEV(SCSI_GENERIC_MAJOR, k), 
1468                                 cl_dev->dev, "%s", 
1469                                 disk->disk_name);
1470                 if (IS_ERR(sg_class_member))
1471                         printk(KERN_WARNING "sg_add: "
1472                                 "class_device_create failed\n");
1473                 class_set_devdata(sg_class_member, sdp);
1474                 error = sysfs_create_link(&scsidp->sdev_gendev.kobj, 
1475                                           &sg_class_member->kobj, "generic");
1476                 if (error)
1477                         printk(KERN_ERR "sg_add: unable to make symlink "
1478                                         "'generic' back to sg%d\n", k);
1479         } else
1480                 printk(KERN_WARNING "sg_add: sg_sys INvalid\n");
1481
1482         sdev_printk(KERN_NOTICE, scsidp,
1483                     "Attached scsi generic sg%d type %d\n", k,scsidp->type);
1484
1485         return 0;
1486
1487 out:
1488         put_disk(disk);
1489         if (cdev)
1490                 cdev_del(cdev);
1491         return error;
1492 }
1493
1494 static void
1495 sg_remove(struct class_device *cl_dev, struct class_interface *cl_intf)
1496 {
1497         struct scsi_device *scsidp = to_scsi_device(cl_dev->dev);
1498         Sg_device *sdp = NULL;
1499         unsigned long iflags;
1500         Sg_fd *sfp;
1501         Sg_fd *tsfp;
1502         Sg_request *srp;
1503         Sg_request *tsrp;
1504         int k, delay;
1505
1506         if (NULL == sg_dev_arr)
1507                 return;
1508         delay = 0;
1509         write_lock_irqsave(&sg_dev_arr_lock, iflags);
1510         for (k = 0; k < sg_dev_max; k++) {
1511                 sdp = sg_dev_arr[k];
1512                 if ((NULL == sdp) || (sdp->device != scsidp))
1513                         continue;       /* dirty but lowers nesting */
1514                 if (sdp->headfp) {
1515                         sdp->detached = 1;
1516                         for (sfp = sdp->headfp; sfp; sfp = tsfp) {
1517                                 tsfp = sfp->nextfp;
1518                                 for (srp = sfp->headrp; srp; srp = tsrp) {
1519                                         tsrp = srp->nextrp;
1520                                         if (sfp->closed || (0 == sg_srp_done(srp, sfp)))
1521                                                 sg_finish_rem_req(srp);
1522                                 }
1523                                 if (sfp->closed) {
1524                                         scsi_device_put(sdp->device);
1525                                         __sg_remove_sfp(sdp, sfp);
1526                                 } else {
1527                                         delay = 1;
1528                                         wake_up_interruptible(&sfp->read_wait);
1529                                         kill_fasync(&sfp->async_qp, SIGPOLL,
1530                                                     POLL_HUP);
1531                                 }
1532                         }
1533                         SCSI_LOG_TIMEOUT(3, printk("sg_detach: dev=%d, dirty\n", k));
1534                         if (NULL == sdp->headfp) {
1535                                 sg_dev_arr[k] = NULL;
1536                         }
1537                 } else {        /* nothing active, simple case */
1538                         SCSI_LOG_TIMEOUT(3, printk("sg_detach: dev=%d\n", k));
1539                         sg_dev_arr[k] = NULL;
1540                 }
1541                 sg_nr_dev--;
1542                 break;
1543         }
1544         write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
1545
1546         if (sdp) {
1547                 sysfs_remove_link(&scsidp->sdev_gendev.kobj, "generic");
1548                 class_device_destroy(sg_sysfs_class, MKDEV(SCSI_GENERIC_MAJOR, k));
1549                 cdev_del(sdp->cdev);
1550                 sdp->cdev = NULL;
1551                 put_disk(sdp->disk);
1552                 sdp->disk = NULL;
1553                 if (NULL == sdp->headfp)
1554                         kfree((char *) sdp);
1555         }
1556
1557         if (delay)
1558                 msleep(10);     /* dirty detach so delay device destruction */
1559 }
1560
1561 /* Set 'perm' (4th argument) to 0 to disable module_param's definition
1562  * of sysfs parameters (which module_param doesn't yet support).
1563  * Sysfs parameters defined explicitly below.
1564  */
1565 module_param_named(def_reserved_size, def_reserved_size, int, S_IRUGO);
1566 module_param_named(allow_dio, sg_allow_dio, int, S_IRUGO | S_IWUSR);
1567
1568 MODULE_AUTHOR("Douglas Gilbert");
1569 MODULE_DESCRIPTION("SCSI generic (sg) driver");
1570 MODULE_LICENSE("GPL");
1571 MODULE_VERSION(SG_VERSION_STR);
1572
1573 MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
1574 MODULE_PARM_DESC(allow_dio, "allow direct I/O (default: 0 (disallow))");
1575
1576 static int __init
1577 init_sg(void)
1578 {
1579         int rc;
1580
1581         if (def_reserved_size >= 0)
1582                 sg_big_buff = def_reserved_size;
1583
1584         rc = register_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), 
1585                                     SG_MAX_DEVS, "sg");
1586         if (rc)
1587                 return rc;
1588         sg_sysfs_class = class_create(THIS_MODULE, "scsi_generic");
1589         if ( IS_ERR(sg_sysfs_class) ) {
1590                 rc = PTR_ERR(sg_sysfs_class);
1591                 goto err_out;
1592         }
1593         sg_sysfs_valid = 1;
1594         rc = scsi_register_interface(&sg_interface);
1595         if (0 == rc) {
1596 #ifdef CONFIG_SCSI_PROC_FS
1597                 sg_proc_init();
1598 #endif                          /* CONFIG_SCSI_PROC_FS */
1599                 return 0;
1600         }
1601         class_destroy(sg_sysfs_class);
1602 err_out:
1603         unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0), SG_MAX_DEVS);
1604         return rc;
1605 }
1606
1607 static void __exit
1608 exit_sg(void)
1609 {
1610 #ifdef CONFIG_SCSI_PROC_FS
1611         sg_proc_cleanup();
1612 #endif                          /* CONFIG_SCSI_PROC_FS */
1613         scsi_unregister_interface(&sg_interface);
1614         class_destroy(sg_sysfs_class);
1615         sg_sysfs_valid = 0;
1616         unregister_chrdev_region(MKDEV(SCSI_GENERIC_MAJOR, 0),
1617                                  SG_MAX_DEVS);
1618         kfree((char *)sg_dev_arr);
1619         sg_dev_arr = NULL;
1620         sg_dev_max = 0;
1621 }
1622
1623 static int
1624 sg_start_req(Sg_request * srp)
1625 {
1626         int res;
1627         Sg_fd *sfp = srp->parentfp;
1628         sg_io_hdr_t *hp = &srp->header;
1629         int dxfer_len = (int) hp->dxfer_len;
1630         int dxfer_dir = hp->dxfer_direction;
1631         Sg_scatter_hold *req_schp = &srp->data;
1632         Sg_scatter_hold *rsv_schp = &sfp->reserve;
1633
1634         SCSI_LOG_TIMEOUT(4, printk("sg_start_req: dxfer_len=%d\n", dxfer_len));
1635         if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
1636                 return 0;
1637         if (sg_allow_dio && (hp->flags & SG_FLAG_DIRECT_IO) &&
1638             (dxfer_dir != SG_DXFER_UNKNOWN) && (0 == hp->iovec_count) &&
1639             (!sfp->parentdp->device->host->unchecked_isa_dma)) {
1640                 res = sg_build_direct(srp, sfp, dxfer_len);
1641                 if (res <= 0)   /* -ve -> error, 0 -> done, 1 -> try indirect */
1642                         return res;
1643         }
1644         if ((!sg_res_in_use(sfp)) && (dxfer_len <= rsv_schp->bufflen))
1645                 sg_link_reserve(sfp, srp, dxfer_len);
1646         else {
1647                 res = sg_build_indirect(req_schp, sfp, dxfer_len);
1648                 if (res) {
1649                         sg_remove_scat(req_schp);
1650                         return res;
1651                 }
1652         }
1653         return 0;
1654 }
1655
1656 static void
1657 sg_finish_rem_req(Sg_request * srp)
1658 {
1659         Sg_fd *sfp = srp->parentfp;
1660         Sg_scatter_hold *req_schp = &srp->data;
1661
1662         SCSI_LOG_TIMEOUT(4, printk("sg_finish_rem_req: res_used=%d\n", (int) srp->res_used));
1663         if (srp->res_used)
1664                 sg_unlink_reserve(sfp, srp);
1665         else
1666                 sg_remove_scat(req_schp);
1667         sg_remove_request(sfp, srp);
1668 }
1669
1670 static int
1671 sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp, int tablesize)
1672 {
1673         int sg_bufflen = tablesize * sizeof(struct scatterlist);
1674         gfp_t gfp_flags = GFP_ATOMIC | __GFP_NOWARN;
1675
1676         /*
1677          * TODO: test without low_dma, we should not need it since
1678          * the block layer will bounce the buffer for us
1679          *
1680          * XXX(hch): we shouldn't need GFP_DMA for the actual S/G list.
1681          */
1682         if (sfp->low_dma)
1683                  gfp_flags |= GFP_DMA;
1684         schp->buffer = kzalloc(sg_bufflen, gfp_flags);
1685         if (!schp->buffer)
1686                 return -ENOMEM;
1687         schp->sglist_len = sg_bufflen;
1688         return tablesize;       /* number of scat_gath elements allocated */
1689 }
1690
1691 #ifdef SG_ALLOW_DIO_CODE
1692 /* vvvvvvvv  following code borrowed from st driver's direct IO vvvvvvvvv */
1693         /* TODO: hopefully we can use the generic block layer code */
1694
1695 /* Pin down user pages and put them into a scatter gather list. Returns <= 0 if
1696    - mapping of all pages not successful
1697    (i.e., either completely successful or fails)
1698 */
1699 static int 
1700 st_map_user_pages(struct scatterlist *sgl, const unsigned int max_pages, 
1701                   unsigned long uaddr, size_t count, int rw)
1702 {
1703         unsigned long end = (uaddr + count + PAGE_SIZE - 1) >> PAGE_SHIFT;
1704         unsigned long start = uaddr >> PAGE_SHIFT;
1705         const int nr_pages = end - start;
1706         int res, i, j;
1707         struct page **pages;
1708
1709         /* User attempted Overflow! */
1710         if ((uaddr + count) < uaddr)
1711                 return -EINVAL;
1712
1713         /* Too big */
1714         if (nr_pages > max_pages)
1715                 return -ENOMEM;
1716
1717         /* Hmm? */
1718         if (count == 0)
1719                 return 0;
1720
1721         if ((pages = kmalloc(max_pages * sizeof(*pages), GFP_ATOMIC)) == NULL)
1722                 return -ENOMEM;
1723
1724         /* Try to fault in all of the necessary pages */
1725         down_read(&current->mm->mmap_sem);
1726         /* rw==READ means read from drive, write into memory area */
1727         res = get_user_pages(
1728                 current,
1729                 current->mm,
1730                 uaddr,
1731                 nr_pages,
1732                 rw == READ,
1733                 0, /* don't force */
1734                 pages,
1735                 NULL);
1736         up_read(&current->mm->mmap_sem);
1737
1738         /* Errors and no page mapped should return here */
1739         if (res < nr_pages)
1740                 goto out_unmap;
1741
1742         for (i=0; i < nr_pages; i++) {
1743                 /* FIXME: flush superflous for rw==READ,
1744                  * probably wrong function for rw==WRITE
1745                  */
1746                 flush_dcache_page(pages[i]);
1747                 /* ?? Is locking needed? I don't think so */
1748                 /* if (TestSetPageLocked(pages[i]))
1749                    goto out_unlock; */
1750         }
1751
1752         sgl[0].page = pages[0];
1753         sgl[0].offset = uaddr & ~PAGE_MASK;
1754         if (nr_pages > 1) {
1755                 sgl[0].length = PAGE_SIZE - sgl[0].offset;
1756                 count -= sgl[0].length;
1757                 for (i=1; i < nr_pages ; i++) {
1758                         sgl[i].page = pages[i]; 
1759                         sgl[i].length = count < PAGE_SIZE ? count : PAGE_SIZE;
1760                         count -= PAGE_SIZE;
1761                 }
1762         }
1763         else {
1764                 sgl[0].length = count;
1765         }
1766
1767         kfree(pages);
1768         return nr_pages;
1769
1770  out_unmap:
1771         if (res > 0) {
1772                 for (j=0; j < res; j++)
1773                         page_cache_release(pages[j]);
1774                 res = 0;
1775         }
1776         kfree(pages);
1777         return res;
1778 }
1779
1780
1781 /* And unmap them... */
1782 static int 
1783 st_unmap_user_pages(struct scatterlist *sgl, const unsigned int nr_pages,
1784                     int dirtied)
1785 {
1786         int i;
1787
1788         for (i=0; i < nr_pages; i++) {
1789                 struct page *page = sgl[i].page;
1790
1791                 if (dirtied)
1792                         SetPageDirty(page);
1793                 /* unlock_page(page); */
1794                 /* FIXME: cache flush missing for rw==READ
1795                  * FIXME: call the correct reference counting function
1796                  */
1797                 page_cache_release(page);
1798         }
1799
1800         return 0;
1801 }
1802
1803 /* ^^^^^^^^  above code borrowed from st driver's direct IO ^^^^^^^^^ */
1804 #endif
1805
1806
1807 /* Returns: -ve -> error, 0 -> done, 1 -> try indirect */
1808 static int
1809 sg_build_direct(Sg_request * srp, Sg_fd * sfp, int dxfer_len)
1810 {
1811 #ifdef SG_ALLOW_DIO_CODE
1812         sg_io_hdr_t *hp = &srp->header;
1813         Sg_scatter_hold *schp = &srp->data;
1814         int sg_tablesize = sfp->parentdp->sg_tablesize;
1815         int mx_sc_elems, res;
1816         struct scsi_device *sdev = sfp->parentdp->device;
1817
1818         if (((unsigned long)hp->dxferp &
1819                         queue_dma_alignment(sdev->request_queue)) != 0)
1820                 return 1;
1821
1822         mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1823         if (mx_sc_elems <= 0) {
1824                 return 1;
1825         }
1826         res = st_map_user_pages(schp->buffer, mx_sc_elems,
1827                                 (unsigned long)hp->dxferp, dxfer_len, 
1828                                 (SG_DXFER_TO_DEV == hp->dxfer_direction) ? 1 : 0);
1829         if (res <= 0)
1830                 return 1;
1831         schp->k_use_sg = res;
1832         schp->dio_in_use = 1;
1833         hp->info |= SG_INFO_DIRECT_IO;
1834         return 0;
1835 #else
1836         return 1;
1837 #endif
1838 }
1839
1840 static int
1841 sg_build_indirect(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
1842 {
1843         struct scatterlist *sg;
1844         int ret_sz = 0, k, rem_sz, num, mx_sc_elems;
1845         int sg_tablesize = sfp->parentdp->sg_tablesize;
1846         int blk_size = buff_size;
1847         struct page *p = NULL;
1848
1849         if ((blk_size < 0) || (!sfp))
1850                 return -EFAULT;
1851         if (0 == blk_size)
1852                 ++blk_size;     /* don't know why */
1853 /* round request up to next highest SG_SECTOR_SZ byte boundary */
1854         blk_size = (blk_size + SG_SECTOR_MSK) & (~SG_SECTOR_MSK);
1855         SCSI_LOG_TIMEOUT(4, printk("sg_build_indirect: buff_size=%d, blk_size=%d\n",
1856                                    buff_size, blk_size));
1857
1858         /* N.B. ret_sz carried into this block ... */
1859         mx_sc_elems = sg_build_sgat(schp, sfp, sg_tablesize);
1860         if (mx_sc_elems < 0)
1861                 return mx_sc_elems;     /* most likely -ENOMEM */
1862
1863         for (k = 0, sg = schp->buffer, rem_sz = blk_size;
1864              (rem_sz > 0) && (k < mx_sc_elems);
1865              ++k, rem_sz -= ret_sz, ++sg) {
1866                 
1867                 num = (rem_sz > SG_SCATTER_SZ) ? SG_SCATTER_SZ : rem_sz;
1868                 p = sg_page_malloc(num, sfp->low_dma, &ret_sz);
1869                 if (!p)
1870                         return -ENOMEM;
1871
1872                 sg->page = p;
1873                 sg->length = ret_sz;
1874
1875                 SCSI_LOG_TIMEOUT(5, printk("sg_build_build: k=%d, a=0x%p, len=%d\n",
1876                                   k, p, ret_sz));
1877         }               /* end of for loop */
1878
1879         schp->k_use_sg = k;
1880         SCSI_LOG_TIMEOUT(5, printk("sg_build_indirect: k_use_sg=%d, rem_sz=%d\n", k, rem_sz));
1881
1882         schp->bufflen = blk_size;
1883         if (rem_sz > 0) /* must have failed */
1884                 return -ENOMEM;
1885
1886         return 0;
1887 }
1888
1889 static int
1890 sg_write_xfer(Sg_request * srp)
1891 {
1892         sg_io_hdr_t *hp = &srp->header;
1893         Sg_scatter_hold *schp = &srp->data;
1894         struct scatterlist *sg = schp->buffer;
1895         int num_xfer = 0;
1896         int j, k, onum, usglen, ksglen, res;
1897         int iovec_count = (int) hp->iovec_count;
1898         int dxfer_dir = hp->dxfer_direction;
1899         unsigned char *p;
1900         unsigned char __user *up;
1901         int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
1902
1903         if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_TO_DEV == dxfer_dir) ||
1904             (SG_DXFER_TO_FROM_DEV == dxfer_dir)) {
1905                 num_xfer = (int) (new_interface ? hp->dxfer_len : hp->flags);
1906                 if (schp->bufflen < num_xfer)
1907                         num_xfer = schp->bufflen;
1908         }
1909         if ((num_xfer <= 0) || (schp->dio_in_use) ||
1910             (new_interface
1911              && ((SG_FLAG_NO_DXFER | SG_FLAG_MMAP_IO) & hp->flags)))
1912                 return 0;
1913
1914         SCSI_LOG_TIMEOUT(4, printk("sg_write_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
1915                           num_xfer, iovec_count, schp->k_use_sg));
1916         if (iovec_count) {
1917                 onum = iovec_count;
1918                 if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
1919                         return -EFAULT;
1920         } else
1921                 onum = 1;
1922
1923         ksglen = sg->length;
1924         p = page_address(sg->page);
1925         for (j = 0, k = 0; j < onum; ++j) {
1926                 res = sg_u_iovec(hp, iovec_count, j, 1, &usglen, &up);
1927                 if (res)
1928                         return res;
1929
1930                 for (; p; ++sg, ksglen = sg->length,
1931                      p = page_address(sg->page)) {
1932                         if (usglen <= 0)
1933                                 break;
1934                         if (ksglen > usglen) {
1935                                 if (usglen >= num_xfer) {
1936                                         if (__copy_from_user(p, up, num_xfer))
1937                                                 return -EFAULT;
1938                                         return 0;
1939                                 }
1940                                 if (__copy_from_user(p, up, usglen))
1941                                         return -EFAULT;
1942                                 p += usglen;
1943                                 ksglen -= usglen;
1944                                 break;
1945                         } else {
1946                                 if (ksglen >= num_xfer) {
1947                                         if (__copy_from_user(p, up, num_xfer))
1948                                                 return -EFAULT;
1949                                         return 0;
1950                                 }
1951                                 if (__copy_from_user(p, up, ksglen))
1952                                         return -EFAULT;
1953                                 up += ksglen;
1954                                 usglen -= ksglen;
1955                         }
1956                         ++k;
1957                         if (k >= schp->k_use_sg)
1958                                 return 0;
1959                 }
1960         }
1961
1962         return 0;
1963 }
1964
1965 static int
1966 sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
1967            int wr_xf, int *countp, unsigned char __user **up)
1968 {
1969         int num_xfer = (int) hp->dxfer_len;
1970         unsigned char __user *p = hp->dxferp;
1971         int count;
1972
1973         if (0 == sg_num) {
1974                 if (wr_xf && ('\0' == hp->interface_id))
1975                         count = (int) hp->flags;        /* holds "old" input_size */
1976                 else
1977                         count = num_xfer;
1978         } else {
1979                 sg_iovec_t iovec;
1980                 if (__copy_from_user(&iovec, p + ind*SZ_SG_IOVEC, SZ_SG_IOVEC))
1981                         return -EFAULT;
1982                 p = iovec.iov_base;
1983                 count = (int) iovec.iov_len;
1984         }
1985         if (!access_ok(wr_xf ? VERIFY_READ : VERIFY_WRITE, p, count))
1986                 return -EFAULT;
1987         if (up)
1988                 *up = p;
1989         if (countp)
1990                 *countp = count;
1991         return 0;
1992 }
1993
1994 static void
1995 sg_remove_scat(Sg_scatter_hold * schp)
1996 {
1997         SCSI_LOG_TIMEOUT(4, printk("sg_remove_scat: k_use_sg=%d\n", schp->k_use_sg));
1998         if (schp->buffer && (schp->sglist_len > 0)) {
1999                 struct scatterlist *sg = schp->buffer;
2000
2001                 if (schp->dio_in_use) {
2002 #ifdef SG_ALLOW_DIO_CODE
2003                         st_unmap_user_pages(sg, schp->k_use_sg, TRUE);
2004 #endif
2005                 } else {
2006                         int k;
2007
2008                         for (k = 0; (k < schp->k_use_sg) && sg->page;
2009                              ++k, ++sg) {
2010                                 SCSI_LOG_TIMEOUT(5, printk(
2011                                     "sg_remove_scat: k=%d, a=0x%p, len=%d\n",
2012                                     k, sg->page, sg->length));
2013                                 sg_page_free(sg->page, sg->length);
2014                         }
2015                 }
2016                 kfree(schp->buffer);
2017         }
2018         memset(schp, 0, sizeof (*schp));
2019 }
2020
2021 static int
2022 sg_read_xfer(Sg_request * srp)
2023 {
2024         sg_io_hdr_t *hp = &srp->header;
2025         Sg_scatter_hold *schp = &srp->data;
2026         struct scatterlist *sg = schp->buffer;
2027         int num_xfer = 0;
2028         int j, k, onum, usglen, ksglen, res;
2029         int iovec_count = (int) hp->iovec_count;
2030         int dxfer_dir = hp->dxfer_direction;
2031         unsigned char *p;
2032         unsigned char __user *up;
2033         int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
2034
2035         if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_FROM_DEV == dxfer_dir)
2036             || (SG_DXFER_TO_FROM_DEV == dxfer_dir)) {
2037                 num_xfer = hp->dxfer_len;
2038                 if (schp->bufflen < num_xfer)
2039                         num_xfer = schp->bufflen;
2040         }
2041         if ((num_xfer <= 0) || (schp->dio_in_use) ||
2042             (new_interface
2043              && ((SG_FLAG_NO_DXFER | SG_FLAG_MMAP_IO) & hp->flags)))
2044                 return 0;
2045
2046         SCSI_LOG_TIMEOUT(4, printk("sg_read_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
2047                           num_xfer, iovec_count, schp->k_use_sg));
2048         if (iovec_count) {
2049                 onum = iovec_count;
2050                 if (!access_ok(VERIFY_READ, hp->dxferp, SZ_SG_IOVEC * onum))
2051                         return -EFAULT;
2052         } else
2053                 onum = 1;
2054
2055         p = page_address(sg->page);
2056         ksglen = sg->length;
2057         for (j = 0, k = 0; j < onum; ++j) {
2058                 res = sg_u_iovec(hp, iovec_count, j, 0, &usglen, &up);
2059                 if (res)
2060                         return res;
2061
2062                 for (; p; ++sg, ksglen = sg->length,
2063                      p = page_address(sg->page)) {
2064                         if (usglen <= 0)
2065                                 break;
2066                         if (ksglen > usglen) {
2067                                 if (usglen >= num_xfer) {
2068                                         if (__copy_to_user(up, p, num_xfer))
2069                                                 return -EFAULT;
2070                                         return 0;
2071                                 }
2072                                 if (__copy_to_user(up, p, usglen))
2073                                         return -EFAULT;
2074                                 p += usglen;
2075                                 ksglen -= usglen;
2076                                 break;
2077                         } else {
2078                                 if (ksglen >= num_xfer) {
2079                                         if (__copy_to_user(up, p, num_xfer))
2080                                                 return -EFAULT;
2081                                         return 0;
2082                                 }
2083                                 if (__copy_to_user(up, p, ksglen))
2084                                         return -EFAULT;
2085                                 up += ksglen;
2086                                 usglen -= ksglen;
2087                         }
2088                         ++k;
2089                         if (k >= schp->k_use_sg)
2090                                 return 0;
2091                 }
2092         }
2093
2094         return 0;
2095 }
2096
2097 static int
2098 sg_read_oxfer(Sg_request * srp, char __user *outp, int num_read_xfer)
2099 {
2100         Sg_scatter_hold *schp = &srp->data;
2101         struct scatterlist *sg = schp->buffer;
2102         int k, num;
2103
2104         SCSI_LOG_TIMEOUT(4, printk("sg_read_oxfer: num_read_xfer=%d\n",
2105                                    num_read_xfer));
2106         if ((!outp) || (num_read_xfer <= 0))
2107                 return 0;
2108
2109         for (k = 0; (k < schp->k_use_sg) && sg->page; ++k, ++sg) {
2110                 num = sg->length;
2111                 if (num > num_read_xfer) {
2112                         if (__copy_to_user(outp, page_address(sg->page),
2113                                            num_read_xfer))
2114                                 return -EFAULT;
2115                         break;
2116                 } else {
2117                         if (__copy_to_user(outp, page_address(sg->page),
2118                                            num))
2119                                 return -EFAULT;
2120                         num_read_xfer -= num;
2121                         if (num_read_xfer <= 0)
2122                                 break;
2123                         outp += num;
2124                 }
2125         }
2126
2127         return 0;
2128 }
2129
2130 static void
2131 sg_build_reserve(Sg_fd * sfp, int req_size)
2132 {
2133         Sg_scatter_hold *schp = &sfp->reserve;
2134
2135         SCSI_LOG_TIMEOUT(4, printk("sg_build_reserve: req_size=%d\n", req_size));
2136         do {
2137                 if (req_size < PAGE_SIZE)
2138                         req_size = PAGE_SIZE;
2139                 if (0 == sg_build_indirect(schp, sfp, req_size))
2140                         return;
2141                 else
2142                         sg_remove_scat(schp);
2143                 req_size >>= 1; /* divide by 2 */
2144         } while (req_size > (PAGE_SIZE / 2));
2145 }
2146
2147 static void
2148 sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
2149 {
2150         Sg_scatter_hold *req_schp = &srp->data;
2151         Sg_scatter_hold *rsv_schp = &sfp->reserve;
2152         struct scatterlist *sg = rsv_schp->buffer;
2153         int k, num, rem;
2154
2155         srp->res_used = 1;
2156         SCSI_LOG_TIMEOUT(4, printk("sg_link_reserve: size=%d\n", size));
2157         rem = size = (size + 1) & (~1); /* round to even for aha1542 */
2158
2159         for (k = 0; k < rsv_schp->k_use_sg; ++k, ++sg) {
2160                 num = sg->length;
2161                 if (rem <= num) {
2162                         sfp->save_scat_len = num;
2163                         sg->length = rem;
2164                         req_schp->k_use_sg = k + 1;
2165                         req_schp->sglist_len = rsv_schp->sglist_len;
2166                         req_schp->buffer = rsv_schp->buffer;
2167
2168                         req_schp->bufflen = size;
2169                         req_schp->b_malloc_len = rsv_schp->b_malloc_len;
2170                         break;
2171                 } else
2172                         rem -= num;
2173         }
2174
2175         if (k >= rsv_schp->k_use_sg)
2176                 SCSI_LOG_TIMEOUT(1, printk("sg_link_reserve: BAD size\n"));
2177 }
2178
2179 static void
2180 sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
2181 {
2182         Sg_scatter_hold *req_schp = &srp->data;
2183         Sg_scatter_hold *rsv_schp = &sfp->reserve;
2184
2185         SCSI_LOG_TIMEOUT(4, printk("sg_unlink_reserve: req->k_use_sg=%d\n",
2186                                    (int) req_schp->k_use_sg));
2187         if ((rsv_schp->k_use_sg > 0) && (req_schp->k_use_sg > 0)) {
2188                 struct scatterlist *sg = rsv_schp->buffer;
2189
2190                 if (sfp->save_scat_len > 0)
2191                         (sg + (req_schp->k_use_sg - 1))->length =
2192                             (unsigned) sfp->save_scat_len;
2193                 else
2194                         SCSI_LOG_TIMEOUT(1, printk ("sg_unlink_reserve: BAD save_scat_len\n"));
2195         }
2196         req_schp->k_use_sg = 0;
2197         req_schp->bufflen = 0;
2198         req_schp->buffer = NULL;
2199         req_schp->sglist_len = 0;
2200         sfp->save_scat_len = 0;
2201         srp->res_used = 0;
2202 }
2203
2204 static Sg_request *
2205 sg_get_rq_mark(Sg_fd * sfp, int pack_id)
2206 {
2207         Sg_request *resp;
2208         unsigned long iflags;
2209
2210         write_lock_irqsave(&sfp->rq_list_lock, iflags);
2211         for (resp = sfp->headrp; resp; resp = resp->nextrp) {
2212                 /* look for requests that are ready + not SG_IO owned */
2213                 if ((1 == resp->done) && (!resp->sg_io_owned) &&
2214                     ((-1 == pack_id) || (resp->header.pack_id == pack_id))) {
2215                         resp->done = 2; /* guard against other readers */
2216                         break;
2217                 }
2218         }
2219         write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
2220         return resp;
2221 }
2222
2223 #ifdef CONFIG_SCSI_PROC_FS
2224 static Sg_request *
2225 sg_get_nth_request(Sg_fd * sfp, int nth)
2226 {
2227         Sg_request *resp;
2228         unsigned long iflags;
2229         int k;
2230
2231         read_lock_irqsave(&sfp->rq_list_lock, iflags);
2232         for (k = 0, resp = sfp->headrp; resp && (k < nth);
2233              ++k, resp = resp->nextrp) ;
2234         read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
2235         return resp;
2236 }
2237 #endif
2238
2239 /* always adds to end of list */
2240 static Sg_request *
2241 sg_add_request(Sg_fd * sfp)
2242 {
2243         int k;
2244         unsigned long iflags;
2245         Sg_request *resp;
2246         Sg_request *rp = sfp->req_arr;
2247
2248         write_lock_irqsave(&sfp->rq_list_lock, iflags);
2249         resp = sfp->headrp;
2250         if (!resp) {
2251                 memset(rp, 0, sizeof (Sg_request));
2252                 rp->parentfp = sfp;
2253                 resp = rp;
2254                 sfp->headrp = resp;
2255         } else {
2256                 if (0 == sfp->cmd_q)
2257                         resp = NULL;    /* command queuing disallowed */
2258                 else {
2259                         for (k = 0; k < SG_MAX_QUEUE; ++k, ++rp) {
2260                                 if (!rp->parentfp)
2261                                         break;
2262                         }
2263                         if (k < SG_MAX_QUEUE) {
2264                                 memset(rp, 0, sizeof (Sg_request));
2265                                 rp->parentfp = sfp;
2266                                 while (resp->nextrp)
2267                                         resp = resp->nextrp;
2268                                 resp->nextrp = rp;
2269                                 resp = rp;
2270                         } else
2271                                 resp = NULL;
2272                 }
2273         }
2274         if (resp) {
2275                 resp->nextrp = NULL;
2276                 resp->header.duration = jiffies_to_msecs(jiffies);
2277         }
2278         write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
2279         return resp;
2280 }
2281
2282 /* Return of 1 for found; 0 for not found */
2283 static int
2284 sg_remove_request(Sg_fd * sfp, Sg_request * srp)
2285 {
2286         Sg_request *prev_rp;
2287         Sg_request *rp;
2288         unsigned long iflags;
2289         int res = 0;
2290
2291         if ((!sfp) || (!srp) || (!sfp->headrp))
2292                 return res;
2293         write_lock_irqsave(&sfp->rq_list_lock, iflags);
2294         prev_rp = sfp->headrp;
2295         if (srp == prev_rp) {
2296                 sfp->headrp = prev_rp->nextrp;
2297                 prev_rp->parentfp = NULL;
2298                 res = 1;
2299         } else {
2300                 while ((rp = prev_rp->nextrp)) {
2301                         if (srp == rp) {
2302                                 prev_rp->nextrp = rp->nextrp;
2303                                 rp->parentfp = NULL;
2304                                 res = 1;
2305                                 break;
2306                         }
2307                         prev_rp = rp;
2308                 }
2309         }
2310         write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
2311         return res;
2312 }
2313
2314 #ifdef CONFIG_SCSI_PROC_FS
2315 static Sg_fd *
2316 sg_get_nth_sfp(Sg_device * sdp, int nth)
2317 {
2318         Sg_fd *resp;
2319         unsigned long iflags;
2320         int k;
2321
2322         read_lock_irqsave(&sg_dev_arr_lock, iflags);
2323         for (k = 0, resp = sdp->headfp; resp && (k < nth);
2324              ++k, resp = resp->nextfp) ;
2325         read_unlock_irqrestore(&sg_dev_arr_lock, iflags);
2326         return resp;
2327 }
2328 #endif
2329
2330 static Sg_fd *
2331 sg_add_sfp(Sg_device * sdp, int dev)
2332 {
2333         Sg_fd *sfp;
2334         unsigned long iflags;
2335
2336         sfp = kzalloc(sizeof(*sfp), GFP_ATOMIC | __GFP_NOWARN);
2337         if (!sfp)
2338                 return NULL;
2339
2340         init_waitqueue_head(&sfp->read_wait);
2341         rwlock_init(&sfp->rq_list_lock);
2342
2343         sfp->timeout = SG_DEFAULT_TIMEOUT;
2344         sfp->timeout_user = SG_DEFAULT_TIMEOUT_USER;
2345         sfp->force_packid = SG_DEF_FORCE_PACK_ID;
2346         sfp->low_dma = (SG_DEF_FORCE_LOW_DMA == 0) ?
2347             sdp->device->host->unchecked_isa_dma : 1;
2348         sfp->cmd_q = SG_DEF_COMMAND_Q;
2349         sfp->keep_orphan = SG_DEF_KEEP_ORPHAN;
2350         sfp->parentdp = sdp;
2351         write_lock_irqsave(&sg_dev_arr_lock, iflags);
2352         if (!sdp->headfp)
2353                 sdp->headfp = sfp;
2354         else {                  /* add to tail of existing list */
2355                 Sg_fd *pfp = sdp->headfp;
2356                 while (pfp->nextfp)
2357                         pfp = pfp->nextfp;
2358                 pfp->nextfp = sfp;
2359         }
2360         write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
2361         SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: sfp=0x%p\n", sfp));
2362         sg_build_reserve(sfp, sg_big_buff);
2363         SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp:   bufflen=%d, k_use_sg=%d\n",
2364                            sfp->reserve.bufflen, sfp->reserve.k_use_sg));
2365         return sfp;
2366 }
2367
2368 static void
2369 __sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp)
2370 {
2371         Sg_fd *fp;
2372         Sg_fd *prev_fp;
2373
2374         prev_fp = sdp->headfp;
2375         if (sfp == prev_fp)
2376                 sdp->headfp = prev_fp->nextfp;
2377         else {
2378                 while ((fp = prev_fp->nextfp)) {
2379                         if (sfp == fp) {
2380                                 prev_fp->nextfp = fp->nextfp;
2381                                 break;
2382                         }
2383                         prev_fp = fp;
2384                 }
2385         }
2386         if (sfp->reserve.bufflen > 0) {
2387                 SCSI_LOG_TIMEOUT(6, 
2388                         printk("__sg_remove_sfp:    bufflen=%d, k_use_sg=%d\n",
2389                         (int) sfp->reserve.bufflen, (int) sfp->reserve.k_use_sg));
2390                 if (sfp->mmap_called)
2391                         sg_rb_correct4mmap(&sfp->reserve, 0);   /* undo correction */
2392                 sg_remove_scat(&sfp->reserve);
2393         }
2394         sfp->parentdp = NULL;
2395         SCSI_LOG_TIMEOUT(6, printk("__sg_remove_sfp:    sfp=0x%p\n", sfp));
2396         kfree(sfp);
2397 }
2398
2399 /* Returns 0 in normal case, 1 when detached and sdp object removed */
2400 static int
2401 sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp)
2402 {
2403         Sg_request *srp;
2404         Sg_request *tsrp;
2405         int dirty = 0;
2406         int res = 0;
2407
2408         for (srp = sfp->headrp; srp; srp = tsrp) {
2409                 tsrp = srp->nextrp;
2410                 if (sg_srp_done(srp, sfp))
2411                         sg_finish_rem_req(srp);
2412                 else
2413                         ++dirty;
2414         }
2415         if (0 == dirty) {
2416                 unsigned long iflags;
2417
2418                 write_lock_irqsave(&sg_dev_arr_lock, iflags);
2419                 __sg_remove_sfp(sdp, sfp);
2420                 if (sdp->detached && (NULL == sdp->headfp)) {
2421                         int k, maxd;
2422
2423                         maxd = sg_dev_max;
2424                         for (k = 0; k < maxd; ++k) {
2425                                 if (sdp == sg_dev_arr[k])
2426                                         break;
2427                         }
2428                         if (k < maxd)
2429                                 sg_dev_arr[k] = NULL;
2430                         kfree((char *) sdp);
2431                         res = 1;
2432                 }
2433                 write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
2434         } else {
2435                 /* MOD_INC's to inhibit unloading sg and associated adapter driver */
2436                 /* only bump the access_count if we actually succeeded in
2437                  * throwing another counter on the host module */
2438                 scsi_device_get(sdp->device);   /* XXX: retval ignored? */      
2439                 sfp->closed = 1;        /* flag dirty state on this fd */
2440                 SCSI_LOG_TIMEOUT(1, printk("sg_remove_sfp: worrisome, %d writes pending\n",
2441                                   dirty));
2442         }
2443         return res;
2444 }
2445
2446 static int
2447 sg_res_in_use(Sg_fd * sfp)
2448 {
2449         const Sg_request *srp;
2450         unsigned long iflags;
2451
2452         read_lock_irqsave(&sfp->rq_list_lock, iflags);
2453         for (srp = sfp->headrp; srp; srp = srp->nextrp)
2454                 if (srp->res_used)
2455                         break;
2456         read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
2457         return srp ? 1 : 0;
2458 }
2459
2460 /* If retSzp==NULL want exact size or fail */
2461 static struct page *
2462 sg_page_malloc(int rqSz, int lowDma, int *retSzp)
2463 {
2464         struct page *resp = NULL;
2465         gfp_t page_mask;
2466         int order, a_size;
2467         int resSz = rqSz;
2468
2469         if (rqSz <= 0)
2470                 return resp;
2471
2472         if (lowDma)
2473                 page_mask = GFP_ATOMIC | GFP_DMA | __GFP_NOWARN;
2474         else
2475                 page_mask = GFP_ATOMIC | __GFP_NOWARN;
2476
2477         for (order = 0, a_size = PAGE_SIZE; a_size < rqSz;
2478              order++, a_size <<= 1) ;
2479         resp = alloc_pages(page_mask, order);
2480         while ((!resp) && order && retSzp) {
2481                 --order;
2482                 a_size >>= 1;   /* divide by 2, until PAGE_SIZE */
2483                 resp =  alloc_pages(page_mask, order);  /* try half */
2484                 resSz = a_size;
2485         }
2486         if (resp) {
2487                 if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
2488                         memset(page_address(resp), 0, resSz);
2489                 if (retSzp)
2490                         *retSzp = resSz;
2491         }
2492         return resp;
2493 }
2494
2495 static void
2496 sg_page_free(struct page *page, int size)
2497 {
2498         int order, a_size;
2499
2500         if (!page)
2501                 return;
2502         for (order = 0, a_size = PAGE_SIZE; a_size < size;
2503              order++, a_size <<= 1) ;
2504         __free_pages(page, order);
2505 }
2506
2507 #ifndef MAINTENANCE_IN_CMD
2508 #define MAINTENANCE_IN_CMD 0xa3
2509 #endif
2510
2511 static unsigned char allow_ops[] = { TEST_UNIT_READY, REQUEST_SENSE,
2512         INQUIRY, READ_CAPACITY, READ_BUFFER, READ_6, READ_10, READ_12,
2513         READ_16, MODE_SENSE, MODE_SENSE_10, LOG_SENSE, REPORT_LUNS,
2514         SERVICE_ACTION_IN, RECEIVE_DIAGNOSTIC, READ_LONG, MAINTENANCE_IN_CMD
2515 };
2516
2517 static int
2518 sg_allow_access(unsigned char opcode, char dev_type)
2519 {
2520         int k;
2521
2522         if (TYPE_SCANNER == dev_type)   /* TYPE_ROM maybe burner */
2523                 return 1;
2524         for (k = 0; k < sizeof (allow_ops); ++k) {
2525                 if (opcode == allow_ops[k])
2526                         return 1;
2527         }
2528         return 0;
2529 }
2530
2531 #ifdef CONFIG_SCSI_PROC_FS
2532 static int
2533 sg_last_dev(void)
2534 {
2535         int k;
2536         unsigned long iflags;
2537
2538         read_lock_irqsave(&sg_dev_arr_lock, iflags);
2539         for (k = sg_dev_max - 1; k >= 0; --k)
2540                 if (sg_dev_arr[k] && sg_dev_arr[k]->device)
2541                         break;
2542         read_unlock_irqrestore(&sg_dev_arr_lock, iflags);
2543         return k + 1;           /* origin 1 */
2544 }
2545 #endif
2546
2547 static Sg_device *
2548 sg_get_dev(int dev)
2549 {
2550         Sg_device *sdp = NULL;
2551         unsigned long iflags;
2552
2553         if (sg_dev_arr && (dev >= 0)) {
2554                 read_lock_irqsave(&sg_dev_arr_lock, iflags);
2555                 if (dev < sg_dev_max)
2556                         sdp = sg_dev_arr[dev];
2557                 read_unlock_irqrestore(&sg_dev_arr_lock, iflags);
2558         }
2559         return sdp;
2560 }
2561
2562 #ifdef CONFIG_SCSI_PROC_FS
2563
2564 static struct proc_dir_entry *sg_proc_sgp = NULL;
2565
2566 static char sg_proc_sg_dirname[] = "scsi/sg";
2567
2568 static int sg_proc_seq_show_int(struct seq_file *s, void *v);
2569
2570 static int sg_proc_single_open_adio(struct inode *inode, struct file *file);
2571 static ssize_t sg_proc_write_adio(struct file *filp, const char __user *buffer,
2572                                   size_t count, loff_t *off);
2573 static struct file_operations adio_fops = {
2574         /* .owner, .read and .llseek added in sg_proc_init() */
2575         .open = sg_proc_single_open_adio,
2576         .write = sg_proc_write_adio,
2577         .release = single_release,
2578 };
2579
2580 static int sg_proc_single_open_dressz(struct inode *inode, struct file *file);
2581 static ssize_t sg_proc_write_dressz(struct file *filp, 
2582                 const char __user *buffer, size_t count, loff_t *off);
2583 static struct file_operations dressz_fops = {
2584         .open = sg_proc_single_open_dressz,
2585         .write = sg_proc_write_dressz,
2586         .release = single_release,
2587 };
2588
2589 static int sg_proc_seq_show_version(struct seq_file *s, void *v);
2590 static int sg_proc_single_open_version(struct inode *inode, struct file *file);
2591 static struct file_operations version_fops = {
2592         .open = sg_proc_single_open_version,
2593         .release = single_release,
2594 };
2595
2596 static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v);
2597 static int sg_proc_single_open_devhdr(struct inode *inode, struct file *file);
2598 static struct file_operations devhdr_fops = {
2599         .open = sg_proc_single_open_devhdr,
2600         .release = single_release,
2601 };
2602
2603 static int sg_proc_seq_show_dev(struct seq_file *s, void *v);
2604 static int sg_proc_open_dev(struct inode *inode, struct file *file);
2605 static void * dev_seq_start(struct seq_file *s, loff_t *pos);
2606 static void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos);
2607 static void dev_seq_stop(struct seq_file *s, void *v);
2608 static struct file_operations dev_fops = {
2609         .open = sg_proc_open_dev,
2610         .release = seq_release,
2611 };
2612 static struct seq_operations dev_seq_ops = {
2613         .start = dev_seq_start,
2614         .next  = dev_seq_next,
2615         .stop  = dev_seq_stop,
2616         .show  = sg_proc_seq_show_dev,
2617 };
2618
2619 static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v);
2620 static int sg_proc_open_devstrs(struct inode *inode, struct file *file);
2621 static struct file_operations devstrs_fops = {
2622         .open = sg_proc_open_devstrs,
2623         .release = seq_release,
2624 };
2625 static struct seq_operations devstrs_seq_ops = {
2626         .start = dev_seq_start,
2627         .next  = dev_seq_next,
2628         .stop  = dev_seq_stop,
2629         .show  = sg_proc_seq_show_devstrs,
2630 };
2631
2632 static int sg_proc_seq_show_debug(struct seq_file *s, void *v);
2633 static int sg_proc_open_debug(struct inode *inode, struct file *file);
2634 static struct file_operations debug_fops = {
2635         .open = sg_proc_open_debug,
2636         .release = seq_release,
2637 };
2638 static struct seq_operations debug_seq_ops = {
2639         .start = dev_seq_start,
2640         .next  = dev_seq_next,
2641         .stop  = dev_seq_stop,
2642         .show  = sg_proc_seq_show_debug,
2643 };
2644
2645
2646 struct sg_proc_leaf {
2647         const char * name;
2648         struct file_operations * fops;
2649 };
2650
2651 static struct sg_proc_leaf sg_proc_leaf_arr[] = {
2652         {"allow_dio", &adio_fops},
2653         {"debug", &debug_fops},
2654         {"def_reserved_size", &dressz_fops},
2655         {"device_hdr", &devhdr_fops},
2656         {"devices", &dev_fops},
2657         {"device_strs", &devstrs_fops},
2658         {"version", &version_fops}
2659 };
2660
2661 static int
2662 sg_proc_init(void)
2663 {
2664         int k, mask;
2665         int num_leaves =
2666             sizeof (sg_proc_leaf_arr) / sizeof (sg_proc_leaf_arr[0]);
2667         struct proc_dir_entry *pdep;
2668         struct sg_proc_leaf * leaf;
2669
2670         sg_proc_sgp = proc_mkdir(sg_proc_sg_dirname, NULL);
2671         if (!sg_proc_sgp)
2672                 return 1;
2673         for (k = 0; k < num_leaves; ++k) {
2674                 leaf = &sg_proc_leaf_arr[k];
2675                 mask = leaf->fops->write ? S_IRUGO | S_IWUSR : S_IRUGO;
2676                 pdep = create_proc_entry(leaf->name, mask, sg_proc_sgp);
2677                 if (pdep) {
2678                         leaf->fops->owner = THIS_MODULE,
2679                         leaf->fops->read = seq_read,
2680                         leaf->fops->llseek = seq_lseek,
2681                         pdep->proc_fops = leaf->fops;
2682                 }
2683         }
2684         return 0;
2685 }
2686
2687 static void
2688 sg_proc_cleanup(void)
2689 {
2690         int k;
2691         int num_leaves =
2692             sizeof (sg_proc_leaf_arr) / sizeof (sg_proc_leaf_arr[0]);
2693
2694         if (!sg_proc_sgp)
2695                 return;
2696         for (k = 0; k < num_leaves; ++k)
2697                 remove_proc_entry(sg_proc_leaf_arr[k].name, sg_proc_sgp);
2698         remove_proc_entry(sg_proc_sg_dirname, NULL);
2699 }
2700
2701
2702 static int sg_proc_seq_show_int(struct seq_file *s, void *v)
2703 {
2704         seq_printf(s, "%d\n", *((int *)s->private));
2705         return 0;
2706 }
2707
2708 static int sg_proc_single_open_adio(struct inode *inode, struct file *file)
2709 {
2710         return single_open(file, sg_proc_seq_show_int, &sg_allow_dio);
2711 }
2712
2713 static ssize_t 
2714 sg_proc_write_adio(struct file *filp, const char __user *buffer,
2715                    size_t count, loff_t *off)
2716 {
2717         int num;
2718         char buff[11];
2719
2720         if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
2721                 return -EACCES;
2722         num = (count < 10) ? count : 10;
2723         if (copy_from_user(buff, buffer, num))
2724                 return -EFAULT;
2725         buff[num] = '\0';
2726         sg_allow_dio = simple_strtoul(buff, NULL, 10) ? 1 : 0;
2727         return count;
2728 }
2729
2730 static int sg_proc_single_open_dressz(struct inode *inode, struct file *file)
2731 {
2732         return single_open(file, sg_proc_seq_show_int, &sg_big_buff);
2733 }
2734
2735 static ssize_t 
2736 sg_proc_write_dressz(struct file *filp, const char __user *buffer,
2737                      size_t count, loff_t *off)
2738 {
2739         int num;
2740         unsigned long k = ULONG_MAX;
2741         char buff[11];
2742
2743         if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
2744                 return -EACCES;
2745         num = (count < 10) ? count : 10;
2746         if (copy_from_user(buff, buffer, num))
2747                 return -EFAULT;
2748         buff[num] = '\0';
2749         k = simple_strtoul(buff, NULL, 10);
2750         if (k <= 1048576) {     /* limit "big buff" to 1 MB */
2751                 sg_big_buff = k;
2752                 return count;
2753         }
2754         return -ERANGE;
2755 }
2756
2757 static int sg_proc_seq_show_version(struct seq_file *s, void *v)
2758 {
2759         seq_printf(s, "%d\t%s [%s]\n", sg_version_num, SG_VERSION_STR,
2760                    sg_version_date);
2761         return 0;
2762 }
2763
2764 static int sg_proc_single_open_version(struct inode *inode, struct file *file)
2765 {
2766         return single_open(file, sg_proc_seq_show_version, NULL);
2767 }
2768
2769 static int sg_proc_seq_show_devhdr(struct seq_file *s, void *v)
2770 {
2771         seq_printf(s, "host\tchan\tid\tlun\ttype\topens\tqdepth\tbusy\t"
2772                    "online\n");
2773         return 0;
2774 }
2775
2776 static int sg_proc_single_open_devhdr(struct inode *inode, struct file *file)
2777 {
2778         return single_open(file, sg_proc_seq_show_devhdr, NULL);
2779 }
2780
2781 struct sg_proc_deviter {
2782         loff_t  index;
2783         size_t  max;
2784 };
2785
2786 static void * dev_seq_start(struct seq_file *s, loff_t *pos)
2787 {
2788         struct sg_proc_deviter * it = kmalloc(sizeof(*it), GFP_KERNEL);
2789
2790         s->private = it;
2791         if (! it)
2792                 return NULL;
2793
2794         if (NULL == sg_dev_arr)
2795                 return NULL;
2796         it->index = *pos;
2797         it->max = sg_last_dev();
2798         if (it->index >= it->max)
2799                 return NULL;
2800         return it;
2801 }
2802
2803 static void * dev_seq_next(struct seq_file *s, void *v, loff_t *pos)
2804 {
2805         struct sg_proc_deviter * it = s->private;
2806
2807         *pos = ++it->index;
2808         return (it->index < it->max) ? it : NULL;
2809 }
2810
2811 static void dev_seq_stop(struct seq_file *s, void *v)
2812 {
2813         kfree(s->private);
2814 }
2815
2816 static int sg_proc_open_dev(struct inode *inode, struct file *file)
2817 {
2818         return seq_open(file, &dev_seq_ops);
2819 }
2820
2821 static int sg_proc_seq_show_dev(struct seq_file *s, void *v)
2822 {
2823         struct sg_proc_deviter * it = (struct sg_proc_deviter *) v;
2824         Sg_device *sdp;
2825         struct scsi_device *scsidp;
2826
2827         sdp = it ? sg_get_dev(it->index) : NULL;
2828         if (sdp && (scsidp = sdp->device) && (!sdp->detached))
2829                 seq_printf(s, "%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n",
2830                               scsidp->host->host_no, scsidp->channel,
2831                               scsidp->id, scsidp->lun, (int) scsidp->type,
2832                               1,
2833                               (int) scsidp->queue_depth,
2834                               (int) scsidp->device_busy,
2835                               (int) scsi_device_online(scsidp));
2836         else
2837                 seq_printf(s, "-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\n");
2838         return 0;
2839 }
2840
2841 static int sg_proc_open_devstrs(struct inode *inode, struct file *file)
2842 {
2843         return seq_open(file, &devstrs_seq_ops);
2844 }
2845
2846 static int sg_proc_seq_show_devstrs(struct seq_file *s, void *v)
2847 {
2848         struct sg_proc_deviter * it = (struct sg_proc_deviter *) v;
2849         Sg_device *sdp;
2850         struct scsi_device *scsidp;
2851
2852         sdp = it ? sg_get_dev(it->index) : NULL;
2853         if (sdp && (scsidp = sdp->device) && (!sdp->detached))
2854                 seq_printf(s, "%8.8s\t%16.16s\t%4.4s\n",
2855                            scsidp->vendor, scsidp->model, scsidp->rev);
2856         else
2857                 seq_printf(s, "<no active device>\n");
2858         return 0;
2859 }
2860
2861 static void sg_proc_debug_helper(struct seq_file *s, Sg_device * sdp)
2862 {
2863         int k, m, new_interface, blen, usg;
2864         Sg_request *srp;
2865         Sg_fd *fp;
2866         const sg_io_hdr_t *hp;
2867         const char * cp;
2868         unsigned int ms;
2869
2870         for (k = 0; (fp = sg_get_nth_sfp(sdp, k)); ++k) {
2871                 seq_printf(s, "   FD(%d): timeout=%dms bufflen=%d "
2872                            "(res)sgat=%d low_dma=%d\n", k + 1,
2873                            jiffies_to_msecs(fp->timeout),
2874                            fp->reserve.bufflen,
2875                            (int) fp->reserve.k_use_sg,
2876                            (int) fp->low_dma);
2877                 seq_printf(s, "   cmd_q=%d f_packid=%d k_orphan=%d closed=%d\n",
2878                            (int) fp->cmd_q, (int) fp->force_packid,
2879                            (int) fp->keep_orphan, (int) fp->closed);
2880                 for (m = 0; (srp = sg_get_nth_request(fp, m)); ++m) {
2881                         hp = &srp->header;
2882                         new_interface = (hp->interface_id == '\0') ? 0 : 1;
2883                         if (srp->res_used) {
2884                                 if (new_interface && 
2885                                     (SG_FLAG_MMAP_IO & hp->flags))
2886                                         cp = "     mmap>> ";
2887                                 else
2888                                         cp = "     rb>> ";
2889                         } else {
2890                                 if (SG_INFO_DIRECT_IO_MASK & hp->info)
2891                                         cp = "     dio>> ";
2892                                 else
2893                                         cp = "     ";
2894                         }
2895                         seq_printf(s, cp);
2896                         blen = srp->data.bufflen;
2897                         usg = srp->data.k_use_sg;
2898                         seq_printf(s, srp->done ? 
2899                                    ((1 == srp->done) ?  "rcv:" : "fin:")
2900                                    : "act:");
2901                         seq_printf(s, " id=%d blen=%d",
2902                                    srp->header.pack_id, blen);
2903                         if (srp->done)
2904                                 seq_printf(s, " dur=%d", hp->duration);
2905                         else {
2906                                 ms = jiffies_to_msecs(jiffies);
2907                                 seq_printf(s, " t_o/elap=%d/%d",
2908                                         (new_interface ? hp->timeout :
2909                                                   jiffies_to_msecs(fp->timeout)),
2910                                         (ms > hp->duration ? ms - hp->duration : 0));
2911                         }
2912                         seq_printf(s, "ms sgat=%d op=0x%02x\n", usg,
2913                                    (int) srp->data.cmd_opcode);
2914                 }
2915                 if (0 == m)
2916                         seq_printf(s, "     No requests active\n");
2917         }
2918 }
2919
2920 static int sg_proc_open_debug(struct inode *inode, struct file *file)
2921 {
2922         return seq_open(file, &debug_seq_ops);
2923 }
2924
2925 static int sg_proc_seq_show_debug(struct seq_file *s, void *v)
2926 {
2927         struct sg_proc_deviter * it = (struct sg_proc_deviter *) v;
2928         Sg_device *sdp;
2929
2930         if (it && (0 == it->index)) {
2931                 seq_printf(s, "dev_max(currently)=%d max_active_device=%d "
2932                            "(origin 1)\n", sg_dev_max, (int)it->max);
2933                 seq_printf(s, " def_reserved_size=%d\n", sg_big_buff);
2934         }
2935         sdp = it ? sg_get_dev(it->index) : NULL;
2936         if (sdp) {
2937                 struct scsi_device *scsidp = sdp->device;
2938
2939                 if (NULL == scsidp) {
2940                         seq_printf(s, "device %d detached ??\n", 
2941                                    (int)it->index);
2942                         return 0;
2943                 }
2944
2945                 if (sg_get_nth_sfp(sdp, 0)) {
2946                         seq_printf(s, " >>> device=%s ",
2947                                 sdp->disk->disk_name);
2948                         if (sdp->detached)
2949                                 seq_printf(s, "detached pending close ");
2950                         else
2951                                 seq_printf
2952                                     (s, "scsi%d chan=%d id=%d lun=%d   em=%d",
2953                                      scsidp->host->host_no,
2954                                      scsidp->channel, scsidp->id,
2955                                      scsidp->lun,
2956                                      scsidp->host->hostt->emulated);
2957                         seq_printf(s, " sg_tablesize=%d excl=%d\n",
2958                                    sdp->sg_tablesize, sdp->exclude);
2959                 }
2960                 sg_proc_debug_helper(s, sdp);
2961         }
2962         return 0;
2963 }
2964
2965 #endif                          /* CONFIG_SCSI_PROC_FS */
2966
2967 module_init(init_sg);
2968 module_exit(exit_sg);
2969 MODULE_ALIAS_CHARDEV_MAJOR(SCSI_GENERIC_MAJOR);