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