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