ecd59ef8c8a361a34916cd486f5b083577b31612
[cascardo/linux.git] / drivers / ieee1394 / sbp2.c
1 /*
2  * sbp2.c - SBP-2 protocol driver for IEEE-1394
3  *
4  * Copyright (C) 2000 James Goodwin, Filanet Corporation (www.filanet.com)
5  * jamesg@filanet.com (JSG)
6  *
7  * Copyright (C) 2003 Ben Collins <bcollins@debian.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22  */
23
24 /*
25  * Brief Description:
26  *
27  * This driver implements the Serial Bus Protocol 2 (SBP-2) over IEEE-1394
28  * under Linux. The SBP-2 driver is implemented as an IEEE-1394 high-level
29  * driver. It also registers as a SCSI lower-level driver in order to accept
30  * SCSI commands for transport using SBP-2.
31  *
32  * You may access any attached SBP-2 storage devices as if they were SCSI
33  * devices (e.g. mount /dev/sda1,  fdisk, mkfs, etc.).
34  *
35  * Current Issues:
36  *
37  *      - Error Handling: SCSI aborts and bus reset requests are handled somewhat
38  *        but the code needs additional debugging.
39  */
40
41 #include <linux/config.h>
42 #include <linux/kernel.h>
43 #include <linux/list.h>
44 #include <linux/string.h>
45 #include <linux/stringify.h>
46 #include <linux/slab.h>
47 #include <linux/interrupt.h>
48 #include <linux/fs.h>
49 #include <linux/poll.h>
50 #include <linux/module.h>
51 #include <linux/moduleparam.h>
52 #include <linux/types.h>
53 #include <linux/delay.h>
54 #include <linux/sched.h>
55 #include <linux/blkdev.h>
56 #include <linux/smp_lock.h>
57 #include <linux/init.h>
58 #include <linux/pci.h>
59
60 #include <asm/current.h>
61 #include <asm/uaccess.h>
62 #include <asm/io.h>
63 #include <asm/byteorder.h>
64 #include <asm/atomic.h>
65 #include <asm/system.h>
66 #include <asm/scatterlist.h>
67
68 #include <scsi/scsi.h>
69 #include <scsi/scsi_cmnd.h>
70 #include <scsi/scsi_dbg.h>
71 #include <scsi/scsi_device.h>
72 #include <scsi/scsi_host.h>
73
74 #include "csr1212.h"
75 #include "ieee1394.h"
76 #include "ieee1394_types.h"
77 #include "ieee1394_core.h"
78 #include "nodemgr.h"
79 #include "hosts.h"
80 #include "highlevel.h"
81 #include "ieee1394_transactions.h"
82 #include "sbp2.h"
83
84 /*
85  * Module load parameter definitions
86  */
87
88 /*
89  * Change max_speed on module load if you have a bad IEEE-1394
90  * controller that has trouble running 2KB packets at 400mb.
91  *
92  * NOTE: On certain OHCI parts I have seen short packets on async transmit
93  * (probably due to PCI latency/throughput issues with the part). You can
94  * bump down the speed if you are running into problems.
95  */
96 static int max_speed = IEEE1394_SPEED_MAX;
97 module_param(max_speed, int, 0644);
98 MODULE_PARM_DESC(max_speed, "Force max speed (3 = 800mb, 2 = 400mb, 1 = 200mb, 0 = 100mb)");
99
100 /*
101  * Set serialize_io to 1 if you'd like only one scsi command sent
102  * down to us at a time (debugging). This might be necessary for very
103  * badly behaved sbp2 devices.
104  *
105  * TODO: Make this configurable per device.
106  */
107 static int serialize_io = 1;
108 module_param(serialize_io, int, 0444);
109 MODULE_PARM_DESC(serialize_io, "Serialize I/O coming from scsi drivers (default = 1, faster = 0)");
110
111 /*
112  * Bump up max_sectors if you'd like to support very large sized
113  * transfers. Please note that some older sbp2 bridge chips are broken for
114  * transfers greater or equal to 128KB.  Default is a value of 255
115  * sectors, or just under 128KB (at 512 byte sector size). I can note that
116  * the Oxsemi sbp2 chipsets have no problems supporting very large
117  * transfer sizes.
118  */
119 static int max_sectors = SBP2_MAX_SECTORS;
120 module_param(max_sectors, int, 0444);
121 MODULE_PARM_DESC(max_sectors, "Change max sectors per I/O supported (default = "
122                  __stringify(SBP2_MAX_SECTORS) ")");
123
124 /*
125  * Exclusive login to sbp2 device? In most cases, the sbp2 driver should
126  * do an exclusive login, as it's generally unsafe to have two hosts
127  * talking to a single sbp2 device at the same time (filesystem coherency,
128  * etc.). If you're running an sbp2 device that supports multiple logins,
129  * and you're either running read-only filesystems or some sort of special
130  * filesystem supporting multiple hosts (one such filesystem is OpenGFS,
131  * see opengfs.sourceforge.net for more info), then set exclusive_login
132  * to zero. Note: The Oxsemi OXFW911 sbp2 chipset supports up to four
133  * concurrent logins.
134  */
135 static int exclusive_login = 1;
136 module_param(exclusive_login, int, 0644);
137 MODULE_PARM_DESC(exclusive_login, "Exclusive login to sbp2 device (default = 1)");
138
139 /*
140  * If any of the following workarounds is required for your device to work,
141  * please submit the kernel messages logged by sbp2 to the linux1394-devel
142  * mailing list.
143  *
144  * - 128kB max transfer
145  *   Limit transfer size. Necessary for some old bridges.
146  *
147  * - 36 byte inquiry
148  *   When scsi_mod probes the device, let the inquiry command look like that
149  *   from MS Windows.
150  *
151  * - skip mode page 8
152  *   Suppress sending of mode_sense for mode page 8 if the device pretends to
153  *   support the SCSI Primary Block commands instead of Reduced Block Commands.
154  */
155 static int sbp2_default_workarounds;
156 module_param_named(workarounds, sbp2_default_workarounds, int, 0644);
157 MODULE_PARM_DESC(workarounds, "Work around device bugs (default = 0"
158         ", 128kB max transfer = " __stringify(SBP2_WORKAROUND_128K_MAX_TRANS)
159         ", 36 byte inquiry = "    __stringify(SBP2_WORKAROUND_INQUIRY_36)
160         ", skip mode page 8 = "   __stringify(SBP2_WORKAROUND_MODE_SENSE_8)
161         ", or a combination)");
162
163 /* legacy parameter */
164 static int force_inquiry_hack;
165 module_param(force_inquiry_hack, int, 0644);
166 MODULE_PARM_DESC(force_inquiry_hack, "Deprecated, use 'workarounds'");
167
168 /*
169  * Export information about protocols/devices supported by this driver.
170  */
171 static struct ieee1394_device_id sbp2_id_table[] = {
172         {
173          .match_flags = IEEE1394_MATCH_SPECIFIER_ID | IEEE1394_MATCH_VERSION,
174          .specifier_id = SBP2_UNIT_SPEC_ID_ENTRY & 0xffffff,
175          .version = SBP2_SW_VERSION_ENTRY & 0xffffff},
176         {}
177 };
178
179 MODULE_DEVICE_TABLE(ieee1394, sbp2_id_table);
180
181 /*
182  * Debug levels, configured via kernel config, or enable here.
183  */
184
185 #define CONFIG_IEEE1394_SBP2_DEBUG 0
186 /* #define CONFIG_IEEE1394_SBP2_DEBUG_ORBS */
187 /* #define CONFIG_IEEE1394_SBP2_DEBUG_DMA */
188 /* #define CONFIG_IEEE1394_SBP2_DEBUG 1 */
189 /* #define CONFIG_IEEE1394_SBP2_DEBUG 2 */
190 /* #define CONFIG_IEEE1394_SBP2_PACKET_DUMP */
191
192 #ifdef CONFIG_IEEE1394_SBP2_DEBUG_ORBS
193 #define SBP2_ORB_DEBUG(fmt, args...)    HPSB_ERR("sbp2(%s): "fmt, __FUNCTION__, ## args)
194 static u32 global_outstanding_command_orbs = 0;
195 #define outstanding_orb_incr global_outstanding_command_orbs++
196 #define outstanding_orb_decr global_outstanding_command_orbs--
197 #else
198 #define SBP2_ORB_DEBUG(fmt, args...)
199 #define outstanding_orb_incr
200 #define outstanding_orb_decr
201 #endif
202
203 #ifdef CONFIG_IEEE1394_SBP2_DEBUG_DMA
204 #define SBP2_DMA_ALLOC(fmt, args...) \
205         HPSB_ERR("sbp2(%s)alloc(%d): "fmt, __FUNCTION__, \
206                  ++global_outstanding_dmas, ## args)
207 #define SBP2_DMA_FREE(fmt, args...) \
208         HPSB_ERR("sbp2(%s)free(%d): "fmt, __FUNCTION__, \
209                  --global_outstanding_dmas, ## args)
210 static u32 global_outstanding_dmas = 0;
211 #else
212 #define SBP2_DMA_ALLOC(fmt, args...)
213 #define SBP2_DMA_FREE(fmt, args...)
214 #endif
215
216 #if CONFIG_IEEE1394_SBP2_DEBUG >= 2
217 #define SBP2_DEBUG(fmt, args...)        HPSB_ERR("sbp2: "fmt, ## args)
218 #define SBP2_INFO(fmt, args...)         HPSB_ERR("sbp2: "fmt, ## args)
219 #define SBP2_NOTICE(fmt, args...)       HPSB_ERR("sbp2: "fmt, ## args)
220 #define SBP2_WARN(fmt, args...)         HPSB_ERR("sbp2: "fmt, ## args)
221 #elif CONFIG_IEEE1394_SBP2_DEBUG == 1
222 #define SBP2_DEBUG(fmt, args...)        HPSB_DEBUG("sbp2: "fmt, ## args)
223 #define SBP2_INFO(fmt, args...)         HPSB_INFO("sbp2: "fmt, ## args)
224 #define SBP2_NOTICE(fmt, args...)       HPSB_NOTICE("sbp2: "fmt, ## args)
225 #define SBP2_WARN(fmt, args...)         HPSB_WARN("sbp2: "fmt, ## args)
226 #else
227 #define SBP2_DEBUG(fmt, args...)
228 #define SBP2_INFO(fmt, args...)         HPSB_INFO("sbp2: "fmt, ## args)
229 #define SBP2_NOTICE(fmt, args...)       HPSB_NOTICE("sbp2: "fmt, ## args)
230 #define SBP2_WARN(fmt, args...)         HPSB_WARN("sbp2: "fmt, ## args)
231 #endif
232
233 #define SBP2_ERR(fmt, args...)          HPSB_ERR("sbp2: "fmt, ## args)
234 #define SBP2_DEBUG_ENTER()              SBP2_DEBUG("%s", __FUNCTION__)
235
236 /*
237  * Globals
238  */
239
240 static void sbp2scsi_complete_all_commands(struct scsi_id_instance_data *scsi_id,
241                                            u32 status);
242
243 static void sbp2scsi_complete_command(struct scsi_id_instance_data *scsi_id,
244                                       u32 scsi_status, struct scsi_cmnd *SCpnt,
245                                       void (*done)(struct scsi_cmnd *));
246
247 static struct scsi_host_template scsi_driver_template;
248
249 static const u8 sbp2_speedto_max_payload[] = { 0x7, 0x8, 0x9, 0xA, 0xB, 0xC };
250
251 static void sbp2_host_reset(struct hpsb_host *host);
252
253 static int sbp2_probe(struct device *dev);
254 static int sbp2_remove(struct device *dev);
255 static int sbp2_update(struct unit_directory *ud);
256
257 static struct hpsb_highlevel sbp2_highlevel = {
258         .name =         SBP2_DEVICE_NAME,
259         .host_reset =   sbp2_host_reset,
260 };
261
262 static struct hpsb_address_ops sbp2_ops = {
263         .write = sbp2_handle_status_write
264 };
265
266 #ifdef CONFIG_IEEE1394_SBP2_PHYS_DMA
267 static struct hpsb_address_ops sbp2_physdma_ops = {
268         .read = sbp2_handle_physdma_read,
269         .write = sbp2_handle_physdma_write,
270 };
271 #endif
272
273 static struct hpsb_protocol_driver sbp2_driver = {
274         .name           = "SBP2 Driver",
275         .id_table       = sbp2_id_table,
276         .update         = sbp2_update,
277         .driver         = {
278                 .name           = SBP2_DEVICE_NAME,
279                 .bus            = &ieee1394_bus_type,
280                 .probe          = sbp2_probe,
281                 .remove         = sbp2_remove,
282         },
283 };
284
285 /*
286  * List of devices with known bugs.
287  *
288  * The firmware_revision field, masked with 0xffff00, is the best indicator
289  * for the type of bridge chip of a device.  It yields a few false positives
290  * but this did not break correctly behaving devices so far.
291  */
292 static const struct {
293         u32 firmware_revision;
294         unsigned workarounds;
295 } sbp2_workarounds_table[] = {
296         /* TSB42AA9 */ {
297                 .firmware_revision      = 0x002800,
298                 .workarounds            = SBP2_WORKAROUND_INQUIRY_36 |
299                                           SBP2_WORKAROUND_MODE_SENSE_8,
300         },
301         /* Initio bridges, actually only needed for some older ones */ {
302                 .firmware_revision      = 0x000200,
303                 .workarounds            = SBP2_WORKAROUND_INQUIRY_36,
304         },
305         /* Symbios bridge */ {
306                 .firmware_revision      = 0xa0b800,
307                 .workarounds            = SBP2_WORKAROUND_128K_MAX_TRANS,
308         }
309 };
310
311 /**************************************
312  * General utility functions
313  **************************************/
314
315 #ifndef __BIG_ENDIAN
316 /*
317  * Converts a buffer from be32 to cpu byte ordering. Length is in bytes.
318  */
319 static __inline__ void sbp2util_be32_to_cpu_buffer(void *buffer, int length)
320 {
321         u32 *temp = buffer;
322
323         for (length = (length >> 2); length--; )
324                 temp[length] = be32_to_cpu(temp[length]);
325
326         return;
327 }
328
329 /*
330  * Converts a buffer from cpu to be32 byte ordering. Length is in bytes.
331  */
332 static __inline__ void sbp2util_cpu_to_be32_buffer(void *buffer, int length)
333 {
334         u32 *temp = buffer;
335
336         for (length = (length >> 2); length--; )
337                 temp[length] = cpu_to_be32(temp[length]);
338
339         return;
340 }
341 #else /* BIG_ENDIAN */
342 /* Why waste the cpu cycles? */
343 #define sbp2util_be32_to_cpu_buffer(x,y)
344 #define sbp2util_cpu_to_be32_buffer(x,y)
345 #endif
346
347 #ifdef CONFIG_IEEE1394_SBP2_PACKET_DUMP
348 /*
349  * Debug packet dump routine. Length is in bytes.
350  */
351 static void sbp2util_packet_dump(void *buffer, int length, char *dump_name,
352                                  u32 dump_phys_addr)
353 {
354         int i;
355         unsigned char *dump = buffer;
356
357         if (!dump || !length || !dump_name)
358                 return;
359
360         if (dump_phys_addr)
361                 printk("[%s, 0x%x]", dump_name, dump_phys_addr);
362         else
363                 printk("[%s]", dump_name);
364         for (i = 0; i < length; i++) {
365                 if (i > 0x3f) {
366                         printk("\n   ...");
367                         break;
368                 }
369                 if ((i & 0x3) == 0)
370                         printk("  ");
371                 if ((i & 0xf) == 0)
372                         printk("\n   ");
373                 printk("%02x ", (int)dump[i]);
374         }
375         printk("\n");
376
377         return;
378 }
379 #else
380 #define sbp2util_packet_dump(w,x,y,z)
381 #endif
382
383 /*
384  * Goofy routine that basically does a down_timeout function.
385  */
386 static int sbp2util_down_timeout(atomic_t *done, int timeout)
387 {
388         int i;
389
390         for (i = timeout; (i > 0 && atomic_read(done) == 0); i-= HZ/10) {
391                 if (msleep_interruptible(100))  /* 100ms */
392                         return 1;
393         }
394         return (i > 0) ? 0 : 1;
395 }
396
397 /* Free's an allocated packet */
398 static void sbp2_free_packet(struct hpsb_packet *packet)
399 {
400         hpsb_free_tlabel(packet);
401         hpsb_free_packet(packet);
402 }
403
404 /* This is much like hpsb_node_write(), except it ignores the response
405  * subaction and returns immediately. Can be used from interrupts.
406  */
407 static int sbp2util_node_write_no_wait(struct node_entry *ne, u64 addr,
408                                        quadlet_t *buffer, size_t length)
409 {
410         struct hpsb_packet *packet;
411
412         packet = hpsb_make_writepacket(ne->host, ne->nodeid,
413                                        addr, buffer, length);
414         if (!packet)
415                 return -ENOMEM;
416
417         hpsb_set_packet_complete_task(packet,
418                                       (void (*)(void *))sbp2_free_packet,
419                                       packet);
420
421         hpsb_node_fill_packet(ne, packet);
422
423         if (hpsb_send_packet(packet) < 0) {
424                 sbp2_free_packet(packet);
425                 return -EIO;
426         }
427
428         return 0;
429 }
430
431 /*
432  * This function is called to create a pool of command orbs used for
433  * command processing. It is called when a new sbp2 device is detected.
434  */
435 static int sbp2util_create_command_orb_pool(struct scsi_id_instance_data *scsi_id)
436 {
437         struct sbp2scsi_host_info *hi = scsi_id->hi;
438         int i;
439         unsigned long flags, orbs;
440         struct sbp2_command_info *command;
441
442         orbs = serialize_io ? 2 : SBP2_MAX_CMDS;
443
444         spin_lock_irqsave(&scsi_id->sbp2_command_orb_lock, flags);
445         for (i = 0; i < orbs; i++) {
446                 command = kzalloc(sizeof(*command), GFP_ATOMIC);
447                 if (!command) {
448                         spin_unlock_irqrestore(&scsi_id->sbp2_command_orb_lock,
449                                                flags);
450                         return -ENOMEM;
451                 }
452                 command->command_orb_dma =
453                     pci_map_single(hi->host->pdev, &command->command_orb,
454                                    sizeof(struct sbp2_command_orb),
455                                    PCI_DMA_BIDIRECTIONAL);
456                 SBP2_DMA_ALLOC("single command orb DMA");
457                 command->sge_dma =
458                     pci_map_single(hi->host->pdev,
459                                    &command->scatter_gather_element,
460                                    sizeof(command->scatter_gather_element),
461                                    PCI_DMA_BIDIRECTIONAL);
462                 SBP2_DMA_ALLOC("scatter_gather_element");
463                 INIT_LIST_HEAD(&command->list);
464                 list_add_tail(&command->list, &scsi_id->sbp2_command_orb_completed);
465         }
466         spin_unlock_irqrestore(&scsi_id->sbp2_command_orb_lock, flags);
467         return 0;
468 }
469
470 /*
471  * This function is called to delete a pool of command orbs.
472  */
473 static void sbp2util_remove_command_orb_pool(struct scsi_id_instance_data *scsi_id)
474 {
475         struct hpsb_host *host = scsi_id->hi->host;
476         struct list_head *lh, *next;
477         struct sbp2_command_info *command;
478         unsigned long flags;
479
480         spin_lock_irqsave(&scsi_id->sbp2_command_orb_lock, flags);
481         if (!list_empty(&scsi_id->sbp2_command_orb_completed)) {
482                 list_for_each_safe(lh, next, &scsi_id->sbp2_command_orb_completed) {
483                         command = list_entry(lh, struct sbp2_command_info, list);
484
485                         /* Release our generic DMA's */
486                         pci_unmap_single(host->pdev, command->command_orb_dma,
487                                          sizeof(struct sbp2_command_orb),
488                                          PCI_DMA_BIDIRECTIONAL);
489                         SBP2_DMA_FREE("single command orb DMA");
490                         pci_unmap_single(host->pdev, command->sge_dma,
491                                          sizeof(command->scatter_gather_element),
492                                          PCI_DMA_BIDIRECTIONAL);
493                         SBP2_DMA_FREE("scatter_gather_element");
494
495                         kfree(command);
496                 }
497         }
498         spin_unlock_irqrestore(&scsi_id->sbp2_command_orb_lock, flags);
499         return;
500 }
501
502 /*
503  * This function finds the sbp2_command for a given outstanding command
504  * orb.Only looks at the inuse list.
505  */
506 static struct sbp2_command_info *sbp2util_find_command_for_orb(
507                 struct scsi_id_instance_data *scsi_id, dma_addr_t orb)
508 {
509         struct sbp2_command_info *command;
510         unsigned long flags;
511
512         spin_lock_irqsave(&scsi_id->sbp2_command_orb_lock, flags);
513         if (!list_empty(&scsi_id->sbp2_command_orb_inuse)) {
514                 list_for_each_entry(command, &scsi_id->sbp2_command_orb_inuse, list) {
515                         if (command->command_orb_dma == orb) {
516                                 spin_unlock_irqrestore(&scsi_id->sbp2_command_orb_lock, flags);
517                                 return command;
518                         }
519                 }
520         }
521         spin_unlock_irqrestore(&scsi_id->sbp2_command_orb_lock, flags);
522
523         SBP2_ORB_DEBUG("could not match command orb %x", (unsigned int)orb);
524
525         return NULL;
526 }
527
528 /*
529  * This function finds the sbp2_command for a given outstanding SCpnt.
530  * Only looks at the inuse list.
531  * Must be called with scsi_id->sbp2_command_orb_lock held.
532  */
533 static struct sbp2_command_info *sbp2util_find_command_for_SCpnt(
534                 struct scsi_id_instance_data *scsi_id, void *SCpnt)
535 {
536         struct sbp2_command_info *command;
537
538         if (!list_empty(&scsi_id->sbp2_command_orb_inuse))
539                 list_for_each_entry(command, &scsi_id->sbp2_command_orb_inuse, list)
540                         if (command->Current_SCpnt == SCpnt)
541                                 return command;
542         return NULL;
543 }
544
545 /*
546  * This function allocates a command orb used to send a scsi command.
547  */
548 static struct sbp2_command_info *sbp2util_allocate_command_orb(
549                 struct scsi_id_instance_data *scsi_id,
550                 struct scsi_cmnd *Current_SCpnt,
551                 void (*Current_done)(struct scsi_cmnd *))
552 {
553         struct list_head *lh;
554         struct sbp2_command_info *command = NULL;
555         unsigned long flags;
556
557         spin_lock_irqsave(&scsi_id->sbp2_command_orb_lock, flags);
558         if (!list_empty(&scsi_id->sbp2_command_orb_completed)) {
559                 lh = scsi_id->sbp2_command_orb_completed.next;
560                 list_del(lh);
561                 command = list_entry(lh, struct sbp2_command_info, list);
562                 command->Current_done = Current_done;
563                 command->Current_SCpnt = Current_SCpnt;
564                 list_add_tail(&command->list, &scsi_id->sbp2_command_orb_inuse);
565         } else {
566                 SBP2_ERR("%s: no orbs available", __FUNCTION__);
567         }
568         spin_unlock_irqrestore(&scsi_id->sbp2_command_orb_lock, flags);
569         return command;
570 }
571
572 /* Free our DMA's */
573 static void sbp2util_free_command_dma(struct sbp2_command_info *command)
574 {
575         struct scsi_id_instance_data *scsi_id =
576                 (struct scsi_id_instance_data *)command->Current_SCpnt->device->host->hostdata[0];
577         struct hpsb_host *host;
578
579         if (!scsi_id) {
580                 SBP2_ERR("%s: scsi_id == NULL", __FUNCTION__);
581                 return;
582         }
583
584         host = scsi_id->ud->ne->host;
585
586         if (command->cmd_dma) {
587                 if (command->dma_type == CMD_DMA_SINGLE) {
588                         pci_unmap_single(host->pdev, command->cmd_dma,
589                                          command->dma_size, command->dma_dir);
590                         SBP2_DMA_FREE("single bulk");
591                 } else if (command->dma_type == CMD_DMA_PAGE) {
592                         pci_unmap_page(host->pdev, command->cmd_dma,
593                                        command->dma_size, command->dma_dir);
594                         SBP2_DMA_FREE("single page");
595                 } /* XXX: Check for CMD_DMA_NONE bug */
596                 command->dma_type = CMD_DMA_NONE;
597                 command->cmd_dma = 0;
598         }
599
600         if (command->sge_buffer) {
601                 pci_unmap_sg(host->pdev, command->sge_buffer,
602                              command->dma_size, command->dma_dir);
603                 SBP2_DMA_FREE("scatter list");
604                 command->sge_buffer = NULL;
605         }
606 }
607
608 /*
609  * This function moves a command to the completed orb list.
610  * Must be called with scsi_id->sbp2_command_orb_lock held.
611  */
612 static void sbp2util_mark_command_completed(
613                 struct scsi_id_instance_data *scsi_id,
614                 struct sbp2_command_info *command)
615 {
616         list_del(&command->list);
617         sbp2util_free_command_dma(command);
618         list_add_tail(&command->list, &scsi_id->sbp2_command_orb_completed);
619 }
620
621 /*
622  * Is scsi_id valid? Is the 1394 node still present?
623  */
624 static inline int sbp2util_node_is_available(struct scsi_id_instance_data *scsi_id)
625 {
626         return scsi_id && scsi_id->ne && !scsi_id->ne->in_limbo;
627 }
628
629 /*********************************************
630  * IEEE-1394 core driver stack related section
631  *********************************************/
632 static struct scsi_id_instance_data *sbp2_alloc_device(struct unit_directory *ud);
633
634 static int sbp2_probe(struct device *dev)
635 {
636         struct unit_directory *ud;
637         struct scsi_id_instance_data *scsi_id;
638
639         SBP2_DEBUG_ENTER();
640
641         ud = container_of(dev, struct unit_directory, device);
642
643         /* Don't probe UD's that have the LUN flag. We'll probe the LUN(s)
644          * instead. */
645         if (ud->flags & UNIT_DIRECTORY_HAS_LUN_DIRECTORY)
646                 return -ENODEV;
647
648         scsi_id = sbp2_alloc_device(ud);
649
650         if (!scsi_id)
651                 return -ENOMEM;
652
653         sbp2_parse_unit_directory(scsi_id, ud);
654
655         return sbp2_start_device(scsi_id);
656 }
657
658 static int sbp2_remove(struct device *dev)
659 {
660         struct unit_directory *ud;
661         struct scsi_id_instance_data *scsi_id;
662         struct scsi_device *sdev;
663
664         SBP2_DEBUG_ENTER();
665
666         ud = container_of(dev, struct unit_directory, device);
667         scsi_id = ud->device.driver_data;
668         if (!scsi_id)
669                 return 0;
670
671         if (scsi_id->scsi_host) {
672                 /* Get rid of enqueued commands if there is no chance to
673                  * send them. */
674                 if (!sbp2util_node_is_available(scsi_id))
675                         sbp2scsi_complete_all_commands(scsi_id, DID_NO_CONNECT);
676                 /* scsi_remove_device() will trigger shutdown functions of SCSI
677                  * highlevel drivers which would deadlock if blocked. */
678                 scsi_unblock_requests(scsi_id->scsi_host);
679         }
680         sdev = scsi_id->sdev;
681         if (sdev) {
682                 scsi_id->sdev = NULL;
683                 scsi_remove_device(sdev);
684         }
685
686         sbp2_logout_device(scsi_id);
687         sbp2_remove_device(scsi_id);
688
689         return 0;
690 }
691
692 static int sbp2_update(struct unit_directory *ud)
693 {
694         struct scsi_id_instance_data *scsi_id = ud->device.driver_data;
695
696         SBP2_DEBUG_ENTER();
697
698         if (sbp2_reconnect_device(scsi_id)) {
699
700                 /*
701                  * Ok, reconnect has failed. Perhaps we didn't
702                  * reconnect fast enough. Try doing a regular login, but
703                  * first do a logout just in case of any weirdness.
704                  */
705                 sbp2_logout_device(scsi_id);
706
707                 if (sbp2_login_device(scsi_id)) {
708                         /* Login failed too, just fail, and the backend
709                          * will call our sbp2_remove for us */
710                         SBP2_ERR("Failed to reconnect to sbp2 device!");
711                         return -EBUSY;
712                 }
713         }
714
715         /* Set max retries to something large on the device. */
716         sbp2_set_busy_timeout(scsi_id);
717
718         /* Do a SBP-2 fetch agent reset. */
719         sbp2_agent_reset(scsi_id, 1);
720
721         /* Get the max speed and packet size that we can use. */
722         sbp2_max_speed_and_size(scsi_id);
723
724         /* Complete any pending commands with busy (so they get
725          * retried) and remove them from our queue
726          */
727         sbp2scsi_complete_all_commands(scsi_id, DID_BUS_BUSY);
728
729         /* Make sure we unblock requests (since this is likely after a bus
730          * reset). */
731         scsi_unblock_requests(scsi_id->scsi_host);
732
733         return 0;
734 }
735
736 /* This functions is called by the sbp2_probe, for each new device. We now
737  * allocate one scsi host for each scsi_id (unit directory). */
738 static struct scsi_id_instance_data *sbp2_alloc_device(struct unit_directory *ud)
739 {
740         struct sbp2scsi_host_info *hi;
741         struct Scsi_Host *scsi_host = NULL;
742         struct scsi_id_instance_data *scsi_id = NULL;
743
744         SBP2_DEBUG_ENTER();
745
746         scsi_id = kzalloc(sizeof(*scsi_id), GFP_KERNEL);
747         if (!scsi_id) {
748                 SBP2_ERR("failed to create scsi_id");
749                 goto failed_alloc;
750         }
751
752         scsi_id->ne = ud->ne;
753         scsi_id->ud = ud;
754         scsi_id->speed_code = IEEE1394_SPEED_100;
755         scsi_id->max_payload_size = sbp2_speedto_max_payload[IEEE1394_SPEED_100];
756         atomic_set(&scsi_id->sbp2_login_complete, 0);
757         INIT_LIST_HEAD(&scsi_id->sbp2_command_orb_inuse);
758         INIT_LIST_HEAD(&scsi_id->sbp2_command_orb_completed);
759         INIT_LIST_HEAD(&scsi_id->scsi_list);
760         spin_lock_init(&scsi_id->sbp2_command_orb_lock);
761         scsi_id->sbp2_lun = 0;
762
763         ud->device.driver_data = scsi_id;
764
765         hi = hpsb_get_hostinfo(&sbp2_highlevel, ud->ne->host);
766         if (!hi) {
767                 hi = hpsb_create_hostinfo(&sbp2_highlevel, ud->ne->host, sizeof(*hi));
768                 if (!hi) {
769                         SBP2_ERR("failed to allocate hostinfo");
770                         goto failed_alloc;
771                 }
772                 SBP2_DEBUG("sbp2_alloc_device: allocated hostinfo");
773                 hi->host = ud->ne->host;
774                 INIT_LIST_HEAD(&hi->scsi_ids);
775
776 #ifdef CONFIG_IEEE1394_SBP2_PHYS_DMA
777                 /* Handle data movement if physical dma is not
778                  * enabled or not supported on host controller */
779                 if (!hpsb_register_addrspace(&sbp2_highlevel, ud->ne->host,
780                                              &sbp2_physdma_ops,
781                                              0x0ULL, 0xfffffffcULL)) {
782                         SBP2_ERR("failed to register lower 4GB address range");
783                         goto failed_alloc;
784                 }
785 #endif
786         }
787
788         /* Prevent unloading of the 1394 host */
789         if (!try_module_get(hi->host->driver->owner)) {
790                 SBP2_ERR("failed to get a reference on 1394 host driver");
791                 goto failed_alloc;
792         }
793
794         scsi_id->hi = hi;
795
796         list_add_tail(&scsi_id->scsi_list, &hi->scsi_ids);
797
798         /* Register the status FIFO address range. We could use the same FIFO
799          * for targets at different nodes. However we need different FIFOs per
800          * target in order to support multi-unit devices. */
801         scsi_id->status_fifo_addr = hpsb_allocate_and_register_addrspace(
802                         &sbp2_highlevel, ud->ne->host, &sbp2_ops,
803                         sizeof(struct sbp2_status_block), sizeof(quadlet_t),
804                         ~0ULL, ~0ULL);
805         if (!scsi_id->status_fifo_addr) {
806                 SBP2_ERR("failed to allocate status FIFO address range");
807                 goto failed_alloc;
808         }
809
810         /* Register our host with the SCSI stack. */
811         scsi_host = scsi_host_alloc(&scsi_driver_template,
812                                     sizeof(unsigned long));
813         if (!scsi_host) {
814                 SBP2_ERR("failed to register scsi host");
815                 goto failed_alloc;
816         }
817
818         scsi_host->hostdata[0] = (unsigned long)scsi_id;
819
820         if (!scsi_add_host(scsi_host, &ud->device)) {
821                 scsi_id->scsi_host = scsi_host;
822                 return scsi_id;
823         }
824
825         SBP2_ERR("failed to add scsi host");
826         scsi_host_put(scsi_host);
827
828 failed_alloc:
829         sbp2_remove_device(scsi_id);
830         return NULL;
831 }
832
833 static void sbp2_host_reset(struct hpsb_host *host)
834 {
835         struct sbp2scsi_host_info *hi;
836         struct scsi_id_instance_data *scsi_id;
837
838         hi = hpsb_get_hostinfo(&sbp2_highlevel, host);
839
840         if (hi) {
841                 list_for_each_entry(scsi_id, &hi->scsi_ids, scsi_list)
842                         scsi_block_requests(scsi_id->scsi_host);
843         }
844 }
845
846 /*
847  * This function is where we first pull the node unique ids, and then
848  * allocate memory and register a SBP-2 device.
849  */
850 static int sbp2_start_device(struct scsi_id_instance_data *scsi_id)
851 {
852         struct sbp2scsi_host_info *hi = scsi_id->hi;
853         int error;
854
855         SBP2_DEBUG_ENTER();
856
857         /* Login FIFO DMA */
858         scsi_id->login_response =
859                 pci_alloc_consistent(hi->host->pdev,
860                                      sizeof(struct sbp2_login_response),
861                                      &scsi_id->login_response_dma);
862         if (!scsi_id->login_response)
863                 goto alloc_fail;
864         SBP2_DMA_ALLOC("consistent DMA region for login FIFO");
865
866         /* Query logins ORB DMA */
867         scsi_id->query_logins_orb =
868                 pci_alloc_consistent(hi->host->pdev,
869                                      sizeof(struct sbp2_query_logins_orb),
870                                      &scsi_id->query_logins_orb_dma);
871         if (!scsi_id->query_logins_orb)
872                 goto alloc_fail;
873         SBP2_DMA_ALLOC("consistent DMA region for query logins ORB");
874
875         /* Query logins response DMA */
876         scsi_id->query_logins_response =
877                 pci_alloc_consistent(hi->host->pdev,
878                                      sizeof(struct sbp2_query_logins_response),
879                                      &scsi_id->query_logins_response_dma);
880         if (!scsi_id->query_logins_response)
881                 goto alloc_fail;
882         SBP2_DMA_ALLOC("consistent DMA region for query logins response");
883
884         /* Reconnect ORB DMA */
885         scsi_id->reconnect_orb =
886                 pci_alloc_consistent(hi->host->pdev,
887                                      sizeof(struct sbp2_reconnect_orb),
888                                      &scsi_id->reconnect_orb_dma);
889         if (!scsi_id->reconnect_orb)
890                 goto alloc_fail;
891         SBP2_DMA_ALLOC("consistent DMA region for reconnect ORB");
892
893         /* Logout ORB DMA */
894         scsi_id->logout_orb =
895                 pci_alloc_consistent(hi->host->pdev,
896                                      sizeof(struct sbp2_logout_orb),
897                                      &scsi_id->logout_orb_dma);
898         if (!scsi_id->logout_orb)
899                 goto alloc_fail;
900         SBP2_DMA_ALLOC("consistent DMA region for logout ORB");
901
902         /* Login ORB DMA */
903         scsi_id->login_orb =
904                 pci_alloc_consistent(hi->host->pdev,
905                                      sizeof(struct sbp2_login_orb),
906                                      &scsi_id->login_orb_dma);
907         if (!scsi_id->login_orb)
908                 goto alloc_fail;
909         SBP2_DMA_ALLOC("consistent DMA region for login ORB");
910
911         SBP2_DEBUG("New SBP-2 device inserted, SCSI ID = %x", scsi_id->ud->id);
912
913         /*
914          * Create our command orb pool
915          */
916         if (sbp2util_create_command_orb_pool(scsi_id)) {
917                 SBP2_ERR("sbp2util_create_command_orb_pool failed!");
918                 sbp2_remove_device(scsi_id);
919                 return -ENOMEM;
920         }
921
922         /* Schedule a timeout here. The reason is that we may be so close
923          * to a bus reset, that the device is not available for logins.
924          * This can happen when the bus reset is caused by the host
925          * connected to the sbp2 device being removed. That host would
926          * have a certain amount of time to relogin before the sbp2 device
927          * allows someone else to login instead. One second makes sense. */
928         msleep_interruptible(1000);
929         if (signal_pending(current)) {
930                 sbp2_remove_device(scsi_id);
931                 return -EINTR;
932         }
933
934         /*
935          * Login to the sbp-2 device
936          */
937         if (sbp2_login_device(scsi_id)) {
938                 /* Login failed, just remove the device. */
939                 sbp2_remove_device(scsi_id);
940                 return -EBUSY;
941         }
942
943         /*
944          * Set max retries to something large on the device
945          */
946         sbp2_set_busy_timeout(scsi_id);
947
948         /*
949          * Do a SBP-2 fetch agent reset
950          */
951         sbp2_agent_reset(scsi_id, 1);
952
953         /*
954          * Get the max speed and packet size that we can use
955          */
956         sbp2_max_speed_and_size(scsi_id);
957
958         /* Add this device to the scsi layer now */
959         error = scsi_add_device(scsi_id->scsi_host, 0, scsi_id->ud->id, 0);
960         if (error) {
961                 SBP2_ERR("scsi_add_device failed");
962                 sbp2_logout_device(scsi_id);
963                 sbp2_remove_device(scsi_id);
964                 return error;
965         }
966
967         return 0;
968
969 alloc_fail:
970         SBP2_ERR("Could not allocate memory for scsi_id");
971         sbp2_remove_device(scsi_id);
972         return -ENOMEM;
973 }
974
975 /*
976  * This function removes an sbp2 device from the sbp2scsi_host_info struct.
977  */
978 static void sbp2_remove_device(struct scsi_id_instance_data *scsi_id)
979 {
980         struct sbp2scsi_host_info *hi;
981
982         SBP2_DEBUG_ENTER();
983
984         if (!scsi_id)
985                 return;
986
987         hi = scsi_id->hi;
988
989         /* This will remove our scsi device aswell */
990         if (scsi_id->scsi_host) {
991                 scsi_remove_host(scsi_id->scsi_host);
992                 scsi_host_put(scsi_id->scsi_host);
993         }
994
995         sbp2util_remove_command_orb_pool(scsi_id);
996
997         list_del(&scsi_id->scsi_list);
998
999         if (scsi_id->login_response) {
1000                 pci_free_consistent(hi->host->pdev,
1001                                     sizeof(struct sbp2_login_response),
1002                                     scsi_id->login_response,
1003                                     scsi_id->login_response_dma);
1004                 SBP2_DMA_FREE("single login FIFO");
1005         }
1006
1007         if (scsi_id->login_orb) {
1008                 pci_free_consistent(hi->host->pdev,
1009                                     sizeof(struct sbp2_login_orb),
1010                                     scsi_id->login_orb,
1011                                     scsi_id->login_orb_dma);
1012                 SBP2_DMA_FREE("single login ORB");
1013         }
1014
1015         if (scsi_id->reconnect_orb) {
1016                 pci_free_consistent(hi->host->pdev,
1017                                     sizeof(struct sbp2_reconnect_orb),
1018                                     scsi_id->reconnect_orb,
1019                                     scsi_id->reconnect_orb_dma);
1020                 SBP2_DMA_FREE("single reconnect orb");
1021         }
1022
1023         if (scsi_id->logout_orb) {
1024                 pci_free_consistent(hi->host->pdev,
1025                                     sizeof(struct sbp2_logout_orb),
1026                                     scsi_id->logout_orb,
1027                                     scsi_id->logout_orb_dma);
1028                 SBP2_DMA_FREE("single logout orb");
1029         }
1030
1031         if (scsi_id->query_logins_orb) {
1032                 pci_free_consistent(hi->host->pdev,
1033                                     sizeof(struct sbp2_query_logins_orb),
1034                                     scsi_id->query_logins_orb,
1035                                     scsi_id->query_logins_orb_dma);
1036                 SBP2_DMA_FREE("single query logins orb");
1037         }
1038
1039         if (scsi_id->query_logins_response) {
1040                 pci_free_consistent(hi->host->pdev,
1041                                     sizeof(struct sbp2_query_logins_response),
1042                                     scsi_id->query_logins_response,
1043                                     scsi_id->query_logins_response_dma);
1044                 SBP2_DMA_FREE("single query logins data");
1045         }
1046
1047         if (scsi_id->status_fifo_addr)
1048                 hpsb_unregister_addrspace(&sbp2_highlevel, hi->host,
1049                         scsi_id->status_fifo_addr);
1050
1051         scsi_id->ud->device.driver_data = NULL;
1052
1053         if (hi)
1054                 module_put(hi->host->driver->owner);
1055
1056         SBP2_DEBUG("SBP-2 device removed, SCSI ID = %d", scsi_id->ud->id);
1057
1058         kfree(scsi_id);
1059 }
1060
1061 #ifdef CONFIG_IEEE1394_SBP2_PHYS_DMA
1062 /*
1063  * This function deals with physical dma write requests (for adapters that do not support
1064  * physical dma in hardware). Mostly just here for debugging...
1065  */
1066 static int sbp2_handle_physdma_write(struct hpsb_host *host, int nodeid,
1067                                      int destid, quadlet_t *data, u64 addr,
1068                                      size_t length, u16 flags)
1069 {
1070
1071         /*
1072          * Manually put the data in the right place.
1073          */
1074         memcpy(bus_to_virt((u32) addr), data, length);
1075         sbp2util_packet_dump(data, length, "sbp2 phys dma write by device",
1076                              (u32) addr);
1077         return RCODE_COMPLETE;
1078 }
1079
1080 /*
1081  * This function deals with physical dma read requests (for adapters that do not support
1082  * physical dma in hardware). Mostly just here for debugging...
1083  */
1084 static int sbp2_handle_physdma_read(struct hpsb_host *host, int nodeid,
1085                                     quadlet_t *data, u64 addr, size_t length,
1086                                     u16 flags)
1087 {
1088
1089         /*
1090          * Grab data from memory and send a read response.
1091          */
1092         memcpy(data, bus_to_virt((u32) addr), length);
1093         sbp2util_packet_dump(data, length, "sbp2 phys dma read by device",
1094                              (u32) addr);
1095         return RCODE_COMPLETE;
1096 }
1097 #endif
1098
1099 /**************************************
1100  * SBP-2 protocol related section
1101  **************************************/
1102
1103 /*
1104  * This function queries the device for the maximum concurrent logins it
1105  * supports.
1106  */
1107 static int sbp2_query_logins(struct scsi_id_instance_data *scsi_id)
1108 {
1109         struct sbp2scsi_host_info *hi = scsi_id->hi;
1110         quadlet_t data[2];
1111         int max_logins;
1112         int active_logins;
1113
1114         SBP2_DEBUG_ENTER();
1115
1116         scsi_id->query_logins_orb->reserved1 = 0x0;
1117         scsi_id->query_logins_orb->reserved2 = 0x0;
1118
1119         scsi_id->query_logins_orb->query_response_lo = scsi_id->query_logins_response_dma;
1120         scsi_id->query_logins_orb->query_response_hi = ORB_SET_NODE_ID(hi->host->node_id);
1121
1122         scsi_id->query_logins_orb->lun_misc = ORB_SET_FUNCTION(SBP2_QUERY_LOGINS_REQUEST);
1123         scsi_id->query_logins_orb->lun_misc |= ORB_SET_NOTIFY(1);
1124         scsi_id->query_logins_orb->lun_misc |= ORB_SET_LUN(scsi_id->sbp2_lun);
1125
1126         scsi_id->query_logins_orb->reserved_resp_length =
1127                 ORB_SET_QUERY_LOGINS_RESP_LENGTH(sizeof(struct sbp2_query_logins_response));
1128
1129         scsi_id->query_logins_orb->status_fifo_hi =
1130                 ORB_SET_STATUS_FIFO_HI(scsi_id->status_fifo_addr, hi->host->node_id);
1131         scsi_id->query_logins_orb->status_fifo_lo =
1132                 ORB_SET_STATUS_FIFO_LO(scsi_id->status_fifo_addr);
1133
1134         sbp2util_cpu_to_be32_buffer(scsi_id->query_logins_orb, sizeof(struct sbp2_query_logins_orb));
1135
1136         sbp2util_packet_dump(scsi_id->query_logins_orb, sizeof(struct sbp2_query_logins_orb),
1137                              "sbp2 query logins orb", scsi_id->query_logins_orb_dma);
1138
1139         memset(scsi_id->query_logins_response, 0, sizeof(struct sbp2_query_logins_response));
1140         memset(&scsi_id->status_block, 0, sizeof(struct sbp2_status_block));
1141
1142         data[0] = ORB_SET_NODE_ID(hi->host->node_id);
1143         data[1] = scsi_id->query_logins_orb_dma;
1144         sbp2util_cpu_to_be32_buffer(data, 8);
1145
1146         atomic_set(&scsi_id->sbp2_login_complete, 0);
1147
1148         hpsb_node_write(scsi_id->ne, scsi_id->sbp2_management_agent_addr, data, 8);
1149
1150         if (sbp2util_down_timeout(&scsi_id->sbp2_login_complete, 2*HZ)) {
1151                 SBP2_INFO("Error querying logins to SBP-2 device - timed out");
1152                 return -EIO;
1153         }
1154
1155         if (scsi_id->status_block.ORB_offset_lo != scsi_id->query_logins_orb_dma) {
1156                 SBP2_INFO("Error querying logins to SBP-2 device - timed out");
1157                 return -EIO;
1158         }
1159
1160         if (STATUS_GET_RESP(scsi_id->status_block.ORB_offset_hi_misc) ||
1161             STATUS_GET_DEAD_BIT(scsi_id->status_block.ORB_offset_hi_misc) ||
1162             STATUS_GET_SBP_STATUS(scsi_id->status_block.ORB_offset_hi_misc)) {
1163
1164                 SBP2_INFO("Error querying logins to SBP-2 device - timed out");
1165                 return -EIO;
1166         }
1167
1168         sbp2util_cpu_to_be32_buffer(scsi_id->query_logins_response, sizeof(struct sbp2_query_logins_response));
1169
1170         SBP2_DEBUG("length_max_logins = %x",
1171                    (unsigned int)scsi_id->query_logins_response->length_max_logins);
1172
1173         SBP2_DEBUG("Query logins to SBP-2 device successful");
1174
1175         max_logins = RESPONSE_GET_MAX_LOGINS(scsi_id->query_logins_response->length_max_logins);
1176         SBP2_DEBUG("Maximum concurrent logins supported: %d", max_logins);
1177
1178         active_logins = RESPONSE_GET_ACTIVE_LOGINS(scsi_id->query_logins_response->length_max_logins);
1179         SBP2_DEBUG("Number of active logins: %d", active_logins);
1180
1181         if (active_logins >= max_logins) {
1182                 return -EIO;
1183         }
1184
1185         return 0;
1186 }
1187
1188 /*
1189  * This function is called in order to login to a particular SBP-2 device,
1190  * after a bus reset.
1191  */
1192 static int sbp2_login_device(struct scsi_id_instance_data *scsi_id)
1193 {
1194         struct sbp2scsi_host_info *hi = scsi_id->hi;
1195         quadlet_t data[2];
1196
1197         SBP2_DEBUG_ENTER();
1198
1199         if (!scsi_id->login_orb) {
1200                 SBP2_DEBUG("%s: login_orb not alloc'd!", __FUNCTION__);
1201                 return -EIO;
1202         }
1203
1204         if (!exclusive_login) {
1205                 if (sbp2_query_logins(scsi_id)) {
1206                         SBP2_INFO("Device does not support any more concurrent logins");
1207                         return -EIO;
1208                 }
1209         }
1210
1211         /* Set-up login ORB, assume no password */
1212         scsi_id->login_orb->password_hi = 0;
1213         scsi_id->login_orb->password_lo = 0;
1214
1215         scsi_id->login_orb->login_response_lo = scsi_id->login_response_dma;
1216         scsi_id->login_orb->login_response_hi = ORB_SET_NODE_ID(hi->host->node_id);
1217
1218         scsi_id->login_orb->lun_misc = ORB_SET_FUNCTION(SBP2_LOGIN_REQUEST);
1219         scsi_id->login_orb->lun_misc |= ORB_SET_RECONNECT(0);   /* One second reconnect time */
1220         scsi_id->login_orb->lun_misc |= ORB_SET_EXCLUSIVE(exclusive_login);     /* Exclusive access to device */
1221         scsi_id->login_orb->lun_misc |= ORB_SET_NOTIFY(1);      /* Notify us of login complete */
1222         scsi_id->login_orb->lun_misc |= ORB_SET_LUN(scsi_id->sbp2_lun);
1223
1224         scsi_id->login_orb->passwd_resp_lengths =
1225                 ORB_SET_LOGIN_RESP_LENGTH(sizeof(struct sbp2_login_response));
1226
1227         scsi_id->login_orb->status_fifo_hi =
1228                 ORB_SET_STATUS_FIFO_HI(scsi_id->status_fifo_addr, hi->host->node_id);
1229         scsi_id->login_orb->status_fifo_lo =
1230                 ORB_SET_STATUS_FIFO_LO(scsi_id->status_fifo_addr);
1231
1232         sbp2util_cpu_to_be32_buffer(scsi_id->login_orb, sizeof(struct sbp2_login_orb));
1233
1234         sbp2util_packet_dump(scsi_id->login_orb, sizeof(struct sbp2_login_orb),
1235                              "sbp2 login orb", scsi_id->login_orb_dma);
1236
1237         memset(scsi_id->login_response, 0, sizeof(struct sbp2_login_response));
1238         memset(&scsi_id->status_block, 0, sizeof(struct sbp2_status_block));
1239
1240         data[0] = ORB_SET_NODE_ID(hi->host->node_id);
1241         data[1] = scsi_id->login_orb_dma;
1242         sbp2util_cpu_to_be32_buffer(data, 8);
1243
1244         atomic_set(&scsi_id->sbp2_login_complete, 0);
1245
1246         hpsb_node_write(scsi_id->ne, scsi_id->sbp2_management_agent_addr, data, 8);
1247
1248         /*
1249          * Wait for login status (up to 20 seconds)...
1250          */
1251         if (sbp2util_down_timeout(&scsi_id->sbp2_login_complete, 20*HZ)) {
1252                 SBP2_ERR("Error logging into SBP-2 device - login timed-out");
1253                 return -EIO;
1254         }
1255
1256         /*
1257          * Sanity. Make sure status returned matches login orb.
1258          */
1259         if (scsi_id->status_block.ORB_offset_lo != scsi_id->login_orb_dma) {
1260                 SBP2_ERR("Error logging into SBP-2 device - login timed-out");
1261                 return -EIO;
1262         }
1263
1264         /*
1265          * Check status
1266          */
1267         if (STATUS_GET_RESP(scsi_id->status_block.ORB_offset_hi_misc) ||
1268             STATUS_GET_DEAD_BIT(scsi_id->status_block.ORB_offset_hi_misc) ||
1269             STATUS_GET_SBP_STATUS(scsi_id->status_block.ORB_offset_hi_misc)) {
1270
1271                 SBP2_ERR("Error logging into SBP-2 device - login failed");
1272                 return -EIO;
1273         }
1274
1275         /*
1276          * Byte swap the login response, for use when reconnecting or
1277          * logging out.
1278          */
1279         sbp2util_cpu_to_be32_buffer(scsi_id->login_response, sizeof(struct sbp2_login_response));
1280
1281         /*
1282          * Grab our command block agent address from the login response.
1283          */
1284         SBP2_DEBUG("command_block_agent_hi = %x",
1285                    (unsigned int)scsi_id->login_response->command_block_agent_hi);
1286         SBP2_DEBUG("command_block_agent_lo = %x",
1287                    (unsigned int)scsi_id->login_response->command_block_agent_lo);
1288
1289         scsi_id->sbp2_command_block_agent_addr =
1290                 ((u64)scsi_id->login_response->command_block_agent_hi) << 32;
1291         scsi_id->sbp2_command_block_agent_addr |= ((u64)scsi_id->login_response->command_block_agent_lo);
1292         scsi_id->sbp2_command_block_agent_addr &= 0x0000ffffffffffffULL;
1293
1294         SBP2_INFO("Logged into SBP-2 device");
1295
1296         return 0;
1297
1298 }
1299
1300 /*
1301  * This function is called in order to logout from a particular SBP-2
1302  * device, usually called during driver unload.
1303  */
1304 static int sbp2_logout_device(struct scsi_id_instance_data *scsi_id)
1305 {
1306         struct sbp2scsi_host_info *hi = scsi_id->hi;
1307         quadlet_t data[2];
1308         int error;
1309
1310         SBP2_DEBUG_ENTER();
1311
1312         /*
1313          * Set-up logout ORB
1314          */
1315         scsi_id->logout_orb->reserved1 = 0x0;
1316         scsi_id->logout_orb->reserved2 = 0x0;
1317         scsi_id->logout_orb->reserved3 = 0x0;
1318         scsi_id->logout_orb->reserved4 = 0x0;
1319
1320         scsi_id->logout_orb->login_ID_misc = ORB_SET_FUNCTION(SBP2_LOGOUT_REQUEST);
1321         scsi_id->logout_orb->login_ID_misc |= ORB_SET_LOGIN_ID(scsi_id->login_response->length_login_ID);
1322
1323         /* Notify us when complete */
1324         scsi_id->logout_orb->login_ID_misc |= ORB_SET_NOTIFY(1);
1325
1326         scsi_id->logout_orb->reserved5 = 0x0;
1327         scsi_id->logout_orb->status_fifo_hi =
1328                 ORB_SET_STATUS_FIFO_HI(scsi_id->status_fifo_addr, hi->host->node_id);
1329         scsi_id->logout_orb->status_fifo_lo =
1330                 ORB_SET_STATUS_FIFO_LO(scsi_id->status_fifo_addr);
1331
1332         /*
1333          * Byte swap ORB if necessary
1334          */
1335         sbp2util_cpu_to_be32_buffer(scsi_id->logout_orb, sizeof(struct sbp2_logout_orb));
1336
1337         sbp2util_packet_dump(scsi_id->logout_orb, sizeof(struct sbp2_logout_orb),
1338                              "sbp2 logout orb", scsi_id->logout_orb_dma);
1339
1340         /*
1341          * Ok, let's write to the target's management agent register
1342          */
1343         data[0] = ORB_SET_NODE_ID(hi->host->node_id);
1344         data[1] = scsi_id->logout_orb_dma;
1345         sbp2util_cpu_to_be32_buffer(data, 8);
1346
1347         atomic_set(&scsi_id->sbp2_login_complete, 0);
1348
1349         error = hpsb_node_write(scsi_id->ne,
1350                                 scsi_id->sbp2_management_agent_addr, data, 8);
1351         if (error)
1352                 return error;
1353
1354         /* Wait for device to logout...1 second. */
1355         if (sbp2util_down_timeout(&scsi_id->sbp2_login_complete, HZ))
1356                 return -EIO;
1357
1358         SBP2_INFO("Logged out of SBP-2 device");
1359
1360         return 0;
1361
1362 }
1363
1364 /*
1365  * This function is called in order to reconnect to a particular SBP-2
1366  * device, after a bus reset.
1367  */
1368 static int sbp2_reconnect_device(struct scsi_id_instance_data *scsi_id)
1369 {
1370         struct sbp2scsi_host_info *hi = scsi_id->hi;
1371         quadlet_t data[2];
1372         int error;
1373
1374         SBP2_DEBUG_ENTER();
1375
1376         /*
1377          * Set-up reconnect ORB
1378          */
1379         scsi_id->reconnect_orb->reserved1 = 0x0;
1380         scsi_id->reconnect_orb->reserved2 = 0x0;
1381         scsi_id->reconnect_orb->reserved3 = 0x0;
1382         scsi_id->reconnect_orb->reserved4 = 0x0;
1383
1384         scsi_id->reconnect_orb->login_ID_misc = ORB_SET_FUNCTION(SBP2_RECONNECT_REQUEST);
1385         scsi_id->reconnect_orb->login_ID_misc |=
1386                 ORB_SET_LOGIN_ID(scsi_id->login_response->length_login_ID);
1387
1388         /* Notify us when complete */
1389         scsi_id->reconnect_orb->login_ID_misc |= ORB_SET_NOTIFY(1);
1390
1391         scsi_id->reconnect_orb->reserved5 = 0x0;
1392         scsi_id->reconnect_orb->status_fifo_hi =
1393                 ORB_SET_STATUS_FIFO_HI(scsi_id->status_fifo_addr, hi->host->node_id);
1394         scsi_id->reconnect_orb->status_fifo_lo =
1395                 ORB_SET_STATUS_FIFO_LO(scsi_id->status_fifo_addr);
1396
1397         /*
1398          * Byte swap ORB if necessary
1399          */
1400         sbp2util_cpu_to_be32_buffer(scsi_id->reconnect_orb, sizeof(struct sbp2_reconnect_orb));
1401
1402         sbp2util_packet_dump(scsi_id->reconnect_orb, sizeof(struct sbp2_reconnect_orb),
1403                              "sbp2 reconnect orb", scsi_id->reconnect_orb_dma);
1404
1405         /*
1406          * Initialize status fifo
1407          */
1408         memset(&scsi_id->status_block, 0, sizeof(struct sbp2_status_block));
1409
1410         /*
1411          * Ok, let's write to the target's management agent register
1412          */
1413         data[0] = ORB_SET_NODE_ID(hi->host->node_id);
1414         data[1] = scsi_id->reconnect_orb_dma;
1415         sbp2util_cpu_to_be32_buffer(data, 8);
1416
1417         atomic_set(&scsi_id->sbp2_login_complete, 0);
1418
1419         error = hpsb_node_write(scsi_id->ne,
1420                                 scsi_id->sbp2_management_agent_addr, data, 8);
1421         if (error)
1422                 return error;
1423
1424         /*
1425          * Wait for reconnect status (up to 1 second)...
1426          */
1427         if (sbp2util_down_timeout(&scsi_id->sbp2_login_complete, HZ)) {
1428                 SBP2_ERR("Error reconnecting to SBP-2 device - reconnect timed-out");
1429                 return -EIO;
1430         }
1431
1432         /*
1433          * Sanity. Make sure status returned matches reconnect orb.
1434          */
1435         if (scsi_id->status_block.ORB_offset_lo != scsi_id->reconnect_orb_dma) {
1436                 SBP2_ERR("Error reconnecting to SBP-2 device - reconnect timed-out");
1437                 return -EIO;
1438         }
1439
1440         /*
1441          * Check status
1442          */
1443         if (STATUS_GET_RESP(scsi_id->status_block.ORB_offset_hi_misc) ||
1444             STATUS_GET_DEAD_BIT(scsi_id->status_block.ORB_offset_hi_misc) ||
1445             STATUS_GET_SBP_STATUS(scsi_id->status_block.ORB_offset_hi_misc)) {
1446
1447                 SBP2_ERR("Error reconnecting to SBP-2 device - reconnect failed");
1448                 return -EIO;
1449         }
1450
1451         HPSB_DEBUG("Reconnected to SBP-2 device");
1452
1453         return 0;
1454
1455 }
1456
1457 /*
1458  * This function is called in order to set the busy timeout (number of
1459  * retries to attempt) on the sbp2 device.
1460  */
1461 static int sbp2_set_busy_timeout(struct scsi_id_instance_data *scsi_id)
1462 {
1463         quadlet_t data;
1464
1465         SBP2_DEBUG_ENTER();
1466
1467         data = cpu_to_be32(SBP2_BUSY_TIMEOUT_VALUE);
1468         if (hpsb_node_write(scsi_id->ne, SBP2_BUSY_TIMEOUT_ADDRESS, &data, 4))
1469                 SBP2_ERR("%s error", __FUNCTION__);
1470         return 0;
1471 }
1472
1473 /*
1474  * This function is called to parse sbp2 device's config rom unit
1475  * directory. Used to determine things like sbp2 management agent offset,
1476  * and command set used (SCSI or RBC).
1477  */
1478 static void sbp2_parse_unit_directory(struct scsi_id_instance_data *scsi_id,
1479                                       struct unit_directory *ud)
1480 {
1481         struct csr1212_keyval *kv;
1482         struct csr1212_dentry *dentry;
1483         u64 management_agent_addr;
1484         u32 command_set_spec_id, command_set, unit_characteristics,
1485             firmware_revision;
1486         unsigned workarounds;
1487         int i;
1488
1489         SBP2_DEBUG_ENTER();
1490
1491         management_agent_addr = 0x0;
1492         command_set_spec_id = 0x0;
1493         command_set = 0x0;
1494         unit_characteristics = 0x0;
1495         firmware_revision = 0x0;
1496
1497         /* Handle different fields in the unit directory, based on keys */
1498         csr1212_for_each_dir_entry(ud->ne->csr, kv, ud->ud_kv, dentry) {
1499                 switch (kv->key.id) {
1500                 case CSR1212_KV_ID_DEPENDENT_INFO:
1501                         if (kv->key.type == CSR1212_KV_TYPE_CSR_OFFSET) {
1502                                 /* Save off the management agent address */
1503                                 management_agent_addr =
1504                                     CSR1212_REGISTER_SPACE_BASE +
1505                                     (kv->value.csr_offset << 2);
1506
1507                                 SBP2_DEBUG("sbp2_management_agent_addr = %x",
1508                                            (unsigned int)management_agent_addr);
1509                         } else if (kv->key.type == CSR1212_KV_TYPE_IMMEDIATE) {
1510                                 scsi_id->sbp2_lun =
1511                                     ORB_SET_LUN(kv->value.immediate);
1512                         }
1513                         break;
1514
1515                 case SBP2_COMMAND_SET_SPEC_ID_KEY:
1516                         /* Command spec organization */
1517                         command_set_spec_id = kv->value.immediate;
1518                         SBP2_DEBUG("sbp2_command_set_spec_id = %x",
1519                                    (unsigned int)command_set_spec_id);
1520                         break;
1521
1522                 case SBP2_COMMAND_SET_KEY:
1523                         /* Command set used by sbp2 device */
1524                         command_set = kv->value.immediate;
1525                         SBP2_DEBUG("sbp2_command_set = %x",
1526                                    (unsigned int)command_set);
1527                         break;
1528
1529                 case SBP2_UNIT_CHARACTERISTICS_KEY:
1530                         /*
1531                          * Unit characterisitcs (orb related stuff
1532                          * that I'm not yet paying attention to)
1533                          */
1534                         unit_characteristics = kv->value.immediate;
1535                         SBP2_DEBUG("sbp2_unit_characteristics = %x",
1536                                    (unsigned int)unit_characteristics);
1537                         break;
1538
1539                 case SBP2_FIRMWARE_REVISION_KEY:
1540                         /* Firmware revision */
1541                         firmware_revision = kv->value.immediate;
1542                         SBP2_DEBUG("sbp2_firmware_revision = %x",
1543                                    (unsigned int)firmware_revision);
1544                         break;
1545
1546                 default:
1547                         break;
1548                 }
1549         }
1550
1551         workarounds = sbp2_default_workarounds;
1552         if (force_inquiry_hack) {
1553                 SBP2_WARN("force_inquiry_hack is deprecated. "
1554                           "Use parameter 'workarounds' instead.");
1555                 workarounds |= SBP2_WORKAROUND_INQUIRY_36;
1556         }
1557
1558         for (i = 0; i < ARRAY_SIZE(sbp2_workarounds_table); i++) {
1559                 if (sbp2_workarounds_table[i].firmware_revision !=
1560                     (firmware_revision & 0xffff00))
1561                         continue;
1562                 workarounds |= sbp2_workarounds_table[i].workarounds;
1563                 break;
1564         }
1565
1566         if (workarounds)
1567                 SBP2_INFO("Workarounds for node " NODE_BUS_FMT ": "
1568                           "0x%x (firmware_revision 0x%x)",
1569                           NODE_BUS_ARGS(ud->ne->host, ud->ne->nodeid),
1570                           workarounds, firmware_revision);
1571
1572         /* We would need one SCSI host template for each target to adjust
1573          * max_sectors on the fly, therefore warn only. */
1574         if (workarounds & SBP2_WORKAROUND_128K_MAX_TRANS &&
1575             (max_sectors * 512) > (128 * 1024))
1576                 SBP2_WARN("Node " NODE_BUS_FMT ": Bridge only supports 128KB "
1577                           "max transfer size. WARNING: Current max_sectors "
1578                           "setting is larger than 128KB (%d sectors)",
1579                           NODE_BUS_ARGS(ud->ne->host, ud->ne->nodeid),
1580                           max_sectors);
1581
1582         /* If this is a logical unit directory entry, process the parent
1583          * to get the values. */
1584         if (ud->flags & UNIT_DIRECTORY_LUN_DIRECTORY) {
1585                 struct unit_directory *parent_ud =
1586                         container_of(ud->device.parent, struct unit_directory, device);
1587                 sbp2_parse_unit_directory(scsi_id, parent_ud);
1588         } else {
1589                 scsi_id->sbp2_management_agent_addr = management_agent_addr;
1590                 scsi_id->sbp2_command_set_spec_id = command_set_spec_id;
1591                 scsi_id->sbp2_command_set = command_set;
1592                 scsi_id->sbp2_unit_characteristics = unit_characteristics;
1593                 scsi_id->sbp2_firmware_revision = firmware_revision;
1594                 scsi_id->workarounds = workarounds;
1595                 if (ud->flags & UNIT_DIRECTORY_HAS_LUN)
1596                         scsi_id->sbp2_lun = ORB_SET_LUN(ud->lun);
1597         }
1598 }
1599
1600 /*
1601  * This function is called in order to determine the max speed and packet
1602  * size we can use in our ORBs. Note, that we (the driver and host) only
1603  * initiate the transaction. The SBP-2 device actually transfers the data
1604  * (by reading from the DMA area we tell it). This means that the SBP-2
1605  * device decides the actual maximum data it can transfer. We just tell it
1606  * the speed that it needs to use, and the max_rec the host supports, and
1607  * it takes care of the rest.
1608  */
1609 static int sbp2_max_speed_and_size(struct scsi_id_instance_data *scsi_id)
1610 {
1611         struct sbp2scsi_host_info *hi = scsi_id->hi;
1612
1613         SBP2_DEBUG_ENTER();
1614
1615         /* Initial setting comes from the hosts speed map */
1616         scsi_id->speed_code =
1617             hi->host->speed_map[NODEID_TO_NODE(hi->host->node_id) * 64 +
1618                                 NODEID_TO_NODE(scsi_id->ne->nodeid)];
1619
1620         /* Bump down our speed if the user requested it */
1621         if (scsi_id->speed_code > max_speed) {
1622                 scsi_id->speed_code = max_speed;
1623                 SBP2_ERR("Forcing SBP-2 max speed down to %s",
1624                          hpsb_speedto_str[scsi_id->speed_code]);
1625         }
1626
1627         /* Payload size is the lesser of what our speed supports and what
1628          * our host supports.  */
1629         scsi_id->max_payload_size =
1630             min(sbp2_speedto_max_payload[scsi_id->speed_code],
1631                 (u8) (hi->host->csr.max_rec - 1));
1632
1633         HPSB_DEBUG("Node " NODE_BUS_FMT ": Max speed [%s] - Max payload [%u]",
1634                    NODE_BUS_ARGS(hi->host, scsi_id->ne->nodeid),
1635                    hpsb_speedto_str[scsi_id->speed_code],
1636                    1 << ((u32) scsi_id->max_payload_size + 2));
1637
1638         return 0;
1639 }
1640
1641 /*
1642  * This function is called in order to perform a SBP-2 agent reset.
1643  */
1644 static int sbp2_agent_reset(struct scsi_id_instance_data *scsi_id, int wait)
1645 {
1646         quadlet_t data;
1647         u64 addr;
1648         int retval;
1649
1650         SBP2_DEBUG_ENTER();
1651
1652         data = ntohl(SBP2_AGENT_RESET_DATA);
1653         addr = scsi_id->sbp2_command_block_agent_addr + SBP2_AGENT_RESET_OFFSET;
1654
1655         if (wait)
1656                 retval = hpsb_node_write(scsi_id->ne, addr, &data, 4);
1657         else
1658                 retval = sbp2util_node_write_no_wait(scsi_id->ne, addr, &data, 4);
1659
1660         if (retval < 0) {
1661                 SBP2_ERR("hpsb_node_write failed.\n");
1662                 return -EIO;
1663         }
1664
1665         /*
1666          * Need to make sure orb pointer is written on next command
1667          */
1668         scsi_id->last_orb = NULL;
1669
1670         return 0;
1671 }
1672
1673 static void sbp2_prep_command_orb_sg(struct sbp2_command_orb *orb,
1674                                      struct sbp2scsi_host_info *hi,
1675                                      struct sbp2_command_info *command,
1676                                      unsigned int scsi_use_sg,
1677                                      struct scatterlist *sgpnt,
1678                                      u32 orb_direction,
1679                                      enum dma_data_direction dma_dir)
1680 {
1681         command->dma_dir = dma_dir;
1682         orb->data_descriptor_hi = ORB_SET_NODE_ID(hi->host->node_id);
1683         orb->misc |= ORB_SET_DIRECTION(orb_direction);
1684
1685         /* Special case if only one element (and less than 64KB in size) */
1686         if ((scsi_use_sg == 1) &&
1687             (sgpnt[0].length <= SBP2_MAX_SG_ELEMENT_LENGTH)) {
1688
1689                 SBP2_DEBUG("Only one s/g element");
1690                 command->dma_size = sgpnt[0].length;
1691                 command->dma_type = CMD_DMA_PAGE;
1692                 command->cmd_dma = pci_map_page(hi->host->pdev,
1693                                                 sgpnt[0].page,
1694                                                 sgpnt[0].offset,
1695                                                 command->dma_size,
1696                                                 command->dma_dir);
1697                 SBP2_DMA_ALLOC("single page scatter element");
1698
1699                 orb->data_descriptor_lo = command->cmd_dma;
1700                 orb->misc |= ORB_SET_DATA_SIZE(command->dma_size);
1701
1702         } else {
1703                 struct sbp2_unrestricted_page_table *sg_element =
1704                                         &command->scatter_gather_element[0];
1705                 u32 sg_count, sg_len;
1706                 dma_addr_t sg_addr;
1707                 int i, count = pci_map_sg(hi->host->pdev, sgpnt, scsi_use_sg,
1708                                           dma_dir);
1709
1710                 SBP2_DMA_ALLOC("scatter list");
1711
1712                 command->dma_size = scsi_use_sg;
1713                 command->sge_buffer = sgpnt;
1714
1715                 /* use page tables (s/g) */
1716                 orb->misc |= ORB_SET_PAGE_TABLE_PRESENT(0x1);
1717                 orb->data_descriptor_lo = command->sge_dma;
1718
1719                 /*
1720                  * Loop through and fill out our sbp-2 page tables
1721                  * (and split up anything too large)
1722                  */
1723                 for (i = 0, sg_count = 0 ; i < count; i++, sgpnt++) {
1724                         sg_len = sg_dma_len(sgpnt);
1725                         sg_addr = sg_dma_address(sgpnt);
1726                         while (sg_len) {
1727                                 sg_element[sg_count].segment_base_lo = sg_addr;
1728                                 if (sg_len > SBP2_MAX_SG_ELEMENT_LENGTH) {
1729                                         sg_element[sg_count].length_segment_base_hi =
1730                                                 PAGE_TABLE_SET_SEGMENT_LENGTH(SBP2_MAX_SG_ELEMENT_LENGTH);
1731                                         sg_addr += SBP2_MAX_SG_ELEMENT_LENGTH;
1732                                         sg_len -= SBP2_MAX_SG_ELEMENT_LENGTH;
1733                                 } else {
1734                                         sg_element[sg_count].length_segment_base_hi =
1735                                                 PAGE_TABLE_SET_SEGMENT_LENGTH(sg_len);
1736                                         sg_len = 0;
1737                                 }
1738                                 sg_count++;
1739                         }
1740                 }
1741
1742                 /* Number of page table (s/g) elements */
1743                 orb->misc |= ORB_SET_DATA_SIZE(sg_count);
1744
1745                 sbp2util_packet_dump(sg_element,
1746                                      (sizeof(struct sbp2_unrestricted_page_table)) * sg_count,
1747                                      "sbp2 s/g list", command->sge_dma);
1748
1749                 /* Byte swap page tables if necessary */
1750                 sbp2util_cpu_to_be32_buffer(sg_element,
1751                                             (sizeof(struct sbp2_unrestricted_page_table)) *
1752                                             sg_count);
1753         }
1754 }
1755
1756 static void sbp2_prep_command_orb_no_sg(struct sbp2_command_orb *orb,
1757                                         struct sbp2scsi_host_info *hi,
1758                                         struct sbp2_command_info *command,
1759                                         struct scatterlist *sgpnt,
1760                                         u32 orb_direction,
1761                                         unsigned int scsi_request_bufflen,
1762                                         void *scsi_request_buffer,
1763                                         enum dma_data_direction dma_dir)
1764 {
1765         command->dma_dir = dma_dir;
1766         command->dma_size = scsi_request_bufflen;
1767         command->dma_type = CMD_DMA_SINGLE;
1768         command->cmd_dma = pci_map_single(hi->host->pdev, scsi_request_buffer,
1769                                           command->dma_size, command->dma_dir);
1770         orb->data_descriptor_hi = ORB_SET_NODE_ID(hi->host->node_id);
1771         orb->misc |= ORB_SET_DIRECTION(orb_direction);
1772
1773         SBP2_DMA_ALLOC("single bulk");
1774
1775         /*
1776          * Handle case where we get a command w/o s/g enabled (but
1777          * check for transfers larger than 64K)
1778          */
1779         if (scsi_request_bufflen <= SBP2_MAX_SG_ELEMENT_LENGTH) {
1780
1781                 orb->data_descriptor_lo = command->cmd_dma;
1782                 orb->misc |= ORB_SET_DATA_SIZE(scsi_request_bufflen);
1783
1784         } else {
1785                 struct sbp2_unrestricted_page_table *sg_element =
1786                         &command->scatter_gather_element[0];
1787                 u32 sg_count, sg_len;
1788                 dma_addr_t sg_addr;
1789
1790                 /*
1791                  * Need to turn this into page tables, since the
1792                  * buffer is too large.
1793                  */
1794                 orb->data_descriptor_lo = command->sge_dma;
1795
1796                 /* Use page tables (s/g) */
1797                 orb->misc |= ORB_SET_PAGE_TABLE_PRESENT(0x1);
1798
1799                 /*
1800                  * fill out our sbp-2 page tables (and split up
1801                  * the large buffer)
1802                  */
1803                 sg_count = 0;
1804                 sg_len = scsi_request_bufflen;
1805                 sg_addr = command->cmd_dma;
1806                 while (sg_len) {
1807                         sg_element[sg_count].segment_base_lo = sg_addr;
1808                         if (sg_len > SBP2_MAX_SG_ELEMENT_LENGTH) {
1809                                 sg_element[sg_count].length_segment_base_hi =
1810                                         PAGE_TABLE_SET_SEGMENT_LENGTH(SBP2_MAX_SG_ELEMENT_LENGTH);
1811                                 sg_addr += SBP2_MAX_SG_ELEMENT_LENGTH;
1812                                 sg_len -= SBP2_MAX_SG_ELEMENT_LENGTH;
1813                         } else {
1814                                 sg_element[sg_count].length_segment_base_hi =
1815                                         PAGE_TABLE_SET_SEGMENT_LENGTH(sg_len);
1816                                 sg_len = 0;
1817                         }
1818                         sg_count++;
1819                 }
1820
1821                 /* Number of page table (s/g) elements */
1822                 orb->misc |= ORB_SET_DATA_SIZE(sg_count);
1823
1824                 sbp2util_packet_dump(sg_element,
1825                                      (sizeof(struct sbp2_unrestricted_page_table)) * sg_count,
1826                                      "sbp2 s/g list", command->sge_dma);
1827
1828                 /* Byte swap page tables if necessary */
1829                 sbp2util_cpu_to_be32_buffer(sg_element,
1830                                             (sizeof(struct sbp2_unrestricted_page_table)) *
1831                                              sg_count);
1832         }
1833 }
1834
1835 /*
1836  * This function is called to create the actual command orb and s/g list
1837  * out of the scsi command itself.
1838  */
1839 static void sbp2_create_command_orb(struct scsi_id_instance_data *scsi_id,
1840                                     struct sbp2_command_info *command,
1841                                     unchar *scsi_cmd,
1842                                     unsigned int scsi_use_sg,
1843                                     unsigned int scsi_request_bufflen,
1844                                     void *scsi_request_buffer,
1845                                     enum dma_data_direction dma_dir)
1846 {
1847         struct sbp2scsi_host_info *hi = scsi_id->hi;
1848         struct scatterlist *sgpnt = (struct scatterlist *)scsi_request_buffer;
1849         struct sbp2_command_orb *command_orb = &command->command_orb;
1850         u32 orb_direction;
1851
1852         /*
1853          * Set-up our command ORB..
1854          *
1855          * NOTE: We're doing unrestricted page tables (s/g), as this is
1856          * best performance (at least with the devices I have). This means
1857          * that data_size becomes the number of s/g elements, and
1858          * page_size should be zero (for unrestricted).
1859          */
1860         command_orb->next_ORB_hi = ORB_SET_NULL_PTR(1);
1861         command_orb->next_ORB_lo = 0x0;
1862         command_orb->misc = ORB_SET_MAX_PAYLOAD(scsi_id->max_payload_size);
1863         command_orb->misc |= ORB_SET_SPEED(scsi_id->speed_code);
1864         command_orb->misc |= ORB_SET_NOTIFY(1); /* Notify us when complete */
1865
1866         if (dma_dir == DMA_NONE)
1867                 orb_direction = ORB_DIRECTION_NO_DATA_TRANSFER;
1868         else if (dma_dir == DMA_TO_DEVICE && scsi_request_bufflen)
1869                 orb_direction = ORB_DIRECTION_WRITE_TO_MEDIA;
1870         else if (dma_dir == DMA_FROM_DEVICE && scsi_request_bufflen)
1871                 orb_direction = ORB_DIRECTION_READ_FROM_MEDIA;
1872         else {
1873                 SBP2_WARN("Falling back to DMA_NONE");
1874                 orb_direction = ORB_DIRECTION_NO_DATA_TRANSFER;
1875         }
1876
1877         /* Set-up our pagetable stuff */
1878         if (orb_direction == ORB_DIRECTION_NO_DATA_TRANSFER) {
1879                 SBP2_DEBUG("No data transfer");
1880                 command_orb->data_descriptor_hi = 0x0;
1881                 command_orb->data_descriptor_lo = 0x0;
1882                 command_orb->misc |= ORB_SET_DIRECTION(1);
1883         } else if (scsi_use_sg) {
1884                 SBP2_DEBUG("Use scatter/gather");
1885                 sbp2_prep_command_orb_sg(command_orb, hi, command, scsi_use_sg,
1886                                          sgpnt, orb_direction, dma_dir);
1887         } else {
1888                 SBP2_DEBUG("No scatter/gather");
1889                 sbp2_prep_command_orb_no_sg(command_orb, hi, command, sgpnt,
1890                                             orb_direction, scsi_request_bufflen,
1891                                             scsi_request_buffer, dma_dir);
1892         }
1893
1894         /* Byte swap command ORB if necessary */
1895         sbp2util_cpu_to_be32_buffer(command_orb, sizeof(struct sbp2_command_orb));
1896
1897         /* Put our scsi command in the command ORB */
1898         memset(command_orb->cdb, 0, 12);
1899         memcpy(command_orb->cdb, scsi_cmd, COMMAND_SIZE(*scsi_cmd));
1900 }
1901
1902 /*
1903  * This function is called in order to begin a regular SBP-2 command.
1904  */
1905 static int sbp2_link_orb_command(struct scsi_id_instance_data *scsi_id,
1906                                  struct sbp2_command_info *command)
1907 {
1908         struct sbp2scsi_host_info *hi = scsi_id->hi;
1909         struct sbp2_command_orb *command_orb = &command->command_orb;
1910         struct node_entry *ne = scsi_id->ne;
1911         u64 addr;
1912
1913         outstanding_orb_incr;
1914         SBP2_ORB_DEBUG("sending command orb %p, total orbs = %x",
1915                        command_orb, global_outstanding_command_orbs);
1916
1917         pci_dma_sync_single_for_device(hi->host->pdev, command->command_orb_dma,
1918                                        sizeof(struct sbp2_command_orb),
1919                                        PCI_DMA_BIDIRECTIONAL);
1920         pci_dma_sync_single_for_device(hi->host->pdev, command->sge_dma,
1921                                        sizeof(command->scatter_gather_element),
1922                                        PCI_DMA_BIDIRECTIONAL);
1923         /*
1924          * Check to see if there are any previous orbs to use
1925          */
1926         if (scsi_id->last_orb == NULL) {
1927                 quadlet_t data[2];
1928
1929                 /*
1930                  * Ok, let's write to the target's management agent register
1931                  */
1932                 addr = scsi_id->sbp2_command_block_agent_addr + SBP2_ORB_POINTER_OFFSET;
1933                 data[0] = ORB_SET_NODE_ID(hi->host->node_id);
1934                 data[1] = command->command_orb_dma;
1935                 sbp2util_cpu_to_be32_buffer(data, 8);
1936
1937                 SBP2_ORB_DEBUG("write command agent, command orb %p", command_orb);
1938
1939                 if (sbp2util_node_write_no_wait(ne, addr, data, 8) < 0) {
1940                         SBP2_ERR("sbp2util_node_write_no_wait failed.\n");
1941                         return -EIO;
1942                 }
1943
1944                 SBP2_ORB_DEBUG("write command agent complete");
1945
1946                 scsi_id->last_orb = command_orb;
1947                 scsi_id->last_orb_dma = command->command_orb_dma;
1948
1949         } else {
1950                 quadlet_t data;
1951
1952                 /*
1953                  * We have an orb already sent (maybe or maybe not
1954                  * processed) that we can append this orb to. So do so,
1955                  * and ring the doorbell. Have to be very careful
1956                  * modifying these next orb pointers, as they are accessed
1957                  * both by the sbp2 device and us.
1958                  */
1959                 scsi_id->last_orb->next_ORB_lo =
1960                     cpu_to_be32(command->command_orb_dma);
1961                 /* Tells hardware that this pointer is valid */
1962                 scsi_id->last_orb->next_ORB_hi = 0x0;
1963                 pci_dma_sync_single_for_device(hi->host->pdev,
1964                                                scsi_id->last_orb_dma,
1965                                                sizeof(struct sbp2_command_orb),
1966                                                PCI_DMA_BIDIRECTIONAL);
1967
1968                 /*
1969                  * Ring the doorbell
1970                  */
1971                 data = cpu_to_be32(command->command_orb_dma);
1972                 addr = scsi_id->sbp2_command_block_agent_addr + SBP2_DOORBELL_OFFSET;
1973
1974                 SBP2_ORB_DEBUG("ring doorbell, command orb %p", command_orb);
1975
1976                 if (sbp2util_node_write_no_wait(ne, addr, &data, 4) < 0) {
1977                         SBP2_ERR("sbp2util_node_write_no_wait failed");
1978                         return -EIO;
1979                 }
1980
1981                 scsi_id->last_orb = command_orb;
1982                 scsi_id->last_orb_dma = command->command_orb_dma;
1983
1984         }
1985         return 0;
1986 }
1987
1988 /*
1989  * This function is called in order to begin a regular SBP-2 command.
1990  */
1991 static int sbp2_send_command(struct scsi_id_instance_data *scsi_id,
1992                              struct scsi_cmnd *SCpnt,
1993                              void (*done)(struct scsi_cmnd *))
1994 {
1995         unchar *cmd = (unchar *) SCpnt->cmnd;
1996         unsigned int request_bufflen = SCpnt->request_bufflen;
1997         struct sbp2_command_info *command;
1998
1999         SBP2_DEBUG_ENTER();
2000         SBP2_DEBUG("SCSI transfer size = %x", request_bufflen);
2001         SBP2_DEBUG("SCSI s/g elements = %x", (unsigned int)SCpnt->use_sg);
2002
2003         /*
2004          * Allocate a command orb and s/g structure
2005          */
2006         command = sbp2util_allocate_command_orb(scsi_id, SCpnt, done);
2007         if (!command) {
2008                 return -EIO;
2009         }
2010
2011         /*
2012          * Now actually fill in the comamnd orb and sbp2 s/g list
2013          */
2014         sbp2_create_command_orb(scsi_id, command, cmd, SCpnt->use_sg,
2015                                 request_bufflen, SCpnt->request_buffer,
2016                                 SCpnt->sc_data_direction);
2017
2018         sbp2util_packet_dump(&command->command_orb, sizeof(struct sbp2_command_orb),
2019                              "sbp2 command orb", command->command_orb_dma);
2020
2021         /*
2022          * Initialize status fifo
2023          */
2024         memset(&scsi_id->status_block, 0, sizeof(struct sbp2_status_block));
2025
2026         /*
2027          * Link up the orb, and ring the doorbell if needed
2028          */
2029         sbp2_link_orb_command(scsi_id, command);
2030
2031         return 0;
2032 }
2033
2034 /*
2035  * Translates SBP-2 status into SCSI sense data for check conditions
2036  */
2037 static unsigned int sbp2_status_to_sense_data(unchar *sbp2_status, unchar *sense_data)
2038 {
2039         SBP2_DEBUG_ENTER();
2040
2041         /*
2042          * Ok, it's pretty ugly...   ;-)
2043          */
2044         sense_data[0] = 0x70;
2045         sense_data[1] = 0x0;
2046         sense_data[2] = sbp2_status[9];
2047         sense_data[3] = sbp2_status[12];
2048         sense_data[4] = sbp2_status[13];
2049         sense_data[5] = sbp2_status[14];
2050         sense_data[6] = sbp2_status[15];
2051         sense_data[7] = 10;
2052         sense_data[8] = sbp2_status[16];
2053         sense_data[9] = sbp2_status[17];
2054         sense_data[10] = sbp2_status[18];
2055         sense_data[11] = sbp2_status[19];
2056         sense_data[12] = sbp2_status[10];
2057         sense_data[13] = sbp2_status[11];
2058         sense_data[14] = sbp2_status[20];
2059         sense_data[15] = sbp2_status[21];
2060
2061         return sbp2_status[8] & 0x3f;   /* return scsi status */
2062 }
2063
2064 /*
2065  * This function is called after a command is completed, in order to do any necessary SBP-2
2066  * response data translations for the SCSI stack
2067  */
2068 static void sbp2_check_sbp2_response(struct scsi_id_instance_data *scsi_id,
2069                                      struct scsi_cmnd *SCpnt)
2070 {
2071         u8 *scsi_buf = SCpnt->request_buffer;
2072
2073         SBP2_DEBUG_ENTER();
2074
2075         if (SCpnt->cmnd[0] == INQUIRY && (SCpnt->cmnd[1] & 3) == 0) {
2076                 /*
2077                  * Make sure data length is ok. Minimum length is 36 bytes
2078                  */
2079                 if (scsi_buf[4] == 0) {
2080                         scsi_buf[4] = 36 - 5;
2081                 }
2082
2083                 /*
2084                  * Fix ansi revision and response data format
2085                  */
2086                 scsi_buf[2] |= 2;
2087                 scsi_buf[3] = (scsi_buf[3] & 0xf0) | 2;
2088         }
2089 }
2090
2091 /*
2092  * This function deals with status writes from the SBP-2 device
2093  */
2094 static int sbp2_handle_status_write(struct hpsb_host *host, int nodeid, int destid,
2095                                     quadlet_t *data, u64 addr, size_t length, u16 fl)
2096 {
2097         struct sbp2scsi_host_info *hi;
2098         struct scsi_id_instance_data *scsi_id = NULL, *scsi_id_tmp;
2099         struct scsi_cmnd *SCpnt = NULL;
2100         u32 scsi_status = SBP2_SCSI_STATUS_GOOD;
2101         struct sbp2_command_info *command;
2102         unsigned long flags;
2103
2104         SBP2_DEBUG_ENTER();
2105
2106         sbp2util_packet_dump(data, length, "sbp2 status write by device", (u32)addr);
2107
2108         if (!host) {
2109                 SBP2_ERR("host is NULL - this is bad!");
2110                 return RCODE_ADDRESS_ERROR;
2111         }
2112
2113         hi = hpsb_get_hostinfo(&sbp2_highlevel, host);
2114
2115         if (!hi) {
2116                 SBP2_ERR("host info is NULL - this is bad!");
2117                 return RCODE_ADDRESS_ERROR;
2118         }
2119
2120         /*
2121          * Find our scsi_id structure by looking at the status fifo address
2122          * written to by the sbp2 device.
2123          */
2124         list_for_each_entry(scsi_id_tmp, &hi->scsi_ids, scsi_list) {
2125                 if (scsi_id_tmp->ne->nodeid == nodeid &&
2126                     scsi_id_tmp->status_fifo_addr == addr) {
2127                         scsi_id = scsi_id_tmp;
2128                         break;
2129                 }
2130         }
2131
2132         if (!scsi_id) {
2133                 SBP2_ERR("scsi_id is NULL - device is gone?");
2134                 return RCODE_ADDRESS_ERROR;
2135         }
2136
2137         /*
2138          * Put response into scsi_id status fifo...
2139          */
2140         memcpy(&scsi_id->status_block, data, length);
2141
2142         /*
2143          * Byte swap first two quadlets (8 bytes) of status for processing
2144          */
2145         sbp2util_be32_to_cpu_buffer(&scsi_id->status_block, 8);
2146
2147         /*
2148          * Handle command ORB status here if necessary. First, need to match status with command.
2149          */
2150         command = sbp2util_find_command_for_orb(scsi_id, scsi_id->status_block.ORB_offset_lo);
2151         if (command) {
2152
2153                 SBP2_DEBUG("Found status for command ORB");
2154                 pci_dma_sync_single_for_cpu(hi->host->pdev, command->command_orb_dma,
2155                                             sizeof(struct sbp2_command_orb),
2156                                             PCI_DMA_BIDIRECTIONAL);
2157                 pci_dma_sync_single_for_cpu(hi->host->pdev, command->sge_dma,
2158                                             sizeof(command->scatter_gather_element),
2159                                             PCI_DMA_BIDIRECTIONAL);
2160
2161                 SBP2_ORB_DEBUG("matched command orb %p", &command->command_orb);
2162                 outstanding_orb_decr;
2163
2164                 /*
2165                  * Matched status with command, now grab scsi command pointers and check status
2166                  */
2167                 SCpnt = command->Current_SCpnt;
2168                 spin_lock_irqsave(&scsi_id->sbp2_command_orb_lock, flags);
2169                 sbp2util_mark_command_completed(scsi_id, command);
2170                 spin_unlock_irqrestore(&scsi_id->sbp2_command_orb_lock, flags);
2171
2172                 if (SCpnt) {
2173
2174                         /*
2175                          * See if the target stored any scsi status information
2176                          */
2177                         if (STATUS_GET_LENGTH(scsi_id->status_block.ORB_offset_hi_misc) > 1) {
2178                                 /*
2179                                  * Translate SBP-2 status to SCSI sense data
2180                                  */
2181                                 SBP2_DEBUG("CHECK CONDITION");
2182                                 scsi_status = sbp2_status_to_sense_data((unchar *)&scsi_id->status_block, SCpnt->sense_buffer);
2183                         }
2184
2185                         /*
2186                          * Check to see if the dead bit is set. If so, we'll have to initiate
2187                          * a fetch agent reset.
2188                          */
2189                         if (STATUS_GET_DEAD_BIT(scsi_id->status_block.ORB_offset_hi_misc)) {
2190
2191                                 /*
2192                                  * Initiate a fetch agent reset.
2193                                  */
2194                                 SBP2_DEBUG("Dead bit set - initiating fetch agent reset");
2195                                 sbp2_agent_reset(scsi_id, 0);
2196                         }
2197
2198                         SBP2_ORB_DEBUG("completing command orb %p", &command->command_orb);
2199                 }
2200
2201                 /*
2202                  * Check here to see if there are no commands in-use. If there are none, we can
2203                  * null out last orb so that next time around we write directly to the orb pointer...
2204                  * Quick start saves one 1394 bus transaction.
2205                  */
2206                 spin_lock_irqsave(&scsi_id->sbp2_command_orb_lock, flags);
2207                 if (list_empty(&scsi_id->sbp2_command_orb_inuse)) {
2208                         scsi_id->last_orb = NULL;
2209                 }
2210                 spin_unlock_irqrestore(&scsi_id->sbp2_command_orb_lock, flags);
2211
2212         } else {
2213
2214                 /*
2215                  * It's probably a login/logout/reconnect status.
2216                  */
2217                 if ((scsi_id->login_orb_dma == scsi_id->status_block.ORB_offset_lo) ||
2218                     (scsi_id->query_logins_orb_dma == scsi_id->status_block.ORB_offset_lo) ||
2219                     (scsi_id->reconnect_orb_dma == scsi_id->status_block.ORB_offset_lo) ||
2220                     (scsi_id->logout_orb_dma == scsi_id->status_block.ORB_offset_lo)) {
2221                         atomic_set(&scsi_id->sbp2_login_complete, 1);
2222                 }
2223         }
2224
2225         if (SCpnt) {
2226
2227                 /* Complete the SCSI command. */
2228                 SBP2_DEBUG("Completing SCSI command");
2229                 sbp2scsi_complete_command(scsi_id, scsi_status, SCpnt,
2230                                           command->Current_done);
2231                 SBP2_ORB_DEBUG("command orb completed");
2232         }
2233
2234         return RCODE_COMPLETE;
2235 }
2236
2237 /**************************************
2238  * SCSI interface related section
2239  **************************************/
2240
2241 /*
2242  * This routine is the main request entry routine for doing I/O. It is
2243  * called from the scsi stack directly.
2244  */
2245 static int sbp2scsi_queuecommand(struct scsi_cmnd *SCpnt,
2246                                  void (*done)(struct scsi_cmnd *))
2247 {
2248         struct scsi_id_instance_data *scsi_id =
2249                 (struct scsi_id_instance_data *)SCpnt->device->host->hostdata[0];
2250         struct sbp2scsi_host_info *hi;
2251         int result = DID_NO_CONNECT << 16;
2252
2253         SBP2_DEBUG_ENTER();
2254 #if (CONFIG_IEEE1394_SBP2_DEBUG >= 2) || defined(CONFIG_IEEE1394_SBP2_PACKET_DUMP)
2255         scsi_print_command(SCpnt);
2256 #endif
2257
2258         if (!sbp2util_node_is_available(scsi_id))
2259                 goto done;
2260
2261         hi = scsi_id->hi;
2262
2263         if (!hi) {
2264                 SBP2_ERR("sbp2scsi_host_info is NULL - this is bad!");
2265                 goto done;
2266         }
2267
2268         /*
2269          * Until we handle multiple luns, just return selection time-out
2270          * to any IO directed at non-zero LUNs
2271          */
2272         if (SCpnt->device->lun)
2273                 goto done;
2274
2275         /*
2276          * Check for request sense command, and handle it here
2277          * (autorequest sense)
2278          */
2279         if (SCpnt->cmnd[0] == REQUEST_SENSE) {
2280                 SBP2_DEBUG("REQUEST_SENSE");
2281                 memcpy(SCpnt->request_buffer, SCpnt->sense_buffer, SCpnt->request_bufflen);
2282                 memset(SCpnt->sense_buffer, 0, sizeof(SCpnt->sense_buffer));
2283                 sbp2scsi_complete_command(scsi_id, SBP2_SCSI_STATUS_GOOD, SCpnt, done);
2284                 return 0;
2285         }
2286
2287         /*
2288          * Check to see if we are in the middle of a bus reset.
2289          */
2290         if (!hpsb_node_entry_valid(scsi_id->ne)) {
2291                 SBP2_ERR("Bus reset in progress - rejecting command");
2292                 result = DID_BUS_BUSY << 16;
2293                 goto done;
2294         }
2295
2296         /*
2297          * Bidirectional commands are not yet implemented,
2298          * and unknown transfer direction not handled.
2299          */
2300         if (SCpnt->sc_data_direction == DMA_BIDIRECTIONAL) {
2301                 SBP2_ERR("Cannot handle DMA_BIDIRECTIONAL - rejecting command");
2302                 result = DID_ERROR << 16;
2303                 goto done;
2304         }
2305
2306         /*
2307          * Try and send our SCSI command
2308          */
2309         if (sbp2_send_command(scsi_id, SCpnt, done)) {
2310                 SBP2_ERR("Error sending SCSI command");
2311                 sbp2scsi_complete_command(scsi_id, SBP2_SCSI_STATUS_SELECTION_TIMEOUT,
2312                                           SCpnt, done);
2313         }
2314         return 0;
2315
2316 done:
2317         SCpnt->result = result;
2318         done(SCpnt);
2319         return 0;
2320 }
2321
2322 /*
2323  * This function is called in order to complete all outstanding SBP-2
2324  * commands (in case of resets, etc.).
2325  */
2326 static void sbp2scsi_complete_all_commands(struct scsi_id_instance_data *scsi_id,
2327                                            u32 status)
2328 {
2329         struct sbp2scsi_host_info *hi = scsi_id->hi;
2330         struct list_head *lh;
2331         struct sbp2_command_info *command;
2332         unsigned long flags;
2333
2334         SBP2_DEBUG_ENTER();
2335
2336         spin_lock_irqsave(&scsi_id->sbp2_command_orb_lock, flags);
2337         while (!list_empty(&scsi_id->sbp2_command_orb_inuse)) {
2338                 SBP2_DEBUG("Found pending command to complete");
2339                 lh = scsi_id->sbp2_command_orb_inuse.next;
2340                 command = list_entry(lh, struct sbp2_command_info, list);
2341                 pci_dma_sync_single_for_cpu(hi->host->pdev, command->command_orb_dma,
2342                                             sizeof(struct sbp2_command_orb),
2343                                             PCI_DMA_BIDIRECTIONAL);
2344                 pci_dma_sync_single_for_cpu(hi->host->pdev, command->sge_dma,
2345                                             sizeof(command->scatter_gather_element),
2346                                             PCI_DMA_BIDIRECTIONAL);
2347                 sbp2util_mark_command_completed(scsi_id, command);
2348                 if (command->Current_SCpnt) {
2349                         command->Current_SCpnt->result = status << 16;
2350                         command->Current_done(command->Current_SCpnt);
2351                 }
2352         }
2353         spin_unlock_irqrestore(&scsi_id->sbp2_command_orb_lock, flags);
2354
2355         return;
2356 }
2357
2358 /*
2359  * This function is called in order to complete a regular SBP-2 command.
2360  *
2361  * This can be called in interrupt context.
2362  */
2363 static void sbp2scsi_complete_command(struct scsi_id_instance_data *scsi_id,
2364                                       u32 scsi_status, struct scsi_cmnd *SCpnt,
2365                                       void (*done)(struct scsi_cmnd *))
2366 {
2367         SBP2_DEBUG_ENTER();
2368
2369         /*
2370          * Sanity
2371          */
2372         if (!SCpnt) {
2373                 SBP2_ERR("SCpnt is NULL");
2374                 return;
2375         }
2376
2377         /*
2378          * If a bus reset is in progress and there was an error, don't
2379          * complete the command, just let it get retried at the end of the
2380          * bus reset.
2381          */
2382         if (!hpsb_node_entry_valid(scsi_id->ne)
2383             && (scsi_status != SBP2_SCSI_STATUS_GOOD)) {
2384                 SBP2_ERR("Bus reset in progress - retry command later");
2385                 return;
2386         }
2387
2388         /*
2389          * Switch on scsi status
2390          */
2391         switch (scsi_status) {
2392         case SBP2_SCSI_STATUS_GOOD:
2393                 SCpnt->result = DID_OK << 16;
2394                 break;
2395
2396         case SBP2_SCSI_STATUS_BUSY:
2397                 SBP2_ERR("SBP2_SCSI_STATUS_BUSY");
2398                 SCpnt->result = DID_BUS_BUSY << 16;
2399                 break;
2400
2401         case SBP2_SCSI_STATUS_CHECK_CONDITION:
2402                 SBP2_DEBUG("SBP2_SCSI_STATUS_CHECK_CONDITION");
2403                 SCpnt->result = CHECK_CONDITION << 1 | DID_OK << 16;
2404 #if CONFIG_IEEE1394_SBP2_DEBUG >= 1
2405                 scsi_print_command(SCpnt);
2406                 scsi_print_sense(SBP2_DEVICE_NAME, SCpnt);
2407 #endif
2408                 break;
2409
2410         case SBP2_SCSI_STATUS_SELECTION_TIMEOUT:
2411                 SBP2_ERR("SBP2_SCSI_STATUS_SELECTION_TIMEOUT");
2412                 SCpnt->result = DID_NO_CONNECT << 16;
2413                 scsi_print_command(SCpnt);
2414                 break;
2415
2416         case SBP2_SCSI_STATUS_CONDITION_MET:
2417         case SBP2_SCSI_STATUS_RESERVATION_CONFLICT:
2418         case SBP2_SCSI_STATUS_COMMAND_TERMINATED:
2419                 SBP2_ERR("Bad SCSI status = %x", scsi_status);
2420                 SCpnt->result = DID_ERROR << 16;
2421                 scsi_print_command(SCpnt);
2422                 break;
2423
2424         default:
2425                 SBP2_ERR("Unsupported SCSI status = %x", scsi_status);
2426                 SCpnt->result = DID_ERROR << 16;
2427         }
2428
2429         /*
2430          * Take care of any sbp2 response data mucking here (RBC stuff, etc.)
2431          */
2432         if (SCpnt->result == DID_OK << 16) {
2433                 sbp2_check_sbp2_response(scsi_id, SCpnt);
2434         }
2435
2436         /*
2437          * If a bus reset is in progress and there was an error, complete
2438          * the command as busy so that it will get retried.
2439          */
2440         if (!hpsb_node_entry_valid(scsi_id->ne)
2441             && (scsi_status != SBP2_SCSI_STATUS_GOOD)) {
2442                 SBP2_ERR("Completing command with busy (bus reset)");
2443                 SCpnt->result = DID_BUS_BUSY << 16;
2444         }
2445
2446         /*
2447          * If a unit attention occurs, return busy status so it gets
2448          * retried... it could have happened because of a 1394 bus reset
2449          * or hot-plug...
2450          * XXX  DID_BUS_BUSY is actually a bad idea because it will defy
2451          * the scsi layer's retry logic.
2452          */
2453 #if 0
2454         if ((scsi_status == SBP2_SCSI_STATUS_CHECK_CONDITION) &&
2455             (SCpnt->sense_buffer[2] == UNIT_ATTENTION)) {
2456                 SBP2_DEBUG("UNIT ATTENTION - return busy");
2457                 SCpnt->result = DID_BUS_BUSY << 16;
2458         }
2459 #endif
2460
2461         /*
2462          * Tell scsi stack that we're done with this command
2463          */
2464         done(SCpnt);
2465 }
2466
2467 static int sbp2scsi_slave_alloc(struct scsi_device *sdev)
2468 {
2469         struct scsi_id_instance_data *scsi_id =
2470                 (struct scsi_id_instance_data *)sdev->host->hostdata[0];
2471
2472         scsi_id->sdev = sdev;
2473
2474         if (scsi_id->workarounds & SBP2_WORKAROUND_INQUIRY_36)
2475                 sdev->inquiry_len = 36;
2476         return 0;
2477 }
2478
2479 static int sbp2scsi_slave_configure(struct scsi_device *sdev)
2480 {
2481         struct scsi_id_instance_data *scsi_id =
2482                 (struct scsi_id_instance_data *)sdev->host->hostdata[0];
2483
2484         blk_queue_dma_alignment(sdev->request_queue, (512 - 1));
2485         sdev->use_10_for_rw = 1;
2486         sdev->use_10_for_ms = 1;
2487
2488         if (sdev->type == TYPE_DISK &&
2489             scsi_id->workarounds & SBP2_WORKAROUND_MODE_SENSE_8)
2490                 sdev->skip_ms_page_8 = 1;
2491         return 0;
2492 }
2493
2494 static void sbp2scsi_slave_destroy(struct scsi_device *sdev)
2495 {
2496         ((struct scsi_id_instance_data *)sdev->host->hostdata[0])->sdev = NULL;
2497         return;
2498 }
2499
2500 /*
2501  * Called by scsi stack when something has really gone wrong.  Usually
2502  * called when a command has timed-out for some reason.
2503  */
2504 static int sbp2scsi_abort(struct scsi_cmnd *SCpnt)
2505 {
2506         struct scsi_id_instance_data *scsi_id =
2507                 (struct scsi_id_instance_data *)SCpnt->device->host->hostdata[0];
2508         struct sbp2scsi_host_info *hi = scsi_id->hi;
2509         struct sbp2_command_info *command;
2510         unsigned long flags;
2511
2512         SBP2_ERR("aborting sbp2 command");
2513         scsi_print_command(SCpnt);
2514
2515         if (sbp2util_node_is_available(scsi_id)) {
2516
2517                 /*
2518                  * Right now, just return any matching command structures
2519                  * to the free pool.
2520                  */
2521                 spin_lock_irqsave(&scsi_id->sbp2_command_orb_lock, flags);
2522                 command = sbp2util_find_command_for_SCpnt(scsi_id, SCpnt);
2523                 if (command) {
2524                         SBP2_DEBUG("Found command to abort");
2525                         pci_dma_sync_single_for_cpu(hi->host->pdev,
2526                                                     command->command_orb_dma,
2527                                                     sizeof(struct sbp2_command_orb),
2528                                                     PCI_DMA_BIDIRECTIONAL);
2529                         pci_dma_sync_single_for_cpu(hi->host->pdev,
2530                                                     command->sge_dma,
2531                                                     sizeof(command->scatter_gather_element),
2532                                                     PCI_DMA_BIDIRECTIONAL);
2533                         sbp2util_mark_command_completed(scsi_id, command);
2534                         if (command->Current_SCpnt) {
2535                                 command->Current_SCpnt->result = DID_ABORT << 16;
2536                                 command->Current_done(command->Current_SCpnt);
2537                         }
2538                 }
2539                 spin_unlock_irqrestore(&scsi_id->sbp2_command_orb_lock, flags);
2540
2541                 /*
2542                  * Initiate a fetch agent reset.
2543                  */
2544                 sbp2_agent_reset(scsi_id, 0);
2545                 sbp2scsi_complete_all_commands(scsi_id, DID_BUS_BUSY);
2546         }
2547
2548         return SUCCESS;
2549 }
2550
2551 /*
2552  * Called by scsi stack when something has really gone wrong.
2553  */
2554 static int sbp2scsi_reset(struct scsi_cmnd *SCpnt)
2555 {
2556         struct scsi_id_instance_data *scsi_id =
2557                 (struct scsi_id_instance_data *)SCpnt->device->host->hostdata[0];
2558
2559         SBP2_ERR("reset requested");
2560
2561         if (sbp2util_node_is_available(scsi_id)) {
2562                 SBP2_ERR("Generating sbp2 fetch agent reset");
2563                 sbp2_agent_reset(scsi_id, 0);
2564         }
2565
2566         return SUCCESS;
2567 }
2568
2569 static ssize_t sbp2_sysfs_ieee1394_id_show(struct device *dev,
2570                                            struct device_attribute *attr,
2571                                            char *buf)
2572 {
2573         struct scsi_device *sdev;
2574         struct scsi_id_instance_data *scsi_id;
2575         int lun;
2576
2577         if (!(sdev = to_scsi_device(dev)))
2578                 return 0;
2579
2580         if (!(scsi_id = (struct scsi_id_instance_data *)sdev->host->hostdata[0]))
2581                 return 0;
2582
2583         lun = ORB_SET_LUN(scsi_id->sbp2_lun);
2584
2585         return sprintf(buf, "%016Lx:%d:%d\n", (unsigned long long)scsi_id->ne->guid,
2586                        scsi_id->ud->id, lun);
2587 }
2588 static DEVICE_ATTR(ieee1394_id, S_IRUGO, sbp2_sysfs_ieee1394_id_show, NULL);
2589
2590 static struct device_attribute *sbp2_sysfs_sdev_attrs[] = {
2591         &dev_attr_ieee1394_id,
2592         NULL
2593 };
2594
2595 MODULE_AUTHOR("Ben Collins <bcollins@debian.org>");
2596 MODULE_DESCRIPTION("IEEE-1394 SBP-2 protocol driver");
2597 MODULE_SUPPORTED_DEVICE(SBP2_DEVICE_NAME);
2598 MODULE_LICENSE("GPL");
2599
2600 /* SCSI host template */
2601 static struct scsi_host_template scsi_driver_template = {
2602         .module =                       THIS_MODULE,
2603         .name =                         "SBP-2 IEEE-1394",
2604         .proc_name =                    SBP2_DEVICE_NAME,
2605         .queuecommand =                 sbp2scsi_queuecommand,
2606         .eh_abort_handler =             sbp2scsi_abort,
2607         .eh_device_reset_handler =      sbp2scsi_reset,
2608         .slave_alloc =                  sbp2scsi_slave_alloc,
2609         .slave_configure =              sbp2scsi_slave_configure,
2610         .slave_destroy =                sbp2scsi_slave_destroy,
2611         .this_id =                      -1,
2612         .sg_tablesize =                 SG_ALL,
2613         .use_clustering =               ENABLE_CLUSTERING,
2614         .cmd_per_lun =                  SBP2_MAX_CMDS,
2615         .can_queue =                    SBP2_MAX_CMDS,
2616         .emulated =                     1,
2617         .sdev_attrs =                   sbp2_sysfs_sdev_attrs,
2618 };
2619
2620 static int sbp2_module_init(void)
2621 {
2622         int ret;
2623
2624         SBP2_DEBUG_ENTER();
2625
2626         /* Module load debug option to force one command at a time (serializing I/O) */
2627         if (serialize_io) {
2628                 SBP2_INFO("Driver forced to serialize I/O (serialize_io=1)");
2629                 SBP2_INFO("Try serialize_io=0 for better performance");
2630                 scsi_driver_template.can_queue = 1;
2631                 scsi_driver_template.cmd_per_lun = 1;
2632         }
2633
2634         if (sbp2_default_workarounds & SBP2_WORKAROUND_128K_MAX_TRANS &&
2635             (max_sectors * 512) > (128 * 1024))
2636                 max_sectors = 128 * 1024 / 512;
2637         scsi_driver_template.max_sectors = max_sectors;
2638
2639         /* Register our high level driver with 1394 stack */
2640         hpsb_register_highlevel(&sbp2_highlevel);
2641
2642         ret = hpsb_register_protocol(&sbp2_driver);
2643         if (ret) {
2644                 SBP2_ERR("Failed to register protocol");
2645                 hpsb_unregister_highlevel(&sbp2_highlevel);
2646                 return ret;
2647         }
2648
2649         return 0;
2650 }
2651
2652 static void __exit sbp2_module_exit(void)
2653 {
2654         SBP2_DEBUG_ENTER();
2655
2656         hpsb_unregister_protocol(&sbp2_driver);
2657
2658         hpsb_unregister_highlevel(&sbp2_highlevel);
2659 }
2660
2661 module_init(sbp2_module_init);
2662 module_exit(sbp2_module_exit);