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