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