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