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