xref: /linux/drivers/scsi/scsi_error.c (revision 7eb7f5723df50a7d5564aa609e4c147f669a5cb4)
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 
scsi_eh_wakeup(struct Scsi_Host * shost,unsigned int busy)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  */
scsi_schedule_eh(struct Scsi_Host * shost)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 
scsi_host_eh_past_deadline(struct Scsi_Host * shost)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 
scsi_cmd_retry_allowed(struct scsi_cmnd * cmd)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 
scsi_eh_should_retry_cmd(struct scsi_cmnd * cmd)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
scmd_eh_abort_handler(struct work_struct * work)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
scsi_abort_command(struct scsi_cmnd * scmd)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  */
scsi_eh_reset(struct scsi_cmnd * scmd)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 
scsi_eh_inc_host_failed(struct rcu_head * head)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  */
scsi_eh_scmd_add(struct scsi_cmnd * scmd)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  */
scsi_timeout(struct request * req)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  */
scsi_block_when_processing_errors(struct scsi_device * sdev)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  */
scsi_eh_prt_fail_stats(struct Scsi_Host * shost,struct list_head * work_q)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  */
scsi_report_lun_change(struct scsi_device * sdev)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  */
scsi_report_sense(struct scsi_device * sdev,struct scsi_sense_hdr * sshdr)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 
set_scsi_ml_byte(struct scsi_cmnd * cmd,u8 status)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  */
scsi_check_sense(struct scsi_cmnd * scmd)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 
scsi_handle_queue_ramp_up(struct scsi_device * sdev)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 
scsi_handle_queue_full(struct scsi_device * sdev)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  */
scsi_eh_completed_normally(struct scsi_cmnd * scmd)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  */
scsi_eh_done(struct scsi_cmnd * scmd)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  */
scsi_try_host_reset(struct scsi_cmnd * scmd)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  */
scsi_try_bus_reset(struct scsi_cmnd * scmd)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 
__scsi_report_device_reset(struct scsi_device * sdev,void * data)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  */
scsi_try_target_reset(struct scsi_cmnd * scmd)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  */
scsi_try_bus_device_reset(struct scsi_cmnd * scmd)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
scsi_try_to_abort_cmd(const struct scsi_host_template * hostt,struct scsi_cmnd * scmd)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 
scsi_abort_eh_cmnd(struct scsi_cmnd * scmd)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  */
scsi_eh_prep_cmnd(struct scsi_cmnd * scmd,struct scsi_eh_save * ses,unsigned char * cmnd,int cmnd_size,unsigned sense_bytes)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 
1067 	/*
1068 	 * We need saved copies of a number of fields - this is because
1069 	 * error handling may need to overwrite these with different values
1070 	 * to run different commands, and once error handling is complete,
1071 	 * we will need to restore these values prior to running the actual
1072 	 * command.
1073 	 */
1074 	ses->cmd_len = scmd->cmd_len;
1075 	ses->data_direction = scmd->sc_data_direction;
1076 	ses->sdb = scmd->sdb;
1077 	ses->result = scmd->result;
1078 	ses->resid_len = scmd->resid_len;
1079 	ses->underflow = scmd->underflow;
1080 	ses->prot_op = scmd->prot_op;
1081 	ses->eh_eflags = scmd->eh_eflags;
1082 
1083 	scmd->prot_op = SCSI_PROT_NORMAL;
1084 	scmd->eh_eflags = 0;
1085 	memcpy(ses->cmnd, scmd->cmnd, sizeof(ses->cmnd));
1086 	memset(scmd->cmnd, 0, sizeof(scmd->cmnd));
1087 	memset(&scmd->sdb, 0, sizeof(scmd->sdb));
1088 	scmd->result = 0;
1089 	scmd->resid_len = 0;
1090 
1091 	if (sense_bytes) {
1092 		scmd->sdb.length = min_t(unsigned, SCSI_SENSE_BUFFERSIZE,
1093 					 sense_bytes);
1094 		sg_init_one(&ses->sense_sgl, scmd->sense_buffer,
1095 			    scmd->sdb.length);
1096 		scmd->sdb.table.sgl = &ses->sense_sgl;
1097 		scmd->sc_data_direction = DMA_FROM_DEVICE;
1098 		scmd->sdb.table.nents = scmd->sdb.table.orig_nents = 1;
1099 		scmd->cmnd[0] = REQUEST_SENSE;
1100 		scmd->cmnd[4] = scmd->sdb.length;
1101 		scmd->cmd_len = COMMAND_SIZE(scmd->cmnd[0]);
1102 	} else {
1103 		scmd->sc_data_direction = DMA_NONE;
1104 		if (cmnd) {
1105 			BUG_ON(cmnd_size > sizeof(scmd->cmnd));
1106 			memcpy(scmd->cmnd, cmnd, cmnd_size);
1107 			scmd->cmd_len = COMMAND_SIZE(scmd->cmnd[0]);
1108 		}
1109 	}
1110 
1111 	scmd->underflow = 0;
1112 
1113 	if (sdev->scsi_level <= SCSI_2 && sdev->scsi_level != SCSI_UNKNOWN)
1114 		scmd->cmnd[1] = (scmd->cmnd[1] & 0x1f) |
1115 			(sdev->lun << 5 & 0xe0);
1116 
1117 	/*
1118 	 * Zero the sense buffer.  The scsi spec mandates that any
1119 	 * untransferred sense data should be interpreted as being zero.
1120 	 */
1121 	memset(scmd->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
1122 }
1123 EXPORT_SYMBOL(scsi_eh_prep_cmnd);
1124 
1125 /**
1126  * scsi_eh_restore_cmnd  - Restore a scsi command info as part of error recovery
1127  * @scmd:       SCSI command structure to restore
1128  * @ses:        saved information from a coresponding call to scsi_eh_prep_cmnd
1129  *
1130  * Undo any damage done by above scsi_eh_prep_cmnd().
1131  */
scsi_eh_restore_cmnd(struct scsi_cmnd * scmd,struct scsi_eh_save * ses)1132 void scsi_eh_restore_cmnd(struct scsi_cmnd* scmd, struct scsi_eh_save *ses)
1133 {
1134 	/*
1135 	 * Restore original data
1136 	 */
1137 	scmd->cmd_len = ses->cmd_len;
1138 	memcpy(scmd->cmnd, ses->cmnd, sizeof(ses->cmnd));
1139 	scmd->sc_data_direction = ses->data_direction;
1140 	scmd->sdb = ses->sdb;
1141 	scmd->result = ses->result;
1142 	scmd->resid_len = ses->resid_len;
1143 	scmd->underflow = ses->underflow;
1144 	scmd->prot_op = ses->prot_op;
1145 	scmd->eh_eflags = ses->eh_eflags;
1146 }
1147 EXPORT_SYMBOL(scsi_eh_restore_cmnd);
1148 
1149 /**
1150  * scsi_send_eh_cmnd  - submit a scsi command as part of error recovery
1151  * @scmd:       SCSI command structure to hijack
1152  * @cmnd:       CDB to send
1153  * @cmnd_size:  size in bytes of @cmnd
1154  * @timeout:    timeout for this request
1155  * @sense_bytes: size of sense data to copy or 0
1156  *
1157  * This function is used to send a scsi command down to a target device
1158  * as part of the error recovery process. See also scsi_eh_prep_cmnd() above.
1159  *
1160  * Return value:
1161  *    SUCCESS or FAILED or NEEDS_RETRY
1162  */
scsi_send_eh_cmnd(struct scsi_cmnd * scmd,unsigned char * cmnd,int cmnd_size,int timeout,unsigned sense_bytes)1163 static enum scsi_disposition scsi_send_eh_cmnd(struct scsi_cmnd *scmd,
1164 	unsigned char *cmnd, int cmnd_size, int timeout, unsigned sense_bytes)
1165 {
1166 	struct scsi_device *sdev = scmd->device;
1167 	struct Scsi_Host *shost = sdev->host;
1168 	DECLARE_COMPLETION_ONSTACK(done);
1169 	unsigned long timeleft = timeout, delay;
1170 	struct scsi_eh_save ses;
1171 	const unsigned long stall_for = msecs_to_jiffies(100);
1172 	int rtn;
1173 
1174 retry:
1175 	scsi_eh_prep_cmnd(scmd, &ses, cmnd, cmnd_size, sense_bytes);
1176 	shost->eh_action = &done;
1177 
1178 	scsi_log_send(scmd);
1179 	scmd->submitter = SUBMITTED_BY_SCSI_ERROR_HANDLER;
1180 	scmd->flags |= SCMD_LAST;
1181 
1182 	/*
1183 	 * Lock sdev->state_mutex to avoid that scsi_device_quiesce() can
1184 	 * change the SCSI device state after we have examined it and before
1185 	 * .queuecommand() is called.
1186 	 */
1187 	mutex_lock(&sdev->state_mutex);
1188 	while (sdev->sdev_state == SDEV_BLOCK && timeleft > 0) {
1189 		mutex_unlock(&sdev->state_mutex);
1190 		SCSI_LOG_ERROR_RECOVERY(5, sdev_printk(KERN_DEBUG, sdev,
1191 			"%s: state %d <> %d\n", __func__, sdev->sdev_state,
1192 			SDEV_BLOCK));
1193 		delay = min(timeleft, stall_for);
1194 		timeleft -= delay;
1195 		msleep(jiffies_to_msecs(delay));
1196 		mutex_lock(&sdev->state_mutex);
1197 	}
1198 	if (sdev->sdev_state != SDEV_BLOCK)
1199 		rtn = shost->hostt->queuecommand(shost, scmd);
1200 	else
1201 		rtn = FAILED;
1202 	mutex_unlock(&sdev->state_mutex);
1203 
1204 	if (rtn) {
1205 		if (timeleft > stall_for) {
1206 			scsi_eh_restore_cmnd(scmd, &ses);
1207 
1208 			timeleft -= stall_for;
1209 			msleep(jiffies_to_msecs(stall_for));
1210 			goto retry;
1211 		}
1212 		/* signal not to enter either branch of the if () below */
1213 		timeleft = 0;
1214 		rtn = FAILED;
1215 	} else {
1216 		timeleft = wait_for_completion_timeout(&done, timeout);
1217 		rtn = SUCCESS;
1218 	}
1219 
1220 	shost->eh_action = NULL;
1221 
1222 	scsi_log_completion(scmd, rtn);
1223 
1224 	SCSI_LOG_ERROR_RECOVERY(3, scmd_printk(KERN_INFO, scmd,
1225 			"%s timeleft: %ld\n",
1226 			__func__, timeleft));
1227 
1228 	/*
1229 	 * If there is time left scsi_eh_done got called, and we will examine
1230 	 * the actual status codes to see whether the command actually did
1231 	 * complete normally, else if we have a zero return and no time left,
1232 	 * the command must still be pending, so abort it and return FAILED.
1233 	 * If we never actually managed to issue the command, because
1234 	 * ->queuecommand() kept returning non zero, use the rtn = FAILED
1235 	 * value above (so don't execute either branch of the if)
1236 	 */
1237 	if (timeleft) {
1238 		rtn = scsi_eh_completed_normally(scmd);
1239 		SCSI_LOG_ERROR_RECOVERY(3, scmd_printk(KERN_INFO, scmd,
1240 			"%s: scsi_eh_completed_normally %x\n", __func__, rtn));
1241 
1242 		switch (rtn) {
1243 		case SUCCESS:
1244 		case NEEDS_RETRY:
1245 		case FAILED:
1246 			break;
1247 		case ADD_TO_MLQUEUE:
1248 			rtn = NEEDS_RETRY;
1249 			break;
1250 		default:
1251 			rtn = FAILED;
1252 			break;
1253 		}
1254 	} else if (rtn != FAILED) {
1255 		scsi_abort_eh_cmnd(scmd);
1256 		rtn = FAILED;
1257 	}
1258 
1259 	scsi_eh_restore_cmnd(scmd, &ses);
1260 
1261 	return rtn;
1262 }
1263 
1264 /**
1265  * scsi_request_sense - Request sense data from a particular target.
1266  * @scmd:	SCSI cmd for request sense.
1267  *
1268  * Notes:
1269  *    Some hosts automatically obtain this information, others require
1270  *    that we obtain it on our own. This function will *not* return until
1271  *    the command either times out, or it completes.
1272  */
scsi_request_sense(struct scsi_cmnd * scmd)1273 static enum scsi_disposition scsi_request_sense(struct scsi_cmnd *scmd)
1274 {
1275 	return scsi_send_eh_cmnd(scmd, NULL, 0, scmd->device->eh_timeout, ~0);
1276 }
1277 
1278 static enum scsi_disposition
scsi_eh_action(struct scsi_cmnd * scmd,enum scsi_disposition rtn)1279 scsi_eh_action(struct scsi_cmnd *scmd, enum scsi_disposition rtn)
1280 {
1281 	if (!blk_rq_is_passthrough(scsi_cmd_to_rq(scmd))) {
1282 		struct scsi_driver *sdrv = scsi_cmd_to_driver(scmd);
1283 		if (sdrv->eh_action)
1284 			rtn = sdrv->eh_action(scmd, rtn);
1285 	}
1286 	return rtn;
1287 }
1288 
1289 /**
1290  * scsi_eh_finish_cmd - Handle a cmd that eh is finished with.
1291  * @scmd:	Original SCSI cmd that eh has finished.
1292  * @done_q:	Queue for processed commands.
1293  *
1294  * Notes:
1295  *    We don't want to use the normal command completion while we are are
1296  *    still handling errors - it may cause other commands to be queued,
1297  *    and that would disturb what we are doing.  Thus we really want to
1298  *    keep a list of pending commands for final completion, and once we
1299  *    are ready to leave error handling we handle completion for real.
1300  */
scsi_eh_finish_cmd(struct scsi_cmnd * scmd,struct list_head * done_q)1301 void scsi_eh_finish_cmd(struct scsi_cmnd *scmd, struct list_head *done_q)
1302 {
1303 	list_move_tail(&scmd->eh_entry, done_q);
1304 }
1305 EXPORT_SYMBOL(scsi_eh_finish_cmd);
1306 
1307 /**
1308  * scsi_eh_get_sense - Get device sense data.
1309  * @work_q:	Queue of commands to process.
1310  * @done_q:	Queue of processed commands.
1311  *
1312  * Description:
1313  *    See if we need to request sense information.  if so, then get it
1314  *    now, so we have a better idea of what to do.
1315  *
1316  * Notes:
1317  *    This has the unfortunate side effect that if a shost adapter does
1318  *    not automatically request sense information, we end up shutting
1319  *    it down before we request it.
1320  *
1321  *    All drivers should request sense information internally these days,
1322  *    so for now all I have to say is tough noogies if you end up in here.
1323  *
1324  *    XXX: Long term this code should go away, but that needs an audit of
1325  *         all LLDDs first.
1326  */
scsi_eh_get_sense(struct list_head * work_q,struct list_head * done_q)1327 int scsi_eh_get_sense(struct list_head *work_q,
1328 		      struct list_head *done_q)
1329 {
1330 	struct scsi_cmnd *scmd, *next;
1331 	struct Scsi_Host *shost;
1332 	enum scsi_disposition rtn;
1333 
1334 	/*
1335 	 * If SCSI_EH_ABORT_SCHEDULED has been set, it is timeout IO,
1336 	 * should not get sense.
1337 	 */
1338 	list_for_each_entry_safe(scmd, next, work_q, eh_entry) {
1339 		if ((scmd->eh_eflags & SCSI_EH_ABORT_SCHEDULED) ||
1340 		    SCSI_SENSE_VALID(scmd))
1341 			continue;
1342 
1343 		shost = scmd->device->host;
1344 		if (scsi_host_eh_past_deadline(shost)) {
1345 			SCSI_LOG_ERROR_RECOVERY(3,
1346 				scmd_printk(KERN_INFO, scmd,
1347 					    "%s: skip request sense, past eh deadline\n",
1348 					     current->comm));
1349 			break;
1350 		}
1351 		if (!scsi_status_is_check_condition(scmd->result))
1352 			/*
1353 			 * don't request sense if there's no check condition
1354 			 * status because the error we're processing isn't one
1355 			 * that has a sense code (and some devices get
1356 			 * confused by sense requests out of the blue)
1357 			 */
1358 			continue;
1359 
1360 		SCSI_LOG_ERROR_RECOVERY(2, scmd_printk(KERN_INFO, scmd,
1361 						  "%s: requesting sense\n",
1362 						  current->comm));
1363 		rtn = scsi_request_sense(scmd);
1364 		if (rtn != SUCCESS)
1365 			continue;
1366 
1367 		SCSI_LOG_ERROR_RECOVERY(3, scmd_printk(KERN_INFO, scmd,
1368 			"sense requested, result %x\n", scmd->result));
1369 		SCSI_LOG_ERROR_RECOVERY(3, scsi_print_sense(scmd));
1370 
1371 		rtn = scsi_decide_disposition(scmd);
1372 
1373 		/*
1374 		 * if the result was normal, then just pass it along to the
1375 		 * upper level.
1376 		 */
1377 		if (rtn == SUCCESS)
1378 			/*
1379 			 * We don't want this command reissued, just finished
1380 			 * with the sense data, so set retries to the max
1381 			 * allowed to ensure it won't get reissued. If the user
1382 			 * has requested infinite retries, we also want to
1383 			 * finish this command, so force completion by setting
1384 			 * retries and allowed to the same value.
1385 			 */
1386 			if (scmd->allowed == SCSI_CMD_RETRIES_NO_LIMIT)
1387 				scmd->retries = scmd->allowed = 1;
1388 			else
1389 				scmd->retries = scmd->allowed;
1390 		else if (rtn != NEEDS_RETRY)
1391 			continue;
1392 
1393 		scsi_eh_finish_cmd(scmd, done_q);
1394 	}
1395 
1396 	return list_empty(work_q);
1397 }
1398 EXPORT_SYMBOL_GPL(scsi_eh_get_sense);
1399 
1400 /**
1401  * scsi_eh_tur - Send TUR to device.
1402  * @scmd:	&scsi_cmnd to send TUR
1403  *
1404  * Return value:
1405  *    0 - Device is ready. 1 - Device NOT ready.
1406  */
scsi_eh_tur(struct scsi_cmnd * scmd)1407 static int scsi_eh_tur(struct scsi_cmnd *scmd)
1408 {
1409 	static unsigned char tur_command[6] = {TEST_UNIT_READY, 0, 0, 0, 0, 0};
1410 	int retry_cnt = 1;
1411 	enum scsi_disposition rtn;
1412 
1413 retry_tur:
1414 	rtn = scsi_send_eh_cmnd(scmd, tur_command, 6,
1415 				scmd->device->eh_timeout, 0);
1416 
1417 	SCSI_LOG_ERROR_RECOVERY(3, scmd_printk(KERN_INFO, scmd,
1418 		"%s return: %x\n", __func__, rtn));
1419 
1420 	switch (rtn) {
1421 	case NEEDS_RETRY:
1422 		if (retry_cnt--)
1423 			goto retry_tur;
1424 		fallthrough;
1425 	case SUCCESS:
1426 		return 0;
1427 	default:
1428 		return 1;
1429 	}
1430 }
1431 
1432 /**
1433  * scsi_eh_test_devices - check if devices are responding from error recovery.
1434  * @cmd_list:	scsi commands in error recovery.
1435  * @work_q:	queue for commands which still need more error recovery
1436  * @done_q:	queue for commands which are finished
1437  * @try_stu:	boolean on if a STU command should be tried in addition to TUR.
1438  *
1439  * Decription:
1440  *    Tests if devices are in a working state.  Commands to devices now in
1441  *    a working state are sent to the done_q while commands to devices which
1442  *    are still failing to respond are returned to the work_q for more
1443  *    processing.
1444  **/
scsi_eh_test_devices(struct list_head * cmd_list,struct list_head * work_q,struct list_head * done_q,int try_stu)1445 static int scsi_eh_test_devices(struct list_head *cmd_list,
1446 				struct list_head *work_q,
1447 				struct list_head *done_q, int try_stu)
1448 {
1449 	struct scsi_cmnd *scmd, *next;
1450 	struct scsi_device *sdev;
1451 	int finish_cmds;
1452 
1453 	while (!list_empty(cmd_list)) {
1454 		scmd = list_entry(cmd_list->next, struct scsi_cmnd, eh_entry);
1455 		sdev = scmd->device;
1456 
1457 		if (!try_stu) {
1458 			if (scsi_host_eh_past_deadline(sdev->host)) {
1459 				/* Push items back onto work_q */
1460 				list_splice_init(cmd_list, work_q);
1461 				SCSI_LOG_ERROR_RECOVERY(3,
1462 					sdev_printk(KERN_INFO, sdev,
1463 						    "%s: skip test device, past eh deadline",
1464 						    current->comm));
1465 				break;
1466 			}
1467 		}
1468 
1469 		finish_cmds = !scsi_device_online(scmd->device) ||
1470 			(try_stu && !scsi_eh_try_stu(scmd) &&
1471 			 !scsi_eh_tur(scmd)) ||
1472 			!scsi_eh_tur(scmd);
1473 
1474 		list_for_each_entry_safe(scmd, next, cmd_list, eh_entry)
1475 			if (scmd->device == sdev) {
1476 				if (finish_cmds &&
1477 				    (try_stu ||
1478 				     scsi_eh_action(scmd, SUCCESS) == SUCCESS))
1479 					scsi_eh_finish_cmd(scmd, done_q);
1480 				else
1481 					list_move_tail(&scmd->eh_entry, work_q);
1482 			}
1483 	}
1484 	return list_empty(work_q);
1485 }
1486 
1487 /**
1488  * scsi_eh_try_stu - Send START_UNIT to device.
1489  * @scmd:	&scsi_cmnd to send START_UNIT
1490  *
1491  * Return value:
1492  *    0 - Device is ready. 1 - Device NOT ready.
1493  */
scsi_eh_try_stu(struct scsi_cmnd * scmd)1494 static int scsi_eh_try_stu(struct scsi_cmnd *scmd)
1495 {
1496 	static unsigned char stu_command[6] = {START_STOP, 0, 0, 0, 1, 0};
1497 
1498 	if (scmd->device->allow_restart) {
1499 		int i;
1500 		enum scsi_disposition rtn = NEEDS_RETRY;
1501 
1502 		for (i = 0; rtn == NEEDS_RETRY && i < 2; i++)
1503 			rtn = scsi_send_eh_cmnd(scmd, stu_command, 6,
1504 						scmd->device->eh_timeout, 0);
1505 
1506 		if (rtn == SUCCESS)
1507 			return 0;
1508 	}
1509 
1510 	return 1;
1511 }
1512 
1513  /**
1514  * scsi_eh_stu - send START_UNIT if needed
1515  * @shost:	&scsi host being recovered.
1516  * @work_q:	&list_head for pending commands.
1517  * @done_q:	&list_head for processed commands.
1518  *
1519  * Notes:
1520  *    If commands are failing due to not ready, initializing command required,
1521  *	try revalidating the device, which will end up sending a start unit.
1522  */
scsi_eh_stu(struct Scsi_Host * shost,struct list_head * work_q,struct list_head * done_q)1523 static int scsi_eh_stu(struct Scsi_Host *shost,
1524 			      struct list_head *work_q,
1525 			      struct list_head *done_q)
1526 {
1527 	struct scsi_cmnd *scmd, *stu_scmd, *next;
1528 	struct scsi_device *sdev;
1529 
1530 	shost_for_each_device(sdev, shost) {
1531 		if (scsi_host_eh_past_deadline(shost)) {
1532 			SCSI_LOG_ERROR_RECOVERY(3,
1533 				sdev_printk(KERN_INFO, sdev,
1534 					    "%s: skip START_UNIT, past eh deadline\n",
1535 					    current->comm));
1536 			scsi_device_put(sdev);
1537 			break;
1538 		}
1539 		stu_scmd = NULL;
1540 		list_for_each_entry(scmd, work_q, eh_entry)
1541 			if (scmd->device == sdev && SCSI_SENSE_VALID(scmd) &&
1542 			    scsi_check_sense(scmd) == FAILED ) {
1543 				stu_scmd = scmd;
1544 				break;
1545 			}
1546 
1547 		if (!stu_scmd)
1548 			continue;
1549 
1550 		SCSI_LOG_ERROR_RECOVERY(3,
1551 			sdev_printk(KERN_INFO, sdev,
1552 				     "%s: Sending START_UNIT\n",
1553 				    current->comm));
1554 
1555 		if (!scsi_eh_try_stu(stu_scmd)) {
1556 			if (!scsi_device_online(sdev) ||
1557 			    !scsi_eh_tur(stu_scmd)) {
1558 				list_for_each_entry_safe(scmd, next,
1559 							  work_q, eh_entry) {
1560 					if (scmd->device == sdev &&
1561 					    scsi_eh_action(scmd, SUCCESS) == SUCCESS)
1562 						scsi_eh_finish_cmd(scmd, done_q);
1563 				}
1564 			}
1565 		} else {
1566 			SCSI_LOG_ERROR_RECOVERY(3,
1567 				sdev_printk(KERN_INFO, sdev,
1568 					    "%s: START_UNIT failed\n",
1569 					    current->comm));
1570 		}
1571 	}
1572 
1573 	return list_empty(work_q);
1574 }
1575 
1576 
1577 /**
1578  * scsi_eh_bus_device_reset - send bdr if needed
1579  * @shost:	scsi host being recovered.
1580  * @work_q:	&list_head for pending commands.
1581  * @done_q:	&list_head for processed commands.
1582  *
1583  * Notes:
1584  *    Try a bus device reset.  Still, look to see whether we have multiple
1585  *    devices that are jammed or not - if we have multiple devices, it
1586  *    makes no sense to try bus_device_reset - we really would need to try
1587  *    a bus_reset instead.
1588  */
scsi_eh_bus_device_reset(struct Scsi_Host * shost,struct list_head * work_q,struct list_head * done_q)1589 static int scsi_eh_bus_device_reset(struct Scsi_Host *shost,
1590 				    struct list_head *work_q,
1591 				    struct list_head *done_q)
1592 {
1593 	struct scsi_cmnd *scmd, *bdr_scmd, *next;
1594 	struct scsi_device *sdev;
1595 	enum scsi_disposition rtn;
1596 
1597 	shost_for_each_device(sdev, shost) {
1598 		if (scsi_host_eh_past_deadline(shost)) {
1599 			SCSI_LOG_ERROR_RECOVERY(3,
1600 				sdev_printk(KERN_INFO, sdev,
1601 					    "%s: skip BDR, past eh deadline\n",
1602 					     current->comm));
1603 			scsi_device_put(sdev);
1604 			break;
1605 		}
1606 		bdr_scmd = NULL;
1607 		list_for_each_entry(scmd, work_q, eh_entry)
1608 			if (scmd->device == sdev) {
1609 				bdr_scmd = scmd;
1610 				break;
1611 			}
1612 
1613 		if (!bdr_scmd)
1614 			continue;
1615 
1616 		SCSI_LOG_ERROR_RECOVERY(3,
1617 			sdev_printk(KERN_INFO, sdev,
1618 				     "%s: Sending BDR\n", current->comm));
1619 		rtn = scsi_try_bus_device_reset(bdr_scmd);
1620 		if (rtn == SUCCESS || rtn == FAST_IO_FAIL) {
1621 			if (!scsi_device_online(sdev) ||
1622 			    rtn == FAST_IO_FAIL ||
1623 			    !scsi_eh_tur(bdr_scmd)) {
1624 				list_for_each_entry_safe(scmd, next,
1625 							 work_q, eh_entry) {
1626 					if (scmd->device == sdev &&
1627 					    scsi_eh_action(scmd, rtn) != FAILED)
1628 						scsi_eh_finish_cmd(scmd,
1629 								   done_q);
1630 				}
1631 			}
1632 		} else {
1633 			SCSI_LOG_ERROR_RECOVERY(3,
1634 				sdev_printk(KERN_INFO, sdev,
1635 					    "%s: BDR failed\n", current->comm));
1636 		}
1637 	}
1638 
1639 	return list_empty(work_q);
1640 }
1641 
1642 /**
1643  * scsi_eh_target_reset - send target reset if needed
1644  * @shost:	scsi host being recovered.
1645  * @work_q:	&list_head for pending commands.
1646  * @done_q:	&list_head for processed commands.
1647  *
1648  * Notes:
1649  *    Try a target reset.
1650  */
scsi_eh_target_reset(struct Scsi_Host * shost,struct list_head * work_q,struct list_head * done_q)1651 static int scsi_eh_target_reset(struct Scsi_Host *shost,
1652 				struct list_head *work_q,
1653 				struct list_head *done_q)
1654 {
1655 	LIST_HEAD(tmp_list);
1656 	LIST_HEAD(check_list);
1657 
1658 	list_splice_init(work_q, &tmp_list);
1659 
1660 	while (!list_empty(&tmp_list)) {
1661 		struct scsi_cmnd *next, *scmd;
1662 		enum scsi_disposition rtn;
1663 		unsigned int id;
1664 
1665 		if (scsi_host_eh_past_deadline(shost)) {
1666 			/* push back on work queue for further processing */
1667 			list_splice_init(&check_list, work_q);
1668 			list_splice_init(&tmp_list, work_q);
1669 			SCSI_LOG_ERROR_RECOVERY(3,
1670 				shost_printk(KERN_INFO, shost,
1671 					    "%s: Skip target reset, past eh deadline\n",
1672 					     current->comm));
1673 			return list_empty(work_q);
1674 		}
1675 
1676 		scmd = list_entry(tmp_list.next, struct scsi_cmnd, eh_entry);
1677 		id = scmd_id(scmd);
1678 
1679 		SCSI_LOG_ERROR_RECOVERY(3,
1680 			shost_printk(KERN_INFO, shost,
1681 				     "%s: Sending target reset to target %d\n",
1682 				     current->comm, id));
1683 		rtn = scsi_try_target_reset(scmd);
1684 		if (rtn != SUCCESS && rtn != FAST_IO_FAIL)
1685 			SCSI_LOG_ERROR_RECOVERY(3,
1686 				shost_printk(KERN_INFO, shost,
1687 					     "%s: Target reset failed"
1688 					     " target: %d\n",
1689 					     current->comm, id));
1690 		list_for_each_entry_safe(scmd, next, &tmp_list, eh_entry) {
1691 			if (scmd_id(scmd) != id)
1692 				continue;
1693 
1694 			if (rtn == SUCCESS)
1695 				list_move_tail(&scmd->eh_entry, &check_list);
1696 			else if (rtn == FAST_IO_FAIL)
1697 				scsi_eh_finish_cmd(scmd, done_q);
1698 			else
1699 				/* push back on work queue for further processing */
1700 				list_move(&scmd->eh_entry, work_q);
1701 		}
1702 	}
1703 
1704 	return scsi_eh_test_devices(&check_list, work_q, done_q, 0);
1705 }
1706 
1707 /**
1708  * scsi_eh_bus_reset - send a bus reset
1709  * @shost:	&scsi host being recovered.
1710  * @work_q:	&list_head for pending commands.
1711  * @done_q:	&list_head for processed commands.
1712  */
scsi_eh_bus_reset(struct Scsi_Host * shost,struct list_head * work_q,struct list_head * done_q)1713 static int scsi_eh_bus_reset(struct Scsi_Host *shost,
1714 			     struct list_head *work_q,
1715 			     struct list_head *done_q)
1716 {
1717 	struct scsi_cmnd *scmd, *chan_scmd, *next;
1718 	LIST_HEAD(check_list);
1719 	unsigned int channel;
1720 	enum scsi_disposition rtn;
1721 
1722 	/*
1723 	 * we really want to loop over the various channels, and do this on
1724 	 * a channel by channel basis.  we should also check to see if any
1725 	 * of the failed commands are on soft_reset devices, and if so, skip
1726 	 * the reset.
1727 	 */
1728 
1729 	for (channel = 0; channel <= shost->max_channel; channel++) {
1730 		if (scsi_host_eh_past_deadline(shost)) {
1731 			list_splice_init(&check_list, work_q);
1732 			SCSI_LOG_ERROR_RECOVERY(3,
1733 				shost_printk(KERN_INFO, shost,
1734 					    "%s: skip BRST, past eh deadline\n",
1735 					     current->comm));
1736 			return list_empty(work_q);
1737 		}
1738 
1739 		chan_scmd = NULL;
1740 		list_for_each_entry(scmd, work_q, eh_entry) {
1741 			if (channel == scmd_channel(scmd)) {
1742 				chan_scmd = scmd;
1743 				break;
1744 				/*
1745 				 * FIXME add back in some support for
1746 				 * soft_reset devices.
1747 				 */
1748 			}
1749 		}
1750 
1751 		if (!chan_scmd)
1752 			continue;
1753 		SCSI_LOG_ERROR_RECOVERY(3,
1754 			shost_printk(KERN_INFO, shost,
1755 				     "%s: Sending BRST chan: %d\n",
1756 				     current->comm, channel));
1757 		rtn = scsi_try_bus_reset(chan_scmd);
1758 		if (rtn == SUCCESS || rtn == FAST_IO_FAIL) {
1759 			list_for_each_entry_safe(scmd, next, work_q, eh_entry) {
1760 				if (channel == scmd_channel(scmd)) {
1761 					if (rtn == FAST_IO_FAIL)
1762 						scsi_eh_finish_cmd(scmd,
1763 								   done_q);
1764 					else
1765 						list_move_tail(&scmd->eh_entry,
1766 							       &check_list);
1767 				}
1768 			}
1769 		} else {
1770 			SCSI_LOG_ERROR_RECOVERY(3,
1771 				shost_printk(KERN_INFO, shost,
1772 					     "%s: BRST failed chan: %d\n",
1773 					     current->comm, channel));
1774 		}
1775 	}
1776 	return scsi_eh_test_devices(&check_list, work_q, done_q, 0);
1777 }
1778 
1779 /**
1780  * scsi_eh_host_reset - send a host reset
1781  * @shost:	host to be reset.
1782  * @work_q:	&list_head for pending commands.
1783  * @done_q:	&list_head for processed commands.
1784  */
scsi_eh_host_reset(struct Scsi_Host * shost,struct list_head * work_q,struct list_head * done_q)1785 static int scsi_eh_host_reset(struct Scsi_Host *shost,
1786 			      struct list_head *work_q,
1787 			      struct list_head *done_q)
1788 {
1789 	struct scsi_cmnd *scmd, *next;
1790 	LIST_HEAD(check_list);
1791 	enum scsi_disposition rtn;
1792 
1793 	if (!list_empty(work_q)) {
1794 		scmd = list_entry(work_q->next,
1795 				  struct scsi_cmnd, eh_entry);
1796 
1797 		SCSI_LOG_ERROR_RECOVERY(3,
1798 			shost_printk(KERN_INFO, shost,
1799 				     "%s: Sending HRST\n",
1800 				     current->comm));
1801 
1802 		rtn = scsi_try_host_reset(scmd);
1803 		if (rtn == SUCCESS) {
1804 			list_splice_init(work_q, &check_list);
1805 		} else if (rtn == FAST_IO_FAIL) {
1806 			list_for_each_entry_safe(scmd, next, work_q, eh_entry) {
1807 					scsi_eh_finish_cmd(scmd, done_q);
1808 			}
1809 		} else {
1810 			SCSI_LOG_ERROR_RECOVERY(3,
1811 				shost_printk(KERN_INFO, shost,
1812 					     "%s: HRST failed\n",
1813 					     current->comm));
1814 		}
1815 	}
1816 	return scsi_eh_test_devices(&check_list, work_q, done_q, 1);
1817 }
1818 
1819 /**
1820  * scsi_eh_offline_sdevs - offline scsi devices that fail to recover
1821  * @work_q:	&list_head for pending commands.
1822  * @done_q:	&list_head for processed commands.
1823  */
scsi_eh_offline_sdevs(struct list_head * work_q,struct list_head * done_q)1824 static void scsi_eh_offline_sdevs(struct list_head *work_q,
1825 				  struct list_head *done_q)
1826 {
1827 	struct scsi_cmnd *scmd, *next;
1828 	struct scsi_device *sdev;
1829 
1830 	list_for_each_entry_safe(scmd, next, work_q, eh_entry) {
1831 		sdev_printk(KERN_INFO, scmd->device, "Device offlined - "
1832 			    "not ready after error recovery\n");
1833 		sdev = scmd->device;
1834 
1835 		mutex_lock(&sdev->state_mutex);
1836 		scsi_device_set_state(sdev, SDEV_OFFLINE);
1837 		mutex_unlock(&sdev->state_mutex);
1838 
1839 		scsi_eh_finish_cmd(scmd, done_q);
1840 	}
1841 	return;
1842 }
1843 
1844 /**
1845  * scsi_noretry_cmd - determine if command should be failed fast
1846  * @scmd:	SCSI cmd to examine.
1847  */
scsi_noretry_cmd(struct scsi_cmnd * scmd)1848 bool scsi_noretry_cmd(struct scsi_cmnd *scmd)
1849 {
1850 	struct request *req = scsi_cmd_to_rq(scmd);
1851 
1852 	switch (host_byte(scmd->result)) {
1853 	case DID_OK:
1854 		break;
1855 	case DID_TIME_OUT:
1856 		goto check_type;
1857 	case DID_BUS_BUSY:
1858 		return !!(req->cmd_flags & REQ_FAILFAST_TRANSPORT);
1859 	case DID_PARITY:
1860 		return !!(req->cmd_flags & REQ_FAILFAST_DEV);
1861 	case DID_ERROR:
1862 		if (get_status_byte(scmd) == SAM_STAT_RESERVATION_CONFLICT)
1863 			return false;
1864 		fallthrough;
1865 	case DID_SOFT_ERROR:
1866 		return !!(req->cmd_flags & REQ_FAILFAST_DRIVER);
1867 	}
1868 
1869 	/* Never retry commands aborted due to a duration limit timeout */
1870 	if (scsi_ml_byte(scmd->result) == SCSIML_STAT_DL_TIMEOUT)
1871 		return true;
1872 
1873 	if (!scsi_status_is_check_condition(scmd->result))
1874 		return false;
1875 
1876 check_type:
1877 	/*
1878 	 * assume caller has checked sense and determined
1879 	 * the check condition was retryable.
1880 	 */
1881 	if (req->cmd_flags & REQ_FAILFAST_DEV || blk_rq_is_passthrough(req))
1882 		return true;
1883 
1884 	return false;
1885 }
1886 
1887 /**
1888  * scsi_decide_disposition - Disposition a cmd on return from LLD.
1889  * @scmd:	SCSI cmd to examine.
1890  *
1891  * Notes:
1892  *    This is *only* called when we are examining the status after sending
1893  *    out the actual data command.  any commands that are queued for error
1894  *    recovery (e.g. test_unit_ready) do *not* come through here.
1895  *
1896  *    When this routine returns failed, it means the error handler thread
1897  *    is woken.  In cases where the error code indicates an error that
1898  *    doesn't require the error handler read (i.e. we don't need to
1899  *    abort/reset), this function should return SUCCESS.
1900  */
scsi_decide_disposition(struct scsi_cmnd * scmd)1901 enum scsi_disposition scsi_decide_disposition(struct scsi_cmnd *scmd)
1902 {
1903 	enum scsi_disposition rtn;
1904 
1905 	/*
1906 	 * if the device is offline, then we clearly just pass the result back
1907 	 * up to the top level.
1908 	 */
1909 	if (!scsi_device_online(scmd->device)) {
1910 		SCSI_LOG_ERROR_RECOVERY(5, scmd_printk(KERN_INFO, scmd,
1911 			"%s: device offline - report as SUCCESS\n", __func__));
1912 		return SUCCESS;
1913 	}
1914 
1915 	/*
1916 	 * first check the host byte, to see if there is anything in there
1917 	 * that would indicate what we need to do.
1918 	 */
1919 	switch (host_byte(scmd->result)) {
1920 	case DID_PASSTHROUGH:
1921 		/*
1922 		 * no matter what, pass this through to the upper layer.
1923 		 * nuke this special code so that it looks like we are saying
1924 		 * did_ok.
1925 		 */
1926 		scmd->result &= 0xff00ffff;
1927 		return SUCCESS;
1928 	case DID_OK:
1929 		/*
1930 		 * looks good.  drop through, and check the next byte.
1931 		 */
1932 		break;
1933 	case DID_ABORT:
1934 		if (scmd->eh_eflags & SCSI_EH_ABORT_SCHEDULED) {
1935 			set_host_byte(scmd, DID_TIME_OUT);
1936 			return SUCCESS;
1937 		}
1938 		fallthrough;
1939 	case DID_NO_CONNECT:
1940 	case DID_BAD_TARGET:
1941 		/*
1942 		 * note - this means that we just report the status back
1943 		 * to the top level driver, not that we actually think
1944 		 * that it indicates SUCCESS.
1945 		 */
1946 		return SUCCESS;
1947 	case DID_SOFT_ERROR:
1948 		/*
1949 		 * when the low level driver returns did_soft_error,
1950 		 * it is responsible for keeping an internal retry counter
1951 		 * in order to avoid endless loops (db)
1952 		 */
1953 		goto maybe_retry;
1954 	case DID_IMM_RETRY:
1955 		return NEEDS_RETRY;
1956 
1957 	case DID_REQUEUE:
1958 		return ADD_TO_MLQUEUE;
1959 	case DID_TRANSPORT_DISRUPTED:
1960 		/*
1961 		 * LLD/transport was disrupted during processing of the IO.
1962 		 * The transport class is now blocked/blocking,
1963 		 * and the transport will decide what to do with the IO
1964 		 * based on its timers and recovery capablilities if
1965 		 * there are enough retries.
1966 		 */
1967 		goto maybe_retry;
1968 	case DID_TRANSPORT_FAILFAST:
1969 		/*
1970 		 * The transport decided to failfast the IO (most likely
1971 		 * the fast io fail tmo fired), so send IO directly upwards.
1972 		 */
1973 		return SUCCESS;
1974 	case DID_TRANSPORT_MARGINAL:
1975 		/*
1976 		 * caller has decided not to do retries on
1977 		 * abort success, so send IO directly upwards
1978 		 */
1979 		return SUCCESS;
1980 	case DID_ERROR:
1981 		if (get_status_byte(scmd) == SAM_STAT_RESERVATION_CONFLICT)
1982 			/*
1983 			 * execute reservation conflict processing code
1984 			 * lower down
1985 			 */
1986 			break;
1987 		fallthrough;
1988 	case DID_BUS_BUSY:
1989 	case DID_PARITY:
1990 		goto maybe_retry;
1991 	case DID_TIME_OUT:
1992 		/*
1993 		 * when we scan the bus, we get timeout messages for
1994 		 * these commands if there is no device available.
1995 		 * other hosts report did_no_connect for the same thing.
1996 		 */
1997 		if ((scmd->cmnd[0] == TEST_UNIT_READY ||
1998 		     scmd->cmnd[0] == INQUIRY)) {
1999 			return SUCCESS;
2000 		} else {
2001 			return FAILED;
2002 		}
2003 	case DID_RESET:
2004 		return SUCCESS;
2005 	default:
2006 		return FAILED;
2007 	}
2008 
2009 	/*
2010 	 * check the status byte to see if this indicates anything special.
2011 	 */
2012 	switch (get_status_byte(scmd)) {
2013 	case SAM_STAT_TASK_SET_FULL:
2014 		scsi_handle_queue_full(scmd->device);
2015 		/*
2016 		 * the case of trying to send too many commands to a
2017 		 * tagged queueing device.
2018 		 */
2019 		fallthrough;
2020 	case SAM_STAT_BUSY:
2021 		/*
2022 		 * device can't talk to us at the moment.  Should only
2023 		 * occur (SAM-3) when the task queue is empty, so will cause
2024 		 * the empty queue handling to trigger a stall in the
2025 		 * device.
2026 		 */
2027 		return ADD_TO_MLQUEUE;
2028 	case SAM_STAT_GOOD:
2029 		if (scmd->cmnd[0] == REPORT_LUNS)
2030 			scmd->device->sdev_target->expecting_lun_change = 0;
2031 		scsi_handle_queue_ramp_up(scmd->device);
2032 		if (scmd->sense_buffer && SCSI_SENSE_VALID(scmd))
2033 			/*
2034 			 * If we have sense data, call scsi_check_sense() in
2035 			 * order to set the correct SCSI ML byte (if any).
2036 			 * No point in checking the return value, since the
2037 			 * command has already completed successfully.
2038 			 */
2039 			scsi_check_sense(scmd);
2040 		fallthrough;
2041 	case SAM_STAT_COMMAND_TERMINATED:
2042 		return SUCCESS;
2043 	case SAM_STAT_TASK_ABORTED:
2044 		goto maybe_retry;
2045 	case SAM_STAT_CHECK_CONDITION:
2046 		rtn = scsi_check_sense(scmd);
2047 		if (rtn == NEEDS_RETRY)
2048 			goto maybe_retry;
2049 		/* if rtn == FAILED, we have no sense information;
2050 		 * returning FAILED will wake the error handler thread
2051 		 * to collect the sense and redo the decide
2052 		 * disposition */
2053 		return rtn;
2054 	case SAM_STAT_CONDITION_MET:
2055 	case SAM_STAT_INTERMEDIATE:
2056 	case SAM_STAT_INTERMEDIATE_CONDITION_MET:
2057 	case SAM_STAT_ACA_ACTIVE:
2058 		/*
2059 		 * who knows?  FIXME(eric)
2060 		 */
2061 		return SUCCESS;
2062 
2063 	case SAM_STAT_RESERVATION_CONFLICT:
2064 		sdev_printk(KERN_INFO, scmd->device,
2065 			    "reservation conflict\n");
2066 		set_scsi_ml_byte(scmd, SCSIML_STAT_RESV_CONFLICT);
2067 		return SUCCESS; /* causes immediate i/o error */
2068 	}
2069 	return FAILED;
2070 
2071 maybe_retry:
2072 
2073 	/* we requeue for retry because the error was retryable, and
2074 	 * the request was not marked fast fail.  Note that above,
2075 	 * even if the request is marked fast fail, we still requeue
2076 	 * for queue congestion conditions (QUEUE_FULL or BUSY) */
2077 	if (scsi_cmd_retry_allowed(scmd) && !scsi_noretry_cmd(scmd)) {
2078 		return NEEDS_RETRY;
2079 	} else {
2080 		/*
2081 		 * no more retries - report this one back to upper level.
2082 		 */
2083 		return SUCCESS;
2084 	}
2085 }
2086 
eh_lock_door_done(struct request * req,blk_status_t status)2087 static enum rq_end_io_ret eh_lock_door_done(struct request *req,
2088 					    blk_status_t status)
2089 {
2090 	blk_mq_free_request(req);
2091 	return RQ_END_IO_NONE;
2092 }
2093 
2094 /**
2095  * scsi_eh_lock_door - Prevent medium removal for the specified device
2096  * @sdev:	SCSI device to prevent medium removal
2097  *
2098  * Locking:
2099  * 	We must be called from process context.
2100  *
2101  * Notes:
2102  * 	We queue up an asynchronous "ALLOW MEDIUM REMOVAL" request on the
2103  * 	head of the devices request queue, and continue.
2104  */
scsi_eh_lock_door(struct scsi_device * sdev)2105 static void scsi_eh_lock_door(struct scsi_device *sdev)
2106 {
2107 	struct scsi_cmnd *scmd;
2108 	struct request *req;
2109 
2110 	req = scsi_alloc_request(sdev->request_queue, REQ_OP_DRV_IN, 0);
2111 	if (IS_ERR(req))
2112 		return;
2113 	scmd = blk_mq_rq_to_pdu(req);
2114 
2115 	scmd->cmnd[0] = ALLOW_MEDIUM_REMOVAL;
2116 	scmd->cmnd[1] = 0;
2117 	scmd->cmnd[2] = 0;
2118 	scmd->cmnd[3] = 0;
2119 	scmd->cmnd[4] = SCSI_REMOVAL_PREVENT;
2120 	scmd->cmnd[5] = 0;
2121 	scmd->cmd_len = COMMAND_SIZE(scmd->cmnd[0]);
2122 	scmd->allowed = 5;
2123 
2124 	req->rq_flags |= RQF_QUIET;
2125 	req->timeout = 10 * HZ;
2126 	req->end_io = eh_lock_door_done;
2127 
2128 	blk_execute_rq_nowait(req, true);
2129 }
2130 
2131 /**
2132  * scsi_restart_operations - restart io operations to the specified host.
2133  * @shost:	Host we are restarting.
2134  *
2135  * Notes:
2136  *    When we entered the error handler, we blocked all further i/o to
2137  *    this device.  we need to 'reverse' this process.
2138  */
scsi_restart_operations(struct Scsi_Host * shost)2139 static void scsi_restart_operations(struct Scsi_Host *shost)
2140 {
2141 	struct scsi_device *sdev;
2142 	unsigned long flags;
2143 
2144 	/*
2145 	 * If the door was locked, we need to insert a door lock request
2146 	 * onto the head of the SCSI request queue for the device.  There
2147 	 * is no point trying to lock the door of an off-line device.
2148 	 */
2149 	shost_for_each_device(sdev, shost) {
2150 		if (scsi_device_online(sdev) && sdev->was_reset && sdev->locked) {
2151 			scsi_eh_lock_door(sdev);
2152 			sdev->was_reset = 0;
2153 		}
2154 	}
2155 
2156 	/*
2157 	 * next free up anything directly waiting upon the host.  this
2158 	 * will be requests for character device operations, and also for
2159 	 * ioctls to queued block devices.
2160 	 */
2161 	SCSI_LOG_ERROR_RECOVERY(3,
2162 		shost_printk(KERN_INFO, shost, "waking up host to restart\n"));
2163 
2164 	spin_lock_irqsave(shost->host_lock, flags);
2165 	if (scsi_host_set_state(shost, SHOST_RUNNING))
2166 		if (scsi_host_set_state(shost, SHOST_CANCEL))
2167 			BUG_ON(scsi_host_set_state(shost, SHOST_DEL));
2168 	spin_unlock_irqrestore(shost->host_lock, flags);
2169 
2170 	wake_up(&shost->host_wait);
2171 
2172 	/*
2173 	 * finally we need to re-initiate requests that may be pending.  we will
2174 	 * have had everything blocked while error handling is taking place, and
2175 	 * now that error recovery is done, we will need to ensure that these
2176 	 * requests are started.
2177 	 */
2178 	scsi_run_host_queues(shost);
2179 
2180 	/*
2181 	 * if eh is active and host_eh_scheduled is pending we need to re-run
2182 	 * recovery.  we do this check after scsi_run_host_queues() to allow
2183 	 * everything pent up since the last eh run a chance to make forward
2184 	 * progress before we sync again.  Either we'll immediately re-run
2185 	 * recovery or scsi_device_unbusy() will wake us again when these
2186 	 * pending commands complete.
2187 	 */
2188 	spin_lock_irqsave(shost->host_lock, flags);
2189 	if (shost->host_eh_scheduled)
2190 		if (scsi_host_set_state(shost, SHOST_RECOVERY))
2191 			WARN_ON(scsi_host_set_state(shost, SHOST_CANCEL_RECOVERY));
2192 	spin_unlock_irqrestore(shost->host_lock, flags);
2193 }
2194 
2195 /**
2196  * scsi_eh_ready_devs - check device ready state and recover if not.
2197  * @shost:	host to be recovered.
2198  * @work_q:	&list_head for pending commands.
2199  * @done_q:	&list_head for processed commands.
2200  */
scsi_eh_ready_devs(struct Scsi_Host * shost,struct list_head * work_q,struct list_head * done_q)2201 void scsi_eh_ready_devs(struct Scsi_Host *shost,
2202 			struct list_head *work_q,
2203 			struct list_head *done_q)
2204 {
2205 	if (!scsi_eh_stu(shost, work_q, done_q))
2206 		if (!scsi_eh_bus_device_reset(shost, work_q, done_q))
2207 			if (!scsi_eh_target_reset(shost, work_q, done_q))
2208 				if (!scsi_eh_bus_reset(shost, work_q, done_q))
2209 					if (!scsi_eh_host_reset(shost, work_q, done_q))
2210 						scsi_eh_offline_sdevs(work_q,
2211 								      done_q);
2212 }
2213 EXPORT_SYMBOL_GPL(scsi_eh_ready_devs);
2214 
2215 /**
2216  * scsi_eh_flush_done_q - finish processed commands or retry them.
2217  * @done_q:	list_head of processed commands.
2218  */
scsi_eh_flush_done_q(struct list_head * done_q)2219 void scsi_eh_flush_done_q(struct list_head *done_q)
2220 {
2221 	struct scsi_cmnd *scmd, *next;
2222 
2223 	list_for_each_entry_safe(scmd, next, done_q, eh_entry) {
2224 		struct scsi_device *sdev = scmd->device;
2225 
2226 		list_del_init(&scmd->eh_entry);
2227 		if (scsi_device_online(sdev) && !scsi_noretry_cmd(scmd) &&
2228 		    scsi_cmd_retry_allowed(scmd) &&
2229 		    scsi_eh_should_retry_cmd(scmd)) {
2230 			SCSI_LOG_ERROR_RECOVERY(3,
2231 				scmd_printk(KERN_INFO, scmd,
2232 					     "%s: flush retry cmd\n",
2233 					     current->comm));
2234 				scsi_queue_insert(scmd, SCSI_MLQUEUE_EH_RETRY);
2235 				blk_mq_kick_requeue_list(sdev->request_queue);
2236 		} else {
2237 			/*
2238 			 * If just we got sense for the device (called
2239 			 * scsi_eh_get_sense), scmd->result is already
2240 			 * set, do not set DID_TIME_OUT.
2241 			 */
2242 			if (!scmd->result &&
2243 			    !(scmd->flags & SCMD_FORCE_EH_SUCCESS))
2244 				scmd->result |= (DID_TIME_OUT << 16);
2245 			SCSI_LOG_ERROR_RECOVERY(3,
2246 				scmd_printk(KERN_INFO, scmd,
2247 					     "%s: flush finish cmd\n",
2248 					     current->comm));
2249 			scsi_finish_command(scmd);
2250 		}
2251 	}
2252 }
2253 EXPORT_SYMBOL(scsi_eh_flush_done_q);
2254 
2255 /**
2256  * scsi_unjam_host - Attempt to fix a host which has a cmd that failed.
2257  * @shost:	Host to unjam.
2258  *
2259  * Notes:
2260  *    When we come in here, we *know* that all commands on the bus have
2261  *    either completed, failed or timed out.  we also know that no further
2262  *    commands are being sent to the host, so things are relatively quiet
2263  *    and we have freedom to fiddle with things as we wish.
2264  *
2265  *    This is only the *default* implementation.  it is possible for
2266  *    individual drivers to supply their own version of this function, and
2267  *    if the maintainer wishes to do this, it is strongly suggested that
2268  *    this function be taken as a template and modified.  this function
2269  *    was designed to correctly handle problems for about 95% of the
2270  *    different cases out there, and it should always provide at least a
2271  *    reasonable amount of error recovery.
2272  *
2273  *    Any command marked 'failed' or 'timeout' must eventually have
2274  *    scsi_finish_cmd() called for it.  we do all of the retry stuff
2275  *    here, so when we restart the host after we return it should have an
2276  *    empty queue.
2277  */
scsi_unjam_host(struct Scsi_Host * shost)2278 static void scsi_unjam_host(struct Scsi_Host *shost)
2279 {
2280 	unsigned long flags;
2281 	LIST_HEAD(eh_work_q);
2282 	LIST_HEAD(eh_done_q);
2283 
2284 	spin_lock_irqsave(shost->host_lock, flags);
2285 	list_splice_init(&shost->eh_cmd_q, &eh_work_q);
2286 	spin_unlock_irqrestore(shost->host_lock, flags);
2287 
2288 	SCSI_LOG_ERROR_RECOVERY(1, scsi_eh_prt_fail_stats(shost, &eh_work_q));
2289 
2290 	if (!scsi_eh_get_sense(&eh_work_q, &eh_done_q))
2291 		scsi_eh_ready_devs(shost, &eh_work_q, &eh_done_q);
2292 
2293 	spin_lock_irqsave(shost->host_lock, flags);
2294 	if (shost->eh_deadline != -1)
2295 		shost->last_reset = 0;
2296 	spin_unlock_irqrestore(shost->host_lock, flags);
2297 	scsi_eh_flush_done_q(&eh_done_q);
2298 }
2299 
2300 /**
2301  * scsi_error_handler - SCSI error handler thread
2302  * @data:	Host for which we are running.
2303  *
2304  * Notes:
2305  *    This is the main error handling loop.  This is run as a kernel thread
2306  *    for every SCSI host and handles all error handling activity.
2307  */
scsi_error_handler(void * data)2308 int scsi_error_handler(void *data)
2309 {
2310 	struct Scsi_Host *shost = data;
2311 
2312 	/*
2313 	 * We use TASK_INTERRUPTIBLE so that the thread is not
2314 	 * counted against the load average as a running process.
2315 	 * We never actually get interrupted because kthread_run
2316 	 * disables signal delivery for the created thread.
2317 	 */
2318 	while (true) {
2319 		/*
2320 		 * The sequence in kthread_stop() sets the stop flag first
2321 		 * then wakes the process.  To avoid missed wakeups, the task
2322 		 * should always be in a non running state before the stop
2323 		 * flag is checked
2324 		 */
2325 		set_current_state(TASK_INTERRUPTIBLE);
2326 		if (kthread_should_stop())
2327 			break;
2328 
2329 		if ((shost->host_failed == 0 && shost->host_eh_scheduled == 0) ||
2330 		    shost->host_failed != scsi_host_busy(shost)) {
2331 			SCSI_LOG_ERROR_RECOVERY(1,
2332 				shost_printk(KERN_INFO, shost,
2333 					     "scsi_eh_%d: sleeping\n",
2334 					     shost->host_no));
2335 			schedule();
2336 			continue;
2337 		}
2338 
2339 		__set_current_state(TASK_RUNNING);
2340 		SCSI_LOG_ERROR_RECOVERY(1,
2341 			shost_printk(KERN_INFO, shost,
2342 				     "scsi_eh_%d: waking up %d/%d/%d\n",
2343 				     shost->host_no, shost->host_eh_scheduled,
2344 				     shost->host_failed,
2345 				     scsi_host_busy(shost)));
2346 
2347 		/*
2348 		 * We have a host that is failing for some reason.  Figure out
2349 		 * what we need to do to get it up and online again (if we can).
2350 		 * If we fail, we end up taking the thing offline.
2351 		 */
2352 		if (!shost->eh_noresume && scsi_autopm_get_host(shost) != 0) {
2353 			SCSI_LOG_ERROR_RECOVERY(1,
2354 				shost_printk(KERN_ERR, shost,
2355 					     "scsi_eh_%d: unable to autoresume\n",
2356 					     shost->host_no));
2357 			continue;
2358 		}
2359 
2360 		if (shost->transportt->eh_strategy_handler)
2361 			shost->transportt->eh_strategy_handler(shost);
2362 		else
2363 			scsi_unjam_host(shost);
2364 
2365 		/* All scmds have been handled */
2366 		shost->host_failed = 0;
2367 
2368 		/*
2369 		 * Note - if the above fails completely, the action is to take
2370 		 * individual devices offline and flush the queue of any
2371 		 * outstanding requests that may have been pending.  When we
2372 		 * restart, we restart any I/O to any other devices on the bus
2373 		 * which are still online.
2374 		 */
2375 		scsi_restart_operations(shost);
2376 		if (!shost->eh_noresume)
2377 			scsi_autopm_put_host(shost);
2378 	}
2379 	__set_current_state(TASK_RUNNING);
2380 
2381 	SCSI_LOG_ERROR_RECOVERY(1,
2382 		shost_printk(KERN_INFO, shost,
2383 			     "Error handler scsi_eh_%d exiting\n",
2384 			     shost->host_no));
2385 	shost->ehandler = NULL;
2386 	return 0;
2387 }
2388 
2389 /**
2390  * scsi_report_bus_reset() - report bus reset observed
2391  *
2392  * Utility function used by low-level drivers to report that
2393  * they have observed a bus reset on the bus being handled.
2394  *
2395  * @shost:      Host in question
2396  * @channel:    channel on which reset was observed.
2397  *
2398  * Returns:     Nothing
2399  *
2400  * Lock status: Host lock must be held.
2401  *
2402  * Notes:       This only needs to be called if the reset is one which
2403  *		originates from an unknown location.  Resets originated
2404  *		by the mid-level itself don't need to call this, but there
2405  *		should be no harm.
2406  *
2407  *		The main purpose of this is to make sure that a CHECK_CONDITION
2408  *		is properly treated.
2409  */
scsi_report_bus_reset(struct Scsi_Host * shost,int channel)2410 void scsi_report_bus_reset(struct Scsi_Host *shost, int channel)
2411 {
2412 	struct scsi_device *sdev;
2413 
2414 	__shost_for_each_device(sdev, shost) {
2415 		if (channel == sdev_channel(sdev))
2416 			__scsi_report_device_reset(sdev, NULL);
2417 	}
2418 }
2419 EXPORT_SYMBOL(scsi_report_bus_reset);
2420 
2421 /**
2422  * scsi_report_device_reset() - report device reset observed
2423  *
2424  * Utility function used by low-level drivers to report that
2425  * they have observed a device reset on the device being handled.
2426  *
2427  * @shost:      Host in question
2428  * @channel:    channel on which reset was observed
2429  * @target:     target on which reset was observed
2430  *
2431  * Returns:     Nothing
2432  *
2433  * Lock status: Host lock must be held
2434  *
2435  * Notes:       This only needs to be called if the reset is one which
2436  *		originates from an unknown location.  Resets originated
2437  *		by the mid-level itself don't need to call this, but there
2438  *		should be no harm.
2439  *
2440  *		The main purpose of this is to make sure that a CHECK_CONDITION
2441  *		is properly treated.
2442  */
scsi_report_device_reset(struct Scsi_Host * shost,int channel,int target)2443 void scsi_report_device_reset(struct Scsi_Host *shost, int channel, int target)
2444 {
2445 	struct scsi_device *sdev;
2446 
2447 	__shost_for_each_device(sdev, shost) {
2448 		if (channel == sdev_channel(sdev) &&
2449 		    target == sdev_id(sdev))
2450 			__scsi_report_device_reset(sdev, NULL);
2451 	}
2452 }
2453 EXPORT_SYMBOL(scsi_report_device_reset);
2454 
2455 /**
2456  * scsi_ioctl_reset: explicitly reset a host/bus/target/device
2457  * @dev:	scsi_device to operate on
2458  * @arg:	reset type (see sg.h)
2459  */
2460 int
scsi_ioctl_reset(struct scsi_device * dev,int __user * arg)2461 scsi_ioctl_reset(struct scsi_device *dev, int __user *arg)
2462 {
2463 	struct scsi_cmnd *scmd;
2464 	struct Scsi_Host *shost = dev->host;
2465 	struct request *rq;
2466 	unsigned long flags;
2467 	int error = 0, val;
2468 	enum scsi_disposition rtn;
2469 
2470 	if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
2471 		return -EACCES;
2472 
2473 	error = get_user(val, arg);
2474 	if (error)
2475 		return error;
2476 
2477 	if (scsi_autopm_get_host(shost) < 0)
2478 		return -EIO;
2479 
2480 	error = -EIO;
2481 	rq = kzalloc(sizeof(struct request) + sizeof(struct scsi_cmnd) +
2482 			shost->hostt->cmd_size, GFP_KERNEL);
2483 	if (!rq)
2484 		goto out_put_autopm_host;
2485 	blk_rq_init(NULL, rq);
2486 
2487 	scmd = (struct scsi_cmnd *)(rq + 1);
2488 	scsi_init_command(dev, scmd);
2489 
2490 	scmd->submitter = SUBMITTED_BY_SCSI_RESET_IOCTL;
2491 	scmd->flags |= SCMD_LAST;
2492 	memset(&scmd->sdb, 0, sizeof(scmd->sdb));
2493 
2494 	scmd->cmd_len			= 0;
2495 
2496 	scmd->sc_data_direction		= DMA_BIDIRECTIONAL;
2497 
2498 	spin_lock_irqsave(shost->host_lock, flags);
2499 	shost->tmf_in_progress = 1;
2500 	spin_unlock_irqrestore(shost->host_lock, flags);
2501 
2502 	switch (val & ~SG_SCSI_RESET_NO_ESCALATE) {
2503 	case SG_SCSI_RESET_NOTHING:
2504 		rtn = SUCCESS;
2505 		break;
2506 	case SG_SCSI_RESET_DEVICE:
2507 		rtn = scsi_try_bus_device_reset(scmd);
2508 		if (rtn == SUCCESS || (val & SG_SCSI_RESET_NO_ESCALATE))
2509 			break;
2510 		fallthrough;
2511 	case SG_SCSI_RESET_TARGET:
2512 		rtn = scsi_try_target_reset(scmd);
2513 		if (rtn == SUCCESS || (val & SG_SCSI_RESET_NO_ESCALATE))
2514 			break;
2515 		fallthrough;
2516 	case SG_SCSI_RESET_BUS:
2517 		rtn = scsi_try_bus_reset(scmd);
2518 		if (rtn == SUCCESS || (val & SG_SCSI_RESET_NO_ESCALATE))
2519 			break;
2520 		fallthrough;
2521 	case SG_SCSI_RESET_HOST:
2522 		rtn = scsi_try_host_reset(scmd);
2523 		if (rtn == SUCCESS)
2524 			break;
2525 		fallthrough;
2526 	default:
2527 		rtn = FAILED;
2528 		break;
2529 	}
2530 
2531 	error = (rtn == SUCCESS) ? 0 : -EIO;
2532 
2533 	spin_lock_irqsave(shost->host_lock, flags);
2534 	shost->tmf_in_progress = 0;
2535 	spin_unlock_irqrestore(shost->host_lock, flags);
2536 
2537 	/*
2538 	 * be sure to wake up anyone who was sleeping or had their queue
2539 	 * suspended while we performed the TMF.
2540 	 */
2541 	SCSI_LOG_ERROR_RECOVERY(3,
2542 		shost_printk(KERN_INFO, shost,
2543 			     "waking up host to restart after TMF\n"));
2544 
2545 	wake_up(&shost->host_wait);
2546 	scsi_run_host_queues(shost);
2547 
2548 	kfree(rq);
2549 
2550 out_put_autopm_host:
2551 	scsi_autopm_put_host(shost);
2552 	return error;
2553 }
2554 
scsi_command_normalize_sense(const struct scsi_cmnd * cmd,struct scsi_sense_hdr * sshdr)2555 bool scsi_command_normalize_sense(const struct scsi_cmnd *cmd,
2556 				  struct scsi_sense_hdr *sshdr)
2557 {
2558 	return scsi_normalize_sense(cmd->sense_buffer,
2559 			SCSI_SENSE_BUFFERSIZE, sshdr);
2560 }
2561 EXPORT_SYMBOL(scsi_command_normalize_sense);
2562 
2563 /**
2564  * scsi_get_sense_info_fld - get information field from sense data (either fixed or descriptor format)
2565  * @sense_buffer:	byte array of sense data
2566  * @sb_len:		number of valid bytes in sense_buffer
2567  * @info_out:		pointer to 64 integer where 8 or 4 byte information
2568  *			field will be placed if found.
2569  *
2570  * Return value:
2571  *	true if information field found, false if not found.
2572  */
scsi_get_sense_info_fld(const u8 * sense_buffer,int sb_len,u64 * info_out)2573 bool scsi_get_sense_info_fld(const u8 *sense_buffer, int sb_len,
2574 			     u64 *info_out)
2575 {
2576 	const u8 * ucp;
2577 
2578 	if (sb_len < 7)
2579 		return false;
2580 	switch (sense_buffer[0] & 0x7f) {
2581 	case 0x70:
2582 	case 0x71:
2583 		if (sense_buffer[0] & 0x80) {
2584 			*info_out = get_unaligned_be32(&sense_buffer[3]);
2585 			return true;
2586 		}
2587 		return false;
2588 	case 0x72:
2589 	case 0x73:
2590 		ucp = scsi_sense_desc_find(sense_buffer, sb_len,
2591 					   0 /* info desc */);
2592 		if (ucp && (0xa == ucp[1])) {
2593 			*info_out = get_unaligned_be64(&ucp[4]);
2594 			return true;
2595 		}
2596 		return false;
2597 	default:
2598 		return false;
2599 	}
2600 }
2601 EXPORT_SYMBOL(scsi_get_sense_info_fld);
2602