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