Import changeset
[linux-flexiantxendom0-3.2.10.git] / drivers / scsi / sg.c
1 /*
2  *  History:
3  *  Started: Aug 9 by Lawrence Foard (entropy@world.std.com),
4  *           to allow user process control of SCSI devices.
5  *  Development Sponsored by Killy Corp. NY NY
6  *
7  * Original driver (sg.c):
8  *        Copyright (C) 1992 Lawrence Foard
9  * Version 2 and 3 extensions to driver:
10  *        Copyright (C) 1998 - 2000 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 #include <linux/config.h>
21 #ifdef CONFIG_PROC_FS
22  static char * sg_version_str = "Version: 3.1.17 (20001002)";
23 #endif
24  static int sg_version_num = 30117; /* 2 digits for each component */
25 /*
26  *  D. P. Gilbert (dgilbert@interlog.com, dougg@triode.net.au), notes:
27  *      - scsi logging is available via SCSI_LOG_TIMEOUT macros. First
28  *        the kernel/module needs to be built with CONFIG_SCSI_LOGGING
29  *        (otherwise the macros compile to empty statements).
30  *        Then before running the program to be debugged enter:
31  *          # echo "scsi log timeout 7" > /proc/scsi/scsi
32  *        This will send copious output to the console and the log which
33  *        is usually /var/log/messages. To turn off debugging enter:
34  *          # echo "scsi log timeout 0" > /proc/scsi/scsi
35  *        The 'timeout' token was chosen because it is relatively unused.
36  *        The token 'hlcomplete' should be used but that triggers too
37  *        much output from the sd device driver. To dump the current
38  *        state of the SCSI mid level data structures enter:
39  *          # echo "scsi dump 1" > /proc/scsi/scsi
40  *        To dump the state of sg's data structures use:
41  *          # cat /proc/scsi/sg/debug
42  *
43  */
44 #include <linux/module.h>
45
46 #include <linux/fs.h>
47 #include <linux/kernel.h>
48 #include <linux/sched.h>
49 #include <linux/string.h>
50 #include <linux/mm.h>
51 #include <linux/errno.h>
52 #include <linux/mtio.h>
53 #include <linux/ioctl.h>
54 #include <linux/fcntl.h>
55 #include <linux/init.h>
56 #include <linux/poll.h>
57 #include <linux/smp_lock.h>
58
59 #include <asm/io.h>
60 #include <asm/uaccess.h>
61 #include <asm/system.h>
62
63 #include <linux/blk.h>
64 #include "scsi.h"
65 #include "hosts.h"
66 #include <scsi/scsi_ioctl.h>
67 #include <scsi/sg.h>
68
69 #ifdef CONFIG_PROC_FS
70 #include <linux/proc_fs.h>
71 static int sg_proc_init(void);
72 static void sg_proc_cleanup(void);
73 #endif
74
75 #ifndef LINUX_VERSION_CODE
76 #include <linux/version.h>
77 #endif /* LINUX_VERSION_CODE */
78
79 /* #define SG_ALLOW_DIO */
80 #ifdef SG_ALLOW_DIO
81 #include <linux/iobuf.h>
82 #endif
83
84 int sg_big_buff = SG_DEF_RESERVED_SIZE;
85 /* N.B. This variable is readable and writeable via
86    /proc/scsi/sg/def_reserved_size . Each time sg_open() is called a buffer
87    of this size (or less if there is not enough memory) will be reserved
88    for use by this file descriptor. [Deprecated usage: this variable is also
89    readable via /proc/sys/kernel/sg-big-buff if the sg driver is built into
90    the kernel (i.e. it is not a module).] */
91 static int def_reserved_size = -1;      /* picks up init parameter */
92
93 #define SG_SECTOR_SZ 512
94 #define SG_SECTOR_MSK (SG_SECTOR_SZ - 1)
95
96 #define SG_LOW_POOL_THRESHHOLD 30
97 #define SG_MAX_POOL_SECTORS 320  /* Max. number of pool sectors to take */
98
99 static int sg_pool_secs_avail = SG_MAX_POOL_SECTORS;
100
101 #define SG_HEAP_PAGE 1  /* heap from kernel via get_free_pages() */
102 #define SG_HEAP_KMAL 2  /* heap from kernel via kmalloc() */
103 #define SG_HEAP_POOL 3  /* heap from scsi dma pool (mid-level) */
104 #define SG_USER_MEM 4   /* memory belongs to user space */
105
106 #define SG_DEV_ARR_LUMP 6 /* amount to over allocate sg_dev_arr by */
107
108
109 static int sg_init(void);
110 static int sg_attach(Scsi_Device *);
111 static void sg_finish(void);
112 static int sg_detect(Scsi_Device *);
113 static void sg_detach(Scsi_Device *);
114
115 static Scsi_Request * dummy_cmdp = 0;    /* only used for sizeof */
116
117 static rwlock_t sg_dev_arr_lock = RW_LOCK_UNLOCKED;  /* Also used to lock
118                         file descriptor list for device */
119
120 static struct Scsi_Device_Template sg_template =
121 {
122       tag:"sg",
123       scsi_type:0xff,
124       major:SCSI_GENERIC_MAJOR,
125       detect:sg_detect,
126       init:sg_init,
127       finish:sg_finish,
128       attach:sg_attach,
129       detach:sg_detach
130 };
131
132
133 typedef struct sg_scatter_hold  /* holding area for scsi scatter gather info */
134 {
135     unsigned short k_use_sg;    /* Count of kernel scatter-gather pieces */
136     unsigned short sglist_len;  /* size of malloc'd scatter-gather list */
137     unsigned bufflen;           /* Size of (aggregate) data buffer */
138     unsigned b_malloc_len;      /* actual len malloc'ed in buffer */
139     void * buffer;              /* Data buffer or scatter list,12 bytes each*/
140     struct kiobuf * kiobp;      /* for direct IO information */
141     char mapped;                /* indicates kiobp has locked pages */
142     char buffer_mem_src;        /* heap whereabouts of 'buffer' */
143     unsigned char cmd_opcode;   /* first byte of command */
144 } Sg_scatter_hold;    /* 24 bytes long on i386 */
145
146 struct sg_device;               /* forward declarations */
147 struct sg_fd;
148
149 typedef struct sg_request  /* SG_MAX_QUEUE requests outstanding per file */
150 {
151     Scsi_Request * my_cmdp;     /* != 0  when request with lower levels */
152     struct sg_request * nextrp; /* NULL -> tail request (slist) */
153     struct sg_fd * parentfp;    /* NULL -> not in use */
154     Sg_scatter_hold data;       /* hold buffer, perhaps scatter list */
155     sg_io_hdr_t header;         /* scsi command+info, see <scsi/sg.h> */
156     unsigned char sense_b[sizeof(dummy_cmdp->sr_sense_buffer)];
157     char res_used;              /* 1 -> using reserve buffer, 0 -> not ... */
158     char orphan;                /* 1 -> drop on sight, 0 -> normal */
159     char sg_io_owned;           /* 1 -> packet belongs to SG_IO */
160     char done;                  /* 0->before bh, 1->before read, 2->read */
161 } Sg_request; /* 168 bytes long on i386 */
162
163 typedef struct sg_fd /* holds the state of a file descriptor */
164 {
165     struct sg_fd * nextfp; /* NULL when last opened fd on this device */
166     struct sg_device * parentdp;     /* owning device */
167     wait_queue_head_t read_wait;     /* queue read until command done */
168     rwlock_t rq_list_lock;           /* protect access to list in req_arr */
169     int timeout;                     /* defaults to SG_DEFAULT_TIMEOUT */
170     Sg_scatter_hold reserve;  /* buffer held for this file descriptor */
171     unsigned save_scat_len;   /* original length of trunc. scat. element */
172     Sg_request * headrp;      /* head of request slist, NULL->empty */
173     struct fasync_struct * async_qp; /* used by asynchronous notification */
174     Sg_request req_arr[SG_MAX_QUEUE]; /* used as singly-linked list */
175     char low_dma;       /* as in parent but possibly overridden to 1 */
176     char force_packid;  /* 1 -> pack_id input to read(), 0 -> ignored */
177     char closed;        /* 1 -> fd closed but request(s) outstanding */
178     char fd_mem_src;    /* heap whereabouts of this Sg_fd object */
179     char cmd_q;         /* 1 -> allow command queuing, 0 -> don't */
180     char next_cmd_len;  /* 0 -> automatic (def), >0 -> use on next write() */
181     char keep_orphan;   /* 0 -> drop orphan (def), 1 -> keep for read() */
182 } Sg_fd; /* 2768 bytes long on i386 */
183
184 typedef struct sg_device /* holds the state of each scsi generic device */
185 {
186     Scsi_Device * device;
187     wait_queue_head_t o_excl_wait;   /* queue open() when O_EXCL in use */
188     int sg_tablesize;   /* adapter's max scatter-gather table size */
189     Sg_fd * headfp;     /* first open fd belonging to this device */
190     devfs_handle_t de;
191     kdev_t i_rdev;      /* holds device major+minor number */
192     char exclude;       /* opened for exclusive access */
193     char sgdebug;       /* 0->off, 1->sense, 9->dump dev, 10-> all devs */
194     char detached;      /* 0->attached, 1->detached pending removal */
195 } Sg_device; /* 44 bytes long on i386 */
196
197
198 static int sg_fasync(int fd, struct file * filp, int mode);
199 static void sg_cmd_done_bh(Scsi_Cmnd * SCpnt);
200 static int sg_start_req(Sg_request * srp);
201 static void sg_finish_rem_req(Sg_request * srp);
202 static int sg_build_indi(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size);
203 static int sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp);
204 static ssize_t sg_new_read(Sg_fd * sfp, char * buf, size_t count,
205                            Sg_request * srp);
206 static ssize_t sg_new_write(Sg_fd * sfp, const char * buf, size_t count,
207                         int blocking, int read_only, Sg_request ** o_srp);
208 static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
209                            unsigned char * cmnd, int timeout, int blocking);
210 static int sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
211                       int wr_xf, int * countp, unsigned char ** up);
212 static int sg_write_xfer(Sg_request * srp);
213 static int sg_read_xfer(Sg_request * srp);
214 static void sg_read_oxfer(Sg_request * srp, char * outp, int num_read_xfer);
215 static void sg_remove_scat(Sg_scatter_hold * schp);
216 static char * sg_get_sgat_msa(Sg_scatter_hold * schp);
217 static void sg_build_reserve(Sg_fd * sfp, int req_size);
218 static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size);
219 static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp);
220 static char * sg_malloc(const Sg_fd * sfp, int size, int * retSzp,
221                         int * mem_srcp);
222 static void sg_free(char * buff, int size, int mem_src);
223 static char * sg_low_malloc(int rqSz, int lowDma, int mem_src,
224                             int * retSzp);
225 static void sg_low_free(char * buff, int size, int mem_src);
226 static Sg_fd * sg_add_sfp(Sg_device * sdp, int dev);
227 static int sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp);
228 static Sg_request * sg_get_rq_mark(Sg_fd * sfp, int pack_id);
229 static Sg_request * sg_add_request(Sg_fd * sfp);
230 static int sg_remove_request(Sg_fd * sfp, Sg_request * srp);
231 static int sg_res_in_use(Sg_fd * sfp);
232 static int sg_dio_in_use(Sg_fd * sfp);
233 static void sg_clr_srpnt(Scsi_Request * SRpnt);
234 static void sg_shorten_timeout(Scsi_Request * srpnt);
235 static int sg_ms_to_jif(unsigned int msecs);
236 static unsigned sg_jif_to_ms(int jifs);
237 static int sg_allow_access(unsigned char opcode, char dev_type);
238 static int sg_build_dir(Sg_request * srp, Sg_fd * sfp, int dxfer_len);
239 static void sg_unmap_and(Sg_scatter_hold * schp, int free_also);
240 static Sg_device * sg_get_dev(int dev);
241 #ifdef CONFIG_PROC_FS
242 static int sg_last_dev(void);
243 #endif
244
245 static Sg_device ** sg_dev_arr = NULL;
246
247 static const int size_sg_header = sizeof(struct sg_header);
248 static const int size_sg_io_hdr = sizeof(sg_io_hdr_t);
249 static const int size_sg_iovec = sizeof(sg_iovec_t);
250 static const int size_sg_req_info = sizeof(sg_req_info_t);
251
252
253 static int sg_open(struct inode * inode, struct file * filp)
254 {
255     int dev = MINOR(inode->i_rdev);
256     int flags = filp->f_flags;
257     Sg_device * sdp;
258     Sg_fd * sfp;
259     int res;
260
261     sdp = sg_get_dev(dev);
262     if ((! sdp) || (! sdp->device) || (! sdp->device->host))
263         return -ENXIO;
264     if (sdp->i_rdev != inode->i_rdev)
265         printk("sg_open: inode maj=%d, min=%d   sdp maj=%d, min=%d\n",
266                MAJOR(inode->i_rdev), MINOR(inode->i_rdev),
267                MAJOR(sdp->i_rdev), MINOR(sdp->i_rdev));
268     /* If we are in the middle of error recovery, don't let anyone
269      * else try and use this device.  Also, if error recovery fails, it
270      * may try and take the device offline, in which case all further
271      * access to the device is prohibited.  */
272     if (! ((flags & O_NONBLOCK) || 
273            scsi_block_when_processing_errors(sdp->device)))
274         return -ENXIO;
275
276     SCSI_LOG_TIMEOUT(3, printk("sg_open: dev=%d, flags=0x%x\n", dev, flags));
277
278     if (flags & O_EXCL) {
279         if (O_RDONLY == (flags & O_ACCMODE))
280             return -EACCES;   /* Can't lock it with read only access */
281         if (sdp->headfp && (flags & O_NONBLOCK))
282             return -EBUSY;
283         res = 0;  /* following is a macro that beats race condition */
284         __wait_event_interruptible(sdp->o_excl_wait,
285                ((sdp->headfp || sdp->exclude) ? 0 : (sdp->exclude = 1)),
286                                    res);
287         if (res)
288             return res; /* -ERESTARTSYS because signal hit process */
289     }
290     else if (sdp->exclude) { /* some other fd has an exclusive lock on dev */
291         if (flags & O_NONBLOCK)
292             return -EBUSY;
293         res = 0;  /* following is a macro that beats race condition */
294         __wait_event_interruptible(sdp->o_excl_wait, (! sdp->exclude), res);
295         if (res)
296             return res; /* -ERESTARTSYS because signal hit process */
297     }
298     if (! sdp->headfp) { /* no existing opens on this device */
299         sdp->sgdebug = 0;
300         sdp->sg_tablesize = sdp->device->host->sg_tablesize;
301     }
302     if ((sfp = sg_add_sfp(sdp, dev)))
303         filp->private_data = sfp;
304     else {
305         if (flags & O_EXCL) sdp->exclude = 0; /* undo if error */
306         return -ENOMEM;
307     }
308
309     if (sdp->device->host->hostt->module)
310         __MOD_INC_USE_COUNT(sdp->device->host->hostt->module);
311     return 0;
312 }
313
314 /* Following function was formerly called 'sg_close' */
315 static int sg_release(struct inode * inode, struct file * filp)
316 {
317     Sg_device * sdp;
318     Sg_fd * sfp;
319
320     lock_kernel();
321     if ((! (sfp = (Sg_fd *)filp->private_data)) || (! (sdp = sfp->parentdp))) {
322         unlock_kernel();
323         return -ENXIO;
324     }
325     SCSI_LOG_TIMEOUT(3, printk("sg_release: dev=%d\n", MINOR(sdp->i_rdev)));
326     sg_fasync(-1, filp, 0);   /* remove filp from async notification list */
327     sg_remove_sfp(sdp, sfp);
328     if (! sdp->headfp)
329         filp->private_data = NULL;
330
331     if (sdp->device->host->hostt->module)
332         __MOD_DEC_USE_COUNT(sdp->device->host->hostt->module);
333     sdp->exclude = 0;
334     wake_up_interruptible(&sdp->o_excl_wait);
335     unlock_kernel();
336     return 0;
337 }
338
339 static ssize_t sg_read(struct file * filp, char * buf,
340                        size_t count, loff_t *ppos)
341 {
342     int k, res;
343     Sg_device * sdp;
344     Sg_fd * sfp;
345     Sg_request * srp;
346     int req_pack_id = -1;
347     struct sg_header old_hdr;
348     sg_io_hdr_t new_hdr;
349     sg_io_hdr_t * hp;
350
351     if ((! (sfp = (Sg_fd *)filp->private_data)) || (! (sdp = sfp->parentdp)))
352         return -ENXIO;
353     SCSI_LOG_TIMEOUT(3, printk("sg_read: dev=%d, count=%d\n",
354                                MINOR(sdp->i_rdev), (int)count));
355     if (ppos != &filp->f_pos)
356         ; /* FIXME: Hmm.  Seek to the right place, or fail?  */
357     if ((k = verify_area(VERIFY_WRITE, buf, count)))
358         return k;
359     if (sfp->force_packid && (count >= size_sg_header)) {
360         __copy_from_user(&old_hdr, buf, size_sg_header);
361         if (old_hdr.reply_len < 0) {
362             if (count >= size_sg_io_hdr) {
363                 __copy_from_user(&new_hdr, buf, size_sg_io_hdr);
364                 req_pack_id = new_hdr.pack_id;
365             }
366         }
367         else
368             req_pack_id = old_hdr.pack_id;
369     }
370     srp = sg_get_rq_mark(sfp, req_pack_id);
371     if (! srp) { /* now wait on packet to arrive */
372         if (filp->f_flags & O_NONBLOCK)
373             return -EAGAIN;
374         while (1) {
375             int dio = sg_dio_in_use(sfp);
376             res = 0;  /* following is a macro that beats race condition */
377             __wait_event_interruptible(sfp->read_wait,
378                                    (srp = sg_get_rq_mark(sfp, req_pack_id)),
379                                    res);
380             if (0 == res)
381                 break;
382             else if (! dio)     /* only let signal out if no dio */
383                 return res; /* -ERESTARTSYS because signal hit process */
384         }
385     }
386     if (srp->header.interface_id != '\0')
387         return sg_new_read(sfp, buf, count, srp);
388
389     hp = &srp->header;
390     memset(&old_hdr, 0, size_sg_header);
391     old_hdr.reply_len = (int)hp->timeout;
392     old_hdr.pack_len = old_hdr.reply_len;   /* very old, strange behaviour */
393     old_hdr.pack_id = hp->pack_id;
394     old_hdr.twelve_byte =
395             ((srp->data.cmd_opcode >= 0xc0) && (12 == hp->cmd_len)) ? 1 : 0;
396     old_hdr.target_status = hp->masked_status;
397     old_hdr.host_status = hp->host_status;
398     old_hdr.driver_status = hp->driver_status;
399     if ((CHECK_CONDITION & hp->masked_status) ||
400         (DRIVER_SENSE & hp->driver_status))
401         memcpy(old_hdr.sense_buffer, srp->sense_b,
402                sizeof(old_hdr.sense_buffer));
403     switch (hp->host_status)
404     { /* This setup of 'result' is for backward compatibility and is best
405          ignored by the user who should use target, host + driver status */
406         case DID_OK:
407         case DID_PASSTHROUGH:
408         case DID_SOFT_ERROR:
409             old_hdr.result = 0;
410             break;
411         case DID_NO_CONNECT:
412         case DID_BUS_BUSY:
413         case DID_TIME_OUT:
414             old_hdr.result = EBUSY;
415             break;
416         case DID_BAD_TARGET:
417         case DID_ABORT:
418         case DID_PARITY:
419         case DID_RESET:
420         case DID_BAD_INTR:
421             old_hdr.result = EIO;
422             break;
423         case DID_ERROR:
424             old_hdr.result =
425               (srp->sense_b[0] == 0 && hp->masked_status == GOOD) ? 0 : EIO;
426             break;
427         default:
428             old_hdr.result = EIO;
429             break;
430     }
431
432     /* Now copy the result back to the user buffer.  */
433     if (count >= size_sg_header) {
434         __copy_to_user(buf, &old_hdr, size_sg_header);
435         buf += size_sg_header;
436         if (count > old_hdr.reply_len)
437             count = old_hdr.reply_len;
438         if (count > size_sg_header)
439             sg_read_oxfer(srp, buf, count - size_sg_header);
440     }
441     else
442         count = (old_hdr.result == 0) ? 0 : -EIO;
443     sg_finish_rem_req(srp);
444     return count;
445 }
446
447 static ssize_t sg_new_read(Sg_fd * sfp, char * buf, size_t count,
448                            Sg_request * srp)
449 {
450     sg_io_hdr_t         * hp = &srp->header;
451     int                   k, len;
452
453     if (count < size_sg_io_hdr)
454         return -EINVAL;
455     hp->sb_len_wr = 0;
456     if ((hp->mx_sb_len > 0) && hp->sbp) {
457         if ((CHECK_CONDITION & hp->masked_status) ||
458             (DRIVER_SENSE & hp->driver_status)) {
459             int sb_len = sizeof(dummy_cmdp->sr_sense_buffer);
460             sb_len = (hp->mx_sb_len > sb_len) ? sb_len : hp->mx_sb_len;
461             len = 8 + (int)srp->sense_b[7]; /* Additional sense length field */
462             len = (len > sb_len) ? sb_len : len;
463             if ((k = verify_area(VERIFY_WRITE, hp->sbp, len)))
464                 return k;
465             __copy_to_user(hp->sbp, srp->sense_b, len);
466             hp->sb_len_wr = len;
467         }
468     }
469     if (hp->masked_status || hp->host_status || hp->driver_status)
470         hp->info |= SG_INFO_CHECK;
471     copy_to_user(buf, hp, size_sg_io_hdr);
472
473     k = sg_read_xfer(srp);
474     if (k) return k; /* probably -EFAULT, bad addr in dxferp or iovec list */
475     sg_finish_rem_req(srp);
476     return count;
477 }
478
479
480 static ssize_t sg_write(struct file * filp, const char * buf,
481                         size_t count, loff_t *ppos)
482 {
483     int                   mxsize, cmd_size, k;
484     int                   input_size, blocking;
485     unsigned char         opcode;
486     Sg_device           * sdp;
487     Sg_fd               * sfp;
488     Sg_request          * srp;
489     struct sg_header      old_hdr;
490     sg_io_hdr_t         * hp;
491     unsigned char         cmnd[sizeof(dummy_cmdp->sr_cmnd)];
492
493     if ((! (sfp = (Sg_fd *)filp->private_data)) || (! (sdp = sfp->parentdp)))
494         return -ENXIO;
495     SCSI_LOG_TIMEOUT(3, printk("sg_write: dev=%d, count=%d\n",
496                                MINOR(sdp->i_rdev), (int)count));
497
498     if (! ((filp->f_flags & O_NONBLOCK) ||
499            scsi_block_when_processing_errors(sdp->device)))
500         return -ENXIO;
501     if (ppos != &filp->f_pos)
502         ; /* FIXME: Hmm.  Seek to the right place, or fail?  */
503
504     if ((k = verify_area(VERIFY_READ, buf, count)))
505         return k;  /* protects following copy_from_user()s + get_user()s */
506     if (count < size_sg_header)
507         return -EIO;
508     __copy_from_user(&old_hdr, buf, size_sg_header);
509     blocking = !(filp->f_flags & O_NONBLOCK);
510     if (old_hdr.reply_len < 0)
511         return sg_new_write(sfp, buf, count, blocking, 0, NULL);
512     if (count < (size_sg_header + 6))
513         return -EIO;   /* The minimum scsi command length is 6 bytes. */
514
515     if (! (srp = sg_add_request(sfp))) {
516         SCSI_LOG_TIMEOUT(1, printk("sg_write: queue full\n"));
517         return -EDOM;
518     }
519     buf += size_sg_header;
520     __get_user(opcode, buf);
521     if (sfp->next_cmd_len > 0) {
522         if (sfp->next_cmd_len > MAX_COMMAND_SIZE) {
523             SCSI_LOG_TIMEOUT(1, printk("sg_write: command length too long\n"));
524             sfp->next_cmd_len = 0;
525             sg_remove_request(sfp, srp);
526             return -EIO;
527         }
528         cmd_size = sfp->next_cmd_len;
529         sfp->next_cmd_len = 0; /* reset so only this write() effected */
530     }
531     else {
532         cmd_size = COMMAND_SIZE(opcode); /* based on SCSI command group */
533         if ((opcode >= 0xc0) && old_hdr.twelve_byte)
534             cmd_size = 12;
535     }
536     SCSI_LOG_TIMEOUT(4, printk("sg_write:   scsi opcode=0x%02x, cmd_size=%d\n",
537                                (int)opcode, cmd_size));
538 /* Determine buffer size.  */
539     input_size = count - cmd_size;
540     mxsize = (input_size > old_hdr.reply_len) ? input_size :
541                                                 old_hdr.reply_len;
542     mxsize -= size_sg_header;
543     input_size -= size_sg_header;
544     if (input_size < 0) {
545         sg_remove_request(sfp, srp);
546         return -EIO; /* User did not pass enough bytes for this command. */
547     }
548     hp = &srp->header;
549     hp->interface_id = '\0'; /* indicator of old interface tunnelled */
550     hp->cmd_len = (unsigned char)cmd_size;
551     hp->iovec_count = 0;
552     hp->mx_sb_len = 0;
553 #if 0
554     hp->dxfer_direction = SG_DXFER_UNKNOWN;
555 #else
556     if (input_size > 0)
557         hp->dxfer_direction = ((old_hdr.reply_len - size_sg_header) > 0) ?
558                               SG_DXFER_TO_FROM_DEV : SG_DXFER_TO_DEV;
559     else
560         hp->dxfer_direction = (mxsize > 0) ? SG_DXFER_FROM_DEV :
561                                              SG_DXFER_NONE;
562 #endif
563     hp->dxfer_len = mxsize;
564     hp->dxferp = (unsigned char *)buf + cmd_size;
565     hp->sbp = NULL;
566     hp->timeout = old_hdr.reply_len;    /* structure abuse ... */
567     hp->flags = input_size;             /* structure abuse ... */
568     hp->pack_id = old_hdr.pack_id;
569     hp->usr_ptr = NULL;
570     __copy_from_user(cmnd, buf, cmd_size);
571     k = sg_common_write(sfp, srp, cmnd, sfp->timeout, blocking);
572     return (k < 0) ? k : count;
573 }
574
575 static ssize_t sg_new_write(Sg_fd * sfp, const char * buf, size_t count,
576                             int blocking, int read_only, Sg_request ** o_srp)
577 {
578     int                   k;
579     Sg_request          * srp;
580     sg_io_hdr_t         * hp;
581     unsigned char         cmnd[sizeof(dummy_cmdp->sr_cmnd)];
582     int                   timeout;
583
584     if (count < size_sg_io_hdr)
585         return -EINVAL;
586     if ((k = verify_area(VERIFY_READ, buf, count)))
587         return k;  /* protects following copy_from_user()s + get_user()s */
588
589     sfp->cmd_q = 1;  /* when sg_io_hdr seen, set command queuing on */
590     if (! (srp = sg_add_request(sfp))) {
591         SCSI_LOG_TIMEOUT(1, printk("sg_new_write: queue full\n"));
592         return -EDOM;
593     }
594     hp = &srp->header;
595     __copy_from_user(hp, buf, size_sg_io_hdr);
596     if (hp->interface_id != 'S') {
597         sg_remove_request(sfp, srp);
598         return -ENOSYS;
599     }
600     timeout = sg_ms_to_jif(srp->header.timeout);
601     if ((! hp->cmdp) || (hp->cmd_len < 6) || (hp->cmd_len > sizeof(cmnd))) {
602         sg_remove_request(sfp, srp);
603         return -EMSGSIZE;
604     }
605     if ((k = verify_area(VERIFY_READ, hp->cmdp, hp->cmd_len))) {
606         sg_remove_request(sfp, srp);
607         return k;  /* protects following copy_from_user()s + get_user()s */
608     }
609     __copy_from_user(cmnd, hp->cmdp, hp->cmd_len);
610     if (read_only &&
611         (! sg_allow_access(cmnd[0], sfp->parentdp->device->type))) {
612         sg_remove_request(sfp, srp);
613         return -EACCES;
614     }
615     k = sg_common_write(sfp, srp, cmnd, timeout, blocking);
616     if (k < 0) return k;
617     if (o_srp) *o_srp = srp;
618     return count;
619 }
620
621 static int sg_common_write(Sg_fd * sfp, Sg_request * srp,
622                            unsigned char * cmnd, int timeout, int blocking)
623 {
624     int                   k;
625     Scsi_Request        * SRpnt;
626     Sg_device           * sdp = sfp->parentdp;
627     sg_io_hdr_t         * hp = &srp->header;
628
629     srp->data.cmd_opcode = cmnd[0];  /* hold opcode of command */
630     hp->status = 0;
631     hp->masked_status = 0;
632     hp->msg_status = 0;
633     hp->info = 0;
634     hp->host_status = 0;
635     hp->driver_status = 0;
636     hp->resid = 0;
637     SCSI_LOG_TIMEOUT(4,
638         printk("sg_common_write:  scsi opcode=0x%02x, cmd_size=%d\n",
639                (int)cmnd[0], (int)hp->cmd_len));
640
641     if ((k = sg_start_req(srp))) {
642         SCSI_LOG_TIMEOUT(1, printk("sg_write: start_req err=%d\n", k));
643         sg_finish_rem_req(srp);
644         return k;    /* probably out of space --> ENOMEM */
645     }
646     if ((k = sg_write_xfer(srp))) {
647         SCSI_LOG_TIMEOUT(1, printk("sg_write: write_xfer, bad address\n"));
648         sg_finish_rem_req(srp);
649         return k;
650     }
651 /*  SCSI_LOG_TIMEOUT(7, printk("sg_write: allocating device\n")); */
652     SRpnt = scsi_allocate_request(sdp->device);
653     if(SRpnt == NULL) {
654         SCSI_LOG_TIMEOUT(1, printk("sg_write: no mem\n"));
655         sg_finish_rem_req(srp);
656         return -ENOMEM;
657     }
658
659 /*  SCSI_LOG_TIMEOUT(7, printk("sg_write: device allocated\n")); */
660     srp->my_cmdp = SRpnt;
661     SRpnt->sr_request.rq_dev = sdp->i_rdev;
662     SRpnt->sr_request.rq_status = RQ_ACTIVE;
663     SRpnt->sr_sense_buffer[0] = 0;
664     SRpnt->sr_cmd_len = hp->cmd_len;
665 /* Set the LUN field in the command structure, overriding user input  */
666     if (! (hp->flags & SG_FLAG_LUN_INHIBIT))
667         cmnd[1] = (cmnd[1] & 0x1f) | (sdp->device->lun << 5);
668
669 /*  SCSI_LOG_TIMEOUT(7, printk("sg_write: do cmd\n")); */
670     SRpnt->sr_use_sg = srp->data.k_use_sg;
671     SRpnt->sr_sglist_len = srp->data.sglist_len;
672     SRpnt->sr_bufflen = srp->data.bufflen;
673     SRpnt->sr_underflow = 0;
674     SRpnt->sr_buffer = srp->data.buffer;
675     switch (hp->dxfer_direction) {
676     case SG_DXFER_TO_FROM_DEV:
677     case SG_DXFER_FROM_DEV:
678         SRpnt->sr_data_direction = SCSI_DATA_READ; break;
679     case SG_DXFER_TO_DEV:
680         SRpnt->sr_data_direction = SCSI_DATA_WRITE; break;
681     case SG_DXFER_UNKNOWN:
682         SRpnt->sr_data_direction = SCSI_DATA_UNKNOWN; break;
683     default:
684         SRpnt->sr_data_direction = SCSI_DATA_NONE; break;
685     }
686     srp->data.k_use_sg = 0;
687     srp->data.sglist_len = 0;
688     srp->data.bufflen = 0;
689     srp->data.buffer = NULL;
690     hp->duration = jiffies;     /* unit jiffies now, millisecs after done */
691 /* Now send everything of to mid-level. The next time we hear about this
692    packet is when sg_cmd_done_bh() is called (i.e. a callback). */
693     scsi_do_req(SRpnt, (void *)cmnd,
694                 (void *)SRpnt->sr_buffer, hp->dxfer_len,
695                 sg_cmd_done_bh, timeout, SG_DEFAULT_RETRIES);
696     /* dxfer_len overwrites SRpnt->sr_bufflen, hence need for b_malloc_len */
697     return 0;
698 }
699
700 static int sg_ioctl(struct inode * inode, struct file * filp,
701                     unsigned int cmd_in, unsigned long arg)
702 {
703     int result, val, read_only;
704     Sg_device * sdp;
705     Sg_fd * sfp;
706     Sg_request * srp;
707     unsigned long iflags;
708
709     if ((! (sfp = (Sg_fd *)filp->private_data)) || (! (sdp = sfp->parentdp)))
710         return -ENXIO;
711     SCSI_LOG_TIMEOUT(3, printk("sg_ioctl: dev=%d, cmd=0x%x\n",
712                                MINOR(sdp->i_rdev), (int)cmd_in));
713     read_only = (O_RDWR != (filp->f_flags & O_ACCMODE));
714
715     switch(cmd_in)
716     {
717     case SG_IO:
718         {
719             int blocking = 1;   /* ignore O_NONBLOCK flag */
720
721             if(! scsi_block_when_processing_errors(sdp->device) )
722                 return -ENXIO;
723             result = verify_area(VERIFY_WRITE, (void *)arg, size_sg_io_hdr);
724             if (result) return result;
725             result = sg_new_write(sfp, (const char *)arg, size_sg_io_hdr,
726                                   blocking, read_only, &srp);
727             if (result < 0) return result;
728             srp->sg_io_owned = 1;
729             while (1) {
730                 int dio = sg_dio_in_use(sfp);
731                 result = 0;  /* following macro to beat race condition */
732                 __wait_event_interruptible(sfp->read_wait,
733                                    (sfp->closed || srp->done), result);
734                 if (sfp->closed)
735                     return 0;       /* request packet dropped already */
736                 if (0 == result)
737                     break;
738                 else if (! dio) {       /* only let signal out if no dio */
739                     srp->orphan = 1;
740                     return result; /* -ERESTARTSYS because signal hit process */
741                 }
742             }
743             srp->done = 2;
744             result = sg_new_read(sfp, (char *)arg, size_sg_io_hdr, srp);
745             return (result < 0) ? result : 0;
746         }
747     case SG_SET_TIMEOUT:
748         result =  get_user(val, (int *)arg);
749         if (result) return result;
750         if (val < 0)
751             return -EIO;
752         sfp->timeout = val;
753         return 0;
754     case SG_GET_TIMEOUT:  /* N.B. User receives timeout as return value */
755         return sfp->timeout; /* strange ..., for backward compatibility */
756     case SG_SET_FORCE_LOW_DMA:
757         result = get_user(val, (int *)arg);
758         if (result) return result;
759         if (val) {
760             sfp->low_dma = 1;
761             if ((0 == sfp->low_dma) && (0 == sg_res_in_use(sfp))) {
762                 val = (int)sfp->reserve.bufflen;
763                 sg_remove_scat(&sfp->reserve);
764                 sg_build_reserve(sfp, val);
765             }
766         }
767         else
768             sfp->low_dma = sdp->device->host->unchecked_isa_dma;
769         return 0;
770     case SG_GET_LOW_DMA:
771         return put_user((int)sfp->low_dma, (int *)arg);
772     case SG_GET_SCSI_ID:
773         result = verify_area(VERIFY_WRITE, (void *)arg, sizeof(sg_scsi_id_t));
774         if (result) return result;
775         else {
776             sg_scsi_id_t * sg_idp = (sg_scsi_id_t *)arg;
777             __put_user((int)sdp->device->host->host_no, &sg_idp->host_no);
778             __put_user((int)sdp->device->channel, &sg_idp->channel);
779             __put_user((int)sdp->device->id, &sg_idp->scsi_id);
780             __put_user((int)sdp->device->lun, &sg_idp->lun);
781             __put_user((int)sdp->device->type, &sg_idp->scsi_type);
782             __put_user((short)sdp->device->host->cmd_per_lun,
783                        &sg_idp->h_cmd_per_lun);
784             __put_user((short)sdp->device->queue_depth,
785                        &sg_idp->d_queue_depth);
786             __put_user(0, &sg_idp->unused[0]);
787             __put_user(0, &sg_idp->unused[1]);
788             return 0;
789         }
790     case SG_SET_FORCE_PACK_ID:
791         result = get_user(val, (int *)arg);
792         if (result) return result;
793         sfp->force_packid = val ? 1 : 0;
794         return 0;
795     case SG_GET_PACK_ID:
796         result = verify_area(VERIFY_WRITE, (void *) arg, sizeof(int));
797         if (result) return result;
798         read_lock_irqsave(&sfp->rq_list_lock, iflags);
799         for (srp = sfp->headrp; srp; srp = srp->nextrp) {
800             if ((1 == srp->done) && (! srp->sg_io_owned)) {
801                 read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
802                 __put_user(srp->header.pack_id, (int *)arg);
803                 return 0;
804             }
805         }
806         read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
807         __put_user(-1, (int *)arg);
808         return 0;
809     case SG_GET_NUM_WAITING:
810         read_lock_irqsave(&sfp->rq_list_lock, iflags);
811         for (val = 0, srp = sfp->headrp; srp; srp = srp->nextrp) {
812             if ((1 == srp->done) && (! srp->sg_io_owned))
813                 ++val;
814         }
815         read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
816         return put_user(val, (int *)arg);
817     case SG_GET_SG_TABLESIZE:
818         return put_user(sdp->sg_tablesize, (int *)arg);
819     case SG_SET_RESERVED_SIZE:
820         result = get_user(val, (int *)arg);
821         if (result) return result;
822         if (val != sfp->reserve.bufflen) {
823             if (sg_res_in_use(sfp))
824                 return -EBUSY;
825             sg_remove_scat(&sfp->reserve);
826             sg_build_reserve(sfp, val);
827         }
828         return 0;
829     case SG_GET_RESERVED_SIZE:
830         val = (int)sfp->reserve.bufflen;
831         return put_user(val, (int *)arg);
832     case SG_SET_COMMAND_Q:
833         result = get_user(val, (int *)arg);
834         if (result) return result;
835         sfp->cmd_q = val ? 1 : 0;
836         return 0;
837     case SG_GET_COMMAND_Q:
838         return put_user((int)sfp->cmd_q, (int *)arg);
839     case SG_SET_KEEP_ORPHAN:
840         result = get_user(val, (int *)arg);
841         if (result) return result;
842         sfp->keep_orphan = val;
843         return 0;
844     case SG_GET_KEEP_ORPHAN:
845         return put_user((int)sfp->keep_orphan, (int *)arg);
846     case SG_NEXT_CMD_LEN:
847         result = get_user(val, (int *)arg);
848         if (result) return result;
849         sfp->next_cmd_len = (val > 0) ? val : 0;
850         return 0;
851     case SG_GET_VERSION_NUM:
852         return put_user(sg_version_num, (int *)arg);
853     case SG_GET_REQUEST_TABLE:
854         result = verify_area(VERIFY_WRITE, (void *) arg,
855                              size_sg_req_info * SG_MAX_QUEUE);
856         if (result) return result;
857         else {
858             sg_req_info_t rinfo[SG_MAX_QUEUE];
859             Sg_request * srp;
860             read_lock_irqsave(&sfp->rq_list_lock, iflags);
861             for (srp = sfp->headrp, val = 0; val < SG_MAX_QUEUE;
862                  ++val, srp = srp ? srp->nextrp : srp) {
863                 memset(&rinfo[val], 0, size_sg_req_info);
864                 if (srp) {
865                     rinfo[val].req_state = srp->done + 1;
866                     rinfo[val].problem = srp->header.masked_status &
867                         srp->header.host_status & srp->header.driver_status;
868                     rinfo[val].duration = srp->done ?
869                             srp->header.duration :
870                             sg_jif_to_ms(jiffies - srp->header.duration);
871                     rinfo[val].orphan = srp->orphan;
872                     rinfo[val].sg_io_owned = srp->sg_io_owned;
873                     rinfo[val].pack_id = srp->header.pack_id;
874                     rinfo[val].usr_ptr = srp->header.usr_ptr;
875                 }
876             }
877             read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
878             __copy_to_user((void *)arg, rinfo, size_sg_req_info * SG_MAX_QUEUE);
879             return 0;
880         }
881     case SG_EMULATED_HOST:
882         return put_user(sdp->device->host->hostt->emulated, (int *)arg);
883     case SG_SCSI_RESET:
884         if (filp->f_flags & O_NONBLOCK) {
885             if (sdp->device->host->in_recovery)
886                 return -EBUSY;
887         }
888         else if (! scsi_block_when_processing_errors(sdp->device))
889             return -EBUSY;
890         result = get_user(val, (int *)arg);
891         if (result) return result;
892         if (SG_SCSI_RESET_NOTHING == val)
893             return 0;
894 #ifdef SCSI_TRY_RESET_DEVICE
895         switch (val)
896         {
897         case SG_SCSI_RESET_DEVICE:
898             val = SCSI_TRY_RESET_DEVICE;
899             break;
900         case SG_SCSI_RESET_BUS:
901             val = SCSI_TRY_RESET_BUS;
902             break;
903         case SG_SCSI_RESET_HOST:
904             val = SCSI_TRY_RESET_HOST;
905             break;
906         default:
907             return -EINVAL;
908         }
909         if(! capable(CAP_SYS_ADMIN))  return -EACCES;
910         return (scsi_reset_provider(sdp->device, val) == SUCCESS) ? 0 : -EIO;
911 #else
912         SCSI_LOG_TIMEOUT(1, printk("sg_ioctl: SG_RESET_SCSI not supported\n"));
913         result = -EINVAL;
914 #endif
915     case SCSI_IOCTL_SEND_COMMAND:
916         if (read_only) {
917             unsigned char opcode = WRITE_6;
918             Scsi_Ioctl_Command * siocp = (void *)arg;
919
920             copy_from_user(&opcode, siocp->data, 1);
921             if (! sg_allow_access(opcode, sdp->device->type))
922                 return -EACCES;
923         }
924         return scsi_ioctl_send_command(sdp->device, (void *)arg);
925     case SG_SET_DEBUG:
926         result = get_user(val, (int *)arg);
927         if (result) return result;
928         sdp->sgdebug = (char)val;
929         return 0;
930     case SCSI_IOCTL_GET_IDLUN:
931     case SCSI_IOCTL_GET_BUS_NUMBER:
932     case SCSI_IOCTL_PROBE_HOST:
933     case SG_GET_TRANSFORM:
934         return scsi_ioctl(sdp->device, cmd_in, (void *)arg);
935     default:
936         if (read_only)
937             return -EACCES; /* don't know so take safe approach */
938         return scsi_ioctl(sdp->device, cmd_in, (void *)arg);
939     }
940 }
941
942 static unsigned int sg_poll(struct file * filp, poll_table * wait)
943 {
944     unsigned int res = 0;
945     Sg_device * sdp;
946     Sg_fd * sfp;
947     Sg_request * srp;
948     int count = 0;
949     unsigned long iflags;
950
951     if ((! (sfp = (Sg_fd *)filp->private_data)) || (! (sdp = sfp->parentdp)))
952         return POLLERR;
953     poll_wait(filp, &sfp->read_wait, wait);
954     read_lock_irqsave(&sfp->rq_list_lock, iflags);
955     for (srp = sfp->headrp; srp; srp = srp->nextrp) {   
956         /* if any read waiting, flag it */
957         if ((0 == res) && (1 == srp->done) && (! srp->sg_io_owned))
958             res = POLLIN | POLLRDNORM;
959         ++count;
960     }
961     read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
962     if (! sfp->cmd_q) {
963         if (0 == count)
964             res |= POLLOUT | POLLWRNORM;
965     }
966     else if (count < SG_MAX_QUEUE)
967         res |= POLLOUT | POLLWRNORM;
968     SCSI_LOG_TIMEOUT(3, printk("sg_poll: dev=%d, res=0x%x\n",
969                         MINOR(sdp->i_rdev), (int)res));
970     return res;
971 }
972
973 static int sg_fasync(int fd, struct file * filp, int mode)
974 {
975     int retval;
976     Sg_device * sdp;
977     Sg_fd * sfp;
978
979     if ((! (sfp = (Sg_fd *)filp->private_data)) || (! (sdp = sfp->parentdp)))
980         return -ENXIO;
981     SCSI_LOG_TIMEOUT(3, printk("sg_fasync: dev=%d, mode=%d\n",
982                                MINOR(sdp->i_rdev), mode));
983
984     retval = fasync_helper(fd, filp, mode, &sfp->async_qp);
985     return (retval < 0) ? retval : 0;
986 }
987
988 /* This function is a "bottom half" handler that is called by the
989  * mid level when a command is completed (or has failed). */
990 static void sg_cmd_done_bh(Scsi_Cmnd * SCpnt)
991 {
992     Scsi_Request * SRpnt = SCpnt->sc_request;
993     int dev = MINOR(SRpnt->sr_request.rq_dev);
994     Sg_device * sdp = NULL;
995     Sg_fd * sfp;
996     Sg_request * srp = NULL;
997
998     read_lock(&sg_dev_arr_lock);
999     if (sg_dev_arr && (dev >= 0)) {
1000         if (dev < sg_template.dev_max)
1001             sdp = sg_dev_arr[dev];
1002     }
1003     if (NULL == sdp) {
1004         read_unlock(&sg_dev_arr_lock);
1005         SCSI_LOG_TIMEOUT(1, printk("sg...bh: bad args dev=%d\n", dev));
1006         scsi_release_request(SRpnt);
1007         SRpnt = NULL;
1008         return;
1009     }
1010     sfp = sdp->headfp;
1011     while (sfp) {
1012         read_lock(&sfp->rq_list_lock);
1013         for (srp = sfp->headrp; srp; srp = srp->nextrp) {
1014             if (SRpnt == srp->my_cmdp)
1015                 break;
1016         }
1017         read_unlock(&sfp->rq_list_lock);
1018         if (srp)
1019             break;
1020         sfp = sfp->nextfp;
1021     }
1022     read_unlock(&sg_dev_arr_lock);
1023     if (! srp) {
1024         SCSI_LOG_TIMEOUT(1, printk("sg...bh: req missing, dev=%d\n", dev));
1025         scsi_release_request(SRpnt);
1026         SRpnt = NULL;
1027         return;
1028     }
1029     /* First transfer ownership of data buffers to sg_device object. */
1030     srp->data.k_use_sg = SRpnt->sr_use_sg;
1031     srp->data.sglist_len = SRpnt->sr_sglist_len;
1032     srp->data.bufflen = SRpnt->sr_bufflen;
1033     srp->data.buffer = SRpnt->sr_buffer;
1034     sg_clr_srpnt(SRpnt);
1035     srp->my_cmdp = NULL;
1036     srp->done = 1;
1037
1038     SCSI_LOG_TIMEOUT(4, printk("sg...bh: dev=%d, pack_id=%d, res=0x%x\n",
1039                      dev, srp->header.pack_id, (int)SRpnt->sr_result));
1040     srp->header.resid = SCpnt->resid;
1041     /* sg_unmap_and(&srp->data, 0); */     /* unmap locked pages a.s.a.p. */
1042     /* N.B. unit of duration changes here from jiffies to millisecs */
1043     srp->header.duration = sg_jif_to_ms(jiffies - (int)srp->header.duration);
1044     if (0 != SRpnt->sr_result) {
1045         memcpy(srp->sense_b, SRpnt->sr_sense_buffer, sizeof(srp->sense_b));
1046         srp->header.status = 0xff & SRpnt->sr_result;
1047         srp->header.masked_status  = status_byte(SRpnt->sr_result);
1048         srp->header.msg_status  = msg_byte(SRpnt->sr_result);
1049         srp->header.host_status = host_byte(SRpnt->sr_result);
1050         srp->header.driver_status = driver_byte(SRpnt->sr_result);
1051         if ((sdp->sgdebug > 0) &&
1052             ((CHECK_CONDITION == srp->header.masked_status) ||
1053              (COMMAND_TERMINATED == srp->header.masked_status)))
1054             print_req_sense("sg_cmd_done_bh", SRpnt);
1055
1056         /* Following if statement is a patch supplied by Eric Youngdale */
1057         if (driver_byte(SRpnt->sr_result) != 0
1058             && (SRpnt->sr_sense_buffer[0] & 0x7f) == 0x70
1059             && (SRpnt->sr_sense_buffer[2] & 0xf) == UNIT_ATTENTION
1060             && sdp->device->removable) {
1061             /* Detected disc change. Set the bit - this may be used if */
1062             /* there are filesystems using this device. */
1063             sdp->device->changed = 1;
1064         }
1065     }
1066     /* Rely on write phase to clean out srp status values, so no "else" */
1067
1068     scsi_release_request(SRpnt);
1069     SRpnt = NULL;
1070     if (sfp->closed) { /* whoops this fd already released, cleanup */
1071         SCSI_LOG_TIMEOUT(1,
1072                printk("sg...bh: already closed, freeing ...\n"));
1073         /* should check if module is unloaded <<<<<<< */
1074         sg_finish_rem_req(srp);
1075         srp = NULL;
1076         if (NULL == sfp->headrp) {
1077             SCSI_LOG_TIMEOUT(1,
1078                 printk("sg...bh: already closed, final cleanup\n"));
1079             sg_remove_sfp(sdp, sfp);
1080             sfp = NULL;
1081         }
1082     }
1083     else if (srp && srp->orphan) {
1084         if (sfp->keep_orphan)
1085             srp->sg_io_owned = 0;
1086         else {
1087             sg_finish_rem_req(srp);
1088             srp = NULL;
1089         }
1090     }
1091     if (sfp && srp) {
1092         /* Now wake up any sg_read() that is waiting for this packet. */
1093         wake_up_interruptible(&sfp->read_wait);
1094         kill_fasync(&sfp->async_qp, SIGPOLL, POLL_IN);
1095     }
1096 }
1097
1098 static struct file_operations sg_fops = {
1099         owner:          THIS_MODULE,
1100         read:           sg_read,
1101         write:          sg_write,
1102         poll:           sg_poll,
1103         ioctl:          sg_ioctl,
1104         open:           sg_open,
1105         release:        sg_release,
1106         fasync:         sg_fasync,
1107 };
1108
1109
1110 static int sg_detect(Scsi_Device * scsidp)
1111 {
1112     switch (scsidp->type) {
1113         case TYPE_DISK:
1114         case TYPE_MOD:
1115         case TYPE_ROM:
1116         case TYPE_WORM:
1117         case TYPE_TAPE: break;
1118         default:
1119         printk("Detected scsi generic sg%d at scsi%d,"
1120                 " channel %d, id %d, lun %d, type %d\n",
1121                sg_template.dev_noticed,
1122                scsidp->host->host_no, scsidp->channel,
1123                scsidp->id, scsidp->lun, scsidp->type);
1124     }
1125     sg_template.dev_noticed++;
1126     return 1;
1127 }
1128
1129 /* Driver initialization */
1130 static int sg_init()
1131 {
1132     static int sg_registered = 0;
1133     unsigned long iflags;
1134
1135     if ((sg_template.dev_noticed == 0) || sg_dev_arr)
1136         return 0;
1137
1138     write_lock_irqsave(&sg_dev_arr_lock, iflags);
1139     if(!sg_registered) {
1140         if (devfs_register_chrdev(SCSI_GENERIC_MAJOR,"sg",&sg_fops))
1141         {
1142             printk("Unable to get major %d for generic SCSI device\n",
1143                    SCSI_GENERIC_MAJOR);
1144             write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
1145             return 1;
1146         }
1147         sg_registered++;
1148     }
1149
1150     SCSI_LOG_TIMEOUT(3, printk("sg_init\n"));
1151     sg_template.dev_max = sg_template.dev_noticed + SG_DEV_ARR_LUMP;
1152     sg_dev_arr = (Sg_device **)kmalloc(sg_template.dev_max * 
1153                                         sizeof(Sg_device *), GFP_ATOMIC);
1154     if (NULL == sg_dev_arr) {
1155         printk("sg_init: no space for sg_dev_arr\n");
1156         write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
1157         return 1;
1158     }
1159     memset(sg_dev_arr, 0, sg_template.dev_max * sizeof(Sg_device *));
1160     write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
1161 #ifdef CONFIG_PROC_FS
1162     sg_proc_init();
1163 #endif  /* CONFIG_PROC_FS */
1164     return 0;
1165 }
1166
1167 #ifndef MODULE
1168 static int __init sg_def_reserved_size_setup(char *str)
1169 {
1170     int tmp;
1171
1172     if (get_option(&str, &tmp) == 1) {
1173         def_reserved_size = tmp;
1174         if (tmp >= 0)
1175             sg_big_buff = tmp;
1176         return 1;
1177     } else {
1178         printk("sg_def_reserved_size : usage sg_def_reserved_size=n "
1179                "(n could be 65536, 131072 or 262144)\n");
1180         return 0;
1181     }
1182 }
1183
1184 __setup("sg_def_reserved_size=", sg_def_reserved_size_setup);
1185 #endif
1186
1187
1188 static int sg_attach(Scsi_Device * scsidp)
1189 {
1190     Sg_device * sdp;
1191     unsigned long iflags;
1192     int k;
1193
1194     write_lock_irqsave(&sg_dev_arr_lock, iflags);
1195     if (sg_template.nr_dev >= sg_template.dev_max) { /* try to resize */
1196         Sg_device ** tmp_da;
1197         int tmp_dev_max = sg_template.nr_dev + SG_DEV_ARR_LUMP;
1198
1199         tmp_da = (Sg_device **)kmalloc(tmp_dev_max * 
1200                                         sizeof(Sg_device *), GFP_ATOMIC);
1201         if (NULL == tmp_da) {
1202             scsidp->attached--;
1203             write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
1204             printk("sg_attach: device array cannot be resized\n");
1205             return 1;
1206         }
1207         memset(tmp_da, 0, tmp_dev_max * sizeof(Sg_device *));
1208         memcpy(tmp_da, sg_dev_arr, sg_template.dev_max * sizeof(Sg_device *));
1209         kfree((char *)sg_dev_arr);
1210         sg_dev_arr = tmp_da;
1211         sg_template.dev_max = tmp_dev_max;
1212     }
1213
1214     for(k = 0; k < sg_template.dev_max; k++)
1215         if(! sg_dev_arr[k]) break;
1216     if(k < sg_template.dev_max)
1217         sdp = (Sg_device *)kmalloc(sizeof(Sg_device), GFP_ATOMIC);
1218     else
1219         sdp = NULL;
1220     if (NULL == sdp) {
1221         scsidp->attached--;
1222         write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
1223         printk("sg_attach: Sg_device cannot be allocated\n");
1224         return 1;
1225     }
1226
1227     SCSI_LOG_TIMEOUT(3, printk("sg_attach: dev=%d \n", k));
1228     sdp->device = scsidp;
1229     init_waitqueue_head(&sdp->o_excl_wait);
1230     sdp->headfp= NULL;
1231     sdp->exclude = 0;
1232     sdp->sgdebug = 0;
1233     sdp->detached = 0;
1234     sdp->sg_tablesize = scsidp->host ? scsidp->host->sg_tablesize : 0;
1235     sdp->i_rdev = MKDEV(SCSI_GENERIC_MAJOR, k);
1236     sdp->de = devfs_register (scsidp->de, "generic", DEVFS_FL_DEFAULT,
1237                              SCSI_GENERIC_MAJOR, k,
1238                              S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP,
1239                              &sg_fops, NULL);
1240     sg_template.nr_dev++;
1241     sg_dev_arr[k] = sdp;
1242     write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
1243     return 0;
1244 }
1245
1246 /* Called at 'finish' of init process, after all attaches */
1247 static void sg_finish(void)
1248 {
1249     SCSI_LOG_TIMEOUT(3, printk("sg_finish: dma_free_sectors=%u\n",
1250                      scsi_dma_free_sectors));
1251 }
1252
1253 static void sg_detach(Scsi_Device * scsidp)
1254 {
1255     Sg_device * sdp;
1256     unsigned long iflags;
1257     Sg_fd * sfp;
1258     Sg_request * srp;
1259     int k;
1260
1261     if (NULL == sg_dev_arr)
1262         return;
1263     write_lock_irqsave(&sg_dev_arr_lock, iflags);
1264     for (k = 0; k < sg_template.dev_max; k++) {
1265         sdp = sg_dev_arr[k];
1266         if ((NULL == sdp) || (sdp->device != scsidp))
1267             continue;   /* dirty but lowers nesting */
1268         if (sdp->headfp) {
1269             for (sfp = sdp->headfp; sfp; sfp = sfp->nextfp) {
1270                 /* no lock on request list here */
1271                 for (srp = sfp->headrp; srp; srp = srp->nextrp) {
1272                     if (! srp->done) {
1273                         write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
1274                         sg_shorten_timeout(srp->my_cmdp);
1275                         write_lock_irqsave(&sg_dev_arr_lock, iflags);
1276                 }
1277             }
1278             }
1279             write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
1280     SCSI_LOG_TIMEOUT(3, printk("sg_detach: dev=%d, dirty, sleep(3)\n", k));
1281             scsi_sleep(3); /* sleep 3 jiffies, hoping for timeout to go off */
1282             devfs_unregister (sdp->de);
1283             sdp->de = NULL;
1284             sdp->detached = 1;
1285             write_lock_irqsave(&sg_dev_arr_lock, iflags);
1286         }
1287         else {
1288             SCSI_LOG_TIMEOUT(3, printk("sg_detach: dev=%d\n", k));
1289             devfs_unregister (sdp->de);
1290             kfree((char *)sdp);
1291             sg_dev_arr[k] = NULL;
1292         }
1293         scsidp->attached--;
1294         sg_template.nr_dev--;
1295 /* avoid associated device /dev/sg? being incremented
1296  * each time module is inserted/removed , <dan@lectra.fr> */
1297         sg_template.dev_noticed--;
1298         break;
1299     }
1300     write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
1301     return;
1302 }
1303
1304 MODULE_AUTHOR("Douglas Gilbert");
1305 MODULE_DESCRIPTION("SCSI generic (sg) driver");
1306 MODULE_PARM(def_reserved_size, "i");
1307 MODULE_PARM_DESC(def_reserved_size, "size of buffer reserved for each fd");
1308
1309 static int __init init_sg(void) {
1310     if (def_reserved_size >= 0)
1311         sg_big_buff = def_reserved_size;
1312     sg_template.module = THIS_MODULE;
1313     return scsi_register_module(MODULE_SCSI_DEV, &sg_template);
1314 }
1315
1316 static void __exit exit_sg( void)
1317 {
1318 #ifdef CONFIG_PROC_FS
1319     sg_proc_cleanup();
1320 #endif  /* CONFIG_PROC_FS */
1321     scsi_unregister_module(MODULE_SCSI_DEV, &sg_template);
1322     devfs_unregister_chrdev(SCSI_GENERIC_MAJOR, "sg");
1323     if(sg_dev_arr != NULL) {
1324 /* Really worrying situation of writes still pending and get here */
1325 /* Strategy: shorten timeout on release + wait on detach ... */
1326         kfree((char *)sg_dev_arr);
1327         sg_dev_arr = NULL;
1328     }
1329     sg_template.dev_max = 0;
1330 }
1331
1332
1333 #if 0
1334 extern void scsi_times_out (Scsi_Cmnd * SCpnt);
1335 extern void scsi_old_times_out (Scsi_Cmnd * SCpnt);
1336 #endif
1337
1338 /* Can't see clean way to abort a command so shorten timeout to 1 jiffy */
1339 static void sg_shorten_timeout(Scsi_Request * srpnt)
1340 {
1341 #if 0 /* scsi_syms.c is very miserly about exported functions */
1342     scsi_delete_timer(scpnt);
1343     if (! scpnt)
1344         return;
1345     scpnt->timeout_per_command = 1; /* try 1 jiffy (perhaps 0 jiffies) */
1346     if (scpnt->host->hostt->use_new_eh_code)
1347         scsi_add_timer(scpnt, scpnt->timeout_per_command, scsi_times_out);
1348     else
1349         scsi_add_timer(scpnt, scpnt->timeout_per_command,
1350                        scsi_old_times_out);
1351 #else
1352     scsi_sleep(HZ); /* just sleep 1 second and hope ... */
1353 #endif
1354 }
1355
1356 static int sg_start_req(Sg_request * srp)
1357 {
1358     int res;
1359     Sg_fd * sfp = srp->parentfp;
1360     sg_io_hdr_t * hp = &srp->header;
1361     int dxfer_len = (int)hp->dxfer_len;
1362     int dxfer_dir = hp->dxfer_direction;
1363     Sg_scatter_hold * req_schp = &srp->data;
1364     Sg_scatter_hold * rsv_schp = &sfp->reserve;
1365
1366     SCSI_LOG_TIMEOUT(4, printk("sg_start_req: dxfer_len=%d\n", dxfer_len));
1367     if ((dxfer_len <= 0) || (dxfer_dir == SG_DXFER_NONE))
1368         return 0;
1369     if ((hp->flags & SG_FLAG_DIRECT_IO) && 
1370         (dxfer_dir != SG_DXFER_UNKNOWN) &&
1371         (0 == hp->iovec_count) &&
1372         (! sfp->parentdp->device->host->unchecked_isa_dma)) {
1373         res = sg_build_dir(srp, sfp, dxfer_len);
1374         if (res <= 0)   /* -ve -> error, 0 -> done, 1 -> try indirect */
1375             return res;
1376     }
1377     if ((! sg_res_in_use(sfp)) && (dxfer_len <= rsv_schp->bufflen)) {
1378         sg_link_reserve(sfp, srp, dxfer_len);
1379     }
1380     else {
1381         res = sg_build_indi(req_schp, sfp, dxfer_len);
1382         if (res) {
1383             sg_remove_scat(req_schp);
1384             return res;
1385         }
1386     }
1387     return 0;
1388 }
1389
1390 static void sg_finish_rem_req(Sg_request * srp)
1391 {
1392     Sg_fd * sfp = srp->parentfp;
1393     Sg_scatter_hold * req_schp = &srp->data;
1394
1395     SCSI_LOG_TIMEOUT(4, printk("sg_finish_rem_req: res_used=%d\n",
1396                                (int)srp->res_used));
1397     sg_unmap_and(&srp->data, 1);
1398     if (srp->res_used)
1399         sg_unlink_reserve(sfp, srp);
1400     else
1401         sg_remove_scat(req_schp);
1402     sg_remove_request(sfp, srp);
1403 }
1404
1405 static int sg_build_sgat(Sg_scatter_hold * schp, const Sg_fd * sfp)
1406 {
1407     int mem_src, ret_sz;
1408     int sg_bufflen = PAGE_SIZE;
1409     int elem_sz = sizeof(struct scatterlist) + sizeof(char);
1410     int mx_sc_elems = (sg_bufflen / elem_sz) - 1;
1411
1412     mem_src = SG_HEAP_KMAL;
1413     schp->buffer = (struct scatterlist *)sg_malloc(sfp, sg_bufflen,
1414                                                    &ret_sz, &mem_src);
1415     schp->buffer_mem_src = (char)mem_src;
1416     if (! schp->buffer)
1417         return -ENOMEM;
1418     else if (ret_sz != sg_bufflen) {
1419         sg_bufflen = ret_sz;
1420         mx_sc_elems = (sg_bufflen / elem_sz) - 1;
1421     }
1422     schp->sglist_len = sg_bufflen;
1423     memset(schp->buffer, 0, sg_bufflen);
1424     return mx_sc_elems; /* number of scat_gath elements allocated */
1425 }
1426
1427 static void sg_unmap_and(Sg_scatter_hold * schp, int free_also)
1428 {
1429 #ifdef SG_ALLOW_DIO
1430     if (schp && schp->kiobp) {
1431         if (schp->mapped) {
1432             unmap_kiobuf(schp->kiobp);
1433             schp->mapped = 0;
1434         }
1435         if (free_also) {
1436             free_kiovec(1, &schp->kiobp);
1437             schp->kiobp = NULL;
1438         }
1439     }
1440 #endif
1441 }
1442
1443 static int sg_build_dir(Sg_request * srp, Sg_fd * sfp, int dxfer_len)
1444 {
1445 #ifdef SG_ALLOW_DIO
1446     int res, k, split, offset, num, mx_sc_elems, rem_sz;
1447     struct kiobuf * kp;
1448     char * mem_src_arr;
1449     struct scatterlist * sclp;
1450     unsigned long addr, prev_addr;
1451     sg_io_hdr_t * hp = &srp->header;
1452     Sg_scatter_hold * schp = &srp->data;
1453     int sg_tablesize = sfp->parentdp->sg_tablesize;
1454
1455     res = alloc_kiovec(1, &schp->kiobp);
1456     if (0 != res) {
1457         SCSI_LOG_TIMEOUT(5, printk("sg_build_dir: alloc_kiovec res=%d\n", res));
1458         return 1;
1459     }
1460     res = map_user_kiobuf((SG_DXFER_TO_DEV == hp->dxfer_direction) ? 1 : 0,
1461                           schp->kiobp, (unsigned long)hp->dxferp, dxfer_len);
1462     if (0 != res) {
1463         SCSI_LOG_TIMEOUT(5,
1464                 printk("sg_build_dir: map_user_kiobuf res=%d\n", res));
1465         sg_unmap_and(schp, 1);
1466         return 1;
1467     }
1468     schp->mapped = 1;
1469     kp = schp->kiobp;
1470     prev_addr = (unsigned long) page_address(kp->maplist[0]);
1471     for (k = 1, split = 0; k < kp->nr_pages; ++k, prev_addr = addr) {
1472         addr = (unsigned long) page_address(kp->maplist[k]);
1473         if ((prev_addr + PAGE_SIZE) != addr) {
1474             split = k;
1475             break;
1476         }
1477     }
1478     if (! split) {
1479         schp->k_use_sg = 0;
1480         schp->buffer = page_address(kp->maplist[0]) + kp->offset;
1481         schp->bufflen = dxfer_len;
1482         schp->buffer_mem_src = SG_USER_MEM;
1483         schp->b_malloc_len = dxfer_len;
1484         hp->info |= SG_INFO_DIRECT_IO;
1485         return 0;
1486     }
1487     mx_sc_elems = sg_build_sgat(schp, sfp);
1488     if (mx_sc_elems <= 1) {
1489         sg_unmap_and(schp, 1);
1490         sg_remove_scat(schp);
1491         return 1;
1492     }
1493     mem_src_arr = schp->buffer + (mx_sc_elems * sizeof(struct scatterlist));
1494     for (k = 0, sclp = schp->buffer, rem_sz = dxfer_len;
1495          (k < sg_tablesize) && (rem_sz > 0) && (k < mx_sc_elems);
1496          ++k, ++sclp) {
1497         offset = (0 == k) ? kp->offset : 0;
1498         num = (rem_sz > (PAGE_SIZE - offset)) ? (PAGE_SIZE - offset) :
1499                                                 rem_sz;
1500         sclp->address = page_address(kp->maplist[k]) + offset;
1501         sclp->length = num;
1502         mem_src_arr[k] = SG_USER_MEM;
1503         rem_sz -= num;
1504         SCSI_LOG_TIMEOUT(5,
1505             printk("sg_build_dir: k=%d, a=0x%p, len=%d, ms=%d\n",
1506             k, sclp->address, num, mem_src_arr[k]));
1507     }
1508     schp->k_use_sg = k;
1509     SCSI_LOG_TIMEOUT(5,
1510         printk("sg_build_dir: k_use_sg=%d, rem_sz=%d\n", k, rem_sz));
1511     schp->bufflen = dxfer_len;
1512     if (rem_sz > 0) {   /* must have failed */
1513         sg_unmap_and(schp, 1);
1514         sg_remove_scat(schp);
1515         return 1;   /* out of scatter gather elements, try indirect */
1516     }
1517     hp->info |= SG_INFO_DIRECT_IO;
1518     return 0;
1519 #else
1520     return 1;
1521 #endif /* SG_ALLOW_DIO */
1522 }
1523
1524 static int sg_build_indi(Sg_scatter_hold * schp, Sg_fd * sfp, int buff_size)
1525 {
1526     int ret_sz, mem_src;
1527     int blk_size = buff_size;
1528     char * p = NULL;
1529
1530     if ((blk_size < 0) || (! sfp))
1531         return -EFAULT;
1532     if (0 == blk_size)
1533         ++blk_size;             /* don't know why */
1534 /* round request up to next highest SG_SECTOR_SZ byte boundary */
1535     blk_size = (blk_size + SG_SECTOR_MSK) & (~SG_SECTOR_MSK);
1536     SCSI_LOG_TIMEOUT(4, printk("sg_build_indi: buff_size=%d, blk_size=%d\n",
1537                                buff_size, blk_size));
1538     if (blk_size <= SG_SCATTER_SZ) {
1539         mem_src = SG_HEAP_PAGE;
1540         p = sg_malloc(sfp, blk_size, &ret_sz, &mem_src);
1541         if (! p)
1542             return -ENOMEM;
1543         if (blk_size == ret_sz) { /* got it on the first attempt */
1544             schp->k_use_sg = 0;
1545             schp->buffer = p;
1546             schp->bufflen = blk_size;
1547             schp->buffer_mem_src = (char)mem_src;
1548             schp->b_malloc_len = blk_size;
1549             return 0;
1550         }
1551     }
1552     else {
1553         mem_src = SG_HEAP_PAGE;
1554         p = sg_malloc(sfp, SG_SCATTER_SZ, &ret_sz, &mem_src);
1555         if (! p)
1556             return -ENOMEM;
1557     }
1558 /* Want some local declarations, so start new block ... */
1559     {   /* lets try and build a scatter gather list */
1560         struct scatterlist * sclp;
1561         int k, rem_sz, num;
1562         int mx_sc_elems;
1563         int sg_tablesize = sfp->parentdp->sg_tablesize;
1564         int first = 1;
1565         char * mem_src_arr;
1566
1567         /* N.B. ret_sz and mem_src carried into this block ... */
1568         mx_sc_elems = sg_build_sgat(schp, sfp);
1569         if (mx_sc_elems < 0)
1570             return mx_sc_elems; /* most likely -ENOMEM */
1571         mem_src_arr = schp->buffer +
1572                       (mx_sc_elems * sizeof(struct scatterlist));
1573
1574         for (k = 0, sclp = schp->buffer, rem_sz = blk_size;
1575              (k < sg_tablesize) && (rem_sz > 0) && (k < mx_sc_elems);
1576              ++k, rem_sz -= ret_sz, ++sclp) {
1577             if (first)
1578                 first = 0;
1579             else {
1580                 num = (rem_sz > SG_SCATTER_SZ) ? SG_SCATTER_SZ : rem_sz;
1581                 mem_src = SG_HEAP_PAGE;
1582                 p = sg_malloc(sfp, num, &ret_sz, &mem_src);
1583                 if (! p)
1584                     break;
1585             }
1586             sclp->address = p;
1587             sclp->length = ret_sz;
1588             mem_src_arr[k] = mem_src;
1589
1590             SCSI_LOG_TIMEOUT(5,
1591                 printk("sg_build_build: k=%d, a=0x%p, len=%d, ms=%d\n",
1592                 k, sclp->address, ret_sz, mem_src));
1593         } /* end of for loop */
1594         schp->k_use_sg = k;
1595         SCSI_LOG_TIMEOUT(5,
1596             printk("sg_build_indi: k_use_sg=%d, rem_sz=%d\n", k, rem_sz));
1597         schp->bufflen = blk_size;
1598         if (rem_sz > 0)   /* must have failed */
1599             return -ENOMEM;
1600     }
1601     return 0;
1602 }
1603
1604 static int sg_write_xfer(Sg_request * srp)
1605 {
1606     sg_io_hdr_t * hp = &srp->header;
1607     Sg_scatter_hold * schp = &srp->data;
1608     int num_xfer = 0;
1609     int j, k, onum, usglen, ksglen, res, ok;
1610     int iovec_count = (int)hp->iovec_count;
1611     int dxfer_dir = hp->dxfer_direction;
1612     unsigned char * p;
1613     unsigned char * up;
1614     int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
1615
1616     if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_TO_DEV == dxfer_dir) ||
1617         (SG_DXFER_TO_FROM_DEV == dxfer_dir)) {
1618         num_xfer = (int)(new_interface ?  hp->dxfer_len : hp->flags);
1619         if (schp->bufflen < num_xfer)
1620             num_xfer = schp->bufflen;
1621     }
1622     if ((num_xfer <= 0) || (new_interface && (SG_FLAG_NO_DXFER & hp->flags)))
1623         return 0;
1624
1625     SCSI_LOG_TIMEOUT(4,
1626          printk("sg_write_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
1627                 num_xfer, iovec_count, schp->k_use_sg));
1628     if (iovec_count) {
1629         onum = iovec_count;
1630         if ((k = verify_area(VERIFY_READ, hp->dxferp,
1631                              size_sg_iovec * onum)))
1632             return k;
1633     }
1634     else
1635         onum = 1;
1636
1637     if (0 == schp->k_use_sg) {  /* kernel has single buffer */
1638         if (SG_USER_MEM != schp->buffer_mem_src) { /* else nothing to do */
1639
1640             for (j = 0, p = schp->buffer; j < onum; ++j) {
1641                 res = sg_u_iovec(hp, iovec_count, j, 1, &usglen, &up);
1642                 if (res) return res;
1643                 usglen = (num_xfer > usglen) ? usglen : num_xfer;
1644                 __copy_from_user(p, up, usglen);
1645                 p += usglen;
1646                 num_xfer -= usglen;
1647                 if (num_xfer <= 0)
1648                     return 0;
1649             }
1650         }
1651     }
1652     else {      /* kernel using scatter gather list */
1653         struct scatterlist * sclp = (struct scatterlist *)schp->buffer;
1654         char * mem_src_arr = sg_get_sgat_msa(schp);
1655         ksglen = (int)sclp->length;
1656         p = sclp->address;
1657
1658         for (j = 0, k = 0; j < onum; ++j) {
1659             res = sg_u_iovec(hp, iovec_count, j, 1, &usglen, &up);
1660             if (res) return res;
1661
1662             for (; (k < schp->k_use_sg) && p;
1663                  ++k, ++sclp, ksglen = (int)sclp->length, p = sclp->address) {
1664                 ok = (SG_USER_MEM != mem_src_arr[k]);
1665                 if (usglen <= 0)
1666                     break;
1667                 if (ksglen > usglen) {
1668                     if (usglen >= num_xfer) {
1669                         if (ok) __copy_from_user(p, up, num_xfer);
1670                         return 0;
1671                     }
1672                     if (ok) __copy_from_user(p, up, usglen);
1673                     p += usglen;
1674                     ksglen -= usglen;
1675                     break;
1676                 }
1677                 else {
1678                     if (ksglen >= num_xfer) {
1679                         if (ok) __copy_from_user(p, up, num_xfer);
1680                         return 0;
1681                     }
1682                     if (ok) __copy_from_user(p, up, ksglen);
1683                     up += ksglen;
1684                     usglen -= ksglen;
1685                 }
1686             }
1687         }
1688     }
1689     return 0;
1690 }
1691
1692 static int sg_u_iovec(sg_io_hdr_t * hp, int sg_num, int ind,
1693                       int wr_xf, int * countp, unsigned char ** up)
1694 {
1695     int num_xfer = (int)hp->dxfer_len;
1696     unsigned char * p;
1697     int count, k;
1698     sg_iovec_t u_iovec;
1699
1700     if (0 == sg_num) {
1701         p = (unsigned char *)hp->dxferp;
1702         if (wr_xf && ('\0' == hp->interface_id))
1703             count = (int)hp->flags; /* holds "old" input_size */
1704         else
1705             count = num_xfer;
1706     }
1707     else {
1708         __copy_from_user(&u_iovec,
1709                          (unsigned char *)hp->dxferp + (ind * size_sg_iovec),
1710                          size_sg_iovec);
1711         p = (unsigned char *)u_iovec.iov_base;
1712         count = (int)u_iovec.iov_len;
1713     }
1714     if ((k = verify_area(wr_xf ? VERIFY_READ : VERIFY_WRITE, p, count)))
1715         return k;
1716     if (up) *up = p;
1717     if (countp) *countp = count;
1718     return 0;
1719 }
1720
1721 static char * sg_get_sgat_msa(Sg_scatter_hold * schp)
1722 {
1723     int elem_sz = sizeof(struct scatterlist) + sizeof(char);
1724     int mx_sc_elems = (schp->sglist_len / elem_sz) - 1;
1725     return schp->buffer + (sizeof(struct scatterlist) * mx_sc_elems);
1726 }
1727
1728 static void sg_remove_scat(Sg_scatter_hold * schp)
1729 {
1730     SCSI_LOG_TIMEOUT(4, printk("sg_remove_scat: k_use_sg=%d\n",
1731                                schp->k_use_sg));
1732     if (schp->buffer && schp->sglist_len) {
1733         int k, mem_src;
1734         struct scatterlist * sclp = (struct scatterlist *)schp->buffer;
1735         char * mem_src_arr = sg_get_sgat_msa(schp);
1736
1737         for (k = 0; (k < schp->k_use_sg) && sclp->address; ++k, ++sclp) {
1738             mem_src = mem_src_arr[k];
1739             SCSI_LOG_TIMEOUT(5,
1740                 printk("sg_remove_scat: k=%d, a=0x%p, len=%d, ms=%d\n",
1741                        k, sclp->address, sclp->length, mem_src));
1742             sg_free(sclp->address, sclp->length, mem_src);
1743             sclp->address = NULL;
1744             sclp->length = 0;
1745         }
1746         sg_free(schp->buffer, schp->sglist_len, schp->buffer_mem_src);
1747     }
1748     else if (schp->buffer)
1749         sg_free(schp->buffer, schp->b_malloc_len, schp->buffer_mem_src);
1750     memset(schp, 0, sizeof(*schp));
1751 }
1752
1753 static int sg_read_xfer(Sg_request * srp)
1754 {
1755     sg_io_hdr_t * hp = &srp->header;
1756     Sg_scatter_hold * schp = &srp->data;
1757     int num_xfer = 0;
1758     int j, k, onum, usglen, ksglen, res, ok;
1759     int iovec_count = (int)hp->iovec_count;
1760     int dxfer_dir = hp->dxfer_direction;
1761     unsigned char * p;
1762     unsigned char * up;
1763     int new_interface = ('\0' == hp->interface_id) ? 0 : 1;
1764
1765     if ((SG_DXFER_UNKNOWN == dxfer_dir) || (SG_DXFER_FROM_DEV == dxfer_dir) ||
1766         (SG_DXFER_TO_FROM_DEV == dxfer_dir)) {
1767         num_xfer =  hp->dxfer_len;
1768         if (schp->bufflen < num_xfer)
1769             num_xfer = schp->bufflen;
1770     }
1771     if ((num_xfer <= 0) || (new_interface && (SG_FLAG_NO_DXFER & hp->flags)))
1772         return 0;
1773
1774     SCSI_LOG_TIMEOUT(4,
1775          printk("sg_read_xfer: num_xfer=%d, iovec_count=%d, k_use_sg=%d\n",
1776                 num_xfer, iovec_count, schp->k_use_sg));
1777     if (iovec_count) {
1778         onum = iovec_count;
1779         if ((k = verify_area(VERIFY_READ, hp->dxferp,
1780                              size_sg_iovec * onum)))
1781             return k;
1782     }
1783     else
1784         onum = 1;
1785
1786     if (0 == schp->k_use_sg) {  /* kernel has single buffer */
1787         if (SG_USER_MEM != schp->buffer_mem_src) { /* else nothing to do */
1788
1789             for (j = 0, p = schp->buffer; j < onum; ++j) {
1790                 res = sg_u_iovec(hp, iovec_count, j, 0, &usglen, &up);
1791                 if (res) return res;
1792                 usglen = (num_xfer > usglen) ? usglen : num_xfer;
1793                 __copy_to_user(up, p, usglen);
1794                 p += usglen;
1795                 num_xfer -= usglen;
1796                 if (num_xfer <= 0)
1797                     return 0;
1798             }
1799         }
1800     }
1801     else {      /* kernel using scatter gather list */
1802         struct scatterlist * sclp = (struct scatterlist *)schp->buffer;
1803         char * mem_src_arr = sg_get_sgat_msa(schp);
1804         ksglen = (int)sclp->length;
1805         p = sclp->address;
1806
1807         for (j = 0, k = 0; j < onum; ++j) {
1808             res = sg_u_iovec(hp, iovec_count, j, 0, &usglen, &up);
1809             if (res) return res;
1810
1811             for (; (k < schp->k_use_sg) && p;
1812                  ++k, ++sclp, ksglen = (int)sclp->length, p = sclp->address) {
1813                 ok = (SG_USER_MEM != mem_src_arr[k]);
1814                 if (usglen <= 0)
1815                     break;
1816                 if (ksglen > usglen) {
1817                     if (usglen >= num_xfer) {
1818                         if (ok) __copy_to_user(up, p, num_xfer);
1819                         return 0;
1820                     }
1821                     if (ok) __copy_to_user(up, p, usglen);
1822                     p += usglen;
1823                     ksglen -= usglen;
1824                     break;
1825                 }
1826                 else {
1827                     if (ksglen >= num_xfer) {
1828                         if (ok) __copy_to_user(up, p, num_xfer);
1829                         return 0;
1830                     }
1831                     if (ok) __copy_to_user(up, p, ksglen);
1832                     up += ksglen;
1833                     usglen -= ksglen;
1834                 }
1835             }
1836         }
1837     }
1838     return 0;
1839 }
1840
1841 static void sg_read_oxfer(Sg_request * srp, char * outp, int num_read_xfer)
1842 {
1843     Sg_scatter_hold * schp = &srp->data;
1844
1845     SCSI_LOG_TIMEOUT(4, printk("sg_read_oxfer: num_read_xfer=%d\n",
1846                                num_read_xfer));
1847     if ((! outp) || (num_read_xfer <= 0))
1848         return;
1849     if(schp->k_use_sg > 0) {
1850         int k, num;
1851         struct scatterlist * sclp = (struct scatterlist *)schp->buffer;
1852
1853         for (k = 0; (k < schp->k_use_sg) && sclp->address; ++k, ++sclp) {
1854             num = (int)sclp->length;
1855             if (num > num_read_xfer) {
1856                 __copy_to_user(outp, sclp->address, num_read_xfer);
1857                 break;
1858             }
1859             else {
1860                 __copy_to_user(outp, sclp->address, num);
1861                 num_read_xfer -= num;
1862                 if (num_read_xfer <= 0)
1863                     break;
1864                 outp += num;
1865             }
1866         }
1867     }
1868     else
1869         __copy_to_user(outp, schp->buffer, num_read_xfer);
1870 }
1871
1872 static void sg_build_reserve(Sg_fd * sfp, int req_size)
1873 {
1874     Sg_scatter_hold * schp = &sfp->reserve;
1875
1876     SCSI_LOG_TIMEOUT(4, printk("sg_build_reserve: req_size=%d\n", req_size));
1877     do {
1878         if (req_size < PAGE_SIZE)
1879             req_size = PAGE_SIZE;
1880         if (0 == sg_build_indi(schp, sfp, req_size))
1881             return;
1882         else
1883             sg_remove_scat(schp);
1884         req_size >>= 1; /* divide by 2 */
1885     } while (req_size >  (PAGE_SIZE / 2));
1886 }
1887
1888 static void sg_link_reserve(Sg_fd * sfp, Sg_request * srp, int size)
1889 {
1890     Sg_scatter_hold * req_schp = &srp->data;
1891     Sg_scatter_hold * rsv_schp = &sfp->reserve;
1892
1893     srp->res_used = 1;
1894     SCSI_LOG_TIMEOUT(4, printk("sg_link_reserve: size=%d\n", size));
1895     size = (size + 1) & (~1);    /* round to even for aha1542 */
1896     if (rsv_schp->k_use_sg > 0) {
1897         int k, num;
1898         int rem = size;
1899         struct scatterlist * sclp = (struct scatterlist *)rsv_schp->buffer;
1900
1901         for (k = 0; k < rsv_schp->k_use_sg; ++k, ++sclp) {
1902             num = (int)sclp->length;
1903             if (rem <= num) {
1904                 if (0 == k) {
1905                     req_schp->k_use_sg = 0;
1906                     req_schp->buffer = sclp->address;
1907                 }
1908                 else {
1909                     sfp->save_scat_len = num;
1910                     sclp->length = (unsigned)rem;
1911                     req_schp->k_use_sg = k + 1;
1912                     req_schp->sglist_len = rsv_schp->sglist_len;
1913                     req_schp->buffer = rsv_schp->buffer;
1914                 }
1915                 req_schp->bufflen = size;
1916                 req_schp->buffer_mem_src = rsv_schp->buffer_mem_src;
1917                 req_schp->b_malloc_len = rsv_schp->b_malloc_len;
1918                 break;
1919             }
1920             else
1921                 rem -= num;
1922         }
1923         if (k >= rsv_schp->k_use_sg)
1924             SCSI_LOG_TIMEOUT(1, printk("sg_link_reserve: BAD size\n"));
1925     }
1926     else {
1927         req_schp->k_use_sg = 0;
1928         req_schp->bufflen = size;
1929         req_schp->buffer = rsv_schp->buffer;
1930         req_schp->buffer_mem_src = rsv_schp->buffer_mem_src;
1931         req_schp->b_malloc_len = rsv_schp->b_malloc_len;
1932     }
1933 }
1934
1935 static void sg_unlink_reserve(Sg_fd * sfp, Sg_request * srp)
1936 {
1937     Sg_scatter_hold * req_schp = &srp->data;
1938     Sg_scatter_hold * rsv_schp = &sfp->reserve;
1939
1940     SCSI_LOG_TIMEOUT(4, printk("sg_unlink_reserve: req->k_use_sg=%d\n",
1941                                (int)req_schp->k_use_sg));
1942     if ((rsv_schp->k_use_sg > 0) && (req_schp->k_use_sg > 0)) {
1943         struct scatterlist * sclp = (struct scatterlist *)rsv_schp->buffer;
1944
1945         if (sfp->save_scat_len > 0)
1946             (sclp + (req_schp->k_use_sg - 1))->length =
1947                                         (unsigned)sfp->save_scat_len;
1948         else
1949             SCSI_LOG_TIMEOUT(1, printk(
1950                         "sg_unlink_reserve: BAD save_scat_len\n"));
1951     }
1952     req_schp->k_use_sg = 0;
1953     req_schp->bufflen = 0;
1954     req_schp->buffer = NULL;
1955     req_schp->sglist_len = 0;
1956     sfp->save_scat_len = 0;
1957     srp->res_used = 0;
1958 }
1959
1960 static Sg_request * sg_get_rq_mark(Sg_fd * sfp, int pack_id)
1961 {
1962     Sg_request * resp;
1963     unsigned long iflags;
1964
1965     write_lock_irqsave(&sfp->rq_list_lock, iflags);
1966     for (resp = sfp->headrp; resp; resp = resp->nextrp) { 
1967         /* look for requests that are ready + not SG_IO owned */
1968         if ((1 == resp->done) && (! resp->sg_io_owned) &&
1969             ((-1 == pack_id) || (resp->header.pack_id == pack_id))) {
1970             resp->done = 2;   /* guard against other readers */
1971             break;
1972         }
1973     }
1974     write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
1975     return resp;
1976 }
1977
1978 #ifdef CONFIG_PROC_FS
1979 static Sg_request * sg_get_nth_request(Sg_fd * sfp, int nth)
1980 {
1981     Sg_request * resp;
1982     unsigned long iflags;
1983     int k;
1984
1985     read_lock_irqsave(&sfp->rq_list_lock, iflags);
1986     for (k = 0, resp = sfp->headrp; resp && (k < nth); 
1987          ++k, resp = resp->nextrp)
1988         ;
1989     read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
1990     return resp;
1991 }
1992 #endif
1993
1994 /* always adds to end of list */
1995 static Sg_request * sg_add_request(Sg_fd * sfp)
1996 {
1997     int k;
1998     unsigned long iflags;
1999     Sg_request * resp;
2000     Sg_request * rp =  sfp->req_arr;
2001
2002     write_lock_irqsave(&sfp->rq_list_lock, iflags);
2003     resp = sfp->headrp;
2004     if (! resp) {
2005         memset(rp, 0, sizeof(Sg_request));
2006         rp->parentfp = sfp;
2007         resp = rp;
2008         sfp->headrp = resp;
2009     }
2010     else {
2011         if (0 == sfp->cmd_q)
2012             resp = NULL;   /* command queuing disallowed */
2013         else {
2014             for (k = 0; k < SG_MAX_QUEUE; ++k, ++rp) {
2015                 if (! rp->parentfp)
2016                     break;
2017             }
2018             if (k < SG_MAX_QUEUE) {
2019                 memset(rp, 0, sizeof(Sg_request));
2020                 rp->parentfp = sfp;
2021                 while (resp->nextrp) 
2022                     resp = resp->nextrp;
2023                 resp->nextrp = rp;
2024                 resp = rp;
2025             }
2026             else
2027                 resp = NULL;
2028         }
2029     }
2030     if (resp) {
2031         resp->nextrp = NULL;
2032         resp->header.duration = jiffies;
2033         resp->my_cmdp = NULL;
2034         resp->data.kiobp = NULL;
2035     }
2036     write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
2037     return resp;
2038 }
2039
2040 /* Return of 1 for found; 0 for not found */
2041 static int sg_remove_request(Sg_fd * sfp, Sg_request * srp)
2042 {
2043     Sg_request * prev_rp;
2044     Sg_request * rp;
2045     unsigned long iflags;
2046     int res = 0;
2047
2048     if ((! sfp) || (! srp) || (! sfp->headrp))
2049         return res;
2050     write_lock_irqsave(&sfp->rq_list_lock, iflags);
2051     prev_rp = sfp->headrp;
2052     if (srp == prev_rp) {
2053         sfp->headrp = prev_rp->nextrp;
2054         prev_rp->parentfp = NULL;
2055         res = 1;
2056     }
2057     else {
2058         while ((rp = prev_rp->nextrp)) {
2059             if (srp == rp) {
2060                 prev_rp->nextrp = rp->nextrp;
2061                 rp->parentfp = NULL;
2062                 res = 1;
2063                 break;
2064             }
2065             prev_rp = rp;
2066         }
2067     }
2068     write_unlock_irqrestore(&sfp->rq_list_lock, iflags);
2069     return res;
2070 }
2071
2072 #ifdef CONFIG_PROC_FS
2073 static Sg_fd * sg_get_nth_sfp(Sg_device * sdp, int nth)
2074 {
2075     Sg_fd * resp;
2076     unsigned long iflags;
2077     int k;
2078
2079     read_lock_irqsave(&sg_dev_arr_lock, iflags);
2080     for (k = 0, resp = sdp->headfp; resp && (k < nth); 
2081          ++k, resp = resp->nextfp)
2082         ;
2083     read_unlock_irqrestore(&sg_dev_arr_lock, iflags);
2084     return resp;
2085 }
2086 #endif
2087
2088 static Sg_fd * sg_add_sfp(Sg_device * sdp, int dev)
2089 {
2090     Sg_fd * sfp;
2091     unsigned long iflags;
2092
2093     sfp = (Sg_fd *)sg_low_malloc(sizeof(Sg_fd), 0, SG_HEAP_KMAL, 0);
2094     if (! sfp)
2095         return NULL;
2096     memset(sfp, 0, sizeof(Sg_fd));
2097     sfp->fd_mem_src = SG_HEAP_KMAL;
2098     init_waitqueue_head(&sfp->read_wait);
2099     sfp->rq_list_lock = RW_LOCK_UNLOCKED;
2100
2101     sfp->timeout = SG_DEFAULT_TIMEOUT;
2102     sfp->force_packid = SG_DEF_FORCE_PACK_ID;
2103     sfp->low_dma = (SG_DEF_FORCE_LOW_DMA == 0) ?
2104                    sdp->device->host->unchecked_isa_dma : 1;
2105     sfp->cmd_q = SG_DEF_COMMAND_Q;
2106     sfp->keep_orphan = SG_DEF_KEEP_ORPHAN;
2107     sfp->parentdp = sdp;
2108     write_lock_irqsave(&sg_dev_arr_lock, iflags);
2109     if (! sdp->headfp)
2110         sdp->headfp = sfp;
2111     else {    /* add to tail of existing list */
2112         Sg_fd * pfp = sdp->headfp;
2113         while (pfp->nextfp)
2114             pfp = pfp->nextfp;
2115         pfp->nextfp = sfp;
2116     }
2117     write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
2118     SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp: sfp=0x%p, m_s=%d\n",
2119                                sfp, (int)sfp->fd_mem_src));
2120     sg_build_reserve(sfp, sg_big_buff);
2121     SCSI_LOG_TIMEOUT(3, printk("sg_add_sfp:   bufflen=%d, k_use_sg=%d\n",
2122                            sfp->reserve.bufflen, sfp->reserve.k_use_sg));
2123     return sfp;
2124 }
2125
2126 static int sg_remove_sfp(Sg_device * sdp, Sg_fd * sfp)
2127 {
2128     Sg_request * srp;
2129     Sg_request * tsrp;
2130     int dirty = 0;
2131     int res = 0;
2132
2133     srp = sfp->headrp;
2134     if (srp) {
2135         while (srp) {
2136             tsrp = srp->nextrp;
2137             if (srp->done)
2138                 sg_finish_rem_req(srp);
2139             else
2140                 ++dirty;
2141             srp = tsrp;
2142         }
2143     }
2144     if (0 == dirty) {
2145         Sg_fd * fp;
2146         Sg_fd * prev_fp;
2147         unsigned long iflags;
2148
2149         write_lock_irqsave(&sg_dev_arr_lock, iflags);
2150         prev_fp =  sdp->headfp;
2151         if (sfp == prev_fp)
2152             sdp->headfp = prev_fp->nextfp;
2153         else {
2154             while ((fp = prev_fp->nextfp)) {
2155                 if (sfp == fp) {
2156                     prev_fp->nextfp = fp->nextfp;
2157                     break;
2158                 }
2159                 prev_fp = fp;
2160             }
2161         }
2162         write_unlock_irqrestore(&sg_dev_arr_lock, iflags);
2163         if (sfp->reserve.bufflen > 0) {
2164 SCSI_LOG_TIMEOUT(6, printk("sg_remove_sfp:    bufflen=%d, k_use_sg=%d\n",
2165                  (int)sfp->reserve.bufflen, (int)sfp->reserve.k_use_sg));
2166             sg_remove_scat(&sfp->reserve);
2167         }
2168         sfp->parentdp = NULL;
2169         SCSI_LOG_TIMEOUT(6, printk("sg_remove_sfp:    sfp=0x%p\n", sfp));
2170         sg_low_free((char *)sfp, sizeof(Sg_fd), sfp->fd_mem_src);
2171         if (sdp->detached && (NULL == sdp->headfp)) {
2172             int k, maxd;
2173
2174             maxd = sg_template.dev_max;
2175             for (k = 0; k < maxd; ++k) {
2176                 if (sdp == sg_dev_arr[k])
2177                     break;
2178             }
2179             if (k < maxd)
2180                 sg_dev_arr[k] = NULL;
2181             kfree((char *)sdp);
2182         }
2183         res = 1;
2184     }
2185     else {
2186         sfp->closed = 1; /* flag dirty state on this fd */
2187         SCSI_LOG_TIMEOUT(1, printk(
2188           "sg_remove_sfp: worrisome, %d writes pending\n", dirty));
2189     }
2190     return res;
2191 }
2192
2193 static int sg_res_in_use(Sg_fd * sfp)
2194 {
2195     const Sg_request * srp;
2196     unsigned long iflags;
2197
2198     read_lock_irqsave(&sfp->rq_list_lock, iflags);
2199     for (srp = sfp->headrp; srp; srp = srp->nextrp)
2200         if (srp->res_used) break;
2201     read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
2202     return srp ? 1 : 0;
2203 }
2204
2205 static int sg_dio_in_use(Sg_fd * sfp)
2206 {
2207     const Sg_request * srp;
2208     unsigned long iflags;
2209
2210     read_lock_irqsave(&sfp->rq_list_lock, iflags);
2211     for (srp = sfp->headrp; srp; srp = srp->nextrp)
2212         if ((! srp->done) && srp->data.kiobp) break;
2213     read_unlock_irqrestore(&sfp->rq_list_lock, iflags);
2214     return srp ? 1 : 0;
2215 }
2216
2217 /* If retSzp==NULL want exact size or fail */
2218 /* sg_low_malloc() should always be called from a process context allowing
2219    GFP_KERNEL to be used instead of GFP_ATOMIC */
2220 static char * sg_low_malloc(int rqSz, int lowDma, int mem_src, int * retSzp)
2221 {
2222     char * resp = NULL;
2223     int page_mask = lowDma ? (GFP_KERNEL | GFP_DMA) : GFP_KERNEL;
2224
2225     if (rqSz <= 0)
2226         return resp;
2227     if (SG_HEAP_KMAL == mem_src) {
2228         page_mask = lowDma ? (GFP_ATOMIC | GFP_DMA) : GFP_ATOMIC;
2229         /* Seen kmalloc(..,GFP_KERNEL) hang for 40 secs! */
2230         resp = kmalloc(rqSz, page_mask);
2231         if (resp && retSzp) *retSzp = rqSz;
2232         return resp;
2233     }
2234     if (SG_HEAP_POOL == mem_src) {
2235         int num_sect = rqSz / SG_SECTOR_SZ;
2236
2237         if (0 != (rqSz & SG_SECTOR_MSK)) {
2238             if (! retSzp)
2239                 return resp;
2240             ++num_sect;
2241             rqSz = num_sect * SG_SECTOR_SZ;
2242         }
2243         while (num_sect > 0) {
2244             if ((num_sect <= sg_pool_secs_avail) &&
2245                 (scsi_dma_free_sectors > (SG_LOW_POOL_THRESHHOLD + num_sect))) {
2246                 resp = scsi_malloc(rqSz);
2247                 if (resp) {
2248                     if (retSzp) *retSzp = rqSz;
2249                     sg_pool_secs_avail -= num_sect;
2250                     return resp;
2251                 }
2252             }
2253             if (! retSzp)
2254                 return resp;
2255             num_sect /= 2;      /* try half as many */
2256             rqSz = num_sect * SG_SECTOR_SZ;
2257         }
2258     }
2259     else if (SG_HEAP_PAGE == mem_src) {
2260         int order, a_size;
2261         int resSz = rqSz;
2262
2263         for (order = 0, a_size = PAGE_SIZE;
2264              a_size < rqSz; order++, a_size <<= 1)
2265             ;
2266         resp = (char *)__get_free_pages(page_mask, order);
2267         while ((! resp) && order && retSzp) {
2268             --order;
2269             a_size >>= 1;   /* divide by 2, until PAGE_SIZE */
2270             resp = (char *)__get_free_pages(page_mask, order); /* try half */
2271             resSz = a_size;
2272         }
2273         if (retSzp) *retSzp = resSz;
2274     }
2275     else
2276         printk("sg_low_malloc: bad mem_src=%d, rqSz=%df\n", mem_src, rqSz);
2277     return resp;
2278 }
2279
2280 static char * sg_malloc(const Sg_fd * sfp, int size, int * retSzp,
2281                         int * mem_srcp)
2282 {
2283     char * resp = NULL;
2284
2285     if (retSzp) *retSzp = size;
2286     if (size <= 0)
2287         ;
2288     else {
2289         int low_dma = sfp->low_dma;
2290         int l_ms = -1;  /* invalid value */
2291
2292         switch (*mem_srcp)
2293         {
2294         case SG_HEAP_PAGE:
2295             l_ms = (size < PAGE_SIZE) ? SG_HEAP_POOL : SG_HEAP_PAGE;
2296             resp = sg_low_malloc(size, low_dma, l_ms, 0);
2297             if (resp)
2298                 break;
2299             resp = sg_low_malloc(size, low_dma, l_ms, &size);
2300             if (! resp) {
2301                 l_ms = (SG_HEAP_POOL == l_ms) ? SG_HEAP_PAGE : SG_HEAP_POOL;
2302                 resp = sg_low_malloc(size, low_dma, l_ms, &size);
2303                 if (! resp) {
2304                     l_ms = SG_HEAP_KMAL;
2305                     resp = sg_low_malloc(size, low_dma, l_ms, &size);
2306                 }
2307             }
2308             if (resp && retSzp) *retSzp = size;
2309             break;
2310         case SG_HEAP_KMAL:
2311             l_ms = SG_HEAP_PAGE;
2312             resp = sg_low_malloc(size, low_dma, l_ms, 0);
2313             if (resp)
2314                 break;
2315             l_ms = SG_HEAP_POOL;
2316             resp = sg_low_malloc(size, low_dma, l_ms, &size);
2317             if (resp && retSzp) *retSzp = size;
2318             break;
2319         default:
2320             SCSI_LOG_TIMEOUT(1, printk("sg_malloc: bad ms=%d\n", *mem_srcp));
2321             break;
2322         }
2323         if (resp) *mem_srcp = l_ms;
2324     }
2325     SCSI_LOG_TIMEOUT(6, printk("sg_malloc: size=%d, ms=%d, ret=0x%p\n",
2326                                size, *mem_srcp, resp));
2327     return resp;
2328 }
2329
2330 static void sg_low_free(char * buff, int size, int mem_src)
2331 {
2332     if (! buff) return;
2333     switch (mem_src) {
2334     case SG_HEAP_POOL:
2335         {
2336             int num_sect = size / SG_SECTOR_SZ;
2337
2338             scsi_free(buff, size);
2339             sg_pool_secs_avail += num_sect;
2340         }
2341         break;
2342     case SG_HEAP_KMAL:
2343         kfree(buff);    /* size not used */
2344         break;
2345     case SG_HEAP_PAGE:
2346         {
2347             int order, a_size;
2348             for (order = 0, a_size = PAGE_SIZE;
2349                  a_size < size; order++, a_size <<= 1)
2350                 ;
2351             free_pages((unsigned long)buff, order);
2352         }
2353         break;
2354     case SG_USER_MEM:
2355         break; /* nothing to do */
2356     default:
2357         printk("sg_low_free: bad mem_src=%d, buff=0x%p, rqSz=%df\n",
2358                mem_src, buff, size);
2359         break;
2360     }
2361 }
2362
2363 static void sg_free(char * buff, int size, int mem_src)
2364 {
2365     SCSI_LOG_TIMEOUT(6,
2366         printk("sg_free: buff=0x%p, size=%d\n", buff, size));
2367     if ((! buff) || (size <= 0))
2368         ;
2369     else
2370         sg_low_free(buff, size, mem_src);
2371 }
2372
2373 static void sg_clr_srpnt(Scsi_Request * SRpnt)
2374 {
2375     SRpnt->sr_use_sg = 0;
2376     SRpnt->sr_sglist_len = 0;
2377     SRpnt->sr_bufflen = 0;
2378     SRpnt->sr_buffer = NULL;
2379     SRpnt->sr_underflow = 0;
2380     SRpnt->sr_request.rq_dev = MKDEV(0, 0);  /* "sg" _disowns_ command blk */
2381 }
2382
2383 static int sg_ms_to_jif(unsigned int msecs)
2384 {
2385     if ((UINT_MAX / 2U) < msecs)
2386         return INT_MAX;      /* special case, set largest possible */
2387     else
2388         return ((int)msecs < (INT_MAX / 1000)) ? (((int)msecs * HZ) / 1000)
2389                                                : (((int)msecs / 1000) * HZ);
2390 }
2391
2392 static unsigned sg_jif_to_ms(int jifs)
2393 {
2394     if (jifs <= 0)
2395         return 0U;
2396     else {
2397         unsigned int j = (unsigned int)jifs;
2398         return (j < (UINT_MAX / 1000)) ? ((j * 1000) / HZ) : ((j / HZ) * 1000);
2399     }
2400 }
2401
2402 static unsigned char allow_ops[] = {TEST_UNIT_READY, INQUIRY,
2403 READ_CAPACITY, READ_BUFFER, READ_6, READ_10, READ_12,
2404 MODE_SENSE, MODE_SENSE_10};
2405
2406 static int sg_allow_access(unsigned char opcode, char dev_type)
2407 {
2408     int k;
2409
2410     if (TYPE_SCANNER == dev_type) /* TYPE_ROM maybe burner */
2411         return 1;
2412     for (k = 0; k < sizeof(allow_ops); ++k) {
2413         if (opcode == allow_ops[k])
2414             return 1;
2415     }
2416     return 0;
2417 }
2418
2419
2420 #ifdef CONFIG_PROC_FS
2421 static int sg_last_dev()
2422 {
2423     int k;
2424     unsigned long iflags;
2425
2426     read_lock_irqsave(&sg_dev_arr_lock, iflags);
2427     for (k = sg_template.dev_max - 1; k >= 0; --k)
2428         if (sg_dev_arr[k] && sg_dev_arr[k]->device) break;
2429     read_unlock_irqrestore(&sg_dev_arr_lock, iflags);
2430     return k + 1;   /* origin 1 */
2431 }
2432 #endif
2433
2434 static Sg_device * sg_get_dev(int dev)
2435 {
2436     Sg_device * sdp = NULL;
2437     unsigned long iflags;
2438
2439     if (sg_dev_arr && (dev >= 0))
2440     {
2441         read_lock_irqsave(&sg_dev_arr_lock, iflags);
2442     if (dev < sg_template.dev_max)
2443         sdp = sg_dev_arr[dev];
2444         read_unlock_irqrestore(&sg_dev_arr_lock, iflags);
2445     }
2446     return sdp;
2447 }
2448
2449 #ifdef CONFIG_PROC_FS
2450
2451 static struct proc_dir_entry * sg_proc_sgp = NULL;
2452
2453 static const char * sg_proc_sg_dirname = "sg";
2454 static const char * sg_proc_leaf_names[] = {"def_reserved_size", "debug",
2455                             "devices", "device_hdr", "device_strs",
2456                             "hosts", "host_hdr", "host_strs", "version"};
2457
2458 static int sg_proc_dressz_read(char * buffer, char ** start, off_t offset,
2459                                int size, int * eof, void * data);
2460 static int sg_proc_dressz_info(char * buffer, int * len, off_t * begin,
2461                                off_t offset, int size);
2462 static int sg_proc_dressz_write(struct file * filp, const char * buffer,
2463                                 unsigned long count, void * data);
2464 static int sg_proc_debug_read(char * buffer, char ** start, off_t offset,
2465                               int size, int * eof, void * data);
2466 static int sg_proc_debug_info(char * buffer, int * len, off_t * begin,
2467                               off_t offset, int size);
2468 static int sg_proc_dev_read(char * buffer, char ** start, off_t offset,
2469                             int size, int * eof, void * data);
2470 static int sg_proc_dev_info(char * buffer, int * len, off_t * begin,
2471                             off_t offset, int size);
2472 static int sg_proc_devhdr_read(char * buffer, char ** start, off_t offset,
2473                                int size, int * eof, void * data);
2474 static int sg_proc_devhdr_info(char * buffer, int * len, off_t * begin,
2475                                off_t offset, int size);
2476 static int sg_proc_devstrs_read(char * buffer, char ** start, off_t offset,
2477                                 int size, int * eof, void * data);
2478 static int sg_proc_devstrs_info(char * buffer, int * len, off_t * begin,
2479                                 off_t offset, int size);
2480 static int sg_proc_host_read(char * buffer, char ** start, off_t offset,
2481                              int size, int * eof, void * data);
2482 static int sg_proc_host_info(char * buffer, int * len, off_t * begin,
2483                              off_t offset, int size);
2484 static int sg_proc_hosthdr_read(char * buffer, char ** start, off_t offset,
2485                                 int size, int * eof, void * data);
2486 static int sg_proc_hosthdr_info(char * buffer, int * len, off_t * begin,
2487                                 off_t offset, int size);
2488 static int sg_proc_hoststrs_read(char * buffer, char ** start, off_t offset,
2489                                  int size, int * eof, void * data);
2490 static int sg_proc_hoststrs_info(char * buffer, int * len, off_t * begin,
2491                                  off_t offset, int size);
2492 static int sg_proc_version_read(char * buffer, char ** start, off_t offset,
2493                                 int size, int * eof, void * data);
2494 static int sg_proc_version_info(char * buffer, int * len, off_t * begin,
2495                                 off_t offset, int size);
2496 static read_proc_t * sg_proc_leaf_reads[] = {
2497              sg_proc_dressz_read, sg_proc_debug_read,
2498              sg_proc_dev_read, sg_proc_devhdr_read, sg_proc_devstrs_read,
2499              sg_proc_host_read, sg_proc_hosthdr_read, sg_proc_hoststrs_read,
2500              sg_proc_version_read};
2501 static write_proc_t * sg_proc_leaf_writes[] = {
2502              sg_proc_dressz_write, 0, 0, 0, 0, 0, 0, 0, 0};
2503
2504 #define PRINT_PROC(fmt,args...)                                 \
2505     do {                                                        \
2506         *len += sprintf(buffer + *len, fmt, ##args);            \
2507         if (*begin + *len > offset + size)                      \
2508             return 0;                                           \
2509         if (*begin + *len < offset) {                           \
2510             *begin += *len;                                     \
2511             *len = 0;                                           \
2512         }                                                       \
2513     } while(0)
2514
2515 #define SG_PROC_READ_FN(infofp)                                 \
2516     do {                                                        \
2517         int len = 0;                                            \
2518         off_t begin = 0;                                        \
2519         *eof = infofp(buffer, &len, &begin, offset, size);      \
2520         if (offset >= (begin + len))                            \
2521             return 0;                                           \
2522         *start = buffer + offset - begin;                       \
2523         return (size < (begin + len - offset)) ?                \
2524                                 size : begin + len - offset;    \
2525     } while(0)
2526
2527
2528 static int sg_proc_init()
2529 {
2530     int k, mask;
2531     int leaves = sizeof(sg_proc_leaf_names) / sizeof(sg_proc_leaf_names[0]);
2532     struct proc_dir_entry * pdep;
2533
2534     if (! proc_scsi)
2535         return 1;
2536     sg_proc_sgp = create_proc_entry(sg_proc_sg_dirname,
2537                                     S_IFDIR | S_IRUGO | S_IXUGO, proc_scsi);
2538     if (! sg_proc_sgp)
2539         return 1;
2540     for (k = 0; k < leaves; ++k) {
2541         mask = sg_proc_leaf_writes[k] ? S_IRUGO | S_IWUSR : S_IRUGO;
2542         pdep = create_proc_entry(sg_proc_leaf_names[k], mask, sg_proc_sgp);
2543         if (pdep) {
2544             pdep->read_proc = sg_proc_leaf_reads[k];
2545             if (sg_proc_leaf_writes[k])
2546                 pdep->write_proc = sg_proc_leaf_writes[k];
2547         }
2548     }
2549     return 0;
2550 }
2551
2552 static void sg_proc_cleanup()
2553 {
2554     int k;
2555     int leaves = sizeof(sg_proc_leaf_names) / sizeof(sg_proc_leaf_names[0]);
2556
2557     if ((! proc_scsi) || (! sg_proc_sgp))
2558         return;
2559     for (k = 0; k < leaves; ++k)
2560         remove_proc_entry(sg_proc_leaf_names[k], sg_proc_sgp);
2561     remove_proc_entry(sg_proc_sg_dirname, proc_scsi);
2562 }
2563
2564 static int sg_proc_dressz_read(char * buffer, char ** start, off_t offset,
2565                                int size, int * eof, void * data)
2566 { SG_PROC_READ_FN(sg_proc_dressz_info); }
2567
2568 static int sg_proc_dressz_info(char * buffer, int * len, off_t * begin,
2569                                off_t offset, int size)
2570 {
2571     PRINT_PROC("%d\n", sg_big_buff);
2572     return 1;
2573 }
2574
2575 static int sg_proc_dressz_write(struct file * filp, const char * buffer,
2576                                 unsigned long count, void * data)
2577 {
2578     int num;
2579     unsigned long k = ULONG_MAX;
2580     char buff[11];
2581
2582     if (! capable(CAP_SYS_ADMIN))
2583         return -EACCES;
2584     num = (count < 10) ? count : 10;
2585     copy_from_user(buff, buffer, num);
2586     buff[num] = '\0';
2587     k = simple_strtoul(buff, 0, 10);
2588     if (k <= 1048576) {
2589         sg_big_buff = k;
2590         return count;
2591     }
2592     return -ERANGE;
2593 }
2594
2595 static int sg_proc_debug_read(char * buffer, char ** start, off_t offset,
2596                               int size, int * eof, void * data)
2597 { SG_PROC_READ_FN(sg_proc_debug_info); }
2598
2599 static int sg_proc_debug_info(char * buffer, int * len, off_t * begin,
2600                               off_t offset, int size)
2601 {
2602     Sg_device * sdp;
2603     const sg_io_hdr_t * hp;
2604     int j, max_dev;
2605
2606     if (NULL == sg_dev_arr) {
2607         PRINT_PROC("sg_dev_arr NULL, driver not initialized\n");
2608         return 1;
2609     }
2610     max_dev = sg_last_dev();
2611     PRINT_PROC("dev_max(currently)=%d max_active_device=%d (origin 1)\n",
2612                sg_template.dev_max, max_dev);
2613     PRINT_PROC(" scsi_dma_free_sectors=%u sg_pool_secs_aval=%d "
2614                "def_reserved_size=%d\n",
2615                scsi_dma_free_sectors, sg_pool_secs_avail, sg_big_buff);
2616     for (j = 0; j < max_dev; ++j) {
2617         if ((sdp = sg_get_dev(j))) {
2618             Sg_fd * fp;
2619             Sg_request * srp;
2620             struct scsi_device * scsidp;
2621             int dev, k, m, blen, usg;
2622
2623             if (! (scsidp = sdp->device)) {
2624                 PRINT_PROC("device %d detached ??\n", j);
2625                 continue;
2626             }
2627             dev = MINOR(sdp->i_rdev);
2628
2629             if (sg_get_nth_sfp(sdp, 0)) {
2630                 PRINT_PROC(" >>> device=sg%d ", dev);
2631                 PRINT_PROC("scsi%d chan=%d id=%d lun=%d   em=%d sg_tablesize=%d"
2632                        " excl=%d\n", scsidp->host->host_no, scsidp->channel,
2633                        scsidp->id, scsidp->lun, scsidp->host->hostt->emulated,
2634                        sdp->sg_tablesize, sdp->exclude);
2635             }
2636             for (k = 0; (fp = sg_get_nth_sfp(sdp, k)); ++k) {
2637                 PRINT_PROC("   FD(%d): timeout=%dms bufflen=%d "
2638                            "(res)sgat=%d low_dma=%d\n", k + 1,
2639                            sg_jif_to_ms(fp->timeout), fp->reserve.bufflen,
2640                            (int)fp->reserve.k_use_sg, (int)fp->low_dma);
2641                 PRINT_PROC("   cmd_q=%d f_packid=%d k_orphan=%d closed=%d\n",
2642                            (int)fp->cmd_q, (int)fp->force_packid,
2643                            (int)fp->keep_orphan, (int)fp->closed);
2644                 for (m = 0; (srp = sg_get_nth_request(fp, m)); ++m) {
2645                     hp = &srp->header;
2646 /* stop indenting so far ... */
2647         PRINT_PROC(srp->res_used ? "     rb>> " :
2648             ((SG_INFO_DIRECT_IO_MASK & hp->info) ? "     dio>> " : "     "));
2649         blen = srp->my_cmdp ? srp->my_cmdp->sr_bufflen : srp->data.bufflen;
2650         usg = srp->my_cmdp ? srp->my_cmdp->sr_use_sg : srp->data.k_use_sg;
2651         PRINT_PROC(srp->done ? ((1 == srp->done) ? "rcv:" : "fin:") 
2652                              : (srp->my_cmdp ? "act:" : "prior:"));
2653         PRINT_PROC(" id=%d blen=%d", srp->header.pack_id, blen);
2654         if (srp->done)
2655             PRINT_PROC(" dur=%d", hp->duration);
2656         else
2657             PRINT_PROC(" t_o/elap=%d/%d", ((hp->interface_id == '\0') ?
2658                         sg_jif_to_ms(fp->timeout) : hp->timeout),
2659                   sg_jif_to_ms(hp->duration ? (jiffies - hp->duration) : 0));
2660         PRINT_PROC("ms sgat=%d op=0x%02x\n", usg, (int)srp->data.cmd_opcode);
2661 /* reset indenting */
2662                 }
2663                 if (0 == m)
2664                     PRINT_PROC("     No requests active\n");
2665             }
2666         }
2667     }
2668     return 1;
2669 }
2670
2671 static int sg_proc_dev_read(char * buffer, char ** start, off_t offset,
2672                             int size, int * eof, void * data)
2673 { SG_PROC_READ_FN(sg_proc_dev_info); }
2674
2675 static int sg_proc_dev_info(char * buffer, int * len, off_t * begin,
2676                             off_t offset, int size)
2677 {
2678     Sg_device * sdp;
2679     int j, max_dev;
2680     struct scsi_device * scsidp;
2681
2682     max_dev = sg_last_dev();
2683     for (j = 0; j < max_dev; ++j) {
2684         sdp = sg_get_dev(j);
2685         if (sdp && (scsidp = sdp->device))
2686             PRINT_PROC("%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n",
2687                scsidp->host->host_no, scsidp->channel, scsidp->id,
2688                scsidp->lun, (int)scsidp->type, (int)scsidp->access_count,
2689                (int)scsidp->queue_depth, (int)scsidp->device_busy);
2690         else
2691             PRINT_PROC("-1\t-1\t-1\t-1\t-1\t-1\t-1\t-1\n");
2692     }
2693     return 1;
2694 }
2695
2696 static int sg_proc_devhdr_read(char * buffer, char ** start, off_t offset,
2697                                int size, int * eof, void * data)
2698 { SG_PROC_READ_FN(sg_proc_devhdr_info); }
2699
2700 static int sg_proc_devhdr_info(char * buffer, int * len, off_t * begin,
2701                                off_t offset, int size)
2702 {
2703     PRINT_PROC("host\tchan\tid\tlun\ttype\tbopens\tqdepth\tbusy\n");
2704     return 1;
2705 }
2706
2707 static int sg_proc_devstrs_read(char * buffer, char ** start, off_t offset,
2708                                 int size, int * eof, void * data)
2709 { SG_PROC_READ_FN(sg_proc_devstrs_info); }
2710
2711 static int sg_proc_devstrs_info(char * buffer, int * len, off_t * begin,
2712                                 off_t offset, int size)
2713 {
2714     Sg_device * sdp;
2715     int j, max_dev;
2716     struct scsi_device * scsidp;
2717
2718     max_dev = sg_last_dev();
2719     for (j = 0; j < max_dev; ++j) {
2720         sdp = sg_get_dev(j);
2721         if (sdp && (scsidp = sdp->device))
2722             PRINT_PROC("%8.8s\t%16.16s\t%4.4s\n",
2723                        scsidp->vendor, scsidp->model, scsidp->rev);
2724         else
2725             PRINT_PROC("<no active device>\n");
2726     }
2727     return 1;
2728 }
2729
2730 static int sg_proc_host_read(char * buffer, char ** start, off_t offset,
2731                              int size, int * eof, void * data)
2732 { SG_PROC_READ_FN(sg_proc_host_info); }
2733
2734 static int sg_proc_host_info(char * buffer, int * len, off_t * begin,
2735                              off_t offset, int size)
2736 {
2737     struct Scsi_Host * shp;
2738     int k;
2739
2740     for (k = 0, shp = scsi_hostlist; shp; shp = shp->next, ++k) {
2741         for ( ; k < shp->host_no; ++k)
2742             PRINT_PROC("-1\t-1\t-1\t-1\t-1\t-1\n");
2743         PRINT_PROC("%u\t%hu\t%hd\t%hu\t%d\t%d\n",
2744                    shp->unique_id, shp->host_busy, shp->cmd_per_lun,
2745                    shp->sg_tablesize, (int)shp->unchecked_isa_dma,
2746                    (int)shp->hostt->emulated);
2747     }
2748     return 1;
2749 }
2750
2751 static int sg_proc_hosthdr_read(char * buffer, char ** start, off_t offset,
2752                                 int size, int * eof, void * data)
2753 { SG_PROC_READ_FN(sg_proc_hosthdr_info); }
2754
2755 static int sg_proc_hosthdr_info(char * buffer, int * len, off_t * begin,
2756                                 off_t offset, int size)
2757 {
2758     PRINT_PROC("uid\tbusy\tcpl\tscatg\tisa\temul\n");
2759     return 1;
2760 }
2761
2762 static int sg_proc_hoststrs_read(char * buffer, char ** start, off_t offset,
2763                                  int size, int * eof, void * data)
2764 { SG_PROC_READ_FN(sg_proc_hoststrs_info); }
2765
2766 static int sg_proc_hoststrs_info(char * buffer, int * len, off_t * begin,
2767                                  off_t offset, int size)
2768 {
2769     struct Scsi_Host * shp;
2770     int k;
2771
2772     for (k = 0, shp = scsi_hostlist; shp; shp = shp->next, ++k) {
2773         for ( ; k < shp->host_no; ++k)
2774             PRINT_PROC("<no active host>\n");
2775         PRINT_PROC("%s\n", shp->hostt->info ? shp->hostt->info(shp) :
2776                     (shp->hostt->name ? shp->hostt->name : "<no name>"));
2777     }
2778     return 1;
2779 }
2780
2781 static int sg_proc_version_read(char * buffer, char ** start, off_t offset,
2782                                 int size, int * eof, void * data)
2783 { SG_PROC_READ_FN(sg_proc_version_info); }
2784
2785 static int sg_proc_version_info(char * buffer, int * len, off_t * begin,
2786                                 off_t offset, int size)
2787 {
2788     PRINT_PROC("%d\t%s\n", sg_version_num, sg_version_str);
2789     return 1;
2790 }
2791 #endif  /* CONFIG_PROC_FS */
2792
2793
2794 module_init(init_sg);
2795 module_exit(exit_sg);