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