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