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