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