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