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