xref: /linux/drivers/scsi/scsi_lib.c (revision 6e8331ac6973435b1e7604c30f2ad394035b46e1)
1 /*
2  *  scsi_lib.c Copyright (C) 1999 Eric Youngdale
3  *
4  *  SCSI queueing library.
5  *      Initial versions: Eric Youngdale (eric@andante.org).
6  *                        Based upon conversations with large numbers
7  *                        of people at Linux Expo.
8  */
9 
10 #include <linux/bio.h>
11 #include <linux/blkdev.h>
12 #include <linux/completion.h>
13 #include <linux/kernel.h>
14 #include <linux/mempool.h>
15 #include <linux/slab.h>
16 #include <linux/init.h>
17 #include <linux/pci.h>
18 #include <linux/delay.h>
19 #include <linux/hardirq.h>
20 
21 #include <scsi/scsi.h>
22 #include <scsi/scsi_cmnd.h>
23 #include <scsi/scsi_dbg.h>
24 #include <scsi/scsi_device.h>
25 #include <scsi/scsi_driver.h>
26 #include <scsi/scsi_eh.h>
27 #include <scsi/scsi_host.h>
28 
29 #include "scsi_priv.h"
30 #include "scsi_logging.h"
31 
32 
33 #define SG_MEMPOOL_NR		ARRAY_SIZE(scsi_sg_pools)
34 #define SG_MEMPOOL_SIZE		32
35 
36 struct scsi_host_sg_pool {
37 	size_t		size;
38 	char		*name;
39 	kmem_cache_t	*slab;
40 	mempool_t	*pool;
41 };
42 
43 #if (SCSI_MAX_PHYS_SEGMENTS < 32)
44 #error SCSI_MAX_PHYS_SEGMENTS is too small
45 #endif
46 
47 #define SP(x) { x, "sgpool-" #x }
48 static struct scsi_host_sg_pool scsi_sg_pools[] = {
49 	SP(8),
50 	SP(16),
51 	SP(32),
52 #if (SCSI_MAX_PHYS_SEGMENTS > 32)
53 	SP(64),
54 #if (SCSI_MAX_PHYS_SEGMENTS > 64)
55 	SP(128),
56 #if (SCSI_MAX_PHYS_SEGMENTS > 128)
57 	SP(256),
58 #if (SCSI_MAX_PHYS_SEGMENTS > 256)
59 #error SCSI_MAX_PHYS_SEGMENTS is too large
60 #endif
61 #endif
62 #endif
63 #endif
64 };
65 #undef SP
66 
67 static void scsi_run_queue(struct request_queue *q);
68 
69 /*
70  * Function:	scsi_unprep_request()
71  *
72  * Purpose:	Remove all preparation done for a request, including its
73  *		associated scsi_cmnd, so that it can be requeued.
74  *
75  * Arguments:	req	- request to unprepare
76  *
77  * Lock status:	Assumed that no locks are held upon entry.
78  *
79  * Returns:	Nothing.
80  */
81 static void scsi_unprep_request(struct request *req)
82 {
83 	struct scsi_cmnd *cmd = req->special;
84 
85 	req->flags &= ~REQ_DONTPREP;
86 	req->special = NULL;
87 
88 	scsi_put_command(cmd);
89 }
90 
91 /*
92  * Function:    scsi_queue_insert()
93  *
94  * Purpose:     Insert a command in the midlevel queue.
95  *
96  * Arguments:   cmd    - command that we are adding to queue.
97  *              reason - why we are inserting command to queue.
98  *
99  * Lock status: Assumed that lock is not held upon entry.
100  *
101  * Returns:     Nothing.
102  *
103  * Notes:       We do this for one of two cases.  Either the host is busy
104  *              and it cannot accept any more commands for the time being,
105  *              or the device returned QUEUE_FULL and can accept no more
106  *              commands.
107  * Notes:       This could be called either from an interrupt context or a
108  *              normal process context.
109  */
110 int scsi_queue_insert(struct scsi_cmnd *cmd, int reason)
111 {
112 	struct Scsi_Host *host = cmd->device->host;
113 	struct scsi_device *device = cmd->device;
114 	struct request_queue *q = device->request_queue;
115 	unsigned long flags;
116 
117 	SCSI_LOG_MLQUEUE(1,
118 		 printk("Inserting command %p into mlqueue\n", cmd));
119 
120 	/*
121 	 * Set the appropriate busy bit for the device/host.
122 	 *
123 	 * If the host/device isn't busy, assume that something actually
124 	 * completed, and that we should be able to queue a command now.
125 	 *
126 	 * Note that the prior mid-layer assumption that any host could
127 	 * always queue at least one command is now broken.  The mid-layer
128 	 * will implement a user specifiable stall (see
129 	 * scsi_host.max_host_blocked and scsi_device.max_device_blocked)
130 	 * if a command is requeued with no other commands outstanding
131 	 * either for the device or for the host.
132 	 */
133 	if (reason == SCSI_MLQUEUE_HOST_BUSY)
134 		host->host_blocked = host->max_host_blocked;
135 	else if (reason == SCSI_MLQUEUE_DEVICE_BUSY)
136 		device->device_blocked = device->max_device_blocked;
137 
138 	/*
139 	 * Decrement the counters, since these commands are no longer
140 	 * active on the host/device.
141 	 */
142 	scsi_device_unbusy(device);
143 
144 	/*
145 	 * Requeue this command.  It will go before all other commands
146 	 * that are already in the queue.
147 	 *
148 	 * NOTE: there is magic here about the way the queue is plugged if
149 	 * we have no outstanding commands.
150 	 *
151 	 * Although we *don't* plug the queue, we call the request
152 	 * function.  The SCSI request function detects the blocked condition
153 	 * and plugs the queue appropriately.
154          */
155 	spin_lock_irqsave(q->queue_lock, flags);
156 	blk_requeue_request(q, cmd->request);
157 	spin_unlock_irqrestore(q->queue_lock, flags);
158 
159 	scsi_run_queue(q);
160 
161 	return 0;
162 }
163 
164 /**
165  * scsi_execute - insert request and wait for the result
166  * @sdev:	scsi device
167  * @cmd:	scsi command
168  * @data_direction: data direction
169  * @buffer:	data buffer
170  * @bufflen:	len of buffer
171  * @sense:	optional sense buffer
172  * @timeout:	request timeout in seconds
173  * @retries:	number of times to retry request
174  * @flags:	or into request flags;
175  *
176  * returns the req->errors value which is the the scsi_cmnd result
177  * field.
178  **/
179 int scsi_execute(struct scsi_device *sdev, const unsigned char *cmd,
180 		 int data_direction, void *buffer, unsigned bufflen,
181 		 unsigned char *sense, int timeout, int retries, int flags)
182 {
183 	struct request *req;
184 	int write = (data_direction == DMA_TO_DEVICE);
185 	int ret = DRIVER_ERROR << 24;
186 
187 	req = blk_get_request(sdev->request_queue, write, __GFP_WAIT);
188 
189 	if (bufflen &&	blk_rq_map_kern(sdev->request_queue, req,
190 					buffer, bufflen, __GFP_WAIT))
191 		goto out;
192 
193 	req->cmd_len = COMMAND_SIZE(cmd[0]);
194 	memcpy(req->cmd, cmd, req->cmd_len);
195 	req->sense = sense;
196 	req->sense_len = 0;
197 	req->retries = retries;
198 	req->timeout = timeout;
199 	req->flags |= flags | REQ_BLOCK_PC | REQ_SPECIAL | REQ_QUIET;
200 
201 	/*
202 	 * head injection *required* here otherwise quiesce won't work
203 	 */
204 	blk_execute_rq(req->q, NULL, req, 1);
205 
206 	ret = req->errors;
207  out:
208 	blk_put_request(req);
209 
210 	return ret;
211 }
212 EXPORT_SYMBOL(scsi_execute);
213 
214 
215 int scsi_execute_req(struct scsi_device *sdev, const unsigned char *cmd,
216 		     int data_direction, void *buffer, unsigned bufflen,
217 		     struct scsi_sense_hdr *sshdr, int timeout, int retries)
218 {
219 	char *sense = NULL;
220 	int result;
221 
222 	if (sshdr) {
223 		sense = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_NOIO);
224 		if (!sense)
225 			return DRIVER_ERROR << 24;
226 	}
227 	result = scsi_execute(sdev, cmd, data_direction, buffer, bufflen,
228 			      sense, timeout, retries, 0);
229 	if (sshdr)
230 		scsi_normalize_sense(sense, SCSI_SENSE_BUFFERSIZE, sshdr);
231 
232 	kfree(sense);
233 	return result;
234 }
235 EXPORT_SYMBOL(scsi_execute_req);
236 
237 struct scsi_io_context {
238 	void *data;
239 	void (*done)(void *data, char *sense, int result, int resid);
240 	char sense[SCSI_SENSE_BUFFERSIZE];
241 };
242 
243 static kmem_cache_t *scsi_io_context_cache;
244 
245 static void scsi_end_async(struct request *req, int uptodate)
246 {
247 	struct scsi_io_context *sioc = req->end_io_data;
248 
249 	if (sioc->done)
250 		sioc->done(sioc->data, sioc->sense, req->errors, req->data_len);
251 
252 	kmem_cache_free(scsi_io_context_cache, sioc);
253 	__blk_put_request(req->q, req);
254 }
255 
256 static int scsi_merge_bio(struct request *rq, struct bio *bio)
257 {
258 	struct request_queue *q = rq->q;
259 
260 	bio->bi_flags &= ~(1 << BIO_SEG_VALID);
261 	if (rq_data_dir(rq) == WRITE)
262 		bio->bi_rw |= (1 << BIO_RW);
263 	blk_queue_bounce(q, &bio);
264 
265 	if (!rq->bio)
266 		blk_rq_bio_prep(q, rq, bio);
267 	else if (!q->back_merge_fn(q, rq, bio))
268 		return -EINVAL;
269 	else {
270 		rq->biotail->bi_next = bio;
271 		rq->biotail = bio;
272 		rq->hard_nr_sectors += bio_sectors(bio);
273 		rq->nr_sectors = rq->hard_nr_sectors;
274 	}
275 
276 	return 0;
277 }
278 
279 static int scsi_bi_endio(struct bio *bio, unsigned int bytes_done, int error)
280 {
281 	if (bio->bi_size)
282 		return 1;
283 
284 	bio_put(bio);
285 	return 0;
286 }
287 
288 /**
289  * scsi_req_map_sg - map a scatterlist into a request
290  * @rq:		request to fill
291  * @sg:		scatterlist
292  * @nsegs:	number of elements
293  * @bufflen:	len of buffer
294  * @gfp:	memory allocation flags
295  *
296  * scsi_req_map_sg maps a scatterlist into a request so that the
297  * request can be sent to the block layer. We do not trust the scatterlist
298  * sent to use, as some ULDs use that struct to only organize the pages.
299  */
300 static int scsi_req_map_sg(struct request *rq, struct scatterlist *sgl,
301 			   int nsegs, unsigned bufflen, gfp_t gfp)
302 {
303 	struct request_queue *q = rq->q;
304 	int nr_pages = (bufflen + sgl[0].offset + PAGE_SIZE - 1) >> PAGE_SHIFT;
305 	unsigned int data_len = 0, len, bytes, off;
306 	struct page *page;
307 	struct bio *bio = NULL;
308 	int i, err, nr_vecs = 0;
309 
310 	for (i = 0; i < nsegs; i++) {
311 		page = sgl[i].page;
312 		off = sgl[i].offset;
313 		len = sgl[i].length;
314 		data_len += len;
315 
316 		while (len > 0) {
317 			bytes = min_t(unsigned int, len, PAGE_SIZE - off);
318 
319 			if (!bio) {
320 				nr_vecs = min_t(int, BIO_MAX_PAGES, nr_pages);
321 				nr_pages -= nr_vecs;
322 
323 				bio = bio_alloc(gfp, nr_vecs);
324 				if (!bio) {
325 					err = -ENOMEM;
326 					goto free_bios;
327 				}
328 				bio->bi_end_io = scsi_bi_endio;
329 			}
330 
331 			if (bio_add_pc_page(q, bio, page, bytes, off) !=
332 			    bytes) {
333 				bio_put(bio);
334 				err = -EINVAL;
335 				goto free_bios;
336 			}
337 
338 			if (bio->bi_vcnt >= nr_vecs) {
339 				err = scsi_merge_bio(rq, bio);
340 				if (err) {
341 					bio_endio(bio, bio->bi_size, 0);
342 					goto free_bios;
343 				}
344 				bio = NULL;
345 			}
346 
347 			page++;
348 			len -= bytes;
349 			off = 0;
350 		}
351 	}
352 
353 	rq->buffer = rq->data = NULL;
354 	rq->data_len = data_len;
355 	return 0;
356 
357 free_bios:
358 	while ((bio = rq->bio) != NULL) {
359 		rq->bio = bio->bi_next;
360 		/*
361 		 * call endio instead of bio_put incase it was bounced
362 		 */
363 		bio_endio(bio, bio->bi_size, 0);
364 	}
365 
366 	return err;
367 }
368 
369 /**
370  * scsi_execute_async - insert request
371  * @sdev:	scsi device
372  * @cmd:	scsi command
373  * @cmd_len:	length of scsi cdb
374  * @data_direction: data direction
375  * @buffer:	data buffer (this can be a kernel buffer or scatterlist)
376  * @bufflen:	len of buffer
377  * @use_sg:	if buffer is a scatterlist this is the number of elements
378  * @timeout:	request timeout in seconds
379  * @retries:	number of times to retry request
380  * @flags:	or into request flags
381  **/
382 int scsi_execute_async(struct scsi_device *sdev, const unsigned char *cmd,
383 		       int cmd_len, int data_direction, void *buffer, unsigned bufflen,
384 		       int use_sg, int timeout, int retries, void *privdata,
385 		       void (*done)(void *, char *, int, int), gfp_t gfp)
386 {
387 	struct request *req;
388 	struct scsi_io_context *sioc;
389 	int err = 0;
390 	int write = (data_direction == DMA_TO_DEVICE);
391 
392 	sioc = kmem_cache_alloc(scsi_io_context_cache, gfp);
393 	if (!sioc)
394 		return DRIVER_ERROR << 24;
395 	memset(sioc, 0, sizeof(*sioc));
396 
397 	req = blk_get_request(sdev->request_queue, write, gfp);
398 	if (!req)
399 		goto free_sense;
400 	req->flags |= REQ_BLOCK_PC | REQ_QUIET;
401 
402 	if (use_sg)
403 		err = scsi_req_map_sg(req, buffer, use_sg, bufflen, gfp);
404 	else if (bufflen)
405 		err = blk_rq_map_kern(req->q, req, buffer, bufflen, gfp);
406 
407 	if (err)
408 		goto free_req;
409 
410 	req->cmd_len = cmd_len;
411 	memcpy(req->cmd, cmd, req->cmd_len);
412 	req->sense = sioc->sense;
413 	req->sense_len = 0;
414 	req->timeout = timeout;
415 	req->retries = retries;
416 	req->end_io_data = sioc;
417 
418 	sioc->data = privdata;
419 	sioc->done = done;
420 
421 	blk_execute_rq_nowait(req->q, NULL, req, 1, scsi_end_async);
422 	return 0;
423 
424 free_req:
425 	blk_put_request(req);
426 free_sense:
427 	kfree(sioc);
428 	return DRIVER_ERROR << 24;
429 }
430 EXPORT_SYMBOL_GPL(scsi_execute_async);
431 
432 /*
433  * Function:    scsi_init_cmd_errh()
434  *
435  * Purpose:     Initialize cmd fields related to error handling.
436  *
437  * Arguments:   cmd	- command that is ready to be queued.
438  *
439  * Notes:       This function has the job of initializing a number of
440  *              fields related to error handling.   Typically this will
441  *              be called once for each command, as required.
442  */
443 static void scsi_init_cmd_errh(struct scsi_cmnd *cmd)
444 {
445 	cmd->serial_number = 0;
446 	memset(cmd->sense_buffer, 0, sizeof cmd->sense_buffer);
447 	if (cmd->cmd_len == 0)
448 		cmd->cmd_len = COMMAND_SIZE(cmd->cmnd[0]);
449 }
450 
451 void scsi_device_unbusy(struct scsi_device *sdev)
452 {
453 	struct Scsi_Host *shost = sdev->host;
454 	unsigned long flags;
455 
456 	spin_lock_irqsave(shost->host_lock, flags);
457 	shost->host_busy--;
458 	if (unlikely(scsi_host_in_recovery(shost) &&
459 		     (shost->host_failed || shost->host_eh_scheduled)))
460 		scsi_eh_wakeup(shost);
461 	spin_unlock(shost->host_lock);
462 	spin_lock(sdev->request_queue->queue_lock);
463 	sdev->device_busy--;
464 	spin_unlock_irqrestore(sdev->request_queue->queue_lock, flags);
465 }
466 
467 /*
468  * Called for single_lun devices on IO completion. Clear starget_sdev_user,
469  * and call blk_run_queue for all the scsi_devices on the target -
470  * including current_sdev first.
471  *
472  * Called with *no* scsi locks held.
473  */
474 static void scsi_single_lun_run(struct scsi_device *current_sdev)
475 {
476 	struct Scsi_Host *shost = current_sdev->host;
477 	struct scsi_device *sdev, *tmp;
478 	struct scsi_target *starget = scsi_target(current_sdev);
479 	unsigned long flags;
480 
481 	spin_lock_irqsave(shost->host_lock, flags);
482 	starget->starget_sdev_user = NULL;
483 	spin_unlock_irqrestore(shost->host_lock, flags);
484 
485 	/*
486 	 * Call blk_run_queue for all LUNs on the target, starting with
487 	 * current_sdev. We race with others (to set starget_sdev_user),
488 	 * but in most cases, we will be first. Ideally, each LU on the
489 	 * target would get some limited time or requests on the target.
490 	 */
491 	blk_run_queue(current_sdev->request_queue);
492 
493 	spin_lock_irqsave(shost->host_lock, flags);
494 	if (starget->starget_sdev_user)
495 		goto out;
496 	list_for_each_entry_safe(sdev, tmp, &starget->devices,
497 			same_target_siblings) {
498 		if (sdev == current_sdev)
499 			continue;
500 		if (scsi_device_get(sdev))
501 			continue;
502 
503 		spin_unlock_irqrestore(shost->host_lock, flags);
504 		blk_run_queue(sdev->request_queue);
505 		spin_lock_irqsave(shost->host_lock, flags);
506 
507 		scsi_device_put(sdev);
508 	}
509  out:
510 	spin_unlock_irqrestore(shost->host_lock, flags);
511 }
512 
513 /*
514  * Function:	scsi_run_queue()
515  *
516  * Purpose:	Select a proper request queue to serve next
517  *
518  * Arguments:	q	- last request's queue
519  *
520  * Returns:     Nothing
521  *
522  * Notes:	The previous command was completely finished, start
523  *		a new one if possible.
524  */
525 static void scsi_run_queue(struct request_queue *q)
526 {
527 	struct scsi_device *sdev = q->queuedata;
528 	struct Scsi_Host *shost = sdev->host;
529 	unsigned long flags;
530 
531 	if (sdev->single_lun)
532 		scsi_single_lun_run(sdev);
533 
534 	spin_lock_irqsave(shost->host_lock, flags);
535 	while (!list_empty(&shost->starved_list) &&
536 	       !shost->host_blocked && !shost->host_self_blocked &&
537 		!((shost->can_queue > 0) &&
538 		  (shost->host_busy >= shost->can_queue))) {
539 		/*
540 		 * As long as shost is accepting commands and we have
541 		 * starved queues, call blk_run_queue. scsi_request_fn
542 		 * drops the queue_lock and can add us back to the
543 		 * starved_list.
544 		 *
545 		 * host_lock protects the starved_list and starved_entry.
546 		 * scsi_request_fn must get the host_lock before checking
547 		 * or modifying starved_list or starved_entry.
548 		 */
549 		sdev = list_entry(shost->starved_list.next,
550 					  struct scsi_device, starved_entry);
551 		list_del_init(&sdev->starved_entry);
552 		spin_unlock_irqrestore(shost->host_lock, flags);
553 
554 		blk_run_queue(sdev->request_queue);
555 
556 		spin_lock_irqsave(shost->host_lock, flags);
557 		if (unlikely(!list_empty(&sdev->starved_entry)))
558 			/*
559 			 * sdev lost a race, and was put back on the
560 			 * starved list. This is unlikely but without this
561 			 * in theory we could loop forever.
562 			 */
563 			break;
564 	}
565 	spin_unlock_irqrestore(shost->host_lock, flags);
566 
567 	blk_run_queue(q);
568 }
569 
570 /*
571  * Function:	scsi_requeue_command()
572  *
573  * Purpose:	Handle post-processing of completed commands.
574  *
575  * Arguments:	q	- queue to operate on
576  *		cmd	- command that may need to be requeued.
577  *
578  * Returns:	Nothing
579  *
580  * Notes:	After command completion, there may be blocks left
581  *		over which weren't finished by the previous command
582  *		this can be for a number of reasons - the main one is
583  *		I/O errors in the middle of the request, in which case
584  *		we need to request the blocks that come after the bad
585  *		sector.
586  * Notes:	Upon return, cmd is a stale pointer.
587  */
588 static void scsi_requeue_command(struct request_queue *q, struct scsi_cmnd *cmd)
589 {
590 	struct request *req = cmd->request;
591 	unsigned long flags;
592 
593 	scsi_unprep_request(req);
594 	spin_lock_irqsave(q->queue_lock, flags);
595 	blk_requeue_request(q, req);
596 	spin_unlock_irqrestore(q->queue_lock, flags);
597 
598 	scsi_run_queue(q);
599 }
600 
601 void scsi_next_command(struct scsi_cmnd *cmd)
602 {
603 	struct scsi_device *sdev = cmd->device;
604 	struct request_queue *q = sdev->request_queue;
605 
606 	/* need to hold a reference on the device before we let go of the cmd */
607 	get_device(&sdev->sdev_gendev);
608 
609 	scsi_put_command(cmd);
610 	scsi_run_queue(q);
611 
612 	/* ok to remove device now */
613 	put_device(&sdev->sdev_gendev);
614 }
615 
616 void scsi_run_host_queues(struct Scsi_Host *shost)
617 {
618 	struct scsi_device *sdev;
619 
620 	shost_for_each_device(sdev, shost)
621 		scsi_run_queue(sdev->request_queue);
622 }
623 
624 /*
625  * Function:    scsi_end_request()
626  *
627  * Purpose:     Post-processing of completed commands (usually invoked at end
628  *		of upper level post-processing and scsi_io_completion).
629  *
630  * Arguments:   cmd	 - command that is complete.
631  *              uptodate - 1 if I/O indicates success, <= 0 for I/O error.
632  *              bytes    - number of bytes of completed I/O
633  *		requeue  - indicates whether we should requeue leftovers.
634  *
635  * Lock status: Assumed that lock is not held upon entry.
636  *
637  * Returns:     cmd if requeue required, NULL otherwise.
638  *
639  * Notes:       This is called for block device requests in order to
640  *              mark some number of sectors as complete.
641  *
642  *		We are guaranteeing that the request queue will be goosed
643  *		at some point during this call.
644  * Notes:	If cmd was requeued, upon return it will be a stale pointer.
645  */
646 static struct scsi_cmnd *scsi_end_request(struct scsi_cmnd *cmd, int uptodate,
647 					  int bytes, int requeue)
648 {
649 	request_queue_t *q = cmd->device->request_queue;
650 	struct request *req = cmd->request;
651 	unsigned long flags;
652 
653 	/*
654 	 * If there are blocks left over at the end, set up the command
655 	 * to queue the remainder of them.
656 	 */
657 	if (end_that_request_chunk(req, uptodate, bytes)) {
658 		int leftover = (req->hard_nr_sectors << 9);
659 
660 		if (blk_pc_request(req))
661 			leftover = req->data_len;
662 
663 		/* kill remainder if no retrys */
664 		if (!uptodate && blk_noretry_request(req))
665 			end_that_request_chunk(req, 0, leftover);
666 		else {
667 			if (requeue) {
668 				/*
669 				 * Bleah.  Leftovers again.  Stick the
670 				 * leftovers in the front of the
671 				 * queue, and goose the queue again.
672 				 */
673 				scsi_requeue_command(q, cmd);
674 				cmd = NULL;
675 			}
676 			return cmd;
677 		}
678 	}
679 
680 	add_disk_randomness(req->rq_disk);
681 
682 	spin_lock_irqsave(q->queue_lock, flags);
683 	if (blk_rq_tagged(req))
684 		blk_queue_end_tag(q, req);
685 	end_that_request_last(req, uptodate);
686 	spin_unlock_irqrestore(q->queue_lock, flags);
687 
688 	/*
689 	 * This will goose the queue request function at the end, so we don't
690 	 * need to worry about launching another command.
691 	 */
692 	scsi_next_command(cmd);
693 	return NULL;
694 }
695 
696 static struct scatterlist *scsi_alloc_sgtable(struct scsi_cmnd *cmd, gfp_t gfp_mask)
697 {
698 	struct scsi_host_sg_pool *sgp;
699 	struct scatterlist *sgl;
700 
701 	BUG_ON(!cmd->use_sg);
702 
703 	switch (cmd->use_sg) {
704 	case 1 ... 8:
705 		cmd->sglist_len = 0;
706 		break;
707 	case 9 ... 16:
708 		cmd->sglist_len = 1;
709 		break;
710 	case 17 ... 32:
711 		cmd->sglist_len = 2;
712 		break;
713 #if (SCSI_MAX_PHYS_SEGMENTS > 32)
714 	case 33 ... 64:
715 		cmd->sglist_len = 3;
716 		break;
717 #if (SCSI_MAX_PHYS_SEGMENTS > 64)
718 	case 65 ... 128:
719 		cmd->sglist_len = 4;
720 		break;
721 #if (SCSI_MAX_PHYS_SEGMENTS  > 128)
722 	case 129 ... 256:
723 		cmd->sglist_len = 5;
724 		break;
725 #endif
726 #endif
727 #endif
728 	default:
729 		return NULL;
730 	}
731 
732 	sgp = scsi_sg_pools + cmd->sglist_len;
733 	sgl = mempool_alloc(sgp->pool, gfp_mask);
734 	return sgl;
735 }
736 
737 static void scsi_free_sgtable(struct scatterlist *sgl, int index)
738 {
739 	struct scsi_host_sg_pool *sgp;
740 
741 	BUG_ON(index >= SG_MEMPOOL_NR);
742 
743 	sgp = scsi_sg_pools + index;
744 	mempool_free(sgl, sgp->pool);
745 }
746 
747 /*
748  * Function:    scsi_release_buffers()
749  *
750  * Purpose:     Completion processing for block device I/O requests.
751  *
752  * Arguments:   cmd	- command that we are bailing.
753  *
754  * Lock status: Assumed that no lock is held upon entry.
755  *
756  * Returns:     Nothing
757  *
758  * Notes:       In the event that an upper level driver rejects a
759  *		command, we must release resources allocated during
760  *		the __init_io() function.  Primarily this would involve
761  *		the scatter-gather table, and potentially any bounce
762  *		buffers.
763  */
764 static void scsi_release_buffers(struct scsi_cmnd *cmd)
765 {
766 	if (cmd->use_sg)
767 		scsi_free_sgtable(cmd->request_buffer, cmd->sglist_len);
768 
769 	/*
770 	 * Zero these out.  They now point to freed memory, and it is
771 	 * dangerous to hang onto the pointers.
772 	 */
773 	cmd->request_buffer = NULL;
774 	cmd->request_bufflen = 0;
775 }
776 
777 /*
778  * Function:    scsi_io_completion()
779  *
780  * Purpose:     Completion processing for block device I/O requests.
781  *
782  * Arguments:   cmd   - command that is finished.
783  *
784  * Lock status: Assumed that no lock is held upon entry.
785  *
786  * Returns:     Nothing
787  *
788  * Notes:       This function is matched in terms of capabilities to
789  *              the function that created the scatter-gather list.
790  *              In other words, if there are no bounce buffers
791  *              (the normal case for most drivers), we don't need
792  *              the logic to deal with cleaning up afterwards.
793  *
794  *		We must do one of several things here:
795  *
796  *		a) Call scsi_end_request.  This will finish off the
797  *		   specified number of sectors.  If we are done, the
798  *		   command block will be released, and the queue
799  *		   function will be goosed.  If we are not done, then
800  *		   scsi_end_request will directly goose the queue.
801  *
802  *		b) We can just use scsi_requeue_command() here.  This would
803  *		   be used if we just wanted to retry, for example.
804  */
805 void scsi_io_completion(struct scsi_cmnd *cmd, unsigned int good_bytes)
806 {
807 	int result = cmd->result;
808 	int this_count = cmd->request_bufflen;
809 	request_queue_t *q = cmd->device->request_queue;
810 	struct request *req = cmd->request;
811 	int clear_errors = 1;
812 	struct scsi_sense_hdr sshdr;
813 	int sense_valid = 0;
814 	int sense_deferred = 0;
815 
816 	scsi_release_buffers(cmd);
817 
818 	if (result) {
819 		sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
820 		if (sense_valid)
821 			sense_deferred = scsi_sense_is_deferred(&sshdr);
822 	}
823 
824 	if (blk_pc_request(req)) { /* SG_IO ioctl from block level */
825 		req->errors = result;
826 		if (result) {
827 			clear_errors = 0;
828 			if (sense_valid && req->sense) {
829 				/*
830 				 * SG_IO wants current and deferred errors
831 				 */
832 				int len = 8 + cmd->sense_buffer[7];
833 
834 				if (len > SCSI_SENSE_BUFFERSIZE)
835 					len = SCSI_SENSE_BUFFERSIZE;
836 				memcpy(req->sense, cmd->sense_buffer,  len);
837 				req->sense_len = len;
838 			}
839 		} else
840 			req->data_len = cmd->resid;
841 	}
842 
843 	/*
844 	 * Next deal with any sectors which we were able to correctly
845 	 * handle.
846 	 */
847 	SCSI_LOG_HLCOMPLETE(1, printk("%ld sectors total, "
848 				      "%d bytes done.\n",
849 				      req->nr_sectors, good_bytes));
850 	SCSI_LOG_HLCOMPLETE(1, printk("use_sg is %d\n", cmd->use_sg));
851 
852 	if (clear_errors)
853 		req->errors = 0;
854 
855 	/* A number of bytes were successfully read.  If there
856 	 * are leftovers and there is some kind of error
857 	 * (result != 0), retry the rest.
858 	 */
859 	if (scsi_end_request(cmd, 1, good_bytes, result == 0) == NULL)
860 		return;
861 
862 	/* good_bytes = 0, or (inclusive) there were leftovers and
863 	 * result = 0, so scsi_end_request couldn't retry.
864 	 */
865 	if (sense_valid && !sense_deferred) {
866 		switch (sshdr.sense_key) {
867 		case UNIT_ATTENTION:
868 			if (cmd->device->removable) {
869 				/* Detected disc change.  Set a bit
870 				 * and quietly refuse further access.
871 				 */
872 				cmd->device->changed = 1;
873 				scsi_end_request(cmd, 0, this_count, 1);
874 				return;
875 			} else {
876 				/* Must have been a power glitch, or a
877 				 * bus reset.  Could not have been a
878 				 * media change, so we just retry the
879 				 * request and see what happens.
880 				 */
881 				scsi_requeue_command(q, cmd);
882 				return;
883 			}
884 			break;
885 		case ILLEGAL_REQUEST:
886 			/* If we had an ILLEGAL REQUEST returned, then
887 			 * we may have performed an unsupported
888 			 * command.  The only thing this should be
889 			 * would be a ten byte read where only a six
890 			 * byte read was supported.  Also, on a system
891 			 * where READ CAPACITY failed, we may have
892 			 * read past the end of the disk.
893 			 */
894 			if ((cmd->device->use_10_for_rw &&
895 			    sshdr.asc == 0x20 && sshdr.ascq == 0x00) &&
896 			    (cmd->cmnd[0] == READ_10 ||
897 			     cmd->cmnd[0] == WRITE_10)) {
898 				cmd->device->use_10_for_rw = 0;
899 				/* This will cause a retry with a
900 				 * 6-byte command.
901 				 */
902 				scsi_requeue_command(q, cmd);
903 				return;
904 			} else {
905 				scsi_end_request(cmd, 0, this_count, 1);
906 				return;
907 			}
908 			break;
909 		case NOT_READY:
910 			/* If the device is in the process of becoming
911 			 * ready, or has a temporary blockage, retry.
912 			 */
913 			if (sshdr.asc == 0x04) {
914 				switch (sshdr.ascq) {
915 				case 0x01: /* becoming ready */
916 				case 0x04: /* format in progress */
917 				case 0x05: /* rebuild in progress */
918 				case 0x06: /* recalculation in progress */
919 				case 0x07: /* operation in progress */
920 				case 0x08: /* Long write in progress */
921 				case 0x09: /* self test in progress */
922 					scsi_requeue_command(q, cmd);
923 					return;
924 				default:
925 					break;
926 				}
927 			}
928 			if (!(req->flags & REQ_QUIET)) {
929 				scmd_printk(KERN_INFO, cmd,
930 					    "Device not ready: ");
931 				scsi_print_sense_hdr("", &sshdr);
932 			}
933 			scsi_end_request(cmd, 0, this_count, 1);
934 			return;
935 		case VOLUME_OVERFLOW:
936 			if (!(req->flags & REQ_QUIET)) {
937 				scmd_printk(KERN_INFO, cmd,
938 					    "Volume overflow, CDB: ");
939 				__scsi_print_command(cmd->cmnd);
940 				scsi_print_sense("", cmd);
941 			}
942 			/* See SSC3rXX or current. */
943 			scsi_end_request(cmd, 0, this_count, 1);
944 			return;
945 		default:
946 			break;
947 		}
948 	}
949 	if (host_byte(result) == DID_RESET) {
950 		/* Third party bus reset or reset for error recovery
951 		 * reasons.  Just retry the request and see what
952 		 * happens.
953 		 */
954 		scsi_requeue_command(q, cmd);
955 		return;
956 	}
957 	if (result) {
958 		if (!(req->flags & REQ_QUIET)) {
959 			scmd_printk(KERN_INFO, cmd,
960 				    "SCSI error: return code = 0x%08x\n",
961 				    result);
962 			if (driver_byte(result) & DRIVER_SENSE)
963 				scsi_print_sense("", cmd);
964 		}
965 	}
966 	scsi_end_request(cmd, 0, this_count, !result);
967 }
968 EXPORT_SYMBOL(scsi_io_completion);
969 
970 /*
971  * Function:    scsi_init_io()
972  *
973  * Purpose:     SCSI I/O initialize function.
974  *
975  * Arguments:   cmd   - Command descriptor we wish to initialize
976  *
977  * Returns:     0 on success
978  *		BLKPREP_DEFER if the failure is retryable
979  *		BLKPREP_KILL if the failure is fatal
980  */
981 static int scsi_init_io(struct scsi_cmnd *cmd)
982 {
983 	struct request     *req = cmd->request;
984 	struct scatterlist *sgpnt;
985 	int		   count;
986 
987 	/*
988 	 * if this is a rq->data based REQ_BLOCK_PC, setup for a non-sg xfer
989 	 */
990 	if ((req->flags & REQ_BLOCK_PC) && !req->bio) {
991 		cmd->request_bufflen = req->data_len;
992 		cmd->request_buffer = req->data;
993 		req->buffer = req->data;
994 		cmd->use_sg = 0;
995 		return 0;
996 	}
997 
998 	/*
999 	 * we used to not use scatter-gather for single segment request,
1000 	 * but now we do (it makes highmem I/O easier to support without
1001 	 * kmapping pages)
1002 	 */
1003 	cmd->use_sg = req->nr_phys_segments;
1004 
1005 	/*
1006 	 * if sg table allocation fails, requeue request later.
1007 	 */
1008 	sgpnt = scsi_alloc_sgtable(cmd, GFP_ATOMIC);
1009 	if (unlikely(!sgpnt)) {
1010 		scsi_unprep_request(req);
1011 		return BLKPREP_DEFER;
1012 	}
1013 
1014 	cmd->request_buffer = (char *) sgpnt;
1015 	cmd->request_bufflen = req->nr_sectors << 9;
1016 	if (blk_pc_request(req))
1017 		cmd->request_bufflen = req->data_len;
1018 	req->buffer = NULL;
1019 
1020 	/*
1021 	 * Next, walk the list, and fill in the addresses and sizes of
1022 	 * each segment.
1023 	 */
1024 	count = blk_rq_map_sg(req->q, req, cmd->request_buffer);
1025 
1026 	/*
1027 	 * mapped well, send it off
1028 	 */
1029 	if (likely(count <= cmd->use_sg)) {
1030 		cmd->use_sg = count;
1031 		return 0;
1032 	}
1033 
1034 	printk(KERN_ERR "Incorrect number of segments after building list\n");
1035 	printk(KERN_ERR "counted %d, received %d\n", count, cmd->use_sg);
1036 	printk(KERN_ERR "req nr_sec %lu, cur_nr_sec %u\n", req->nr_sectors,
1037 			req->current_nr_sectors);
1038 
1039 	/* release the command and kill it */
1040 	scsi_release_buffers(cmd);
1041 	scsi_put_command(cmd);
1042 	return BLKPREP_KILL;
1043 }
1044 
1045 static int scsi_issue_flush_fn(request_queue_t *q, struct gendisk *disk,
1046 			       sector_t *error_sector)
1047 {
1048 	struct scsi_device *sdev = q->queuedata;
1049 	struct scsi_driver *drv;
1050 
1051 	if (sdev->sdev_state != SDEV_RUNNING)
1052 		return -ENXIO;
1053 
1054 	drv = *(struct scsi_driver **) disk->private_data;
1055 	if (drv->issue_flush)
1056 		return drv->issue_flush(&sdev->sdev_gendev, error_sector);
1057 
1058 	return -EOPNOTSUPP;
1059 }
1060 
1061 static void scsi_blk_pc_done(struct scsi_cmnd *cmd)
1062 {
1063 	BUG_ON(!blk_pc_request(cmd->request));
1064 	/*
1065 	 * This will complete the whole command with uptodate=1 so
1066 	 * as far as the block layer is concerned the command completed
1067 	 * successfully. Since this is a REQ_BLOCK_PC command the
1068 	 * caller should check the request's errors value
1069 	 */
1070 	scsi_io_completion(cmd, cmd->request_bufflen);
1071 }
1072 
1073 static void scsi_setup_blk_pc_cmnd(struct scsi_cmnd *cmd)
1074 {
1075 	struct request *req = cmd->request;
1076 
1077 	BUG_ON(sizeof(req->cmd) > sizeof(cmd->cmnd));
1078 	memcpy(cmd->cmnd, req->cmd, sizeof(cmd->cmnd));
1079 	cmd->cmd_len = req->cmd_len;
1080 	if (!req->data_len)
1081 		cmd->sc_data_direction = DMA_NONE;
1082 	else if (rq_data_dir(req) == WRITE)
1083 		cmd->sc_data_direction = DMA_TO_DEVICE;
1084 	else
1085 		cmd->sc_data_direction = DMA_FROM_DEVICE;
1086 
1087 	cmd->transfersize = req->data_len;
1088 	cmd->allowed = req->retries;
1089 	cmd->timeout_per_command = req->timeout;
1090 	cmd->done = scsi_blk_pc_done;
1091 }
1092 
1093 static int scsi_prep_fn(struct request_queue *q, struct request *req)
1094 {
1095 	struct scsi_device *sdev = q->queuedata;
1096 	struct scsi_cmnd *cmd;
1097 	int specials_only = 0;
1098 
1099 	/*
1100 	 * Just check to see if the device is online.  If it isn't, we
1101 	 * refuse to process any commands.  The device must be brought
1102 	 * online before trying any recovery commands
1103 	 */
1104 	if (unlikely(!scsi_device_online(sdev))) {
1105 		sdev_printk(KERN_ERR, sdev,
1106 			    "rejecting I/O to offline device\n");
1107 		goto kill;
1108 	}
1109 	if (unlikely(sdev->sdev_state != SDEV_RUNNING)) {
1110 		/* OK, we're not in a running state don't prep
1111 		 * user commands */
1112 		if (sdev->sdev_state == SDEV_DEL) {
1113 			/* Device is fully deleted, no commands
1114 			 * at all allowed down */
1115 			sdev_printk(KERN_ERR, sdev,
1116 				    "rejecting I/O to dead device\n");
1117 			goto kill;
1118 		}
1119 		/* OK, we only allow special commands (i.e. not
1120 		 * user initiated ones */
1121 		specials_only = sdev->sdev_state;
1122 	}
1123 
1124 	/*
1125 	 * Find the actual device driver associated with this command.
1126 	 * The SPECIAL requests are things like character device or
1127 	 * ioctls, which did not originate from ll_rw_blk.  Note that
1128 	 * the special field is also used to indicate the cmd for
1129 	 * the remainder of a partially fulfilled request that can
1130 	 * come up when there is a medium error.  We have to treat
1131 	 * these two cases differently.  We differentiate by looking
1132 	 * at request->cmd, as this tells us the real story.
1133 	 */
1134 	if (req->flags & REQ_SPECIAL && req->special) {
1135 		cmd = req->special;
1136 	} else if (req->flags & (REQ_CMD | REQ_BLOCK_PC)) {
1137 
1138 		if(unlikely(specials_only) && !(req->flags & REQ_SPECIAL)) {
1139 			if(specials_only == SDEV_QUIESCE ||
1140 					specials_only == SDEV_BLOCK)
1141 				goto defer;
1142 
1143 			sdev_printk(KERN_ERR, sdev,
1144 				    "rejecting I/O to device being removed\n");
1145 			goto kill;
1146 		}
1147 
1148 
1149 		/*
1150 		 * Now try and find a command block that we can use.
1151 		 */
1152 		if (!req->special) {
1153 			cmd = scsi_get_command(sdev, GFP_ATOMIC);
1154 			if (unlikely(!cmd))
1155 				goto defer;
1156 		} else
1157 			cmd = req->special;
1158 
1159 		/* pull a tag out of the request if we have one */
1160 		cmd->tag = req->tag;
1161 	} else {
1162 		blk_dump_rq_flags(req, "SCSI bad req");
1163 		goto kill;
1164 	}
1165 
1166 	/* note the overloading of req->special.  When the tag
1167 	 * is active it always means cmd.  If the tag goes
1168 	 * back for re-queueing, it may be reset */
1169 	req->special = cmd;
1170 	cmd->request = req;
1171 
1172 	/*
1173 	 * FIXME: drop the lock here because the functions below
1174 	 * expect to be called without the queue lock held.  Also,
1175 	 * previously, we dequeued the request before dropping the
1176 	 * lock.  We hope REQ_STARTED prevents anything untoward from
1177 	 * happening now.
1178 	 */
1179 	if (req->flags & (REQ_CMD | REQ_BLOCK_PC)) {
1180 		int ret;
1181 
1182 		/*
1183 		 * This will do a couple of things:
1184 		 *  1) Fill in the actual SCSI command.
1185 		 *  2) Fill in any other upper-level specific fields
1186 		 * (timeout).
1187 		 *
1188 		 * If this returns 0, it means that the request failed
1189 		 * (reading past end of disk, reading offline device,
1190 		 * etc).   This won't actually talk to the device, but
1191 		 * some kinds of consistency checking may cause the
1192 		 * request to be rejected immediately.
1193 		 */
1194 
1195 		/*
1196 		 * This sets up the scatter-gather table (allocating if
1197 		 * required).
1198 		 */
1199 		ret = scsi_init_io(cmd);
1200 		switch(ret) {
1201 			/* For BLKPREP_KILL/DEFER the cmd was released */
1202 		case BLKPREP_KILL:
1203 			goto kill;
1204 		case BLKPREP_DEFER:
1205 			goto defer;
1206 		}
1207 
1208 		/*
1209 		 * Initialize the actual SCSI command for this request.
1210 		 */
1211 		if (req->flags & REQ_BLOCK_PC) {
1212 			scsi_setup_blk_pc_cmnd(cmd);
1213 		} else if (req->rq_disk) {
1214 			struct scsi_driver *drv;
1215 
1216 			drv = *(struct scsi_driver **)req->rq_disk->private_data;
1217 			if (unlikely(!drv->init_command(cmd))) {
1218 				scsi_release_buffers(cmd);
1219 				scsi_put_command(cmd);
1220 				goto kill;
1221 			}
1222 		}
1223 	}
1224 
1225 	/*
1226 	 * The request is now prepped, no need to come back here
1227 	 */
1228 	req->flags |= REQ_DONTPREP;
1229 	return BLKPREP_OK;
1230 
1231  defer:
1232 	/* If we defer, the elv_next_request() returns NULL, but the
1233 	 * queue must be restarted, so we plug here if no returning
1234 	 * command will automatically do that. */
1235 	if (sdev->device_busy == 0)
1236 		blk_plug_device(q);
1237 	return BLKPREP_DEFER;
1238  kill:
1239 	req->errors = DID_NO_CONNECT << 16;
1240 	return BLKPREP_KILL;
1241 }
1242 
1243 /*
1244  * scsi_dev_queue_ready: if we can send requests to sdev, return 1 else
1245  * return 0.
1246  *
1247  * Called with the queue_lock held.
1248  */
1249 static inline int scsi_dev_queue_ready(struct request_queue *q,
1250 				  struct scsi_device *sdev)
1251 {
1252 	if (sdev->device_busy >= sdev->queue_depth)
1253 		return 0;
1254 	if (sdev->device_busy == 0 && sdev->device_blocked) {
1255 		/*
1256 		 * unblock after device_blocked iterates to zero
1257 		 */
1258 		if (--sdev->device_blocked == 0) {
1259 			SCSI_LOG_MLQUEUE(3,
1260 				   sdev_printk(KERN_INFO, sdev,
1261 				   "unblocking device at zero depth\n"));
1262 		} else {
1263 			blk_plug_device(q);
1264 			return 0;
1265 		}
1266 	}
1267 	if (sdev->device_blocked)
1268 		return 0;
1269 
1270 	return 1;
1271 }
1272 
1273 /*
1274  * scsi_host_queue_ready: if we can send requests to shost, return 1 else
1275  * return 0. We must end up running the queue again whenever 0 is
1276  * returned, else IO can hang.
1277  *
1278  * Called with host_lock held.
1279  */
1280 static inline int scsi_host_queue_ready(struct request_queue *q,
1281 				   struct Scsi_Host *shost,
1282 				   struct scsi_device *sdev)
1283 {
1284 	if (scsi_host_in_recovery(shost))
1285 		return 0;
1286 	if (shost->host_busy == 0 && shost->host_blocked) {
1287 		/*
1288 		 * unblock after host_blocked iterates to zero
1289 		 */
1290 		if (--shost->host_blocked == 0) {
1291 			SCSI_LOG_MLQUEUE(3,
1292 				printk("scsi%d unblocking host at zero depth\n",
1293 					shost->host_no));
1294 		} else {
1295 			blk_plug_device(q);
1296 			return 0;
1297 		}
1298 	}
1299 	if ((shost->can_queue > 0 && shost->host_busy >= shost->can_queue) ||
1300 	    shost->host_blocked || shost->host_self_blocked) {
1301 		if (list_empty(&sdev->starved_entry))
1302 			list_add_tail(&sdev->starved_entry, &shost->starved_list);
1303 		return 0;
1304 	}
1305 
1306 	/* We're OK to process the command, so we can't be starved */
1307 	if (!list_empty(&sdev->starved_entry))
1308 		list_del_init(&sdev->starved_entry);
1309 
1310 	return 1;
1311 }
1312 
1313 /*
1314  * Kill a request for a dead device
1315  */
1316 static void scsi_kill_request(struct request *req, request_queue_t *q)
1317 {
1318 	struct scsi_cmnd *cmd = req->special;
1319 	struct scsi_device *sdev = cmd->device;
1320 	struct Scsi_Host *shost = sdev->host;
1321 
1322 	blkdev_dequeue_request(req);
1323 
1324 	if (unlikely(cmd == NULL)) {
1325 		printk(KERN_CRIT "impossible request in %s.\n",
1326 				 __FUNCTION__);
1327 		BUG();
1328 	}
1329 
1330 	scsi_init_cmd_errh(cmd);
1331 	cmd->result = DID_NO_CONNECT << 16;
1332 	atomic_inc(&cmd->device->iorequest_cnt);
1333 
1334 	/*
1335 	 * SCSI request completion path will do scsi_device_unbusy(),
1336 	 * bump busy counts.  To bump the counters, we need to dance
1337 	 * with the locks as normal issue path does.
1338 	 */
1339 	sdev->device_busy++;
1340 	spin_unlock(sdev->request_queue->queue_lock);
1341 	spin_lock(shost->host_lock);
1342 	shost->host_busy++;
1343 	spin_unlock(shost->host_lock);
1344 	spin_lock(sdev->request_queue->queue_lock);
1345 
1346 	__scsi_done(cmd);
1347 }
1348 
1349 static void scsi_softirq_done(struct request *rq)
1350 {
1351 	struct scsi_cmnd *cmd = rq->completion_data;
1352 	unsigned long wait_for = (cmd->allowed + 1) * cmd->timeout_per_command;
1353 	int disposition;
1354 
1355 	INIT_LIST_HEAD(&cmd->eh_entry);
1356 
1357 	disposition = scsi_decide_disposition(cmd);
1358 	if (disposition != SUCCESS &&
1359 	    time_before(cmd->jiffies_at_alloc + wait_for, jiffies)) {
1360 		sdev_printk(KERN_ERR, cmd->device,
1361 			    "timing out command, waited %lus\n",
1362 			    wait_for/HZ);
1363 		disposition = SUCCESS;
1364 	}
1365 
1366 	scsi_log_completion(cmd, disposition);
1367 
1368 	switch (disposition) {
1369 		case SUCCESS:
1370 			scsi_finish_command(cmd);
1371 			break;
1372 		case NEEDS_RETRY:
1373 			scsi_retry_command(cmd);
1374 			break;
1375 		case ADD_TO_MLQUEUE:
1376 			scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY);
1377 			break;
1378 		default:
1379 			if (!scsi_eh_scmd_add(cmd, 0))
1380 				scsi_finish_command(cmd);
1381 	}
1382 }
1383 
1384 /*
1385  * Function:    scsi_request_fn()
1386  *
1387  * Purpose:     Main strategy routine for SCSI.
1388  *
1389  * Arguments:   q       - Pointer to actual queue.
1390  *
1391  * Returns:     Nothing
1392  *
1393  * Lock status: IO request lock assumed to be held when called.
1394  */
1395 static void scsi_request_fn(struct request_queue *q)
1396 {
1397 	struct scsi_device *sdev = q->queuedata;
1398 	struct Scsi_Host *shost;
1399 	struct scsi_cmnd *cmd;
1400 	struct request *req;
1401 
1402 	if (!sdev) {
1403 		printk("scsi: killing requests for dead queue\n");
1404 		while ((req = elv_next_request(q)) != NULL)
1405 			scsi_kill_request(req, q);
1406 		return;
1407 	}
1408 
1409 	if(!get_device(&sdev->sdev_gendev))
1410 		/* We must be tearing the block queue down already */
1411 		return;
1412 
1413 	/*
1414 	 * To start with, we keep looping until the queue is empty, or until
1415 	 * the host is no longer able to accept any more requests.
1416 	 */
1417 	shost = sdev->host;
1418 	while (!blk_queue_plugged(q)) {
1419 		int rtn;
1420 		/*
1421 		 * get next queueable request.  We do this early to make sure
1422 		 * that the request is fully prepared even if we cannot
1423 		 * accept it.
1424 		 */
1425 		req = elv_next_request(q);
1426 		if (!req || !scsi_dev_queue_ready(q, sdev))
1427 			break;
1428 
1429 		if (unlikely(!scsi_device_online(sdev))) {
1430 			sdev_printk(KERN_ERR, sdev,
1431 				    "rejecting I/O to offline device\n");
1432 			scsi_kill_request(req, q);
1433 			continue;
1434 		}
1435 
1436 
1437 		/*
1438 		 * Remove the request from the request list.
1439 		 */
1440 		if (!(blk_queue_tagged(q) && !blk_queue_start_tag(q, req)))
1441 			blkdev_dequeue_request(req);
1442 		sdev->device_busy++;
1443 
1444 		spin_unlock(q->queue_lock);
1445 		cmd = req->special;
1446 		if (unlikely(cmd == NULL)) {
1447 			printk(KERN_CRIT "impossible request in %s.\n"
1448 					 "please mail a stack trace to "
1449 					 "linux-scsi@vger.kernel.org",
1450 					 __FUNCTION__);
1451 			BUG();
1452 		}
1453 		spin_lock(shost->host_lock);
1454 
1455 		if (!scsi_host_queue_ready(q, shost, sdev))
1456 			goto not_ready;
1457 		if (sdev->single_lun) {
1458 			if (scsi_target(sdev)->starget_sdev_user &&
1459 			    scsi_target(sdev)->starget_sdev_user != sdev)
1460 				goto not_ready;
1461 			scsi_target(sdev)->starget_sdev_user = sdev;
1462 		}
1463 		shost->host_busy++;
1464 
1465 		/*
1466 		 * XXX(hch): This is rather suboptimal, scsi_dispatch_cmd will
1467 		 *		take the lock again.
1468 		 */
1469 		spin_unlock_irq(shost->host_lock);
1470 
1471 		/*
1472 		 * Finally, initialize any error handling parameters, and set up
1473 		 * the timers for timeouts.
1474 		 */
1475 		scsi_init_cmd_errh(cmd);
1476 
1477 		/*
1478 		 * Dispatch the command to the low-level driver.
1479 		 */
1480 		rtn = scsi_dispatch_cmd(cmd);
1481 		spin_lock_irq(q->queue_lock);
1482 		if(rtn) {
1483 			/* we're refusing the command; because of
1484 			 * the way locks get dropped, we need to
1485 			 * check here if plugging is required */
1486 			if(sdev->device_busy == 0)
1487 				blk_plug_device(q);
1488 
1489 			break;
1490 		}
1491 	}
1492 
1493 	goto out;
1494 
1495  not_ready:
1496 	spin_unlock_irq(shost->host_lock);
1497 
1498 	/*
1499 	 * lock q, handle tag, requeue req, and decrement device_busy. We
1500 	 * must return with queue_lock held.
1501 	 *
1502 	 * Decrementing device_busy without checking it is OK, as all such
1503 	 * cases (host limits or settings) should run the queue at some
1504 	 * later time.
1505 	 */
1506 	spin_lock_irq(q->queue_lock);
1507 	blk_requeue_request(q, req);
1508 	sdev->device_busy--;
1509 	if(sdev->device_busy == 0)
1510 		blk_plug_device(q);
1511  out:
1512 	/* must be careful here...if we trigger the ->remove() function
1513 	 * we cannot be holding the q lock */
1514 	spin_unlock_irq(q->queue_lock);
1515 	put_device(&sdev->sdev_gendev);
1516 	spin_lock_irq(q->queue_lock);
1517 }
1518 
1519 u64 scsi_calculate_bounce_limit(struct Scsi_Host *shost)
1520 {
1521 	struct device *host_dev;
1522 	u64 bounce_limit = 0xffffffff;
1523 
1524 	if (shost->unchecked_isa_dma)
1525 		return BLK_BOUNCE_ISA;
1526 	/*
1527 	 * Platforms with virtual-DMA translation
1528 	 * hardware have no practical limit.
1529 	 */
1530 	if (!PCI_DMA_BUS_IS_PHYS)
1531 		return BLK_BOUNCE_ANY;
1532 
1533 	host_dev = scsi_get_device(shost);
1534 	if (host_dev && host_dev->dma_mask)
1535 		bounce_limit = *host_dev->dma_mask;
1536 
1537 	return bounce_limit;
1538 }
1539 EXPORT_SYMBOL(scsi_calculate_bounce_limit);
1540 
1541 struct request_queue *scsi_alloc_queue(struct scsi_device *sdev)
1542 {
1543 	struct Scsi_Host *shost = sdev->host;
1544 	struct request_queue *q;
1545 
1546 	q = blk_init_queue(scsi_request_fn, NULL);
1547 	if (!q)
1548 		return NULL;
1549 
1550 	blk_queue_prep_rq(q, scsi_prep_fn);
1551 
1552 	blk_queue_max_hw_segments(q, shost->sg_tablesize);
1553 	blk_queue_max_phys_segments(q, SCSI_MAX_PHYS_SEGMENTS);
1554 	blk_queue_max_sectors(q, shost->max_sectors);
1555 	blk_queue_bounce_limit(q, scsi_calculate_bounce_limit(shost));
1556 	blk_queue_segment_boundary(q, shost->dma_boundary);
1557 	blk_queue_issue_flush_fn(q, scsi_issue_flush_fn);
1558 	blk_queue_softirq_done(q, scsi_softirq_done);
1559 
1560 	if (!shost->use_clustering)
1561 		clear_bit(QUEUE_FLAG_CLUSTER, &q->queue_flags);
1562 	return q;
1563 }
1564 
1565 void scsi_free_queue(struct request_queue *q)
1566 {
1567 	blk_cleanup_queue(q);
1568 }
1569 
1570 /*
1571  * Function:    scsi_block_requests()
1572  *
1573  * Purpose:     Utility function used by low-level drivers to prevent further
1574  *		commands from being queued to the device.
1575  *
1576  * Arguments:   shost       - Host in question
1577  *
1578  * Returns:     Nothing
1579  *
1580  * Lock status: No locks are assumed held.
1581  *
1582  * Notes:       There is no timer nor any other means by which the requests
1583  *		get unblocked other than the low-level driver calling
1584  *		scsi_unblock_requests().
1585  */
1586 void scsi_block_requests(struct Scsi_Host *shost)
1587 {
1588 	shost->host_self_blocked = 1;
1589 }
1590 EXPORT_SYMBOL(scsi_block_requests);
1591 
1592 /*
1593  * Function:    scsi_unblock_requests()
1594  *
1595  * Purpose:     Utility function used by low-level drivers to allow further
1596  *		commands from being queued to the device.
1597  *
1598  * Arguments:   shost       - Host in question
1599  *
1600  * Returns:     Nothing
1601  *
1602  * Lock status: No locks are assumed held.
1603  *
1604  * Notes:       There is no timer nor any other means by which the requests
1605  *		get unblocked other than the low-level driver calling
1606  *		scsi_unblock_requests().
1607  *
1608  *		This is done as an API function so that changes to the
1609  *		internals of the scsi mid-layer won't require wholesale
1610  *		changes to drivers that use this feature.
1611  */
1612 void scsi_unblock_requests(struct Scsi_Host *shost)
1613 {
1614 	shost->host_self_blocked = 0;
1615 	scsi_run_host_queues(shost);
1616 }
1617 EXPORT_SYMBOL(scsi_unblock_requests);
1618 
1619 int __init scsi_init_queue(void)
1620 {
1621 	int i;
1622 
1623 	scsi_io_context_cache = kmem_cache_create("scsi_io_context",
1624 					sizeof(struct scsi_io_context),
1625 					0, 0, NULL, NULL);
1626 	if (!scsi_io_context_cache) {
1627 		printk(KERN_ERR "SCSI: can't init scsi io context cache\n");
1628 		return -ENOMEM;
1629 	}
1630 
1631 	for (i = 0; i < SG_MEMPOOL_NR; i++) {
1632 		struct scsi_host_sg_pool *sgp = scsi_sg_pools + i;
1633 		int size = sgp->size * sizeof(struct scatterlist);
1634 
1635 		sgp->slab = kmem_cache_create(sgp->name, size, 0,
1636 				SLAB_HWCACHE_ALIGN, NULL, NULL);
1637 		if (!sgp->slab) {
1638 			printk(KERN_ERR "SCSI: can't init sg slab %s\n",
1639 					sgp->name);
1640 		}
1641 
1642 		sgp->pool = mempool_create_slab_pool(SG_MEMPOOL_SIZE,
1643 						     sgp->slab);
1644 		if (!sgp->pool) {
1645 			printk(KERN_ERR "SCSI: can't init sg mempool %s\n",
1646 					sgp->name);
1647 		}
1648 	}
1649 
1650 	return 0;
1651 }
1652 
1653 void scsi_exit_queue(void)
1654 {
1655 	int i;
1656 
1657 	kmem_cache_destroy(scsi_io_context_cache);
1658 
1659 	for (i = 0; i < SG_MEMPOOL_NR; i++) {
1660 		struct scsi_host_sg_pool *sgp = scsi_sg_pools + i;
1661 		mempool_destroy(sgp->pool);
1662 		kmem_cache_destroy(sgp->slab);
1663 	}
1664 }
1665 
1666 /**
1667  *	scsi_mode_select - issue a mode select
1668  *	@sdev:	SCSI device to be queried
1669  *	@pf:	Page format bit (1 == standard, 0 == vendor specific)
1670  *	@sp:	Save page bit (0 == don't save, 1 == save)
1671  *	@modepage: mode page being requested
1672  *	@buffer: request buffer (may not be smaller than eight bytes)
1673  *	@len:	length of request buffer.
1674  *	@timeout: command timeout
1675  *	@retries: number of retries before failing
1676  *	@data: returns a structure abstracting the mode header data
1677  *	@sense: place to put sense data (or NULL if no sense to be collected).
1678  *		must be SCSI_SENSE_BUFFERSIZE big.
1679  *
1680  *	Returns zero if successful; negative error number or scsi
1681  *	status on error
1682  *
1683  */
1684 int
1685 scsi_mode_select(struct scsi_device *sdev, int pf, int sp, int modepage,
1686 		 unsigned char *buffer, int len, int timeout, int retries,
1687 		 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
1688 {
1689 	unsigned char cmd[10];
1690 	unsigned char *real_buffer;
1691 	int ret;
1692 
1693 	memset(cmd, 0, sizeof(cmd));
1694 	cmd[1] = (pf ? 0x10 : 0) | (sp ? 0x01 : 0);
1695 
1696 	if (sdev->use_10_for_ms) {
1697 		if (len > 65535)
1698 			return -EINVAL;
1699 		real_buffer = kmalloc(8 + len, GFP_KERNEL);
1700 		if (!real_buffer)
1701 			return -ENOMEM;
1702 		memcpy(real_buffer + 8, buffer, len);
1703 		len += 8;
1704 		real_buffer[0] = 0;
1705 		real_buffer[1] = 0;
1706 		real_buffer[2] = data->medium_type;
1707 		real_buffer[3] = data->device_specific;
1708 		real_buffer[4] = data->longlba ? 0x01 : 0;
1709 		real_buffer[5] = 0;
1710 		real_buffer[6] = data->block_descriptor_length >> 8;
1711 		real_buffer[7] = data->block_descriptor_length;
1712 
1713 		cmd[0] = MODE_SELECT_10;
1714 		cmd[7] = len >> 8;
1715 		cmd[8] = len;
1716 	} else {
1717 		if (len > 255 || data->block_descriptor_length > 255 ||
1718 		    data->longlba)
1719 			return -EINVAL;
1720 
1721 		real_buffer = kmalloc(4 + len, GFP_KERNEL);
1722 		if (!real_buffer)
1723 			return -ENOMEM;
1724 		memcpy(real_buffer + 4, buffer, len);
1725 		len += 4;
1726 		real_buffer[0] = 0;
1727 		real_buffer[1] = data->medium_type;
1728 		real_buffer[2] = data->device_specific;
1729 		real_buffer[3] = data->block_descriptor_length;
1730 
1731 
1732 		cmd[0] = MODE_SELECT;
1733 		cmd[4] = len;
1734 	}
1735 
1736 	ret = scsi_execute_req(sdev, cmd, DMA_TO_DEVICE, real_buffer, len,
1737 			       sshdr, timeout, retries);
1738 	kfree(real_buffer);
1739 	return ret;
1740 }
1741 EXPORT_SYMBOL_GPL(scsi_mode_select);
1742 
1743 /**
1744  *	scsi_mode_sense - issue a mode sense, falling back from 10 to
1745  *		six bytes if necessary.
1746  *	@sdev:	SCSI device to be queried
1747  *	@dbd:	set if mode sense will allow block descriptors to be returned
1748  *	@modepage: mode page being requested
1749  *	@buffer: request buffer (may not be smaller than eight bytes)
1750  *	@len:	length of request buffer.
1751  *	@timeout: command timeout
1752  *	@retries: number of retries before failing
1753  *	@data: returns a structure abstracting the mode header data
1754  *	@sense: place to put sense data (or NULL if no sense to be collected).
1755  *		must be SCSI_SENSE_BUFFERSIZE big.
1756  *
1757  *	Returns zero if unsuccessful, or the header offset (either 4
1758  *	or 8 depending on whether a six or ten byte command was
1759  *	issued) if successful.
1760  **/
1761 int
1762 scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage,
1763 		  unsigned char *buffer, int len, int timeout, int retries,
1764 		  struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
1765 {
1766 	unsigned char cmd[12];
1767 	int use_10_for_ms;
1768 	int header_length;
1769 	int result;
1770 	struct scsi_sense_hdr my_sshdr;
1771 
1772 	memset(data, 0, sizeof(*data));
1773 	memset(&cmd[0], 0, 12);
1774 	cmd[1] = dbd & 0x18;	/* allows DBD and LLBA bits */
1775 	cmd[2] = modepage;
1776 
1777 	/* caller might not be interested in sense, but we need it */
1778 	if (!sshdr)
1779 		sshdr = &my_sshdr;
1780 
1781  retry:
1782 	use_10_for_ms = sdev->use_10_for_ms;
1783 
1784 	if (use_10_for_ms) {
1785 		if (len < 8)
1786 			len = 8;
1787 
1788 		cmd[0] = MODE_SENSE_10;
1789 		cmd[8] = len;
1790 		header_length = 8;
1791 	} else {
1792 		if (len < 4)
1793 			len = 4;
1794 
1795 		cmd[0] = MODE_SENSE;
1796 		cmd[4] = len;
1797 		header_length = 4;
1798 	}
1799 
1800 	memset(buffer, 0, len);
1801 
1802 	result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer, len,
1803 				  sshdr, timeout, retries);
1804 
1805 	/* This code looks awful: what it's doing is making sure an
1806 	 * ILLEGAL REQUEST sense return identifies the actual command
1807 	 * byte as the problem.  MODE_SENSE commands can return
1808 	 * ILLEGAL REQUEST if the code page isn't supported */
1809 
1810 	if (use_10_for_ms && !scsi_status_is_good(result) &&
1811 	    (driver_byte(result) & DRIVER_SENSE)) {
1812 		if (scsi_sense_valid(sshdr)) {
1813 			if ((sshdr->sense_key == ILLEGAL_REQUEST) &&
1814 			    (sshdr->asc == 0x20) && (sshdr->ascq == 0)) {
1815 				/*
1816 				 * Invalid command operation code
1817 				 */
1818 				sdev->use_10_for_ms = 0;
1819 				goto retry;
1820 			}
1821 		}
1822 	}
1823 
1824 	if(scsi_status_is_good(result)) {
1825 		if (unlikely(buffer[0] == 0x86 && buffer[1] == 0x0b &&
1826 			     (modepage == 6 || modepage == 8))) {
1827 			/* Initio breakage? */
1828 			header_length = 0;
1829 			data->length = 13;
1830 			data->medium_type = 0;
1831 			data->device_specific = 0;
1832 			data->longlba = 0;
1833 			data->block_descriptor_length = 0;
1834 		} else if(use_10_for_ms) {
1835 			data->length = buffer[0]*256 + buffer[1] + 2;
1836 			data->medium_type = buffer[2];
1837 			data->device_specific = buffer[3];
1838 			data->longlba = buffer[4] & 0x01;
1839 			data->block_descriptor_length = buffer[6]*256
1840 				+ buffer[7];
1841 		} else {
1842 			data->length = buffer[0] + 1;
1843 			data->medium_type = buffer[1];
1844 			data->device_specific = buffer[2];
1845 			data->block_descriptor_length = buffer[3];
1846 		}
1847 		data->header_length = header_length;
1848 	}
1849 
1850 	return result;
1851 }
1852 EXPORT_SYMBOL(scsi_mode_sense);
1853 
1854 int
1855 scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries)
1856 {
1857 	char cmd[] = {
1858 		TEST_UNIT_READY, 0, 0, 0, 0, 0,
1859 	};
1860 	struct scsi_sense_hdr sshdr;
1861 	int result;
1862 
1863 	result = scsi_execute_req(sdev, cmd, DMA_NONE, NULL, 0, &sshdr,
1864 				  timeout, retries);
1865 
1866 	if ((driver_byte(result) & DRIVER_SENSE) && sdev->removable) {
1867 
1868 		if ((scsi_sense_valid(&sshdr)) &&
1869 		    ((sshdr.sense_key == UNIT_ATTENTION) ||
1870 		     (sshdr.sense_key == NOT_READY))) {
1871 			sdev->changed = 1;
1872 			result = 0;
1873 		}
1874 	}
1875 	return result;
1876 }
1877 EXPORT_SYMBOL(scsi_test_unit_ready);
1878 
1879 /**
1880  *	scsi_device_set_state - Take the given device through the device
1881  *		state model.
1882  *	@sdev:	scsi device to change the state of.
1883  *	@state:	state to change to.
1884  *
1885  *	Returns zero if unsuccessful or an error if the requested
1886  *	transition is illegal.
1887  **/
1888 int
1889 scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state)
1890 {
1891 	enum scsi_device_state oldstate = sdev->sdev_state;
1892 
1893 	if (state == oldstate)
1894 		return 0;
1895 
1896 	switch (state) {
1897 	case SDEV_CREATED:
1898 		/* There are no legal states that come back to
1899 		 * created.  This is the manually initialised start
1900 		 * state */
1901 		goto illegal;
1902 
1903 	case SDEV_RUNNING:
1904 		switch (oldstate) {
1905 		case SDEV_CREATED:
1906 		case SDEV_OFFLINE:
1907 		case SDEV_QUIESCE:
1908 		case SDEV_BLOCK:
1909 			break;
1910 		default:
1911 			goto illegal;
1912 		}
1913 		break;
1914 
1915 	case SDEV_QUIESCE:
1916 		switch (oldstate) {
1917 		case SDEV_RUNNING:
1918 		case SDEV_OFFLINE:
1919 			break;
1920 		default:
1921 			goto illegal;
1922 		}
1923 		break;
1924 
1925 	case SDEV_OFFLINE:
1926 		switch (oldstate) {
1927 		case SDEV_CREATED:
1928 		case SDEV_RUNNING:
1929 		case SDEV_QUIESCE:
1930 		case SDEV_BLOCK:
1931 			break;
1932 		default:
1933 			goto illegal;
1934 		}
1935 		break;
1936 
1937 	case SDEV_BLOCK:
1938 		switch (oldstate) {
1939 		case SDEV_CREATED:
1940 		case SDEV_RUNNING:
1941 			break;
1942 		default:
1943 			goto illegal;
1944 		}
1945 		break;
1946 
1947 	case SDEV_CANCEL:
1948 		switch (oldstate) {
1949 		case SDEV_CREATED:
1950 		case SDEV_RUNNING:
1951 		case SDEV_QUIESCE:
1952 		case SDEV_OFFLINE:
1953 		case SDEV_BLOCK:
1954 			break;
1955 		default:
1956 			goto illegal;
1957 		}
1958 		break;
1959 
1960 	case SDEV_DEL:
1961 		switch (oldstate) {
1962 		case SDEV_CREATED:
1963 		case SDEV_RUNNING:
1964 		case SDEV_OFFLINE:
1965 		case SDEV_CANCEL:
1966 			break;
1967 		default:
1968 			goto illegal;
1969 		}
1970 		break;
1971 
1972 	}
1973 	sdev->sdev_state = state;
1974 	return 0;
1975 
1976  illegal:
1977 	SCSI_LOG_ERROR_RECOVERY(1,
1978 				sdev_printk(KERN_ERR, sdev,
1979 					    "Illegal state transition %s->%s\n",
1980 					    scsi_device_state_name(oldstate),
1981 					    scsi_device_state_name(state))
1982 				);
1983 	return -EINVAL;
1984 }
1985 EXPORT_SYMBOL(scsi_device_set_state);
1986 
1987 /**
1988  *	scsi_device_quiesce - Block user issued commands.
1989  *	@sdev:	scsi device to quiesce.
1990  *
1991  *	This works by trying to transition to the SDEV_QUIESCE state
1992  *	(which must be a legal transition).  When the device is in this
1993  *	state, only special requests will be accepted, all others will
1994  *	be deferred.  Since special requests may also be requeued requests,
1995  *	a successful return doesn't guarantee the device will be
1996  *	totally quiescent.
1997  *
1998  *	Must be called with user context, may sleep.
1999  *
2000  *	Returns zero if unsuccessful or an error if not.
2001  **/
2002 int
2003 scsi_device_quiesce(struct scsi_device *sdev)
2004 {
2005 	int err = scsi_device_set_state(sdev, SDEV_QUIESCE);
2006 	if (err)
2007 		return err;
2008 
2009 	scsi_run_queue(sdev->request_queue);
2010 	while (sdev->device_busy) {
2011 		msleep_interruptible(200);
2012 		scsi_run_queue(sdev->request_queue);
2013 	}
2014 	return 0;
2015 }
2016 EXPORT_SYMBOL(scsi_device_quiesce);
2017 
2018 /**
2019  *	scsi_device_resume - Restart user issued commands to a quiesced device.
2020  *	@sdev:	scsi device to resume.
2021  *
2022  *	Moves the device from quiesced back to running and restarts the
2023  *	queues.
2024  *
2025  *	Must be called with user context, may sleep.
2026  **/
2027 void
2028 scsi_device_resume(struct scsi_device *sdev)
2029 {
2030 	if(scsi_device_set_state(sdev, SDEV_RUNNING))
2031 		return;
2032 	scsi_run_queue(sdev->request_queue);
2033 }
2034 EXPORT_SYMBOL(scsi_device_resume);
2035 
2036 static void
2037 device_quiesce_fn(struct scsi_device *sdev, void *data)
2038 {
2039 	scsi_device_quiesce(sdev);
2040 }
2041 
2042 void
2043 scsi_target_quiesce(struct scsi_target *starget)
2044 {
2045 	starget_for_each_device(starget, NULL, device_quiesce_fn);
2046 }
2047 EXPORT_SYMBOL(scsi_target_quiesce);
2048 
2049 static void
2050 device_resume_fn(struct scsi_device *sdev, void *data)
2051 {
2052 	scsi_device_resume(sdev);
2053 }
2054 
2055 void
2056 scsi_target_resume(struct scsi_target *starget)
2057 {
2058 	starget_for_each_device(starget, NULL, device_resume_fn);
2059 }
2060 EXPORT_SYMBOL(scsi_target_resume);
2061 
2062 /**
2063  * scsi_internal_device_block - internal function to put a device
2064  *				temporarily into the SDEV_BLOCK state
2065  * @sdev:	device to block
2066  *
2067  * Block request made by scsi lld's to temporarily stop all
2068  * scsi commands on the specified device.  Called from interrupt
2069  * or normal process context.
2070  *
2071  * Returns zero if successful or error if not
2072  *
2073  * Notes:
2074  *	This routine transitions the device to the SDEV_BLOCK state
2075  *	(which must be a legal transition).  When the device is in this
2076  *	state, all commands are deferred until the scsi lld reenables
2077  *	the device with scsi_device_unblock or device_block_tmo fires.
2078  *	This routine assumes the host_lock is held on entry.
2079  **/
2080 int
2081 scsi_internal_device_block(struct scsi_device *sdev)
2082 {
2083 	request_queue_t *q = sdev->request_queue;
2084 	unsigned long flags;
2085 	int err = 0;
2086 
2087 	err = scsi_device_set_state(sdev, SDEV_BLOCK);
2088 	if (err)
2089 		return err;
2090 
2091 	/*
2092 	 * The device has transitioned to SDEV_BLOCK.  Stop the
2093 	 * block layer from calling the midlayer with this device's
2094 	 * request queue.
2095 	 */
2096 	spin_lock_irqsave(q->queue_lock, flags);
2097 	blk_stop_queue(q);
2098 	spin_unlock_irqrestore(q->queue_lock, flags);
2099 
2100 	return 0;
2101 }
2102 EXPORT_SYMBOL_GPL(scsi_internal_device_block);
2103 
2104 /**
2105  * scsi_internal_device_unblock - resume a device after a block request
2106  * @sdev:	device to resume
2107  *
2108  * Called by scsi lld's or the midlayer to restart the device queue
2109  * for the previously suspended scsi device.  Called from interrupt or
2110  * normal process context.
2111  *
2112  * Returns zero if successful or error if not.
2113  *
2114  * Notes:
2115  *	This routine transitions the device to the SDEV_RUNNING state
2116  *	(which must be a legal transition) allowing the midlayer to
2117  *	goose the queue for this device.  This routine assumes the
2118  *	host_lock is held upon entry.
2119  **/
2120 int
2121 scsi_internal_device_unblock(struct scsi_device *sdev)
2122 {
2123 	request_queue_t *q = sdev->request_queue;
2124 	int err;
2125 	unsigned long flags;
2126 
2127 	/*
2128 	 * Try to transition the scsi device to SDEV_RUNNING
2129 	 * and goose the device queue if successful.
2130 	 */
2131 	err = scsi_device_set_state(sdev, SDEV_RUNNING);
2132 	if (err)
2133 		return err;
2134 
2135 	spin_lock_irqsave(q->queue_lock, flags);
2136 	blk_start_queue(q);
2137 	spin_unlock_irqrestore(q->queue_lock, flags);
2138 
2139 	return 0;
2140 }
2141 EXPORT_SYMBOL_GPL(scsi_internal_device_unblock);
2142 
2143 static void
2144 device_block(struct scsi_device *sdev, void *data)
2145 {
2146 	scsi_internal_device_block(sdev);
2147 }
2148 
2149 static int
2150 target_block(struct device *dev, void *data)
2151 {
2152 	if (scsi_is_target_device(dev))
2153 		starget_for_each_device(to_scsi_target(dev), NULL,
2154 					device_block);
2155 	return 0;
2156 }
2157 
2158 void
2159 scsi_target_block(struct device *dev)
2160 {
2161 	if (scsi_is_target_device(dev))
2162 		starget_for_each_device(to_scsi_target(dev), NULL,
2163 					device_block);
2164 	else
2165 		device_for_each_child(dev, NULL, target_block);
2166 }
2167 EXPORT_SYMBOL_GPL(scsi_target_block);
2168 
2169 static void
2170 device_unblock(struct scsi_device *sdev, void *data)
2171 {
2172 	scsi_internal_device_unblock(sdev);
2173 }
2174 
2175 static int
2176 target_unblock(struct device *dev, void *data)
2177 {
2178 	if (scsi_is_target_device(dev))
2179 		starget_for_each_device(to_scsi_target(dev), NULL,
2180 					device_unblock);
2181 	return 0;
2182 }
2183 
2184 void
2185 scsi_target_unblock(struct device *dev)
2186 {
2187 	if (scsi_is_target_device(dev))
2188 		starget_for_each_device(to_scsi_target(dev), NULL,
2189 					device_unblock);
2190 	else
2191 		device_for_each_child(dev, NULL, target_unblock);
2192 }
2193 EXPORT_SYMBOL_GPL(scsi_target_unblock);
2194 
2195 /**
2196  * scsi_kmap_atomic_sg - find and atomically map an sg-elemnt
2197  * @sg:		scatter-gather list
2198  * @sg_count:	number of segments in sg
2199  * @offset:	offset in bytes into sg, on return offset into the mapped area
2200  * @len:	bytes to map, on return number of bytes mapped
2201  *
2202  * Returns virtual address of the start of the mapped page
2203  */
2204 void *scsi_kmap_atomic_sg(struct scatterlist *sg, int sg_count,
2205 			  size_t *offset, size_t *len)
2206 {
2207 	int i;
2208 	size_t sg_len = 0, len_complete = 0;
2209 	struct page *page;
2210 
2211 	for (i = 0; i < sg_count; i++) {
2212 		len_complete = sg_len; /* Complete sg-entries */
2213 		sg_len += sg[i].length;
2214 		if (sg_len > *offset)
2215 			break;
2216 	}
2217 
2218 	if (unlikely(i == sg_count)) {
2219 		printk(KERN_ERR "%s: Bytes in sg: %zu, requested offset %zu, "
2220 			"elements %d\n",
2221 		       __FUNCTION__, sg_len, *offset, sg_count);
2222 		WARN_ON(1);
2223 		return NULL;
2224 	}
2225 
2226 	/* Offset starting from the beginning of first page in this sg-entry */
2227 	*offset = *offset - len_complete + sg[i].offset;
2228 
2229 	/* Assumption: contiguous pages can be accessed as "page + i" */
2230 	page = nth_page(sg[i].page, (*offset >> PAGE_SHIFT));
2231 	*offset &= ~PAGE_MASK;
2232 
2233 	/* Bytes in this sg-entry from *offset to the end of the page */
2234 	sg_len = PAGE_SIZE - *offset;
2235 	if (*len > sg_len)
2236 		*len = sg_len;
2237 
2238 	return kmap_atomic(page, KM_BIO_SRC_IRQ);
2239 }
2240 EXPORT_SYMBOL(scsi_kmap_atomic_sg);
2241 
2242 /**
2243  * scsi_kunmap_atomic_sg - atomically unmap a virtual address, previously
2244  *			   mapped with scsi_kmap_atomic_sg
2245  * @virt:	virtual address to be unmapped
2246  */
2247 void scsi_kunmap_atomic_sg(void *virt)
2248 {
2249 	kunmap_atomic(virt, KM_BIO_SRC_IRQ);
2250 }
2251 EXPORT_SYMBOL(scsi_kunmap_atomic_sg);
2252