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