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