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