]> git.proxmox.com Git - mirror_ubuntu-zesty-kernel.git/blame - drivers/scsi/scsi_lib.c
[SCSI] remove a useless get/put_device pair in scsi_next_command
[mirror_ubuntu-zesty-kernel.git] / drivers / scsi / scsi_lib.c
CommitLineData
1da177e4
LT
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>
d3f46f39 11#include <linux/bitops.h>
1da177e4
LT
12#include <linux/blkdev.h>
13#include <linux/completion.h>
14#include <linux/kernel.h>
09703660 15#include <linux/export.h>
1da177e4
LT
16#include <linux/mempool.h>
17#include <linux/slab.h>
18#include <linux/init.h>
19#include <linux/pci.h>
20#include <linux/delay.h>
faead26d 21#include <linux/hardirq.h>
c6132da1 22#include <linux/scatterlist.h>
1da177e4
LT
23
24#include <scsi/scsi.h>
beb40487 25#include <scsi/scsi_cmnd.h>
1da177e4
LT
26#include <scsi/scsi_dbg.h>
27#include <scsi/scsi_device.h>
28#include <scsi/scsi_driver.h>
29#include <scsi/scsi_eh.h>
30#include <scsi/scsi_host.h>
1da177e4
LT
31
32#include "scsi_priv.h"
33#include "scsi_logging.h"
34
35
6391a113 36#define SG_MEMPOOL_NR ARRAY_SIZE(scsi_sg_pools)
5972511b 37#define SG_MEMPOOL_SIZE 2
1da177e4
LT
38
39struct scsi_host_sg_pool {
40 size_t size;
a8474ce2 41 char *name;
e18b890b 42 struct kmem_cache *slab;
1da177e4
LT
43 mempool_t *pool;
44};
45
d3f46f39
JB
46#define SP(x) { x, "sgpool-" __stringify(x) }
47#if (SCSI_MAX_SG_SEGMENTS < 32)
48#error SCSI_MAX_SG_SEGMENTS is too small (must be 32 or greater)
49#endif
52c1da39 50static struct scsi_host_sg_pool scsi_sg_pools[] = {
1da177e4
LT
51 SP(8),
52 SP(16),
fd820f40 53#if (SCSI_MAX_SG_SEGMENTS > 32)
d3f46f39 54 SP(32),
fd820f40 55#if (SCSI_MAX_SG_SEGMENTS > 64)
d3f46f39
JB
56 SP(64),
57#if (SCSI_MAX_SG_SEGMENTS > 128)
1da177e4 58 SP(128),
d3f46f39
JB
59#if (SCSI_MAX_SG_SEGMENTS > 256)
60#error SCSI_MAX_SG_SEGMENTS is too large (256 MAX)
fd820f40
FT
61#endif
62#endif
63#endif
d3f46f39
JB
64#endif
65 SP(SCSI_MAX_SG_SEGMENTS)
a8474ce2 66};
1da177e4
LT
67#undef SP
68
7027ad72 69struct kmem_cache *scsi_sdb_cache;
6f9a35e2 70
a488e749
JA
71/*
72 * When to reinvoke queueing after a resource shortage. It's 3 msecs to
73 * not change behaviour from the previous unplug mechanism, experimentation
74 * may prove this needs changing.
75 */
76#define SCSI_QUEUE_DELAY 3
77
e91442b6
JB
78/*
79 * Function: scsi_unprep_request()
80 *
81 * Purpose: Remove all preparation done for a request, including its
82 * associated scsi_cmnd, so that it can be requeued.
83 *
84 * Arguments: req - request to unprepare
85 *
86 * Lock status: Assumed that no locks are held upon entry.
87 *
88 * Returns: Nothing.
89 */
90static void scsi_unprep_request(struct request *req)
91{
92 struct scsi_cmnd *cmd = req->special;
93
28018c24 94 blk_unprep_request(req);
beb40487 95 req->special = NULL;
e91442b6 96
e91442b6 97 scsi_put_command(cmd);
04796336 98 put_device(&cmd->device->sdev_gendev);
e91442b6 99}
a1bf9d1d 100
4f5299ac
JB
101/**
102 * __scsi_queue_insert - private queue insertion
103 * @cmd: The SCSI command being requeued
104 * @reason: The reason for the requeue
105 * @unbusy: Whether the queue should be unbusied
1da177e4 106 *
4f5299ac
JB
107 * This is a private queue insertion. The public interface
108 * scsi_queue_insert() always assumes the queue should be unbusied
109 * because it's always called before the completion. This function is
110 * for a requeue after completion, which should only occur in this
111 * file.
1da177e4 112 */
84feb166 113static void __scsi_queue_insert(struct scsi_cmnd *cmd, int reason, int unbusy)
1da177e4
LT
114{
115 struct Scsi_Host *host = cmd->device->host;
116 struct scsi_device *device = cmd->device;
f0c0a376 117 struct scsi_target *starget = scsi_target(device);
a1bf9d1d
TH
118 struct request_queue *q = device->request_queue;
119 unsigned long flags;
1da177e4
LT
120
121 SCSI_LOG_MLQUEUE(1,
122 printk("Inserting command %p into mlqueue\n", cmd));
123
124 /*
d8c37e7b 125 * Set the appropriate busy bit for the device/host.
1da177e4
LT
126 *
127 * If the host/device isn't busy, assume that something actually
128 * completed, and that we should be able to queue a command now.
129 *
130 * Note that the prior mid-layer assumption that any host could
131 * always queue at least one command is now broken. The mid-layer
132 * will implement a user specifiable stall (see
133 * scsi_host.max_host_blocked and scsi_device.max_device_blocked)
134 * if a command is requeued with no other commands outstanding
135 * either for the device or for the host.
136 */
f0c0a376
MC
137 switch (reason) {
138 case SCSI_MLQUEUE_HOST_BUSY:
1da177e4 139 host->host_blocked = host->max_host_blocked;
f0c0a376
MC
140 break;
141 case SCSI_MLQUEUE_DEVICE_BUSY:
573e5913 142 case SCSI_MLQUEUE_EH_RETRY:
1da177e4 143 device->device_blocked = device->max_device_blocked;
f0c0a376
MC
144 break;
145 case SCSI_MLQUEUE_TARGET_BUSY:
146 starget->target_blocked = starget->max_target_blocked;
147 break;
148 }
1da177e4 149
1da177e4
LT
150 /*
151 * Decrement the counters, since these commands are no longer
152 * active on the host/device.
153 */
4f5299ac
JB
154 if (unbusy)
155 scsi_device_unbusy(device);
1da177e4
LT
156
157 /*
a1bf9d1d 158 * Requeue this command. It will go before all other commands
b485462a
BVA
159 * that are already in the queue. Schedule requeue work under
160 * lock such that the kblockd_schedule_work() call happens
161 * before blk_cleanup_queue() finishes.
a488e749 162 */
a1bf9d1d 163 spin_lock_irqsave(q->queue_lock, flags);
59897dad 164 blk_requeue_request(q, cmd->request);
9937a5e2 165 kblockd_schedule_work(q, &device->requeue_work);
b485462a 166 spin_unlock_irqrestore(q->queue_lock, flags);
1da177e4
LT
167}
168
4f5299ac
JB
169/*
170 * Function: scsi_queue_insert()
171 *
172 * Purpose: Insert a command in the midlevel queue.
173 *
174 * Arguments: cmd - command that we are adding to queue.
175 * reason - why we are inserting command to queue.
176 *
177 * Lock status: Assumed that lock is not held upon entry.
178 *
179 * Returns: Nothing.
180 *
181 * Notes: We do this for one of two cases. Either the host is busy
182 * and it cannot accept any more commands for the time being,
183 * or the device returned QUEUE_FULL and can accept no more
184 * commands.
185 * Notes: This could be called either from an interrupt context or a
186 * normal process context.
187 */
84feb166 188void scsi_queue_insert(struct scsi_cmnd *cmd, int reason)
4f5299ac 189{
84feb166 190 __scsi_queue_insert(cmd, reason, 1);
4f5299ac 191}
39216033 192/**
33aa687d 193 * scsi_execute - insert request and wait for the result
39216033
JB
194 * @sdev: scsi device
195 * @cmd: scsi command
196 * @data_direction: data direction
197 * @buffer: data buffer
198 * @bufflen: len of buffer
199 * @sense: optional sense buffer
200 * @timeout: request timeout in seconds
201 * @retries: number of times to retry request
33aa687d 202 * @flags: or into request flags;
f4f4e47e 203 * @resid: optional residual length
39216033 204 *
59c51591 205 * returns the req->errors value which is the scsi_cmnd result
ea73a9f2 206 * field.
eb44820c 207 */
33aa687d
JB
208int scsi_execute(struct scsi_device *sdev, const unsigned char *cmd,
209 int data_direction, void *buffer, unsigned bufflen,
f4f4e47e
FT
210 unsigned char *sense, int timeout, int retries, int flags,
211 int *resid)
39216033
JB
212{
213 struct request *req;
214 int write = (data_direction == DMA_TO_DEVICE);
215 int ret = DRIVER_ERROR << 24;
216
217 req = blk_get_request(sdev->request_queue, write, __GFP_WAIT);
bfe159a5
JB
218 if (!req)
219 return ret;
39216033
JB
220
221 if (bufflen && blk_rq_map_kern(sdev->request_queue, req,
222 buffer, bufflen, __GFP_WAIT))
223 goto out;
224
225 req->cmd_len = COMMAND_SIZE(cmd[0]);
226 memcpy(req->cmd, cmd, req->cmd_len);
227 req->sense = sense;
228 req->sense_len = 0;
17e01f21 229 req->retries = retries;
39216033 230 req->timeout = timeout;
4aff5e23
JA
231 req->cmd_type = REQ_TYPE_BLOCK_PC;
232 req->cmd_flags |= flags | REQ_QUIET | REQ_PREEMPT;
39216033
JB
233
234 /*
235 * head injection *required* here otherwise quiesce won't work
236 */
237 blk_execute_rq(req->q, NULL, req, 1);
238
bdb2b8ca
AS
239 /*
240 * Some devices (USB mass-storage in particular) may transfer
241 * garbage data together with a residue indicating that the data
242 * is invalid. Prevent the garbage from being misinterpreted
243 * and prevent security leaks by zeroing out the excess data.
244 */
c3a4d78c
TH
245 if (unlikely(req->resid_len > 0 && req->resid_len <= bufflen))
246 memset(buffer + (bufflen - req->resid_len), 0, req->resid_len);
bdb2b8ca 247
f4f4e47e 248 if (resid)
c3a4d78c 249 *resid = req->resid_len;
39216033
JB
250 ret = req->errors;
251 out:
252 blk_put_request(req);
253
254 return ret;
255}
33aa687d 256EXPORT_SYMBOL(scsi_execute);
39216033 257
9b21493c 258int scsi_execute_req_flags(struct scsi_device *sdev, const unsigned char *cmd,
ea73a9f2 259 int data_direction, void *buffer, unsigned bufflen,
f4f4e47e 260 struct scsi_sense_hdr *sshdr, int timeout, int retries,
9b21493c 261 int *resid, int flags)
ea73a9f2
JB
262{
263 char *sense = NULL;
1ccb48bb 264 int result;
265
ea73a9f2 266 if (sshdr) {
24669f75 267 sense = kzalloc(SCSI_SENSE_BUFFERSIZE, GFP_NOIO);
ea73a9f2
JB
268 if (!sense)
269 return DRIVER_ERROR << 24;
ea73a9f2 270 }
1ccb48bb 271 result = scsi_execute(sdev, cmd, data_direction, buffer, bufflen,
9b21493c 272 sense, timeout, retries, flags, resid);
ea73a9f2 273 if (sshdr)
e514385b 274 scsi_normalize_sense(sense, SCSI_SENSE_BUFFERSIZE, sshdr);
ea73a9f2
JB
275
276 kfree(sense);
277 return result;
278}
9b21493c 279EXPORT_SYMBOL(scsi_execute_req_flags);
ea73a9f2 280
1da177e4
LT
281/*
282 * Function: scsi_init_cmd_errh()
283 *
284 * Purpose: Initialize cmd fields related to error handling.
285 *
286 * Arguments: cmd - command that is ready to be queued.
287 *
1da177e4
LT
288 * Notes: This function has the job of initializing a number of
289 * fields related to error handling. Typically this will
290 * be called once for each command, as required.
291 */
631c228c 292static void scsi_init_cmd_errh(struct scsi_cmnd *cmd)
1da177e4 293{
1da177e4 294 cmd->serial_number = 0;
30b0c37b 295 scsi_set_resid(cmd, 0);
b80ca4f7 296 memset(cmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
1da177e4 297 if (cmd->cmd_len == 0)
db4742dd 298 cmd->cmd_len = scsi_command_size(cmd->cmnd);
1da177e4
LT
299}
300
301void scsi_device_unbusy(struct scsi_device *sdev)
302{
303 struct Scsi_Host *shost = sdev->host;
f0c0a376 304 struct scsi_target *starget = scsi_target(sdev);
1da177e4
LT
305 unsigned long flags;
306
307 spin_lock_irqsave(shost->host_lock, flags);
308 shost->host_busy--;
f0c0a376 309 starget->target_busy--;
939647ee 310 if (unlikely(scsi_host_in_recovery(shost) &&
ee7863bc 311 (shost->host_failed || shost->host_eh_scheduled)))
1da177e4
LT
312 scsi_eh_wakeup(shost);
313 spin_unlock(shost->host_lock);
152587de 314 spin_lock(sdev->request_queue->queue_lock);
1da177e4 315 sdev->device_busy--;
152587de 316 spin_unlock_irqrestore(sdev->request_queue->queue_lock, flags);
1da177e4
LT
317}
318
319/*
320 * Called for single_lun devices on IO completion. Clear starget_sdev_user,
321 * and call blk_run_queue for all the scsi_devices on the target -
322 * including current_sdev first.
323 *
324 * Called with *no* scsi locks held.
325 */
326static void scsi_single_lun_run(struct scsi_device *current_sdev)
327{
328 struct Scsi_Host *shost = current_sdev->host;
329 struct scsi_device *sdev, *tmp;
330 struct scsi_target *starget = scsi_target(current_sdev);
331 unsigned long flags;
332
333 spin_lock_irqsave(shost->host_lock, flags);
334 starget->starget_sdev_user = NULL;
335 spin_unlock_irqrestore(shost->host_lock, flags);
336
337 /*
338 * Call blk_run_queue for all LUNs on the target, starting with
339 * current_sdev. We race with others (to set starget_sdev_user),
340 * but in most cases, we will be first. Ideally, each LU on the
341 * target would get some limited time or requests on the target.
342 */
343 blk_run_queue(current_sdev->request_queue);
344
345 spin_lock_irqsave(shost->host_lock, flags);
346 if (starget->starget_sdev_user)
347 goto out;
348 list_for_each_entry_safe(sdev, tmp, &starget->devices,
349 same_target_siblings) {
350 if (sdev == current_sdev)
351 continue;
352 if (scsi_device_get(sdev))
353 continue;
354
355 spin_unlock_irqrestore(shost->host_lock, flags);
356 blk_run_queue(sdev->request_queue);
357 spin_lock_irqsave(shost->host_lock, flags);
358
359 scsi_device_put(sdev);
360 }
361 out:
362 spin_unlock_irqrestore(shost->host_lock, flags);
363}
364
9d112517
KU
365static inline int scsi_device_is_busy(struct scsi_device *sdev)
366{
367 if (sdev->device_busy >= sdev->queue_depth || sdev->device_blocked)
368 return 1;
369
370 return 0;
371}
372
f0c0a376
MC
373static inline int scsi_target_is_busy(struct scsi_target *starget)
374{
375 return ((starget->can_queue > 0 &&
376 starget->target_busy >= starget->can_queue) ||
377 starget->target_blocked);
378}
379
9d112517
KU
380static inline int scsi_host_is_busy(struct Scsi_Host *shost)
381{
382 if ((shost->can_queue > 0 && shost->host_busy >= shost->can_queue) ||
383 shost->host_blocked || shost->host_self_blocked)
384 return 1;
385
386 return 0;
387}
388
21a05df5 389static void scsi_starved_list_run(struct Scsi_Host *shost)
1da177e4 390{
2a3a59e5 391 LIST_HEAD(starved_list);
21a05df5 392 struct scsi_device *sdev;
1da177e4
LT
393 unsigned long flags;
394
1da177e4 395 spin_lock_irqsave(shost->host_lock, flags);
2a3a59e5
MC
396 list_splice_init(&shost->starved_list, &starved_list);
397
398 while (!list_empty(&starved_list)) {
e2eb7244
JB
399 struct request_queue *slq;
400
1da177e4
LT
401 /*
402 * As long as shost is accepting commands and we have
403 * starved queues, call blk_run_queue. scsi_request_fn
404 * drops the queue_lock and can add us back to the
405 * starved_list.
406 *
407 * host_lock protects the starved_list and starved_entry.
408 * scsi_request_fn must get the host_lock before checking
409 * or modifying starved_list or starved_entry.
410 */
2a3a59e5 411 if (scsi_host_is_busy(shost))
f0c0a376 412 break;
f0c0a376 413
2a3a59e5
MC
414 sdev = list_entry(starved_list.next,
415 struct scsi_device, starved_entry);
416 list_del_init(&sdev->starved_entry);
f0c0a376
MC
417 if (scsi_target_is_busy(scsi_target(sdev))) {
418 list_move_tail(&sdev->starved_entry,
419 &shost->starved_list);
420 continue;
421 }
422
e2eb7244
JB
423 /*
424 * Once we drop the host lock, a racing scsi_remove_device()
425 * call may remove the sdev from the starved list and destroy
426 * it and the queue. Mitigate by taking a reference to the
427 * queue and never touching the sdev again after we drop the
428 * host lock. Note: if __scsi_remove_device() invokes
429 * blk_cleanup_queue() before the queue is run from this
430 * function then blk_run_queue() will return immediately since
431 * blk_cleanup_queue() marks the queue with QUEUE_FLAG_DYING.
432 */
433 slq = sdev->request_queue;
434 if (!blk_get_queue(slq))
435 continue;
436 spin_unlock_irqrestore(shost->host_lock, flags);
437
438 blk_run_queue(slq);
439 blk_put_queue(slq);
440
441 spin_lock_irqsave(shost->host_lock, flags);
1da177e4 442 }
2a3a59e5
MC
443 /* put any unprocessed entries back */
444 list_splice(&starved_list, &shost->starved_list);
1da177e4 445 spin_unlock_irqrestore(shost->host_lock, flags);
21a05df5
CH
446}
447
448/*
449 * Function: scsi_run_queue()
450 *
451 * Purpose: Select a proper request queue to serve next
452 *
453 * Arguments: q - last request's queue
454 *
455 * Returns: Nothing
456 *
457 * Notes: The previous command was completely finished, start
458 * a new one if possible.
459 */
460static void scsi_run_queue(struct request_queue *q)
461{
462 struct scsi_device *sdev = q->queuedata;
463
464 if (scsi_target(sdev)->single_lun)
465 scsi_single_lun_run(sdev);
466 if (!list_empty(&sdev->host->starved_list))
467 scsi_starved_list_run(sdev->host);
1da177e4
LT
468
469 blk_run_queue(q);
470}
471
9937a5e2
JA
472void scsi_requeue_run_queue(struct work_struct *work)
473{
474 struct scsi_device *sdev;
475 struct request_queue *q;
476
477 sdev = container_of(work, struct scsi_device, requeue_work);
478 q = sdev->request_queue;
479 scsi_run_queue(q);
480}
481
1da177e4
LT
482/*
483 * Function: scsi_requeue_command()
484 *
485 * Purpose: Handle post-processing of completed commands.
486 *
487 * Arguments: q - queue to operate on
488 * cmd - command that may need to be requeued.
489 *
490 * Returns: Nothing
491 *
492 * Notes: After command completion, there may be blocks left
493 * over which weren't finished by the previous command
494 * this can be for a number of reasons - the main one is
495 * I/O errors in the middle of the request, in which case
496 * we need to request the blocks that come after the bad
497 * sector.
e91442b6 498 * Notes: Upon return, cmd is a stale pointer.
1da177e4
LT
499 */
500static void scsi_requeue_command(struct request_queue *q, struct scsi_cmnd *cmd)
501{
940f5d47 502 struct scsi_device *sdev = cmd->device;
e91442b6 503 struct request *req = cmd->request;
283369cc
TH
504 unsigned long flags;
505
940f5d47
BVA
506 /*
507 * We need to hold a reference on the device to avoid the queue being
508 * killed after the unlock and before scsi_run_queue is invoked which
509 * may happen because scsi_unprep_request() puts the command which
510 * releases its reference on the device.
511 */
512 get_device(&sdev->sdev_gendev);
513
283369cc 514 spin_lock_irqsave(q->queue_lock, flags);
02bd3499 515 scsi_unprep_request(req);
e91442b6 516 blk_requeue_request(q, req);
283369cc 517 spin_unlock_irqrestore(q->queue_lock, flags);
1da177e4
LT
518
519 scsi_run_queue(q);
940f5d47
BVA
520
521 put_device(&sdev->sdev_gendev);
1da177e4
LT
522}
523
524void scsi_next_command(struct scsi_cmnd *cmd)
525{
49d7bc64
LT
526 struct scsi_device *sdev = cmd->device;
527 struct request_queue *q = sdev->request_queue;
528
1da177e4
LT
529 scsi_put_command(cmd);
530 scsi_run_queue(q);
49d7bc64 531
49d7bc64 532 put_device(&sdev->sdev_gendev);
1da177e4
LT
533}
534
535void scsi_run_host_queues(struct Scsi_Host *shost)
536{
537 struct scsi_device *sdev;
538
539 shost_for_each_device(sdev, shost)
540 scsi_run_queue(sdev->request_queue);
541}
542
79ed2429
JB
543static void __scsi_release_buffers(struct scsi_cmnd *, int);
544
1da177e4
LT
545/*
546 * Function: scsi_end_request()
547 *
548 * Purpose: Post-processing of completed commands (usually invoked at end
549 * of upper level post-processing and scsi_io_completion).
550 *
551 * Arguments: cmd - command that is complete.
610d8b0c 552 * error - 0 if I/O indicates success, < 0 for I/O error.
1da177e4
LT
553 * bytes - number of bytes of completed I/O
554 * requeue - indicates whether we should requeue leftovers.
555 *
556 * Lock status: Assumed that lock is not held upon entry.
557 *
e91442b6 558 * Returns: cmd if requeue required, NULL otherwise.
1da177e4
LT
559 *
560 * Notes: This is called for block device requests in order to
561 * mark some number of sectors as complete.
562 *
563 * We are guaranteeing that the request queue will be goosed
564 * at some point during this call.
e91442b6 565 * Notes: If cmd was requeued, upon return it will be a stale pointer.
1da177e4 566 */
610d8b0c 567static struct scsi_cmnd *scsi_end_request(struct scsi_cmnd *cmd, int error,
1da177e4
LT
568 int bytes, int requeue)
569{
165125e1 570 struct request_queue *q = cmd->device->request_queue;
1da177e4 571 struct request *req = cmd->request;
1da177e4
LT
572
573 /*
574 * If there are blocks left over at the end, set up the command
575 * to queue the remainder of them.
576 */
610d8b0c 577 if (blk_end_request(req, error, bytes)) {
1da177e4 578 /* kill remainder if no retrys */
4a27446f 579 if (error && scsi_noretry_cmd(cmd))
e458824f 580 blk_end_request_all(req, error);
1da177e4 581 else {
e91442b6 582 if (requeue) {
1da177e4
LT
583 /*
584 * Bleah. Leftovers again. Stick the
585 * leftovers in the front of the
586 * queue, and goose the queue again.
587 */
79ed2429 588 scsi_release_buffers(cmd);
1da177e4 589 scsi_requeue_command(q, cmd);
e91442b6
JB
590 cmd = NULL;
591 }
1da177e4
LT
592 return cmd;
593 }
594 }
595
1da177e4
LT
596 /*
597 * This will goose the queue request function at the end, so we don't
598 * need to worry about launching another command.
599 */
79ed2429 600 __scsi_release_buffers(cmd, 0);
1da177e4
LT
601 scsi_next_command(cmd);
602 return NULL;
603}
604
a8474ce2
JA
605static inline unsigned int scsi_sgtable_index(unsigned short nents)
606{
607 unsigned int index;
608
d3f46f39
JB
609 BUG_ON(nents > SCSI_MAX_SG_SEGMENTS);
610
611 if (nents <= 8)
a8474ce2 612 index = 0;
d3f46f39
JB
613 else
614 index = get_count_order(nents) - 3;
1da177e4 615
a8474ce2
JA
616 return index;
617}
618
5ed7959e 619static void scsi_sg_free(struct scatterlist *sgl, unsigned int nents)
a8474ce2
JA
620{
621 struct scsi_host_sg_pool *sgp;
a8474ce2 622
5ed7959e
JA
623 sgp = scsi_sg_pools + scsi_sgtable_index(nents);
624 mempool_free(sgl, sgp->pool);
625}
a8474ce2 626
5ed7959e
JA
627static struct scatterlist *scsi_sg_alloc(unsigned int nents, gfp_t gfp_mask)
628{
629 struct scsi_host_sg_pool *sgp;
a8474ce2 630
5ed7959e
JA
631 sgp = scsi_sg_pools + scsi_sgtable_index(nents);
632 return mempool_alloc(sgp->pool, gfp_mask);
633}
a3bec5c5 634
30b0c37b
BH
635static int scsi_alloc_sgtable(struct scsi_data_buffer *sdb, int nents,
636 gfp_t gfp_mask)
5ed7959e
JA
637{
638 int ret;
a8474ce2 639
30b0c37b 640 BUG_ON(!nents);
a8474ce2 641
30b0c37b
BH
642 ret = __sg_alloc_table(&sdb->table, nents, SCSI_MAX_SG_SEGMENTS,
643 gfp_mask, scsi_sg_alloc);
5ed7959e 644 if (unlikely(ret))
30b0c37b 645 __sg_free_table(&sdb->table, SCSI_MAX_SG_SEGMENTS,
7cedb1f1 646 scsi_sg_free);
45711f1a 647
a8474ce2 648 return ret;
1da177e4
LT
649}
650
30b0c37b 651static void scsi_free_sgtable(struct scsi_data_buffer *sdb)
1da177e4 652{
30b0c37b 653 __sg_free_table(&sdb->table, SCSI_MAX_SG_SEGMENTS, scsi_sg_free);
1da177e4
LT
654}
655
79ed2429
JB
656static void __scsi_release_buffers(struct scsi_cmnd *cmd, int do_bidi_check)
657{
658
659 if (cmd->sdb.table.nents)
660 scsi_free_sgtable(&cmd->sdb);
661
662 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
663
664 if (do_bidi_check && scsi_bidi_cmnd(cmd)) {
665 struct scsi_data_buffer *bidi_sdb =
666 cmd->request->next_rq->special;
667 scsi_free_sgtable(bidi_sdb);
668 kmem_cache_free(scsi_sdb_cache, bidi_sdb);
669 cmd->request->next_rq->special = NULL;
670 }
671
672 if (scsi_prot_sg_count(cmd))
673 scsi_free_sgtable(cmd->prot_sdb);
674}
675
1da177e4
LT
676/*
677 * Function: scsi_release_buffers()
678 *
679 * Purpose: Completion processing for block device I/O requests.
680 *
681 * Arguments: cmd - command that we are bailing.
682 *
683 * Lock status: Assumed that no lock is held upon entry.
684 *
685 * Returns: Nothing
686 *
687 * Notes: In the event that an upper level driver rejects a
688 * command, we must release resources allocated during
689 * the __init_io() function. Primarily this would involve
690 * the scatter-gather table, and potentially any bounce
691 * buffers.
692 */
bb52d82f 693void scsi_release_buffers(struct scsi_cmnd *cmd)
1da177e4 694{
79ed2429 695 __scsi_release_buffers(cmd, 1);
1da177e4 696}
bb52d82f 697EXPORT_SYMBOL(scsi_release_buffers);
1da177e4 698
0f7f6234
HR
699/**
700 * __scsi_error_from_host_byte - translate SCSI error code into errno
701 * @cmd: SCSI command (unused)
702 * @result: scsi error code
703 *
704 * Translate SCSI error code into standard UNIX errno.
705 * Return values:
706 * -ENOLINK temporary transport failure
707 * -EREMOTEIO permanent target failure, do not retry
708 * -EBADE permanent nexus failure, retry on other path
a9d6ceb8 709 * -ENOSPC No write space available
7e782af5 710 * -ENODATA Medium error
0f7f6234
HR
711 * -EIO unspecified I/O error
712 */
63583cca
HR
713static int __scsi_error_from_host_byte(struct scsi_cmnd *cmd, int result)
714{
715 int error = 0;
716
717 switch(host_byte(result)) {
718 case DID_TRANSPORT_FAILFAST:
719 error = -ENOLINK;
720 break;
721 case DID_TARGET_FAILURE:
2082ebc4 722 set_host_byte(cmd, DID_OK);
63583cca
HR
723 error = -EREMOTEIO;
724 break;
725 case DID_NEXUS_FAILURE:
2082ebc4 726 set_host_byte(cmd, DID_OK);
63583cca
HR
727 error = -EBADE;
728 break;
a9d6ceb8
HR
729 case DID_ALLOC_FAILURE:
730 set_host_byte(cmd, DID_OK);
731 error = -ENOSPC;
732 break;
7e782af5
HR
733 case DID_MEDIUM_ERROR:
734 set_host_byte(cmd, DID_OK);
735 error = -ENODATA;
736 break;
63583cca
HR
737 default:
738 error = -EIO;
739 break;
740 }
741
742 return error;
743}
744
1da177e4
LT
745/*
746 * Function: scsi_io_completion()
747 *
748 * Purpose: Completion processing for block device I/O requests.
749 *
750 * Arguments: cmd - command that is finished.
751 *
752 * Lock status: Assumed that no lock is held upon entry.
753 *
754 * Returns: Nothing
755 *
756 * Notes: This function is matched in terms of capabilities to
757 * the function that created the scatter-gather list.
758 * In other words, if there are no bounce buffers
759 * (the normal case for most drivers), we don't need
760 * the logic to deal with cleaning up afterwards.
761 *
b60af5b0
AS
762 * We must call scsi_end_request(). This will finish off
763 * the specified number of sectors. If we are done, the
764 * command block will be released and the queue function
765 * will be goosed. If we are not done then we have to
766 * figure out what to do next:
1da177e4 767 *
b60af5b0
AS
768 * a) We can call scsi_requeue_command(). The request
769 * will be unprepared and put back on the queue. Then
770 * a new command will be created for it. This should
771 * be used if we made forward progress, or if we want
772 * to switch from READ(10) to READ(6) for example.
1da177e4 773 *
b60af5b0
AS
774 * b) We can call scsi_queue_insert(). The request will
775 * be put back on the queue and retried using the same
776 * command as before, possibly after a delay.
777 *
778 * c) We can call blk_end_request() with -EIO to fail
779 * the remainder of the request.
1da177e4 780 */
03aba2f7 781void scsi_io_completion(struct scsi_cmnd *cmd, unsigned int good_bytes)
1da177e4
LT
782{
783 int result = cmd->result;
165125e1 784 struct request_queue *q = cmd->device->request_queue;
1da177e4 785 struct request *req = cmd->request;
fa8e36c3 786 int error = 0;
1da177e4
LT
787 struct scsi_sense_hdr sshdr;
788 int sense_valid = 0;
789 int sense_deferred = 0;
b60af5b0
AS
790 enum {ACTION_FAIL, ACTION_REPREP, ACTION_RETRY,
791 ACTION_DELAYED_RETRY} action;
792 char *description = NULL;
ee60b2c5 793 unsigned long wait_for = (cmd->allowed + 1) * req->timeout;
1da177e4 794
1da177e4
LT
795 if (result) {
796 sense_valid = scsi_command_normalize_sense(cmd, &sshdr);
797 if (sense_valid)
798 sense_deferred = scsi_sense_is_deferred(&sshdr);
799 }
631c228c 800
33659ebb 801 if (req->cmd_type == REQ_TYPE_BLOCK_PC) { /* SG_IO ioctl from block level */
1da177e4 802 if (result) {
1da177e4
LT
803 if (sense_valid && req->sense) {
804 /*
805 * SG_IO wants current and deferred errors
806 */
807 int len = 8 + cmd->sense_buffer[7];
808
809 if (len > SCSI_SENSE_BUFFERSIZE)
810 len = SCSI_SENSE_BUFFERSIZE;
811 memcpy(req->sense, cmd->sense_buffer, len);
812 req->sense_len = len;
813 }
fa8e36c3 814 if (!sense_deferred)
63583cca 815 error = __scsi_error_from_host_byte(cmd, result);
b22f687d 816 }
27c41973
MS
817 /*
818 * __scsi_error_from_host_byte may have reset the host_byte
819 */
820 req->errors = cmd->result;
e6bb7a96
FT
821
822 req->resid_len = scsi_get_resid(cmd);
823
6f9a35e2 824 if (scsi_bidi_cmnd(cmd)) {
e6bb7a96
FT
825 /*
826 * Bidi commands Must be complete as a whole,
827 * both sides at once.
828 */
829 req->next_rq->resid_len = scsi_in(cmd)->resid;
830
63c43b0e 831 scsi_release_buffers(cmd);
e6bb7a96
FT
832 blk_end_request_all(req, 0);
833
e6bb7a96 834 scsi_next_command(cmd);
6f9a35e2
BH
835 return;
836 }
1da177e4
LT
837 }
838
33659ebb
CH
839 /* no bidi support for !REQ_TYPE_BLOCK_PC yet */
840 BUG_ON(blk_bidi_rq(req));
30b0c37b 841
1da177e4
LT
842 /*
843 * Next deal with any sectors which we were able to correctly
844 * handle.
845 */
83096ebf 846 SCSI_LOG_HLCOMPLETE(1, printk("%u sectors total, "
d6b0c537 847 "%d bytes done.\n",
83096ebf 848 blk_rq_sectors(req), good_bytes));
d6b0c537 849
a9bddd74
JB
850 /*
851 * Recovered errors need reporting, but they're always treated
852 * as success, so fiddle the result code here. For BLOCK_PC
853 * we already took a copy of the original into rq->errors which
854 * is what gets returned to the user
855 */
e7efe593
DG
856 if (sense_valid && (sshdr.sense_key == RECOVERED_ERROR)) {
857 /* if ATA PASS-THROUGH INFORMATION AVAILABLE skip
858 * print since caller wants ATA registers. Only occurs on
859 * SCSI ATA PASS_THROUGH commands when CK_COND=1
860 */
861 if ((sshdr.asc == 0x0) && (sshdr.ascq == 0x1d))
862 ;
863 else if (!(req->cmd_flags & REQ_QUIET))
a9bddd74
JB
864 scsi_print_sense("", cmd);
865 result = 0;
866 /* BLOCK_PC may have set error */
867 error = 0;
868 }
869
870 /*
871 * A number of bytes were successfully read. If there
d6b0c537
JB
872 * are leftovers and there is some kind of error
873 * (result != 0), retry the rest.
874 */
fa8e36c3 875 if (scsi_end_request(cmd, error, good_bytes, result == 0) == NULL)
d6b0c537 876 return;
03aba2f7 877
63583cca 878 error = __scsi_error_from_host_byte(cmd, result);
3e695f89 879
b60af5b0
AS
880 if (host_byte(result) == DID_RESET) {
881 /* Third party bus reset or reset for error recovery
882 * reasons. Just retry the command and see what
883 * happens.
884 */
885 action = ACTION_RETRY;
886 } else if (sense_valid && !sense_deferred) {
1da177e4
LT
887 switch (sshdr.sense_key) {
888 case UNIT_ATTENTION:
889 if (cmd->device->removable) {
03aba2f7 890 /* Detected disc change. Set a bit
1da177e4
LT
891 * and quietly refuse further access.
892 */
893 cmd->device->changed = 1;
b60af5b0
AS
894 description = "Media Changed";
895 action = ACTION_FAIL;
1da177e4 896 } else {
03aba2f7
LT
897 /* Must have been a power glitch, or a
898 * bus reset. Could not have been a
899 * media change, so we just retry the
b60af5b0 900 * command and see what happens.
03aba2f7 901 */
b60af5b0 902 action = ACTION_RETRY;
1da177e4
LT
903 }
904 break;
905 case ILLEGAL_REQUEST:
03aba2f7
LT
906 /* If we had an ILLEGAL REQUEST returned, then
907 * we may have performed an unsupported
908 * command. The only thing this should be
909 * would be a ten byte read where only a six
910 * byte read was supported. Also, on a system
911 * where READ CAPACITY failed, we may have
912 * read past the end of the disk.
913 */
26a68019
JA
914 if ((cmd->device->use_10_for_rw &&
915 sshdr.asc == 0x20 && sshdr.ascq == 0x00) &&
1da177e4
LT
916 (cmd->cmnd[0] == READ_10 ||
917 cmd->cmnd[0] == WRITE_10)) {
b60af5b0 918 /* This will issue a new 6-byte command. */
1da177e4 919 cmd->device->use_10_for_rw = 0;
b60af5b0 920 action = ACTION_REPREP;
3e695f89
MP
921 } else if (sshdr.asc == 0x10) /* DIX */ {
922 description = "Host Data Integrity Failure";
923 action = ACTION_FAIL;
924 error = -EILSEQ;
c98a0eb0 925 /* INVALID COMMAND OPCODE or INVALID FIELD IN CDB */
5db44863
MP
926 } else if (sshdr.asc == 0x20 || sshdr.asc == 0x24) {
927 switch (cmd->cmnd[0]) {
928 case UNMAP:
929 description = "Discard failure";
930 break;
931 case WRITE_SAME:
932 case WRITE_SAME_16:
933 if (cmd->cmnd[1] & 0x8)
934 description = "Discard failure";
935 else
936 description =
937 "Write same failure";
938 break;
939 default:
940 description = "Invalid command failure";
941 break;
942 }
c98a0eb0 943 action = ACTION_FAIL;
66a651aa 944 error = -EREMOTEIO;
b60af5b0
AS
945 } else
946 action = ACTION_FAIL;
947 break;
511e44f4 948 case ABORTED_COMMAND:
126c0982 949 action = ACTION_FAIL;
511e44f4 950 if (sshdr.asc == 0x10) { /* DIF */
3e695f89 951 description = "Target Data Integrity Failure";
3e695f89 952 error = -EILSEQ;
126c0982 953 }
1da177e4
LT
954 break;
955 case NOT_READY:
03aba2f7 956 /* If the device is in the process of becoming
f3e93f73 957 * ready, or has a temporary blockage, retry.
1da177e4 958 */
f3e93f73
JB
959 if (sshdr.asc == 0x04) {
960 switch (sshdr.ascq) {
961 case 0x01: /* becoming ready */
962 case 0x04: /* format in progress */
963 case 0x05: /* rebuild in progress */
964 case 0x06: /* recalculation in progress */
965 case 0x07: /* operation in progress */
966 case 0x08: /* Long write in progress */
967 case 0x09: /* self test in progress */
d8705f11 968 case 0x14: /* space allocation in progress */
b60af5b0 969 action = ACTION_DELAYED_RETRY;
f3e93f73 970 break;
3dbf6a54
AS
971 default:
972 description = "Device not ready";
973 action = ACTION_FAIL;
974 break;
f3e93f73 975 }
b60af5b0
AS
976 } else {
977 description = "Device not ready";
978 action = ACTION_FAIL;
1da177e4 979 }
b60af5b0 980 break;
1da177e4 981 case VOLUME_OVERFLOW:
03aba2f7 982 /* See SSC3rXX or current. */
b60af5b0
AS
983 action = ACTION_FAIL;
984 break;
1da177e4 985 default:
b60af5b0
AS
986 description = "Unhandled sense code";
987 action = ACTION_FAIL;
1da177e4
LT
988 break;
989 }
b60af5b0
AS
990 } else {
991 description = "Unhandled error code";
992 action = ACTION_FAIL;
03aba2f7 993 }
b60af5b0 994
ee60b2c5
ET
995 if (action != ACTION_FAIL &&
996 time_before(cmd->jiffies_at_alloc + wait_for, jiffies)) {
997 action = ACTION_FAIL;
998 description = "Command timed out";
999 }
1000
b60af5b0
AS
1001 switch (action) {
1002 case ACTION_FAIL:
1003 /* Give up and fail the remainder of the request */
79ed2429 1004 scsi_release_buffers(cmd);
4aff5e23 1005 if (!(req->cmd_flags & REQ_QUIET)) {
b60af5b0 1006 if (description)
3dbf6a54 1007 scmd_printk(KERN_INFO, cmd, "%s\n",
b60af5b0 1008 description);
a4d04a4c 1009 scsi_print_result(cmd);
3173d8c3
JB
1010 if (driver_byte(result) & DRIVER_SENSE)
1011 scsi_print_sense("", cmd);
002b1eb2 1012 scsi_print_command(cmd);
3173d8c3 1013 }
ad630826 1014 if (blk_end_request_err(req, error))
da6c5c72
TH
1015 scsi_requeue_command(q, cmd);
1016 else
1017 scsi_next_command(cmd);
b60af5b0
AS
1018 break;
1019 case ACTION_REPREP:
1020 /* Unprep the request and put it back at the head of the queue.
1021 * A new command will be prepared and issued.
1022 */
79ed2429 1023 scsi_release_buffers(cmd);
b60af5b0
AS
1024 scsi_requeue_command(q, cmd);
1025 break;
1026 case ACTION_RETRY:
1027 /* Retry the same command immediately */
4f5299ac 1028 __scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY, 0);
b60af5b0
AS
1029 break;
1030 case ACTION_DELAYED_RETRY:
1031 /* Retry the same command after a delay */
4f5299ac 1032 __scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY, 0);
b60af5b0 1033 break;
1da177e4
LT
1034 }
1035}
1da177e4 1036
6f9a35e2
BH
1037static int scsi_init_sgtable(struct request *req, struct scsi_data_buffer *sdb,
1038 gfp_t gfp_mask)
1da177e4 1039{
6f9a35e2 1040 int count;
1da177e4
LT
1041
1042 /*
3b003157 1043 * If sg table allocation fails, requeue request later.
1da177e4 1044 */
30b0c37b
BH
1045 if (unlikely(scsi_alloc_sgtable(sdb, req->nr_phys_segments,
1046 gfp_mask))) {
1da177e4 1047 return BLKPREP_DEFER;
7c72ce81 1048 }
1da177e4 1049
3b003157 1050 req->buffer = NULL;
1da177e4
LT
1051
1052 /*
1053 * Next, walk the list, and fill in the addresses and sizes of
1054 * each segment.
1055 */
30b0c37b
BH
1056 count = blk_rq_map_sg(req->q, req, sdb->table.sgl);
1057 BUG_ON(count > sdb->table.nents);
1058 sdb->table.nents = count;
1011c1b9 1059 sdb->length = blk_rq_bytes(req);
4a03d90e 1060 return BLKPREP_OK;
1da177e4 1061}
6f9a35e2
BH
1062
1063/*
1064 * Function: scsi_init_io()
1065 *
1066 * Purpose: SCSI I/O initialize function.
1067 *
1068 * Arguments: cmd - Command descriptor we wish to initialize
1069 *
1070 * Returns: 0 on success
1071 * BLKPREP_DEFER if the failure is retryable
1072 * BLKPREP_KILL if the failure is fatal
1073 */
1074int scsi_init_io(struct scsi_cmnd *cmd, gfp_t gfp_mask)
1075{
13f05c8d
MP
1076 struct request *rq = cmd->request;
1077
1078 int error = scsi_init_sgtable(rq, &cmd->sdb, gfp_mask);
6f9a35e2
BH
1079 if (error)
1080 goto err_exit;
1081
13f05c8d 1082 if (blk_bidi_rq(rq)) {
6f9a35e2 1083 struct scsi_data_buffer *bidi_sdb = kmem_cache_zalloc(
6362abd3 1084 scsi_sdb_cache, GFP_ATOMIC);
6f9a35e2
BH
1085 if (!bidi_sdb) {
1086 error = BLKPREP_DEFER;
1087 goto err_exit;
1088 }
1089
13f05c8d
MP
1090 rq->next_rq->special = bidi_sdb;
1091 error = scsi_init_sgtable(rq->next_rq, bidi_sdb, GFP_ATOMIC);
6f9a35e2
BH
1092 if (error)
1093 goto err_exit;
1094 }
1095
13f05c8d 1096 if (blk_integrity_rq(rq)) {
7027ad72
MP
1097 struct scsi_data_buffer *prot_sdb = cmd->prot_sdb;
1098 int ivecs, count;
1099
1100 BUG_ON(prot_sdb == NULL);
13f05c8d 1101 ivecs = blk_rq_count_integrity_sg(rq->q, rq->bio);
7027ad72
MP
1102
1103 if (scsi_alloc_sgtable(prot_sdb, ivecs, gfp_mask)) {
1104 error = BLKPREP_DEFER;
1105 goto err_exit;
1106 }
1107
13f05c8d 1108 count = blk_rq_map_integrity_sg(rq->q, rq->bio,
7027ad72
MP
1109 prot_sdb->table.sgl);
1110 BUG_ON(unlikely(count > ivecs));
13f05c8d 1111 BUG_ON(unlikely(count > queue_max_integrity_segments(rq->q)));
7027ad72
MP
1112
1113 cmd->prot_sdb = prot_sdb;
1114 cmd->prot_sdb->table.nents = count;
1115 }
1116
6f9a35e2
BH
1117 return BLKPREP_OK ;
1118
1119err_exit:
1120 scsi_release_buffers(cmd);
610a6349 1121 cmd->request->special = NULL;
3a5c19c2 1122 scsi_put_command(cmd);
04796336 1123 put_device(&cmd->device->sdev_gendev);
6f9a35e2
BH
1124 return error;
1125}
bb52d82f 1126EXPORT_SYMBOL(scsi_init_io);
1da177e4 1127
3b003157
CH
1128static struct scsi_cmnd *scsi_get_cmd_from_req(struct scsi_device *sdev,
1129 struct request *req)
1130{
1131 struct scsi_cmnd *cmd;
1132
1133 if (!req->special) {
04796336
CH
1134 /* Bail if we can't get a reference to the device */
1135 if (!get_device(&sdev->sdev_gendev))
1136 return NULL;
1137
3b003157 1138 cmd = scsi_get_command(sdev, GFP_ATOMIC);
04796336
CH
1139 if (unlikely(!cmd)) {
1140 put_device(&sdev->sdev_gendev);
3b003157 1141 return NULL;
04796336 1142 }
3b003157
CH
1143 req->special = cmd;
1144 } else {
1145 cmd = req->special;
1146 }
1147
1148 /* pull a tag out of the request if we have one */
1149 cmd->tag = req->tag;
1150 cmd->request = req;
1151
64a87b24 1152 cmd->cmnd = req->cmd;
72f7d322 1153 cmd->prot_op = SCSI_PROT_NORMAL;
64a87b24 1154
3b003157
CH
1155 return cmd;
1156}
1157
7f9a6bc4 1158int scsi_setup_blk_pc_cmnd(struct scsi_device *sdev, struct request *req)
7b16318d 1159{
3b003157 1160 struct scsi_cmnd *cmd;
7f9a6bc4
JB
1161 int ret = scsi_prep_state_check(sdev, req);
1162
1163 if (ret != BLKPREP_OK)
1164 return ret;
3b003157
CH
1165
1166 cmd = scsi_get_cmd_from_req(sdev, req);
1167 if (unlikely(!cmd))
1168 return BLKPREP_DEFER;
1169
1170 /*
1171 * BLOCK_PC requests may transfer data, in which case they must
1172 * a bio attached to them. Or they might contain a SCSI command
1173 * that does not transfer data, in which case they may optionally
1174 * submit a request without an attached bio.
1175 */
1176 if (req->bio) {
1177 int ret;
1178
1179 BUG_ON(!req->nr_phys_segments);
1180
bb52d82f 1181 ret = scsi_init_io(cmd, GFP_ATOMIC);
3b003157
CH
1182 if (unlikely(ret))
1183 return ret;
1184 } else {
b0790410 1185 BUG_ON(blk_rq_bytes(req));
3b003157 1186
30b0c37b 1187 memset(&cmd->sdb, 0, sizeof(cmd->sdb));
3b003157
CH
1188 req->buffer = NULL;
1189 }
7b16318d 1190
7b16318d 1191 cmd->cmd_len = req->cmd_len;
b0790410 1192 if (!blk_rq_bytes(req))
7b16318d
JB
1193 cmd->sc_data_direction = DMA_NONE;
1194 else if (rq_data_dir(req) == WRITE)
1195 cmd->sc_data_direction = DMA_TO_DEVICE;
1196 else
1197 cmd->sc_data_direction = DMA_FROM_DEVICE;
1198
b0790410 1199 cmd->transfersize = blk_rq_bytes(req);
7b16318d 1200 cmd->allowed = req->retries;
3b003157 1201 return BLKPREP_OK;
7b16318d 1202}
7f9a6bc4 1203EXPORT_SYMBOL(scsi_setup_blk_pc_cmnd);
7b16318d 1204
3b003157
CH
1205/*
1206 * Setup a REQ_TYPE_FS command. These are simple read/write request
1207 * from filesystems that still need to be translated to SCSI CDBs from
1208 * the ULD.
1209 */
7f9a6bc4 1210int scsi_setup_fs_cmnd(struct scsi_device *sdev, struct request *req)
1da177e4 1211{
1da177e4 1212 struct scsi_cmnd *cmd;
7f9a6bc4 1213 int ret = scsi_prep_state_check(sdev, req);
1da177e4 1214
7f9a6bc4
JB
1215 if (ret != BLKPREP_OK)
1216 return ret;
a6a8d9f8
CS
1217
1218 if (unlikely(sdev->scsi_dh_data && sdev->scsi_dh_data->scsi_dh
1219 && sdev->scsi_dh_data->scsi_dh->prep_fn)) {
1220 ret = sdev->scsi_dh_data->scsi_dh->prep_fn(sdev, req);
1221 if (ret != BLKPREP_OK)
1222 return ret;
1223 }
1224
1da177e4 1225 /*
3b003157 1226 * Filesystem requests must transfer data.
1da177e4 1227 */
3b003157
CH
1228 BUG_ON(!req->nr_phys_segments);
1229
1230 cmd = scsi_get_cmd_from_req(sdev, req);
1231 if (unlikely(!cmd))
1232 return BLKPREP_DEFER;
1233
64a87b24 1234 memset(cmd->cmnd, 0, BLK_MAX_CDB);
bb52d82f 1235 return scsi_init_io(cmd, GFP_ATOMIC);
3b003157 1236}
7f9a6bc4 1237EXPORT_SYMBOL(scsi_setup_fs_cmnd);
3b003157 1238
7f9a6bc4 1239int scsi_prep_state_check(struct scsi_device *sdev, struct request *req)
3b003157 1240{
3b003157
CH
1241 int ret = BLKPREP_OK;
1242
1da177e4 1243 /*
3b003157
CH
1244 * If the device is not in running state we will reject some
1245 * or all commands.
1da177e4 1246 */
3b003157
CH
1247 if (unlikely(sdev->sdev_state != SDEV_RUNNING)) {
1248 switch (sdev->sdev_state) {
1249 case SDEV_OFFLINE:
1b8d2620 1250 case SDEV_TRANSPORT_OFFLINE:
3b003157
CH
1251 /*
1252 * If the device is offline we refuse to process any
1253 * commands. The device must be brought online
1254 * before trying any recovery commands.
1255 */
1256 sdev_printk(KERN_ERR, sdev,
1257 "rejecting I/O to offline device\n");
1258 ret = BLKPREP_KILL;
1259 break;
1260 case SDEV_DEL:
1261 /*
1262 * If the device is fully deleted, we refuse to
1263 * process any commands as well.
1264 */
9ccfc756 1265 sdev_printk(KERN_ERR, sdev,
3b003157
CH
1266 "rejecting I/O to dead device\n");
1267 ret = BLKPREP_KILL;
1268 break;
1269 case SDEV_QUIESCE:
1270 case SDEV_BLOCK:
6f4267e3 1271 case SDEV_CREATED_BLOCK:
3b003157
CH
1272 /*
1273 * If the devices is blocked we defer normal commands.
1274 */
1275 if (!(req->cmd_flags & REQ_PREEMPT))
1276 ret = BLKPREP_DEFER;
1277 break;
1278 default:
1279 /*
1280 * For any other not fully online state we only allow
1281 * special commands. In particular any user initiated
1282 * command is not allowed.
1283 */
1284 if (!(req->cmd_flags & REQ_PREEMPT))
1285 ret = BLKPREP_KILL;
1286 break;
1da177e4 1287 }
1da177e4 1288 }
7f9a6bc4
JB
1289 return ret;
1290}
1291EXPORT_SYMBOL(scsi_prep_state_check);
1da177e4 1292
7f9a6bc4
JB
1293int scsi_prep_return(struct request_queue *q, struct request *req, int ret)
1294{
1295 struct scsi_device *sdev = q->queuedata;
1da177e4 1296
3b003157
CH
1297 switch (ret) {
1298 case BLKPREP_KILL:
1299 req->errors = DID_NO_CONNECT << 16;
7f9a6bc4
JB
1300 /* release the command and kill it */
1301 if (req->special) {
1302 struct scsi_cmnd *cmd = req->special;
1303 scsi_release_buffers(cmd);
1304 scsi_put_command(cmd);
04796336 1305 put_device(&cmd->device->sdev_gendev);
7f9a6bc4
JB
1306 req->special = NULL;
1307 }
3b003157
CH
1308 break;
1309 case BLKPREP_DEFER:
1da177e4 1310 /*
9934c8c0 1311 * If we defer, the blk_peek_request() returns NULL, but the
a488e749
JA
1312 * queue must be restarted, so we schedule a callback to happen
1313 * shortly.
1da177e4 1314 */
3b003157 1315 if (sdev->device_busy == 0)
a488e749 1316 blk_delay_queue(q, SCSI_QUEUE_DELAY);
3b003157
CH
1317 break;
1318 default:
1319 req->cmd_flags |= REQ_DONTPREP;
1da177e4
LT
1320 }
1321
3b003157 1322 return ret;
1da177e4 1323}
7f9a6bc4
JB
1324EXPORT_SYMBOL(scsi_prep_return);
1325
751bf4d7 1326int scsi_prep_fn(struct request_queue *q, struct request *req)
7f9a6bc4
JB
1327{
1328 struct scsi_device *sdev = q->queuedata;
1329 int ret = BLKPREP_KILL;
1330
1331 if (req->cmd_type == REQ_TYPE_BLOCK_PC)
1332 ret = scsi_setup_blk_pc_cmnd(sdev, req);
1333 return scsi_prep_return(q, req, ret);
1334}
b391277a 1335EXPORT_SYMBOL(scsi_prep_fn);
1da177e4
LT
1336
1337/*
1338 * scsi_dev_queue_ready: if we can send requests to sdev, return 1 else
1339 * return 0.
1340 *
1341 * Called with the queue_lock held.
1342 */
1343static inline int scsi_dev_queue_ready(struct request_queue *q,
1344 struct scsi_device *sdev)
1345{
1da177e4
LT
1346 if (sdev->device_busy == 0 && sdev->device_blocked) {
1347 /*
1348 * unblock after device_blocked iterates to zero
1349 */
1350 if (--sdev->device_blocked == 0) {
1351 SCSI_LOG_MLQUEUE(3,
9ccfc756
JB
1352 sdev_printk(KERN_INFO, sdev,
1353 "unblocking device at zero depth\n"));
1da177e4 1354 } else {
a488e749 1355 blk_delay_queue(q, SCSI_QUEUE_DELAY);
1da177e4
LT
1356 return 0;
1357 }
1358 }
9d112517 1359 if (scsi_device_is_busy(sdev))
1da177e4
LT
1360 return 0;
1361
1362 return 1;
1363}
1364
f0c0a376
MC
1365
1366/*
1367 * scsi_target_queue_ready: checks if there we can send commands to target
1368 * @sdev: scsi device on starget to check.
1369 *
1370 * Called with the host lock held.
1371 */
1372static inline int scsi_target_queue_ready(struct Scsi_Host *shost,
1373 struct scsi_device *sdev)
1374{
1375 struct scsi_target *starget = scsi_target(sdev);
1376
1377 if (starget->single_lun) {
1378 if (starget->starget_sdev_user &&
1379 starget->starget_sdev_user != sdev)
1380 return 0;
1381 starget->starget_sdev_user = sdev;
1382 }
1383
1384 if (starget->target_busy == 0 && starget->target_blocked) {
1385 /*
1386 * unblock after target_blocked iterates to zero
1387 */
1388 if (--starget->target_blocked == 0) {
1389 SCSI_LOG_MLQUEUE(3, starget_printk(KERN_INFO, starget,
1390 "unblocking target at zero depth\n"));
b4efdd58 1391 } else
f0c0a376 1392 return 0;
f0c0a376
MC
1393 }
1394
1395 if (scsi_target_is_busy(starget)) {
466c08c7 1396 list_move_tail(&sdev->starved_entry, &shost->starved_list);
fd01a663 1397 return 0;
f0c0a376
MC
1398 }
1399
f0c0a376
MC
1400 return 1;
1401}
1402
1da177e4
LT
1403/*
1404 * scsi_host_queue_ready: if we can send requests to shost, return 1 else
1405 * return 0. We must end up running the queue again whenever 0 is
1406 * returned, else IO can hang.
1407 *
1408 * Called with host_lock held.
1409 */
1410static inline int scsi_host_queue_ready(struct request_queue *q,
1411 struct Scsi_Host *shost,
1412 struct scsi_device *sdev)
1413{
939647ee 1414 if (scsi_host_in_recovery(shost))
1da177e4
LT
1415 return 0;
1416 if (shost->host_busy == 0 && shost->host_blocked) {
1417 /*
1418 * unblock after host_blocked iterates to zero
1419 */
1420 if (--shost->host_blocked == 0) {
1421 SCSI_LOG_MLQUEUE(3,
1422 printk("scsi%d unblocking host at zero depth\n",
1423 shost->host_no));
1424 } else {
1da177e4
LT
1425 return 0;
1426 }
1427 }
9d112517 1428 if (scsi_host_is_busy(shost)) {
1da177e4
LT
1429 if (list_empty(&sdev->starved_entry))
1430 list_add_tail(&sdev->starved_entry, &shost->starved_list);
1431 return 0;
1432 }
1433
1434 /* We're OK to process the command, so we can't be starved */
1435 if (!list_empty(&sdev->starved_entry))
1436 list_del_init(&sdev->starved_entry);
1437
1438 return 1;
1439}
1440
6c5121b7
KU
1441/*
1442 * Busy state exporting function for request stacking drivers.
1443 *
1444 * For efficiency, no lock is taken to check the busy state of
1445 * shost/starget/sdev, since the returned value is not guaranteed and
1446 * may be changed after request stacking drivers call the function,
1447 * regardless of taking lock or not.
1448 *
67bd9413
BVA
1449 * When scsi can't dispatch I/Os anymore and needs to kill I/Os scsi
1450 * needs to return 'not busy'. Otherwise, request stacking drivers
1451 * may hold requests forever.
6c5121b7
KU
1452 */
1453static int scsi_lld_busy(struct request_queue *q)
1454{
1455 struct scsi_device *sdev = q->queuedata;
1456 struct Scsi_Host *shost;
6c5121b7 1457
3f3299d5 1458 if (blk_queue_dying(q))
6c5121b7
KU
1459 return 0;
1460
1461 shost = sdev->host;
6c5121b7 1462
b7e94a16
JN
1463 /*
1464 * Ignore host/starget busy state.
1465 * Since block layer does not have a concept of fairness across
1466 * multiple queues, congestion of host/starget needs to be handled
1467 * in SCSI layer.
1468 */
1469 if (scsi_host_in_recovery(shost) || scsi_device_is_busy(sdev))
6c5121b7
KU
1470 return 1;
1471
1472 return 0;
1473}
1474
1da177e4 1475/*
e91442b6 1476 * Kill a request for a dead device
1da177e4 1477 */
165125e1 1478static void scsi_kill_request(struct request *req, struct request_queue *q)
1da177e4 1479{
e91442b6 1480 struct scsi_cmnd *cmd = req->special;
03b14708
JS
1481 struct scsi_device *sdev;
1482 struct scsi_target *starget;
1483 struct Scsi_Host *shost;
1da177e4 1484
9934c8c0 1485 blk_start_request(req);
788ce43a 1486
74571813
HR
1487 scmd_printk(KERN_INFO, cmd, "killing request\n");
1488
03b14708
JS
1489 sdev = cmd->device;
1490 starget = scsi_target(sdev);
1491 shost = sdev->host;
e91442b6
JB
1492 scsi_init_cmd_errh(cmd);
1493 cmd->result = DID_NO_CONNECT << 16;
1494 atomic_inc(&cmd->device->iorequest_cnt);
e36e0c80
TH
1495
1496 /*
1497 * SCSI request completion path will do scsi_device_unbusy(),
1498 * bump busy counts. To bump the counters, we need to dance
1499 * with the locks as normal issue path does.
1500 */
1501 sdev->device_busy++;
1502 spin_unlock(sdev->request_queue->queue_lock);
1503 spin_lock(shost->host_lock);
1504 shost->host_busy++;
f0c0a376 1505 starget->target_busy++;
e36e0c80
TH
1506 spin_unlock(shost->host_lock);
1507 spin_lock(sdev->request_queue->queue_lock);
1508
242f9dcb 1509 blk_complete_request(req);
1da177e4
LT
1510}
1511
1aea6434
JA
1512static void scsi_softirq_done(struct request *rq)
1513{
242f9dcb
JA
1514 struct scsi_cmnd *cmd = rq->special;
1515 unsigned long wait_for = (cmd->allowed + 1) * rq->timeout;
1aea6434
JA
1516 int disposition;
1517
1518 INIT_LIST_HEAD(&cmd->eh_entry);
1519
242f9dcb
JA
1520 atomic_inc(&cmd->device->iodone_cnt);
1521 if (cmd->result)
1522 atomic_inc(&cmd->device->ioerr_cnt);
1523
1aea6434
JA
1524 disposition = scsi_decide_disposition(cmd);
1525 if (disposition != SUCCESS &&
1526 time_before(cmd->jiffies_at_alloc + wait_for, jiffies)) {
1527 sdev_printk(KERN_ERR, cmd->device,
1528 "timing out command, waited %lus\n",
1529 wait_for/HZ);
1530 disposition = SUCCESS;
1531 }
1532
1533 scsi_log_completion(cmd, disposition);
1534
1535 switch (disposition) {
1536 case SUCCESS:
1537 scsi_finish_command(cmd);
1538 break;
1539 case NEEDS_RETRY:
596f482a 1540 scsi_queue_insert(cmd, SCSI_MLQUEUE_EH_RETRY);
1aea6434
JA
1541 break;
1542 case ADD_TO_MLQUEUE:
1543 scsi_queue_insert(cmd, SCSI_MLQUEUE_DEVICE_BUSY);
1544 break;
1545 default:
1546 if (!scsi_eh_scmd_add(cmd, 0))
1547 scsi_finish_command(cmd);
1548 }
1549}
1550
1da177e4
LT
1551/*
1552 * Function: scsi_request_fn()
1553 *
1554 * Purpose: Main strategy routine for SCSI.
1555 *
1556 * Arguments: q - Pointer to actual queue.
1557 *
1558 * Returns: Nothing
1559 *
1560 * Lock status: IO request lock assumed to be held when called.
1561 */
1562static void scsi_request_fn(struct request_queue *q)
613be1f6
BVA
1563 __releases(q->queue_lock)
1564 __acquires(q->queue_lock)
1da177e4
LT
1565{
1566 struct scsi_device *sdev = q->queuedata;
1567 struct Scsi_Host *shost;
1568 struct scsi_cmnd *cmd;
1569 struct request *req;
1570
1da177e4
LT
1571 /*
1572 * To start with, we keep looping until the queue is empty, or until
1573 * the host is no longer able to accept any more requests.
1574 */
1575 shost = sdev->host;
a488e749 1576 for (;;) {
1da177e4
LT
1577 int rtn;
1578 /*
1579 * get next queueable request. We do this early to make sure
1580 * that the request is fully prepared even if we cannot
1581 * accept it.
1582 */
9934c8c0 1583 req = blk_peek_request(q);
1da177e4
LT
1584 if (!req || !scsi_dev_queue_ready(q, sdev))
1585 break;
1586
1587 if (unlikely(!scsi_device_online(sdev))) {
9ccfc756
JB
1588 sdev_printk(KERN_ERR, sdev,
1589 "rejecting I/O to offline device\n");
e91442b6 1590 scsi_kill_request(req, q);
1da177e4
LT
1591 continue;
1592 }
1593
1594
1595 /*
1596 * Remove the request from the request list.
1597 */
1598 if (!(blk_queue_tagged(q) && !blk_queue_start_tag(q, req)))
9934c8c0 1599 blk_start_request(req);
1da177e4
LT
1600 sdev->device_busy++;
1601
1602 spin_unlock(q->queue_lock);
e91442b6
JB
1603 cmd = req->special;
1604 if (unlikely(cmd == NULL)) {
1605 printk(KERN_CRIT "impossible request in %s.\n"
1606 "please mail a stack trace to "
4aff5e23 1607 "linux-scsi@vger.kernel.org\n",
cadbd4a5 1608 __func__);
4aff5e23 1609 blk_dump_rq_flags(req, "foo");
e91442b6
JB
1610 BUG();
1611 }
1da177e4
LT
1612 spin_lock(shost->host_lock);
1613
ecefe8a9
MC
1614 /*
1615 * We hit this when the driver is using a host wide
1616 * tag map. For device level tag maps the queue_depth check
1617 * in the device ready fn would prevent us from trying
1618 * to allocate a tag. Since the map is a shared host resource
1619 * we add the dev to the starved list so it eventually gets
1620 * a run when a tag is freed.
1621 */
6bd522f6 1622 if (blk_queue_tagged(q) && !blk_rq_tagged(req)) {
ecefe8a9
MC
1623 if (list_empty(&sdev->starved_entry))
1624 list_add_tail(&sdev->starved_entry,
1625 &shost->starved_list);
1626 goto not_ready;
1627 }
1628
f0c0a376
MC
1629 if (!scsi_target_queue_ready(shost, sdev))
1630 goto not_ready;
1631
1da177e4
LT
1632 if (!scsi_host_queue_ready(q, shost, sdev))
1633 goto not_ready;
f0c0a376
MC
1634
1635 scsi_target(sdev)->target_busy++;
1da177e4
LT
1636 shost->host_busy++;
1637
1638 /*
1639 * XXX(hch): This is rather suboptimal, scsi_dispatch_cmd will
1640 * take the lock again.
1641 */
1642 spin_unlock_irq(shost->host_lock);
1643
1da177e4
LT
1644 /*
1645 * Finally, initialize any error handling parameters, and set up
1646 * the timers for timeouts.
1647 */
1648 scsi_init_cmd_errh(cmd);
1649
1650 /*
1651 * Dispatch the command to the low-level driver.
1652 */
1653 rtn = scsi_dispatch_cmd(cmd);
1654 spin_lock_irq(q->queue_lock);
a488e749
JA
1655 if (rtn)
1656 goto out_delay;
1da177e4
LT
1657 }
1658
613be1f6 1659 return;
1da177e4
LT
1660
1661 not_ready:
1662 spin_unlock_irq(shost->host_lock);
1663
1664 /*
1665 * lock q, handle tag, requeue req, and decrement device_busy. We
1666 * must return with queue_lock held.
1667 *
1668 * Decrementing device_busy without checking it is OK, as all such
1669 * cases (host limits or settings) should run the queue at some
1670 * later time.
1671 */
1672 spin_lock_irq(q->queue_lock);
1673 blk_requeue_request(q, req);
1674 sdev->device_busy--;
a488e749
JA
1675out_delay:
1676 if (sdev->device_busy == 0)
1677 blk_delay_queue(q, SCSI_QUEUE_DELAY);
1da177e4
LT
1678}
1679
1680u64 scsi_calculate_bounce_limit(struct Scsi_Host *shost)
1681{
1682 struct device *host_dev;
1683 u64 bounce_limit = 0xffffffff;
1684
1685 if (shost->unchecked_isa_dma)
1686 return BLK_BOUNCE_ISA;
1687 /*
1688 * Platforms with virtual-DMA translation
1689 * hardware have no practical limit.
1690 */
1691 if (!PCI_DMA_BUS_IS_PHYS)
1692 return BLK_BOUNCE_ANY;
1693
1694 host_dev = scsi_get_device(shost);
1695 if (host_dev && host_dev->dma_mask)
e83b3664 1696 bounce_limit = (u64)dma_max_pfn(host_dev) << PAGE_SHIFT;
1da177e4
LT
1697
1698 return bounce_limit;
1699}
1700EXPORT_SYMBOL(scsi_calculate_bounce_limit);
1701
b58d9154
FT
1702struct request_queue *__scsi_alloc_queue(struct Scsi_Host *shost,
1703 request_fn_proc *request_fn)
1da177e4 1704{
1da177e4 1705 struct request_queue *q;
6f381fa3 1706 struct device *dev = shost->dma_dev;
1da177e4 1707
b58d9154 1708 q = blk_init_queue(request_fn, NULL);
1da177e4
LT
1709 if (!q)
1710 return NULL;
1711
a8474ce2
JA
1712 /*
1713 * this limit is imposed by hardware restrictions
1714 */
8a78362c
MP
1715 blk_queue_max_segments(q, min_t(unsigned short, shost->sg_tablesize,
1716 SCSI_MAX_SG_CHAIN_SEGMENTS));
a8474ce2 1717
13f05c8d
MP
1718 if (scsi_host_prot_dma(shost)) {
1719 shost->sg_prot_tablesize =
1720 min_not_zero(shost->sg_prot_tablesize,
1721 (unsigned short)SCSI_MAX_PROT_SG_SEGMENTS);
1722 BUG_ON(shost->sg_prot_tablesize < shost->sg_tablesize);
1723 blk_queue_max_integrity_segments(q, shost->sg_prot_tablesize);
1724 }
1725
086fa5ff 1726 blk_queue_max_hw_sectors(q, shost->max_sectors);
1da177e4
LT
1727 blk_queue_bounce_limit(q, scsi_calculate_bounce_limit(shost));
1728 blk_queue_segment_boundary(q, shost->dma_boundary);
99c84dbd 1729 dma_set_seg_boundary(dev, shost->dma_boundary);
1da177e4 1730
860ac568
FT
1731 blk_queue_max_segment_size(q, dma_get_max_seg_size(dev));
1732
1da177e4 1733 if (!shost->use_clustering)
e692cb66 1734 q->limits.cluster = 0;
465ff318
JB
1735
1736 /*
1737 * set a reasonable default alignment on word boundaries: the
1738 * host and device may alter it using
1739 * blk_queue_update_dma_alignment() later.
1740 */
1741 blk_queue_dma_alignment(q, 0x03);
1742
1da177e4
LT
1743 return q;
1744}
b58d9154
FT
1745EXPORT_SYMBOL(__scsi_alloc_queue);
1746
1747struct request_queue *scsi_alloc_queue(struct scsi_device *sdev)
1748{
1749 struct request_queue *q;
1750
1751 q = __scsi_alloc_queue(sdev->host, scsi_request_fn);
1752 if (!q)
1753 return NULL;
1754
1755 blk_queue_prep_rq(q, scsi_prep_fn);
b58d9154 1756 blk_queue_softirq_done(q, scsi_softirq_done);
242f9dcb 1757 blk_queue_rq_timed_out(q, scsi_times_out);
6c5121b7 1758 blk_queue_lld_busy(q, scsi_lld_busy);
b58d9154
FT
1759 return q;
1760}
1da177e4 1761
1da177e4
LT
1762/*
1763 * Function: scsi_block_requests()
1764 *
1765 * Purpose: Utility function used by low-level drivers to prevent further
1766 * commands from being queued to the device.
1767 *
1768 * Arguments: shost - Host in question
1769 *
1770 * Returns: Nothing
1771 *
1772 * Lock status: No locks are assumed held.
1773 *
1774 * Notes: There is no timer nor any other means by which the requests
1775 * get unblocked other than the low-level driver calling
1776 * scsi_unblock_requests().
1777 */
1778void scsi_block_requests(struct Scsi_Host *shost)
1779{
1780 shost->host_self_blocked = 1;
1781}
1782EXPORT_SYMBOL(scsi_block_requests);
1783
1784/*
1785 * Function: scsi_unblock_requests()
1786 *
1787 * Purpose: Utility function used by low-level drivers to allow further
1788 * commands from being queued to the device.
1789 *
1790 * Arguments: shost - Host in question
1791 *
1792 * Returns: Nothing
1793 *
1794 * Lock status: No locks are assumed held.
1795 *
1796 * Notes: There is no timer nor any other means by which the requests
1797 * get unblocked other than the low-level driver calling
1798 * scsi_unblock_requests().
1799 *
1800 * This is done as an API function so that changes to the
1801 * internals of the scsi mid-layer won't require wholesale
1802 * changes to drivers that use this feature.
1803 */
1804void scsi_unblock_requests(struct Scsi_Host *shost)
1805{
1806 shost->host_self_blocked = 0;
1807 scsi_run_host_queues(shost);
1808}
1809EXPORT_SYMBOL(scsi_unblock_requests);
1810
1811int __init scsi_init_queue(void)
1812{
1813 int i;
1814
6362abd3
MP
1815 scsi_sdb_cache = kmem_cache_create("scsi_data_buffer",
1816 sizeof(struct scsi_data_buffer),
1817 0, 0, NULL);
1818 if (!scsi_sdb_cache) {
1819 printk(KERN_ERR "SCSI: can't init scsi sdb cache\n");
f078727b 1820 return -ENOMEM;
6f9a35e2
BH
1821 }
1822
1da177e4
LT
1823 for (i = 0; i < SG_MEMPOOL_NR; i++) {
1824 struct scsi_host_sg_pool *sgp = scsi_sg_pools + i;
1825 int size = sgp->size * sizeof(struct scatterlist);
1826
1827 sgp->slab = kmem_cache_create(sgp->name, size, 0,
20c2df83 1828 SLAB_HWCACHE_ALIGN, NULL);
1da177e4
LT
1829 if (!sgp->slab) {
1830 printk(KERN_ERR "SCSI: can't init sg slab %s\n",
1831 sgp->name);
6362abd3 1832 goto cleanup_sdb;
1da177e4
LT
1833 }
1834
93d2341c
MD
1835 sgp->pool = mempool_create_slab_pool(SG_MEMPOOL_SIZE,
1836 sgp->slab);
1da177e4
LT
1837 if (!sgp->pool) {
1838 printk(KERN_ERR "SCSI: can't init sg mempool %s\n",
1839 sgp->name);
6362abd3 1840 goto cleanup_sdb;
1da177e4
LT
1841 }
1842 }
1843
1844 return 0;
3d9dd6ee 1845
6362abd3 1846cleanup_sdb:
3d9dd6ee
FT
1847 for (i = 0; i < SG_MEMPOOL_NR; i++) {
1848 struct scsi_host_sg_pool *sgp = scsi_sg_pools + i;
1849 if (sgp->pool)
1850 mempool_destroy(sgp->pool);
1851 if (sgp->slab)
1852 kmem_cache_destroy(sgp->slab);
1853 }
6362abd3 1854 kmem_cache_destroy(scsi_sdb_cache);
3d9dd6ee
FT
1855
1856 return -ENOMEM;
1da177e4
LT
1857}
1858
1859void scsi_exit_queue(void)
1860{
1861 int i;
1862
6362abd3 1863 kmem_cache_destroy(scsi_sdb_cache);
aa7b5cd7 1864
1da177e4
LT
1865 for (i = 0; i < SG_MEMPOOL_NR; i++) {
1866 struct scsi_host_sg_pool *sgp = scsi_sg_pools + i;
1867 mempool_destroy(sgp->pool);
1868 kmem_cache_destroy(sgp->slab);
1869 }
1870}
5baba830
JB
1871
1872/**
1873 * scsi_mode_select - issue a mode select
1874 * @sdev: SCSI device to be queried
1875 * @pf: Page format bit (1 == standard, 0 == vendor specific)
1876 * @sp: Save page bit (0 == don't save, 1 == save)
1877 * @modepage: mode page being requested
1878 * @buffer: request buffer (may not be smaller than eight bytes)
1879 * @len: length of request buffer.
1880 * @timeout: command timeout
1881 * @retries: number of retries before failing
1882 * @data: returns a structure abstracting the mode header data
eb44820c 1883 * @sshdr: place to put sense data (or NULL if no sense to be collected).
5baba830
JB
1884 * must be SCSI_SENSE_BUFFERSIZE big.
1885 *
1886 * Returns zero if successful; negative error number or scsi
1887 * status on error
1888 *
1889 */
1890int
1891scsi_mode_select(struct scsi_device *sdev, int pf, int sp, int modepage,
1892 unsigned char *buffer, int len, int timeout, int retries,
1893 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
1894{
1895 unsigned char cmd[10];
1896 unsigned char *real_buffer;
1897 int ret;
1898
1899 memset(cmd, 0, sizeof(cmd));
1900 cmd[1] = (pf ? 0x10 : 0) | (sp ? 0x01 : 0);
1901
1902 if (sdev->use_10_for_ms) {
1903 if (len > 65535)
1904 return -EINVAL;
1905 real_buffer = kmalloc(8 + len, GFP_KERNEL);
1906 if (!real_buffer)
1907 return -ENOMEM;
1908 memcpy(real_buffer + 8, buffer, len);
1909 len += 8;
1910 real_buffer[0] = 0;
1911 real_buffer[1] = 0;
1912 real_buffer[2] = data->medium_type;
1913 real_buffer[3] = data->device_specific;
1914 real_buffer[4] = data->longlba ? 0x01 : 0;
1915 real_buffer[5] = 0;
1916 real_buffer[6] = data->block_descriptor_length >> 8;
1917 real_buffer[7] = data->block_descriptor_length;
1918
1919 cmd[0] = MODE_SELECT_10;
1920 cmd[7] = len >> 8;
1921 cmd[8] = len;
1922 } else {
1923 if (len > 255 || data->block_descriptor_length > 255 ||
1924 data->longlba)
1925 return -EINVAL;
1926
1927 real_buffer = kmalloc(4 + len, GFP_KERNEL);
1928 if (!real_buffer)
1929 return -ENOMEM;
1930 memcpy(real_buffer + 4, buffer, len);
1931 len += 4;
1932 real_buffer[0] = 0;
1933 real_buffer[1] = data->medium_type;
1934 real_buffer[2] = data->device_specific;
1935 real_buffer[3] = data->block_descriptor_length;
1936
1937
1938 cmd[0] = MODE_SELECT;
1939 cmd[4] = len;
1940 }
1941
1942 ret = scsi_execute_req(sdev, cmd, DMA_TO_DEVICE, real_buffer, len,
f4f4e47e 1943 sshdr, timeout, retries, NULL);
5baba830
JB
1944 kfree(real_buffer);
1945 return ret;
1946}
1947EXPORT_SYMBOL_GPL(scsi_mode_select);
1948
1da177e4 1949/**
eb44820c 1950 * scsi_mode_sense - issue a mode sense, falling back from 10 to six bytes if necessary.
1cf72699 1951 * @sdev: SCSI device to be queried
1da177e4
LT
1952 * @dbd: set if mode sense will allow block descriptors to be returned
1953 * @modepage: mode page being requested
1954 * @buffer: request buffer (may not be smaller than eight bytes)
1955 * @len: length of request buffer.
1956 * @timeout: command timeout
1957 * @retries: number of retries before failing
1958 * @data: returns a structure abstracting the mode header data
eb44820c 1959 * @sshdr: place to put sense data (or NULL if no sense to be collected).
1cf72699 1960 * must be SCSI_SENSE_BUFFERSIZE big.
1da177e4
LT
1961 *
1962 * Returns zero if unsuccessful, or the header offset (either 4
1963 * or 8 depending on whether a six or ten byte command was
1964 * issued) if successful.
eb44820c 1965 */
1da177e4 1966int
1cf72699 1967scsi_mode_sense(struct scsi_device *sdev, int dbd, int modepage,
1da177e4 1968 unsigned char *buffer, int len, int timeout, int retries,
5baba830
JB
1969 struct scsi_mode_data *data, struct scsi_sense_hdr *sshdr)
1970{
1da177e4
LT
1971 unsigned char cmd[12];
1972 int use_10_for_ms;
1973 int header_length;
1cf72699 1974 int result;
ea73a9f2 1975 struct scsi_sense_hdr my_sshdr;
1da177e4
LT
1976
1977 memset(data, 0, sizeof(*data));
1978 memset(&cmd[0], 0, 12);
1979 cmd[1] = dbd & 0x18; /* allows DBD and LLBA bits */
1980 cmd[2] = modepage;
1981
ea73a9f2
JB
1982 /* caller might not be interested in sense, but we need it */
1983 if (!sshdr)
1984 sshdr = &my_sshdr;
1985
1da177e4 1986 retry:
1cf72699 1987 use_10_for_ms = sdev->use_10_for_ms;
1da177e4
LT
1988
1989 if (use_10_for_ms) {
1990 if (len < 8)
1991 len = 8;
1992
1993 cmd[0] = MODE_SENSE_10;
1994 cmd[8] = len;
1995 header_length = 8;
1996 } else {
1997 if (len < 4)
1998 len = 4;
1999
2000 cmd[0] = MODE_SENSE;
2001 cmd[4] = len;
2002 header_length = 4;
2003 }
2004
1da177e4
LT
2005 memset(buffer, 0, len);
2006
1cf72699 2007 result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buffer, len,
f4f4e47e 2008 sshdr, timeout, retries, NULL);
1da177e4
LT
2009
2010 /* This code looks awful: what it's doing is making sure an
2011 * ILLEGAL REQUEST sense return identifies the actual command
2012 * byte as the problem. MODE_SENSE commands can return
2013 * ILLEGAL REQUEST if the code page isn't supported */
2014
1cf72699
JB
2015 if (use_10_for_ms && !scsi_status_is_good(result) &&
2016 (driver_byte(result) & DRIVER_SENSE)) {
ea73a9f2
JB
2017 if (scsi_sense_valid(sshdr)) {
2018 if ((sshdr->sense_key == ILLEGAL_REQUEST) &&
2019 (sshdr->asc == 0x20) && (sshdr->ascq == 0)) {
1da177e4
LT
2020 /*
2021 * Invalid command operation code
2022 */
1cf72699 2023 sdev->use_10_for_ms = 0;
1da177e4
LT
2024 goto retry;
2025 }
2026 }
2027 }
2028
1cf72699 2029 if(scsi_status_is_good(result)) {
6d73c851
AV
2030 if (unlikely(buffer[0] == 0x86 && buffer[1] == 0x0b &&
2031 (modepage == 6 || modepage == 8))) {
2032 /* Initio breakage? */
2033 header_length = 0;
2034 data->length = 13;
2035 data->medium_type = 0;
2036 data->device_specific = 0;
2037 data->longlba = 0;
2038 data->block_descriptor_length = 0;
2039 } else if(use_10_for_ms) {
1da177e4
LT
2040 data->length = buffer[0]*256 + buffer[1] + 2;
2041 data->medium_type = buffer[2];
2042 data->device_specific = buffer[3];
2043 data->longlba = buffer[4] & 0x01;
2044 data->block_descriptor_length = buffer[6]*256
2045 + buffer[7];
2046 } else {
2047 data->length = buffer[0] + 1;
2048 data->medium_type = buffer[1];
2049 data->device_specific = buffer[2];
2050 data->block_descriptor_length = buffer[3];
2051 }
6d73c851 2052 data->header_length = header_length;
1da177e4
LT
2053 }
2054
1cf72699 2055 return result;
1da177e4
LT
2056}
2057EXPORT_SYMBOL(scsi_mode_sense);
2058
001aac25
JB
2059/**
2060 * scsi_test_unit_ready - test if unit is ready
2061 * @sdev: scsi device to change the state of.
2062 * @timeout: command timeout
2063 * @retries: number of retries before failing
2064 * @sshdr_external: Optional pointer to struct scsi_sense_hdr for
2065 * returning sense. Make sure that this is cleared before passing
2066 * in.
2067 *
2068 * Returns zero if unsuccessful or an error if TUR failed. For
9f8a2c23 2069 * removable media, UNIT_ATTENTION sets ->changed flag.
001aac25 2070 **/
1da177e4 2071int
001aac25
JB
2072scsi_test_unit_ready(struct scsi_device *sdev, int timeout, int retries,
2073 struct scsi_sense_hdr *sshdr_external)
1da177e4 2074{
1da177e4
LT
2075 char cmd[] = {
2076 TEST_UNIT_READY, 0, 0, 0, 0, 0,
2077 };
001aac25 2078 struct scsi_sense_hdr *sshdr;
1da177e4 2079 int result;
001aac25
JB
2080
2081 if (!sshdr_external)
2082 sshdr = kzalloc(sizeof(*sshdr), GFP_KERNEL);
2083 else
2084 sshdr = sshdr_external;
2085
2086 /* try to eat the UNIT_ATTENTION if there are enough retries */
2087 do {
2088 result = scsi_execute_req(sdev, cmd, DMA_NONE, NULL, 0, sshdr,
f4f4e47e 2089 timeout, retries, NULL);
32c356d7
JB
2090 if (sdev->removable && scsi_sense_valid(sshdr) &&
2091 sshdr->sense_key == UNIT_ATTENTION)
2092 sdev->changed = 1;
2093 } while (scsi_sense_valid(sshdr) &&
2094 sshdr->sense_key == UNIT_ATTENTION && --retries);
001aac25 2095
001aac25
JB
2096 if (!sshdr_external)
2097 kfree(sshdr);
1da177e4
LT
2098 return result;
2099}
2100EXPORT_SYMBOL(scsi_test_unit_ready);
2101
2102/**
eb44820c 2103 * scsi_device_set_state - Take the given device through the device state model.
1da177e4
LT
2104 * @sdev: scsi device to change the state of.
2105 * @state: state to change to.
2106 *
2107 * Returns zero if unsuccessful or an error if the requested
2108 * transition is illegal.
eb44820c 2109 */
1da177e4
LT
2110int
2111scsi_device_set_state(struct scsi_device *sdev, enum scsi_device_state state)
2112{
2113 enum scsi_device_state oldstate = sdev->sdev_state;
2114
2115 if (state == oldstate)
2116 return 0;
2117
2118 switch (state) {
2119 case SDEV_CREATED:
6f4267e3
JB
2120 switch (oldstate) {
2121 case SDEV_CREATED_BLOCK:
2122 break;
2123 default:
2124 goto illegal;
2125 }
2126 break;
1da177e4
LT
2127
2128 case SDEV_RUNNING:
2129 switch (oldstate) {
2130 case SDEV_CREATED:
2131 case SDEV_OFFLINE:
1b8d2620 2132 case SDEV_TRANSPORT_OFFLINE:
1da177e4
LT
2133 case SDEV_QUIESCE:
2134 case SDEV_BLOCK:
2135 break;
2136 default:
2137 goto illegal;
2138 }
2139 break;
2140
2141 case SDEV_QUIESCE:
2142 switch (oldstate) {
2143 case SDEV_RUNNING:
2144 case SDEV_OFFLINE:
1b8d2620 2145 case SDEV_TRANSPORT_OFFLINE:
1da177e4
LT
2146 break;
2147 default:
2148 goto illegal;
2149 }
2150 break;
2151
2152 case SDEV_OFFLINE:
1b8d2620 2153 case SDEV_TRANSPORT_OFFLINE:
1da177e4
LT
2154 switch (oldstate) {
2155 case SDEV_CREATED:
2156 case SDEV_RUNNING:
2157 case SDEV_QUIESCE:
2158 case SDEV_BLOCK:
2159 break;
2160 default:
2161 goto illegal;
2162 }
2163 break;
2164
2165 case SDEV_BLOCK:
2166 switch (oldstate) {
1da177e4 2167 case SDEV_RUNNING:
6f4267e3
JB
2168 case SDEV_CREATED_BLOCK:
2169 break;
2170 default:
2171 goto illegal;
2172 }
2173 break;
2174
2175 case SDEV_CREATED_BLOCK:
2176 switch (oldstate) {
2177 case SDEV_CREATED:
1da177e4
LT
2178 break;
2179 default:
2180 goto illegal;
2181 }
2182 break;
2183
2184 case SDEV_CANCEL:
2185 switch (oldstate) {
2186 case SDEV_CREATED:
2187 case SDEV_RUNNING:
9ea72909 2188 case SDEV_QUIESCE:
1da177e4 2189 case SDEV_OFFLINE:
1b8d2620 2190 case SDEV_TRANSPORT_OFFLINE:
1da177e4
LT
2191 case SDEV_BLOCK:
2192 break;
2193 default:
2194 goto illegal;
2195 }
2196 break;
2197
2198 case SDEV_DEL:
2199 switch (oldstate) {
309bd271
BK
2200 case SDEV_CREATED:
2201 case SDEV_RUNNING:
2202 case SDEV_OFFLINE:
1b8d2620 2203 case SDEV_TRANSPORT_OFFLINE:
1da177e4 2204 case SDEV_CANCEL:
0516c08d 2205 case SDEV_CREATED_BLOCK:
1da177e4
LT
2206 break;
2207 default:
2208 goto illegal;
2209 }
2210 break;
2211
2212 }
2213 sdev->sdev_state = state;
2214 return 0;
2215
2216 illegal:
2217 SCSI_LOG_ERROR_RECOVERY(1,
9ccfc756
JB
2218 sdev_printk(KERN_ERR, sdev,
2219 "Illegal state transition %s->%s\n",
2220 scsi_device_state_name(oldstate),
2221 scsi_device_state_name(state))
1da177e4
LT
2222 );
2223 return -EINVAL;
2224}
2225EXPORT_SYMBOL(scsi_device_set_state);
2226
a341cd0f
JG
2227/**
2228 * sdev_evt_emit - emit a single SCSI device uevent
2229 * @sdev: associated SCSI device
2230 * @evt: event to emit
2231 *
2232 * Send a single uevent (scsi_event) to the associated scsi_device.
2233 */
2234static void scsi_evt_emit(struct scsi_device *sdev, struct scsi_event *evt)
2235{
2236 int idx = 0;
2237 char *envp[3];
2238
2239 switch (evt->evt_type) {
2240 case SDEV_EVT_MEDIA_CHANGE:
2241 envp[idx++] = "SDEV_MEDIA_CHANGE=1";
2242 break;
279afdfe
EM
2243 case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
2244 envp[idx++] = "SDEV_UA=INQUIRY_DATA_HAS_CHANGED";
2245 break;
2246 case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
2247 envp[idx++] = "SDEV_UA=CAPACITY_DATA_HAS_CHANGED";
2248 break;
2249 case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
2250 envp[idx++] = "SDEV_UA=THIN_PROVISIONING_SOFT_THRESHOLD_REACHED";
2251 break;
2252 case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
2253 envp[idx++] = "SDEV_UA=MODE_PARAMETERS_CHANGED";
2254 break;
2255 case SDEV_EVT_LUN_CHANGE_REPORTED:
2256 envp[idx++] = "SDEV_UA=REPORTED_LUNS_DATA_HAS_CHANGED";
2257 break;
a341cd0f
JG
2258 default:
2259 /* do nothing */
2260 break;
2261 }
2262
2263 envp[idx++] = NULL;
2264
2265 kobject_uevent_env(&sdev->sdev_gendev.kobj, KOBJ_CHANGE, envp);
2266}
2267
2268/**
2269 * sdev_evt_thread - send a uevent for each scsi event
2270 * @work: work struct for scsi_device
2271 *
2272 * Dispatch queued events to their associated scsi_device kobjects
2273 * as uevents.
2274 */
2275void scsi_evt_thread(struct work_struct *work)
2276{
2277 struct scsi_device *sdev;
279afdfe 2278 enum scsi_device_event evt_type;
a341cd0f
JG
2279 LIST_HEAD(event_list);
2280
2281 sdev = container_of(work, struct scsi_device, event_work);
2282
279afdfe
EM
2283 for (evt_type = SDEV_EVT_FIRST; evt_type <= SDEV_EVT_LAST; evt_type++)
2284 if (test_and_clear_bit(evt_type, sdev->pending_events))
2285 sdev_evt_send_simple(sdev, evt_type, GFP_KERNEL);
2286
a341cd0f
JG
2287 while (1) {
2288 struct scsi_event *evt;
2289 struct list_head *this, *tmp;
2290 unsigned long flags;
2291
2292 spin_lock_irqsave(&sdev->list_lock, flags);
2293 list_splice_init(&sdev->event_list, &event_list);
2294 spin_unlock_irqrestore(&sdev->list_lock, flags);
2295
2296 if (list_empty(&event_list))
2297 break;
2298
2299 list_for_each_safe(this, tmp, &event_list) {
2300 evt = list_entry(this, struct scsi_event, node);
2301 list_del(&evt->node);
2302 scsi_evt_emit(sdev, evt);
2303 kfree(evt);
2304 }
2305 }
2306}
2307
2308/**
2309 * sdev_evt_send - send asserted event to uevent thread
2310 * @sdev: scsi_device event occurred on
2311 * @evt: event to send
2312 *
2313 * Assert scsi device event asynchronously.
2314 */
2315void sdev_evt_send(struct scsi_device *sdev, struct scsi_event *evt)
2316{
2317 unsigned long flags;
2318
4d1566ed
KS
2319#if 0
2320 /* FIXME: currently this check eliminates all media change events
2321 * for polled devices. Need to update to discriminate between AN
2322 * and polled events */
a341cd0f
JG
2323 if (!test_bit(evt->evt_type, sdev->supported_events)) {
2324 kfree(evt);
2325 return;
2326 }
4d1566ed 2327#endif
a341cd0f
JG
2328
2329 spin_lock_irqsave(&sdev->list_lock, flags);
2330 list_add_tail(&evt->node, &sdev->event_list);
2331 schedule_work(&sdev->event_work);
2332 spin_unlock_irqrestore(&sdev->list_lock, flags);
2333}
2334EXPORT_SYMBOL_GPL(sdev_evt_send);
2335
2336/**
2337 * sdev_evt_alloc - allocate a new scsi event
2338 * @evt_type: type of event to allocate
2339 * @gfpflags: GFP flags for allocation
2340 *
2341 * Allocates and returns a new scsi_event.
2342 */
2343struct scsi_event *sdev_evt_alloc(enum scsi_device_event evt_type,
2344 gfp_t gfpflags)
2345{
2346 struct scsi_event *evt = kzalloc(sizeof(struct scsi_event), gfpflags);
2347 if (!evt)
2348 return NULL;
2349
2350 evt->evt_type = evt_type;
2351 INIT_LIST_HEAD(&evt->node);
2352
2353 /* evt_type-specific initialization, if any */
2354 switch (evt_type) {
2355 case SDEV_EVT_MEDIA_CHANGE:
279afdfe
EM
2356 case SDEV_EVT_INQUIRY_CHANGE_REPORTED:
2357 case SDEV_EVT_CAPACITY_CHANGE_REPORTED:
2358 case SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED:
2359 case SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED:
2360 case SDEV_EVT_LUN_CHANGE_REPORTED:
a341cd0f
JG
2361 default:
2362 /* do nothing */
2363 break;
2364 }
2365
2366 return evt;
2367}
2368EXPORT_SYMBOL_GPL(sdev_evt_alloc);
2369
2370/**
2371 * sdev_evt_send_simple - send asserted event to uevent thread
2372 * @sdev: scsi_device event occurred on
2373 * @evt_type: type of event to send
2374 * @gfpflags: GFP flags for allocation
2375 *
2376 * Assert scsi device event asynchronously, given an event type.
2377 */
2378void sdev_evt_send_simple(struct scsi_device *sdev,
2379 enum scsi_device_event evt_type, gfp_t gfpflags)
2380{
2381 struct scsi_event *evt = sdev_evt_alloc(evt_type, gfpflags);
2382 if (!evt) {
2383 sdev_printk(KERN_ERR, sdev, "event %d eaten due to OOM\n",
2384 evt_type);
2385 return;
2386 }
2387
2388 sdev_evt_send(sdev, evt);
2389}
2390EXPORT_SYMBOL_GPL(sdev_evt_send_simple);
2391
1da177e4
LT
2392/**
2393 * scsi_device_quiesce - Block user issued commands.
2394 * @sdev: scsi device to quiesce.
2395 *
2396 * This works by trying to transition to the SDEV_QUIESCE state
2397 * (which must be a legal transition). When the device is in this
2398 * state, only special requests will be accepted, all others will
2399 * be deferred. Since special requests may also be requeued requests,
2400 * a successful return doesn't guarantee the device will be
2401 * totally quiescent.
2402 *
2403 * Must be called with user context, may sleep.
2404 *
2405 * Returns zero if unsuccessful or an error if not.
eb44820c 2406 */
1da177e4
LT
2407int
2408scsi_device_quiesce(struct scsi_device *sdev)
2409{
2410 int err = scsi_device_set_state(sdev, SDEV_QUIESCE);
2411 if (err)
2412 return err;
2413
2414 scsi_run_queue(sdev->request_queue);
2415 while (sdev->device_busy) {
2416 msleep_interruptible(200);
2417 scsi_run_queue(sdev->request_queue);
2418 }
2419 return 0;
2420}
2421EXPORT_SYMBOL(scsi_device_quiesce);
2422
2423/**
2424 * scsi_device_resume - Restart user issued commands to a quiesced device.
2425 * @sdev: scsi device to resume.
2426 *
2427 * Moves the device from quiesced back to running and restarts the
2428 * queues.
2429 *
2430 * Must be called with user context, may sleep.
eb44820c 2431 */
a7a20d10 2432void scsi_device_resume(struct scsi_device *sdev)
1da177e4 2433{
a7a20d10
DW
2434 /* check if the device state was mutated prior to resume, and if
2435 * so assume the state is being managed elsewhere (for example
2436 * device deleted during suspend)
2437 */
2438 if (sdev->sdev_state != SDEV_QUIESCE ||
2439 scsi_device_set_state(sdev, SDEV_RUNNING))
1da177e4
LT
2440 return;
2441 scsi_run_queue(sdev->request_queue);
2442}
2443EXPORT_SYMBOL(scsi_device_resume);
2444
2445static void
2446device_quiesce_fn(struct scsi_device *sdev, void *data)
2447{
2448 scsi_device_quiesce(sdev);
2449}
2450
2451void
2452scsi_target_quiesce(struct scsi_target *starget)
2453{
2454 starget_for_each_device(starget, NULL, device_quiesce_fn);
2455}
2456EXPORT_SYMBOL(scsi_target_quiesce);
2457
2458static void
2459device_resume_fn(struct scsi_device *sdev, void *data)
2460{
2461 scsi_device_resume(sdev);
2462}
2463
2464void
2465scsi_target_resume(struct scsi_target *starget)
2466{
2467 starget_for_each_device(starget, NULL, device_resume_fn);
2468}
2469EXPORT_SYMBOL(scsi_target_resume);
2470
2471/**
eb44820c 2472 * scsi_internal_device_block - internal function to put a device temporarily into the SDEV_BLOCK state
1da177e4
LT
2473 * @sdev: device to block
2474 *
2475 * Block request made by scsi lld's to temporarily stop all
2476 * scsi commands on the specified device. Called from interrupt
2477 * or normal process context.
2478 *
2479 * Returns zero if successful or error if not
2480 *
2481 * Notes:
2482 * This routine transitions the device to the SDEV_BLOCK state
2483 * (which must be a legal transition). When the device is in this
2484 * state, all commands are deferred until the scsi lld reenables
2485 * the device with scsi_device_unblock or device_block_tmo fires.
eb44820c 2486 */
1da177e4
LT
2487int
2488scsi_internal_device_block(struct scsi_device *sdev)
2489{
165125e1 2490 struct request_queue *q = sdev->request_queue;
1da177e4
LT
2491 unsigned long flags;
2492 int err = 0;
2493
2494 err = scsi_device_set_state(sdev, SDEV_BLOCK);
6f4267e3
JB
2495 if (err) {
2496 err = scsi_device_set_state(sdev, SDEV_CREATED_BLOCK);
2497
2498 if (err)
2499 return err;
2500 }
1da177e4
LT
2501
2502 /*
2503 * The device has transitioned to SDEV_BLOCK. Stop the
2504 * block layer from calling the midlayer with this device's
2505 * request queue.
2506 */
2507 spin_lock_irqsave(q->queue_lock, flags);
2508 blk_stop_queue(q);
2509 spin_unlock_irqrestore(q->queue_lock, flags);
2510
2511 return 0;
2512}
2513EXPORT_SYMBOL_GPL(scsi_internal_device_block);
2514
2515/**
2516 * scsi_internal_device_unblock - resume a device after a block request
2517 * @sdev: device to resume
5d9fb5cc 2518 * @new_state: state to set devices to after unblocking
1da177e4
LT
2519 *
2520 * Called by scsi lld's or the midlayer to restart the device queue
2521 * for the previously suspended scsi device. Called from interrupt or
2522 * normal process context.
2523 *
2524 * Returns zero if successful or error if not.
2525 *
2526 * Notes:
2527 * This routine transitions the device to the SDEV_RUNNING state
5d9fb5cc 2528 * or to one of the offline states (which must be a legal transition)
d075498c 2529 * allowing the midlayer to goose the queue for this device.
eb44820c 2530 */
1da177e4 2531int
5d9fb5cc
MC
2532scsi_internal_device_unblock(struct scsi_device *sdev,
2533 enum scsi_device_state new_state)
1da177e4 2534{
165125e1 2535 struct request_queue *q = sdev->request_queue;
1da177e4 2536 unsigned long flags;
5d9fb5cc
MC
2537
2538 /*
2539 * Try to transition the scsi device to SDEV_RUNNING or one of the
2540 * offlined states and goose the device queue if successful.
1da177e4 2541 */
0e58076b
VC
2542 if ((sdev->sdev_state == SDEV_BLOCK) ||
2543 (sdev->sdev_state == SDEV_TRANSPORT_OFFLINE))
5d9fb5cc
MC
2544 sdev->sdev_state = new_state;
2545 else if (sdev->sdev_state == SDEV_CREATED_BLOCK) {
2546 if (new_state == SDEV_TRANSPORT_OFFLINE ||
2547 new_state == SDEV_OFFLINE)
2548 sdev->sdev_state = new_state;
2549 else
2550 sdev->sdev_state = SDEV_CREATED;
2551 } else if (sdev->sdev_state != SDEV_CANCEL &&
986fe6c7 2552 sdev->sdev_state != SDEV_OFFLINE)
5c10e63c 2553 return -EINVAL;
1da177e4
LT
2554
2555 spin_lock_irqsave(q->queue_lock, flags);
2556 blk_start_queue(q);
2557 spin_unlock_irqrestore(q->queue_lock, flags);
2558
2559 return 0;
2560}
2561EXPORT_SYMBOL_GPL(scsi_internal_device_unblock);
2562
2563static void
2564device_block(struct scsi_device *sdev, void *data)
2565{
2566 scsi_internal_device_block(sdev);
2567}
2568
2569static int
2570target_block(struct device *dev, void *data)
2571{
2572 if (scsi_is_target_device(dev))
2573 starget_for_each_device(to_scsi_target(dev), NULL,
2574 device_block);
2575 return 0;
2576}
2577
2578void
2579scsi_target_block(struct device *dev)
2580{
2581 if (scsi_is_target_device(dev))
2582 starget_for_each_device(to_scsi_target(dev), NULL,
2583 device_block);
2584 else
2585 device_for_each_child(dev, NULL, target_block);
2586}
2587EXPORT_SYMBOL_GPL(scsi_target_block);
2588
2589static void
2590device_unblock(struct scsi_device *sdev, void *data)
2591{
5d9fb5cc 2592 scsi_internal_device_unblock(sdev, *(enum scsi_device_state *)data);
1da177e4
LT
2593}
2594
2595static int
2596target_unblock(struct device *dev, void *data)
2597{
2598 if (scsi_is_target_device(dev))
5d9fb5cc 2599 starget_for_each_device(to_scsi_target(dev), data,
1da177e4
LT
2600 device_unblock);
2601 return 0;
2602}
2603
2604void
5d9fb5cc 2605scsi_target_unblock(struct device *dev, enum scsi_device_state new_state)
1da177e4
LT
2606{
2607 if (scsi_is_target_device(dev))
5d9fb5cc 2608 starget_for_each_device(to_scsi_target(dev), &new_state,
1da177e4
LT
2609 device_unblock);
2610 else
5d9fb5cc 2611 device_for_each_child(dev, &new_state, target_unblock);
1da177e4
LT
2612}
2613EXPORT_SYMBOL_GPL(scsi_target_unblock);
cdb8c2a6
GL
2614
2615/**
2616 * scsi_kmap_atomic_sg - find and atomically map an sg-elemnt
eb44820c 2617 * @sgl: scatter-gather list
cdb8c2a6
GL
2618 * @sg_count: number of segments in sg
2619 * @offset: offset in bytes into sg, on return offset into the mapped area
2620 * @len: bytes to map, on return number of bytes mapped
2621 *
2622 * Returns virtual address of the start of the mapped page
2623 */
c6132da1 2624void *scsi_kmap_atomic_sg(struct scatterlist *sgl, int sg_count,
cdb8c2a6
GL
2625 size_t *offset, size_t *len)
2626{
2627 int i;
2628 size_t sg_len = 0, len_complete = 0;
c6132da1 2629 struct scatterlist *sg;
cdb8c2a6
GL
2630 struct page *page;
2631
22cfefb5
AM
2632 WARN_ON(!irqs_disabled());
2633
c6132da1 2634 for_each_sg(sgl, sg, sg_count, i) {
cdb8c2a6 2635 len_complete = sg_len; /* Complete sg-entries */
c6132da1 2636 sg_len += sg->length;
cdb8c2a6
GL
2637 if (sg_len > *offset)
2638 break;
2639 }
2640
2641 if (unlikely(i == sg_count)) {
169e1a2a
AM
2642 printk(KERN_ERR "%s: Bytes in sg: %zu, requested offset %zu, "
2643 "elements %d\n",
cadbd4a5 2644 __func__, sg_len, *offset, sg_count);
cdb8c2a6
GL
2645 WARN_ON(1);
2646 return NULL;
2647 }
2648
2649 /* Offset starting from the beginning of first page in this sg-entry */
c6132da1 2650 *offset = *offset - len_complete + sg->offset;
cdb8c2a6
GL
2651
2652 /* Assumption: contiguous pages can be accessed as "page + i" */
45711f1a 2653 page = nth_page(sg_page(sg), (*offset >> PAGE_SHIFT));
cdb8c2a6
GL
2654 *offset &= ~PAGE_MASK;
2655
2656 /* Bytes in this sg-entry from *offset to the end of the page */
2657 sg_len = PAGE_SIZE - *offset;
2658 if (*len > sg_len)
2659 *len = sg_len;
2660
77dfce07 2661 return kmap_atomic(page);
cdb8c2a6
GL
2662}
2663EXPORT_SYMBOL(scsi_kmap_atomic_sg);
2664
2665/**
eb44820c 2666 * scsi_kunmap_atomic_sg - atomically unmap a virtual address, previously mapped with scsi_kmap_atomic_sg
cdb8c2a6
GL
2667 * @virt: virtual address to be unmapped
2668 */
2669void scsi_kunmap_atomic_sg(void *virt)
2670{
77dfce07 2671 kunmap_atomic(virt);
cdb8c2a6
GL
2672}
2673EXPORT_SYMBOL(scsi_kunmap_atomic_sg);
6f4c827e
AL
2674
2675void sdev_disable_disk_events(struct scsi_device *sdev)
2676{
2677 atomic_inc(&sdev->disk_events_disable_depth);
2678}
2679EXPORT_SYMBOL(sdev_disable_disk_events);
2680
2681void sdev_enable_disk_events(struct scsi_device *sdev)
2682{
2683 if (WARN_ON_ONCE(atomic_read(&sdev->disk_events_disable_depth) <= 0))
2684 return;
2685 atomic_dec(&sdev->disk_events_disable_depth);
2686}
2687EXPORT_SYMBOL(sdev_enable_disk_events);