scsi: core: Ensure that the SCSI error handler gets woken up
[platform/kernel/linux-exynos.git] / drivers / scsi / scsi_error.c
1 /*
2  *  scsi_error.c Copyright (C) 1997 Eric Youngdale
3  *
4  *  SCSI error/timeout handling
5  *      Initial versions: Eric Youngdale.  Based upon conversations with
6  *                        Leonard Zubkoff and David Miller at Linux Expo,
7  *                        ideas originating from all over the place.
8  *
9  *      Restructured scsi_unjam_host and associated functions.
10  *      September 04, 2002 Mike Anderson (andmike@us.ibm.com)
11  *
12  *      Forward port of Russell King's (rmk@arm.linux.org.uk) changes and
13  *      minor cleanups.
14  *      September 30, 2002 Mike Anderson (andmike@us.ibm.com)
15  */
16
17 #include <linux/module.h>
18 #include <linux/sched.h>
19 #include <linux/gfp.h>
20 #include <linux/timer.h>
21 #include <linux/string.h>
22 #include <linux/kernel.h>
23 #include <linux/freezer.h>
24 #include <linux/kthread.h>
25 #include <linux/interrupt.h>
26 #include <linux/blkdev.h>
27 #include <linux/delay.h>
28 #include <linux/jiffies.h>
29
30 #include <scsi/scsi.h>
31 #include <scsi/scsi_cmnd.h>
32 #include <scsi/scsi_dbg.h>
33 #include <scsi/scsi_device.h>
34 #include <scsi/scsi_driver.h>
35 #include <scsi/scsi_eh.h>
36 #include <scsi/scsi_common.h>
37 #include <scsi/scsi_transport.h>
38 #include <scsi/scsi_host.h>
39 #include <scsi/scsi_ioctl.h>
40 #include <scsi/scsi_dh.h>
41 #include <scsi/sg.h>
42
43 #include "scsi_priv.h"
44 #include "scsi_logging.h"
45 #include "scsi_transport_api.h"
46
47 #include <trace/events/scsi.h>
48
49 #include <asm/unaligned.h>
50
51 static void scsi_eh_done(struct scsi_cmnd *scmd);
52
53 /*
54  * These should *probably* be handled by the host itself.
55  * Since it is allowed to sleep, it probably should.
56  */
57 #define BUS_RESET_SETTLE_TIME   (10)
58 #define HOST_RESET_SETTLE_TIME  (10)
59
60 static int scsi_eh_try_stu(struct scsi_cmnd *scmd);
61 static int scsi_try_to_abort_cmd(struct scsi_host_template *,
62                                  struct scsi_cmnd *);
63
64 /* called with shost->host_lock held */
65 void scsi_eh_wakeup(struct Scsi_Host *shost)
66 {
67         if (atomic_read(&shost->host_busy) == shost->host_failed) {
68                 trace_scsi_eh_wakeup(shost);
69                 wake_up_process(shost->ehandler);
70                 SCSI_LOG_ERROR_RECOVERY(5, shost_printk(KERN_INFO, shost,
71                         "Waking error handler thread\n"));
72         }
73 }
74
75 /**
76  * scsi_schedule_eh - schedule EH for SCSI host
77  * @shost:      SCSI host to invoke error handling on.
78  *
79  * Schedule SCSI EH without scmd.
80  */
81 void scsi_schedule_eh(struct Scsi_Host *shost)
82 {
83         unsigned long flags;
84
85         spin_lock_irqsave(shost->host_lock, flags);
86
87         if (scsi_host_set_state(shost, SHOST_RECOVERY) == 0 ||
88             scsi_host_set_state(shost, SHOST_CANCEL_RECOVERY) == 0) {
89                 shost->host_eh_scheduled++;
90                 scsi_eh_wakeup(shost);
91         }
92
93         spin_unlock_irqrestore(shost->host_lock, flags);
94 }
95 EXPORT_SYMBOL_GPL(scsi_schedule_eh);
96
97 static int scsi_host_eh_past_deadline(struct Scsi_Host *shost)
98 {
99         if (!shost->last_reset || shost->eh_deadline == -1)
100                 return 0;
101
102         /*
103          * 32bit accesses are guaranteed to be atomic
104          * (on all supported architectures), so instead
105          * of using a spinlock we can as well double check
106          * if eh_deadline has been set to 'off' during the
107          * time_before call.
108          */
109         if (time_before(jiffies, shost->last_reset + shost->eh_deadline) &&
110             shost->eh_deadline > -1)
111                 return 0;
112
113         return 1;
114 }
115
116 /**
117  * scmd_eh_abort_handler - Handle command aborts
118  * @work:       command to be aborted.
119  */
120 void
121 scmd_eh_abort_handler(struct work_struct *work)
122 {
123         struct scsi_cmnd *scmd =
124                 container_of(work, struct scsi_cmnd, abort_work.work);
125         struct scsi_device *sdev = scmd->device;
126         int rtn;
127
128         if (scsi_host_eh_past_deadline(sdev->host)) {
129                 SCSI_LOG_ERROR_RECOVERY(3,
130                         scmd_printk(KERN_INFO, scmd,
131                                     "eh timeout, not aborting\n"));
132         } else {
133                 SCSI_LOG_ERROR_RECOVERY(3,
134                         scmd_printk(KERN_INFO, scmd,
135                                     "aborting command\n"));
136                 rtn = scsi_try_to_abort_cmd(sdev->host->hostt, scmd);
137                 if (rtn == SUCCESS) {
138                         set_host_byte(scmd, DID_TIME_OUT);
139                         if (scsi_host_eh_past_deadline(sdev->host)) {
140                                 SCSI_LOG_ERROR_RECOVERY(3,
141                                         scmd_printk(KERN_INFO, scmd,
142                                                     "eh timeout, not retrying "
143                                                     "aborted command\n"));
144                         } else if (!scsi_noretry_cmd(scmd) &&
145                             (++scmd->retries <= scmd->allowed)) {
146                                 SCSI_LOG_ERROR_RECOVERY(3,
147                                         scmd_printk(KERN_WARNING, scmd,
148                                                     "retry aborted command\n"));
149                                 scsi_queue_insert(scmd, SCSI_MLQUEUE_EH_RETRY);
150                                 return;
151                         } else {
152                                 SCSI_LOG_ERROR_RECOVERY(3,
153                                         scmd_printk(KERN_WARNING, scmd,
154                                                     "finish aborted command\n"));
155                                 scsi_finish_command(scmd);
156                                 return;
157                         }
158                 } else {
159                         SCSI_LOG_ERROR_RECOVERY(3,
160                                 scmd_printk(KERN_INFO, scmd,
161                                             "cmd abort %s\n",
162                                             (rtn == FAST_IO_FAIL) ?
163                                             "not send" : "failed"));
164                 }
165         }
166
167         scsi_eh_scmd_add(scmd);
168 }
169
170 /**
171  * scsi_abort_command - schedule a command abort
172  * @scmd:       scmd to abort.
173  *
174  * We only need to abort commands after a command timeout
175  */
176 static int
177 scsi_abort_command(struct scsi_cmnd *scmd)
178 {
179         struct scsi_device *sdev = scmd->device;
180         struct Scsi_Host *shost = sdev->host;
181         unsigned long flags;
182
183         if (scmd->eh_eflags & SCSI_EH_ABORT_SCHEDULED) {
184                 /*
185                  * Retry after abort failed, escalate to next level.
186                  */
187                 SCSI_LOG_ERROR_RECOVERY(3,
188                         scmd_printk(KERN_INFO, scmd,
189                                     "previous abort failed\n"));
190                 BUG_ON(delayed_work_pending(&scmd->abort_work));
191                 return FAILED;
192         }
193
194         spin_lock_irqsave(shost->host_lock, flags);
195         if (shost->eh_deadline != -1 && !shost->last_reset)
196                 shost->last_reset = jiffies;
197         spin_unlock_irqrestore(shost->host_lock, flags);
198
199         scmd->eh_eflags |= SCSI_EH_ABORT_SCHEDULED;
200         SCSI_LOG_ERROR_RECOVERY(3,
201                 scmd_printk(KERN_INFO, scmd, "abort scheduled\n"));
202         queue_delayed_work(shost->tmf_work_q, &scmd->abort_work, HZ / 100);
203         return SUCCESS;
204 }
205
206 /**
207  * scsi_eh_reset - call into ->eh_action to reset internal counters
208  * @scmd:       scmd to run eh on.
209  *
210  * The scsi driver might be carrying internal state about the
211  * devices, so we need to call into the driver to reset the
212  * internal state once the error handler is started.
213  */
214 static void scsi_eh_reset(struct scsi_cmnd *scmd)
215 {
216         if (!blk_rq_is_passthrough(scmd->request)) {
217                 struct scsi_driver *sdrv = scsi_cmd_to_driver(scmd);
218                 if (sdrv->eh_reset)
219                         sdrv->eh_reset(scmd);
220         }
221 }
222
223 static void scsi_eh_inc_host_failed(struct rcu_head *head)
224 {
225         struct Scsi_Host *shost = container_of(head, typeof(*shost), rcu);
226         unsigned long flags;
227
228         spin_lock_irqsave(shost->host_lock, flags);
229         shost->host_failed++;
230         scsi_eh_wakeup(shost);
231         spin_unlock_irqrestore(shost->host_lock, flags);
232 }
233
234 /**
235  * scsi_eh_scmd_add - add scsi cmd to error handling.
236  * @scmd:       scmd to run eh on.
237  */
238 void scsi_eh_scmd_add(struct scsi_cmnd *scmd)
239 {
240         struct Scsi_Host *shost = scmd->device->host;
241         unsigned long flags;
242         int ret;
243
244         WARN_ON_ONCE(!shost->ehandler);
245
246         spin_lock_irqsave(shost->host_lock, flags);
247         if (scsi_host_set_state(shost, SHOST_RECOVERY)) {
248                 ret = scsi_host_set_state(shost, SHOST_CANCEL_RECOVERY);
249                 WARN_ON_ONCE(ret);
250         }
251         if (shost->eh_deadline != -1 && !shost->last_reset)
252                 shost->last_reset = jiffies;
253
254         scsi_eh_reset(scmd);
255         list_add_tail(&scmd->eh_entry, &shost->eh_cmd_q);
256         spin_unlock_irqrestore(shost->host_lock, flags);
257         /*
258          * Ensure that all tasks observe the host state change before the
259          * host_failed change.
260          */
261         call_rcu(&shost->rcu, scsi_eh_inc_host_failed);
262 }
263
264 /**
265  * scsi_times_out - Timeout function for normal scsi commands.
266  * @req:        request that is timing out.
267  *
268  * Notes:
269  *     We do not need to lock this.  There is the potential for a race
270  *     only in that the normal completion handling might run, but if the
271  *     normal completion function determines that the timer has already
272  *     fired, then it mustn't do anything.
273  */
274 enum blk_eh_timer_return scsi_times_out(struct request *req)
275 {
276         struct scsi_cmnd *scmd = blk_mq_rq_to_pdu(req);
277         enum blk_eh_timer_return rtn = BLK_EH_NOT_HANDLED;
278         struct Scsi_Host *host = scmd->device->host;
279
280         trace_scsi_dispatch_cmd_timeout(scmd);
281         scsi_log_completion(scmd, TIMEOUT_ERROR);
282
283         if (host->eh_deadline != -1 && !host->last_reset)
284                 host->last_reset = jiffies;
285
286         if (host->hostt->eh_timed_out)
287                 rtn = host->hostt->eh_timed_out(scmd);
288
289         if (rtn == BLK_EH_NOT_HANDLED) {
290                 if (scsi_abort_command(scmd) != SUCCESS) {
291                         set_host_byte(scmd, DID_TIME_OUT);
292                         scsi_eh_scmd_add(scmd);
293                 }
294         }
295
296         return rtn;
297 }
298
299 /**
300  * scsi_block_when_processing_errors - Prevent cmds from being queued.
301  * @sdev:       Device on which we are performing recovery.
302  *
303  * Description:
304  *     We block until the host is out of error recovery, and then check to
305  *     see whether the host or the device is offline.
306  *
307  * Return value:
308  *     0 when dev was taken offline by error recovery. 1 OK to proceed.
309  */
310 int scsi_block_when_processing_errors(struct scsi_device *sdev)
311 {
312         int online;
313
314         wait_event(sdev->host->host_wait, !scsi_host_in_recovery(sdev->host));
315
316         online = scsi_device_online(sdev);
317
318         SCSI_LOG_ERROR_RECOVERY(5, sdev_printk(KERN_INFO, sdev,
319                 "%s: rtn: %d\n", __func__, online));
320
321         return online;
322 }
323 EXPORT_SYMBOL(scsi_block_when_processing_errors);
324
325 #ifdef CONFIG_SCSI_LOGGING
326 /**
327  * scsi_eh_prt_fail_stats - Log info on failures.
328  * @shost:      scsi host being recovered.
329  * @work_q:     Queue of scsi cmds to process.
330  */
331 static inline void scsi_eh_prt_fail_stats(struct Scsi_Host *shost,
332                                           struct list_head *work_q)
333 {
334         struct scsi_cmnd *scmd;
335         struct scsi_device *sdev;
336         int total_failures = 0;
337         int cmd_failed = 0;
338         int cmd_cancel = 0;
339         int devices_failed = 0;
340
341         shost_for_each_device(sdev, shost) {
342                 list_for_each_entry(scmd, work_q, eh_entry) {
343                         if (scmd->device == sdev) {
344                                 ++total_failures;
345                                 if (scmd->eh_eflags & SCSI_EH_ABORT_SCHEDULED)
346                                         ++cmd_cancel;
347                                 else
348                                         ++cmd_failed;
349                         }
350                 }
351
352                 if (cmd_cancel || cmd_failed) {
353                         SCSI_LOG_ERROR_RECOVERY(3,
354                                 shost_printk(KERN_INFO, shost,
355                                             "%s: cmds failed: %d, cancel: %d\n",
356                                             __func__, cmd_failed,
357                                             cmd_cancel));
358                         cmd_cancel = 0;
359                         cmd_failed = 0;
360                         ++devices_failed;
361                 }
362         }
363
364         SCSI_LOG_ERROR_RECOVERY(2, shost_printk(KERN_INFO, shost,
365                                    "Total of %d commands on %d"
366                                    " devices require eh work\n",
367                                    total_failures, devices_failed));
368 }
369 #endif
370
371  /**
372  * scsi_report_lun_change - Set flag on all *other* devices on the same target
373  *                          to indicate that a UNIT ATTENTION is expected.
374  * @sdev:       Device reporting the UNIT ATTENTION
375  */
376 static void scsi_report_lun_change(struct scsi_device *sdev)
377 {
378         sdev->sdev_target->expecting_lun_change = 1;
379 }
380
381 /**
382  * scsi_report_sense - Examine scsi sense information and log messages for
383  *                     certain conditions, also issue uevents for some of them.
384  * @sdev:       Device reporting the sense code
385  * @sshdr:      sshdr to be examined
386  */
387 static void scsi_report_sense(struct scsi_device *sdev,
388                               struct scsi_sense_hdr *sshdr)
389 {
390         enum scsi_device_event evt_type = SDEV_EVT_MAXBITS;     /* i.e. none */
391
392         if (sshdr->sense_key == UNIT_ATTENTION) {
393                 if (sshdr->asc == 0x3f && sshdr->ascq == 0x03) {
394                         evt_type = SDEV_EVT_INQUIRY_CHANGE_REPORTED;
395                         sdev_printk(KERN_WARNING, sdev,
396                                     "Inquiry data has changed");
397                 } else if (sshdr->asc == 0x3f && sshdr->ascq == 0x0e) {
398                         evt_type = SDEV_EVT_LUN_CHANGE_REPORTED;
399                         scsi_report_lun_change(sdev);
400                         sdev_printk(KERN_WARNING, sdev,
401                                     "Warning! Received an indication that the "
402                                     "LUN assignments on this target have "
403                                     "changed. The Linux SCSI layer does not "
404                                     "automatically remap LUN assignments.\n");
405                 } else if (sshdr->asc == 0x3f)
406                         sdev_printk(KERN_WARNING, sdev,
407                                     "Warning! Received an indication that the "
408                                     "operating parameters on this target have "
409                                     "changed. The Linux SCSI layer does not "
410                                     "automatically adjust these parameters.\n");
411
412                 if (sshdr->asc == 0x38 && sshdr->ascq == 0x07) {
413                         evt_type = SDEV_EVT_SOFT_THRESHOLD_REACHED_REPORTED;
414                         sdev_printk(KERN_WARNING, sdev,
415                                     "Warning! Received an indication that the "
416                                     "LUN reached a thin provisioning soft "
417                                     "threshold.\n");
418                 }
419
420                 if (sshdr->asc == 0x2a && sshdr->ascq == 0x01) {
421                         evt_type = SDEV_EVT_MODE_PARAMETER_CHANGE_REPORTED;
422                         sdev_printk(KERN_WARNING, sdev,
423                                     "Mode parameters changed");
424                 } else if (sshdr->asc == 0x2a && sshdr->ascq == 0x06) {
425                         evt_type = SDEV_EVT_ALUA_STATE_CHANGE_REPORTED;
426                         sdev_printk(KERN_WARNING, sdev,
427                                     "Asymmetric access state changed");
428                 } else if (sshdr->asc == 0x2a && sshdr->ascq == 0x09) {
429                         evt_type = SDEV_EVT_CAPACITY_CHANGE_REPORTED;
430                         sdev_printk(KERN_WARNING, sdev,
431                                     "Capacity data has changed");
432                 } else if (sshdr->asc == 0x2a)
433                         sdev_printk(KERN_WARNING, sdev,
434                                     "Parameters changed");
435         }
436
437         if (evt_type != SDEV_EVT_MAXBITS) {
438                 set_bit(evt_type, sdev->pending_events);
439                 schedule_work(&sdev->event_work);
440         }
441 }
442
443 /**
444  * scsi_check_sense - Examine scsi cmd sense
445  * @scmd:       Cmd to have sense checked.
446  *
447  * Return value:
448  *      SUCCESS or FAILED or NEEDS_RETRY or ADD_TO_MLQUEUE
449  *
450  * Notes:
451  *      When a deferred error is detected the current command has
452  *      not been executed and needs retrying.
453  */
454 int scsi_check_sense(struct scsi_cmnd *scmd)
455 {
456         struct scsi_device *sdev = scmd->device;
457         struct scsi_sense_hdr sshdr;
458
459         if (! scsi_command_normalize_sense(scmd, &sshdr))
460                 return FAILED;  /* no valid sense data */
461
462         scsi_report_sense(sdev, &sshdr);
463
464         if (scsi_sense_is_deferred(&sshdr))
465                 return NEEDS_RETRY;
466
467         if (sdev->handler && sdev->handler->check_sense) {
468                 int rc;
469
470                 rc = sdev->handler->check_sense(sdev, &sshdr);
471                 if (rc != SCSI_RETURN_NOT_HANDLED)
472                         return rc;
473                 /* handler does not care. Drop down to default handling */
474         }
475
476         if (scmd->cmnd[0] == TEST_UNIT_READY && scmd->scsi_done != scsi_eh_done)
477                 /*
478                  * nasty: for mid-layer issued TURs, we need to return the
479                  * actual sense data without any recovery attempt.  For eh
480                  * issued ones, we need to try to recover and interpret
481                  */
482                 return SUCCESS;
483
484         /*
485          * Previous logic looked for FILEMARK, EOM or ILI which are
486          * mainly associated with tapes and returned SUCCESS.
487          */
488         if (sshdr.response_code == 0x70) {
489                 /* fixed format */
490                 if (scmd->sense_buffer[2] & 0xe0)
491                         return SUCCESS;
492         } else {
493                 /*
494                  * descriptor format: look for "stream commands sense data
495                  * descriptor" (see SSC-3). Assume single sense data
496                  * descriptor. Ignore ILI from SBC-2 READ LONG and WRITE LONG.
497                  */
498                 if ((sshdr.additional_length > 3) &&
499                     (scmd->sense_buffer[8] == 0x4) &&
500                     (scmd->sense_buffer[11] & 0xe0))
501                         return SUCCESS;
502         }
503
504         switch (sshdr.sense_key) {
505         case NO_SENSE:
506                 return SUCCESS;
507         case RECOVERED_ERROR:
508                 return /* soft_error */ SUCCESS;
509
510         case ABORTED_COMMAND:
511                 if (sshdr.asc == 0x10) /* DIF */
512                         return SUCCESS;
513
514                 return NEEDS_RETRY;
515         case NOT_READY:
516         case UNIT_ATTENTION:
517                 /*
518                  * if we are expecting a cc/ua because of a bus reset that we
519                  * performed, treat this just as a retry.  otherwise this is
520                  * information that we should pass up to the upper-level driver
521                  * so that we can deal with it there.
522                  */
523                 if (scmd->device->expecting_cc_ua) {
524                         /*
525                          * Because some device does not queue unit
526                          * attentions correctly, we carefully check
527                          * additional sense code and qualifier so as
528                          * not to squash media change unit attention.
529                          */
530                         if (sshdr.asc != 0x28 || sshdr.ascq != 0x00) {
531                                 scmd->device->expecting_cc_ua = 0;
532                                 return NEEDS_RETRY;
533                         }
534                 }
535                 /*
536                  * we might also expect a cc/ua if another LUN on the target
537                  * reported a UA with an ASC/ASCQ of 3F 0E -
538                  * REPORTED LUNS DATA HAS CHANGED.
539                  */
540                 if (scmd->device->sdev_target->expecting_lun_change &&
541                     sshdr.asc == 0x3f && sshdr.ascq == 0x0e)
542                         return NEEDS_RETRY;
543                 /*
544                  * if the device is in the process of becoming ready, we
545                  * should retry.
546                  */
547                 if ((sshdr.asc == 0x04) && (sshdr.ascq == 0x01))
548                         return NEEDS_RETRY;
549                 /*
550                  * if the device is not started, we need to wake
551                  * the error handler to start the motor
552                  */
553                 if (scmd->device->allow_restart &&
554                     (sshdr.asc == 0x04) && (sshdr.ascq == 0x02))
555                         return FAILED;
556                 /*
557                  * Pass the UA upwards for a determination in the completion
558                  * functions.
559                  */
560                 return SUCCESS;
561
562                 /* these are not supported */
563         case DATA_PROTECT:
564                 if (sshdr.asc == 0x27 && sshdr.ascq == 0x07) {
565                         /* Thin provisioning hard threshold reached */
566                         set_host_byte(scmd, DID_ALLOC_FAILURE);
567                         return SUCCESS;
568                 }
569                 /* FALLTHROUGH */
570         case COPY_ABORTED:
571         case VOLUME_OVERFLOW:
572         case MISCOMPARE:
573         case BLANK_CHECK:
574                 set_host_byte(scmd, DID_TARGET_FAILURE);
575                 return SUCCESS;
576
577         case MEDIUM_ERROR:
578                 if (sshdr.asc == 0x11 || /* UNRECOVERED READ ERR */
579                     sshdr.asc == 0x13 || /* AMNF DATA FIELD */
580                     sshdr.asc == 0x14) { /* RECORD NOT FOUND */
581                         set_host_byte(scmd, DID_MEDIUM_ERROR);
582                         return SUCCESS;
583                 }
584                 return NEEDS_RETRY;
585
586         case HARDWARE_ERROR:
587                 if (scmd->device->retry_hwerror)
588                         return ADD_TO_MLQUEUE;
589                 else
590                         set_host_byte(scmd, DID_TARGET_FAILURE);
591                 /* FALLTHROUGH */
592
593         case ILLEGAL_REQUEST:
594                 if (sshdr.asc == 0x20 || /* Invalid command operation code */
595                     sshdr.asc == 0x21 || /* Logical block address out of range */
596                     sshdr.asc == 0x24 || /* Invalid field in cdb */
597                     sshdr.asc == 0x26 || /* Parameter value invalid */
598                     sshdr.asc == 0x27) { /* Write protected */
599                         set_host_byte(scmd, DID_TARGET_FAILURE);
600                 }
601                 return SUCCESS;
602
603         default:
604                 return SUCCESS;
605         }
606 }
607 EXPORT_SYMBOL_GPL(scsi_check_sense);
608
609 static void scsi_handle_queue_ramp_up(struct scsi_device *sdev)
610 {
611         struct scsi_host_template *sht = sdev->host->hostt;
612         struct scsi_device *tmp_sdev;
613
614         if (!sht->track_queue_depth ||
615             sdev->queue_depth >= sdev->max_queue_depth)
616                 return;
617
618         if (time_before(jiffies,
619             sdev->last_queue_ramp_up + sdev->queue_ramp_up_period))
620                 return;
621
622         if (time_before(jiffies,
623             sdev->last_queue_full_time + sdev->queue_ramp_up_period))
624                 return;
625
626         /*
627          * Walk all devices of a target and do
628          * ramp up on them.
629          */
630         shost_for_each_device(tmp_sdev, sdev->host) {
631                 if (tmp_sdev->channel != sdev->channel ||
632                     tmp_sdev->id != sdev->id ||
633                     tmp_sdev->queue_depth == sdev->max_queue_depth)
634                         continue;
635
636                 scsi_change_queue_depth(tmp_sdev, tmp_sdev->queue_depth + 1);
637                 sdev->last_queue_ramp_up = jiffies;
638         }
639 }
640
641 static void scsi_handle_queue_full(struct scsi_device *sdev)
642 {
643         struct scsi_host_template *sht = sdev->host->hostt;
644         struct scsi_device *tmp_sdev;
645
646         if (!sht->track_queue_depth)
647                 return;
648
649         shost_for_each_device(tmp_sdev, sdev->host) {
650                 if (tmp_sdev->channel != sdev->channel ||
651                     tmp_sdev->id != sdev->id)
652                         continue;
653                 /*
654                  * We do not know the number of commands that were at
655                  * the device when we got the queue full so we start
656                  * from the highest possible value and work our way down.
657                  */
658                 scsi_track_queue_full(tmp_sdev, tmp_sdev->queue_depth - 1);
659         }
660 }
661
662 /**
663  * scsi_eh_completed_normally - Disposition a eh cmd on return from LLD.
664  * @scmd:       SCSI cmd to examine.
665  *
666  * Notes:
667  *    This is *only* called when we are examining the status of commands
668  *    queued during error recovery.  the main difference here is that we
669  *    don't allow for the possibility of retries here, and we are a lot
670  *    more restrictive about what we consider acceptable.
671  */
672 static int scsi_eh_completed_normally(struct scsi_cmnd *scmd)
673 {
674         /*
675          * first check the host byte, to see if there is anything in there
676          * that would indicate what we need to do.
677          */
678         if (host_byte(scmd->result) == DID_RESET) {
679                 /*
680                  * rats.  we are already in the error handler, so we now
681                  * get to try and figure out what to do next.  if the sense
682                  * is valid, we have a pretty good idea of what to do.
683                  * if not, we mark it as FAILED.
684                  */
685                 return scsi_check_sense(scmd);
686         }
687         if (host_byte(scmd->result) != DID_OK)
688                 return FAILED;
689
690         /*
691          * next, check the message byte.
692          */
693         if (msg_byte(scmd->result) != COMMAND_COMPLETE)
694                 return FAILED;
695
696         /*
697          * now, check the status byte to see if this indicates
698          * anything special.
699          */
700         switch (status_byte(scmd->result)) {
701         case GOOD:
702                 scsi_handle_queue_ramp_up(scmd->device);
703                 /* FALLTHROUGH */
704         case COMMAND_TERMINATED:
705                 return SUCCESS;
706         case CHECK_CONDITION:
707                 return scsi_check_sense(scmd);
708         case CONDITION_GOOD:
709         case INTERMEDIATE_GOOD:
710         case INTERMEDIATE_C_GOOD:
711                 /*
712                  * who knows?  FIXME(eric)
713                  */
714                 return SUCCESS;
715         case RESERVATION_CONFLICT:
716                 if (scmd->cmnd[0] == TEST_UNIT_READY)
717                         /* it is a success, we probed the device and
718                          * found it */
719                         return SUCCESS;
720                 /* otherwise, we failed to send the command */
721                 return FAILED;
722         case QUEUE_FULL:
723                 scsi_handle_queue_full(scmd->device);
724                 /* fall through */
725         case BUSY:
726                 return NEEDS_RETRY;
727         default:
728                 return FAILED;
729         }
730         return FAILED;
731 }
732
733 /**
734  * scsi_eh_done - Completion function for error handling.
735  * @scmd:       Cmd that is done.
736  */
737 static void scsi_eh_done(struct scsi_cmnd *scmd)
738 {
739         struct completion *eh_action;
740
741         SCSI_LOG_ERROR_RECOVERY(3, scmd_printk(KERN_INFO, scmd,
742                         "%s result: %x\n", __func__, scmd->result));
743
744         eh_action = scmd->device->host->eh_action;
745         if (eh_action)
746                 complete(eh_action);
747 }
748
749 /**
750  * scsi_try_host_reset - ask host adapter to reset itself
751  * @scmd:       SCSI cmd to send host reset.
752  */
753 static int scsi_try_host_reset(struct scsi_cmnd *scmd)
754 {
755         unsigned long flags;
756         int rtn;
757         struct Scsi_Host *host = scmd->device->host;
758         struct scsi_host_template *hostt = host->hostt;
759
760         SCSI_LOG_ERROR_RECOVERY(3,
761                 shost_printk(KERN_INFO, host, "Snd Host RST\n"));
762
763         if (!hostt->eh_host_reset_handler)
764                 return FAILED;
765
766         rtn = hostt->eh_host_reset_handler(scmd);
767
768         if (rtn == SUCCESS) {
769                 if (!hostt->skip_settle_delay)
770                         ssleep(HOST_RESET_SETTLE_TIME);
771                 spin_lock_irqsave(host->host_lock, flags);
772                 scsi_report_bus_reset(host, scmd_channel(scmd));
773                 spin_unlock_irqrestore(host->host_lock, flags);
774         }
775
776         return rtn;
777 }
778
779 /**
780  * scsi_try_bus_reset - ask host to perform a bus reset
781  * @scmd:       SCSI cmd to send bus reset.
782  */
783 static int scsi_try_bus_reset(struct scsi_cmnd *scmd)
784 {
785         unsigned long flags;
786         int rtn;
787         struct Scsi_Host *host = scmd->device->host;
788         struct scsi_host_template *hostt = host->hostt;
789
790         SCSI_LOG_ERROR_RECOVERY(3, scmd_printk(KERN_INFO, scmd,
791                 "%s: Snd Bus RST\n", __func__));
792
793         if (!hostt->eh_bus_reset_handler)
794                 return FAILED;
795
796         rtn = hostt->eh_bus_reset_handler(scmd);
797
798         if (rtn == SUCCESS) {
799                 if (!hostt->skip_settle_delay)
800                         ssleep(BUS_RESET_SETTLE_TIME);
801                 spin_lock_irqsave(host->host_lock, flags);
802                 scsi_report_bus_reset(host, scmd_channel(scmd));
803                 spin_unlock_irqrestore(host->host_lock, flags);
804         }
805
806         return rtn;
807 }
808
809 static void __scsi_report_device_reset(struct scsi_device *sdev, void *data)
810 {
811         sdev->was_reset = 1;
812         sdev->expecting_cc_ua = 1;
813 }
814
815 /**
816  * scsi_try_target_reset - Ask host to perform a target reset
817  * @scmd:       SCSI cmd used to send a target reset
818  *
819  * Notes:
820  *    There is no timeout for this operation.  if this operation is
821  *    unreliable for a given host, then the host itself needs to put a
822  *    timer on it, and set the host back to a consistent state prior to
823  *    returning.
824  */
825 static int scsi_try_target_reset(struct scsi_cmnd *scmd)
826 {
827         unsigned long flags;
828         int rtn;
829         struct Scsi_Host *host = scmd->device->host;
830         struct scsi_host_template *hostt = host->hostt;
831
832         if (!hostt->eh_target_reset_handler)
833                 return FAILED;
834
835         rtn = hostt->eh_target_reset_handler(scmd);
836         if (rtn == SUCCESS) {
837                 spin_lock_irqsave(host->host_lock, flags);
838                 __starget_for_each_device(scsi_target(scmd->device), NULL,
839                                           __scsi_report_device_reset);
840                 spin_unlock_irqrestore(host->host_lock, flags);
841         }
842
843         return rtn;
844 }
845
846 /**
847  * scsi_try_bus_device_reset - Ask host to perform a BDR on a dev
848  * @scmd:       SCSI cmd used to send BDR
849  *
850  * Notes:
851  *    There is no timeout for this operation.  if this operation is
852  *    unreliable for a given host, then the host itself needs to put a
853  *    timer on it, and set the host back to a consistent state prior to
854  *    returning.
855  */
856 static int scsi_try_bus_device_reset(struct scsi_cmnd *scmd)
857 {
858         int rtn;
859         struct scsi_host_template *hostt = scmd->device->host->hostt;
860
861         if (!hostt->eh_device_reset_handler)
862                 return FAILED;
863
864         rtn = hostt->eh_device_reset_handler(scmd);
865         if (rtn == SUCCESS)
866                 __scsi_report_device_reset(scmd->device, NULL);
867         return rtn;
868 }
869
870 /**
871  * scsi_try_to_abort_cmd - Ask host to abort a SCSI command
872  * @hostt:      SCSI driver host template
873  * @scmd:       SCSI cmd used to send a target reset
874  *
875  * Return value:
876  *      SUCCESS, FAILED, or FAST_IO_FAIL
877  *
878  * Notes:
879  *    SUCCESS does not necessarily indicate that the command
880  *    has been aborted; it only indicates that the LLDDs
881  *    has cleared all references to that command.
882  *    LLDDs should return FAILED only if an abort was required
883  *    but could not be executed. LLDDs should return FAST_IO_FAIL
884  *    if the device is temporarily unavailable (eg due to a
885  *    link down on FibreChannel)
886  */
887 static int scsi_try_to_abort_cmd(struct scsi_host_template *hostt,
888                                  struct scsi_cmnd *scmd)
889 {
890         if (!hostt->eh_abort_handler)
891                 return FAILED;
892
893         return hostt->eh_abort_handler(scmd);
894 }
895
896 static void scsi_abort_eh_cmnd(struct scsi_cmnd *scmd)
897 {
898         if (scsi_try_to_abort_cmd(scmd->device->host->hostt, scmd) != SUCCESS)
899                 if (scsi_try_bus_device_reset(scmd) != SUCCESS)
900                         if (scsi_try_target_reset(scmd) != SUCCESS)
901                                 if (scsi_try_bus_reset(scmd) != SUCCESS)
902                                         scsi_try_host_reset(scmd);
903 }
904
905 /**
906  * scsi_eh_prep_cmnd  - Save a scsi command info as part of error recovery
907  * @scmd:       SCSI command structure to hijack
908  * @ses:        structure to save restore information
909  * @cmnd:       CDB to send. Can be NULL if no new cmnd is needed
910  * @cmnd_size:  size in bytes of @cmnd (must be <= BLK_MAX_CDB)
911  * @sense_bytes: size of sense data to copy. or 0 (if != 0 @cmnd is ignored)
912  *
913  * This function is used to save a scsi command information before re-execution
914  * as part of the error recovery process.  If @sense_bytes is 0 the command
915  * sent must be one that does not transfer any data.  If @sense_bytes != 0
916  * @cmnd is ignored and this functions sets up a REQUEST_SENSE command
917  * and cmnd buffers to read @sense_bytes into @scmd->sense_buffer.
918  */
919 void scsi_eh_prep_cmnd(struct scsi_cmnd *scmd, struct scsi_eh_save *ses,
920                         unsigned char *cmnd, int cmnd_size, unsigned sense_bytes)
921 {
922         struct scsi_device *sdev = scmd->device;
923
924         /*
925          * We need saved copies of a number of fields - this is because
926          * error handling may need to overwrite these with different values
927          * to run different commands, and once error handling is complete,
928          * we will need to restore these values prior to running the actual
929          * command.
930          */
931         ses->cmd_len = scmd->cmd_len;
932         ses->cmnd = scmd->cmnd;
933         ses->data_direction = scmd->sc_data_direction;
934         ses->sdb = scmd->sdb;
935         ses->next_rq = scmd->request->next_rq;
936         ses->result = scmd->result;
937         ses->underflow = scmd->underflow;
938         ses->prot_op = scmd->prot_op;
939         ses->eh_eflags = scmd->eh_eflags;
940
941         scmd->prot_op = SCSI_PROT_NORMAL;
942         scmd->eh_eflags = 0;
943         scmd->cmnd = ses->eh_cmnd;
944         memset(scmd->cmnd, 0, BLK_MAX_CDB);
945         memset(&scmd->sdb, 0, sizeof(scmd->sdb));
946         scmd->request->next_rq = NULL;
947         scmd->result = 0;
948
949         if (sense_bytes) {
950                 scmd->sdb.length = min_t(unsigned, SCSI_SENSE_BUFFERSIZE,
951                                          sense_bytes);
952                 sg_init_one(&ses->sense_sgl, scmd->sense_buffer,
953                             scmd->sdb.length);
954                 scmd->sdb.table.sgl = &ses->sense_sgl;
955                 scmd->sc_data_direction = DMA_FROM_DEVICE;
956                 scmd->sdb.table.nents = scmd->sdb.table.orig_nents = 1;
957                 scmd->cmnd[0] = REQUEST_SENSE;
958                 scmd->cmnd[4] = scmd->sdb.length;
959                 scmd->cmd_len = COMMAND_SIZE(scmd->cmnd[0]);
960         } else {
961                 scmd->sc_data_direction = DMA_NONE;
962                 if (cmnd) {
963                         BUG_ON(cmnd_size > BLK_MAX_CDB);
964                         memcpy(scmd->cmnd, cmnd, cmnd_size);
965                         scmd->cmd_len = COMMAND_SIZE(scmd->cmnd[0]);
966                 }
967         }
968
969         scmd->underflow = 0;
970
971         if (sdev->scsi_level <= SCSI_2 && sdev->scsi_level != SCSI_UNKNOWN)
972                 scmd->cmnd[1] = (scmd->cmnd[1] & 0x1f) |
973                         (sdev->lun << 5 & 0xe0);
974
975         /*
976          * Zero the sense buffer.  The scsi spec mandates that any
977          * untransferred sense data should be interpreted as being zero.
978          */
979         memset(scmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
980 }
981 EXPORT_SYMBOL(scsi_eh_prep_cmnd);
982
983 /**
984  * scsi_eh_restore_cmnd  - Restore a scsi command info as part of error recovery
985  * @scmd:       SCSI command structure to restore
986  * @ses:        saved information from a coresponding call to scsi_eh_prep_cmnd
987  *
988  * Undo any damage done by above scsi_eh_prep_cmnd().
989  */
990 void scsi_eh_restore_cmnd(struct scsi_cmnd* scmd, struct scsi_eh_save *ses)
991 {
992         /*
993          * Restore original data
994          */
995         scmd->cmd_len = ses->cmd_len;
996         scmd->cmnd = ses->cmnd;
997         scmd->sc_data_direction = ses->data_direction;
998         scmd->sdb = ses->sdb;
999         scmd->request->next_rq = ses->next_rq;
1000         scmd->result = ses->result;
1001         scmd->underflow = ses->underflow;
1002         scmd->prot_op = ses->prot_op;
1003         scmd->eh_eflags = ses->eh_eflags;
1004 }
1005 EXPORT_SYMBOL(scsi_eh_restore_cmnd);
1006
1007 /**
1008  * scsi_send_eh_cmnd  - submit a scsi command as part of error recovery
1009  * @scmd:       SCSI command structure to hijack
1010  * @cmnd:       CDB to send
1011  * @cmnd_size:  size in bytes of @cmnd
1012  * @timeout:    timeout for this request
1013  * @sense_bytes: size of sense data to copy or 0
1014  *
1015  * This function is used to send a scsi command down to a target device
1016  * as part of the error recovery process. See also scsi_eh_prep_cmnd() above.
1017  *
1018  * Return value:
1019  *    SUCCESS or FAILED or NEEDS_RETRY
1020  */
1021 static int scsi_send_eh_cmnd(struct scsi_cmnd *scmd, unsigned char *cmnd,
1022                              int cmnd_size, int timeout, unsigned sense_bytes)
1023 {
1024         struct scsi_device *sdev = scmd->device;
1025         struct Scsi_Host *shost = sdev->host;
1026         DECLARE_COMPLETION_ONSTACK(done);
1027         unsigned long timeleft = timeout;
1028         struct scsi_eh_save ses;
1029         const unsigned long stall_for = msecs_to_jiffies(100);
1030         int rtn;
1031
1032 retry:
1033         scsi_eh_prep_cmnd(scmd, &ses, cmnd, cmnd_size, sense_bytes);
1034         shost->eh_action = &done;
1035
1036         scsi_log_send(scmd);
1037         scmd->scsi_done = scsi_eh_done;
1038         rtn = shost->hostt->queuecommand(shost, scmd);
1039         if (rtn) {
1040                 if (timeleft > stall_for) {
1041                         scsi_eh_restore_cmnd(scmd, &ses);
1042                         timeleft -= stall_for;
1043                         msleep(jiffies_to_msecs(stall_for));
1044                         goto retry;
1045                 }
1046                 /* signal not to enter either branch of the if () below */
1047                 timeleft = 0;
1048                 rtn = FAILED;
1049         } else {
1050                 timeleft = wait_for_completion_timeout(&done, timeout);
1051                 rtn = SUCCESS;
1052         }
1053
1054         shost->eh_action = NULL;
1055
1056         scsi_log_completion(scmd, rtn);
1057
1058         SCSI_LOG_ERROR_RECOVERY(3, scmd_printk(KERN_INFO, scmd,
1059                         "%s timeleft: %ld\n",
1060                         __func__, timeleft));
1061
1062         /*
1063          * If there is time left scsi_eh_done got called, and we will examine
1064          * the actual status codes to see whether the command actually did
1065          * complete normally, else if we have a zero return and no time left,
1066          * the command must still be pending, so abort it and return FAILED.
1067          * If we never actually managed to issue the command, because
1068          * ->queuecommand() kept returning non zero, use the rtn = FAILED
1069          * value above (so don't execute either branch of the if)
1070          */
1071         if (timeleft) {
1072                 rtn = scsi_eh_completed_normally(scmd);
1073                 SCSI_LOG_ERROR_RECOVERY(3, scmd_printk(KERN_INFO, scmd,
1074                         "%s: scsi_eh_completed_normally %x\n", __func__, rtn));
1075
1076                 switch (rtn) {
1077                 case SUCCESS:
1078                 case NEEDS_RETRY:
1079                 case FAILED:
1080                         break;
1081                 case ADD_TO_MLQUEUE:
1082                         rtn = NEEDS_RETRY;
1083                         break;
1084                 default:
1085                         rtn = FAILED;
1086                         break;
1087                 }
1088         } else if (rtn != FAILED) {
1089                 scsi_abort_eh_cmnd(scmd);
1090                 rtn = FAILED;
1091         }
1092
1093         scsi_eh_restore_cmnd(scmd, &ses);
1094
1095         return rtn;
1096 }
1097
1098 /**
1099  * scsi_request_sense - Request sense data from a particular target.
1100  * @scmd:       SCSI cmd for request sense.
1101  *
1102  * Notes:
1103  *    Some hosts automatically obtain this information, others require
1104  *    that we obtain it on our own. This function will *not* return until
1105  *    the command either times out, or it completes.
1106  */
1107 static int scsi_request_sense(struct scsi_cmnd *scmd)
1108 {
1109         return scsi_send_eh_cmnd(scmd, NULL, 0, scmd->device->eh_timeout, ~0);
1110 }
1111
1112 static int scsi_eh_action(struct scsi_cmnd *scmd, int rtn)
1113 {
1114         if (!blk_rq_is_passthrough(scmd->request)) {
1115                 struct scsi_driver *sdrv = scsi_cmd_to_driver(scmd);
1116                 if (sdrv->eh_action)
1117                         rtn = sdrv->eh_action(scmd, rtn);
1118         }
1119         return rtn;
1120 }
1121
1122 /**
1123  * scsi_eh_finish_cmd - Handle a cmd that eh is finished with.
1124  * @scmd:       Original SCSI cmd that eh has finished.
1125  * @done_q:     Queue for processed commands.
1126  *
1127  * Notes:
1128  *    We don't want to use the normal command completion while we are are
1129  *    still handling errors - it may cause other commands to be queued,
1130  *    and that would disturb what we are doing.  Thus we really want to
1131  *    keep a list of pending commands for final completion, and once we
1132  *    are ready to leave error handling we handle completion for real.
1133  */
1134 void scsi_eh_finish_cmd(struct scsi_cmnd *scmd, struct list_head *done_q)
1135 {
1136         list_move_tail(&scmd->eh_entry, done_q);
1137 }
1138 EXPORT_SYMBOL(scsi_eh_finish_cmd);
1139
1140 /**
1141  * scsi_eh_get_sense - Get device sense data.
1142  * @work_q:     Queue of commands to process.
1143  * @done_q:     Queue of processed commands.
1144  *
1145  * Description:
1146  *    See if we need to request sense information.  if so, then get it
1147  *    now, so we have a better idea of what to do.
1148  *
1149  * Notes:
1150  *    This has the unfortunate side effect that if a shost adapter does
1151  *    not automatically request sense information, we end up shutting
1152  *    it down before we request it.
1153  *
1154  *    All drivers should request sense information internally these days,
1155  *    so for now all I have to say is tough noogies if you end up in here.
1156  *
1157  *    XXX: Long term this code should go away, but that needs an audit of
1158  *         all LLDDs first.
1159  */
1160 int scsi_eh_get_sense(struct list_head *work_q,
1161                       struct list_head *done_q)
1162 {
1163         struct scsi_cmnd *scmd, *next;
1164         struct Scsi_Host *shost;
1165         int rtn;
1166
1167         /*
1168          * If SCSI_EH_ABORT_SCHEDULED has been set, it is timeout IO,
1169          * should not get sense.
1170          */
1171         list_for_each_entry_safe(scmd, next, work_q, eh_entry) {
1172                 if ((scmd->eh_eflags & SCSI_EH_ABORT_SCHEDULED) ||
1173                     SCSI_SENSE_VALID(scmd))
1174                         continue;
1175
1176                 shost = scmd->device->host;
1177                 if (scsi_host_eh_past_deadline(shost)) {
1178                         SCSI_LOG_ERROR_RECOVERY(3,
1179                                 scmd_printk(KERN_INFO, scmd,
1180                                             "%s: skip request sense, past eh deadline\n",
1181                                              current->comm));
1182                         break;
1183                 }
1184                 if (status_byte(scmd->result) != CHECK_CONDITION)
1185                         /*
1186                          * don't request sense if there's no check condition
1187                          * status because the error we're processing isn't one
1188                          * that has a sense code (and some devices get
1189                          * confused by sense requests out of the blue)
1190                          */
1191                         continue;
1192
1193                 SCSI_LOG_ERROR_RECOVERY(2, scmd_printk(KERN_INFO, scmd,
1194                                                   "%s: requesting sense\n",
1195                                                   current->comm));
1196                 rtn = scsi_request_sense(scmd);
1197                 if (rtn != SUCCESS)
1198                         continue;
1199
1200                 SCSI_LOG_ERROR_RECOVERY(3, scmd_printk(KERN_INFO, scmd,
1201                         "sense requested, result %x\n", scmd->result));
1202                 SCSI_LOG_ERROR_RECOVERY(3, scsi_print_sense(scmd));
1203
1204                 rtn = scsi_decide_disposition(scmd);
1205
1206                 /*
1207                  * if the result was normal, then just pass it along to the
1208                  * upper level.
1209                  */
1210                 if (rtn == SUCCESS)
1211                         /* we don't want this command reissued, just
1212                          * finished with the sense data, so set
1213                          * retries to the max allowed to ensure it
1214                          * won't get reissued */
1215                         scmd->retries = scmd->allowed;
1216                 else if (rtn != NEEDS_RETRY)
1217                         continue;
1218
1219                 scsi_eh_finish_cmd(scmd, done_q);
1220         }
1221
1222         return list_empty(work_q);
1223 }
1224 EXPORT_SYMBOL_GPL(scsi_eh_get_sense);
1225
1226 /**
1227  * scsi_eh_tur - Send TUR to device.
1228  * @scmd:       &scsi_cmnd to send TUR
1229  *
1230  * Return value:
1231  *    0 - Device is ready. 1 - Device NOT ready.
1232  */
1233 static int scsi_eh_tur(struct scsi_cmnd *scmd)
1234 {
1235         static unsigned char tur_command[6] = {TEST_UNIT_READY, 0, 0, 0, 0, 0};
1236         int retry_cnt = 1, rtn;
1237
1238 retry_tur:
1239         rtn = scsi_send_eh_cmnd(scmd, tur_command, 6,
1240                                 scmd->device->eh_timeout, 0);
1241
1242         SCSI_LOG_ERROR_RECOVERY(3, scmd_printk(KERN_INFO, scmd,
1243                 "%s return: %x\n", __func__, rtn));
1244
1245         switch (rtn) {
1246         case NEEDS_RETRY:
1247                 if (retry_cnt--)
1248                         goto retry_tur;
1249                 /*FALLTHRU*/
1250         case SUCCESS:
1251                 return 0;
1252         default:
1253                 return 1;
1254         }
1255 }
1256
1257 /**
1258  * scsi_eh_test_devices - check if devices are responding from error recovery.
1259  * @cmd_list:   scsi commands in error recovery.
1260  * @work_q:     queue for commands which still need more error recovery
1261  * @done_q:     queue for commands which are finished
1262  * @try_stu:    boolean on if a STU command should be tried in addition to TUR.
1263  *
1264  * Decription:
1265  *    Tests if devices are in a working state.  Commands to devices now in
1266  *    a working state are sent to the done_q while commands to devices which
1267  *    are still failing to respond are returned to the work_q for more
1268  *    processing.
1269  **/
1270 static int scsi_eh_test_devices(struct list_head *cmd_list,
1271                                 struct list_head *work_q,
1272                                 struct list_head *done_q, int try_stu)
1273 {
1274         struct scsi_cmnd *scmd, *next;
1275         struct scsi_device *sdev;
1276         int finish_cmds;
1277
1278         while (!list_empty(cmd_list)) {
1279                 scmd = list_entry(cmd_list->next, struct scsi_cmnd, eh_entry);
1280                 sdev = scmd->device;
1281
1282                 if (!try_stu) {
1283                         if (scsi_host_eh_past_deadline(sdev->host)) {
1284                                 /* Push items back onto work_q */
1285                                 list_splice_init(cmd_list, work_q);
1286                                 SCSI_LOG_ERROR_RECOVERY(3,
1287                                         sdev_printk(KERN_INFO, sdev,
1288                                                     "%s: skip test device, past eh deadline",
1289                                                     current->comm));
1290                                 break;
1291                         }
1292                 }
1293
1294                 finish_cmds = !scsi_device_online(scmd->device) ||
1295                         (try_stu && !scsi_eh_try_stu(scmd) &&
1296                          !scsi_eh_tur(scmd)) ||
1297                         !scsi_eh_tur(scmd);
1298
1299                 list_for_each_entry_safe(scmd, next, cmd_list, eh_entry)
1300                         if (scmd->device == sdev) {
1301                                 if (finish_cmds &&
1302                                     (try_stu ||
1303                                      scsi_eh_action(scmd, SUCCESS) == SUCCESS))
1304                                         scsi_eh_finish_cmd(scmd, done_q);
1305                                 else
1306                                         list_move_tail(&scmd->eh_entry, work_q);
1307                         }
1308         }
1309         return list_empty(work_q);
1310 }
1311
1312 /**
1313  * scsi_eh_try_stu - Send START_UNIT to device.
1314  * @scmd:       &scsi_cmnd to send START_UNIT
1315  *
1316  * Return value:
1317  *    0 - Device is ready. 1 - Device NOT ready.
1318  */
1319 static int scsi_eh_try_stu(struct scsi_cmnd *scmd)
1320 {
1321         static unsigned char stu_command[6] = {START_STOP, 0, 0, 0, 1, 0};
1322
1323         if (scmd->device->allow_restart) {
1324                 int i, rtn = NEEDS_RETRY;
1325
1326                 for (i = 0; rtn == NEEDS_RETRY && i < 2; i++)
1327                         rtn = scsi_send_eh_cmnd(scmd, stu_command, 6, scmd->device->request_queue->rq_timeout, 0);
1328
1329                 if (rtn == SUCCESS)
1330                         return 0;
1331         }
1332
1333         return 1;
1334 }
1335
1336  /**
1337  * scsi_eh_stu - send START_UNIT if needed
1338  * @shost:      &scsi host being recovered.
1339  * @work_q:     &list_head for pending commands.
1340  * @done_q:     &list_head for processed commands.
1341  *
1342  * Notes:
1343  *    If commands are failing due to not ready, initializing command required,
1344  *      try revalidating the device, which will end up sending a start unit.
1345  */
1346 static int scsi_eh_stu(struct Scsi_Host *shost,
1347                               struct list_head *work_q,
1348                               struct list_head *done_q)
1349 {
1350         struct scsi_cmnd *scmd, *stu_scmd, *next;
1351         struct scsi_device *sdev;
1352
1353         shost_for_each_device(sdev, shost) {
1354                 if (scsi_host_eh_past_deadline(shost)) {
1355                         SCSI_LOG_ERROR_RECOVERY(3,
1356                                 sdev_printk(KERN_INFO, sdev,
1357                                             "%s: skip START_UNIT, past eh deadline\n",
1358                                             current->comm));
1359                         break;
1360                 }
1361                 stu_scmd = NULL;
1362                 list_for_each_entry(scmd, work_q, eh_entry)
1363                         if (scmd->device == sdev && SCSI_SENSE_VALID(scmd) &&
1364                             scsi_check_sense(scmd) == FAILED ) {
1365                                 stu_scmd = scmd;
1366                                 break;
1367                         }
1368
1369                 if (!stu_scmd)
1370                         continue;
1371
1372                 SCSI_LOG_ERROR_RECOVERY(3,
1373                         sdev_printk(KERN_INFO, sdev,
1374                                      "%s: Sending START_UNIT\n",
1375                                     current->comm));
1376
1377                 if (!scsi_eh_try_stu(stu_scmd)) {
1378                         if (!scsi_device_online(sdev) ||
1379                             !scsi_eh_tur(stu_scmd)) {
1380                                 list_for_each_entry_safe(scmd, next,
1381                                                           work_q, eh_entry) {
1382                                         if (scmd->device == sdev &&
1383                                             scsi_eh_action(scmd, SUCCESS) == SUCCESS)
1384                                                 scsi_eh_finish_cmd(scmd, done_q);
1385                                 }
1386                         }
1387                 } else {
1388                         SCSI_LOG_ERROR_RECOVERY(3,
1389                                 sdev_printk(KERN_INFO, sdev,
1390                                             "%s: START_UNIT failed\n",
1391                                             current->comm));
1392                 }
1393         }
1394
1395         return list_empty(work_q);
1396 }
1397
1398
1399 /**
1400  * scsi_eh_bus_device_reset - send bdr if needed
1401  * @shost:      scsi host being recovered.
1402  * @work_q:     &list_head for pending commands.
1403  * @done_q:     &list_head for processed commands.
1404  *
1405  * Notes:
1406  *    Try a bus device reset.  Still, look to see whether we have multiple
1407  *    devices that are jammed or not - if we have multiple devices, it
1408  *    makes no sense to try bus_device_reset - we really would need to try
1409  *    a bus_reset instead.
1410  */
1411 static int scsi_eh_bus_device_reset(struct Scsi_Host *shost,
1412                                     struct list_head *work_q,
1413                                     struct list_head *done_q)
1414 {
1415         struct scsi_cmnd *scmd, *bdr_scmd, *next;
1416         struct scsi_device *sdev;
1417         int rtn;
1418
1419         shost_for_each_device(sdev, shost) {
1420                 if (scsi_host_eh_past_deadline(shost)) {
1421                         SCSI_LOG_ERROR_RECOVERY(3,
1422                                 sdev_printk(KERN_INFO, sdev,
1423                                             "%s: skip BDR, past eh deadline\n",
1424                                              current->comm));
1425                         break;
1426                 }
1427                 bdr_scmd = NULL;
1428                 list_for_each_entry(scmd, work_q, eh_entry)
1429                         if (scmd->device == sdev) {
1430                                 bdr_scmd = scmd;
1431                                 break;
1432                         }
1433
1434                 if (!bdr_scmd)
1435                         continue;
1436
1437                 SCSI_LOG_ERROR_RECOVERY(3,
1438                         sdev_printk(KERN_INFO, sdev,
1439                                      "%s: Sending BDR\n", current->comm));
1440                 rtn = scsi_try_bus_device_reset(bdr_scmd);
1441                 if (rtn == SUCCESS || rtn == FAST_IO_FAIL) {
1442                         if (!scsi_device_online(sdev) ||
1443                             rtn == FAST_IO_FAIL ||
1444                             !scsi_eh_tur(bdr_scmd)) {
1445                                 list_for_each_entry_safe(scmd, next,
1446                                                          work_q, eh_entry) {
1447                                         if (scmd->device == sdev &&
1448                                             scsi_eh_action(scmd, rtn) != FAILED)
1449                                                 scsi_eh_finish_cmd(scmd,
1450                                                                    done_q);
1451                                 }
1452                         }
1453                 } else {
1454                         SCSI_LOG_ERROR_RECOVERY(3,
1455                                 sdev_printk(KERN_INFO, sdev,
1456                                             "%s: BDR failed\n", current->comm));
1457                 }
1458         }
1459
1460         return list_empty(work_q);
1461 }
1462
1463 /**
1464  * scsi_eh_target_reset - send target reset if needed
1465  * @shost:      scsi host being recovered.
1466  * @work_q:     &list_head for pending commands.
1467  * @done_q:     &list_head for processed commands.
1468  *
1469  * Notes:
1470  *    Try a target reset.
1471  */
1472 static int scsi_eh_target_reset(struct Scsi_Host *shost,
1473                                 struct list_head *work_q,
1474                                 struct list_head *done_q)
1475 {
1476         LIST_HEAD(tmp_list);
1477         LIST_HEAD(check_list);
1478
1479         list_splice_init(work_q, &tmp_list);
1480
1481         while (!list_empty(&tmp_list)) {
1482                 struct scsi_cmnd *next, *scmd;
1483                 int rtn;
1484                 unsigned int id;
1485
1486                 if (scsi_host_eh_past_deadline(shost)) {
1487                         /* push back on work queue for further processing */
1488                         list_splice_init(&check_list, work_q);
1489                         list_splice_init(&tmp_list, work_q);
1490                         SCSI_LOG_ERROR_RECOVERY(3,
1491                                 shost_printk(KERN_INFO, shost,
1492                                             "%s: Skip target reset, past eh deadline\n",
1493                                              current->comm));
1494                         return list_empty(work_q);
1495                 }
1496
1497                 scmd = list_entry(tmp_list.next, struct scsi_cmnd, eh_entry);
1498                 id = scmd_id(scmd);
1499
1500                 SCSI_LOG_ERROR_RECOVERY(3,
1501                         shost_printk(KERN_INFO, shost,
1502                                      "%s: Sending target reset to target %d\n",
1503                                      current->comm, id));
1504                 rtn = scsi_try_target_reset(scmd);
1505                 if (rtn != SUCCESS && rtn != FAST_IO_FAIL)
1506                         SCSI_LOG_ERROR_RECOVERY(3,
1507                                 shost_printk(KERN_INFO, shost,
1508                                              "%s: Target reset failed"
1509                                              " target: %d\n",
1510                                              current->comm, id));
1511                 list_for_each_entry_safe(scmd, next, &tmp_list, eh_entry) {
1512                         if (scmd_id(scmd) != id)
1513                                 continue;
1514
1515                         if (rtn == SUCCESS)
1516                                 list_move_tail(&scmd->eh_entry, &check_list);
1517                         else if (rtn == FAST_IO_FAIL)
1518                                 scsi_eh_finish_cmd(scmd, done_q);
1519                         else
1520                                 /* push back on work queue for further processing */
1521                                 list_move(&scmd->eh_entry, work_q);
1522                 }
1523         }
1524
1525         return scsi_eh_test_devices(&check_list, work_q, done_q, 0);
1526 }
1527
1528 /**
1529  * scsi_eh_bus_reset - send a bus reset
1530  * @shost:      &scsi host being recovered.
1531  * @work_q:     &list_head for pending commands.
1532  * @done_q:     &list_head for processed commands.
1533  */
1534 static int scsi_eh_bus_reset(struct Scsi_Host *shost,
1535                              struct list_head *work_q,
1536                              struct list_head *done_q)
1537 {
1538         struct scsi_cmnd *scmd, *chan_scmd, *next;
1539         LIST_HEAD(check_list);
1540         unsigned int channel;
1541         int rtn;
1542
1543         /*
1544          * we really want to loop over the various channels, and do this on
1545          * a channel by channel basis.  we should also check to see if any
1546          * of the failed commands are on soft_reset devices, and if so, skip
1547          * the reset.
1548          */
1549
1550         for (channel = 0; channel <= shost->max_channel; channel++) {
1551                 if (scsi_host_eh_past_deadline(shost)) {
1552                         list_splice_init(&check_list, work_q);
1553                         SCSI_LOG_ERROR_RECOVERY(3,
1554                                 shost_printk(KERN_INFO, shost,
1555                                             "%s: skip BRST, past eh deadline\n",
1556                                              current->comm));
1557                         return list_empty(work_q);
1558                 }
1559
1560                 chan_scmd = NULL;
1561                 list_for_each_entry(scmd, work_q, eh_entry) {
1562                         if (channel == scmd_channel(scmd)) {
1563                                 chan_scmd = scmd;
1564                                 break;
1565                                 /*
1566                                  * FIXME add back in some support for
1567                                  * soft_reset devices.
1568                                  */
1569                         }
1570                 }
1571
1572                 if (!chan_scmd)
1573                         continue;
1574                 SCSI_LOG_ERROR_RECOVERY(3,
1575                         shost_printk(KERN_INFO, shost,
1576                                      "%s: Sending BRST chan: %d\n",
1577                                      current->comm, channel));
1578                 rtn = scsi_try_bus_reset(chan_scmd);
1579                 if (rtn == SUCCESS || rtn == FAST_IO_FAIL) {
1580                         list_for_each_entry_safe(scmd, next, work_q, eh_entry) {
1581                                 if (channel == scmd_channel(scmd)) {
1582                                         if (rtn == FAST_IO_FAIL)
1583                                                 scsi_eh_finish_cmd(scmd,
1584                                                                    done_q);
1585                                         else
1586                                                 list_move_tail(&scmd->eh_entry,
1587                                                                &check_list);
1588                                 }
1589                         }
1590                 } else {
1591                         SCSI_LOG_ERROR_RECOVERY(3,
1592                                 shost_printk(KERN_INFO, shost,
1593                                              "%s: BRST failed chan: %d\n",
1594                                              current->comm, channel));
1595                 }
1596         }
1597         return scsi_eh_test_devices(&check_list, work_q, done_q, 0);
1598 }
1599
1600 /**
1601  * scsi_eh_host_reset - send a host reset
1602  * @shost:      host to be reset.
1603  * @work_q:     &list_head for pending commands.
1604  * @done_q:     &list_head for processed commands.
1605  */
1606 static int scsi_eh_host_reset(struct Scsi_Host *shost,
1607                               struct list_head *work_q,
1608                               struct list_head *done_q)
1609 {
1610         struct scsi_cmnd *scmd, *next;
1611         LIST_HEAD(check_list);
1612         int rtn;
1613
1614         if (!list_empty(work_q)) {
1615                 scmd = list_entry(work_q->next,
1616                                   struct scsi_cmnd, eh_entry);
1617
1618                 SCSI_LOG_ERROR_RECOVERY(3,
1619                         shost_printk(KERN_INFO, shost,
1620                                      "%s: Sending HRST\n",
1621                                      current->comm));
1622
1623                 rtn = scsi_try_host_reset(scmd);
1624                 if (rtn == SUCCESS) {
1625                         list_splice_init(work_q, &check_list);
1626                 } else if (rtn == FAST_IO_FAIL) {
1627                         list_for_each_entry_safe(scmd, next, work_q, eh_entry) {
1628                                         scsi_eh_finish_cmd(scmd, done_q);
1629                         }
1630                 } else {
1631                         SCSI_LOG_ERROR_RECOVERY(3,
1632                                 shost_printk(KERN_INFO, shost,
1633                                              "%s: HRST failed\n",
1634                                              current->comm));
1635                 }
1636         }
1637         return scsi_eh_test_devices(&check_list, work_q, done_q, 1);
1638 }
1639
1640 /**
1641  * scsi_eh_offline_sdevs - offline scsi devices that fail to recover
1642  * @work_q:     &list_head for pending commands.
1643  * @done_q:     &list_head for processed commands.
1644  */
1645 static void scsi_eh_offline_sdevs(struct list_head *work_q,
1646                                   struct list_head *done_q)
1647 {
1648         struct scsi_cmnd *scmd, *next;
1649         struct scsi_device *sdev;
1650
1651         list_for_each_entry_safe(scmd, next, work_q, eh_entry) {
1652                 sdev_printk(KERN_INFO, scmd->device, "Device offlined - "
1653                             "not ready after error recovery\n");
1654                 sdev = scmd->device;
1655
1656                 mutex_lock(&sdev->state_mutex);
1657                 scsi_device_set_state(sdev, SDEV_OFFLINE);
1658                 mutex_unlock(&sdev->state_mutex);
1659
1660                 scsi_eh_finish_cmd(scmd, done_q);
1661         }
1662         return;
1663 }
1664
1665 /**
1666  * scsi_noretry_cmd - determine if command should be failed fast
1667  * @scmd:       SCSI cmd to examine.
1668  */
1669 int scsi_noretry_cmd(struct scsi_cmnd *scmd)
1670 {
1671         switch (host_byte(scmd->result)) {
1672         case DID_OK:
1673                 break;
1674         case DID_TIME_OUT:
1675                 goto check_type;
1676         case DID_BUS_BUSY:
1677                 return (scmd->request->cmd_flags & REQ_FAILFAST_TRANSPORT);
1678         case DID_PARITY:
1679                 return (scmd->request->cmd_flags & REQ_FAILFAST_DEV);
1680         case DID_ERROR:
1681                 if (msg_byte(scmd->result) == COMMAND_COMPLETE &&
1682                     status_byte(scmd->result) == RESERVATION_CONFLICT)
1683                         return 0;
1684                 /* fall through */
1685         case DID_SOFT_ERROR:
1686                 return (scmd->request->cmd_flags & REQ_FAILFAST_DRIVER);
1687         }
1688
1689         if (status_byte(scmd->result) != CHECK_CONDITION)
1690                 return 0;
1691
1692 check_type:
1693         /*
1694          * assume caller has checked sense and determined
1695          * the check condition was retryable.
1696          */
1697         if (scmd->request->cmd_flags & REQ_FAILFAST_DEV ||
1698             blk_rq_is_passthrough(scmd->request))
1699                 return 1;
1700         else
1701                 return 0;
1702 }
1703
1704 /**
1705  * scsi_decide_disposition - Disposition a cmd on return from LLD.
1706  * @scmd:       SCSI cmd to examine.
1707  *
1708  * Notes:
1709  *    This is *only* called when we are examining the status after sending
1710  *    out the actual data command.  any commands that are queued for error
1711  *    recovery (e.g. test_unit_ready) do *not* come through here.
1712  *
1713  *    When this routine returns failed, it means the error handler thread
1714  *    is woken.  In cases where the error code indicates an error that
1715  *    doesn't require the error handler read (i.e. we don't need to
1716  *    abort/reset), this function should return SUCCESS.
1717  */
1718 int scsi_decide_disposition(struct scsi_cmnd *scmd)
1719 {
1720         int rtn;
1721
1722         /*
1723          * if the device is offline, then we clearly just pass the result back
1724          * up to the top level.
1725          */
1726         if (!scsi_device_online(scmd->device)) {
1727                 SCSI_LOG_ERROR_RECOVERY(5, scmd_printk(KERN_INFO, scmd,
1728                         "%s: device offline - report as SUCCESS\n", __func__));
1729                 return SUCCESS;
1730         }
1731
1732         /*
1733          * first check the host byte, to see if there is anything in there
1734          * that would indicate what we need to do.
1735          */
1736         switch (host_byte(scmd->result)) {
1737         case DID_PASSTHROUGH:
1738                 /*
1739                  * no matter what, pass this through to the upper layer.
1740                  * nuke this special code so that it looks like we are saying
1741                  * did_ok.
1742                  */
1743                 scmd->result &= 0xff00ffff;
1744                 return SUCCESS;
1745         case DID_OK:
1746                 /*
1747                  * looks good.  drop through, and check the next byte.
1748                  */
1749                 break;
1750         case DID_ABORT:
1751                 if (scmd->eh_eflags & SCSI_EH_ABORT_SCHEDULED) {
1752                         set_host_byte(scmd, DID_TIME_OUT);
1753                         return SUCCESS;
1754                 }
1755                 /* FALLTHROUGH */
1756         case DID_NO_CONNECT:
1757         case DID_BAD_TARGET:
1758                 /*
1759                  * note - this means that we just report the status back
1760                  * to the top level driver, not that we actually think
1761                  * that it indicates SUCCESS.
1762                  */
1763                 return SUCCESS;
1764                 /*
1765                  * when the low level driver returns did_soft_error,
1766                  * it is responsible for keeping an internal retry counter
1767                  * in order to avoid endless loops (db)
1768                  *
1769                  * actually this is a bug in this function here.  we should
1770                  * be mindful of the maximum number of retries specified
1771                  * and not get stuck in a loop.
1772                  */
1773         case DID_SOFT_ERROR:
1774                 goto maybe_retry;
1775         case DID_IMM_RETRY:
1776                 return NEEDS_RETRY;
1777
1778         case DID_REQUEUE:
1779                 return ADD_TO_MLQUEUE;
1780         case DID_TRANSPORT_DISRUPTED:
1781                 /*
1782                  * LLD/transport was disrupted during processing of the IO.
1783                  * The transport class is now blocked/blocking,
1784                  * and the transport will decide what to do with the IO
1785                  * based on its timers and recovery capablilities if
1786                  * there are enough retries.
1787                  */
1788                 goto maybe_retry;
1789         case DID_TRANSPORT_FAILFAST:
1790                 /*
1791                  * The transport decided to failfast the IO (most likely
1792                  * the fast io fail tmo fired), so send IO directly upwards.
1793                  */
1794                 return SUCCESS;
1795         case DID_ERROR:
1796                 if (msg_byte(scmd->result) == COMMAND_COMPLETE &&
1797                     status_byte(scmd->result) == RESERVATION_CONFLICT)
1798                         /*
1799                          * execute reservation conflict processing code
1800                          * lower down
1801                          */
1802                         break;
1803                 /* fallthrough */
1804         case DID_BUS_BUSY:
1805         case DID_PARITY:
1806                 goto maybe_retry;
1807         case DID_TIME_OUT:
1808                 /*
1809                  * when we scan the bus, we get timeout messages for
1810                  * these commands if there is no device available.
1811                  * other hosts report did_no_connect for the same thing.
1812                  */
1813                 if ((scmd->cmnd[0] == TEST_UNIT_READY ||
1814                      scmd->cmnd[0] == INQUIRY)) {
1815                         return SUCCESS;
1816                 } else {
1817                         return FAILED;
1818                 }
1819         case DID_RESET:
1820                 return SUCCESS;
1821         default:
1822                 return FAILED;
1823         }
1824
1825         /*
1826          * next, check the message byte.
1827          */
1828         if (msg_byte(scmd->result) != COMMAND_COMPLETE)
1829                 return FAILED;
1830
1831         /*
1832          * check the status byte to see if this indicates anything special.
1833          */
1834         switch (status_byte(scmd->result)) {
1835         case QUEUE_FULL:
1836                 scsi_handle_queue_full(scmd->device);
1837                 /*
1838                  * the case of trying to send too many commands to a
1839                  * tagged queueing device.
1840                  */
1841                 /* FALLTHROUGH */
1842         case BUSY:
1843                 /*
1844                  * device can't talk to us at the moment.  Should only
1845                  * occur (SAM-3) when the task queue is empty, so will cause
1846                  * the empty queue handling to trigger a stall in the
1847                  * device.
1848                  */
1849                 return ADD_TO_MLQUEUE;
1850         case GOOD:
1851                 if (scmd->cmnd[0] == REPORT_LUNS)
1852                         scmd->device->sdev_target->expecting_lun_change = 0;
1853                 scsi_handle_queue_ramp_up(scmd->device);
1854                 /* FALLTHROUGH */
1855         case COMMAND_TERMINATED:
1856                 return SUCCESS;
1857         case TASK_ABORTED:
1858                 goto maybe_retry;
1859         case CHECK_CONDITION:
1860                 rtn = scsi_check_sense(scmd);
1861                 if (rtn == NEEDS_RETRY)
1862                         goto maybe_retry;
1863                 /* if rtn == FAILED, we have no sense information;
1864                  * returning FAILED will wake the error handler thread
1865                  * to collect the sense and redo the decide
1866                  * disposition */
1867                 return rtn;
1868         case CONDITION_GOOD:
1869         case INTERMEDIATE_GOOD:
1870         case INTERMEDIATE_C_GOOD:
1871         case ACA_ACTIVE:
1872                 /*
1873                  * who knows?  FIXME(eric)
1874                  */
1875                 return SUCCESS;
1876
1877         case RESERVATION_CONFLICT:
1878                 sdev_printk(KERN_INFO, scmd->device,
1879                             "reservation conflict\n");
1880                 set_host_byte(scmd, DID_NEXUS_FAILURE);
1881                 return SUCCESS; /* causes immediate i/o error */
1882         default:
1883                 return FAILED;
1884         }
1885         return FAILED;
1886
1887       maybe_retry:
1888
1889         /* we requeue for retry because the error was retryable, and
1890          * the request was not marked fast fail.  Note that above,
1891          * even if the request is marked fast fail, we still requeue
1892          * for queue congestion conditions (QUEUE_FULL or BUSY) */
1893         if ((++scmd->retries) <= scmd->allowed
1894             && !scsi_noretry_cmd(scmd)) {
1895                 return NEEDS_RETRY;
1896         } else {
1897                 /*
1898                  * no more retries - report this one back to upper level.
1899                  */
1900                 return SUCCESS;
1901         }
1902 }
1903
1904 static void eh_lock_door_done(struct request *req, blk_status_t status)
1905 {
1906         __blk_put_request(req->q, req);
1907 }
1908
1909 /**
1910  * scsi_eh_lock_door - Prevent medium removal for the specified device
1911  * @sdev:       SCSI device to prevent medium removal
1912  *
1913  * Locking:
1914  *      We must be called from process context.
1915  *
1916  * Notes:
1917  *      We queue up an asynchronous "ALLOW MEDIUM REMOVAL" request on the
1918  *      head of the devices request queue, and continue.
1919  */
1920 static void scsi_eh_lock_door(struct scsi_device *sdev)
1921 {
1922         struct request *req;
1923         struct scsi_request *rq;
1924
1925         /*
1926          * blk_get_request with GFP_KERNEL (__GFP_RECLAIM) sleeps until a
1927          * request becomes available
1928          */
1929         req = blk_get_request(sdev->request_queue, REQ_OP_SCSI_IN, GFP_KERNEL);
1930         if (IS_ERR(req))
1931                 return;
1932         rq = scsi_req(req);
1933
1934         rq->cmd[0] = ALLOW_MEDIUM_REMOVAL;
1935         rq->cmd[1] = 0;
1936         rq->cmd[2] = 0;
1937         rq->cmd[3] = 0;
1938         rq->cmd[4] = SCSI_REMOVAL_PREVENT;
1939         rq->cmd[5] = 0;
1940         rq->cmd_len = COMMAND_SIZE(rq->cmd[0]);
1941
1942         req->rq_flags |= RQF_QUIET;
1943         req->timeout = 10 * HZ;
1944         rq->retries = 5;
1945
1946         blk_execute_rq_nowait(req->q, NULL, req, 1, eh_lock_door_done);
1947 }
1948
1949 /**
1950  * scsi_restart_operations - restart io operations to the specified host.
1951  * @shost:      Host we are restarting.
1952  *
1953  * Notes:
1954  *    When we entered the error handler, we blocked all further i/o to
1955  *    this device.  we need to 'reverse' this process.
1956  */
1957 static void scsi_restart_operations(struct Scsi_Host *shost)
1958 {
1959         struct scsi_device *sdev;
1960         unsigned long flags;
1961
1962         /*
1963          * If the door was locked, we need to insert a door lock request
1964          * onto the head of the SCSI request queue for the device.  There
1965          * is no point trying to lock the door of an off-line device.
1966          */
1967         shost_for_each_device(sdev, shost) {
1968                 if (scsi_device_online(sdev) && sdev->was_reset && sdev->locked) {
1969                         scsi_eh_lock_door(sdev);
1970                         sdev->was_reset = 0;
1971                 }
1972         }
1973
1974         /*
1975          * next free up anything directly waiting upon the host.  this
1976          * will be requests for character device operations, and also for
1977          * ioctls to queued block devices.
1978          */
1979         SCSI_LOG_ERROR_RECOVERY(3,
1980                 shost_printk(KERN_INFO, shost, "waking up host to restart\n"));
1981
1982         spin_lock_irqsave(shost->host_lock, flags);
1983         if (scsi_host_set_state(shost, SHOST_RUNNING))
1984                 if (scsi_host_set_state(shost, SHOST_CANCEL))
1985                         BUG_ON(scsi_host_set_state(shost, SHOST_DEL));
1986         spin_unlock_irqrestore(shost->host_lock, flags);
1987
1988         wake_up(&shost->host_wait);
1989
1990         /*
1991          * finally we need to re-initiate requests that may be pending.  we will
1992          * have had everything blocked while error handling is taking place, and
1993          * now that error recovery is done, we will need to ensure that these
1994          * requests are started.
1995          */
1996         scsi_run_host_queues(shost);
1997
1998         /*
1999          * if eh is active and host_eh_scheduled is pending we need to re-run
2000          * recovery.  we do this check after scsi_run_host_queues() to allow
2001          * everything pent up since the last eh run a chance to make forward
2002          * progress before we sync again.  Either we'll immediately re-run
2003          * recovery or scsi_device_unbusy() will wake us again when these
2004          * pending commands complete.
2005          */
2006         spin_lock_irqsave(shost->host_lock, flags);
2007         if (shost->host_eh_scheduled)
2008                 if (scsi_host_set_state(shost, SHOST_RECOVERY))
2009                         WARN_ON(scsi_host_set_state(shost, SHOST_CANCEL_RECOVERY));
2010         spin_unlock_irqrestore(shost->host_lock, flags);
2011 }
2012
2013 /**
2014  * scsi_eh_ready_devs - check device ready state and recover if not.
2015  * @shost:      host to be recovered.
2016  * @work_q:     &list_head for pending commands.
2017  * @done_q:     &list_head for processed commands.
2018  */
2019 void scsi_eh_ready_devs(struct Scsi_Host *shost,
2020                         struct list_head *work_q,
2021                         struct list_head *done_q)
2022 {
2023         if (!scsi_eh_stu(shost, work_q, done_q))
2024                 if (!scsi_eh_bus_device_reset(shost, work_q, done_q))
2025                         if (!scsi_eh_target_reset(shost, work_q, done_q))
2026                                 if (!scsi_eh_bus_reset(shost, work_q, done_q))
2027                                         if (!scsi_eh_host_reset(shost, work_q, done_q))
2028                                                 scsi_eh_offline_sdevs(work_q,
2029                                                                       done_q);
2030 }
2031 EXPORT_SYMBOL_GPL(scsi_eh_ready_devs);
2032
2033 /**
2034  * scsi_eh_flush_done_q - finish processed commands or retry them.
2035  * @done_q:     list_head of processed commands.
2036  */
2037 void scsi_eh_flush_done_q(struct list_head *done_q)
2038 {
2039         struct scsi_cmnd *scmd, *next;
2040
2041         list_for_each_entry_safe(scmd, next, done_q, eh_entry) {
2042                 list_del_init(&scmd->eh_entry);
2043                 if (scsi_device_online(scmd->device) &&
2044                     !scsi_noretry_cmd(scmd) &&
2045                     (++scmd->retries <= scmd->allowed)) {
2046                         SCSI_LOG_ERROR_RECOVERY(3,
2047                                 scmd_printk(KERN_INFO, scmd,
2048                                              "%s: flush retry cmd\n",
2049                                              current->comm));
2050                                 scsi_queue_insert(scmd, SCSI_MLQUEUE_EH_RETRY);
2051                 } else {
2052                         /*
2053                          * If just we got sense for the device (called
2054                          * scsi_eh_get_sense), scmd->result is already
2055                          * set, do not set DRIVER_TIMEOUT.
2056                          */
2057                         if (!scmd->result)
2058                                 scmd->result |= (DRIVER_TIMEOUT << 24);
2059                         SCSI_LOG_ERROR_RECOVERY(3,
2060                                 scmd_printk(KERN_INFO, scmd,
2061                                              "%s: flush finish cmd\n",
2062                                              current->comm));
2063                         scsi_finish_command(scmd);
2064                 }
2065         }
2066 }
2067 EXPORT_SYMBOL(scsi_eh_flush_done_q);
2068
2069 /**
2070  * scsi_unjam_host - Attempt to fix a host which has a cmd that failed.
2071  * @shost:      Host to unjam.
2072  *
2073  * Notes:
2074  *    When we come in here, we *know* that all commands on the bus have
2075  *    either completed, failed or timed out.  we also know that no further
2076  *    commands are being sent to the host, so things are relatively quiet
2077  *    and we have freedom to fiddle with things as we wish.
2078  *
2079  *    This is only the *default* implementation.  it is possible for
2080  *    individual drivers to supply their own version of this function, and
2081  *    if the maintainer wishes to do this, it is strongly suggested that
2082  *    this function be taken as a template and modified.  this function
2083  *    was designed to correctly handle problems for about 95% of the
2084  *    different cases out there, and it should always provide at least a
2085  *    reasonable amount of error recovery.
2086  *
2087  *    Any command marked 'failed' or 'timeout' must eventually have
2088  *    scsi_finish_cmd() called for it.  we do all of the retry stuff
2089  *    here, so when we restart the host after we return it should have an
2090  *    empty queue.
2091  */
2092 static void scsi_unjam_host(struct Scsi_Host *shost)
2093 {
2094         unsigned long flags;
2095         LIST_HEAD(eh_work_q);
2096         LIST_HEAD(eh_done_q);
2097
2098         spin_lock_irqsave(shost->host_lock, flags);
2099         list_splice_init(&shost->eh_cmd_q, &eh_work_q);
2100         spin_unlock_irqrestore(shost->host_lock, flags);
2101
2102         SCSI_LOG_ERROR_RECOVERY(1, scsi_eh_prt_fail_stats(shost, &eh_work_q));
2103
2104         if (!scsi_eh_get_sense(&eh_work_q, &eh_done_q))
2105                 scsi_eh_ready_devs(shost, &eh_work_q, &eh_done_q);
2106
2107         spin_lock_irqsave(shost->host_lock, flags);
2108         if (shost->eh_deadline != -1)
2109                 shost->last_reset = 0;
2110         spin_unlock_irqrestore(shost->host_lock, flags);
2111         scsi_eh_flush_done_q(&eh_done_q);
2112 }
2113
2114 /**
2115  * scsi_error_handler - SCSI error handler thread
2116  * @data:       Host for which we are running.
2117  *
2118  * Notes:
2119  *    This is the main error handling loop.  This is run as a kernel thread
2120  *    for every SCSI host and handles all error handling activity.
2121  */
2122 int scsi_error_handler(void *data)
2123 {
2124         struct Scsi_Host *shost = data;
2125
2126         /*
2127          * We use TASK_INTERRUPTIBLE so that the thread is not
2128          * counted against the load average as a running process.
2129          * We never actually get interrupted because kthread_run
2130          * disables signal delivery for the created thread.
2131          */
2132         while (true) {
2133                 /*
2134                  * The sequence in kthread_stop() sets the stop flag first
2135                  * then wakes the process.  To avoid missed wakeups, the task
2136                  * should always be in a non running state before the stop
2137                  * flag is checked
2138                  */
2139                 set_current_state(TASK_INTERRUPTIBLE);
2140                 if (kthread_should_stop())
2141                         break;
2142
2143                 if ((shost->host_failed == 0 && shost->host_eh_scheduled == 0) ||
2144                     shost->host_failed != atomic_read(&shost->host_busy)) {
2145                         SCSI_LOG_ERROR_RECOVERY(1,
2146                                 shost_printk(KERN_INFO, shost,
2147                                              "scsi_eh_%d: sleeping\n",
2148                                              shost->host_no));
2149                         schedule();
2150                         continue;
2151                 }
2152
2153                 __set_current_state(TASK_RUNNING);
2154                 SCSI_LOG_ERROR_RECOVERY(1,
2155                         shost_printk(KERN_INFO, shost,
2156                                      "scsi_eh_%d: waking up %d/%d/%d\n",
2157                                      shost->host_no, shost->host_eh_scheduled,
2158                                      shost->host_failed,
2159                                      atomic_read(&shost->host_busy)));
2160
2161                 /*
2162                  * We have a host that is failing for some reason.  Figure out
2163                  * what we need to do to get it up and online again (if we can).
2164                  * If we fail, we end up taking the thing offline.
2165                  */
2166                 if (!shost->eh_noresume && scsi_autopm_get_host(shost) != 0) {
2167                         SCSI_LOG_ERROR_RECOVERY(1,
2168                                 shost_printk(KERN_ERR, shost,
2169                                              "scsi_eh_%d: unable to autoresume\n",
2170                                              shost->host_no));
2171                         continue;
2172                 }
2173
2174                 if (shost->transportt->eh_strategy_handler)
2175                         shost->transportt->eh_strategy_handler(shost);
2176                 else
2177                         scsi_unjam_host(shost);
2178
2179                 /* All scmds have been handled */
2180                 shost->host_failed = 0;
2181
2182                 /*
2183                  * Note - if the above fails completely, the action is to take
2184                  * individual devices offline and flush the queue of any
2185                  * outstanding requests that may have been pending.  When we
2186                  * restart, we restart any I/O to any other devices on the bus
2187                  * which are still online.
2188                  */
2189                 scsi_restart_operations(shost);
2190                 if (!shost->eh_noresume)
2191                         scsi_autopm_put_host(shost);
2192         }
2193         __set_current_state(TASK_RUNNING);
2194
2195         SCSI_LOG_ERROR_RECOVERY(1,
2196                 shost_printk(KERN_INFO, shost,
2197                              "Error handler scsi_eh_%d exiting\n",
2198                              shost->host_no));
2199         shost->ehandler = NULL;
2200         return 0;
2201 }
2202
2203 /*
2204  * Function:    scsi_report_bus_reset()
2205  *
2206  * Purpose:     Utility function used by low-level drivers to report that
2207  *              they have observed a bus reset on the bus being handled.
2208  *
2209  * Arguments:   shost       - Host in question
2210  *              channel     - channel on which reset was observed.
2211  *
2212  * Returns:     Nothing
2213  *
2214  * Lock status: Host lock must be held.
2215  *
2216  * Notes:       This only needs to be called if the reset is one which
2217  *              originates from an unknown location.  Resets originated
2218  *              by the mid-level itself don't need to call this, but there
2219  *              should be no harm.
2220  *
2221  *              The main purpose of this is to make sure that a CHECK_CONDITION
2222  *              is properly treated.
2223  */
2224 void scsi_report_bus_reset(struct Scsi_Host *shost, int channel)
2225 {
2226         struct scsi_device *sdev;
2227
2228         __shost_for_each_device(sdev, shost) {
2229                 if (channel == sdev_channel(sdev))
2230                         __scsi_report_device_reset(sdev, NULL);
2231         }
2232 }
2233 EXPORT_SYMBOL(scsi_report_bus_reset);
2234
2235 /*
2236  * Function:    scsi_report_device_reset()
2237  *
2238  * Purpose:     Utility function used by low-level drivers to report that
2239  *              they have observed a device reset on the device being handled.
2240  *
2241  * Arguments:   shost       - Host in question
2242  *              channel     - channel on which reset was observed
2243  *              target      - target on which reset was observed
2244  *
2245  * Returns:     Nothing
2246  *
2247  * Lock status: Host lock must be held
2248  *
2249  * Notes:       This only needs to be called if the reset is one which
2250  *              originates from an unknown location.  Resets originated
2251  *              by the mid-level itself don't need to call this, but there
2252  *              should be no harm.
2253  *
2254  *              The main purpose of this is to make sure that a CHECK_CONDITION
2255  *              is properly treated.
2256  */
2257 void scsi_report_device_reset(struct Scsi_Host *shost, int channel, int target)
2258 {
2259         struct scsi_device *sdev;
2260
2261         __shost_for_each_device(sdev, shost) {
2262                 if (channel == sdev_channel(sdev) &&
2263                     target == sdev_id(sdev))
2264                         __scsi_report_device_reset(sdev, NULL);
2265         }
2266 }
2267 EXPORT_SYMBOL(scsi_report_device_reset);
2268
2269 static void
2270 scsi_reset_provider_done_command(struct scsi_cmnd *scmd)
2271 {
2272 }
2273
2274 /**
2275  * scsi_ioctl_reset: explicitly reset a host/bus/target/device
2276  * @dev:        scsi_device to operate on
2277  * @arg:        reset type (see sg.h)
2278  */
2279 int
2280 scsi_ioctl_reset(struct scsi_device *dev, int __user *arg)
2281 {
2282         struct scsi_cmnd *scmd;
2283         struct Scsi_Host *shost = dev->host;
2284         struct request *rq;
2285         unsigned long flags;
2286         int error = 0, rtn, val;
2287
2288         if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
2289                 return -EACCES;
2290
2291         error = get_user(val, arg);
2292         if (error)
2293                 return error;
2294
2295         if (scsi_autopm_get_host(shost) < 0)
2296                 return -EIO;
2297
2298         error = -EIO;
2299         rq = kzalloc(sizeof(struct request) + sizeof(struct scsi_cmnd) +
2300                         shost->hostt->cmd_size, GFP_KERNEL);
2301         if (!rq)
2302                 goto out_put_autopm_host;
2303         blk_rq_init(NULL, rq);
2304
2305         scmd = (struct scsi_cmnd *)(rq + 1);
2306         scsi_init_command(dev, scmd);
2307         scmd->request = rq;
2308         scmd->cmnd = scsi_req(rq)->cmd;
2309
2310         scmd->scsi_done         = scsi_reset_provider_done_command;
2311         memset(&scmd->sdb, 0, sizeof(scmd->sdb));
2312
2313         scmd->cmd_len                   = 0;
2314
2315         scmd->sc_data_direction         = DMA_BIDIRECTIONAL;
2316
2317         spin_lock_irqsave(shost->host_lock, flags);
2318         shost->tmf_in_progress = 1;
2319         spin_unlock_irqrestore(shost->host_lock, flags);
2320
2321         switch (val & ~SG_SCSI_RESET_NO_ESCALATE) {
2322         case SG_SCSI_RESET_NOTHING:
2323                 rtn = SUCCESS;
2324                 break;
2325         case SG_SCSI_RESET_DEVICE:
2326                 rtn = scsi_try_bus_device_reset(scmd);
2327                 if (rtn == SUCCESS || (val & SG_SCSI_RESET_NO_ESCALATE))
2328                         break;
2329                 /* FALLTHROUGH */
2330         case SG_SCSI_RESET_TARGET:
2331                 rtn = scsi_try_target_reset(scmd);
2332                 if (rtn == SUCCESS || (val & SG_SCSI_RESET_NO_ESCALATE))
2333                         break;
2334                 /* FALLTHROUGH */
2335         case SG_SCSI_RESET_BUS:
2336                 rtn = scsi_try_bus_reset(scmd);
2337                 if (rtn == SUCCESS || (val & SG_SCSI_RESET_NO_ESCALATE))
2338                         break;
2339                 /* FALLTHROUGH */
2340         case SG_SCSI_RESET_HOST:
2341                 rtn = scsi_try_host_reset(scmd);
2342                 if (rtn == SUCCESS)
2343                         break;
2344                 /* FALLTHROUGH */
2345         default:
2346                 rtn = FAILED;
2347                 break;
2348         }
2349
2350         error = (rtn == SUCCESS) ? 0 : -EIO;
2351
2352         spin_lock_irqsave(shost->host_lock, flags);
2353         shost->tmf_in_progress = 0;
2354         spin_unlock_irqrestore(shost->host_lock, flags);
2355
2356         /*
2357          * be sure to wake up anyone who was sleeping or had their queue
2358          * suspended while we performed the TMF.
2359          */
2360         SCSI_LOG_ERROR_RECOVERY(3,
2361                 shost_printk(KERN_INFO, shost,
2362                              "waking up host to restart after TMF\n"));
2363
2364         wake_up(&shost->host_wait);
2365         scsi_run_host_queues(shost);
2366
2367         scsi_put_command(scmd);
2368         kfree(rq);
2369
2370 out_put_autopm_host:
2371         scsi_autopm_put_host(shost);
2372         return error;
2373 }
2374 EXPORT_SYMBOL(scsi_ioctl_reset);
2375
2376 bool scsi_command_normalize_sense(const struct scsi_cmnd *cmd,
2377                                   struct scsi_sense_hdr *sshdr)
2378 {
2379         return scsi_normalize_sense(cmd->sense_buffer,
2380                         SCSI_SENSE_BUFFERSIZE, sshdr);
2381 }
2382 EXPORT_SYMBOL(scsi_command_normalize_sense);
2383
2384 /**
2385  * scsi_get_sense_info_fld - get information field from sense data (either fixed or descriptor format)
2386  * @sense_buffer:       byte array of sense data
2387  * @sb_len:             number of valid bytes in sense_buffer
2388  * @info_out:           pointer to 64 integer where 8 or 4 byte information
2389  *                      field will be placed if found.
2390  *
2391  * Return value:
2392  *      true if information field found, false if not found.
2393  */
2394 bool scsi_get_sense_info_fld(const u8 *sense_buffer, int sb_len,
2395                              u64 *info_out)
2396 {
2397         const u8 * ucp;
2398
2399         if (sb_len < 7)
2400                 return false;
2401         switch (sense_buffer[0] & 0x7f) {
2402         case 0x70:
2403         case 0x71:
2404                 if (sense_buffer[0] & 0x80) {
2405                         *info_out = get_unaligned_be32(&sense_buffer[3]);
2406                         return true;
2407                 }
2408                 return false;
2409         case 0x72:
2410         case 0x73:
2411                 ucp = scsi_sense_desc_find(sense_buffer, sb_len,
2412                                            0 /* info desc */);
2413                 if (ucp && (0xa == ucp[1])) {
2414                         *info_out = get_unaligned_be64(&ucp[4]);
2415                         return true;
2416                 }
2417                 return false;
2418         default:
2419                 return false;
2420         }
2421 }
2422 EXPORT_SYMBOL(scsi_get_sense_info_fld);