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