1/*
2 *  scsi_error.c Copyright (C) 1997 Eric Youngdale
3 *
4 *  SCSI error/timeout handling
5 *      Initial versions: Eric Youngdale.  Based upon conversations with
6 *                        Leonard Zubkoff and David Miller at Linux Expo,
7 *                        ideas originating from all over the place.
8 *
9 *	Restructured scsi_unjam_host and associated functions.
10 *	September 04, 2002 Mike Anderson (andmike@us.ibm.com)
11 *
12 *	Forward port of Russell King's (rmk@arm.linux.org.uk) changes and
13 *	minor  cleanups.
14 *	September 30, 2002 Mike Anderson (andmike@us.ibm.com)
15 */
16
17#include <linux/module.h>
18#include <linux/sched.h>
19#include <linux/timer.h>
20#include <linux/string.h>
21#include <linux/slab.h>
22#include <linux/kernel.h>
23#include <linux/kthread.h>
24#include <linux/interrupt.h>
25#include <linux/blkdev.h>
26#include <linux/delay.h>
27
28#include <scsi/scsi.h>
29#include <scsi/scsi_cmnd.h>
30#include <scsi/scsi_dbg.h>
31#include <scsi/scsi_device.h>
32#include <scsi/scsi_eh.h>
33#include <scsi/scsi_transport.h>
34#include <scsi/scsi_host.h>
35#include <scsi/scsi_ioctl.h>
36
37#include "scsi_priv.h"
38#include "scsi_logging.h"
39
40#define SENSE_TIMEOUT		(10*HZ)
41
42/*
43 * These should *probably* be handled by the host itself.
44 * Since it is allowed to sleep, it probably should.
45 */
46#define BUS_RESET_SETTLE_TIME   (10)
47#define HOST_RESET_SETTLE_TIME  (10)
48
49/* called with shost->host_lock held */
50void scsi_eh_wakeup(struct Scsi_Host *shost)
51{
52	if (shost->host_busy == shost->host_failed) {
53		wake_up_process(shost->ehandler);
54		SCSI_LOG_ERROR_RECOVERY(5,
55				printk("Waking error handler thread\n"));
56	}
57}
58
59/**
60 * scsi_schedule_eh - schedule EH for SCSI host
61 * @shost:	SCSI host to invoke error handling on.
62 *
63 * Schedule SCSI EH without scmd.
64 **/
65void scsi_schedule_eh(struct Scsi_Host *shost)
66{
67	unsigned long flags;
68
69	spin_lock_irqsave(shost->host_lock, flags);
70
71	if (scsi_host_set_state(shost, SHOST_RECOVERY) == 0 ||
72	    scsi_host_set_state(shost, SHOST_CANCEL_RECOVERY) == 0) {
73		shost->host_eh_scheduled++;
74		scsi_eh_wakeup(shost);
75	}
76
77	spin_unlock_irqrestore(shost->host_lock, flags);
78}
79EXPORT_SYMBOL_GPL(scsi_schedule_eh);
80
81/**
82 * scsi_eh_scmd_add - add scsi cmd to error handling.
83 * @scmd:	scmd to run eh on.
84 * @eh_flag:	optional SCSI_EH flag.
85 *
86 * Return value:
87 *	0 on failure.
88 **/
89int scsi_eh_scmd_add(struct scsi_cmnd *scmd, int eh_flag)
90{
91	struct Scsi_Host *shost = scmd->device->host;
92	unsigned long flags;
93	int ret = 0;
94
95	if (!shost->ehandler)
96		return 0;
97
98	spin_lock_irqsave(shost->host_lock, flags);
99	if (scsi_host_set_state(shost, SHOST_RECOVERY))
100		if (scsi_host_set_state(shost, SHOST_CANCEL_RECOVERY))
101			goto out_unlock;
102
103	ret = 1;
104	scmd->eh_eflags |= eh_flag;
105	list_add_tail(&scmd->eh_entry, &shost->eh_cmd_q);
106	shost->host_failed++;
107	scsi_eh_wakeup(shost);
108 out_unlock:
109	spin_unlock_irqrestore(shost->host_lock, flags);
110	return ret;
111}
112
113/**
114 * scsi_add_timer - Start timeout timer for a single scsi command.
115 * @scmd:	scsi command that is about to start running.
116 * @timeout:	amount of time to allow this command to run.
117 * @complete:	timeout function to call if timer isn't canceled.
118 *
119 * Notes:
120 *    This should be turned into an inline function.  Each scsi command
121 *    has its own timer, and as it is added to the queue, we set up the
122 *    timer.  When the command completes, we cancel the timer.
123 **/
124void scsi_add_timer(struct scsi_cmnd *scmd, int timeout,
125		    void (*complete)(struct scsi_cmnd *))
126{
127
128	/*
129	 * If the clock was already running for this command, then
130	 * first delete the timer.  The timer handling code gets rather
131	 * confused if we don't do this.
132	 */
133	if (scmd->eh_timeout.function)
134		del_timer(&scmd->eh_timeout);
135
136	scmd->eh_timeout.data = (unsigned long)scmd;
137	scmd->eh_timeout.expires = jiffies + timeout;
138	scmd->eh_timeout.function = (void (*)(unsigned long)) complete;
139
140	SCSI_LOG_ERROR_RECOVERY(5, printk("%s: scmd: %p, time:"
141					  " %d, (%p)\n", __FUNCTION__,
142					  scmd, timeout, complete));
143
144	add_timer(&scmd->eh_timeout);
145}
146
147/**
148 * scsi_delete_timer - Delete/cancel timer for a given function.
149 * @scmd:	Cmd that we are canceling timer for
150 *
151 * Notes:
152 *     This should be turned into an inline function.
153 *
154 * Return value:
155 *     1 if we were able to detach the timer.  0 if we blew it, and the
156 *     timer function has already started to run.
157 **/
158int scsi_delete_timer(struct scsi_cmnd *scmd)
159{
160	int rtn;
161
162	rtn = del_timer(&scmd->eh_timeout);
163
164	SCSI_LOG_ERROR_RECOVERY(5, printk("%s: scmd: %p,"
165					 " rtn: %d\n", __FUNCTION__,
166					 scmd, rtn));
167
168	scmd->eh_timeout.data = (unsigned long)NULL;
169	scmd->eh_timeout.function = NULL;
170
171	return rtn;
172}
173
174/**
175 * scsi_times_out - Timeout function for normal scsi commands.
176 * @scmd:	Cmd that is timing out.
177 *
178 * Notes:
179 *     We do not need to lock this.  There is the potential for a race
180 *     only in that the normal completion handling might run, but if the
181 *     normal completion function determines that the timer has already
182 *     fired, then it mustn't do anything.
183 **/
184void scsi_times_out(struct scsi_cmnd *scmd)
185{
186	enum scsi_eh_timer_return (* eh_timed_out)(struct scsi_cmnd *);
187
188	scsi_log_completion(scmd, TIMEOUT_ERROR);
189
190	if (scmd->device->host->transportt->eh_timed_out)
191		eh_timed_out = scmd->device->host->transportt->eh_timed_out;
192	else if (scmd->device->host->hostt->eh_timed_out)
193		eh_timed_out = scmd->device->host->hostt->eh_timed_out;
194	else
195		eh_timed_out = NULL;
196
197	if (eh_timed_out)
198		switch (eh_timed_out(scmd)) {
199		case EH_HANDLED:
200			__scsi_done(scmd);
201			return;
202		case EH_RESET_TIMER:
203			scsi_add_timer(scmd, scmd->timeout_per_command,
204				       scsi_times_out);
205			return;
206		case EH_NOT_HANDLED:
207			break;
208		}
209
210	if (unlikely(!scsi_eh_scmd_add(scmd, SCSI_EH_CANCEL_CMD))) {
211		scmd->result |= DID_TIME_OUT << 16;
212		__scsi_done(scmd);
213	}
214}
215
216/**
217 * scsi_block_when_processing_errors - Prevent cmds from being queued.
218 * @sdev:	Device on which we are performing recovery.
219 *
220 * Description:
221 *     We block until the host is out of error recovery, and then check to
222 *     see whether the host or the device is offline.
223 *
224 * Return value:
225 *     0 when dev was taken offline by error recovery. 1 OK to proceed.
226 **/
227int scsi_block_when_processing_errors(struct scsi_device *sdev)
228{
229	int online;
230
231	wait_event(sdev->host->host_wait, !scsi_host_in_recovery(sdev->host));
232
233	online = scsi_device_online(sdev);
234
235	SCSI_LOG_ERROR_RECOVERY(5, printk("%s: rtn: %d\n", __FUNCTION__,
236					  online));
237
238	return online;
239}
240EXPORT_SYMBOL(scsi_block_when_processing_errors);
241
242#ifdef CONFIG_SCSI_LOGGING
243/**
244 * scsi_eh_prt_fail_stats - Log info on failures.
245 * @shost:	scsi host being recovered.
246 * @work_q:	Queue of scsi cmds to process.
247 **/
248static inline void scsi_eh_prt_fail_stats(struct Scsi_Host *shost,
249					  struct list_head *work_q)
250{
251	struct scsi_cmnd *scmd;
252	struct scsi_device *sdev;
253	int total_failures = 0;
254	int cmd_failed = 0;
255	int cmd_cancel = 0;
256	int devices_failed = 0;
257
258	shost_for_each_device(sdev, shost) {
259		list_for_each_entry(scmd, work_q, eh_entry) {
260			if (scmd->device == sdev) {
261				++total_failures;
262				if (scmd->eh_eflags & SCSI_EH_CANCEL_CMD)
263					++cmd_cancel;
264				else
265					++cmd_failed;
266			}
267		}
268
269		if (cmd_cancel || cmd_failed) {
270			SCSI_LOG_ERROR_RECOVERY(3,
271				sdev_printk(KERN_INFO, sdev,
272					    "%s: cmds failed: %d, cancel: %d\n",
273					    __FUNCTION__, cmd_failed,
274					    cmd_cancel));
275			cmd_cancel = 0;
276			cmd_failed = 0;
277			++devices_failed;
278		}
279	}
280
281	SCSI_LOG_ERROR_RECOVERY(2, printk("Total of %d commands on %d"
282					  " devices require eh work\n",
283				  total_failures, devices_failed));
284}
285#endif
286
287/**
288 * scsi_check_sense - Examine scsi cmd sense
289 * @scmd:	Cmd to have sense checked.
290 *
291 * Return value:
292 * 	SUCCESS or FAILED or NEEDS_RETRY
293 *
294 * Notes:
295 *	When a deferred error is detected the current command has
296 *	not been executed and needs retrying.
297 **/
298static int scsi_check_sense(struct scsi_cmnd *scmd)
299{
300	struct scsi_sense_hdr sshdr;
301
302	if (! scsi_command_normalize_sense(scmd, &sshdr))
303		return FAILED;	/* no valid sense data */
304
305	if (scsi_sense_is_deferred(&sshdr))
306		return NEEDS_RETRY;
307
308	/*
309	 * Previous logic looked for FILEMARK, EOM or ILI which are
310	 * mainly associated with tapes and returned SUCCESS.
311	 */
312	if (sshdr.response_code == 0x70) {
313		/* fixed format */
314		if (scmd->sense_buffer[2] & 0xe0)
315			return SUCCESS;
316	} else {
317		/*
318		 * descriptor format: look for "stream commands sense data
319		 * descriptor" (see SSC-3). Assume single sense data
320		 * descriptor. Ignore ILI from SBC-2 READ LONG and WRITE LONG.
321		 */
322		if ((sshdr.additional_length > 3) &&
323		    (scmd->sense_buffer[8] == 0x4) &&
324		    (scmd->sense_buffer[11] & 0xe0))
325			return SUCCESS;
326	}
327
328	switch (sshdr.sense_key) {
329	case NO_SENSE:
330		return SUCCESS;
331	case RECOVERED_ERROR:
332		return /* soft_error */ SUCCESS;
333
334	case ABORTED_COMMAND:
335		return NEEDS_RETRY;
336	case NOT_READY:
337	case UNIT_ATTENTION:
338		/*
339		 * if we are expecting a cc/ua because of a bus reset that we
340		 * performed, treat this just as a retry.  otherwise this is
341		 * information that we should pass up to the upper-level driver
342		 * so that we can deal with it there.
343		 */
344		if (scmd->device->expecting_cc_ua) {
345			scmd->device->expecting_cc_ua = 0;
346			return NEEDS_RETRY;
347		}
348		/*
349		 * if the device is in the process of becoming ready, we
350		 * should retry.
351		 */
352		if ((sshdr.asc == 0x04) && (sshdr.ascq == 0x01))
353			return NEEDS_RETRY;
354		/*
355		 * if the device is not started, we need to wake
356		 * the error handler to start the motor
357		 */
358		if (scmd->device->allow_restart &&
359		    (sshdr.asc == 0x04) && (sshdr.ascq == 0x02))
360			return FAILED;
361		return SUCCESS;
362
363		/* these three are not supported */
364	case COPY_ABORTED:
365	case VOLUME_OVERFLOW:
366	case MISCOMPARE:
367		return SUCCESS;
368
369	case MEDIUM_ERROR:
370		if (sshdr.asc == 0x11 || /* UNRECOVERED READ ERR */
371		    sshdr.asc == 0x13 || /* AMNF DATA FIELD */
372		    sshdr.asc == 0x14) { /* RECORD NOT FOUND */
373			return SUCCESS;
374		}
375		return NEEDS_RETRY;
376
377	case HARDWARE_ERROR:
378		if (scmd->device->retry_hwerror)
379			return NEEDS_RETRY;
380		else
381			return SUCCESS;
382
383	case ILLEGAL_REQUEST:
384	case BLANK_CHECK:
385	case DATA_PROTECT:
386	default:
387		return SUCCESS;
388	}
389}
390
391/**
392 * scsi_eh_completed_normally - Disposition a eh cmd on return from LLD.
393 * @scmd:	SCSI cmd to examine.
394 *
395 * Notes:
396 *    This is *only* called when we are examining the status of commands
397 *    queued during error recovery.  the main difference here is that we
398 *    don't allow for the possibility of retries here, and we are a lot
399 *    more restrictive about what we consider acceptable.
400 **/
401static int scsi_eh_completed_normally(struct scsi_cmnd *scmd)
402{
403	/*
404	 * first check the host byte, to see if there is anything in there
405	 * that would indicate what we need to do.
406	 */
407	if (host_byte(scmd->result) == DID_RESET) {
408		/*
409		 * rats.  we are already in the error handler, so we now
410		 * get to try and figure out what to do next.  if the sense
411		 * is valid, we have a pretty good idea of what to do.
412		 * if not, we mark it as FAILED.
413		 */
414		return scsi_check_sense(scmd);
415	}
416	if (host_byte(scmd->result) != DID_OK)
417		return FAILED;
418
419	/*
420	 * next, check the message byte.
421	 */
422	if (msg_byte(scmd->result) != COMMAND_COMPLETE)
423		return FAILED;
424
425	/*
426	 * now, check the status byte to see if this indicates
427	 * anything special.
428	 */
429	switch (status_byte(scmd->result)) {
430	case GOOD:
431	case COMMAND_TERMINATED:
432		return SUCCESS;
433	case CHECK_CONDITION:
434		return scsi_check_sense(scmd);
435	case CONDITION_GOOD:
436	case INTERMEDIATE_GOOD:
437	case INTERMEDIATE_C_GOOD:
438		return SUCCESS;
439	case BUSY:
440	case QUEUE_FULL:
441	case RESERVATION_CONFLICT:
442	default:
443		return FAILED;
444	}
445	return FAILED;
446}
447
448/**
449 * scsi_eh_done - Completion function for error handling.
450 * @scmd:	Cmd that is done.
451 **/
452static void scsi_eh_done(struct scsi_cmnd *scmd)
453{
454	struct completion     *eh_action;
455
456	SCSI_LOG_ERROR_RECOVERY(3,
457		printk("%s scmd: %p result: %x\n",
458			__FUNCTION__, scmd, scmd->result));
459
460	eh_action = scmd->device->host->eh_action;
461	if (eh_action)
462		complete(eh_action);
463}
464
465/**
466 * scsi_try_host_reset - ask host adapter to reset itself
467 * @scmd:	SCSI cmd to send hsot reset.
468 **/
469static int scsi_try_host_reset(struct scsi_cmnd *scmd)
470{
471	unsigned long flags;
472	int rtn;
473
474	SCSI_LOG_ERROR_RECOVERY(3, printk("%s: Snd Host RST\n",
475					  __FUNCTION__));
476
477	if (!scmd->device->host->hostt->eh_host_reset_handler)
478		return FAILED;
479
480	rtn = scmd->device->host->hostt->eh_host_reset_handler(scmd);
481
482	if (rtn == SUCCESS) {
483		if (!scmd->device->host->hostt->skip_settle_delay)
484			ssleep(HOST_RESET_SETTLE_TIME);
485		spin_lock_irqsave(scmd->device->host->host_lock, flags);
486		scsi_report_bus_reset(scmd->device->host,
487				      scmd_channel(scmd));
488		spin_unlock_irqrestore(scmd->device->host->host_lock, flags);
489	}
490
491	return rtn;
492}
493
494/**
495 * scsi_try_bus_reset - ask host to perform a bus reset
496 * @scmd:	SCSI cmd to send bus reset.
497 **/
498static int scsi_try_bus_reset(struct scsi_cmnd *scmd)
499{
500	unsigned long flags;
501	int rtn;
502
503	SCSI_LOG_ERROR_RECOVERY(3, printk("%s: Snd Bus RST\n",
504					  __FUNCTION__));
505
506	if (!scmd->device->host->hostt->eh_bus_reset_handler)
507		return FAILED;
508
509	rtn = scmd->device->host->hostt->eh_bus_reset_handler(scmd);
510
511	if (rtn == SUCCESS) {
512		if (!scmd->device->host->hostt->skip_settle_delay)
513			ssleep(BUS_RESET_SETTLE_TIME);
514		spin_lock_irqsave(scmd->device->host->host_lock, flags);
515		scsi_report_bus_reset(scmd->device->host,
516				      scmd_channel(scmd));
517		spin_unlock_irqrestore(scmd->device->host->host_lock, flags);
518	}
519
520	return rtn;
521}
522
523/**
524 * scsi_try_bus_device_reset - Ask host to perform a BDR on a dev
525 * @scmd:	SCSI cmd used to send BDR
526 *
527 * Notes:
528 *    There is no timeout for this operation.  if this operation is
529 *    unreliable for a given host, then the host itself needs to put a
530 *    timer on it, and set the host back to a consistent state prior to
531 *    returning.
532 **/
533static int scsi_try_bus_device_reset(struct scsi_cmnd *scmd)
534{
535	int rtn;
536
537	if (!scmd->device->host->hostt->eh_device_reset_handler)
538		return FAILED;
539
540	rtn = scmd->device->host->hostt->eh_device_reset_handler(scmd);
541	if (rtn == SUCCESS) {
542		scmd->device->was_reset = 1;
543		scmd->device->expecting_cc_ua = 1;
544	}
545
546	return rtn;
547}
548
549static int __scsi_try_to_abort_cmd(struct scsi_cmnd *scmd)
550{
551	if (!scmd->device->host->hostt->eh_abort_handler)
552		return FAILED;
553
554	return scmd->device->host->hostt->eh_abort_handler(scmd);
555}
556
557/**
558 * scsi_try_to_abort_cmd - Ask host to abort a running command.
559 * @scmd:	SCSI cmd to abort from Lower Level.
560 *
561 * Notes:
562 *    This function will not return until the user's completion function
563 *    has been called.  there is no timeout on this operation.  if the
564 *    author of the low-level driver wishes this operation to be timed,
565 *    they can provide this facility themselves.  helper functions in
566 *    scsi_error.c can be supplied to make this easier to do.
567 **/
568static int scsi_try_to_abort_cmd(struct scsi_cmnd *scmd)
569{
570	/*
571	 * scsi_done was called just after the command timed out and before
572	 * we had a chance to process it. (db)
573	 */
574	if (scmd->serial_number == 0)
575		return SUCCESS;
576	return __scsi_try_to_abort_cmd(scmd);
577}
578
579static void scsi_abort_eh_cmnd(struct scsi_cmnd *scmd)
580{
581	if (__scsi_try_to_abort_cmd(scmd) != SUCCESS)
582		if (scsi_try_bus_device_reset(scmd) != SUCCESS)
583			if (scsi_try_bus_reset(scmd) != SUCCESS)
584				scsi_try_host_reset(scmd);
585}
586
587/**
588 * scsi_send_eh_cmnd  - submit a scsi command as part of error recory
589 * @scmd:       SCSI command structure to hijack
590 * @cmnd:       CDB to send
591 * @cmnd_size:  size in bytes of @cmnd
592 * @timeout:    timeout for this request
593 * @copy_sense: request sense data if set to 1
594 *
595 * This function is used to send a scsi command down to a target device
596 * as part of the error recovery process.  If @copy_sense is 0 the command
597 * sent must be one that does not transfer any data.  If @copy_sense is 1
598 * the command must be REQUEST_SENSE and this functions copies out the
599 * sense buffer it got into @scmd->sense_buffer.
600 *
601 * Return value:
602 *    SUCCESS or FAILED or NEEDS_RETRY
603 **/
604static int scsi_send_eh_cmnd(struct scsi_cmnd *scmd, unsigned char *cmnd,
605			     int cmnd_size, int timeout, int copy_sense)
606{
607	struct scsi_device *sdev = scmd->device;
608	struct Scsi_Host *shost = sdev->host;
609	int old_result = scmd->result;
610	DECLARE_COMPLETION_ONSTACK(done);
611	unsigned long timeleft;
612	unsigned long flags;
613	struct scatterlist sgl;
614	unsigned char old_cmnd[MAX_COMMAND_SIZE];
615	enum dma_data_direction old_data_direction;
616	unsigned short old_use_sg;
617	unsigned char old_cmd_len;
618	unsigned old_bufflen;
619	void *old_buffer;
620	int rtn;
621
622	/*
623	 * We need saved copies of a number of fields - this is because
624	 * error handling may need to overwrite these with different values
625	 * to run different commands, and once error handling is complete,
626	 * we will need to restore these values prior to running the actual
627	 * command.
628	 */
629	old_buffer = scmd->request_buffer;
630	old_bufflen = scmd->request_bufflen;
631	memcpy(old_cmnd, scmd->cmnd, sizeof(scmd->cmnd));
632	old_data_direction = scmd->sc_data_direction;
633	old_cmd_len = scmd->cmd_len;
634	old_use_sg = scmd->use_sg;
635
636	memset(scmd->cmnd, 0, sizeof(scmd->cmnd));
637	memcpy(scmd->cmnd, cmnd, cmnd_size);
638
639	if (copy_sense) {
640		gfp_t gfp_mask = GFP_ATOMIC;
641
642		if (shost->hostt->unchecked_isa_dma)
643			gfp_mask |= __GFP_DMA;
644
645		sgl.page = alloc_page(gfp_mask);
646		if (!sgl.page)
647			return FAILED;
648		sgl.offset = 0;
649		sgl.length = 252;
650
651		scmd->sc_data_direction = DMA_FROM_DEVICE;
652		scmd->request_bufflen = sgl.length;
653		scmd->request_buffer = &sgl;
654		scmd->use_sg = 1;
655	} else {
656		scmd->request_buffer = NULL;
657		scmd->request_bufflen = 0;
658		scmd->sc_data_direction = DMA_NONE;
659		scmd->use_sg = 0;
660	}
661
662	scmd->underflow = 0;
663	scmd->cmd_len = COMMAND_SIZE(scmd->cmnd[0]);
664
665	if (sdev->scsi_level <= SCSI_2)
666		scmd->cmnd[1] = (scmd->cmnd[1] & 0x1f) |
667			(sdev->lun << 5 & 0xe0);
668
669	/*
670	 * Zero the sense buffer.  The scsi spec mandates that any
671	 * untransferred sense data should be interpreted as being zero.
672	 */
673	memset(scmd->sense_buffer, 0, sizeof(scmd->sense_buffer));
674
675	shost->eh_action = &done;
676
677	spin_lock_irqsave(shost->host_lock, flags);
678	scsi_log_send(scmd);
679	shost->hostt->queuecommand(scmd, scsi_eh_done);
680	spin_unlock_irqrestore(shost->host_lock, flags);
681
682	timeleft = wait_for_completion_timeout(&done, timeout);
683
684	shost->eh_action = NULL;
685
686	scsi_log_completion(scmd, SUCCESS);
687
688	SCSI_LOG_ERROR_RECOVERY(3,
689		printk("%s: scmd: %p, timeleft: %ld\n",
690			__FUNCTION__, scmd, timeleft));
691
692	/*
693	 * If there is time left scsi_eh_done got called, and we will
694	 * examine the actual status codes to see whether the command
695	 * actually did complete normally, else tell the host to forget
696	 * about this command.
697	 */
698	if (timeleft) {
699		rtn = scsi_eh_completed_normally(scmd);
700		SCSI_LOG_ERROR_RECOVERY(3,
701			printk("%s: scsi_eh_completed_normally %x\n",
702			       __FUNCTION__, rtn));
703
704		switch (rtn) {
705		case SUCCESS:
706		case NEEDS_RETRY:
707		case FAILED:
708			break;
709		default:
710			rtn = FAILED;
711			break;
712		}
713	} else {
714		scsi_abort_eh_cmnd(scmd);
715		rtn = FAILED;
716	}
717
718
719	/*
720	 * Last chance to have valid sense data.
721	 */
722	if (copy_sense) {
723		if (!SCSI_SENSE_VALID(scmd)) {
724			memcpy(scmd->sense_buffer, page_address(sgl.page),
725			       sizeof(scmd->sense_buffer));
726		}
727		__free_page(sgl.page);
728	}
729
730
731	/*
732	 * Restore original data
733	 */
734	scmd->request_buffer = old_buffer;
735	scmd->request_bufflen = old_bufflen;
736	memcpy(scmd->cmnd, old_cmnd, sizeof(scmd->cmnd));
737	scmd->sc_data_direction = old_data_direction;
738	scmd->cmd_len = old_cmd_len;
739	scmd->use_sg = old_use_sg;
740	scmd->result = old_result;
741	return rtn;
742}
743
744/**
745 * scsi_request_sense - Request sense data from a particular target.
746 * @scmd:	SCSI cmd for request sense.
747 *
748 * Notes:
749 *    Some hosts automatically obtain this information, others require
750 *    that we obtain it on our own. This function will *not* return until
751 *    the command either times out, or it completes.
752 **/
753static int scsi_request_sense(struct scsi_cmnd *scmd)
754{
755	static unsigned char generic_sense[6] =
756		{REQUEST_SENSE, 0, 0, 0, 252, 0};
757
758	return scsi_send_eh_cmnd(scmd, generic_sense, 6, SENSE_TIMEOUT, 1);
759}
760
761/**
762 * scsi_eh_finish_cmd - Handle a cmd that eh is finished with.
763 * @scmd:	Original SCSI cmd that eh has finished.
764 * @done_q:	Queue for processed commands.
765 *
766 * Notes:
767 *    We don't want to use the normal command completion while we are are
768 *    still handling errors - it may cause other commands to be queued,
769 *    and that would disturb what we are doing.  thus we really want to
770 *    keep a list of pending commands for final completion, and once we
771 *    are ready to leave error handling we handle completion for real.
772 **/
773void scsi_eh_finish_cmd(struct scsi_cmnd *scmd, struct list_head *done_q)
774{
775	scmd->device->host->host_failed--;
776	scmd->eh_eflags = 0;
777	list_move_tail(&scmd->eh_entry, done_q);
778}
779EXPORT_SYMBOL(scsi_eh_finish_cmd);
780
781int scsi_eh_get_sense(struct list_head *work_q,
782		      struct list_head *done_q)
783{
784	struct scsi_cmnd *scmd, *next;
785	int rtn;
786
787	list_for_each_entry_safe(scmd, next, work_q, eh_entry) {
788		if ((scmd->eh_eflags & SCSI_EH_CANCEL_CMD) ||
789		    SCSI_SENSE_VALID(scmd))
790			continue;
791
792		SCSI_LOG_ERROR_RECOVERY(2, scmd_printk(KERN_INFO, scmd,
793						  "%s: requesting sense\n",
794						  current->comm));
795		rtn = scsi_request_sense(scmd);
796		if (rtn != SUCCESS)
797			continue;
798
799		SCSI_LOG_ERROR_RECOVERY(3, printk("sense requested for %p"
800						  " result %x\n", scmd,
801						  scmd->result));
802		SCSI_LOG_ERROR_RECOVERY(3, scsi_print_sense("bh", scmd));
803
804		rtn = scsi_decide_disposition(scmd);
805
806		/*
807		 * if the result was normal, then just pass it along to the
808		 * upper level.
809		 */
810		if (rtn == SUCCESS)
811			/* we don't want this command reissued, just
812			 * finished with the sense data, so set
813			 * retries to the max allowed to ensure it
814			 * won't get reissued */
815			scmd->retries = scmd->allowed;
816		else if (rtn != NEEDS_RETRY)
817			continue;
818
819		scsi_eh_finish_cmd(scmd, done_q);
820	}
821
822	return list_empty(work_q);
823}
824EXPORT_SYMBOL_GPL(scsi_eh_get_sense);
825
826/**
827 * scsi_eh_tur - Send TUR to device.
828 * @scmd:	Scsi cmd to send TUR
829 *
830 * Return value:
831 *    0 - Device is ready. 1 - Device NOT ready.
832 **/
833static int scsi_eh_tur(struct scsi_cmnd *scmd)
834{
835	static unsigned char tur_command[6] = {TEST_UNIT_READY, 0, 0, 0, 0, 0};
836	int retry_cnt = 1, rtn;
837
838retry_tur:
839	rtn = scsi_send_eh_cmnd(scmd, tur_command, 6, SENSE_TIMEOUT, 0);
840
841	SCSI_LOG_ERROR_RECOVERY(3, printk("%s: scmd %p rtn %x\n",
842		__FUNCTION__, scmd, rtn));
843
844	switch (rtn) {
845	case NEEDS_RETRY:
846		if (retry_cnt--)
847			goto retry_tur;
848		/*FALLTHRU*/
849	case SUCCESS:
850		return 0;
851	default:
852		return 1;
853	}
854}
855
856/**
857 * scsi_eh_abort_cmds - abort canceled commands.
858 * @shost:	scsi host being recovered.
859 * @eh_done_q:	list_head for processed commands.
860 *
861 * Decription:
862 *    Try and see whether or not it makes sense to try and abort the
863 *    running command.  this only works out to be the case if we have one
864 *    command that has timed out.  if the command simply failed, it makes
865 *    no sense to try and abort the command, since as far as the shost
866 *    adapter is concerned, it isn't running.
867 **/
868static int scsi_eh_abort_cmds(struct list_head *work_q,
869			      struct list_head *done_q)
870{
871	struct scsi_cmnd *scmd, *next;
872	int rtn;
873
874	list_for_each_entry_safe(scmd, next, work_q, eh_entry) {
875		if (!(scmd->eh_eflags & SCSI_EH_CANCEL_CMD))
876			continue;
877		SCSI_LOG_ERROR_RECOVERY(3, printk("%s: aborting cmd:"
878						  "0x%p\n", current->comm,
879						  scmd));
880		rtn = scsi_try_to_abort_cmd(scmd);
881		if (rtn == SUCCESS) {
882			scmd->eh_eflags &= ~SCSI_EH_CANCEL_CMD;
883			if (!scsi_device_online(scmd->device) ||
884			    !scsi_eh_tur(scmd)) {
885				scsi_eh_finish_cmd(scmd, done_q);
886			}
887
888		} else
889			SCSI_LOG_ERROR_RECOVERY(3, printk("%s: aborting"
890							  " cmd failed:"
891							  "0x%p\n",
892							  current->comm,
893							  scmd));
894	}
895
896	return list_empty(work_q);
897}
898
899/**
900 * scsi_eh_try_stu - Send START_UNIT to device.
901 * @scmd:	Scsi cmd to send START_UNIT
902 *
903 * Return value:
904 *    0 - Device is ready. 1 - Device NOT ready.
905 **/
906static int scsi_eh_try_stu(struct scsi_cmnd *scmd)
907{
908	static unsigned char stu_command[6] = {START_STOP, 0, 0, 0, 1, 0};
909
910	if (scmd->device->allow_restart) {
911		int i, rtn = NEEDS_RETRY;
912
913		for (i = 0; rtn == NEEDS_RETRY && i < 2; i++)
914			rtn = scsi_send_eh_cmnd(scmd, stu_command, 6,
915						scmd->device->timeout, 0);
916
917		if (rtn == SUCCESS)
918			return 0;
919	}
920
921	return 1;
922}
923
924 /**
925 * scsi_eh_stu - send START_UNIT if needed
926 * @shost:	scsi host being recovered.
927 * @eh_done_q:	list_head for processed commands.
928 *
929 * Notes:
930 *    If commands are failing due to not ready, initializing command required,
931 *	try revalidating the device, which will end up sending a start unit.
932 **/
933static int scsi_eh_stu(struct Scsi_Host *shost,
934			      struct list_head *work_q,
935			      struct list_head *done_q)
936{
937	struct scsi_cmnd *scmd, *stu_scmd, *next;
938	struct scsi_device *sdev;
939
940	shost_for_each_device(sdev, shost) {
941		stu_scmd = NULL;
942		list_for_each_entry(scmd, work_q, eh_entry)
943			if (scmd->device == sdev && SCSI_SENSE_VALID(scmd) &&
944			    scsi_check_sense(scmd) == FAILED ) {
945				stu_scmd = scmd;
946				break;
947			}
948
949		if (!stu_scmd)
950			continue;
951
952		SCSI_LOG_ERROR_RECOVERY(3, printk("%s: Sending START_UNIT to sdev:"
953						  " 0x%p\n", current->comm, sdev));
954
955		if (!scsi_eh_try_stu(stu_scmd)) {
956			if (!scsi_device_online(sdev) ||
957			    !scsi_eh_tur(stu_scmd)) {
958				list_for_each_entry_safe(scmd, next,
959							  work_q, eh_entry) {
960					if (scmd->device == sdev)
961						scsi_eh_finish_cmd(scmd, done_q);
962				}
963			}
964		} else {
965			SCSI_LOG_ERROR_RECOVERY(3,
966						printk("%s: START_UNIT failed to sdev:"
967						       " 0x%p\n", current->comm, sdev));
968		}
969	}
970
971	return list_empty(work_q);
972}
973
974
975/**
976 * scsi_eh_bus_device_reset - send bdr if needed
977 * @shost:	scsi host being recovered.
978 * @eh_done_q:	list_head for processed commands.
979 *
980 * Notes:
981 *    Try a bus device reset.  still, look to see whether we have multiple
982 *    devices that are jammed or not - if we have multiple devices, it
983 *    makes no sense to try bus_device_reset - we really would need to try
984 *    a bus_reset instead.
985 **/
986static int scsi_eh_bus_device_reset(struct Scsi_Host *shost,
987				    struct list_head *work_q,
988				    struct list_head *done_q)
989{
990	struct scsi_cmnd *scmd, *bdr_scmd, *next;
991	struct scsi_device *sdev;
992	int rtn;
993
994	shost_for_each_device(sdev, shost) {
995		bdr_scmd = NULL;
996		list_for_each_entry(scmd, work_q, eh_entry)
997			if (scmd->device == sdev) {
998				bdr_scmd = scmd;
999				break;
1000			}
1001
1002		if (!bdr_scmd)
1003			continue;
1004
1005		SCSI_LOG_ERROR_RECOVERY(3, printk("%s: Sending BDR sdev:"
1006						  " 0x%p\n", current->comm,
1007						  sdev));
1008		rtn = scsi_try_bus_device_reset(bdr_scmd);
1009		if (rtn == SUCCESS) {
1010			if (!scsi_device_online(sdev) ||
1011			    !scsi_eh_tur(bdr_scmd)) {
1012				list_for_each_entry_safe(scmd, next,
1013							 work_q, eh_entry) {
1014					if (scmd->device == sdev)
1015						scsi_eh_finish_cmd(scmd,
1016								   done_q);
1017				}
1018			}
1019		} else {
1020			SCSI_LOG_ERROR_RECOVERY(3, printk("%s: BDR"
1021							  " failed sdev:"
1022							  "0x%p\n",
1023							  current->comm,
1024							   sdev));
1025		}
1026	}
1027
1028	return list_empty(work_q);
1029}
1030
1031/**
1032 * scsi_eh_bus_reset - send a bus reset
1033 * @shost:	scsi host being recovered.
1034 * @eh_done_q:	list_head for processed commands.
1035 **/
1036static int scsi_eh_bus_reset(struct Scsi_Host *shost,
1037			     struct list_head *work_q,
1038			     struct list_head *done_q)
1039{
1040	struct scsi_cmnd *scmd, *chan_scmd, *next;
1041	unsigned int channel;
1042	int rtn;
1043
1044	/*
1045	 * we really want to loop over the various channels, and do this on
1046	 * a channel by channel basis.  we should also check to see if any
1047	 * of the failed commands are on soft_reset devices, and if so, skip
1048	 * the reset.
1049	 */
1050
1051	for (channel = 0; channel <= shost->max_channel; channel++) {
1052		chan_scmd = NULL;
1053		list_for_each_entry(scmd, work_q, eh_entry) {
1054			if (channel == scmd_channel(scmd)) {
1055				chan_scmd = scmd;
1056				break;
1057			}
1058		}
1059
1060		if (!chan_scmd)
1061			continue;
1062		SCSI_LOG_ERROR_RECOVERY(3, printk("%s: Sending BRST chan:"
1063						  " %d\n", current->comm,
1064						  channel));
1065		rtn = scsi_try_bus_reset(chan_scmd);
1066		if (rtn == SUCCESS) {
1067			list_for_each_entry_safe(scmd, next, work_q, eh_entry) {
1068				if (channel == scmd_channel(scmd))
1069					if (!scsi_device_online(scmd->device) ||
1070					    !scsi_eh_tur(scmd))
1071						scsi_eh_finish_cmd(scmd,
1072								   done_q);
1073			}
1074		} else {
1075			SCSI_LOG_ERROR_RECOVERY(3, printk("%s: BRST"
1076							  " failed chan: %d\n",
1077							  current->comm,
1078							  channel));
1079		}
1080	}
1081	return list_empty(work_q);
1082}
1083
1084/**
1085 * scsi_eh_host_reset - send a host reset
1086 * @work_q:	list_head for processed commands.
1087 * @done_q:	list_head for processed commands.
1088 **/
1089static int scsi_eh_host_reset(struct list_head *work_q,
1090			      struct list_head *done_q)
1091{
1092	struct scsi_cmnd *scmd, *next;
1093	int rtn;
1094
1095	if (!list_empty(work_q)) {
1096		scmd = list_entry(work_q->next,
1097				  struct scsi_cmnd, eh_entry);
1098
1099		SCSI_LOG_ERROR_RECOVERY(3, printk("%s: Sending HRST\n"
1100						  , current->comm));
1101
1102		rtn = scsi_try_host_reset(scmd);
1103		if (rtn == SUCCESS) {
1104			list_for_each_entry_safe(scmd, next, work_q, eh_entry) {
1105				if (!scsi_device_online(scmd->device) ||
1106				    (!scsi_eh_try_stu(scmd) && !scsi_eh_tur(scmd)) ||
1107				    !scsi_eh_tur(scmd))
1108					scsi_eh_finish_cmd(scmd, done_q);
1109			}
1110		} else {
1111			SCSI_LOG_ERROR_RECOVERY(3, printk("%s: HRST"
1112							  " failed\n",
1113							  current->comm));
1114		}
1115	}
1116	return list_empty(work_q);
1117}
1118
1119/**
1120 * scsi_eh_offline_sdevs - offline scsi devices that fail to recover
1121 * @work_q:	list_head for processed commands.
1122 * @done_q:	list_head for processed commands.
1123 *
1124 **/
1125static void scsi_eh_offline_sdevs(struct list_head *work_q,
1126				  struct list_head *done_q)
1127{
1128	struct scsi_cmnd *scmd, *next;
1129
1130	list_for_each_entry_safe(scmd, next, work_q, eh_entry) {
1131		sdev_printk(KERN_INFO, scmd->device,
1132			    "scsi: Device offlined - not"
1133			    " ready after error recovery\n");
1134		scsi_device_set_state(scmd->device, SDEV_OFFLINE);
1135		if (scmd->eh_eflags & SCSI_EH_CANCEL_CMD) {
1136		}
1137		scsi_eh_finish_cmd(scmd, done_q);
1138	}
1139	return;
1140}
1141
1142/**
1143 * scsi_decide_disposition - Disposition a cmd on return from LLD.
1144 * @scmd:	SCSI cmd to examine.
1145 *
1146 * Notes:
1147 *    This is *only* called when we are examining the status after sending
1148 *    out the actual data command.  any commands that are queued for error
1149 *    recovery (e.g. test_unit_ready) do *not* come through here.
1150 *
1151 *    When this routine returns failed, it means the error handler thread
1152 *    is woken.  In cases where the error code indicates an error that
1153 *    doesn't require the error handler read (i.e. we don't need to
1154 *    abort/reset), this function should return SUCCESS.
1155 **/
1156int scsi_decide_disposition(struct scsi_cmnd *scmd)
1157{
1158	int rtn;
1159
1160	/*
1161	 * if the device is offline, then we clearly just pass the result back
1162	 * up to the top level.
1163	 */
1164	if (!scsi_device_online(scmd->device)) {
1165		SCSI_LOG_ERROR_RECOVERY(5, printk("%s: device offline - report"
1166						  " as SUCCESS\n",
1167						  __FUNCTION__));
1168		return SUCCESS;
1169	}
1170
1171	/*
1172	 * first check the host byte, to see if there is anything in there
1173	 * that would indicate what we need to do.
1174	 */
1175	switch (host_byte(scmd->result)) {
1176	case DID_PASSTHROUGH:
1177		/*
1178		 * no matter what, pass this through to the upper layer.
1179		 * nuke this special code so that it looks like we are saying
1180		 * did_ok.
1181		 */
1182		scmd->result &= 0xff00ffff;
1183		return SUCCESS;
1184	case DID_OK:
1185		/*
1186		 * looks good.  drop through, and check the next byte.
1187		 */
1188		break;
1189	case DID_NO_CONNECT:
1190	case DID_BAD_TARGET:
1191	case DID_ABORT:
1192		/*
1193		 * note - this means that we just report the status back
1194		 * to the top level driver, not that we actually think
1195		 * that it indicates SUCCESS.
1196		 */
1197		return SUCCESS;
1198		/*
1199		 * when the low level driver returns did_soft_error,
1200		 * it is responsible for keeping an internal retry counter
1201		 * in order to avoid endless loops (db)
1202		 *
1203		 * actually this is a bug in this function here.  we should
1204		 * be mindful of the maximum number of retries specified
1205		 * and not get stuck in a loop.
1206		 */
1207	case DID_SOFT_ERROR:
1208		goto maybe_retry;
1209	case DID_IMM_RETRY:
1210		return NEEDS_RETRY;
1211
1212	case DID_REQUEUE:
1213		return ADD_TO_MLQUEUE;
1214
1215	case DID_ERROR:
1216		if (msg_byte(scmd->result) == COMMAND_COMPLETE &&
1217		    status_byte(scmd->result) == RESERVATION_CONFLICT)
1218			/*
1219			 * execute reservation conflict processing code
1220			 * lower down
1221			 */
1222			break;
1223		/* fallthrough */
1224
1225	case DID_BUS_BUSY:
1226	case DID_PARITY:
1227		goto maybe_retry;
1228	case DID_TIME_OUT:
1229		/*
1230		 * when we scan the bus, we get timeout messages for
1231		 * these commands if there is no device available.
1232		 * other hosts report did_no_connect for the same thing.
1233		 */
1234		if ((scmd->cmnd[0] == TEST_UNIT_READY ||
1235		     scmd->cmnd[0] == INQUIRY)) {
1236			return SUCCESS;
1237		} else {
1238			return FAILED;
1239		}
1240	case DID_RESET:
1241		return SUCCESS;
1242	default:
1243		return FAILED;
1244	}
1245
1246	/*
1247	 * next, check the message byte.
1248	 */
1249	if (msg_byte(scmd->result) != COMMAND_COMPLETE)
1250		return FAILED;
1251
1252	/*
1253	 * check the status byte to see if this indicates anything special.
1254	 */
1255	switch (status_byte(scmd->result)) {
1256	case QUEUE_FULL:
1257		/*
1258		 * the case of trying to send too many commands to a
1259		 * tagged queueing device.
1260		 */
1261	case BUSY:
1262		/*
1263		 * device can't talk to us at the moment.  Should only
1264		 * occur (SAM-3) when the task queue is empty, so will cause
1265		 * the empty queue handling to trigger a stall in the
1266		 * device.
1267		 */
1268		return ADD_TO_MLQUEUE;
1269	case GOOD:
1270	case COMMAND_TERMINATED:
1271	case TASK_ABORTED:
1272		return SUCCESS;
1273	case CHECK_CONDITION:
1274		rtn = scsi_check_sense(scmd);
1275		if (rtn == NEEDS_RETRY)
1276			goto maybe_retry;
1277		/* if rtn == FAILED, we have no sense information;
1278		 * returning FAILED will wake the error handler thread
1279		 * to collect the sense and redo the decide
1280		 * disposition */
1281		return rtn;
1282	case CONDITION_GOOD:
1283	case INTERMEDIATE_GOOD:
1284	case INTERMEDIATE_C_GOOD:
1285	case ACA_ACTIVE:
1286		return SUCCESS;
1287
1288	case RESERVATION_CONFLICT:
1289		sdev_printk(KERN_INFO, scmd->device,
1290			    "reservation conflict\n");
1291		return SUCCESS; /* causes immediate i/o error */
1292	default:
1293		return FAILED;
1294	}
1295	return FAILED;
1296
1297      maybe_retry:
1298
1299	/* we requeue for retry because the error was retryable, and
1300	 * the request was not marked fast fail.  Note that above,
1301	 * even if the request is marked fast fail, we still requeue
1302	 * for queue congestion conditions (QUEUE_FULL or BUSY) */
1303	if ((++scmd->retries) <= scmd->allowed
1304	    && !blk_noretry_request(scmd->request)) {
1305		return NEEDS_RETRY;
1306	} else {
1307		/*
1308		 * no more retries - report this one back to upper level.
1309		 */
1310		return SUCCESS;
1311	}
1312}
1313
1314/**
1315 * scsi_eh_lock_door - Prevent medium removal for the specified device
1316 * @sdev:	SCSI device to prevent medium removal
1317 *
1318 * Locking:
1319 * 	We must be called from process context; scsi_allocate_request()
1320 * 	may sleep.
1321 *
1322 * Notes:
1323 * 	We queue up an asynchronous "ALLOW MEDIUM REMOVAL" request on the
1324 * 	head of the devices request queue, and continue.
1325 *
1326 * Bugs:
1327 * 	scsi_allocate_request() may sleep waiting for existing requests to
1328 * 	be processed.  However, since we haven't kicked off any request
1329 * 	processing for this host, this may deadlock.
1330 *
1331 *	If scsi_allocate_request() fails for what ever reason, we
1332 *	completely forget to lock the door.
1333 **/
1334static void scsi_eh_lock_door(struct scsi_device *sdev)
1335{
1336	unsigned char cmnd[MAX_COMMAND_SIZE];
1337
1338	cmnd[0] = ALLOW_MEDIUM_REMOVAL;
1339	cmnd[1] = 0;
1340	cmnd[2] = 0;
1341	cmnd[3] = 0;
1342	cmnd[4] = SCSI_REMOVAL_PREVENT;
1343	cmnd[5] = 0;
1344
1345	scsi_execute_async(sdev, cmnd, 6, DMA_NONE, NULL, 0, 0, 10 * HZ,
1346			   5, NULL, NULL, GFP_KERNEL);
1347}
1348
1349
1350/**
1351 * scsi_restart_operations - restart io operations to the specified host.
1352 * @shost:	Host we are restarting.
1353 *
1354 * Notes:
1355 *    When we entered the error handler, we blocked all further i/o to
1356 *    this device.  we need to 'reverse' this process.
1357 **/
1358static void scsi_restart_operations(struct Scsi_Host *shost)
1359{
1360	struct scsi_device *sdev;
1361	unsigned long flags;
1362
1363	/*
1364	 * If the door was locked, we need to insert a door lock request
1365	 * onto the head of the SCSI request queue for the device.  There
1366	 * is no point trying to lock the door of an off-line device.
1367	 */
1368	shost_for_each_device(sdev, shost) {
1369		if (scsi_device_online(sdev) && sdev->locked)
1370			scsi_eh_lock_door(sdev);
1371	}
1372
1373	/*
1374	 * next free up anything directly waiting upon the host.  this
1375	 * will be requests for character device operations, and also for
1376	 * ioctls to queued block devices.
1377	 */
1378	SCSI_LOG_ERROR_RECOVERY(3, printk("%s: waking up host to restart\n",
1379					  __FUNCTION__));
1380
1381	spin_lock_irqsave(shost->host_lock, flags);
1382	if (scsi_host_set_state(shost, SHOST_RUNNING))
1383		if (scsi_host_set_state(shost, SHOST_CANCEL))
1384			BUG_ON(scsi_host_set_state(shost, SHOST_DEL));
1385	spin_unlock_irqrestore(shost->host_lock, flags);
1386
1387	wake_up(&shost->host_wait);
1388
1389	/*
1390	 * finally we need to re-initiate requests that may be pending.  we will
1391	 * have had everything blocked while error handling is taking place, and
1392	 * now that error recovery is done, we will need to ensure that these
1393	 * requests are started.
1394	 */
1395	scsi_run_host_queues(shost);
1396}
1397
1398/**
1399 * scsi_eh_ready_devs - check device ready state and recover if not.
1400 * @shost: 	host to be recovered.
1401 * @eh_done_q:	list_head for processed commands.
1402 *
1403 **/
1404void scsi_eh_ready_devs(struct Scsi_Host *shost,
1405			struct list_head *work_q,
1406			struct list_head *done_q)
1407{
1408	if (!scsi_eh_stu(shost, work_q, done_q))
1409		if (!scsi_eh_bus_device_reset(shost, work_q, done_q))
1410			if (!scsi_eh_bus_reset(shost, work_q, done_q))
1411				if (!scsi_eh_host_reset(work_q, done_q))
1412					scsi_eh_offline_sdevs(work_q, done_q);
1413}
1414EXPORT_SYMBOL_GPL(scsi_eh_ready_devs);
1415
1416/**
1417 * scsi_eh_flush_done_q - finish processed commands or retry them.
1418 * @done_q:	list_head of processed commands.
1419 *
1420 **/
1421void scsi_eh_flush_done_q(struct list_head *done_q)
1422{
1423	struct scsi_cmnd *scmd, *next;
1424
1425	list_for_each_entry_safe(scmd, next, done_q, eh_entry) {
1426		list_del_init(&scmd->eh_entry);
1427		if (scsi_device_online(scmd->device) &&
1428		    !blk_noretry_request(scmd->request) &&
1429		    (++scmd->retries <= scmd->allowed)) {
1430			SCSI_LOG_ERROR_RECOVERY(3, printk("%s: flush"
1431							  " retry cmd: %p\n",
1432							  current->comm,
1433							  scmd));
1434				scsi_queue_insert(scmd, SCSI_MLQUEUE_EH_RETRY);
1435		} else {
1436			/*
1437			 * If just we got sense for the device (called
1438			 * scsi_eh_get_sense), scmd->result is already
1439			 * set, do not set DRIVER_TIMEOUT.
1440			 */
1441			if (!scmd->result)
1442				scmd->result |= (DRIVER_TIMEOUT << 24);
1443			SCSI_LOG_ERROR_RECOVERY(3, printk("%s: flush finish"
1444							" cmd: %p\n",
1445							current->comm, scmd));
1446			scsi_finish_command(scmd);
1447		}
1448	}
1449}
1450EXPORT_SYMBOL(scsi_eh_flush_done_q);
1451
1452/**
1453 * scsi_unjam_host - Attempt to fix a host which has a cmd that failed.
1454 * @shost:	Host to unjam.
1455 *
1456 * Notes:
1457 *    When we come in here, we *know* that all commands on the bus have
1458 *    either completed, failed or timed out.  we also know that no further
1459 *    commands are being sent to the host, so things are relatively quiet
1460 *    and we have freedom to fiddle with things as we wish.
1461 *
1462 *    This is only the *default* implementation.  it is possible for
1463 *    individual drivers to supply their own version of this function, and
1464 *    if the maintainer wishes to do this, it is strongly suggested that
1465 *    this function be taken as a template and modified.  this function
1466 *    was designed to correctly handle problems for about 95% of the
1467 *    different cases out there, and it should always provide at least a
1468 *    reasonable amount of error recovery.
1469 *
1470 *    Any command marked 'failed' or 'timeout' must eventually have
1471 *    scsi_finish_cmd() called for it.  we do all of the retry stuff
1472 *    here, so when we restart the host after we return it should have an
1473 *    empty queue.
1474 **/
1475static void scsi_unjam_host(struct Scsi_Host *shost)
1476{
1477	unsigned long flags;
1478	LIST_HEAD(eh_work_q);
1479	LIST_HEAD(eh_done_q);
1480
1481	spin_lock_irqsave(shost->host_lock, flags);
1482	list_splice_init(&shost->eh_cmd_q, &eh_work_q);
1483	spin_unlock_irqrestore(shost->host_lock, flags);
1484
1485	SCSI_LOG_ERROR_RECOVERY(1, scsi_eh_prt_fail_stats(shost, &eh_work_q));
1486
1487	if (!scsi_eh_get_sense(&eh_work_q, &eh_done_q))
1488		if (!scsi_eh_abort_cmds(&eh_work_q, &eh_done_q))
1489			scsi_eh_ready_devs(shost, &eh_work_q, &eh_done_q);
1490
1491	scsi_eh_flush_done_q(&eh_done_q);
1492}
1493
1494/**
1495 * scsi_error_handler - SCSI error handler thread
1496 * @data:	Host for which we are running.
1497 *
1498 * Notes:
1499 *    This is the main error handling loop.  This is run as a kernel thread
1500 *    for every SCSI host and handles all error handling activity.
1501 **/
1502int scsi_error_handler(void *data)
1503{
1504	struct Scsi_Host *shost = data;
1505
1506	current->flags |= PF_NOFREEZE;
1507
1508	/*
1509	 * We use TASK_INTERRUPTIBLE so that the thread is not
1510	 * counted against the load average as a running process.
1511	 * We never actually get interrupted because kthread_run
1512	 * disables singal delivery for the created thread.
1513	 */
1514	set_current_state(TASK_INTERRUPTIBLE);
1515	while (!kthread_should_stop()) {
1516		if ((shost->host_failed == 0 && shost->host_eh_scheduled == 0) ||
1517		    shost->host_failed != shost->host_busy) {
1518			SCSI_LOG_ERROR_RECOVERY(1,
1519				printk("Error handler scsi_eh_%d sleeping\n",
1520					shost->host_no));
1521			schedule();
1522			set_current_state(TASK_INTERRUPTIBLE);
1523			continue;
1524		}
1525
1526		__set_current_state(TASK_RUNNING);
1527		SCSI_LOG_ERROR_RECOVERY(1,
1528			printk("Error handler scsi_eh_%d waking up\n",
1529				shost->host_no));
1530
1531		/*
1532		 * We have a host that is failing for some reason.  Figure out
1533		 * what we need to do to get it up and online again (if we can).
1534		 * If we fail, we end up taking the thing offline.
1535		 */
1536		if (shost->transportt->eh_strategy_handler)
1537			shost->transportt->eh_strategy_handler(shost);
1538		else
1539			scsi_unjam_host(shost);
1540
1541		/*
1542		 * Note - if the above fails completely, the action is to take
1543		 * individual devices offline and flush the queue of any
1544		 * outstanding requests that may have been pending.  When we
1545		 * restart, we restart any I/O to any other devices on the bus
1546		 * which are still online.
1547		 */
1548		scsi_restart_operations(shost);
1549		set_current_state(TASK_INTERRUPTIBLE);
1550	}
1551	__set_current_state(TASK_RUNNING);
1552
1553	SCSI_LOG_ERROR_RECOVERY(1,
1554		printk("Error handler scsi_eh_%d exiting\n", shost->host_no));
1555	shost->ehandler = NULL;
1556	return 0;
1557}
1558
1559/*
1560 * Function:    scsi_report_bus_reset()
1561 *
1562 * Purpose:     Utility function used by low-level drivers to report that
1563 *		they have observed a bus reset on the bus being handled.
1564 *
1565 * Arguments:   shost       - Host in question
1566 *		channel     - channel on which reset was observed.
1567 *
1568 * Returns:     Nothing
1569 *
1570 * Lock status: Host lock must be held.
1571 *
1572 * Notes:       This only needs to be called if the reset is one which
1573 *		originates from an unknown location.  Resets originated
1574 *		by the mid-level itself don't need to call this, but there
1575 *		should be no harm.
1576 *
1577 *		The main purpose of this is to make sure that a CHECK_CONDITION
1578 *		is properly treated.
1579 */
1580void scsi_report_bus_reset(struct Scsi_Host *shost, int channel)
1581{
1582	struct scsi_device *sdev;
1583
1584	__shost_for_each_device(sdev, shost) {
1585		if (channel == sdev_channel(sdev)) {
1586			sdev->was_reset = 1;
1587			sdev->expecting_cc_ua = 1;
1588		}
1589	}
1590}
1591EXPORT_SYMBOL(scsi_report_bus_reset);
1592
1593/*
1594 * Function:    scsi_report_device_reset()
1595 *
1596 * Purpose:     Utility function used by low-level drivers to report that
1597 *		they have observed a device reset on the device being handled.
1598 *
1599 * Arguments:   shost       - Host in question
1600 *		channel     - channel on which reset was observed
1601 *		target	    - target on which reset was observed
1602 *
1603 * Returns:     Nothing
1604 *
1605 * Lock status: Host lock must be held
1606 *
1607 * Notes:       This only needs to be called if the reset is one which
1608 *		originates from an unknown location.  Resets originated
1609 *		by the mid-level itself don't need to call this, but there
1610 *		should be no harm.
1611 *
1612 *		The main purpose of this is to make sure that a CHECK_CONDITION
1613 *		is properly treated.
1614 */
1615void scsi_report_device_reset(struct Scsi_Host *shost, int channel, int target)
1616{
1617	struct scsi_device *sdev;
1618
1619	__shost_for_each_device(sdev, shost) {
1620		if (channel == sdev_channel(sdev) &&
1621		    target == sdev_id(sdev)) {
1622			sdev->was_reset = 1;
1623			sdev->expecting_cc_ua = 1;
1624		}
1625	}
1626}
1627EXPORT_SYMBOL(scsi_report_device_reset);
1628
1629static void
1630scsi_reset_provider_done_command(struct scsi_cmnd *scmd)
1631{
1632}
1633
1634/*
1635 * Function:	scsi_reset_provider
1636 *
1637 * Purpose:	Send requested reset to a bus or device at any phase.
1638 *
1639 * Arguments:	device	- device to send reset to
1640 *		flag - reset type (see scsi.h)
1641 *
1642 * Returns:	SUCCESS/FAILURE.
1643 *
1644 * Notes:	This is used by the SCSI Generic driver to provide
1645 *		Bus/Device reset capability.
1646 */
1647int
1648scsi_reset_provider(struct scsi_device *dev, int flag)
1649{
1650	struct scsi_cmnd *scmd = scsi_get_command(dev, GFP_KERNEL);
1651	struct Scsi_Host *shost = dev->host;
1652	struct request req;
1653	unsigned long flags;
1654	int rtn;
1655
1656	scmd->request = &req;
1657	memset(&scmd->eh_timeout, 0, sizeof(scmd->eh_timeout));
1658
1659	memset(&scmd->cmnd, '\0', sizeof(scmd->cmnd));
1660
1661	scmd->scsi_done		= scsi_reset_provider_done_command;
1662	scmd->done			= NULL;
1663	scmd->request_buffer		= NULL;
1664	scmd->request_bufflen		= 0;
1665
1666	scmd->cmd_len			= 0;
1667
1668	scmd->sc_data_direction		= DMA_BIDIRECTIONAL;
1669
1670	init_timer(&scmd->eh_timeout);
1671
1672	/*
1673	 * Sometimes the command can get back into the timer chain,
1674	 * so use the pid as an identifier.
1675	 */
1676	scmd->pid			= 0;
1677
1678	spin_lock_irqsave(shost->host_lock, flags);
1679	shost->tmf_in_progress = 1;
1680	spin_unlock_irqrestore(shost->host_lock, flags);
1681
1682	switch (flag) {
1683	case SCSI_TRY_RESET_DEVICE:
1684		rtn = scsi_try_bus_device_reset(scmd);
1685		if (rtn == SUCCESS)
1686			break;
1687		/* FALLTHROUGH */
1688	case SCSI_TRY_RESET_BUS:
1689		rtn = scsi_try_bus_reset(scmd);
1690		if (rtn == SUCCESS)
1691			break;
1692		/* FALLTHROUGH */
1693	case SCSI_TRY_RESET_HOST:
1694		rtn = scsi_try_host_reset(scmd);
1695		break;
1696	default:
1697		rtn = FAILED;
1698	}
1699
1700	spin_lock_irqsave(shost->host_lock, flags);
1701	shost->tmf_in_progress = 0;
1702	spin_unlock_irqrestore(shost->host_lock, flags);
1703
1704	/*
1705	 * be sure to wake up anyone who was sleeping or had their queue
1706	 * suspended while we performed the TMF.
1707	 */
1708	SCSI_LOG_ERROR_RECOVERY(3,
1709		printk("%s: waking up host to restart after TMF\n",
1710		__FUNCTION__));
1711
1712	wake_up(&shost->host_wait);
1713
1714	scsi_run_host_queues(shost);
1715
1716	scsi_next_command(scmd);
1717	return rtn;
1718}
1719EXPORT_SYMBOL(scsi_reset_provider);
1720
1721/**
1722 * scsi_normalize_sense - normalize main elements from either fixed or
1723 *			descriptor sense data format into a common format.
1724 *
1725 * @sense_buffer:	byte array containing sense data returned by device
1726 * @sb_len:		number of valid bytes in sense_buffer
1727 * @sshdr:		pointer to instance of structure that common
1728 *			elements are written to.
1729 *
1730 * Notes:
1731 *	The "main elements" from sense data are: response_code, sense_key,
1732 *	asc, ascq and additional_length (only for descriptor format).
1733 *
1734 *	Typically this function can be called after a device has
1735 *	responded to a SCSI command with the CHECK_CONDITION status.
1736 *
1737 * Return value:
1738 *	1 if valid sense data information found, else 0;
1739 **/
1740int scsi_normalize_sense(const u8 *sense_buffer, int sb_len,
1741                         struct scsi_sense_hdr *sshdr)
1742{
1743	if (!sense_buffer || !sb_len)
1744		return 0;
1745
1746	memset(sshdr, 0, sizeof(struct scsi_sense_hdr));
1747
1748	sshdr->response_code = (sense_buffer[0] & 0x7f);
1749
1750	if (!scsi_sense_valid(sshdr))
1751		return 0;
1752
1753	if (sshdr->response_code >= 0x72) {
1754		/*
1755		 * descriptor format
1756		 */
1757		if (sb_len > 1)
1758			sshdr->sense_key = (sense_buffer[1] & 0xf);
1759		if (sb_len > 2)
1760			sshdr->asc = sense_buffer[2];
1761		if (sb_len > 3)
1762			sshdr->ascq = sense_buffer[3];
1763		if (sb_len > 7)
1764			sshdr->additional_length = sense_buffer[7];
1765	} else {
1766		/*
1767		 * fixed format
1768		 */
1769		if (sb_len > 2)
1770			sshdr->sense_key = (sense_buffer[2] & 0xf);
1771		if (sb_len > 7) {
1772			sb_len = (sb_len < (sense_buffer[7] + 8)) ?
1773					 sb_len : (sense_buffer[7] + 8);
1774			if (sb_len > 12)
1775				sshdr->asc = sense_buffer[12];
1776			if (sb_len > 13)
1777				sshdr->ascq = sense_buffer[13];
1778		}
1779	}
1780
1781	return 1;
1782}
1783EXPORT_SYMBOL(scsi_normalize_sense);
1784
1785int scsi_command_normalize_sense(struct scsi_cmnd *cmd,
1786				 struct scsi_sense_hdr *sshdr)
1787{
1788	return scsi_normalize_sense(cmd->sense_buffer,
1789			sizeof(cmd->sense_buffer), sshdr);
1790}
1791EXPORT_SYMBOL(scsi_command_normalize_sense);
1792
1793/**
1794 * scsi_sense_desc_find - search for a given descriptor type in
1795 *			descriptor sense data format.
1796 *
1797 * @sense_buffer:	byte array of descriptor format sense data
1798 * @sb_len:		number of valid bytes in sense_buffer
1799 * @desc_type:		value of descriptor type to find
1800 *			(e.g. 0 -> information)
1801 *
1802 * Notes:
1803 *	only valid when sense data is in descriptor format
1804 *
1805 * Return value:
1806 *	pointer to start of (first) descriptor if found else NULL
1807 **/
1808const u8 * scsi_sense_desc_find(const u8 * sense_buffer, int sb_len,
1809				int desc_type)
1810{
1811	int add_sen_len, add_len, desc_len, k;
1812	const u8 * descp;
1813
1814	if ((sb_len < 8) || (0 == (add_sen_len = sense_buffer[7])))
1815		return NULL;
1816	if ((sense_buffer[0] < 0x72) || (sense_buffer[0] > 0x73))
1817		return NULL;
1818	add_sen_len = (add_sen_len < (sb_len - 8)) ?
1819			add_sen_len : (sb_len - 8);
1820	descp = &sense_buffer[8];
1821	for (desc_len = 0, k = 0; k < add_sen_len; k += desc_len) {
1822		descp += desc_len;
1823		add_len = (k < (add_sen_len - 1)) ? descp[1]: -1;
1824		desc_len = add_len + 2;
1825		if (descp[0] == desc_type)
1826			return descp;
1827		if (add_len < 0) // short descriptor ??
1828			break;
1829	}
1830	return NULL;
1831}
1832EXPORT_SYMBOL(scsi_sense_desc_find);
1833
1834/**
1835 * scsi_get_sense_info_fld - attempts to get information field from
1836 *			sense data (either fixed or descriptor format)
1837 *
1838 * @sense_buffer:	byte array of sense data
1839 * @sb_len:		number of valid bytes in sense_buffer
1840 * @info_out:		pointer to 64 integer where 8 or 4 byte information
1841 *			field will be placed if found.
1842 *
1843 * Return value:
1844 *	1 if information field found, 0 if not found.
1845 **/
1846int scsi_get_sense_info_fld(const u8 * sense_buffer, int sb_len,
1847			    u64 * info_out)
1848{
1849	int j;
1850	const u8 * ucp;
1851	u64 ull;
1852
1853	if (sb_len < 7)
1854		return 0;
1855	switch (sense_buffer[0] & 0x7f) {
1856	case 0x70:
1857	case 0x71:
1858		if (sense_buffer[0] & 0x80) {
1859			*info_out = (sense_buffer[3] << 24) +
1860				    (sense_buffer[4] << 16) +
1861				    (sense_buffer[5] << 8) + sense_buffer[6];
1862			return 1;
1863		} else
1864			return 0;
1865	case 0x72:
1866	case 0x73:
1867		ucp = scsi_sense_desc_find(sense_buffer, sb_len,
1868					   0 /* info desc */);
1869		if (ucp && (0xa == ucp[1])) {
1870			ull = 0;
1871			for (j = 0; j < 8; ++j) {
1872				if (j > 0)
1873					ull <<= 8;
1874				ull |= ucp[4 + j];
1875			}
1876			*info_out = ull;
1877			return 1;
1878		} else
1879			return 0;
1880	default:
1881		return 0;
1882	}
1883}
1884EXPORT_SYMBOL(scsi_get_sense_info_fld);
1885