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